diff --git a/.clang-tidy b/.clang-tidy deleted file mode 100644 index cc55fefd258a8d..00000000000000 --- a/.clang-tidy +++ /dev/null @@ -1,19 +0,0 @@ ---- -Checks: ' -bugprone-*, --bugprone-integer-division, --bugprone-narrowing-conversions, -performance-*, -clang-analyzer-*, -misc-*, --misc-unused-parameters, -modernize-*, --modernize-avoid-c-arrays, --modernize-deprecated-headers, --modernize-use-auto, --modernize-use-using, --modernize-use-nullptr, --modernize-use-trailing-return-type, -' -CheckOptions: -... diff --git a/.devcontainer/.gitignore b/.devcontainer/.gitignore deleted file mode 100644 index 5682fe1190e970..00000000000000 --- a/.devcontainer/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.Xauthority -.env -.host/ \ No newline at end of file diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile deleted file mode 100644 index 53a06f6f31db77..00000000000000 --- a/.devcontainer/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM ghcr.io/commaai/openpilot-base:latest - -RUN apt update && apt install -y vim net-tools usbutils htop ripgrep tmux wget mesa-utils xvfb libxtst6 libxv1 libglu1-mesa gdb bash-completion -RUN python3 -m ensurepip --upgrade -RUN pip3 install ipython jupyter jupyterlab - -RUN cd /tmp && \ - ARCH=$(arch | sed s/aarch64/arm64/ | sed s/x86_64/amd64/) && \ - curl -L -o virtualgl.deb "https://github.com/VirtualGL/virtualgl/releases/download/3.1.1/virtualgl_3.1.1_$ARCH.deb" && \ - dpkg -i virtualgl.deb - -RUN usermod -aG video batman - -USER batman - -RUN cd $HOME && \ - curl -O https://raw.githubusercontent.com/commaai/agnos-builder/master/userspace/home/.tmux.conf && \ - curl -O https://raw.githubusercontent.com/commaai/agnos-builder/master/userspace/home/.vimrc diff --git a/.devcontainer/container_post_create.sh b/.devcontainer/container_post_create.sh deleted file mode 100755 index dee1c611018bad..00000000000000 --- a/.devcontainer/container_post_create.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash - -TARGET_USER=batman -source .devcontainer/.host/.env - -# override display flag for mac hosts -if [[ $HOST_OS == darwin ]]; then - echo "Setting up DISPLAY override for macOS..." - cat <> /home/$TARGET_USER/.bashrc -source .devcontainer/.host/.env -if [ -n "\$HOST_DISPLAY" ]; then - DISPLAY_NUM=\$(echo "\$HOST_DISPLAY" | awk -F: '{print \$NF}') - export DISPLAY=host.docker.internal:\$DISPLAY_NUM -fi -EOF -fi - -# setup virtualgl for mac hosts -if [[ $HOST_OS == darwin ]]; then - echo "Setting up virtualgl for macOS..." - cat <> /home/$TARGET_USER/.bashrc -if [ -n "\$HOST_DISPLAY" ]; then - export VGL_PORT=10000 - export VGL_CLIENT=host.docker.internal - export VGL_COMPRESS=rgb - export VGL_DISPLAY=:99 - export VGL_FPS=60 - # prevent vglrun from running exec - alias exec=:; source vglrun :; unalias exec -fi -EOF -fi - -# These lines are temporary, to remain backwards compatible with old devcontainers -# that were running as root and therefore had their caches written as root -sudo chown -R $TARGET_USER: /tmp/scons_cache -sudo chown -R $TARGET_USER: /tmp/comma_download_cache -sudo chown -R $TARGET_USER: /home/batman/.comma diff --git a/.devcontainer/container_post_start.sh b/.devcontainer/container_post_start.sh deleted file mode 100755 index 1521b9c3fb4c30..00000000000000 --- a/.devcontainer/container_post_start.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash - -source .devcontainer/.host/.env - -# setup safe directories for submodules -SUBMODULE_DIRS=$(git config --file .gitmodules --get-regexp path | awk '{ print $2 }') -for DIR in $SUBMODULE_DIRS; do - git config --global --add safe.directory "$PWD/$DIR" -done - -# virtual display for virtualgl -if [[ "$HOST_OS" == "darwin" ]] && [[ -n "$HOST_DISPLAY" ]]; then - echo "Starting virtual display at :99 ..." - tmux new-session -d -s fakedisplay Xvfb :99 -screen 0 1920x1080x24 -fi diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 3f5b38d12ea0d1..00000000000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "openpilot devcontainer", - "build": { - "dockerfile": "Dockerfile" - }, - "postCreateCommand": ".devcontainer/container_post_create.sh", - "postStartCommand": ".devcontainer/container_post_start.sh", - "initializeCommand": [".devcontainer/host_setup"], - "privileged": true, - "containerEnv": { - "DISPLAY": "${localEnv:DISPLAY}", - "PYTHONPATH": "${containerWorkspaceFolder}", - "TERM": "xterm-256color", - "force_color_prompt": "1" - }, - "runArgs": [ - "--volume=/dev:/dev", - "--volume=/tmp/.X11-unix:/tmp/.X11-unix", - "--volume=${localWorkspaceFolder}/.devcontainer/.host/.Xauthority:/home/batman/.Xauthority", - "--volume=${localEnv:HOME}/.comma:/home/batman/.comma", - "--volume=${localEnv:HOME}/.azure:/home/batman/.azure", - "--volume=/tmp/comma_download_cache:/tmp/comma_download_cache", - "--shm-size=1G", - "--add-host=host.docker.internal:host-gateway", // required to use host.docker.internal on linux - "--publish=0.0.0.0:8070-8079:8070-8079" // body ZMQ services - ], - "features": { - "ghcr.io/devcontainers/features/common-utils:2": { - "installZsh": false, - "installOhMyZsh": false, - "upgradePackages": false, - "username": "batman" - }, - "ghcr.io/devcontainers-contrib/features/gh-cli:1": {}, - "ghcr.io/devcontainers/features/azure-cli:1": {} - }, - "containerUser": "batman", - "remoteUser": "batman", - "customizations": { - "vscode": { - "extensions": [ - "ms-python.python", - "ms-vscode.cpptools", - "ms-toolsai.jupyter", - "guyskk.language-cython", - "lharri73.dbc" - ] - } - }, - "mounts": [ - "type=volume,source=scons_cache,target=/tmp/scons_cache" - ] -} diff --git a/.devcontainer/host_setup b/.devcontainer/host_setup deleted file mode 100755 index 8ff81ebe421b6b..00000000000000 --- a/.devcontainer/host_setup +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env bash - -# pull base image -if [[ -z $USE_LOCAL_IMAGE ]]; then - echo "Updating openpilot_base image if needed..." - docker pull ghcr.io/commaai/openpilot-base:latest -fi - -# setup .host dir -mkdir -p .devcontainer/.host - -# setup links to Xauthority -XAUTHORITY_LINK=".devcontainer/.host/.Xauthority" -rm -f $XAUTHORITY_LINK -if [[ -z $XAUTHORITY ]]; then - echo "XAUTHORITY not set. Fallback to ~/.Xauthority ..." - if ! [[ -f $HOME/.Xauthority ]]; then - echo "~/.XAuthority file does not exist. GUI tools may not work properly." - touch $XAUTHORITY_LINK # dummy file to satisfy container volume mount - else - ln -sf $HOME/.Xauthority $XAUTHORITY_LINK - fi -else - ln -sf $XAUTHORITY $XAUTHORITY_LINK -fi - -# setup host env file -HOST_INFO_FILE=".devcontainer/.host/.env" -SYSTEM=$(uname -s | tr '[:upper:]' '[:lower:]') -echo "HOST_OS=\"$SYSTEM\"" > $HOST_INFO_FILE -echo "HOST_DISPLAY=\"$DISPLAY\"" >> $HOST_INFO_FILE - -# run virtualgl if macos -if [[ $SYSTEM == "darwin" ]]; then - echo - if [[ -f /opt/VirtualGL/bin/vglclient ]]; then - echo "Starting VirtualGL client at port 10000..." - VGL_LOG_FILE=".devcontainer/.host/.vgl/vglclient.log" - mkdir -p "$(dirname $VGL_LOG_FILE)" - /opt/VirtualGL/bin/vglclient -l "$VGL_LOG_FILE" -display "$DISPLAY" -port 10000 -detach - else - echo "VirtualGL not found. GUI tools may not work properly. Some GUI tools require OpenGL to work properly. To use them with XQuartz on mac, VirtualGL needs to be installed. To install it run:" - echo - echo " brew install --cask virtualgl" - echo - fi -fi diff --git a/.devcontainer/host_setup.cmd b/.devcontainer/host_setup.cmd deleted file mode 100644 index 885bd27f2568ec..00000000000000 --- a/.devcontainer/host_setup.cmd +++ /dev/null @@ -1,10 +0,0 @@ -:: pull base image -IF NOT DEFINED USE_LOCAL_IMAGE ^ -echo "Updating openpilot_base image if needed..." && ^ -docker pull ghcr.io/commaai/openpilot-base:latest - -:: setup .host dir -mkdir .devcontainer\.host - -:: setup host env file -echo "" > .devcontainer\.host\.env \ No newline at end of file diff --git a/.dockerignore b/.dockerignore index cfc34e5848ad0b..631ea048403903 100644 --- a/.dockerignore +++ b/.dockerignore @@ -13,27 +13,6 @@ *.o-* *.os *.os-* -*.so -*.a venv/ .venv/ - -notebooks -phone -massivemap -neos -installer -chffr/app2 -chffr/backend/env -selfdrive/nav -selfdrive/baseui -selfdrive/test/simulator2 -**/cache_data -xx/plus -xx/community -xx/projects -!xx/projects/eon_testing_master -!xx/projects/map3d -xx/ops -xx/junk diff --git a/.editorconfig b/.editorconfig index 879e6eebca7498..d506433ecec172 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,7 +5,7 @@ end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true -[{*.py, *.pyx, *.pxd}] +[*.{py,pyx,pxd}] charset = utf-8 indent_style = space indent_size = 2 diff --git a/.gitattributes b/.gitattributes index 3a1f47eda01669..0b01385ee712d0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,91 +2,16 @@ # to move existing files into LFS: # git add --renormalize . -*.dlc filter=lfs diff=lfs merge=lfs -text *.onnx filter=lfs diff=lfs merge=lfs -text *.svg filter=lfs diff=lfs merge=lfs -text *.png filter=lfs diff=lfs merge=lfs -text *.gif filter=lfs diff=lfs merge=lfs -text *.ttf filter=lfs diff=lfs merge=lfs -text +*.otf filter=lfs diff=lfs merge=lfs -text *.wav filter=lfs diff=lfs merge=lfs -text +# Generated chime. Small enough to live in git; comma's LFS remote is not ours to push. +selfdrive/assets/sounds/animal_chime.wav !filter !diff !merge -text + selfdrive/car/tests/test_models_segs.txt filter=lfs diff=lfs merge=lfs -text -system/hardware/tici/updater filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/qt/spinner_larch64 filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/qt/text_larch64 filter=lfs diff=lfs merge=lfs -text -third_party/**/*.a filter=lfs diff=lfs merge=lfs -text -third_party/**/*.so filter=lfs diff=lfs merge=lfs -text -third_party/**/*.so.* filter=lfs diff=lfs merge=lfs -text -third_party/**/*.dylib filter=lfs diff=lfs merge=lfs -text -third_party/acados/*/t_renderer filter=lfs diff=lfs merge=lfs -text -third_party/qt5/larch64/bin/lrelease filter=lfs diff=lfs merge=lfs -text -third_party/qt5/larch64/bin/lupdate filter=lfs diff=lfs merge=lfs -text -third_party/catch2/include/catch2/catch.hpp filter=lfs diff=lfs merge=lfs -text -*.ico filter=lfs diff=lfs merge=lfs -text -*.apk filter=lfs diff=lfs merge=lfs -text -*.apkpatch filter=lfs diff=lfs merge=lfs -text -*.jar filter=lfs diff=lfs merge=lfs -text -*.pdf filter=lfs diff=lfs merge=lfs -text -*.jpg filter=lfs diff=lfs merge=lfs -text -*.mp3 filter=lfs diff=lfs merge=lfs -text -*.thneed filter=lfs diff=lfs merge=lfs -text -*.tar.gz filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.csv filter=lfs diff=lfs merge=lfs -text -*.a filter=lfs diff=lfs merge=lfs -text -*.so* filter=lfs diff=lfs merge=lfs -text -*.dylib filter=lfs diff=lfs merge=lfs -text -*.o filter=lfs diff=lfs merge=lfs -text -*.b64 filter=lfs diff=lfs merge=lfs -text -selfdrive/hardware/tici/updater filter=lfs diff=lfs merge=lfs -text -selfdrive/boardd/tests/test_boardd filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/qt/spinner_aarch64 filter=lfs diff=lfs merge=lfs -text -installer/updater/updater filter=lfs diff=lfs merge=lfs -text -selfdrive/debug/profiling/simpleperf/**/* filter=lfs diff=lfs merge=lfs -text -selfdrive/hardware/eon/updater filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/qt/text_aarch64 filter=lfs diff=lfs merge=lfs -text -selfdrive/debug/profiling/pyflame/**/* filter=lfs diff=lfs merge=lfs -text -installer/installers/installer_openpilot filter=lfs diff=lfs merge=lfs -text -installer/installers/installer_dashcam filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/text/text filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/android/text/text filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/spinner/spinner filter=lfs diff=lfs merge=lfs -text -selfdrive/visiond/visiond filter=lfs diff=lfs merge=lfs -text -selfdrive/loggerd/loggerd filter=lfs diff=lfs merge=lfs -text -selfdrive/sensord/sensord filter=lfs diff=lfs merge=lfs -text -selfdrive/sensord/gpsd filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/android/spinner/spinner filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/qt/spinner filter=lfs diff=lfs merge=lfs -text -selfdrive/ui/qt/text filter=lfs diff=lfs merge=lfs -text -_stringdefs.py filter=lfs diff=lfs merge=lfs -text -dfu-util-aarch64-linux filter=lfs diff=lfs merge=lfs -text -dfu-util-aarch64 filter=lfs diff=lfs merge=lfs -text -dfu-util-x86_64-linux filter=lfs diff=lfs merge=lfs -text -dfu-util-x86_64 filter=lfs diff=lfs merge=lfs -text -stb_image.h filter=lfs diff=lfs merge=lfs -text -clpeak3 filter=lfs diff=lfs merge=lfs -text -clwaste filter=lfs diff=lfs merge=lfs -text -apk/**/* filter=lfs diff=lfs merge=lfs -text -external/**/* filter=lfs diff=lfs merge=lfs -text -phonelibs/**/* filter=lfs diff=lfs merge=lfs -text -third_party/boringssl/**/* filter=lfs diff=lfs merge=lfs -text -pyextra/**/* filter=lfs diff=lfs merge=lfs -text -panda/board/**/inc/*.h filter=lfs diff=lfs merge=lfs -text -panda/board/obj/*.elf filter=lfs diff=lfs merge=lfs -text -board/inc/*.h filter=lfs diff=lfs merge=lfs -text -third_party/nanovg/**/* filter=lfs diff=lfs merge=lfs -text -selfdrive/controls/lib/lateral_mpc/lib_mpc_export/**/* filter=lfs diff=lfs merge=lfs -text -third_party/android_hardware_libhardware/**/* filter=lfs diff=lfs merge=lfs -text -selfdrive/controls/lib/lead_mpc_lib/lib_mpc_export/**/* filter=lfs diff=lfs merge=lfs -text -*.pro filter=lfs diff=lfs merge=lfs -text -selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/**/* filter=lfs diff=lfs merge=lfs -text -selfdrive/controls/lib/lateral_mpc/mpc_export/**/* filter=lfs diff=lfs merge=lfs -text -third_party/curl/**/* filter=lfs diff=lfs merge=lfs -text -selfdrive/modeld/thneed/debug/**/* filter=lfs diff=lfs merge=lfs -text -selfdrive/modeld/thneed/include/**/* filter=lfs diff=lfs merge=lfs -text -third_party/openmax/**/* filter=lfs diff=lfs merge=lfs -text -selfdrive/controls/lib/longitudinal_mpc/mpc_export/**/* filter=lfs diff=lfs merge=lfs -text -selfdrive/controls/lib/longitudinal_mpc_model/lib_mpc_export/**/* filter=lfs diff=lfs merge=lfs -text -Pipfile filter=lfs diff=lfs merge=lfs -text -Pipfile.lock filter=lfs diff=lfs merge=lfs -text -poetry.lock filter=lfs diff=lfs merge=lfs -text -*.qm filter=lfs diff=lfs merge=lfs -text +system/hardware/tici/updater_weston filter=lfs diff=lfs merge=lfs -text +system/hardware/tici/updater_magic filter=lfs diff=lfs merge=lfs -text diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000000000..d38181f76599c8 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,20 @@ +# Longitudinal safety gate and its protected test surface +/.github/CODEOWNERS @daggerhashjack @SloPOS +/.github/workflows/ @daggerhashjack +/.github/ci/process_replay_active_inventory.json @daggerhashjack +/.github/ci/validate_process_replay_release.py @daggerhashjack +/.github/ci/test_assemble_replay_release.py @daggerhashjack +/.github/ci/test_validate_process_replay_release.py @daggerhashjack +/.github/workflows/tests.yaml @daggerhashjack @SloPOS +/.github/ci/tesla_preap_longitudinal_mutations.py @daggerhashjack @SloPOS +/.github/ci/tesla_preap_mutation_common.py @daggerhashjack @SloPOS +/.github/ci/tesla_preap_mutation_defs_a.py @daggerhashjack @SloPOS +/.github/ci/tesla_preap_mutation_defs_b.py @daggerhashjack @SloPOS +/.github/ci/test_tesla_preap_longitudinal_workflow.py @daggerhashjack @SloPOS +/selfdrive/controls/tests/test_tesla_preap_longcontrol.py @daggerhashjack @SloPOS +/opendbc_repo @daggerhashjack @SloPOS +/selfdrive/test/process_replay/ @daggerhashjack +/third_party/acados/ @daggerhashjack +/tools/ci/Dockerfile.replay @daggerhashjack +/tools/ci/assemble_replay_release.py @daggerhashjack +/Dockerfile.replay @daggerhashjack diff --git a/.github/ISSUE_TEMPLATE/car_bug_report.yml b/.github/ISSUE_TEMPLATE/car_bug_report.yml deleted file mode 100644 index 7f368f11b49a76..00000000000000 --- a/.github/ISSUE_TEMPLATE/car_bug_report.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: Car bug report -description: For issues with a particular car make or model -labels: ["car", "bug"] -body: - - - type: markdown - attributes: - value: > - Before creating a **bug report**, please check the following: - * Ensure you're running the latest openpilot release. - * Ensure you're using officially supported hardware. Issues running on PCs have a different issue template. - * Ensure there isn't an existing issue for your bug. If there is, leave a comment on the existing issue. - * Ensure you're running stock openpilot. We cannot look into bug reports from forks. - - If you're unsure whether you've hit a bug, check out the #installation-help channel in the [community Discord server](https://discord.comma.ai). - - - type: textarea - attributes: - label: Describe the bug - description: Also include a description of how to reproduce the bug - validations: - required: true - - - type: input - id: car - attributes: - label: Which car does this affect? - placeholder: Toyota Prius 2017 - validations: - required: true - - - type: input - id: route - attributes: - label: Provide a route where the issue occurs - description: Ensure the route is fully uploaded at https://useradmin.comma.ai - placeholder: 77611a1fac303767|2020-05-11--16-37-07 - validations: - required: true - - - type: input - id: version - attributes: - label: openpilot version - description: If you're not on release, provide the commit hash - placeholder: 0.8.10 - validations: - required: true - - - type: textarea - attributes: - label: Additional info - diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 9e9f6af61d1011..6efdc059a595e8 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,9 +1,12 @@ blank_issues_enabled: false contact_links: + - name: Car bug report + url: https://github.com/commaai/opendbc/issues/new + about: For issues with a particular car make or model - name: Join the Discord url: https://discord.comma.ai about: The community Discord is for both openpilot development and experience discussion - - name: Report model bugs + - name: Report driving behavior feedback url: https://discord.com/channels/469524606043160576/1254834193066623017 about: Feedback for the driving and driver monitoring models goes in the #driving-feedback in Discord - name: Community Wiki diff --git a/.github/ISSUE_TEMPLATE/enhancement.md b/.github/ISSUE_TEMPLATE/enhancement.md deleted file mode 100644 index 330b9b110154fe..00000000000000 --- a/.github/ISSUE_TEMPLATE/enhancement.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -name: Enhancement -about: For openpilot enhancement suggestions -title: '' -labels: 'enhancement' -assignees: '' ---- - diff --git a/.github/PULL_REQUEST_TEMPLATE/bugfix.md b/.github/PULL_REQUEST_TEMPLATE/bugfix.md deleted file mode 100644 index e28661db3b7ab3..00000000000000 --- a/.github/PULL_REQUEST_TEMPLATE/bugfix.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: Bug fix -about: For openpilot bug fixes -title: '' -labels: 'bugfix' -assignees: '' ---- - -**Description** - - - -**Verification** - - diff --git a/.github/PULL_REQUEST_TEMPLATE/car_bugfix.md b/.github/PULL_REQUEST_TEMPLATE/car_bugfix.md deleted file mode 100644 index 76c86346c85491..00000000000000 --- a/.github/PULL_REQUEST_TEMPLATE/car_bugfix.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: Car Bug fix -about: For vehicle/brand specific bug fixes -title: '' -labels: 'car bug fix' -assignees: '' ---- - -**Description** - - - -**Verification** - - - -**Route** - -Route: [a route with the bug fix] diff --git a/.github/PULL_REQUEST_TEMPLATE/car_port.md b/.github/PULL_REQUEST_TEMPLATE/car_port.md deleted file mode 100644 index c1581d20559d65..00000000000000 --- a/.github/PULL_REQUEST_TEMPLATE/car_port.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: Car port -about: For new car ports -title: '' -labels: 'car port' -assignees: '' ---- - -**Checklist** - -- [ ] added entry to CAR in selfdrive/car/*/values.py and ran `selfdrive/opcar/docs.py` to generate new docs -- [ ] test route added to [routes.py](https://github.com/commaai/openpilot/blob/master/selfdrive/car/tests/routes.py) -- [ ] route with openpilot: -- [ ] route with stock system: -- [ ] car harness used (if comma doesn't sell it, put N/A): diff --git a/.github/PULL_REQUEST_TEMPLATE/fingerprint.md b/.github/PULL_REQUEST_TEMPLATE/fingerprint.md deleted file mode 100644 index b94f7dc53f4209..00000000000000 --- a/.github/PULL_REQUEST_TEMPLATE/fingerprint.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -name: Fingerprint -about: For adding fingerprints to existing cars -title: '' -labels: 'fingerprint' -assignees: '' ---- - -**Car** -Which car (make, model, year) this fingerprint is for - -**Route** -A route with the fingerprint \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE/refactor.md b/.github/PULL_REQUEST_TEMPLATE/refactor.md deleted file mode 100644 index 1ee21c1bba1151..00000000000000 --- a/.github/PULL_REQUEST_TEMPLATE/refactor.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: Refactor -about: For code refactors -title: '' -labels: 'refactor' -assignees: '' ---- - -**Description** - - - -**Verification** - - diff --git a/.github/PULL_REQUEST_TEMPLATE/tuning.md b/.github/PULL_REQUEST_TEMPLATE/tuning.md deleted file mode 100644 index 4397e5ad20fed0..00000000000000 --- a/.github/PULL_REQUEST_TEMPLATE/tuning.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -name: Tuning -about: For openpilot tuning changes -title: '' -labels: 'tuning' -assignees: '' ---- - -**Description** - - - -**Verification** - - \ No newline at end of file diff --git a/.github/build.py b/.github/build.py deleted file mode 100644 index e141ea05df87d6..00000000000000 --- a/.github/build.py +++ /dev/null @@ -1,30 +0,0 @@ -import pathlib - -GITHUB_FOLDER = pathlib.Path(__file__).parent - -PULL_REQUEST_TEMPLATES = (GITHUB_FOLDER / "PULL_REQUEST_TEMPLATE") - -order = ["fingerprint", "car_bugfix", "bugfix", "car_port", "refactor"] - -def create_pull_request_template(): - with open(GITHUB_FOLDER / "pull_request_template.md", "w") as f: - f.write("\n\n") - - for t in order: - template = PULL_REQUEST_TEMPLATES / f"{t}.md" - text = template.read_text() - - # Remove metadata for GitHub - start = text.find("---") - end = text.find("---", start+1) - text = text[end + 4:] - - # Remove comments - text = text.replace("", "") - - f.write(f"\n\n") - -create_pull_request_template() diff --git a/.github/ci/process_replay_active_inventory.json b/.github/ci/process_replay_active_inventory.json new file mode 100644 index 00000000000000..d067aebc8f22b7 --- /dev/null +++ b/.github/ci/process_replay_active_inventory.json @@ -0,0 +1,356 @@ +{ + "allowed_processes": [ + "calibrationd", + "card", + "controlsd", + "dmonitoringd", + "lagd", + "locationd", + "paramsd", + "plannerd", + "radard", + "selfdrived", + "torqued", + "ubloxd" + ], + "cases": [ + { + "car_brand": "HYUNDAI", + "case_id": "hyundai", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd", + "selfdrived", + "radard", + "plannerd", + "calibrationd", + "dmonitoringd", + "locationd", + "paramsd", + "ubloxd", + "torqued" + ], + "source": "regenAA0FC4ED71E|2025-04-08--22-57-50--0", + "source_bytes": 11873030, + "source_sha256": "0b6734026f7c775f7fd648ef76130f9b9a672c5236c6a328eff31ec9cc3c5343" + }, + { + "car_brand": "HYUNDAI2", + "case_id": "hyundai2", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regenAFB9780D823|2025-04-08--23-00-34--0", + "source_bytes": 12527194, + "source_sha256": "4cc51a77bf8d128d5720fd692e5a0994c887ee35fdd949cc0ce54d4215e2b7a2" + }, + { + "car_brand": "TOYOTA", + "case_id": "toyota", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd", + "selfdrived", + "radard", + "plannerd", + "calibrationd", + "dmonitoringd", + "locationd", + "paramsd", + "ubloxd", + "torqued" + ], + "source": "regen218A4DCFAA1|2025-04-08--22-57-51--0", + "source_bytes": 10846201, + "source_sha256": "6c028c0d40328fc00fa12acf91dba30d9f152e89d99a7089aadac62f6c7d5d64" + }, + { + "car_brand": "TOYOTA3", + "case_id": "toyota3", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen1455E3B4BDF|2025-04-09--03-26-06--0", + "source_bytes": 9272538, + "source_sha256": "876100021b13ddd1a39efad5fdb4e7376ad5b298f64bf390b5f58742ffc6e429" + }, + { + "car_brand": "HONDA", + "case_id": "honda", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regenB328FF8BA0A|2025-04-08--22-57-45--0", + "source_bytes": 10090147, + "source_sha256": "8ea4ab5412a99bfc65fbe95cd169a54edb6bcb68f6fa20c97f2bc58ed4bba538" + }, + { + "car_brand": "HONDA2", + "case_id": "honda2", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen6170C8C9A35|2025-04-08--22-57-46--0", + "source_bytes": 10419375, + "source_sha256": "fc9ab2b4fd9702ceb8e3342186076dc6a85dbd6a3bd859ac6b965234bcc65c69" + }, + { + "car_brand": "CHRYSLER", + "case_id": "chrysler", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen5B28FC2A437|2025-04-08--23-04-24--0", + "source_bytes": 11951101, + "source_sha256": "a30f65eb1033afbd0cff70d965aa9c0a276cc5ceb73d28baa817430df178009a" + }, + { + "car_brand": "RAM", + "case_id": "ram", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regenBF81EA96E08|2025-04-08--23-06-54--0", + "source_bytes": 11420074, + "source_sha256": "cc1d8bb9729a71c3166e04343e436a67fbc1ff7107a30201a5d13ea9b45ea143" + }, + { + "car_brand": "SUBARU", + "case_id": "subaru", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen7366F13F6A1|2025-04-08--23-07-07--0", + "source_bytes": 9393878, + "source_sha256": "f501c1c99bae27ca710f40f723a1960ea4e898836d7edfb57ea6397591e5aff2" + }, + { + "car_brand": "GM", + "case_id": "gm", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen1271097D038|2025-04-09--03-26-00--0", + "source_bytes": 9846869, + "source_sha256": "6c10ce899270e4fc8350730e44cb39dfbda451670dd598798207ffc929baa69a" + }, + { + "car_brand": "NISSAN", + "case_id": "nissan", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen15D60604EAB|2025-04-08--23-06-59--0", + "source_bytes": 11775886, + "source_sha256": "58f3822418e86d8c4afca79ef9058602c8825fadaedf8b63477ed53a2b9ba748" + }, + { + "car_brand": "VOLKSWAGEN", + "case_id": "volkswagen", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen0F2F06C9539|2025-04-08--23-06-56--0", + "source_bytes": 10593610, + "source_sha256": "bca512375f61ade1af793227f4aa9137ba1cbd0067d3b92f1242f5907f84a0af" + }, + { + "car_brand": "MAZDA", + "case_id": "mazda", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regenACF84CCF482|2024-08-30--03-21-55--0", + "source_bytes": 12309353, + "source_sha256": "a84e9f84c39802f58a64031e7c56b362c0e745b5c216848ca2d561f5ae6d440a" + }, + { + "car_brand": "FORD", + "case_id": "ford", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen755D8CB1E1F|2025-04-08--23-13-43--0", + "source_bytes": 11315727, + "source_sha256": "786dfef08325d24e8205320862adc940706ff3475ae082ea104127fb5da62823" + }, + { + "car_brand": "RIVIAN", + "case_id": "rivian", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen5FCAC896BBE|2025-04-08--23-13-35--0", + "source_bytes": 11022997, + "source_sha256": "2f2574c057b7cb55fbb2e05c99c5f1b1d6d894222422c4b51d4363ad66e6c840" + }, + { + "car_brand": "TESLA", + "case_id": "tesla", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "2c912ca5de3b1ee9|0000025d--6eb6bcbca4--4", + "source_bytes": 8287366, + "source_sha256": "ca3bfc37b118f0e1987c2177b77b7446d44fbc7806cc5fae71c2ed79d4776fff" + } + ], + "expected_cases": 16, + "expected_params_digest": "39222ea1947da902789761de487c2f308ebe66c6b2242c983a7cf9d9d64913d3", + "expected_sources_digest": "73a05665dbaaf10abae7f7566e53cfb2e90f30ef7aafa5f4ce035d9b71298ca7", + "expected_tasks": 66, + "inventory": "active", + "partition": { + "card": 16, + "controlsd": 16, + "lagd": 16, + "other": 18 + }, + "schema_version": 1, + "task_ids": [ + "hyundai:card", + "hyundai:controlsd", + "hyundai:lagd", + "hyundai:selfdrived", + "hyundai:radard", + "hyundai:plannerd", + "hyundai:calibrationd", + "hyundai:dmonitoringd", + "hyundai:locationd", + "hyundai:paramsd", + "hyundai:ubloxd", + "hyundai:torqued", + "hyundai2:card", + "hyundai2:controlsd", + "hyundai2:lagd", + "toyota:card", + "toyota:controlsd", + "toyota:lagd", + "toyota:selfdrived", + "toyota:radard", + "toyota:plannerd", + "toyota:calibrationd", + "toyota:dmonitoringd", + "toyota:locationd", + "toyota:paramsd", + "toyota:ubloxd", + "toyota:torqued", + "toyota3:card", + "toyota3:controlsd", + "toyota3:lagd", + "honda:card", + "honda:controlsd", + "honda:lagd", + "honda2:card", + "honda2:controlsd", + "honda2:lagd", + "chrysler:card", + "chrysler:controlsd", + "chrysler:lagd", + "ram:card", + "ram:controlsd", + "ram:lagd", + "subaru:card", + "subaru:controlsd", + "subaru:lagd", + "gm:card", + "gm:controlsd", + "gm:lagd", + "nissan:card", + "nissan:controlsd", + "nissan:lagd", + "volkswagen:card", + "volkswagen:controlsd", + "volkswagen:lagd", + "mazda:card", + "mazda:controlsd", + "mazda:lagd", + "ford:card", + "ford:controlsd", + "ford:lagd", + "rivian:card", + "rivian:controlsd", + "rivian:lagd", + "tesla:card", + "tesla:controlsd", + "tesla:lagd" + ] +} diff --git a/.github/ci/process_replay_staged_inventory.json b/.github/ci/process_replay_staged_inventory.json new file mode 100644 index 00000000000000..3d5dd2ea85d391 --- /dev/null +++ b/.github/ci/process_replay_staged_inventory.json @@ -0,0 +1,438 @@ +{ + "allowed_processes": [ + "calibrationd", + "card", + "controlsd", + "dmonitoringd", + "lagd", + "locationd", + "paramsd", + "plannerd", + "radard", + "selfdrived", + "torqued", + "ubloxd" + ], + "cases": [ + { + "car_brand": "HYUNDAI", + "case_id": "hyundai", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd", + "selfdrived", + "radard", + "plannerd", + "calibrationd", + "dmonitoringd", + "locationd", + "paramsd", + "ubloxd", + "torqued" + ], + "source": "regenAA0FC4ED71E|2025-04-08--22-57-50--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "HYUNDAI2", + "case_id": "hyundai2", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regenAFB9780D823|2025-04-08--23-00-34--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "TOYOTA", + "case_id": "toyota", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd", + "selfdrived", + "radard", + "plannerd", + "calibrationd", + "dmonitoringd", + "locationd", + "paramsd", + "ubloxd", + "torqued" + ], + "source": "regen218A4DCFAA1|2025-04-08--22-57-51--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "TOYOTA3", + "case_id": "toyota3", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen1455E3B4BDF|2025-04-09--03-26-06--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "HONDA", + "case_id": "honda", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regenB328FF8BA0A|2025-04-08--22-57-45--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "HONDA2", + "case_id": "honda2", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen6170C8C9A35|2025-04-08--22-57-46--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "CHRYSLER", + "case_id": "chrysler", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen5B28FC2A437|2025-04-08--23-04-24--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "RAM", + "case_id": "ram", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regenBF81EA96E08|2025-04-08--23-06-54--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "SUBARU", + "case_id": "subaru", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen7366F13F6A1|2025-04-08--23-07-07--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "GM", + "case_id": "gm", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen1271097D038|2025-04-09--03-26-00--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "NISSAN", + "case_id": "nissan", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen15D60604EAB|2025-04-08--23-06-59--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "VOLKSWAGEN", + "case_id": "volkswagen", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen0F2F06C9539|2025-04-08--23-06-56--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "MAZDA", + "case_id": "mazda", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regenACF84CCF482|2024-08-30--03-21-55--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "FORD", + "case_id": "ford", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen755D8CB1E1F|2025-04-08--23-13-43--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "RIVIAN", + "case_id": "rivian", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "regen5FCAC896BBE|2025-04-08--23-13-35--0", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "TESLA", + "case_id": "tesla", + "custom_params": {}, + "executable": true, + "params_digest": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", + "processes": [ + "card", + "controlsd", + "lagd" + ], + "source": "2c912ca5de3b1ee9|0000025d--6eb6bcbca4--4", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "TESLA", + "case_id": "nap-preap-pedal-v1", + "custom_params": { + "NAPAdaptiveAccel": true, + "NAPBrakeFactor": 1.0, + "NAPFollowDistance": 7, + "NAPForcePreAP": true, + "NAPPedalCalibDone": true, + "NAPPedalCalibFactor": 0.9478672985781991, + "NAPPedalCalibMax": 110.23299810159, + "NAPPedalCalibMin": 0.73299810159, + "NAPPedalCalibZero": 4.732998101589998, + "NAPPedalCanBus": 2, + "NAPPedalEnabled": true, + "NAPPedalProfile": 4, + "NAPRadarBehindNosecone": true, + "NAPRadarEnabled": true, + "NAPRadarOffset": -0.5, + "NAPiBoosterEnabled": false + }, + "executable": false, + "params_digest": "b5217b239c759d5a960872a99f2e9ff6cacdb37aff6e99e1ee1bd0c20dead809", + "processes": [ + "card", + "controlsd", + "selfdrived", + "radard", + "plannerd", + "lagd" + ], + "source": "", + "source_bytes": null, + "source_sha256": null + }, + { + "car_brand": "TESLA", + "case_id": "nap-preap-no-pedal-v1", + "custom_params": { + "NAPAdaptiveAccel": true, + "NAPBrakeFactor": 1.0, + "NAPFollowDistance": 5, + "NAPForcePreAP": true, + "NAPPedalCalibDone": true, + "NAPPedalCalibFactor": 0.946969696969697, + "NAPPedalCalibMax": 110.43821722611, + "NAPPedalCalibMin": 0.9382172261100007, + "NAPPedalCalibZero": 4.838217226109999, + "NAPPedalCanBus": 2, + "NAPPedalEnabled": false, + "NAPPedalProfile": 4, + "NAPRadarBehindNosecone": true, + "NAPRadarEnabled": true, + "NAPRadarOffset": -0.25, + "NAPiBoosterEnabled": false + }, + "executable": false, + "params_digest": "96b5f9f76bdf20f24bf2a29d408d87e60ebf377eccc3858b4f0c0de7c3c2e786", + "processes": [ + "card", + "controlsd", + "selfdrived", + "radard", + "plannerd", + "lagd" + ], + "source": "", + "source_bytes": null, + "source_sha256": null + } + ], + "expected_cases": 18, + "expected_params_digest": "200ac7871bca5f1026c3a271864d88cc7a28e36f10051e85ce73205409658522", + "expected_sources_digest": "d08466e4dfe7796111b612aed7bbc2532bb40567fc85b9d71ea4343440d7736f", + "expected_tasks": 78, + "inventory": "staged", + "partition": { + "card": 18, + "controlsd": 18, + "lagd": 18, + "other": 24 + }, + "schema_version": 1, + "task_ids": [ + "hyundai:card", + "hyundai:controlsd", + "hyundai:lagd", + "hyundai:selfdrived", + "hyundai:radard", + "hyundai:plannerd", + "hyundai:calibrationd", + "hyundai:dmonitoringd", + "hyundai:locationd", + "hyundai:paramsd", + "hyundai:ubloxd", + "hyundai:torqued", + "hyundai2:card", + "hyundai2:controlsd", + "hyundai2:lagd", + "toyota:card", + "toyota:controlsd", + "toyota:lagd", + "toyota:selfdrived", + "toyota:radard", + "toyota:plannerd", + "toyota:calibrationd", + "toyota:dmonitoringd", + "toyota:locationd", + "toyota:paramsd", + "toyota:ubloxd", + "toyota:torqued", + "toyota3:card", + "toyota3:controlsd", + "toyota3:lagd", + "honda:card", + "honda:controlsd", + "honda:lagd", + "honda2:card", + "honda2:controlsd", + "honda2:lagd", + "chrysler:card", + "chrysler:controlsd", + "chrysler:lagd", + "ram:card", + "ram:controlsd", + "ram:lagd", + "subaru:card", + "subaru:controlsd", + "subaru:lagd", + "gm:card", + "gm:controlsd", + "gm:lagd", + "nissan:card", + "nissan:controlsd", + "nissan:lagd", + "volkswagen:card", + "volkswagen:controlsd", + "volkswagen:lagd", + "mazda:card", + "mazda:controlsd", + "mazda:lagd", + "ford:card", + "ford:controlsd", + "ford:lagd", + "rivian:card", + "rivian:controlsd", + "rivian:lagd", + "tesla:card", + "tesla:controlsd", + "tesla:lagd", + "nap-preap-pedal-v1:card", + "nap-preap-pedal-v1:controlsd", + "nap-preap-pedal-v1:selfdrived", + "nap-preap-pedal-v1:radard", + "nap-preap-pedal-v1:plannerd", + "nap-preap-pedal-v1:lagd", + "nap-preap-no-pedal-v1:card", + "nap-preap-no-pedal-v1:controlsd", + "nap-preap-no-pedal-v1:selfdrived", + "nap-preap-no-pedal-v1:radard", + "nap-preap-no-pedal-v1:plannerd", + "nap-preap-no-pedal-v1:lagd" + ] +} diff --git a/.github/ci/tesla_preap_lane_change_mutations.py b/.github/ci/tesla_preap_lane_change_mutations.py new file mode 100644 index 00000000000000..04779601170904 --- /dev/null +++ b/.github/ci/tesla_preap_lane_change_mutations.py @@ -0,0 +1,206 @@ +"""Lane-change lock robustness mutations for the Tesla Pre-AP gate. + +Kept separate from tesla_preap_longitudinal_mutations.py (the parent list) and reuses its +HistoricalMutation / apply / pytest / JUnit helpers: a mutation is KILLED only by assertion +failures, sources are restored byte-identically, and any survivor or invalid run fails the job. +""" +import importlib.util +import sys +import tempfile +from pathlib import Path + + +_PARENT_PATH = Path(__file__).resolve().parent / "tesla_preap_longitudinal_mutations.py" +_spec = importlib.util.spec_from_file_location("tesla_preap_longitudinal_mutations", _PARENT_PATH) +assert _spec is not None and _spec.loader is not None +parent = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = parent +_spec.loader.exec_module(parent) + +HistoricalMutation = parent.HistoricalMutation +T = "selfdrive/controls/lib/tests/test_lane_change_lock.py" +TARGET = "selfdrive/controls/lib/lane_change_target.py" +DH = "selfdrive/controls/lib/desire_helper.py" +EVENTS = "selfdrive/selfdrived/lane_change_alerts.py" +EXPECTED_COUNT = 11 + +MUTATIONS = ( + HistoricalMutation( + name="lc-lock-needs-crossing-line", + source_path=TARGET, + original=b" if probs[1 if direction == LEFT else 2] < LANE_LINE_MIN_PROB:\n", + replacement=b" if False:\n", + test_nodes=( + "selfdrive/controls/lib/tests/test_lane_change_target.py::test_low_confidence_at_start_does_not_guess", + f"{T}::test_weak_crossing_line_waits_shows_unclear_and_never_silently_cancels", + ), + ), + HistoricalMutation( + name="lc-lock-far-line-weak-refuses-again", + source_path=TARGET, + original=b" width = last_width if last_width is not None and _sane_width(last_width) else DEFAULT_LANE_WIDTH_M\n", + replacement=b" return None\n", + test_nodes=( + f"{T}::test_sep29_1200_48_left_right_line_020_locks_on_left_line", + f"{T}::test_sep29_1200_51_left_right_line_013_soft_confirm_locks", + f"{T}::test_right_change_needs_only_the_right_line", + ), + ), + HistoricalMutation( + name="lc-lock-ignores-last-good-width", + source_path=TARGET, + original=b" width = last_width if last_width is not None and _sane_width(last_width) else DEFAULT_LANE_WIDTH_M\n", + replacement=b" width = DEFAULT_LANE_WIDTH_M\n", + test_nodes=( + f"{T}::test_far_line_weak_uses_last_good_lane_width", + ), + ), + HistoricalMutation( + name="lc-lock-crossing-line-wrong-side-accepted", + source_path=TARGET, + original=b" if direction == LEFT and not left_y < 0.0:\n", + replacement=b" if False:\n", + test_nodes=( + f"{T}::test_lock_refuses_when_the_crossing_line_is_on_the_wrong_side", + ), + ), + HistoricalMutation( + name="lc-lock-retry-gives-up-at-once", + source_path=DH, + original=b" if self._lock_wait_s >= LOCK_RETRY_S - 1e-9:\n", + replacement=b" if True:\n", + test_nodes=( + f"{T}::test_brief_crossing_line_dip_retries_and_locks", + ), + ), + HistoricalMutation( + name="lc-lock-refusal-cancels-silently", + source_path=DH, + original=b" self._lock_gave_up = True\n", + replacement=b" self._reset()\n self._suppress_next_tip = True\n", + test_nodes=( + f"{T}::test_weak_crossing_line_waits_shows_unclear_and_never_silently_cancels", + f"{T}::test_line_returns_after_retry_ran_out_locks_while_nudge_held", + ), + ), + HistoricalMutation( + name="lc-lock-pending-survives-slow-speed-and-blindspot", + source_path=DH, + original=b" if blindspot_detected or below_lane_change_speed:\n self._lock_pending = False\n", + replacement=b" if False:\n self._lock_pending = False\n", + test_nodes=( + f"{T}::test_pending_lock_is_dropped_if_speed_falls_under_20_mph_before_the_line_returns", + f"{T}::test_pending_lock_is_dropped_on_blindspot_before_the_line_returns", + ), + ), + HistoricalMutation( + name="lc-lock-unclear-not-flagged-to-selfdrived", + source_path=DH, + original=b" self.signals_remaining = LANE_LINES_UNCLEAR_SIGNAL\n", + replacement=b" pass\n", + test_nodes=( + f"{T}::test_weak_crossing_line_waits_shows_unclear_and_never_silently_cancels", + ), + ), + HistoricalMutation( + name="lc-lock-released-nudge-locks-later", + source_path=DH, + original=b" elif model is not None and (self._lock_pending or (self._lock_gave_up and eligible)):\n", + replacement=b" elif model is not None and (self._lock_pending or self._lock_gave_up):\n", + test_nodes=( + f"{T}::test_released_nudge_after_retry_ran_out_does_not_lock_later", + ), + ), + HistoricalMutation( + name="lc-unclear-alert-text-dropped", + source_path=EVENTS, + original=b" unclear = sm['modelV2'].meta.laneChangeSignalsRemaining == LANE_LINES_UNCLEAR_SIGNAL\n", + replacement=b" unclear = False\n", + test_nodes=( + f"{T}::test_unclear_alert_text_only_when_flagged", + ), + ), + HistoricalMutation( + name="lc-unclear-alert-not-installed", + source_path="selfdrive/selfdrived/helpers.py", + original=b"\ninstall_lane_change_alerts()\n", + replacement=b"\n", + test_nodes=( + f"{T}::test_selfdrived_installs_the_unclear_alert", + ), + ), +) + + +def main() -> int: + if len(MUTATIONS) != EXPECTED_COUNT: + print(f"INVALID: expected {EXPECTED_COUNT} lane-change mutations, found {len(MUTATIONS)}") + return 1 + with tempfile.TemporaryDirectory(prefix="tesla-preap-lane-change-mutation-") as temp_dir: + temp_root = Path(temp_dir) + baseline_xml = temp_root / "baseline.xml" + baseline = parent.run_pytest((T,), baseline_xml) + if baseline.returncode != 0: + print("BASELINE FAILED: lane-change target tests did not pass") + print(baseline.stdout) + return 1 + try: + baseline_testcases = parent.junit_testcases(baseline_xml) + except parent.JUnitReportError as exc: + print(f"BASELINE INVALID: {exc}") + return 1 + print(f"BASELINE PASS: {len(baseline_testcases)} lane-change target tests") + + survivors = [] + for mutation in MUTATIONS: + source_path = None + original_source = None + mutation_result = None + mutation_error = None + restored = False + mutation_xml = temp_root / f"{mutation.name}.xml" + try: + source_path, original_source = parent.apply_mutation(mutation) + mutation_result = parent.run_pytest(mutation.test_nodes, mutation_xml) + except Exception as exc: # pragma: no cover - failure reporting path + mutation_error = exc + finally: + if source_path is not None and original_source is not None: + source_path.write_bytes(original_source) + restored = source_path.read_bytes() == original_source + + if not restored: + print(f"INVALID: {mutation.name} source restoration was not byte-identical") + return 1 + if mutation_error is not None: + print(f"INVALID: {mutation.name} could not run: {mutation_error}") + return 1 + if mutation_result is None: + print(f"INVALID: {mutation.name} produced no pytest result") + return 1 + try: + mutation_testcases = parent.junit_testcases(mutation_xml) + except parent.JUnitReportError as exc: + print(f"INVALID: {mutation.name} {exc}") + return 1 + if mutation_result.returncode == 1 and parent.has_only_assertion_failures(mutation_testcases): + print(f"KILLED: {mutation.name} [{', '.join(mutation.test_nodes)}]") + elif mutation_result.returncode == 0: + survivors.append(mutation.name) + print(f"SURVIVED: {mutation.name} [{', '.join(mutation.test_nodes)}]") + else: + print(f"INVALID: {mutation.name} exited without assertion-only test failures " + + f"(pytest status {mutation_result.returncode})") + print(mutation_result.stdout) + return 1 + + if survivors: + print(f"Lane-change mutations survived: {', '.join(survivors)}") + return 1 + print(f"ALL KILLED: {len(MUTATIONS)} lane-change mutations") + print("RESTORED: every mutated source is byte-identical") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/ci/tesla_preap_lat_yield_mutations.py b/.github/ci/tesla_preap_lat_yield_mutations.py new file mode 100644 index 00000000000000..9d5a5f4bce4b26 --- /dev/null +++ b/.github/ci/tesla_preap_lat_yield_mutations.py @@ -0,0 +1,283 @@ +"""Lateral-yield (A cancels / B never cancels) mutations for the Tesla Pre-AP gate. + +Panda and the card infer "lateral yielded" from the 0x488 type-1 send history +(opendbc preap/lat_yield.py, safety/modes/tesla_preap_latyield.h). The opendbc +repo's own gate kills the panda / tracker mutations; this one covers what only +runs with cereal: the CarController stamp and block, the card <-> car_specific +plumbing, the early yield, and the guard that ties the handoff timing to the +inference windows. + +Kept separate from tesla_preap_longitudinal_mutations.py (the parent list) and +reuses its HistoricalMutation / apply / pytest / JUnit helpers: a mutation is +KILLED only by assertion failures, sources are restored byte-identically, and +any survivor or invalid run fails the job. +""" +import importlib.util +import sys +import tempfile +from pathlib import Path + + +_PARENT_PATH = Path(__file__).resolve().parent / "tesla_preap_longitudinal_mutations.py" +_spec = importlib.util.spec_from_file_location("tesla_preap_longitudinal_mutations", _PARENT_PATH) +assert _spec is not None and _spec.loader is not None +parent = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = parent +_spec.loader.exec_module(parent) + +HistoricalMutation = parent.HistoricalMutation +TL = "selfdrive/car/tesla/tests/test_preap_lat_yield.py" +TE = "selfdrive/controls/lib/tests/test_driver_lateral_handoff_early_yield.py" +TG = "selfdrive/controls/lib/tests/test_lat_yield_inference_guard.py" +TW = "selfdrive/controls/lib/tests/test_driver_lateral_handoff_wheel_resume.py" +CARD = "selfdrive/car/tesla/preap_blinker_lat_pause.py" +CAR_SPECIFIC = "selfdrive/car/car_specific.py" +NUDGE = "selfdrive/controls/lib/lane_change_nudge.py" +HANDOFF = "selfdrive/controls/lib/driver_lateral_handoff.py" +CONTROLSD = "selfdrive/controls/controlsd.py" +CARCONTROLLER = "opendbc_repo/opendbc/car/tesla/carcontroller.py" +LAT_YIELD = "opendbc_repo/opendbc/car/tesla/preap/lat_yield.py" +HEADER = "opendbc_repo/opendbc/safety/modes/tesla_preap_latyield.h" +EXPECTED_COUNT = 40 + + +def _m(name, source_path, original, replacement, *test_nodes): + return HistoricalMutation(name, source_path, original, replacement, tuple(test_nodes)) + + +MUTATIONS = ( + # -- card <-> car_specific plumbing (B must not cancel, A must) ---------- + _m("card-handoff-ignores-lat-full-control", CARD, + b" _ORIG_HANDLE(self, steering_disengage, lat_full_control)\n", + b" _ORIG_HANDLE(self, steering_disengage)\n", + f"{TL}::test_B_yank_on_yielded_lateral_cancels_nothing_and_keeps_long"), + _m("card-stash-always-says-full-control", CARD, + b"encode_hands_stash(hands, bool(full_control))", b"encode_hands_stash(hands, True)", + f"{TL}::test_B_yank_on_yielded_lateral_cancels_nothing_and_keeps_long"), + _m("car-specific-ignores-the-stash", CAR_SPECIFIC, + b" lat_full_control=lat_full_control):", b" lat_full_control=True):", + f"{TL}::test_B_yank_on_yielded_lateral_cancels_nothing_and_keeps_long"), + _m("steer-disengage-event-never-fires", NUDGE, + b" if confirm or not lat_full_control:\n", b" if True:\n", + f"{TL}::test_A_yank_on_full_lateral_cancels_everything"), + # -- CarController: the 0x488 frames ARE the yield signal -------------- + _m("carcontroller-never-stamps-type1", CARCONTROLLER, + b" lat_yield.note_steer_tx(bool(lat_active), engaged=bool(CS.engagement.cruiseEnabled))\n", + b" pass\n", + f"{TL}::test_carcontroller_stamps_the_type1_frames_it_sends", + f"{TL}::test_A_yank_on_full_lateral_cancels_everything"), + _m("carcontroller-stamps-type0-frames", CARCONTROLLER, + b"lat_yield.note_steer_tx(bool(lat_active),", b"lat_yield.note_steer_tx(True,", + f"{TL}::test_carcontroller_type0_frames_do_not_stamp", + f"{TL}::test_B_yank_on_yielded_lateral_cancels_nothing_and_keeps_long"), + _m("carcontroller-ignores-the-b-edge-block", CARCONTROLLER, + b" and CS.hands_on_level < 3 and not lat_yield.blocked\n", b" and CS.hands_on_level < 3\n", + f"{TL}::test_carcontroller_refuses_type1_while_blocked_and_resumes_after_release", + f"{TL}::test_B_yank_on_yielded_lateral_cancels_nothing_and_keeps_long"), + # -- early yield on steeringPressed ------------------------------------ + _m("early-yield-disabled", HANDOFF, + b" return self._early_cnt >= EARLY_YIELD_FRAMES\n", b" return False\n", + f"{TE}::test_sustained_same_sign_push_yields_without_hands"), + _m("early-yield-ignores-sign-flips", HANDOFF, + b" self._early_cnt == 0 or sign == self._early_sign):", b" True):", + f"{TE}::test_alternating_sign_chatter_does_not_yield"), + _m("soft-yield-threshold-dropped", HANDOFF, + b"YIELD_SOFT_NM = 0.9\n", b"YIELD_SOFT_NM = 0.2\n", + f"{TE}::test_resting_band_never_yields"), + _m("early-yield-threshold-1nm", HANDOFF, + b"EARLY_YIELD_NM = 2.0\n", b"EARLY_YIELD_NM = 1.0\n", + f"{TE}::test_below_threshold_does_not_yield", f"{TG}::test_handoff_constants_are_pinned"), + _m("controlsd-drops-steering-pressed", CONTROLSD, + b" steering_pressed=bool(CS.steeringPressed),\n model_curvature=float(self._raw_model_curvature),\n", + b" model_curvature=float(self._raw_model_curvature),\n", + f"{TE}::test_controlsd_and_card_pass_steering_pressed_to_the_handoff"), + _m("card-handoff-drops-steering-pressed", CARD, + b" steering_pressed=steering_pressed,\n dt=dt,\n", b" dt=dt,\n", + f"{TL}::test_card_handoff_forwards_steering_pressed_to_the_early_yield"), + # -- guard: handoff timing vs inference windows ----------------------- + _m("handoff-blend-diverges-from-inference", HANDOFF, + b"BLEND_TIME_S = 1.0\n", b"BLEND_TIME_S = 1.6\n", + f"{TG}::test_handoff_timing_matches_what_the_inference_assumes", + f"{TG}::test_handoff_constants_are_pinned"), + _m("handoff-confirm-diverges-from-inference", HANDOFF, + b"HANDS_OFF_CONFIRM_S = 0.15\n", b"HANDS_OFF_CONFIRM_S = 0.05\n", + f"{TG}::test_handoff_timing_matches_what_the_inference_assumes", + f"{TG}::test_handoff_constants_are_pinned"), + _m("inference-grace-shorter-than-blend", LAT_YIELD, + b"GRACE_S = 1.0\n", b"GRACE_S = 0.5\n", + f"{TG}::test_grace_covers_the_blend_and_gap_sits_below_the_shortest_yield", + f"{TG}::test_blend_and_yield_read_correctly_through_the_real_handoff"), + _m("inference-gap-above-shortest-yield", LAT_YIELD, + b"GAP_S = 0.14\n", b"GAP_S = 0.30\n", + f"{TG}::test_grace_covers_the_blend_and_gap_sits_below_the_shortest_yield", + f"{TG}::test_blend_and_yield_read_correctly_through_the_real_handoff"), + # -- guard: the contract notes must stay where an editor will see them - + _m("contract-note-removed-from-handoff-module", HANDOFF, + b"INFERENCE CONTRACT (lateral yield is inferred, never announced):", + b"NOTE (lateral yield is inferred, never announced):", + f"{TG}::test_inference_contract_comment_present"), + _m("contract-note-removed-from-lat-active-doc", HANDOFF, + b" INFERENCE CONTRACT: this bit becomes", b" NOTE: this bit becomes", + f"{TG}::test_lat_active_after_handoff_documents_the_contract"), + _m("contract-note-removed-from-carcontroller", CARCONTROLLER, + b"# INFERENCE CONTRACT: type 1 must mean", b"# NOTE: type 1 must mean", + f"{TG}::test_inference_contract_comment_present"), + _m("contract-note-removed-from-lat-yield-module", LAT_YIELD, + b"INFERENCE CONTRACT (read before touching", b"NOTE (read before touching", + f"{TG}::test_inference_contract_comment_present"), + _m("contract-note-removed-from-safety-header", HEADER, + b"// INFERENCE CONTRACT: openpilot does not send panda", b"// NOTE: openpilot does not send panda", + f"{TG}::test_inference_contract_comment_present"), + # -- wheel-resume gate: no take-back while the wheel is still uncoiling - + _m("wheel-gate-removed-from-yielded-resume", HANDOFF, + b" elif self._yielded:\n pull_now = self._pull_pending and self._min_yield_met(dt)\n ready = self._integrate_giveback(tq, curv_err, dt, have_curv)\n if pull_now or (ready and not self._wheel_gate_holds(steering_angle_deg, dt)):\n", + b" elif self._yielded:\n pull_now = self._pull_pending and self._min_yield_met(dt)\n ready = self._integrate_giveback(tq, curv_err, dt, have_curv)\n if pull_now or ready:\n", + f"{TW}::test_uncoil_from_large_angle_does_not_resume_until_straight", + f"{TW}::test_low_speed_lot_is_gated_and_crossing_10mph_at_lock_does_not_resume"), + _m("wheel-gate-removed-from-inhibit-cleared-resume", HANDOFF, + b" self._blinker_was_paused = False\n self._enter_yield()\n pull_now = self._pull_pending and self._min_yield_met(dt)\n ready = self._integrate_giveback(tq, curv_err, dt, have_curv)\n if pull_now or (ready and not self._wheel_gate_holds(steering_angle_deg, dt)):\n", + b" self._blinker_was_paused = False\n self._enter_yield()\n pull_now = self._pull_pending and self._min_yield_met(dt)\n ready = self._integrate_giveback(tq, curv_err, dt, have_curv)\n if pull_now or ready:\n", + f"{TW}::test_inhibit_cleared_landing_cannot_blend_in_one_big_step"), + _m("wheel-gate-straight-window-too-wide", HANDOFF, + b" if a <= WHEEL_RESUME_STRAIGHT_DEG:\n self._straight_s += dt\n", + b" if a <= 90.0:\n self._straight_s += dt\n", + f"{TW}::test_just_outside_the_window_still_holds", + f"{TW}::test_uncoil_from_large_angle_does_not_resume_until_straight"), + _m("wheel-gate-straight-window-never-opens", HANDOFF, + b" if a <= WHEEL_RESUME_STRAIGHT_DEG:\n self._straight_s += dt\n", + b" if a <= 0.0:\n self._straight_s += dt\n", + f"{TW}::test_blend_starts_within_dwell_of_entering_the_window"), + _m("wheel-gate-dwell-removed", HANDOFF, + b" return self._straight_s + 1e-12 < WHEEL_STRAIGHT_DWELL_S\n", + b" return False\n", + f"{TW}::test_rapid_swing_through_centre_is_not_straight", + f"{TW}::test_blend_starts_within_dwell_of_entering_the_window"), + _m("wheel-gate-armed-for-every-angle", HANDOFF, + b" if self._peak_angle_deg < WHEEL_GATE_ARM_DEG:\n return False\n", + b" if False:\n return False\n", + f"{TW}::test_small_angle_nudge_resumes_as_before"), + _m("wheel-gate-never-armed", HANDOFF, + b" if self._peak_angle_deg < WHEEL_GATE_ARM_DEG:\n return False\n", + b" if True:\n return False\n", + f"{TW}::test_uncoil_from_large_angle_does_not_resume_until_straight"), + _m("wheel-gate-safety-valve-removed", HANDOFF, + b" if self._gate_hold_s >= WHEEL_GATE_MAX_HOLD_S:\n return False\n", + b" if False:\n return False\n", + f"{TW}::test_safety_valve_lets_go_after_max_hold"), + _m("wheel-gate-peak-never-tracked", HANDOFF, + b" if np.isfinite(a) and a > self._peak_angle_deg:\n", + b" if False and np.isfinite(a) and a > self._peak_angle_deg:\n", + f"{TW}::test_uncoil_from_large_angle_does_not_resume_until_straight", + f"{TW}::test_arming_is_the_peak_since_the_yield_not_the_start_angle"), + _m("wheel-gate-peak-kept-after-blend-completes", HANDOFF, + b" self._quiet_s = 0.0\n self._peak_angle_deg = 0.0\n", + b" self._quiet_s = 0.0\n", + f"{TW}::test_completed_blend_clears_the_peak"), + _m("wheel-gate-peak-lost-on-standstill-blip", HANDOFF, + b" self._peak_angle_deg = peak\n", + b" self._peak_angle_deg = 0.0\n", + f"{TW}::test_standstill_blip_keeps_the_peak_when_inhibited"), + _m("wheel-gate-peak-uses-signed-angle", HANDOFF, + b" a = abs(float(steering_angle_deg))\n if np.isfinite(a) and a > self._peak_angle_deg:\n", + b" a = float(steering_angle_deg)\n if np.isfinite(a) and a > self._peak_angle_deg:\n", + f"{TW}::test_sign_of_the_angle_does_not_matter"), + _m("wheel-gate-window-uses-signed-angle", HANDOFF, + b" a = abs(float(steering_angle_deg))\n if not np.isfinite(a):\n return False\n", + b" a = float(steering_angle_deg)\n if not np.isfinite(a):\n return False\n", + f"{TW}::test_sign_of_the_angle_does_not_matter"), + _m("wheel-gate-non-finite-angle-blocks-resume", HANDOFF, + b" if not np.isfinite(a):\n return False\n if self._peak_angle_deg", + b" if False:\n return False\n if self._peak_angle_deg", + f"{TW}::test_non_finite_or_missing_angle_never_blocks"), + _m("wheel-gate-controlsd-drops-the-angle", CONTROLSD, + b" steering_angle_deg=float(CS.steeringAngleDeg),\n", + b"", + f"{TW}::test_controlsd_passes_the_steering_angle_to_the_handoff"), + _m("wheel-gate-dwell-kept-across-hands-on", HANDOFF, + b" self._gate_hold_s = 0.0\n self._straight_s = 0.0\n self.authority = 0.0\n self.ui_paused = True\n if self._yield_age_s is None:\n", + b" self._gate_hold_s = 0.0\n self.authority = 0.0\n self.ui_paused = True\n if self._yield_age_s is None:\n", + f"{TW}::test_hands_on_during_the_dwell_restarts_the_dwell"), + _m("wheel-gate-valve-kept-across-hands-on", HANDOFF, + b" self._gate_hold_s = 0.0\n self._straight_s = 0.0\n self.authority = 0.0\n self.ui_paused = True\n if self._yield_age_s is None:\n", + b" self._straight_s = 0.0\n self.authority = 0.0\n self.ui_paused = True\n if self._yield_age_s is None:\n", + f"{TW}::test_hands_on_restarts_the_safety_valve"), + _m("wheel-gate-note-removed-from-handoff-module", HANDOFF, + b"WHEEL-RESUME GATE (rapid back-and-forth turns).", b"NOTE (rapid back-and-forth turns).", + f"{TW}::test_gate_is_written_in_the_module_docstring_and_pins_the_contract"), +) + +BASELINE_NODES = (TL, TE, TG, TW) + + +def main() -> int: + if len(MUTATIONS) != EXPECTED_COUNT: + print(f"INVALID: expected {EXPECTED_COUNT} lateral-yield mutations, found {len(MUTATIONS)}") + return 1 + with tempfile.TemporaryDirectory(prefix="tesla-preap-lat-yield-mutation-") as temp_dir: + temp_root = Path(temp_dir) + baseline_xml = temp_root / "baseline.xml" + baseline = parent.run_pytest(BASELINE_NODES, baseline_xml) + if baseline.returncode != 0: + print("BASELINE FAILED: lateral-yield tests did not pass") + print(baseline.stdout) + return 1 + try: + baseline_testcases = parent.junit_testcases(baseline_xml) + except parent.JUnitReportError as exc: + print(f"BASELINE INVALID: {exc}") + return 1 + print(f"BASELINE PASS: {len(baseline_testcases)} lateral-yield tests") + + survivors = [] + for mutation in MUTATIONS: + source_path = None + original_source = None + mutation_result = None + mutation_error = None + restored = False + mutation_xml = temp_root / f"{mutation.name}.xml" + try: + source_path, original_source = parent.apply_mutation(mutation) + mutation_result = parent.run_pytest(mutation.test_nodes, mutation_xml) + except Exception as exc: # pragma: no cover - failure reporting path + mutation_error = exc + finally: + if source_path is not None and original_source is not None: + source_path.write_bytes(original_source) + restored = source_path.read_bytes() == original_source + + if source_path is not None and not restored: + print(f"INVALID: {mutation.name} source restoration was not byte-identical") + return 1 + if mutation_error is not None: + print(f"INVALID: {mutation.name} could not run: {mutation_error}") + return 1 + if mutation_result is None: + print(f"INVALID: {mutation.name} produced no pytest result") + return 1 + try: + mutation_testcases = parent.junit_testcases(mutation_xml) + except parent.JUnitReportError as exc: + print(f"INVALID: {mutation.name} {exc}") + return 1 + if mutation_result.returncode == 1 and parent.has_only_assertion_failures(mutation_testcases): + print(f"KILLED: {mutation.name} [{', '.join(mutation.test_nodes)}]") + elif mutation_result.returncode == 0: + survivors.append(mutation.name) + print(f"SURVIVED: {mutation.name} [{', '.join(mutation.test_nodes)}]") + else: + print(f"INVALID: {mutation.name} exited without assertion-only test failures " + + f"(pytest status {mutation_result.returncode})") + print(mutation_result.stdout) + return 1 + + if survivors: + print(f"Lateral-yield mutations survived: {', '.join(survivors)}") + return 1 + print(f"ALL KILLED: {len(MUTATIONS)} lateral-yield mutations") + print("RESTORED: every mutated source is byte-identical") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/ci/tesla_preap_longitudinal_mutations.py b/.github/ci/tesla_preap_longitudinal_mutations.py new file mode 100644 index 00000000000000..fae2dc2654faab --- /dev/null +++ b/.github/ci/tesla_preap_longitudinal_mutations.py @@ -0,0 +1,160 @@ +import os +import subprocess +import sys +import tempfile +import xml.etree.ElementTree as ET +from pathlib import Path + +from tesla_preap_mutation_common import ( + FOLLOWING_TEST_PATH, + HistoricalMutation, + LONGCONTROL_TEST_PATH, + NOISE_GATE_TEST_NODE, + REPO_ROOT, +) +from tesla_preap_mutation_defs_a import MUTATIONS_A +from tesla_preap_mutation_defs_b import MUTATIONS_B +from tesla_preap_mutation_defs_c import MUTATIONS_C +from tesla_preap_mutation_defs_d import MUTATIONS_D +from tesla_preap_mutation_defs_e import MUTATIONS_E +from tesla_preap_mutation_defs_f import MUTATIONS_F +from tesla_preap_mutation_defs_g import MUTATIONS_G +from tesla_preap_mutation_defs_h import MUTATIONS_H +from tesla_preap_mutation_defs_i import MUTATIONS_I +from tesla_preap_mutation_defs_j import MUTATIONS_J + +MUTATIONS = MUTATIONS_A + MUTATIONS_B + MUTATIONS_C + MUTATIONS_D + MUTATIONS_E + MUTATIONS_F + MUTATIONS_G + MUTATIONS_H + MUTATIONS_I + MUTATIONS_J + + +class JUnitReportError(RuntimeError): + pass + + +def run_pytest(test_nodes: tuple[str, ...], junit_path: Path) -> subprocess.CompletedProcess[str]: + environment = os.environ.copy() + environment["PYTHONDONTWRITEBYTECODE"] = "1" + environment["PYTHONPATH"] = str(REPO_ROOT) + return subprocess.run( + [ + sys.executable, "-m", "pytest", "-q", "-n", "0", "-p", "no:cacheprovider", + f"--junitxml={junit_path}", *test_nodes, + ], + cwd=REPO_ROOT, + env=environment, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + + +def junit_testcases(junit_path: Path) -> list[ET.Element]: + try: + return list(ET.parse(junit_path).iter("testcase")) + except (OSError, ET.ParseError) as exc: + raise JUnitReportError(f"cannot read {junit_path.name}: {exc}") from exc + + +def has_only_assertion_failures(testcases: list[ET.Element]) -> bool: + failures = [failure for testcase in testcases for failure in testcase.findall("failure")] + errors = [error for testcase in testcases for error in testcase.findall("error")] + return ( + bool(failures) + and not errors + and all( + (failure.get("type") or "").endswith("AssertionError") + or (failure.get("message") or "").startswith("AssertionError:") + or "AssertionError" in (failure.text or "") + for failure in failures + ) + ) + + +def apply_mutation(mutation: HistoricalMutation) -> tuple[Path, bytes]: + source_path = REPO_ROOT / mutation.source_path + original_source = source_path.read_bytes() + match_count = original_source.count(mutation.original) + if match_count != 1: + raise RuntimeError( + f"{mutation.name}: expected one source match in {mutation.source_path}, found {match_count}" + ) + source_path.write_bytes(original_source.replace(mutation.original, mutation.replacement, 1)) + return source_path, original_source + + +def main() -> int: + with tempfile.TemporaryDirectory(prefix="tesla-preap-parent-mutation-") as temp_dir: + temp_root = Path(temp_dir) + baseline_xml = temp_root / "baseline.xml" + baseline = run_pytest( + (LONGCONTROL_TEST_PATH, FOLLOWING_TEST_PATH, NOISE_GATE_TEST_NODE), + baseline_xml, + ) + if baseline.returncode != 0: + print("BASELINE FAILED: parent longitudinal regression tests did not pass") + print(baseline.stdout) + return 1 + try: + baseline_testcases = junit_testcases(baseline_xml) + except JUnitReportError as exc: + print(f"BASELINE INVALID: {exc}") + return 1 + print(f"BASELINE PASS: {len(baseline_testcases)} parent tests") + + survivors = [] + for mutation in MUTATIONS: + source_path = None + original_source = None + mutation_result = None + mutation_error = None + restored = False + try: + source_path, original_source = apply_mutation(mutation) + mutation_result = run_pytest( + mutation.test_nodes, + temp_root / f"{mutation.name}.xml", + ) + except Exception as exc: # pragma: no cover - failure reporting path + mutation_error = exc + finally: + if source_path is not None and original_source is not None: + source_path.write_bytes(original_source) + restored = source_path.read_bytes() == original_source + + if not restored: + print(f"INVALID: {mutation.name} source restoration was not byte-identical") + return 1 + if mutation_error is not None: + print(f"INVALID: {mutation.name} could not run: {mutation_error}") + return 1 + if mutation_result is None: + print(f"INVALID: {mutation.name} produced no pytest result") + return 1 + + mutation_xml = temp_root / f"{mutation.name}.xml" + try: + mutation_testcases = junit_testcases(mutation_xml) + except JUnitReportError as exc: + print(f"INVALID: {mutation.name} {exc}") + return 1 + if mutation_result.returncode == 1 and has_only_assertion_failures(mutation_testcases): + print(f"KILLED: {mutation.name} [{', '.join(mutation.test_nodes)}]") + elif mutation_result.returncode == 0: + survivors.append(mutation.name) + print(f"SURVIVED: {mutation.name} [{', '.join(mutation.test_nodes)}]") + else: + print(f"INVALID: {mutation.name} exited without assertion-only test failures " + + f"(pytest status {mutation_result.returncode})") + print(mutation_result.stdout) + return 1 + + if survivors: + print(f"Historical mutations survived: {', '.join(survivors)}") + return 1 + print(f"ALL KILLED: {len(MUTATIONS)} parent longitudinal mutations") + print("RESTORED: every mutated source is byte-identical") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/ci/tesla_preap_mutation_common.py b/.github/ci/tesla_preap_mutation_common.py new file mode 100644 index 00000000000000..cb91aaa7fdbd78 --- /dev/null +++ b/.github/ci/tesla_preap_mutation_common.py @@ -0,0 +1,47 @@ +"""Shared paths and the HistoricalMutation record for the Pre-AP mutation gate.""" +from dataclasses import dataclass +from pathlib import Path + + +REPO_ROOT = Path(__file__).resolve().parents[2] +LONGCONTROL_TEST_PATH = "selfdrive/controls/tests/test_tesla_preap_longcontrol.py" +FOLLOWING_TEST_PATH = "selfdrive/controls/tests/test_tesla_preap_following.py" +GAS_LIFT_TEST_PATH = "selfdrive/controls/tests/test_tesla_preap_gas_lift_handoff.py" +BRAKE_CANCEL_TEST_PATH = ( + "selfdrive/controls/tests/test_tesla_preap_brake_cancel_regen.py" +) +UNIFIED_TEST_PATH = "selfdrive/controls/tests/test_unified_lead.py" +UNIFIED_PLANNER_TEST_PATH = "selfdrive/controls/tests/test_unified_lead_planner.py" +CURVE_PREVIEW_TEST_PATH = "selfdrive/controls/tests/test_curve_preview.py" +CURVE_FOLLOW_TEST_PATH = "selfdrive/controls/tests/test_curve_follow.py" +CURVE_FOLLOW_PLANNER_TEST_PATH = "selfdrive/controls/tests/test_curve_follow_planner.py" +CURVE_FOLLOW_CARD_TEST_PATH = "selfdrive/car/tests/test_curve_follow_card_max.py" +CURVE_MAX_HOLD_TEST_PATH = "selfdrive/controls/lib/tests/test_curve_max_hold.py" +LEAD_LEAVING_TEST_PATH = "selfdrive/controls/tests/test_lead_leaving.py" +TURN_GEOM_TEST_PATH = "selfdrive/controls/lib/tests/test_lat_turn_geometry.py" +LC_REPLAY_TEST_PATH = "selfdrive/controls/lib/tests/test_lane_change_confirm_replay.py" +LC_NUDGE_TEST_PATH = "selfdrive/controls/lib/tests/test_lane_change_nudge.py" +OFFSET_TEST_PATH = "selfdrive/mapd/tests/test_map_speed_offset_slew.py" +ENGAGE_MAX_TEST_PATH = "selfdrive/car/tests/test_preap_engage_max_after_pause.py" +FRONTAGE_TEST_PATH = "selfdrive/mapd/tests/test_map_match_frontage.py" +ROAD_CLASS_TEST_PATH = "selfdrive/mapd/tests/test_map_match_road_class.py" +LANE_CHANGE_TARGET_TEST_PATH = "selfdrive/controls/lib/tests/test_lane_change_target.py" +LC_TURN_TEST_PATH = "selfdrive/controls/lib/tests/test_lane_change_turn.py" +NOISE_GATE_TEST_NODE = ( + "opendbc_repo/opendbc/car/tesla/preap/tests/test_virtual_das.py::TestInnerPID::" + + "test_sub_deadband_sign_changing_noise_does_not_accumulate_residual_authority" +) +INNER_DEADBAND_TEST_NODE = ( + "opendbc_repo/opendbc/car/tesla/preap/tests/test_virtual_das.py::TestInnerPID::" + + "test_persistent_sub_deadband_error_earns_residual_authority" +) + + +@dataclass(frozen=True) +class HistoricalMutation: + name: str + source_path: str + original: bytes + replacement: bytes + test_nodes: tuple[str, ...] + diff --git a/.github/ci/tesla_preap_mutation_defs_a.py b/.github/ci/tesla_preap_mutation_defs_a.py new file mode 100644 index 00000000000000..b75ee56b1da09e --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_a.py @@ -0,0 +1,670 @@ +"""Parent longitudinal mutation definitions, part 1 (see tesla_preap_longitudinal_mutations.py). +""" +from tesla_preap_mutation_common import ( + BRAKE_CANCEL_TEST_PATH, + CURVE_MAX_HOLD_TEST_PATH, + CURVE_PREVIEW_TEST_PATH, + ENGAGE_MAX_TEST_PATH, + FOLLOWING_TEST_PATH, + FRONTAGE_TEST_PATH, + GAS_LIFT_TEST_PATH, + HistoricalMutation, + INNER_DEADBAND_TEST_NODE, + LANE_CHANGE_TARGET_TEST_PATH, + LEAD_LEAVING_TEST_PATH, + LONGCONTROL_TEST_PATH, + NOISE_GATE_TEST_NODE, + OFFSET_TEST_PATH, + UNIFIED_PLANNER_TEST_PATH, + UNIFIED_TEST_PATH, +) + + +MUTATIONS_A = ( + HistoricalMutation( + name="gas-lift-keeps-full-engage-grace", + source_path="opendbc_repo/opendbc/car/tesla/preap/carcontroller.py", + original=b" if gas_handoff:\n", + replacement=b" if False:\n", + test_nodes=( + f"{GAS_LIFT_TEST_PATH}::test_gas_lift_after_long_engage_does_not_floor_a_for_half_second", + ), + ), + HistoricalMutation( + name="brake-cancel-keeps-interceptor-after-long-drop", + source_path="opendbc_repo/opendbc/car/tesla/preap/carcontroller.py", + original=b" authority_requested = pedal_long_allowed and long_active and not brake_pressed and not gas_pressed\n", + replacement=b" authority_requested = pedal_long_allowed and not gas_pressed\n", + test_nodes=( + f"{BRAKE_CANCEL_TEST_PATH}::test_short_tip_releases_interceptor_immediately", + ), + ), + HistoricalMutation( + name="gas-lift-seed-ignores-planner-climb", + source_path="opendbc_repo/opendbc/car/tesla/preap/carcontroller.py", + original=b" for candidate in (last_nonneg_a_ego, measured_accel, planner_accel):\n", + replacement=b" for candidate in (last_nonneg_a_ego, measured_accel):\n", + test_nodes=( + f"{GAS_LIFT_TEST_PATH}::test_gas_lift_open_road_seed_uses_mannerisms_accel_not_only_aego", + ), + ), + HistoricalMutation( + name="gas-lift-zero-command-seed", + source_path="opendbc_repo/opendbc/car/tesla/preap/carcontroller.py", + original=( + b" commanded_accel = gas_lift_handoff_seed_accel(\n" + + b" self.last_nonneg_a_ego,\n" + + b" CS.out.aEgo,\n" + + b" self.engage_a_max,\n" + + b" float(actuators.accel),\n" + + b" )\n" + ), + replacement=b" commanded_accel = 0.0\n", + test_nodes=( + f"{GAS_LIFT_TEST_PATH}::test_gas_lift_after_long_engage_does_not_floor_a_for_half_second", + ), + ), + HistoricalMutation( + name="historical-outer-ki", + source_path="opendbc_repo/opendbc/car/tesla/preap/constants.py", + original=b"PEDAL_LONG_KI_V = [0.0, 0.0, 0.0, 0.0]\n", + replacement=b"PEDAL_LONG_KI_V = [0.05, 0.08, 0.10, 0.15]\n", + test_nodes=( + f"{LONGCONTROL_TEST_PATH}::test_vdas_receives_route_shaped_planner_target_trace_unchanged", + f"{LONGCONTROL_TEST_PATH}::test_road_load_history_cannot_reverse_finite_jerk_negative_planner_target", + f"{LONGCONTROL_TEST_PATH}::test_negative_planner_target_reaches_regen_side_of_coast_anchor", + ), + ), + HistoricalMutation( + name="adaptive-follow-cap-bypassed", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=( + b" cap_strength = get_preap_follow_cap_strength(" + + b"v_ego, lead.dRel, lead.vLead, self.t_follow)\n" + ), + replacement=b" cap_strength = 0.0\n", + test_nodes=( + f"{FOLLOWING_TEST_PATH}::" + + "test_planner_adaptive_cap_changes_the_delivered_acceleration_for_unequal_speed_lead", + ), + ), + HistoricalMutation( + name="longcontrol-feedforward-coupling-bypassed", + source_path="selfdrive/controls/lib/longcontrol.py", + original=b" feedforward=a_target)\n", + replacement=b" feedforward=0.0)\n", + test_nodes=( + f"{FOLLOWING_TEST_PATH}::test_max_follow_full_closed_loop_recovers_gap_with_production_fallback", + ), + ), + HistoricalMutation( + name="hard-inner-error-deadband-restored", + source_path="opendbc_repo/opendbc/car/tesla/preap/virtual_das.py", + original=b" error = self._gate_pid_error_noise(error, freeze_integrator)\n", + replacement=( + b" if abs(error) < PID_ERROR_DEADBAND:\n" + + b" error = 0.0\n" + ), + test_nodes=(INNER_DEADBAND_TEST_NODE,), + ), + HistoricalMutation( + name="inner-error-noise-gate-call-bypassed", + source_path="opendbc_repo/opendbc/car/tesla/preap/virtual_das.py", + original=b" error = self._gate_pid_error_noise(error, freeze_integrator)\n", + replacement=b" error = error\n", + test_nodes=(NOISE_GATE_TEST_NODE,), + ), + HistoricalMutation( + name="negative-handoff-integral-slew-regressed", + source_path="opendbc_repo/opendbc/car/tesla/preap/virtual_das.py", + original=b"NEGATIVE_HANDOFF_INTEGRAL_SLEW = 0.25 # m/s\xc2\xb3\n", + replacement=b"NEGATIVE_HANDOFF_INTEGRAL_SLEW = 0.20 # m/s\xc2\xb3\n", + test_nodes=( + f"{LONGCONTROL_TEST_PATH}::test_negative_planner_target_reaches_regen_side_of_coast_anchor", + ), + ), + HistoricalMutation( + name="grade-effort-compensation-removed", + source_path="opendbc_repo/opendbc/car/tesla/preap/virtual_das.py", + original=b" a_limited + steady_grade_compensation + transient_pitch_compensation,\n", + replacement=b" a_limited,\n", + test_nodes=( + f"{FOLLOWING_TEST_PATH}::test_plant_aligned_full_closed_loop_grade_compensation_holds_speed", + ), + ), + HistoricalMutation( + name="grade-effort-compensation-sign-flipped", + source_path="opendbc_repo/opendbc/car/tesla/preap/virtual_das.py", + original=b" a_limited + steady_grade_compensation + transient_pitch_compensation,\n", + replacement=b" a_limited - steady_grade_compensation - transient_pitch_compensation,\n", + test_nodes=( + f"{FOLLOWING_TEST_PATH}::test_plant_aligned_full_closed_loop_grade_compensation_holds_speed", + ), + ), + HistoricalMutation( + name="grade-effort-compensation-doubled", + source_path="opendbc_repo/opendbc/car/tesla/preap/virtual_das.py", + original=b" a_limited + steady_grade_compensation + transient_pitch_compensation,\n", + replacement=( + b" a_limited + 2.0 * steady_grade_compensation " + + b"+ 2.0 * transient_pitch_compensation,\n" + ), + test_nodes=( + f"{FOLLOWING_TEST_PATH}::test_plant_aligned_full_closed_loop_grade_compensation_holds_speed", + ), + ), + HistoricalMutation( + name="unified-lead-drops-braking-lead-term", + source_path="selfdrive/controls/lib/unified_lead.py", + original=( + b" a_pd = a_gv + k_a * a_l\n" + + b"\n" + + b" a_kin = _a_kin(slack, v_close, gap_f, v_e, t_follow, v_l)\n" + + b" # Braking-lead contribution on the bound. Positive a_lead stays in a_pd only.\n" + + b" a_bound = a_kin + min(a_l, 0.0) * k_a\n" + ), + replacement=( + b" a_pd = a_gv\n" + + b"\n" + + b" a_kin = _a_kin(slack, v_close, gap_f, v_e, t_follow, v_l)\n" + + b" # Braking-lead contribution on the bound. Positive a_lead stays in a_pd only.\n" + + b" a_bound = a_kin\n" + ), + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_sep23_222_exemplars_match_a_braking_lead", + ), + ), + HistoricalMutation( + name="unified-lead-jerk-limit-removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" nxt = _limit_jerk(prev, target, frame_dt, down=down, up=up)\n", + replacement=b" nxt = target\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_stateful_sweep_has_no_jerk_cliff", + ), + ), + HistoricalMutation( + name="unified-lead kinematic close term removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" return max(A_MIN_MS2, -(v * v) / (2.0 * room))\n", + replacement=b" return 0.0\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_sep25_1007_rapid_close_is_at_least_legacy_firm", + ), + ), + HistoricalMutation( + name="unified-lead gap curve discontinuity restored", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" room = outside + inside - REACTION_S * v\n", + replacement=b" room = (outside if e > 0.0 else inside) - REACTION_S * v\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_no_jump_across_the_follow_distance", + ), + ), + HistoricalMutation( + name="unified-lead MAX hard clamp restored", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" return -OVERSPEED_MAX_MS2 * math.tanh(raw / OVERSPEED_MAX_MS2)\n", + replacement=b" return A_MIN_MS2\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_sep25_1043_overspeed_is_proportional_not_a_clamp", + ), + ), + HistoricalMutation( + name="unified-lead confidence weighting removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" target_conf = on_path * lead_quality(model_prob, radar)\n", + replacement=b" target_conf = on_path\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_lead_confidence_weights_weak_readings_and_ramps_strong_ones", + ), + ), + HistoricalMutation( + name="unified-lead release rate not proportional", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" up = min(JERK_PHYS_MS3, release_base + JERK_PROP_1_S * max(0.0, err)) * frame_dt\n", + replacement=b" up = release_base * frame_dt\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_release_rate_is_proportional_to_how_far_below_target", + ), + ), + HistoricalMutation( + name="unified-lead opening trickle removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" a_cmd = w * min(a_cmd, trickle) + (1.0 - w) * a_cmd\n", + replacement=b" a_cmd = a_cmd\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_sep25_pulling_away_lead_near_gap_is_a_trickle", + ), + ), + HistoricalMutation( + name="engage MAX stale seed restored", + source_path="selfdrive/car/card.py", + original=( + b" restore_a_ms2=map_accel_a_ms2(self._map_speed_lookahead, self._map_speed_accel),\n" + + b" long_active=soft_long,\n" + ), + replacement=( + b" restore_a_ms2=map_accel_a_ms2(self._map_speed_lookahead, self._map_speed_accel),\n" + + b" long_active=True,\n" + ), + test_nodes=( + f"{ENGAGE_MAX_TEST_PATH}::test_resume_with_gas_after_pause_turn_publishes_held_max_first_frame", + f"{ENGAGE_MAX_TEST_PATH}::test_paused_long_curve_does_not_rewrite_hud_max", + ), + ), + HistoricalMutation( + name="unified-lead-shadow-guard-reraises", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=( + b" except Exception:\n" + + b" self._note_unified_fault()\n" + ), + replacement=( + b" except Exception:\n" + + b" raise\n" + ), + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_unified_fault_latches_and_publishes_the_lead_free_command", + ), + ), + HistoricalMutation( + name="same-direction nudge during ALC treated as takeover", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=( + b" # Same-direction nudge during tipped ALC is the lane-change confirm, not a takeover.\n" + b" if same_direction:\n" + b" return False\n" + ), + replacement=( + b" # Same-direction nudge during tipped ALC is the lane-change confirm, not a takeover.\n" + b" if same_direction:\n" + b" return True\n" + ), + test_nodes=( + "selfdrive/controls/lib/tests/test_lane_change_nudge.py::" + "test_tip_at_45_same_direction_nudge_confirms_through_flash_gap", + ), + ), + HistoricalMutation( + name="emergency yank suppressed during ALC", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=( + b" # Emergency yank always releases, including a same-direction yank during ALC.\n" + b" if emergency:\n" + b" return True\n" + ), + replacement=( + b" # Emergency yank always releases, including a same-direction yank during ALC.\n" + b" if emergency:\n" + b" return False\n" + ), + test_nodes=( + "selfdrive/controls/lib/tests/test_lane_change_nudge.py::" + "test_emergency_yank_same_direction_releases_and_cancels", + ), + ), + HistoricalMutation( + name="same-direction bump pauses target-locked lane change", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" suspended = locked and not lateral_active\n", + replacement=b" suspended = locked and (not lateral_active or bool(carstate.steeringPressed))\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_same_direction_bump_mid_change_continues_with_no_pause", + ), + ), + HistoricalMutation( + name="resume after release disabled", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" if not engaged or (not lateral_active and not locked) or \\\n", + replacement=b" if not engaged or not lateral_active or \\\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_ordinary_release_pauses_then_resumes_to_target", + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_resume_from_partially_over_finishes_centered_in_target_lane", + ), + ), + HistoricalMutation( + name="desire held through release so resume is not a fresh pulse", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" if self.target is not None and (self.target_suspended or pulse_gap):\n", + replacement=b" if self.target is not None and pulse_gap:\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_ordinary_release_pauses_then_resumes_to_target", + ), + ), + HistoricalMutation( + name="opposite pull no longer cancels", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" elif locked and opposite_pull:\n", + replacement=b" elif False:\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_opposite_pull_cancels", + ), + ), + HistoricalMutation( + name="opposite tip no longer cancels target-locked lane change", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" elif opposite_press:\n", + replacement=b" elif False:\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_opposite_tip_cancels", + ), + ), + HistoricalMutation( + name="target-locked lane change completes on crossing instead of centered", + source_path="selfdrive/controls/lib/lane_change_target.py", + original=b" return self.crossed and self.centered_s + 1e-9 >= CENTERED_HOLD_S\n", + replacement=b" return self.crossed\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_completes_when_centered_in_target_lane_not_on_a_timer", + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_resume_from_partially_over_finishes_centered_in_target_lane", + ), + ), + HistoricalMutation( + name="target lock timeout removed", + source_path="selfdrive/controls/lib/lane_change_target.py", + original=b" return self.age_s > TARGET_LOCK_TIMEOUT_S\n", + replacement=b" return False\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_timeout_cancels_including_released_time", + ), + ), + HistoricalMutation( + name="low-confidence lane lines keep guessing", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" elif locked and (self.target.timed_out or self.target.low_confidence):\n", + replacement=b" elif locked and self.target.timed_out:\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_low_lane_line_confidence_cancels", + ), + ), + HistoricalMutation( + name="target lock accepts low-confidence ego lines", + source_path="selfdrive/controls/lib/lane_change_target.py", + original=b" if probs[1] < LANE_LINE_MIN_PROB or probs[2] < LANE_LINE_MIN_PROB:\n", + replacement=b" if False:\n", + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_low_confidence_at_start_does_not_guess", + ), + ), + HistoricalMutation( + name="map-offset-double-add-restored", + source_path="selfdrive/car/card.py", + original=b" return (float(displayed_kph) - float(offset_kph)) * CV.KPH_TO_MS\n", + replacement=b" return float(displayed_kph) * CV.KPH_TO_MS\n", + test_nodes=( + f"{OFFSET_TEST_PATH}::test_engage_mph_offset_is_limit_plus_offset_after_1s", + f"{OFFSET_TEST_PATH}::test_engage_kph_offset_is_limit_plus_offset_after_1s", + f"{OFFSET_TEST_PATH}::test_posted_raise_keeps_single_offset", + ), + ), + HistoricalMutation( + name="current-way-stickiness-removed", + source_path="selfdrive/mapd/osm_db.py", + original=( + b" \"\"\"Keep the previous way unless a candidate is clearly closer for several lookups.\"\"\"\n" + b" if prev_dist_m > STICK_KEEP_M or not heading_aligned:\n" + b" return False\n" + b" if closer_m >= STICK_SWITCH_CLOSER_M and pending_lookups >= STICK_SWITCH_LOOKUPS:\n" + b" return False\n" + b" return True\n" + ), + replacement=( + b" \"\"\"Keep the previous way unless a candidate is clearly closer for several lookups.\"\"\"\n" + b" _ = prev_dist_m, heading_aligned, closer_m, pending_lookups\n" + b" return False\n" + ), + test_nodes=( + f"{FRONTAGE_TEST_PATH}::test_nearer_parallel_road_does_not_steal_without_clear_advantage", + ), + ), + HistoricalMutation( + name="unified-lead-decel-anticipation-removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b' a_eff = self._a_f - lead_decel_anticipation(self._a_f, self._lead_jerk, gap, v_ego)\n', + replacement=b' a_eff = self._a_f\n', + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_real_lead_brake_onset_is_anticipated_but_gradual_slowdown_is_not", + ), + ), + HistoricalMutation( + name="unified-lead-brake-scale-removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b' k_a = _k_a(slack) * _k_a_brake_scale(a_l)\n', + replacement=b' k_a = _k_a(slack)\n', + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_mild_lead_slowing_is_under_matched_and_braking_over_matched", + ), + ), + HistoricalMutation( + name="unified-lead-glide-inside-removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b' glide_keep = GLIDE_KEEP + (GLIDE_KEEP_INSIDE - GLIDE_KEEP) * _smooth01(-slack / GLIDE_GAP_M)\n', + replacement=b' glide_keep = GLIDE_KEEP\n', + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_small_inside_gap_keeps_easing_until_the_gap_recovers", + ), + ), + HistoricalMutation( + name="unified-lead-far-close-fade-removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b' k_v_close *= 1.0 - (1.0 - K_V_FAR_MIN) * _smooth01(\n', + replacement=b' k_v_close *= 1.0 - 0.0 * _smooth01(\n', + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_far_slow_close_coasts_near_close_does_not", + ), + ), + HistoricalMutation( + name="unified-lead-far-trust-bound-removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" a_cmd = trust_bound(a_cmd, hard_decel_floor(gap_f, v_e, v_l, a_l, t_follow), trust)\n", + replacement=b" a_cmd = a_cmd\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_far_offset_or_weak_lead_cannot_reach_full_regen", + ), + ), + HistoricalMutation( + name="unified-lead-far-trust-ignores-lateral-offset", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" lat_w = 1.0 - (1.0 - TRUST_LAT_MIN) * _smooth01((y - TRUST_LAT_Y0_M) / (DEPART_Y0_M - TRUST_LAT_Y0_M))\n", + replacement=b" lat_w = 1.0\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_far_offset_or_weak_lead_cannot_reach_full_regen", + ), + ), + HistoricalMutation( + name="unified-lead-far-trust-ignores-range", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" remote = far * slow\n", + replacement=b" remote = slow\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_222_exemplars_are_fully_trusted_so_unchanged", + ), + ), + HistoricalMutation( + name="unified-lead-kinematic-need-zeroed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" return max(A_MIN_MS2, min(0.0, a_match))\n", + replacement=b" return 0.0\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_far_lead_that_kinematically_needs_full_regen_still_gets_it", + ), + ), + HistoricalMutation( + name="unified-lead-inherited-seed-carried-into-remote-lead", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" self._cutin_from = trust_bound(self._cutin_from, carry, carry_trust)\n", + replacement=b" self._cutin_from = self._cutin_from\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_inherited_firm_seed_is_not_carried_into_a_remote_lead", + ), + ), + HistoricalMutation( + name="unified-lead-fresh-seed-unbounded", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" prev = trust_bound(prev, carry, carry_trust)\n", + replacement=b" prev = prev\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_inherited_firm_seed_is_not_carried_into_a_remote_lead", + ), + ), + HistoricalMutation( + name="unified-lead-seed-carry-ignores-confidence", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" carry_trust = trust * self._conf\n", + replacement=b" carry_trust = trust\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_sep28_1107_far_ambiguous_lead_is_not_a_full_regen_flash", + ), + ), + HistoricalMutation( + name="unified-lead-close-closer-trust-reduced", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" if remote <= 0.0:\n return 1.0\n", + replacement=b" if remote <= 0.0:\n return TRUST_REMOTE\n", + test_nodes=( + f"{UNIFIED_TEST_PATH}::test_close_rapid_closer_still_gets_full_fast_brake", + f"{UNIFIED_TEST_PATH}::test_moderate_range_cut_in_still_responds", + ), + ), + HistoricalMutation( + name="curve-preview-min-removed", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b' output_a_target = min(float(output_a_target), self.curve_preview_a)\n', + replacement=b' output_a_target = float(output_a_target)\n', + test_nodes=( + f"{CURVE_PREVIEW_TEST_PATH}::test_planner_preview_only_lowers_the_command", + ), + ), + HistoricalMutation( + name="curve-preview-may-raise-command", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b' output_a_target = min(float(output_a_target), self.curve_preview_a)\n', + replacement=( + b' output_a_target = self.curve_preview_a if self.curve_preview_a < PREVIEW_FREE_A_MS2 else float(output_a_target)\n' + ), + test_nodes=( + f"{CURVE_PREVIEW_TEST_PATH}::test_planner_preview_only_lowers_the_command", + ), + ), + HistoricalMutation( + name="curve-preview-decel-limit-removed", + source_path="selfdrive/controls/lib/curve_preview.py", + original=b' return min(PREVIEW_FREE_A_MS2, max(a, -preview_decel_limit_ms2(v)))\n', + replacement=b' return min(PREVIEW_FREE_A_MS2, a)\n', + test_nodes=( + f"{CURVE_PREVIEW_TEST_PATH}::test_highway_bend_preview_is_a_lift", + f"{CURVE_PREVIEW_TEST_PATH}::test_town_bend_preview_slows_early_and_gently", + ), + ), + HistoricalMutation( + name="curve-preview-release-rate-removed", + source_path="selfdrive/controls/lib/curve_preview.py", + original=b' if self.a < 0.0:\n', + replacement=b' if False:\n', + test_nodes=( + f"{CURVE_PREVIEW_TEST_PATH}::test_preview_sweep_has_no_jump", + ), + ), + HistoricalMutation( + name="turn-clip-ignores-path-ahead", + source_path="selfdrive/controls/lib/curve_preview.py", + original=b' ay = min(ay, abs(float(a_y_ahead)))\n', + replacement=b' ay = max(ay, 0.0)\n', + test_nodes=( + f"{CURVE_PREVIEW_TEST_PATH}::test_turn_clip_returns_accel_near_the_apex", + ), + ), + HistoricalMutation( + name="curve-cap-unwind-disabled", + source_path="selfdrive/controls/lib/curve_max_hold.py", + original=b' elif proposed > self._cap_kph and unwind > 0.0:\n', + replacement=b' elif proposed > self._cap_kph and False:\n', + test_nodes=( + f"{CURVE_MAX_HOLD_TEST_PATH}::test_lat_accel_smooths_and_cap_holds_then_ramps", + ), + ), + HistoricalMutation( + name="curve-lat-target-constant", + source_path="selfdrive/controls/lib/curve_max_hold.py", + original=b' return _interp(float(v_ms), CURVE_LAT_TARGET_BP_MS, CURVE_LAT_TARGET_MS2)\n', + replacement=b' return 2.0\n', + test_nodes=( + f"{CURVE_PREVIEW_TEST_PATH}::test_lateral_target_vs_speed", + ), + ), + HistoricalMutation( + name="curve-restore-profile-constant", + source_path="selfdrive/controls/lib/curve_max_hold.py", + original=b' base = _interp(float(v_ms), CURVE_RESTORE_BP_MS, CURVE_RESTORE_A_MS2)\n', + replacement=b' base = 0.40\n', + test_nodes=( + f"{CURVE_PREVIEW_TEST_PATH}::test_restore_rate_is_speed_dependent", + ), + ), + HistoricalMutation( + name="lead-leaving-clearance-bound-removed", + source_path="selfdrive/controls/lib/lead_leaving.py", + original=b" clear_w = _smooth01((y_proj - clearance_needed_m(v_ego)) / CLEAR_BAND_M)\n", + replacement=b" clear_w = 1.0\n", + test_nodes=( + f"{LEAD_LEAVING_TEST_PATH}::test_stalled_half_out_lead_keeps_braking", + f"{LEAD_LEAVING_TEST_PATH}::test_clearance_bound_is_ego_half_width_plus_lead_plus_margin", + ), + ), + HistoricalMutation( + name="lead-leaving-stall-gate-removed", + source_path="selfdrive/controls/lib/lead_leaving.py", + original=b" vy_eff = max(0.0, float(vy_away) - VY_DEADBAND_MS)\n", + replacement=b" vy_eff = 1.5\n", + test_nodes=( + f"{LEAD_LEAVING_TEST_PATH}::test_stalled_half_out_lead_keeps_braking", + ), + ), + HistoricalMutation( + name="lead-leaving-overlap-gate-removed", + source_path="selfdrive/controls/lib/lead_leaving.py", + original=b" overlap_w = _smooth01((y - OVERLAP_Y0_M) / OVERLAP_BAND_M)\n", + replacement=b" overlap_w = 1.0\n", + test_nodes=( + f"{LEAD_LEAVING_TEST_PATH}::test_lead_drifting_within_lane_not_released", + f"{LEAD_LEAVING_TEST_PATH}::test_turning_lead_released_early_with_clearance", + ), + ), + HistoricalMutation( + name="lead-leaving-fcw-suppress-removed", + source_path="selfdrive/controls/lib/lead_leaving.py", + original=b" if suppress:\n", + replacement=b" if False:\n", + test_nodes=( + f"{LEAD_LEAVING_TEST_PATH}::test_fcw_lead_two_and_new_track_restore_full_weight", + ), + ), + HistoricalMutation( + name="lead-leaving-unified-application-removed", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" fade = _leave_fade(y_rel, curvature, gap_f, path_lat, leave_w)\n", + replacement=b" fade = _depart_fade(y_rel, curvature, gap_f, path_lat)\n", + test_nodes=( + f"{LEAD_LEAVING_TEST_PATH}::test_unified_leave_weight_releases_brake_but_keeps_max_ceiling", + ), + ), + HistoricalMutation( + name="unified-static-depart-fades-half-out-lead", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b"DEPART_Y0_M = EGO_HALF_WIDTH_M + LEAD_HALF_WIDTH_M + CLEAR_MARGIN_M\n", + replacement=b"DEPART_Y0_M = 1.2\n", + test_nodes=( + f"{LEAD_LEAVING_TEST_PATH}::test_unified_leave_weight_releases_brake_but_keeps_max_ceiling", + ), + ), + HistoricalMutation( + name="unified-leaving-drops-confidence-instead", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" on_path = 1.0 - _depart_fade(y_rel, curvature, gap, path_lat)\n", + replacement=b" on_path = 1.0 - fade\n", + test_nodes=( + f"{LEAD_LEAVING_TEST_PATH}::test_unified_leave_weight_releases_brake_but_keeps_max_ceiling", + ), + ), +) diff --git a/.github/ci/tesla_preap_mutation_defs_b.py b/.github/ci/tesla_preap_mutation_defs_b.py new file mode 100644 index 00000000000000..f9a38f7715adcb --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_b.py @@ -0,0 +1,691 @@ +"""Parent longitudinal mutation definitions, part 2 (see tesla_preap_longitudinal_mutations.py). +""" +from tesla_preap_mutation_common import ( + HistoricalMutation, + LANE_CHANGE_TARGET_TEST_PATH, + LC_NUDGE_TEST_PATH, + LC_REPLAY_TEST_PATH, + LC_TURN_TEST_PATH, + LEAD_LEAVING_TEST_PATH, + TURN_GEOM_TEST_PATH, + UNIFIED_PLANNER_TEST_PATH, +) + + +MUTATIONS_B = ( + HistoricalMutation( + name="turn-geom-ref-offset-ignored", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b'-delay_offset_s(v) + ref_offset_s(v, ref_offset_m)))', + replacement=b'-delay_offset_s(v)))', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_ref_offset_is_used", + ), + ), + HistoricalMutation( + name="turn-geom-delay-table-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b'max(0.0, -delay_offset_s(v) + ref_offset_s', + replacement=b'max(0.0, ref_offset_s', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_delay_table_values", + ), + ), + HistoricalMutation( + name="turn-geom-speed-floor-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b'/ max(float(v_ego), REF_SPEED_FLOOR_MS)', + replacement=b'/ max(float(v_ego), 1e-3)', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_ref_offset_speed_floor", + ), + ), + HistoricalMutation( + name="turn-geom-highway-fade-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b'DELAY_OFFSET_S = (-0.13, -0.10, -0.08, -0.05, 0.0)', + replacement=b'DELAY_OFFSET_S = (-0.13, -0.10, -0.08, -0.05, -0.05)', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_highway_only_reference_offset", + ), + ), + HistoricalMutation( + name="turn-geom-low-speed-fade-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' return red * speed_fade(v)\n', + replacement=b' return red\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_no_effect_below_1p5ms_and_continuous_fade", + ), + ), + HistoricalMutation( + name="turn-geom-toggle-forced-on", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' if not enabled:\n self.reset()\n', + replacement=b' if False:\n self.reset()\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_off_is_stock_bit_for_bit", + ), + ), + HistoricalMutation( + name="turn-geom-active-ignores-toggle", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' return bool(is_preap) and bool(param_on)\n', + replacement=b' return bool(is_preap)\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_active_only_preap_and_toggle_on", + ), + ), + HistoricalMutation( + name="turn-geom-toggle-forced-off", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' return bool(is_preap) and bool(param_on)\n', + replacement=b' return False\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_active_only_preap_and_toggle_on", + ), + ), + HistoricalMutation( + name="turn-geom-default-off", + source_path="common/params_keys.h", + original=b'{"NAPLatTurnGeom", {PERSISTENT, BOOL, "1"}}', + replacement=b'{"NAPLatTurnGeom", {PERSISTENT, BOOL, "0"}}', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_params_default_on_and_offset_035", + ), + ), + HistoricalMutation( + name="turn-geom-reduction-cap-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' red = min(reduction_cap_s(v), max(0.0, -delay_offset_s(v)', + replacement=b' red = min(9.9, max(0.0, -delay_offset_s(v)', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_reduction_capped_at_02", + ), + ), + HistoricalMutation( + name="turn-geom-min-lookahead-clamp-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' return max(min(stock, MIN_LOOKAHEAD_S), stock - red)\n', + replacement=b' return stock - red\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_min_lookahead_floor_never_raises", + ), + ), + HistoricalMutation( + name="turn-geom-rate-limit-hold-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b'target = 0.0 if self._hold_s > 0.0 else target_reduction_s(v_ego, ref_offset_m)', + replacement=b'target = target_reduction_s(v_ego, ref_offset_m)', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_rate_limit_holds_stock_then_slews_back", + ), + ), + HistoricalMutation( + name="turn-geom-low-speed-fade-start-restored", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b'MIN_SPEED_MS = 1.5 ', + replacement=b'MIN_SPEED_MS = 3.0 ', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_no_effect_below_1p5ms_and_continuous_fade", + ), + ), + HistoricalMutation( + name="turn-geom-low-speed-reach-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' return float(np.clip(w, 0.0, 1.0))\n', + replacement=b' return 0.0\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_low_speed_extra_reach_at_5_to_8_mph", + ), + ), + HistoricalMutation( + name="turn-geom-low-speed-reach-not-faded-by-10mph", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' return float(np.clip(w, 0.0, 1.0))\n', + replacement=b' return 1.0\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_at_or_above_10mph_output_identical_to_7c49a8e", + ), + ), + HistoricalMutation( + name="turn-geom-low-speed-cap-not-raised", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b'LOW_SPEED_MAX_REDUCTION_S = 0.25\n', + replacement=b'LOW_SPEED_MAX_REDUCTION_S = 0.20\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_low_speed_extra_reach_at_5_to_8_mph", + ), + ), + HistoricalMutation( + name="turn-geom-direct-sampling-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' if floor >= MIN_STABLE_DELAY or float(action_t) >= MIN_STABLE_DELAY:\n', + replacement=b' if True:\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_plan_curvature_direct_sampling_below_03", + ), + ), + HistoricalMutation( + name="turn-geom-direct-sampling-ignores-floor", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' t = max(float(action_t), floor, LOW_SPEED_SAMPLE_FLOOR_S)\n', + replacement=b' t = max(float(action_t), 0.05)\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_plan_curvature_direct_sampling_below_03", + ), + ), + HistoricalMutation( + name="turn-geom-low-speed-freeze-removed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' if self._hold_s > 0.0 and low_speed_reach_weight(v_ego) > 0.0:\n', + replacement=b' if False:\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_rate_limit_freezes_reduction_below_10mph", + ), + ), + HistoricalMutation( + name="turn-geom-freeze-applied-above-10mph", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' if self._hold_s > 0.0 and low_speed_reach_weight(v_ego) > 0.0:\n', + replacement=b' if self._hold_s > 0.0:\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_at_or_above_10mph_output_identical_to_7c49a8e", + ), + ), + HistoricalMutation( + name="turn-geom-low-speed-cap-not-passed", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' return apply_reduction(stock_lookahead_s, self.reduction_s, reduction_cap_s(v_ego))\n', + replacement=b' return apply_reduction(stock_lookahead_s, self.reduction_s)\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_low_speed_extra_reach_at_5_to_8_mph", + ), + ), + HistoricalMutation( + name="turn-geom-sample-floor-not-updated", + source_path="selfdrive/controls/lib/lat_turn_geometry.py", + original=b' self.sample_floor_s = sample_floor_s(v_ego)\n', + replacement=b' pass\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_low_speed_extra_reach_at_5_to_8_mph", + ), + ), + HistoricalMutation( + name="turn-geom-modeld-sample-floor-not-wired", + source_path="selfdrive/modeld/modeld.py", + original=b' lat_sample_floor_s = turn_geom.sample_floor_s\n', + replacement=b' pass\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_modeld_applies_only_to_model_action_lookahead", + ), + ), + HistoricalMutation( + name="turn-geom-applied-to-maneuver-plan", + source_path="selfdrive/controls/controlsd.py", + original=b" model_or_plan_curvature = self.sm['lateralManeuverPlan'].desiredCurvature\n", + replacement=b' model_or_plan_curvature = model_v2.action.desiredCurvature\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_lateral_maneuver_plan_bypasses_correction", + ), + ), + HistoricalMutation( + name="turn-geom-modeld-off-path-not-stock", + source_path="selfdrive/modeld/modeld.py", + original=b' lat_action_t = lat_delay + frame_delay + action_delay\n', + replacement=b' lat_action_t = lat_delay + frame_delay\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_modeld_applies_only_to_model_action_lookahead", + ), + ), + HistoricalMutation( + name="roundabout-outer-bias-kept-with-turn-geom", + source_path="selfdrive/mapd/roundabout.py", + original=b' if turn_geometry_active:\n return 0.0\n return roundabout_outer_curvature_bias(', + replacement=b' return roundabout_outer_curvature_bias(', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_roundabout_outer_bias_stripped_when_correction_active", + ), + ), + HistoricalMutation( + name="roundabout-controlsd-ignores-turn-geom", + source_path="selfdrive/controls/controlsd.py", + original=b'turn_geometry_active=self._turn_geom_active,', + replacement=b'turn_geometry_active=False,', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_controlsd_gates_roundabout_bias_on_turn_geometry", + ), + ), + HistoricalMutation( + name="roundabout-off-path-bias-dropped", + source_path="selfdrive/mapd/roundabout.py", + original=b' if turn_geometry_active:\n return 0.0\n', + replacement=b' if True:\n return 0.0\n', + test_nodes=( + f"{TURN_GEOM_TEST_PATH}::test_roundabout_outer_bias_off_path_is_legacy", + ), + ), + HistoricalMutation( + name="lc-emergency-rise-line-restored", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b"EMERGENCY_RISE_NM = 4.0 * SOFT_YIELD_TRIGGER_NM\n", + replacement=b"EMERGENCY_RISE_NM = 3.0 * SOFT_YIELD_TRIGGER_NM\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_new_thresholds", + ), + ), + HistoricalMutation( + name="lc-emergency-rise-window-restored", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b"EMERGENCY_RISE_WINDOW_S = 0.250\n", + replacement=b"EMERGENCY_RISE_WINDOW_S = 0.150\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_new_thresholds", + ), + ), + HistoricalMutation( + name="lc-emergency-torque-line-restored", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b"EMERGENCY_TORQUE_NM = 2.5 * float(STEER_THRESHOLD)\n", + replacement=b"EMERGENCY_TORQUE_NM = 2.0 * float(STEER_THRESHOLD)\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_new_thresholds", + ), + ), + HistoricalMutation( + name="lc-emergency-rise-sustain-removed", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" (t - self._rise_cross_t) >= EMERGENCY_SUSTAIN_S - 1e-9)\n", + replacement=b" (t - self._rise_cross_t) >= -1.0)\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_one_frame_spike_over_the_lines_is_not_an_emergency", + ), + ), + HistoricalMutation( + name="lc-emergency-torque-sustain-removed", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" self.over_torque_s >= EMERGENCY_SUSTAIN_S - 1e-9)\n", + replacement=b" self.over_torque_s >= -1.0)\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_one_frame_spike_over_the_lines_is_not_an_emergency", + ), + ), + HistoricalMutation( + name="lc-emergency-rise-window-check-removed", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" self._rise_ok = (self._last_low_t is not None and\n (t - self._last_low_t) <= EMERGENCY_RISE_WINDOW_S + 1e-9)\n", + replacement=b" self._rise_ok = True\n", + test_nodes=( + f"{LC_NUDGE_TEST_PATH}::test_fast_torque_rise_is_an_emergency_yank", + ), + ), + HistoricalMutation( + name="lc-hands3-same-direction-still-emergency", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" if not same_direction:\n return True\n", + replacement=b" if True:\n return True\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_hands_on_level_3_same_direction_confirm_is_not_an_emergency", + ), + ), + HistoricalMutation( + name="lc-hands3-never-emergency", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" if int(hands_on_level or 0) >= EMERGENCY_HANDS_ON_LEVEL:\n", + replacement=b" if False:\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_hands_on_level_3_same_direction_confirm_is_not_an_emergency", + ), + ), + HistoricalMutation( + name="lc-card-ignores-sustained-over-torque", + source_path="selfdrive/car/car_specific.py", + original=b" over_torque=self._yank.over_torque, alc_direction=direction if alc_confirm else 0)\n", + replacement=b" over_torque=False, alc_direction=direction if alc_confirm else 0)\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_slow_hard_pull_against_the_change_releases", + ), + ), + HistoricalMutation( + name="lc-card-hands3-ignores-alc-direction", + source_path="selfdrive/car/car_specific.py", + original=b" over_torque=self._yank.over_torque, alc_direction=direction if alc_confirm else 0)\n", + replacement=b" over_torque=self._yank.over_torque, alc_direction=0)\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_hands_on_level_3_same_direction_confirm_is_not_an_emergency", + ), + ), + HistoricalMutation( + name="lc-desire-ignores-sustained-over-torque", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" over_torque=self._yank.over_torque,\n", + replacement=b" over_torque=False,\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_slow_hard_pull_against_the_change_releases", + ), + ), + HistoricalMutation( + name="lc-desire-hands3-ignores-alc-direction", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" alc_direction=lc_dir,\n", + replacement=b" alc_direction=0,\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_hands_on_level_3_same_direction_confirm_is_not_an_emergency", + ), + ), + HistoricalMutation( + name="lc-soft-confirm-not-applied", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b" torque_applied = torque_applied or soft_confirm\n", + replacement=b" torque_applied = torque_applied\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_first_nudge_below_steering_pressed_now_confirms", + ), + ), + HistoricalMutation( + name="lc-soft-confirm-line-too-low", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b"SOFT_CONFIRM_NM = 0.65 * float(STEER_THRESHOLD)\n", + replacement=b"SOFT_CONFIRM_NM = 0.45 * float(STEER_THRESHOLD)\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_road_bumps_and_crown_do_not_confirm", + ), + ), + HistoricalMutation( + name="lc-soft-confirm-sustain-removed", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" return self._held_s >= SOFT_CONFIRM_SUSTAIN_S - 1e-9\n", + replacement=b" return True\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_road_bumps_and_crown_do_not_confirm", + f"{LC_REPLAY_TEST_PATH}::test_soft_confirm_needs_the_sustain_time", + ), + ), + HistoricalMutation( + name="lc-soft-confirm-any-direction", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" signed = torque if direction == 1 else (-torque if direction == 2 else 0.0)\n", + replacement=b" signed = abs(torque)\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_soft_confirm_only_same_direction_and_at_speed", + ), + ), + HistoricalMutation( + name="lc-soft-confirm-not-armed-only", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" if not armed or signed < SOFT_CONFIRM_NM:\n", + replacement=b" if signed < SOFT_CONFIRM_NM:\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_soft_confirm_only_same_direction_and_at_speed", + ), + ), + HistoricalMutation( + name="lc-soft-confirm-no-reset-on-dip", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b" self._held_s = 0.0\n return False\n", + replacement=b" return False\n", + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_road_bumps_and_crown_do_not_confirm", + ), + ), + HistoricalMutation( + name="lc-takeover-is-an-emergency", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b' if over_torque and not same_direction:\n', + replacement=b' if over_torque:\n', + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_sustained_same_direction_pull_is_a_takeover_not_an_emergency", + f"{LC_TURN_TEST_PATH}::test_sustained_hard_turn_is_never_an_emergency", + ), + ), + HistoricalMutation( + name="lc-takeover-sustain-too-short", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b'TAKEOVER_SUSTAIN_S = 0.30\n', + replacement=b'TAKEOVER_SUSTAIN_S = 0.10\n', + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_new_thresholds", + f"{LC_REPLAY_TEST_PATH}::test_hard_confirm_peak_is_not_a_takeover", + f"{LC_REPLAY_TEST_PATH}::test_sustained_same_direction_pull_is_a_takeover_not_an_emergency", + ), + ), + HistoricalMutation( + name="lc-takeover-never-clears", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b' if self.takeover and self._hands_off_s >= TAKEOVER_HANDS_OFF_S - 1e-9:\n self.takeover = False\n', + replacement=b'', + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_sustained_same_direction_pull_is_a_takeover_not_an_emergency", + ), + ), + HistoricalMutation( + name="lc-opposite-pull-sustain-removed", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b' return self._opposite_s >= OPPOSITE_PULL_SUSTAIN_S - 1e-9\n', + replacement=b' return self._opposite_s > 0.0\n', + test_nodes=( + f"{LC_REPLAY_TEST_PATH}::test_sep28_1037_right_confirm_still_confirms", + f"{LC_REPLAY_TEST_PATH}::test_sep28_1101_left_confirm_still_confirms", + f"{LC_REPLAY_TEST_PATH}::test_sep28_1111_right_confirm_still_confirms", + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_confirm_spring_back_does_not_cancel", + ), + ), + HistoricalMutation( + name="lc-opposite-pull-any-torque", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b' return torque <= -OPPOSITE_PULL_NM\n', + replacement=b' return torque < 0.0\n', + test_nodes=( + f"{LANE_CHANGE_TARGET_TEST_PATH}::test_confirm_spring_back_does_not_cancel", + ), + ), + HistoricalMutation( + name="lc-turn-angle-too-low", + source_path="selfdrive/controls/lib/lane_change_turn.py", + original=b'TURN_ENTER_ANGLE_DEG = 45.0\n', + replacement=b'TURN_ENTER_ANGLE_DEG = 20.0\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_thresholds_from_logs", + ), + ), + HistoricalMutation( + name="lc-turn-without-driver-steering", + source_path="selfdrive/controls/lib/lane_change_turn.py", + original=b' return (not lat_active) or _signed(torque_nm, direction) >= TURN_DRIVER_TORQUE_NM\n', + replacement=b' return True\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_curve_steered_by_openpilot_is_not_a_turn", + ), + ), + HistoricalMutation( + name="lc-turn-exit-hold-removed", + source_path="selfdrive/controls/lib/lane_change_turn.py", + original=b' if self._exit_s >= TURN_EXIT_HOLD_S - 1e-9:\n', + replacement=b' if True:\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_turn_hold_unit_exit_needs_the_hold_time", + ), + ), + HistoricalMutation( + name="lc-turn-hold-timeout-removed", + source_path="selfdrive/controls/lib/lane_change_turn.py", + original=b' if self._t >= TURN_HOLD_TIMEOUT_S - 1e-9:\n', + replacement=b' if False:\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_blinker_hold_never_flashes_forever", + ), + ), + HistoricalMutation( + name="lc-turn-hold-opposite-stalk-ignored", + source_path="selfdrive/controls/lib/lane_change_turn.py", + original=b' if stalk == opposite and prev_stalk != opposite:\n', + replacement=b' if False:\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_blinker_hold_never_flashes_forever", + ), + ), + HistoricalMutation( + name="lc-speed-hold-never-resumes", + source_path="selfdrive/controls/lib/lane_change_turn.py", + original=b' elif float(v_ego) >= HOLD_RESUME_SPEED:\n', + replacement=b' elif False:\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_speed_hold_ends_when_back_up_to_speed_without_a_turn", + ), + ), + HistoricalMutation( + name="lc-desire-ignores-driver-turn", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b' elif driver_turn:\n', + replacement=b' elif False:\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_turn_mid_change_pauses_lat_keeps_engaged_and_blinker", + f"{LC_TURN_TEST_PATH}::test_turn_then_straight_road_resumes_on_lane_center_not_old_target", + ), + ), + HistoricalMutation( + name="lc-desire-keeps-change-under-20mph", + source_path="selfdrive/controls/lib/desire_helper.py", + original=b' elif below_lane_change_speed and self.lane_change_state in (\n', + replacement=b' elif False and self.lane_change_state in (\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_speed_under_20_mid_change_ends_it_and_holds_the_blinker_for_the_turn", + ), + ), + HistoricalMutation( + name="lc-hold-ignores-driver-turn", + source_path="selfdrive/controls/lib/blinker_lateral_pause.py", + original=b' if stalk_is_turn or driver_turn:\n', + replacement=b' if stalk_is_turn:\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_turn_mid_change_pauses_lat_keeps_engaged_and_blinker", + ), + ), + HistoricalMutation( + name="lc-post-change-hand-on-hold-removed", + source_path="selfdrive/controls/lib/blinker_lateral_pause.py", + original=b' if steering_pressed:\n self.holding = True\n', + replacement=b' if False:\n self.holding = True\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_lane_change_ending_with_hands_on_keeps_the_disengage_block", + ), + ), + HistoricalMutation( + name="lc-controlsd-yields-on-emergency-only", + source_path="selfdrive/controls/controlsd.py", + original=b'emergency_yank=bool(self._lane_change_torque.release),', + replacement=b'emergency_yank=bool(self._lane_change_torque.emergency),', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_controlsd_wires_turn_hold_and_tipped_torque", + ), + ), + HistoricalMutation( + name="lc-controlsd-drops-turn-blinker", + source_path="selfdrive/controls/controlsd.py", + original=b' turn_hold_dir)\n', + replacement=b' 0)\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_controlsd_wires_turn_hold_and_tipped_torque", + ), + ), + HistoricalMutation( + name="lc-controlsd-no-driver-turn-pause", + source_path="selfdrive/controls/controlsd.py", + original=b'driver_turn=self._lane_change_turn.turning,', + replacement=b'driver_turn=False,', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_controlsd_wires_turn_hold_and_tipped_torque", + ), + ), + HistoricalMutation( + name="lc-slow-turn-ramp-counted-as-yank", + source_path="selfdrive/controls/lib/lane_change_nudge.py", + original=b'EMERGENCY_RISE_WINDOW_S = 0.250\n', + replacement=b'EMERGENCY_RISE_WINDOW_S = 0.600\n', + test_nodes=( + f"{LC_TURN_TEST_PATH}::test_sep28_1113_sustained_turn_with_latched_stalk_is_not_an_emergency", + ), + ), + HistoricalMutation( + name="unified-output-not-published", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b" self.output_a_target = float(command)\n", + replacement=b" self.output_a_target = self.output_a_target\n", + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_sole_path_follows_the_continuous_command_for_sep23", + ), + ), + HistoricalMutation( + name="unified-seed-bound-removed", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b" seed = min(existing, max(wanted, 0.0))\n", + replacement=b" seed = existing\n", + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_first_far_closing_lead_is_never_rematched_with_plus_a", + ), + ), + HistoricalMutation( + name="unified-seed-brake-head-start-removed", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b" seed = min(existing, max(wanted, min(existing, 0.0) - SEED_BRAKE_STEP_MS2))\n", + replacement=b" seed = existing\n", + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_first_hard_close_frame_starts_firmer_than_the_lead_free_command", + ), + ), + HistoricalMutation( + name="unified-fcw-clamp-removed", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b" command = min(command, existing)\n", + replacement=b" command = command\n", + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_fcw_is_not_weaker_than_the_lead_free_command", + ), + ), + HistoricalMutation( + name="unified-curve-ceiling-removed", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b" v_cap = min(v_cap, float(v_curve))\n", + replacement=b" v_cap = v_cap\n", + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_curve_ceiling_brakes_with_a_lead_present", + ), + ), + HistoricalMutation( + name="unified-gate-ignores-fingerprint", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b"CP.brand == \"tesla\" and CP.carFingerprint == \"TESLA_MODEL_S_PREAP\"", + replacement=b"CP.brand == \"tesla\"", + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_other_cars_never_run_the_unified_controller", + ), + ), + HistoricalMutation( + name="unified-gate-ignores-pcm-cruise", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b" and CP.openpilotLongitudinalControl and not CP.pcmCruise)\n", + replacement=b" and CP.openpilotLongitudinalControl)\n", + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_other_cars_never_run_the_unified_controller", + ), + ), + HistoricalMutation( + name="unified-lead-release-ignores-max-ceiling", + source_path="selfdrive/controls/lib/unified_lead.py", + original=b" a_cmd = min(a_cmd, speed_ceiling_accel(v_e, float(v_ceiling)))\n", + replacement=b" a_cmd = a_cmd\n", + test_nodes=( + f"{LEAD_LEAVING_TEST_PATH}::test_unified_leave_weight_releases_brake_but_keeps_max_ceiling", + f"{LEAD_LEAVING_TEST_PATH}::test_planner_leaving_release_respects_max_ceiling", + ), + ), + HistoricalMutation( + name="planner-cycle-log-never-closes-window", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=b" if self.n < self.every_n:\n", + replacement=b" if True:\n", + test_nodes=( + f"{UNIFIED_PLANNER_TEST_PATH}::test_cycle_time_log_reports_mean_and_max_per_window", + ), + ), +) diff --git a/.github/ci/tesla_preap_mutation_defs_c.py b/.github/ci/tesla_preap_mutation_defs_c.py new file mode 100644 index 00000000000000..0a0d531d888c82 --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_c.py @@ -0,0 +1,49 @@ +"""Map road-class mutation definitions (see tesla_preap_longitudinal_mutations.py). + +A golf-cart `highway=path maxspeed=5 mph` must never be matched as the posted +limit (Oct 1-3 routes locked HUD MAX to 5 mph). Kept in its own part so the +parent defs stay untouched. +""" +from tesla_preap_mutation_common import ( + HistoricalMutation, + ROAD_CLASS_TEST_PATH, +) + + +MUTATIONS_C = ( + HistoricalMutation( + name="road-class-filter-removed", + source_path="selfdrive/mapd/osm_db.py", + original=( + b" highway = row[\"highway\"] or \"\"\n" + + b" if _is_non_road_highway(highway):\n" + + b" continue\n" + ), + replacement=b" highway = row[\"highway\"] or \"\"\n", + test_nodes=( + f"{ROAD_CLASS_TEST_PATH}::test_non_road_way_alone_is_not_matched", + f"{ROAD_CLASS_TEST_PATH}::test_non_road_way_does_not_beat_a_farther_tagged_road", + ), + ), + HistoricalMutation( + name="road-class-filter-missing-from-next-limit", + source_path="selfdrive/mapd/osm_db.py", + original=b" if _is_non_road_highway(highway):\n continue\n", + replacement=b" if along_route is None and _is_non_road_highway(highway):\n continue\n", + test_nodes=( + f"{ROAD_CLASS_TEST_PATH}::test_next_limit_ignores_a_non_road_way_ahead", + ), + ), + HistoricalMutation( + name="road-class-filter-moved-into-candidates", + source_path="selfdrive/mapd/osm_db.py", + original=b" return list(self._con.execute(q, ids))\n\n def _best_match(", + replacement=( + b" return [r for r in self._con.execute(q, ids) if not _is_non_road_highway(r[\"highway\"])]\n" + + b"\n def _best_match(" + ), + test_nodes=( + f"{ROAD_CLASS_TEST_PATH}::test_junction_tagged_ring_is_found_even_in_a_non_road_class", + ), + ), +) diff --git a/.github/ci/tesla_preap_mutation_defs_d.py b/.github/ci/tesla_preap_mutation_defs_d.py new file mode 100644 index 00000000000000..6f13755f6f60ad --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_d.py @@ -0,0 +1,398 @@ +"""Curve-follow mutation definitions (see tesla_preap_longitudinal_mutations.py). + +The continuous curve term (NAPCurveFollow) ships in shadow first. Each entry +breaks one rule of the term, its wiring, or the shadow guarantee (commands +and MAX untouched) and must fail the pinned tests with an AssertionError. +""" +from tesla_preap_mutation_common import ( + CURVE_FOLLOW_CARD_TEST_PATH, + CURVE_FOLLOW_PLANNER_TEST_PATH, + CURVE_FOLLOW_TEST_PATH, + HistoricalMutation, +) + + +MUTATIONS_D = ( + HistoricalMutation( + name="release-buffer-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'float(d) - RELEASE_BEFORE_TIGHTEST_S * v - min_room' + ), + replacement=( + b'float(d) - 0.0 * v - min_room' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_release_buffer_is_one_named_constant_and_is_wired", + ), + ), + HistoricalMutation( + name="spike-clip-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'if nb and kc[i] > SPIKE_MIN_K and kc[i] > SPIKE_RATIO * max(nb):' + ), + replacement=( + b'if False and nb and kc[i] > SPIKE_MIN_K and kc[i] > SPIKE_RATIO * max(nb):' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_curvature_filter_clips_a_spike_and_opens_slowly", + ), + ), + HistoricalMutation( + name="k-filter-opens-as-fast-as-it-tightens", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'if x > cur else K_DOWN_TAU_S' + ), + replacement=( + b'if x > cur else K_UP_TAU_S' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_curvature_filter_clips_a_spike_and_opens_slowly", + ), + ), + HistoricalMutation( + name="k-filter-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'self._kf[i] = cur + dt / (tau + dt) * (x - cur)' + ), + replacement=( + b'self._kf[i] = x' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_curvature_filter_clips_a_spike_and_opens_slowly", + ), + ), + HistoricalMutation( + name="snr-accumulates-unsigned-curvature", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'k_mid = 0.5 * (float(ks[i]) + float(ks[i - 1]))' + ), + replacement=( + b'k_mid = 0.5 * (abs(float(ks[i])) + abs(float(ks[i - 1])))' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_zero_mean_curvature_noise_does_not_accumulate_into_a_bend", + ), + ), + HistoricalMutation( + name="snr-gate-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'w[i] = _smooth01((abs(y) / std - SNR_S0) / (SNR_S1 - SNR_S0))' + ), + replacement=( + b'w[i] = 1.0' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_high_position_std_silences_far_points_low_std_trusts_them", + ), + ), + HistoricalMutation( + name="position-std-ignored", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'std = max(STD_FLOOR_M, float(y_std[i]))' + ), + replacement=( + b'std = STD_FLOOR_M' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_high_position_std_silences_far_points_low_std_trusts_them", + ), + ), + HistoricalMutation( + name="low-speed-gate-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'gate = 1.0 - (slow if not blinker else 0.0)' + ), + replacement=( + b'gate = 1.0' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_low_speed_rules", + ), + ), + HistoricalMutation( + name="blinker-does-not-open-the-low-speed-gate", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'gate = 1.0 - (slow if not blinker else 0.0)' + ), + replacement=( + b'gate = 1.0 - slow' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_low_speed_rules", + ), + ), + HistoricalMutation( + name="low-speed-horizon-cut-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'far_cut = slow * _smooth01((float(t) - LOW_HORIZON_S) / LOW_HORIZON_BAND_S)' + ), + replacement=( + b'far_cut = 0.0' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_low_speed_rules", + ), + ), + HistoricalMutation( + name="lane-change-does-not-fade-the-term", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'ctx_ok = not (lane_change or rb_active or float(frame_drop_pct) > FRAME_DROP_MAX_PCT)' + ), + replacement=( + b'ctx_ok = not (rb_active or float(frame_drop_pct) > FRAME_DROP_MAX_PCT)' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_lane_change_fades_the_term_out_without_a_step", + ), + ), + HistoricalMutation( + name="roundabout-funnel-does-not-fade-the-term", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'ctx_ok = not (lane_change or rb_active or float(frame_drop_pct) > FRAME_DROP_MAX_PCT)' + ), + replacement=( + b'ctx_ok = not (lane_change or float(frame_drop_pct) > FRAME_DROP_MAX_PCT)' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_active_roundabout_funnel_fades_the_term_out", + ), + ), + HistoricalMutation( + name="frame-drops-do-not-fade-the-term", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'ctx_ok = not (lane_change or rb_active or float(frame_drop_pct) > FRAME_DROP_MAX_PCT)' + ), + replacement=( + b'ctx_ok = not (lane_change or rb_active)' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_dropped_frames_fade_the_term_out_and_light_drops_do_not", + ), + ), + HistoricalMutation( + name="confidence-steps-instead-of-ramping", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'self._conf = min(1.0, max(0.0, self._conf + min(1.0, rate * dt) * (target - self._conf)))' + ), + replacement=( + b'self._conf = target' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_lane_change_fades_the_term_out_without_a_step", + ), + ), + HistoricalMutation( + name="brake-build-jerk-limit-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'build = min(BUILD_MAX_MS3, base + BUILD_PROP_1_S * (-err)) * dt' + ), + replacement=( + b'build = 1e9 * dt' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_constant_radius_bend_slows_early_gently_and_to_the_table", + ), + ), + HistoricalMutation( + name="brake-release-rate-unbounded", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'release = min(RELEASE_MAX_MS3, rel_base + RELEASE_PROP_1_S * max(0.0, err)) * dt' + ), + replacement=( + b'release = 1e9 * dt' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_proportional_release_rate_is_bounded", + ), + ), + HistoricalMutation( + name="near-field-term-allowed-to-brake-hard", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'max(over, -NEAR_BRAKE_MAX_MS2)' + ), + replacement=( + b'over' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_near_field_term_is_a_lift_not_a_brake", + ), + ), + HistoricalMutation( + name="apex-detection-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'self.passed = _smooth01((PEAK_RATIO0 - k_ahead / k_now) / PEAK_BAND)' + ), + replacement=( + b'self.passed = 0.0' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_apex_detection_reads_the_path_peaking", + ), + ), + HistoricalMutation( + name="relief-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'relief = r0 * (1.0 - _smooth01((v - v_env) / max(v_prof - v_env, 0.5)))' + ), + replacement=( + b'relief = 0.0' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_s_curve_family_regens_back_down_without_chatter_or_latch", + ), + ), + HistoricalMutation( + name="decel-limit-removed", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'a_c = min(FREE_A_MS2, max(a_c, -preview_decel_limit_ms2(v)))' + ), + replacement=( + b'a_c = min(FREE_A_MS2, a_c)' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_braking_never_exceeds_the_speed_dependent_decel_limit", + ), + ), + HistoricalMutation( + name="mode-param-unknown-value-not-shadow", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'return mode if mode in (MODE_OFF, MODE_SHADOW, MODE_ACTIVE) else DEFAULT_MODE' + ), + replacement=( + b'return mode' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_mode_param_reader_defaults_to_shadow_and_clamps", + ), + ), + HistoricalMutation( + name="mode-param-default-is-active", + source_path="selfdrive/controls/lib/curve_follow.py", + original=( + b'DEFAULT_MODE = MODE_SHADOW' + ), + replacement=( + b'DEFAULT_MODE = MODE_ACTIVE' + ), + test_nodes=( + f"{CURVE_FOLLOW_TEST_PATH}::test_mode_param_reader_defaults_to_shadow_and_clamps", + ), + ), + HistoricalMutation( + name="shadow-overwrites-the-preview", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=( + b'if self._cf_mode == MODE_ACTIVE:\n' + + b' self.curve_preview_a = a_cf' + ), + replacement=( + b'if self._cf_mode != MODE_OFF:\n' + + b' self.curve_preview_a = a_cf' + ), + test_nodes=( + f"{CURVE_FOLLOW_PLANNER_TEST_PATH}::test_shadow_commands_are_bit_identical_to_off", + ), + ), + HistoricalMutation( + name="reactive-cap-skipped-when-untrusted", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=( + b'cf_owns_curve = self._cf_mode == MODE_ACTIVE and self._cf_trusted and not self._cf_faulted' + ), + replacement=( + b'cf_owns_curve = self._cf_mode == MODE_ACTIVE and not self._cf_faulted' + ), + test_nodes=( + f"{CURVE_FOLLOW_PLANNER_TEST_PATH}::test_dead_camera_keeps_the_reactive_cap_in_active", + ), + ), + HistoricalMutation( + name="reactive-cap-skipped-in-shadow", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=( + b'cf_owns_curve = self._cf_mode == MODE_ACTIVE and self._cf_trusted and not self._cf_faulted' + ), + replacement=( + b'cf_owns_curve = self._cf_mode != MODE_OFF and self._cf_trusted and not self._cf_faulted' + ), + test_nodes=( + f"{CURVE_FOLLOW_PLANNER_TEST_PATH}::test_reactive_cap_stays_unless_active_and_trusted", + ), + ), + HistoricalMutation( + name="fault-does-not-latch", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=( + b' self._cf_faulted = True\n' + + b' self._cf_trusted = False' + ), + replacement=( + b' self._cf_trusted = False' + ), + test_nodes=( + f"{CURVE_FOLLOW_PLANNER_TEST_PATH}::test_a_fault_latches_and_the_old_preview_stays", + ), + ), + HistoricalMutation( + name="log-failure-reaches-the-command", + source_path="selfdrive/controls/lib/longitudinal_planner.py", + original=( + b' except Exception:\n' + + b' pass # logging must never touch the command' + ), + replacement=( + b' except ZeroDivisionError:\n' + + b' pass # logging must never touch the command' + ), + test_nodes=( + f"{CURVE_FOLLOW_PLANNER_TEST_PATH}::test_a_logging_exception_cannot_touch_the_command", + ), + ), + HistoricalMutation( + name="shadow-retires-the-max-cap", + source_path="selfdrive/car/card.py", + original=( + b'curve_follow_on = getattr(self, "_curve_follow_mode", MODE_SHADOW) == MODE_ACTIVE' + ), + replacement=( + b'curve_follow_on = getattr(self, "_curve_follow_mode", MODE_SHADOW) != MODE_SHADOW' + ), + test_nodes=( + f"{CURVE_FOLLOW_CARD_TEST_PATH}::test_off_and_shadow_still_cap_max_in_a_bend", + ), + ), + HistoricalMutation( + name="active-keeps-the-max-cap", + source_path="selfdrive/car/card.py", + original=( + b'curve_follow_on = getattr(self, "_curve_follow_mode", MODE_SHADOW) == MODE_ACTIVE' + ), + replacement=( + b'curve_follow_on = False' + ), + test_nodes=( + f"{CURVE_FOLLOW_CARD_TEST_PATH}::test_active_never_touches_max", + ), + ), +) diff --git a/.github/ci/tesla_preap_mutation_defs_e.py b/.github/ci/tesla_preap_mutation_defs_e.py new file mode 100644 index 00000000000000..8711643c580a94 --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_e.py @@ -0,0 +1,102 @@ +"""Turn-in delay trim mutation definitions (see tesla_preap_longitudinal_mutations.py). + +NAPTurnInDelay (steps -2..+3, 30 ms each) trims the low-speed turn-in on top of +the turn geometry correction. Each entry breaks one rule of the trim (default +0 identical, bounded, low-speed band only, slewed, wired into modeld and the +Driving Mannerisms menu) and must fail the pinned tests with an AssertionError. +""" +from tesla_preap_mutation_common import ( + HistoricalMutation, + TURN_GEOM_TEST_PATH, +) + +TG = "selfdrive/controls/lib/lat_turn_geometry.py" +MODELD = "selfdrive/modeld/modeld.py" +MENU = "selfdrive/ui/layouts/settings/driving_mannerisms.py" +T = TURN_GEOM_TEST_PATH + + +def _m(name, path, original, replacement, *tests): + return HistoricalMutation( + name=name, source_path=path, original=original, replacement=replacement, + test_nodes=tuple(f"{T}::{t}" for t in tests), + ) + + +MUTATIONS_E = ( + _m("turn-in-step-clamp-removed", TG, + b" return int(min(TURN_IN_STEP_MAX, max(TURN_IN_STEP_MIN, round(v))))\n", + b" return int(round(v))\n", + "test_turn_in_step_is_clamped_and_junk_is_zero"), + _m("turn-in-junk-step-not-zero", TG, + b" return 0\n if not np.isfinite(v):\n return 0\n", + b" return 0\n if not np.isfinite(v):\n return 1\n", + "test_turn_in_step_is_clamped_and_junk_is_zero"), + _m("turn-in-step-size-doubled", TG, + b"TURN_IN_STEP_S = 0.030 ", b"TURN_IN_STEP_S = 0.060 ", + "test_turn_in_param_defaults_to_zero_int", "test_turn_in_each_step_is_30ms_in_the_full_band"), + _m("turn-in-max-step-raised", TG, + b"TURN_IN_STEP_MAX = 3\n", b"TURN_IN_STEP_MAX = 5\n", + "test_turn_in_param_defaults_to_zero_int", "test_turn_in_step_is_clamped_and_junk_is_zero"), + _m("turn-in-min-lookahead-lowered", TG, + b"TURN_IN_MIN_LOOKAHEAD_S = 0.10 ", b"TURN_IN_MIN_LOOKAHEAD_S = 0.01 ", + "test_turn_in_param_defaults_to_zero_int", "test_turn_in_lookahead_is_bounded"), + _m("turn-in-band-not-faded-by-10mph", TG, + b" return low_speed_reach_weight(v_ego) * speed_fade(v_ego)\n", + b" return speed_fade(v_ego)\n", + "test_turn_in_trim_never_changes_10mph_and_up_or_below_1p5ms", + "test_turn_in_band_fades_out_by_10mph_and_in_between_1p5_and_2p5"), + _m("turn-in-band-active-at-standstill", TG, + b" return low_speed_reach_weight(v_ego) * speed_fade(v_ego)\n", + b" return low_speed_reach_weight(v_ego)\n", + "test_turn_in_trim_never_changes_10mph_and_up_or_below_1p5ms", + "test_turn_in_band_fades_out_by_10mph_and_in_between_1p5_and_2p5"), + _m("turn-in-shift-sign-flipped", TG, + b" return clamp_turn_in_step(step) * TURN_IN_STEP_S * turn_in_weight(v_ego)\n", + b" return -clamp_turn_in_step(step) * TURN_IN_STEP_S * turn_in_weight(v_ego)\n", + "test_turn_in_each_step_is_30ms_in_the_full_band"), + _m("turn-in-step-not-clamped-in-shift", TG, + b" return clamp_turn_in_step(step) * TURN_IN_STEP_S * turn_in_weight(v_ego)\n", + b" return float(step) * TURN_IN_STEP_S * turn_in_weight(v_ego)\n", + "test_turn_in_band_fades_out_by_10mph_and_in_between_1p5_and_2p5"), + _m("turn-in-later-floor-removed", TG, + b" return max(min(L, TURN_IN_MIN_LOOKAHEAD_S), L - shift)\n", + b" return L - shift\n", + "test_turn_in_lookahead_is_bounded"), + _m("turn-in-earlier-above-stock", TG, + b" return min(max(L, float(stock_lookahead_s)), L - shift)\n", + b" return L - shift\n", + "test_turn_in_lookahead_is_bounded"), + _m("turn-in-sample-floor-not-trimmed", TG, + b" self.sample_floor_s = float(min(MIN_STABLE_DELAY, max(TURN_IN_MIN_LOOKAHEAD_S, trim_floor)))\n", + b" pass\n", + "test_turn_in_moves_the_sample_floor_with_the_lookahead"), + _m("turn-in-plan-sampling-floor-restored", TG, + b" t = max(float(action_t), floor, TURN_IN_MIN_LOOKAHEAD_S)\n", + b" t = max(float(action_t), floor, LOW_SPEED_SAMPLE_FLOOR_S)\n", + "test_turn_in_moves_the_sample_floor_with_the_lookahead"), + _m("turn-in-trim-not-slewed", TG, + b" self.trim_s += float(np.clip(shift_target - self.trim_s, -trim_step, trim_step))\n", + b" self.trim_s = shift_target\n", + "test_turn_in_trim_is_slewed_not_stepped"), + _m("turn-in-trim-kept-when-geometry-off", TG, + b" def reset(self) -> None:\n self.trim_s = 0.0\n", + b" def reset(self) -> None:\n", + "test_turn_in_trim_needs_turn_geometry_on"), + _m("turn-in-default-step-one", "common/params_keys.h", + b'{"NAPTurnInDelay", {PERSISTENT, INT, "0"}}', b'{"NAPTurnInDelay", {PERSISTENT, INT, "1"}}', + "test_turn_in_param_defaults_to_zero_int"), + _m("turn-in-modeld-drops-the-step", MODELD, + b"None,\n turn_in_step=turn_in_step)\n", b"None)\n", + "test_turn_in_trim_is_wired_into_modeld_and_the_menu"), + _m("turn-in-modeld-reads-wrong-param", MODELD, + b"clamp_turn_in_step(params.get(PARAM_TURN_IN_DELAY, return_default=True))", + b"clamp_turn_in_step(params.get(PARAM_REF_OFFSET, return_default=True))", + "test_turn_in_trim_is_wired_into_modeld_and_the_menu"), + _m("turn-in-menu-row-not-added", MENU, + b" self._all_items.append(self._turn_in_buttons)\n", b" pass\n", + "test_turn_in_trim_is_wired_into_modeld_and_the_menu"), + _m("turn-in-menu-writes-the-button-index", MENU, + b"int(TURN_IN_DELAY_STEPS[index])", b"int(index)", + "test_turn_in_trim_is_wired_into_modeld_and_the_menu"), +) diff --git a/.github/ci/tesla_preap_mutation_defs_f.py b/.github/ci/tesla_preap_mutation_defs_f.py new file mode 100644 index 00000000000000..4463ad4c3fb9bd --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_f.py @@ -0,0 +1,174 @@ +"""Bosch SensorDirty degrade mutation definitions (see tesla_preap_longitudinal_mutations.py). + +NAPRadarIgnoreSensorDirty (default on) masks the radar's SensorDirty flag only while +live measured tracks exist, tags radarPreferReason, keeps the radar lead, warns through the +existing radarPreferFallback event (never a disable), and escalates to the old soft-disable only when the flag +persists SENSOR_DIRTY_PERSIST_S with no live track. Each entry breaks one rule of that +policy (or of the radarstat line) and must fail the pinned tests with an AssertionError. +""" +from tesla_preap_mutation_common import HistoricalMutation + +T = "selfdrive/controls/tests/test_radar_sensor_dirty.py" +SD = "selfdrive/controls/lib/radar_sensor_dirty.py" +RADARD = "selfdrive/controls/radard.py" +EVENTS = "selfdrive/selfdrived/events.py" +SELFDRIVED = "selfdrive/selfdrived/selfdrived.py" +CARD = "selfdrive/car/card.py" +STAT = "selfdrive/controls/lib/radar_status_log.py" + + +def _m(name, path, original, replacement, *tests): + return HistoricalMutation( + name=name, source_path=path, original=original, replacement=replacement, + test_nodes=tuple(f"{T}::{t}" for t in tests), + ) + + +MUTATIONS_F = ( + # --- policy constants and escalation ------------------------------------------------ + _m("dirty-persist-window-doubled", SD, + b"SENSOR_DIRTY_PERSIST_S = 10.0\n", b"SENSOR_DIRTY_PERSIST_S = 20.0\n", + "test_constants_are_pinned", "test_flag_without_live_tracks_escalates_after_persist_window"), + _m("dirty-persist-window-shortened", SD, + b"SENSOR_DIRTY_PERSIST_S = 10.0\n", b"SENSOR_DIRTY_PERSIST_S = 2.0\n", + "test_constants_are_pinned", "test_live_tracks_keep_the_flag_masked_indefinitely", + "test_flag_without_live_tracks_escalates_after_persist_window"), + _m("dirty-live-recover-zero", SD, + b"SENSOR_DIRTY_LIVE_RECOVER_S = 1.0\n", b"SENSOR_DIRTY_LIVE_RECOVER_S = 0.0\n", + "test_constants_are_pinned", "test_brief_track_blip_does_not_restart_the_no_track_clock"), + _m("dirty-escalation-never", SD, + b" self.escalated = self.no_track_s >= SENSOR_DIRTY_PERSIST_S\n", + b" self.escalated = False\n", + "test_flag_without_live_tracks_escalates_after_persist_window", + "test_radard_escalates_to_the_old_soft_disable_when_flag_persists_without_tracks"), + _m("dirty-degraded-while-escalated", SD, + b" self.degraded = not self.escalated\n", b" self.degraded = True\n", + "test_flag_without_live_tracks_escalates_after_persist_window", + "test_radard_escalates_to_the_old_soft_disable_when_flag_persists_without_tracks"), + _m("dirty-live-tracks-inverted", SD, + b" if live_tracks:\n self._live_s += dt\n", b" if not live_tracks:\n self._live_s += dt\n", + "test_live_tracks_keep_the_flag_masked_indefinitely", "test_tracks_back_restart_the_clock_and_lift_the_escalation"), + _m("dirty-no-track-clock-never-resets", SD, + b" if self._live_s >= SENSOR_DIRTY_LIVE_RECOVER_S:\n self.no_track_s = 0.0\n", + b" if self._live_s >= SENSOR_DIRTY_LIVE_RECOVER_S:\n pass\n", + "test_live_tracks_keep_the_flag_masked_indefinitely", "test_tracks_back_restart_the_clock_and_lift_the_escalation"), + _m("dirty-live-streak-not-broken-by-gap", SD, + b" self._live_s = 0.0\n self.no_track_s += dt\n", b" self.no_track_s += dt\n", + "test_brief_track_blip_does_not_restart_the_no_track_clock"), + _m("dirty-param-off-still-masks", SD, + b" if not ignore or not flag:\n", b" if not flag:\n", + "test_ignore_off_never_masks_and_never_degrades", "test_radard_param_off_keeps_the_old_soft_disable_flag"), + _m("dirty-flag-clear-keeps-state", SD, + b" if not ignore or not flag:\n self.reset()\n return False\n", + b" if not ignore or not flag:\n return False\n", + "test_no_flag_never_masks_and_resets"), + # --- param default -------------------------------------------------------------------- + _m("dirty-param-default-off", SD, + b" if params is None:\n return True\n", b" if params is None:\n return False\n", + "test_param_defaults_on_and_off_means_old_behavior"), + _m("dirty-param-read-error-is-old-behavior", SD, + b" return bool(int(val)) if not isinstance(val, bool) else bool(val)\n except Exception:\n return True\n", + b" return bool(int(val)) if not isinstance(val, bool) else bool(val)\n except Exception:\n return False\n", + "test_param_defaults_on_and_off_means_old_behavior"), + _m("dirty-param-key-renamed", SD, + b'SENSOR_DIRTY_PARAM = "NAPRadarIgnoreSensorDirty"\n', b'SENSOR_DIRTY_PARAM = "NAPRadarIgnoreSensorDirt"\n', + "test_constants_are_pinned"), + # --- reason token --------------------------------------------------------------------- + _m("dirty-reason-token-drops-base", SD, + b' return f"{SENSOR_DIRTY_REASON}+{base}" if base else SENSOR_DIRTY_REASON\n', + b" return SENSOR_DIRTY_REASON\n", + "test_reason_token_and_parse"), + _m("dirty-reason-token-always-added", SD, + b" if not degraded:\n return base\n", b" if False:\n return base\n", + "test_reason_token_and_parse", "test_radard_clean_radar_has_no_sensor_dirty_trace"), + _m("dirty-reason-parse-substring", SD, + b' return SENSOR_DIRTY_REASON in reason.split("+")\n', b" return SENSOR_DIRTY_REASON in reason\n", + "test_reason_token_and_parse"), + _m("dirty-reason-parse-accepts-junk", SD, + b" if not isinstance(reason, str):\n return False\n", b" if not isinstance(reason, str):\n return True\n", + "test_reason_token_and_parse"), + # --- radard --------------------------------------------------------------------------- + _m("dirty-radard-mask-removed", RADARD, + b" if sensor_dirty_mask:\n self.radar_state.radarErrors.radarUnavailableTemporary = False\n", + b" if False:\n self.radar_state.radarErrors.radarUnavailableTemporary = False\n", + "test_radard_masks_sensor_dirty_while_tracks_are_live_and_keeps_the_radar_lead"), + _m("dirty-radard-warning-flag-dropped", RADARD, + b"= bool(self.rain_gate.fallback_alert) or sensor_dirty_mask\n", b"= bool(self.rain_gate.fallback_alert)\n", + "test_radard_masks_sensor_dirty_while_tracks_are_live_and_keeps_the_radar_lead"), + _m("dirty-radard-masks-can-error-too", RADARD, + b" self.radar_state.radarErrors.radarUnavailableTemporary = False\n", + b" self.radar_state.radarErrors.radarUnavailableTemporary = False\n self.radar_state.radarErrors.canError = False\n", + "test_radard_never_masks_other_radar_errors"), + _m("dirty-radard-reliability-sees-raw-flag", RADARD, + b"tracks=self.tracks, errors=self.radar_state.radarErrors, v_ego=self.v_ego,", + b"tracks=self.tracks, errors=rr.errors, v_ego=self.v_ego,", + "test_radard_masks_sensor_dirty_while_tracks_are_live_and_keeps_the_radar_lead"), + _m("dirty-radard-reason-untagged", RADARD, + b"= reason_token(self.reliability.log_reason, sensor_dirty_mask)\n", + b"= str(self.reliability.log_reason)\n", + "test_radard_masks_sensor_dirty_while_tracks_are_live_and_keeps_the_radar_lead", + "test_radard_escalates_to_the_old_soft_disable_when_flag_persists_without_tracks"), + _m("dirty-radard-param-ignored", RADARD, + b" ignore=self.read_sensor_dirty_ignore())\n", b" ignore=True)\n", + "test_radard_param_off_keeps_the_old_soft_disable_flag"), + _m("dirty-radard-default-param-off", RADARD, + b" return sensor_dirty_ignore_enabled(self.rain_gate._get_params())\n", b" return False\n", + "test_radard_default_param_is_read_from_params_and_defaults_on", + "test_radard_masks_sensor_dirty_while_tracks_are_live_and_keeps_the_radar_lead"), + _m("dirty-radard-unmeasured-counts-live", RADARD, + b" self._live_measured = any(rpt[3] for rpt in ar_pts.values())\n", + b" self._live_measured = bool(ar_pts)\n", + "test_radard_unmeasured_tracks_do_not_count_as_live"), + _m("dirty-radard-live-ignores-measured-flag-on-empty", RADARD, + b" sensor_dirty_flag, self._live_measured and not radar_timed_out, DT_MDL,\n", + b" sensor_dirty_flag, True, DT_MDL,\n", + "test_radard_escalates_to_the_old_soft_disable_when_flag_persists_without_tracks", + "test_radard_radar_going_silent_counts_as_no_live_tracks"), + # --- alert / event wiring ------------------------------------------------------------- + _m("dirty-alert-warning-text-old", EVENTS, + b' if _radar_sensor_dirty_active(sm):\n title, sub =', b' if False:\n title, sub =', + "test_alert_text_switches_on_the_sensor_dirty_token"), + _m("dirty-alert-permanent-text-old", EVENTS, + b" if _radar_sensor_dirty_active(sm):\n return NormalPermanentAlert(", + b" if False:\n return NormalPermanentAlert(", + "test_alert_text_switches_on_the_sensor_dirty_token"), + _m("dirty-alert-always-dirty", EVENTS, + b" return sensor_dirty_degraded(getattr(sm['radarState'], 'radarPreferReason', ''))\n", + b" return True\n", + "test_alert_text_switches_on_the_sensor_dirty_token"), + _m("dirty-alert-gains-no-entry", EVENTS, + b" ET.WARNING: radar_prefer_fallback_warning_alert,\n },\n", + b' ET.WARNING: radar_prefer_fallback_warning_alert,\n ET.NO_ENTRY: NoEntryAlert("Radar Sensor Dirty"),\n },\n', + "test_degraded_alert_is_a_warning_not_a_disable_or_no_entry"), + _m("dirty-selfdrived-hard-event-changed", SELFDRIVED, + b" elif self.sm['radarState'].radarErrors.radarUnavailableTemporary:\n self.events.add(EventName.radarTempUnavailable)\n", + b" elif self.sm['radarState'].radarErrors.radarUnavailableTemporary:\n self.events.add(EventName.radarFault)\n", + "test_selfdrived_wiring_is_unchanged_and_degrade_rides_the_fallback_event"), + _m("dirty-param-key-default-off", "common/params_keys.h", + b'{"NAPRadarIgnoreSensorDirty", {PERSISTENT, BOOL, "1"}}', b'{"NAPRadarIgnoreSensorDirty", {PERSISTENT, BOOL}}', + "test_param_key_defaults_on"), + # --- radarstat line ------------------------------------------------------------------- + _m("dirty-statlog-dirty-bit-moved", STAT, b"SGU_DIRTY_BIT = 44\n", b"SGU_DIRTY_BIT = 43\n", + "test_status_log_bit_positions_match_the_ui_decoder", "test_status_log_decodes_the_oct4_sgu_frame"), + _m("dirty-statlog-period-zero", STAT, b"LOG_PERIOD_S = 0.5\n", b"LOG_PERIOD_S = 0.0\n", + "test_status_log_emits_two_hz_with_bits_and_summary"), + _m("dirty-statlog-rate-state-not-kept", STAT, b" self._last_log_t = now\n rec: dict", b" rec: dict", + "test_status_log_emits_two_hz_with_bits_and_summary"), + _m("dirty-statlog-stationary-threshold-wide", STAT, b"STATIONARY_VREL_MS = 1.5\n", b"STATIONARY_VREL_MS = 20.0\n", + "test_status_log_track_summary_counts_the_barrier_signature"), + _m("dirty-statlog-near-lateral-wide", STAT, b"NEAR_LATERAL_Y_M = 3.0\n", b"NEAR_LATERAL_Y_M = 8.0\n", + "test_status_log_track_summary_counts_the_barrier_signature"), + _m("dirty-statlog-near-range-wide", STAT, b"NEAR_LATERAL_D_M = 60.0\n", b"NEAR_LATERAL_D_M = 100.0\n", + "test_status_log_track_summary_counts_the_barrier_signature"), + _m("dirty-statlog-any-bus", STAT, b" return (int(src) & 0x7F) == RADAR_BUS\n", b" return True\n", + "test_status_log_ignores_non_radar_bus_and_never_raises", "test_status_log_emits_two_hz_with_bits_and_summary"), + _m("dirty-statlog-alert-names-swapped", STAT, b'"sensorBlinded", "plantModeActive"', b'"plantModeActive", "sensorBlinded"', + "test_status_log_bit_positions_match_the_ui_decoder", "test_status_log_alert_names_cover_blinded_and_radome_heater"), + _m("dirty-statlog-errors-escape", STAT, b" except Exception:\n return None\n", b" except ZeroDivisionError:\n return None\n", + "test_status_log_ignores_non_radar_bus_and_never_raises"), + _m("dirty-statlog-card-logs-every-car", CARD, + b"self._radar_stat = RadarStatusLogger() if tesla_preap else None", b"self._radar_stat = RadarStatusLogger()", + "test_card_wires_the_status_log_for_preap_only"), + _m("dirty-statlog-card-line-dropped", CARD, b" cloudlog.error(stat_line)\n", b" pass\n", + "test_card_wires_the_status_log_for_preap_only"), +) diff --git a/.github/ci/tesla_preap_mutation_defs_g.py b/.github/ci/tesla_preap_mutation_defs_g.py new file mode 100644 index 00000000000000..5d3a4cd018611d --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_g.py @@ -0,0 +1,122 @@ +"""Firm-brake latch mutation definitions (see tesla_preap_longitudinal_mutations.py). + +The latch keeps the Pre-AP follow guard from re-clipping a firm mid-gap +brake to MILD while the close eases under 1.5 m/s (15a 11:26:49). It sits +outside the guard, may only make the command firmer while the plan is +still firm, never overrides the early kinematic cap, and must expire on a soft plan, a collapsed close, a lost lead, a reset, or +4 s. Each entry breaks one rule and must fail the pinned tests with an +AssertionError. +""" +from tesla_preap_mutation_common import HistoricalMutation + +T = "selfdrive/controls/tests/test_firm_brake_latch.py" +LA = "selfdrive/controls/lib/firm_brake_latch.py" +LC = "selfdrive/controls/lib/longcontrol.py" + + +def _m(name, path, original, replacement, *tests): + return HistoricalMutation( + name=name, source_path=path, original=original, replacement=replacement, + test_nodes=tuple(f"{T}::{t}" for t in tests), + ) + + +MUTATIONS_G = ( + # --- constants ----------------------------------------------------------------- + _m("latch-enter-plan-softer", LA, + b"LEAD_FIRM_LATCH_ENTER_PLAN_MS2 = -0.80\n", b"LEAD_FIRM_LATCH_ENTER_PLAN_MS2 = -0.40\n", + "test_constants_are_pinned", "test_latch_enters_on_a_firm_plan_and_a_firm_close"), + _m("latch-hold-plan-softer", LA, + b"LEAD_FIRM_LATCH_HOLD_PLAN_MS2 = -0.50\n", b"LEAD_FIRM_LATCH_HOLD_PLAN_MS2 = -0.10\n", + "test_constants_are_pinned", "test_latch_releases_when_the_plan_goes_soft", + "test_hold_pass_changes_nothing_when_the_plan_is_not_firm"), + _m("latch-hold-close-zero", LA, + b"LEAD_FIRM_LATCH_HOLD_CLOSE_MS = 0.80\n", b"LEAD_FIRM_LATCH_HOLD_CLOSE_MS = 0.0\n", + "test_constants_are_pinned", "test_latch_releases_when_the_close_collapses"), + _m("latch-max-ten-times-longer", LA, + b"LEAD_FIRM_LATCH_MAX_S = 4.0\n", b"LEAD_FIRM_LATCH_MAX_S = 40.0\n", + "test_constants_are_pinned", "test_latch_expires_after_four_seconds"), + _m("latch-enter-close-lowered", LA, + b"LEAD_FIRM_LATCH_ENTER_CLOSE_MS = LEAD_APPROACH_SOFT_LIMIT_CLOSE_MS\n", + b"LEAD_FIRM_LATCH_ENTER_CLOSE_MS = 0.5\n", + "test_constants_are_pinned", "test_hit_needs_a_firm_close_in_the_mid_gap_band"), + # --- latch state machine ------------------------------------------------------- + _m("latch-never-expires-by-age", LA, + b" if (self.age > LEAD_FIRM_LATCH_MAX_S\n or p >", + b" if (False\n or p >", + "test_latch_expires_after_four_seconds", "test_longcontrol_latch_is_never_softer_than_legacy_and_expires"), + _m("latch-age-never-advances", LA, + b" self.age += float(dt)\n", b" pass\n", + "test_latch_expires_after_four_seconds"), + _m("latch-ignores-soft-plan", LA, + b" or p > LEAD_FIRM_LATCH_HOLD_PLAN_MS2\n", b" or False\n", + "test_latch_releases_when_the_plan_goes_soft", "test_longcontrol_mild_and_settle_plans_are_bit_identical_to_legacy"), + _m("latch-ignores-collapsed-close", LA, + b" or v < LEAD_FIRM_LATCH_HOLD_CLOSE_MS):\n", b" or False):\n", + "test_latch_releases_when_the_close_collapses", "test_longcontrol_latch_is_never_softer_than_legacy_and_expires"), + _m("latch-enters-without-a-hit", LA, + b" if not self.on and hit and p <= LEAD_FIRM_LATCH_ENTER_PLAN_MS2:\n", + b" if not self.on and p <= LEAD_FIRM_LATCH_ENTER_PLAN_MS2:\n", + "test_latch_enters_on_a_firm_plan_and_a_firm_close", "test_latch_releases_when_the_plan_goes_soft"), + _m("latch-enters-on-soft-plan", LA, + b" if not self.on and hit and p <= LEAD_FIRM_LATCH_ENTER_PLAN_MS2:\n", + b" if not self.on and hit:\n", + "test_latch_enters_on_a_firm_plan_and_a_firm_close", + "test_longcontrol_mild_and_settle_plans_are_bit_identical_to_legacy"), + _m("latch-survives-lost-lead", LA, + b" self.reset()\n return False\n p = float(planner_a)\n", + b" return False\n p = float(planner_a)\n", + "test_latch_resets_when_the_lead_or_plan_is_missing", "test_longcontrol_drops_the_latch_with_the_lead_and_on_reset"), + # --- latch seam ------------------------------------------------------------------ + _m("apply-ignores-hold", LA, + b" if not hold or guarded_a is None or raw_a is None or planner_a is None:\n", + b" if guarded_a is None or raw_a is None or planner_a is None:\n", + "test_hold_pass_is_never_softer_than_the_unlatched_guard", "test_latch_seam_ignores_missing_inputs_and_soft_plans"), + _m("apply-has-no-effect", LA, + b" return min(float(guarded_a), float(raw_a))\n", b" return guarded_a\n", + "test_hold_pass_lets_the_firm_plan_reach_the_plant_below_the_close_gate", + "test_longcontrol_removes_the_1p5_to_mild_to_1p5_cliff"), + _m("apply-takes-the-softer-command", LA, + b" return min(float(guarded_a), float(raw_a))\n", b" return max(float(guarded_a), float(raw_a))\n", + "test_hold_pass_lets_the_firm_plan_reach_the_plant_below_the_close_gate", + "test_longcontrol_removes_the_1p5_to_mild_to_1p5_cliff"), + _m("apply-ungated-by-plan", LA, + b" if float(planner_a) > LEAD_FIRM_LATCH_HOLD_PLAN_MS2:\n return guarded_a\n", b"", + "test_hold_pass_changes_nothing_when_the_plan_is_not_firm", "test_latch_seam_ignores_missing_inputs_and_soft_plans"), + _m("apply-overrides-early-kinematic-cap", LA, + (b" if (v_rel is not None and not lead_approach_is_rapid(float(v_rel))\n" + + b" and lead_firm_large_slack_a(v_rel, slack, a_lead) is not None):\n return guarded_a\n"), b"", + "test_early_kinematic_cap_keeps_ownership_of_its_frame"), + # --- hit helper -------------------------------------------------------------------- + _m("hit-ignores-mid-gap-band", LA, + b" if not lead_mid_gap_map_band(slack, d_rel):\n return False\n return lead_firm_alead(", + b" return lead_firm_alead(", + "test_hit_needs_a_firm_close_in_the_mid_gap_band"), + _m("hit-ignores-near-bumper", LA, + (b" if d_rel is not None and float(d_rel) <= LEAD_MPC_SOFT_NEAR_M:\n return False\n" + + b" if not lead_mid_gap_map_band(slack, d_rel):\n return False\n return lead_firm_alead("), + b" if not lead_mid_gap_map_band(slack, d_rel):\n return False\n return lead_firm_alead(", + "test_hit_needs_a_firm_close_in_the_mid_gap_band"), + _m("hit-accepts-any-close", LA, + b" return lead_firm_alead(a_lead) or lead_rising_or_residual_brake(\n v, prev_v_rel, a_ego, dt,\n )\n\n\nclass FirmBrakeLatch", + b" return True\n\n\nclass FirmBrakeLatch", + "test_hit_needs_a_firm_close_in_the_mid_gap_band", "test_hit_accepts_the_222_residual_brake_without_a_firm_alead"), + _m("hit-drops-222-residual", LA, + b" return lead_firm_alead(a_lead) or lead_rising_or_residual_brake(\n v, prev_v_rel, a_ego, dt,\n )\n\n\nclass FirmBrakeLatch", + b" return lead_firm_alead(a_lead)\n\n\nclass FirmBrakeLatch", + "test_hit_accepts_the_222_residual_brake_without_a_firm_alead"), + # --- LongControl wiring -------------------------------------------------------------- + _m("longcontrol-never-applies-latch", LC, + b" guarded_accel, raw_accel, a_target, hold_pass,\n", b" guarded_accel, raw_accel, a_target, False,\n", + "test_longcontrol_removes_the_1p5_to_mild_to_1p5_cliff", "test_longcontrol_wires_the_latch_into_the_guard"), + _m("longcontrol-latch-restores-the-guarded-value", LC, + b" guarded_accel, raw_accel, a_target, hold_pass,\n", b" guarded_accel, guarded_accel, a_target, hold_pass,\n", + "test_longcontrol_removes_the_1p5_to_mild_to_1p5_cliff"), + _m("longcontrol-latch-clock-wrong", LC, + b" DT_CTRL,\n )\n raw_accel = self.last_output_accel\n", + b" 0.05,\n )\n raw_accel = self.last_output_accel\n", + "test_longcontrol_removes_the_1p5_to_mild_to_1p5_cliff", "test_longcontrol_wires_the_latch_into_the_guard"), + _m("longcontrol-reset-keeps-latch", LC, + b" self._lead_residual.reset()\n self._firm_latch.reset()\n", b" self._lead_residual.reset()\n", + "test_longcontrol_drops_the_latch_with_the_lead_and_on_reset"), +) diff --git a/.github/ci/tesla_preap_mutation_defs_h.py b/.github/ci/tesla_preap_mutation_defs_h.py new file mode 100644 index 00000000000000..fe432ba3b8f1be --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_h.py @@ -0,0 +1,61 @@ +"""Regen-limit prompt command-pin mutation definitions (see tesla_preap_longitudinal_mutations.py). + +The Pre-AP "regen limit, add brake" prompt triggers on the unclamped plan. With +the post-guard actuator command available it must also be pinned at the +envelope floor, an unknown command keeps the plan-only rule, and an active +prompt is kept by the plan alone. Each entry breaks one rule and must fail the +pinned tests with an AssertionError. +""" +from tesla_preap_mutation_common import HistoricalMutation + +T = "selfdrive/selfdrived/tests/test_preap_regen_cmd_pin.py" +PR = "selfdrive/selfdrived/preap_regen.py" +SD = "selfdrive/selfdrived/selfdrived.py" + + +def _m(name, path, original, replacement, *tests): + return HistoricalMutation( + name=name, source_path=path, original=original, replacement=replacement, + test_nodes=tuple(f"{T}::{t}" for t in tests), + ) + + +MUTATIONS_H = ( + _m("regen-pin-margin-widened", PR, + b"REGEN_DEMAND_CMD_PIN_MARGIN = 0.05 #", b"REGEN_DEMAND_CMD_PIN_MARGIN = 1.5 #", + "test_constants_are_pinned", "test_phantom_prompt_is_gone_when_the_command_is_not_at_the_rail", + "test_command_just_inside_the_pin_margin_prompts_just_outside_does_not"), + _m("regen-pin-margin-zero", PR, + b"REGEN_DEMAND_CMD_PIN_MARGIN = 0.05 #", b"REGEN_DEMAND_CMD_PIN_MARGIN = 0.0 #", + "test_constants_are_pinned", "test_command_just_inside_the_pin_margin_prompts_just_outside_does_not"), + _m("regen-pin-ignored", PR, + b" and cmd_pinned\n", b"", + "test_phantom_prompt_is_gone_when_the_command_is_not_at_the_rail", + "test_a_command_off_the_rail_cannot_build_evidence_between_pinned_frames", + "test_never_more_prompts_than_the_plan_only_rule"), + _m("regen-pin-inverted", PR, + b" or a_cmd <= accel_floor + REGEN_DEMAND_CMD_PIN_MARGIN\n", + b" or a_cmd >= accel_floor + REGEN_DEMAND_CMD_PIN_MARGIN\n", + "test_phantom_prompt_is_gone_when_the_command_is_not_at_the_rail", + "test_real_overflow_still_prompts_when_the_command_is_pinned"), + _m("regen-unknown-command-suppresses", PR, + b" a_cmd is None or not math.isfinite(a_cmd)\n or a_cmd <=", + b" a_cmd is not None and math.isfinite(a_cmd)\n and a_cmd <=", + "test_unknown_command_is_the_plan_only_rule"), + _m("regen-nonfinite-command-suppresses", PR, + b" a_cmd is None or not math.isfinite(a_cmd)\n or a_cmd <=", + b" a_cmd is None\n or a_cmd <=", + "test_unknown_command_is_the_plan_only_rule"), + _m("regen-keep-prompting-needs-the-command", PR, + b" and a_target <= accel_floor - REGEN_DEMAND_CLEAR_MARGIN\n", + (b" and a_target <= accel_floor - REGEN_DEMAND_CLEAR_MARGIN\n" + + b" and (a_cmd is None or a_cmd <= accel_floor + REGEN_DEMAND_CMD_PIN_MARGIN)\n"), + "test_active_prompt_keeps_going_on_the_plan_alone"), + _m("regen-selfdrived-drops-the-command", SD, + b" a_cmd=float(self.sm['carControl'].actuators.accel),\n", b"", + "test_selfdrived_passes_the_guarded_command"), + _m("regen-selfdrived-passes-the-plan-as-command", SD, + b" a_cmd=float(self.sm['carControl'].actuators.accel),\n", + b" a_cmd=float(self.sm['longitudinalPlan'].aTarget),\n", + "test_selfdrived_passes_the_guarded_command"), +) diff --git a/.github/ci/tesla_preap_mutation_defs_i.py b/.github/ci/tesla_preap_mutation_defs_i.py new file mode 100644 index 00000000000000..c7bff4d35acf51 --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_i.py @@ -0,0 +1,86 @@ +"""Far-gap kinematic gate widening mutation definitions (see tesla_preap_longitudinal_mutations.py). + +The unified lead controller widens its kinematic gate at a far gap while the PD +term accelerates and the kinematic bound is not a real brake. It must stay +inert for slack under 15 m, a real bound, or a non-accelerating PD, never be +firmer than the old gate, be capped, and be continuous. Each entry breaks one +rule and must fail the pinned tests with an AssertionError. +""" +from tesla_preap_mutation_common import HistoricalMutation + +T = "selfdrive/controls/tests/test_unified_far_gap_gate.py" +UL = "selfdrive/controls/lib/unified_lead.py" + +_BIT = "test_bit_identical_to_the_old_gate_inside_the_far_gap_line" +_FIRM = "test_never_firmer_and_unchanged_where_the_old_command_braked" +_ZERO = "test_widen_is_zero_unless_all_three_conditions_hold" +_CONST = "test_constants_are_pinned" +_E2 = "test_far_gap_slow_close_keeps_the_pd_accel_through_the_old_gate_edge" +_CONT = "test_widen_is_continuous_in_slack_bound_and_pd" + + +def _m(name, original, replacement, *tests): + return HistoricalMutation( + name=name, source_path=UL, original=original, replacement=replacement, + test_nodes=tuple(f"{T}::{t}" for t in tests), + ) + + +MUTATIONS_I = ( + _m("gate-widen-slack-line-lowered", + b"KIN_GATE_WIDEN_SLACK_LO_M = 15.0\n", b"KIN_GATE_WIDEN_SLACK_LO_M = 5.0\n", + _CONST, _BIT, _ZERO), + _m("gate-widen-slack-ramp-hardened", + b"KIN_GATE_WIDEN_SLACK_RAMP_M = 5.0\n", b"KIN_GATE_WIDEN_SLACK_RAMP_M = 0.01\n", + _CONST, _CONT), + _m("gate-widen-real-bound-threshold-lowered", + b"KIN_GATE_WIDEN_A_BOUND_LO = -0.10\n", b"KIN_GATE_WIDEN_A_BOUND_LO = -0.60\n", + _CONST, _FIRM, _ZERO), + _m("gate-widen-bound-ramp-hardened", + b"KIN_GATE_WIDEN_A_BOUND_RAMP = 0.10\n", b"KIN_GATE_WIDEN_A_BOUND_RAMP = 0.001\n", + _CONST, _CONT), + _m("gate-widen-pd-cap-raised", + b"KIN_GATE_WIDEN_A_CAP = 0.50\n", b"KIN_GATE_WIDEN_A_CAP = 2.0\n", + _CONST, "test_widen_full_weight_and_cap", _FIRM), + _m("gate-widen-gain-halved", + b"KIN_GATE_WIDEN_K = 1.0 #", b"KIN_GATE_WIDEN_K = 0.5 #", + _CONST, "test_widen_full_weight_and_cap"), + _m("gate-widen-ignores-slack", + b" return wide * w_slack * w_bound\n", b" return wide * w_bound\n", + _BIT, _ZERO), + _m("gate-widen-ignores-real-bound", + b" return wide * w_slack * w_bound\n", b" return wide * w_slack\n", + _FIRM, _ZERO), + _m("gate-widen-without-pd-headroom", + b" wide = min(a_pd, KIN_GATE_WIDEN_A_CAP) / KIN_GATE_WIDEN_K - KIN_GATE_MS\n", + b" wide = min(a_pd, KIN_GATE_WIDEN_A_CAP) / KIN_GATE_WIDEN_K\n", + _ZERO, _BIT, _FIRM), + _m("gate-widen-pd-uncapped", + b" wide = min(a_pd, KIN_GATE_WIDEN_A_CAP) / KIN_GATE_WIDEN_K - KIN_GATE_MS\n", + b" wide = a_pd / KIN_GATE_WIDEN_K - KIN_GATE_MS\n", + "test_widen_full_weight_and_cap"), + _m("gate-widen-bound-step-not-smooth", + b" w_bound = _smooth01((a_bound - KIN_GATE_WIDEN_A_BOUND_LO) / KIN_GATE_WIDEN_A_BOUND_RAMP)\n", + b" w_bound = float(a_bound > KIN_GATE_WIDEN_A_BOUND_LO)\n", + _CONT), + _m("gate-widen-slack-step-not-smooth", + b" w_slack = _smooth01((slack - KIN_GATE_WIDEN_SLACK_LO_M) / KIN_GATE_WIDEN_SLACK_RAMP_M)\n", + b" w_slack = float(slack > KIN_GATE_WIDEN_SLACK_LO_M)\n", + _CONT), + _m("gate-widen-narrows-instead", + b" gate_w = KIN_GATE_MS + _kin_gate_widen(slack, a_pd, a_bound)\n", + b" gate_w = KIN_GATE_MS - _kin_gate_widen(slack, a_pd, a_bound)\n", + _FIRM, _E2, "test_close_sweep_has_a_smaller_step_than_the_old_gate"), + _m("gate-widen-not-wired", + b" gate_w = KIN_GATE_MS + _kin_gate_widen(slack, a_pd, a_bound)\n", + b" gate_w = KIN_GATE_MS\n", + _E2, "test_close_sweep_has_a_smaller_step_than_the_old_gate", _FIRM), + _m("gate-widen-wired-with-swapped-args", + b" gate_w = KIN_GATE_MS + _kin_gate_widen(slack, a_pd, a_bound)\n", + b" gate_w = KIN_GATE_MS + _kin_gate_widen(slack, a_bound, a_pd)\n", + _E2, _FIRM), + _m("gate-widen-wired-with-gap-not-slack", + b" gate_w = KIN_GATE_MS + _kin_gate_widen(slack, a_pd, a_bound)\n", + b" gate_w = KIN_GATE_MS + _kin_gate_widen(gap_f, a_pd, a_bound)\n", + _BIT, "test_inside_the_follow_gap_and_real_closes_match_the_old_command"), +) diff --git a/.github/ci/tesla_preap_mutation_defs_j.py b/.github/ci/tesla_preap_mutation_defs_j.py new file mode 100644 index 00000000000000..b075289159ca6f --- /dev/null +++ b/.github/ci/tesla_preap_mutation_defs_j.py @@ -0,0 +1,50 @@ +"""Far-gap soft closing-speed mutation definitions. + +The catch-up blend fades k_g·slack from 15 → 50 m and replaces it with a soft +desired closing speed, and only while the classic PD term is a catch-up and +the kinematic bound is not a real brake. Each entry breaks one of those guards +and must fail the pinned tests with an AssertionError. +""" +from tesla_preap_mutation_common import HistoricalMutation + +T = "selfdrive/controls/tests/test_unified_far_gap_catchup.py" +UL = "selfdrive/controls/lib/unified_lead.py" + +_BIT = "test_bit_identical_for_slack_at_or_under_15m" +_SLACK = "test_slack_weight_keeps_the_near_gap_term" +_ACCEL = "test_accel_weight_keeps_a_braking_pd_term" +_BOUND = "test_bound_weight_keeps_the_gap_term_on_a_real_brake" +_BRAKE = "test_braking_lead_at_a_far_gap_keeps_the_classic_command" +_SOFT = "test_matched_far_command_is_a_soft_ease" +_CLIP = "test_closing_faster_than_desired_adds_no_gap_brake" +_PROP = "test_never_firmer_on_catchup_and_never_deeper_when_classic_brakes" + + +def _m(name, original, replacement, *tests): + return HistoricalMutation( + name=name, source_path=UL, original=original, replacement=replacement, + test_nodes=tuple(f"{T}::{t}" for t in tests), + ) + + +_W = b" w = w_slack * w_accel * w_bound\n" + + +MUTATIONS_J = ( + _m("catchup-drops-slack-weight", + _W, b" w = w_accel * w_bound\n", + _SLACK, _BIT, _PROP), + _m("catchup-drops-accel-weight", + _W, b" w = w_slack * w_bound\n", + _ACCEL, _PROP), + _m("catchup-drops-bound-weight", + _W, b" w = w_slack * w_accel\n", + _BOUND, _BRAKE, _PROP), + _m("catchup-gain-raised-fivefold", + b"K_CATCH = 0.14", b"K_CATCH = 1.00", + _SOFT), + _m("catchup-negative-soft-term-not-clipped", + b" a_gap = (1.0 - w) * a_gap_classic + w * max(0.0, a_soft)\n", + b" a_gap = (1.0 - w) * a_gap_classic + w * a_soft\n", + _CLIP), +) diff --git a/.github/ci/tesla_preap_roundabout_mutations.py b/.github/ci/tesla_preap_roundabout_mutations.py new file mode 100644 index 00000000000000..4b9672471ac830 --- /dev/null +++ b/.github/ci/tesla_preap_roundabout_mutations.py @@ -0,0 +1,1130 @@ +"""Roundabout map + Roundabout Steering Assist mutations for the Tesla Pre-AP gate. + +Kept separate from tesla_preap_longitudinal_mutations.py (which stays the parent list). +Reuses that file's HistoricalMutation / apply / pytest / JUnit helpers so a mutation is +KILLED only by assertion failures, sources are restored byte-identically, and any survivor +or invalid run fails the job. +""" +import importlib.util +import sys +import tempfile +from pathlib import Path + + +_PARENT_PATH = Path(__file__).resolve().parent / "tesla_preap_longitudinal_mutations.py" +_spec = importlib.util.spec_from_file_location("tesla_preap_longitudinal_mutations", _PARENT_PATH) +assert _spec is not None and _spec.loader is not None +parent = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = parent +_spec.loader.exec_module(parent) + +HistoricalMutation = parent.HistoricalMutation +RB_GUIDE_TEST_PATH = "selfdrive/controls/lib/tests/test_roundabout_guide.py" +RB_MAP_TEST_PATH = "selfdrive/mapd/tests/test_roundabout_map.py" +RB_HOLD_TEST_PATH = "selfdrive/controls/lib/tests/test_roundabout_ring_hold.py" +RB_MAPD_TEST_PATH = "selfdrive/mapd/tests/test_roundabout.py" +RH_PATH = "selfdrive/controls/lib/roundabout_ring_hold.py" +RG_PATH = "selfdrive/controls/lib/roundabout_guide.py" +EXPECTED_COUNT = 110 + + +MUTATIONS = ( + HistoricalMutation( + name="rb-guide-early-left-before-turn-distance", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' k_raw = max(model_k, k_pp) # hold / add right only; never an early left\n', + replacement=b' k_raw = k_pp\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_right_entry_held_until_turn_distance", + ), + ), + HistoricalMutation( + name="rb-guide-correction-not-slewed", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' self.dk_out += min(max(dk - self.dk_out, -oslew * dt), oslew * dt)\n', + replacement=b' self.dk_out = dk\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_left_transition_within_jerk_limit", + ), + ), + HistoricalMutation( + name="rb-guide-output-exceeds-jerk-limit", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' allowed = max(oslew * dt, abs(model_k - self.prev_model))\n', + replacement=b' allowed = 1.0\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_left_transition_within_jerk_limit", + ), + ), + HistoricalMutation( + name="rb-guide-no-preview", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' px, py, ppsi = _arc_ahead(x, y, psi, v, yaw_rate, PREVIEW_S)\n', + replacement=b' px, py, ppsi = x, y, psi\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_follow_keeps_the_passes_in_the_ring_band", + ), + ), + HistoricalMutation( + name="rb-guide-circle-follow-wrong-sign", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' return -sense * k_center\n', + replacement=b' return sense * k_center\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_circle_follow_sign_convention", + ), + ), + HistoricalMutation( + name="rb-guide-no-map-bias", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' bn += BIAS_GAIN * (ex - bn)\n', + replacement=b' bn += 0.0\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_map_match_bias_removes_gnss_offset_beyond_a_lane", + ), + ), + HistoricalMutation( + name="rb-guide-ignores-fix-age", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' c_fix = _interp(t - self.last_fix_t, (FIX_FRESH_S, FIX_STALE_S), (1.0, 0.0))\n', + replacement=b' c_fix = 1.0\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_pose_error_lowers_confidence_and_fades", + ), + ), + HistoricalMutation( + name="rb-guide-ignores-camera-edges", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' dy = max(dy, min(0.0, allowed))\n', + replacement=b' dy = dy\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_edge_limit_keeps_camera_authority", + ), + ), + HistoricalMutation( + name="rb-guide-never-hands-back", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' if self.phase == EXITING and self.phase_w <= 0.0 and abs(self.dk_out) < HANDOFF_DK:\n', + replacement=b' if False:\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_hands_back_to_model_after_exit", + ), + ), + HistoricalMutation( + name="rb-assist-ignores-toggle", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' on = bool(self.params.get_bool(PARAM_ROUNDABOUT_ASSIST))\n', + replacement=b' on = True\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_identity_when_off_or_not_preap", + ), + ), + HistoricalMutation( + name="rb-assist-not-preap-only", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' if not self.preap:\n return float(model_k)\n', + replacement=b' if False:\n return float(model_k)\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_identity_when_off_or_not_preap", + ), + ), + HistoricalMutation( + name="rb-assist-runs-during-maneuver", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' if maneuver_active or lane_change_active:\n on = False\n', + replacement=b' if False:\n on = False\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_identity_when_driver_has_wheel_or_maneuver", + ), + ), + HistoricalMutation( + name="rb-assist-without-hint", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' on = (t - self._last_hint_t) <= HINT_HOLD_S or busy\n', + replacement=b' on = True\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_stale_ring_does_not_engage", + ), + ), + HistoricalMutation( + name="rb-controlsd-legacy-bias-stacks-on-assist", + source_path="selfdrive/controls/controlsd.py", + original=b'(0.0 if self.rb_assist.active else rb_bias)', + replacement=b'rb_bias', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_controlsd_applies_assist_before_legacy_bias_and_pins_nothing_else", + ), + ), + HistoricalMutation( + name="rb-assist-default-on", + source_path="common/params_keys.h", + original=b'{"NAPRoundaboutAssist", {PERSISTENT, BOOL, "0"}}', + replacement=b'{"NAPRoundaboutAssist", {PERSISTENT, BOOL, "1"}}', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_params_and_menu_wiring", + ), + ), + HistoricalMutation( + name="rb-guide-nan-odometry-poisons-pose", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' if not (math.isfinite(t) and math.isfinite(v) and math.isfinite(yaw_rate)):\n', + replacement=b' if False:\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_nan_odometry_sample_does_not_poison_the_pose", + ), + ), + HistoricalMutation( + name="rb-map-ring-geometry-searches-around-car", + source_path="selfdrive/mapd/osm_db.py", + original=b' lat, lon = 0.5 * (box[0] + box[1]), 0.5 * (box[2] + box[3])\n', + replacement=b' lat, lon = float(lat), float(lon)\n', + test_nodes=( + f"{RB_MAP_TEST_PATH}::test_v4_pack_ring_geometry_from_first_hint_distance", + ), + ), + HistoricalMutation( + name="rb-map-find-roundabout-skips-rb-ways", + source_path="selfdrive/mapd/osm_db.py", + original=b' rows += [r for r in self._rb_candidates(float(lat), float(lon), RB_SEARCH_PAD_DEG, role=ROLE_RING)\n', + replacement=b' rows += [r for r in []\n', + test_nodes=( + f"{RB_MAP_TEST_PATH}::test_v4_pack_find_roundabout_sees_untagged_speed_ring", + ), + ), + HistoricalMutation( + name="rb-map-overpass-drops-rings", + source_path="selfdrive/mapd/overpass.py", + original=b' rb_union = "" if not include_roundabouts else "\\n .rb;\\n .ap;"\n', + replacement=b' rb_union = ""\n', + test_nodes=( + f"{RB_MAP_TEST_PATH}::test_overpass_queries_include_rings_and_approaches", + ), + ), + HistoricalMutation( + name="rb-map-refresh-drops-rb-rows", + source_path="selfdrive/mapd/local_refresh.py", + original=b' for row in rb_rows:\n OsmSpeedLimitDB.insert_rb_way(con, row)\n', + replacement=b' for row in []:\n OsmSpeedLimitDB.insert_rb_way(con, row)\n', + test_nodes=( + f"{RB_MAP_TEST_PATH}::test_refresh_merge_replaces_rb_rows_in_bbox", + ), + ), + HistoricalMutation( + name="rb-map-approach-direction-lost", + source_path="selfdrive/mapd/roundabout_map.py", + original=b' fwd = list(reversed(trimmed)) if inbound else trimmed\n', + replacement=b' fwd = trimmed\n', + test_nodes=( + f"{RB_MAP_TEST_PATH}::test_approaches_are_stored_in_travel_direction", + ), + ), + HistoricalMutation( + name="rb-map-comfort-speed-outer-lane", + source_path="selfdrive/mapd/roundabout_map.py", + original=b' r_inner = max(4.0, float(radius_m) - 0.5 * (lanes_n - 1) * LANE_WIDTH_M)\n', + replacement=b' r_inner = max(4.0, float(radius_m) + 0.5 * (lanes_n - 1) * LANE_WIDTH_M)\n', + test_nodes=( + f"{RB_MAP_TEST_PATH}::test_comfort_speed_soco_about_15_mph", + ), + ), + HistoricalMutation( + name="rb-map-builder-skips-roundabouts", + source_path="scripts/nap/build_osm_speed_limits.py", + original=b' rb_rows = rb_rows_from_overpass(payload)\n', + replacement=b' rb_rows = []\n', + test_nodes=( + f"{RB_MAP_TEST_PATH}::test_builder_from_json_writes_pack_v4", + ), + ), +) + + +CARD = "selfdrive/car/card.py" +MAPD = "selfdrive/mapd/mapd.py" +RMAP = "selfdrive/mapd/roundabout_status.py" +T = RB_MAP_TEST_PATH + +MUTATIONS += ( + HistoricalMutation( + name="rb-card-ring-limit-needs-speed-match", + source_path=CARD, + original=b" if rb_hint is not None:\n posted_ms =", + replacement=b" if rb_hint is not None and map_valid and md is not None:\n posted_ms =", + test_nodes=( + f"{T}::test_card_ring_hint_drops_hud_max_without_speed_match", + f"{T}::test_card_ring_hint_same_max_with_or_without_speed_match", + ), + ), + HistoricalMutation( + name="rb-card-ring-hint-ignores-message-validity", + source_path=CARD, + original=b" rb_md = self.sm['liveMapDataNAP'] if self.sm.valid.get('liveMapDataNAP', False) else None\n", + replacement=b" rb_md = self.sm['liveMapDataNAP']\n", + test_nodes=( + f"{T}::test_card_ring_hint_needs_a_valid_map_message", + ), + ), + HistoricalMutation( + name="rb-card-ring-limit-read-from-speed-match-only", + source_path=CARD, + original=b" rb_hint = live_map_roundabout_hint(rb_md)\n", + replacement=b" rb_hint = live_map_roundabout_hint(md)\n", + test_nodes=( + f"{T}::test_card_ring_hint_drops_hud_max_without_speed_match", + ), + ), + HistoricalMutation( + name="rb-card-ring-slowdown-gated-on-assist-toggle", + source_path=CARD, + original=b" rb_hint = live_map_roundabout_hint(rb_md)\n", + replacement=b" rb_hint = live_map_roundabout_hint(rb_md) if Params().get_bool('NAPRoundaboutAssist') else None\n", + test_nodes=( + f"{T}::test_card_and_mapd_never_read_the_assist_toggle", + ), + ), + HistoricalMutation( + name="rb-mapd-ring-hint-leaves-message-invalid", + source_path=MAPD, + original=b"matched=match is not None, ring_hint=True)", + replacement=b"matched=match is not None, ring_hint=False)", + test_nodes=( + f"{T}::test_mapd_ring_hint_keeps_message_valid_without_speed_match", + ), + ), + HistoricalMutation( + name="rb-mapd-valid-without-speed-match-off-ring", + source_path=MAPD, + original=b"matched=match is not None, ring_hint=False)", + replacement=b"matched=match is not None, ring_hint=True)", + test_nodes=( + f"{T}::test_mapd_ring_hint_keeps_message_valid_without_speed_match", + ), + ), + HistoricalMutation( + name="rb-map-valid-ignores-ring-hint", + source_path=RMAP, + original=b" return bool(gps_ok and db_loaded and (matched or ring_hint))\n", + replacement=b" return bool(gps_ok and db_loaded and matched)\n", + test_nodes=( + f"{T}::test_map_msg_valid_only_changes_with_a_ring_hint", + ), + ), + HistoricalMutation( + name="rb-map-valid-ring-hint-skips-gps-check", + source_path=RMAP, + original=b" return bool(gps_ok and db_loaded and (matched or ring_hint))\n", + replacement=b" return bool(db_loaded and (matched or ring_hint))\n", + test_nodes=( + f"{T}::test_map_msg_valid_only_changes_with_a_ring_hint", + ), + ), + HistoricalMutation( + name="rb-map-ring-count-v3-pack-reads-as-none", + source_path=RMAP, + original=b" if row is None:\n return 0\n", + replacement=b" if row is None:\n return None\n", + test_nodes=( + f"{T}::test_pack_ring_count_and_summary", + ), + ), + HistoricalMutation( + name="rb-map-ring-count-counts-approach-rows", + source_path=RMAP, + original=b'"SELECT COUNT(*) FROM rb_ways WHERE role = ?", (ROLE_RING,)', + replacement=b'"SELECT COUNT(*) FROM rb_ways WHERE role != ?", ("",)', + test_nodes=( + f"{T}::test_pack_ring_count_and_summary", + ), + ), + HistoricalMutation( + name="rb-map-ring-summary-zero-rings-not-flagged", + source_path=RMAP, + original=b" if count <= 0:\n return RING_MISSING_TEXT\n", + replacement=b" if count < 0:\n return RING_MISSING_TEXT\n", + test_nodes=( + f"{T}::test_pack_ring_count_and_summary", + ), + ), + HistoricalMutation( + name="rb-map-ring-watch-logs-every-check", + source_path=RMAP, + original=b" if key == self._key:\n return None\n", + replacement=b" if key is None:\n return None\n", + test_nodes=( + f"{T}::test_ring_data_watch_logs_once_per_pack_state", + ), + ), + HistoricalMutation( + name="rb-mapd-never-logs-missing-ring-rows", + source_path=MAPD, + original=b" getattr(cloudlog, note[0])(note[1])\n", + replacement=b" pass\n", + test_nodes=( + f"{T}::test_mapd_logs_missing_ring_rows_once", + ), + ), + HistoricalMutation( + name="rb-map-ring-summary-ignores-path", + source_path=RMAP, + original=b"pack_ring_count(path or default_db_path())", + replacement=b"pack_ring_count(default_db_path())", + test_nodes=( + f"{T}::test_pack_ring_count_and_summary", + ), + ), + HistoricalMutation( + name="rb-guide-gps-latency-back-to-0-9", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b'GPS_LATENCY_S = 0.66 ', + replacement=b'GPS_LATENCY_S = 0.9 ', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_gps_latency_is_the_measured_one", + f"{RB_GUIDE_TEST_PATH}::test_sep29_left_curl_no_longer_doubles_the_model", + ), + ), + HistoricalMutation( + name="rb-guide-left-transition-a-lat-3-0", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b'A_LAT_CIRC_MAX = 2.2 ', + replacement=b'A_LAT_CIRC_MAX = 3.0 ', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_left_transition_cap_uses_actual_speed", + ), + ), + HistoricalMutation( + name="rb-guide-output-slew-back-to-0-07", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b'OUT_SLEW = 0.035 ', + replacement=b'OUT_SLEW = 0.07 ', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_slews_are_0_035_for_a_poor_pose", + f"{RB_GUIDE_TEST_PATH}::test_poor_pose_uses_the_slow_slews", + ), + ), + HistoricalMutation( + name="rb-guide-bearing-accuracy-never-unreliable", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' unreliable = bearing_acc_deg > BEARING_ACC_UNRELIABLE_DEG or \\\n', + replacement=b' unreliable = False or \\\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_pose_quality_thresholds", + f"{RB_GUIDE_TEST_PATH}::test_unreliable_or_unsettled_pose_does_not_latch", + ), + ), + HistoricalMutation( + name="rb-guide-large-bias-never-unreliable", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' (bias_m > BIAS_UNRELIABLE_M and bearing_acc_deg > BEARING_ACC_POOR_DEG)\n', + replacement=b' False\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_pose_quality_thresholds", + f"{RB_GUIDE_TEST_PATH}::test_unreliable_or_unsettled_pose_does_not_latch", + ), + ), + HistoricalMutation( + name="rb-guide-latches-on-unreliable-pose", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' can_latch = not unreliable and drift <= BIAS_LATCH_DRIFT_M\n', + replacement=b' can_latch = True\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_unreliable_or_unsettled_pose_does_not_latch", + f"{RB_GUIDE_TEST_PATH}::test_sep29_left_curl_no_longer_doubles_the_model", + ), + ), + HistoricalMutation( + name="rb-guide-latches-before-bias-settles", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' can_latch = not unreliable and drift <= BIAS_LATCH_DRIFT_M\n', + replacement=b' can_latch = not unreliable\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_unreliable_or_unsettled_pose_does_not_latch", + ), + ), + HistoricalMutation( + name="rb-guide-fades-nothing-on-unreliable-pose", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' phase_target = 0.0 if (unreliable and not self.latched) else 1.0\n', + replacement=b' phase_target = 1.0\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_sep29_left_curl_no_longer_doubles_the_model", + ), + ), + HistoricalMutation( + name="rb-guide-curl-not-held-over-ring-speed", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' k_raw = hold_curl(k_raw, model_k, sense)\n', + replacement=b' pass\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_curl_held_while_over_ring_speed_on_the_fixtures", + ), + ), + HistoricalMutation( + name="rb-guide-hold-curl-wrong-side", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' return max(model_k, k_raw) if sense > 0.0 else min(model_k, k_raw)\n', + replacement=b' return min(model_k, k_raw) if sense > 0.0 else max(model_k, k_raw)\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_curl_is_held_until_within_3_mph_of_ring_speed", + ), + ), + HistoricalMutation( + name="rb-guide-hold-speed-window-removed", + source_path="selfdrive/controls/lib/roundabout_guide.py", + original=b' holding = v > self.ring_v + SPEED_HOLD_MS\n', + replacement=b' holding = False\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_curl_held_while_over_ring_speed_on_the_fixtures", + f"{RB_GUIDE_TEST_PATH}::test_curl_is_held_until_within_3_mph_of_ring_speed", + ), + ), + HistoricalMutation( + name="rb-guide-left-cap-ignores-circulation-side", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' k_circ, k_other = A_LAT_CIRC_MAX / v2, A_LAT_MAX / v2\n', + replacement=b' k_circ, k_other = A_LAT_MAX / v2, A_LAT_MAX / v2\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_left_transition_cap_uses_actual_speed", + ), + ), + HistoricalMutation( + name="rb-guide-poor-pose-uses-fast-output-slew", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' oslew = RING_SLEW if self.latched else (OUT_SLEW if poor else OUT_SLEW_GOOD)\n', + replacement=b' oslew = RING_SLEW if self.latched else OUT_SLEW_GOOD\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_poor_pose_uses_the_slow_slews", + ), + ), + HistoricalMutation( + name="rb-guide-poor-pose-uses-fast-target-slew", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' slew = RING_SLEW if self.latched else (TARGET_SLEW if poor else TARGET_SLEW_GOOD)\n', + replacement=b' slew = RING_SLEW if self.latched else TARGET_SLEW_GOOD\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_poor_pose_target_slew", + ), + ), + HistoricalMutation( + name="rb-guide-inner-lane-on-poor-pose", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' inner = r <= R and not (poor or bias_m > BIAS_UNRELIABLE_M) # doubtful pose: never the inner lane\n', + replacement=b' inner = r <= R\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_poor_pose_latch_never_aims_at_the_inner_side", + ), + ), + HistoricalMutation( + name="rb-guide-ring-state-not-logged", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' cloudlog.error(f"roundabout_assist {e}")\n', + replacement=b' pass\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_state_is_logged_via_cloudlog_without_capnp", + ), + ), + HistoricalMutation( + name="rb-guide-ring-state-logged-below-qlog-level", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' cloudlog.error(f"roundabout_assist {e}")\n', + replacement=b' cloudlog.warning(f"roundabout_assist {e}")\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_state_is_logged_via_cloudlog_without_capnp", + ), + ), + HistoricalMutation( + name="rb-guide-raw-model-summary-not-logged", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' cloudlog.error("roundabout_raw " + raw_ring_summary(g, t, v_ego, model_k, out, model_v2, driver))\n', + replacement=b' pass\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_raw_model_summary_logged_near_and_in_the_ring", + ), + ), + HistoricalMutation( + name="rb-guide-raw-model-summary-logged-far-from-ring", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' near = on and g.d_edge is not None and g.d_edge < RAW_LOG_EDGE_M and g.phase != DONE\n', + replacement=b' near = on\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_raw_model_summary_logged_near_and_in_the_ring", + ), + ), + HistoricalMutation( + name="rb-guide-ring-cap-ratio-1-5", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b'RING_CAP_RATIO = 1.15 ', + replacement=b'RING_CAP_RATIO = 1.5 ', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_cap_is_1_15x_the_model_and_2_2_mps2", + f"{RB_GUIDE_TEST_PATH}::test_ring_output_never_above_1_15x_the_model_or_2_2_after_the_latch", + ), + ), + HistoricalMutation( + name="rb-guide-ring-a-lat-cap-3-0", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b'RING_A_LAT_MAX = 2.2 ', + replacement=b'RING_A_LAT_MAX = 3.0 ', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_cap_is_1_15x_the_model_and_2_2_mps2", + ), + ), + HistoricalMutation( + name="rb-guide-ring-slew-0-07", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b'RING_SLEW = 0.035 ', + replacement=b'RING_SLEW = 0.07 ', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_cap_is_1_15x_the_model_and_2_2_mps2", + f"{RB_GUIDE_TEST_PATH}::test_ring_output_slews_at_most_0_035_after_the_latch", + ), + ), + HistoricalMutation( + name="rb-guide-ring-floor-removed", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b'RING_FLOOR_RATIO = 0.85 ', + replacement=b'RING_FLOOR_RATIO = 0.0 ', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_cap_is_1_15x_the_model_and_2_2_mps2", + ), + ), + HistoricalMutation( + name="rb-guide-ring-cap-not-lateral-limited", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' return max(s_model, min(RING_CAP_RATIO * max(ref_k, s_model) + RING_CAP_FLOOR, RING_A_LAT_MAX / max(v * v, 1.0)))\n', + replacement=b' return max(s_model, RING_CAP_RATIO * max(ref_k, s_model) + RING_CAP_FLOOR)\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_cap_is_1_15x_the_model_and_2_2_mps2", + ), + ), + HistoricalMutation( + name="rb-guide-ring-cap-steers-against-the-model", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' return s_model # model not curving with the circulation: the assist never steers against it\n', + replacement=b' return 0.0\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_cap_is_1_15x_the_model_and_2_2_mps2", + ), + ), + HistoricalMutation( + name="rb-guide-ring-cap-skipped-on-poor-pose", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' base = -sense * model_k if holding else ring_cap(self.k_ref, model_k, v, sense)\n', + replacement=b' base = -sense * model_k if holding else (1e9 if poor else ring_cap(self.k_ref, model_k, v, sense))\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_output_never_above_1_15x_the_model_or_2_2_after_the_latch", + ), + ), + HistoricalMutation( + name="rb-guide-ring-hard-clamp-removed", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' out = -sense * min(-sense * (model_k + self.dk_out), cap)\n', + replacement=b' out = model_k + self.dk_out\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_output_never_above_1_15x_the_model_or_2_2_after_the_latch", + f"{RB_GUIDE_TEST_PATH}::test_curl_held_while_over_ring_speed_on_the_fixtures", + ), + ), + HistoricalMutation( + name="rb-guide-lane-circle-is-the-center-line", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' self.r_lane = R - LANE_CIRCLE_FRAC * hw\n', + replacement=b' self.r_lane = R\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_assist_follows_the_lane_circle_once_latched", + ), + ), + HistoricalMutation( + name="rb-guide-latched-confidence-weight-only", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' w = self.phase_w if self.latched else W_MAX * conf * self.phase_w # latched: the cap, not the confidence, bounds the assist\n', + replacement=b' w = W_MAX * conf * self.phase_w\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_latched_weight_does_not_depend_on_pose_confidence", + ), + ), + HistoricalMutation( + name="rb-guide-stalk-releases-wrong-side", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' exit_dir = 2 if sense > 0.0 else 1 # exit side: right on a CCW ring\n', + replacement=b' exit_dir = 1 if sense > 0.0 else 2\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_held_right_stalk_releases_the_ring_and_hands_back_at_once", + f"{RB_GUIDE_TEST_PATH}::test_held_left_stalk_does_not_release_but_the_guide_weight_is_zero", + ), + ), + HistoricalMutation( + name="rb-guide-stalk-never-releases", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' if drv.stalk_held and drv.stalk_dir == exit_dir:\n', + replacement=b' if False:\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_held_right_stalk_releases_the_ring_and_hands_back_at_once", + f"{RB_GUIDE_TEST_PATH}::test_latched_param_and_stalk_release_through_the_assist", + ), + ), + HistoricalMutation( + name="rb-guide-any-stalk-releases", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' if drv.stalk_held and drv.stalk_dir == exit_dir:\n', + replacement=b' if drv.stalk_held:\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_held_left_stalk_does_not_release_but_the_guide_weight_is_zero", + ), + ), + HistoricalMutation( + name="rb-guide-pull-wrong-direction", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' self.pull_s = self.pull_s + dt if -sense * drv.torque >= PULL_TORQUE_NM else 0.0\n', + replacement=b' self.pull_s = self.pull_s + dt if sense * drv.torque >= PULL_TORQUE_NM else 0.0\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_steering_pull_toward_the_exit_releases_after_0_3_s", + f"{RB_GUIDE_TEST_PATH}::test_steering_pull_toward_the_circulation_does_not_release_but_wins", + ), + ), + HistoricalMutation( + name="rb-guide-pull-never-releases", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' if self.pull_s >= PULL_RELEASE_S:\n', + replacement=b' if False:\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_steering_pull_toward_the_exit_releases_after_0_3_s", + ), + ), + HistoricalMutation( + name="rb-guide-override-never-releases", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' if self.override_s >= OVERRIDE_S:\n', + replacement=b' if False:\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_steering_press_zeroes_the_weight_after_0_3_s_and_overrides_after_0_5_s", + ), + ), + HistoricalMutation( + name="rb-guide-map-only-exit", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' if v > V_MAX + 2.0:\n return "speed"\n', + replacement=b' if self.travel > 60.0:\n return "map_exit"\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_no_blinker_no_map_exit_the_car_stays_on_the_ring", + ), + ), + HistoricalMutation( + name="rb-guide-driver-torque-does-not-win", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' drv_active, self.drv_s = RH.driver_wins(drv.stalk_held, drv.pressed, drv.torque, sense, self.drv_s, dt)\n', + replacement=b' drv_active, self.drv_s = bool(drv.stalk_held or drv.pressed), 0.0\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_steering_pull_toward_the_exit_releases_after_0_3_s", + f"{RB_GUIDE_TEST_PATH}::test_steering_pull_toward_the_circulation_does_not_release_but_wins", + ), + ), + HistoricalMutation( + name="rb-guide-held-stalk-keeps-the-assist", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' if not lat_active or drv_active:\n', + replacement=b' if not lat_active:\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_held_left_stalk_does_not_release_but_the_guide_weight_is_zero", + ), + ), + HistoricalMutation( + name="rb-guide-held-stalk-weight-not-zero", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' if drv_active:\n w = 0.0\n', + replacement=b' if False:\n w = 0.0\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_held_left_stalk_does_not_release_but_the_guide_weight_is_zero", + ), + ), + HistoricalMutation( + name="rb-guide-latched-param-not-written", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' self.params.put_bool(PARAM_RING_LATCHED, latched)\n', + replacement=b' pass\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_latched_param_and_stalk_release_through_the_assist", + f"{RB_GUIDE_TEST_PATH}::test_off_while_latched_resets_and_clears_the_param", + ), + ), + HistoricalMutation( + name="rb-guide-off-while-latched-keeps-the-ring", + source_path='selfdrive/controls/lib/roundabout_guide.py', + original=b' if self.guide.latched:\n self.guide.reset_state() # toggled Off on the ring: nothing carried over\n', + replacement=b' if False:\n self.guide.reset_state()\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_off_while_latched_resets_and_clears_the_param", + ), + ), + HistoricalMutation( + name="rb-desire-helper-tips-not-suppressed-on-ring", + source_path='selfdrive/controls/lib/desire_helper.py', + original=b' tip_event = self._tip_turn.tip_event and not self._suppress_next_tip and not self.suppress_tips\n', + replacement=b' tip_event = self._tip_turn.tip_event and not self._suppress_next_tip\n', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_tips_are_suppressed_while_latched_and_modeld_controlsd_are_wired", + ), + ), + HistoricalMutation( + name="rb-modeld-ring-latch-not-read", + source_path='selfdrive/modeld/modeld.py', + original=b' DH.suppress_tips = params.get_bool(PARAM_RING_LATCHED)', + replacement=b' DH.suppress_tips = False', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_tips_are_suppressed_while_latched_and_modeld_controlsd_are_wired", + ), + ), + HistoricalMutation( + name="rb-controlsd-driver-stalk-not-passed", + source_path='selfdrive/controls/controlsd.py', + original=b"stalk_state=int(getattr(CS, 'turnSignalStalkState', 0) or 0)", + replacement=b'stalk_state=0', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_tips_are_suppressed_while_latched_and_modeld_controlsd_are_wired", + ), + ), + HistoricalMutation( + name="rb-controlsd-driver-torque-not-passed", + source_path='selfdrive/controls/controlsd.py', + original=b'steering_pressed=bool(CS.steeringPressed), steering_torque=float(CS.steeringTorque)', + replacement=b'steering_pressed=False, steering_torque=0.0', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_tips_are_suppressed_while_latched_and_modeld_controlsd_are_wired", + ), + ), + HistoricalMutation( + name="rb-latched-param-persists-across-drives", + source_path='common/params_keys.h', + original=b'{"NAPRoundaboutLatched", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}', + replacement=b'{"NAPRoundaboutLatched", {PERSISTENT, BOOL}}', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_tips_are_suppressed_while_latched_and_modeld_controlsd_are_wired", + ), + ), + HistoricalMutation( + name="rb-ring-speed-back-to-15-8-mph", + source_path='selfdrive/mapd/roundabout.py', + original=b'RB_RING_SPEED_MPH = 18.0', + replacement=b'RB_RING_SPEED_MPH = 15.8', + test_nodes=( + f"{RB_GUIDE_TEST_PATH}::test_ring_speed_constant_is_18_mph_and_planner_uses_it", + f"{RB_GUIDE_TEST_PATH}::test_ring_speed_is_18_mph_and_lateral_cap", + ), + ), + HistoricalMutation( + name="rb-hold-cap-never-widens", + source_path=RH_PATH, + original=b' if s_circle <= 0.0 or s_model >= CIRCLE_CAP_FRAC * s_circle:\n', + replacement=b' if True:\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_widen_cap_only_below_half_the_circle_and_bounded", + ), + ), + HistoricalMutation( + name="rb-hold-cap-widens-above-half", + source_path=RH_PATH, + original=b' if s_circle <= 0.0 or s_model >= CIRCLE_CAP_FRAC * s_circle:\n', + replacement=b' if s_circle <= 0.0 or s_model >= 2.0 * s_circle:\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_widen_cap_only_below_half_the_circle_and_bounded", + ), + ), + HistoricalMutation( + name="rb-hold-cap-extra-unbounded", + source_path=RH_PATH, + original=b's_model + CIRCLE_CAP_EXTRA * fade, a_lat_max', + replacement=b's_model + 9.0 * fade, a_lat_max', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_widen_cap_only_below_half_the_circle_and_bounded", + ), + ), + HistoricalMutation( + name="rb-hold-cap-ignores-lateral-accel-cap", + source_path=RH_PATH, + original=b' return max(cap, min(s_circle, s_model + CIRCLE_CAP_EXTRA * fade, a_lat_max / max(v * v, 1.0)))\n', + replacement=b' return max(cap, min(s_circle, s_model + CIRCLE_CAP_EXTRA * fade))\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_widen_cap_only_below_half_the_circle_and_bounded", + f"{RB_HOLD_TEST_PATH}::test_cap_against_the_circle_when_the_model_is_flat_but_still_2_2_and_slew_bound", + ), + ), + HistoricalMutation( + name="rb-hold-cap-widening-steps-at-half-circle", + source_path=RH_PATH, + original=b' fade = min(max(1.0 - s_model / (CIRCLE_CAP_FRAC * s_circle), 0.0), 1.0)\n', + replacement=b' fade = 1.0\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_widen_cap_only_below_half_the_circle_and_bounded", + ), + ), + HistoricalMutation( + name="rb-hold-exit-floor-removed", + source_path=RH_PATH, + original=b' floor = max(floor, min(s_circle, a_lat_max / max(v * v, 1.0)))\n', + replacement=b' floor = floor\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_ring_limits_floor_only_in_the_exit_window_without_a_stalk", + ), + ), + HistoricalMutation( + name="rb-hold-exit-floor-ignores-stalk", + source_path=RG_PATH, + original=b' plain = drv.stalk_dir == (2 if sense > 0.0 else 1) or d_edge', + replacement=b' plain = d_edge', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_window_floor_keeps_the_circle_target_without_a_stalk_and_not_with_one", + ), + ), + HistoricalMutation( + name="rb-hold-exit-window-never-applied", + source_path=RG_PATH, + original=b'RH.in_exit_window(theta, sense, self.exits), plain)', + replacement=b'False, plain)', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_window_floor_keeps_the_circle_target_without_a_stalk_and_not_with_one", + ), + ), + HistoricalMutation( + name="rb-hold-exit-window-too-short", + source_path=RH_PATH, + original=b'EXIT_BEFORE_DEG = 20.0 ', + replacement=b'EXIT_BEFORE_DEG = 5.0 ', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_windows_20_deg_before_and_5_after_for_both_senses", + ), + ), + HistoricalMutation( + name="rb-hold-exit-window-wrong-side", + source_path=RH_PATH, + original=b' return _wrap_deg(sense * (exit_deg - math.degrees(theta_rad)))\n', + replacement=b' return _wrap_deg(exit_deg - math.degrees(theta_rad))\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_windows_20_deg_before_and_5_after_for_both_senses", + f"{RB_HOLD_TEST_PATH}::test_cw_ring_mirror_of_the_window_and_the_widening", + ), + ), + HistoricalMutation( + name="rb-hold-exits-not-computed", + source_path=RG_PATH, + original=b' self.exits = RH.exit_angles(ring)\n', + replacement=b' self.exits = []\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_angles_are_the_three_soco_branches", + f"{RB_HOLD_TEST_PATH}::test_exit_window_floor_keeps_the_circle_target_without_a_stalk_and_not_with_one", + ), + ), + HistoricalMutation( + name="rb-hold-exit-blinker-never-releases", + source_path=RG_PATH, + original=b' if drv.stalk_dir == exit_dir and RH.on_exit_arm(', + replacement=b' if False and RH.on_exit_arm(', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_blinker_releases_only_on_the_exit_arm_and_only_to_the_model", + ), + ), + HistoricalMutation( + name="rb-hold-exit-blinker-releases-either-side", + source_path=RG_PATH, + original=b' if drv.stalk_dir == exit_dir and RH.on_exit_arm(', + replacement=b' if drv.stalk_dir != 0 and RH.on_exit_arm(', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_blinker_releases_only_on_the_exit_arm_and_only_to_the_model", + ), + ), + HistoricalMutation( + name="rb-hold-exit-blinker-releases-anywhere", + source_path=RH_PATH, + original=b' return near_exit(theta_rad, sense, exits) and d_edge >= -EXIT_ARM_EDGE_M\n', + replacement=b' return True\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_blinker_releases_only_on_the_exit_arm_and_only_to_the_model", + ), + ), + HistoricalMutation( + name="rb-hold-press-not-debounced", + source_path=RH_PATH, + original=b'return bool(stalk_held or exit_pull), drv_s', + replacement=b'return bool(stalk_held or exit_pull or counts_as_press(pressed, torque, sense)), drv_s', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_press_debounce_and_light_torque", + f"{RB_HOLD_TEST_PATH}::test_press_flicker_keeps_the_correction_but_a_held_press_and_hard_torque_still_win", + ), + ), + HistoricalMutation( + name="rb-hold-light-torque-not-ignored", + source_path=RH_PATH, + original=b' return bool(pressed) and not (sense * torque > 0.0)\n', + replacement=b' return bool(pressed)\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_press_debounce_and_light_torque", + ), + ), + HistoricalMutation( + name="rb-hold-light-torque-ignored-toward-exit", + source_path=RH_PATH, + original=b'not (sense * torque > 0.0)', + replacement=b'not (-sense * torque > 0.0)', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_press_debounce_and_light_torque", + ), + ), + HistoricalMutation( + name="rb-hold-hard-override-removed", + source_path=RH_PATH, + original=b'bool(stalk_held or exit_pull)', + replacement=b'bool(stalk_held)', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_press_debounce_and_light_torque", + f"{RB_HOLD_TEST_PATH}::test_press_flicker_keeps_the_correction_but_a_held_press_and_hard_torque_still_win", + ), + ), + HistoricalMutation( + name="rb-hold-guide-override-uses-raw-press", + source_path=RG_PATH, + original=b' hands = RH.counts_as_press(drv.pressed, drv.torque, sense) or', + replacement=b' hands = drv.pressed or', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_press_flicker_keeps_the_correction_but_a_held_press_and_hard_torque_still_win", + ), + ), + HistoricalMutation( + name="rb-hold-latch-waits-for-tangent", + source_path=RH_PATH, + original=b' return d_edge < LATCH_EDGE_M and align_deg < max(tangent_deg, LATCH_ALIGN_EDGE_DEG)\n', + replacement=b' return d_edge < LATCH_EDGE_M and align_deg < tangent_deg\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_latch_ready_earlier_at_the_ring_edge", + f"{RB_HOLD_TEST_PATH}::test_early_latch_at_45_deg_alignment_and_not_beyond", + ), + ), + HistoricalMutation( + name="rb-hold-cap-widening-given-up-at-once", + source_path=RH_PATH, + original=b' rate = 1.0 if plain or base + extra > a_cap else fall\n', + replacement=b' rate = 1.0\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_step_cap_rises_at_once_falls_slowly_and_is_bound_by_a_lat", + ), + ), + HistoricalMutation( + name="rb-hold-cap-widening-kept-over-ring-speed", + source_path=RH_PATH, + original=b' if holding:\n return 0.0, base\n', + replacement=b' if False:\n return 0.0, base\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_step_cap_rises_at_once_falls_slowly_and_is_bound_by_a_lat", + ), + ), + HistoricalMutation( + name="rb-hold-guide-caps-against-live-model", + source_path=RG_PATH, + original=b' s_cmd = max(min(-sense * k_pp, lim[0]), lim[1])\n', + replacement=b' s_cmd = max(min(-sense * k_pp, ring_cap(self.k_ref, model_k, v, sense)), ring_floor(self.k_ref, v))\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_0000013c_holds_the_left_turn_at_the_ring_edge_in_band", + f"{RB_HOLD_TEST_PATH}::test_cap_against_the_circle_when_the_model_is_flat_but_still_2_2_and_slew_bound", + ), + ), + HistoricalMutation( + name="rb-hold-guide-widening-past-lateral-accel", + source_path=RG_PATH, + original=b' if self.latched and self.phase != EXITING and self.cap_extra > 0.0:\n', + replacement=b' if False:\n', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_0000013c_holds_the_left_turn_at_the_ring_edge_in_band", + ), + ), + HistoricalMutation( + name="rb-hold-guide-exit-blinker-not-handed-back", + source_path=RG_PATH, + original=b'("stalk", "pull", "override", "exit_blinker")', + replacement=b'("stalk", "pull", "override")', + test_nodes=( + f"{RB_HOLD_TEST_PATH}::test_exit_blinker_releases_only_on_the_exit_arm_and_only_to_the_model", + ), + ), + HistoricalMutation( + name="rb-hold-decel-onset-back-to-200m", + source_path="selfdrive/mapd/roundabout.py", + original=b'RB_ONSET_MIN_M = 140.0\n', + replacement=b'RB_ONSET_MIN_M = 200.0\n', + test_nodes=( + f"{RB_MAPD_TEST_PATH}::test_funnel_eases_speed", + f"{RB_HOLD_TEST_PATH}::test_decel_onset_is_a_named_constant_near_the_ring", + f"{RB_MAPD_TEST_PATH}::test_funnel_detects_farther_out", + ), + ), +) + + +def main() -> int: + if len(MUTATIONS) != EXPECTED_COUNT: + print(f"INVALID: expected {EXPECTED_COUNT} roundabout mutations, found {len(MUTATIONS)}") + return 1 + with tempfile.TemporaryDirectory(prefix="tesla-preap-roundabout-mutation-") as temp_dir: + temp_root = Path(temp_dir) + baseline_xml = temp_root / "baseline.xml" + baseline = parent.run_pytest((RB_GUIDE_TEST_PATH, RB_MAP_TEST_PATH, RB_HOLD_TEST_PATH, RB_MAPD_TEST_PATH), baseline_xml) + if baseline.returncode != 0: + print("BASELINE FAILED: roundabout tests did not pass") + print(baseline.stdout) + return 1 + try: + baseline_testcases = parent.junit_testcases(baseline_xml) + except parent.JUnitReportError as exc: + print(f"BASELINE INVALID: {exc}") + return 1 + print(f"BASELINE PASS: {len(baseline_testcases)} roundabout tests") + + survivors = [] + for mutation in MUTATIONS: + source_path = None + original_source = None + mutation_result = None + mutation_error = None + restored = False + mutation_xml = temp_root / f"{mutation.name}.xml" + try: + source_path, original_source = parent.apply_mutation(mutation) + mutation_result = parent.run_pytest(mutation.test_nodes, mutation_xml) + except Exception as exc: # pragma: no cover - failure reporting path + mutation_error = exc + finally: + if source_path is not None and original_source is not None: + source_path.write_bytes(original_source) + restored = source_path.read_bytes() == original_source + + if not restored: + print(f"INVALID: {mutation.name} source restoration was not byte-identical") + return 1 + if mutation_error is not None: + print(f"INVALID: {mutation.name} could not run: {mutation_error}") + return 1 + if mutation_result is None: + print(f"INVALID: {mutation.name} produced no pytest result") + return 1 + try: + mutation_testcases = parent.junit_testcases(mutation_xml) + except parent.JUnitReportError as exc: + print(f"INVALID: {mutation.name} {exc}") + return 1 + if mutation_result.returncode == 1 and parent.has_only_assertion_failures(mutation_testcases): + print(f"KILLED: {mutation.name} [{', '.join(mutation.test_nodes)}]") + elif mutation_result.returncode == 0: + survivors.append(mutation.name) + print(f"SURVIVED: {mutation.name} [{', '.join(mutation.test_nodes)}]") + else: + print(f"INVALID: {mutation.name} exited without assertion-only test failures " + + f"(pytest status {mutation_result.returncode})") + print(mutation_result.stdout) + return 1 + + if survivors: + print(f"Roundabout mutations survived: {', '.join(survivors)}") + return 1 + print(f"ALL KILLED: {len(MUTATIONS)} roundabout mutations") + print("RESTORED: every mutated source is byte-identical") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/ci/test_assemble_replay_release.py b/.github/ci/test_assemble_replay_release.py new file mode 100644 index 00000000000000..63ca8da17cb6d0 --- /dev/null +++ b/.github/ci/test_assemble_replay_release.py @@ -0,0 +1,285 @@ +"""Focused tests for active process-replay release assembly. + +Covers a valid 66-ref assembly and fail-closed rejects (missing/extra task, +invalid digest, executable=false). Uses local synthetic fakedata only — no +network downloads. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import subprocess +import sys +from pathlib import Path + +CI_DIR = Path(__file__).resolve().parent +REPO_ROOT = CI_DIR.parents[1] +ASSEMBLE_PATH = REPO_ROOT / "tools" / "ci" / "assemble_replay_release.py" +ACTIVE_INVENTORY = CI_DIR / "process_replay_active_inventory.json" + +SOURCE_SHA = "a" * 40 +OPENDBC_SHA = "b" * 40 +PREV_TAG = "process-replay/v1/" + ("c" * 40) + "-" + ("d" * 12) + + +def _load_assemble(): + spec = importlib.util.spec_from_file_location("assemble_replay_release", ASSEMBLE_PATH) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = mod + spec.loader.exec_module(mod) + return mod + + +assemble = _load_assemble() + + +def _canonical(obj: object) -> bytes: + return assemble.canonical_json(obj) + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _load_inventory_cases() -> list[dict]: + inventory = json.loads(ACTIVE_INVENTORY.read_text(encoding="utf-8")) + assert inventory["inventory"] == "active" + assert inventory["expected_cases"] == 16 + assert inventory["expected_tasks"] == 66 + cases = inventory["cases"] + assert isinstance(cases, list) and len(cases) == 16 + return [dict(c) for c in cases] + + +def _write_cases(path: Path, cases: list[dict]) -> None: + path.write_text(json.dumps(cases, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + +def _seed_fakedata(fakedata: Path, cases: list[dict], *, skip_task: str | None = None, extra_name: str | None = None) -> list[str]: + fakedata.mkdir(parents=True, exist_ok=True) + written: list[str] = [] + for case in cases: + for proc in case["processes"]: + task_id = f"{case['case_id']}:{proc}" + if skip_task is not None and task_id == skip_task: + continue + name = f"{case['case_id']}__{proc}__{SOURCE_SHA}.zst" + (fakedata / name).write_bytes(f"{task_id}\n".encode()) + written.append(task_id) + if extra_name is not None: + (fakedata / extra_name).write_bytes(b"extra-ref\n") + return written + + +def _run_assemble(cases_json: Path, fakedata: Path, release: Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [ + sys.executable, + str(ASSEMBLE_PATH), + "--operation", + "generate-active", + "--source-sha", + SOURCE_SHA, + "--fakedata-dir", + str(fakedata), + "--release-dir", + str(release), + "--opendbc-sha", + OPENDBC_SHA, + "--cases-json", + str(cases_json), + "--previous-accepted-tag", + PREV_TAG, + ], + check=False, + capture_output=True, + text=True, + ) + + +def test_active_inventory_matches_harness_case_record_contract(): + inventory = json.loads(ACTIVE_INVENTORY.read_text(encoding="utf-8")) + assert inventory["schema_version"] == 1 + assert inventory["inventory"] == "active" + assert inventory["expected_cases"] == 16 + assert inventory["expected_tasks"] == 66 + assert inventory["partition"] == {"card": 16, "controlsd": 16, "lagd": 16, "other": 18} + assert inventory["allowed_processes"] == sorted(inventory["allowed_processes"]) + + cases = inventory["cases"] + task_ids = inventory["task_ids"] + assert len(cases) == 16 + assert len(task_ids) == 66 + assert len(set(task_ids)) == 66 + + derived = [f"{c['case_id']}:{p}" for c in cases for p in c["processes"]] + assert derived == task_ids + assert all(c["executable"] is True for c in cases) + assert all(isinstance(c["source"], str) and c["source"] for c in cases) + assert all(isinstance(c["source_bytes"], int) and c["source_bytes"] > 0 for c in cases) + assert all(isinstance(c["source_sha256"], str) and len(c["source_sha256"]) == 64 for c in cases) + assert all(isinstance(c["params_digest"], str) and len(c["params_digest"]) == 64 for c in cases) + + sorted_cases = sorted(cases, key=lambda c: c["case_id"]) + sources_payload = [ + { + "case_id": c["case_id"], + "source": c["source"], + "source_bytes": c["source_bytes"], + "source_sha256": c["source_sha256"], + } + for c in sorted_cases + ] + params_payload = [{"case_id": c["case_id"], "params_digest": c["params_digest"]} for c in sorted_cases] + assert inventory["expected_sources_digest"] == _sha256(_canonical(sources_payload)) + assert inventory["expected_params_digest"] == _sha256(_canonical(params_payload)) + + counts = {"card": 0, "controlsd": 0, "lagd": 0, "other": 0} + for task_id in task_ids: + proc = task_id.split(":", 1)[1] + counts[proc if proc in counts else "other"] += 1 + assert counts == inventory["partition"] + + +def test_assemble_valid_66_ref_release(tmp_path: Path): + cases = _load_inventory_cases() + cases_json = tmp_path / "cases.json" + fakedata = tmp_path / "fakedata" + release = tmp_path / "release" + _write_cases(cases_json, cases) + written = _seed_fakedata(fakedata, cases) + assert len(written) == 66 + + proc = _run_assemble(cases_json, fakedata, release) + assert proc.returncode == 0, proc.stderr + proc.stdout + + assert (release / "ref_commit").read_text(encoding="utf-8") == SOURCE_SHA + "\n" + manifest_bytes = (release / "manifest.json").read_bytes() + assert manifest_bytes == _canonical(json.loads(manifest_bytes.decode("utf-8"))) + + manifest = json.loads(manifest_bytes.decode("utf-8")) + assert manifest["schema_version"] == 1 + assert manifest["openpilot_sha"] == SOURCE_SHA + assert manifest["opendbc_sha"] == OPENDBC_SHA + assert manifest["previous_accepted_tag"] == PREV_TAG + assert len(manifest["cases"]) == 16 + assert len(manifest["refs"]) == 66 + + inventory = json.loads(ACTIVE_INVENTORY.read_text(encoding="utf-8")) + assert manifest["sources_digest"] == inventory["expected_sources_digest"] + assert manifest["params_digest"] == inventory["expected_params_digest"] + + by_id = {c["case_id"]: c for c in cases} + for cid, rec in by_id.items(): + assembled = next(c for c in manifest["cases"] if c["case_id"] == cid) + assert assembled["source"] == rec["source"] + assert assembled["source_sha256"] == rec["source_sha256"] + assert assembled["source_bytes"] == rec["source_bytes"] + assert assembled["params_digest"] == rec["params_digest"] + assert assembled["executable"] is True + + for task_id, entry in manifest["refs"].items(): + case_id, process = task_id.split(":", 1) + rec = by_id[case_id] + assert process in rec["processes"] + assert entry["filename"] == f"{case_id}__{process}__{SOURCE_SHA}.zst" + assert entry["source"] == rec["source"] + assert entry["source_sha256"] == rec["source_sha256"] + assert entry["source_bytes"] == rec["source_bytes"] + assert entry["params_digest"] == rec["params_digest"] + payload = (release / entry["filename"]).read_bytes() + assert entry["size"] == len(payload) + assert entry["sha256"] == _sha256(payload) + + zsts = sorted(p.name for p in release.iterdir() if p.name.endswith(".zst")) + assert len(zsts) == 66 + assert set(release.iterdir()) == {release / "ref_commit", release / "manifest.json"} | {release / n for n in zsts} + + +def test_assemble_rejects_missing_task(tmp_path: Path): + cases = _load_inventory_cases() + cases_json = tmp_path / "cases.json" + fakedata = tmp_path / "fakedata" + release = tmp_path / "release" + _write_cases(cases_json, cases) + victim = f"{cases[0]['case_id']}:{cases[0]['processes'][0]}" + _seed_fakedata(fakedata, cases, skip_task=victim) + + proc = _run_assemble(cases_json, fakedata, release) + assert proc.returncode != 0 + assert "expected 66 tasks" in (proc.stderr + proc.stdout) + + +def test_assemble_rejects_extra_task(tmp_path: Path): + cases = _load_inventory_cases() + cases_json = tmp_path / "cases.json" + fakedata = tmp_path / "fakedata" + release = tmp_path / "release" + _write_cases(cases_json, cases) + # hyundai2 is core-only; selfdrived is an extra process for that case. + extra = f"hyundai2__selfdrived__{SOURCE_SHA}.zst" + _seed_fakedata(fakedata, cases, extra_name=extra) + + proc = _run_assemble(cases_json, fakedata, release) + assert proc.returncode != 0 + combined = proc.stderr + proc.stdout + assert "process selfdrived not in case hyundai2 process set" in combined or "expected 66 tasks" in combined + + +def test_assemble_rejects_invalid_digest(tmp_path: Path): + cases = _load_inventory_cases() + cases[0]["params_digest"] = "not-a-digest" + cases_json = tmp_path / "cases.json" + fakedata = tmp_path / "fakedata" + release = tmp_path / "release" + _write_cases(cases_json, cases) + _seed_fakedata(fakedata, cases) + + proc = _run_assemble(cases_json, fakedata, release) + assert proc.returncode != 0 + assert "params_digest" in (proc.stderr + proc.stdout) + + +def test_assemble_rejects_executable_false(tmp_path: Path): + cases = _load_inventory_cases() + cases[0]["executable"] = False + cases_json = tmp_path / "cases.json" + fakedata = tmp_path / "fakedata" + release = tmp_path / "release" + _write_cases(cases_json, cases) + _seed_fakedata(fakedata, cases) + + proc = _run_assemble(cases_json, fakedata, release) + assert proc.returncode != 0 + assert "must be executable" in (proc.stderr + proc.stdout) + + +def test_assemble_rejects_generate_staged_operation(): + proc = subprocess.run( + [ + sys.executable, + str(ASSEMBLE_PATH), + "--operation", + "generate-staged", + "--source-sha", + SOURCE_SHA, + "--fakedata-dir", + ".", + "--release-dir", + ".", + "--opendbc-sha", + OPENDBC_SHA, + "--cases-json", + str(ACTIVE_INVENTORY), + "--previous-accepted-tag", + PREV_TAG, + ], + check=False, + capture_output=True, + text=True, + ) + assert proc.returncode != 0 + assert "generate-staged" in (proc.stderr + proc.stdout) or "invalid choice" in (proc.stderr + proc.stdout).lower() diff --git a/.github/ci/test_tesla_preap_longitudinal_workflow.py b/.github/ci/test_tesla_preap_longitudinal_workflow.py new file mode 100644 index 00000000000000..f10dbbf3f8e75b --- /dev/null +++ b/.github/ci/test_tesla_preap_longitudinal_workflow.py @@ -0,0 +1,150 @@ +import re +from pathlib import Path + + +WORKFLOW_PATH = Path(__file__).resolve().parents[1] / "workflows" / "tests.yaml" +PROCESS_REPLAY_PATH = Path(__file__).resolve().parents[2] / "selfdrive" / "test" / "process_replay" / "process_replay.py" + + +def indented_block(document: str, header: str) -> str: + lines = document.splitlines() + header_index = lines.index(header) + header_indent = len(header) - len(header.lstrip()) + block = [] + for line in lines[header_index + 1:]: + line_indent = len(line) - len(line.lstrip()) + if line.strip() and line_indent <= header_indent: + break + block.append(line) + return "\n".join(block) + + +def normalized_lines(block: str) -> set[str]: + return {line.strip().removesuffix("\\").rstrip() for line in block.splitlines()} + + +def test_nap_ci_uses_fork_lfs_storage(): + workflow = WORKFLOW_PATH.read_text() + + assert "OPENPILOT_LFS_URL: https://github.com/${{ github.repository }}.git/info/lfs" in normalized_lines(workflow) + assert 'command: git config lfs.url "$OPENPILOT_LFS_URL" && git lfs pull' in normalized_lines(workflow) + + +def test_nap_branches_run_on_push(): + workflow = WORKFLOW_PATH.read_text() + push_config = indented_block(workflow, " push:") + push_branches = indented_block(push_config, " branches:") + + assert re.search(r"^\s*-\s+['\"]?nap-\*['\"]?\s*$", push_branches, re.MULTILINE) + + +def test_named_focused_job_is_present(): + workflow = WORKFLOW_PATH.read_text() + focused_job = indented_block(workflow, " tesla_preap_longitudinal_regression:") + + assert "name: Tesla Pre-AP longitudinal regressions" in normalized_lines(focused_job) + + +def test_focused_tests_and_mutations_are_pinned(): + workflow = WORKFLOW_PATH.read_text() + focused_job = indented_block(workflow, " tesla_preap_longitudinal_regression:") + required_commands = ( + "selfdrive/controls/tests/test_following_distance.py", + "selfdrive/controls/tests/test_follow_distance.py", + "selfdrive/controls/tests/test_lead_approach.py", + "selfdrive/controls/tests/test_firm_brake_latch.py", + "selfdrive/selfdrived/tests/test_preap_regen_cmd_pin.py", + "selfdrive/controls/tests/test_unified_far_gap_gate.py", + "selfdrive/controls/tests/test_unified_far_gap_catchup.py", + "selfdrive/mapd/tests/test_map_speed_policy.py", + "selfdrive/mapd/tests/test_map_speed_policy_2.py", + "selfdrive/mapd/tests/test_map_match_road_class.py", + "selfdrive/controls/tests/test_radard.py", + "selfdrive/controls/tests/test_path_obstacle_radar.py", + "selfdrive/controls/lib/tests/test_path_obstacle.py", + "selfdrive/controls/tests/test_radar_path_gate.py", + "selfdrive/controls/tests/test_rain_radar_hold.py", + "selfdrive/controls/tests/test_radar_sensor_dirty.py", + "selfdrive/controls/tests/test_tesla_preap_following.py", + "selfdrive/controls/tests/test_gap_lock_gesture.py", + "selfdrive/controls/tests/test_gap_lock_latch.py", + "selfdrive/controls/tests/test_curve_preview.py", + "selfdrive/controls/tests/test_curve_follow.py", + "selfdrive/controls/tests/test_curve_follow_planner.py", + "selfdrive/controls/tests/test_sight_cap_planner.py", + "selfdrive/controls/tests/test_sight_cap_replay.py", + "selfdrive/controls/tests/test_model_sight.py", + "selfdrive/car/tests/test_curve_follow_card_max.py", + "selfdrive/controls/tests/test_lead_leaving.py", + "selfdrive/controls/lib/tests/test_curve_max_hold.py", + "selfdrive/controls/lib/tests/test_lat_turn_geometry.py", + "selfdrive/controls/lib/tests/test_lane_change_confirm_replay.py", + "selfdrive/controls/lib/tests/test_lane_change_nudge.py", + "selfdrive/controls/lib/tests/test_lane_change_target.py", + "selfdrive/controls/lib/tests/test_lane_change_lock.py", + "selfdrive/controls/lib/tests/test_lane_change_turn.py", + "selfdrive/mapd/tests/test_roundabout.py", + "selfdrive/mapd/tests/test_roundabout_map.py", + "selfdrive/controls/lib/tests/test_roundabout_guide.py", + "selfdrive/controls/lib/tests/test_roundabout_ring_hold.py", + "selfdrive/controls/lib/tests/test_driver_lateral_handoff_early_yield.py", + "selfdrive/controls/lib/tests/test_driver_lateral_handoff_wheel_resume.py", + "selfdrive/controls/lib/tests/test_lat_yield_inference_guard.py", + "selfdrive/car/tesla/tests/test_preap_lat_yield.py", + "selfdrive/controls/tests/test_roundabout_planner.py", + "selfdrive/controls/tests/test_tesla_preap_longcontrol.py", + "selfdrive/controls/tests/test_tesla_preap_gas_lift_handoff.py", + "selfdrive/controls/tests/test_tesla_preap_brake_cancel_regen.py", + "selfdrive/controls/tests/test_tesla_preap_one_pedal_long.py", + "opendbc_repo/opendbc/car/tesla/preap/tests/test_preap_engagement.py", + "opendbc_repo/opendbc/car/tesla/preap/tests/test_lat_yield.py", + "opendbc_repo/opendbc/car/tesla/preap/tests/test_longitudinal_tuning.py", + "opendbc_repo/opendbc/car/tesla/preap/tests/test_virtual_das.py", + "opendbc_repo/opendbc/car/tesla/preap/tests/test_vdas_grade_control.py", + ) + + for command in required_commands: + assert command in normalized_lines(focused_job) + assert "run: python .github/ci/tesla_preap_longitudinal_mutations.py" in normalized_lines(focused_job) + assert "run: python .github/ci/tesla_preap_roundabout_mutations.py" in normalized_lines(focused_job) + assert "run: python .github/ci/tesla_preap_lane_change_mutations.py" in normalized_lines(focused_job) + assert "run: python .github/ci/tesla_preap_lat_yield_mutations.py" in normalized_lines(focused_job) + + +def test_focused_job_builds_generated_mpc_dependencies(): + workflow = WORKFLOW_PATH.read_text() + focused_job = indented_block(workflow, " tesla_preap_longitudinal_regression:") + build_step = indented_block(focused_job, " - name: Build focused test dependencies") + + assert "run: scons -j$(nproc)" in normalized_lines(build_step) + + +def test_focused_job_cannot_be_skipped_or_soft_failed(): + workflow = WORKFLOW_PATH.read_text() + focused_job = indented_block(workflow, " tesla_preap_longitudinal_regression:") + + assert not re.search(r"^\s*(?:if|continue-on-error)\s*:", focused_job, re.MULTILINE) + + +def test_additive_follow_telemetry_is_ignored_by_process_replay(): + process_replay = PROCESS_REPLAY_PATH.read_text() + plannerd_config = re.search(r'proc_name="plannerd",(?P.*?)\n \),', process_replay, re.DOTALL) + assert plannerd_config is not None + + assert '"longitudinalPlan.napFollowDistance"' in plannerd_config.group("body") + assert '"longitudinalPlan.tFollow"' in plannerd_config.group("body") + + +def main(): + test_nap_branches_run_on_push() + test_nap_ci_uses_fork_lfs_storage() + test_named_focused_job_is_present() + test_focused_tests_and_mutations_are_pinned() + test_focused_job_builds_generated_mpc_dependencies() + test_focused_job_cannot_be_skipped_or_soft_failed() + test_additive_follow_telemetry_is_ignored_by_process_replay() + print("Tesla Pre-AP longitudinal workflow contract passed") + + +if __name__ == "__main__": + main() diff --git a/.github/ci/test_validate_process_replay_release.py b/.github/ci/test_validate_process_replay_release.py new file mode 100644 index 00000000000000..03a1c5bda9be03 --- /dev/null +++ b/.github/ci/test_validate_process_replay_release.py @@ -0,0 +1,441 @@ +"""Contract tests for process-replay release validator and publisher gates. + +These tests prove fail-closed publication behavior against pending inventory and +common release/manifest tampering. They do not run process replay itself. +""" + +from __future__ import annotations + +import hashlib +import json +import zipfile +from pathlib import Path + +import pytest + +import validate_process_replay_release as v + + +CI_DIR = Path(__file__).resolve().parent +WORKFLOW_PATH = CI_DIR.parent / "workflows" / "process_replay_refs.yaml" +STAGED_INVENTORY = CI_DIR / "process_replay_staged_inventory.json" + +SOURCE_SHA = "a" * 40 +OPENDBC_SHA = "b" * 40 +OTHER_OPENDBC = "c" * 40 + + +def _canonical(obj) -> bytes: + return v.canonical_json(obj) + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _allowed_processes() -> list[str]: + return sorted({ + "calibrationd", "card", "controlsd", "dmonitoringd", "lagd", "locationd", + "paramsd", "plannerd", "radard", "selfdrived", "torqued", "ubloxd", + }) + + +def _build_cases( + inventory: str = "staged", + *, + executable: bool = True, + pin_sources: bool = True, +) -> list[dict]: + """Synthetic cases matching exact active (16/66) or staged (18/78) contracts.""" + allowed = _allowed_processes() + other = [p for p in allowed if p not in {"card", "controlsd", "lagd"}] + assert len(other) == 9 + if inventory == "active": + # 16 cases / 66 tasks: two full (9 other each => 18), fourteen core-only. + n_cases = 16 + extra_plan = {0: other, 1: other} + elif inventory == "staged": + # 18 cases / 78 tasks: two full (9 other) + two partial (3 other) => 24 other. + n_cases = 18 + extra_plan = {0: other, 1: other, 2: other[:3], 3: other[:3]} + else: + raise ValueError(f"unknown inventory {inventory!r}") + + cases = [] + for idx in range(n_cases): + cid = f"case{idx:02d}" + procs = ["card", "controlsd", "lagd"] + list(extra_plan.get(idx, [])) + source = f"https://example.test/rlogs/{cid}.zst" if executable else "" + case = { + "case_id": cid, + "car_brand": f"BRAND{idx}", + "source": source, + "source_sha256": ("1" * 64) if pin_sources and executable else None, + "source_bytes": 16 if pin_sources and executable else None, + "processes": procs, + "params_digest": "2" * 64, + "custom_params": {}, + "executable": bool(executable and source), + } + cases.append(case) + return cases + + +def _inventory_from_cases(cases: list[dict], inventory: str = "staged") -> dict: + contract = v.INVENTORY_CONTRACTS[inventory] + expected_cases = contract["expected_cases"] + expected_tasks = contract["expected_tasks"] + partition = dict(contract["partition"]) + allowed = _allowed_processes() + task_ids = [] + for case in cases: + for proc in case["processes"]: + task_ids.append(f"{case['case_id']}:{proc}") + assert len(cases) == expected_cases + assert len(task_ids) == expected_tasks + sorted_cases = sorted(cases, key=lambda c: c["case_id"]) + sources_payload = [ + { + "case_id": c["case_id"], + "source": c["source"], + "source_bytes": c["source_bytes"], + "source_sha256": c["source_sha256"], + } + for c in sorted_cases + ] + params_payload = [{"case_id": c["case_id"], "params_digest": c["params_digest"]} for c in sorted_cases] + return { + "schema_version": 1, + "inventory": inventory, + "expected_cases": expected_cases, + "expected_tasks": expected_tasks, + "partition": partition, + "allowed_processes": allowed, + "cases": cases, + "task_ids": task_ids, + "expected_sources_digest": _sha256(_canonical(sources_payload)), + "expected_params_digest": _sha256(_canonical(params_payload)), + } + + +def _write_release( + release: Path, + cases: list[dict], + *, + opendbc_sha: str = OPENDBC_SHA, + previous_accepted_tag: str = "", +) -> str: + release.mkdir(parents=True, exist_ok=True) + (release / "ref_commit").write_text(SOURCE_SHA + "\n", encoding="utf-8") + refs = {} + for case in cases: + for proc in case["processes"]: + task_id = f"{case['case_id']}:{proc}" + filename = f"{case['case_id']}__{proc}__{SOURCE_SHA}.zst" + payload = f"{task_id}\n".encode() + (release / filename).write_bytes(payload) + refs[task_id] = { + "filename": filename, + "size": len(payload), + "sha256": _sha256(payload), + "source": case["source"], + "source_sha256": case["source_sha256"], + "source_bytes": case["source_bytes"], + "params_digest": case["params_digest"], + } + sorted_cases = sorted((v.case_identity(c) for c in cases), key=lambda c: c["case_id"]) + sources_payload = [ + { + "case_id": c["case_id"], + "source": c["source"], + "source_bytes": c["source_bytes"], + "source_sha256": c["source_sha256"], + } + for c in sorted_cases + ] + params_payload = [{"case_id": c["case_id"], "params_digest": c["params_digest"]} for c in sorted_cases] + manifest = { + "schema_version": 1, + "cases": sorted_cases, + "refs": {k: refs[k] for k in sorted(refs)}, + "openpilot_sha": SOURCE_SHA, + "opendbc_sha": opendbc_sha, + "sources_digest": _sha256(_canonical(sources_payload)), + "params_digest": _sha256(_canonical(params_payload)), + "previous_accepted_tag": previous_accepted_tag, + } + raw = _canonical(manifest) + (release / "manifest.json").write_bytes(raw) + return _sha256(raw) + + +def test_current_staged_inventory_is_rejected_at_publish_boundary(): + trusted = json.loads(STAGED_INVENTORY.read_text(encoding="utf-8")) + with pytest.raises(SystemExit, match="publication requires"): + v.require_publishable_inventory(trusted) + + +def test_validate_release_fails_closed_on_pending_repo_inventory(tmp_path: Path): + # Ignore synthetic cases; exercise the real checked-in pending inventory path. + inv_path = STAGED_INVENTORY + release = tmp_path / "release" + release.mkdir() + (release / "ref_commit").write_text(SOURCE_SHA + "\n", encoding="utf-8") + (release / "manifest.json").write_text("{}\n", encoding="utf-8") + trusted = v.load_trusted_inventory(inv_path) + with pytest.raises(SystemExit, match="publication requires"): + v.validate_release( + release, + trusted=trusted, + source_sha=SOURCE_SHA, + operation="publish", + expected_manifest_sha256="d" * 64, + rollback_tag=None, + expected_opendbc_sha=OPENDBC_SHA, + ) + + +def test_happy_path_accepts_fully_pinned_inventory(tmp_path: Path): + cases = _build_cases(executable=True, pin_sources=True) + inventory = _inventory_from_cases(cases) + inv_path = tmp_path / "inventory.json" + inv_path.write_bytes(_canonical(inventory)) + release = tmp_path / "release" + manifest_sha = _write_release(release, cases, opendbc_sha=OPENDBC_SHA) + trusted = v.load_trusted_inventory(inv_path) + result = v.validate_release( + release, + trusted=trusted, + source_sha=SOURCE_SHA, + operation="publish", + expected_manifest_sha256=manifest_sha, + rollback_tag=None, + expected_opendbc_sha=OPENDBC_SHA, + ) + assert result["release_source_sha"] == SOURCE_SHA + assert result["release_manifest_sha256"] == manifest_sha + assert result["release_tag"] == f"process-replay/v1/{SOURCE_SHA}-{manifest_sha[:12]}" + + +def test_valid_active_inventory_loads(tmp_path: Path): + cases = _build_cases("active", executable=True, pin_sources=True) + inventory = _inventory_from_cases(cases, inventory="active") + inv_path = tmp_path / "active_inventory.json" + inv_path.write_bytes(_canonical(inventory)) + trusted = v.load_trusted_inventory(inv_path) + assert trusted["inventory"] == "active" + assert trusted["expected_cases"] == 16 + assert trusted["expected_tasks"] == 66 + assert trusted["partition"] == {"card": 16, "controlsd": 16, "lagd": 16, "other": 18} + + +def test_active_declared_count_or_partition_mismatch_rejected(tmp_path: Path): + cases = _build_cases("active") + inventory = _inventory_from_cases(cases, inventory="active") + + bad_counts = dict(inventory) + bad_counts["expected_cases"] = 18 + bad_counts["expected_tasks"] = 78 + path_counts = tmp_path / "bad_counts.json" + path_counts.write_bytes(_canonical(bad_counts)) + with pytest.raises(SystemExit, match="must declare 16 cases / 66 tasks for inventory=active"): + v.load_trusted_inventory(path_counts) + + bad_partition = dict(inventory) + bad_partition["partition"] = {"card": 18, "controlsd": 18, "lagd": 18, "other": 24} + path_part = tmp_path / "bad_partition.json" + path_part.write_bytes(_canonical(bad_partition)) + with pytest.raises(SystemExit, match="partition mismatch for inventory=active"): + v.load_trusted_inventory(path_part) + + cross = dict(inventory) + cross["inventory"] = "staged" + path_cross = tmp_path / "cross_label.json" + path_cross.write_bytes(_canonical(cross)) + with pytest.raises(SystemExit, match="must declare 18 cases / 78 tasks for inventory=staged"): + v.load_trusted_inventory(path_cross) + + +def test_archive_previous_accepted_tag_identity_accepted(tmp_path: Path): + cases = _build_cases("staged", executable=True, pin_sources=True) + inventory = _inventory_from_cases(cases, inventory="staged") + inv_path = tmp_path / "inventory.json" + inv_path.write_bytes(_canonical(inventory)) + archive_tag = f"process-replay/archive/{'f' * 40}" + release = tmp_path / "release" + manifest_sha = _write_release(release, cases, previous_accepted_tag=archive_tag) + trusted = v.load_trusted_inventory(inv_path) + result = v.validate_release( + release, + trusted=trusted, + source_sha=SOURCE_SHA, + operation="publish", + expected_manifest_sha256=manifest_sha, + rollback_tag=None, + expected_opendbc_sha=OPENDBC_SHA, + ) + assert result["release_manifest_sha256"] == manifest_sha + + +def test_ref_identity_fields_must_match_trusted_case(tmp_path: Path): + cases = _build_cases("staged", executable=True, pin_sources=True) + inventory = _inventory_from_cases(cases, inventory="staged") + inv_path = tmp_path / "inventory.json" + inv_path.write_bytes(_canonical(inventory)) + release = tmp_path / "release" + _write_release(release, cases) + manifest = json.loads((release / "manifest.json").read_text(encoding="utf-8")) + victim = next(iter(manifest["refs"])) + manifest["refs"][victim]["source_sha256"] = "e" * 64 + tampered = _canonical(manifest) + (release / "manifest.json").write_bytes(tampered) + trusted = v.load_trusted_inventory(inv_path) + with pytest.raises(SystemExit, match="ref source_sha256 diverges from trusted case"): + v.validate_release( + release, + trusted=trusted, + source_sha=SOURCE_SHA, + operation="publish", + expected_manifest_sha256=_sha256(tampered), + rollback_tag=None, + expected_opendbc_sha=OPENDBC_SHA, + ) + + +def test_opendbc_gitlink_mismatch_is_rejected(tmp_path: Path): + cases = _build_cases() + inventory = _inventory_from_cases(cases) + inv_path = tmp_path / "inventory.json" + inv_path.write_bytes(_canonical(inventory)) + release = tmp_path / "release" + manifest_sha = _write_release(release, cases, opendbc_sha=OTHER_OPENDBC) + trusted = v.load_trusted_inventory(inv_path) + with pytest.raises(SystemExit, match="opendbc_sha .* != trusted gitlink"): + v.validate_release( + release, + trusted=trusted, + source_sha=SOURCE_SHA, + operation="publish", + expected_manifest_sha256=manifest_sha, + rollback_tag=None, + expected_opendbc_sha=OPENDBC_SHA, + ) + + +def test_manifest_case_tamper_is_rejected(tmp_path: Path): + cases = _build_cases() + inventory = _inventory_from_cases(cases) + inv_path = tmp_path / "inventory.json" + inv_path.write_bytes(_canonical(inventory)) + release = tmp_path / "release" + _write_release(release, cases) + # Tamper one pinned source hash after the fact and rewrite canonical manifest. + manifest = json.loads((release / "manifest.json").read_text(encoding="utf-8")) + manifest["cases"][0]["source_sha256"] = "e" * 64 + # keep refs/digests stale on purpose + tampered = _canonical(manifest) + (release / "manifest.json").write_bytes(tampered) + trusted = v.load_trusted_inventory(inv_path) + with pytest.raises(SystemExit): + v.validate_release( + release, + trusted=trusted, + source_sha=SOURCE_SHA, + operation="publish", + expected_manifest_sha256=_sha256(tampered), + rollback_tag=None, + expected_opendbc_sha=OPENDBC_SHA, + ) + + +def test_ref_bytes_tamper_is_rejected(tmp_path: Path): + cases = _build_cases() + inventory = _inventory_from_cases(cases) + inv_path = tmp_path / "inventory.json" + inv_path.write_bytes(_canonical(inventory)) + release = tmp_path / "release" + manifest_sha = _write_release(release, cases) + # Corrupt one ref payload without updating manifest metadata. + victim = next(release.glob(f"*__card__{SOURCE_SHA}.zst")) + victim.write_bytes(b"tampered-ref-bytes") + trusted = v.load_trusted_inventory(inv_path) + with pytest.raises(SystemExit, match="(size mismatch|hash mismatch)"): + v.validate_release( + release, + trusted=trusted, + source_sha=SOURCE_SHA, + operation="publish", + expected_manifest_sha256=manifest_sha, + rollback_tag=None, + expected_opendbc_sha=OPENDBC_SHA, + ) + + +def test_non_executable_inventory_rejected(): + cases = _build_cases(executable=False, pin_sources=False) + inventory = _inventory_from_cases(cases) + with pytest.raises(SystemExit, match="executable=true"): + v.require_publishable_inventory(inventory) + + +def test_workflow_generates_only_current_active_inventory(): + workflow = WORKFLOW_PATH.read_text(encoding="utf-8") + assert "generate-active" in workflow + assert "generate-staged" not in workflow + assert "CONTROLLER_REPO" not in workflow + assert "NAP_CI_CONTROLLER_ARTIFACT_READ_TOKEN" not in workflow + assert 'EXPECTED_TASKS: "66"' in workflow + assert 'github.ref == \'refs/heads/nap-dev\'' in workflow + assert 'EXPECTED_WORKFLOW_REF="${SOURCE_REPO}/.github/workflows/process_replay_refs.yaml@refs/heads/nap-dev"' in workflow + + +def test_workflow_rejects_unsafe_downloaded_artifact_layouts(): + workflow = WORKFLOW_PATH.read_text(encoding="utf-8") + assert "unexpected candidate top-level entry" in workflow + assert "path traversal in candidate" in workflow + assert "symlink forbidden in candidate" in workflow + assert "non-regular candidate member" in workflow + assert "nested release path forbidden" in workflow + + +def test_workflow_binds_same_run_review_proof_and_opendbc_gitlink(): + workflow = WORKFLOW_PATH.read_text(encoding="utf-8") + assert "handoff-meta.json" in workflow + assert "compare" in workflow and "results.json" in workflow + assert "review proof pass count must be {expected_tasks}" in workflow + assert "workflow_run_id" in workflow + assert "GITHUB_RUN_ID" in workflow + assert "HEAD:opendbc_repo" in workflow + assert "expected_ids = sorted(trusted_ids)" in workflow + assert "len(set(trusted_ids)) != expected_tasks" in workflow + assert "path: .process-replay-publish-release" in workflow + assert "--release-dir .process-replay-publish-release" in workflow + assert 'cp -a "${GITHUB_WORKSPACE}/.process-replay-publish-release/." .' in workflow + assert "--expected-opendbc-sha" in workflow + + +def test_workflow_preserves_same_source_no_op_and_atomic_publication(): + workflow = WORKFLOW_PATH.read_text(encoding="utf-8") + assert 'CURRENT_REF_COMMIT}" == "${SOURCE_SHA}' in workflow + assert "manifest.json?ref=${PREVIOUS_HEAD}" in workflow + assert "previous_accepted_tag" in workflow + assert "git push --atomic" in workflow + assert '--force-with-lease="refs/heads/${ARTIFACTS_BRANCH}:${CAPTURED_HEAD}"' in workflow + + +def test_zip_extractor_snippet_rejects_symlink_member(tmp_path: Path): + """Exercise the same mode checks the workflow embeds before extraction.""" + zpath = tmp_path / "cand.zip" + with zipfile.ZipFile(zpath, "w") as zf: + info = zipfile.ZipInfo("release/evil.zst") + # symlink mode + info.external_attr = (0o120777 & 0xFFFF) << 16 + zf.writestr(info, b"target") + + S_IFMT = 0o170000 + S_IFREG = 0o100000 + with zipfile.ZipFile(zpath) as zf: + for info in zf.infolist(): + mode = (info.external_attr >> 16) & 0xFFFF + ftype = mode & S_IFMT + assert ftype not in (0, S_IFREG) diff --git a/.github/ci/validate_process_replay_release.py b/.github/ci/validate_process_replay_release.py new file mode 100755 index 00000000000000..8b664736722660 --- /dev/null +++ b/.github/ci/validate_process_replay_release.py @@ -0,0 +1,454 @@ +#!/usr/bin/env python3 +"""Fail-closed validation of a process-replay release tree. + +Trusted inventory is loaded from the protected nap-dev checkout (GITHUB_SHA) +under the exact active or staged contract declared by the inventory itself. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import sys +from pathlib import Path +from typing import Any, Never + +REQUIRED_MANIFEST_KEYS = ( + "schema_version", + "cases", + "refs", + "openpilot_sha", + "opendbc_sha", + "sources_digest", + "params_digest", + "previous_accepted_tag", +) +REQUIRED_CASE_KEYS = ( + "case_id", + "car_brand", + "source", + "source_sha256", + "source_bytes", + "processes", + "params_digest", + "custom_params", + "executable", +) +REQUIRED_REF_KEYS = ("filename", "size", "sha256", "source", "source_sha256", "source_bytes", "params_digest") +CASE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$") +PROC_RE = re.compile(r"^[a-z0-9_]+$") +SHA40_RE = re.compile(r"^[0-9a-f]{40}$") +SHA64_RE = re.compile(r"^[0-9a-f]{64}$") +TAG_RE = re.compile(r"^process-replay/v1/([0-9a-f]{40})-([0-9a-f]{12})$") +ARCHIVE_TAG_RE = re.compile(r"^process-replay/archive/([0-9a-f]{40})$") +CORE_PROCS = frozenset({"card", "controlsd", "lagd"}) + +# Exact trusted inventory contracts. Counts, partitions, and labels are fail-closed. +INVENTORY_CONTRACTS: dict[str, dict[str, Any]] = { + "active": { + "expected_cases": 16, + "expected_tasks": 66, + "partition": {"card": 16, "controlsd": 16, "lagd": 16, "other": 18}, + }, + "staged": { + "expected_cases": 18, + "expected_tasks": 78, + "partition": {"card": 18, "controlsd": 18, "lagd": 18, "other": 24}, + }, +} + + +def die(msg: str) -> Never: + raise SystemExit(f"validate_process_replay_release: {msg}") + + +def canonical_json(obj: Any) -> bytes: + return (json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n").encode("utf-8") + + +def load_trusted_inventory(path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink(): + die(f"trusted inventory missing or symlink: {path}") + raw = path.read_bytes() + try: + inventory = json.loads(raw.decode("utf-8")) + except json.JSONDecodeError as exc: + die(f"trusted inventory is not valid JSON: {exc}") + if not isinstance(inventory, dict): + die("trusted inventory must be an object") + if inventory.get("schema_version") != 1: + die("trusted inventory schema_version must be 1") + label = inventory.get("inventory") + contract = INVENTORY_CONTRACTS.get(label) if isinstance(label, str) else None + if contract is None: + die(f"trusted inventory must declare inventory as one of {sorted(INVENTORY_CONTRACTS)}") + expected_cases = contract["expected_cases"] + expected_tasks = contract["expected_tasks"] + expected_partition = contract["partition"] + if inventory.get("expected_cases") != expected_cases or inventory.get("expected_tasks") != expected_tasks: + die(f"trusted inventory must declare {expected_cases} cases / {expected_tasks} tasks for inventory={label}") + partition = inventory.get("partition") + if partition != expected_partition: + die(f"trusted inventory partition mismatch for inventory={label}: {partition}") + cases = inventory.get("cases") + task_ids = inventory.get("task_ids") + allowed = inventory.get("allowed_processes") + if not isinstance(cases, list) or len(cases) != expected_cases: + die(f"trusted inventory cases must be a list of {expected_cases}") + if not isinstance(task_ids, list) or len(task_ids) != expected_tasks: + die(f"trusted inventory task_ids must be a list of {expected_tasks}") + if not isinstance(allowed, list) or not all(isinstance(p, str) for p in allowed): + die("trusted inventory allowed_processes must be a string list") + if list(allowed) != sorted(allowed): + die("trusted inventory allowed_processes must be sorted") + derived: list[str] = [] + seen_cases: set[str] = set() + for case in cases: + if not isinstance(case, dict): + die("trusted case must be an object") + if set(case) != set(REQUIRED_CASE_KEYS): + die(f"trusted case keys must be exactly {REQUIRED_CASE_KEYS}") + cid = case["case_id"] + if not isinstance(cid, str) or not CASE_ID_RE.fullmatch(cid): + die(f"trusted case_id invalid: {cid!r}") + if cid in seen_cases: + die(f"duplicate trusted case_id: {cid}") + seen_cases.add(cid) + procs = case["processes"] + if not isinstance(procs, list) or not procs or len(set(procs)) != len(procs): + die(f"trusted processes invalid for {cid}") + for proc in procs: + if not isinstance(proc, str) or not PROC_RE.fullmatch(proc) or proc not in allowed: + die(f"trusted process rejected for {cid}: {proc!r}") + derived.append(f"{cid}:{proc}") + if derived != task_ids: + die("trusted task_ids do not match derived case/process inventory") + if len(set(task_ids)) != expected_tasks: + die("trusted task_ids must be unique") + sorted_cases = sorted(cases, key=lambda c: c["case_id"]) + sources_payload = [ + { + "case_id": c["case_id"], + "source": c["source"], + "source_bytes": c["source_bytes"], + "source_sha256": c["source_sha256"], + } + for c in sorted_cases + ] + params_payload = [{"case_id": c["case_id"], "params_digest": c["params_digest"]} for c in sorted_cases] + sources_digest = hashlib.sha256(canonical_json(sources_payload)).hexdigest() + params_digest = hashlib.sha256(canonical_json(params_payload)).hexdigest() + if inventory.get("expected_sources_digest") != sources_digest: + die("trusted expected_sources_digest mismatch against recomputed full sorted case records") + if inventory.get("expected_params_digest") != params_digest: + die("trusted expected_params_digest mismatch against recomputed full sorted case records") + counts = {"card": 0, "controlsd": 0, "lagd": 0, "other": 0} + for task_id in task_ids: + process = task_id.split(":", 1)[1] + if process in CORE_PROCS: + counts[process] += 1 + else: + counts["other"] += 1 + if counts != partition: + die(f"trusted partition derived mismatch: {counts}") + return inventory + + +def list_release_files(release: Path) -> list[str]: + if release.is_symlink() or not release.is_dir(): + die("release/ must be a real directory") + rel_files: list[str] = [] + for path in sorted(release.rglob("*")): + rel = path.relative_to(release).as_posix() + if ".." in Path(rel).parts or rel.startswith("/"): + die(f"illegal path {rel}") + if path.is_symlink(): + die(f"symlink forbidden: {rel}") + if path.is_dir(): + continue + if not path.is_file(): + die(f"non-regular file forbidden: {rel}") + if "/" in rel: + die(f"nested release paths forbidden: {rel}") + rel_files.append(rel) + return rel_files + + +def case_identity(case: dict[str, Any]) -> dict[str, Any]: + return {key: case[key] for key in REQUIRED_CASE_KEYS} + + +def require_publishable_case(case: dict[str, Any], *, where: str) -> None: + """Publication boundary: every case must be executable with pinned source bytes.""" + cid = case.get("case_id", "") + if case.get("executable") is not True: + die(f"{where} case {cid}: publication requires executable=true (descriptors not finalized)") + source = case.get("source") + if not isinstance(source, str) or not source.strip(): + die(f"{where} case {cid}: publication requires non-empty source locator/URL") + source_bytes = case.get("source_bytes") + if not isinstance(source_bytes, int) or isinstance(source_bytes, bool) or source_bytes <= 0: + die(f"{where} case {cid}: publication requires positive source_bytes") + source_sha256 = case.get("source_sha256") + if not isinstance(source_sha256, str) or not SHA64_RE.fullmatch(source_sha256): + die(f"{where} case {cid}: publication requires 64 lowercase hex source_sha256") + + +def require_publishable_inventory(trusted: dict[str, Any]) -> None: + """Fail closed on pending/stale inventory until fixture descriptors are finalized.""" + cases = trusted.get("cases") + if not isinstance(cases, list): + die("trusted inventory cases missing") + for case in cases: + if not isinstance(case, dict): + die("trusted case must be an object") + require_publishable_case(case, where="trusted inventory") + + +def validate_release( + release: Path, + *, + trusted: dict[str, Any], + source_sha: str, + operation: str, + expected_manifest_sha256: str | None, + rollback_tag: str | None, + expected_opendbc_sha: str | None, +) -> dict[str, str]: + if not SHA40_RE.fullmatch(source_sha) or source_sha != source_sha.lower(): + die("source_sha must be lowercase 40-hex") + if operation not in {"publish", "rollback"}: + die(f"unknown operation {operation}") + + # Publication requires every trusted case to be executable with pinned source digests. + require_publishable_inventory(trusted) + + expected_cases = int(trusted["expected_cases"]) + expected_tasks = int(trusted["expected_tasks"]) + partition = dict(trusted["partition"]) + allowed_processes = set(trusted["allowed_processes"]) + trusted_cases = {c["case_id"]: case_identity(c) for c in trusted["cases"]} + trusted_task_ids = list(trusted["task_ids"]) + trusted_task_set = set(trusted_task_ids) + trusted_sources_digest = trusted["expected_sources_digest"] + trusted_params_digest = trusted["expected_params_digest"] + + rel_files = list_release_files(release) + if "ref_commit" not in rel_files or "manifest.json" not in rel_files: + die("release tree missing ref_commit or manifest.json") + zsts = [name for name in rel_files if name.endswith(".zst")] + extras = [name for name in rel_files if name not in {"ref_commit", "manifest.json"} and not name.endswith(".zst")] + if extras: + die(f"unexpected release files: {extras}") + if len(zsts) != expected_tasks: + die(f"expected {expected_tasks} zst refs, found {len(zsts)}") + + ref_commit = (release / "ref_commit").read_text(encoding="utf-8").strip() + if ref_commit != source_sha: + die(f"ref_commit {ref_commit} != source_sha {source_sha}") + + manifest_bytes = (release / "manifest.json").read_bytes() + if not manifest_bytes.endswith(b"\n"): + die("manifest.json must end with LF") + manifest_sha = hashlib.sha256(manifest_bytes).hexdigest() + if operation == "publish": + if not expected_manifest_sha256 or not SHA64_RE.fullmatch(expected_manifest_sha256): + die("publish requires expected manifest sha256") + if manifest_sha != expected_manifest_sha256: + die("manifest sha256 mismatch against dispatch input") + + try: + manifest = json.loads(manifest_bytes.decode("utf-8")) + except json.JSONDecodeError as exc: + die(f"manifest.json is not valid JSON: {exc}") + if not isinstance(manifest, dict): + die("manifest must be an object") + if canonical_json(manifest) != manifest_bytes: + die("manifest.json is not canonical sorted UTF-8 JSON with LF") + if set(manifest) != set(REQUIRED_MANIFEST_KEYS): + die(f"manifest keys must be exactly {REQUIRED_MANIFEST_KEYS}; got {sorted(manifest)}") + if manifest["schema_version"] != 1: + die("manifest schema_version must be integer 1") + if manifest["openpilot_sha"] != source_sha: + die("manifest openpilot_sha must equal source_sha") + if not isinstance(manifest["opendbc_sha"], str) or not SHA40_RE.fullmatch(manifest["opendbc_sha"]): + die("opendbc_sha must be 40 lowercase hex") + if not expected_opendbc_sha or not SHA40_RE.fullmatch(expected_opendbc_sha): + die("expected_opendbc_sha must be lowercase 40-hex from trusted gitlink") + if manifest["opendbc_sha"] != expected_opendbc_sha: + die(f"manifest opendbc_sha {manifest['opendbc_sha']} != trusted gitlink {expected_opendbc_sha}") + previous = manifest["previous_accepted_tag"] + if previous != "" and not ( + isinstance(previous, str) + and (TAG_RE.fullmatch(previous) or ARCHIVE_TAG_RE.fullmatch(previous)) + ): + die("previous_accepted_tag must be empty, a process-replay/v1 release tag, or a process-replay/archive SHA tag") + + cases = manifest["cases"] + refs = manifest["refs"] + if not isinstance(cases, list) or not isinstance(refs, dict): + die("manifest must contain cases list and refs object") + if len(cases) != expected_cases: + die(f"expected {expected_cases} cases, found {len(cases)}") + if len(refs) != expected_tasks: + die(f"expected {expected_tasks} refs, found {len(refs)}") + + case_ids: list[str] = [] + for case in cases: + if not isinstance(case, dict): + die("manifest case must be an object") + if set(case) != set(REQUIRED_CASE_KEYS): + die(f"manifest case keys must be exactly {REQUIRED_CASE_KEYS}") + cid = case["case_id"] + if not isinstance(cid, str) or not CASE_ID_RE.fullmatch(cid): + die(f"invalid case_id in manifest: {cid!r}") + require_publishable_case(case, where="manifest") + case_ids.append(cid) + trusted_case = trusted_cases.get(cid) + if trusted_case is None: + die(f"manifest case_id not in trusted inventory: {cid}") + if case_identity(case) != trusted_case: + die(f"manifest case identity diverges from trusted inventory: {cid}") + if len(set(case_ids)) != expected_cases: + die("case_id values must be unique") + if case_ids != sorted(case_ids): + die("cases must be sorted by case_id") + if set(case_ids) != set(trusted_cases): + die("manifest case set must equal trusted inventory") + + sorted_cases = sorted((case_identity(c) for c in cases), key=lambda c: c["case_id"]) + sources_payload = [ + { + "case_id": c["case_id"], + "source": c["source"], + "source_bytes": c["source_bytes"], + "source_sha256": c["source_sha256"], + } + for c in sorted_cases + ] + params_payload = [{"case_id": c["case_id"], "params_digest": c["params_digest"]} for c in sorted_cases] + sources_digest = hashlib.sha256(canonical_json(sources_payload)).hexdigest() + params_digest = hashlib.sha256(canonical_json(params_payload)).hexdigest() + if manifest["sources_digest"] != sources_digest or sources_digest != trusted_sources_digest: + die("sources_digest mismatch against recomputed full sorted case records / trusted inventory") + if manifest["params_digest"] != params_digest or params_digest != trusted_params_digest: + die("params_digest mismatch against recomputed full sorted case records / trusted inventory") + + if list(refs.keys()) != sorted(refs.keys()): + die("refs must be sorted by task key") + if set(refs) != trusted_task_set: + die("manifest refs task set must equal trusted task inventory") + + counts = {"card": 0, "controlsd": 0, "lagd": 0, "other": 0} + name_re = re.compile(rf"^[a-z0-9][a-z0-9-]*__[a-z0-9_]+__{re.escape(source_sha)}\.zst$") + for task_id, meta in refs.items(): + if not isinstance(task_id, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]*:[a-z0-9_]+", task_id): + die(f"bad task id {task_id}") + if not isinstance(meta, dict) or set(meta) != set(REQUIRED_REF_KEYS): + die(f"ref metadata keys must be exactly {REQUIRED_REF_KEYS} for {task_id}") + case_id, process = task_id.split(":", 1) + if case_id not in trusted_cases: + die(f"ref case_id not in trusted cases: {case_id}") + if process not in allowed_processes: + die(f"unknown process rejected: {process}") + if process not in trusted_cases[case_id]["processes"]: + die(f"process {process} not in trusted case {case_id}") + trusted_case = trusted_cases[case_id] + if meta.get("source") != trusted_case["source"]: + die(f"ref source diverges from trusted case for {task_id}") + if meta.get("source_sha256") != trusted_case["source_sha256"]: + die(f"ref source_sha256 diverges from trusted case for {task_id}") + if meta.get("source_bytes") != trusted_case["source_bytes"]: + die(f"ref source_bytes diverges from trusted case for {task_id}") + if meta.get("params_digest") != trusted_case["params_digest"]: + die(f"ref params_digest diverges from trusted case for {task_id}") + if process in CORE_PROCS: + counts[process] += 1 + else: + counts["other"] += 1 + filename = meta["filename"] + size = meta["size"] + digest = meta["sha256"] + if not isinstance(filename, str) or filename not in zsts: + die(f"ref filename missing from tree: {filename}") + if not name_re.fullmatch(filename): + die(f"ref filename must encode source_sha: {filename}") + if filename != f"{case_id}__{process}__{source_sha}.zst": + die(f"filename does not match task identity: {filename}") + if not isinstance(size, int) or isinstance(size, bool) or size < 0: + die(f"invalid size for {filename}") + if not isinstance(digest, str) or not SHA64_RE.fullmatch(digest): + die(f"invalid sha256 for {filename}") + data = (release / filename).read_bytes() + if size != len(data): + die(f"size mismatch for {filename}") + actual = hashlib.sha256(data).hexdigest() + if digest != actual: + die(f"hash mismatch for {filename}") + + if counts != partition: + die(f"partition mismatch: {counts} != {partition}") + if set(zsts) != {refs[task_id]["filename"] for task_id in refs}: + die("zst set does not equal manifest filenames") + + release_tag = f"process-replay/v1/{source_sha}-{manifest_sha[:12]}" + if operation == "rollback": + if not rollback_tag: + die("rollback requires rollback_tag") + if not TAG_RE.fullmatch(rollback_tag): + die("rollback_tag must match process-replay/v1/<40-hex>-<12-hex>") + if rollback_tag != release_tag: + die(f"rollback_tag {rollback_tag} is not cryptographically bound to fetched manifest {release_tag}") + + return { + "release_source_sha": source_sha, + "release_manifest_sha256": manifest_sha, + "release_tag": release_tag, + "release_previous_accepted_tag": previous, + } + + +def write_github_output(result: dict[str, str]) -> None: + out_path = os.environ.get("GITHUB_OUTPUT") + if not out_path: + return + with open(out_path, "a", encoding="utf-8") as handle: + for key, value in result.items(): + handle.write(f"{key}={value}\n") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--release-dir", required=True, type=Path) + parser.add_argument("--trusted-inventory", required=True, type=Path) + parser.add_argument("--source-sha", required=True) + parser.add_argument("--operation", required=True, choices=("publish", "rollback")) + parser.add_argument("--expected-manifest-sha256", default="") + parser.add_argument("--rollback-tag", default="") + parser.add_argument( + "--expected-opendbc-sha", + required=True, + help="Trusted opendbc_repo gitlink SHA for source_sha (lowercase 40-hex)", + ) + args = parser.parse_args() + + trusted = load_trusted_inventory(args.trusted_inventory) + result = validate_release( + args.release_dir, + trusted=trusted, + source_sha=args.source_sha.strip().lower(), + operation=args.operation, + expected_manifest_sha256=(args.expected_manifest_sha256 or None), + rollback_tag=(args.rollback_tag or None), + expected_opendbc_sha=args.expected_opendbc_sha.strip().lower(), + ) + write_github_output(result) + print(f"validated release tree source_sha={result['release_source_sha']} tasks={trusted['expected_tasks']} tag={result['release_tag']}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/labeler.yaml b/.github/labeler.yaml index db1f976da839a5..63d41d5b73506c 100644 --- a/.github/labeler.yaml +++ b/.github/labeler.yaml @@ -1,6 +1,6 @@ CI / testing: - changed-files: - - any-glob-to-all-files: "{.github/**,**/test_*,Jenkinsfile}" + - any-glob-to-all-files: "{.github/**,**/test_*,**/test/**,Jenkinsfile}" car: - changed-files: @@ -12,7 +12,7 @@ simulation: ui: - changed-files: - - any-glob-to-all-files: 'selfdrive/ui/**' + - any-glob-to-all-files: '{selfdrive/assets/**,selfdrive/ui/**,system/ui/**}' tools: - changed-files: diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 9e0c54218e24ea..2b4a5ed48f1b14 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -44,7 +44,7 @@ Explain how you tested this bug fix. **Checklist** -- [ ] added entry to CAR in selfdrive/car/*/values.py and ran `selfdrive/opcar/docs.py` to generate new docs +- [ ] added entry to CAR in selfdrive/car/*/values.py and ran `selfdrive/car/docs.py` to generate new docs - [ ] test route added to [routes.py](https://github.com/commaai/openpilot/blob/master/selfdrive/car/tests/routes.py) - [ ] route with openpilot: - [ ] route with stock system: diff --git a/.github/workflows/auto-cache/action.yaml b/.github/workflows/auto-cache/action.yaml deleted file mode 100644 index e99c46e3c3f533..00000000000000 --- a/.github/workflows/auto-cache/action.yaml +++ /dev/null @@ -1,49 +0,0 @@ -name: 'automatically cache based on current runner' - -inputs: - path: - description: 'path to cache' - required: true - key: - description: 'key' - required: true - restore-keys: - description: 'restore-keys' - required: true - save: - description: 'whether to save the cache' - default: 'false' - required: false - -runs: - using: "composite" - steps: - - name: setup namespace cache - if: ${{ contains(runner.name, 'nsc') }} - uses: namespacelabs/nscloud-cache-action@v1 - with: - path: ${{ inputs.path }} - - - name: setup github cache - if: ${{ !contains(runner.name, 'nsc') && inputs.save != 'false' }} - uses: 'actions/cache@v4' - with: - path: ${{ inputs.path }} - key: ${{ inputs.key }} - restore-keys: ${{ inputs.restore-keys }} - - - name: setup github cache - if: ${{ !contains(runner.name, 'nsc') && inputs.save == 'false' }} - uses: 'actions/cache/restore@v4' - with: - path: ${{ inputs.path }} - key: ${{ inputs.key }} - restore-keys: ${{ inputs.restore-keys }} - - # make the directory manually in case we didn't get a hit, so it doesn't fail on future steps - - id: scons-cache-setup - shell: bash - run: | - mkdir -p ${{ inputs.path }} - sudo chmod -R 777 ${{ inputs.path }} - sudo chown -R $USER ${{ inputs.path }} diff --git a/.github/workflows/auto_pr_review.yaml b/.github/workflows/auto_pr_review.yaml index eaaca560605f92..99c3a258c649a3 100644 --- a/.github/workflows/auto_pr_review.yaml +++ b/.github/workflows/auto_pr_review.yaml @@ -1,7 +1,7 @@ name: "PR review" on: pull_request_target: - types: [opened, reopened, synchronize, edited, edited] + types: [opened, reopened, synchronize, edited] jobs: labeler: @@ -11,12 +11,12 @@ jobs: pull-requests: write runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: submodules: false # Label PRs - - uses: actions/labeler@v5.0.0 + - uses: actions/labeler@v6 with: dot: true configuration-path: .github/labeler.yaml @@ -33,21 +33,3 @@ jobs: change-to: ${{ github.base_ref }} already-exists-action: close_this already-exists-comment: "Your PR should be made against the `master` branch" - - # Welcome comment - - name: "First timers PR" - uses: actions/first-interaction@v1 - if: github.event.pull_request.head.repo.full_name != 'commaai/openpilot' - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - pr-message: | - - Thanks for contributing to openpilot! In order for us to review your PR as quickly as possible, check the following: - * Convert your PR to a draft unless it's ready to review - * Read the [contributing docs](https://github.com/commaai/openpilot/blob/master/docs/CONTRIBUTING.md) - * Before marking as "ready for review", ensure: - * the goal is clearly stated in the description - * all the tests are passing - * the change is [something we merge](https://github.com/commaai/openpilot/blob/master/docs/CONTRIBUTING.md#what-gets-merged) - * include a route or your device' dongle ID if relevant - diff --git a/.github/workflows/badges.yaml b/.github/workflows/badges.yaml deleted file mode 100644 index 63ee736dcab84b..00000000000000 --- a/.github/workflows/badges.yaml +++ /dev/null @@ -1,37 +0,0 @@ -name: badges -on: - schedule: - - cron: '0 * * * *' - workflow_dispatch: - -env: - BASE_IMAGE: openpilot-base - DOCKER_REGISTRY: ghcr.io/commaai - RUN: docker run --shm-size 2G -v $PWD:/tmp/openpilot -w /tmp/openpilot -e PYTHONPATH=/tmp/openpilot -e NUM_JOBS -e JOB_ID -e GITHUB_ACTION -e GITHUB_REF -e GITHUB_HEAD_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_RUN_ID -v $GITHUB_WORKSPACE/.ci_cache/scons_cache:/tmp/scons_cache -v $GITHUB_WORKSPACE/.ci_cache/comma_download_cache:/tmp/comma_download_cache -v $GITHUB_WORKSPACE/.ci_cache/openpilot_cache:/tmp/openpilot_cache $DOCKER_REGISTRY/$BASE_IMAGE:latest /bin/bash -c - -jobs: - badges: - name: create badges - runs-on: ubuntu-latest - if: github.repository == 'commaai/openpilot' - permissions: - contents: write - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Push badges - run: | - ${{ env.RUN }} "scons -j$(nproc) && python3 selfdrive/ui/translations/create_badges.py" - - rm .gitattributes - - git checkout --orphan badges - git rm -rf --cached . - git config user.email "badge-researcher@comma.ai" - git config user.name "Badge Researcher" - - git add translation_badge.svg - git commit -m "Add/Update badges" - git push -f origin HEAD diff --git a/.github/workflows/ci_weekly_report.yaml b/.github/workflows/ci_weekly_report.yaml deleted file mode 100644 index 9821283cb57442..00000000000000 --- a/.github/workflows/ci_weekly_report.yaml +++ /dev/null @@ -1,101 +0,0 @@ -name: weekly CI test report -on: - schedule: - - cron: '37 9 * * 1' # 9:37AM UTC -> 2:37AM PST every monday - workflow_dispatch: - inputs: - ci_runs: - description: 'The amount of runs to trigger in CI test report' -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - CI_RUNS: ${{ github.event.inputs.ci_runs || '50' }} - -jobs: - setup: - if: github.repository == 'commaai/openpilot' - runs-on: ubuntu-latest - outputs: - ci_runs: ${{ steps.ci_runs_setup.outputs.matrix }} - steps: - - id: ci_runs_setup - name: CI_RUNS=${{ env.CI_RUNS }} - run: | - matrix=$(python3 -c "import json; print(json.dumps({ 'run_number' : list(range(${{ env.CI_RUNS }})) }))") - echo "matrix=$matrix" >> $GITHUB_OUTPUT - - ci_matrix_run: - needs: [ setup ] - strategy: - fail-fast: false - matrix: ${{fromJSON(needs.setup.outputs.ci_runs)}} - uses: commaai/openpilot/.github/workflows/ci_weekly_run.yaml@master - with: - run_number: ${{ matrix.run_number }} - - report: - needs: [ci_matrix_run] - runs-on: ubuntu-latest - if: always() - steps: - - name: Get job results - uses: actions/github-script@v7 - id: get-job-results - with: - script: | - const jobs = await github - .paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt}/jobs", { - owner: "commaai", - repo: "${{ github.event.repository.name }}", - run_id: "${{ github.run_id }}", - attempt: "${{ github.run_attempt }}", - }) - var report = {} - jobs.slice(1, jobs.length-1).forEach(job => { - if (job.conclusion === "skipped") return; - const jobName = job.name.split(" / ")[2]; - const runRegex = /\((.*?)\)/; - const run = job.name.match(runRegex)[1]; - report[jobName] = report[jobName] || { successes: [], failures: [], canceled: [] }; - switch (job.conclusion) { - case "success": - report[jobName].successes.push({ "run_number": run, "link": job.html_url}); break; - case "failure": - report[jobName].failures.push({ "run_number": run, "link": job.html_url }); break; - case "canceled": - report[jobName].canceled.push({ "run_number": run, "link": job.html_url }); break; - } - }); - return JSON.stringify({"jobs": report}); - - - name: Add job results to summary - env: - JOB_RESULTS: ${{ fromJSON(steps.get-job-results.outputs.result) }} - run: | - cat <> template.html - - - - - - - - - - - {% for key in jobs.keys() %} - - - - - - {% endfor %} -
Job✅ Passing❌ Failure Details
{% for i in range(5) %}{% if i+1 <= (5 * jobs[key]["successes"]|length // ${{ env.CI_RUNS }}) %}🟩{% else %}🟥{% endif %}{% endfor%}{{ key }}{{ 100 * jobs[key]["successes"]|length // ${{ env.CI_RUNS }} }}%{% if jobs[key]["failures"]|length > 0 %}
{% for failure in jobs[key]["failures"] %}Log for run #{{ failure['run_number'] }}
{% endfor %}
{% else %}{% endif %}
- EOF - - pip install jinja2-cli - echo $JOB_RESULTS | jinja2 template.html > report.html - echo "# CI Test Report - ${{ env.CI_RUNS }} Runs" >> $GITHUB_STEP_SUMMARY - cat report.html >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/ci_weekly_run.yaml b/.github/workflows/ci_weekly_run.yaml deleted file mode 100644 index c3ce8c42da861e..00000000000000 --- a/.github/workflows/ci_weekly_run.yaml +++ /dev/null @@ -1,21 +0,0 @@ -name: weekly CI test run -on: - workflow_call: - inputs: - run_number: - required: true - type: string - -concurrency: - group: ci-run-${{ inputs.run_number }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - selfdrive_tests: - uses: commaai/openpilot/.github/workflows/selfdrive_tests.yaml@master - with: - run_number: ${{ inputs.run_number }} - tools_tests: - uses: commaai/openpilot/.github/workflows/tools_tests.yaml@master - with: - run_number: ${{ inputs.run_number }} diff --git a/.github/workflows/compile-openpilot/action.yaml b/.github/workflows/compile-openpilot/action.yaml deleted file mode 100644 index 4015746c0e3680..00000000000000 --- a/.github/workflows/compile-openpilot/action.yaml +++ /dev/null @@ -1,21 +0,0 @@ -name: 'compile openpilot' - -runs: - using: "composite" - steps: - - shell: bash - name: Build openpilot with all flags - run: | - ${{ env.RUN }} "scons -j$(nproc)" - ${{ env.RUN }} "release/check-dirty.sh" - - shell: bash - name: Cleanup scons cache and rebuild - run: | - ${{ env.RUN }} "rm -rf /tmp/scons_cache/* && \ - scons -j$(nproc) --cache-populate" - - name: Save scons cache - uses: actions/cache/save@v4 - if: github.ref == 'refs/heads/master' - with: - path: .ci_cache/scons_cache - key: scons-${{ runner.arch }}-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} diff --git a/.github/workflows/diff_report.yaml b/.github/workflows/diff_report.yaml new file mode 100644 index 00000000000000..2ddb8509449148 --- /dev/null +++ b/.github/workflows/diff_report.yaml @@ -0,0 +1,45 @@ +name: diff report + +on: + pull_request_target: + types: [opened, synchronize, reopened] + +jobs: + comment: + name: comment + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pull-requests: write + actions: read + steps: + - name: Wait for process replay + id: wait + continue-on-error: true + uses: lewagon/wait-on-check-action@v1.3.4 + with: + ref: ${{ github.event.pull_request.head.sha }} + check-name: process replay + repo-token: ${{ secrets.GITHUB_TOKEN }} + allowed-conclusions: success,failure + wait-interval: 20 + - name: Download diff + if: steps.wait.outcome == 'success' + uses: dawidd6/action-download-artifact@v6 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + workflow: tests.yaml + workflow_conclusion: '' + pr: ${{ github.event.number }} + name: diff_report_${{ github.event.number }} + path: . + allow_forks: true + - name: Comment on PR + if: steps.wait.outcome == 'success' + uses: thollander/actions-comment-pull-request@v2 + with: + filePath: diff_report.txt + comment_tag: diff_report + pr_number: ${{ github.event.number }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index 26b60ffec27670..f618c1bdf8936e 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -18,22 +18,23 @@ concurrency: jobs: docs: name: build docs - runs-on: ubuntu-latest - timeout-minutes: 1 + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 + - uses: commaai/timeout@v1 + + - uses: actions/checkout@v6 with: submodules: true # Build - name: Build docs run: | - # TODO: can we install just the "docs" dependency group without the normal deps? - pip install mkdocs - mkdocs build + git lfs pull + pip install zensical + python scripts/docs.py build # Push to docs.comma.ai - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 if: github.ref == 'refs/heads/master' && github.repository == 'commaai/openpilot' with: path: openpilot-docs diff --git a/.github/workflows/jenkins-pr-trigger.yaml b/.github/workflows/jenkins-pr-trigger.yaml index db1d5240188ae2..fdd26253fadd49 100644 --- a/.github/workflows/jenkins-pr-trigger.yaml +++ b/.github/workflows/jenkins-pr-trigger.yaml @@ -5,14 +5,54 @@ on: types: [created, edited] jobs: - # TODO: gc old branches in a separate job in this workflow + cleanup-branches: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Delete stale Jenkins branches + uses: actions/github-script@v8 + with: + script: | + const cutoff = Date.now() - 24 * 60 * 60 * 1000; + const prefixes = ['tmp-jenkins', '__jenkins']; + + for await (const response of github.paginate.iterator(github.rest.repos.listBranches, { + owner: context.repo.owner, + repo: context.repo.repo, + per_page: 100, + })) { + for (const branch of response.data) { + if (!prefixes.some(p => branch.name.startsWith(p))) continue; + + const { data: commit } = await github.rest.repos.getCommit({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: branch.commit.sha, + }); + + const commitDate = new Date(commit.commit.committer.date).getTime(); + if (commitDate < cutoff) { + console.log(`Deleting branch: ${branch.name} (last commit: ${commit.commit.committer.date})`); + await github.rest.git.deleteRef({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: `heads/${branch.name}`, + }); + } + } + } + scan-comments: runs-on: ubuntu-latest if: ${{ github.event.issue.pull_request }} + permissions: + contents: write + issues: write steps: - name: Check for trigger phrase id: check_comment - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | const triggerPhrase = "trigger-jenkins"; @@ -32,7 +72,7 @@ jobs: - name: Checkout repository if: steps.check_comment.outputs.result == 'true' - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: ref: refs/pull/${{ github.event.issue.number }}/head @@ -43,3 +83,14 @@ jobs: git config --global user.email "github-actions[bot]@users.noreply.github.com" git checkout -b tmp-jenkins-${{ github.event.issue.number }} GIT_LFS_SKIP_PUSH=1 git push -f origin tmp-jenkins-${{ github.event.issue.number }} + + - name: Delete trigger comment + if: steps.check_comment.outputs.result == 'true' && always() + uses: actions/github-script@v8 + with: + script: | + await github.rest.issues.deleteComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + }); diff --git a/.github/workflows/model_review.yaml b/.github/workflows/model_review.yaml new file mode 100644 index 00000000000000..2775dbc5743056 --- /dev/null +++ b/.github/workflows/model_review.yaml @@ -0,0 +1,42 @@ +name: "model review" + +on: + pull_request: + types: [opened, reopened, synchronize] + paths: + - 'selfdrive/modeld/models/*.onnx' + workflow_dispatch: + +jobs: + comment: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + if: github.repository == 'commaai/openpilot' + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + submodules: true + - name: Checkout master + uses: actions/checkout@v6 + with: + ref: master + path: base + - run: git lfs pull + - run: cd base && git lfs pull + + - name: scripts/reporter.py + id: report + run: | + echo "content<> $GITHUB_OUTPUT + echo "## Model Review" >> $GITHUB_OUTPUT + PYTHONPATH=${{ github.workspace }} MASTER_PATH=${{ github.workspace }}/base python scripts/reporter.py >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + - name: Post model report comment + uses: marocchino/sticky-pull-request-comment@baa7203ed60924babbe5dcd0ac8eae3b66ec5e16 + with: + header: model-review + message: ${{ steps.report.outputs.content }} \ No newline at end of file diff --git a/.github/workflows/prebuilt.yaml b/.github/workflows/prebuilt.yaml index d8963ec89f4f93..ecf1e8503aee57 100644 --- a/.github/workflows/prebuilt.yaml +++ b/.github/workflows/prebuilt.yaml @@ -6,7 +6,7 @@ on: env: DOCKER_LOGIN: docker login ghcr.io -u ${{ github.actor }} -p ${{ secrets.GITHUB_TOKEN }} - BUILD: selfdrive/test/docker_build.sh prebuilt + BUILD: selfdrive/test/docker_build.sh jobs: build_prebuilt: @@ -28,8 +28,8 @@ jobs: wait-interval: 30 running-workflow-name: 'build prebuilt' repo-token: ${{ secrets.GITHUB_TOKEN }} - check-regexp: ^((?!.*(build master-ci).*).)*$ - - uses: actions/checkout@v4 + check-regexp: ^((?!.*(build master-ci|create badges).*).)*$ + - uses: actions/checkout@v6 with: submodules: true - run: git lfs pull diff --git a/.github/workflows/process_replay_refs.yaml b/.github/workflows/process_replay_refs.yaml new file mode 100644 index 00000000000000..55649f2a7eeabf --- /dev/null +++ b/.github/workflows/process_replay_refs.yaml @@ -0,0 +1,892 @@ +# GitHub-hosted reference publisher only. Never runs on self-hosted infrastructure. +# generate-active builds and assembles refs on ubuntu-24.04; verify is fail-closed +# and execution-free against the trusted active inventory at GITHUB_SHA. +# The ci-artifacts write token is exposed only in the final push step. +name: process replay refs + +on: + workflow_dispatch: + inputs: + operation: + description: "generate-active refs on protected nap-dev, or rollback to a protected tag" + type: choice + options: + - generate-active + - rollback + default: generate-active + rollback_tag: + description: "Protected tag process-replay/v1/- for rollback" + required: false + type: string + +permissions: + contents: read + actions: write + +concurrency: + group: process-replay-refs + cancel-in-progress: false + +env: + SOURCE_REPO: NotAutopilot/openpilot + ARTIFACTS_REPO: NotAutopilot/ci-artifacts + ARTIFACTS_BRANCH: process-replay + TRUSTED_INVENTORY_PATH: .github/ci/process_replay_active_inventory.json + RELEASE_VALIDATOR: .github/ci/validate_process_replay_release.py + CANDIDATE_ARTIFACT_PREFIX: process-replay-candidate + EXPECTED_TASKS: "66" + +jobs: + # workflow_dispatch is discoverable on the default branch (nap-release). + # Retarget to the protected nap-dev workflow/ref before any publication work. + retarget-from-default: + name: Retarget nap-release dispatch to nap-dev + if: github.repository == 'NotAutopilot/openpilot' && github.ref == 'refs/heads/nap-release' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Invoke protected nap-dev workflow + env: + GH_TOKEN: ${{ github.token }} + OPERATION: ${{ inputs.operation }} + IN_ROLLBACK_TAG: ${{ inputs.rollback_tag }} + run: | + set -euo pipefail + case "${OPERATION}" in + generate-active|rollback) ;; + *) + echo "Invalid operation" >&2 + exit 1 + ;; + esac + ARGS=(--ref nap-dev -f "operation=${OPERATION}") + if [[ -n "${IN_ROLLBACK_TAG}" ]]; then + [[ "${IN_ROLLBACK_TAG}" =~ ^process-replay/v1/[0-9a-f]{40}-[0-9a-f]{12}$ ]] || { echo "rollback_tag invalid" >&2; exit 1; } + ARGS+=(-f "rollback_tag=${IN_ROLLBACK_TAG}") + fi + gh workflow run process_replay_refs.yaml "${ARGS[@]}" + echo "Retargeted publication workflow to refs/heads/nap-dev" + + gate-nap-dev: + name: Enforce protected nap-dev contract + if: github.repository == 'NotAutopilot/openpilot' && github.ref == 'refs/heads/nap-dev' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + operation: ${{ steps.validate.outputs.operation }} + source_sha: ${{ steps.validate.outputs.source_sha }} + rollback_tag: ${{ steps.validate.outputs.rollback_tag }} + candidate_artifact: ${{ steps.validate.outputs.candidate_artifact }} + steps: + - name: Validate ref, sha, workflow_ref, and inputs + id: validate + env: + GH_TOKEN: ${{ github.token }} + OPERATION: ${{ inputs.operation }} + IN_ROLLBACK_TAG: ${{ inputs.rollback_tag }} + run: | + set -euo pipefail + + if [[ "${GITHUB_REF}" != "refs/heads/nap-dev" ]]; then + echo "Publication requires github.ref=refs/heads/nap-dev" >&2 + exit 1 + fi + if [[ ! "${GITHUB_SHA}" =~ ^[0-9a-f]{40}$ ]]; then + echo "github.sha must be lowercase 40-hex" >&2 + exit 1 + fi + EXPECTED_WORKFLOW_REF="${SOURCE_REPO}/.github/workflows/process_replay_refs.yaml@refs/heads/nap-dev" + if [[ "${GITHUB_WORKFLOW_REF}" != "${EXPECTED_WORKFLOW_REF}" ]]; then + echo "github.workflow_ref must be ${EXPECTED_WORKFLOW_REF}, got ${GITHUB_WORKFLOW_REF}" >&2 + exit 1 + fi + + TIP="$(gh api "repos/${SOURCE_REPO}/git/ref/heads/nap-dev" --jq '.object.sha')" + if [[ "${TIP}" != "${GITHUB_SHA}" ]]; then + echo "Refusing: workflow SHA ${GITHUB_SHA} is not current nap-dev tip ${TIP}" >&2 + exit 1 + fi + + case "${OPERATION}" in + generate-active) + IN_SOURCE_SHA="${TIP}" + ;; + rollback) + if [[ -z "${IN_ROLLBACK_TAG}" ]]; then + echo "rollback requires rollback_tag" >&2 + exit 1 + fi + if [[ ! "${IN_ROLLBACK_TAG}" =~ ^process-replay/v1/[0-9a-f]{40}-[0-9a-f]{12}$ ]]; then + echo "rollback_tag must match process-replay/v1/<40-hex>-<12-hex>" >&2 + exit 1 + fi + IN_SOURCE_SHA="$(sed -E 's|^process-replay/v1/([0-9a-f]{40})-[0-9a-f]{12}$|\1|' <<<"${IN_ROLLBACK_TAG}")" + ;; + *) + echo "Unknown operation ${OPERATION}" >&2 + exit 1 + ;; + esac + + { + echo "operation=${OPERATION}" + echo "source_sha=${IN_SOURCE_SHA}" + echo "rollback_tag=${IN_ROLLBACK_TAG}" + echo "candidate_artifact=${CANDIDATE_ARTIFACT_PREFIX}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + } >> "${GITHUB_OUTPUT}" + + generate: + name: Generate active refs on GitHub-hosted runner + needs: gate-nap-dev + if: needs.gate-nap-dev.result == 'success' && needs.gate-nap-dev.outputs.operation == 'generate-active' + runs-on: ubuntu-24.04 + timeout-minutes: 120 + env: + CI: 1 + PYTHONPATH: ${{ github.workspace }} + SOURCE_SHA: ${{ needs.gate-nap-dev.outputs.source_sha }} + CANDIDATE_ARTIFACT: ${{ needs.gate-nap-dev.outputs.candidate_artifact }} + outputs: + source_sha: ${{ steps.prove.outputs.source_sha }} + manifest_sha256: ${{ steps.prove.outputs.manifest_sha256 }} + previous_accepted_tag: ${{ steps.prove.outputs.previous_accepted_tag }} + candidate_artifact: ${{ needs.gate-nap-dev.outputs.candidate_artifact }} + steps: + - name: Checkout exact GITHUB_SHA + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.0 + with: + ref: ${{ github.sha }} + submodules: true + persist-credentials: false + + - name: Reconfirm current tip before generation + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + TIP="$(gh api "repos/${SOURCE_REPO}/git/ref/heads/nap-dev" --jq '.object.sha')" + if [[ "${TIP}" != "${GITHUB_SHA}" || "${TIP}" != "${SOURCE_SHA}" ]]; then + echo "Refusing stale generate: tip=${TIP} sha=${GITHUB_SHA} source=${SOURCE_SHA}" >&2 + exit 1 + fi + HEAD_SHA="$(git rev-parse HEAD)" + if [[ "${HEAD_SHA}" != "${SOURCE_SHA}" ]]; then + echo "Checkout HEAD ${HEAD_SHA} != source_sha ${SOURCE_SHA}" >&2 + exit 1 + fi + + - name: Use fork LFS storage + run: git config lfs.url "https://github.com/${GITHUB_REPOSITORY}.git/info/lfs" + + - name: Set up dependencies + uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e + with: + timeout_minutes: 10 + max_attempts: 3 + command: ./tools/op.sh setup + + - name: Install video encoding deps + run: sudo apt-get install -y libva-dev libva-drm2 libdrm-dev + + - name: Build openpilot + run: scons -j$(nproc) + + - name: Generate, assemble, compare, and write proof + id: prove + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + REPLAY=selfdrive/test/process_replay/test_processes.py + ASSEMBLE=tools/ci/assemble_replay_release.py + test -x "${REPLAY}" -o -f "${REPLAY}" + test -f "${ASSEMBLE}" + + OPENDBC_SHA="$(git rev-parse HEAD:opendbc_repo)" + if [[ ! "${OPENDBC_SHA}" =~ ^[0-9a-f]{40}$ ]]; then + echo "Failed to resolve opendbc_repo gitlink" >&2 + exit 1 + fi + + # Bind provenance to the current accepted head. A same-source rerun + # reuses the accepted manifest's predecessor so deterministic output + # remains byte-identical and publication becomes a no-op. + if ! gh api "repos/${ARTIFACTS_REPO}/git/ref/heads/${ARTIFACTS_BRANCH}" >/tmp/artifacts-head.json; then + echo "Missing ${ARTIFACTS_REPO}@${ARTIFACTS_BRANCH}; cannot resolve previous accepted identity" >&2 + exit 1 + fi + PREVIOUS_HEAD="$(jq -r '.object.sha' /tmp/artifacts-head.json)" + if [[ ! "${PREVIOUS_HEAD}" =~ ^[0-9a-f]{40}$ ]]; then + echo "Invalid process-replay head ${PREVIOUS_HEAD}" >&2 + exit 1 + fi + CURRENT_REF_COMMIT="$(gh api "repos/${ARTIFACTS_REPO}/contents/ref_commit?ref=${PREVIOUS_HEAD}" --jq '.content' | base64 -d | tr -d '\n')" + if [[ "${CURRENT_REF_COMMIT}" == "${SOURCE_SHA}" ]]; then + PREVIOUS_ACCEPTED_TAG="$(gh api "repos/${ARTIFACTS_REPO}/contents/manifest.json?ref=${PREVIOUS_HEAD}" --jq '.content' \ + | base64 -d | jq -r '.previous_accepted_tag')" + if [[ -z "${PREVIOUS_ACCEPTED_TAG}" || "${PREVIOUS_ACCEPTED_TAG}" == "null" ]]; then + echo "Current same-source manifest has no previous accepted identity" >&2 + exit 1 + fi + else + PREVIOUS_ACCEPTED_TAG="process-replay/archive/${PREVIOUS_HEAD}" + fi + + WORK="$(pwd)/.process-replay-generate" + export WORK OPENDBC_SHA PREVIOUS_HEAD PREVIOUS_ACCEPTED_TAG + rm -rf "${WORK}" + mkdir -p \ + "${WORK}/generate" \ + "${WORK}/compare" \ + "${WORK}/release" \ + "${WORK}/candidate/release" \ + "${WORK}/candidate/review/generate-active/compare" + + echo "Listing active cases" + python3 "${REPLAY}" --inventory active --list-cases > "${WORK}/cases.json" + python3 - <<'PY' + import json, os, pathlib + cases = json.loads(pathlib.Path(os.environ['WORK'], 'cases.json').read_text(encoding='utf-8')) + if not isinstance(cases, list) or len(cases) != 16: + raise SystemExit(f'expected 16 active cases, got {len(cases) if isinstance(cases, list) else type(cases)}') + print(f'listed {len(cases)} active cases') + PY + + echo "Generating refs with --update-refs" + python3 "${REPLAY}" \ + -j"$(nproc)" \ + --inventory active \ + --update-refs \ + --output-dir "${WORK}/generate" + + echo "Assembling release tree" + python3 "${ASSEMBLE}" \ + --operation generate-active \ + --source-sha "${SOURCE_SHA}" \ + --fakedata-dir selfdrive/test/process_replay/fakedata \ + --release-dir "${WORK}/release" \ + --opendbc-sha "${OPENDBC_SHA}" \ + --cases-json "${WORK}/cases.json" \ + --previous-accepted-tag "${PREVIOUS_ACCEPTED_TAG}" \ + | tee "${WORK}/assemble.log" + MANIFEST_SHA256="$(awk -F= '/^manifest_sha256=/{print $2; exit}' "${WORK}/assemble.log")" + if [[ ! "${MANIFEST_SHA256}" =~ ^[0-9a-f]{64}$ ]]; then + MANIFEST_SHA256="$(python3 - <<'PY' + import hashlib, pathlib, os + path = pathlib.Path(os.environ['WORK']) / 'release' / 'manifest.json' + print(hashlib.sha256(path.read_bytes()).hexdigest()) + PY + )" + fi + if [[ ! "${MANIFEST_SHA256}" =~ ^[0-9a-f]{64}$ ]]; then + echo "Failed to resolve manifest_sha256" >&2 + exit 1 + fi + export MANIFEST_SHA256 + + echo "Comparing all active tasks against assembled release" + python3 "${REPLAY}" \ + -j"$(nproc)" \ + --inventory active \ + --output-dir "${WORK}/compare" \ + --reference-dir "${WORK}/release" + + python3 - <<'PY' + import json, os, pathlib, re + work = pathlib.Path(os.environ['WORK']) + source_sha = os.environ['SOURCE_SHA'] + manifest_sha = os.environ['MANIFEST_SHA256'] + previous = os.environ['PREVIOUS_ACCEPTED_TAG'] + opendbc_sha = os.environ['OPENDBC_SHA'] + run_id = os.environ['GITHUB_RUN_ID'] + expected_tasks = int(os.environ['EXPECTED_TASKS']) + + results_path = work / 'compare' / 'results.json' + if not results_path.is_file() or results_path.is_symlink(): + raise SystemExit('missing compare results.json') + results = json.loads(results_path.read_text(encoding='utf-8')) + cases = json.loads((work / 'cases.json').read_text(encoding='utf-8')) + expected_ids = sorted( + f"{case['case_id']}:{process}" + for case in cases + for process in case['processes'] + ) + if results.get('schema_version') != 1 or results.get('inventory') != 'active': + raise SystemExit('compare proof requires schema_version=1 and inventory=active') + if results.get('tested_commit') != source_sha or results.get('ref_commit') != source_sha: + raise SystemExit('compare tested_commit/ref_commit must equal source_sha') + if results.get('expected_task_ids') != expected_ids: + raise SystemExit('compare expected_task_ids mismatch active inventory') + if results.get('completed_task_ids') != expected_ids or results.get('incomplete_task_ids') != []: + raise SystemExit('compare task completion proof is not exact') + records = results.get('results') + if not isinstance(records, list) or len(records) != expected_tasks: + raise SystemExit('compare results must contain exactly one record per active task') + record_ids = [record.get('task_id') for record in records if isinstance(record, dict)] + if sorted(record_ids) != expected_ids or len(set(record_ids)) != expected_tasks: + raise SystemExit('compare result task IDs must exactly match active inventory') + if any(record.get('status') != 'pass' for record in records): + raise SystemExit('compare result records must all pass') + counts = results.get('status_counts') or {} + if int(counts.get('pass', -1)) != expected_tasks: + raise SystemExit(f"compare pass count must be {expected_tasks}, got {counts.get('pass')}") + for key in ('diff', 'error', 'incomplete'): + if int(counts.get(key, -1)) != 0: + raise SystemExit(f'compare requires zero {key}, got {counts.get(key)}') + + release = work / 'release' + manifest_path = release / 'manifest.json' + actual = __import__('hashlib').sha256(manifest_path.read_bytes()).hexdigest() + if actual != manifest_sha: + raise SystemExit('manifest_sha256 drifted before proof write') + + # Reject unsafe release layout before packaging. + for path in sorted(release.rglob('*')): + rel = path.relative_to(release).as_posix() + if '..' in pathlib.Path(rel).parts or rel.startswith('/'): + raise SystemExit(f'unsafe release path: {rel}') + if path.is_symlink(): + raise SystemExit(f'symlink forbidden in release: {rel}') + + proof = { + 'schema_version': 1, + 'source_sha': source_sha, + 'opendbc_sha': opendbc_sha, + 'operation': 'generate-active', + 'manifest_sha256': manifest_sha, + 'accepted_head': os.environ['PREVIOUS_HEAD'], + 'previous_accepted_tag': previous, + 'workflow_run_id': str(run_id), + 'expected_tasks': expected_tasks, + 'status_counts': { + 'pass': expected_tasks, + 'diff': 0, + 'error': 0, + 'incomplete': 0, + }, + } + if not re.fullmatch(r'[0-9a-f]{40}', source_sha): + raise SystemExit('invalid source_sha in proof') + if not re.fullmatch(r'[0-9a-f]{64}', manifest_sha): + raise SystemExit('invalid manifest_sha256 in proof') + + candidate = work / 'candidate' + # Copy release tree files only (no nested dirs). + for entry in sorted(release.iterdir()): + if entry.is_symlink(): + raise SystemExit(f'symlink forbidden: {entry}') + if entry.is_dir(): + raise SystemExit(f'nested release directory forbidden: {entry.name}') + if entry.is_file(): + (candidate / 'release' / entry.name).write_bytes(entry.read_bytes()) + + (candidate / 'handoff-meta.json').write_text( + json.dumps(proof, indent=2, sort_keys=True) + '\n', encoding='utf-8' + ) + compare_dest = candidate / 'review' / 'generate-active' / 'compare' + compare_dest.mkdir(parents=True, exist_ok=True) + (compare_dest / 'results.json').write_bytes(results_path.read_bytes()) + if (work / 'compare' / 'diff.txt').is_file(): + (compare_dest / 'diff.txt').write_bytes((work / 'compare' / 'diff.txt').read_bytes()) + (candidate / 'review' / 'generate-active' / 'cases.json').write_bytes( + (work / 'cases.json').read_bytes() + ) + + out = pathlib.Path(os.environ['GITHUB_OUTPUT']) + with out.open('a', encoding='utf-8') as handle: + handle.write(f'source_sha={source_sha}\n') + handle.write(f'manifest_sha256={manifest_sha}\n') + handle.write(f'previous_accepted_tag={previous}\n') + print(f'proof bound source_sha={source_sha} manifest_sha256={manifest_sha} previous={previous}') + PY + + - name: Upload immutable same-run candidate artifact + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + with: + name: ${{ needs.gate-nap-dev.outputs.candidate_artifact }} + path: .process-replay-generate/candidate + if-no-files-found: error + overwrite: false + retention-days: 14 + + verify: + name: Verify candidate without execution + needs: [gate-nap-dev, generate] + if: | + always() && + needs.gate-nap-dev.result == 'success' && + ( + needs.gate-nap-dev.outputs.operation == 'rollback' || + needs.generate.result == 'success' + ) + runs-on: ubuntu-24.04 + timeout-minutes: 20 + # No environment: publication token must not be available here. + outputs: + release_source_sha: ${{ steps.validate.outputs.release_source_sha }} + release_manifest_sha256: ${{ steps.validate.outputs.release_manifest_sha256 }} + release_tag: ${{ steps.validate.outputs.release_tag }} + accepted_head: ${{ steps.proof.outputs.accepted_head }} + release_previous_accepted_tag: ${{ steps.validate.outputs.release_previous_accepted_tag }} + steps: + - name: Checkout trusted nap-dev inventory + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Materialize candidate tree + id: fetch + env: + OPERATION: ${{ needs.gate-nap-dev.outputs.operation }} + SOURCE_SHA: ${{ needs.gate-nap-dev.outputs.source_sha }} + ROLLBACK_TAG: ${{ needs.gate-nap-dev.outputs.rollback_tag }} + CANDIDATE_ARTIFACT: ${{ needs.gate-nap-dev.outputs.candidate_artifact }} + GENERATE_MANIFEST_SHA256: ${{ needs.generate.outputs.manifest_sha256 }} + GITHUB_READ_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + mkdir -p candidate + if [[ "${OPERATION}" == "generate-active" ]]; then + # Same-run artifact only; never trust foreign payloads. + if [[ -z "${CANDIDATE_ARTIFACT}" ]]; then + echo "Missing candidate artifact name" >&2 + exit 1 + fi + if [[ ! "${CANDIDATE_ARTIFACT}" =~ ^process-replay-candidate-[0-9]+-[0-9]+$ ]]; then + echo "Unexpected candidate artifact name ${CANDIDATE_ARTIFACT}" >&2 + exit 1 + fi + else + # Rollback reads an archived tag tree with the job token only. + export GH_TOKEN="${GITHUB_READ_TOKEN}" + REF_SHA="$(gh api "repos/${ARTIFACTS_REPO}/git/ref/tags/${ROLLBACK_TAG}" --jq '.object.sha')" + OBJ_TYPE="$(gh api "repos/${ARTIFACTS_REPO}/git/ref/tags/${ROLLBACK_TAG}" --jq '.object.type')" + if [[ "${OBJ_TYPE}" == "tag" ]]; then + REF_SHA="$(gh api "repos/${ARTIFACTS_REPO}/git/tags/${REF_SHA}" --jq '.object.sha')" + fi + mkdir -p candidate/release + TREE_SHA="$(gh api "repos/${ARTIFACTS_REPO}/git/commits/${REF_SHA}" --jq '.tree.sha')" + gh api "repos/${ARTIFACTS_REPO}/git/trees/${TREE_SHA}?recursive=1" > /tmp/tree.json + python3 - <<'PY' + import json, base64, urllib.request, os + from pathlib import Path + token = os.environ['GH_TOKEN'] + repo = os.environ['ARTIFACTS_REPO'] + tree = json.load(open('/tmp/tree.json')) + if tree.get('truncated'): + raise SystemExit('rollback tree truncated') + for entry in tree['tree']: + path = entry['path'] + if path.startswith('/') or '..' in Path(path).parts: + raise SystemExit(f'path traversal: {path}') + if entry['type'] != 'blob': + continue + url = f'https://api.github.com/repos/{repo}/git/blobs/{entry["sha"]}' + req = urllib.request.Request(url, headers={ + 'Authorization': f'Bearer {token}', + 'Accept': 'application/vnd.github+json', + }) + with urllib.request.urlopen(req) as resp: + blob = json.load(resp) + data = base64.b64decode(blob['content']) + target = Path('candidate/release') / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + PY + fi + + - name: Download same-run generate-active artifact + if: needs.gate-nap-dev.outputs.operation == 'generate-active' + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: ${{ needs.gate-nap-dev.outputs.candidate_artifact }} + path: candidate + + - name: Reject unsafe layouts and bind generate-active proof + id: proof + if: needs.gate-nap-dev.outputs.operation == 'generate-active' + env: + SOURCE_SHA: ${{ needs.gate-nap-dev.outputs.source_sha }} + MANIFEST_SHA256: ${{ needs.generate.outputs.manifest_sha256 }} + OPERATION: ${{ needs.gate-nap-dev.outputs.operation }} + run: | + set -euo pipefail + python3 - <<'PY' + import hashlib + import json + import os + import re + from pathlib import Path + + source_sha = os.environ['SOURCE_SHA'] + manifest_sha = os.environ['MANIFEST_SHA256'] + operation = os.environ['OPERATION'] + workflow_run_id = os.environ['GITHUB_RUN_ID'] + expected_tasks = int(os.environ['EXPECTED_TASKS']) + sha40 = re.compile(r'^[0-9a-f]{40}$') + sha64 = re.compile(r'^[0-9a-f]{64}$') + if operation != 'generate-active': + raise SystemExit(f'expected generate-active, got {operation!r}') + if not sha40.fullmatch(source_sha) or not sha64.fullmatch(manifest_sha): + raise SystemExit('invalid source_sha or manifest_sha256 for proof binding') + + root = Path('candidate') + if root.is_symlink() or not root.is_dir(): + raise SystemExit('candidate root must be a real directory') + + # Fail closed on unsafe extracted layouts (symlinks / traversal / unexpected nesting). + allowed_top = {'release', 'handoff-meta.json', 'review'} + for child in root.iterdir(): + if child.name not in allowed_top: + raise SystemExit(f'unexpected candidate top-level entry: {child.name}') + for path in sorted(root.rglob('*')): + rel = path.relative_to(root).as_posix() + parts = Path(rel).parts + if rel.startswith('/') or '..' in parts: + raise SystemExit(f'path traversal in candidate: {rel}') + if path.is_symlink(): + raise SystemExit(f'symlink forbidden in candidate: {rel}') + if path.is_dir(): + continue + if not path.is_file(): + raise SystemExit(f'non-regular candidate member: {rel}') + if rel.startswith('release/') and '/' in rel[len('release/'):]: + raise SystemExit(f'nested release path forbidden: {rel}') + + handoff = root / 'handoff-meta.json' + if not handoff.is_file() or handoff.is_symlink(): + raise SystemExit('missing handoff-meta.json proof in candidate artifact') + meta = json.loads(handoff.read_text(encoding='utf-8')) + if meta.get('source_sha') != source_sha: + raise SystemExit(f"handoff source_sha mismatch: {meta.get('source_sha')} != {source_sha}") + if meta.get('manifest_sha256') != manifest_sha: + raise SystemExit('handoff manifest_sha256 mismatch against generate output') + if meta.get('operation') != 'generate-active': + raise SystemExit(f"handoff operation must be generate-active, got {meta.get('operation')!r}") + if str(meta.get('workflow_run_id')) != workflow_run_id: + raise SystemExit('handoff workflow_run_id mismatch against current run') + if int(meta.get('expected_tasks', -1)) != expected_tasks: + raise SystemExit('handoff expected_tasks mismatch') + accepted_head = str(meta.get('accepted_head', '')) + if not sha40.fullmatch(accepted_head): + raise SystemExit('handoff accepted_head must be lowercase 40-hex') + + release_manifest = root / 'release' / 'manifest.json' + if not release_manifest.is_file(): + raise SystemExit('candidate release/manifest.json missing after download') + actual = hashlib.sha256(release_manifest.read_bytes()).hexdigest() + if actual != manifest_sha: + raise SystemExit('release/manifest.json hash mismatch against handoff/generate proof') + + results_path = root / 'review' / 'generate-active' / 'compare' / 'results.json' + if not results_path.is_file() or results_path.is_symlink(): + raise SystemExit(f'missing review proof {results_path}') + results = json.loads(results_path.read_text(encoding='utf-8')) + trusted = json.loads(Path(os.environ['TRUSTED_INVENTORY_PATH']).read_text(encoding='utf-8')) + trusted_ids = trusted.get('task_ids') + if (not isinstance(trusted_ids, list) or len(trusted_ids) != expected_tasks + or len(set(trusted_ids)) != expected_tasks): + raise SystemExit('trusted active task inventory is invalid') + expected_ids = sorted(trusted_ids) + if results.get('schema_version') != 1 or results.get('inventory') != 'active': + raise SystemExit('review proof requires schema_version=1 and inventory=active') + if results.get('tested_commit') != source_sha or results.get('ref_commit') != source_sha: + raise SystemExit('review proof tested_commit/ref_commit must equal source_sha') + if results.get('expected_task_ids') != expected_ids: + raise SystemExit('review expected_task_ids mismatch trusted active inventory') + if results.get('completed_task_ids') != expected_ids or results.get('incomplete_task_ids') != []: + raise SystemExit('review task completion proof is not exact') + records = results.get('results') + if not isinstance(records, list) or len(records) != expected_tasks: + raise SystemExit('review results must contain exactly one record per active task') + record_ids = [record.get('task_id') for record in records if isinstance(record, dict)] + if sorted(record_ids) != sorted(expected_ids) or len(set(record_ids)) != expected_tasks: + raise SystemExit('review result task IDs must exactly match trusted active inventory') + if any(record.get('status') != 'pass' for record in records): + raise SystemExit('review result records must all pass') + counts = results.get('status_counts') or {} + if int(counts.get('pass', -1)) != expected_tasks: + raise SystemExit(f"review proof pass count must be {expected_tasks}, got {counts.get('pass')}") + for key in ('diff', 'error', 'incomplete'): + if int(counts.get(key, -1)) != 0: + raise SystemExit(f'review proof requires zero {key}, got {counts.get(key)}') + with Path(os.environ['GITHUB_OUTPUT']).open('a', encoding='utf-8') as output: + output.write(f'accepted_head={accepted_head}\n') + print(f'bound same-run generate-active proof with {expected_tasks} green compares') + PY + test -d candidate/release + + - name: Fail-closed release-tree validation + id: validate + env: + OPERATION: ${{ needs.gate-nap-dev.outputs.operation }} + SOURCE_SHA: ${{ needs.gate-nap-dev.outputs.source_sha }} + MANIFEST_SHA256: ${{ needs.generate.outputs.manifest_sha256 }} + ROLLBACK_TAG: ${{ needs.gate-nap-dev.outputs.rollback_tag }} + GITHUB_READ_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + test -f "${TRUSTED_INVENTORY_PATH}" + test -f "${RELEASE_VALIDATOR}" + test -d candidate/release + HEAD_SHA="$(git rev-parse HEAD)" + if [[ "${SOURCE_SHA}" == "${HEAD_SHA}" ]]; then + EXPECTED_OPENDBC_SHA="$(git rev-parse HEAD:opendbc_repo)" + else + # Rollback may target an older source tip than the publisher checkout. + export GH_TOKEN="${GITHUB_READ_TOKEN}" + EXPECTED_OPENDBC_SHA="$(gh api "repos/${SOURCE_REPO}/git/trees/${SOURCE_SHA}" \ + --jq '.tree[] | select(.path=="opendbc_repo" and .mode=="160000") | .sha')" + fi + if [[ ! "${EXPECTED_OPENDBC_SHA}" =~ ^[0-9a-f]{40}$ ]]; then + echo "Failed to resolve trusted opendbc_repo gitlink for ${SOURCE_SHA}" >&2 + exit 1 + fi + VALIDATOR_OPERATION="${OPERATION}" + if [[ "${OPERATION}" == "generate-active" ]]; then + # Release-tree validator uses publish|rollback; workflow op remains generate-active. + VALIDATOR_OPERATION="publish" + fi + python3 "${RELEASE_VALIDATOR}" \ + --release-dir candidate/release \ + --trusted-inventory "${TRUSTED_INVENTORY_PATH}" \ + --source-sha "${SOURCE_SHA}" \ + --operation "${VALIDATOR_OPERATION}" \ + --expected-manifest-sha256 "${MANIFEST_SHA256}" \ + --expected-opendbc-sha "${EXPECTED_OPENDBC_SHA}" \ + --rollback-tag "${ROLLBACK_TAG}" + + - name: Upload verified same-run artifact + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + with: + name: process-replay-release-verified-${{ github.run_id }}-${{ github.run_attempt }} + path: candidate/release + if-no-files-found: error + overwrite: false + retention-days: 14 + + publish: + name: Publish to ci-artifacts + needs: [gate-nap-dev, verify] + if: needs.verify.result == 'success' + runs-on: ubuntu-24.04 + timeout-minutes: 20 + environment: process-replay-publish + steps: + - name: Checkout trusted nap-dev inventory + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Download verified same-run artifact + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: process-replay-release-verified-${{ github.run_id }}-${{ github.run_attempt }} + path: .process-replay-publish-release + + - name: Revalidate release tree before push + env: + OPERATION: ${{ needs.gate-nap-dev.outputs.operation }} + SOURCE_SHA: ${{ needs.verify.outputs.release_source_sha }} + MANIFEST_SHA256: ${{ needs.verify.outputs.release_manifest_sha256 }} + ROLLBACK_TAG: ${{ needs.verify.outputs.release_tag }} + GITHUB_READ_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + test -f "${TRUSTED_INVENTORY_PATH}" + test -f "${RELEASE_VALIDATOR}" + HEAD_SHA="$(git rev-parse HEAD)" + if [[ "${SOURCE_SHA}" == "${HEAD_SHA}" ]]; then + EXPECTED_OPENDBC_SHA="$(git rev-parse HEAD:opendbc_repo)" + else + export GH_TOKEN="${GITHUB_READ_TOKEN}" + EXPECTED_OPENDBC_SHA="$(gh api "repos/${SOURCE_REPO}/git/trees/${SOURCE_SHA}" \ + --jq '.tree[] | select(.path=="opendbc_repo" and .mode=="160000") | .sha')" + fi + if [[ ! "${EXPECTED_OPENDBC_SHA}" =~ ^[0-9a-f]{40}$ ]]; then + echo "Failed to resolve trusted opendbc_repo gitlink for ${SOURCE_SHA}" >&2 + exit 1 + fi + # Same strict validator as the no-environment verifier. + VALIDATOR_OPERATION="${OPERATION}" + if [[ "${OPERATION}" == "generate-active" ]]; then + VALIDATOR_OPERATION="publish" + fi + python3 "${RELEASE_VALIDATOR}" \ + --release-dir .process-replay-publish-release \ + --trusted-inventory "${TRUSTED_INVENTORY_PATH}" \ + --source-sha "${SOURCE_SHA}" \ + --operation "${VALIDATOR_OPERATION}" \ + --expected-manifest-sha256 "${MANIFEST_SHA256}" \ + --expected-opendbc-sha "${EXPECTED_OPENDBC_SHA}" \ + --rollback-tag "${ROLLBACK_TAG}" + + - name: Capture current process-replay head + id: head + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_ACCEPTED_HEAD: ${{ needs.verify.outputs.accepted_head }} + OPERATION: ${{ needs.gate-nap-dev.outputs.operation }} + run: | + set -euo pipefail + if gh api "repos/${ARTIFACTS_REPO}/git/ref/heads/${ARTIFACTS_BRANCH}" >/tmp/head.json 2>/dev/null; then + CAPTURED="$(jq -r '.object.sha' /tmp/head.json)" + echo "branch_exists=true" >> "${GITHUB_OUTPUT}" + else + CAPTURED="" + echo "branch_exists=false" >> "${GITHUB_OUTPUT}" + fi + if [[ -n "${CAPTURED}" && ! "${CAPTURED}" =~ ^[0-9a-f]{40}$ ]]; then + echo "Invalid captured head ${CAPTURED}" >&2 + exit 1 + fi + if [[ "${OPERATION}" == "generate-active" && "${EXPECTED_ACCEPTED_HEAD}" != "${CAPTURED}" ]]; then + echo "process-replay moved after generation: expected=${EXPECTED_ACCEPTED_HEAD} current=${CAPTURED}" >&2 + exit 1 + fi + echo "captured_head=${CAPTURED}" >> "${GITHUB_OUTPUT}" + echo "Captured ${ARTIFACTS_BRANCH} head: ${CAPTURED:-}" + + - name: Push with force-with-lease, tag, and remote rehash + env: + # Repository-scoped write token is intentionally available only in this final push step. + NAP_CI_ARTIFACTS_WRITE_TOKEN: ${{ secrets.NAP_CI_ARTIFACTS_WRITE_TOKEN }} + JOB_TOKEN: ${{ github.token }} + OPERATION: ${{ needs.gate-nap-dev.outputs.operation }} + SOURCE_SHA: ${{ needs.verify.outputs.release_source_sha }} + MANIFEST_SHA256: ${{ needs.verify.outputs.release_manifest_sha256 }} + RELEASE_TAG: ${{ needs.verify.outputs.release_tag }} + CAPTURED_HEAD: ${{ steps.head.outputs.captured_head }} + BRANCH_EXISTS: ${{ steps.head.outputs.branch_exists }} + run: | + set -euo pipefail + if [[ -z "${NAP_CI_ARTIFACTS_WRITE_TOKEN}" ]]; then + echo "Missing NAP_CI_ARTIFACTS_WRITE_TOKEN in process-replay-publish environment" >&2 + exit 1 + fi + + TIP="$(GH_TOKEN="${JOB_TOKEN}" gh api "repos/${SOURCE_REPO}/git/ref/heads/nap-dev" --jq '.object.sha')" + if [[ "${OPERATION}" == "generate-active" && "${TIP}" != "${SOURCE_SHA}" ]]; then + echo "nap-dev moved to ${TIP}; refusing stale candidate" >&2 + exit 1 + fi + + AUTH_URL="https://x-access-token:${NAP_CI_ARTIFACTS_WRITE_TOKEN}@github.com/${ARTIFACTS_REPO}.git" + rm -rf /tmp/ci-artifacts + if [[ "${BRANCH_EXISTS}" == "true" ]]; then + git clone --depth 1 --branch "${ARTIFACTS_BRANCH}" "${AUTH_URL}" /tmp/ci-artifacts + else + git clone --depth 1 "${AUTH_URL}" /tmp/ci-artifacts + fi + + cd /tmp/ci-artifacts + git config user.name "process-replay-publisher" + git config user.email "process-replay-publisher@users.noreply.github.com" + EXTRA_REFS=() + + if [[ "${BRANCH_EXISTS}" == "true" ]]; then + git checkout -B "${ARTIFACTS_BRANCH}" "origin/${ARTIFACTS_BRANCH}" + CURRENT="$(git rev-parse HEAD)" + if [[ "${CURRENT}" != "${CAPTURED_HEAD}" ]]; then + echo "Captured head drifted before push: ${CURRENT} != ${CAPTURED_HEAD}" >&2 + exit 1 + fi + ARCHIVE_TAG="process-replay/archive/${CAPTURED_HEAD}" + if git ls-remote --tags origin "refs/tags/${ARCHIVE_TAG}" | grep -q .; then + git fetch origin "refs/tags/${ARCHIVE_TAG}:refs/tags/${ARCHIVE_TAG}" + if [[ "$(git rev-list -n 1 "refs/tags/${ARCHIVE_TAG}")" != "${CAPTURED_HEAD}" ]]; then + echo "Archive tag ${ARCHIVE_TAG} does not resolve to captured head" >&2 + exit 1 + fi + else + git tag "${ARCHIVE_TAG}" "${CAPTURED_HEAD}" + EXTRA_REFS+=("refs/tags/${ARCHIVE_TAG}") + fi + else + git checkout --orphan "${ARTIFACTS_BRANCH}" + git rm -rf . >/dev/null 2>&1 || true + fi + + find . -mindepth 1 -maxdepth 1 ! -name '.git' -exec rm -rf {} + + cp -a "${GITHUB_WORKSPACE}/.process-replay-publish-release/." . + + if [[ "${BRANCH_EXISTS}" == "true" ]] && git diff --quiet HEAD -- .; then + echo "Byte-identical release tree; no-op success" + NEW_COMMIT="${CAPTURED_HEAD}" + else + git add -A + git commit -m "process-replay refs for ${SOURCE_REPO}@${SOURCE_SHA}" + NEW_COMMIT="$(git rev-parse HEAD)" + + if git ls-remote --tags origin "refs/tags/${RELEASE_TAG}" | grep -q .; then + git fetch origin "refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + TAG_COMMIT="$(git rev-list -n 1 "refs/tags/${RELEASE_TAG}")" + TREE_MATCH="$(git rev-parse "${TAG_COMMIT}^{tree}")" + NEW_TREE="$(git rev-parse "${NEW_COMMIT}^{tree}")" + if [[ "${TREE_MATCH}" != "${NEW_TREE}" ]]; then + echo "Release tag ${RELEASE_TAG} already exists with a different tree" >&2 + exit 1 + fi + else + git tag -a "${RELEASE_TAG}" -m "process-replay release ${SOURCE_SHA}" + EXTRA_REFS+=("refs/tags/${RELEASE_TAG}") + fi + + if [[ "${BRANCH_EXISTS}" == "true" ]]; then + git push --atomic \ + --force-with-lease="refs/heads/${ARTIFACTS_BRANCH}:${CAPTURED_HEAD}" \ + origin "HEAD:refs/heads/${ARTIFACTS_BRANCH}" "${EXTRA_REFS[@]}" + else + git push --atomic origin "HEAD:refs/heads/${ARTIFACTS_BRANCH}" "${EXTRA_REFS[@]}" + fi + echo "Published ${ARTIFACTS_BRANCH} at ${NEW_COMMIT} tag ${RELEASE_TAG}" + fi + + # ci-artifacts is public; the job token is sufficient for the remote rehash audit. + export GH_TOKEN="${JOB_TOKEN}" + export NEW_COMMIT + TREE="$(gh api "repos/${ARTIFACTS_REPO}/git/commits/${NEW_COMMIT}" --jq '.tree.sha')" + gh api "repos/${ARTIFACTS_REPO}/git/trees/${TREE}?recursive=1" > /tmp/remote-tree.json + python3 - <<'PY' + import hashlib, json, os, urllib.request, base64 + token = os.environ['GH_TOKEN'] + repo = os.environ['ARTIFACTS_REPO'] + source_sha = os.environ['SOURCE_SHA'] + expected = int(os.environ['EXPECTED_TASKS']) + tree = json.load(open('/tmp/remote-tree.json')) + if tree.get('truncated'): + raise SystemExit('remote tree truncated') + blobs = {e['path']: e for e in tree['tree'] if e['type'] == 'blob'} + if 'ref_commit' not in blobs or 'manifest.json' not in blobs: + raise SystemExit('remote tree missing metadata') + zsts = [p for p in blobs if p.endswith('.zst')] + if len(zsts) != expected: + raise SystemExit(f'remote zst count {len(zsts)} != {expected}') + extras = [p for p in blobs if p not in {'ref_commit', 'manifest.json'} and not p.endswith('.zst')] + if extras: + raise SystemExit(f'remote extras: {extras}') + + def fetch(sha): + req = urllib.request.Request( + f'https://api.github.com/repos/{repo}/git/blobs/{sha}', + headers={'Authorization': f'Bearer {token}', 'Accept': 'application/vnd.github+json'}, + ) + with urllib.request.urlopen(req) as resp: + return base64.b64decode(json.load(resp)['content']) + + if fetch(blobs['ref_commit']['sha']).decode().strip() != source_sha: + raise SystemExit('remote ref_commit mismatch') + manifest_bytes = fetch(blobs['manifest.json']['sha']) + if hashlib.sha256(manifest_bytes).hexdigest() != os.environ['MANIFEST_SHA256']: + raise SystemExit('remote manifest hash mismatch') + manifest = json.loads(manifest_bytes) + for _, meta in manifest['refs'].items(): + data = fetch(blobs[meta['filename']]['sha']) + if hashlib.sha256(data).hexdigest() != meta['sha256'] or len(data) != meta['size']: + raise SystemExit(f'remote rehash failed for {meta["filename"]}') + if not meta['filename'].endswith(f'__{source_sha}.zst'): + raise SystemExit('remote filename source_sha mismatch') + print(f'remote rehash OK for {expected} refs at {os.environ["NEW_COMMIT"]}') + PY diff --git a/.github/workflows/process_replay_trusted.yaml b/.github/workflows/process_replay_trusted.yaml new file mode 100644 index 00000000000000..019f3fbfaea173 --- /dev/null +++ b/.github/workflows/process_replay_trusted.yaml @@ -0,0 +1,247 @@ +# Public post-merge dispatch only. Never schedules self-hosted runners. +# After a successful hosted `tests` run for an exact refs/heads/nap-dev push tip, +# require Actions API proof of exact workflow name/path/event/SHA and successful +# conclusions for process replay (card|controlsd|lagd|other), then dispatch the +# private controller with client_payload: +# source_sha / source_repo / operation=test / jobs=6 / public_workflow_run_id / nonce. +# Zero-runner proof for NotAutopilot/openpilot is a documented rollout prerequisite +# (install-runner / host attestation). Ordinary GITHUB_TOKEN cannot authorize the +# repository runners administration API, so this workflow does not call it. +name: process replay trusted dispatch + +on: + workflow_run: + workflows: + - tests + types: + - completed + +permissions: + contents: read + actions: read + +concurrency: + group: process-replay-trusted-${{ github.event.workflow_run.head_sha }} + cancel-in-progress: true + +jobs: + dispatch-private-controller: + name: Dispatch private controller + if: > + github.repository == 'NotAutopilot/openpilot' && + github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_branch == 'nap-dev' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + # Environment-scoped fine-grained credential; never CI_ARTIFACTS_TOKEN. + # Restrict this environment to protected nap-dev in repo settings. + environment: process-replay-dispatch + env: + SOURCE_REPO: NotAutopilot/openpilot + CONTROLLER_REPO: NotAutopilot/nap-ci-controller + HOSTED_WORKFLOW_NAME: tests + EXPECTED_REF: refs/heads/nap-dev + DISPATCH_OPERATION: test + DISPATCH_JOBS: "6" + steps: + - name: Validate exact tip and successful hosted run + id: gate + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_SHA: ${{ github.event.workflow_run.head_sha }} + CANDIDATE_RUN_ID: ${{ github.event.workflow_run.id }} + CANDIDATE_EVENT: ${{ github.event.workflow_run.event }} + CANDIDATE_BRANCH: ${{ github.event.workflow_run.head_branch }} + CANDIDATE_CONCLUSION: ${{ github.event.workflow_run.conclusion }} + CANDIDATE_WORKFLOW: ${{ github.event.workflow_run.name }} + CANDIDATE_PATH: ${{ github.event.workflow_run.path }} + run: | + set -euo pipefail + + echo "candidate_sha=${CANDIDATE_SHA}" + echo "candidate_run_id=${CANDIDATE_RUN_ID}" + echo "candidate_event=${CANDIDATE_EVENT}" + echo "candidate_branch=${CANDIDATE_BRANCH}" + echo "candidate_conclusion=${CANDIDATE_CONCLUSION}" + echo "candidate_workflow=${CANDIDATE_WORKFLOW}" + echo "candidate_path=${CANDIDATE_PATH}" + + if [[ "${CANDIDATE_CONCLUSION}" != "success" ]]; then + echo "Refusing dispatch: hosted workflow conclusion is not success" >&2 + exit 1 + fi + if [[ "${CANDIDATE_EVENT}" != "push" ]]; then + echo "Refusing dispatch: underlying event must be push" >&2 + exit 1 + fi + if [[ "${CANDIDATE_BRANCH}" != "nap-dev" ]]; then + echo "Refusing dispatch: head branch must be nap-dev" >&2 + exit 1 + fi + if [[ "${CANDIDATE_WORKFLOW}" != "${HOSTED_WORKFLOW_NAME}" ]]; then + echo "Refusing dispatch: unexpected workflow name ${CANDIDATE_WORKFLOW}" >&2 + exit 1 + fi + if [[ -n "${CANDIDATE_PATH}" && "${CANDIDATE_PATH}" != ".github/workflows/tests.yaml" ]]; then + echo "Refusing dispatch: unexpected workflow path ${CANDIDATE_PATH}" >&2 + exit 1 + fi + if [[ ! "${CANDIDATE_SHA}" =~ ^[0-9a-f]{40}$ ]]; then + echo "Refusing dispatch: source_sha must be exact lowercase 40-hex" >&2 + exit 1 + fi + if [[ ! "${CANDIDATE_RUN_ID}" =~ ^[0-9]+$ ]]; then + echo "Refusing dispatch: public workflow run ID must be numeric" >&2 + exit 1 + fi + + TIP="$(gh api "repos/${SOURCE_REPO}/git/ref/heads/nap-dev" --jq '.object.sha')" + if [[ ! "${TIP}" =~ ^[0-9a-f]{40}$ ]]; then + echo "Refusing dispatch: current nap-dev tip is not lowercase 40-hex: ${TIP}" >&2 + exit 1 + fi + if [[ "${TIP}" != "${CANDIDATE_SHA}" ]]; then + echo "Refusing dispatch: candidate ${CANDIDATE_SHA} is not the current ${EXPECTED_REF} tip ${TIP}" >&2 + exit 1 + fi + + # Re-check the exact hosted run via API (fail closed). + RUN_JSON="$(gh api "repos/${SOURCE_REPO}/actions/runs/${CANDIDATE_RUN_ID}")" + RUN_SHA="$(jq -r '.head_sha' <<<"${RUN_JSON}")" + RUN_BRANCH="$(jq -r '.head_branch' <<<"${RUN_JSON}")" + RUN_EVENT="$(jq -r '.event' <<<"${RUN_JSON}")" + RUN_CONCLUSION="$(jq -r '.conclusion' <<<"${RUN_JSON}")" + RUN_STATUS="$(jq -r '.status' <<<"${RUN_JSON}")" + RUN_PATH="$(jq -r '.path' <<<"${RUN_JSON}")" + RUN_NAME="$(jq -r '.name' <<<"${RUN_JSON}")" + + if [[ "${RUN_STATUS}" != "completed" || "${RUN_CONCLUSION}" != "success" ]]; then + echo "Refusing dispatch: hosted run ${CANDIDATE_RUN_ID} is not a successful completion" >&2 + exit 1 + fi + if [[ "${RUN_SHA}" != "${CANDIDATE_SHA}" || "${RUN_SHA}" != "${TIP}" ]]; then + echo "Refusing dispatch: hosted run SHA mismatch" >&2 + exit 1 + fi + if [[ "${RUN_BRANCH}" != "nap-dev" || "${RUN_EVENT}" != "push" ]]; then + echo "Refusing dispatch: hosted run is not an exact nap-dev push" >&2 + exit 1 + fi + if [[ "${RUN_NAME}" != "${HOSTED_WORKFLOW_NAME}" ]]; then + echo "Refusing dispatch: hosted run workflow name mismatch" >&2 + exit 1 + fi + if [[ "${RUN_PATH}" != ".github/workflows/tests.yaml" ]]; then + echo "Refusing dispatch: hosted run path mismatch: ${RUN_PATH}" >&2 + exit 1 + fi + + # Require successful conclusions for the four exact hosted process-replay jobs. + mapfile -t JOB_LINES < <( + gh api --paginate \ + "repos/${SOURCE_REPO}/actions/runs/${CANDIDATE_RUN_ID}/jobs" \ + --jq '.jobs[] | [.name, .status, .conclusion] | @tsv' + ) + declare -A JOB_STATUS=() + declare -A JOB_CONCLUSION=() + for line in "${JOB_LINES[@]}"; do + IFS=$' ' read -r job_name job_status job_conclusion <<<"${line}" + JOB_STATUS["${job_name}"]="${job_status}" + JOB_CONCLUSION["${job_name}"]="${job_conclusion}" + done + EXPECTED_JOBS=( + "process replay (card)" + "process replay (controlsd)" + "process replay (lagd)" + "process replay (other)" + ) + for job_name in "${EXPECTED_JOBS[@]}"; do + if [[ -z "${JOB_STATUS[${job_name}]+x}" ]]; then + echo "Refusing dispatch: missing required hosted job ${job_name}" >&2 + exit 1 + fi + if [[ "${JOB_STATUS[${job_name}]}" != "completed" || "${JOB_CONCLUSION[${job_name}]}" != "success" ]]; then + echo "Refusing dispatch: job ${job_name} status=${JOB_STATUS[${job_name}]} conclusion=${JOB_CONCLUSION[${job_name}]}" >&2 + exit 1 + fi + done + + # Zero public-repo self-hosted runners remain a rollout prerequisite attested + # during private runner install; ordinary GITHUB_TOKEN cannot query that API. + + NONCE="$(openssl rand -hex 16)" + if [[ ! "${NONCE}" =~ ^[0-9a-f]{32}$ ]]; then + echo "Failed to generate nonce" >&2 + exit 1 + fi + + { + echo "source_sha=${CANDIDATE_SHA}" + echo "public_workflow_run_id=${CANDIDATE_RUN_ID}" + echo "nonce=${NONCE}" + } >> "${GITHUB_OUTPUT}" + + - name: Dispatch private controller + env: + # Fine-grained token scoped to the private controller only. + GH_TOKEN: ${{ secrets.NAP_CI_CONTROLLER_DISPATCH_TOKEN }} + SOURCE_SHA: ${{ steps.gate.outputs.source_sha }} + PUBLIC_WORKFLOW_RUN_ID: ${{ steps.gate.outputs.public_workflow_run_id }} + NONCE: ${{ steps.gate.outputs.nonce }} + run: | + set -euo pipefail + + if [[ -z "${GH_TOKEN}" ]]; then + echo "Missing NAP_CI_CONTROLLER_DISPATCH_TOKEN in process-replay-dispatch environment" >&2 + exit 1 + fi + if [[ ! "${SOURCE_SHA}" =~ ^[0-9a-f]{40}$ ]]; then + echo "Invalid source_sha" >&2 + exit 1 + fi + if [[ ! "${PUBLIC_WORKFLOW_RUN_ID}" =~ ^[0-9]+$ ]]; then + echo "Invalid public_workflow_run_id" >&2 + exit 1 + fi + if [[ ! "${NONCE}" =~ ^[0-9a-f]{32}$ ]]; then + echo "Invalid nonce" >&2 + exit 1 + fi + if [[ "${SOURCE_REPO}" != "NotAutopilot/openpilot" || "${DISPATCH_OPERATION}" != "test" || "${DISPATCH_JOBS}" != "6" ]]; then + echo "Invalid fixed dispatch contract" >&2 + exit 1 + fi + + # Tip must still match at dispatch time. + TIP="$(gh api "repos/${SOURCE_REPO}/git/ref/heads/nap-dev" --jq '.object.sha')" + if [[ "${TIP}" != "${SOURCE_SHA}" ]]; then + echo "Refusing dispatch: nap-dev moved to ${TIP} before controller dispatch" >&2 + exit 1 + fi + + PAYLOAD="$(jq -cn \ + --arg source_sha "${SOURCE_SHA}" \ + --arg source_repo "${SOURCE_REPO}" \ + --arg operation "${DISPATCH_OPERATION}" \ + --arg jobs "${DISPATCH_JOBS}" \ + --arg public_workflow_run_id "${PUBLIC_WORKFLOW_RUN_ID}" \ + --arg nonce "${NONCE}" \ + '{ + event_type: "nap-replay", + client_payload: { + source_sha: $source_sha, + source_repo: $source_repo, + operation: $operation, + jobs: $jobs, + public_workflow_run_id: $public_workflow_run_id, + nonce: $nonce + } + }')" + + echo "Dispatching controller for ${SOURCE_REPO}@${SOURCE_SHA} operation=${DISPATCH_OPERATION} jobs=${DISPATCH_JOBS}" + gh api --method POST "repos/${CONTROLLER_REPO}/dispatches" \ + -H "Accept: application/vnd.github+json" \ + --input - <<<"${PAYLOAD}" + + echo "Dispatched private controller; public workflow does not schedule self-hosted runners." diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 34e333bb59eec9..a90f064b82cb61 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -1,54 +1,31 @@ name: release on: schedule: - - cron: '0 10 * * *' + - cron: '0 9 * * *' workflow_dispatch: jobs: build_masterci: name: build master-ci - env: - TARGET_DIR: /tmp/openpilot - ImageOS: ubuntu20 - container: - image: ghcr.io/commaai/openpilot-base:latest runs-on: ubuntu-latest if: github.repository == 'commaai/openpilot' permissions: checks: read contents: write steps: - - name: Install wait-on-check-action dependencies - run: | - sudo apt-get update - sudo apt-get install -y libyaml-dev - name: Wait for green check mark - if: ${{ github.event_name != 'workflow_dispatch' }} + if: ${{ github.event_name == 'schedule' }} uses: lewagon/wait-on-check-action@ccfb013c15c8afb7bf2b7c028fb74dc5a068cccc with: ref: master wait-interval: 30 running-workflow-name: 'build master-ci' repo-token: ${{ secrets.GITHUB_TOKEN }} - check-regexp: ^((?!.*(build prebuilt).*).)*$ + check-regexp: ^((?!.*(build prebuilt|create badges).*).)*$ - uses: actions/checkout@v4 with: submodules: true fetch-depth: 0 - - name: Pull LFS - run: | - git config --global --add safe.directory '*' - git lfs pull - - name: Build master-ci - run: | - release/build_devel.sh - - name: Run tests - run: | - export PYTHONPATH=$TARGET_DIR - cd $TARGET_DIR - scons -j$(nproc) - pytest -n logical selfdrive/car/tests/test_car_interfaces.py + - run: ./tools/op.sh setup - name: Push master-ci - run: | - unset TARGET_DIR - BRANCH=master-ci release/build_devel.sh + run: BRANCH=__nightly release/build_stripped.sh diff --git a/.github/workflows/repo-maintenance.yaml b/.github/workflows/repo-maintenance.yaml index c724c00c5ee44c..f829415f4eea68 100644 --- a/.github/workflows/repo-maintenance.yaml +++ b/.github/workflows/repo-maintenance.yaml @@ -5,34 +5,51 @@ on: - cron: "0 14 * * 1" # every Monday at 2am UTC (6am PST) workflow_dispatch: +env: + PYTHONPATH: ${{ github.workspace }} + jobs: package_updates: name: package_updates runs-on: ubuntu-latest - container: - image: ghcr.io/commaai/openpilot-base:latest if: github.repository == 'commaai/openpilot' steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: submodules: true + - run: ./tools/op.sh setup - name: uv lock + run: uv lock --upgrade + - name: uv pip tree + id: pip_tree + run: | + echo 'PIP_TREE<> $GITHUB_OUTPUT + uv pip tree >> $GITHUB_OUTPUT + echo 'EOF' >> $GITHUB_OUTPUT + - name: venv size + id: venv_size run: | - python3 -m ensurepip --upgrade - pip3 install uv - uv lock --upgrade + echo 'VENV_SIZE<> $GITHUB_OUTPUT + echo "Total: $(du -sh .venv | cut -f1)" >> $GITHUB_OUTPUT + echo "" >> $GITHUB_OUTPUT + echo "Top 10 by size:" >> $GITHUB_OUTPUT + du -sh .venv/lib/python*/site-packages/* 2>/dev/null \ + | grep -v '\.dist-info' \ + | grep -v '__pycache__' \ + | sort -rh \ + | head -10 \ + | while IFS=$'\t' read size path; do echo "$size ${path##*/}"; done >> $GITHUB_OUTPUT + echo 'EOF' >> $GITHUB_OUTPUT - name: bump submodules run: | - git config --global --add safe.directory '*' - git -c submodule."tinygrad".update=none submodule update --remote + git submodule update --remote git add . - name: update car docs run: | - scons -j$(nproc) --minimal opendbc - PYTHONPATH=. python selfdrive/car/docs.py + python selfdrive/car/docs.py git add docs/CARS.md - name: Create Pull Request - uses: peter-evans/create-pull-request@9153d834b60caba6d51c9b9510b087acf9f33f83 + uses: peter-evans/create-pull-request@c0f553fe549906ede9cf27b5156039d195d2ece0 with: author: Vehicle Researcher token: ${{ secrets.ACTIONS_CREATE_PR_PAT }} @@ -41,5 +58,16 @@ jobs: branch: auto-package-updates base: master delete-branch: true - body: 'Automatic PR from repo-maintenance -> package_updates' + body: | + Automatic PR from repo-maintenance -> package_updates + + ``` + $ du -sh .venv && du -sh .venv/lib/python*/site-packages/* | sort -rh | head -10 + ${{ steps.venv_size.outputs.VENV_SIZE }} + ``` + + ``` + $ uv pip tree + ${{ steps.pip_tree.outputs.PIP_TREE }} + ``` labels: bot diff --git a/.github/workflows/selfdrive_tests.yaml b/.github/workflows/selfdrive_tests.yaml deleted file mode 100644 index b2831118f66266..00000000000000 --- a/.github/workflows/selfdrive_tests.yaml +++ /dev/null @@ -1,357 +0,0 @@ -name: selfdrive - -on: - push: - branches: - - master - pull_request: - workflow_dispatch: - workflow_call: - inputs: - run_number: - default: '1' - required: true - type: string - -concurrency: - group: selfdrive-tests-ci-run-${{ inputs.run_number }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && github.run_id || github.head_ref || github.ref }}-${{ github.workflow }}-${{ github.event_name }} - cancel-in-progress: true - -env: - PYTHONWARNINGS: error - BASE_IMAGE: openpilot-base - AZURE_TOKEN: ${{ secrets.AZURE_COMMADATACI_OPENPILOTCI_TOKEN }} - - DOCKER_LOGIN: docker login ghcr.io -u ${{ github.actor }} -p ${{ secrets.GITHUB_TOKEN }} - BUILD: selfdrive/test/docker_build.sh base - - RUN: docker run --shm-size 2G -v $PWD:/tmp/openpilot -w /tmp/openpilot -e CI=1 -e PYTHONWARNINGS=error -e FILEREADER_CACHE=1 -e PYTHONPATH=/tmp/openpilot -e NUM_JOBS -e JOB_ID -e GITHUB_ACTION -e GITHUB_REF -e GITHUB_HEAD_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_RUN_ID -v $GITHUB_WORKSPACE/.ci_cache/scons_cache:/tmp/scons_cache -v $GITHUB_WORKSPACE/.ci_cache/comma_download_cache:/tmp/comma_download_cache -v $GITHUB_WORKSPACE/.ci_cache/openpilot_cache:/tmp/openpilot_cache $BASE_IMAGE /bin/bash -c - - PYTEST: pytest --continue-on-collection-errors --cov --cov-report=xml --cov-append --durations=0 --durations-min=5 --hypothesis-seed 0 -n logical - -jobs: - build_release: - name: build release - runs-on: ${{ ((github.repository == 'commaai/openpilot') && - ((github.event_name != 'pull_request') || - (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-amd64-8x16' || 'ubuntu-latest' }} - env: - STRIPPED_DIR: /tmp/releasepilot - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - run: git lfs pull - - name: Build devel - timeout-minutes: 1 - run: TARGET_DIR=$STRIPPED_DIR release/build_devel.sh - - uses: ./.github/workflows/setup-with-retry - - name: Check submodules - if: github.ref == 'refs/heads/master' && github.repository == 'commaai/openpilot' - timeout-minutes: 1 - run: release/check-submodules.sh - - name: Build openpilot and run checks - timeout-minutes: ${{ ((steps.restore-scons-cache.outputs.cache-hit == 'true') && 10 || 30) }} # allow more time when we missed the scons cache - run: | - cd $STRIPPED_DIR - ${{ env.RUN }} "python3 system/manager/build.py" - - name: Run tests - timeout-minutes: 3 - run: | - cd $STRIPPED_DIR - ${{ env.RUN }} "release/check-dirty.sh && \ - MAX_EXAMPLES=5 $PYTEST -m 'not slow' selfdrive/car" - - name: Static analysis - timeout-minutes: 1 - run: | - cd $GITHUB_WORKSPACE - cp pyproject.toml $STRIPPED_DIR - cd $STRIPPED_DIR - ${{ env.RUN }} "scripts/lint/lint.sh --skip check_added_large_files" - - build: - strategy: - matrix: - arch: ${{ fromJson( - ((github.repository == 'commaai/openpilot') && - ((github.event_name != 'pull_request') || - (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && '["x86_64", "aarch64"]' || '["x86_64"]' ) }} - runs-on: ${{ (matrix.arch == 'aarch64') && 'namespace-profile-arm64-2x8' || 'ubuntu-latest' }} - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - name: Setup docker push - if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' && github.repository == 'commaai/openpilot' - run: | - echo "PUSH_IMAGE=true" >> "$GITHUB_ENV" - echo "TARGET_ARCHITECTURE=${{ matrix.arch }}" >> "$GITHUB_ENV" - $DOCKER_LOGIN - - uses: ./.github/workflows/setup-with-retry - with: - docker_hub_pat: ${{ secrets.DOCKER_HUB_PAT }} - - uses: ./.github/workflows/compile-openpilot - timeout-minutes: ${{ ((steps.restore-scons-cache.outputs.cache-hit == 'true') && 15 || 30) }} # allow more time when we missed the scons cache - - build_mac: - name: build macOS - runs-on: macos-latest - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - run: git lfs pull - - name: Install dependencies - run: ./tools/mac_setup.sh - env: - # package install has DeprecationWarnings - PYTHONWARNINGS: default - - run: echo "CACHE_COMMIT_DATE=$(git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d-%H:%M')" >> $GITHUB_ENV - - name: Getting scons cache - uses: 'actions/cache@v4' - with: - path: /tmp/scons_cache - key: scons-${{ runner.arch }}-macos-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} - restore-keys: | - scons-${{ runner.arch }}-macos-${{ env.CACHE_COMMIT_DATE }} - scons-${{ runner.arch }}-macos - - name: Building openpilot - run: . .venv/bin/activate && scons -j$(nproc) - - docker_push_multiarch: - name: docker push multiarch tag - runs-on: ubuntu-latest - if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' && github.repository == 'commaai/openpilot' - needs: [build] - steps: - - uses: actions/checkout@v4 - with: - submodules: false - - name: Setup docker - run: | - $DOCKER_LOGIN - - name: Merge x64 and arm64 tags - run: | - export PUSH_IMAGE=true - scripts/retry.sh selfdrive/test/docker_tag_multiarch.sh base x86_64 aarch64 - - static_analysis: - name: static analysis - runs-on: ${{ ((github.repository == 'commaai/openpilot') && - ((github.event_name != 'pull_request') || - (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-amd64-8x16' || 'ubuntu-24.04' }} - env: - PYTHONWARNINGS: default - steps: - - uses: actions/checkout@v4 - - name: Setup - run: tools/op.sh setup - - name: Static analysis - timeout-minutes: 1 - run: tools/op.sh lint - - unit_tests: - name: unit tests - runs-on: ${{ ((github.repository == 'commaai/openpilot') && - ((github.event_name != 'pull_request') || - (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-amd64-8x16' || 'ubuntu-latest' }} - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - with: - docker_hub_pat: ${{ secrets.DOCKER_HUB_PAT }} - - name: Build openpilot - timeout-minutes: ${{ ((steps.restore-scons-cache.outputs.cache-hit == 'true') && 10 || 30) }} # allow more time when we missed the scons cache - run: ${{ env.RUN }} "scons -j$(nproc)" - - name: Run unit tests - timeout-minutes: 15 - run: | - ${{ env.RUN }} "source selfdrive/test/setup_xvfb.sh && \ - $PYTEST --timeout 60 -m 'not slow' && \ - ./selfdrive/ui/tests/create_test_translations.sh && \ - QT_QPA_PLATFORM=offscreen ./selfdrive/ui/tests/test_translations && \ - pytest ./selfdrive/ui/tests/test_translations.py" - - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v4 - with: - name: ${{ github.job }} - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - process_replay: - name: process replay - runs-on: ${{ ((github.repository == 'commaai/openpilot') && - ((github.event_name != 'pull_request') || - (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-amd64-8x16' || 'ubuntu-latest' }} - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - with: - docker_hub_pat: ${{ secrets.DOCKER_HUB_PAT }} - - name: Cache test routes - id: dependency-cache - uses: actions/cache@v4 - with: - path: .ci_cache/comma_download_cache - key: proc-replay-${{ hashFiles('.github/workflows/selfdrive_tests.yaml', 'selfdrive/test/process_replay/ref_commit', 'selfdrive/test/process_replay/test_regen.py') }} - - name: Build openpilot - run: | - ${{ env.RUN }} "scons -j$(nproc)" - - name: Run replay - timeout-minutes: 30 - run: | - ${{ env.RUN }} "coverage run selfdrive/test/process_replay/test_processes.py -j$(nproc) && \ - chmod -R 777 /tmp/comma_download_cache && \ - coverage combine && \ - coverage xml" - - name: Print diff - id: print-diff - if: always() - run: cat selfdrive/test/process_replay/diff.txt - - uses: actions/upload-artifact@v4 - if: always() - continue-on-error: true - with: - name: process_replay_diff.txt - path: selfdrive/test/process_replay/diff.txt - - name: Upload reference logs - if: ${{ failure() && steps.print-diff.outcome == 'success' && github.repository == 'commaai/openpilot' && env.AZURE_TOKEN != '' }} - run: | - ${{ env.RUN }} "unset PYTHONWARNINGS && AZURE_TOKEN='$AZURE_TOKEN' python3 selfdrive/test/process_replay/test_processes.py -j$(nproc) --upload-only" - # PYTHONWARNINGS triggers a SyntaxError in onnxruntime - - name: Run model replay with ONNX - timeout-minutes: 4 - run: | - ${{ env.RUN }} "unset PYTHONWARNINGS && \ - ONNXCPU=1 NO_NAV=1 coverage run selfdrive/test/process_replay/model_replay.py && \ - coverage combine && coverage xml" - - name: Run regen - timeout-minutes: 4 - run: | - ${{ env.RUN }} "ONNXCPU=1 $PYTEST selfdrive/test/process_replay/test_regen.py && \ - chmod -R 777 /tmp/comma_download_cache" - - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v4 - with: - name: ${{ github.job }} - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - test_cars: - name: cars - runs-on: ${{ ((github.repository == 'commaai/openpilot') && - ((github.event_name != 'pull_request') || - (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-amd64-8x16' || 'ubuntu-latest' }} - strategy: - fail-fast: false - matrix: - job: [0, 1] - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Cache test routes - id: dependency-cache - uses: ./.github/workflows/auto-cache - with: - path: .ci_cache/comma_download_cache - key: car_models-${{ hashFiles('selfdrive/car/tests/test_models.py', 'selfdrive/car/tests/routes.py') }}-${{ matrix.job }} - - name: Build openpilot - run: ${{ env.RUN }} "scons -j$(nproc)" - - name: Test car models - timeout-minutes: 20 - run: | - ${{ env.RUN }} "$PYTEST selfdrive/car/tests/test_models.py && \ - chmod -R 777 /tmp/comma_download_cache" - env: - NUM_JOBS: 2 - JOB_ID: ${{ matrix.job }} - - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v4 - with: - name: ${{ github.job }}-${{ matrix.job }} - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - car_docs_diff: - name: PR comments - runs-on: ubuntu-latest - #if: github.event_name == 'pull_request' - if: false # TODO: run this in opendbc? - steps: - - uses: actions/checkout@v4 - with: - submodules: true - ref: ${{ github.event.pull_request.base.ref }} - - run: git lfs pull - - uses: ./.github/workflows/setup-with-retry - - name: Get base car info - run: | - ${{ env.RUN }} "scons -j$(nproc) && python3 selfdrive/debug/dump_car_docs.py --path /tmp/openpilot_cache/base_car_docs" - sudo chown -R $USER:$USER ${{ github.workspace }} - - uses: actions/checkout@v4 - with: - submodules: true - path: current - - run: cd current && git lfs pull - - name: Save car docs diff - id: save_diff - run: | - cd current - ${{ env.RUN }} "scons -j$(nproc)" - output=$(${{ env.RUN }} "python3 selfdrive/debug/print_docs_diff.py --path /tmp/openpilot_cache/base_car_docs") - output="${output//$'\n'/'%0A'}" - echo "::set-output name=diff::$output" - - name: Find comment - if: ${{ env.AZURE_TOKEN != '' }} - uses: peter-evans/find-comment@3eae4d37986fb5a8592848f6a574fdf654e61f9e - id: fc - with: - issue-number: ${{ github.event.pull_request.number }} - body-includes: This PR makes changes to - - name: Update comment - if: ${{ steps.save_diff.outputs.diff != '' && env.AZURE_TOKEN != '' }} - uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043 - with: - comment-id: ${{ steps.fc.outputs.comment-id }} - issue-number: ${{ github.event.pull_request.number }} - body: "${{ steps.save_diff.outputs.diff }}" - edit-mode: replace - - name: Delete comment - if: ${{ steps.fc.outputs.comment-id != '' && steps.save_diff.outputs.diff == '' && env.AZURE_TOKEN != '' }} - uses: actions/github-script@v7 - with: - script: | - github.rest.issues.deleteComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: ${{ steps.fc.outputs.comment-id }} - }) - - create_ui_report: - # This job name needs to be the same as UI_JOB_NAME in ui_preview.yaml - name: Create UI Report - runs-on: ubuntu-latest - if: github.event_name == 'pull_request' - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Build openpilot - run: ${{ env.RUN }} "scons -j$(nproc)" - - name: Create Test Report - run: > - ${{ env.RUN }} "PYTHONWARNINGS=ignore && - source selfdrive/test/setup_xvfb.sh && - python3 selfdrive/ui/tests/test_ui/run.py" - - name: Upload Test Report - uses: actions/upload-artifact@v4 - with: - name: report-${{ github.event.number }} - path: selfdrive/ui/tests/test_ui/report_1/screenshots diff --git a/.github/workflows/setup-with-retry/action.yaml b/.github/workflows/setup-with-retry/action.yaml deleted file mode 100644 index 369ac45c9a81f6..00000000000000 --- a/.github/workflows/setup-with-retry/action.yaml +++ /dev/null @@ -1,40 +0,0 @@ -name: 'openpilot env setup, with retry on failure' - -inputs: - docker_hub_pat: - description: 'Auth token for Docker Hub, required for BuildJet jobs' - required: false - default: '' - sleep_time: - description: 'Time to sleep between retries' - required: false - default: 30 - -runs: - using: "composite" - steps: - - id: setup1 - uses: ./.github/workflows/setup - continue-on-error: true - with: - docker_hub_pat: ${{ inputs.docker_hub_pat }} - is_retried: true - - if: steps.setup1.outcome == 'failure' - shell: bash - run: sleep ${{ inputs.sleep_time }} - - id: setup2 - if: steps.setup1.outcome == 'failure' - uses: ./.github/workflows/setup - continue-on-error: true - with: - docker_hub_pat: ${{ inputs.docker_hub_pat }} - is_retried: true - - if: steps.setup2.outcome == 'failure' - shell: bash - run: sleep ${{ inputs.sleep_time }} - - id: setup3 - if: steps.setup2.outcome == 'failure' - uses: ./.github/workflows/setup - with: - docker_hub_pat: ${{ inputs.docker_hub_pat }} - is_retried: true diff --git a/.github/workflows/setup/action.yaml b/.github/workflows/setup/action.yaml deleted file mode 100644 index 701675942f5f39..00000000000000 --- a/.github/workflows/setup/action.yaml +++ /dev/null @@ -1,63 +0,0 @@ -name: 'openpilot env setup' - -inputs: - docker_hub_pat: - description: 'Auth token for Docker Hub, required for BuildJet jobs' - required: true - default: '' - is_retried: - description: 'A mock param that asserts that we use the setup-with-retry instead of this action directly' - required: false - default: 'false' - -runs: - using: "composite" - steps: - # assert that this action is retried using the setup-with-retry - - shell: bash - if: ${{ inputs.is_retried == 'false' }} - run: | - echo "You should not run this action directly. Use setup-with-retry instead" - exit 1 - - # do this after checkout to ensure our custom LFS config is used to pull from GitLab - - shell: bash - run: git lfs pull - - # on BuildJet runners, must be logged into DockerHub to avoid rate limiting - # https://buildjet.com/for-github-actions/docs/guides/docker - - shell: bash - if: ${{ contains(runner.name, 'buildjet') && inputs.docker_hub_pat == '' }} - run: | - echo "Need to set the Docker Hub PAT secret as an input to this action" - exit 1 - - name: Login to Docker Hub - if: contains(runner.name, 'buildjet') - shell: bash - run: | - docker login -u adeebshihadeh -p ${{ inputs.docker_hub_pat }} - - # build cache - - id: date - shell: bash - run: echo "CACHE_COMMIT_DATE=$(git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d-%H:%M')" >> $GITHUB_ENV - - shell: bash - run: echo "$CACHE_COMMIT_DATE" - - id: scons-cache - uses: ./.github/workflows/auto-cache - with: - path: .ci_cache/scons_cache - key: scons-${{ runner.arch }}-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} - restore-keys: | - scons-${{ runner.arch }}-${{ env.CACHE_COMMIT_DATE }} - scons-${{ runner.arch }} - # as suggested here: https://github.com/moby/moby/issues/32816#issuecomment-910030001 - - id: normalize-file-permissions - shell: bash - name: Normalize file permissions to ensure a consistent docker build cache - run: | - find . -type f -executable -not -perm 755 -exec chmod 755 {} \; - find . -type f -not -executable -not -perm 644 -exec chmod 644 {} \; - # build our docker image - - shell: bash - run: eval ${{ env.BUILD }} diff --git a/.github/workflows/stale.yaml b/.github/workflows/stale.yaml index f7f92a0387bad8..cb7c0ac0764ca0 100644 --- a/.github/workflows/stale.yaml +++ b/.github/workflows/stale.yaml @@ -5,14 +5,15 @@ on: workflow_dispatch: env: - DAYS_BEFORE_PR_CLOSE: 2 - DAYS_BEFORE_PR_STALE: 9 + DAYS_BEFORE_PR_CLOSE: 7 + DAYS_BEFORE_PR_STALE: 24 + DAYS_BEFORE_PR_STALE_DRAFT: 30 jobs: stale: runs-on: ubuntu-latest steps: - - uses: actions/stale@v9 + - uses: actions/stale@v10 with: exempt-all-milestones: true @@ -21,9 +22,31 @@ jobs: close-pr-message: 'This PR has been automatically closed due to inactivity. Feel free to re-open once activity resumes.' stale-pr-label: stale delete-branch: ${{ github.event.pull_request.head.repo.full_name == 'commaai/openpilot' }} # only delete branches on the main repo - exempt-pr-labels: "ignore stale,needs testing,car port,car" # if wip or it needs testing from the community, don't mark as stale + exempt-pr-labels: "ignore stale,needs testing" # if wip or it needs testing from the community, don't mark as stale days-before-pr-stale: ${{ env.DAYS_BEFORE_PR_STALE }} days-before-pr-close: ${{ env.DAYS_BEFORE_PR_CLOSE }} + exempt-draft-pr: false + + # issue config + days-before-issue-stale: -1 # ignore issues for now + + # same as above, but give draft PRs more time + stale_drafts: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v10 + with: + exempt-all-milestones: true + + # pull request config + stale-pr-message: 'This PR has had no activity for ${{ env.DAYS_BEFORE_PR_STALE_DRAFT }} days. It will be automatically closed in ${{ env.DAYS_BEFORE_PR_CLOSE }} days if there is no activity.' + close-pr-message: 'This PR has been automatically closed due to inactivity. Feel free to re-open once activity resumes.' + stale-pr-label: stale + delete-branch: ${{ github.event.pull_request.head.repo.full_name == 'commaai/openpilot' }} # only delete branches on the main repo + exempt-pr-labels: "ignore stale,needs testing" # if wip or it needs testing from the community, don't mark as stale + days-before-pr-stale: ${{ env.DAYS_BEFORE_PR_STALE_DRAFT }} + days-before-pr-close: ${{ env.DAYS_BEFORE_PR_CLOSE }} + exempt-draft-pr: true # issue config days-before-issue-stale: -1 # ignore issues for now diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 00000000000000..dfdc01b0b1da2b --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,384 @@ +name: tests + +on: + push: + branches: + - master + - 'nap-*' + pull_request: + workflow_dispatch: + workflow_call: + inputs: + run_number: + default: '1' + required: true + type: string + +concurrency: + group: tests-ci-run-${{ inputs.run_number }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && github.run_id || github.head_ref || github.ref }}-${{ github.workflow }}-${{ github.event_name }} + cancel-in-progress: true + +env: + CI: 1 + PYTHONPATH: ${{ github.workspace }} + PYTEST: pytest --continue-on-collection-errors --durations=0 -n logical + OPENPILOT_LFS_URL: https://github.com/${{ github.repository }}.git/info/lfs + +jobs: + tesla_preap_longitudinal_regression: + name: Tesla Pre-AP longitudinal regressions + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + with: + submodules: true + - name: Check workflow contract + run: python3 .github/ci/test_tesla_preap_longitudinal_workflow.py + - name: Set up dependencies + uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e + with: + timeout_minutes: 10 + max_attempts: 3 + command: ./tools/op.sh setup + - name: Build focused test dependencies + run: scons -j$(nproc) + - name: Run focused longitudinal tests + run: | + pytest -q -n 0 \ + selfdrive/controls/tests/test_following_distance.py \ + selfdrive/controls/tests/test_follow_distance.py \ + selfdrive/controls/tests/test_lead_approach.py \ + selfdrive/controls/tests/test_firm_brake_latch.py \ + selfdrive/selfdrived/tests/test_preap_regen_cmd_pin.py \ + selfdrive/mapd/tests/test_map_speed_policy.py \ + selfdrive/mapd/tests/test_map_speed_policy_2.py \ + selfdrive/mapd/tests/test_map_speed_offset_slew.py \ + selfdrive/mapd/tests/test_map_match_frontage.py \ + selfdrive/mapd/tests/test_map_match_road_class.py \ + selfdrive/car/tests/test_preap_engage_max_after_pause.py \ + selfdrive/controls/tests/test_radard.py \ + selfdrive/controls/tests/test_path_obstacle_radar.py \ + selfdrive/controls/lib/tests/test_path_obstacle.py \ + selfdrive/controls/tests/test_radar_path_gate.py \ + selfdrive/controls/tests/test_rain_radar_hold.py \ + selfdrive/controls/tests/test_radar_sensor_dirty.py \ + selfdrive/controls/tests/test_tesla_preap_following.py \ + selfdrive/controls/tests/test_unified_lead.py \ + selfdrive/controls/tests/test_farm_cutin_follow.py \ + selfdrive/controls/tests/test_crossing_vehicle.py \ + selfdrive/controls/tests/test_gap_lock_gesture.py \ + selfdrive/controls/tests/test_gap_lock_latch.py \ + selfdrive/controls/tests/test_unified_far_gap_gate.py \ + selfdrive/controls/tests/test_unified_far_gap_catchup.py \ + selfdrive/controls/tests/test_unified_lead_planner.py \ + selfdrive/controls/tests/test_curve_preview.py \ + selfdrive/controls/tests/test_curve_follow.py \ + selfdrive/controls/tests/test_curve_follow_planner.py \ + selfdrive/controls/tests/test_sight_cap_planner.py \ + selfdrive/controls/tests/test_sight_cap_replay.py \ + selfdrive/controls/tests/test_model_sight.py \ + selfdrive/car/tests/test_curve_follow_card_max.py \ + selfdrive/controls/tests/test_lead_leaving.py \ + selfdrive/controls/lib/tests/test_curve_max_hold.py \ + selfdrive/controls/lib/tests/test_lat_turn_geometry.py \ + selfdrive/controls/lib/tests/test_lane_change_confirm_replay.py \ + selfdrive/controls/lib/tests/test_lane_change_nudge.py \ + selfdrive/controls/lib/tests/test_lane_change_target.py \ + selfdrive/controls/lib/tests/test_lane_change_lock.py \ + selfdrive/controls/lib/tests/test_lane_change_turn.py \ + selfdrive/mapd/tests/test_roundabout.py \ + selfdrive/mapd/tests/test_roundabout_map.py \ + selfdrive/controls/lib/tests/test_roundabout_guide.py \ + selfdrive/controls/lib/tests/test_roundabout_ring_hold.py \ + selfdrive/controls/lib/tests/test_driver_lateral_handoff_early_yield.py \ + selfdrive/controls/lib/tests/test_driver_lateral_handoff_wheel_resume.py \ + selfdrive/controls/lib/tests/test_lat_yield_inference_guard.py \ + selfdrive/car/tesla/tests/test_preap_lat_yield.py \ + selfdrive/controls/tests/test_roundabout_planner.py \ + selfdrive/controls/tests/test_tesla_preap_longcontrol.py \ + selfdrive/controls/tests/test_tesla_preap_gas_lift_handoff.py \ + selfdrive/controls/tests/test_tesla_preap_brake_cancel_regen.py \ + selfdrive/controls/tests/test_preap_brake_long_active.py \ + selfdrive/controls/tests/test_tesla_preap_one_pedal_long.py \ + opendbc_repo/opendbc/car/tesla/preap/tests/test_preap_carstate.py \ + opendbc_repo/opendbc/car/tesla/preap/tests/test_preap_engagement.py \ + opendbc_repo/opendbc/car/tesla/preap/tests/test_lat_yield.py \ + opendbc_repo/opendbc/car/tesla/preap/tests/test_longitudinal_tuning.py \ + opendbc_repo/opendbc/car/tesla/preap/tests/test_virtual_das.py \ + opendbc_repo/opendbc/car/tesla/preap/tests/test_vdas_grade_control.py + - name: Run historical mutation checks + run: python .github/ci/tesla_preap_longitudinal_mutations.py + - name: Run roundabout mutation checks + run: python .github/ci/tesla_preap_roundabout_mutations.py + - name: Run lane-change mutation checks + run: python .github/ci/tesla_preap_lane_change_mutations.py + - name: Run lateral-yield mutation checks + run: python .github/ci/tesla_preap_lat_yield_mutations.py + + build_release: + name: build release + runs-on: ${{ + (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('["ubuntu-24.04"]') }} + env: + STRIPPED_DIR: /tmp/releasepilot + PYTHONPATH: /tmp/releasepilot + steps: + - uses: actions/checkout@v6 + with: + submodules: true + - name: Getting LFS files + uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e + with: + timeout_minutes: 2 + max_attempts: 3 + command: git config lfs.url "$OPENPILOT_LFS_URL" && git lfs pull + - name: Build devel + timeout-minutes: 1 + run: TARGET_DIR=$STRIPPED_DIR release/build_stripped.sh + - run: ./tools/op.sh setup + - name: Install video encoding deps + run: sudo apt-get install -y libva-dev libva-drm2 libdrm-dev + - name: Build openpilot and run checks + timeout-minutes: 30 + working-directory: ${{ env.STRIPPED_DIR }} + run: python3 system/manager/build.py + - name: Run tests + timeout-minutes: 1 + working-directory: ${{ env.STRIPPED_DIR }} + run: release/check-dirty.sh + - name: Check submodules + if: github.repository == 'commaai/openpilot' + timeout-minutes: 3 + run: release/check-submodules.sh + + build_mac: + name: build macOS + runs-on: ${{ ((github.repository == 'commaai/openpilot') && ((github.event_name != 'pull_request') || (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-macos-8x14' || 'macos-latest' }} + steps: + - uses: actions/checkout@v6 + with: + submodules: true + - name: Remove Homebrew from environment + run: | + FILTERED=$(echo "$PATH" | tr ':' '\n' | grep -v '/opt/homebrew' | tr '\n' ':') + echo "PATH=${FILTERED}/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" >> $GITHUB_ENV + - run: ./tools/op.sh setup + - name: Building openpilot + run: scons + + static_analysis: + name: static analysis + runs-on: ${{ + (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('["ubuntu-24.04"]') }} + steps: + - uses: actions/checkout@v6 + with: + submodules: true + - run: ./tools/op.sh setup + - name: Static analysis + timeout-minutes: 1 + run: scripts/lint/lint.sh + + unit_tests: + name: unit tests + runs-on: ${{ + (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('["ubuntu-24.04"]') }} + steps: + - uses: actions/checkout@v6 + with: + submodules: true + - run: ./tools/op.sh setup + - name: Install extra deps + run: | + sudo apt-get install -y libva-dev libva-drm2 libdrm-dev + uv pip install natsort + - name: Build openpilot + run: scons -j$(nproc) + - name: Validate process replay release contracts + run: | + pytest -q -n 0 \ + .github/ci/test_assemble_replay_release.py \ + .github/ci/test_validate_process_replay_release.py + - name: Run unit tests + timeout-minutes: ${{ contains(runner.name, 'nsc') && 2 || 20 }} + run: | + source selfdrive/test/setup_xvfb.sh + # Pre-compile Python bytecode so each pytest worker doesn't need to + $PYTEST --collect-only -m 'not slow' -qq + MAX_EXAMPLES=1 $PYTEST -m 'not slow' + + process_replay: + name: process replay (${{ matrix.shard }}) + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - shard: card + filter_args: "--whitelist-procs card" + expected_tasks: 16 + - shard: controlsd + filter_args: "--whitelist-procs controlsd" + expected_tasks: 16 + - shard: lagd + filter_args: "--whitelist-procs lagd" + expected_tasks: 16 + - shard: other + filter_args: "--blacklist-procs card controlsd lagd" + expected_tasks: 18 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + submodules: true + persist-credentials: false + - name: Set up dependencies + uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e + with: + timeout_minutes: 10 + max_attempts: 3 + command: ./tools/op.sh setup + - name: Install video encoding deps + run: sudo apt-get install -y libva-dev libva-drm2 libdrm-dev + - name: Build openpilot + run: scons -j$(nproc) + - name: Verify shard inventory contracts + env: + SHARD: ${{ matrix.shard }} + FILTER_ARGS: ${{ matrix.filter_args }} + EXPECTED_TASKS: ${{ matrix.expected_tasks }} + run: | + set -euo pipefail + REPLAY=selfdrive/test/process_replay/test_processes.py + + python3 - <<'PY' + from openpilot.selfdrive.test.process_replay import test_processes as tp + + active_cases = tp.select_cases("active") + staged_cases = tp.select_cases("staged") + tp.assert_inventory_invariants(active_cases) + tp.assert_inventory_invariants(staged_cases) + + assert len(active_cases) == 16, len(active_cases) + assert len(staged_cases) == 18, len(staged_cases) + + active_tasks = tp.build_tasks(active_cases) + staged_tasks = tp.build_tasks(staged_cases) + assert len(active_tasks) == 66, len(active_tasks) + assert len(staged_tasks) == 78, len(staged_tasks) + + active_counts = {name: len(tp.shard_task_ids(active_tasks, name)) for name in ("card", "controlsd", "lagd", "other")} + assert active_counts == {"card": 16, "controlsd": 16, "lagd": 16, "other": 18}, active_counts + assert sum(active_counts.values()) == 66 + + staged_counts = {name: len(tp.shard_task_ids(staged_tasks, name)) for name in ("card", "controlsd", "lagd", "other")} + assert staged_counts == {"card": 18, "controlsd": 18, "lagd": 18, "other": 24}, staged_counts + assert sum(staged_counts.values()) == 78 + + staged_task_ids = {task.task_id for task in staged_tasks} + staged_union = set(tp.shard_task_ids(staged_tasks, "card")) + staged_union |= set(tp.shard_task_ids(staged_tasks, "controlsd")) + staged_union |= set(tp.shard_task_ids(staged_tasks, "lagd")) + staged_union |= set(tp.shard_task_ids(staged_tasks, "other")) + assert staged_union == staged_task_ids, (len(staged_union), len(staged_task_ids)) + assert len(staged_union) == 78, len(staged_union) + print("inventory unit checks passed:", active_counts, staged_counts) + PY + + mapfile -t shard_tasks < <(${REPLAY} --inventory active --list-tasks ${FILTER_ARGS}) + echo "shard=${SHARD} list-tasks count=${#shard_tasks[@]}" + printf '%s\n' "${shard_tasks[@]}" + test "${#shard_tasks[@]}" -eq "${EXPECTED_TASKS}" + + active_total="$(${REPLAY} --inventory active --list-tasks | wc -l)" + staged_total="$(${REPLAY} --inventory staged --list-tasks | wc -l)" + echo "active_total=${active_total} staged_total=${staged_total}" + test "${active_total}" -eq 66 + test "${staged_total}" -eq 78 + - name: Run replay + run: | + set -euo pipefail + OUT_DIR="selfdrive/test/process_replay/out/${{ matrix.shard }}" + mkdir -p "${OUT_DIR}" + selfdrive/test/process_replay/test_processes.py \ + -j$(nproc) \ + --inventory active \ + --output-dir "${OUT_DIR}" \ + ${{ matrix.filter_args }} + - name: Print diff + if: always() + run: cat selfdrive/test/process_replay/out/${{ matrix.shard }}/diff.txt + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + if: always() + with: + name: process_replay_${{ matrix.shard }} + path: | + selfdrive/test/process_replay/out/${{ matrix.shard }}/diff.txt + selfdrive/test/process_replay/out/${{ matrix.shard }}/results.json + selfdrive/test/process_replay/fakedata + if-no-files-found: error + + simulator_driving: + name: simulator driving + runs-on: ${{ + (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('["ubuntu-24.04"]') }} + if: false # FIXME: Started to timeout recently + steps: + - uses: actions/checkout@v6 + with: + submodules: true + - run: ./tools/op.sh setup + - name: Build openpilot + run: scons -j$(nproc) + - name: Driving test + timeout-minutes: 2 + run: | + source selfdrive/test/setup_xvfb.sh + pytest -s tools/sim/tests/test_metadrive_bridge.py + + create_ui_report: + name: Create UI Report + runs-on: ${{ + (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('["ubuntu-24.04"]') }} + steps: + - uses: actions/checkout@v6 + with: + submodules: true + - run: ./tools/op.sh setup + - name: Install video encoding deps + run: sudo apt-get install -y libva-dev libva-drm2 libdrm-dev + - name: Build openpilot + run: scons -j$(nproc) + - name: Create UI Report + run: | + source selfdrive/test/setup_xvfb.sh + python3 selfdrive/ui/tests/diff/replay.py + python3 selfdrive/ui/tests/diff/replay.py --big + - name: Upload UI Report + uses: actions/upload-artifact@v6 + with: + name: ui-report-${{ inputs.run_number || '1' }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && 'master' || github.event.number }} + path: selfdrive/ui/tests/diff/report diff --git a/.github/workflows/tools_tests.yaml b/.github/workflows/tools_tests.yaml deleted file mode 100644 index 271e4bda17f162..00000000000000 --- a/.github/workflows/tools_tests.yaml +++ /dev/null @@ -1,102 +0,0 @@ -name: tools - -on: - push: - branches: - - master - pull_request: - workflow_call: - inputs: - run_number: - default: '1' - required: true - type: string -concurrency: - group: tools-tests-ci-run-${{ inputs.run_number }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && github.run_id || github.head_ref || github.ref }}-${{ github.workflow }}-${{ github.event_name }} - cancel-in-progress: true - -env: - BASE_IMAGE: openpilot-base - DOCKER_LOGIN: docker login ghcr.io -u ${{ github.actor }} -p ${{ secrets.GITHUB_TOKEN }} - - BUILD: selfdrive/test/docker_build.sh base - - RUN: docker run --shm-size 2G -v $GITHUB_WORKSPACE:/tmp/openpilot -w /tmp/openpilot -e FILEREADER_CACHE=1 -e PYTHONPATH=/tmp/openpilot -e NUM_JOBS -e JOB_ID -e GITHUB_ACTION -e GITHUB_REF -e GITHUB_HEAD_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_RUN_ID -v $GITHUB_WORKSPACE/.ci_cache/scons_cache:/tmp/scons_cache -v $GITHUB_WORKSPACE/.ci_cache/comma_download_cache:/tmp/comma_download_cache -v $GITHUB_WORKSPACE/.ci_cache/openpilot_cache:/tmp/openpilot_cache $BASE_IMAGE /bin/bash -c - - -jobs: - simulator_driving: - name: simulator driving - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Build openpilot - run: | - ${{ env.RUN }} "scons -j$(nproc)" - - name: Run bridge test - run: | - ${{ env.RUN }} "source selfdrive/test/setup_xvfb.sh && \ - source selfdrive/test/setup_vsound.sh && \ - CI=1 pytest tools/sim/tests/test_metadrive_bridge.py" - - test_compatibility: - name: test 20.04 + 3.11 - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - name: Installing ubuntu dependencies - run: INSTALL_EXTRA_PACKAGES=no tools/install_ubuntu_dependencies.sh - - name: Installing python - uses: actions/setup-python@v5 - with: - python-version: '3.11.4' - - name: Installing pip - run: pip install pip==24.0 - - name: Installing uv - run: pip install uv - - name: git LFS - run: git lfs pull - - run: echo "CACHE_COMMIT_DATE=$(git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d-%H:%M')" >> $GITHUB_ENV - - name: Getting scons cache - uses: 'actions/cache@v4' - with: - path: /tmp/scons_cache - key: scons-${{ runner.arch }}-ubuntu2004-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} - restore-keys: | - scons-${{ runner.arch }}-ubuntu2004-${{ env.CACHE_COMMIT_DATE }} - scons-${{ runner.arch }}-ubuntu2004 - - name: Building openpilot - run: uv run scons -u -j$(nproc) - - devcontainer: - name: devcontainer - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Use local image for testing devcontainer with latest base image - run: | - echo "USE_LOCAL_IMAGE=true" >> "$GITHUB_ENV" - - name: Setup Dev Container CLI - run: npm install -g @devcontainers/cli - - name: Build dev container image - run: ./scripts/retry.sh devcontainer build --workspace-folder . - - name: Run dev container - run: | - mkdir -p /tmp/devcontainer_scons_cache/ - cp -r $GITHUB_WORKSPACE/.ci_cache/scons_cache/. /tmp/devcontainer_scons_cache/ - devcontainer up --workspace-folder . - - name: Test environment - run: | - devcontainer exec --workspace-folder . scons -j$(nproc) cereal/ common/ - devcontainer exec --workspace-folder . pip3 install pip-install-test - devcontainer exec --workspace-folder . touch /home/batman/.comma/auth.json - devcontainer exec --workspace-folder . sudo touch /root/test.txt diff --git a/.github/workflows/ui_preview.yaml b/.github/workflows/ui_preview.yaml index c6d70e9ceb5d69..72ced4985228d1 100644 --- a/.github/workflows/ui_preview.yaml +++ b/.github/workflows/ui_preview.yaml @@ -1,15 +1,27 @@ name: "ui preview" on: + push: + branches: + - master pull_request_target: types: [assigned, opened, synchronize, reopened, edited] branches: - 'master' paths: + - 'selfdrive/assets/**' - 'selfdrive/ui/**' + - 'system/ui/**' workflow_dispatch: env: UI_JOB_NAME: "Create UI Report" + REPORT_NAME: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && 'master' || github.event.number }} + SHA: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && github.sha || github.event.pull_request.head.sha }} + BRANCH_NAME: "openpilot/pr-${{ github.event.number }}-ui-preview" + REPORT_FILES_BRANCH_NAME: "mici-raylib-ui-reports" + + # variant:video_prefix:master_branch + VARIANTS: "mici:mici_ui_replay:openpilot_master_ui_mici_raylib big:tizi_ui_replay:openpilot_master_ui_big_raylib" jobs: preview: @@ -22,87 +34,142 @@ jobs: pull-requests: write actions: read steps: - - name: Waiting for ui test to start - run: sleep 30 + - uses: actions/checkout@v6 + with: + submodules: true - - name: Wait for ui report + - name: Waiting for ui generation to end uses: lewagon/wait-on-check-action@v1.3.4 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ env.SHA }} check-name: ${{ env.UI_JOB_NAME }} repo-token: ${{ secrets.GITHUB_TOKEN }} allowed-conclusions: success wait-interval: 20 - - name: Get workflow run ID + - name: Getting workflow run ID id: get_run_id run: | - echo "run_id=$(curl https://api.github.com/repos/${{ github.repository }}/commits/${{ github.event.pull_request.head.sha }}/check-runs | jq -r '.check_runs[] | select(.name == "${{ env.UI_JOB_NAME }}") | .html_url | capture("(?[0-9]+)") | .number')" >> $GITHUB_OUTPUT - - - name: Checkout ci-artifacts - uses: actions/checkout@v4 - with: - repository: commaai/ci-artifacts - ssh-key: ${{ secrets.CI_ARTIFACTS_DEPLOY_KEY }} - path: ${{ github.workspace }}/ci-artifacts - ref: master + echo "run_id=$(curl https://api.github.com/repos/${{ github.repository }}/commits/${{ env.SHA }}/check-runs | jq -r '.check_runs[] | select(.name == "${{ env.UI_JOB_NAME }}") | .html_url | capture("(?[0-9]+)") | .number')" >> $GITHUB_OUTPUT - - name: Download artifact - id: download-artifact + - name: Getting proposed ui uses: dawidd6/action-download-artifact@v6 with: github_token: ${{ secrets.GITHUB_TOKEN }} run_id: ${{ steps.get_run_id.outputs.run_id }} search_artifacts: true - name: report-${{ github.event.number }} - path: ${{ github.workspace }}/ci-artifacts + name: ui-report-1-${{ env.REPORT_NAME }} + path: ${{ github.workspace }}/pr_ui - - name: Push Screenshots - working-directory: ${{ github.workspace }}/ci-artifacts + - name: Getting mici master ui + uses: actions/checkout@v6 + with: + repository: commaai/ci-artifacts + ssh-key: ${{ secrets.CI_ARTIFACTS_DEPLOY_KEY }} + path: ${{ github.workspace }}/master_mici + ref: openpilot_master_ui_mici_raylib + + - name: Getting big master ui + uses: actions/checkout@v6 + with: + repository: commaai/ci-artifacts + ssh-key: ${{ secrets.CI_ARTIFACTS_DEPLOY_KEY }} + path: ${{ github.workspace }}/master_big + ref: openpilot_master_ui_big_raylib + + - name: Saving new master ui + if: github.ref == 'refs/heads/master' && github.event_name == 'push' + run: | + for variant in $VARIANTS; do + IFS=':' read -r name video branch <<< "$variant" + master_dir="${{ github.workspace }}/master_${name}" + cd "$master_dir" + git checkout --orphan=new_branch + git rm -rf * + git branch -D "$branch" + git branch -m "$branch" + git config user.name "GitHub Actions Bot" + git config user.email "<>" + cp "${{ github.workspace }}/pr_ui/${video}.mp4" . + git add . + git commit -m "${name} video for commit ${{ env.SHA }}" + git push origin "$branch" --force + done + + - name: Setup FFmpeg + uses: AnimMouse/setup-ffmpeg@ae28d57dabbb148eff63170b6bf7f2b60062cbae + + - name: Finding diffs + if: github.event_name == 'pull_request_target' + id: find_diff + run: | + export PYTHONPATH=${{ github.workspace }} + baseurl="https://github.com/commaai/ci-artifacts/raw/refs/heads/${{ env.BRANCH_NAME }}" + + COMMENT="" + for variant in $VARIANTS; do + IFS=':' read -r name video _ <<< "$variant" + diff_name="${name}_diff" + + mv "${{ github.workspace }}/pr_ui/${video}.mp4" "${{ github.workspace }}/pr_ui/${video}_proposed.mp4" + cp "${{ github.workspace }}/master_${name}/${video}.mp4" "${{ github.workspace }}/pr_ui/${video}_master.mp4" + + diff_exit_code=0 + python3 ${{ github.workspace }}/selfdrive/ui/tests/diff/diff.py \ + "${{ github.workspace }}/pr_ui/${video}_master.mp4" \ + "${{ github.workspace }}/pr_ui/${video}_proposed.mp4" \ + "${diff_name}.html" --basedir "$baseurl" --no-open || diff_exit_code=$? + + cp "${{ github.workspace }}/selfdrive/ui/tests/diff/report/${diff_name}.html" "${{ github.workspace }}/pr_ui/" + cp "${{ github.workspace }}/selfdrive/ui/tests/diff/report/${diff_name}.mp4" "${{ github.workspace }}/pr_ui/" + + REPORT_URL="https://commaai.github.io/ci-artifacts/${diff_name}_pr_${{ github.event.number }}.html" + if [ $diff_exit_code -eq 0 ]; then + COMMENT+="**${name}**: Videos are identical! [View Diff Report]($REPORT_URL)"$'\n' + else + COMMENT+="**${name}**: ⚠️ Videos differ! [View Diff Report]($REPORT_URL)"$'\n' + fi + done + + { + echo "COMMENT<> "$GITHUB_OUTPUT" + + - name: Saving proposed ui + if: github.event_name == 'pull_request_target' + working-directory: ${{ github.workspace }}/master_mici run: | - git checkout -b openpilot/pr-${{ github.event.number }} git config user.name "GitHub Actions Bot" git config user.email "<>" - git add ${{ github.workspace }}/ci-artifacts/* - git commit -m "screenshots for PR #${{ github.event.number }}" - git push origin openpilot/pr-${{ github.event.number }} --force + git checkout --orphan=${{ env.BRANCH_NAME }} + git rm -rf * + mv ${{ github.workspace }}/pr_ui/* . + git add . + git commit -m "ui videos for PR #${{ github.event.number }}" + git push origin ${{ env.BRANCH_NAME }} --force + + # Append diff reports to report files branch + git fetch origin ${{ env.REPORT_FILES_BRANCH_NAME }} + git checkout ${{ env.REPORT_FILES_BRANCH_NAME }} + for variant in $VARIANTS; do + IFS=':' read -r name _ _ <<< "$variant" + diff_name="${name}_diff" + cp "${{ github.workspace }}/selfdrive/ui/tests/diff/report/${diff_name}.html" "${diff_name}_pr_${{ github.event.number }}.html" + git add "${diff_name}_pr_${{ github.event.number }}.html" + done + git commit -m "ui diff reports for PR #${{ github.event.number }}" || echo "No changes to commit" + git push origin ${{ env.REPORT_FILES_BRANCH_NAME }} - - name: Comment Screenshots on PR + - name: Comment on PR + if: github.event_name == 'pull_request_target' uses: thollander/actions-comment-pull-request@v2 with: message: | - - ## UI Screenshots - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- comment_tag: run_id_screenshots + + ## UI Preview + ${{ steps.find_diff.outputs.COMMENT }} + comment_tag: run_id_ui_preview pr_number: ${{ github.event.number }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index d66823bb506f4b..f9db2b2a02fe66 100644 --- a/.gitignore +++ b/.gitignore @@ -10,15 +10,22 @@ venv/ .overlay_init .overlay_consistent .sconsign.dblite -model2.png + +# AI/assistant config — local only +CLAUDE.md +.claude/ +.cursor/ +.copilot/ a.out .hypothesis +.cache/ +bin/ -/docs_site/ - +*.mp4 *.dylib *.DSYM *.d +*.pem *.pyc *.pyo .*.swp @@ -35,73 +42,55 @@ a.out *.class *.pyxbldc *.vcd -*.qm +*.mo +*_pyx.cpp +*.stats +*.pkl +*.pkl* config.json -clcache compile_commands.json compare_runtime*.html +selfdrive/modeld/models/tg_input_devices.json -persist +# build artifacts +docs_site/ selfdrive/pandad/pandad cereal/services.h cereal/gen cereal/messaging/bridge -selfdrive/logcatd/logcatd -selfdrive/mapd/default_speeds_by_region.json -system/proclogd/proclogd -selfdrive/ui/translations/alerts_generated.h selfdrive/ui/translations/tmp -selfdrive/test/longitudinal_maneuvers/out selfdrive/car/tests/cars_dump system/camerad/camerad system/camerad/test/ae_gray_test -selfdrive/modeld/_modeld -selfdrive/modeld/_dmonitoringmodeld -/src/ - -notebooks -hyperthneed -provisioning .coverage* coverage.xml htmlcov -pandaextra - -.mypy_cache/ -flycheck_* - -cppcheck_report.txt -comma*.sh - -selfdrive/modeld/thneed/compile -selfdrive/modeld/models/*.thneed -selfdrive/modeld/models/*.pkl +# openpilot log files *.bz2 +*.zst +*.rlog build/ !**/.gitkeep -poetry.toml -Pipfile ### VisualStudioCode ### +*.vsix +.history +.ionide .vscode/* +.history/ !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json !.vscode/*.code-snippets -# Local History for Visual Studio Code -.history/ - -# Built Visual Studio Code Extensions -*.vsix - -### VisualStudioCode Patch ### -# Ignore all local history of files -.history -.ionide +# agents +.claude/ +.context/ +PLAN.md +TASK.md diff --git a/.gitmodules b/.gitmodules index ad6530de9ac910..c9476fb9819055 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,11 @@ [submodule "panda"] path = panda - url = ../../commaai/panda.git + url = https://github.com/NotAutopilot/panda.git + branch = master-nap [submodule "opendbc"] path = opendbc_repo - url = ../../commaai/opendbc.git + url = https://github.com/jmbrunick/opendbc.git + branch = nap-dev [submodule "msgq"] path = msgq_repo url = ../../commaai/msgq.git diff --git a/.python-version b/.python-version new file mode 100644 index 00000000000000..28d9a01b1faabb --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.12.13 diff --git a/.vscode/launch.json b/.vscode/launch.json index a6b341d9eafbdd..151b757dabbece 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -23,6 +23,11 @@ "id": "args", "description": "Arguments to pass to the process", "type": "promptString" + }, + { + "id": "replayArg", + "type": "promptString", + "description": "Enter route or segment to replay." } ], "configurations": [ @@ -40,7 +45,44 @@ "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/${input:cpp_process}", - "cwd": "${workspaceFolder}", + "cwd": "${workspaceFolder}" + }, + { + "name": "Attach LLDB to Replay drive", + "type": "lldb", + "request": "attach", + "pid": "${command:pickMyProcess}", + "sourceMap": { + ".": "${workspaceFolder}/opendbc/safety" + }, + "initCommands": [ + "script import time; time.sleep(3)" + ] + }, + { + "name": "Replay drive", + "type": "debugpy", + "request": "launch", + "program": "${workspaceFolder}/opendbc/safety/tests/safety_replay/replay_drive.py", + "args": [ + "${input:replayArg}" + ], + "console": "integratedTerminal", + "justMyCode": false, + "env": { + "PYTHONPATH": "${workspaceFolder}" + }, + "subProcess": true, + "stopOnEntry": false + } + ], + "compounds": [ + { + "name": "Replay drive + Safety LLDB", + "configurations": [ + "Replay drive", + "Attach LLDB to Replay drive" + ] } ] } \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index f0731c362d9a5c..811306f399cdac 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -21,7 +21,6 @@ "common/**", "selfdrive/**", "system/**", - "third_party/**", "tools/**", ] } diff --git a/Dockerfile.openpilot b/Dockerfile.openpilot index e26a427eb1aba9..802effe69958b7 100644 --- a/Dockerfile.openpilot +++ b/Dockerfile.openpilot @@ -1,13 +1,38 @@ -FROM ghcr.io/commaai/openpilot-base:latest +FROM ubuntu:24.04 -ENV PYTHONUNBUFFERED 1 +ENV PYTHONUNBUFFERED=1 -ENV OPENPILOT_PATH /home/batman/openpilot -ENV PYTHONPATH ${OPENPILOT_PATH}:${PYTHONPATH} +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && \ + apt-get install -y --no-install-recommends sudo tzdata locales libgl1 libglib2.0-0 && \ + rm -rf /var/lib/apt/lists/* +RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen +ENV LANG=en_US.UTF-8 +ENV LANGUAGE=en_US:en +ENV LC_ALL=en_US.UTF-8 + +ENV NVIDIA_VISIBLE_DEVICES=all +ENV NVIDIA_DRIVER_CAPABILITIES=graphics,utility,compute + +ARG USER=batman +ARG USER_UID=1001 +RUN useradd -m -s /bin/bash -u $USER_UID $USER +RUN usermod -aG sudo $USER +RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers +USER $USER + +ENV OPENPILOT_PATH=/home/$USER/openpilot RUN mkdir -p ${OPENPILOT_PATH} WORKDIR ${OPENPILOT_PATH} -COPY . ${OPENPILOT_PATH}/ +COPY --chown=$USER . ${OPENPILOT_PATH}/ + +ENV UV_BIN="/home/$USER/.local/bin/" +ENV VIRTUAL_ENV=${OPENPILOT_PATH}/.venv +ENV PATH="$UV_BIN:$VIRTUAL_ENV/bin:$PATH" +RUN tools/setup_dependencies.sh && \ + sudo rm -rf /var/lib/apt/lists/* -RUN scons --cache-readonly -j$(nproc) +USER root +RUN git config --global --add safe.directory '*' diff --git a/Dockerfile.openpilot_base b/Dockerfile.openpilot_base deleted file mode 100644 index 6dbd249c2355a6..00000000000000 --- a/Dockerfile.openpilot_base +++ /dev/null @@ -1,84 +0,0 @@ -FROM ubuntu:24.04 - -ENV PYTHONUNBUFFERED 1 - -ENV DEBIAN_FRONTEND=noninteractive -RUN apt-get update && \ - apt-get install -y --no-install-recommends sudo tzdata locales ssh pulseaudio xvfb x11-xserver-utils gnome-screenshot && \ - rm -rf /var/lib/apt/lists/* - -RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen -ENV LANG en_US.UTF-8 -ENV LANGUAGE en_US:en -ENV LC_ALL en_US.UTF-8 - -COPY tools/install_ubuntu_dependencies.sh /tmp/tools/ -RUN /tmp/tools/install_ubuntu_dependencies.sh && \ - rm -rf /var/lib/apt/lists/* /tmp/* && \ - cd /usr/lib/gcc/arm-none-eabi/* && \ - rm -rf arm/ thumb/nofp thumb/v6* thumb/v8* thumb/v7+fp thumb/v7-r+fp.sp - -# Add OpenCL -RUN apt-get update && apt-get install -y --no-install-recommends \ - apt-utils \ - alien \ - unzip \ - tar \ - curl \ - xz-utils \ - dbus \ - gcc-arm-none-eabi \ - tmux \ - vim \ - libx11-6 \ - wget \ - && rm -rf /var/lib/apt/lists/* - -RUN mkdir -p /tmp/opencl-driver-intel && \ - cd /tmp/opencl-driver-intel && \ - wget https://github.com/intel/llvm/releases/download/2024-WW14/oclcpuexp-2024.17.3.0.09_rel.tar.gz && \ - wget https://github.com/oneapi-src/oneTBB/releases/download/v2021.12.0/oneapi-tbb-2021.12.0-lin.tgz && \ - mkdir -p /opt/intel/oclcpuexp_2024.17.3.0.09_rel && \ - cd /opt/intel/oclcpuexp_2024.17.3.0.09_rel && \ - tar -zxvf /tmp/opencl-driver-intel/oclcpuexp-2024.17.3.0.09_rel.tar.gz && \ - mkdir -p /etc/OpenCL/vendors && \ - echo /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64/libintelocl.so > /etc/OpenCL/vendors/intel_expcpu.icd && \ - cd /opt/intel && \ - tar -zxvf /tmp/opencl-driver-intel/oneapi-tbb-2021.12.0-lin.tgz && \ - ln -s /opt/intel/oneapi-tbb-2021.12.0/lib/intel64/gcc4.8/libtbb.so /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 && \ - ln -s /opt/intel/oneapi-tbb-2021.12.0/lib/intel64/gcc4.8/libtbbmalloc.so /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 && \ - ln -s /opt/intel/oneapi-tbb-2021.12.0/lib/intel64/gcc4.8/libtbb.so.12 /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 && \ - ln -s /opt/intel/oneapi-tbb-2021.12.0/lib/intel64/gcc4.8/libtbbmalloc.so.2 /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 && \ - mkdir -p /etc/ld.so.conf.d && \ - echo /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 > /etc/ld.so.conf.d/libintelopenclexp.conf && \ - ldconfig -f /etc/ld.so.conf.d/libintelopenclexp.conf && \ - cd / && \ - rm -rf /tmp/opencl-driver-intel - -ENV NVIDIA_VISIBLE_DEVICES all -ENV NVIDIA_DRIVER_CAPABILITIES graphics,utility,compute -ENV QTWEBENGINE_DISABLE_SANDBOX 1 - -RUN dbus-uuidgen > /etc/machine-id - -ARG USER=batman -ARG USER_UID=1001 -RUN useradd -m -s /bin/bash -u $USER_UID $USER -RUN usermod -aG sudo $USER -RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers -USER $USER - -COPY --chown=$USER pyproject.toml uv.lock /tmp/ -COPY --chown=$USER tools/install_python_dependencies.sh /tmp/tools/ - -ENV VIRTUAL_ENV=/home/$USER/.venv -ENV PATH="$VIRTUAL_ENV/bin:$PATH" -RUN cd /tmp && \ - tools/install_python_dependencies.sh && \ - mkdir -p $VIRTUAL_ENV && \ - cp -r /tmp/.venv/* $VIRTUAL_ENV && \ - rm -rf /tmp/* && \ - rm -rf /home/$USER/.cache - -USER root -RUN sudo git config --global --add safe.directory /tmp/openpilot diff --git a/Jenkinsfile b/Jenkinsfile index 799b4fbbeb932e..a7f46ce17a0d2e 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -12,22 +12,26 @@ def retryWithDelay(int maxRetries, int delay, Closure body) { def device(String ip, String step_label, String cmd) { withCredentials([file(credentialsId: 'id_rsa', variable: 'key_file')]) { def ssh_cmd = """ -ssh -tt -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=2 -o BatchMode=yes -o StrictHostKeyChecking=no -i ${key_file} 'comma@${ip}' /usr/bin/bash <<'END' +ssh -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=2 -o BatchMode=yes -o StrictHostKeyChecking=no -i ${key_file} 'comma@${ip}' exec /usr/bin/bash <<'END' set -e +export TERM=xterm-256color + shopt -s huponexit # kill all child processes when the shell exits export CI=1 export PYTHONWARNINGS=error -export LOGPRINT=debug +#export LOGPRINT=debug # this has gotten too spammy... export TEST_DIR=${env.TEST_DIR} export SOURCE_DIR=${env.SOURCE_DIR} export GIT_BRANCH=${env.GIT_BRANCH} export GIT_COMMIT=${env.GIT_COMMIT} +export CI_ARTIFACTS_TOKEN=${env.CI_ARTIFACTS_TOKEN} +export GITHUB_COMMENTS_TOKEN=${env.GITHUB_COMMENTS_TOKEN} export AZURE_TOKEN='${env.AZURE_TOKEN}' # only use 1 thread for tici tests since most require HIL -export PYTEST_ADDOPTS="-n 0" +export PYTEST_ADDOPTS="-n0 -s" export GIT_SSH_COMMAND="ssh -i /data/gitkey" @@ -62,9 +66,7 @@ fi ln -snf ${env.TEST_DIR} /data/pythonpath cd ${env.TEST_DIR} || true -${cmd} -exit 0 - +time ${cmd} END""" sh script: ssh_cmd, label: step_label @@ -77,17 +79,38 @@ def deviceStage(String stageName, String deviceType, List extra_env, def steps) return } + if (isReplay()) { + error("REPLAYING TESTS IS NOT ALLOWED. FIX THEM INSTEAD.") + } + def extra = extra_env.collect { "export ${it}" }.join('\n'); def branch = env.BRANCH_NAME ?: 'master'; + def gitDiff = sh returnStdout: true, script: 'curl -s -H "Authorization: Bearer ${GITHUB_COMMENTS_TOKEN}" https://api.github.com/repos/commaai/openpilot/compare/master...${GIT_BRANCH} | jq .files[].filename || echo "/"', label: 'Getting changes' lock(resource: "", label: deviceType, inversePrecedence: true, variable: 'device_ip', quantity: 1, resourceSelectStrategy: 'random') { docker.image('ghcr.io/commaai/alpine-ssh').inside('--user=root') { timeout(time: 35, unit: 'MINUTES') { retry (3) { + def date = sh(script: 'date', returnStdout: true).trim(); + device(device_ip, "set time", "date -s '" + date + "'") device(device_ip, "git checkout", extra + "\n" + readFile("selfdrive/test/setup_device_ci.sh")) } steps.each { item -> - device(device_ip, item[0], item[1]) + def name = item[0] + def cmd = item[1] + + def args = item[2] + def diffPaths = args.diffPaths ?: [] + def cmdTimeout = args.timeout ?: 9999 + + if (branch != "master" && !branch.contains("__jenkins_loop_") && diffPaths && !hasPathChanged(gitDiff, diffPaths)) { + println "Skipping ${name}: no changes in ${diffPaths}." + return + } else { + timeout(time: cmdTimeout, unit: 'SECONDS') { + device(device_ip, name, cmd) + } + } } } } @@ -95,14 +118,43 @@ def deviceStage(String stageName, String deviceType, List extra_env, def steps) } } +def hasPathChanged(String gitDiff, List paths) { + for (path in paths) { + if (gitDiff.contains(path)) { + return true + } + } + return false +} + +def isReplay() { + def replayClass = "org.jenkinsci.plugins.workflow.cps.replay.ReplayCause" + return currentBuild.rawBuild.getCauses().any{ cause -> cause.toString().contains(replayClass) } +} + def setupCredentials() { withCredentials([ string(credentialsId: 'azure_token', variable: 'AZURE_TOKEN'), ]) { env.AZURE_TOKEN = "${AZURE_TOKEN}" } + + withCredentials([ + string(credentialsId: 'ci_artifacts_pat', variable: 'CI_ARTIFACTS_TOKEN'), + ]) { + env.CI_ARTIFACTS_TOKEN = "${CI_ARTIFACTS_TOKEN}" + } + + withCredentials([ + string(credentialsId: 'post_comments_github_pat', variable: 'GITHUB_COMMENTS_TOKEN'), + ]) { + env.GITHUB_COMMENTS_TOKEN = "${GITHUB_COMMENTS_TOKEN}" + } } +def step(String name, String cmd, Map args = [:]) { + return [name, cmd, args] +} node { env.CI = "1" @@ -114,11 +166,11 @@ node { env.GIT_BRANCH = checkout(scm).GIT_BRANCH env.GIT_COMMIT = checkout(scm).GIT_COMMIT - def excludeBranches = ['master-ci', 'devel', 'devel-staging', 'release3', 'release3-staging', - 'testing-closet*', 'hotfix-*'] + def excludeBranches = ['__nightly', 'devel', 'devel-staging', + 'release-tizi', 'release-tizi-staging', 'release-mici', 'release-mici-staging', 'testing-closet*', 'hotfix-*'] def excludeRegex = excludeBranches.join('|').replaceAll('\\*', '.*') - if (env.BRANCH_NAME != 'master') { + if (env.BRANCH_NAME != 'master' && !env.BRANCH_NAME.contains('__jenkins_loop_')) { properties([ disableConcurrentBuilds(abortPrevious: true) ]) @@ -126,83 +178,75 @@ node { try { if (env.BRANCH_NAME == 'devel-staging') { - deviceStage("build release3-staging", "tici-needs-can", [], [ - ["build release3-staging", "RELEASE_BRANCH=release3-staging $SOURCE_DIR/release/build_release.sh"], + deviceStage("build release-tizi-staging", "tizi-needs-can", [], [ + step("build release-tizi-staging", "RELEASE_BRANCH=release-tizi-staging,release-mici-staging $SOURCE_DIR/release/build_release.sh"), ]) } - if (env.BRANCH_NAME == 'master-ci') { - deviceStage("build nightly", "tici-needs-can", [], [ - ["build nightly", "RELEASE_BRANCH=nightly $SOURCE_DIR/release/build_release.sh"], - ]) + if (env.BRANCH_NAME == '__nightly') { + parallel ( + 'nightly': { + deviceStage("build nightly", "tizi-needs-can", [], [ + step("build nightly", "RELEASE_BRANCH=nightly $SOURCE_DIR/release/build_release.sh"), + ]) + }, + 'nightly-dev': { + deviceStage("build nightly-dev", "tizi-needs-can", [], [ + step("build nightly-dev", "PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-dev $SOURCE_DIR/release/build_release.sh"), + ]) + }, + ) } if (!env.BRANCH_NAME.matches(excludeRegex)) { parallel ( - // tici tests 'onroad tests': { - deviceStage("onroad", "tici-needs-can", [], [ - // TODO: ideally, this test runs in master-ci, but it takes 5+m to build it - //["build master-ci", "cd $SOURCE_DIR/release && TARGET_DIR=$TEST_DIR $SOURCE_DIR/scripts/retry.sh ./build_devel.sh"], - ["build openpilot", "cd system/manager && ./build.py"], - ["check dirty", "release/check-dirty.sh"], - ["onroad tests", "pytest selfdrive/test/test_onroad.py -s"], - ["time to onroad", "pytest selfdrive/test/test_time_to_onroad.py"], + deviceStage("onroad", "tizi-needs-can", ["UNSAFE=1"], [ + step("build openpilot", "cd system/manager && ./build.py"), + step("check dirty", "release/check-dirty.sh"), + step("onroad tests", "pytest selfdrive/test/test_onroad.py -s", [timeout: 60]), ]) }, 'HW + Unit Tests': { - deviceStage("tici-hardware", "tici-common", ["UNSAFE=1"], [ - ["build", "cd system/manager && ./build.py"], - ["test pandad", "pytest selfdrive/pandad/tests/test_pandad.py"], - ["test power draw", "pytest -s system/hardware/tici/tests/test_power_draw.py"], - ["test encoder", "LD_LIBRARY_PATH=/usr/local/lib pytest system/loggerd/tests/test_encoder.py"], - ["test pigeond", "pytest system/ubloxd/tests/test_pigeond.py"], - ["test manager", "pytest system/manager/test/test_manager.py"], + deviceStage("tizi-hardware", "tizi-common", ["UNSAFE=1"], [ + step("build", "cd system/manager && ./build.py"), + step("test power draw", "pytest -s system/hardware/tici/tests/test_power_draw.py"), + step("test encoder", "LD_LIBRARY_PATH=/usr/local/lib pytest system/loggerd/tests/test_encoder.py", [diffPaths: ["system/loggerd/"]]), + step("test manager", "pytest system/manager/test/test_manager.py"), ]) }, - 'loopback': { - deviceStage("loopback", "tici-loopback", ["UNSAFE=1"], [ - ["build openpilot", "cd system/manager && ./build.py"], - ["test pandad loopback", "pytest selfdrive/pandad/tests/test_pandad_loopback.py"], + 'camerad OX03C10': { + deviceStage("OX03C10", "tizi-ox03c10", ["UNSAFE=1"], [ + step("build", "cd system/manager && ./build.py"), + step("test pandad", "pytest selfdrive/pandad/tests/test_pandad.py"), + step("test camerad", "pytest system/camerad/test/test_camerad.py", [timeout: 90]), ]) }, - 'camerad': { - deviceStage("AR0231", "tici-ar0231", ["UNSAFE=1"], [ - ["build", "cd system/manager && ./build.py"], - ["test camerad", "pytest system/camerad/test/test_camerad.py"], - ["test exposure", "pytest system/camerad/test/test_exposure.py"], - ]) - deviceStage("OX03C10", "tici-ox03c10", ["UNSAFE=1"], [ - ["build", "cd system/manager && ./build.py"], - ["test camerad", "pytest system/camerad/test/test_camerad.py"], - ["test exposure", "pytest system/camerad/test/test_exposure.py"], + 'camerad OS04C10': { + deviceStage("OS04C10", "tici-os04c10", ["UNSAFE=1"], [ + step("build", "cd system/manager && ./build.py"), + step("test pandad", "pytest selfdrive/pandad/tests/test_pandad.py"), + step("test camerad", "pytest system/camerad/test/test_camerad.py", [timeout: 90]), ]) }, 'sensord': { - deviceStage("LSM + MMC", "tici-lsmc", ["UNSAFE=1"], [ - ["build", "cd system/manager && ./build.py"], - ["test sensord", "pytest system/sensord/tests/test_sensord.py"], - ]) - deviceStage("BMX + LSM", "tici-bmx-lsm", ["UNSAFE=1"], [ - ["build", "cd system/manager && ./build.py"], - ["test sensord", "pytest system/sensord/tests/test_sensord.py"], + deviceStage("LSM + MMC", "tizi-lsmc", ["UNSAFE=1"], [ + step("build", "cd system/manager && ./build.py"), + step("test sensord", "pytest system/sensord/tests/test_sensord.py"), ]) }, 'replay': { - deviceStage("model-replay", "tici-replay", ["UNSAFE=1"], [ - ["build", "cd system/manager && ./build.py"], - ["model replay", "selfdrive/test/process_replay/model_replay.py"], + deviceStage("model-replay", "tizi-replay", ["UNSAFE=1"], [ + step("build", "cd system/manager && ./build.py", [diffPaths: ["selfdrive/modeld/", "tinygrad_repo", "selfdrive/test/process_replay/model_replay.py"]]), + step("model replay", "selfdrive/test/process_replay/model_replay.py", [diffPaths: ["selfdrive/modeld/", "tinygrad_repo", "selfdrive/test/process_replay/model_replay.py"]]), ]) }, 'tizi': { deviceStage("tizi", "tizi", ["UNSAFE=1"], [ - ["build openpilot", "cd system/manager && ./build.py"], - ["test pandad loopback", "SINGLE_PANDA=1 pytest selfdrive/pandad/tests/test_pandad_loopback.py"], - ["test pandad spi", "pytest selfdrive/pandad/tests/test_pandad_spi.py"], - ["test pandad", "pytest selfdrive/pandad/tests/test_pandad.py"], - ["test amp", "pytest system/hardware/tici/tests/test_amplifier.py"], - ["test hw", "pytest system/hardware/tici/tests/test_hardware.py"], - ["test qcomgpsd", "pytest system/qcomgpsd/tests/test_qcomgpsd.py"], + step("build openpilot", "cd system/manager && ./build.py"), + step("test pandad loopback", "pytest selfdrive/pandad/tests/test_pandad_loopback.py"), + step("test pandad spi", "pytest selfdrive/pandad/tests/test_pandad_spi.py"), + step("test amp", "pytest system/hardware/tici/tests/test_amplifier.py"), ]) }, diff --git a/README.md b/README.md index 38d32ec3b69761..dc355d49863c9e 100644 --- a/README.md +++ b/README.md @@ -1,98 +1,108 @@ -
+
-

openpilot

+

NotAutopilot

- openpilot is an operating system for robotics. + Self driving for pre-Autopilot Tesla Model S.
- Currently, it upgrades the driver assistance system in 275+ supported cars. + Lane keeping, adaptive cruise, and driver monitoring for the 25,000+ pre-AP vehicles Tesla left behind.

- Docs + Website · - Roadmap + Wiki · - Contribute + Discord · - Community - · - Try it on a comma 3X + How It Works

-Quick start: `bash <(curl -fsSL openpilot.comma.ai)` +Install on your comma 3X: `https://installer.comma.ai/NotAutopilot/openpilot/nap-release` -![openpilot tests](https://github.com/commaai/openpilot/actions/workflows/selfdrive_tests.yaml/badge.svg) -[![codecov](https://codecov.io/gh/commaai/openpilot/branch/master/graph/badge.svg)](https://codecov.io/gh/commaai/openpilot) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) -[![X Follow](https://img.shields.io/twitter/follow/comma_ai)](https://x.com/comma_ai) -[![Discord](https://img.shields.io/discord/469524606043160576)](https://discord.comma.ai)
- - - - - - -
+--- + +## What is NotAutopilot? + +NotAutopilot (NAP) is a fork of [comma.ai's openpilot](https://github.com/commaai/openpilot) that brings driver assistance to 2012–2014 pre-Autopilot Tesla Model S vehicles. These cars shipped without forward-facing cameras, radar, or any driver assistance — NAP adds all of it. + +Built on the foundation of the [Tinkla project](https://tinkla.us/t/index) (which first proved openpilot could work on pre-AP Teslas) and [xnor-tech's openpilot](https://github.com/xnor-tech/openpilot) (which added working AP1 Model S support), NAP extends support to pre-Autopilot vehicles with a standalone safety model, Bosch radar integration, and Comma Pedal longitudinal control. + +### Features + +- **Lateral control** — Steering via EPAS with full panda safety validation +- **Longitudinal control** — Comma Pedal interceptor with zero-torque learning, smooth engagement, and three driving profiles (Aggressive, Standard, Chill) +- **Radar** — Bosch radar support with GTW emulation for lead car detection and adaptive following +- **Driver monitoring** — Stock openpilot driver monitoring camera +- **On-device settings** — Full NAP settings panel for pedal calibration, radar configuration, EPAS firmware management, and tuning + +### Hardware Required + +1. **2012–2014 Tesla Model S** (pre-Autopilot, no AP ECU) +2. **[comma 3X](https://comma.ai/shop)** (or comma 3) +3. **[Tesla Model S HW1 harness](https://comma.ai/shop/car-harness)** +4. **[Comma Pedal](https://github.com/commaai/openpilot/wiki/Comma-Pedal)** — for longitudinal (throttle/regen) control +5. **Bosch radar** *(optional)* — for adaptive cruise with lead car following + +## Installation + +On your comma device, enter this URL during setup or in Software settings under Custom Fork: -To start using openpilot in a car ------- +``` +https://installer.comma.ai/NotAutopilot/openpilot/nap-release +``` -To use openpilot in a car, you need four things: -1. **Supported Device:** a comma 3/3X, available at [comma.ai/shop](https://comma.ai/shop/comma-3x). -2. **Software:** The setup procedure for the comma 3/3X allows users to enter a URL for custom software. Use the URL `openpilot.comma.ai` to install the release version. -3. **Supported Car:** Ensure that you have one of [the 275+ supported cars](docs/CARS.md). -4. **Car Harness:** You will also need a [car harness](https://comma.ai/shop/car-harness) to connect your comma 3/3X to your car. +## Branches -We have detailed instructions for [how to install the harness and device in a car](https://comma.ai/setup). Note that it's possible to run openpilot on [other hardware](https://blog.comma.ai/self-driving-car-for-free/), although it's not plug-and-play. +| Branch | Install URL | Description | +|--------|------------|-------------| +| `nap-release` | `NotAutopilot/openpilot/nap-release` | **Recommended.** Stable release for daily driving. | +| `nap-staging` | — | Pre-release testing. Coming soon. | +| `nap-alpha` | `NotAutopilot/openpilot/nap-alpha` | Alpha builds for testers. May have rough edges. | +| `nap-dev` | — | Active development. Expect things to break. | -To start developing openpilot ------- +## Lineage -openpilot is developed by [comma](https://comma.ai/) and by users like you. We welcome both pull requests and issues on [GitHub](http://github.com/commaai/openpilot). +``` +comma.ai/openpilot + └── sunnypilot/sunnypilot + └── xnor-tech/openpilot (AP1 Model S support) + └── NotAutopilot/openpilot (Pre-AP Model S support) -* Join the [community Discord](https://discord.comma.ai) -* Check out [the contributing docs](docs/CONTRIBUTING.md) -* Check out the [openpilot tools](tools/) -* Read about the [development workflow](docs/WORKFLOW.md) -* Code documentation lives at https://docs.comma.ai -* Information about running openpilot lives on the [community wiki](https://github.com/commaai/openpilot/wiki) +boggyver/openpilot (Tinkla — the original Pre-AP Tesla fork) + └── inspiration, radar emulation, pedal architecture → NotAutopilot +``` -Want to get paid to work on openpilot? [comma is hiring](https://comma.ai/jobs#open-positions) and offers lots of [bounties](https://comma.ai/bounties) for external contributors. +## Acknowledgments -Safety and Testing ----- +NotAutopilot wouldn't exist without: -* openpilot observes [ISO26262](https://en.wikipedia.org/wiki/ISO_26262) guidelines, see [SAFETY.md](docs/SAFETY.md) for more details. -* openpilot has software-in-the-loop [tests](.github/workflows/selfdrive_tests.yaml) that run on every commit. -* The code enforcing the safety model lives in panda and is written in C, see [code rigor](https://github.com/commaai/panda#code-rigor) for more details. -* panda has software-in-the-loop [safety tests](https://github.com/commaai/panda/tree/master/tests/safety). -* Internally, we have a hardware-in-the-loop Jenkins test suite that builds and unit tests the various processes. -* panda has additional hardware-in-the-loop [tests](https://github.com/commaai/panda/blob/master/Jenkinsfile). -* We run the latest openpilot in a testing closet containing 10 comma devices continuously replaying routes. +- **[Boggyver](https://github.com/boggyver) and the [Tinkla Project](https://tinkla.us/t/index)** — First proved openpilot could work on pre-AP Teslas. The foundation everything is built on. +- **[Lukas Loetkolben](https://github.com/lukasloetkolben)** — Clean isolated safety model approach that inspired the SAFETY_TESLA_PREAP refactor. +- **[xnor-tech](https://github.com/xnor-tech)** — Working AP1/HW1-4 Tesla support in openpilot. +- **[comma.ai](https://comma.ai)** — openpilot itself. The hard parts were already solved. +- **Johnmr1, SeriouslySerious, Pod042, 1FrostlySlime** — Early testers who drove broken builds so others wouldn't have to. -Licensing ------- +## Contributing -openpilot is released under the MIT license. Some parts of the software are released under other licenses as specified. +Pull requests are welcome against the `nap-dev` branch. See [`docs-nap/`](docs-nap/) for branch structure, build instructions, pre-push checklist, safety invariants, and the engagement flow. -Any user of this software shall indemnify and hold harmless Comma.ai, Inc. and its directors, officers, employees, agents, stockholders, affiliates, subcontractors and customers from and against all allegations, claims, actions, suits, demands, damages, liabilities, obligations, losses, settlements, judgments, costs and expenses (including without limitation attorneys’ fees and costs) which arise out of, relate to or result from any use of this software by user. +## User Data -**THIS IS ALPHA QUALITY SOFTWARE FOR RESEARCH PURPOSES ONLY. THIS IS NOT A PRODUCT. -YOU ARE RESPONSIBLE FOR COMPLYING WITH LOCAL LAWS AND REGULATIONS. -NO WARRANTY EXPRESSED OR IMPLIED.** +By default, openpilot uploads driving data to comma servers. You can access your data through [comma connect](https://connect.comma.ai/). Data collection can be disabled in settings. -User Data and comma Account ------- +## Licensing -By default, openpilot uploads the driving data to our servers. You can also access your data through [comma connect](https://connect.comma.ai/). We use your data to train better models and improve openpilot for everyone. +NotAutopilot is released under the [MIT License](LICENSE). This repository includes original work as well as code derived from [openpilot by comma.ai](https://github.com/commaai/openpilot) and the [Tinkla project by boggyver](https://github.com/boggyver/openpilot), both released under the MIT license. -openpilot is open source software: the user is free to disable data collection if they wish to do so. +> **THIS IS ALPHA QUALITY SOFTWARE FOR RESEARCH PURPOSES ONLY. THIS IS NOT A PRODUCT. +> YOU ARE RESPONSIBLE FOR COMPLYING WITH LOCAL LAWS AND REGULATIONS. +> NO WARRANTY EXPRESSED OR IMPLIED.** -openpilot logs the road-facing cameras, CAN, GPS, IMU, magnetometer, thermal sensors, crashes, and operating system logs. -The driver-facing camera is only logged if you explicitly opt-in in settings. The microphone is not recorded. +Any user of this software shall indemnify and hold harmless Comma.ai, Inc. and its directors, officers, employees, agents, stockholders, affiliates, subcontractors and customers from and against all allegations, claims, actions, suits, demands, damages, liabilities, obligations, losses, settlements, judgments, costs and expenses (including without limitation attorneys' fees and costs) which arise out of, relate to or result from any use of this software by user. -By using openpilot, you agree to [our Privacy Policy](https://comma.ai/privacy). You understand that use of this software or its related services will generate certain types of user data, which may be logged and stored at the sole discretion of comma. By accepting this agreement, you grant an irrevocable, perpetual, worldwide right to comma for the use of this data. +Any user of this software shall also indemnify and hold harmless the NotAutopilot project, its contributors, maintainers, and affiliates from and against all allegations, claims, actions, suits, demands, damages, liabilities, obligations, losses, settlements, judgments, costs and expenses (including without limitation attorneys' fees and costs) which arise out of, relate to or result from any use of this software by user. diff --git a/RELEASES.md b/RELEASES.md index 57f69791170238..92bdcda5dc0f10 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,6 +1,415 @@ -Version 0.9.8 (2024-XX-XX) +NAP sight-distance cap, LOG ONLY (2026-10-11) ======================== +* Pre-AP shadow (`NAPSightCap`, default 1 = shadow; 0 off). Nothing reads it: speed, MAX, curve follow, CurveMaxHold, the #222 cases and the -0.22 EV settle are unchanged. +* Sight distance = where the model path's lateral std reaches 2 m (`model_sight`, shared with low-visibility steering, whose path std read now lives there unchanged). +* Would fire when sight drops below half its 2-12 s median for 0.5 s at 25-55 mph, with rising path curvature or a map roundabout ahead, unless the model was already red with a short path. Vehicles never count as sight loss: any lead (moving or stopped), adjacent car or parked car within 150 m suppresses it and the reason is logged. Steps aside while the roundabout funnel is live. Glare-only low-vis never feeds it. +* Logs `sightcap {json}` (errorLogMessage, no new capnp fields): sight, baseline, cap speed (slow to a 30 m bend at 15 mph inside the sight at 1.5 m/s², 2 m/s³ jerk), would-be accel, min with curve follow, leads, pitch, crest, night/sun, lane-line probs, blinker, confidence, low-vis. + +NAP gap lock (2026-10-05) +======================== +* Pre-AP, default Off (`NAPGapLock`). Hold the engage stalk toward you for 2 seconds to keep the current radar gap (8–80 m) instead of the time gap. Long can be on, paused, or not yet taken; a finished hold resumes it. Same follow law, a custom distance. The 3X shows the lock while it is on. A tip, cancel, brake, or One-Pedal pause returns to Follow Distance. Another 2 second hold stores a new distance. No panda flash. + +NAP release firm lead brake when the gap opens or the lead leaves the lane (2026-09-23) +======================== +* Pre-AP: a slightly negative lead acceleration no longer holds a full brake when the car ahead is pulling away with gap left (Scallywag 09:57 and 10:05). That firm brake now needs a real close — still coming together, a closing residual, or already inside the follow gap. After a short run of the gap opening, the command publishes the mild ease (−0.22), not a zero coast and not the full brake. A lead that slides out of the lane (about 2.5 m off the path) with gap still left does the same (08:57:50–52). An on-path close, including a hard brake for a slowing lead, stays firm. A broken construction path is pickier about starting a new lead that is already a couple of meters to the side. No panda flash. + +NAP City/Hwy follow follows MAX, near-FD coast cliffs floor (2026-09-23) +======================== +* City vs highway Follow Distance now follows **MAX**, for both the stalk bump and the live gap. **City** when MAX is under 50 mph. **Highway** when MAX is 50 or higher (exactly 50 is highway), including while the car is still coming up to that set speed and while it slows under a highway MAX. Traveled speed is used only when MAX is unset. A first-detent bump steps that band. A full press still nudges MAX. Slowing from highway speed under MAX 75 no longer opens the larger city gap. +* Near Follow Distance, a one-frame hard brake while the plan is still coasting (gap only a few meters long of the set follow, closing under about 1 m/s, lead not braking) is held to the mild ease instead of a full dump. A real brake for a slowing lead ahead — closing up, lead braking, or the firm-match path — stays firm. Near-bumper, forward collision warning, and a stop request stay firm. No panda flash. + +NAP stalk tip writes the matching City or Highway Follow Distance (2026-09-23) +======================== +* Pre-AP stalk **bump** (first detent, 1 mph) steps Follow Distance 1–7 on the matching band. **Highway** when ego is above 50 mph, or whenever MAX is above 50 (a bump while still accelerating up to a highway set speed stays on Highway, even under 50). **City** only when ego is at or under 50 mph and MAX is also at or under 50. HUD **Follow Distance: N** shows that band. Full press (2nd detent / 5 mph) still nudges MAX. Live follow blend (hysteresis around 50, highway follow from about 30 mph with a lead and MAX above 50) is unchanged. No panda flash. + +NAP follow-smooth mid-gap rematch (2026-09-20) +======================== +* Pre-AP comfort on a held radar lead: mid-gap Accel rematch no longer pulses while still slowly closing (~0.8–2.0 m/s, slack 12–50 m) unless a same-speed / opening catch-up is already latched (100 m start / too-close recovery still Accel through that band; latch also clears settle so a matched 0–25 m hold cannot freeze rematch while the gap is wrong). A *settled* follow that opens or hunts is not catch-up. Ceiling is a trickle (~0.10), not Accel 1–10. Slack > 50 still Accel. After acquire, small ±a chatter slews both ways so +0.25 ↔ −0.02 cannot flip gas↔regen — catch-up / too-close recovery skips that slew. When planner aTarget is ~0, VirtualDAS cannot dump firm regen (ef 10:18:42: plant −1.23 then rematch +0.40) — effort floor is MILD −0.22. Grade / pitch hold, rapid / near-bumper / FCW / #222 residual-close / planner ≤ −0.5 stay full −a/+a. No panda flash. + +NAP skip mild floor on closing / near-gap braking lead (2026-09-20) +======================== +* Pre-AP: `#216` kept the MILD −0.22 floor until confirmed rapid ≥ 6 / near-bumper / FCW, so a held lead that hard-braked (closing 1.8→4.4, aLead ~−1, dRel 38→25) never escaped slight-lift. Soft-limit now skips when residual close (worsened beyond ego a, including a planner-frame Δv that is smaller than the 0.15 rise gate) or measured aLead shows brake on an owned / path-synced lead. That also unlocks match-aLead (not `k·v_rel` dump). Closing ≥ 1.5 still reacts, including a cut-in. Matched / slow-close and large-slack e4 stay MILD / #218 glide. Map decel above MAX still mins in on a same-speed lead. Firm 0.55 / full hard-brake still wait on the rapid confirm. Rapid gate stays 6. No panda flash. + +NAP roundabout detect + speed ease + outer bias (2026-09-20) +======================== +* Map `junction=roundabout` (or a compact closed circulating way already in the OSM pack) ~200 m out — not a big steer, and not every sharp town corner / signalized cross. Kinematic decel toward **15–20 mph** (OSM ring maxspeed when present, often 20) so 40–45 mph plans **a ≤ −1.0** until near ring speed; `aTarget` stays ≤ 0 in the funnel (no +a after a lead clears). Long enable inside the funnel applies full ease immediately. ~3.2 m outer path bias on entry + circulating (right in RHT / US) to counter a ~3 m inside cut. Yield-before-merge / continue-circulate / UI chip are later. No panda flash. + +NAP matched-speed glide + earlier settle (2026-09-19) +======================== +* After #214 acquire + #216 slight-lift + #219 MAX ceiling: when matched or slightly slower near Follow Distance, leftover mild −a glides to 0; rematch trickle still finishes / holds grade under MAX. Last-meter closing, braking lead, or already inside FD is not a glide. +3 m kinematic gap bias. Inside FD still closing slowly commands the mild floor. Rapid / near-bumper / FCW keep full −a. No panda flash. + +NAP MAX is a hard ceiling on lead rematch (2026-09-19) +======================== +* Pre-AP: if the lead is faster than MAX/set, **hold ≤ MAX and let the gap open**. Lead rematch / remaining-close no longer commands Accel-1 (+0.36) to keep up past MAX (ea 11:46: 62.2 on a 60). At/above MAX, lead-close `a_env` is 0, not Accel peak. Catch-up under MAX, #214 acquire slew, #216 slight-lift floor, and emergency −a kept. No panda flash. + +NAP EV slight-lift comfort path (2026-09-19) +======================== +* Pre-AP Model S EV: non-emergency approach/follow is **slight lift only** (MILD −0.22). Full throttle lift / deep −a is reserved for rapid close / near-bumper / FCW. Closing ≳ 1.5 and near-gap aLead no longer skip the floor or acquire slew (that still punched −0.996 at 80–130 m). #214 acquire slew kept. No panda flash. + +NAP lead acquire slew + small MPC bite soften (2026-09-19) +======================== +* First lead latch no longer punches regen then rematch +a (e4 09:53:19: aTarget −0.46 → +0.05 in ~0.5 s at 118 m). Acquire window slews both ways. Large-slack small MPC adjustments (e4 −2.33 at ~40 m / 9.5 m/s) stay at the mild floor. Rapid close / near-bumper / FCW keep full −a. No panda flash. + +NAP town look-ahead for reverse-digitized / short first-way 30s (2026-09-19) +======================== +* Map Lookahead Early: `nextSpeedLimit` now arms for along-route town drops when OSM digitized the street opposite travel, and when the first 30 piece is only ~250 ft but the contiguous same-limit run is the real town. Side-road / stub blips under ~250 ft still ignored. No panda flash. + +NAP port of #192 flash tip onto nap-dev (2026-09-18) +======================== +* Tonight ship to **nap-dev** of the stacked flash tip through **#192** (`c3570c957`). Same Pre-AP longitudinal behavior as `cursor/alead-opening-gate-bc6e`. No panda flash. Hypermile / Hill Climb / map-climb-owns-follow kept. +* **#187** Accel-owns-catch-up + MPC mild floor + city/hwy Follow Distance. +* **#188** skip MPC −MILD floor when closing / lead braking; far mild close must not steal cruise +a. +* **#189** analog `DI_pedalPos` as `gasDEPRECATED`; SET-while-gas arms long. +* **#190** hard-block rematch / cruise +a while closing on a live or held lead; farther radar lead ID. +* **#191** settle rematch deadband + Accel-proportional gap hunt; hwy FD from ~30 mph when MAX > 50. +* **#192** do not match aLeadK on far opening leads (slack ≳ 20 m / gap opening). + +NAP One-Pedal SET-while-gas lift keeps long (2026-09-18) +======================== +* **One-Pedal Long On:** double-SET (or one SET) **while the foot is already on gas**, then lift, must **keep `enableLongControl`**, hold MAX, and **ACQUIRE** the interceptor on that falling edge — not dive into stock Tesla one-pedal regen. #185's pause-gate DI **> 1** extra kick treated lift-through DI 1–2 as a from-rest tip-in (phantom rising edge after stock `gasPressed` fell), dropped long, zeroed cruise speed, and left `aTarget` climbing while `aEgo` was stock regen (~−1.5). Log: `1c95345a3286a5db|000000dc--9b28358130` 13:16:14 (SET→lift **197 ms**), 13:15:30 (7.5 s regen hole), 13:17:19 success when DI dropped through 1 in one sample. **Now:** orig kick takes `interceptor_di`; `_one_pedal_armed_with_gas` holds lift-to-start until DI is fully off; overlay skips extra kick on falling edge / armed. Light tip-in after a real rest still pauses. Toggle default **Off**. + +NAP Accel-owns-catch-up + city/hwy Follow Distance (2026-09-17) +======================== +* **Accel 1–10 owns all +a**, including lead gap-close: same Mannerisms gradient as open-road / MAX climb (Accel 1 baby-steps the last ~5 mph; Accel 7–10 stay brisk). No separate 0.20/0.30/0.50 catch-up curve. Close-cap covers the Bosch window (**~200 m**) so a 160–180 m lead does not punch cruise 1.6. Brief hold on `leadOne` flicker. **Hard/rapid regen** (0.55) waits for **4 consecutive** in-window samples (~0.20 s); mild ease is immediate. **Non-rapid MPC −a is floored at mild (~0.22)** so min(MPC, overlay) cannot dump ~−2.5; FCW / rapid / a real stop still own danger. +* **City vs highway Follow Distance** on Driving Mannerisms (TICI + mici): City (<~50 mph) and Highway (>~50 mph), 1–7. Fluid blend with hysteresis around 50 — not a step. Dropping below 50 while following, ego is slightly slower than the lead so the gap opens to city FD, then holds. Rising above 50, t_follow creeps toward hwy FD. Only with a valid lead + long engaged. Migrates from single `NAPFollowDistance`. **Not Hypermile** — available whenever Mannerisms FD is used. Stalk tip steps the active band. Hypermile / Hill Climb / map-climb-owns-follow kept. No panda flash. + +NAP follow soften + One-Pedal pause DI>1 (2026-09-17) +======================== +* Port of the nap-release **#181 stack** plus pause sensitivity: **mild / normal closes stay light** (~0.22 m/s²) instead of the TTC-floor 0.26 / short-TTC 0.55 path. **Rapid / dumping** only (`v_rel` ≥ ~13 mph) still uses 0.55. Overlay **slew both ways**; near-gap opening rematch **+a trickles** (0.08 / 0.12). Large-gap lead-close cap stays **0.20 / 0.30 / 0.50**. **One-Pedal SET resume** (pause latch is one SET, including SET-while-gas; opendbc skip_resume). Pause gate interceptor DI **> 1** (stock gasPressed stays **> 2**). Hypermile / Hill Climb / map-climb-owns-follow unchanged. No panda flash. + +NAP revert tip-brake soft-glide (2026-09-15) +======================== +* **#157 reverted:** Pre-AP silent long pause brake cancel is **firm/stock again** (#156-era RELEASE). When `real_brake_pressed` drops software long, interceptor **RELEASEs immediately** to Tesla regen — no tip/hold classifier, no −0.30 start, no ~2.5 s comfort-shaped glide. On-car: the soft cancel felt worse than stock regen. **Kept:** One-Pedal Long (#170–#172) accelerator pause + SET latch, #152 A+B and #153 A3 gas-lift climb. Full cancel / FCW / AEB / hard lead unchanged. No `GAS_COMMAND` rewrite, no PostEngageCoast / climb latch / pedal-hold, no locationd or safety change. + +NAP One-Pedal Long pause holds through lift (2026-09-15) +======================== +* Follow-up to #171 after on-car: **One-Pedal Long On + long already holding + gas takeover** still **pauses** long (lat stays). **Lift / coast / regen must not resume** — Justin took over at ~60, decelerated to ~50, then long climbed back (A+B / A3). #171 only latched on a single interceptor `gasPressed` rising edge; stock `gasPressedOverride` ending still makes `CC.longActive` true, and a missed/soft edge left `enableLongControl` true so lift ACQUIREd. **Now:** sticky `_one_pedal_had_long_at_rest` + controller `_saw_long_without_gas` latch any gas after long was holding with the foot off (not only that one edge). Latch holds `enableLongControl` false and blocks interceptor ACQUIRE until a **single SET**. **Keep:** foot already on the throttle + SET still arms long; lift starts A+B/A3. Brake pause resume stays as today (firm/stock RELEASE). Toggle default **Off**. **nap-dev only — no nap-release twin until Justin signs off.** + +NAP One-Pedal Long SET-to-resume latch (2026-09-15) +======================== +* Follow-up to #170 after on-car: **One-Pedal Long On + long already active + gas from rest** still **pauses** long (lat stays, not `USER_DISABLE`). That pause is now a **held latch** (`_one_pedal_pause_latched`) until a **single SET**. **Lift alone must not resume** long / re-ACQUIRE — stock `gasPressedOverride` ending makes `CC.longActive` true again; the latch blocks interceptor ACQUIRE and re-drops long if it comes back without SET. **Keep:** foot already on the throttle + one SET (or two) still arms long; lift starts A+B/A3. Brake pause resume stays as today (this latch is gas-pause only). Toggle default **Off**. **nap-dev only — no nap-release twin until Justin signs off.** + +NAP One-Pedal Long (2026-09-15) +======================== +* Settings → NAP → **Driving Mannerisms** → **One-Pedal Long** (`NAPOnePedalLong`, default **Off**). Pedal-interceptor Pre-AP only. **On + OP long already active + accelerator rising from rest** (interceptor `gasPressed`, not `DI_pedalPos`): **pauses longitudinal the same way brake does today** — long lets go, lateral stays, sticky MAX, one SET resumes, no `pedalCruiseDisabled` chime. Not `USER_DISABLE` / full session cancel / take-control (`EventName.pedalPressed` is suppressed while this toggle is On, even if DisengageOnAccelerator is On). **SET while the foot is already on the accelerator** (one-stalk or two-stalk) still **arms long**; lift starts the stock A+B grace expire + aEgo seed / A3 climb — One-Pedal Long does not pause or block that handoff. After a from-rest pause the interceptor **RELEASEs** (`ENABLE=0`, command=0) and **stays RELEASED on lift** so Tesla physical pedal / stock lift-regen is the one-pedal path (same envelope as `REGEN_MAX` ≈ −1.5 m/s²). Resume-long after pause matches brake pause (sticky MAX + one SET). Limits: do **not** re-ACQUIRE on lift after a from-rest pause (that is the ENABLE 0↔1 chatter from earlier `GAS_COMMAND` overlays), do **not** rewrite driver pedal DI while ENABLE=1, cannot invent friction beyond interceptor regen. **Off** = stock: gas overrides then A+B/A3 resume climb. Standstill wait-for-gas resume, A+B/A3 engage-while-gas, firm brake cancel, FCW/AEB / #163–#167 / #169 unchanged. **nap-dev only — no nap-release twin until Justin signs off.** + +NAP lead-approach earlier normal-close ease (2026-09-15) +======================== +* Pre-AP lead-approach **normal closes** ease **earlier and a bit stronger**, so Justin does not ride up then take a late 0.55 / MPC bite. Comfort peak stays **0.55** (Early map). FCW / AEB / MPC hard brake untouched. Follow Distance stalk **1–7** still owns the settle gap (maneuver Follow 1 stays **23.5 m ± 0.5**). Tip-brake glide (#157) and #163/#164/#165/#167 are not this path. +* **Why it was soft:** `a = −v_rel² / (2 · slack)` at far slack is a nibble (|a| ~0.06–0.13). Catch-up +a ignored that nibble, so ego kept pulling in until the 0.55 peak. **Tune (normal close):** when time-to-follow-gap (`slack / v_rel`) is **≤ 20 s** *and* kinematic |a| is already past **0.15**, command at least **0.26** m/s² (or `v_rel / 12` if smaller) so regen is felt. Do **not** boost a far/catch-up nibble — that parked Follow 1 ~0.6 m long of the selected gap. Bleed tapers as `v_rel` drops. Far slack (TTC **> 20 s**, or |a_kin| still a nibble) stays the light kinematic, not a hard early brake. +* **Rapid / dumping:** `v_rel ≥ 6.0` m/s (~13 mph) or TTC **≤ 8 s** keeps kinematics up to the **0.55** peak (already above the light floor). Clear-close skip is **2.0** m/s (~4.5 mph, was 2.5) so a 5 mph close starts at first reliable radar. Need-path head-start **28 s** (was 24). A nibble must not steal Accel-1 rematch / Follow 1–7 catch-up. Enter/exit **0.55 / 0.20**, slew **0.05**/frame, Bosch **200 m** ceiling unchanged. **nap-dev only — no nap-release twin until Justin signs off.** + +NAP no lat re-engage below 10 mph (2026-09-15) +======================== +* Soft-lat **On**: the driver-turn blinker **no re-enable** gate (`lat_reenable_inhibited`) also applies whenever **v_ego < 10 mph** (`LAT_REENABLE_MIN_V_EGO_MPH`, strictly below, mph→m/s). Keep control if we still have it. Already yielded / blending / lat-down stay yielded — do not finish a take-back blend. After speed crosses 10 mph, resume is yield + the normal **0.15 s** hands-off confirm + **1 s** blend. Blinker-on still blocks take-back at any speed. Above 10 mph with the blinker off, prior resume is unchanged. Soft-lat **Off**, ALC tip/hold, long / follow, FCW / AEB, and #163/#164/#165 are not this path. **nap-dev only — no nap-release twin until Justin signs off (batching a release group).** + +NAP DM look-away pause below 2 mph (2026-09-15) +======================== +* Looking-away / distraction / eyes-off-road DM alerts do **not** fire below **2 mph** (`DM_LOOKAWAY_GATE_MPH`), even if **Simulate Look** and/or **False Alert Ignore** are On. Same stock standstill pause (hold before the green prompt; recover if already orange), plus creeping at a light — Tesla `CS.standstill` is only true when fully stopped, so 1 mph still nagged. Toggles stay as set; this is a speed gate, not Sim Look / FAI Off. Above 2 mph, Sim Look / FAI / stock 3 / 5 / 11 s are unchanged. FCW / AEB / hard cancels (hands-on ≥ 2 / stalk / door / reverse) unchanged. **nap-dev only — no nap-release twin until Justin signs off after a road test.** + +NAP tip-brake soft-glide (2026-09-14) +======================== +* **Tip-brake comfort ramp (reverted):** Pre-AP silent long pause classified digital Applied like the stalk. A **short tip** (Applied < **0.30 s**, then lift, not firm `aEgo`) that knocked software long off kept interceptor ENABLE and ran a **comfort-shaped regen ramp** over **~2.5 s**: gentle first (`a ≈ −0.30`), then quadratic ease-in to `REGEN_MAX`. **Reverted — Justin asked for firm/stock brake cancel again** (same as #156). One-Pedal Long (#170–#172) is the accelerator path and stays. + +NAP revert soft brake-cancel regen (2026-09-14) +======================== +* **R1 reverted:** Pre-AP silent long pause brake cancel is firm/stock again. When `real_brake_pressed` drops software long, interceptor **RELEASEs immediately** to Tesla regen — no tip/hold classifier, no 0.50 s coast, no 0.75 s 0→stock ramp. On-car feedback: engage/accel (A+B + A3) felt better; the soft cancel made braking worse. **Kept:** #152 A+B (expire engage grace on gas→long + seed last non-negative `aEgo`) and #153 A3 (`max(aEgo, planner climb)` so Mannerisms Acceleration 1–10 drives open-road climb). Full cancel / FCW / AEB / hard lead unchanged. No `GAS_COMMAND` rewrite, no PostEngageCoast / climb latch / pedal-hold, no locationd or safety change. **Current again** after #157 soft-glide was also reverted. + +NAP regen ramp on light brake-cancel (2026-09-14) +======================== +* **R1 follow-up (reverted):** Pre-AP silent long pause: a **short/light** brake tap that knocks software long off now **ramps interceptor regen** from coast (`accel_request=0`) to stock (`REGEN_MAX` −1.5 m/s²) over **0.75 s** (tunable 0.5–1.0), then RELEASEs. ENABLE stays on; VDAS interpolates commanded accel so pedal DI walks into regen. **Not** a 0.50 s coast plateau then sudden stock bite, and **not** full regen on the first frame. Distinguishes tip vs hold like the stalk: Applied shorter than **0.30 s** without firm `aEgo` is a tip; a **held** pedal or **deeper** decel (`aEgo <= −1.5`) RELEASEs immediately so friction + stock regen stay firm. A3 Accel 1–10 gas-lift climb from #153 is unchanged. Full session cancel / FCW / AEB / hard lead braking unchanged. No `GAS_COMMAND` DI rewrite, no PostEngageCoast / climb latch, no locationd change. **Reverted — Justin asked for firm/stock brake cancel.** + +NAP soft regen + gas-lift Accel climb (2026-09-14) +======================== +* **R1 (reverted):** Pre-AP silent long pause: a **short/light** brake tap that knocks software long off now eases toward **coast** for **0.50 s** (tunable 0.3–0.8) before the interceptor RELEASEs to stock Tesla regen. Distinguishes tip vs hold like the stalk: Applied shorter than **0.30 s** without firm `aEgo` is a tip; a **held** pedal or **deeper** decel (`aEgo <= −1.5`) RELEASEs immediately so friction + stock regen stay firm. Full session cancel / FCW / AEB / hard lead braking unchanged. **Superseded, then fully reverted** (coast/ramp both felt worse than stock regen). +* **A3 (kept):** After gas→long handoff, open-road VDAS seed is `max(aEgo, planner climb)` so takeover uses Mannerisms **Acceleration** 1–10 (`NAPMapSpeedAccel`) toward MAX — not only the post-lift `aEgo`. Personality / MAX still caps. Lead hard decel / FCW / should-stop (`actuators.accel < 0`) still seed 0. No `GAS_COMMAND` DI rewrite, no PostEngageCoast / climb latch. **nap-dev only — no nap-release twin until Justin signs off.** + +NAP gas-lift long handoff (2026-09-13) +======================== +* After engage-on-gas then lift (or a gas override while software long is already on), Pre-AP no longer restarts the 0.5 s `ENGAGE_GRACE` a=0 floor, and VDAS is seeded from the last non-negative `aEgo` (MAX-capped) instead of `commanded_accel=0`. Lead hard decel / FCW / should-stop and brake still win. First engage without gas is unchanged (grace still ramps from 0). No `GAS_COMMAND` rewrite, no PostEngageCoast / climb-to-MAX / pedal-hold overlay, no panda or locationd change. **nap-dev only — no nap-release twin until Justin signs off.** + +NAP Acceleration settings placement (2026-09-13) +======================== +* Settings → NAP → **Driving Mannerisms** now has **Acceleration** 1–10 (`NAPMapSpeedAccel`, default 5). Same temperament as before: scales MAX climb / open-road accel feel (1 lazy → 10 quicker); map brake to a lower MAX stays Accel 5; lead still owns follow. Removed from Map Speed Limit so it sits with Adaptive Accel. Mannerisms order is accel feel → follow → soft lat → Hypermile; Map Speed is mode/offset/lookahead → refresh/download → status. Shorter settings copy. Hypermile still snaps/restores Accel 1. No longitudinal math change. + +NAP post-engage overlay stack revert (2026-09-13) +======================== +* Removed the whole post-engage overlay stack for driveability: climb-to-MAX / climb-sustain (#144, #146), last-pressed pedal hold (#142), and the 1 s speed-coast (#136). Those paths added delay and an intrusive climb/pedal/`ENABLE` rewrite that surged / pulsed. Handoff is stock OP long again (no `post_engage_coast.py` / `preap_post_engage_hold.py`). Will revisit later with a lighter approach. Locationd safety unchanged. + +NAP Follow Distance HUD hold (2026-09-13) +======================== +* Stalk Follow Distance toast is held **1.5 s** (WARNING + PERMANENT) and a tip already at **1 or 7** still shows **Follow Distance: N** (`NAPFollowHudPending`). Fixes intermittent missing HUD when the one-frame param poll lost to another alert or a no-op write. + +NAP Simulate Look full wipe restore (2026-09-13) +======================== +* **Simulate Look On** is again the pre–False Alert Ignore full looking-path wipe on the existing **1–3 s** cadence (no-face / uncertain / phone / pose / eye). The FAI split had narrowed it to a no-face glance that still let phone/pose/eye nag. **False Alert Ignore On** (Sim Look Off) stays phone-only soft-clear; pose/eye still drain. Mutex unchanged. Hard cancels (hands-on ≥ 2 / stalk / door / reverse) unchanged. nap-dev defaults stay Simulate Look **On** / FAI **Off**. Same behavior as nap-release (defaults differ). + +NAP Simulate Look / False Alert Ignore exclusive (2026-09-13) +======================== +* Triple-tap **Simulate Look** and **False Alert Ignore** are **mutually exclusive** — only one may be On (both Off is allowed). Enabling one in the 3X / mici popup clears the other live. Turning FAI On aborts an in-flight glance hold; turning Simulate Look On stops the phone soft-clear path. DM/policy also resolve a stale both-On (old installs) on first read: **Simulate Look On / FAI Off**. nap-dev defaults: Simulate Look **On**, FAI **Off**. nap-release: both **Off**. Pose/eye timers and yaw thresholds unchanged. + +NAP False Alert Ignore (2026-09-13) +======================== +* Triple-tap NAP popup is now **Force Offroad**, **Simulate Look**, **False Alert Ignore** (third item). New `NAPDmFalseAlertIgnore` (default **Off** on nap-dev so it is not On with Simulate Look; persistent like Simulate Look). While engaged, false **phone/device** distraction (`phoneProb` / phone bit) soft-clears on the same random **(1.0 s, 3.0 s]** cadence so a false “Driver Distracted” can recover without a real glance. **Pose** and **eye** still drain and alert — no hold / no awareness reset while those are alarming. Simulate Look no longer full-wipes `driver_distracted` (that was masking pose/eye); it only injects a no-face / uncertain glance. Simulate Look On + False Alert Ignore Off = stock phone detection. Hands-on ≥ 2 / stalk / door / reverse unchanged. Not a nap-release default-On change. + +NAP Force Offroad stock-CC handoff (2026-09-13) +======================== +* Pre-AP pedal / software long (`enableLongControl`): Force Offroad first shows a big on-road **Yes / No** (**Ready to resume steering control?**). No cancels the toggle and leaves assist as-is. Yes then holds `started` until stock Tesla CC is **ENABLED** at current speed (CANCEL toward STANDBY, drop OP long, SET_ACCEL). Avoids the hard regen bite when OP long dropped with nothing holding speed. Lat-only / stock-CC / not engaged: Yes still required on-road, then today's immediate offroad. Parked: no popup. On OP long engage, stock CC is canceled off if it was ENABLED or STANDBY so it does not fight the pedal. 2.5 s card / 3.0 s hardwared fallback if DI never takes SET (timeout starts only after Yes). + +NAP lead-follow comfort (2026-09-13) +======================== +* Pre-AP lead-approach enter is a bit higher so occasional **bump-pull** (regen bite → Accel rematch → bite) at the follow gap is less chatty. Enter `v_rel` **0.55** m/s (~1.2 mph); exit stays **0.20**. A far/gentle overlay nibble (|a| < **0.15**) must not steal Accel-1 catch-up / Follow Distance close; real ease and MPC 0/−a still use `min()`. Clear-close skip is **2.5** m/s (~5.6 mph). Comfort peak **0.55**, onset slew **0.05**/frame, slack gates, and immediate release stay. Still closes onto Follow Distance 1–7. MPC / FCW / danger braking unchanged. + +NAP Follow stalk tip vs full press (2026-09-13) +======================== +* Behind a radar lead, a Pre-AP full stalk press (through 1st detent to 2nd / **5 mph**) no longer also steps Follow Distance. Follow commits only when the lever returns to **IDLE** after a first-detent **tip** (1 mph) that never hit 2nd detent; that tip frame’s MAX is still undone. Raw `SpdCtrlLvr_Stat` / CruiseButtons distinguish UP_1ST vs UP_2ND (and DN). `buttonEvents` alone are not a tip — Pre-AP maps both detents to the same accel/decelCruise. No lead: stalk is still MAX only. Same tip/hold Follow rule as nap-release; Hypermile eco / Hill Climb / Step Down unchanged. + +NAP lead-approach earlier ease (2026-09-13) +======================== +* Pre-AP comfort ease now starts as soon as radar has **reasonable feedback** on a closing lead (`leadOne` valid and closing), not only near Follow Distance. Start ceiling **200 m** (usable Bosch; far tracks need `radar` + `modelProb` ≥ 0.5 — LeadData has no track age). Head-start **24 s**. Clearly closing (`v_rel` ≥ 1.0 m/s) eases even with large slack, still capped at **0.55** and slewed. Hysteresis from #121 stays. Catch-up +a cap stays at 140 m. MPC / FCW / map climb vs lead (#118) unchanged. No brake-light feature. + +NAP lead-follow comfort (2026-09-13) +======================== +* Pre-AP lead-approach overlay is smoother on a slight grade: enter/exit **hysteresis** on radar `v_rel` / slack so regen does not chatter on/off around the follow gap, comfort peak |a| is **0.55** (Early map, was Normal 0.80), and more-negative overlay `a` slews at **0.05**/frame. Off / milder `a` is immediate. MPC danger / hard brake / FCW unchanged. Map climb still does not replace MPC when a lead is present (#118). Grade-hold for no-lead uphills is unchanged. Not a nap-release change. + +NAP Follow Distance stalk tip vs hold (2026-09-13) +======================== +* Behind a radar lead, a Tesla stalk **tip / bump** (1 mph / 1 kph cruise step) adjusts stock Follow Distance 1–7 only and undoes that frame’s MAX / `pedal_speed` step (HUD **Follow Distance: N**). A **full press** (5 mph / 5 kph) keeps MAX +5/−5 and does not remap Follow Distance. No lead: tip and hold both still step MAX as stock. Pedal delta magnitude is the source of truth; a button-only edge without a clear 5 mph delta still counts as a tip. Hypermile does not own follow. + +NAP map climb vs lead + Follow HUD (2026-09-13) +======================== +* Under HUD MAX, map climb (`a_up` Accel 1–10) no longer **replaces** a non-negative MPC `aTarget` when a radar lead is valid. That overwrite pulled ego toward MAX through a slower/matched lead (hard punch while closing, then drop to ~48 and refuse to rematch 53–55). `map_track_decel` above MAX still mins in. Grade-hold `+g·sin` extras are also skipped while a lead constrains. Follow Distance HUD toast restored: stalk/settings 1–7 change shows **Follow Distance: N** for 1.5 s (`hypermileFollowChanged`, same WARNING+permanent affordance as personality). Grade-hold itself stays. Not a nap-release change. + +NAP Follow Distance (2026-09-13) +======================== +* Unified stock **Follow Distance 1–7** (`NAPFollowDistance`) for stalk adjustments — same whether Hypermile is On or Off. Behind a radar lead, stalk up/down writes that param so the Driving Mannerisms slider updates live, and that frame’s MAX / `pedal_speed` step is undone. No lead: stalk still steps MAX. Full stock seven including closest **1**. Removed the Hypermile-only 1–5 band, the “never stock 1” floor, the ≤50 mph forced far-gap (stock 7) override, and `NAPHypermileFollowLevel`. Follow Distance stays visible while Hypermile is On. HUD shows **Follow Distance: N**. Eco / Step Down / Adaptive Accel / Early / Accel 1 snaps stay; they no longer force follow. Grade-hold behavior is unchanged. Intentional product change: Hypermile no longer owns follow levels. Not a nap-release change. + +NAP Hypermile Hill Climb gate (2026-09-13) +======================== +* Hill Climb no longer treats `TRACK_TAPER` (~4.5 mph under MAX) as “near MAX”. Crest / downhill ease only when ego is **at or above MAX** (cruise − deadband). Grade hold (`+g·sin`) only when clearly under MAX — deadband / at-MAX leave the map hold (0) so we do not punch past MAX and hunt with Accel-5. Fixes Hypermile hunting ~4 mph under MAX (47–51 under a 54 MAX) with regen pulses instead of settling. **Maps-elevation lookahead is NOT included.** Never raises MAX. Lead / MPC still win. Not a nap-release change. + +NAP Simulate Look label (2026-09-13) +======================== +* Triple-tap NAP popup title is **Simulate Look** (was **Simulate Look-at-Road**). Same `NAPDmSimulateLooking` param and behavior. Force Offroad label unchanged. Not a nap-release change. + +NAP hidden settings (2026-09-13) +======================== +* **Simulate Look** and **Force Offroad / Go Offline** are no longer on the normal NAP or Driving Mannerisms lists. Triple-tap **NAP** in Settings (3 taps in a 1.0 s sliding window) opens a side popup with those two toggles only. Tap outside the card to dismiss (X / tap NAP again also work). Same params and Reset-All defaults. Soft-lat, Hypermile, Hill Climb, Step Down unchanged. mici: triple-tap the **nap** button. Not a nap-release change. + +NAP Hypermile Hill Climb (2026-09-12) +======================== +* Settings → NAP → Driving Mannerisms → **Hill Climb** (default **On**, hidden/inert unless Hypermile is On). IMU pitch (`orientationNED[1]`) raises Accel 1 climb authority on a real uphill so Hypermile does not sag under HUD MAX, and eases lightly on a flattening crest / downhill. **Maps-elevation lookahead is NOT included.** Never raises MAX. Lead / MPC hard brake still win. Soft-lat, blinker, sticky MAX, Step Down, lead-close, DM unchanged. Not a nap-release change. + +NAP curve MAX (2026-09-12) +======================== +* Sharp curve: still slow for a comfortable corner (`limit_accel_in_turns` + a temporary lat-accel MAX cap). Snapshot HUD MAX / sticky at entry; after the bend (lat accel / steer straight-ish) restore that pre-curve set. Do not permanently bounce MAX down through a turn — Hypermile eco −5 (posted 60 → steady 55) must not replace a pre-curve MAX of 60. Step Down, lead-close, soft-lat, and blinker-keep-long unchanged. + +NAP Hypermile (2026-09-12) +======================== +* Hypermile On + Step Down Off no longer snaps Map Speed Offset to a flat **−5** (that dropped town posted **30 → 25**). Eco offset is live from the posted/OSM limit: **0** at/under 50 mph so 30 stays 30 and 50 stays 50; linear 0 → −8 from 50 to 80 (65 → 61); **−8** at 80 (→72) and capped −8 above (90 → 82). **Step Down On** uses the same 50→80 scale, just larger: **0** at/under 50 (town 30 stays 30), **−15** at 80 (→65), cap −15 above (90 → 75). Replaces eco, no stack, no flat −15 on town limits. **Maps-only:** eco / Step Down apply only with a known OSM/posted limit; maps off, no match, or unknown posted → no invented drop (same as sticky MAX). Off still restores the saved offset slider. Early lookahead / Accel 1 / stalk 1–5 / 50 mph follow split / curve hold / lead-close / soft-lat unchanged. Not a nap-release change. + +NAP blinker (2026-09-12) +======================== +* A latched driver-turn blinker no longer drops / pauses longitudinal. `enableLongControl` stays true through a held stalk / flash-latched turn; lead/map braking and accel still apply. Soft-lat On/Off lat behavior, brake silent long pause + sticky MAX + one SET / double SET, ALC tip/keep-alive, reverse hard-cancel, standstill one-SET gas gate, Hypermile, and lead-close accel unchanged. + +NAP lead follow (2026-09-12) +======================== +* Pre-AP: closing on / coming up behind a radar lead no longer uses the cruise **1.6–0.6 m/s²** punch (Adaptive Accel used the full profile on a large gap; map Accel 1–10 only gated MAX-rise climb). Catch-up **+a** is now `lead_close_accel_ms2`: **0.20** at Accel 1, **0.30** at 5, **0.50** at 10, inside ~140 m. Still closes onto the selected Follow Distance. MPC danger / hard brake, Hypermile, sticky MAX, soft-lat, and DM unchanged. Settings → NAP → Map Speed Limit → Acceleration. + +NAP Hypermile (2026-09-12) +======================== +* Settings → NAP → Driving Mannerisms → **Hypermile** (default Off, nap-dev only). Comfort-biased efficiency: On snaps Adaptive Accel + Cap/Follow / −5 mph / **Early** lookahead / **Accel 1** lazy climb (early light ease, not max regen bite), then restores those knobs when Off. Soft-lat / DM / blinker unchanged. Below ~50 mph follow sits far back (stock 7 / 1.9 s); above 50 mph uses a stalk 1–5 draft band (1=closest safe 0.9 s, 5=1.7 s). With a lead, stalk up=closer and down=farther (MAX unchanged). No lead: stalk still adjusts MAX. HUD shows **Hypermile: Follow N** when the level changes. Opt-in **Step Down Speed** (default Off, inert unless Hypermile is On): Cap/Follow targets **15 mph under posted** (75→60, 55→40; no stack with eco −5). Follow stalk SET can still hold above the step-down until posted changes. Not a nap-release change. + +NAP driver monitoring (2026-09-12) +======================== +* Pre-AP engaged: **Simulate Look** (default On) injects a simulated glance on the **stock vision looking-path** (`face_detected` + low pose std + `driver_distraction_filter.x < 0.37`) and **holds** that attentive state until stock gradual recovery returns awareness to **1.0** (not a one-frame pulse / mute). After drain starts, wait **past 1.0 s**, then fire at a **random time in the next 2.0 s** — fire is uniform in **(1.0 s, 3.0 s]** of that countdown. After a full reset the same rule applies to the next countdown. Orange / red stay stock **5 / 11 s** if the toggle is Off. Hands-on ≥ 2 / stalk / door / reverse hard cancels unchanged. Replaces the #103 hands-on-only first-band reset. Settings → triple-tap **NAP** (not Driving Mannerisms). Not a nap-release change. + +NAP settings (2026-09-12) +======================== +* Settings → NAP: Adaptive Accel Limits, Follow Distance, and Soft Lateral Handoff move into **Driving Mannerisms**. Same params and behavior. Back returns to NAP (not the side Settings list). Map Speed Limit, Radar, pedal, beams, speed-sign, and EPAS stay on the main NAP list. + +NAP Pre-AP reverse / gear / standstill SET (2026-09-12) +======================== +* Reverse (and any gear out of Drive / door) is a **full hard cancel**: session down, sticky MAX forgotten, soft-lat reset, CANCEL spoof so panda can re-arm `controls_allowed`. After Drive returns, a normal double SET engages without Controls Mismatch or a prior disable dance. Soft-lat Off blinker pause and sticky-MAX brake/turn pause unchanged. +* One SET after a silent long pause **at a stop** does not take long / creep from 0. SET still keeps held MAX (“I want resume”); a light throttle touch then resumes at that MAX. Rolling one-SET resume and double SET / forget-sticky unchanged. + +NAP driver lat handoff (2026-09-12) +======================== +* Soft-lat **On**: a driver-turn blinker no longer strips lateral. Lamp latch does not clear `latActive` / force EPS free — keep control if we still have it. Soft-lat may still yield if the driver pushes. While the driver-turn blinker is latched, do not re-enable (stay yielded / do not finish a take-back blend). After it clears, resume goes through soft yield + the normal **0.15 s** hands-off confirm + **1 s** blend — no dedicated blinker rising-edge blend. Soft-lat **Off** keeps today’s blinker lat-pause so a held turn still frees the wheel. ALC tip/keep-alive, long sticky-MAX turn pause, yield thresholds, emergency hard-brake cancel, and hazards unchanged. + +NAP driver lat handoff (2026-09-11) +======================== +* Soft-lat hands-off confirm before take-back shortened from **0.25 s → 0.15 s** (`HANDS_OFF_CONFIRM_S`). Free-wheel yield, 1 s blend, blinker re-entry, and emergency cancel unchanged. Renewed hands-on or a firm push during the 0.15 s wait still re-yields and resets. + +NAP map speed (2026-09-11) +======================== +* Map MAX short-zone ignore raised from ~50 ft (15 m) to **~250 ft (76 m)** along heading. Cross-street / bleed flashes that lasted past 50 ft are now ignored. Real on-route drops that continue for hundreds of meters (US 12 tagged 50 ~760 m, DeGraff 30) still ease. Off-route bearing/class filter unchanged. + +NAP driver lat handoff (2026-09-11) +======================== +* Soft lateral handoff is **default On**. After a free-wheel yield, stay free while `handsOnLevel >= 1` or a renewed firm push. When hands go to **0**, require **~0.25 s** hands-off confirm (`HANDS_OFF_CONFIRM_S`) before the **1 s** smoothstep blend — not the old 80 ms confirm. A brief hands-off or right-then-left crossover during the dodge must not snatch. Renewed hands-on or ≥ 0.55 Nm during that wait or the blend re-yields (EPS free) and resets the delay. `QUIET_WAIT_S` stays 0 (torsion-quiet used to blend on mid-dodge dips). Entry ~0.55 Nm / 90 ms + hands, blinker 1 s soft re-entry, emergency hard-brake cancel, sticky MAX / light brake, gravel spike rejection unchanged. Settings → NAP → Soft Lateral Handoff default **On**. Panda / hands-on ≥ 2 unchanged. + +NAP map speed (2026-09-11) +======================== +* Map MAX ignores a lower OSM limit that only lasts ~50 ft (15 m) along heading — cross-street bleed / intersection stubs. Real on-route drops that continue past that still ease. Off-route bearing/class filter unchanged. + +NAP driver lat handoff (2026-09-11) +======================== +* Soft lateral handoff is **default On**. **Yield = free the EPS**, not follow-measured angle control. A light purposeful push + hands (`|torsion| >= 0.55 Nm` for ~90 ms consecutive, `handsOnLevel >= 1`) drops `latActive` so Pre-AP sends `DAS_steeringControlType=0` — same release as blinker lat-pause. #79 still wrestled because OP kept full authority until the 0.70 Nm / 140 ms debounce finished, then kept `latActive` and commanded measured angle (closed-loop hold). Near 1.0 Nm the consecutive bar drops toward 60 ms so the soft path still beats hands-on ≥ 2. Hands-on hold + pin-to-wheel + **1 s blend** on return unchanged (parking-lot blinker soft re-entry kept: pin while lat down; 1 s blend on blinker rising edge; yield / stay free if hands still on). Gravel spike trains still gap-reset; rumble at ~0.50 Nm or hands-off must not free-yield. **Emergency / hard brake** while yielded or within 2 s of yield entry (digital Applied + `aEgo <= −3.5 m/s²` for 80 ms) fully cancels OP. Light brake is still sticky-MAX silent pause + one SET. Settings → NAP → Soft Lateral Handoff can turn **Off**. Panda / hands-on ≥ 2 unchanged. + +NAP driver lat handoff (2026-09-11) +======================== +* Soft lateral handoff is **default On**. Yield on a **sustained driver push + hands** (`|torsion| >= 0.70 Nm` for ~140 ms consecutive, `handsOnLevel >= 1`). Steer rate is **not** required — an isometric fight (low rate, high tracking error) soft-yields instead of holding until hands-on ≥ 2 / `STEER_THRESHOLD` hard cancel. Near 1.0 Nm the consecutive bar drops toward 80 ms so the soft path wins first. Disturbance veto only when torsion is **below** 0.70 Nm (wind / crown). Gravel spike trains still gap-reset. Hands-on hold + 1 s hands-off blend + curvature pin unchanged. **Emergency / hard brake** while yielded or within 2 s of yield entry (digital Applied + `aEgo <= −3.5 m/s²` for 80 ms) fully cancels OP. Light brake is still sticky-MAX silent pause + one SET. Settings → NAP → Soft Lateral Handoff can turn **Off**. Panda / hands-on ≥ 2 unchanged. + +NAP driver lat handoff (2026-09-11) +======================== +* Soft lateral handoff is **default On** and now yields only on **driver intent** to turn the wheel: sustained torsion (≥ 0.70 Nm / 140 ms) **and** matching steer rate **and** hands on the rim. Gravel spikes, opposite-rate pressure, and high tracking error without matching torsion (wind / crown) do not yield. Hands-on hold + 1 s hands-off blend unchanged. **Emergency / hard brake** while yielded or within 2 s of yield entry (digital Applied + `aEgo <= −3.5 m/s²` for 80 ms) fully cancels OP with the normal disengage chime — not the silent long pause. Light brake is still sticky-MAX silent pause + one SET. Settings → NAP → Soft Lateral Handoff can turn **Off**. Panda / hands-on ≥ 2 unchanged. + +NAP driver lat handoff (2026-09-11) +======================== +* Soft lateral handoff is **default On**. Yield stays ~0.70 Nm held 0.14 s consecutive (gap reset; not 0.5 Nm / 80 ms rumble). Stay yielded while `EPAS_handsOnLevel >= 1` so a mid-dodge torsion dip does not start hand-back. 1 s blend starts only after hands are truly off the rim for ~80 ms. Hands back on or a firm push cancels the blend and re-yields. Planner still pins to the wheel while yielded / lat down so resume tracks the path. Blinker-turn re-entry is still the same 1 s blend from the wheel. Settings → NAP → Soft Lateral Handoff: turn **Off** if gravel or wind still gray the chrome. Brake silent long-pause + one SET is unchanged. Panda / hands-on ≥ 2 hard cancel unchanged. + +NAP driver lat handoff (2026-09-11) +======================== +* Soft lateral handoff is **default On**. Firmer yield: ~0.85 Nm held 0.25 s consecutive (not 0.5 Nm rumble). After a yield, planner curvature stays on the wheel so resume actually tracks the path (green HUD + on-screen path was not enough). Settings → NAP → Soft Lateral Handoff: turn **Off** if gravel or wind still gray the chrome. Brake silent long-pause + one SET is unchanged. + +NAP driver lat handoff (2026-09-11) +======================== +* Light wheel input (about half the usual override effort) now yields steering without canceling openpilot. Speed control stays on. After 0.25 s of quiet the wheel blends back over 1 s. Gray HUD until ~70% lateral is back; no disengage chime. A hard yank / cancel still fully disengages. No panda flash. + +NAP sticky MAX (2026-09-11) +======================== +* Pedal mode: brake or a held/latched driver-turn blinker pauses longitudinal only. Held MAX is remembered. That pause is **silent** — no “Pedal Cruise Disengaged” / disengage chime. One SET resumes long at that MAX (already rebased if posted changed) without a full-stack engage fanfare. Double SET forgets sticky: maps on + posted known → current posted; maps off / unknown → current traveled speed. Same double SET is initial engage. Maps never overwrite sticky every frame; GPS drop does not invent or wipe posted. Tip ALC does not use this pause. Hard cancel (stalk / door / gear / steer fault / hands-on ≥ 2) still fully disengages and still plays the disengage prompt. No-pedal stock CC is unchanged. Soft lat handoff unchanged. + +NAP speed-sign log (2026-09-11) +======================== +* SIGN WAIT is only when openpilot is actively controlling. A 1 Hz SubMaster used to treat unknown / stale `selfdriveState` as engaged for ~10 s after cancel (`recv_frame <= 0` + 100 ms alive window). Poll at 20 Hz; gate on `active`; abandon in-flight ONNX on re-engage so the loop never blocks. If TAKE CONTROL / Communication Issue comes back, turn Logger Off. + +NAP speed-sign log (2026-09-10) +======================== +* Speed Sign Logger On no longer runs YOLO while openpilot is engaged (SIGN shows WAIT). Manual driving — moving OK — still logs signs at 1 Hz. If TAKE CONTROL comes back, turn Logger Off. + +NAP blinker (2026-09-10) +======================== +* A held/latched driver turn blinker now drops longitudinal as well as pausing lat. After the lamps/latch end, one stalk SET restores long (lat still paused or already active). ALC tip/keep-alive does not drop long. Stalk cancel still fully disengages; brake can still drop long. No panda flash required. + +NAP blinker (2026-09-09) +======================== +* Panda tesla_preap now keeps controls_allowed on a driver blinker-held turn (one lamp or LEFT/RIGHT, flash-latched ~1s) so hands-on ≥ 2 does not controlsMismatch after the turn. **Flash the panda after this update** (reboot so pandad reflashes; Python-only pull is not enough). Stalk cancel / doors / gear still drop. +* Held-blinker turns no longer full-cancel mid-corner. Higher steering torque / EPAS hands-on ≥ 2 while lat is paused stays engaged (lat pause only). The 3X "Steering Disengaged" HUD is EventName.pcmDisable (cruiseEnabled fell) — keep cruise up on lamp or held stalk, and do not treat that torque as controlsMismatch / steerDisengage. Stalk cancel / doors / gear / permanent steer fault still fully disengage. + +NAP Force Offroad (2026-09-09) +======================== +* Settings → NAP → Force Offroad / Go Offline. Temporarily drops the device into offroad (started=false) while the car is still moving so Download US Maps, Refresh maps, and software install unlock. Stops openpilot — drive manually. Default Off. Clears on toggle Off, Reset to Defaults, reboot, or the next ignition ON. + +NAP speed-sign log (2026-09-09) +======================== +* Optional on-drive MUTCD speed-sign logger (default off). ROAD camera + GPS, JSONL under /data. On-road SIGN plate shows the live mph for 1.5s. Does not change cruise or maps. + +NAP blinker (2026-09-09) +======================== +* During ALC (or leftover keep-alive), holding the physical stalk the same direction for more than 1.0s cancels the lane change and pauses steering as a driver turn. A shorter same-direction press does not force a turn. Tip-to-ALC from idle is still LEFT/RIGHT then IDLE within 0.40s. +* Tip vs turn no longer depends on speed. A partial stalk push (LEFT/RIGHT then IDLE within 0.40s) is automatic lane change at any speed; a full held stalk is a driver turn and releases steering. Lane change still will not *start* below 20 mph until a wheel nudge at speed. + +NAP map speed (2026-09-08) +======================== +* Refresh maps queries live OSM within 100 miles of the car and merges into the installed US sqlite. Download US Maps remains the first-install of the published pack. + +NAP map speed (2026-09-07) +======================== +* OSM map speed can drive HUD MAX (pedal mode). Off by default. Download US maps from Settings → NAP → Map Speed Limit (ODbL). Map speed sets the cruise ceiling; radar still follows a slower lead. + +NAP 2026-09-02 +======================== +* Fix card crash on clean Comma install (Tesla radar DBC) + +Version 0.11.1 (2026-05-18) +======================== +* New driver monitoring model +* Improved image processing pipeline for driver camera +* Improved thermal policy for comma four +* Acura MDX 2022-24 support thanks to mvl-boston! +* Rivian R1S and R1T 2025 support thanks to lukasloetkolben! + +Version 0.11.0 (2026-03-17) +======================== +* New driving model #36798 + * Fully trained using a learned simulator + * Improved longitudinal performance in Experimental mode +* Reduce comma four standby power usage by 77% to 52 mW +* Kia K7 2017 support thanks to royjr! +* Lexus LS 2018 support thanks to Hacheoy! + +Version 0.10.3 (2025-12-17) +======================== +* New driving model #36249 + * New temporal policy architecture + * New on-policy training physics noise model +* New driver monitoring model #36409 + * Trained on a new dataset, including comma four data +* Improved inter-process communication memory efficiency + +Version 0.10.2 (2025-11-19) +======================== +* comma four support + +Version 0.10.1 (2025-09-08) +======================== +* New driving model #36276 + * World Model: removed global localization inputs + * World Model: 2x the number of parameters + * World Model: trained on 4x the number of segments + * VAE Compression Model: new architecture and training objective + * Driving Vision Model: trained on 4x the number of segments +* New Driver Monitoring model #36198 +* Acura TLX 2021 support thanks to MVL! +* Honda City 2023 support thanks to vanillagorillaa and drFritz! +* Honda N-Box 2018 support thanks to miettal! +* Honda Odyssey 2021-25 support thanks to csouers and MVL! +* Honda Passport 2026 support thanks to vanillagorillaa and MVL! + +Version 0.10.0 (2025-08-05) +======================== +* New driving model + * New training architecture + * Described in our CVPR paper: "Learning to Drive from a World Model" + * Longitudinal MPC replaced by E2E planning from World Model in Experimental Mode + * Action from lateral MPC as training objective replaced by E2E planning from World Model + * Low-speed lead car ground-truth fixes +* Enable live-learned steering actuation delay +* Opt-in audio recording for dashcam video +* Acura MDX 2025 support thanks to vanillagorillaa and MVL! +* Honda Accord 2023-25 support thanks to vanillagorillaa and MVL! +* Honda CR-V 2023-25 support thanks to vanillagorillaa and MVL! +* Honda Pilot 2023-25 support thanks to vanillagorillaa and MVL! + +Version 0.9.9 (2025-05-23) +======================== +* New driving model + * New training architecture using parts from MLSIM +* Steering actuation delay is now learned online +* Ford Escape 2023-24 support thanks to incognitojam! +* Ford Kuga 2024 support thanks to incognitojam! +* Hyundai Nexo 2021 support thanks to sunnyhaibin! +* Tesla Model 3 and Y support thanks to lukasloetkolben! +* Lexus RC 2023 support thanks to nelsonjchen! + +Version 0.9.8 (2025-02-28) +======================== +* New driving model + * Model now gates applying positive acceleration in Chill mode +* New driver monitoring model + * Reduced false positives related to passengers +* Image processing pipeline moved to the ISP + * More GPU time for bigger driving models + * Power draw reduced 0.5W, which means your device runs cooler * Added toggle to enable driver monitoring even when openpilot is not engaged +* Localizer rewritten to remove GPS dependency at runtime +* Firehose Mode for maximizing your training data uploads +* Enable openpilot longitudinal control for Ford Q3 vehicles +* New Toyota TSS2 longitudinal tune +* Rivian R1S and R1T support thanks to lukasloetkolben! +* Ford F-150, F-150 Hybrid, Mach-E, and Ranger support Version 0.9.7 (2024-06-13) ======================== diff --git a/SConstruct b/SConstruct index fea47440cf4955..ff6236d74ecbfb 100644 --- a/SConstruct +++ b/SConstruct @@ -3,388 +3,333 @@ import subprocess import sys import sysconfig import platform +import shlex +import importlib import numpy as np import SCons.Errors - -SCons.Warnings.warningAsException(True) - -# pending upstream fix - https://github.com/SCons/scons/issues/4461 -#SetOption('warn', 'all') +from SCons.Defaults import _stripixes TICI = os.path.isfile('/TICI') -AGNOS = TICI - -Decider('MD5-timestamp') - -SetOption('num_jobs', int(os.cpu_count()/2)) - -AddOption('--kaitai', - action='store_true', - help='Regenerate kaitai struct parsers') - -AddOption('--asan', - action='store_true', - help='turn on ASAN') - -AddOption('--ubsan', - action='store_true', - help='turn on UBSan') -AddOption('--coverage', - action='store_true', - help='build with test coverage options') - -AddOption('--clazy', - action='store_true', - help='build with clazy') - -AddOption('--compile_db', - action='store_true', - help='build clang compilation database') - -AddOption('--ccflags', - action='store', - type='string', - default='', - help='pass arbitrary flags over the command line') - -AddOption('--snpe', - action='store_true', - help='use SNPE on PC') +SCons.Warnings.warningAsException(True) -AddOption('--external-sconscript', - action='store', - metavar='FILE', - dest='external_sconscript', - help='add an external SConscript to the build') +Decider('MD5-timestamp') -AddOption('--pc-thneed', - action='store_true', - dest='pc_thneed', - help='use thneed on pc') +SetOption('num_jobs', max(1, int(os.cpu_count()/(1 if "CI" in os.environ else 2)))) +AddOption('--ccflags', action='store', type='string', default='', help='pass arbitrary flags over the command line') +AddOption('--verbose', action='store_true', default=False, help='show full build commands') +release = not os.path.exists(File('#.gitattributes').abspath) # file absent on release branch, see release_files.py AddOption('--minimal', action='store_false', dest='extras', - default=os.path.exists(File('#.lfsconfig').abspath), # minimal by default on release branch (where there's no LFS) + default=(not TICI and not release), help='the minimum build to run openpilot. no tests, tools, etc.') -## Architecture name breakdown (arch) -## - larch64: linux tici aarch64 -## - aarch64: linux pc aarch64 -## - x86_64: linux pc x64 -## - Darwin: mac x64 or arm64 -real_arch = arch = subprocess.check_output(["uname", "-m"], encoding='utf8').rstrip() +# Detect platform +arch = subprocess.check_output(["uname", "-m"], encoding='utf8').rstrip() if platform.system() == "Darwin": arch = "Darwin" - brew_prefix = subprocess.check_output(['brew', '--prefix'], encoding='utf8').strip() -elif arch == "aarch64" and AGNOS: +elif arch == "aarch64" and TICI: arch = "larch64" -assert arch in ["larch64", "aarch64", "x86_64", "Darwin"] - -lenv = { - "PATH": os.environ['PATH'], - "LD_LIBRARY_PATH": [Dir(f"#third_party/acados/{arch}/lib").abspath], - "PYTHONPATH": Dir("#").abspath + ':' + Dir(f"#third_party/acados").abspath, - - "ACADOS_SOURCE_DIR": Dir("#third_party/acados").abspath, - "ACADOS_PYTHON_INTERFACE_PATH": Dir("#third_party/acados/acados_template").abspath, - "TERA_PATH": Dir("#").abspath + f"/third_party/acados/{arch}/t_renderer" -} +assert arch in [ + "larch64", # linux tici arm64 + "aarch64", # linux pc arm64 + "x86_64", # linux pc x64 + "Darwin", # macOS arm64 (x86 not supported) +] -rpath = lenv["LD_LIBRARY_PATH"].copy() +pkg_names = ['acados', 'bzip2', 'capnproto', 'catch2', 'eigen', 'ffmpeg', 'json11', 'libjpeg', 'libyuv', 'ncurses', 'zeromq', 'zstd'] +pkgs = [importlib.import_module(name) for name in pkg_names] +acados = pkgs[pkg_names.index('acados')] +acados_include_dirs = [ + acados.INCLUDE_DIR, + os.path.join(acados.INCLUDE_DIR, "blasfeo", "include"), + os.path.join(acados.INCLUDE_DIR, "hpipm", "include"), +] -if arch == "larch64": - cpppath = [ - "#third_party/opencl/include", - ] - - libpath = [ - "/usr/local/lib", - "/system/vendor/lib64", - f"#third_party/acados/{arch}/lib", - ] - - libpath += [ - "#third_party/snpe/larch64", - "#third_party/libyuv/larch64/lib", - "/usr/lib/aarch64-linux-gnu" - ] - cflags = ["-DQCOM2", "-mcpu=cortex-a57"] - cxxflags = ["-DQCOM2", "-mcpu=cortex-a57"] - rpath += ["/usr/local/lib"] -else: - cflags = [] - cxxflags = [] - cpppath = [] - rpath += [] - - # MacOS - if arch == "Darwin": - libpath = [ - f"#third_party/libyuv/{arch}/lib", - f"#third_party/acados/{arch}/lib", - f"{brew_prefix}/lib", - f"{brew_prefix}/opt/openssl@3.0/lib", - "/System/Library/Frameworks/OpenGL.framework/Libraries", - ] - - cflags += ["-DGL_SILENCE_DEPRECATION"] - cxxflags += ["-DGL_SILENCE_DEPRECATION"] - cpppath += [ - f"{brew_prefix}/include", - f"{brew_prefix}/opt/openssl@3.0/include", - ] - lenv["DYLD_LIBRARY_PATH"] = lenv["LD_LIBRARY_PATH"] - # Linux - else: - libpath = [ - f"#third_party/acados/{arch}/lib", - f"#third_party/libyuv/{arch}/lib", - "/usr/lib", - "/usr/local/lib", - ] - - if arch == "x86_64": - libpath += [ - f"#third_party/snpe/{arch}" - ] - rpath += [ - Dir(f"#third_party/snpe/{arch}").abspath, - ] - -if GetOption('asan'): - ccflags = ["-fsanitize=address", "-fno-omit-frame-pointer"] - ldflags = ["-fsanitize=address"] -elif GetOption('ubsan'): - ccflags = ["-fsanitize=undefined"] - ldflags = ["-fsanitize=undefined"] -else: - ccflags = [] - ldflags = [] -# no --as-needed on mac linker -if arch != "Darwin": - ldflags += ["-Wl,--as-needed", "-Wl,--no-undefined"] +# ***** enforce a whitelist of system libraries ***** +# this prevents silently relying on a 3rd party package, +# e.g. apt-installed libusb. all libraries should either +# be distributed with all Linux distros and macOS, or +# vendored in commaai/dependencies. +allowed_system_libs = { + "EGL", "GLESv2", "GL", + "Qt5Charts", "Qt5Core", "Qt5Gui", "Qt5Widgets", + "dl", "drm", "gbm", "m", "pthread", +} -ccflags_option = GetOption('ccflags') -if ccflags_option: - ccflags += ccflags_option.split(' ') +def _resolve_lib(env, name): + for d in env.Flatten(env.get('LIBPATH', [])): + p = Dir(str(d)).abspath + for ext in ('.a', '.so', '.dylib'): + f = File(os.path.join(p, f'lib{name}{ext}')) + if f.exists() or f.has_builder(): + return name + if name in allowed_system_libs: + return name + raise SCons.Errors.UserError(f"Unexpected non-vendored library '{name}'") + +def _libflags(target, source, env, for_signature): + libs = [] + lp = env.subst('$LIBLITERALPREFIX') + for lib in env.Flatten(env.get('LIBS', [])): + if isinstance(lib, str): + if os.sep in lib or lib.startswith('#'): + libs.append(File(lib)) + elif lib.startswith('-') or (lp and lib.startswith(lp)): + libs.append(lib) + else: + libs.append(_resolve_lib(env, lib)) + else: + libs.append(lib) + return _stripixes(env['LIBLINKPREFIX'], libs, env['LIBLINKSUFFIX'], + env['LIBPREFIXES'], env['LIBSUFFIXES'], env, env['LIBLITERALPREFIX']) env = Environment( - ENV=lenv, + ENV={ + "PATH": os.environ['PATH'], + "PYTHONPATH": Dir("#").abspath, + "ACADOS_SOURCE_DIR": acados.DIR, + "ACADOS_PYTHON_INTERFACE_PATH": acados.TEMPLATE_DIR, + "TERA_PATH": acados.TERA_PATH + }, CCFLAGS=[ "-g", "-fPIC", "-O2", "-Wunused", "-Werror", - "-Wshadow", + "-Wshadow" if arch in ("Darwin", "larch64") else "-Wshadow=local", "-Wno-unknown-warning-option", "-Wno-inconsistent-missing-override", "-Wno-c99-designator", "-Wno-reorder-init-list", "-Wno-vla-cxx-extension", - ] + cflags + ccflags, - - CPPPATH=cpppath + [ + ], + CFLAGS=["-std=gnu11"], + CXXFLAGS=["-std=c++1z"], + CPPPATH=[ "#", - "#third_party/acados/include", - "#third_party/acados/include/blasfeo/include", - "#third_party/acados/include/hpipm/include", - "#third_party/catch2/include", - "#third_party/libyuv/include", - "#third_party/json11", - "#third_party/linux/include", - "#third_party/snpe/include", - "#third_party", "#msgq", + acados_include_dirs, + [x.INCLUDE_DIR for x in pkgs], ], - - CC='clang', - CXX='clang++', - LINKFLAGS=ldflags, - - RPATH=rpath, - - CFLAGS=["-std=gnu11"] + cflags, - CXXFLAGS=["-std=c++1z"] + cxxflags, - LIBPATH=libpath + [ + LIBPATH=[ + "#common", "#msgq_repo", - "#third_party", "#selfdrive/pandad", - "#common", "#rednose/helpers", + [x.LIB_DIR for x in pkgs], ], + RPATH=[], CYTHONCFILESUFFIX=".cpp", COMPILATIONDB_USE_ABSPATH=True, REDNOSE_ROOT="#", tools=["default", "cython", "compilation_db", "rednose_filter"], toolpath=["#site_scons/site_tools", "#rednose_repo/site_scons/site_tools"], ) +if arch != "larch64": + env['_LIBFLAGS'] = _libflags -if arch == "Darwin": - # RPATH is not supported on macOS, instead use the linker flags - darwin_rpath_link_flags = [f"-Wl,-rpath,{path}" for path in env["RPATH"]] - env["LINKFLAGS"] += darwin_rpath_link_flags - -if GetOption('compile_db'): - env.CompilationDatabase('compile_commands.json') - -# Setup cache dir -cache_dir = '/data/scons_cache' if AGNOS else '/tmp/scons_cache' -CacheDir(cache_dir) -Clean(["."], cache_dir) - -node_interval = 5 -node_count = 0 -def progress_function(node): - global node_count - node_count += node_interval - sys.stderr.write("progress: %d\n" % node_count) +# Arch-specific flags and paths +if arch == "larch64": + env["CC"] = "clang" + env["CXX"] = "clang++" + env.Append(LIBPATH=[ + "/usr/lib/aarch64-linux-gnu", + ]) + arch_flags = ["-D__TICI__", "-mcpu=cortex-a57"] + env.Append(CCFLAGS=arch_flags) + env.Append(CXXFLAGS=arch_flags) +elif arch == "Darwin": + env.Append(LIBPATH=[ + "/System/Library/Frameworks/OpenGL.framework/Libraries", + ]) + env.Append(CCFLAGS=["-DGL_SILENCE_DEPRECATION"]) + env.Append(CXXFLAGS=["-DGL_SILENCE_DEPRECATION"]) -if os.environ.get('SCONS_PROGRESS'): - Progress(progress_function, interval=node_interval) +_extra_cc = shlex.split(GetOption('ccflags') or '') +if _extra_cc: + env.Append(CCFLAGS=_extra_cc) -# Cython build environment -py_include = sysconfig.get_paths()['include'] +# no --as-needed on mac linker +if arch != "Darwin": + env.Append(LINKFLAGS=["-Wl,--as-needed", "-Wl,--no-undefined"]) + +# Shorter build output: show brief descriptions instead of full commands. +# Full command lines are still printed on failure by scons. +if not GetOption('verbose'): + for action, short in ( + ("CC", "CC"), + ("CXX", "CXX"), + ("LINK", "LINK"), + ("SHCC", "CC"), + ("SHCXX", "CXX"), + ("SHLINK", "LINK"), + ("AR", "AR"), + ("RANLIB", "RANLIB"), + ("AS", "AS"), + ): + env[f"{action}COMSTR"] = f" [{short}] $TARGET" + +# ********** Cython build environment ********** envCython = env.Clone() -envCython["CPPPATH"] += [py_include, np.get_include()] -envCython["CCFLAGS"] += ["-Wno-#warnings", "-Wno-shadow", "-Wno-deprecated-declarations"] +envCython["CPPPATH"] += [sysconfig.get_paths()['include'], np.get_include()] +envCython["CCFLAGS"] += ["-Wno-#warnings", "-Wno-cpp", "-Wno-shadow", "-Wno-deprecated-declarations"] envCython["CCFLAGS"].remove("-Werror") envCython["LIBS"] = [] if arch == "Darwin": - envCython["LINKFLAGS"] = ["-bundle", "-undefined", "dynamic_lookup"] + darwin_rpath_link_flags + envCython["LINKFLAGS"] = env["LINKFLAGS"] + ["-bundle", "-undefined", "dynamic_lookup"] else: envCython["LINKFLAGS"] = ["-pthread", "-shared"] np_version = SCons.Script.Value(np.__version__) Export('envCython', 'np_version') -# Qt build environment -qt_env = env.Clone() -qt_modules = ["Widgets", "Gui", "Core", "Network", "Concurrent", "DBus", "Xml"] +Export('env', 'arch', 'acados') -qt_libs = [] -if arch == "Darwin": - qt_env['QTDIR'] = f"{brew_prefix}/opt/qt@5" - qt_dirs = [ - os.path.join(qt_env['QTDIR'], "include"), - ] - qt_dirs += [f"{qt_env['QTDIR']}/include/Qt{m}" for m in qt_modules] - qt_env["LINKFLAGS"] += ["-F" + os.path.join(qt_env['QTDIR'], "lib")] - qt_env["FRAMEWORKS"] += [f"Qt{m}" for m in qt_modules] + ["OpenGL"] - qt_env.AppendENVPath('PATH', os.path.join(qt_env['QTDIR'], "bin")) -else: - qt_install_prefix = subprocess.check_output(['qmake', '-query', 'QT_INSTALL_PREFIX'], encoding='utf8').strip() - qt_install_headers = subprocess.check_output(['qmake', '-query', 'QT_INSTALL_HEADERS'], encoding='utf8').strip() - - qt_env['QTDIR'] = qt_install_prefix - qt_dirs = [ - f"{qt_install_headers}", - ] - - qt_gui_path = os.path.join(qt_install_headers, "QtGui") - qt_gui_dirs = [d for d in os.listdir(qt_gui_path) if os.path.isdir(os.path.join(qt_gui_path, d))] - qt_dirs += [f"{qt_install_headers}/QtGui/{qt_gui_dirs[0]}/QtGui", ] if qt_gui_dirs else [] - qt_dirs += [f"{qt_install_headers}/Qt{m}" for m in qt_modules] - - qt_libs = [f"Qt5{m}" for m in qt_modules] - if arch == "larch64": - qt_libs += ["GLESv2", "wayland-client"] - qt_env.PrependENVPath('PATH', Dir("#third_party/qt5/larch64/bin/").abspath) - elif arch != "Darwin": - qt_libs += ["GL"] -qt_env['QT3DIR'] = qt_env['QTDIR'] - -# compatibility for older SCons versions -try: - qt_env.Tool('qt3') -except SCons.Errors.UserError: - qt_env.Tool('qt') - -qt_env['CPPPATH'] += qt_dirs + ["#third_party/qrcode"] -qt_flags = [ - "-D_REENTRANT", - "-DQT_NO_DEBUG", - "-DQT_WIDGETS_LIB", - "-DQT_GUI_LIB", - "-DQT_CORE_LIB", - "-DQT_MESSAGELOGCONTEXT", -] -qt_env['CXXFLAGS'] += qt_flags -qt_env['LIBPATH'] += ['#selfdrive/ui', ] -qt_env['LIBS'] = qt_libs - -if GetOption("clazy"): - checks = [ - "level0", - "level1", - "no-range-loop", - "no-non-pod-global-static", - ] - qt_env['CXX'] = 'clazy' - qt_env['ENV']['CLAZY_IGNORE_DIRS'] = qt_dirs[0] - qt_env['ENV']['CLAZY_CHECKS'] = ','.join(checks) - -Export('env', 'qt_env', 'arch', 'real_arch') +# Setup cache dir +cache_dir = '/data/scons_cache' if arch == "larch64" else '/tmp/scons_cache' +cache_size_limit = 4e9 if "CI" in os.environ else 2e9 +CacheDir(cache_dir) +Clean(["."], cache_dir) + +def prune_cache_dir(target=None, source=None, env=None): + cache_files = sorted((os.path.join(root, f) for root, _, files in os.walk(cache_dir) for f in files), key=os.path.getmtime) + cache_size = sum(os.path.getsize(f) for f in cache_files) + for f in cache_files: + if cache_size < cache_size_limit: + break + cache_size -= os.path.getsize(f) + os.unlink(f) + +# ********** start building stuff ********** # Build common module SConscript(['common/SConscript']) -Import('_common', '_gpucommon') - +Import('_common') common = [_common, 'json11', 'zmq'] -gpucommon = [_gpucommon] - -Export('common', 'gpucommon') +Export('common') # Build messaging (cereal + msgq + socketmaster + their dependencies) # Enable swaglog include in submodules env_swaglog = env.Clone() env_swaglog['CXXFLAGS'].append('-DSWAGLOG="\\"common/swaglog.h\\""') SConscript(['msgq_repo/SConscript'], exports={'env': env_swaglog}) -SConscript(['opendbc/can/SConscript'], exports={'env': env_swaglog}) SConscript(['cereal/SConscript']) Import('socketmaster', 'msgq') -messaging = [socketmaster, msgq, 'zmq', 'capnp', 'kj',] +messaging = [socketmaster, msgq, 'capnp', 'kj',] Export('messaging') # Build other submodules SConscript(['panda/SConscript']) +# Tesla radar DBCs are generated, not in git. TICI/device scons defaults +# extras=False (--minimal), so this cannot live only behind extras. +# extras still builds libsafety.so for pytest; do not enable extras on TICI. +opendbc_generated_dbcs = env.Command( + target=[ + File('#opendbc_repo/opendbc/dbc/tesla_radar_bosch_generated.dbc'), + File('#opendbc_repo/opendbc/dbc/tesla_radar_continental_generated.dbc'), + ], + source=[ + File('#opendbc_repo/opendbc/dbc/generator/generator.py'), + File('#opendbc_repo/opendbc/dbc/generator/tesla/tesla_radar_bosch.py'), + File('#opendbc_repo/opendbc/dbc/generator/tesla/tesla_radar_continental.py'), + File('#opendbc_repo/opendbc/dbc/generator/tesla/_radar_common.py'), + ], + action='python3 ${SOURCES[0]}', +) +env.Alias('opendbc_generated_dbcs', opendbc_generated_dbcs) + +if GetOption('extras'): + env.Command( + target=[ + File('#opendbc_repo/opendbc/safety/tests/libsafety/libsafety.so'), + ], + source=[ + File('#opendbc_repo/SConstruct'), + File('#opendbc_repo/opendbc/safety/tests/libsafety/safety.c'), + ] + list(opendbc_generated_dbcs), + action='scons -C opendbc_repo', + ) + # Build rednose library SConscript(['rednose/SConscript']) # Build system services SConscript([ - 'system/proclogd/SConscript', - 'system/ubloxd/SConscript', 'system/loggerd/SConscript', ]) -if arch != "Darwin": - SConscript([ - 'system/sensord/SConscript', - 'system/logcatd/SConscript', - ]) if arch == "larch64": SConscript(['system/camerad/SConscript']) -# Build openpilot -SConscript(['third_party/SConscript']) - -SConscript(['selfdrive/SConscript']) +# Build selfdrive +SConscript([ + 'selfdrive/pandad/SConscript', + 'selfdrive/controls/lib/lateral_mpc_lib/SConscript', + 'selfdrive/controls/lib/longitudinal_mpc_lib/SConscript', + 'selfdrive/locationd/SConscript', + 'selfdrive/modeld/SConscript', + 'selfdrive/ui/SConscript', +]) -if Dir('#tools/cabana/').exists() and GetOption('extras'): - SConscript(['tools/replay/SConscript']) - if arch != "larch64": - SConscript(['tools/cabana/SConscript']) +# Build desktop-only tools +if GetOption('extras') and arch != "larch64": + SConscript([ + 'tools/replay/SConscript', + 'tools/cabana/SConscript', + ]) + # jotpluggler needs get_generated_dbcs from a newer opendbc than NAP's + # Pre-AP submodule. Skip until that API exists in opendbc_repo. + try: + from opendbc import get_generated_dbcs # noqa: F401 + except ImportError: + get_generated_dbcs = None + if get_generated_dbcs is not None: + SConscript(['tools/jotpluggler/SConscript']) + + +env.CompilationDatabase('compile_commands.json') + +# progress output +def count_scons_nodes(nodes): + seen = set() + stack = list(nodes) + + while stack: + node = stack.pop().disambiguate() + if node in seen: + continue + seen.add(node) + executor = node.get_executor() + if executor is not None: + stack += executor.get_all_prerequisites() + executor.get_all_children() + + return len(seen) + +progress_interval = 5 +progress_count = 0 +progress_total = max(1, count_scons_nodes(env.arg2nodes(BUILD_TARGETS or [Dir('.')], env.fs.Entry))) -external_sconscript = GetOption('external_sconscript') -if external_sconscript: - SConscript([external_sconscript]) +def progress_function(node): + global progress_count + if progress_count >= progress_total: + return + progress_count = min(progress_count + progress_interval, progress_total) + progress = round(100. * progress_count / progress_total, 1) + sys.stderr.write("\rBuilding: %5.1f%%" % progress if sys.stderr.isatty() else "progress: %.1f\n" % progress) + if progress == 100. and sys.stderr.isatty(): + sys.stderr.write("\n") + sys.stderr.flush() + +Progress(progress_function, interval=progress_interval) +AddPostAction(BUILD_TARGETS or [Dir('.')], prune_cache_dir) diff --git a/cereal/README.md b/cereal/README.md index ad940facdceaa6..45e859c09ca4a6 100644 --- a/cereal/README.md +++ b/cereal/README.md @@ -29,6 +29,50 @@ then means breaking backwards-compatibility with all old logs of your fork. So w [custom.capnp](custom.capnp) that we will leave empty in mainline cereal/openpilot. **If you only modify those, you can ensure your fork will remain backwards-compatible with all versions of mainline openpilot and your fork.** +An example of compatible changes: +```diff +diff --git a/cereal/custom.capnp b/cereal/custom.capnp +index 3348e859e..3365c7b98 100644 +--- a/cereal/custom.capnp ++++ b/cereal/custom.capnp +@@ -10,7 +10,11 @@ $Cxx.namespace("cereal"); + # DO rename the structs + # DON'T change the identifier (e.g. @0x81c2f05a394cf4af) + +-struct CustomReserved0 @0x81c2f05a394cf4af { ++struct SteeringInfo @0x81c2f05a394cf4af { ++ active @0 :Bool; ++ steeringAngleDeg @1 :Float32; ++ steeringRateDeg @2 :Float32; ++ steeringAccelDeg @3 :Float32; + } + + struct CustomReserved1 @0xaedffd8f31e7b55d { +diff --git a/cereal/log.capnp b/cereal/log.capnp +index 1209f3fd9..b189f58b6 100644 +--- a/cereal/log.capnp ++++ b/cereal/log.capnp +@@ -2558,14 +2558,14 @@ struct Event { + + # DO change the name of the field + # DON'T change anything after the "@" +- customReservedRawData0 @124 :Data; ++ rawCanData @124 :Data; + customReservedRawData1 @125 :Data; + customReservedRawData2 @126 :Data; + + # DO change the name of the field and struct + # DON'T change the ID (e.g. @107) + # DON'T change which struct it points to +- customReserved0 @107 :Custom.CustomReserved0; ++ steeringInfo @107 :Custom.SteeringInfo; + customReserved1 @108 :Custom.CustomReserved1; + customReserved2 @109 :Custom.CustomReserved2; + customReserved3 @110 :Custom.CustomReserved3; +``` + +--- + Example --- ```python diff --git a/cereal/SConscript b/cereal/SConscript index a58a9490ce6488..de7ca0d7214ae1 100644 --- a/cereal/SConscript +++ b/cereal/SConscript @@ -4,7 +4,7 @@ cereal_dir = Dir('.') gen_dir = Dir('gen') # Build cereal -schema_files = ['log.capnp', 'car.capnp', 'legacy.capnp', 'custom.capnp'] +schema_files = ['log.capnp', 'car.capnp', 'deprecated.capnp', 'custom.capnp'] env.Command([f'gen/cpp/{s}.c++' for s in schema_files] + [f'gen/cpp/{s}.h' for s in schema_files], schema_files, f"capnpc --src-prefix={cereal_dir.path} $SOURCES -o c++:{gen_dir.path}/cpp/") @@ -13,7 +13,7 @@ cereal = env.Library('cereal', [f'gen/cpp/{s}.c++' for s in schema_files]) # Build messaging services_h = env.Command(['services.h'], ['services.py'], 'python3 ' + cereal_dir.path + '/services.py > $TARGET') -env.Program('messaging/bridge', ['messaging/bridge.cc', 'messaging/msgq_to_zmq.cc'], LIBS=[msgq, common, 'pthread']) +env.Program('messaging/bridge', ['messaging/bridge.cc', 'messaging/msgq_to_zmq.cc', 'messaging/bridge_zmq.cc'], LIBS=[msgq, common, 'pthread']) socketmaster = env.Library('socketmaster', ['messaging/socketmaster.cc']) diff --git a/cereal/__init__.py b/cereal/__init__.py index 89c5cf38e390e7..93f4d772276d57 100644 --- a/cereal/__init__.py +++ b/cereal/__init__.py @@ -1,9 +1,11 @@ import os import capnp +from importlib.resources import as_file, files -CEREAL_PATH = os.path.dirname(os.path.abspath(__file__)) capnp.remove_import_hook() -log = capnp.load(os.path.join(CEREAL_PATH, "log.capnp")) -car = capnp.load(os.path.join(CEREAL_PATH, "car.capnp")) -custom = capnp.load(os.path.join(CEREAL_PATH, "custom.capnp")) +with as_file(files("cereal")) as fspath: + CEREAL_PATH = fspath.as_posix() + log = capnp.load(os.path.join(CEREAL_PATH, "log.capnp")) + car = capnp.load(os.path.join(CEREAL_PATH, "car.capnp")) + custom = capnp.load(os.path.join(CEREAL_PATH, "custom.capnp")) diff --git a/cereal/car.capnp b/cereal/car.capnp deleted file mode 100644 index 9f72e31637b249..00000000000000 --- a/cereal/car.capnp +++ /dev/null @@ -1,715 +0,0 @@ -using Cxx = import "./include/c++.capnp"; -$Cxx.namespace("cereal"); - -@0x8e2af1e708af8b8d; - -# ******* events causing controls state machine transition ******* - -# FIXME: OnroadEvent shouldn't be in car.capnp, but can't immediately -# move due to being referenced by structs in this file -struct OnroadEvent @0x9b1657f34caf3ad3 { - name @0 :EventName; - - # event types - enable @1 :Bool; - noEntry @2 :Bool; - warning @3 :Bool; # alerts presented only when enabled or soft disabling - userDisable @4 :Bool; - softDisable @5 :Bool; - immediateDisable @6 :Bool; - preEnable @7 :Bool; - permanent @8 :Bool; # alerts presented regardless of openpilot state - overrideLateral @10 :Bool; - overrideLongitudinal @9 :Bool; - - enum EventName @0xbaa8c5d505f727de { - canError @0; - steerUnavailable @1; - wrongGear @4; - doorOpen @5; - seatbeltNotLatched @6; - espDisabled @7; - wrongCarMode @8; - steerTempUnavailable @9; - reverseGear @10; - buttonCancel @11; - buttonEnable @12; - pedalPressed @13; # exits active state - preEnableStandstill @73; # added during pre-enable state with brake - gasPressedOverride @108; # added when user is pressing gas with no disengage on gas - steerOverride @114; - cruiseDisabled @14; - speedTooLow @17; - outOfSpace @18; - overheat @19; - calibrationIncomplete @20; - calibrationInvalid @21; - calibrationRecalibrating @117; - controlsMismatch @22; - pcmEnable @23; - pcmDisable @24; - radarFault @26; - brakeHold @28; - parkBrake @29; - manualRestart @30; - lowSpeedLockout @31; - joystickDebug @34; - steerTempUnavailableSilent @35; - resumeRequired @36; - preDriverDistracted @37; - promptDriverDistracted @38; - driverDistracted @39; - preDriverUnresponsive @43; - promptDriverUnresponsive @44; - driverUnresponsive @45; - belowSteerSpeed @46; - lowBattery @48; - accFaulted @51; - sensorDataInvalid @52; - commIssue @53; - commIssueAvgFreq @109; - tooDistracted @54; - posenetInvalid @55; - soundsUnavailable @56; - preLaneChangeLeft @57; - preLaneChangeRight @58; - laneChange @59; - lowMemory @63; - stockAeb @64; - ldw @65; - carUnrecognized @66; - invalidLkasSetting @69; - speedTooHigh @70; - laneChangeBlocked @71; - relayMalfunction @72; - stockFcw @74; - startup @75; - startupNoCar @76; - startupNoControl @77; - startupMaster @78; - startupNoFw @104; - fcw @79; - steerSaturated @80; - belowEngageSpeed @84; - noGps @85; - wrongCruiseMode @87; - modeldLagging @89; - deviceFalling @90; - fanMalfunction @91; - cameraMalfunction @92; - cameraFrameRate @110; - processNotRunning @95; - dashcamMode @96; - controlsInitializing @98; - usbError @99; - roadCameraError @100; - driverCameraError @101; - wideRoadCameraError @102; - highCpuUsage @105; - cruiseMismatch @106; - lkasDisabled @107; - canBusMissing @111; - controlsdLagging @112; - resumeBlocked @113; - steerTimeLimit @115; - vehicleSensorsInvalid @116; - locationdTemporaryError @103; - locationdPermanentError @118; - paramsdTemporaryError @50; - paramsdPermanentError @119; - actuatorsApiUnavailable @120; - espActive @121; - personalityChanged @122; - - radarCanErrorDEPRECATED @15; - communityFeatureDisallowedDEPRECATED @62; - radarCommIssueDEPRECATED @67; - driverMonitorLowAccDEPRECATED @68; - gasUnavailableDEPRECATED @3; - dataNeededDEPRECATED @16; - modelCommIssueDEPRECATED @27; - ipasOverrideDEPRECATED @33; - geofenceDEPRECATED @40; - driverMonitorOnDEPRECATED @41; - driverMonitorOffDEPRECATED @42; - calibrationProgressDEPRECATED @47; - invalidGiraffeHondaDEPRECATED @49; - invalidGiraffeToyotaDEPRECATED @60; - internetConnectivityNeededDEPRECATED @61; - whitePandaUnsupportedDEPRECATED @81; - commIssueWarningDEPRECATED @83; - focusRecoverActiveDEPRECATED @86; - neosUpdateRequiredDEPRECATED @88; - modelLagWarningDEPRECATED @93; - startupOneplusDEPRECATED @82; - startupFuzzyFingerprintDEPRECATED @97; - noTargetDEPRECATED @25; - brakeUnavailableDEPRECATED @2; - plannerErrorDEPRECATED @32; - gpsMalfunctionDEPRECATED @94; - } -} - -# ******* main car state @ 100hz ******* -# all speeds in m/s - -struct CarState { - events @13 :List(OnroadEvent); - - # CAN health - canValid @26 :Bool; # invalid counter/checksums - canTimeout @40 :Bool; # CAN bus dropped out - canErrorCounter @48 :UInt32; - - # car speed - vEgo @1 :Float32; # best estimate of speed - aEgo @16 :Float32; # best estimate of aCAN cceleration - vEgoRaw @17 :Float32; # unfiltered speed from wheel speed sensors - vEgoCluster @44 :Float32; # best estimate of speed shown on car's instrument cluster, used for UI - - vCruise @53 :Float32; # actual set speed - vCruiseCluster @54 :Float32; # set speed to display in the UI - - yawRate @22 :Float32; # best estimate of yaw rate - standstill @18 :Bool; - wheelSpeeds @2 :WheelSpeeds; - - # gas pedal, 0.0-1.0 - gas @3 :Float32; # this is user pedal only - gasPressed @4 :Bool; # this is user pedal only - - engineRpm @46 :Float32; - - # brake pedal, 0.0-1.0 - brake @5 :Float32; # this is user pedal only - brakePressed @6 :Bool; # this is user pedal only - regenBraking @45 :Bool; # this is user pedal only - parkingBrake @39 :Bool; - brakeHoldActive @38 :Bool; - - # steering wheel - steeringAngleDeg @7 :Float32; - steeringAngleOffsetDeg @37 :Float32; # Offset betweens sensors in case there multiple - steeringRateDeg @15 :Float32; - steeringTorque @8 :Float32; # TODO: standardize units - steeringTorqueEps @27 :Float32; # TODO: standardize units - steeringPressed @9 :Bool; # if the user is using the steering wheel - steerFaultTemporary @35 :Bool; # temporary EPS fault - steerFaultPermanent @36 :Bool; # permanent EPS fault - stockAeb @30 :Bool; - stockFcw @31 :Bool; - espDisabled @32 :Bool; - accFaulted @42 :Bool; - carFaultedNonCritical @47 :Bool; # some ECU is faulted, but car remains controllable - espActive @51 :Bool; - vehicleSensorsInvalid @52 :Bool; # invalid steering angle readings, etc. - - # cruise state - cruiseState @10 :CruiseState; - - # gear - gearShifter @14 :GearShifter; - - # button presses - buttonEvents @11 :List(ButtonEvent); - leftBlinker @20 :Bool; - rightBlinker @21 :Bool; - genericToggle @23 :Bool; - - # lock info - doorOpen @24 :Bool; - seatbeltUnlatched @25 :Bool; - - # clutch (manual transmission only) - clutchPressed @28 :Bool; - - # blindspot sensors - leftBlindspot @33 :Bool; # Is there something blocking the left lane change - rightBlindspot @34 :Bool; # Is there something blocking the right lane change - - fuelGauge @41 :Float32; # battery or fuel tank level from 0.0 to 1.0 - charging @43 :Bool; - - # process meta - cumLagMs @50 :Float32; - - struct WheelSpeeds { - # optional wheel speeds - fl @0 :Float32; - fr @1 :Float32; - rl @2 :Float32; - rr @3 :Float32; - } - - struct CruiseState { - enabled @0 :Bool; - speed @1 :Float32; - speedCluster @6 :Float32; # Set speed as shown on instrument cluster - available @2 :Bool; - speedOffset @3 :Float32; - standstill @4 :Bool; - nonAdaptive @5 :Bool; - } - - enum GearShifter { - unknown @0; - park @1; - drive @2; - neutral @3; - reverse @4; - sport @5; - low @6; - brake @7; - eco @8; - manumatic @9; - } - - # send on change - struct ButtonEvent { - pressed @0 :Bool; - type @1 :Type; - - enum Type { - unknown @0; - leftBlinker @1; - rightBlinker @2; - accelCruise @3; - decelCruise @4; - cancel @5; - altButton1 @6; - altButton2 @7; - altButton3 @8; - setCruise @9; - resumeCruise @10; - gapAdjustCruise @11; - } - } - - # deprecated - errorsDEPRECATED @0 :List(OnroadEvent.EventName); - brakeLightsDEPRECATED @19 :Bool; - steeringRateLimitedDEPRECATED @29 :Bool; - canMonoTimesDEPRECATED @12: List(UInt64); - canRcvTimeoutDEPRECATED @49 :Bool; -} - -# ******* radar state @ 20hz ******* - -struct RadarData @0x888ad6581cf0aacb { - errors @0 :List(Error); - points @1 :List(RadarPoint); - - enum Error { - canError @0; - fault @1; - wrongConfig @2; - } - - # similar to LiveTracks - # is one timestamp valid for all? I think so - struct RadarPoint { - trackId @0 :UInt64; # no trackId reuse - - # these 3 are the minimum required - dRel @1 :Float32; # m from the front bumper of the car - yRel @2 :Float32; # m - vRel @3 :Float32; # m/s - - # these are optional and valid if they are not NaN - aRel @4 :Float32; # m/s^2 - yvRel @5 :Float32; # m/s - - # some radars flag measurements VS estimates - measured @6 :Bool; - } - - # deprecated - canMonoTimesDEPRECATED @2 :List(UInt64); -} - -# ******* car controls @ 100hz ******* - -struct CarControl { - # must be true for any actuator commands to work - enabled @0 :Bool; - latActive @11: Bool; - longActive @12: Bool; - - # Actuator commands as computed by controlsd - actuators @6 :Actuators; - - # moved to CarOutput - actuatorsOutputDEPRECATED @10 :Actuators; - - leftBlinker @15: Bool; - rightBlinker @16: Bool; - - orientationNED @13 :List(Float32); - angularVelocity @14 :List(Float32); - - cruiseControl @4 :CruiseControl; - hudControl @5 :HUDControl; - - struct Actuators { - # range from 0.0 - 1.0 - gas @0: Float32; - brake @1: Float32; - # range from -1.0 - 1.0 - steer @2: Float32; - # value sent over can to the car - steerOutputCan @8: Float32; - steeringAngleDeg @3: Float32; - - curvature @7: Float32; - - speed @6: Float32; # m/s - accel @4: Float32; # m/s^2 - longControlState @5: LongControlState; - - enum LongControlState @0xe40f3a917d908282{ - off @0; - pid @1; - stopping @2; - starting @3; - } - } - - struct CruiseControl { - cancel @0: Bool; - resume @1: Bool; - override @4: Bool; - speedOverrideDEPRECATED @2: Float32; - accelOverrideDEPRECATED @3: Float32; - } - - struct HUDControl { - speedVisible @0: Bool; - setSpeed @1: Float32; - lanesVisible @2: Bool; - leadVisible @3: Bool; - visualAlert @4: VisualAlert; - audibleAlert @5: AudibleAlert; - rightLaneVisible @6: Bool; - leftLaneVisible @7: Bool; - rightLaneDepart @8: Bool; - leftLaneDepart @9: Bool; - leadDistanceBars @10: Int8; # 1-3: 1 is closest, 3 is farthest. some ports may utilize 2-4 bars instead - - enum VisualAlert { - # these are the choices from the Honda - # map as good as you can for your car - none @0; - fcw @1; - steerRequired @2; - brakePressed @3; - wrongGear @4; - seatbeltUnbuckled @5; - speedTooHigh @6; - ldw @7; - } - - enum AudibleAlert { - none @0; - - engage @1; - disengage @2; - refuse @3; - - warningSoft @4; - warningImmediate @5; - - prompt @6; - promptRepeat @7; - promptDistracted @8; - } - } - - gasDEPRECATED @1 :Float32; - brakeDEPRECATED @2 :Float32; - steeringTorqueDEPRECATED @3 :Float32; - activeDEPRECATED @7 :Bool; - rollDEPRECATED @8 :Float32; - pitchDEPRECATED @9 :Float32; -} - -struct CarOutput { - # Any car specific rate limits or quirks applied by - # the CarController are reflected in actuatorsOutput - # and matches what is sent to the car - actuatorsOutput @0 :CarControl.Actuators; -} - -# ****** car param ****** - -struct CarParams { - carName @0 :Text; - carFingerprint @1 :Text; - fuzzyFingerprint @55 :Bool; - - notCar @66 :Bool; # flag for non-car robotics platforms - - pcmCruise @3 :Bool; # is openpilot's state tied to the PCM's cruise state? - enableDsu @5 :Bool; # driving support unit - enableBsm @56 :Bool; # blind spot monitoring - flags @64 :UInt32; # flags for car specific quirks - experimentalLongitudinalAvailable @71 :Bool; - - minEnableSpeed @7 :Float32; - minSteerSpeed @8 :Float32; - safetyConfigs @62 :List(SafetyConfig); - alternativeExperience @65 :Int16; # panda flag for features like no disengage on gas - - # Car docs fields - maxLateralAccel @68 :Float32; - autoResumeSng @69 :Bool; # describes whether car can resume from a stop automatically - - # things about the car in the manual - mass @17 :Float32; # [kg] curb weight: all fluids no cargo - wheelbase @18 :Float32; # [m] distance from rear axle to front axle - centerToFront @19 :Float32; # [m] distance from center of mass to front axle - steerRatio @20 :Float32; # [] ratio of steering wheel angle to front wheel angle - steerRatioRear @21 :Float32; # [] ratio of steering wheel angle to rear wheel angle (usually 0) - - # things we can derive - rotationalInertia @22 :Float32; # [kg*m2] body rotational inertia - tireStiffnessFactor @72 :Float32; # scaling factor used in calculating tireStiffness[Front,Rear] - tireStiffnessFront @23 :Float32; # [N/rad] front tire coeff of stiff - tireStiffnessRear @24 :Float32; # [N/rad] rear tire coeff of stiff - - longitudinalTuning @25 :LongitudinalPIDTuning; - lateralParams @48 :LateralParams; - lateralTuning :union { - pid @26 :LateralPIDTuning; - indiDEPRECATED @27 :LateralINDITuning; - lqrDEPRECATED @40 :LateralLQRTuning; - torque @67 :LateralTorqueTuning; - } - - steerLimitAlert @28 :Bool; - steerLimitTimer @47 :Float32; # time before steerLimitAlert is issued - - vEgoStopping @29 :Float32; # Speed at which the car goes into stopping state - vEgoStarting @59 :Float32; # Speed at which the car goes into starting state - stoppingControl @31 :Bool; # Does the car allow full control even at lows speeds when stopping - steerControlType @34 :SteerControlType; - radarUnavailable @35 :Bool; # True when radar objects aren't visible on CAN or aren't parsed out - stopAccel @60 :Float32; # Required acceleration to keep vehicle stationary - stoppingDecelRate @52 :Float32; # m/s^2/s while trying to stop - startAccel @32 :Float32; # Required acceleration to get car moving - startingState @70 :Bool; # Does this car make use of special starting state - - steerActuatorDelay @36 :Float32; # Steering wheel actuator delay in seconds - longitudinalActuatorDelay @58 :Float32; # Gas/Brake actuator delay in seconds - openpilotLongitudinalControl @37 :Bool; # is openpilot doing the longitudinal control? - carVin @38 :Text; # VIN number queried during fingerprinting - dashcamOnly @41: Bool; - passive @73: Bool; # is openpilot in control? - transmissionType @43 :TransmissionType; - carFw @44 :List(CarFw); - - radarTimeStep @45: Float32 = 0.05; # time delta between radar updates, 20Hz is very standard - fingerprintSource @49: FingerprintSource; - networkLocation @50 :NetworkLocation; # Where Panda/C2 is integrated into the car's CAN network - - wheelSpeedFactor @63 :Float32; # Multiplier on wheels speeds to computer actual speeds - - struct SafetyConfig { - safetyModel @0 :SafetyModel; - safetyParam @3 :UInt16; - safetyParamDEPRECATED @1 :Int16; - safetyParam2DEPRECATED @2 :UInt32; - } - - struct LateralParams { - torqueBP @0 :List(Int32); - torqueV @1 :List(Int32); - } - - struct LateralPIDTuning { - kpBP @0 :List(Float32); - kpV @1 :List(Float32); - kiBP @2 :List(Float32); - kiV @3 :List(Float32); - kf @4 :Float32; - } - - struct LateralTorqueTuning { - useSteeringAngle @0 :Bool; - kp @1 :Float32; - ki @2 :Float32; - friction @3 :Float32; - kf @4 :Float32; - steeringAngleDeadzoneDeg @5 :Float32; - latAccelFactor @6 :Float32; - latAccelOffset @7 :Float32; - } - - struct LongitudinalPIDTuning { - kpBP @0 :List(Float32); - kpV @1 :List(Float32); - kiBP @2 :List(Float32); - kiV @3 :List(Float32); - kf @6 :Float32; - deadzoneBPDEPRECATED @4 :List(Float32); - deadzoneVDEPRECATED @5 :List(Float32); - } - - struct LateralINDITuning { - outerLoopGainBP @4 :List(Float32); - outerLoopGainV @5 :List(Float32); - innerLoopGainBP @6 :List(Float32); - innerLoopGainV @7 :List(Float32); - timeConstantBP @8 :List(Float32); - timeConstantV @9 :List(Float32); - actuatorEffectivenessBP @10 :List(Float32); - actuatorEffectivenessV @11 :List(Float32); - - outerLoopGainDEPRECATED @0 :Float32; - innerLoopGainDEPRECATED @1 :Float32; - timeConstantDEPRECATED @2 :Float32; - actuatorEffectivenessDEPRECATED @3 :Float32; - } - - struct LateralLQRTuning { - scale @0 :Float32; - ki @1 :Float32; - dcGain @2 :Float32; - - # State space system - a @3 :List(Float32); - b @4 :List(Float32); - c @5 :List(Float32); - - k @6 :List(Float32); # LQR gain - l @7 :List(Float32); # Kalman gain - } - - enum SafetyModel { - silent @0; - hondaNidec @1; - toyota @2; - elm327 @3; - gm @4; - hondaBoschGiraffe @5; - ford @6; - cadillac @7; - hyundai @8; - chrysler @9; - tesla @10; - subaru @11; - gmPassive @12; - mazda @13; - nissan @14; - volkswagen @15; - toyotaIpas @16; - allOutput @17; - gmAscm @18; - noOutput @19; # like silent but without silent CAN TXs - hondaBosch @20; - volkswagenPq @21; - subaruPreglobal @22; # pre-Global platform - hyundaiLegacy @23; - hyundaiCommunity @24; - volkswagenMlb @25; - hongqi @26; - body @27; - hyundaiCanfd @28; - volkswagenMqbEvo @29; - chryslerCusw @30; - psa @31; - } - - enum SteerControlType { - torque @0; - angle @1; - - curvatureDEPRECATED @2; - } - - enum TransmissionType { - unknown @0; - automatic @1; # Traditional auto, including DSG - manual @2; # True "stick shift" only - direct @3; # Electric vehicle or other direct drive - cvt @4; - } - - struct CarFw { - ecu @0 :Ecu; - fwVersion @1 :Data; - address @2 :UInt32; - subAddress @3 :UInt8; - responseAddress @4 :UInt32; - request @5 :List(Data); - brand @6 :Text; - bus @7 :UInt8; - logging @8 :Bool; - obdMultiplexing @9 :Bool; - } - - enum Ecu { - eps @0; - abs @1; - fwdRadar @2; - fwdCamera @3; - engine @4; - unknown @5; - transmission @8; # Transmission Control Module - hybrid @18; # hybrid control unit, e.g. Chrysler's HCP, Honda's IMA Control Unit, Toyota's hybrid control computer - srs @9; # airbag - gateway @10; # can gateway - hud @11; # heads up display - combinationMeter @12; # instrument cluster - electricBrakeBooster @15; - shiftByWire @16; - adas @19; - cornerRadar @21; - hvac @20; - parkingAdas @7; # parking assist system ECU, e.g. Toyota's IPAS, Hyundai's RSPA, etc. - epb @22; # electronic parking brake - telematics @23; - body @24; # body control module - - # Toyota only - dsu @6; - - # Honda only - vsa @13; # Vehicle Stability Assist - programmedFuelInjection @14; - - debug @17; - } - - enum FingerprintSource { - can @0; - fw @1; - fixed @2; - } - - enum NetworkLocation { - fwdCamera @0; # Standard/default integration at LKAS camera - gateway @1; # Integration at vehicle's CAN gateway - } - - enableGasInterceptorDEPRECATED @2 :Bool; - enableCameraDEPRECATED @4 :Bool; - enableApgsDEPRECATED @6 :Bool; - steerRateCostDEPRECATED @33 :Float32; - isPandaBlackDEPRECATED @39 :Bool; - hasStockCameraDEPRECATED @57 :Bool; - safetyParamDEPRECATED @10 :Int16; - safetyModelDEPRECATED @9 :SafetyModel; - safetyModelPassiveDEPRECATED @42 :SafetyModel = silent; - minSpeedCanDEPRECATED @51 :Float32; - communityFeatureDEPRECATED @46: Bool; - startingAccelRateDEPRECATED @53 :Float32; - steerMaxBPDEPRECATED @11 :List(Float32); - steerMaxVDEPRECATED @12 :List(Float32); - gasMaxBPDEPRECATED @13 :List(Float32); - gasMaxVDEPRECATED @14 :List(Float32); - brakeMaxBPDEPRECATED @15 :List(Float32); - brakeMaxVDEPRECATED @16 :List(Float32); - directAccelControlDEPRECATED @30 :Bool; - maxSteeringAngleDegDEPRECATED @54 :Float32; - longitudinalActuatorDelayLowerBoundDEPRECATEDDEPRECATED @61 :Float32; -} diff --git a/cereal/car.capnp b/cereal/car.capnp new file mode 120000 index 00000000000000..4bc7f89b1fb5f2 --- /dev/null +++ b/cereal/car.capnp @@ -0,0 +1 @@ +../opendbc_repo/opendbc/car/car.capnp \ No newline at end of file diff --git a/cereal/custom.capnp b/cereal/custom.capnp index 369222add8c622..4e1d8cd3127c9e 100644 --- a/cereal/custom.capnp +++ b/cereal/custom.capnp @@ -7,20 +7,166 @@ $Cxx.namespace("cereal"); # These structs are guaranteed to remain reserved and empty in mainline # cereal, so use these if you want custom events in your fork. -# you can rename the struct, but don't change the identifier -struct CustomReserved0 @0x81c2f05a394cf4af { +# DO rename the structs +# DON'T change the identifier (e.g. @0x81c2f05a394cf4af) + +# NAP live OSM speed-limit sample. SI units. Published by selfdrive.mapd. +struct LiveMapDataNAP @0x81c2f05a394cf4af { + speedLimit @0 :Float32; # m/s, 0 if unknown + speedLimitValid @1 :Bool; + nextSpeedLimit @2 :Float32; # m/s, 0 if unknown + nextSpeedLimitDistance @3 :Float32; # m + latitude @4 :Float64; + longitude @5 :Float64; + bearingDeg @6 :Float32; + roadName @7 :Text; + highway @8 :Text; + wayId @9 :UInt64; + source @10 :Text; # "osm" + dbLoaded @11 :Bool; + matchDistance @12 :Float32; # m, distance to matched way + onRoundabout @13 :Bool; + approachingRoundabout @14 :Bool; + roundaboutDistance @15 :Float32; # m to circulating way; 0 if on + roundaboutSpeedLimit @16 :Float32; # m/s, OSM maxspeed on the RB way + roundaboutWayId @17 :UInt64; } -struct CustomReserved1 @0xaedffd8f31e7b55d { +# NAP on-drive MUTCD camera speed-sign sample. Display/log only. mph in the field name. +struct LiveSpeedSignNAP @0xaedffd8f31e7b55d { + mph @0 :Int16; # posted mph, 0 if none + conf @1 :Float32; + valid @2 :Bool; # live detection including HUD hold + weightsMissing @3 :Bool; # ONNX failed to load; HUD shows NO WT, never a fake mph + detectPaused @4 :Bool; # HUD WAIT if set. Engaged detect leaves this false. } -struct CustomReserved2 @0xf35cc4560bbf6ec2 { +# NAP radar cone-line sample. Log only. Does not steer. +# lat*, wouldLimit, and wouldSteer are path-relative device y, +right +# (modelV2.position.y and PathObstacle y). radarState.yRel is +left; +# device y = -yRel. side is the real side of the lane and therefore +# has the opposite sign from lat: +1 left, -1 right. +# wouldSteer is the shift away from the line, capped at 0.4 m, for +# later evaluation. controlsd does not apply it. +struct ConeLineNAP @0xf35cc4560bbf6ec2 { + active @0 :Bool; + side @1 :Int8; # +1 left of the path, -1 right, 0 none + confidence @2 :Float32; + count @3 :UInt8; + latNear @4 :Float32; # path-relative y at ~15 m, +right + latMid @5 :Float32; # ~30 m, +right + latFar @6 :Float32; # ~45 m, +right + wouldLimit @7 :Float32; # m, +right; shift that would leave ~1 m of clearance + barrier @8 :Bool; # continuous guardrail / barrier, not a cone line + parked @9 :Bool; # short wide cluster rejected as a parked car + spanM @10 :Float32; + wouldSteer @11 :Float32; # m, +right; in-lane cone shift (corridor midpoint / away from one line), |v| <= 1.0 + # Oct 14 corridor: both sides tracked at once. + leftActive @12 :Bool; + leftClear @13 :Float32; # m from path centre to the nearest left post, 0 when none + rightActive @14 :Bool; + rightClear @15 :Float32; # m from path centre to the nearest right post, 0 when none + corridor @16 :Bool; # both sides active; wouldSteer aims at the midpoint + marginM @17 :Float32; # smallest clearance to a tracked line after wouldSteer + releasing @18 :Bool; # corridor ended; wouldSteer easing to 0 (applied while easing) } -struct CustomReserved3 @0xda96579883444c35 { +# NAP in-path / roadside obstacle sample. Log only, plus an animal/person +# chime. y is path-relative, +right (device frame; radarState.yRel is +left +# and y = -yRel). Vision fields are NaN until a radar trigger asks for a +# patch. brakeGate is a future hook and is not applied. +struct PathObstacleNAP @0xda96579883444c35 { + active @0 :Bool; + trackId @1 :UInt64; + range @2 :Float32; # m, camera frame + lateral @3 :Float32; # m, path-relative, +right + vRel @4 :Float32; # m/s, radar longitudinal relative + vLat @5 :Float32; # m/s, +right + radarConf @6 :Float32; # 0..1 + visionConf @7 :Float32; # 0..1, NaN if not evaluated + visionEvaluated @8 :Bool; + lightingScore @9 :Float32; # 0 poor .. 1 good + wRadar @10 :Float32; + wVision @11 :Float32; + fusedScore @12 :Float32; + agree @13 :Bool; # both confidences over their bars + rejectReason @14 :Text; + inPath @15 :Bool; + timeToReach @16 :Float32; # s, NaN if not closing + objectClass @17 :ObjectClass; + visionConfHuman @18 :Float32; + visionConfAnimal @19 :Float32; + visionConfObstacle @20 :Float32; + clusterCount @21 :UInt8; + spanM @22 :Float32; # lateral span of the cluster, m + timeToEnter @23 :Float32; # s, 0 if already in the path + entering @24 :Bool; + zone @25 :Zone; + brakeGate @26 :Bool; # log-only: agree + in path or entering, any class + chimed @27 :Bool; + chimeReason @28 :Text; + scanUs @29 :Float32; + visionUs @30 :Float32; + livelyScore @31 :Float32; # 0 still .. 1 moved in the last ~2 s + # Radar-stage fields forwarded to the camera helper. Additive. + y @32 :Float32; # device frame, +right + along @33 :Float32; # m/s ground speed along the road + radarClass @34 :ObjectClass; + memberIds @35 :List(UInt64); + laneProbMin @36 :Float32; # min(left, right) lane prob, for lighting + pathYStd3s @37 :Float32; # model y std near t=3 s + overBudget @38 :Bool; + heartbeat @39 :Bool; + # Night drive-over. Radard sets modelLeadAgree when a model or radar + # lead sits on this stationary in-lane return. driveOverReason is the + # chime-side suppression (light, no_solid, beyond_60) and is empty + # until the camera helper decides. Daytime lead matches stay quiet. + modelLeadAgree @40 :Bool; + driveOverReason @41 :Text; + + enum ObjectClass { + unknown @0; + human @1; + animal @2; + obstacle @3; + } + + enum Zone { + none @0; + inPath @1; + entering @2; + roadside @3; + } } -struct CustomReserved4 @0x80ae746ee2596b11 { +# Camera-helper result. Same type id as the old empty CustomReserved4. +# The chime reads this. radard does not. +struct PathObstacleVisionNAP @0x80ae746ee2596b11 { + trackId @0 :UInt64; + visionEvaluated @1 :Bool; + visionConf @2 :Float32; + visionConfHuman @3 :Float32; + visionConfAnimal @4 :Float32; + visionConfObstacle @5 :Float32; + lightingScore @6 :Float32; + wRadar @7 :Float32; + wVision @8 :Float32; + fusedScore @9 :Float32; + agree @10 :Bool; + objectClass @11 :PathObstacleNAP.ObjectClass; + zone @12 :PathObstacleNAP.Zone; + brakeGate @13 :Bool; + chimed @14 :Bool; + chimeReason @15 :Text; + livelyScore @16 :Float32; + visionUs @17 :Float32; + # Set when this attempt produced no score. Empty when a score was written. + # no_connection, no_frame, stale_frame, roi_out_of_frame, budget, model_error. + visionFailReason @18 :Text; + # Night drive-over suppression. Empty when the rule did not suppress. + # light: crop is headlights or taillights. no_solid: nothing solid in + # the crop and no model lead. beyond_60: farther than low-beam range. + driveOverReason @19 :Text; } struct CustomReserved5 @0xa5cd762cd951a455 { @@ -37,3 +183,33 @@ struct CustomReserved8 @0xf416ec09499d9d19 { struct CustomReserved9 @0xa1680744031fdb2d { } + +struct CustomReserved10 @0xcb9fd56c7057593a { +} + +struct CustomReserved11 @0xc2243c65e0340384 { +} + +struct CustomReserved12 @0x9ccdc8676701b412 { +} + +struct CustomReserved13 @0xcd96dafb67a082d0 { +} + +struct CustomReserved14 @0xb057204d7deadf3f { +} + +struct CustomReserved15 @0xbd443b539493bc68 { +} + +struct CustomReserved16 @0xfc6241ed8877b611 { +} + +struct CustomReserved17 @0xa30662f84033036c { +} + +struct CustomReserved18 @0xc86a3d38d13eb3ef { +} + +struct CustomReserved19 @0xa4f1eb3323f5f582 { +} diff --git a/cereal/deprecated.capnp b/cereal/deprecated.capnp new file mode 100644 index 00000000000000..45ce25c6827e27 --- /dev/null +++ b/cereal/deprecated.capnp @@ -0,0 +1,789 @@ +using Cxx = import "./include/c++.capnp"; +$Cxx.namespace("cereal"); + +@0x80ef1ec4889c2a63; + +# deprecated.capnp: a home for deprecated structs + +struct LogRotate @0x9811e1f38f62f2d1 { + segmentNum @0 :Int32; + path @1 :Text; +} + +struct LiveUI @0xc08240f996aefced { + rearViewCam @0 :Bool; + alertText1 @1 :Text; + alertText2 @2 :Text; + awarenessStatus @3 :Float32; +} + +struct UiLayoutState @0x88dcce08ad29dda0 { + activeApp @0 :App; + sidebarCollapsed @1 :Bool; + mapEnabled @2 :Bool; + mockEngaged @3 :Bool; + + enum App @0x9917470acf94d285 { + home @0; + music @1; + nav @2; + settings @3; + none @4; + } +} + +struct OrbslamCorrection @0x8afd33dc9b35e1aa { + correctionMonoTime @0 :UInt64; + prePositionECEF @1 :List(Float64); + postPositionECEF @2 :List(Float64); + prePoseQuatECEF @3 :List(Float32); + postPoseQuatECEF @4 :List(Float32); + numInliers @5 :UInt32; +} + +struct EthernetPacket @0xa99a9d5b33cf5859 { + pkt @0 :Data; + ts @1 :Float32; +} + +struct CellInfo @0xcff7566681c277ce { + timestamp @0 :UInt64; + repr @1 :Text; # android toString() for now +} + +struct WifiScan @0xd4df5a192382ba0b { + bssid @0 :Text; + ssid @1 :Text; + capabilities @2 :Text; + frequency @3 :Int32; + level @4 :Int32; + timestamp @5 :Int64; + + centerFreq0 @6 :Int32; + centerFreq1 @7 :Int32; + channelWidth @8 :ChannelWidth; + operatorFriendlyName @9 :Text; + venueName @10 :Text; + is80211mcResponder @11 :Bool; + passpoint @12 :Bool; + + distanceCm @13 :Int32; + distanceSdCm @14 :Int32; + + enum ChannelWidth @0xcb6a279f015f6b51 { + w20Mhz @0; + w40Mhz @1; + w80Mhz @2; + w160Mhz @3; + w80Plus80Mhz @4; + } +} + +struct LiveEventData @0x94b7baa90c5c321e { + name @0 :Text; + value @1 :Int32; +} + +struct ModelData @0xb8aad62cffef28a9 { + frameId @0 :UInt32; + frameAge @12 :UInt32; + frameDropPerc @13 :Float32; + timestampEof @9 :UInt64; + modelExecutionTime @14 :Float32; + gpuExecutionTime @16 :Float32; + rawPred @15 :Data; + + path @1 :PathData; + leftLane @2 :PathData; + rightLane @3 :PathData; + lead @4 :LeadData; + freePath @6 :List(Float32); + + settings @5 :ModelSettings; + leadFuture @7 :LeadData; + speed @8 :List(Float32); + meta @10 :MetaData; + longitudinal @11 :LongitudinalData; + + struct PathData @0x8817eeea389e9f08 { + points @0 :List(Float32); + prob @1 :Float32; + std @2 :Float32; + stds @3 :List(Float32); + poly @4 :List(Float32); + validLen @5 :Float32; + } + + struct LeadData @0xd1c9bef96d26fa91 { + dist @0 :Float32; + prob @1 :Float32; + std @2 :Float32; + relVel @3 :Float32; + relVelStd @4 :Float32; + relY @5 :Float32; + relYStd @6 :Float32; + relA @7 :Float32; + relAStd @8 :Float32; + } + + struct ModelSettings @0xa26e3710efd3e914 { + bigBoxX @0 :UInt16; + bigBoxY @1 :UInt16; + bigBoxWidth @2 :UInt16; + bigBoxHeight @3 :UInt16; + boxProjection @4 :List(Float32); + yuvCorrection @5 :List(Float32); + inputTransform @6 :List(Float32); + } + + struct MetaData @0x9744f25fb60f2bf8 { + engagedProb @0 :Float32; + desirePrediction @1 :List(Float32); + brakeDisengageProb @2 :Float32; + gasDisengageProb @3 :Float32; + steerOverrideProb @4 :Float32; + desireState @5 :List(Float32); + } + + struct LongitudinalData @0xf98f999c6a071122 { + distances @2 :List(Float32); + speeds @0 :List(Float32); + accelerations @1 :List(Float32); + } +} + +struct ECEFPoint @0xc25bbbd524983447 { + x @0 :Float64; + y @1 :Float64; + z @2 :Float64; +} + +struct ECEFPointDEPRECATED @0xe10e21168db0c7f7 { + x @0 :Float32; + y @1 :Float32; + z @2 :Float32; +} + +struct GPSPlannerPoints @0xab54c59699f8f9f3 { + curPosDEPRECATED @0 :ECEFPointDEPRECATED; + pointsDEPRECATED @1 :List(ECEFPointDEPRECATED); + curPos @6 :ECEFPoint; + points @7 :List(ECEFPoint); + valid @2 :Bool; + trackName @3 :Text; + speedLimit @4 :Float32; + accelTarget @5 :Float32; +} + +struct GPSPlannerPlan @0xf5ad1d90cdc1dd6b { + valid @0 :Bool; + poly @1 :List(Float32); + trackName @2 :Text; + speed @3 :Float32; + acceleration @4 :Float32; + pointsDEPRECATED @5 :List(ECEFPointDEPRECATED); + points @6 :List(ECEFPoint); + xLookahead @7 :Float32; +} + +struct UiNavigationEvent @0x90c8426c3eaddd3b { + type @0: Type; + status @1: Status; + distanceTo @2: Float32; + endRoadPointDEPRECATED @3: ECEFPointDEPRECATED; + endRoadPoint @4: ECEFPoint; + + enum Type @0xe8db07dcf8fcea05 { + none @0; + laneChangeLeft @1; + laneChangeRight @2; + mergeLeft @3; + mergeRight @4; + turnLeft @5; + turnRight @6; + } + + enum Status @0xb9aa88c75ef99a1f { + none @0; + passive @1; + approaching @2; + active @3; + } +} + +struct LiveLocationData @0xb99b2bc7a57e8128 { + status @0 :UInt8; + + # 3D fix + lat @1 :Float64; + lon @2 :Float64; + alt @3 :Float32; # m + + # speed + speed @4 :Float32; # m/s + + # NED velocity components + vNED @5 :List(Float32); + + # roll, pitch, heading (x,y,z) + roll @6 :Float32; # WRT to center of earth? + pitch @7 :Float32; # WRT to center of earth? + heading @8 :Float32; # WRT to north? + + # what are these? + wanderAngle @9 :Float32; + trackAngle @10 :Float32; + + # car frame -- https://upload.wikimedia.org/wikipedia/commons/f/f5/RPY_angles_of_cars.png + + # gyro, in car frame, deg/s + gyro @11 :List(Float32); + + # accel, in car frame, m/s^2 + accel @12 :List(Float32); + + accuracy @13 :Accuracy; + + source @14 :SensorSource; + # if we are fixing a location in the past + fixMonoTime @15 :UInt64; + + gpsWeek @16 :Int32; + timeOfWeek @17 :Float64; + + positionECEF @18 :List(Float64); + poseQuatECEF @19 :List(Float32); + pitchCalibration @20 :Float32; + yawCalibration @21 :Float32; + imuFrame @22 :List(Float32); + + struct Accuracy @0x943dc4625473b03f { + pNEDError @0 :List(Float32); + vNEDError @1 :List(Float32); + rollError @2 :Float32; + pitchError @3 :Float32; + headingError @4 :Float32; + ellipsoidSemiMajorError @5 :Float32; + ellipsoidSemiMinorError @6 :Float32; + ellipsoidOrientationError @7 :Float32; + } + + enum SensorSource @0xc871d3cc252af657 { + applanix @0; + kalman @1; + orbslam @2; + timing @3; + dummy @4; + } +} + +struct OrbOdometry @0xd7700859ed1f5b76 { + # timing first + startMonoTime @0 :UInt64; + endMonoTime @1 :UInt64; + + # fundamental matrix and error + f @2: List(Float64); + err @3: Float64; + + # number of inlier points + inliers @4: Int32; + + # for debug only + # indexed by endMonoTime features + # value is startMonoTime feature match + # -1 if no match + matches @5: List(Int16); +} + +struct OrbFeatures @0xcd60164a8a0159ef { + timestampEof @0 :UInt64; + # transposed arrays of normalized image coordinates + # len(xs) == len(ys) == len(descriptors) * 32 + xs @1 :List(Float32); + ys @2 :List(Float32); + descriptors @3 :Data; + octaves @4 :List(Int8); + + # match index to last OrbFeatures + # -1 if no match + timestampLastEof @5 :UInt64; + matches @6: List(Int16); +} + +struct OrbFeaturesSummary @0xd500d30c5803fa4f { + timestampEof @0 :UInt64; + timestampLastEof @1 :UInt64; + + featureCount @2 :UInt16; + matchCount @3 :UInt16; + computeNs @4 :UInt64; +} + +struct OrbKeyFrame @0xc8233c0345e27e24 { + # this is a globally unique id for the KeyFrame + id @0: UInt64; + + # this is the location of the KeyFrame + pos @1: ECEFPoint; + + # these are the features in the world + # len(dpos) == len(descriptors) * 32 + dpos @2 :List(ECEFPoint); + descriptors @3 :Data; +} + +struct KalmanOdometry @0x92e21bb7ea38793a { + trans @0 :List(Float32); # m/s in device frame + rot @1 :List(Float32); # rad/s in device frame + transStd @2 :List(Float32); # std m/s in device frame + rotStd @3 :List(Float32); # std rad/s in device frame +} + +struct OrbObservation @0x9b326d4e436afec7 { + observationMonoTime @0 :UInt64; + normalizedCoordinates @1 :List(Float32); + locationECEF @2 :List(Float64); + matchDistance @3: UInt32; +} + +struct CalibrationFeatures @0x8fdfadb254ea867a { + frameId @0 :UInt32; + + p0 @1 :List(Float32); + p1 @2 :List(Float32); + status @3 :List(Int8); +} + +struct NavStatus @0xbd8822120928120c { + isNavigating @0 :Bool; + currentAddress @1 :Address; + + struct Address @0xce7cd672cacc7814 { + title @0 :Text; + lat @1 :Float64; + lng @2 :Float64; + house @3 :Text; + address @4 :Text; + street @5 :Text; + city @6 :Text; + state @7 :Text; + country @8 :Text; + } +} + +struct NavUpdate @0xdb98be6565516acb { + isNavigating @0 :Bool; + curSegment @1 :Int32; + segments @2 :List(Segment); + + struct LatLng @0x9eaef9187cadbb9b { + lat @0 :Float64; + lng @1 :Float64; + } + + struct Segment @0xa5b39b4fc4d7da3f { + from @0 :LatLng; + to @1 :LatLng; + updateTime @2 :Int32; + distance @3 :Int32; + crossTime @4 :Int32; + exitNo @5 :Int32; + instruction @6 :Instruction; + + parts @7 :List(LatLng); + + enum Instruction @0xc5417a637451246f { + turnLeft @0; + turnRight @1; + keepLeft @2; + keepRight @3; + straight @4; + roundaboutExitNumber @5; + roundaboutExit @6; + roundaboutTurnLeft @7; + unkn8 @8; + roundaboutStraight @9; + unkn10 @10; + roundaboutTurnRight @11; + unkn12 @12; + roundaboutUturn @13; + unkn14 @14; + arrive @15; + exitLeft @16; + exitRight @17; + unkn18 @18; + uturn @19; + # ... + } + } +} + +struct TrafficEvent @0xacfa74a094e62626 { + type @0 :Type; + distance @1 :Float32; + action @2 :Action; + resuming @3 :Bool; + + enum Type @0xd85d75253435bf4b { + stopSign @0; + lightRed @1; + lightYellow @2; + lightGreen @3; + stopLight @4; + } + + enum Action @0xa6f6ce72165ccb49 { + none @0; + yield @1; + stop @2; + resumeReady @3; + } + +} + + +struct AndroidGnss @0xdfdf30d03fc485bd { + union { + measurements @0 :Measurements; + navigationMessage @1 :NavigationMessage; + } + + struct Measurements @0xa20710d4f428d6cd { + clock @0 :Clock; + measurements @1 :List(Measurement); + + struct Clock @0xa0e27b453a38f450 { + timeNanos @0 :Int64; + hardwareClockDiscontinuityCount @1 :Int32; + + hasTimeUncertaintyNanos @2 :Bool; + timeUncertaintyNanos @3 :Float64; + + hasLeapSecond @4 :Bool; + leapSecond @5 :Int32; + + hasFullBiasNanos @6 :Bool; + fullBiasNanos @7 :Int64; + + hasBiasNanos @8 :Bool; + biasNanos @9 :Float64; + + hasBiasUncertaintyNanos @10 :Bool; + biasUncertaintyNanos @11 :Float64; + + hasDriftNanosPerSecond @12 :Bool; + driftNanosPerSecond @13 :Float64; + + hasDriftUncertaintyNanosPerSecond @14 :Bool; + driftUncertaintyNanosPerSecond @15 :Float64; + } + + struct Measurement @0xd949bf717d77614d { + svId @0 :Int32; + constellation @1 :Constellation; + + timeOffsetNanos @2 :Float64; + state @3 :Int32; + receivedSvTimeNanos @4 :Int64; + receivedSvTimeUncertaintyNanos @5 :Int64; + cn0DbHz @6 :Float64; + pseudorangeRateMetersPerSecond @7 :Float64; + pseudorangeRateUncertaintyMetersPerSecond @8 :Float64; + accumulatedDeltaRangeState @9 :Int32; + accumulatedDeltaRangeMeters @10 :Float64; + accumulatedDeltaRangeUncertaintyMeters @11 :Float64; + + hasCarrierFrequencyHz @12 :Bool; + carrierFrequencyHz @13 :Float32; + hasCarrierCycles @14 :Bool; + carrierCycles @15 :Int64; + hasCarrierPhase @16 :Bool; + carrierPhase @17 :Float64; + hasCarrierPhaseUncertainty @18 :Bool; + carrierPhaseUncertainty @19 :Float64; + hasSnrInDb @20 :Bool; + snrInDb @21 :Float64; + + multipathIndicator @22 :MultipathIndicator; + + enum Constellation @0x9ef1f3ff0deb5ffb { + unknown @0; + gps @1; + sbas @2; + glonass @3; + qzss @4; + beidou @5; + galileo @6; + } + + enum State @0xcbb9490adce12d72 { + unknown @0; + codeLock @1; + bitSync @2; + subframeSync @3; + towDecoded @4; + msecAmbiguous @5; + symbolSync @6; + gloStringSync @7; + gloTodDecoded @8; + bdsD2BitSync @9; + bdsD2SubframeSync @10; + galE1bcCodeLock @11; + galE1c2ndCodeLock @12; + galE1bPageSync @13; + sbasSync @14; + } + + enum MultipathIndicator @0xc04e7b6231d4caa8 { + unknown @0; + detected @1; + notDetected @2; + } + } + } + + struct NavigationMessage @0xe2517b083095fd4e { + type @0 :Int32; + svId @1 :Int32; + messageId @2 :Int32; + submessageId @3 :Int32; + data @4 :Data; + status @5 :Status; + + enum Status @0xec1ff7996b35366f { + unknown @0; + parityPassed @1; + parityRebuilt @2; + } + } +} + +struct LidarPts @0xe3d6685d4e9d8f7a { + r @0 :List(UInt16); # uint16 m*500.0 + theta @1 :List(UInt16); # uint16 deg*100.0 + reflect @2 :List(UInt8); # uint8 0-255 + + # For storing out of file. + idx @3 :UInt64; + + # For storing in file + pkt @4 :Data; +} + +struct LiveTracksDEPRECATED @0xb16f60103159415a { + trackId @0 :Int32; + dRel @1 :Float32; + yRel @2 :Float32; + vRel @3 :Float32; + aRel @4 :Float32; + timeStamp @5 :Float32; + status @6 :Float32; + currentTime @7 :Float32; + stationary @8 :Bool; + oncoming @9 :Bool; +} + +struct LiveMpcData @0x92a5e332a85f32a0 { + x @0 :List(Float32); + y @1 :List(Float32); + psi @2 :List(Float32); + curvature @3 :List(Float32); + qpIterations @4 :UInt32; + calculationTime @5 :UInt64; + cost @6 :Float64; +} + +struct LiveLongitudinalMpcData @0xe7e17c434f865ae2 { + xEgo @0 :List(Float32); + vEgo @1 :List(Float32); + aEgo @2 :List(Float32); + xLead @3 :List(Float32); + vLead @4 :List(Float32); + aLead @5 :List(Float32); + aLeadTau @6 :Float32; # lead accel time constant + qpIterations @7 :UInt32; + mpcId @8 :UInt32; + calculationTime @9 :UInt64; + cost @10 :Float64; +} + +struct DriverStateDEPRECATED @0xb83c6cc593ed0a00 { + frameId @0 :UInt32; + modelExecutionTime @14 :Float32; + dspExecutionTime @16 :Float32; + rawPredictions @15 :Data; + + faceOrientation @3 :List(Float32); + facePosition @4 :List(Float32); + faceProb @5 :Float32; + leftEyeProb @6 :Float32; + rightEyeProb @7 :Float32; + leftBlinkProb @8 :Float32; + rightBlinkProb @9 :Float32; + faceOrientationStd @11 :List(Float32); + facePositionStd @12 :List(Float32); + sunglassesProb @13 :Float32; + poorVision @17 :Float32; + partialFace @18 :Float32; + distractedPose @19 :Float32; + distractedEyes @20 :Float32; + eyesOnRoad @21 :Float32; + phoneUse @22 :Float32; + occludedProb @23 :Float32; + + readyProb @24 :List(Float32); + notReadyProb @25 :List(Float32); + + irPwrDEPRECATED @10 :Float32; + descriptorDEPRECATED @1 :List(Float32); + stdDEPRECATED @2 :Float32; +} + +struct NavModelData @0xac3de5c437be057a { + frameId @0 :UInt32; + locationMonoTime @6 :UInt64; + modelExecutionTime @1 :Float32; + dspExecutionTime @2 :Float32; + features @3 :List(Float32); + # predicted future position + position @4 :XYData; + desirePrediction @5 :List(Float32); + + # All SI units and in device frame + struct XYData @0xbe09e615b2507e26 { + x @0 :List(Float32); + y @1 :List(Float32); + xStd @2 :List(Float32); + yStd @3 :List(Float32); + } +} + +struct AndroidBuildInfo @0xfe2919d5c21f426c { + board @0 :Text; + bootloader @1 :Text; + brand @2 :Text; + device @3 :Text; + display @4 :Text; + fingerprint @5 :Text; + hardware @6 :Text; + host @7 :Text; + id @8 :Text; + manufacturer @9 :Text; + model @10 :Text; + product @11 :Text; + radioVersion @12 :Text; + serial @13 :Text; + supportedAbis @14 :List(Text); + tags @15 :Text; + time @16 :Int64; + type @17 :Text; + user @18 :Text; + + versionCodename @19 :Text; + versionRelease @20 :Text; + versionSdk @21 :Int32; + versionSecurityPatch @22 :Text; +} + +struct AndroidSensor @0x9b513b93a887dbcd { + id @0 :Int32; + name @1 :Text; + vendor @2 :Text; + version @3 :Int32; + handle @4 :Int32; + type @5 :Int32; + maxRange @6 :Float32; + resolution @7 :Float32; + power @8 :Float32; + minDelay @9 :Int32; + fifoReservedEventCount @10 :UInt32; + fifoMaxEventCount @11 :UInt32; + stringType @12 :Text; + maxDelay @13 :Int32; +} + +struct IosBuildInfo @0xd97e3b28239f5580 { + appVersion @0 :Text; + appBuild @1 :UInt32; + osVersion @2 :Text; + deviceModel @3 :Text; +} + +enum FrameTypeDEPRECATED @0xa37f0d8558e193fd { + unknown @0; + neo @1; + chffrAndroid @2; + front @3; +} + +struct AndroidCaptureResult @0xbcc3efbac41d2048 { + sensitivity @0 :Int32; + frameDuration @1 :Int64; + exposureTime @2 :Int64; + rollingShutterSkew @3 :UInt64; + colorCorrectionTransform @4 :List(Int32); + colorCorrectionGains @5 :List(Float32); + displayRotation @6 :Int8; +} + +enum UsbPowerModeDEPRECATED @0xa8883583b32c9877 { + none @0; + client @1; + cdp @2; + dcp @3; +} + +struct LateralINDIState @0x939463348632375e { + active @0 :Bool; + steeringAngleDeg @1 :Float32; + steeringRateDeg @2 :Float32; + steeringAccelDeg @3 :Float32; + rateSetPoint @4 :Float32; + accelSetPoint @5 :Float32; + accelError @6 :Float32; + delayedOutput @7 :Float32; + delta @8 :Float32; + output @9 :Float32; + saturated @10 :Bool; + steeringAngleDesiredDeg @11 :Float32; + steeringRateDesiredDeg @12 :Float32; +} + +struct LateralLQRState @0x9024e2d790c82ade { + active @0 :Bool; + steeringAngleDeg @1 :Float32; + i @2 :Float32; + output @3 :Float32; + lqrOutput @4 :Float32; + saturated @5 :Bool; + steeringAngleDesiredDeg @6 :Float32; +} + +struct LateralCurvatureState @0xad9d8095c06f7c61 { + active @0 :Bool; + actualCurvature @1 :Float32; + desiredCurvature @2 :Float32; + error @3 :Float32; + p @4 :Float32; + i @5 :Float32; + f @6 :Float32; + output @7 :Float32; + saturated @8 :Bool; +} + +struct LateralPlannerSolution @0x84caeca5a6b4acfe { + x @0 :List(Float32); + y @1 :List(Float32); + yaw @2 :List(Float32); + yawRate @3 :List(Float32); + xStd @4 :List(Float32); + yStd @5 :List(Float32); + yawStd @6 :List(Float32); + yawRateStd @7 :List(Float32); +} + +struct GpsTrajectory @0x8cfeb072f5301000 { + x @0 :List(Float32); + y @1 :List(Float32); +} diff --git a/cereal/legacy.capnp b/cereal/legacy.capnp deleted file mode 100644 index a8fa5e4a1f7d5d..00000000000000 --- a/cereal/legacy.capnp +++ /dev/null @@ -1,574 +0,0 @@ -using Cxx = import "./include/c++.capnp"; -$Cxx.namespace("cereal"); - -@0x80ef1ec4889c2a63; - -# legacy.capnp: a home for deprecated structs - -struct LogRotate @0x9811e1f38f62f2d1 { - segmentNum @0 :Int32; - path @1 :Text; -} - -struct LiveUI @0xc08240f996aefced { - rearViewCam @0 :Bool; - alertText1 @1 :Text; - alertText2 @2 :Text; - awarenessStatus @3 :Float32; -} - -struct UiLayoutState @0x88dcce08ad29dda0 { - activeApp @0 :App; - sidebarCollapsed @1 :Bool; - mapEnabled @2 :Bool; - mockEngaged @3 :Bool; - - enum App @0x9917470acf94d285 { - home @0; - music @1; - nav @2; - settings @3; - none @4; - } -} - -struct OrbslamCorrection @0x8afd33dc9b35e1aa { - correctionMonoTime @0 :UInt64; - prePositionECEF @1 :List(Float64); - postPositionECEF @2 :List(Float64); - prePoseQuatECEF @3 :List(Float32); - postPoseQuatECEF @4 :List(Float32); - numInliers @5 :UInt32; -} - -struct EthernetPacket @0xa99a9d5b33cf5859 { - pkt @0 :Data; - ts @1 :Float32; -} - -struct CellInfo @0xcff7566681c277ce { - timestamp @0 :UInt64; - repr @1 :Text; # android toString() for now -} - -struct WifiScan @0xd4df5a192382ba0b { - bssid @0 :Text; - ssid @1 :Text; - capabilities @2 :Text; - frequency @3 :Int32; - level @4 :Int32; - timestamp @5 :Int64; - - centerFreq0 @6 :Int32; - centerFreq1 @7 :Int32; - channelWidth @8 :ChannelWidth; - operatorFriendlyName @9 :Text; - venueName @10 :Text; - is80211mcResponder @11 :Bool; - passpoint @12 :Bool; - - distanceCm @13 :Int32; - distanceSdCm @14 :Int32; - - enum ChannelWidth @0xcb6a279f015f6b51 { - w20Mhz @0; - w40Mhz @1; - w80Mhz @2; - w160Mhz @3; - w80Plus80Mhz @4; - } -} - -struct LiveEventData @0x94b7baa90c5c321e { - name @0 :Text; - value @1 :Int32; -} - -struct ModelData @0xb8aad62cffef28a9 { - frameId @0 :UInt32; - frameAge @12 :UInt32; - frameDropPerc @13 :Float32; - timestampEof @9 :UInt64; - modelExecutionTime @14 :Float32; - gpuExecutionTime @16 :Float32; - rawPred @15 :Data; - - path @1 :PathData; - leftLane @2 :PathData; - rightLane @3 :PathData; - lead @4 :LeadData; - freePath @6 :List(Float32); - - settings @5 :ModelSettings; - leadFuture @7 :LeadData; - speed @8 :List(Float32); - meta @10 :MetaData; - longitudinal @11 :LongitudinalData; - - struct PathData @0x8817eeea389e9f08 { - points @0 :List(Float32); - prob @1 :Float32; - std @2 :Float32; - stds @3 :List(Float32); - poly @4 :List(Float32); - validLen @5 :Float32; - } - - struct LeadData @0xd1c9bef96d26fa91 { - dist @0 :Float32; - prob @1 :Float32; - std @2 :Float32; - relVel @3 :Float32; - relVelStd @4 :Float32; - relY @5 :Float32; - relYStd @6 :Float32; - relA @7 :Float32; - relAStd @8 :Float32; - } - - struct ModelSettings @0xa26e3710efd3e914 { - bigBoxX @0 :UInt16; - bigBoxY @1 :UInt16; - bigBoxWidth @2 :UInt16; - bigBoxHeight @3 :UInt16; - boxProjection @4 :List(Float32); - yuvCorrection @5 :List(Float32); - inputTransform @6 :List(Float32); - } - - struct MetaData @0x9744f25fb60f2bf8 { - engagedProb @0 :Float32; - desirePrediction @1 :List(Float32); - brakeDisengageProb @2 :Float32; - gasDisengageProb @3 :Float32; - steerOverrideProb @4 :Float32; - desireState @5 :List(Float32); - } - - struct LongitudinalData @0xf98f999c6a071122 { - distances @2 :List(Float32); - speeds @0 :List(Float32); - accelerations @1 :List(Float32); - } -} - -struct ECEFPoint @0xc25bbbd524983447 { - x @0 :Float64; - y @1 :Float64; - z @2 :Float64; -} - -struct ECEFPointDEPRECATED @0xe10e21168db0c7f7 { - x @0 :Float32; - y @1 :Float32; - z @2 :Float32; -} - -struct GPSPlannerPoints @0xab54c59699f8f9f3 { - curPosDEPRECATED @0 :ECEFPointDEPRECATED; - pointsDEPRECATED @1 :List(ECEFPointDEPRECATED); - curPos @6 :ECEFPoint; - points @7 :List(ECEFPoint); - valid @2 :Bool; - trackName @3 :Text; - speedLimit @4 :Float32; - accelTarget @5 :Float32; -} - -struct GPSPlannerPlan @0xf5ad1d90cdc1dd6b { - valid @0 :Bool; - poly @1 :List(Float32); - trackName @2 :Text; - speed @3 :Float32; - acceleration @4 :Float32; - pointsDEPRECATED @5 :List(ECEFPointDEPRECATED); - points @6 :List(ECEFPoint); - xLookahead @7 :Float32; -} - -struct UiNavigationEvent @0x90c8426c3eaddd3b { - type @0: Type; - status @1: Status; - distanceTo @2: Float32; - endRoadPointDEPRECATED @3: ECEFPointDEPRECATED; - endRoadPoint @4: ECEFPoint; - - enum Type @0xe8db07dcf8fcea05 { - none @0; - laneChangeLeft @1; - laneChangeRight @2; - mergeLeft @3; - mergeRight @4; - turnLeft @5; - turnRight @6; - } - - enum Status @0xb9aa88c75ef99a1f { - none @0; - passive @1; - approaching @2; - active @3; - } -} - -struct LiveLocationData @0xb99b2bc7a57e8128 { - status @0 :UInt8; - - # 3D fix - lat @1 :Float64; - lon @2 :Float64; - alt @3 :Float32; # m - - # speed - speed @4 :Float32; # m/s - - # NED velocity components - vNED @5 :List(Float32); - - # roll, pitch, heading (x,y,z) - roll @6 :Float32; # WRT to center of earth? - pitch @7 :Float32; # WRT to center of earth? - heading @8 :Float32; # WRT to north? - - # what are these? - wanderAngle @9 :Float32; - trackAngle @10 :Float32; - - # car frame -- https://upload.wikimedia.org/wikipedia/commons/f/f5/RPY_angles_of_cars.png - - # gyro, in car frame, deg/s - gyro @11 :List(Float32); - - # accel, in car frame, m/s^2 - accel @12 :List(Float32); - - accuracy @13 :Accuracy; - - source @14 :SensorSource; - # if we are fixing a location in the past - fixMonoTime @15 :UInt64; - - gpsWeek @16 :Int32; - timeOfWeek @17 :Float64; - - positionECEF @18 :List(Float64); - poseQuatECEF @19 :List(Float32); - pitchCalibration @20 :Float32; - yawCalibration @21 :Float32; - imuFrame @22 :List(Float32); - - struct Accuracy @0x943dc4625473b03f { - pNEDError @0 :List(Float32); - vNEDError @1 :List(Float32); - rollError @2 :Float32; - pitchError @3 :Float32; - headingError @4 :Float32; - ellipsoidSemiMajorError @5 :Float32; - ellipsoidSemiMinorError @6 :Float32; - ellipsoidOrientationError @7 :Float32; - } - - enum SensorSource @0xc871d3cc252af657 { - applanix @0; - kalman @1; - orbslam @2; - timing @3; - dummy @4; - } -} - -struct OrbOdometry @0xd7700859ed1f5b76 { - # timing first - startMonoTime @0 :UInt64; - endMonoTime @1 :UInt64; - - # fundamental matrix and error - f @2: List(Float64); - err @3: Float64; - - # number of inlier points - inliers @4: Int32; - - # for debug only - # indexed by endMonoTime features - # value is startMonoTime feature match - # -1 if no match - matches @5: List(Int16); -} - -struct OrbFeatures @0xcd60164a8a0159ef { - timestampEof @0 :UInt64; - # transposed arrays of normalized image coordinates - # len(xs) == len(ys) == len(descriptors) * 32 - xs @1 :List(Float32); - ys @2 :List(Float32); - descriptors @3 :Data; - octaves @4 :List(Int8); - - # match index to last OrbFeatures - # -1 if no match - timestampLastEof @5 :UInt64; - matches @6: List(Int16); -} - -struct OrbFeaturesSummary @0xd500d30c5803fa4f { - timestampEof @0 :UInt64; - timestampLastEof @1 :UInt64; - - featureCount @2 :UInt16; - matchCount @3 :UInt16; - computeNs @4 :UInt64; -} - -struct OrbKeyFrame @0xc8233c0345e27e24 { - # this is a globally unique id for the KeyFrame - id @0: UInt64; - - # this is the location of the KeyFrame - pos @1: ECEFPoint; - - # these are the features in the world - # len(dpos) == len(descriptors) * 32 - dpos @2 :List(ECEFPoint); - descriptors @3 :Data; -} - -struct KalmanOdometry @0x92e21bb7ea38793a { - trans @0 :List(Float32); # m/s in device frame - rot @1 :List(Float32); # rad/s in device frame - transStd @2 :List(Float32); # std m/s in device frame - rotStd @3 :List(Float32); # std rad/s in device frame -} - -struct OrbObservation @0x9b326d4e436afec7 { - observationMonoTime @0 :UInt64; - normalizedCoordinates @1 :List(Float32); - locationECEF @2 :List(Float64); - matchDistance @3: UInt32; -} - -struct CalibrationFeatures @0x8fdfadb254ea867a { - frameId @0 :UInt32; - - p0 @1 :List(Float32); - p1 @2 :List(Float32); - status @3 :List(Int8); -} - -struct NavStatus @0xbd8822120928120c { - isNavigating @0 :Bool; - currentAddress @1 :Address; - - struct Address @0xce7cd672cacc7814 { - title @0 :Text; - lat @1 :Float64; - lng @2 :Float64; - house @3 :Text; - address @4 :Text; - street @5 :Text; - city @6 :Text; - state @7 :Text; - country @8 :Text; - } -} - -struct NavUpdate @0xdb98be6565516acb { - isNavigating @0 :Bool; - curSegment @1 :Int32; - segments @2 :List(Segment); - - struct LatLng @0x9eaef9187cadbb9b { - lat @0 :Float64; - lng @1 :Float64; - } - - struct Segment @0xa5b39b4fc4d7da3f { - from @0 :LatLng; - to @1 :LatLng; - updateTime @2 :Int32; - distance @3 :Int32; - crossTime @4 :Int32; - exitNo @5 :Int32; - instruction @6 :Instruction; - - parts @7 :List(LatLng); - - enum Instruction @0xc5417a637451246f { - turnLeft @0; - turnRight @1; - keepLeft @2; - keepRight @3; - straight @4; - roundaboutExitNumber @5; - roundaboutExit @6; - roundaboutTurnLeft @7; - unkn8 @8; - roundaboutStraight @9; - unkn10 @10; - roundaboutTurnRight @11; - unkn12 @12; - roundaboutUturn @13; - unkn14 @14; - arrive @15; - exitLeft @16; - exitRight @17; - unkn18 @18; - uturn @19; - # ... - } - } -} - -struct TrafficEvent @0xacfa74a094e62626 { - type @0 :Type; - distance @1 :Float32; - action @2 :Action; - resuming @3 :Bool; - - enum Type @0xd85d75253435bf4b { - stopSign @0; - lightRed @1; - lightYellow @2; - lightGreen @3; - stopLight @4; - } - - enum Action @0xa6f6ce72165ccb49 { - none @0; - yield @1; - stop @2; - resumeReady @3; - } - -} - - -struct AndroidGnss @0xdfdf30d03fc485bd { - union { - measurements @0 :Measurements; - navigationMessage @1 :NavigationMessage; - } - - struct Measurements @0xa20710d4f428d6cd { - clock @0 :Clock; - measurements @1 :List(Measurement); - - struct Clock @0xa0e27b453a38f450 { - timeNanos @0 :Int64; - hardwareClockDiscontinuityCount @1 :Int32; - - hasTimeUncertaintyNanos @2 :Bool; - timeUncertaintyNanos @3 :Float64; - - hasLeapSecond @4 :Bool; - leapSecond @5 :Int32; - - hasFullBiasNanos @6 :Bool; - fullBiasNanos @7 :Int64; - - hasBiasNanos @8 :Bool; - biasNanos @9 :Float64; - - hasBiasUncertaintyNanos @10 :Bool; - biasUncertaintyNanos @11 :Float64; - - hasDriftNanosPerSecond @12 :Bool; - driftNanosPerSecond @13 :Float64; - - hasDriftUncertaintyNanosPerSecond @14 :Bool; - driftUncertaintyNanosPerSecond @15 :Float64; - } - - struct Measurement @0xd949bf717d77614d { - svId @0 :Int32; - constellation @1 :Constellation; - - timeOffsetNanos @2 :Float64; - state @3 :Int32; - receivedSvTimeNanos @4 :Int64; - receivedSvTimeUncertaintyNanos @5 :Int64; - cn0DbHz @6 :Float64; - pseudorangeRateMetersPerSecond @7 :Float64; - pseudorangeRateUncertaintyMetersPerSecond @8 :Float64; - accumulatedDeltaRangeState @9 :Int32; - accumulatedDeltaRangeMeters @10 :Float64; - accumulatedDeltaRangeUncertaintyMeters @11 :Float64; - - hasCarrierFrequencyHz @12 :Bool; - carrierFrequencyHz @13 :Float32; - hasCarrierCycles @14 :Bool; - carrierCycles @15 :Int64; - hasCarrierPhase @16 :Bool; - carrierPhase @17 :Float64; - hasCarrierPhaseUncertainty @18 :Bool; - carrierPhaseUncertainty @19 :Float64; - hasSnrInDb @20 :Bool; - snrInDb @21 :Float64; - - multipathIndicator @22 :MultipathIndicator; - - enum Constellation @0x9ef1f3ff0deb5ffb { - unknown @0; - gps @1; - sbas @2; - glonass @3; - qzss @4; - beidou @5; - galileo @6; - } - - enum State @0xcbb9490adce12d72 { - unknown @0; - codeLock @1; - bitSync @2; - subframeSync @3; - towDecoded @4; - msecAmbiguous @5; - symbolSync @6; - gloStringSync @7; - gloTodDecoded @8; - bdsD2BitSync @9; - bdsD2SubframeSync @10; - galE1bcCodeLock @11; - galE1c2ndCodeLock @12; - galE1bPageSync @13; - sbasSync @14; - } - - enum MultipathIndicator @0xc04e7b6231d4caa8 { - unknown @0; - detected @1; - notDetected @2; - } - } - } - - struct NavigationMessage @0xe2517b083095fd4e { - type @0 :Int32; - svId @1 :Int32; - messageId @2 :Int32; - submessageId @3 :Int32; - data @4 :Data; - status @5 :Status; - - enum Status @0xec1ff7996b35366f { - unknown @0; - parityPassed @1; - parityRebuilt @2; - } - } -} - -struct LidarPts @0xe3d6685d4e9d8f7a { - r @0 :List(UInt16); # uint16 m*500.0 - theta @1 :List(UInt16); # uint16 deg*100.0 - reflect @2 :List(UInt8); # uint8 0-255 - - # For storing out of file. - idx @3 :UInt64; - - # For storing in file - pkt @4 :Data; -} - - diff --git a/cereal/log.capnp b/cereal/log.capnp index a82122e1a543a1..ae4dcc9e6d6e0e 100644 --- a/cereal/log.capnp +++ b/cereal/log.capnp @@ -2,7 +2,7 @@ using Cxx = import "./include/c++.capnp"; $Cxx.namespace("cereal"); using Car = import "car.capnp"; -using Legacy = import "legacy.capnp"; +using Deprecated = import "deprecated.capnp"; using Custom = import "custom.capnp"; @0xf3b1f17e25a4285b; @@ -17,6 +17,143 @@ struct Map(Key, Value) { } } +struct OnroadEvent @0xc4fa6047f024e718 { + name @0 :EventName; + + # event types + enable @1 :Bool; + noEntry @2 :Bool; + warning @3 :Bool; # alerts presented only when enabled or soft disabling + userDisable @4 :Bool; + softDisable @5 :Bool; + immediateDisable @6 :Bool; + preEnable @7 :Bool; + permanent @8 :Bool; # alerts presented regardless of openpilot state + overrideLateral @10 :Bool; + overrideLongitudinal @9 :Bool; + + enum EventName @0x91f1992a1f77fb03 { + canError @0; + steerUnavailable @1; + wrongGear @2; + doorOpen @3; + seatbeltNotLatched @4; + espDisabled @5; + wrongCarMode @6; + steerTempUnavailable @7; + reverseGear @8; + buttonCancel @9; + buttonEnable @10; + pedalPressed @11; # exits active state + preEnableStandstill @12; # added during pre-enable state with brake + gasPressedOverride @13; # added when user is pressing gas with no disengage on gas + steerOverride @14; + steerDisengage @94; # exits active state + cruiseDisabled @15; + speedTooLow @16; + outOfSpace @17; + overheat @18; + calibrationIncomplete @19; + calibrationInvalid @20; + calibrationRecalibrating @21; + controlsMismatch @22; + pcmEnable @23; + pcmDisable @24; + radarFault @25; + radarTempUnavailable @93; + brakeHold @26; + parkBrake @27; + manualRestart @28; + joystickDebug @29; + longitudinalManeuver @30; + steerTempUnavailableSilent @31; + resumeRequired @32; + driverDistracted1 @33; + driverDistracted2 @34; + driverDistracted3 @35; + driverUnresponsive1 @36; + driverUnresponsive2 @37; + driverUnresponsive3 @38; + belowSteerSpeed @39; + lowBattery @40; + accFaulted @41; + sensorDataInvalid @42; + commIssue @43; + commIssueAvgFreq @44; + tooDistracted @45; + posenetInvalid @46; + preLaneChangeLeft @48; + preLaneChangeRight @49; + laneChange @50; + lowMemory @51; + stockAeb @52; + stockLkas @98; + lateralManeuver @99; + ldw @53; + carUnrecognized @54; + invalidLkasSetting @55; + speedTooHigh @56; + laneChangeBlocked @57; + relayMalfunction @58; + stockFcw @59; + startup @60; + startupNoCar @61; + startupNoControl @62; + startupNoSecOcKey @63; + startupMaster @64; + fcw @65; + steerSaturated @66; + belowEngageSpeed @67; + noGps @68; + wrongCruiseMode @69; + modeldLagging @70; + deviceFalling @71; + fanMalfunction @72; + cameraMalfunction @73; + cameraFrameRate @74; + processNotRunning @75; + dashcamMode @76; + selfdriveInitializing @77; + usbError @78; + cruiseMismatch @79; + canBusMissing @80; + selfdrivedLagging @81; + resumeBlocked @82; + steerTimeLimit @83; + vehicleSensorsInvalid @84; + locationdTemporaryError @85; + locationdPermanentError @86; + paramsdTemporaryError @87; + paramsdPermanentError @88; + actuatorsApiUnavailable @89; + espActive @90; + personalityChanged @91; + aeb @92; + userBookmark @95; + excessiveActuation @96; + audioFeedback @97; + # NAP events. @98/@99 are comma 0.11.1 (stockLkas, lateralManeuver). + pedalCruiseEnabled @100; + pedalCruiseDisabled @101; + pedalMaxRegen @102; + teslaCCEngaged @103; + teslaCCDisengaged @104; + teslaCCNotArmed @105; + pedalNotCalibrated @106; + pedalUnavailable @107; + hypermileFollowChanged @108; + radarPreferFallback @109; + napWiperChanged @110; + gapLock @111; + lowVisibility @112; + obstacleChime @113; + preapBrakeLongActive @114; # Pre-AP: brake switch down while pedal long is still active. Log only. + lowVisibilityProlonged @115; # NAP: low-visibility lateral degrade latched > 45 s. Louder alert. + + soundsUnavailableDEPRECATED @47; + } +} + enum LongitudinalPersonality { aggressive @0; standard @1; @@ -38,6 +175,10 @@ struct InitData { gitBranch @11 :Text; gitRemote @13 :Text; + # this is source commit for prebuilt branches + gitSrcCommit @23 :Text; + gitSrcCommitDate @24 :Text; + androidProperties @16 :Map(Text, Text); pandaInfo @8 :PandaInfo; @@ -68,66 +209,16 @@ struct InitData { espVersion @3 :Text; } - # ***** deprecated stuff ***** - gctxDEPRECATED @1 :Text; - androidBuildInfo @5 :AndroidBuildInfo; - androidSensorsDEPRECATED @6 :List(AndroidSensor); - chffrAndroidExtraDEPRECATED @7 :ChffrAndroidExtra; - iosBuildInfoDEPRECATED @14 :IosBuildInfo; - - struct AndroidBuildInfo { - board @0 :Text; - bootloader @1 :Text; - brand @2 :Text; - device @3 :Text; - display @4 :Text; - fingerprint @5 :Text; - hardware @6 :Text; - host @7 :Text; - id @8 :Text; - manufacturer @9 :Text; - model @10 :Text; - product @11 :Text; - radioVersion @12 :Text; - serial @13 :Text; - supportedAbis @14 :List(Text); - tags @15 :Text; - time @16 :Int64; - type @17 :Text; - user @18 :Text; - - versionCodename @19 :Text; - versionRelease @20 :Text; - versionSdk @21 :Int32; - versionSecurityPatch @22 :Text; - } - - struct AndroidSensor { - id @0 :Int32; - name @1 :Text; - vendor @2 :Text; - version @3 :Int32; - handle @4 :Int32; - type @5 :Int32; - maxRange @6 :Float32; - resolution @7 :Float32; - power @8 :Float32; - minDelay @9 :Int32; - fifoReservedEventCount @10 :UInt32; - fifoMaxEventCount @11 :UInt32; - stringType @12 :Text; - maxDelay @13 :Int32; - } - struct ChffrAndroidExtra { allCameraCharacteristics @0 :Map(Text, Text); } - struct IosBuildInfo { - appVersion @0 :Text; - appBuild @1 :UInt32; - osVersion @2 :Text; - deviceModel @3 :Text; + deprecated :group { + gctx @1 :Text; + androidBuildInfo @5 :Deprecated.AndroidBuildInfo; + androidSensors @6 :List(Deprecated.AndroidSensor); + chffrAndroidExtra @7 :ChffrAndroidExtra; + iosBuildInfo @14 :Deprecated.IosBuildInfo; } } @@ -156,13 +247,6 @@ struct FrameData { temperaturesC @24 :List(Float32); - enum FrameTypeDEPRECATED { - unknown @0; - neo @1; - chffrAndroid @2; - front @3; - } - sensor @26 :ImageSensor; enum ImageSensor { unknown @0; @@ -171,26 +255,19 @@ struct FrameData { os04c10 @3; } - frameLengthDEPRECATED @3 :Int32; - globalGainDEPRECATED @5 :Int32; - frameTypeDEPRECATED @7 :FrameTypeDEPRECATED; - androidCaptureResultDEPRECATED @9 :AndroidCaptureResult; - lensPosDEPRECATED @11 :Int32; - lensSagDEPRECATED @12 :Float32; - lensErrDEPRECATED @13 :Float32; - lensTruePosDEPRECATED @14 :Float32; - focusValDEPRECATED @16 :List(Int16); - focusConfDEPRECATED @17 :List(UInt8); - sharpnessScoreDEPRECATED @18 :List(UInt16); - recoverStateDEPRECATED @19 :Int32; - struct AndroidCaptureResult { - sensitivity @0 :Int32; - frameDuration @1 :Int64; - exposureTime @2 :Int64; - rollingShutterSkew @3 :UInt64; - colorCorrectionTransform @4 :List(Int32); - colorCorrectionGains @5 :List(Float32); - displayRotation @6 :Int8; + deprecated :group { + frameLength @3 :Int32; + globalGain @5 :Int32; + frameType @7 :Deprecated.FrameTypeDEPRECATED; + androidCaptureResult @9 :Deprecated.AndroidCaptureResult; + lensPos @11 :Int32; + lensSag @12 :Float32; + lensErr @13 :Float32; + lensTruePos @14 :Float32; + focusVal @16 :List(Int16); + focusConf @17 :List(UInt8); + sharpnessScore @18 :List(UInt16); + recoverState @19 :Int32; } } @@ -213,13 +290,8 @@ struct GPSNMEAData { nmea @2 :Text; } -# android sensor_event_t struct SensorEventData { - version @0 :Int32; - sensor @1 :Int32; - type @2 :Int32; timestamp @3 :Int64; - uncalibratedDEPRECATED @10 :Bool; union { acceleration @4 :SensorVec; @@ -237,7 +309,10 @@ struct SensorEventData { struct SensorVec { v @0 :List(Float32); - status @1 :Int8; + + deprecated :group { + status @1 :Int8; + } } enum SensorSource { @@ -254,6 +329,14 @@ struct SensorEventData { lsm6ds3trc @10; mmc5603nj @11; } + + # formerly based on android sensor_event_t + deprecated :group { + version @0 :Int32; + sensor @1 :Int32; + type @2 :Int32; + uncalibrated @10 :Bool; + } } # android struct GpsLocation @@ -296,6 +379,7 @@ struct GpsLocationData { speedAccuracy @12 :Float32; hasFix @13 :Bool; + satelliteCount @14 :Int8; enum SensorSource { android @0; @@ -338,7 +422,10 @@ struct CanData { address @0 :UInt32; dat @2 :Data; src @3 :UInt8; - busTimeDEPRECATED @1 :UInt16; + + deprecated :group { + busTime @1 :UInt16; + } } struct DeviceState @0xa4d8b5af2aa492eb { @@ -369,10 +456,14 @@ struct DeviceState @0xa4d8b5af2aa492eb { # device thermals cpuTempC @26 :List(Float32); gpuTempC @27 :List(Float32); + dspTempC @49 :Float32; memoryTempC @28 :Float32; - nvmeTempC @35 :List(Float32); modemTempC @36 :List(Float32); pmicTempC @39 :List(Float32); + intakeTempC @46 :Float32; + exhaustTempC @47 :Float32; + gnssTempC @48 :Float32; + bottomSocTempC @50 :Float32; maxTempC @44 :Float32; # max of other temps, used to control fan thermalZones @38 :List(ThermalZone); thermalStatus @14 :ThermalStatus; @@ -386,10 +477,10 @@ struct DeviceState @0xa4d8b5af2aa492eb { } enum ThermalStatus { - green @0; - yellow @1; - red @2; - danger @3; + ok @0; + warmDEPRECATED @1; + overheated @2; + critical @3; } enum NetworkType { @@ -424,25 +515,27 @@ struct DeviceState @0xa4d8b5af2aa492eb { wwanRx @1 :Int64; } - # deprecated - cpu0DEPRECATED @0 :UInt16; - cpu1DEPRECATED @1 :UInt16; - cpu2DEPRECATED @2 :UInt16; - cpu3DEPRECATED @3 :UInt16; - memDEPRECATED @4 :UInt16; - gpuDEPRECATED @5 :UInt16; - batDEPRECATED @6 :UInt32; - pa0DEPRECATED @21 :UInt16; - cpuUsagePercentDEPRECATED @20 :Int8; - batteryStatusDEPRECATED @9 :Text; - batteryVoltageDEPRECATED @16 :Int32; - batteryTempCDEPRECATED @29 :Float32; - batteryPercentDEPRECATED @8 :Int16; - batteryCurrentDEPRECATED @15 :Int32; - chargingErrorDEPRECATED @17 :Bool; - chargingDisabledDEPRECATED @18 :Bool; - usbOnlineDEPRECATED @12 :Bool; - ambientTempCDEPRECATED @30 :Float32; + deprecated :group { + cpu0 @0 :UInt16; + cpu1 @1 :UInt16; + cpu2 @2 :UInt16; + cpu3 @3 :UInt16; + mem @4 :UInt16; + gpu @5 :UInt16; + bat @6 :UInt32; + pa0 @21 :UInt16; + cpuUsagePercent @20 :Int8; + batteryStatus @9 :Text; + batteryVoltage @16 :Int32; + batteryTempC @29 :Float32; + batteryPercent @8 :Int16; + batteryCurrent @15 :Int32; + chargingError @17 :Bool; + chargingDisabled @18 :Bool; + usbOnline @12 :Bool; + ambientTempC @30 :Float32; + nvmeTempC @35 :List(Float32); + } } struct PandaState @0xa7649e2575e4591e { @@ -458,13 +551,13 @@ struct PandaState @0xa7649e2575e4591e { heartbeatLost @22 :Bool; interruptLoad @25 :Float32; fanPower @28 :UInt8; - fanStallCount @34 :UInt8; - spiChecksumErrorCount @33 :UInt16; + spiErrorCount @33 :UInt16; harnessStatus @21 :HarnessStatus; sbu1Voltage @35 :Float32; sbu2Voltage @36 :Float32; + soundOutputLevel @37 :UInt16; # can health canState0 @29 :PandaCanState; @@ -483,6 +576,11 @@ struct PandaState @0xa7649e2575e4591e { voltage @0 :UInt32; current @1 :UInt32; + # these fields are not used by openpilot, but they're + # reserved for forks building alternate experiences. + controlsAllowedRESERVED1 @38 :Bool; + controlsAllowedRESERVED2 @39 :Bool; + enum FaultStatus { none @0; faultTemp @1; @@ -579,14 +677,17 @@ struct PandaState @0xa7649e2575e4591e { } } - gasInterceptorDetectedDEPRECATED @4 :Bool; - startedSignalDetectedDEPRECATED @5 :Bool; - hasGpsDEPRECATED @6 :Bool; - gmlanSendErrsDEPRECATED @9 :UInt32; - fanSpeedRpmDEPRECATED @11 :UInt16; - usbPowerModeDEPRECATED @12 :PeripheralState.UsbPowerModeDEPRECATED; - safetyParamDEPRECATED @20 :Int16; - safetyParam2DEPRECATED @26 :UInt32; + deprecated :group { + gasInterceptorDetected @4 :Bool; + startedSignalDetected @5 :Bool; + hasGps @6 :Bool; + gmlanSendErrs @9 :UInt32; + fanSpeedRpm @11 :UInt16; + usbPowerMode @12 :Deprecated.UsbPowerModeDEPRECATED; + safetyParam @20 :Int16; + safetyParam2 @26 :UInt32; + fanStallCount @34 :UInt8; + } } struct PeripheralState { @@ -595,23 +696,22 @@ struct PeripheralState { current @2 :UInt32; fanSpeedRpm @3 :UInt16; - usbPowerModeDEPRECATED @4 :UsbPowerModeDEPRECATED; - enum UsbPowerModeDEPRECATED @0xa8883583b32c9877 { - none @0; - client @1; - cdp @2; - dcp @3; + deprecated :group { + usbPowerMode @4 :Deprecated.UsbPowerModeDEPRECATED; } } struct RadarState @0x9a185389d6fdd05f { mdMonoTime @6 :UInt64; carStateMonoTime @11 :UInt64; - radarErrors @12 :List(Car.RadarData.Error); + radarErrors @13 :Car.RadarData.Error; leadOne @3 :LeadData; leadTwo @4 :LeadData; - cumLagMs @5 :Float32; + # Path-gated radar prefer dropped to stock fusion (enabled but unhealthy). + radarPreferFallback @14 :Bool; + # Latched trip reason, or this-frame soft reason (dropout/erratic) for digs. + radarPreferReason @15 :Text; struct LeadData { dRel @0 :Float32; @@ -630,17 +730,22 @@ struct RadarState @0x9a185389d6fdd05f { radar @14 :Bool; radarTrackId @15 :Int32 = -1; - aLeadDEPRECATED @5 :Float32; + deprecated :group { + aLead @5 :Float32; + } } - # deprecated - ftMonoTimeDEPRECATED @7 :UInt64; - warpMatrixDEPRECATED @0 :List(Float32); - angleOffsetDEPRECATED @1 :Float32; - calStatusDEPRECATED @2 :Int8; - calCycleDEPRECATED @8 :Int32; - calPercDEPRECATED @9 :Int8; - canMonoTimesDEPRECATED @10 :List(UInt64); + deprecated :group { + ftMonoTime @7 :UInt64; + warpMatrix @0 :List(Float32); + angleOffset @1 :Float32; + calStatus @2 :Int8; + calCycle @8 :Int32; + calPerc @9 :Int8; + canMonoTimes @10 :List(UInt64); + cumLagMs @5 :Float32; + radarErrors @12 :List(Car.RadarData.ErrorDEPRECATED); + } } struct LiveCalibrationData { @@ -658,10 +763,6 @@ struct LiveCalibrationData { wideFromDeviceEuler @10 :List(Float32); height @12 :List(Float32); - warpMatrixDEPRECATED @0 :List(Float32); - calStatusDEPRECATED @1 :Int8; - warpMatrix2DEPRECATED @5 :List(Float32); - warpMatrixBigDEPRECATED @6 :List(Float32); enum Status { uncalibrated @0; @@ -669,19 +770,13 @@ struct LiveCalibrationData { invalid @2; recalibrating @3; } -} -struct LiveTracks { - trackId @0 :Int32; - dRel @1 :Float32; - yRel @2 :Float32; - vRel @3 :Float32; - aRel @4 :Float32; - timeStamp @5 :Float32; - status @6 :Float32; - currentTime @7 :Float32; - stationary @8 :Bool; - oncoming @9 :Bool; + deprecated :group { + warpMatrix @0 :List(Float32); + calStatus @1 :Int8; + warpMatrix2 @5 :List(Float32); + warpMatrixBig @6 :List(Float32); + } } struct SelfdriveState { @@ -698,6 +793,7 @@ struct SelfdriveState { alertSize @6 :AlertSize; alertType @7 :Text; alertSound @8 :Car.CarControl.HUDControl.AudibleAlert; + alertHudVisual @12 :Car.CarControl.HUDControl.VisualAlert; # configurable driving settings experimentalMode @10 :Bool; @@ -726,45 +822,31 @@ struct SelfdriveState { } struct ControlsState @0x97ff69c53601abf1 { - cumLagMs @15 :Float32; longitudinalPlanMonoTime @28 :UInt64; lateralPlanMonoTime @50 :UInt64; longControlState @30 :Car.CarControl.Actuators.LongControlState; - vTargetLead @3 :Float32; upAccelCmd @4 :Float32; uiAccelCmd @5 :Float32; ufAccelCmd @33 :Float32; - aTarget @35 :Float32; curvature @37 :Float32; # path curvature from vehicle model desiredCurvature @61 :Float32; # lag adjusted curvatures used by lateral controllers forceDecel @51 :Bool; + latAuthority @67 :Float32; # 0-1 NAP lateral actuator authority (Pre-AP driver wheel handoff) + latHandoffPaused @68 :Bool; # HUD: yielded or blending below 70% authority + lowVisibility @69 :Bool; # NAP: model/camera blind, lateral eased toward the driver + coneLineHold @70 :Bool; # NAP: holding the driver's offset or applying the cone shift near cones + coneLineOffset @71 :Float32; # m, +right, path shift applied (0 when not holding/shifting) lateralControlState :union { - indiState @52 :LateralINDIState; pidState @53 :LateralPIDState; angleState @58 :LateralAngleState; debugState @59 :LateralDebugState; torqueState @60 :LateralTorqueState; - curvatureStateDEPRECATED @65 :LateralCurvatureState; - lqrStateDEPRECATED @55 :LateralLQRState; - } - - struct LateralINDIState { - active @0 :Bool; - steeringAngleDeg @1 :Float32; - steeringRateDeg @2 :Float32; - steeringAccelDeg @3 :Float32; - rateSetPoint @4 :Float32; - accelSetPoint @5 :Float32; - accelError @6 :Float32; - delayedOutput @7 :Float32; - delta @8 :Float32; - output @9 :Float32; - saturated @10 :Bool; - steeringAngleDesiredDeg @11 :Float32; - steeringRateDesiredDeg @12 :Float32; + curvatureStateDEPRECATED @65 :Deprecated.LateralCurvatureState; + lqrStateDEPRECATED @55 :Deprecated.LateralLQRState; + indiStateDEPRECATED @52 :Deprecated.LateralINDIState; } struct LateralPIDState { @@ -792,18 +874,10 @@ struct ControlsState @0x97ff69c53601abf1 { saturated @7 :Bool; actualLateralAccel @9 :Float32; desiredLateralAccel @10 :Float32; + desiredLateralJerk @11 :Float32; + version @12 :Int32; } - struct LateralLQRState { - active @0 :Bool; - steeringAngleDeg @1 :Float32; - i @2 :Float32; - output @3 :Float32; - lqrOutput @4 :Float32; - saturated @5 :Bool; - steeringAngleDesiredDeg @6 :Float32; - } - struct LateralAngleState { active @0 :Bool; steeringAngleDeg @1 :Float32; @@ -812,18 +886,6 @@ struct ControlsState @0x97ff69c53601abf1 { steeringAngleDesiredDeg @4 :Float32; } - struct LateralCurvatureState { - active @0 :Bool; - actualCurvature @1 :Float32; - desiredCurvature @2 :Float32; - error @3 :Float32; - p @4 :Float32; - i @5 :Float32; - f @6 :Float32; - output @7 :Float32; - saturated @8 :Bool; - } - struct LateralDebugState { active @0 :Bool; steeringAngleDeg @1 :Float32; @@ -831,61 +893,66 @@ struct ControlsState @0x97ff69c53601abf1 { saturated @3 :Bool; } - # deprecated - vEgoDEPRECATED @0 :Float32; - vEgoRawDEPRECATED @32 :Float32; - aEgoDEPRECATED @1 :Float32; - canMonoTimeDEPRECATED @16 :UInt64; - radarStateMonoTimeDEPRECATED @17 :UInt64; - mdMonoTimeDEPRECATED @18 :UInt64; - yActualDEPRECATED @6 :Float32; - yDesDEPRECATED @7 :Float32; - upSteerDEPRECATED @8 :Float32; - uiSteerDEPRECATED @9 :Float32; - ufSteerDEPRECATED @34 :Float32; - aTargetMinDEPRECATED @10 :Float32; - aTargetMaxDEPRECATED @11 :Float32; - rearViewCamDEPRECATED @23 :Bool; - driverMonitoringOnDEPRECATED @43 :Bool; - hudLeadDEPRECATED @14 :Int32; - alertSoundDEPRECATED @45 :Text; - angleModelBiasDEPRECATED @27 :Float32; - gpsPlannerActiveDEPRECATED @40 :Bool; - decelForTurnDEPRECATED @47 :Bool; - decelForModelDEPRECATED @54 :Bool; - awarenessStatusDEPRECATED @26 :Float32; - angleSteersDEPRECATED @13 :Float32; - vCurvatureDEPRECATED @46 :Float32; - mapValidDEPRECATED @49 :Bool; - jerkFactorDEPRECATED @12 :Float32; - steerOverrideDEPRECATED @20 :Bool; - steeringAngleDesiredDegDEPRECATED @29 :Float32; - canMonoTimesDEPRECATED @21 :List(UInt64); - desiredCurvatureRateDEPRECATED @62 :Float32; - canErrorCounterDEPRECATED @57 :UInt32; - vPidDEPRECATED @2 :Float32; - alertBlinkingRateDEPRECATED @42 :Float32; - alertText1DEPRECATED @24 :Text; - alertText2DEPRECATED @25 :Text; - alertStatusDEPRECATED @38 :SelfdriveState.AlertStatus; - alertSizeDEPRECATED @39 :SelfdriveState.AlertSize; - alertTypeDEPRECATED @44 :Text; - alertSound2DEPRECATED @56 :Car.CarControl.HUDControl.AudibleAlert; - engageableDEPRECATED @41 :Bool; # can OP be engaged? - stateDEPRECATED @31 :SelfdriveState.OpenpilotState; - enabledDEPRECATED @19 :Bool; - activeDEPRECATED @36 :Bool; - experimentalModeDEPRECATED @64 :Bool; - personalityDEPRECATED @66 :LongitudinalPersonality; - vCruiseDEPRECATED @22 :Float32; # actual set speed - vCruiseClusterDEPRECATED @63 :Float32; # set speed to display in the UI - startMonoTimeDEPRECATED @48 :UInt64; + deprecated :group { + vEgo @0 :Float32; + vEgoRaw @32 :Float32; + aEgo @1 :Float32; + canMonoTime @16 :UInt64; + radarStateMonoTime @17 :UInt64; + mdMonoTime @18 :UInt64; + yActual @6 :Float32; + yDes @7 :Float32; + upSteer @8 :Float32; + uiSteer @9 :Float32; + ufSteer @34 :Float32; + aTargetMin @10 :Float32; + aTargetMax @11 :Float32; + rearViewCam @23 :Bool; + driverMonitoringOn @43 :Bool; + hudLead @14 :Int32; + alertSound @45 :Text; + angleModelBias @27 :Float32; + gpsPlannerActive @40 :Bool; + decelForTurn @47 :Bool; + decelForModel @54 :Bool; + awarenessStatus @26 :Float32; + angleSteers @13 :Float32; + vCurvature @46 :Float32; + mapValid @49 :Bool; + jerkFactor @12 :Float32; + steerOverride @20 :Bool; + steeringAngleDesiredDeg @29 :Float32; + canMonoTimes @21 :List(UInt64); + desiredCurvatureRate @62 :Float32; + canErrorCounter @57 :UInt32; + vPid @2 :Float32; + alertBlinkingRate @42 :Float32; + alertText1 @24 :Text; + alertText2 @25 :Text; + alertStatus @38 :SelfdriveState.AlertStatus; + alertSize @39 :SelfdriveState.AlertSize; + alertType @44 :Text; + alertSound2 @56 :Car.CarControl.HUDControl.AudibleAlert; + engageable @41 :Bool; # can OP be engaged? + state @31 :SelfdriveState.OpenpilotState; + enabled @19 :Bool; + active @36 :Bool; + experimentalMode @64 :Bool; + personality @66 :LongitudinalPersonality; + vCruise @22 :Float32; # actual set speed + vCruiseCluster @63 :Float32; # set speed to display in the UI + startMonoTime @48 :UInt64; + cumLagMs @15 :Float32; + aTarget @35 :Float32; + vTargetLead @3 :Float32; + } } struct DrivingModelData { frameId @0 :UInt32; frameIdExtra @1 :UInt32; frameDropPerc @6 :Float32; + modelExecutionTime @7 :Float32; action @2 :ModelDataV2.Action; @@ -931,7 +998,6 @@ struct ModelDataV2 { frameDropPerc @2 :Float32; timestampEof @3 :UInt64; modelExecutionTime @15 :Float32; - gpuExecutionTime @17 :Float32; rawPredictions @16 :Data; # predicted future position, orientation, etc.. @@ -955,16 +1021,11 @@ struct ModelDataV2 { meta @12 :MetaData; confidence @23: ConfidenceClass; - # Model perceived motion - temporalPose @21 :Pose; - - navEnabledDEPRECATED @22 :Bool; - locationMonoTimeDEPRECATED @24 :UInt64; - # e2e lateral planner - lateralPlannerSolutionDEPRECATED @25: LateralPlannerSolution; action @26: Action; + lateralPlannerSolutionDEPRECATED @25: Deprecated.LateralPlannerSolution; + struct LeadDataV2 { prob @0 :Float32; # probability that car is your lead at time t t @1 :Float32; @@ -1003,12 +1064,15 @@ struct ModelDataV2 { hardBrakePredicted @7 :Bool; laneChangeState @8 :LaneChangeState; laneChangeDirection @9 :LaneChangeDirection; + laneChangeSignalsRemaining @10 :UInt8; + laneChangeRemaining @11 :UInt8; - # deprecated - brakeDisengageProbDEPRECATED @2 :Float32; - gasDisengageProbDEPRECATED @3 :Float32; - steerOverrideProbDEPRECATED @4 :Float32; + deprecated :group { + brakeDisengageProb @2 :Float32; + gasDisengageProb @3 :Float32; + steerOverrideProb @4 :Float32; + } } enum ConfidenceClass { @@ -1036,19 +1100,17 @@ struct ModelDataV2 { rotStd @3 :List(Float32); # std rad/s in device frame } - struct LateralPlannerSolution { - x @0 :List(Float32); - y @1 :List(Float32); - yaw @2 :List(Float32); - yawRate @3 :List(Float32); - xStd @4 :List(Float32); - yStd @5 :List(Float32); - yawStd @6 :List(Float32); - yawRateStd @7 :List(Float32); - } - struct Action { desiredCurvature @0 :Float32; + desiredAcceleration @1 :Float32; + shouldStop @2 :Bool; + } + + deprecated :group { + temporalPose @21 :Pose; + gpuExecutionTime @17 :Float32; + navEnabled @22 :Bool; + locationMonoTime @24 :UInt64; } } @@ -1096,6 +1158,18 @@ struct AndroidLogEntry { message @6 :Text; } +struct DriverAssistance { + # Lane Departure Warnings + leftLaneDeparture @0 :Bool; + rightLaneDeparture @1 :Bool; + + # FCW, AEB, etc. will go here +} + +struct LateralManeuverPlan { + desiredCurvature @0 :Float32; # 1/m +} + struct LongitudinalPlan @0xe00b5b3eba12876c { modelMonoTime @9 :UInt64; hasLead @7 :Bool; @@ -1111,6 +1185,14 @@ struct LongitudinalPlan @0xe00b5b3eba12876c { shouldStop @37: Bool; allowThrottle @38: Bool; allowBrake @39: Bool; + napFollowDistance @40 :UInt8; + tFollow @41 :Float32; + # Shadow of the continuous lead-follow controller. Logged every frame, + # including while NAPLongUnified is off. + unifiedATarget @42 :Float32; + # Gap lock meters. 0 = time-gap follow. Event: 0 none, 2 unavailable, 3 lead lost. + gapLockM @43 :Float32; + gapLockEvent @44 :UInt8; solverExecutionTime @35 :Float32; @@ -1123,38 +1205,35 @@ struct LongitudinalPlan @0xe00b5b3eba12876c { e2e @4; } - # deprecated - vCruiseDEPRECATED @16 :Float32; - aCruiseDEPRECATED @17 :Float32; - vTargetDEPRECATED @3 :Float32; - vTargetFutureDEPRECATED @14 :Float32; - vStartDEPRECATED @26 :Float32; - aStartDEPRECATED @27 :Float32; - vMaxDEPRECATED @20 :Float32; - radarStateMonoTimeDEPRECATED @10 :UInt64; - jerkFactorDEPRECATED @6 :Float32; - hasLeftLaneDEPRECATED @23 :Bool; - hasRightLaneDEPRECATED @24 :Bool; - aTargetMinDEPRECATED @4 :Float32; - aTargetMaxDEPRECATED @5 :Float32; - lateralValidDEPRECATED @0 :Bool; - longitudinalValidDEPRECATED @2 :Bool; - dPolyDEPRECATED @1 :List(Float32); - laneWidthDEPRECATED @11 :Float32; - vCurvatureDEPRECATED @21 :Float32; - decelForTurnDEPRECATED @22 :Bool; - mapValidDEPRECATED @25 :Bool; - radarValidDEPRECATED @28 :Bool; - radarCanErrorDEPRECATED @30 :Bool; - commIssueDEPRECATED @31 :Bool; - eventsDEPRECATED @13 :List(Car.OnroadEvent); - gpsTrajectoryDEPRECATED @12 :GpsTrajectory; - gpsPlannerActiveDEPRECATED @19 :Bool; - personalityDEPRECATED @36 :LongitudinalPersonality; - - struct GpsTrajectory { - x @0 :List(Float32); - y @1 :List(Float32); + + deprecated :group { + vCruise @16 :Float32; + aCruise @17 :Float32; + vTarget @3 :Float32; + vTargetFuture @14 :Float32; + vStart @26 :Float32; + aStart @27 :Float32; + vMax @20 :Float32; + radarStateMonoTime @10 :UInt64; + jerkFactor @6 :Float32; + hasLeftLane @23 :Bool; + hasRightLane @24 :Bool; + aTargetMin @4 :Float32; + aTargetMax @5 :Float32; + lateralValid @0 :Bool; + longitudinalValid @2 :Bool; + dPoly @1 :List(Float32); + laneWidth @11 :Float32; + vCurvature @21 :Float32; + decelForTurn @22 :Bool; + mapValid @25 :Bool; + radarValid @28 :Bool; + radarCanError @30 :Bool; + commIssue @31 :Bool; + events @13 :List(Car.OnroadEventDEPRECATED); + gpsTrajectory @12 :Deprecated.GpsTrajectory; + gpsPlannerActive @19 :Bool; + personality @36 :LongitudinalPersonality; } } struct UiPlan { @@ -1165,11 +1244,7 @@ struct UiPlan { struct LateralPlan @0xe1e9318e2ae8b51e { modelMonoTime @31 :UInt64; - laneWidthDEPRECATED @0 :Float32; - lProbDEPRECATED @5 :Float32; - rProbDEPRECATED @7 :Float32; dPathPoints @20 :List(Float32); - dProbDEPRECATED @21 :Float32; mpcSolutionValid @9 :Bool; desire @17 :Desire; @@ -1191,24 +1266,29 @@ struct LateralPlan @0xe1e9318e2ae8b51e { u @1 :List(Float32); } - # deprecated - curvatureDEPRECATED @22 :Float32; - curvatureRateDEPRECATED @23 :Float32; - rawCurvatureDEPRECATED @24 :Float32; - rawCurvatureRateDEPRECATED @25 :Float32; - cProbDEPRECATED @3 :Float32; - dPolyDEPRECATED @1 :List(Float32); - cPolyDEPRECATED @2 :List(Float32); - lPolyDEPRECATED @4 :List(Float32); - rPolyDEPRECATED @6 :List(Float32); - modelValidDEPRECATED @12 :Bool; - commIssueDEPRECATED @15 :Bool; - posenetValidDEPRECATED @16 :Bool; - sensorValidDEPRECATED @14 :Bool; - paramsValidDEPRECATED @10 :Bool; - steeringAngleDegDEPRECATED @8 :Float32; # deg - steeringRateDegDEPRECATED @13 :Float32; # deg/s - angleOffsetDegDEPRECATED @11 :Float32; + deprecated :group { + laneWidth @0 :Float32; + lProb @5 :Float32; + rProb @7 :Float32; + dProb @21 :Float32; + curvature @22 :Float32; + curvatureRate @23 :Float32; + rawCurvature @24 :Float32; + rawCurvatureRate @25 :Float32; + cProb @3 :Float32; + dPoly @1 :List(Float32); + cPoly @2 :List(Float32); + lPoly @4 :List(Float32); + rPoly @6 :List(Float32); + modelValid @12 :Bool; + commIssue @15 :Bool; + posenetValid @16 :Bool; + sensorValid @14 :Bool; + paramsValid @10 :Bool; + steeringAngleDeg @8 :Float32; # deg + steeringRateDeg @13 :Float32; # deg/s + angleOffsetDeg @11 :Float32; + } } struct LiveLocationKalman { @@ -1281,7 +1361,9 @@ struct LivePose { posenetOK @5 :Bool = false; sensorsOK @6 :Bool = false; - filterState @7 :FilterState; + timestamp @8 :UInt64; + + debugFilterState @7 :FilterState; struct XYZMeasurement { x @0 :Float32; @@ -1297,6 +1379,14 @@ struct LivePose { value @0 : List(Float64); std @1 : List(Float64); valid @2 : Bool; + + observations @3 :List(Observation); + + struct Observation { + kind @0 :Int32; + value @1 :List(Float32); + error @2 :List(Float32); + } } } @@ -1327,6 +1417,11 @@ struct ProcLog { cmdline @15 :List(Text); exe @16 :Text; + + # from /proc//smaps_rollup (proportional/private memory) + memPss @17 :UInt64; # Pss — shared pages split by mapper count + memPssAnon @18 :UInt64; # Pss_Anon — private anonymous (heap, stack) + memPssShmem @19 :UInt64; # Pss_Shmem — proportional MSGQ/tmpfs share } struct CPUTimes { @@ -1388,7 +1483,10 @@ struct GnssMeasurements { # Satellite position and velocity [x,y,z] satPos @7 :List(Float64); satVel @8 :List(Float64); - ephemerisSourceDEPRECATED @9 :EphemerisSourceDEPRECATED; + + deprecated :group { + ephemerisSource @9 :EphemerisSourceDEPRECATED; + } } struct EphemerisSourceDEPRECATED { @@ -1445,6 +1543,10 @@ struct UbloxGnss { svId @0 :UInt8; gnssId @1 :UInt8; flagsBitfield @2 :UInt32; + cno @3 :UInt8; + elevationDeg @4 :Int8; + azimuthDeg @5 :Int16; + pseudorangeResidual @6 :Float32; } } @@ -1539,7 +1641,6 @@ struct UbloxGnss { iDot @26 :Float64; codesL2 @27 :Float64; - gpsWeekDEPRECATED @28 :Float64; l2 @29 :Float64; svAcc @30 :Float64; @@ -1559,6 +1660,10 @@ struct UbloxGnss { towCount @40 :UInt32; toeWeek @41 :UInt16; tocWeek @42 :UInt16; + + deprecated :group { + gpsWeek @28 :Float64; + } } struct IonoData { @@ -1637,7 +1742,6 @@ struct UbloxGnss { age @17 :UInt8; svHealth @18 :UInt8; - tkDEPRECATED @19 :UInt16; tb @20 :UInt16; tauN @21 :Float64; @@ -1649,12 +1753,16 @@ struct UbloxGnss { p3 @26 :UInt8; p4 @27 :UInt8; - freqNumDEPRECATED @28 :UInt32; n4 @29 :UInt8; nt @30 :UInt16; freqNum @31 :Int16; tkSeconds @32 :UInt32; + + deprecated :group { + tk @19 :UInt16; + freqNum @28 :UInt32; + } } } @@ -1955,34 +2063,12 @@ struct QcomGnss @0xde94674b07ae51c1 { struct Clocks { wallTimeNanos @3 :UInt64; # unix epoch time - bootTimeNanosDEPRECATED @0 :UInt64; - monotonicNanosDEPRECATED @1 :UInt64; - monotonicRawNanosDEPRECATD @2 :UInt64; - modemUptimeMillisDEPRECATED @4 :UInt64; -} - -struct LiveMpcData { - x @0 :List(Float32); - y @1 :List(Float32); - psi @2 :List(Float32); - curvature @3 :List(Float32); - qpIterations @4 :UInt32; - calculationTime @5 :UInt64; - cost @6 :Float64; -} - -struct LiveLongitudinalMpcData { - xEgo @0 :List(Float32); - vEgo @1 :List(Float32); - aEgo @2 :List(Float32); - xLead @3 :List(Float32); - vLead @4 :List(Float32); - aLead @5 :List(Float32); - aLeadTau @6 :Float32; # lead accel time constant - qpIterations @7 :UInt32; - mpcId @8 :UInt32; - calculationTime @9 :UInt64; - cost @10 :Float64; + deprecated :group { + bootTimeNanos @0 :UInt64; + monotonicNanos @1 :UInt64; + monotonicRawNanos @2 :UInt64; + modemUptimeMillis @4 :UInt64; + } } struct Joystick { @@ -1994,12 +2080,10 @@ struct Joystick { struct DriverStateV2 { frameId @0 :UInt32; modelExecutionTime @1 :Float32; - dspExecutionTime @2 :Float32; + gpuExecutionTime @8 :Float32; rawPredictions @3 :Data; - poorVisionProb @4 :Float32; wheelOnRightProb @5 :Float32; - leftDriverData @6 :DriverData; rightDriverData @7 :DriverData; @@ -2014,46 +2098,24 @@ struct DriverStateV2 { leftBlinkProb @7 :Float32; rightBlinkProb @8 :Float32; sunglassesProb @9 :Float32; - occludedProb @10 :Float32; - readyProb @11 :List(Float32); - notReadyProb @12 :List(Float32); + phoneProb @13 :Float32; + sleepProb @14 :Float32; + + deprecated :group { + notReadyProb @12 :List(Float32); + occludedProb @10 :Float32; + readyProb @11 :List(Float32); + } } -} -struct DriverStateDEPRECATED @0xb83c6cc593ed0a00 { - frameId @0 :UInt32; - modelExecutionTime @14 :Float32; - dspExecutionTime @16 :Float32; - rawPredictions @15 :Data; - - faceOrientation @3 :List(Float32); - facePosition @4 :List(Float32); - faceProb @5 :Float32; - leftEyeProb @6 :Float32; - rightEyeProb @7 :Float32; - leftBlinkProb @8 :Float32; - rightBlinkProb @9 :Float32; - faceOrientationStd @11 :List(Float32); - facePositionStd @12 :List(Float32); - sunglassesProb @13 :Float32; - poorVision @17 :Float32; - partialFace @18 :Float32; - distractedPose @19 :Float32; - distractedEyes @20 :Float32; - eyesOnRoad @21 :Float32; - phoneUse @22 :Float32; - occludedProb @23 :Float32; - - readyProb @24 :List(Float32); - notReadyProb @25 :List(Float32); - - irPwrDEPRECATED @10 :Float32; - descriptorDEPRECATED @1 :List(Float32); - stdDEPRECATED @2 :Float32; + deprecated :group { + dspExecutionTime @2 :Float32; + poorVisionProb @4 :Float32; + } } -struct DriverMonitoringState @0xb83cda094a1da284 { - events @0 :List(Car.OnroadEvent); +struct DriverMonitoringStateDEPRECATED @0xb83cda094a1da284 { + events @18 :List(OnroadEvent); faceDetected @1 :Bool; isDistracted @2 :Bool; distractedType @17 :UInt32; @@ -2069,9 +2131,84 @@ struct DriverMonitoringState @0xb83cda094a1da284 { hiStdCount @14 :UInt32; isActiveMode @16 :Bool; isRHD @4 :Bool; + uncertainCount @19 :UInt32; - isPreviewDEPRECATED @15 :Bool; - rhdCheckedDEPRECATED @5 :Bool; + deprecated :group { + phoneProbOffset @20 :Float32; + phoneProbValidCount @21 :UInt32; + isPreview @15 :Bool; + rhdChecked @5 :Bool; + events @0 :List(Car.OnroadEventDEPRECATED); + } +} + +struct DriverMonitoringState { + lockout @0 :Bool; + alertCountLockoutPercent @1 :Int8; + alertTimeLockoutPercent @2 :Int8; + + alwaysOn @3 :Bool; + alwaysOnLockout @4 :Bool; + + alertLevel @5 :AlertLevel; + activePolicy @6 :MonitoringPolicy; + isRHD @7 :Bool; + rhdCalibration @8 :CalibrationState; + + visionPolicyState @9 :VisionPolicyState; + wheeltouchPolicyState @10 :WheeltouchPolicyState; + + enum AlertLevel { + # ordinal must match the name to prevent bugs + # comparing against the raw ordinal value + none @0; + one @1; + two @2; + three @3; + } + + enum MonitoringPolicy { + wheeltouch @0; + vision @1; + } + + struct VisionPolicyState { + awarenessPercent @0 :Int8; + awarenessStep @1 :Float32; + isDistracted @2 :Bool; + distractedTypes @3 :DistractedTypes; + + faceDetected @4 :Bool; + pose @5 :Pose; + wheeltouchFallbackPercent @6 :Int8; + uncertainOffroadAlertPercent @7 :Int8; + + struct DistractedTypes { + pose @0: Bool; + eye @1: Bool; + phone @2: Bool; + } + + struct Pose { + pitch @0 :Float32; + yaw @1 :Float32; + pitchCalib @2 :CalibrationState; + yawCalib @3 :CalibrationState; + calibrated @4 :Bool; + uncertainty @5 :Float32; + } + } + + struct WheeltouchPolicyState { + awarenessPercent @0 :Int8; + awarenessStep @1 :Float32; + driverInteracting @2 :Bool; + } + + struct CalibrationState { + calibratedPercent @0 :Int8; + offset @1 :Float32; + } } struct Boot { @@ -2080,8 +2217,10 @@ struct Boot { commands @5 :Map(Text, Data); launchLog @3 :Text; - lastKmsgDEPRECATED @1 :Data; - lastPmsgDEPRECATED @2 :Data; + deprecated :group { + lastKmsg @1 :Data; + lastPmsg @2 :Data; + } } struct LiveParametersData { @@ -2101,13 +2240,21 @@ struct LiveParametersData { roll @14 :Float32; debugFilterState @16 :FilterState; - yawRateDEPRECATED @7 :Float32; - filterStateDEPRECATED @15 :LiveLocationKalman.Measurement; + angleOffsetValid @17 :Bool = true; + angleOffsetAverageValid @18 :Bool = true; + steerRatioValid @19 :Bool = true; + stiffnessFactorValid @20 :Bool = true; + struct FilterState { value @0 : List(Float64); std @1 : List(Float64); } + + deprecated :group { + yawRate @7 :Float32; + filterState @15 :LiveLocationKalman.Measurement; + } } struct LiveTorqueParametersData { @@ -2124,6 +2271,24 @@ struct LiveTorqueParametersData { points @10 :List(List(Float32)); version @11 :Int32; useParams @12 :Bool; + calPerc @13 :Int8; +} + +struct LiveDelayData { + lateralDelay @0 :Float32; + validBlocks @1 :Int32; + status @2 :Status; + + lateralDelayEstimate @3 :Float32; + lateralDelayEstimateStd @5 :Float32; + points @4 :List(Float32); + calPerc @6 :Int8; + + enum Status { + unestimated @0; + estimated @1; + invalid @2; + } } struct LiveMapDataDEPRECATED { @@ -2171,7 +2336,8 @@ struct Sentinel { } struct UIDebug { - drawTimeMillis @0 :Float32; + cpuTimeMillis @0 :Float32; + frameTimeMillis @1 :Float32; } struct ManagerState { @@ -2259,25 +2425,6 @@ struct MapRenderState { frameId @2: UInt32; } -struct NavModelData { - frameId @0 :UInt32; - locationMonoTime @6 :UInt64; - modelExecutionTime @1 :Float32; - dspExecutionTime @2 :Float32; - features @3 :List(Float32); - # predicted future position - position @4 :XYData; - desirePrediction @5 :List(Float32); - - # All SI units and in device frame - struct XYData { - x @0 :List(Float32); - y @1 :List(Float32); - xStd @2 :List(Float32); - yStd @3 :List(Float32); - } -} - struct EncodeData { idx @0 :EncodeIndex; data @1 :Data; @@ -2287,16 +2434,42 @@ struct EncodeData { height @5 :UInt32; } -struct UserFlag { +struct DebugAlert { + alertText1 @0 :Text; + alertText2 @1 :Text; } -struct Microphone { +struct UserBookmark @0xfe346a9de48d9b50 { +} + +struct SoundPressure @0xdc24138990726023 { soundPressure @0 :Float32; # uncalibrated, A-weighted soundPressureWeighted @3 :Float32; soundPressureWeightedDb @1 :Float32; - filteredSoundPressureWeightedDb @2 :Float32; + + deprecated :group { + filteredSoundPressureWeightedDb @2 :Float32; + } +} + +struct AudioData { + data @0 :Data; + sampleRate @1 :UInt32; +} + +struct AudioFeedback { + audio @0 :AudioData; + blockNum @1 :UInt16; +} + +struct Touch { + sec @0 :Int64; + usec @1 :Int64; + type @2 :UInt8; + code @3 :Int32; + value @4 :Int32; } struct Event { @@ -2312,41 +2485,38 @@ struct Event { boot @60 :Boot; # ********** openpilot daemon msgs ********** - gpsNMEA @3 :GPSNMEAData; can @5 :List(CanData); controlsState @7 :ControlsState; selfdriveState @130 :SelfdriveState; gyroscope @99 :SensorEventData; - gyroscope2 @100 :SensorEventData; accelerometer @98 :SensorEventData; - accelerometer2 @101 :SensorEventData; magnetometer @95 :SensorEventData; lightSensor @96 :SensorEventData; temperatureSensor @97 :SensorEventData; - temperatureSensor2 @123 :SensorEventData; pandaStates @81 :List(PandaState); peripheralState @80 :PeripheralState; radarState @13 :RadarState; - liveTracks @16 :List(LiveTracks); + liveTracks @131 :Car.RadarData; sendcan @17 :List(CanData); liveCalibration @19 :LiveCalibrationData; carState @22 :Car.CarState; carControl @23 :Car.CarControl; carOutput @127 :Car.CarOutput; longitudinalPlan @24 :LongitudinalPlan; + driverAssistance @132 :DriverAssistance; ubloxGnss @34 :UbloxGnss; ubloxRaw @39 :Data; qcomGnss @31 :QcomGnss; gpsLocationExternal @48 :GpsLocationData; gpsLocation @21 :GpsLocationData; - gnssMeasurements @91 :GnssMeasurements; liveParameters @61 :LiveParametersData; liveTorqueParameters @94 :LiveTorqueParametersData; + liveDelay @146 : LiveDelayData; cameraOdometry @63 :CameraOdometry; thumbnail @66: Thumbnail; - onroadEvents @68: List(Car.OnroadEvent); + onroadEvents @134: List(OnroadEvent); carParams @69: Car.CarParams; - driverMonitoringState @71: DriverMonitoringState; + driverMonitoringState @151 :DriverMonitoringState; livePose @129 :LivePose; modelV2 @75 :ModelDataV2; drivingModelData @128 :DrivingModelData; @@ -2366,96 +2536,129 @@ struct Event { livestreamDriverEncodeIdx @119 :EncodeIndex; # microphone data - microphone @103 :Microphone; + soundPressure @103 :SoundPressure; + rawAudioData @147 :AudioData; # systems stuff androidLog @20 :AndroidLogEntry; managerState @78 :ManagerState; - uploaderState @79 :UploaderState; procLog @33 :ProcLog; clocks @35 :Clocks; deviceState @6 :DeviceState; logMessage @18 :Text; errorLogMessage @85 :Text; - # navigation - navInstruction @82 :NavInstruction; - navRoute @83 :NavRoute; - navThumbnail @84: Thumbnail; - mapRenderState @105: MapRenderState; + # touch frame + touch @135 :List(Touch); # UI services - userFlag @93 :UserFlag; uiDebug @102 :UIDebug; + # driving feedback + userBookmark @93 :UserBookmark; + bookmarkButton @148 :UserBookmark; + audioFeedback @149 :AudioFeedback; + + lateralManeuverPlan @150 :LateralManeuverPlan; + # *********** debug *********** testJoystick @52 :Joystick; roadEncodeData @86 :EncodeData; driverEncodeData @87 :EncodeData; wideRoadEncodeData @88 :EncodeData; qRoadEncodeData @89 :EncodeData; + alertDebug @133 :DebugAlert; livestreamRoadEncodeData @120 :EncodeData; livestreamWideRoadEncodeData @121 :EncodeData; livestreamDriverEncodeData @122 :EncodeData; + # *********** Custom: reserved for forks *********** + + # DO change the name of the field + # DON'T change anything after the "@" customReservedRawData0 @124 :Data; customReservedRawData1 @125 :Data; customReservedRawData2 @126 :Data; - # *********** Custom: reserved for forks *********** - customReserved0 @107 :Custom.CustomReserved0; - customReserved1 @108 :Custom.CustomReserved1; - customReserved2 @109 :Custom.CustomReserved2; - customReserved3 @110 :Custom.CustomReserved3; - customReserved4 @111 :Custom.CustomReserved4; + # DO change the name of the field and struct + # DON'T change the ID (e.g. @107) + # DON'T change which struct it points to + liveMapDataNAP @107 :Custom.LiveMapDataNAP; + liveSpeedSignNAP @108 :Custom.LiveSpeedSignNAP; + coneLineNAP @109 :Custom.ConeLineNAP; + pathObstacleNAP @110 :Custom.PathObstacleNAP; + pathObstacleVisionNAP @111 :Custom.PathObstacleVisionNAP; customReserved5 @112 :Custom.CustomReserved5; customReserved6 @113 :Custom.CustomReserved6; customReserved7 @114 :Custom.CustomReserved7; customReserved8 @115 :Custom.CustomReserved8; customReserved9 @116 :Custom.CustomReserved9; + customReserved10 @136 :Custom.CustomReserved10; + customReserved11 @137 :Custom.CustomReserved11; + customReserved12 @138 :Custom.CustomReserved12; + customReserved13 @139 :Custom.CustomReserved13; + customReserved14 @140 :Custom.CustomReserved14; + customReserved15 @141 :Custom.CustomReserved15; + customReserved16 @142 :Custom.CustomReserved16; + customReserved17 @143 :Custom.CustomReserved17; + customReserved18 @144 :Custom.CustomReserved18; + customReserved19 @145 :Custom.CustomReserved19; # *********** legacy + deprecated *********** - model @9 :Legacy.ModelData; # TODO: rename modelV2 and mark this as deprecated - liveMpcDEPRECATED @36 :LiveMpcData; - liveLongitudinalMpcDEPRECATED @37 :LiveLongitudinalMpcData; - liveLocationKalmanLegacyDEPRECATED @51 :Legacy.LiveLocationData; - orbslamCorrectionDEPRECATED @45 :Legacy.OrbslamCorrection; - liveUIDEPRECATED @14 :Legacy.LiveUI; + model @9 :Deprecated.ModelData; # TODO: rename modelV2 and mark this as deprecated + liveMpcDEPRECATED @36 :Deprecated.LiveMpcData; + liveLongitudinalMpcDEPRECATED @37 :Deprecated.LiveLongitudinalMpcData; + liveLocationKalmanDeprecatedDEPRECATED @51 :Deprecated.LiveLocationData; + orbslamCorrectionDEPRECATED @45 :Deprecated.OrbslamCorrection; + liveUIDEPRECATED @14 :Deprecated.LiveUI; sensorEventDEPRECATED @4 :SensorEventData; - liveEventDEPRECATED @8 :List(Legacy.LiveEventData); - liveLocationDEPRECATED @25 :Legacy.LiveLocationData; - ethernetDataDEPRECATED @26 :List(Legacy.EthernetPacket); - cellInfoDEPRECATED @28 :List(Legacy.CellInfo); - wifiScanDEPRECATED @29 :List(Legacy.WifiScan); - uiNavigationEventDEPRECATED @50 :Legacy.UiNavigationEvent; + liveEventDEPRECATED @8 :List(Deprecated.LiveEventData); + liveLocationDEPRECATED @25 :Deprecated.LiveLocationData; + ethernetDataDEPRECATED @26 :List(Deprecated.EthernetPacket); + cellInfoDEPRECATED @28 :List(Deprecated.CellInfo); + wifiScanDEPRECATED @29 :List(Deprecated.WifiScan); + uiNavigationEventDEPRECATED @50 :Deprecated.UiNavigationEvent; liveMapDataDEPRECATED @62 :LiveMapDataDEPRECATED; - gpsPlannerPointsDEPRECATED @40 :Legacy.GPSPlannerPoints; - gpsPlannerPlanDEPRECATED @41 :Legacy.GPSPlannerPlan; + gpsPlannerPointsDEPRECATED @40 :Deprecated.GPSPlannerPoints; + gpsPlannerPlanDEPRECATED @41 :Deprecated.GPSPlannerPlan; applanixRawDEPRECATED @42 :Data; - androidGnssDEPRECATED @30 :Legacy.AndroidGnss; - lidarPtsDEPRECATED @32 :Legacy.LidarPts; - navStatusDEPRECATED @38 :Legacy.NavStatus; - trafficEventsDEPRECATED @43 :List(Legacy.TrafficEvent); - liveLocationTimingDEPRECATED @44 :Legacy.LiveLocationData; - liveLocationCorrectedDEPRECATED @46 :Legacy.LiveLocationData; - navUpdateDEPRECATED @27 :Legacy.NavUpdate; - orbObservationDEPRECATED @47 :List(Legacy.OrbObservation); - locationDEPRECATED @49 :Legacy.LiveLocationData; - orbOdometryDEPRECATED @53 :Legacy.OrbOdometry; - orbFeaturesDEPRECATED @54 :Legacy.OrbFeatures; - applanixLocationDEPRECATED @55 :Legacy.LiveLocationData; - orbKeyFrameDEPRECATED @56 :Legacy.OrbKeyFrame; - orbFeaturesSummaryDEPRECATED @58 :Legacy.OrbFeaturesSummary; - featuresDEPRECATED @10 :Legacy.CalibrationFeatures; - kalmanOdometryDEPRECATED @65 :Legacy.KalmanOdometry; - uiLayoutStateDEPRECATED @57 :Legacy.UiLayoutState; + androidGnssDEPRECATED @30 :Deprecated.AndroidGnss; + lidarPtsDEPRECATED @32 :Deprecated.LidarPts; + navStatusDEPRECATED @38 :Deprecated.NavStatus; + trafficEventsDEPRECATED @43 :List(Deprecated.TrafficEvent); + liveLocationTimingDEPRECATED @44 :Deprecated.LiveLocationData; + liveLocationCorrectedDEPRECATED @46 :Deprecated.LiveLocationData; + navUpdateDEPRECATED @27 :Deprecated.NavUpdate; + orbObservationDEPRECATED @47 :List(Deprecated.OrbObservation); + locationDEPRECATED @49 :Deprecated.LiveLocationData; + orbOdometryDEPRECATED @53 :Deprecated.OrbOdometry; + orbFeaturesDEPRECATED @54 :Deprecated.OrbFeatures; + applanixLocationDEPRECATED @55 :Deprecated.LiveLocationData; + orbKeyFrameDEPRECATED @56 :Deprecated.OrbKeyFrame; + orbFeaturesSummaryDEPRECATED @58 :Deprecated.OrbFeaturesSummary; + featuresDEPRECATED @10 :Deprecated.CalibrationFeatures; + kalmanOdometryDEPRECATED @65 :Deprecated.KalmanOdometry; + uiLayoutStateDEPRECATED @57 :Deprecated.UiLayoutState; pandaStateDEPRECATED @12 :PandaState; - driverStateDEPRECATED @59 :DriverStateDEPRECATED; + driverStateDEPRECATED @59 :Deprecated.DriverStateDEPRECATED; sensorEventsDEPRECATED @11 :List(SensorEventData); lateralPlanDEPRECATED @64 :LateralPlan; - navModelDEPRECATED @104 :NavModelData; + navModelDEPRECATED @104 :Deprecated.NavModelData; uiPlanDEPRECATED @106 :UiPlan; liveLocationKalmanDEPRECATED @72 :LiveLocationKalman; + liveTracksDEPRECATED @16 :List(Deprecated.LiveTracksDEPRECATED); + onroadEventsDEPRECATED @68: List(Car.OnroadEventDEPRECATED); + gyroscope2DEPRECATED @100 :SensorEventData; + accelerometer2DEPRECATED @101 :SensorEventData; + temperatureSensor2DEPRECATED @123 :SensorEventData; + driverMonitoringStateDEPRECATED @71 :DriverMonitoringStateDEPRECATED; + gpsNMEADEPRECATED @3 :GPSNMEAData; + uploaderStateDEPRECATED @79 :UploaderState; + navInstructionDEPRECATED @82 :NavInstruction; + navRouteDEPRECATED @83 :NavRoute; + navThumbnailDEPRECATED @84 :Thumbnail; + gnssMeasurementsDEPRECATED @91 :GnssMeasurements; + mapRenderStateDEPRECATED @105: MapRenderState; } } diff --git a/cereal/maptile.capnp b/cereal/maptile.capnp deleted file mode 100644 index c8a23a1822b808..00000000000000 --- a/cereal/maptile.capnp +++ /dev/null @@ -1,49 +0,0 @@ -using Cxx = import "./include/c++.capnp"; -$Cxx.namespace("cereal"); - -@0xa086df597ef5d7a0; - -# Geometry -struct Point { - x @0: Float64; - y @1: Float64; - z @2: Float64; -} - -struct PolyLine { - points @0: List(Point); -} - -# Map features -struct Lane { - id @0 :Text; - - leftBoundary @1 :LaneBoundary; - rightBoundary @2 :LaneBoundary; - - leftAdjacentId @3 :Text; - rightAdjacentId @4 :Text; - - inboundIds @5 :List(Text); - outboundIds @6 :List(Text); - - struct LaneBoundary { - polyLine @0 :PolyLine; - startHeading @1 :Float32; # WRT north - } -} - -# Map tiles -struct TileSummary { - version @0 :Text; - updatedAt @1 :UInt64; # Millis since epoch - - level @2 :UInt8; - x @3 :UInt16; - y @4 :UInt16; -} - -struct MapTile { - summary @0 :TileSummary; - lanes @1 :List(Lane); -} diff --git a/cereal/messaging/__init__.py b/cereal/messaging/__init__.py index 32b7a6553f353f..ae32bfd4cbebc1 100644 --- a/cereal/messaging/__init__.py +++ b/cereal/messaging/__init__.py @@ -1,23 +1,35 @@ # must be built with scons -from msgq.ipc_pyx import Context, Poller, SubSocket, PubSocket, SocketEventHandle, toggle_fake_events, \ - set_fake_prefix, get_fake_prefix, delete_fake_prefix, wait_for_one_event -from msgq.ipc_pyx import MultiplePublishersError, IpcError -from msgq import fake_event_handle, pub_sock, sub_sock, drain_sock_raw +from msgq import fake_event_handle, drain_sock_raw, MultiplePublishersError, IpcError, \ + Context, Poller, SubSocket, PubSocket, SocketEventHandle, toggle_fake_events, \ + set_fake_prefix, get_fake_prefix, delete_fake_prefix, wait_for_one_event import msgq - import os import capnp import time -from typing import Optional, List, Union, Dict, Deque -from collections import deque +from typing import Optional, List, Union, Dict from cereal import log from cereal.services import SERVICE_LIST +from openpilot.common.utils import MovingAverage NO_TRAVERSAL_LIMIT = 2**64-1 +def pub_sock(endpoint: str) -> PubSocket: + service = SERVICE_LIST.get(endpoint) + segment_size = service.queue_size if service else 0 + return msgq.pub_sock(endpoint, segment_size) + + +def sub_sock(endpoint: str, poller: Optional[Poller] = None, addr: str = "127.0.0.1", + conflate: bool = False, timeout: Optional[int] = None) -> SubSocket: + service = SERVICE_LIST.get(endpoint) + segment_size = service.queue_size if service else 0 + return msgq.sub_sock(endpoint, poller=poller, addr=addr, conflate=conflate, + timeout=timeout, segment_size=segment_size) + + def reset_context(): msgq.context = Context() @@ -108,26 +120,30 @@ def __init__(self, service_freq: float, update_freq: float, is_poll: bool): self.min_freq = min_freq * 0.8 self.max_freq = max_freq * 1.2 - self.recv_dts: Deque[float] = deque(maxlen=int(10 * freq)) + self.avg_dt = MovingAverage(int(10 * freq)) + self.recent_avg_dt = MovingAverage(int(freq)) self.prev_time = 0.0 def record_recv_time(self, cur_time: float) -> None: # TODO: Handle case where cur_time is less than prev_time if self.prev_time > 1e-5: - self.recv_dts.append(cur_time - self.prev_time) + dt = cur_time - self.prev_time + + self.avg_dt.add_value(dt) + self.recent_avg_dt.add_value(dt) + self.prev_time = cur_time @property def valid(self) -> bool: - if not self.recv_dts: + if self.avg_dt.count == 0: return False - avg_freq = len(self.recv_dts) / sum(self.recv_dts) + avg_freq = 1.0 / self.avg_dt.get_average() if self.min_freq <= avg_freq <= self.max_freq: return True - recent_dts = list(self.recv_dts)[-int(self.recv_dts.maxlen / 10):] - avg_freq_recent = len(recent_dts) / sum(recent_dts) + avg_freq_recent = 1.0 / self.recent_avg_dt.get_average() return self.min_freq <= avg_freq_recent <= self.max_freq @@ -141,12 +157,16 @@ def __init__(self, services: List[str], poll: Optional[str] = None, self.updated = {s: False for s in services} self.recv_time = {s: 0. for s in services} self.recv_frame = {s: 0 for s in services} - self.alive = {s: False for s in services} - self.freq_ok = {s: False for s in services} self.sock = {} self.data = {} - self.valid = {} - self.logMonoTime = {} + self.logMonoTime = {s: 0 for s in services} + + # zero-frequency / on-demand services are always alive and presumed valid; all others must pass checks + on_demand = {s: SERVICE_LIST[s].frequency <= 1e-5 for s in services} + self.static_freq_services = set(s for s in services if not on_demand[s]) + self.alive = {s: on_demand[s] for s in services} + self.freq_ok = {s: on_demand[s] for s in services} + self.valid = {s: on_demand[s] for s in services} self.freq_tracker: Dict[str, FrequencyTracker] = {} self.poller = Poller() @@ -173,8 +193,6 @@ def __init__(self, services: List[str], poll: Optional[str] = None, data = new_message(s, 0) # lists self.data[s] = getattr(data.as_reader(), s) - self.logMonoTime[s] = 0 - self.valid[s] = True # FIXME: this should default to False self.freq_tracker[s] = FrequencyTracker(SERVICE_LIST[s].frequency, self.update_freq, s == poll) def __getitem__(self, s: str) -> capnp.lib.capnp._DynamicStructReader: @@ -211,14 +229,10 @@ def update_msgs(self, cur_time: float, msgs: List[capnp.lib.capnp._DynamicStruct self.logMonoTime[s] = msg.logMonoTime self.valid[s] = msg.valid - for s in self.services: - if SERVICE_LIST[s].frequency > 1e-5 and not self.simulation: - # alive if delay is within 10x the expected frequency - self.alive[s] = (cur_time - self.recv_time[s]) < (10. / SERVICE_LIST[s].frequency) - self.freq_ok[s] = self.freq_tracker[s].valid - else: - self.freq_ok[s] = True - self.alive[s] = self.seen[s] if self.simulation else True + for s in self.static_freq_services: + # alive if delay is within 10x the expected frequency; checks relaxed in simulator + self.alive[s] = (cur_time - self.recv_time[s]) < (10. / SERVICE_LIST[s].frequency) or (self.seen[s] and self.simulation) + self.freq_ok[s] = self.freq_tracker[s].valid or self.simulation def all_alive(self, service_list: Optional[List[str]] = None) -> bool: return all(self.alive[s] for s in (service_list or self.services) if s not in self.ignore_alive) @@ -245,11 +259,11 @@ def send(self, s: str, dat: Union[bytes, capnp.lib.capnp._DynamicStructBuilder]) self.sock[s].send(dat) def wait_for_readers_to_update(self, s: str, timeout: int, dt: float = 0.05) -> bool: - for _ in range(int(timeout*(1./dt))): - if self.sock[s].all_readers_updated(): - return True - time.sleep(dt) - return False + try: + self.sock[s].wait_for_readers(timeout=timeout, interval=dt) + return True + except TimeoutError: + return False def all_readers_updated(self, s: str) -> bool: - return self.sock[s].all_readers_updated() # type: ignore + return self.sock[s].all_readers_updated() diff --git a/cereal/messaging/bridge.cc b/cereal/messaging/bridge.cc index 93af988358df85..77823c413acae2 100644 --- a/cereal/messaging/bridge.cc +++ b/cereal/messaging/bridge.cc @@ -6,12 +6,12 @@ ExitHandler do_exit; -static std::vector get_services(std::string whitelist_str, bool zmq_to_msgq) { +static std::vector get_services(const std::string &whitelist_str, bool zmq_to_msgq) { std::vector service_list; for (const auto& it : services) { std::string name = it.second.name; bool in_whitelist = whitelist_str.find(name) != std::string::npos; - if (name == "plusFrame" || name == "uiLayoutState" || (zmq_to_msgq && !in_whitelist)) { + if (zmq_to_msgq && !in_whitelist) { continue; } service_list.push_back(name); @@ -25,15 +25,16 @@ void msgq_to_zmq(const std::vector &endpoints, const std::string &i } void zmq_to_msgq(const std::vector &endpoints, const std::string &ip) { - auto poller = std::make_unique(); - auto pub_context = std::make_unique(); - auto sub_context = std::make_unique(); - std::map sub2pub; + auto poller = std::make_unique(); + auto pub_context = std::make_unique(); + auto sub_context = std::make_unique(); + std::map sub2pub; for (auto endpoint : endpoints) { - auto pub_sock = new MSGQPubSocket(); - auto sub_sock = new ZMQSubSocket(); - pub_sock->connect(pub_context.get(), endpoint); + auto pub_sock = new PubSocket(); + auto sub_sock = new BridgeZmqSubSocket(); + size_t queue_size = services.at(endpoint).queue_size; + pub_sock->connect(pub_context.get(), endpoint, true, queue_size); sub_sock->connect(sub_context.get(), endpoint, ip, false); poller->registerSocket(sub_sock); diff --git a/cereal/messaging/bridge_zmq.cc b/cereal/messaging/bridge_zmq.cc new file mode 100644 index 00000000000000..5c56673b472adf --- /dev/null +++ b/cereal/messaging/bridge_zmq.cc @@ -0,0 +1,170 @@ +#include "cereal/messaging/bridge_zmq.h" + +#include +#include +#include + +static size_t fnv1a_hash(const std::string &str) { + const size_t fnv_prime = 0x100000001b3; + size_t hash_value = 0xcbf29ce484222325; + for (char c : str) { + hash_value ^= (unsigned char)c; + hash_value *= fnv_prime; + } + return hash_value; +} + +// FIXME: This is a hack to get the port number from the socket name, might have collisions. +static int get_port(std::string endpoint) { + size_t hash_value = fnv1a_hash(endpoint); + int start_port = 8023; + int max_port = 65535; + return start_port + (hash_value % (max_port - start_port)); +} + +BridgeZmqContext::BridgeZmqContext() { + context = zmq_ctx_new(); +} + +BridgeZmqContext::~BridgeZmqContext() { + if (context != nullptr) { + zmq_ctx_term(context); + } +} + +void BridgeZmqMessage::init(size_t sz) { + size = sz; + data = new char[size]; +} + +void BridgeZmqMessage::init(char *d, size_t sz) { + size = sz; + data = new char[size]; + memcpy(data, d, size); +} + +void BridgeZmqMessage::close() { + if (size > 0) { + delete[] data; + } + data = nullptr; + size = 0; +} + +BridgeZmqMessage::~BridgeZmqMessage() { + close(); +} + +int BridgeZmqSubSocket::connect(BridgeZmqContext *context, std::string endpoint, std::string address, bool conflate, bool check_endpoint) { + sock = zmq_socket(context->getRawContext(), ZMQ_SUB); + if (sock == nullptr) { + return -1; + } + + zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0); + + if (conflate) { + int arg = 1; + zmq_setsockopt(sock, ZMQ_CONFLATE, &arg, sizeof(int)); + } + + int reconnect_ivl = 500; + zmq_setsockopt(sock, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl, sizeof(reconnect_ivl)); + + full_endpoint = "tcp://" + address + ":"; + if (check_endpoint) { + full_endpoint += std::to_string(get_port(endpoint)); + } else { + full_endpoint += endpoint; + } + + return zmq_connect(sock, full_endpoint.c_str()); +} + +void BridgeZmqSubSocket::setTimeout(int timeout) { + zmq_setsockopt(sock, ZMQ_RCVTIMEO, &timeout, sizeof(int)); +} + +Message *BridgeZmqSubSocket::receive(bool non_blocking) { + zmq_msg_t msg; + assert(zmq_msg_init(&msg) == 0); + + int flags = non_blocking ? ZMQ_DONTWAIT : 0; + int rc = zmq_msg_recv(&msg, sock, flags); + + Message *ret = nullptr; + if (rc >= 0) { + ret = new BridgeZmqMessage; + ret->init((char *)zmq_msg_data(&msg), zmq_msg_size(&msg)); + } + + zmq_msg_close(&msg); + return ret; +} + +BridgeZmqSubSocket::~BridgeZmqSubSocket() { + if (sock != nullptr) { + zmq_close(sock); + } +} + +int BridgeZmqPubSocket::connect(BridgeZmqContext *context, std::string endpoint, bool check_endpoint) { + sock = zmq_socket(context->getRawContext(), ZMQ_PUB); + if (sock == nullptr) { + return -1; + } + + full_endpoint = "tcp://*:"; + if (check_endpoint) { + full_endpoint += std::to_string(get_port(endpoint)); + } else { + full_endpoint += endpoint; + } + + // ZMQ pub sockets cannot be shared between processes, so we need to ensure pid stays the same. + pid = getpid(); + + return zmq_bind(sock, full_endpoint.c_str()); +} + +int BridgeZmqPubSocket::sendMessage(Message *message) { + assert(pid == getpid()); + return zmq_send(sock, message->getData(), message->getSize(), ZMQ_DONTWAIT); +} + +int BridgeZmqPubSocket::send(char *data, size_t size) { + assert(pid == getpid()); + return zmq_send(sock, data, size, ZMQ_DONTWAIT); +} + +BridgeZmqPubSocket::~BridgeZmqPubSocket() { + if (sock != nullptr) { + zmq_close(sock); + } +} + +void BridgeZmqPoller::registerSocket(BridgeZmqSubSocket *socket) { + assert(num_polls + 1 < (sizeof(polls) / sizeof(polls[0]))); + polls[num_polls].socket = socket->getRawSocket(); + polls[num_polls].events = ZMQ_POLLIN; + + sockets.push_back(socket); + num_polls++; +} + +std::vector BridgeZmqPoller::poll(int timeout) { + std::vector ret; + + int rc = zmq_poll(polls, num_polls, timeout); + if (rc < 0) { + return ret; + } + + for (size_t i = 0; i < num_polls; i++) { + if (polls[i].revents) { + ret.push_back(sockets[i]); + } + } + + return ret; +} diff --git a/cereal/messaging/bridge_zmq.h b/cereal/messaging/bridge_zmq.h new file mode 100644 index 00000000000000..ebdbc56c245f40 --- /dev/null +++ b/cereal/messaging/bridge_zmq.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include + +#include + +#include "msgq/ipc.h" + +class BridgeZmqContext { +public: + BridgeZmqContext(); + void *getRawContext() { return context; } + ~BridgeZmqContext(); + +private: + void *context = nullptr; +}; + +class BridgeZmqMessage : public Message { +public: + void init(size_t size); + void init(char *data, size_t size); + void close(); + size_t getSize() { return size; } + char *getData() { return data; } + ~BridgeZmqMessage(); + +private: + char *data = nullptr; + size_t size = 0; +}; + +class BridgeZmqSubSocket { +public: + int connect(BridgeZmqContext *context, std::string endpoint, std::string address, bool conflate = false, bool check_endpoint = true); + void setTimeout(int timeout); + Message *receive(bool non_blocking = false); + void *getRawSocket() { return sock; } + ~BridgeZmqSubSocket(); + +private: + void *sock = nullptr; + std::string full_endpoint; +}; + +class BridgeZmqPubSocket { +public: + int connect(BridgeZmqContext *context, std::string endpoint, bool check_endpoint = true); + int sendMessage(Message *message); + int send(char *data, size_t size); + void *getRawSocket() { return sock; } + ~BridgeZmqPubSocket(); + +private: + void *sock = nullptr; + std::string full_endpoint; + int pid = -1; +}; + +class BridgeZmqPoller { +public: + void registerSocket(BridgeZmqSubSocket *socket); + std::vector poll(int timeout); + +private: + static constexpr size_t MAX_BRIDGE_ZMQ_POLLERS = 128; + std::vector sockets; + zmq_pollitem_t polls[MAX_BRIDGE_ZMQ_POLLERS] = {}; + size_t num_polls = 0; +}; diff --git a/cereal/messaging/msgq_to_zmq.cc b/cereal/messaging/msgq_to_zmq.cc index a130f7dd04618f..5e7ea222739823 100644 --- a/cereal/messaging/msgq_to_zmq.cc +++ b/cereal/messaging/msgq_to_zmq.cc @@ -2,6 +2,7 @@ #include +#include "cereal/services.h" #include "common/util.h" extern ExitHandler do_exit; @@ -21,14 +22,14 @@ static std::string recv_zmq_msg(void *sock) { } void MsgqToZmq::run(const std::vector &endpoints, const std::string &ip) { - zmq_context = std::make_unique(); - msgq_context = std::make_unique(); + zmq_context = std::make_unique(); + msgq_context = std::make_unique(); // Create ZMQPubSockets for each endpoint for (const auto &endpoint : endpoints) { auto &socket_pair = socket_pairs.emplace_back(); socket_pair.endpoint = endpoint; - socket_pair.pub_sock = std::make_unique(); + socket_pair.pub_sock = std::make_unique(); int ret = socket_pair.pub_sock->connect(zmq_context.get(), endpoint); if (ret != 0) { printf("Failed to create ZMQ publisher for [%s]: %s\n", endpoint.c_str(), zmq_strerror(zmq_errno())); @@ -48,11 +49,12 @@ void MsgqToZmq::run(const std::vector &endpoints, const std::string for (auto sub_sock : msgq_poller->poll(100)) { // Process messages for each socket + BridgeZmqPubSocket *pub_sock = sub2pub.at(sub_sock); for (int i = 0; i < MAX_MESSAGES_PER_SOCKET; ++i) { auto msg = std::unique_ptr(sub_sock->receive(true)); if (!msg) break; - while (sub2pub[sub_sock]->sendMessage(msg.get()) == -1) { + while (pub_sock->sendMessage(msg.get()) == -1) { if (errno != EINTR) break; } } @@ -70,7 +72,7 @@ void MsgqToZmq::zmqMonitorThread() { // Set up ZMQ monitor for each pub socket for (int i = 0; i < socket_pairs.size(); ++i) { std::string addr = "inproc://op-bridge-monitor-" + std::to_string(i); - zmq_socket_monitor(socket_pairs[i].pub_sock->sock, addr.c_str(), ZMQ_EVENT_ACCEPTED | ZMQ_EVENT_DISCONNECTED); + zmq_socket_monitor(socket_pairs[i].pub_sock->getRawSocket(), addr.c_str(), ZMQ_EVENT_ACCEPTED | ZMQ_EVENT_DISCONNECTED); void *monitor_socket = zmq_socket(zmq_context->getRawContext(), ZMQ_PAIR); zmq_connect(monitor_socket, addr.c_str()); @@ -107,7 +109,8 @@ void MsgqToZmq::zmqMonitorThread() { if (++pair.connected_clients == 1) { // Create new MSGQ subscriber socket and map to ZMQ publisher pair.sub_sock = std::make_unique(); - pair.sub_sock->connect(msgq_context.get(), pair.endpoint, "127.0.0.1"); + size_t queue_size = services.at(pair.endpoint).queue_size; + pair.sub_sock->connect(msgq_context.get(), pair.endpoint, "127.0.0.1", false, true, queue_size); sub2pub[pair.sub_sock.get()] = pair.pub_sock.get(); registerSockets(); } @@ -127,7 +130,7 @@ void MsgqToZmq::zmqMonitorThread() { // Clean up monitor sockets for (int i = 0; i < pollitems.size(); ++i) { - zmq_socket_monitor(socket_pairs[i].pub_sock->sock, nullptr, 0); + zmq_socket_monitor(socket_pairs[i].pub_sock->getRawSocket(), nullptr, 0); zmq_close(pollitems[i].socket); } cv.notify_one(); diff --git a/cereal/messaging/msgq_to_zmq.h b/cereal/messaging/msgq_to_zmq.h index ebdbe5df690e98..64f3a2173e7bea 100644 --- a/cereal/messaging/msgq_to_zmq.h +++ b/cereal/messaging/msgq_to_zmq.h @@ -7,9 +7,8 @@ #include #include -#define private public #include "msgq/impl_msgq.h" -#include "msgq/impl_zmq.h" +#include "cereal/messaging/bridge_zmq.h" class MsgqToZmq { public: @@ -22,16 +21,16 @@ class MsgqToZmq { struct SocketPair { std::string endpoint; - std::unique_ptr pub_sock; + std::unique_ptr pub_sock; std::unique_ptr sub_sock; int connected_clients = 0; }; - std::unique_ptr msgq_context; - std::unique_ptr zmq_context; + std::unique_ptr msgq_context; + std::unique_ptr zmq_context; std::mutex mutex; std::condition_variable cv; std::unique_ptr msgq_poller; - std::map sub2pub; + std::map sub2pub; std::vector socket_pairs; }; diff --git a/cereal/messaging/socketmaster.cc b/cereal/messaging/socketmaster.cc index 38b9842414ebb1..dfeeb807ee596f 100644 --- a/cereal/messaging/socketmaster.cc +++ b/cereal/messaging/socketmaster.cc @@ -33,8 +33,8 @@ MessageContext message_context; struct SubMaster::SubMessage { std::string name; SubSocket *socket = nullptr; - int freq = 0; - bool updated = false, alive = false, valid = true, ignore_alive; + float freq = 0.0f; + bool updated = false, alive = false, valid = false, ignore_alive; uint64_t rcv_time = 0, rcv_frame = 0; void *allocated_msg_reader = nullptr; bool is_polled = false; @@ -50,7 +50,7 @@ SubMaster::SubMaster(const std::vector &service_list, const std::v assert(services.count(std::string(name)) > 0); service serv = services.at(std::string(name)); - SubSocket *socket = SubSocket::create(message_context.context(), name, address ? address : "127.0.0.1", true); + SubSocket *socket = SubSocket::create(message_context.context(), name, address ? address : "127.0.0.1", true, true, serv.queue_size); assert(socket != 0); bool is_polled = inList(poll, name) || poll.empty(); if (is_polled) poller_->registerSocket(socket); @@ -187,7 +187,8 @@ SubMaster::~SubMaster() { PubMaster::PubMaster(const std::vector &service_list) { for (auto name : service_list) { assert(services.count(name) > 0); - PubSocket *socket = PubSocket::create(message_context.context(), name); + service serv = services.at(std::string(name)); + PubSocket *socket = PubSocket::create(message_context.context(), name, true, serv.queue_size); assert(socket); sockets_[name] = socket; } diff --git a/cereal/messaging/tests/test_messaging.py b/cereal/messaging/tests/test_messaging.py index 58fa7f7b28c093..afdab8a51f4bdb 100644 --- a/cereal/messaging/tests/test_messaging.py +++ b/cereal/messaging/tests/test_messaging.py @@ -5,7 +5,7 @@ import random import threading import time -from parameterized import parameterized +from openpilot.common.parameterized import parameterized import pytest from cereal import log, car @@ -30,7 +30,7 @@ def zmq_sleep(t=1): # TODO: this should take any capnp struct and returrn a msg with random populated data def random_carstate(): - fields = ["vEgo", "aEgo", "gas", "steeringAngleDeg"] + fields = ["vEgo", "aEgo", "brake", "steeringAngleDeg"] msg = messaging.new_message("carState") cs = msg.carState for f in fields: @@ -168,18 +168,18 @@ def test_recv_one_retry(self): # this test doesn't work with ZMQ since multiprocessing interrupts it if "ZMQ" not in os.environ: - # wait 15 socket timeouts and make sure it's still retrying + # wait 5 socket timeouts and make sure it's still retrying p = multiprocessing.Process(target=messaging.recv_one_retry, args=(sub_sock,)) p.start() - time.sleep(sock_timeout*15) + time.sleep(sock_timeout*5) assert p.is_alive() p.terminate() - # wait 15 socket timeouts before sending + # wait 5 socket timeouts before sending msg = random_carstate() - delayed_send(sock_timeout*15, pub_sock, msg.to_bytes()) start_time = time.monotonic() + delayed_send(sock_timeout*5, pub_sock, msg.to_bytes()) recvd = messaging.recv_one_retry(sub_sock) - assert (time.monotonic() - start_time) >= sock_timeout*15 + assert (time.monotonic() - start_time) >= sock_timeout*5 assert isinstance(recvd, capnp._DynamicStructReader) assert_carstate(msg.carState, recvd.carState) diff --git a/cereal/messaging/tests/test_pub_sub_master.py b/cereal/messaging/tests/test_pub_sub_master.py index 99965319eb03ed..5e26b49701e87a 100644 --- a/cereal/messaging/tests/test_pub_sub_master.py +++ b/cereal/messaging/tests/test_pub_sub_master.py @@ -6,6 +6,7 @@ from cereal.messaging.tests.test_messaging import events, random_sock, random_socks, \ random_bytes, random_carstate, assert_carstate, \ zmq_sleep +from cereal.services import SERVICE_LIST class TestSubMaster: @@ -26,7 +27,9 @@ def test_init_state(self): sm = messaging.SubMaster(socks) assert sm.frame == -1 assert not any(sm.updated.values()) - assert not any(sm.alive.values()) + assert not any(sm.seen.values()) + on_demand = {s: SERVICE_LIST[s].frequency <= 1e-5 for s in sm.services} + assert all(sm.alive[s] == sm.valid[s] == sm.freq_ok[s] == on_demand[s] for s in sm.services) assert all(t == 0. for t in sm.recv_time.values()) assert all(f == 0 for f in sm.recv_frame.values()) assert all(t == 0 for t in sm.logMonoTime.values()) @@ -63,14 +66,13 @@ def test_update(self): def test_update_timeout(self): sock = random_sock() sm = messaging.SubMaster([sock,]) - for _ in range(5): - timeout = random.randrange(1000, 5000) - start_time = time.monotonic() - sm.update(timeout) - t = time.monotonic() - start_time - assert t >= timeout/1000. - assert t < 5 - assert not any(sm.updated.values()) + timeout = random.randrange(1000, 3000) + start_time = time.monotonic() + sm.update(timeout) + t = time.monotonic() - start_time + assert t >= timeout/1000. + assert t < 3 + assert not any(sm.updated.values()) def test_avg_frequency_checks(self): for poll in (True, False): @@ -84,6 +86,7 @@ def test_avg_frequency_checks(self): "cameraOdometry": (20, 10), "liveCalibration": (4, 4), "carParams": (None, None), + "userBookmark": (None, None), } for service, (max_freq, min_freq) in checks.items(): diff --git a/cereal/messaging/tests/test_services.py b/cereal/messaging/tests/test_services.py index 01e859a5a32ee1..3320723fec855b 100644 --- a/cereal/messaging/tests/test_services.py +++ b/cereal/messaging/tests/test_services.py @@ -1,7 +1,7 @@ import os import tempfile from typing import Dict -from parameterized import parameterized +from openpilot.common.parameterized import parameterized import cereal.services as services from cereal.services import SERVICE_LIST @@ -17,5 +17,5 @@ def test_services(self, s): def test_generated_header(self): with tempfile.NamedTemporaryFile(suffix=".h") as f: - ret = os.system(f"python3 {services.__file__} > {f.name} && clang++ {f.name}") + ret = os.system(f"python3 {services.__file__} > {f.name} && clang++ {f.name} -std=c++11") assert ret == 0, "generated services header is not valid C" diff --git a/cereal/services.py b/cereal/services.py index b50e47be608150..32846eab60cfd5 100755 --- a/cereal/services.py +++ b/cereal/services.py @@ -1,57 +1,64 @@ #!/usr/bin/env python3 +from enum import IntEnum from typing import Optional +# TODO: this should be automatically determined using the capnp schema +class QueueSize(IntEnum): + BIG = 10 * 1024 * 1024 # 10MB - video frames, large AI outputs + MEDIUM = 2 * 1024 * 1024 # 2MB - high freq (CAN), livestream + SMALL = 250 * 1024 # 250KB - most services + + class Service: - def __init__(self, should_log: bool, frequency: float, decimation: Optional[int] = None): + def __init__(self, should_log: bool, frequency: float, decimation: Optional[int] = None, + queue_size: QueueSize = QueueSize.SMALL): self.should_log = should_log self.frequency = frequency self.decimation = decimation + self.queue_size = queue_size _services: dict[str, tuple] = { # service: (should_log, frequency, qlog decimation (optional)) # note: the "EncodeIdx" packets will still be in the log "gyroscope": (True, 104., 104), - "gyroscope2": (True, 100., 100), "accelerometer": (True, 104., 104), - "accelerometer2": (True, 100., 100), - "magnetometer": (True, 25.), - "lightSensor": (True, 100., 100), "temperatureSensor": (True, 2., 200), - "temperatureSensor2": (True, 2., 200), - "gpsNMEA": (True, 9.), "deviceState": (True, 2., 1), - "can": (True, 100., 2053), # decimation gives ~3 msgs in a full segment - "controlsState": (True, 100., 10), + "touch": (True, 20., 1), + "can": (True, 100., 2053, QueueSize.BIG), # decimation gives ~3 msgs in a full segment + "controlsState": (True, 100., 10, QueueSize.MEDIUM), "selfdriveState": (True, 100., 10), "pandaStates": (True, 10., 1), "peripheralState": (True, 2., 1), "radarState": (True, 20., 5), "roadEncodeIdx": (False, 20., 1), "liveTracks": (True, 20.), - "sendcan": (True, 100., 139), - "logMessage": (True, 0.), - "errorLogMessage": (True, 0., 1), + "sendcan": (True, 100., 139, QueueSize.MEDIUM), + "logMessage": (True, 0., None, QueueSize.BIG), + "errorLogMessage": (True, 0., 1, QueueSize.BIG), "liveCalibration": (True, 4., 4), "liveTorqueParameters": (True, 4., 1), + "liveDelay": (True, 4., 1), "androidLog": (True, 0.), "carState": (True, 100., 10), "carControl": (True, 100., 10), "carOutput": (True, 100., 10), "longitudinalPlan": (True, 20., 10), - "procLog": (True, 0.5, 15), + "lateralManeuverPlan": (True, 20.), + "driverAssistance": (True, 20., 20), + "procLog": (True, 0.5, 15, QueueSize.BIG), "gpsLocationExternal": (True, 10., 10), "gpsLocation": (True, 1., 1), "ubloxGnss": (True, 10.), "qcomGnss": (True, 2.), - "gnssMeasurements": (True, 10., 10), "clocks": (True, 0.1, 1), "ubloxRaw": (True, 20.), "livePose": (True, 20., 4), "liveParameters": (True, 20., 5), "cameraOdometry": (True, 20., 10), - "thumbnail": (True, 0.2, 1), + "thumbnail": (True, 1 / 60., 1), "onroadEvents": (True, 1., 1), "carParams": (True, 0.02, 1), "roadCameraState": (True, 20., 20), @@ -62,32 +69,38 @@ def __init__(self, should_log: bool, frequency: float, decimation: Optional[int] "wideRoadEncodeIdx": (False, 20., 1), "wideRoadCameraState": (True, 20., 20), "drivingModelData": (True, 20., 10), - "modelV2": (True, 20.), + "modelV2": (True, 20., None, QueueSize.BIG), "managerState": (True, 2., 1), - "uploaderState": (True, 0., 1), - "navInstruction": (True, 1., 10), - "navRoute": (True, 0.), - "navThumbnail": (True, 0.), "qRoadEncodeIdx": (False, 20.), - "userFlag": (True, 0., 1), - "microphone": (True, 10., 10), + "userBookmark": (True, 0., 1), + "soundPressure": (True, 10., 10), + "rawAudioData": (False, 20.), + "bookmarkButton": (True, 0., 1), + "audioFeedback": (True, 0., 1), + "roadEncodeData": (False, 20., None, QueueSize.BIG), + "driverEncodeData": (False, 20., None, QueueSize.BIG), + "wideRoadEncodeData": (False, 20., None, QueueSize.BIG), + "qRoadEncodeData": (False, 20., None, QueueSize.BIG), # debug "uiDebug": (True, 0., 1), "testJoystick": (True, 0.), - "roadEncodeData": (False, 20.), - "driverEncodeData": (False, 20.), - "wideRoadEncodeData": (False, 20.), - "qRoadEncodeData": (False, 20.), + "alertDebug": (True, 20., 5), "livestreamWideRoadEncodeIdx": (False, 20.), "livestreamRoadEncodeIdx": (False, 20.), "livestreamDriverEncodeIdx": (False, 20.), - "livestreamWideRoadEncodeData": (False, 20.), - "livestreamRoadEncodeData": (False, 20.), - "livestreamDriverEncodeData": (False, 20.), + "livestreamWideRoadEncodeData": (False, 20., None, QueueSize.MEDIUM), + "livestreamRoadEncodeData": (False, 20., None, QueueSize.MEDIUM), + "livestreamDriverEncodeData": (False, 20., None, QueueSize.MEDIUM), + "liveMapDataNAP": (True, 2., 2), + "liveSpeedSignNAP": (True, 4., 4), + # Radar-rate cone line. Decimation 2 keeps ~4 Hz in the qlog. + "coneLineNAP": (True, 8., 2), + # On-demand obstacle samples. Frequency 0 is not health-checked. + # Decimation 1 keeps every published message in the qlog. + "pathObstacleNAP": (True, 0., 1), + "pathObstacleVisionNAP": (True, 0., 1), "customReservedRawData0": (True, 0.), - "customReservedRawData1": (True, 0.), - "customReservedRawData2": (True, 0.), } SERVICE_LIST = {name: Service(*vals) for idx, (name, vals) in enumerate(_services.items())} @@ -102,13 +115,13 @@ def build_header(): h += "#include \n" h += "#include \n" - h += "struct service { std::string name; bool should_log; int frequency; int decimation; };\n" + h += "struct service { std::string name; bool should_log; float frequency; int decimation; size_t queue_size; };\n" h += "static std::map services = {\n" for k, v in SERVICE_LIST.items(): should_log = "true" if v.should_log else "false" decimation = -1 if v.decimation is None else v.decimation - h += ' { "%s", {"%s", %s, %d, %d}},\n' % \ - (k, k, should_log, v.frequency, decimation) + h += ' { "%s", {"%s", %s, %f, %d, %d}},\n' % \ + (k, k, should_log, v.frequency, decimation, v.queue_size) h += "};\n" h += "#endif\n" diff --git a/codecov.yml b/codecov.yml deleted file mode 100644 index 519e7d1a38f49b..00000000000000 --- a/codecov.yml +++ /dev/null @@ -1,13 +0,0 @@ -comment: false -coverage: - status: - project: - default: - informational: true - patch: off - -ignore: - - "**/test_*.py" - - "selfdrive/test/**" - - "system/version.py" # codecov changes depending on if we are in a branch or not - - "tools" diff --git a/common/.gitignore b/common/.gitignore deleted file mode 100644 index ce1da4c53c0301..00000000000000 --- a/common/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.cpp diff --git a/common/SConscript b/common/SConscript index 829db6eeec0cc9..c9bd1c72d136c0 100644 --- a/common/SConscript +++ b/common/SConscript @@ -1,25 +1,14 @@ -Import('env', 'envCython', 'arch') +Import('env', 'envCython') common_libs = [ 'params.cc', 'swaglog.cc', 'util.cc', - 'i2c.cc', - 'watchdog.cc', - 'ratekeeper.cc' + 'ratekeeper.cc', ] -if arch != "Darwin": - common_libs.append('gpio.cc') - _common = env.Library('common', common_libs, LIBS="json11") - -files = [ - 'clutil.cc', -] - -_gpucommon = env.Library('gpucommon', files) -Export('_common', '_gpucommon') +Export('_common') if GetOption('extras'): env.Program('tests/test_common', @@ -29,11 +18,6 @@ if GetOption('extras'): # Cython bindings params_python = envCython.Program('params_pyx.so', 'params_pyx.pyx', LIBS=envCython['LIBS'] + [_common, 'zmq', 'json11']) -SConscript([ - 'transformations/SConscript', -]) - -Import('transformations_python') -common_python = [params_python, transformations_python] +common_python = [params_python] Export('common_python') diff --git a/common/api.py b/common/api.py new file mode 100644 index 00000000000000..ebf0290d154de7 --- /dev/null +++ b/common/api.py @@ -0,0 +1,62 @@ +import jwt +import os +import requests +from datetime import datetime, timedelta, UTC +from openpilot.system.hardware.hw import Paths +from openpilot.system.version import get_version + +API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') + +# name: jwt signature algorithm +KEYS = {"id_rsa": "RS256", + "id_ecdsa": "ES256"} + + +class Api: + def __init__(self, dongle_id): + self.dongle_id = dongle_id + self.jwt_algorithm, self.private_key, _ = get_key_pair() + + def get(self, *args, **kwargs): + return self.request('GET', *args, **kwargs) + + def post(self, *args, **kwargs): + return self.request('POST', *args, **kwargs) + + def request(self, method, endpoint, timeout=None, access_token=None, **params): + return api_get(endpoint, method=method, timeout=timeout, access_token=access_token, **params) + + def get_token(self, payload_extra=None, expiry_hours=1): + now = datetime.now(UTC).replace(tzinfo=None) + payload = { + 'identity': self.dongle_id, + 'nbf': now, + 'iat': now, + 'exp': now + timedelta(hours=expiry_hours) + } + if payload_extra is not None: + payload.update(payload_extra) + token = jwt.encode(payload, self.private_key, algorithm=self.jwt_algorithm) + if isinstance(token, bytes): + token = token.decode('utf8') + return token + + +def api_get(endpoint, method='GET', timeout=None, access_token=None, session=None, **params): + headers = {} + if access_token is not None: + headers['Authorization'] = "JWT " + access_token + + headers['User-Agent'] = "openpilot-" + get_version() + + # TODO: add session to Api + req = requests if session is None else session + return req.request(method, API_HOST + "/" + endpoint, timeout=timeout, headers=headers, params=params) + + +def get_key_pair() -> tuple[str, str, str] | tuple[None, None, None]: + for key in KEYS: + if os.path.isfile(Paths.persist_root() + f'/comma/{key}') and os.path.isfile(Paths.persist_root() + f'/comma/{key}.pub'): + with open(Paths.persist_root() + f'/comma/{key}') as private, open(Paths.persist_root() + f'/comma/{key}.pub') as public: + return KEYS[key], private.read(), public.read() + return None, None, None diff --git a/common/api/__init__.py b/common/api/__init__.py deleted file mode 100644 index ac231400a47cc7..00000000000000 --- a/common/api/__init__.py +++ /dev/null @@ -1,46 +0,0 @@ -import jwt -import os -import requests -from datetime import datetime, timedelta, UTC -from openpilot.system.hardware.hw import Paths -from openpilot.system.version import get_version - -API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') - -class Api: - def __init__(self, dongle_id): - self.dongle_id = dongle_id - with open(Paths.persist_root()+'/comma/id_rsa') as f: - self.private_key = f.read() - - def get(self, *args, **kwargs): - return self.request('GET', *args, **kwargs) - - def post(self, *args, **kwargs): - return self.request('POST', *args, **kwargs) - - def request(self, method, endpoint, timeout=None, access_token=None, **params): - return api_get(endpoint, method=method, timeout=timeout, access_token=access_token, **params) - - def get_token(self, expiry_hours=1): - now = datetime.now(UTC).replace(tzinfo=None) - payload = { - 'identity': self.dongle_id, - 'nbf': now, - 'iat': now, - 'exp': now + timedelta(hours=expiry_hours) - } - token = jwt.encode(payload, self.private_key, algorithm='RS256') - if isinstance(token, bytes): - token = token.decode('utf8') - return token - - -def api_get(endpoint, method='GET', timeout=None, access_token=None, **params): - headers = {} - if access_token is not None: - headers['Authorization'] = "JWT " + access_token - - headers['User-Agent'] = "openpilot-" + get_version() - - return requests.request(method, API_HOST + "/" + endpoint, timeout=timeout, headers=headers, params=params) diff --git a/common/clutil.cc b/common/clutil.cc deleted file mode 100644 index 4f2a783d3e6e46..00000000000000 --- a/common/clutil.cc +++ /dev/null @@ -1,200 +0,0 @@ -#include "common/clutil.h" - -#include -#include -#include - -#include "common/util.h" -#include "common/swaglog.h" - -namespace { // helper functions - -template -std::string get_info(Func get_info_func, Id id, Name param_name) { - size_t size = 0; - CL_CHECK(get_info_func(id, param_name, 0, NULL, &size)); - std::string info(size, '\0'); - CL_CHECK(get_info_func(id, param_name, size, info.data(), NULL)); - return info; -} -inline std::string get_platform_info(cl_platform_id id, cl_platform_info name) { return get_info(&clGetPlatformInfo, id, name); } -inline std::string get_device_info(cl_device_id id, cl_device_info name) { return get_info(&clGetDeviceInfo, id, name); } - -void cl_print_info(cl_platform_id platform, cl_device_id device) { - size_t work_group_size = 0; - cl_device_type device_type = 0; - clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(work_group_size), &work_group_size, NULL); - clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(device_type), &device_type, NULL); - const char *type_str = "Other..."; - switch (device_type) { - case CL_DEVICE_TYPE_CPU: type_str ="CL_DEVICE_TYPE_CPU"; break; - case CL_DEVICE_TYPE_GPU: type_str = "CL_DEVICE_TYPE_GPU"; break; - case CL_DEVICE_TYPE_ACCELERATOR: type_str = "CL_DEVICE_TYPE_ACCELERATOR"; break; - } - - LOGD("vendor: %s", get_platform_info(platform, CL_PLATFORM_VENDOR).c_str()); - LOGD("platform version: %s", get_platform_info(platform, CL_PLATFORM_VERSION).c_str()); - LOGD("profile: %s", get_platform_info(platform, CL_PLATFORM_PROFILE).c_str()); - LOGD("extensions: %s", get_platform_info(platform, CL_PLATFORM_EXTENSIONS).c_str()); - LOGD("name: %s", get_device_info(device, CL_DEVICE_NAME).c_str()); - LOGD("device version: %s", get_device_info(device, CL_DEVICE_VERSION).c_str()); - LOGD("max work group size: %zu", work_group_size); - LOGD("type = %d, %s", (int)device_type, type_str); -} - -void cl_print_build_errors(cl_program program, cl_device_id device) { - cl_build_status status; - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_STATUS, sizeof(status), &status, NULL); - size_t log_size; - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); - std::string log(log_size, '\0'); - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size, &log[0], NULL); - - LOGE("build failed; status=%d, log: %s", status, log.c_str()); -} - -} // namespace - -cl_device_id cl_get_device_id(cl_device_type device_type) { - cl_uint num_platforms = 0; - CL_CHECK(clGetPlatformIDs(0, NULL, &num_platforms)); - std::unique_ptr platform_ids = std::make_unique(num_platforms); - CL_CHECK(clGetPlatformIDs(num_platforms, &platform_ids[0], NULL)); - - for (size_t i = 0; i < num_platforms; ++i) { - LOGD("platform[%zu] CL_PLATFORM_NAME: %s", i, get_platform_info(platform_ids[i], CL_PLATFORM_NAME).c_str()); - - // Get first device - if (cl_device_id device_id = NULL; clGetDeviceIDs(platform_ids[i], device_type, 1, &device_id, NULL) == 0 && device_id) { - cl_print_info(platform_ids[i], device_id); - return device_id; - } - } - LOGE("No valid openCL platform found"); - assert(0); - return nullptr; -} - -cl_context cl_create_context(cl_device_id device_id) { - return CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); -} - -cl_program cl_program_from_file(cl_context ctx, cl_device_id device_id, const char* path, const char* args) { - return cl_program_from_source(ctx, device_id, util::read_file(path), args); -} - -cl_program cl_program_from_source(cl_context ctx, cl_device_id device_id, const std::string& src, const char* args) { - const char *csrc = src.c_str(); - cl_program prg = CL_CHECK_ERR(clCreateProgramWithSource(ctx, 1, &csrc, NULL, &err)); - if (int err = clBuildProgram(prg, 1, &device_id, args, NULL, NULL); err != 0) { - cl_print_build_errors(prg, device_id); - assert(0); - } - return prg; -} - -cl_program cl_program_from_binary(cl_context ctx, cl_device_id device_id, const uint8_t* binary, size_t length, const char* args) { - cl_program prg = CL_CHECK_ERR(clCreateProgramWithBinary(ctx, 1, &device_id, &length, &binary, NULL, &err)); - if (int err = clBuildProgram(prg, 1, &device_id, args, NULL, NULL); err != 0) { - cl_print_build_errors(prg, device_id); - assert(0); - } - return prg; -} - -// Given a cl code and return a string representation -#define CL_ERR_TO_STR(err) case err: return #err -const char* cl_get_error_string(int err) { - switch (err) { - CL_ERR_TO_STR(CL_SUCCESS); - CL_ERR_TO_STR(CL_DEVICE_NOT_FOUND); - CL_ERR_TO_STR(CL_DEVICE_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_COMPILER_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_MEM_OBJECT_ALLOCATION_FAILURE); - CL_ERR_TO_STR(CL_OUT_OF_RESOURCES); - CL_ERR_TO_STR(CL_OUT_OF_HOST_MEMORY); - CL_ERR_TO_STR(CL_PROFILING_INFO_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_MEM_COPY_OVERLAP); - CL_ERR_TO_STR(CL_IMAGE_FORMAT_MISMATCH); - CL_ERR_TO_STR(CL_IMAGE_FORMAT_NOT_SUPPORTED); - CL_ERR_TO_STR(CL_MAP_FAILURE); - CL_ERR_TO_STR(CL_MISALIGNED_SUB_BUFFER_OFFSET); - CL_ERR_TO_STR(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST); - CL_ERR_TO_STR(CL_COMPILE_PROGRAM_FAILURE); - CL_ERR_TO_STR(CL_LINKER_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_LINK_PROGRAM_FAILURE); - CL_ERR_TO_STR(CL_DEVICE_PARTITION_FAILED); - CL_ERR_TO_STR(CL_KERNEL_ARG_INFO_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_INVALID_VALUE); - CL_ERR_TO_STR(CL_INVALID_DEVICE_TYPE); - CL_ERR_TO_STR(CL_INVALID_PLATFORM); - CL_ERR_TO_STR(CL_INVALID_DEVICE); - CL_ERR_TO_STR(CL_INVALID_CONTEXT); - CL_ERR_TO_STR(CL_INVALID_QUEUE_PROPERTIES); - CL_ERR_TO_STR(CL_INVALID_COMMAND_QUEUE); - CL_ERR_TO_STR(CL_INVALID_HOST_PTR); - CL_ERR_TO_STR(CL_INVALID_MEM_OBJECT); - CL_ERR_TO_STR(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR); - CL_ERR_TO_STR(CL_INVALID_IMAGE_SIZE); - CL_ERR_TO_STR(CL_INVALID_SAMPLER); - CL_ERR_TO_STR(CL_INVALID_BINARY); - CL_ERR_TO_STR(CL_INVALID_BUILD_OPTIONS); - CL_ERR_TO_STR(CL_INVALID_PROGRAM); - CL_ERR_TO_STR(CL_INVALID_PROGRAM_EXECUTABLE); - CL_ERR_TO_STR(CL_INVALID_KERNEL_NAME); - CL_ERR_TO_STR(CL_INVALID_KERNEL_DEFINITION); - CL_ERR_TO_STR(CL_INVALID_KERNEL); - CL_ERR_TO_STR(CL_INVALID_ARG_INDEX); - CL_ERR_TO_STR(CL_INVALID_ARG_VALUE); - CL_ERR_TO_STR(CL_INVALID_ARG_SIZE); - CL_ERR_TO_STR(CL_INVALID_KERNEL_ARGS); - CL_ERR_TO_STR(CL_INVALID_WORK_DIMENSION); - CL_ERR_TO_STR(CL_INVALID_WORK_GROUP_SIZE); - CL_ERR_TO_STR(CL_INVALID_WORK_ITEM_SIZE); - CL_ERR_TO_STR(CL_INVALID_GLOBAL_OFFSET); - CL_ERR_TO_STR(CL_INVALID_EVENT_WAIT_LIST); - CL_ERR_TO_STR(CL_INVALID_EVENT); - CL_ERR_TO_STR(CL_INVALID_OPERATION); - CL_ERR_TO_STR(CL_INVALID_GL_OBJECT); - CL_ERR_TO_STR(CL_INVALID_BUFFER_SIZE); - CL_ERR_TO_STR(CL_INVALID_MIP_LEVEL); - CL_ERR_TO_STR(CL_INVALID_GLOBAL_WORK_SIZE); - CL_ERR_TO_STR(CL_INVALID_PROPERTY); - CL_ERR_TO_STR(CL_INVALID_IMAGE_DESCRIPTOR); - CL_ERR_TO_STR(CL_INVALID_COMPILER_OPTIONS); - CL_ERR_TO_STR(CL_INVALID_LINKER_OPTIONS); - CL_ERR_TO_STR(CL_INVALID_DEVICE_PARTITION_COUNT); - case -69: return "CL_INVALID_PIPE_SIZE"; - case -70: return "CL_INVALID_DEVICE_QUEUE"; - case -71: return "CL_INVALID_SPEC_ID"; - case -72: return "CL_MAX_SIZE_RESTRICTION_EXCEEDED"; - case -1002: return "CL_INVALID_D3D10_DEVICE_KHR"; - case -1003: return "CL_INVALID_D3D10_RESOURCE_KHR"; - case -1004: return "CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR"; - case -1005: return "CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR"; - case -1006: return "CL_INVALID_D3D11_DEVICE_KHR"; - case -1007: return "CL_INVALID_D3D11_RESOURCE_KHR"; - case -1008: return "CL_D3D11_RESOURCE_ALREADY_ACQUIRED_KHR"; - case -1009: return "CL_D3D11_RESOURCE_NOT_ACQUIRED_KHR"; - case -1010: return "CL_INVALID_DX9_MEDIA_ADAPTER_KHR"; - case -1011: return "CL_INVALID_DX9_MEDIA_SURFACE_KHR"; - case -1012: return "CL_DX9_MEDIA_SURFACE_ALREADY_ACQUIRED_KHR"; - case -1013: return "CL_DX9_MEDIA_SURFACE_NOT_ACQUIRED_KHR"; - case -1093: return "CL_INVALID_EGL_OBJECT_KHR"; - case -1092: return "CL_EGL_RESOURCE_NOT_ACQUIRED_KHR"; - case -1001: return "CL_PLATFORM_NOT_FOUND_KHR"; - case -1057: return "CL_DEVICE_PARTITION_FAILED_EXT"; - case -1058: return "CL_INVALID_PARTITION_COUNT_EXT"; - case -1059: return "CL_INVALID_PARTITION_NAME_EXT"; - case -1094: return "CL_INVALID_ACCELERATOR_INTEL"; - case -1095: return "CL_INVALID_ACCELERATOR_TYPE_INTEL"; - case -1096: return "CL_INVALID_ACCELERATOR_DESCRIPTOR_INTEL"; - case -1097: return "CL_ACCELERATOR_TYPE_NOT_SUPPORTED_INTEL"; - case -1000: return "CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR"; - case -1098: return "CL_INVALID_VA_API_MEDIA_ADAPTER_INTEL"; - case -1099: return "CL_INVALID_VA_API_MEDIA_SURFACE_INTEL"; - case -1100: return "CL_VA_API_MEDIA_SURFACE_ALREADY_ACQUIRED_INTEL"; - case -1101: return "CL_VA_API_MEDIA_SURFACE_NOT_ACQUIRED_INTEL"; - default: return "CL_UNKNOWN_ERROR"; - } -} diff --git a/common/clutil.h b/common/clutil.h deleted file mode 100644 index af986d64343fcf..00000000000000 --- a/common/clutil.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include - -#define CL_CHECK(_expr) \ - do { \ - assert(CL_SUCCESS == (_expr)); \ - } while (0) - -#define CL_CHECK_ERR(_expr) \ - ({ \ - cl_int err = CL_INVALID_VALUE; \ - __typeof__(_expr) _ret = _expr; \ - assert(_ret&& err == CL_SUCCESS); \ - _ret; \ - }) - -cl_device_id cl_get_device_id(cl_device_type device_type); -cl_context cl_create_context(cl_device_id device_id); -cl_program cl_program_from_source(cl_context ctx, cl_device_id device_id, const std::string& src, const char* args = nullptr); -cl_program cl_program_from_binary(cl_context ctx, cl_device_id device_id, const uint8_t* binary, size_t length, const char* args = nullptr); -cl_program cl_program_from_file(cl_context ctx, cl_device_id device_id, const char* path, const char* args); -const char* cl_get_error_string(int err); diff --git a/common/constants.py b/common/constants.py new file mode 100644 index 00000000000000..7ca425c4b2430a --- /dev/null +++ b/common/constants.py @@ -0,0 +1,23 @@ +import numpy as np + +# conversions +class CV: + # Speed + MPH_TO_KPH = 1.609344 + KPH_TO_MPH = 1. / MPH_TO_KPH + MS_TO_KPH = 3.6 + KPH_TO_MS = 1. / MS_TO_KPH + MS_TO_MPH = MS_TO_KPH * KPH_TO_MPH + MPH_TO_MS = MPH_TO_KPH * KPH_TO_MS + MS_TO_KNOTS = 1.9438 + KNOTS_TO_MS = 1. / MS_TO_KNOTS + + # Angle + DEG_TO_RAD = np.pi / 180. + RAD_TO_DEG = 1. / DEG_TO_RAD + + # Mass + LB_TO_KG = 0.453592 + + +ACCELERATION_DUE_TO_GRAVITY = 9.81 # m/s^2 diff --git a/common/conversions.py b/common/conversions.py deleted file mode 100644 index b02b33c625a73f..00000000000000 --- a/common/conversions.py +++ /dev/null @@ -1,19 +0,0 @@ -import numpy as np - -class Conversions: - # Speed - MPH_TO_KPH = 1.609344 - KPH_TO_MPH = 1. / MPH_TO_KPH - MS_TO_KPH = 3.6 - KPH_TO_MS = 1. / MS_TO_KPH - MS_TO_MPH = MS_TO_KPH * KPH_TO_MPH - MPH_TO_MS = MPH_TO_KPH * KPH_TO_MS - MS_TO_KNOTS = 1.9438 - KNOTS_TO_MS = 1. / MS_TO_KNOTS - - # Angle - DEG_TO_RAD = np.pi / 180. - RAD_TO_DEG = 1. / DEG_TO_RAD - - # Mass - LB_TO_KG = 0.453592 diff --git a/common/dict_helpers.py b/common/dict_helpers.py deleted file mode 100644 index 62cff63b58ebb7..00000000000000 --- a/common/dict_helpers.py +++ /dev/null @@ -1,9 +0,0 @@ -# remove all keys that end in DEPRECATED -def strip_deprecated_keys(d): - for k in list(d.keys()): - if isinstance(k, str): - if k.endswith('DEPRECATED'): - d.pop(k) - elif isinstance(d[k], dict): - strip_deprecated_keys(d[k]) - return d diff --git a/common/ffi_wrapper.py b/common/ffi_wrapper.py deleted file mode 100644 index 01741c6f423a54..00000000000000 --- a/common/ffi_wrapper.py +++ /dev/null @@ -1,8 +0,0 @@ -import platform - - -def suffix(): - if platform.system() == "Darwin": - return ".dylib" - else: - return ".so" diff --git a/common/file_chunker.py b/common/file_chunker.py new file mode 100755 index 00000000000000..57dfc3553107a9 --- /dev/null +++ b/common/file_chunker.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +import sys +import math +import os +from pathlib import Path + +CHUNK_SIZE = 45 * 1024 * 1024 # 45MB, under GitHub's 50MB limit + +def get_chunk_name(name, idx, num_chunks): + return f"{name}.chunk{idx+1:02d}of{num_chunks:02d}" + +def get_manifest_path(name): + return f"{name}.chunkmanifest" + +def _chunk_paths(path, num_chunks): + return [get_manifest_path(path)] + [get_chunk_name(path, i, num_chunks) for i in range(num_chunks)] + +def get_chunk_targets(path, file_size): + num_chunks = math.ceil(file_size / CHUNK_SIZE) + return _chunk_paths(path, num_chunks) + +def chunk_file(path, targets): + manifest_path, *chunk_paths = targets + with open(path, 'rb') as f: + data = f.read() + actual_num_chunks = max(1, math.ceil(len(data) / CHUNK_SIZE)) + assert len(chunk_paths) >= actual_num_chunks, f"Allowed {len(chunk_paths)} chunks but needs at least {actual_num_chunks}, for path {path}" + for i, chunk_path in enumerate(chunk_paths): + with open(chunk_path, 'wb') as f: + f.write(data[i * CHUNK_SIZE:(i + 1) * CHUNK_SIZE]) + Path(manifest_path).write_text(str(len(chunk_paths))) + os.remove(path) + +def get_existing_chunks(path): + if os.path.isfile(path): + return [path] + if os.path.isfile(manifest := get_manifest_path(path)): + num_chunks = int(Path(manifest).read_text().strip()) + return _chunk_paths(path, num_chunks) + raise FileNotFoundError(path) + +def read_file_chunked(path): + manifest_path = get_manifest_path(path) + if os.path.isfile(manifest_path): + num_chunks = int(Path(manifest_path).read_text().strip()) + return b''.join(Path(get_chunk_name(path, i, num_chunks)).read_bytes() for i in range(num_chunks)) + if os.path.isfile(path): + return Path(path).read_bytes() + raise FileNotFoundError(path) + + +if __name__ == "__main__": + path = sys.argv[1] + chunk_paths = get_chunk_targets(path, os.path.getsize(path)) + chunk_file(path, chunk_paths) diff --git a/common/file_helpers.py b/common/file_helpers.py deleted file mode 100644 index 29ad219c076600..00000000000000 --- a/common/file_helpers.py +++ /dev/null @@ -1,37 +0,0 @@ -import os -import tempfile -import contextlib - - -class CallbackReader: - """Wraps a file, but overrides the read method to also - call a callback function with the number of bytes read so far.""" - def __init__(self, f, callback, *args): - self.f = f - self.callback = callback - self.cb_args = args - self.total_read = 0 - - def __getattr__(self, attr): - return getattr(self.f, attr) - - def read(self, *args, **kwargs): - chunk = self.f.read(*args, **kwargs) - self.total_read += len(chunk) - self.callback(*self.cb_args, self.total_read) - return chunk - - -@contextlib.contextmanager -def atomic_write_in_dir(path: str, mode: str = 'w', buffering: int = -1, encoding: str = None, newline: str = None, - overwrite: bool = False): - """Write to a file atomically using a temporary file in the same directory as the destination file.""" - dir_name = os.path.dirname(path) - - if not overwrite and os.path.exists(path): - raise FileExistsError(f"File '{path}' already exists. To overwrite it, set 'overwrite' to True.") - - with tempfile.NamedTemporaryFile(mode=mode, buffering=buffering, encoding=encoding, newline=newline, dir=dir_name, delete=False) as tmp_file: - yield tmp_file - tmp_file_name = tmp_file.name - os.replace(tmp_file_name, path) diff --git a/common/filter_simple.py b/common/filter_simple.py index 0ec7a515621afb..b28c3d68f59463 100644 --- a/common/filter_simple.py +++ b/common/filter_simple.py @@ -1,5 +1,4 @@ class FirstOrderFilter: - # first order filter def __init__(self, x0, rc, dt, initialized=True): self.x = x0 self.dt = dt @@ -16,3 +15,20 @@ def update(self, x): self.initialized = True self.x = x return self.x + + +class BounceFilter(FirstOrderFilter): + def __init__(self, x0, rc, dt, initialized=True, bounce=2): + self.velocity = FirstOrderFilter(0.0, 0.15, dt) + self.bounce = bounce + super().__init__(x0, rc, dt, initialized) + + def update(self, x): + super().update(x) + scale = self.dt / (1.0 / 60.0) # tuned at 60 fps + self.velocity.x += (x - self.x) * self.bounce * scale * self.dt + self.velocity.update(0.0) + if abs(self.velocity.x) < 1e-3: + self.velocity.x = 0.0 + self.x += self.velocity.x + return self.x diff --git a/common/git.py b/common/git.py index 4406bf96b10c77..6b662e57191d03 100644 --- a/common/git.py +++ b/common/git.py @@ -1,30 +1,30 @@ from functools import cache import subprocess -from openpilot.common.run import run_cmd, run_cmd_default +from openpilot.common.utils import run_cmd, run_cmd_default @cache -def get_commit(cwd: str = None, branch: str = "HEAD") -> str: +def get_commit(cwd: str | None = None, branch: str = "HEAD") -> str: return run_cmd_default(["git", "rev-parse", branch], cwd=cwd) @cache -def get_commit_date(cwd: str = None, commit: str = "HEAD") -> str: +def get_commit_date(cwd: str | None = None, commit: str = "HEAD") -> str: return run_cmd_default(["git", "show", "--no-patch", "--format='%ct %ci'", commit], cwd=cwd) @cache -def get_short_branch(cwd: str = None) -> str: +def get_short_branch(cwd: str | None = None) -> str: return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=cwd) @cache -def get_branch(cwd: str = None) -> str: +def get_branch(cwd: str | None = None) -> str: return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], cwd=cwd) @cache -def get_origin(cwd: str = None) -> str: +def get_origin(cwd: str | None = None) -> str: try: local_branch = run_cmd(["git", "name-rev", "--name-only", "HEAD"], cwd=cwd) tracking_remote = run_cmd(["git", "config", "branch." + local_branch + ".remote"], cwd=cwd) @@ -34,7 +34,7 @@ def get_origin(cwd: str = None) -> str: @cache -def get_normalized_origin(cwd: str = None) -> str: +def get_normalized_origin(cwd: str | None = None) -> str: return get_origin(cwd) \ .replace("git@", "", 1) \ .replace(".git", "", 1) \ diff --git a/common/gpio.cc b/common/gpio.cc deleted file mode 100644 index dd7ba34b6d3fc3..00000000000000 --- a/common/gpio.cc +++ /dev/null @@ -1,84 +0,0 @@ -#include "common/gpio.h" - -#include - -#ifdef __APPLE__ -int gpio_init(int pin_nr, bool output) { - return 0; -} - -int gpio_set(int pin_nr, bool high) { - return 0; -} - -int gpiochip_get_ro_value_fd(const char* consumer_label, int gpiochiop_id, int pin_nr) { - return 0; -} - -#else - -#include -#include - -#include -#include -#include - -#include "common/util.h" -#include "common/swaglog.h" - -int gpio_init(int pin_nr, bool output) { - char pin_dir_path[50]; - int pin_dir_path_len = snprintf(pin_dir_path, sizeof(pin_dir_path), - "/sys/class/gpio/gpio%d/direction", pin_nr); - if (pin_dir_path_len <= 0) { - return -1; - } - const char *value = output ? "out" : "in"; - return util::write_file(pin_dir_path, (void*)value, strlen(value)); -} - -int gpio_set(int pin_nr, bool high) { - char pin_val_path[50]; - int pin_val_path_len = snprintf(pin_val_path, sizeof(pin_val_path), - "/sys/class/gpio/gpio%d/value", pin_nr); - if (pin_val_path_len <= 0) { - return -1; - } - return util::write_file(pin_val_path, (void*)(high ? "1" : "0"), 1); -} - -int gpiochip_get_ro_value_fd(const char* consumer_label, int gpiochiop_id, int pin_nr) { - - // Assumed that all interrupt pins are unexported and rights are given to - // read from gpiochip0. - std::string gpiochip_path = "/dev/gpiochip" + std::to_string(gpiochiop_id); - int fd = open(gpiochip_path.c_str(), O_RDONLY); - if (fd < 0) { - LOGE("Error opening gpiochip0 fd"); - return -1; - } - - // Setup event - struct gpioevent_request rq; - rq.lineoffset = pin_nr; - rq.handleflags = GPIOHANDLE_REQUEST_INPUT; - - /* Requesting both edges as the data ready pulse from the lsm6ds sensor is - very short(75us) and is mostly detected as falling edge instead of rising. - So if it is detected as rising the following falling edge is skipped. */ - rq.eventflags = GPIOEVENT_REQUEST_BOTH_EDGES; - - strncpy(rq.consumer_label, consumer_label, std::size(rq.consumer_label) - 1); - int ret = util::safe_ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, &rq); - if (ret == -1) { - LOGE("Unable to get line event from ioctl : %s", strerror(errno)); - close(fd); - return -1; - } - - close(fd); - return rq.fd; -} - -#endif diff --git a/common/gpio.h b/common/gpio.h deleted file mode 100644 index 89cdedd66c9ce8..00000000000000 --- a/common/gpio.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -// Pin definitions -#ifdef QCOM2 - #define GPIO_HUB_RST_N 30 - #define GPIO_UBLOX_RST_N 32 - #define GPIO_UBLOX_SAFEBOOT_N 33 - #define GPIO_GNSS_PWR_EN 34 /* SCHEMATIC LABEL: GPIO_UBLOX_PWR_EN */ - #define GPIO_STM_RST_N 124 - #define GPIO_STM_BOOT0 134 - #define GPIO_BMX_ACCEL_INT 21 - #define GPIO_BMX_GYRO_INT 23 - #define GPIO_BMX_MAGN_INT 87 - #define GPIO_LSM_INT 84 - #define GPIOCHIP_INT 0 -#else - #define GPIO_HUB_RST_N 0 - #define GPIO_UBLOX_RST_N 0 - #define GPIO_UBLOX_SAFEBOOT_N 0 - #define GPIO_GNSS_PWR_EN 0 /* SCHEMATIC LABEL: GPIO_UBLOX_PWR_EN */ - #define GPIO_STM_RST_N 0 - #define GPIO_STM_BOOT0 0 - #define GPIO_BMX_ACCEL_INT 0 - #define GPIO_BMX_GYRO_INT 0 - #define GPIO_BMX_MAGN_INT 0 - #define GPIO_LSM_INT 0 - #define GPIOCHIP_INT 0 -#endif - -int gpio_init(int pin_nr, bool output); -int gpio_set(int pin_nr, bool high); - -int gpiochip_get_ro_value_fd(const char* consumer_label, int gpiochiop_id, int pin_nr); diff --git a/common/gpio.py b/common/gpio.py index 66b2adf438e653..8f025a2daf726e 100644 --- a/common/gpio.py +++ b/common/gpio.py @@ -1,4 +1,6 @@ import os +import fcntl +import ctypes from functools import cache def gpio_init(pin: int, output: bool) -> None: @@ -52,3 +54,36 @@ def get_irqs_for_action(action: str) -> list[str]: if irq.isdigit() and action in get_irq_action(irq): ret.append(irq) return ret + +# *** gpiochip *** + +class gpioevent_data(ctypes.Structure): + _fields_ = [ + ("timestamp", ctypes.c_uint64), + ("id", ctypes.c_uint32), + ] + +class gpioevent_request(ctypes.Structure): + _fields_ = [ + ("lineoffset", ctypes.c_uint32), + ("handleflags", ctypes.c_uint32), + ("eventflags", ctypes.c_uint32), + ("label", ctypes.c_char * 32), + ("fd", ctypes.c_int) + ] + +def gpiochip_get_ro_value_fd(label: str, gpiochip_id: int, pin: int) -> int: + GPIOEVENT_REQUEST_BOTH_EDGES = 0x3 + GPIOHANDLE_REQUEST_INPUT = 0x1 + GPIO_GET_LINEEVENT_IOCTL = 0xc030b404 + + rq = gpioevent_request() + rq.lineoffset = pin + rq.handleflags = GPIOHANDLE_REQUEST_INPUT + rq.eventflags = GPIOEVENT_REQUEST_BOTH_EDGES + rq.label = label.encode('utf-8')[:31] + b'\0' + + fd = os.open(f"/dev/gpiochip{gpiochip_id}", os.O_RDONLY) + fcntl.ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, rq) + os.close(fd) + return int(rq.fd) diff --git a/common/i2c.cc b/common/i2c.cc deleted file mode 100644 index 3d6c79efc5384b..00000000000000 --- a/common/i2c.cc +++ /dev/null @@ -1,92 +0,0 @@ -#include "common/i2c.h" - -#include -#include -#include - -#include -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" - -#define UNUSED(x) (void)(x) - -#ifdef QCOM2 -// TODO: decide if we want to install libi2c-dev everywhere -extern "C" { - #include - #include -} - -I2CBus::I2CBus(uint8_t bus_id) { - char bus_name[20]; - snprintf(bus_name, 20, "/dev/i2c-%d", bus_id); - - i2c_fd = HANDLE_EINTR(open(bus_name, O_RDWR)); - if (i2c_fd < 0) { - throw std::runtime_error("Failed to open I2C bus"); - } -} - -I2CBus::~I2CBus() { - if (i2c_fd >= 0) { - close(i2c_fd); - } -} - -int I2CBus::read_register(uint8_t device_address, uint register_address, uint8_t *buffer, uint8_t len) { - std::lock_guard lk(m); - - int ret = 0; - - ret = HANDLE_EINTR(ioctl(i2c_fd, I2C_SLAVE, device_address)); - if (ret < 0) { goto fail; } - - ret = i2c_smbus_read_i2c_block_data(i2c_fd, register_address, len, buffer); - if ((ret < 0) || (ret != len)) { goto fail; } - -fail: - return ret; -} - -int I2CBus::set_register(uint8_t device_address, uint register_address, uint8_t data) { - std::lock_guard lk(m); - - int ret = 0; - - ret = HANDLE_EINTR(ioctl(i2c_fd, I2C_SLAVE, device_address)); - if (ret < 0) { goto fail; } - - ret = i2c_smbus_write_byte_data(i2c_fd, register_address, data); - if (ret < 0) { goto fail; } - -fail: - return ret; -} - -#else - -I2CBus::I2CBus(uint8_t bus_id) { - UNUSED(bus_id); - i2c_fd = -1; -} - -I2CBus::~I2CBus() {} - -int I2CBus::read_register(uint8_t device_address, uint register_address, uint8_t *buffer, uint8_t len) { - UNUSED(device_address); - UNUSED(register_address); - UNUSED(buffer); - UNUSED(len); - return -1; -} - -int I2CBus::set_register(uint8_t device_address, uint register_address, uint8_t data) { - UNUSED(device_address); - UNUSED(register_address); - UNUSED(data); - return -1; -} -#endif diff --git a/common/i2c.h b/common/i2c.h deleted file mode 100644 index ca0d4635b890c9..00000000000000 --- a/common/i2c.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include - -#include - -class I2CBus { - private: - int i2c_fd; - std::mutex m; - - public: - I2CBus(uint8_t bus_id); - ~I2CBus(); - - int read_register(uint8_t device_address, uint register_address, uint8_t *buffer, uint8_t len); - int set_register(uint8_t device_address, uint register_address, uint8_t data); -}; diff --git a/common/i2c.py b/common/i2c.py new file mode 100644 index 00000000000000..1dfaa659ad302e --- /dev/null +++ b/common/i2c.py @@ -0,0 +1,81 @@ +import os +import fcntl +import ctypes + +# I2C constants from /usr/include/linux/i2c-dev.h +I2C_SLAVE = 0x0703 +I2C_SLAVE_FORCE = 0x0706 +I2C_SMBUS = 0x0720 + +# SMBus transfer types +I2C_SMBUS_READ = 1 +I2C_SMBUS_WRITE = 0 +I2C_SMBUS_BYTE_DATA = 2 +I2C_SMBUS_I2C_BLOCK_DATA = 8 + +I2C_SMBUS_BLOCK_MAX = 32 + + +class _I2cSmbusData(ctypes.Union): + _fields_ = [ + ("byte", ctypes.c_uint8), + ("word", ctypes.c_uint16), + ("block", ctypes.c_uint8 * (I2C_SMBUS_BLOCK_MAX + 2)), + ] + + +class _I2cSmbusIoctlData(ctypes.Structure): + _fields_ = [ + ("read_write", ctypes.c_uint8), + ("command", ctypes.c_uint8), + ("size", ctypes.c_uint32), + ("data", ctypes.POINTER(_I2cSmbusData)), + ] + + +class SMBus: + def __init__(self, bus: int): + self._fd = os.open(f'/dev/i2c-{bus}', os.O_RDWR) + + def __enter__(self) -> 'SMBus': + return self + + def __exit__(self, *args) -> None: + self.close() + + def close(self) -> None: + if hasattr(self, '_fd') and self._fd >= 0: + os.close(self._fd) + self._fd = -1 + + def _set_address(self, addr: int, force: bool = False) -> None: + ioctl_arg = I2C_SLAVE_FORCE if force else I2C_SLAVE + fcntl.ioctl(self._fd, ioctl_arg, addr) + + def _smbus_access(self, read_write: int, command: int, size: int, data: _I2cSmbusData) -> None: + ioctl_data = _I2cSmbusIoctlData(read_write, command, size, ctypes.pointer(data)) + fcntl.ioctl(self._fd, I2C_SMBUS, ioctl_data) + + def read_byte_data(self, addr: int, register: int, force: bool = False) -> int: + self._set_address(addr, force) + data = _I2cSmbusData() + self._smbus_access(I2C_SMBUS_READ, register, I2C_SMBUS_BYTE_DATA, data) + return int(data.byte) + + def write_byte_data(self, addr: int, register: int, value: int, force: bool = False) -> None: + self._set_address(addr, force) + data = _I2cSmbusData() + data.byte = value & 0xFF + self._smbus_access(I2C_SMBUS_WRITE, register, I2C_SMBUS_BYTE_DATA, data) + + def read_i2c_block_data(self, addr: int, register: int, length: int, force: bool = False) -> list[int]: + self._set_address(addr, force) + if not (0 <= length <= I2C_SMBUS_BLOCK_MAX): + raise ValueError(f"length must be 0..{I2C_SMBUS_BLOCK_MAX}") + + data = _I2cSmbusData() + data.block[0] = length + self._smbus_access(I2C_SMBUS_READ, register, I2C_SMBUS_I2C_BLOCK_DATA, data) + read_len = int(data.block[0]) or length + read_len = min(read_len, length) + return [int(b) for b in data.block[1 : read_len + 1]] diff --git a/common/logging_extra.py b/common/logging_extra.py index f53d503108837d..ceaf083cd5c442 100644 --- a/common/logging_extra.py +++ b/common/logging_extra.py @@ -8,6 +8,7 @@ import socket import logging import traceback +import numpy as np from threading import local from collections import OrderedDict from contextlib import contextmanager @@ -15,6 +16,8 @@ LOG_TIMESTAMPS = "LOG_TIMESTAMPS" in os.environ def json_handler(obj): + if isinstance(obj, np.bool_): + return bool(obj) # if isinstance(obj, (datetime.date, datetime.time)): # return obj.isoformat() return repr(obj) @@ -196,7 +199,6 @@ def findCaller(self, stack_info=False, stacklevel=1): co = f.f_code filename = os.path.normcase(co.co_filename) - # TODO: is this pylint exception correct? if filename == _srcfile: f = f.f_back continue diff --git a/common/mat.h b/common/mat.h deleted file mode 100644 index 8e10d619717ba3..00000000000000 --- a/common/mat.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once - -typedef struct vec3 { - float v[3]; -} vec3; - -typedef struct vec4 { - float v[4]; -} vec4; - -typedef struct mat3 { - float v[3*3]; -} mat3; - -typedef struct mat4 { - float v[4*4]; -} mat4; - -static inline mat3 matmul3(const mat3 &a, const mat3 &b) { - mat3 ret = {{0.0}}; - for (int r=0; r<3; r++) { - for (int c=0; c<3; c++) { - float v = 0.0; - for (int k=0; k<3; k++) { - v += a.v[r*3+k] * b.v[k*3+c]; - } - ret.v[r*3+c] = v; - } - } - return ret; -} - -static inline vec3 matvecmul3(const mat3 &a, const vec3 &b) { - vec3 ret = {{0.0}}; - for (int r=0; r<3; r++) { - for (int c=0; c<3; c++) { - ret.v[r] += a.v[r*3+c] * b.v[c]; - } - } - return ret; -} - -static inline mat4 matmul(const mat4 &a, const mat4 &b) { - mat4 ret = {{0.0}}; - for (int r=0; r<4; r++) { - for (int c=0; c<4; c++) { - float v = 0.0; - for (int k=0; k<4; k++) { - v += a.v[r*4+k] * b.v[k*4+c]; - } - ret.v[r*4+c] = v; - } - } - return ret; -} - -static inline vec4 matvecmul(const mat4 &a, const vec4 &b) { - vec4 ret = {{0.0}}; - for (int r=0; r<4; r++) { - for (int c=0; c<4; c++) { - ret.v[r] += a.v[r*4+c] * b.v[c]; - } - } - return ret; -} - -// scales the input and output space of a transformation matrix -// that assumes pixel-center origin. -static inline mat3 transform_scale_buffer(const mat3 &in, float s) { - // in_pt = ( transform(out_pt/s + 0.5) - 0.5) * s - - mat3 transform_out = {{ - 1.0f/s, 0.0f, 0.5f, - 0.0f, 1.0f/s, 0.5f, - 0.0f, 0.0f, 1.0f, - }}; - - mat3 transform_in = {{ - s, 0.0f, -0.5f*s, - 0.0f, s, -0.5f*s, - 0.0f, 0.0f, 1.0f, - }}; - - return matmul3(transform_in, matmul3(in, transform_out)); -} diff --git a/common/numpy_fast.py b/common/numpy_fast.py deleted file mode 100644 index 878c0005c8e811..00000000000000 --- a/common/numpy_fast.py +++ /dev/null @@ -1,19 +0,0 @@ -def clip(x, lo, hi): - return max(lo, min(hi, x)) - -def interp(x, xp, fp): - N = len(xp) - - def get_interp(xv): - hi = 0 - while hi < N and xv > xp[hi]: - hi += 1 - low = hi - 1 - return fp[-1] if hi == N and xv > xp[low] else ( - fp[0] if hi == 0 else - (xv - xp[low]) * (fp[hi] - fp[low]) / (xp[hi] - xp[low]) + fp[low]) - - return [get_interp(v) for v in x] if hasattr(x, '__iter__') else get_interp(x) - -def mean(x): - return sum(x) / len(x) diff --git a/common/parameterized.py b/common/parameterized.py new file mode 100644 index 00000000000000..7cd21bb9c5e4e6 --- /dev/null +++ b/common/parameterized.py @@ -0,0 +1,47 @@ +import sys +import pytest +import inspect + + +class parameterized: + @staticmethod + def expand(cases): + cases = list(cases) + + if not cases: + return lambda func: pytest.mark.skip("no parameterized cases")(func) + + def decorator(func): + params = [p for p in inspect.signature(func).parameters if p != 'self'] + normalized = [c if isinstance(c, tuple) else (c,) for c in cases] + # Infer arg count from first case so extra params (e.g. from @given) are left untouched + expand_params = params[: len(normalized[0])] + if len(expand_params) == 1: + return pytest.mark.parametrize(expand_params[0], [c[0] for c in normalized])(func) + return pytest.mark.parametrize(', '.join(expand_params), normalized)(func) + + return decorator + + +def parameterized_class(attrs, input_list=None): + if isinstance(attrs, list) and (not attrs or isinstance(attrs[0], dict)): + params_list = attrs + else: + assert input_list is not None + attr_names = (attrs,) if isinstance(attrs, str) else tuple(attrs) + params_list = [dict(zip(attr_names, v if isinstance(v, (tuple, list)) else (v,), strict=False)) for v in input_list] + + def decorator(cls): + globs = sys._getframe(1).f_globals + for i, params in enumerate(params_list): + name = f"{cls.__name__}_{i}" + new_cls = type(name, (cls,), dict(params)) + new_cls.__module__ = cls.__module__ + new_cls.__test__ = True # override inherited False so pytest collects this subclass + globs[name] = new_cls + # Don't collect the un-parametrised base, but return it so outer decorators + # (e.g. @pytest.mark.skip) land on it and propagate to subclasses via MRO. + cls.__test__ = False + return cls + + return decorator diff --git a/common/params.cc b/common/params.cc index 098e1de58e7476..6af00fe95c0109 100644 --- a/common/params.cc +++ b/common/params.cc @@ -8,6 +8,7 @@ #include #include +#include "common/params_keys.h" #include "common/queue.h" #include "common/swaglog.h" #include "common/util.h" @@ -87,119 +88,6 @@ class FileLock { int fd_ = -1; }; -std::unordered_map keys = { - {"AccessToken", CLEAR_ON_MANAGER_START | DONT_LOG}, - {"AlwaysOnDM", PERSISTENT}, - {"ApiCache_Device", PERSISTENT}, - {"AssistNowToken", PERSISTENT}, - {"AthenadPid", PERSISTENT}, - {"AthenadUploadQueue", PERSISTENT}, - {"AthenadRecentlyViewedRoutes", PERSISTENT}, - {"BootCount", PERSISTENT}, - {"CalibrationParams", PERSISTENT}, - {"CameraDebugExpGain", CLEAR_ON_MANAGER_START}, - {"CameraDebugExpTime", CLEAR_ON_MANAGER_START}, - {"CarBatteryCapacity", PERSISTENT}, - {"CarParams", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"CarParamsCache", CLEAR_ON_MANAGER_START}, - {"CarParamsPersistent", PERSISTENT}, - {"CarParamsPrevRoute", PERSISTENT}, - {"CompletedTrainingVersion", PERSISTENT}, - {"ControlsReady", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"CurrentBootlog", PERSISTENT}, - {"CurrentRoute", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"DisableLogging", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"DisablePowerDown", PERSISTENT}, - {"DisableUpdates", PERSISTENT}, - {"DisengageOnAccelerator", PERSISTENT}, - {"DmModelInitialized", CLEAR_ON_ONROAD_TRANSITION}, - {"DongleId", PERSISTENT}, - {"DoReboot", CLEAR_ON_MANAGER_START}, - {"DoShutdown", CLEAR_ON_MANAGER_START}, - {"DoUninstall", CLEAR_ON_MANAGER_START}, - {"ExperimentalLongitudinalEnabled", PERSISTENT | DEVELOPMENT_ONLY}, - {"ExperimentalMode", PERSISTENT}, - {"ExperimentalModeConfirmed", PERSISTENT}, - {"FirmwareQueryDone", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"ForcePowerDown", PERSISTENT}, - {"GitBranch", PERSISTENT}, - {"GitCommit", PERSISTENT}, - {"GitCommitDate", PERSISTENT}, - {"GitDiff", PERSISTENT}, - {"GithubSshKeys", PERSISTENT}, - {"GithubUsername", PERSISTENT}, - {"GitRemote", PERSISTENT}, - {"GsmApn", PERSISTENT}, - {"GsmMetered", PERSISTENT}, - {"GsmRoaming", PERSISTENT}, - {"HardwareSerial", PERSISTENT}, - {"HasAcceptedTerms", PERSISTENT}, - {"IMEI", PERSISTENT}, - {"InstallDate", PERSISTENT}, - {"IsDriverViewEnabled", CLEAR_ON_MANAGER_START}, - {"IsEngaged", PERSISTENT}, - {"IsLdwEnabled", PERSISTENT}, - {"IsMetric", PERSISTENT}, - {"IsOffroad", CLEAR_ON_MANAGER_START}, - {"IsOnroad", PERSISTENT}, - {"IsRhdDetected", PERSISTENT}, - {"IsReleaseBranch", CLEAR_ON_MANAGER_START}, - {"IsTakingSnapshot", CLEAR_ON_MANAGER_START}, - {"IsTestedBranch", CLEAR_ON_MANAGER_START}, - {"JoystickDebugMode", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"LanguageSetting", PERSISTENT}, - {"LastAthenaPingTime", CLEAR_ON_MANAGER_START}, - {"LastGPSPosition", PERSISTENT}, - {"LastManagerExitReason", CLEAR_ON_MANAGER_START}, - {"LastOffroadStatusPacket", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"LastPowerDropDetected", CLEAR_ON_MANAGER_START}, - {"LastUpdateException", CLEAR_ON_MANAGER_START}, - {"LastUpdateTime", PERSISTENT}, - {"LiveParameters", PERSISTENT}, - {"LiveTorqueParameters", PERSISTENT | DONT_LOG}, - {"LongitudinalPersonality", PERSISTENT}, - {"NetworkMetered", PERSISTENT}, - {"ObdMultiplexingChanged", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"ObdMultiplexingEnabled", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_BadNvme", CLEAR_ON_MANAGER_START}, - {"Offroad_CarUnrecognized", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_ConnectivityNeeded", CLEAR_ON_MANAGER_START}, - {"Offroad_ConnectivityNeededPrompt", CLEAR_ON_MANAGER_START}, - {"Offroad_IsTakingSnapshot", CLEAR_ON_MANAGER_START}, - {"Offroad_NeosUpdate", CLEAR_ON_MANAGER_START}, - {"Offroad_NoFirmware", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_Recalibration", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_StorageMissing", CLEAR_ON_MANAGER_START}, - {"Offroad_TemperatureTooHigh", CLEAR_ON_MANAGER_START}, - {"Offroad_UnofficialHardware", CLEAR_ON_MANAGER_START}, - {"Offroad_UpdateFailed", CLEAR_ON_MANAGER_START}, - {"OpenpilotEnabledToggle", PERSISTENT}, - {"PandaHeartbeatLost", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"PandaSomResetTriggered", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"PandaSignatures", CLEAR_ON_MANAGER_START}, - {"PrimeType", PERSISTENT}, - {"RecordFront", PERSISTENT}, - {"RecordFrontLock", PERSISTENT}, // for the internal fleet - {"RouteCount", PERSISTENT}, - {"SnoozeUpdate", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"SshEnabled", PERSISTENT}, - {"TermsVersion", PERSISTENT}, - {"TrainingVersion", PERSISTENT}, - {"UbloxAvailable", PERSISTENT}, - {"UpdateAvailable", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"UpdateFailedCount", CLEAR_ON_MANAGER_START}, - {"UpdaterAvailableBranches", PERSISTENT}, - {"UpdaterCurrentDescription", CLEAR_ON_MANAGER_START}, - {"UpdaterCurrentReleaseNotes", CLEAR_ON_MANAGER_START}, - {"UpdaterFetchAvailable", CLEAR_ON_MANAGER_START}, - {"UpdaterNewDescription", CLEAR_ON_MANAGER_START}, - {"UpdaterNewReleaseNotes", CLEAR_ON_MANAGER_START}, - {"UpdaterState", CLEAR_ON_MANAGER_START}, - {"UpdaterTargetBranch", CLEAR_ON_MANAGER_START}, - {"UpdaterLastFetchTime", PERSISTENT}, - {"Version", PERSISTENT}, -}; - } // namespace @@ -227,8 +115,16 @@ bool Params::checkKey(const std::string &key) { return keys.find(key) != keys.end(); } +ParamKeyFlag Params::getKeyFlag(const std::string &key) { + return static_cast(keys[key].flags); +} + ParamKeyType Params::getKeyType(const std::string &key) { - return static_cast(keys[key]); + return keys[key].type; +} + +std::optional Params::getKeyDefaultValue(const std::string &key) { + return keys[key].default_value; } int Params::put(const char* key, const char* value, size_t value_size) { @@ -252,7 +148,7 @@ int Params::put(const char* key, const char* value, size_t value_size) { } // fsync to force persist the changes. - if ((result = fsync(tmp_fd)) < 0) break; + if ((result = HANDLE_EINTR(fsync(tmp_fd))) < 0) break; FileLock file_lock(params_path + "/.lock"); @@ -307,17 +203,17 @@ std::map Params::readAll() { return util::read_files_in_dir(getParamPath()); } -void Params::clearAll(ParamKeyType key_type) { +void Params::clearAll(ParamKeyFlag key_flag) { FileLock file_lock(params_path + "/.lock"); - // 1) delete params of key_type + // 1) delete params of key_flag // 2) delete files that are not defined in the keys. if (DIR *d = opendir(getParamPath().c_str())) { struct dirent *de = NULL; while ((de = readdir(d))) { if (de->d_type != DT_DIR) { auto it = keys.find(de->d_name); - if (it == keys.end() || (it->second & key_type)) { + if (it == keys.end() || (it->second.flags & key_flag)) { unlink(getParamPath(de->d_name).c_str()); } } diff --git a/common/params.h b/common/params.h index d726a6185f3c77..8169063ac0d932 100644 --- a/common/params.h +++ b/common/params.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -9,16 +10,33 @@ #include "common/queue.h" -enum ParamKeyType { +enum ParamKeyFlag { PERSISTENT = 0x02, CLEAR_ON_MANAGER_START = 0x04, CLEAR_ON_ONROAD_TRANSITION = 0x08, CLEAR_ON_OFFROAD_TRANSITION = 0x10, DONT_LOG = 0x20, DEVELOPMENT_ONLY = 0x40, + CLEAR_ON_IGNITION_ON = 0x80, ALL = 0xFFFFFFFF }; +enum ParamKeyType { + STRING = 0, // must be utf-8 decodable + BOOL = 1, + INT = 2, + FLOAT = 3, + TIME = 4, // ISO 8601 + JSON = 5, + BYTES = 6 +}; + +struct ParamKeyAttributes { + uint32_t flags; + ParamKeyType type; + std::optional default_value = std::nullopt; +}; + class Params { public: explicit Params(const std::string &path = {}); @@ -29,14 +47,16 @@ class Params { std::vector allKeys() const; bool checkKey(const std::string &key); + ParamKeyFlag getKeyFlag(const std::string &key); ParamKeyType getKeyType(const std::string &key); + std::optional getKeyDefaultValue(const std::string &key); inline std::string getParamPath(const std::string &key = {}) { return params_path + params_prefix + (key.empty() ? "" : "/" + key); } // Delete a value int remove(const std::string &key); - void clearAll(ParamKeyType type); + void clearAll(ParamKeyFlag flag); // helpers for reading values std::string get(const std::string &key, bool block = false); diff --git a/common/params.py b/common/params.py index 66808083dcd9bf..8af80c04bb20c3 100644 --- a/common/params.py +++ b/common/params.py @@ -1,5 +1,6 @@ -from openpilot.common.params_pyx import Params, ParamKeyType, UnknownKeyName +from openpilot.common.params_pyx import Params, ParamKeyFlag, ParamKeyType, UnknownKeyName assert Params +assert ParamKeyFlag assert ParamKeyType assert UnknownKeyName @@ -13,6 +14,6 @@ if len(sys.argv) == 3: val = sys.argv[2] print(f"SET: {key} = {val}") - params.put(key, val) + params.put(key, val, block=True) elif len(sys.argv) == 2: print(f"GET: {key} = {params.get(key)}") diff --git a/common/params_keys.h b/common/params_keys.h new file mode 100644 index 00000000000000..c09058dc71b056 --- /dev/null +++ b/common/params_keys.h @@ -0,0 +1,308 @@ +#pragma once + +#include +#include + +#include "cereal/gen/cpp/log.capnp.h" + +inline static std::unordered_map keys = { + {"AccessToken", {CLEAR_ON_MANAGER_START | DONT_LOG, STRING}}, + {"AdbEnabled", {PERSISTENT, BOOL}}, + {"AlwaysOnDM", {PERSISTENT, BOOL}}, + {"ApiCache_Device", {PERSISTENT, STRING}}, + {"ApiCache_FirehoseStats", {PERSISTENT, JSON}}, + {"AssistNowToken", {PERSISTENT, STRING}}, + {"AthenadPid", {PERSISTENT, INT}}, + {"AthenadUploadQueue", {PERSISTENT, JSON}}, + {"AthenadRecentlyViewedRoutes", {PERSISTENT, STRING}}, + {"BootCount", {PERSISTENT, INT}}, + {"CalibrationParams", {PERSISTENT, BYTES}}, + {"CameraDebugExpGain", {CLEAR_ON_MANAGER_START, STRING}}, + {"CameraDebugExpTime", {CLEAR_ON_MANAGER_START, STRING}}, + {"CarBatteryCapacity", {PERSISTENT, INT}}, + {"CarParams", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BYTES}}, + {"CarParamsCache", {CLEAR_ON_MANAGER_START, BYTES}}, + {"CarParamsPersistent", {PERSISTENT, BYTES}}, + {"CarParamsPrevRoute", {PERSISTENT, BYTES}}, + {"CompletedTrainingVersion", {PERSISTENT, STRING, "0"}}, + {"ControlsReady", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"CurrentBootlog", {PERSISTENT, STRING}}, + {"CurrentRoute", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, STRING}}, + {"DisableLogging", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"DisablePowerDown", {PERSISTENT, BOOL}}, + {"DisableUpdates", {PERSISTENT, BOOL}}, + {"DisengageOnAccelerator", {PERSISTENT, BOOL, "0"}}, + {"DongleId", {PERSISTENT, STRING}}, + {"DoReboot", {CLEAR_ON_MANAGER_START, BOOL}}, + {"DoShutdown", {CLEAR_ON_MANAGER_START, BOOL}}, + {"DoUninstall", {CLEAR_ON_MANAGER_START, BOOL}}, + {"DriverTooDistracted", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, BOOL}}, + {"AlphaLongitudinalEnabled", {PERSISTENT | DEVELOPMENT_ONLY, BOOL}}, + {"ExperimentalMode", {PERSISTENT, BOOL}}, + {"ExperimentalModeConfirmed", {PERSISTENT, BOOL}}, + {"FirmwareQueryDone", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"ForcePowerDown", {PERSISTENT, BOOL}}, + {"GitBranch", {PERSISTENT, STRING}}, + {"GitCommit", {PERSISTENT, STRING}}, + {"GitCommitDate", {PERSISTENT, STRING}}, + {"GitDiff", {PERSISTENT, STRING}}, + {"GithubSshKeys", {PERSISTENT, STRING}}, + {"GithubUsername", {PERSISTENT, STRING}}, + {"GitRemote", {PERSISTENT, STRING}}, + {"GsmApn", {PERSISTENT, STRING}}, + {"GsmMetered", {PERSISTENT, BOOL, "1"}}, + {"GsmRoaming", {PERSISTENT, BOOL}}, + {"HardwareSerial", {PERSISTENT, STRING}}, + {"HasAcceptedTerms", {PERSISTENT, STRING, "0"}}, + {"InstallDate", {PERSISTENT, TIME}}, + {"IsDriverViewEnabled", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsEngaged", {PERSISTENT, BOOL}}, + {"IsLdwEnabled", {PERSISTENT, BOOL}}, + {"IsMetric", {PERSISTENT, BOOL}}, + {"IsOffroad", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsOnroad", {PERSISTENT, BOOL}}, + {"IsRhdDetected", {PERSISTENT, BOOL}}, + {"IsReleaseBranch", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsTakingSnapshot", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsTestedBranch", {CLEAR_ON_MANAGER_START, BOOL}}, + {"JoystickDebugMode", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"LanguageSetting", {PERSISTENT, STRING, "en"}}, + {"LastAthenaPingTime", {CLEAR_ON_MANAGER_START, INT}}, + {"LastGPSPosition", {PERSISTENT, STRING}}, + {"LastManagerExitReason", {CLEAR_ON_MANAGER_START, STRING}}, + {"LastOffroadStatusPacket", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, JSON}}, + {"LastAgnosPowerMonitorShutdown", {CLEAR_ON_MANAGER_START, STRING}}, + {"LastPowerDropDetected", {CLEAR_ON_MANAGER_START, STRING}}, + {"LastUpdateException", {CLEAR_ON_MANAGER_START, STRING}}, + {"LastUpdateRouteCount", {PERSISTENT, INT, "0"}}, + {"LastUpdateTime", {PERSISTENT, TIME}}, + {"LastUpdateUptimeOnroad", {PERSISTENT, FLOAT, "0.0"}}, + {"LiveDelay", {PERSISTENT, BYTES}}, + {"LiveParameters", {PERSISTENT, JSON}}, + {"LiveParametersV2", {PERSISTENT, BYTES}}, + {"LiveTorqueParameters", {PERSISTENT | DONT_LOG, BYTES}}, + {"LocationFilterInitialState", {PERSISTENT, BYTES}}, + {"LateralManeuverMode", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"LongitudinalManeuverMode", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"LongitudinalPersonality", {PERSISTENT, INT, std::to_string(static_cast(cereal::LongitudinalPersonality::STANDARD))}}, + {"NetworkMetered", {PERSISTENT, BOOL}}, + {"ObdMultiplexingChanged", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"ObdMultiplexingEnabled", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"Offroad_CarUnrecognized", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"Offroad_ConnectivityNeeded", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_ConnectivityNeededPrompt", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_ExcessiveActuation", {PERSISTENT, JSON}}, + {"Offroad_IsTakingSnapshot", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_NeosUpdate", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_NoFirmware", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"Offroad_Recalibration", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"Offroad_TemperatureTooHigh", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_UnregisteredHardware", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_UpdateFailed", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_DriverMonitoringUncertain", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"OnroadCycleRequested", {CLEAR_ON_MANAGER_START, BOOL}}, + {"OpenpilotEnabledToggle", {PERSISTENT, BOOL, "1"}}, + {"PandaHeartbeatLost", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"PrimeType", {PERSISTENT, INT}}, + {"RecordAudio", {PERSISTENT, BOOL}}, + {"RecordAudioFeedback", {PERSISTENT, BOOL, "0"}}, + {"RecordFront", {PERSISTENT, BOOL}}, + {"RecordFrontLock", {PERSISTENT, BOOL}}, // for the internal fleet + {"SecOCKey", {PERSISTENT | DONT_LOG, STRING}}, + {"ShowDebugInfo", {PERSISTENT, BOOL}}, + {"RouteCount", {PERSISTENT, INT, "0"}}, + {"SnoozeUpdate", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"SshEnabled", {PERSISTENT, BOOL}}, + {"UbloxAvailable", {PERSISTENT, BOOL}}, + {"UpdateAvailable", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"UpdateFailedCount", {CLEAR_ON_MANAGER_START, INT}}, + {"UpdaterAvailableBranches", {PERSISTENT, STRING}}, + {"UpdaterCurrentDescription", {CLEAR_ON_MANAGER_START, STRING}}, + {"UpdaterCurrentReleaseNotes", {CLEAR_ON_MANAGER_START, BYTES}}, + {"UpdaterFetchAvailable", {CLEAR_ON_MANAGER_START, BOOL}}, + {"UpdaterNewDescription", {CLEAR_ON_MANAGER_START, STRING}}, + {"UpdaterNewReleaseNotes", {CLEAR_ON_MANAGER_START, BYTES}}, + {"UpdaterState", {CLEAR_ON_MANAGER_START, STRING}}, + {"UpdaterTargetBranch", {CLEAR_ON_MANAGER_START, STRING}}, + {"UpdaterLastFetchTime", {PERSISTENT, TIME}}, + {"UptimeOffroad", {PERSISTENT, FLOAT, "0.0"}}, + {"UptimeOnroad", {PERSISTENT, FLOAT, "0.0"}}, + {"UsbGpuPresent", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"UsbGpuCompiled", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"Version", {PERSISTENT, STRING}}, + + // NAP (NotAutopilot) Pre-AP Tesla params + {"NAPBookmarkRequest", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, INT}}, + {"NAPBookmarkRecording", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, INT}}, + {"NAPBrakeFactor", {PERSISTENT, FLOAT, "1.0"}}, + // Stock Follow Distance 1–7. Stalk behind a radar lead writes this + // (Hypermile On or Off). Driving Mannerisms slider stays visible. + {"NAPFollowDistance", {PERSISTENT, INT, "4"}}, + // City (<~50 mph) and highway (>~50 mph) Follow Distance 1–7. Migrated + // from NAPFollowDistance on first use. Mannerisms always; not Hypermile. + {"NAPFollowDistanceCity", {PERSISTENT, INT, "4"}}, + {"NAPFollowDistanceHwy", {PERSISTENT, INT, "4"}}, + {"NAPFollowDistanceSplitMigrated", {PERSISTENT, BOOL, "0"}}, + // One-shot Follow Distance HUD. card sets on every stalk persist + // (including a tip already at 1 or 7). selfdrived consumes and + // holds the toast ~1.5 s. Not a preference. + {"NAPFollowHudPending", {CLEAR_ON_MANAGER_START, BOOL, "0"}}, + // Settings → NAP → Driving Mannerisms → Hypermile. Default Off. + // On: comfort-biased eco-snap (Adaptive Accel, Cap/Follow, + // Early lookahead, Accel 1 lazy climb) — early light ease, not max + // regen bite. Restore those knobs on Off. Soft-lat / DM / blinker / + // stock 1–7 Follow Distance unchanged (Hypermile does not own follow). + {"NAPHypermile", {PERSISTENT, BOOL, "0"}}, + {"NAPHypermileSaved", {PERSISTENT, STRING}}, + // Opt-in mileage defer. Default Off. Inert unless Hypermile is On. + // Lowers the Cap/Follow posted target by a fixed 15 mph (75→60). + // Does not stack with the eco −5 offset. Never exceeds posted. + {"NAPHypermileStepDown", {PERSISTENT, BOOL, "0"}}, + // Hypermile sub-toggle. Default On. Inert unless Hypermile is On. + // IMU-pitch climb hold + crest/downhill ease. No maps-elevation lookahead. + // Never raises HUD MAX. Lead / MPC brake still wins. + {"NAPHypermileHillClimb", {PERSISTENT, BOOL, "1"}}, + {"NAPForcePreAP", {PERSISTENT, BOOL, "1"}}, + {"NAPiBoosterEnabled", {PERSISTENT, BOOL}}, + {"NAPPedalCalibDone", {PERSISTENT, BOOL}}, + {"NAPPedalCalibFactor", {PERSISTENT, FLOAT, "1.0"}}, + {"NAPPedalCalibMax", {PERSISTENT, FLOAT, "99.6"}}, + {"NAPPedalCalibMin", {PERSISTENT, FLOAT, "-3.0"}}, + {"NAPPedalCalibZero", {PERSISTENT, FLOAT, "0.0"}}, + {"NAPPedalCanBus", {PERSISTENT, INT, "2"}}, + {"NAPAdaptiveAccel", {PERSISTENT, BOOL, "1"}}, + // Curve-follow (continuous curve term in the longitudinal planner). + // 0 = off, 1 = shadow (compute + log only; old preview and CurveMaxHold + // stay in force), 2 = active (replaces the preview, retires the + // CurveMaxHold MAX cap). Default 1. + {"NAPCurveFollow", {PERSISTENT, INT, "1"}}, + {"NAPSightCap", {PERSISTENT, INT, "1"}}, + // Settings → NAP → Lateral Control. Default On (Pre-AP only). Turn + // geometry correction: low-speed lag + rear reference offset (m) in + // modeld's plan sampling time. On also drops the legacy roundabout + // outer bias. Off = previous lateral behavior. + {"NAPLatTurnGeom", {PERSISTENT, BOOL, "1"}}, + {"NAPLatRefOffset", {PERSISTENT, FLOAT, "0.35"}}, + {"NAPTurnInDelay", {PERSISTENT, INT, "0"}}, + // Settings → NAP → Driving Mannerisms → Roundabout Steering Assist. + // Pre-AP, default Off. Near / on a mapped OSM ring, blends the model's + // curvature toward the lane's circle curvature (map-match confidence + // weighted; camera keeps lane edges; driver torque overrides as today). + {"NAPRoundaboutAssist", {PERSISTENT, BOOL, "0"}}, + // mapd → controlsd: fitted ring geometry of the hinted roundabout (JSON). + {"NAPRoundaboutRing", {CLEAR_ON_MANAGER_START, JSON}}, + // controlsd -> modeld: the ring assist is latched on a ring; DesireHelper ignores stalk tips (no ALC) while true. + {"NAPRoundaboutLatched", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + // Settings → NAP → Driving Mannerisms → One-Pedal Long. Default Off. + // Pedal mode: gas rising from rest kicks software long off (silent + // pause, like brake). After RELEASE, lift/near-zero accel is Tesla + // regen through interceptor pass-through — not a GAS_COMMAND rewrite. + // Off = stock gas override + A+B/A3 resume climb. + {"NAPOnePedalLong", {PERSISTENT, BOOL, "0"}}, + // Settings → NAP → Driving Mannerisms → Gap lock. Default Off. + // Pedal mode: 2 s engage-stalk hold latches radar dRel (long may be paused). + {"NAPGapLock", {PERSISTENT, BOOL, "0"}}, + {"NAPPedalEnabled", {PERSISTENT, BOOL}}, + {"NAPPedalProfile", {PERSISTENT, INT, "4"}}, + {"NAPRadarBehindNosecone", {PERSISTENT, BOOL}}, + {"NAPRadarDonorVin", {PERSISTENT, STRING}}, + {"NAPRadarEnabled", {PERSISTENT, BOOL}}, + {"NAPRadarEpasType", {PERSISTENT, INT, "0"}}, + {"NAPRadarHud", {PERSISTENT, BOOL}}, + {"NAPRadarIgnoreHwFail", {PERSISTENT, BOOL}}, + {"NAPRadarIgnoreSensorDirty", {PERSISTENT, BOOL, "1"}}, + {"NAPRadarOffset", {PERSISTENT, FLOAT, "0.0"}}, + {"NAPRadarPosition", {PERSISTENT, INT, "0"}}, + {"NAPRadarReadVin", {CLEAR_ON_MANAGER_START, BOOL}}, + {"NAPRadarVinReadStatus", {CLEAR_ON_MANAGER_START, STRING}}, + {"NAPScriptRunning", {CLEAR_ON_MANAGER_START, BOOL}}, + // Companion Dash process. Default On. Off stops nap_dash without + // blocking engage (process is optional / non-critical). + {"NAPDashEnabled", {PERSISTENT, BOOL, "1"}}, + // OSM map speed → HUD MAX. Mode: 0=off 1=display 2=cap 3=follow. Lookahead 2=normal. Accel 5=default. + {"NAPMapSpeedMode", {PERSISTENT, INT, "0"}}, + {"NAPMapSpeedOffsetMph", {PERSISTENT, INT, "0"}}, + {"NAPMapSpeedLookahead", {PERSISTENT, INT, "2"}}, + {"NAPMapSpeedAccel", {PERSISTENT, INT, "5"}}, + {"NAPMapSpeedDbPath", {PERSISTENT, STRING}}, + {"NAPMapSpeedDbRevision", {PERSISTENT, STRING}}, + {"NAPMapSpeedDbSha256", {PERSISTENT, STRING}}, + // Pre-AP 0x45 stalk wiper/high-beam. Default 0 = today's forwarded stalk. + // Wiper UI: 0=off 3=auto. Legacy 1=int / 2=on coerce to Off. + // Auto overlays collar INTERVAL1 while on, in Drive/Reverse, moving, + // and the 3X ROAD camera sees rain or ice/frost. + // Beam: 0/1 leave stalk, 2=high (low nibble 4). + // DAS wiper/beam fields stay 0. No auto headlights. + {"NAPWiperSpeed", {PERSISTENT, INT, "0"}}, + // One-shot Wipers Off/Auto HUD. card/body sets on collar 0→1→0 toggle. + // selfdrived consumes and holds the toast ~2.5 s. Not a preference. + {"NAPWiperHudPending", {CLEAR_ON_MANAGER_START, BOOL, "0"}}, + // Auto wiper sensitivity 0–4. Mid 2 = baseline. Lower = wipe sooner / + // more often (more dry). Higher = tolerate more film (more wet). + {"NAPWiperSensitivity", {PERSISTENT, INT, "2"}}, + // Live Auto-wiper status (~1 Hz Params.put). STRING so unknown-key put + // cannot fail silently. No CLEAR_ON_ONROAD: loggerd embeds Params in qlog + // InitData at route start (same snapshot copied into each segment), so an + // onroad wipe would hide this from Connect qlog digs. Last 1 Hz line must + // survive into the next snapshot. Still cleared on manager start. + {"NAPWiperRainStatus", {CLEAR_ON_MANAGER_START, STRING}}, + {"NAPHighLowBeam", {PERSISTENT, INT, "0"}}, + // On-drive MUTCD speed-sign JSONL logger. Default off. Log-only: no sqlite, + // no vCruise / HUD MAX, no osm.org. Process: speedsignd. + {"NAPSpeedSignLog", {PERSISTENT, BOOL, "0"}}, + {"NAPSpeedSignConfirmed", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, JSON}}, + // Soft wheel lateral handoff. Default ON. Yield on driver intent + // (sustained torsion + aligned rate + hands on). Stay yielded while + // handsOnLevel >= 1; blend after ~80 ms hands-off. Hard brake during + // yield fully cancels. Settings can turn Off. + {"NAPDriverLatHandoff", {PERSISTENT, BOOL, "1"}}, + // Low-visibility lateral back-off. Default On. When lane/road-edge + // confidence collapses with a wide path, or road-camera exposure + // collapses (sooner if the sun is low and ahead), lateral eases + // toward the driver and the HUD says Low visibility. Longitudinal + // stays engaged. Off = stock lateral, no alert. + {"NAPLowVisBackoff", {PERSISTENT, BOOL, "1"}}, + // After a ~2 s push away from a radar cone line, the soft-handoff + // re-take holds that lateral offset instead of blending onto the + // model path. Default On. Longitudinal is unchanged. + {"NAPConeLineHold", {PERSISTENT, BOOL, "1"}}, + // Log-only cone-line detector (coneLineNAP in the qlog). Default On. + // Off stops the publish; the hold then sees no line. Does not steer. + {"NAPConeLineLog", {PERSISTENT, BOOL, "1"}}, + // Log-only radar obstacle detector (pathObstacleNAP). Default On. + // Animals, people, and solid debris in or beside the lane. Does not + // brake or steer. Off stops the log and the chime. + {"NAPObstacleLog", {PERSISTENT, BOOL, "1"}}, + // Chime when radar and vision agree something solid is in the lane + // or stepping into it, and for an animal or a person near the road. + // Default On. A still mailbox or post on the shoulder stays quiet. + // Does not brake, steer, or change engagement. + {"NAPObstacleChime", {PERSISTENT, BOOL, "1"}}, + // Pre-AP DM: while engaged, full looking-path wipe on the stock + // vision path (no-face / uncertain / phone / pose / eye). After + // drain past 1.0 s, fire at random in the next 2.0 s (fire in + // (1.0, 3.0] of that countdown). Hold until awareness recovers. + // Mutually exclusive with NAPDmFalseAlertIgnore. Triple-tap + // Settings → NAP. Default On (nap-dev). + {"NAPDmSimulateLooking", {PERSISTENT, BOOL, "1"}}, + // Pre-AP DM: soft-clear false phone/device distraction only + // (phoneProb / distracted_types phone). Same 1–3 s cadence as + // Simulate Look. Pose and eye still drain / alert. Triple-tap + // Settings → NAP (third item). Mutually exclusive with Simulate + // Look — default Off on nap-dev so both are not On. PERSISTENT + // like Simulate Look (preference, not a session flag). + {"NAPDmFalseAlertIgnore", {PERSISTENT, BOOL, "0"}}, + // Settings → NAP → Force Offroad. Default off. Not persistent: reboot + // (manager start) and the next ignition ON clear it. Toggle Off and + // Reset to Defaults also clear. When on, hardwared keeps started=false + // after the Pre-AP stock-CC handoff reports ready (or a short timeout). + {"NAPForceOffroad", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, BOOL, "0"}}, + // card → hardwared: stock CC is ENABLED (or handoff gave up). Do not + // CLEAR_ON_OFFROAD — going offroad is the point. Default off. + {"NAPForceOffroadHandoffReady", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, BOOL, "0"}}, + // UI Yes on "Ready to resume steering control?". Default off. Handoff + // and started=false wait for this while onroad. Same clear flags. + {"NAPForceOffroadConfirmed", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, BOOL, "0"}}, + {"TermsVersion", {PERSISTENT, STRING}}, + {"TrainingVersion", {PERSISTENT, STRING}}, +}; diff --git a/common/params_pyx.pyx b/common/params_pyx.pyx index 535514e521a6d9..c919c85f0c40e8 100644 --- a/common/params_pyx.pyx +++ b/common/params_pyx.pyx @@ -1,18 +1,34 @@ # distutils: language = c++ # cython: language_level = 3 +import builtins +import datetime +import json from libcpp cimport bool from libcpp.string cimport string from libcpp.vector cimport vector +from libcpp.optional cimport optional + +from openpilot.common.swaglog import cloudlog cdef extern from "common/params.h": - cpdef enum ParamKeyType: + cpdef enum ParamKeyFlag: PERSISTENT CLEAR_ON_MANAGER_START CLEAR_ON_ONROAD_TRANSITION CLEAR_ON_OFFROAD_TRANSITION DEVELOPMENT_ONLY + CLEAR_ON_IGNITION_ON ALL + cpdef enum ParamKeyType: + STRING + BOOL + INT + FLOAT + TIME + JSON + BYTES + cdef cppclass c_Params "Params": c_Params(string) except + nogil string get(string, bool) nogil @@ -23,10 +39,31 @@ cdef extern from "common/params.h": void putBoolNonBlocking(string, bool) nogil int putBool(string, bool) nogil bool checkKey(string) nogil + ParamKeyType getKeyType(string) nogil + optional[string] getKeyDefaultValue(string) nogil string getParamPath(string) nogil - void clearAll(ParamKeyType) + void clearAll(ParamKeyFlag) vector[string] allKeys() +PYTHON_2_CPP = { + (str, STRING): lambda v: v, + (builtins.bool, BOOL): lambda v: "1" if v else "0", + (int, INT): str, + (float, FLOAT): str, + (datetime.datetime, TIME): lambda v: v.isoformat(), + (dict, JSON): json.dumps, + (list, JSON): json.dumps, + (bytes, BYTES): lambda v: v, +} +CPP_2_PYTHON = { + STRING: lambda v: v.decode("utf-8"), + BOOL: lambda v: v == b"1", + INT: int, + FLOAT: float, + TIME: lambda v: datetime.datetime.fromisoformat(v.decode("utf-8")), + JSON: json.loads, + BYTES: lambda v: v, +} def ensure_bytes(v): return v.encode() if isinstance(v, str) else v @@ -36,17 +73,22 @@ class UnknownKeyName(Exception): cdef class Params: cdef c_Params* p + cdef str d def __cinit__(self, d=""): cdef string path = d.encode() with nogil: self.p = new c_Params(path) + self.d = d + + def __reduce__(self): + return (type(self), (self.d,)) def __dealloc__(self): del self.p - def clear_all(self, tx_type=ParamKeyType.ALL): - self.p.clearAll(tx_type) + def clear_all(self, tx_flag=ParamKeyFlag.ALL): + self.p.clearAll(tx_flag) def check_key(self, key): key = ensure_bytes(key) @@ -54,21 +96,38 @@ cdef class Params: raise UnknownKeyName(key) return key - def get(self, key, bool block=False, encoding=None): + def python2cpp(self, proposed_type, expected_type, value, key): + cast = PYTHON_2_CPP.get((proposed_type, expected_type)) + if cast: + return cast(value) + raise TypeError(f"Type mismatch while writing param {key}: {proposed_type=} {expected_type=} {value=}") + + def _cpp2python(self, t, value, default, key): + if value is None: + return None + try: + return CPP_2_PYTHON[t](value) + except (KeyError, TypeError, ValueError): + cloudlog.warning(f"Failed to cast param {key} with {value=} from type {t=}") + return self._cpp2python(t, default, None, key) + + def get(self, key, bool block=False, bool return_default=False): cdef string k = self.check_key(key) + cdef ParamKeyType t = self.p.getKeyType(k) + cdef optional[string] default = self.p.getKeyDefaultValue(k) cdef string val with nogil: val = self.p.get(k, block) + default_val = (default.value() if default.has_value() else None) if return_default else None if val == b"": if block: # If we got no value while running in blocked mode # it means we got an interrupt while waiting raise KeyboardInterrupt else: - return None - - return val if encoding is None else val.decode(encoding) + return self._cpp2python(t, default_val, None, key) + return self._cpp2python(t, val, default_val, key) def get_bool(self, key, bool block=False): cdef string k = self.check_key(key) @@ -77,33 +136,33 @@ cdef class Params: r = self.p.getBool(k, block) return r - def put(self, key, dat): + def _put_cast(self, key, dat): + cdef string k = self.check_key(key) + cdef ParamKeyType t = self.p.getKeyType(k) + return ensure_bytes(self.python2cpp(type(dat), t, dat, key)) + + def put(self, key, dat, bool block = False): """ - Warning: This function blocks until the param is written to disk! + Warning: block=True blocks until the param is written to disk! In very rare cases this can take over a second, and your code will hang. - Use the put_nonblocking, put_bool_nonblocking in time sensitive code, but - in general try to avoid writing params as much as possible. + Use block=False in time sensitive code, but in general try to avoid + writing params as much as possible. """ cdef string k = self.check_key(key) - cdef string dat_bytes = ensure_bytes(dat) - with nogil: - self.p.put(k, dat_bytes) - - def put_bool(self, key, bool val): - cdef string k = self.check_key(key) + cdef string dat_bytes = self._put_cast(key, dat) with nogil: - self.p.putBool(k, val) - - def put_nonblocking(self, key, dat): - cdef string k = self.check_key(key) - cdef string dat_bytes = ensure_bytes(dat) - with nogil: - self.p.putNonBlocking(k, dat_bytes) + if block: + self.p.put(k, dat_bytes) + else: + self.p.putNonBlocking(k, dat_bytes) - def put_bool_nonblocking(self, key, bool val): + def put_bool(self, key, bool val, bool block = False): cdef string k = self.check_key(key) with nogil: - self.p.putBoolNonBlocking(k, val) + if block: + self.p.putBool(k, val) + else: + self.p.putBoolNonBlocking(k, val) def remove(self, key): cdef string k = self.check_key(key) @@ -114,5 +173,19 @@ cdef class Params: cdef string key_bytes = ensure_bytes(key) return self.p.getParamPath(key_bytes).decode("utf-8") + def get_type(self, key): + return self.p.getKeyType(self.check_key(key)) + def all_keys(self): return self.p.allKeys() + + def get_default_value(self, key): + cdef string k = self.check_key(key) + cdef ParamKeyType t = self.p.getKeyType(k) + cdef optional[string] default = self.p.getKeyDefaultValue(k) + return self._cpp2python(t, default.value(), None, key) if default.has_value() else None + + def cpp2python(self, key, value): + cdef string k = self.check_key(key) + cdef ParamKeyType t = self.p.getKeyType(k) + return self._cpp2python(t, value, None, key) diff --git a/common/pid.py b/common/pid.py index 29c4d8bd469c07..b3d64d6fcdc2d6 100644 --- a/common/pid.py +++ b/common/pid.py @@ -1,46 +1,30 @@ import numpy as np from numbers import Number -from openpilot.common.numpy_fast import clip, interp - - class PIDController: - def __init__(self, k_p, k_i, k_f=0., k_d=0., pos_limit=1e308, neg_limit=-1e308, rate=100): - self._k_p = k_p - self._k_i = k_i - self._k_d = k_d - self.k_f = k_f # feedforward gain - if isinstance(self._k_p, Number): - self._k_p = [[0], [self._k_p]] - if isinstance(self._k_i, Number): - self._k_i = [[0], [self._k_i]] - if isinstance(self._k_d, Number): - self._k_d = [[0], [self._k_d]] + def __init__(self, k_p, k_i, k_d=0., pos_limit=1e308, neg_limit=-1e308, rate=100): + self._k_p: list[list[float]] = [[0], [k_p]] if isinstance(k_p, Number) else k_p + self._k_i: list[list[float]] = [[0], [k_i]] if isinstance(k_i, Number) else k_i + self._k_d: list[list[float]] = [[0], [k_d]] if isinstance(k_d, Number) else k_d - self.pos_limit = pos_limit - self.neg_limit = neg_limit + self.set_limits(pos_limit, neg_limit) - self.i_unwind_rate = 0.3 / rate - self.i_rate = 1.0 / rate + self.i_dt = 1.0 / rate self.speed = 0.0 self.reset() @property def k_p(self): - return interp(self.speed, self._k_p[0], self._k_p[1]) + return np.interp(self.speed, self._k_p[0], self._k_p[1]) @property def k_i(self): - return interp(self.speed, self._k_i[0], self._k_i[1]) + return np.interp(self.speed, self._k_i[0], self._k_i[1]) @property def k_d(self): - return interp(self.speed, self._k_d[0], self._k_d[1]) - - @property - def error_integral(self): - return self.i/self.k_i + return np.interp(self.speed, self._k_d[0], self._k_d[1]) def reset(self): self.p = 0.0 @@ -49,27 +33,25 @@ def reset(self): self.f = 0.0 self.control = 0 - def update(self, error, error_rate=0.0, speed=0.0, override=False, feedforward=0., freeze_integrator=False): - self.speed = speed + def set_limits(self, pos_limit, neg_limit): + self.pos_limit = pos_limit + self.neg_limit = neg_limit - self.p = float(error) * self.k_p - self.f = feedforward * self.k_f - self.d = error_rate * self.k_d + def update(self, error, error_rate=0.0, speed=0.0, feedforward=0., freeze_integrator=False): + self.speed = speed + self.p = self.k_p * float(error) + self.d = self.k_d * error_rate + self.f = feedforward - if override: - self.i -= self.i_unwind_rate * float(np.sign(self.i)) - else: - i = self.i + error * self.k_i * self.i_rate - control = self.p + i + self.d + self.f + if not freeze_integrator: + i = self.i + self.k_i * self.i_dt * error - # Update when changing i will move the control away from the limits - # or when i will move towards the sign of the error - if ((error >= 0 and (control <= self.pos_limit or i < 0.0)) or - (error <= 0 and (control >= self.neg_limit or i > 0.0))) and \ - not freeze_integrator: - self.i = i + # Don't allow windup if already clipping + test_control = self.p + i + self.d + self.f + i_upperbound = self.i if test_control > self.pos_limit else self.pos_limit + i_lowerbound = self.i if test_control < self.neg_limit else self.neg_limit + self.i = np.clip(i, i_lowerbound, i_upperbound) control = self.p + self.i + self.d + self.f - - self.control = clip(control, self.neg_limit, self.pos_limit) + self.control = np.clip(control, self.neg_limit, self.pos_limit) return self.control diff --git a/common/prefix.h b/common/prefix.h index 11d0bc10661e06..de3a94d71f2072 100644 --- a/common/prefix.h +++ b/common/prefix.h @@ -13,7 +13,11 @@ class OpenpilotPrefix { if (prefix.empty()) { prefix = util::random_string(15); } - msgq_path = "/dev/shm/" + prefix; +#ifdef __APPLE__ + msgq_path = "/tmp/msgq_" + prefix; +#else + msgq_path = "/dev/shm/msgq_" + prefix; +#endif bool ret = util::create_directories(msgq_path, 0777); assert(ret); setenv("OPENPILOT_PREFIX", prefix.c_str(), 1); @@ -23,14 +27,14 @@ class OpenpilotPrefix { auto param_path = Params().getParamPath(); if (util::file_exists(param_path)) { std::string real_path = util::readlink(param_path); - system(util::string_format("rm %s -rf", real_path.c_str()).c_str()); + util::check_system(util::string_format("rm %s -rf", real_path.c_str())); unlink(param_path.c_str()); } if (getenv("COMMA_CACHE") == nullptr) { - system(util::string_format("rm %s -rf", Path::download_cache_root().c_str()).c_str()); + util::check_system(util::string_format("rm %s -rf", Path::download_cache_root().c_str())); } - system(util::string_format("rm %s -rf", Path::comma_home().c_str()).c_str()); - system(util::string_format("rm %s -rf", msgq_path.c_str()).c_str()); + util::check_system(util::string_format("rm %s -rf", Path::comma_home().c_str())); + util::check_system(util::string_format("rm %s -rf", msgq_path.c_str())); unsetenv("OPENPILOT_PREFIX"); } diff --git a/common/prefix.py b/common/prefix.py index 3292acae8623ed..d0a5f926286935 100644 --- a/common/prefix.py +++ b/common/prefix.py @@ -1,4 +1,5 @@ import os +import platform import shutil import uuid @@ -9,20 +10,20 @@ from openpilot.system.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT class OpenpilotPrefix: - def __init__(self, prefix: str = None, clean_dirs_on_exit: bool = True, shared_download_cache: bool = False): + def __init__(self, prefix: str | None = None, create_dirs_on_enter: bool = True, clean_dirs_on_exit: bool = True, shared_download_cache: bool = False): self.prefix = prefix if prefix else str(uuid.uuid4().hex[0:15]) - self.msgq_path = os.path.join('/dev/shm', self.prefix) + shm_path = "/tmp" if platform.system() == "Darwin" else "/dev/shm" + self.msgq_path = os.path.join(shm_path, "msgq_" + self.prefix) + self.create_dirs_on_enter = create_dirs_on_enter self.clean_dirs_on_exit = clean_dirs_on_exit self.shared_download_cache = shared_download_cache def __enter__(self): self.original_prefix = os.environ.get('OPENPILOT_PREFIX', None) os.environ['OPENPILOT_PREFIX'] = self.prefix - try: - os.mkdir(self.msgq_path) - except FileExistsError: - pass - os.makedirs(Paths.log_root(), exist_ok=True) + + if self.create_dirs_on_enter: + self.create_dirs() if self.shared_download_cache: os.environ["COMMA_CACHE"] = DEFAULT_DOWNLOAD_CACHE_ROOT @@ -40,6 +41,13 @@ def __exit__(self, exc_type, exc_obj, exc_tb): pass return False + def create_dirs(self): + try: + os.mkdir(self.msgq_path) + except FileExistsError: + pass + os.makedirs(Paths.log_root(), exist_ok=True) + def clean_dirs(self): symlink_path = Params().get_param_path() if os.path.exists(symlink_path): diff --git a/common/ratekeeper.cc b/common/ratekeeper.cc index 7e63815168d1e8..a79acd7d516797 100644 --- a/common/ratekeeper.cc +++ b/common/ratekeeper.cc @@ -6,9 +6,9 @@ #include "common/timing.h" #include "common/util.h" -RateKeeper::RateKeeper(const std::string &name, float rate, float print_delay_threshold) - : name(name), - print_delay_threshold(std::max(0.f, print_delay_threshold)) { +RateKeeper::RateKeeper(const std::string &name_, float rate, float print_delay_threshold_) + : name(name_), + print_delay_threshold(std::max(0.f, print_delay_threshold_)) { interval = 1 / rate; last_monitor_time = seconds_since_boot(); next_frame_time = last_monitor_time + interval; diff --git a/common/realtime.py b/common/realtime.py index dd97ea3d787ccf..91d2e165e909c8 100644 --- a/common/realtime.py +++ b/common/realtime.py @@ -1,11 +1,12 @@ """Utilities for reading real time clocks and keeping soft real time constraints.""" import gc import os +import sys import time -from collections import deque from setproctitle import getproctitle +from openpilot.common.utils import MovingAverage from openpilot.system.hardware import PC @@ -27,19 +28,20 @@ class Priority: CTRL_HIGH = 53 -def set_realtime_priority(level: int) -> None: - if not PC: - os.sched_setscheduler(0, os.SCHED_FIFO, os.sched_param(level)) +def drop_realtime() -> None: + if sys.platform == 'linux' and not PC: + os.sched_setscheduler(0, os.SCHED_OTHER, os.sched_param(0)) def set_core_affinity(cores: list[int]) -> None: - if not PC: + if sys.platform == 'linux' and not PC: os.sched_setaffinity(0, cores) def config_realtime_process(cores: int | list[int], priority: int) -> None: gc.disable() - set_realtime_priority(priority) + if sys.platform == 'linux' and not PC: + os.sched_setscheduler(0, os.SCHED_FIFO, os.sched_param(priority)) c = cores if isinstance(cores, list) else [cores, ] set_core_affinity(c) @@ -48,13 +50,15 @@ class Ratekeeper: def __init__(self, rate: float, print_delay_threshold: float | None = 0.0) -> None: """Rate in Hz for ratekeeping. print_delay_threshold must be nonnegative.""" self._interval = 1. / rate - self._next_frame_time = time.monotonic() + self._interval self._print_delay_threshold = print_delay_threshold self._frame = 0 self._remaining = 0.0 self._process_name = getproctitle() - self._dts = deque([self._interval], maxlen=100) - self._last_monitor_time = time.monotonic() + self._last_monitor_time = -1. + self._next_frame_time = -1. + + self.avg_dt = MovingAverage(100) + self.avg_dt.add_value(self._interval) @property def frame(self) -> int: @@ -66,9 +70,8 @@ def remaining(self) -> float: @property def lagging(self) -> bool: - avg_dt = sum(self._dts) / len(self._dts) expected_dt = self._interval * (1 / 0.9) - return avg_dt > expected_dt + return self.avg_dt.get_average() > expected_dt # Maintain loop rate by calling this at the end of each loop def keep_time(self) -> bool: @@ -79,9 +82,13 @@ def keep_time(self) -> bool: # Monitors the cumulative lag, but does not enforce a rate def monitor_time(self) -> bool: + if self._last_monitor_time < 0: + self._next_frame_time = time.monotonic() + self._interval + self._last_monitor_time = time.monotonic() + prev = self._last_monitor_time self._last_monitor_time = time.monotonic() - self._dts.append(self._last_monitor_time - prev) + self.avg_dt.add_value(self._last_monitor_time - prev) lagged = False remaining = self._next_frame_time - time.monotonic() diff --git a/common/retry.py b/common/retry.py deleted file mode 100644 index 9bd4ac9522c77e..00000000000000 --- a/common/retry.py +++ /dev/null @@ -1,30 +0,0 @@ -import time -import functools - -from openpilot.common.swaglog import cloudlog - - -def retry(attempts=3, delay=1.0, ignore_failure=False): - def decorator(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - for _ in range(attempts): - try: - return func(*args, **kwargs) - except Exception: - cloudlog.exception(f"{func.__name__} failed, trying again") - time.sleep(delay) - - if ignore_failure: - cloudlog.error(f"{func.__name__} failed after retry") - else: - raise Exception(f"{func.__name__} failed after retry") - return wrapper - return decorator - - -if __name__ == "__main__": - @retry(attempts=10) - def abc(): - raise ValueError("abc failed :(") - abc() diff --git a/common/run.py b/common/run.py deleted file mode 100644 index 06deb6388df19a..00000000000000 --- a/common/run.py +++ /dev/null @@ -1,13 +0,0 @@ -import subprocess - - -def run_cmd(cmd: list[str], cwd=None, env=None) -> str: - return subprocess.check_output(cmd, encoding='utf8', cwd=cwd, env=env).strip() - - -def run_cmd_default(cmd: list[str], default: str = "", cwd=None, env=None) -> str: - try: - return run_cmd(cmd, cwd=cwd, env=env) - except subprocess.CalledProcessError: - return default - diff --git a/common/spinner.py b/common/spinner.py old mode 100644 new mode 100755 index dcf22641c42b71..12a816eaf8d729 --- a/common/spinner.py +++ b/common/spinner.py @@ -6,9 +6,9 @@ class Spinner: def __init__(self): try: - self.spinner_proc = subprocess.Popen(["./spinner"], + self.spinner_proc = subprocess.Popen(["./spinner.py"], stdin=subprocess.PIPE, - cwd=os.path.join(BASEDIR, "selfdrive", "ui"), + cwd=os.path.join(BASEDIR, "system", "ui"), close_fds=True) except OSError: self.spinner_proc = None diff --git a/common/swaglog.cc b/common/swaglog.cc index 7864a6355a6030..df7ce94c146457 100644 --- a/common/swaglog.cc +++ b/common/swaglog.cc @@ -11,7 +11,7 @@ #include #include -#include "third_party/json11/json11.hpp" +#include "json11/json11.hpp" #include "common/version.h" #include "system/hardware/hw.h" @@ -26,6 +26,9 @@ class SwaglogState { zmq_setsockopt(sock, ZMQ_LINGER, &timeout, sizeof(timeout)); zmq_connect(sock, Path::swaglog_ipc().c_str()); + // workaround for https://github.com/dropbox/json11/issues/38 + setlocale(LC_NUMERIC, "C"); + print_level = CLOUDLOG_WARNING; if (const char* print_lvl = getenv("LOGPRINT")) { if (strcmp(print_lvl, "debug") == 0) { diff --git a/common/tests/test_file_helpers.py b/common/tests/test_file_helpers.py index a9977c2362d301..c2b880f873d1e4 100644 --- a/common/tests/test_file_helpers.py +++ b/common/tests/test_file_helpers.py @@ -1,7 +1,7 @@ import os from uuid import uuid4 -from openpilot.common.file_helpers import atomic_write_in_dir +from openpilot.common.utils import atomic_write class TestFileHelpers: @@ -15,5 +15,5 @@ def run_atomic_write_func(self, atomic_write_func): assert f.read() == "test" os.remove(path) - def test_atomic_write_in_dir(self): - self.run_atomic_write_func(atomic_write_in_dir) + def test_atomic_write(self): + self.run_atomic_write_func(atomic_write) diff --git a/common/tests/test_nap_force_offroad.py b/common/tests/test_nap_force_offroad.py new file mode 100644 index 00000000000000..f87c9af12e317f --- /dev/null +++ b/common/tests/test_nap_force_offroad.py @@ -0,0 +1,191 @@ +"""NAP Force Offroad: param, hardwared started gate, settings, docs.""" +import importlib.util +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + +# Load the helper without importing system.hardware (cereal / params_pyx). +_spec = importlib.util.spec_from_file_location( + "nap_force_offroad", ROOT / "system" / "hardware" / "nap_force_offroad.py", +) +_mod = importlib.util.module_from_spec(_spec) +assert _spec.loader is not None +_spec.loader.exec_module(_mod) +PARAM = _mod.PARAM +HANDOFF_READY_PARAM = _mod.HANDOFF_READY_PARAM +CONFIRMED_PARAM = _mod.CONFIRMED_PARAM +CONFIRM_PROMPT = _mod.CONFIRM_PROMPT +allows_onroad = _mod.allows_onroad +apply_force_offroad_toggle = _mod.apply_force_offroad_toggle +cancel_force_offroad = _mod.cancel_force_offroad +confirm_force_offroad = _mod.confirm_force_offroad +handoff_wait_timed_out = _mod.handoff_wait_timed_out +needs_driver_confirm = _mod.needs_driver_confirm +should_start_now = _mod.should_start_now + + +def _assert_force_offroad_param_line(keys: str, name: str): + line = next(ln for ln in keys.splitlines() if f'"{name}"' in ln) + assert "CLEAR_ON_MANAGER_START" in line + assert "CLEAR_ON_IGNITION_ON" in line + assert "PERSISTENT" not in line + # Going offroad is what the toggle does — that flag would undo it. + assert "CLEAR_ON_OFFROAD" not in line + assert 'BOOL, "0"' in line + + +def test_param_default_off_and_clears_on_ignition_and_manager(): + keys = (ROOT / "common" / "params_keys.h").read_text(encoding="utf-8") + assert PARAM == "NAPForceOffroad" + assert HANDOFF_READY_PARAM == "NAPForceOffroadHandoffReady" + assert CONFIRMED_PARAM == "NAPForceOffroadConfirmed" + assert CONFIRM_PROMPT == "Ready to resume steering control?" + _assert_force_offroad_param_line(keys, PARAM) + _assert_force_offroad_param_line(keys, HANDOFF_READY_PARAM) + _assert_force_offroad_param_line(keys, CONFIRMED_PARAM) + + +def test_allows_onroad_default_and_toggle(): + assert allows_onroad(False) is True + assert allows_onroad(True) is False + + +def test_allows_onroad_holds_while_handoff_pending(): + """Already onroad + Force Offroad: keep started until stock CC ENABLED or timeout.""" + assert allows_onroad(True, already_started=True, handoff_ready=False) is True + assert allows_onroad(True, already_started=True, handoff_ready=True) is False + assert allows_onroad(True, already_started=True, handoff_ready=False, timed_out=True) is False + # Parked / not started: do not wait — stay offroad. + assert allows_onroad(True, already_started=False, handoff_ready=False) is False + assert handoff_wait_timed_out(None, 10.0) is False + assert handoff_wait_timed_out(0.0, 2.9) is False + assert handoff_wait_timed_out(0.0, 3.0) is True + + +def test_onroad_confirm_holds_started_until_yes(): + assert needs_driver_confirm(True, False, True) is True + assert needs_driver_confirm(True, True, True) is False + assert needs_driver_confirm(True, False, False) is False + assert needs_driver_confirm(False, False, True) is False + # Yes not tapped: stay onroad even if handoff_ready leaked. + assert allows_onroad(True, already_started=True, confirmed=False, handoff_ready=True) is True + assert allows_onroad(True, already_started=True, confirmed=True, handoff_ready=True) is False + + +def test_apply_toggle_and_no_clears_intent(): + class P: + def __init__(self): + self.d = {} + def put_bool(self, k, v): + self.d[k] = bool(v) + def get_bool(self, k): + return bool(self.d.get(k, False)) + + p = P() + apply_force_offroad_toggle(p, True, started=True) + assert p.get_bool(PARAM) is True + assert p.get_bool(CONFIRMED_PARAM) is False + confirm_force_offroad(p) + assert p.get_bool(CONFIRMED_PARAM) is True + cancel_force_offroad(p) + assert p.get_bool(PARAM) is False + assert p.get_bool(CONFIRMED_PARAM) is False + assert p.get_bool(HANDOFF_READY_PARAM) is False + + apply_force_offroad_toggle(p, True, started=False) + assert p.get_bool(CONFIRMED_PARAM) is True + + +def test_force_offroad_blocks_should_start_while_ignition_on(): + onroad = { + "ignition": True, + "not_onroad_cycle": True, + "device_temp_good": True, + "not_force_offroad": allows_onroad(True), + } + startup = {"up_to_date": True, "accepted_terms": True} + assert should_start_now(onroad, startup, already_started=True) is False + assert should_start_now(onroad, startup, already_started=False) is False + + onroad["not_force_offroad"] = allows_onroad(False) + assert should_start_now(onroad, startup, already_started=True) is True + assert should_start_now(onroad, startup, already_started=False) is True + + # Missing a startup condition still blocks a cold start, not a stay-onroad. + startup["up_to_date"] = False + assert should_start_now(onroad, startup, already_started=True) is True + assert should_start_now(onroad, startup, already_started=False) is False + + +def test_hardwared_hooks_param_before_ign_edge(): + text = (ROOT / "system" / "hardware" / "hardwared.py").read_text(encoding="utf-8") + assert "not_force_offroad" in text + assert "nap_force_offroad_allows_onroad" in text + assert "should_start_now" in text + assert "NAP_FORCE_OFFROAD_PARAM" in text + assert "NAP_FORCE_OFFROAD_HANDOFF_READY_PARAM" in text + assert "NAP_FORCE_OFFROAD_CONFIRMED_PARAM" in text + assert "handoff_ready" in text + assert "force_offroad_confirmed" in text + cond = text.index('onroad_conditions["not_force_offroad"]') + edge = text.index("ign_edge =") + assert cond < edge + + +def test_settings_and_docs_cover_warning_and_reset(): + nap = (ROOT / "selfdrive" / "ui" / "layouts" / "settings" / "nap.py").read_text(encoding="utf-8") + mici = (ROOT / "selfdrive" / "ui" / "mici" / "layouts" / "settings" / "nap.py").read_text(encoding="utf-8") + popup = (ROOT / "selfdrive" / "ui" / "layouts" / "settings" / "hidden_toggles.py").read_text(encoding="utf-8") + overlay = (ROOT / "selfdrive" / "ui" / "mici" / "layouts" / "settings" / "hidden_toggles.py").read_text(encoding="utf-8") + content = (ROOT / "selfdrive" / "ui" / "layouts" / "settings" / "nap_content.py").read_text(encoding="utf-8") + docs = (ROOT / "docs-nap" / "force-offroad.md").read_text(encoding="utf-8") + readme = (ROOT / "docs-nap" / "README.md").read_text(encoding="utf-8") + ui_state = (ROOT / "selfdrive" / "ui" / "ui_state.py").read_text(encoding="utf-8") + + assert "NAP_FORCE_OFFROAD" in nap + assert "put_bool(NAP_FORCE_OFFROAD, False)" in nap + assert 'self._add_toggle(\n NAP_FORCE_OFFROAD' not in nap + + assert "Force Offroad" in popup + assert "NAP_FORCE_OFFROAD" in popup + assert "is_offroad" not in popup + + assert "NAP_FORCE_OFFROAD" not in mici + assert "force offroad" in overlay + assert "NAP_FORCE_OFFROAD" in overlay + assert "drive manually" in overlay + assert "set_enabled(ui_state.is_offroad)" not in overlay + + assert "WARNING" in content + assert "Drive manually" in content + assert "NAPForceOffroad" in docs + assert "NAPForceOffroadHandoffReady" in docs + assert "NAPForceOffroadConfirmed" in docs + assert "Ready to resume steering control?" in docs + assert "CLEAR_ON_IGNITION_ON" in docs + assert "deviceState.started" in docs + assert "triple-tap" in docs + assert "STANDBY" in docs + assert "enableLongControl" in docs + assert "force-offroad.md" in readme + assert "NAP Force Offroad" in ui_state + + +def test_params_roundtrip_if_compiled(): + """Compiled Params picks up params_keys.h. Skip when params_pyx is not built.""" + import pytest + params_mod = pytest.importorskip("openpilot.common.params") + Params = params_mod.Params + ParamKeyFlag = params_mod.ParamKeyFlag + params = Params() + assert params.get_bool(PARAM) is False + params.put_bool(PARAM, True, block=True) + assert params.get_bool(PARAM) is True + params.clear_all(ParamKeyFlag.CLEAR_ON_IGNITION_ON) + assert params.get_bool(PARAM) is False + params.put_bool(PARAM, True, block=True) + params.clear_all(ParamKeyFlag.CLEAR_ON_MANAGER_START) + assert params.get_bool(PARAM) is False + params.put_bool(PARAM, True, block=True) + params.clear_all(ParamKeyFlag.CLEAR_ON_OFFROAD_TRANSITION) + assert params.get_bool(PARAM) is True diff --git a/common/tests/test_numpy_fast.py b/common/tests/test_numpy_fast.py deleted file mode 100644 index aa53851db04981..00000000000000 --- a/common/tests/test_numpy_fast.py +++ /dev/null @@ -1,21 +0,0 @@ -import numpy as np - -from openpilot.common.numpy_fast import interp - - -class TestInterp: - def test_correctness_controls(self): - _A_CRUISE_MIN_BP = np.asarray([0., 5., 10., 20., 40.]) - _A_CRUISE_MIN_V = np.asarray([-1.0, -.8, -.67, -.5, -.30]) - v_ego_arr = [-1, -1e-12, 0, 4, 5, 6, 7, 10, 11, 15.2, 20, 21, 39, - 39.999999, 40, 41] - - expected = np.interp(v_ego_arr, _A_CRUISE_MIN_BP, _A_CRUISE_MIN_V) - actual = interp(v_ego_arr, _A_CRUISE_MIN_BP, _A_CRUISE_MIN_V) - - np.testing.assert_equal(actual, expected) - - for v_ego in v_ego_arr: - expected = np.interp(v_ego, _A_CRUISE_MIN_BP, _A_CRUISE_MIN_V) - actual = interp(v_ego, _A_CRUISE_MIN_BP, _A_CRUISE_MIN_V) - np.testing.assert_equal(actual, expected) diff --git a/common/tests/test_params.py b/common/tests/test_params.py index 16cbc45295d527..f3fb71b388ab20 100644 --- a/common/tests/test_params.py +++ b/common/tests/test_params.py @@ -1,27 +1,28 @@ import pytest +import datetime import os import threading import time import uuid -from openpilot.common.params import Params, ParamKeyType, UnknownKeyName +from openpilot.common.params import Params, ParamKeyFlag, UnknownKeyName class TestParams: def setup_method(self): self.params = Params() def test_params_put_and_get(self): - self.params.put("DongleId", "cb38263377b873ee") - assert self.params.get("DongleId") == b"cb38263377b873ee" + self.params.put("DongleId", "cb38263377b873ee", block=True) + assert self.params.get("DongleId") == "cb38263377b873ee" def test_params_non_ascii(self): st = b"\xe1\x90\xff" - self.params.put("CarParams", st) + self.params.put("CarParams", st, block=True) assert self.params.get("CarParams") == st def test_params_get_cleared_manager_start(self): - self.params.put("CarParams", "test") - self.params.put("DongleId", "cb38263377b873ee") + self.params.put("CarParams", b"test", block=True) + self.params.put("DongleId", "cb38263377b873ee", block=True) assert self.params.get("CarParams") == b"test" undefined_param = self.params.get_param_path(uuid.uuid4().hex) @@ -29,24 +30,24 @@ def test_params_get_cleared_manager_start(self): f.write("test") assert os.path.isfile(undefined_param) - self.params.clear_all(ParamKeyType.CLEAR_ON_MANAGER_START) + self.params.clear_all(ParamKeyFlag.CLEAR_ON_MANAGER_START) assert self.params.get("CarParams") is None assert self.params.get("DongleId") is not None assert not os.path.isfile(undefined_param) def test_params_two_things(self): - self.params.put("DongleId", "bob") - self.params.put("AthenadPid", "123") - assert self.params.get("DongleId") == b"bob" - assert self.params.get("AthenadPid") == b"123" + self.params.put("DongleId", "bob", block=True) + self.params.put("AthenadPid", 123, block=True) + assert self.params.get("DongleId") == "bob" + assert self.params.get("AthenadPid") == 123 def test_params_get_block(self): def _delayed_writer(): time.sleep(0.1) - self.params.put("CarParams", "test") + self.params.put("CarParams", b"test", block=True) threading.Thread(target=_delayed_writer).start() assert self.params.get("CarParams") is None - assert self.params.get("CarParams", True) == b"test" + assert self.params.get("CarParams", block=True) == b"test" def test_params_unknown_key_fails(self): with pytest.raises(UnknownKeyName): @@ -56,10 +57,10 @@ def test_params_unknown_key_fails(self): self.params.get_bool("swag") with pytest.raises(UnknownKeyName): - self.params.put("swag", "abc") + self.params.put("swag", "abc", block=True) with pytest.raises(UnknownKeyName): - self.params.put_bool("swag", True) + self.params.put_bool("swag", True, block=True) def test_remove_not_there(self): assert self.params.get("CarParams") is None @@ -70,23 +71,23 @@ def test_get_bool(self): self.params.remove("IsMetric") assert not self.params.get_bool("IsMetric") - self.params.put_bool("IsMetric", True) + self.params.put_bool("IsMetric", True, block=True) assert self.params.get_bool("IsMetric") - self.params.put_bool("IsMetric", False) + self.params.put_bool("IsMetric", False, block=True) assert not self.params.get_bool("IsMetric") - self.params.put("IsMetric", "1") + self.params.put("IsMetric", True, block=True) assert self.params.get_bool("IsMetric") - self.params.put("IsMetric", "0") + self.params.put("IsMetric", False, block=True) assert not self.params.get_bool("IsMetric") def test_put_non_blocking_with_get_block(self): q = Params() def _delayed_writer(): time.sleep(0.1) - Params().put_nonblocking("CarParams", "test") + Params().put("CarParams", b"test") threading.Thread(target=_delayed_writer).start() assert q.get("CarParams") is None assert q.get("CarParams", True) == b"test" @@ -95,7 +96,7 @@ def test_put_bool_non_blocking_with_get_block(self): q = Params() def _delayed_writer(): time.sleep(0.1) - Params().put_bool_nonblocking("CarParams", True) + Params().put_bool("CarParams", True) threading.Thread(target=_delayed_writer).start() assert q.get("CarParams") is None assert q.get("CarParams", True) == b"1" @@ -107,3 +108,62 @@ def test_params_all_keys(self): assert len(keys) > 20 assert len(keys) == len(set(keys)) assert b"CarParams" in keys + + def test_params_default_value(self): + self.params.remove("LanguageSetting") + self.params.remove("LongitudinalPersonality") + self.params.remove("LiveParameters") + + assert self.params.get("LanguageSetting") is None + assert self.params.get("LanguageSetting", return_default=False) is None + assert isinstance(self.params.get("LanguageSetting", return_default=True), str) + assert isinstance(self.params.get("LongitudinalPersonality", return_default=True), int) + assert self.params.get("LiveParameters") is None + assert self.params.get("LiveParameters", return_default=True) is None + + def test_params_get_type(self): + # json + self.params.put("ApiCache_FirehoseStats", {"a": 0}, block=True) + assert self.params.get("ApiCache_FirehoseStats") == {"a": 0} + + # int + self.params.put("BootCount", 1441, block=True) + assert self.params.get("BootCount") == 1441 + + # bool + self.params.put("AdbEnabled", True, block=True) + assert self.params.get("AdbEnabled") + assert isinstance(self.params.get("AdbEnabled"), bool) + + # time + now = datetime.datetime.now(datetime.UTC) + self.params.put("InstallDate", now, block=True) + assert self.params.get("InstallDate") == now + + +def test_nap_wiper_rain_status_key_survives_onroad_for_qlog(): + # loggerd copies Params into qlog InitData at route start. Unknown keys + # fail put silently; CLEAR_ON_ONROAD would wipe this before that snapshot. + import re + from openpilot.common.basedir import BASEDIR + keys_h = os.path.join(BASEDIR, "common/params_keys.h") + with open(keys_h) as f: + src = f.read() + m = re.search(r'\{\s*"NAPWiperRainStatus"\s*,\s*\{([^}]+)\}', src) + assert m, "NAPWiperRainStatus missing from params_keys.h" + attrs = m.group(1) + assert "CLEAR_ON_MANAGER_START" in attrs + assert "CLEAR_ON_ONROAD_TRANSITION" not in attrs + assert "STRING" in attrs + assert "DONT_LOG" not in attrs + wiper_speed = re.search(r'\{\s*"NAPWiperSpeed"\s*,\s*\{([^}]+)\}', src) + assert wiper_speed and "PERSISTENT" in wiper_speed.group(1) + wiper_sens = re.search(r'\{\s*"NAPWiperSensitivity"\s*,\s*\{([^}]+)\}', src) + assert wiper_sens, "NAPWiperSensitivity missing from params_keys.h" + assert "PERSISTENT" in wiper_sens.group(1) + assert "INT" in wiper_sens.group(1) + assert '"2"' in wiper_sens.group(1) + wiper_hud = re.search(r'\{\s*"NAPWiperHudPending"\s*,\s*\{([^}]+)\}', src) + assert wiper_hud, "NAPWiperHudPending missing from params_keys.h" + assert "CLEAR_ON_MANAGER_START" in wiper_hud.group(1) + assert "BOOL" in wiper_hud.group(1) diff --git a/common/tests/test_simple_kalman.py b/common/tests/test_simple_kalman.py index f4a967e58ad418..e44ac2cc57ca87 100644 --- a/common/tests/test_simple_kalman.py +++ b/common/tests/test_simple_kalman.py @@ -24,6 +24,6 @@ def test_getter_setter(self): self.kf.set_x([[1.0], [1.0]]) assert self.kf.x == [[1.0], [1.0]] - def update_returns_state(self): + def test_update_returns_state(self): x = self.kf.update(100) - assert x == self.kf.x + assert x == [i[0] for i in self.kf.x] diff --git a/common/tests/test_swaglog.cc b/common/tests/test_swaglog.cc index 09bc4c3795fd5e..8142f8d63e295c 100644 --- a/common/tests/test_swaglog.cc +++ b/common/tests/test_swaglog.cc @@ -7,7 +7,7 @@ #include "common/util.h" #include "common/version.h" #include "system/hardware/hw.h" -#include "third_party/json11/json11.hpp" +#include "json11/json11.hpp" std::string daemon_name = "testy"; std::string dongle_id = "test_dongle_id"; diff --git a/common/tests/test_util.cc b/common/tests/test_util.cc index de87fa3e0642ed..d927b98a4d19b5 100644 --- a/common/tests/test_util.cc +++ b/common/tests/test_util.cc @@ -36,7 +36,7 @@ TEST_CASE("util::read_file") { REQUIRE(util::read_file(filename).empty()); std::string content = random_bytes(64 * 1024); - write(fd, content.c_str(), content.size()); + REQUIRE(write(fd, content.c_str(), content.size()) == (ssize_t)content.size()); std::string ret = util::read_file(filename); bool equal = (ret == content); REQUIRE(equal); @@ -114,12 +114,12 @@ TEST_CASE("util::safe_fwrite") { } TEST_CASE("util::create_directories") { - system("rm /tmp/test_create_directories -rf"); + REQUIRE(system("rm /tmp/test_create_directories -rf") == 0); std::string dir = "/tmp/test_create_directories/a/b/c/d/e/f"; - auto check_dir_permissions = [](const std::string &dir, mode_t mode) -> bool { + auto check_dir_permissions = [](const std::string &path, mode_t mode) -> bool { struct stat st = {}; - return stat(dir.c_str(), &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR && (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) == mode; + return stat(path.c_str(), &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR && (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) == mode; }; SECTION("create_directories") { @@ -132,7 +132,7 @@ TEST_CASE("util::create_directories") { } SECTION("a file exists with the same name") { REQUIRE(util::create_directories(dir, 0755)); - int f = open((dir + "/file").c_str(), O_RDWR | O_CREAT); + int f = open((dir + "/file").c_str(), O_RDWR | O_CREAT, 0644); REQUIRE(f != -1); close(f); REQUIRE(util::create_directories(dir + "/file", 0755) == false); diff --git a/common/text_window.py b/common/text_window.py index d2762ebf7dc010..358243d1f1fb9e 100755 --- a/common/text_window.py +++ b/common/text_window.py @@ -8,9 +8,9 @@ class TextWindow: def __init__(self, text): try: - self.text_proc = subprocess.Popen(["./text", text], + self.text_proc = subprocess.Popen(["./text.py", text], stdin=subprocess.PIPE, - cwd=os.path.join(BASEDIR, "selfdrive", "ui"), + cwd=os.path.join(BASEDIR, "system", "ui"), close_fds=True) except OSError: self.text_proc = None diff --git a/common/time.py b/common/time.py deleted file mode 100644 index 60233e17fd861e..00000000000000 --- a/common/time.py +++ /dev/null @@ -1,15 +0,0 @@ -import datetime -from pathlib import Path - -_MIN_DATE = datetime.datetime(year=2024, month=8, day=26) - -def min_date(): - # on systemd systems, the default time is the systemd build time - systemd_path = Path("/lib/systemd/systemd") - if systemd_path.exists(): - d = datetime.datetime.fromtimestamp(systemd_path.stat().st_mtime) - return d + datetime.timedelta(days=1) - return _MIN_DATE - -def system_time_valid(): - return datetime.datetime.now() > min_date() diff --git a/common/time_helpers.py b/common/time_helpers.py new file mode 100644 index 00000000000000..c709182d455f72 --- /dev/null +++ b/common/time_helpers.py @@ -0,0 +1,16 @@ +import datetime +from pathlib import Path + +MIN_DATE = datetime.datetime(year=2025, month=2, day=21) +MAX_DATE = datetime.datetime(year=2035, month=1, day=1) + +def min_date(): + # on systemd systems, the default time is the systemd build time + systemd_path = Path("/lib/systemd/systemd") + if systemd_path.exists(): + d = datetime.datetime.fromtimestamp(systemd_path.stat().st_mtime) + return max(MIN_DATE, d + datetime.timedelta(days=1)) + return MIN_DATE + +def system_time_valid(): + return min_date() < datetime.datetime.now() < MAX_DATE diff --git a/common/transformations/.gitignore b/common/transformations/.gitignore deleted file mode 100644 index a67290f09ae511..00000000000000 --- a/common/transformations/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -transformations -transformations.cpp diff --git a/common/transformations/SConscript b/common/transformations/SConscript deleted file mode 100644 index 4ac73a165e4ba2..00000000000000 --- a/common/transformations/SConscript +++ /dev/null @@ -1,5 +0,0 @@ -Import('env', 'envCython') - -transformations = env.Library('transformations', ['orientation.cc', 'coordinates.cc']) -transformations_python = envCython.Program('transformations.so', 'transformations.pyx') -Export('transformations', 'transformations_python') diff --git a/common/transformations/coordinates.cc b/common/transformations/coordinates.cc deleted file mode 100644 index 5b00b53a4f4928..00000000000000 --- a/common/transformations/coordinates.cc +++ /dev/null @@ -1,100 +0,0 @@ -#define _USE_MATH_DEFINES - -#include "common/transformations/coordinates.hpp" - -#include -#include -#include - -double a = 6378137; // lgtm [cpp/short-global-name] -double b = 6356752.3142; // lgtm [cpp/short-global-name] -double esq = 6.69437999014 * 0.001; // lgtm [cpp/short-global-name] -double e1sq = 6.73949674228 * 0.001; - - -static Geodetic to_degrees(Geodetic geodetic){ - geodetic.lat = RAD2DEG(geodetic.lat); - geodetic.lon = RAD2DEG(geodetic.lon); - return geodetic; -} - -static Geodetic to_radians(Geodetic geodetic){ - geodetic.lat = DEG2RAD(geodetic.lat); - geodetic.lon = DEG2RAD(geodetic.lon); - return geodetic; -} - - -ECEF geodetic2ecef(Geodetic g){ - g = to_radians(g); - double xi = sqrt(1.0 - esq * pow(sin(g.lat), 2)); - double x = (a / xi + g.alt) * cos(g.lat) * cos(g.lon); - double y = (a / xi + g.alt) * cos(g.lat) * sin(g.lon); - double z = (a / xi * (1.0 - esq) + g.alt) * sin(g.lat); - return {x, y, z}; -} - -Geodetic ecef2geodetic(ECEF e){ - // Convert from ECEF to geodetic using Ferrari's methods - // https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#Ferrari.27s_solution - double x = e.x; - double y = e.y; - double z = e.z; - - double r = sqrt(x * x + y * y); - double Esq = a * a - b * b; - double F = 54 * b * b * z * z; - double G = r * r + (1 - esq) * z * z - esq * Esq; - double C = (esq * esq * F * r * r) / (pow(G, 3)); - double S = cbrt(1 + C + sqrt(C * C + 2 * C)); - double P = F / (3 * pow((S + 1 / S + 1), 2) * G * G); - double Q = sqrt(1 + 2 * esq * esq * P); - double r_0 = -(P * esq * r) / (1 + Q) + sqrt(0.5 * a * a*(1 + 1.0 / Q) - P * (1 - esq) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r); - double U = sqrt(pow((r - esq * r_0), 2) + z * z); - double V = sqrt(pow((r - esq * r_0), 2) + (1 - esq) * z * z); - double Z_0 = b * b * z / (a * V); - double h = U * (1 - b * b / (a * V)); - - double lat = atan((z + e1sq * Z_0) / r); - double lon = atan2(y, x); - - return to_degrees({lat, lon, h}); -} - -LocalCoord::LocalCoord(Geodetic g, ECEF e){ - init_ecef << e.x, e.y, e.z; - - g = to_radians(g); - - ned2ecef_matrix << - -sin(g.lat)*cos(g.lon), -sin(g.lon), -cos(g.lat)*cos(g.lon), - -sin(g.lat)*sin(g.lon), cos(g.lon), -cos(g.lat)*sin(g.lon), - cos(g.lat), 0, -sin(g.lat); - ecef2ned_matrix = ned2ecef_matrix.transpose(); -} - -NED LocalCoord::ecef2ned(ECEF e) { - Eigen::Vector3d ecef; - ecef << e.x, e.y, e.z; - - Eigen::Vector3d ned = (ecef2ned_matrix * (ecef - init_ecef)); - return {ned[0], ned[1], ned[2]}; -} - -ECEF LocalCoord::ned2ecef(NED n) { - Eigen::Vector3d ned; - ned << n.n, n.e, n.d; - - Eigen::Vector3d ecef = (ned2ecef_matrix * ned) + init_ecef; - return {ecef[0], ecef[1], ecef[2]}; -} - -NED LocalCoord::geodetic2ned(Geodetic g) { - ECEF e = ::geodetic2ecef(g); - return ecef2ned(e); -} - -Geodetic LocalCoord::ned2geodetic(NED n){ - ECEF e = ned2ecef(n); - return ::ecef2geodetic(e); -} diff --git a/common/transformations/coordinates.hpp b/common/transformations/coordinates.hpp deleted file mode 100644 index 32ec2ff66e3058..00000000000000 --- a/common/transformations/coordinates.hpp +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include - -#define DEG2RAD(x) ((x) * M_PI / 180.0) -#define RAD2DEG(x) ((x) * 180.0 / M_PI) - -struct ECEF { - double x, y, z; - Eigen::Vector3d to_vector(){ - return Eigen::Vector3d(x, y, z); - } -}; - -struct NED { - double n, e, d; - Eigen::Vector3d to_vector(){ - return Eigen::Vector3d(n, e, d); - } -}; - -struct Geodetic { - double lat, lon, alt; - bool radians=false; -}; - -ECEF geodetic2ecef(Geodetic g); -Geodetic ecef2geodetic(ECEF e); - -class LocalCoord { -public: - Eigen::Matrix3d ned2ecef_matrix; - Eigen::Matrix3d ecef2ned_matrix; - Eigen::Vector3d init_ecef; - LocalCoord(Geodetic g, ECEF e); - LocalCoord(Geodetic g) : LocalCoord(g, ::geodetic2ecef(g)) {} - LocalCoord(ECEF e) : LocalCoord(::ecef2geodetic(e), e) {} - - NED ecef2ned(ECEF e); - ECEF ned2ecef(NED n); - NED geodetic2ned(Geodetic g); - Geodetic ned2geodetic(NED n); -}; diff --git a/common/transformations/model.py b/common/transformations/model.py index aaa12d776a8ed0..ea1dff30e8fc4e 100644 --- a/common/transformations/model.py +++ b/common/transformations/model.py @@ -1,7 +1,7 @@ import numpy as np from openpilot.common.transformations.orientation import rot_from_euler -from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame +from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame, _ar_ox_fisheye # segnet SEGNET_SIZE = (512, 384) @@ -39,6 +39,13 @@ [0.0, sbigmodel_fl, 0.5 * (256 + MEDMODEL_CY)], [0.0, 0.0, 1.0]]) +DM_INPUT_SIZE = (1440, 960) +dmonitoringmodel_fl = _ar_ox_fisheye.focal_length +dmonitoringmodel_intrinsics = np.array([ + [dmonitoringmodel_fl, 0.0, DM_INPUT_SIZE[0]/2], + [0.0, dmonitoringmodel_fl, DM_INPUT_SIZE[1]/2 - (_ar_ox_fisheye.height - DM_INPUT_SIZE[1])/2], + [0.0, 0.0, 1.0]]) + bigmodel_frame_from_calib_frame = np.dot(bigmodel_intrinsics, get_view_frame_from_calib_frame(0, 0, 0, 0)) diff --git a/common/transformations/orientation.cc b/common/transformations/orientation.cc deleted file mode 100644 index 00888c3a926080..00000000000000 --- a/common/transformations/orientation.cc +++ /dev/null @@ -1,144 +0,0 @@ -#define _USE_MATH_DEFINES - -#include -#include -#include - -#include "common/transformations/orientation.hpp" -#include "common/transformations/coordinates.hpp" - -Eigen::Quaterniond ensure_unique(Eigen::Quaterniond quat){ - if (quat.w() > 0){ - return quat; - } else { - return Eigen::Quaterniond(-quat.w(), -quat.x(), -quat.y(), -quat.z()); - } -} - -Eigen::Quaterniond euler2quat(Eigen::Vector3d euler){ - Eigen::Quaterniond q; - - q = Eigen::AngleAxisd(euler(2), Eigen::Vector3d::UnitZ()) - * Eigen::AngleAxisd(euler(1), Eigen::Vector3d::UnitY()) - * Eigen::AngleAxisd(euler(0), Eigen::Vector3d::UnitX()); - return ensure_unique(q); -} - - -Eigen::Vector3d quat2euler(Eigen::Quaterniond quat){ - // TODO: switch to eigen implementation if the range of the Euler angles doesn't matter anymore - // Eigen::Vector3d euler = quat.toRotationMatrix().eulerAngles(2, 1, 0); - // return {euler(2), euler(1), euler(0)}; - double gamma = atan2(2 * (quat.w() * quat.x() + quat.y() * quat.z()), 1 - 2 * (quat.x()*quat.x() + quat.y()*quat.y())); - double asin_arg_clipped = std::clamp(2 * (quat.w() * quat.y() - quat.z() * quat.x()), -1.0, 1.0); - double theta = asin(asin_arg_clipped); - double psi = atan2(2 * (quat.w() * quat.z() + quat.x() * quat.y()), 1 - 2 * (quat.y()*quat.y() + quat.z()*quat.z())); - return {gamma, theta, psi}; -} - -Eigen::Matrix3d quat2rot(Eigen::Quaterniond quat){ - return quat.toRotationMatrix(); -} - -Eigen::Quaterniond rot2quat(const Eigen::Matrix3d &rot){ - return ensure_unique(Eigen::Quaterniond(rot)); -} - -Eigen::Matrix3d euler2rot(Eigen::Vector3d euler){ - return quat2rot(euler2quat(euler)); -} - -Eigen::Vector3d rot2euler(const Eigen::Matrix3d &rot){ - return quat2euler(rot2quat(rot)); -} - -Eigen::Matrix3d rot_matrix(double roll, double pitch, double yaw){ - return euler2rot({roll, pitch, yaw}); -} - -Eigen::Matrix3d rot(Eigen::Vector3d axis, double angle){ - Eigen::Quaterniond q; - q = Eigen::AngleAxisd(angle, axis); - return q.toRotationMatrix(); -} - - -Eigen::Vector3d ecef_euler_from_ned(ECEF ecef_init, Eigen::Vector3d ned_pose) { - /* - Using Rotations to Build Aerospace Coordinate Systems - Don Koks - https://apps.dtic.mil/dtic/tr/fulltext/u2/a484864.pdf - */ - LocalCoord converter = LocalCoord(ecef_init); - Eigen::Vector3d zero = ecef_init.to_vector(); - - Eigen::Vector3d x0 = converter.ned2ecef({1, 0, 0}).to_vector() - zero; - Eigen::Vector3d y0 = converter.ned2ecef({0, 1, 0}).to_vector() - zero; - Eigen::Vector3d z0 = converter.ned2ecef({0, 0, 1}).to_vector() - zero; - - Eigen::Vector3d x1 = rot(z0, ned_pose(2)) * x0; - Eigen::Vector3d y1 = rot(z0, ned_pose(2)) * y0; - Eigen::Vector3d z1 = rot(z0, ned_pose(2)) * z0; - - Eigen::Vector3d x2 = rot(y1, ned_pose(1)) * x1; - Eigen::Vector3d y2 = rot(y1, ned_pose(1)) * y1; - Eigen::Vector3d z2 = rot(y1, ned_pose(1)) * z1; - - Eigen::Vector3d x3 = rot(x2, ned_pose(0)) * x2; - Eigen::Vector3d y3 = rot(x2, ned_pose(0)) * y2; - - - x0 = Eigen::Vector3d(1, 0, 0); - y0 = Eigen::Vector3d(0, 1, 0); - z0 = Eigen::Vector3d(0, 0, 1); - - double psi = atan2(x3.dot(y0), x3.dot(x0)); - double theta = atan2(-x3.dot(z0), sqrt(pow(x3.dot(x0), 2) + pow(x3.dot(y0), 2))); - - y2 = rot(z0, psi) * y0; - z2 = rot(y2, theta) * z0; - - double phi = atan2(y3.dot(z2), y3.dot(y2)); - - return {phi, theta, psi}; -} - -Eigen::Vector3d ned_euler_from_ecef(ECEF ecef_init, Eigen::Vector3d ecef_pose){ - /* - Using Rotations to Build Aerospace Coordinate Systems - Don Koks - https://apps.dtic.mil/dtic/tr/fulltext/u2/a484864.pdf - */ - LocalCoord converter = LocalCoord(ecef_init); - - Eigen::Vector3d x0 = Eigen::Vector3d(1, 0, 0); - Eigen::Vector3d y0 = Eigen::Vector3d(0, 1, 0); - Eigen::Vector3d z0 = Eigen::Vector3d(0, 0, 1); - - Eigen::Vector3d x1 = rot(z0, ecef_pose(2)) * x0; - Eigen::Vector3d y1 = rot(z0, ecef_pose(2)) * y0; - Eigen::Vector3d z1 = rot(z0, ecef_pose(2)) * z0; - - Eigen::Vector3d x2 = rot(y1, ecef_pose(1)) * x1; - Eigen::Vector3d y2 = rot(y1, ecef_pose(1)) * y1; - Eigen::Vector3d z2 = rot(y1, ecef_pose(1)) * z1; - - Eigen::Vector3d x3 = rot(x2, ecef_pose(0)) * x2; - Eigen::Vector3d y3 = rot(x2, ecef_pose(0)) * y2; - - Eigen::Vector3d zero = ecef_init.to_vector(); - x0 = converter.ned2ecef({1, 0, 0}).to_vector() - zero; - y0 = converter.ned2ecef({0, 1, 0}).to_vector() - zero; - z0 = converter.ned2ecef({0, 0, 1}).to_vector() - zero; - - double psi = atan2(x3.dot(y0), x3.dot(x0)); - double theta = atan2(-x3.dot(z0), sqrt(pow(x3.dot(x0), 2) + pow(x3.dot(y0), 2))); - - y2 = rot(z0, psi) * y0; - z2 = rot(y2, theta) * z0; - - double phi = atan2(y3.dot(z2), y3.dot(y2)); - - return {phi, theta, psi}; -} - diff --git a/common/transformations/orientation.hpp b/common/transformations/orientation.hpp deleted file mode 100644 index 150b12cadee1d1..00000000000000 --- a/common/transformations/orientation.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include -#include "common/transformations/coordinates.hpp" - - -Eigen::Quaterniond ensure_unique(Eigen::Quaterniond quat); - -Eigen::Quaterniond euler2quat(Eigen::Vector3d euler); -Eigen::Vector3d quat2euler(Eigen::Quaterniond quat); -Eigen::Matrix3d quat2rot(Eigen::Quaterniond quat); -Eigen::Quaterniond rot2quat(const Eigen::Matrix3d &rot); -Eigen::Matrix3d euler2rot(Eigen::Vector3d euler); -Eigen::Vector3d rot2euler(const Eigen::Matrix3d &rot); -Eigen::Matrix3d rot_matrix(double roll, double pitch, double yaw); -Eigen::Matrix3d rot(Eigen::Vector3d axis, double angle); -Eigen::Vector3d ecef_euler_from_ned(ECEF ecef_init, Eigen::Vector3d ned_pose); -Eigen::Vector3d ned_euler_from_ecef(ECEF ecef_init, Eigen::Vector3d ecef_pose); diff --git a/common/transformations/tests/test_coordinates.py b/common/transformations/tests/test_coordinates.py index 11a6bf70eefabb..0b5d1c36dfb0c2 100644 --- a/common/transformations/tests/test_coordinates.py +++ b/common/transformations/tests/test_coordinates.py @@ -102,3 +102,36 @@ def test_ned_batch(self): np.testing.assert_allclose(converter.ned2ecef(ned_offsets_batch), ecef_positions_offset_batch, rtol=1e-9, atol=1e-7) + + def test_errors(self): + # Test wrong shape/type for geodetic2ecef + # numpy_wrap raises IndexError for scalar input + with np.testing.assert_raises(IndexError): + coord.geodetic2ecef(1.0) + + with np.testing.assert_raises_regex(ValueError, "Geodetic must be size 3"): + coord.geodetic2ecef([0, 0]) + + with np.testing.assert_raises_regex(ValueError, "Geodetic must be size 3"): + coord.geodetic2ecef([0, 0, 0, 0]) + + with np.testing.assert_raises(TypeError): + coord.geodetic2ecef(['a', 'b', 'c']) + + # Test LocalCoord constructor errors + with np.testing.assert_raises(ValueError): + coord.LocalCoord.from_geodetic([0, 0]) + + with np.testing.assert_raises(ValueError): + coord.LocalCoord.from_geodetic(1) + + with np.testing.assert_raises(TypeError): + coord.LocalCoord.from_geodetic(['a', 'b', 'c']) + + # Test wrong shape/type for ecef2geodetic + with np.testing.assert_raises(ValueError): + coord.ecef2geodetic([1, 2]) + with np.testing.assert_raises(ValueError): + coord.ecef2geodetic([1, 2, 3, 4]) + with np.testing.assert_raises(IndexError): + coord.ecef2geodetic(1.0) diff --git a/common/transformations/tests/test_orientation.py b/common/transformations/tests/test_orientation.py index 55fbc6581e3c89..1bf94115c8320b 100644 --- a/common/transformations/tests/test_orientation.py +++ b/common/transformations/tests/test_orientation.py @@ -1,4 +1,5 @@ import numpy as np +import pytest from openpilot.common.transformations.orientation import euler2quat, quat2euler, euler2rot, rot2euler, \ rot2quat, quat2rot, \ @@ -59,3 +60,32 @@ def test_euler_ned(self): np.testing.assert_allclose(ned_eulers[i], ned_euler_from_ecef(ecef_positions[i], eulers[i]), rtol=1e-7) #np.testing.assert_allclose(eulers[i], ecef_euler_from_ned(ecef_positions[i], ned_eulers[i]), rtol=1e-7) # np.testing.assert_allclose(ned_eulers, ned_euler_from_ecef(ecef_positions, eulers), rtol=1e-7) + + def test_inputs(self): + with pytest.raises(ValueError): + euler2quat([1, 2]) + + with pytest.raises(ValueError): + quat2rot([1, 2, 3]) + + with pytest.raises(IndexError): + rot2quat(np.zeros((2, 2))) + + def test_euler_rot_consistency(self): + rpy = [0.1, 0.2, 0.3] + R = euler2rot(rpy) + + # R -> q -> R + q = rot2quat(R) + R_new = quat2rot(q) + np.testing.assert_allclose(R, R_new, atol=1e-15) + + # q -> R -> Euler (quat2euler) -> R + rpy_new = quat2euler(q) + R_new2 = euler2rot(rpy_new) + np.testing.assert_allclose(R, R_new2, atol=1e-15) + + # R -> Euler (rot2euler) -> R + rpy_from_rot = rot2euler(R) + R_new3 = euler2rot(rpy_from_rot) + np.testing.assert_allclose(R, R_new3, atol=1e-15) diff --git a/common/transformations/transformations.pxd b/common/transformations/transformations.pxd deleted file mode 100644 index 964adf06ece9e8..00000000000000 --- a/common/transformations/transformations.pxd +++ /dev/null @@ -1,72 +0,0 @@ -# cython: language_level=3 -from libcpp cimport bool - -cdef extern from "orientation.cc": - pass - -cdef extern from "orientation.hpp": - cdef cppclass Quaternion "Eigen::Quaterniond": - Quaternion() - Quaternion(double, double, double, double) - double w() - double x() - double y() - double z() - - cdef cppclass Vector3 "Eigen::Vector3d": - Vector3() - Vector3(double, double, double) - double operator()(int) - - cdef cppclass Matrix3 "Eigen::Matrix3d": - Matrix3() - Matrix3(double*) - - double operator()(int, int) - - Quaternion euler2quat(Vector3) - Vector3 quat2euler(Quaternion) - Matrix3 quat2rot(Quaternion) - Quaternion rot2quat(Matrix3) - Vector3 rot2euler(Matrix3) - Matrix3 euler2rot(Vector3) - Matrix3 rot_matrix(double, double, double) - Vector3 ecef_euler_from_ned(ECEF, Vector3) - Vector3 ned_euler_from_ecef(ECEF, Vector3) - - -cdef extern from "coordinates.cc": - cdef struct ECEF: - double x - double y - double z - - cdef struct NED: - double n - double e - double d - - cdef struct Geodetic: - double lat - double lon - double alt - bool radians - - ECEF geodetic2ecef(Geodetic) - Geodetic ecef2geodetic(ECEF) - - cdef cppclass LocalCoord_c "LocalCoord": - Matrix3 ned2ecef_matrix - Matrix3 ecef2ned_matrix - - LocalCoord_c(Geodetic, ECEF) - LocalCoord_c(Geodetic) - LocalCoord_c(ECEF) - - NED ecef2ned(ECEF) - ECEF ned2ecef(NED) - NED geodetic2ned(Geodetic) - Geodetic ned2geodetic(NED) - -cdef extern from "coordinates.hpp": - pass diff --git a/common/transformations/transformations.py b/common/transformations/transformations.py new file mode 100644 index 00000000000000..5cb6220f95ec76 --- /dev/null +++ b/common/transformations/transformations.py @@ -0,0 +1,342 @@ +import numpy as np + + +# Constants +a = 6378137.0 +b = 6356752.3142 +esq = 6.69437999014e-3 +e1sq = 6.73949674228e-3 + + +def geodetic2ecef_single(g): + """ + Convert geodetic coordinates (latitude, longitude, altitude) to ECEF. + """ + try: + if len(g) != 3: + raise ValueError("Geodetic must be size 3") + except TypeError: + raise ValueError("Geodetic must be a sequence of length 3") from None + + lat, lon, alt = g + lat = np.radians(lat) + lon = np.radians(lon) + xi = np.sqrt(1.0 - esq * np.sin(lat)**2) + x = (a / xi + alt) * np.cos(lat) * np.cos(lon) + y = (a / xi + alt) * np.cos(lat) * np.sin(lon) + z = (a / xi * (1.0 - esq) + alt) * np.sin(lat) + return np.array([x, y, z]) + + +def ecef2geodetic_single(e): + """ + Convert ECEF to geodetic coordinates using Ferrari's solution. + """ + x, y, z = e + r = np.sqrt(x**2 + y**2) + Esq = a**2 - b**2 + F = 54 * b**2 * z**2 + G = r**2 + (1 - esq) * z**2 - esq * Esq + C = (esq**2 * F * r**2) / (G**3) + S = np.cbrt(1 + C + np.sqrt(C**2 + 2 * C)) + P = F / (3 * (S + 1 / S + 1)**2 * G**2) + Q = np.sqrt(1 + 2 * esq**2 * P) + r_0 = -(P * esq * r) / (1 + Q) + np.sqrt(0.5 * a**2 * (1 + 1.0 / Q) - P * (1 - esq) * z**2 / (Q * (1 + Q)) - 0.5 * P * r**2) + U = np.sqrt((r - esq * r_0)**2 + z**2) + V = np.sqrt((r - esq * r_0)**2 + (1 - esq) * z**2) + Z_0 = b**2 * z / (a * V) + h = U * (1 - b**2 / (a * V)) + lat = np.arctan((z + e1sq * Z_0) / r) + lon = np.arctan2(y, x) + return np.array([np.degrees(lat), np.degrees(lon), h]) + + +def euler2quat_single(euler): + """ + Convert Euler angles (roll, pitch, yaw) to a quaternion. + Rotation order: Z-Y-X (yaw, pitch, roll). + """ + phi, theta, psi = euler + + c_phi, s_phi = np.cos(phi / 2), np.sin(phi / 2) + c_theta, s_theta = np.cos(theta / 2), np.sin(theta / 2) + c_psi, s_psi = np.cos(psi / 2), np.sin(psi / 2) + + w = c_phi * c_theta * c_psi + s_phi * s_theta * s_psi + x = s_phi * c_theta * c_psi - c_phi * s_theta * s_psi + y = c_phi * s_theta * c_psi + s_phi * c_theta * s_psi + z = c_phi * c_theta * s_psi - s_phi * s_theta * c_psi + + if w < 0: + return np.array([-w, -x, -y, -z]) + return np.array([w, x, y, z]) + + +def quat2euler_single(q): + """ + Convert a quaternion to Euler angles (roll, pitch, yaw). + """ + w, x, y, z = q + gamma = np.arctan2(2 * (w * x + y * z), 1 - 2 * (x**2 + y**2)) + sin_arg = 2 * (w * y - z * x) + sin_arg = np.clip(sin_arg, -1.0, 1.0) + theta = np.arcsin(sin_arg) + psi = np.arctan2(2 * (w * z + x * y), 1 - 2 * (y**2 + z**2)) + return np.array([gamma, theta, psi]) + + +def quat2rot_single(q): + """ + Convert a quaternion to a 3x3 rotation matrix. + """ + w, x, y, z = q + xx, yy, zz = x * x, y * y, z * z + xy, xz, yz = x * y, x * z, y * z + wx, wy, wz = w * x, w * y, w * z + + mat = np.array([ + [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy)], + [2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx)], + [2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy)] + ]) + return mat + + +def rot2quat_single(rot): + """ + Convert a 3x3 rotation matrix to a quaternion. + """ + trace = np.trace(rot) + if trace > 0: + s = 0.5 / np.sqrt(trace + 1.0) + w = 0.25 / s + x = (rot[2, 1] - rot[1, 2]) * s + y = (rot[0, 2] - rot[2, 0]) * s + z = (rot[1, 0] - rot[0, 1]) * s + else: + if rot[0, 0] > rot[1, 1] and rot[0, 0] > rot[2, 2]: + s = 2.0 * np.sqrt(1.0 + rot[0, 0] - rot[1, 1] - rot[2, 2]) + w = (rot[2, 1] - rot[1, 2]) / s + x = 0.25 * s + y = (rot[0, 1] + rot[1, 0]) / s + z = (rot[0, 2] + rot[2, 0]) / s + elif rot[1, 1] > rot[2, 2]: + s = 2.0 * np.sqrt(1.0 + rot[1, 1] - rot[0, 0] - rot[2, 2]) + w = (rot[0, 2] - rot[2, 0]) / s + x = (rot[0, 1] + rot[1, 0]) / s + y = 0.25 * s + z = (rot[1, 2] + rot[2, 1]) / s + else: + s = 2.0 * np.sqrt(1.0 + rot[2, 2] - rot[0, 0] - rot[1, 1]) + w = (rot[1, 0] - rot[0, 1]) / s + x = (rot[0, 2] + rot[2, 0]) / s + y = (rot[1, 2] + rot[2, 1]) / s + z = 0.25 * s + + if w < 0: + return np.array([-w, -x, -y, -z]) + return np.array([w, x, y, z]) + + +def euler2rot_single(euler): + """ + Convert Euler angles (roll, pitch, yaw) to a 3x3 rotation matrix. + Rotation order: Z-Y-X (yaw, pitch, roll). + """ + phi, theta, psi = euler + + cx, sx = np.cos(phi), np.sin(phi) + cy, sy = np.cos(theta), np.sin(theta) + cz, sz = np.cos(psi), np.sin(psi) + + Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]]) + Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]]) + Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]]) + + return Rz @ Ry @ Rx + + +def rot2euler_single(rot): + """ + Convert a 3x3 rotation matrix to Euler angles (roll, pitch, yaw). + """ + return quat2euler_single(rot2quat_single(rot)) + + +def rot_matrix(roll, pitch, yaw): + """ + Create a 3x3 rotation matrix from roll, pitch, and yaw angles. + """ + return euler2rot_single([roll, pitch, yaw]) + + +def axis_angle_to_rot(axis, angle): + """ + Convert an axis-angle representation to a 3x3 rotation matrix. + """ + c = np.cos(angle / 2) + s = np.sin(angle / 2) + q = np.array([c, s*axis[0], s*axis[1], s*axis[2]]) + return quat2rot_single(q) + + +class LocalCoord: + """ + A class to handle conversions between ECEF and local NED coordinates. + """ + def __init__(self, geodetic=None, ecef=None): + """ + Initialize LocalCoord with either geodetic or ECEF coordinates. + """ + if geodetic is not None: + self.init_ecef = geodetic2ecef_single(geodetic) + lat, lon, _ = geodetic + elif ecef is not None: + self.init_ecef = np.array(ecef) + lat, lon, _ = ecef2geodetic_single(ecef) + else: + raise ValueError("Must provide geodetic or ecef") + + lat = np.radians(lat) + lon = np.radians(lon) + + self.ned2ecef_matrix = np.array([ + [-np.sin(lat) * np.cos(lon), -np.sin(lon), -np.cos(lat) * np.cos(lon)], + [-np.sin(lat) * np.sin(lon), np.cos(lon), -np.cos(lat) * np.sin(lon)], + [np.cos(lat), 0, -np.sin(lat)] + ]) + self.ecef2ned_matrix = self.ned2ecef_matrix.T + + @classmethod + def from_geodetic(cls, geodetic): + """ + Create a LocalCoord instance from geodetic coordinates. + """ + return cls(geodetic=geodetic) + + @classmethod + def from_ecef(cls, ecef): + """ + Create a LocalCoord instance from ECEF coordinates. + """ + return cls(ecef=ecef) + + def ecef2ned_single(self, ecef): + """ + Convert a single ECEF point to NED coordinates relative to the origin. + """ + return self.ecef2ned_matrix @ (ecef - self.init_ecef) + + def ned2ecef_single(self, ned): + """ + Convert a single NED point to ECEF coordinates. + """ + return self.ned2ecef_matrix @ ned + self.init_ecef + + def geodetic2ned_single(self, geodetic): + """ + Convert a single geodetic point to NED coordinates. + """ + ecef = geodetic2ecef_single(geodetic) + return self.ecef2ned_single(ecef) + + def ned2geodetic_single(self, ned): + """ + Convert a single NED point to geodetic coordinates. + """ + ecef = self.ned2ecef_single(ned) + return ecef2geodetic_single(ecef) + + @property + def ned_from_ecef_matrix(self): + """ + Returns the rotation matrix from ECEF to NED coordinates. + """ + return self.ecef2ned_matrix + + @property + def ecef_from_ned_matrix(self): + """ + Returns the rotation matrix from NED to ECEF coordinates. + """ + return self.ned2ecef_matrix + + +def ecef_euler_from_ned_single(ecef_init, ned_pose): + """ + Convert NED Euler angles (roll, pitch, yaw) at a given ECEF origin + to equivalent ECEF Euler angles. + """ + converter = LocalCoord(ecef=ecef_init) + zero = np.array(ecef_init) + + x0 = converter.ned2ecef_single([1, 0, 0]) - zero + y0 = converter.ned2ecef_single([0, 1, 0]) - zero + z0 = converter.ned2ecef_single([0, 0, 1]) - zero + + phi, theta, psi = ned_pose + + x1 = axis_angle_to_rot(z0, psi) @ x0 + y1 = axis_angle_to_rot(z0, psi) @ y0 + z1 = axis_angle_to_rot(z0, psi) @ z0 + + x2 = axis_angle_to_rot(y1, theta) @ x1 + y2 = axis_angle_to_rot(y1, theta) @ y1 + z2 = axis_angle_to_rot(y1, theta) @ z1 + + x3 = axis_angle_to_rot(x2, phi) @ x2 + y3 = axis_angle_to_rot(x2, phi) @ y2 + + x0 = np.array([1.0, 0, 0]) + y0 = np.array([0, 1.0, 0]) + z0 = np.array([0, 0, 1.0]) + + psi_out = np.arctan2(np.dot(x3, y0), np.dot(x3, x0)) + theta_out = np.arctan2(-np.dot(x3, z0), np.sqrt(np.dot(x3, x0)**2 + np.dot(x3, y0)**2)) + + y2 = axis_angle_to_rot(z0, psi_out) @ y0 + z2 = axis_angle_to_rot(y2, theta_out) @ z0 + + phi_out = np.arctan2(np.dot(y3, z2), np.dot(y3, y2)) + + return np.array([phi_out, theta_out, psi_out]) + + +def ned_euler_from_ecef_single(ecef_init, ecef_pose): + """ + Convert ECEF Euler angles (roll, pitch, yaw) at a given ECEF origin + to equivalent NED Euler angles. + """ + converter = LocalCoord(ecef=ecef_init) + + x0 = np.array([1.0, 0, 0]) + y0 = np.array([0, 1.0, 0]) + z0 = np.array([0, 0, 1.0]) + + phi, theta, psi = ecef_pose + + x1 = axis_angle_to_rot(z0, psi) @ x0 + y1 = axis_angle_to_rot(z0, psi) @ y0 + z1 = axis_angle_to_rot(z0, psi) @ z0 + + x2 = axis_angle_to_rot(y1, theta) @ x1 + y2 = axis_angle_to_rot(y1, theta) @ y1 + z2 = axis_angle_to_rot(y1, theta) @ z1 + + x3 = axis_angle_to_rot(x2, phi) @ x2 + y3 = axis_angle_to_rot(x2, phi) @ y2 + + zero = np.array(ecef_init) + x0 = converter.ned2ecef_single([1, 0, 0]) - zero + y0 = converter.ned2ecef_single([0, 1, 0]) - zero + z0 = converter.ned2ecef_single([0, 0, 1]) - zero + + psi_out = np.arctan2(np.dot(x3, y0), np.dot(x3, x0)) + theta_out = np.arctan2(-np.dot(x3, z0), np.sqrt(np.dot(x3, x0)**2 + np.dot(x3, y0)**2)) + + y2 = axis_angle_to_rot(z0, psi_out) @ y0 + z2 = axis_angle_to_rot(y2, theta_out) @ z0 + + phi_out = np.arctan2(np.dot(y3, z2), np.dot(y3, y2)) + + return np.array([phi_out, theta_out, psi_out]) diff --git a/common/transformations/transformations.pyx b/common/transformations/transformations.pyx deleted file mode 100644 index ae045c369d7506..00000000000000 --- a/common/transformations/transformations.pyx +++ /dev/null @@ -1,173 +0,0 @@ -# distutils: language = c++ -# cython: language_level = 3 -from openpilot.common.transformations.transformations cimport Matrix3, Vector3, Quaternion -from openpilot.common.transformations.transformations cimport ECEF, NED, Geodetic - -from openpilot.common.transformations.transformations cimport euler2quat as euler2quat_c -from openpilot.common.transformations.transformations cimport quat2euler as quat2euler_c -from openpilot.common.transformations.transformations cimport quat2rot as quat2rot_c -from openpilot.common.transformations.transformations cimport rot2quat as rot2quat_c -from openpilot.common.transformations.transformations cimport euler2rot as euler2rot_c -from openpilot.common.transformations.transformations cimport rot2euler as rot2euler_c -from openpilot.common.transformations.transformations cimport rot_matrix as rot_matrix_c -from openpilot.common.transformations.transformations cimport ecef_euler_from_ned as ecef_euler_from_ned_c -from openpilot.common.transformations.transformations cimport ned_euler_from_ecef as ned_euler_from_ecef_c -from openpilot.common.transformations.transformations cimport geodetic2ecef as geodetic2ecef_c -from openpilot.common.transformations.transformations cimport ecef2geodetic as ecef2geodetic_c -from openpilot.common.transformations.transformations cimport LocalCoord_c - - -import numpy as np -cimport numpy as np - -cdef np.ndarray[double, ndim=2] matrix2numpy(Matrix3 m): - return np.array([ - [m(0, 0), m(0, 1), m(0, 2)], - [m(1, 0), m(1, 1), m(1, 2)], - [m(2, 0), m(2, 1), m(2, 2)], - ]) - -cdef Matrix3 numpy2matrix(np.ndarray[double, ndim=2, mode="fortran"] m): - assert m.shape[0] == 3 - assert m.shape[1] == 3 - return Matrix3(m.data) - -cdef ECEF list2ecef(ecef): - cdef ECEF e - e.x = ecef[0] - e.y = ecef[1] - e.z = ecef[2] - return e - -cdef NED list2ned(ned): - cdef NED n - n.n = ned[0] - n.e = ned[1] - n.d = ned[2] - return n - -cdef Geodetic list2geodetic(geodetic): - cdef Geodetic g - g.lat = geodetic[0] - g.lon = geodetic[1] - g.alt = geodetic[2] - return g - -def euler2quat_single(euler): - cdef Vector3 e = Vector3(euler[0], euler[1], euler[2]) - cdef Quaternion q = euler2quat_c(e) - return [q.w(), q.x(), q.y(), q.z()] - -def quat2euler_single(quat): - cdef Quaternion q = Quaternion(quat[0], quat[1], quat[2], quat[3]) - cdef Vector3 e = quat2euler_c(q) - return [e(0), e(1), e(2)] - -def quat2rot_single(quat): - cdef Quaternion q = Quaternion(quat[0], quat[1], quat[2], quat[3]) - cdef Matrix3 r = quat2rot_c(q) - return matrix2numpy(r) - -def rot2quat_single(rot): - cdef Matrix3 r = numpy2matrix(np.asfortranarray(rot, dtype=np.double)) - cdef Quaternion q = rot2quat_c(r) - return [q.w(), q.x(), q.y(), q.z()] - -def euler2rot_single(euler): - cdef Vector3 e = Vector3(euler[0], euler[1], euler[2]) - cdef Matrix3 r = euler2rot_c(e) - return matrix2numpy(r) - -def rot2euler_single(rot): - cdef Matrix3 r = numpy2matrix(np.asfortranarray(rot, dtype=np.double)) - cdef Vector3 e = rot2euler_c(r) - return [e(0), e(1), e(2)] - -def rot_matrix(roll, pitch, yaw): - return matrix2numpy(rot_matrix_c(roll, pitch, yaw)) - -def ecef_euler_from_ned_single(ecef_init, ned_pose): - cdef ECEF init = list2ecef(ecef_init) - cdef Vector3 pose = Vector3(ned_pose[0], ned_pose[1], ned_pose[2]) - - cdef Vector3 e = ecef_euler_from_ned_c(init, pose) - return [e(0), e(1), e(2)] - -def ned_euler_from_ecef_single(ecef_init, ecef_pose): - cdef ECEF init = list2ecef(ecef_init) - cdef Vector3 pose = Vector3(ecef_pose[0], ecef_pose[1], ecef_pose[2]) - - cdef Vector3 e = ned_euler_from_ecef_c(init, pose) - return [e(0), e(1), e(2)] - -def geodetic2ecef_single(geodetic): - cdef Geodetic g = list2geodetic(geodetic) - cdef ECEF e = geodetic2ecef_c(g) - return [e.x, e.y, e.z] - -def ecef2geodetic_single(ecef): - cdef ECEF e = list2ecef(ecef) - cdef Geodetic g = ecef2geodetic_c(e) - return [g.lat, g.lon, g.alt] - - -cdef class LocalCoord: - cdef LocalCoord_c * lc - - def __init__(self, geodetic=None, ecef=None): - assert (geodetic is not None) or (ecef is not None) - if geodetic is not None: - self.lc = new LocalCoord_c(list2geodetic(geodetic)) - elif ecef is not None: - self.lc = new LocalCoord_c(list2ecef(ecef)) - - @property - def ned2ecef_matrix(self): - return matrix2numpy(self.lc.ned2ecef_matrix) - - @property - def ecef2ned_matrix(self): - return matrix2numpy(self.lc.ecef2ned_matrix) - - @property - def ned_from_ecef_matrix(self): - return self.ecef2ned_matrix - - @property - def ecef_from_ned_matrix(self): - return self.ned2ecef_matrix - - @classmethod - def from_geodetic(cls, geodetic): - return cls(geodetic=geodetic) - - @classmethod - def from_ecef(cls, ecef): - return cls(ecef=ecef) - - def ecef2ned_single(self, ecef): - assert self.lc - cdef ECEF e = list2ecef(ecef) - cdef NED n = self.lc.ecef2ned(e) - return [n.n, n.e, n.d] - - def ned2ecef_single(self, ned): - assert self.lc - cdef NED n = list2ned(ned) - cdef ECEF e = self.lc.ned2ecef(n) - return [e.x, e.y, e.z] - - def geodetic2ned_single(self, geodetic): - assert self.lc - cdef Geodetic g = list2geodetic(geodetic) - cdef NED n = self.lc.geodetic2ned(g) - return [n.n, n.e, n.d] - - def ned2geodetic_single(self, ned): - assert self.lc - cdef NED n = list2ned(ned) - cdef Geodetic g = self.lc.ned2geodetic(n) - return [g.lat, g.lon, g.alt] - - def __dealloc__(self): - del self.lc diff --git a/common/util.cc b/common/util.cc index 5ffd6e4099f27b..84b47e187ee05e 100644 --- a/common/util.cc +++ b/common/util.cc @@ -1,4 +1,5 @@ #include "common/util.h" +#include "common/swaglog.h" #include #include @@ -12,6 +13,7 @@ #include #include #include +#include #ifdef __linux__ #include @@ -78,8 +80,9 @@ std::string read_file(const std::string& fn) { std::ifstream f(fn, std::ios::binary | std::ios::in); if (f.is_open()) { f.seekg(0, std::ios::end); - int size = f.tellg(); - if (f.good() && size > 0) { + std::streamsize size = f.tellg(); + // seekg and tellg on a directory doesn't return pos_type(-1) but max(streamsize) + if (f.good() && size > 0 && size < std::numeric_limits::max()) { std::string result(size, '\0'); f.seekg(0, std::ios::beg); f.read(result.data(), size); @@ -149,11 +152,16 @@ int safe_fflush(FILE *stream) { return ret; } -int safe_ioctl(int fd, unsigned long request, void *argp) { +int safe_ioctl(int fd, unsigned long request, void *argp, const char* exception_msg) { int ret; do { ret = ioctl(fd, request, argp); } while ((ret == -1) && (errno == EINTR)); + + if (ret == -1 && exception_msg) { + LOGE("safe_ioctl error: %s %s(%d) (fd: %d request: %lx argp: %p)", exception_msg, strerror(errno), errno, fd, request, argp); + throw std::runtime_error(exception_msg); + } return ret; } @@ -173,9 +181,9 @@ bool file_exists(const std::string& fn) { } static bool createDirectory(std::string dir, mode_t mode) { - auto verify_dir = [](const std::string& dir) -> bool { + auto verify_dir = [](const std::string& path) -> bool { struct stat st = {}; - return (stat(dir.c_str(), &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR); + return (stat(path.c_str(), &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR); }; // remove trailing /'s while (dir.size() > 1 && dir.back() == '/') { @@ -255,10 +263,32 @@ bool ends_with(const std::string& s, const std::string& suffix) { strcmp(s.c_str() + (s.size() - suffix.size()), suffix.c_str()) == 0; } +std::string strip(const std::string &str) { + auto should_trim = [](unsigned char ch) { + return std::isspace(ch) || ch == '\0'; + }; + + size_t start = 0; + while (start < str.size() && should_trim(static_cast(str[start]))) { + start++; + } + + if (start == str.size()) { + return ""; + } + + size_t end = str.size() - 1; + while (end > 0 && should_trim(static_cast(str[end]))) { + end--; + } + + return str.substr(start, end - start + 1); +} + std::string check_output(const std::string& command) { char buffer[128]; std::string result; - std::unique_ptr pipe(popen(command.c_str(), "r"), pclose); + std::unique_ptr pipe(popen(command.c_str(), "r"), pclose); if (!pipe) { return ""; @@ -271,4 +301,17 @@ std::string check_output(const std::string& command) { return result; } +bool system_time_valid() { + // Default to August 26, 2024 + tm min_tm = {.tm_mday = 26, .tm_mon = 7, .tm_year = 2024 - 1900}; + time_t min_date = mktime(&min_tm); + + struct stat st; + if (stat("/lib/systemd/systemd", &st) == 0) { + min_date = std::max(min_date, st.st_mtime + 86400); // Add 1 day (86400 seconds) + } + + return time(nullptr) > min_date; +} + } // namespace util diff --git a/common/util.h b/common/util.h index 186873ac216b28..e4483ee7a57c4e 100644 --- a/common/util.h +++ b/common/util.h @@ -37,6 +37,8 @@ const double MS_TO_MPH = MS_TO_KPH * KM_TO_MILE; const double METER_TO_MILE = KM_TO_MILE / 1000.0; const double METER_TO_FOOT = 3.28084; +#define ALIGNED_SIZE(x, align) (((x) + (align)-1) & ~((align)-1)) + namespace util { void set_thread_name(const char* name); @@ -72,6 +74,7 @@ float getenv(const char* key, float default_val); std::string hexdump(const uint8_t* in, const size_t size); bool starts_with(const std::string &s1, const std::string &s2); bool ends_with(const std::string &s, const std::string &suffix); +std::string strip(const std::string &str); // ***** random helpers ***** int random_int(int min, int max); @@ -85,7 +88,7 @@ int write_file(const char* path, const void* data, size_t size, int flags = O_WR FILE* safe_fopen(const char* filename, const char* mode); size_t safe_fwrite(const void * ptr, size_t size, size_t count, FILE * stream); int safe_fflush(FILE *stream); -int safe_ioctl(int fd, unsigned long request, void *argp); +int safe_ioctl(int fd, unsigned long request, void *argp, const char* exception_msg = nullptr); std::string readlink(const std::string& path); bool file_exists(const std::string& fn); @@ -93,6 +96,15 @@ bool create_directories(const std::string &dir, mode_t mode); std::string check_output(const std::string& command); +inline void check_system(const std::string& cmd) { + int ret = std::system(cmd.c_str()); + if (ret != 0) { + fprintf(stderr, "system command failed (%d): %s\n", ret, cmd.c_str()); + } +} + +bool system_time_valid(); + inline void sleep_for(const int milliseconds) { if (milliseconds > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); diff --git a/common/utils.py b/common/utils.py new file mode 100644 index 00000000000000..183363f39d1b54 --- /dev/null +++ b/common/utils.py @@ -0,0 +1,272 @@ +import io +import os +import tempfile +import contextlib +import subprocess +import time +import functools +from subprocess import Popen, PIPE, TimeoutExpired +import zstandard as zstd + +LOG_COMPRESSION_LEVEL = 10 # little benefit up to level 15. level ~17 is a small step change + +class Timer: + """Simple lap timer for profiling sequential operations.""" + + def __init__(self): + self._start = self._lap = time.monotonic() + self._sections = {} + + def lap(self, name): + now = time.monotonic() + self._sections[name] = now - self._lap + self._lap = now + + @property + def total(self): + return time.monotonic() - self._start + + def fmt(self, duration): + parts = ", ".join(f"{k}={v:.2f}s" + (f" ({duration/v:.0f}x)" if k == 'render' and v > 0 else "") for k, v in self._sections.items()) + total = self.total + realtime = f"{duration/total:.1f}x realtime" if total > 0 else "N/A" + return f"{duration}s in {total:.1f}s ({realtime}) | {parts}" + +def sudo_write(val: str, path: str) -> None: + try: + with open(path, 'w') as f: + f.write(str(val)) + except PermissionError: + os.system(f"sudo chmod a+w {path}") + try: + with open(path, 'w') as f: + f.write(str(val)) + except PermissionError: + # fallback for debugfs files + os.system(f"sudo su -c 'echo {val} > {path}'") + + +def sudo_read(path: str) -> str: + try: + return subprocess.check_output(["sudo", "cat", "--", path], encoding='utf8').strip() + except Exception: + return "" + + +class MovingAverage: + def __init__(self, window_size: int): + self.window_size: int = window_size + self.buffer: list[float] = [0.0] * window_size + self.index: int = 0 + self.count: int = 0 + self.sum: float = 0.0 + + def add_value(self, new_value: float): + # Update the sum: subtract the value being replaced and add the new value + self.sum -= self.buffer[self.index] + self.buffer[self.index] = new_value + self.sum += new_value + + # Update the index in a circular manner + self.index = (self.index + 1) % self.window_size + + # Track the number of added values (for partial windows) + self.count = min(self.count + 1, self.window_size) + + def get_average(self) -> float: + if self.count == 0: + return float('nan') + return self.sum / self.count + + +class CallbackReader: + """Wraps a file, but overrides the read method to also + call a callback function with the number of bytes read so far.""" + + def __init__(self, f, callback, *args): + self.f = f + self.callback = callback + self.cb_args = args + self.total_read = 0 + + def __getattr__(self, attr): + return getattr(self.f, attr) + + def read(self, *args, **kwargs): + chunk = self.f.read(*args, **kwargs) + self.total_read += len(chunk) + self.callback(*self.cb_args, self.total_read) + return chunk + + +@contextlib.contextmanager +def atomic_write(path: str, mode: str = 'w', buffering: int = -1, encoding: str | None = None, newline: str | None = None, + overwrite: bool = False): + """Write to a file atomically using a temporary file in the same directory as the destination file.""" + dir_name = os.path.dirname(path) + + if not overwrite and os.path.exists(path): + raise FileExistsError(f"File '{path}' already exists. To overwrite it, set 'overwrite' to True.") + + with tempfile.NamedTemporaryFile(mode=mode, buffering=buffering, encoding=encoding, newline=newline, dir=dir_name, delete=False) as tmp_file: + yield tmp_file + tmp_file_name = tmp_file.name + os.replace(tmp_file_name, path) + + +def get_upload_stream(filepath: str, should_compress: bool) -> tuple[io.BufferedIOBase, int]: + if not should_compress: + file_size = os.path.getsize(filepath) + file_stream = open(filepath, "rb") + return file_stream, file_size + + # Compress the file on the fly + compressed_stream = io.BytesIO() + compressor = zstd.ZstdCompressor(level=LOG_COMPRESSION_LEVEL) + + with open(filepath, "rb") as f: + compressor.copy_stream(f, compressed_stream) + compressed_size = compressed_stream.tell() + compressed_stream.seek(0) + return compressed_stream, compressed_size + + +# remove all keys that end in DEPRECATED, plus any "deprecated" group +def strip_deprecated_keys(d): + for k in list(d.keys()): + if isinstance(k, str): + if k.endswith('DEPRECATED') or k == 'deprecated': + d.pop(k) + elif isinstance(d[k], dict): + strip_deprecated_keys(d[k]) + return d + + +def run_cmd(cmd: list[str], cwd=None, env=None) -> str: + return subprocess.check_output(cmd, encoding='utf8', cwd=cwd, env=env).strip() + + +def run_cmd_default(cmd: list[str], default: str = "", cwd=None, env=None) -> str: + try: + return run_cmd(cmd, cwd=cwd, env=env) + except subprocess.CalledProcessError: + return default + + +@contextlib.contextmanager +def managed_proc(cmd: list[str], env: dict[str, str]): + proc = Popen(cmd, env=env, stdout=PIPE, stderr=PIPE) + try: + yield proc + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except TimeoutExpired: + proc.kill() + + +def tabulate(tabular_data, headers=(), tablefmt="simple", floatfmt="g", stralign="left", numalign=None): + rows = [list(row) for row in tabular_data] + + def fmt(val): + if isinstance(val, str): + return val + if isinstance(val, (bool, int)): + return str(val) + try: + return format(val, floatfmt) + except (TypeError, ValueError): + return str(val) + + formatted = [[fmt(c) for c in row] for row in rows] + hdrs = [str(h) for h in headers] if headers else None + + ncols = max((len(r) for r in formatted), default=0) + if hdrs: + ncols = max(ncols, len(hdrs)) + if ncols == 0: + return "" + + for r in formatted: + r.extend([""] * (ncols - len(r))) + if hdrs: + hdrs.extend([""] * (ncols - len(hdrs))) + + widths = [0] * ncols + if hdrs: + for i in range(ncols): + widths[i] = len(hdrs[i]) + for row in formatted: + for i in range(ncols): + widths[i] = max(widths[i], max(len(ln) for ln in row[i].split('\n'))) + + def _align(s, w): + if stralign == "center": + return s.center(w) + return s.ljust(w) + + if tablefmt == "html": + parts = [""] + if hdrs: + parts.append("") + parts.append("" + "".join(f"" for h in hdrs) + "") + parts.append("") + parts.append("") + for row in formatted: + parts.append("" + "".join(f"" for c in row) + "") + parts.append("") + parts.append("
{h}
{c}
") + return "\n".join(parts) + + if tablefmt == "simple_grid": + def _sep(left, mid, right): + return left + mid.join("\u2500" * (w + 2) for w in widths) + right + + top, mid_sep, bot = _sep("\u250c", "\u252c", "\u2510"), _sep("\u251c", "\u253c", "\u2524"), _sep("\u2514", "\u2534", "\u2518") + + def _fmt_row(cells): + split = [c.split('\n') for c in cells] + nlines = max(len(s) for s in split) + for s in split: + s.extend([""] * (nlines - len(s))) + return ["\u2502" + "\u2502".join(f" {_align(split[i][li], widths[i])} " for i in range(ncols)) + "\u2502" for li in range(nlines)] + + lines = [top] + if hdrs: + lines.extend(_fmt_row(hdrs)) + lines.append(mid_sep) + for ri, row in enumerate(formatted): + lines.extend(_fmt_row(row)) + lines.append(mid_sep if ri < len(formatted) - 1 else bot) + return "\n".join(lines) + + # simple + gap = " " + lines = [] + if hdrs: + lines.append(gap.join(h.ljust(w) for h, w in zip(hdrs, widths, strict=True))) + lines.append(gap.join("-" * w for w in widths)) + for row in formatted: + lines.append(gap.join(_align(row[i], widths[i]) for i in range(ncols))) + return "\n".join(lines) + + +def retry(attempts=3, delay=1.0, ignore_failure=False): + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + for _ in range(attempts): + try: + return func(*args, **kwargs) + except Exception: + print(f"{func.__name__} failed, trying again") + time.sleep(delay) + + if ignore_failure: + print(f"{func.__name__} failed after retry") + else: + raise Exception(f"{func.__name__} failed after retry") + return wrapper + return decorator diff --git a/common/version.h b/common/version.h index 1f651fb3926dd6..41440556c54eef 100644 --- a/common/version.h +++ b/common/version.h @@ -1 +1 @@ -#define COMMA_VERSION "0.9.8" +#define COMMA_VERSION "0.11.1" diff --git a/common/watchdog.cc b/common/watchdog.cc deleted file mode 100644 index 3483ad21c2c608..00000000000000 --- a/common/watchdog.cc +++ /dev/null @@ -1,11 +0,0 @@ -#include - -#include "common/watchdog.h" -#include "common/util.h" - -const std::string watchdog_fn_prefix = "/dev/shm/wd_"; // + - -bool watchdog_kick(uint64_t ts) { - static std::string fn = watchdog_fn_prefix + std::to_string(getpid()); - return util::write_file(fn.c_str(), &ts, sizeof(ts), O_WRONLY | O_CREAT) > 0; -} diff --git a/common/watchdog.h b/common/watchdog.h deleted file mode 100644 index 12dd2ca0355f09..00000000000000 --- a/common/watchdog.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include - -bool watchdog_kick(uint64_t ts); diff --git a/conftest.py b/conftest.py index fc4931fb54d2f9..f2fd482be9947f 100644 --- a/conftest.py +++ b/conftest.py @@ -2,17 +2,19 @@ import gc import os import pytest -import random from openpilot.common.prefix import OpenpilotPrefix from openpilot.system.manager import manager from openpilot.system.hardware import TICI, HARDWARE - -def pytest_sessionstart(session): - # TODO: fix tests and enable test order randomization - if session.config.pluginmanager.hasplugin('randomly'): - session.config.option.randomly_reorganize = False +# these are heavy CI-only tests, invoked explicitly in .github/workflows/tests.yaml +collect_ignore = [ + "selfdrive/test/process_replay/test_processes.py", + "selfdrive/test/process_replay/test_regen.py", +] +collect_ignore_glob = [ + "selfdrive/debug/*.py", +] @pytest.hookimpl(hookwrapper=True, trylast=True) @@ -36,8 +38,6 @@ def clean_env(): @pytest.fixture(scope="function", autouse=True) def openpilot_function_fixture(request): - random.seed(0) - with clean_env(): # setup a clean environment for each test with OpenpilotPrefix(shared_download_cache=request.node.get_closest_marker("shared_download_cache") is not None) as prefix: @@ -65,8 +65,10 @@ def openpilot_class_fixture(): @pytest.fixture(scope="function") -def tici_setup_fixture(openpilot_function_fixture): +def tici_setup_fixture(request, openpilot_function_fixture): """Ensure a consistent state for tests on-device. Needs the openpilot function fixture to run first.""" + if 'skip_tici_setup' in request.keywords: + return HARDWARE.initialize_hardware() HARDWARE.set_power_save(False) os.system("pkill -9 -f athena") @@ -86,15 +88,3 @@ def pytest_collection_modifyitems(config, items): class_property_name = item.get_closest_marker('xdist_group_class_property').args[0] class_property_value = getattr(item.cls, class_property_name) item.add_marker(pytest.mark.xdist_group(class_property_value)) - - -@pytest.hookimpl(trylast=True) -def pytest_configure(config): - config_line = "xdist_group_class_property: group tests by a property of the class that contains them" - config.addinivalue_line("markers", config_line) - - config_line = "nocapture: don't capture test output" - config.addinivalue_line("markers", config_line) - - config_line = "shared_download_cache: share download cache between tests" - config.addinivalue_line("markers", config_line) diff --git a/docs-nap/README.md b/docs-nap/README.md new file mode 100644 index 00000000000000..1f4a098165043c --- /dev/null +++ b/docs-nap/README.md @@ -0,0 +1,29 @@ +# NAP Developer Docs + +Documentation for contributors working on NotAutopilot. These are NAP-specific — upstream openpilot docs live in `docs/` (comma.ai). + +## Start here + +- **[contributing.md](contributing.md)** — branch structure, pre-push checklist, submodules, how to submit bugs +- **[architecture.md](architecture.md)** — Pre-AP Model S design overview: standalone safety model, radar emulation, pedal interceptor +- **[safety-model.md](safety-model.md)** — panda safety invariants for the Pre-AP target +- **[map-speed.md](map-speed.md)** — OSM map speed → HUD MAX / cruise set speed (comma 3X) +- **[force-offroad.md](force-offroad.md)** — Settings → triple-tap NAP → Force Offroad / Go Offline (started=false while moving) +- **[speed-sign-log.md](speed-sign-log.md)** — on-drive MUTCD speed-sign JSONL logger (log-only, default off) +- **[engagement.md](engagement.md)** — stalk FSM, pedal-vs-no-pedal engagement paths, brake behavior, driver-wheel lateral handoff (default On; intent-to-steer yield; emergency hard-brake full cancel; Settings can disable) +- **[hypermile.md](hypermile.md)** — Hypermile eco snap + Hill Climb (nap-dev experimental, default Off). Stock Follow Distance 1–7 is shared; Hypermile does not own follow. +- **[nap-dash.md](nap-dash.md)** — comma web UI at `http://100.99.9.1/` (Params + `/api/software`, no cereal). Hotspot `100.99.9.0/24`. Optional process. Flash `cursor/mcu-web-ui-c588`. Do not merge until Justin confirms. + +## Layout + +``` +openpilot-nap/ +├── docs/ # upstream openpilot docs (comma.ai) +├── docs-nap/ # ← you are here +├── opendbc_repo/ # submodule: NotAutopilot/opendbc fork +├── panda/ # submodule: commaai/panda (tracked upstream) +├── selfdrive/ +└── ... +``` + +The Pre-AP car port lives in `opendbc_repo/opendbc/car/tesla/preap/` and the standalone panda safety mode in `opendbc_repo/opendbc/safety/modes/tesla_preap.h`. diff --git a/docs-nap/architecture.md b/docs-nap/architecture.md new file mode 100644 index 00000000000000..0fa79565904a24 --- /dev/null +++ b/docs-nap/architecture.md @@ -0,0 +1,99 @@ +# Pre-AP Architecture + +High-level design of NAP's Pre-AP Model S port. For safety-layer details see [safety-model.md](safety-model.md); for the engagement flow see [engagement.md](engagement.md). + +## What makes pre-AP different + +2012–2014 Model S cars have no Autopilot ECU, no harness relay, and a CAN layout distinct from HW1+ Teslas. Standard openpilot assumes a relay that routes CAN between stock AP and the panda — pre-AP has neither. The port is a spiritual successor to Tinkla (`boggyver/openpilot`, `tesla_unity_betaC3`). + +## Layout + +``` +opendbc_repo/opendbc/ +├── car/tesla/preap/ # Python car port +│ ├── interface.py # CarParams + safety flags +│ ├── carstate.py # CAN → CarState translation +│ ├── carcontroller.py # CarControl → CAN (steering + pedal + stalk spoof) +│ ├── engagement.py # stalk FSM (double-pull, brake, cancel) +│ ├── pedal_feedback.py # Comma Pedal interceptor parser + health tracking +│ ├── constants.py # accel profiles, pedal PID tunings +│ └── nap_conf.py # runtime config (Params-backed) +├── safety/modes/tesla_preap.h # standalone panda safety mode +└── dbc/tesla_preap.dbc # CAN message definitions +``` + +## Major subsystems + +### Standalone safety mode (`tesla_preap.h`) + +Independent from `tesla_legacy.h` and upstream tesla safety. Its own hooks, counter/checksum, init, and RX/TX/fwd paths. Registered as `SAFETY_TESLA_PREAP`. + +Key rationale for each nonstandard setting is commented in the file header. In short: + +- `check_relay=false` + `disable_static_blocking=true` on every TX: pre-AP has no harness relay +- `ignore_checksum=true` + `ignore_counter=true` on RX: the pre-AP EPAS checksum algorithm is not fully verified across firmware versions; mismatched validation caused a silent 21-second steering dropout during testing + +All actual safety checks are active (steering angle/rate limits, hands-on disengage except during a blinker-latched driver turn, EPAS error codes, door/gear, stalk echo-filtered cancel, AEB block). A tesla_preap.h change requires a panda flash after pull. + +### Radar (optional) + +Bosch radar with GTW (GateWay ECU) emulation. The panda forwards chassis-bus traffic with a radar-position rewrite when `RADAR_BEHIND_NOSECONE` is set. The emulation hook is `rx_all` (not `rx`) because it must see every CAN frame, not just whitelisted ones. + +`tesla_radar_bosch_generated.dbc` and `tesla_radar_continental_generated.dbc` are produced by device scons from `opendbc_repo/opendbc/dbc/generator/` and are not in git. See [contributing.md](contributing.md). + +### Comma Pedal (optional) + +Pedal interceptor on bus 0 or bus 2 (wiring varies). Interface flag `ENABLE_PEDAL` gates both TX whitelist (`0x551` GAS_COMMAND) and RX route (`0x552` GAS_SENSOR). Without the pedal, pre-AP uses stock Tesla CC via stalk-spoof engage/cancel — see [engagement.md](engagement.md). + +### EPAS firmware ownership + +The NAP settings panel exposes EPAS firmware switching. Steering only engages when the EPAS variant is known-good for our compute_checksum. See the on-device settings for supported firmware. + +## Vehicle model + +Physical parameters (mass, wheelbase, steer ratio) come from `CarSpecs` in `opendbc_repo/opendbc/car/tesla/values.py`. Pre-AP is the same platform as HW1/HW2/HW3 Model S; we inherit the HW3 values. Do **not** override in `preap/interface.py` — the framework adds `STD_CARGO_KG` automatically, and overriding double-counts it. + +Panda steering params (`PREAP_STEERING_PARAMS` in `tesla_preap.h`) must match the Python-layer `VehicleModel(TESLA_MODEL_S_PREAP)`. Verify: + +```python +from opendbc.car.tesla.interface import CarInterface +from opendbc.car.vehicle_model import VehicleModel, calc_slip_factor +VM = VehicleModel(CarInterface.get_non_essential_params("TESLA_MODEL_S_PREAP")) +print(calc_slip_factor(VM)) # must match slip_factor in tesla_preap.h +``` + +Any divergence causes the steering angle command limiter to disagree between layers — silent control ceiling. + +## Upstream relationship + +NAP tracks upstream openpilot closely. We fork `opendbc` because the pre-AP DBCs, car port, and safety mode all live there and are NAP-only. We track upstream `panda` directly — pre-AP safety changes go through the `opendbc_repo/opendbc/safety/` path that panda pulls in as a submodule. + +See [Tinkla](https://github.com/boggyver/openpilot/tree/tesla_unity_betaC3) and [xnor-tech/openpilot](https://github.com/xnor-tech/openpilot) for the prior art NAP builds on. + +## Turn stalk vs automatic lane change + +Pre-AP `TurnIndLvr_Stat` is only IDLE / LEFT / RIGHT / SNA — no tip vs latch bit. NAP classifies from hold time (`selfdrive/controls/lib/stalk_tip_turn.py`): + +- **Tip:** LEFT or RIGHT then IDLE within `STALK_TIP_HOLD_S` (0.40s) → arm ALC at any speed (wheel nudge still starts the change; opposite tap cancels; stalk IDLE alone does not). +- **Held turn:** LEFT or RIGHT past 0.40s from idle → do not arm ALC; latch a driver turn (flash-latch ~1s dark). Soft-lat **Off** still pauses lat (hand release resumes). Soft-lat **On** does not clear `latActive` on lamp latch; the driver may still soft-yield, and take-back is inhibited until the latch ends (then yield + normal 0.15 s confirm + 1 s blend). A driver turn does **not** drop longitudinal — `enableLongControl` stays true and lead/map braking and accel apply through the turn. Brake still uses the silent long pause; interceptor RELEASEs immediately to stock regen. +- **During ALC / leftover keep-alive:** same-direction physical stalk held past `STALK_ALC_TURN_HOLD_S` (1.0s) cancels ALC, stops OP blinker keep-alive, and latches a driver turn (Soft-lat Off pauses lat; Soft-lat On inhibits re-enable). A shorter same-direction hold does not force a turn. Opposite brief tap still cancels ALC without becoming a turn; opposite held uses the 0.40s window. + +`LANE_CHANGE_SPEED_MIN` (20 mph) still gates *starting* the lane-change maneuver after a nudge, not tip vs turn and not pause vs ALC. Hazards do neither. ALC keep-alive lamps do not pause lat. + +## Driver-wheel temporary lateral handoff + +**Default On** (`NAPDriverLatHandoff=1`). Yield on **driver intent** (sustained torsion + aligned steer rate + hands on the rim), not gravel/wind/crown. Stay yielded while `EPAS_handsOnLevel >= 1`; 1 s blend starts after ~0.15 s of hands truly off. Emergency/hard brake (`aEgo <= −3.5 m/s²` for 80 ms + digital Applied) during yield / 2 s window fully cancels OP. Light brake is still the silent long pause. A driver-turn blinker does not strip lat when soft-lat is On; after a yielded turn, resume is yield + 0.15 s confirm + 1 s blend (no dedicated blinker blend). The same re-enable inhibit ORs **v_ego < 10 mph** (`LAT_REENABLE_MIN_V_EGO_MPH`). Turn Off in Settings → NAP → Driving Mannerisms if false-yields remain — Off also restores stock blinker lat-pause. See [engagement.md](engagement.md#driver-wheel-temporary-lateral-handoff). + +## Driver monitoring (simulate looking) + +Stock DM timers stay **3 / 5 / 11 s**. Looking-away / distraction alerts **do not fire below 2 mph** (`DM_LOOKAWAY_GATE_MPH` in `policy.py`) — stock standstill pause plus creeping; Simulate Look / FAI stay as toggled. Triple-tap **NAP** (1.0 s window; not under Driving Mannerisms) has three hidden toggles: **Force Offroad**, **Simulate Look**, **False Alert Ignore**. On nap-dev, Simulate Look defaults **On** and False Alert Ignore defaults **Off** — they are **mutually exclusive** (both Off is allowed; stale both-On → Simulate Look On). Shared cadence: drain **past 1.0 s**, then fire uniform in **(1.0 s, 3.0 s]**. `NAPDmSimulateLooking` is the pre-FAI **full looking-path wipe** (no-face / uncertain / phone / pose / eye) so common false nags recover on cadence. `NAPDmFalseAlertIgnore` (Sim Look Off) soft-clears **phone/device** false positives (`phoneProb` / `distracted_types['phone']`) only, and only when pose and eye are not alarming. Either toggle Off = that path is stock. Hard cancels (hands-on ≥ 2, stalk, door, reverse) are unchanged. See [engagement.md](engagement.md#driver-monitoring-simulate-looking). + +## OSM map speed (MAX) + +`selfdrive/mapd` looks up OpenStreetMap `maxspeed` from an offline sqlite and publishes `liveMapDataNAP`. In pre-AP **pedal** mode, `card.py` overlays that limit onto software cruise (`CS.vCruise` / HUD **MAX**): Cap never raises, Follow tracks the sign, engage seeds to the posted limit, and a Follow stalk set (above or below) holds until the posted limit changes. A sharp curve snapshots that MAX and restores it after the bend so temporary corner slowing / OSM flicker cannot permanently rebase sticky (Hypermile eco must not bounce a pre-curve 60 down to the live posted-scaled target). HUD current speed is wheel/ESP `vEgo` (not `vEgoCluster` / MAX). When ego is above MAX the planner commands Accel-5 comfort decel (`map_track_decel`); when ego is below MAX and there is **no** radar lead it commands Accel 1–10 climb (`map_track_accel`, last-mph taper). A valid lead owns follow — map climb must not replace non-negative MPC `a` (or add Hill Climb `+g·sin`) toward MAX through that lead. `map_track_decel` above MAX still mins in with a lead. Hypermile **Hill Climb** (default On while Hypermile is On; IMU pitch only — **no maps-elevation lookahead**) adds `g·sin(pitch)` to that climb on a real uphill **under** MAX so Accel 1 does not sag, and applies a light crest/downhill ease **only at or above MAX** (not `TRACK_TAPER`); deadband leaves hold 0 (no `+g·sin` past MAX). It never raises MAX and lead/MPC brake still win. Coming up behind a radar lead caps **positive** close-the-gap accel to the same Accel 1–10 envelope inside ~200 m so catch-up is not the cruise 1.6–0.6 punch. Non-rapid MPC −a is floored at mild ease; FCW / rapid still own danger. `LongitudinalMpc.update(radarState, v_cruise)` still takes `min(lead, cruise)`. No-pedal stock CC is display-only. US maps are a GitHub Release download; Refresh maps overlays live OSM within 100 miles. Details: [map-speed.md](map-speed.md). + +Behind a radar lead, a Pre-AP stalk **tip** (first detent, 1 mph) undoes that frame’s MAX and steps City or Highway Follow Distance 1–7 (`NAPFollowDistanceCity` / `NAPFollowDistanceHwy`, HUD still `NAPFollowDistance`) when the lever returns to IDLE. Highway when MAX is 50 mph or higher (including while still accelerating up to that MAX, and including exactly 50). City when MAX is under 50, even if the car is already going faster. Traveled speed picks the band only when MAX is unset. Live follow uses that same cut, so slowing under a highway MAX does not open the city gap. A **full press** (2nd detent, 5 mph) still steps MAX +5/−5 and does not remap Follow — even if the press passed through first detent. Hypermile On or Off. The Driving Mannerisms sliders stay visible and update live. No lead: tip and hold both still step MAX. Hypermile does not own follow levels. See [hypermile.md](hypermile.md) and [engagement.md](engagement.md). + +## Speed sign logger (log-only) + +`selfdrive/speedsignd` is a separate on-road process (default **Off**, Settings → NAP → Speed Sign Logger). Stock `modelV2` has no speed-sign head, so this runs a compact YOLOv8 ONNX on the ROAD camera (+ GNSS for JSONL) and publishes `liveSpeedSignNAP` for a display-only SIGN plate. Weights live on `/data` (not git). It does not write the OSM sqlite, does not change `vCruise`, and does not query osm.org. **No YOLO while openpilot is actively controlling** (`selfdriveState.active`; SIGN shows WAIT). Manual driving (moving OK) still detects at **1 Hz** with skip-on-overrun and nice 19; SubMaster polls at 20 Hz so cereal alive/valid cannot stuck WAIT. Not gated on park / Force Offroad. Unthrottled 4 Hz YOLO on a 3X starved `modeld` and can TAKE CONTROL. Details: [speed-sign-log.md](speed-sign-log.md). diff --git a/docs-nap/contributing.md b/docs-nap/contributing.md new file mode 100644 index 00000000000000..85ee1d6d4919fc --- /dev/null +++ b/docs-nap/contributing.md @@ -0,0 +1,105 @@ +# Contributing + +Pull requests welcome against `nap-dev`. For anything non-trivial, open an issue first. + +## Branches + +| openpilot branch | opendbc branch | purpose | +|------------------|----------------|---------| +| `nap-dev` | `nap-dev` | active development | +| `nap-alpha` | `nap-alpha` | tester builds (mirrors `nap-dev` when stable) | +| `nap-release` | `nap-release` | production release (what `installer.comma.ai/NotAutopilot/openpilot/nap-release` serves) | +| `naponsp-dev` | `naponsp-dev` | sunnypilot fork (keep sunnypilot-specific code here only) | + +Do not push sunnypilot-specific code (MADS, `CP_SP`, etc.) to `nap-dev` or `nap-alpha`. + +Soft Lateral Handoff (`NAPDriverLatHandoff`) defaults **On** (Settings → NAP → Driving Mannerisms). Yield is a light purposeful push (torsion ≥ ~0.55 Nm / ~90 ms + hands) that **frees the EPS** (`latActive` false), not follow-measured angle hold. Rate is not an entry gate. Gravel spikes and low-torsion wind must not yield. Parking-lot blinker 1 s re-entry stays. Emergency/hard brake during yield fully cancels; light brake must keep the silent long-pause / one-SET path. Turn the toggle **Off** if false-yields remain. + +Simulate Look (`NAPDmSimulateLooking`) defaults **On**. False Alert Ignore (`NAPDmFalseAlertIgnore`) defaults **Off**. They are **mutually exclusive** — only one may be On (both Off is allowed). Reveal them with Force Offroad via a **triple-tap on Settings → NAP** (3 taps within 1.0 s; order Force Offroad / Simulate Look / False Alert Ignore). Shared cadence: after drain is past **1.0 s**, fire at a random time in the next **2.0 s** (**(1.0 s, 3.0 s]**). Simulate Look On is the pre-FAI **full looking-path wipe** (no-face / uncertain / phone / pose / eye). False Alert Ignore On (Sim Look Off) soft-clears phone/device false positives only, and only when pose/eye are not alarming. Turning one On clears the other (and aborts the other in-flight path). A stale both-On from older installs resolves to Simulate Look On / FAI Off on first read. Looking-away alerts also pause below **2 mph** regardless of those toggles. + +Hypermile (`NAPHypermile`) defaults **Off** (nap-dev experimental). Hill Climb (`NAPHypermileHillClimb`) defaults **On** but is inert unless Hypermile is On. See [hypermile.md](hypermile.md). Do not merge Hypermile into nap-release until Justin signs off. + +One-Pedal Long (`NAPOnePedalLong`) defaults **Off**. Pedal mode: gas while long is **already holding** **pauses** software long (silent long pause, lat stays, not a full disable) and **holds that pause until a stalk SET** — lift / coast / regen must not resume or climb back to MAX. SET with the foot already on the pedal still arms long; lift starts A+B/A3. Brake that pauses long RELEASEs immediately to stock regen (no tip-brake soft glide). Off = stock gas override + A+B/A3. + +## Submodules + +`panda` and `opendbc_repo` use NotAutopilot forks. After checkout: + +```bash +git submodule sync --recursive +git submodule update --init --recursive +``` + +When bumping the `opendbc_repo` pointer, push the submodule change first, then the pointer bump in the main repo. + +## Local build (macOS) + +```bash +source .venv/bin/activate +scons -j$(sysctl -n hw.ncpu) +``` + +## Device build + +On Comma hardware, scons defaults to `--minimal` (`TICI`, extras off). That +build must still generate Tesla radar DBCs; they are not in git: + +- `opendbc_repo/opendbc/dbc/tesla_radar_bosch_generated.dbc` +- `opendbc_repo/opendbc/dbc/tesla_radar_continental_generated.dbc` + +Source is `opendbc_repo/opendbc/dbc/generator/`. Do not turn on extras on +device just to get these files (extras builds tests/tools/cabana). Check: + +```bash +scons --minimal opendbc_generated_dbcs +``` + +## CI build (Linux x86_64) + +Reproduces the GitHub Actions build locally: + +```bash +docker build -t nap-ci -f Dockerfile.openpilot . +docker run --rm nap-ci bash -c "source .venv/bin/activate && scons -j\$(nproc)" +``` + +## Pre-AP safety tests + +```bash +source .venv/bin/activate +python -m pytest opendbc_repo/opendbc/safety/tests/test_tesla_preap.py -v +``` + +Safety-critical code (`opendbc_repo/opendbc/safety/**`) must ship with test coverage. See the existing test file for the pattern. + +## Pre-push checklist + +Before pushing to any `nap-*` branch: + +1. Local `scons` succeeds +2. `pytest opendbc_repo/opendbc/safety/tests/test_tesla_preap.py` green +3. If touching `safety/`, run the Docker CI build too +4. If bumping `opendbc_repo`, confirm the submodule SHA has been pushed upstream + +## Release notes + +When pushing user-facing changes to `nap-dev`, update the top section of `RELEASES.md`. The comma updater shows this on the device's Software update screen. + +Format: +``` +Version X.Y.Z (YYYY-MM-DD) +======================== +* Short description of change +* Another change +``` + +Only the text before the first blank line is displayed. Keep it concise. File is parsed by `system/updated/updated.py:parse_release_notes()`. + +## Bug reports + +Report in `#bug-reports` on [Discord](https://discord.gg/notautopilot), not DMs. Include: + +- What happened (symptom, not just "didn't work") +- Car year/model (must be pre-AP Model S) +- NAP branch + commit if known +- Route ID from [comma connect](https://connect.comma.ai) if applicable diff --git a/docs-nap/engagement.md b/docs-nap/engagement.md new file mode 100644 index 00000000000000..c3585f0c6e4721 --- /dev/null +++ b/docs-nap/engagement.md @@ -0,0 +1,241 @@ +# Engagement Flow + +Pre-AP has two modes depending on whether a Comma Pedal is installed. Mode is selected by `nap_conf.use_pedal` (NAP settings panel, persisted via Params). Both modes share the same stalk FSM in `engagement.py`. + +## State vocabulary + +- `cruiseEnabled` — NAP is engaged at the FSM level (lateral on) +- `enableLongControl` — NAP is actively modulating longitudinal (pedal mode only) +- `enableJustCC` — NAP is lateral-only, stock CC is (or will be) driving speed +- `pedal_long_allowed = use_pedal AND pedal_transform_valid` — pedal hardware is usable +- `long_control_allowed = (not use_pedal) OR pedal_transform_valid` — NAP's FSM may transition into the "cruise" state (pedal mode requires a valid pedal transform) + +## Pedal mode + +`use_pedal=True`, pedal hardware present: + +1. Driver pulls the stalk once while rolling, foot off the accelerator, brake not held → `cruiseEnabled=True`, `enableLongControl=True` on that pull. MAX is take-speed-now (posted limit + offset when maps know it, otherwise current speed). One engage chime: lat and long rise together, and the higher-priority Pedal Cruise Engaged alert is the sound. Stock cruise still gets the same CANCEL (button press and long rising edge). A second pull inside `double_pull_window_ms` stays engaged and applies take-speed-now again. At a stop, that single pull engages lateral and arms long as wait-for-gas — it does not roll the car; a Tesla DI gas tap (DI > 2, not interceptor rest noise) starts long at the same take-now MAX. Brake held stays lateral-only. Foot already on the gas keeps engage-while-gas (arm long, lift acquires). +2. `carcontroller.py` sends `GAS_COMMAND` (0x551) based on `actuators.accel` from the long planner +3. Zero-torque learning tracks the resting pedal position that produces zero torque at the current speed. On engage, we seed `prev_pedal_di` to this value so there is no regen spike +4. Brake rising edge → drops `enableLongControl=False`, keeps `cruiseEnabled=True` (steering stays on, pedal drops). `enableJustCC` flips true so the carcontroller knows to spoof stock CC cancel. This is a **silent long pause**, not a full disengage: no `EventName.pedalCruiseDisabled` / no disengage chime / no HUD “Pedal Cruise Disengaged”. Held MAX (`pedal_speed_kph` / `MapCruiseHold.held_max_kph` / sticky set) is remembered. Soft-wheel handoff is a separate lat-only path and does not use this pause. **Exception:** an emergency/hard brake *during a soft-lat yield* (or within 2 s of yield entry) fully cancels the session — see below. Light brake alone never takes that path. After the long drop, interceptor RELEASEs immediately to stock Tesla regen — no tip/hold classification, no coast hold, no comfort-shaped regen ramp. FCW / AEB / hard lead while long is still on are unchanged. +5. A latched **driver turn** blinker (held stalk / flash-latched lamps, not ALC tip or keep-alive) does **not** drop `enableLongControl`. Long stays engaged; normal lead/map braking and accel apply through the turn. **Soft-lat Off:** lateral still pauses on lamp latch and resumes only after hand release. **Soft-lat On:** blinker-on alone does **not** drop `latActive`; the driver may still soft-yield by pushing, and soft-lat will not take lateral back while the driver-turn blinker is latched. After the blinker clears, a yielded turn resumes through soft yield + the normal 0.15 s hands-off confirm + 1 s blend (no dedicated blinker blend). Brake still uses the silent long pause + sticky MAX + one SET / double SET. Tip ALC is not a driver turn and already does not drop long. +6. Gas press → `OVERRIDE_LONGITUDINAL` **when One-Pedal Long is Off** (default). Pedal command passes through with `enable=0` — driver's foot controls throttle directly, NAP tracks position for smooth resume. Long engage/disengage prompts follow `enableLongControl` for **session** edges (initial engage / full cancel), not interceptor handshake, not gas override, and not a brake / one-pedal long pause. `enableLongControl` stays true while the driver is on the pedal, so press and release are silent. On the gas falling edge, ACQUIRE expires the 0.5 s engage-grace a=0 floor and seeds VDAS from `max(last non-negative aEgo, planner climb)` (clamped to the personality MAX). Open-road planner climb is Mannerisms **Acceleration** 1–10 toward HUD MAX. Lead hard decel / FCW / should-stop (`actuators.accel < 0`) still seed 0 and pass through immediately. Brake clears the pending handoff so a later SET resume keeps the normal grace ramp. First engage without prior gas is unchanged. + - **One-Pedal Long On** (Settings → NAP → Driving Mannerisms, default Off): if OP long is **already holding with the foot off** and the accelerator is then pressed (interceptor DI **> 1**, slightly more sensitive than stock `gasPressed` DI **> 2**; not `DI_pedalPos`), **pause** `enableLongControl` with the same silent long pause as brake (`_drop_longitudinal_keep_lateral`: lat stays, sticky MAX) and **latch** `_one_pedal_pause_latched` until a stalk SET. The rest bit (`_one_pedal_had_long_at_rest` / controller `_saw_long_without_gas`) is sticky — a soft or late `gasPressed` still latches; a missed rising edge must not leave long armed. Lift / coast / regen must **not** restore long or re-ACQUIRE (stock `gasPressedOverride` ending makes `CC.longActive` true again — the latch blocks A+B / A3 and re-drops long if it comes back without SET). Do **not** `USER_DISABLE` / `hard_cancel_session` / take-control. **Engage while gas is already pressed** (one SET or two SET) does **not** pause or latch — long stays armed; lift still ACQUIREs with A+B grace expire + aEgo / A3 climb. Same-frame SET + first gas sample is engage-with-gas, not a takeover. **Lift-through DI 1–2:** stock `gasPressed` falls (DI ≤ 2) while interceptor DI is still **> 1**. That is still the engage-while-gas lift, not a from-rest tip-in — do not extra-kick a phantom rising edge (that dropped `enableLongControl`, zeroed MAX, and left Tesla regen owning the car). Orig kick passes `interceptor_di` so pause-gas stays true across 2→1; overlay `maybe_one_pedal_overlay_kick` skips `_one_pedal_gas_falling_edge`. After a takeover pause, interceptor **RELEASEs** and stays RELEASED on lift — Tesla physical pedal / stock lift-regen is the one-pedal path (REGEN_MAX envelope, ~−1.5 m/s²). **One SET** (rolling) clears the pause latch and restores long at held MAX — including SET with the foot still on gas (arms lift-to-start A+B / A3; controller `_saw_long_without_gas` must not re-latch). At a stop, that SET arms wait-for-gas like brake pause (clears the One-Pedal latch so a later gas touch can complete). Brake pause does **not** use this latch (brake resume stays as today). Standstill wait-for-gas resume and a SET that just restored long are not paused. Brake cancel is firm/stock RELEASE (not the #157 soft glide). FCW/AEB unchanged. +7. Stalk cancel (real, not spoof echo) → full disengage. `AudibleAlert.disengage` / `EventName.pedalCruiseDisabled` fire on that session teardown, including when openpilot is already going disabled. Door / **Reverse (or any gear out of Drive)** / permanent steer fault / hands-on ≥ 2 (when not blinker-latched) are the same hard cancel: session down, held MAX forgotten, soft-lat reset, `preap_cc_cancel_needed` so stock CC drops. Reverse `USER_DISABLE` is quiet (no take-control-immediately alarm); other hard cancels keep the disengage prompt. Orig `check_can_engage` only zeroed `cruiseEnabled` / long — that left sticky MAX and did not spoof CANCEL. Panda `tesla_preap` uses `pcm_cruise_check(false)` **while not in Drive** so `cruise_engaged_prev` is already clear before Drive return (same cleanup as stalk cancel). Python's CANCEL spoof is TX-only and cannot clear that latch. Drive SET while `!controls_allowed` is last-resort only; in-Drive mismatch checks and engagement are otherwise unchanged. selfdrived holds the 3X/OP `mismatch_counter` at 0 **for the whole R/P period**, not on Drive entry. After returning to Drive, a normal single pull while rolling is a new lat+long engage (not a sticky-MAX resume). No-pedal still double-pulls. **Flash the panda** after this safety change. + +Interface flags for this mode: `openpilotLongitudinalControl=True`, `pcmCruise=False`. Long planner runs; accel goes to pedal. + +**Stock CC vs pedal long:** on the rising edge of `enableLongControl` (and while DI stays **ENABLED** or **STANDBY**), card keeps `preap_cc_cancel_needed` until `di_cruise_state` is neither. One CANCEL from ENABLED typically lands in STANDBY; a second CANCEL takes it OFF. That closes the gap where stock CC stayed armed and could fight the pedal. `PreAPLongController` already one-shots CANCEL on long rising / falling / a stalk press — the persist-until-off path is in `preap_force_offroad_handoff.py`. + +**Force Offroad while software long is on:** on-road, a big **Yes / No** (**Ready to resume steering control?**) comes first. **No** clears the toggle and leaves long as it was. **Yes**, then do **not** drop `started` until stock CC is ENABLED at current speed (CANCEL → STANDBY → drop OP long → SET_ACCEL). See [force-offroad.md](force-offroad.md). The handoff suppresses the engage-kill so it can park DI in STANDBY and SET. + +**Follow Distance + Hypermile (nap-dev):** Settings → NAP → Driving Mannerisms. Behind a radar lead, a stalk **tip** (first detent, 1 mph / 1 kph) undoes that frame’s MAX and steps the matching City or Highway Follow Distance 1–7 (`NAPFollowDistanceCity` / `NAPFollowDistanceHwy`; HUD `NAPFollowDistance`) on return to IDLE — Highway when MAX is 50 mph or higher, City when MAX is under 50 (traveled speed only if MAX is unset); a **full press** (2nd detent, 5 mph / 5 kph) still steps MAX +5/−5 and does not remap Follow, even though the lever passes through first detent. Same whether Hypermile is On or Off. The Driving Mannerisms slider stays visible and updates live. No lead: tip and hold both still adjust MAX. Hypermile (default Off) is eco snap / Step Down / Hill Climb only; it does not own follow levels. Opt-in **Step Down Speed** (default Off) uses the same posted-scale as eco, larger drop (−15 at 80; town 30 stays 30); Follow stalk SET can still hold above that until posted changes. **Hill Climb** (default On, inert unless Hypermile is On) uses IMU pitch to hold Accel 1 on grades and ease over a crest — no maps-elevation lookahead. See [hypermile.md](hypermile.md). Soft-lat / DM / blinker / sticky MAX / one-SET / standstill gas-gate / reverse hard-cancel unchanged. + +## No-pedal mode + +`use_pedal=False`, no pedal hardware: + +1. Driver double-pulls stalk → `cruiseEnabled=True`, `preap_cc_engage_needed=True` +2. `carstate` publishes `ret.cruiseState.enabled=True` +3. selfdrived sees this with `pcmCruise=True` → engages op lateral +4. `carcontroller` sends `RES_ACCEL` stalk spoof via `0x45` → stock Tesla CC engages and holds current speed +5. `CC.longActive=False` always (`openpilotLongitudinalControl=False`) — no planner accel is produced or consumed +6. Stalk cancel → `preap_cc_cancel_needed=True` → carcontroller spoofs `CANCEL` stalk → stock CC drops +7. Driver's own stalk +/- buttons adjust stock CC speed directly (stock CC is on the same CAN bus) + +Interface flags for this mode: `openpilotLongitudinalControl=False`, `pcmCruise=True`. Mirrors the honda/hyundai/volkswagen pattern. + +## Stalk spoofing and echo filters + +NAP both reads the real stalk and sends spoofed stalk messages. This creates an echo risk: our own spoofed message could be read back as a real driver press. Two windows suppress this: + +- `CANCEL_ECHO_WINDOW_MS = 600` — ignore `CANCEL` events within 600 ms of our last non-cancel stalk activity (so auto-cancel echoes from engage spoofs don't look like the driver pressing cancel) +- `SPOOF_ECHO_WINDOW_MS = 300` — ignore `CANCEL` events within 300 ms of our last explicit spoof send + +Both tuned on real drive logs. If you see stale "driver canceled" events in logs, these are the knobs. + +## Double-pull vs single-pull + +`nap_conf.double_pull_enabled` stays on. Pedal mode does not wait for a second pull to take longitudinal. + +**Pedal mode, from fully off:** + +- Rolling, foot off (Tesla DI ≤ 2), brake not held → one pull engages lateral and longitudinal immediately. MAX is take-speed-now. One engage chime. Stock cruise cancel is unchanged. +- A second pull inside `double_pull_window_ms` stays lat+long and applies take-speed-now again (no drop, no flicker). The pull time is stamped on that first engage, including engage-while-gas, so the window is real. +- Stopped, foot off → lateral on, longitudinal armed as wait-for-gas. The pull does not creep. A later DI > 2 tap starts long at the same take-now MAX. Another pull while still stopped does not start rolling. +- Brake held → lateral only (orig still refuses long while the brake is down). +- Foot on the accelerator (DI > 2), rolling → engage-while-gas, unchanged. Lift still acquires, including One-Pedal armed-with-gas grace. Interceptor rest noise is not a press; the gate is the Tesla DI reading. + +**Already engaged or long-paused (pedal):** unchanged. One SET resumes the sticky MAX (at a stop, that SET still waits for gas). A second SET inside the window is take-speed-now. A 2 s hold is gap lock even if long is paused or was not yet taken. + +**No-pedal mode:** double-pull is unchanged. + +- First pull → lateral only, and an immediate stock-CC cancel +- Second pull within `double_pull_window_ms` → lateral plus stock CC engage +- Window expires → stays lateral-only + +Once already engaged in pedal mode, a brake drop of long is not a new first pull: one SET restores long with the held MAX. A latched driver turn does not drop long. + +### Sticky MAX (pedal mode) + +HUD MAX is `CS.vCruise` / `pedal_speed_kph`. Policy lives in `MapCruiseHold` (`selfdrive/mapd/map_speed_policy.py`): + +| Field | Role | +|--------|------| +| `held_max_kph` | MAX to resume after a long pause. Survives brake. Forgotten on hard cancel or double SET. | +| `sticky_set_kph` | Driver hold that Follow must not overwrite while posted is unchanged. | +| `last_posted_kph` | Last *known* OSM posted (+ offset). GPS/match drop does not clear it or invent a posted. | + +- **Maps on / posted known:** MAX rebases **only** when the posted value itself changes (e.g. 65→45 or 65→70), including while long-paused. Driver can hold 55 in a 65. Do not overwrite sticky toward posted every frame. +- **Maps off / posted unknown:** MAX never auto-rebases. Never invent a posted value. GPS glitch → keep held MAX. +- **One SET** (session already up, typical after long pause): resume long only; write `held_max_kph` (already rebased if posted changed). **At a stop** (`vEgo <= 0.3 m/s` / standstill — same floor as controlsd lat): one SET does **not** take long or creep from 0. It still means “I want resume” (held MAX is kept). A **light throttle / gas** touch then resumes at that held MAX. Rolling (not at stop): one-SET resume is unchanged. A second SET inside the window is still forget-sticky / take-speed-now. +- **From fully off, pedal, rolling:** one pull is the old double-pull engage. Forget sticky; maps+posted known → write current posted (+ offset); else write current traveled speed. A quick second pull applies that same MAX again. +- **From fully off, pedal, stopped:** the pull does not seed a creep. The gas tap that starts long uses that same take-speed-now MAX. +- **Double SET while already engaged:** forget sticky; maps+posted known → write current posted; else write current traveled speed. + +No-pedal / stock CC does not own software MAX. Brake does not pause NAP long (stock CC handles brake). Double-pull still engages lat; set speed stays with Tesla CC. + +### Follow Distance stalk (radar lead) + +When `radarState.leadOne` is present, a Pre-AP stalk **tip** (first detent, 1 mph / 1 kph) undoes that frame’s MAX and steps City or Highway Follow Distance **1–7** (`NAPFollowDistanceCity` / `NAPFollowDistanceHwy`, HUD still `NAPFollowDistance`) when the lever returns to IDLE — the same controls as Settings → NAP → Driving Mannerisms. The tip writes **Highway** when MAX is 50 mph or higher (still accelerating up to a highway set speed, and exactly 50). It writes **City** when MAX is under 50, even if ego is already above 50. Traveled speed is the fallback only when MAX is unset, invalid, or 0. Live follow uses that same MAX cut, so a slowdown under a highway MAX does not switch to city follow. With no MAX, traveled speed still uses a little hysteresis around 50 so 49–51 mph does not flap. The gap itself still eases between the two setpoints instead of stepping. Stalk up = closer (toward 1). Stalk down = farther (toward 7). Closest (1) is allowed. A **full press** (2nd detent, 5 mph / 5 kph) keeps MAX +5/−5 and does not remap Follow Distance, even though a physical full press walks through first detent. Raw `SpdCtrlLvr_Stat` / CruiseButtons distinguish tip vs hold; `buttonEvents` alone do not. HUD shows **Follow Distance: N** (`EventName.followDistanceChanged`, WARNING + PERMANENT, held ~1.5 s). A tip already at 1 or 7 still requests the HUD (`NAPFollowHudPending`). No lead: tip and hold both stay MAX / RES+/−. This is not Hypermile (no 1–5, no ≤50 forced far gap — city/hwy are independent Mannerisms setpoints with a fluid blend). Helper: `selfdrive/controls/lib/hypermile.py` + `follow_distance.py`; remap lives in `card.py` (`_maybe_follow_stalk`). + +### Gap lock + +Default **Off** (`NAPGapLock`, Settings → NAP → Driving Mannerisms, and the companion Dash). Pedal longitudinal. Pull the engage stalk toward you (`SpdCtrlLvr_Stat` = MAIN) and hold it for **2.0 s**. That latches the current radar `leadOne.dRel` (0.4 s median, only inside 8–80 m) and that track id, whether long is already on, paused (pedal, One-Pedal, brake, or standstill wait-for-gas), or not yet taken. A finished hold resumes long so those meters are the unified setpoint (`slack = dRel − locked meters`). From the start of the hold the same law tracks the running median, so it does not keep easing out to the time gap and then have to catch back. Follow Distance 1–7 stays the time gap for intrusion, MPC, and FCW. A stalk tip, cancel, brake, or One-Pedal pause clears a lock that is already on. Lead loss past the usual ~0.5 s flicker, a new radar track, or a vision-only lead clears it too. Another 2 s hold stores a new distance. The C3X keeps a **LOCK** chip under MAX for the whole latch. The **Gap lock engaged** banner shows for about 2 seconds when the lock first engages, then goes away; the chip stays until the lock clears. A lead-loss clear also shows **Gap lock off** briefly. A stalk, brake, or pause clear does not. No panda flash: an in-session CANCEL spoof after 0.5 s of the hold keeps stock cruise asleep and does not drop lateral. + +## Steering disengage + +`handle_steering_disengage()` runs on every frame. Rising edge of `steeringDisengage` (hands-on level ≥ 2 or EPAS rejecting) fully tears down FSM state: `cruiseEnabled=False`, `enableLongControl=False`, `pedal_speed_kph=0`, pull timers cleared. + +On Pre-AP that falling `cruiseState.enabled` is `EventName.pcmDisable`. The 3X HUD string is **"Steering Disengaged"** (`pcm_disable_alert`) — not `EventName.steerDisengage`, which is sound-only. Do not hide `pcmDisable` after cruise is already down; keep `cruiseEnabled` during a blinker-held / lat-paused turn so the alert never fires. Hard-gate teardown on one lamp, physical LEFT/RIGHT, or the flash-latch hold. Door / Reverse / stalk cancel / permanent steer fault still fully disengage (`hard_cancel_session` from `check_can_engage`). Reverse is that session end — not a pause that stays half-engaged — but the Reverse `USER_DISABLE` is **quiet** (no “TAKE CONTROL IMMEDIATELY” / `warningImmediate`). A silent PERMANENT “Reverse Gear” overlay is OK; lat/long stay off until Drive + a new engage. + +This is the primary user override path when the driver is *not* in a blinker turn. The panda also enforces it independently via EPAS error codes 6–9 and hands-on level ≥ 2 — except during a blinker-latched driver turn, where those conditions must not drop `controls_allowed` (otherwise selfdrived fires `controlsMismatch` after 2s and fully cancels while the lamps are still flashing). + +During a **tipped** lane change (not a latched stalk), a same-direction nudge — including hands-on level 2 through the ~1 s lamp flash-dark gap — is the lane-change confirm and must not disengage. An emergency yank still takes over immediately: EPAS hands-on level 3, torsion above `2 * STEER_THRESHOLD` (2.0 Nm), or torsion reaching `3 *` the 0.55 Nm soft-lat floor within 150 ms. Panda allows that level-3 disengage during the flash gap. **Reflash the panda** so the flash-gap tolerance matches Python; otherwise a firm confirm in the dark half of the blink drops `controls_allowed`. + +Panda firmware must be flashed after this safety change. Software update / on-device `scons` rebuilds the panda image from `opendbc_repo/opendbc/safety/modes/tesla_preap.h` (latch in `tesla_preap_blinker.h`); reboot so `pandad` sees the new signature and flashes. Python `BlinkerLateralHold` alone cannot keep `controls_allowed`. + +## Driver-wheel temporary lateral handoff + +**Default On.** Settings → NAP → Driving Mannerisms → Soft Lateral Handoff can be turned **Off**. Yield is a **light purposeful push** with a hand on the rim that **frees the EPS** (generally avoiding something), not gravel spike trains / wind / road-crown false pressure. + +#79 still felt like wrestling for two reasons: (1) OP kept **full lateral authority until the 0.70 Nm / 140 ms debounce completed**, and (2) after “yield” it kept `latActive=True` and commanded **measured angle** (`apply_lat_authority(0)` / `DAS_steeringControlType=1`). That is closed-loop follow-the-rim — the driver could nudge off-path but OP was still holding/steering. Yield now reuses the **blinker lat-pause EPS release** (`latActive` false → `DAS_steeringControlType=0`). Hands stay detected via `EPAS_handsOnLevel`. Resume is still pin-to-wheel + **1 s blend**; hands still on stay yielded (do not blend onto the model). A driver-turn blinker does **not** itself free the EPS when Soft Lateral Handoff is On. + +Pothole / obstacle dodges — including fighting OP to leave the path — without a full disengage, unless the driver then emergency-brakes (full cancel). Software-only; panda hands-on ≥ 2 and `STEER_THRESHOLD` are unchanged. + +### Signals (Pre-AP) + +| Signal | Source | Type | Role | +|--------|--------|------|------| +| `EPAS_torsionBarTorque` / `CS.steeringTorque` | `EPAS_sysStatus` 0x370 | continuous Nm (0.01, −20.5) | sustained directional torque (not spikes) | +| `StW_AnglHP_Spd` / `CS.steeringRateDeg` | `STW_ANGLHP_STAT` 0x0E | continuous deg/s (0.5, −4096), negated | **not** an entry gate. Weak wind filter only when torsion is below the yield trigger | +| `EPAS_handsOnLevel` | same EPAS msg | discrete 0/1/2/3 | required for intent (≥ 1). ≥ 1 holds yield. ≥ 2 remains hard disengage | +| path / tracking error | `desired_curvature − measured` | 1/m | high error **and** torsion below trigger → disturbance (wind / crown). High torsion is intent even if error is large | +| digital brake Applied | `DI_brakePedal` / `BrakeMessage.driverBrakeStatus` | boolean | light brake = silent long pause. Not `CS.brakePressed` (forced false) | +| `CS.aEgo` | speed KF | m/s² | emergency decel qualifier (no analog pressure on parsed buses) | + +`steeringPressed` is still `|torsion| > STEER_THRESHOLD` (**1.0 Nm**) with **5-frame** debounce (~50 ms). That fires `EventName.steerOverride` (`OVERRIDE_LATERAL`, stays enabled) and is the current software override effort. + +### Intent to enter yield + +All of the following, consecutive frames (gaps reset — gravel spike trains do not accumulate): + +1. `|torsion| >= 0.55 Nm` (55% of `STEER_THRESHOLD`; a light purposeful push, still below `steeringPressed` 1.0 Nm) +2. `handsOnLevel >= 1` (hand on the rim) — required so rumble / wind with hands off or resting does not free-yield +3. Held for **90 ms** at the 0.55 Nm floor. Fewer frames as torsion approaches `STEER_THRESHOLD` (down to **60 ms** at 1.0 Nm) so the soft path beats hands-on ≥ 2. Never below 60 ms (5-frame gravel bursts stay rejected). + +Do **not** require high steer rate. An isometric fight (firm torsion, wheel barely moving, high tracking error) **must** yield. Rate may stay as a weak wind filter only when torsion is **below** 0.55 Nm — it never blocks a firm push and never promotes low torsion to intent. + +Disturbance veto only when torsion is **below** the yield trigger: `|desired − measured| curvature >= 0.0025` **and** `|torsion| < 0.55 Nm` is wind / crown — do not yield. High torsion is intent even if tracking error is large (driver is leaving the path). + +Release hysteresis stays **0.40 Nm** (press-latch only). Do **not** go back to raw 0.5 Nm / 80 ms *torsion-only* (no hands gate) — that was #71 rumble. ≥ 2 stays the hard/safety path. + +### Behavior (lat yield) + +**Yield = free wheel, not follow-angle.** Same EPS release as blinker lat-pause. + +1. OP engaged and providing lateral. Intent detected → `carControl.latActive` goes **false**. Pre-AP carcontroller sends `DAS_steeringControlType=0` and `apply_steer_angle_limits_vm` snaps `apply_angle` to measured (stock inactive). The driver steers the car; OP is not angle-controlling to the rim. `desired_curvature` is **pinned to measured** so resume starts from the wheel. Longitudinal and `cruiseEnabled` stay up. Stalk cancel / doors / hands-on ≥ 2 still hard-disengage. An occasional light torsion probe is OK to confirm he is still there — hold is `EPAS_handsOnLevel`, not continuous angle-hold. +2. Stay yielded (EPS free) while still maneuvering: **`EPAS_handsOnLevel >= 1`** **or** a renewed **≥ 0.55 Nm** push. Mid-dodge torsion dips must **not** start the hand-back. Rate is not a hold signal (caster / road after release). +3. After hands go to **0** for **~0.15 s**, lat comes back and a **1.0 s** smoothstep (`t²(3−2t)`) blends authority 0 → 1. `QUIET_WAIT_S` stays 0 (no torsion-quiet — that blended on mid-dodge dips). The pin lifts when blend starts. `apply_lat_authority` is skipped at authority=1 and while lat is down. +4. Renewed **hands-on** or a firm push ≥ 0.55 Nm during that wait or the blend immediately re-yields (EPS free again) and resets the delay. Hands off ~0.15 s and the 1 s blend retries. +5. Hand-back is the S-curve from the wheel, not a grab onto the model. There is **no** dedicated blinker rising-edge 1 s blend. +6. HUD: `controlsState.latHandoffPaused` stays set until authority ≥ **0.70**. Gray **override**, no sounds. Green + on-screen path is not enough — the wheel must unwind onto that path. + +**Driver-turn blinker + soft-lat (On):** lamp latch / held stalk must **not** clear `latActive` or force EPS free. If soft-lat (or stock lat) still has control when the blinker rises, **keep control**. Soft-lat may still yield if the driver pushes (intent / hands) — that is the driver taking control, not the blinker stripping it. While the driver-turn blinker is latched, do **not** re-enable: if already yielded or blending, stay yielded / do not finish a take-back blend. After the blinker clears, do **not** special-case blend; if we were yielded / blending / lat-down, **land in soft yield** and let the normal resume own it (hands on / firm push stay free; hands 0 for `HANDS_OFF_CONFIRM_S` ~0.15 s, then the 1 s smoothstep). **v_ego strictly below 10 mph** (`LAT_REENABLE_MIN_V_EGO_MPH`) uses that **same** re-enable inhibit (OR, not a parallel path): keep control if we still have it; already yielded / blending stay yielded; after speed crosses 10 mph, land in yield then the normal resume. Blinker-on still blocks take-back at any speed. Above 10 mph with the blinker off, prior resume is unchanged. ALC tip / keep-alive flashes are **not** a driver turn. **Soft-lat Off** keeps today’s blinker lat-pause so a held turn still frees the wheel (speed does not pause lat on that path). A latched driver turn does **not** pause long. Brake sticky-MAX silent pause + one SET / double SET and panda blinker latch are unchanged. Hazards still do not pause. + +### Emergency / hard brake → full OP disable + +Pre-AP has **no analog brake pressure** on the buses we parse (`test_preap_brake_signals.py`: `BrakeMessage` is a 2-bit Applied enum; no `IBST_` / iBooster travel). Light brake is that digital bit and **must** keep the existing sticky-MAX silent long pause + one SET. Do not turn every brake into a full cancel. + +**Emergency definition** (testable, in `driver_lateral_handoff.py`): + +| Check | Value | Why | +|--------|--------|-----| +| Digital Applied | `DI_brakePedal==1` **or** `driverBrakeStatus==APPLIED`, published on `CS.brake` (not `brakePressed`) | Driver is on the pedal. OP map-track / planner decel does not set this. | +| Measured decel | `aEgo <= −3.5 m/s²` for **80 ms** (8 frames) | ~0.36 g. Comfort Accel-5 is **−0.80 m/s²**; pre-AP planner clip is **−1.5 m/s²**. A lone pothole spike is shorter than 80 ms. | +| Speed | `vEgo >= 1.0 m/s` | Reject standstill KF chatter. | +| Timing | currently yielded **or** blending **or** within **2.0 s** of yield entry | Same timeframe as the soft-lat takeover. | + +When that fires, card calls `hard_cancel_session()`: `cruiseEnabled=False`, long down, held MAX forgotten, `preap_cc_cancel_needed`. That is the normal hard-cancel path: `EventName.pcmDisable` / “Steering Disengaged” + disengage chime, and `pedalCruiseDisabled` if long was on (session down, not a silent pause). controlsd also sets `CC.cruiseControl.cancel`. Light brake while yielded or not **does not** set this flag. + +### Where to look + +- `selfdrive/controls/lib/driver_lateral_handoff.py` — firm-push detector (torsion + hands; rate not an entry gate), `lat_active_after_handoff` (yield = free EPS), low-torsion disturbance veto, emergency definition, hands-on hold, smoothstep, curvature pin, `lat_reenable_inhibited` (blinker OR v_ego < 10 mph) +- `selfdrive/controls/controlsd.py` — drop `CC.latActive` while yielded; pin `desired_curvature` while lat down; pass torsion / rate / hands / tracking error / digital brake / aEgo; cancel on emergency +- `opendbc_repo/opendbc/car/tesla/carcontroller.py` — `DAS_steeringControlType` from `CC.latActive` (0 = EPS free, same as blinker pause) +- `selfdrive/car/tesla/preap_blinker_lat_pause.py` — publish hands-on + digital brake; card-local handoff; `hard_cancel_session` +- `selfdrive/ui/ui_state.py` — gray override chrome while paused +- `selfdrive/controls/lib/tests/test_driver_lateral_handoff.py` + +### On-car test plan (Pre-AP Model S / comma 3X) + +Do these at a quiet road / parking lot first, then a known pothole stretch. Pedal or no-pedal both OK. Do **not** expect a panda flash. + +1. **Engage** with one stalk pull while moving, foot off the pedal. Confirm one engage chime, green engaged chrome, and that long is holding speed (posted + offset if the map has it, otherwise current speed). A quick second pull stays engaged at that same MAX. At a stop, one pull must not roll the car; tap the accelerator, then long starts at that MAX. Brake held: steering only. +2. **Intentional dodge** (hands on, light purposeful push ≥ ~0.55 Nm for ~90 ms — the wheel does **not** have to be moving). Includes fighting OP to leave the path (high tracking error, low rate). The wheel should **just let go** (EPS free, not still holding/steering to the rim) **before** a hard yank / hands-on ≥ 2. Speed control must stay on. HUD should go **gray override**, not “Steering Disengaged”, and must not play the disengage chime. +3. **Hold** through a pothole dodge (hands still on the rim). Authority must stay yielded even if torsion dips. +4. **Release.** Hands clearly off the rim. After ~0.15 s the wheel eases back onto the path over about **one second**. A brief hands-off or right-then-left crossover during the dodge must **not** snatch. When green returns, the wheel must follow the on-screen path. +5. **Re-grab during the wait or blend.** Hands back on or a firm push: yield again (delay resets). Hands off ~0.15 s and the 1 s blend retries. +6. **Road rumble / crosswind / crown** with hands resting: must **not** gray. Wind that makes NAP fight the path (high tracking error, low torsion) must **not** yield. If it still does, turn Soft Lateral Handoff **Off**. Do not lower panda / `STEER_THRESHOLD`. +7. **Light brake** (tap, not a panic stop) while engaged, yielded or not: silent long pause + held MAX; one SET resumes **if already moving**. At a stop, one SET must **not** roll the car; tap the accelerator, then long resumes at held MAX. No disengage chime. Sticky MAX (#72+#77) unchanged. Brake that knocks long off must **RELEASE interceptor immediately** to stock Tesla regen (firm, not a 0.75 s ramp or coast-then-bite). FCW / AEB / hard lead braking must still bite. +8. **Hard brake during / just after a soft-lat dodge** (firm pedal, strong decel): full OP cancel, “Steering Disengaged”, disengage chime. Not a silent pause. One SET is a new engage, not resume-at-held-MAX. +9. **Blinker turn** (held stalk), Soft-lat **On**: blinker-on alone must **not** free the wheel. A push may still yield. Soft-lat must not take lat back while the driver-turn lamps are latched. After the blinker clears, if lat was yielded, ease back through yield + ~0.15 s hands-off + **1 s** blend (not an immediate blinker blend). Soft-lat **Off**: existing lamp-latch lat pause (free wheel). Long stays engaged through the turn on both settings. Tip ALC must not latch a driver turn. +10. **Below 10 mph**, Soft-lat **On**: same no-lat-re-engage as blinker-on. If lat is still on, keep it. If already yielded / blending / lat-down, stay free until **above 10 mph**, then the normal 0.15 s hands-off + 1 s blend. Blinker-on still blocks take-back at any speed. Long / follow unchanged. Tip ALC / held-turn classification unchanged. +11. **ALC tip** still arms a lane change; wheel nudge at 1 Nm still starts it. +12. **Hard yank / hands-on 2**, stalk cancel, door: full disengage, unchanged. +13. **Reverse while engaged:** session ends (not a pause). No take-control-immediately alarm — OP just goes off. After Drive a normal single pull (rolling, foot off) must engage lat+long without Controls Mismatch and without resuming the old MAX. Soft-lat / blinker / sticky MAX must not stay wedged. No-pedal still needs the double pull. +14. **Gas-lift open-road climb (A3):** below MAX, no lead: engage-on-gas then lift (or tap gas while long is on). Takeover should climb toward MAX at Mannerisms **Acceleration** 1–10 — Accel 1 lazy, Accel 10 quicker — not sit at post-lift aEgo / coast. Must not punch past HUD MAX. **Lead / FCW:** must still slow; no climb through a car ahead. **Engage-on-gas then lift** still works with **One-Pedal Long On**. **Tap gas while long is already on** is One-Pedal **Off** (On would pause long). +15. **One-Pedal Long On:** Mannerisms toggle Off by default. Turn On. Foot off, long holding speed: press gas from rest — long should **pause** silently (lat stays, no disengage chime, session still up). Drive on the pedal; **lift must stay paused** (Tesla stock regen via interceptor RELEASE, not OP climbing back to MAX). Press gas again: accel, still no OP long, still not a full disable. **One SET** resumes at held MAX. **Foot already on the accelerator, then one SET:** long must arm; lift must start long (A+B / A3) — must not pause. A second pull inside the window stays armed. Toggle Off: gas tap then lift should resume long and climb (A3). Brake still pauses long and still resumes as today (this latch is gas-pause only). At a stop, one SET then gas still resumes (does not pause). + +## Driver monitoring simulate looking + +Stock DM stays on while engaged. Vision timeouts stay **3 / 5 / 11 s** (`DRIVER_MONITOR_SETTINGS` in `selfdrive/monitoring/policy.py`). The #103 hands-on-only first-band reset did not stop look-at-road nagging: light rim contact is not what `dmonitoringd` treats as looking, orange/red still fired, and `maybe_distracted` (no face / uncertain) kept draining. + +Triple-tap **NAP** (1.0 s window → side popup; not under Driving Mannerisms) order: **Force Offroad**, **Simulate Look**, **False Alert Ignore**. On nap-dev, Simulate Look defaults **On** and False Alert Ignore defaults **Off**. They are **mutually exclusive** — turning one On clears the other (and aborts the other in-flight path). Both Off is allowed. A stale both-On from older installs resolves to Simulate Look On / FAI Off on first read. Shared cadence: after awareness has gone **past 1.0 s**, fire uniform in **(1.0 s, 3.0 s]** of that countdown and **hold** (minimum 0.5 s, until awareness is 1.0). Not a mute and not `driver_interacting` full reset. + +`NAPDmSimulateLooking` restores the pre-FAI **full looking-path wipe** on that cadence: face + low std + `driver_distracted` / filter + pose / eye / phone type bits. That recovers no-face, uncertain, phone, pose, and eye false nags the way Simulate Look did before the False Alert Ignore split. It is not a mute of hard cancels. + +`NAPDmFalseAlertIgnore` (only when Simulate Look is Off) owns the **phone-only** path: when `phoneProb` is above `_PHONE_THRESH` (0.5) and pose/eye are **not** alarming, it soft-clears only `distracted_types['phone']` so a false device “Driver Distracted” can recover without a real glance. If pose or eye are actively alarming, it does **not** start or keep a hold — those timers keep draining. Phone + pose together: pose still drains; once pose/eye are clear, remaining phone can soft-clear on the same cadence. + +Below **2 mph** (`DM_LOOKAWAY_GATE_MPH`; strictly below, ~0.89 m/s) looking-away / distraction / eyes-off-road alerts do **not** fire, whether Simulate Look / FAI are On or Off. This reuses the stock standstill exemption (pause before the green prompt; recover if already orange) and ORs in ego speed, because Pre-AP `CS.standstill` is only true when fully stopped — creeping at a light still nagged. Toggles stay as set. Above 2 mph, Sim Look / FAI / stock 3 / 5 / 11 s are unchanged. FCW / AEB / hard cancels are not this path. + +Always-on DM when not engaged does **not** simulate or ignore. Either toggle **Off** = that path is stock. Mutex: only one On. Hands-on ≥ 2 / steer disengage, door, reverse, and stalk cancel are unchanged. + +## Where to look + +- `opendbc_repo/opendbc/car/tesla/preap/engagement.py` — stalk FSM +- `opendbc_repo/opendbc/car/tesla/preap/carstate.py` — interceptor `gasPressed` then One-Pedal Long pause +- `selfdrive/car/tesla/preap_blinker_lat_pause.py` — blinker lat pause / soft-lat gate (does not drop long on driver turn) +- `opendbc_repo/opendbc/car/tesla/preap/carstate.py:120+` — button event pump + cruise state publish +- `opendbc_repo/opendbc/car/tesla/preap/carcontroller.py` — pedal TX, engage grace, gas-lift VDAS seed +- `selfdrive/controls/tests/test_tesla_preap_gas_lift_handoff.py` — gas-lift grace expire + Accel 1–10 climb seed +- `selfdrive/controls/tests/test_tesla_preap_one_pedal_long.py` — One-Pedal Long pause latch + RELEASE regen (gas→lift keeps enableLongControl/longActive off until SET; kick-miss still latches; engage-while-gas still ACQUIREs, including lift-through DI 1–2 / dc 13:16:14; no USER_DISABLE) +- `selfdrive/controls/tests/test_tesla_preap_brake_cancel_regen.py` — brake cancel is firm RELEASE / stock regen +- `selfdrive/car/tesla/preap_force_offroad_handoff.py` — Force Offroad cancel→STANDBY→drop long→SET; kill stock CC on OP long engage +- `opendbc_repo/opendbc/car/tesla/preap/tests/test_preap_engagement.py` — FSM tests (brake drop, steering disengage, double-pull) +- `selfdrive/car/tesla/tests/test_preap_force_offroad_handoff.py` — handoff ordering + kill-on-long +- `selfdrive/car/tesla/tests/test_preap_blinker_lat_pause.py` — blinker lat pause, latched turn keeps long, brake still drops long +- `selfdrive/car/tesla/tests/test_preap_sticky_max.py` — sticky MAX across brake pause, one vs double SET, cancel +- `selfdrive/monitoring/dm_toggles.py` — mutually exclusive write/read helpers (Simulate Look wins stale both-On) +- `selfdrive/monitoring/policy.py` — Simulate Look (`NAPDmSimulateLooking`) full looking-path wipe; False Alert Ignore (`NAPDmFalseAlertIgnore`) phone-only soft-clear; `DM_LOOKAWAY_GATE_MPH` (2 mph) look-away pause +- `selfdrive/monitoring/test_monitoring.py` — Simulate Look full-wipe recover; FAI phone-only vs pose/eye; Off is stock; mutual exclusion; look-away pause below 2 mph diff --git a/docs-nap/force-offroad.md b/docs-nap/force-offroad.md new file mode 100644 index 00000000000000..6e974033037463 --- /dev/null +++ b/docs-nap/force-offroad.md @@ -0,0 +1,112 @@ +# Force Offroad (Go Offline) + +Hidden Settings → NAP toggle (triple-tap the **NAP** sidebar / **nap** button) so the comma can enter the same **started=false / offroad** path used for map download, Refresh maps, software install, and other offroad-only NAP actions **while the car is still moving**. Not on the normal NAP list. + +## Why + +Those actions gate on `ui_state.is_offroad()` (`not started`). Stock openpilot only goes offroad when ignition is off (or thermal / onroad-cycle). Parking for every pull around Benson is the pain this avoids. + +## Param + +| | | +|---|---| +| Name | `NAPForceOffroad` | +| Default | Off (`0`) | +| Flags | `CLEAR_ON_MANAGER_START \| CLEAR_ON_IGNITION_ON` (not persistent) | + +On-road confirm (UI → params), then handshake (card → hardwared): + +| | | +|---|---| +| Name | `NAPForceOffroadHandoffReady` | +| Default | Off (`0`) | +| Flags | `CLEAR_ON_MANAGER_START \| CLEAR_ON_IGNITION_ON` (not persistent) | + +| | | +|---|---| +| Name | `NAPForceOffroadConfirmed` | +| Default | Off (`0`) | +| Flags | `CLEAR_ON_MANAGER_START \| CLEAR_ON_IGNITION_ON` (not persistent) | + +Do **not** flag either param `CLEAR_ON_OFFROAD_TRANSITION` — going offroad is what the toggle does, so that flag would immediately undo it. + +## How it hooks + +`hardwared` reads `NAPForceOffroad` every loop into `onroad_conditions["not_force_offroad"]`. When the toggle is on **and** the device is not already onroad, `should_start` is false → `deviceState.started = false` (today's parked path). No confirm popup when already offroad / parked. + +If the device is **already onroad**: + +1. A full-screen **Yes / No** modal (not a Settings row): **“Ready to resume steering control?”** Large type and large buttons so it is hard to miss while driving. Same `gui_app.push_widget` stack as other 3X ConfirmDialogs (`selfdrive/ui/onroad/force_offroad_confirm.py`). +2. **No** (or Escape) cancels the whole Force Offroad process: clears the toggle, confirm, and handoff-ready flags. NAP/OP stay as they were. No cancel/SET, no `started=false`. +3. **Yes** sets `NAPForceOffroadConfirmed`. Only then card may start the stock-CC handoff. +4. hardwared then holds `started` until card writes `NAPForceOffroadHandoffReady` (or **3.0 s** fallback, which does **not** run until Yes) so the onroad carcontroller can still spoof stalk CANCEL / SET. Then `started=false`. + +Then the existing chain runs: + +1. **manager** sees `deviceState.started` false → stops the onroad stack (`controlsd` / `selfdrived` / …) and writes `IsOffroad=true` / `IsOnroad=false`. +2. **ui_state** `started = deviceState.started and ignition` → `is_offroad()` true → Download US Maps, Refresh maps, software install, pedal/EPAS scripts unlock. + +There is no UI-only override. A cosmetic button would leave openpilot able to engage. + +## Pre-AP stock-CC handoff (pedal / software long) + +Gate: `enableLongControl` (NAP is commanding software long). Not the interceptor handshake / `pedalLongActive`. Lat-only, stock-CC mode, or not engaged: skip the handoff and write ready immediately. + +CANCEL / SET live in `StockCCSpoofer` (onroad). **Do not** flip `started=false` until stock CC is **ENABLED** (prefer) or the timeout. + +Sequence when Force Offroad turns ON while software long is active (**after Yes**): + +1. Drive DI toward **STANDBY**. `DI_cruiseState` from `DI_state`: + - **ENABLED** / STANDSTILL / OVERRIDE / PRE_CANCEL → spoof **CANCEL** (existing `preap_cc_cancel_needed`). Tesla typically drops ENABLED → STANDBY. Keep OP long on during this so something still holds speed. + - **STANDBY** → already ready to SET. + - **OFF** (SET_ACCEL is ignored on an unarmed DI) → spoof **MAIN** (RWD pull) to arm. If MAIN SETs in one step, skip the extra SET. +2. Once **STANDBY** (or DI already ENABLED from MAIN): **drop `enableLongControl`** (silent; `cruiseEnabled` stays so lat does not dump before offroad). Pedal long falling would otherwise set `preap_cc_cancel_needed` and abort ENGAGING — that cancel is suppressed for this handoff. +3. **Immediately** `preap_cc_engage_needed` → SET_ACCEL at current ego (existing ENGAGING FSM, retries on the 10 Hz slot, 500 ms timeout). +4. When DI is **ENABLED** (or STANDSTILL), write `NAPForceOffroadHandoffReady`. Only then hardwared sets `started=false`. + +Timing (100 Hz card / carcontroller): + +| Step | Budget | +|------|--------| +| CANCEL_DELAY_FRAMES | 10 (100 ms) + `frame % 10` slot | +| STANDBY / ARM wait | 0.80 s then fallback | +| ENGAGING retries | `CC_ENGAGE_TIMEOUT_FRAMES` = 50 (500 ms) | +| ENABLED wait | 0.80 s then fallback | +| card overall | 2.5 s then write ready anyway | +| hardwared fallback | 3.0 s if card never writes ready | + +Prefer waiting for ENABLED. The timeouts are so maps still unlock if DI never takes SET (below min cruise speed, unarmed, CAN miss). + +## Clear policy + +Default **Off**. Safer to auto-clear than to stay forced-offroad on the next drive. + +| How | Result | +|---|---| +| Toggle Off | Goes onroad again if ignition is on and other start conditions pass | +| Reset to Defaults | Writes `NAPForceOffroad=false` (3X NAP panel) | +| Reboot / manager start | Param cleared | +| Next ignition ON | Param cleared (park, then start → assist is back) | + +## How to use (on the road) + +1. Settings → triple-tap **NAP** (3 taps within 1.0 s, sliding window) → **Force Offroad** on the side popup (3X) or the nap-button overlay (mici / comma 4). Tap outside the card to dismiss. Leave it available while onroad — that is the point. Not on the normal NAP list or Driving Mannerisms. +2. On-road: a big popup asks **Ready to resume steering control?** **Yes** continues; **No** turns Force Offroad back off and leaves assist as it was. +3. If pedal long was holding speed **and you tapped Yes**: stock CC should take over at about the current speed, then the onroad stack stops. **Drive manually** after that. Do not expect steering or accel assist. +4. Settings → NAP → Map Speed Limit → **Download US Maps** / **Refresh maps** (or Software install) should be tappable, same as when parked. +5. Toggle Off when done, or park and cycle ignition. + +## Retest (Justin — Pre-AP Model S + comma 3X) + +Hold a steady speed on **pedal long**, then triple-tap NAP → Force Offroad **ON**: + +1. Big popup: **Ready to resume steering control?** **No** must leave pedal long / OP as they were (toggle goes back Off, no regen dump). +2. **Yes**, then stock CC should go **ENABLED** at about the current speed (no intentional “nothing holding speed” window / hard regen bite). +3. Then maps / Refresh / install unlock (comma is offroad). +4. If already lat-only or stock-CC mode: Yes still required on-road; then offroad immediately (no CC handoff). Parked / already offroad: no popup. + +Also: engage OP **long** with stock CC already **ENABLED** or **STANDBY** — stock CC must cancel off so it does not fight the pedal. See [engagement.md](engagement.md). + +## Warning + +Forces offroad and disengages openpilot. Drive manually. Do not expect assist while this is on. diff --git a/docs-nap/hypermile.md b/docs-nap/hypermile.md new file mode 100644 index 00000000000000..b055cfd144dcf6 --- /dev/null +++ b/docs-nap/hypermile.md @@ -0,0 +1,134 @@ +# Hypermile (phase 1+2) + +Experimental on **nap-dev only**. Default **Off**. Not a nap-release change. + +Settings → NAP → Driving Mannerisms → **Hypermile**. + +This is a small controller (`selfdrive/controls/lib/hypermile.py`) that snaps eco knobs. It does not rewrite longcontrol, disable lead braking, or raise MAX above posted Cap/Follow / sticky MAX. Stock Follow Distance 1–7 (`NAPFollowDistance`) is shared with Driving Mannerisms — Hypermile does **not** own follow levels. + +## A — Eco preset (comfort-biased, not max regen) + +The goal is **early, light regenerative ease** — not the biggest regen bite. Late hard regen that pitches the car and makes the driver sick is the wrong trade. Safety / MPC hard braking is unchanged. + +Turning **On** remembers the current values, then snaps: + +| Knob | Eco value | +|------|-----------| +| Adaptive Accel Limits | On (softer peak accel when close to a lead) | +| Map Speed mode | Follow (3), or keep Cap if already Cap. Off/Display → Follow | +| Map Speed Offset | **not snapped**. Live eco offset is posted-scaled from the OSM limit (see below). Off restores the user's saved slider. | +| Lookahead | **Early** (3) — starts farther out at 0.55 m/s². Always snapped (Late/Normal/Off become Early). Late is 1.20 m/s² and is *not* kept. | +| Acceleration (Driving Mannerisms; map climb + lead-close) | **1** — laziest Follow climb and lead-close +a (0.20 m/s² catch-up) | + +Turning **Off** restores that snapshot. Soft Lateral Handoff, Simulate Look / False Alert Ignore (triple-tap NAP popup), blinker / sticky MAX / one-SET / standstill gas-gate / reverse hard-cancel, and the stock 1–7 Follow Distance param are **not** changed (eco does not snap or restore follow). + +**Posted-scaled eco offset** (Hypermile On, Step Down Off), from the raw posted/OSM limit in mph — not a forever `NAPMapSpeedOffsetMph = −5`: + +| Posted | Eco offset | MAX target | +|--------|------------|------------| +| < 50 mph (town 30) | **0** | 30 stays 30 | +| 50 mph | **0** (scale starts) | 50 | +| 50–80 mph | linear 0 → −8 | 65 → 61 | +| 80 mph | **−8** | 72 | +| > 80 mph | **−8** (cap) | 90 → 82 | + +**Curves:** eco is the live posted-scaled Cap/Follow target. If MAX was 60 before a sharp bend (sticky hold or that displayed set), curve slowing may move HUD MAX through the corner, then **restore 60** — not leave the eco target. The bend must not permanently rebase sticky / map target. See [map-speed.md](map-speed.md#safety-invariants). + +Params: `NAPHypermile` (bool, default 0), `NAPHypermileSaved` (JSON snapshot). + +## Hill Climb (grade-aware Accel 1) + +Third toggle under Hypermile: **Hill Climb** (`NAPHypermileHillClimb`, default **On**). Hidden/inert unless Hypermile is On. Same visibility pattern as Step Down Speed. + +**v1 signal is IMU pitch** (`carControl.orientationNED[1]`, the same value `get_coast_accel` already reads). **Maps-elevation lookahead is NOT included** — that is a later phase. + +Hypermile snaps Driving Mannerisms **Acceleration** (`NAPMapSpeedAccel`) to **1**. Flat-road `map_track_accel` is then a fixed comfort `a` (Early + Accel 1 → 0.30 m/s²). Grade gravity is not in that number, so a real climb droops under HUD MAX. Stock `get_coast_accel` only lowers +a when `allow_throttle` is false; Pre-AP always allows throttle, so that path does not hold a hill. + +| Pitch (NED) | Clearly under HUD MAX (outside deadband below) | At / above MAX (ego ≥ cruise − deadband) | +|-------------|----------------|---------------| +| ≥ **2.0°** uphill (≈3.5% grade) | Add `g·sin(pitch)` to Accel 1 (extra capped at 0.80 m/s²). Leftover Accel 1 still walks toward MAX. | Leave map hold (**0**). **No** `+g·sin` that fights the deadband zero or punches past MAX. **Does not raise MAX.** | +| Flattening crest (pitch falling through < 2° after a climb) | Leave climb alone (no regen while still climbing). | Early **light** regen **0.15 m/s²** — not Late 1.20. | +| ≤ **−2.0°** downhill | Lower +a by the grade (gravity already pulls toward MAX). **No regen** while still several mph under MAX. | Light regen **0.15–0.25 m/s²**. | +| \|pitch\| < 2° (flat / crown) | Existing Accel 1 / map_track / lead-close unchanged. | Unchanged. | + +Ease is **not** gated on `TRACK_TAPER` (~4.5 mph / 2.0 m/s under MAX). That taper is map-track climb/brake scaling only. Using it as “near MAX” regen’d around 50 mph under a 54 MAX and hunted 47–51 with regen pulses instead of settling. Climb hold is also off in the deadband so grade does not overshoot into Accel-5 comfort brake. + +Cruise `get_max_accel` and the lead-close +a cap still clip after this. Lead-approach and MPC hard brake `min()` after hill climb and still win. Never invents or raises MAX above Cap/Follow / sticky / posted. + +**Why these numbers:** 1° is typical road crown + IMU bias; 2° is a real grade Accel 1 (0.30) cannot hold (`g·sin(2°)≈0.34`). Full `g·sin` matches the Pre-AP VirtualDAS plant (not the shallower 5.65 coast fit). Ease stays well under Early map brake (0.55) so it is comfort, not a dump. + +## Step Down Speed (mileage defer) + +Second toggle under Hypermile: **Step Down Speed** (`NAPHypermileStepDown`, default **Off**). Hidden/inert unless Hypermile is On. + +| Hypermile | Step Down | Map MAX target | +|-----------|-----------|----------------| +| On | Off | Posted + posted-scaled eco (30 stays 30; 80→72; 90→82) | +| On | On | Same 50→80 scale, **−15 at 80** (30 stays 30; 75→62.5; 80→65; 90→75). Replaces eco — does not stack | +| Off | On or Off | Step-down ignored. Normal posted / held MAX | + +Same breakpoints as eco: **0** at/under 50, linear to the 80 value, cap above 80. Hard cap: never more than 15 mph under posted, never above posted. Legal: step-down only lowers. No flat −15 on town limits. + +**Maps-only:** eco and Step Down apply only when maps are present and that road has a known OSM/posted `speedLimit`. Maps off, no match, or posted unknown → **offset 0** — do not invent a drop. Same spirit as sticky MAX (no invented posted without maps). Town 30 with maps stays 30. + +This is an offset on the **posted/map target** Cap/Follow already use (`posted_kph` / `apply_map_speed_kph` offset). Sticky / one-SET / rebase are not rewritten. + +**What wins** + +- **Follow + stalk SET:** driver can hold above the step-down (up to posted). Sticky until the posted *value* changes, then MAX rebases to the new scaled step-down target. +- **Cap:** cannot exceed the stepped posted (80 posted + step-down → cap 65). +- **One-SET** after a long pause: resume held MAX (already rebased if posted or step-down changed). +- **Double SET:** take the current map target (stepped if On). +- Toggling Step Down On/Off mid-drive changes the posted target (scaled eco ↔ scaled step-down), which Follow treats as a posted change and rebases. + +## B — Stock Follow Distance 1–7 (not Hypermile-owned) + +Follow Distance is the stock Driving Mannerisms slider (`NAPFollowDistance`, 1–7, default 4). It stays **visible** while Hypermile is On. There is no Hypermile 1–5 band, no “never stock 1” floor, and no ≤50 mph forced far-gap (stock 7) override. Planner / MPC always use whatever `NAPFollowDistance` says. + +| Stock `NAPFollowDistance` | `T_FOLLOW` | +|---------------------------|------------| +| 1 closest | 0.7 s | +| 2 | 0.9 s | +| 3 | 1.1 s | +| 4 default | 1.3 s | +| 5 | 1.5 s | +| 6 | 1.7 s | +| 7 farthest | 1.9 s | + +Gaps come from the existing `NAP_T_FOLLOW` table. Lead braking / MPC danger zone stay on. Cruise ceiling is still HUD MAX (posted Cap/Follow + sticky). + +### Stalk remapping (Pre-AP pedal software cruise) + +Normally stalk up/down is RES+/RES− and steps MAX / `pedal_speed` 1 or 5 mph. + +With a **radar lead present** (Hypermile On **or** Off): + +- Stalk **tip / bump** (Tesla first detent, **1 mph** / 1 kph) = Follow Distance 1–7 only. Stalk **up** = closer (toward stock 1). Stalk **down** = farther (toward stock 7). The tip steps **Highway** when MAX is 50 mph or higher (including while still accelerating up to that MAX, and including exactly 50). It steps **City** when MAX is under 50, even if ego is already faster. Traveled speed is used only when MAX is unset. Live follow uses the same cut. That frame’s MAX / `pedal_speed` step is undone immediately. Follow commits when the lever returns to IDLE after a first-detent tip that never hit 2nd detent. HUD **Follow Distance: N** shows the band that was stepped. +- Stalk **full press** (Tesla 2nd detent, **5 mph** / 5 kph) = keep MAX +5/−5. Do **not** remap Follow Distance, even though a physical full press always walks through first detent. + +card.py writes `NAPFollowDistance` on tip-release so the Driving Mannerisms indicator/slider updates live. Cooldown 0.25 s so press+release cannot double-step. Raw `SpdCtrlLvr_Stat` / CruiseButtons (UP_1ST vs UP_2ND, DN_1ST vs DN_2ND) distinguish tip vs hold. Pre-AP `buttonEvents` map both detents to the same `accelCruise`/`decelCruise` and must not be treated as a completed tip. + +**No lead:** tip and hold both stay MAX adjust (documented rule). During a long pause, `cruiseState.speed` is ego — detent still classifies tip vs hold. + +### HUD + +When stock Follow Distance changes onroad, selfdrived fires `EventName.hypermileFollowChanged` — same 1.5 s `NormalPermanentAlert` affordance as Driving Personality: **Follow Distance: N**. First read seeds the HUD baseline (no toast at process start); every later stalk/settings 1–7 change shows the toast. A stalk tip already at 1 or 7 still requests the HUD (`NAPFollowHudPending`). The event is held ~1.5 s (WARNING + PERMANENT) so a one-frame poll does not miss the 3X. + +## Safety + +- Default Off +- Stay at/under MAX and posted Cap/Follow +- Do not disable lead braking +- Soft-lat / DM / blinker / sticky MAX / one-SET / standstill gas-gate / reverse hard-cancel / One-Pedal Long unchanged +- Hill Climb does not raise MAX and does not disable lead braking +- Eco / Step Down / Hill Climb do not force Follow Distance + +## Tests + +`selfdrive/controls/tests/test_hypermile.py` — On snaps + Off restore (offset param not written −5; Follow Distance not snapped); posted-scaled eco (30 stays 30; 80→72) and Step Down (30 stays 30; 75→62.5; 80→65); maps-only (no invent without posted); stalk tip+lead writes `NAPFollowDistance` with Hypermile On and Off (full stock 1–7, including closest 1) after tip→IDLE; lead + tip-then-2nd-detent / 5 mph hold keeps MAX and does not remap Follow; button-only press is not a completed tip; no lead still steps MAX on tip and hold; Follow Distance HUD announces every param change after seed; settings/docs wiring. + +`selfdrive/controls/tests/test_hill_climb.py` — Hypermile Off / Hill Climb Off inert; uphill under MAX raises Accel 1 authority; several mph under MAX + downhill does **not** regen; deadband + uphill does **not** invent +g·sin; at/above MAX + downhill still eases; never exceeds MAX; lead / MPC brake still wins; under MAX + valid lead does **not** replace non-negative MPC `a` with map climb (no lead still climbs); above MAX + lead still map-decels. + +`selfdrive/controls/lib/tests/test_curve_max_hold.py` — curve snapshot/restore (sticky 60 survives a bend; a lower posted/eco target does not replace it). + +Existing `test_following_distance` / Pre-AP following tests stay on the stock 1–7 path. diff --git a/docs-nap/map-speed.md b/docs-nap/map-speed.md new file mode 100644 index 00000000000000..0a41a62ad76986 --- /dev/null +++ b/docs-nap/map-speed.md @@ -0,0 +1,279 @@ +# OSM Map Speed (MAX) + +Live OpenStreetMap speed limits on comma 3X, wired into NAP's existing cruise **MAX** (`CS.vCruise` / HUD "MAX"). This is not a second longitudinal controller. + +## What MAX is + +The on-road HUD box labeled **MAX** is the cruise set speed (`carState.vCruiseCluster`). This feature maps OSM `maxspeed` onto that value (and the long planner's `v_cruise`) while NAP already owns software cruise. + +``` +GNSS → mapd (offline OSM sqlite) → liveMapDataNAP + → card.py (pre-AP pedal software cruise only) + CS.vCruise / vCruiseCluster ← HUD MAX + → plannerd cap + map_track_decel (comfort a; lead can still brake more) + → LongitudinalMpc.update(radarState, v_cruise) + constraint = min(lead0, lead1, cruise_obstacle(v_cruise)) +``` + +Licenses: pfeiferj/mapd and sunnypilot SLA are MIT; we did **not** vendor the Go `mapd` binary or sunnypilot UI. NAP keeps a Python OSM querier (ODbL map data) on the existing `vCruise` path. The sunnypilot-specific stack stays on `naponsp-dev` per [contributing.md](contributing.md). Map data is © OpenStreetMap contributors ([ODbL](https://www.openstreetmap.org/copyright)). + +## Safety invariants + +- **Pedal mode** (`openpilotLongitudinalControl`, not `pcmCruise`): Cap/Follow may change `vCruise`. +- **No-pedal / stock CC**: display only. We do not spoof stalk +/- to chase map limits. +- **Cap**: `MAX = min(driver set, OSM limit + offset)`. Never raises. +- **Follow** (preferred): MAX tracks the OSM limit. A manual stalk set — **above or below** posted `a` — holds that absolute MAX until the posted value changes to `b`, then MAX **rebases to `b`** (driving or long-paused). Do not continuously overwrite sticky toward posted every frame while posted is unchanged. GPS / match drop is posted unknown: keep held MAX, never invent a posted. +- **Sharp curve:** snapshot HUD MAX / sticky / held at curve entry (lat accel or steer). Temporary corner slowing may lower published MAX (`limit_accel_in_turns` plus a comfort lat-accel cap). After lat accel / steer are straight-ish, restore that pre-curve set. Do not let the bend permanently rebase sticky or the map target (OSM flicker on a ramp must not bounce a pre-curve 60 down to the live eco target). A posted change that is still there after exit is a real new zone and may rebase. +- **Engage / SET:** **Double SET** (initial engage from fully disengaged, or second SET in the window while already in session) forgets sticky: maps on + posted known → HUD MAX and `pedal_speed_kph` = current posted (+ offset); maps off / posted unknown → current traveled speed. **One SET** after a brake long pause resumes longitudinal only at the held MAX (already rebased if posted changed). Pedal write-back is **take-speed-now**, **resume-held**, a **real stalk step**, or **Follow/system raise** when the posted limit increased. A sticky hold must **not** write every frame (that ate stalk +/- after CI.update). Stalk +/- is a 1 or 5 mph `pedal_speed` step; button events are extra. An ego jump is not a stalk. +- **Display / Off**: no control change. +- **Lookahead (Cap/Follow):** a **lower** OSM maxspeed ahead eases MAX down so you reach about the new limit as you enter that way. A **higher** limit ahead does **not** raise MAX early — Follow raises only once GPS is on the faster segment. +- **Roundabout:** detect OSM `junction=roundabout` / a compact closed circulating way out to **~140 m** (`RB_DECEL_ONSET_M`; was 200 m until Oct 1; must still have fired by 80–100 m) — not a big steer, and not a sharp town corner or signalized cross. Kinematic decel toward **15–20 mph** (OSM ring maxspeed when tagged, often 20) so 40–45 mph plans **a ≤ −1.0** until near ring speed. `aTarget` stays **≤ 0** while approaching / on the ring (no +a after a lead clears). Long enable inside the funnel applies full ease on that frame. Outer path bias **~3.2 m** (right in RHT / US) on the last 50 m of approach and while circulating — enough to counter a ~3 m inside cut. A short RB way is **not** dropped as a min-zone stub. Yield-before-merge, continue-circulate desire, and a UI chip are later tips. +- **A falling MAX must decelerate** (Cap/Follow, pedal mode, no overriding lead). The stock MPC cruise column is a virtual lead ~`get_safe_obstacle_distance(v_ego)` ahead with `V_EGO_COST=0`, so a 70→45 mph drop would not bind. Planner `min()`s MPC with `map_track_decel` at the **Accel 5** comfort `a` (0.80 m/s² at Normal). Accel 1–10 does not change this brake. Tesla `get_preap_accel_limits` still clips to −1.5 m/s². +- **A rising MAX must accelerate** (Follow, no overriding lead). MPC also will not climb to a higher MAX. Planner commands `map_track_accel` at Accel 1–10 when ego is below MAX and MPC is not braking — **except** when `radarState.leadOne` is valid: a lead owns follow, so map climb must not replace ~0 / slight+ MPC `a` toward MAX (that punched through a slower lead, then overshot and would not rematch). `map_track_decel` when above MAX still mins in with a lead present. Stalk up / Follow posted raise also writes that higher MAX onto `pedal_speed`. Hypermile **Hill Climb** (IMU pitch only; maps-elevation lookahead NOT included) may add grade to that climb when clearly under MAX **and there is no lead** so Accel 1 does not sag; it never raises MAX and does not invent `+g·sin` in the deadband. +- **Lead outranks map.** Map only sets the cruise ceiling plus comfort decel/accel. `mpc.update` is always `mpc.update(radarState, v_cruise)` after the map cap. +- Panda TX whitelist, pedal gating, and engagement FSM are unchanged. +- Default **Off** until US maps are downloaded and you pick a mode. + +## US map data + +The US speed-limits sqlite is **not in git** (too large; ODbL still requires attribution). After flash, download the prebuilt asset over Wi-Fi: + +| | | +|---|---| +| Release tag | `osm-us-speed-limits-v5` on `jmbrunick/openpilot` | +| Asset | `speed_limits_us.sqlite.zst` | +| SHA-256 | of the **zst** (`ASSET_SHA256`), verified **before** decompress. Dest sqlite is not hashed unless `SQLITE_SHA256` is set. `--sha256 ''` skips. | +| Install path | `/data/media/0/osm/speed_limits.sqlite` | +| Staging | `/data/media/0/osm/.download/` on the dest filesystem (not `/tmp`) | +| Size | **~204 MiB zst → ~570 MiB sqlite**. Fetch needs **854 MiB** free on `/data`. | + +On the comma 3X: **Settings → NAP → Map Speed Limit → Download US Maps** (offroad), or `python -m scripts.nap.fetch_osm_maps`. That is the first-install of the published US pack. Frequent local updates: **Refresh maps** (or `python -m scripts.nap.refresh_osm_maps`) — live OSM within **100 miles** (~160.9 km), merged into the installed sqlite. `mapd` reloads the sqlite every ~15s onroad — no reboot. To unlock those buttons without parking, Settings → triple-tap **NAP** → **Force Offroad** (see [force-offroad.md](force-offroad.md)). + +Download US Maps retries timeouts and dropped connections up to 8 times with backoff ("Retrying… (n)" on screen) and resumes with HTTP Range from `/data/media/0/osm/.download/*.partial`. If it still fails, tap Download again: it resumes from the kept partial for the same asset. Only a SHA-256 mismatch deletes the partial. + +If a previous download died with ENOSPC, remove leftovers then retry: + +```bash +rm -f /data/media/0/osm/*.partial /data/media/0/osm/.download/* +df -h /data +``` + +A previous good sqlite is left in place. Optional override path: param `NAPMapSpeedDbPath`. + +Publish a new US pack from a PC (Geofabrik PBF ~11 GB): + +```bash +osmium tags-filter us-latest.osm.pbf w/highway w/maxspeed -o us-maxspeed.osm.pbf +python scripts/nap/build_osm_speed_limits.py --pbf us-maxspeed.osm.pbf \ + --out speed_limits_us.sqlite --zst + +# Overlay MN statutory fills (~100 miles around Benson) onto that US pack: +python scripts/nap/build_osm_speed_limits.py --pbf minnesota-latest.osm.pbf \ + --fill-mn-statutory --benson --merge-into speed_limits_us.sqlite \ + --out speed_limits_us.sqlite --zst +``` + +Fills are NAP estimates (`source=MN_169.14`, Minn. Stat. 169.14). Do **not** upload guessed `maxspeed` tags to osm.org. Meta on the sqlite records tagged vs filled counts. + +Put the **zst** SHA-256 in `selfdrive/mapd/maps_manifest.py` **and** bump `selfdrive/mapd/maps-index.json` (see [Publishing a US pack](#publishing-a-us-pack)). For a PC-only smaller region file: `python scripts/nap/download_osm_speed_limits.py --lat … --lon … --radius-km 30`. + +## Refresh maps (100 miles) + +**Refresh maps** is one button: a local Overpass update, not a published-pack download. Radius is **100 miles** (~160.9 km) around the vehicle — the bounding box that contains that circle. + +On the 3X (offroad, Wi-Fi): + +1. **Location.** Wait up to **10s** for a GNSS fix (`gpsLocationExternal`, then `gpsLocation`). Refresh accepts the last received plausible lat/lon (not 0,0), including samples older than 2.5s and accuracy up to 200 m (yard/tree cover). mapd's onroad MAX match still uses 2.5s / 50 m. Otherwise last stored GPS (`LastGPSPosition` param or `/data/params/d/LastGPSPosition`). A successful fix is persisted so the next offroad tap works. If still nothing: start openpilot onroad until the GPS icon/fix is up for about a minute, then retry. Maps will **not** guess a city. +2. **Query OSM.** Reuses Overpass / `scripts.nap.download_osm_speed_limits` / mapd builders for highway ways in that box. Does **not** download the full US Geofabrik PBF on the 3X. Tagged numeric `maxspeed` is authoritative. The query also includes drivable highways **without** maxspeed (motorway…unclassified; plus residential/alley inside Minnesota) and applies the state default fill below locally (never uploaded to osm.org), so Refresh maps does not wipe the pack's estimated fills. +3. **Merge.** Copy the installed `/data/media/0/osm/speed_limits.sqlite` onto `/data` (not `/tmp`), delete/replace `way_id`s whose bbox intersects the 100-mile box, insert the Overpass ways (tagged + estimated state-default fills), keep the rest of the US pack. If no sqlite is installed yet, Download US Maps runs first, then the overlay — never a 100-mile-only dest file. +4. **Atomic install.** `os.replace` onto dest. Overpass timeout / HTTP / merge failure prints a real error and leaves the previous good sqlite. Retry-safe. mapd reloads ~15s onroad — no reboot. Progress (querying OSM, merging, installing) shows on the existing script-runner UI. + +Overpass can be slow in a dense metro. Wait or retry; the old maps stay put. + +## US default fills (estimated limits) + +Many US roads have no `maxspeed` in OSM (e.g. US-212 and town streets in Watertown, SD — route 00000185 matched nothing). Pack v5 and Refresh maps fill those ways with the **state default** for the road class. Posted OSM `maxspeed` always wins. + +- **Flag:** filled ways have `ways.estimated = 1` (posted = 0); `SpeedLimitMatch.estimated` exposes it. Sources: `_default`, or `MN_169.14` for Minnesota (the existing MN statute logic, `mn_statutory.py`, unchanged and now statewide). The car currently treats estimated limits **exactly like** the Minnesota fills always were (same Cap/Follow/lookahead) — no special handling yet; the flag is there so it can. +- **Classes filled:** motorway, trunk, primary, secondary, tertiary (+ links), unclassified. **Not** residential/living_street/alley/service outside Minnesota (they would roughly triple the pack for streets that are nearly always 25 mph). Unposted `*_link` ramps are capped at **45 mph**. +- **Urban vs rural:** a way is urban if its midpoint is inside an OSM `place=city|town|village` or city/town/village admin_level=8 polygon, or it has a `sidewalk` tag (same heuristic as the MN fills). +- **State:** from simplified US Census state polygons (`selfdrive/mapd/data/us_states.json`, public domain, via PublicaMundi/MappingAPI); shore roads use the nearest state within 0.1°. +- **Values:** + - Interstate (motorway) rural/urban and expressway: IIHS "Maximum posted speed limits", Oct 2026 — https://www.iihs.org/research-areas/speed/speed-limit-laws (Montana: night values). + - Rural trunk/primary: IIHS "other roads" capped at **65**; rural secondary/tertiary/unclassified: IIHS "other roads" capped at **55** (IIHS figures are ceilings, not what an unmarked road carries). + - Urban district: **25** unless the state code sets another default: IL 625 ILCS 5/11-601 (30), IN IC 9-21-5-2 (30), MN 169.14 subd. 2 (30), NY VTL 1180 / city default (30), TX Transp. Code 545.352(b) (30), FL 316.183 (30), GA O.C.G.A. 40-6-181 (30), NC G.S. 20-141(b) (35), PA 75 Pa.C.S. 3362 (35). +- These are estimates. Local ordinances, school zones and engineering-study postings differ; tag real limits in OSM to override. + +| State | Rural interstate | Urban interstate | Expressway (trunk/primary tagged expressway/motorroad) | Rural trunk/primary | Rural secondary/tertiary/unclassified | Urban (in city/town/village) | +|---|---|---|---|---|---|---| +| AK | 65 | 55 | 65 | 55 | 55 | 25 | +| AL | 70 | 70 | 65 | 65 | 55 | 25 | +| AR | 75 | 65 | 75 | 65 | 55 | 25 | +| AZ | 75 | 65 | 65 | 65 | 55 | 25 | +| CA | 70 | 65 | 70 | 65 | 55 | 25 | +| CO | 75 | 65 | 65 | 65 | 55 | 25 | +| CT | 65 | 55 | 65 | 55 | 55 | 25 | +| DC | 55 | 55 | 55 | 25 | 25 | 25 | +| DE | 65 | 55 | 65 | 55 | 55 | 25 | +| FL | 70 | 65 | 70 | 65 | 55 | 30 | +| GA | 70 | 70 | 65 | 65 | 55 | 30 | +| HI | 60 | 60 | 55 | 45 | 45 | 25 | +| IA | 70 | 65 | 70 | 65 | 55 | 25 | +| ID | 75 | 75 | 70 | 65 | 55 | 25 | +| IL | 70 | 55 | 65 | 55 | 55 | 30 | +| IN | 70 | 55 | 60 | 55 | 55 | 30 | +| KS | 75 | 75 | 75 | 65 | 55 | 25 | +| KY | 65 | 65 | 65 | 55 | 55 | 25 | +| LA | 75 | 70 | 70 | 65 | 55 | 25 | +| MA | 65 | 65 | 65 | 55 | 55 | 25 | +| MD | 70 | 70 | 70 | 55 | 55 | 25 | +| ME | 75 | 75 | 75 | 60 | 55 | 25 | +| MI | 70 | 70 | 70 | 55 | 55 | 25 | +| MN | 70 | 70 | 65 | 55 | 55 | 30 (residential 30, alley 10) — Minn. Stat. 169.14 rules, unchanged | +| MO | 75 | 60 | 75 | 65 | 55 | 25 | +| MS | 70 | 70 | 70 | 65 | 55 | 25 | +| MT | 80 | 65 | 70 | 65 | 55 | 25 | +| NC | 70 | 70 | 70 | 55 | 55 | 35 | +| ND | 80 | 75 | 70 | 65 | 55 | 25 | +| NE | 75 | 70 | 70 | 65 | 55 | 25 | +| NH | 65 | 65 | 55 | 55 | 55 | 25 | +| NJ | 65 | 55 | 65 | 55 | 55 | 25 | +| NM | 75 | 75 | 65 | 55 | 55 | 25 | +| NV | 80 | 65 | 70 | 65 | 55 | 25 | +| NY | 65 | 65 | 65 | 55 | 55 | 30 | +| OH | 70 | 65 | 70 | 55 | 55 | 25 | +| OK | 75 | 70 | 70 | 65 | 55 | 25 | +| OR | 65 | 55 | 65 | 65 | 55 | 25 | +| PA | 70 | 70 | 70 | 55 | 55 | 35 | +| RI | 65 | 55 | 55 | 55 | 55 | 25 | +| SC | 70 | 70 | 60 | 55 | 55 | 25 | +| SD | 80 | 80 | 70 | 65 | 55 | 25 | +| TN | 70 | 70 | 70 | 65 | 55 | 25 | +| TX | 75 | 75 | 75 | 65 | 55 | 30 | +| UT | 75 | 70 | 75 | 65 | 55 | 25 | +| VA | 70 | 70 | 65 | 55 | 55 | 25 | +| VT | 65 | 55 | 50 | 50 | 50 | 25 | +| WA | 70 | 60 | 60 | 60 | 55 | 25 | +| WI | 70 | 70 | 70 | 55 | 55 | 25 | +| WV | 70 | 55 | 65 | 55 | 55 | 25 | +| WY | 75 | 75 | 70 | 65 | 55 | 25 | + +## Roundabouts in the pack (schema v4) + +Pack schema **v4** (`meta.pack_schema = 4`) adds `rb_ways` / `rb_nodes`: every OSM way tagged `junction=roundabout` (with or without `maxspeed` / `lanes`) plus the highway ways that touch a ring (approach/exit roads), stored in travel direction (two-way roads both ways). Rings without `maxspeed` get no speed-limit row, so the MAX/limit behavior is unchanged; they only feed roundabout detection and ring geometry. `build_osm_speed_limits.py` includes them by default; `--no-roundabouts` builds the old v3 layout. v3 packs still load (no rb tables = no ring geometry). + +- **Getting rings on the device:** Settings → NAP → Map Speed Limit → **Refresh maps**. The 100-mile Overpass query now also fetches `junction=roundabout` ways and their approach roads, and the merge adds `rb_ways` even onto an installed v3 pack. The v4 US first-install pack (`osm-us-speed-limits-v4`) includes rings for all 50 states + DC, so Download US Maps adds them. +- **Advisory and mini-roundabouts:** a ring's `maxspeed:advisory` is stored when it is lower than the posted `maxspeed` (or when there is no posted limit). `highway=mini_roundabout` nodes become a synthetic 7 m ring (way_id = −node id) in PBF builds, so the funnel sees them; roads through the node are its approaches. Refresh maps (Overpass) does not add mini-roundabouts yet. +- **Ring slow-down target:** when the ring geometry is known, `roundaboutSpeedLimit` uses a comfort speed from the lane radius (lateral ≤ ~2.5 m/s², clamped 15–20 mph; e.g. Soco Rd/Dellwood ≈ 15.8 mph) instead of the default 20 mph. +- **Roundabout Steering Assist** (`NAPRoundaboutAssist`, Settings → NAP → Driving Mannerisms, **default Off**, Tesla Pre-AP only): on a mapped ring, blends the model curvature toward the lane circle (hold right entry until ~8–10 m before the ring, correction slewed ≤ 0.07/s, weight from GNSS/map-match confidence). The camera path keeps authority on lane edges and driver torque overrides as usual. It depends on GNSS accuracy (validated only in replay), hence default Off. mapd publishes the matched ring to `NAPRoundaboutRing`. + +## Publishing a US pack + +Download US Maps still uses the GitHub Release + `maps-index.json`. Bump those when you republish a full US sqlite from a PC: + +1. Build a new US sqlite and zst on a PC (same `build_osm_speed_limits.py` flow as above). +2. Attach `speed_limits_us.sqlite.zst` to a **new** GitHub Release on `jmbrunick/openpilot` (e.g. `osm-us-speed-limits-v3`). Do not replace the in-git JSON with the 204MB zst. +3. SHA-256 the **zst** (`sha256sum speed_limits_us.sqlite.zst`). +4. Bump `selfdrive/mapd/maps-index.json`: + - `revision` — integer or dotted semver, must be **greater** than the previous value (current first-install is `"4"`) + - `asset_url` — Release download URL for the new zst + - `asset_name` — usually `speed_limits_us.sqlite.zst` + - `sha256` — hex digest of the zst + - `bytes` — zst size (optional) + - `notes` — optional +5. Keep first-install constants in `selfdrive/mapd/maps_manifest.py` in sync when you intend a new clone/flash to get this pack (`RELEASE_TAG`, `ASSET_SHA256`, `RELEASE_REVISION`, sizes). +6. Merge the JSON (and manifest) to `nap-dev`. Download US Maps fetches: + + `https://raw.githubusercontent.com/jmbrunick/openpilot/nap-dev/selfdrive/mapd/maps-index.json` + +## Settings → NAP → Map Speed Limit + +All map-speed controls live in this submenu (main NAP stays uncluttered). TICI and mici: + +- **Map Speed (MAX)** (`NAPMapSpeedMode`): Off / Display / Cap / Follow +- **Map Speed Offset** (`NAPMapSpeedOffsetMph`): -5 / 0 / +5 mph +- **Lookahead** (`NAPMapSpeedLookahead`): Off / Late / Normal (default) / Early +- **Refresh maps**: live OSM within 100 miles, merged into the installed US sqlite +- **Download US Maps**: first install of the current published pack +- **OSM Map Data** / **Map revision**: installed pack status (Refresh does not bump revision) +- Cap/Follow require the pedal interceptor +- **Acceleration** 1–10 is on **Settings → NAP → Driving Mannerisms** (`NAPMapSpeedAccel`) — not this page + +## Anticipatory decreases and Accel + +`mapd` probes 40–600 m along GPS heading **and** walks the matched OSM way to its end (then the next way) so a short intermediate maxspeed is published as `nextSpeedLimit`. Policy uses **decreases only**. + +**Minimum zone length:** a lower limit (current match or `nextSpeedLimit`) that is gone within **`MIN_ZONE_LENGTH_M` (76 m / ~250 ft)** along the travel heading is ignored. OSM/GPS at a crossroads can briefly snap onto a side street or a tiny fill stub and look like a short speed zone on the highway. Real posted drops that continue past that threshold still apply (US 12 Benson 60→50 is ~760 m of tagged 50; DeGraff 30 is hundreds of meters). This is a general matcher rule, not a Benson/DeGraff hardcode. Bearing / class route continuity from the off-route filter still applies. Lookahead Off still disables anticipatory easing. + +| Lookahead | Comfort decel | Extra margin | Start no farther than | +|---|---|---|---| +| Off | — | — | change only after GPS is on the slower way | +| Late | 1.20 m/s² | 110 m | 360 m | +| Normal (default) | 0.80 m/s² | 110 m | 600 m | +| Early | 0.55 m/s² | 230 m | 600 m | + +When the upcoming drop is inside that window, MAX interpolates from the current limit at `d = kinematic + margin` to the new limit at the sign. Brake stays Accel-5 **0.80 m/s²** at Normal (not raised). The +110 m is the measured 50→30 shortfall (42 mph at the sign vs 30); every decrease starts at `kin + 110 m`, not a 50→30-only window. A 10 mph drop (60→50) is not filtered. `mapd` walks the matched OSM way to its end (then the next way) so a short intermediate limit is not skipped by 40 m heading probes. A stub shorter than 76 m (~250 ft) along heading is not a posted drop. + +**HUD current speed** (top-middle on the 3X) is wheel/ESP `vEgo` only. `vEgoCluster` is Tesla `DI_digitalSpeed`, which pre-AP also uses as `cruiseState.speed`. Map-speed writes MAX into `vCruise` / `pedal_speed` / `cruiseState.speed` (90 kph = **56 mph**). LIMIT/MAX may show the map limit; the live number must not. + +**Acceleration** (Settings → NAP → Driving Mannerisms) scales **Follow climb** (MAX rising, no overriding lead) **and** lead gap-close +a. Same Accel 1–10 envelope, including last-mph taper (Accel 1 baby-steps ~5 mph out; Accel 7–10 stay brisk). Brake uses Accel 5 (`map_brake_a_ms2` / `map_track_decel`). Adaptive Accel no longer uses the full cruise profile to punch a large follow gap. + +| Accel | Factor | MAX climb / lead-close `a` (Normal) | Used for | +|---|---|---|---| +| 1 | 0.45 | **0.36 m/s²** | climb + catch-up (gentlest; last ~5 mph is a baby-step) | +| **5** | 1.00 | **0.80 m/s²** | climb, catch-up, *and* all map braking | +| 10 | 2.00 | **1.60 m/s²** | climb + catch-up (quickest, clamped); Accel 7–10 stay brisk to the target | + +MAX-rise and lead-close `a = clamp(0.30, 1.60, a_lookahead × factor)` inside ~200 m (Bosch). Changing Accel 1 vs 10 must not change brake feel. Rapid / FCW / a real stop still own MPC danger; non-rapid mild closes are floored at overlay MILD. A higher limit ahead may still be published as `nextSpeedLimit`; Cap/Follow ignore it until `speedLimit` itself is the higher value. + +## How to test + +**Off-device:** + +```bash +pytest selfdrive/mapd/tests/test_map_speed_policy.py \ + selfdrive/mapd/tests/test_osm_db.py \ + selfdrive/mapd/tests/test_fetch_maps.py \ + selfdrive/mapd/tests/test_local_refresh.py \ + selfdrive/car/tesla/tests/test_preap_sticky_max.py \ + selfdrive/car/tesla/tests/test_preap_blinker_lat_pause.py \ + selfdrive/selfdrived/tests/test_preap_regen.py \ + selfdrive/controls/lib/tests/test_driver_lateral_handoff.py \ + selfdrive/controls/lib/tests/test_curve_max_hold.py -q +``` + +Policy tests include lead precedence, fetch of a tiny sqlite over HTTP, and Refresh maps location/merge (no network). + +**Offroad Refresh maps (3X, Wi-Fi):** + +1. After a drive with GPS (so `LastGPSPosition` is stored), park, Settings → NAP → Map Speed Limit → **Refresh maps** → Start. +2. Script runner should show location source (GNSS or last stored GPS), querying OSM, merging, installing. Must not name a guessed city. +3. `ls -l --time-style=full-iso /data/media/0/osm/speed_limits.sqlite` — mtime updates; size stays US-pack scale (hundreds of MB), not a tiny 100-mile-only file. +4. Unplug GPS / no LastGPSPosition (fresh flash, never driven): Refresh maps must error and leave any existing sqlite. +5. Airplane mode / Overpass down: error text, previous sqlite kept. Retry later. +6. No sqlite yet: Refresh maps downloads the US pack first, then overlays. Download US Maps still does first-install only. + +**On comma 3X, parked, GPS lock:** Mode = Display. Confirm the LIMIT sign matches a known posted limit (OSM, not NAR). After Refresh maps, a local OSM edit (new maxspeed) should show within ~15s onroad — no reboot. + +**On-road, pedal mode:** + +1. Cap, **no lead**: set MAX above the posted limit; the car must decelerate toward that MAX (Accel 5 ≈ 0.80 m/s²). Raising the stalk cannot exceed the cap. +2. Cap/Follow, **slower lead**: the car still slows for radar `leadOne`. +3. Follow, Lookahead Normal, **no lead**. On a known drop (50→30), Accel **1 and 10 must feel the same brake**, and ego should be near 30 at the sign (not still ~42). On a known rise (35→45, after GPS is on the faster way), Accel 1 climbs lazily and Accel 10 quicker — the pedal target and the car must actually speed up. Lookahead = Off: MAX and decel start only after GPS matches the slower way. On a continuous highway through a grid of cross streets (US 12 SE Benson→DeGraff is the example, not a special case), MAX must **not** ease for a side street or a ~250 ft stub; it may ease for a real on-route 60→50→30 that lasts longer than 76 m. +4. Drive toward a **higher** limit: MAX must **not** rise until you are on the faster segment. +5. Follow: set 55 in a 65 — MAX stays 55 until the posted limit changes; set 45 in a 65 — same. Posted 65→45 (or 65→70), driving or long-paused, rebases MAX to the new posted. Brake pause then one SET resumes the held MAX (55 in a 65, or the rebased posted). Double SET with maps on takes current posted; maps off / unknown posted takes current traveled speed. GPS glitch must not wipe sticky or invent a posted. Double-pull engage with a valid limit: MAX **and** the car start at the posted limit immediately. +6. Top-middle live speed must match wheel/ESP (about 45 if that is actual), not MAX (56) and not LIMIT. +7. Cancel is a full disengage (held MAX forgotten). Brake is a long pause: one SET resumes held MAX; double SET takes posted or current speed as above. A latched driver turn does not pause long. +8. **Sharp curve, Hypermile On / Step Down Off:** if MAX is 60 before the bend (sticky or that displayed set), the car may slow and HUD MAX may move through the corner. After exit MAX must return to **60**, not stay on the live eco posted target. A real posted change that is still there after the bend may rebase. + +**No-pedal:** LIMIT sign only; stock CC set speed is unchanged. Sticky MAX / one-SET resume is pedal software cruise only. + +## Build notes + +- Python-only `selfdrive/mapd`. Device needs `zstandard` (already an openpilot dep) to decompress the Release asset. +- Cereal: `liveMapDataNAP` on custom reserved 0. Rebuild so `params_keys.h` picks up the new params. +- `mapd` is an onroad managed process in `system/manager/process_config.py`. + +## Rail crossings (pack v5, data only) + +Pack schema 5 adds `rail_crossings` (node_id, lat, lon, way_id, kind, barrier, light, crossing): OSM `railway=level_crossing` / `railway=crossing` nodes that lie on a drivable highway way, with `crossing:barrier`, `crossing:light` and `crossing=*`. 250,339 in the US (2026-10-11 extracts), ~4.9 MB of the zst. `selfdrive/mapd/rail_crossings.py: crossings_ahead(con, lat, lon, bearing_deg, horizon_m, lateral_m)` returns them nearest-first. No alert/UI yet; older packs simply return []. diff --git a/docs-nap/nap-dash.md b/docs-nap/nap-dash.md new file mode 100644 index 00000000000000..ecefb85dbed8e8 --- /dev/null +++ b/docs-nap/nap-dash.md @@ -0,0 +1,93 @@ +# Comma web UI + +The comma 3X serves its own settings page. Two devices: the comma and the car (the Tesla MCU browser, or a phone on the same network). There is no phone-hub app and no video or audio stream. + +Process: `nap_dash` (`selfdrive.nap_dash.server`). It starts with openpilot when `NAPDashEnabled` is On (default). + +**Do not merge** this branch into `nap-dev` until Justin flashes it and confirms on-road engage is clean. No panda flash. The installer rebuilds `common` only if a Params key changed; this branch does not add one. + +## URL + +``` +http://100.99.9.1/ +``` + +That is port 80 on the hotspot. The server binds `0.0.0.0`, so the same page is also served on home Wi-Fi at `http:///`. If port 80 cannot be bound, it falls back to `http://100.99.9.1:7070/` and keeps running. Override with `NAP_DASH_HOST` / `NAP_DASH_PORT`. + +This is LAN / hotspot only. Do not expose it with Funnel, ngrok, or Cloudflare. + +## Hotspot subnet + +The comma hotspot (Settings → Network → Enable Tethering) uses **100.99.9.0/24**, comma at **100.99.9.1**. + +Pre-AP Tesla browsers would load local pages on `100.99.9.x` and not on the default `192.168.43.0/24` or `10.42.0.0/24` ranges. `TETHERING_IP_ADDRESS` in `system/ui/lib/wifi_manager.py` is what NetworkManager stores on the hotspot profile (`method=shared`, prefix 24, `never-default`). That profile is on disk under NetworkManager's system connections, so it survives reboot. + +On every UI start the comma rewrites the hotspot profile if it still has an old address. Joining a normal Wi-Fi network is a different profile (`method=auto`) and is not touched. `shared` still NATs clients through the comma's default route, so LTE internet sharing keeps working. A phone or the MCU that uses the hotspot for internet is using the comma's LTE data. + +## What the page is + +Tabs follow the on-device settings sidebar (Device, Network, Toggles, Software, NAP, Firehose, Developer). NAP subpages (Driving Mannerisms, Map Speed Limit, Radar, and the triple-tap Hidden card) are discovered from those screens. + +The page is laid out for the Pre-AP Model S 17" portrait MCU with the map on top and the browser on the bottom: a wide, short pane. Compact top tabs use a blue highlight on the selected tab. Each setting is a dark row with the control on the right, in the same order and sections as the comma screen. The tab bar stays put and the open panel scrolls inside itself, so the bottom of the pane is not clipped. A phone gets the same rows in one column. + +Toggles, choices, titles, and descriptions are parsed from the device UI source at startup (`selfdrive/ui/layouts/settings/*.py` and the constants those files import). There is no second hand-written toggle list. A new toggle added in that UI source shows up here after restart, with no web-side edit. + +Writes go through Params the same way the device does: plain `put` / `put_bool`, and the same helpers for Experimental Mode, Simulate Look / False Alert Ignore, Force Offroad, and Hypermile. Toggles the device locks while the car is on stay locked while `IsOnroad` is set. Toggles it locks while engaged stay locked while `IsEngaged` is set. Those two Params are written by `hardwared`; this process does not subscribe to cereal to read them. Dangerous toggles (Experimental Mode, alpha longitudinal, reboot, power off) ask for confirmation. + +Software / branch switching stays: `GET/POST /api/software` (`set_branch`, `fetch`, `download`, `install`). The Software tab has Check and Download buttons (Download lights up once a check finds an update); Install & reboot appears once a downloaded update is ready. + +## What it is not + +- Not a live cluster, BMS view, or camera stream +- Not engage. There is no engage control. `POST /api/set` with action `engage` is rejected. +- No high-rate sockets. No `SubMaster`, no `can`, no `modelV2`. +- Not nav injection +- Script actions (EPAS flash, pedal calibrate, map download, uninstall, reset calibration) stay on the comma screen + +Speed-limit sign reading, map speed, and speed-limit control are not modified by this branch. If those panels define a toggle, the page shows it only because it was parsed from that source, and the write is the same Params write the device already does. + +## No high-rate sockets + +`selfdrive/nap_dash/server.py` does not construct a cereal subscriber. There is no live loop. `/api/state` is an empty stub so an old page does not 500. + +`nap_dash` is an **optional / non-critical** manager process. A crash, a port bind failure, or a preimport error must **not** raise `processNotRunning` (`Process Not Running` / `nap_dash`) and must **not** fail `manager` start. That alert is NO_ENTRY + SOFT_DISABLE — it prevents engage entirely. + +## Setup + +1. Flash: + +``` +https://installer.comma.ai/jmbrunick/openpilot/cursor/mcu-web-ui-c588 +``` + +2. Reboot so `nap_dash` starts and the UI rewrites the hotspot profile. +3. On the comma: Settings → Network → Enable Tethering. Note the network name (`weedle-` plus the first 4 characters of the dongle id) and the password (default `swagswagcomma` until you change it). +4. On the Tesla MCU, join that Wi-Fi network. +5. Open `http://100.99.9.1/` and bookmark it. +6. A phone on the same hotspot, or any browser on the comma's home Wi-Fi, can open the same page. + +## Dash off + +SSH: + +``` +python3 -c "from openpilot.common.params import Params; Params().put_bool('NAPDashEnabled', False)" +``` + +Then reboot. Or set `BLOCK=nap_dash` in the launch environment. Re-enable with `NAPDashEnabled=True` and a reboot. Default is On. + +## Tests + +`selfdrive/nap_dash/tests/test_discover.py` — parsing the device UI, including a new toggle added only in that source. + +`selfdrive/nap_dash/tests/test_settings.py` — Params writes, onroad / engaged locks, confirmation, no engage. + +`selfdrive/nap_dash/tests/test_server_smoke.py` — process wiring, HTTP, no cereal subscriber. + +`selfdrive/nap_dash/tests/test_system_api.py` — `/api/software` branch switch. + +`system/ui/lib/tests/test_tethering_subnet.py` — hotspot address `100.99.9.1/24`. + +## Not verified on hardware + +The Tesla MCU browser, NetworkManager DHCP on the new subnet, LTE NAT, and an on-road engage check need the comma and the car. This tree was not flashed. diff --git a/docs-nap/safety-model.md b/docs-nap/safety-model.md new file mode 100644 index 00000000000000..217699ced0b85f --- /dev/null +++ b/docs-nap/safety-model.md @@ -0,0 +1,98 @@ +# Safety Model + +Panda-layer invariants for the Pre-AP target. Source of truth is `opendbc_repo/opendbc/safety/modes/tesla_preap.h` — this doc explains the *why*. + +## Relay and blocking + +```c +{0x488, 0, 4, .check_relay = false, .disable_static_blocking = true} +``` + +Every Pre-AP TX entry uses both. Pre-AP has no harness relay hardware — the panda connects directly to the car's CAN bus. Standard openpilot assumes a relay that routes CAN between stock AP and panda when openpilot is inactive; setting `check_relay=true` would cause the panda to falsely detect a relay malfunction and block all TX permanently. `disable_static_blocking=true` is required for the same reason. + +Tinkla handled this identically via `generic_rx_checks(false)` in the older panda API ("PreAP has no relay", `safety_tesla.h` line 1071, `tesla_unity_betaC3`). The modern API added `check_relay` and `disable_static_blocking` with restrictive defaults, so we explicitly opt out. + +## RX checksum and counter validation + +```c +{.msg = {{0x370, 0, 8, 25U, .ignore_quality_flag = true, + .ignore_checksum = true, .ignore_counter = true}, ...}} +``` + +Pre-AP EPAS firmware uses a byte-sum checksum, but the exact algorithm has not been verified across every firmware version in the field. A mismatched validation caused a silent 21-second steering dropout during testing — the safety layer silently rejected EPAS messages, the car stopped steering, and no alert fired because the underlying RX check was "valid" from the framework's perspective. + +Tinkla's RX checks also disabled checksum/counter validation. Once the checksum algorithm is verified across all in-the-wild EPAS firmware, these can be re-enabled. + +All actual safety logic remains active: + +- Steering angle + rate limits via `steer_angle_cmd_checks_vm()` +- `controls_allowed` gating on every TX +- Disengage on hands-on override (level >= 2), except during a blinker-latched driver turn (one lamp or held LEFT/RIGHT, flash-latched ~1s, then hand-on until release) +- Disengage on EPAS error codes 6–9, except during that same turn pause +- Disengage on door open, gear out of Drive via `pcm_cruise_check(false)` **while not in Drive** so `cruise_engaged_prev` is already clear before Drive return. Python reverse/door `hard_cancel_session` still spoofs CANCEL to drop stock CC, but that spoof is **TX-only** — panda does not RX its own TX. Drive SET while `!controls_allowed` is last-resort only. TX CANCEL while already disallowed also clears the latch. selfdrived holds the 3X/OP mismatch counters at 0 for the whole R/P period — not on Drive entry. **Flash the panda** after this safety change. +- Disengage on stalk cancel (with 600 ms echo filter) +- AEB events blocked from openpilot +- EPB `epasControl` mode validation +- Pedal TX gated by `ENABLE_PEDAL` flag + `get_longitudinal_allowed()` + +## Conditional RX checks + +`preap_rx_checks[]` is selected by the `ENABLE_PEDAL` flag. The pedal variant adds `0x552` at 50 Hz; the no-pedal variant omits it. + +Reason: panda's `safety_tick` computes `timestep = 1e6 / frequency` unconditionally. `frequency=0` means divide-by-zero, which marks the check as lagging and trips `safetyRxChecksInvalid` → controls mismatch. A tester without a pedal hit this on `nap-release` in April 2026 — regression test lives in `test_tesla_preap.py::test_no_pedal_does_not_invalidate_rx_checks`. + +## TX whitelist + +```c +static const CanMsg PREAP_TX_MSGS[] = { + {0x488, 0, 4, ...}, // DAS_steeringControl + {0x2B9, 0, 8, ...}, // DAS_control + {0x214, 0, 3, ...}, // EPB_epasControl + {0x551, 0, 6, ...}, // Pedal on bus 0 + {0x551, 2, 6, ...}, // Pedal on bus 2 (alternate wiring) + {0x45, 0, 8, ...}, // STW_ACTN_RQ (stalk spoof) +}; +``` + +`0x45` is the stalk-action request message. We spoof it to drive stock Tesla CC when no pedal is installed (see [engagement.md](engagement.md)). There is no relay to hide behind, so every TX address must be explicitly listed. + +## GTW radar emulation + +When `RADAR_EMULATION` is set, the panda forwards chassis-bus traffic with an optional radar-position rewrite. This uses the `rx_all` hook — not `rx` — because it must see every CAN frame, not just the whitelist. Using `rx` here would break radar forwarding silently when messages fell outside `preap_rx_checks[]`. + +## Brake architecture + +Panda hardcodes `brake_pressed=false`. The framework's generic brake-to-disengage path never fires on pre-AP. This is deliberate: + +1. `carstate.py` reads real brake state from `BrakeMessage` CAN +2. Passes to `engagement.process_buttons(real_brake_pressed=...)` +3. On brake rising edge in pedal mode: drops `enableLongControl=False` but keeps `cruiseEnabled=True` (lateral stays active, only pedal drops) +4. `ret.brakePressed = False` suppresses the generic openpilot brake handler from also killing lateral + +The driver can always override steering via hands-on level ≥ 2. The panda enforces that, except during a blinker-latched driver turn (lat is already released; wheel torque must not `pcm_cruise_check(false)` or selfdrived will `controlsMismatch` after 2s). It does not enforce brake-to-disengage. + +See `test_tesla_preap.py::test_prev_user_brake` for the panda-layer invariant test. + +## Blinker-turn latch (panda flash required) + +`tesla_preap` keeps `controls_allowed` when a **driver turn** is active so a high-torque corner (EPAS hands-on ≥ 2 / error 6–9) does not `pcm_cruise_check(false)`. That is the same intent as Python `BlinkerLateralHold` / `blinker_turn_blocks_steering_disengage`: + +- one GTW lamp XOR (`BC_indicatorLStatus` / `R` == 1), or +- physical stalk `TurnIndLvr_Stat` LEFT/RIGHT, or +- latched through GTW lamp flash gaps (~1s continuous dark ends the turn), then hand-on until release + +A stalk **tip** (LEFT/RIGHT then IDLE within 0.40s) is ALC: leftover keep-alive flashes are not a turn. Same-direction stalk during that keep-alive must be held 1.0s to become a turn. Hazards (both lamps) are not a turn. Stalk cancel, door open, and gear out of Drive still drop immediately. + +While that tipped lane change is active, including the ~1 s lamp flash-dark gap (`preap_alc_keep`), hands-on **level 2** must not drop `controls_allowed`. That torque is the lane-change confirm, not a takeover. Hands-on **level 3** (EPAS maximum) is an emergency yank and still disengages during the flash gap. A latched stalk is unchanged (level 2 and 3 stay suppressed for the turn). **Reflash the panda** after this safety change; a Python-only update still drops `controls_allowed` in the flash-dark gap and selfdrived then raises `controlsMismatch`. + +This lives in the panda firmware, not just Python. tesla_preap skips `pcm_cruise_check(false)` and sets `steering_disengage_keep_controls` so `generic_rx_checks` does not drop on the same rising edge. + +After pulling this change, **flash the panda** (usual NAP/panda update path: on-device `scons` rebuilds `panda/board` from `opendbc_repo` safety, then reboot so `pandad` compares firmware signatures and flashes). A Python-only update leaves the old firmware dropping `controls_allowed` mid-turn; `controlsMismatch` then appears right after the hold ends. + +## Changing safety code + +1. Every edit to `tesla_preap.h` / `tesla_preap_blinker.h` needs a test in `test_tesla_preap.py` or `test_tesla_preap_blinker.py` +2. Run `scons opendbc_repo/opendbc/safety/tests/libsafety/libsafety.so` after editing +3. Pre-push: full `pytest test_tesla_preap.py`, then CI (safety tests run on every branch push) +4. If changing RX rate expectations, replay against a real drive log to confirm — see `scripts/nap/analyze_engagement.py` for a starter replay harness +5. Device: rebuild panda firmware and reboot so `pandad` flashes. Confirm no "reflash panda" / signature mismatch in logs. diff --git a/docs-nap/speed-sign-log.md b/docs-nap/speed-sign-log.md new file mode 100644 index 00000000000000..4dd3b6240cdfc6 --- /dev/null +++ b/docs-nap/speed-sign-log.md @@ -0,0 +1,220 @@ +# Speed Sign Logger (log-only) + +On-drive MUTCD numeric speed-sign logger for comma 3X. **Default off.** Log-only: it does not write sqlite, does not change cruise / HUD **MAX** (`vCruise`), and does not query osm.org. + +Stock `modelV2` has no `speedSign` head. This is a separate process (`speedsignd`) that reads the ROAD camera + GNSS and runs a compact **YOLOv8 ONNX** (US traffic-sign classes, including 55/60). The old numpy template matcher is tests/dev only — it does not see real roadside signs. + +**Driving model first.** Route 0000017a showed the failure was the GPU, not the CPU budget. modeld sat at 22–26 ms until speedsignd's tinygrad realize dispatched onto the same Adreno (QCOM) modeld uses, and modeld jumped to 300–710 ms. Inference is CPU only. The stock 3X image has neither `onnxruntime` nor `cv2.dnn` (route 00000180 logged `onnxruntime-absent(ModuleNotFoundError)` and `cv2-dnn-absent` and fell back to tinygrad CLANG). **Install weights** also installs pinned onnxruntime **1.31.0** CPU (`cp312`, `manylinux_2_28_aarch64`) into `/data/media/0/nap/pylib` and speedsignd loads it with `sys.path`. That wheel is not pip-installed and does not touch the system venv. Session options stay `CPUExecutionProvider`, `intra_op_num_threads=1`. Tinygrad `DEV=CPU` / CLANG remains the slow fallback only, and its first realize is refused while engaged (`reason=compile-wait`), including when the first frame arrives already engaged at boot. 4 Hz YOLO can still show “driving model is lagging”, ~35% `modeld` frame drops, **TAKE CONTROL IMMEDIATELY**, or “Communication Issue Between Processes.” + +**Logger On keeps running YOLO while openpilot is engaged** (`selfdriveState.active`, or state in enabled / softDisabling / overriding). The process and SIGN / NO WT HUD still start. The plate shows the held mph while engaged. It does **not** show **WAIT** for that — WAIT was the old pause, and it is why a drive that was engaged 95% of the time never read a sign. + +Report `swaglog | grep "speedsignd timing"` (`read_interval_ms`, `infer_ms`, `cpu_share`, `threads`, `os_threads`, `backend`, `engaged`, `backoff`, `reason`). `backend=` must be `onnxruntime-cpu`, `opencv-dnn-cpu`, `tinygrad-clang`, or `tinygrad-cpu`. `threads=` is the pinned compute pool and must be `1`. `os_threads=` is every OS thread in the process. Do not treat a blank plate as “drive parked” or “weights are bad.” + +**Engaged and manual driving both collect** — including moving, no assist. This is **not** gated on park or Force Offroad. Logger On, and log speed-limit signs + GNSS to JSONL. OSM upload is future work. + +Unknown cereal is **not** a pause. After a ~2 s startup, unread `selfdriveState` allows the same throttled detect and logs a warning. SubMaster polls at **20 Hz** so 100 Hz `selfdriveState` alive/valid cannot flap the gate; YOLO stays ≤ **1 Hz**, and a long infer idles at least 3× that infer before the next one (about 25% of one core). Engaging does **not** abandon an in-flight ONNX. + +Detect is **1 Hz** or slower, `SCHED_IDLE` (else nice 19), little **core 2** only, one thread — engaged and manual. Core 0 is the UI, 1 is sensord, 3 is pandad/encoderd, 4 is controlsd, 7 is modeld. **If TAKE CONTROL or lag comes back, turn Speed Sign Logger Off.** Do not raise `modeld` priority. A back-off line in swaglog means speedsignd saw `modelV2` frame drops, a skipped frame id, `modelExecutionTime` above 50 ms, its own CPU share over 25%, or a model/controls alert, and rested. A frame skip or modeld over 50 ms pauses at least 10 s (`reason=model-skip` or `reason=model-exec`). + +## Enable + +1. **Install weights** (once, Wi-Fi) — Settings → NAP → **Install weights** (offroad / Force Offroad), or SSH below. That installs the ONNX and the CPU runtime. Without `/data/media/0/nap/speed_sign.onnx` the onroad SIGN plate shows **NO WT**. With the ONNX but without the runtime, Settings says **runtime missing** and the plate shows **NO RT**. Neither will light mph on real signs. +2. **Settings → NAP → Speed Sign Logger** → On + (comma 4 / mici: **Settings → NAP → speed sign logger**) +3. Or: `Params().put_bool("NAPSpeedSignLog", True)` / `echo -n 1 > /data/params/d/NAPSpeedSignLog` +4. Go onroad. Manager starts `speedsignd` only when the param is true **and** the car is onroad. +5. **Drive, including engaged** (moving is OK). SIGN shows the mph while openpilot is **actively controlling**. It does not show **WAIT** for engage. If the plate stays blank on a clear sign, grab swaglog. + +Off (default): the process does not run. Logger On never changes that default. + +Reset to Defaults turns the logger back off. Weights on `/data` stay. + +Optional detect rate (default 1 Hz, clamped 0.2–4): `NAP_SPEED_SIGN_HZ=0.5` in the process environment. Do not raise this on a 3X. While engaged, a short infer still waits out that period. A long infer waits `4× infer` (the infer plus 3× idle). It is not 0 Hz. + +Manual detect is **cheap-path** so Logger On is less likely to starve `modeld`: + +- two right-side tiles of the 1928×1208 ROAD frame, alternating one read at a time, letterboxed into the 320 ONNX — never a full-frame RGB convert, and not the old 1208² letterbox (that left an 80 ft sign at about 20 px). The lower tile is **x=1300, y=520, 628×320** (through x=1928, y=840). Route 0000017a signs sat at about y=557–805, x=1110–1914, inside that tile. Town routes sat at y=340–795, x=968–1928, and y=340 is above the lower tile, so the second tile is **x=1288, y=260, 640×320** (through x=1928, y=580). It covers y=340 and overlaps the lower tile from y=520 to y=580. The x=968–1288 tail is not a third tile: at the measured 627 ms infer, two tiles already use the 25% budget and each band is seen about every 5 s; a third tile would push that to about 7.5 s. Scale on the lower tile is 320/628 ≈ 0.51. A sign ≥ 60 px tall stays ≥ 30 px in the model. +- **CPU only.** Order: vendored or system `onnxruntime` `CPUExecutionProvider` (the 3X install puts 1.31.0 on `sys.path` from `/data/media/0/nap/pylib`), else `cv2.dnn` with `DNN_BACKEND_OPENCV` and `DNN_TARGET_CPU` when `cv2.dnn.readNetFromONNX` exists (it does not on this 3X), else tinygrad on `DEV=CPU` with the CLANG renderer, `CPU_COUNT=1`, `BEAM=0`, `NOOPT=0`, and `GPU`/`QCOM` set to 0. Startup logs `speedsignd cpu-only asserted backend=...` plus `threads=` (the BLAS pool, must be 1) and `os_threads=` (every OS thread) and raises if the device is not CPU. OpenCL is forced off. +- **No compile while engaged.** The first realize runs only when `selfdriveState` is known and not controlling. Unknown cereal is not that window. A boot whose first frame is already engaged does not compile. The worker re-reads that flag before realize. Engaged reads wait (`reason=compile-wait`). The kernels are written under `/data/media/0/nap/speed_sign_cache//` so that clang compile happens once per weights sha. `model-skip` rest is capped at **60 s** (route 0000017f logged a 531828 ms backoff after a 177 s compile). +- **1 ONNX / BLAS thread** (`OMP_NUM_THREADS`, `OPENBLAS_NUM_THREADS`, `TINYGRAD_NUM_THREADS`, `CPU_COUNT`, and the rest, all forced to 1) +- pinned to **little core 2** (modeld stays FIFO on core 7) +- `NAP_SPEED_SIGN_INFER_CAP_MS` default **800** is logged only. It does **not** add a second wait. Pressure adds another 3× infer of rest. `modelV2.frameDropPerc` backs off before the lag alert. Any skipped `frameId`, or `modelExecutionTime` above 0.050 s, pauses at least 10 s. +- `os.sched_yield()` while an infer is busy + +YOLOv8n-320 is about **2.2 GFLOP**. Expected timing on one Cortex-A55 after Install weights: + +| backend | where it exists | expected infer | read gap | +|---|---|---|---| +| `onnxruntime-cpu` | vendored 1.31.0 wheel (this is the 3X path) | **627 ms** median on route 00000181 (the x86 scale estimate was ~300 ms) | **~2.5 s** steady (`4× infer`); each tile ~5 s | +| `opencv-dnn-cpu` | not in the stock 3X image | **~300–500 ms** if some other image has it | **~1.2–2 s** | +| `tinygrad-clang` | always, slow fallback | **~5800 ms** steady, first compile **~177 s** | multi-second, and the compile must not run while engaged | + +Route 0000017e measured tinygrad CLANG at about **5800 ms** (0.38 GFLOP/s) after a ~3 minute first compile. Route 0000017f (nap-dev) measured the first compile at **177 s**, finished while engaged, `threads=11`, then a false `model-skip` backoff of **531828 ms**. That steady CLANG time is the kernel, not a per-call recompile: ClangJITCompiler emits freestanding C at `-O2` and does not run LLVM's loop/SLP vectorizer, so the kernels stay scalar. `BEAM` and `NOOPT` were already off. A one-thread bench of this same file on onnxruntime **1.31.0** `CPUExecutionProvider` (AVX-512 Xeon at 2.4 GHz) measured **12 ms** (~180 GFLOP/s). **cv2.dnn** on that host was **25 ms**. One A55 at 1.8 GHz peaks near 14 GFLOP/s (8 FP32 FLOP/cycle). The Xeon peak is on the order of 150 GFLOP/s, so scaling the 12 ms ORT result by peak (14/150) is about **130 ms** if the A55 build keeps the same fraction of peak. ORT was near peak on x86; an A55 at 30–50% of its peak is about **300–500 ms**. The x86 scale suggested **~300 ms** and a gap of about **1.2 s**. Route 00000181 measured the A55 at **627 ms** median, `read_interval` median **2.6 s**, `cpu_share` **0.22**, modeld **22 ms** with 0% drops and no commIssue, `backend=onnxruntime-cpu`. Steady duty stays **≤ 0.25**: start-to-start is **max(1 s, 4× infer)**, about **2.5 s** at 627 ms (`read_interval_ms` ≈ 2500, `cpu_share` ≤ 0.250, `threads=1`, `reason=pace`). The two tiles alternate, so each tile is about every **5 s** when nothing is bursting. A class score ≥ 0.15 schedules two more YOLO reads on that same tile immediately (three frames, about 0.63 s apart, ~1.9 s of core time). 3×627 ms = 1.88 s, inside the 2.5 s allowed in a 10 s window. The idle after the burst waits until the trailing 10 s of infer time is back to ≤ 2.5 s. A model-skip or model-exec pause still cancels the burst. `reason=burst` is that immediate re-read. The 3X does not have cv2.dnn, so do not expect `opencv-dnn-cpu` there. The tinygrad CLANG fallback stays multi-second and is not the path after Install weights. The first session still waits until disengaged (`reason=compile-wait`), including a boot that is already engaged, and is then cached for that weights sha. `model-skip` extra rest is capped at 60 s. + +Onroad, `swaglog` prints `speedsignd detect paused (controlling=True enabled=… active=… state=… alive=… valid=…)` when you SET, `speedsignd abandon in-flight ONNX` if a YOLO was still running, and every infer: + +``` +speedsignd timing read_interval_ms=32000 infer_ms=8000 cpu_share=0.250 threads=1 backend=tinygrad-clang engaged=1 backoff=0 reason=pace +speedsignd infer 8000ms backend=tinygrad-clang frame=1928x1208 letterbox=320 crop=1300,520 628x320 … peak=0.72/speedLimit65 n_over=1 sl_peak=0.72/speedLimit65 … refine=50:0.71 class=65 luma=90/35 chroma=1 prep=18 sess=7900 raw=[(50, 0.71)] hud=[(50, 0.71)] jsonl=[] +``` + +`refine=` is the existing crop digit read (`refine_mph`), not a new digit reader. It may replace the class only with a real US limit (5–85, step 5). It must not store 4, 46, or 100, and it must not turn a valid class into a dropped digit (route 00000181 produced a 5 from a 45). JSONL still lights only after **two reads from different frames** agree. The HUD does too, except one read at **≥ 0.70** on a real limit lights immediately and holds **~45 s** unless a different limit is read within **3 s**. 0.60 still needs the second read. `YOLO_MIN_CONF` stays **0.40**. Class and OCR on the same frame are one vote when they match, and **no vote** when they contradict (v2 often reads 60 as 30 and 30 as 50; a matching wrong OCR must not lock that in). A class-only hit below 0.70 does not vote. OCR-only (the second look) is one vote. `sl_unreadable` and `neg_*` never become an mph; `sl_unreadable` may schedule the OCR second look, and any speed-sign class ≥ 0.15 schedules the YOLO burst instead. The two-read window is **12 s**. Route 00000181 had five one-off class reads (45@0.60, 45@0.77, 30@0.75, 45@0.89, 30@0.81) and none had a second agreeing read inside 12 s, so the plate stayed dark under the old two-read rule. Route 0000017e stayed at mph 0 because CLANG plus a false model-skip stretched the gap to ~40 s, longer than the window. A slower infer can still miss a sign. That is a miss, not a wrong plate. + +Every finished read logs a greppable line: + +``` +speedsignd timing read_interval_ms=17200 infer_ms=4300 cpu_share=0.250 threads=1 engaged=1 backoff=0 reason=pace +``` + +`read_interval_ms` is the gap between read starts. On a ~4.3 s infer it should sit near **4× `infer_ms`** (about 17200), and `cpu_share` near **0.250** or lower. `threads=1`. `engaged=1` while openpilot is controlling. `reason=pace` is the duty cycle. `reason=model-drop`, `model-skip`, or `cpu-budget` means it rested early. A back-off is: + +``` +speedsignd timing backoff=1 reason=model-lag extra_ms=3980 infer_ms=3980 engaged=1 +``` + +A 15 s summary still prints `speedsignd timing hz=… infer_ms mean=… max=… n=… skip=… engaged=…`. If TAKE CONTROL / “driving model is lagging” / Communication Issue comes back, Logger Off. The same `speedsignd timing` lines show whether detect was running. + +## Install weights on the 3X + +No large weights in git (~12 MB ONNX). Same idea as the OSM map pack: fetch onto `/data` with a SHA-256 check. A new sha replaces the file at the same path. The old v1 weights must not stay. + +On the 3X (parked / Force Offroad, Wi-Fi): **Settings → NAP → Install weights** → Start. That downloads both files. Settings shows **Speed Sign Weights: Installed**, **Out of date**, or **Missing**, and **runtime onnxruntime 1.31.0** or **runtime missing**. **Out of date** means the ONNX is present but the sha is not v2 — tap Install weights again; the download replaces it. **runtime missing** means the wheel is not importable yet — the same button installs it; the onroad plate shows **NO RT** (NO WT still wins when the ONNX itself is missing). Progress and errors stay on that runner screen (does not block the rest of the UI, does not reboot). speedsignd will not load a mismatched sha (the plate stays **NO WT** until the file matches). + +Or SSH: + +```bash +python -m scripts.nap.install_speed_sign_weights +``` + +That downloads GitHub Release `speed-sign-onnx-v2` / `speed_sign.onnx` and writes: + +| | | +|---|---| +| ONNX path | `/data/media/0/nap/speed_sign.onnx` | +| Runtime path | `/data/media/0/nap/pylib` (unzipped wheel, not the system venv) | +| Override | env `NAP_SPEED_SIGN_ONNX` or `--out`; pylib via `NAP_SPEED_SIGN_PYLIB` | +| ONNX SHA-256 | `1131200b7fe2d400596e09d7680fc3a26a08dcd8952acfdf261170bdb22d3d28` | +| Runtime | onnxruntime `1.31.0` `cp312` `manylinux_2_28_aarch64`, 21420804 bytes | +| Runtime SHA-256 | `35758d7606d578ec5b9d65f6e8a1f488013194c3f6097038a3223cb26d35ef9a` | + +If the Release asset is not up yet, export once on a PC (needs `pip install ultralytics onnx`), then copy: + +```bash +# PC +python -m scripts.nap.export_speed_sign_onnx --out ./speed_sign.onnx +scp ./speed_sign.onnx comma@:/tmp/speed_sign.onnx + +# 3X +python -m scripts.nap.install_speed_sign_weights /tmp/speed_sign.onnx +``` + +Or pass `--url` at a local `file://` / HTTP path. `--sha256 ''` skips the digest (local experiments only). + +Shipped detector: GitHub Release `speed-sign-onnx-v2`, file `speed_sign.onnx`, YOLOv8n, imgsz 320, opset 12, input `images` 1×3×320×320, output `[1, 17, 2100]`. Classes, in order: `sl_25`, `sl_30`, `sl_35`, `sl_40`, `sl_45`, `sl_50`, `sl_55`, `sl_60`, `sl_65`, `sl_70`, `sl_unreadable`, `neg_yellow`, `neg_other`. SHA-256 `1131200b7fe2d400596e09d7680fc3a26a08dcd8952acfdf261170bdb22d3d28`, 12658953 bytes. Runtime: pinned CPU wheel `onnxruntime-1.31.0-cp312-cp312-manylinux_2_28_aarch64.whl` (SHA-256 `35758d7606d578ec5b9d65f6e8a1f488013194c3f6097038a3223cb26d35ef9a`, 21420804 bytes), unzipped into `/data/media/0/nap/pylib` and imported via `sys.path` when the system package is absent. The ELF is AArch64, needs only glibc 2.28 (AGNOS 18.4 is newer), and does not link CUDA. Else `cv2.dnn` on the CPU target when the image has `readNetFromONNX` (this 3X does not), else tinygrad `OnnxRunner` on `DEV=CPU` / CLANG with GPU and QCOM off and the kernel cache under `/data`. The startup log names which one loaded. After Install weights the 3X path is `onnxruntime-cpu`. `tinygrad-clang` is the slow fallback and must not compile while engaged. + +## What Justin should see + +After weights are installed and the logger is **On**, **drive manually** (do not engage openpilot). Pass a **clear, unobstructed MUTCD R2-1** (white SPEED LIMIT plate) in daylight — e.g. a roadside **55** or **60**. Moving is the intended path. Parked / Force Offroad is not required to detect. + +- SIGN shows the mph **while engaged**. It does not show **WAIT** just because openpilot is controlling. A blank plate on a clear sign is a miss, not a pause (report `swaglog | grep "speedsignd timing"`). +- After two reads agree (the OCR second look is the next frame or two, not the next YOLO), a large opaque **SIGN** plate appears with that mph on the **left** (driver) side of the onroad UI. +- **Yes** / **No** (“is this accurate?”) sit under the plate on 3X (beside it on comma 4). They are **stubs** right now — they do not change cruise, HUD MAX, or map speed. Later, Yes may confirm the marker (JSONL + optional OSM); No may discard a wrong read. +- It holds **~45 s** after the last accepted detection (the old **3.0 s** hold blanked between multi-second infers), then hides (Yes/No hide with it). +- A JSONL row is appended only with a live GNSS fix (same mph near the last write is skipped ~8 s / ~40 m). +- HUD **MAX** / cruise / OSM LIMIT do not change. + +If the plate never appears, see **SIGN never lights** below. + +## Log path + +| | | +|---|---| +| Device | `/data/media/0/nap/speed_signs.jsonl` | +| PC / tests | `~/.comma/media/0/nap/speed_signs.jsonl` | +| Override | env `NAP_SPEED_SIGN_LOG` | + +One JSON object per line: + +```json +{"t":1710000000.12,"lat":45.315,"lon":-95.601,"bearing":87.2,"mph":45,"conf":0.81} +``` + +| Field | Meaning | +|---|---| +| `t` | Unix time (seconds) | +| `lat`, `lon` | GNSS fix used for the row | +| `bearing` | GNSS bearing (deg), or `null` | +| `mph` | MUTCD posted integer (5–85 step 5, or 100) | +| `conf` | Detector confidence 0–1 | + +A row is written only with a live GNSS fix. The on-road HUD still updates from every **confirmed** detection (cereal `liveSpeedSignNAP`), including without GPS. + +Pull the log off the device: + +```bash +scp comma@:/data/media/0/nap/speed_signs.jsonl . +``` + +## On-road HUD + +When the logger is **On**, a large opaque **SIGN** plate shows the mph the camera is reading. Display-only — it does not change MAX or cruise. + +| | | +|---|---| +| Where (3X) | Left / driver side, below the MAX box. Large plate (200×248). | +| Where (comma 4) | Left / driver side (top-left), same idea | +| Yes / No | Shown only with a live mph. 3X: stacked under the plate (full-width, ~112 px tall). comma 4: beside the plate. **No-op stubs** (cloudlog debug only). | +| Confirm | **2** reads of the same mph from **different frames**, inside **12 s**, or **one** read ≥ **0.70** on a real limit (5–85, step 5) unless a different limit arrives within **3 s**. Class and OCR on one frame are one vote when they match, and no vote when they contradict. Class-only below 0.70 does not vote. JSONL still uses the two-read rule, conf ≥ **0.40**. | +| Hold | **~45 s** after the last accepted detection (old hold was **3.0 s**), then it hides | +| Detect rate | Default **1 Hz** while engaged and while manual (env `NAP_SPEED_SIGN_HZ`, clamped 0.2–4), including while moving. A long infer idles 3× that infer. SubMaster **20 Hz**. | +| Engaged plate | The mph, not **WAIT**. YOLO keeps running. | +| Source | cereal `liveSpeedSignNAP` (not the JSONL file) | + +White MUTCD-style plate, black digits, red border, **SIGN** label so it is not confused with HUD MAX or OSM LIMIT. + +If the logger is On and ONNX failed to load, the same left-side plate shows **NO WT** (not a mph) — **no Yes/No**. If the ONNX is installed and the CPU runtime is not, the plate shows **NO RT** and Settings says **runtime missing** — tap Install weights again (it installs the runtime too). If the logger is On and openpilot is **controlling**, the plate still shows the mph when a sign is read — detect is not paused. A blank plate with weights Installed and the runtime present means no confirmed detection yet — that is normal. Report `swaglog | grep "speedsignd timing"` if reads are many seconds apart or `engaged=0` for the whole drive. `threads=` must be 1. `os_threads=` is the whole process. + +Yes/No do not write params, JSONL, or sqlite in this revision. The hook is `on_confirm_accuracy(mph, yes)` — future work may JSONL-confirm a good read and optionally push the marker to OSM. + +## SIGN never lights + +Speed Sign Logger On, onroad, but SIGN stays dark or never shows mph — almost always missing weights, not a bad model. + +1. Look at the onroad plate: **NO WT** means `/data/media/0/nap/speed_sign.onnx` is absent or failed to load. Settings → NAP → Speed Sign Weights should say **Missing**. **NO RT** means the ONNX is present and the CPU runtime is not — Settings says **runtime missing**. +2. Park or turn on Force Offroad. Tap **Install weights** (Wi-Fi). That installs the ONNX and the runtime. Wait for the runner to finish — do not leave it spinning forever; an error prints on that screen. Or SSH: `python -m scripts.nap.install_speed_sign_weights`. +3. ONNX should be ~12 MB (12658953 bytes). `ls -l /data/media/0/nap/speed_sign.onnx`. Runtime: `ls /data/media/0/nap/pylib/onnxruntime`. Settings should flip to **Installed** and must not say **runtime missing**. **Out of date** means the old ONNX is still there — run Install weights again. +4. No full reboot required: speedsignd retries ONNX every ~15 s. `swaglog` should show `speedsignd starting … backend=onnxruntime-cpu` (also `threads=1`, `os_threads=`, `hz=` / `nice=19`). Leave Logger On while disengaged until that first session finishes, then engage. A boot that is already engaged waits (`reason=compile-wait`) and does not run the multi-minute CLANG compile. +5. Engage or stay manual. Pass a clear, unobstructed MUTCD R2-1. Two agreeing reads, or one read ≥ 0.70, light SIGN while **controlling**. `swaglog | grep "speedsignd timing"` should show `backend=onnxruntime-cpu`, `engaged=1`, `threads=1`, `os_threads=`, `cpu_share` at or under `0.250`, and `read_interval_ms` about 4× `infer_ms` (about 2500 when infer is ~627 ms; `reason=burst` is a short back-to-back confirm). A blank plate with weights Installed and the runtime present means no detection yet (night, glare, tiny sign — see Accuracy limits). + +Do not treat a blank plate as “the detector is running.” Blank + Installed = no confirmed sign. **WAIT** is not the engaged state. Blank + Missing / **NO WT** = install weights. + +If you see **TAKE CONTROL IMMEDIATELY** or “Communication Issue Between Processes,” turn **Speed Sign Logger Off** and use **nap-release**. + +## Accuracy limits (honest) + +This is a small CPU detector at **1 Hz** (was 4 Hz) on two native right-side tiles (628×320 at y=520 and 640×320 at y=260), including while **controlling**. It is **not** a modeld head and is **not** used for control. It must not starve `modeld`: little core 2, SCHED_IDLE or nice 19, 1 thread, idle at least 3× each infer, and a back-off when `modelV2` drops frames, skips a frame id, or `modelExecutionTime` is above 50 ms, or this process's own CPU share goes over 25%. modeld stays FIFO on core 7; controlsd stays on core 4. `swaglog` logs `speedsignd detect paused/running` with `enabled` / `active` / `state` / alive / valid on those edges and every infer `backend=` `peak=` `refine=` `luma=` `chroma=` `prep=` `sess=` `raw=` plus `speedsignd timing read_interval_ms=… infer_ms=… cpu_share=… threads=… backend=… engaged=… backoff=… reason=…`. Offline val on this window: 105 hits, 52 misreads, 58 misses (30/35/60 read as 50, 30 read as 45). Held-out route 17a: 5 hits, 39 misreads (60 as 30 twenty-one times, 30 as 50 seventeen times), 7 misses. `YOLO_MIN_CONF` stays **0.40**. Two different frames must agree, and a class/OCR contradiction does not vote, so those misreads miss instead of lighting. If both frames are wrong the same way, the plate can still be wrong. + +**Usually works:** daylight, dry, a standard white R2-1 facing the car, large enough in the ROAD frame (near / mid roadside, not a speck on the horizon). 55 and 60 are in the trained class set. + +**Often misses or misreads:** + +- Night, rain, snow, heavy shadow, glare / washout, dirty lens +- Temporary orange / work-zone plaques, electronic VMS, banner-style overlays +- Metric (km/h) plates, yellow advisory plaques, school-zone assemblies when the number is secondary +- Strong perspective (sign almost edge-on), motion blur at high speed, occlusion (trees, trucks) +- Far freeway signs that occupy only a few pixels after the 320² letterbox +- 25 vs 35 vs 55 confusion when the glyph is tiny or partly clipped (similar white plates) +- Non-MUTCD artwork, stickers, or a sign not in the LISA/Roboflow mix + +Empty road / sky is quiet at the 0.40 threshold (the model’s background scores are ~0). Debounce exists to kill single-frame flashes, not to invent detections in the dark. + +Bring-your-own ONNX is still accepted if it matches the YOLO layout above or the older `[N,6] = x,y,w,h,mph,conf` custom layout. + +## What this does not do + +- No sqlite writes (OSM map speed is unchanged) +- No cruise / `vCruise` / HUD MAX overlay +- No osm.org / Overpass +- No modeld / `modelV2` head +- The SIGN plate is display-only (same process; not a second controller) +- Yes/No accuracy buttons are display-only stubs (no JSONL confirm, no OSM upload) diff --git a/docs/CARS.md b/docs/CARS.md index e4813eb1d929ef..89d583f363f8a8 100644 --- a/docs/CARS.md +++ b/docs/CARS.md @@ -4,312 +4,363 @@ A supported vehicle is one that just works when you install a comma device. All supported cars provide a better experience than any stock system. Supported vehicles reference the US market unless otherwise specified. -# 287 Supported Cars +# 334 Supported Cars -|Make|Model|Supported Package|ACC|No ACC accel below|No ALC below|Steering Torque|Resume from stop|Hardware Needed
 |Video| -|---|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:| -|Acura|ILX 2016-19|AcuraWatch Plus|openpilot|26 mph|25 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Acura|RDX 2016-18|AcuraWatch Plus|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Acura|RDX 2019-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Audi|A3 2014-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Audi|A3 Sportback e-tron 2017-18|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Audi|Q2 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Audi|Q3 2019-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Audi|RS3 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Audi|S3 2015-17|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chevrolet|Bolt EUV 2022-23|Premier or Premier Redline Trim without Super Cruise Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chevrolet|Bolt EV 2022-23|2LT Trim with Adaptive Cruise Control Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chevrolet|Equinox 2019-22|Adaptive Cruise Control (ACC)|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chevrolet|Silverado 1500 2020-21|Safety Package II|openpilot available[1](#footnotes)|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chevrolet|Trailblazer 2021-22|Adaptive Cruise Control (ACC)|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chrysler|Pacifica 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chrysler|Pacifica 2019-20|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chrysler|Pacifica 2021-23|All|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chrysler|Pacifica Hybrid 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Chrysler|Pacifica Hybrid 2019-24|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|comma|body|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|None|| -|CUPRA|Ateca 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Dodge|Durango 2020-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Bronco Sport 2021-23|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Escape 2020-22|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Escape Hybrid 2020-22|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Escape Plug-in Hybrid 2020-22|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Explorer 2020-23|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Explorer Hybrid 2020-23|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Focus 2018[3](#footnotes)|Adaptive Cruise Control with Lane Centering|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Focus Hybrid 2018[3](#footnotes)|Adaptive Cruise Control with Lane Centering|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Kuga 2020-22|Adaptive Cruise Control with Lane Centering|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Kuga Hybrid 2020-22|Adaptive Cruise Control with Lane Centering|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Kuga Plug-in Hybrid 2020-22|Adaptive Cruise Control with Lane Centering|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Maverick 2022|LARIAT Luxury|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Maverick 2023-24|Co-Pilot360 Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Maverick Hybrid 2022|LARIAT Luxury|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ford|Maverick Hybrid 2023-24|Co-Pilot360 Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|G70 2018|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|G70 2019-21|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|G70 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|G80 2017|All|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai J connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|G80 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|G90 2017-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|GV60 (Advanced Trim) 2023[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|GV60 (Performance Trim) 2023[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|GV70 (2.5T Trim, without HDA II) 2022-23[5](#footnotes)|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|GV70 (3.5T Trim, without HDA II) 2022-23[5](#footnotes)|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai M connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Genesis|GV80 2023[5](#footnotes)|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai M connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|GMC|Sierra 1500 2020-21|Driver Alert Package II|openpilot available[1](#footnotes)|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Accord 2018-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Accord Hybrid 2018-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Civic 2016-18|Honda Sensing|openpilot|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Civic 2019-21|All|openpilot available[1](#footnotes)|0 mph|2 mph[4](#footnotes)|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Civic 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Civic Hatchback 2017-21|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Civic Hatchback 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|CR-V 2015-16|Touring Trim|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|CR-V 2017-22|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|CR-V Hybrid 2017-21|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|e 2020|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Fit 2018-20|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Freed 2020|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|HR-V 2019-22|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|HR-V 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Insight 2019-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Inspire 2018|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Odyssey 2018-20|Honda Sensing|openpilot|26 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Passport 2019-23|All|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Pilot 2016-22|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Honda|Ridgeline 2017-24|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Azera 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Azera Hybrid 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Azera Hybrid 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Custin 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Elantra 2017-18|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai B connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Elantra 2019|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai G connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Elantra 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Elantra GT 2017-19|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Elantra Hybrid 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Genesis 2015-16|Smart Cruise Control (SCC)|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai J connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|i30 2017-19|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq 5 (Non-US only) 2022-24[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq 5 (with HDA II) 2022-24[5](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq 5 (without HDA II) 2022-24[5](#footnotes)|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq 6 (with HDA II) 2023-24[5](#footnotes)|Highway Driving Assist II|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq Electric 2019|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq Electric 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq Hybrid 2017-19|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq Hybrid 2020-22|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq Plug-in Hybrid 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Ioniq Plug-in Hybrid 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Kona 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai B connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Kona Electric 2018-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai G connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Kona Electric 2022-23|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai O connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Kona Electric (with HDA II, Korea only) 2023[5](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai R connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Kona Hybrid 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai I connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Palisade 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Santa Cruz 2022-24[5](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Santa Fe 2019-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Santa Fe 2021-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Santa Fe Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Santa Fe Plug-in Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Sonata 2018-19|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Sonata 2020-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Sonata Hybrid 2020-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Staria 2023[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Tucson 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai L connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Tucson 2022[5](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Tucson 2023-24[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Tucson Diesel 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Tucson Hybrid 2022-24[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Tucson Plug-in Hybrid 2024[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Hyundai|Veloster 2019-20|Smart Cruise Control (SCC)|Stock|5 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai E connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Jeep|Grand Cherokee 2016-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Jeep|Grand Cherokee 2019-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Carnival 2022-24[5](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Carnival (China only) 2023[5](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Ceed 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|EV6 (Non-US only) 2022-24[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|EV6 (with HDA II) 2022-24[5](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|EV6 (without HDA II) 2022-24[5](#footnotes)|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Forte 2019-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai G connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Forte 2022-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|K5 2021-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|K5 Hybrid 2020-22|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|K8 Hybrid (with HDA II) 2023[5](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro EV 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro EV 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro EV 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro EV 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro EV 2023[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro Hybrid 2018|All|Stock|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro Hybrid 2023[5](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro Plug-in Hybrid 2018-19|All|Stock|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro Plug-in Hybrid 2020|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro Plug-in Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Niro Plug-in Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Optima 2017|Advanced Smart Cruise Control|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai B connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Optima 2019-20|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai G connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Optima Hybrid 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Seltos 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Sorento 2018|Advanced Smart Cruise Control & LKAS|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Sorento 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Sorento 2021-23[5](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Sorento Hybrid 2021-23[5](#footnotes)|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Sorento Plug-in Hybrid 2022-23[5](#footnotes)|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Sportage 2023-24[5](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Sportage Hybrid 2023[5](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Stinger 2018-20|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Stinger 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Kia|Telluride 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|CT Hybrid 2017-18|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|ES 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|ES 2019-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|ES Hybrid 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|ES Hybrid 2019-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|GS F 2016|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|IS 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|IS 2022-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|LC 2024|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|NX 2018-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|NX 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|NX Hybrid 2018-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|NX Hybrid 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|RC 2018-20|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|RX 2016|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|RX 2017-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|RX 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|RX Hybrid 2016|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|RX Hybrid 2017-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|RX Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lexus|UX Hybrid 2019-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lincoln|Aviator 2020-23|Co-Pilot360 Plus|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Lincoln|Aviator Plug-in Hybrid 2020-23|Co-Pilot360 Plus|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|MAN|eTGE 2020-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|MAN|TGE 2017-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Mazda|CX-5 2022-24|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Mazda connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Mazda|CX-9 2021-23|All|Stock|0 mph|28 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Mazda connector
- 1 RJ45 cable (7 ft)
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Nissan|Altima 2019-20|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan B connector
- 1 RJ45 cable (7 ft)
- 1 USB-C coupler
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Nissan|Leaf 2018-23|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 RJ45 cable (7 ft)
- 1 USB-C coupler
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Nissan|Rogue 2018-20|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 RJ45 cable (7 ft)
- 1 USB-C coupler
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Nissan|X-Trail 2017|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 RJ45 cable (7 ft)
- 1 USB-C coupler
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Ram|1500 2019-24|Adaptive Cruise Control (ACC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Ram connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|SEAT|Ateca 2016-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|SEAT|Leon 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Subaru|Ascent 2019-21|All[6](#footnotes)|openpilot available[1,7](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|Crosstrek 2018-19|EyeSight Driver Assistance[6](#footnotes)|openpilot available[1,7](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|Crosstrek 2020-23|EyeSight Driver Assistance[6](#footnotes)|openpilot available[1,7](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|Forester 2019-21|All[6](#footnotes)|openpilot available[1,7](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|Impreza 2017-19|EyeSight Driver Assistance[6](#footnotes)|openpilot available[1,7](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|Impreza 2020-22|EyeSight Driver Assistance[6](#footnotes)|openpilot available[1,7](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|Legacy 2020-22|All[6](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru B connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|Outback 2020-22|All[6](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru B connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|XV 2018-19|EyeSight Driver Assistance[6](#footnotes)|openpilot available[1,7](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Subaru|XV 2020-21|EyeSight Driver Assistance[6](#footnotes)|openpilot available[1,7](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
|| -|Škoda|Fabia 2022-23[11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[13](#footnotes)|| -|Škoda|Kamiq 2021-23[9,11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[13](#footnotes)|| -|Škoda|Karoq 2019-23[11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Škoda|Kodiaq 2017-23[11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Škoda|Octavia 2015-19[11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Škoda|Octavia RS 2016[11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Škoda|Octavia Scout 2017-19[11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Škoda|Scala 2020-23[11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[13](#footnotes)|| -|Škoda|Superb 2015-22[11](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Alphard 2019-20|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Alphard Hybrid 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Avalon 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Avalon 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Avalon 2019-21|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Avalon 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Avalon Hybrid 2019-21|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Avalon Hybrid 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|C-HR 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|C-HR 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|C-HR Hybrid 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|C-HR Hybrid 2021-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Camry 2018-20|All|Stock|0 mph[8](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Camry 2021-24|All|openpilot|0 mph[8](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Camry Hybrid 2018-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Camry Hybrid 2021-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Corolla 2017-19|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Corolla 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Corolla Cross (Non-US only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Corolla Cross Hybrid (Non-US only) 2020-22|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Corolla Hatchback 2019-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Corolla Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Corolla Hybrid (South America only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Highlander 2017-19|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Highlander 2020-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Highlander Hybrid 2017-19|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Highlander Hybrid 2020-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Mirai 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Prius 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Prius 2017-20|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Prius 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Prius Prime 2017-20|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Prius Prime 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Prius v 2017|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 2023-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 Hybrid 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 Hybrid 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 Hybrid 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 Hybrid 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|RAV4 Hybrid 2023-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Toyota|Sienna 2018-20|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 RJ45 cable (7 ft)
- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v2
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Arteon 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Arteon eHybrid 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Arteon R 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Arteon Shooting Brake 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Atlas 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Atlas Cross Sport 2020-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|California 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Caravelle 2020|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|CC 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Crafter 2017-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|e-Crafter 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|e-Golf 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Golf 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Golf Alltrack 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Golf GTD 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Golf GTE 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Golf GTI 2015-21|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Golf R 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Golf SportsVan 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Grand California 2019-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Jetta 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Jetta GLI 2021-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Passat 2015-22[10](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Passat Alltrack 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Passat GTE 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Polo 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[13](#footnotes)|| -|Volkswagen|Polo GTI 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[13](#footnotes)|| -|Volkswagen|T-Cross 2021|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[13](#footnotes)|| -|Volkswagen|T-Roc 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Taos 2022-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Teramont 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Teramont Cross Sport 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Teramont X 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Tiguan 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Tiguan eHybrid 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| -|Volkswagen|Touran 2016-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,12](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
|| +|Make|Model|Supported Package|ACC|No ACC accel below|No ALC below|Steering Torque|Resume from stop|Hardware Needed
 |Video|Setup Video| +|---|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| +|Acura|ILX 2016-18|Technology Plus Package or AcuraWatch Plus|openpilot|26 mph|25 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|ILX 2019|All|openpilot|26 mph|25 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|MDX 2022-24|All|openpilot available[1,5](#footnotes)|0 mph|43 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|MDX 2025-26|All except Type S|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|RDX 2016-18|AcuraWatch Plus or Advance Package|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|RDX 2019-21|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|TLX 2021-22|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|TLX 2025|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|A3 2014-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|A3 Sportback e-tron 2017-18|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|Q2 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|Q3 2019-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|RS3 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|S3 2015-17|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Chevrolet|Bolt EUV 2022-23|Premier or Premier Redline Trim, without Super Cruise Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chevrolet|Bolt EV 2022-23|2LT Trim with Adaptive Cruise Control Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chevrolet|Equinox 2019-22|Adaptive Cruise Control (ACC)|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chevrolet|Silverado 1500 2020-21|Safety Package II|openpilot available[1](#footnotes)|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chevrolet|Trailblazer 2021-22|Adaptive Cruise Control (ACC)|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica 2019-20|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica 2021-23|All|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica Hybrid 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica Hybrid 2019-25|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|comma|body|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|None||| +|CUPRA[12](#footnotes)|Ateca 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Dodge|Durango 2020-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Bronco Sport 2021-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Escape 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Escape 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Escape Hybrid 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Escape Hybrid 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Escape Plug-in Hybrid 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Escape Plug-in Hybrid 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Expedition 2022-24|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Explorer 2020-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Explorer Hybrid 2020-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|F-150 2021-23|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|F-150 Hybrid 2021-23|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Focus 2018[2](#footnotes)|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Focus Hybrid 2018[2](#footnotes)|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Kuga 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Kuga Hybrid 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Kuga Hybrid 2024|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Kuga Plug-in Hybrid 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Kuga Plug-in Hybrid 2024|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Maverick 2022|LARIAT Luxury|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Maverick 2023-24|Co-Pilot360 Assist|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Maverick Hybrid 2022|LARIAT Luxury|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Maverick Hybrid 2023-24|Co-Pilot360 Assist|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Mustang Mach-E 2021-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Ranger 2024|Adaptive Cruise Control with Lane Centering|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Genesis|G70 2018|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G70 2019-21|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G70 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G80 2017|All|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai J connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G80 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G80 (2.5T Advanced Trim, with HDA II) 2024|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G90 2017-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV60 (Advanced Trim) 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV60 (Performance Trim) 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV70 (2.5T Trim, without HDA II) 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV70 (3.5T Trim, without HDA II) 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai M connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV70 Electrified (Australia Only) 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV70 Electrified (with HDA II) 2023-24|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV80 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai M connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|GMC|Sierra 1500 2020-21|Driver Alert Package II|openpilot available[1](#footnotes)|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Accord 2018-22|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Accord 2023-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Accord Hybrid 2018-22|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Accord Hybrid 2023-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|City (Brazil only) 2023|All|openpilot available[1,5](#footnotes)|0 mph|14 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic 2016-18|Honda Sensing|openpilot|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic 2019-21|All|openpilot available[1,5](#footnotes)|0 mph|2 mph[4](#footnotes)|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic 2022-24|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback 2017-18|Honda Sensing|openpilot available[1,5](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback 2019-21|All|openpilot available[1,5](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback 2022-24|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback Hybrid 2025-26|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback Hybrid (Europe only) 2023|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hybrid 2025-26|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V 2015-16|Touring Trim|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V 2017-22|Honda Sensing|openpilot available[1,5](#footnotes)|0 mph|15 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V 2023-26|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V Hybrid 2017-22|Honda Sensing|openpilot available[1,5](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V Hybrid 2023-26|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|e 2020|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Fit 2018-20|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Freed 2020|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|HR-V 2019-22|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|HR-V 2023-25|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Insight 2019-22|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Inspire 2018|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|N-Box 2018|All|openpilot available[1,5](#footnotes)|0 mph|11 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Odyssey 2018-20|Honda Sensing|openpilot|26 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Odyssey 2021-26|All|openpilot available[1,5](#footnotes)|0 mph|43 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Odyssey (Singapore) 2021|Honda Sensing|openpilot|19 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Odyssey (Taiwan) 2018-19|Honda Sensing|openpilot|19 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Passport 2019-25|All|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Passport 2026|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Pilot 2016-22|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Pilot 2023-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Ridgeline 2017-25|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Azera 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Azera Hybrid 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Azera Hybrid 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Custin 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra 2017-18|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra 2019|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai G connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra GT 2017-20|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra Hybrid 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Genesis 2015-16|Smart Cruise Control (SCC)|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai J connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|i30 2017-19|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 5 (Southeast Asia and Europe only) 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 5 (with HDA II) 2022-24|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 5 (without HDA II) 2022-24|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 6 (with HDA II) 2023-24|Highway Driving Assist II|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 6 (without HDA II) 2023-24|Highway Driving Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Electric 2019|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Electric 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Hybrid 2017-19|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Hybrid 2020-22|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Plug-in Hybrid 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Plug-in Hybrid 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona Electric 2018-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai G connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona Electric 2022-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai O connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona Electric (with HDA II, Korea only) 2023|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai R connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona Hybrid 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai I connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Nexo 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Palisade 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Cruz 2022-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Fe 2019-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Fe 2021-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Fe Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Fe Plug-in Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Sonata 2018-19|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Sonata 2020-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Sonata Hybrid 2020-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Staria 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson 2023-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson Diesel 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson Hybrid 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson Plug-in Hybrid 2024|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Veloster 2019-20|Smart Cruise Control (SCC)|Stock|5 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Jeep|Grand Cherokee 2016-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Jeep|Grand Cherokee 2019-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Carnival 2022-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Carnival (China only) 2023|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Ceed 2019-21|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|EV6 (Southeast Asia only) 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|EV6 (with HDA II) 2022-24|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|EV6 (without HDA II) 2022-24|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Forte 2019-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai G connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Forte 2022-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|K5 2021-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|K5 Hybrid 2020-22|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|K7 2017|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|K8 Hybrid (with HDA II) 2023|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV (with HDA II) 2024-25|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai R connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV (without HDA II) 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Hybrid 2018|Smart Cruise Control (SCC)|Stock|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Hybrid 2023-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Plug-in Hybrid 2018-19|All|Stock|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Plug-in Hybrid 2020|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Plug-in Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Plug-in Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Optima 2017|Advanced Smart Cruise Control|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Optima 2019-20|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai G connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Optima Hybrid 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Seltos 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento 2018|Advanced Smart Cruise Control & LKAS|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento Hybrid 2021-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento Plug-in Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sportage 2023-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sportage Hybrid 2023|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Stinger 2018-20|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Stinger 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Telluride 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|CT Hybrid 2017-18|Lexus Safety System+|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|ES 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|ES 2019-25|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|ES Hybrid 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|ES Hybrid 2019-25|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|GS F 2016|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|IS 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|IS 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|LC 2024-25|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|LS 2018|All except Lexus Safety System+ A|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|NX 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|NX 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|NX Hybrid 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|NX Hybrid 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RC 2018-20|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RC 2023|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX 2016|Lexus Safety System+|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX 2017-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX Hybrid 2016|Lexus Safety System+|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX Hybrid 2017-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|UX Hybrid 2019-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lincoln|Aviator 2020-24|Co-Pilot360 Plus|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lincoln|Aviator Plug-in Hybrid 2020-24|Co-Pilot360 Plus|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|MAN[12](#footnotes)|eTGE 2020-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|MAN[12](#footnotes)|TGE 2017-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Mazda|CX-5 2022-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Mazda connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Mazda|CX-9 2021-23|All|Stock|0 mph|28 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Mazda connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Nissan[6](#footnotes)|Altima 2019-24|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Nissan[6](#footnotes)|Leaf 2018-23|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Nissan[6](#footnotes)|Rogue 2018-20|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Nissan[6](#footnotes)|X-Trail 2017|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ram|1500 2019-24|Adaptive Cruise Control (ACC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Ram connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Rivian|R1S 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Rivian A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Rivian|R1S 2025|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Rivian B connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Rivian|R1T 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Rivian A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Rivian|R1T 2025|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Rivian B connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|SEAT[12](#footnotes)|Ateca 2016-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|SEAT[12](#footnotes)|Leon 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Subaru|Ascent 2019-21|All[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Crosstrek 2018-19|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Crosstrek 2020-23|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Forester 2019-21|All[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Impreza 2017-19|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Impreza 2020-22|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Legacy 2020-22|All[7](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru B connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Outback 2020-22|All[7](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru B connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|XV 2018-19|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|XV 2020-21|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Škoda|Fabia 2022-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Škoda|Kamiq 2021-23[13,15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Škoda[12](#footnotes)|Karoq 2019-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda[12](#footnotes)|Kodiaq 2017-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda[12](#footnotes)|Octavia 2015-19[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda[12](#footnotes)|Octavia RS 2016[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda[12](#footnotes)|Octavia Scout 2017-19[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda|Scala 2020-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Škoda[12](#footnotes)|Superb 2015-22[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Tesla[10](#footnotes)|Model 3 (with HW3) 2019-23[9](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Tesla A connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Tesla[10](#footnotes)|Model 3 (with HW4) 2024-25[9](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Tesla B connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Tesla[10](#footnotes)|Model Y (with HW3) 2020-23[9](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Tesla A connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Tesla[10](#footnotes)|Model Y (with HW4) 2024-25[9](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Tesla B connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Toyota|Alphard 2019-20|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Alphard Hybrid 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon 2016|Toyota Safety Sense P|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon 2019-21|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon Hybrid 2019-21|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon Hybrid 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|C-HR 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|C-HR 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|C-HR Hybrid 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|C-HR Hybrid 2021-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Camry 2018-20|All|Stock|0 mph[11](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Camry 2021-24|All|openpilot|0 mph[11](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Camry Hybrid 2018-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Camry Hybrid 2021-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Cross (Non-US only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Cross Hybrid (Non-US only) 2020-22|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Hatchback 2019-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Hybrid (South America only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Highlander 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Highlander 2020-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Highlander Hybrid 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Highlander Hybrid 2020-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Mirai 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius 2016|Toyota Safety Sense P|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius Prime 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius Prime 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius v 2017|Toyota Safety Sense P|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2016|Toyota Safety Sense P|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2016|Toyota Safety Sense P|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Sienna 2018-20|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Arteon 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Arteon eHybrid 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Arteon R 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Arteon Shooting Brake 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Atlas 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Atlas Cross Sport 2020-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|California 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Caravelle 2020|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|CC 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Crafter 2017-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|e-Crafter 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|e-Golf 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf Alltrack 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf GTD 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf GTE 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf GTI 2015-21|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf R 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf SportsVan 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Grand California 2019-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Jetta 2019-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Jetta GLI 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen|Passat 2015-22[14](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Passat Alltrack 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Passat GTE 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen|Polo 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Volkswagen|Polo GTI 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Volkswagen|T-Cross 2021|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Volkswagen[12](#footnotes)|T-Roc 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Taos 2022-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Teramont 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Teramont Cross Sport 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Teramont X 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Tiguan 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Tiguan eHybrid 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Touran 2016-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| ### Footnotes -1openpilot Longitudinal Control (Alpha) is available behind a toggle; the toggle is only available in non-release branches such as `devel` or `master-ci`.
-2By default, this car will use the stock Adaptive Cruise Control (ACC) for longitudinal control. If the Driver Support Unit (DSU) is disconnected, openpilot ACC will replace stock ACC. NOTE: disconnecting the DSU disables Automatic Emergency Braking (AEB).
-3Refers only to the Focus Mk4 (C519) available in Europe/China/Taiwan/Australasia, not the Focus Mk3 (C346) in North and South America/Southeast Asia.
+1openpilot Longitudinal Control (Alpha) is available behind a toggle; the toggle is only available in non-release branches such as `nightly-dev`.
+2Refers only to the Focus Mk4 (C519) available in Europe/China/Taiwan/Australasia, not the Focus Mk3 (C346) in North and South America/Southeast Asia.
+3See more setup details for GM.
42019 Honda Civic 1.6L Diesel Sedan does not have ALC below 12mph.
-5Requires a CAN FD panda kit if not using comma 3X for this CAN FD car.
-6In the non-US market, openpilot requires the car to come equipped with EyeSight with Lane Keep Assistance.
-7Enabling longitudinal control (alpha) will disable all EyeSight functionality, including AEB, LDW, and RAB.
-8openpilot operates above 28mph for Camry 4CYL L, 4CYL LE and 4CYL SE which don't have Full-Speed Range Dynamic Radar Cruise Control.
-9Not including the China market Kamiq, which is based on the (currently) unsupported PQ34 platform.
-10Refers only to the MQB-based European B8 Passat, not the NMS Passat in the USA/China/Mideast markets.
-11Some Škoda vehicles are equipped with heated windshields, which are known to block GPS signal needed for some comma 3X functionality.
-12Only available for vehicles using a gateway (J533) harness. At this time, vehicles using a camera harness are limited to using stock ACC.
-13Model-years 2022 and beyond may have a combined CAN gateway and BCM, which is supported by openpilot in software, but doesn't yet have a harness available from the comma store.
+5Enabling longitudinal control (alpha) will disable all CMBS functionality, including AEB and FCW.
+6See more setup details for Nissan.
+7In the non-US market, openpilot requires the car to come equipped with EyeSight with Lane Keep Assistance.
+8Enabling longitudinal control (alpha) will disable all EyeSight functionality, including AEB, LDW, and RAB.
+9Some 2023 model years have HW4. To check which hardware type your vehicle has, look for Autopilot computer under Software -> Additional Vehicle Information on your vehicle's touchscreen. See this page for more information.
+10See more setup details for Tesla.
+11openpilot operates above 28mph for Camry 4CYL L, 4CYL LE and 4CYL SE which don't have Full-Speed Range Dynamic Radar Cruise Control.
+12The J533 harness plugs in at the CAN gateway under the dashboard, just above the steering column. More information can be found at this guide.
+13Not including the China market Kamiq, which is based on the (currently) unsupported PQ34 platform.
+14Refers only to the MQB-based European B8 Passat, not the NMS Passat in the USA/China/Mideast markets.
+15Some Škoda vehicles are equipped with heated windshields, which are known to block GPS signal needed for some comma four functionality.
+16Only available for vehicles using a gateway (J533) harness. At this time, vehicles using a camera harness are limited to using stock ACC.
+17Model-years 2022 and beyond may have a combined CAN gateway and BCM, which is supported by openpilot in software, but doesn't yet have a harness available from the comma store.
## Community Maintained Cars Although they're not upstream, the community has openpilot running on other makes and models. See the 'Community Supported Models' section of each make [on our wiki](https://wiki.comma.ai/). @@ -327,7 +378,7 @@ If your car has the following packages or features, then it's a good candidate f | Make | Required Package/Features | | ---- | ------------------------- | -| Acura | Any car with AcuraWatch Plus will work. AcuraWatch Plus comes standard on many newer models. | +| Acura | Any car with AcuraWatch will work. AcuraWatch comes standard on many newer models. | | Ford | Any car with Lane Centering will likely work. | | Honda | Any car with Honda Sensing will work. Honda Sensing comes standard on many newer models. | | Subaru | Any car with EyeSight will work. EyeSight comes standard on many newer models. | diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index c66b20c88e2831..3d39420c01b18d 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -6,21 +6,20 @@ Development is coordinated through [Discord](https://discord.comma.ai) and GitHu ### Getting Started -* Setup your [development environment](../tools/) -* Read about the [development workflow](WORKFLOW.md) +* Set up your [development environment](/tools/) * Join our [Discord](https://discord.comma.ai) * Docs are at https://docs.comma.ai and https://blog.comma.ai ## What contributions are we looking for? **openpilot's priorities are [safety](SAFETY.md), stability, quality, and features, in that order.** -openpilot is part of comma's mission to *solve self-driving cars while delivering shippable intermediaries*, and all development is towards that goal. +openpilot is part of comma's mission to *solve self-driving cars while delivering shippable intermediaries*, and all development is towards that goal. ### What gets merged? The probability of a pull request being merged is a function of its value to the project and the effort it will take us to get it merged. If a PR offers *some* value but will take lots of time to get merged, it will be closed. -Simple, well-tested bug fixes are the easiest to merge, and new features are the hardest to get merged. +Simple, well-tested bug fixes are the easiest to merge, and new features are the hardest to get merged. All of these are examples of good PRs: * typo fix: https://github.com/commaai/openpilot/pull/30678 @@ -30,17 +29,17 @@ All of these are examples of good PRs: ### What doesn't get merged? -* **style changes**: code is art, and it's up to the author to make it beautiful +* **style changes**: code is art, and it's up to the author to make it beautiful * **500+ line PRs**: clean it up, break it up into smaller PRs, or both * **PRs without a clear goal**: every PR must have a singular and clear goal * **UI design**: we do not have a good review process for this yet * **New features**: We believe openpilot is mostly feature-complete, and the rest is a matter of refinement and fixing bugs. As a result of this, most feature PRs will be immediately closed, however the beauty of open source is that forks can and do offer features that upstream openpilot doesn't. -* **Negative expected value**: This a class of PRs that makes an improvement, but the risk or validation costs more than the improvement. The risk can be mitigated by first getting a failing test merged. +* **Negative expected value**: This is a class of PRs that makes an improvement, but the risk or validation costs more than the improvement. The risk can be mitigated by first getting a failing test merged. ### First contribution -[Bounties](https://comma.ai/bounties) are the best place to get started. -There's lot of bounties that don't require a comma 3/3X or a car. +[Projects / openpilot bounties](https://github.com/orgs/commaai/projects/26/views/1?pane=info) is the best place to get started and goes in-depth on what's expected when working on a bounty. +There are a lot of bounties that don't require a comma four or a car. ## Pull Requests @@ -63,3 +62,12 @@ A good pull request has all of the following: * Connect your device to Wi-Fi regularly, so that we can pull data for training better driving models. * Run the `nightly` branch and report issues. This branch is like `master` but it's built just like a release. * Annotate images in the [comma10k dataset](https://github.com/commaai/comma10k). + +## Contributing Training Data + +### A guide for forks + +In order for your fork's data to be eligible for the training set: +* **Your cereal messaging structs must be [compatible](../cereal#custom-forks)** +* **The definitions of all the stock messaging structs must not change**: Do not change how any of the fields are set, including everything from `selfdriveState.enabled` to `carState.steeringAngleDeg`. Instead, create your own structs and set them however you'd like. +* **Do not include cars that are not supported in upstream platforms**: Instead, create new opendbc platforms for cars that you'd like to support outside of upstream, even if it's just a trim-level difference. diff --git a/docs/DEBUGGING_SAFETY.md b/docs/DEBUGGING_SAFETY.md new file mode 100644 index 00000000000000..cd0a46b446c94b --- /dev/null +++ b/docs/DEBUGGING_SAFETY.md @@ -0,0 +1,30 @@ +# Debugging Panda Safety with Replay Drive + LLDB + +## 1. Start the debugger in VS Code + +* Select **Replay drive + Safety LLDB**. +* Enter the route or segment when prompted. +[](https://github.com/user-attachments/assets/b0cc320a-083e-46a7-a9f8-ca775bbe5604) + +## 2. Attach LLDB + +* When prompted, pick the running **`replay_drive` process**. +* ⚠️ Attach quickly, or `replay_drive` will start consuming messages. + +> [!TIP] +> Add a Python breakpoint at the start of `replay_drive.py` to pause execution and give yourself time to attach LLDB. + +## 3. Set breakpoints in VS Code +Breakpoints can be set directly in `modes/xxx.h` (or any C file). +No extra LLDB commands are required — just place breakpoints in the editor. + +## 4. Resume execution +Once attached, you can step through both Python (on the replay) and C safety code as CAN logs are replayed. + +> [!NOTE] +> * Use short routes for quicker iteration. +> * Pause `replay_drive` early to avoid wasting log messages. + +## Video + +View a demo of this workflow on the PR that added it: https://github.com/commaai/openpilot/pull/36055#issue-3352911578 \ No newline at end of file diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md new file mode 100644 index 00000000000000..e803a3fb8a36d6 --- /dev/null +++ b/docs/DEVELOPMENT.md @@ -0,0 +1,24 @@ +# Docs development + +The `docs/` tree is the source for [docs.comma.ai](https://docs.comma.ai). +The site is updated on pushes to master by this [workflow](../.github/workflows/docs.yaml). + +Those commands must be run in the root directory of openpilot, **not /docs** + +**1. Install the docs dependencies** +``` bash +uv pip install .[docs] +``` + +**2. Build the new site** +``` bash +docs build +``` + +**3. Run the new site locally** +``` bash +docs serve +``` + +References: +* https://zensical.org/docs/ diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 08dd4fa8bcca9b..00000000000000 --- a/docs/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# openpilot docs - -This is the source for [docs.comma.ai](https://docs.comma.ai). -The site is updated on pushes to master by this [workflow](../.github/workflows/docs.yaml). - -## Development -NOTE: Those commands must be run in the root directory of openpilot, **not /docs** - -**1. Install the docs dependencies** -``` bash -pip install .[docs] -``` - -**2. Build the new site** -``` bash -mkdocs build -``` - -**3. Run the new site locally** -``` bash -mkdocs serve -``` - -References: -* https://www.mkdocs.org/getting-started/ -* https://github.com/ntno/mkdocs-terminal diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 4b568728a7fd90..0a662ac6cd6136 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -4,8 +4,8 @@ openpilot is an Adaptive Cruise Control (ACC) and Automated Lane Centering (ALC) Like other ACC and ALC systems, openpilot is a failsafe passive system and it requires the driver to be alert and to pay attention at all times. -In order to enforce driver alertness, openpilot includes a driver monitoring feature -that alerts the driver when distracted. +To assist the driver in maintaining alertness, openpilot includes a driver monitoring feature +that alerts when it detects driver distraction. However, even with an attentive driver, we must make further efforts for the system to be safe. We repeat, **driver alertness is necessary, but not sufficient, for openpilot to be @@ -16,7 +16,7 @@ industry standards of safety for Level 2 Driver Assistance Systems. In particula ISO26262 guidelines, including those from [pertinent documents](https://www.nhtsa.gov/sites/nhtsa.dot.gov/files/documents/13498a_812_573_alcsystemreport.pdf) released by NHTSA. In addition, we impose strict coding guidelines (like [MISRA C : 2012](https://www.misra.org.uk/what-is-misra/)) on parts of openpilot that are safety relevant. We also perform software-in-the-loop, -hardware-in-the-loop and in-vehicle tests before each software release. +hardware-in-the-loop, and in-vehicle tests before each software release. Following Hazard and Risk Analysis and FMEA, at a very high level, we have designed openpilot ensuring two main safety requirements. @@ -25,12 +25,22 @@ ensuring two main safety requirements. by stepping on the brake pedal or by pressing the cancel button. 2. The vehicle must not alter its trajectory too quickly for the driver to safely react. This means that while the system is engaged, the actuators are constrained - to operate within reasonable limits[^1]. + to operate within reasonable limits[^1]. -For additional safety implementation details, refer to [panda safety model](https://github.com/commaai/panda#safety-model). For vehicle specific implementation of the safety concept, refer to [panda/board/safety/](https://github.com/commaai/panda/tree/master/board/safety). +For additional safety implementation details, refer to [panda safety model](https://github.com/commaai/panda#safety-model). For vehicle specific implementation of the safety concept, refer to [opendbc/safety/safety](https://github.com/commaai/opendbc/tree/master/opendbc/safety/safety). -**Extra note**: comma.ai strongly discourages the use of openpilot forks with safety code either missing or - not fully meeting the above requirements. +[^1]: For these actuator limits we observe ISO11270 and ISO15622. Lateral limits described there translate to 0.9 seconds of maximum actuation to achieve a 1m lateral deviation. -[^1]: For these actuator limits we observe ISO11270 and ISO15622. Lateral limits described there translate to 0.9 seconds of maximum actuation to achieve a 1m lateral deviation. +--- +### Forks of openpilot + +* Do not disable or nerf [driver monitoring](https://github.com/commaai/openpilot/tree/master/selfdrive/monitoring) +* Do not disable or nerf [excessive actuation checks](https://github.com/commaai/openpilot/tree/master/selfdrive/selfdrived/helpers.py) +* If your fork modifies any of the code in `opendbc/safety/`: + * your fork cannot use the openpilot trademark + * your fork must preserve the full [safety test suite](https://github.com/commaai/opendbc/tree/master/opendbc/safety/tests) and all tests must pass, including any new coverage required by the fork's changes + +Failure to comply with these standards will get you and your users banned from comma.ai servers. + +**comma.ai strongly discourages the use of openpilot forks with safety code either missing or not fully meeting the above requirements.** diff --git a/docs/WORKFLOW.md b/docs/WORKFLOW.md deleted file mode 100644 index 477c7511ca6a9c..00000000000000 --- a/docs/WORKFLOW.md +++ /dev/null @@ -1,43 +0,0 @@ -# openpilot development workflow - -Aside from the ML models, most tools used for openpilot development are in this repo. - -Most development happens on normal Ubuntu workstations, and not in cars or directly on comma devices. See the [setup guide](../tools) for getting your PC setup for openpilot development. - -## Quick start - -```bash -# get the latest stuff -git pull -git lfs pull -git submodule update --init --recursive - -# update dependencies -tools/ubuntu_setup.sh - -# build everything -scons -j$(nproc) - -# build just the ui with either of these -scons -j8 selfdrive/ui/ -cd selfdrive/ui/ && scons -u -j8 - -# test everything -pytest - -# test just logging services -cd system/loggerd && pytest . - -# run the linter -op lint -``` - -## Testing - -### Automated Testing - -All PRs and commits are automatically checked by GitHub Actions. Check out `.github/workflows/` for what GitHub Actions runs. Any new tests should be added to GitHub Actions. - -### Code Style and Linting - -Code is automatically checked for style by GitHub Actions as part of the automated tests. You can also run these tests yourself by running `pre-commit run --all`. diff --git a/docs/assets/comma-logo.png b/docs/assets/comma-logo.png new file mode 120000 index 00000000000000..2838d92bfb1975 --- /dev/null +++ b/docs/assets/comma-logo.png @@ -0,0 +1 @@ +../../selfdrive/assets/icons_mici/settings/comma_icon.png \ No newline at end of file diff --git a/docs/assets/three-back.svg b/docs/assets/three-back.svg new file mode 100644 index 00000000000000..4dfeeeb46a502a --- /dev/null +++ b/docs/assets/three-back.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a5245f9458982b608fee67fc689d899ca638a405ff62bf9db5e4978b177ef3e +size 121394 diff --git a/docs/car-porting/brand-port.md b/docs/car-porting/brand-port.md deleted file mode 100644 index a3daa7a84850f3..00000000000000 --- a/docs/car-porting/brand-port.md +++ /dev/null @@ -1,5 +0,0 @@ -# Developing a car brand port - -A brand port is a port of openpilot to a substantially new car brand or platform within a brand. - -Here's an example of one: https://github.com/commaai/openpilot/pull/23331. diff --git a/docs/car-porting/model-port.md b/docs/car-porting/model-port.md deleted file mode 100644 index e148a40ecb131b..00000000000000 --- a/docs/car-porting/model-port.md +++ /dev/null @@ -1,5 +0,0 @@ -# Developing a car model port - -A model port is a port of openpilot to a new car model within an already supported brand. Model ports are easier than brand ports because the car's existing APIs are already known. - -Here's an example of one: https://github.com/commaai/openpilot/pull/30672/. diff --git a/docs/car-porting/what-is-a-car-port.md b/docs/car-porting/what-is-a-car-port.md deleted file mode 100644 index 622fe9e75e8c81..00000000000000 --- a/docs/car-porting/what-is-a-car-port.md +++ /dev/null @@ -1,22 +0,0 @@ -# What is a car port? - -A car port enables openpilot support on a particular car. Each car model openpilot supports needs to be individually ported. All car ports live in `openpilot/selfdrive/car/car_specific.py` and `opendbc_repo/opendbc/car`. - -The complexity of a car port varies depending on many factors including: -* existing openpilot support for similar cars -* architecture and APIs available in the car - - -# Structure of a car port -* `interface.py`: Interface for the car, defines the CarInterface class -* `carstate.py`: Reads CAN from car and builds openpilot CarState message -* `carcontroller.py`: Builds CAN messages to send to car -* `values.py`: Limits for actuation, general constants for cars, and supported car documentation -* `radar_interface.py`: Interface for parsing radar points from the car - - -# Overiew - -[Jason Young](https://github.com/jyoung8607) gave a talk at COMMA_CON with an overview of the car porting process. The talk is available on YouTube: - -https://youtu.be/KcfzEHB6ms4?si=5szh1PX6TksOCKmM diff --git a/docs/concepts/glossary.md b/docs/concepts/glossary.md index 46e8e834d2186e..4f4dd54756c527 100644 --- a/docs/concepts/glossary.md +++ b/docs/concepts/glossary.md @@ -1,8 +1,3 @@ # openpilot glossary -* **route**: -* **segment**: routes are split into one minute chunks called segments. -* **panda**: this is . See the repo. -* **onroad**: -* **offroad**: -* **comma 3X**: +{{GLOSSARY_DEFINITIONS}} diff --git a/docs/concepts/logs.md b/docs/concepts/logs.md index 46ab2897df9eec..e533d3629725de 100644 --- a/docs/concepts/logs.md +++ b/docs/concepts/logs.md @@ -6,9 +6,9 @@ Check out our [Python library](https://github.com/commaai/openpilot/blob/master/ For each segment, openpilot records the following log types: -## rlog.bz2 +## rlog.zst -rlogs contain all the messages passed amongst openpilot's processes. See [cereal/services.py](https://github.com/commaai/cereal/blob/master/services.py) for a list of all the logged services. They're a bzip2 archive of the serialized capnproto messages. +rlogs contain all the messages passed amongst openpilot's processes. See [cereal/services.py](https://github.com/commaai/openpilot/blob/master/cereal/services.py) for a list of all the logged services. They're a zstd archive of the serialized [Cap’n Proto](https://capnproto.org/) messages. ## {f,e,d}camera.hevc @@ -18,12 +18,10 @@ Each camera stream is H.265 encoded and written to its respective file. * `ecamera.hevc` is the wide road camera * `dcamera.hevc` is the driver camera -## qlog.bz2 & qcamera.ts +## qlog.zst & qcamera.ts qlogs are a decimated subset of the rlogs. Check out [cereal/services.py](https://github.com/commaai/cereal/blob/master/services.py) for the decimation. - qcameras are H.264 encoded, lower res versions of the fcamera.hevc. The video shown in [comma connect](https://connect.comma.ai/) is from the qcameras. - -qlogs and qcameras are designed to be small enough to upload instantly on slow internet and store forever, yet useful enough for most analysis and debugging. +qlogs and qcameras are designed to be small enough to upload instantly on slow internet, yet useful enough for most analysis and debugging. diff --git a/docs/contributing/feedback.md b/docs/contributing/feedback.md new file mode 100644 index 00000000000000..335d24e13a8a73 --- /dev/null +++ b/docs/contributing/feedback.md @@ -0,0 +1,36 @@ +# How to Give Feedback + +Feedback is one of the highest leverage ways to contribute to openpilot as a user. + +## Driving + +Got feedback about how your car drives? +Join the community Discord, then use the form in `#submit-feedback`. + +Before posting feedback, please ensure: + +- **openpilot is up to date** you should be on the latest openpilot release or nightly +- **both road-facing cameras have a clear view** your windshield is clean, lenses are clean, etc. +- **your device is mounted properly** your device must be mounted horizontally center and relatively high on the windshield + +## Driver Monitoring + +If you find DM annoying while being perfectly attentive, these are likely false positives and we want to fix them! +In general, driver monitoring feedback is very actionable, and we can fix your complaint within a release cycle. + +To post your feedback: + +1. Join the [community Discord](https://discord.comma.ai). +2. If driver camera recording is toggled off, temporarily enable driver camera recording in the settings until you reproduce the issue. +3. Using comma connect, identify the relevant segment and upload the segment's logs and driver camera. +4. Post the segment in the `#openpilot-experience` channel on Discord with a good description. + +Before posting feedback, please ensure: + +- **openpilot is up to date** you should be on the latest openpilot release or nightly +- **the driver camera has a clear view of the driver** ensure nothing blocks view of the driver (e.g. a cable), the lens is clean, etc. +- **your device is mounted properly** your device must be mounted horizontally center and relatively high on the windshield + +## Other bugs + +Got an issue with something else? Open an issue on our [GitHub issue tracker](https://github.com/commaai/openpilot/issues/new/choose). diff --git a/docs/contributing/roadmap.md b/docs/contributing/roadmap.md index ce50ad5577e2e6..ae27a5461cacdf 100644 --- a/docs/contributing/roadmap.md +++ b/docs/contributing/roadmap.md @@ -7,25 +7,11 @@ This is the roadmap for the next major openpilot releases. Also check out * [Bounties](https://comma.ai/bounties) for paid individual issues * [#current-projects](https://discord.com/channels/469524606043160576/1249579909739708446) in Discord for discussion on work-in-progress projects -## openpilot 0.10 - -openpilot 0.10 will be the first release with a driving policy trained in -a [learned simulator](https://youtu.be/EqQNZXqzFSI). - -* Driving model trained in a learned simlator -* Always-on driver monitoring (behind a toggle) -* GPS removed from the driving stack -* 100KB qlogs -* `master-ci` pushed after 1000 hours of hardware-in-the-loop testing -* Car interface code moved into [opendbc](https://github.com/commaai/opendbc) -* openpilot on PC for Linux x86, Linux arm64, and Mac (Apple Silicon) - ## openpilot 1.0 openpilot 1.0 will feature a fully end-to-end driving policy. * End-to-end longitudinal control in Chill mode -* Automatic Emergency Braking (AEB) * Driver monitoring with sleep detection * Rolling updates/releases pushed out by CI * [panda safety 1.0](https://github.com/orgs/commaai/projects/27) diff --git a/docs/ext/glossary.py b/docs/ext/glossary.py new file mode 100644 index 00000000000000..9bbf3c78d71c10 --- /dev/null +++ b/docs/ext/glossary.py @@ -0,0 +1,216 @@ +import posixpath +import re +import tomllib +import xml.etree.ElementTree as ET +from pathlib import Path + +from markdown.extensions import Extension +from markdown.preprocessors import Preprocessor +from markdown.treeprocessors import Treeprocessor + +from zensical.extensions.links import LinksTreeprocessor + +GlossaryTerm = tuple[str, re.Pattern[str], str] + +GLOSSARY_FILE = Path(__file__).with_name("glossary.toml") +GLOSSARY_PAGE = "concepts/glossary.md" +GLOSSARY_PLACEHOLDER = "{{GLOSSARY_DEFINITIONS}}" + +SKIP_TAGS = { + "a", + "code", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "kbd", + "pre", + "script", + "style", +} + +def clean_tooltip(description: str) -> str: + text = re.sub(r"\[([^\]]+)]\([^)]+\)", r"\1", description) + text = re.sub(r"`([^`]+)`", r"\1", text) + text = re.sub(r"[*_~]", "", text) + return re.sub(r"\s+", " ", text).strip() + + +def load_glossary() -> tuple[list[GlossaryTerm], str]: + with GLOSSARY_FILE.open("rb") as f: + glossary_data = tomllib.load(f).get("glossary", {}) + + glossary: list[GlossaryTerm] = [] + rendered = [] + for key, value in glossary_data.items(): + label = str(key).strip().replace("_", " ") + description = str(value).strip() + if not description: + continue + + slug = label.replace(" ", "-").replace("_", "-").lower() + glossary.append((slug, re.compile(rf"(?**{label}**: {description}') + + return glossary, "\n".join(rendered) + + +class GlossaryPreprocessor(Preprocessor): + def __init__(self, md, glossary: str): + super().__init__(md) + self.glossary = glossary + + def run(self, lines: list[str]) -> list[str]: + markdown = "\n".join(lines) + if GLOSSARY_PLACEHOLDER not in markdown: + return lines + return markdown.replace(GLOSSARY_PLACEHOLDER, self.glossary).splitlines() + + +class GlossaryTreeprocessor(Treeprocessor): + def __init__(self, md, glossary: list[GlossaryTerm]): + super().__init__(md) + self.glossary = glossary + self.seen: set[str] = set() + + def run(self, root: ET.Element) -> None: + at = self.md.treeprocessors.get_index_for_name("zrelpath") + processor = self.md.treeprocessors[at] + if not isinstance(processor, LinksTreeprocessor): + raise TypeError("Links processor not registered") + if processor.path == GLOSSARY_PAGE: + return + + self.seen.clear() + glossary_href = f"{posixpath.relpath(GLOSSARY_PAGE, posixpath.dirname(processor.path) or '.')}#" + self._walk(root, glossary_href) + + def _walk(self, element: ET.Element, glossary_href: str) -> None: + if element.tag in SKIP_TAGS or element.attrib.get("data-glossary-skip") is not None: + return + + self._replace(element, glossary_href) + + idx = 0 + while idx < len(element): + child = element[idx] + self._walk(child, glossary_href) + idx = self._replace(element, glossary_href, idx) + 1 + + def _replace(self, parent: ET.Element, glossary_href: str, index: int | None = None) -> int: + child = None if index is None else parent[index] + text = parent.text if child is None else child.tail + pieces = self._pieces(text or "", glossary_href) + if not pieces: + return -1 if index is None else index + + if child is None: + parent.text = pieces[0] if isinstance(pieces[0], str) else "" + # Insert replacements for parent.text before the first existing child. + insert_at = -1 + else: + assert index is not None + child.tail = pieces[0] if isinstance(pieces[0], str) else "" + insert_at = index + + start = 1 if isinstance(pieces[0], str) else 0 + previous = child + + for piece in pieces[start:]: + if isinstance(piece, str): + previous.tail = (previous.tail or "") + piece + continue + + insert_at += 1 + parent.insert(insert_at, piece) + previous = piece + + return insert_at + + def _pieces(self, text: str, glossary_href: str) -> list[str | ET.Element]: + if not text.strip(): + return [] + + pieces: list[str | ET.Element] = [] + cursor = 0 + + while True: + best = None + for slug, pattern, tooltip in self.glossary: + if slug in self.seen: + continue + + found = pattern.search(text, cursor) + if found is None: + continue + + candidate = (slug, tooltip, found.start(), found.end()) + if best is None: + best = candidate + continue + + _, _, best_start, best_end = best + _, _, current_start, current_end = candidate + if current_start < best_start: + best = candidate + continue + + if current_start == best_start and current_end - current_start > best_end - best_start: + best = candidate + + if best is None: + break + + slug, tooltip, start, end = best + if start > cursor: + pieces.append(text[cursor:start]) + + link = ET.Element( + "a", + { + "class": "glossary-term", + "data-glossary-term": "", + "href": f"{glossary_href}{slug}", + }, + ) + ET.SubElement(link, "span", {"class": "glossary-term__label"}).text = text[start:end] + ET.SubElement( + link, + "span", + { + "class": "glossary-term__tooltip", + "data-search-exclude": "", + }, + ).text = tooltip + pieces.append(link) + self.seen.add(slug) + cursor = end + + if not pieces: + return [] + if cursor < len(text): + pieces.append(text[cursor:]) + return pieces + + +class GlossaryExtension(Extension): + def extendMarkdown(self, md) -> None: + md.registerExtension(self) + glossary, rendered = load_glossary() + + md.preprocessors.register( + GlossaryPreprocessor(md, rendered), + "docs-ext-glossary-preprocessor", + 27, + ) + md.treeprocessors.register( + GlossaryTreeprocessor(md, glossary), + "docs-ext-glossary-treeprocessor", + 0, + ) + + +def makeExtension(**kwargs) -> GlossaryExtension: + return GlossaryExtension(**kwargs) diff --git a/docs/ext/glossary.toml b/docs/ext/glossary.toml new file mode 100644 index 00000000000000..62408d9dddf4bf --- /dev/null +++ b/docs/ext/glossary.toml @@ -0,0 +1,8 @@ +[glossary] +onroad = "openpilot's system state while ignition is on." +offroad = "openpilot's system state while ignition is off." +route = "A route is a recording of an onroad session." +segment = "Routes are split into one minute chunks called segments." +"comma connect" = "The web viewer for all your routes; check it out at [connect.comma.ai](https://connect.comma.ai)." +panda = "The secondary processor on the device that implements the functional safety and directly talks to the car over CAN. See the [panda repo](https://github.com/commaai/panda)." +"comma four" = "The latest hardware by comma.ai for running openpilot. More info at [comma.ai/shop/comma-four](https://www.comma.ai/shop/comma-four)." diff --git a/docs/getting-started/what-is-openpilot.md b/docs/getting-started/what-is-openpilot.md deleted file mode 100644 index b3c56c8410d803..00000000000000 --- a/docs/getting-started/what-is-openpilot.md +++ /dev/null @@ -1,12 +0,0 @@ -# What is openpilot? - -[openpilot](http://github.com/commaai/openpilot) is an open source driver assistance system. Currently, openpilot performs the functions of Adaptive Cruise Control (ACC), Automated Lane Centering (ALC), Forward Collision Warning (FCW), and Lane Departure Warning (LDW) for a growing variety of [supported car makes, models, and model years](https://github.com/commaai/openpilot/blob/master/docs/CARS.md). In addition, while openpilot is engaged, a camera-based Driver Monitoring (DM) feature alerts distracted and asleep drivers. See more about [the vehicle integration](https://github.com/commaai/openpilot/blob/master/docs/INTEGRATION.md) and [limitations](https://github.com/commaai/openpilot/blob/master/docs/LIMITATIONS.md). - - -## How do I use it? - -openpilot is designed to be used on the comma 3X. - -## How does it work? - -In short, openpilot uses the car's existing APIs for the built-in [ADAS](https://en.wikipedia.org/wiki/Advanced_driver-assistance_system) system and simply provides better acceleration, braking, and steering inputs than the stock system. diff --git a/docs/how-to/car-port.md b/docs/how-to/car-port.md new file mode 100644 index 00000000000000..ca565e53f6dd3f --- /dev/null +++ b/docs/how-to/car-port.md @@ -0,0 +1,51 @@ +# What is a car port? + +A car port enables openpilot support on a particular car. Each car model openpilot supports needs to be individually ported. The complexity of a car port varies depending on many factors including: + +* existing openpilot support for similar cars +* architecture and APIs available in the car + + +# Structure of a car port + +All car-specific code is contained in the [opendbc](https://github.com/commaai/opendbc) project. + +## opendbc + +Each car brand is supported by a standard interface structure in `opendbc/car/[brand]`: + +* `interface.py`: Interface for the car, defines the CarInterface class +* `carstate.py`: Reads CAN messages from the car and builds openpilot CarState messages +* `carcontroller.py`: Control logic for executing openpilot CarControl actions on the car +* `[brand]can.py`: Composes CAN messages for carcontroller to send +* `values.py`: Limits for actuation, general constants for cars, and supported car documentation +* `radar_interface.py`: Interface for parsing radar points from the car, if applicable + +## safety + +* `opendbc/safety/modes/[brand].h`: Brand-specific safety logic +* `opendbc/safety/tests/test_[brand].py`: Brand-specific safety CI tests + +## openpilot + +For historical reasons, openpilot still contains a small amount of car-specific logic. This will eventually be migrated to opendbc or otherwise removed. + +* `selfdrive/car/car_specific.py`: Brand-specific event logic + +# How do I port car? + +[Jason Young](https://github.com/jyoung8607) gave a talk at COMMA_CON with an overview of the car porting process. The talk is available on YouTube: + +https://www.youtube.com/watch?v=XxPS5TpTUnI + +## Brand Port + +A brand port is a port of openpilot to a substantially new car brand or platform within a brand. + +Here's an example of one: https://github.com/commaai/openpilot/pull/23331. + +## Model Port + +A model port is a port of openpilot to a new car model within an already supported brand. Model ports are easier than brand ports because the car's existing APIs are already known. + +Here's an example of one: https://github.com/commaai/openpilot/pull/30672/. diff --git a/docs/how-to/connect-to-comma.md b/docs/how-to/connect-to-comma.md index 67327fbaaf9ada..e4e322f111b5ef 100644 --- a/docs/how-to/connect-to-comma.md +++ b/docs/how-to/connect-to-comma.md @@ -1,15 +1,18 @@ -# connect to a comma 3/3X +# connect to a comma 3X or comma four -A comma 3/3X is a normal [Linux](https://github.com/commaai/agnos-builder) computer that exposes [SSH](https://wiki.archlinux.org/title/Secure_Shell) and a [serial console](https://wiki.archlinux.org/title/Working_with_the_serial_console). +A comma device is a normal [Linux](https://github.com/commaai/agnos-builder) computer that exposes [SSH](https://wiki.archlinux.org/title/Secure_Shell) and a [serial console](https://wiki.archlinux.org/title/Working_with_the_serial_console). ## Serial Console -On both the comma three and 3X, the serial console is accessible from the main OBD-C port. -Connect the comma 3/3X to your computer with a normal USB C cable, or use a [comma serial](https://comma.ai/shop/comma-serial) for steady 12V power. +On the comma 3X, the serial console is accessible from the main OBD-C port, forwarded through the panda. +Access it using `panda/scripts/som_debug.sh`. -On the comma three, the serial console is exposed through a UART-to-USB chip, and `tools/scripts/serial.sh` can be used to connect. +comma four also exposes a serial console, albeit through an internal debug connector. Dedicated debug hardware coming soon to the comma shop. -On the comma 3X, the serial console is accessible through the [panda](https://github.com/commaai/panda) using the `panda/tests/som_debug.sh` script. +Login to the default user with: + + * Username: `comma` + * Password: `comma` ## SSH @@ -22,17 +25,37 @@ In order to SSH into your device, you'll need a GitHub account with SSH keys. Se * Port: `22` Here's an example command for connecting to your device using its tethered connection:
-`ssh comma@192.168.43.1` +`ssh comma@192.168.43.1 -i ~/.ssh/my_github_key` For doing development work on device, it's recommended to use [SSH agent forwarding](https://docs.github.com/en/developers/overview/using-ssh-agent-forwarding). + +## ADB + +In order to use ADB on your device, you'll need to perform the following steps using the image below for reference: + +![comma 3/3x back](../assets/three-back.svg) + +* Plug your device into constant power using port 2, letting the device boot up +* Enable ADB in your device's settings +* Plug in your device to your PC using port 1 +* Connect to your device + * `adb shell` over USB + * `adb connect` over WiFi + * Here's an example command for connecting to your device using its tethered connection: `adb connect 192.168.43.1:5555` + +> [!NOTE] +> The default port for ADB is 5555. + +For more info on ADB, see the [Android Debug Bridge (ADB) documentation](https://developer.android.com/tools/adb). + ### Notes The public keys are only fetched from your GitHub account once. In order to update your device's authorized keys, you'll need to re-enter your GitHub username. The `id_rsa` key in this directory only works while your device is in the setup state with no software installed. After installation, that default key will be removed. -#### ssh.comma.ai proxy +## ssh.comma.ai proxy With a [comma prime subscription](https://comma.ai/connect), you can SSH into your comma device from anywhere. @@ -56,6 +79,7 @@ Host ssh.comma.ai ``` ssh -i ~/.ssh/my_github_key -o ProxyCommand="ssh -i ~/.ssh/my_github_key -W %h:%p -p %p %h@ssh.comma.ai" comma@ffffffffffffffff ``` + (Replace `ffffffffffffffff` with your dongle_id) ### ssh.comma.ai host key fingerprint diff --git a/docs/how-to/replay-a-drive.md b/docs/how-to/replay-a-drive.md index 084b6bf825a785..a11b29dcc4e3f7 100644 --- a/docs/how-to/replay-a-drive.md +++ b/docs/how-to/replay-a-drive.md @@ -8,7 +8,7 @@ Replaying is a critical tool for openpilot development and debugging. Just run `tools/replay/replay --demo`. ## Replaying CAN data -*Hardware required: jungle and comma 3/3X* +*Hardware required: jungle and comma four* 1. Connect your PC to a jungle. 2. diff --git a/docs/how-to/turn-the-speed-blue.md b/docs/how-to/turn-the-speed-blue.md index e8b55ef81b86ca..b5692daff752c6 100644 --- a/docs/how-to/turn-the-speed-blue.md +++ b/docs/how-to/turn-the-speed-blue.md @@ -1,11 +1,11 @@ # Turn the speed blue *A getting started guide for openpilot development* -In 30 minutes, we'll get an openpilot development environment setup on your computer and make some changes to openpilot's UI. +In 30 minutes, we'll get an openpilot development environment set up on your computer and make some changes to openpilot's UI. -And if you have a comma 3/3X, we'll deploy the change to your device for testing. +And if you have a comma four, we'll deploy the change to your device for testing. -## 1. Setup your development environment +## 1. Set up your development environment Run this to clone openpilot and install all the dependencies: ```bash @@ -20,7 +20,7 @@ source .venv/bin/activate Then, compile openpilot: ```bash -scons -j8 +scons ``` ## 2. Run replay @@ -31,68 +31,81 @@ We'll run the `replay` tool with the demo route to get data streaming for testin tools/replay/replay --demo # in terminal 2 -selfdrive/ui/ui +./selfdrive/ui/ui.py ``` The openpilot UI should launch and show a replay of the demo route. If you have your own comma device, you can replace `--demo` with one of your own routes from comma connect. + ## 3. Make the speed blue -Search for “mph” with git grep in the `ui` folder. -```bash -$ git grep "mph" selfdrive/ui/ -paint.cc: ui_draw_text(s, s->fb_w/2, 290, s->scene.is_metric ? "km/h" : "mph", 36 * 2.5, COLOR_WHITE_ALPHA(200), "sans-regular"); -``` +Now let’s update the speed display color in the UI. -The line right above contains the actual speed. Unfortunately, COLOR_BLUE isn’t defined, but a git grep of COLOR_WHITE shows it’s nvgRGBA(255, 255, 255, 255). Personally, I like a lighter blue, so I went with #8080FF. +Search for the function responsible for rendering the current speed: ```bash -$ git diff -diff --git a/selfdrive/ui/paint.cc b/selfdrive/ui/paint.cc -index 821d95115..cc996eaa1 100644 ---- a/selfdrive/ui/paint.cc -+++ b/selfdrive/ui/paint.cc -@@ -175,8 +175,8 @@ static void ui_draw_vision_speed(UIState *s) { - const float speed = std::max(0.0, (*s->sm)["carState"].getCarState().getVEgo() * (s->scene.is_metric ? 3.6 : 2.2369363)); - const std::string speed_str = std::to_string((int)std::nearbyint(speed)); - nvgTextAlign(s->vg, NVG_ALIGN_CENTER | NVG_ALIGN_BASELINE); -- ui_draw_text(s, s->fb_w/2, 210, speed_str.c_str(), 96 * 2.5, COLOR_WHITE, "sans-bold"); -- ui_draw_text(s, s->fb_w/2, 290, s->scene.is_metric ? "km/h" : "mph", 36 * 2.5, COLOR_WHITE_ALPHA(200), "sans-regular"); -+ ui_draw_text(s, s->fb_w/2, 210, speed_str.c_str(), 96 * 2.5, nvgRGBA(128, 128, 255, 255), "sans-bold"); -+ ui_draw_text(s, s->fb_w/2, 290, s->scene.is_metric ? "km/h" : "mph", 36 * 2.5, nvgRGBA(128, 128, 255, 200), "sans-regular"); - } - - static void ui_draw_vision_event(UIState *s) { +git grep "_draw_current_speed" selfdrive/ui/onroad/hud_renderer.py ``` +You'll find the relevant code inside `selfdrive/ui/onroad/hud_renderer.py`, in this function: -## 4. Rebuild UI, and admire your work - +```python +def _draw_current_speed(self, rect: rl.Rectangle) -> None: + """Draw the current vehicle speed and unit.""" + speed_text = str(round(self.speed)) + speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) + speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) + rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.white) # <- this sets the speed text color ``` -scons -j8 && selfdrive/ui/ui + +Change `COLORS.white` to make it **blue** instead of white. A nice soft blue is `#8080FF`, which you can change inline: + +```diff +- rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.white) ++ rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, rl.Color(0x80, 0x80, 0xFF, 255)) ``` +--- + +## 4. Re-run the UI + +After making changes, re-run the UI to see your new UI: +```bash +./selfdrive/ui/ui.py +``` ![](https://blog.comma.ai/img/blue_speed_ui.png) +You should now see the speed displayed in a nice blue shade during the demo replay. + +--- + ## 5. Push your fork to GitHub -Click fork on GitHub. Then, push with: +Click **"Fork"** on the [Openpilot GitHub repo](https://github.com/commaai/openpilot). Then push with: ```bash git remote rm origin git remote add origin git@github.com:/openpilot.git git add . -git commit -m "Make the speed blue." +git commit -m "Make the speed display blue" git push --set-upstream origin master ``` -## 6. Run your fork on device in your car! +--- -Uninstall openpilot from your device through the settings. Then, enter the URL for your very own installer: +## 6. Run your fork on your comma device + +Uninstall Openpilot through the settings on your device. + +Then reinstall using your own GitHub-hosted fork: ``` installer.comma.ai//master ``` -## 7. Admire your work IRL +--- + +## 7. Admire your work IRL 🚗💨 + +You’ve now successfully modified Openpilot’s UI and deployed it to your own car! ![](https://blog.comma.ai/img/c3_blue_ui.jpg) diff --git a/docs/index.md b/docs/index.md deleted file mode 120000 index 74ea27aeeb6b72..00000000000000 --- a/docs/index.md +++ /dev/null @@ -1 +0,0 @@ -getting-started/what-is-openpilot.md \ No newline at end of file diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000000000..6fab2b979b1429 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,12 @@ +# What is openpilot? + +[openpilot](http://github.com/commaai/openpilot) is an open source driver assistance system. Currently, openpilot performs the functions of Adaptive Cruise Control (ACC), Automated Lane Centering (ALC), Forward Collision Warning (FCW), and Lane Departure Warning (LDW) for a growing variety of [supported car makes, models, and model years](https://github.com/commaai/openpilot/blob/master/docs/CARS.md). In addition, while openpilot is engaged, a camera-based Driver Monitoring (DM) feature alerts distracted and asleep drivers. See more about [the vehicle integration](https://github.com/commaai/openpilot/blob/master/docs/INTEGRATION.md) and [limitations](https://github.com/commaai/openpilot/blob/master/docs/LIMITATIONS.md). + + +## How do I use it? + +openpilot is designed to be used on the comma four. + +## How does it work? + +In short, openpilot uses the car's existing APIs for the built-in [ADAS](https://en.wikipedia.org/wiki/Advanced_driver-assistance_system) system and simply provides better acceleration, braking, and steering inputs than the stock system. diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css new file mode 100644 index 00000000000000..36ce354af10af3 --- /dev/null +++ b/docs/stylesheets/extra.css @@ -0,0 +1,42 @@ +.md-logo img { + filter: invert(1); +} + +.glossary-term { + position: relative; + color: inherit; + text-decoration: none; +} + +.glossary-term__label { + border-bottom: 1px dotted currentColor; +} + +.glossary-term__tooltip { + position: absolute; + top: calc(100% + 0.4rem); + left: 50%; + width: max-content; + max-width: min(30rem, 80vw); + padding: 0.65rem 0.8rem; + border-radius: 0.6rem; + background: rgb(26 26 26 / 96%); + color: white; + box-shadow: 0 0.6rem 1.8rem rgb(0 0 0 / 22%); + font-size: 0.85rem; + line-height: 1.45; + opacity: 0; + pointer-events: none; + transform: translateX(-50%) translateY(-0.15rem); + transition: opacity 120ms ease, transform 120ms ease; + visibility: hidden; + z-index: 20; +} + +.glossary-term:hover .glossary-term__tooltip, +.glossary-term:focus-visible .glossary-term__tooltip, +.glossary-term:focus-within .glossary-term__tooltip { + opacity: 1; + transform: translateX(-50%) translateY(0); + visibility: visible; +} diff --git a/fill50 b/fill50 new file mode 120000 index 00000000000000..690eb114b67a35 --- /dev/null +++ b/fill50 @@ -0,0 +1 @@ +/workspace/fill50 \ No newline at end of file diff --git a/launch_chffrplus.sh b/launch_chffrplus.sh index 442a811b160603..16b8587514399d 100755 --- a/launch_chffrplus.sh +++ b/launch_chffrplus.sh @@ -1,16 +1,13 @@ #!/usr/bin/env bash -if [ -z "$BASEDIR" ]; then - BASEDIR="/data/openpilot" -fi - -source "$BASEDIR/launch_env.sh" - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +source "$DIR/launch_env.sh" + function agnos_init { # TODO: move this to agnos sudo rm -f /data/etc/NetworkManager/system-connections/*.nmmeta + rm -f /data/scons_cache/config.lock # set success flag for current boot slot sudo abctl --set_success @@ -38,25 +35,25 @@ function launch { # Check to see if there's a valid overlay-based update available. Conditions # are as follows: # - # 1. The BASEDIR init file has to exist, with a newer modtime than anything in - # the BASEDIR Git repo. This checks for local development work or the user + # 1. The DIR init file has to exist, with a newer modtime than anything in + # the DIR Git repo. This checks for local development work or the user # switching branches/forks, which should not be overwritten. # 2. The FINALIZED consistent file has to exist, indicating there's an update # that completed successfully and synced to disk. - if [ -f "${BASEDIR}/.overlay_init" ]; then - find ${BASEDIR}/.git -newer ${BASEDIR}/.overlay_init | grep -q '.' 2> /dev/null + if [ -f "${DIR}/.overlay_init" ]; then + find ${DIR}/.git -newer ${DIR}/.overlay_init | grep -q '.' 2> /dev/null if [ $? -eq 0 ]; then - echo "${BASEDIR} has been modified, skipping overlay update installation" + echo "${DIR} has been modified, skipping overlay update installation" else if [ -f "${STAGING_ROOT}/finalized/.overlay_consistent" ]; then if [ ! -d /data/safe_staging/old_openpilot ]; then echo "Valid overlay update found, installing" LAUNCHER_LOCATION="${BASH_SOURCE[0]}" - mv $BASEDIR /data/safe_staging/old_openpilot - mv "${STAGING_ROOT}/finalized" $BASEDIR - cd $BASEDIR + mv $DIR /data/safe_staging/old_openpilot + mv "${STAGING_ROOT}/finalized" $DIR + cd $DIR echo "Restarting launch script ${LAUNCHER_LOCATION}" unset AGNOS_VERSION @@ -78,6 +75,19 @@ function launch { agnos_init fi + # NotAutopilot: block comma 3 (tici) — this build requires comma 3X (tizi) or newer + if [ -f /sys/firmware/devicetree/base/model ]; then + DEVICE_TYPE=$(cat /sys/firmware/devicetree/base/model | tr -d '\0' | awk -F'comma ' '{print $2}') + if [ "$DEVICE_TYPE" = "tici" ]; then + echo "=============================================" + echo "NotAutopilot does not support comma 3 (tici)." + echo "Please use a comma 3X or newer device." + echo "=============================================" + sleep 30 + exit 1 + fi + fi + # write tmux scrollback to a file tmux capture-pane -pq -S-1000 > /tmp/launch_log diff --git a/launch_env.sh b/launch_env.sh index 1e5bc7b607cc37..d71a5c27670c1d 100755 --- a/launch_env.sh +++ b/launch_env.sh @@ -6,8 +6,17 @@ export NUMEXPR_NUM_THREADS=1 export OPENBLAS_NUM_THREADS=1 export VECLIB_MAXIMUM_THREADS=1 +# models get lower priority than ui +# - ui is ~5ms +# - modeld is 20ms +# - DM is 10ms +# in order to run ui at 60fps (16.67ms), we need to allow +# it to preempt the model workloads. we have enough +# headroom for this until ui is moved to the CPU. +export QCOM_PRIORITY=12 + if [ -z "$AGNOS_VERSION" ]; then - export AGNOS_VERSION="10.1" + export AGNOS_VERSION="18.4" fi export STAGING_ROOT="/data/safe_staging" diff --git a/mkdocs.yml b/mkdocs.yml deleted file mode 100644 index 743b8fa1b789c6..00000000000000 --- a/mkdocs.yml +++ /dev/null @@ -1,38 +0,0 @@ -site_name: openpilot docs -repo_url: https://github.com/commaai/openpilot/ -site_url: https://docs.comma.ai - -exclude_docs: README.md - -strict: true -docs_dir: docs -site_dir: docs_site/ - -theme: - name: readthedocs - navigation_depth: 3 - -nav: - - Getting Started: - - What is openpilot?: getting-started/what-is-openpilot.md - - How-to: - - Turn the speed blue: how-to/turn-the-speed-blue.md - - Connect to a comma 3/3X: how-to/connect-to-comma.md - #- Replay a drive: how-to/replay-a-drive.md - - Concepts: - - Logs: concepts/logs.md - - Safety: concepts/safety.md - - Car Porting: - - What is a car port?: car-porting/what-is-a-car-port.md - - Porting a car brand: car-porting/brand-port.md - - Porting a car model: car-porting/model-port.md - - Contributing: - - Roadmap: contributing/roadmap.md - #- Architecture: contributing/architecture.md - - Contributing Guide →: https://github.com/commaai/openpilot/blob/master/docs/CONTRIBUTING.md - - Links: - - Blog →: https://blog.comma.ai - - Bounties →: https://comma.ai/bounties - - GitHub →: https://github.com/commaai - - Discord →: https://discord.comma.ai - - X →: https://x.com/comma_ai diff --git a/msgq_repo b/msgq_repo index cdcf84f44a4edd..9beb84af67527f 160000 --- a/msgq_repo +++ b/msgq_repo @@ -1 +1 @@ -Subproject commit cdcf84f44a4edd40f7aa4d06eb95550ac64b3b37 +Subproject commit 9beb84af67527f7b6bfee349dcbe3dbb8d4f4789 diff --git a/opendbc_repo b/opendbc_repo index f383e5cc64d105..508d26fcbe39c5 160000 --- a/opendbc_repo +++ b/opendbc_repo @@ -1 +1 @@ -Subproject commit f383e5cc64d105e90b8133d58dc18490b79153fb +Subproject commit 508d26fcbe39c51b89305538104e5dee943b3ea6 diff --git a/openpilot/third_party b/openpilot/third_party deleted file mode 120000 index d838c05a86286e..00000000000000 --- a/openpilot/third_party +++ /dev/null @@ -1 +0,0 @@ -../third_party \ No newline at end of file diff --git a/panda b/panda index aac60b8a7938d4..282fae705ecd16 160000 --- a/panda +++ b/panda @@ -1 +1 @@ -Subproject commit aac60b8a7938d4d32c0c02608058022e4d876156 +Subproject commit 282fae705ecd16dc94e0978a23b1f0c015303d1d diff --git a/pyproject.toml b/pyproject.toml index b42eb671413d45..1e8ecb0232a602 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,11 +1,11 @@ [project] name = "openpilot" -requires-python = ">= 3.11" +requires-python = ">= 3.12.3, < 3.13" license = {text = "MIT License"} version = "0.1.0" description = "an open source driver assistance system" authors = [ - {name ="Vehicle Researcher", email="user@comma.ai"} + {name = "Vehicle Researcher", email="user@comma.ai"} ] dependencies = [ @@ -14,46 +14,57 @@ dependencies = [ "pyserial", # pigeond + qcomgpsd "requests", # many one-off uses "sympy", # rednose + friends - "crcmod", # cars + qcomgpsd + "crcmod-plus", # cars + qcomgpsd "tqdm", # cars (fw_versions.py) on start + many one-off uses - # hardwared - "smbus2", # configuring amp - # core "cffi", "scons", - "pycapnp", + "pycapnp==2.1.0", # 2.2 introduces a memory leak due to cyclic references "Cython", "setuptools", - "numpy < 2.0.0", + "numpy >=2.0", + + # vendored native dependencies + "bzip2 @ git+https://github.com/commaai/dependencies.git@release-bzip2#subdirectory=bzip2", + "bootstrap-icons @ git+https://github.com/commaai/dependencies.git@release-bootstrap-icons#subdirectory=bootstrap-icons", + "capnproto @ git+https://github.com/commaai/dependencies.git@release-capnproto#subdirectory=capnproto", + "catch2 @ git+https://github.com/commaai/dependencies.git@release-catch2#subdirectory=catch2", + "acados @ git+https://github.com/commaai/dependencies.git@release-acados#subdirectory=acados", + "eigen @ git+https://github.com/commaai/dependencies.git@release-eigen#subdirectory=eigen", + "ffmpeg @ git+https://github.com/commaai/dependencies.git@release-ffmpeg#subdirectory=ffmpeg", + "libjpeg @ git+https://github.com/commaai/dependencies.git@release-libjpeg#subdirectory=libjpeg", + "libyuv @ git+https://github.com/commaai/dependencies.git@release-libyuv#subdirectory=libyuv", + "zstd @ git+https://github.com/commaai/dependencies.git@release-zstd#subdirectory=zstd", + "ncurses @ git+https://github.com/commaai/dependencies.git@release-ncurses#subdirectory=ncurses", + "zeromq @ git+https://github.com/commaai/dependencies.git@release-zeromq#subdirectory=zeromq", + "libusb @ git+https://github.com/commaai/dependencies.git@release-libusb#subdirectory=libusb", + "json11 @ git+https://github.com/commaai/dependencies.git@release-json11#subdirectory=json11", + "git-lfs @ git+https://github.com/commaai/dependencies.git@release-git-lfs#subdirectory=git-lfs", + "gcc-arm-none-eabi @ git+https://github.com/commaai/dependencies.git@release-gcc-arm-none-eabi#subdirectory=gcc-arm-none-eabi", + "xvfb @ git+https://github.com/commaai/dependencies.git@release-xvfb#subdirectory=xvfb", # body / webrtcd + "av", "aiohttp", "aiortc", - "pyaudio", # panda "libusb1", "spidev; platform_system == 'Linux'", - # modeld - "onnx >= 1.14.0", - "onnxruntime >=1.16.3; platform_system == 'Linux' and platform_machine == 'aarch64'", - "onnxruntime-gpu >=1.16.3; platform_system == 'Linux' and platform_machine == 'x86_64'", - # logging "pyzmq", "sentry-sdk", + "xattr", # used in place of 'os.getxattr' for macOS compatibility # athena "PyJWT", "json-rpc", "websocket_client", - # acados deps - "casadi >=3.6.6", # 3.12 fixed in 3.6.6 - "future-fstrings", + # joystickd + "inputs", # these should be removed "psutil", @@ -62,62 +73,47 @@ dependencies = [ # logreader "zstandard", + + # ui + "raylib @ git+https://github.com/commaai/dependencies.git@release-raylib#subdirectory=raylib", + "qrcode", + "jeepney", + "pillow", ] [project.optional-dependencies] docs = [ "Jinja2", - "natsort", - "mkdocs", + "zensical", ] testing = [ "coverage", "hypothesis ==6.47.*", - "mypy", + "ty", "pytest", - "pytest-cov", "pytest-cpp", "pytest-subtests", - "pytest-xdist", - "pytest-timeout", - "pytest-randomly", - "pytest-asyncio", + # https://github.com/pytest-dev/pytest-xdist/pull/1229 + "pytest-xdist @ git+https://github.com/sshane/pytest-xdist@2b4372bd62699fb412c4fe2f95bf9f01bd2018da", "pytest-mock", - "pytest-repeat", "ruff", "codespell", "pre-commit-hooks", ] dev = [ - "av", - "azure-identity", - "azure-storage-blob", - "dictdiffer", - "flaky", - "inputs", - "lru-dict", "matplotlib", - "metadrive-simulator @ https://github.com/commaai/metadrive/releases/download/MetaDrive-minimal/metadrive_simulator-0.4.2.3-py3-none-any.whl ; (platform_machine != 'aarch64')", - "parameterized >=0.8, <0.9", - #"pprofile", - "pyautogui", - "pyopencl; platform_machine != 'aarch64'", # broken on arm64 - "pytools < 2024.1.11; platform_machine != 'aarch64'", # pyopencl use a broken version - "pywinctl", - "pyprof2calltree", - "rerun-sdk >= 0.18", - "tabulate", - "types-requests", - "types-tabulate", + "opencv-python-headless", +] - # this is only pinned since 5.15.11 is broken - "pyqt5 ==5.15.2; platform_machine == 'x86_64'", # no aarch64 wheels for macOS/linux +tools = [ + "imgui @ git+https://github.com/commaai/dependencies.git@release-imgui#subdirectory=imgui", + "metadrive-simulator @ git+https://github.com/commaai/metadrive.git@minimal ; (platform_machine != 'aarch64')", ] [project.urls] -Homepage = "https://comma.ai" +Homepage = "https://github.com/commaai/openpilot" [build-system] requires = ["hatchling"] @@ -131,98 +127,44 @@ allow-direct-references = true [tool.pytest.ini_options] minversion = "6.0" -addopts = "--ignore=openpilot/ --ignore=opendbc/ --ignore=panda/ --ignore=rednose_repo/ --ignore=tinygrad_repo/ --ignore=teleoprtc_repo/ --ignore=msgq/ -Werror --strict-config --strict-markers --durations=10 -n auto --dist=loadgroup" +addopts = "--ignore=openpilot/ --ignore=opendbc/ --ignore=panda/ --ignore=rednose_repo/ --ignore=tinygrad_repo/ --ignore=teleoprtc_repo/ --ignore=msgq/ -Werror --strict-config --strict-markers --durations=10 -n auto --dist=loadgroup" cpp_files = "test_*" cpp_harness = "selfdrive/test/cpp_harness.py" python_files = "test_*.py" -asyncio_default_fixture_loop_scope = "function" -#timeout = "30" # you get this long by default markers = [ "slow: tests that take awhile to run and can be skipped with -m 'not slow'", "tici: tests that are only meant to run on the C3/C3X", + "skip_tici_setup: mark test to skip tici setup fixture", + "nocapture: don't capture test output", + "shared_download_cache: share download cache between tests", + "xdist_group_class_property: group tests by a property of the class that contains them", ] testpaths = [ "common", - "selfdrive/pandad", - "selfdrive/car", - "selfdrive/opcar", - "selfdrive/controls", - "selfdrive/locationd", - "selfdrive/monitoring", - "selfdrive/test/longitudinal_maneuvers", - "selfdrive/test/process_replay/test_fuzzy.py", - "system/updated", - "system/athena", - "system/camerad", - "system/hardware", - "system/loggerd", - "system/proclogd", - "system/tests", - "system/ubloxd", - "system/webrtc", - "tools/lib/tests", - "tools/replay", - "tools/cabana", - "cereal/messaging/tests", + "selfdrive", + "system", + "tools", + "cereal", ] [tool.codespell] quiet-level = 3 # if you've got a short variable name that's getting flagged, add it here -ignore-words-list = "bu,ro,te,ue,alo,hda,ois,nam,nams,ned,som,parm,setts,inout,warmup,bumb,nd,sie,preints,whit,indexIn,ws,uint,grey,deque,stdio,amin,BA,LITE,atEnd,UIs,errorString,arange,FocusIn,od,tim,relA,hist,copyable,jupyter,thead" +ignore-words-list = "bu,ro,te,ue,alo,hda,ois,nam,nams,ned,som,parm,setts,inout,warmup,bumb,nd,sie,preints,whit,indexIn,ws,uint,grey,deque,stdio,amin,BA,LITE,atEnd,UIs,errorString,arange,FocusIn,od,tim,relA,hist,copyable,jupyter,thead,TGE,abl,lite,ser" builtin = "clear,rare,informal,code,names,en-GB_to_en-US" -skip = "./third_party/*, ./tinygrad/*, ./tinygrad_repo/*, ./msgq/*, ./panda/*, ./opendbc/*, ./opendbc_repo/*, ./rednose/*, ./rednose_repo/*, ./teleoprtc/*, ./teleoprtc_repo/*, *.ts, uv.lock, *.onnx, ./cereal/gen/*, */c_generated_code/*" - -[tool.mypy] -python_version = "3.11" -plugins = [ - "numpy.typing.mypy_plugin", -] -exclude = [ - "cereal/", - "msgq/", - "msgq_repo/", - "opendbc/", - "opendbc_repo/", - "panda/", - "rednose/", - "rednose_repo/", - "tinygrad/", - "tinygrad_repo/", - "teleoprtc/", - "teleoprtc_repo/", - "third_party/", -] - -# third-party packages -ignore_missing_imports=true - -# helpful warnings -warn_redundant_casts=true -warn_unreachable=true -warn_unused_ignores=true - -# restrict dynamic typing -warn_return_any=true - -# allow implicit optionals for default args -implicit_optional = true +skip = "../tinygrad/*, ./tinygrad_repo/*, ./msgq/*, ./panda/*, ./opendbc/*, ./opendbc_repo/*, ./rednose/*, ./rednose_repo/*, ./teleoprtc/*, ./teleoprtc_repo/*, *.po, uv.lock, *.onnx, *.pem, ./cereal/gen/*, */c_generated_code/*, docs/assets/*, tools/plotjuggler/layouts/*, selfdrive/assets/offroad/mici_fcc.html" -local_partial_types=true -explicit_package_bases=true -disable_error_code = "annotation-unchecked" - -# https://beta.ruff.rs/docs/configuration/#using-pyprojecttoml +# https://docs.astral.sh/ruff/configuration/#using-pyprojecttoml [tool.ruff] indent-width = 2 lint.select = [ "E", "F", "W", "PIE", "C4", "ISC", "A", "B", "NPY", # numpy "UP", # pyupgrade - "TRY302", "TRY400", "TRY401", # try/excepts + "TRY203", "TRY400", "TRY401", # try/excepts "RUF008", "RUF100", "TID251", - "PLR1704", + "PLE", "PLR1704", ] lint.ignore = [ "E741", @@ -232,21 +174,20 @@ lint.ignore = [ "B027", "B024", "NPY002", # new numpy random syntax is worse - "UP038", # (x, y) -> x|y for isinstance + "UP045", "UP007", # these don't play nice with raylib atm ] line-length = 160 -target-version ="py311" exclude = [ - "body", "cereal", "panda", "opendbc", + "opendbc_repo", "rednose_repo", "tinygrad_repo", "teleoprtc", "teleoprtc_repo", - "third_party", "*.ipynb", + "generated", ] lint.flake8-implicit-str-concat.allow-multiline = false @@ -254,13 +195,47 @@ lint.flake8-implicit-str-concat.allow-multiline = false "selfdrive".msg = "Use openpilot.selfdrive" "common".msg = "Use openpilot.common" "system".msg = "Use openpilot.system" -"third_party".msg = "Use openpilot.third_party" "tools".msg = "Use openpilot.tools" "pytest.main".msg = "pytest.main requires special handling that is easy to mess up!" "unittest".msg = "Use pytest" +"time.time".msg = "Use time.monotonic" -[tool.coverage.run] -concurrency = ["multiprocessing", "thread"] +# raylib banned APIs +"pyray.measure_text_ex".msg = "Use openpilot.system.ui.lib.text_measure" +"pyray.is_mouse_button_pressed".msg = "This can miss events. Use Widget._handle_mouse_press" +"pyray.is_mouse_button_released".msg = "This can miss events. Use Widget._handle_mouse_release" +"pyray.draw_text".msg = "Use a function (such as rl.draw_font_ex) that takes font as an argument" +"pyray.draw_texture".msg = "Use rl.draw_texture_ex for float position support" [tool.ruff.format] quote-style = "preserve" + +[tool.ty.src] +exclude = [ + "msgq/", + "msgq_repo/", + "opendbc/", + "opendbc_repo/", + "panda/", + "rednose/", + "rednose_repo/", + "tinygrad/", + "tinygrad_repo/", + "teleoprtc/", + "teleoprtc_repo/", +] + +[tool.ty.rules] +unresolved-import = "ignore" # Cython-compiled modules (.pyx) +unresolved-attribute = "ignore" # many from capnp and Cython modules +invalid-method-override = "ignore" # signature variance issues +possibly-missing-attribute = "ignore" # too many false positives +invalid-assignment = "ignore" # often intentional monkey-patching +no-matching-overload = "ignore" # numpy/ctypes overload matching issues +invalid-argument-type = "ignore" # many false positives from raylib, ctypes, numpy +call-non-callable = "ignore" # false positives from dynamic types +unsupported-operator = "ignore" # false positives from dynamic types +not-subscriptable = "ignore" # false positives from dynamic types + +[tool.uv] +python-preference = "only-managed" diff --git a/rednose_repo b/rednose_repo index 05fd60278a9519..7ffefa3d8811a8 160000 --- a/rednose_repo +++ b/rednose_repo @@ -1 +1 @@ -Subproject commit 05fd60278a95190cc5a61f40730c82eaa1d986e1 +Subproject commit 7ffefa3d8811a842f8ec97d311103ce3a45dfae0 diff --git a/release/README.md b/release/README.md index 1d3e78493694d8..7aeea9fe4aff6d 100644 --- a/release/README.md +++ b/release/README.md @@ -1,36 +1,35 @@ # openpilot releases +``` ## release checklist -**Go to `devel-staging`** -- [ ] update `devel-staging`: `git reset --hard origin/master-ci` -- [ ] open a pull request from `devel-staging` to `devel` - -**Go to `devel`** -- [ ] update RELEASES.md -- [ ] close out milestone -- [ ] post on Discord dev channel +### Go to staging +- [ ] make a GitHub issue to track release with this checklist +- [ ] create release master branch + - [ ] create a branch from upstream master named `zerotentwo` for release `v0.10.2` + - [ ] revert risky commits (double check with autonomy team) + - [ ] push the new branch +- [ ] push to staging: + - [ ] make sure you are on the newly created release master branch (`zerotentwo`) + - [ ] run `BRANCH=devel-staging release/build_stripped.sh`. Jenkins will then automatically build staging on device, run `test_onroad` and update the staging branch - [ ] bump version on master: `common/version.h` and `RELEASES.md` -- [ ] merge the pull request - -tests: -- [ ] update from previous release -> new release -- [ ] update from new release -> previous release -- [ ] fresh install with `openpilot-test.comma.ai` -- [ ] drive on fresh install -- [ ] comma body test -- [ ] no submodules or LFS -- [ ] check sentry, MTBF, etc. +- [ ] post on Discord, tag `@release crew` -**Go to `release3`** +### Go to release +- [ ] before going to release, test the following: + - [ ] update from previous release -> new release + - [ ] update from new release -> previous release + - [ ] fresh install with `openpilot-test.comma.ai` + - [ ] drive on fresh install + - [ ] no submodules or LFS + - [ ] check sentry, MTBF, etc. + - [ ] stress test passes in production - [ ] publish the blog post -- [ ] `git reset --hard origin/release3-staging` -- [ ] tag the release -``` -git tag v0.X.X -git push origin v0.X.X -``` +- [ ] `git reset --hard origin/release-mici-staging` +- [ ] tag the release: `git tag v0.X.X && git push origin v0.X.X` - [ ] create GitHub release - [ ] final test install on `openpilot.comma.ai` -- [ ] update production -- [ ] Post on Discord, X, etc. +- [ ] update factory provisioning +- [ ] close out milestone and issue +- [ ] post on Discord, X, etc. +``` diff --git a/release/build_devel.sh b/release/build_devel.sh deleted file mode 100755 index c6d04396fe397d..00000000000000 --- a/release/build_devel.sh +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env bash -set -ex - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" - -SOURCE_DIR="$(git -C $DIR rev-parse --show-toplevel)" -if [ -z "$TARGET_DIR" ]; then - TARGET_DIR="$(mktemp -d)" -fi - -# set git identity -source $DIR/identity.sh - -echo "[-] Setting up target repo T=$SECONDS" - -rm -rf $TARGET_DIR -mkdir -p $TARGET_DIR -cd $TARGET_DIR -cp -r $SOURCE_DIR/.git $TARGET_DIR -pre-commit uninstall || true - -echo "[-] bringing master-ci and devel in sync T=$SECONDS" -cd $TARGET_DIR - -git fetch --depth 1 origin master-ci -git fetch --depth 1 origin devel - -git checkout -f --track origin/master-ci -git reset --hard master-ci -git checkout master-ci -git reset --hard origin/devel -git clean -xdff -git lfs uninstall - -# remove everything except .git -echo "[-] erasing old openpilot T=$SECONDS" -find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; - -# reset source tree -cd $SOURCE_DIR -git clean -xdff - -# do the files copy -echo "[-] copying files T=$SECONDS" -cd $SOURCE_DIR -cp -pR --parents $(./release/release_files.py) $TARGET_DIR/ - -# in the directory -cd $TARGET_DIR -rm -f panda/board/obj/panda.bin.signed - -# include source commit hash and build date in commit -GIT_HASH=$(git --git-dir=$SOURCE_DIR/.git rev-parse HEAD) -DATETIME=$(date '+%Y-%m-%dT%H:%M:%S') -VERSION=$(cat $SOURCE_DIR/common/version.h | awk -F\" '{print $2}') - -echo "[-] committing version $VERSION T=$SECONDS" -git add -f . -git status -git commit -a -m "openpilot v$VERSION release - -date: $DATETIME -master commit: $GIT_HASH -" - -# should be no submodules or LFS files -git submodule status -if [ ! -z "$(git lfs ls-files)" ]; then - echo "LFS files detected!" - exit 1 -fi - -# ensure files are within GitHub's limit -BIG_FILES="$(find . -type f -not -path './.git/*' -size +95M)" -if [ ! -z "$BIG_FILES" ]; then - printf '\n\n\n' - echo "Found files exceeding GitHub's 100MB limit:" - echo "$BIG_FILES" - exit 1 -fi - -if [ ! -z "$BRANCH" ]; then - echo "[-] Pushing to $BRANCH T=$SECONDS" - git push -f origin master-ci:$BRANCH -fi - -echo "[-] done T=$SECONDS, ready at $TARGET_DIR" diff --git a/release/build_release.sh b/release/build_release.sh index bcc4b5cdedd735..cec6f4ecdca327 100755 --- a/release/build_release.sh +++ b/release/build_release.sh @@ -16,6 +16,8 @@ if [ -z "$RELEASE_BRANCH" ]; then exit 1 fi +BUILD_BRANCH=release-mici-staging + # set git identity source $DIR/identity.sh @@ -26,7 +28,7 @@ mkdir -p $BUILD_DIR cd $BUILD_DIR git init git remote add origin git@github.com:commaai/openpilot.git -git checkout --orphan $RELEASE_BRANCH +git checkout --orphan $BUILD_BRANCH # do the files copy echo "[-] copying files T=$SECONDS" @@ -40,18 +42,21 @@ rm -f panda/board/obj/panda.bin.signed rm -f panda/board/obj/panda_h7.bin.signed VERSION=$(cat common/version.h | awk -F[\"-] '{print $2}') -echo "#define COMMA_VERSION \"$VERSION-release\"" > common/version.h - echo "[-] committing version $VERSION T=$SECONDS" git add -f . git commit -a -m "openpilot v$VERSION release" # Build export PYTHONPATH="$BUILD_DIR" -scons -j$(nproc) --minimal - -# release panda fw -CERT=/data/pandaextra/certs/release RELEASE=1 scons -j$(nproc) panda/ +scons + +if [ -z "$PANDA_DEBUG_BUILD" ]; then + # release panda fw + CERT=/data/pandaextra/certs/release RELEASE=1 scons panda/ +else + # build with ALLOW_DEBUG=1 to enable features like experimental longitudinal + scons panda/ +fi # Ensure no submodules in release if test "$(git submodule--helper list | wc -l)" -gt "0"; then @@ -69,14 +74,7 @@ find . -name '*.pyc' -delete find . -name 'moc_*' -delete find . -name '__pycache__' -delete rm -rf .sconsign.dblite Jenkinsfile release/ -rm selfdrive/modeld/models/supercombo.onnx - -find third_party/ -name '*x86*' -exec rm -r {} + -find third_party/ -name '*Darwin*' -exec rm -r {} + - - -# Restore third_party -git checkout third_party/ +rm -f selfdrive/modeld/models/*.onnx* # Mark as prebuilt release touch prebuilt @@ -86,18 +84,15 @@ git add -f . git commit --amend -m "openpilot v$VERSION" # Run tests -TEST_FILES="tools/" -cd $SOURCE_DIR -cp -pR -n --parents $TEST_FILES $BUILD_DIR/ cd $BUILD_DIR RELEASE=1 pytest -n0 -s selfdrive/test/test_onroad.py -#system/manager/test/test_manager.py -pytest selfdrive/car/tests/test_car_interfaces.py -rm -rf $TEST_FILES - -if [ ! -z "$RELEASE_BRANCH" ]; then - echo "[-] pushing release T=$SECONDS" - git push -f origin $RELEASE_BRANCH:$RELEASE_BRANCH -fi +#pytest selfdrive/car/tests/test_car_interfaces.py + +echo "[-] pushing release T=$SECONDS" +REFS=() +for branch in ${RELEASE_BRANCH//,/ }; do + REFS+=("$BUILD_BRANCH:$branch") +done +git push -f origin "${REFS[@]}" echo "[-] done T=$SECONDS" diff --git a/release/build_stripped.sh b/release/build_stripped.sh new file mode 100755 index 00000000000000..91c94b44a05030 --- /dev/null +++ b/release/build_stripped.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +set -ex + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" + +SOURCE_DIR="$(git -C $DIR rev-parse --show-toplevel)" +if [ -z "$TARGET_DIR" ]; then + TARGET_DIR="$(mktemp -d)" +fi + +# set git identity +source $DIR/identity.sh + +echo "[-] Setting up target repo T=$SECONDS" + +rm -rf $TARGET_DIR +mkdir -p $TARGET_DIR +cd $TARGET_DIR +cp -r $SOURCE_DIR/.git $TARGET_DIR + +echo "[-] setting up stripped branch sync T=$SECONDS" +cd $TARGET_DIR + +# tmp branch +git checkout --orphan tmp + +# remove everything except .git +echo "[-] erasing old openpilot T=$SECONDS" +git submodule deinit -f --all +git rm -rf --cached . +find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; + +# cleanup before the copy +cd $SOURCE_DIR +git clean -xdff +git submodule foreach --recursive git clean -xdff + +# do the files copy +echo "[-] copying files T=$SECONDS" +cd $SOURCE_DIR +cp -pR --parents $(./release/release_files.py) $TARGET_DIR/ + +# in the directory +cd $TARGET_DIR +rm -rf .git/modules/ +rm -f panda/board/obj/panda.bin.signed + +find selfdrive/modeld/models -name '*.onnx' -size +95M -exec ./common/file_chunker.py {} \; + +# include source commit hash and build date in commit +GIT_HASH=$(git --git-dir=$SOURCE_DIR/.git rev-parse HEAD) +GIT_COMMIT_DATE=$(git --git-dir=$SOURCE_DIR/.git show --no-patch --format='%ct %ci' HEAD) +DATETIME=$(date '+%Y-%m-%dT%H:%M:%S') +VERSION=$(cat $SOURCE_DIR/common/version.h | awk -F\" '{print $2}') + +echo -n "$GIT_HASH" > git_src_commit +echo -n "$GIT_COMMIT_DATE" > git_src_commit_date + +echo "[-] committing version $VERSION T=$SECONDS" +git add -f . +git status +git commit -a -m "openpilot v$VERSION release + +date: $DATETIME +master commit: $GIT_HASH +" + +# should be no submodules or LFS files +git submodule status +if [ ! -z "$(git lfs ls-files)" ]; then + echo "LFS files detected!" + exit 1 +fi + +# ensure files are within GitHub's limit +BIG_FILES="$(find . -type f -not -path './.git/*' -size +95M)" +if [ ! -z "$BIG_FILES" ]; then + printf '\n\n\n' + echo "Found files exceeding GitHub's 100MB limit:" + echo "$BIG_FILES" + exit 1 +fi + +if [ ! -z "$BRANCH" ]; then + echo "[-] Pushing to $BRANCH T=$SECONDS" + git push -f origin tmp:$BRANCH +fi + +echo "[-] done T=$SECONDS, ready at $TARGET_DIR" diff --git a/release/check-submodules.sh b/release/check-submodules.sh index 895f8fe1e0d94c..93869a740347d9 100755 --- a/release/check-submodules.sh +++ b/release/check-submodules.sh @@ -1,7 +1,12 @@ #!/usr/bin/env bash while read hash submodule ref; do - git -C $submodule fetch --depth 4000 origin master + if [ "$submodule" = "tinygrad_repo" ]; then + echo "Skipping $submodule" + continue + fi + + git -C $submodule fetch --depth 100 origin master git -C $submodule branch -r --contains $hash | grep "origin/master" if [ "$?" -eq 0 ]; then echo "$submodule ok" diff --git a/release/pack.py b/release/pack.py new file mode 100755 index 00000000000000..560500e7a77fce --- /dev/null +++ b/release/pack.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 + +import importlib +import shutil +import sys +import tempfile +import zipapp +from argparse import ArgumentParser +from pathlib import Path + +from openpilot.common.basedir import BASEDIR + + +DIRS = ['cereal', 'openpilot'] +EXTS = ['.png', '.py', '.ttf', '.capnp', '.json', '.fnt', '.mo', '.po'] +EXCLUDE = ['selfdrive/assets/training'] +INTERPRETER = '/usr/bin/env python3' + + +def copy(src, dest): + if any(src.endswith(ext) for ext in EXTS) and not any(exc in src for exc in EXCLUDE): + shutil.copy2(src, dest, follow_symlinks=True) + + +if __name__ == '__main__': + parser = ArgumentParser(prog='pack.py', description="package script into a portable executable", epilog='comma.ai') + parser.add_argument('-e', '--entrypoint', help="function to call in module, default is 'main'", default='main') + parser.add_argument('-o', '--output', help='output file') + parser.add_argument('module', help="the module to target, e.g. 'openpilot.system.ui.spinner'") + args = parser.parse_args() + + print('WARNING: copying all files! make sure to run scons and git tree is clean') + + if not args.output: + args.output = args.module + + try: + mod = importlib.import_module(args.module) + except ModuleNotFoundError: + print(f'{args.module} not found, typo?') + sys.exit(1) + + if not hasattr(mod, args.entrypoint): + print(f'{args.module} does not have a {args.entrypoint}() function, typo?') + sys.exit(1) + + with tempfile.TemporaryDirectory() as tmp: + for directory in DIRS: + shutil.copytree(BASEDIR + '/' + directory, tmp + '/' + directory, symlinks=False, dirs_exist_ok=True, copy_function=copy) + entry = f'{args.module}:{args.entrypoint}' + zipapp.create_archive(tmp, target=args.output, interpreter=INTERPRETER, main=entry) + + print(f'created executable {Path(args.output).resolve()}') diff --git a/release/release_files.py b/release/release_files.py index 5e9371c6fcc244..36910293a4c6ca 100755 --- a/release/release_files.py +++ b/release/release_files.py @@ -6,40 +6,11 @@ HERE = os.path.abspath(os.path.dirname(__file__)) ROOT = HERE + "/.." -# blacklisting is for two purposes: -# - minimizing release download size -# - keeping the diff readable blacklist = [ - "panda/drivers/", - "panda/examples/", - "panda/tests/safety/", - - "opendbc_repo/dbc/.*.dbc$", - "opendbc_repo/dbc/generator/", - - "cereal/.*test.*", - "^common/tests/", - - # particularly large text files - "uv.lock", - "third_party/catch2", - "selfdrive/car/tests/test_models.*", - - "^tools/", - "^tinygrad_repo/", - - "matlab.*.md", - ".git/", - ".github/", - ".devcontainer/", - "Darwin/", - ".vscode", + ".github/workflows/", - # common things - "LICENSE", - "Dockerfile", - ".pre-commit", + "matlab.*.md", # no LFS or submodules in release ".lfsconfig", @@ -49,78 +20,9 @@ ] # gets you through the blacklist -whitelist = [ - "tools/lib/", - "tools/bodyteleop/", - - "tinygrad_repo/openpilot/compile2.py", - "tinygrad_repo/extra/onnx.py", - "tinygrad_repo/extra/onnx_ops.py", - "tinygrad_repo/extra/thneed.py", - "tinygrad_repo/extra/utils.py", - "tinygrad_repo/tinygrad/codegen/kernel.py", - "tinygrad_repo/tinygrad/codegen/linearizer.py", - "tinygrad_repo/tinygrad/features/image.py", - "tinygrad_repo/tinygrad/features/search.py", - "tinygrad_repo/tinygrad/nn/*", - "tinygrad_repo/tinygrad/renderer/cstyle.py", - "tinygrad_repo/tinygrad/renderer/opencl.py", - "tinygrad_repo/tinygrad/runtime/lib.py", - "tinygrad_repo/tinygrad/runtime/ops_cpu.py", - "tinygrad_repo/tinygrad/runtime/ops_disk.py", - "tinygrad_repo/tinygrad/runtime/ops_gpu.py", - "tinygrad_repo/tinygrad/shape/*", - "tinygrad_repo/tinygrad/.*.py", - - # TODO: do this automatically - "opendbc_repo/dbc/comma_body.dbc", - "opendbc_repo/dbc/chrysler_ram_hd_generated.dbc", - "opendbc_repo/dbc/chrysler_ram_dt_generated.dbc", - "opendbc_repo/dbc/chrysler_pacifica_2017_hybrid_generated.dbc", - "opendbc_repo/dbc/chrysler_pacifica_2017_hybrid_private_fusion.dbc", - "opendbc_repo/dbc/gm_global_a_powertrain_generated.dbc", - "opendbc_repo/dbc/gm_global_a_object.dbc", - "opendbc_repo/dbc/gm_global_a_chassis.dbc", - "opendbc_repo/dbc/FORD_CADS.dbc", - "opendbc_repo/dbc/ford_fusion_2018_adas.dbc", - "opendbc_repo/dbc/ford_lincoln_base_pt.dbc", - "opendbc_repo/dbc/honda_accord_2018_can_generated.dbc", - "opendbc_repo/dbc/acura_ilx_2016_can_generated.dbc", - "opendbc_repo/dbc/acura_rdx_2018_can_generated.dbc", - "opendbc_repo/dbc/acura_rdx_2020_can_generated.dbc", - "opendbc_repo/dbc/honda_civic_touring_2016_can_generated.dbc", - "opendbc_repo/dbc/honda_civic_hatchback_ex_2017_can_generated.dbc", - "opendbc_repo/dbc/honda_crv_touring_2016_can_generated.dbc", - "opendbc_repo/dbc/honda_crv_ex_2017_can_generated.dbc", - "opendbc_repo/dbc/honda_crv_ex_2017_body_generated.dbc", - "opendbc_repo/dbc/honda_crv_executive_2016_can_generated.dbc", - "opendbc_repo/dbc/honda_fit_ex_2018_can_generated.dbc", - "opendbc_repo/dbc/honda_odyssey_exl_2018_generated.dbc", - "opendbc_repo/dbc/honda_odyssey_extreme_edition_2018_china_can_generated.dbc", - "opendbc_repo/dbc/honda_insight_ex_2019_can_generated.dbc", - "opendbc_repo/dbc/acura_ilx_2016_nidec.dbc", - "opendbc_repo/dbc/honda_civic_ex_2022_can_generated.dbc", - "opendbc_repo/dbc/hyundai_canfd.dbc", - "opendbc_repo/dbc/hyundai_kia_generic.dbc", - "opendbc_repo/dbc/hyundai_kia_mando_front_radar_generated.dbc", - "opendbc_repo/dbc/mazda_2017.dbc", - "opendbc_repo/dbc/nissan_x_trail_2017_generated.dbc", - "opendbc_repo/dbc/nissan_leaf_2018_generated.dbc", - "opendbc_repo/dbc/subaru_global_2017_generated.dbc", - "opendbc_repo/dbc/subaru_global_2020_hybrid_generated.dbc", - "opendbc_repo/dbc/subaru_outback_2015_generated.dbc", - "opendbc_repo/dbc/subaru_outback_2019_generated.dbc", - "opendbc_repo/dbc/subaru_forester_2017_generated.dbc", - "opendbc_repo/dbc/toyota_tnga_k_pt_generated.dbc", - "opendbc_repo/dbc/toyota_new_mc_pt_generated.dbc", - "opendbc_repo/dbc/toyota_nodsu_pt_generated.dbc", - "opendbc_repo/dbc/toyota_adas.dbc", - "opendbc_repo/dbc/toyota_tss2_adas.dbc", - "opendbc_repo/dbc/vw_golf_mk4.dbc", - "opendbc_repo/dbc/vw_mqb_2010.dbc", +whitelist: list[str] = [ ] - if __name__ == "__main__": for f in Path(ROOT).rglob("**/*"): if not (f.is_file() or f.is_symlink()): diff --git a/scripts/build_small.sh b/scripts/build_small.sh deleted file mode 100755 index 176ca5aaa8f92a..00000000000000 --- a/scripts/build_small.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env bash -set -ex - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -cd $DIR - -# git clone --mirror -SRC=/tmp/openpilot.git/ -OUT=/tmp/smallpilot/ - -echo "starting size $(du -hs .git/)" - -rm -rf $OUT - -cd $SRC -git remote update - -# copy contents -#rsync -a --exclude='.git/' $DIR $OUT - -cp -r $SRC $OUT - -cd $OUT - -# remove all tags -git tag -l | xargs git tag -d - -# remove non-master branches -BRANCHES="release2 release3 devel master-ci nightly" -for branch in $BRANCHES; do - git branch -D $branch - git branch -D ${branch}-staging || true -done - -#git gc -git reflog expire --expire=now --all -git gc --prune=now -git gc --aggressive --prune=now -echo "new one is $(du -hs .)" diff --git a/scripts/ci_results.py b/scripts/ci_results.py new file mode 100755 index 00000000000000..a133541c69ca50 --- /dev/null +++ b/scripts/ci_results.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Fetch CI results from GitHub Actions and Jenkins.""" + +import argparse +import json +import subprocess +import time +import urllib.error +import urllib.request +from datetime import datetime + +JENKINS_URL = "https://jenkins.comma.life" +DEFAULT_TIMEOUT = 1800 # 30 minutes +POLL_INTERVAL = 30 # seconds +LOG_TAIL_LINES = 10 # lines of log to include for failed jobs + + +def get_git_info(): + branch = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], text=True).strip() + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() + return branch, commit + + +def get_github_actions_status(commit_sha): + result = subprocess.run( + ["gh", "run", "list", "--commit", commit_sha, "--workflow", "tests.yaml", "--json", "databaseId,status,conclusion"], + capture_output=True, text=True, check=True + ) + runs = json.loads(result.stdout) + if not runs: + return None, None + + run_id = runs[0]["databaseId"] + result = subprocess.run( + ["gh", "run", "view", str(run_id), "--json", "jobs"], + capture_output=True, text=True, check=True + ) + data = json.loads(result.stdout) + jobs = {job["name"]: {"status": job["status"], "conclusion": job["conclusion"], + "duration": format_duration(job) if job["conclusion"] not in ("skipped", None) and job.get("startedAt") else "", + "id": job["databaseId"]} + for job in data.get("jobs", [])} + return jobs, run_id + + +def get_github_job_log(run_id, job_id): + result = subprocess.run( + ["gh", "run", "view", str(run_id), "--job", str(job_id), "--log-failed"], + capture_output=True, text=True + ) + lines = result.stdout.strip().split('\n') + return '\n'.join(lines[-LOG_TAIL_LINES:]) if len(lines) > LOG_TAIL_LINES else result.stdout.strip() + + +def format_duration(job): + start = datetime.fromisoformat(job["startedAt"].replace("Z", "+00:00")) + end = datetime.fromisoformat(job["completedAt"].replace("Z", "+00:00")) + secs = int((end - start).total_seconds()) + return f"{secs // 60}m {secs % 60}s" + + +def get_jenkins_status(branch, commit_sha): + base_url = f"{JENKINS_URL}/job/openpilot/job/{branch}" + try: + # Get list of recent builds + with urllib.request.urlopen(f"{base_url}/api/json?tree=builds[number,url]", timeout=10) as resp: + builds = json.loads(resp.read().decode()).get("builds", []) + + # Find build matching commit + for build in builds[:20]: # check last 20 builds + with urllib.request.urlopen(f"{build['url']}api/json", timeout=10) as resp: + data = json.loads(resp.read().decode()) + for action in data.get("actions", []): + if action.get("_class") == "hudson.plugins.git.util.BuildData": + build_sha = action.get("lastBuiltRevision", {}).get("SHA1", "") + if build_sha.startswith(commit_sha) or commit_sha.startswith(build_sha): + # Get stages info + stages = [] + try: + with urllib.request.urlopen(f"{build['url']}wfapi/describe", timeout=10) as resp2: + wf_data = json.loads(resp2.read().decode()) + stages = [{"name": s["name"], "status": s["status"]} for s in wf_data.get("stages", [])] + except urllib.error.HTTPError: + pass + return { + "number": data["number"], + "in_progress": data.get("inProgress", False), + "result": data.get("result"), + "url": data.get("url", ""), + "stages": stages, + } + return None # no build found for this commit + except urllib.error.HTTPError: + return None # branch doesn't exist on Jenkins + + +def get_jenkins_log(build_url): + url = f"{build_url}consoleText" + with urllib.request.urlopen(url, timeout=30) as resp: + text = resp.read().decode(errors='replace') + lines = text.strip().split('\n') + return '\n'.join(lines[-LOG_TAIL_LINES:]) if len(lines) > LOG_TAIL_LINES else text.strip() + + +def is_complete(gh_status, jenkins_status): + gh_done = gh_status is None or all(j["status"] == "completed" for j in gh_status.values()) + jenkins_done = jenkins_status is None or not jenkins_status.get("in_progress", True) + return gh_done and jenkins_done + + +def status_icon(status, conclusion=None): + if status == "completed": + return ":white_check_mark:" if conclusion == "success" else ":x:" + return ":hourglass:" if status == "in_progress" else ":grey_question:" + + +def format_markdown(gh_status, gh_run_id, jenkins_status, commit_sha, branch): + lines = ["# CI Results", "", + f"**Branch**: {branch}", + f"**Commit**: {commit_sha[:7]}", + f"**Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ""] + + lines.extend(["## GitHub Actions", "", "| Job | Status | Duration |", "|-----|--------|----------|"]) + failed_gh_jobs = [] + if gh_status: + for job_name, job in gh_status.items(): + icon = status_icon(job["status"], job.get("conclusion")) + conclusion = job.get("conclusion") or job["status"] + lines.append(f"| {job_name} | {icon} {conclusion} | {job.get('duration', '')} |") + if job.get("conclusion") == "failure": + failed_gh_jobs.append((job_name, job.get("id"))) + else: + lines.append("| - | No workflow runs found | |") + + lines.extend(["", "## Jenkins", "", "| Stage | Status |", "|-------|--------|"]) + failed_jenkins_stages = [] + if jenkins_status: + stages = jenkins_status.get("stages", []) + if stages: + for stage in stages: + icon = ":white_check_mark:" if stage["status"] == "SUCCESS" else ( + ":x:" if stage["status"] == "FAILED" else ":hourglass:") + lines.append(f"| {stage['name']} | {icon} {stage['status'].lower()} |") + if stage["status"] == "FAILED": + failed_jenkins_stages.append(stage["name"]) + # Show overall build status if still in progress + if jenkins_status["in_progress"]: + lines.append("| (build in progress) | :hourglass: in_progress |") + else: + icon = ":hourglass:" if jenkins_status["in_progress"] else ( + ":white_check_mark:" if jenkins_status["result"] == "SUCCESS" else ":x:") + status = "in progress" if jenkins_status["in_progress"] else (jenkins_status["result"] or "unknown") + lines.append(f"| #{jenkins_status['number']} | {icon} {status.lower()} |") + if jenkins_status.get("url"): + lines.append(f"\n[View build]({jenkins_status['url']})") + else: + lines.append("| - | No builds found for branch |") + + if failed_gh_jobs or failed_jenkins_stages: + lines.extend(["", "## Failure Logs", ""]) + + for job_name, job_id in failed_gh_jobs: + lines.append(f"### GitHub Actions: {job_name}") + log = get_github_job_log(gh_run_id, job_id) + lines.extend(["", "```", log, "```", ""]) + + for stage_name in failed_jenkins_stages: + lines.append(f"### Jenkins: {stage_name}") + log = get_jenkins_log(jenkins_status["url"]) + lines.extend(["", "```", log, "```", ""]) + + return "\n".join(lines) + "\n" + + +def main(): + parser = argparse.ArgumentParser(description="Fetch CI results from GitHub Actions and Jenkins") + parser.add_argument("--wait", action="store_true", help="Wait for CI to complete") + parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT, help="Timeout in seconds (default: 1800)") + parser.add_argument("-o", "--output", default="ci_results.md", help="Output file (default: ci_results.md)") + parser.add_argument("--branch", help="Branch to check (default: current branch)") + parser.add_argument("--commit", help="Commit SHA to check (default: HEAD)") + args = parser.parse_args() + + branch, commit = get_git_info() + branch = args.branch or branch + commit = args.commit or commit + print(f"Fetching CI results for {branch} @ {commit[:7]}") + + start_time = time.monotonic() + while True: + gh_status, gh_run_id = get_github_actions_status(commit) + jenkins_status = get_jenkins_status(branch, commit) if branch != "HEAD" else None + + if not args.wait or is_complete(gh_status, jenkins_status): + break + + elapsed = time.monotonic() - start_time + if elapsed >= args.timeout: + print(f"Timeout after {int(elapsed)}s") + break + + print(f"CI still running, waiting {POLL_INTERVAL}s... ({int(elapsed)}s elapsed)") + time.sleep(POLL_INTERVAL) + + content = format_markdown(gh_status, gh_run_id, jenkins_status, commit, branch) + with open(args.output, "w") as f: + f.write(content) + print(f"Results written to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/scripts/code_stats.py b/scripts/code_stats.py deleted file mode 100755 index 3189cd7cc1bd20..00000000000000 --- a/scripts/code_stats.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python3 -import os -import ast -import stat -import subprocess - -fouts = {x.decode('utf-8') for x in subprocess.check_output(['git', 'ls-files']).strip().split()} - -pyf = [] -for d in ["cereal", "common", "scripts", "selfdrive", "tools"]: - for root, _, files in os.walk(d): - for f in files: - if f.endswith(".py"): - pyf.append(os.path.join(root, f)) - -imps: set[str] = set() - -class Analyzer(ast.NodeVisitor): - def visit_Import(self, node): - for alias in node.names: - imps.add(alias.name) - self.generic_visit(node) - - def visit_ImportFrom(self, node): - imps.add(node.module) - self.generic_visit(node) - -tlns = 0 -carlns = 0 -scriptlns = 0 -testlns = 0 -for f in sorted(pyf): - if f not in fouts: - continue - xbit = bool(os.stat(f)[stat.ST_MODE] & stat.S_IXUSR) - src = open(f).read() - lns = len(src.split("\n")) - tree = ast.parse(src) - Analyzer().visit(tree) - print("%5d %s %s" % (lns, f, xbit)) - if 'test' in f: - testlns += lns - elif f.startswith(('tools/', 'scripts/', 'selfdrive/debug')): - scriptlns += lns - elif f.startswith('selfdrive/car'): - carlns += lns - else: - tlns += lns - -print("%d lines of openpilot python" % tlns) -print("%d lines of car ports" % carlns) -print("%d lines of tools/scripts/debug" % scriptlns) -print("%d lines of tests" % testlns) -#print(sorted(list(imps))) diff --git a/scripts/count_cars.py b/scripts/count_cars.py deleted file mode 100755 index 19f486735a7a58..00000000000000 --- a/scripts/count_cars.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python3 -from collections import Counter -from pprint import pprint - -from opendbc.car.docs import get_all_car_docs - -if __name__ == "__main__": - cars = get_all_car_docs() - make_count = Counter(l.make for l in cars) - print("\n", "*" * 20, len(cars), "total", "*" * 20, "\n") - pprint(make_count) diff --git a/scripts/docs.py b/scripts/docs.py new file mode 100644 index 00000000000000..d60bfb791f65f3 --- /dev/null +++ b/scripts/docs.py @@ -0,0 +1,63 @@ +""" + wrapper that materializes symlinks in docs/ before build + + we can delete this once zensical supports symlinks: + https://github.com/zensical/backlog/issues/55 +""" +import os +import shutil +import signal +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +DOCS_DIR = REPO_ROOT / "docs" +SITE_DIR = REPO_ROOT / "docs_site" +sys.path.insert(0, str(REPO_ROOT)) +# Local docs build helpers live under docs/ so they stay near the content +# source. The wrapper prunes them from docs_site/ after build. +sys.path.insert(0, str(DOCS_DIR)) + + +def _materialize(docs: Path) -> dict[Path, str]: + originals: dict[Path, str] = {} + for link in docs.rglob("*"): + if not link.is_symlink(): + continue + target = link.resolve() + if not target.is_file(): + continue + originals[link] = os.readlink(link) + link.unlink() + shutil.copy2(target, link) + return originals + + +def _restore(originals: dict[Path, str]) -> None: + for link, target in originals.items(): + link.unlink(missing_ok=True) + os.symlink(target, link) + + +def _raise_interrupt(*_): + raise KeyboardInterrupt + + +def _prune_site_output() -> None: + shutil.rmtree(SITE_DIR / "ext", ignore_errors=True) + + +def main() -> None: + signal.signal(signal.SIGTERM, _raise_interrupt) + originals = _materialize(DOCS_DIR) + try: + from zensical.main import cli + cli(standalone_mode=False) + if len(sys.argv) > 1 and sys.argv[1] == "build": + _prune_site_output() + finally: + _restore(originals) + + +if __name__ == "__main__": + main() diff --git a/scripts/generate_ff_table.py b/scripts/generate_ff_table.py new file mode 100755 index 00000000000000..07c2670dd15e75 --- /dev/null +++ b/scripts/generate_ff_table.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Generate a data-driven feedforward table for VirtualDAS. + +Reads drive logs and builds a 2D lookup table mapping (speed, accel) → pedal_di +by observing what pedal positions produced what accelerations at each speed. + +Usage: + python scripts/generate_ff_table.py /path/to/*.rlog.zst + +Output: /data/vdas_ff_table.json (or --output path) + +The script: + 1. Extracts (v_ego, actuators.accel, carState.aEgo) from logs where + longitudinal control was active and the car was moving + 2. Bins observations by speed and commanded accel + 3. For each bin, finds the median pedal_di that was being sent + 4. Builds the inverse: (speed, desired_accel) → pedal_di + 5. Writes JSON in the format FeedforwardModel expects +""" + +import argparse +import json +import sys + +import numpy as np + +from openpilot.tools.lib.logreader import LogReader + + +MIN_SPEED = 3.0 # m/s + +SPEED_BP = [0.0, 5.0, 12.0, 20.0, 30.0, 40.0] +ACCEL_BP = [-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5] + +# Delay between command and response — shift a_ego backward by this many seconds +ACTUATOR_DELAY = 0.4 + + +def extract_data(route_or_file: str): + """Extract time-aligned longitudinal data from a log.""" + lr = LogReader(route_or_file) + + cmd_data = [] # (time, accel_cmd) + ego_data = [] # (time, a_ego, v_ego) + + for msg in lr: + t = msg.logMonoTime / 1e9 + + if msg.which() == 'carControl' and msg.carControl.longActive: + cmd_data.append((t, float(msg.carControl.actuators.accel))) + + elif msg.which() == 'carState': + v = float(msg.carState.vEgo) + if v > MIN_SPEED: + ego_data.append((t, float(msg.carState.aEgo), v)) + + return cmd_data, ego_data + + +def build_table(all_cmd_data, all_ego_data): + """Build the 2D feedforward table from collected data. + + Strategy: for each (speed_bin, accel_cmd_bin), find what a_ego resulted + after the actuator delay. Then invert: the accel_cmd that produced a + given a_ego at a given speed tells us what pedal position to use for + that desired acceleration. + + Since we don't have direct pedal_di in the logs, we use accel_cmd as + a proxy for the feedforward output. The table then maps + (speed, desired_accel) → accel_cmd_that_achieved_it, which is what the + feedforward should output (the current linear interp's job). + """ + if not all_cmd_data or not all_ego_data: + return None + + cmd_t = np.array([d[0] for d in all_cmd_data]) + cmd_a = np.array([d[1] for d in all_cmd_data]) + + ego_t = np.array([d[0] for d in all_ego_data]) + ego_a = np.array([d[1] for d in all_ego_data]) + ego_v = np.array([d[2] for d in all_ego_data]) + + # Resample cmd to ego timestamps (shifted by delay) + cmd_at_ego = np.interp(ego_t - ACTUATOR_DELAY, cmd_t, cmd_a) + + # Bin by speed and commanded accel, collect achieved accel + speed_edges = [(SPEED_BP[i] + SPEED_BP[i+1]) / 2 for i in range(len(SPEED_BP) - 1)] + accel_edges = [(ACCEL_BP[i] + ACCEL_BP[i+1]) / 2 for i in range(len(ACCEL_BP) - 1)] + + from opendbc.car.tesla.preap.ff_table_default import DEFAULT_TABLE + + # For each (speed, accel_cmd) bin, compute a correction factor from + # observed (commanded vs achieved) accel, then scale the default DI. + table = [] + for si, _s_target in enumerate(SPEED_BP): + if si == 0: + s_lo, s_hi = 0.0, speed_edges[0] if speed_edges else 100.0 + elif si == len(SPEED_BP) - 1: + s_lo, s_hi = speed_edges[-1], 100.0 + else: + s_lo, s_hi = speed_edges[si-1], speed_edges[si] + + s_mask = (ego_v >= s_lo) & (ego_v < s_hi) + + row = [] + for ai, _a_target in enumerate(ACCEL_BP): + if ai == 0: + a_lo, a_hi = -10.0, accel_edges[0] if accel_edges else 10.0 + elif ai == len(ACCEL_BP) - 1: + a_lo, a_hi = accel_edges[-1], 10.0 + else: + a_lo, a_hi = accel_edges[ai-1], accel_edges[ai] + + a_mask = (cmd_at_ego >= a_lo) & (cmd_at_ego < a_hi) + combined = s_mask & a_mask + + default_di = DEFAULT_TABLE[si][ai] + if combined.sum() > 5: + achieved = np.median(ego_a[combined]) + cmd_median = np.median(cmd_at_ego[combined]) + if abs(achieved) > 0.05 and abs(cmd_median) > 0.05: + correction = cmd_median / achieved + else: + correction = 1.0 + row.append(round(float(default_di * correction), 2)) + else: + row.append(default_di) + + table.append(row) + + return { + 'speed_bp': SPEED_BP, + 'accel_bp': ACCEL_BP, + 'table': table, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('logs', nargs='+', help='rlog files or route identifiers') + parser.add_argument('--output', default=FF_TABLE_PATH, + help=f'output JSON path (default: {FF_TABLE_PATH})') + args = parser.parse_args() + + all_cmd, all_ego = [], [] + + for log_path in args.logs: + print(f"Reading: {log_path}") + try: + cmd, ego = extract_data(log_path) + all_cmd.extend(cmd) + all_ego.extend(ego) + print(f" cmd={len(cmd)}, ego={len(ego)}") + except Exception as e: + print(f" Error: {e}") + + print(f"\nTotal: cmd={len(all_cmd)}, ego={len(all_ego)}") + + if not all_cmd or not all_ego: + print("Not enough data to build table.") + sys.exit(1) + + result = build_table(all_cmd, all_ego) + if result is None: + print("Failed to build table.") + sys.exit(1) + + output = args.output + with open(output, 'w') as f: + json.dump(result, f, indent=2) + + print(f"\nTable written to: {output}") + print(f"Speed breakpoints: {result['speed_bp']}") + print(f"Accel breakpoints: {result['accel_bp']}") + for i, row in enumerate(result['table']): + print(f" {result['speed_bp'][i]:5.1f} m/s: {row}") + + +FF_TABLE_PATH = "/data/vdas_ff_table.json" + +if __name__ == '__main__': + main() diff --git a/scripts/git_rewrite/rewrite-git-history.sh b/scripts/git_rewrite/rewrite-git-history.sh deleted file mode 100755 index cce4455ce5be13..00000000000000 --- a/scripts/git_rewrite/rewrite-git-history.sh +++ /dev/null @@ -1,391 +0,0 @@ -#!/usr/bin/env bash -set -e - -SRC=/tmp/openpilot/ -SRC_CLONE=/tmp/openpilot-clone/ -OUT=/tmp/openpilot-tiny/ - -REWRITE_IGNORE_BRANCHES=( - dashcam3 - devel - master-ci - nightly - release2 - release3 - release3-staging -) - -VALIDATE_IGNORE_FILES=( - ".github/ISSUE_TEMPLATE/bug_report.md" - ".github/pull_request_template.md" -) - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -cd $DIR - -LOGS_DIR=$DIR/git-rewrite-$(date +"%Y-%m-%dT%H:%M:%S%z") -mkdir -p $LOGS_DIR - -GIT_REWRITE_LOG=$LOGS_DIR/git-rewrite-log.txt -BRANCH_DIFF_LOG=$LOGS_DIR/branch-diff-log.txt -COMMIT_DIFF_LOG=$LOGS_DIR/commit-diff-log.txt - -START_TIME=$(date +%s) -exec > >(while IFS= read -r line; do - CURRENT_TIME=$(date +%s) - ELAPSED_TIME=$((CURRENT_TIME - START_TIME)) - echo "[${ELAPSED_TIME}s] $line" -done | tee -a "$GIT_REWRITE_LOG") 2>&1 - -# INSTALL git-filter-repo -if [ ! -f /tmp/git-filter-repo ]; then - echo "Installing git-filter-repo..." - curl -sSo /tmp/git-filter-repo https://raw.githubusercontent.com/newren/git-filter-repo/main/git-filter-repo - chmod +x /tmp/git-filter-repo -fi - -# MIRROR openpilot -if [ ! -d $SRC ]; then - echo "Mirroring openpilot..." - git clone --mirror https://github.com/commaai/openpilot.git $SRC # 4.18 GiB (488034 objects) - - cd $SRC - - echo "Starting size $(du -sh .)" - - git remote update - - # the git-filter-repo analysis is bliss - can be found in the repo root/filter-repo/analysis - echo "Analyzing with git-filter-repo..." - /tmp/git-filter-repo --force --analyze - - echo "Pushing to openpilot-archive..." - # push to archive repo - in smaller parts because the 2 GB push limit - https://docs.github.com/en/get-started/using-git/troubleshooting-the-2-gb-push-limit - ARCHIVE_REPO=git@github.com:commaai/openpilot-archive.git - git push --prune $ARCHIVE_REPO +refs/heads/master:refs/heads/master # push master first so it's the default branch (when openpilot-archive is an empty repo) - git push --prune $ARCHIVE_REPO +refs/heads/*:refs/heads/* # 956.39 MiB (110725 objects) - git push --prune $ARCHIVE_REPO +refs/tags/*:refs/tags/* # 1.75 GiB (21694 objects) - # git push --mirror $ARCHIVE_REPO || true # fails to push refs/pull/* (deny updating a hidden ref) for pull requests - # we fail and continue - more reading: https://stackoverflow.com/a/34266401/639708 and https://blog.plataformatec.com.br/2013/05/how-to-properly-mirror-a-git-repository/ -fi - -# REWRITE master and tags -if [ ! -d $SRC_CLONE ]; then - echo "Cloning $SRC..." - GIT_LFS_SKIP_SMUDGE=1 git clone $SRC $SRC_CLONE - - cd $SRC_CLONE - - echo "Checking out old history..." - - git checkout tags/v0.7.1 > /dev/null 2>&1 - # checkout as main, since we need master ref later - git checkout -b main - - echo "Creating setup commits..." - - # rm these so we don't get conflicts later - git rm -r cereal opendbc panda selfdrive/ui/ui > /dev/null - git commit -m "removed conflicting files" > /dev/null - - # skip-smudge to get rid of some lfs errors that it can't find the reference of some lfs files - # we don't care about fetching/pushing lfs right now - git lfs install --skip-smudge --local - - # squash initial setup commits - git cherry-pick -n -X theirs 6c33a5c..59b3d06 > /dev/null - git commit -m "switching to master" > /dev/null - - # squash the two commits - git reset --soft HEAD~2 - git commit -m "switching to master" -m "$(git log --reverse --format=%B 6c33a5c..59b3d06)" -m "removed conflicting files" > /dev/null - - # get commits we want to cherry-pick - # will start with the next commit after #59b3d06 tools is local now - COMMITS=$(git rev-list --reverse 59b3d06..master) - - # we need this for logging - TOTAL_COMMITS=$(echo $COMMITS | wc -w | xargs) - CURRENT_COMMIT_NUMBER=0 - - # empty this file - > commit-map.txt - - echo "Rewriting master commits..." - - for COMMIT in $COMMITS; do - CURRENT_COMMIT_NUMBER=$((CURRENT_COMMIT_NUMBER + 1)) - # echo -ne "[$CURRENT_COMMIT_NUMBER/$TOTAL_COMMITS] Cherry-picking commit: $COMMIT"\\r - echo "[$CURRENT_COMMIT_NUMBER/$TOTAL_COMMITS] Cherry-picking commit: $COMMIT" - - # set environment variables to preserve author/committer and dates - export GIT_AUTHOR_NAME=$(git show -s --format='%an' $COMMIT) - export GIT_AUTHOR_EMAIL=$(git show -s --format='%ae' $COMMIT) - export GIT_COMMITTER_NAME=$(git show -s --format='%cn' $COMMIT) - export GIT_COMMITTER_EMAIL=$(git show -s --format='%ce' $COMMIT) - export GIT_AUTHOR_DATE=$(git show -s --format='%ad' $COMMIT) - export GIT_COMMITTER_DATE=$(git show -s --format='%cd' $COMMIT) - - # cherry-pick the commit - if ! GIT_OUTPUT=$(git cherry-pick -m 1 -X theirs $COMMIT 2>&1); then - # check if the failure is because of an empty commit - if [[ "$GIT_OUTPUT" == *"The previous cherry-pick is now empty"* ]]; then - echo "Empty commit detected. Skipping commit $COMMIT" - git cherry-pick --skip - # log it was empty to the mapping file - echo "$COMMIT EMPTY" >> commit-map.txt - else - # handle other errors or conflicts - echo "Cherry-pick failed. Handling error..." - echo "$GIT_OUTPUT" - exit 1 - fi - else - # capture the new commit hash - NEW_COMMIT=$(git rev-parse HEAD) - - # save the old and new commit hashes to the mapping file - echo "$COMMIT $NEW_COMMIT" >> commit-map.txt - - # append the old commit ID to the commit message - git commit --amend -m "$(git log -1 --pretty=%B)" -m "Former-commit-id: $COMMIT" > /dev/null - fi - - # prune every 3000 commits to avoid gc errors - if [ $((CURRENT_COMMIT_NUMBER % 3000)) -eq 0 ]; then - echo "Pruning repo..." - git gc - fi - done - - echo "Rewriting tags..." - - # remove all old tags - git tag -l | xargs git tag -d - - # read each line from the tag-commit-map.txt - while IFS=' ' read -r TAG OLD_COMMIT; do - # search for the new commit in commit-map.txt corresponding to the old commit - NEW_COMMIT=$(grep "^$OLD_COMMIT " "commit-map.txt" | awk '{print $2}') - - # check if this is a rebased commit - if [ -z "$NEW_COMMIT" ]; then - # if not, then just use old commit hash - NEW_COMMIT=$OLD_COMMIT - fi - - echo "Rewriting tag $TAG from commit $NEW_COMMIT" - git tag -f "$TAG" "$NEW_COMMIT" - done < "$DIR/tag-commit-map.txt" - - # uninstall lfs since we don't want to touch (push to) lfs right now - # git push will also push lfs, if we don't uninstall (--local so just for this repo) - git lfs uninstall --local - - # force push new master - git push --force origin main:master - - # force push new tags - git push --force --tags -fi - -# REWRITE branches based on master -if [ ! -f "$SRC_CLONE/rewrite-branches-done" ]; then - cd $SRC_CLONE - > rewrite-branches-done - - # empty file - > $BRANCH_DIFF_LOG - - echo "Rewriting branches based on master..." - - # will store raw diffs here, if exist - mkdir -p differences - - # get a list of all branches except master and REWRITE_IGNORE_BRANCHES - BRANCHES=$(git branch -r | grep -v ' -> ' | sed 's/.*origin\///' | grep -v '^master$' | grep -v -f <(echo "${REWRITE_IGNORE_BRANCHES[*]}" | tr ' ' '\n')) - - for BRANCH in $BRANCHES; do - # check if the branch is based on master history - MERGE_BASE=$(git merge-base master origin/$BRANCH) || true - if [ -n "$MERGE_BASE" ]; then - echo "Rewriting branch: $BRANCH" - - # create a new branch based on the new master - NEW_MERGE_BASE=$(grep "^$MERGE_BASE " "commit-map.txt" | awk '{print $2}') - if [ -z "$NEW_MERGE_BASE" ]; then - echo "Error: could not find new merge base for branch $BRANCH" >> $BRANCH_DIFF_LOG - continue - fi - git checkout -b ${BRANCH}_new $NEW_MERGE_BASE - - # get the range of commits unique to this branch - COMMITS=$(git rev-list --reverse $MERGE_BASE..origin/${BRANCH}) - - HAS_ERROR=0 - - # simple delimiter - echo "BRANCH ${BRANCH}" >> commit-map.txt - - for COMMIT in $COMMITS; do - # set environment variables to preserve author/committer and dates - export GIT_AUTHOR_NAME=$(git show -s --format='%an' $COMMIT) - export GIT_AUTHOR_EMAIL=$(git show -s --format='%ae' $COMMIT) - export GIT_COMMITTER_NAME=$(git show -s --format='%cn' $COMMIT) - export GIT_COMMITTER_EMAIL=$(git show -s --format='%ce' $COMMIT) - export GIT_AUTHOR_DATE=$(git show -s --format='%ad' $COMMIT) - export GIT_COMMITTER_DATE=$(git show -s --format='%cd' $COMMIT) - - # cherry-pick the commit - if ! GIT_OUTPUT=$(git cherry-pick -m 1 -X theirs $COMMIT 2>&1); then - # check if the failure is because of an empty commit - if [[ "$GIT_OUTPUT" == *"The previous cherry-pick is now empty"* ]]; then - echo "Empty commit detected. Skipping commit $COMMIT" - git cherry-pick --skip - # log it was empty to the mapping file - echo "$COMMIT EMPTY" >> commit-map.txt - else - # handle other errors or conflicts - echo "Cherry-pick of ${BRANCH} branch failed. Removing branch upstream..." >> $BRANCH_DIFF_LOG - echo "$GIT_OUTPUT" > "$LOGS_DIR/branch-${BRANCH}" - git cherry-pick --abort - git push --delete origin ${BRANCH} - HAS_ERROR=1 - break - fi - else - # capture the new commit hash - NEW_COMMIT=$(git rev-parse HEAD) - - # save the old and new commit hashes to the mapping file - echo "$COMMIT $NEW_COMMIT" >> commit-map.txt - - # append the old commit ID to the commit message - git commit --amend -m "$(git log -1 --pretty=%B)" -m "Former-commit-id: $COMMIT" > /dev/null - fi - done - - # force push the new branch - if [ $HAS_ERROR -eq 0 ]; then - # git lfs goes haywire here, so we need to install and uninstall - # git lfs install --skip-smudge --local - git lfs uninstall --local > /dev/null - git push -f origin ${BRANCH}_new:${BRANCH} - fi - - # clean up local branch - git checkout master > /dev/null - git branch -D ${BRANCH}_new > /dev/null - else - echo "Deleting branch $BRANCH as it's not based on master history" >> $BRANCH_DIFF_LOG - git push --delete origin ${BRANCH} - fi - done -fi - -# VALIDATE cherry-pick -if [ ! -f "$SRC_CLONE/validation-done" ]; then - cd $SRC_CLONE - > validation-done - - TOTAL_COMMITS=$(grep -cve '^\s*$' commit-map.txt) - CURRENT_COMMIT_NUMBER=0 - COUNT_SAME=0 - COUNT_DIFF=0 - - # empty file - > $COMMIT_DIFF_LOG - - echo "Validating commits..." - - # will store raw diffs here, if exist - mkdir -p differences - - # read each line from commit-map.txt - while IFS=' ' read -r OLD_COMMIT NEW_COMMIT; do - if [ "$NEW_COMMIT" == "EMPTY" ]; then - continue - fi - if [ "$OLD_COMMIT" == "BRANCH" ]; then - echo "Branch ${NEW_COMMIT} below:" >> $COMMIT_DIFF_LOG - continue - fi - CURRENT_COMMIT_NUMBER=$((CURRENT_COMMIT_NUMBER + 1)) - # retrieve short hashes and dates for the old and new commits - OLD_COMMIT_SHORT=$(git rev-parse --short $OLD_COMMIT) - NEW_COMMIT_SHORT=$(git rev-parse --short $NEW_COMMIT) - OLD_DATE=$(git show -s --format='%cd' $OLD_COMMIT) - NEW_DATE=$(git show -s --format='%cd' $NEW_COMMIT) - - # echo -ne "[$CURRENT_COMMIT_NUMBER/$TOTAL_COMMITS] Comparing old commit $OLD_COMMIT_SHORT ($OLD_DATE) with new commit $NEW_COMMIT_SHORT ($NEW_DATE)"\\r - echo "[$CURRENT_COMMIT_NUMBER/$TOTAL_COMMITS] Comparing old commit $OLD_COMMIT_SHORT ($OLD_DATE) with new commit $NEW_COMMIT_SHORT ($NEW_DATE)" - - # generate lists of files and their hashes for the old and new commits, excluding ignored files - OLD_FILES=$(git ls-tree -r $OLD_COMMIT | grep -vE "$(IFS='|'; echo "${VALIDATE_IGNORE_FILES[*]}")") - NEW_FILES=$(git ls-tree -r $NEW_COMMIT | grep -vE "$(IFS='|'; echo "${VALIDATE_IGNORE_FILES[*]}")") - - # Compare the diffs - if diff <(echo "$OLD_FILES") <(echo "$NEW_FILES") > /dev/null; then - # echo "Old commit $OLD_COMMIT_SHORT and new commit $NEW_COMMIT_SHORT are equivalent." - COUNT_SAME=$((COUNT_SAME + 1)) - else - echo "[$CURRENT_COMMIT_NUMBER/$TOTAL_COMMITS] Difference found between old commit $OLD_COMMIT_SHORT and new commit $NEW_COMMIT_SHORT" >> $COMMIT_DIFF_LOG - COUNT_DIFF=$((COUNT_DIFF + 1)) - set +e - diff -u <(echo "$OLD_FILES") <(echo "$NEW_FILES") > "$LOGS_DIR/commit-$CURRENT_COMMIT_NUMBER-$OLD_COMMIT_SHORT-$NEW_COMMIT_SHORT" - set -e - fi - done < "commit-map.txt" - - echo "Summary:" >> $COMMIT_DIFF_LOG - echo "Equivalent commits: $COUNT_SAME" >> $COMMIT_DIFF_LOG - echo "Different commits: $COUNT_DIFF" >> $COMMIT_DIFF_LOG -fi - -if [ ! -d $OUT ]; then - cp -r $SRC $OUT - - cd $OUT - - # remove all non-master branches - # git branch | grep -v "^ master$" | grep -v "\*" | xargs git branch -D - - # echo "cleaning up refs" - # delete pull request refs since we can't alter them anyway (https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/checking-out-pull-requests-locally#error-failed-to-push-some-refs) - # git for-each-ref --format='%(refname)' | grep '^refs/pull/' | xargs -I {} git update-ref -d {} - - echo "importing new lfs files" - # import "almost" everything to lfs - BRANCHES=$(git for-each-ref --format='%(refname)' refs/heads/ | sed 's%refs/heads/%%g' | grep -v -f <(echo "${REWRITE_IGNORE_BRANCHES[*]}" | tr ' ' '\n') | tr '\n' ' ') - git lfs migrate import --include="*.dlc,*.onnx,*.svg,*.png,*.gif,*.ttf,*.wav,selfdrive/car/tests/test_models_segs.txt,system/hardware/tici/updater,selfdrive/ui/qt/spinner_larch64,selfdrive/ui/qt/text_larch64,third_party/**/*.a,third_party/**/*.so,third_party/**/*.so.*,third_party/**/*.dylib,third_party/acados/*/t_renderer,third_party/qt5/larch64/bin/lrelease,third_party/qt5/larch64/bin/lupdate,third_party/catch2/include/catch2/catch.hpp,*.apk,*.apkpatch,*.jar,*.pdf,*.jpg,*.mp3,*.thneed,*.tar.gz,*.npy,*.csv,*.a,*.so*,*.dylib,*.o,*.b64,selfdrive/hardware/tici/updater,selfdrive/boardd/tests/test_boardd,selfdrive/ui/qt/spinner_aarch64,installer/updater/updater,selfdrive/debug/profiling/simpleperf/**/*,selfdrive/hardware/eon/updater,selfdrive/ui/qt/text_aarch64,selfdrive/debug/profiling/pyflame/**/*,installer/installers/installer_openpilot,installer/installers/installer_dashcam,selfdrive/ui/text/text,selfdrive/ui/android/text/text,selfdrive/ui/spinner/spinner,selfdrive/visiond/visiond,selfdrive/loggerd/loggerd,selfdrive/sensord/sensord,selfdrive/sensord/gpsd,selfdrive/ui/android/spinner/spinner,selfdrive/ui/qt/spinner,selfdrive/ui/qt/text,_stringdefs.py,dfu-util-aarch64-linux,dfu-util-aarch64,dfu-util-x86_64-linux,dfu-util-x86_64,stb_image.h,clpeak3,clwaste,apk/**/*,external/**/*,phonelibs/**/*,third_party/boringssl/**/*,flask/**/*,panda/**/*,board/**/*,messaging/**/*,opendbc/**/*,tools/cabana/chartswidget.cc,third_party/nanovg/**/*,selfdrive/controls/lib/lateral_mpc/lib_mpc_export/**/*,selfdrive/ui/paint.cc,werkzeug/**/*,pyextra/**/*,third_party/android_hardware_libhardware/**/*,selfdrive/controls/lib/lead_mpc_lib/lib_mpc_export/**/*,selfdrive/locationd/laikad.py,selfdrive/locationd/test/test_laikad.py,tools/gpstest/test_laikad.py,selfdrive/locationd/laikad_helpers.py,tools/nui/**/*,jsonrpc/**/*,selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/**/*,selfdrive/controls/lib/lateral_mpc/mpc_export/**/*,selfdrive/camerad/cameras/camera_qcom.cc,selfdrive/manager.py,selfdrive/modeld/models/driving.cc,third_party/curl/**/*,selfdrive/modeld/thneed/debug/**/*,selfdrive/modeld/thneed/include/**/*,third_party/openmax/**/*,selfdrive/controls/lib/longitudinal_mpc/mpc_export/**/*,selfdrive/controls/lib/longitudinal_mpc_model/lib_mpc_export/**/*,Pipfile,Pipfile.lock,gunicorn/**/*,*.qm,jinja2/**/*,click/**/*,dbcs/**/*,websocket/**/*" $BRANCHES - - echo "reflog and gc" - # this is needed after lfs import - git reflog expire --expire=now --all - git gc --prune=now --aggressive - - # check the git-filter-repo analysis again - can be found in the repo root/filter-repo/analysis - echo "Analyzing with git-filter-repo..." - /tmp/git-filter-repo --force --analyze - - echo "New size is $(du -sh .)" -fi - -cd $OUT - -# fetch all lfs files from https://github.com/commaai/openpilot.git -# some lfs files are missing on gitlab, but they can be found on github -git config lfs.url https://github.com/commaai/openpilot.git/info/lfs -git config lfs.pushurl ssh://git@github.com/commaai/openpilot.git -git lfs fetch --all || true - -# also fetch all lfs files from https://gitlab.com/commaai/openpilot-lfs.git -git config lfs.url https://gitlab.com/commaai/openpilot-lfs.git/info/lfs -git config lfs.pushurl ssh://git@gitlab.com/commaai/openpilot-lfs.git -git lfs fetch --all || true - -# final push - will also push lfs -# TODO: switch to git@github.com:commaai/openpilot.git when ready -# git push --mirror git@github.com:commaai/openpilot-tiny.git -# using this instead to ignore refs/pull/* - since this is also what --mirror does - https://blog.plataformatec.com.br/2013/05/how-to-properly-mirror-a-git-repository/ -git push --prune git@github.com:commaai/openpilot-tiny.git +refs/heads/*:refs/heads/* +refs/tags/*:refs/tags/* diff --git a/scripts/git_rewrite/rewrite.sh b/scripts/git_rewrite/rewrite.sh deleted file mode 100755 index 8a18b15bec9e03..00000000000000 --- a/scripts/git_rewrite/rewrite.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -cd $DIR - -git clone --bare https://github.com/commaai/openpilot -cp -r openpilot.git openpilot_backup -cd openpilot.git - -# backup old repo -git push git@github.com:commaai/openpilot-archive.git +refs/heads/master:refs/heads/master -git push git@github.com:commaai/openpilot-archive.git +refs/heads/*:refs/heads/* -git push git@github.com:commaai/openpilot-archive.git +refs/tags/*:refs/tags/* -git push --mirror git@github.com:commaai/openpilot-archive.git - -# ignore all release branches -git for-each-ref --format='delete %(refname)' | grep 'dashcam3\|devel\|master-ci\|nightly\|release2\|release3\|release3-staging' | git update-ref --stdin - -# re-tag old releases on master -declare -A TAGS=( ["f8cb04e4a8b032b72a909f68b808a50936184bee"]="v0.9.7" ["0b4d08fab8e35a264bc7383e878538f8083c33e5"]="v0.9.6" ["3b1e9017c560499786d8a0e46aaaeea65037acac"]="v0.9.5" ["fa310d9e2542cf497d92f007baec8fd751ffa99c"]="v0.9.4" ["8704c1ff952b5c85a44f50143bbd1a4f7b4887e2"]="v0.9.3" ["c7d3b28b93faa6c955fb24bc64031512ee985ee9"]="v0.9.2" ["89f68bf0cbf53a81b0553d3816fdbe522f941fa1"]="v0.9.1" ["58b84fb401a804967aa0dd5ee66fafa90194fd30"]="v0.9.0" ["f41dc62a12cc0f3cb8c5453c0caa0ba21e1bd01e"]="v0.8.16" ["5a7c2f90361e72e9c35e88abd2e11acdc4aba354"]="v0.8.15" ["71901c94dbbaa2f9f156a80c14cc7ea65219fc7c"]="v0.8.14" ["95da47079510afc91665263619e5939126da637c"]="v0.8.13" ["472177e2a8a1d002e56f9096326fd2dff62e54f9"]="v0.8.12" ["08078acbd0b4f7da469c7dff6159000e358974a9"]="v0.8.11" ["687925c775c375495f9827946138a724bde00b9d"]="v0.8.10" ["204e5a090735a059d69c29145a4cee49450da07e"]="v0.8.9" ["4be956f8861ecbb521ef9503a3c87b07c9d36721"]="v0.8.8" ["589f82c76627d634761a31a34b2488403556eb0b"]="v0.8.7" ["507cfc8910f74ddb8810039d68b880b426ff9ff9"]="v0.8.6" ["d47b00b45a866bef088f51d1ff31de5885ab04e9"]="v0.8.5" ["553e7d1cce314e7eb0587186b1764c3ff43bed62"]="v0.8.4" ["9896438d1511602a1ff87f7c4eb3c7172b30104a"]="v0.8.3" ["280192ed1443f112463417c2d815ea8ee2762fbd"]="v0.8.2" ["8039361567e4659eae2a084e6f39f34acadf4cac"]="v0.8.1" ["d56e04c0d960c8d3d4ab88b578dc508a2b4e07dc"]="v0.8" ["3d456e5d0fbf0c9887d0499dee812f2b029edf6d"]="v0.7.10" ["81763a18b5d0e379b749e090ecce36a91fca7c43"]="v0.7.9" ["9bc0b350fd273bbb2deb3dcaef0312944e4f6cfd"]="v0.7.8" ["ede5b632b58c55e4ff003f948efae07fe03c2280"]="v0.7.7" ["775acd11ba2e0a8c2f5a5655338718d796491b36"]="v0.7.6.1" ["302417b4cf0dcf00d45e4995b5410e543ad121d1"]="v0.7.5" ["12ff088b42221dd17d9d97decb1fc61a7cb0a861"]="v0.7.4" ["9563f7730252451fdcba9bc3d9fe36dab9c86a26"]="v0.7.3" ["8321cf283abbc2ca3fda7e0c7a069a77a492fe0c"]="v0.7.2" ["1e1de64a1e59476b7b3d3558b92149246d5c3292"]="v0.7.1" ["a2ae18d1dbd1e59c38ce22fa25ddffbd1d3084e3"]="v0.7" ["d4eb5a6eafdd4803d09e6f3963918216cca5a81f"]="v0.6.6" ["70d17cd69b80e7627dcad8fd5b6438f2309ac307"]="v0.6.5" ["58f376002e0c654fbc2de127765fa297cf694a33"]="v0.6.4" ["d5f9caa82d80cdcc7f1b7748f2cf3ccbf94f82a3"]="v0.6.3" ["095ef5f9f60fca1b269aabcc3cfd322b17b9e674"]="v0.6.2" ["cf5c4aeacb1703d0ffd35bdb5297d3494fee9a22"]="v0.6.1" ["60a20537c5f3fcc7f11946d81aebc8f90c08c117"]="v0.6" ["dd34ccfe288ebda8e2568cf550994ae890379f45"]="v0.5.13" ["3f9059fea886f1fa3b0c19a62a981d891dcc84eb"]="v0.5.12" ["2f92d577f995ff6ae1945ef6b89df3cb69b92999"]="v0.5.11" ["5a9d89ed42ddcd209d001a10d7eb828ef0e6d9de"]="v0.5.10" ["0207a970400ee28d3e366f2e8f5c551281accf02"]="v0.5.9" ["b967da5fc1f7a07e3561db072dd714d325e857b0"]="v0.5.8" ["210db686bb89f8696aa040e6e16de65424b808c9"]="v0.5.7" ["860a48765d1016ba226fb2c64aea35a45fe40e4a"]="v0.5.6" ["8f3539a27b28851153454eb737da9624cccaed2d"]="v0.5.5" ["a422246dc30bce11e970514f13f7c110f4470cc3"]="v0.5.4" ["285c52eb693265a0a530543e9ca0aeb593a2a55e"]="v0.5.3" ["0129a8a4ff8da5314e8e4d4d3336e89667ff6d54"]="v0.5.2" ["6f3d10a4c475c4c4509f0b370805419acd13912d"]="v0.5.1" ["de33bc46452b1046387ee2b3a03191b2c71135fb"]="v0.5" ["ae5cb7a0dab8b1bed9d52292f9b4e8e66a0f8ec9"]="v0.4.7" ["c6df34f55ba8c5a911b60d3f9eb20e3fa45f68c1"]="v0.4.6" ["37285038d3f91fa1b49159c4a35a8383168e644f"]="v0.4.5" ["9a9ff839a9b70cb2601d7696af743f5652395389"]="v0.4.4" ["28c0797d30175043bbfa31307b63aab4197cf996"]="v0.4.2" ["4474b9b3718653aeb0aee26422caefb90460cc0e"]="v0.4.1" ["da52d065a4c4f52d6017a537f3a80326f5af8bdc"]="v0.4.0.2" ["9d3963559ae7b15193057937ff3e72481899f40d"]="v0.3.5" ["1b8c44b5067525a5d266b6e99799d8097da76a29"]="v0.3.4" ["5cf91d0496688fed4f2a6c7021349b1fc0e057a2"]="v0.3.3" ["7fe46f1e1df5dec08a940451ba0feefd5c039165"]="v0.3.2" ["41e3a0f699f5c39cb61a15c0eb7a4aa816d47c24"]="v0.3.1" ["c5d8aec28b5230d34ae4b677c2091cc3dec7e3e8"]="v0.3.0" ["693bcb0f83478f2651db6bac9be5ca5ad60d03f3"]="v0.2.9" ["95a349abcc050712c50d4d85a1c8a804eee7f6c2"]="v0.2.8" ["c6ba5dc5391d3ca6cda479bf1923b88ce45509a0"]="v0.2.7" ["6c3afeec0fb439070b2912978b8dbb659033b1d9"]="v0.2.6" ["29c58b45882ac79595356caf98580c1d2a626011"]="v0.2.5" ["ecc565aa3fdc4c7e719aadc000e1fdc4d80d4fe0"]="v0.2.4" ["adaa4ed350acda4067fc0b455ad15b54cdf4c768"]="v0.2.3" ["a64b9aa9b8cb5863c917b6926516291a63c02fe5"]="v0.2.2" ["17d9becd3c673091b22f09aa02559a9ed9230f50"]="v0.2.1" ["449b482cc3236ccf31829830b4f6a44b2dcc06c2"]="v0.2" ["e94a30bec07e719c5a7b037ca1f4db8312702cce"]="v0.1" ) -for tag in "${!TAGS[@]}"; do git tag -f "${TAGS[$tag]}" "$tag" ; done - -# get master root commit -ROOT_COMMIT=$(git rev-list --max-parents=0 HEAD | tail -n 1) - -# link master and devel -git replace --graft $ROOT_COMMIT v0.7.1 -git-filter-repo --prune-empty never --force --commit-callback 'h=commit.original_id.decode("utf-8");m=commit.message.decode("utf-8");commit.message=str.encode(m + "\n" + "old-commit-hash: " + h)' - -# delete replace refs -git for-each-ref --format='delete %(refname)' refs/replace | git update-ref --stdin - -# machine validation -tail -n +2 "filter-repo/commit-map" | tr ' ' '\n' | xargs -P $(nproc) -n 2 bash -c 'H1=$(cd ../openpilot_backup && git ls-tree -r $0 | sha1sum) && H2=$(git ls-tree -r $1 | sha1sum) && echo "$H1 $H2" >> /tmp/GIT_HASHES && diff <(echo $H1) <(echo $H2) || exit 255' -# human validation -less /tmp/GIT_HASH - -# cleanup -git reflog expire --expire=now --all -git gc --prune=now --aggressive - -# get all lfs files -set +e -git config lfs.url https://github.com/commaai/openpilot.git/info/lfs -git lfs fetch --all -git config lfs.url https://gitlab.com/commaai/openpilot-lfs.git/info/lfs -git lfs fetch --all -set -e - -# add new files to lfs -git lfs migrate import --everything --include="*.ico,*.dlc,*.onnx,*.svg,*.png,*.gif,*.ttf,*.wav,system/hardware/tici/updater,selfdrive/ui/qt/spinner_larch64,selfdrive/ui/qt/text_larch64,third_party/**/*.a,third_party/**/*.so,third_party/**/*.so.*,third_party/**/*.dylib,third_party/acados/*/t_renderer,third_party/qt5/larch64/bin/lrelease,third_party/qt5/larch64/bin/lupdate,third_party/catch2/include/catch2/catch.hpp,*.apk,*.apkpatch,*.jar,*.pdf,*.jpg,*.mp3,*.thneed,*.tar.gz,*.npy,*.csv,*.a,*.so*,*.dylib,*.o,*.b64,selfdrive/hardware/tici/updater,selfdrive/boardd/tests/test_boardd,selfdrive/ui/qt/spinner_aarch64,installer/updater/updater,selfdrive/debug/profiling/simpleperf/**/*,selfdrive/hardware/eon/updater,selfdrive/ui/qt/text_aarch64,selfdrive/debug/profiling/pyflame/**/*,installer/installers/installer_openpilot,installer/installers/installer_dashcam,selfdrive/ui/text/text,selfdrive/ui/android/text/text,selfdrive/ui/spinner/spinner,selfdrive/visiond/visiond,selfdrive/loggerd/loggerd,selfdrive/sensord/sensord,selfdrive/sensord/gpsd,selfdrive/ui/android/spinner/spinner,selfdrive/ui/qt/spinner,selfdrive/ui/qt/text,_stringdefs.py,dfu-util-aarch64-linux,dfu-util-aarch64,dfu-util-x86_64-linux,dfu-util-x86_64,stb_image.h,clpeak3,clwaste,apk/**/*,external/**/*,phonelibs/**/*,third_party/boringssl/**/*,pyextra/**/*,panda/board/**/inc/*.h,panda/board/obj/*.elf,board/inc/*.h,third_party/nanovg/**/*,selfdrive/controls/lib/lateral_mpc/lib_mpc_export/**/*,pyextra/**/*,third_party/android_hardware_libhardware/**/*,selfdrive/controls/lib/lead_mpc_lib/lib_mpc_export/**/*,*.pro,selfdrive/controls/lib/longitudinal_mpc/lib_mpc_export/**/*,selfdrive/controls/lib/lateral_mpc/mpc_export/**/*,third_party/curl/**/*,selfdrive/modeld/thneed/debug/**/*,selfdrive/modeld/thneed/include/**/*,third_party/openmax/**/*,selfdrive/controls/lib/longitudinal_mpc/mpc_export/**/*,selfdrive/controls/lib/longitudinal_mpc_model/lib_mpc_export/**/*,Pipfile,Pipfile.lock,poetry.lock,*.qm" - -# set new lfs endpoint -git config lfs.url https://gitlab.com/commaai/openpilot-lfs.git/info/lfs -git config lfs.pushurl ssh://git@gitlab.com/commaai/openpilot-lfs.git - -# push all branch+tag (scary stuff...) -git push -f --set-upstream git@github.com:commaai/openpilot.git +refs/heads/*:refs/heads/* +refs/tags/*:refs/tags/* diff --git a/scripts/git_rewrite/tag-commit-map.txt b/scripts/git_rewrite/tag-commit-map.txt deleted file mode 100644 index 66b1fb00c182a0..00000000000000 --- a/scripts/git_rewrite/tag-commit-map.txt +++ /dev/null @@ -1,82 +0,0 @@ -v0.1 e94a30bec07e719c5a7b037ca1f4db8312702cce -v0.2 449b482cc3236ccf31829830b4f6a44b2dcc06c2 -v0.2.1 17d9becd3c673091b22f09aa02559a9ed9230f50 -v0.2.2 a64b9aa9b8cb5863c917b6926516291a63c02fe5 -v0.2.3 adaa4ed350acda4067fc0b455ad15b54cdf4c768 -v0.2.4 ecc565aa3fdc4c7e719aadc000e1fdc4d80d4fe0 -v0.2.5 29c58b45882ac79595356caf98580c1d2a626011 -v0.2.6 6c3afeec0fb439070b2912978b8dbb659033b1d9 -v0.2.7 c6ba5dc5391d3ca6cda479bf1923b88ce45509a0 -v0.2.8 95a349abcc050712c50d4d85a1c8a804eee7f6c2 -v0.2.9 693bcb0f83478f2651db6bac9be5ca5ad60d03f3 -v0.3.0 c5d8aec28b5230d34ae4b677c2091cc3dec7e3e8 -v0.3.1 41e3a0f699f5c39cb61a15c0eb7a4aa816d47c24 -v0.3.2 7fe46f1e1df5dec08a940451ba0feefd5c039165 -v0.3.3 5cf91d0496688fed4f2a6c7021349b1fc0e057a2 -v0.3.4 1b8c44b5067525a5d266b6e99799d8097da76a29 -v0.3.5 b111277f464cf66fa34b67819a83ea683e0f64df -v0.4.0.2 da52d065a4c4f52d6017a537f3a80326f5af8bdc -v0.4.1 4474b9b3718653aeb0aee26422caefb90460cc0e -v0.4.2 28c0797d30175043bbfa31307b63aab4197cf996 -v0.4.4 9a9ff839a9b70cb2601d7696af743f5652395389 -v0.4.5 37285038d3f91fa1b49159c4a35a8383168e644f -v0.4.6 c6df34f55ba8c5a911b60d3f9eb20e3fa45f68c1 -v0.4.7 ae5cb7a0dab8b1bed9d52292f9b4e8e66a0f8ec9 -v0.5 de33bc46452b1046387ee2b3a03191b2c71135fb -v0.5.1 8f22f52235c48eada586795ac57edb22688e4d08 -v0.5.2 0129a8a4ff8da5314e8e4d4d3336e89667ff6d54 -v0.5.3 285c52eb693265a0a530543e9ca0aeb593a2a55e -v0.5.4 a422246dc30bce11e970514f13f7c110f4470cc3 -v0.5.5 8f3539a27b28851153454eb737da9624cccaed2d -v0.5.6 860a48765d1016ba226fb2c64aea35a45fe40e4a -v0.5.7 9ce3045f139ee29bf0eea5ec59dfe7df9c3d2c51 -v0.5.8 2cee2e05ba0f3824fdbb8b957958800fa99071a1 -v0.5.9 ad145da3bcded0fe75306df02061d07a633963c3 -v0.5.10 ff4c1557d8358f158f4358788ff18ef93d2470ef -v0.5.11 d1866845df423c6855e2b365ff230cf7d89a420b -v0.5.12 f6e8ef27546e9a406724841e75f8df71cc4c2c97 -v0.5.13 dd34ccfe288ebda8e2568cf550994ae890379f45 -v0.6 60a20537c5f3fcc7f11946d81aebc8f90c08c117 -v0.6.1 cf5c4aeacb1703d0ffd35bdb5297d3494fee9a22 -v0.6.2 095ef5f9f60fca1b269aabcc3cfd322b17b9e674 -v0.6.3 d5f9caa82d80cdcc7f1b7748f2cf3ccbf94f82a3 -v0.6.4 58f376002e0c654fbc2de127765fa297cf694a33 -v0.6.5 70d17cd69b80e7627dcad8fd5b6438f2309ac307 -v0.6.6 d4eb5a6eafdd4803d09e6f3963918216cca5a81f -v0.7 a2ae18d1dbd1e59c38ce22fa25ddffbd1d3084e3 -v0.7.1 1e1de64a1e59476b7b3d3558b92149246d5c3292 -v0.7.2 59bd58c940673b4c4a6a86f299022614bcf42b22 -v0.7.3 d7acd8b68f8131e0e714400cf124a3e228638643 -v0.7.4 e93649882c5e914eec4a8b8b593dc0587e497033 -v0.7.5 8abc0afe464626a461d2c7e192c912eeebeccc65 -v0.7.6 69aacd9d179fe6dd3110253a099c38b34cff7899 -v0.7.7 f1caed7299cdba5e45635d8377da6cc1e5fd7072 -v0.7.8 2189fe8741b635d8394d55dee28959425cfd5ad0 -v0.7.9 86dc54b836a973f132ed26db9f5a60b29f9b25b2 -v0.7.10 47a42ff432db8a2494e922ca5e767e58020f0446 -v0.7.11 f46ed718ba8d6bb4d42cd7b0f0150c406017c373 -v0.8 d56e04c0d960c8d3d4ab88b578dc508a2b4e07dc -v0.8.1 cd6f26664cb8d32a13847d6648567c47c580e248 -v0.8.2 7cc0999aebfe63b6bb6dd83c1dff62c3915c4820 -v0.8.3 986500fe2f10870018f1fba1e5465476b8915977 -v0.8.4 f0d0b82b8d6f5f450952113e234d0a5a49e80c48 -v0.8.5 f5d9ddc6c2a2802a61e5ce590c6b6688bf736a69 -v0.8.6 75904ed7452c6cbfb2a70cd379a899d8a75b97c2 -v0.8.7 4f9e568019492126e236da85b5ca0a059f292900 -v0.8.8 a949a49d5efaaf2d881143d23e9fb5ff9e28e88c -v0.8.9 a034926264cd1025c69d6ceb3fe444965f960b75 -v0.8.10 59accdd814398b884167c0f41dbf46dcccf0c29c -v0.8.11 d630ec9092f039cb5e51c5dd6d92fc47b91407e4 -v0.8.12 57871c99031cf597ffa0d819057ac1401e129f32 -v0.8.13 e43e6e876513450d235124fcb711f1724ed9814c -v0.8.14 71901c94dbbaa2f9f156a80c14cc7ea65219fc7c -v0.8.15 5a7c2f90361e72e9c35e88abd2e11acdc4aba354 -v0.8.16 f41dc62a12cc0f3cb8c5453c0caa0ba21e1bd01e -v0.9.0 58b84fb401a804967aa0dd5ee66fafa90194fd30 -v0.9.1 89f68bf0cbf53a81b0553d3816fdbe522f941fa1 -v0.9.2 c7d3b28b93faa6c955fb24bc64031512ee985ee9 -v0.9.3 8704c1ff952b5c85a44f50143bbd1a4f7b4887e2 -v0.9.4 fa310d9e2542cf497d92f007baec8fd751ffa99c -v0.9.5 3b1e9017c560499786d8a0e46aaaeea65037acac -v0.9.6 0b4d08fab8e35a264bc7383e878538f8083c33e5 -v0.9.7 f8cb04e4a8b032b72a909f68b808a50936184bee diff --git a/scripts/jenkins_loop_test.sh b/scripts/jenkins_loop_test.sh new file mode 100755 index 00000000000000..8073f4668c1888 --- /dev/null +++ b/scripts/jenkins_loop_test.sh @@ -0,0 +1,129 @@ +#!/usr/bin/env bash +set -e + +YELLOW='\033[0;33m' +GREEN='\033[0;32m' +UNDERLINE='\033[4m' +BOLD='\033[1m' +NC='\033[0m' + +BRANCH="master" +RUNS="20" + +COOKIE_JAR=/tmp/cookies +CRUMB=$(curl -s --cookie-jar $COOKIE_JAR 'https://jenkins.comma.life/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)') + +FIRST_LOOP=1 + +function loop() { + JENKINS_BRANCH="__jenkins_loop_${BRANCH}_$(date +%s)" + API_ROUTE="https://jenkins.comma.life/job/openpilot/job/$JENKINS_BRANCH" + + for run in $(seq 1 $((RUNS / 2))); do + + N=2 + + if [[ $FIRST_LOOP ]]; then + TEMP_DIR=$(mktemp -d) + GIT_LFS_SKIP_SMUDGE=1 git clone --quiet -b $BRANCH --depth=1 --no-tags git@github.com:commaai/openpilot $TEMP_DIR + git -C $TEMP_DIR checkout --quiet -b $JENKINS_BRANCH + echo "TESTING: $(date)" >> $TEMP_DIR/testing_jenkins + git -C $TEMP_DIR add testing_jenkins + git -C $TEMP_DIR commit --quiet -m "testing" + git -C $TEMP_DIR push --quiet -f origin $JENKINS_BRANCH + rm -rf $TEMP_DIR + FIRST_BUILD=1 + echo '' + echo 'waiting on Jenkins...' + echo '' + sleep 90 + FIRST_LOOP="" + fi + + FIRST_BUILD=$(curl -s $API_ROUTE/api/json | jq .nextBuildNumber) + LAST_BUILD=$((FIRST_BUILD+N-1)) + TEST_BUILDS=( $(seq $FIRST_BUILD $LAST_BUILD) ) + + # Start N new builds + for i in ${TEST_BUILDS[@]}; + do + echo "Starting build $i" + curl -s --output /dev/null --cookie $COOKIE_JAR -H "$CRUMB" -X POST $API_ROUTE/build?delay=0sec + sleep 5 + done + echo "" + + # Wait for all builds to end + while true; do + sleep 30 + + count=0 + for i in ${TEST_BUILDS[@]}; + do + RES=$(curl -s -w "\n%{http_code}" --cookie $COOKIE_JAR -H "$CRUMB" $API_ROUTE/$i/api/json) + HTTP_CODE=$(tail -n1 <<< "$RES") + JSON=$(sed '$ d' <<< "$RES") + + if [[ $HTTP_CODE == "200" ]]; then + STILL_RUNNING=$(echo $JSON | jq .inProgress) + if [[ $STILL_RUNNING == "true" ]]; then + echo -e "Build $i: ${YELLOW}still running${NC}" + continue + else + count=$((count+1)) + echo -e "Build $i: ${GREEN}done${NC}" + fi + else + echo "No status for build $i" + fi + done + echo "See live results: ${API_ROUTE}/buildTimeTrend" + echo "" + + if [[ $count -ge $N ]]; then + break + fi + done + + done +} + +function usage() { + echo "" + echo "Run the Jenkins tests multiple times on a specific branch" + echo "" + echo -e "${BOLD}${UNDERLINE}Options:${NC}" + echo -e " ${BOLD}-n, --n${NC}" + echo -e " Specify how many runs to do (default to ${BOLD}20${NC})" + echo -e " ${BOLD}-b, --branch${NC}" + echo -e " Specify which branch to run the tests against (default to ${BOLD}master${NC})" + echo "" +} + +function _looper() { + if [[ $# -eq 0 ]]; then + usage + exit 0 + fi + + # parse Options + while [[ $# -gt 0 ]]; do + case $1 in + -n | --n ) shift 1; RUNS="$1"; shift 1 ;; + -b | --b | --branch | -branch ) shift 1; BRANCH="$1"; shift 1 ;; + * ) usage; exit 0 ;; + esac + done + + echo "" + echo -e "You are about to start $RUNS Jenkins builds against the $BRANCH branch." + echo -e "If you expect this to run overnight, ${UNDERLINE}${BOLD}unplug the cold reboot power switch${NC} from the testing closet before." + echo "" + read -p "Press (y/Y) to confirm: " choice + if [[ "$choice" == "y" || "$choice" == "Y" ]]; then + loop + fi + +} + +_looper $@ diff --git a/scripts/lint/check_nomerge_comments.sh b/scripts/lint/check_nomerge_comments.sh new file mode 100755 index 00000000000000..6737d62a2053b2 --- /dev/null +++ b/scripts/lint/check_nomerge_comments.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +FAIL=0 + +if grep -n '\(#\|//\)\([[:space:]]*\)NOMERGE' $@; then + echo -e "NOMERGE comments found! Remove them before merging\n" + FAIL=1 +fi + +exit $FAIL diff --git a/scripts/lint/check_shebang_format.sh b/scripts/lint/check_shebang_format.sh index 89b95d5929a3b2..131e0867c828aa 100755 --- a/scripts/lint/check_shebang_format.sh +++ b/scripts/lint/check_shebang_format.sh @@ -2,12 +2,12 @@ FAIL=0 -if grep '^#!.*python' $@ | grep -v '#!/usr/bin/env python3$'; then +if grep -I '^#!.*python' "$@" | grep -v '#!/usr/bin/env python3$'; then echo -e "Invalid shebang! Must use '#!/usr/bin/env python3'\n" FAIL=1 fi -if grep '^#!.*bash' $@ | grep -v '#!/usr/bin/env bash$'; then +if grep -I '^#!.*bash' "$@" | grep -v '#!/usr/bin/env bash$'; then echo -e "Invalid shebang! Must use '#!/usr/bin/env bash'" FAIL=1 fi diff --git a/scripts/lint/lint.sh b/scripts/lint/lint.sh index 4b65e4a89509f0..5170678b55ff57 100755 --- a/scripts/lint/lint.sh +++ b/scripts/lint/lint.sh @@ -13,8 +13,8 @@ cd $ROOT FAILED=0 -IGNORED_FILES="uv\.lock|docs\/CARS.md" -IGNORED_DIRS="^third_party.*|^msgq.*|^msgq_repo.*|^opendbc.*|^opendbc_repo.*|^cereal.*|^panda.*|^rednose.*|^rednose_repo.*|^tinygrad.*|^tinygrad_repo.*|^teleoprtc.*|^teleoprtc_repo.*" +IGNORED_FILES="uv\.lock|docs\/CARS.md|scripts\/nap\/firmware\/.*\.bin" +IGNORED_DIRS="^msgq.*|^msgq_repo.*|^opendbc.*|^opendbc_repo.*|^cereal.*|^panda.*|^rednose.*|^rednose_repo.*|^tinygrad.*|^tinygrad_repo.*|^teleoprtc.*|^teleoprtc_repo.*" function run() { shopt -s extglob @@ -52,9 +52,10 @@ function run_tests() { run "check_added_large_files" python3 -m pre_commit_hooks.check_added_large_files --enforce-all $ALL_FILES --maxkb=120 run "check_shebang_scripts_are_executable" python3 -m pre_commit_hooks.check_shebang_scripts_are_executable $ALL_FILES run "check_shebang_format" $DIR/check_shebang_format.sh $ALL_FILES + run "check_nomerge_comments" $DIR/check_nomerge_comments.sh $ALL_FILES if [[ -z "$FAST" ]]; then - run "mypy" mypy $PYTHON_FILES + run "ty" ty check run "codespell" codespell $ALL_FILES fi @@ -68,7 +69,7 @@ function help() { echo "" echo -e "${BOLD}${UNDERLINE}Tests:${NC}" echo -e " ${BOLD}ruff${NC}" - echo -e " ${BOLD}mypy${NC}" + echo -e " ${BOLD}ty${NC}" echo -e " ${BOLD}codespell${NC}" echo -e " ${BOLD}check_added_large_files${NC}" echo -e " ${BOLD}check_shebang_scripts_are_executable${NC}" @@ -80,11 +81,11 @@ function help() { echo " Specify tests to skip separated by spaces" echo "" echo -e "${BOLD}${UNDERLINE}Examples:${NC}" - echo " op lint mypy ruff" - echo " Only run the mypy and ruff tests" + echo " op lint ty ruff" + echo " Only run the ty and ruff tests" echo "" - echo " op lint --skip mypy ruff" - echo " Skip the mypy and ruff tests" + echo " op lint --skip ty ruff" + echo " Skip the ty and ruff tests" echo "" echo " op lint" echo " Run all the tests" diff --git a/scripts/measure_actuator_delay.py b/scripts/measure_actuator_delay.py new file mode 100755 index 00000000000000..52c2773c68c173 --- /dev/null +++ b/scripts/measure_actuator_delay.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Measure the actuator delay between pedal command and measured acceleration. + +Cross-correlates actuators.accel (commanded) with carState.aEgo (measured) +to find the time offset that best aligns the two signals. This gives the +true end-to-end delay: CAN TX → pedal firmware → inverter → motor → IMU. + +Usage: + # From a local rlog file + python scripts/measure_actuator_delay.py /path/to/rlog.zst + + # From a route segment + python scripts/measure_actuator_delay.py "dongle_id/date--time/segment" + + # Multiple segments for better statistics + python scripts/measure_actuator_delay.py /path/to/rlog1.zst /path/to/rlog2.zst + +The script filters for periods where longitudinal control is active and +the car is moving (v_ego > 3 m/s), since delay measurement is meaningless +at standstill or when the system is disengaged. +""" + +import sys +import numpy as np + +from openpilot.tools.lib.logreader import LogReader + + +MIN_SPEED = 3.0 # m/s — ignore standstill +MIN_ACTIVE_SECONDS = 5 # need at least this much active data +MAX_DELAY_S = 1.0 # search window for cross-correlation + + +def extract_signals(route_or_file: str): + """Extract time-aligned accel command and measured accel from a log.""" + lr = LogReader(route_or_file) + + cmd_times, cmd_vals = [], [] + ego_times, ego_vals, ego_speeds = [], [], [] + + for msg in lr: + w = msg.which() + t = msg.logMonoTime / 1e9 + + if w == 'carControl': + if msg.carControl.longActive: + cmd_times.append(t) + cmd_vals.append(float(msg.carControl.actuators.accel)) + + elif w == 'carState': + ego_times.append(t) + ego_vals.append(float(msg.carState.aEgo)) + ego_speeds.append(float(msg.carState.vEgo)) + + return (np.array(cmd_times), np.array(cmd_vals), + np.array(ego_times), np.array(ego_vals), np.array(ego_speeds)) + + +def resample_to_uniform(times, values, dt=0.01): + """Resample irregular time series to uniform grid via linear interpolation.""" + if len(times) < 2: + return np.array([]), np.array([]) + t_uniform = np.arange(times[0], times[-1], dt) + v_uniform = np.interp(t_uniform, times, values) + return t_uniform, v_uniform + + +def measure_delay(cmd_t, cmd_v, ego_t, ego_v, ego_speed, dt=0.01): + """Cross-correlate command and measurement to find actuator delay. + + Returns (delay_seconds, correlation_peak, n_samples_used). + """ + # Resample both to the same uniform grid + t0 = max(cmd_t[0], ego_t[0]) + t1 = min(cmd_t[-1], ego_t[-1]) + if t1 - t0 < MIN_ACTIVE_SECONDS: + return None, None, 0 + + t_grid = np.arange(t0, t1, dt) + cmd_resampled = np.interp(t_grid, cmd_t, cmd_v) + ego_resampled = np.interp(t_grid, ego_t, ego_v) + speed_resampled = np.interp(t_grid, ego_t, ego_speed) + + # Filter: only use samples where car is moving + mask = speed_resampled > MIN_SPEED + if mask.sum() < MIN_ACTIVE_SECONDS / dt: + return None, None, int(mask.sum()) + + cmd_masked = cmd_resampled.copy() + ego_masked = ego_resampled.copy() + cmd_masked[~mask] = 0.0 + ego_masked[~mask] = 0.0 + + # Remove mean (cross-correlation needs zero-mean signals) + cmd_masked -= cmd_masked[mask].mean() + ego_masked -= ego_masked[mask].mean() + + # Normalize + cmd_std = cmd_masked[mask].std() + ego_std = ego_masked[mask].std() + if cmd_std < 1e-6 or ego_std < 1e-6: + return None, None, int(mask.sum()) + + cmd_masked /= cmd_std + ego_masked /= ego_std + + # Cross-correlate: shift ego relative to cmd + max_lag_samples = int(MAX_DELAY_S / dt) + lags = np.arange(0, max_lag_samples) + correlations = np.zeros(len(lags)) + + n = len(cmd_masked) + for i, lag in enumerate(lags): + if lag >= n: + break + overlap = min(n - lag, n) + correlations[i] = np.mean(cmd_masked[:overlap] * ego_masked[lag:lag + overlap]) + + best_idx = np.argmax(correlations) + delay = lags[best_idx] * dt + peak_corr = correlations[best_idx] + + return delay, peak_corr, int(mask.sum()) + + +def main(): + if len(sys.argv) < 2: + print(__doc__) + sys.exit(1) + + routes = sys.argv[1:] + delays = [] + + for route in routes: + print(f"\nProcessing: {route}") + try: + cmd_t, cmd_v, ego_t, ego_v, ego_speed = extract_signals(route) + except Exception as e: + print(f" Error reading: {e}") + continue + + print(f" Command samples: {len(cmd_t)}, Ego samples: {len(ego_t)}") + + if len(cmd_t) < 10 or len(ego_t) < 10: + print(" Not enough data (need active longitudinal control)") + continue + + delay, corr, n_used = measure_delay(cmd_t, cmd_v, ego_t, ego_v, ego_speed) + + if delay is None: + print(f" Could not measure delay (n_samples={n_used})") + continue + + print(f" Delay: {delay:.3f}s (correlation: {corr:.3f}, samples: {n_used})") + delays.append(delay) + + if delays: + delays = np.array(delays) + print(f"\n{'='*50}") + print(f"Results across {len(delays)} segment(s):") + print(f" Mean delay: {delays.mean():.3f}s") + print(f" Std dev: {delays.std():.3f}s") + print(f" Min: {delays.min():.3f}s") + print(f" Max: {delays.max():.3f}s") + print("\nCurrent setting: longitudinalActuatorDelay = 0.4s") + print(f"Measured: {delays.mean():.3f}s") + if abs(delays.mean() - 0.4) > 0.05: + print(f" --> Consider updating to {delays.mean():.2f}s") + else: + print(" --> Current 0.4s is within tolerance") + else: + print("\nNo valid measurements. Need drive logs with active pedal control.") + + +if __name__ == '__main__': + main() diff --git a/scripts/nap/RADAR_TOOLS.md b/scripts/nap/RADAR_TOOLS.md new file mode 100644 index 00000000000000..cef5d354c6556a --- /dev/null +++ b/scripts/nap/RADAR_TOOLS.md @@ -0,0 +1,101 @@ +# NAP Radar Diagnostic Tools + +Tools for diagnosing and validating the Pre-AP Tesla Bosch radar pipeline. + +## diagnose_radar.py + +Real-time diagnostic tool with two modes. Run on-device while openpilot is active. + +### Cereal Monitor (default) + +```bash +python3 scripts/nap/diagnose_radar.py +``` + +Monitors both CAN buses via cereal messaging (non-invasive, GTW emulation stays active): + +- **Bus 0 source rates** — Measures every chassis bus message that triggers GTW forwarding. Since CAN TX doesn't loopback to RX, we can't see our own GTW messages on bus 1. Instead, bus 0 source rates directly equal the GTW forwarding rates. +- **Timing gap detection** — Tracks max inter-message gap and counts gaps >2.5x the expected period. Detects burstiness that could cause the radar to drop Doppler tracking. +- **Rate trend** — Per-second rate history (last 10s) for the 3 critical sources: 0x118 (wheel speed, 100Hz), 0x0E (steering, 100Hz), 0x115 (ESP control, 50Hz). +- **Vehicle speed decode** — Live speed from DI_torque2 (0x118), the source the firmware uses to synthesize 0x169 wheel speeds. +- **Radar status transitions** — Catches ACTIVE (0x300) to INIT (0x631) flip-flops. +- **Doppler tracking** — Per-interval percentage of radar tracks with non-zero vRel. + +Press Ctrl+C to stop. A final summary with timing statistics is printed. + +### Panda Health Check + +```bash +python3 scripts/nap/diagnose_radar.py --panda +``` + +Quick one-shot check (does NOT change safety mode): + +- Reads NAPRadarEnabled param +- Verifies safety_mode=36 (teslaLegacy) and all param flags (PREAP, RADAR_EMULATION, etc.) +- Shows CAN bus health (rx/tx/error counts per bus) +- 3-second bus 1 sniff to check for radar traffic + +### GTW Source-to-Destination Map + +| Source (bus 0) | Dest (bus 1) | Name | Expected Rate | +|---|---|---|---| +| 0x108 | 0x109 | DI_torque1 | 100 Hz | +| 0x118 | 0x119 | DI_torque2 | 100 Hz | +| 0x0E | 0x199 | STW_ANGLHP_STAT | 100 Hz | +| 0x115 | 0x129 | ESP_115h | 50 Hz | +| 0x145 | 0x149 | ESP_145h | 50 Hz | +| 0x20A | 0x209 | GTW_odo | 50 Hz | +| 0x308 | 0x219 | STW_ACTN_RQ | 10 Hz | +| 0x405 | 0x2B9 | VIP_405HS | 5 Hz | +| 0x398 | 0x2D9 | BC_status | 1 Hz | + +Synthesized (no direct source on bus 0): +- 0x169 (ESP_wheelSpeeds) — built from 0x118 data, sent at 100 Hz +- 0x1A9 (DI_espControl) — built from 0x115 data, sent at 50 Hz + +Messages not present on Pre-AP (expected missing): +- 0x158 (ESP_C/Brake), 0x2A8 (GTW_carConfig — event-triggered only) + +--- + +## radar_replay.py + +Offline replay harness for validating radar pipeline changes against drive logs. + +### Usage + +```bash +# Replay a specific log file +python3 scripts/nap/radar_replay.py path/to/log.zst + +# Replay first .zst in logs/crappy-radar/ +python3 scripts/nap/radar_replay.py +``` + +Runs the radar pipeline twice on each log: +1. **Baseline** (dt=0.05, old DT_MDL) — measures behavior with the original KF time step +2. **Fixed** (dt=0.125, 8Hz radar) — measures behavior with the corrected time step + +### What It Measures + +- **Lead ID changes/s** — How often the selected lead vehicle changes. Target: <1.0/s +- **Unique track IDs** — Total distinct radar tracks seen during the drive +- **Average track lifespan** — Mean frames a track survives before disappearing +- **Max detection range** — Farthest object detected +- **Radar-fused vs vision-only** — Percentage of lead selections backed by radar data + +### Output + +- CSV file per run (one row per radar cycle) with columns: timestamp, num_tracks, lead_id, lead_dRel, lead_vRel, lead_aLeadK, lead_radar, v_ego, track_ids +- Summary statistics printed to console + +### Important Note + +The replay uses a simplified lead selection (closest in-lane track) without the vision model. Lead ID change rates from replay will be higher than the live system, which uses vision-radar fusion with Laplacian matching and hysteresis. To measure actual live lead stability, analyze the `radarState` events in the log (leadOne.radarTrackId). + +### Dependencies + +- `zstandard` — for .zst decompression +- `pycapnp` — for capnp message parsing (fallback when cereal is unavailable) +- Works both on-device (with cereal) and locally (with pycapnp + log.capnp schema) diff --git a/selfdrive/debug/internal/__init__.py b/scripts/nap/__init__.py similarity index 100% rename from selfdrive/debug/internal/__init__.py rename to scripts/nap/__init__.py diff --git a/scripts/nap/analyze_engagement.py b/scripts/nap/analyze_engagement.py new file mode 100755 index 00000000000000..1da277637eb805 --- /dev/null +++ b/scripts/nap/analyze_engagement.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Analyze pedal engagement transitions from openpilot route logs. + +Usage: + python scripts/nap/analyze_engagement.py /path/to/logs/ + +Shows engagement events, gas release transitions, and pedal state +to diagnose regen spikes and engagement failures. +""" +import glob +import sys +import bisect + +from openpilot.tools.lib.logreader import LogReader + + +def analyze(log_dir): + files = sorted(glob.glob(f'{log_dir}/*--rlog.zst')) + if not files: + print(f'No rlog.zst files found in {log_dir}') + return + + print(f'Reading {len(files)} segments from {log_dir}...') + + cs_list = [] + cc_list = [] + + for f in files: + for msg in LogReader(f): + t = msg.logMonoTime / 1e9 + w = msg.which() + if w == 'carState': + cs = msg.carState + cs_list.append({ + 't': t, + 'enabled': cs.cruiseState.enabled, + 'gas': cs.gasPressed, + 'vEgo': cs.vEgo, + 'aEgo': cs.aEgo, + }) + elif w == 'carControl': + cc = msg.carControl + cc_list.append({ + 't': t, + 'enabled': cc.enabled, + 'longActive': cc.longActive, + 'latActive': cc.latActive, + 'accel': cc.actuators.accel, + }) + + cs_list.sort(key=lambda x: x['t']) + cc_list.sort(key=lambda x: x['t']) + cc_times = [c['t'] for c in cc_list] + + print(f'carStates: {len(cs_list)} | carControls: {len(cc_list)}') + print(f'Duration: {(cs_list[-1]["t"] - cs_list[0]["t"]) / 60:.1f} min') + + def get_cc(t): + idx = bisect.bisect_left(cc_times, t) + if idx < len(cc_list): + return cc_list[idx] + return None + + def print_window(center, before=3, after=20, label=""): + start = max(0, center - before) + end = min(center + after, len(cs_list)) + for j in range(start, end): + c = cs_list[j] + cc = get_cc(c['t']) + la = f'{cc["longActive"]}' if cc else '--' + ca = f'{cc["accel"]:+6.2f}' if cc else ' -- ' + marker = f' <-- {label}' if j == center else '' + print(f' t={c["t"]:.2f} en={c["enabled"]} gas={c["gas"]} v={c["vEgo"]:5.1f} a={c["aEgo"]:+6.2f} longAct={la:5s} ccAccel={ca}{marker}') + + prev_en = False + prev_gas = False + engage_num = 0 + release_num = 0 + + for i, cs in enumerate(cs_list): + if cs['enabled'] and not prev_en: + engage_num += 1 + print(f'\n=== ENGAGE #{engage_num} at t={cs["t"]:.2f}s ===') + print_window(i, label="ENGAGE") + + if prev_gas and not cs['gas'] and cs['enabled']: + release_num += 1 + if release_num <= 20: + print(f'\n=== GAS RELEASE #{release_num} at t={cs["t"]:.2f}s ===') + print_window(i, label="RELEASE") + + prev_en = cs['enabled'] + prev_gas = cs['gas'] + + print(f'\nTotal: {engage_num} engagements, {release_num} gas releases while engaged') + + +if __name__ == '__main__': + if len(sys.argv) < 2: + print(__doc__) + sys.exit(1) + analyze(sys.argv[1]) diff --git a/scripts/nap/build_osm_speed_limits.py b/scripts/nap/build_osm_speed_limits.py new file mode 100755 index 00000000000000..a4fd1e48986b01 --- /dev/null +++ b/scripts/nap/build_osm_speed_limits.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python3 +"""Build a NAP OSM speed-limit sqlite from Geofabrik PBF / Overpass / GeoJSON. + +OpenStreetMap data is ODbL: © OpenStreetMap contributors. +https://www.openstreetmap.org/copyright + +This is a PC tool. Do not commit the sqlite to git. Attach the zstd file to +GitHub Release tag osm-us-speed-limits-v3 (asset speed_limits_us.sqlite.zst). + +US tagged-maxspeed ways ~3.4M (Taginfo 2026-09). After polyline simplify, +expect roughly 0.8–1.5 GB sqlite and 200–500 MB zstd — one US-wide asset. + +Examples: + + # After: osmium tags-filter us-latest.osm.pbf w/highway w/maxspeed -o us-ms.osm.pbf + # (w/highway keeps every highway way, so roundabout rings and their approach + # roads are in the filtered PBF; they go to the rb_ways table, pack v4+) + python scripts/nap/build_osm_speed_limits.py --pbf us-ms.osm.pbf --out speed_limits_us.sqlite + zstd -19 speed_limits_us.sqlite -o speed_limits_us.sqlite.zst + + # Overlay MN statutory fills for unmarked highways in the Benson 100-mile box + # onto an existing US pack (does not upload guessed maxspeed to osm.org): + python scripts/nap/build_osm_speed_limits.py --pbf minnesota-latest.osm.pbf \\ + --fill-mn-statutory --benson --merge-into speed_limits_us.sqlite \\ + --out speed_limits_us.sqlite --zst + + python scripts/nap/build_osm_speed_limits.py --from-json overpass.json --out speed_limits.sqlite +""" +from __future__ import annotations + +import argparse +import json +import os +import shutil +import sqlite3 +import sys + +from openpilot.selfdrive.mapd.local_refresh import merge_ways_into_db +from openpilot.selfdrive.mapd.maps_manifest import ATTRIBUTION, LICENSE, LICENSE_URL +from openpilot.selfdrive.mapd.mn_statutory import ( + BENSON_LAT, + BENSON_LON, + BENSON_RADIUS_MILES, + FILL_NOTES, + FILL_SOURCE, + PlaceIndex, + benson_fill_bbox, + is_urban_place_tags, +) +from openpilot.selfdrive.mapd.us_statutory import fillable_highway, inherit_posted_neighbors, is_fill_source, state_index +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB +from openpilot.selfdrive.mapd.overpass import bbox_from_center, resolve_way_speed, ways_from_overpass +from openpilot.selfdrive.mapd.roundabout_map import ( + ROLE_RING, + is_ring_tags, + mini_roundabout_way, + rb_rows_from_overpass, + roundabout_rows, +) +from openpilot.selfdrive.mapd.speed_limit import parse_maxspeed + + + +def _parse_bbox(text: str) -> tuple[float, float, float, float]: + parts = [float(x.strip()) for x in text.split(",")] + if len(parts) != 4: + raise argparse.ArgumentTypeError("--bbox must be south,west,north,east") + return parts[0], parts[1], parts[2], parts[3] + + +def _bbox_intersects_way(coords: list[tuple[float, float]], bbox: tuple[float, float, float, float]) -> bool: + south, west, north, east = bbox + lats = [c[0] for c in coords] + lons = [c[1] for c in coords] + return max(lats) >= south and min(lats) <= north and max(lons) >= west and min(lons) <= east + + +def _area_outer_rings(a) -> list[list[tuple[float, float]]]: + rings: list[list[tuple[float, float]]] = [] + try: + for ring in a.outer_rings(): + coords: list[tuple[float, float]] = [] + for n in ring: + loc = n.location + if not loc.valid(): + coords = [] + break + coords.append((float(loc.lat), float(loc.lon))) + if len(coords) >= 3: + rings.append(coords) + except Exception: + return [] + return rings + + +def _places_from_pyosmium(pbf: str) -> PlaceIndex: + try: + import osmium + except ImportError as e: + raise RuntimeError( + "Reading .osm.pbf needs pyosmium (pip install osmium) or convert with osmium-tool first." + ) from e + + idx = PlaceIndex() + + class H(osmium.SimpleHandler): + def area(self, a): + tags = dict(a.tags) + if not is_urban_place_tags(tags): + return + rings = _area_outer_rings(a) + if rings: + idx.add_rings(rings, tags.get("name") or "") + + print(f"Collecting MN city/town urban boundary polygons from {pbf}…", file=sys.stderr, flush=True) + H().apply_file(pbf, locations=True) + print(f" {len(idx)} urban place polygons", file=sys.stderr, flush=True) + return idx + + +def _ways_from_pyosmium( + pbf: str, + *, + bbox: tuple[float, float, float, float] | None = None, + fill_unmarked: bool = False, + places: PlaceIndex | None = None, + mn_only: bool = False, +) -> list[dict]: + try: + import osmium + except ImportError as e: + raise RuntimeError( + "Reading .osm.pbf needs pyosmium (pip install osmium) or convert with osmium-tool first." + ) from e + + out: list[dict] = [] + + class H(osmium.SimpleHandler): + def way(self, w): + tags = dict(w.tags) + highway = tags.get("highway") or "" + if not highway: + return + tagged = parse_maxspeed(tags.get("maxspeed")) or parse_maxspeed(tags.get("maxspeed:forward")) + if tagged is None and not (fill_unmarked and fillable_highway("MN", highway.lower())): + # MN's class set is the widest (adds residential/alley); the state check is below. + return + coords = [] + try: + for n in w.nodes: + if not n.location.valid(): + return + coords.append((float(n.lat), float(n.lon))) + except osmium.InvalidLocationError: + return + if len(coords) < 2: + return + if bbox is not None and not _bbox_intersects_way(coords, bbox): + return + fill = fill_unmarked + state = None + if fill and tagged is None: + state = state_index().state_of_way(coords) + if mn_only and state != "MN": + fill = False + elif not fillable_highway(state, highway.lower()): + return + ms, source = resolve_way_speed(tags, coords, fill_unmarked=fill, places=places, state=state) + if ms is None: + return + out.append({ + "way_id": int(w.id), + "name": w.tags.get("name") or w.tags.get("ref") or "", + "highway": highway, + "maxspeed_ms": ms, + "coords": coords, + "source": source, + "estimated": is_fill_source(source), + "junction": tags.get("junction") or "", + }) + + print(f"Reading highway ways from {pbf}…", file=sys.stderr, flush=True) + H().apply_file(pbf, locations=True, filters=[osmium.filter.KeyFilter("highway")]) + if fill_unmarked: + n = inherit_posted_neighbors(out) + print(f" {n} estimated ways took the posted limit of the same road at their ends", file=sys.stderr, flush=True) + return out + + +def _rb_rows_from_pyosmium(pbf: str, *, bbox: tuple[float, float, float, float] | None = None) -> list[dict]: + """Roundabout rings (any maxspeed) + approach roads touching them. Two passes over the PBF.""" + try: + import osmium + except ImportError as e: + raise RuntimeError( + "Reading .osm.pbf needs pyosmium (pip install osmium) or convert with osmium-tool first." + ) from e + + generic: list[dict] = [] + ring_nodes: set[int] = set() + + def _coords(w) -> tuple[list[int], list[tuple[float, float]]] | None: + nodes: list[int] = [] + coords: list[tuple[float, float]] = [] + try: + for n in w.nodes: + if not n.location.valid(): + return None + nodes.append(int(n.ref)) + coords.append((float(n.lat), float(n.lon))) + except osmium.InvalidLocationError: + return None + return nodes, coords + + class Rings(osmium.SimpleHandler): + def node(self, n): + tags = {t.k: t.v for t in n.tags} + if tags.get("highway") != "mini_roundabout" or not n.location.valid(): + return + lat, lon = float(n.location.lat), float(n.location.lon) + if bbox is not None and not _bbox_intersects_way([(lat, lon)], bbox): + return + ring_nodes.add(int(n.id)) + generic.append(mini_roundabout_way(int(n.id), lat, lon, tags)) + + def way(self, w): + tags = {t.k: t.v for t in w.tags} + if not is_ring_tags(tags): + return + got = _coords(w) + if got is None or len(got[1]) < 2: + return + if bbox is not None and not _bbox_intersects_way(got[1], bbox): + return + ring_nodes.update(got[0]) + generic.append({"way_id": int(w.id), "tags": tags, "node_ids": got[0], "coords": got[1]}) + + class Approaches(osmium.SimpleHandler): + def way(self, w): + tags = {t.k: t.v for t in w.tags} + if not tags.get("highway") or is_ring_tags(tags): + return + if not any(int(n.ref) in ring_nodes for n in w.nodes): + return + got = _coords(w) + if got is None or len(got[1]) < 2: + return + generic.append({"way_id": int(w.id), "tags": tags, "node_ids": got[0], "coords": got[1]}) + + print(f"Reading roundabout rings from {pbf}…", file=sys.stderr, flush=True) + # Only objects with a highway key reach Python (big speedup on large PBFs). + Rings().apply_file(pbf, locations=True, filters=[osmium.filter.KeyFilter("highway")]) + if ring_nodes: + print(f"Reading approach roads for {len(generic)} ring ways…", file=sys.stderr, flush=True) + Approaches().apply_file(pbf, locations=True, filters=[osmium.filter.KeyFilter("highway")]) + return roundabout_rows(generic) + + +def _count_sources(ways: list[dict]) -> tuple[int, int]: + filled = sum(1 for w in ways if is_fill_source(w.get("source"))) + tagged = len(ways) - filled + return tagged, filled + + +def write_db(path: str, ways: list[dict], extra_meta: dict | None = None, + rb_rows: list[dict] | None = None) -> int: + con = OsmSpeedLimitDB.create(path) + for row in rb_rows or []: + OsmSpeedLimitDB.insert_rb_way(con, row) + OsmSpeedLimitDB.recount_rb_ways(con) + n = 0 + for w in ways: + OsmSpeedLimitDB.insert_way( + con, w["way_id"], w["name"], w["highway"], w["maxspeed_ms"], w["coords"], + junction=w.get("junction") or "", estimated=bool(w.get("estimated")), + ) + n += 1 + if n % 100000 == 0: + print(f" {n} ways…", file=sys.stderr, flush=True) + con.commit() + tagged, filled = _count_sources(ways) + meta = { + "attribution": ATTRIBUTION, + "license": LICENSE, + "license_url": LICENSE_URL, + "way_count": str(n), + "tagged_way_count": str(tagged), + "filled_way_count": str(filled), + } + if rb_rows is not None: + # Pack v4: rb_ways (roundabout rings + approaches, any maxspeed). Readers + # without rb support ignore the extra tables. + meta["pack_schema"] = "4" + if extra_meta: + meta.update({str(k): str(v) for k, v in extra_meta.items()}) + con.executemany("INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", list(meta.items())) + con.commit() + con.close() + return n + + +def _write_zst(sqlite_path: str) -> str: + import zstandard as zstd + zst_path = sqlite_path + ".zst" + cctx = zstd.ZstdCompressor(level=19) + with open(sqlite_path, "rb") as inf, open(zst_path, "wb") as outf: + cctx.copy_stream(inf, outf) + return zst_path + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description="Build NAP OSM speed-limit sqlite (ODbL)") + p.add_argument("--pbf", help="OSM PBF (ideally pre-filtered to highway+maxspeed)") + p.add_argument("--from-json", help="Overpass JSON") + p.add_argument("--out", required=True, help="Output sqlite path") + p.add_argument("--zst", action="store_true", help="Also write .zst via Python zstandard") + p.add_argument("--bbox", type=_parse_bbox, default=None, help="south,west,north,east (limit PBF ways)") + p.add_argument("--lat", type=float, help="Center latitude (with --lon / --radius-km)") + p.add_argument("--lon", type=float, help="Center longitude") + p.add_argument("--radius-km", type=float, default=None) + p.add_argument("--benson", action="store_true", + help="Use the ~100 mile Benson, MN bbox clipped to Minnesota") + p.add_argument("--fill-mn-statutory", action="store_true", + help="Fill unmarked fillable highways with Minn. Stat. 169.14 estimates, Minnesota only (NAP pack only)") + p.add_argument("--fill-us-defaults", action="store_true", + help="Fill unmarked drivable highways with each state's default limit (us_statutory; MN = 169.14)") + p.add_argument("--merge-into", help="Existing NAP sqlite to overlay the bbox into (keeps US tagged coverage)") + p.add_argument("--no-roundabouts", action="store_true", + help="Skip the rb_ways table (roundabout rings + approach roads, pack v4+)") + args = p.parse_args(argv) + + bbox = args.bbox + if args.benson: + bbox = benson_fill_bbox() + elif args.lat is not None and args.lon is not None: + radius = args.radius_km if args.radius_km is not None else BENSON_RADIUS_MILES * 1.609344 + bbox = bbox_from_center(args.lat, args.lon, radius) + elif (args.lat is None) ^ (args.lon is None): + p.error("provide both --lat and --lon") + + fill = bool(args.fill_mn_statutory or args.fill_us_defaults) + mn_only = bool(args.fill_mn_statutory and not args.fill_us_defaults) + places: PlaceIndex | None = None + if fill and args.pbf: + places = _places_from_pyosmium(args.pbf) + + rb_rows: list[dict] | None = None + if args.from_json: + with open(args.from_json, encoding="utf-8") as f: + payload = json.load(f) + ways = ways_from_overpass(payload, fill_unmarked=fill) + if not args.no_roundabouts: + rb_rows = rb_rows_from_overpass(payload) + source = os.path.basename(args.from_json) + elif args.pbf: + ways = _ways_from_pyosmium(args.pbf, bbox=bbox, fill_unmarked=fill, places=places, mn_only=mn_only) + if not args.no_roundabouts: + rb_rows = _rb_rows_from_pyosmium(args.pbf, bbox=bbox) + source = os.path.basename(args.pbf) + else: + p.error("provide --pbf or --from-json") + if rb_rows is not None: + rings = sum(1 for r in rb_rows if r["role"] == ROLE_RING) + print(f"Roundabouts: {rings} ring ways, {len(rb_rows) - rings} approach pieces (no maxspeed needed)", file=sys.stderr) + + tagged, filled = _count_sources(ways) + print(f"Prepared {len(ways)} ways ({tagged} tagged OSM maxspeed, {filled} estimated state-default fills)", file=sys.stderr) + + extra_meta: dict[str, str] = {"source": source} + if bbox is not None: + extra_meta["fill_bbox"] = ",".join(f"{x:.6f}" for x in bbox) + extra_meta["fill_center"] = f"{BENSON_LAT},{BENSON_LON}" if args.benson else "" + if fill: + extra_meta["fill_source"] = FILL_SOURCE if mn_only else "us_statutory (_default, MN_169.14)" + extra_meta["fill_notes"] = FILL_NOTES + extra_meta["tagged_way_count"] = str(tagged) + extra_meta["filled_way_count"] = str(filled) + extra_meta["place_polygon_count"] = str(len(places) if places is not None else 0) + + if args.merge_into: + if bbox is None: + p.error("--merge-into requires --bbox, --benson, or --lat/--lon") + src = os.path.abspath(args.merge_into) + dest = os.path.abspath(args.out) + if not os.path.isfile(src): + p.error(f"--merge-into file not found: {src}") + if src != dest: + os.makedirs(os.path.dirname(dest) or ".", exist_ok=True) + print(f"Copying {src} → {dest}", file=sys.stderr) + shutil.copy2(src, dest) + print(f"Overlaying {len(ways)} ways into {dest} (delete ∩ bbox, then insert)", file=sys.stderr) + deleted, inserted = merge_ways_into_db(dest, ways, bbox, extra_meta, rb_rows=rb_rows) + # merge_ways_into_db recounts way_count; keep tagged/filled overlay counts in meta. + con = sqlite3.connect(dest) + try: + con.executemany( + "INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", + [ + ("tagged_way_count", str(tagged)), + ("filled_way_count", str(filled)), + ("overlay_deleted", str(deleted)), + ("overlay_inserted", str(inserted)), + ], + ) + con.commit() + finally: + con.close() + n = inserted + print(f"Replaced {deleted} intersecting ways; inserted {inserted} ({tagged} tagged, {filled} filled)", file=sys.stderr) + else: + print(f"Writing {len(ways)} ways → {args.out}", file=sys.stderr) + n = write_db(args.out, ways, extra_meta=extra_meta, rb_rows=rb_rows) + + sz = os.path.getsize(args.out) if os.path.isfile(args.out) else 0 + print(f"Wrote {n} overlay ways, {sz / 1e6:.0f} MB sqlite (ODbL, {ATTRIBUTION})") + if fill: + print(FILL_NOTES, file=sys.stderr) + if args.zst: + zst_path = _write_zst(args.out) + zsz = os.path.getsize(zst_path) + print(f"Wrote {zst_path} ({zsz / 1e6:.0f} MB). Attach to GitHub Release {os.path.basename(zst_path)}.") + if n == 0: + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/nap/calibrate_pedal.py b/scripts/nap/calibrate_pedal.py new file mode 100755 index 00000000000000..e137a564059c1e --- /dev/null +++ b/scripts/nap/calibrate_pedal.py @@ -0,0 +1,503 @@ +#!/usr/bin/env python3 +""" +Tesla Pre-AP Comma Pedal Calibration Tool (GUI version) +Adapted from calibrate_pedal.py for use with ScriptRunner (no keyboard input). + +CRITICAL: This script uses DIRECT PANDA ACCESS with SAFETY_ALLOUTPUT (mode 17). +This bypasses the normal safety layer to allow sending pedal commands while +the car is in Neutral (not engaged). + +Reads configuration from openpilot Params and saves calibration results back to Params. +""" + +import time +import sys +import struct +from ctypes import create_string_buffer + +from openpilot.common.params import Params +from opendbc.car.tesla.preap.nap_params import NAPParamKeys + +# ============================================ +# Safety Mode Constants +# ============================================ +SAFETY_SILENT = 0 +SAFETY_ALLOUTPUT = 17 + +# ============================================ +# Pedal Constants from Tinkla +# ============================================ +M1 = 0.050796813 +M2 = 0.101593626 +D = -22.85856576 + +# CAN Message IDs +GAS_SENSOR_ID = 0x552 +GAS_COMMAND_ID = 0x551 +GTW_STATUS_ID = 0x348 +BRAKE_MESSAGE_ID = 0x20A +DI_TORQUE1_ID = 0x108 +DI_TORQUE2_ID = 0x118 + +# Timing +PEDAL_TIMEOUT_MS = 500 +MAX_PEDAL_ERRORS = 10 +SEND_RATE_MS = 20 + +# Gear values +GEAR_NEUTRAL = 0x30 + + +def current_time_ms(): + return int(round(time.monotonic() * 1000)) + + +def p(msg): + """Print with flush for real-time ScriptRunner display.""" + print(msg, flush=True) + + +class PedalCalibrator: + """Comma Pedal Calibrator using Direct Panda Access.""" + + @staticmethod + def checksum(msg_id, dat): + ret = (msg_id & 0xFF) + ((msg_id >> 8) & 0xFF) + ret += sum(dat) + return ret & 0xFF + + def __init__(self, params: Params): + from panda import Panda + + self.params = params + + p("Initializing...") + p("Configuring Panda...") + + try: + self.panda = Panda() + p(" Connected to Panda") + except Exception as e: + p(f" ERROR: Panda not found: {e}") + raise + + p(f" Setting safety mode to ALLOUTPUT ({SAFETY_ALLOUTPUT})...") + self.panda.set_safety_mode(SAFETY_ALLOUTPUT) + p(" Safety mode set") + + # Read pedal CAN bus from Params + pedal_bus = params.get(NAPParamKeys.PEDAL_CAN_BUS, return_default=True) + self.pedal_can = pedal_bus if pedal_bus in (0, 2) else 2 + p(f" Pedal CAN bus: {self.pedal_can}") + + # Rolling counter (0-15) + self.pedal_idx = 0 + + # Pedal state + self.rcv_pedal_idx = -1 + self.last_rcv_pedal_idx = -1 + self.last_pedal_seen_ms = 0 + self.last_pedal_sent_ms = 0 + self.pedal_interceptor_state = 0 + self.pedal_interceptor_value = 1000.0 + self.pedal_interceptor_value2 = 1000.0 + self.pedal_available = False + self.pedal_timeout = True + self.pedal_error_count = 0 + self.pedal_enabled = 0 + self.tx_count = 0 + + # Car state + self.car_on = False + self.brake_pressed = False + self.gear_shifter = None + self.gear_neutral = False + self.di_gas = 0.0 + + # Calibration state + self.status = 0 + self.prev_status = -1 + self.frame = 0 + + # Stage 2: Pedal zero + self.pedal_zero_count = 0 + self.pedal_zero_values_to_read = 100 + self.pedal_zero_sum = 0.0 + + # Stage 3: Pedal max detection + self.pedal_last_value_sent = 0.0 + self.pedal_pressed_value = -1000.0 + self.pedal_max_value = -1000.0 + self.pedal_step = 0 + + # Stage 4: Fine-tuning + self.finetuning_stage = 0 + self.finetuning_target = 99.6 + self.finetuning_step = 0.1 + self.finetuning_sum = 0.0 + self.finetuning_count = 0 + self.finetuning_steps = 10 + self.finetuning_best_val = 0.0 + self.finetuning_best_delta = 1000.0 + self.finetuning_best_result = -1000.0 + self.finetuning_start = 0.0 + + # Stage 5: Validation + self.validation_stage = 0 + self.validation_target = 0.0 + self.validation_count = 0 + self.validation_sum = 0.0 + self.validation_steps = 10 + self.validation_value = 0.0 + + # Final values + self.pedal_min = -1000.0 + self.pedal_max = -1000.0 + self.pedal_pressed = -1000.0 + self.pedal_factor = -1000.0 + + def cleanup(self): + """Restore Panda to safe state.""" + if hasattr(self, 'panda') and self.panda is not None: + p("") + p("=" * 50) + p("RESTORING PANDA SAFETY MODE") + p("=" * 50) + try: + p(" Disabling pedal...") + self.send_pedal_command(0, enable=0) + time.sleep(0.1) + p(f" Setting safety mode to SILENT ({SAFETY_SILENT})...") + self.panda.set_safety_mode(SAFETY_SILENT) + p(" Panda safety restored") + except Exception as e: + p(f" Warning: {e}") + try: + self.panda.close() + except Exception: + pass + + def send_pedal_command(self, accel_command, enable=1): + msg_id = GAS_COMMAND_ID + msg_len = 6 + + if enable == 1: + int_accel = int((accel_command - D) / M1) + int_accel2 = int((accel_command - D) / M2) + else: + int_accel = 0 + int_accel2 = 0 + + int_accel = max(0, min(65534, int_accel)) + int_accel2 = max(0, min(65534, int_accel2)) + + msg = create_string_buffer(msg_len) + struct.pack_into( + "BBBBB", msg, 0, + (int_accel >> 8) & 0xFF, + int_accel & 0xFF, + (int_accel2 >> 8) & 0xFF, + int_accel2 & 0xFF, + ((enable << 7) | (self.pedal_idx & 0x0F)) & 0xFF, + ) + struct.pack_into("B", msg, msg_len - 1, self.checksum(msg_id, msg.raw)) + + self.panda.can_send(msg_id, msg.raw, self.pedal_can) + self.pedal_idx = (self.pedal_idx + 1) % 16 + self.last_pedal_sent_ms = current_time_ms() + self.tx_count += 1 + + def process_can(self): + try: + for msg in self.panda.can_recv(): + if len(msg) == 4: + addr, _, dat, src = msg + elif len(msg) == 3: + addr, dat, src = msg + else: + continue + + if addr == GTW_STATUS_ID: + self.car_on = (dat[0] & 0x01) == 1 + elif addr == BRAKE_MESSAGE_ID: + self.brake_pressed = ((dat[0] >> 2) & 0x03) != 1 + elif addr == DI_TORQUE2_ID: + self.gear_shifter = dat[1] & 0x70 + self.gear_neutral = self.gear_shifter == GEAR_NEUTRAL + elif addr == DI_TORQUE1_ID: + self.di_gas = dat[6] * 0.4 + elif addr == GAS_SENSOR_ID: + self.pedal_interceptor_state = (dat[4] >> 7) & 0x01 + self.pedal_interceptor_value = ((dat[0] << 8) + dat[1]) * M1 + D + self.pedal_interceptor_value2 = ((dat[2] << 8) + dat[3]) * M2 + D + self.rcv_pedal_idx = dat[4] & 0x0F + self.last_pedal_seen_ms = current_time_ms() + except Exception as e: + if "not enough values" not in str(e): + p(f" CAN recv error: {e}") + + def check_safety(self): + if not self.car_on: + if self.frame % 100 == 0: + p(" Waiting: Car is not ON! Turn ignition on.") + return False + + if not self.brake_pressed: + if self.frame % 100 == 0: + p(" Waiting: Brake not pressed! Press and hold brake.") + if self.pedal_enabled: + self.send_pedal_command(0, enable=0) + self.pedal_enabled = 0 + return False + + if not self.gear_neutral: + if self.frame % 100 == 0: + p(" Waiting: Car is not in NEUTRAL! Shift to N.") + if self.pedal_enabled: + self.send_pedal_command(0, enable=0) + self.pedal_enabled = 0 + return False + + if self.di_gas > 0 and self.status < 3: + if self.frame % 100 == 0: + p(" Waiting: Accelerator pedal is pressed! Release it.") + if self.pedal_enabled: + self.send_pedal_command(0, enable=0) + self.pedal_enabled = 0 + return False + + return True + + STATUS_MESSAGES = [ + "Initializing...", + "Configuring Panda...", + "Reading Pedal Zero...", + "Detecting Pedal Max...", + "Fine-tuning calibration...", + "Validating calibration...", + "Saving values...", + "Calibration Complete!", + ] + + def run(self, rate=100): + self.status = 2 # Start at "Reading Pedal Zero" + + p("") + p("Waiting for safety conditions...") + p(" - Car ON") + p(" - Gear in NEUTRAL") + p(" - Brake PRESSED") + p(" - Accelerator RELEASED") + p(f" [TX: Bus {self.pedal_can}, ID 0x{GAS_COMMAND_ID:03X}]") + + loop_period = 1.0 / rate + + while True: + loop_start = time.monotonic() + self.frame += 1 + curr_time_ms = current_time_ms() + + self.process_can() + + if self.status != self.prev_status: + p(f"\n{self.STATUS_MESSAGES[self.status]}") + self.prev_status = self.status + + if self.status == 7: + p("\nCalibration Complete!") + return 0 + + if not self.check_safety(): + time.sleep(loop_period) + continue + + # Send pedal command at 50Hz to keep watchdog happy + if curr_time_ms - self.last_pedal_sent_ms >= SEND_RATE_MS: + self.send_pedal_command(self.pedal_last_value_sent, self.pedal_enabled) + if self.tx_count % 100 == 0: + p(f" [TX #{self.tx_count}: val={self.pedal_last_value_sent:.1f}, en={self.pedal_enabled}]") + + # Check for new pedal message + if self.rcv_pedal_idx != self.last_rcv_pedal_idx: + self.last_rcv_pedal_idx = self.rcv_pedal_idx + + if self.pedal_interceptor_state == 0: + self.pedal_error_count = 0 + + # Stage 2: Reading pedal zero + if self.status == 2: + self.pedal_zero_sum += self.pedal_interceptor_value + self.pedal_zero_count += 1 + if self.pedal_zero_count >= self.pedal_zero_values_to_read: + self.pedal_min = self.pedal_zero_sum / self.pedal_zero_count + p(f"\n Pedal MIN: {self.pedal_min:.2f}") + self.pedal_last_value_sent = self.pedal_min + self.pedal_enabled = 1 + self.status = 3 + elif self.frame % 20 == 0: + p(f" Reading zero: {self.pedal_zero_count}/{self.pedal_zero_values_to_read} (val={self.pedal_interceptor_value:.2f})") + + # Stage 3: Detecting pedal max + elif self.status == 3: + if self.di_gas >= 99.6 and self.pedal_max_value == -1000 and self.pedal_step == 1: + p(f"\n Pedal MAX: {self.pedal_last_value_sent:.2f}") + self.pedal_max_value = self.pedal_last_value_sent + self.pedal_last_value_sent = self.pedal_max_value - 0.5 + self.finetuning_start = self.pedal_max_value - 0.5 + self.pedal_step = 0 + self.status = 4 + + if self.di_gas > 0 and self.pedal_pressed_value == -1000 and self.pedal_step == 1: + p(f"\n Pedal PRESSED threshold: {self.pedal_last_value_sent:.2f}") + self.pedal_pressed_value = self.pedal_last_value_sent + + if self.di_gas < 100: + if self.frame % 50 == 0: + p(f" Detecting: sent {self.pedal_last_value_sent:.1f} -> car sees {self.di_gas:.1f}%") + if self.pedal_step == 1: + self.pedal_last_value_sent += 1 + self.pedal_step = 0 + else: + self.pedal_step = 1 + + # Stage 4: Fine-tuning + elif self.status == 4: + if self.finetuning_count < self.finetuning_steps: + self.finetuning_sum += self.di_gas + self.finetuning_count += 1 + + if self.finetuning_count == self.finetuning_steps: + avg = self.finetuning_sum / self.finetuning_count + delta = abs(self.finetuning_target - avg) + if delta < self.finetuning_best_delta: + self.finetuning_best_val = self.pedal_last_value_sent + self.finetuning_best_delta = delta + + self.pedal_last_value_sent += self.finetuning_step + p(f" Fine-tuning: target {self.finetuning_target:.1f}%, got {avg:.1f}%") + self.finetuning_count = 0 + self.finetuning_sum = 0 + + if self.pedal_last_value_sent > self.finetuning_start + 0.5: + if self.finetuning_stage == 0: + self.pedal_max = self.finetuning_best_val + self.finetuning_best_val = 0 + self.finetuning_best_delta = 1000.0 + self.finetuning_stage = 1 + self.pedal_last_value_sent = self.pedal_pressed_value - 0.5 + self.finetuning_start = self.pedal_pressed_value - 0.5 + self.finetuning_target = 0.4 + p("\n Done fine-tuning MAX") + else: + self.pedal_pressed = self.finetuning_best_val + self.pedal_last_value_sent = self.pedal_min + self.pedal_factor = 100.0 / (self.pedal_max - self.pedal_pressed) + self.status = 5 + p("\n Done fine-tuning ZERO") + + # Stage 5: Validation + elif self.status == 5: + if self.validation_stage == 0: + self.validation_stage = 1 + self.validation_target = self.validation_stage * 10 + self.validation_count = 0 + self.validation_sum = 0 + self.validation_value = self.pedal_pressed + self.validation_target * (self.pedal_max - self.pedal_pressed) / 100.0 + self.pedal_last_value_sent = self.validation_value + else: + if self.validation_count < self.validation_steps: + self.validation_sum += self.di_gas + self.validation_count += 1 + if self.validation_count == self.validation_steps: + avg = self.validation_sum / self.validation_count + p(f" Validating {self.validation_target:.0f}%: got {avg:.1f}%") + self.validation_stage += 1 + if self.validation_stage == 10: + p("\n Validation complete") + self.status = 6 + else: + self.validation_target = self.validation_stage * 10 + self.validation_count = 0 + self.validation_sum = 0 + self.validation_value = self.pedal_pressed + self.validation_target * (self.pedal_max - self.pedal_pressed) / 100.0 + self.pedal_last_value_sent = self.validation_value + + # Stage 6: Save values to Params + elif self.status == 6: + p("") + p("=" * 50) + p("CALIBRATION RESULTS") + p("=" * 50) + + p(f" Pedal Min: {self.pedal_min:.2f}") + self.params.put(NAPParamKeys.PEDAL_CALIB_MIN, self.pedal_min) + + p(f" Pedal Max: {self.pedal_max:.2f}") + self.params.put(NAPParamKeys.PEDAL_CALIB_MAX, self.pedal_max) + + p(f" Pedal Zero: {self.pedal_pressed:.2f}") + self.params.put(NAPParamKeys.PEDAL_CALIB_ZERO, self.pedal_pressed) + + p(f" Pedal Factor: {self.pedal_factor:.4f}") + self.params.put(NAPParamKeys.PEDAL_CALIB_FACTOR, self.pedal_factor) + + self.params.put_bool(NAPParamKeys.PEDAL_CALIB_DONE, True) + self.params.put_bool(NAPParamKeys.PEDAL_ENABLED, True) + p("\n Saved to openpilot Params") + + self.status = 7 + + # Check pedal timeout + self.pedal_timeout = curr_time_ms - self.last_pedal_seen_ms > PEDAL_TIMEOUT_MS + if self.pedal_timeout: + self.pedal_error_count += 1 + if self.pedal_error_count > MAX_PEDAL_ERRORS * 10: + p("\nERROR: Pedal communication timeout!") + return 1 + + elapsed = time.monotonic() - loop_start + if elapsed < loop_period: + time.sleep(loop_period - elapsed) + + return 0 + + +def main(): + p("=" * 60) + p("COMMA PEDAL CALIBRATION") + p("=" * 60) + p("") + p("REQUIREMENTS:") + p(" 1. Park in a SAFE location") + p(" 2. Turn the car ON (ready to drive)") + p(" 3. Shift into NEUTRAL (N)") + p(" 4. Press and HOLD the BRAKE pedal") + p("") + p("SAFETY_ALLOUTPUT mode will be used for TX.") + p("Safety is restored automatically on exit.") + p("=" * 60) + + params = Params() + calibrator = None + exit_code = 0 + + try: + calibrator = PedalCalibrator(params) + exit_code = calibrator.run() + except KeyboardInterrupt: + p("\nInterrupted by user.") + exit_code = 1 + except Exception as e: + p(f"\nERROR: {e}") + import traceback + traceback.print_exc() + exit_code = 1 + finally: + if calibrator is not None: + calibrator.cleanup() + + return exit_code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/nap/calibrate_radar.py b/scripts/nap/calibrate_radar.py new file mode 100755 index 00000000000000..4d64680b4ae5f1 --- /dev/null +++ b/scripts/nap/calibrate_radar.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +""" +Tesla Pre-AP Radar Calibration Tool (GUI version) +Displays filtered radar points to help align the Bosch radar. + +Shows only tracked objects within the calibration window: + - Distance: 2.5m to 14.5m ahead + - Lateral: +/-1.0m from center + +Place a metal calibration target (e.g., corner reflector or metal plate) +at a known distance and adjust radar aim until the target appears centered. + +Uses direct Panda access (stops pandad via ScriptRunner). +""" + +import time +import sys + +# ============================================ +# Radar CAN Constants (Bosch, 32 points) +# ============================================ +RADAR_BUS = 1 # CANBUS.radar +NUM_RADAR_POINTS = 32 +# RadarPoint{i}_A = 0x310 + i*2 +# RadarPoint{i}_B = 0x311 + i*2 +RADAR_ADDR_START = 0x310 +RADAR_ADDR_END = 0x36F + +# ============================================ +# Calibration Window +# ============================================ +MIN_LONG = 2.5 # meters (min distance) +MAX_LONG = 14.5 # meters (max distance) +MIN_LAT = -1.0 # meters (left) +MAX_LAT = 1.0 # meters (right) + +# ============================================ +# Display +# ============================================ +DISPLAY_INTERVAL = 0.5 # seconds between screen refreshes +PANDA_CONNECT_RETRIES = 5 +PANDA_CONNECT_DELAY = 2.0 + + +def p(msg): + """Print with flush for real-time ScriptRunner display.""" + print(msg, flush=True) + + +def extract_signal(data, start_bit, length): + """Extract a little-endian CAN signal from raw bytes.""" + value = 0 + for i in range(length): + bit_pos = start_bit + i + byte_idx = bit_pos // 8 + bit_idx = bit_pos % 8 + if byte_idx < len(data) and (data[byte_idx] & (1 << bit_idx)): + value |= (1 << i) + return value + + +def parse_radar_a(data): + """Parse RadarPoint_A message (position, speed, status).""" + return { + 'long_dist': extract_signal(data, 0, 12) * 0.0625, + 'long_speed': extract_signal(data, 12, 12) * 0.0625 - 128, + 'lat_dist': extract_signal(data, 24, 11) * 0.125 - 128, + 'prob_exist': extract_signal(data, 35, 5) * 3.125, + 'long_accel': extract_signal(data, 40, 10) * 0.03125 - 16, + 'valid': extract_signal(data, 55, 1), + 'meas': extract_signal(data, 61, 1), + 'tracked': extract_signal(data, 62, 1), + 'index': extract_signal(data, 63, 1), + } + + +def parse_radar_b(data): + """Parse RadarPoint_B message (lateral speed, classification).""" + return { + 'lat_speed': extract_signal(data, 0, 10) * 0.125 - 64, + 'length': extract_signal(data, 10, 6) * 0.125, + 'dz': extract_signal(data, 16, 6) * 0.25 - 5, + 'moving_state': extract_signal(data, 22, 2), + 'index2': extract_signal(data, 63, 1), + } + + +def connect_panda(): + """Connect to Panda with retries (pandad may still be shutting down).""" + from panda import Panda + + for attempt in range(PANDA_CONNECT_RETRIES): + try: + panda = Panda() + return panda + except Exception as e: + if attempt < PANDA_CONNECT_RETRIES - 1: + p(f" Panda not ready ({e}), retrying in {PANDA_CONNECT_DELAY}s...") + time.sleep(PANDA_CONNECT_DELAY) + else: + raise + + +def main(): + p("=" * 60) + p("RADAR CALIBRATION TOOL") + p("=" * 60) + p("") + p("Place a calibration target (metal reflector or plate)") + p("3-10m ahead of the vehicle, centered on the driving axis.") + p("") + p("Adjust radar aim until the target shows centered at ~0.0m lateral.") + p("") + p(f"Filter window: {MIN_LONG}-{MAX_LONG}m ahead, {MIN_LAT} to {MAX_LAT}m lateral") + p("Press Cancel when done.") + p("=" * 60) + + panda = None + try: + p("\nConnecting to Panda...") + panda = connect_panda() + p(" Connected") + + # Read-only mode — we just need CAN RX + panda.set_safety_mode(17) # SAFETY_ALLOUTPUT to ensure CAN forwarding + p(" Safety mode set") + + # Radar point storage + points_a = {} + points_b = {} + + start_time = time.monotonic() + last_display = 0 + msg_count = 0 + radar_msgs_seen = False + + p("\nListening for radar data on CAN bus 1...") + + while True: + try: + for msg in panda.can_recv(): + if len(msg) == 4: + addr, _, dat, src = msg + elif len(msg) == 3: + addr, dat, src = msg + else: + continue + + if src != RADAR_BUS: + continue + + if RADAR_ADDR_START <= addr <= RADAR_ADDR_END: + radar_msgs_seen = True + point_idx = (addr - RADAR_ADDR_START) // 2 + is_b = (addr - RADAR_ADDR_START) % 2 == 1 + data = bytes(dat) if not isinstance(dat, (bytes, bytearray)) else dat + + if is_b: + points_b[point_idx] = parse_radar_b(data) + else: + points_a[point_idx] = parse_radar_a(data) + msg_count += 1 + except Exception as e: + if "not enough values" not in str(e): + p(f" CAN recv error: {e}") + + now = time.monotonic() + if now - last_display >= DISPLAY_INTERVAL: + last_display = now + elapsed = now - start_time + + if not radar_msgs_seen: + p(f" [{elapsed:.0f}s] No radar messages on bus {RADAR_BUS}...") + time.sleep(0.5) + continue + + # Filter points in calibration window + filtered = [] + for i in range(NUM_RADAR_POINTS): + if i not in points_a: + continue + pa = points_a[i] + if not pa['tracked']: + continue + if pa['long_dist'] <= 0 or pa['long_dist'] > 250: + continue + if pa['prob_exist'] < 50: + continue + + d = pa['long_dist'] + y = pa['lat_dist'] + if MIN_LONG <= d <= MAX_LONG and MIN_LAT <= y <= MAX_LAT: + filtered.append((i, pa)) + + p(f"\n--- [{elapsed:.0f}s] {len(filtered)} point(s) in calibration window ---") + if filtered: + p(f" {'#':>3s} {'Dist(m)':>8s} {'Lat(m)':>8s} {'Speed':>8s} {'Prob':>6s}") + p(f" {'---':>3s} {'-------':>8s} {'------':>8s} {'-----':>8s} {'----':>6s}") + for idx, pa in filtered: + p(f" {idx:3d} {pa['long_dist']:8.2f} {pa['lat_dist']:8.2f} {pa['long_speed']:8.2f} {pa['prob_exist']:5.1f}%") + else: + p(" (no points in calibration window)") + + time.sleep(0.01) + + except KeyboardInterrupt: + p("\nStopped.") + except Exception as e: + p(f"\nERROR: {e}") + import traceback + traceback.print_exc() + return 1 + finally: + if panda is not None: + try: + panda.set_safety_mode(0) # SAFETY_SILENT + panda.close() + p("\nPanda connection closed.") + except Exception: + pass + + p("\nRadar calibration monitoring ended.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/nap/diagnose_radar.py b/scripts/nap/diagnose_radar.py new file mode 100755 index 00000000000000..2320ab86af1201 --- /dev/null +++ b/scripts/nap/diagnose_radar.py @@ -0,0 +1,643 @@ +#!/usr/bin/env python3 +""" +Tesla Pre-AP Radar Diagnostic Tool + +Two modes of operation: + --panda Direct panda health check (reads safety mode, bus config). + Does NOT change safety mode. Quick one-shot check. + (default) Cereal CAN monitor. Reads CAN bus via cereal messaging while + openpilot runs normally, so GTW emulation stays active. + +Monitors CAN bus 1 for: + - All GTW emulation messages (0x109, 0x119, 0x129, 0x149, 0x159, + 0x169, 0x199, 0x1A9, 0x209, 0x219, 0x2A9, 0x2B9, 0x2D9) + - Radar status: 0x631 (init) -> 0x300 (active) + - Radar alert matrix (0x501) for error codes + - Radar tracks (0x310-0x36F) for non-zero vRel + +Run on-device: + # With openpilot running (preferred — sees GTW emulation live): + python3 scripts/nap/diagnose_radar.py + + # Quick panda health check (can run anytime): + python3 scripts/nap/diagnose_radar.py --panda +""" + +import time +import sys + +# ============================================ +# GTW Emulation Messages Expected on Bus 1 +# ============================================ +GTW_MESSAGES = { + 0x109: "DI_torque1", + 0x119: "DI_torque2", + 0x129: "ESP_115h", + 0x149: "ESP_145h", + 0x159: "ESP_C (Brake)", + 0x169: "ESP_wheelSpeeds", + 0x199: "STW_ANGLHP_STAT", + 0x1A9: "DI_espControl", + 0x209: "GTW_odo", + 0x219: "STW_ACTN_RQ", + 0x2A9: "GTW_carConfig", + 0x2B9: "VIP_405HS", + 0x2D9: "BC_status", +} + +# Bus 0 source address → Bus 1 GTW destination address mapping +# The firmware re-addresses these on forwarding. We monitor the BUS 0 sources +# because CAN TX doesn't loopback to RX (we can't see our own GTW TX on bus 1). +GTW_SOURCE_MAP = { + # src_addr: (dest_addr, name, expected_hz) + 0x108: (0x109, "DI_torque1", 100), + 0x118: (0x119, "DI_torque2", 100), # also source for 0x169 wheel speed synthesis + 0x115: (0x129, "ESP_115h", 50), # re-addressed; also source for 0x1A9 synthesis + 0x145: (0x149, "ESP_145h", 50), + 0x158: (0x159, "ESP_C (Brake)", 50), + # 0x169 is SYNTHESIZED from 0x118 — no direct source + 0x0E: (0x199, "STW_ANGLHP_STAT", 100), + # 0x1A9 is SYNTHESIZED from 0x115 — no direct source + 0x20A: (0x209, "GTW_odo", 10), + 0x308: (0x219, "STW_ACTN_RQ", 10), # re-addressed 0x308 → 0x219 + 0x2A8: (0x2A9, "GTW_carConfig", 1), + 0x405: (0x2B9, "VIP_405HS", 2), # re-addressed 0x405 → 0x2B9 + 0x398: (0x2D9, "BC_status", 10), # re-addressed 0x398 → 0x2D9 +} + +# Critical messages for radar tracking (without these the radar can't compute Doppler) +CRITICAL_SOURCES = {0x118, 0x0E, 0x115} # wheel speed, steering, ESP control + +# Radar control/status messages +RADAR_STATUS_MSGS = { + 0x631: "Radar Init Sync", + 0x300: "Radar Active", + 0x501: "Radar Alert Matrix", +} + +# Radar track messages +RADAR_ADDR_START = 0x310 +RADAR_ADDR_END = 0x36F +NUM_RADAR_POINTS = 32 + +RADAR_BUS = 1 +DISPLAY_INTERVAL = 1.0 + +# Safety mode constants +SAFETY_TESLA_LEGACY = 36 +SAFETY_FLAG_PREAP = 32 +SAFETY_FLAG_RADAR_EMULATION = 256 +SAFETY_FLAG_RADAR_BEHIND_NOSECONE = 128 +SAFETY_FLAG_LONG_CONTROL = 1 +SAFETY_FLAG_ENABLE_PEDAL = 64 + + +def p(msg): + """Print with flush for real-time display.""" + print(msg, flush=True) + + +def extract_signal(data, start_bit, length): + """Extract a little-endian CAN signal from raw bytes.""" + value = 0 + for i in range(length): + bit_pos = start_bit + i + byte_idx = bit_pos // 8 + bit_idx = bit_pos % 8 + if byte_idx < len(data) and (data[byte_idx] & (1 << bit_idx)): + value |= (1 << i) + return value + + +def decode_wheel_speed_0x169(data): + """Decode ESP_wheelSpeeds (0x169) — 4 identical 13-bit speeds.""" + if len(data) < 8: + return None + b = data + rdlr = b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24) + rdhr = b[4] | (b[5] << 8) | (b[6] << 16) | (b[7] << 24) + + ws0 = rdlr & 0x1FFF + ws1 = (rdlr >> 13) & 0x1FFF + ws2 = ((rdlr >> 26) | ((rdhr & 0x7F) << 6)) & 0x1FFF + ws3 = (rdhr >> 7) & 0x1FFF + counter = (rdhr >> 20) & 0x0F + checksum = (rdhr >> 24) & 0xFF + + speeds_kph = [v * 0.04 for v in [ws0, ws1, ws2, ws3]] + sna = any(v == 0x1FFF for v in [ws0, ws1, ws2, ws3]) + + return { + 'speeds_kph': speeds_kph, + 'counter': counter, + 'checksum': checksum, + 'sna': sna, + 'raw': [ws0, ws1, ws2, ws3], + } + + +def decode_car_config_0x2A9(data): + """Decode GTW_carConfig (0x2A9) — check autopilot/radar config bits.""" + if len(data) < 8: + return None + rdlr = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24) + rdhr = data[4] | (data[5] << 8) | (data[6] << 16) | (data[7] << 24) + + park_assist = (rdlr >> 8) & 0x03 + fwd_radar_hw = (rdlr >> 6) & 0x03 + das_hw = (rdlr >> 10) & 0x03 + autopilot = (rdhr >> 28) & 0x03 + radar_pos = (rdhr >> 4) & 0x0F + epas_type = (rdhr >> 12) & 0x0F + + return { + 'park_assist': park_assist, + 'fwd_radar_hw': fwd_radar_hw, + 'das_hw': das_hw, + 'autopilot': autopilot, + 'radar_position': radar_pos, + 'epas_type': epas_type, + } + + +# ============================================ +# Mode 1: Panda Health Check (--panda) +# ============================================ +def panda_health_check(): + """Quick panda diagnostic — reads safety mode, param, bus config. + Does NOT change safety mode or interfere with openpilot. + """ + p("=" * 65) + p("PANDA HEALTH CHECK") + p("=" * 65) + + # Check NAPRadarEnabled param first + p("\n--- OPENPILOT PARAMS ---") + try: + from openpilot.common.params import Params + params = Params() + radar_enabled = params.get_bool("NAPRadarEnabled") + p(f" NAPRadarEnabled: {radar_enabled}") + if not radar_enabled: + p(" !! RADAR NOT ENABLED — GTW emulation will NOT run") + p(" !! Set NAPRadarEnabled=True in tesla_setup or params") + + radar_behind = params.get_bool("NAPRadarBehindNosecone") + p(f" NAPRadarBehindNosecone: {radar_behind}") + except Exception as e: + p(f" Could not read params: {e}") + p(" (This is OK if running outside openpilot environment)") + + p("\n--- PANDA CONNECTION ---") + try: + from panda import Panda + panda = Panda() + p(" Connected to Panda") + except Exception as e: + p(f" FAILED to connect: {e}") + return 1 + + try: + health = panda.health() + p("\n--- PANDA HEALTH ---") + safety_mode = health.get('safety_mode', health.get('safety_model', 'unknown')) + safety_param = health.get('safety_param', 'unknown') + p(f" Safety mode: {safety_mode} (expect {SAFETY_TESLA_LEGACY} = teslaLegacy)") + p(f" Safety param: {safety_param}") + + if safety_mode == SAFETY_TESLA_LEGACY: + p(" [OK] Safety mode is teslaLegacy") + else: + p(" [!!] Safety mode is NOT teslaLegacy!") + p(" GTW emulation is NOT running!") + + if isinstance(safety_param, int): + flags = [] + if safety_param & SAFETY_FLAG_PREAP: + flags.append("PREAP") + if safety_param & SAFETY_FLAG_LONG_CONTROL: + flags.append("LONG_CONTROL") + if safety_param & SAFETY_FLAG_ENABLE_PEDAL: + flags.append("ENABLE_PEDAL") + if safety_param & SAFETY_FLAG_RADAR_EMULATION: + flags.append("RADAR_EMULATION") + if safety_param & SAFETY_FLAG_RADAR_BEHIND_NOSECONE: + flags.append("RADAR_BEHIND_NOSECONE") + p(f" Flags: {' | '.join(flags) if flags else 'NONE'}") + p(f" Param binary: {safety_param:016b}") + + if not (safety_param & SAFETY_FLAG_RADAR_EMULATION): + p(" [!!] RADAR_EMULATION flag (256) is NOT SET!") + p(" GTW emulation codepath is disabled!") + p(" => This is likely the root cause of frozen radar data") + else: + p(" [OK] RADAR_EMULATION flag is set") + + if not (safety_param & SAFETY_FLAG_PREAP): + p(" [!!] PREAP flag (32) is NOT SET!") + else: + p(" [OK] PREAP flag is set") + + # Check CAN bus health + p("\n--- CAN BUS STATUS ---") + for _bus_key in ['can0', 'can1', 'can2']: + bus_health_fn = getattr(panda, 'can_health', None) + if bus_health_fn: + break + if bus_health_fn: + for bus_num in range(3): + try: + bh = bus_health_fn(bus_num) + p(f" Bus {bus_num}: " + + f"rx={bh.get('total_rx_cnt', bh.get('receive_count', '?'))}, " + + f"tx={bh.get('total_tx_cnt', bh.get('transmit_count', '?'))}, " + + f"err={bh.get('total_error_cnt', bh.get('bus_error', '?'))}, " + + f"fwd_bus={bh.get('bus_fwd', bh.get('forwarding_bus', '?'))}") + except Exception as e: + p(f" Bus {bus_num}: error reading health: {e}") + else: + p(" (can_health not available on this panda version)") + + # Quick CAN sniff — count bus 1 messages for 3 seconds + p("\n--- BUS 1 TRAFFIC (3s sniff) ---") + panda.can_clear(0xFFFF) + bus1_count = 0 + bus1_addrs = set() + sniff_start = time.monotonic() + while time.monotonic() - sniff_start < 3.0: + for msg in panda.can_recv(): + if len(msg) == 4: + addr, _, dat, src = msg + elif len(msg) == 3: + addr, dat, src = msg + else: + continue + if src == RADAR_BUS: + bus1_count += 1 + bus1_addrs.add(addr) + time.sleep(0.005) + + p(f" Total bus 1 messages: {bus1_count}") + p(f" Unique addresses: {len(bus1_addrs)}") + if bus1_count == 0: + p(" [!!] NO TRAFFIC on bus 1!") + p(" Radar is not connected, or CAN bus not configured") + else: + gtw_seen = bus1_addrs & set(GTW_MESSAGES.keys()) + radar_seen = {a for a in bus1_addrs if RADAR_ADDR_START <= a <= RADAR_ADDR_END} + status_seen = bus1_addrs & set(RADAR_STATUS_MSGS.keys()) + p(f" GTW emulation msgs: {len(gtw_seen)}/{len(GTW_MESSAGES)} present") + if gtw_seen: + for a in sorted(gtw_seen): + p(f" [OK] 0x{a:03X} {GTW_MESSAGES[a]}") + missing_gtw = set(GTW_MESSAGES.keys()) - gtw_seen + for a in sorted(missing_gtw): + p(f" [!!] 0x{a:03X} {GTW_MESSAGES[a]} MISSING") + p(f" Radar track msgs: {'YES' if radar_seen else 'NO'} ({len(radar_seen)} addrs)") + p(f" Radar status msgs: {sorted(f'0x{a:03X}' for a in status_seen) if status_seen else 'NONE'}") + + panda.close() + p("\nPanda closed (safety mode unchanged).") + + except Exception as e: + p(f"\nERROR: {e}") + import traceback + traceback.print_exc() + try: + panda.close() + except Exception: + pass + return 1 + + return 0 + + +# ============================================ +# Mode 2: Cereal CAN Monitor (default) +# ============================================ +def cereal_monitor(): + """Monitor CAN bus via cereal messaging while openpilot runs. + GTW emulation stays active because we don't touch the panda. + + Monitors BOTH buses: + - Bus 0: source messages that trigger GTW forwarding (measures input rates) + - Bus 1: radar output (tracks, status, any GTW loopback) + + Since CAN TX doesn't loopback to RX, we can't directly see GTW messages + on bus 1. But by measuring bus 0 source rates, we know exactly what the + radar is receiving (every source message triggers an event-driven forward). + """ + p("=" * 65) + p("RADAR DIAGNOSTIC TOOL (Cereal CAN Monitor)") + p("=" * 65) + p("") + p("Monitors bus 0 SOURCE rates (input to GTW emulation)") + p("and bus 1 radar output (tracks + status).") + p("CAN TX doesn't loopback, so GTW msgs won't appear on bus 1.") + p("Instead, bus 0 source rates = GTW forwarding rates.") + p("Ctrl+C to stop.") + p("=" * 65) + + try: + from cereal import messaging + except ImportError: + p("\nERROR: cereal not available. Run on-device with openpilot environment.") + p("Alternatively, use --panda mode for direct panda access.") + return 1 + + sm = messaging.SubMaster(['can']) + + # --- Bus 0 source message tracking --- + src_total_counts = dict.fromkeys(GTW_SOURCE_MAP, 0) + src_interval_counts = dict.fromkeys(GTW_SOURCE_MAP, 0) + src_last_timestamps = dict.fromkeys(GTW_SOURCE_MAP) + # Per-source: track max gap between consecutive messages (detect burstiness) + src_max_gap_ms = dict.fromkeys(GTW_SOURCE_MAP, 0.0) + src_min_gap_ms = {addr: float('inf') for addr in GTW_SOURCE_MAP} + src_gap_count = dict.fromkeys(GTW_SOURCE_MAP, 0) # gaps > 2x expected interval + # Per-second history for rate trend (last 10 seconds) + src_rate_history = {addr: [] for addr in GTW_SOURCE_MAP} + + # --- Bus 1 radar output tracking --- + radar_status_counts = dict.fromkeys(RADAR_STATUS_MSGS, 0) + radar_status = "UNKNOWN" + radar_status_transitions = [] # list of (timestamp, old_status, new_status) + tracks_with_velocity = 0 + total_tracked = 0 + last_car_config = None + alert_data = None + + # --- Vehicle speed from bus 0 source (0x118 DI_torque2) --- + last_vehicle_speed = None + + # --- Bus 1 GTW messages (shouldn't appear, but check anyway) --- + gtw_bus1_counts = dict.fromkeys(GTW_MESSAGES, 0) + + start_time = time.monotonic() + last_display = 0 + last_interval_reset = start_time + total_bus0_msgs = 0 + total_bus1_msgs = 0 + interval_num = 0 + + p("\nListening on CAN buses 0+1 via cereal...") + + try: + while True: + sm.update(100) # 100ms timeout + + if sm.updated['can']: + now = time.monotonic() + for msg in sm['can']: + addr = msg.address + bus = msg.src + data = bytes(msg.dat) + + # ---- Bus 0: GTW source messages ---- + if bus == 0 and addr in GTW_SOURCE_MAP: + total_bus0_msgs += 1 + src_total_counts[addr] += 1 + src_interval_counts[addr] += 1 + + # Track inter-message timing + prev_ts = src_last_timestamps[addr] + if prev_ts is not None: + gap_ms = (now - prev_ts) * 1000.0 + if gap_ms > src_max_gap_ms[addr]: + src_max_gap_ms[addr] = gap_ms + if gap_ms < src_min_gap_ms[addr]: + src_min_gap_ms[addr] = gap_ms + # Flag gaps > 2x expected interval + _, _, expected_hz = GTW_SOURCE_MAP[addr] + if expected_hz > 0: + expected_ms = 1000.0 / expected_hz + if gap_ms > expected_ms * 2.5: + src_gap_count[addr] += 1 + src_last_timestamps[addr] = now + + # Decode vehicle speed from DI_torque2 (0x118) + # This is the source for 0x169 wheel speed synthesis + if addr == 0x118 and len(data) >= 4: + rdlr = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24) + raw_speed = (rdlr >> 16) & 0xFFF # bits [27:16], 12-bit + speed_mph = raw_speed * 0.05 - 25.0 + speed_kph = speed_mph * 1.609344 + last_vehicle_speed = {'mph': speed_mph, 'kph': speed_kph, 'raw': raw_speed} + + # ---- Bus 1: Radar output ---- + if bus == RADAR_BUS: + total_bus1_msgs += 1 + + # Check for GTW messages on bus 1 (shouldn't appear due to no TX loopback) + if addr in GTW_MESSAGES: + gtw_bus1_counts[addr] += 1 + + # Radar status messages + if addr in RADAR_STATUS_MSGS: + radar_status_counts[addr] += 1 + new_status = None + if addr == 0x631: + new_status = "INIT (0x631)" + elif addr == 0x300: + new_status = "ACTIVE (0x300)" + elif addr == 0x501: + alert_data = data + + if new_status and new_status != radar_status: + radar_status_transitions.append( + (now - start_time, radar_status, new_status)) + radar_status = new_status + + # Radar track messages + if RADAR_ADDR_START <= addr <= RADAR_ADDR_END: + is_b = (addr - RADAR_ADDR_START) % 2 == 1 + if not is_b: + tracked = extract_signal(data, 62, 1) + if tracked: + total_tracked += 1 + vrel = extract_signal(data, 12, 12) * 0.0625 - 128 + if abs(vrel) > 0.1: + tracks_with_velocity += 1 + + now = time.monotonic() + if now - last_display >= DISPLAY_INTERVAL: + interval_dt = now - last_interval_reset + last_interval_reset = now + interval_num += 1 + last_display = now + elapsed = now - start_time + + # Record per-second rates in history + for addr in GTW_SOURCE_MAP: + rate = src_interval_counts[addr] / max(interval_dt, 0.01) + src_rate_history[addr].append(rate) + if len(src_rate_history[addr]) > 10: + src_rate_history[addr].pop(0) + + p(f"\n{'='*65}") + p(f"[{elapsed:.0f}s] Bus 0: {total_bus0_msgs} src msgs | Bus 1: {total_bus1_msgs} radar msgs") + p(f"{'='*65}") + + # ===== Section 1: Bus 0 Source Message Rates ===== + p("\n--- BUS 0 SOURCE RATES (GTW emulation input) ---") + p(f" {'Source':>6s} → {'Dest':>6s} {'Name':20s} {'Rate':>7s} {'Expect':>7s} {'MaxGap':>8s} {'Gaps':>5s}") + p(f" {'-'*6:>6s} {'-'*6:>6s} {'-'*20:20s} {'-'*7:>7s} {'-'*7:>7s} {'-'*8:>8s} {'-'*5:>5s}") + + any_critical_missing = False + for src_addr in sorted(GTW_SOURCE_MAP.keys()): + dest_addr, name, expected_hz = GTW_SOURCE_MAP[src_addr] + count = src_total_counts[src_addr] + rate = count / max(elapsed, 0.1) + max_gap = src_max_gap_ms[src_addr] + gaps = src_gap_count[src_addr] + + # Status indicator + if count == 0: + status = "!!" + elif expected_hz > 0 and rate < expected_hz * 0.5: + status = "LO" + else: + status = "OK" + + is_critical = src_addr in CRITICAL_SOURCES + marker = " *" if is_critical else " " + + if count > 0: + gap_str = f"{max_gap:6.0f}ms" + gap_warn = f" {gaps:4d}" if gaps > 0 else " 0" + else: + gap_str = " N/A" + gap_warn = " N/A" + if is_critical: + any_critical_missing = True + + p(f" [{status}] 0x{src_addr:03X} → 0x{dest_addr:03X} {name:20s} {rate:5.1f}/s {expected_hz:5d}/s {gap_str} {gap_warn}{marker}") + + p("\n * = critical for radar Doppler (vehicle speed, steering, ESP)") + p(" Gaps = count of intervals > 2.5x expected period") + + if any_critical_missing: + p(" !! CRITICAL SOURCES MISSING — radar CANNOT compute Doppler!") + + # ===== Section 1b: Synthesized messages ===== + p("\n Synthesized messages (derived from sources above):") + ws_rate = src_total_counts.get(0x118, 0) / max(elapsed, 0.1) + esp_rate = src_total_counts.get(0x115, 0) / max(elapsed, 0.1) + p(f" 0x169 ESP_wheelSpeeds: synthesized from 0x118 at {ws_rate:.1f}/s (expect 100/s)") + p(f" 0x1A9 DI_espControl: synthesized from 0x115 at {esp_rate:.1f}/s (expect 50/s)") + + # ===== Section 2: Rate Trend (last 10s) for critical messages ===== + p("\n--- CRITICAL SOURCE RATE TREND (last 10s, per-second) ---") + for src_addr in sorted(CRITICAL_SOURCES): + dest_addr, name, expected_hz = GTW_SOURCE_MAP[src_addr] + history = src_rate_history.get(src_addr, []) + if history: + hist_str = " ".join(f"{r:5.0f}" for r in history[-10:]) + min_r = min(history[-10:]) + max_r = max(history[-10:]) + p(f" 0x{src_addr:03X} ({name[:16]:16s}): [{hist_str}] range=[{min_r:.0f}-{max_r:.0f}] expect={expected_hz}") + else: + p(f" 0x{src_addr:03X} ({name[:16]:16s}): no data yet") + + # ===== Section 3: Vehicle Speed (from bus 0 source) ===== + p("\n--- VEHICLE SPEED (from 0x118 DI_torque2 on bus 0) ---") + if last_vehicle_speed: + vs = last_vehicle_speed + p(f" Speed: {vs['kph']:.1f} KPH / {vs['mph']:.1f} MPH (raw={vs['raw']})") + p(" This is used by firmware to synthesize 0x169 wheel speeds") + else: + p(" No 0x118 data seen on bus 0") + + # ===== Section 4: Car Config Decode ===== + p("\n--- CAR CONFIG (0x2A9) ---") + if last_car_config: + cc = last_car_config + p(f" Autopilot: {cc['autopilot']} RadarPos: {cc['radar_position']} EpasType: {cc['epas_type']}") + p(f" ParkAssist: {cc['park_assist']} FwdRadarHW: {cc['fwd_radar_hw']} DAS_HW: {cc['das_hw']}") + else: + p(" No 0x2A9 data received") + + # ===== Section 5: Radar Status & Transitions ===== + p("\n--- RADAR STATUS ---") + p(f" Current: {radar_status}") + for addr, name in sorted(RADAR_STATUS_MSGS.items()): + count = radar_status_counts[addr] + if count > 0: + rate = count / max(elapsed, 0.1) + p(f" 0x{addr:03X} {name}: {count} msgs ({rate:.1f}/s)") + + if radar_status_transitions: + p(f"\n Status transitions ({len(radar_status_transitions)} total):") + for ts, old, new in radar_status_transitions[-5:]: + p(f" [{ts:.1f}s] {old} → {new}") + if len(radar_status_transitions) > 5: + p(f" ... ({len(radar_status_transitions) - 5} earlier transitions omitted)") + + if alert_data and len(alert_data) >= 2: + p(f" Alert data: {alert_data.hex()}") + + # ===== Section 6: Track Velocity Check ===== + p("\n--- RADAR TRACKING (this interval) ---") + if total_tracked > 0: + p(f" Tracked points: {total_tracked}") + p(f" With non-zero vRel: {tracks_with_velocity}") + if tracks_with_velocity == 0: + p(" WARNING: ALL tracks have vRel=0 (Doppler not working)") + p(" => Radar is in degraded 'raw echo' mode") + else: + pct = 100.0 * tracks_with_velocity / total_tracked + p(f" Doppler: {pct:.0f}% of tracks have velocity") + else: + p(" No tracked radar points") + + # ===== Section 7: Bus 1 GTW check (should be empty) ===== + gtw_on_bus1 = sum(gtw_bus1_counts.values()) + if gtw_on_bus1 > 0: + p("\n--- UNEXPECTED: GTW messages seen on bus 1 RX! ---") + for addr, count in sorted(gtw_bus1_counts.items()): + if count > 0: + p(f" 0x{addr:03X} {GTW_MESSAGES[addr]}: {count}") + p(" (CAN TX normally doesn't loopback — this is unusual)") + + # Reset per-interval counters + total_tracked = 0 + tracks_with_velocity = 0 + src_interval_counts = dict.fromkeys(GTW_SOURCE_MAP, 0) + + except KeyboardInterrupt: + p("\nStopped.") + # Print final summary + elapsed = time.monotonic() - start_time + p(f"\n{'='*65}") + p(f"FINAL SUMMARY ({elapsed:.0f}s)") + p(f"{'='*65}") + p(f" Bus 0 source msgs: {total_bus0_msgs}") + p(f" Bus 1 radar msgs: {total_bus1_msgs}") + p(f" Status transitions: {len(radar_status_transitions)}") + p("\n Source message timing:") + for src_addr in sorted(GTW_SOURCE_MAP.keys()): + dest_addr, name, expected_hz = GTW_SOURCE_MAP[src_addr] + count = src_total_counts[src_addr] + if count > 0: + rate = count / max(elapsed, 0.1) + max_gap = src_max_gap_ms[src_addr] + min_gap = src_min_gap_ms[src_addr] + gaps = src_gap_count[src_addr] + p(f" 0x{src_addr:03X} → 0x{dest_addr:03X}: {rate:.1f}/s avg, gaps={gaps}, " + + f"timing=[{min_gap:.1f}-{max_gap:.1f}ms]") + else: + p(f" 0x{src_addr:03X} → 0x{dest_addr:03X}: NOT SEEN") + + p("\nDiagnostic ended.") + return 0 + + +def main(): + if '--panda' in sys.argv: + return panda_health_check() + else: + return cereal_monitor() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/nap/download_osm_speed_limits.py b/scripts/nap/download_osm_speed_limits.py new file mode 100755 index 00000000000000..36e29b62364620 --- /dev/null +++ b/scripts/nap/download_osm_speed_limits.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Build a small-region OSM speed-limit SQLite DB for NAP mapd (Overpass). + +OpenStreetMap data is ODbL: © OpenStreetMap contributors. +https://www.openstreetmap.org/copyright + +For the full United States after flash, use the GitHub Release download instead: + + python -m scripts.nap.fetch_osm_maps + + # or Settings → NAP → Download US Maps + +On the 3X, Settings → NAP → Map Speed Limit → Refresh maps overlays live OSM +within 100 miles of the vehicle onto that US sqlite (see +python -m scripts.nap.refresh_osm_maps). This script is the PC / bbox builder. + +To *publish* a US Release from a PC (Geofabrik PBF), see scripts/nap/build_osm_speed_limits.py +and docs-nap/map-speed.md. + +Small bbox / Overpass examples (run on a PC): + + # Bounding box (south,west,north,east) + python scripts/nap/download_osm_speed_limits.py --bbox 37.6,-122.5,37.9,-122.2 \\ + --out /tmp/speed_limits.sqlite + + # Center + radius + python scripts/nap/download_osm_speed_limits.py --lat 37.7749 --lon -122.4194 --radius-km 25 + +On the device the file belongs at: + /data/media/0/osm/speed_limits.sqlite + +scp example: + scp speed_limits.sqlite comma@:/data/media/0/osm/speed_limits.sqlite +""" +from __future__ import annotations + +import argparse +import json +import sys + +from openpilot.selfdrive.mapd.db_paths import default_db_path +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB +from openpilot.selfdrive.mapd.overpass import ( + OVERPASS_URL, + bbox_from_center, + fetch_overpass, + ways_from_overpass, +) + + +def write_db(path: str, ways: list[dict], extra_meta: dict | None = None) -> int: + con = OsmSpeedLimitDB.create(path) + n = 0 + for w in ways: + OsmSpeedLimitDB.insert_way( + con, w["way_id"], w["name"], w["highway"], w["maxspeed_ms"], w["coords"], + junction=w.get("junction") or "", + ) + n += 1 + meta = {"way_count": str(n)} + if extra_meta: + meta.update({str(k): str(v) for k, v in extra_meta.items()}) + con.executemany("INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", list(meta.items())) + con.commit() + con.close() + return n + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description="Download OSM maxspeed ways into a NAP mapd sqlite DB") + p.add_argument("--bbox", help="south,west,north,east") + p.add_argument("--lat", type=float) + p.add_argument("--lon", type=float) + p.add_argument("--radius-km", type=float, default=20.0) + p.add_argument("--from-json", help="Use a saved Overpass JSON instead of the network") + p.add_argument("--out", default=default_db_path(), help="Output sqlite path") + p.add_argument("--overpass-url", default=OVERPASS_URL) + args = p.parse_args(argv) + + if args.from_json: + with open(args.from_json, encoding="utf-8") as f: + payload = json.load(f) + bbox_s = "file" + else: + if args.bbox: + parts = [float(x.strip()) for x in args.bbox.split(",")] + if len(parts) != 4: + p.error("--bbox must be south,west,north,east") + bbox = (parts[0], parts[1], parts[2], parts[3]) + elif args.lat is not None and args.lon is not None: + bbox = bbox_from_center(args.lat, args.lon, args.radius_km) + else: + p.error("provide --bbox or --lat/--lon (or --from-json)") + print(f"Overpass bbox={bbox} …", file=sys.stderr) + payload = fetch_overpass(bbox, url=args.overpass_url) + bbox_s = ",".join(str(x) for x in bbox) + + ways = ways_from_overpass(payload) + n = write_db(args.out, ways, extra_meta={"bbox": bbox_s}) + print(f"Wrote {n} ways → {args.out}") + if n == 0: + print("No maxspeed ways found. Try a larger bbox or a denser OSM region.", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/nap/export_speed_sign_onnx.py b/scripts/nap/export_speed_sign_onnx.py new file mode 100644 index 00000000000000..fb4abf90f72f13 --- /dev/null +++ b/scripts/nap/export_speed_sign_onnx.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Export the US MUTCD YOLOv8 ONNX on a PC (not on the 3X). + +Needs: pip install ultralytics onnx + + python -m scripts.nap.export_speed_sign_onnx --out ./speed_sign.onnx + python -m scripts.nap.install_speed_sign_weights ./speed_sign.onnx + +Then either scp the ONNX to the device or attach it to GitHub Release +speed-sign-onnx-v1 as speed_sign.onnx (same pattern as the OSM map pack). +""" +from __future__ import annotations + +import argparse +import os + +from openpilot.selfdrive.speedsignd.export import export_and_report +from openpilot.selfdrive.speedsignd.weights_manifest import ASSET_SHA256, YOLO_IMGSZ + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--out", default="speed_sign.onnx", help="output ONNX path") + args = p.parse_args(argv) + path, digest, matches = export_and_report(args.out) + print(f"exported {os.path.getsize(path)} bytes -> {path}") + print(f"sha256 {digest}") + if matches: + print(f"matches bundled ASSET_SHA256 ({ASSET_SHA256[:12]}…)") + else: + print(f"note: digest differs from bundled ASSET_SHA256 ({ASSET_SHA256})") + print("update weights_manifest.ASSET_SHA256 if you intend to republish") + print(f"imgsz {YOLO_IMGSZ}. next: python -m scripts.nap.install_speed_sign_weights {path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/nap/extract_epas.py b/scripts/nap/extract_epas.py new file mode 100755 index 00000000000000..5e55f5dccf12b8 --- /dev/null +++ b/scripts/nap/extract_epas.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +""" +Extract stock Tesla Pre-AP EPAS firmware image only. + +Thin wrapper around flash_epas.py so ScriptRunner can launch extraction mode +without passing command-line flags. +""" + +from scripts.nap.flash_epas import main + + +if __name__ == "__main__": + raise SystemExit(main(["--extract-only"])) diff --git a/scripts/nap/fetch_osm_maps.py b/scripts/nap/fetch_osm_maps.py new file mode 100755 index 00000000000000..c635ee9acd1236 --- /dev/null +++ b/scripts/nap/fetch_osm_maps.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Download the prebuilt US OSM speed-limit DB onto comma 3X. + +OpenStreetMap data is ODbL: © OpenStreetMap contributors. +https://www.openstreetmap.org/copyright + +Run on the device (Wi-Fi): + + python -m scripts.nap.fetch_osm_maps + +To overlay live OSM around the vehicle onto that sqlite (100 miles): + + python -m scripts.nap.refresh_osm_maps + +Or from a PC, then scp the sqlite (see --out). +""" +from openpilot.selfdrive.mapd.fetch_maps import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/nap/firmware/epas-bootloader-0x3ff7000-0x3ffacbd.bin b/scripts/nap/firmware/epas-bootloader-0x3ff7000-0x3ffacbd.bin new file mode 100644 index 00000000000000..14d7f005ef228c Binary files /dev/null and b/scripts/nap/firmware/epas-bootloader-0x3ff7000-0x3ffacbd.bin differ diff --git a/scripts/nap/firmware/epas-firmware-0x7000-0x45fff.bin b/scripts/nap/firmware/epas-firmware-0x7000-0x45fff.bin new file mode 100644 index 00000000000000..54835dc7ebe98f Binary files /dev/null and b/scripts/nap/firmware/epas-firmware-0x7000-0x45fff.bin differ diff --git a/scripts/nap/flash_epas.py b/scripts/nap/flash_epas.py new file mode 100755 index 00000000000000..ec87e0320d346b --- /dev/null +++ b/scripts/nap/flash_epas.py @@ -0,0 +1,618 @@ +#!/usr/bin/env python3 +""" +Tesla Pre-AP EPAS Firmware Flasher (GUI version) +Extracts, patches, and flashes the EPAS (Electric Power Assisted Steering) +firmware to enable openpilot steering control on pre-AP Tesla vehicles. + +Firmware modifications: + - Patches EPB_epasEACAllow to always return 1 + - Patches GTW_epasControlType to always return 1 + - Patches GTW_epasLDWEnable to always return 1 + (The actual CAN messages must still be present on the bus) + +Based on the Tinkla EPAS flasher by the openpilot Tesla community. + +CRITICAL: This permanently modifies EPAS firmware. Ensure you have a backup. +Uses direct Panda access with UDS protocol (stops pandad via ScriptRunner). +""" + +import argparse +import os +import sys +import time +import struct +import hashlib +import binascii + +# ============================================ +# Firmware Constants +# ============================================ +FW_MD5SUM = "9e51ddd80606fbdaaf604c73c8dde0d1" +FW_START_ADDR = 0x7000 +FW_END_ADDR = 0x45FFF +FW_SIZE = FW_END_ADDR - FW_START_ADDR + 1 +BOOTLOADER_ADDR = 0x3ff7000 + +# UDS defaults +DEFAULT_CAN_ADDR = 0x730 +DEFAULT_CAN_BUS = 0 +DEFAULT_BOOTLOADER_FILE = "epas-bootloader-0x3ff7000-0x3ffacbd.bin" +BOOTLOADER_MD5SUM = "09cdd03705692725290942f4065c2706" +BOOTLOADER_SIZE = 15550 +RISK_ACK_PARAM_KEY = "NAPEpasRiskAccepted" + +# Panda connection +PANDA_CONNECT_RETRIES = 5 +PANDA_CONNECT_DELAY = 2.0 + + +def p(msg="", end="\n"): + """Print with flush for real-time ScriptRunner display.""" + print(msg, end=end, flush=True) + + +def progress_bar(current, total, prefix="", width=40): + """Simple text progress bar.""" + pct = current / total if total > 0 else 0 + filled = int(width * pct) + bar = "#" * filled + "-" * (width - filled) + p(f" {prefix}[{bar}] {pct*100:.1f}%") + + +def _consume_ui_risk_ack() -> bool: + """ + Consume one-time EPAS risk acknowledgment set by UI. + + Returns True when a valid acknowledgment token was present. + """ + try: + from openpilot.common.params import Params + params = Params() + accepted = params.get_bool(RISK_ACK_PARAM_KEY) + if accepted: + params.put_bool(RISK_ACK_PARAM_KEY, False) + return accepted + except Exception: + return False + + +def _ensure_risk_ack(args) -> bool: + """ + Require explicit risk acknowledgment for operations that write EPAS firmware. + + When launched from the ScriptRunner UI, risk is acknowledged by the user + pressing Start after reading the on-screen warnings. CLI users must pass + --accept-risk. + """ + if args.extract_only: + return True + + if args.accept_risk: + return True + + if _consume_ui_risk_ack(): + return True + + # When launched from ScriptRunner the NAPScriptRunning param is set, + # meaning the user already navigated through the UI warnings. + try: + from openpilot.common.params import Params + if Params().get_bool("NAPScriptRunning"): + return True + except Exception: + pass + + p("") + p("RISK ACKNOWLEDGMENT REQUIRED") + p("- Flashing/restoring EPAS firmware modifies a safety-critical steering ECU.") + p("- While unlikely, interruption/power loss or wrong image can brick EPAS.") + p("- By proceeding, you assume this risk.") + p("") + p("Re-run with --accept-risk to continue from CLI,") + p("or start from UI and press the explicit risk agreement prompt.") + return False + + +# ============================================ +# Security Access Algorithm (Tesla-specific) +# ============================================ +def get_security_access_key(seed): + key = 0xc541a9 + + mask = struct.unpack('> 1 + key = key >> 1 + if msb != 0: + key = (key | msb << 0x17) ^ 0x109028 + + mask = 0x55f222f9 + for _i in range(32): + msb = key & 1 ^ mask & 1 + mask = mask >> 1 + key = key >> 1 + if msb != 0: + key = (key | msb << 0x17) ^ 0x109028 + + key = bytes([ + (key & 0xff0) >> 4, + (key & 0xf000) >> 8 | (key & 0xf00000) >> 20, + (key & 0xf0000) >> 16 | (key & 0xf) << 4, + ]) + + return key + + +# ============================================ +# UDS Helper Functions +# ============================================ +def wait_for_ecu(uds_client): + """Wait for ECU to respond after reboot.""" + from opendbc.car.uds import MessageTimeoutError + + p(" Waiting for ECU .", end="") + prev_timeout = uds_client.timeout + uds_client.timeout = 0.1 + for _ in range(10): + try: + uds_client.tester_present() + uds_client.timeout = prev_timeout + p("") + return + except MessageTimeoutError: + p(".", end="") + uds_client.timeout = prev_timeout + raise Exception("ECU did not respond after reboot!") + + +def extract_firmware(uds_client, start_addr, end_addr): + """Extract firmware from EPAS ECU via UDS.""" + from opendbc.car.uds import SESSION_TYPE, ACCESS_TYPE + + p("Starting extended diagnostic session...") + uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) + + p("Requesting security access seed...") + seed = uds_client.security_access(ACCESS_TYPE.REQUEST_SEED) + p(f" Seed: 0x{seed.hex()}") + + p("Sending security access key...") + key = get_security_access_key(seed) + p(f" Key: 0x{key.hex()}") + uds_client.security_access(ACCESS_TYPE.SEND_KEY, key) + + p("Extracting firmware...") + p(f" Start addr: {hex(start_addr)}") + p(f" End addr: {hex(end_addr)}") + total = end_addr - start_addr + 1 + fw = b"" + chunk_size = 128 + chunks_done = 0 + total_chunks = (total + chunk_size - 1) // chunk_size + report_every = max(1, total_chunks // 20) # report ~20 times + + for addr in range(start_addr, end_addr + 1, chunk_size): + dat = uds_client.read_memory_by_address(addr, chunk_size) + if len(dat) != chunk_size: + raise Exception(f"Expected {chunk_size} bytes but got {len(dat)} at addr {hex(addr)}") + fw += dat + chunks_done += 1 + if chunks_done % report_every == 0 or chunks_done == total_chunks: + progress_bar(chunks_done, total_chunks, "Extract: ") + + p(f" Extracted {len(fw)} bytes") + return fw + + +def update_checksums(fw, offset, restore=False): + """Recalculate firmware checksums after patching.""" + for addr in [0x79c0, 0x79d0]: + idx = addr - offset + if idx < 0: + raise Exception(f"Checksum address {hex(addr)} is before firmware start") + + start = struct.unpack('= len(fw): + raise Exception(f"Checksum end addr {hex(end)} is outside firmware range") + + crc32 = binascii.crc32(fw[start - offset:end - offset + 1]) + cksum = struct.pack(" 0x{new_val.hex()}") + if len(old_val) != len(new_val): + raise Exception(f"Patch size mismatch at {hex(addr)}") + if fw[idx:idx + len(old_val)] != old_val: + raise Exception(f"Unexpected firmware content at {hex(addr)}: " + + f"0x{fw[idx:idx + len(old_val)].hex()} != 0x{old_val.hex()}") + + fw = fw[:idx] + new_val + fw[idx + len(new_val):] + + return fw + + +def flash_bootloader(uds_client, bootloader_path, start_addr): + """Flash bootloader to EPAS ECU.""" + from opendbc.car.uds import SESSION_TYPE, ACCESS_TYPE, ROUTINE_CONTROL_TYPE + + p("Reading bootloader...") + with open(bootloader_path, "rb") as f: + fw = f.read() + fw_len = len(fw) + end_addr = start_addr + fw_len - 1 + p(f" Size: {fw_len} bytes") + + bl_md5 = hashlib.md5(fw).hexdigest() + p(f" MD5: {bl_md5}") + if fw_len != BOOTLOADER_SIZE or bl_md5 != BOOTLOADER_MD5SUM: + raise Exception("Bootloader integrity check failed! " + + f"Expected md5={BOOTLOADER_MD5SUM} size={BOOTLOADER_SIZE}, " + + f"got md5={bl_md5} size={fw_len}") + + p("Starting programming session...") + uds_client.diagnostic_session_control(SESSION_TYPE.PROGRAMMING) + wait_for_ecu(uds_client) + + p("Requesting security access seed...") + seed = uds_client.security_access(ACCESS_TYPE.REQUEST_SEED) + p(f" Seed: 0x{seed.hex()}") + + p("Sending security access key...") + key = get_security_access_key(seed) + p(f" Key: 0x{key.hex()}") + uds_client.security_access(ACCESS_TYPE.SEND_KEY, key) + + p("Requesting download...") + p(f" Start addr: {hex(start_addr)}") + p(f" End addr: {hex(end_addr)}") + p(f" Size: {hex(fw_len)}") + block_size = uds_client.request_download(start_addr, fw_len) + + p("Transferring bootloader...") + p(f" Block size: {block_size}") + chunk_size = block_size - 2 + if chunk_size <= 0: + raise Exception(f"Invalid block size {block_size} returned by ECU") + cnt = 0 + total_chunks = (fw_len + chunk_size - 1) // chunk_size + report_every = max(1, total_chunks // 10) + + for i in range(0, fw_len, chunk_size): + cnt += 1 + uds_client.transfer_data(cnt & 0xFF, fw[i:i + chunk_size]) + if cnt % report_every == 0 or i + chunk_size >= fw_len: + progress_bar(cnt, total_chunks, "Bootloader: ") + + p("Requesting transfer exit...") + uds_client.request_transfer_exit() + + p("Entering bootloader...") + uds_client.routine_control(ROUTINE_CONTROL_TYPE.START, 0x0301, + struct.pack(">I", start_addr)) + p(" Bootloader flashed successfully") + + +def flash_firmware(uds_client, fw_slice, start_addr, end_addr): + """Flash modified firmware to EPAS ECU.""" + from opendbc.car.uds import (SESSION_TYPE, ACCESS_TYPE, ROUTINE_CONTROL_TYPE, + ROUTINE_IDENTIFIER_TYPE, RESET_TYPE, MessageTimeoutError) + + slice_len = end_addr - start_addr + 1 + if slice_len != len(fw_slice): + raise Exception(f"Firmware size mismatch: expected {slice_len}, got {len(fw_slice)}") + + start_and_length = struct.pack('>II', start_addr, slice_len) + + p("Erasing memory...") + p(f" Start addr: {hex(start_addr)}") + p(f" End addr: {hex(end_addr)}") + p(f" Size: {hex(slice_len)}") + uds_client.routine_control(ROUTINE_CONTROL_TYPE.START, + ROUTINE_IDENTIFIER_TYPE.ERASE_MEMORY, + start_and_length) + + p("Requesting download...") + block_size = uds_client.request_download(start_addr, slice_len) + + p("Transferring firmware...") + p(f" Block size: {block_size}") + chunk_size = block_size - 2 + if chunk_size <= 0: + raise Exception(f"Invalid block size {block_size} returned by ECU") + cnt = 0 + total_chunks = (slice_len + chunk_size - 1) // chunk_size + report_every = max(1, total_chunks // 20) + + for i in range(0, slice_len, chunk_size): + cnt += 1 + uds_client.transfer_data(cnt & 0xFF, fw_slice[i:i + chunk_size]) + if cnt % report_every == 0 or i + chunk_size >= slice_len: + progress_bar(cnt, total_chunks, "Firmware: ") + + p("Requesting transfer exit...") + uds_client.request_transfer_exit() + + p("Resetting ECU...") + wait_for_ecu(uds_client) + try: + uds_client.ecu_reset(RESET_TYPE.HARD | 0x80) + except MessageTimeoutError: + # suppress-response bit set, timeout expected (waits for reboot) + pass + wait_for_ecu(uds_client) + + p("Starting extended diagnostic session...") + uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) + + p("Requesting security access seed...") + seed = uds_client.security_access(ACCESS_TYPE.REQUEST_SEED) + p(f" Seed: 0x{seed.hex()}") + + p("Sending security access key...") + key = get_security_access_key(seed) + p(f" Key: 0x{key.hex()}") + uds_client.security_access(ACCESS_TYPE.SEND_KEY, key) + + p("Checking dependencies...") + uds_client.routine_control(ROUTINE_CONTROL_TYPE.START, 0xDC03) + + p(" Firmware flashed successfully!") + + +def connect_panda(): + """Connect to Panda with retries.""" + from panda import Panda + + for attempt in range(PANDA_CONNECT_RETRIES): + try: + panda = Panda() + return panda + except Exception as e: + if attempt < PANDA_CONNECT_RETRIES - 1: + p(f" Panda not ready ({e}), retrying in {PANDA_CONNECT_DELAY}s...") + time.sleep(PANDA_CONNECT_DELAY) + else: + raise + + +def parse_args(cli_args=None): + parser = argparse.ArgumentParser( + description="Patch/restore Tesla Pre-AP EPAS firmware via Panda UDS", + ) + parser.add_argument("--extract-only", action="store_true", + help="Extract firmware only; do not flash") + parser.add_argument("--restore", action="store_true", + help="Flash stock firmware image (no patch modifications)") + parser.add_argument("--debug", action="store_true", + help="Enable UDS debug logging") + parser.add_argument("--accept-risk", action="store_true", + help="Acknowledge EPAS flashing risk and allow write operations") + parser.add_argument("--bootloader", type=str, default=DEFAULT_BOOTLOADER_FILE, + help="Bootloader filename/path (relative paths are resolved under scripts/nap/firmware)") + parser.add_argument("--can-addr", type=lambda x: int(x, 0), default=DEFAULT_CAN_ADDR, + help="UDS transmit CAN address (default: 0x730)") + parser.add_argument("--can-bus", type=int, default=DEFAULT_CAN_BUS, + help="CAN bus number (default: 0)") + return parser.parse_args(cli_args) + + +def main(cli_args=None): + from cereal import car + from opendbc.car.uds import UdsClient + SafetyModel = car.CarParams.SafetyModel + args = parse_args(cli_args) + + p("=" * 60) + p("EPAS FIRMWARE FLASHER") + p("=" * 60) + p("") + p("This tool will:") + p(" 1. Extract the current EPAS firmware") + p(" 2. Verify the firmware checksum") + if args.extract_only: + p(" 3. Save backup image and exit") + elif args.restore: + p(" 3. Flash stock firmware image") + else: + p(" 3. Apply steering control patches") + p(" 4. Flash the patched firmware") + p("") + p("WARNING: This permanently modifies the EPAS firmware.") + p("A backup of the original firmware will be saved.") + p("=" * 60) + + if not _ensure_risk_ack(args): + return 1 + + # Resolve paths relative to script location + script_dir = os.path.dirname(os.path.realpath(__file__)) + firmware_dir = os.path.join(script_dir, "firmware") + bootloader_path = args.bootloader + if not os.path.isabs(bootloader_path): + bootloader_path = os.path.join(firmware_dir, bootloader_path) + fw_fn = os.path.join(firmware_dir, f"epas-firmware-{hex(FW_START_ADDR)}-{hex(FW_END_ADDR)}.bin") + + if not args.extract_only and not os.path.exists(bootloader_path): + p(f"\nERROR: Bootloader not found at: {bootloader_path}") + return 1 + + panda = None + try: + # Allow time for manager to see NAPScriptRunning and stop pandad + p("\nWaiting for pandad to release Panda USB...") + time.sleep(2) + + p("Connecting to Panda...") + panda = connect_panda() + p(" Connected") + + panda.set_safety_mode(SafetyModel.elm327) + p(" Safety mode: ELM327 (UDS)") + + # Flush stale CAN messages left by pandad / other processes + p(" Flushing CAN buffers...") + panda.can_clear(0xFFFF) + time.sleep(0.1) + panda.can_recv() + + uds_client = UdsClient(panda, args.can_addr, bus=args.can_bus, timeout=1) + p(f" UDS client: addr=0x{args.can_addr:03X}, bus={args.can_bus}") + + # Step 1: Extract firmware + p("\n" + "=" * 40) + p("STEP 1: Extract Firmware") + p("=" * 40) + + fw_slice = None + if args.extract_only or not os.path.exists(fw_fn): + fw_slice = extract_firmware(uds_client, FW_START_ADDR, FW_END_ADDR) + # Undo any previous patches to get clean firmware + fw_slice = patch_firmware(fw_slice, FW_START_ADDR, restore=True) + fw_slice = update_checksums(fw_slice, FW_START_ADDR, restore=True) + p(f" Saving backup: {fw_fn}") + os.makedirs(os.path.dirname(fw_fn), exist_ok=True) + with open(fw_fn, "wb") as f: + f.write(fw_slice) + else: + p(f" Loading cached firmware: {fw_fn}") + with open(fw_fn, "rb") as f: + fw_slice = f.read() + md5 = hashlib.md5(fw_slice).hexdigest() + if md5 != FW_MD5SUM or len(fw_slice) != FW_SIZE: + p(f" Cached firmware invalid (md5={md5}), re-extracting...") + fw_slice = extract_firmware(uds_client, FW_START_ADDR, FW_END_ADDR) + # Undo any previous patches to get clean firmware + fw_slice = patch_firmware(fw_slice, FW_START_ADDR, restore=True) + fw_slice = update_checksums(fw_slice, FW_START_ADDR, restore=True) + p(f" Saving backup: {fw_fn}") + os.makedirs(os.path.dirname(fw_fn), exist_ok=True) + with open(fw_fn, "wb") as f: + f.write(fw_slice) + + # Step 2: Verify firmware + p("\n" + "=" * 40) + p("STEP 2: Verify Firmware") + p("=" * 40) + + md5 = hashlib.md5(fw_slice).hexdigest() + p(f" Size: {len(fw_slice)} bytes (expected {FW_SIZE})") + p(f" MD5: {md5}") + + if len(fw_slice) != FW_SIZE: + p("\nERROR: Firmware size mismatch!") + return 1 + + if md5 != FW_MD5SUM: + p("\nERROR: Firmware checksum mismatch!") + p(f" Expected: {FW_MD5SUM}") + p(f" Got: {md5}") + return 1 + + p(" Firmware verified OK") + + if args.extract_only: + p("\n" + "=" * 60) + p("EXTRACT COMPLETE") + p("=" * 60) + p(f"Backup saved to: {fw_fn}") + return 0 + + # Step 3: Patch or Restore firmware payload + p("\n" + "=" * 40) + p("STEP 3: Prepare Firmware Payload") + p("=" * 40) + + if args.restore: + p("Restore mode enabled: flashing stock firmware image.") + else: + p("Applying patches...") + fw_slice = patch_firmware(fw_slice, FW_START_ADDR) + p("Updating checksums...") + fw_slice = update_checksums(fw_slice, FW_START_ADDR) + mod_fn = os.path.join(firmware_dir, f"{FW_MD5SUM}.modified.bin") + p(f" Saving modified firmware: {mod_fn}") + with open(mod_fn, "wb") as f: + f.write(fw_slice) + + # Step 4: Flash + p("\n" + "=" * 40) + p("STEP 4: Flash Bootloader") + p("=" * 40) + + flash_bootloader(uds_client, bootloader_path, BOOTLOADER_ADDR) + + p("\n" + "=" * 40) + p("STEP 5: Flash Firmware") + p("=" * 40) + + flash_firmware(uds_client, fw_slice, FW_START_ADDR, FW_END_ADDR) + + p("\n" + "=" * 60) + p("EPAS FLASH COMPLETE!") + p("=" * 60) + p("") + if args.restore: + p("The stock EPAS firmware image has been restored.") + else: + p("The EPAS firmware has been patched for openpilot steering control.") + p("Please restart the vehicle to apply changes.") + + return 0 + + except KeyboardInterrupt: + p("\nFlashing interrupted!") + p("WARNING: If interrupted during flash, the EPAS may need recovery.") + return 1 + except Exception as e: + p(f"\nERROR: {e}") + import traceback + traceback.print_exc() + return 1 + finally: + if panda is not None: + try: + panda.set_safety_mode(SafetyModel.silent) + panda.close() + p("\nPanda connection closed.") + except Exception: + pass + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/nap/install_speed_sign_weights.py b/scripts/nap/install_speed_sign_weights.py new file mode 100644 index 00000000000000..3785300f0e7c83 --- /dev/null +++ b/scripts/nap/install_speed_sign_weights.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Install the compact US MUTCD speed-sign ONNX and the CPU runtime onto /data. + +Does not download maps, does not talk to osm.org, and does not write sqlite. +Does not pip-install and does not modify the system venv. + +On the comma 3X (Wi-Fi), fetch the published weights (~12 MB) and the pinned +aarch64 CPU onnxruntime wheel (~21 MB). Both are SHA-256 checked. The wheel +is unzipped into /data/media/0/nap/pylib and loaded via sys.path. Settings +shows "runtime missing" until that import works. + + python -m scripts.nap.install_speed_sign_weights + +Or copy a local export (from scripts.nap.export_speed_sign_onnx): + + python -m scripts.nap.install_speed_sign_weights /path/to/speed_sign.onnx + +Destination (override with --out or NAP_SPEED_SIGN_ONNX): + + /data/media/0/nap/speed_sign.onnx + /data/media/0/nap/pylib/onnxruntime + +Do not commit the ONNX or the wheel to git. Enable the logger separately +(Settings → NAP → Speed Sign Logger; still default Off). +""" +from __future__ import annotations + +import argparse +import os +import sys + +from openpilot.selfdrive.speedsignd.install import ( + fetch_and_install, + fetch_and_install_proposer, + fetch_and_install_runtime, + install_weights, + runtime_status_summary, + sha256_file, +) +from openpilot.selfdrive.speedsignd.paths import nap_data_dir +from openpilot.selfdrive.speedsignd.weights_manifest import ASSET_SHA256, ORT_SHA256 + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument( + "onnx", + nargs="?", + default=None, + help="local speed_sign.onnx (omit to download the published asset)", + ) + p.add_argument("--out", default=None, help="destination (default /data/media/0/nap/speed_sign.onnx)") + p.add_argument("--url", default=None, help="override download URL") + p.add_argument( + "--sha256", + default=ASSET_SHA256, + help="expected SHA-256 of the ONNX (empty string skips)", + ) + p.add_argument( + "--skip-runtime", + action="store_true", + help="install the ONNX only (tests). The settings button does not pass this.", + ) + args = p.parse_args(argv) + sha = (args.sha256 or "").strip() or None + if args.onnx: + dest = install_weights(args.onnx, args.out, sha256=None) + else: + dest = fetch_and_install(dest=args.out, url=args.url, sha256=sha) + digest = sha256_file(dest) + print(f"installed {os.path.getsize(dest)} bytes -> {dest}") + print(f"sha256 {digest}") + print(f"nap data dir: {nap_data_dir()}") + if not args.onnx: + # Two-stage strip proposer. Not fatal: speedsignd falls back to fixed tiles. + try: + prop = fetch_and_install_proposer() + print(f"proposer -> {prop}") + except Exception as e: + print("proposer install failed (fixed tiles stay in use): " + str(e), file=sys.stderr) + if not args.skip_runtime: + try: + pylib = fetch_and_install_runtime(sha256=ORT_SHA256) + except Exception as e: + print("runtime install failed: " + str(e), file=sys.stderr) + print("status: runtime missing", file=sys.stderr) + return 1 + print(f"runtime -> {pylib}") + print(runtime_status_summary()) + print("enable: Settings → NAP → Speed Sign Logger, or Params put NAPSpeedSignLog 1") + print("leave Logger On while disengaged until the first session is cached, then engage") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/nap/lead_source_analysis.py b/scripts/nap/lead_source_analysis.py new file mode 100755 index 00000000000000..44cc82ef2a380c --- /dev/null +++ b/scripts/nap/lead_source_analysis.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +""" +Lead Source Analysis — check if leadOne.radar flips between True/False, +and correlate with longitudinal plan accel changes. + +Usage: python scripts/nap/lead_source_analysis.py [log_dir] +""" + +import sys +import struct +from pathlib import Path +from collections import defaultdict + + +def read_events(path): + import zstandard as zstd + print(f" Reading {Path(path).name}...", end="", flush=True) + dctx = zstd.ZstdDecompressor() + with open(path, 'rb') as f: + raw = dctx.decompress(f.read(), max_output_size=500 * 1024 * 1024) + try: + from cereal import log as cereal_log + events = list(cereal_log.Event.read_multiple_bytes(raw)) + print(f" {len(events)} events", flush=True) + return events + except ImportError: + pass + # capnp fallback + import capnp + schema_paths = list(Path('/Users/jackbrandt/projects/openpilot-dev').rglob('log.capnp')) + capnp.remove_import_hook() + log_capnp = capnp.load(str(schema_paths[0]), + imports=[str(schema_paths[0].parent.parent / 'cereal'), + str(schema_paths[0].parent)]) + msg_list = [] + pos = 0 + while pos < len(raw): + try: + if pos + 4 > len(raw): + break + n_segs = struct.unpack_from(' 10: + pos += 1 + continue + raw_header_size = 4 + 4 * n_segs + if raw_header_size % 8 != 0: + raw_header_size += 4 + if pos + raw_header_size > len(raw): + break + total_data = 0 + for s in range(n_segs): + total_data += struct.unpack_from(' len(raw): + break + msg_list.append(raw[pos:msg_end]) + pos = msg_end + except Exception: + pos += 1 + events = [] + for msg_bytes in msg_list: + try: + with log_capnp.Event.from_bytes(msg_bytes, traversal_limit_in_words=2**63 - 1) as event: + events.append(event) + except Exception: + continue + print(f" {len(events)} events", flush=True) + return events + + +def analyze(log_paths): + paths = sorted(log_paths)[:5] + + rs_data = [] # (time, leadOne.status, leadOne.radar, leadOne.dRel, leadOne.radarTrackId, valid) + lp_data = [] # (time, hasLead, source, aDesired) + lt_data = [] # (time, n_points) + + for path in paths: + events = read_events(path) + for evt in events: + which = evt.which() + mono = evt.logMonoTime + + if which == 'radarState': + rs = evt.radarState + l1 = rs.leadOne + rs_data.append((mono, l1.status, l1.radar, l1.dRel, l1.radarTrackId, evt.valid)) + + elif which == 'longitudinalPlan': + lp = evt.longitudinalPlan + lp_data.append((mono, lp.hasLead, str(lp.longitudinalPlanSource), + lp.accels[0] if len(lp.accels) > 0 else 0.0, evt.valid)) + + elif which == 'liveTracks': + lt = evt.liveTracks + lt_data.append((mono, len(lt.points))) + + print(f"\n{'='*70}") + print("LEAD SOURCE ANALYSIS") + print(f"{'='*70}") + + # radarState analysis + if rs_data: + n_status = sum(1 for d in rs_data if d[1]) + n_radar = sum(1 for d in rs_data if d[1] and d[2]) + n_vision = sum(1 for d in rs_data if d[1] and not d[2]) + n_valid = sum(1 for d in rs_data if d[5]) + n_invalid = sum(1 for d in rs_data if not d[5]) + + print(f"\n radarState frames: {len(rs_data)}") + print(f" valid: {n_valid} ({100*n_valid/len(rs_data):.1f}%)") + print(f" invalid: {n_invalid} ({100*n_invalid/len(rs_data):.1f}%)") + print(f" leadOne.status=True: {n_status} ({100*n_status/len(rs_data):.1f}%)") + print(f" leadOne.radar=True: {n_radar} ({100*n_status/len(rs_data) if n_status else 0:.1f}% of total)") + print(f" leadOne.radar=False: {n_vision} (vision-only)") + + if n_status > 0: + print(f" Of active leads: {100*n_radar/n_status:.1f}% radar, {100*n_vision/n_status:.1f}% vision-only") + + # Count radar↔vision transitions + transitions = 0 + prev_radar = None + for d in rs_data: + if d[1]: # status=True + if prev_radar is not None and d[2] != prev_radar: + transitions += 1 + prev_radar = d[2] + duration = (rs_data[-1][0] - rs_data[0][0]) * 1e-9 + print(f"\n Radar↔Vision transitions: {transitions} in {duration:.1f}s = {transitions/max(duration,0.1):.2f}/s") + + # Track ID changes + prev_tid = None + tid_changes = 0 + for d in rs_data: + if d[1]: # status=True + if prev_tid is not None and d[4] != prev_tid: + tid_changes += 1 + prev_tid = d[4] + print(f" Track ID changes: {tid_changes} in {duration:.1f}s = {tid_changes/max(duration,0.1):.2f}/s") + + # valid↔invalid transitions + valid_transitions = 0 + prev_valid = None + for d in rs_data: + if prev_valid is not None and d[5] != prev_valid: + valid_transitions += 1 + prev_valid = d[5] + print(f" Valid↔Invalid transitions: {valid_transitions}") + + # liveTracks analysis + if lt_data: + duration = (lt_data[-1][0] - lt_data[0][0]) * 1e-9 + rate = len(lt_data) / max(duration, 0.1) + n_zero = sum(1 for d in lt_data if d[1] == 0) + n_nonzero = sum(1 for d in lt_data if d[1] > 0) + print("\n liveTracks:") + print(f" Count: {len(lt_data)}, Rate: {rate:.1f} Hz") + print(f" Zero points: {n_zero} ({100*n_zero/len(lt_data):.1f}%)") + print(f" Non-zero: {n_nonzero} ({100*n_nonzero/len(lt_data):.1f}%)") + + # longitudinalPlan analysis + if lp_data: + n_has_lead = sum(1 for d in lp_data if d[1]) + n_valid = sum(1 for d in lp_data if d[4]) + sources = defaultdict(int) + for d in lp_data: + sources[d[2]] += 1 + + print("\n longitudinalPlan:") + print(f" Count: {len(lp_data)}") + print(f" valid: {n_valid} ({100*n_valid/len(lp_data):.1f}%)") + print(f" hasLead=True: {n_has_lead} ({100*n_has_lead/len(lp_data):.1f}%)") + print(f" Sources: {dict(sources)}") + + # Check accel oscillation + accels = [d[3] for d in lp_data] + sign_changes = 0 + for i in range(1, len(accels)): + if accels[i] * accels[i-1] < 0: + sign_changes += 1 + duration = (lp_data[-1][0] - lp_data[0][0]) * 1e-9 + print(f" Accel sign changes: {sign_changes} in {duration:.1f}s = {sign_changes/max(duration,0.1):.2f}/s") + + +def main(): + if len(sys.argv) > 1: + p = Path(sys.argv[1]) + if p.is_dir(): + log_paths = sorted(p.glob('*.zst')) + else: + log_paths = [p] + else: + log_dir = Path('/Users/jackbrandt/projects/openpilot-dev/logs/crappy-radar/route-7') + log_paths = sorted(log_dir.glob('*.zst')) + + if not log_paths: + print("No .zst log files found.") + sys.exit(1) + + analyze(log_paths) + + +if __name__ == '__main__': + main() diff --git a/scripts/nap/livetracks_availability.py b/scripts/nap/livetracks_availability.py new file mode 100755 index 00000000000000..c3eedeaa71bd53 --- /dev/null +++ b/scripts/nap/livetracks_availability.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +""" +LiveTracks Availability Analysis + +Investigate why liveTracks has zero points 90% of the time. +Checks: + 1. liveTracks update rate vs radarState rate + 2. When liveTracks has points vs when it doesn't + 3. Number of points per liveTracks message + 4. Timing gaps in liveTracks + +Usage: + python scripts/nap/livetracks_availability.py [log_dir] +""" + +import sys +import struct +from pathlib import Path +from collections import defaultdict +import statistics + +def read_events_all(path): + """Read ALL events (not just filtered) to check timing.""" + import zstandard as zstd + print(f" Reading {Path(path).name}...", end="", flush=True) + + dctx = zstd.ZstdDecompressor() + with open(path, 'rb') as f: + raw = dctx.decompress(f.read(), max_output_size=500 * 1024 * 1024) + + try: + from cereal import log as cereal_log + events = list(cereal_log.Event.read_multiple_bytes(raw)) + print(f" {len(events)} events", flush=True) + return events + except ImportError: + pass + + import capnp + schema_paths = list(Path('/Users/jackbrandt/projects/openpilot-dev').rglob('log.capnp')) + if not schema_paths: + print(" ERROR", flush=True) + sys.exit(1) + capnp.remove_import_hook() + log_capnp = capnp.load(str(schema_paths[0]), + imports=[str(schema_paths[0].parent.parent / 'cereal'), + str(schema_paths[0].parent)]) + + msg_list = [] + pos = 0 + while pos < len(raw): + try: + if pos + 4 > len(raw): + break + n_segs = struct.unpack_from(' 10: + pos += 1 + continue + raw_header_size = 4 + 4 * n_segs + if raw_header_size % 8 != 0: + raw_header_size += 4 + if pos + raw_header_size > len(raw): + break + total_data = 0 + for s in range(n_segs): + seg_size = struct.unpack_from(' len(raw): + break + msg_list.append(raw[pos:msg_end]) + pos = msg_end + except Exception: + pos += 1 + + events = [] + for msg_bytes in msg_list: + try: + with log_capnp.Event.from_bytes(msg_bytes, traversal_limit_in_words=2**63 - 1) as event: + events.append({ + 'which': event.which(), + 'logMonoTime': event.logMonoTime, + '_raw': event, + }) + except Exception: + continue + print(f" {len(events)} events", flush=True) + return events + + +def analyze(log_paths): + # Process first 2 files for detailed timing analysis + paths_to_analyze = sorted(log_paths)[:3] + + lt_times = [] # liveTracks timestamps + lt_n_points = [] # number of points per liveTracks message + rs_times = [] # radarState timestamps + mv_times = [] # modelV2 timestamps + all_event_types = defaultdict(int) + + for path in paths_to_analyze: + events = read_events_all(path) + for evt in events: + if isinstance(evt, dict): + which = evt['which'] + mono = evt['logMonoTime'] + else: + which = evt.which() + mono = evt.logMonoTime + + all_event_types[which] += 1 + + if which == 'liveTracks': + lt_times.append(mono) + try: + if isinstance(evt, dict) and '_raw' in evt: + lt = evt['_raw'].liveTracks + else: + lt = evt.liveTracks + pts = list(lt.points) + lt_n_points.append(len(pts)) + except Exception: + lt_n_points.append(-1) + + elif which == 'radarState': + rs_times.append(mono) + + elif which == 'modelV2': + mv_times.append(mono) + + print(f"\n{'='*70}") + print("LIVETRACKS AVAILABILITY ANALYSIS") + print(f"{'='*70}") + + print(f"\n Analyzed {len(paths_to_analyze)} log files") + + # Event type distribution + print(f"\n Event types in first {len(paths_to_analyze)} files:") + for etype, count in sorted(all_event_types.items(), key=lambda x: -x[1])[:15]: + print(f" {etype:<25} {count:>6}") + + # liveTracks timing + if lt_times: + lt_times.sort() + lt_intervals = [(lt_times[i] - lt_times[i-1]) * 1e-9 for i in range(1, len(lt_times))] + duration = (lt_times[-1] - lt_times[0]) * 1e-9 + rate = len(lt_times) / max(duration, 0.1) + print("\n liveTracks:") + print(f" Count: {len(lt_times)}") + print(f" Duration: {duration:.1f}s") + print(f" Rate: {rate:.1f} Hz") + if lt_intervals: + print(f" Interval mean: {statistics.mean(lt_intervals)*1000:.1f} ms") + print(f" Interval median: {statistics.median(lt_intervals)*1000:.1f} ms") + print(f" Interval max: {max(lt_intervals)*1000:.1f} ms") + gaps_1s = sum(1 for i in lt_intervals if i > 1.0) + gaps_500ms = sum(1 for i in lt_intervals if i > 0.5) + print(f" Gaps > 500ms: {gaps_500ms}") + print(f" Gaps > 1s: {gaps_1s}") + + # liveTracks points per message + if lt_n_points: + zero_pts = sum(1 for n in lt_n_points if n == 0) + nonzero_pts = sum(1 for n in lt_n_points if n > 0) + print("\n liveTracks points per message:") + print(f" Zero points: {zero_pts}/{len(lt_n_points)} ({100*zero_pts/len(lt_n_points):.1f}%)") + print(f" Non-zero points: {nonzero_pts}/{len(lt_n_points)} ({100*nonzero_pts/len(lt_n_points):.1f}%)") + if nonzero_pts > 0: + nz = [n for n in lt_n_points if n > 0] + print(f" When non-zero, mean: {statistics.mean(nz):.1f}") + print(f" When non-zero, max: {max(nz)}") + + # radarState timing + if rs_times: + rs_times.sort() + [(rs_times[i] - rs_times[i-1]) * 1e-9 for i in range(1, len(rs_times))] + rs_duration = (rs_times[-1] - rs_times[0]) * 1e-9 + rs_rate = len(rs_times) / max(rs_duration, 0.1) + print("\n radarState:") + print(f" Count: {len(rs_times)}") + print(f" Rate: {rs_rate:.1f} Hz") + + # modelV2 timing + if mv_times: + mv_times.sort() + mv_duration = (mv_times[-1] - mv_times[0]) * 1e-9 + mv_rate = len(mv_times) / max(mv_duration, 0.1) + print("\n modelV2:") + print(f" Count: {len(mv_times)}") + print(f" Rate: {mv_rate:.1f} Hz") + + # Key ratio + if lt_times and rs_times: + lt_dur = (lt_times[-1] - lt_times[0]) * 1e-9 + rs_dur = (rs_times[-1] - rs_times[0]) * 1e-9 + lt_rate = len(lt_times) / max(lt_dur, 0.1) + rs_rate = len(rs_times) / max(rs_dur, 0.1) + print("\n Rate comparison:") + print(f" liveTracks: {lt_rate:.1f} Hz") + print(f" radarState: {rs_rate:.1f} Hz") + print(f" Ratio (RS/LT): {rs_rate/max(lt_rate, 0.1):.1f}x") + print() + print(" CRITICAL: radard polls on modelV2 (~20Hz) and only calls") + print(" RD.update() when sm.updated['liveTracks'] is True.") + print(f" If liveTracks rate is {lt_rate:.0f}Hz but radarState is {rs_rate:.0f}Hz,") + print(f" then {rs_rate/max(lt_rate, 0.1):.1f}x radarState frames run with STALE liveTracks.") + print(" radard ALWAYS publishes on every modelV2 cycle, but only") + print(" calls RD.update() when liveTracks is updated.") + print() + print(" BUT: if liveTracks messages have zero points, RD.update()") + print(" will clear self.tracks (line 258-260 in radard.py) on every") + print(" radar cycle where no points exist.") + + +def main(): + if len(sys.argv) > 1: + p = Path(sys.argv[1]) + if p.is_dir(): + log_paths = sorted(p.glob('*.zst')) + else: + log_paths = [p] + else: + log_dir = Path(__file__).resolve().parent.parent.parent / 'logs' / 'crappy-radar' / 'route-5' + log_paths = sorted(log_dir.glob('*.zst')) + + if not log_paths: + print("No .zst log files found.") + sys.exit(1) + + print("LiveTracks Availability Analysis") + print(f"{'='*70}") + analyze(log_paths) + + +if __name__ == '__main__': + main() diff --git a/scripts/nap/radar_replay.py b/scripts/nap/radar_replay.py new file mode 100755 index 00000000000000..f2d330fc9a3d36 --- /dev/null +++ b/scripts/nap/radar_replay.py @@ -0,0 +1,626 @@ +#!/usr/bin/env python3 +""" +Radar Replay Harness — Offline validation against drive logs. + +Reads compressed rlog files from logs/crappy-radar/, feeds CAN frames +through the radar_interface CAN parsing, then through radard's KF + +lead selection logic. Outputs CSV metrics for before/after comparison. + +Usage: + python scripts/nap/radar_replay.py [log_path] + +If no path given, processes the first .zst file in logs/crappy-radar/. + +Output CSV columns: + timestamp, num_tracks, lead_id, lead_dRel, lead_vRel, lead_aLeadK, + lead_radar, v_ego, track_ids + +Summary stats printed at end: + - Average track lifespan + - Lead ID change frequency + - Max detection range + - Radar-fused lead percentage +""" + +import sys +import csv +import math +import struct +from collections import defaultdict +from pathlib import Path + +# --------------------------------------------------------------------------- +# Minimal KF1D (same as openpilot.common.simple_kalman.KF1D) +# --------------------------------------------------------------------------- +class KF1D: + def __init__(self, x0, A, C, K): + self.x0_0 = x0[0][0] + self.x1_0 = x0[1][0] + self.A0_0 = A[0][0] + self.A0_1 = A[0][1] + self.A1_0 = A[1][0] + self.A1_1 = A[1][1] + self.C0_0 = C[0] + self.C0_1 = C[1] + self.K0_0 = K[0][0] + self.K1_0 = K[1][0] + self.A_K_0 = self.A0_0 - self.K0_0 * self.C0_0 + self.A_K_1 = self.A0_1 - self.K0_0 * self.C0_1 + self.A_K_2 = self.A1_0 - self.K1_0 * self.C0_0 + self.A_K_3 = self.A1_1 - self.K1_0 * self.C0_1 + + def update(self, meas): + x0 = self.A_K_0 * self.x0_0 + self.A_K_1 * self.x1_0 + self.K0_0 * meas + x1 = self.A_K_2 * self.x0_0 + self.A_K_3 * self.x1_0 + self.K1_0 * meas + self.x0_0 = x0 + self.x1_0 = x1 + + @property + def x(self): + return [[self.x0_0], [self.x1_0]] + + +# --------------------------------------------------------------------------- +# Minimal KalmanParams (mirrors radard.py) +# --------------------------------------------------------------------------- +def interp(x, xp, fp): + """Simple linear interpolation.""" + if x <= xp[0]: + return fp[0] + if x >= xp[-1]: + return fp[-1] + for i in range(len(xp) - 1): + if xp[i] <= x <= xp[i + 1]: + t = (x - xp[i]) / (xp[i + 1] - xp[i]) + return fp[i] + t * (fp[i + 1] - fp[i]) + return fp[-1] + + +class KalmanParams: + def __init__(self, dt): + self.A = [[1.0, dt], [0.0, 1.0]] + self.C = [1.0, 0.0] + dts = [i * 0.01 for i in range(1, 21)] + K0 = [0.12287673, 0.14556536, 0.16522756, 0.18281627, 0.1988689, 0.21372394, + 0.22761098, 0.24069424, 0.253096, 0.26491023, 0.27621103, 0.28705801, + 0.29750003, 0.30757767, 0.31732515, 0.32677158, 0.33594201, 0.34485814, + 0.35353899, 0.36200124] + K1 = [0.29666309, 0.29330885, 0.29042818, 0.28787125, 0.28555364, 0.28342219, + 0.28144091, 0.27958406, 0.27783249, 0.27617149, 0.27458948, 0.27307714, + 0.27162685, 0.27023228, 0.26888809, 0.26758976, 0.26633338, 0.26511557, + 0.26393339, 0.26278425] + self.K = [[interp(dt, dts, K0)], [interp(dt, dts, K1)]] + + +# --------------------------------------------------------------------------- +# Track (mirrors radard.py Track) +# --------------------------------------------------------------------------- +_LEAD_ACCEL_TAU = 1.5 +SPEED, ACCEL = 0, 1 +RADAR_TO_CAMERA = 1.52 + + +class Track: + def __init__(self, identifier, v_lead, kp): + self.identifier = identifier + self.cnt = 0 + self.aLeadTau = _LEAD_ACCEL_TAU + self.kf = KF1D([[v_lead], [0.0]], kp.A, kp.C, kp.K) + + def update(self, d_rel, y_rel, v_rel, v_lead, measured): + self.dRel = d_rel + self.yRel = y_rel + self.vRel = v_rel + self.vLead = v_lead + self.measured = measured + if self.cnt > 0: + self.kf.update(self.vLead) + self.vLeadK = float(self.kf.x[SPEED][0]) + self.aLeadK = float(self.kf.x[ACCEL][0]) + if abs(self.aLeadK) < 0.5: + self.aLeadTau = _LEAD_ACCEL_TAU + else: + self.aLeadTau *= 0.9 + self.cnt += 1 + + +# --------------------------------------------------------------------------- +# Bosch Radar CAN Parser (standalone, no opendbc dependency) +# --------------------------------------------------------------------------- +def extract_le_signal(data, start_bit, length): + """Extract a little-endian CAN signal from raw bytes.""" + value = 0 + for i in range(length): + bit_pos = start_bit + i + byte_idx = bit_pos // 8 + bit_idx = bit_pos % 8 + if byte_idx < len(data) and (data[byte_idx] & (1 << bit_idx)): + value |= (1 << i) + return value + + +def parse_radar_points(can_frames): + """Parse radar points from a dict of {addr: data} for one radar cycle. + + Returns list of (track_id, dRel, yRel, vRel, measured). + """ + points = [] + for i in range(32): + addr_a = 0x310 + i * 2 + addr_b = 0x310 + i * 2 + 1 + if addr_a not in can_frames: + continue + data_a = can_frames[addr_a] + data_b = can_frames.get(addr_b) + + tracked = extract_le_signal(data_a, 62, 1) + if not tracked: + continue + + long_dist = extract_le_signal(data_a, 0, 12) * 0.0625 + long_speed = extract_le_signal(data_a, 12, 12) * 0.0625 - 128 + lat_dist = extract_le_signal(data_a, 24, 11) * 0.125 - 128 + prob_exist = extract_le_signal(data_a, 35, 5) * 3.125 + measured = extract_le_signal(data_a, 61, 1) + + if long_dist <= 0 or long_dist > 250 or prob_exist < 50: + continue + + idx_a = extract_le_signal(data_a, 63, 1) + if data_b is not None: + idx_b = extract_le_signal(data_b, 63, 1) + if idx_a != idx_b: + continue + + points.append((i, long_dist, lat_dist, long_speed, bool(measured))) + + return points + + +# --------------------------------------------------------------------------- +# Laplacian matching (mirrors radard.py) +# --------------------------------------------------------------------------- +def laplacian_pdf(x, mu, b): + b = max(b, 1e-4) + return math.exp(-abs(x - mu) / b) + + +def match_vision_to_tracks(v_ego, vision_x, vision_y, vision_v, tracks): + """Simple lead matching. Returns best track or None.""" + if not tracks: + return None + offset = vision_x - RADAR_TO_CAMERA + + def score(t): + pd = laplacian_pdf(t.dRel, offset, 5.0) + py = laplacian_pdf(t.yRel, -vision_y, 2.0) + pv = laplacian_pdf(t.vRel + v_ego, vision_v, 5.0) + return pd * py * pv + + best = max(tracks.values(), key=score) + dist_ok = abs(best.dRel - offset) < max(offset * 0.25, 5.0) + vel_ok = (abs(best.vRel + v_ego - vision_v) < 10) or (v_ego + best.vRel > 3) + return best if dist_ok and vel_ok else None + + +# --------------------------------------------------------------------------- +# Log Reader +# --------------------------------------------------------------------------- +def read_rlog(path): + """Read an rlog.zst file, yield (logMonoTime, event_type, event_data). + + Uses capnp for proper deserialization. + """ + import zstandard as zstd + import capnp + # Find the log.capnp schema + try: + from cereal import log as cereal_log + schema = cereal_log.Event.schema + except ImportError: + # Fallback: try to find the schema file + print("WARNING: cereal not importable, trying manual capnp load", flush=True) + schema_paths = list(Path('/Users/jackbrandt/projects/openpilot-dev').rglob('log.capnp')) + if not schema_paths: + print("ERROR: Cannot find log.capnp schema", flush=True) + sys.exit(1) + capnp.remove_import_hook() + log_capnp = capnp.load(str(schema_paths[0])) + schema = log_capnp.Event.schema + + dctx = zstd.ZstdDecompressor() + with open(path, 'rb') as f: + reader = dctx.stream_reader(f) + buf = b'' + while True: + chunk = reader.read(65536) + if not chunk: + break + buf += chunk + # capnp messages are packed sequentially + while len(buf) >= 8: + try: + # Try to read a message from buffer + capnp.lib.capnp._MallocMessageBuilder() + # Use packed stream reading + break + except Exception: + break + # We'll use a simpler approach: read all at once + + # Simpler approach: decompress fully then parse + with open(path, 'rb') as f: + dctx = zstd.ZstdDecompressor() + raw = dctx.decompress(f.read(), max_output_size=500 * 1024 * 1024) + + events = [] + pos = 0 + while pos < len(raw): + try: + # Read capnp segment header: number of segments (uint32), then sizes + if pos + 4 > len(raw): + break + n_segs = struct.unpack_from(' len(raw): + break + total_data = 0 + for s in range(n_segs): + seg_size = struct.unpack_from(' len(raw): + break + msg_bytes = raw[pos:msg_end] + pos = msg_end + + with schema.from_bytes(msg_bytes, traversal_limit_in_words=2**63 - 1) as event: + which = event.which() + mono_time = event.logMonoTime + events.append((mono_time, which, event)) + except Exception: + pos += 1 # skip byte and retry + continue + + return events + + +def read_rlog_simple(path): + """Simplified rlog reader — extract CAN frames and carState/modelV2 events. + + Returns list of cereal Event readers with timestamp and event data. + Tries cereal module first, falls back to manual capnp parsing. + """ + import zstandard as zstd + + print(f"Reading {path}...", flush=True) + + dctx = zstd.ZstdDecompressor() + with open(path, 'rb') as f: + raw = dctx.decompress(f.read(), max_output_size=500 * 1024 * 1024) + + print(f" Decompressed: {len(raw)} bytes", flush=True) + + try: + from cereal import log as cereal_log + events = list(cereal_log.Event.read_multiple_bytes(raw)) + print(f" Parsed {len(events)} events (cereal)", flush=True) + return events + except ImportError: + pass + + # Fallback: manual capnp parsing + import capnp + schema_paths = list(Path(__file__).resolve().parent.parent.parent.rglob('log.capnp')) + if not schema_paths: + # Try broader search + schema_paths = list(Path('/Users/jackbrandt/projects/openpilot-dev').rglob('log.capnp')) + if not schema_paths: + print("ERROR: Cannot find log.capnp schema", flush=True) + sys.exit(1) + + print(f" Using capnp schema: {schema_paths[0]}", flush=True) + capnp.remove_import_hook() + log_capnp = capnp.load(str(schema_paths[0]), + imports=[str(schema_paths[0].parent.parent / 'cereal'), + str(schema_paths[0].parent)]) + + # First pass: extract raw message bytes for each event + msg_list = [] + pos = 0 + while pos < len(raw): + try: + if pos + 4 > len(raw): + break + n_segs = struct.unpack_from(' 10: + pos += 1 + continue + raw_header_size = 4 + 4 * n_segs + if raw_header_size % 8 != 0: + raw_header_size += 4 + if pos + raw_header_size > len(raw): + break + total_data = 0 + for s in range(n_segs): + seg_size = struct.unpack_from(' len(raw): + break + msg_list.append(raw[pos:msg_end]) + pos = msg_end + except Exception: + pos += 1 + continue + + # Second pass: parse each message and extract the fields we need into plain dicts + # (from_bytes returns a context manager; data is only valid inside the with block) + events = [] + for msg_bytes in msg_list: + try: + with log_capnp.Event.from_bytes(msg_bytes, traversal_limit_in_words=2**63 - 1) as event: + w = event.which() + mono_time = event.logMonoTime + if w == 'can': + frames = [] + for f in event.can: + frames.append({'src': f.src, 'address': f.address, 'dat': bytes(f.dat)}) + events.append({'which': w, 'logMonoTime': mono_time, 'can': frames}) + elif w == 'carState': + events.append({'which': w, 'logMonoTime': mono_time, 'vEgo': event.carState.vEgo}) + elif w == 'liveTracks': + points = [] + for pt in event.liveTracks.points: + points.append({ + 'trackId': pt.trackId, + 'dRel': pt.dRel, + 'yRel': pt.yRel, + 'vRel': pt.vRel, + 'measured': bool(pt.measured), + }) + events.append({'which': w, 'logMonoTime': mono_time, 'points': points}) + else: + events.append({'which': w, 'logMonoTime': mono_time}) + except Exception: + continue + + print(f" Parsed {len(events)} events (capnp fallback)", flush=True) + return events + + +# --------------------------------------------------------------------------- +# Main Replay +# --------------------------------------------------------------------------- +def replay(log_path, radar_dt=0.125): + """Run radar pipeline replay on a drive log. + + Args: + log_path: Path to .zst rlog file + radar_dt: KF time step (0.05 for old DT_MDL, 0.125 for fixed 8Hz) + """ + events = read_rlog_simple(log_path) + + kp = KalmanParams(radar_dt) + tracks = {} + v_ego = 0.0 + prev_lead_id = None + + # Collect radar frames by trigger cycle + radar_can_buf = {} # addr -> data for current cycle + + # Output data + rows = [] + lead_ids_over_time = [] + track_lifetimes = defaultdict(int) + max_range = 0.0 + radar_lead_count = 0 + vision_lead_count = 0 + total_lead_count = 0 + + t0 = None + + for event in events: + # Support both cereal Event objects and plain dicts (capnp fallback) + if isinstance(event, dict): + which = event['which'] + mono_time = event['logMonoTime'] + else: + try: + which = event.which() + except Exception: + continue + mono_time = event.logMonoTime + + if t0 is None: + t0 = mono_time + t_sec = (mono_time - t0) * 1e-9 + + # Track v_ego from carState + if which == 'carState': + try: + v_ego = event['vEgo'] if isinstance(event, dict) else event.carState.vEgo + except Exception: + pass + continue + + # Collect CAN frames + if which == 'can': + try: + frames = event['can'] if isinstance(event, dict) else event.can + for frame in frames: + src = frame['src'] if isinstance(frame, dict) else frame.src + if src == 1: # radar bus + addr = frame['address'] if isinstance(frame, dict) else frame.address + dat = frame['dat'] if isinstance(frame, dict) else bytes(frame.dat) + radar_can_buf[addr] = dat + except Exception: + pass + continue + + # Process on liveTracks (radar cycle boundary) + if which == 'liveTracks': + # Parse radar points from liveTracks.points (RadarData struct) + ar_pts = {} + if isinstance(event, dict): + points = event['points'] + for pt in points: + ar_pts[pt['trackId']] = (pt['dRel'], pt['yRel'], pt['vRel'], pt['measured']) + else: + try: + live_tracks = event.liveTracks + for pt in live_tracks.points: + ar_pts[pt.trackId] = (pt.dRel, pt.yRel, pt.vRel, bool(pt.measured)) + except Exception: + continue + + # Remove disappeared tracks + for tid in list(tracks.keys()): + if tid not in ar_pts: + tracks.pop(tid) + + # Update tracks + for tid, (d, y, v, m) in ar_pts.items(): + v_lead = v + v_ego + if tid not in tracks: + tracks[tid] = Track(tid, v_lead, kp) + tracks[tid].update(d, y, v, v_lead, m) + track_lifetimes[tid] += 1 + if d > max_range: + max_range = d + + # Simple lead selection (closest tracked point in lane) + lead_track = None + for t in sorted(tracks.values(), key=lambda t: t.dRel): + if abs(t.yRel) < 2.5 and t.dRel > 0.5: + lead_track = t + break + + lead_id = lead_track.identifier if lead_track else -1 + lead_dRel = lead_track.dRel if lead_track else 0.0 + lead_vRel = lead_track.vRel if lead_track else 0.0 + lead_aLeadK = lead_track.aLeadK if lead_track else 0.0 + is_radar = lead_track is not None + + if lead_id != -1: + total_lead_count += 1 + if is_radar: + radar_lead_count += 1 + else: + vision_lead_count += 1 + + lead_ids_over_time.append((t_sec, lead_id)) + + if prev_lead_id is not None and lead_id != prev_lead_id: + pass # counted below + + track_id_list = sorted(tracks.keys()) + + rows.append({ + 'timestamp': f"{t_sec:.3f}", + 'num_tracks': len(tracks), + 'lead_id': lead_id, + 'lead_dRel': f"{lead_dRel:.2f}", + 'lead_vRel': f"{lead_vRel:.2f}", + 'lead_aLeadK': f"{lead_aLeadK:.3f}", + 'lead_radar': 1 if is_radar else 0, + 'v_ego': f"{v_ego:.2f}", + 'track_ids': '|'.join(str(x) for x in track_id_list), + }) + + prev_lead_id = lead_id + continue + + # --------------------------------------------------------------------------- + # Output CSV + # --------------------------------------------------------------------------- + csv_path = str(log_path).replace('.zst', '') + f'_replay_dt{radar_dt:.3f}.csv' + if rows: + with open(csv_path, 'w', newline='') as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + print(f"\nCSV written: {csv_path} ({len(rows)} rows)", flush=True) + else: + print("\nNo radar data found in log.", flush=True) + return + + # --------------------------------------------------------------------------- + # Summary Statistics + # --------------------------------------------------------------------------- + print(f"\n{'='*60}", flush=True) + print(f"REPLAY SUMMARY (dt={radar_dt:.3f}s)", flush=True) + print(f"{'='*60}", flush=True) + + duration = float(rows[-1]['timestamp']) - float(rows[0]['timestamp']) if len(rows) > 1 else 0 + + # Lead ID changes + id_changes = 0 + for i in range(1, len(lead_ids_over_time)): + if lead_ids_over_time[i][1] != lead_ids_over_time[i - 1][1]: + id_changes += 1 + change_rate = id_changes / max(duration, 0.1) + + # Track lifetimes + lifetimes = list(track_lifetimes.values()) + avg_lifetime = sum(lifetimes) / max(len(lifetimes), 1) + max_lifetime = max(lifetimes) if lifetimes else 0 + + # Dynamic tracks (non-zero vRel) + dynamic_count = 0 + for row in rows: + for tid_str in row['track_ids'].split('|'): + if tid_str and int(tid_str) in tracks: + t = tracks[int(tid_str)] + if abs(t.vRel) > 0.1: + dynamic_count += 1 + + # Radar-fused percentage + radar_pct = 100.0 * radar_lead_count / max(total_lead_count, 1) + + print(f" Duration: {duration:.1f}s", flush=True) + print(f" Total frames: {len(rows)}", flush=True) + print(f" Unique track IDs: {len(track_lifetimes)}", flush=True) + print(f" Avg track lifespan: {avg_lifetime:.1f} frames", flush=True) + print(f" Max track lifespan: {max_lifetime} frames", flush=True) + print(f" Max detection range: {max_range:.1f}m", flush=True) + print(f" Lead ID changes: {id_changes} ({change_rate:.2f}/s)", flush=True) + print(f" Radar-fused leads: {radar_lead_count}/{total_lead_count} ({radar_pct:.0f}%)", flush=True) + print(f" Vision-only leads: {vision_lead_count}/{total_lead_count}", flush=True) + + +def main(): + log_dir = Path(__file__).resolve().parent.parent.parent / 'logs' / 'crappy-radar' + + if len(sys.argv) > 1: + log_path = Path(sys.argv[1]) + else: + # Find first .zst file + zst_files = sorted(log_dir.glob('*.zst')) + if not zst_files: + print(f"No .zst files found in {log_dir}", flush=True) + sys.exit(1) + log_path = zst_files[0] + + print("Radar Replay Harness", flush=True) + print(f"Log: {log_path}", flush=True) + print(f"{'='*60}", flush=True) + + # Run with old dt (baseline) and new dt (fixed) + print("\n--- BASELINE (dt=0.05, DT_MDL) ---", flush=True) + replay(log_path, radar_dt=0.05) + + print("\n\n--- FIXED (dt=0.125, 8Hz radar) ---", flush=True) + replay(log_path, radar_dt=0.125) + + +if __name__ == "__main__": + main() diff --git a/scripts/nap/refresh_osm_maps.py b/scripts/nap/refresh_osm_maps.py new file mode 100755 index 00000000000000..70fb22e6f75643 --- /dev/null +++ b/scripts/nap/refresh_osm_maps.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Refresh installed US OSM maps with live Overpass data around the vehicle. + +OpenStreetMap data is ODbL: © OpenStreetMap contributors. +https://www.openstreetmap.org/copyright + +Run on the device (offroad, Wi-Fi): + + python -m scripts.nap.refresh_osm_maps + +Queries OSM maxspeed ways within 100 miles (~160.9 km) of a current GNSS fix +or last stored GPS, then merges those way_ids into the already-installed +`/data/media/0/osm/speed_limits.sqlite`. The rest of the US pack is kept. + +This is not a published-pack / maps-index.json download. For first install of +the full US sqlite use: + + python -m scripts.nap.fetch_osm_maps +""" +from openpilot.selfdrive.mapd.local_refresh import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/nap/restore_epas.py b/scripts/nap/restore_epas.py new file mode 100755 index 00000000000000..dcb391918c6f6f --- /dev/null +++ b/scripts/nap/restore_epas.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +""" +Restore stock Tesla Pre-AP EPAS firmware image. + +Thin wrapper around flash_epas.py so ScriptRunner can launch restore mode +without passing command-line flags. +""" + +from scripts.nap.flash_epas import main + + +if __name__ == "__main__": + raise SystemExit(main(["--restore"])) diff --git a/scripts/nap/run_script.py b/scripts/nap/run_script.py new file mode 100755 index 00000000000000..b2a5f4abdeaee3 --- /dev/null +++ b/scripts/nap/run_script.py @@ -0,0 +1,425 @@ +#!/usr/bin/env python3 +""" +NAP Script Runner + +Standalone full-screen application for running scripts with live output display. +Launched as a separate process to take over the display. + +Usage: + ./run_script.py "Title" "module.path.to.script" "Instructions text..." + +The settings-panel button is offroad-gated, which forces the user to be +parked when they tap. After the runner opens, the user is expected to +turn the car on (brake + power button — Tesla pre-AP wake) before +pressing Start, so the ECU being targeted is electrically active. +""" + +import signal +import sys +import subprocess +import threading +import queue +import pyray as rl + +# Add openpilot to path +sys.path.insert(0, '/data/openpilot') + +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.hardware import HARDWARE, PC +from scripts.nap.script_lifecycle import script_reboots_on_exit + +# UI Constants +MARGIN = 50 +TITLE_FONT_SIZE = 70 +TEXT_FONT_SIZE = 45 +OUTPUT_FONT_SIZE = 35 +LINE_HEIGHT = 45 +BUTTON_WIDTH = 350 +BUTTON_HEIGHT = 110 +BUTTON_SPACING = 30 + + +class ScriptState: + READY = 0 + RUNNING = 1 + COMPLETED = 2 + ERROR = 3 + + +class ScriptRunnerApp: + def __init__(self, title: str, script_module: str, instructions: str): + self._title = title + self._script_module = script_module + self._instructions = instructions + self._reboot_on_exit = script_reboots_on_exit(script_module) + + self._state = ScriptState.READY + self._output_lines: list[str] = [] + self._output_queue: queue.Queue[str] = queue.Queue() + self._process: subprocess.Popen | None = None + self._reader_thread: threading.Thread | None = None + + self._scroll_panel = GuiScrollPanel() + self._instruction_lines: list[str] = [] + self._params = Params() + + # Will be initialized after gui_app.init_window() + self._font = None + self._title_font = None + self._start_button = None + self._exit_button = None + + def _init_ui(self): + """Initialize UI components after window is created""" + self._font = gui_app.font(FontWeight.NORMAL) + self._title_font = gui_app.font(FontWeight.BOLD) + + self._start_button = Button( + "Start", + click_callback=self._on_start_clicked, + button_style=ButtonStyle.PRIMARY, + font_size=TEXT_FONT_SIZE + ) + self._exit_button = Button( + "Exit", + click_callback=self._on_exit_clicked, + button_style=ButtonStyle.TRANSPARENT_WHITE_BORDER, + font_size=TEXT_FONT_SIZE + ) + + def _wrap_text(self, text: str, max_width: float, font_size: int) -> list[str]: + lines = [] + for paragraph in text.split("\n"): + if not paragraph.strip(): + lines.append("") + continue + + words = paragraph.split() + current_line = "" + + for word in words: + test_line = f"{current_line} {word}".strip() + text_width = measure_text_cached(self._font, test_line, font_size).x + + if text_width <= max_width: + current_line = test_line + else: + if current_line: + lines.append(current_line) + current_line = word + + if current_line: + lines.append(current_line) + + return lines + + def _on_start_clicked(self): + if self._state != ScriptState.READY: + return + + self._state = ScriptState.RUNNING + self._output_lines = ["Starting script...", ""] + + # Hardware scripts: set NAPScriptRunning before spawn so manager + # stops pandad before the child opens Panda USB. + if self._reboot_on_exit: + self._params.put_bool("NAPScriptRunning", True) + + try: + self._process = subprocess.Popen( + ["python", "-m", self._script_module], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd="/data/openpilot", + text=True, + encoding="utf-8", + bufsize=1 + ) + + self._reader_thread = threading.Thread(target=self._read_output, daemon=True) + self._reader_thread.start() + + except Exception as e: + if self._reboot_on_exit: + self._params.put_bool("NAPScriptRunning", False) + self._output_lines.append(f"Error starting script: {e}") + self._state = ScriptState.ERROR + + def _read_output(self): + try: + if self._process and self._process.stdout: + for line in iter(self._process.stdout.readline, ''): + if line: + self._output_queue.put(line.rstrip()) + if self._process.poll() is not None: + break + + if self._process: + return_code = self._process.wait() + if return_code == 0: + self._output_queue.put("\n[Script completed successfully]") + self._state = ScriptState.COMPLETED + else: + self._output_queue.put(f"\n[Script exited with code {return_code}]") + self._state = ScriptState.ERROR + + except Exception as e: + self._output_queue.put(f"\n[Error reading output: {e}]") + self._state = ScriptState.ERROR + + def _on_exit_clicked(self): + if self._process and self._process.poll() is None: + # Cooperative cancel: SIGINT raises KeyboardInterrupt in the + # child, so its finally blocks run (Panda safety reset, pedal + # disable, etc.). Plain SIGTERM bypasses those, which for + # calibrate_pedal means leaving the interceptor at ALLOUTPUT + # with whatever GAS_COMMAND was last sent. + self._process.send_signal(signal.SIGINT) + try: + self._process.wait(timeout=5) + except subprocess.TimeoutExpired: + # Didn't cooperate. Escalate to SIGTERM, then SIGKILL. + self._process.terminate() + try: + self._process.wait(timeout=2) + except subprocess.TimeoutExpired: + self._process.kill() + try: + self._process.wait(timeout=2) + except subprocess.TimeoutExpired: + # Child still alive after SIGKILL. Bail without clearing + # NAPScriptRunning — letting manager resume pandad while + # a zombie script may still hold Panda USB would create + # the exact dual-owner state this runner is meant to + # prevent. Surface an error and keep the runner up. + self._output_lines.append( + "[ERROR] script did not exit; manager will stay paused") + self._output_lines.append("Reboot the device to recover.") + self._state = ScriptState.ERROR + return + + # Clear NAPScriptRunning only after we've confirmed the child is gone. + if self._reboot_on_exit: + self._params.put_bool("NAPScriptRunning", False) + + gui_app.request_close() + if self._reboot_on_exit and not PC: + HARDWARE.reboot() + + def _process_output_queue(self): + while True: + try: + line = self._output_queue.get_nowait() + self._output_lines.append(line) + except queue.Empty: + break + + def render(self): + rect = rl.Rectangle(0, 0, gui_app.width, gui_app.height) + + # Draw background + rl.draw_rectangle_rec(rect, rl.Color(20, 20, 20, 255)) + + # Process pending output + self._process_output_queue() + + content_x = rect.x + MARGIN + content_width = rect.width - MARGIN * 2 + current_y = rect.y + MARGIN + + # Draw title + title_size = measure_text_cached(self._title_font, self._title, TITLE_FONT_SIZE) + rl.draw_text_ex( + self._title_font, + self._title, + rl.Vector2(content_x, current_y), + TITLE_FONT_SIZE, + 0, + rl.WHITE + ) + current_y += title_size.y + MARGIN + + # Draw separator + rl.draw_line_ex( + rl.Vector2(content_x, current_y), + rl.Vector2(content_x + content_width, current_y), + 2, + rl.Color(80, 80, 80, 255) + ) + current_y += MARGIN + + if self._state == ScriptState.READY: + self._render_instructions(rect, content_x, content_width, current_y) + else: + self._render_output(rect, content_x, content_width, current_y) + + self._render_buttons(rect) + + def _render_instructions(self, rect, content_x, content_width, start_y): + if not self._instruction_lines: + self._instruction_lines = self._wrap_text(self._instructions, content_width, TEXT_FONT_SIZE) + + button_area_height = BUTTON_HEIGHT + MARGIN * 2 + text_area_height = rect.height - start_y - button_area_height - rect.y + + current_y = start_y + for line in self._instruction_lines: + if current_y + LINE_HEIGHT > start_y + text_area_height: + break + rl.draw_text_ex( + self._font, + line, + rl.Vector2(content_x, current_y), + TEXT_FONT_SIZE, + 0, + rl.Color(200, 200, 200, 255) + ) + current_y += LINE_HEIGHT + + def _render_output(self, rect, content_x, content_width, start_y): + button_area_height = BUTTON_HEIGHT + MARGIN * 2 + output_area_height = rect.height - start_y - button_area_height - rect.y + + output_rect = rl.Rectangle(content_x, start_y, content_width, output_area_height) + + content_height = len(self._output_lines) * LINE_HEIGHT + content_rect = rl.Rectangle(0, 0, content_width, content_height) + + # Auto-scroll to bottom + if content_height > output_area_height: + self._scroll_panel._offset_filter_y.x = -(content_height - output_area_height) + + scroll = self._scroll_panel.update(output_rect, content_rect) + + rl.begin_scissor_mode( + int(output_rect.x), + int(output_rect.y), + int(output_rect.width), + int(output_rect.height) + ) + + for i, line in enumerate(self._output_lines): + line_y = output_rect.y + scroll + i * LINE_HEIGHT + + if line_y + LINE_HEIGHT < output_rect.y or line_y > output_rect.y + output_rect.height: + continue + + if "[Error" in line or "Error:" in line: + color = rl.Color(255, 100, 100, 255) + elif "[Script completed" in line: + color = rl.Color(100, 255, 100, 255) + elif line.startswith("***"): + color = rl.Color(100, 200, 255, 255) + else: + color = rl.WHITE + + rl.draw_text_ex( + self._font, + line, + rl.Vector2(output_rect.x, line_y), + OUTPUT_FONT_SIZE, + 0, + color + ) + + rl.end_scissor_mode() + + # Status indicator + status_text = "" + status_color = rl.WHITE + if self._state == ScriptState.RUNNING: + status_text = "Running..." + status_color = rl.Color(255, 200, 100, 255) + elif self._state == ScriptState.COMPLETED: + status_text = "Completed" + status_color = rl.Color(100, 255, 100, 255) + elif self._state == ScriptState.ERROR: + status_text = "Error" + status_color = rl.Color(255, 100, 100, 255) + + if status_text: + status_size = measure_text_cached(self._font, status_text, TEXT_FONT_SIZE) + rl.draw_text_ex( + self._font, + status_text, + rl.Vector2(rect.x + rect.width - MARGIN - status_size.x, start_y - LINE_HEIGHT), + TEXT_FONT_SIZE, + 0, + status_color + ) + + def _render_buttons(self, rect): + button_y = rect.y + rect.height - MARGIN - BUTTON_HEIGHT + + if self._state == ScriptState.READY: + start_rect = rl.Rectangle( + rect.x + rect.width - MARGIN - BUTTON_WIDTH * 2 - BUTTON_SPACING, + button_y, + BUTTON_WIDTH, + BUTTON_HEIGHT + ) + exit_rect = rl.Rectangle( + rect.x + rect.width - MARGIN - BUTTON_WIDTH, + button_y, + BUTTON_WIDTH, + BUTTON_HEIGHT + ) + self._start_button.render(start_rect) + self._exit_button.render(exit_rect) + else: + exit_rect = rl.Rectangle( + rect.x + rect.width - MARGIN - BUTTON_WIDTH, + button_y, + BUTTON_WIDTH, + BUTTON_HEIGHT + ) + # Exit is disabled while RUNNING. The flash path can't be + # safely interrupted mid-write; the calibration/test paths + # also disable cancel for consistency with the original design. + self._exit_button.set_enabled(self._state != ScriptState.RUNNING) + self._exit_button.render(exit_rect) + + +def main(): + if len(sys.argv) < 4: + print("Usage: run_script.py <module> <instructions>") + print("Example: run_script.py 'Pedal Calibration' 'scripts.nap.calibrate_pedal' 'Instructions...'") + sys.exit(1) + + title = sys.argv[1] + module = sys.argv[2] + instructions = sys.argv[3] + + # Dispatch to the mici (comma 4) runner when the device's logical + # canvas is small. The tici runner's hardcoded font/button sizes are + # unusable at 536x240. Same lifecycle, different UI primitives. + if not gui_app.big_ui(): + from scripts.nap import run_script_mici + sys.argv = ["run_script_mici", title, module, instructions] + run_script_mici.main() + return + + # Kill the main openpilot UI tmux session so we can take over the screen. + # tmux isn't installed on dev hosts (macOS), so swallow the FileNotFoundError. + # Map sqlite jobs leave the session up so Exit can return to Settings. + if script_reboots_on_exit(module): + try: + subprocess.run(["tmux", "kill-session", "-t", "comma"], capture_output=True) + except FileNotFoundError: + pass + + gui_app.init_window("NAP Script Runner") + + app = ScriptRunnerApp(title, module, instructions) + app._init_ui() + + for _ in gui_app.render(): + app.render() + + +if __name__ == "__main__": + main() diff --git a/scripts/nap/run_script_mici.py b/scripts/nap/run_script_mici.py new file mode 100644 index 00000000000000..655cf72a83df66 --- /dev/null +++ b/scripts/nap/run_script_mici.py @@ -0,0 +1,153 @@ +"""Mici (comma 4) NAP script runner. + +Selected from `run_script.py:main()` when `gui_app.big_ui()` is False. + +Matches the tici runner's lifecycle contract — `NAPScriptRunning` +param dance, SIGINT → SIGTERM → SIGKILL cancel with fail-closed on +stuck child, reboot on exit (PC=False). The settings-panel button is +offroad-gated, which forces the user to be parked at tap time; the +user is expected to wake the car (brake + power button) before +pressing Start so the targeted ECU is electrically active. + +The UI primitive lives at `system/ui/mici/widgets/script_runner_app.py` +so that it can be reused for any future mici full-screen-script flow. +""" +import queue +import signal +import subprocess +import sys +import threading + +from openpilot.common.params import Params +from openpilot.system.hardware import HARDWARE, PC +from openpilot.system.ui.mici.widgets.script_runner_app import MiciScriptRunnerApp, ScriptState +from scripts.nap.script_lifecycle import script_reboots_on_exit + + +class _NAPMiciRunner: + def __init__(self, title: str, module: str, instructions: str): + self._module = module + self._reboot_on_exit = script_reboots_on_exit(module) + self._params = Params() + self._process: subprocess.Popen | None = None + self._reader_thread: threading.Thread | None = None + self._output_queue: queue.Queue[str] = queue.Queue() + + self._app = MiciScriptRunnerApp( + title=title, + instructions=instructions, + on_start=self._on_start, + on_exit=self._on_exit, + ) + + def run(self) -> None: + self._app.run("NAP Script Runner") + + # ── start ───────────────────────────────────────── + + def _on_start(self) -> None: + if self._reboot_on_exit: + self._params.put_bool("NAPScriptRunning", True) + try: + self._process = subprocess.Popen( + ["python", "-m", self._module], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd="/data/openpilot", + text=True, + encoding="utf-8", + bufsize=1, + ) + except Exception as e: + if self._reboot_on_exit: + self._params.put_bool("NAPScriptRunning", False) + self._app.append_output(f"Error starting script: {e}") + self._app.set_state(ScriptState.ERROR) + return + + self._app.append_output("Starting script...") + self._app.set_state(ScriptState.RUNNING) + self._reader_thread = threading.Thread(target=self._read_output, daemon=True) + self._reader_thread.start() + + def _read_output(self) -> None: + try: + assert self._process is not None + if self._process.stdout is not None: + for line in iter(self._process.stdout.readline, ''): + if line: + self._app.append_output(line.rstrip()) + if self._process.poll() is not None: + break + + return_code = self._process.wait() + if return_code == 0: + self._app.append_output("") + self._app.append_output("[Script completed successfully]") + self._app.set_state(ScriptState.COMPLETED) + else: + self._app.append_output("") + self._app.append_output(f"[Script exited with code {return_code}]") + self._app.set_state(ScriptState.ERROR) + except Exception as e: + self._app.append_output(f"[Error reading output: {e}]") + self._app.set_state(ScriptState.ERROR) + + # ── exit ────────────────────────────────────────── + + def _on_exit(self) -> None: + if self._process is not None and self._process.poll() is None: + # Cooperative cancel: SIGINT first so the child's finally blocks + # run (Panda safety reset, pedal disable). Escalate only if the + # child doesn't cooperate. Note: by the time Exit is clickable + # (state != RUNNING) the child is already dead, so this path is + # mostly defense in depth. + self._process.send_signal(signal.SIGINT) + try: + self._process.wait(timeout=5) + except subprocess.TimeoutExpired: + self._process.terminate() + try: + self._process.wait(timeout=2) + except subprocess.TimeoutExpired: + self._process.kill() + try: + self._process.wait(timeout=2) + except subprocess.TimeoutExpired: + self._app.append_output("[ERROR] script did not exit; manager will stay paused") + self._app.append_output("Reboot the device to recover.") + self._app.set_state(ScriptState.ERROR) + return + + if self._reboot_on_exit: + self._params.put_bool("NAPScriptRunning", False) + + from openpilot.system.ui.lib.application import gui_app + gui_app.request_close() + if self._reboot_on_exit and not PC: + HARDWARE.reboot() + + +def main(): + if len(sys.argv) < 4: + print("Usage: run_script_mici.py <title> <module> <instructions>") + sys.exit(1) + + title = sys.argv[1] + module = sys.argv[2] + instructions = sys.argv[3] + + # Kill the comma tmux session so we own the screen (no-op on dev hosts). + # Map sqlite jobs leave the session up so Exit can return to Settings. + if script_reboots_on_exit(module): + try: + subprocess.run(["tmux", "kill-session", "-t", "comma"], capture_output=True) + except FileNotFoundError: + pass + + runner = _NAPMiciRunner(title, module, instructions) + runner.run() + + +if __name__ == "__main__": + main() diff --git a/scripts/nap/script_lifecycle.py b/scripts/nap/script_lifecycle.py new file mode 100644 index 00000000000000..f24160ea519be6 --- /dev/null +++ b/scripts/nap/script_lifecycle.py @@ -0,0 +1,17 @@ +"""Which NAP script-runner jobs reboot the device on Exit. + +Refresh maps, Download US Maps, and Install speed-sign weights only write +files under /data. Pedal / EPAS / other Panda tools keep HARDWARE.reboot() +so manager can resume. +""" +from __future__ import annotations + +_NO_REBOOT_MODULES = frozenset({ + "scripts.nap.fetch_osm_maps", + "scripts.nap.refresh_osm_maps", + "scripts.nap.install_speed_sign_weights", +}) + + +def script_reboots_on_exit(module: str) -> bool: + return module not in _NO_REBOOT_MODULES diff --git a/scripts/nap/test_radar.py b/scripts/nap/test_radar.py new file mode 100755 index 00000000000000..c95aae358ac355 --- /dev/null +++ b/scripts/nap/test_radar.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +""" +Tesla Pre-AP Radar Test Tool (GUI version) +Shows all detected radar points to verify radar connectivity and operation. + +Displays every tracked radar point from the Bosch radar with distance, +lateral offset, speed, and probability. Use this to verify the radar +is working and communicating properly. + +Uses direct Panda access (stops pandad via ScriptRunner). +""" + +import time +import sys + +# ============================================ +# Radar CAN Constants (Bosch, 32 points) +# ============================================ +RADAR_BUS = 1 # CANBUS.radar +NUM_RADAR_POINTS = 32 +RADAR_ADDR_START = 0x310 +RADAR_ADDR_END = 0x36F + +# ============================================ +# Display +# ============================================ +DISPLAY_INTERVAL = 0.5 +PANDA_CONNECT_RETRIES = 5 +PANDA_CONNECT_DELAY = 2.0 + +# Moving state names +MOVING_STATES = { + 0: "Unknown", + 1: "Moving", + 2: "Stopped", + 3: "Standing", +} + + +def p(msg): + """Print with flush for real-time ScriptRunner display.""" + print(msg, flush=True) + + +def extract_signal(data, start_bit, length): + """Extract a little-endian CAN signal from raw bytes.""" + value = 0 + for i in range(length): + bit_pos = start_bit + i + byte_idx = bit_pos // 8 + bit_idx = bit_pos % 8 + if byte_idx < len(data) and (data[byte_idx] & (1 << bit_idx)): + value |= (1 << i) + return value + + +def parse_radar_a(data): + """Parse RadarPoint_A message.""" + return { + 'long_dist': extract_signal(data, 0, 12) * 0.0625, + 'long_speed': extract_signal(data, 12, 12) * 0.0625 - 128, + 'lat_dist': extract_signal(data, 24, 11) * 0.125 - 128, + 'prob_exist': extract_signal(data, 35, 5) * 3.125, + 'long_accel': extract_signal(data, 40, 10) * 0.03125 - 16, + 'valid': extract_signal(data, 55, 1), + 'meas': extract_signal(data, 61, 1), + 'tracked': extract_signal(data, 62, 1), + 'index': extract_signal(data, 63, 1), + } + + +def parse_radar_b(data): + """Parse RadarPoint_B message.""" + return { + 'lat_speed': extract_signal(data, 0, 10) * 0.125 - 64, + 'length': extract_signal(data, 10, 6) * 0.125, + 'dz': extract_signal(data, 16, 6) * 0.25 - 5, + 'moving_state': extract_signal(data, 22, 2), + 'index2': extract_signal(data, 63, 1), + } + + +def connect_panda(): + """Connect to Panda with retries.""" + from panda import Panda + + for attempt in range(PANDA_CONNECT_RETRIES): + try: + panda = Panda() + return panda + except Exception as e: + if attempt < PANDA_CONNECT_RETRIES - 1: + p(f" Panda not ready ({e}), retrying in {PANDA_CONNECT_DELAY}s...") + time.sleep(PANDA_CONNECT_DELAY) + else: + raise + + +def main(): + p("=" * 60) + p("RADAR TEST TOOL") + p("=" * 60) + p("") + p("Showing ALL tracked radar points.") + p("Use this to verify radar connectivity and operation.") + p("Press Cancel when done.") + p("=" * 60) + + panda = None + try: + p("\nConnecting to Panda...") + panda = connect_panda() + p(" Connected") + + panda.set_safety_mode(17) # SAFETY_ALLOUTPUT for CAN forwarding + p(" Safety mode set") + + points_a = {} + points_b = {} + + start_time = time.monotonic() + last_display = 0 + msg_count = 0 + radar_msgs_seen = False + + p("\nListening for radar data on CAN bus 1...") + + while True: + try: + for msg in panda.can_recv(): + if len(msg) == 4: + addr, _, dat, src = msg + elif len(msg) == 3: + addr, dat, src = msg + else: + continue + + if src != RADAR_BUS: + continue + + if RADAR_ADDR_START <= addr <= RADAR_ADDR_END: + radar_msgs_seen = True + point_idx = (addr - RADAR_ADDR_START) // 2 + is_b = (addr - RADAR_ADDR_START) % 2 == 1 + data = bytes(dat) if not isinstance(dat, (bytes, bytearray)) else dat + + if is_b: + points_b[point_idx] = parse_radar_b(data) + else: + points_a[point_idx] = parse_radar_a(data) + msg_count += 1 + except Exception as e: + if "not enough values" not in str(e): + p(f" CAN recv error: {e}") + + now = time.monotonic() + if now - last_display >= DISPLAY_INTERVAL: + last_display = now + elapsed = now - start_time + + if not radar_msgs_seen: + p(f" [{elapsed:.0f}s] No radar messages on bus {RADAR_BUS}...") + time.sleep(0.5) + continue + + # Collect all tracked points + tracked = [] + total_with_data = 0 + for i in range(NUM_RADAR_POINTS): + if i not in points_a: + continue + pa = points_a[i] + total_with_data += 1 + if not pa['tracked']: + continue + if pa['long_dist'] <= 0 or pa['long_dist'] > 250: + continue + if pa['prob_exist'] < 50: + continue + pb = points_b.get(i, {}) + tracked.append((i, pa, pb)) + + # Sort by distance + tracked.sort(key=lambda x: x[1]['long_dist']) + + p(f"\n--- [{elapsed:.0f}s] {len(tracked)} tracked / {total_with_data} active ({msg_count} msgs) ---") + if tracked: + p(f" {'#':>3s} {'Dist(m)':>8s} {'Lat(m)':>8s} {'Spd(m/s)':>9s} {'Accel':>7s} {'Prob':>6s} {'State':>8s}") + p(f" {'---':>3s} {'-------':>8s} {'------':>8s} {'--------':>9s} {'-----':>7s} {'----':>6s} {'-----':>8s}") + for idx, pa, pb in tracked: + state = MOVING_STATES.get(pb.get('moving_state', 0), "?") + p(f" {idx:3d} {pa['long_dist']:8.2f} {pa['lat_dist']:8.2f} {pa['long_speed']:9.2f}" + + f" {pa['long_accel']:7.2f} {pa['prob_exist']:5.1f}% {state:>8s}") + else: + p(" (no tracked points)") + + time.sleep(0.01) + + except KeyboardInterrupt: + p("\nStopped.") + except Exception as e: + p(f"\nERROR: {e}") + import traceback + traceback.print_exc() + return 1 + finally: + if panda is not None: + try: + panda.set_safety_mode(0) # SAFETY_SILENT + panda.close() + p("\nPanda connection closed.") + except Exception: + pass + + p("\nRadar test ended.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/nap/vision_radar_deep.py b/scripts/nap/vision_radar_deep.py new file mode 100755 index 00000000000000..12dd3afbcd5e99 --- /dev/null +++ b/scripts/nap/vision_radar_deep.py @@ -0,0 +1,419 @@ +#!/usr/bin/env python3 +""" +Deep Vision vs Radar Analysis — compares raw liveTracks radar data +against modelV2 vision leads to find WHY matching fails. + +For each radarState frame, also looks at the liveTracks (raw radar points) +to see if a suitable radar track EXISTS but wasn't matched. + +Outputs: + 1. Per-frame CSV with vision lead, best radar track, and match diagnostics + 2. Summary of WHY 89.7% of frames are vision-only + +Usage: + python scripts/nap/vision_radar_deep.py [log_dir] +""" + +import math +import sys +import csv +import struct +from pathlib import Path +from collections import defaultdict +import statistics + +RADAR_TO_CAMERA = 1.52 + + +def read_events(path): + """Read a .zst cereal log file.""" + import zstandard as zstd + print(f" Reading {Path(path).name}...", end="", flush=True) + + dctx = zstd.ZstdDecompressor() + with open(path, 'rb') as f: + raw = dctx.decompress(f.read(), max_output_size=500 * 1024 * 1024) + + try: + from cereal import log as cereal_log + events = list(cereal_log.Event.read_multiple_bytes(raw)) + print(f" {len(events)} events (cereal)", flush=True) + return events + except ImportError: + pass + + import capnp + schema_paths = list(Path(__file__).resolve().parent.parent.parent.rglob('log.capnp')) + if not schema_paths: + schema_paths = list(Path('/Users/jackbrandt/projects/openpilot-dev').rglob('log.capnp')) + if not schema_paths: + print(" ERROR: Cannot find log.capnp schema", flush=True) + sys.exit(1) + capnp.remove_import_hook() + log_capnp = capnp.load(str(schema_paths[0]), + imports=[str(schema_paths[0].parent.parent / 'cereal'), + str(schema_paths[0].parent)]) + + msg_list = [] + pos = 0 + while pos < len(raw): + try: + if pos + 4 > len(raw): + break + n_segs = struct.unpack_from('<I', raw, pos)[0] + 1 + if n_segs > 10: + pos += 1 + continue + raw_header_size = 4 + 4 * n_segs + if raw_header_size % 8 != 0: + raw_header_size += 4 + if pos + raw_header_size > len(raw): + break + total_data = 0 + for s in range(n_segs): + seg_size = struct.unpack_from('<I', raw, pos + 4 + s * 4)[0] * 8 + total_data += seg_size + msg_end = pos + raw_header_size + total_data + if msg_end > len(raw): + break + msg_list.append(raw[pos:msg_end]) + pos = msg_end + except Exception: + pos += 1 + continue + + events = [] + for msg_bytes in msg_list: + try: + with log_capnp.Event.from_bytes(msg_bytes, traversal_limit_in_words=2**63 - 1) as event: + w = event.which() + mono = event.logMonoTime + if w == 'modelV2': + leads = event.modelV2.leadsV3 + if len(leads) > 0: + lead0 = leads[0] + events.append({ + 'which': 'modelV2', 'logMonoTime': mono, + 'x0': list(lead0.x)[0] if len(lead0.x) > 0 else 0, + 'xStd0': list(lead0.xStd)[0] if len(lead0.xStd) > 0 else 0, + 'y0': list(lead0.y)[0] if len(lead0.y) > 0 else 0, + 'yStd0': list(lead0.yStd)[0] if len(lead0.yStd) > 0 else 0, + 'v0': list(lead0.v)[0] if len(lead0.v) > 0 else 0, + 'vStd0': list(lead0.vStd)[0] if len(lead0.vStd) > 0 else 0, + 'prob': float(lead0.prob), + }) + elif w == 'radarState': + rs = event.radarState + l1 = rs.leadOne + events.append({ + 'which': 'radarState', 'logMonoTime': mono, + 'mdMonoTime': int(rs.mdMonoTime), + 'dRel': float(l1.dRel), 'radar': bool(l1.radar), + 'status': bool(l1.status), 'radarTrackId': int(l1.radarTrackId), + }) + elif w == 'liveTracks': + lt = event.liveTracks + points = [] + for pt in lt.points: + points.append({ + 'trackId': int(pt.trackId), 'dRel': float(pt.dRel), + 'yRel': float(pt.yRel), 'vRel': float(pt.vRel), + 'measured': bool(pt.measured), + }) + events.append({ + 'which': 'liveTracks', 'logMonoTime': mono, + 'points': points, + }) + elif w == 'carState': + events.append({ + 'which': 'carState', 'logMonoTime': mono, + 'vEgo': float(event.carState.vEgo), + }) + else: + pass + except Exception: + continue + print(f" {len(events)} events (capnp)", flush=True) + return events + + +def laplacian_pdf(x, mu, b): + b = max(b, 1e-4) + return math.exp(-abs(x - mu) / b) + + +def analyze(log_paths): + """Run deep analysis.""" + # Collect all events + all_events = [] + for path in sorted(log_paths): + all_events.extend(read_events(path)) + + # Sort by timestamp + all_events.sort(key=lambda e: e['logMonoTime'] if isinstance(e, dict) else e.logMonoTime) + + # Index events by type for pairing + model_by_time = {} + live_tracks_latest = [] # most recent liveTracks points + v_ego = 0.0 + t0 = None + + rows = [] + + # Reason counters + reasons = defaultdict(int) + + for evt in all_events: + if isinstance(evt, dict): + which = evt['which'] + mono = evt['logMonoTime'] + else: + which = evt.which() + mono = evt.logMonoTime + + if t0 is None: + t0 = mono + + if which == 'carState': + v_ego = evt['vEgo'] if isinstance(evt, dict) else evt.carState.vEgo + + elif which == 'modelV2': + model_by_time[mono] = evt + + elif which == 'liveTracks': + pts = evt['points'] if isinstance(evt, dict) else [] + live_tracks_latest = pts + + elif which == 'radarState': + rs = evt if isinstance(evt, dict) else None + if rs is None: + continue + + t_sec = (mono - t0) * 1e-9 + md_mono = rs['mdMonoTime'] + + # Find corresponding model frame + model = model_by_time.get(md_mono) + if model is None: + # Find nearest + best_t = None + best_dt = float('inf') + for t in model_by_time: + dt = abs(t - md_mono) + if dt < best_dt: + best_dt = dt + best_t = t + if best_t is not None and best_dt < 1e9: + model = model_by_time[best_t] + + if model is None: + continue + + vision_x = model['x0'] + vision_y = model['y0'] + vision_v = model['v0'] + vision_prob = model['prob'] + vision_xStd = model['xStd0'] + vision_yStd = model['yStd0'] + vision_vStd = model['vStd0'] + offset_vision_dist = vision_x - RADAR_TO_CAMERA + + is_radar = rs['radar'] + has_status = rs['status'] + radar_dRel = rs['dRel'] + rs['radarTrackId'] + + # Analyze what liveTracks has + n_tracks = len(live_tracks_latest) + + # Find the best-matching track manually (replicate radard logic) + best_track = None + best_score = -1 + best_d_delta = None + best_y_delta = None + best_v_delta = None + + for pt in live_tracks_latest: + pd = laplacian_pdf(pt['dRel'], offset_vision_dist, + max(vision_xStd, 1e-4)) + py = laplacian_pdf(pt['yRel'], -vision_y, + max(vision_yStd, 1e-4)) + pv = laplacian_pdf(pt['vRel'] + v_ego, vision_v, + max(vision_vStd, 1e-4)) + score = pd * py * pv + if score > best_score: + best_score = score + best_track = pt + best_d_delta = pt['dRel'] - offset_vision_dist + best_y_delta = pt['yRel'] - (-vision_y) + best_v_delta = (pt['vRel'] + v_ego) - vision_v + + # Check dist_sane and vel_sane on best track + if best_track is not None: + dist_sane = abs(best_track['dRel'] - offset_vision_dist) < max(offset_vision_dist * 0.25, 5.0) + dist_sane_35 = abs(best_track['dRel'] - offset_vision_dist) < max(offset_vision_dist * 0.35, 8.0) + vel_sane = (abs(best_track['vRel'] + v_ego - vision_v) < 10) or (v_ego + best_track['vRel'] > 3) + else: + dist_sane = False + dist_sane_35 = False + vel_sane = False + + # Determine WHY matching failed (if it did) + reason = "matched" + if not is_radar and has_status: + if n_tracks == 0: + reason = "no_radar_tracks" + elif not (vision_prob > 0.5): + reason = "low_vision_prob" + elif best_track is not None and not dist_sane: + reason = "dist_sane_fail" + elif best_track is not None and not vel_sane: + reason = "vel_sane_fail" + else: + reason = "unknown" + elif not has_status: + reason = "no_lead" + + reasons[reason] += 1 + + row = { + 'time_s': f"{t_sec:.3f}", + 'v_ego': f"{v_ego:.2f}", + 'vision_x_cam': f"{vision_x:.2f}", + 'vision_x_radar': f"{offset_vision_dist:.2f}", + 'vision_prob': f"{vision_prob:.3f}", + 'vision_xStd': f"{vision_xStd:.2f}", + 'n_radar_tracks': n_tracks, + 'is_radar_matched': 1 if is_radar else 0, + 'lead_status': 1 if has_status else 0, + 'fused_dRel': f"{radar_dRel:.2f}", + 'best_track_id': best_track['trackId'] if best_track else -1, + 'best_track_dRel': f"{best_track['dRel']:.2f}" if best_track else "", + 'best_track_yRel': f"{best_track['yRel']:.2f}" if best_track else "", + 'best_track_vRel': f"{best_track['vRel']:.2f}" if best_track else "", + 'd_delta': f"{best_d_delta:.2f}" if best_d_delta is not None else "", + 'y_delta': f"{best_y_delta:.2f}" if best_y_delta is not None else "", + 'v_delta': f"{best_v_delta:.2f}" if best_v_delta is not None else "", + 'dist_sane_25': 1 if dist_sane else 0, + 'dist_sane_35': 1 if dist_sane_35 else 0, + 'vel_sane': 1 if vel_sane else 0, + 'match_score': f"{best_score:.6f}" if best_score > 0 else "", + 'reason': reason, + } + rows.append(row) + + # Write CSV + csv_path = str(log_paths[0].parent / 'vision_radar_deep.csv') + with open(csv_path, 'w', newline='') as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + print(f"\nCSV: {csv_path} ({len(rows)} rows)") + + # ----------------------------------------------------------------------- + # Summary + # ----------------------------------------------------------------------- + print(f"\n{'='*70}") + print("DEEP VISION vs RADAR ANALYSIS") + print(f"{'='*70}") + + total = len(rows) + print(f"\n Total radarState frames: {total}") + print("\n Match failure reasons:") + for reason, count in sorted(reasons.items(), key=lambda x: -x[1]): + print(f" {reason:<25} {count:>6} ({100*count/total:.1f}%)") + + # Focus on "no_radar_tracks" — when vision sees a lead but radar has zero tracks + no_tracks_frames = [r for r in rows if r['reason'] == 'no_radar_tracks'] + if no_tracks_frames: + dists = [float(r['vision_x_cam']) for r in no_tracks_frames] + print("\n 'no_radar_tracks' analysis (vision sees lead, radar has nothing):") + print(f" Count: {len(no_tracks_frames)}") + print(f" Vision dist mean: {statistics.mean(dists):.1f} m") + print(f" Vision dist median: {statistics.median(dists):.1f} m") + print(f" Vision dist range: {min(dists):.1f} - {max(dists):.1f} m") + + # Focus on "dist_sane_fail" — radar tracks exist but distance doesn't match + dist_fail = [r for r in rows if r['reason'] == 'dist_sane_fail'] + if dist_fail: + d_deltas = [float(r['d_delta']) for r in dist_fail if r['d_delta']] + abs_d = [abs(d) for d in d_deltas] + y_deltas = [float(r['y_delta']) for r in dist_fail if r['y_delta']] + print("\n 'dist_sane_fail' analysis (radar tracks exist, distance mismatch):") + print(f" Count: {len(dist_fail)}") + if d_deltas: + print(f" d_delta mean: {statistics.mean(d_deltas):+.2f} m") + print(f" d_delta median: {statistics.median(d_deltas):+.2f} m") + print(f" d_delta std: {statistics.stdev(d_deltas):.2f} m") + print(f" abs d_delta mean: {statistics.mean(abs_d):.2f} m") + print(f" abs d_delta P50: {sorted(abs_d)[len(abs_d)//2]:.2f} m") + print(f" abs d_delta P90: {sorted(abs_d)[int(len(abs_d)*0.9)]:.2f} m") + vision_dists = [float(r['vision_x_radar']) for r in dist_fail] + print(f" Vision dist mean: {statistics.mean(vision_dists):.1f} m") + if y_deltas: + print(f" y_delta mean: {statistics.mean(y_deltas):+.2f} m") + + # When radar IS matched, what do the deltas look like? + matched = [r for r in rows if int(r['is_radar_matched']) == 1] + if matched: + md = [float(r['d_delta']) for r in matched if r['d_delta']] + if md: + print("\n Radar-matched frames delta analysis:") + print(f" Count: {len(matched)}") + print(f" d_delta mean: {statistics.mean(md):+.2f} m") + print(f" d_delta std: {statistics.stdev(md):.2f} m") + print(f" abs d_delta mean: {statistics.mean([abs(d) for d in md]):.2f} m") + + # Frames with vision lead but NO radar tracks at all — by distance bins + if no_tracks_frames: + print("\n 'no_radar_tracks' by distance:") + ranges = [(0, 20, "0-20m"), (20, 40, "20-40m"), (40, 60, "40-60m"), + (60, 100, "60-100m"), (100, 300, "100m+")] + for lo, hi, label in ranges: + in_range = [r for r in no_tracks_frames if lo <= float(r['vision_x_cam']) < hi] + pct_of_total = 100 * len(in_range) / len(no_tracks_frames) if no_tracks_frames else 0 + print(f" {label:<12} {len(in_range):>6} ({pct_of_total:.1f}%)") + + # Radar track availability: for ALL active-lead frames, how many have tracks? + active = [r for r in rows if int(r['lead_status']) == 1] + has_tracks = [r for r in active if int(r['n_radar_tracks']) > 0] + print("\n Radar track availability (active lead frames):") + print(f" With radar tracks: {len(has_tracks)}/{len(active)} ({100*len(has_tracks)/max(len(active),1):.1f}%)") + print(f" Without radar tracks: {len(active)-len(has_tracks)}/{len(active)} ({100*(len(active)-len(has_tracks))/max(len(active),1):.1f}%)") + + # When tracks exist but aren't matched — is it dist_sane or vel_sane? + has_tracks_not_matched = [r for r in active if int(r['n_radar_tracks']) > 0 and int(r['is_radar_matched']) == 0] + if has_tracks_not_matched: + ds_fail = sum(1 for r in has_tracks_not_matched if int(r['dist_sane_25']) == 0) + vs_fail = sum(1 for r in has_tracks_not_matched if int(r['vel_sane']) == 0) + both_pass = sum(1 for r in has_tracks_not_matched if int(r['dist_sane_25']) == 1 and int(r['vel_sane']) == 1) + print(f"\n Tracks exist but not matched ({len(has_tracks_not_matched)} frames):") + print(f" dist_sane fail: {ds_fail} ({100*ds_fail/len(has_tracks_not_matched):.1f}%)") + print(f" vel_sane fail: {vs_fail} ({100*vs_fail/len(has_tracks_not_matched):.1f}%)") + print(f" Both pass (mystery): {both_pass} ({100*both_pass/len(has_tracks_not_matched):.1f}%)") + + +def main(): + if len(sys.argv) > 1: + p = Path(sys.argv[1]) + if p.is_dir(): + log_paths = sorted(p.glob('*.zst')) + else: + log_paths = [p] + else: + log_dir = Path(__file__).resolve().parent.parent.parent / 'logs' / 'crappy-radar' / 'route-5' + log_paths = sorted(log_dir.glob('*.zst')) + + if not log_paths: + print("No .zst log files found.") + sys.exit(1) + + print("Deep Vision vs Radar Analysis") + print(f"Processing {len(log_paths)} log files") + print(f"{'='*70}") + + analyze(log_paths) + + +if __name__ == '__main__': + main() diff --git a/scripts/nap/vision_radar_delta.py b/scripts/nap/vision_radar_delta.py new file mode 100755 index 00000000000000..5d9244963145e2 --- /dev/null +++ b/scripts/nap/vision_radar_delta.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python3 +""" +Vision vs Radar Lead Distance Analysis + +Reads drive logs and extracts per-frame: + - Vision model lead distance (modelV2.leadsV3[0].x[0]) + - Fused radar lead distance (radarState.leadOne.dRel) + - Whether lead is radar-matched or vision-only + - The delta between vision and radar distances + - Vision lead standard deviation (xStd) and probability + +Outputs CSV and prints summary statistics showing the disagreement pattern. + +Usage: + python scripts/nap/vision_radar_delta.py [log_dir_or_file] + +Default: processes all .zst files in logs/crappy-radar/route-5/ +""" + +import sys +import csv +import struct +from pathlib import Path + +RADAR_TO_CAMERA = 1.52 # Same as radard.py + +def read_events(path): + """Read a .zst cereal log file and return list of parsed events.""" + import zstandard as zstd + + print(f" Reading {Path(path).name}...", end="", flush=True) + + dctx = zstd.ZstdDecompressor() + with open(path, 'rb') as f: + raw = dctx.decompress(f.read(), max_output_size=500 * 1024 * 1024) + + # Try cereal module first (faster) + try: + from cereal import log as cereal_log + events = list(cereal_log.Event.read_multiple_bytes(raw)) + print(f" {len(events)} events (cereal)", flush=True) + return events + except ImportError: + pass + + # Fallback: manual capnp parsing + import capnp + schema_paths = list(Path(__file__).resolve().parent.parent.parent.rglob('log.capnp')) + if not schema_paths: + print(" ERROR: Cannot find log.capnp schema", flush=True) + sys.exit(1) + capnp.remove_import_hook() + log_capnp = capnp.load(str(schema_paths[0]), + imports=[str(schema_paths[0].parent.parent / 'cereal'), + str(schema_paths[0].parent)]) + + # Parse raw capnp messages + msg_list = [] + pos = 0 + while pos < len(raw): + try: + if pos + 4 > len(raw): + break + n_segs = struct.unpack_from('<I', raw, pos)[0] + 1 + if n_segs > 10: + pos += 1 + continue + raw_header_size = 4 + 4 * n_segs + if raw_header_size % 8 != 0: + raw_header_size += 4 + if pos + raw_header_size > len(raw): + break + total_data = 0 + for s in range(n_segs): + seg_size = struct.unpack_from('<I', raw, pos + 4 + s * 4)[0] * 8 + total_data += seg_size + msg_end = pos + raw_header_size + total_data + if msg_end > len(raw): + break + msg_list.append(raw[pos:msg_end]) + pos = msg_end + except Exception: + pos += 1 + continue + + events = [] + for msg_bytes in msg_list: + try: + with log_capnp.Event.from_bytes(msg_bytes, traversal_limit_in_words=2**63 - 1) as event: + events.append(event) + except Exception: + continue + print(f" {len(events)} events (capnp)", flush=True) + return events + + +def extract_frames(events): + """Extract modelV2 and radarState data, paired by timestamp.""" + # Collect all modelV2 and radarState events + model_frames = {} # logMonoTime -> model data + radar_frames = [] # list of (logMonoTime, radar data, mdMonoTime) + car_state = {} # logMonoTime -> vEgo + + for event in events: + try: + which = event.which() + except Exception: + continue + mono = event.logMonoTime + + if which == 'modelV2': + mv = event.modelV2 + leads = mv.leadsV3 + if len(leads) > 0: + lead0 = leads[0] + x_vals = list(lead0.x) + xstd_vals = list(lead0.xStd) + v_vals = list(lead0.v) + model_frames[mono] = { + 'x0': x_vals[0] if x_vals else 0.0, + 'xStd0': xstd_vals[0] if xstd_vals else 0.0, + 'prob': float(lead0.prob), + 'v0': v_vals[0] if v_vals else 0.0, + } + + elif which == 'radarState': + rs = event.radarState + l1 = rs.leadOne + radar_frames.append((mono, { + 'dRel': float(l1.dRel), + 'yRel': float(l1.yRel), + 'vRel': float(l1.vRel), + 'vLead': float(l1.vLead), + 'vLeadK': float(l1.vLeadK), + 'aLeadK': float(l1.aLeadK), + 'status': bool(l1.status), + 'radar': bool(l1.radar), + 'radarTrackId': int(l1.radarTrackId), + 'modelProb': float(l1.modelProb), + }, int(rs.mdMonoTime))) + + elif which == 'carState': + car_state[mono] = float(event.carState.vEgo) + + return model_frames, radar_frames, car_state + + +def find_nearest_model(md_mono_time, model_frames): + """Find the model frame closest to the given mdMonoTime.""" + if md_mono_time in model_frames: + return model_frames[md_mono_time] + # Find nearest + best_t = None + best_dt = float('inf') + for t in model_frames: + dt = abs(t - md_mono_time) + if dt < best_dt: + best_dt = dt + best_t = t + if best_t is not None and best_dt < 1e9: # within 1 second + return model_frames[best_t] + return None + + +def find_nearest_vego(mono_time, car_state): + """Find vEgo closest to the given timestamp.""" + best_t = None + best_dt = float('inf') + for t in car_state: + dt = abs(t - mono_time) + if dt < best_dt: + best_dt = dt + best_t = t + if best_t is not None: + return car_state[best_t] + return 0.0 + + +def analyze(log_paths): + """Run the full analysis on a set of log files.""" + all_model_frames = {} + all_radar_frames = [] + all_car_state = {} + + for path in sorted(log_paths): + events = read_events(path) + mf, rf, cs = extract_frames(events) + all_model_frames.update(mf) + all_radar_frames.extend(rf) + all_car_state.update(cs) + + # Sort radar frames by time + all_radar_frames.sort(key=lambda x: x[0]) + + if not all_radar_frames: + print("No radarState events found in logs.") + return + + # Pair each radarState with its corresponding modelV2 + rows = [] + t0 = all_radar_frames[0][0] + + for mono_time, radar, md_mono in all_radar_frames: + t_sec = (mono_time - t0) * 1e-9 + model = find_nearest_model(md_mono, all_model_frames) + v_ego = find_nearest_vego(mono_time, all_car_state) + + if model is None: + continue + + vision_dist_cam = model['x0'] # distance from camera + vision_dist_radar = vision_dist_cam - RADAR_TO_CAMERA # distance from radar + radar_dist = radar['dRel'] + is_radar = radar['radar'] + has_status = radar['status'] + + if has_status: + delta = vision_dist_radar - radar_dist + else: + delta = 0.0 + + # Compute what dist_sane would be (25% original, 35% updated) + if vision_dist_radar > 0: + threshold_25 = max(vision_dist_radar * 0.25, 5.0) + threshold_35 = max(vision_dist_radar * 0.35, 8.0) + dist_sane_25 = abs(delta) < threshold_25 if is_radar or has_status else True + dist_sane_35 = abs(delta) < threshold_35 if is_radar or has_status else True + else: + threshold_25 = 5.0 + threshold_35 = 8.0 + dist_sane_25 = True + dist_sane_35 = True + + rows.append({ + 'time_s': f"{t_sec:.3f}", + 'v_ego_mps': f"{v_ego:.2f}", + 'vision_dist_cam': f"{vision_dist_cam:.2f}", + 'vision_dist_radar_frame': f"{vision_dist_radar:.2f}", + 'radar_dRel': f"{radar_dist:.2f}", + 'delta_m': f"{delta:.2f}", + 'abs_delta_m': f"{abs(delta):.2f}", + 'is_radar_matched': 1 if is_radar else 0, + 'lead_status': 1 if has_status else 0, + 'radar_track_id': radar['radarTrackId'], + 'vision_prob': f"{model['prob']:.3f}", + 'vision_xStd': f"{model['xStd0']:.2f}", + 'threshold_25pct': f"{threshold_25:.2f}", + 'threshold_35pct': f"{threshold_35:.2f}", + 'dist_sane_25': 1 if dist_sane_25 else 0, + 'dist_sane_35': 1 if dist_sane_35 else 0, + }) + + # Write CSV + csv_path = str(log_paths[0].parent / 'vision_radar_delta.csv') + with open(csv_path, 'w', newline='') as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + print(f"\nCSV written: {csv_path} ({len(rows)} rows)") + + # ----------------------------------------------------------------------- + # Summary statistics + # ----------------------------------------------------------------------- + print(f"\n{'='*70}") + print("VISION vs RADAR LEAD DISTANCE ANALYSIS") + print(f"{'='*70}") + + # Filter to frames with active lead + active = [r for r in rows if int(r['lead_status']) == 1] + radar_matched = [r for r in active if int(r['is_radar_matched']) == 1] + vision_only = [r for r in active if int(r['is_radar_matched']) == 0] + + print(f"\n Total frames: {len(rows)}") + print(f" Active lead frames: {len(active)}") + print(f" Radar-matched: {len(radar_matched)} ({100*len(radar_matched)/max(len(active),1):.1f}%)") + print(f" Vision-only: {len(vision_only)} ({100*len(vision_only)/max(len(active),1):.1f}%)") + + if active: + deltas = [float(r['delta_m']) for r in active] + abs_deltas = [abs(d) for d in deltas] + import statistics + print("\n Delta (vision - radar) statistics:") + print(f" Mean: {statistics.mean(deltas):+.2f} m") + print(f" Median: {statistics.median(deltas):+.2f} m") + print(f" Std dev: {statistics.stdev(deltas):.2f} m") + print(f" Min: {min(deltas):+.2f} m") + print(f" Max: {max(deltas):+.2f} m") + print(f" Abs mean: {statistics.mean(abs_deltas):.2f} m") + + # Percentiles + sorted_abs = sorted(abs_deltas) + p50 = sorted_abs[len(sorted_abs)//2] + p90 = sorted_abs[int(len(sorted_abs)*0.9)] + p95 = sorted_abs[int(len(sorted_abs)*0.95)] + p99 = sorted_abs[int(len(sorted_abs)*0.99)] + print(f" P50 abs delta: {p50:.2f} m") + print(f" P90 abs delta: {p90:.2f} m") + print(f" P95 abs delta: {p95:.2f} m") + print(f" P99 abs delta: {p99:.2f} m") + + # dist_sane failure analysis + if active: + fail_25 = [r for r in active if int(r['dist_sane_25']) == 0] + fail_35 = [r for r in active if int(r['dist_sane_35']) == 0] + print("\n dist_sane failure rate:") + print(f" At 25% threshold: {len(fail_25)}/{len(active)} ({100*len(fail_25)/len(active):.1f}%)") + print(f" At 35% threshold: {len(fail_35)}/{len(active)} ({100*len(fail_35)/len(active):.1f}%)") + + # Vision model noise analysis + if active: + xstds = [float(r['vision_xStd']) for r in active] + print("\n Vision model xStd (positional uncertainty):") + print(f" Mean: {statistics.mean(xstds):.2f} m") + print(f" Max: {max(xstds):.2f} m") + + # Radar-matched vs vision-only lead distance comparison + if radar_matched and vision_only: + rm_dists = [float(r['radar_dRel']) for r in radar_matched] + vo_dists = [float(r['radar_dRel']) for r in vision_only] + print("\n Lead distance by source:") + print(f" Radar-matched mean: {statistics.mean(rm_dists):.1f} m") + print(f" Vision-only mean: {statistics.mean(vo_dists):.1f} m") + + # Transition analysis: how often does it flip between radar and vision? + if len(active) > 1: + flips = 0 + for i in range(1, len(active)): + if int(active[i]['is_radar_matched']) != int(active[i-1]['is_radar_matched']): + flips += 1 + duration = float(active[-1]['time_s']) - float(active[0]['time_s']) + flip_rate = flips / max(duration, 0.1) + print("\n Radar/vision source flips:") + print(f" Total: {flips}") + print(f" Rate: {flip_rate:.2f}/s") + + # Delta by distance range (is the disagreement worse at range?) + if active: + ranges = [(0, 30, "0-30m"), (30, 60, "30-60m"), (60, 100, "60-100m"), (100, 300, "100m+")] + print("\n Delta by distance range:") + print(f" {'Range':<12} {'Count':>6} {'Mean delta':>12} {'Abs mean':>10} {'Std':>8}") + for lo, hi, label in ranges: + in_range = [r for r in active if lo <= float(r['vision_dist_radar_frame']) < hi] + if in_range: + d = [float(r['delta_m']) for r in in_range] + ad = [abs(x) for x in d] + std = statistics.stdev(d) if len(d) > 1 else 0 + print(f" {label:<12} {len(in_range):>6} {statistics.mean(d):>+12.2f} {statistics.mean(ad):>10.2f} {std:>8.2f}") + + # Check for consistent offset (sign of delta) + if active: + pos = sum(1 for r in active if float(r['delta_m']) > 0) + neg = sum(1 for r in active if float(r['delta_m']) < 0) + zero = sum(1 for r in active if float(r['delta_m']) == 0) + print("\n Delta sign distribution:") + print(f" Vision > Radar: {pos} ({100*pos/len(active):.1f}%)") + print(f" Vision < Radar: {neg} ({100*neg/len(active):.1f}%)") + print(f" Equal: {zero}") + + # Vision-only frames: what does the delta look like there? + # (delta is vision_dist - radarState.dRel; when vision-only, dRel IS the vision dist) + # So delta should be ~0 for vision-only frames. If not, there's a timing mismatch. + + # Frame-to-frame vision lead jitter + if len(active) > 1: + vdists = [float(r['vision_dist_cam']) for r in active] + jitter = [abs(vdists[i] - vdists[i-1]) for i in range(1, len(vdists))] + print("\n Vision lead frame-to-frame jitter:") + print(f" Mean: {statistics.mean(jitter):.2f} m") + print(f" Max: {max(jitter):.2f} m") + print(f" P90: {sorted(jitter)[int(len(jitter)*0.9)]:.2f} m") + print(f" P99: {sorted(jitter)[int(len(jitter)*0.99)]:.2f} m") + big_jitter = sum(1 for j in jitter if j > 5.0) + print(f" Frames with >5m jump: {big_jitter} ({100*big_jitter/len(jitter):.1f}%)") + + +def main(): + if len(sys.argv) > 1: + p = Path(sys.argv[1]) + if p.is_dir(): + log_paths = sorted(p.glob('*.zst')) + else: + log_paths = [p] + else: + log_dir = Path(__file__).resolve().parent.parent.parent / 'logs' / 'crappy-radar' / 'route-5' + log_paths = sorted(log_dir.glob('*.zst')) + + if not log_paths: + print("No .zst log files found.") + sys.exit(1) + + print("Vision vs Radar Lead Distance Analysis") + print(f"Processing {len(log_paths)} log files") + print(f"{'='*70}") + + analyze(log_paths) + + +if __name__ == '__main__': + main() diff --git a/scripts/pyqt_demo.py b/scripts/pyqt_demo.py deleted file mode 100755 index 783728bdb88e37..00000000000000 --- a/scripts/pyqt_demo.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python3 - -from PyQt5.QtWidgets import QApplication, QLabel -from openpilot.selfdrive.ui.qt.python_helpers import set_main_window - - -if __name__ == "__main__": - app = QApplication([]) - label = QLabel('Hello World!') - - # Set full screen and rotate - set_main_window(label) - - app.exec_() diff --git a/scripts/reporter.py b/scripts/reporter.py new file mode 100755 index 00000000000000..93b71761a9e421 --- /dev/null +++ b/scripts/reporter.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +import os +import glob + +from tinygrad.nn.onnx import OnnxPBParser + +BASEDIR = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../")) + +MASTER_PATH = os.getenv("MASTER_PATH", BASEDIR) +MODEL_PATH = "/selfdrive/modeld/models/" + + +class MetadataOnnxPBParser(OnnxPBParser): + def _parse_ModelProto(self) -> dict: + obj = {"metadata_props": []} + for fid, wire_type in self._parse_message(self.reader.len): + match fid: + case 14: + obj["metadata_props"].append(self._parse_StringStringEntryProto()) + case _: + self.reader.skip_field(wire_type) + return obj + + +def get_checkpoint(f): + model = MetadataOnnxPBParser(f).parse() + metadata = {prop["key"]: prop["value"] for prop in model["metadata_props"]} + return metadata['model_checkpoint'].split('/')[0] + + +if __name__ == "__main__": + print("| | master | PR branch |") + print("|-| ----- | --------- |") + + for f in glob.glob(BASEDIR + MODEL_PATH + "/*.onnx"): + fn = os.path.basename(f) + master = get_checkpoint(MASTER_PATH + MODEL_PATH + fn) + pr = get_checkpoint(BASEDIR + MODEL_PATH + fn) + print("|", fn, "|", f"[{master}](https://reporterv2.comma.life/{master})", "|", f"[{pr}](https://reporterv2.comma.life/{pr})", "|") diff --git a/scripts/usb.sh b/scripts/usb.sh new file mode 100755 index 00000000000000..5796cfa028b526 --- /dev/null +++ b/scripts/usb.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +# testing the GPU box + +export XDG_CACHE_HOME=/data/tinycache +mkdir -p $XDG_CACHE_HOME + +cd /data/openpilot/tinygrad_repo/examples +while true; do + AMD=1 AMD_IFACE=usb python ./beautiful_cartpole.py + sleep 1 +done diff --git a/scripts/usbgpu/benchmark.sh b/scripts/usbgpu/benchmark.sh new file mode 100755 index 00000000000000..04a76d054e7ab4 --- /dev/null +++ b/scripts/usbgpu/benchmark.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +cd $DIR/../../tinygrad_repo + +GREEN='\033[0;32m' +NC='\033[0m' + + +#export DEBUG=2 +export PYTHONPATH=. +export AM_RESET=1 +export AMD=1 +export AMD_IFACE=USB +export AMD_LLVM=1 + +python3 -m unittest -q --buffer test.test_tiny.TestTiny.test_plus \ + > /tmp/test_tiny.log 2>&1 || (cat /tmp/test_tiny.log; exit 1) +printf "${GREEN}Booted in ${SECONDS}s${NC}\n" +printf "${GREEN}=============${NC}\n" + +printf "\n\n" +printf "${GREEN}Transfer speeds:${NC}\n" +printf "${GREEN}================${NC}\n" +python3 test/external/external_test_usb_asm24.py TestDevCopySpeeds diff --git a/scripts/waste.py b/scripts/waste.py index 0764ff77c37cb6..bdee09d3f6b583 100755 --- a/scripts/waste.py +++ b/scripts/waste.py @@ -16,9 +16,9 @@ def waste(core): j = 0 while 1: if (i % 100) == 0: - setproctitle("%3d: %8d" % (core, i)) + setproctitle(f"{core:3d}: {i:8d}") lt = time.monotonic() - print("%3d: %8d %f %.2f" % (core, i, lt-st, j)) + print(f"{core:3d}: {i:8d} {lt-st:f} {j:.2f}") st = lt i += 1 j = np.sum(np.matmul(m1, m2)) diff --git a/selfdrive/SConscript b/selfdrive/SConscript deleted file mode 100644 index 0b49e69116f395..00000000000000 --- a/selfdrive/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -SConscript(['pandad/SConscript']) -SConscript(['controls/lib/lateral_mpc_lib/SConscript']) -SConscript(['controls/lib/longitudinal_mpc_lib/SConscript']) -SConscript(['locationd/SConscript']) -SConscript(['modeld/SConscript']) -SConscript(['ui/SConscript']) \ No newline at end of file diff --git a/selfdrive/assets/.gitignore b/selfdrive/assets/.gitignore index 1f90a2a93288ec..2d97f8b111f90c 100644 --- a/selfdrive/assets/.gitignore +++ b/selfdrive/assets/.gitignore @@ -1,2 +1,2 @@ -*.cc -translations_assets.qrc +fonts/*.fnt +fonts/*.png diff --git a/selfdrive/assets/assets.qrc b/selfdrive/assets/assets.qrc index 6d8d8df334ccc8..72e2f7f3c0bba4 100644 --- a/selfdrive/assets/assets.qrc +++ b/selfdrive/assets/assets.qrc @@ -1,19 +1,19 @@ <!DOCTYPE RCC><RCC version="1.0"> <qresource> - <file alias="bootstrap-icons.svg">../../third_party/bootstrap/bootstrap-icons.svg</file> - <file>img_continue_triangle.svg</file> - <file>img_circled_check.svg</file> - <file>img_circled_slash.svg</file> - <file>img_eye_open.svg</file> - <file>img_eye_closed.svg</file> + <file alias="bootstrap-icons.svg">@BOOTSTRAP_ICONS_SVG@</file> + <file>images/button_continue_triangle.svg</file> + <file>icons/circled_check.svg</file> + <file>icons/circled_slash.svg</file> + <file>icons/eye_open.svg</file> + <file>icons/eye_closed.svg</file> <file>icons/close.svg</file> - <file>offroad/icon_lock_closed.svg</file> - <file>offroad/icon_checkmark.svg</file> - <file>offroad/icon_warning.png</file> - <file>offroad/icon_wifi_strength_low.svg</file> - <file>offroad/icon_wifi_strength_medium.svg</file> - <file>offroad/icon_wifi_strength_high.svg</file> - <file>offroad/icon_wifi_strength_full.svg</file> + <file>icons/lock_closed.svg</file> + <file>icons/checkmark.svg</file> + <file>icons/warning.png</file> + <file>icons/wifi_strength_low.svg</file> + <file>icons/wifi_strength_medium.svg</file> + <file>icons/wifi_strength_high.svg</file> + <file>icons/wifi_strength_full.svg</file> <file alias="languages.json">../ui/translations/languages.json</file> </qresource> diff --git a/selfdrive/assets/fonts/NotoColorEmoji.ttf b/selfdrive/assets/fonts/NotoColorEmoji.ttf new file mode 100644 index 00000000000000..778e821ce35672 --- /dev/null +++ b/selfdrive/assets/fonts/NotoColorEmoji.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93cdc4ee9aa40e2afceecc63da0ca05ec7aab4bec991ece51a6b52389f48a477 +size 10788068 diff --git a/selfdrive/assets/fonts/process.py b/selfdrive/assets/fonts/process.py new file mode 100755 index 00000000000000..62ae6ec6843980 --- /dev/null +++ b/selfdrive/assets/fonts/process.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +from pathlib import Path +import json + +import pyray as rl + +FONT_DIR = Path(__file__).resolve().parent +SELFDRIVE_DIR = FONT_DIR.parents[1] +TRANSLATIONS_DIR = SELFDRIVE_DIR / "ui" / "translations" +LANGUAGES_FILE = TRANSLATIONS_DIR / "languages.json" + +GLYPH_PADDING = 6 +EXTRA_CHARS = "–‑✓×°§•X⚙✕◀▶✔⌫⇧␣○●↳çêüñ–‑✓×°§•€£¥" +UNIFONT_LANGUAGES = {"th", "zh-CHT", "zh-CHS", "ko", "ja"} + + +def _languages(): + if not LANGUAGES_FILE.exists(): + return {} + with LANGUAGES_FILE.open(encoding="utf-8") as f: + return json.load(f) + + +def _char_sets(): + base = set(map(chr, range(32, 127))) | set(EXTRA_CHARS) + unifont = set(base) + + for language, code in _languages().items(): + unifont.update(language) + po_path = TRANSLATIONS_DIR / f"app_{code}.po" + try: + chars = set(po_path.read_text(encoding="utf-8")) + except FileNotFoundError: + continue + (unifont if code in UNIFONT_LANGUAGES else base).update(chars) + + return tuple(sorted(ord(c) for c in base)), tuple(sorted(ord(c) for c in unifont)) + + +def _glyph_metrics(glyphs, rects, glyph_count: int): + entries = [] + min_offset_y, max_extent = None, 0 + for idx in range(glyph_count): + glyph = glyphs[idx] + rect = rects[idx] + width = int(round(rect.width)) + height = int(round(rect.height)) + offset_y = int(round(glyph.offsetY)) + min_offset_y = offset_y if min_offset_y is None else min(min_offset_y, offset_y) + max_extent = max(max_extent, offset_y + height) + entries.append({ + "id": glyph.value, + "x": int(round(rect.x)), + "y": int(round(rect.y)), + "width": width, + "height": height, + "xoffset": int(round(glyph.offsetX)), + "yoffset": offset_y, + "xadvance": int(round(glyph.advanceX)), + }) + + if min_offset_y is None: + raise RuntimeError("No glyphs were generated") + + line_height = int(round(max_extent - min_offset_y)) + base = int(round(max_extent)) + return entries, line_height, base + + +def _write_bmfont(path: Path, font_size: int, face: str, atlas_name: str, line_height: int, base: int, atlas_size, entries): + # TODO: why doesn't raylib calculate these metrics correctly? + if line_height != font_size: + print("using font size for line height", atlas_name) + line_height = font_size + lines = [ + f"info face=\"{face}\" size=-{font_size} bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=0 aa=1 padding=0,0,0,0 spacing=0,0 outline=0", + f"common lineHeight={line_height} base={base} scaleW={atlas_size[0]} scaleH={atlas_size[1]} pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4", + f"page id=0 file=\"{atlas_name}\"", + f"chars count={len(entries)}", + ] + for entry in entries: + lines.append( + ("char id={id:<4} x={x:<5} y={y:<5} width={width:<5} height={height:<5} " + + "xoffset={xoffset:<5} yoffset={yoffset:<5} xadvance={xadvance:<5} page=0 chnl=15").format(**entry) + ) + path.write_text("\n".join(lines) + "\n") + + +def _process_font(font_path: Path, codepoints: tuple[int, ...]): + print(f"Processing {font_path.name}...") + + font_size = { + "unifont.otf": 16, # unifont is only 16x8 or 16x16 pixels per glyph + }.get(font_path.name, 200) + + data = font_path.read_bytes() + file_buf = rl.ffi.new("unsigned char[]", data) + cp_buffer = rl.ffi.new("int[]", codepoints) + cp_ptr = rl.ffi.cast("int *", cp_buffer) + glyph_count = rl.ffi.new("int *", len(codepoints)) + glyphs = rl.load_font_data( + rl.ffi.cast("unsigned char *", file_buf), len(data), font_size, cp_ptr, len(codepoints), + rl.FontType.FONT_DEFAULT, glyph_count + ) + if glyphs == rl.ffi.NULL: + raise RuntimeError("raylib failed to load font data") + + rects_ptr = rl.ffi.new("Rectangle **") + image = rl.gen_image_font_atlas(glyphs, rects_ptr, glyph_count[0], font_size, GLYPH_PADDING, 0) + if image.width == 0 or image.height == 0: + raise RuntimeError("raylib returned an empty atlas") + + rects = rects_ptr[0] + atlas_name = f"{font_path.stem}.png" + atlas_path = FONT_DIR / atlas_name + entries, line_height, base = _glyph_metrics(glyphs, rects, glyph_count[0]) + + if not rl.export_image(image, atlas_path.as_posix()): + raise RuntimeError("Failed to export atlas image") + + _write_bmfont(FONT_DIR / f"{font_path.stem}.fnt", font_size, font_path.stem, atlas_name, line_height, base, (image.width, image.height), entries) + + +def main(): + base_cp, unifont_cp = _char_sets() + fonts = sorted(FONT_DIR.glob("*.ttf")) + sorted(FONT_DIR.glob("*.otf")) + for font in fonts: + if "emoji" in font.name.lower(): + continue + glyphs = unifont_cp if font.stem.lower().startswith("unifont") else base_cp + _process_font(font, glyphs) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/selfdrive/assets/fonts/unifont.otf b/selfdrive/assets/fonts/unifont.otf new file mode 100644 index 00000000000000..b85597b1f4c3e3 --- /dev/null +++ b/selfdrive/assets/fonts/unifont.otf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9712a9bc089af7ddc06e0826aa84f2ee23ed2f1a1dddaf2a89c2483e753a8475 +size 5321484 diff --git a/selfdrive/assets/icons/arrow-right.png b/selfdrive/assets/icons/arrow-right.png new file mode 100644 index 00000000000000..b275134f648bd8 --- /dev/null +++ b/selfdrive/assets/icons/arrow-right.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a999d5f3e616eeafc310689accdd26efb90769596604a62c460ef8acece18bc +size 1734 diff --git a/selfdrive/assets/icons/backspace.png b/selfdrive/assets/icons/backspace.png new file mode 100644 index 00000000000000..16686be6f54fd0 --- /dev/null +++ b/selfdrive/assets/icons/backspace.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:576da562df8eb513e64ccb614ec727b257cbca8b5507974d01efc0f64c5382c2 +size 6267 diff --git a/selfdrive/assets/offroad/icon_calibration.png b/selfdrive/assets/icons/calibration.png similarity index 100% rename from selfdrive/assets/offroad/icon_calibration.png rename to selfdrive/assets/icons/calibration.png diff --git a/selfdrive/assets/icons/capslock-fill.png b/selfdrive/assets/icons/capslock-fill.png new file mode 100644 index 00000000000000..66854e78f228bd --- /dev/null +++ b/selfdrive/assets/icons/capslock-fill.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6872a1047f1a534a037be7b1367640fe1bfb205a6e1c50420a2d1a946cda78ed +size 4397 diff --git a/selfdrive/assets/icons/checkmark.png b/selfdrive/assets/icons/checkmark.png new file mode 100644 index 00000000000000..0f9a802a35b5b2 --- /dev/null +++ b/selfdrive/assets/icons/checkmark.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc472f0e575e314c4006cb6e9845fb9fb9a13cf08fe74fbe1593dee53c20d977 +size 4329 diff --git a/selfdrive/assets/icons/checkmark.svg b/selfdrive/assets/icons/checkmark.svg new file mode 100644 index 00000000000000..26480698cd3721 --- /dev/null +++ b/selfdrive/assets/icons/checkmark.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17a135c18634647a73734300f5d0ad98082b07779b5553e72b99686857380ee7 +size 244 diff --git a/selfdrive/assets/offroad/icon_chevron_right.png b/selfdrive/assets/icons/chevron_right.png similarity index 100% rename from selfdrive/assets/offroad/icon_chevron_right.png rename to selfdrive/assets/icons/chevron_right.png diff --git a/selfdrive/assets/img_chffr_wheel.png b/selfdrive/assets/icons/chffr_wheel.png similarity index 100% rename from selfdrive/assets/img_chffr_wheel.png rename to selfdrive/assets/icons/chffr_wheel.png diff --git a/selfdrive/assets/icons/circled_check.png b/selfdrive/assets/icons/circled_check.png new file mode 100644 index 00000000000000..7611bc821f4730 --- /dev/null +++ b/selfdrive/assets/icons/circled_check.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdb0be280ac3a78bf95f5b92fafe94de5084ecc06836459c3a9fe1912a5b2454 +size 10479 diff --git a/selfdrive/assets/icons/circled_check.svg b/selfdrive/assets/icons/circled_check.svg new file mode 100644 index 00000000000000..aab06ec1e0f6f0 --- /dev/null +++ b/selfdrive/assets/icons/circled_check.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c88458f6326265965626cbc97c2219bd513b15a6468b08f80b43ef014b7904b +size 372 diff --git a/selfdrive/assets/icons/circled_slash.png b/selfdrive/assets/icons/circled_slash.png new file mode 100644 index 00000000000000..74a9b342f67f41 --- /dev/null +++ b/selfdrive/assets/icons/circled_slash.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2a992a83eaa87762e12dc226f36af48e1cdbfc3b83ef75b6a2fc4103e3697a0 +size 9120 diff --git a/selfdrive/assets/icons/circled_slash.svg b/selfdrive/assets/icons/circled_slash.svg new file mode 100644 index 00000000000000..89c6e2b1aed8a2 --- /dev/null +++ b/selfdrive/assets/icons/circled_slash.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d91c86028af58cbe2770799d0fe7e55d143f9b3f67fdebcb47d328d6e410285 +size 223 diff --git a/selfdrive/assets/icons/close.png b/selfdrive/assets/icons/close.png new file mode 100644 index 00000000000000..66d15456321663 --- /dev/null +++ b/selfdrive/assets/icons/close.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c11f831c17080a8ffaa8469cf91a079a4abfb72e5238afe02b92bceb3442db0 +size 2656 diff --git a/selfdrive/assets/icons/close.svg b/selfdrive/assets/icons/close.svg index 33f68f02bca29e..e6db01321a82e7 100644 --- a/selfdrive/assets/icons/close.svg +++ b/selfdrive/assets/icons/close.svg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:84c6b23bd3245954b86f80278511186fca4ddfa70d87c8b25e8f9fb76f9af758 -size 379 +oid sha256:a28a4dcaba33d800d109cc5f9a810065203d3bfccd104b2e503f6fe3fc5b6f91 +size 250 diff --git a/selfdrive/assets/icons/close2.png b/selfdrive/assets/icons/close2.png new file mode 100644 index 00000000000000..4497c97547daf3 --- /dev/null +++ b/selfdrive/assets/icons/close2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbfed12ddb5731b7b568539fe59f382356b46fdd146a9e0a1b768d3e5efd0378 +size 4350 diff --git a/selfdrive/assets/icons/close2.svg b/selfdrive/assets/icons/close2.svg new file mode 100644 index 00000000000000..56a36cecd58bd2 --- /dev/null +++ b/selfdrive/assets/icons/close2.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d2a7cd3913ab97a386e946969f6a684895adf5d641c38dfd8f5efa0197a6c58 +size 513 diff --git a/selfdrive/assets/icons/couch.png b/selfdrive/assets/icons/couch.png new file mode 100644 index 00000000000000..677ad0f9eef6dc --- /dev/null +++ b/selfdrive/assets/icons/couch.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:911f59f248015600da7ecc689398103d47dfc57f6be17ac8c8e543a726a6c64b +size 3311 diff --git a/selfdrive/assets/icons/couch.svg b/selfdrive/assets/icons/couch.svg new file mode 100644 index 00000000000000..f56970f289774b --- /dev/null +++ b/selfdrive/assets/icons/couch.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd5d8d3fce5e30662797f7eeed224f5775b2cabcc055f01f5ebf6e7b2657b616 +size 1801 diff --git a/selfdrive/assets/icons/disengage_on_accelerator.png b/selfdrive/assets/icons/disengage_on_accelerator.png new file mode 100644 index 00000000000000..41348344489c01 --- /dev/null +++ b/selfdrive/assets/icons/disengage_on_accelerator.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f23fabbf60fff6ef88ba6f27f2775b1ae6be172a994e41267983a9ec0f984bfc +size 15059 diff --git a/selfdrive/assets/icons/disengage_on_accelerator.svg b/selfdrive/assets/icons/disengage_on_accelerator.svg new file mode 100644 index 00000000000000..eef5181935f586 --- /dev/null +++ b/selfdrive/assets/icons/disengage_on_accelerator.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:baac01efc894527c8234b774c89cc57b69460d60ad81691a6d50ce0904c60ba7 +size 3638 diff --git a/selfdrive/assets/img_driver_face.png b/selfdrive/assets/icons/driver_face.png similarity index 100% rename from selfdrive/assets/img_driver_face.png rename to selfdrive/assets/icons/driver_face.png diff --git a/selfdrive/assets/icons/experimental.png b/selfdrive/assets/icons/experimental.png new file mode 100644 index 00000000000000..2332fe11d05acc --- /dev/null +++ b/selfdrive/assets/icons/experimental.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e58deb1778cf2826339f27e9f09eecc79ea137c1436210c14b71c352a649c77 +size 34953 diff --git a/selfdrive/assets/icons/experimental.svg b/selfdrive/assets/icons/experimental.svg new file mode 100644 index 00000000000000..8a97cdeac101b9 --- /dev/null +++ b/selfdrive/assets/icons/experimental.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7ab989c9fe22e7d2119bac5284cdccfba2889477d69f5f6c6b4470c7ee0aab3 +size 1801 diff --git a/selfdrive/assets/icons/experimental_grey.png b/selfdrive/assets/icons/experimental_grey.png new file mode 100644 index 00000000000000..058c3e135811ff --- /dev/null +++ b/selfdrive/assets/icons/experimental_grey.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f37a02dd914405c6f86f415700dd5985eb976b923e7abd6580d2da76533594e +size 9466 diff --git a/selfdrive/assets/icons/experimental_grey.svg b/selfdrive/assets/icons/experimental_grey.svg new file mode 100644 index 00000000000000..25ab33f388b234 --- /dev/null +++ b/selfdrive/assets/icons/experimental_grey.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90d441310f8e1833c661d8a4f0546aab2eb50eb21cc21beb0aff0d27b5ee6066 +size 1571 diff --git a/selfdrive/assets/icons/experimental_white.png b/selfdrive/assets/icons/experimental_white.png new file mode 100644 index 00000000000000..6a9cfc44078bfa --- /dev/null +++ b/selfdrive/assets/icons/experimental_white.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b2dad33fead9f064c3a548651d6ef37daf82b6127c329683f538ec6e986ecbc +size 11204 diff --git a/selfdrive/assets/icons/experimental_white.svg b/selfdrive/assets/icons/experimental_white.svg new file mode 100644 index 00000000000000..51d76989478380 --- /dev/null +++ b/selfdrive/assets/icons/experimental_white.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82648254da89edb0cf65ef63fc5e6e0741414051bfea8a40449132fd61b1ed0f +size 1533 diff --git a/selfdrive/assets/icons/eye_closed.png b/selfdrive/assets/icons/eye_closed.png new file mode 100644 index 00000000000000..8eba02e6008874 --- /dev/null +++ b/selfdrive/assets/icons/eye_closed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64d9dc106172d3a54088ef51a27a48145154ca040c43ecbc8d626fa42e38886e +size 9352 diff --git a/selfdrive/assets/icons/eye_closed.svg b/selfdrive/assets/icons/eye_closed.svg new file mode 100644 index 00000000000000..a9cb9251864263 --- /dev/null +++ b/selfdrive/assets/icons/eye_closed.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fcb0db3b77d6057b94544b6d91b6078fbd91b8f2de189322b90feae3d1ac29da +size 1054 diff --git a/selfdrive/assets/icons/eye_open.png b/selfdrive/assets/icons/eye_open.png new file mode 100644 index 00000000000000..9783716ff3476b --- /dev/null +++ b/selfdrive/assets/icons/eye_open.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94246db66e774cbaee618931f76ecc38ecb72eca097d1e6c20a8dec2a5f8cd29 +size 7087 diff --git a/selfdrive/assets/icons/eye_open.svg b/selfdrive/assets/icons/eye_open.svg new file mode 100644 index 00000000000000..2befa13adb1f0f --- /dev/null +++ b/selfdrive/assets/icons/eye_open.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:411774f4a80831833a344e58932c23a6ebd1db73a6327a63259deca2c6f53613 +size 597 diff --git a/selfdrive/assets/icons/eyes_crossed.png b/selfdrive/assets/icons/eyes_crossed.png new file mode 100644 index 00000000000000..af2122cd9ac2dd --- /dev/null +++ b/selfdrive/assets/icons/eyes_crossed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4def42b5faffc6a8f747c210d24c3a1a8a7f82891738ff7f3317091e63326ba5 +size 1083 diff --git a/selfdrive/assets/icons/eyes_open.png b/selfdrive/assets/icons/eyes_open.png new file mode 100644 index 00000000000000..ad9afc3a3e01b0 --- /dev/null +++ b/selfdrive/assets/icons/eyes_open.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52019b72834e478588114584820313af866d2d7a737591a166c413ccaab6acf5 +size 931 diff --git a/selfdrive/assets/icons/link.png b/selfdrive/assets/icons/link.png new file mode 100644 index 00000000000000..8a795c05b8fa7b --- /dev/null +++ b/selfdrive/assets/icons/link.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a69514fe68dd1b4c73f28771640dcba10fc40989d1c7e771cb48bfd830fef206 +size 5713 diff --git a/selfdrive/assets/icons/lock_closed.png b/selfdrive/assets/icons/lock_closed.png new file mode 100644 index 00000000000000..21e67957374fda --- /dev/null +++ b/selfdrive/assets/icons/lock_closed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b89b8803bb610515aef051c93b833dc62f8c847558873cfd50a0b240c968449 +size 4911 diff --git a/selfdrive/assets/icons/lock_closed.svg b/selfdrive/assets/icons/lock_closed.svg new file mode 100644 index 00000000000000..22a510d1c2c210 --- /dev/null +++ b/selfdrive/assets/icons/lock_closed.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64e8fc90b79c725a8bf5bbc99643989ae885570997092762e216738805649ade +size 492 diff --git a/selfdrive/assets/offroad/icon_menu.png b/selfdrive/assets/icons/menu.png similarity index 100% rename from selfdrive/assets/offroad/icon_menu.png rename to selfdrive/assets/icons/menu.png diff --git a/selfdrive/assets/offroad/icon_metric.png b/selfdrive/assets/icons/metric.png similarity index 100% rename from selfdrive/assets/offroad/icon_metric.png rename to selfdrive/assets/icons/metric.png diff --git a/selfdrive/assets/icons/microphone.png b/selfdrive/assets/icons/microphone.png new file mode 100644 index 00000000000000..6cb9cc02543757 --- /dev/null +++ b/selfdrive/assets/icons/microphone.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9fc1f7f31d41f26ea7d6f52b3096f7a91844a3b897bc233a8489253c46f0403b +size 6324 diff --git a/selfdrive/assets/offroad/icon_minus.png b/selfdrive/assets/icons/minus.png similarity index 100% rename from selfdrive/assets/offroad/icon_minus.png rename to selfdrive/assets/icons/minus.png diff --git a/selfdrive/assets/offroad/icon_monitoring.png b/selfdrive/assets/icons/monitoring.png similarity index 100% rename from selfdrive/assets/offroad/icon_monitoring.png rename to selfdrive/assets/icons/monitoring.png diff --git a/selfdrive/assets/offroad/icon_network.png b/selfdrive/assets/icons/network.png similarity index 100% rename from selfdrive/assets/offroad/icon_network.png rename to selfdrive/assets/icons/network.png diff --git a/selfdrive/assets/offroad/icon_road.png b/selfdrive/assets/icons/road.png similarity index 100% rename from selfdrive/assets/offroad/icon_road.png rename to selfdrive/assets/icons/road.png diff --git a/selfdrive/assets/offroad/icon_settings.png b/selfdrive/assets/icons/settings.png similarity index 100% rename from selfdrive/assets/offroad/icon_settings.png rename to selfdrive/assets/icons/settings.png diff --git a/selfdrive/assets/offroad/icon_shell.png b/selfdrive/assets/icons/shell.png similarity index 100% rename from selfdrive/assets/offroad/icon_shell.png rename to selfdrive/assets/icons/shell.png diff --git a/selfdrive/assets/icons/shift-fill.png b/selfdrive/assets/icons/shift-fill.png new file mode 100644 index 00000000000000..1ce02d58225e9c --- /dev/null +++ b/selfdrive/assets/icons/shift-fill.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e625ca991746abaaac375b095aa9a586601982232f4aae0fc2b17b2a524e9ce9 +size 3946 diff --git a/selfdrive/assets/icons/shift.png b/selfdrive/assets/icons/shift.png new file mode 100644 index 00000000000000..de2a68b482c3ae --- /dev/null +++ b/selfdrive/assets/icons/shift.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a93dd816bd0600ad47d10ebe530326bfa725dc31e4d5e1ee275f39b10f17a59d +size 4931 diff --git a/selfdrive/assets/offroad/icon_speed_limit.png b/selfdrive/assets/icons/speed_limit.png similarity index 100% rename from selfdrive/assets/offroad/icon_speed_limit.png rename to selfdrive/assets/icons/speed_limit.png diff --git a/selfdrive/assets/icons/triangle.png b/selfdrive/assets/icons/triangle.png new file mode 100644 index 00000000000000..47ff24f200305b --- /dev/null +++ b/selfdrive/assets/icons/triangle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f2745ce89c926e507888ea7c6df1884aab045887048cf0d813407396a2e6b18 +size 5894 diff --git a/selfdrive/assets/icons/triangle.svg b/selfdrive/assets/icons/triangle.svg new file mode 100644 index 00000000000000..233eb5e979a701 --- /dev/null +++ b/selfdrive/assets/icons/triangle.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a83c9a78673429caf16d02917be4c8afedadff17b6ceb8c248703ad1120116ed +size 394 diff --git a/selfdrive/assets/offroad/icon_warning.png b/selfdrive/assets/icons/warning.png similarity index 100% rename from selfdrive/assets/offroad/icon_warning.png rename to selfdrive/assets/icons/warning.png diff --git a/selfdrive/assets/icons/wifi_strength_full.png b/selfdrive/assets/icons/wifi_strength_full.png new file mode 100644 index 00000000000000..1a710f29676de8 --- /dev/null +++ b/selfdrive/assets/icons/wifi_strength_full.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b7f0971cf612b905ccb338e40921932773538517fc9f0f7a4a847ad596287a9 +size 7171 diff --git a/selfdrive/assets/icons/wifi_strength_full.svg b/selfdrive/assets/icons/wifi_strength_full.svg new file mode 100644 index 00000000000000..4137d3cd4c1d6a --- /dev/null +++ b/selfdrive/assets/icons/wifi_strength_full.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c16c005d666dea64ba6f85de50dfcf161353176eca3d9f475677cbc04fd0382 +size 1161 diff --git a/selfdrive/assets/icons/wifi_strength_high.png b/selfdrive/assets/icons/wifi_strength_high.png new file mode 100644 index 00000000000000..2d360968b630a1 --- /dev/null +++ b/selfdrive/assets/icons/wifi_strength_high.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2afacf302bcdc3f5e0d2f734508e8fea6f803813098d52fa6b878c765ba7a58 +size 9360 diff --git a/selfdrive/assets/icons/wifi_strength_high.svg b/selfdrive/assets/icons/wifi_strength_high.svg new file mode 100644 index 00000000000000..17d721fe31d4a3 --- /dev/null +++ b/selfdrive/assets/icons/wifi_strength_high.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f207b9a1f4ab6009e261f03edd1d05a9d485217415664cba0253d32381e3a03 +size 1164 diff --git a/selfdrive/assets/icons/wifi_strength_low.png b/selfdrive/assets/icons/wifi_strength_low.png new file mode 100644 index 00000000000000..d0165283043bb5 --- /dev/null +++ b/selfdrive/assets/icons/wifi_strength_low.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7dfe50815c76d459dc104ce4a5e4b5dfd882e11b65e07706cacd336e69e788f4 +size 9756 diff --git a/selfdrive/assets/icons/wifi_strength_low.svg b/selfdrive/assets/icons/wifi_strength_low.svg new file mode 100644 index 00000000000000..4088866370cc88 --- /dev/null +++ b/selfdrive/assets/icons/wifi_strength_low.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6835937483e5a539618a94e3ec8fad661ae2f7afb39c958e6c8b007b8f4b9b2c +size 1198 diff --git a/selfdrive/assets/icons/wifi_strength_medium.png b/selfdrive/assets/icons/wifi_strength_medium.png new file mode 100644 index 00000000000000..9c943543a4500d --- /dev/null +++ b/selfdrive/assets/icons/wifi_strength_medium.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:304ab97ac9724a7a133a36c2d14da9fe8ab660c9a29abb99cc0a4828f94d8801 +size 9627 diff --git a/selfdrive/assets/icons/wifi_strength_medium.svg b/selfdrive/assets/icons/wifi_strength_medium.svg new file mode 100644 index 00000000000000..f0c029dedd64e2 --- /dev/null +++ b/selfdrive/assets/icons/wifi_strength_medium.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ebb1fb5539d9f8ea9899acf4f9cb359503dbe22cd38a3461ad43936348475b9 +size 1167 diff --git a/selfdrive/assets/icons/wifi_uploading.png b/selfdrive/assets/icons/wifi_uploading.png new file mode 100644 index 00000000000000..19d9bf36ce167f --- /dev/null +++ b/selfdrive/assets/icons/wifi_uploading.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8eac201013322db1580649a253da7ae38eb9f16f6089234e769b746951e874ee +size 7171 diff --git a/selfdrive/assets/icons/wifi_uploading.svg b/selfdrive/assets/icons/wifi_uploading.svg new file mode 100644 index 00000000000000..07a14a59f4c6b0 --- /dev/null +++ b/selfdrive/assets/icons/wifi_uploading.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7cfefbda22b53f7eb72a25893ab41c00dabea49f690cafb1d224375a669e608 +size 1170 diff --git a/selfdrive/assets/icons_mici/adb_short.png b/selfdrive/assets/icons_mici/adb_short.png new file mode 100644 index 00000000000000..c49226c858a755 --- /dev/null +++ b/selfdrive/assets/icons_mici/adb_short.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:263598da73c577c01cebd31ae78f45969ef8b335be1a5f55d54a696bb2982c0a +size 2062 diff --git a/selfdrive/assets/icons_mici/alerts_bell.png b/selfdrive/assets/icons_mici/alerts_bell.png new file mode 100644 index 00000000000000..5d775425ebfe7c --- /dev/null +++ b/selfdrive/assets/icons_mici/alerts_bell.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ce1d357acadd798939b398cce1761ceb05564b44f2a5bc6865c7842e60e79f2 +size 1474 diff --git a/selfdrive/assets/icons_mici/alerts_pill.png b/selfdrive/assets/icons_mici/alerts_pill.png new file mode 100644 index 00000000000000..29ab2ad5b3fa50 --- /dev/null +++ b/selfdrive/assets/icons_mici/alerts_pill.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3fe73cd1a24c05346a9b4a02e4f900a314c83a422beb38b0f88f91389582cd4 +size 3960 diff --git a/selfdrive/assets/icons_mici/body.png b/selfdrive/assets/icons_mici/body.png new file mode 100644 index 00000000000000..2f7bb779d18e07 --- /dev/null +++ b/selfdrive/assets/icons_mici/body.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b45f88128430fb50ef51c8e08b8e2a1c8fbe0b5c3a08de9f5d9d59bc1edc82e +size 4545 diff --git a/selfdrive/assets/icons_mici/buttons/button_circle.png b/selfdrive/assets/icons_mici/buttons/button_circle.png new file mode 100644 index 00000000000000..b6f4cc9d12b0fd --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/button_circle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f92e5f0b7fc50c3b64bd18ecee8a8d518017b5461104de76dee6feb0f4f0d70d +size 7496 diff --git a/selfdrive/assets/icons_mici/buttons/button_circle_disabled.png b/selfdrive/assets/icons_mici/buttons/button_circle_disabled.png new file mode 100644 index 00000000000000..d2104df4e1c891 --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/button_circle_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:947aa3beb7eff6afb44101daf0aeaae7b7f31961c273df00eec0ca8359233c56 +size 5175 diff --git a/selfdrive/assets/icons_mici/buttons/button_circle_pressed.png b/selfdrive/assets/icons_mici/buttons/button_circle_pressed.png new file mode 100644 index 00000000000000..9db0c2cd811ca9 --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/button_circle_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70d4236bcfd3aa8f100b81179c1e0f193c6ffbd84769c4a516be4381e62b270a +size 18666 diff --git a/selfdrive/assets/icons_mici/buttons/button_circle_red.png b/selfdrive/assets/icons_mici/buttons/button_circle_red.png new file mode 100644 index 00000000000000..68ae400b1eb4ec --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/button_circle_red.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b48d8a191979f27dae8a336f99d944008e2536f698c58cffa5f3dddc17429b45 +size 11451 diff --git a/selfdrive/assets/icons_mici/buttons/button_circle_red_pressed.png b/selfdrive/assets/icons_mici/buttons/button_circle_red_pressed.png new file mode 100644 index 00000000000000..e61a678c1c34a0 --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/button_circle_red_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed07f72339cf1c3926a2cb7314f9baa099bcdb3f8bc89a9084661b71334b0526 +size 32599 diff --git a/selfdrive/assets/icons_mici/buttons/button_rectangle.png b/selfdrive/assets/icons_mici/buttons/button_rectangle.png new file mode 100644 index 00000000000000..4ccf6995b193e5 --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/button_rectangle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5dedb4139a7ddeafcdaf050144769e490643820db726201a15250e1042eb6d15 +size 7982 diff --git a/selfdrive/assets/icons_mici/buttons/button_rectangle_disabled.png b/selfdrive/assets/icons_mici/buttons/button_rectangle_disabled.png new file mode 100644 index 00000000000000..5e891588f5f22e --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/button_rectangle_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d527dcff61fa66902681706b4916586244b8cf0520086ac980ff782ab2d99ce7 +size 4778 diff --git a/selfdrive/assets/icons_mici/buttons/button_rectangle_pressed.png b/selfdrive/assets/icons_mici/buttons/button_rectangle_pressed.png new file mode 100644 index 00000000000000..2cbf1cedb87ea7 --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/button_rectangle_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6b1b0f1270a596b5ac150dee8ade54794de55b2033a529d4a17176f688aa6f0 +size 56738 diff --git a/selfdrive/assets/icons_mici/buttons/slider_bg.png b/selfdrive/assets/icons_mici/buttons/slider_bg.png new file mode 100644 index 00000000000000..9164f74bad14b9 --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/slider_bg.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ca620a05e9e69351b9bbcfcf021dae11fde26be50d7f1a39257d319f6303616 +size 9779 diff --git a/selfdrive/assets/icons_mici/buttons/toggle_dot_disabled.png b/selfdrive/assets/icons_mici/buttons/toggle_dot_disabled.png new file mode 100644 index 00000000000000..1ff4db45a55f8a --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/toggle_dot_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89ac033d879beeb0a7fa1919838e0ec64b1a625a4aafc14f7b990c607a79b676 +size 2220 diff --git a/selfdrive/assets/icons_mici/buttons/toggle_dot_enabled.png b/selfdrive/assets/icons_mici/buttons/toggle_dot_enabled.png new file mode 100644 index 00000000000000..5bb4d778f8132d --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/toggle_dot_enabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:532bf0e8535e3f9bc13af13029a27d6c14ae788d52224b6c65623334f62fada0 +size 6048 diff --git a/selfdrive/assets/icons_mici/buttons/toggle_pill_disabled.png b/selfdrive/assets/icons_mici/buttons/toggle_pill_disabled.png new file mode 100644 index 00000000000000..555c16e095f71d --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/toggle_pill_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7891a628bd9cedc1097114e89fcec4a50a88021c7d6c63f1329d087be9e1783e +size 3065 diff --git a/selfdrive/assets/icons_mici/buttons/toggle_pill_enabled.png b/selfdrive/assets/icons_mici/buttons/toggle_pill_enabled.png new file mode 100644 index 00000000000000..d95039da9282fc --- /dev/null +++ b/selfdrive/assets/icons_mici/buttons/toggle_pill_enabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad31da78544edd18d0ac154670f22d1cd1ac57f50576002f04701d22c59502a8 +size 8257 diff --git a/selfdrive/assets/icons_mici/egpu.png b/selfdrive/assets/icons_mici/egpu.png new file mode 100644 index 00000000000000..dc2bc8e276fcd8 --- /dev/null +++ b/selfdrive/assets/icons_mici/egpu.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec3dcf64cbc34251d8423cb8b3b31d743e93d14002dec43c389a857cb7e8eb17 +size 10875 diff --git a/selfdrive/assets/icons_mici/egpu_gray.png b/selfdrive/assets/icons_mici/egpu_gray.png new file mode 100644 index 00000000000000..a6aeb846891219 --- /dev/null +++ b/selfdrive/assets/icons_mici/egpu_gray.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7409c53d7c72681c24982fd83b56ce70f80797c9c0f936d9296a5c18557ac472 +size 7279 diff --git a/selfdrive/assets/icons_mici/exclamation_point.png b/selfdrive/assets/icons_mici/exclamation_point.png new file mode 100644 index 00000000000000..ede3b638bc3615 --- /dev/null +++ b/selfdrive/assets/icons_mici/exclamation_point.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:254b7f753b70c964847b686f0f71af751f2f49beea6ede4aeb333fe06062a257 +size 2289 diff --git a/selfdrive/assets/icons_mici/experimental_mode.png b/selfdrive/assets/icons_mici/experimental_mode.png new file mode 100644 index 00000000000000..75850d08f51f04 --- /dev/null +++ b/selfdrive/assets/icons_mici/experimental_mode.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01841b602632c66ab14a8e52b874a1623f09641dc2ef0620f4e2d00bb4a913f3 +size 16243 diff --git a/selfdrive/assets/icons_mici/microphone.png b/selfdrive/assets/icons_mici/microphone.png new file mode 100644 index 00000000000000..9af8f2f455290d --- /dev/null +++ b/selfdrive/assets/icons_mici/microphone.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:744dbaa68ee74e300cd46439bad79449c860e1c5c027304b0f382bd5383fba77 +size 6817 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/big_alert.png b/selfdrive/assets/icons_mici/offroad_alerts/big_alert.png new file mode 100644 index 00000000000000..142367d0e68eae --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/big_alert.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aeee7f049879caff52320fab5f286cf3fd6a52c820cd8e150ff242e53a14176f +size 14774 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/big_alert_pressed.png b/selfdrive/assets/icons_mici/offroad_alerts/big_alert_pressed.png new file mode 100644 index 00000000000000..2ff01024d9f6df --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/big_alert_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b59ddada9c9e0e7972ead27396ebe6c10fd2352687b18ff6b476f61f74d80bf +size 46106 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/green_wheel.png b/selfdrive/assets/icons_mici/offroad_alerts/green_wheel.png new file mode 100644 index 00000000000000..08181ca35f47c8 --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/green_wheel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b11ee84d48972a2499cb29f01594d77a1a39692f6424a315a3f83262bc16087 +size 13481 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/medium_alert.png b/selfdrive/assets/icons_mici/offroad_alerts/medium_alert.png new file mode 100644 index 00000000000000..91a7b43c5a6890 --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/medium_alert.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46d08a8a08b42d466ff45d8ad6d2578e345dcbb1c06c126ad361873d9d35eaec +size 12877 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/medium_alert_pressed.png b/selfdrive/assets/icons_mici/offroad_alerts/medium_alert_pressed.png new file mode 100644 index 00000000000000..09ca2d08d5eb0e --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/medium_alert_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42ea275e5fe0a8a0e2fddb5a4a8487806fb22850115ea3646ee8f213d5fd6bb6 +size 37202 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/orange_warning.png b/selfdrive/assets/icons_mici/offroad_alerts/orange_warning.png new file mode 100644 index 00000000000000..52e6836d4b4804 --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/orange_warning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d548405a65ba4d4590c55866612dc6aa0e78d9278fc864ef60fe3e463edf4a68 +size 12169 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/red_warning.png b/selfdrive/assets/icons_mici/offroad_alerts/red_warning.png new file mode 100644 index 00000000000000..df608d3518b747 --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/red_warning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6fc63326d34fbe72f6daf104d101ce19e547dbfe134427c067c957a7179df74 +size 12124 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/small_alert.png b/selfdrive/assets/icons_mici/offroad_alerts/small_alert.png new file mode 100644 index 00000000000000..0a50b6a1ca94ee --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/small_alert.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfbf38672a893fd1d8fadf942354d2511e2436814a9af0e5c188cbb427fc6c70 +size 12281 diff --git a/selfdrive/assets/icons_mici/offroad_alerts/small_alert_pressed.png b/selfdrive/assets/icons_mici/offroad_alerts/small_alert_pressed.png new file mode 100644 index 00000000000000..865355ef01f57a --- /dev/null +++ b/selfdrive/assets/icons_mici/offroad_alerts/small_alert_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7102850bcfb075a285041cecb546559374a905403ab3b9814fa6097d2d822dd +size 34680 diff --git a/selfdrive/assets/icons_mici/onroad/blind_spot_left.png b/selfdrive/assets/icons_mici/onroad/blind_spot_left.png new file mode 100644 index 00000000000000..fdc189b858274f --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/blind_spot_left.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77b20a8c478d982412d556afb3a035b80b4aa9fe7a86aea761af4a42147d9435 +size 45297 diff --git a/selfdrive/assets/icons_mici/onroad/bookmark.png b/selfdrive/assets/icons_mici/onroad/bookmark.png new file mode 100644 index 00000000000000..305561f509c5b7 --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/bookmark.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd91685bf656e828648acf035a4737acb2c4709e8514cf0aa0a10fa470a9bb60 +size 11580 diff --git a/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_background.png b/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_background.png new file mode 100644 index 00000000000000..4129b13d922c90 --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_background.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb89d9f11cf44992f92142aa5ad84e1ac700a2601aff2abab373e2a822af149e +size 11678 diff --git a/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_cone.png b/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_cone.png new file mode 100644 index 00000000000000..6974b6d8e237e8 --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_cone.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f5d4b7bd406114945e53f4d56089102ee83ba7d0a4590a371f7acab90c7ad53 +size 1862 diff --git a/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_person.png b/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_person.png new file mode 100644 index 00000000000000..5b917f3a4a8442 --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_person.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2772c6a9fe9c57099d347ad49f0cb7c906593f1fdf0e6dde96d104baf0200b0 +size 1365 diff --git a/selfdrive/assets/icons_mici/onroad/eye_fill.png b/selfdrive/assets/icons_mici/onroad/eye_fill.png new file mode 100644 index 00000000000000..78758a9809caf0 --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/eye_fill.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07310879d093108435c0011846ae1184966db86443bc6e7ca036a6fa6123700b +size 4983 diff --git a/selfdrive/assets/icons_mici/onroad/eye_orange.png b/selfdrive/assets/icons_mici/onroad/eye_orange.png new file mode 100644 index 00000000000000..932c71260b446b --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/eye_orange.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7be447e56d649e0362ef650494b484e140a01ead31799ce43b266f5781c918d2 +size 36473 diff --git a/selfdrive/assets/icons_mici/onroad/glasses.png b/selfdrive/assets/icons_mici/onroad/glasses.png new file mode 100644 index 00000000000000..006972fd397c41 --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/glasses.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56de402482b5987ed9a0ff3f793a1c89f857304b34fbb8a3deb5b5d4a332be1c +size 3688 diff --git a/selfdrive/assets/icons_mici/onroad/onroad_fade.png b/selfdrive/assets/icons_mici/onroad/onroad_fade.png new file mode 100644 index 00000000000000..3f823061b9b8ec --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/onroad_fade.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2aa6d04ba038f15a92868de6e6c7b04f624b4fe89d03bc3e9c4cd44cb729b24e +size 38317 diff --git a/selfdrive/assets/icons_mici/onroad/turn_signal_left.png b/selfdrive/assets/icons_mici/onroad/turn_signal_left.png new file mode 100644 index 00000000000000..97b5cf1443f2cf --- /dev/null +++ b/selfdrive/assets/icons_mici/onroad/turn_signal_left.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9f7d0554c0c79ab605c1119ffdef0a4f55196e53b75a65b6ac5218911e24a02 +size 45701 diff --git a/selfdrive/assets/icons_mici/settings.png b/selfdrive/assets/icons_mici/settings.png new file mode 100644 index 00000000000000..4ba7df9fdf65f5 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14b457d2dc19d8658f525cc6989c9cfcf0edaf695b18767514242acbdbe2a6dd +size 2198 diff --git a/selfdrive/assets/icons_mici/settings/comma_icon.png b/selfdrive/assets/icons_mici/settings/comma_icon.png new file mode 100644 index 00000000000000..dd38a8938f6440 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/comma_icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ad4ee47ec6470f788a026f95ed86bf344f64f9cf3186c9c78927233d2694a1d +size 1388 diff --git a/selfdrive/assets/icons_mici/settings/developer/ssh.png b/selfdrive/assets/icons_mici/settings/developer/ssh.png new file mode 100644 index 00000000000000..0f17d04eca8fd2 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/developer/ssh.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b26133bee089627202d5e89a4e939ad23aaceb5d8e26d7381b1aea3ef892f2ee +size 2620 diff --git a/selfdrive/assets/icons_mici/settings/developer_icon.png b/selfdrive/assets/icons_mici/settings/developer_icon.png new file mode 100644 index 00000000000000..f9d553c7c30f6d --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/developer_icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebb4f7ad9fd2f9fb3c69a38fbc00cbe690809b0ff202ffd4768ae5b699acc035 +size 1759 diff --git a/selfdrive/assets/icons_mici/settings/device/cameras.png b/selfdrive/assets/icons_mici/settings/device/cameras.png new file mode 100644 index 00000000000000..ae9a88c4dc8d0a --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/cameras.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f47e636025e044977f278a35546e0fc971f48fd53c2eeafd3508e95c35f378f +size 3117 diff --git a/selfdrive/assets/icons_mici/settings/device/fcc_logo.png b/selfdrive/assets/icons_mici/settings/device/fcc_logo.png new file mode 100644 index 00000000000000..f29b24fd099208 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/fcc_logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cac8546d19e75a9edcbc0721a887fd74c8a3c41bfe19e36186b2b2bcabdae98 +size 1817 diff --git a/selfdrive/assets/icons_mici/settings/device/info.png b/selfdrive/assets/icons_mici/settings/device/info.png new file mode 100644 index 00000000000000..9a29c46d0d2c35 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/info.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66858a5d3302333485fa391f7a9bb3a9b1ab4ae881e7fb47b04c3a4507011c94 +size 2613 diff --git a/selfdrive/assets/icons_mici/settings/device/lkas.png b/selfdrive/assets/icons_mici/settings/device/lkas.png new file mode 100644 index 00000000000000..80d37d4d5c1a4a --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/lkas.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a05a41e66c7a24d461a4bbcdab0979031e5900e1db270af52ca363f0bed521f5 +size 2028 diff --git a/selfdrive/assets/icons_mici/settings/device/pair.png b/selfdrive/assets/icons_mici/settings/device/pair.png new file mode 100644 index 00000000000000..807d44335dcc67 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/pair.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:678483230831d0a7d3dcad5f067a7b641e5d2ae0db477665dfc6c53a675eba18 +size 1779 diff --git a/selfdrive/assets/icons_mici/settings/device/power.png b/selfdrive/assets/icons_mici/settings/device/power.png new file mode 100644 index 00000000000000..711f1a4ab9b997 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/power.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a34885e79f42d19b7777dd07e7ab51df344880cb770c48e0baaddb177c2ae938 +size 2228 diff --git a/selfdrive/assets/icons_mici/settings/device/reboot.png b/selfdrive/assets/icons_mici/settings/device/reboot.png new file mode 100644 index 00000000000000..298a85c5041d86 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/reboot.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1356fe3ddda14568e9be1dca4e16ca9048852e3a27a3f531cd58d7d368485a82 +size 2362 diff --git a/selfdrive/assets/icons_mici/settings/device/uninstall.png b/selfdrive/assets/icons_mici/settings/device/uninstall.png new file mode 100644 index 00000000000000..53f8bc0e7d30cb --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/uninstall.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50a8ce4fa8ff7f5b0f56ba0dc65b4802dc0be2dc0967b5cb3a15e3b79a4e513e +size 2424 diff --git a/selfdrive/assets/icons_mici/settings/device/up_to_date.png b/selfdrive/assets/icons_mici/settings/device/up_to_date.png new file mode 100644 index 00000000000000..e09f7d33085d99 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/up_to_date.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61bc44b6e0f99640434d6abcb64880c7bf575eda5cdcf7d74cba7d73307dd39a +size 2739 diff --git a/selfdrive/assets/icons_mici/settings/device/update.png b/selfdrive/assets/icons_mici/settings/device/update.png new file mode 100644 index 00000000000000..498c066191a021 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device/update.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f28cdeaba9146521335bc11ad60a8e0368eb0ed1381e88b35a12a6138ba22ed6 +size 2409 diff --git a/selfdrive/assets/icons_mici/settings/device_icon.png b/selfdrive/assets/icons_mici/settings/device_icon.png new file mode 100644 index 00000000000000..6a716e4dfde507 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/device_icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2273629450aa870f0964dd285721c35d3d313fb8b4684122215a65844ae744d0 +size 1888 diff --git a/selfdrive/assets/icons_mici/settings/firehose.png b/selfdrive/assets/icons_mici/settings/firehose.png new file mode 100644 index 00000000000000..37451c0482c186 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/firehose.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:416656861380981acc114e5285b448d6e4dc42b98539d0ba16821cbc3db89208 +size 1364 diff --git a/selfdrive/assets/icons_mici/settings/horizontal_scroll_indicator.png b/selfdrive/assets/icons_mici/settings/horizontal_scroll_indicator.png new file mode 100644 index 00000000000000..39dd7b194773e8 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/horizontal_scroll_indicator.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af8d5ecb6468442361462aa838a2d234b1256b8139418be8ef2962e4350cfbef +size 2176 diff --git a/selfdrive/assets/icons_mici/settings/keyboard/backspace.png b/selfdrive/assets/icons_mici/settings/keyboard/backspace.png new file mode 100644 index 00000000000000..53ff00c2ae7ff9 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/keyboard/backspace.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69bb4a401429c3fdf473778f751288b2aafea27eb13f09b20e83d55212f084ba +size 1963 diff --git a/selfdrive/assets/icons_mici/settings/keyboard/caps_lock.png b/selfdrive/assets/icons_mici/settings/keyboard/caps_lock.png new file mode 100644 index 00000000000000..2d173bfc9fa5b8 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/keyboard/caps_lock.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:563c211fd98018e24418235602e596f3a481f04fddde0a14590e563474fcffd2 +size 1423 diff --git a/selfdrive/assets/icons_mici/settings/keyboard/caps_lower.png b/selfdrive/assets/icons_mici/settings/keyboard/caps_lower.png new file mode 100644 index 00000000000000..a3ce71f04924c0 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/keyboard/caps_lower.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f81811ea9cdc409d5549035ca928c76e22396193e1cefb6cacab3747ee0c297 +size 1142 diff --git a/selfdrive/assets/icons_mici/settings/keyboard/caps_upper.png b/selfdrive/assets/icons_mici/settings/keyboard/caps_upper.png new file mode 100644 index 00000000000000..7c147bc07bb05e --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/keyboard/caps_upper.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60875e73dd9659122c9248d8e99d5cfd301d68dabeec2cb42cebce812c9baae9 +size 1102 diff --git a/selfdrive/assets/icons_mici/settings/keyboard/enter.png b/selfdrive/assets/icons_mici/settings/keyboard/enter.png new file mode 100644 index 00000000000000..0b7fc95c510e84 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/keyboard/enter.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dd956d5ccfce01a01bea74ef59c9e73dfca406a5ff9ac62417203afa6027fba +size 5620 diff --git a/selfdrive/assets/icons_mici/settings/keyboard/enter_disabled.png b/selfdrive/assets/icons_mici/settings/keyboard/enter_disabled.png new file mode 100644 index 00000000000000..251d5d8d14027d --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/keyboard/enter_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1dd1c2308872729d58adab390030ae9c987dc7908f0c39391651ea2b6cb620c5 +size 2445 diff --git a/selfdrive/assets/icons_mici/settings/keyboard/keyboard_background.png b/selfdrive/assets/icons_mici/settings/keyboard/keyboard_background.png new file mode 100644 index 00000000000000..8c2c068d4131cf --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/keyboard/keyboard_background.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:399e7ff9dea6710244827c91014f1a08d8ae989dce922928d6b7f7504b15ba79 +size 11321 diff --git a/selfdrive/assets/icons_mici/settings/keyboard/space.png b/selfdrive/assets/icons_mici/settings/keyboard/space.png new file mode 100644 index 00000000000000..3d61109721b5ea --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/keyboard/space.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f431e428772991323ee3ce662479e1ab29c3d80a72b93cf9c9673716ba245d5f +size 654 diff --git a/selfdrive/assets/icons_mici/settings/network/cell_strength_full.png b/selfdrive/assets/icons_mici/settings/network/cell_strength_full.png new file mode 100644 index 00000000000000..13f70386d44fa3 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/cell_strength_full.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb7af523411c5ed75c6e1418dfc2a379486f6dbd7f2f1c281d3ff54e1ea7810e +size 777 diff --git a/selfdrive/assets/icons_mici/settings/network/cell_strength_high.png b/selfdrive/assets/icons_mici/settings/network/cell_strength_high.png new file mode 100644 index 00000000000000..1fea6d23b809b5 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/cell_strength_high.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db86e176e016458fcff00d40e37636a808977e0cc01bcc9c04b31a1001562de8 +size 936 diff --git a/selfdrive/assets/icons_mici/settings/network/cell_strength_low.png b/selfdrive/assets/icons_mici/settings/network/cell_strength_low.png new file mode 100644 index 00000000000000..d763f86c7fa313 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/cell_strength_low.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cd0b3a00db36ee7eacf5887d07d40e5351fb441d98643a02df4c742cd1e935d +size 945 diff --git a/selfdrive/assets/icons_mici/settings/network/cell_strength_medium.png b/selfdrive/assets/icons_mici/settings/network/cell_strength_medium.png new file mode 100644 index 00000000000000..148ee63e990d17 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/cell_strength_medium.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25724acfe0c261070b103ef5933053d5dd8b726ece42d0e5f715f05c67be2294 +size 956 diff --git a/selfdrive/assets/icons_mici/settings/network/cell_strength_none.png b/selfdrive/assets/icons_mici/settings/network/cell_strength_none.png new file mode 100644 index 00000000000000..c6d82ac316eb8f --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/cell_strength_none.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb0aeb6260bcd0642204f842112479f4b19b350db9addae5e14c9c5131bcf956 +size 781 diff --git a/selfdrive/assets/icons_mici/settings/network/new/forget_button.png b/selfdrive/assets/icons_mici/settings/network/new/forget_button.png new file mode 100644 index 00000000000000..541433be763012 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/new/forget_button.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ccb5f2298389ae36df87de84d85440ee5a82c50e803c9bd362c9b89ea45aa69 +size 6611 diff --git a/selfdrive/assets/icons_mici/settings/network/new/forget_button_pressed.png b/selfdrive/assets/icons_mici/settings/network/new/forget_button_pressed.png new file mode 100644 index 00000000000000..26cc8b4fca6d6b --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/new/forget_button_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9f17c82b2f349d107d27c69418f054be1f1753f970c7d3d3520c1e65de00511 +size 12894 diff --git a/selfdrive/assets/icons_mici/settings/network/new/lock.png b/selfdrive/assets/icons_mici/settings/network/new/lock.png new file mode 100644 index 00000000000000..65bd71f6543c2f --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/new/lock.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7488c1aa69b728387b2cf300a614cc64e3c2305d2b509c14cf44cad65d20d85c +size 2509 diff --git a/selfdrive/assets/icons_mici/settings/network/new/trash.png b/selfdrive/assets/icons_mici/settings/network/new/trash.png new file mode 100644 index 00000000000000..81e5f13e43a663 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/new/trash.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9074162bf0469fc5ab0b5711a121289a983c887161df269ac120edd8fd024499 +size 1533 diff --git a/selfdrive/assets/icons_mici/settings/network/tethering.png b/selfdrive/assets/icons_mici/settings/network/tethering.png new file mode 100644 index 00000000000000..4bb416b0b105d8 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/tethering.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1e322ea6e57b05b3515fcd4e9100f890e6ff80607c11360b7927fa5a9765beb +size 2752 diff --git a/selfdrive/assets/icons_mici/settings/network/wifi_strength_full.png b/selfdrive/assets/icons_mici/settings/network/wifi_strength_full.png new file mode 100644 index 00000000000000..fe81ffa572076d --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/wifi_strength_full.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73c76e5240bdff64c1d1ed0ac2bb9c3fadb2fd61fbf8dc710b812757af8bcf6c +size 2026 diff --git a/selfdrive/assets/icons_mici/settings/network/wifi_strength_low.png b/selfdrive/assets/icons_mici/settings/network/wifi_strength_low.png new file mode 100644 index 00000000000000..2649cc89dce40e --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/wifi_strength_low.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e66cc6174a54177793c42ef3525a9aa1592e05b0abb677442c7226269d1371a5 +size 2196 diff --git a/selfdrive/assets/icons_mici/settings/network/wifi_strength_medium.png b/selfdrive/assets/icons_mici/settings/network/wifi_strength_medium.png new file mode 100644 index 00000000000000..8881833375319c --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/wifi_strength_medium.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7948a9234f2bc996aefb3a9e58a37c06ebbf54e8e4596e47800f78ef7e81961f +size 2231 diff --git a/selfdrive/assets/icons_mici/settings/network/wifi_strength_none.png b/selfdrive/assets/icons_mici/settings/network/wifi_strength_none.png new file mode 100644 index 00000000000000..848d7849a23c10 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/wifi_strength_none.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a57ea402448dacc2026631174e448b6254698fe92309221576400cbf28196936 +size 2195 diff --git a/selfdrive/assets/icons_mici/settings/network/wifi_strength_slash.png b/selfdrive/assets/icons_mici/settings/network/wifi_strength_slash.png new file mode 100644 index 00000000000000..4457a3fcd27908 --- /dev/null +++ b/selfdrive/assets/icons_mici/settings/network/wifi_strength_slash.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e6d166bdbbcdc106e7cd4a44ba85848888f18a6ef34e86daac8e12a3f519443 +size 2318 diff --git a/selfdrive/assets/icons_mici/setup/cancel.png b/selfdrive/assets/icons_mici/setup/cancel.png new file mode 100644 index 00000000000000..f50cc9ef3fe6ac --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/cancel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6892bd4d9b14b587fa491a6d608562e38819b4c618b1d7a3e8c384f05d52a2b +size 1245 diff --git a/selfdrive/assets/icons_mici/setup/continue.png b/selfdrive/assets/icons_mici/setup/continue.png new file mode 100644 index 00000000000000..7a67bb0c9603e7 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/continue.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3428d8fcf2ecf9542c524706124f82b7fc809453c63418c9234ac9df5d85bd24 +size 10074 diff --git a/selfdrive/assets/icons_mici/setup/continue_disabled.png b/selfdrive/assets/icons_mici/setup/continue_disabled.png new file mode 100644 index 00000000000000..8a2bcc2ffee17f --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/continue_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2810add4943dd4f20a984ed6011b520925919a58d5c0dd0d846fc4d7f8a1d02 +size 7109 diff --git a/selfdrive/assets/icons_mici/setup/continue_pressed.png b/selfdrive/assets/icons_mici/setup/continue_pressed.png new file mode 100644 index 00000000000000..3eaee7bf1c92c8 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/continue_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a3a87454a3d2f1ebb327211062c52480de945673dcfd137c5da3df8fa98d731 +size 22400 diff --git a/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_check.png b/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_check.png new file mode 100644 index 00000000000000..dfb9799b0b8535 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_check.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2290105f9b055b3c3d482d883d148de3418cad07b653133b0f61137e1976c407 +size 1412 diff --git a/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_question.png b/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_question.png new file mode 100644 index 00000000000000..fa29be1827ffec --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_question.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec9691d2572e2e084f0b3c99a1dcd0daadf5040d16c02347ffec9dd5466c061a +size 1438 diff --git a/selfdrive/assets/icons_mici/setup/factory_reset.png b/selfdrive/assets/icons_mici/setup/factory_reset.png new file mode 100644 index 00000000000000..bcb3ea92cb1290 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/factory_reset.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:122a614d1aa26187507951f932160eebfddfebcb4293e78f8d23e350fc97bc0f +size 11489 diff --git a/selfdrive/assets/icons_mici/setup/green_dm.png b/selfdrive/assets/icons_mici/setup/green_dm.png new file mode 100644 index 00000000000000..87f4ffe78850e6 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/green_dm.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b6d7747dd6bbf47d9782fc0d847c224b933f6616218ade1f9220018aa9d6acc +size 15052 diff --git a/selfdrive/assets/icons_mici/setup/green_info.png b/selfdrive/assets/icons_mici/setup/green_info.png new file mode 100644 index 00000000000000..57e005abd67620 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/green_info.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5055bc385a1de674e6f3cbafdb611ee4b1088de2a3c357bce76f6a192226c952 +size 14154 diff --git a/selfdrive/assets/icons_mici/setup/orange_dm.png b/selfdrive/assets/icons_mici/setup/orange_dm.png new file mode 100644 index 00000000000000..97df767a987215 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/orange_dm.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c45ab0b949c1c71651f9f48cf6ff10196d64eb85e042b063e92b1d7ca02dcb5 +size 13155 diff --git a/selfdrive/assets/icons_mici/setup/red_warning.png b/selfdrive/assets/icons_mici/setup/red_warning.png new file mode 100644 index 00000000000000..387794cf13a9a8 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/red_warning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8e8bc3c15df7512a81b902e47fb069eff1370c833095d3b25f3866efb815fff +size 11123 diff --git a/selfdrive/assets/icons_mici/setup/reset_failed.png b/selfdrive/assets/icons_mici/setup/reset_failed.png new file mode 100644 index 00000000000000..680df97cbcdd83 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/reset_failed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d5b8f76e5f47e77e5af3016ebdbe548ad3bc9af83a1111b3214bf4017c95a28 +size 11792 diff --git a/selfdrive/assets/icons_mici/setup/restore.png b/selfdrive/assets/icons_mici/setup/restore.png new file mode 100644 index 00000000000000..5c62086f64fda7 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/restore.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63c1499106621a4d927c21b2b04c87235a927216d9f513a0205f0fe03b8c799b +size 12320 diff --git a/selfdrive/assets/icons_mici/setup/small_button.png b/selfdrive/assets/icons_mici/setup/small_button.png new file mode 100644 index 00000000000000..1ee01aeac2f0f1 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_button.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13919cf5df3137fdffdb8cc53a1215f13bf478a780ca8614234b7af0cdc0e766 +size 5409 diff --git a/selfdrive/assets/icons_mici/setup/small_button_disabled.png b/selfdrive/assets/icons_mici/setup/small_button_disabled.png new file mode 100644 index 00000000000000..da8bb3eefd78ce --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_button_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ed258d8e0531c19705953ded065c6d5e14929728a2909d8d4e335898fa5d080 +size 4056 diff --git a/selfdrive/assets/icons_mici/setup/small_button_pressed.png b/selfdrive/assets/icons_mici/setup/small_button_pressed.png new file mode 100644 index 00000000000000..6e30f47fba4cb8 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_button_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c032fd71ccfebe161827de420771e7927fe1ed799e615e24d458cfd79fead7f7 +size 7875 diff --git a/selfdrive/assets/icons_mici/setup/small_slider/slider_arrow.png b/selfdrive/assets/icons_mici/setup/small_slider/slider_arrow.png new file mode 100644 index 00000000000000..acf5b174147742 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_slider/slider_arrow.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75a6557935075a646b17d083202832daafb263d4cfa38aea2af407afc04e2ef4 +size 1312 diff --git a/selfdrive/assets/icons_mici/setup/small_slider/slider_bg_larger.png b/selfdrive/assets/icons_mici/setup/small_slider/slider_bg_larger.png new file mode 100644 index 00000000000000..11c3ae2d3f2678 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_slider/slider_bg_larger.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:950d55fd7294fb05c10ba9944537c02637776497c159e1b7d145c73f0f9d3253 +size 7119 diff --git a/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle.png b/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle.png new file mode 100644 index 00000000000000..683587a060c8a4 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61281d3e3ef5ac5a8fe75405a93c2096bf235f090b27832e986444e3fb85715e +size 7427 diff --git a/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle_pressed.png b/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle_pressed.png new file mode 100644 index 00000000000000..470bfc50c0b3b3 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1dd642ae4708cc7a837e8ef8b4c75f578654d241f8c854249c2b1ade640ceca +size 14058 diff --git a/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle.png b/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle.png new file mode 100644 index 00000000000000..88e6985f12603c --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ba98ab2b75f0c1f8fdffb9eab0a742645b80ef4ca404c007f374a5e0fd48d8c +size 10254 diff --git a/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle_pressed.png b/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle_pressed.png new file mode 100644 index 00000000000000..999cdafcc78d5e --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4545fdbaf67402b28b18644a7353a0620250ece6416c1b0ce0e27c758817b042 +size 26729 diff --git a/selfdrive/assets/icons_mici/setup/start_button.png b/selfdrive/assets/icons_mici/setup/start_button.png new file mode 100644 index 00000000000000..58d8a8b7488ff0 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/start_button.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e993247160edcbc9c3cba3efa93169028568d484bcfd0bf64f3e3a7ec7556c0 +size 18608 diff --git a/selfdrive/assets/icons_mici/setup/start_button_pressed.png b/selfdrive/assets/icons_mici/setup/start_button_pressed.png new file mode 100644 index 00000000000000..564de0bef78b81 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/start_button_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c4f1002ecde9a2b33779c2e784a39b492b4c8d76abc063e935ce0aa971925dd +size 65513 diff --git a/selfdrive/assets/icons_mici/setup/warning.png b/selfdrive/assets/icons_mici/setup/warning.png new file mode 100644 index 00000000000000..1b7839f47f6777 --- /dev/null +++ b/selfdrive/assets/icons_mici/setup/warning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7584d32ac0231381e38646fdac2f71b4517905ef22024f01bd9e124d3918f33a +size 9194 diff --git a/selfdrive/assets/icons_mici/ssh_short.png b/selfdrive/assets/icons_mici/ssh_short.png new file mode 100644 index 00000000000000..699ddd72e8fb90 --- /dev/null +++ b/selfdrive/assets/icons_mici/ssh_short.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef1735e6effcb625ea618fa35a6b908b28ca483d5997e15241d48e2d3d29819e +size 1433 diff --git a/selfdrive/assets/icons_mici/turn_intent_left.png b/selfdrive/assets/icons_mici/turn_intent_left.png new file mode 100644 index 00000000000000..3934200c9d9c7f --- /dev/null +++ b/selfdrive/assets/icons_mici/turn_intent_left.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:001cb8227eaaff5367055395d9b3ccd5822f9a47276091832d8ad28b074d77c9 +size 914 diff --git a/selfdrive/assets/icons_mici/wheel.png b/selfdrive/assets/icons_mici/wheel.png new file mode 100644 index 00000000000000..a43bcb3b9933f2 --- /dev/null +++ b/selfdrive/assets/icons_mici/wheel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8cf9c6361ed82551eb99e028e0a75ff56b72ca856ccf7c9a76afe6745434980a +size 2720 diff --git a/selfdrive/assets/icons_mici/wheel_critical.png b/selfdrive/assets/icons_mici/wheel_critical.png new file mode 100644 index 00000000000000..676b0b4d7108c9 --- /dev/null +++ b/selfdrive/assets/icons_mici/wheel_critical.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c3d9082b295f9e5ddef93f8d4e9cb961ea2374c7affd26394bbccb26e7137b2 +size 11023 diff --git a/selfdrive/assets/images/button_continue_triangle.png b/selfdrive/assets/images/button_continue_triangle.png new file mode 100644 index 00000000000000..c56e1120945770 --- /dev/null +++ b/selfdrive/assets/images/button_continue_triangle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9218e02c42b0f80858477255e24a97da4cf0b2898fc76f3806409d65b104668 +size 4510 diff --git a/selfdrive/assets/images/button_continue_triangle.svg b/selfdrive/assets/images/button_continue_triangle.svg new file mode 100644 index 00000000000000..e6d362927cd8a9 --- /dev/null +++ b/selfdrive/assets/images/button_continue_triangle.svg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8084e5a8bbc16956a98b010092ae1c4e32b3391b0551fa1cd65cb1e2bb59d3df +size 169 diff --git a/selfdrive/assets/images/spinner_comma.png b/selfdrive/assets/images/spinner_comma.png new file mode 100644 index 00000000000000..ac6b2d4e1faa58 Binary files /dev/null and b/selfdrive/assets/images/spinner_comma.png differ diff --git a/selfdrive/assets/img_spinner_track.png b/selfdrive/assets/images/spinner_track.png similarity index 100% rename from selfdrive/assets/img_spinner_track.png rename to selfdrive/assets/images/spinner_track.png diff --git a/selfdrive/assets/images/triangle.svg b/selfdrive/assets/images/triangle.svg deleted file mode 100644 index f3a8db44b767c4..00000000000000 --- a/selfdrive/assets/images/triangle.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:aaf9a1967365f2c641bf7b54a409e32842cee0bfded7ebb01b1a95c4ac9f0154 -size 2163 diff --git a/selfdrive/assets/img_circled_check.svg b/selfdrive/assets/img_circled_check.svg deleted file mode 100644 index 1852ba947afd95..00000000000000 --- a/selfdrive/assets/img_circled_check.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c5687faf4cb22bece0405893671651eb13e8eda393987610f493ee5e05eac61d -size 439 diff --git a/selfdrive/assets/img_circled_slash.svg b/selfdrive/assets/img_circled_slash.svg deleted file mode 100644 index 6c77030d15ec60..00000000000000 --- a/selfdrive/assets/img_circled_slash.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fbec38447732a443c304042c3c3d362c94e11e794e7cc7dc86aa1c7bba16c6b6 -size 328 diff --git a/selfdrive/assets/img_continue_triangle.svg b/selfdrive/assets/img_continue_triangle.svg deleted file mode 100644 index ee9db369a40c00..00000000000000 --- a/selfdrive/assets/img_continue_triangle.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1764c0c93703481b2ced63bc35c5a23a6c12388ca690ce4cf577b3b478a08b69 -size 197 diff --git a/selfdrive/assets/img_couch.svg b/selfdrive/assets/img_couch.svg deleted file mode 100644 index 7c58515200d270..00000000000000 --- a/selfdrive/assets/img_couch.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a428d2561198ebdc853ba6fb25a8b9c5a58064d000413694e1535adc06633c0a -size 2649 diff --git a/selfdrive/assets/img_driver_face_static.png b/selfdrive/assets/img_driver_face_static.png deleted file mode 100644 index 5d5ebf67955106..00000000000000 --- a/selfdrive/assets/img_driver_face_static.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f7565541b4e6213221174839b9b2b67397ced0b9807ea56413989fd37325b3b6 -size 4908 diff --git a/selfdrive/assets/img_experimental.svg b/selfdrive/assets/img_experimental.svg deleted file mode 100644 index 3c31caa07ec640..00000000000000 --- a/selfdrive/assets/img_experimental.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c26afadff128244567a7cf98f1c998f97056b19209301ff7fc8851eb807fb748 -size 2193 diff --git a/selfdrive/assets/img_experimental_grey.svg b/selfdrive/assets/img_experimental_grey.svg deleted file mode 100644 index 8ba6c87bd59246..00000000000000 --- a/selfdrive/assets/img_experimental_grey.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5ae28a53171567c8a0d52eec75cc49004cb8dd19dcab9a360784718ab8ec7c02 -size 1931 diff --git a/selfdrive/assets/img_experimental_white.svg b/selfdrive/assets/img_experimental_white.svg deleted file mode 100644 index 9714fe0c013046..00000000000000 --- a/selfdrive/assets/img_experimental_white.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:99be696be983700d7eb1768bd1c840198a4eb9525b71e28efea49f13c358e519 -size 1891 diff --git a/selfdrive/assets/img_eye_closed.svg b/selfdrive/assets/img_eye_closed.svg deleted file mode 100644 index fcef6e8a3cf6c5..00000000000000 --- a/selfdrive/assets/img_eye_closed.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8e0e5b451ed2e426fea99da24a9df6552be7048205b9aa7b89e46eeb89f6d08e -size 1490 diff --git a/selfdrive/assets/img_eye_open.svg b/selfdrive/assets/img_eye_open.svg deleted file mode 100644 index 7289c4a5710733..00000000000000 --- a/selfdrive/assets/img_eye_open.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:23935f9e2ddba8dafd4a5d0217f29783260a0832c9b0d3e6a2ef66d4529b91d2 -size 775 diff --git a/selfdrive/assets/img_spinner_comma.png b/selfdrive/assets/img_spinner_comma.png deleted file mode 100644 index 81f2fb38c4da46..00000000000000 --- a/selfdrive/assets/img_spinner_comma.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:78d140abe572b00765a7ece46bd990cff1287c2e8705a5f551b74461ab307b6b -size 15713 diff --git a/selfdrive/assets/offroad/fcc.html b/selfdrive/assets/offroad/fcc.html index 793bea533c61ef..960a7a06cb2ced 100644 --- a/selfdrive/assets/offroad/fcc.html +++ b/selfdrive/assets/offroad/fcc.html @@ -12,11 +12,10 @@ <h5>Thundersoft TurboX D845 SOM</h5> <h5>Quectel/EG25-G</h5> <p>FCC ID: XMR201903EG25G</p> - <p> - This device complies with Part 15 of the FCC Rules. - Operation is subject to the following two conditions: + <p>This device complies with Part 15 of the FCC Rules.</p> + <p>Operation is subject to the following two conditions:</p> - <p>(1) this device may not cause harmful interference, and + <p>(1) this device may not cause harmful interference, and</p> <p>(2) this device must accept any interference received, including interference that may cause undesired operation.</p> The following test reports are subject to this declaration: diff --git a/selfdrive/assets/offroad/icon_checkmark.svg b/selfdrive/assets/offroad/icon_checkmark.svg deleted file mode 100644 index 7a1db134977297..00000000000000 --- a/selfdrive/assets/offroad/icon_checkmark.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:da1540859c4c42878a32a0a81a38ca38b04be4cb0fe46709df3e024b7f3b4036 -size 243 diff --git a/selfdrive/assets/offroad/icon_close.svg b/selfdrive/assets/offroad/icon_close.svg deleted file mode 100644 index 54a44146d7aa3a..00000000000000 --- a/selfdrive/assets/offroad/icon_close.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4eff44a05132ed9f99ad821993be4bab9b1a1c880e07441f3b887214bee62afe -size 825 diff --git a/selfdrive/assets/offroad/icon_disengage_on_accelerator.svg b/selfdrive/assets/offroad/icon_disengage_on_accelerator.svg deleted file mode 100644 index d5a8c87e21cc31..00000000000000 --- a/selfdrive/assets/offroad/icon_disengage_on_accelerator.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5252412f2225c89ea7e78ad0fbd6544170aea157693ce0f9778f26a64f582ec2 -size 6821 diff --git a/selfdrive/assets/offroad/icon_lock_closed.svg b/selfdrive/assets/offroad/icon_lock_closed.svg deleted file mode 100644 index 501d978a8a30a7..00000000000000 --- a/selfdrive/assets/offroad/icon_lock_closed.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ef09792cc1893f81c64abd6b72091d3762c07b849863ce90508afdd29b392c02 -size 732 diff --git a/selfdrive/assets/offroad/icon_openpilot.png b/selfdrive/assets/offroad/icon_openpilot.png deleted file mode 100644 index ae6faa45eaa64a..00000000000000 --- a/selfdrive/assets/offroad/icon_openpilot.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a3cd3b91673eded1282e2082be0efa8e54ed477b5feb3580e521d08078e18ed1 -size 42640 diff --git a/selfdrive/assets/offroad/icon_plus.png b/selfdrive/assets/offroad/icon_plus.png deleted file mode 100644 index 6418a37a654ffa..00000000000000 --- a/selfdrive/assets/offroad/icon_plus.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fa3f1c39a4e82adfb52d43fc0ad6773a70dbaa4fc79109a7d6b6c1f73b298eac -size 2833 diff --git a/selfdrive/assets/offroad/icon_wifi_strength_full.svg b/selfdrive/assets/offroad/icon_wifi_strength_full.svg deleted file mode 100644 index c9d22d89614a80..00000000000000 --- a/selfdrive/assets/offroad/icon_wifi_strength_full.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:485dd0d4eb8968726003ae460bab4ff498127def52b8b1ed6d968f4629ab233a -size 1655 diff --git a/selfdrive/assets/offroad/icon_wifi_strength_high.svg b/selfdrive/assets/offroad/icon_wifi_strength_high.svg deleted file mode 100644 index ff001bd14ab199..00000000000000 --- a/selfdrive/assets/offroad/icon_wifi_strength_high.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c92fd8bebbe630f991fe3f61f61407f8002d29881698634239be3a6fae2fb4bc -size 1657 diff --git a/selfdrive/assets/offroad/icon_wifi_strength_low.svg b/selfdrive/assets/offroad/icon_wifi_strength_low.svg deleted file mode 100644 index bcc6e83c634d3f..00000000000000 --- a/selfdrive/assets/offroad/icon_wifi_strength_low.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e629e3a84dc288278e455be4a8deff95730e24d9a0b894f8c417ac1c409670ab -size 1661 diff --git a/selfdrive/assets/offroad/icon_wifi_strength_medium.svg b/selfdrive/assets/offroad/icon_wifi_strength_medium.svg deleted file mode 100644 index e14ebd238f51ad..00000000000000 --- a/selfdrive/assets/offroad/icon_wifi_strength_medium.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:52113c14656483854a814c50c93770f5e6ab7d63b2b5048ddd6fd47fdfd4a7de -size 1659 diff --git a/selfdrive/assets/offroad/icon_wifi_uploading.svg b/selfdrive/assets/offroad/icon_wifi_uploading.svg deleted file mode 100644 index b9392dfe7c122d..00000000000000 --- a/selfdrive/assets/offroad/icon_wifi_uploading.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bedd579f56c65fffe2ad571f92843b6d103826fe173f8f5b58fc2200d2ad8850 -size 1663 diff --git a/selfdrive/assets/offroad/mici_fcc.html b/selfdrive/assets/offroad/mici_fcc.html new file mode 100644 index 00000000000000..e6e4189128f286 --- /dev/null +++ b/selfdrive/assets/offroad/mici_fcc.html @@ -0,0 +1,16 @@ +<h3>HVIN: comma four</h3> +<h3>FCC ID: 2BFC6-MICI</h3> +<h3>IC: 32232-MICI</h3> +<h3>Contains FCC ID: XMR2023EG916QGL</h3> +<h3>Contains IC: 10224A-023EG916QGL</h3> +<br><br> +This device contains licence-exempt transmitter(s)/receiver(s) that comply with Innovation, Science and Economic Development +Canada's licence-exempt RSS(s) and complies with part 15 of the FCC Rules. Operation is subject to the following two conditions:<br> +1. This device may not cause harmful interference.<br> +2. This device must accept any interference received, including interference that may cause undesired operation of the device.<br> +<br><br> +L'émetteur/récepteur exempt de licence contenu dans le présent appareil est conforme aux CNR d'Innovation, Sciences +et Développement économique Canada applicables aux appareils radio exempts de licence. L'exploitation est autorisée +aux deux conditions suivantes :<br> +1. L'appareil ne doit pas produire de brouillage.<br> +2. L'appareil doit accepter tout brouillage radioélectrique subi, même si le brouillage est susceptible d'en compromettre<br> diff --git a/selfdrive/assets/offroad/tc.html b/selfdrive/assets/offroad/tc.html deleted file mode 100644 index f88daf08f24602..00000000000000 --- a/selfdrive/assets/offroad/tc.html +++ /dev/null @@ -1,44 +0,0 @@ -<!DOCTYPE html> - -<head> - <meta charset="utf-8" /> - <title>openpilot Terms of Service - - - - -

The Terms and Conditions below are effective for all users

-

Last Updated on October 18, 2019

-

Please read these Terms of Use (“Terms”) carefully before using openpilot which is open-sourced software developed by Comma.ai, Inc., a corporation organized under the laws of Delaware (“comma,” “us,” “we,” or “our”).

-

Before using and by accessing openpilot, you indicate that you have read, understood, and agree to these Terms. These Terms apply to all users and others who access or use openpilot. If others use openpilot through your user account or vehicle, you are responsible to ensure that they only use openpilot when it is safe to do so, and in compliance with these Terms and with applicable law. If you disagree with any part of the Terms, you should not access or use openpilot.

-

Communications

-

You agree that comma may contact you by email or telephone in connection with openpilot or for other business purposes. You may opt out of receiving email messages at any time by contacting us at support@comma.ai.

-

We collect, use, and share information from and about you and your vehicle in connection with openpilot. You consent to comma accessing the systems associated with openpilot, without additional notice or consent, for the purposes of providing openpilot, data collection, software updates, safety and cybersecurity, suspension or removal of your account, and as disclosed in the Privacy Policy (available at https://connect.comma.ai/privacy).

-

Safety

-

openpilot performs the functions of Adaptive Cruise Control (ACC) and Lane Keeping Assist System (LKAS) designed for use in compatible motor vehicles. While using openpilot, it is your responsibility to obey all laws, traffic rules, and traffic regulations governing your vehicle and its operation. Access to and use of openpilot is at your own risk and responsibility, and openpilot should be accessed and/or used only when you can do so safely.

-

openpilot does not make your vehicle “autonomous” or capable of operation without the active monitoring of a licensed driver. It is designed to assist a licensed driver. A licensed driver must pay attention to the road, remain aware of navigation at all times, and be prepared to take immediate action. Failure to do so can cause damage, injury, or death.

-

Supported Locations and Models

-

openpilot is compatible only with particular makes and models of vehicles. For a complete list of currently supported vehicles, visit https://comma.ai. openpilot will not function properly when installed in an incompatible vehicle. openpilot is compatible only within the geographical boundaries of the United States of America.

-

Indemnification

-

To the maximum extent allowable by law, you agree to defend, indemnify and hold harmless comma, and its employees, partners, suppliers, contractors, investors, agents, officers, directors, and affiliates, from and against any and all claims, damages, causes of action, penalties, interest, demands, obligations, losses, liabilities, costs or debt, additional taxes, and expenses (including but not limited to attorneys’ fees), resulting from or arising out of (i) your use and access of, or inability to use or access, openpilot, (ii) your breach of these Terms, (iii) the inaccuracy of any information, representation or warranty made by you, (iv) activities of anyone other than you in connection with openpilot conducted through your comma device or account, (v) any other of your activities under or in connection with these Terms or openpilot.

-

Limitation of Liability

-

In no event shall comma, nor its directors, employees, partners, agents, suppliers, or affiliates, be liable for any indirect, incidental, special, consequential or punitive damages, including without limitation, loss of profits, data, use, goodwill, or other intangible losses, resulting from (i) your access to or use of or inability to access or use of the Software; or (ii) any conduct or content of any third party on the Software whether based on warranty, contract, tort (including negligence) or any other legal theory, whether or not we have been informed of the possibility of such damage, and even if a remedy set forth herein is found to have failed of its essential purpose.

-

No Warranty or Obligations to Maintain or Service

-

comma provides openpilot without representations, conditions, or warranties of any kind. openpilot is provided on an “AS IS” and “AS AVAILABLE” basis, including with all faults and errors as may occur. To the extent permitted by law and unless prohibited by law, comma on behalf of itself and all persons and parties acting by, through, or for comma, explicitly disclaims all warranties or conditions, express, implied, or collateral, including any implied warranties of merchantability, satisfactory quality, and fitness for a particular purpose in respect of openpilot.

-

To the extent permitted by law, comma does not warrant the operation, performance, or availability of openpilot under all conditions. comma is not responsible for any failures caused by server errors, misdirected or redirected transmissions, failed internet connections, interruptions or failures in the transmission of data, any computer virus, or any acts or omissions of third parties that damage the network or impair wireless service.

-

We undertake reasonable measures to preserve and secure information collected through our openpilot. However, no data collection, transmission or storage system is 100% secure, and there is always a risk that your information may be intercepted without our consent. In using openpilot, you acknowledge that comma is not responsible for intercepted information, and you hereby release us from any and all claims arising out of or related to the use of intercepted information in any unauthorized manner.

-

By providing openpilot, comma does not transfer or license its intellectual property or grant rights in its brand names, nor does comma make representations with respect to third-party intellectual property rights.

-

We are not obligated to provide any maintenance or support for openpilot, technical or otherwise. If we voluntarily provide any maintenance or support for openpilot, we may stop any such maintenance, support, or services at any time in our sole discretion.

-

Modification of Software

-

In no event shall comma, nor its directors, employees, partners, agents, suppliers, or affiliates, be liable if you choose to modify the software.

-

Changes

-

We reserve the right, at our sole discretion, to modify or replace these Terms at any time. If a revision is material we will provide at least 15 days’ notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion.

-

By continuing to access or use our Software after any revisions become effective, you agree to be bound by the revised terms. If you do not agree to the new terms, you are no longer authorized to use the Software.

-

Contact Us

-

If you have any questions about these Terms, please contact us at support@comma.ai.

- - diff --git a/selfdrive/assets/prep-svg.sh b/selfdrive/assets/prep-svg.sh new file mode 100755 index 00000000000000..567c17da325a67 --- /dev/null +++ b/selfdrive/assets/prep-svg.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +ICONS_DIR="$DIR/icons" +BOOTSTRAP_SVG="$(python3 -c 'import bootstrap_icons; print(bootstrap_icons.SVG_PATH)')" + +ICON_IDS=( + arrow-right + backspace + capslock-fill + shift + shift-fill +) +ICON_FILL_COLOR="#fff" + +# extract bootstrap icons +for id in "${ICON_IDS[@]}"; do + svg="${ICONS_DIR}/${id}.svg" + perl -0777 -ne "print \$& if /]*id=\"$id\"[^>]*>.*?<\/symbol>/s" "$BOOTSTRAP_SVG" \ + | sed "s//<\/svg>/" > "$svg" +done + +# sudo apt install inkscape + +for svg in $(find $DIR -type f | grep svg$); do + bunx svgo $svg --multipass --pretty --indent 2 + + # convert to PNG + png="${svg%.svg}.png" + width=$(inkscape --query-width "$svg") + height=$(inkscape --query-height "$svg") + if (( $(echo "$width > $height" | bc -l) )); then + export_dim="--export-width=512" + else + export_dim="--export-height=512" + fi + inkscape "$svg" --export-filename="$png" "$export_dim" + + optipng -o7 -strip all "$png" +done + +# cleanup bootstrap SVGs +for id in "${ICON_IDS[@]}"; do + rm "${ICONS_DIR}/${id}.svg" +done diff --git a/selfdrive/assets/sounds/animal_chime.wav b/selfdrive/assets/sounds/animal_chime.wav new file mode 100644 index 00000000000000..9e586ede5d6355 Binary files /dev/null and b/selfdrive/assets/sounds/animal_chime.wav differ diff --git a/selfdrive/assets/sounds/disengage.wav b/selfdrive/assets/sounds/disengage.wav index f3b5f21a27c7ae..7bfd97ad715e2e 100644 --- a/selfdrive/assets/sounds/disengage.wav +++ b/selfdrive/assets/sounds/disengage.wav @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1f061777d66d8d856a5fcb17378416f959088885ed770181355195ad15de881b -size 68628 +oid sha256:42bd04a57b527c787a0555503e02a203f7d672c12d448769a3f41f17befbf013 +size 48044 diff --git a/selfdrive/assets/sounds/disengage_tizi.wav b/selfdrive/assets/sounds/disengage_tizi.wav new file mode 100644 index 00000000000000..f3b5f21a27c7ae --- /dev/null +++ b/selfdrive/assets/sounds/disengage_tizi.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f061777d66d8d856a5fcb17378416f959088885ed770181355195ad15de881b +size 68628 diff --git a/selfdrive/assets/sounds/engage.wav b/selfdrive/assets/sounds/engage.wav index fc24a23c2f7da4..8633b5ac2d82b1 100644 --- a/selfdrive/assets/sounds/engage.wav +++ b/selfdrive/assets/sounds/engage.wav @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6b54a85cc09b8ee79fce23d48209205d2e70510eed4c5a86fa400fe3f7caebfd -size 63120 +oid sha256:b1e177499d9439367179cc57a6301b6162393972e3a136cc35c5fdac026bf10a +size 48044 diff --git a/selfdrive/assets/sounds/engage_tizi.wav b/selfdrive/assets/sounds/engage_tizi.wav new file mode 100644 index 00000000000000..fc24a23c2f7da4 --- /dev/null +++ b/selfdrive/assets/sounds/engage_tizi.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b54a85cc09b8ee79fce23d48209205d2e70510eed4c5a86fa400fe3f7caebfd +size 63120 diff --git a/selfdrive/assets/sounds/make_beeps.py b/selfdrive/assets/sounds/make_beeps.py new file mode 100644 index 00000000000000..6161e80e742a04 --- /dev/null +++ b/selfdrive/assets/sounds/make_beeps.py @@ -0,0 +1,19 @@ +import numpy as np +from scipy.io import wavfile + + +sr = 48000 +max_int16 = 2**15 - 1 + +def harmonic_beep(freq, duration_seconds): + n_total = int(sr * duration_seconds) + + signal = np.sin(2 * np.pi * freq * np.arange(n_total) / sr) + x = np.arange(n_total) + exp_scale = np.exp(-x/5.5e3) + return max_int16 * signal * exp_scale + +engage_beep = harmonic_beep(1661.219, 0.5) +wavfile.write("engage.wav", sr, engage_beep.astype(np.int16)) +disengage_beep = harmonic_beep(1318.51, 0.5) +wavfile.write("disengage.wav", sr, disengage_beep.astype(np.int16)) diff --git a/selfdrive/assets/sounds/make_obstacle_chime.py b/selfdrive/assets/sounds/make_obstacle_chime.py new file mode 100644 index 00000000000000..0cc6af5aaef9a2 --- /dev/null +++ b/selfdrive/assets/sounds/make_obstacle_chime.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Write animal_chime.wav: two rising high notes, played twice. + +Stock engage is one decaying sine near 1661 Hz. Stock prompt is a +different tone. This is G6 (1568 Hz) then C7 (2093 Hz), each with a +short attack, a quick decay, and the 2nd and 3rd harmonics, then the +pair again. 48 kHz mono 16-bit, about 1.0 s, peak near full scale, so +the small speaker can actually say it. +""" +from __future__ import annotations + +import math +import struct +import wave +from pathlib import Path + +SAMPLE_RATE = 48000 +PEAK = 0.98 + + +def _note(freq: float, duration: float, decay: float) -> list[float]: + n = int(duration * SAMPLE_RATE) + attack = 0.006 + out = [] + for i in range(n): + t = i / SAMPLE_RATE + if t < attack: + env = 0.5 * (1.0 - math.cos(math.pi * t / attack)) + else: + env = math.exp(-(t - attack) / decay) + sample = math.sin(2.0 * math.pi * freq * t) + sample += 0.55 * math.sin(2.0 * math.pi * 2.0 * freq * t) + sample += 0.28 * math.sin(2.0 * math.pi * 3.0 * freq * t) + out.append(env * sample) + return out + + +def _phrase() -> list[float]: + gap = [0.0] * int(0.045 * SAMPLE_RATE) + pause = [0.0] * int(0.07 * SAMPLE_RATE) + # G6 then C7. Rising, so it is not the falling engage tone. + return _note(1567.98, 0.18, 0.055) + gap + _note(2093.00, 0.22, 0.06) + pause + + +def build() -> list[float]: + raw = _phrase() + _phrase() + peak = max(abs(s) for s in raw) or 1.0 + return [PEAK * s / peak for s in raw] + + +def write(path: Path) -> None: + samples = build() + pcm = b"".join(struct.pack("{{loop.index}}{{footnote}}
+{{loop.index}}{{footnote | replace('
', '')}}
{% endfor %} ## Community Maintained Cars @@ -42,7 +42,7 @@ If your car has the following packages or features, then it's a good candidate f | Make | Required Package/Features | | ---- | ------------------------- | -| Acura | Any car with AcuraWatch Plus will work. AcuraWatch Plus comes standard on many newer models. | +| Acura | Any car with AcuraWatch will work. AcuraWatch comes standard on many newer models. | | Ford | Any car with Lane Centering will likely work. | | Honda | Any car with Honda Sensing will work. Honda Sensing comes standard on many newer models. | | Subaru | Any car with EyeSight will work. EyeSight comes standard on many newer models. | diff --git a/selfdrive/car/README.md b/selfdrive/car/README.md deleted file mode 100644 index 2c49cf20511cc4..00000000000000 --- a/selfdrive/car/README.md +++ /dev/null @@ -1,19 +0,0 @@ -## Car port structure - -### interface.py -Generic interface to send and receive messages from CAN (controlsd uses this to communicate with car) - -### fingerprints.py -Fingerprints for matching to a specific car - -### carcontroller.py -Builds CAN messages to send to car - -##### carstate.py -Reads CAN from car and builds openpilot CarState message - -##### values.py -Limits for actuation, general constants for cars, and supported car documentation - -##### radar_interface.py -Interface for parsing radar points from the car diff --git a/selfdrive/car/car_specific.py b/selfdrive/car/car_specific.py index 25a7defbbd5c1e..67586de80af490 100644 --- a/selfdrive/car/car_specific.py +++ b/selfdrive/car/car_specific.py @@ -1,33 +1,30 @@ -from cereal import car -import cereal.messaging as messaging +from cereal import car, log from opendbc.car import DT_CTRL, structs -from opendbc.car.interfaces import MAX_CTRL_SPEED, CarStateBase, CarControllerBase -from opendbc.car.volkswagen.values import CarControllerParams as VWCarControllerParams -from opendbc.car.hyundai.interface import ENABLE_BUTTONS as HYUNDAI_ENABLE_BUTTONS - -from openpilot.selfdrive.controls.lib.events import Events +from opendbc.car.car_helpers import interfaces +from opendbc.car.interfaces import MAX_CTRL_SPEED +from opendbc.car.tesla.preap.lat_yield import stash_full_control +from opendbc.car.toyota.values import ToyotaFlags + +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import ( + BlinkerLateralHold, + blinker_turn_blocks_steering_disengage, +) +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import cs_hands_on_level +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + EmergencyYankTracker, + is_emergency_yank, + steer_disengage_this_frame, + tipped_lane_change_driver_release, + torque_is_same_direction, +) +from openpilot.selfdrive.selfdrived.events import Events ButtonType = structs.CarState.ButtonEvent.Type GearShifter = structs.CarState.GearShifter -EventName = car.OnroadEvent.EventName +EventName = log.OnroadEvent.EventName NetworkLocation = structs.CarParams.NetworkLocation -# TODO: the goal is to abstract this file into the CarState struct and make events generic -class MockCarState: - def __init__(self): - self.sm = messaging.SubMaster(['gpsLocation', 'gpsLocationExternal']) - - def update(self, CS: car.CarState): - self.sm.update(0) - gps_sock = 'gpsLocationExternal' if self.sm.recv_frame['gpsLocationExternal'] > 1 else 'gpsLocation' - - CS.vEgo = self.sm[gps_sock].speed - CS.vEgoRaw = self.sm[gps_sock].speed - - return CS - - class CarSpecificEvents: def __init__(self, CP: structs.CarParams): self.CP = CP @@ -36,152 +33,119 @@ def __init__(self, CP: structs.CarParams): self.low_speed_alert = False self.no_steer_warning = False self.silent_steer_warning = True + self.blinker_lat_hold = BlinkerLateralHold() + self._yank = EmergencyYankTracker() + self._yank_release_prev = False - def update(self, CS: CarStateBase, CS_prev: car.CarState, CC: CarControllerBase, CC_prev: car.CarControl): - if self.CP.carName in ('body', 'mock'): - events = Events() - - elif self.CP.carName == 'subaru': - events = self.create_common_events(CS.out, CS_prev) - - elif self.CP.carName == 'ford': - events = self.create_common_events(CS.out, CS_prev, extra_gears=[GearShifter.manumatic]) - - elif self.CP.carName == 'nissan': - events = self.create_common_events(CS.out, CS_prev, extra_gears=[GearShifter.brake]) + def update(self, CS: car.CarState, CS_prev: car.CarState, CC: car.CarControl): + if self.CP.brand in ('body', 'mock'): + return Events() - if CS.lkas_enabled: # type: ignore[attr-defined] - events.add(EventName.invalidLkasSetting) - - elif self.CP.carName == 'mazda': - events = self.create_common_events(CS.out, CS_prev) - - if CS.lkas_disabled: # type: ignore[attr-defined] - events.add(EventName.lkasDisabled) - elif CS.low_speed_alert: # type: ignore[attr-defined] - events.add(EventName.belowSteerSpeed) - - elif self.CP.carName == 'chrysler': - events = self.create_common_events(CS.out, CS_prev, extra_gears=[GearShifter.low]) + events = self.create_common_events(CS, CS_prev, CC) + if self.CP.brand == 'chrysler': # Low speed steer alert hysteresis logic - if self.CP.minSteerSpeed > 0. and CS.out.vEgo < (self.CP.minSteerSpeed + 0.5): + if self.CP.minSteerSpeed > 0. and CS.vEgo < (self.CP.minSteerSpeed + 0.5): self.low_speed_alert = True - elif CS.out.vEgo > (self.CP.minSteerSpeed + 1.): + elif CS.vEgo > (self.CP.minSteerSpeed + 1.): self.low_speed_alert = False if self.low_speed_alert: events.add(EventName.belowSteerSpeed) - elif self.CP.carName == 'honda': - events = self.create_common_events(CS.out, CS_prev, pcm_enable=False) - - if self.CP.pcmCruise and CS.out.vEgo < self.CP.minEnableSpeed: + elif self.CP.brand == 'honda': + if self.CP.pcmCruise and CS.vEgo < self.CP.minEnableSpeed: events.add(EventName.belowEngageSpeed) if self.CP.pcmCruise: # we engage when pcm is active (rising edge) - if CS.out.cruiseState.enabled and not CS_prev.cruiseState.enabled: + if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled: events.add(EventName.pcmEnable) - elif not CS.out.cruiseState.enabled and (CC_prev.actuators.accel >= 0. or not self.CP.openpilotLongitudinalControl): + elif not CS.cruiseState.enabled and (CC.actuators.accel >= 0. or not self.CP.openpilotLongitudinalControl): # it can happen that car cruise disables while comma system is enabled: need to # keep braking if needed or if the speed is very low - if CS.out.vEgo < self.CP.minEnableSpeed + 2.: + if CS.vEgo < self.CP.minEnableSpeed + 2.: # non loud alert if cruise disables below 25mph as expected (+ a little margin) events.add(EventName.speedTooLow) else: events.add(EventName.cruiseDisabled) - if self.CP.minEnableSpeed > 0 and CS.out.vEgo < 0.001: + if self.CP.minEnableSpeed > 0 and CS.vEgo < 0.001: events.add(EventName.manualRestart) - elif self.CP.carName == 'toyota': - events = self.create_common_events(CS.out, CS_prev) - + elif self.CP.brand == 'toyota': + # TODO: when we check for unexpected disengagement, check gear not S1, S2, S3 if self.CP.openpilotLongitudinalControl: - if CS.out.cruiseState.standstill and not CS.out.brakePressed: + # Only can leave standstill when planner wants to move + if CS.cruiseState.standstill and not CS.brakePressed and (CC.cruiseControl.resume or self.CP.flags & ToyotaFlags.HYBRID.value): events.add(EventName.resumeRequired) - if CS.low_speed_lockout: # type: ignore[attr-defined] - events.add(EventName.lowSpeedLockout) - if CS.out.vEgo < self.CP.minEnableSpeed: + if CS.vEgo < self.CP.minEnableSpeed: events.add(EventName.belowEngageSpeed) - if CC_prev.actuators.accel > 0.3: + if CC.actuators.accel > 0.3: # some margin on the actuator to not false trigger cancellation while stopping events.add(EventName.speedTooLow) - if CS.out.vEgo < 0.001: + if CS.vEgo < 0.001: # while in standstill, send a user alert events.add(EventName.manualRestart) - elif self.CP.carName == 'gm': - # The ECM allows enabling on falling edge of set, but only rising edge of resume - events = self.create_common_events(CS.out, CS_prev, extra_gears=[GearShifter.sport, GearShifter.low, - GearShifter.eco, GearShifter.manumatic], - pcm_enable=self.CP.pcmCruise, enable_buttons=(ButtonType.decelCruise,)) - if not self.CP.pcmCruise: - if any(b.type == ButtonType.accelCruise and b.pressed for b in CS.out.buttonEvents): - events.add(EventName.buttonEnable) - + elif self.CP.brand == 'gm': # Enabling at a standstill with brake is allowed # TODO: verify 17 Volt can enable for the first time at a stop and allow for all GMs - below_min_enable_speed = CS.out.vEgo < self.CP.minEnableSpeed or CS.moving_backward # type: ignore[attr-defined] - if below_min_enable_speed and not (CS.out.standstill and CS.out.brake >= 20 and - self.CP.networkLocation == NetworkLocation.fwdCamera): + if CS.vEgo < self.CP.minEnableSpeed and not (CS.standstill and CS.brake >= 20 and + self.CP.networkLocation == NetworkLocation.fwdCamera): events.add(EventName.belowEngageSpeed) - if CS.out.cruiseState.standstill: + if CS.cruiseState.standstill: events.add(EventName.resumeRequired) - if CS.out.vEgo < self.CP.minSteerSpeed: - events.add(EventName.belowSteerSpeed) - - elif self.CP.carName == 'volkswagen': - events = self.create_common_events(CS.out, CS_prev, extra_gears=[GearShifter.eco, GearShifter.sport, GearShifter.manumatic], - pcm_enable=not self.CP.openpilotLongitudinalControl, - enable_buttons=(ButtonType.setCruise, ButtonType.resumeCruise)) - - # Low speed steer alert hysteresis logic - if (self.CP.minSteerSpeed - 1e-3) > VWCarControllerParams.DEFAULT_MIN_STEER_SPEED and CS.out.vEgo < (self.CP.minSteerSpeed + 1.): - self.low_speed_alert = True - elif CS.out.vEgo > (self.CP.minSteerSpeed + 2.): - self.low_speed_alert = False - if self.low_speed_alert: - events.add(EventName.belowSteerSpeed) + elif self.CP.brand == 'volkswagen': if self.CP.openpilotLongitudinalControl: - if CS.out.vEgo < self.CP.minEnableSpeed + 0.5: + if CS.vEgo < self.CP.minEnableSpeed + 0.5: events.add(EventName.belowEngageSpeed) - if CC_prev.enabled and CS.out.vEgo < self.CP.minEnableSpeed: + if CC.enabled and CS.vEgo < self.CP.minEnableSpeed: events.add(EventName.speedTooLow) - if CC.eps_timer_soft_disable_alert: # type: ignore[attr-defined] - events.add(EventName.steerTimeLimit) - - elif self.CP.carName == 'hyundai': - # On some newer model years, the CANCEL button acts as a pause/resume button based on the PCM state - # To avoid re-engaging when openpilot cancels, check user engagement intention via buttons - # Main button also can trigger an engagement on these cars - allow_enable = any(btn in HYUNDAI_ENABLE_BUTTONS for btn in CS.cruise_buttons) or any(CS.main_buttons) # type: ignore[attr-defined] - events = self.create_common_events(CS.out, CS_prev, pcm_enable=self.CP.pcmCruise, allow_enable=allow_enable) - - # low speed steer alert hysteresis logic (only for cars with steer cut off above 10 m/s) - if CS.out.vEgo < (self.CP.minSteerSpeed + 2.) and self.CP.minSteerSpeed > 10.: - self.low_speed_alert = True - if CS.out.vEgo > (self.CP.minSteerSpeed + 4.): - self.low_speed_alert = False - if self.low_speed_alert: - events.add(EventName.belowSteerSpeed) - - else: - raise ValueError(f"Unsupported car: {self.CP.carName}") + # TODO: this needs to be implemented generically in carState struct + # if CC.eps_timer_soft_disable_alert: + # events.add(EventName.steerTimeLimit) + + elif self.CP.brand == 'tesla': + if self.CP.carFingerprint == "TESLA_MODEL_S_PREAP": + if self.CP.pcmCruise: + if getattr(CS, 'teslaCCEngaged', False): + events.add(EventName.teslaCCEngaged) + if getattr(CS, 'teslaCCDisengaged', False): + events.add(EventName.teslaCCDisengaged) + if getattr(CS, 'teslaCCNotArmed', False): + events.add(EventName.teslaCCNotArmed) + else: + # Pedal mode: refuse to engage until the Comma Pedal is calibrated. + # Without calibration, INTERCEPTOR_GAS values sit near the press + # threshold and produce gasPressedOverride chatter that blocks engage. + from opendbc.car.tesla.preap.nap_conf import nap_conf + if not nap_conf.pedal_calibrated: + events.add(EventName.pedalNotCalibrated) + if self.CP.openpilotLongitudinalControl and getattr(CS, 'pedalAuthorityFailed', False): + events.add(EventName.pedalUnavailable) return events - def create_common_events(self, CS: structs.CarState, CS_prev: car.CarState, extra_gears=None, pcm_enable=True, - allow_enable=True, enable_buttons=(ButtonType.accelCruise, ButtonType.decelCruise)): + def create_common_events(self, CS: structs.CarState, CS_prev: car.CarState, CC: car.CarControl): events = Events() + CI = interfaces[self.CP.carFingerprint] + # TODO: cleanup the honda-specific logic + # Pre-AP Tesla manages cruiseState.enabled via its own software FSM, + # so treat it the same as pcmCruise for the enable/disable event path. + preap_software_cruise = (self.CP.brand == "tesla" and self.CP.carFingerprint == "TESLA_MODEL_S_PREAP" + and self.CP.openpilotLongitudinalControl and not self.CP.pcmCruise) + pcm_enable = (self.CP.pcmCruise and self.CP.brand != 'honda') or preap_software_cruise + # TODO: on some hyundai cars, the cancel button is also the pause/resume button, + # so only use it for cancel when running openpilot longitudinal + allow_button_cancel = self.CP.brand != 'hyundai' + if CS.doorOpen: events.add(EventName.doorOpen) if CS.seatbeltUnlatched: events.add(EventName.seatbeltNotLatched) - if CS.gearShifter != GearShifter.drive and (extra_gears is None or - CS.gearShifter not in extra_gears): + if CS.gearShifter != GearShifter.drive and CS.gearShifter not in CI.DRIVABLE_GEARS: events.add(EventName.wrongGear) if CS.gearShifter == GearShifter.reverse: events.add(EventName.reverseGear) @@ -195,6 +159,8 @@ def create_common_events(self, CS: structs.CarState, CS_prev: car.CarState, extr events.add(EventName.stockFcw) if CS.stockAeb: events.add(EventName.stockAeb) + if CS.stockLkas: + events.add(EventName.stockLkas) if CS.vEgo > MAX_CTRL_SPEED: events.add(EventName.speedTooHigh) if CS.cruiseState.nonAdaptive: @@ -207,20 +173,84 @@ def create_common_events(self, CS: structs.CarState, CS_prev: car.CarState, extr events.add(EventName.accFaulted) if CS.steeringPressed: events.add(EventName.steerOverride) + # Wheel input during a blinker-lamp turn (including flash gaps), and + # while the hand is still on the wheel after ~1s of dark, must not + # USER_DISABLE cruise. steeringDisengage (hands-on >= 2 / EPAS reject) + # is the faster-corner signal and must count even if steeringPressed + # has not yet debounced. Hard-gate on one lamp or physical LEFT/RIGHT + # so a stale hold cannot drop cruiseEnabled — that falling edge is + # EventName.pcmDisable / HUD "Steering Disengaged" on Pre-AP. Do not + # suppress pcmDisable after cruise is already down. ALC keep-alive + # flashes are not a driver turn: do not pause lat, and do not + # steerDisengage. A held stalk past the 0.40s tip window is a turn at + # any speed when ALC is not latched; during ALC / keep-alive, + # same-direction stalk needs >1.0s. A firm stalk cancel still fully + # disengages. + alc_active = bool(getattr(CC, 'leftBlinker', False) or getattr(CC, 'rightBlinker', False)) + self.blinker_lat_hold.update( + getattr(CS, 'leftBlinker', False), getattr(CS, 'rightBlinker', False), + getattr(CS, 'steeringPressed', False), + engaged=bool(getattr(CS.cruiseState, 'enabled', False)), + alc_active=alc_active, + v_ego=float(getattr(CS, 'vEgo', 0.0) or 0.0), + stalk_state=int(getattr(CS, 'turnSignalStalkState', 0) or 0), + steering_disengage=bool(getattr(CS, 'steeringDisengage', False))) + torque_nm = float(getattr(CS, 'steeringTorque', 0.0) or 0.0) + hands = cs_hands_on_level(CS) + fast_rise = self._yank.update(torque_nm, DT_CTRL) + cc_left = bool(getattr(CC, 'leftBlinker', False)) + cc_right = bool(getattr(CC, 'rightBlinker', False)) + # Tipped ALC, including the lamp flash-dark gap (_alc_keep ~1 s, or + # controlsd still requesting the keep-alive blinker). A latched stalk + # clears _alc_keep and is not this window. + alc_confirm = bool(self.blinker_lat_hold._alc_keep) or (cc_left != cc_right) + direction = int(self.blinker_lat_hold._alc_direction or 0) + if direction not in (1, 2): + direction = 1 if cc_left and not cc_right else (2 if cc_right and not cc_left else 0) + emergency = is_emergency_yank( + torque_nm=torque_nm, hands_on_level=hands, fast_rise=fast_rise, + over_torque=self._yank.over_torque, alc_direction=direction if alc_confirm else 0) + same_direction = torque_is_same_direction(torque_nm, direction) + # Confirm: do not steering-disengage, even if the lamp is in a + # flash-dark gap and the hold has not latched blocks yet. + confirm = alc_confirm and same_direction and not emergency + release = alc_confirm and tipped_lane_change_driver_release( + same_direction=same_direction, emergency=emergency) + blocks = blinker_turn_blocks_steering_disengage( + getattr(CS, 'leftBlinker', False), getattr(CS, 'rightBlinker', False), + getattr(CS, 'turnSignalStalkState', 0), self.blinker_lat_hold, + emergency=emergency, alc_confirm=alc_confirm) + disengage_edge = bool(CS.steeringDisengage and not CS_prev.steeringDisengage) + # Pre-AP: a wheel yank cancels only while OP is in full lateral control + # (A). With lateral yielded (B) it is a driver maneuver. The card + # stashes that on steeringTorqueEps; see opendbc preap/lat_yield.py. + lat_full_control = True + if self.CP.carFingerprint == "TESLA_MODEL_S_PREAP": + lat_full_control = stash_full_control(getattr(CS, 'steeringTorqueEps', 0.0)) + if steer_disengage_this_frame( + confirm=confirm, release=release, release_prev=self._yank_release_prev, + disengage_edge=disengage_edge, blocks=blocks, + lat_full_control=lat_full_control): + events.add(EventName.steerDisengage) + self._yank_release_prev = release if CS.brakePressed and CS.standstill: events.add(EventName.preEnableStandstill) if CS.gasPressed: events.add(EventName.gasPressedOverride) if CS.vehicleSensorsInvalid: events.add(EventName.vehicleSensorsInvalid) - - # Handle button presses + if CS.invalidLkasSetting: + events.add(EventName.invalidLkasSetting) + if CS.lowSpeedAlert: + events.add(EventName.belowSteerSpeed) + if CS.buttonEnable: + events.add(EventName.buttonEnable) + + # Handle cancel button presses for b in CS.buttonEvents: - # Enable OP long on falling edge of enable buttons (defaults to accelCruise and decelCruise, overridable per-port) - if not self.CP.pcmCruise and (b.type in enable_buttons and not b.pressed): - events.add(EventName.buttonEnable) # Disable on rising and falling edge of cancel for both stock and OP long - if b.type == ButtonType.cancel: + # TODO: only check the cancel button with openpilot longitudinal on all brands to match panda safety + if b.type == ButtonType.cancel and (allow_button_cancel or not self.CP.pcmCruise): events.add(EventName.buttonCancel) # Handle permanent and temporary steering faults @@ -246,7 +276,7 @@ def create_common_events(self, CS: structs.CarState, CS_prev: car.CarState, extr # we engage when pcm is active (rising edge) # enabling can optionally be blocked by the car interface if pcm_enable: - if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled and allow_enable: + if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled and not CS.blockPcmEnable: events.add(EventName.pcmEnable) elif not CS.cruiseState.enabled: events.add(EventName.pcmDisable) diff --git a/selfdrive/car/card.py b/selfdrive/car/card.py old mode 100755 new mode 100644 index 57b41a5cf5b087..58051a6a9a1ba4 --- a/selfdrive/car/card.py +++ b/selfdrive/car/card.py @@ -1,43 +1,181 @@ #!/usr/bin/env python3 +import json import os import time import threading import cereal.messaging as messaging -from cereal import car - -from panda import ALTERNATIVE_EXPERIENCE +from cereal import car, log +from opendbc.car.common.conversions import Conversions as CV from openpilot.common.params import Params from openpilot.common.realtime import config_realtime_process, Priority, Ratekeeper from openpilot.common.swaglog import cloudlog, ForwardingHandler -from opendbc.car import DT_CTRL, carlog, structs +from opendbc.car import DT_CTRL, structs from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable +from opendbc.car.carlog import carlog from opendbc.car.fw_versions import ObdCallback -from opendbc.car.car_helpers import get_car -from opendbc.car.interfaces import CarInterfaceBase +from opendbc.car.car_helpers import get_car, interfaces +from opendbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp -from openpilot.selfdrive.car.cruise import VCruiseHelper -from openpilot.selfdrive.car.car_specific import CarSpecificEvents, MockCarState -from openpilot.selfdrive.car.helpers import convert_carControl, convert_to_capnp -from openpilot.selfdrive.controls.lib.events import Events, ET +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET, VCruiseHelper +from openpilot.selfdrive.mapd.constants import MANUAL_SET_EPS_KPH, map_accel_a_ms2 +from openpilot.selfdrive.mapd.map_speed_policy import ( + DEFAULT_DROP_A_MS2, + MAP_SOURCE_DEFAULT, + MapCruiseHold, apply_map_speed_kph, decide_map_cruise, effective_map_limit_ms, + map_slew_a_ms2, read_map_speed_params, should_write_preap_pedal, slew_map_speed_ms, +) +from openpilot.selfdrive.mapd.roundabout import ( + RB_EXIT_RESTORE_MS2, + RingExitGate, + live_map_roundabout_hint, + roundabout_ease_v_ms, + roundabout_target_ms, +) +from openpilot.selfdrive.controls.lib.curve_follow import MODE_ACTIVE, MODE_SHADOW, read_curve_follow_mode +from openpilot.selfdrive.controls.lib.curve_max_hold import CurveMaxHold +from openpilot.selfdrive.controls.lib.radar_status_log import RadarStatusLogger +from openpilot.selfdrive.controls.lib.follow_distance import published_cruise_ms +from openpilot.selfdrive.controls.lib.hypermile import ( + FollowStalkGesture, button_event_closer, button_event_released, + map_target_offset_kph, persist_follow_distance, read_hypermile_params, + read_hypermile_step_down, +) +from openpilot.selfdrive.car.tesla.preap_force_offroad_handoff import ( + install_force_offroad_handoff, + update_force_offroad_handoff, +) REPLAY = "REPLAY" in os.environ -EventName = car.OnroadEvent.EventName +EventName = log.OnroadEvent.EventName + + +def map_slew_from_displayed_kph(displayed_kph: float, offset_kph: float) -> float: + """Slew state tracks the raw OSM limit. HUD / pedal MAX already includes offset.""" + return (float(displayed_kph) - float(offset_kph)) * CV.KPH_TO_MS + + +def _kph_near(a, b, eps: float = 1.0) -> bool: + if a is None or b is None: + return False + try: + return abs(float(a) - float(b)) <= eps + except (TypeError, ValueError): + return False + + +def _snapshot_cruise_hold(hold) -> dict: + return { + "sticky_set_kph": hold.sticky_set_kph, + "held_max_kph": hold.held_max_kph, + "policy_kph": hold.policy_kph, + "last_raw": hold.last_raw_kph, + } + + +def _refresh_ring_snapshot(pre: dict, hold, ring_kph: float) -> None: + """Posted / stalk changes that are not the ring speed become the resume target.""" + if pre is None or _kph_near(hold.held_max_kph, ring_kph): + return + pre["held_max_kph"] = hold.held_max_kph + pre["policy_kph"] = hold.policy_kph + pre["sticky_set_kph"] = hold.sticky_set_kph + pre["last_raw"] = hold.last_raw_kph + + +def _unwind_ring_speed_set(hold, pre, ring_kph: float) -> bool: + """Drop a MAX that was stored as the ring speed. Keep a pre-ring set. + + Returns True when a ring-speed latch was removed. Gap lock is a lead + setpoint and is not touched; MAX stays the cruise ceiling. + """ + if pre is None: + return False + changed = False + for field in ("sticky_set_kph", "held_max_kph", "policy_kph"): + cur = getattr(hold, field) + old = pre.get(field) + if _kph_near(cur, ring_kph) and not _kph_near(old, ring_kph): + setattr(hold, field, old) + changed = True + if changed and _kph_near(hold.last_raw_kph, ring_kph): + old_raw = pre.get("last_raw") + if old_raw is not None: + hold.last_raw_kph = old_raw + return changed + + +def _ring_exit_target_ms(hold, lim, posted_kph, detect_v_ms: float | None = None) -> float | None: + """Posted limit, else the pre-ring MAX. None when nothing is known. + + MAX is a hard ceiling: a driver-set pre-ring MAX (stalk sticky / held) + is restored exactly, even if the car was faster when the ring was first + detected. Only a map-auto MAX (policy_kph, no driver set) with no posted + limit now may rise to the detection speed, since that MAX was never a + driver choice and the map no longer has a limit to restore toward. + """ + if hold.sticky_set_kph is None and lim is not None and float(lim) > 0.0: + return float(lim) + for val in (hold.sticky_set_kph, hold.held_max_kph): + if val is not None and float(val) > 0.0: + return float(val) * CV.KPH_TO_MS + if hold.policy_kph is not None and float(hold.policy_kph) > 0.0: + pol = float(hold.policy_kph) * CV.KPH_TO_MS + if detect_v_ms is not None and float(detect_v_ms) > pol: + return float(detect_v_ms) + return pol + if posted_kph is not None and float(posted_kph) > 0.0: + return float(posted_kph) * CV.KPH_TO_MS + return None + + +def _apply_ring_exit_max(target_ms, floor_ms, lookahead, accel_level): + """Start the ramp at least at current speed, then ease toward the target. + + One map-rate step, so a ring exit does not publish the ring speed and + does not step MAX down in a single frame. + """ + start = float(floor_ms) + if target_ms is None or float(target_ms) <= 0.0: + return start * CV.MS_TO_KPH, start + a = map_slew_a_ms2(start, float(target_ms), lookahead, accel_level) + nxt = slew_map_speed_ms(start, float(target_ms), DT_CTRL, a) + return nxt * CV.MS_TO_KPH, nxt # forward carlog.addHandler(ForwardingHandler(cloudlog)) +def log_curve_max(owner, curve_out, hud_in_kph, posted_kph, CS) -> None: + """2 Hz `curvemax` line (errorLogMessage -> qlog) while the MAX cap is in play. Never touches MAX.""" + try: + owner._curve_log_n = getattr(owner, "_curve_log_n", 0) + 1 + cap = getattr(owner._curve_max, "_cap_kph", None) + if owner._curve_log_n % 50 != 0 or not (curve_out.active or cap is not None): + return + rec = { + "m": int(getattr(owner, "_curve_follow_mode", MODE_SHADOW)), "act": int(bool(curve_out.active)), + "cap": None if cap is None else round(float(cap), 1), "hud_in": round(float(hud_in_kph), 1), + "hud": round(float(curve_out.hud_kph), 1), + "seed": None if curve_out.restore_seed_kph is None else round(float(curve_out.restore_seed_kph), 1), + "frz": int(bool(curve_out.freeze_posted)), "posted": None if posted_kph is None else round(float(posted_kph), 1), + "v": round(float(CS.vEgo), 2), + } + cloudlog.error("curvemax " + json.dumps(rec, separators=(",", ":"))) + except Exception: + pass + + def obd_callback(params: Params) -> ObdCallback: def set_obd_multiplexing(obd_multiplexing: bool): if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing: cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}") params.remove("ObdMultiplexingChanged") - params.put_bool("ObdMultiplexingEnabled", obd_multiplexing) + params.put_bool("ObdMultiplexingEnabled", obd_multiplexing, block=True) params.get_bool("ObdMultiplexingChanged", block=True) cloudlog.warning("OBD multiplexing set successfully") return set_obd_multiplexing @@ -63,13 +201,17 @@ def can_send(msgs: list[CanData]) -> None: class Car: CI: CarInterfaceBase - CP: structs.CarParams - CP_capnp: car.CarParams + RI: RadarInterfaceBase + CP: car.CarParams - def __init__(self, CI=None) -> None: + def __init__(self, CI=None, RI=None) -> None: self.can_sock = messaging.sub_sock('can', timeout=20) - self.sm = messaging.SubMaster(['pandaStates', 'carControl', 'onroadEvents']) - self.pm = messaging.PubMaster(['sendcan', 'carState', 'carParams', 'carOutput']) + # Curve MAX reads vehicle-model curvature off carControl (already + # polled here). Do not subscribe to controlsState: that 100 Hz socket + # pinned card/controlsd/selfdrived and dropped controlsd below 100 Hz. + self.sm = messaging.SubMaster(['pandaStates', 'carControl', 'onroadEvents', 'liveMapDataNAP', 'radarState', + 'livePose']) + self.pm = messaging.PubMaster(['sendcan', 'carState', 'carParams', 'carOutput', 'liveTracks']) self.can_rcv_cum_timeout_counter = 0 @@ -83,6 +225,8 @@ def __init__(self, CI=None) -> None: self.can_callbacks = can_comm_callbacks(self.can_sock, self.pm.sock['sendcan']) + is_release = self.params.get_bool("IsReleaseBranch") + if CI is None: # wait for one pandaState and one CAN packet print("Waiting for CAN messages...") @@ -91,57 +235,74 @@ def __init__(self, CI=None) -> None: if len(can.can) > 0: break - experimental_long_allowed = self.params.get_bool("ExperimentalLongitudinalEnabled") - num_pandas = len(messaging.recv_one_retry(self.sm.sock['pandaStates']).pandaStates) + alpha_long_allowed = self.params.get_bool("AlphaLongitudinalEnabled") cached_params = None cached_params_raw = self.params.get("CarParamsCache") if cached_params_raw is not None: with car.CarParams.from_bytes(cached_params_raw) as _cached_params: - cached_params = structs.CarParams(carName=_cached_params.carName, carFw=_cached_params.carFw, carVin=_cached_params.carVin) + cached_params = _cached_params - self.CI = get_car(*self.can_callbacks, obd_callback(self.params), experimental_long_allowed, num_pandas, cached_params) + self.CI = get_car(*self.can_callbacks, obd_callback(self.params), alpha_long_allowed, is_release, cached_params) + self.RI = interfaces[self.CI.CP.carFingerprint].RadarInterface(self.CI.CP) self.CP = self.CI.CP # continue onto next fingerprinting step in pandad - self.params.put_bool("FirmwareQueryDone", True) + self.params.put_bool("FirmwareQueryDone", True, block=True) else: self.CI, self.CP = CI, CI.CP + self.RI = RI - # set alternative experiences from parameters - self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator") self.CP.alternativeExperience = 0 - if not self.disengage_on_accelerator: - self.CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS - openpilot_enabled_toggle = self.params.get_bool("OpenpilotEnabledToggle") - controller_available = self.CI.CC is not None and openpilot_enabled_toggle and not self.CP.dashcamOnly - self.CP.passive = not controller_available or self.CP.dashcamOnly if self.CP.passive: safety_config = structs.CarParams.SafetyConfig() safety_config.safetyModel = structs.CarParams.SafetyModel.noOutput self.CP.safetyConfigs = [safety_config] + if self.CP.secOcRequired: + # Copy user key if available + try: + with open("/cache/params/SecOCKey") as f: + user_key = f.readline().strip() + if len(user_key) == 32: + self.params.put("SecOCKey", user_key, block=True) + except Exception: + pass + + secoc_key = self.params.get("SecOCKey") + if secoc_key is not None: + saved_secoc_key = bytes.fromhex(secoc_key.strip()) + if len(saved_secoc_key) == 16: + self.CP.secOcKeyAvailable = True + self.CI.CS.secoc_key = saved_secoc_key + if controller_available: + self.CI.CC.secoc_key = saved_secoc_key + else: + cloudlog.warning("Saved SecOC key is invalid") + # Write previous route's CarParams prev_cp = self.params.get("CarParamsPersistent") if prev_cp is not None: - self.params.put("CarParamsPrevRoute", prev_cp) + self.params.put("CarParamsPrevRoute", prev_cp, block=True) # Write CarParams for controls and radard - # convert to pycapnp representation for caching and logging - self.CP_capnp = convert_to_capnp(self.CP) - cp_bytes = self.CP_capnp.to_bytes() - self.params.put("CarParams", cp_bytes) - self.params.put_nonblocking("CarParamsCache", cp_bytes) - self.params.put_nonblocking("CarParamsPersistent", cp_bytes) - - self.events = Events() + cp_bytes = self.CP.to_bytes() + self.params.put("CarParams", cp_bytes, block=True) + self.params.put("CarParamsCache", cp_bytes) + self.params.put("CarParamsPersistent", cp_bytes) - self.car_events = CarSpecificEvents(self.CP) - self.mock_carstate = MockCarState() self.v_cruise_helper = VCruiseHelper(self.CP) + self._map_hold = MapCruiseHold() + self._curve_max = CurveMaxHold() + self._map_slew_ms: float | None = None + self._last_pedal_kph: float | None = None + self._pedal_self_write_kph: float | None = None + self._follow_stalk_mono: float = 0.0 + self._follow_gesture = FollowStalkGesture() + self._refresh_map_speed_params() self.is_metric = self.params.get_bool("IsMetric") self.experimental_mode = self.params.get_bool("ExperimentalMode") @@ -149,15 +310,58 @@ def __init__(self, CI=None) -> None: # card is driven by can recv, expected at 100Hz self.rk = Ratekeeper(100, print_delay_threshold=None) - def state_update(self) -> car.CarState: + self._can_packets: list[CanData] = [] + self.radar_donor_vin = None + tesla_preap = any(cfg.safetyModel == car.CarParams.SafetyModel.teslaPreap for cfg in self.CP.safetyConfigs) + self._tesla_preap = tesla_preap + self._nap_orphan_s = 0.0 + # 2 Hz radarstat line (radar status bits + track summary) for Pre-AP Bosch digs. + self._radar_stat = RadarStatusLogger() if tesla_preap else None + if tesla_preap: + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause + from openpilot.selfdrive.car.tesla.preap_body_controls import install_body_controls_test + from opendbc.car.tesla.preap.nap_conf import nap_conf + from opendbc.car.tesla.preap.radar_donor_vin import RadarDonorVinCommissioner + + from openpilot.selfdrive.controls.lib.lead_approach import install_preap_plant_regen_guard + + install_blinker_lat_pause() + install_body_controls_test() + install_force_offroad_handoff() + install_preap_plant_regen_guard() + + def store_donor_vin(vin: str) -> None: + nap_conf.radar_donor_vin = vin + self.params.put("NAPRadarVinReadStatus", f"saved {vin}") + cloudlog.info("preap radar donor vin stored") + + self._nap_conf = nap_conf + self.radar_donor_vin = RadarDonorVinCommissioner(store_donor_vin) + + def state_update(self) -> tuple[car.CarState, structs.RadarDataT | None]: """carState update loop, driven by can""" - # Update carState from CAN can_strs = messaging.drain_sock_raw(self.can_sock, wait_for_one=True) - CS = convert_to_capnp(self.CI.update(can_capnp_to_list(can_strs))) + can_list = can_capnp_to_list(can_strs) + self._can_packets = [CanData(addr, dat, src) for _ts, frames in can_list for addr, dat, src in frames] - if self.CP.carName == 'mock': - CS = self.mock_carstate.update(CS) + # Update carState from CAN + CS = self.CI.update(can_list) + + # Pre-AP Force Offroad stock-CC handoff (or immediate ready if not + # software-long). Must run while onroad so CANCEL/SET can still TX. + update_force_offroad_handoff( + getattr(self.CI, "CS", None) if getattr(self, "_tesla_preap", False) else None, + CS, + ) + + # Update radar tracks from CAN + RD: structs.RadarDataT | None = self.RI.update(can_list) + radar_stat = getattr(self, "_radar_stat", None) + if radar_stat is not None: + stat_line = radar_stat.update(self._can_packets, getattr(RD, "points", None), CS.vEgo) + if stat_line is not None: + cloudlog.error(stat_line) self.sm.update(0) @@ -170,48 +374,491 @@ def state_update(self) -> car.CarState: if can_rcv_valid and REPLAY: self.can_log_mono_time = messaging.log_from_bytes(can_strs[0]).logMonoTime + if getattr(self, "_tesla_preap", False): + # Cruise latched on the car side, openpilot not actually engaged + # (startup, noEntry, missed rising edge). Quiet reset after 0.75 s. + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import reconcile_orphan_session + self._nap_orphan_s, _canceled = reconcile_orphan_session( + getattr(getattr(self.CI, "CS", None), "engagement", None), + op_enabled=bool(self.sm['carControl'].enabled), + orphan_s=float(getattr(self, "_nap_orphan_s", 0.0)), + dt=DT_CTRL, + cereal_cs=CS, + interface_cs=getattr(self.CI, "CS", None), + ) + + try: + preap_software_cruise = ( + self.CP.brand == "tesla" + and self.CP.carFingerprint == "TESLA_MODEL_S_PREAP" + and self.CP.openpilotLongitudinalControl + and not self.CP.pcmCruise + ) + + if not preap_software_cruise: + self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric) + if self.sm['carControl'].enabled and not self.CC_prev.enabled: + # Use CarState w/ buttons from the step selfdrived enables on + self.v_cruise_helper.initialize_v_cruise(self.CS_prev, self.experimental_mode) + else: + self._update_preap_map_cruise(CS) + except Exception: + # Fail-safe: never crash card due cruise-target selection logic. + cloudlog.exception("Pre-AP software cruise target update failed, falling back to VCruiseHelper default") + self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric) + if self.sm['carControl'].enabled and not self.CC_prev.enabled: + self.v_cruise_helper.initialize_v_cruise(self.CS_prev, self.experimental_mode) + # TODO: mirror the carState.cruiseState struct? - self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric) CS.vCruise = float(self.v_cruise_helper.v_cruise_kph) CS.vCruiseCluster = float(self.v_cruise_helper.v_cruise_cluster_kph) - return CS - - def update_events(self, CS: car.CarState): - self.events.clear() - - CS.events = self.car_events.update(self.CI.CS, self.CS_prev, self.CI.CC, self.CC_prev).to_msg() - - self.events.add_from_msg(CS.events) - - if self.CP.notCar: - # wait for everything to init first - if self.sm.frame > int(5. / DT_CTRL) and self.initialized_prev: - # body always wants to enable - self.events.add(EventName.pcmEnable) - - # Disable on rising edge of accelerator or brake. Also disable on brake when speed > 0 - if (CS.gasPressed and not self.CS_prev.gasPressed and self.disengage_on_accelerator) or \ - (CS.brakePressed and (not self.CS_prev.brakePressed or not CS.standstill)) or \ - (CS.regenBraking and (not self.CS_prev.regenBraking or not CS.standstill)): - self.events.add(EventName.pedalPressed) - - CS.events = self.events.to_msg() - - def state_publish(self, CS: car.CarState): + return CS, RD + + def _update_preap_map_cruise(self, CS) -> None: + """OSM overlay for pre-AP pedal MAX. Slew state stays in raw-limit units.""" + # Pre-AP pedal mode owns set-speed via pedal_speed_kph. Overlay OSM + # onto vCruise/MAX for the OP session (cruiseEnabled), including a + # brake long pause so sticky MAX can rebase. The first + # pull is lateral-only and must not seed or arm a sticky hold. + raw_kph = float(CS.cruiseState.speed * CV.MS_TO_KPH) + raw_kph, follow_stalk = self._maybe_follow_stalk(CS, raw_kph) + long_active = bool(getattr(CS, 'pedalLongActive', False)) + long_active_prev = bool(getattr(self.CS_prev, 'pedalLongActive', False)) + engage_rising = long_active and not long_active_prev + session_enabled = bool(getattr(CS.cruiseState, 'enabled', False)) + resume_held, take_speed_now = self._preap_set_events() + # Overlay held can be None (maps off never stalk-latched). The FSM + # still has the brake-pause MAX — adopt it before pause substitution + # so we never treat ego as held, and so session_engaged stays up. + self._adopt_preap_fsm_held_max() + # Software long (enableLongControl), not pedal authority. Pause and + # the authority-acquisition gap both have pedalLongActive False; + # only a true long pause publishes cruiseState.speed as ego. + soft_long = bool(getattr(CS, 'enableLongControl', False)) + # Pause publishes cruiseState.speed as ego. Keep the held MAX instead. + if not soft_long and self._map_hold.held_max_kph is not None: + raw_kph = float(self._map_hold.held_max_kph) + traveled_kph = float(CS.vEgo) * CV.MS_TO_KPH + has_held = self._map_hold.held_max_kph is not None + session_engaged = bool(session_enabled) and ( + soft_long or has_held or resume_held or take_speed_now + ) + stalk_pressed = (not follow_stalk) and self._preap_stalk_set_pressed(CS) + self_wrote_pedal = ( + self._pedal_self_write_kph is not None + and abs(float(raw_kph) - float(self._pedal_self_write_kph)) <= MANUAL_SET_EPS_KPH + ) + self._pedal_self_write_kph = None + posted_kph = None + map_kph = None + map_valid = bool(self.sm.valid.get('liveMapDataNAP', False) and self.sm['liveMapDataNAP'].speedLimitValid) + md = self.sm['liveMapDataNAP'] if map_valid else None + raw_posted_kph = None + if md is not None and md.speedLimit > 0: + raw_posted_kph = float(md.speedLimit) * CV.MS_TO_KPH + # Offset from raw OSM posted (mph). Hypermile eco / Step Down apply + # only with a known map posted — never invent a drop when maps are + # off, unmatched, or speedLimit unknown (same as sticky MAX). + maps_posted = raw_posted_kph is not None + map_offset_kph = self._live_map_offset_kph(raw_posted_kph, maps_posted=maps_posted) + if raw_posted_kph is not None: + posted_kph = raw_posted_kph + map_offset_kph + # Snapshot pre-curve MAX before decide so OSM flicker cannot wipe sticky. + last_hud_kph = float(self.v_cruise_helper.v_cruise_kph) + steer_deg = float(getattr(CS, 'steeringAngleDeg', 0.0) or 0.0) + curve_kappa, curve_yaw = self._curve_cornering() + # NAPCurveFollow = 2: the planner's continuous curve term owns bends and MAX + # is never touched. CurveMaxHold is fed engaged=False, which resets it and + # passes posted / HUD MAX straight through (no cap, snapshot, restore or + # posted freeze). 0 / 1 (shadow): CurveMaxHold runs exactly as before. + curve_follow_on = getattr(self, "_curve_follow_mode", MODE_SHADOW) == MODE_ACTIVE + policy_posted_kph, _ = self._curve_max.begin_cycle( + self._map_hold, + last_hud_kph=last_hud_kph, + posted_kph=posted_kph, + v_ego_ms=float(CS.vEgo), + angle_steers_deg=steer_deg, + steer_ratio=float(getattr(self.CP, 'steerRatio', 0.0) or 0.0), + wheelbase=float(getattr(self.CP, 'wheelbase', 0.0) or 0.0), + engaged=session_engaged and not curve_follow_on, + take_speed_now=take_speed_now, + dt=DT_CTRL, + curvature=curve_kappa, + yaw_rate=curve_yaw, + ) + dec = decide_map_cruise( + self._map_hold, + engaged=session_engaged, + mode=self._map_speed_mode, + raw_kph=raw_kph, + posted_kph=policy_posted_kph, + engage_rising=engage_rising, + now=time.monotonic(), + stalk_pressed=stalk_pressed, + take_speed_now=take_speed_now, + resume_held=resume_held, + traveled_kph=traveled_kph, + long_active=soft_long, + self_wrote_pedal=self_wrote_pedal, + ) + # Stalk +/- while maps off updates overlay held; keep the FSM latch + # aligned so the next brake pause resumes that MAX. + self._publish_preap_held_max(long_active=soft_long) + if map_valid and md is not None and not dec.sticky: + # Any posted decrease: kin+110 m ease, never assign the new limit in one shot. + lim = effective_map_limit_ms( + float(md.speedLimit), + float(md.nextSpeedLimit), + float(md.nextSpeedLimitDistance), + float(CS.vEgo), + self._map_speed_lookahead, + self._map_speed_accel, + sticky=False, + ) + else: + lim = None + # RB funnel is geometry, not a posted rebase. Ease even on a sticky + # hold so aTarget cannot stay +a into the ring (Willmar 49→17). + # The ring hint does not need a speed-limit match: a ring often has no + # maxspeed. Read it whenever mapd publishes it, then use the ring speed. + rb_lim = None + rb_md = self.sm['liveMapDataNAP'] if self.sm.valid.get('liveMapDataNAP', False) else None + rb_hint = live_map_roundabout_hint(rb_md) + # Oct 13: right blinker on the ring + actually leaving it releases the + # ring cap early; otherwise it holds until the car is off the ring. + if not hasattr(self, "_rb_exit_gate"): + self._rb_exit_gate = RingExitGate() + if self._rb_exit_gate.update(rb_hint, bool(getattr(CS, "rightBlinker", False)), curve_kappa, DT_CTRL): + rb_hint = None + if rb_hint is not None: + posted_ms = float(md.speedLimit) if md is not None and md.speedLimit > 0 else float(CS.vEgo) + rb_lim = roundabout_ease_v_ms(rb_hint, float(CS.vEgo), posted_ms, self._map_speed_lookahead) + if rb_lim is not None and map_valid and md is not None: + lim = rb_lim if lim is None else min(float(lim), rb_lim) + was_on_ring = bool(getattr(self, "_rb_active", False)) + exiting_ring = was_on_ring and rb_lim is None + if exiting_ring: + ring_kph = float(getattr(self, "_rb_target_ms", 0.0) or 0.0) * CV.MS_TO_KPH + if _unwind_ring_speed_set(self._map_hold, getattr(self, "_rb_pre", None), ring_kph): + dec.sticky = self._map_hold.sticky_set_kph is not None + dec.follow_override = bool(dec.sticky) + if not dec.sticky and map_valid and md is not None: + lim = effective_map_limit_ms( + float(md.speedLimit), + float(md.nextSpeedLimit), + float(md.nextSpeedLimitDistance), + float(CS.vEgo), + self._map_speed_lookahead, + self._map_speed_accel, + sticky=False, + ) + if map_valid and md is not None and lim is not None and lim > 0: + if rb_lim is not None: + # Instant RB latch: MAX is the ring target now. Do not Accel-5 + # slew over another 100 m after long enables in the funnel. + self._map_slew_ms = float(lim) + map_kph = float(lim) * CV.MS_TO_KPH + else: + if self._map_slew_ms is None: + hud_kph = float(self.v_cruise_helper.v_cruise_kph) + prev_ms = map_slew_from_displayed_kph(hud_kph, map_offset_kph) + if 0.0 < hud_kph < V_CRUISE_UNSET and prev_ms > lim + 0.3: + self._map_slew_ms = prev_ms + else: + self._map_slew_ms = lim + a = map_slew_a_ms2( + self._map_slew_ms, lim, self._map_speed_lookahead, self._map_speed_accel, + ) + if lim < self._map_slew_ms and str(getattr(md, "source", "") or "") == MAP_SOURCE_DEFAULT: + # Oct 13: an untagged state default never brakes harder than -0.5. + a = min(float(a), DEFAULT_DROP_A_MS2) + if getattr(self, "_rb_restoring", False): + if lim > self._map_slew_ms + 0.05: + # Oct 13: ring exit restores at 1.5–2 mph/s (was ~0.8, he pressed gas). + a = max(float(a), RB_EXIT_RESTORE_MS2) + else: + self._rb_restoring = False + self._map_slew_ms = slew_map_speed_ms(self._map_slew_ms, lim, DT_CTRL, a) + map_kph = self._map_slew_ms * CV.MS_TO_KPH + elif map_valid and md is not None: + self._map_slew_ms = None + elif not map_valid: + self._map_slew_ms = None + # seed_kph is a one-shot write (engage, posted raise, stalk step). + # Sticky hold uses driver_kph / follow_override — do not write pedal + # every frame or CI.update's stalk step is undone. + if dec.seed_kph is not None: + preap_v_cruise_kph = dec.seed_kph + self._map_slew_ms = map_slew_from_displayed_kph(dec.seed_kph, map_offset_kph) + else: + preap_v_cruise_kph = apply_map_speed_kph( + dec.driver_kph, + map_kph, + mode=self._map_speed_mode, + offset_kph=map_offset_kph, + engaged=session_engaged, + op_long_software_cruise=True, + driver_override=dec.follow_override, + ) + ring_capped = False + if rb_lim is not None: + rb_kph = float(rb_lim) * CV.MS_TO_KPH + # The ring ceiling is the HUD MAX only. A higher set stays the + # resume target so a SET in the ring cannot latch the ring speed. + if float(preap_v_cruise_kph) > rb_kph + MANUAL_SET_EPS_KPH: + ring_capped = True + preap_v_cruise_kph = min(float(preap_v_cruise_kph), rb_kph) + self._map_slew_ms = float(rb_lim) + # Temporary curve cap may lower HUD MAX. Restore seed puts pre-curve + # MAX back after the bend. Do not let that cap rebase sticky / held. + curve_out = self._curve_max.finish( + hud_kph=preap_v_cruise_kph, + hold=self._map_hold, + posted_kph=posted_kph, + v_ego_ms=float(CS.vEgo), + angle_steers_deg=steer_deg, + steer_ratio=float(getattr(self.CP, 'steerRatio', 0.0) or 0.0), + wheelbase=float(getattr(self.CP, 'wheelbase', 0.0) or 0.0), + engaged=session_engaged and not curve_follow_on, + stalk_pressed=stalk_pressed, + take_speed_now=take_speed_now, + dt=DT_CTRL, + curvature=curve_kappa, + yaw_rate=curve_yaw, + restore_a_ms2=map_accel_a_ms2(self._map_speed_lookahead, self._map_speed_accel), + long_active=soft_long, + ) + log_curve_max(self, curve_out, preap_v_cruise_kph, posted_kph, CS) + preap_v_cruise_kph = float(curve_out.hud_kph) + restore_seed_kph = curve_out.restore_seed_kph + seed_kph = dec.seed_kph if restore_seed_kph is None else float(restore_seed_kph) + if restore_seed_kph is not None: + self._map_slew_ms = map_slew_from_displayed_kph(float(restore_seed_kph), map_offset_kph) + if exiting_ring: + # Leave the ring at least at current speed and ramp toward the + # posted / pre-ring MAX. MAX stays a hard ceiling (the slew target). + # Gap lock still owns the lead gap; this does not raise it. + floor_ms = max(float(getattr(self, "_rb_target_ms", 0.0) or 0.0), float(CS.vEgo)) + target_ms = _ring_exit_target_ms(self._map_hold, None if dec.sticky else lim, posted_kph, + getattr(self, "_rb_detect_v_ms", None)) + preap_v_cruise_kph, self._map_slew_ms = _apply_ring_exit_max( + target_ms, floor_ms, self._map_speed_lookahead, self._map_speed_accel, + ) + self._rb_restoring = True + # Write engage/posted/stalk seed, or when HUD MAX rose. Never write + # the same sticky MAX every frame. Pause still writes a rebase / + # resume seed onto pedal_speed so one SET keeps the held MAX. + # Curve restore is a one-shot seed so MAX returns to the pre-bend set. + write_max = long_active or soft_long or resume_held or take_speed_now or ( + session_engaged and seed_kph is not None + ) + if write_max and should_write_preap_pedal(seed_kph, preap_v_cruise_kph, self._last_pedal_kph) and not ring_capped: + self._write_preap_pedal_speed(CS, preap_v_cruise_kph) + self._last_pedal_kph = float(preap_v_cruise_kph) + self._pedal_self_write_kph = float(preap_v_cruise_kph) + elif not session_enabled: + self._last_pedal_kph = None + self._pedal_self_write_kph = None + if rb_lim is not None: + # Latch / unwind key on the ring target, not the approach profile + # value (rb_lim ramps down along the 0.7 m/s² profile). + rb_target_ms = roundabout_target_ms(rb_hint.speed_limit_ms) + ring_kph = rb_target_ms * CV.MS_TO_KPH + if not was_on_ring or getattr(self, "_rb_pre", None) is None: + self._rb_pre = _snapshot_cruise_hold(self._map_hold) + self._rb_detect_v_ms = float(CS.vEgo) + else: + _refresh_ring_snapshot(self._rb_pre, self._map_hold, ring_kph) + _unwind_ring_speed_set(self._map_hold, self._rb_pre, ring_kph) + eng = self._preap_engagement() + if eng is not None and _kph_near(getattr(eng, "_nap_held_max_kph", None), ring_kph): + restore = None if self._rb_pre is None else self._rb_pre.get("held_max_kph") + if restore is not None and not _kph_near(restore, ring_kph): + eng._nap_held_max_kph = restore + self._rb_target_ms = rb_target_ms + self._rb_active = True + else: + self._rb_active = False + self.v_cruise_helper.v_cruise_kph_last = self.v_cruise_helper.v_cruise_kph + self.v_cruise_helper.v_cruise_kph = preap_v_cruise_kph + self.v_cruise_helper.v_cruise_cluster_kph = preap_v_cruise_kph + + def _curve_cornering(self) -> tuple[float | None, float | None]: + """Vehicle-model curvature, else livePose yaw rate. None if not yet valid. + + controlsd publishes the learned-ratio / angle-offset curvature on + carControl.currentCurvature (the same value as controlsState.curvature). + card already receives carControl, so this is a field read, not another + 100 Hz poll. livePose stays the low-rate yaw fallback only. + """ + curvature = None + yaw_rate = None + if self.sm.valid.get('carControl', False): + curvature = float(self.sm['carControl'].currentCurvature) + if self.sm.valid.get('livePose', False): + av = self.sm['livePose'].angularVelocityDevice + if bool(getattr(av, 'valid', False)): + yaw_rate = float(av.z) + return curvature, yaw_rate + + def _preap_engagement(self): + inner = getattr(self.CI, 'CS', None) + return getattr(inner, 'engagement', None) if inner is not None else None + + def _preap_set_events(self) -> tuple[bool, bool]: + """Consume one-shot SET flags from the Pre-AP engagement patch. + + resume_held: one SET after a brake long pause. + take_speed_now: double SET / initial engage (forget sticky). + """ + eng = self._preap_engagement() + resume = bool(getattr(eng, '_nap_set_resume_long', False)) + take = bool(getattr(eng, '_nap_set_take_speed_now', False)) + if eng is not None: + eng._nap_set_resume_long = False + eng._nap_set_take_speed_now = False + return resume, take + + def _adopt_preap_fsm_held_max(self) -> None: + """If overlay never latched MAX, take the brake/turn FSM hold. + + Maps off does not invent posted. A stalk-set pedal MAX can exist on + the FSM latch while MapCruiseHold.held_max_kph is still None. Adopting + it before pause substitution prevents writing ego into held. + """ + if self._map_hold.held_max_kph is not None: + return + eng = self._preap_engagement() + held = getattr(eng, '_nap_held_max_kph', None) if eng is not None else None + if held is not None and 0.0 < float(held) < V_CRUISE_UNSET: + self._map_hold.held_max_kph = float(held) + + def _publish_preap_held_max(self, *, long_active: bool) -> None: + """Keep the FSM latch in sync with overlay held while software long is on.""" + if not long_active or self._map_hold.held_max_kph is None: + return + eng = self._preap_engagement() + if eng is not None: + eng._nap_held_max_kph = float(self._map_hold.held_max_kph) + + def _preap_cruise_detent(self) -> int | None: + """Raw SpdCtrlLvr_Stat / CruiseButtons. Distinguishes tip vs 2nd detent.""" + inner = getattr(self.CI, "CS", None) + if inner is None: + return None + if hasattr(inner, "cruise_buttons"): + try: + return int(inner.cruise_buttons) + except (TypeError, ValueError): + pass + msg = getattr(inner, "msg_stw_actn_req", None) + if isinstance(msg, dict): + try: + return int(msg.get("SpdCtrlLvr_Stat") or 0) + except (TypeError, ValueError): + return None + return None + + def _maybe_follow_stalk(self, CS, raw_kph: float) -> tuple[float, bool]: + """Route Pre-AP stalk tip to City or Highway Follow Distance with a lead. + + Same whether Hypermile is On or Off. A first-detent tip undoes that + frame's 1 mph MAX and, after the lever returns to IDLE without a + 2nd detent, steps the matching 1–7: Highway when MAX is 50 mph or + higher (including while ego is still coming up to that set speed), + City when MAX is under 50 even if ego is already faster. Traveled + speed picks the band only when MAX is unset. HUD NAPFollowDistance + tracks the band just stepped. A full press (2nd detent / 5 mph) + keeps MAX +5/−5 and does not remap Follow, even if the lever passed + through first detent. + No lead: leave stalk as MAX adjust. During a long pause, + cruiseState.speed is ego — detent still distinguishes tip vs hold; + buttonEvents alone do not. + """ + has_lead = bool( + self.sm.valid.get("radarState", False) + and getattr(self.sm["radarState"].leadOne, "status", False) + ) + soft_long = bool(getattr(CS, "enableLongControl", False)) + prev_raw = None + try: + prev_raw = float(self.CS_prev.cruiseState.speed) * CV.MS_TO_KPH + except Exception: + prev_raw = None + events = getattr(CS, "buttonEvents", None) + commit, closer, undo = self._follow_gesture.update( + has_lead=has_lead, + detent=self._preap_cruise_detent(), + button_closer=button_event_closer(events), + button_released=button_event_released(events), + raw_kph=raw_kph if soft_long else None, + prev_raw_kph=prev_raw if soft_long else None, + ) + routed = commit or self._follow_gesture.is_pending or undo is not None + if commit and closer is not None and (time.monotonic() - self._follow_stalk_mono) >= 0.25: + # CarState.vCruise is still 0 here — card publishes it at the end of + # the frame. Read the HUD MAX already on the helper. + v_cruise_ms = published_cruise_ms(self.v_cruise_helper.v_cruise_kph, V_CRUISE_UNSET) + persist_follow_distance( + self.params, bool(closer), + v_ego=getattr(CS, "vEgo", None), + v_cruise=v_cruise_ms, + has_lead=has_lead, + engaged=soft_long, + ) + self._follow_stalk_mono = time.monotonic() + if undo is not None and soft_long: + self._write_preap_pedal_speed(CS, undo) + self._last_pedal_kph = float(undo) + self._pedal_self_write_kph = float(undo) + return float(undo), True + return raw_kph, routed + + @staticmethod + def _preap_stalk_set_pressed(CS) -> bool: + """True on stalk +/-. Extra signal; pedal_speed 1/5 mph steps also count.""" + for be in getattr(CS, 'buttonEvents', None) or []: + try: + typ = getattr(be, 'type', None) + name = str(getattr(typ, 'name', typ)).lower().replace('_', '') + if 'accelcruise' in name or 'decelcruise' in name or name in ('accel', 'decel'): + return True + except Exception: + continue + return False + + def _write_preap_pedal_speed(self, CS, kph: float) -> None: + """Write HUD MAX into pre-AP pedal_speed so long / stalk +/- track that set.""" + kph = float(kph) + try: + CS.cruiseState.speed = kph * CV.KPH_TO_MS + except Exception: + pass + inner = getattr(self.CI, 'CS', None) + if inner is None: + return + if hasattr(inner, 'pedal_speed_kph'): + inner.pedal_speed_kph = kph + eng = getattr(inner, 'engagement', None) + if eng is not None and hasattr(eng, 'pedal_speed_kph'): + eng.pedal_speed_kph = kph + eng._nap_held_max_kph = kph + + def state_publish(self, CS: car.CarState, RD: structs.RadarDataT | None): """carState and carParams publish loop""" # carParams - logged every 50 seconds (> 1 per segment) if self.sm.frame % int(50. / DT_CTRL) == 0: cp_send = messaging.new_message('carParams') cp_send.valid = True - cp_send.carParams = self.CP_capnp + cp_send.carParams = self.CP self.pm.send('carParams', cp_send) # publish new carOutput co_send = messaging.new_message('carOutput') co_send.valid = self.sm.all_checks(['carControl']) - co_send.carOutput.actuatorsOutput = convert_to_capnp(self.last_actuators_output) + co_send.carOutput.actuatorsOutput = self.last_actuators_output self.pm.send('carOutput', co_send) # kick off controlsd step while we actuate the latest carControl packet @@ -221,6 +868,41 @@ def state_publish(self, CS: car.CarState): cs_send.carState.canErrorCounter = self.can_rcv_cum_timeout_counter cs_send.carState.cumLagMs = -self.rk.remaining * 1000. self.pm.send('carState', cs_send) + if self._tesla_preap: + from openpilot.selfdrive.car.tesla.preap_body_controls import note_published_car_state + note_published_car_state(cs_send.carState) + + if RD is not None: + tracks_msg = messaging.new_message('liveTracks') + tracks_msg.valid = not any(RD.errors.to_dict().values()) + tracks_msg.liveTracks = RD + self.pm.send('liveTracks', tracks_msg) + + def _preap_lat_yield_flag(self, CC: car.CarControl): + """Host-only 0x561. Widens yield-not-disengage. Never an actuation bit. + + Panda drops the frame (tx hook returns false). Stuck true means a + steering yank yields lateral instead of ending the session, which is + the existing yielded-lateral rule. Stuck false is today's disengage + plus the local angle-error help check. Doors, gear, stalk, brake, + and an EPAS reject with hands off still disengage. + """ + from opendbc.car.tesla.preap.lat_yield import ( + UNDERTRACK_CURVATURE, YIELD_FLAG_ADDR, encode_yield_flag, roundabout_yield_context) + + md = self.sm['liveMapDataNAP'] if self.sm.alive.get('liveMapDataNAP', False) else None + hint = live_map_roundabout_hint(md) + on_rb = bool(hint is not None and roundabout_yield_context( + hint.on_roundabout, hint.approaching, hint.distance_m)) + try: + under = abs(float(CC.actuators.curvature) - float(CC.currentCurvature)) > UNDERTRACK_CURVATURE + except (TypeError, ValueError): + under = False + eng = getattr(getattr(self.CI, "CS", None), "engagement", None) + if eng is not None: + eng._nap_roundabout_yield = on_rb + eng._nap_undertrack = bool(under) + return (YIELD_FLAG_ADDR, encode_yield_flag(on_rb, under), 0) def controls_update(self, CS: car.CarState, CC: car.CarControl): """control update loop, driven by carControl""" @@ -230,38 +912,84 @@ def controls_update(self, CS: car.CarState, CC: car.CarControl): # TODO: this can make us miss at least a few cycles when doing an ECU knockout self.CI.init(self.CP, *self.can_callbacks) # signal pandad to switch to car safety mode - self.params.put_bool_nonblocking("ControlsReady", True) + self.params.put_bool("ControlsReady", True) if self.sm.all_alive(['carControl']): # send car controls over can now_nanos = self.can_log_mono_time if REPLAY else int(time.monotonic() * 1e9) - self.last_actuators_output, can_sends = self.CI.apply(convert_carControl(CC), now_nanos) + self.last_actuators_output, can_sends = self.CI.apply(CC, now_nanos) + can_sends = list(can_sends) + if getattr(self, "_tesla_preap", False): + can_sends.append(self._preap_lat_yield_flag(CC)) + if self.radar_donor_vin is not None: + controls_allowed = False + if self.sm.valid['pandaStates']: + controls_allowed = any(ps.controlsAllowed for ps in self.sm['pandaStates']) + force_read = self.params.get_bool("NAPRadarReadVin") + if force_read and not self._nap_conf.radar_enabled: + self.params.put("NAPRadarVinReadStatus", "enable radar first") + self.params.put_bool("NAPRadarReadVin", False) + else: + can_sends.extend(self.radar_donor_vin.update( + self._can_packets, + time.monotonic(), + radar_enabled=self._nap_conf.radar_enabled, + stored_vin=self._nap_conf.radar_donor_vin, + controls_allowed=controls_allowed, + enabled=bool(CC.enabled), + force_read=force_read, + )) + if force_read and self.radar_donor_vin.read_finished: + if not self.radar_donor_vin.reader.vin and self.radar_donor_vin.reader.failure: + self.params.put( + "NAPRadarVinReadStatus", + self.radar_donor_vin.reader.failure.name.lower().replace("_", " "), + ) + self.params.put_bool("NAPRadarReadVin", False) self.pm.send('sendcan', can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid)) self.CC_prev = CC def step(self): - CS = self.state_update() - - self.update_events(CS) - - if not self.sm['carControl'].enabled and self.events.contains(ET.ENABLE): - self.v_cruise_helper.initialize_v_cruise(CS, self.experimental_mode) + CS, RD = self.state_update() - self.state_publish(CS) + self.state_publish(CS, RD) - initialized = (not any(e.name == EventName.controlsInitializing for e in self.sm['onroadEvents']) and + initialized = (not any(e.name == EventName.selfdriveInitializing for e in self.sm['onroadEvents']) and self.sm.seen['onroadEvents']) if not self.CP.passive and initialized: self.controls_update(CS, self.sm['carControl']) self.initialized_prev = initialized - self.CS_prev = CS.as_reader() + self.CS_prev = CS + + def _refresh_map_speed_params(self): + self._curve_follow_mode = read_curve_follow_mode(self.params) + mode, offset, lookahead, accel = read_map_speed_params(self.params) + hm_on = read_hypermile_params(self.params) + self._map_speed_mode = mode + # User / settings offset only. Hypermile eco is computed live from posted. + self._map_speed_user_offset_kph = offset + self._map_hypermile_on = hm_on + self._map_step_down_on = read_hypermile_step_down(self.params) + self._map_speed_lookahead = lookahead + self._map_speed_accel = accel + + def _live_map_offset_kph(self, raw_posted_kph: float | None, + maps_posted: bool | None = None) -> float: + return map_target_offset_kph( + self._map_speed_user_offset_kph, + hypermile_on=self._map_hypermile_on, + step_down_on=self._map_step_down_on, + posted_kph=raw_posted_kph, + maps_posted=maps_posted, + ) def params_thread(self, evt): while not evt.is_set(): self.is_metric = self.params.get_bool("IsMetric") self.experimental_mode = self.params.get_bool("ExperimentalMode") and self.CP.openpilotLongitudinalControl + self._refresh_map_speed_params() time.sleep(0.1) def card_thread(self): diff --git a/selfdrive/car/cruise.py b/selfdrive/car/cruise.py index e2d83033d6ec3d..0d761844b53810 100644 --- a/selfdrive/car/cruise.py +++ b/selfdrive/car/cruise.py @@ -1,8 +1,8 @@ import math +import numpy as np from cereal import car -from openpilot.common.conversions import Conversions as CV -from openpilot.common.numpy_fast import clip +from openpilot.common.constants import CV # WARNING: this value was determined based on the model's training distribution, @@ -53,6 +53,12 @@ def update_v_cruise(self, CS, enabled, is_metric): else: self.v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH self.v_cruise_cluster_kph = CS.cruiseState.speedCluster * CV.MS_TO_KPH + if CS.cruiseState.speed == 0: + self.v_cruise_kph = V_CRUISE_UNSET + self.v_cruise_cluster_kph = V_CRUISE_UNSET + elif CS.cruiseState.speed == -1: + self.v_cruise_kph = -1 + self.v_cruise_cluster_kph = -1 else: self.v_cruise_kph = V_CRUISE_UNSET self.v_cruise_cluster_kph = V_CRUISE_UNSET @@ -103,7 +109,7 @@ def _update_v_cruise_non_pcm(self, CS, enabled, is_metric): if CS.gasPressed and button_type in (ButtonType.decelCruise, ButtonType.setCruise): self.v_cruise_kph = max(self.v_cruise_kph, CS.vEgo * CV.MS_TO_KPH) - self.v_cruise_kph = clip(round(self.v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX) + self.v_cruise_kph = np.clip(round(self.v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX) def update_button_timers(self, CS, enabled): # increment timer for buttons still pressed @@ -127,6 +133,6 @@ def initialize_v_cruise(self, CS, experimental_mode: bool) -> None: if any(b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents) and self.v_cruise_initialized: self.v_cruise_kph = self.v_cruise_kph_last else: - self.v_cruise_kph = int(round(clip(CS.vEgo * CV.MS_TO_KPH, initial, V_CRUISE_MAX))) + self.v_cruise_kph = int(round(np.clip(CS.vEgo * CV.MS_TO_KPH, initial, V_CRUISE_MAX))) self.v_cruise_cluster_kph = self.v_cruise_kph diff --git a/selfdrive/car/helpers.py b/selfdrive/car/helpers.py deleted file mode 100644 index f4d899346847e1..00000000000000 --- a/selfdrive/car/helpers.py +++ /dev/null @@ -1,72 +0,0 @@ -import capnp -from typing import Any - -from cereal import car -from opendbc.car import structs - -_FIELDS = '__dataclass_fields__' # copy of dataclasses._FIELDS - - -def is_dataclass(obj): - """Similar to dataclasses.is_dataclass without instance type check checking""" - return hasattr(obj, _FIELDS) - - -def _asdictref_inner(obj) -> dict[str, Any] | Any: - if is_dataclass(obj): - ret = {} - for field in getattr(obj, _FIELDS): # similar to dataclasses.fields() - ret[field] = _asdictref_inner(getattr(obj, field)) - return ret - elif isinstance(obj, (tuple, list)): - return type(obj)(_asdictref_inner(v) for v in obj) - else: - return obj - - -def asdictref(obj) -> dict[str, Any]: - """ - Similar to dataclasses.asdict without recursive type checking and copy.deepcopy - Note that the resulting dict will contain references to the original struct as a result - """ - if not is_dataclass(obj): - raise TypeError("asdictref() should be called on dataclass instances") - - return _asdictref_inner(obj) - - -def convert_to_capnp(struct: structs.CarParams | structs.CarState | structs.CarControl.Actuators) -> capnp.lib.capnp._DynamicStructBuilder: - struct_dict = asdictref(struct) - - if isinstance(struct, structs.CarParams): - del struct_dict['lateralTuning'] - struct_capnp = car.CarParams.new_message(**struct_dict) - - # this is the only union, special handling - which = struct.lateralTuning.which() - struct_capnp.lateralTuning.init(which) - lateralTuning_dict = asdictref(getattr(struct.lateralTuning, which)) - setattr(struct_capnp.lateralTuning, which, lateralTuning_dict) - elif isinstance(struct, structs.CarState): - struct_capnp = car.CarState.new_message(**struct_dict) - elif isinstance(struct, structs.CarControl.Actuators): - struct_capnp = car.CarControl.Actuators.new_message(**struct_dict) - else: - raise ValueError(f"Unsupported struct type: {type(struct)}") - - return struct_capnp - - -def convert_carControl(struct: capnp.lib.capnp._DynamicStructReader) -> structs.CarControl: - # TODO: recursively handle any car struct as needed - def remove_deprecated(s: dict) -> dict: - return {k: v for k, v in s.items() if not k.endswith('DEPRECATED')} - - struct_dict = struct.to_dict() - struct_dataclass = structs.CarControl(**remove_deprecated({k: v for k, v in struct_dict.items() if not isinstance(k, dict)})) - - struct_dataclass.actuators = structs.CarControl.Actuators(**remove_deprecated(struct_dict.get('actuators', {}))) - struct_dataclass.cruiseControl = structs.CarControl.CruiseControl(**remove_deprecated(struct_dict.get('cruiseControl', {}))) - struct_dataclass.hudControl = structs.CarControl.HUDControl(**remove_deprecated(struct_dict.get('hudControl', {}))) - - return struct_dataclass diff --git a/selfdrive/modeld/tests/__init__.py b/selfdrive/car/tesla/__init__.py similarity index 100% rename from selfdrive/modeld/tests/__init__.py rename to selfdrive/car/tesla/__init__.py diff --git a/selfdrive/car/tesla/preap_blinker_lat_pause.py b/selfdrive/car/tesla/preap_blinker_lat_pause.py new file mode 100644 index 00000000000000..fbd64147c33b47 --- /dev/null +++ b/selfdrive/car/tesla/preap_blinker_lat_pause.py @@ -0,0 +1,1375 @@ +"""Keep Pre-AP cruiseEnabled while a blinker lamp pauses lateral. + +opendbc's handle_steering_disengage tears down the FSM on hands-on ≥ 2. +That drop is EventName.pcmDisable — Pre-AP HUD "Steering Disengaged". +GTW lamp bits flash, so BlinkerLateralHold latches turn-active through +those gaps. During that turn we have already released steering, so a +wheel input must not drop cruiseEnabled. After ~1s of continuous dark, +keep that suppression until torque is released so a finishing hand-steer +does not fully disengage NAP. Stalk cancel / door / reverse (gear +out of Drive) still full-teardown via hard_cancel_session so panda's +cruise latch can re-arm. + +A latched *driver turn* (not ALC tip/keep-alive) does **not** drop +longitudinal. enableLongControl stays true; lead/map braking and accel +apply through the turn. Brake still uses the silent long pause: +enableLongControl=False, cruiseEnabled stays, held MAX remembered. +After a brake pause, one stalk SET restores long (skipped double-pull +first-pull) and keeps the held MAX. At a stop, that SET arms resume +but does not take long until a light throttle. A second SET in the +double-pull window forgets sticky and takes posted (maps on + known) +or current traveled speed (maps off / unknown posted). From fully off +in pedal mode, one rolling pull (foot off, brake not held) is that +same lat+long take-speed-now engage. A stop with the foot off arms +wait-for-gas instead of rolling. No-pedal mode still double-pulls. +Tip ALC was already not a driver turn and never used the long-pause path. + +card.py imports tesla.carstate (binding update_preap) before this install. +Patch both the source module and that imported name, or the live path +never sets _nap_* lamps/stalk and a faster corner still full-cancels. + +ALC keep-alive flashes are not a driver turn: do not latch turn-active, +do not drop long, and do not tear down cruise. DAS_bodyControls +turn-indicator TX stays in teslacan / carcontroller from CC.leftBlinker; +this helper does not touch it. + +This follows the same install-from-card pattern as preap_body_controls. + +Panda tesla_preap still has its own hands-on >= 2 path. Matching flash-latch +in tesla_preap.h keeps controls_allowed; selfdrived also hides the +controlsMismatch that would otherwise full-cancel after 2s. +""" + +import time + +from opendbc.car.tesla.preap.lat_yield import encode_hands_stash +from openpilot.common.constants import CV +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import ( + BlinkerLateralHold, + DT_CTRL, + blinker_turn_blocks_steering_disengage, +) +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + EmergencyYankTracker, + is_emergency_yank, +) +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + PARAM_DRIVER_LAT_HANDOFF, + PREAP_FINGERPRINT, + DriverLateralHandoff, + handoff_enabled, +) + +_ORIG_HANDLE = None +_ORIG_UPDATE = None +_ORIG_PROCESS = None +_ORIG_DROP = None +_ORIG_CHECK = None +_ORIG_KICK = None +_installed = False + +# Same floor as controlsd lat standstill: abs(vEgo) <= max(minSteerSpeed, 0.3). +# Pre-AP minSteerSpeed is 0, so 0.3 m/s (~0.7 mph) is "at a stop." +RESUME_STANDSTILL_V_EGO = 0.3 +# Stock interceptor / DI gasPressed is DI > 2. One-Pedal pause is slightly +# more sensitive so a light tip-in latches; keep a tiny deadzone above coast. +# Must match opendbc nap_conf.ONE_PEDAL_GAS_DI_PRESSED / PEDAL_DI_PRESSED. +ONE_PEDAL_GAS_DI_PRESSED = 1.0 +PEDAL_DI_PRESSED_STOCK = 2.0 +# One sample this far above coast is a real press. Anything softer has to +# hold for five 100 Hz frames (50 ms) before it pauses long. Oct 7: a +# reading shorter than 0.1 s latched the pause and the car fell into +# Tesla lift regen. +ONE_PEDAL_GAS_FIRM_DI = 4.0 +ONE_PEDAL_GAS_CONFIRM_FRAMES = 5 +_GAS_BLIP_SAME_CYCLE_S = 0.005 + + +def one_pedal_gas_for_pause(interceptor_di) -> bool: + """True when interceptor DI is enough to pause One-Pedal Long. + + Stock `gasPressed` / OVERRIDE stays DI > 2. Pause is DI > 1 so a light + tip-in latches; foot at coast (0) does not. + """ + if interceptor_di is None: + return False + return float(interceptor_di) > ONE_PEDAL_GAS_DI_PRESSED + + +def _gas_blip_now(engagement) -> float: + """monotonic, or `_gas_blip_clock` when a test steps frames by hand.""" + clock = getattr(engagement, "_gas_blip_clock", None) + if clock is not None: + try: + return float(clock) + except (TypeError, ValueError): + pass + return time.monotonic() + + +def _remember_gas_sample(engagement, di) -> None: + """Keep the hottest pedal sample in this unconfirmed window for the log.""" + raw = getattr(engagement, "_nap_gas_sensor", None) + snap = dict(raw) if isinstance(raw, dict) else {} + snap["di"] = di + snap["di_pedal"] = getattr(engagement, "_nap_di_pedal_pos", None) + peak = getattr(engagement, "_gas_blip_peak", None) + peak_di = None if not isinstance(peak, dict) else peak.get("di") + if peak is None or di is None or peak_di is None or float(di) >= float(peak_di): + engagement._gas_blip_peak = snap + + +def _log_one_pedal_pedal(engagement, kind: str, frames: int) -> None: + """qlog line (errorLogMessage) with the raw GAS_SENSOR / GAS_COMMAND fields. + + No new carState subscriber. The parser values are stashed on the + engagement object before the kick runs. + """ + try: + import json + peak = getattr(engagement, "_gas_blip_peak", None) + raw = peak if isinstance(peak, dict) else (getattr(engagement, "_nap_gas_sensor", None) or {}) + rec = { + "kind": kind, + "frames": int(frames), + "di": raw.get("di", getattr(engagement, "_gas_blip_di", None)), + "di_pedal": raw.get("di_pedal", getattr(engagement, "_nap_di_pedal_pos", None)), + "gas": raw.get("gas"), + "gas2": raw.get("gas2"), + "state": raw.get("state"), + "idx": raw.get("idx"), + "gas_cmd": raw.get("gas_cmd"), + "gas_cmd2": raw.get("gas_cmd2"), + } + cloudlog.error("gasblip " + json.dumps(rec, separators=(",", ":"))) + except Exception: + pass + + +def note_one_pedal_gas_sample(engagement, *, above: bool, firm: bool, now: float) -> bool: + """True when this pedal sample is allowed to pause long. + + DI > 4 confirms on that sample. A lighter reading has to stay above + the pause gate for five control frames. Two calls in one 100 Hz cycle + (carstate kick, then the overlay kick) count as one frame. + """ + last = float(getattr(engagement, "_gas_blip_mono", 0.0) or 0.0) + same = last > 0.0 and (float(now) - last) < _GAS_BLIP_SAME_CYCLE_S + if firm: + engagement._gas_blip_frames = ONE_PEDAL_GAS_CONFIRM_FRAMES + engagement._gas_blip_confirmed = True + if not same: + engagement._gas_blip_mono = float(now) + return True + if same: + return bool(getattr(engagement, "_gas_blip_confirmed", False)) + frames = int(getattr(engagement, "_gas_blip_frames", 0) or 0) + if above: + frames += 1 + else: + if 0 < frames < ONE_PEDAL_GAS_CONFIRM_FRAMES: + _log_one_pedal_pedal(engagement, "ignored", frames) + frames = 0 + engagement._gas_blip_peak = None + confirmed = frames >= ONE_PEDAL_GAS_CONFIRM_FRAMES + engagement._gas_blip_frames = frames + engagement._gas_blip_mono = float(now) + engagement._gas_blip_confirmed = confirmed + return confirmed + + +def _filtered_one_pedal_gas_kick(self, gas_pressed, one_pedal_long, interceptor_di=None): + """Installed over PreAPEngagement.maybe_one_pedal_gas_kick. + + A from-rest blip shorter than 50 ms does not reach the latch. A firm + sample, a press with no sensor reading, an engage-while-gas arm, and + an already-latched pause still go straight through, so a real press + pauses on that frame. Samples before the first foot-off rest are not + debounced: hiding them would set the rest flag and pause on the next + frames. + """ + if _ORIG_KICK is None or not bool(one_pedal_long): + return _ORIG_KICK(self, gas_pressed, one_pedal_long, interceptor_di) + di = None + if interceptor_di is not None: + try: + di = float(interceptor_di) + except (TypeError, ValueError): + di = None + self._gas_blip_di = di + above = bool(gas_pressed) or (di is not None and di > ONE_PEDAL_GAS_DI_PRESSED) + # No sensor sample means the caller asserted gas. That is a deliberate + # press, not the one-frame interceptor spike seen at the roundabout. + firm = (di is not None and di > ONE_PEDAL_GAS_FIRM_DI) or ( + bool(gas_pressed) and interceptor_di is None + ) + armed = bool(getattr(self, "_one_pedal_armed_with_gas", False)) + was_latched = bool(getattr(self, "_one_pedal_pause_latched", False)) + # Engage-while-gas has not had a foot-off rest yet. Hiding that sample + # would look like a release and set the rest flag, so the next frames + # would pause. Only a from-rest takeover is debounced. + at_rest = bool(getattr(self, "_one_pedal_had_long_at_rest", False)) + debounce = at_rest and not armed and not was_latched + if above and (debounce or firm): + _remember_gas_sample(self, di) + if debounce or firm: + confirmed = note_one_pedal_gas_sample( + self, above=above, firm=firm, now=_gas_blip_now(self)) + else: + confirmed = False + if firm or confirmed or not debounce or not above: + paused = _ORIG_KICK(self, gas_pressed, one_pedal_long, interceptor_di) + if paused and not was_latched: + _log_one_pedal_pedal(self, "pause", int(getattr(self, "_gas_blip_frames", 0) or 0)) + self._gas_blip_peak = None + return paused + return _ORIG_KICK(self, False, one_pedal_long, 0.0) + + +def _peek_pedal_raw(can_parsers) -> dict: + """GAS_SENSOR and, when the parser has it, GAS_COMMAND. Empty if absent.""" + out = {} + try: + from opendbc.car import Bus + buses = [] + for name in ("ap_party", "party", "pt", "chassis"): + bus = getattr(Bus, name, None) + if bus is not None: + buses.append(bus) + for bus in buses: + try: + vl = can_parsers[bus].vl + except Exception: + continue + getter = getattr(vl, "get", None) + if getter is None: + continue + sens = getter("GAS_SENSOR") or {} + if sens: + out["gas"] = sens.get("INTERCEPTOR_GAS") + out["gas2"] = sens.get("INTERCEPTOR_GAS2") + out["state"] = sens.get("STATE") + out["idx"] = sens.get("IDX") + cmd = getter("GAS_COMMAND") or {} + if cmd: + out["gas_cmd"] = cmd.get("GAS_COMMAND") + out["gas_cmd2"] = cmd.get("GAS_COMMAND2") + except Exception: + return out + return out + + +def maybe_one_pedal_overlay_kick(engagement, interceptor_di) -> bool: + """Light tip-in extra kick after orig stock gasPressed kick. + + Do **not** fire on a stock falling edge this cycle: that is lift + through DI 1–2 after engage/SET-while-gas, not a from-rest tip-in. + `_one_pedal_armed_with_gas` is the same grace until interceptor DI + is fully off. If extra does not fire, clear `_one_pedal_gas_falling_edge` + so the next real from-rest press is still a takeover. + """ + falling = bool(getattr(engagement, "_one_pedal_gas_falling_edge", False)) + armed = bool(getattr(engagement, "_one_pedal_armed_with_gas", False)) + if armed: + if one_pedal_gas_for_pause(interceptor_di): + return False + engagement._one_pedal_armed_with_gas = False + if bool(getattr(engagement, "enableLongControl", False)): + engagement._one_pedal_had_long_at_rest = True + if falling: + engagement._one_pedal_gas_falling_edge = False + return False + if not one_pedal_gas_for_pause(interceptor_di): + if falling: + engagement._one_pedal_gas_falling_edge = False + return False + if falling: + engagement._one_pedal_gas_falling_edge = False + return False + if not hasattr(engagement, "maybe_one_pedal_gas_kick"): + return False + return bool(engagement.maybe_one_pedal_gas_kick( + True, True, interceptor_di=interceptor_di)) + + +def _peek_blinker_lamps(can_parsers): + try: + from opendbc.car import Bus + gtw = can_parsers[Bus.chassis].vl["GTW_carState"] + return gtw["BC_indicatorLStatus"] == 1, gtw["BC_indicatorRStatus"] == 1 + except Exception: + return False, False + + +def _peek_hands_on_level(can_parsers) -> int: + """Raw EPAS_handsOnLevel 0/1/2/3. 1 = still on the rim (soft-yield hold).""" + try: + from opendbc.car import Bus + epas = can_parsers[Bus.chassis].vl["EPAS_sysStatus"] + return int(epas.get("EPAS_handsOnLevel", 0) or 0) + except Exception: + return 0 + + +def _publish_hands_on_level(ret, hands: int, full_control: bool = True) -> None: + """Expose EPAS hands-on to controlsd for soft lat hold. + + Prefer cereal handsOnLevel when the schema has it. Also stash the + discrete 0/1/2/3 on steeringTorqueEps (unused on Pre-AP angle control) + so a nap-dev-only PR works without an opendbc cereal bump. + + The same float carries one more bit: hands + 0.25 means lateral was + yielded at this frame (see opendbc preap/lat_yield.py). car_specific + reads it to decide whether a hands-on edge raises steerDisengage (A) or + not (B). cs_hands_on_level rounds, so the level still decodes. + """ + hands = int(max(0, min(3, hands))) + if hasattr(ret, 'handsOnLevel'): + try: + ret.handsOnLevel = hands + except Exception: + pass + if hasattr(ret, 'steeringTorqueEps'): + try: + ret.steeringTorqueEps = encode_hands_stash(hands, bool(full_control)) + except Exception: + pass + + +def _publish_real_brake(ret, applied: bool) -> None: + """Expose digital Applied without setting brakePressed. + + Pre-AP keeps brakePressed=False so generic OP brake-to-disengage never + fires. driverBrakeApplied is that switch. CS.brake stays the 1.0/0.0 + fallback controlsd and the lateral handoff already read. + """ + if hasattr(ret, 'brake'): + try: + ret.brake = 1.0 if applied else 0.0 + except Exception: + pass + if hasattr(ret, 'driverBrakeApplied'): + try: + ret.driverBrakeApplied = bool(applied) + except Exception: + pass + + +def _handoff_for(engagement) -> DriverLateralHandoff: + h = getattr(engagement, "_nap_lat_handoff", None) + if h is None: + h = DriverLateralHandoff(enabled=True) + engagement._nap_lat_handoff = h + return h + + +def _handoff_param_on() -> bool: + try: + from openpilot.common.params import Params + return bool(Params().get_bool(PARAM_DRIVER_LAT_HANDOFF)) + except Exception: + return True + + +def hard_cancel_session(engagement) -> None: + """Full OP session teardown (hard cancel), not silent long pause. + + Same FSM contract as stalk cancel / door / gear-out-of-Drive / + hands-on >= 2: cruiseEnabled down, held MAX forgotten, disengage + chime via pcmDisable + long falling while lat is also down. Sets + preap_cc_cancel_needed so the carcontroller spoofs CANCEL (stock CC + off). That spoof is TX-only — panda does not RX it, so it cannot + clear cruise_engaged_prev the way a real stalk disable does. + tesla_preap therefore pcm_cruise_check(false) on every non-Drive + 0x118 (latch already gone before Drive return). Drive SET while + !allowed is last-resort only. TX CANCEL while already disallowed + also clears the latch (spoof path). + Do not call _drop_longitudinal_keep_lateral. + """ + was_long = bool(getattr(engagement, "enableLongControl", False)) + engagement.cruiseEnabled = False + engagement.enableLongControl = False + engagement.enableJustCC = False + engagement.pending_enable = False + engagement.pedal_speed_kph = 0.0 + engagement.stalk_pull_time_ms = 0 + engagement.prev_stalk_pull_time_ms = -1000 + if hasattr(engagement, "pending_cancel_at_ms"): + engagement.pending_cancel_at_ms = 0 + if hasattr(engagement, "_clear_pedal_unavailable"): + engagement._clear_pedal_unavailable() + _clear_session_max_flags(engagement) + engagement.preap_cc_cancel_needed = True + if was_long: + engagement.longCtrlEvent = "pccDisabled" + h = getattr(engagement, "_nap_lat_handoff", None) + if h is not None: + h.reset() + + +# Card latched cruise, but openpilot never took the engage (startup, +# noEntry, or a rising edge consumed while update_events returned early). +ORPHAN_SESSION_S = 0.75 + + +def silent_cancel_session(engagement) -> None: + """Drop a latched Pre-AP session without a disengage chime. + + Same clears as hard_cancel_session, including the stock-CC cancel + spoof, but longCtrlEvent is left alone so pedalCruiseDisabled does + not fire. The next stalk pull is a fresh engage. + """ + engagement.cruiseEnabled = False + engagement.enableLongControl = False + engagement.enableJustCC = False + engagement.pending_enable = False + engagement.pedal_speed_kph = 0.0 + engagement.stalk_pull_time_ms = 0 + engagement.prev_stalk_pull_time_ms = -1000 + if hasattr(engagement, "pending_cancel_at_ms"): + engagement.pending_cancel_at_ms = 0 + if hasattr(engagement, "_clear_pedal_unavailable"): + engagement._clear_pedal_unavailable() + _clear_session_max_flags(engagement) + engagement.preap_cc_cancel_needed = True + h = getattr(engagement, "_nap_lat_handoff", None) + if h is not None: + h.reset() + + +def reconcile_orphan_session(engagement, *, op_enabled: bool, orphan_s: float, + dt: float = DT_CTRL, cereal_cs=None, + interface_cs=None) -> tuple[float, bool]: + """Quietly reset the session if openpilot has not engaged within 0.75 s. + + Returns (orphan_timer_s, canceled_this_frame). + """ + if engagement is None: + return 0.0, False + if bool(getattr(engagement, "cruiseEnabled", False)) and not bool(op_enabled): + orphan_s = float(orphan_s) + float(dt) + else: + return 0.0, False + if orphan_s + 1e-12 < ORPHAN_SESSION_S: + return orphan_s, False + silent_cancel_session(engagement) + if interface_cs is not None: + interface_cs.cruiseEnabled = False + interface_cs.enableLongControl = False + interface_cs.enableJustCC = False + interface_cs.pedal_speed_kph = 0.0 + interface_cs.preap_cc_cancel_needed = True + if hasattr(interface_cs, "cruise_enabled_prev"): + interface_cs.cruise_enabled_prev = False + if cereal_cs is not None: + try: + cereal_cs.cruiseState.enabled = False + except Exception: + pass + try: + cereal_cs.enableLongControl = False + except Exception: + pass + return 0.0, True + + +def _check_can_engage(self, door_open, gear_shifter, seatbelt_unlatched): + """Door / gear-out-of-Drive / seatbelt must full-teardown, not a partial reset. + + Orig check_can_engage zeros cruiseEnabled / long but leaves sticky MAX, + soft-lat yield, stalk timers, and preap_cc_cancel_needed unset. Panda + tesla_preap pcm_cruise_check(false) while not in Drive so the latch + is already gone before Drive return. The CANCEL spoof still drops + stock CC (TX-only; latch is panda). Without this wrapper, sticky MAX + / soft-lat yield would survive Reverse. + """ + from opendbc.car import structs + + in_drive = gear_shifter == structs.CarState.GearShifter.drive + can_engage = not door_open and in_drive and not seatbelt_unlatched + if not can_engage and self.cruiseEnabled: + hard_cancel_session(self) + return can_engage + + +def update_card_lat_handoff(engagement, *, engaged: bool, + lat_would_be_active: bool, + steering_torque: float, steering_rate_deg: float, + hands_on_level: int, brake_applied: bool, + a_ego: float, v_ego: float, + alc_active: bool = False, + blinker_paused: bool = False, + steering_pressed: bool = False, + steering_angle_deg: float | None = None, + dt: float | None = None, + param_on: bool | None = None, + commanded_angle_deg: float | None = None, + roundabout_yield: bool = False, + undertrack: bool = False) -> bool: + """Card-local intent tracker. Emergency hard-brake → full session cancel. + + Returns True when this frame tore the session down. Light brake alone + never returns True — engagement.process_buttons still does the silent + long pause. + """ + h = _handoff_for(engagement) + if param_on is None: + param_on = _handoff_param_on() + h.enabled = handoff_enabled( + fingerprint=PREAP_FINGERPRINT, param_on=bool(param_on)) + out = h.update( + engaged=engaged, + lat_would_be_active=lat_would_be_active, + steering_torque=steering_torque, + steering_rate_deg=steering_rate_deg, + alc_active=alc_active, + blinker_paused=blinker_paused, + hands_on_level=hands_on_level, + brake_applied=brake_applied, + a_ego=a_ego, + v_ego=v_ego, + steering_pressed=steering_pressed, + dt=dt, + steering_angle_deg=steering_angle_deg, + commanded_angle_deg=commanded_angle_deg, + roundabout_yield=roundabout_yield, + undertrack=undertrack, + ) + if out.emergency_cancel and engaged: + hard_cancel_session(engagement) + return True + return False + + +def _peek_meas_angle_deg(can_parsers) -> float: + """carState steering angle (positive left), same sign as CS.steeringAngleDeg.""" + try: + from opendbc.car import Bus + epas = can_parsers[Bus.chassis].vl["EPAS_sysStatus"] + return -float(epas.get("EPAS_internalSAS", 0.0) or 0.0) + except Exception: + return 0.0 + + +def _yield_instead_of_disengage(engagement, steering_disengage) -> bool: + """Hands-on edge that should yield lateral instead of ending the session. + + Uses this frame's torque and measured angle (peeked before CarState + update) and the previous type-1 command / roundabout flag. An EPAS + reject with hands off is not a yield. + """ + if not steering_disengage or bool(getattr(engagement, "prev_steering_disengage", False)): + return False + from opendbc.car.tesla.preap.lat_yield import hands_edge_is_yield + return hands_edge_is_yield( + hands=int(getattr(engagement, "_nap_hands", 0) or 0), + torque_nm=float(getattr(engagement, "_nap_torque_nm", 0.0) or 0.0), + commanded_angle_deg=getattr(engagement, "_nap_cmd_angle_deg", None), + measured_angle_deg=float(getattr(engagement, "_nap_meas_angle_deg", 0.0) or 0.0), + undertrack=bool(getattr(engagement, "_nap_undertrack", False)), + roundabout=bool(getattr(engagement, "_nap_roundabout_yield", False)), + ) + + +def _peek_torsion_nm_and_hands(can_parsers): + """Signed torsion (same sign as CS.steeringTorque) and EPAS hands-on 0–3.""" + try: + from opendbc.car import Bus + epas = can_parsers[Bus.chassis].vl["EPAS_sysStatus"] + torque = -float(epas.get("EPAS_torsionBarTorque", 0.0) or 0.0) + hands = int(epas.get("EPAS_handsOnLevel", 0) or 0) + return torque, hands + except Exception: + return 0.0, 0 + + +def _peek_steering_override(can_parsers): + """(steering_pressed, steering_disengage) from EPAS. + + A slightly faster corner hits EPAS_handsOnLevel 2 (steeringDisengage) + before the 5-frame steeringPressed debounce. Counting only the torque + threshold let a flash-gap expire the latch, then the next hands-on + rising edge tore down cruiseEnabled. + """ + try: + from opendbc.car import Bus + from opendbc.car.tesla.values import STEER_THRESHOLD + epas = can_parsers[Bus.chassis].vl["EPAS_sysStatus"] + torque = abs(epas["EPAS_torsionBarTorque"]) > STEER_THRESHOLD + hands = int(epas.get("EPAS_handsOnLevel", 0) or 0) >= 2 + return bool(torque), bool(hands) + except Exception: + return False, False + + +def _peek_steering_pressed(can_parsers): + pressed, disengage = _peek_steering_override(can_parsers) + return pressed or disengage + + +def _peek_stalk_and_speed(can_parsers): + try: + from opendbc.car import Bus + stw = can_parsers[Bus.chassis].vl["STW_ACTN_RQ"] + stalk = int(stw.get("TurnIndLvr_Stat", 0) or 0) + if stalk == 3: # SNA + stalk = 0 + v_kph = can_parsers[Bus.chassis].vl["ESP_B"]["ESP_vehicleSpeed"] + return stalk, float(v_kph) * CV.KPH_TO_MS + except Exception: + return 0, 0.0 + + +def _peek_di_pedal_percent(can_parsers) -> float: + """Parser-scaled DI_pedalPos as 0–100%. SNA / missing → 0.""" + try: + from opendbc.car import Bus + from opendbc.car.tesla.preap.carstate import di_pedal_pos_percent + pos = can_parsers[Bus.pt].vl["DI_torque1"].get("DI_pedalPos", 0) + return di_pedal_pos_percent(pos) + except Exception: + return 0.0 + + +def _peek_gas_pressed(cs, can_parsers) -> bool: + """Light throttle: interceptor (prior frame) or DI_pedalPos this frame.""" + if bool(getattr(getattr(cs, "pedal", None), "gas_pressed", False)): + return True + return _peek_di_pedal_percent(can_parsers) > PEDAL_DI_PRESSED_STOCK + + +def _peek_standstill(can_parsers) -> bool: + try: + from opendbc.car import Bus + sts = can_parsers[Bus.chassis].vl["ESP_B"].get("ESP_vehicleStandstillSts", 0) + return int(sts or 0) == 1 + except Exception: + return False + + +def _hold_for(engagement): + hold = getattr(engagement, "_nap_lat_hold", None) + if hold is None: + hold = BlinkerLateralHold() + engagement._nap_lat_hold = hold + return hold + + +def _hold_kwargs(engagement, dt=None): + kwargs = dict( + alc_active=bool(getattr(engagement, "_nap_alc_active", False)), + v_ego=float(getattr(engagement, "_nap_v_ego", 0.0) or 0.0), + stalk_state=int(getattr(engagement, "_nap_stalk_state", 0) or 0), + ) + if dt is not None: + kwargs["dt"] = dt + return kwargs + + +def _should_drop_long_for_turn(_engagement) -> bool: + """Driver-turn blinker must not pause longitudinal. + + Long stays engaged through a latched turn (lamp, held LEFT/RIGHT, or + flash latch). Brake still uses the silent long-pause path. Kept as a + predicate so SET/resume gates stay readable. + """ + return False + + +def _drop_long_if_driver_turn(_engagement): + """No-op: latching the blinker stalk must not drop enableLongControl. + + ALC tip/keep-alive never set turn_active. Soft-lat Off still pauses + lat in BlinkerLateralHold / controlsd; that is independent of long. + """ + return + + +def _drop_longitudinal_keep_lateral(self): + # Remember that long was released while staying engaged so the next SET + # can restore it in one pull (double-pull's first pull would otherwise + # stay lat-only and demand a second pull inside the window). + # Orig zeros pedal_speed_kph — restore held MAX so one SET does not + # recapture ego and so card can keep sticky across the pause. + if self.cruiseEnabled: + self._nap_long_resume_pending = True + held = float(getattr(self, "pedal_speed_kph", 0.0) or 0.0) + prev_held = getattr(self, "_nap_held_max_kph", None) + if held > 0: + self._nap_held_max_kph = held + elif prev_held is None: + self._nap_held_max_kph = held + result = _ORIG_DROP(self) + held = getattr(self, "_nap_held_max_kph", None) + if self.cruiseEnabled and held is not None: + self.pedal_speed_kph = float(held) + return result + + +def _step_gap_lock(self, cruise_buttons, prev_cruise_buttons, curr_time_ms, use_pedal, qualify_press, brake=False): + """2 s MAIN hold. Long may be paused. Does not touch stalk_pull_time_ms.""" + from openpilot.selfdrive.controls.lib.gap_lock import GapLockGesture, gap_lock_enabled + + gesture = getattr(self, "_nap_gap_lock", None) + if gesture is None: + gesture = GapLockGesture() + self._nap_gap_lock = gesture + gesture.update( + enabled=gap_lock_enabled(self), + use_pedal=bool(use_pedal), + can_valid=getattr(self, "_nap_can_valid", True) is not False, + cruise_buttons=cruise_buttons, + prev=prev_cruise_buttons, + now_ms=float(curr_time_ms or 0), + cruise_on=bool(self.cruiseEnabled), + qualify_press=bool(qualify_press), + brake=bool(brake), + ) + if gesture.cancel_hold: + # Keep a read-back CANCEL inside the spoof echo window for this hold. + self.preap_last_cc_spoof_ms = float(curr_time_ms or 0) + + +def _speed_units(args, kwargs) -> str: + if len(args) >= 3: + return str(args[2] or "MPH") + return str(kwargs.get("speed_units", "MPH") or "MPH") + + +def _take_long_for_gap_lock(self, args, kwargs) -> None: + """A finished hold takes longitudinal so the locked meters are the setpoint.""" + if not self.cruiseEnabled or self.enableLongControl: + return + if not _long_control_allowed(args, kwargs) or _real_brake_pressed(args, kwargs): + return + self.enableLongControl = True + self.enableJustCC = False + self.pending_enable = False + self._nap_set_resume_long = True + self._nap_long_resume_pending = False + self._nap_resume_wait_gas = False + if hasattr(self, "_clear_pedal_unavailable"): + self._clear_pedal_unavailable() + if float(getattr(self, "pedal_speed_kph", 0.0) or 0.0) <= 0.0: + _restore_held_max(self) + if float(getattr(self, "pedal_speed_kph", 0.0) or 0.0) <= 0.0: + self.pedal_speed_kph = type(self)._capture_target_speed( + _v_ego_ms(args, kwargs), _speed_units(args, kwargs)) + gas = _gas_pressed(self) + if hasattr(self, "_clear_one_pedal_pause_latch"): + self._clear_one_pedal_pause_latch() + else: + self._one_pedal_pause_latched = False + # Foot still down: same grace as SET-while-gas, so this hold is not + # immediately re-paused by One-Pedal. A later from-rest press still pauses + # and that pause still clears the lock. + if gas: + self._one_pedal_armed_with_gas = True + self._one_pedal_had_long_at_rest = False + else: + self._one_pedal_had_long_at_rest = True + if hasattr(self, "longCtrlEvent"): + self.longCtrlEvent = "pccEnabled" + + +def _gap_lock_after_buttons(self, cruise_buttons, prev_cruise_buttons, curr_time_ms, use_pedal, qualify_press, brake, args, kwargs): + from openpilot.selfdrive.controls.lib.gap_lock import gap_lock_arm_seq + before = gap_lock_arm_seq(self) + _step_gap_lock(self, cruise_buttons, prev_cruise_buttons, curr_time_ms, use_pedal, qualify_press, brake) + if gap_lock_arm_seq(self) != before: + _take_long_for_gap_lock(self, args, kwargs) + + +def _peek_can_valid(can_parsers) -> bool: + try: + from opendbc.car.tesla.values import Bus + cp = can_parsers[Bus.chassis] + valid = getattr(cp, "can_valid", True) + return False if valid is False else True + except Exception: + return True + + +def _curr_time_ms(args, kwargs): + if args: + return args[0] + return kwargs.get("curr_time_ms", 0) + + +def _use_pedal(args, kwargs): + if len(args) >= 4: + return bool(args[3]) + return bool(kwargs.get("use_pedal", False)) + + +def _v_ego_ms(args, kwargs) -> float: + if len(args) >= 2: + return float(args[1] or 0.0) + return float(kwargs.get("v_ego", 0.0) or 0.0) + + +def _long_control_allowed(args, kwargs) -> bool: + if len(args) >= 6: + return bool(args[5]) + return bool(kwargs.get("long_control_allowed", False)) + + +def _real_brake_pressed(args, kwargs) -> bool: + if len(args) >= 7: + return bool(args[6]) + return bool(kwargs.get("real_brake_pressed", False)) + + +def _at_standstill(engagement, v_ego: float) -> bool: + if bool(getattr(engagement, "_nap_standstill", False)): + return True + return abs(float(v_ego or 0.0)) <= RESUME_STANDSTILL_V_EGO + + +def _gas_pressed(engagement) -> bool: + return bool(getattr(engagement, "_nap_gas_pressed", False)) + + +def _restore_held_max(engagement) -> None: + held = getattr(engagement, "_nap_held_max_kph", None) + if held is not None: + engagement.pedal_speed_kph = float(held) + + +def _di_gas(engagement) -> bool: + """Tesla DI pedal, not the interceptor. Rest noise stays below DI > 2.""" + return float(getattr(engagement, "_nap_di_pedal_pos", 0.0) or 0.0) > PEDAL_DI_PRESSED_STOCK + + +def _standstill_start_gas(engagement) -> bool: + """Gas that may take long after an armed stop. + + A paused session uses gasPressed, including a light interceptor touch. + A fresh engage from a stop only starts on the Tesla DI pedal so + interceptor rest-noise cannot roll the car on the pull. + """ + if getattr(engagement, "_nap_from_off_stop_take_now", False): + return _di_gas(engagement) + return _gas_pressed(engagement) + + +def _complete_standstill_resume(engagement, *, long_allowed: bool) -> None: + """Gas after an armed stop: take long. + + Paused session keeps held MAX. A fresh engage from a stop seeds + take-speed-now (posted + offset if known, else current speed). + """ + if not long_allowed or not engagement.cruiseEnabled: + return + take_now = bool(getattr(engagement, "_nap_from_off_stop_take_now", False)) + engagement.enableLongControl = True + engagement.enableJustCC = False + engagement.pending_enable = False + if take_now: + engagement._nap_set_take_speed_now = True + engagement._nap_set_resume_long = False + engagement._nap_held_max_kph = None + if hasattr(engagement, "longCtrlEvent"): + engagement.longCtrlEvent = "pccEnabled" + else: + engagement._nap_set_resume_long = True + _restore_held_max(engagement) + engagement._nap_from_off_stop_take_now = False + engagement._nap_long_resume_pending = False + engagement._nap_resume_wait_gas = False + if hasattr(engagement, "_clear_pedal_unavailable"): + engagement._clear_pedal_unavailable() + + +def _clear_session_max_flags(engagement): + engagement._nap_long_resume_pending = False + engagement._nap_held_max_kph = None + engagement._nap_set_resume_long = False + engagement._nap_set_take_speed_now = False + engagement._nap_resume_wait_gas = False + engagement._nap_from_off_stop_take_now = False + if hasattr(engagement, "_clear_one_pedal_pause_latch"): + engagement._clear_one_pedal_pause_latch() + else: + engagement._one_pedal_pause_latched = False + + +def _process_buttons(self, cruise_buttons, prev_cruise_buttons, *args, **kwargs): + from opendbc.car.tesla.values import CruiseButtons + + self._nap_set_resume_long = False + self._nap_set_take_speed_now = False + + # Full disengage (cancel, door, reverse/gear, previous cycle) must not + # leave a stale resume latch that would skip double-pull on the next + # first SET, or a held MAX from the previous session. + if not self.cruiseEnabled: + _clear_session_max_flags(self) + + _drop_long_if_driver_turn(self) + + curr_time_ms = _curr_time_ms(args, kwargs) + use_pedal = _use_pedal(args, kwargs) + v_ego = _v_ego_ms(args, kwargs) + at_stop = _at_standstill(self, v_ego) + gas = _gas_pressed(self) + brake = _real_brake_pressed(args, kwargs) + was_off = not bool(self.cruiseEnabled) + set_edge = ( + cruise_buttons == CruiseButtons.MAIN + and prev_cruise_buttons != CruiseButtons.MAIN + ) + # Tesla DI percent (not interceptor). Sticky interceptor rest-noise + # must not look like a gas press. A real press (DI > 2) on a rolling + # SET is engage-while-gas: arm long on this pull, acquire on lift. + # Foot off while rolling still engages lat+long; the DI gate only + # chooses that path versus engage-while-gas. + di_pedal_pct = float(getattr(self, "_nap_di_pedal_pos", 0.0) or 0.0) + di_gas = di_pedal_pct > PEDAL_DI_PRESSED_STOCK + window_ms = float(getattr(self, "double_pull_window_ms", 0) or 0) + dt_ms = curr_time_ms - float(getattr(self, "stalk_pull_time_ms", 0) or 0) + in_double_window = ( + window_ms > 0 + and float(getattr(self, "stalk_pull_time_ms", 0) or 0) > 0 + and 0 <= dt_ms < window_ms + ) + + # One SET restores long after brake drop-keep-lat. Do not start a new + # double-pull window. A latched driver turn no longer drops long and + # no longer blocks that resume. + # At a stop, one SET must not take long / creep from 0. Arm wait-for-gas + # and keep held MAX. Double SET in the window is still take-speed-now. + # Rolling: unchanged one-SET resume. + # One-Pedal gas pause uses the same one-SET overlay. If `_nap_long_ + # resume_pending` was missed (latch without drop), the pause latch + # itself still means "one SET resumes" — do not fall through to + # double-pull first-pull (lat-only, long stays off). + resume_set = ( + set_edge + and bool(self.cruiseEnabled) + and ( + bool(getattr(self, "_nap_long_resume_pending", False)) + or bool(getattr(self, "_one_pedal_pause_latched", False)) + ) + and not _should_drop_long_for_turn(self) + ) + swallow_standstill_set = ( + resume_set and at_stop and not gas and not in_double_window + ) + resume = resume_set and not swallow_standstill_set + # Already lat+long in pedal mode: first SET only arms the double-SET + # window (do not drop long). Second SET in the window forgets sticky / + # take speed now. No-pedal keeps the stock first-pull pending_enable path. + in_session_long_set = ( + set_edge + and bool(use_pedal) + and bool(self.cruiseEnabled) + and bool(self.enableLongControl) + and bool(self.enableDoublePull) + and not resume + and not _should_drop_long_for_turn(self) + ) + swallow_set = in_session_long_set and not in_double_window + take_now_in_session = in_session_long_set and in_double_window + # 2 s hold arms with long on, paused, or not yet taken. A second pull + # inside the double-SET window is still take-speed-now, not a lock. + # Brake does not start a hold (and aborts one already running). + gap_qualify = ( + set_edge + and bool(use_pedal) + and not brake + and not take_now_in_session + and not _should_drop_long_for_turn(self) + ) + + # Pedal, long not yet on. Temporarily drop double-pull so orig + # takes lat+long on this edge (one engage; stock CC still cancels on + # the button / long rising edge). + # - DI > 2, rolling: engage-while-gas. Lift still ACQUIREs. Brake + # still zeros long_control_allowed inside orig. + # - Fully off, rolling, foot off, brake not held: same lat+long + # take-speed-now as the old second pull. + # Stop + foot off is not this branch (wait-for-gas below). Brake + # held and no-pedal stay on the stock double-pull path. + engage_from_off = ( + set_edge + and bool(use_pedal) + and not resume + and not bool(self.enableLongControl) + and not _should_drop_long_for_turn(self) + and ( + (di_gas and not at_stop) + or (was_off and not di_gas and not at_stop and not brake) + ) + ) + # Second pull while a from-off stop is still waiting must not take + # long. Orig would treat it as a double-pull and start rolling. + swallow_from_off_stop_repull = ( + set_edge + and at_stop + and not di_gas + and not brake + and bool(use_pedal) + and not resume + and not was_off + and bool(getattr(self, "_nap_from_off_stop_take_now", False)) + and bool(self.cruiseEnabled) + and not bool(self.enableLongControl) + ) + + saved_double = self.enableDoublePull + if resume or engage_from_off: + self.enableDoublePull = False + swallow_press = swallow_set or swallow_standstill_set or swallow_from_off_stop_repull + orig_buttons = prev_cruise_buttons if swallow_press else cruise_buttons + was_long = bool(self.enableLongControl) + was_wait_gas = bool(getattr(self, "_nap_resume_wait_gas", False)) + try: + result = _ORIG_PROCESS(self, orig_buttons, prev_cruise_buttons, *args, **kwargs) + finally: + self.enableDoublePull = saved_double + + if swallow_press: + self.stalk_pull_time_ms = curr_time_ms + self.last_stalk_non_cancel_ms = curr_time_ms + if swallow_standstill_set: + self._nap_resume_wait_gas = True + # Orig did not see MAIN (swallowed), so it never cleared the + # One-Pedal latch. Wait-for-gas complete is gated on that latch + # being false — leave it set and a later gas touch stays paused. + if hasattr(self, "_clear_one_pedal_pause_latch"): + self._clear_one_pedal_pause_latch() + else: + self._one_pedal_pause_latched = False + # First pull from off at a stop: lat on, long waits for a real DI + # gas tap. Do not creep. MAX on that tap is take-speed-now. + if ( + was_off + and set_edge + and at_stop + and not di_gas + and not brake + and bool(use_pedal) + and bool(self.cruiseEnabled) + and not bool(self.enableLongControl) + ): + self._nap_resume_wait_gas = True + self._nap_from_off_stop_take_now = True + + _drop_long_if_driver_turn(self) + + if not self.cruiseEnabled: + _clear_session_max_flags(self) + _gap_lock_after_buttons( + self, cruise_buttons, prev_cruise_buttons, curr_time_ms, use_pedal, gap_qualify, brake, args, kwargs) + return result + + # In-session pull (pedal single pull or either half of a no-pedal + # double pull). The counter sticks on carState so controlsd sees it + # on the subscription it already has, even if one frame is dropped. + if set_edge and not was_off: + seq = (int(getattr(self, "_nap_stalk_seq", 0)) + 1) & 0xFF + if seq == 0: + seq = 1 + self._nap_stalk_seq = seq + h = getattr(self, "_nap_lat_handoff", None) + if h is not None: + h.driver_resume_request() + + # Armed stop-SET: gas touch completes held-MAX resume. Brake still down + # stays waiting (silent pause would drop long again anyway). + if ( + getattr(self, "_nap_resume_wait_gas", False) + and not self.enableLongControl + and _standstill_start_gas(self) and not brake + and not bool(getattr(self, "_one_pedal_pause_latched", False)) + and not _should_drop_long_for_turn(self) + ): + _complete_standstill_resume( + self, long_allowed=_long_control_allowed(args, kwargs)) + + if engage_from_off and self.enableLongControl and not was_long: + # Initial pedal engage (foot off, or engage-while-gas). Stamp the + # pull so a second pull inside the window is take-speed-now and + # does not look like a new first pull. + self._nap_set_take_speed_now = True + self._nap_held_max_kph = None + self.stalk_pull_time_ms = curr_time_ms + self.last_stalk_non_cancel_ms = curr_time_ms + if hasattr(self, "longCtrlEvent"): + self.longCtrlEvent = "pccEnabled" + elif resume and self.enableLongControl: + # Second SET in the window after a stop-SET is still take-speed-now. + if was_wait_gas and in_double_window and set_edge: + self._nap_set_take_speed_now = True + self._nap_held_max_kph = None + self._nap_resume_wait_gas = False + else: + self._nap_set_resume_long = True + _restore_held_max(self) + self._nap_resume_wait_gas = False + self.stalk_pull_time_ms = curr_time_ms + self.last_stalk_non_cancel_ms = curr_time_ms + elif take_now_in_session and self.enableLongControl: + self._nap_set_take_speed_now = True + self._nap_held_max_kph = None + elif ( + self.enableLongControl and not was_long and not resume + and not getattr(self, "_nap_set_resume_long", False) + ): + # Second pull from lat-only (brake-held first pull, or no-pedal is + # not this flag). A paused stop-SET that just resumed held MAX sets + # `_nap_set_resume_long` and must not also take-speed-now. + self._nap_set_take_speed_now = True + self._nap_held_max_kph = None + + if self.enableLongControl: + self._nap_long_resume_pending = False + self._nap_resume_wait_gas = False + self._nap_from_off_stop_take_now = False + _gap_lock_after_buttons( + self, cruise_buttons, prev_cruise_buttons, curr_time_ms, use_pedal, gap_qualify, brake, args, kwargs) + return result + + +def _handle_steering_disengage(self, steering_disengage, lat_full_control=True): + # A hands-on edge cancels only while OP is in full control of lateral + # (lat_full_control, inferred from the 0x488 type-1 history in opendbc + # preap/lat_yield.py). Yielded lateral (B) keeps the session and long. + # The blinker/ALC gates below are independent and stay as they were. + lat_yield = getattr(self, "lat_yield", None) + if lat_yield is not None: + lat_yield.update_block(bool(steering_disengage)) + left = getattr(self, "_nap_left_blinker", False) + right = getattr(self, "_nap_right_blinker", False) + stalk = int(getattr(self, "_nap_stalk_state", 0) or 0) + pressed = bool(getattr(self, "_nap_steering_pressed", False) or steering_disengage) + hold = _hold_for(self) + # dt=0: _update_preap already advanced the dark timer this cycle. + hold.update( + left, right, pressed, engaged=bool(getattr(self, "cruiseEnabled", False)), + steering_disengage=bool(steering_disengage), + **_hold_kwargs(self, dt=0.0)) + _drop_long_if_driver_turn(self) + # Hard gate: one lamp or physical LEFT/RIGHT, not only hold state. + # Dropping cruiseEnabled here is EventName.pcmDisable on Pre-AP — + # the 3X HUD string "Steering Disengaged". + # Tipped ALC flash-gap: level-2 hands stay a confirm. An emergency + # yank (level 3, hard torque, or a fast rise) must still tear down. + # A latched stalk is not _alc_keep. Panda needs a reflash for the + # matching hands-on level 2 / level 3 split. + emergency = bool(getattr(self, "_nap_emergency_yank", False)) + alc_confirm = bool(hold._alc_keep) + if blinker_turn_blocks_steering_disengage( + left, right, stalk, hold, emergency=emergency, alc_confirm=alc_confirm): + # Keep prev in sync so lamp-off / hand-release is not a rising edge. + self.prev_steering_disengage = steering_disengage + return + # Helping push or roundabout: the B path (session and long stay, lat blocks). + # An opposite yank leaves lat_full_control as the tracker computed it. + if _yield_instead_of_disengage(self, steering_disengage): + lat_full_control = False + self._nap_yield_instead = True + _ORIG_HANDLE(self, steering_disengage, lat_full_control) + if not self.cruiseEnabled: + _clear_session_max_flags(self) + + +def _update_preap(cs, can_parsers): + left, right = _peek_blinker_lamps(can_parsers) + pressed, disengage = _peek_steering_override(can_parsers) + stalk, v_ego = _peek_stalk_and_speed(can_parsers) + engagement = getattr(cs, "engagement", None) + if engagement is not None: + engagement._nap_can_valid = _peek_can_valid(can_parsers) + engagement._nap_left_blinker = left + engagement._nap_right_blinker = right + engagement._nap_steering_pressed = pressed or disengage + engagement._nap_stalk_state = stalk + engagement._nap_v_ego = v_ego + engagement._nap_di_pedal_pos = _peek_di_pedal_percent(can_parsers) + engagement._nap_gas_pressed = _peek_gas_pressed(cs, can_parsers) + engagement._nap_gas_sensor = _peek_pedal_raw(can_parsers) + engagement._nap_standstill = _peek_standstill(can_parsers) + _hold_for(engagement).update( + left, right, pressed, engaged=bool(getattr(engagement, "cruiseEnabled", False)), + steering_disengage=disengage, + **_hold_kwargs(engagement)) + _drop_long_if_driver_turn(engagement) + torque_nm, hands = _peek_torsion_nm_and_hands(can_parsers) + engagement._nap_torque_nm = torque_nm + engagement._nap_hands = hands + engagement._nap_meas_angle_deg = _peek_meas_angle_deg(can_parsers) + engagement._nap_yield_instead = False + tracker = getattr(engagement, "_nap_yank_tracker", None) + if tracker is None: + tracker = EmergencyYankTracker() + engagement._nap_yank_tracker = tracker + fast_rise = tracker.update(torque_nm, DT_CTRL) + hold = _hold_for(engagement) + alc_direction = int(hold._alc_direction or 0) if hold._alc_keep else 0 + engagement._nap_emergency_yank = is_emergency_yank( + torque_nm=torque_nm, hands_on_level=hands, fast_rise=fast_rise, + over_torque=tracker.over_torque, alc_direction=alc_direction) + ret = _ORIG_UPDATE(cs, can_parsers) + engagement = getattr(cs, "engagement", None) + if engagement is not None and getattr(engagement, "_nap_yield_instead", False): + # Tracker still says full control (type 1 was recent). The stash must + # say yielded so car_specific does not add steerDisengage this edge. + cs.lat_full_control = False + if engagement is not None: + from openpilot.selfdrive.controls.lib.gap_lock import ( + gap_lock_arm_seq, gap_lock_cancel_hold, gap_lock_holding) + cs.preap_cc_cancel_hold = gap_lock_cancel_hold(engagement) + try: + ret.gapLockArmSeq = gap_lock_arm_seq(engagement) + except Exception: + pass + try: + ret.gapLockHold = gap_lock_holding(engagement) + except Exception: + pass + # Same carState message controlsd already reads. Not a new subscriber. + try: + ret.napStalkSeq = int(getattr(engagement, "_nap_stalk_seq", 0)) & 0xFF + except Exception: + pass + hands = int(getattr(cs, 'hands_on_level', 0) or 0) + if hands <= 0: + hands = _peek_hands_on_level(can_parsers) + _publish_hands_on_level(ret, hands, bool(getattr(cs, 'lat_full_control', True))) + real_brake = bool(getattr(cs, 'real_brake_pressed', False)) + _publish_real_brake(ret, real_brake) + engagement = getattr(cs, "engagement", None) + if engagement is not None: + hold = getattr(engagement, "_nap_lat_hold", None) + # Driver-turn latch only (not ALC, not post-turn hand-on). Soft-lat + # On must not treat lamp latch as lat-down — that reset the card + # handoff and forgot a yield (emergency cancel / inhibit). v_ego + # is already passed so the same < 10 mph re-enable inhibit applies. + # Soft-lat Off is identity here; BlinkerLateralHold still frees lat + # in controlsd. + driver_turn = bool(hold is not None and hold.turn_active) + canceled = update_card_lat_handoff( + engagement, + engaged=bool(getattr(engagement, "cruiseEnabled", False)), + lat_would_be_active=True, + steering_torque=float(getattr(ret, "steeringTorque", 0.0) or 0.0), + steering_rate_deg=float(getattr(ret, "steeringRateDeg", 0.0) or 0.0), + hands_on_level=hands, + brake_applied=real_brake, + a_ego=float(getattr(ret, "aEgo", 0.0) or 0.0), + v_ego=float(getattr(ret, "vEgo", 0.0) or 0.0), + alc_active=bool(getattr(engagement, "_nap_alc_active", False)), + blinker_paused=driver_turn, + steering_pressed=bool(getattr(ret, "steeringPressed", False)), + steering_angle_deg=float(getattr(ret, "steeringAngleDeg", 0.0) or 0.0), + commanded_angle_deg=getattr(engagement, "_nap_cmd_angle_deg", None), + roundabout_yield=bool(getattr(engagement, "_nap_roundabout_yield", False)), + undertrack=bool(getattr(engagement, "_nap_undertrack", False)), + ) + try: + h = getattr(engagement, "_nap_lat_handoff", None) + # Offset the card handoff just applied. steeringRateDeg is SNA on + # this car; the learner uses steeringAngleDeg for the wheel-still test. + ret.napRestTorqueNm = float(h.rest_bias) if h is not None else 0.0 + except Exception: + pass + if canceled: + if hasattr(ret, "cruiseState"): + try: + ret.cruiseState.enabled = False + except Exception: + pass + cs.cruiseEnabled = False + cs.enableLongControl = False + cs.enableJustCC = False + cs.pedal_speed_kph = 0.0 + cs.preap_cc_cancel_needed = True + cs.longCtrlEvent = getattr(engagement, "longCtrlEvent", None) + else: + # Interceptor gas is published after process_buttons. A stop-SET + # armed this frame / last frame completes here on a light throttle. + gas = bool(getattr(ret, "gasPressed", False)) or _peek_gas_pressed(cs, can_parsers) + engagement._nap_gas_pressed = gas + if bool(getattr(ret, "standstill", False)): + engagement._nap_standstill = True + if ( + getattr(engagement, "_nap_resume_wait_gas", False) + and _standstill_start_gas(engagement) + and not real_brake + and not bool(getattr(engagement, "enableLongControl", False)) + and not bool(getattr(engagement, "_one_pedal_pause_latched", False)) + and not _should_drop_long_for_turn(engagement) + ): + _complete_standstill_resume(engagement, long_allowed=True) + cs.enableLongControl = engagement.enableLongControl + cs.enableJustCC = engagement.enableJustCC + cs.pedal_speed_kph = engagement.pedal_speed_kph + # One-Pedal pause is slightly more sensitive than stock gasPressed + # (DI > 1 vs DI > 2). Orig kick already ran with interceptor_di. + # Always run the overlay helper so a stock falling edge with DI ≤ 1 + # closes `_one_pedal_gas_falling_edge` (extra will not fire). + try: + from opendbc.car.tesla.preap.nap_conf import nap_conf as _nap_conf + di = float(getattr(getattr(cs, "pedal", None), "interceptor_value", 0.0) or 0.0) + if ( + bool(getattr(_nap_conf, "one_pedal_long", False)) + and bool(getattr(_nap_conf, "use_pedal", False)) + ): + maybe_one_pedal_overlay_kick(engagement, di) + cs.enableLongControl = engagement.enableLongControl + cs.enableJustCC = engagement.enableJustCC + cs.pedal_speed_kph = engagement.pedal_speed_kph + cs.longCtrlEvent = engagement.longCtrlEvent + cs.one_pedal_pause_latched = bool(engagement._one_pedal_pause_latched) + except Exception: + pass + # Orig wrote enableLongControl before standstill-gas complete and the + # One-Pedal overlay. A finished gap-lock hold takes long inside + # process_buttons; publish that final flag so the planner sees long-on + # on the same carState as the new arm sequence. + try: + ret.enableLongControl = bool(engagement.enableLongControl) + except Exception: + pass + return ret + + +def _rewire_tesla_carstate_update(): + """card.py builds CarInterface before install, which binds update_preap. + + tesla/carstate.py does `from ...preap.carstate import update_preap` and + calls that local name. Patching only the source module leaves the live + path on the original, so _nap_* lamp/stalk never land and a faster + corner tears down cruiseEnabled → pcmDisable / "Steering Disengaged". + """ + try: + from opendbc.car.tesla import carstate as tesla_carstate + tesla_carstate.update_preap = _update_preap + except Exception: + pass + + +def install_blinker_lat_pause(): + """Patch Pre-AP engagement so a lamp-on turn does not tear down cruise.""" + global _installed, _ORIG_HANDLE, _ORIG_UPDATE, _ORIG_PROCESS, _ORIG_DROP, _ORIG_CHECK, _ORIG_KICK + from opendbc.car.tesla.preap import carstate as preap_carstate + from opendbc.car.tesla.preap.engagement import PreAPEngagement + + if not _installed: + _ORIG_HANDLE = PreAPEngagement.handle_steering_disengage + _ORIG_UPDATE = preap_carstate.update_preap + _ORIG_PROCESS = PreAPEngagement.process_buttons + _ORIG_DROP = PreAPEngagement._drop_longitudinal_keep_lateral + _ORIG_CHECK = PreAPEngagement.check_can_engage + _ORIG_KICK = PreAPEngagement.maybe_one_pedal_gas_kick + PreAPEngagement.handle_steering_disengage = _handle_steering_disengage + PreAPEngagement.process_buttons = _process_buttons + PreAPEngagement._drop_longitudinal_keep_lateral = _drop_longitudinal_keep_lateral + PreAPEngagement.check_can_engage = _check_can_engage + PreAPEngagement.maybe_one_pedal_gas_kick = _filtered_one_pedal_gas_kick + preap_carstate.update_preap = _update_preap + _installed = True + _rewire_tesla_carstate_update() diff --git a/selfdrive/car/tesla/preap_body_controls.py b/selfdrive/car/tesla/preap_body_controls.py new file mode 100644 index 00000000000000..911f84e9e4540c --- /dev/null +++ b/selfdrive/car/tesla/preap_body_controls.py @@ -0,0 +1,1215 @@ +"""Pre-AP wiper / high-beam on the forwarded stalk. + +DAS_bodyControls DAS_wiperSpeed and DAS_highLowBeamDecision were ignored by +this pre-AP Model S and raised a controls mismatch. Those DAS fields stay 0 +(stock teslacan blinker-only TX). This rewrites the wiper/beam byte on +the 0x45 STW_ACTN_RQ frame NAP already forwards for stalk spoof. + +Justin’s parked capture (ignore counter/checksum): + rest 00ff00.... byte after ff is 0x00 + wipers on 00ff10.... high nibble of that byte is 1 + washer 00ff20.... do not send + high beams 00ff04.... low nibble of that byte is 4 + +DBC HiBmLvr_Stat is a 2-bit enum, not a latched-on state: + 0 IDLE, 1 HIBM_ON_PSD (nibble 4), 2 HIBM_FLSH_ON_PSD (nibble 8), 3 SNA. +There is no separate low-beam press. candump src 0 is the live stalk RX; +src 128 is our TX echo (returned | 0x80) — not a panda 0↔2 relay. The body +hears both on party bus 0. A pulse-then-SNA extra TX lost to repeating +bus-0 IDLE. The real stalk continuously sends 00ff04 (HIBM_ON_PSD) while +high beams are held — not a one-shot press. + +While High is selected, keep sending 00ff04 (nibble 4 held) on the +live-counter in-place replacement of 0x45 so the body keeps seeing +high-beam pressed and bus-0 IDLE cannot last-win as a cancel. Off/Low +return the real stalk. Do not pulse 4 then drop to SNA or rest. + +Off leaves the driver’s real stalk nibble alone (do not force 0). +Settings UI is Off or Auto only (persist 0 / 3). Legacy Int(1)/On(2) +coerce to Off at read. Camera Auto does not use TIPWIPE. Auto overlays +WprSw6Posn INTERVAL1 (collar=1) and WprWashSw_Psd=0 only when all of: +setting is Auto, the vehicle is on, gear is Drive or Reverse, vEgo is +above a small creep floor, and the 3X road camera sees a rainy or +icy/frosted windshield (unwarped ROAD Y). Park, Neutral, and standstill +(v≈0) never Auto-wipe, even with the car on. Physical collar Off=0 +Int1=1 Int2=2 Low=5 High=6; Int1 already timed-wipes on this BCM. +A physical collar flick Off→Int1→Off within 1.0 s toggles NAP Auto +on/off; the stock stalk stays Off. No stalk Auto required. + +Live stalk Off repeats collar=0 on bus 0. A 10 Hz Int hold loses that +last-win, so Auto wipe extra-forwards every card frame (~100 Hz) like +High: live MC, in-place 0x45, resign CRC, collar=1 held. candump src 0 +is the live stalk; src 128 is our TX echo (returned | 0x80). + +Pre-AP latches ~32 s intermittent from TIPWIPE nibble 1. Bus-0 rest does +not cancel that. Collar Int1 is a held position — live Off would cancel +if it last-wins, so Auto dry still extra-forwards rest with collar forced +0 (and wash 0) at the 10 Hz slot. On the falling edge of wipe, send +several rest frames immediately (do not wait for the next 10 Hz slot). +Park/Neutral/standstill stay wipe=0 and use that same cancel if we had been wiping. +Do not force wipe on dry glass. Off that never Auto-wiped still leaves +the stalk alone. + +Dry overcast must not acquire or keep HOLD. Off is the escape. Default +Off — Auto is opt-in. No spray. No auto high-beam. Do not flash. +Do not inject a second 0x45 — overlay the existing forwarded frame and +recompute CRC the same way create_action_request already does. + +Panda already allows TX of 0x45 on bus 0 (stalk spoof whitelist). The TX +hook does not gate 0x45 on controls_allowed — stock-CC engage already +sends this ID while disengaged. 0x3E9 DAS_bodyControls *is* gated; that +is why this must not use DAS. Do not bypass safety if that ever +changes. Do not fake this through another ID. + +Auto is not gated on cruiseEnabled, latActive, or a stalk pull. +Legacy Int/On packing still maps to TIPWIPE for tests; live params +coerce those values to Off. + +Known risk: pre-AP may still see the real stalk rest on bus 0. Auto +holds INTERVAL1 at high rate so Off cannot last-win, not a pulse. +""" + +# Params / UI. 0 is off (today's forwarded stalk). Indexes, not raw DBC. +import threading +import time + +NAP_WIPER_SPEED = "NAPWiperSpeed" +NAP_WIPER_SENSITIVITY = "NAPWiperSensitivity" +NAP_HIGH_LOW_BEAM = "NAPHighLowBeam" +NAP_WIPER_HUD_PENDING = "NAPWiperHudPending" + +WIPER_SETTING_OFF = 0 +WIPER_SETTING_INTERMITTENT = 1 +WIPER_SETTING_ON = 2 +WIPER_SETTING_AUTO = 3 +WIPER_SENSITIVITY_DEFAULT = 2 +# Physical collar Off→Int1→Off within this window toggles NAP Auto. +STALK_FLICK_WINDOW_S = 1.0 +STALK_FLICK_COOLDOWN_S = 0.25 +WIPER_HUD_OFF = "Wipers Off" +WIPER_HUD_AUTO = "Wipers Auto" +WIPER_HUD_DURATION_S = 2.5 +# Garage / stopped-in-Drive: do not Auto-wipe below this (m/s). Unknown +# speed does not suppress so Drive tests without vEgo still wipe. +AUTO_WIPE_CREEP_MS = 0.5 +BEAM_SETTING_OFF = 0 +BEAM_SETTING_LOW = 1 +BEAM_SETTING_HIGH = 2 + +STW_ACTN_RQ_ADDR = 0x45 +STW_WIPER_BEAM_BYTE = 2 +STW_WIPER_ON = 0x10 +STW_WASHER_SPRAY = 0x20 +STW_TURN_MASK = 0x03 # TurnIndLvr_Stat. Do not touch — blinker lat-pause. +STW_HIBM_MASK = 0x0C # HiBmLvr_Stat bits 2-3 of the captured byte. +STW_HIGH_BEAM = 0x04 # HIBM_ON_PSD — held while High is selected +STW_HIGH_BEAM_FLASH = 0x08 # HIBM_FLSH_ON_PSD — never send +STW_WASH_MASK = 0x30 # WprWashSw_Psd bits 4-5. 0=NPSD 1=TIPWIPE 2=WASH. +STW_COLLAR_BYTE = 6 +STW_COLLAR_MASK = 0x07 # WprSw6Posn bits 0-2. MC lives in the high nibble. +STW_COLLAR_INTERVAL1 = 1 # Physical Int1. Camera Auto wipe command. +STW_FORWARD_SLOT = 10 +# Falling-edge rest: several 10 ms frames so Pre-AP drops latched Int now. +STW_CANCEL_BURST_N = 8 + +_ORIG_CREATE_ACTION_REQUEST = None +_ORIG_STOCK_CC_UPDATE = None +_installed = False +_rain_needed_override = None +_live_cs = None +_vehicle_on_override = None +_gear_override = None +_v_ego_override = None +_cereal_gear_override = None +_cereal_gear_forced = False +# Last carState card published. Not a subscriber — card is already at the cap. +_published_car_state = None +# Names for Drive/Reverse. Pre-AP DI_torque2 is DI_GEAR_D / DI_GEAR_R. +_DRIVE_GEARS = ( + "drive", "reverse", "d", "r", + "di_gear_d", "di_gear_r", "di_gear_drive", "di_gear_reverse", +) +_PARK_NEUTRAL_GEARS = ( + "park", "neutral", "p", "n", + "di_gear_p", "di_gear_n", "di_gear_park", "di_gear_neutral", +) +# cereal/opendbc GearShifter.drive=2 reverse=4. Tesla DI_gear R=2 D=4 — both allowed. +_DRIVE_INTS = frozenset({2, 4}) +# GearShifter.park=1 neutral=3. Not 0 — unknown must fall through to cereal. +_PARK_NEUTRAL_INTS = frozenset({1, 3}) +_GEAR_ATTRS = ( + "gearShifter", "gear_shifter", "gear", "shifter", + "DI_gear", "di_gear", +) +_AUTO_DEBUG_S = 1.0 +# First Auto stock_cc must not connect ROAD during engage (modeld + GIL). +RAIN_HELPER_START_DELAY_S = 2.5 +_last_auto_log_t = 0.0 +_last_status_put_t = 0.0 +_last_status_gate = None +_status_disk_once = True +_last_gear_src = "none" +_last_wiper_req = False +_wiper_cancel_burst = 0 +_params = None +_rain_mod = None +_rain_import_started = False +_auto_since_t = 0.0 +_GEAR_SHIFTER_ENUMS = None +_wiper_migrated = False +_stalk_prev_collar = None +_stalk_flick_t0 = 0.0 +_stalk_flick_valid = False +_stalk_cooldown_until = 0.0 + + +def _tesla_can(): + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + return TeslaCANPreAP + + +def _stock_cc(): + from opendbc.car.tesla.preap.stock_cc_spoofer import StockCCSpoofer + return StockCCSpoofer + + +def register_nap_body_params(): + """Expose the test keys on NAPParamKeys / DEFAULTS for settings reset.""" + from opendbc.car.tesla.preap.nap_params import DEFAULTS, NAPParamKeys + NAPParamKeys.WIPER_SPEED = NAP_WIPER_SPEED + NAPParamKeys.WIPER_SENSITIVITY = NAP_WIPER_SENSITIVITY + NAPParamKeys.HIGH_LOW_BEAM = NAP_HIGH_LOW_BEAM + DEFAULTS[NAP_WIPER_SPEED] = WIPER_SETTING_OFF + DEFAULTS[NAP_WIPER_SENSITIVITY] = WIPER_SENSITIVITY_DEFAULT + DEFAULTS[NAP_HIGH_LOW_BEAM] = BEAM_SETTING_OFF + + +def wiper_test_requested(setting: int, rain_needed: bool = False) -> bool: + """Int and On hold TIPWIPE nibble 1. Auto wipe is true only while wet. + + Gear / vehicle-on are applied in requested_wiper_test, not here, so packing + tests can still check the flag without a CarState. Auto TX is INTERVAL1 + (collar=1), not this nibble — see requested_auto_collar_posn. + """ + s = int(setting) + if s in (WIPER_SETTING_INTERMITTENT, WIPER_SETTING_ON): + return True + if s == WIPER_SETTING_AUTO: + return bool(rain_needed) + return False + + +def high_beam_test_requested(setting: int) -> bool: + """Only High spoofs. Low/Off leave the stalk — forcing 0 fights a held lever.""" + return int(setting) == BEAM_SETTING_HIGH + + +def hibm_nibble(dat: bytes) -> int: + if len(dat) <= STW_WIPER_BEAM_BYTE: + return 0 + return dat[STW_WIPER_BEAM_BYTE] & STW_HIBM_MASK + + +def stw_collar_posn(dat: bytes) -> int: + if len(dat) <= STW_COLLAR_BYTE: + return 0 + return dat[STW_COLLAR_BYTE] & STW_COLLAR_MASK + + +def stw_wash(dat: bytes) -> int: + """WprWashSw_Psd: 0 NPSD, 1 TIPWIPE, 2 WASH, 3 SNA.""" + if len(dat) <= STW_WIPER_BEAM_BYTE: + return 0 + return (dat[STW_WIPER_BEAM_BYTE] & STW_WASH_MASK) >> 4 + + +def apply_stw_collar(dat: bytes, posn: int | None) -> bytes: + """Force WprSw6Posn and WprWashSw_Psd=0. None is identity. Never spray. + + Keeps MC (high nibble of byte 6), turn, high-beam, and rear-wash bits. + Camera Auto wipe is INTERVAL1 — no TIPWIPE 0x10. Auto dry forces 0. + """ + if posn is None or len(dat) <= STW_COLLAR_BYTE: + return bytes(dat) + out = bytearray(dat) + out[STW_COLLAR_BYTE] = (out[STW_COLLAR_BYTE] & ~STW_COLLAR_MASK) | (int(posn) & STW_COLLAR_MASK) + if len(out) > STW_WIPER_BEAM_BYTE: + out[STW_WIPER_BEAM_BYTE] = out[STW_WIPER_BEAM_BYTE] & ~STW_WASH_MASK + return bytes(out) + + +def apply_stw_wiper_beam_nibbles(dat: bytes, wiper_on: bool, high_beam_on: bool, + clear_wiper: bool = False) -> bytes: + """Set captured stalk nibbles. Off leaves that nibble. Never writes spray. + + High holds HIBM_ON_PSD (4) for as long as the setting is High. Only HiBm + bits are touched — turn-indicator bits stay for blinker lat-pause. + Auto dry / wipe-release cancel sets clear_wiper so the high nibble is + rest 0, not a leftover 1 that would keep Pre-AP intermittent. + """ + if len(dat) <= STW_WIPER_BEAM_BYTE: + return bytes(dat) + out = bytearray(dat) + b = out[STW_WIPER_BEAM_BYTE] + if wiper_on: + b = (b & 0x0F) | STW_WIPER_ON + elif clear_wiper: + b = b & 0x0F + if high_beam_on: + b = (b & ~STW_HIBM_MASK) | STW_HIGH_BEAM + out[STW_WIPER_BEAM_BYTE] = b + return bytes(out) + + +def stalk_test_active(wiper_on: bool | None = None, high_beam_on: bool | None = None) -> bool: + """Settings only. Not gated on cruiseEnabled, latActive, or a stalk pull.""" + if wiper_on is None: + wiper_on = requested_wiper_test() + if high_beam_on is None: + high_beam_on = requested_high_beam_test() + return bool(wiper_on or high_beam_on) + + +def extra_stw_forward_needed(can_sends, frame: int, wiper_on: bool, high_beam_on: bool, + wiper_cancel: bool = False, cancel_now: bool = False, + collar_hold: bool = False) -> bool: + """One 0x45 when holding a nibble/collar or sending rest-cancel. Never a second frame. + + Parked / not-engaged: stock-cc only TXes 0x45 on engage/cancel. Wiper + On/Int extra-forwards on the 10 Hz slot so TIPWIPE nibble 1 stays held. + Camera Auto wipe extra-forwards every 10 ms like High so INTERVAL1 + last-wins against repeating bus-0 Off (collar=0). Auto dry / wipe-release + extra-forwards rest with collar forced 0 on the 10 Hz slot so Pre-AP + drops intermittent. Falling-edge cancel_now does not wait for the slot. + High extra-forwards every 10 ms so held nibble 4 can last-win against + repeating bus-0 IDLE. + """ + if not (stalk_test_active(wiper_on, high_beam_on) or wiper_cancel or collar_hold): + return False + if not high_beam_on and not collar_hold and not cancel_now and int(frame) % STW_FORWARD_SLOT != 0: + return False + return not any(msg[0] == STW_ACTN_RQ_ADDR for msg in can_sends) + + +def live_stw_counter(msg_stw) -> int: + """Use the live/relayed MC. +1 builds a second competing 0x45.""" + if not msg_stw: + return 0 + return int(msg_stw.get("MC_STW_ACTN_RQ", 0) or 0) + + +def overlay_stw_wiper_beam(dat: bytes, wiper_on: bool, high_beam_on: bool, crc_fn=None, + clear_wiper: bool = False, collar_posn: int | None = None) -> bytes: + """Apply nibbles/collar and resign CRC only when the payload changed.""" + new_dat = apply_stw_wiper_beam_nibbles(dat, wiper_on, high_beam_on, clear_wiper=clear_wiper) + new_dat = apply_stw_collar(new_dat, collar_posn) + if new_dat == dat: + return dat + if crc_fn is None or len(new_dat) < 8: + return new_dat + out = bytearray(new_dat) + out[7] = crc_fn(bytes(out[:7])) + return bytes(out) + + +def replace_relayed_stw(dat: bytes, wiper_on: bool, high_beam_on: bool, crc_fn=None, + clear_wiper: bool = False, collar_posn: int | None = None) -> bytes: + """Edit the live/relayed 0x45 payload. Do not invent a second frame.""" + return overlay_stw_wiper_beam(dat, wiper_on, high_beam_on, crc_fn=crc_fn, + clear_wiper=clear_wiper, collar_posn=collar_posn) + + +def overlay_collar_on_can_msg(msg, tesla_can, posn: int | None): + """Force WprSw6Posn / wash=0 on a packed 0x45 TX and resign CRC. + + Last-mile so Auto INTERVAL1 still TXes if create_action_request is the + stock packer. Identity when posn is None, tesla_can is missing, or dat + is too short. + """ + if msg is None or posn is None or tesla_can is None: + return msg + try: + addr, dat, bus = msg[0], msg[1], msg[2] + except (TypeError, IndexError, ValueError): + return msg + if int(addr) != STW_ACTN_RQ_ADDR: + return msg + crc_fn = getattr(tesla_can, "stw_crc", None) + if crc_fn is None: + return msg + new_dat = overlay_stw_wiper_beam(bytes(dat), False, False, crc_fn=crc_fn, collar_posn=int(posn)) + if new_dat == bytes(dat): + return msg + return (addr, new_dat, bus) + + +def send_replaced_live_stw(spoofer, CS, tesla_can, bus): + """TX the live stalk with nibbles patched, same MC as bus 0 RX.""" + msg_stw = getattr(CS, "msg_stw_actn_req", None) + if msg_stw is None: + return None + button = int(msg_stw.get("SpdCtrlLvr_Stat", 0) or 0) + if tesla_can is None: + return spoofer._send(CS, tesla_can, bus, button) + return tesla_can.create_action_request(button, bus, live_stw_counter(msg_stw), msg_stw) + + +def _get_params(): + """Reuse one Params handle. Constructing Params() every 10 ms lagged card.""" + global _params + if _params is None: + from openpilot.common.params import Params + _params = Params() + return _params + + +def _param_int(key: str, default: int = 0) -> int: + try: + val = _get_params().get(key, return_default=True) + if val is None: + return default + if isinstance(val, (bytes, bytearray)): + val = val.decode("utf-8", errors="ignore").strip() + return int(val) + except Exception: + return default + + +def normalize_wiper_setting(setting) -> int: + """Live Off or Auto. Legacy Int(1)/On(2) and unknowns are Off.""" + try: + if int(setting) == WIPER_SETTING_AUTO: + return WIPER_SETTING_AUTO + except (TypeError, ValueError): + pass + return WIPER_SETTING_OFF + + +def wiper_hud_text(setting=None) -> str: + if setting is None: + setting = read_wiper_setting() + return WIPER_HUD_AUTO if normalize_wiper_setting(setting) == WIPER_SETTING_AUTO else WIPER_HUD_OFF + + +def _write_wiper_setting(setting: int, announce: bool = False) -> int: + setting = normalize_wiper_setting(setting) + try: + params = _get_params() + params.put(NAP_WIPER_SPEED, int(setting)) + if announce: + try: + params.put_bool(NAP_WIPER_HUD_PENDING, True) + except Exception: + try: + params.put(NAP_WIPER_HUD_PENDING, True) + except Exception: + pass + except Exception: + pass + return setting + + +def read_wiper_setting() -> int: + """NAPWiperSpeed as Off or Auto. Persist-coerces leftover Int/On once.""" + global _wiper_migrated + raw = _param_int(NAP_WIPER_SPEED, WIPER_SETTING_OFF) + setting = normalize_wiper_setting(raw) + if setting != raw and not _wiper_migrated: + _wiper_migrated = True + _write_wiper_setting(setting, announce=False) + return setting + + +def toggle_wiper_auto(announce: bool = True) -> int: + """Off (or any non-Auto) → Auto; Auto → Off. Same write as settings.""" + current = read_wiper_setting() + nxt = WIPER_SETTING_OFF if current == WIPER_SETTING_AUTO else WIPER_SETTING_AUTO + return _write_wiper_setting(nxt, announce=announce) + + +def reset_wiper_stalk_detector() -> None: + global _stalk_prev_collar, _stalk_flick_t0, _stalk_flick_valid, _stalk_cooldown_until + global _wiper_migrated + _stalk_prev_collar = None + _stalk_flick_t0 = 0.0 + _stalk_flick_valid = False + _stalk_cooldown_until = 0.0 + _wiper_migrated = False + + +def _live_physical_collar(cs) -> tuple[int | None, int]: + """Raw bus-0 WprSw6Posn / wash from CS before Auto overlay.""" + msg = getattr(cs, "msg_stw_actn_req", None) if cs is not None else None + if not isinstance(msg, dict): + return None, 0 + try: + collar = int(msg.get("WprSw6Posn") or 0) + except (TypeError, ValueError): + collar = None + try: + wash = int(msg.get("WprWashSw_Psd") or 0) + except (TypeError, ValueError): + wash = 0 + return collar, wash + + +def poll_wiper_stalk_shortcut(cs, now: float | None = None) -> int | None: + """Physical collar 0→1→0 within 1.0 s toggles NAP Auto. Returns new setting or None. + + Detects from live CS.msg_stw_actn_req (bus-0 stalk), not the Auto INTERVAL1 + overlay. Wash, Int2+, Low, and High cancel the gesture. A held Int1 longer + than 1.0 s does not toggle. + """ + global _stalk_prev_collar, _stalk_flick_t0, _stalk_flick_valid, _stalk_cooldown_until + if now is None: + now = time.monotonic() + collar, wash = _live_physical_collar(cs) + if collar is None: + return None + prev = _stalk_prev_collar + _stalk_prev_collar = collar + + if wash != 0 or collar not in (0, STW_COLLAR_INTERVAL1): + _stalk_flick_valid = False + _stalk_flick_t0 = 0.0 + return None + + if now < _stalk_cooldown_until: + return None + + toggled = None + if prev == 0 and collar == STW_COLLAR_INTERVAL1: + _stalk_flick_t0 = now + _stalk_flick_valid = True + elif prev == STW_COLLAR_INTERVAL1 and collar == 0: + if _stalk_flick_valid and _stalk_flick_t0 > 0.0 and (now - _stalk_flick_t0) <= STALK_FLICK_WINDOW_S: + toggled = toggle_wiper_auto(announce=True) + _stalk_cooldown_until = now + STALK_FLICK_COOLDOWN_S + _stalk_flick_valid = False + _stalk_flick_t0 = 0.0 + elif collar == STW_COLLAR_INTERVAL1 and _stalk_flick_valid and _stalk_flick_t0 > 0.0: + if (now - _stalk_flick_t0) > STALK_FLICK_WINDOW_S: + _stalk_flick_valid = False + return toggled + + +def set_rain_wiper_needed(needed: bool | None) -> None: + """Tests inject the rain/ice/wiper-need signal. None returns to the camera.""" + global _rain_needed_override + _rain_needed_override = None if needed is None else bool(needed) + + +def update_live_car_state(cs) -> None: + """Stock-cc update publishes gear / vehicle-on for Auto.""" + global _live_cs + _live_cs = cs + + +def set_auto_gates(vehicle_on: bool | None = None, gear=None, v_ego=None) -> None: + """Tests inject vehicle-on, gear, and vEgo. None leaves that field on live CS.""" + global _vehicle_on_override, _gear_override, _v_ego_override + _vehicle_on_override = None if vehicle_on is None else bool(vehicle_on) + _gear_override = gear + _v_ego_override = v_ego + + +def set_cereal_gear(gear) -> None: + """Tests inject cereal carState.gearShifter. None means cereal is empty.""" + global _cereal_gear_override, _cereal_gear_forced + _cereal_gear_forced = True + _cereal_gear_override = gear + + +def note_published_car_state(cs) -> None: + """card.state_publish passes the carState it just sent. No socket.""" + global _published_car_state + _published_car_state = cs + + +def reset_auto_gates() -> None: + global _live_cs, _vehicle_on_override, _gear_override, _last_gear_src, _last_wiper_req + global _cereal_gear_override, _cereal_gear_forced, _wiper_cancel_burst + global _last_auto_log_t, _last_status_put_t, _last_status_gate, _auto_since_t + global _v_ego_override, _status_disk_once, _published_car_state + _live_cs = None + _published_car_state = None + _vehicle_on_override = None + _gear_override = None + _v_ego_override = None + _cereal_gear_override = None + _cereal_gear_forced = False + _last_gear_src = "none" + _last_wiper_req = False + _wiper_cancel_burst = 0 + _last_auto_log_t = 0.0 + _last_status_put_t = 0.0 + _last_status_gate = None + _status_disk_once = True + _auto_since_t = 0.0 + reset_wiper_stalk_detector() + + +def _gear_name(gear) -> str: + """Token for Drive/Reverse. capnp _DynamicEnum has .name=None and str()=='drive'.""" + if gear is None: + return "" + tokens = [] + try: + tokens.append(str(gear)) + except Exception: + pass + name = getattr(gear, "name", None) + if isinstance(name, str) and name: + tokens.append(name) + for raw in tokens: + token = str(raw).rsplit(".", 1)[-1].lower().strip() + if token and token not in ("none", "null"): + return token + return "" + + +def _gear_int(gear): + if isinstance(gear, bool): + return None + if isinstance(gear, int): + return int(gear) + for attr in ("raw",): + try: + v = getattr(gear, attr, None) + if isinstance(v, int) and not isinstance(v, bool): + return int(v) + except Exception: + pass + try: + return int(gear) + except Exception: + return None + + +def _gear_present(gear) -> bool: + """True if a gear value was found. GearShifter.unknown is 0 — still present.""" + return gear is not None and gear != "" + + +def _gear_type_name(gear) -> str: + if gear is None: + return "none" + try: + return type(gear).__name__ + except Exception: + return "?" + + +def _is_drive_or_reverse(gear) -> bool: + """Drive/Reverse. Token first: cereal _DynamicEnum != structs.GearShifter.drive.""" + if not _gear_present(gear): + return False + if _gear_name(gear) in _DRIVE_GEARS: + return True + gi = _gear_int(gear) + if gi in _DRIVE_INTS: + return True + for gs in _gear_shifter_enums(): + try: + if gear == gs.drive or gear == gs.reverse: + return True + except Exception: + pass + try: + if gi is not None and gi in (int(gs.drive), int(gs.reverse)): + return True + except Exception: + pass + for side in (gs.drive, gs.reverse): + try: + if _gear_name(gear) == _gear_name(side): + return True + except Exception: + pass + return False + + +def _is_park_or_neutral(gear) -> bool: + """Known Park/Neutral. Unknown 0 is missing, not Park.""" + if not _gear_present(gear): + return False + name = _gear_name(gear) + if name in _PARK_NEUTRAL_GEARS: + return True + if name in ("unknown", "invalid", "di_gear_invalid", "sna"): + return False + gi = _gear_int(gear) + if gi in _PARK_NEUTRAL_INTS and name not in _DRIVE_GEARS: + return True + for gs in _gear_shifter_enums(): + for side_name in ("park", "neutral"): + side = getattr(gs, side_name, None) + if side is None: + continue + try: + if gear == side: + return True + except Exception: + pass + try: + if _gear_name(gear) == _gear_name(side): + return True + except Exception: + pass + return False + + +def _gear_known(gear) -> bool: + """Drive/Reverse/Park/Neutral. unknown 0 is not known — fall through to cereal.""" + return _is_drive_or_reverse(gear) or _is_park_or_neutral(gear) + + +def _gear_shifter_enums(): + """Import once. Re-importing opendbc/cereal on the 10 ms path hit the GIL.""" + global _GEAR_SHIFTER_ENUMS + if _GEAR_SHIFTER_ENUMS is not None: + return _GEAR_SHIFTER_ENUMS + found = [] + try: + from opendbc.car import structs + found.append(structs.CarState.GearShifter) + except Exception: + pass + try: + from cereal import car + gs = car.CarState.GearShifter + if gs not in found: + found.append(gs) + except Exception: + pass + _GEAR_SHIFTER_ENUMS = tuple(found) + return _GEAR_SHIFTER_ENUMS + + +def _attr_gear(obj, attr: str): + if obj is None: + return None + try: + if isinstance(obj, dict): + return obj.get(attr) + return getattr(obj, attr, None) + except Exception: + return None + + +def _host_gears(host, src: str) -> list[tuple[object, str]]: + found = [] + if host is None: + return found + for attr in _GEAR_ATTRS: + gear = _attr_gear(host, attr) + if _gear_present(gear): + found.append((gear, src if attr == "gearShifter" else f"{src}.{attr}")) + if isinstance(host, dict): + for key in ("DI_gear", "gearShifter"): + if key in host and _gear_present(host[key]): + found.append((host[key], src)) + return found + + +def _cs_gear(cs) -> tuple[object, str]: + """Live stock-cc CS is the inner parser. Drive is on CS.out / cereal carState. + + Prefer a candidate that already looks like Drive/Reverse so an inner + unknown default cannot hide CS.out (cereal _DynamicEnum, str='drive'). + Unknown 0 is not a gear — caller may fall through to cereal. + """ + if cs is None: + return None, "none" + candidates = [] + candidates.extend(_host_gears(cs, "cs")) + out = _attr_gear(cs, "out") + if out is not None: + candidates.extend(_host_gears(out, "out")) + for key in ("msg_di_torque2", "DI_torque2"): + msg = _attr_gear(cs, key) + if isinstance(msg, dict): + g = msg.get("DI_gear") + if _gear_present(g): + candidates.append((g, "di_torque2")) + for gear, src in candidates: + if _is_drive_or_reverse(gear): + return gear, src + for gear, src in candidates: + if _is_park_or_neutral(gear): + return gear, src + return None, "none" + + +def _read_cereal_gear() -> tuple[object, str]: + """Published carState.gearShifter. Justin's probe: drive _DynamicEnum.""" + if _cereal_gear_forced: + if _gear_present(_cereal_gear_override): + return _cereal_gear_override, "cereal" + return None, "none" + cs = _published_car_state + if cs is None: + return None, "none" + try: + gear = _attr_gear(cs, "gearShifter") + if not _gear_present(gear): + gear = _attr_gear(cs, "gear") + if _gear_known(gear): + return gear, "cereal" + except Exception: + pass + return None, "none" + + +def _resolved_gear() -> tuple[object, str]: + """CS aliases first. Cereal carState when inner CS has no known gear.""" + if _gear_override is not None: + return _gear_override, "override" + gear, src = _cs_gear(_live_cs) + if _gear_known(gear): + return gear, src + cg, csrc = _read_cereal_gear() + if _gear_known(cg): + return cg, csrc + if _gear_present(gear): + return gear, src + return cg, csrc + + +def vehicle_is_on() -> bool: + """Onroad CarState is only published while the vehicle is on.""" + if _vehicle_on_override is not None: + return bool(_vehicle_on_override) + return _live_cs is not None + + +def in_drive_gear() -> bool: + """Drive or Reverse. Park, Neutral, and unknown do not Auto-wipe.""" + global _last_gear_src + gear, src = _resolved_gear() + _last_gear_src = src + return _is_drive_or_reverse(gear) + + +def _read_v_ego(host) -> float | None: + if host is None: + return None + for attr in ("vEgo", "v_ego"): + try: + v = getattr(host, attr, None) + except Exception: + v = None + if v is None: + continue + try: + return abs(float(v)) + except (TypeError, ValueError): + continue + return None + + +def live_v_ego() -> float | None: + """Signed speed is folded to abs. None means unknown — do not suppress.""" + if _v_ego_override is not None: + try: + return abs(float(_v_ego_override)) + except (TypeError, ValueError): + return None + cs = _live_cs + v = _read_v_ego(cs) + if v is not None: + return v + return _read_v_ego(_attr_gear(cs, "out")) + + +def auto_wipe_moving() -> bool: + """False when vEgo is known and below creep. Unknown speed does not suppress.""" + v = live_v_ego() + if v is None: + return True + return v >= AUTO_WIPE_CREEP_MS + + +def rain_wiper_needed() -> bool: + """Rainy or icy/frosted windshield latch. Default clear so Auto does not wipe every drive. + + Order: test override, then the 3X ROAD camera near-glass check. + """ + if _rain_needed_override is not None: + return bool(_rain_needed_override) + try: + rain = _rain_module() + if rain is None: + return False + return bool(rain.windshield_rain_needed()) + except Exception: + return False + + +def _rain_module(): + """Already-imported rain module only. Never import numpy on the card RT thread.""" + global _rain_mod + if _rain_mod is not None: + return _rain_mod + import sys + m = sys.modules.get("openpilot.selfdrive.car.tesla.preap_windshield_rain") + if m is not None: + _rain_mod = m + return _rain_mod + + +def _preimport_rain_module() -> None: + """Background numpy import. stock_cc.update must not pay this on CTRL_HIGH.""" + global _rain_mod + try: + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + _rain_mod = rain + except Exception: + pass + + +def _kick_rain_import() -> None: + global _rain_import_started + if _rain_import_started: + return + _rain_import_started = True + threading.Thread(target=_preimport_rain_module, name="nap-wiper-import", daemon=True).start() + + +def _sync_rain_helper() -> None: + """VisionIpc + numpy only while Wipers = Auto. Off must not recv ROAD.""" + global _auto_since_t + if _rain_needed_override is not None: + return + setting = read_wiper_setting() + rain = _rain_module() + if int(setting) != WIPER_SETTING_AUTO: + _auto_since_t = 0.0 + if rain is not None: + try: + rain.stop_windshield_rain_helper() + except Exception: + pass + return + now = time.monotonic() + if _auto_since_t <= 0.0: + _auto_since_t = now + if rain is None: + _kick_rain_import() + return + if now - _auto_since_t < float(RAIN_HELPER_START_DELAY_S): + return + try: + rain.ensure_windshield_rain_helper() + except Exception: + pass + + +def _auto_status_line(setting: int, on: bool, drive: bool, rain: bool, wipe: bool, + moving: bool = True) -> str: + gear, src = _resolved_gear() + rain_bits = "rain=0" + sens = _param_int(NAP_WIPER_SENSITIVITY, WIPER_SENSITIVITY_DEFAULT) + acq = 0 + rpt = 0 + gap_left = 0.0 + gap_s = 0.0 + try: + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rainmod + d = rainmod._detector + acq_on = rainmod.acquire_threshold(sens) + rpt_on = rainmod.repeat_threshold(sens) + gap_s = rainmod.min_rewipe_gap_light_s(sens) + if d is not None: + now = time.monotonic() + age_ms = (now - d._last_frame_t) * 1000.0 if d._last_frame_t else -1.0 + pulse_s = float(getattr(rainmod, "WIPE_PULSE_S", 0.0)) + wait_s = float(getattr(rainmod, "CLEAR_WAIT_S", 0.0)) + wipe_t0 = float(getattr(d, "_wipe_t0", 0.0) or 0.0) + wait_t0 = float(getattr(d, "_wait_t0", 0.0) or 0.0) + last_wipe = float(getattr(d, "_last_wipe_t0", 0.0) or 0.0) + pulse_left = max(0.0, pulse_s - (now - wipe_t0)) if d.hold and wipe_t0 else 0.0 + wait_left = max(0.0, wait_s - (now - wait_t0)) if wait_t0 else 0.0 + acq = int(d.last_score >= acq_on) + rpt = int(d.last_score >= rpt_on) + if last_wipe > 0.0: + gap_left = max(0.0, gap_s - (now - last_wipe)) + hold_need = int(getattr(d, '_acquire_n', 0) or rainmod.acquire_hold_n(sens)) + thin_s = 0.0 + try: + thin_s = float(rainmod.thin_gap_s(sens)) + except Exception: + thin_s = float(getattr(d, '_thin_gap_s', 0.0) or 0.0) + thin_t0 = float(getattr(d, '_thin_t0', 0.0) or 0.0) + thin_left = 0.0 + if thin_s > 0.0: + if last_wipe > 0.0: + thin_left = max(0.0, thin_s - (now - last_wipe)) + elif thin_t0 > 0.0: + thin_left = max(0.0, thin_s - (now - thin_t0)) + else: + thin_left = thin_s + thin = int(getattr(d, '_thin', False) or getattr(d, '_thin_wipe', False)) + rain_bits = ( + f"hold={int(d.hold)} holdn={int(getattr(d, '_hold_n', 0))}/{hold_need} " + + f"warm={int(getattr(d, '_warm_n', 0))}/{int(getattr(rainmod, 'WARMUP_N', 0))} " + + f"ema={d.ema:.2f} score={d.last_score:.2f} bokeh={d.last_bokeh:.2f} blob={d.last_blob:.2f} " + + f"speckle={d.last_speckle:.3f} sparse={d.last_sparse:.1f} struct={d.last_structure:.3f} sat={d.last_sat:.3f} " + + f"clear={int(getattr(d, '_clear_n', 0))}/{int(getattr(rainmod, 'CLEAR_RELEASE_N', 0))} " + + f"sens={int(sens)} acq={acq} rpt={rpt} " + + f"heavy={int(d.last_score >= float(getattr(rainmod, 'HEAVY_ON', 2.2)))} " + + f"pulse={pulse_left:.1f}/{pulse_s:.1f} wait={wait_left:.1f}/{wait_s:.1f} " + + f"gap={gap_left:.1f}/{gap_s:.1f} " + + f"thin={thin} thin_gap={thin_left:.1f}/{thin_s:.1f} " + + f"connected={int(d.connected)} failed={int(d._failed)} frames={d.n_frames} stream={d.stream} " + + f"helper={int(d.helper_alive)} period_s={float(getattr(rainmod, 'SCORE_PERIOD_S', 0)):.1f} " + + f"hz={float(getattr(rainmod, 'SCORE_HZ', 0)):.1f} age_ms={age_ms:.0f} err={d.last_err or '-'}" + ) + except Exception: + rain_bits = "rain=err" + gi = _gear_int(gear) + raw = "-" if gi is None else str(gi) + park = int(_is_park_or_neutral(gear)) + v = live_v_ego() + v0 = int(v is not None and v < AUTO_WIPE_CREEP_MS) + v_bits = "-" if v is None else f"{v:.2f}" + if int(setting) == WIPER_SETTING_AUTO: + collar_n = STW_COLLAR_INTERVAL1 if wipe else 0 + collar_bits = f"collar={collar_n} wash=0" + else: + collar_bits = "collar=-" + return ( + f"nap wiper auto setting={int(setting)} on={int(on)} gear={_gear_name(gear) or '-'} gear_src={src} " + + f"gear_type={_gear_type_name(gear)} raw={raw} drive={int(drive)} moving={int(moving)} " + + f"rain={int(rain)} wipe={int(wipe)} " + + f"sens={int(sens)} acq={int(acq)} rpt={int(rpt)} park={park} v0={v0} v={v_bits} " + + f"cancel={int(wiper_rest_tx_needed(wipe))} {collar_bits} " + + f"installed={int(_installed)} {rain_bits}" + ) + + +def _put_wiper_status(line: str) -> None: + """Write NAPWiperRainStatus. Callers must rate-limit — this is the expensive put. + + First write is block=True so the key lands on disk (e0/e1 qlog InitData + missed it when only the async put ran after loggerd snapshot, or when + CLEAR_ON_MANAGER_START wiped the install stub). Do not clear the once + flag before a successful put. If the key is empty later, block again. + Later 1 Hz writes stay non-blocking on the card RT path. + """ + global _status_disk_once + try: + params = _get_params() + block = bool(_status_disk_once) + if not block: + try: + cur = params.get("NAPWiperRainStatus") + if cur is None or cur == b"" or cur == "": + block = True + except Exception: + block = True + try: + params.put("NAPWiperRainStatus", line, block=block) + _status_disk_once = False + except TypeError: + params.put("NAPWiperRainStatus", line) + _status_disk_once = False + except Exception: + pass + + +def _log_auto_status(setting: int, on: bool, drive: bool, rain: bool, wipe: bool, + moving: bool = True) -> None: + """Params.put / cloudlog at 1 Hz, or immediately on Auto gate changes. Not every 10 ms.""" + global _last_auto_log_t, _last_status_put_t, _last_status_gate + sens = _param_int(NAP_WIPER_SENSITIVITY, WIPER_SENSITIVITY_DEFAULT) + gate = (int(setting), bool(on), bool(drive), bool(moving), bool(rain), bool(wipe), int(sens)) + now = time.monotonic() + if gate == _last_status_gate and now - _last_status_put_t < _AUTO_DEBUG_S: + return + _last_status_gate = gate + _last_status_put_t = now + line = _auto_status_line(setting, on, drive, rain, wipe, moving=moving) + if now - _last_auto_log_t >= _AUTO_DEBUG_S: + _last_auto_log_t = now + try: + from openpilot.common.swaglog import cloudlog + cloudlog.info("%s", line) + except Exception: + pass + _put_wiper_status(line) + + +def wiper_rest_tx_needed(wiper_on: bool | None = None) -> bool: + """Auto dry, or a wipe 1→0 burst, still extra-forwards rest. Off-never-wiped does not.""" + if wiper_on is None: + wiper_on = _last_wiper_req + if wiper_on: + return False + if _wiper_cancel_burst > 0: + return True + return read_wiper_setting() == WIPER_SETTING_AUTO + + +def _arm_wiper_cancel(prev_wiper: bool, wiper_on: bool) -> None: + global _last_wiper_req, _wiper_cancel_burst + if prev_wiper and not wiper_on: + _wiper_cancel_burst = STW_CANCEL_BURST_N + _last_wiper_req = bool(wiper_on) + + +def _note_wiper_cancel_frame() -> None: + global _wiper_cancel_burst + if _wiper_cancel_burst > 0: + _wiper_cancel_burst -= 1 + + +def requested_auto_collar_posn(wiper_on: bool | None = None) -> int | None: + """INTERVAL1 while Auto wants wipe; 0 while Auto rest-cancel; else live collar. + + Live settings are Off or Auto. Camera Auto is collar=1. + """ + if int(read_wiper_setting()) != WIPER_SETTING_AUTO: + return None + if wiper_on is None: + wiper_on = requested_wiper_test() + return STW_COLLAR_INTERVAL1 if wiper_on else 0 + + +def requested_wiper_test() -> bool: + global _last_wiper_req + setting = read_wiper_setting() + _sync_rain_helper() + if int(setting) == WIPER_SETTING_AUTO: + on = vehicle_is_on() + drive = in_drive_gear() + moving = auto_wipe_moving() + rain = False + try: + rain = rain_wiper_needed() + except Exception: + rain = False + wipe = bool(on and drive and moving and rain) + _last_wiper_req = wipe + _log_auto_status(setting, on, drive, rain, wipe, moving=moving) + return wipe + wipe = wiper_test_requested(setting) + _last_wiper_req = wipe + return wipe + + +def requested_high_beam_test() -> bool: + return high_beam_test_requested(_param_int(NAP_HIGH_LOW_BEAM, BEAM_SETTING_OFF)) + + +def create_action_request_with_overlay(self, button_to_press, bus, counter, msg_stw=None): + """Forward the live stalk, then overlay the test nibbles on that same frame.""" + orig = _ORIG_CREATE_ACTION_REQUEST + if orig is None: + orig = _tesla_can().create_action_request + addr, dat, out_bus = orig(self, button_to_press, bus, counter, msg_stw) + wiper = requested_wiper_test() + auto_collar = requested_auto_collar_posn(wiper) + tipwipe = bool(wiper and auto_collar is None) + clear = bool(wiper_rest_tx_needed(wiper) or auto_collar == 0) + dat = replace_relayed_stw(dat, tipwipe, requested_high_beam_test(), + crc_fn=self.stw_crc, clear_wiper=clear and not tipwipe, + collar_posn=auto_collar) + return addr, dat, out_bus + + +def stock_cc_update_with_overlay(self, CS, frame, tesla_can, can_bus_party): + """Keep the single 0x45 TX path. When the test is on, forward if idle this slot. + + Does not read cruiseEnabled, latActive, or CC.enabled. High extra-forwards + every 10 ms with held nibble 4 on the live-counter frame; Int/On keep + forwarding TIPWIPE on the 10 Hz slot. Camera Auto wipe extra-forwards + every 10 ms like High with WprSw6Posn=INTERVAL1 and WprWashSw_Psd=0 so + live stalk Off (collar=0) cannot last-win. Auto dry / wipe-release + extra-forwards rest (collar 0, wash 0, TIPWIPE cleared) on the 10 Hz + slot so Pre-AP drops intermittent; a wipe 1→0 burst does not wait for + the slot. Auto reads gear and vEgo from this CS: Park/Neutral/standstill stay + wipe=0 and still cancel if we had been wiping. Scoring/status keep + running so Connect digs can see park/v0 suppress. Primes the ROAD + VisionIpc helper only while Auto so poll() does not recv on this + CTRL_HIGH thread. Off stops the helper. Physical collar 0→1→0 within + 1 s toggles NAP Auto from the live bus-0 stalk (before overlay). + """ + orig = _ORIG_STOCK_CC_UPDATE + if orig is None: + orig = _stock_cc().update + update_live_car_state(CS) + poll_wiper_stalk_shortcut(CS) + _sync_rain_helper() + prev_wiper = _last_wiper_req + wiper = requested_wiper_test() + _arm_wiper_cancel(prev_wiper, wiper) + auto_collar = requested_auto_collar_posn(wiper) + collar_hold = auto_collar == STW_COLLAR_INTERVAL1 + high_setting = requested_high_beam_test() + cancel = wiper_rest_tx_needed(wiper) + cancel_now = bool(cancel and _wiper_cancel_burst > 0) + can_sends = orig(self, CS, frame, tesla_can, can_bus_party) + had_stw = any(msg[0] == STW_ACTN_RQ_ADDR for msg in can_sends) + if extra_stw_forward_needed(can_sends, frame, wiper, high_setting, + wiper_cancel=cancel, cancel_now=cancel_now, + collar_hold=collar_hold): + msg_stw = getattr(CS, "msg_stw_actn_req", None) + if msg_stw is not None: + if high_setting or collar_hold: + # Same MC as the bus-0 RX rest — edit that frame, do not +1 a second 0x45. + # Auto INTERVAL1 must last-win like High: live Off repeats collar=0. + sent = send_replaced_live_stw(self, CS, tesla_can, can_bus_party) + else: + sent = self._send(CS, tesla_can, can_bus_party, + int(msg_stw.get("SpdCtrlLvr_Stat", 0) or 0)) + if sent is not None: + sent = overlay_collar_on_can_msg(sent, tesla_can, auto_collar) + can_sends.append(sent) + had_stw = True + if auto_collar is not None: + can_sends = [overlay_collar_on_can_msg(msg, tesla_can, auto_collar) for msg in can_sends] + had_stw = any(msg[0] == STW_ACTN_RQ_ADDR for msg in can_sends) + if cancel and had_stw: + _note_wiper_cancel_frame() + # Qualified engage-stalk hold: keep stock CC asleep. In-session CANCEL TX + # does not drop lateral (tesla_preap_tx.h: lever==CANCEL only when + # !controls_allowed). Do not reset the spoofer's cancel_frame. + hold = getattr(CS, "preap_cc_cancel_hold", False) + if hold is True: + from openpilot.selfdrive.controls.lib.gap_lock import gap_lock_cancel_hold_tx + if gap_lock_cancel_hold_tx(had_stw, True, frame): + from opendbc.car.tesla.values import CruiseButtons + sent = self._send(CS, tesla_can, can_bus_party, int(CruiseButtons.CANCEL)) + if sent is not None: + can_sends.append(sent) + return can_sends + + +def install_body_controls_test(): + """Wire NAP Wipers & Lights settings to the forwarded 0x45 stalk byte. + + Does not patch DAS_bodyControls — those wiper/beam fields stay 0. + DAS_turnIndicatorRequest stays on teslacan.create_body_controls_message, + driven by CC.leftBlinker / rightBlinker while ALC is armed or in progress. + """ + global _installed, _ORIG_CREATE_ACTION_REQUEST, _ORIG_STOCK_CC_UPDATE + register_nap_body_params() + if _installed: + return + tesla_can = _tesla_can() + stock_cc = _stock_cc() + _ORIG_CREATE_ACTION_REQUEST = tesla_can.create_action_request + _ORIG_STOCK_CC_UPDATE = stock_cc.update + tesla_can.create_action_request = create_action_request_with_overlay + stock_cc.update = stock_cc_update_with_overlay + _installed = True + try: + from openpilot.common.swaglog import cloudlog + cloudlog.info("nap body controls overlay installed (0x45 wiper/beam)") + except Exception: + pass + _put_wiper_status( + "nap wiper auto setting=- on=0 gear=- gear_src=none raw=- drive=0 rain=0 wipe=0 " + "sens=- acq=0 rpt=0 gap=- thin=0 thin_gap=- park=- v0=- collar=0 wash=0 installed=1 waiting" + ) diff --git a/selfdrive/car/tesla/preap_force_offroad_handoff.py b/selfdrive/car/tesla/preap_force_offroad_handoff.py new file mode 100644 index 00000000000000..fe09acefc19c66 --- /dev/null +++ b/selfdrive/car/tesla/preap_force_offroad_handoff.py @@ -0,0 +1,510 @@ +"""Pre-AP stock-CC handoff for Force Offroad, and kill CC on OP long engage. + +Force Offroad (`NAPForceOffroad`) used to flip `deviceState.started` false +immediately. Cancel / SET spoofs live in the onroad carcontroller stack, so +that dumped pedal long with nothing holding speed (hard regen). + +When NAP is actively using software long (`enableLongControl`), hold +`started` until this FSM finishes: + + 1. Drive DI toward STANDBY (CANCEL from ENABLED / STANDSTILL / OVERRIDE; + MAIN arm from OFF — SET_ACCEL is ignored on an unarmed DI). + 2. Once STANDBY (or DI already ENABLED from MAIN), drop OP long. + 3. SET_ACCEL at current ego (`preap_cc_engage_needed`). + 4. After DI ENABLED (or a short timeout), write + `NAPForceOffroadHandoffReady` so hardwared may set started=false. + +If NAP is not in software long, write ready immediately (today's path). + +On OP long engage, if stock CC is ENABLED or STANDBY, keep canceling until +it is neither so pedal long and stock CC do not fight. Force Offroad +handoff suppresses that kill so it can park DI in STANDBY and SET. + +Install-from-card, same pattern as preap_blinker_lat_pause / body_controls. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +# Mirror opendbc StockCCSpoofer so this module stays importable without capnp. +# Keep in sync with opendbc_repo/opendbc/car/tesla/preap/stock_cc_spoofer.py. +CANCEL_DELAY_FRAMES = 10 # 100 ms at 100 Hz +CC_ENGAGE_TIMEOUT_FRAMES = 50 # 500 ms ENGAGING retries + +PARAM = "NAPForceOffroad" +HANDOFF_READY_PARAM = "NAPForceOffroadHandoffReady" +CONFIRMED_PARAM = "NAPForceOffroadConfirmed" + +# Card-side overall budget. CANCEL_DELAY (100 ms) + slot align (~100 ms) + +# DI lag + ENGAGING retries (500 ms) + another DI lag. Prefer ENABLED; +# after this, write ready anyway so maps still unlock. +HANDOFF_TIMEOUT_S = 2.5 + +# Re-issue a one-shot spoof only after the spoofer has had time to TX +# (CANCEL_DELAY_FRAMES + one 10 Hz slot) plus a little DI lag. +SPOOF_RETRY_S = 0.25 + +# Wait for STANDBY after cancel/arm before giving up that phase. +STANDBY_WAIT_S = 0.80 + +# Wait for ENABLED after SET. StockCCSpoofer's ENGAGING timeout (500 ms) +# plus DI_state lag. +ENABLED_WAIT_S = (CC_ENGAGE_TIMEOUT_FRAMES / 100.0) + 0.30 + +# Tesla DI_cruiseState values that are holding / about to hold speed. +_HOLDING = frozenset({"ENABLED", "STANDSTILL", "OVERRIDE", "PRE_CANCEL"}) +_READY_TO_SET = frozenset({"STANDBY"}) +_ENABLED_OK = frozenset({"ENABLED", "STANDSTILL"}) +_KILL = frozenset({"ENABLED", "STANDBY", "STANDSTILL", "OVERRIDE", "PRE_CANCEL"}) + +IDLE = "idle" +CANCELING = "canceling" +ARMING = "arming" +DROP_AND_SET = "drop_and_set" +WAIT_ENABLED = "wait_enabled" +READY = "ready" + + +@dataclass(frozen=True) +class HandoffCommand: + """One-tick intent for engagement + StockCCSpoofer flags.""" + cancel: bool = False + arm: bool = False + engage: bool = False + drop_long: bool = False + ready: bool = False + ignore_stalk: bool = False + suppress_cancel: bool = False + state: str = IDLE + + +def di_is_holding(di_state: str) -> bool: + return (di_state or "OFF") in _HOLDING + + +def di_ready_to_set(di_state: str) -> bool: + return (di_state or "OFF") in _READY_TO_SET + + +def di_enabled_ok(di_state: str) -> bool: + return (di_state or "OFF") in _ENABLED_OK + + +def di_needs_kill(di_state: str) -> bool: + return (di_state or "OFF") in _KILL + + +def software_long_active(enable_long_control: bool) -> bool: + """Gate for the Force Offroad handoff. Software long, not pedal handshake.""" + return bool(enable_long_control) + + +class StockCCKillOnLong: + """Cancel stock CC while OP long is coming up, until it is not ENABLED/STANDBY. + + One-shot CANCELs with a cooldown so we do not reset StockCCSpoofer's + cancel_frame every tick (that would prevent the TX). Rising long starts + the sequence; ENABLED while long is on re-arms it (they are fighting). + """ + + def __init__(self): + self.active = False + self.prev_long = False + self.last_cancel_t: float | None = None + + def reset(self): + self.active = False + self.prev_long = False + self.last_cancel_t = None + + def update(self, enable_long: bool, di_state: str, now: float) -> bool: + if not enable_long: + self.active = False + self.prev_long = False + return False + + rising = enable_long and not self.prev_long + self.prev_long = True + if rising or di_is_holding(di_state): + self.active = True + + if not self.active: + return False + if not di_needs_kill(di_state): + self.active = False + return False + if self.last_cancel_t is not None and (now - self.last_cancel_t) < SPOOF_RETRY_S: + return False + self.last_cancel_t = now + return True + + +class ForceOffroadHandoff: + """Pure FSM. No Params / CAN. card + controller wraps apply the command.""" + + def __init__(self, timeout_s: float = HANDOFF_TIMEOUT_S): + self.timeout_s = timeout_s + self.state = IDLE + self.started_t: float | None = None + self.phase_t: float | None = None + self.last_spoof_t: float | None = None + self.last_cmd = HandoffCommand() + self.kill = StockCCKillOnLong() + self.dropped_long = False + + def reset(self): + self.state = IDLE + self.started_t = None + self.phase_t = None + self.last_spoof_t = None + self.dropped_long = False + self.last_cmd = HandoffCommand() + self.kill.reset() + + def _enter(self, state: str, now: float): + self.state = state + self.phase_t = now + + def _overall_timeout(self, now: float) -> bool: + return self.started_t is not None and (now - self.started_t) >= self.timeout_s + + def _phase_timeout(self, now: float, budget: float) -> bool: + return self.phase_t is not None and (now - self.phase_t) >= budget + + def _emit_spoof(self, now: float) -> bool: + if self.last_spoof_t is not None and (now - self.last_spoof_t) < SPOOF_RETRY_S: + return False + self.last_spoof_t = now + return True + + def update(self, *, force_offroad: bool, enable_long: bool, di_state: str, + now: float, confirmed: bool = True) -> HandoffCommand: + di_state = di_state or "OFF" + + if force_offroad and not confirmed: + # Waiting for the on-road Yes/No. Do not cancel, drop long, or SET. + self.state = IDLE + self.started_t = None + self.phase_t = None + self.last_spoof_t = None + self.dropped_long = False + self.last_cmd = HandoffCommand(ready=False, state=IDLE) + return self.last_cmd + + if not force_offroad: + self.state = IDLE + self.started_t = None + self.phase_t = None + self.last_spoof_t = None + self.dropped_long = False + cancel = self.kill.update(enable_long, di_state, now) + self.last_cmd = HandoffCommand(cancel=cancel, ready=False, state=IDLE) + return self.last_cmd + + # Force Offroad is on. Stop the engage-kill so we can park in STANDBY. + self.kill.reset() + self.kill.prev_long = bool(enable_long) + + if self.state == IDLE: + if not software_long_active(enable_long): + self.last_cmd = HandoffCommand(ready=True, state=READY) + return self.last_cmd + self.started_t = now + self.dropped_long = False + if di_is_holding(di_state): + self._enter(CANCELING, now) + elif di_ready_to_set(di_state) or di_enabled_ok(di_state): + self._enter(DROP_AND_SET, now) + else: + self._enter(ARMING, now) + + if self._overall_timeout(now) and self.state != READY: + self._enter(READY, now) + + cmd = self._step(enable_long=enable_long, di_state=di_state, now=now) + self.last_cmd = cmd + return cmd + + def _step(self, *, enable_long: bool, di_state: str, now: float) -> HandoffCommand: + if self.state == CANCELING: + if di_ready_to_set(di_state): + self._enter(DROP_AND_SET, now) + elif not di_is_holding(di_state): + # CANCEL went to OFF (or fault). Arm, then SET. + self._enter(ARMING, now) + elif self._phase_timeout(now, STANDBY_WAIT_S): + self._enter(READY, now) + else: + return HandoffCommand( + cancel=self._emit_spoof(now), + ignore_stalk=True, + state=CANCELING, + ) + + if self.state == ARMING: + if di_ready_to_set(di_state): + self._enter(DROP_AND_SET, now) + elif di_enabled_ok(di_state): + # MAIN from OFF sometimes SETs in one step. Drop OP; CC already holds. + self._enter(DROP_AND_SET, now) + elif self._phase_timeout(now, STANDBY_WAIT_S): + self._enter(READY, now) + else: + return HandoffCommand( + arm=self._emit_spoof(now), + ignore_stalk=True, + state=ARMING, + ) + + if self.state == DROP_AND_SET: + drop = not self.dropped_long + self.dropped_long = True + self._enter(WAIT_ENABLED, now) + # If DI is already ENABLED (MAIN took it), do not SET — just finish. + if di_enabled_ok(di_state): + self._enter(READY, now) + return HandoffCommand( + drop_long=drop, + ready=True, + ignore_stalk=True, + suppress_cancel=True, + state=READY, + ) + return HandoffCommand( + engage=True, + drop_long=drop, + ignore_stalk=True, + suppress_cancel=True, + state=WAIT_ENABLED, + ) + + if self.state == WAIT_ENABLED: + if di_enabled_ok(di_state): + self._enter(READY, now) + elif self._phase_timeout(now, ENABLED_WAIT_S) or self._overall_timeout(now): + self._enter(READY, now) + else: + # StockCCSpoofer retries SET while ENGAGING. Re-issue only if it + # dropped back to IDLE (timeout / cancel) and DI is still STANDBY. + return HandoffCommand( + engage=di_ready_to_set(di_state) and self._emit_spoof(now), + ignore_stalk=True, + suppress_cancel=True, + state=WAIT_ENABLED, + ) + + if self.state == READY: + return HandoffCommand( + ready=True, + ignore_stalk=True, + suppress_cancel=True, + drop_long=False, + state=READY, + ) + + return HandoffCommand(state=self.state) + + +_handoff = ForceOffroadHandoff() +_ready_written: bool | None = None +_ORIG_PREAP_LONG_UPDATE = None +_ORIG_STOCK_CC_UPDATE = None +_ORIG_PROCESS_BUTTONS = None +_installed = False + + +def _params(): + try: + from openpilot.common.params import Params + return Params() + except Exception: + return None + + +def _read_force_offroad(params=None) -> bool: + try: + p = params if params is not None else _params() + return bool(p.get_bool(PARAM)) if p is not None else False + except Exception: + return False + + +def _read_confirmed(params=None) -> bool: + try: + p = params if params is not None else _params() + return bool(p.get_bool(CONFIRMED_PARAM)) if p is not None else False + except Exception: + return False + + +def _write_ready(ready: bool) -> None: + global _ready_written + ready = bool(ready) + if _ready_written is ready: + return + p = _params() + if p is None: + return + try: + p.put_bool(HANDOFF_READY_PARAM, ready) + _ready_written = ready + except Exception: + pass + + +def _drop_long_silent(inner_cs) -> None: + """Stop commanding long. Keep cruiseEnabled so lat stays until offroad.""" + eng = getattr(inner_cs, "engagement", None) + if eng is not None: + eng.enableLongControl = False + if getattr(eng, "cruiseEnabled", False): + eng.enableJustCC = True + if hasattr(inner_cs, "enableLongControl"): + inner_cs.enableLongControl = False + if getattr(inner_cs, "cruiseEnabled", False): + inner_cs.enableJustCC = True + + +def _apply_cmd_flags(inner_cs, cmd: HandoffCommand) -> None: + if inner_cs is None: + return + if cmd.cancel: + inner_cs.preap_cc_cancel_needed = True + if cmd.engage: + inner_cs.preap_cc_engage_needed = True + if cmd.arm: + inner_cs.preap_cc_arm_needed = True + eng = getattr(inner_cs, "engagement", None) + if eng is not None: + eng._nap_handoff_ignore_stalk = bool(cmd.ignore_stalk) + if cmd.cancel: + eng.preap_cc_cancel_needed = True + if cmd.engage: + eng.preap_cc_engage_needed = True + + +def apply_controller_flags(CS, cmd: HandoffCommand | None = None) -> None: + """Re-assert spoof flags after PreAPLongController may have overwritten them. + + Falling enableLongControl otherwise sets cancel_needed and StockCCSpoofer + would abort ENGAGING (cancel beats engage). + """ + if cmd is None: + cmd = _handoff.last_cmd + if cmd.suppress_cancel: + CS.preap_cc_cancel_needed = False + if cmd.cancel: + CS.preap_cc_cancel_needed = True + if cmd.engage: + CS.preap_cc_engage_needed = True + if cmd.arm: + CS.preap_cc_arm_needed = True + + +def update_force_offroad_handoff(inner_cs, public_cs=None, *, now: float | None = None, + force_offroad: bool | None = None, + confirmed: bool | None = None, + params=None) -> HandoffCommand: + """card.state_update hook. Runs at 100 Hz after CI.update().""" + import time + if now is None: + now = time.monotonic() + if force_offroad is None: + force_offroad = _read_force_offroad(params) + if confirmed is None: + confirmed = _read_confirmed(params) if force_offroad else False + + if inner_cs is None and public_cs is None: + ready = bool(force_offroad) and confirmed + _write_ready(ready) + return HandoffCommand(ready=ready, state=READY if ready else IDLE) + + enable_long = bool( + getattr(inner_cs, "enableLongControl", False) + if inner_cs is not None else False + ) + if public_cs is not None: + enable_long = enable_long or bool(getattr(public_cs, "enableLongControl", False)) + di_state = "OFF" + if inner_cs is not None: + di_state = getattr(inner_cs, "di_cruise_state", None) or "OFF" + + cmd = _handoff.update( + force_offroad=force_offroad, + enable_long=enable_long, + di_state=di_state, + now=now, + confirmed=confirmed, + ) + if cmd.drop_long and inner_cs is not None: + _drop_long_silent(inner_cs) + if public_cs is not None and hasattr(public_cs, "enableLongControl"): + try: + public_cs.enableLongControl = False + except Exception: + pass + _apply_cmd_flags(inner_cs, cmd) + _write_ready(bool(cmd.ready) if force_offroad else False) + return cmd + + +def _preap_long_update_with_handoff(self, CC, CS, frame, tesla_can, can_bus_party, now_nanos=0): + orig = _ORIG_PREAP_LONG_UPDATE + sends = orig(self, CC, CS, frame, tesla_can, can_bus_party, now_nanos) + apply_controller_flags(CS) + return sends + + +def _stock_cc_update_with_arm(self, CS, frame, tesla_can, can_bus_party): + """MAIN arm spoof. StockCCSpoofer only knows cancel + SET_ACCEL.""" + orig = _ORIG_STOCK_CC_UPDATE + if getattr(CS, "preap_cc_arm_needed", False): + self._nap_arm_pending = True + self._nap_arm_frame = frame + CS.preap_cc_arm_needed = False + can_sends = orig(self, CS, frame, tesla_can, can_bus_party) + if getattr(self, "_nap_arm_pending", False): + from opendbc.car.tesla.values import CruiseButtons + ready = (frame - int(getattr(self, "_nap_arm_frame", frame))) >= CANCEL_DELAY_FRAMES + if ready and frame % 10 == 0: + sent = self._send(CS, tesla_can, can_bus_party, CruiseButtons.MAIN) + if sent is not None: + can_sends.append(sent) + self._nap_arm_pending = False + return can_sends + + +def _process_buttons_with_handoff(self, cruise_buttons, prev_cruise_buttons, *args, **kwargs): + """Spoofed MAIN / CANCEL / SET must not look like a driver stalk pull.""" + from opendbc.car.tesla.values import CruiseButtons + orig = _ORIG_PROCESS_BUTTONS + if getattr(self, "_nap_handoff_ignore_stalk", False): + cruise_buttons = CruiseButtons.IDLE + prev_cruise_buttons = CruiseButtons.IDLE + return orig(self, cruise_buttons, prev_cruise_buttons, *args, **kwargs) + + +def install_force_offroad_handoff(): + """Patch pedal-long + stock-cc + engagement. Call after the other Pre-AP installs.""" + global _installed, _ORIG_PREAP_LONG_UPDATE, _ORIG_STOCK_CC_UPDATE, _ORIG_PROCESS_BUTTONS + from opendbc.car.tesla.preap.carcontroller import PreAPLongController + from opendbc.car.tesla.preap.engagement import PreAPEngagement + from opendbc.car.tesla.preap.stock_cc_spoofer import StockCCSpoofer + + if _installed: + return + _ORIG_PREAP_LONG_UPDATE = PreAPLongController.update + _ORIG_STOCK_CC_UPDATE = StockCCSpoofer.update + _ORIG_PROCESS_BUTTONS = PreAPEngagement.process_buttons + PreAPLongController.update = _preap_long_update_with_handoff + StockCCSpoofer.update = _stock_cc_update_with_arm + PreAPEngagement.process_buttons = _process_buttons_with_handoff + _installed = True + + +def reset_handoff_for_tests(): + """Unit tests: clear singleton state. Does not uninstall patches.""" + global _ready_written + _handoff.reset() + _ready_written = None diff --git a/selfdrive/car/tesla/preap_windshield_rain.py b/selfdrive/car/tesla/preap_windshield_rain.py new file mode 100644 index 00000000000000..cca210010d9bfb --- /dev/null +++ b/selfdrive/car/tesla/preap_windshield_rain.py @@ -0,0 +1,1213 @@ +"""Windshield rain / ice check from the comma 3X road camera. + +There is no rain sensor, and this driving model does not publish rainProb. +Auto looks at the unwarped ROAD camera Y plane (camerad VisionIpc +VISION_STREAM_ROAD). The 3X looks through the windshield, focused on the +far scene, so drops on the glass are large soft defocused bokeh — not +sharp beads. The model warp crops that near field away, so this does not +use modelV2. + +Rain: large low-frequency bokeh in the upper/mid ROAD bands, sparse + streaks/speckles, or a wet sheet (high blob / overlapping milky + defocus). Ice/frost: a milky sheet or crystal mottle. +Score is monotonic with obstruction: once the glass is past a wetness +floor, more water (blob, bokeh, haze, streaks, dense beads) must score +at least as rainy — never drop to dry because it is "too wet". Do not +require a bokeh/blob ratio sweet spot. Dense beads covering the pane +raise sharp-residual "structure"; that is still rain if bokeh is +rain-like. Foliage/brick is sharp structure *without* rain-scale bokeh. +Headlamp plates are isolated saturated hotspots, not distributed +droplet highlights. Dry overcast / scene texture stays under the +wetness floor. A real wipe may look clear for one idle score tick (~4 s). +Duty cycle (Justin): idle watching assesses every SCORE_PERIOD_S (~4 s) +and does not wipe first on Auto select / helper start. The first +WARMUP_N helper looks are ignored (VisionIpc / first ROAD). First wipe +needs two consecutive *meaningful* wet idle looks (ACQUIRE_ON) after +warmup — light sprinkle / residual beads stay idle (watch every ~4 s). +Dry indoor/garage ROAD and light sprinkle look the same to the old +wet-sheet path (blob≈7–9, live dry score=6.29). That must score well +below acquire. Light mist / film on the glass (highway streaks; ROAD +UI looks through it) must still wipe via the near-glass haze path — +not distant atmospheric fog alone. Then: one blade sweep → +wipe=0 + Auto rest-cancel → wait CLEAR_WAIT_S (~2.5 s) → assess against +the *repeat* bar (REWIPE_ON), not acquire. True heavy (HEAVY_ON≈9) can +rewipe after that holdoff. Light mist must not clock Mid at the old +~12.5 s pulses (pulse+wait+two idle looks); Mid keeps +MIN_REWIPE_GAP_LIGHT_S (~25 s). Drier/Dry (sens 0–1) lower acquire and +repeat further so evening film (~2.15 highway mist) first-wipes and +can rewipe without waiting for heavy≈9; Drier light gap is ~5–8 s, +Dry ~8–12 s. Below acquire, a thin-rain floor (THIN_ON≈HOLD_ON) still +fires an occasional INTERVAL1 after thin_gap_s (Drier ~18 s, Dry ~22 s, +Mid ~36 s) so light mist does not sit quiet for minutes. Drier acquires +on one wet look (park / v≈0 still suppress TX). NAPWiperSensitivity +(0–4, mid=2) scales acquire, repeat, looks, the light gap, and the +thin gap. Park / v≈0 suppress is in body controls; scoring still runs. +Off still leaves the real stalk. + +Bokeh energy is an 8-bit residual (~0 dry, ~2–5 wet). A live clear-glass +log showed bokeh=49165 — wrong Y scale or a bandpass blowup. Impossible +magnitudes are invalid/dry (they must not latch HOLD or look like rain +returning after a wipe). Real heavy-rain scores above ~12 are still wet. + +VisionIpc runs only while NAPWiperSpeed is Auto. Off stops the +helper, drop HOLD, and do not recv ROAD. The helper is SCHED_OTHER +(nice 10): blocking recv, conflate +ROAD then WIDE. Numpy scoring while idle runs once per SCORE_PERIOD_S +(~4 s, SCORE_HZ ≈ 0.25), not every ROAD frame and not 4 Hz / 1 Hz. A +full-res Y copy plus 20 Hz multi-blur starved card's GIL (age_ms ~30 s, +Selfdrive Process Lagging). Recv downsamples immediately; one feature +pass per scored frame; ice contrast uses the tiny grid. Keep the ROAD client while Auto so we do not +resubscribe every 4 s (Justin: frames stuck at 1–2, age_ms thousands, +stale first Y after reconnect). Recv+numpy still once per period, not +20 Hz. One wipe is WIPE_PULSE_S (~1.5 s of Auto INTERVAL1 / collar=1, one +slow park-to-park), then CLEAR_WAIT_S with HOLD off (cancel + blades out of +FOV), then the helper assesses — it does not wait another idle 4 s. +2 s settle left blades in ROAD FOV on bone-dry Auto (wipe loop). Do not +prime hold_n after a wipe: a marginal post-wipe score must not INTERVAL1 +again. (Old LIGHT_REST_N=6 left wet glass ~15 s. BURST_MAX_N=3 sat on +Low for ~7.5 s / several sweeps. Idle used to score every 2.5 s.) +card is CTRL_HIGH: stock_cc.update / poll() only reads the latch, never +recvs, never joins the helper. NAPWiperRainStatus and cloudlog are 1 Hz +or on gate changes — not every 10 ms Params.put. Numpy is imported on a +background thread, not on card's RT path. Helper start waits +RAIN_HELPER_START_DELAY_S after Auto is selected so engage is not +fighting ROAD subscribe. Failures retry; they do not permanently dry Auto. +""" +from __future__ import annotations + +import os +import threading +import time + +import numpy as np + +# Unwarped ROAD. Distant road/sky in the upper-mid view is what made dry +# indoor/garage blob≈7.5 look like a wet sheet (Justin 5f32c450b). Score +# near-bottom glass, US LHD driver side (left). Skip the last rows so +# parked blades / hood edge stay out. Ice haze uses the same near glass. +_NEAR_ROWS = (0.58, 0.90) +_BOKEH_ROWS = (0.48, 0.82) +_MID_ROWS = (0.52, 0.84) +_COLS = (0.06, 0.50) +_RAIN_BANDS = (_NEAR_ROWS, _BOKEH_ROWS) +# Farther driving view (not near-glass). Atmospheric fog collapses this; +# mist-on-glass leaves it relatively sharp (Justin's 59 mph ROAD UI). +_FAR_ROWS = (0.18, 0.42) +_FAR_COLS = (0.22, 0.78) + +# Rain. Detrended bokeh ~4 on wet ROAD, ~0 on dry sky gradients. +# Speckle-drop path stays ~2–4. +SCORE_ON = 1.8 +SCORE_OFF = 1.0 +# Justin's heavier-rain ROAD UI: mid-band detrended bokeh ~1.85–3.3. +# Dry sky/road wash is ~0.2. Live clear/overcast texture was latching at +# 1.5 — raise the bar so that is not rain. Real wet is still ~3+. +# Light sprinkle 5f32c450b: bokeh=3.01 blob=7.40 — not a wet sheet. +# At-or-above: bokeh >= this is rain. Do not also require a ratio vs blob. +BOKEH_ON = 2.2 +# Old sweet-spot veto: bokeh/(blob+0.2) >= 0.22 dropped heavy rain to 0 +# when blob rose. Kept so tests prove we no longer use it as a reject. +_BOKEH_RATIO = 0.22 +# Dry/overcast fine residual on *smooth* fixtures is ~2. Live dry garage +# and light sprinkle both sat blob≈7.0–8.8. Overlapping milky wet is ~12. +# Sheet bar must sit above that dry/sprinkle blob, not at 8. +BLOB_WET = 10.5 +# Live 5f32c450b dry + sprinkle (same scorer look): +# dry last: blob=7.55 sparse=6.7 struct=0.022 bokeh=3.85 score=6.29 +# sprinkle: blob=7.40–8.83 sparse=4.7–9.7 +# Heavy wet sheet is blob~12 sparse~2. Residual beads can hit sparse~8–10 +# with the same mid blob — still not a sheet. +_SCENE_BLOB_MIN = 3.5 +_SCENE_SPARSE = (2.5, 12.0) +# 8-bit ROAD: wet bokeh ~2–5. Justin's clear-glass log was bokeh=49165. +# Anything this high is a unit/scale bug, not rain. +BOKEH_ABSURD = 24.0 +BLOB_ABSURD = 40.0 +# Typical wet rain score is ~2–12. Heavy blob can exceed this and is still wet. +SCORE_ABSURD = 12.0 +# 8-bit obstruction never reaches this. 49165 is garbage → dry, not a cap. +SCORE_INVALID = 80.0 +_SPECKLE_MIN = 0.012 +# Frost crystals: moderate uniform residual. Calm near-glass (blob~1.2) +# is not frost. Live dry blob=7.4 must not be frost either. +FROST_ON = 1.8 +FROST_BLOB_MAX = 4.0 +ICE_ON = 1.5 +ICE_CONTRAST = 0.085 +ICE_LUM = (45.0, 210.0) +ICE_BLOB_MIN = 1.8 +# Light mist / film on the glass: low near-glass contrast + mild bokeh or +# streaks, while the distant ROAD view stays relatively sharp. Not dry +# calm glass (bokeh~0.1), not garage grain, not distant fog alone. +MIST_ON = 1.0 +MIST_BOKEH_MIN = 0.70 +MIST_SPECKLE_MIN = 0.010 +MIST_NEAR_C = 0.085 +MIST_FAR_C = 0.055 +MIST_NEAR_OVER_FAR = 0.90 +MIST_LUM = (40.0, 220.0) +# Live 2db9e6c30 highway mist that should wipe (lower-left FOV): +# score=2.15 bokeh=1.42 blob=3.93 sparse=3.2 speckle=0 struct=0 +# 48f458dd9 still missed dense fine drizzle (uniform film, ROAD looks +# through it). Status blob/bokeh are the *max-bokeh* band; scoring only +# NEAR dropped the film. Band sits below old-FOV garage (blob~7–9). +# Blob floor is above dry/overcast mid-left (~2.5) and calm glass (~1.2). +MIST_FILM_BLOB = (2.75, 6.2) +MIST_FILM_BOKEH = (0.55, 2.40) +MIST_FILM_SPARSE = (1.8, 5.25) +MIST_FILM_SPECKLE = 0.008 +# Combined obstruction: 1.0 is looks_rainy / wetness floor (rain/frost/ice). +HOLD_ON = 1.0 +# Thin-mist maintenance: some wetness, below acquire. e1 Drier Auto On +# showed rain but sat 76–240 s between wipes on light film. Same INTERVAL1 +# pulse as acquire; do not wait hold_n. First thin wipe waits thin_gap +# from the first sustained look (last_wipe=0 must not fire immediately). +THIN_ON = HOLD_ON +# First wipe: Mid+ needs two consecutive idle scores at/above this +# *after* warmup. Drier (sens 0) needs one. Mist film live/offline sits +# ~6–8. Do not "fix" dry garage by raising this past old 6.29. Heavy +# milky / dense beads (~10+) still enter. Lower than REWIPE_ON so the +# first wipe is not waiting on a heavy bar. Sens 0–1 scale this down +# further: 2db9e6c30 highway mist was ~2.15; #200 Drier acquire (~2.61) +# still missed e0 000000e0--68791b5c92 (one wipe in ~7 min). +ACQUIRE_ON = 4.5 +# Status "heavy" and the unscaled gap-skip bar. Light film (~6–8.4) is +# not heavy. 2026-09-18 Drier mist: long 125–271 s quiet gaps because +# repeat sat at HEAVY_ON*0.80≈7.2 and the light gap was still ~20 s. +# #200 dropped Drier repeat to 4.5; e0 still under-wiped. +HEAVY_ON = 9.0 +# Mid post-wipe re-enter. Sens 0–1 scale below the film / highway-mist +# band so Drier/Dry can rewipe without needing heavy≈9. Gap still +# applies unless the score is truly HEAVY_ON — do not 4 s-thrash. +REWIPE_ON = HEAVY_ON +# 0 = wipe sooner / more often (more dry). 4 = tolerate more film (more wet). +NAP_WIPER_SENSITIVITY = "NAPWiperSensitivity" +WIPER_SENSITIVITY_MIN = 0 +WIPER_SENSITIVITY_MAX = 4 +WIPER_SENSITIVITY_DEFAULT = 2 +# Mid=1.00. Sens 0–1 drop more than #200 (0.58/0.76) so ~2.15 mist +# acquires. Mid+ stays the previous curve. +ACQUIRE_SENSITIVITY_SCALE = (0.36, 0.46, 1.00, 1.10, 1.20) +# #200 Drier/Dry repeat was 4.5/5.85 — still above highway mist ~2.15. +# Drier/Dry now sit in that band; Mid stays 9. +REPEAT_SENSITIVITY_SCALE = (0.18, 0.22, 1.00, 1.10, 1.20) +# Compat alias (older tests / callers). Prefer ACQUIRE_SENSITIVITY_SCALE. +SENSITIVITY_SCALE = ACQUIRE_SENSITIVITY_SCALE +# Light-mist min interval between wipe *starts*. Drier ~6.5 s; Dry ~10 s; +# Mid 25 s (do not return to the old ~12.5 s Mid pulse). Wet/Wetter 27.5/30. +MIN_REWIPE_GAP_LIGHT_S = 25.0 +MIN_REWIPE_GAP_BY_SENS = (6.5, 10.0, 25.0, 27.5, 30.0) +MIN_REWIPE_GAP_SENS_STEP = 2.5 +# Below-acquire occasional wipe. Drier/Dry keep mist moving; Mid is calmer; +# Wet/Wetter rare (0 = off). Longer than the acquire light gap so Mid/Wetter +# do not thrash on film that never reaches ACQUIRE_ON. +THIN_GAP_BY_SENS = (18.0, 22.0, 36.0, 48.0, 0.0) +HOLD_OFF = 0.70 +EMA_ALPHA = 0.35 +EMA_HOLD_ALPHA = 0.35 +CLEAR_RELEASE_N = 2 +MIN_HOLD_N = 2 +WIPE_CLEAR_N = 1 +# First looks after helper start (VisionIpc / first ROAD) do not acquire. +WARMUP_N = 2 +# One slow park-to-park sweep. Camera Auto holds INTERVAL1 (physical Int1), +# not TIPWIPE nibble 1 (BCM Wiper Low / ~32 s latch). Pulse then cancel — +# do not sit on continuous Int. poll() ends the pulse on wall-clock so +# we do not wait for the next idle ROAD score. +WIPE_PULSE_S = 1.5 +# After wipe=0 + rest-cancel: ignore ROAD until blades park and streaks +# settle, then assess against the repeat bar. ~2–2.5 s (2.0 s still +# caught blades on bone-dry Auto). +CLEAR_WAIT_S = 2.5 +# Compat aliases (old burst/rest names). Duty cycle uses WIPE_PULSE_S / CLEAR_WAIT_S. +BURST_MAX_N = 1 +BURST_MAX_S = WIPE_PULSE_S +LIGHT_REST_N = 0 +BLADE_BLIND_N = 0 +# Must exceed SCORE_PERIOD_S so poll does not drop HOLD between ticks. +STALE_S = 10.0 +CONNECT_RETRY_S = 0.5 +DEBUG_LOG_S = 1.0 +# Live helper while idle: score windshield clarity once every ~4 s, not +# every ROAD frame / not 4 Hz / 1 Hz. Post-wipe assess uses CLEAR_WAIT_S. +SCORE_PERIOD_S = 4.0 +SCORE_HZ = 1.0 / SCORE_PERIOD_S # ≈ 0.25 Hz +HELPER_RECV_MS = 50 +HELPER_NICE = 10 +# Copy at most this many pixels on the short side from VisionIpc (not full ROAD). +Y_COPY_SIDE = 48 +_FEATURE_SIDE = 24 +_SAT_MAX = 0.08 +# Isolated headlamp plates are sparse hotspots. Dense bead highlights are not. +_LAMP_SPARSE = 200.0 +_SPARSE_MIN = 8.0 +# Dense bead rain on glass is ~6.5–8.5. Justin's upper droplet crop was +# rain-rejected at 6.85. Foliage is still ~1.8. +_SPARSE_RAIN_MIN = 6.0 +_SPARSE_MAX = 80.0 +STREAM_FALLBACK_S = 3.0 +_STRUCTURE_FRAC = 0.05 +# In-focus foliage/brick: sharp residual without rain-scale bokeh. +# Dense beads covering the glass also raise this — do not fail closed. +_STRUCTURE_RAIN = 0.12 +_FOLIAGE_BLOB = 18.0 +_FINE_R = 2 +_MED_R = 4 +_COARSE_R = 8 + +_sensitivity_override: int | None = None + + +def clip_sensitivity(index: int) -> int: + try: + i = int(index) + except (TypeError, ValueError): + return WIPER_SENSITIVITY_DEFAULT + return max(WIPER_SENSITIVITY_MIN, min(WIPER_SENSITIVITY_MAX, i)) + + +def set_wiper_sensitivity(index: int | None) -> None: + """Tests inject 0–4. None returns to NAPWiperSensitivity / mid default.""" + global _sensitivity_override + _sensitivity_override = None if index is None else clip_sensitivity(index) + + +def current_sensitivity() -> int: + if _sensitivity_override is not None: + return clip_sensitivity(_sensitivity_override) + try: + from openpilot.common.params import Params + val = Params().get(NAP_WIPER_SENSITIVITY, return_default=True) + if val is None: + return WIPER_SENSITIVITY_DEFAULT + if isinstance(val, (bytes, bytearray)): + val = val.decode("utf-8", errors="ignore").strip() + return clip_sensitivity(int(val)) + except Exception: + return WIPER_SENSITIVITY_DEFAULT + + +def acquire_threshold(sens: int | None = None) -> float: + if sens is None: + sens = current_sensitivity() + return ACQUIRE_ON * ACQUIRE_SENSITIVITY_SCALE[clip_sensitivity(sens)] + + +def repeat_threshold(sens: int | None = None) -> float: + if sens is None: + sens = current_sensitivity() + return REWIPE_ON * REPEAT_SENSITIVITY_SCALE[clip_sensitivity(sens)] + + +def min_rewipe_gap_light_s(sens: int | None = None) -> float: + """Seconds between wipe starts when score is below HEAVY_ON.""" + if sens is None: + sens = current_sensitivity() + return MIN_REWIPE_GAP_BY_SENS[clip_sensitivity(sens)] + + +def thin_gap_s(sens: int | None = None) -> float: + """Seconds between below-acquire thin-mist maintenance wipes. 0 = off.""" + if sens is None: + sens = current_sensitivity() + return THIN_GAP_BY_SENS[clip_sensitivity(sens)] + + +def acquire_hold_n(sens: int | None = None) -> int: + """Idle looks needed to first-wipe. Drier is 1; Dry+ stay MIN_HOLD_N. + + Park / v≈0 still suppress TX, so one Drier look cannot garage-wipe. + """ + if sens is None: + sens = current_sensitivity() + return 1 if clip_sensitivity(sens) <= 0 else MIN_HOLD_N + + +def y_plane_from_nv12(buf, max_side: int = 0) -> np.ndarray | None: + """Y plane of an NV12 VisionBuf, cropped to width x height (no padding). + + Live helper passes max_side so we never copy a full 3X ROAD frame. + """ + try: + width = int(buf.width) + height = int(buf.height) + stride = int(getattr(buf, "stride", 0) or width) + if width < 16 or height < 16 or stride < width: + return None + data = buf.data + if data is None: + return None + # NV12 Y is bytes. np.asarray(..., dtype=uint8) on a uint16/float view + # wraps or reinterprets and the bokeh residual explodes (49165 vs ~4). + if isinstance(data, np.ndarray) and data.dtype == np.uint8: + raw = data.reshape(-1) + else: + raw = np.frombuffer(memoryview(data).cast("B"), dtype=np.uint8) + if raw.size < stride * height: + return None + y = raw[:stride * height].reshape(height, stride)[:, :width] + if max_side > 0 and min(height, width) > max_side: + step = max(1, min(height, width) // int(max_side)) + y = y[::step, ::step] + return np.ascontiguousarray(y) + except Exception: + return None + + +def _to_y8(img: np.ndarray) -> np.ndarray | None: + """8-bit Y, 0–255. 10/16-bit planes are scaled. Garbage dtype/range is None.""" + if img is None or getattr(img, "ndim", 0) != 2 or img.size < 25: + return None + a = np.asarray(img) + if a.dtype == np.uint8: + return a + af = a.astype(np.float32, copy=False) + if not np.isfinite(af).all(): + return None + mx = float(af.max()) if af.size else 0.0 + mn = float(af.min()) if af.size else 0.0 + if mx > 65535.5 or mn < -1.0: + return None + if mx > 255.5: + if mx <= 1023.5: + af = af * (255.0 / 1023.0) + elif mx <= 4095.5: + af = af * (255.0 / 4095.0) + else: + af = af * (255.0 / 65535.0) + elif mx <= 1.5 and mn >= -0.05: + af = af * 255.0 + return np.clip(af, 0.0, 255.0).astype(np.uint8) + + +def _finite_score(score: float) -> float: + try: + s = float(score) + except (TypeError, ValueError): + return 0.0 + if not np.isfinite(s) or s < 0.0 or s > SCORE_INVALID: + return 0.0 + return s + + +def _band(y: np.ndarray, rows: tuple[float, float], cols: tuple[float, float]) -> np.ndarray: + h, w = y.shape + r0, r1 = int(h * rows[0]), int(h * rows[1]) + c0, c1 = int(w * cols[0]), int(w * cols[1]) + r1 = max(r1, r0 + 4) + c1 = max(c1, c0 + 4) + return y[r0:r1, c0:c1] + + +def _box_blur(x: np.ndarray, radius: int) -> np.ndarray: + """Separable box mean via cumsum. O(HW), no per-tap Python loop.""" + x = np.asarray(x, dtype=np.float32) + if radius < 1: + return x + k = 2 * radius + 1 + kf = float(k) + + def _mean1d(a: np.ndarray, axis: int) -> np.ndarray: + pad_width = [(0, 0), (0, 0)] + pad_width[axis] = (radius, radius) + p = np.pad(a, pad_width, mode="edge") + c = np.cumsum(p, axis=axis) + zshape = list(c.shape) + zshape[axis] = 1 + c = np.concatenate((np.zeros(zshape, dtype=c.dtype), c), axis=axis) + sl_hi = [slice(None), slice(None)] + sl_lo = [slice(None), slice(None)] + sl_hi[axis] = slice(k, None) + sl_lo[axis] = slice(None, -k) + return (c[tuple(sl_hi)] - c[tuple(sl_lo)]) / kf + + return _mean1d(_mean1d(x, 1), 0) + + +def _near_features(img: np.ndarray) -> tuple[float, float, float, float, float, float]: + """Fine blob, speckle, sparsity, sat, strong-edge frac, coarse bokeh energy.""" + z = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + y8 = _to_y8(img) + if y8 is None or y8.size < 25: + return z + step = max(1, min(y8.shape) // _FEATURE_SIDE) + x = y8[::step, ::step].astype(np.float32, copy=False) + if x.shape[0] < 5 or x.shape[1] < 5: + return z + fine = _box_blur(x, _FINE_R) + med = _box_blur(x, _MED_R) + coarse = _box_blur(x, _COARSE_R) + resid = np.abs(x - fine) + blob = float(resid.mean()) + speckle = float(np.mean((x > fine + 18.0) & (resid > 18.0))) + flat = resid.reshape(-1) + p50 = float(np.median(flat)) + k90 = max(0, min(flat.size - 1, int(0.90 * (flat.size - 1)))) + p90 = float(np.partition(flat, k90)[k90]) + sparse = p90 / (p50 + 0.05) + sat = float((x > 240.0).mean()) + structure = float((resid > 40.0).mean()) + # Row-detrend so a vertical sky/road wash is not counted as rain blobs. + bp = np.clip(np.abs(med - coarse), 0.0, 255.0) + row_mean = bp.mean(axis=1, keepdims=True) + if not np.isfinite(blob + speckle + sparse + sat + structure + float(row_mean.mean())): + return z + bp = bp - row_mean + bokeh = float(np.mean(np.abs(bp))) + # Impossible magnitudes: wrong Y scale or bandpass blowup. Not rain. + if (not np.isfinite(bokeh) or bokeh > BOKEH_ABSURD or blob > BLOB_ABSURD + or sparse < 0.0 or sparse > 1.0e4): + return z + return blob, speckle, sparse, sat, structure, bokeh + + +def _band_stats(y: np.ndarray, rows: tuple[float, float], cols: tuple[float, float]) -> tuple[float, float]: + y8 = _to_y8(y) + if y8 is None: + return 0.0, 0.0 + mid = _band(y8, rows, cols) + step = max(1, min(mid.shape) // _FEATURE_SIDE) + x = mid[::step, ::step].astype(np.float32, copy=False) + mean = float(x.mean()) + contrast = float(x.std() / (mean + 1.0)) + return mean, contrast + + +def _mid_stats(y: np.ndarray) -> tuple[float, float]: + return _band_stats(y, _MID_ROWS, _COLS) + + +def _scene_texture(blob: float, sparse: float, structure: float) -> bool: + """Dry indoor/garage + driveway grain. Not a milky wet sheet. + + Justin 5f32c450b: bone-dry garage blob=7.55 sparse=6.7 score=6.29. + Same session light sprinkle was blob=7.4–8.83 sparse=4.7–9.7. Those + are the same look. Heavy overlapping rain is blob~12 sparse~2. + """ + if structure > _STRUCTURE_RAIN: + return False + if blob < _SCENE_BLOB_MIN or blob >= BLOB_WET: + return False + return _SCENE_SPARSE[0] <= sparse <= _SCENE_SPARSE[1] + + +def _rain_from_feats(blob: float, speckle: float, sparse: float, sat: float, + structure: float, bokeh: float) -> float: + if sat > _SAT_MAX and sparse >= _LAMP_SPARSE: + return 0.0 + if structure > _STRUCTURE_RAIN and bokeh < BOKEH_ON: + return 0.0 + if _scene_texture(blob, sparse, structure): + return 0.0 + score = 0.0 + if BOKEH_ON <= bokeh <= BOKEH_ABSURD: + score = max(score, bokeh) + if blob >= BLOB_WET: + score = max(score, blob) + if speckle >= _SPECKLE_MIN: + drop = 12.0 * speckle + # Only a real wet sheet adds blob. Dry garage / residual beads sit + # blob≈7–9 with sparse~5–10 — that is not a milky sheet. + if blob >= BLOB_WET: + drop += blob + score = max(score, drop) + return score + + +def _frost_from_feats(blob: float, _speckle: float, sparse: float, sat: float, + structure: float, _bokeh: float) -> float: + if sat > _SAT_MAX or structure > _STRUCTURE_FRAC: + return 0.0 + if blob > FROST_BLOB_MAX: + return 0.0 + if sparse >= _SPARSE_MIN: + return 0.0 + return blob + + +def _ice_from_feats(blob: float, _speckle: float, _sparse: float, sat: float, + structure: float, _bokeh: float, y: np.ndarray) -> float: + if sat > _SAT_MAX or structure > _STRUCTURE_FRAC or blob > FROST_BLOB_MAX: + return 0.0 + mean, contrast = _mid_stats(y) + if not (ICE_LUM[0] < mean < ICE_LUM[1]): + return 0.0 + haze = ICE_CONTRAST - contrast + if haze <= 0.0 or blob < ICE_BLOB_MIN: + return 0.0 + return 15.0 * haze + blob + + +def _mist_film_from_feats(blob: float, speckle: float, sparse: float, sat: float, + structure: float, bokeh: float) -> float: + """Soft / uniform fine-droplet film. No Y / contrast needed. + + Live highway mist (2db9e6c30): blob=3.93 bokeh=1.42 sparse=3.2 → 2.15 + and holdn=0. Dense drizzle can pile blob toward 8 with *low* bokeh. + Old-FOV dry garage blob~7.5 / bokeh~3.8 / sparse~6.7 must stay 0. + Dry overcast mid-left is blob~2.5 — below the blob floor. + """ + if sat > _SAT_MAX or structure > _STRUCTURE_FRAC: + return 0.0 + if blob < MIST_FILM_BLOB[0]: + return 0.0 + if sparse < MIST_FILM_SPARSE[0] or sparse > MIST_FILM_SPARSE[1]: + return 0.0 + # Garage/old-FOV wet-sheet grain: high blob *and* high bokeh/sparse. + if blob > MIST_FILM_BLOB[1] and (bokeh >= BOKEH_ON or sparse >= 5.5): + return 0.0 + if blob >= BLOB_ABSURD: + return 0.0 + has_bokeh = MIST_FILM_BOKEH[0] <= bokeh <= MIST_FILM_BOKEH[1] + has_speckle = speckle >= MIST_FILM_SPECKLE and blob >= 3.2 + has_film = blob >= 3.2 and bokeh < BOKEH_ON + if not (has_bokeh or has_speckle or has_film): + return 0.0 + return 5.3 + 0.25 * min(blob, 8.0) + 0.4 * max(0.0, bokeh - 0.4) + 8.0 * speckle + + +def _mist_from_feats(blob: float, speckle: float, sparse: float, sat: float, + structure: float, bokeh: float, y: np.ndarray) -> float: + """Near-glass mist film. Distant fog alone must not score. + + Justin 2db9e6c30 highway ~59 mph: small drops/streaks should wipe, but + ROAD looks through the mist (far scene still sharp). Dry garage grain + and calm dry glass must stay off. + """ + film = _mist_film_from_feats(blob, speckle, sparse, sat, structure, bokeh) + if sat > _SAT_MAX or structure > _STRUCTURE_RAIN: + return film + if bokeh < MIST_BOKEH_MIN and speckle < MIST_SPECKLE_MIN: + return film + near_mean, near_c = _band_stats(y, _NEAR_ROWS, _COLS) + _far_mean, far_c = _band_stats(y, _FAR_ROWS, _FAR_COLS) + if not (MIST_LUM[0] < near_mean < MIST_LUM[1]): + return film + if near_c > MIST_NEAR_C or far_c < MIST_FAR_C: + return film + if far_c <= 0.0 or near_c > far_c * MIST_NEAR_OVER_FAR: + return film + haze = MIST_NEAR_C - near_c + veil = 4.6 + 15.0 * haze + 0.8 * max(0.0, bokeh - MIST_BOKEH_MIN) + 20.0 * speckle + return max(film, veil) + + +def _rain_from_band(img: np.ndarray) -> float: + """Soft far-focus bokeh, wet-sheet blob, and/or speckle beads. + + At-or-above: each cue is a floor, not a band. Extra blob/bokeh/speckle + raises the score. Dense beads covering the pane look "structured"; + that is still rain when bokeh is rain-like. Foliage is sharp texture + without that bokeh. Isolated saturated lamps are not rain. + """ + return _rain_from_feats(*_near_features(img)) + + +def windshield_rain_score(y: np.ndarray) -> float: + """Higher = rainier glass (far-focus bokeh, streaks, speckles). + + 3X ROAD is focused on the scene, so windshield drops are large soft + circles of confusion. Heavier water must not score drier. Dense + in-focus texture (foliage, brick) and large saturated headlamp plates + are not treated as rain. + """ + if y is None or y.ndim != 2 or y.shape[0] < 32 or y.shape[1] < 32: + return 0.0 + return max(_rain_from_band(_band(y, rows, _COLS)) for rows in _RAIN_BANDS) + + +def windshield_frost_score(y: np.ndarray) -> float: + """Crystals on the glass: moderate uniform residual, not foliage, not rain drops.""" + if y is None or y.ndim != 2 or y.shape[0] < 32 or y.shape[1] < 32: + return 0.0 + return _frost_from_feats(*_near_features(_band(y, _NEAR_ROWS, _COLS))) + + +def windshield_ice_score(y: np.ndarray) -> float: + """Ice sheet: daytime view through the glass is milky (contrast collapsed).""" + if y is None or y.ndim != 2 or y.shape[1] < 32 or y.shape[0] < 32: + return 0.0 + feats = _near_features(_band(y, _NEAR_ROWS, _COLS)) + return _ice_from_feats(*feats, y) + + +def windshield_mist_score(y: np.ndarray) -> float: + """Light mist / film on near-glass. Distant atmospheric fog scores 0.""" + if y is None or y.ndim != 2 or y.shape[0] < 32 or y.shape[1] < 32: + return 0.0 + mist = 0.0 + near = None + best = None + for rows in _RAIN_BANDS: + feats = _near_features(_band(y, rows, _COLS)) + mist = max(mist, _mist_film_from_feats(*feats)) + if rows == _NEAR_ROWS: + near = feats + if best is None or feats[5] >= best[5]: + best = feats + if near is not None: + mist = max(mist, _mist_from_feats(*near, y)) + if best is not None: + mist = max(mist, _mist_film_from_feats(*best)) + return mist + + +def _score_frame(y: np.ndarray) -> tuple[float, tuple[float, float, float, float, float, float]]: + """One pass: rain + mist film on both lower-left bands; veil/frost/ice on NEAR. + + Status blob/bokeh follow the max-bokeh band. Film must use those same + bands — scoring only NEAR missed live film that showed up in status. + Contrast veil stays on NEAR so dry overcast mid-left does not acquire. + """ + z = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + rain = 0.0 + mist = 0.0 + best = z + near = z + for rows in _RAIN_BANDS: + feats = _near_features(_band(y, rows, _COLS)) + if rows == _NEAR_ROWS: + near = feats + rain = max(rain, _rain_from_feats(*feats)) + mist = max(mist, _mist_film_from_feats(*feats)) + if feats[5] >= best[5]: + best = feats + frost = _frost_from_feats(*near) + ice = _ice_from_feats(*near, y) + mist = max(mist, _mist_from_feats(*near, y), _mist_film_from_feats(*best)) + obs = _finite_score(max(rain / SCORE_ON, frost / FROST_ON, ice / ICE_ON, mist / MIST_ON)) + return obs, best + + +def windshield_obstruction_score(y: np.ndarray) -> float: + """1.0 is the hold line. Rain, frost crystals, or an ice sheet.""" + if y is None or y.ndim != 2 or y.shape[0] < 32 or y.shape[1] < 32: + return 0.0 + obs, _best = _score_frame(y) + return obs + + +def windshield_looks_rainy(y: np.ndarray, prev_hold: bool = False) -> bool: + """True when the glass looks rainy or icy/frosted.""" + score = windshield_obstruction_score(y) + if prev_hold: + return score >= HOLD_OFF + return score >= HOLD_ON + + +windshield_looks_obstructed = windshield_looks_rainy + + +def _drop_realtime() -> None: + """card is CTRL_HIGH. VisionIpc + numpy must not run on that policy.""" + try: + os.sched_setscheduler(0, os.SCHED_OTHER, os.sched_param(0)) + except Exception: + pass + try: + os.nice(HELPER_NICE) + except Exception: + pass + + +class WindshieldRain: + """Live 3X ROAD-camera wet/icy-glass latch for Wiper Auto.""" + + def __init__(self): + self.hold = False + self.ema = 0.0 + self.last_score = 0.0 + self.last_bokeh = 0.0 + self.last_blob = 0.0 + self.last_speckle = 0.0 + self.last_sparse = 0.0 + self.last_sat = 0.0 + self.last_structure = 0.0 + self.n_frames = 0 + self.connected = False + self.last_err = "" + self.stream = "ROAD" + self._client = None + self._failed = False + self._last_frame_t = 0.0 + self._last_connect_t = 0.0 + self._last_log_t = 0.0 + self._stream_idx = 0 + self._stream_t0 = 0.0 + self._lock = threading.Lock() + self._stop = threading.Event() + self._helper: threading.Thread | None = None + self._helper_started = False + self._poll_recv = 0 + self._clear_n = 0 + self._hold_n = 0 + self._wipe_t0 = 0.0 + self._last_wipe_t0 = 0.0 + self._wait_t0 = 0.0 + self._post_wipe = False + self._warm_n = 0 + self._sens = WIPER_SENSITIVITY_DEFAULT + self._acquire_on = ACQUIRE_ON + self._repeat_on = REWIPE_ON + self._gap_light_s = MIN_REWIPE_GAP_LIGHT_S + self._thin_gap_s = THIN_GAP_BY_SENS[WIPER_SENSITIVITY_DEFAULT] + self._thin_t0 = 0.0 + self._thin = False + self._thin_wipe = False + self._acquire_n = MIN_HOLD_N + self._owns_client = False + self._need_flush = False + + def _store_feats(self, feats: tuple[float, float, float, float, float, float]) -> None: + blob, speckle, sparse, sat, structure, bokeh = feats + self.last_blob = blob + self.last_speckle = speckle + self.last_sparse = sparse + self.last_sat = sat + self.last_structure = structure + self.last_bokeh = bokeh + + def update_from_y(self, y: np.ndarray) -> bool: + obs, feats = _score_frame(y) + self._store_feats(feats) + return self._update_score(obs) + + def _thresholds(self) -> tuple[int, float, float, float, float]: + """sens, acquire, repeat, light min-rewipe gap, thin maintenance gap.""" + sens = current_sensitivity() + acquire = acquire_threshold(sens) + repeat = repeat_threshold(sens) + gap_light = min_rewipe_gap_light_s(sens) + gap_thin = thin_gap_s(sens) + self._sens = sens + self._acquire_on = acquire + self._repeat_on = repeat + self._gap_light_s = gap_light + self._thin_gap_s = gap_thin + self._acquire_n = acquire_hold_n(sens) + return sens, acquire, repeat, gap_light, gap_thin + + def _gap_ok(self, now: float, score: float, _repeat: float, gap_light: float) -> bool: + """First wipe has no gap. True heavy may rewipe after CLEAR_WAIT_S. + + Scaled repeat at Drier/Dry sits in the light-film band so those + scores can take the one-look post-wipe path. They still wait the + light gap — only unscaled HEAVY_ON skips it. Mid repeat is HEAVY_ON, + so Mid behavior is unchanged. + """ + last = self._last_wipe_t0 + if last <= 0.0: + return True + if score >= HEAVY_ON: + return True + return (now - last) >= gap_light + + def _start_wipe(self, now: float, thin: bool = False) -> None: + self.hold = True + self._wipe_t0 = now + self._last_wipe_t0 = now + self._wait_t0 = 0.0 + self._post_wipe = False + self._hold_n = self._acquire_n + self._clear_n = 0 + self._thin_t0 = 0.0 + self._thin_wipe = bool(thin) + self._thin = bool(thin) + + def _finish_wipe(self) -> None: + """End the one-sweep pulse. Auto rest-cancels; wait CLEAR_WAIT_S then assess.""" + self.hold = False + self._clear_n = 0 + self._wipe_t0 = 0.0 + self._wait_t0 = time.monotonic() + # Do not prime hold_n. One dry/marginal post-wipe look must exit to idle. + self._hold_n = 0 + self._post_wipe = True + self._thin_t0 = 0.0 + + def _thin_wet(self) -> bool: + """Some wetness at/above the thin floor. EMA covers a one-tick dip.""" + return max(self.last_score, self.ema) >= float(THIN_ON) + + def _maybe_thin_wipe(self, now: float, acquire: float, gap_thin: float) -> None: + """Occasional INTERVAL1 while below acquire. First wipe waits thin_gap. + + last_wipe=0 must not fire on the first thin look — that would thrash + Mid on 2.15 film. After a real wipe, one thin look past thin_gap is + enough (no acquire hold_n). gap_thin<=0 disables the path (Wetter). + """ + in_band = self._thin_wet() and self.last_score < float(acquire) + self._thin = in_band + if (not in_band) or gap_thin <= 0.0: + self._thin_t0 = 0.0 + return + if self._thin_t0 <= 0.0: + self._thin_t0 = now + last = self._last_wipe_t0 + if last <= 0.0: + ready = (now - self._thin_t0) >= float(gap_thin) + else: + ready = (now - last) >= float(gap_thin) + if ready: + self._start_wipe(now, thin=True) + + def _update_score(self, score: float) -> bool: + """Latch from an obstruction score. Tests inject residual/dry scores here.""" + with self._lock: + now = time.monotonic() + self.last_score = _finite_score(score) + _sens, acquire, repeat, gap_light, gap_thin = self._thresholds() + alpha = EMA_HOLD_ALPHA if self.hold else EMA_ALPHA + self.ema = alpha * self.last_score + (1.0 - alpha) * self.ema + waiting = self._wait_t0 > 0.0 and (now - self._wait_t0) < CLEAR_WAIT_S + if self.hold: + if self._wipe_t0 > 0.0 and (now - self._wipe_t0) >= WIPE_PULSE_S: + self._finish_wipe() + elif waiting: + # Blade FOV / glass settling. Do not acquire on this score. + pass + else: + self._wait_t0 = 0.0 + self._clear_n = 0 + if self._post_wipe: + self._post_wipe = False + if (self.last_score >= repeat + and self._gap_ok(now, self.last_score, repeat, gap_light)): + self._start_wipe(now) + else: + # Dry / light mist / marginal → idle. Light needs min rewipe gap. + # Do not thin-wipe on this assess tick (same as not priming hold_n). + self._hold_n = 0 + self._thin_t0 = 0.0 + self._thin = self._thin_wet() and self.last_score < float(acquire) + elif self._warm_n < WARMUP_N: + # First ROAD looks after helper start. Do not acquire. + self._warm_n += 1 + self._hold_n = 0 + self._thin_t0 = 0.0 + self._thin = False + elif self.last_score >= acquire: + self._hold_n += 1 + self._thin = False + self._thin_t0 = 0.0 + if (self._hold_n >= int(self._acquire_n) + and self._gap_ok(now, self.last_score, repeat, gap_light)): + self._start_wipe(now) + else: + # Consecutive idle wet looks only. One below-wet resets acquire. + # Thin maintenance may still INTERVAL1 after thin_gap_s. + self._hold_n = 0 + self._maybe_thin_wipe(now, acquire, gap_thin) + self._last_frame_t = now + self.n_frames += 1 + hold = self.hold + self._debug() + return hold + + def _stream_names(self) -> tuple[str, ...]: + return ("VISION_STREAM_ROAD", "VISION_STREAM_WIDE_ROAD") + + def _maybe_fallback_stream(self, now: float) -> None: + if self.n_frames > 0: + return + if self._stream_t0 <= 0: + self._stream_t0 = now + return + if now - self._stream_t0 < STREAM_FALLBACK_S: + return + names = self._stream_names() + nxt = (self._stream_idx + 1) % len(names) + if nxt == self._stream_idx: + return + self._stream_idx = nxt + self.stream = "WIDE" if "WIDE" in names[nxt] else "ROAD" + self._client = None + self._owns_client = False + self._need_flush = False + self.connected = False + self._stream_t0 = now + self.last_err = f"fallback_{self.stream}" + + def _recv_y(self, timeout_ms: int = 0, max_side: int = 0) -> np.ndarray | None: + now = time.monotonic() + if self._failed and (now - self._last_connect_t) < CONNECT_RETRY_S: + return None + self._failed = False + self._maybe_fallback_stream(now) + try: + if self._client is None: + if now - self._last_connect_t < CONNECT_RETRY_S and self._last_connect_t > 0: + return None + self._last_connect_t = now + from msgq.visionipc import VisionIpcClient, VisionStreamType + st = getattr(VisionStreamType, self._stream_names()[self._stream_idx]) + self._client = VisionIpcClient("camerad", st, True) + self._owns_client = True + self._need_flush = True + self.stream = "WIDE" if "WIDE" in self._stream_names()[self._stream_idx] else "ROAD" + self.connected = bool(self._client.is_connected()) + if not self.connected: + if now - self._last_connect_t < CONNECT_RETRY_S: + self.last_err = self.last_err or "noconnect" + return None + self._last_connect_t = now + if not self._client.connect(False): + self.connected = False + self.last_err = "noconnect" + return None + self.connected = True + self.last_err = "" + buf = self._client.recv(timeout_ms=int(timeout_ms)) + if buf is None: + # Helper blocking timeout is normal. Do not stamp nobuf over a live connect. + if int(timeout_ms) <= 0 and not self.last_err: + self.last_err = "nobuf" + return None + y = y_plane_from_nv12(buf, max_side=max_side) + buf = None + if y is None: + self.last_err = "noyplane" + return None + self.last_err = "" + if self._need_flush: + # First buffer after subscribe is often stale/wrong (blob≈7 dry). + self._need_flush = False + flushed = self._client.recv(timeout_ms=int(timeout_ms)) + if flushed is not None: + y2 = y_plane_from_nv12(flushed, max_side=max_side) + flushed = None + if y2 is not None: + y = y2 + return y + except Exception as e: + self._failed = True + self.connected = False + self._client = None + self._owns_client = False + self._need_flush = False + self._last_connect_t = now + self.last_err = type(e).__name__ + return None + + def _debug(self, reason: str = "") -> None: + """cloudlog at DEBUG_LOG_S. Do not write NAPWiperRainStatus from this thread.""" + now = time.monotonic() + if now - self._last_log_t < DEBUG_LOG_S: + return + self._last_log_t = now + wait_left = 0.0 + if self._wait_t0 > 0.0: + wait_left = max(0.0, CLEAR_WAIT_S - (now - self._wait_t0)) + pulse_left = 0.0 + if self.hold and self._wipe_t0 > 0.0: + pulse_left = max(0.0, WIPE_PULSE_S - (now - self._wipe_t0)) + gap_left = 0.0 + if self._last_wipe_t0 > 0.0: + gap_left = max(0.0, float(self._gap_light_s) - (now - self._last_wipe_t0)) + thin_left = 0.0 + thin_s = float(self._thin_gap_s) + if thin_s > 0.0: + if self._last_wipe_t0 > 0.0: + thin_left = max(0.0, thin_s - (now - self._last_wipe_t0)) + elif self._thin_t0 > 0.0: + thin_left = max(0.0, thin_s - (now - self._thin_t0)) + else: + thin_left = thin_s + age_ms = (now - self._last_frame_t) * 1000.0 if self._last_frame_t else -1.0 + err = f" err={self.last_err}" if self.last_err else "" + why = f" {reason}" if reason else "" + line = ( + f"nap wiper rain hold={int(self.hold)} ema={self.ema:.2f} score={self.last_score:.2f} " + + f"bokeh={self.last_bokeh:.2f} blob={self.last_blob:.2f} speckle={self.last_speckle:.3f} " + + f"sparse={self.last_sparse:.1f} sat={self.last_sat:.3f} struct={self.last_structure:.3f} " + + f"holdn={int(self._hold_n)}/{int(self._acquire_n)} warm={int(self._warm_n)}/{int(WARMUP_N)} " + + f"clear={int(self._clear_n)}/{int(CLEAR_RELEASE_N)} " + + f"sens={int(self._sens)} acq={int(self.last_score >= float(self._acquire_on))} " + + f"rpt={int(self.last_score >= float(self._repeat_on))} " + + f"heavy={int(self.last_score >= HEAVY_ON)} pulse={pulse_left:.1f}/{WIPE_PULSE_S:.1f} " + + f"wait={wait_left:.1f}/{CLEAR_WAIT_S:.1f} gap={gap_left:.1f}/{self._gap_light_s:.1f} " + + f"thin={int(self._thin)} thin_gap={thin_left:.1f}/{thin_s:.1f} " + + f"connected={int(self.connected)} " + + f"failed={int(self._failed)} frames={self.n_frames} stream={self.stream} " + + f"helper={int(self.helper_alive)} period_s={SCORE_PERIOD_S:.1f} hz={SCORE_HZ:.1f} age_ms={age_ms:.0f}{err}{why}" + ) + try: + from openpilot.common.swaglog import cloudlog + cloudlog.info("%s", line) + except Exception: + pass + + @property + def helper_alive(self) -> bool: + t = self._helper + return bool(t is not None and t.is_alive()) + + def _clear_hold(self) -> None: + with self._lock: + self.hold = False + self.ema = 0.0 + self.last_score = 0.0 + self._clear_n = 0 + self._hold_n = 0 + self._wipe_t0 = 0.0 + self._last_wipe_t0 = 0.0 + self._wait_t0 = 0.0 + self._post_wipe = False + self._warm_n = 0 + self._thin_t0 = 0.0 + self._thin = False + self._thin_wipe = False + + def _release_vision(self) -> None: + """Drop the live ROAD client (helper stop / thread exit). Tests inject _client.""" + if not self._owns_client: + return + self._client = None + self._owns_client = False + self._need_flush = False + self.connected = False + + def start_helper(self) -> None: + """Drain ROAD off the card thread. Idempotent. Never join (CTRL_HIGH).""" + t = self._helper + if t is not None and t.is_alive(): + # Still winding down after stop — next stock_cc.update retries. + if not self._stop.is_set(): + self._helper_started = True + return + self._stop = threading.Event() + self._helper_started = True + self._warm_n = 0 + try: + self._helper = threading.Thread(target=self._helper_loop, name="nap-wiper-rain", daemon=True) + self._helper.start() + except Exception as e: + self._helper = None + self._helper_started = False + self.last_err = type(e).__name__ + + def stop_helper(self, join: bool = True) -> None: + """Stop ROAD drain and drop HOLD. join=False from card (do not block RT).""" + t = self._helper + if not self._helper_started and not self.hold and (t is None or not t.is_alive()): + if join: + self._helper = None + return + self._stop.set() + self._helper_started = False + self._clear_hold() + t = self._helper + if join and t is not None and t.is_alive() and t is not threading.current_thread(): + t.join(timeout=0.6) + if join: + self._helper = None + self._release_vision() + + def _next_score_at(self, last_score_t: float, now: float) -> float: + """When the helper should next look at ROAD. + + Idle watching: SCORE_PERIOD_S (~4 s) after the last look. First look + is immediate (assess, do not wipe-first). After a wipe, assess when + CLEAR_WAIT_S elapses against the repeat bar — not another idle 4 s. + """ + with self._lock: + if self.hold and self._wipe_t0 > 0.0: + return self._wipe_t0 + WIPE_PULSE_S + CLEAR_WAIT_S + if self._wait_t0 > 0.0: + return self._wait_t0 + CLEAR_WAIT_S + if last_score_t <= 0.0: + return now + return last_score_t + float(SCORE_PERIOD_S) + + def _helper_loop(self) -> None: + """Recv+score on the idle/wipe-loop cadence. Keep ROAD subscribed while Auto.""" + _drop_realtime() + last_score_t = 0.0 + try: + while not self._stop.is_set(): + now = time.monotonic() + wait = self._next_score_at(last_score_t, now) - now + if wait > 0.0: + # Short chunks so poll() ending a pulse can switch to CLEAR_WAIT_S. + self._stop.wait(min(wait, 0.25)) + continue + try: + y = self._recv_y(timeout_ms=HELPER_RECV_MS, max_side=Y_COPY_SIDE) + except Exception as e: + self._failed = True + self.last_err = type(e).__name__ + y = None + if self._stop.is_set(): + break + if y is not None: + self.update_from_y(y) + last_score_t = time.monotonic() + y = None + else: + self._apply_stale() + if not self.connected or self._failed: + self._stop.wait(CONNECT_RETRY_S) + finally: + self._release_vision() + + def _apply_stale(self) -> None: + """Clear HOLD if ROAD frames stop. Do not wipe dry glass.""" + if self.hold and self._last_frame_t > 0: + if time.monotonic() - self._last_frame_t > STALE_S: + self._clear_hold() + self._debug("stale") + elif not self.hold: + self._debug("noframe") + + def _apply_wipe_pulse(self) -> None: + """End the one-sweep nibble-1 pulse on wall-clock. Latch only (no numpy/recv).""" + with self._lock: + if not self.hold or self._wipe_t0 <= 0.0: + return + if time.monotonic() - self._wipe_t0 < WIPE_PULSE_S: + return + self._finish_wipe() + + def poll(self) -> bool: + """Latch only. Never recv, numpy, Params, or stale-debug on the card RT thread.""" + if not self._helper_started: + return False + if self.hold: + self._apply_stale() + self._apply_wipe_pulse() + return self.hold + + +_detector: WindshieldRain | None = None + + +def ensure_windshield_rain_helper() -> WindshieldRain: + """Start the ROAD drain thread. Called from stock_cc.update while Auto.""" + global _detector + if _detector is None: + _detector = WindshieldRain() + _detector.start_helper() + return _detector + + +def stop_windshield_rain_helper() -> None: + """Off/Int/On: no ROAD recv. Does not join (card is CTRL_HIGH).""" + if _detector is not None: + _detector.stop_helper(join=False) + + +def windshield_rain_needed() -> bool: + """Latch only. stock_cc starts the helper while Auto; do not start from poll.""" + det = _detector + if det is None: + return False + return det.poll() + + +def reset_windshield_rain() -> None: + """Tests reset the singleton.""" + global _detector + set_wiper_sensitivity(None) + if _detector is not None: + _detector.stop_helper() + _detector = None diff --git a/selfdrive/modeld/thneed/__init__.py b/selfdrive/car/tesla/tests/__init__.py similarity index 100% rename from selfdrive/modeld/thneed/__init__.py rename to selfdrive/car/tesla/tests/__init__.py diff --git a/selfdrive/car/tesla/tests/test_preap_blinker_lat_pause.py b/selfdrive/car/tesla/tests/test_preap_blinker_lat_pause.py new file mode 100644 index 00000000000000..c328275d1e5562 --- /dev/null +++ b/selfdrive/car/tesla/tests/test_preap_blinker_lat_pause.py @@ -0,0 +1,760 @@ +"""Pre-AP FSM: blinker-lamp pause must not tear down cruiseEnabled. + +A latched driver turn must leave enableLongControl true. Brake still +drops long (silent pause + one SET). Tip ALC does not drop long. +""" + +from pathlib import Path + +from opendbc.car import Bus, structs +from opendbc.car.tesla.preap.engagement import PreAPEngagement +from opendbc.car.tesla.values import CruiseButtons + +GearShifter = structs.CarState.GearShifter + +from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import ( + _peek_blinker_lamps, + _update_preap, + hard_cancel_session, + install_blinker_lat_pause, + update_card_lat_handoff, +) +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + EMERGENCY_DECEL_FRAMES, + EMERGENCY_DECEL_MPS2, + LAT_REENABLE_MIN_V_EGO, + SOFT_YIELD_DEBOUNCE_FRAMES, +) +from openpilot.selfdrive.car.tesla import preap_blinker_lat_pause as pause_mod +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import LAMP_OFF_DEBOUNCE_S + + +def _engaged(*, double_pull=False): + eng = PreAPEngagement(double_pull_enabled=double_pull, double_pull_window_ms=750) + eng.cruiseEnabled = True + eng.enableLongControl = True + eng.enableJustCC = False + return eng + + +def test_tesla_fsm_keeps_cruise_on_steer_during_one_lamp(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng._nap_right_blinker = False + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_tesla_fsm_hazards_still_tear_down(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng._nap_right_blinker = True + eng.handle_steering_disengage(True) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + + +def test_tesla_fsm_resumes_without_new_engage_after_lamp_clears(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng._nap_right_blinker = False + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + + # Lamp off, hands still on this frame: must not rising-edge tear down. + # Long stays on; cruise/lat latch is unchanged. + eng._nap_left_blinker = False + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + + eng.handle_steering_disengage(False) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_tesla_fsm_no_lamp_still_tears_down(): + install_blinker_lat_pause() + eng = _engaged() + eng.handle_steering_disengage(True) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + + +def test_tesla_fsm_cancel_still_works_during_pause(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng.process_buttons( + cruise_buttons=CruiseButtons.CANCEL, prev_cruise_buttons=0, + curr_time_ms=1000, v_ego=10.0, speed_units="KPH", + use_pedal=True, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=False) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + + +def _buttons(eng, *, cruise_buttons=0, prev=0, t_ms=1000, brake=False): + return eng.process_buttons( + cruise_buttons=cruise_buttons, prev_cruise_buttons=prev, + curr_time_ms=t_ms, v_ego=10.0, speed_units="KPH", + use_pedal=True, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=brake) + + +def test_tesla_fsm_brake_drops_long_and_stays_off(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + _buttons(eng, brake=True, t_ms=2000) + assert eng.cruiseEnabled + assert not eng.enableLongControl + + _buttons(eng, brake=False, t_ms=3000) + assert eng.cruiseEnabled + assert not eng.enableLongControl + + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_tesla_fsm_blinker_brake_then_hand_then_stalk_for_long(): + """Justin sequence: lamp pauses lat, brake drops long (stays off), + hand-steer does not kill cruise, lamp-off with hand on keeps cruise, + hand release keeps cruise, stalk is required to restore long.""" + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + _buttons(eng, brake=True, t_ms=2000) + assert eng.cruiseEnabled + assert not eng.enableLongControl + + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert not eng.enableLongControl + + _buttons(eng, brake=False, t_ms=3000) + assert eng.cruiseEnabled + assert not eng.enableLongControl + + eng._nap_left_blinker = False + eng._nap_steering_pressed = True + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert not eng.enableLongControl + + eng._nap_steering_pressed = False + eng.handle_steering_disengage(False) + assert eng.cruiseEnabled + assert not eng.enableLongControl + + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_tesla_fsm_holds_cruise_until_hand_release_after_lamp(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + + eng._nap_left_blinker = False + eng._nap_steering_pressed = True + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + + # Turn complete (~1s dark), hand still on: cruise stays. Long stays on. + # Lat resumes only after hand release (no SET). Then a later grab tears down. + eng._nap_lat_hold.update(False, False, True, engaged=True, dt=LAMP_OFF_DEBOUNCE_S) + assert not eng._nap_lat_hold.turn_active + assert eng._nap_lat_hold.holding + + eng._nap_steering_pressed = False + eng.handle_steering_disengage(False) + assert eng.cruiseEnabled + assert eng.enableLongControl + + eng.handle_steering_disengage(True) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + + +def test_tesla_fsm_flash_gap_without_hand_keeps_cruise(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + assert eng.cruiseEnabled + assert eng.enableLongControl + + # Lamp dark between flashes, light/no hands, then a grab must not tear down. + eng._nap_left_blinker = False + eng._nap_steering_pressed = False + eng.handle_steering_disengage(False) + assert eng._nap_lat_hold.turn_active + assert eng.cruiseEnabled + assert eng.enableLongControl + + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_tesla_fsm_1s_dark_then_steer_disengages(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + assert eng.cruiseEnabled + + eng._nap_left_blinker = False + eng._nap_lat_hold.update(False, False, False, engaged=True, dt=LAMP_OFF_DEBOUNCE_S) + assert not eng._nap_lat_hold.turn_active + assert not eng._nap_lat_hold.holding + + eng.handle_steering_disengage(True) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + + +class _Parser: + def __init__(self, left, right): + self.vl = {"GTW_carState": {"BC_indicatorLStatus": int(left), "BC_indicatorRStatus": int(right)}} + + +def test_peek_uses_lamp_bits_not_stalk(): + left, right = _peek_blinker_lamps({Bus.chassis: _Parser(True, False)}) + assert left and not right + left, right = _peek_blinker_lamps({Bus.chassis: _Parser(True, True)}) + assert left and right + left, right = _peek_blinker_lamps({}) + assert not left and not right + + +def test_tesla_fsm_alc_lamps_do_not_latch_turn_or_drop_cruise(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng._nap_alc_active = True + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not eng._nap_lat_hold.turn_active + assert eng._nap_lat_hold.blocks_steer_disengage + + +def test_tesla_fsm_highway_stalk_tap_does_not_drop_cruise(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng._nap_stalk_state = 1 + eng._nap_v_ego = 30.0 + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not eng._nap_lat_hold.turn_active + + +def test_tesla_fsm_faster_corner_hands_on_without_torque_threshold(): + """Hands-on 2 with torsion bar below STEER_THRESHOLD must not drop cruise.""" + install_blinker_lat_pause() + eng = _engaged() + eng._nap_left_blinker = True + eng._nap_steering_pressed = False + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert eng._nap_lat_hold.turn_active + + # Flash gap + 1s dark while still wrenching: still the same turn. + eng._nap_left_blinker = False + eng._nap_lat_hold.update(False, False, False, engaged=True, + steering_disengage=True, dt=LAMP_OFF_DEBOUNCE_S) + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert eng._nap_lat_hold.turn_active + + +def test_tesla_fsm_stalk_held_without_lamp_cache_keeps_cruise(): + """Hard gate: physical LEFT/RIGHT even if lamps/hold never latched.""" + install_blinker_lat_pause() + eng = _engaged() + eng._nap_stalk_state = 1 + eng.handle_steering_disengage(True) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +class _FullParser: + def __init__(self, *, left=False, right=False, stalk=1, hands=2, torque=0.0, speed=20.0): + self.vl = { + "GTW_carState": {"BC_indicatorLStatus": int(left), "BC_indicatorRStatus": int(right)}, + "EPAS_sysStatus": {"EPAS_torsionBarTorque": torque, "EPAS_handsOnLevel": hands}, + "STW_ACTN_RQ": {"TurnIndLvr_Stat": stalk}, + "ESP_B": {"ESP_vehicleSpeed": speed}, + } + + +def test_install_rewires_tesla_carstate_imported_update_preap(): + """card.py imports tesla.carstate before install; that binding must wrap.""" + from opendbc.car.tesla import carstate as tesla_carstate + from opendbc.car.tesla.preap import carstate as preap_carstate + + install_blinker_lat_pause() + assert tesla_carstate.update_preap is _update_preap + assert preap_carstate.update_preap is _update_preap + + +def test_update_wrapper_feeds_handle_so_high_torque_keeps_cruise(): + """Live path: wrapper must set _nap_* before orig update calls handle.""" + install_blinker_lat_pause() + eng = _engaged() + called = {} + + def fake_orig(cs, parsers): + called["yes"] = True + cs.engagement.handle_steering_disengage(True) + return "ok" + + real = pause_mod._ORIG_UPDATE + pause_mod._ORIG_UPDATE = fake_orig + try: + cs = type("CS", (), {"engagement": eng})() + parsers = {Bus.chassis: _FullParser(left=True, stalk=1, hands=2)} + assert _update_preap(cs, parsers) == "ok" + assert called["yes"] + assert eng._nap_left_blinker + assert eng._nap_stalk_state == 1 + assert eng.cruiseEnabled + # First frame of LEFT+lamp is still the tip window; a later driver-turn + # latch must also leave long on. + assert eng.enableLongControl + finally: + pause_mod._ORIG_UPDATE = real + + +def _end_turn_latch(eng, *, pressed=False): + """Advance past flash-latch (~1s dark). Lat may still be holding if pressed.""" + eng._nap_left_blinker = False + eng._nap_right_blinker = False + eng._nap_steering_pressed = pressed + eng._nap_lat_hold.update(False, False, pressed, engaged=True, dt=LAMP_OFF_DEBOUNCE_S) + eng.handle_steering_disengage(False) + + +def test_latched_driver_turn_leaves_long_on(): + """Held/latched driver turn must not drop enableLongControl.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not eng.enableJustCC + assert eng._nap_lat_hold.turn_active + assert not getattr(eng, "_nap_long_resume_pending", False) + + +def test_latched_turn_keeps_long_while_lat_paused(): + """After blinker/latch ends, long is still on even if lat is still paused.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_left_blinker = True + eng.handle_steering_disengage(True) + assert eng.enableLongControl + assert eng._nap_lat_hold.turn_active + + _end_turn_latch(eng, pressed=True) + assert not eng._nap_lat_hold.turn_active + assert eng._nap_lat_hold.holding + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not getattr(eng, "_nap_long_resume_pending", False) + + +def test_latched_turn_keeps_long_when_lat_already_active(): + """After blinker/latch ends and hands are off, long is still on.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + assert eng.enableLongControl + + _end_turn_latch(eng, pressed=False) + assert not eng._nap_lat_hold.turn_active + assert not eng._nap_lat_hold.holding + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_set_during_active_turn_does_not_drop_long(): + """SET while a turn lamp is showing must leave long on.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + assert eng.enableLongControl + assert eng._nap_lat_hold.turn_active + + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=2000) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not getattr(eng, "_nap_long_resume_pending", False) + + +def test_lamps_dark_before_latch_expires_still_keeps_long(): + """Blinker off / flash gap must not drop long while turn_active is latched.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + assert eng.enableLongControl + assert eng._nap_lat_hold.turn_active + + eng._nap_left_blinker = False + eng.handle_steering_disengage(False) + assert eng._nap_lat_hold.turn_active + assert eng.enableLongControl + + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=2500) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_brake_still_drops_long_during_driver_turn(): + """Brake silent long pause still works while a driver turn is latched.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + assert eng.enableLongControl + assert eng._nap_lat_hold.turn_active + + _buttons(eng, brake=True, t_ms=2000) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert getattr(eng, "_nap_long_resume_pending", False) + + _buttons(eng, brake=False, t_ms=3000) + assert not eng.enableLongControl + + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000) + assert eng.enableLongControl + + +def test_tip_alc_does_not_drop_long(): + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_left_blinker = True + eng._nap_alc_active = True + eng.handle_steering_disengage(False) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not eng._nap_lat_hold.turn_active + + +def test_stalk_tip_pending_does_not_drop_long(): + """LEFT/RIGHT inside the 0.40s tip window is ALC, not a turn.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_left_blinker = True + eng._nap_stalk_state = 1 + eng.handle_steering_disengage(False) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not eng._nap_lat_hold.turn_active + + +def test_single_pull_from_disengaged_engages_long(): + """A fresh rolling engage is lat+long, not a sticky-MAX resume.""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not getattr(eng, "_nap_set_resume_long", False) + assert getattr(eng, "_nap_set_take_speed_now", False) + + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1400) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_brake_drop_one_set_resumes_long_with_double_pull(): + """Same SET resume path after brake: one pull, not two.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + _buttons(eng, brake=True, t_ms=2000) + assert eng.cruiseEnabled + assert not eng.enableLongControl + + _buttons(eng, brake=False, t_ms=3000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def _intent_then_brake(eng, *, a_ego, brake, frames=None, hands=1): + if frames is None: + frames = EMERGENCY_DECEL_FRAMES + for _ in range(SOFT_YIELD_DEBOUNCE_FRAMES): + update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, + steering_torque=1.5, steering_rate_deg=20.0, hands_on_level=hands, + brake_applied=False, a_ego=0.0, v_ego=15.0, param_on=True) + canceled = False + for _ in range(frames): + canceled = update_card_lat_handoff( + eng, engaged=bool(eng.cruiseEnabled), lat_would_be_active=True, + steering_torque=0.2, steering_rate_deg=8.0, hands_on_level=hands, + brake_applied=brake, a_ego=a_ego, v_ego=15.0, param_on=True) + return canceled + + +def test_emergency_hard_brake_while_yielded_full_cancels_session(): + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + canceled = _intent_then_brake(eng, a_ego=EMERGENCY_DECEL_MPS2, brake=True) + assert canceled + assert not eng.cruiseEnabled + assert not eng.enableLongControl + assert eng.preap_cc_cancel_needed + assert getattr(eng, "_nap_long_resume_pending", False) is False + assert getattr(eng, "_nap_held_max_kph", None) is None + + +def test_light_brake_while_yielded_does_not_full_cancel(): + """Sticky-MAX silent pause stays the light-brake path.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + canceled = _intent_then_brake(eng, a_ego=-1.1, brake=True, frames=40) + assert not canceled + assert eng.cruiseEnabled + _buttons(eng, brake=True, t_ms=2000) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert getattr(eng, "_nap_long_resume_pending", False) + + +def test_hard_cancel_session_is_not_silent_long_pause(): + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_long_resume_pending = True + eng._nap_held_max_kph = 88.5 + hard_cancel_session(eng) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + assert not getattr(eng, "_nap_long_resume_pending", False) + assert getattr(eng, "_nap_held_max_kph", None) is None + + +def test_card_handoff_keeps_yield_during_driver_turn_blinker(): + """Soft-lat On must not treat lamp latch as lat-down (that forgot yield).""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + for _ in range(SOFT_YIELD_DEBOUNCE_FRAMES): + update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, + steering_torque=1.5, steering_rate_deg=20.0, hands_on_level=1, + brake_applied=False, a_ego=0.0, v_ego=15.0, param_on=True) + assert eng._nap_lat_handoff._yielded + # Driver-turn blinker + lat still requested: stay yielded, no identity reset. + out = update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, + steering_torque=0.2, steering_rate_deg=0.0, hands_on_level=1, + brake_applied=False, a_ego=0.0, v_ego=15.0, param_on=True, + blinker_paused=True) + assert not out + assert eng._nap_lat_handoff._yielded + canceled = False + for _ in range(EMERGENCY_DECEL_FRAMES): + canceled = update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, + steering_torque=0.2, steering_rate_deg=0.0, hands_on_level=1, + brake_applied=True, a_ego=EMERGENCY_DECEL_MPS2, v_ego=15.0, + param_on=True, blinker_paused=True) + assert canceled + assert not eng.cruiseEnabled + + +def test_card_handoff_keeps_yield_below_10_mph(): + """Same re-enable inhibit as blinker: stay yielded below 10 mph.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + for _ in range(SOFT_YIELD_DEBOUNCE_FRAMES): + update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, + steering_torque=1.5, steering_rate_deg=20.0, hands_on_level=1, + brake_applied=False, a_ego=0.0, v_ego=15.0, param_on=True) + assert eng._nap_lat_handoff._yielded + slow = LAT_REENABLE_MIN_V_EGO - 0.05 + for _ in range(20): + out = update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, + steering_torque=0.0, steering_rate_deg=0.0, hands_on_level=0, + brake_applied=False, a_ego=0.0, v_ego=slow, param_on=True) + assert not out + assert eng._nap_lat_handoff._yielded + assert not eng._nap_lat_handoff._blending + # Blinker-on still inhibits at highway speed on the card path. + for _ in range(20): + out = update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, + steering_torque=0.0, steering_rate_deg=0.0, hands_on_level=0, + brake_applied=False, a_ego=0.0, v_ego=15.0, param_on=True, + blinker_paused=True) + assert not out + assert eng._nap_lat_handoff._yielded + + +def test_card_update_preap_does_not_clear_lat_on_blinker_when_soft_lat_on(): + src = (Path(__file__).resolve().parents[4] / + "selfdrive/car/tesla/preap_blinker_lat_pause.py").read_text() + assert "lat_would_be_active=True" in src + assert "hold.turn_active" in src + assert "lat_would_be_active=not blinker_paused" not in src + + +def test_reverse_while_engaged_hard_cancels_session(): + """Reverse must full-teardown, not leave sticky / soft-lat / panda latch.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_long_resume_pending = True + eng._nap_held_max_kph = 100.0 + eng._nap_left_blinker = True + for _ in range(SOFT_YIELD_DEBOUNCE_FRAMES): + update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, + steering_torque=1.5, steering_rate_deg=20.0, hands_on_level=1, + brake_applied=False, a_ego=0.0, v_ego=15.0, param_on=True) + assert eng._nap_lat_handoff._yielded + + assert not eng.check_can_engage(False, GearShifter.reverse, False) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + assert not eng.enableJustCC + assert not eng.pending_enable + assert eng.pedal_speed_kph == 0.0 + assert eng.preap_cc_cancel_needed + assert getattr(eng, "_nap_held_max_kph", None) is None + assert not getattr(eng, "_nap_long_resume_pending", False) + assert not eng._nap_lat_handoff._yielded + + # Door uses the same hard-cancel path. + eng = _engaged(double_pull=True) + eng._nap_held_max_kph = 70.0 + assert not eng.check_can_engage(True, GearShifter.drive, False) + assert not eng.cruiseEnabled + assert eng.preap_cc_cancel_needed + assert getattr(eng, "_nap_held_max_kph", None) is None + + +def test_reverse_then_drive_allows_fresh_engage_not_sticky_resume(): + """After Drive returns, double SET is a new session — no Controls Mismatch latch.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_long_resume_pending = True + eng._nap_held_max_kph = 88.5 + + assert not eng.check_can_engage(False, GearShifter.reverse, False) + assert not eng.cruiseEnabled + assert eng.preap_cc_cancel_needed + + # Gear back to Drive: session stays down until a normal engage. + assert eng.check_can_engage(False, GearShifter.drive, False) + assert not eng.cruiseEnabled + assert not getattr(eng, "_nap_long_resume_pending", False) + + # First SET is a fresh lat+long engage, not a silent long resume at held MAX. + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=5000) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert getattr(eng, "_nap_held_max_kph", None) is None + assert not getattr(eng, "_nap_set_resume_long", False) + assert not getattr(eng, "_nap_long_resume_pending", False) + + +def test_park_then_drive_allows_fresh_engage_not_sticky_resume(): + """Park is the same latch as Reverse: Drive + double SET is a new session.""" + install_blinker_lat_pause() + eng = _engaged(double_pull=True) + eng._nap_held_max_kph = 72.0 + assert not eng.check_can_engage(False, GearShifter.park, False) + assert not eng.cruiseEnabled + assert eng.preap_cc_cancel_needed + assert eng.check_can_engage(False, GearShifter.drive, False) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=5000) + _buttons(eng, t_ms=5050) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=5400) + assert eng.cruiseEnabled + assert eng.enableLongControl + + +def test_panda_gear_out_clears_cruise_latch(): + """Panda must pcm_cruise_check(false) on gear-out, not controls_allowed=false alone.""" + rx = (Path(__file__).resolve().parents[4] / + "opendbc_repo/opendbc/safety/modes/tesla_preap_rx.h").read_text() + assert "if (preap_gear != 4)" in rx + gear_block = rx.split("if (preap_gear != 4)")[1].split("preap_gear_prev = preap_gear")[0] + assert "pcm_cruise_check(false)" in gear_block + assert "controls_allowed = false" not in gear_block + assert "preap_last_stalk_engage_us = 0U" in gear_block + assert "preap_gear_prev != 4" not in gear_block + + +def test_panda_drive_set_matches_stalk_cancel_rearm(): + """Drive SET while !allowed must pulse pcm_cruise_check(false) then true.""" + rx = (Path(__file__).resolve().parents[4] / + "opendbc_repo/opendbc/safety/modes/tesla_preap_rx.h").read_text() + set_block = rx.split("if (lever == 2)")[1].split("else if (lever == 1)")[0] + assert "if (!controls_allowed)" in set_block + assert "pcm_cruise_check(false)" in set_block + assert "pcm_cruise_check(true)" in set_block + + +def test_panda_tx_cancel_clears_latch_when_disallowed(): + """TX-only CANCEL spoof must re-arm the latch without dropping an engaged session.""" + tx = (Path(__file__).resolve().parents[4] / + "opendbc_repo/opendbc/safety/modes/tesla_preap_tx.h").read_text() + assert "msg->addr == 0x45U" in tx + cancel_block = tx.split("msg->addr == 0x45U")[1].split("DAS_steeringControl")[0] + assert "lever == 1" in cancel_block + assert "!controls_allowed" in cancel_block + assert "pcm_cruise_check(false)" in cancel_block + + +def test_park_while_engaged_is_also_hard_cancel(): + install_blinker_lat_pause() + eng = _engaged() + assert not eng.check_can_engage(False, GearShifter.park, False) + assert not eng.cruiseEnabled + assert eng.preap_cc_cancel_needed + + +def test_check_can_engage_wrapper_is_installed(): + src = (Path(__file__).resolve().parents[4] / + "selfdrive/car/tesla/preap_blinker_lat_pause.py").read_text() + assert "PreAPEngagement.check_can_engage = _check_can_engage" in src + assert "hard_cancel_session(self)" in src + + +def test_selfdrived_mismatch_clear_is_while_not_in_drive(): + """3X/OP mismatch latch stays clear while out of Drive, not on Drive entry.""" + src = (Path(__file__).resolve().parents[4] / + "selfdrive/selfdrived/selfdrived.py").read_text() + assert "preap_not_in_drive_clears_mismatch" in src + helpers = (Path(__file__).resolve().parents[4] / + "selfdrive/selfdrived/helpers.py").read_text() + assert "Do not clear on Drive entry" in helpers + assert "preap_not_in_drive_clears_mismatch" in helpers diff --git a/selfdrive/car/tesla/tests/test_preap_body_controls.py b/selfdrive/car/tesla/tests/test_preap_body_controls.py new file mode 100644 index 00000000000000..2bc30d44a79ed1 --- /dev/null +++ b/selfdrive/car/tesla/tests/test_preap_body_controls.py @@ -0,0 +1,3667 @@ +"""0x45 stalk wiper / high-beam test. Off matches today's forwarded stalk.""" +import time + +import numpy as np + +from openpilot.selfdrive.car.tesla.preap_body_controls import ( + BEAM_SETTING_HIGH, + BEAM_SETTING_LOW, + BEAM_SETTING_OFF, + NAP_HIGH_LOW_BEAM, + NAP_WIPER_SPEED, + STW_ACTN_RQ_ADDR, + STW_CANCEL_BURST_N, + STW_HIBM_MASK, + STW_HIGH_BEAM, + STW_HIGH_BEAM_FLASH, + STW_TURN_MASK, + STW_WASHER_SPRAY, + STW_WIPER_BEAM_BYTE, + STW_WIPER_ON, + STW_COLLAR_INTERVAL1, + STW_WASH_MASK, + apply_stw_collar, + overlay_collar_on_can_msg, + requested_auto_collar_posn, + stw_collar_posn, + stw_wash, + WIPER_SETTING_AUTO, + WIPER_SETTING_INTERMITTENT, + WIPER_SETTING_OFF, + WIPER_SETTING_ON, + apply_stw_wiper_beam_nibbles, + extra_stw_forward_needed, + high_beam_test_requested, + hibm_nibble, + live_stw_counter, + overlay_stw_wiper_beam, + rain_wiper_needed, + register_nap_body_params, + replace_relayed_stw, + reset_auto_gates, + send_replaced_live_stw, + set_auto_gates, + set_cereal_gear, + set_rain_wiper_needed, + stalk_test_active, + wiper_rest_tx_needed, + wiper_test_requested, +) +from openpilot.selfdrive.car.tesla.preap_windshield_rain import ( + ACQUIRE_ON, + BLOB_WET, + BOKEH_ABSURD, + BOKEH_ON, + CLEAR_RELEASE_N, + CLEAR_WAIT_S, + CONNECT_RETRY_S, + FROST_ON, + HEAVY_ON, + HOLD_OFF, + HOLD_ON, + ICE_ON, + MIN_HOLD_N, + REWIPE_ON, + SCORE_ABSURD, + SCORE_HZ, + SCORE_INVALID, + SCORE_OFF, + SCORE_ON, + SCORE_PERIOD_S, + STALE_S, + STREAM_FALLBACK_S, + WIPE_CLEAR_N, + WIPE_PULSE_S, + WARMUP_N, + Y_COPY_SIDE, + MIN_REWIPE_GAP_LIGHT_S, + THIN_ON, + WindshieldRain, + acquire_hold_n, + acquire_threshold, + min_rewipe_gap_light_s, + repeat_threshold, + thin_gap_s, + reset_windshield_rain, + set_wiper_sensitivity, + windshield_frost_score, + windshield_ice_score, + windshield_looks_rainy, + windshield_mist_score, + windshield_obstruction_score, + windshield_rain_score, + y_plane_from_nv12, +) + + +def _rest() -> bytes: + # Justin's parked capture, counter/checksum ignored for packing. + return bytes.fromhex("00ff000000000000") + + +def _byte(dat: bytes) -> int: + return dat[STW_WIPER_BEAM_BYTE] + + +def test_setting_maps_to_stalk_test_flags(): + assert not wiper_test_requested(WIPER_SETTING_OFF) + assert wiper_test_requested(WIPER_SETTING_INTERMITTENT) + assert wiper_test_requested(WIPER_SETTING_ON) + assert not wiper_test_requested(WIPER_SETTING_AUTO) + assert not wiper_test_requested(WIPER_SETTING_AUTO, False) + assert wiper_test_requested(WIPER_SETTING_AUTO, True) + assert not wiper_test_requested(WIPER_SETTING_OFF, True) + assert wiper_test_requested(WIPER_SETTING_INTERMITTENT, False) + assert wiper_test_requested(WIPER_SETTING_ON, False) + assert not high_beam_test_requested(BEAM_SETTING_OFF) + assert not high_beam_test_requested(BEAM_SETTING_LOW) + assert high_beam_test_requested(BEAM_SETTING_HIGH) + + +def test_byte_packing_rest_wiper_high_both_never_spray(): + rest = _rest() + assert apply_stw_wiper_beam_nibbles(rest, False, False) == rest + assert _byte(apply_stw_wiper_beam_nibbles(rest, True, False)) == STW_WIPER_ON + assert _byte(apply_stw_wiper_beam_nibbles(rest, False, True)) == STW_HIGH_BEAM + assert _byte(apply_stw_wiper_beam_nibbles(rest, True, True)) == (STW_WIPER_ON | STW_HIGH_BEAM) + + packed = [ + apply_stw_wiper_beam_nibbles(rest, False, False), + apply_stw_wiper_beam_nibbles(rest, True, False), + apply_stw_wiper_beam_nibbles(rest, False, True), + apply_stw_wiper_beam_nibbles(rest, True, True), + ] + assert all(_byte(dat) != STW_WASHER_SPRAY for dat in packed) + assert all((_byte(dat) & 0x0F) != STW_HIGH_BEAM_FLASH for dat in packed) + assert all(dat[:2] == rest[:2] and dat[3:] == rest[3:] for dat in packed) + + +def test_off_leaves_real_stalk_nibbles_alone(): + held_wiper = bytes.fromhex("00ff100000000000") + held_high = bytes.fromhex("00ff040000000000") + held_both = bytes.fromhex("00ff140000000000") + spray = bytes.fromhex("00ff200000000000") + assert apply_stw_wiper_beam_nibbles(held_wiper, False, False) == held_wiper + assert apply_stw_wiper_beam_nibbles(held_high, False, False) == held_high + assert apply_stw_wiper_beam_nibbles(held_both, False, False) == held_both + # Off must not force 0 over a stalk the driver is holding, including spray. + assert apply_stw_wiper_beam_nibbles(spray, False, False) == spray + # On replaces spray with wiper 1 instead of sending 2. + assert _byte(apply_stw_wiper_beam_nibbles(spray, True, False)) == STW_WIPER_ON + # Auto dry / wipe-release cancel does clear nibble 1 to rest. + assert apply_stw_wiper_beam_nibbles(held_wiper, False, False, clear_wiper=True) == _rest() + assert _byte(apply_stw_wiper_beam_nibbles(held_both, False, True, clear_wiper=True)) == STW_HIGH_BEAM + assert _byte(apply_stw_wiper_beam_nibbles(spray, False, False, clear_wiper=True)) != STW_WASHER_SPRAY + + +def test_overlay_off_is_identity_including_crc(): + rest = _rest() + assert overlay_stw_wiper_beam(rest, False, False, crc_fn=lambda _: 0xAA) == rest + + +def test_overlay_resigns_crc_only_when_changed(): + rest = _rest() + out = overlay_stw_wiper_beam(rest, True, False, crc_fn=lambda payload: sum(payload) & 0xFF) + assert _byte(out) == STW_WIPER_ON + assert out[:7] != rest[:7] + assert out[7] == (sum(out[:7]) & 0xFF) + held = overlay_stw_wiper_beam(rest, False, True, crc_fn=lambda payload: sum(payload) & 0xFF) + assert hibm_nibble(held) == STW_HIGH_BEAM + assert held[7] == (sum(held[:7]) & 0xFF) + cleared = overlay_stw_wiper_beam( + bytes.fromhex("00ff100000000000"), False, False, crc_fn=lambda payload: sum(payload) & 0xFF, + clear_wiper=True) + assert _byte(cleared) == 0 + assert cleared[7] == (sum(cleared[:7]) & 0xFF) + assert overlay_stw_wiper_beam(rest, False, False, crc_fn=lambda _: 0xAA, clear_wiper=True) == rest + + +def test_high_keeps_sending_captured_00ff04_not_sna_or_rest(): + """Real stalk holds 00ff04. High must keep sending that, not a one-shot press.""" + rest = _rest() + captured_high = bytes.fromhex("00ff04") + assert rest[:3] == bytes.fromhex("00ff00") + for _ in range(50): + held = apply_stw_wiper_beam_nibbles(rest, False, True) + assert held[:3] == captured_high + assert hibm_nibble(held) == STW_HIGH_BEAM + assert hibm_nibble(held) != 0 + assert hibm_nibble(held) != STW_HIGH_BEAM_FLASH + assert (hibm_nibble(held) & STW_HIBM_MASK) != STW_HIBM_MASK # not SNA + off = apply_stw_wiper_beam_nibbles(rest, False, False) + assert off == rest + assert off[:3] == bytes.fromhex("00ff00") + + +def test_off_low_then_high_holds_4_again(): + rest = _rest() + assert apply_stw_wiper_beam_nibbles(rest, False, False) == rest + assert apply_stw_wiper_beam_nibbles(rest, False, high_beam_test_requested(BEAM_SETTING_LOW)) == rest + held = apply_stw_wiper_beam_nibbles(rest, False, high_beam_test_requested(BEAM_SETTING_HIGH)) + assert hibm_nibble(held) == STW_HIGH_BEAM + + +def test_high_overlay_preserves_turn_indicator_bits(): + blinker = bytes.fromhex("00ff010000000000") + held = apply_stw_wiper_beam_nibbles(blinker, False, True) + assert _byte(held) & STW_TURN_MASK == 0x01 + assert hibm_nibble(held) == STW_HIGH_BEAM + off = apply_stw_wiper_beam_nibbles(blinker, False, False) + assert off == blinker + + +def test_wiper_overlay_stays_held_with_high_nibble_4(): + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, True, False) + assert _byte(held) == STW_WIPER_ON + assert apply_stw_wiper_beam_nibbles(rest, True, False) == held + both = apply_stw_wiper_beam_nibbles(held, True, True) + assert _byte(both) == (STW_WIPER_ON | STW_HIGH_BEAM) + assert _byte(both) & 0xF0 == STW_WIPER_ON + assert hibm_nibble(both) == STW_HIGH_BEAM + still = apply_stw_wiper_beam_nibbles(held, True, True) + assert still == both + + +def test_stalk_test_active_is_settings_only(): + assert not stalk_test_active(False, False) + assert stalk_test_active(True, False) + assert stalk_test_active(False, True) + + +def test_extra_forward_only_when_on_and_no_existing_0x45(): + existing = [(STW_ACTN_RQ_ADDR, b"\x00" * 8, 0)] + assert extra_stw_forward_needed([], 10, False, False) is False + assert extra_stw_forward_needed([], 11, True, False) is False + assert extra_stw_forward_needed(existing, 10, True, False) is False + assert extra_stw_forward_needed([], 10, True, False) is True + assert extra_stw_forward_needed([], 20, False, True) is True + # Held High must TX between 10 Hz slots so bus-0 IDLE cannot sit unopposed. + assert extra_stw_forward_needed([], 11, False, True) is True + assert extra_stw_forward_needed([], 11, True, False) is False + assert extra_stw_forward_needed(existing, 11, False, True) is False + # Camera Auto + rain holds INTERVAL1 at High's 10 ms last-win, not 10 Hz Int. + auto_rain = wiper_test_requested(WIPER_SETTING_AUTO, True) + auto_dry = wiper_test_requested(WIPER_SETTING_AUTO, False) + assert extra_stw_forward_needed([], 10, auto_rain, False, collar_hold=True) is True + assert extra_stw_forward_needed([], 11, auto_rain, False, collar_hold=True) is True + assert extra_stw_forward_needed([], 11, auto_rain, False) is False # Int-style without collar_hold + assert extra_stw_forward_needed([], 10, auto_dry, False) is False + assert extra_stw_forward_needed(existing, 10, auto_rain, False, collar_hold=True) is False + assert extra_stw_forward_needed([], 10, auto_rain, False) is True + # Auto dry still extra-forwards rest (cancel). Falling-edge cancel_now + # does not wait for the 10 Hz slot. Off with no cancel leaves the stalk. + assert extra_stw_forward_needed([], 10, auto_dry, False, wiper_cancel=True) is True + assert extra_stw_forward_needed([], 11, auto_dry, False, wiper_cancel=True) is False + assert extra_stw_forward_needed([], 11, auto_dry, False, wiper_cancel=True, cancel_now=True) is True + assert extra_stw_forward_needed(existing, 10, auto_dry, False, wiper_cancel=True) is False + assert extra_stw_forward_needed(existing, 11, auto_dry, False, wiper_cancel=True, cancel_now=True) is False + + +def test_settings_copy_describes_held_4_same_counter_replace(): + from openpilot.selfdrive.ui.layouts.settings.nap_content import HIGH_LOW_BEAM_DESCRIPTION + text = HIGH_LOW_BEAM_DESCRIPTION.lower() + assert "nibble 4" in text + assert "hold" in text + assert "same counter" in text + assert "rest" in text or "idle" in text + assert "second 0x45" in text + assert "off/low" in text + assert "not a one-shot tap" in text + assert "00ff04" in text + assert "flash" in text + assert "pulse" not in text + assert "sna" not in text + + +def test_settings_copy_describes_auto_rain_hold(): + from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + WIPER_HUD_AUTO, WIPER_HUD_OFF, WIPER_SPEED_AUTO, WIPER_SPEED_DESCRIPTION, + WIPER_SPEED_LABELS, WIPER_SPEED_OFF, WIPER_SPEED_VALUES, + coerce_wiper_speed_param, normalize_wiper_speed, wiper_hud_text, + wiper_speed_button_index, + ) + assert WIPER_SPEED_VALUES == [0, 3] + assert WIPER_SPEED_LABELS == ["Off", "Auto"] + assert WIPER_SPEED_OFF == 0 + assert WIPER_SPEED_AUTO == 3 + assert "Int" not in WIPER_SPEED_LABELS + assert "On" not in WIPER_SPEED_LABELS + assert wiper_speed_button_index(0) == 0 + assert wiper_speed_button_index(3) == 1 + assert wiper_speed_button_index(1) == 0 + assert wiper_speed_button_index(2) == 0 + assert normalize_wiper_speed(1) == 0 + assert normalize_wiper_speed(2) == 0 + assert normalize_wiper_speed(3) == 3 + assert wiper_hud_text(0) == WIPER_HUD_OFF == "Wipers Off" + assert wiper_hud_text(3) == WIPER_HUD_AUTO == "Wipers Auto" + + class _Params: + def __init__(self, value): + self.value = value + def get(self, key, return_default=True): + return self.value + def put(self, key, value): + self.value = value + + stale = _Params(1) + assert coerce_wiper_speed_param(stale) == 0 + assert stale.value == 0 + on_stale = _Params(2) + assert coerce_wiper_speed_param(on_stale) == 0 + assert on_stale.value == 0 + auto = _Params(3) + assert coerce_wiper_speed_param(auto) == 3 + assert auto.value == 3 + + text = WIPER_SPEED_DESCRIPTION.lower() + assert "auto" in text + assert "rain" in text or "windshield" in text + assert "ice" in text or "frost" in text + assert "camera" in text + assert "interval1" in text or "collar" in text + assert "hold" in text + assert "spray" in text + assert "das" in text + assert "opt-in" in text or "not every drive" in text + assert "headlight" in text + assert "drive" in text + assert "reverse" in text + assert "park" in text + assert "standstill" in text or "v≈0" in text or "creep" in text + assert "rest" in text + assert "cancel" in text + assert "double-flick" in text or "flick" in text + assert "1 s" in text or "1s" in text + assert "pulse" not in text + assert "rainprob" not in text + assert "int/on" not in text + + +def test_settings_copy_describes_wiper_sensitivity(): + from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + WIPER_SENSITIVITY_DEFAULT, WIPER_SENSITIVITY_DESCRIPTION, + WIPER_SENSITIVITY_LABELS, WIPER_SENSITIVITY_VALUES, + ) + assert WIPER_SENSITIVITY_VALUES == [0, 1, 2, 3, 4] + assert len(WIPER_SENSITIVITY_LABELS) == 5 + assert WIPER_SENSITIVITY_DEFAULT == 2 + text = WIPER_SENSITIVITY_DESCRIPTION.lower() + assert "dry" in text + assert "wet" in text + assert "mid" in text + assert "spray" in text + + +def test_auto_rain_signal_sets_and_clears_hold(): + try: + set_rain_wiper_needed(False) + assert not rain_wiper_needed() + assert not wiper_test_requested(WIPER_SETTING_AUTO, rain_wiper_needed()) + set_rain_wiper_needed(True) + assert rain_wiper_needed() + assert wiper_test_requested(WIPER_SETTING_AUTO, rain_wiper_needed()) + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, True, False) + assert _byte(held) == STW_WIPER_ON + assert _byte(held) != STW_WASHER_SPRAY + set_rain_wiper_needed(False) + assert not rain_wiper_needed() + released = apply_stw_wiper_beam_nibbles(rest, False, False) + assert released == rest + finally: + set_rain_wiper_needed(None) + + +def _dry_windshield(h=240, w=320, seed=0) -> np.ndarray: + """Dry 3X ROAD stand-in: sky + distant grain up top; smoother near-glass below. + + Live dry garage scored blob≈7.5 on the old upper-mid crop. Rain now + looks at the lower driver-side glass, so keep that region calm. + """ + rng = np.random.RandomState(seed) + y = np.full((h, w), 128, np.uint8) + y[:int(h * 0.32)] = np.linspace(70, 150, int(h * 0.32), dtype=np.uint8)[:, None] + mid = y[int(h * 0.32):int(h * 0.52)] + mid[:] = np.clip(110 + rng.randint(-25, 26, mid.shape), 0, 255) + near = y[int(h * 0.52):] + # Calm near-glass. ±6 residual looked like frost (blob~3). + near[:] = np.clip(120 + rng.randint(-2, 3, near.shape), 0, 255) + return y + + +def _wet_windshield(h=240, w=320, n=25, seed=1) -> np.ndarray: + """Same dry scene with soft near-field blobs (drops on the glass).""" + y = _dry_windshield(h, w, seed=0) + rng = np.random.RandomState(seed) + r0, r1 = int(h * 0.50), int(h * 0.88) + c0, c1 = int(w * 0.08), int(w * 0.48) + for _ in range(n): + rad = rng.randint(2, 8) + cy = rng.randint(r0 + rad, r1 - rad) + cx = rng.randint(c0 + rad, c1 - rad) + yy, xx = np.ogrid[-rad:rad + 1, -rad:rad + 1] + mask = yy * yy + xx * xx <= rad * rad + dist = np.sqrt(yy * yy + xx * xx) + bump = (1.0 - dist / max(rad, 1)) * rng.randint(50, 120) + patch = y[cy - rad:cy + rad + 1, cx - rad:cx + rad + 1].astype(np.float32) + patch[mask] += bump[mask] + y[cy - rad:cy + rad + 1, cx - rad:cx + rad + 1] = np.clip(patch, 0, 255).astype(np.uint8) + return y + + +def _dense_bead_windshield(h=240, w=320, n=1200, seed=12) -> np.ndarray: + """Human-obvious: beads covering the whole pane (Justin's rest-in-rain photo). + + Packed droplets raise sharp-residual structure and can sat-highlight. + That used to score 0 as foliage/lamps. Must HOLD at least as strongly + as light soft-bokeh. + """ + y = _dry_windshield(h, w, seed=0) + rng = np.random.RandomState(seed) + r0, r1 = int(h * 0.05), int(h * 0.90) + c0, c1 = int(w * 0.05), int(w * 0.95) + for _ in range(n): + rad = rng.randint(2, 7) + cy = rng.randint(r0 + rad, r1 - rad) + cx = rng.randint(c0 + rad, c1 - rad) + yy, xx = np.ogrid[-rad:rad + 1, -rad:rad + 1] + mask = yy * yy + xx * xx <= rad * rad + dist = np.sqrt(yy * yy + xx * xx) + bump = (1.0 - dist / max(rad, 1)) * rng.randint(60, 160) + patch = y[cy - rad:cy + rad + 1, cx - rad:cx + rad + 1].astype(np.float32) + patch[mask] += bump[mask] + y[cy - rad:cy + rad + 1, cx - rad:cx + rad + 1] = np.clip(patch, 0, 255).astype(np.uint8) + return y + + +def _frost_windshield(h=240, w=320, seed=3) -> np.ndarray: + """Dry scene with near-field crystal mottle on the glass.""" + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + noise = rng.randn(h, w) + k = 3 + p = np.pad(noise, k, mode="edge") + acc = np.zeros_like(noise) + for i in range(2 * k + 1): + for j in range(2 * k + 1): + acc += p[i:i + h, j:j + w] + acc /= float((2 * k + 1) ** 2) + return np.clip(y * 0.85 + 20.0 + acc * 18.0, 0, 255).astype(np.uint8) + + +def _ice_sheet(h=240, w=320, seed=4) -> np.ndarray: + """Milky ice sheet: contrast of the view through the glass is collapsed.""" + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + y = (y - y.mean()) * 0.35 + 140.0 + noise = rng.randn(h, w) + k = 5 + p = np.pad(noise, k, mode="edge") + acc = np.zeros_like(noise) + for i in range(2 * k + 1): + acc += p[i:i + h, k:k + w] + acc /= float(2 * k + 1) + return np.clip(y + acc * 8.0, 0, 255).astype(np.uint8) + + +def _bokeh_windshield(h=240, w=320, n=10, seed=5) -> np.ndarray: + """Far-focus 3X ROAD: large soft circles of confusion on the glass. + + Matches Justin's live ROAD UI in rain — not sharp phone-bead close-ups. + """ + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + yy, xx = np.mgrid[0:h, 0:w] + for _ in range(n): + cy = rng.uniform(h * 0.50, h * 0.86) + cx = rng.uniform(w * 0.08, w * 0.48) + sig = rng.uniform(min(h, w) * 0.055, min(h, w) * 0.14) + amp = rng.uniform(35.0, 80.0) * rng.choice([1.0, 1.0, 0.85, -0.4]) + y += amp * np.exp(-((yy - cy) ** 2 + (xx - cx) ** 2) / (2.0 * sig * sig)) + return np.clip(y, 0, 255).astype(np.uint8) + + +def _overcast_windshield(h=240, w=320, seed=21) -> np.ndarray: + """Dry overcast: sky wash + huge soft clouds. Low bokeh, not rain blobs.""" + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + yy, xx = np.mgrid[0:h, 0:w] + for _ in range(3): + cy = rng.uniform(h * 0.05, h * 0.35) + cx = rng.uniform(w * 0.2, w * 0.8) + sig = rng.uniform(70.0, 120.0) + amp = rng.uniform(8.0, 16.0) + y += amp * np.exp(-((yy - cy) ** 2 + (xx - cx) ** 2) / (2.0 * sig * sig)) + return np.clip(y, 0, 255).astype(np.uint8) + + +def _low_bokeh_overcast(h=240, w=320, seed=13) -> np.ndarray: + """Weak false bokeh under BOKEH_ON — dry/overcast texture, not rain.""" + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + yy, xx = np.mgrid[0:h, 0:w] + for _ in range(8): + cy = rng.uniform(h * 0.18, h * 0.56) + cx = rng.uniform(w * 0.15, w * 0.85) + sig = rng.uniform(min(h, w) * 0.04, min(h, w) * 0.10) + amp = rng.uniform(10.0, 22.0) + y += amp * np.exp(-((yy - cy) ** 2 + (xx - cx) ** 2) / (2.0 * sig * sig)) + return np.clip(y, 0, 255).astype(np.uint8) + + +def _false_bokeh_overcast(h=240, w=320, seed=40) -> np.ndarray: + """Old 1.5–2.1 bokeh band: dry/overcast scene texture, not real rain (~3+).""" + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + yy, xx = np.mgrid[0:h, 0:w] + for _ in range(8): + cy = rng.uniform(h * 0.18, h * 0.56) + cx = rng.uniform(w * 0.15, w * 0.85) + sig = rng.uniform(min(h, w) * 0.05, min(h, w) * 0.12) + amp = rng.uniform(20.0, 38.0) * rng.choice([1.0, 1.0, 0.85, -0.3]) + y += amp * np.exp(-((yy - cy) ** 2 + (xx - cx) ** 2) / (2.0 * sig * sig)) + return np.clip(y, 0, 255).astype(np.uint8) + + +def _heavy_bokeh_windshield(h=240, w=320, seed=6) -> np.ndarray: + """Meaningful wet: overlapping milky drops on the driver-side near glass. + + Must not rely on distant driveway grain (that is what dry garage scored). + """ + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + r0, r1 = int(h * 0.48), int(h * 0.90) + c0, c1 = int(w * 0.04), int(w * 0.52) + for _ in range(90): + rad = rng.randint(5, 16) + cy = rng.randint(r0 + rad, r1 - rad) + cx = rng.randint(c0 + rad, c1 - rad) + yy, xx = np.ogrid[-rad:rad + 1, -rad:rad + 1] + mask = yy * yy + xx * xx <= rad * rad + dist = np.sqrt(yy * yy + xx * xx) + bump = (1.0 - dist / max(rad, 1)) * rng.randint(70, 150) + patch = y[cy - rad:cy + rad + 1, cx - rad:cx + rad + 1] + patch[mask] += bump[mask] + y[cy - rad:cy + rad + 1, cx - rad:cx + rad + 1] = patch + return np.clip(y, 0, 255).astype(np.uint8) + + +def _mist_windshield(h=240, w=320, seed=17) -> np.ndarray: + """Highway light mist: veil + small streaks on near-glass; far road stays sharp.""" + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + r0, r1 = int(h * 0.56), int(h * 0.90) + c0, c1 = int(w * 0.06), int(w * 0.50) + patch = y[r0:r1, c0:c1] + m = float(patch.mean()) + y[r0:r1, c0:c1] = (patch - m) * 0.32 + m + 10.0 + yy, xx = np.mgrid[0:h, 0:w] + for _ in range(14): + cy = rng.uniform(h * 0.58, h * 0.88) + cx = rng.uniform(w * 0.08, w * 0.46) + sigy = rng.uniform(h * 0.012, h * 0.04) + sigx = rng.uniform(w * 0.006, w * 0.016) + amp = rng.uniform(18.0, 36.0) + y += amp * np.exp(-((yy - cy) ** 2) / (2.0 * sigy * sigy) - ((xx - cx) ** 2) / (2.0 * sigx * sigx)) + return np.clip(y, 0, 255).astype(np.uint8) + + +def _fine_mist_windshield(h=240, w=320, seed=19) -> np.ndarray: + """Dense fine drizzle film on near-glass (Justin 13 mph photo). Far road stays.""" + y = _dry_windshield(h, w, seed=0).astype(np.float32) + rng = np.random.RandomState(seed) + r0, r1 = int(h * 0.48), int(h * 0.90) + c0, c1 = int(w * 0.06), int(w * 0.50) + patch = y[r0:r1, c0:c1] + m = float(patch.mean()) + y[r0:r1, c0:c1] = (patch - m) * 0.40 + m + 6.0 + for _ in range(280): + rad = rng.randint(1, 3) + cy = rng.randint(r0 + rad, r1 - rad) + cx = rng.randint(c0 + rad, c1 - rad) + yy, xx = np.ogrid[-rad:rad + 1, -rad:rad + 1] + mask = yy * yy + xx * xx <= rad * rad + bump = rng.uniform(16.0, 40.0) + sl = y[cy - rad:cy + rad + 1, cx - rad:cx + rad + 1] + sl[mask] += bump + y[cy - rad:cy + rad + 1, cx - rad:cx + rad + 1] = sl + return np.clip(y, 0, 255).astype(np.uint8) + + +def _atmos_fog_windshield(h=240, w=320, seed=18) -> np.ndarray: + """Distant atmospheric fog: whole-frame wash, no near-glass streaks.""" + y = _dry_windshield(h, w, seed=0).astype(np.float32) + y = (y - y.mean()) * 0.22 + 145.0 + return np.clip(y, 0, 255).astype(np.uint8) + + +def test_windshield_camera_wet_holds_and_dry_releases(): + dry = _dry_windshield() + wet = _heavy_bokeh_windshield() + assert windshield_rain_score(dry) < SCORE_OFF + assert windshield_rain_score(wet) >= SCORE_ON + assert not windshield_looks_rainy(dry) + assert windshield_looks_rainy(wet) + assert not wiper_test_requested(WIPER_SETTING_AUTO, windshield_looks_rainy(dry)) + assert wiper_test_requested(WIPER_SETTING_AUTO, windshield_looks_rainy(wet)) + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, windshield_looks_rainy(wet), False) + assert _byte(held) == STW_WIPER_ON + assert _byte(held) != STW_WASHER_SPRAY + released = apply_stw_wiper_beam_nibbles(rest, windshield_looks_rainy(dry), False) + assert released == rest + + +def test_windshield_soft_bokeh_holds_and_dry_releases(): + """3X ROAD is far-focused: rain is large soft bokeh, not sharp beads.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import ( + _BOKEH_ROWS, _COLS, _band, _near_features, + ) + + dry = _dry_windshield() + bokeh = _bokeh_windshield() + _blob, speckle, _sparse, _sat, _structure, bokeh_e = _near_features(_band(bokeh, _BOKEH_ROWS, _COLS)) + # Soft circles of confusion: not the old sparse-speckle drop gate. + assert speckle < 0.012 + assert bokeh_e >= BOKEH_ON + assert windshield_rain_score(dry) < SCORE_OFF + assert windshield_rain_score(bokeh) >= SCORE_ON + assert not windshield_looks_rainy(dry) + assert windshield_looks_rainy(bokeh) + assert not wiper_test_requested(WIPER_SETTING_AUTO, windshield_looks_rainy(dry)) + assert wiper_test_requested(WIPER_SETTING_AUTO, windshield_looks_rainy(bokeh)) + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, windshield_looks_rainy(bokeh), False) + assert _byte(held) == STW_WIPER_ON + assert _byte(held) != STW_WASHER_SPRAY + assert apply_stw_wiper_beam_nibbles(rest, windshield_looks_rainy(dry), False) == rest + + # Light sprinkle-level bokeh looks rainy but must not acquire. + det = WindshieldRain() + _skip_warmup(det) + for _ in range(MIN_HOLD_N + 8): + assert not det.update_from_y(bokeh) + assert not det.hold + + +def test_heavy_soft_bokeh_over_driveway_holds(): + """Later live 3X ROAD UI: more rain, large overlapping milky blobs over cars.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import ( + _BOKEH_ROWS, _COLS, _band, _near_features, + ) + + dry = _dry_windshield() + heavy = _heavy_bokeh_windshield() + blob, speckle, _sparse, _sat, _structure, bokeh_e = _near_features(_band(heavy, _BOKEH_ROWS, _COLS)) + assert speckle < 0.35 + # Soft defocus is present; rain score may also come from the speckle path. + assert bokeh_e >= 1.5 + assert blob >= BLOB_WET + assert windshield_rain_score(dry) < SCORE_OFF + assert windshield_rain_score(heavy) >= SCORE_ON + assert windshield_looks_rainy(heavy) + assert not windshield_looks_rainy(dry) + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, windshield_looks_rainy(heavy), False) + assert _byte(held) == STW_WIPER_ON + assert _byte(held) != STW_WASHER_SPRAY + det = WindshieldRain() + saw = False + for _ in range(16): + if det.update_from_y(heavy): + saw = True + break + assert saw + _expire_wipe(det) + assert not det.hold + + +def test_rain_score_is_monotonic_at_or_above_wetness(): + """Anything at or above the wetness floor wipes. More water must not score drier. + + Live miss: light soft-bokeh fired; heavy overlapping milky (high blob, bokeh + under BOKEH_ON, ratio under the old 0.22 veto) scored 0 on the mid band. + """ + from openpilot.selfdrive.car.tesla.preap_windshield_rain import ( + _BOKEH_RATIO, _BOKEH_ROWS, _COLS, _STRUCTURE_RAIN, + _band, _near_features, _rain_from_band, + ) + + dry = _dry_windshield() + light = _bokeh_windshield() + heavy = _heavy_bokeh_windshield() + light_s = windshield_rain_score(light) + heavy_s = windshield_rain_score(heavy) + assert light_s >= SCORE_ON + assert heavy_s >= SCORE_ON + assert heavy_s >= light_s + assert windshield_obstruction_score(heavy) >= windshield_obstruction_score(light) + assert windshield_looks_rainy(light) + assert windshield_looks_rainy(heavy) + assert not windshield_looks_rainy(dry) + + blob, speckle, _sparse, _sat, structure, bokeh_e = _near_features(_band(heavy, _BOKEH_ROWS, _COLS)) + assert blob >= BLOB_WET + assert structure < _STRUCTURE_RAIN + # Meaningful wet must still score if the old ratio gate would have vetoed it. + if bokeh_e < BOKEH_ON or bokeh_e / (blob + 0.2) < _BOKEH_RATIO: + assert _rain_from_band(_band(heavy, _BOKEH_ROWS, _COLS)) >= SCORE_ON + mid = _rain_from_band(_band(heavy, _BOKEH_ROWS, _COLS)) + assert mid >= SCORE_ON + assert mid >= light_s + # Dense wet blob must not be classified as foliage (structure stays low). + assert blob > 8.0 + + det = WindshieldRain() + saw = False + for _ in range(MIN_HOLD_N + 4): + if det.update_from_y(heavy): + saw = True + break + assert saw + assert det.hold + + rest = _rest() + assert _byte(apply_stw_wiper_beam_nibbles(rest, True, False)) == STW_WIPER_ON + _expire_wipe(det) + assert not det.hold + assert apply_stw_wiper_beam_nibbles(rest, False, False) == rest + + +def test_valid_heavy_obstruction_is_not_forced_dry(): + """Old SCORE_ABSURD=12 zeroed real heavy scores. 15 is wet, 49165 is garbage.""" + assert SCORE_ABSURD < SCORE_INVALID + latch = WindshieldRain() + _skip_warmup(latch) + for _ in range(MIN_HOLD_N - 1): + assert not latch._update_score(15.0) + assert not latch.hold + assert latch._update_score(15.0) + assert latch.hold + assert latch.last_score == 15.0 + + garbage = WindshieldRain() + for _ in range(MIN_HOLD_N + 8): + assert not garbage._update_score(49165.0) + assert not garbage.hold + assert garbage.last_score == 0.0 + + +def test_dense_beads_covering_glass_hold_at_least_as_light_bokeh(): + """Packed full-pane beads must wipe. Structure/sat must not fail closed as foliage.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import ( + _BOKEH_ROWS, _NEAR_ROWS, _COLS, _STRUCTURE_RAIN, _SAT_MAX, _band, _near_features, _rain_from_band, + ) + + dry = _dry_windshield() + light = _bokeh_windshield() + dense = _dense_bead_windshield() + light_s = windshield_rain_score(light) + dense_s = windshield_rain_score(dense) + assert light_s >= SCORE_ON + assert dense_s >= SCORE_ON + assert dense_s >= light_s + assert windshield_looks_rainy(dense) + assert not windshield_looks_rainy(dry) + + # This scene is why wipe sat at rest: both bands can exceed the old + # structure/sat vetoes while bokeh is still rain-like. + struct_hi = False + for rows in (_NEAR_ROWS, _BOKEH_ROWS): + blob, speckle, sparse, sat, structure, bokeh_e = _near_features(_band(dense, rows, _COLS)) + band = _rain_from_band(_band(dense, rows, _COLS)) + if structure > _STRUCTURE_RAIN or sat > _SAT_MAX: + struct_hi = True + assert bokeh_e >= BOKEH_ON or blob >= BLOB_WET or speckle >= 0.012 + assert band >= SCORE_ON + assert struct_hi or dense_s >= light_s + + det = WindshieldRain() + saw = False + for _ in range(MIN_HOLD_N + 4): + if det.update_from_y(dense): + saw = True + break + assert saw + assert det.hold + rest = _rest() + assert _byte(apply_stw_wiper_beam_nibbles(rest, True, False)) == STW_WIPER_ON + _expire_wipe(det) + assert not det.hold + + +def test_one_below_wet_idle_look_resets_consecutive_acquire(): + """Two consecutive clearly-wet idle looks acquire. One dry in between resets.""" + wet = HEAVY_ON + 0.8 + det = WindshieldRain() + _skip_warmup(det) + for _ in range(MIN_HOLD_N - 1): + assert not det._update_score(wet) + assert not det.hold + assert det._hold_n == MIN_HOLD_N - 1 + assert not det._update_score(0.0) + assert not det.hold + assert det._hold_n == 0 + assert not det._update_score(wet) + assert not det.hold + assert det._update_score(wet) + assert det.hold + + +def test_windshield_ice_and_frost_hold_like_rain(): + dry = _dry_windshield() + frost = _frost_windshield() + ice = _ice_sheet() + assert windshield_obstruction_score(dry) < HOLD_ON + assert windshield_frost_score(frost) >= FROST_ON + assert windshield_ice_score(ice) >= ICE_ON + assert windshield_looks_rainy(frost) + assert windshield_looks_rainy(ice) + assert not windshield_looks_rainy(dry) + rest = _rest() + assert _byte(apply_stw_wiper_beam_nibbles(rest, True, False)) == STW_WIPER_ON + assert apply_stw_wiper_beam_nibbles(rest, False, False) == rest + + +def test_windshield_rejects_foliage_and_headlamps(): + h, w = 240, 320 + rng = np.random.RandomState(0) + foliage = np.full((h, w), 80, np.uint8) + foliage[int(h * 0.48):int(h * 0.90), :int(w * 0.50)] = rng.randint( + 40, 160, (int(h * 0.90) - int(h * 0.48), int(w * 0.50))).astype(np.uint8) + lamps = np.full((h, w), 30, np.uint8) + lamps[int(h * 0.55):int(h * 0.70), int(w * 0.10):int(w * 0.22)] = 250 + lamps[int(h * 0.55):int(h * 0.70), int(w * 0.70):int(w * 0.82)] = 250 + assert windshield_rain_score(foliage) < SCORE_ON + assert windshield_rain_score(lamps) < SCORE_ON + assert windshield_frost_score(foliage) < FROST_ON + assert windshield_ice_score(foliage) < ICE_ON + assert windshield_frost_score(lamps) < FROST_ON + assert windshield_ice_score(lamps) < ICE_ON + assert not windshield_looks_rainy(foliage) + assert not windshield_looks_rainy(lamps) + + +def test_visionipc_retries_after_failure(monkeypatch): + """One VisionIpc exception must not permanently dry Auto.""" + import time as time_mod + + now = {"t": 1000.0} + monkeypatch.setattr(time_mod, "monotonic", lambda: now["t"]) + + class _Boom: + def is_connected(self): + return True + + def recv(self, timeout_ms=0): + raise RuntimeError("vipc down") + + class _Quiet: + def is_connected(self): + return True + + def recv(self, timeout_ms=0): + return None + + det = WindshieldRain() + det._client = _Boom() + assert det._recv_y() is None + assert det._failed + assert det._client is None + assert det.last_err == "RuntimeError" + assert det._recv_y() is None + assert det._failed + + now["t"] += CONNECT_RETRY_S + 0.05 + det._client = _Quiet() + assert det._recv_y() is None + assert not det._failed + assert det.poll() is False + + +def test_visionipc_falls_back_to_wide_without_frames(): + det = WindshieldRain() + det._stream_t0 = 5000.0 + assert det.stream == "ROAD" + det._maybe_fallback_stream(5000.0 + STREAM_FALLBACK_S + 0.05) + assert det.stream == "WIDE" + assert det._client is None + + +def _nv12_buf(y): + h, w = y.shape + class _Buf: + width = int(w) + height = int(h) + stride = int(w) + uv_offset = int(w * h) + data = np.concatenate([y.reshape(-1), np.full((w * h) // 2, 128, np.uint8)]) + return _Buf() + + +class _CountingVisionClient: + def __init__(self, buf): + self.buf = buf + self.n_recv = 0 + + def is_connected(self): + return True + + def recv(self, timeout_ms=0): + self.n_recv += 1 + wait = (timeout_ms or 0) / 1000.0 + time.sleep(0.02 if wait <= 0 else min(0.03, wait)) + return self.buf + + +def _skip_warmup(det) -> None: + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + det._warm_n = int(rain.WARMUP_N) + + +def _acquire_score(det, score: float) -> None: + """Stop on first HOLD. Skip helper warmup; one-sweep pulse is wall-clock.""" + _skip_warmup(det) + for _ in range(MIN_HOLD_N + 4): + det._update_score(score) + if det.hold: + break + assert det.hold + assert det._wipe_t0 > 0.0 + + +def _acquire_y(det, y) -> None: + _skip_warmup(det) + for _ in range(MIN_HOLD_N + 4): + det.update_from_y(y) + if det.hold: + break + assert det.hold + assert det._wipe_t0 > 0.0 + + +def _expire_wipe(det) -> None: + """End the one-sweep nibble-1 pulse the way poll() does on wall-clock.""" + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + assert det.hold + det._wipe_t0 = time.monotonic() - float(rain.WIPE_PULSE_S) - 0.05 + det._apply_wipe_pulse() + assert not det.hold + assert det._wait_t0 > 0.0 + + +def _expire_wait(det) -> None: + """Skip CLEAR_WAIT_S so the next score is an assess, not blade-FOV.""" + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + assert det._wait_t0 > 0.0 + det._wait_t0 = time.monotonic() - float(rain.CLEAR_WAIT_S) - 0.05 + + +def _expire_min_gap(det) -> None: + """Skip the light-mist min rewipe gap so the next wet look may acquire.""" + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + gap = float(rain.min_rewipe_gap_light_s()) + if det._last_wipe_t0 > 0.0: + det._last_wipe_t0 = time.monotonic() - gap - 0.05 + + +def _expire_thin_gap(det) -> None: + """Skip the below-acquire thin maintenance gap so the next thin look may wipe.""" + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + gap = float(rain.thin_gap_s()) + now = time.monotonic() + if det._last_wipe_t0 > 0.0: + det._last_wipe_t0 = now - gap - 0.05 + if det._thin_t0 > 0.0: + det._thin_t0 = now - gap - 0.05 + elif det._last_wipe_t0 <= 0.0: + det._thin_t0 = now - gap - 0.05 + + +def test_helper_holds_soft_bokeh_and_poll_does_not_recv(monkeypatch): + """stock_cc / card is CTRL_HIGH: poll must not drain VisionIpc. Heavy bokeh HOLD.""" + import time as time_mod + + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + monkeypatch.setattr(rain, "SCORE_PERIOD_S", 0.05) + monkeypatch.setattr(rain, "WIPE_PULSE_S", 60.0) + bokeh = _heavy_bokeh_windshield() + client = _CountingVisionClient(_nv12_buf(bokeh)) + det = WindshieldRain() + det._client = client + det.start_helper() + try: + deadline = time_mod.monotonic() + 2.0 + while time_mod.monotonic() < deadline and not det.hold: + time_mod.sleep(0.02) + assert det.helper_alive + assert det.hold + assert det.n_frames >= 1 + n_poll = det._poll_recv + for _ in range(25): + assert det.poll() is True + assert det._poll_recv == n_poll + assert det.hold + finally: + det.stop_helper() + + +def test_helper_dry_road_does_not_hold(): + import time as time_mod + + dry = _dry_windshield() + client = _CountingVisionClient(_nv12_buf(dry)) + det = WindshieldRain() + det._client = client + det.start_helper() + try: + deadline = time_mod.monotonic() + 1.0 + while time_mod.monotonic() < deadline and det.n_frames < 4: + time_mod.sleep(0.02) + assert det.n_frames >= 1 + assert not det.hold + assert det.poll() is False + assert det._poll_recv == 0 + finally: + det.stop_helper() + + +def test_stock_cc_update_primes_visionipc_helper(monkeypatch): + """Auto stock_cc.update starts ROAD drain; poll does not recv on that thread.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + reset_windshield_rain() + monkeypatch.setattr(body, "RAIN_HELPER_START_DELAY_S", 0.0) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "requested_wiper_test", lambda: False) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + class _Fake: + def _send(self, CS, tesla_can, bus, button): + return (STW_ACTN_RQ_ADDR, b"\x00", bus) + + fake = _Fake() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + reset_auto_gates() + try: + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + # Auto dry still extra-forwards rest (cancel latched Int). Helper must start. + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + assert rain._detector is not None + assert rain._detector._helper_started + assert rain._detector.poll() is False + assert rain._detector._poll_recv == 0 + finally: + reset_windshield_rain() + reset_auto_gates() + + +def test_auto_helper_does_not_start_during_engage_delay(monkeypatch): + """Do not subscribe ROAD in the first RAIN_HELPER_START_DELAY_S of Auto.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + reset_windshield_rain() + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + + class _Fake: + def _send(self, CS, tesla_can, bus, button): + return (STW_ACTN_RQ_ADDR, b"\x00", bus) + + reset_auto_gates() + try: + assert body.RAIN_HELPER_START_DELAY_S >= 2.0 + body.stock_cc_update_with_overlay(_Fake(), SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}), 10, None, 0) + assert rain._detector is None or not rain._detector._helper_started + finally: + reset_windshield_rain() + reset_auto_gates() + + +def test_poll_never_recvs_on_card_thread(): + """Helper down used to recv+numpy on poll() — that lagged selfdrive on engage.""" + import inspect + + class _Boom: + def is_connected(self): + return True + + def recv(self, timeout_ms=0): + raise RuntimeError("poll must not recv") + + det = WindshieldRain() + det._client = _Boom() + det.hold = True + assert det.poll() is False + assert det._poll_recv == 0 + src = inspect.getsource(WindshieldRain.poll) + assert "_recv_y" not in src + assert "update_from_y" not in src + + +def test_stock_cc_int_stops_rain_helper_and_drops_hold(monkeypatch): + """Int/On/Off keep nibble 1 / stalk without ROAD. Switching off Auto must drop HOLD.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + reset_windshield_rain() + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + + class _Fake: + def _send(self, CS, tesla_can, bus, button): + return (STW_ACTN_RQ_ADDR, b"\x00", bus) + + fake = _Fake() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + reset_auto_gates() + try: + det = rain.ensure_windshield_rain_helper() + det.hold = True + assert det._helper_started + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_INTERMITTENT if key == NAP_WIPER_SPEED else default + )) + body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert not det._helper_started + assert not det.hold + assert det.poll() is False + assert det._poll_recv == 0 + # Legacy Int/On coerce to Off — no TIPWIPE extra-forward. + finally: + reset_windshield_rain() + reset_auto_gates() + + +def test_install_does_not_start_rain_helper(): + """card.__init__ must not subscribe ROAD — that hit camerad at engage.""" + import inspect + from openpilot.selfdrive.car.tesla.preap_body_controls import install_body_controls_test + src = inspect.getsource(install_body_controls_test) + assert "ensure_windshield_rain_helper" not in src + assert "start_helper" not in src + + +def test_dense_bead_sparse_below_8_is_rain(): + """Sparse≈6.85 mid-blob used to be a reject. Meaningful wet still rains.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import _SPARSE_MIN, _SPARSE_RAIN_MIN + assert _SPARSE_RAIN_MIN <= 6.85 < _SPARSE_MIN + heavy = _heavy_bokeh_windshield() + assert windshield_rain_score(heavy) >= SCORE_ON + assert windshield_looks_rainy(heavy) + dense = _dense_bead_windshield() + assert windshield_rain_score(dense) >= SCORE_ON + assert windshield_looks_rainy(dense) + + +def test_windshield_latch_holds_then_releases(): + det = WindshieldRain() + wet = _heavy_bokeh_windshield() + dry = _dry_windshield() + saw_wet = False + for _ in range(16): + if det.update_from_y(wet): + saw_wet = True + break + assert saw_wet + assert det.update_from_y(dry) + assert det.hold + _expire_wipe(det) + assert not det.hold + frost = _frost_windshield() + assert windshield_looks_rainy(frost) + assert windshield_obstruction_score(frost) < ACQUIRE_ON + frost_det = WindshieldRain() + for _ in range(MIN_HOLD_N + 8): + assert not frost_det.update_from_y(frost) + ice = _ice_sheet() + assert windshield_looks_rainy(ice) + assert windshield_obstruction_score(ice) < ACQUIRE_ON + ice_det = WindshieldRain() + for _ in range(MIN_HOLD_N + 8): + assert not ice_det.update_from_y(ice) + + +def test_hold_rides_brief_wipe_clear_then_releases_on_sustained_dry(): + """One-sweep pulse: dry ROAD during WIPE_PULSE_S does not abort the wipe.""" + det = WindshieldRain() + wet = _heavy_bokeh_windshield() + dry = _dry_windshield() + _acquire_y(det, wet) + assert det.hold + assert det._wipe_t0 > 0.0 + assert det.update_from_y(dry) + assert det.hold + _expire_wipe(det) + assert not det.hold + assert apply_stw_wiper_beam_nibbles(_rest(), False, False) == _rest() + + +def test_sustained_dry_releases_when_wipe_pulse_ends(): + """HOLD is the one-sweep pulse. poll() / pulse elapsed drops it; dry then stays off.""" + assert MIN_HOLD_N <= CLEAR_RELEASE_N + det = WindshieldRain() + wet = _heavy_bokeh_windshield() + dry = _dry_windshield() + _acquire_y(det, wet) + assert det._hold_n >= MIN_HOLD_N + _expire_wipe(det) + assert not det.hold + _expire_wait(det) + assert not det.update_from_y(dry) + assert not det.hold + assert windshield_obstruction_score(dry) < HOLD_OFF + rest = _rest() + assert apply_stw_wiper_beam_nibbles(rest, False, False) == rest + + +def test_dry_overcast_low_bokeh_does_not_stay_held(): + """Dry overcast / weak false bokeh must not acquire, and must stay off after a wipe.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import ( + _BOKEH_ROWS, _COLS, _band, _near_features, + ) + + overcast = _overcast_windshield() + low = _low_bokeh_overcast() + false_bokeh = _false_bokeh_overcast() + dry = _dry_windshield() + wet = _heavy_bokeh_windshield() + for y in (overcast, low, false_bokeh, dry): + obs = windshield_obstruction_score(y) + _blob, _speckle, _sparse, _sat, _structure, bokeh_e = _near_features(_band(y, _BOKEH_ROWS, _COLS)) + assert obs < HOLD_ON + assert bokeh_e < BOKEH_ON or obs < HOLD_ON + assert not windshield_looks_rainy(y) + det_dry = WindshieldRain() + for _ in range(CLEAR_RELEASE_N + MIN_HOLD_N + 8): + assert not det_dry.update_from_y(y) + + # After one wipe + 2 s wait, overcast residual must not re-wipe. + for residual_y in (overcast, low, false_bokeh, dry): + det = WindshieldRain() + _acquire_y(det, wet) + _expire_wipe(det) + _expire_wait(det) + assert not det.update_from_y(residual_y) + assert not det.hold + + +def test_false_bokeh_below_bar_is_not_rain(): + """Clear/overcast texture in the old 1.5 bokeh band must not look rainy.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import ( + _BOKEH_ROWS, _COLS, _band, _near_features, + ) + + y = _false_bokeh_overcast() + _blob, speckle, _sparse, _sat, _structure, bokeh_e = _near_features(_band(y, _BOKEH_ROWS, _COLS)) + assert speckle < 0.012 + # In the old false-positive band, but under the raised rain bar. + assert bokeh_e < BOKEH_ON + assert windshield_rain_score(y) < SCORE_ON + assert windshield_obstruction_score(y) < HOLD_ON + assert not windshield_looks_rainy(y) + rest = _rest() + assert apply_stw_wiper_beam_nibbles(rest, False, False) == rest + + +def test_absurd_bokeh_scale_is_invalid_dry_and_releases(): + """Live clear glass logged bokeh=49165. Garbage scale must not HOLD.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import _near_features, _band, _BOKEH_ROWS, _COLS + + dry = _dry_windshield() + wet = _heavy_bokeh_windshield() + # 16-bit-ish / exploded float plane (Justin ~49165). + huge = dry.astype(np.float32) * 200.0 + u16 = (dry.astype(np.float32) * 256.0) + assert float(huge.max()) > 20000.0 + for y in (huge, u16): + _blob, _speckle, _sparse, _sat, _structure, bokeh_e = _near_features(_band(y, _BOKEH_ROWS, _COLS)) + assert bokeh_e <= BOKEH_ABSURD + assert windshield_rain_score(y) < SCORE_ON + assert windshield_obstruction_score(y) < HOLD_ON + assert windshield_obstruction_score(y) < SCORE_ABSURD + assert not windshield_looks_rainy(y) + det_dry = WindshieldRain() + for _ in range(CLEAR_RELEASE_N + MIN_HOLD_N + 8): + assert not det_dry.update_from_y(y) + assert det_dry.last_bokeh <= BOKEH_ABSURD + assert det_dry.last_score < HOLD_ON + + # Already held from real rain: pulse ends, then garbage is dry, not "rain returned". + det = WindshieldRain() + _acquire_y(det, wet) + _expire_wipe(det) + _expire_wait(det) + assert not det.update_from_y(huge) + assert not det.hold + assert det.last_bokeh <= BOKEH_ABSURD + + # Direct garbage obstruction must not latch or keep HOLD. + det2 = WindshieldRain() + for _ in range(CLEAR_RELEASE_N + 8): + assert not det2._update_score(49165.0) + det3 = WindshieldRain() + _acquire_score(det3, HEAVY_ON + 0.8) + assert det3._update_score(0.0) + assert det3.hold + _expire_wipe(det3) + _expire_wait(det3) + assert not det3._update_score(0.0) + assert not det3.hold + assert not det3._update_score(49165.0) + assert not det3.hold + + +def test_elevated_residual_below_rewipe_exits_loop(): + """After one wipe + settle, residual / marginal / HOLD_ON must not re-wipe.""" + assert WIPE_CLEAR_N < CLEAR_RELEASE_N + assert HOLD_OFF < HOLD_ON + assert HOLD_ON < ACQUIRE_ON < REWIPE_ON + assert REWIPE_ON == HEAVY_ON + + for residual in (0.0, 0.45, 0.70, 0.95, 1.05, HOLD_ON, 1.7, 3.16, 4.42, 6.1, 6.77, 8.27): + det = WindshieldRain() + _acquire_score(det, HEAVY_ON + 0.8) + _expire_wipe(det) + _expire_wait(det) + assert not det._update_score(residual), residual + assert not det.hold + assert not det._post_wipe + + +def test_light_sprinkle_never_enters_wipe_loop(): + """Very little sprinkles / residual beads: idle 4 s watch, no acquire wipe. + + Thin maintenance waits thin_gap_s — these immediate looks must stay quiet. + """ + for s in (HOLD_ON, 1.7, 3.16, 4.42, ACQUIRE_ON - 0.05): + assert s < ACQUIRE_ON + det = WindshieldRain() + _skip_warmup(det) + for _ in range(MIN_HOLD_N + 8): + assert not det._update_score(s), s + assert not det.hold + assert det._wipe_t0 == 0.0 + + +def test_heavy_rain_one_wipe_then_wait_then_reacquires(): + """Driveway/heavy: one sweep, cancel, settle, then still-clearly-wet wipes again.""" + heavy = HEAVY_ON + 0.8 + det = WindshieldRain() + _acquire_score(det, heavy) + assert det._wipe_t0 > 0.0 + assert det._update_score(heavy) + assert det.hold + _expire_wipe(det) + assert not det.hold + assert not det._update_score(heavy) + assert not det.hold + _expire_wait(det) + assert det._update_score(heavy) + assert det.hold + assert det._wipe_t0 > 0.0 + + +def test_heavy_wipe_end_auto_rest_cancels(monkeypatch): + """Pulse end must drop wipe so Auto extra-forwards rest (Pre-AP Int cancel).""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + reset_windshield_rain() + reset_auto_gates() + det = WindshieldRain() + _acquire_score(det, HEAVY_ON + 0.8) + det._helper_started = True + rain._detector = det + try: + set_auto_gates(True, "drive") + assert body.rain_wiper_needed() + assert not wiper_rest_tx_needed(True) + _expire_wipe(det) + assert not det.hold + assert not body.rain_wiper_needed() + assert wiper_rest_tx_needed(False) + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + reset_windshield_rain() + + +def test_wipe_pulse_wall_clock_drops_hold_between_score_ticks(monkeypatch): + """If ROAD lags, poll() must still end the one-sweep pulse at WIPE_PULSE_S.""" + import time as time_mod + + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + now = {"t": 1000.0} + monkeypatch.setattr(time_mod, "monotonic", lambda: now["t"]) + det = WindshieldRain() + _acquire_score(det, HEAVY_ON + 0.8) + det._helper_started = True + assert det.poll() is True + now["t"] += rain.WIPE_PULSE_S - 0.05 + assert det.poll() is True + now["t"] += 0.10 + assert det.poll() is False + assert not det.hold + assert det._wait_t0 > 0.0 + now["t"] += rain.CLEAR_WAIT_S - 0.05 + assert not det._update_score(HEAVY_ON + 0.8) + assert not det.hold + now["t"] += 0.10 + assert det._update_score(HEAVY_ON + 0.8) + assert det.hold + + +def test_blade_spike_during_clear_wait_does_not_acquire(): + """Blade FOV folds into the post-wipe wait. Spikes there must not nibble-1.""" + det = WindshieldRain() + _acquire_score(det, HEAVY_ON + 0.8) + assert det._update_score(0.0) + assert det.hold + _expire_wipe(det) + assert not det._update_score(HEAVY_ON + 3.0) + assert not det.hold + _expire_wait(det) + assert not det._update_score(0.0) + assert not det.hold + + +def test_mist_on_glass_acquires_and_fog_does_not(): + """Highway mist/streaks should wipe. Distant fog and dry garage must not.""" + mist = _mist_windshield() + fine = _fine_mist_windshield() + fog = _atmos_fog_windshield() + dry = _dry_windshield() + assert windshield_mist_score(mist) >= ACQUIRE_ON + assert windshield_obstruction_score(mist) >= ACQUIRE_ON + assert windshield_looks_rainy(mist) + assert windshield_mist_score(fine) >= ACQUIRE_ON + assert windshield_obstruction_score(fine) >= ACQUIRE_ON + assert windshield_looks_rainy(fine) + assert windshield_mist_score(fog) < HOLD_ON + assert windshield_obstruction_score(fog) < HOLD_ON + assert not windshield_looks_rainy(fog) + assert windshield_mist_score(dry) < HOLD_ON + assert windshield_obstruction_score(dry) < HOLD_ON + + tiny = y_plane_from_nv12(_nv12_buf(mist), max_side=Y_COPY_SIDE) + assert tiny is not None + assert windshield_obstruction_score(tiny) >= ACQUIRE_ON + tiny_fine = y_plane_from_nv12(_nv12_buf(fine), max_side=Y_COPY_SIDE) + assert tiny_fine is not None + assert windshield_obstruction_score(tiny_fine) >= ACQUIRE_ON + + det = WindshieldRain() + _skip_warmup(det) + saw = False + for _ in range(MIN_HOLD_N + 2): + if det.update_from_y(mist): + saw = True + break + assert saw + assert det.hold + _expire_wipe(det) + _expire_wait(det) + # Light mist must not easy-rewipe every ~12.5 s — min gap, then acquire. + assert not det.update_from_y(mist) + assert not det.hold + assert not det.update_from_y(mist) + assert not det.hold + _expire_min_gap(det) + if not det.hold: + assert det.update_from_y(mist) + assert det.hold + + fog_det = WindshieldRain() + _skip_warmup(fog_det) + for _ in range(MIN_HOLD_N + 8): + assert not fog_det.update_from_y(fog) + assert not fog_det.hold + + +def test_light_bokeh_and_wet_drop_fixtures_do_not_acquire(): + """Light sprinkle / residual-drop fixtures stay below acquire. Heavy still wipes.""" + light_y = _bokeh_windshield() + wet_y = _wet_windshield() + heavy_y = _heavy_bokeh_windshield() + assert windshield_obstruction_score(light_y) < ACQUIRE_ON + assert windshield_obstruction_score(wet_y) < ACQUIRE_ON + assert windshield_obstruction_score(heavy_y) >= ACQUIRE_ON + + for y in (light_y, wet_y): + det = WindshieldRain() + _skip_warmup(det) + for _ in range(MIN_HOLD_N + 8): + assert not det.update_from_y(y) + assert not det.hold + + det = WindshieldRain() + _skip_warmup(det) + saw = False + for _ in range(MIN_HOLD_N + 2): + if det.update_from_y(heavy_y): + saw = True + break + assert saw + assert det.hold + + +def test_single_frame_bokeh_score_does_not_acquire_hold(): + """Sprinkle / residual 3.16–4.42 must not HOLD. First 1–2 frames never acquire.""" + det = WindshieldRain() + for _ in range(20): + assert not det._update_score(0.0) + assert not det.hold + assert det.ema < HOLD_ON + + flicker = WindshieldRain() + assert not flicker._update_score(3.16) + assert not flicker.hold + assert not flicker._update_score(0.0) + assert not flicker.hold + assert flicker._hold_n == 0 + + sprinkle = WindshieldRain() + _skip_warmup(sprinkle) + for _ in range(MIN_HOLD_N + 8): + assert not sprinkle._update_score(4.42) + assert not sprinkle.hold + + latch = WindshieldRain() + _skip_warmup(latch) + wet = HEAVY_ON + 0.8 + for _ in range(MIN_HOLD_N - 1): + assert not latch._update_score(wet) + assert not latch.hold + assert latch._update_score(wet) + assert latch.hold + + +def test_clear_glass_after_wipe_stays_off_and_auto_cancels(monkeypatch): + """One wipe then dry assess: HOLD stays off; Auto rest-cancels the Pre-AP Int latch.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "RAIN_HELPER_START_DELAY_S", 0.0) + reset_windshield_rain() + reset_auto_gates() + det = WindshieldRain() + wet = _heavy_bokeh_windshield() + dry = _dry_windshield() + saw = False + for _ in range(16): + if det.update_from_y(wet): + saw = True + break + assert saw + assert det.hold + det._helper_started = True + rain._detector = det + try: + set_auto_gates(True, "drive") + assert body.rain_wiper_needed() + assert body.requested_wiper_test() + assert not wiper_rest_tx_needed(True) + assert det.update_from_y(dry) + assert det.hold + _expire_wipe(det) + assert not det.hold + assert not body.rain_wiper_needed() + assert not body.requested_wiper_test() + assert wiper_rest_tx_needed(False) + _expire_wait(det) + assert not det.update_from_y(dry) + assert not det.hold + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + reset_windshield_rain() + + +def test_y_plane_from_nv12_crops_stride(): + class _Buf: + width, height, stride = 16, 32, 24 + data = bytes([i % 256 for i in range(24 * 32)]) + y = y_plane_from_nv12(_Buf()) + assert y is not None + assert y.shape == (32, 16) + assert y[0, 15] == 15 + assert y[1, 0] == 24 + + +def test_helper_score_period_is_every_few_seconds(): + """Justin: idle assess ~once per 4 s; post-wipe settle then assess.""" + assert 3.5 <= SCORE_PERIOD_S <= 4.5 + assert 0.20 <= SCORE_HZ <= 0.30 + assert STALE_S > SCORE_PERIOD_S + assert abs(SCORE_HZ - 1.0 / SCORE_PERIOD_S) < 1e-6 + assert 16 <= Y_COPY_SIDE <= 64 + assert MIN_HOLD_N == 2 + assert WARMUP_N == 2 + assert CLEAR_RELEASE_N == 2 + assert WIPE_CLEAR_N == 1 + assert MIN_HOLD_N * SCORE_PERIOD_S <= 8.0 + assert HOLD_ON < ACQUIRE_ON + assert THIN_ON == HOLD_ON + assert THIN_ON < ACQUIRE_ON + assert ACQUIRE_ON < REWIPE_ON + assert REWIPE_ON == HEAVY_ON + assert 1.0 <= WIPE_PULSE_S <= 2.0 + assert 2.0 <= CLEAR_WAIT_S <= 2.55 + assert CLEAR_WAIT_S < SCORE_PERIOD_S + assert 20.0 <= MIN_REWIPE_GAP_LIGHT_S <= 30.0 + assert MIN_REWIPE_GAP_LIGHT_S > (WIPE_PULSE_S + CLEAR_WAIT_S + 2.0 * SCORE_PERIOD_S) + + +def test_idle_watch_then_wipe_loop_cadence(): + """First look is assess-now (not wipe-first). Idle is ~4 s. Post-wipe is ~2.5 s.""" + det = WindshieldRain() + t0 = time.monotonic() + assert det._next_score_at(0.0, t0) == t0 + assert abs(det._next_score_at(t0, t0) - (t0 + SCORE_PERIOD_S)) < 1e-6 + _acquire_score(det, HEAVY_ON + 0.8) + t_wipe = det._wipe_t0 + assert t_wipe > 0.0 + assert abs(det._next_score_at(t_wipe, t_wipe) - (t_wipe + WIPE_PULSE_S + CLEAR_WAIT_S)) < 1e-6 + _expire_wipe(det) + assert not det.hold + assert abs(det._next_score_at(t_wipe, det._wait_t0) - (det._wait_t0 + CLEAR_WAIT_S)) < 1e-6 + _expire_wait(det) + now = time.monotonic() + # Dry assess exits the wipe loop: next look is idle SCORE_PERIOD_S, not 2 s. + assert not det._update_score(0.0) + assert not det.hold + assert det._wait_t0 == 0.0 + assert abs(det._next_score_at(now, now) - (now + SCORE_PERIOD_S)) < 1e-6 + + +def test_dry_fixtures_never_enter_wipe_loop(): + """Bone-dry / clear overcast Auto must not nibble-1. 0987b1a7d wiped immediately.""" + dry_ys = ( + _dry_windshield(), + _overcast_windshield(), + _low_bokeh_overcast(), + _false_bokeh_overcast(), + ) + for y in dry_ys: + assert windshield_obstruction_score(y) < ACQUIRE_ON + det = WindshieldRain() + for _ in range(MIN_HOLD_N + 12): + assert not det.update_from_y(y) + assert not det.hold + assert det._wipe_t0 == 0.0 + assert not det._post_wipe + + +def test_live_dry_blob_bokeh_status_is_not_rain(): + """Justin 5f32c450b: dry and light-sprinkle look the same. Must not wipe.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import ( + _mist_film_from_feats, _rain_from_feats, + ) + + # Same session: sprinkle / wiping, then confirmed bone-dry last line. + lives = ( + (7.40, 0.046, 4.7, 0.0, 0.013, 3.01), # score=4.42 wiping + (8.83, 0.081, 9.7, 0.0, 0.045, 4.22), # score=5.44 + (7.00, 0.068, 9.6, 0.0, 0.015, 3.14), # score=3.19 + (7.55, 0.069, 6.7, 0.0, 0.022, 3.85), # score=6.29 BONE DRY + ) + det = WindshieldRain() + _skip_warmup(det) + for feats in lives: + rain = _rain_from_feats(*feats) + mist = _mist_film_from_feats(*feats) + obs = max((rain / SCORE_ON) if rain else 0.0, mist) + assert rain < SCORE_ON, feats + assert mist < HOLD_ON, (feats, mist) + assert obs < ACQUIRE_ON, (feats, obs) + for _ in range(MIN_HOLD_N + 2): + assert not det._update_score(obs) + assert not det._update_score(6.29) + assert not det.hold + + +def test_live_highway_mist_status_acquires(): + """Justin 2db9e6c30 highway mist: score=2.15 bokeh=1.42 blob=3.93 sparse=3.2.""" + from openpilot.selfdrive.car.tesla.preap_windshield_rain import _mist_film_from_feats + + mist = _mist_film_from_feats(3.93, 0.0, 3.2, 0.0, 0.0, 1.42) + assert mist >= ACQUIRE_ON + # Uniform fine film: same blob/sparse, weaker bokeh (ROAD looks through drizzle). + fine = _mist_film_from_feats(3.93, 0.0, 3.2, 0.0, 0.0, 0.55) + assert fine >= ACQUIRE_ON + piled = _mist_film_from_feats(7.90, 0.11, 3.6, 0.0, 0.0, 0.71) + assert piled >= ACQUIRE_ON + det = WindshieldRain() + _skip_warmup(det) + assert not det._update_score(mist) + assert not det.hold + assert det._update_score(mist) + assert det.hold + + +def test_warmup_looks_do_not_acquire(): + """First WARMUP_N helper scores never wipe, even if clearly wet.""" + det = WindshieldRain() + for _ in range(WARMUP_N): + assert not det._update_score(REWIPE_ON + 1.0) + assert not det.hold + assert det._hold_n == 0 + assert det._warm_n == WARMUP_N + assert not det._update_score(REWIPE_ON + 1.0) + assert not det.hold + assert det._update_score(REWIPE_ON + 1.0) + assert det.hold + + +def test_after_wipe_dry_score_exits_loop_and_stays_idle(): + """One dry/marginal post-wipe assess ends the loop. Do not wipe forever.""" + det = WindshieldRain() + _acquire_score(det, HEAVY_ON + 0.8) + _expire_wipe(det) + _expire_wait(det) + assert not det._update_score(0.0) + assert not det.hold + for s in (0.0, 0.8, HOLD_ON, ACQUIRE_ON - 0.05): + assert not det._update_score(s), s + assert not det.hold + # Back on idle: one wet look is not a wipe (need two consecutive). + assert not det._update_score(REWIPE_ON) + assert not det.hold + + +def test_light_mist_score_after_wipe_needs_full_reacquire(): + """Justin: light misty rain acquired, then wipe→3s→rewipe over-fired. + + Post-wipe uses the repeat bar. Light mist must not clock ~12.5 s pulses. + """ + mist = 6.7 + assert ACQUIRE_ON <= mist < REWIPE_ON + det = WindshieldRain() + _skip_warmup(det) + assert not det._update_score(mist) + assert det._update_score(mist) + assert det.hold + _expire_wipe(det) + _expire_wait(det) + assert not det._update_score(mist) + assert not det.hold + assert not det._update_score(mist) + assert not det.hold + assert not det._update_score(mist) + assert not det.hold + _expire_min_gap(det) + assert det._update_score(mist) + assert det.hold + + +def test_light_mist_min_rewipe_gap_is_20_to_30s_not_12s(): + """Eager ~12.5 s light-mist pulse (1.5+2.5+4+4) must not wipe again.""" + mist = 6.7 + assert ACQUIRE_ON <= mist < REWIPE_ON + cycle_12 = WIPE_PULSE_S + CLEAR_WAIT_S + 2.0 * SCORE_PERIOD_S + assert MIN_REWIPE_GAP_LIGHT_S > cycle_12 + det = WindshieldRain() + _skip_warmup(det) + assert not det._update_score(mist) + assert det._update_score(mist) + t0 = det._last_wipe_t0 + assert t0 > 0.0 + _expire_wipe(det) + _expire_wait(det) + # Simulate the old 12.5 s cadence: several idle looks, still too soon. + for _ in range(6): + assert not det._update_score(mist) + assert not det.hold + assert (time.monotonic() - t0) < MIN_REWIPE_GAP_LIGHT_S + det._last_wipe_t0 = time.monotonic() - (cycle_12 + 0.05) + assert not det._update_score(mist) + assert not det.hold + _expire_min_gap(det) + assert det._update_score(mist) + assert det.hold + + +def test_wiper_sensitivity_scales_acquire_repeat_and_gap(): + """Lower index = wipe sooner / more often. Higher = tolerate more film.""" + assert acquire_threshold(0) < acquire_threshold(2) < acquire_threshold(4) + assert repeat_threshold(0) < repeat_threshold(2) < repeat_threshold(4) + assert min_rewipe_gap_light_s(0) < min_rewipe_gap_light_s(2) < min_rewipe_gap_light_s(4) + assert abs(acquire_threshold(2) - ACQUIRE_ON) < 1e-6 + assert abs(repeat_threshold(2) - REWIPE_ON) < 1e-6 + assert 5.0 <= min_rewipe_gap_light_s(0) <= 8.0 + assert 8.0 <= min_rewipe_gap_light_s(1) <= 12.0 + assert 20.0 <= min_rewipe_gap_light_s(2) <= 25.0 + assert abs(min_rewipe_gap_light_s(2) - MIN_REWIPE_GAP_LIGHT_S) < 1e-6 + assert 27.5 <= min_rewipe_gap_light_s(4) <= 30.0 + assert acquire_hold_n(0) == 1 + assert acquire_hold_n(1) == MIN_HOLD_N + assert acquire_hold_n(2) == MIN_HOLD_N + try: + set_wiper_sensitivity(0) + mist = 4.1 + assert acquire_threshold(0) <= mist < acquire_threshold(4) + det = WindshieldRain() + _skip_warmup(det) + assert det._update_score(mist) + assert det.hold + set_wiper_sensitivity(4) + dryish = WindshieldRain() + _skip_warmup(dryish) + for _ in range(MIN_HOLD_N + 4): + assert not dryish._update_score(mist) + assert not dryish.hold + finally: + set_wiper_sensitivity(None) + + +def test_drier_vs_mid_acquire_repeat_and_gap(): + """Sens 0 (Drier) first-wipes and rewipes light mist sooner than Mid. + + e0 000000e0--68791b5c92 on #200 (acquire~2.61, 2 looks, 10 s gap): one + sparse wipe in ~7 min. Highway mist sat ~2.15. Drier acquire/repeat + drop into that band, one look, ~6.5 s gap. Mid stays at 4.5 / 9.0 / + ~25 s so it does not thrash at the old ~12.5 s pulse. + """ + assert 5.0 <= min_rewipe_gap_light_s(0) <= 8.0 + assert 8.0 <= min_rewipe_gap_light_s(1) <= 12.0 + assert 20.0 <= min_rewipe_gap_light_s(2) <= 25.0 + assert min_rewipe_gap_light_s(2) > (WIPE_PULSE_S + CLEAR_WAIT_S + 2.0 * SCORE_PERIOD_S) + assert acquire_threshold(0) < acquire_threshold(1) < acquire_threshold(2) + assert repeat_threshold(0) < repeat_threshold(1) < repeat_threshold(2) + assert repeat_threshold(0) < HEAVY_ON + assert abs(repeat_threshold(2) - HEAVY_ON) < 1e-6 + assert acquire_hold_n(0) == 1 + assert acquire_hold_n(2) == MIN_HOLD_N + # #200 Drier acquire was 4.5*0.58≈2.61 — still above highway mist ~2.15. + assert acquire_threshold(0) <= 2.15 < acquire_threshold(2) + assert acquire_threshold(1) <= 2.15 + assert repeat_threshold(0) <= 2.15 + assert repeat_threshold(1) <= 2.15 + + weak = 2.15 + assert acquire_threshold(0) <= weak < acquire_threshold(2) + try: + set_wiper_sensitivity(0) + drier = WindshieldRain() + _skip_warmup(drier) + assert drier._update_score(weak) + assert drier.hold + + set_wiper_sensitivity(2) + mid = WindshieldRain() + _skip_warmup(mid) + for _ in range(MIN_HOLD_N + 4): + assert not mid._update_score(weak) + assert not mid.hold + + set_wiper_sensitivity(1) + dry = WindshieldRain() + _skip_warmup(dry) + assert not dry._update_score(weak) + assert dry._update_score(weak) + assert dry.hold + finally: + set_wiper_sensitivity(None) + + mist = 6.7 + assert acquire_threshold(2) <= mist < HEAVY_ON + assert mist >= repeat_threshold(0) + assert mist < repeat_threshold(2) + cycle_12 = WIPE_PULSE_S + CLEAR_WAIT_S + 2.0 * SCORE_PERIOD_S + try: + set_wiper_sensitivity(0) + det = WindshieldRain() + _skip_warmup(det) + assert det._update_score(mist) + t0 = det._last_wipe_t0 + _expire_wipe(det) + _expire_wait(det) + assert (time.monotonic() - t0) < min_rewipe_gap_light_s(0) + assert not det._update_score(mist) + assert not det.hold + assert not det._update_score(mist) + assert not det.hold + _expire_min_gap(det) + assert det._update_score(mist) + assert det.hold + + set_wiper_sensitivity(2) + mid = WindshieldRain() + _skip_warmup(mid) + assert not mid._update_score(mist) + assert mid._update_score(mist) + _expire_wipe(mid) + _expire_wait(mid) + mid._last_wipe_t0 = time.monotonic() - (cycle_12 + 0.05) + assert not mid._update_score(mist) + assert not mid.hold + assert not mid._update_score(mist) + assert not mid.hold + _expire_min_gap(mid) + assert mid._update_score(mist) + assert mid.hold + finally: + set_wiper_sensitivity(None) + + +def test_thin_mist_below_acquire_wipes_after_thin_gap(): + """e1 Drier light mist: below acquire, above THIN_ON, occasional INTERVAL1.""" + try: + set_wiper_sensitivity(0) + acq = acquire_threshold(0) + thin = (THIN_ON + acq) * 0.5 + assert THIN_ON <= thin < acq + assert 16.0 <= thin_gap_s(0) <= 20.0 + det = WindshieldRain() + _skip_warmup(det) + for _ in range(MIN_HOLD_N + 4): + assert not det._update_score(thin), thin + assert not det.hold + assert det._thin + assert det._wipe_t0 == 0.0 + _expire_thin_gap(det) + assert det._update_score(thin) + assert det.hold + assert det._thin_wipe + assert det._wipe_t0 > 0.0 + finally: + set_wiper_sensitivity(None) + + +def test_dry_below_thin_stays_quiet(): + """Bone-dry / below THIN_ON must not take the maintenance path.""" + det = WindshieldRain() + _skip_warmup(det) + dry = THIN_ON - 0.25 + assert dry < THIN_ON + for _ in range(MIN_HOLD_N + 6): + assert not det._update_score(dry) + assert not det.hold + assert not det._thin + det._thin_t0 = time.monotonic() - 120.0 + det._last_wipe_t0 = time.monotonic() - 120.0 + assert not det._update_score(dry) + assert not det.hold + assert not det._thin + assert det._wipe_t0 == 0.0 + + +def test_thin_gap_mid_longer_than_drier(): + """Mid thin maintenance is calmer than Drier. Wetter may be off.""" + assert 16.0 <= thin_gap_s(0) <= 20.0 + assert 20.0 <= thin_gap_s(1) <= 24.0 + assert 32.0 <= thin_gap_s(2) <= 40.0 + assert thin_gap_s(2) > thin_gap_s(0) + assert thin_gap_s(2) > thin_gap_s(1) + assert thin_gap_s(3) == 0.0 or thin_gap_s(3) >= thin_gap_s(2) + assert thin_gap_s(4) == 0.0 or thin_gap_s(4) >= 48.0 + + # Below Drier acquire so both sens 0 and 2 take the thin path, not acquire. + score = (THIN_ON + acquire_threshold(0)) * 0.5 + assert THIN_ON <= score < acquire_threshold(0) < acquire_threshold(2) + try: + set_wiper_sensitivity(0) + drier = WindshieldRain() + _skip_warmup(drier) + assert not drier._update_score(score) + assert drier._thin + drier._thin_t0 = time.monotonic() - thin_gap_s(0) - 0.05 + assert drier._update_score(score) + assert drier.hold + + set_wiper_sensitivity(2) + mid = WindshieldRain() + _skip_warmup(mid) + assert not mid._update_score(score) + assert mid._thin + mid._thin_t0 = time.monotonic() - thin_gap_s(0) - 0.05 + assert not mid._update_score(score) + assert not mid.hold + mid._thin_t0 = time.monotonic() - thin_gap_s(2) - 0.05 + assert mid._update_score(score) + assert mid.hold + + set_wiper_sensitivity(4) + if thin_gap_s(4) <= 0.0: + wetter = WindshieldRain() + _skip_warmup(wetter) + wetter._thin_t0 = time.monotonic() - 120.0 + for _ in range(4): + assert not wetter._update_score(score) + assert not wetter.hold + finally: + set_wiper_sensitivity(None) + + +def test_thin_hold_still_park_and_v0_suppressed(monkeypatch): + """Thin INTERVAL1 still dies at body park / v≈0. Drive+moving still wipes.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + reset_windshield_rain() + reset_auto_gates() + det = WindshieldRain() + det.hold = True + det._thin = True + det._thin_wipe = True + det._helper_started = True + rain._detector = det + try: + set_auto_gates(True, "park", v_ego=12.0) + assert not body.requested_wiper_test() + set_auto_gates(True, "neutral", v_ego=12.0) + assert not body.requested_wiper_test() + set_auto_gates(True, "drive", v_ego=0.0) + assert not body.requested_wiper_test() + set_auto_gates(True, "drive", v_ego=12.0) + assert body.rain_wiper_needed() + assert body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + reset_windshield_rain() + + +def test_clearly_wet_still_wipes_and_rewipes(): + """Real rain still acquires (two idle looks) and re-wipes if still clearly wet.""" + heavy = REWIPE_ON + 0.8 + det = WindshieldRain() + _skip_warmup(det) + assert not det._update_score(heavy) + assert not det.hold + assert det._update_score(heavy) + assert det.hold + _expire_wipe(det) + _expire_wait(det) + assert det._update_score(heavy) + assert det.hold + + +def test_helper_keeps_road_client_between_score_ticks(): + """Resubscribe-every-4s left frames=1–2 and age_ms=28s on stale first Y.""" + import inspect + src = inspect.getsource(WindshieldRain._helper_loop) + assert src.count("_release_vision") == 1 + assert "unsubscribe ROAD between ticks" not in src + + +def test_helper_numpy_scores_on_period_not_every_road_frame(monkeypatch): + """Fake ROAD can deliver ~50 Hz. Numpy HOLD ticks must follow SCORE_PERIOD_S.""" + import time as time_mod + + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + monkeypatch.setattr(rain, "SCORE_PERIOD_S", 0.30) + dry = _dry_windshield() + client = _CountingVisionClient(_nv12_buf(dry)) + det = WindshieldRain() + det._client = client + det.start_helper() + try: + time_mod.sleep(0.75) + # Scoring every 20 ms recv would be ~35 frames. Period 0.30 s → ~3. + assert 1 <= det.n_frames <= 4 + finally: + det.stop_helper() + + +def test_stale_does_not_drop_hold_between_score_periods(monkeypatch): + """poll() between idle ~4 s ticks must not fail-closed; STALE_S is longer than the period.""" + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + monkeypatch.setattr(rain, "WIPE_PULSE_S", 60.0) + det = WindshieldRain() + _skip_warmup(det) + for _ in range(MIN_HOLD_N): + det._update_score(HEAVY_ON + 0.8) + assert det.hold + det._helper_started = True + det._last_frame_t = time.monotonic() - SCORE_PERIOD_S + assert det.poll() is True + assert det.hold + det._last_frame_t = time.monotonic() - (STALE_S + 0.05) + assert det.poll() is False + assert not det.hold + + +def test_y_plane_live_copy_is_tiny_and_still_rainy(): + """Helper must not memcpy full ROAD. Tiny light sprinkle stays idle; tiny heavy wipes.""" + light = _bokeh_windshield() + light_buf = _nv12_buf(light) + full = y_plane_from_nv12(light_buf) + tiny_light = y_plane_from_nv12(light_buf, max_side=Y_COPY_SIDE) + assert full is not None and tiny_light is not None + assert full.shape == light.shape + assert min(tiny_light.shape) <= Y_COPY_SIDE + 8 + assert tiny_light.size < full.size + assert windshield_looks_rainy(full) + assert windshield_obstruction_score(tiny_light) < ACQUIRE_ON + det_light = WindshieldRain() + _skip_warmup(det_light) + for _ in range(MIN_HOLD_N + 8): + assert not det_light.update_from_y(tiny_light) + assert not det_light.hold + + heavy = _heavy_bokeh_windshield() + tiny_heavy = y_plane_from_nv12(_nv12_buf(heavy), max_side=Y_COPY_SIDE) + assert tiny_heavy is not None + assert windshield_rain_score(tiny_heavy) >= SCORE_ON + assert windshield_obstruction_score(tiny_heavy) >= ACQUIRE_ON + det = WindshieldRain() + _skip_warmup(det) + saw = False + for _ in range(MIN_HOLD_N + 4): + if det.update_from_y(tiny_heavy): + saw = True + break + assert saw + + +def test_rain_defaults_dry_without_camera(monkeypatch): + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + set_rain_wiper_needed(None) + monkeypatch.setattr(rain, "windshield_rain_needed", lambda: False) + assert not rain_wiper_needed() + monkeypatch.setattr(rain, "windshield_rain_needed", lambda: True) + assert rain_wiper_needed() + set_rain_wiper_needed(False) + assert not rain_wiper_needed() + set_rain_wiper_needed(None) + + +def test_auto_only_in_drive_or_reverse(monkeypatch): + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + try: + set_auto_gates(True, "drive") + assert body.requested_wiper_test() + set_auto_gates(True, "reverse") + assert body.requested_wiper_test() + set_auto_gates(True, "park") + assert not body.requested_wiper_test() + set_auto_gates(True, "neutral") + assert not body.requested_wiper_test() + set_auto_gates(False, "drive") + assert not body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_park_or_standstill_suppress_drive_moving_still_wipes(monkeypatch): + """Garage v≈0 / Park must not Auto-wipe. Drive at speed still wipes.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + try: + set_auto_gates(True, "park", v_ego=0.0) + assert not body.auto_wipe_moving() + assert not body.requested_wiper_test() + set_auto_gates(True, "drive", v_ego=0.0) + assert body.in_drive_gear() + assert not body.auto_wipe_moving() + assert not body.requested_wiper_test() + set_auto_gates(True, "drive", v_ego=0.3) + assert not body.requested_wiper_test() + set_auto_gates(True, "drive", v_ego=12.0) + assert body.auto_wipe_moving() + assert body.requested_wiper_test() + set_auto_gates(True, "reverse", v_ego=5.0) + assert body.requested_wiper_test() + # Unknown speed does not suppress (Drive tests without vEgo still wipe). + set_auto_gates(True, "drive") + assert body.live_v_ego() is None + assert body.auto_wipe_moving() + assert body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_reads_vego_from_cs_out(monkeypatch): + """Stock-cc CS.out.vEgo=0 (garage in Drive) must not Auto-wipe.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + reset_auto_gates() + try: + inner = SimpleNamespace( + msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}, + out=SimpleNamespace(gearShifter="drive", vEgo=0.0), + ) + body.update_live_car_state(inner) + assert body.in_drive_gear() + assert body.live_v_ego() == 0.0 + assert not body.auto_wipe_moving() + assert not body.requested_wiper_test() + line = body._auto_status_line(3, True, True, True, False, moving=False) + assert "park=0" in line + assert "v0=1" in line + assert "moving=0" in line + assert "wipe=0" in line + inner.out.vEgo = 15.0 + assert body.auto_wipe_moving() + assert body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_int_on_ignore_standstill(monkeypatch): + """Legacy Int/On coerce to Off. Auto is the only gated wipe mode.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + set_rain_wiper_needed(False) + set_auto_gates(True, "park", v_ego=0.0) + try: + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_INTERMITTENT if key == NAP_WIPER_SPEED else default + )) + assert not body.requested_wiper_test() + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_ON if key == NAP_WIPER_SPEED else default + )) + assert not body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_gear_aliases_and_enum_name(monkeypatch): + """Live CS may stringify as GearShifter.drive or D — still Auto-wipe.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + + class _Enumish: + name = "drive" + + def __str__(self): + return "CarState.GearShifter.drive" + + try: + for gear in ("drive", "DRIVE", "D", "reverse", "R", _Enumish()): + set_auto_gates(True, gear) + assert body.in_drive_gear(), gear + assert body.requested_wiper_test(), gear + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, True, False) + assert _byte(held) == STW_WIPER_ON + set_auto_gates(True, "park") + assert not body.requested_wiper_test() + set_auto_gates(True, "unknown") + assert not body.requested_wiper_test() + line = body._auto_status_line(3, True, True, True, True) + assert "setting=3" in line + assert "gear=" in line + assert "gear_src=" in line + assert "wipe=1" in line + assert "collar=1" in line + assert "wash=0" in line + assert "installed=" in line + assert line.startswith("nap wiper auto") + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_reads_preap_inner_cs_out_gear(monkeypatch): + """StockCCSpoofer CS is the inner Tesla parser. Drive is on CS.out, not CS.gearShifter.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + reset_auto_gates() + try: + inner = SimpleNamespace( + msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}, + out=SimpleNamespace(gearShifter="drive"), + ) + assert not hasattr(inner, "gearShifter") + body.update_live_car_state(inner) + assert body.vehicle_is_on() + assert body.in_drive_gear() + assert body.requested_wiper_test() + line = body._auto_status_line(3, True, True, True, True) + assert "gear=drive" in line + assert "gear_src=out" in line + assert "wipe=1" in line + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, True, False) + assert _byte(held) == STW_WIPER_ON + + inner.out.gearShifter = "park" + assert not body.in_drive_gear() + assert not body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_gear_int_enum_and_di_gear_tokens(monkeypatch): + """Live Drive may be GearShifter int 2, Tesla DI_gear 4, or DI_GEAR_D.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + try: + for gear in (2, 4, "DI_GEAR_D", "DI_GEAR_R"): + set_auto_gates(True, gear) + assert body.in_drive_gear(), gear + assert body.requested_wiper_test(), gear + set_auto_gates(True, 1) + assert not body.in_drive_gear() + assert not body.requested_wiper_test() + set_auto_gates(True, 3) + assert not body.in_drive_gear() + assert not body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +class _DynamicEnum: + """cereal / opendbc capnp gear: str is 'drive', .name is None, != structs enum.""" + name = None + + def __str__(self): + return "drive" + + def __repr__(self): + return "_DynamicEnum" + + def __eq__(self, other): + return False + + +def test_auto_gear_dynamic_enum_name_none_str_drive(monkeypatch): + """Justin: cereal gearShifter is drive _DynamicEnum None — Auto must still wipe.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + gear = _DynamicEnum() + assert gear.name is None + assert str(gear) == "drive" + try: + set_auto_gates(True, gear) + assert body._gear_name(gear) == "drive" + assert body.in_drive_gear() + assert body.requested_wiper_test() + line = body._auto_status_line(3, True, True, True, True) + assert "gear=drive" in line + assert "gear_type=_DynamicEnum" in line + assert "wipe=1" in line + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, True, False) + assert _byte(held) == STW_WIPER_ON + + inner = SimpleNamespace( + gearShifter=0, + msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}, + out=SimpleNamespace(gearShifter=gear), + ) + reset_auto_gates() + set_rain_wiper_needed(True) + body.update_live_car_state(inner) + assert body.vehicle_is_on() + assert body.in_drive_gear() + assert body.requested_wiper_test() + line = body._auto_status_line(3, True, True, True, True) + assert "gear_src=out" in line + assert "gear=drive" in line + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + fake = _FakeSpoofer() + out = body.stock_cc_update_with_overlay(fake, inner, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_gear_alias_without_gearShifter(monkeypatch): + """Inner CS may expose Drive as gear / gear_shifter, not gearShifter.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + reset_auto_gates() + try: + inner = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}, gear="drive") + assert not hasattr(inner, "gearShifter") + body.update_live_car_state(inner) + assert body.in_drive_gear() + assert body.requested_wiper_test() + line = body._auto_status_line(3, True, True, True, True) + assert "gear=drive" in line + assert "wipe=1" in line + inner.gear = "park" + assert not body.in_drive_gear() + assert not body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_cereal_fallback_when_cs_gearshifter_missing(monkeypatch): + """Live miss: stock-cc CS has no gearShifter; cereal carState is drive _DynamicEnum.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + reset_auto_gates() + gear = _DynamicEnum() + try: + inner = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + assert not hasattr(inner, "gearShifter") + assert not hasattr(inner, "out") + body.update_live_car_state(inner) + set_cereal_gear(gear) + assert body.vehicle_is_on() + assert body.in_drive_gear() + assert body.requested_wiper_test() + line = body._auto_status_line(3, True, True, True, True) + assert line.startswith("nap wiper auto") + assert "gear=drive" in line + assert "gear_src=cereal" in line + assert "gear_type=_DynamicEnum" in line + assert "drive=1" in line + assert "wipe=1" in line + rest = _rest() + held = apply_stw_wiper_beam_nibbles(rest, True, False) + assert _byte(held) == STW_WIPER_ON + + class _Fake: + def __init__(self): + self.sent = [] + + def _send(self, CS, tesla_can, bus, button): + msg = (STW_ACTN_RQ_ADDR, bytes([button]), bus) + self.sent.append(msg) + return msg + + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + out = body.stock_cc_update_with_overlay(_Fake(), inner, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + + set_cereal_gear("park") + assert not body.in_drive_gear() + assert not body.requested_wiper_test() + park_line = body._auto_status_line(3, True, False, True, False) + assert "gear=park" in park_line + assert "wipe=0" in park_line + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_cs_park_wins_over_cereal_drive(monkeypatch): + """Once CS gear is known Park, stale cereal Drive must not Auto-wipe.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + set_rain_wiper_needed(True) + reset_auto_gates() + try: + inner = SimpleNamespace(gearShifter="park", msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + body.update_live_car_state(inner) + set_cereal_gear(_DynamicEnum()) + assert not body.in_drive_gear() + assert not body.requested_wiper_test() + line = body._auto_status_line(3, True, False, True, False) + assert "gear=park" in line + assert "gear_src=cs" in line + assert "wipe=0" in line + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_auto_status_param_is_full_gate_line_not_short_rain(monkeypatch): + """Justin cat'd hold= ema= because rain _debug overwrote the Auto gates.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + captured = {} + monkeypatch.setattr(body, "_put_wiper_status", lambda line: captured.__setitem__("NAPWiperRainStatus", line)) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + det = WindshieldRain() + det.hold = True + det.ema = 4.83 + det.last_score = 5.03 + det.last_bokeh = 4.48 + det.last_sparse = 5.4 + det.connected = True + det._failed = False + det.n_frames = 8865 + det.stream = "ROAD" + rain._detector = det + set_rain_wiper_needed(True) + try: + set_auto_gates(True, "drive") + body._last_auto_log_t = 0.0 + body._last_status_put_t = 0.0 + body._last_status_gate = None + assert body.requested_wiper_test() + line = captured["NAPWiperRainStatus"] + assert line.startswith("nap wiper auto") + assert "setting=3" in line + assert "on=1" in line + assert "gear=drive" in line + assert "drive=1" in line + assert "rain=1" in line + assert "wipe=1" in line + assert "cancel=0" in line + assert "installed=" in line + assert "gear_type=" in line + assert "hold=1" in line + assert "holdn=" in line + assert "warm=" in line + assert "struct=" in line + assert "speckle=" in line + assert "frames=8865" in line + assert "helper=" in line + assert "period_s=" in line + assert "hz=" in line + assert "clear=" in line + assert "heavy=" in line + assert "pulse=" in line + assert "wait=" in line + assert "score=" in line + assert "bokeh=" in line + assert "sens=" in line + assert "acq=" in line + assert "rpt=" in line + assert "gap=" in line + assert "thin=" in line + assert "thin_gap=" in line + assert "park=" in line + assert "v0=" in line + assert "moving=" in line + assert not line.startswith("hold=") + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + reset_windshield_rain() + + +def test_auto_status_sens0_vs_mid_acq_rpt_gap(monkeypatch): + """HUD status: same light-mist score is rpt=1 on Drier, rpt=0 on Mid.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + + mist = 6.7 + assert acquire_threshold(0) <= mist + assert mist >= repeat_threshold(0) + assert mist < repeat_threshold(2) + det = WindshieldRain() + det.last_score = mist + rain._detector = det + + def _param_for(sens): + return lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else + sens if key == body.NAP_WIPER_SENSITIVITY else default + ) + + try: + monkeypatch.setattr(body, "_param_int", _param_for(0)) + line0 = body._auto_status_line(3, True, True, True, False) + assert "sens=0" in line0 + assert "acq=1" in line0 + assert "rpt=1" in line0 + assert "gap=" in line0 + assert "thin=" in line0 + assert "thin_gap=" in line0 + assert "holdn=" in line0 + + monkeypatch.setattr(body, "_param_int", _param_for(2)) + line2 = body._auto_status_line(3, True, True, True, False) + assert "sens=2" in line2 + assert "acq=1" in line2 + assert "rpt=0" in line2 + assert "gap=" in line2 + assert "thin=" in line2 + assert "thin_gap=" in line2 + + det.last_score = (THIN_ON + acquire_threshold(2)) * 0.5 + det._thin = True + det._thin_gap_s = thin_gap_s(2) + det._thin_t0 = time.monotonic() + monkeypatch.setattr(body, "_param_int", _param_for(2)) + line_thin = body._auto_status_line(3, True, True, True, False) + assert "thin=1" in line_thin + assert "thin_gap=" in line_thin + finally: + reset_windshield_rain() + + +def test_auto_status_put_is_rate_limited_not_every_10ms(monkeypatch): + """100 Hz Params.put on stock_cc.update lagged engage. 1 Hz or gate change only.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + puts = [] + monkeypatch.setattr(body, "_put_wiper_status", lambda line: puts.append(line)) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + reset_auto_gates() + set_rain_wiper_needed(True) + try: + set_auto_gates(True, "drive") + for _ in range(20): + assert body.requested_wiper_test() + assert 1 <= len(puts) <= 2 + set_rain_wiper_needed(False) + assert not body.requested_wiper_test() + assert len(puts) >= 2 + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_windshield_rain_needed_does_not_start_helper(): + """poll/needed must not subscribe ROAD. stock_cc starts the helper while Auto.""" + from openpilot.selfdrive.car.tesla import preap_windshield_rain as rain + reset_windshield_rain() + assert not rain.windshield_rain_needed() + assert rain._detector is None + + +def test_rain_debug_does_not_put_status_param(): + """Short hold= line must not overwrite NAPWiperRainStatus.""" + import inspect + from openpilot.selfdrive.car.tesla.preap_windshield_rain import WindshieldRain + src = inspect.getsource(WindshieldRain._debug) + assert "Params" not in src + assert ".put(" not in src + assert "_log_auto_status" not in src + assert "preap_body_controls" not in src + + +def test_put_wiper_status_uses_exact_nap_wiper_rain_status_key(): + """Unknown param keys fail put silently; qlog InitData only logs this name.""" + import inspect + from openpilot.selfdrive.car.tesla.preap_body_controls import _put_wiper_status + src = inspect.getsource(_put_wiper_status) + assert src.count('"NAPWiperRainStatus"') >= 1 + assert "NAPWiperRain" in src + assert "NAPWiperSpeed" not in src + # First write must block so the key exists for Connect / qlog digs. + assert "block=block" in src or "block=True" in src + assert "_status_disk_once" in src + assert "NAPWiperRainStatus" in src + assert "get(" in src + + +def test_put_wiper_status_blocks_again_when_key_missing(monkeypatch): + """e1 InitData missed status after CLEAR_ON_MANAGER_START wiped the stub.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + class FakeParams: + def __init__(self): + self.store = {} + self.blocks = [] + + def get(self, key, return_default=False): + return self.store.get(key) + + def put(self, key, dat, block=False): + self.blocks.append(bool(block)) + self.store[key] = dat + + fake = FakeParams() + monkeypatch.setattr(body, "_get_params", lambda: fake) + body._status_disk_once = True + body._put_wiper_status("first") + assert fake.blocks == [True] + assert body._status_disk_once is False + body._put_wiper_status("second") + assert fake.blocks == [True, False] + fake.store.clear() + body._put_wiper_status("third") + assert fake.blocks[-1] is True + assert fake.store["NAPWiperRainStatus"] == "third" + + +def test_int_on_ignore_gear_and_camera(monkeypatch): + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + set_rain_wiper_needed(False) + set_auto_gates(True, "park") + try: + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_INTERMITTENT if key == NAP_WIPER_SPEED else default + )) + assert not body.requested_wiper_test() + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_ON if key == NAP_WIPER_SPEED else default + )) + assert not body.requested_wiper_test() + monkeypatch.setattr(body, "_param_int", lambda key, default=0: default) + assert not body.requested_wiper_test() + finally: + set_rain_wiper_needed(None) + reset_auto_gates() + + +def test_register_defaults_stay_off(): + from opendbc.car.tesla.preap.nap_params import DEFAULTS, NAPParamKeys + register_nap_body_params() + assert NAPParamKeys.WIPER_SPEED == NAP_WIPER_SPEED + assert NAPParamKeys.HIGH_LOW_BEAM == NAP_HIGH_LOW_BEAM + assert NAPParamKeys.WIPER_SENSITIVITY == "NAPWiperSensitivity" + assert DEFAULTS[NAP_WIPER_SPEED] == 0 + assert DEFAULTS[NAP_HIGH_LOW_BEAM] == 0 + assert DEFAULTS["NAPWiperSensitivity"] == 2 + + +def test_das_body_controls_stays_zero_when_settings_on(): + """DAS wiper/beam fields caused a controls mismatch. Leave them at 0.""" + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + _, dat, _ = tc.create_body_controls_message(1, 0, CANBUS.party, 1) + assert (dat[0] >> 4) & 0x0F == 0 # DAS_wiperSpeed + assert (dat[1] >> 2) & 0x03 == 0 # DAS_highLowBeamDecision + assert dat[0] & 0x03 == 0 # DAS_headlightRequest + + +def test_das_body_controls_still_requests_turn_indicator(): + """ALC keep-alive uses DAS_turnIndicatorRequest. Do not zero it with wipers.""" + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + _, none, _ = tc.create_body_controls_message(0, 0, CANBUS.party, 1) + _, left, _ = tc.create_body_controls_message(1, 0, CANBUS.party, 1) + _, right, _ = tc.create_body_controls_message(2, 0, CANBUS.party, 1) + assert left != none + assert right != none + assert left != right + for dat in (none, left, right): + assert (dat[0] >> 4) & 0x0F == 0 # DAS_wiperSpeed stays 0 + assert (dat[1] >> 2) & 0x03 == 0 # DAS_highLowBeamDecision stays 0 + + +def test_create_action_request_overlay_holds_4_and_valid_crc(monkeypatch): + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS, CruiseButtons + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + msg_stw = { + "MC_STW_ACTN_RQ": 5, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 1, + "WprSw6Posn": 3, + "WprWashSw_Psd": 0, + "HiBmLvr_Stat": 0, + } + stock = tc.create_action_request(CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + monkeypatch.setattr(body, "requested_wiper_test", lambda: True) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: True) + monkeypatch.setattr(body, "_ORIG_CREATE_ACTION_REQUEST", TeslaCANPreAP.create_action_request) + addr, dat, bus = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + assert addr == STW_ACTN_RQ_ADDR == stock[0] + assert bus == stock[2] + assert _byte(dat) == (STW_WIPER_ON | STW_HIGH_BEAM) + assert dat[6] & 0x07 == 3 # WprSw6Posn preserved + assert dat[:2] == stock[1][:2] + assert dat[3:7] == stock[1][3:7] + assert dat[7] == tc.stw_crc(dat[:7]) + assert _byte(dat) != STW_WASHER_SPRAY + # Holding High keeps nibble 4. Rest/IDLE and SNA are not what goes out. + for _ in range(8): + _, held, _ = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + assert _byte(held) == (STW_WIPER_ON | STW_HIGH_BEAM) + assert hibm_nibble(held) == STW_HIGH_BEAM + assert hibm_nibble(held) != 0 + assert (hibm_nibble(held) & STW_HIBM_MASK) != STW_HIBM_MASK + assert held[7] == tc.stw_crc(held[:7]) + + +class _FakeSpoofer: + def __init__(self): + self.sent = [] + + def _send(self, CS, tesla_can, bus, button): + msg = (STW_ACTN_RQ_ADDR, bytes([button]), bus) + self.sent.append((button, msg)) + return msg + + +def test_stock_cc_overlay_forwards_once_and_never_a_second_0x45(monkeypatch): + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + monkeypatch.setattr(body, "requested_wiper_test", lambda: True) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + assert fake.sent[0][0] == 0 + + already = [(STW_ACTN_RQ_ADDR, b"\x00" * 8, 0)] + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: already) + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert out == already + assert fake.sent == [] + + +def test_disengaged_idle_stalk_still_forwards_when_on(monkeypatch): + """Car on, NAP not engaged, no stalk pull: On/High must still forward 0x45.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _FakeSpoofer() + cs = SimpleNamespace( + cruiseEnabled=False, + enableLongControl=False, + enableJustCC=False, + latActive=False, + msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}, # IDLE — no stalk pull + ) + monkeypatch.setattr(body, "requested_wiper_test", lambda: True) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: True) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + assert fake.sent[0][0] == 0 # forwarded idle lever, not a cruise press + + +def test_high_holds_4_and_extra_forwards_until_off(monkeypatch): + """Holding High keeps TXing 0x45 with nibble 4 so rest/IDLE cannot cancel.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0, "MC_STW_ACTN_RQ": 9}) + monkeypatch.setattr(body, "requested_wiper_test", lambda: False) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: True) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + + forwarded = 0 + for slot in range(1, 8): + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, slot * 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + forwarded += 1 + assert forwarded == 7 + # Between 10 Hz slots too — bus-0 IDLE cannot sit unopposed. + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 11, None, 0) + assert len(out) == 1 + assert extra_stw_forward_needed([], 11, False, True) is True + + # Leave High — extra-forward stops, real stalk returns. + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 70, None, 0) + assert out == [] + assert extra_stw_forward_needed([], 70, False, False) is False + # Come back — hold 4 again, not a one-shot tap. + monkeypatch.setattr(body, "requested_high_beam_test", lambda: True) + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 80, None, 0) + assert len(out) == 1 + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 81, None, 0) + assert len(out) == 1 + + +def test_relayed_bus0_rest_is_replaced_with_held_4(): + """candump bus 0 00ff00 is the live stalk. Replace that payload in place.""" + rest = bytes.fromhex("00ff000000090e80") + assert hibm_nibble(rest) == 0 + patched = replace_relayed_stw(rest, False, True, crc_fn=lambda payload: 0xAA) + assert patched[:3] == bytes.fromhex("00ff04") + assert hibm_nibble(patched) == STW_HIGH_BEAM + assert hibm_nibble(patched) != 0 + assert hibm_nibble(patched) != STW_HIGH_BEAM_FLASH + assert (hibm_nibble(patched) & STW_HIBM_MASK) != STW_HIBM_MASK + # Same live frame — counter and neighboring bytes stay. Only HiBm + CRC. + assert patched[:2] == rest[:2] + assert patched[3:7] == rest[3:7] + assert patched[7] == 0xAA + # Off does not rewrite rest/IDLE. + assert replace_relayed_stw(rest, False, False) == rest + # Holding High keeps replacing with 4, not rest. + for _ in range(8): + again = replace_relayed_stw(rest, False, True) + assert hibm_nibble(again) == STW_HIGH_BEAM + assert again[:3] != rest[:3] + + +def test_live_stw_counter_is_not_plus_one(): + assert live_stw_counter({"MC_STW_ACTN_RQ": 9}) == 9 + assert live_stw_counter({"MC_STW_ACTN_RQ": 15}) == 15 + assert live_stw_counter({"MC_STW_ACTN_RQ": 0}) == 0 + + +def test_send_replaced_live_stw_uses_live_counter_not_plus_one(): + from types import SimpleNamespace + + class _Rec: + def __init__(self): + self.counter = None + + def create_action_request(self, button, bus, counter, msg_stw=None): + self.counter = counter + return (STW_ACTN_RQ_ADDR, b"\x00" * 8, bus) + + rec = _Rec() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0, "MC_STW_ACTN_RQ": 9}) + out = send_replaced_live_stw(_FakeSpoofer(), cs, rec, 0) + assert out[0] == STW_ACTN_RQ_ADDR + assert rec.counter == 9 # live MC, not 10 + + +def test_replace_relayed_rest_on_packed_stw_holds_4_same_mc(): + """Edit the packed live 0x45 — same MC, held 4, rest/IDLE gone, CRC re-signed.""" + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS, CruiseButtons + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + msg_stw = { + "MC_STW_ACTN_RQ": 9, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 0, + "HiBmLvr_Stat": 0, + } + _, rest, _ = tc.create_action_request(CruiseButtons.IDLE, CANBUS.party, 9, msg_stw) + assert rest[:3] == bytes.fromhex("00ff00") + patched = replace_relayed_stw(rest, False, True, crc_fn=tc.stw_crc) + assert patched[:3] == bytes.fromhex("00ff04") + assert hibm_nibble(patched) == STW_HIGH_BEAM + assert (patched[6] >> 4) & 0x0F == (rest[6] >> 4) & 0x0F # MC nibble + assert patched[7] == tc.stw_crc(patched[:7]) + assert patched[7] != rest[7] + + +def test_high_extra_forward_keeps_sending_00ff04(monkeypatch): + """High extra-forward keeps 00ff04 on the live-counter 0x45. Never SNA or rest.""" + from types import SimpleNamespace + + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + orig = TeslaCANPreAP.create_action_request + monkeypatch.setattr(TeslaCANPreAP, "create_action_request", body.create_action_request_with_overlay) + monkeypatch.setattr(body, "_ORIG_CREATE_ACTION_REQUEST", orig) + monkeypatch.setattr(body, "requested_wiper_test", lambda: False) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: True) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={ + "SpdCtrlLvr_Stat": 0, + "MC_STW_ACTN_RQ": 9, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 0, + "HiBmLvr_Stat": 0, + }) + for frame in range(20): + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, frame, tc, CANBUS.party) + assert len(out) == 1 + addr, dat, bus = out[0] + assert addr == STW_ACTN_RQ_ADDR + assert bus == CANBUS.party + assert (dat[6] >> 4) & 0x0F == 9 + assert dat[:3] == bytes.fromhex("00ff04") + assert hibm_nibble(dat) == STW_HIGH_BEAM + assert (hibm_nibble(dat) & STW_HIBM_MASK) != STW_HIBM_MASK + assert dat[7] == tc.stw_crc(dat[:7]) + assert fake.sent == [] # High uses send_replaced_live_stw, not _send MC+1 + + +def test_stock_cc_off_does_not_change_forwarding(monkeypatch): + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + reset_auto_gates() + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + monkeypatch.setattr(body, "requested_wiper_test", lambda: False) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + assert body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) == [] + assert fake.sent == [] + assert extra_stw_forward_needed([], 10, False, False) is False + reset_auto_gates() + + +def test_create_action_request_off_matches_stock(monkeypatch): + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS, CruiseButtons + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + msg_stw = { + "MC_STW_ACTN_RQ": 5, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 1, + "WprSw6Posn": 2, + } + stock = tc.create_action_request(CruiseButtons.SET_ACCEL, CANBUS.party, 6, msg_stw) + monkeypatch.setattr(body, "requested_wiper_test", lambda: False) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_CREATE_ACTION_REQUEST", TeslaCANPreAP.create_action_request) + test = body.create_action_request_with_overlay( + tc, CruiseButtons.SET_ACCEL, CANBUS.party, 6, msg_stw) + assert test == stock + + +def test_auto_overlay_holds_interval1_on_rain_and_releases_when_dry(monkeypatch): + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS, CruiseButtons + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + msg_stw = { + "MC_STW_ACTN_RQ": 5, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 1, + "WprSw6Posn": 0, + "WprWashSw_Psd": 0, + "HiBmLvr_Stat": 0, + } + stock = tc.create_action_request(CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + rain = {"on": True} + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "rain_wiper_needed", lambda: rain["on"]) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_CREATE_ACTION_REQUEST", TeslaCANPreAP.create_action_request) + set_auto_gates(True, "drive") + try: + addr, dat, bus = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + assert addr == STW_ACTN_RQ_ADDR == stock[0] + assert bus == stock[2] + assert _byte(dat) != STW_WIPER_ON + assert _byte(dat) != STW_WASHER_SPRAY + assert stw_wash(dat) == 0 + assert stw_collar_posn(dat) == STW_COLLAR_INTERVAL1 + assert (dat[6] >> 4) & 0x0F == (stock[1][6] >> 4) & 0x0F # live MC + assert dat[7] == tc.stw_crc(dat[:7]) + for _ in range(8): + _, held, _ = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + assert stw_collar_posn(held) == STW_COLLAR_INTERVAL1 + assert stw_wash(held) == 0 + assert _byte(held) != STW_WIPER_ON + assert _byte(held) != STW_WASHER_SPRAY + + rain["on"] = False + _, released, _ = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + assert stw_collar_posn(released) == 0 + assert stw_wash(released) == 0 + assert _byte(released) != STW_WIPER_ON + assert released[7] == tc.stw_crc(released[:7]) + + rain["on"] = True + set_auto_gates(True, "park") + _, parked, _ = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + assert stw_collar_posn(parked) == 0 + assert stw_wash(parked) == 0 + assert _byte(parked) != STW_WIPER_ON + finally: + reset_auto_gates() + + +def test_auto_stock_cc_forwards_on_rain_and_cancels_when_dry(monkeypatch): + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + reset_auto_gates() + fake = _FakeSpoofer() + cs = SimpleNamespace( + cruiseEnabled=False, + latActive=False, + msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}, + ) + rain = {"on": True} + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "requested_wiper_test", lambda: wiper_test_requested( + WIPER_SETTING_AUTO, rain["on"])) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 11, None, 0) + assert len(out) == 1 + assert extra_stw_forward_needed([], 11, True, False, collar_hold=True) is True + + rain["on"] = False + fake.sent.clear() + # Falling edge must extra-forward rest immediately, not wait for the 10 Hz slot. + out = body.stock_cc_update_with_overlay(fake, cs, 11, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + assert extra_stw_forward_needed([], 11, False, False, wiper_cancel=True, cancel_now=True) is True + assert extra_stw_forward_needed([], 20, False, False) is False + reset_auto_gates() + + +def test_auto_stock_cc_forwards_when_gear_only_on_cs_out(monkeypatch): + """Live miss: inner CS has no gearShifter, Drive is on CS.out. Still TX nibble 1.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _FakeSpoofer() + cs = SimpleNamespace( + msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}, + out=SimpleNamespace(gearShifter="drive"), + ) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "rain_wiper_needed", lambda: True) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + reset_auto_gates() + try: + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + assert extra_stw_forward_needed([], 10, True, False) is True + cs.out.gearShifter = "park" + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 20, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + assert extra_stw_forward_needed([], 20, False, False, wiper_cancel=True) is True + finally: + reset_auto_gates() + reset_windshield_rain() + + +def test_auto_stock_cc_releases_when_shifted_to_park(monkeypatch): + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _FakeSpoofer() + cs = SimpleNamespace( + gearShifter="drive", + msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}, + ) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "rain_wiper_needed", lambda: True) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + reset_auto_gates() + try: + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + cs.gearShifter = "park" + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 20, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + assert extra_stw_forward_needed([], 20, False, False, wiper_cancel=True) is True + finally: + reset_auto_gates() + reset_windshield_rain() + + +def test_auto_does_not_change_high_beam_hold_path(monkeypatch): + """Auto rain must not switch High off the live-counter 00ff04 hold.""" + from types import SimpleNamespace + + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + orig = TeslaCANPreAP.create_action_request + monkeypatch.setattr(TeslaCANPreAP, "create_action_request", body.create_action_request_with_overlay) + monkeypatch.setattr(body, "_ORIG_CREATE_ACTION_REQUEST", orig) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "requested_wiper_test", lambda: wiper_test_requested( + WIPER_SETTING_AUTO, True)) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: True) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={ + "SpdCtrlLvr_Stat": 0, + "MC_STW_ACTN_RQ": 9, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 0, + "HiBmLvr_Stat": 0, + }) + for frame in range(5): + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, frame, tc, CANBUS.party) + assert len(out) == 1 + addr, dat, bus = out[0] + assert addr == STW_ACTN_RQ_ADDR + assert dat[:3] == bytes.fromhex("00ff04") # High nibble 4, no TIPWIPE + assert hibm_nibble(dat) == STW_HIGH_BEAM + assert stw_collar_posn(dat) == STW_COLLAR_INTERVAL1 + assert stw_wash(dat) == 0 + assert _byte(dat) != STW_WASHER_SPRAY + assert (dat[6] >> 4) & 0x0F == 9 + assert fake.sent == [] # High still uses send_replaced_live_stw, not _send MC+1 + + +def test_auto_does_not_touch_das_body_controls(): + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + _, dat, _ = tc.create_body_controls_message(1, 0, CANBUS.party, 1) + assert (dat[0] >> 4) & 0x0F == 0 # DAS_wiperSpeed + assert (dat[1] >> 2) & 0x03 == 0 # DAS_highLowBeamDecision + assert dat[0] & 0x03 == 0 # DAS_headlightRequest + + +def test_auto_dry_extra_forwards_rest_without_forcing_wipe(monkeypatch): + """Auto selected + wipe=False must still TX rest so Pre-AP drops ~32s Int.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + reset_auto_gates() + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "rain_wiper_needed", lambda: False) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + set_auto_gates(True, "drive") + try: + assert not body.requested_wiper_test() + assert wiper_rest_tx_needed(False) is True + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + assert extra_stw_forward_needed([], 10, False, False, wiper_cancel=True) is True + assert extra_stw_forward_needed([], 11, False, False, wiper_cancel=True) is False + finally: + reset_auto_gates() + + +def test_auto_rain_rising_edge_stops_rest_cancel(monkeypatch): + """Cancel while wipe=0 must not keep rest-TX after HOLD/wipe becomes true.""" + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + rain = {"on": False} + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "rain_wiper_needed", lambda: rain["on"]) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + reset_auto_gates() + set_auto_gates(True, "drive") + try: + assert not body.requested_wiper_test() + assert wiper_rest_tx_needed(False) is True + rest = _rest() + dry = apply_stw_wiper_beam_nibbles(rest, False, False, clear_wiper=True) + assert _byte(dry) != STW_WIPER_ON + assert extra_stw_forward_needed([], 10, False, False, wiper_cancel=True) is True + + rain["on"] = True + assert body.requested_wiper_test() is True + assert wiper_rest_tx_needed(True) is False + wet = apply_stw_wiper_beam_nibbles(rest, True, False, clear_wiper=wiper_rest_tx_needed(True)) + assert _byte(wet) == STW_WIPER_ON + assert _byte(wet) != STW_WASHER_SPRAY + assert extra_stw_forward_needed([], 10, True, False, wiper_cancel=False) is True + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + finally: + reset_auto_gates() + + +def test_int_to_off_sends_rest_cancel_burst_then_leaves_stalk(monkeypatch): + from types import SimpleNamespace + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + reset_auto_gates() + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={"SpdCtrlLvr_Stat": 0}) + on = {"v": True} + monkeypatch.setattr(body, "requested_wiper_test", lambda: on["v"]) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + try: + out = body.stock_cc_update_with_overlay(fake, cs, 10, None, 0) + assert len(out) == 1 + on["v"] = False + forwarded = 0 + for frame in range(11, 11 + STW_CANCEL_BURST_N): + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, frame, None, 0) + assert len(out) == 1 + assert out[0][0] == STW_ACTN_RQ_ADDR + forwarded += 1 + assert forwarded == STW_CANCEL_BURST_N + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, 10 + STW_CANCEL_BURST_N * 10, None, 0) + assert out == [] + assert extra_stw_forward_needed([], 10, False, False) is False + finally: + reset_auto_gates() + + +def test_auto_overlay_dry_clears_held_nibble_not_identity(monkeypatch): + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS, CruiseButtons + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + msg_stw = { + "MC_STW_ACTN_RQ": 5, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 1, + "WprSw6Posn": 3, + "WprWashSw_Psd": 0, + "HiBmLvr_Stat": 0, + } + stock = tc.create_action_request(CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "rain_wiper_needed", lambda: False) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_CREATE_ACTION_REQUEST", TeslaCANPreAP.create_action_request) + set_auto_gates(True, "drive") + try: + addr, dat, bus = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + assert addr == STW_ACTN_RQ_ADDR == stock[0] + assert bus == stock[2] + assert _byte(dat) != STW_WIPER_ON + assert _byte(dat) != STW_WASHER_SPRAY + assert stw_wash(dat) == 0 + assert stw_collar_posn(dat) == 0 # Auto dry forces Off over live leftover + assert (dat[6] >> 4) & 0x0F == (stock[1][6] >> 4) & 0x0F + assert dat != stock + held = bytes.fromhex("00ff10") + stock[1][3:] + cleared = replace_relayed_stw(held, False, False, crc_fn=tc.stw_crc, + clear_wiper=True, collar_posn=0) + assert _byte(cleared) == 0 + assert stw_collar_posn(cleared) == 0 + assert stw_wash(cleared) == 0 + assert cleared[7] == tc.stw_crc(cleared[:7]) + finally: + reset_auto_gates() + + +def test_apply_stw_collar_interval1_clears_tipwipe_keeps_mc(): + rest = _rest() + held = apply_stw_collar(rest, STW_COLLAR_INTERVAL1) + assert stw_collar_posn(held) == STW_COLLAR_INTERVAL1 + assert stw_wash(held) == 0 + assert _byte(held) != STW_WIPER_ON + assert _byte(held) != STW_WASHER_SPRAY + assert apply_stw_collar(rest, None) == rest + tip = apply_stw_wiper_beam_nibbles(rest, True, False) + assert _byte(tip) == STW_WIPER_ON + auto = apply_stw_collar(tip, STW_COLLAR_INTERVAL1) + assert stw_wash(auto) == 0 + assert _byte(auto) & STW_WASH_MASK == 0 + assert stw_collar_posn(auto) == STW_COLLAR_INTERVAL1 + live = bytearray(rest) + live[6] = 0x50 # MC=5, collar Off + forced = apply_stw_collar(bytes(live), STW_COLLAR_INTERVAL1) + assert stw_collar_posn(forced) == STW_COLLAR_INTERVAL1 + assert (forced[6] >> 4) & 0x0F == 5 + dry = apply_stw_collar(forced, 0) + assert stw_collar_posn(dry) == 0 + assert (dry[6] >> 4) & 0x0F == 5 + + +def test_auto_collar_last_wins_live_off(monkeypatch): + """Live stalk Off is collar=0. Auto wipe must overlay INTERVAL1 on that frame.""" + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS, CruiseButtons + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + msg_stw = { + "MC_STW_ACTN_RQ": 9, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 1, + "WprSw6Posn": 0, # live Off + "WprWashSw_Psd": 0, + "HiBmLvr_Stat": 0, + } + stock = tc.create_action_request(CruiseButtons.IDLE, CANBUS.party, 9, msg_stw) + assert stw_collar_posn(stock[1]) == 0 + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_AUTO if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "rain_wiper_needed", lambda: True) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_CREATE_ACTION_REQUEST", TeslaCANPreAP.create_action_request) + orig = TeslaCANPreAP.create_action_request + monkeypatch.setattr(TeslaCANPreAP, "create_action_request", body.create_action_request_with_overlay) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + set_auto_gates(True, "drive") + try: + assert body.requested_auto_collar_posn(True) == STW_COLLAR_INTERVAL1 + _, dat, _ = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 9, msg_stw) + assert stw_collar_posn(dat) == STW_COLLAR_INTERVAL1 + assert stw_wash(dat) == 0 + assert _byte(dat) != STW_WIPER_ON + assert (dat[6] >> 4) & 0x0F == 9 + assert dat[7] == tc.stw_crc(dat[:7]) + last_mile = overlay_collar_on_can_msg(stock, tc, STW_COLLAR_INTERVAL1) + assert stw_collar_posn(last_mile[1]) == STW_COLLAR_INTERVAL1 + assert last_mile[1][7] == tc.stw_crc(last_mile[1][:7]) + + from types import SimpleNamespace + fake = _FakeSpoofer() + cs = SimpleNamespace(msg_stw_actn_req={ + "SpdCtrlLvr_Stat": 0, + "MC_STW_ACTN_RQ": 9, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 1, + "WprSw6Posn": 0, + "WprWashSw_Psd": 0, + "HiBmLvr_Stat": 0, + }) + for frame in range(5): + fake.sent.clear() + out = body.stock_cc_update_with_overlay(fake, cs, frame, tc, CANBUS.party) + assert len(out) == 1 + addr, held, bus = out[0] + assert addr == STW_ACTN_RQ_ADDR + assert stw_collar_posn(held) == STW_COLLAR_INTERVAL1 + assert stw_wash(held) == 0 + assert _byte(held) != STW_WIPER_ON + assert (held[6] >> 4) & 0x0F == 9 + assert held[7] == tc.stw_crc(held[:7]) + assert fake.sent == [] # live-MC replace, not _send +1 + finally: + monkeypatch.setattr(TeslaCANPreAP, "create_action_request", orig) + reset_auto_gates() + + +def test_int_on_still_uses_tipwipe_and_leaves_collar(monkeypatch): + from opendbc.can import CANPacker + from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + from opendbc.car.tesla.values import CANBUS, CruiseButtons + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + packer = CANPacker("tesla_preap") + tc = TeslaCANPreAP({CANBUS.party: packer, CANBUS.autopilot_party: packer}) + msg_stw = { + "MC_STW_ACTN_RQ": 5, + "CRC_STW_ACTN_RQ": 0, + "DTR_Dist_Rq": 255, + "VSL_Enbl_Rq": 1, + "WprSw6Posn": 2, + "WprWashSw_Psd": 0, + "HiBmLvr_Stat": 0, + } + stock = tc.create_action_request(CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + monkeypatch.setattr(body, "_param_int", lambda key, default=0: ( + WIPER_SETTING_INTERMITTENT if key == NAP_WIPER_SPEED else default + )) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_CREATE_ACTION_REQUEST", TeslaCANPreAP.create_action_request) + addr, dat, bus = body.create_action_request_with_overlay( + tc, CruiseButtons.IDLE, CANBUS.party, 6, msg_stw) + assert addr == STW_ACTN_RQ_ADDR == stock[0] + # Legacy Int coerces to Off: no TIPWIPE overlay, live collar left alone. + assert _byte(dat) != STW_WIPER_ON + assert stw_collar_posn(dat) == 2 + assert body.requested_auto_collar_posn(True) is None + + +def test_read_cereal_gear_never_subscribes(monkeypatch): + """Gear comes from the carState card just published, never a new subscriber.""" + import inspect + from pathlib import Path + from types import SimpleNamespace + + import cereal.messaging as messaging + + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + def _boom(*_args, **_kwargs): + raise AssertionError("carState subscriber created") + + monkeypatch.setattr(messaging, "SubMaster", _boom) + monkeypatch.setattr(messaging, "sub_sock", _boom) + body.reset_auto_gates() + try: + assert body._read_cereal_gear() == (None, "none") + body.note_published_car_state(SimpleNamespace(gearShifter="drive")) + assert body._read_cereal_gear() == ("drive", "cereal") + assert body.in_drive_gear() + body.reset_auto_gates() + assert body._read_cereal_gear() == (None, "none") + finally: + body.reset_auto_gates() + + src = inspect.getsource(body._read_cereal_gear) + assert "SubMaster" not in src + assert "sub_sock" not in src + card = Path(__file__).resolve().parents[2].joinpath("card.py").read_text() + assert "note_published_car_state(cs_send.carState)" in card + diff --git a/selfdrive/car/tesla/tests/test_preap_brake_signals.py b/selfdrive/car/tesla/tests/test_preap_brake_signals.py new file mode 100644 index 00000000000000..6d9a23952f6bee --- /dev/null +++ b/selfdrive/car/tesla/tests/test_preap_brake_signals.py @@ -0,0 +1,38 @@ +"""Pre-AP has no analog brake pressure on buses we already parse. + +Long drops on the car's digital Applied flags only. Do not invent a +travel/pressure threshold — we cannot half a boolean the car computed. +""" + +from pathlib import Path + +from opendbc import DBC_PATH + + +_PREAP_DBC = Path(DBC_PATH) / "tesla_preap.dbc" + + +def test_preap_brake_signals_are_digital_only(): + text = _PREAP_DBC.read_text() + + assert "SG_ DI_brakePedal :" in text + assert "SG_ DI_brakePedalState :" in text + assert "SG_ driverBrakeStatus :" in text + assert 'VAL_ 280 DI_brakePedal 1 "Applied" 0 "Not_applied"' in text + assert 'VAL_ 522 driverBrakeStatus 2 "APPLIED" 1 "NOT_APPLIED"' in text + assert 'VAL_ 264 DI_pedalPos 255 "SNA"' in text + + # Analog / iBooster signals exist on HW3 / Raven, not Pre-AP. + assert "IBST_" not in text + assert "ESP_brakeTorqueTarget" not in text + assert "IBST_sInputRodDriver" not in text + assert "ESP_pEstMax" not in text + + # BrakeMessage carries only the 2-bit driver apply enum. Remaining bytes + # are undefined; do not decode them as pressure or travel. + brake_msg = text.split("BO_ 522 BrakeMessage:", 1)[1].split("BO_", 1)[0] + assert "SG_ driverBrakeStatus" in brake_msg + assert brake_msg.count("SG_") == 1 + + # DI_pedalPos is accelerator, not brake travel. + assert "SG_ DI_pedalPos :" in text diff --git a/selfdrive/car/tesla/tests/test_preap_force_offroad_handoff.py b/selfdrive/car/tesla/tests/test_preap_force_offroad_handoff.py new file mode 100644 index 00000000000000..e88da0bee33378 --- /dev/null +++ b/selfdrive/car/tesla/tests/test_preap_force_offroad_handoff.py @@ -0,0 +1,369 @@ +"""Force Offroad stock-CC handoff + OP-long kill. Ordering matters.""" +from types import SimpleNamespace + +from openpilot.selfdrive.car.tesla.preap_force_offroad_handoff import ( + ARMING, + CANCELING, + CANCEL_DELAY_FRAMES, + CC_ENGAGE_TIMEOUT_FRAMES, + DROP_AND_SET, + ENABLED_WAIT_S, + HANDOFF_READY_PARAM, + HANDOFF_TIMEOUT_S, + IDLE, + PARAM, + READY, + SPOOF_RETRY_S, + STANDBY_WAIT_S, + WAIT_ENABLED, + ForceOffroadHandoff, + HandoffCommand, + StockCCKillOnLong, + apply_controller_flags, + di_enabled_ok, + di_is_holding, + di_needs_kill, + di_ready_to_set, + reset_handoff_for_tests, + software_long_active, +) + + +def _fsm(): + return ForceOffroadHandoff() + + +def test_di_helpers_and_long_gate(): + assert di_is_holding("ENABLED") + assert di_is_holding("STANDSTILL") + assert di_is_holding("OVERRIDE") + assert not di_is_holding("STANDBY") + assert not di_is_holding("OFF") + assert di_ready_to_set("STANDBY") + assert not di_ready_to_set("ENABLED") + assert di_enabled_ok("ENABLED") + assert di_enabled_ok("STANDSTILL") + assert di_needs_kill("STANDBY") + assert di_needs_kill("ENABLED") + assert not di_needs_kill("OFF") + assert software_long_active(True) + assert not software_long_active(False) + + +def test_unconfirmed_does_not_start_handoff(): + """Yes/No comes first. No cancel / drop / SET until confirmed.""" + h = _fsm() + cmd = h.update(force_offroad=True, enable_long=True, di_state="ENABLED", + now=0.0, confirmed=False) + assert cmd.state == IDLE + assert not cmd.ready + assert not cmd.cancel + assert not cmd.engage + assert not cmd.drop_long + assert not cmd.arm + + +def test_not_long_force_offroad_is_immediate_ready(): + """Lat-only / stock-CC / not engaged: today's Force Offroad (no invented handoff).""" + h = _fsm() + cmd = h.update(force_offroad=True, enable_long=False, di_state="OFF", now=0.0) + assert cmd.ready + assert not cmd.cancel + assert not cmd.engage + assert not cmd.drop_long + assert cmd.state == READY + + +def test_handoff_enabled_cancel_then_standby_then_drop_then_set(): + """Pedal-long + DI ENABLED: CANCEL while long still on, drop only at STANDBY, then SET.""" + h = _fsm() + cmd = h.update(force_offroad=True, enable_long=True, di_state="ENABLED", now=0.0) + assert cmd.state == CANCELING + assert cmd.cancel + assert not cmd.drop_long + assert not cmd.ready + assert not cmd.engage + + # Still ENABLED: do not drop long (stock CC still holding / about to drop). + cmd = h.update(force_offroad=True, enable_long=True, di_state="ENABLED", now=0.10) + assert cmd.state == CANCELING + assert not cmd.drop_long + assert not cmd.cancel # cooldown; first CANCEL is in-flight + + cmd = h.update(force_offroad=True, enable_long=True, di_state="STANDBY", now=0.20) + assert cmd.drop_long + assert cmd.engage + assert cmd.suppress_cancel + assert not cmd.cancel + assert cmd.state == WAIT_ENABLED + assert h.dropped_long + + cmd = h.update(force_offroad=True, enable_long=False, di_state="STANDBY", now=0.30) + assert cmd.suppress_cancel + assert not cmd.drop_long + assert not cmd.ready + + cmd = h.update(force_offroad=True, enable_long=False, di_state="ENABLED", now=0.40) + assert cmd.ready + assert cmd.state == READY + assert cmd.suppress_cancel + + +def test_handoff_already_standby_drops_and_sets_same_tick(): + h = _fsm() + cmd = h.update(force_offroad=True, enable_long=True, di_state="STANDBY", now=1.0) + assert cmd.drop_long + assert cmd.engage + assert cmd.suppress_cancel + assert not cmd.cancel + assert not cmd.ready + assert cmd.state == WAIT_ENABLED + + +def test_handoff_off_arms_then_sets(): + """Typical after engage-kill: DI is OFF. MAIN → STANDBY, then drop + SET.""" + h = _fsm() + cmd = h.update(force_offroad=True, enable_long=True, di_state="OFF", now=0.0) + assert cmd.state == ARMING + assert cmd.arm + assert not cmd.drop_long + assert not cmd.engage + + cmd = h.update(force_offroad=True, enable_long=True, di_state="STANDBY", now=0.20) + assert cmd.drop_long + assert cmd.engage + assert cmd.suppress_cancel + + cmd = h.update(force_offroad=True, enable_long=False, di_state="ENABLED", now=0.40) + assert cmd.ready + + +def test_handoff_off_main_goes_enabled_drops_without_set(): + """Some DIs SET on MAIN. Already holding → drop OP, no SET fight.""" + h = _fsm() + h.update(force_offroad=True, enable_long=True, di_state="OFF", now=0.0) + cmd = h.update(force_offroad=True, enable_long=True, di_state="ENABLED", now=0.20) + assert cmd.drop_long + assert not cmd.engage + assert cmd.ready + assert cmd.suppress_cancel + + +def test_handoff_does_not_drop_long_before_standby(): + h = _fsm() + for t in (0.0, 0.05, 0.10, 0.15): + cmd = h.update(force_offroad=True, enable_long=True, di_state="ENABLED", now=t) + assert not cmd.drop_long + assert not cmd.engage + assert not cmd.ready + assert cmd.state == CANCELING + + +def test_toggle_off_resets_and_resumes_kill(): + h = _fsm() + h.update(force_offroad=True, enable_long=True, di_state="ENABLED", now=0.0) + assert h.state == CANCELING + cmd = h.update(force_offroad=False, enable_long=True, di_state="ENABLED", now=0.1) + assert h.state == IDLE + assert not cmd.ready + assert cmd.cancel # kill-on-long resumes; they are fighting + + +def test_overall_timeout_writes_ready(): + h = _fsm() + h.update(force_offroad=True, enable_long=True, di_state="ENABLED", now=0.0) + cmd = h.update(force_offroad=True, enable_long=True, di_state="ENABLED", now=HANDOFF_TIMEOUT_S + 0.01) + assert cmd.ready + assert cmd.state == READY + + +def test_standby_phase_timeout_fallback(): + h = _fsm() + h.update(force_offroad=True, enable_long=True, di_state="OFF", now=0.0) + cmd = h.update(force_offroad=True, enable_long=True, di_state="OFF", now=STANDBY_WAIT_S + 0.01) + assert cmd.ready + + +def test_enabled_wait_timeout_fallback(): + h = _fsm() + h.update(force_offroad=True, enable_long=True, di_state="STANDBY", now=0.0) + cmd = h.update(force_offroad=True, enable_long=False, di_state="STANDBY", now=ENABLED_WAIT_S + 0.01) + assert cmd.ready + + +def test_timing_constants_cover_spoofer_budgets(): + assert CANCEL_DELAY_FRAMES == 10 + assert CC_ENGAGE_TIMEOUT_FRAMES == 50 + assert SPOOF_RETRY_S >= (CANCEL_DELAY_FRAMES + 10) / 100.0 + assert ENABLED_WAIT_S >= (CC_ENGAGE_TIMEOUT_FRAMES / 100.0) + assert HANDOFF_TIMEOUT_S > ENABLED_WAIT_S + STANDBY_WAIT_S + + +def test_kill_on_long_rising_enabled_then_standby(): + k = StockCCKillOnLong() + assert k.update(True, "ENABLED", 0.0) + assert not k.update(True, "ENABLED", 0.10) # cooldown + assert k.update(True, "STANDBY", 0.30) + assert not k.update(True, "OFF", 0.60) + assert not k.active + + +def test_kill_on_long_standby_at_engage(): + k = StockCCKillOnLong() + assert k.update(True, "STANDBY", 0.0) + assert not k.update(False, "STANDBY", 0.3) + + +def test_kill_inactive_when_not_long(): + k = StockCCKillOnLong() + assert not k.update(False, "ENABLED", 0.0) + + +def test_handoff_suppresses_kill_while_force_offroad(): + h = _fsm() + # Rising long would kill STANDBY; Force Offroad needs that STANDBY to SET. + cmd = h.update(force_offroad=True, enable_long=True, di_state="STANDBY", now=0.0) + assert not cmd.cancel + assert cmd.engage + + +def test_apply_controller_flags_cancel_does_not_beat_engage(): + cs = SimpleNamespace(preap_cc_cancel_needed=True, preap_cc_engage_needed=False, + preap_cc_arm_needed=False) + apply_controller_flags(cs, HandoffCommand(engage=True, suppress_cancel=True)) + assert cs.preap_cc_cancel_needed is False + assert cs.preap_cc_engage_needed is True + + +def test_drop_long_silent_keeps_cruise(): + from openpilot.selfdrive.car.tesla.preap_force_offroad_handoff import _drop_long_silent + eng = SimpleNamespace(enableLongControl=True, cruiseEnabled=True, enableJustCC=False) + inner = SimpleNamespace(engagement=eng, enableLongControl=True, cruiseEnabled=True, + enableJustCC=False) + _drop_long_silent(inner) + assert inner.enableLongControl is False + assert inner.cruiseEnabled is True + assert inner.enableJustCC is True + assert eng.enableLongControl is False + assert eng.enableJustCC is True + + +def test_update_hook_writes_ready_when_not_long(monkeypatch): + reset_handoff_for_tests() + written = {} + + class FakeParams: + def get_bool(self, key): + return key == PARAM + + def put_bool(self, key, val): + written[key] = bool(val) + + from openpilot.selfdrive.car.tesla import preap_force_offroad_handoff as mod + monkeypatch.setattr(mod, "_params", lambda: FakeParams()) + inner = SimpleNamespace( + enableLongControl=False, + di_cruise_state="OFF", + engagement=SimpleNamespace( + enableLongControl=False, cruiseEnabled=False, enableJustCC=False, + ), + ) + from openpilot.selfdrive.car.tesla.preap_force_offroad_handoff import update_force_offroad_handoff + cmd = update_force_offroad_handoff(inner, None, now=1.0, force_offroad=True, confirmed=True) + assert cmd.ready + assert written.get(HANDOFF_READY_PARAM) is True + reset_handoff_for_tests() + + +def test_update_hook_drops_long_only_after_standby(monkeypatch): + reset_handoff_for_tests() + written = {} + + class FakeParams: + def get_bool(self, key): + return False + + def put_bool(self, key, val): + written[key] = bool(val) + + from openpilot.selfdrive.car.tesla import preap_force_offroad_handoff as mod + monkeypatch.setattr(mod, "_params", lambda: FakeParams()) + from openpilot.selfdrive.car.tesla.preap_force_offroad_handoff import update_force_offroad_handoff + eng = SimpleNamespace(enableLongControl=True, cruiseEnabled=True, enableJustCC=False) + inner = SimpleNamespace( + enableLongControl=True, di_cruise_state="ENABLED", engagement=eng, + cruiseEnabled=True, enableJustCC=False, + ) + public = SimpleNamespace(enableLongControl=True) + cmd = update_force_offroad_handoff(inner, public, now=0.0, force_offroad=True, confirmed=True) + assert cmd.cancel + assert inner.enableLongControl is True + assert public.enableLongControl is True + assert written.get(HANDOFF_READY_PARAM) is not True + + inner.di_cruise_state = "STANDBY" + cmd = update_force_offroad_handoff(inner, public, now=0.2, force_offroad=True, confirmed=True) + assert cmd.drop_long + assert inner.enableLongControl is False + assert public.enableLongControl is False + assert eng.enableLongControl is False + reset_handoff_for_tests() + + +def test_card_and_hardwared_wire_handoff(): + from pathlib import Path + root = Path(__file__).resolve().parents[4] + card = (root / "selfdrive" / "car" / "card.py").read_text(encoding="utf-8") + hw = (root / "system" / "hardware" / "hardwared.py").read_text(encoding="utf-8") + assert "install_force_offroad_handoff" in card + assert "update_force_offroad_handoff(" in card + # Must run after CI.update (live DI + enableLongControl) and while onroad. + assert card.index("CS = self.CI.update") < card.index("update_force_offroad_handoff(") + assert "NAP_FORCE_OFFROAD_HANDOFF_READY_PARAM" in hw + assert "NAP_FORCE_OFFROAD_CONFIRMED_PARAM" in hw + assert "handoff_ready" in hw + assert hw.index("not_force_offroad") < hw.index("ign_edge =") + main = (root / "selfdrive" / "ui" / "layouts" / "main.py").read_text(encoding="utf-8") + confirm = (root / "selfdrive" / "ui" / "onroad" / "force_offroad_confirm.py").read_text(encoding="utf-8") + assert "maybe_show_force_offroad_confirm" in main + assert "CONFIRM_PROMPT" in confirm + assert "CONFIRM_YES" in confirm + assert "CONFIRM_NO" in confirm + assert "ForceOffroadConfirmDialog" in confirm + + +def test_stock_cc_arm_wrapper_sends_main_after_delay(): + import pytest + pytest.importorskip("capnp") + from unittest.mock import MagicMock + from openpilot.selfdrive.car.tesla.preap_force_offroad_handoff import ( + install_force_offroad_handoff, + ) + from opendbc.car.tesla.preap.stock_cc_spoofer import StockCCSpoofer + + install_force_offroad_handoff() + s = StockCCSpoofer() + can = MagicMock() + can.create_action_request.return_value = ("MAIN",) + cs = SimpleNamespace( + preap_cc_cancel_needed=False, + preap_cc_engage_needed=False, + preap_cc_arm_needed=True, + di_cruise_state="OFF", + msg_stw_actn_req={"MC_STW_ACTN_RQ": 3}, + ) + s.update(cs, 0, can, 2) + assert cs.preap_cc_arm_needed is False + assert getattr(s, "_nap_arm_pending", False) + # Before delay: no MAIN + for f in range(1, CANCEL_DELAY_FRAMES): + s.update(cs, f, can, 2) + assert can.create_action_request.call_count == 0 + # Delay + slot + for f in range(CANCEL_DELAY_FRAMES, CANCEL_DELAY_FRAMES + 15): + s.update(cs, f, can, 2) + assert can.create_action_request.call_count >= 1 + from opendbc.car.tesla.values import CruiseButtons + can.create_action_request.assert_called_with( + CruiseButtons.MAIN, 2, 4, cs.msg_stw_actn_req, + ) diff --git a/selfdrive/car/tesla/tests/test_preap_lat_yield.py b/selfdrive/car/tesla/tests/test_preap_lat_yield.py new file mode 100644 index 00000000000000..4abe33f2d5f3a0 --- /dev/null +++ b/selfdrive/car/tesla/tests/test_preap_lat_yield.py @@ -0,0 +1,284 @@ +"""Pre-AP lateral yield, openpilot side: A cancels, B never cancels. + +A steering yank / hands-on cancels OP only while OP is in full lateral +control (A). While lateral is yielded it is a driver maneuver and cancels +nothing (B); longitudinal stays engaged. "Yielded" is inferred from the +0x488 DAS_steeringControlType=1 history (opendbc preap/lat_yield.py, +mirrored by panda tesla_preap_latyield.h). + +These tests run the real CarController.apply, the real card CarState path and +the real CarSpecificEvents. CarController.apply needs cereal, so the two +CarController obligations (stamp the frames it sends; refuse type 1 while +blocked) are pinned here and mutation-tested in +.github/ci/tesla_preap_lat_yield_mutations.py. +""" +from cereal import car, log +from opendbc.can import CANPacker, CANParser +from opendbc.car import CanData +from opendbc.car.car_helpers import interfaces +from opendbc.car.tesla.preap import lat_yield as ly +from opendbc.car.tesla.preap.lat_yield import LatYieldTracker + +from openpilot.selfdrive.car.car_specific import CarSpecificEvents +from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import cs_hands_on_level + +EventName = log.OnroadEvent.EventName +STEER_ADDR = 0x488 + + +class Clock: + def __init__(self): + self.t = 100.0 + + def __call__(self): + return self.t + + def advance(self, dt): + self.t += dt + + +class Rig: + """Real Pre-AP interface (CarState + CarController) with a fake yield clock.""" + + def __init__(self): + install_blinker_lat_pause() + cp = interfaces["TESLA_MODEL_S_PREAP"].get_params( + "TESLA_MODEL_S_PREAP", {bus: {} for bus in range(8)}, [], + alpha_long=False, is_release=False, docs=False) + self.cp = cp + self.itf = interfaces["TESLA_MODEL_S_PREAP"](cp) + self.packer = CANPacker("tesla_preap") + self.parser = CANParser("tesla_preap", [("DAS_steeringControl", 50)], 0) + self.clk = Clock() + self.eng = self.itf.CS.engagement + self.eng.lat_yield = LatYieldTracker(clock=self.clk) + self.counter = 0 + self.events = CarSpecificEvents(cp) + self.prev = None + self.nanos = 0 + self.steer_types = [] + self.engage() + + def engage(self): + self.itf.update(self._can(0)) + self.eng.cruiseEnabled = True + self.eng.enableLongControl = True + self.itf.CS.cruiseEnabled = True + self.itf.CS.enableLongControl = True + self.itf.CS.enableJustCC = False + self.hands(0) # CS_prev for the hands-on edge + + def _can(self, hands, angle=0.0, torque=0.0): + self.counter += 1 + msgs = [] + for name, vals in (("DI_torque2", {"DI_gear": 4}), + ("EPAS_sysStatus", {"EPAS_handsOnLevel": hands, "EPAS_eacStatus": 1, + "EPAS_internalSAS": angle, + "EPAS_torsionBarTorque": torque, + "EPAS_sysStatusCounter": self.counter % 16})): + addr, dat, bus = self.packer.make_can_msg(name, 0, vals) + msgs.append(CanData(addr, dat, bus)) + return [(self.nanos, msgs)] + + def drive(self, seconds, lat_active): + """Run CarController.apply at 100 Hz; record 0x488 control types.""" + control = car.CarControl.new_message() + control.enabled = True + control.latActive = lat_active + control.longActive = True + control = control.as_reader() + for _ in range(int(round(seconds / 0.01))): + self.clk.advance(0.01) + self.nanos += 10_000_000 + _, sends = self.itf.apply(control, now_nanos=self.nanos) + for addr, dat, bus in sends: + if addr == STEER_ADDR: + self.parser.update([(self.nanos, [(addr, dat, bus)])]) + self.steer_types.append(int(self.parser.vl["DAS_steeringControl"]["DAS_steeringControlType"])) + + def hands(self, level, angle=0.0, torque=0.0): + """One CarState frame. angle/torque are CAN EPAS signals (CS negates both).""" + ret = self.itf.update(self._can(level, angle=angle, torque=torque)) + ev = self.events.update(ret, self.prev or ret, car.CarControl.new_message()) + self.prev = ret + return ret, ev + + +def test_carcontroller_stamps_the_type1_frames_it_sends(): + r = Rig() + r.drive(0.3, lat_active=True) + assert r.steer_types and set(r.steer_types) == {1} + assert r.eng.lat_yield.full_control() # the stamp is what makes this A + r.clk.advance(ly.RECENT_S + 0.05) + assert not r.eng.lat_yield.full_control() # and it expires without more frames + + +def test_carcontroller_type0_frames_do_not_stamp(): + r = Rig() + r.drive(0.3, lat_active=False) + assert r.steer_types and set(r.steer_types) == {0} + assert not r.eng.lat_yield.full_control() + + +def test_carcontroller_refuses_type1_while_blocked_and_resumes_after_release(): + r = Rig() + r.drive(0.2, lat_active=True) + r.eng.lat_yield.block() + r.steer_types.clear() + r.drive(0.2, lat_active=True) + assert r.steer_types and set(r.steer_types) == {0} + assert not r.eng.lat_yield.full_control() + # hands released long enough: block clears, type 1 returns (and a re-arm + # grace runs, since the stream resumed after a lapse) + r.eng.lat_yield.update_block(False) + r.clk.advance(ly.BLOCK_CLEAR_S + 0.01) + r.eng.lat_yield.update_block(False) + assert not r.eng.lat_yield.blocked + r.steer_types.clear() + r.drive(0.2, lat_active=True) + assert 1 in r.steer_types + + +def test_A_yank_on_full_lateral_cancels_everything(): + r = Rig() + r.drive(0.3, lat_active=True) + ret, ev = r.hands(2) + assert ret.steeringDisengage + assert not r.eng.cruiseEnabled and not r.eng.enableLongControl + assert cs_hands_on_level(ret) == 2 + assert ly.stash_full_control(ret.steeringTorqueEps) + assert EventName.steerDisengage in ev.names + assert EventName.pcmDisable in ev.names + + +def test_B_yank_on_yielded_lateral_cancels_nothing_and_keeps_long(): + r = Rig() + r.drive(0.2, lat_active=True) + r.drive(0.4, lat_active=False) # driver handoff / blinker turn / ... + ret, ev = r.hands(2) + assert ret.steeringDisengage + assert r.eng.cruiseEnabled and r.eng.enableLongControl + assert cs_hands_on_level(ret) == 2 # hands level survives the stash + assert not ly.stash_full_control(ret.steeringTorqueEps) + assert EventName.steerDisengage not in ev.names + assert EventName.pcmDisable not in ev.names + assert r.eng.lat_yield.blocked + # lateral stays refused until the hands come off, longitudinal untouched + r.steer_types.clear() + r.drive(0.2, lat_active=True) + assert set(r.steer_types) == {0} + assert r.eng.cruiseEnabled and r.eng.enableLongControl + + +def test_B_after_blend_grace_is_still_B_and_A_returns_after_grace(): + r = Rig() + r.drive(0.2, lat_active=True) + r.drive(0.4, lat_active=False) + r.drive(0.5, lat_active=True) # mid take-back blend: type 1 flows + ret, ev = r.hands(2) + assert r.eng.cruiseEnabled and EventName.steerDisengage not in ev.names + r2 = Rig() + r2.drive(0.2, lat_active=True) + r2.drive(0.4, lat_active=False) + r2.drive(ly.GRACE_S + 0.2, lat_active=True) # blend done, OP steering again + ret, ev = r2.hands(2) + assert not r2.eng.cruiseEnabled + assert EventName.steerDisengage in ev.names + + +def test_stash_decodes_hands_level_for_every_level_and_state(): + for hands in range(4): + for full in (True, False): + v = ly.encode_hands_stash(hands, full) + assert ly.stash_full_control(v) is full + assert int(round(v)) == hands + + +def test_same_direction_push_yields_without_disengage(): + """One frame, hands 0→3, torque helping the command. No 80 ms counter.""" + r = Rig() + r.drive(0.3, lat_active=True) + assert r.eng.lat_yield.full_control() + r.eng._nap_cmd_angle_deg = -40.0 + ret, ev = r.hands(3, angle=30.0, torque=3.5) # CS angle -30, CS torque -3.5 + assert ret.steeringDisengage + assert r.eng.cruiseEnabled and r.eng.enableLongControl + assert not ly.stash_full_control(ret.steeringTorqueEps) + assert EventName.steerDisengage not in ev.names + assert EventName.pcmDisable not in ev.names + assert r.eng.lat_yield.blocked + + +def test_opposite_yank_at_full_lateral_disengages(): + r = Rig() + r.drive(0.3, lat_active=True) + r.eng._nap_cmd_angle_deg = -40.0 + _ret, ev = r.hands(3, angle=30.0, torque=-3.5) # CS torque +3.5, against a right command + assert not r.eng.cruiseEnabled and not r.eng.enableLongControl + assert EventName.steerDisengage in ev.names + + +def test_roundabout_any_input_yields(): + r = Rig() + r.drive(0.3, lat_active=True) + r.eng._nap_cmd_angle_deg = -40.0 + r.eng._nap_roundabout_yield = True + _ret, ev = r.hands(2, angle=30.0, torque=-3.5) # opposite yank, still a yield + assert r.eng.cruiseEnabled and r.eng.enableLongControl + assert EventName.steerDisengage not in ev.names + assert r.eng.lat_yield.blocked + + +def test_undertrack_same_side_as_the_wheel_yields_when_the_command_lags(): + r = Rig() + r.drive(0.3, lat_active=True) + r.eng._nap_cmd_angle_deg = -30.0 # lags the wheel + r.eng._nap_undertrack = True + _ret, ev = r.hands(3, angle=40.0, torque=3.5) # CS wheel -40, CS torque -3.5 + assert r.eng.cruiseEnabled + assert EventName.steerDisengage not in ev.names + + +def test_farm_trace_ends_yielded_and_the_opposite_yank_does_not(): + # 14:32:18-19 samples, one frame each. Hands 0 until the final yank. + torques = [0.70, -0.95, 0.47, -2.19, 0.86, -1.79, 0.15, -1.00, -3.29, -3.77] + r = Rig() + r.drive(0.3, lat_active=True) + r.eng._nap_undertrack = True + ev = None + for i, tq in enumerate(torques): + meas = -26.0 + (-44.0 + 26.0) * i / (len(torques) - 1) + r.eng._nap_cmd_angle_deg = meas + 8.0 + hands = 3 if i == len(torques) - 1 else 0 + _ret, ev = r.hands(hands, angle=-meas, torque=-tq) + assert r.eng.cruiseEnabled, tq + assert ev is not None and EventName.steerDisengage not in ev.names + assert r.eng.lat_yield.blocked + + r2 = Rig() + r2.drive(0.3, lat_active=True) + r2.eng._nap_cmd_angle_deg = -50.0 + r2.eng._nap_undertrack = True + _ret, ev = r2.hands(3, angle=40.0, torque=-3.77) # positive CS torque, right command + assert not r2.eng.cruiseEnabled + assert EventName.steerDisengage in ev.names + + +def test_card_handoff_forwards_steering_pressed_to_the_early_yield(): + from pathlib import Path + + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import _handoff_for, update_card_lat_handoff + from openpilot.selfdrive.controls.lib.driver_lateral_handoff import EARLY_YIELD_FRAMES + + # 1.4 Nm / 80 ms yields without steeringPressed, so a 3 Nm push still + # yields if this kwarg is dropped. The forward itself is the contract. + card = Path(__file__).resolve().parents[4] / "selfdrive/car/tesla/preap_blinker_lat_pause.py" + assert " steering_pressed=steering_pressed,\n dt=dt,\n" in card.read_text() + eng = Rig().eng + for _ in range(EARLY_YIELD_FRAMES): + update_card_lat_handoff( + eng, engaged=True, lat_would_be_active=True, steering_torque=3.0, steering_rate_deg=0.0, + hands_on_level=0, brake_applied=False, a_ego=0.0, v_ego=20.0, + steering_pressed=True, param_on=True) + assert _handoff_for(eng)._yielded diff --git a/selfdrive/car/tesla/tests/test_preap_sticky_max.py b/selfdrive/car/tesla/tests/test_preap_sticky_max.py new file mode 100644 index 00000000000000..861ed8e83cd01d --- /dev/null +++ b/selfdrive/car/tesla/tests/test_preap_sticky_max.py @@ -0,0 +1,819 @@ +"""Pre-AP sticky MAX: brake long pause, one SET vs double SET. + +Pedal mode. Soft lateral handoff (#71) and speedsignd are not this path. +""" + +from pathlib import Path + +from openpilot.common.constants import CV +from opendbc.car.tesla.preap.engagement import PreAPEngagement +from opendbc.car.tesla.values import CruiseButtons + +from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import LAMP_OFF_DEBOUNCE_S +from openpilot.selfdrive.mapd.constants import MODE_FOLLOW, MODE_OFF +from openpilot.selfdrive.mapd.map_speed_policy import MapCruiseHold, decide_map_cruise +from openpilot.selfdrive.selfdrived.preap_regen import PreAPChimeState, update_preap_chimes + + +def _engaged(*, double_pull=True, pedal_kph=55.0 * CV.MPH_TO_KPH): + eng = PreAPEngagement(double_pull_enabled=double_pull, double_pull_window_ms=750) + eng.cruiseEnabled = True + eng.enableLongControl = True + eng.enableJustCC = False + eng.pedal_speed_kph = float(pedal_kph) + return eng + + +def _buttons(eng, *, cruise_buttons=0, prev=0, t_ms=1000, brake=False, v_ego=13.4): + return eng.process_buttons( + cruise_buttons=cruise_buttons, prev_cruise_buttons=prev, + curr_time_ms=t_ms, v_ego=v_ego, speed_units="MPH", + use_pedal=True, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=brake) + + +def _end_turn_latch(eng, *, pressed=False): + eng._nap_left_blinker = False + eng._nap_right_blinker = False + eng._nap_steering_pressed = pressed + eng._nap_lat_hold.update(False, False, pressed, engaged=True, dt=LAMP_OFF_DEBOUNCE_S) + eng.handle_steering_disengage(False) + + +def test_brake_pause_keeps_held_max_and_session(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert getattr(eng, "_nap_long_resume_pending", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + assert abs(eng._nap_held_max_kph - held) < 1e-6 + + +def test_one_set_at_standstill_does_not_take_long(): + """Stop + SET alone must not creep. Held MAX stays for a later gas touch.""" + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000, v_ego=0.0) + _buttons(eng, brake=False, t_ms=3000, v_ego=0.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=0.0) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert getattr(eng, "_nap_long_resume_pending", False) + assert getattr(eng, "_nap_resume_wait_gas", False) + assert not getattr(eng, "_nap_set_resume_long", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + assert abs(eng._nap_held_max_kph - held) < 1e-6 + + +def test_one_set_at_standstill_then_gas_resumes_held_max(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000, v_ego=0.0) + _buttons(eng, brake=False, t_ms=3000, v_ego=0.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=0.0) + assert not eng.enableLongControl + eng._nap_gas_pressed = True + _buttons(eng, t_ms=4100, v_ego=0.0) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert getattr(eng, "_nap_set_resume_long", False) + assert not getattr(eng, "_nap_set_take_speed_now", False) + assert not getattr(eng, "_nap_resume_wait_gas", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + assert abs(eng._nap_held_max_kph - held) < 1e-6 + + +def test_one_set_while_rolling_resumes_without_gas(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000, v_ego=8.0) + _buttons(eng, brake=False, t_ms=3000, v_ego=8.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=8.0) + assert eng.enableLongControl + assert getattr(eng, "_nap_set_resume_long", False) + assert not getattr(eng, "_nap_resume_wait_gas", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + + +def test_standstill_set_with_gas_already_down_resumes(): + """SET and throttle on the same frame may take long.""" + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000, v_ego=0.0) + _buttons(eng, brake=False, t_ms=3000, v_ego=0.0) + eng._nap_gas_pressed = True + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=0.0) + assert eng.enableLongControl + assert getattr(eng, "_nap_set_resume_long", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + + +def test_double_set_at_standstill_still_takes_speed_now(): + """Second SET in the window at a stop is still forget-sticky / take now.""" + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000, v_ego=0.0) + _buttons(eng, brake=False, t_ms=3000, v_ego=0.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=0.0) + assert getattr(eng, "_nap_resume_wait_gas", False) + assert not eng.enableLongControl + _buttons(eng, t_ms=4050, v_ego=0.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4300, v_ego=0.0) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert getattr(eng, "_nap_set_take_speed_now", False) + assert not getattr(eng, "_nap_resume_wait_gas", False) + assert getattr(eng, "_nap_held_max_kph", None) is None + + +def test_hard_cancel_clears_standstill_resume_wait(): + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import hard_cancel_session + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, brake=True, t_ms=2000, v_ego=0.0) + _buttons(eng, brake=False, t_ms=3000, v_ego=0.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=0.0) + assert getattr(eng, "_nap_resume_wait_gas", False) + hard_cancel_session(eng) + assert not getattr(eng, "_nap_resume_wait_gas", False) + assert getattr(eng, "_nap_held_max_kph", None) is None + + +def test_one_set_after_brake_resumes_long_keeps_held_max(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000) + _buttons(eng, brake=False, t_ms=3000, v_ego=13.4) # ~30 mph + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=13.4) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert getattr(eng, "_nap_set_resume_long", False) + assert not getattr(eng, "_nap_set_take_speed_now", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + + +def test_double_set_after_brake_forgets_held_and_takes_speed_now(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000) + _buttons(eng, brake=False, t_ms=3000, v_ego=18.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=18.0) + assert getattr(eng, "_nap_set_resume_long", False) + _buttons(eng, t_ms=4050, v_ego=18.0) # release + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4300, v_ego=18.0) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert getattr(eng, "_nap_set_take_speed_now", False) + assert not getattr(eng, "_nap_set_resume_long", False) + + +def test_set_while_long_on_does_not_drop_long(): + """In-session first SET arms double-SET; it must not first-pull drop long.""" + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=2000) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not getattr(eng, "_nap_set_take_speed_now", False) + assert not getattr(eng, "_nap_set_resume_long", False) + + +def test_blinker_turn_keeps_held_max_and_long(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + assert eng.enableLongControl + assert eng.cruiseEnabled + assert abs(eng.pedal_speed_kph - held) < 1e-6 + assert not getattr(eng, "_nap_long_resume_pending", False) + _end_turn_latch(eng, pressed=True) + assert eng.enableLongControl + assert abs(eng.pedal_speed_kph - held) < 1e-6 + assert eng._nap_lat_hold.holding + + +def test_tip_alc_does_not_use_long_pause_path(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + eng._nap_left_blinker = True + eng._nap_alc_active = True + eng.handle_steering_disengage(False) + assert eng.enableLongControl + assert not getattr(eng, "_nap_long_resume_pending", False) + assert not getattr(eng, "_nap_set_resume_long", False) + + +def test_initial_double_pull_engage_is_take_speed_now(): + """One rolling pull from off is lat+long take-speed-now. A quick second pull repeats it.""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000, v_ego=24.6) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert getattr(eng, "_nap_set_take_speed_now", False) + assert not getattr(eng, "_nap_set_resume_long", False) + assert eng.stalk_pull_time_ms == 1000 + _buttons(eng, t_ms=1050, v_ego=24.6) + assert eng.enableLongControl + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1400, v_ego=24.6) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert getattr(eng, "_nap_set_take_speed_now", False) + assert not getattr(eng, "_nap_set_resume_long", False) + + +def test_set_while_di_gas_held_from_disengaged_arms_long(): + """Single SET while accelerating: arm long (do not leave lat-only regen).""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + eng._nap_di_pedal_pos = 20.0 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000, v_ego=8.0) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not getattr(eng, "_one_pedal_pause_latched", False) + assert getattr(eng, "_nap_set_take_speed_now", False) + assert not getattr(eng, "_nap_set_resume_long", False) + assert eng.stalk_pull_time_ms == 1000 + assert eng.enableDoublePull + + +def test_set_without_di_gas_from_disengaged_engages_long(): + """Foot off engages lat+long. Interceptor-only sticky is not a gas press.""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + eng._nap_di_pedal_pos = 0.0 + eng._nap_gas_pressed = True + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000, v_ego=8.0) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert getattr(eng, "_nap_set_take_speed_now", False) + assert eng.stalk_pull_time_ms == 1000 + + +def test_single_pull_rolling_seeds_posted_or_traveled(): + """Same MAX as the old double pull: posted + offset if known, else traveled.""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + v_ego = 24.6 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000, v_ego=v_ego) + assert eng.cruiseEnabled and eng.enableLongControl + assert eng.longCtrlEvent == "pccEnabled" + assert eng.enableJustCC is False + prev = PreAPChimeState() + chimes, prev = _chime_for(eng, prev) + assert chimes.lat_engage and chimes.long_engage + assert not prev.long_paused + posted = 65 * CV.MPH_TO_KPH + traveled = v_ego * CV.MS_TO_KPH + hold = MapCruiseHold() + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=eng.pedal_speed_kph, + posted_kph=posted, engage_rising=True, now=0.0, take_speed_now=True, + traveled_kph=traveled, long_active=True, + ) + assert abs(dec.seed_kph - posted) < 1e-6 + hold_off = MapCruiseHold() + dec_off = decide_map_cruise( + hold_off, engaged=True, mode=MODE_OFF, raw_kph=eng.pedal_speed_kph, + posted_kph=None, engage_rising=True, now=0.0, take_speed_now=True, + traveled_kph=traveled, long_active=True, + ) + assert abs(dec_off.seed_kph - traveled) < 1e-6 + # Release is silent: one engage, not a second chime. + _buttons(eng, prev=CruiseButtons.MAIN, t_ms=1100, v_ego=v_ego) + chimes, _ = _chime_for(eng, prev) + assert not chimes.lat_engage and not chimes.long_engage + cc = (Path(__file__).resolve().parents[4] / + "opendbc_repo/opendbc/car/tesla/preap/carcontroller.py").read_text() + assert "requested_long_rising or pedal_long_falling or pedal_button_press" in cc + + +def test_quick_second_pull_reapplies_take_speed_now(): + """Second pull inside the window stays lat+long and seeds the same MAX.""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + v_ego = 20.0 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=5000, v_ego=v_ego) + assert eng.enableLongControl + first_speed = eng.pedal_speed_kph + _buttons(eng, prev=CruiseButtons.MAIN, t_ms=5100, v_ego=v_ego) + assert eng.enableLongControl + assert eng.pedal_speed_kph == first_speed + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=5300, v_ego=v_ego) + assert eng.cruiseEnabled and eng.enableLongControl + assert not eng.pending_enable + assert eng._nap_set_take_speed_now + assert not eng._nap_set_resume_long + assert eng.pedal_speed_kph == first_speed + assert eng.stalk_pull_time_ms == 5300 + posted = 55 * CV.MPH_TO_KPH + traveled = v_ego * CV.MS_TO_KPH + first = decide_map_cruise( + MapCruiseHold(), engaged=True, mode=MODE_FOLLOW, raw_kph=first_speed, + posted_kph=posted, engage_rising=True, now=0.0, take_speed_now=True, + traveled_kph=traveled, long_active=True, + ) + second = decide_map_cruise( + MapCruiseHold(), engaged=True, mode=MODE_FOLLOW, raw_kph=eng.pedal_speed_kph, + posted_kph=posted, engage_rising=False, now=1.0, take_speed_now=True, + traveled_kph=traveled, long_active=True, + ) + assert abs(first.seed_kph - posted) < 1e-6 + assert abs(second.seed_kph - first.seed_kph) < 1e-6 + + +def test_standstill_single_pull_waits_for_di_gas_then_take_now(): + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000, v_ego=0.0) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert eng._nap_resume_wait_gas + assert eng._nap_from_off_stop_take_now + assert not eng._nap_set_take_speed_now + # Interceptor rest noise is not a gas tap. + eng._nap_gas_pressed = True + eng._nap_di_pedal_pos = 0.5 + _buttons(eng, t_ms=1100, v_ego=0.0) + assert not eng.enableLongControl + assert eng._nap_resume_wait_gas + # A quick second pull must not start rolling. + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1300, v_ego=0.0) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert eng._nap_resume_wait_gas + assert eng._nap_from_off_stop_take_now + # DI > 2 starts long at take-speed-now MAX. + eng._nap_di_pedal_pos = 8.0 + _buttons(eng, t_ms=1500, v_ego=0.0) + assert eng.enableLongControl + assert eng._nap_set_take_speed_now + assert not eng._nap_set_resume_long + assert not eng._nap_resume_wait_gas + posted = 35 * CV.MPH_TO_KPH + dec = decide_map_cruise( + MapCruiseHold(), engaged=True, mode=MODE_FOLLOW, raw_kph=0.0, + posted_kph=posted, engage_rising=True, now=0.0, take_speed_now=True, + traveled_kph=0.0, long_active=True, + ) + assert abs(dec.seed_kph - posted) < 1e-6 + dec_off = decide_map_cruise( + MapCruiseHold(), engaged=True, mode=MODE_OFF, raw_kph=0.0, + posted_kph=None, engage_rising=True, now=0.0, take_speed_now=True, + traveled_kph=0.0, long_active=True, + ) + assert abs(dec_off.seed_kph - 0.0) < 1e-6 + + +def test_brake_held_single_pull_stays_lat_only(): + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000, brake=True, v_ego=15.0) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert not eng._nap_set_take_speed_now + assert not eng._nap_resume_wait_gas + _buttons(eng, prev=CruiseButtons.MAIN, t_ms=1100, brake=True, v_ego=15.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1300, brake=True, v_ego=15.0) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert not eng._nap_set_take_speed_now + + +def test_no_pedal_single_pull_stays_double_pull(): + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + eng.process_buttons( + cruise_buttons=CruiseButtons.MAIN, prev_cruise_buttons=0, + curr_time_ms=1000, v_ego=15.0, speed_units="MPH", + use_pedal=False, pedal_long_allowed=False, + long_control_allowed=True, real_brake_pressed=False) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert eng.preap_cc_cancel_needed + assert not eng._nap_set_take_speed_now + eng.process_buttons( + cruise_buttons=0, prev_cruise_buttons=CruiseButtons.MAIN, + curr_time_ms=1100, v_ego=15.0, speed_units="MPH", + use_pedal=False, pedal_long_allowed=False, + long_control_allowed=True, real_brake_pressed=False) + eng.process_buttons( + cruise_buttons=CruiseButtons.MAIN, prev_cruise_buttons=0, + curr_time_ms=1300, v_ego=15.0, speed_units="MPH", + use_pedal=False, pedal_long_allowed=False, + long_control_allowed=True, real_brake_pressed=False, + di_cruise_state="STANDBY") + assert eng.cruiseEnabled + assert eng.preap_cc_engage_needed + + +def test_cancel_full_disengage_clears_held_max(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, cruise_buttons=CruiseButtons.CANCEL, t_ms=2000) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + assert not getattr(eng, "_nap_long_resume_pending", False) + assert getattr(eng, "_nap_held_max_kph", None) is None + assert eng.pedal_speed_kph == 0.0 + + +def test_steering_disengage_full_teardown_clears_held_max(): + install_blinker_lat_pause() + eng = _engaged() + eng.handle_steering_disengage(True) + assert not eng.cruiseEnabled + assert getattr(eng, "_nap_held_max_kph", None) is None + + +def _overlay(hold, eng, *, posted, mode=MODE_FOLLOW, traveled_kph=None, long_active=None): + if long_active is None: + long_active = bool(eng.enableLongControl) + resume = bool(getattr(eng, "_nap_set_resume_long", False)) + take = bool(getattr(eng, "_nap_set_take_speed_now", False)) + raw = float(eng.pedal_speed_kph) + if not long_active and hold.held_max_kph is not None: + raw = float(hold.held_max_kph) + return decide_map_cruise( + hold, engaged=bool(eng.cruiseEnabled), mode=mode, raw_kph=raw, + posted_kph=posted, engage_rising=False, now=0.0, + take_speed_now=take, resume_held=resume, + traveled_kph=traveled_kph, long_active=long_active, + ) + + +def test_fsm_plus_policy_brake_keeps_sticky_55_in_65(): + install_blinker_lat_pause() + posted = 65 * CV.MPH_TO_KPH + sticky = 55 * CV.MPH_TO_KPH + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=True, now=0.0, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + eng = _engaged(pedal_kph=sticky) + _buttons(eng, brake=True, t_ms=2000, v_ego=13.4) + dec = _overlay(hold, eng, posted=posted, traveled_kph=30 * CV.MPH_TO_KPH) + assert dec.sticky + assert abs(dec.driver_kph - sticky) < 1e-6 + _buttons(eng, brake=False, t_ms=3000, v_ego=13.4) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=13.4) + dec = _overlay(hold, eng, posted=posted, traveled_kph=30 * CV.MPH_TO_KPH) + assert dec.sticky + assert dec.seed_kph is not None + assert abs(dec.seed_kph - sticky) < 1e-6 + + +def test_fsm_plus_policy_no_map_double_set_uses_current_speed(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + now_speed = 42 * CV.MPH_TO_KPH + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=held, + ) + eng = _engaged(pedal_kph=held) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=2000, v_ego=now_speed * CV.KPH_TO_MS) + _buttons(eng, t_ms=2050, v_ego=now_speed * CV.KPH_TO_MS) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=2300, v_ego=now_speed * CV.KPH_TO_MS) + dec = _overlay(hold, eng, posted=None, mode=MODE_OFF, traveled_kph=now_speed) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - now_speed) < 1e-6 + + +def test_fsm_plus_policy_mode_off_gravel_one_set_keeps_19(): + """Maps off, held 19, brake (ego 12), one SET then delayed engage_rising.""" + install_blinker_lat_pause() + held = 19 * CV.MPH_TO_KPH + ego = 12 * CV.MPH_TO_KPH + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=held, + ) + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000, v_ego=ego * CV.KPH_TO_MS) + dec = _overlay(hold, eng, posted=None, mode=MODE_OFF, traveled_kph=ego) + assert abs(dec.driver_kph - held) < 1e-6 + assert abs(hold.held_max_kph - held) < 1e-6 + _buttons(eng, brake=False, t_ms=3000, v_ego=ego * CV.KPH_TO_MS) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=ego * CV.KPH_TO_MS) + assert getattr(eng, "_nap_set_resume_long", False) + assert not getattr(eng, "_nap_set_take_speed_now", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + # SET frame: resume_held, pedalLongActive not up yet (engage_rising False). + dec = _overlay(hold, eng, posted=None, mode=MODE_OFF, traveled_kph=ego) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - held) < 1e-6 + # Next card cycle: resume flag consumed, pedal authority rising. + eng._nap_set_resume_long = False + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=5.0, resume_held=False, long_active=True, + traveled_kph=ego, + ) + assert abs(hold.held_max_kph - held) < 1e-6 + assert abs(dec.driver_kph - held) < 1e-6 + if dec.seed_kph is not None: + assert abs(dec.seed_kph - held) < 1e-6 + + +def test_fsm_plus_policy_mode_off_stalk_then_resume_adjusted(): + install_blinker_lat_pause() + start = 24 * CV.MPH_TO_KPH + adjusted = 19 * CV.MPH_TO_KPH + ego = 12 * CV.MPH_TO_KPH + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=start, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=start, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=start, posted_kph=None, + engage_rising=False, now=1.0, long_active=True, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=adjusted, posted_kph=None, + engage_rising=False, now=2.0, long_active=True, + ) + assert abs(hold.held_max_kph - adjusted) < 1e-6 + eng = _engaged(pedal_kph=adjusted) + _buttons(eng, brake=True, t_ms=2000, v_ego=ego * CV.KPH_TO_MS) + _buttons(eng, brake=False, t_ms=3000, v_ego=ego * CV.KPH_TO_MS) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=ego * CV.KPH_TO_MS) + dec = _overlay(hold, eng, posted=None, mode=MODE_OFF, traveled_kph=ego) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - adjusted) < 1e-6 + + +def test_fsm_plus_policy_mode_off_double_set_after_pause_takes_traveled(): + install_blinker_lat_pause() + held = 19 * CV.MPH_TO_KPH + ego = 12 * CV.MPH_TO_KPH + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=held, + ) + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000, v_ego=ego * CV.KPH_TO_MS) + _buttons(eng, brake=False, t_ms=3000, v_ego=ego * CV.KPH_TO_MS) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=ego * CV.KPH_TO_MS) + _buttons(eng, t_ms=4050, v_ego=ego * CV.KPH_TO_MS) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4300, v_ego=ego * CV.KPH_TO_MS) + dec = _overlay(hold, eng, posted=None, mode=MODE_OFF, traveled_kph=ego) + assert getattr(eng, "_nap_set_take_speed_now", False) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - ego) < 1e-6 + + +def test_fsm_plus_policy_maps_double_set_uses_posted(): + install_blinker_lat_pause() + posted = 65 * CV.MPH_TO_KPH + sticky = 55 * CV.MPH_TO_KPH + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=True, now=0.0, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + eng = _engaged(pedal_kph=sticky) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=2000) + _buttons(eng, t_ms=2050) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=2300) + dec = _overlay(hold, eng, posted=posted, traveled_kph=40 * CV.MPH_TO_KPH) + assert not dec.sticky + assert abs(dec.seed_kph - posted) < 1e-6 + + +def _chime_for(eng, prev): + return update_preap_chimes( + lat_engaged=bool(eng.cruiseEnabled), + long_engaged=bool(eng.enableLongControl), + prev=prev, + ) + + +def test_brake_pause_does_not_chime_disengage_or_resume_fanfare(): + install_blinker_lat_pause() + eng = _engaged() + prev = PreAPChimeState(lat_engaged=True, long_engaged=True) + _buttons(eng, brake=True, t_ms=2000) + chimes, prev = _chime_for(eng, prev) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert not chimes.long_disengage + assert not chimes.long_engage + assert prev.long_paused + + _buttons(eng, brake=False, t_ms=3000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000) + chimes, prev = _chime_for(eng, prev) + assert eng.enableLongControl + assert getattr(eng, "_nap_set_resume_long", False) + assert not chimes.long_engage + assert not chimes.long_disengage + assert not prev.long_paused + + +def test_blinker_turn_does_not_chime_or_pause_long(): + install_blinker_lat_pause() + eng = _engaged() + prev = PreAPChimeState(lat_engaged=True, long_engaged=True) + eng._nap_left_blinker = True + eng.handle_steering_disengage(False) + chimes, prev = _chime_for(eng, prev) + assert eng.cruiseEnabled + assert eng.enableLongControl + assert not chimes.long_disengage + assert not prev.long_paused + + +def test_cancel_after_engaged_still_chimes_long_disengage(): + install_blinker_lat_pause() + eng = _engaged() + prev = PreAPChimeState(lat_engaged=True, long_engaged=True) + _buttons(eng, cruise_buttons=CruiseButtons.CANCEL, t_ms=2000) + chimes, _ = _chime_for(eng, prev) + assert not eng.cruiseEnabled + assert not eng.enableLongControl + assert chimes.long_disengage + assert chimes.lat_disengage + + +def test_handoff_module_does_not_drop_long(): + """#71 soft lat handoff must not share the brake long-pause path.""" + from pathlib import Path + src = (Path(__file__).resolve().parents[4] / "selfdrive/controls/lib/driver_lateral_handoff.py").read_text() + assert "_drop_longitudinal_keep_lateral" not in src + assert "_nap_long_resume_pending" not in src + assert "_nap_set_resume_long" not in src + assert "emergency_cancel" in src + pause = (Path(__file__).resolve().parents[4] / + "selfdrive/car/tesla/preap_blinker_lat_pause.py").read_text() + assert "hard_cancel_session" in pause + assert "_drop_longitudinal_keep_lateral" in pause + assert "RESUME_STANDSTILL_V_EGO" in pause + assert "_nap_resume_wait_gas" in pause + + +def test_one_pedal_gas_kick_keeps_held_max_and_session(): + """Gas-from-rest is the same silent pause as brake (sticky MAX + one SET).""" + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + assert not eng.maybe_one_pedal_gas_kick(False, True) + assert eng.maybe_one_pedal_gas_kick(True, True) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert not getattr(eng, "preap_cc_cancel_needed", False) + assert getattr(eng, "_nap_long_resume_pending", False) + assert getattr(eng, "_one_pedal_pause_latched", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + assert abs(eng._nap_held_max_kph - held) < 1e-6 + + +def test_one_pedal_gas_pause_matches_brake_one_set_resume(): + """One SET after gas pause restores held MAX the same way brake pause does.""" + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + gas = _engaged(pedal_kph=held) + brake = _engaged(pedal_kph=held) + assert not gas.maybe_one_pedal_gas_kick(False, True) + gas.maybe_one_pedal_gas_kick(True, True) + gas.maybe_one_pedal_gas_kick(False, True) + _buttons(brake, brake=True, t_ms=2000) + _buttons(brake, brake=False, t_ms=3000) + assert gas.cruiseEnabled and brake.cruiseEnabled + assert not gas.enableLongControl and not brake.enableLongControl + assert getattr(gas, "_nap_long_resume_pending", False) + assert getattr(brake, "_nap_long_resume_pending", False) + assert getattr(gas, "_one_pedal_pause_latched", False) + assert not getattr(brake, "_one_pedal_pause_latched", False) + _buttons(gas, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=13.4) + _buttons(brake, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=13.4) + assert gas.enableLongControl and brake.enableLongControl + assert not getattr(gas, "_one_pedal_pause_latched", False) + assert getattr(gas, "_nap_set_resume_long", False) + assert getattr(brake, "_nap_set_resume_long", False) + assert abs(gas.pedal_speed_kph - held) < 1e-6 + assert abs(brake.pedal_speed_kph - held) < 1e-6 + + +def test_one_pedal_gas_kick_one_set_resumes_held_max(): + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + assert not eng.maybe_one_pedal_gas_kick(False, True) + eng.maybe_one_pedal_gas_kick(True, True) + eng.maybe_one_pedal_gas_kick(False, True) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=13.4) + assert eng.enableLongControl + assert not getattr(eng, "_one_pedal_pause_latched", False) + assert getattr(eng, "_nap_set_resume_long", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + + +def test_one_pedal_set_while_gas_held_clears_latch_and_resumes(): + """After gas pause, one SET with the foot still down restores long. + + Must not fall through to double-pull first-pull (lat-only). Lift then + starts A+B; lift alone before SET must not have resumed. + """ + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + assert not eng.maybe_one_pedal_gas_kick(False, True) + eng.maybe_one_pedal_gas_kick(True, True) + assert not eng.enableLongControl + assert getattr(eng, "_one_pedal_pause_latched", False) + eng._nap_gas_pressed = True + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=13.4) + assert eng.enableLongControl + assert not getattr(eng, "_one_pedal_pause_latched", False) + assert getattr(eng, "_nap_set_resume_long", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + assert not eng.maybe_one_pedal_gas_kick(True, True) + assert eng.enableLongControl + assert not getattr(eng, "_one_pedal_pause_latched", False) + eng._nap_set_resume_long = False + assert not eng.maybe_one_pedal_gas_kick(True, True) + assert eng.enableLongControl + assert not eng.maybe_one_pedal_gas_kick(False, True) + assert eng.enableLongControl + + +def test_one_pedal_set_resumes_even_if_pending_lost(): + """Pause latch alone is enough for one SET; do not demand a second pull.""" + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + assert not eng.maybe_one_pedal_gas_kick(False, True) + eng.maybe_one_pedal_gas_kick(True, True) + eng.maybe_one_pedal_gas_kick(False, True) + eng._nap_long_resume_pending = False + assert getattr(eng, "_one_pedal_pause_latched", False) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=13.4) + assert eng.enableLongControl + assert not getattr(eng, "_one_pedal_pause_latched", False) + assert getattr(eng, "_nap_set_resume_long", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + + +def test_one_pedal_standstill_set_clears_latch_then_gas_resumes(): + """Stop + SET after gas pause arms wait-gas; later gas completes held MAX.""" + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + assert not eng.maybe_one_pedal_gas_kick(False, True) + eng.maybe_one_pedal_gas_kick(True, True) + eng.maybe_one_pedal_gas_kick(False, True) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=0.0) + assert not eng.enableLongControl + assert getattr(eng, "_nap_resume_wait_gas", False) + assert not getattr(eng, "_one_pedal_pause_latched", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + eng._nap_gas_pressed = True + _buttons(eng, t_ms=4100, v_ego=0.0) + assert eng.enableLongControl + assert getattr(eng, "_nap_set_resume_long", False) + assert abs(eng.pedal_speed_kph - held) < 1e-6 + +def test_one_pedal_does_not_steal_standstill_wait_gas(): + """Armed stop-SET + gas touch still resumes; kick must not fire.""" + install_blinker_lat_pause() + held = 55 * CV.MPH_TO_KPH + eng = _engaged(pedal_kph=held) + _buttons(eng, brake=True, t_ms=2000, v_ego=0.0) + _buttons(eng, brake=False, t_ms=3000, v_ego=0.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=0.0) + assert getattr(eng, "_nap_resume_wait_gas", False) + assert not eng.enableLongControl + assert not eng.maybe_one_pedal_gas_kick(True, True) + eng._nap_gas_pressed = True + _buttons(eng, t_ms=4100, v_ego=0.0) + assert eng.enableLongControl + assert abs(eng.pedal_speed_kph - held) < 1e-6 diff --git a/selfdrive/car/tesla/tests/test_preap_wiper_stalk.py b/selfdrive/car/tesla/tests/test_preap_wiper_stalk.py new file mode 100644 index 00000000000000..8db724dcfa2f9b --- /dev/null +++ b/selfdrive/car/tesla/tests/test_preap_wiper_stalk.py @@ -0,0 +1,189 @@ +"""NAP wiper Off/Auto + physical collar 0→1→0 shortcut.""" +import time +from types import SimpleNamespace + +from openpilot.selfdrive.car.tesla.preap_body_controls import ( + NAP_WIPER_HUD_PENDING, + NAP_WIPER_SPEED, + STALK_FLICK_WINDOW_S, + STW_ACTN_RQ_ADDR, + WIPER_HUD_AUTO, + WIPER_HUD_DURATION_S, + WIPER_HUD_OFF, + WIPER_SETTING_AUTO, + WIPER_SETTING_INTERMITTENT, + WIPER_SETTING_OFF, + WIPER_SETTING_ON, + normalize_wiper_setting, + poll_wiper_stalk_shortcut, + read_wiper_setting, + reset_auto_gates, + reset_wiper_stalk_detector, + toggle_wiper_auto, + wiper_hud_text, +) + + +class _WiperParams: + def __init__(self, speed=WIPER_SETTING_OFF): + self.store = {NAP_WIPER_SPEED: int(speed)} + + def get(self, key, return_default=False): + return self.store.get(key, 0 if return_default else None) + + def put(self, key, dat, block=False): + self.store[key] = dat + + def put_bool(self, key, val): + self.store[key] = bool(val) + + def get_bool(self, key): + return bool(self.store.get(key)) + + +def _collar_cs(posn: int, wash: int = 0): + return SimpleNamespace(msg_stw_actn_req={ + "WprSw6Posn": posn, "WprWashSw_Psd": wash, "SpdCtrlLvr_Stat": 0, + }) + + +def test_normalize_wiper_setting_keeps_auto_coerces_legacy(): + assert normalize_wiper_setting(WIPER_SETTING_OFF) == WIPER_SETTING_OFF + assert normalize_wiper_setting(WIPER_SETTING_AUTO) == WIPER_SETTING_AUTO + assert normalize_wiper_setting(WIPER_SETTING_INTERMITTENT) == WIPER_SETTING_OFF + assert normalize_wiper_setting(WIPER_SETTING_ON) == WIPER_SETTING_OFF + assert normalize_wiper_setting(99) == WIPER_SETTING_OFF + assert normalize_wiper_setting(None) == WIPER_SETTING_OFF + assert wiper_hud_text(WIPER_SETTING_OFF) == WIPER_HUD_OFF + assert wiper_hud_text(WIPER_SETTING_AUTO) == WIPER_HUD_AUTO + assert WIPER_HUD_DURATION_S >= 2.0 + assert STALK_FLICK_WINDOW_S == 1.0 + + +def test_read_wiper_setting_persists_legacy_int_as_off(monkeypatch): + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _WiperParams(WIPER_SETTING_INTERMITTENT) + monkeypatch.setattr(body, "_get_params", lambda: fake) + reset_auto_gates() + try: + assert read_wiper_setting() == WIPER_SETTING_OFF + assert fake.store[NAP_WIPER_SPEED] == WIPER_SETTING_OFF + assert not fake.store.get(NAP_WIPER_HUD_PENDING) + finally: + reset_auto_gates() + + +def test_stalk_double_flick_toggles_off_auto_and_banner(monkeypatch): + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _WiperParams(WIPER_SETTING_OFF) + monkeypatch.setattr(body, "_get_params", lambda: fake) + reset_auto_gates() + t = 100.0 + try: + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t) is None + assert poll_wiper_stalk_shortcut(_collar_cs(1), now=t + 0.05) is None + nxt = poll_wiper_stalk_shortcut(_collar_cs(0), now=t + 0.40) + assert nxt == WIPER_SETTING_AUTO + assert fake.store[NAP_WIPER_SPEED] == WIPER_SETTING_AUTO + assert fake.store[NAP_WIPER_HUD_PENDING] is True + assert wiper_hud_text() == WIPER_HUD_AUTO + + fake.store[NAP_WIPER_HUD_PENDING] = False + t = 200.0 + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t) is None + assert poll_wiper_stalk_shortcut(_collar_cs(1), now=t + 0.05) is None + nxt = poll_wiper_stalk_shortcut(_collar_cs(0), now=t + 0.35) + assert nxt == WIPER_SETTING_OFF + assert fake.store[NAP_WIPER_SPEED] == WIPER_SETTING_OFF + assert fake.store[NAP_WIPER_HUD_PENDING] is True + assert wiper_hud_text() == WIPER_HUD_OFF + finally: + reset_auto_gates() + + +def test_stalk_slow_or_incomplete_flick_does_not_toggle(monkeypatch): + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _WiperParams(WIPER_SETTING_OFF) + monkeypatch.setattr(body, "_get_params", lambda: fake) + reset_auto_gates() + t = 100.0 + try: + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t) is None + assert poll_wiper_stalk_shortcut(_collar_cs(1), now=t + 0.05) is None + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t + 1.20) is None + assert fake.store[NAP_WIPER_SPEED] == WIPER_SETTING_OFF + assert not fake.store.get(NAP_WIPER_HUD_PENDING) + + reset_wiper_stalk_detector() + t = 300.0 + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t) is None + assert poll_wiper_stalk_shortcut(_collar_cs(1), now=t + 0.05) is None + assert poll_wiper_stalk_shortcut(_collar_cs(1), now=t + 0.50) is None + assert fake.store[NAP_WIPER_SPEED] == WIPER_SETTING_OFF + + reset_wiper_stalk_detector() + t = 400.0 + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t) is None + assert poll_wiper_stalk_shortcut(_collar_cs(2), now=t + 0.05) is None + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t + 0.20) is None + assert fake.store[NAP_WIPER_SPEED] == WIPER_SETTING_OFF + + reset_wiper_stalk_detector() + t = 500.0 + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t) is None + assert poll_wiper_stalk_shortcut(_collar_cs(1, wash=2), now=t + 0.05) is None + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t + 0.20) is None + assert fake.store[NAP_WIPER_SPEED] == WIPER_SETTING_OFF + finally: + reset_auto_gates() + + +def test_stalk_flick_uses_physical_collar_not_auto_overlay(monkeypatch): + """Auto INTERVAL1 overlay must not look like a driver flick.""" + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake = _WiperParams(WIPER_SETTING_AUTO) + monkeypatch.setattr(body, "_get_params", lambda: fake) + reset_auto_gates() + t = 100.0 + try: + # Live stalk stays Off while Auto overlays collar=1 on TX. + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t) is None + assert poll_wiper_stalk_shortcut(_collar_cs(0), now=t + 0.05) is None + assert fake.store[NAP_WIPER_SPEED] == WIPER_SETTING_AUTO + nxt = toggle_wiper_auto(announce=False) + assert nxt == WIPER_SETTING_OFF + assert not fake.store.get(NAP_WIPER_HUD_PENDING) + finally: + reset_auto_gates() + + +def test_stock_cc_update_sees_physical_flick(monkeypatch): + from openpilot.selfdrive.car.tesla import preap_body_controls as body + + fake_params = _WiperParams(WIPER_SETTING_OFF) + monkeypatch.setattr(body, "_get_params", lambda: fake_params) + monkeypatch.setattr(body, "requested_high_beam_test", lambda: False) + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", lambda self, CS, frame, tesla_can, bus: []) + + class _Fake: + def _send(self, CS, tesla_can, bus, button): + return (STW_ACTN_RQ_ADDR, b"\x00", bus) + + reset_auto_gates() + t = [1000.0] + monkeypatch.setattr(time, "monotonic", lambda: t[0]) + try: + body.stock_cc_update_with_overlay(_Fake(), _collar_cs(0), 10, None, 0) + t[0] += 0.05 + body.stock_cc_update_with_overlay(_Fake(), _collar_cs(1), 11, None, 0) + t[0] += 0.20 + body.stock_cc_update_with_overlay(_Fake(), _collar_cs(0), 12, None, 0) + assert fake_params.store[NAP_WIPER_SPEED] == WIPER_SETTING_AUTO + assert fake_params.store[NAP_WIPER_HUD_PENDING] is True + finally: + reset_auto_gates() + monkeypatch.setattr(body, "_ORIG_STOCK_CC_UPDATE", None) diff --git a/selfdrive/car/tests/.gitignore b/selfdrive/car/tests/.gitignore deleted file mode 100644 index 192fb0945ec5b3..00000000000000 --- a/selfdrive/car/tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.bz2 diff --git a/selfdrive/car/tests/big_cars_test.sh b/selfdrive/car/tests/big_cars_test.sh index 8b0e96d980670b..bb6e82dd0ebbf5 100755 --- a/selfdrive/car/tests/big_cars_test.sh +++ b/selfdrive/car/tests/big_cars_test.sh @@ -4,9 +4,8 @@ SCRIPT_DIR=$(dirname "$0") BASEDIR=$(realpath "$SCRIPT_DIR/../../../") cd $BASEDIR -MAX_EXAMPLES=300 -INTERNAL_SEG_CNT=300 -FILEREADER_CACHE=1 -INTERNAL_SEG_LIST=selfdrive/car/tests/test_models_segs.txt +export MAX_EXAMPLES=300 +export INTERNAL_SEG_CNT=300 +export INTERNAL_SEG_LIST=selfdrive/car/tests/test_models_segs.txt cd selfdrive/car/tests && pytest test_models.py test_car_interfaces.py diff --git a/selfdrive/car/tests/test_blinker_lat_pause.py b/selfdrive/car/tests/test_blinker_lat_pause.py new file mode 100644 index 00000000000000..885c034ee78c65 --- /dev/null +++ b/selfdrive/car/tests/test_blinker_lat_pause.py @@ -0,0 +1,186 @@ +"""Blinker-lamp lateral pause: events, cruise, and Tesla FSM.""" + +from cereal import car, log +from opendbc.car.toyota.values import CAR as TOYOTA + +from openpilot.selfdrive.car.car_specific import CarSpecificEvents +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import ( + LAMP_OFF_DEBOUNCE_S, + blinker_pauses_lateral, + blinker_turn_blocks_steering_disengage, + preap_blinker_pause_hides_controls_mismatch, +) +from openpilot.selfdrive.selfdrived.events import ET, EVENTS + + +EventName = log.OnroadEvent.EventName +ButtonType = car.CarState.ButtonEvent.Type + + +def _cp(): + # Common-event path only. Tesla pedal-calibration events are unrelated. + cp = car.CarParams.new_message() + cp.carFingerprint = TOYOTA.TOYOTA_RAV4 + cp.brand = "toyota" + cp.pcmCruise = True + cp.openpilotLongitudinalControl = False + return cp + + +def _cs(*, left=False, right=False, steering_disengage=False, steering_pressed=False, + cancel=False, cruise_enabled=True, v_ego=0.0, stalk=0): + cs = car.CarState.new_message() + cs.cruiseState.available = True + cs.cruiseState.enabled = cruise_enabled + cs.gearShifter = "drive" + cs.leftBlinker = left + cs.rightBlinker = right + cs.steeringDisengage = steering_disengage + cs.steeringPressed = steering_pressed + cs.vEgo = v_ego + cs.turnSignalStalkState = stalk + if cancel: + be = car.CarState.ButtonEvent.new_message() + be.type = ButtonType.cancel + be.pressed = True + cs.buttonEvents = [be] + return cs + + +def _events(cs, cs_prev=None, cse=None, cc=None): + helper = cse or CarSpecificEvents(_cp()) + return helper.update(cs, cs_prev or _cs(), cc or car.CarControl.new_message()) + + +def test_one_lamp_steering_does_not_user_disable(): + prev = _cs(left=True) + events = _events(_cs(left=True, steering_disengage=True, steering_pressed=True), prev) + assert EventName.steerDisengage not in events.names + assert ET.USER_DISABLE not in EVENTS[EventName.steerOverride] + + +def test_hazards_still_allow_steer_disengage(): + prev = _cs(left=True, right=True) + events = _events(_cs(left=True, right=True, steering_disengage=True), prev) + assert EventName.steerDisengage in events.names + + +def test_no_lamp_steer_disengage_still_fires(): + events = _events(_cs(steering_disengage=True), _cs()) + assert EventName.steerDisengage in events.names + + +def test_stalk_cancel_still_fires_during_pause(): + events = _events(_cs(left=True, cancel=True), _cs(left=True)) + assert EventName.buttonCancel in events.names + + +def test_blinker_pause_predicate(): + assert blinker_pauses_lateral(True, False) + assert blinker_pauses_lateral(False, True) + assert not blinker_pauses_lateral(True, True) + assert not blinker_pauses_lateral(False, False) + + +def test_lamp_off_hand_still_on_does_not_user_disable(): + cse = CarSpecificEvents(_cp()) + _events(_cs(left=True), _cs(left=True), cse=cse) + # Lamp just cleared on the same frame the wheel is grabbed. + events = _events(_cs(steering_disengage=True, steering_pressed=True), + _cs(left=True), cse=cse) + assert EventName.steerDisengage not in events.names + + +def test_flash_gap_without_hand_does_not_user_disable(): + cse = CarSpecificEvents(_cp()) + _events(_cs(left=True), _cs(), cse=cse) + # Dark between flashes, no steeringPressed, then a grab. + _events(_cs(), _cs(left=True), cse=cse) + events = _events(_cs(steering_disengage=True, steering_pressed=True), _cs(), cse=cse) + assert EventName.steerDisengage not in events.names + assert cse.blinker_lat_hold.turn_active + + +def test_hand_on_after_turn_complete_does_not_user_disable(): + cse = CarSpecificEvents(_cp()) + _events(_cs(left=True), _cs(), cse=cse) + cse.blinker_lat_hold.update(False, False, True, dt=LAMP_OFF_DEBOUNCE_S) + events = _events(_cs(steering_disengage=True, steering_pressed=True), _cs(), cse=cse) + assert EventName.steerDisengage not in events.names + assert cse.blinker_lat_hold.holding + assert not cse.blinker_lat_hold.turn_active + + +def test_steer_disengage_after_hand_release_still_fires(): + cse = CarSpecificEvents(_cp()) + _events(_cs(left=True, steering_disengage=True, steering_pressed=True), + _cs(left=True), cse=cse) + # Turn complete (~1s dark) with the wheel released, then a new grab. + cse.blinker_lat_hold.update(False, False, False, dt=LAMP_OFF_DEBOUNCE_S) + events = _events(_cs(steering_disengage=True, steering_pressed=True), _cs(), cse=cse) + assert EventName.steerDisengage in events.names + + +def test_alc_keep_alive_lamps_do_not_steer_disengage(): + cse = CarSpecificEvents(_cp()) + cc = car.CarControl.new_message() + cc.leftBlinker = True + _events(_cs(left=True), _cs(), cse=cse, cc=cc) + events = _events(_cs(left=True, steering_disengage=True, steering_pressed=True), + _cs(left=True), cse=cse, cc=cc) + assert EventName.steerDisengage not in events.names + assert not cse.blinker_lat_hold.turn_active + assert cse.blinker_lat_hold.blocks_steer_disengage + + +def test_highway_stalk_tap_lamps_do_not_steer_disengage(): + cse = CarSpecificEvents(_cp()) + events = _events(_cs(left=True, steering_disengage=True, steering_pressed=True, + v_ego=30.0, stalk=1), _cs(), cse=cse) + assert EventName.steerDisengage not in events.names + assert not cse.blinker_lat_hold.turn_active + + +def test_held_flashing_corner_keeps_block_and_hides_preap_mismatch(): + cse = CarSpecificEvents(_cp()) + dt = 0.01 + period = 0.66 + on_s = 0.33 + prev = _cs() + for i in range(int(8.0 / dt)): + left = ((i * dt) % period) < on_s + pressed = (i % 20) < 10 + cs = _cs(left=left, steering_disengage=pressed, steering_pressed=pressed, stalk=1) + events = _events(cs, prev, cse=cse) + prev = cs + assert EventName.steerDisengage not in events.names + assert cse.blinker_lat_hold.blocks_steer_disengage + assert preap_blinker_pause_hides_controls_mismatch( + brand="tesla", fingerprint="TESLA_MODEL_S_PREAP", + blocks_steer_disengage=cse.blinker_lat_hold.blocks_steer_disengage) + + +def test_faster_corner_disengage_without_steering_pressed_does_not_cancel(): + cse = CarSpecificEvents(_cp()) + prev = _cs() + for _ in range(50): + cs = _cs(left=True, stalk=1) + _events(cs, prev, cse=cse) + prev = cs + assert cse.blinker_lat_hold.turn_active + events = _events(_cs(left=True, stalk=1, steering_disengage=True, steering_pressed=False), + prev, cse=cse) + assert EventName.steerDisengage not in events.names + assert cse.blinker_lat_hold.blocks_steer_disengage + # Flash-gap dark frames while hands-on 2 still must not USER_DISABLE. + events = _events(_cs(stalk=1, steering_disengage=True, steering_pressed=False), + _cs(left=True, stalk=1, steering_disengage=True), cse=cse) + assert EventName.steerDisengage not in events.names + assert cse.blinker_lat_hold.turn_active + + +def test_stalk_held_without_prior_hold_does_not_steer_disengage(): + """Hard gate: physical LEFT/RIGHT even if the flash-latch never started.""" + events = _events(_cs(stalk=1, steering_disengage=True), _cs()) + assert EventName.steerDisengage not in events.names + assert blinker_turn_blocks_steering_disengage(False, False, 1, None) diff --git a/selfdrive/car/tests/test_car_interfaces.py b/selfdrive/car/tests/test_car_interfaces.py index 66cf0dc6968531..1bc59326a20a3c 100644 --- a/selfdrive/car/tests/test_car_interfaces.py +++ b/selfdrive/car/tests/test_car_interfaces.py @@ -1,78 +1,39 @@ import os -import math import hypothesis.strategies as st from hypothesis import Phase, given, settings -from parameterized import parameterized +from openpilot.common.parameterized import parameterized from cereal import car from opendbc.car import DT_CTRL -from opendbc.car.car_helpers import interfaces from opendbc.car.structs import CarParams -from opendbc.car.tests.test_car_interfaces import get_fuzzy_car_interface_args -from opendbc.car.fingerprints import all_known_cars -from opendbc.car.fw_versions import FW_VERSIONS, FW_QUERY_CONFIGS +from opendbc.car.tests.test_car_interfaces import get_fuzzy_car_interface from opendbc.car.mock.values import CAR as MOCK -from openpilot.selfdrive.car.card import convert_carControl, convert_to_capnp +from opendbc.car.values import PLATFORMS from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque from openpilot.selfdrive.controls.lib.longcontrol import LongControl from openpilot.selfdrive.test.fuzzy_generation import FuzzyGenerator -ALL_ECUS = {ecu for ecus in FW_VERSIONS.values() for ecu in ecus.keys()} -ALL_ECUS |= {ecu for config in FW_QUERY_CONFIGS.values() for ecu in config.extra_ecus} - -ALL_REQUESTS = {tuple(r.request) for config in FW_QUERY_CONFIGS.values() for r in config.requests} - MAX_EXAMPLES = int(os.environ.get('MAX_EXAMPLES', '60')) class TestCarInterfaces: # FIXME: Due to the lists used in carParams, Phase.target is very slow and will cause # many generated examples to overrun when max_examples > ~20, don't use it - @parameterized.expand([(car,) for car in sorted(all_known_cars())] + [MOCK.MOCK]) + @parameterized.expand([(car,) for car in sorted(PLATFORMS)] + [MOCK.MOCK]) @settings(max_examples=MAX_EXAMPLES, deadline=None, phases=(Phase.reuse, Phase.generate, Phase.shrink)) @given(data=st.data()) def test_car_interfaces(self, car_name, data): - CarInterface, CarController, CarState, RadarInterface = interfaces[car_name] - - args = get_fuzzy_car_interface_args(data.draw) - - car_params = CarInterface.get_params(car_name, args['fingerprints'], args['car_fw'], - experimental_long=args['experimental_long'], docs=False) - car_interface = CarInterface(car_params, CarController, CarState) - assert car_params - assert car_interface - - assert car_params.mass > 1 - assert car_params.wheelbase > 0 - # centerToFront is center of gravity to front wheels, assert a reasonable range - assert car_params.wheelbase * 0.3 < car_params.centerToFront < car_params.wheelbase * 0.7 - assert car_params.maxLateralAccel > 0 - - # Longitudinal sanity checks - assert len(car_params.longitudinalTuning.kpV) == len(car_params.longitudinalTuning.kpBP) - assert len(car_params.longitudinalTuning.kiV) == len(car_params.longitudinalTuning.kiBP) - - # Lateral sanity checks - if car_params.steerControlType != CarParams.SteerControlType.angle: - tune = car_params.lateralTuning - if tune.which() == 'pid': - if car_name != MOCK.MOCK: - assert not math.isnan(tune.pid.kf) and tune.pid.kf > 0 - assert len(tune.pid.kpV) > 0 and len(tune.pid.kpV) == len(tune.pid.kpBP) - assert len(tune.pid.kiV) > 0 and len(tune.pid.kiV) == len(tune.pid.kiBP) - - elif tune.which() == 'torque': - assert not math.isnan(tune.torque.kf) and tune.torque.kf > 0 - assert not math.isnan(tune.torque.friction) and tune.torque.friction > 0 + car_interface = get_fuzzy_car_interface(car_name, data.draw) + car_params = car_interface.CP.as_reader() cc_msg = FuzzyGenerator.get_random_msg(data.draw, car.CarControl, real_floats=True) # Run car interface now_nanos = 0 CC = car.CarControl.new_message(**cc_msg) - CC = convert_carControl(CC.as_reader()) + CC = CC.as_reader() for _ in range(10): car_interface.update([]) car_interface.apply(CC, now_nanos) @@ -80,7 +41,9 @@ def test_car_interfaces(self, car_name, data): CC = car.CarControl.new_message(**cc_msg) CC.enabled = True - CC = convert_carControl(CC.as_reader()) + CC.latActive = True + CC.longActive = True + CC = CC.as_reader() for _ in range(10): car_interface.update([]) car_interface.apply(CC, now_nanos) @@ -89,11 +52,10 @@ def test_car_interfaces(self, car_name, data): # Test controller initialization # TODO: wait until card refactor is merged to run controller a few times, # hypothesis also slows down significantly with just one more message draw - car_params_capnp = convert_to_capnp(car_params).as_reader() - LongControl(car_params_capnp) + LongControl(car_params) if car_params.steerControlType == CarParams.SteerControlType.angle: - LatControlAngle(car_params_capnp, car_interface) + LatControlAngle(car_params, car_interface, DT_CTRL) elif car_params.lateralTuning.which() == 'pid': - LatControlPID(car_params_capnp, car_interface) + LatControlPID(car_params, car_interface, DT_CTRL) elif car_params.lateralTuning.which() == 'torque': - LatControlTorque(car_params_capnp, car_interface) + LatControlTorque(car_params, car_interface, DT_CTRL) diff --git a/selfdrive/car/tests/test_car_specific_tesla_preap.py b/selfdrive/car/tests/test_car_specific_tesla_preap.py new file mode 100644 index 00000000000000..f1e56e4ef4f14c --- /dev/null +++ b/selfdrive/car/tests/test_car_specific_tesla_preap.py @@ -0,0 +1,256 @@ +"""Tesla Pre-AP pedal calibration and authority-failure events. + +CarSpecificEvents must raise pedalNotCalibrated only when: + carFingerprint == TESLA_MODEL_S_PREAP (pre-AP car) + and not pcmCruise (pedal mode — we're the longitudinal actuator) + and nap_conf.pedal_calibrated is False (calibration not trusted) + +All three conditions together. + +The authority-failure regression also crosses the real controller, engagement, +CarState publication, event-selection, and alert-definition seams. +""" +from unittest.mock import PropertyMock, patch # noqa: TID251 + +from cereal import car, log +from opendbc.can import CANPacker +from opendbc.car import CanData +from opendbc.car.car_helpers import interfaces + +from openpilot.selfdrive.car.car_specific import CarSpecificEvents +from openpilot.selfdrive.selfdrived.events import ET, EVENTS, pcm_disable_alert, reverse_gear_disable_alert + + +EventName = log.OnroadEvent.EventName +NAP_CONF_PATH = "opendbc.car.tesla.preap.nap_conf.NAPConf.pedal_calibrated" +NAP_USE_PEDAL_PATH = "opendbc.car.tesla.preap.nap_conf.NAPConf.use_pedal" +NAP_PEDAL_FACTOR_PATH = "opendbc.car.tesla.preap.nap_conf.NAPConf.pedal_factor" +GAS_COMMAND_ID = 0x551 + + +def _make_cp(*, fingerprint="TESLA_MODEL_S_PREAP", brand="tesla", pcm_cruise=False, + op_long=True): + cp = car.CarParams.new_message() + cp.carFingerprint = fingerprint + cp.brand = brand + cp.pcmCruise = pcm_cruise + cp.openpilotLongitudinalControl = op_long + return cp + + +def _make_cs(): + cs = car.CarState.new_message() + cs.cruiseState.available = True + cs.gearShifter = "drive" + return cs + + +def _run(cp, calibrated, cs=None): + with patch(NAP_CONF_PATH, new_callable=PropertyMock, return_value=calibrated): + ce = CarSpecificEvents(cp) + events = ce.update(cs or _make_cs(), _make_cs(), car.CarControl.new_message()) + return events.names + + +def _preap_can_packet(message, values): + address, dat, bus = CANPacker("tesla_preap").make_can_msg(message, 0, values) + return [(1, [CanData(address, dat, bus)])] + + +def test_fires_in_preap_pedal_mode_when_uncalibrated(): + cp = _make_cp(pcm_cruise=False, op_long=True) + assert EventName.pedalNotCalibrated in _run(cp, calibrated=False) + + +def test_silent_in_preap_pedal_mode_when_calibrated(): + cp = _make_cp(pcm_cruise=False, op_long=True) + assert EventName.pedalNotCalibrated not in _run(cp, calibrated=True) + + +def test_silent_in_preap_nopedal_mode_even_when_uncalibrated(): + # no-pedal mode doesn't use the Comma Pedal; calibration is irrelevant + cp = _make_cp(pcm_cruise=True, op_long=False) + assert EventName.pedalNotCalibrated not in _run(cp, calibrated=False) + + +def test_silent_on_non_preap_tesla(): + cp = _make_cp(fingerprint="TESLA_MODEL_S", pcm_cruise=False, op_long=True) + assert EventName.pedalNotCalibrated not in _run(cp, calibrated=False) + + +def test_silent_on_non_tesla_brand(): + cp = _make_cp(fingerprint="HONDA_CIVIC_2022", brand="honda", pcm_cruise=True, op_long=False) + assert EventName.pedalNotCalibrated not in _run(cp, calibrated=False) + + +def test_pedal_authority_failure_warns_only_in_preap_pedal_mode(): + cs = _make_cs() + cs.pedalAuthorityFailed = True + + pedal_mode = _make_cp(pcm_cruise=False, op_long=True) + assert EventName.pedalUnavailable in _run(pedal_mode, calibrated=True, cs=cs) + + no_pedal_mode = _make_cp(pcm_cruise=True, op_long=False) + assert EventName.pedalUnavailable not in _run(no_pedal_mode, calibrated=True, cs=cs) + + longitudinal_disabled = _make_cp(pcm_cruise=False, op_long=False) + assert EventName.pedalUnavailable not in _run(longitudinal_disabled, calibrated=True, cs=cs) + + non_preap = _make_cp(fingerprint="TESLA_MODEL_S", pcm_cruise=False, op_long=True) + assert EventName.pedalUnavailable not in _run(non_preap, calibrated=True, cs=cs) + + +def test_pedal_acquisition_failure_keeps_lateral_and_surfaces_alert(): + with ( + patch(NAP_USE_PEDAL_PATH, new_callable=PropertyMock, return_value=True), + patch(NAP_PEDAL_FACTOR_PATH, new_callable=PropertyMock, return_value=1.0), + patch(NAP_CONF_PATH, new_callable=PropertyMock, return_value=True), + ): + CarInterface = interfaces["TESLA_MODEL_S_PREAP"] + cp = CarInterface.get_params( + "TESLA_MODEL_S_PREAP", {bus: {} for bus in range(8)}, [], + alpha_long=False, is_release=False, docs=False, + ) + interface = CarInterface(cp) + drive_packet = _preap_can_packet("DI_torque2", {"DI_gear": 4}) + interface.update(drive_packet) + + internal_state = interface.CS + internal_state.engagement.cruiseEnabled = True + internal_state.engagement.enableLongControl = True + internal_state.cruiseEnabled = True + internal_state.enableLongControl = True + internal_state.enableJustCC = False + internal_state.pedal.available = False + internal_state.pedal.interceptor_state = 5 + internal_state.pedal.idx = 0 + + control = car.CarControl.new_message() + control.enabled = True + control.latActive = True + control.longActive = True + control.actuators.accel = 0.5 + control = control.as_reader() + + pedal_commands = [] + for update_index in range(9): + if interface.CC.frame % 2 == 0: + internal_state.pedal.idx = (internal_state.pedal.idx + 1) % 16 + _, can_sends = interface.apply(control, now_nanos=update_index * 10_000_000) + pedal_commands.extend(command for command in can_sends if command[0] == GAS_COMMAND_ID) + + assert len(pedal_commands) == 4 + assert all(not command[1][4] & 0x80 for command in pedal_commands) + assert internal_state.engagement.cruiseEnabled + assert not internal_state.engagement.enableLongControl + assert internal_state.engagement.enableJustCC + assert internal_state.engagement.pedal_unavailable + + public_state = interface.update(drive_packet) + assert public_state.cruiseState.enabled + assert not public_state.pedalLongActive + assert public_state.pedalAuthorityFailed + + events = CarSpecificEvents(cp).update(public_state, _make_cs(), control) + assert EventName.pedalUnavailable in events.names + + event_types = EVENTS[EventName.pedalUnavailable] + alert = event_types[ET.WARNING] + assert set(event_types) == {ET.WARNING} + assert alert.alert_text_1 == "Pedal Control Unavailable" + assert alert.alert_text_2 == "Speed Control Disabled" + + +def test_pcm_disable_hud_is_steering_disengaged_not_steer_disengage(): + """3X bottom-bar 'Steering Disengaged' is EventName.pcmDisable.""" + assert EVENTS[EventName.pcmDisable][ET.USER_DISABLE] is pcm_disable_alert + cp = _make_cp() + disable = pcm_disable_alert(cp, _make_cs(), None, False, 100, log.LongitudinalPersonality.standard) + assert disable.alert_text_1 == "Steering Disengaged" + steer = EVENTS[EventName.steerDisengage][ET.USER_DISABLE] + assert steer.alert_text_1 == "" + + +def _blinker_cs(*, enabled=True, left=True, stalk=1, steering_disengage=False): + cs = _make_cs() + cs.cruiseState.enabled = enabled + cs.leftBlinker = left + cs.rightBlinker = False + cs.turnSignalStalkState = stalk + cs.steeringDisengage = steering_disengage + return cs + + +def test_preap_blinker_held_high_torque_does_not_add_pcm_disable(): + """Keep cruiseEnabled and the HUD stays off. Pedal and no-pedal both pcm_enable.""" + for pcm_cruise, op_long in ((True, False), (False, True)): + cse = CarSpecificEvents(_make_cp(pcm_cruise=pcm_cruise, op_long=op_long)) + prev = _blinker_cs(enabled=True, steering_disengage=False) + for _ in range(50): + cs = _blinker_cs(enabled=True, steering_disengage=False) + events = cse.update(cs, prev, car.CarControl.new_message()) + assert EventName.pcmDisable not in events.names + prev = cs + events = cse.update( + _blinker_cs(enabled=True, steering_disengage=True), prev, + car.CarControl.new_message()) + assert EventName.steerDisengage not in events.names + assert EventName.pcmDisable not in events.names + + +def test_preap_pcm_disable_still_fires_when_cruise_already_off(): + """Do not hide the HUD after the FSM has already dropped cruise.""" + cse = CarSpecificEvents(_make_cp(pcm_cruise=True, op_long=False)) + events = cse.update( + _blinker_cs(enabled=False, steering_disengage=True), + _blinker_cs(enabled=True, steering_disengage=False), + car.CarControl.new_message()) + assert EventName.pcmDisable in events.names + + +def test_reverse_user_disables_and_blocks_entry(): + """Reverse still USER_DISABLE + NO_ENTRY so OP drops and cannot re-enter.""" + assert ET.USER_DISABLE in EVENTS[EventName.reverseGear] + assert ET.NO_ENTRY in EVENTS[EventName.reverseGear] + assert EVENTS[EventName.reverseGear][ET.USER_DISABLE] is reverse_gear_disable_alert + cse = CarSpecificEvents(_make_cp()) + prev = _make_cs() + prev.cruiseState.enabled = True + prev.gearShifter = "drive" + cs = _make_cs() + cs.cruiseState.enabled = False + cs.gearShifter = "reverse" + events = cse.update(cs, prev, car.CarControl.new_message()) + assert EventName.reverseGear in events.names + assert EventName.pcmDisable in events.names + assert EventName.wrongGear in events.names + assert EventName.controlsMismatch not in events.names + assert EventName.stockFcw not in events.names + assert EventName.stockAeb not in events.names + + +def test_drive_after_reverse_rising_edge_can_pcm_enable(): + """After Drive returns, a new cruise rising edge is a normal engage. + + No leftover reverseGear / controlsMismatch. The FSM must have dropped + cruiseEnabled during reverse so this rising edge exists. + """ + cse = CarSpecificEvents(_make_cp()) + reverse = _make_cs() + reverse.cruiseState.enabled = False + reverse.gearShifter = "reverse" + parked = _make_cs() + parked.cruiseState.enabled = False + parked.gearShifter = "drive" + events = cse.update(parked, reverse, car.CarControl.new_message()) + assert EventName.reverseGear not in events.names + assert EventName.pcmDisable in events.names + assert EventName.controlsMismatch not in events.names + + engaged = _make_cs() + engaged.cruiseState.enabled = True + engaged.gearShifter = "drive" + events = cse.update(engaged, parked, car.CarControl.new_message()) + assert EventName.pcmEnable in events.names + assert EventName.reverseGear not in events.names + assert EventName.controlsMismatch not in events.names diff --git a/selfdrive/car/tests/test_cruise_speed.py b/selfdrive/car/tests/test_cruise_speed.py index 7bda3a24eb31ac..bfb060874d17d5 100644 --- a/selfdrive/car/tests/test_cruise_speed.py +++ b/selfdrive/car/tests/test_cruise_speed.py @@ -2,11 +2,11 @@ import itertools import numpy as np -from parameterized import parameterized_class +from openpilot.common.parameterized import parameterized_class from cereal import log from openpilot.selfdrive.car.cruise import VCruiseHelper, V_CRUISE_MIN, V_CRUISE_MAX, V_CRUISE_INITIAL, IMPERIAL_INCREMENT from cereal import car -from openpilot.common.conversions import Conversions as CV +from openpilot.common.constants import CV from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver ButtonEvent = car.CarState.ButtonEvent @@ -93,7 +93,7 @@ def test_rising_edge_enable(self): self.enable(V_CRUISE_INITIAL * CV.KPH_TO_MS, False) # Expected diff on enabling. Speed should not change on falling edge of pressed - assert not pressed == self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last + assert (not pressed) == (self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last) def test_resume_in_standstill(self): """ diff --git a/selfdrive/car/tests/test_curve_follow_card_max.py b/selfdrive/car/tests/test_curve_follow_card_max.py new file mode 100644 index 00000000000000..3481c93488cb58 --- /dev/null +++ b/selfdrive/car/tests/test_curve_follow_card_max.py @@ -0,0 +1,72 @@ +"""NAPCurveFollow and the HUD MAX (Pre-AP card). + +Shadow (1) and off (0) leave CurveMaxHold exactly as it was. Active (2) never +touches MAX: no cap, no snapshot, no restore. +""" +import json + +import pytest + +from openpilot.common.constants import CV +from openpilot.selfdrive.car import card as card_mod +from openpilot.selfdrive.car.tests.test_preap_engage_max_after_pause import _harness, _run + +MPH = CV.MPH_TO_KPH + + +def _curve(mode, seconds_in=2.0): + h, cs, md, eng = _harness(70.0) + h._curve_follow_mode = mode + _run(h, cs, 2.0) + lowest = h.v_cruise_helper.v_cruise_kph + _run(h, cs, seconds_in, 40.0, 40.0, steer=lambda _x: 30.0) + lowest = min(lowest, h.v_cruise_helper.v_cruise_kph) + return h, cs, lowest + + +@pytest.mark.parametrize("mode", [0, 1]) +def test_off_and_shadow_still_cap_max_in_a_bend(mode): + h, cs, _ = _curve(mode) + assert h.v_cruise_helper.v_cruise_kph < 60.0 * MPH + _run(h, cs, 40.0, 40.0, 40.0, steer=lambda _x: 0.0) + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(70.0 * MPH, abs=0.3) + + +def test_active_never_touches_max(): + h, cs, _ = _curve(2, seconds_in=4.0) + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(70.0 * MPH, abs=0.3) + assert h._curve_max._cap_kph is None + _run(h, cs, 10.0, 40.0, 40.0, steer=lambda _x: 0.0) + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(70.0 * MPH, abs=0.3) + + +def test_active_max_is_bit_identical_to_a_straight_drive(): + a, cs_a, _ = _curve(2, seconds_in=4.0) + b, cs_b, _md, _eng = _harness(70.0) + b._curve_follow_mode = 2 + _run(b, cs_b, 2.0) + _run(b, cs_b, 4.0, 40.0, 40.0, steer=lambda _x: 0.0) + assert a.v_cruise_helper.v_cruise_kph == b.v_cruise_helper.v_cruise_kph + + +def test_flipping_to_active_mid_bend_gives_max_back(): + h, cs, _ = _curve(1, seconds_in=3.0) + assert h.v_cruise_helper.v_cruise_kph < 60.0 * MPH + h._curve_follow_mode = 2 + _run(h, cs, 10.0, 40.0, 40.0, steer=lambda _x: 30.0) + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(70.0 * MPH, abs=0.3) + + +def test_curvemax_log_line_is_2hz_and_only_while_the_cap_is_in_play(monkeypatch): + lines = [] + monkeypatch.setattr(card_mod.cloudlog, "error", lambda msg, *a, **k: lines.append(msg)) + _curve(1, seconds_in=4.0) + cm = [m for m in lines if str(m).startswith("curvemax ")] + assert cm + rec = json.loads(cm[-1][len("curvemax "):]) + for key in ("m", "act", "cap", "hud_in", "hud", "seed", "frz", "posted", "v"): + assert key in rec + assert rec["m"] == 1 + lines.clear() + _curve(2, seconds_in=4.0) + assert not [m for m in lines if str(m).startswith("curvemax ")] diff --git a/selfdrive/car/tests/test_docs.py b/selfdrive/car/tests/test_docs.py index a203b2feff6d45..6e13d55b29a52d 100644 --- a/selfdrive/car/tests/test_docs.py +++ b/selfdrive/car/tests/test_docs.py @@ -4,7 +4,7 @@ from opendbc.car.docs import generate_cars_md, get_all_car_docs from openpilot.selfdrive.debug.dump_car_docs import dump_car_docs from openpilot.selfdrive.debug.print_docs_diff import print_car_docs_diff -from openpilot.selfdrive.car.docs import CARS_MD_OUT, CARS_MD_TEMPLATE +from openpilot.selfdrive.car.docs import CARS_MD_TEMPLATE class TestCarDocs: @@ -13,11 +13,7 @@ def setup_class(cls): cls.all_cars = get_all_car_docs() def test_generator(self): - generated_cars_md = generate_cars_md(self.all_cars, CARS_MD_TEMPLATE) - with open(CARS_MD_OUT) as f: - current_cars_md = f.read() - - assert generated_cars_md == current_cars_md, "Run selfdrive/opcar/docs.py to update the compatibility documentation" + generate_cars_md(self.all_cars, CARS_MD_TEMPLATE) def test_docs_diff(self): dump_path = os.path.join(BASEDIR, "selfdrive", "car", "tests", "cars_dump") diff --git a/selfdrive/car/tests/test_models.py b/selfdrive/car/tests/test_models.py index e8df0a8310f054..a7f3d68c149788 100644 --- a/selfdrive/car/tests/test_models.py +++ b/selfdrive/car/tests/test_models.py @@ -1,37 +1,31 @@ -import capnp -import copy -import dataclasses +import time import os import pytest import random import unittest # noqa: TID251 from collections import defaultdict, Counter -from functools import partial import hypothesis.strategies as st from hypothesis import Phase, given, settings -from parameterized import parameterized_class +from openpilot.common.parameterized import parameterized_class -from cereal import messaging, log, car -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params from opendbc.car import DT_CTRL, gen_empty_fingerprint, structs -from opendbc.car.fingerprints import all_known_cars, MIGRATION +from opendbc.car.can_definitions import CanData from opendbc.car.car_helpers import FRAME_FINGERPRINT, interfaces +from opendbc.car.fingerprints import MIGRATION from opendbc.car.honda.values import CAR as HONDA, HondaFlags -from opendbc.car.values import Platform +from opendbc.car.structs import car from opendbc.car.tests.routes import non_tested_cars, routes, CarTestRoute -from openpilot.selfdrive.car.card import Car, convert_to_capnp +from opendbc.car.values import Platform, PLATFORMS +from opendbc.safety.tests.libsafety import libsafety_py +from openpilot.common.basedir import BASEDIR from openpilot.selfdrive.pandad import can_capnp_to_list from openpilot.selfdrive.test.helpers import read_segment_list from openpilot.system.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT -from openpilot.tools.lib.logreader import LogReader, auto_source, internal_source, openpilotci_source, openpilotci_source_zst +from openpilot.tools.lib.logreader import LogReader, LogsUnavailable, openpilotci_source, internal_source, comma_api_source from openpilot.tools.lib.route import SegmentName -from panda.tests.libpanda import libpanda_py - -EventName = car.OnroadEvent.EventName -PandaType = log.PandaState.PandaType SafetyModel = car.CarParams.SafetyModel +SteerControlType = structs.CarParams.SteerControlType NUM_JOBS = int(os.environ.get("NUM_JOBS", "1")) JOB_ID = int(os.environ.get("JOB_ID", "0")) @@ -47,9 +41,9 @@ def get_test_cases() -> list[tuple[str, CarTestRoute | None]]: if not len(INTERNAL_SEG_LIST): routes_by_car = defaultdict(set) for r in routes: - routes_by_car[r.car_model].add(r) + routes_by_car[str(r.car_model)].add(r) - for i, c in enumerate(sorted(all_known_cars())): + for i, c in enumerate(sorted(PLATFORMS)): if i % NUM_JOBS == JOB_ID: test_cases.extend(sorted((c, r) for r in routes_by_car.get(c, (None,)))) @@ -57,6 +51,7 @@ def get_test_cases() -> list[tuple[str, CarTestRoute | None]]: segment_list = read_segment_list(os.path.join(BASEDIR, INTERNAL_SEG_LIST)) segment_list = random.sample(segment_list, INTERNAL_SEG_CNT or len(segment_list)) for platform, segment in segment_list: + platform = MIGRATION.get(platform, platform) segment_name = SegmentName(segment) test_cases.append((platform, CarTestRoute(segment_name.route_name.canonical_name, platform, segment=segment_name.segment_num))) @@ -68,9 +63,8 @@ def get_test_cases() -> list[tuple[str, CarTestRoute | None]]: class TestCarModelBase(unittest.TestCase): platform: Platform | None = None test_route: CarTestRoute | None = None - test_route_on_bucket: bool = True # whether the route is on the preserved CI bucket - can_msgs: list[capnp.lib.capnp._DynamicStructReader] + can_msgs: list[tuple[int, list[CanData]]] fingerprint: dict[int, dict[int, int]] elm_frame: int | None car_safety_mode_frame: int | None @@ -82,10 +76,11 @@ def get_testing_data_from_logreader(cls, lr): cls.elm_frame = None cls.car_safety_mode_frame = None cls.fingerprint = gen_empty_fingerprint() - experimental_long = False + alpha_long = False for msg in lr: if msg.which() == "can": - can_msgs.append(msg) + can = can_capnp_to_list((msg.as_builder().to_bytes(),))[0] + can_msgs.append((can[0], [CanData(*can) for can in can[1]])) if len(can_msgs) <= FRAME_FINGERPRINT: for m in msg.can: if m.src < 64: @@ -94,8 +89,8 @@ def get_testing_data_from_logreader(cls, lr): elif msg.which() == "carParams": car_fw = msg.carParams.carFw if msg.carParams.openpilotLongitudinalControl: - experimental_long = True - if cls.platform is None and not cls.test_route_on_bucket: + alpha_long = True + if cls.platform is None: live_fingerprint = msg.carParams.carFingerprint cls.platform = MIGRATION.get(live_fingerprint, live_fingerprint) @@ -115,10 +110,8 @@ def get_testing_data_from_logreader(cls, lr): (SafetyModel.elm327, SafetyModel.noOutput): cls.car_safety_mode_frame = len(can_msgs) - if len(can_msgs) > int(50 / DT_CTRL): - return car_fw, can_msgs, experimental_long - - raise Exception("no can data found") + assert len(can_msgs) > int(50 / DT_CTRL), "no can data found" + return car_fw, can_msgs, alpha_long @classmethod def get_testing_data(cls): @@ -126,31 +119,16 @@ def get_testing_data(cls): if cls.test_route.segment is not None: test_segs = (cls.test_route.segment,) - is_internal = len(INTERNAL_SEG_LIST) - for seg in test_segs: segment_range = f"{cls.test_route.route}/{seg}" try: - source = partial(auto_source, sources=[internal_source] if is_internal else [openpilotci_source, openpilotci_source_zst]) - lr = LogReader(segment_range, source=source) + sources = [internal_source] if len(INTERNAL_SEG_LIST) else [openpilotci_source, comma_api_source] + lr = LogReader(segment_range, sources=sources, sort_by_time=True) return cls.get_testing_data_from_logreader(lr) - except Exception: + except (LogsUnavailable, AssertionError): pass - # Route is not in CI bucket, assume either user has access (private), or it is public - # test_route_on_ci_bucket will fail when running in CI - if not is_internal: - cls.test_route_on_bucket = False - - for seg in test_segs: - segment_range = f"{cls.test_route.route}/{seg}" - try: - lr = LogReader(segment_range) - return cls.get_testing_data_from_logreader(lr) - except Exception: - pass - raise Exception(f"Route: {repr(cls.test_route.route)} with segments: {test_segs} not found or no CAN msgs found. Is it uploaded and public?") @@ -165,15 +143,13 @@ def setUpClass(cls): raise unittest.SkipTest raise Exception(f"missing test route for {cls.platform}") - car_fw, can_msgs, experimental_long = cls.get_testing_data() + car_fw, cls.can_msgs, alpha_long = cls.get_testing_data() # if relay is expected to be open in the route cls.openpilot_enabled = cls.car_safety_mode_frame is not None - cls.can_msgs = sorted(can_msgs, key=lambda msg: msg.logMonoTime) - - cls.CarInterface, cls.CarController, cls.CarState, cls.RadarInterface = interfaces[cls.platform] - cls.CP = cls.CarInterface.get_params(cls.platform, cls.fingerprint, car_fw, experimental_long, docs=False) + cls.CarInterface = interfaces[cls.platform] + cls.CP = cls.CarInterface.get_params(cls.platform, cls.fingerprint, car_fw, alpha_long, False, docs=False) assert cls.CP assert cls.CP.carFingerprint == cls.platform @@ -184,15 +160,13 @@ def tearDownClass(cls): del cls.can_msgs def setUp(self): - self.CI = self.CarInterface(copy.deepcopy(self.CP), self.CarController, self.CarState) + self.CI = self.CarInterface(self.CP.copy()) assert self.CI - Params().put_bool("OpenpilotEnabledToggle", self.openpilot_enabled) - # TODO: check safetyModel is in release panda build - self.safety = libpanda_py.libpanda + self.safety = libsafety_py.libsafety - cfg = car.CarParams.SafetyConfig(**dataclasses.asdict(self.CP.safetyConfigs[-1])) + cfg = self.CP.safetyConfigs[-1] set_status = self.safety.set_safety_hooks(cfg.safetyModel.raw, cfg.safetyParam) self.assertEqual(0, set_status, f"failed to set safetyModel {cfg}") self.safety.init_tests() @@ -204,65 +178,61 @@ def test_car_params(self): # make sure car params are within a valid range self.assertGreater(self.CP.mass, 1) - if self.CP.steerControlType != structs.CarParams.SteerControlType.angle: + if self.CP.steerControlType != SteerControlType.angle: tuning = self.CP.lateralTuning.which() if tuning == 'pid': self.assertTrue(len(self.CP.lateralTuning.pid.kpV)) elif tuning == 'torque': - self.assertTrue(self.CP.lateralTuning.torque.kf > 0) + self.assertTrue(self.CP.lateralTuning.torque.latAccelFactor > 0) else: raise Exception("unknown tuning") def test_car_interface(self): # TODO: also check for checksum violations from can parser can_invalid_cnt = 0 - can_valid = False - CC = structs.CarControl() + CC = structs.CarControl().as_reader() for i, msg in enumerate(self.can_msgs): - CS = self.CI.update(can_capnp_to_list((msg.as_builder().to_bytes(),))) - self.CI.apply(CC, msg.logMonoTime) - - if CS.canValid: - can_valid = True + CS = self.CI.update(msg) + self.CI.apply(CC, msg[0]) # wait max of 2s for low frequency msgs to be seen - if i > 200 or can_valid: + if i > 250: can_invalid_cnt += not CS.canValid self.assertEqual(can_invalid_cnt, 0) def test_radar_interface(self): - RI = self.RadarInterface(self.CP) + RI = self.CarInterface.RadarInterface(self.CP) assert RI # Since OBD port is multiplexed to bus 1 (commonly radar bus) while fingerprinting, # start parsing CAN messages after we've left ELM mode and can expect CAN traffic error_cnt = 0 for i, msg in enumerate(self.can_msgs[self.elm_frame:]): - rr: structs.RadarData | None = RI.update(can_capnp_to_list((msg.as_builder().to_bytes(),))) + rr: structs.RadarData | None = RI.update(msg) if rr is not None and i > 50: - error_cnt += structs.RadarData.Error.canError in rr.errors + error_cnt += rr.errors.canError self.assertEqual(error_cnt, 0) def test_panda_safety_rx_checks(self): if self.CP.dashcamOnly: self.skipTest("no need to check panda safety for dashcamOnly") - start_ts = self.can_msgs[0].logMonoTime + start_ts = self.can_msgs[0][0] failed_addrs = Counter() for can in self.can_msgs: # update panda timer - t = (can.logMonoTime - start_ts) / 1e3 + t = (can[0] - start_ts) / 1e3 self.safety.set_timer(int(t)) # run all msgs through the safety RX hook - for msg in can.can: + for msg in can[1]: if msg.src >= 64: continue - to_send = libpanda_py.make_CANPacket(msg.address, msg.src % 4, msg.dat) + to_send = libsafety_py.make_CANPacket(msg.address, msg.src % 4, msg.dat) if self.safety.safety_rx_hook(to_send) != 1: failed_addrs[hex(msg.address)] += 1 @@ -287,13 +257,16 @@ def test_panda_safety_rx_checks(self): def test_panda_safety_tx_cases(self, data=None): """Asserts we can tx common messages""" + if self.CP.dashcamOnly: + self.skipTest("no need to check panda safety for dashcamOnly") + if self.CP.notCar: self.skipTest("Skipping test for notCar") def test_car_controller(car_control): now_nanos = 0 msgs_sent = 0 - CI = self.CarInterface(self.CP, self.CarController, self.CarState) + CI = self.CarInterface(self.CP) for _ in range(round(10.0 / DT_CTRL)): # make sure we hit the slowest messages CI.update([]) _, sendcan = CI.apply(car_control, now_nanos) @@ -301,7 +274,7 @@ def test_car_controller(car_control): now_nanos += DT_CTRL * 1e9 msgs_sent += len(sendcan) for addr, dat, bus in sendcan: - to_send = libpanda_py.make_CANPacket(addr, bus % 4, dat) + to_send = libsafety_py.make_CANPacket(addr, bus % 4, dat) self.assertTrue(self.safety.safety_tx_hook(to_send), (addr, dat, bus)) # Make sure we attempted to send messages @@ -309,17 +282,17 @@ def test_car_controller(car_control): # Make sure we can send all messages while inactive CC = structs.CarControl() - test_car_controller(CC) + test_car_controller(CC.as_reader()) # Test cancel + general messages (controls_allowed=False & cruise_engaged=True) self.safety.set_cruise_engaged_prev(True) CC = structs.CarControl(cruiseControl=structs.CarControl.CruiseControl(cancel=True)) - test_car_controller(CC) + test_car_controller(CC.as_reader()) # Test resume + general messages (controls_allowed=True & cruise_engaged=True) self.safety.set_controls_allowed(True) CC = structs.CarControl(cruiseControl=structs.CarControl.CruiseControl(resume=True)) - test_car_controller(CC) + test_car_controller(CC.as_reader()) # Skip stdout/stderr capture with pytest, causes elevated memory usage @pytest.mark.nocapture @@ -341,24 +314,29 @@ def test_panda_safety_carstate_fuzzy(self, data): msg_strategy = st.binary(min_size=size, max_size=size) msgs = data.draw(st.lists(msg_strategy, min_size=20)) - for dat in msgs: + vehicle_speed_seen = self.CP.steerControlType == SteerControlType.angle and not self.CP.notCar + + for n, dat in enumerate(msgs): # due to panda updating state selectively, only edges are expected to match # TODO: warm up CarState with real CAN messages to check edge of both sources # (eg. toyota's gasPressed is the inverse of a signal being set) prev_panda_gas = self.safety.get_gas_pressed_prev() prev_panda_brake = self.safety.get_brake_pressed_prev() prev_panda_regen_braking = self.safety.get_regen_braking_prev() + prev_panda_steering_disengage = self.safety.get_steering_disengage_prev() prev_panda_vehicle_moving = self.safety.get_vehicle_moving() + prev_panda_vehicle_speed_min = self.safety.get_vehicle_speed_min() + prev_panda_vehicle_speed_max = self.safety.get_vehicle_speed_max() prev_panda_cruise_engaged = self.safety.get_cruise_engaged_prev() prev_panda_acc_main_on = self.safety.get_acc_main_on() - to_send = libpanda_py.make_CANPacket(address, bus, dat) + to_send = libsafety_py.make_CANPacket(address, bus, dat) self.safety.safety_rx_hook(to_send) - can = messaging.new_message('can', 1) - can.can = [log.CanData(address=address, dat=dat, src=bus)] - - CS = self.CI.update(can_capnp_to_list((can.to_bytes(),))) + can = [(int(time.monotonic() * 1e9), [CanData(address=address, dat=dat, src=bus)])] + CS = self.CI.update(can) + if n < 5: # CANParser warmup time + continue if self.safety.get_gas_pressed_prev() != prev_panda_gas: self.assertEqual(CS.gasPressed, self.safety.get_gas_pressed_prev()) @@ -375,14 +353,27 @@ def test_panda_safety_carstate_fuzzy(self, data): if self.safety.get_regen_braking_prev() != prev_panda_regen_braking: self.assertEqual(CS.regenBraking, self.safety.get_regen_braking_prev()) - if self.safety.get_vehicle_moving() != prev_panda_vehicle_moving: + if self.safety.get_steering_disengage_prev() != prev_panda_steering_disengage: + self.assertEqual(CS.steeringDisengage, self.safety.get_steering_disengage_prev()) + + if self.safety.get_vehicle_moving() != prev_panda_vehicle_moving and not self.CP.notCar: self.assertEqual(not CS.standstill, self.safety.get_vehicle_moving()) - if not (self.CP.carName == "honda" and not (self.CP.flags & HondaFlags.BOSCH)): + # check vehicle speed if angle control car or available + if self.safety.get_vehicle_speed_min() > 0 or self.safety.get_vehicle_speed_max() > 0: + vehicle_speed_seen = True + + if vehicle_speed_seen and (self.safety.get_vehicle_speed_min() != prev_panda_vehicle_speed_min or + self.safety.get_vehicle_speed_max() != prev_panda_vehicle_speed_max): + v_ego_raw = CS.vEgoRaw / self.CP.wheelSpeedFactor + self.assertFalse(v_ego_raw > (self.safety.get_vehicle_speed_max() + 1e-3) or + v_ego_raw < (self.safety.get_vehicle_speed_min() - 1e-3)) + + if not (self.CP.brand == "honda" and not (self.CP.flags & HondaFlags.BOSCH)): if self.safety.get_cruise_engaged_prev() != prev_panda_cruise_engaged: self.assertEqual(CS.cruiseState.enabled, self.safety.get_cruise_engaged_prev()) - if self.CP.carName == "honda": + if self.CP.brand == "honda": if self.safety.get_acc_main_on() != prev_panda_acc_main_on: self.assertEqual(CS.cruiseState.available, self.safety.get_acc_main_on()) @@ -395,21 +386,21 @@ def test_panda_safety_carstate(self): # warm up pass, as initial states may be different for can in self.can_msgs[:300]: - self.CI.update(can_capnp_to_list((can.as_builder().to_bytes(), ))) - for msg in filter(lambda m: m.src in range(64), can.can): - to_send = libpanda_py.make_CANPacket(msg.address, msg.src % 4, msg.dat) + self.CI.update(can) + for msg in filter(lambda m: m.src < 64, can[1]): + to_send = libsafety_py.make_CANPacket(msg.address, msg.src % 4, msg.dat) self.safety.safety_rx_hook(to_send) controls_allowed_prev = False CS_prev = car.CarState.new_message() checks = defaultdict(int) - card = Car(CI=self.CI) + vehicle_speed_seen = self.CP.steerControlType == SteerControlType.angle and not self.CP.notCar for idx, can in enumerate(self.can_msgs): - CS = convert_to_capnp(self.CI.update(can_capnp_to_list((can.as_builder().to_bytes(), )))) - for msg in filter(lambda m: m.src in range(64), can.can): - to_send = libpanda_py.make_CANPacket(msg.address, msg.src % 4, msg.dat) + CS = self.CI.update(can).as_reader() + for msg in filter(lambda m: m.src < 64, can[1]): + to_send = libsafety_py.make_CANPacket(msg.address, msg.src % 4, msg.dat) ret = self.safety.safety_rx_hook(to_send) - self.assertEqual(1, ret, f"safety rx failed ({ret=}): {to_send}") + self.assertEqual(1, ret, f"safety rx failed ({ret=}): {(msg.address, msg.src % 4)}") # Skip first frame so CS_prev is properly initialized if idx == 0: @@ -422,7 +413,16 @@ def test_panda_safety_carstate(self): # TODO: check rest of panda's carstate (steering, ACC main on, etc.) checks['gasPressed'] += CS.gasPressed != self.safety.get_gas_pressed_prev() - checks['standstill'] += CS.standstill == self.safety.get_vehicle_moving() + checks['standstill'] += (CS.standstill == self.safety.get_vehicle_moving()) and not self.CP.notCar + + # check vehicle speed if angle control car or available + if self.safety.get_vehicle_speed_min() > 0 or self.safety.get_vehicle_speed_max() > 0: + vehicle_speed_seen = True + + if vehicle_speed_seen: + v_ego_raw = CS.vEgoRaw / self.CP.wheelSpeedFactor + checks['vEgoRaw'] += (v_ego_raw > (self.safety.get_vehicle_speed_max() + 1e-3) or + v_ego_raw < (self.safety.get_vehicle_speed_min() - 1e-3)) # TODO: remove this exception once this mismatch is resolved brake_pressed = CS.brakePressed @@ -431,12 +431,13 @@ def test_panda_safety_carstate(self): brake_pressed = False checks['brakePressed'] += brake_pressed != self.safety.get_brake_pressed_prev() checks['regenBraking'] += CS.regenBraking != self.safety.get_regen_braking_prev() + checks['steeringDisengage'] += CS.steeringDisengage != self.safety.get_steering_disengage_prev() if self.CP.pcmCruise: # On most pcmCruise cars, openpilot's state is always tied to the PCM's cruise state. # On Honda Nidec, we always engage on the rising edge of the PCM cruise state, but # openpilot brakes to zero even if the min ACC speed is non-zero (i.e. the PCM disengages). - if self.CP.carName == "honda" and not (self.CP.flags & HondaFlags.BOSCH): + if self.CP.brand == "honda" and not (self.CP.flags & HondaFlags.BOSCH): # only the rising edges are expected to match if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled: checks['controlsAllowed'] += not self.safety.get_controls_allowed() @@ -447,18 +448,15 @@ def test_panda_safety_carstate(self): if not self.CP.notCar: checks['cruiseState'] += CS.cruiseState.enabled != self.safety.get_cruise_engaged_prev() else: - # Check for enable events on rising edge of controls allowed - card.update_events(CS) - card.CS_prev = CS - button_enable = (any(evt.enable for evt in CS.events) and - not any(evt == EventName.pedalPressed for evt in card.events.names)) + # Check for user button enable on rising edge of controls allowed + button_enable = CS.buttonEnable and (not CS.brakePressed or CS.standstill) mismatch = button_enable != (self.safety.get_controls_allowed() and not controls_allowed_prev) checks['controlsAllowed'] += mismatch controls_allowed_prev = self.safety.get_controls_allowed() if button_enable and not mismatch: self.safety.set_controls_allowed(False) - if self.CP.carName == "honda": + if self.CP.brand == "honda": checks['mainOn'] += CS.cruiseState.available != self.safety.get_acc_main_on() CS_prev = CS @@ -466,11 +464,6 @@ def test_panda_safety_carstate(self): failed_checks = {k: v for k, v in checks.items() if v > 0} self.assertFalse(len(failed_checks), f"panda safety doesn't agree with openpilot: {failed_checks}") - @unittest.skipIf(not CI, "Accessing non CI-bucket routes is allowed only when not in CI") - def test_route_on_ci_bucket(self): - self.assertTrue(self.test_route_on_bucket, "Route not on CI bucket. " + - "This is fine to fail for WIP car ports, just let us know and we can upload your routes to the CI bucket.") - @parameterized_class(('platform', 'test_route'), get_test_cases()) @pytest.mark.xdist_group_class_property('test_route') diff --git a/selfdrive/car/tests/test_preap_engage_max_after_pause.py b/selfdrive/car/tests/test_preap_engage_max_after_pause.py new file mode 100644 index 00000000000000..7ce6989f03e9f8 --- /dev/null +++ b/selfdrive/car/tests/test_preap_engage_max_after_pause.py @@ -0,0 +1,187 @@ +"""MAX on the first frame of a one-SET resume after a One-Pedal gas pause. + +Sep 25 10:43:32–10:43:59 CT: MAX 70, gas takeover paused long, the driver +took a highway exit and a sharp low-speed turn on gas (map dropped out), +then accelerated to ~39 mph and pressed SET with the gas still down. +The temporary curve cap had pulled HUD MAX to 14.4 mph during the pause +and was ramping back at the restore rate. On the resume frame that ramp +value overrode the held-MAX seed and was written onto the pedal set +speed: MAX published 16.7 mph at 39 mph. + +The curve cap exists to slow OP's own long control through a bend. While +long is paused the driver owns speed, so the cap must not rewrite MAX, +and a resume must publish the held MAX (dropout holds MAX) on its first +frame. +""" +import types +from types import SimpleNamespace + +import pytest + +from opendbc.car import DT_CTRL +from openpilot.common.constants import CV +from openpilot.selfdrive.car.card import Car +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.selfdrive.controls.lib.curve_max_hold import CurveMaxHold +from openpilot.selfdrive.mapd.constants import ACCEL_DEFAULT, LOOKAHEAD_NORMAL, MODE_FOLLOW +from openpilot.selfdrive.mapd.map_speed_policy import MapCruiseHold + +MPH = CV.MPH_TO_KPH + + +class _Cruise: + def __init__(self): + self.v_cruise_kph = float(V_CRUISE_UNSET) + self.v_cruise_kph_last = 0.0 + self.v_cruise_cluster_kph = float(V_CRUISE_UNSET) + + +class _MapSm: + def __init__(self, md): + self.valid = {"liveMapDataNAP": True} + self._md = md + + def __getitem__(self, key): + if key == "liveMapDataNAP": + return self._md + raise KeyError(key) + + +def _harness(limit_mph: float): + md = SimpleNamespace( + speedLimit=float(limit_mph) * CV.MPH_TO_MS, + speedLimitValid=True, + nextSpeedLimit=0.0, + nextSpeedLimitDistance=0.0, + ) + v = float(limit_mph) * CV.MPH_TO_MS + eng = SimpleNamespace( + _nap_set_resume_long=False, _nap_set_take_speed_now=False, + _nap_held_max_kph=None, pedal_speed_kph=0.0, + ) + inner = SimpleNamespace(engagement=eng, pedal_speed_kph=0.0) + cs = SimpleNamespace( + cruiseState=SimpleNamespace(speed=v, enabled=True), + pedalLongActive=True, enableLongControl=True, + vEgo=v, steeringAngleDeg=0.0, buttonEvents=[], + ) + h = SimpleNamespace( + CS_prev=SimpleNamespace(pedalLongActive=False, cruiseState=SimpleNamespace(speed=v)), + CI=SimpleNamespace(CS=inner), + CP=SimpleNamespace(steerRatio=15.0, wheelbase=2.98), + sm=_MapSm(md), + _map_hold=MapCruiseHold(), + _curve_max=CurveMaxHold(), + _map_slew_ms=None, + _last_pedal_kph=None, + _pedal_self_write_kph=None, + _map_speed_mode=MODE_FOLLOW, + _map_speed_lookahead=LOOKAHEAD_NORMAL, + _map_speed_accel=ACCEL_DEFAULT, + _map_speed_user_offset_kph=0.0, + _map_hypermile_on=False, + _map_step_down_on=False, + v_cruise_helper=_Cruise(), + _maybe_follow_stalk=lambda _cs, raw_kph: (raw_kph, False), + ) + for name in ( + "_preap_engagement", "_preap_set_events", "_adopt_preap_fsm_held_max", + "_publish_preap_held_max", "_curve_cornering", "_live_map_offset_kph", + "_write_preap_pedal_speed", + ): + setattr(h, name, types.MethodType(getattr(Car, name), h)) + h._preap_stalk_set_pressed = Car._preap_stalk_set_pressed + return h, cs, md, eng + + +def _frame(h, cs): + Car._update_preap_map_cruise(h, cs) + h.CS_prev.pedalLongActive = cs.pedalLongActive + h.CS_prev.cruiseState.speed = cs.cruiseState.speed + + +def _run(h, cs, seconds, v_from_mph=None, v_to_mph=None, steer=None): + n = max(1, int(round(seconds / DT_CTRL))) + for i in range(n): + if v_from_mph is not None: + cs.vEgo = (v_from_mph + (v_to_mph - v_from_mph) * (i + 1) / n) * CV.MPH_TO_MS + if steer is not None: + cs.steeringAngleDeg = steer(i / n) + if not cs.enableLongControl: + # Pause publishes cruiseState.speed as 0 / ego, never MAX. + cs.cruiseState.speed = 0.0 + _frame(h, cs) + + +def _pause_turn_and_resume_with_gas(h, cs, md, eng): + # Engaged at a 70 mph posted limit (Follow): MAX 70. + _run(h, cs, 2.0) + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(70.0 * MPH, abs=0.3) + # Gas takeover: One-Pedal pause (software long off, session and lat on). + cs.enableLongControl = False + cs.pedalLongActive = False + _run(h, cs, 1.0, 48.0, 45.0) + # Exit ramp bend on gas, then decelerating into a sharp turn. + _run(h, cs, 2.0, 45.0, 30.0, steer=lambda _x: 20.0) + _run(h, cs, 2.0, 30.0, 12.0, steer=lambda _x: 0.0) + # Map drops out in the sharp low-speed turn (steer ~130°). + md.speedLimitValid = False + h.sm.valid["liveMapDataNAP"] = False + _run(h, cs, 5.0, 11.0, 13.0, steer=lambda _x: 135.0) + # Straighten and accelerate on gas to ~39 mph. + _run(h, cs, 1.5, 13.0, 22.0, steer=lambda x: 135.0 * (1.0 - x)) + _run(h, cs, 4.5, 22.0, 39.0, steer=lambda _x: 0.0) + # One SET with gas still pressed: the FSM restores its held MAX onto the + # pedal and flags resume-held for card on this frame. + held = eng._nap_held_max_kph + eng._nap_set_resume_long = True + if held is not None: + eng.pedal_speed_kph = float(held) + cs.enableLongControl = True + cs.pedalLongActive = False # authority acquires on gas lift + cs.cruiseState.speed = float(eng.pedal_speed_kph) * CV.KPH_TO_MS + _frame(h, cs) + return held + + +def test_resume_with_gas_after_pause_turn_publishes_held_max_first_frame(): + h, cs, md, eng = _harness(70.0) + held = _pause_turn_and_resume_with_gas(h, cs, md, eng) + # Map dropout holds MAX: the held 70 comes back, on the first frame. + assert held == pytest.approx(70.0 * MPH, abs=0.3) + first = h.v_cruise_helper.v_cruise_kph + assert first == pytest.approx(70.0 * MPH, abs=0.3) + assert cs.cruiseState.speed * CV.MS_TO_KPH == pytest.approx(70.0 * MPH, abs=0.3) + assert eng._nap_held_max_kph == pytest.approx(70.0 * MPH, abs=0.3) + # And it stays there (no stale seed a frame later). + cs.pedalLongActive = False + _run(h, cs, 0.5) + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(70.0 * MPH, abs=0.3) + + +def test_paused_long_curve_does_not_rewrite_hud_max(): + """The driver owns speed in a pause. A bend does not drag HUD MAX down.""" + h, cs, md, eng = _harness(70.0) + _run(h, cs, 2.0) + cs.enableLongControl = False + cs.pedalLongActive = False + lowest = float("inf") + n = int(round(3.0 / DT_CTRL)) + for _ in range(n): + cs.vEgo = 12.0 * CV.MPH_TO_MS + cs.steeringAngleDeg = 135.0 + cs.cruiseState.speed = 0.0 + _frame(h, cs) + lowest = min(lowest, h.v_cruise_helper.v_cruise_kph) + assert lowest == pytest.approx(70.0 * MPH, abs=0.3) + assert eng._nap_held_max_kph == pytest.approx(70.0 * MPH, abs=0.3) + + +def test_engaged_curve_still_caps_and_restores(): + """Under OP long the temporary bend cap still lowers MAX and restores it.""" + h, cs, md, eng = _harness(70.0) + _run(h, cs, 2.0) + _run(h, cs, 2.0, 40.0, 40.0, steer=lambda _x: 30.0) + assert h.v_cruise_helper.v_cruise_kph < 60.0 * MPH + _run(h, cs, 40.0, 40.0, 40.0, steer=lambda _x: 0.0) + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(70.0 * MPH, abs=0.3) diff --git a/selfdrive/controls/.gitignore b/selfdrive/controls/.gitignore deleted file mode 100644 index 22a371d8ffdd18..00000000000000 --- a/selfdrive/controls/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -calibration_param -traces diff --git a/selfdrive/controls/controlsd.py b/selfdrive/controls/controlsd.py old mode 100755 new mode 100644 index c3f1b9ba7ee6fb..9c6eca9ed2d5cf --- a/selfdrive/controls/controlsd.py +++ b/selfdrive/controls/controlsd.py @@ -1,527 +1,271 @@ #!/usr/bin/env python3 -import os import math -import time -import threading -from typing import SupportsFloat - -import cereal.messaging as messaging +from numbers import Number from cereal import car, log -from msgq.visionipc import VisionIpcClient, VisionStreamType - - -from openpilot.common.conversions import Conversions as CV -from openpilot.common.git import get_short_branch -from openpilot.common.numpy_fast import clip +import cereal.messaging as messaging +from openpilot.common.constants import CV from openpilot.common.params import Params -from openpilot.common.realtime import config_realtime_process, Priority, Ratekeeper, DT_CTRL +from openpilot.common.realtime import config_realtime_process, DT_CTRL, Priority, Ratekeeper from openpilot.common.swaglog import cloudlog -from openpilot.common.gps import get_gps_location_service -from opendbc.car.car_helpers import get_car_interface -from openpilot.selfdrive.controls.lib.alertmanager import AlertManager, set_offroad_alert -from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature, get_startup_event -from openpilot.selfdrive.controls.lib.events import Events, ET -from openpilot.selfdrive.controls.lib.latcontrol import LatControl, MIN_LATERAL_CONTROL_SPEED +from opendbc.car.car_helpers import interfaces +from opendbc.car.vehicle_model import VehicleModel +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import BlinkerLateralHold, lat_active_with_blinker_pause +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + PARAM_DRIVER_LAT_HANDOFF, DriverLateralHandoff, apply_lat_authority, + cs_hands_on_level, cs_real_brake_pressed, handoff_enabled, + handoff_new_desired_curvature, lat_active_after_handoff, + pin_desired_curvature_to_measured) +from opendbc.car.tesla.preap.lat_yield import UNDERTRACK_CURVATURE, roundabout_yield_context +from openpilot.selfdrive.controls.lib.cone_line_hold import PARAM_CONE_LINE_HOLD, ConeLineHold, lane_offset_from_model, lookahead_m +from openpilot.selfdrive.controls.lib.lat_low_visibility import ( + PARAM_LOW_VIS_BACKOFF, LowVisibility, fade_curvature, sun_ahead_from_fix) +from openpilot.selfdrive.controls.lib.radar_path_gate import model_path_xy +from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper +from openpilot.selfdrive.controls.lib.lane_change_nudge import TippedLaneChangeTorque +from openpilot.selfdrive.controls.lib.lane_change_turn import LaneChangeTurnHold, blinker_with_turn_hold +from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature +from openpilot.selfdrive.controls.lib.lat_turn_geometry import ( + PARAM_TURN_GEOMETRY, is_preap_car, turn_geometry_active, +) +from openpilot.selfdrive.mapd.roundabout import ( + live_map_roundabout_hint, roundabout_lateral_curvature_bias, +) +from openpilot.selfdrive.controls.lib.roundabout_guide import RoundaboutAssist +from openpilot.selfdrive.controls.lib.latcontrol import LatControl from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle, STEER_ANGLE_SATURATION_THRESHOLD from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque +from openpilot.selfdrive.controls.lib.gap_lock import slack_for_guard from openpilot.selfdrive.controls.lib.longcontrol import LongControl -from openpilot.selfdrive.controls.lib.vehicle_model import VehicleModel +from openpilot.selfdrive.controls.lib.preap_driver_brake import ( + driver_brake_applied, + preap_longitudinal_active, + preap_pedal_long, + published_long_accel, +) +from openpilot.selfdrive.modeld.modeld import LAT_SMOOTH_SECONDS from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose -from openpilot.system.hardware import HARDWARE - -SOFT_DISABLE_TIME = 3 # seconds -LDW_MIN_SPEED = 31 * CV.MPH_TO_MS -LANE_DEPARTURE_THRESHOLD = 0.1 -CAMERA_OFFSET = 0.04 - -REPLAY = "REPLAY" in os.environ -SIMULATION = "SIMULATION" in os.environ -TESTING_CLOSET = "TESTING_CLOSET" in os.environ -IGNORE_PROCESSES = {"loggerd", "encoderd", "statsd"} - -ThermalStatus = log.DeviceState.ThermalStatus State = log.SelfdriveState.OpenpilotState -PandaType = log.PandaState.PandaType -Desire = log.Desire LaneChangeState = log.LaneChangeState -LaneChangeDirection = log.LaneChangeDirection -EventName = car.OnroadEvent.EventName -ButtonType = car.CarState.ButtonEvent.Type -SafetyModel = car.CarParams.SafetyModel -IGNORED_SAFETY_MODES = (SafetyModel.silent, SafetyModel.noOutput) -CSID_MAP = {"1": EventName.roadCameraError, "2": EventName.wideRoadCameraError, "0": EventName.driverCameraError} ACTUATOR_FIELDS = tuple(car.CarControl.Actuators.schema.fields.keys()) -ACTIVE_STATES = (State.enabled, State.softDisabling, State.overriding) -ENABLED_STATES = (State.preEnabled, *ACTIVE_STATES) class Controls: - def __init__(self, CI=None): + def __init__(self) -> None: self.params = Params() - - if CI is None: - cloudlog.info("controlsd is waiting for CarParams") - self.CP = messaging.log_from_bytes(self.params.get("CarParams", block=True), car.CarParams) - cloudlog.info("controlsd got CarParams") - - # Uses car interface helper functions, altering state won't be considered by card for actuation - self.CI = get_car_interface(self.CP) - else: - self.CI, self.CP = CI, CI.CP - - # Ensure the current branch is cached, otherwise the first iteration of controlsd lags - self.branch = get_short_branch() - - # Setup sockets - self.pm = messaging.PubMaster(['selfdriveState', 'controlsState', 'carControl', 'onroadEvents']) - - self.gps_location_service = get_gps_location_service(self.params) - self.gps_packets = [self.gps_location_service] - self.sensor_packets = ["accelerometer", "gyroscope"] - self.camera_packets = ["roadCameraState", "driverCameraState", "wideRoadCameraState"] - - self.log_sock = messaging.sub_sock('androidLog') - - # TODO: de-couple controlsd with card/conflate on carState without introducing controls mismatches - self.car_state_sock = messaging.sub_sock('carState', timeout=20) - - ignore = self.sensor_packets + self.gps_packets + ['testJoystick'] - if SIMULATION: - ignore += ['driverCameraState', 'managerState'] - if REPLAY: - # no vipc in replay will make them ignored anyways - ignore += ['roadCameraState', 'wideRoadCameraState'] - self.sm = messaging.SubMaster(['deviceState', 'pandaStates', 'peripheralState', 'modelV2', 'liveCalibration', - 'carOutput', 'driverMonitoringState', 'longitudinalPlan', 'livePose', - 'managerState', 'liveParameters', 'radarState', 'liveTorqueParameters', - 'testJoystick'] + self.camera_packets + self.sensor_packets + self.gps_packets, - ignore_alive=ignore, ignore_avg_freq=ignore+['radarState', 'testJoystick'], ignore_valid=['testJoystick', ], - frequency=int(1/DT_CTRL)) - - self.joystick_mode = self.params.get_bool("JoystickDebugMode") - - # read params - self.is_metric = self.params.get_bool("IsMetric") - self.is_ldw_enabled = self.params.get_bool("IsLdwEnabled") - - # detect sound card presence and ensure successful init - sounds_available = HARDWARE.get_sound_card_online() - - car_recognized = self.CP.carName != 'mock' - - # cleanup old params - if not self.CP.experimentalLongitudinalAvailable: - self.params.remove("ExperimentalLongitudinalEnabled") - if not self.CP.openpilotLongitudinalControl: - self.params.remove("ExperimentalMode") - - self.CS_prev = car.CarState.new_message() - self.AM = AlertManager() - self.events = Events() + cloudlog.info("controlsd is waiting for CarParams") + self.CP = messaging.log_from_bytes(self.params.get("CarParams", block=True), car.CarParams) + cloudlog.info("controlsd got CarParams") + + self.CI = interfaces[self.CP.carFingerprint](self.CP) + + self.sm = messaging.SubMaster(['liveDelay', 'liveParameters', 'liveTorqueParameters', 'modelV2', 'selfdriveState', + 'liveCalibration', 'livePose', 'longitudinalPlan', 'lateralManeuverPlan', 'carState', 'carOutput', + 'driverMonitoringState', 'onroadEvents', 'driverAssistance', 'liveMapDataNAP', 'radarState', + 'gpsLocation', 'gpsLocationExternal', 'roadCameraState', 'coneLineNAP'], poll='selfdriveState', + ignore_alive=['roadCameraState', 'coneLineNAP'], + ignore_avg_freq=['roadCameraState', 'coneLineNAP'], + ignore_valid=['roadCameraState', 'coneLineNAP']) + self.pm = messaging.PubMaster(['carControl', 'controlsState']) + + self.steer_limited_by_safety = False + self._turn_geom_preap = is_preap_car(self.CP) + self._turn_geom_active = False + self._turn_geom_param_frame = -1 + # Roundabout Steering Assist (NAPRoundaboutAssist, Pre-AP only, default Off). + self.rb_assist = RoundaboutAssist(self._turn_geom_preap, self.params) + self.curvature = 0.0 + self.desired_curvature = 0.0 + self.blinker_lat_hold = BlinkerLateralHold() + self._lane_change_torque = TippedLaneChangeTorque() + # Lane change -> driver turn: blinker hold + manual-turn lat pause. + self._lane_change_turn = LaneChangeTurnHold() + self._lat_active_prev = False + # Default On (NAPDriverLatHandoff=1) for Pre-AP. Re-read each cycle so + # Settings → NAP can turn it Off immediately if gravel/wind misbehave. + self.lat_handoff = DriverLateralHandoff( + enabled=handoff_enabled( + fingerprint=self.CP.carFingerprint, + param_on=bool(self.params.get_bool(PARAM_DRIVER_LAT_HANDOFF)))) + self._lat_handoff = self.lat_handoff.update( + engaged=False, lat_would_be_active=False, + steering_torque=0.0, steering_rate_deg=0.0) + # napStalkSeq rides the carState subscription above. Do not add another. + self._nap_stalk_seq = 0 + self._nap_stalk_seen = False + # Low-visibility fade. Default On. Does not touch longitudinal. + self.low_vis = LowVisibility() + self._low_vis = self.low_vis.update(enabled=False) + self._raw_model_curvature = 0.0 + # Previous cycle's yield context. Card sends the same bits to panda + # after this loop, so the next hands edge sees what panda already has. + self._cmd_angle_prev = None + self._under_prev = False + self._rb_yield_prev = False + # Cone-line offset hold. Default On. Identity until a real push. + self.cone_hold = ConeLineHold() + self._cone_zone = False + self._cone_out = self.cone_hold.update( + enabled=False, engaged=False, cone=None, torque_nm=0.0, measured_k=0.0, + model_k=0.0, path_x=None, path_y=None, v_ego=0.0, yielded=False, + lat_active=False, dt=DT_CTRL) self.pose_calibrator = PoseCalibrator() - self.calibrated_pose: Pose|None = None + self.calibrated_pose: Pose | None = None self.LoC = LongControl(self.CP) self.VM = VehicleModel(self.CP) - self.LaC: LatControl if self.CP.steerControlType == car.CarParams.SteerControlType.angle: - self.LaC = LatControlAngle(self.CP, self.CI) + self.LaC = LatControlAngle(self.CP, self.CI, DT_CTRL) elif self.CP.lateralTuning.which() == 'pid': - self.LaC = LatControlPID(self.CP, self.CI) + self.LaC = LatControlPID(self.CP, self.CI, DT_CTRL) elif self.CP.lateralTuning.which() == 'torque': - self.LaC = LatControlTorque(self.CP, self.CI) - - self.initialized = False - self.state = State.disabled - self.enabled = False - self.active = False - self.soft_disable_timer = 0 - self.mismatch_counter = 0 - self.cruise_mismatch_counter = 0 - self.last_blinker_frame = 0 - self.last_steering_pressed_frame = 0 - self.distance_traveled = 0 - self.last_functional_fan_frame = 0 - self.events_prev = [] - self.current_alert_types = [ET.PERMANENT] - self.logged_comm_issue = None - self.not_running_prev = None - self.steer_limited = False - self.desired_curvature = 0.0 - self.experimental_mode = False - self.personality = self.read_personality_param() - self.recalibrating_seen = False - - self.can_log_mono_time = 0 - - self.startup_event = get_startup_event(car_recognized, not self.CP.passive, len(self.CP.carFw) > 0) + self.LaC = LatControlTorque(self.CP, self.CI, DT_CTRL) - if not sounds_available: - self.events.add(EventName.soundsUnavailable, static=True) - if not car_recognized: - self.events.add(EventName.carUnrecognized, static=True) - if len(self.CP.carFw) > 0: - set_offroad_alert("Offroad_CarUnrecognized", True) - else: - set_offroad_alert("Offroad_NoFirmware", True) - elif self.CP.passive: - self.events.add(EventName.dashcamMode, static=True) - - # controlsd is driven by carState, expected at 100Hz - self.rk = Ratekeeper(100, print_delay_threshold=None) - - def set_initial_state(self): - if REPLAY and any(ps.controlsAllowed for ps in self.sm['pandaStates']): - self.state = State.enabled - - def update_events(self, CS): - """Compute onroadEvents from carState""" - - self.events.clear() - - # Add joystick event, static on cars, dynamic on nonCars - if self.joystick_mode: - self.events.add(EventName.joystickDebug) - self.startup_event = None - - # Add startup event - if self.startup_event is not None: - self.events.add(self.startup_event) - self.startup_event = None - - # Don't add any more events if not initialized - if not self.initialized: - self.events.add(EventName.controlsInitializing) - return - - # no more events while in dashcam mode - if self.CP.passive: - return - - # Block resume if cruise never previously enabled - resume_pressed = any(be.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for be in CS.buttonEvents) - if not self.CP.pcmCruise and CS.vCruise > 250 and resume_pressed: - self.events.add(EventName.resumeBlocked) - - if not self.CP.notCar: - self.events.add_from_msg(self.sm['driverMonitoringState'].events) - - # Add car events, ignore if CAN isn't valid - if CS.canValid: - self.events.add_from_msg(CS.events) - - # Create events for temperature, disk space, and memory - if self.sm['deviceState'].thermalStatus >= ThermalStatus.red: - self.events.add(EventName.overheat) - if self.sm['deviceState'].freeSpacePercent < 7 and not SIMULATION: - # under 7% of space free no enable allowed - self.events.add(EventName.outOfSpace) - if self.sm['deviceState'].memoryUsagePercent > 90 and not SIMULATION: - self.events.add(EventName.lowMemory) - - # TODO: enable this once loggerd CPU usage is more reasonable - #cpus = list(self.sm['deviceState'].cpuUsagePercent) - #if max(cpus, default=0) > 95 and not SIMULATION: - # self.events.add(EventName.highCpuUsage) - - # Alert if fan isn't spinning for 5 seconds - if self.sm['peripheralState'].pandaType != log.PandaState.PandaType.unknown: - if self.sm['peripheralState'].fanSpeedRpm < 500 and self.sm['deviceState'].fanSpeedPercentDesired > 50: - # allow enough time for the fan controller in the panda to recover from stalls - if (self.sm.frame - self.last_functional_fan_frame) * DT_CTRL > 15.0: - self.events.add(EventName.fanMalfunction) - else: - self.last_functional_fan_frame = self.sm.frame - - # Handle calibration status - cal_status = self.sm['liveCalibration'].calStatus - if cal_status != log.LiveCalibrationData.Status.calibrated: - if cal_status == log.LiveCalibrationData.Status.uncalibrated: - self.events.add(EventName.calibrationIncomplete) - elif cal_status == log.LiveCalibrationData.Status.recalibrating: - if not self.recalibrating_seen: - set_offroad_alert("Offroad_Recalibration", True) - self.recalibrating_seen = True - self.events.add(EventName.calibrationRecalibrating) - else: - self.events.add(EventName.calibrationInvalid) - - # Handle lane change - if self.sm['modelV2'].meta.laneChangeState == LaneChangeState.preLaneChange: - direction = self.sm['modelV2'].meta.laneChangeDirection - if (CS.leftBlindspot and direction == LaneChangeDirection.left) or \ - (CS.rightBlindspot and direction == LaneChangeDirection.right): - self.events.add(EventName.laneChangeBlocked) - else: - if direction == LaneChangeDirection.left: - self.events.add(EventName.preLaneChangeLeft) - else: - self.events.add(EventName.preLaneChangeRight) - elif self.sm['modelV2'].meta.laneChangeState in (LaneChangeState.laneChangeStarting, - LaneChangeState.laneChangeFinishing): - self.events.add(EventName.laneChange) - - for i, pandaState in enumerate(self.sm['pandaStates']): - # All pandas must match the list of safetyConfigs, and if outside this list, must be silent or noOutput - if i < len(self.CP.safetyConfigs): - safety_mismatch = pandaState.safetyModel != self.CP.safetyConfigs[i].safetyModel or \ - pandaState.safetyParam != self.CP.safetyConfigs[i].safetyParam or \ - pandaState.alternativeExperience != self.CP.alternativeExperience - else: - safety_mismatch = pandaState.safetyModel not in IGNORED_SAFETY_MODES - - # safety mismatch allows some time for pandad to set the safety mode and publish it back from panda - if (safety_mismatch and self.sm.frame*DT_CTRL > 10.) or pandaState.safetyRxChecksInvalid or self.mismatch_counter >= 200: - self.events.add(EventName.controlsMismatch) - - if log.PandaState.FaultType.relayMalfunction in pandaState.faults: - self.events.add(EventName.relayMalfunction) - - # Handle HW and system malfunctions - # Order is very intentional here. Be careful when modifying this. - # All events here should at least have NO_ENTRY and SOFT_DISABLE. - num_events = len(self.events) - - not_running = {p.name for p in self.sm['managerState'].processes if not p.running and p.shouldBeRunning} - if self.sm.recv_frame['managerState'] and (not_running - IGNORE_PROCESSES): - self.events.add(EventName.processNotRunning) - if not_running != self.not_running_prev: - cloudlog.event("process_not_running", not_running=not_running, error=True) - self.not_running_prev = not_running - else: - if not SIMULATION and not self.rk.lagging: - if not self.sm.all_alive(self.camera_packets): - self.events.add(EventName.cameraMalfunction) - elif not self.sm.all_freq_ok(self.camera_packets): - self.events.add(EventName.cameraFrameRate) - if not REPLAY and self.rk.lagging: - self.events.add(EventName.controlsdLagging) - if len(self.sm['radarState'].radarErrors) or ((not self.rk.lagging or REPLAY) and not self.sm.all_checks(['radarState'])): - self.events.add(EventName.radarFault) - if not self.sm.valid['pandaStates']: - self.events.add(EventName.usbError) - if CS.canTimeout: - self.events.add(EventName.canBusMissing) - elif not CS.canValid: - self.events.add(EventName.canError) - - # generic catch-all. ideally, a more specific event should be added above instead - has_disable_events = self.events.contains(ET.NO_ENTRY) and (self.events.contains(ET.SOFT_DISABLE) or self.events.contains(ET.IMMEDIATE_DISABLE)) - no_system_errors = (not has_disable_events) or (len(self.events) == num_events) - if not self.sm.all_checks() and no_system_errors: - if not self.sm.all_alive(): - self.events.add(EventName.commIssue) - elif not self.sm.all_freq_ok(): - self.events.add(EventName.commIssueAvgFreq) - else: - self.events.add(EventName.commIssue) - - logs = { - 'invalid': [s for s, valid in self.sm.valid.items() if not valid], - 'not_alive': [s for s, alive in self.sm.alive.items() if not alive], - 'not_freq_ok': [s for s, freq_ok in self.sm.freq_ok.items() if not freq_ok], - } - if logs != self.logged_comm_issue: - cloudlog.event("commIssue", error=True, **logs) - self.logged_comm_issue = logs - else: - self.logged_comm_issue = None - - if not (self.CP.notCar and self.joystick_mode): - if not self.sm['livePose'].posenetOK: - self.events.add(EventName.posenetInvalid) - if not self.sm['livePose'].inputsOK: - self.events.add(EventName.locationdTemporaryError) - if not self.sm['liveParameters'].valid and not TESTING_CLOSET and (not SIMULATION or REPLAY): - self.events.add(EventName.paramsdTemporaryError) - - # conservative HW alert. if the data or frequency are off, locationd will throw an error - if any((self.sm.frame - self.sm.recv_frame[s])*DT_CTRL > 10. for s in self.sensor_packets): - self.events.add(EventName.sensorDataInvalid) - - if not REPLAY: - # Check for mismatch between openpilot and car's PCM - cruise_mismatch = CS.cruiseState.enabled and (not self.enabled or not self.CP.pcmCruise) - self.cruise_mismatch_counter = self.cruise_mismatch_counter + 1 if cruise_mismatch else 0 - if self.cruise_mismatch_counter > int(6. / DT_CTRL): - self.events.add(EventName.cruiseMismatch) - - # Check for FCW - stock_long_is_braking = self.enabled and not self.CP.openpilotLongitudinalControl and CS.aEgo < -1.25 - model_fcw = self.sm['modelV2'].meta.hardBrakePredicted and not CS.brakePressed and not stock_long_is_braking - planner_fcw = self.sm['longitudinalPlan'].fcw and self.enabled - if (planner_fcw or model_fcw) and not (self.CP.notCar and self.joystick_mode): - self.events.add(EventName.fcw) - - for m in messaging.drain_sock(self.log_sock, wait_for_one=False): - try: - msg = m.androidLog.message - if any(err in msg for err in ("ERROR_CRC", "ERROR_ECC", "ERROR_STREAM_UNDERFLOW", "APPLY FAILED")): - csid = msg.split("CSID:")[-1].split(" ")[0] - evt = CSID_MAP.get(csid, None) - if evt is not None: - self.events.add(evt) - except UnicodeDecodeError: - pass - - # TODO: fix simulator - if not SIMULATION or REPLAY: - # Not show in first 1.5 km to allow for driving out of garage. This event shows after 5 minutes - gps_ok = self.sm.recv_frame[self.gps_location_service] > 0 and (self.sm.frame - self.sm.recv_frame[self.gps_location_service]) * DT_CTRL < 2.0 - if not gps_ok and self.sm['livePose'].inputsOK and (self.distance_traveled > 1500): - self.events.add(EventName.noGps) - if gps_ok: - self.distance_traveled = 0 - self.distance_traveled += CS.vEgo * DT_CTRL - - if self.sm['modelV2'].frameDropPerc > 20: - self.events.add(EventName.modeldLagging) - - def data_sample(self): - """Receive data from sockets""" - - car_state = messaging.recv_one(self.car_state_sock) - CS = car_state.carState if car_state else self.CS_prev - - self.sm.update(0) - - if not self.initialized: - all_valid = CS.canValid and self.sm.all_checks() - timed_out = self.sm.frame * DT_CTRL > 6. - if all_valid or timed_out or (SIMULATION and not REPLAY): - available_streams = VisionIpcClient.available_streams("camerad", block=False) - if VisionStreamType.VISION_STREAM_ROAD not in available_streams: - self.sm.ignore_alive.append('roadCameraState') - if VisionStreamType.VISION_STREAM_WIDE_ROAD not in available_streams: - self.sm.ignore_alive.append('wideRoadCameraState') - - self.initialized = True - self.set_initial_state() - - cloudlog.event( - "controlsd.initialized", - dt=self.sm.frame*DT_CTRL, - timeout=timed_out, - canValid=CS.canValid, - invalid=[s for s, valid in self.sm.valid.items() if not valid], - not_alive=[s for s, alive in self.sm.alive.items() if not alive], - not_freq_ok=[s for s, freq_ok in self.sm.freq_ok.items() if not freq_ok], - error=True, - ) - - # When the panda and controlsd do not agree on controls_allowed - # we want to disengage openpilot. However the status from the panda goes through - # another socket other than the CAN messages and one can arrive earlier than the other. - # Therefore we allow a mismatch for two samples, then we trigger the disengagement. - if not self.enabled: - self.mismatch_counter = 0 - - # All pandas not in silent mode must have controlsAllowed when openpilot is enabled - if self.enabled and any(not ps.controlsAllowed for ps in self.sm['pandaStates'] - if ps.safetyModel not in IGNORED_SAFETY_MODES): - self.mismatch_counter += 1 - - # calibrate the live pose and save it for later use + def update(self): + self.sm.update(15) if self.sm.updated["liveCalibration"]: self.pose_calibrator.feed_live_calib(self.sm['liveCalibration']) if self.sm.updated["livePose"]: device_pose = Pose.from_live_pose(self.sm['livePose']) self.calibrated_pose = self.pose_calibrator.build_calibrated_pose(device_pose) - return CS - - def state_transition(self, CS): - """Compute conditional state transitions and execute actions on state transitions""" - - # decrement the soft disable timer at every step, as it's reset on - # entrance in SOFT_DISABLING state - self.soft_disable_timer = max(0, self.soft_disable_timer - 1) - - self.current_alert_types = [ET.PERMANENT] - - # ENABLED, SOFT DISABLING, PRE ENABLING, OVERRIDING - if self.state != State.disabled: - # user and immediate disable always have priority in a non-disabled state - if self.events.contains(ET.USER_DISABLE): - self.state = State.disabled - self.current_alert_types.append(ET.USER_DISABLE) - - elif self.events.contains(ET.IMMEDIATE_DISABLE): - self.state = State.disabled - self.current_alert_types.append(ET.IMMEDIATE_DISABLE) + def _update_low_visibility(self, engaged: bool): + """Scale lateral authority when the camera or the model cannot see the road. + Longitudinal is not read or written here. Off (or disengaged) is identity. + """ + try: + param_on = bool(self.params.get_bool(PARAM_LOW_VIS_BACKOFF)) + except Exception: + param_on = True + model = self.sm['modelV2'] + try: + lane_probs = [float(p) for p in model.laneLineProbs] + except Exception: + lane_probs = [] + try: + edge_stds = [float(s) for s in model.roadEdgeStds] + except Exception: + edge_stds = [] + try: + path_t = [float(t) for t in model.position.t] + path_y = [float(y) for y in model.position.yStd] + except Exception: + path_t, path_y = [], [] + integ = None + if self.sm.recv_frame.get('roadCameraState', 0) > 0: + try: + integ = int(self.sm['roadCameraState'].integLines) + except Exception: + integ = None + sun_ahead = False + for key in ('gpsLocationExternal', 'gpsLocation'): + if self.sm.recv_frame.get(key, 0) <= 0: + continue + fix = self.sm[key] + ahead = sun_ahead_from_fix( + latitude=fix.latitude, longitude=fix.longitude, + unix_timestamp_millis=fix.unixTimestampMillis, + bearing_deg=fix.bearingDeg, + horizontal_accuracy_m=fix.horizontalAccuracy) + if ahead is not None: + sun_ahead = bool(ahead) + break + # Same carState subscription controlsd already has. No new socket. + # Measured curvature is self.curvature (steered). Model curvature is + # the desired curvature this loop already reads for the lateral target. + try: + cs = self.sm['carState'] + v_ego = float(cs.vEgo) + blinker = bool(cs.leftBlinker or cs.rightBlinker) + except Exception: + v_ego = 0.0 + blinker = False + try: + if self.sm.valid['lateralManeuverPlan']: + model_k = float(self.sm['lateralManeuverPlan'].desiredCurvature) else: - # ENABLED - if self.state == State.enabled: - if self.events.contains(ET.SOFT_DISABLE): - self.state = State.softDisabling - self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) - self.current_alert_types.append(ET.SOFT_DISABLE) - - elif self.events.contains(ET.OVERRIDE_LATERAL) or self.events.contains(ET.OVERRIDE_LONGITUDINAL): - self.state = State.overriding - self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] - - # SOFT DISABLING - elif self.state == State.softDisabling: - if not self.events.contains(ET.SOFT_DISABLE): - # no more soft disabling condition, so go back to ENABLED - self.state = State.enabled - - elif self.soft_disable_timer > 0: - self.current_alert_types.append(ET.SOFT_DISABLE) - - elif self.soft_disable_timer <= 0: - self.state = State.disabled - - # PRE ENABLING - elif self.state == State.preEnabled: - if not self.events.contains(ET.PRE_ENABLE): - self.state = State.enabled - else: - self.current_alert_types.append(ET.PRE_ENABLE) - - # OVERRIDING - elif self.state == State.overriding: - if self.events.contains(ET.SOFT_DISABLE): - self.state = State.softDisabling - self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) - self.current_alert_types.append(ET.SOFT_DISABLE) - elif not (self.events.contains(ET.OVERRIDE_LATERAL) or self.events.contains(ET.OVERRIDE_LONGITUDINAL)): - self.state = State.enabled - else: - self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] - - # DISABLED - elif self.state == State.disabled: - if self.events.contains(ET.ENABLE): - if self.events.contains(ET.NO_ENTRY): - self.current_alert_types.append(ET.NO_ENTRY) - - else: - if self.events.contains(ET.PRE_ENABLE): - self.state = State.preEnabled - elif self.events.contains(ET.OVERRIDE_LATERAL) or self.events.contains(ET.OVERRIDE_LONGITUDINAL): - self.state = State.overriding - else: - self.state = State.enabled - self.current_alert_types.append(ET.ENABLE) - - # Check if openpilot is engaged and actuators are enabled - self.enabled = self.state in ENABLED_STATES - self.active = self.state in ACTIVE_STATES - if self.active: - self.current_alert_types.append(ET.WARNING) - - def state_control(self, CS): - """Given the state, this function returns a CarControl packet""" + model_k = float(model.action.desiredCurvature) + except Exception: + model_k = 0.0 + # Same liveMapDataNAP read the lateral-yield roundabout flag uses. + # In or within 40 m: roundabout_yield_context. No new socket. + try: + md = self.sm['liveMapDataNAP'] if self.sm.alive.get('liveMapDataNAP', False) else None + hint = live_map_roundabout_hint(md) + near_roundabout = bool( + hint is not None and roundabout_yield_context( + hint.on_roundabout, hint.approaching, hint.distance_m)) + except Exception: + near_roundabout = False + return self.low_vis.update( + enabled=bool(engaged) and param_on, + lane_probs=lane_probs, edge_stds=edge_stds, + path_t=path_t, path_y_std=path_y, integ_lines=integ, + sun_ahead=sun_ahead, dt=DT_CTRL, + v_ego=v_ego, blinker=blinker, + yielded=bool(self._lat_handoff.yielded), + measured_curvature=float(self.curvature), + model_curvature=model_k, + near_roundabout=near_roundabout) + + def _cone_curvature(self, model_k: float, CS) -> float: + """Shift the lateral target onto the driver's line after a cone-line push. + + Returns model_k unchanged until that push has already yielded lateral. + Does not read or write longitudinal. + """ + try: + enabled = bool(self.params.get_bool(PARAM_CONE_LINE_HOLD)) + except Exception: + enabled = True + cone = None + if self.sm.seen.get("coneLineNAP", False) and self.sm.alive.get("coneLineNAP", False): + cone = self.sm["coneLineNAP"] + cone_active = bool(getattr(cone, "active", False)) if cone is not None else False + cone_releasing = bool(getattr(cone, "releasing", False)) if cone is not None else False + # Inside a cone corridor the low-visibility fade must not undo the cone shift. + self._cone_zone = cone_active or cone_releasing or self.cone_hold.busy + path_x = path_y = None + lane_offset = lane_centre = None + cone_shift = 0.0 + if self._cone_zone: + path_x, path_y = model_path_xy(self.sm["modelV2"]) + try: + lane_offset, lane_centre = lane_offset_from_model(self.sm["modelV2"], lookahead_m(float(CS.vEgo))) + except Exception: + lane_offset = lane_centre = None + try: + cone_shift = float(getattr(cone, "wouldSteer", 0.0)) if cone is not None else 0.0 + except (TypeError, ValueError): + cone_shift = 0.0 + self._cone_out = self.cone_hold.update( + enabled=enabled, + engaged=bool(self.sm["selfdriveState"].enabled), + cone=cone, + torque_nm=float(CS.steeringTorque), + measured_k=float(self.curvature), + model_k=float(model_k), + path_x=path_x, + path_y=path_y, + v_ego=float(CS.vEgo), + yielded=bool(self._lat_handoff.yielded), + lat_active=bool(self._lat_active_prev), + dt=DT_CTRL, + lane_offset=lane_offset, + lane_center_la=lane_centre, + cone_shift=cone_shift, + ) + return float(self._cone_out.curvature) + + def state_control(self): + CS = self.sm['carState'] # Update VehicleModel lp = self.sm['liveParameters'] @@ -529,6 +273,9 @@ def state_control(self, CS): sr = max(lp.steerRatio, 0.1) self.VM.update_params(x, sr) + steer_angle_without_offset = math.radians(CS.steeringAngleDeg - lp.angleOffsetDeg) + self.curvature = -self.VM.calc_curvature(steer_angle_without_offset, CS.vEgo, lp.roll) + # Update Torque Params if self.CP.lateralTuning.which() == 'torque': torque_params = self.sm['liveTorqueParameters'] @@ -540,307 +287,362 @@ def state_control(self, CS): model_v2 = self.sm['modelV2'] CC = car.CarControl.new_message() - CC.enabled = self.enabled + CC.enabled = self.sm['selfdriveState'].enabled # Check which actuators can be enabled - standstill = CS.vEgo <= max(self.CP.minSteerSpeed, MIN_LATERAL_CONTROL_SPEED) or CS.standstill - CC.latActive = self.active and not CS.steerFaultTemporary and not CS.steerFaultPermanent and \ - (not standstill or self.joystick_mode) - CC.longActive = self.enabled and not self.events.contains(ET.OVERRIDE_LONGITUDINAL) and self.CP.openpilotLongitudinalControl + standstill = abs(CS.vEgo) <= max(self.CP.minSteerSpeed, 0.3) or CS.standstill + # Driver-turn lamps latch through flash gaps. Soft-lat Off still pauses + # lat on that latch; Soft-lat On keeps latActive and lets handoff + # inhibit re-enable. ALC keep-alive flashes must not latch a driver + # turn: gate while laneChangeState != off, and on a stalk tip + # (LEFT/RIGHT then IDLE within 0.40s) so latActive stays up for + # DesireHelper. A held stalk past that window is a turn at any speed + # when ALC is not latched. During ALC / leftover keep-alive, + # same-direction stalk must stay on >1.0s to steal ALC as a turn. + alc_active = model_v2.meta.laneChangeState != LaneChangeState.off + # Tipped ALC stays armed through lamp flash-dark gaps. Same-direction + # torque is the confirm, not a soft-lat release. An emergency yank + # still frees the EPS immediately. + lc_state = model_v2.meta.laneChangeState + tipped_alc = lc_state in ( + LaneChangeState.preLaneChange, + LaneChangeState.laneChangeStarting, + LaneChangeState.laneChangeFinishing, + ) + if model_v2.meta.laneChangeDirection == log.LaneChangeDirection.left: + nudge_dir = 1 + elif model_v2.meta.laneChangeDirection == log.LaneChangeDirection.right: + nudge_dir = 2 + else: + nudge_dir = 0 + # Emergency (spike / opposite) or a sustained same-direction takeover + # (held until the hands come off) yields lateral now; only the + # emergency also disengages (car_specific steerDisengage). + # Resting EPAS offset (~+0.25 Nm on this car). Relative torque keeps a + # hands-off reading from looking like a left-lane nudge. + driver_tq = float(CS.steeringTorque) - float(self.lat_handoff.rest_bias) + self._lane_change_torque.update( + torque_nm=driver_tq, hands_on_level=cs_hands_on_level(CS), + direction=nudge_dir, tipped=tipped_alc, dt=DT_CTRL) + lane_change_confirm = self._lane_change_torque.confirm + # Turning the wheel well past a lane change in its direction ends the + # change (DesireHelper) and becomes a manual driver turn here: keep the + # blinker until the turn completes, pause lat like a latched stalk. + turn_hold_dir = self._lane_change_turn.update( + lc_state=lc_state, lc_direction=nudge_dir, steering_angle_deg=float(CS.steeringAngleDeg), + torque_nm=driver_tq, lat_active=self._lat_active_prev, + v_ego=float(CS.vEgo), stalk_state=getattr(CS, 'turnSignalStalkState', 0), + engaged=bool(CC.enabled), dt=DT_CTRL) + # Soft yield frees the EPS the same way blinker pause does (latActive + # false → DAS_steeringControlType=0). Do not keep latActive and track + # measured angle — that is follow-the-rim holding, not a free wheel. + # Handoff still sees the pre-yield bit so it does not reset itself. + # Longitudinal / enabled are untouched. ALC is not this path. + # Soft-lat On: lamp latch must not clear latActive. Soft-lat Off: + # keep today's blinker lat-pause so a held turn still frees the wheel. + self.lat_handoff.enabled = handoff_enabled( + fingerprint=self.CP.carFingerprint, + param_on=bool(self.params.get_bool(PARAM_DRIVER_LAT_HANDOFF))) + lat_would_be_active = lat_active_with_blinker_pause( + active=self.sm['selfdriveState'].active, + steer_fault_temporary=CS.steerFaultTemporary, + steer_fault_permanent=CS.steerFaultPermanent, + standstill=standstill, + steer_at_standstill=self.CP.steerAtStandstill, + left_blinker=CS.leftBlinker, + right_blinker=CS.rightBlinker, + steering_pressed=CS.steeringPressed, + steering_disengage=bool(getattr(CS, 'steeringDisengage', False)), + engaged=bool(self.sm['selfdriveState'].enabled), + hold=self.blinker_lat_hold, + alc_active=alc_active, + v_ego=CS.vEgo, + stalk_state=getattr(CS, 'turnSignalStalkState', 0), + soft_lat_on=self.lat_handoff.enabled, + driver_turn=self._lane_change_turn.turning, + ) + # Pre-AP: brake and a long pause keep lateral, but must not log longActive + # or a decel the interceptor is not executing. Other cars keep the stock + # formula (enabled, no longitudinal override, openpilot longitudinal). + preap_pedal = preap_pedal_long(self.CP) + CC.longActive = preap_longitudinal_active( + enabled=CC.enabled, + longitudinal_override=any(e.overrideLongitudinal for e in self.sm['onroadEvents']), + openpilot_longitudinal=self.CP.openpilotLongitudinalControl, + preap_pedal=preap_pedal, + enable_long_control=bool(getattr(CS, "enableLongControl", False)), + driver_brake=driver_brake_applied(CS), + ) + # turn_active is the latched driver-turn blinker (not ALC, not the + # post-turn hand-on hold). Soft-lat ORs that with v_ego < 10 mph + # as re-enable inhibit + falling-edge enter-yield. Soft-lat Off + # ignores it (identity). + # In-session stalk pull: clear a lateral yield. Seq lives on carState. + stalk_seq = int(getattr(CS, "napStalkSeq", 0) or 0) & 0xFF + if self._nap_stalk_seen and stalk_seq != self._nap_stalk_seq: + self.lat_handoff.driver_resume_request() + self._nap_stalk_seen = True + self._nap_stalk_seq = stalk_seq + self._lat_handoff = self.lat_handoff.update( + engaged=bool(CC.enabled), + lat_would_be_active=bool(lat_would_be_active), + steering_torque=float(CS.steeringTorque), + steering_rate_deg=float(CS.steeringRateDeg), + alc_active=alc_active, + blinker_paused=bool(self.blinker_lat_hold.turn_active), + hands_on_level=cs_hands_on_level(CS), + tracking_error=float(self.desired_curvature - self.curvature), + brake_applied=cs_real_brake_pressed(CS), + a_ego=float(CS.aEgo), + v_ego=float(CS.vEgo), + emergency_yank=bool(self._lane_change_torque.release), + lane_change_confirm=bool(lane_change_confirm), + commanded_angle_deg=self._cmd_angle_prev, + roundabout_yield=bool(self._rb_yield_prev), + undertrack=bool(self._under_prev), + steering_angle_deg=float(CS.steeringAngleDeg), + steering_pressed=bool(CS.steeringPressed), + model_curvature=float(self._raw_model_curvature), + measured_curvature=float(self.curvature), + ) + self._low_vis = self._update_low_visibility(bool(CC.enabled)) + CC.latActive = lat_active_after_handoff( + lat_would_be_active, self._lat_handoff.yielded) + self._lat_active_prev = bool(CC.latActive) actuators = CC.actuators actuators.longControlState = self.LoC.long_control_state - # Enable blinkers while lane changing - if model_v2.meta.laneChangeState != LaneChangeState.off: - CC.leftBlinker = model_v2.meta.laneChangeDirection == LaneChangeDirection.left - CC.rightBlinker = model_v2.meta.laneChangeDirection == LaneChangeDirection.right - - if CS.leftBlinker or CS.rightBlinker: - self.last_blinker_frame = self.sm.frame - - # State specific actions + # Keep the indicator flashing while ALC is armed or in progress. Pre-AP + # carcontroller TXes DAS_bodyControls from CC.leftBlinker / rightBlinker. + CC.leftBlinker, CC.rightBlinker = blinker_with_turn_hold( + DesireHelper.lane_change_keep_blinker( + model_v2.meta.laneChangeState, model_v2.meta.laneChangeDirection), + turn_hold_dir) if not CC.latActive: self.LaC.reset() if not CC.longActive: self.LoC.reset() - if not self.joystick_mode: - # accel PID loop - pid_accel_limits = self.CI.get_pid_accel_limits(self.CP, CS.vEgo, CS.vCruise * CV.KPH_TO_MS) - actuators.accel = self.LoC.update(CC.longActive, CS, long_plan.aTarget, long_plan.shouldStop, pid_accel_limits) - - # Steering PID loop and lateral MPC - self.desired_curvature = clip_curvature(CS.vEgo, self.desired_curvature, model_v2.action.desiredCurvature) - actuators.curvature = self.desired_curvature - actuators.steer, actuators.steeringAngleDeg, lac_log = self.LaC.update(CC.latActive, CS, self.VM, lp, - self.steer_limited, self.desired_curvature, - self.calibrated_pose) # TODO what if not available + # accel PID loop + pid_accel_limits = self.CI.get_pid_accel_limits(self.CP, CS.vEgo, CS.vCruise * CV.KPH_TO_MS) + lead_v_rel = lead_d_rel = lead_slack = lead_a_lead = None + if self.sm.valid['radarState'] and self.sm['radarState'].leadOne.status: + lead = self.sm['radarState'].leadOne + lead_d_rel = float(lead.dRel) + lead_v_rel = float(CS.vEgo) - float(lead.vLead) + gap_lock_m = getattr(long_plan, "gapLockM", 0.0) + lead_slack = slack_for_guard(lead_d_rel, float(lead.vLead), float(long_plan.tFollow), gap_lock_m) + lead_a_lead = float(lead.aLeadK) + actuators.accel = published_long_accel( + long_active=bool(CC.longActive), + preap_pedal=preap_pedal, + loc_accel=self.LoC.update( + CC.longActive, CS, long_plan.aTarget, long_plan.shouldStop, pid_accel_limits, + lead_v_rel=lead_v_rel, lead_d_rel=lead_d_rel, lead_slack=lead_slack, + lead_fcw=bool(long_plan.fcw), + lead_v_ego=float(CS.vEgo), lead_v_cruise=float(CS.vCruise) * CV.KPH_TO_MS, + lead_a_lead=lead_a_lead, + ), + ) + + # Steering PID loop and lateral MPC + # Reset desired curvature to current to avoid violating the limits on engage. + # Yield (and soft-lat Off blinker pause) clear latActive (EPS free). + # Pin to the wheel while lat is down so resume clips from there. + # Soft-lat On does not drop lat on lamp latch; after a yielded turn + # the falling blinker enters yield and the normal 0.15 s confirm + + # 1 s blend owns take-back. Hands still on stay yielded. + if self.sm.valid['lateralManeuverPlan']: + model_or_plan_curvature = self.sm['lateralManeuverPlan'].desiredCurvature else: - lac_log = log.ControlsState.LateralDebugState.new_message() - if self.sm.recv_frame['testJoystick'] > 0: - # reset joystick if it hasn't been received in a while - should_reset_joystick = (self.sm.frame - self.sm.recv_frame['testJoystick'])*DT_CTRL > 0.2 - if not should_reset_joystick: - joystick_axes = self.sm['testJoystick'].axes - else: - joystick_axes = [0.0, 0.0] - - if CC.longActive: - actuators.accel = 4.0*clip(joystick_axes[0], -1, 1) - - if CC.latActive: - steer = clip(joystick_axes[1], -1, 1) - # max angle is 45 for angle-based cars, max curvature is 0.02 - actuators.steer, actuators.steeringAngleDeg, actuators.curvature = steer, steer * 90., steer * -0.02 - - lac_log.active = self.active - lac_log.steeringAngleDeg = CS.steeringAngleDeg - lac_log.output = actuators.steer - lac_log.saturated = abs(actuators.steer) >= 0.9 - - if CS.steeringPressed: - self.last_steering_pressed_frame = self.sm.frame - recent_steer_pressed = (self.sm.frame - self.last_steering_pressed_frame)*DT_CTRL < 2.0 - - # Send a "steering required alert" if saturation count has reached the limit - if lac_log.active and not recent_steer_pressed and not self.CP.notCar: - if self.CP.lateralTuning.which() == 'torque' and not self.joystick_mode: - undershooting = abs(lac_log.desiredLateralAccel) / abs(1e-3 + lac_log.actualLateralAccel) > 1.2 - turning = abs(lac_log.desiredLateralAccel) > 1.0 - good_speed = CS.vEgo > 5 - max_torque = abs(self.sm['carOutput'].actuatorsOutput.steer) > 0.99 - if undershooting and turning and good_speed and max_torque: - lac_log.active and self.events.add(EventName.steerSaturated) - elif lac_log.saturated: - # TODO probably should not use dpath_points but curvature - dpath_points = model_v2.position.y - if len(dpath_points): - # Check if we deviated from the path - # TODO use desired vs actual curvature - if self.CP.steerControlType == car.CarParams.SteerControlType.angle: - steering_value = actuators.steeringAngleDeg - else: - steering_value = actuators.steer - - left_deviation = steering_value > 0 and dpath_points[0] < -0.20 - right_deviation = steering_value < 0 and dpath_points[0] > 0.20 - - if left_deviation or right_deviation: - self.events.add(EventName.steerSaturated) - + model_or_plan_curvature = model_v2.action.desiredCurvature + rb_hint = live_map_roundabout_hint(self.sm['liveMapDataNAP'] if self.sm.valid.get('liveMapDataNAP', False) else None) + is_rhd = bool(self.sm['driverMonitoringState'].isRHD) if self.sm.valid.get('driverMonitoringState', False) else False + # Turn geometry ON: no roundabout outer bias (modeld owns turn-in timing). + if self._turn_geom_param_frame < 0 or self._turn_geom_param_frame >= 100: + self._turn_geom_param_frame = 0 + self._turn_geom_active = turn_geometry_active( + self._turn_geom_preap, bool(self.params.get_bool(PARAM_TURN_GEOMETRY))) + self._turn_geom_param_frame += 1 + # Map-guided ring curvature blend (identity unless the toggle is On near a mapped ring). + # The hint is read by alive, not valid: liveMapDataNAP is invalid without a speed match. + rb_assist_hint = rb_hint + if rb_assist_hint is None and self.sm.alive.get('liveMapDataNAP', False): + rb_assist_hint = live_map_roundabout_hint(self.sm['liveMapDataNAP']) + yaw_rate = float(self.calibrated_pose.angular_velocity.z) if self.calibrated_pose is not None else 0.0 + model_or_plan_curvature = self.rb_assist.update( + self.sm, t=float(self.sm.logMonoTime['carState']) * 1e-9, v_ego=float(CS.vEgo), yaw_rate=yaw_rate, + model_k=float(model_or_plan_curvature), lat_active=bool(CC.latActive) and not bool(self._lat_handoff.yielded), + maneuver_active=bool(self.sm.valid['lateralManeuverPlan']), lane_change_active=bool(alc_active), + hint=rb_assist_hint, model_v2=model_v2, stalk_state=int(getattr(CS, 'turnSignalStalkState', 0) or 0), + steering_pressed=bool(CS.steeringPressed), steering_torque=float(CS.steeringTorque)) + rb_bias = roundabout_lateral_curvature_bias( + rb_hint, is_rhd=is_rhd, turn_geometry_active=self._turn_geom_active, + ) + # The legacy outer bias never stacks on the assist. + model_or_plan_curvature = float(model_or_plan_curvature) + (0.0 if self.rb_assist.active else rb_bias) + # Raw model curvature feeds the fight-hold resume (not the faded command). + self._raw_model_curvature = float(model_or_plan_curvature) + # Cone-line hold, after a real push, aims the re-take at the driver's + # line. Identity otherwise. Longitudinal accel above is unchanged. + model_or_plan_curvature = self._cone_curvature(float(model_or_plan_curvature), CS) + # Low visibility eases the lateral target toward the wheel. Longitudinal + # accel above is unchanged, and latActive / enabled are unchanged. + # Not inside a cone corridor (Oct 14 seg 25: the alert was on while the cones closed in). + low_vis_auth = 1.0 if self._cone_zone else float(self._low_vis.authority) + model_or_plan_curvature = fade_curvature( + model_or_plan_curvature, self.curvature, low_vis_auth) + new_desired_curvature = handoff_new_desired_curvature( + yielded=bool(self._lat_handoff.yielded), + lat_active=bool(CC.latActive), + model_curvature=model_or_plan_curvature, + measured_curvature=self.curvature, + ) + if pin_desired_curvature_to_measured( + self._lat_handoff.yielded, bool(CC.latActive)): + self.desired_curvature = self.curvature + curvature_limited = False + else: + self.desired_curvature, curvature_limited = clip_curvature( + CS.vEgo, self.desired_curvature, new_desired_curvature, lp.roll) + lat_delay = self.sm["liveDelay"].lateralDelay + LAT_SMOOTH_SECONDS + + actuators.curvature = self.desired_curvature + steer, steeringAngleDeg, lac_log = self.LaC.update(CC.latActive, CS, self.VM, lp, + self.steer_limited_by_safety, self.desired_curvature, + curvature_limited, lat_delay) + # Blend only while lat is actually requesting and authority < 1. + # While yielded, latActive is false — do not follow-measured-angle. + # Do not write blended values back into desired_curvature. + if CC.latActive and self._lat_handoff.authority < 1.0: + steer, steeringAngleDeg, blended_curvature = apply_lat_authority( + self._lat_handoff.authority, steer, steeringAngleDeg, CS.steeringAngleDeg, + self.desired_curvature, self.curvature) + actuators.torque = float(steer) + actuators.steeringAngleDeg = float(steeringAngleDeg) + actuators.curvature = float(blended_curvature) + else: + actuators.torque = float(steer) + actuators.steeringAngleDeg = float(steeringAngleDeg) + if low_vis_auth < 1.0: + actuators.torque = float(actuators.torque) * low_vis_auth + # Latch what this cycle will tell panda (0x561) for the next hands edge. + self._cmd_angle_prev = float(actuators.steeringAngleDeg) + self._under_prev = abs(float(actuators.curvature) - float(self.curvature)) > UNDERTRACK_CURVATURE + _md = self.sm['liveMapDataNAP'] if self.sm.alive.get('liveMapDataNAP', False) else None + _hint = live_map_roundabout_hint(_md) + self._rb_yield_prev = bool( + _hint is not None and roundabout_yield_context( + _hint.on_roundabout, _hint.approaching, _hint.distance_m)) # Ensure no NaNs/Infs for p in ACTUATOR_FIELDS: attr = getattr(actuators, p) - if not isinstance(attr, SupportsFloat): + if not isinstance(attr, Number): continue if not math.isfinite(attr): cloudlog.error(f"actuators.{p} not finite {actuators.to_dict()}") setattr(actuators, p, 0.0) - # decrement personality on distance button press - if self.CP.openpilotLongitudinalControl: - if any(not be.pressed and be.type == ButtonType.gapAdjustCruise for be in CS.buttonEvents): - self.personality = (self.personality - 1) % 3 - self.params.put_nonblocking('LongitudinalPersonality', str(self.personality)) - self.events.add(EventName.personalityChanged) - return CC, lac_log - def publish_logs(self, CS, CC, lac_log): - """Send actuators and hud commands to the car, send controlsstate and MPC logging""" + def publish(self, CC, lac_log): + CS = self.sm['carState'] # Orientation and angle rates can be useful for carcontroller # Only calibrated (car) frame is relevant for the carcontroller + CC.currentCurvature = self.curvature if self.calibrated_pose is not None: CC.orientationNED = self.calibrated_pose.orientation.xyz.tolist() CC.angularVelocity = self.calibrated_pose.angular_velocity.xyz.tolist() - CC.cruiseControl.override = self.enabled and not CC.longActive and self.CP.openpilotLongitudinalControl - CC.cruiseControl.cancel = CS.cruiseState.enabled and (not self.enabled or not self.CP.pcmCruise) - if self.joystick_mode and self.sm.recv_frame['testJoystick'] > 0 and self.sm['testJoystick'].buttons[0]: - CC.cruiseControl.cancel = True - - speeds = self.sm['longitudinalPlan'].speeds - if len(speeds): - CC.cruiseControl.resume = self.enabled and CS.cruiseState.standstill and speeds[-1] > 0.1 + CC.cruiseControl.override = CC.enabled and not CC.longActive and self.CP.openpilotLongitudinalControl + # Soft-lat emergency hard-brake: request the normal cancel path (stock + # CC spoof / session teardown). Distinct from silent long pause. + emergency_cancel = bool( + self.lat_handoff.enabled and self._lat_handoff.emergency_cancel) + CC.cruiseControl.cancel = CS.cruiseState.enabled and ( + not CC.enabled or not self.CP.pcmCruise or emergency_cancel) + CC.cruiseControl.resume = CC.enabled and CS.cruiseState.standstill and not self.sm['longitudinalPlan'].shouldStop hudControl = CC.hudControl hudControl.setSpeed = float(CS.vCruiseCluster * CV.KPH_TO_MS) - hudControl.speedVisible = self.enabled - hudControl.lanesVisible = self.enabled + hudControl.speedVisible = CC.enabled + hudControl.lanesVisible = CC.enabled hudControl.leadVisible = self.sm['longitudinalPlan'].hasLead - hudControl.leadDistanceBars = self.personality + 1 + hudControl.leadDistanceBars = self.sm['selfdriveState'].personality.raw + 1 + hudControl.visualAlert = self.sm['selfdriveState'].alertHudVisual hudControl.rightLaneVisible = True hudControl.leftLaneVisible = True + if self.sm.valid['driverAssistance']: + hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture + hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture - recent_blinker = (self.sm.frame - self.last_blinker_frame) * DT_CTRL < 5.0 # 5s blinker cooldown - ldw_allowed = self.is_ldw_enabled and CS.vEgo > LDW_MIN_SPEED and not recent_blinker \ - and not CC.latActive and self.sm['liveCalibration'].calStatus == log.LiveCalibrationData.Status.calibrated - - model_v2 = self.sm['modelV2'] - desire_prediction = model_v2.meta.desirePrediction - if len(desire_prediction) and ldw_allowed: - right_lane_visible = model_v2.laneLineProbs[2] > 0.5 - left_lane_visible = model_v2.laneLineProbs[1] > 0.5 - l_lane_change_prob = desire_prediction[Desire.laneChangeLeft] - r_lane_change_prob = desire_prediction[Desire.laneChangeRight] - - lane_lines = model_v2.laneLines - l_lane_close = left_lane_visible and (lane_lines[1].y[0] > -(1.08 + CAMERA_OFFSET)) - r_lane_close = right_lane_visible and (lane_lines[2].y[0] < (1.08 - CAMERA_OFFSET)) - - hudControl.leftLaneDepart = bool(l_lane_change_prob > LANE_DEPARTURE_THRESHOLD and l_lane_close) - hudControl.rightLaneDepart = bool(r_lane_change_prob > LANE_DEPARTURE_THRESHOLD and r_lane_close) - - if hudControl.rightLaneDepart or hudControl.leftLaneDepart: - self.events.add(EventName.ldw) - - clear_event_types = set() - if ET.WARNING not in self.current_alert_types: - clear_event_types.add(ET.WARNING) - if self.enabled: - clear_event_types.add(ET.NO_ENTRY) - - pers = {v: k for k, v in log.LongitudinalPersonality.schema.enumerants.items()}[self.personality] - alerts = self.events.create_alerts(self.current_alert_types, [self.CP, CS, self.sm, self.is_metric, self.soft_disable_timer, pers]) - self.AM.add_many(self.sm.frame, alerts) - current_alert = self.AM.process_alerts(self.sm.frame, clear_event_types) - if current_alert: - hudControl.visualAlert = current_alert.visual_alert - - if not self.CP.passive and self.initialized: + if self.sm['selfdriveState'].active: CO = self.sm['carOutput'] if self.CP.steerControlType == car.CarParams.SteerControlType.angle: - self.steer_limited = abs(CC.actuators.steeringAngleDeg - CO.actuatorsOutput.steeringAngleDeg) > \ - STEER_ANGLE_SATURATION_THRESHOLD + self.steer_limited_by_safety = abs(CC.actuators.steeringAngleDeg - CO.actuatorsOutput.steeringAngleDeg) > \ + STEER_ANGLE_SATURATION_THRESHOLD else: - self.steer_limited = abs(CC.actuators.steer - CO.actuatorsOutput.steer) > 1e-2 - - force_decel = (self.sm['driverMonitoringState'].awarenessStatus < 0.) or \ - (self.state == State.softDisabling) + self.steer_limited_by_safety = abs(CC.actuators.torque - CO.actuatorsOutput.torque) > 1e-2 - # Curvature & Steering angle - lp = self.sm['liveParameters'] - - steer_angle_without_offset = math.radians(CS.steeringAngleDeg - lp.angleOffsetDeg) - curvature = -self.VM.calc_curvature(steer_angle_without_offset, CS.vEgo, lp.roll) + # TODO: both controlsState and carControl valids should be set by + # sm.all_checks(), but this creates a circular dependency # controlsState dat = messaging.new_message('controlsState') dat.valid = CS.canValid - controlsState = dat.controlsState - controlsState.longitudinalPlanMonoTime = self.sm.logMonoTime['longitudinalPlan'] - controlsState.lateralPlanMonoTime = self.sm.logMonoTime['modelV2'] - controlsState.curvature = curvature - controlsState.desiredCurvature = self.desired_curvature - controlsState.longControlState = self.LoC.long_control_state - controlsState.upAccelCmd = float(self.LoC.pid.p) - controlsState.uiAccelCmd = float(self.LoC.pid.i) - controlsState.ufAccelCmd = float(self.LoC.pid.f) - controlsState.cumLagMs = -self.rk.remaining * 1000. - controlsState.forceDecel = bool(force_decel) + cs = dat.controlsState + + cs.curvature = self.curvature + cs.longitudinalPlanMonoTime = self.sm.logMonoTime['longitudinalPlan'] + cs.lateralPlanMonoTime = self.sm.logMonoTime['modelV2'] + cs.desiredCurvature = self.desired_curvature + if self.lat_handoff.enabled: + cs.latAuthority = float(self._lat_handoff.authority) + cs.latHandoffPaused = bool(self._lat_handoff.ui_paused) + cs.lowVisibility = bool(self._low_vis.alert) + cs.coneLineHold = bool(self._cone_out.active) + cs.coneLineOffset = float(self._cone_out.offset_m) + cs.longControlState = self.LoC.long_control_state + cs.upAccelCmd = float(self.LoC.pid.p) + cs.uiAccelCmd = float(self.LoC.pid.i) + cs.ufAccelCmd = float(self.LoC.pid.f) + cs.forceDecel = bool((self.sm['driverMonitoringState'].alertLevel == log.DriverMonitoringState.AlertLevel.three) or + (self.sm['selfdriveState'].state == State.softDisabling)) lat_tuning = self.CP.lateralTuning.which() - if self.joystick_mode: - controlsState.lateralControlState.debugState = lac_log - elif self.CP.steerControlType == car.CarParams.SteerControlType.angle: - controlsState.lateralControlState.angleState = lac_log + if self.CP.steerControlType == car.CarParams.SteerControlType.angle: + cs.lateralControlState.angleState = lac_log elif lat_tuning == 'pid': - controlsState.lateralControlState.pidState = lac_log + cs.lateralControlState.pidState = lac_log elif lat_tuning == 'torque': - controlsState.lateralControlState.torqueState = lac_log + cs.lateralControlState.torqueState = lac_log self.pm.send('controlsState', dat) - # selfdriveState - ss_msg = messaging.new_message('selfdriveState') - ss_msg.valid = CS.canValid - ss = ss_msg.selfdriveState - if current_alert: - ss.alertText1 = current_alert.alert_text_1 - ss.alertText2 = current_alert.alert_text_2 - ss.alertSize = current_alert.alert_size - ss.alertStatus = current_alert.alert_status - ss.alertType = current_alert.alert_type - ss.alertSound = current_alert.audible_alert - ss.enabled = self.enabled - ss.active = self.active - ss.state = self.state - ss.engageable = not self.events.contains(ET.NO_ENTRY) - ss.experimentalMode = self.experimental_mode - ss.personality = self.personality - self.pm.send('selfdriveState', ss_msg) - - # onroadEvents - logged every second or on change - if (self.sm.frame % int(1. / DT_CTRL) == 0) or (self.events.names != self.events_prev): - ce_send = messaging.new_message('onroadEvents', len(self.events)) - ce_send.valid = True - ce_send.onroadEvents = self.events.to_msg() - self.pm.send('onroadEvents', ce_send) - self.events_prev = self.events.names.copy() - # carControl cc_send = messaging.new_message('carControl') cc_send.valid = CS.canValid cc_send.carControl = CC self.pm.send('carControl', cc_send) - def step(self): - # Sample data from sockets and get a carState - CS = self.data_sample() - cloudlog.timestamp("Data sampled") - - self.update_events(CS) - cloudlog.timestamp("Events updated") - - if not self.CP.passive and self.initialized: - # Update control state - self.state_transition(CS) - - # Compute actuators (runs PID loops and lateral MPC) - CC, lac_log = self.state_control(CS) - - # Publish data - self.publish_logs(CS, CC, lac_log) - - self.CS_prev = CS - - def read_personality_param(self): - try: - return int(self.params.get('LongitudinalPersonality')) - except (ValueError, TypeError): - return log.LongitudinalPersonality.standard - - def params_thread(self, evt): - while not evt.is_set(): - self.is_metric = self.params.get_bool("IsMetric") - self.experimental_mode = self.params.get_bool("ExperimentalMode") and self.CP.openpilotLongitudinalControl - self.personality = self.read_personality_param() - if self.CP.notCar: - self.joystick_mode = self.params.get_bool("JoystickDebugMode") - time.sleep(0.1) - - def controlsd_thread(self): - e = threading.Event() - t = threading.Thread(target=self.params_thread, args=(e, )) - try: - t.start() - while True: - self.step() - self.rk.monitor_time() - finally: - e.set() - t.join() + def run(self): + rk = Ratekeeper(100, print_delay_threshold=None) + while True: + self.update() + CC, lac_log = self.state_control() + self.publish(CC, lac_log) + rk.monitor_time() def main(): config_realtime_process(4, Priority.CTRL_HIGH) controls = Controls() - controls.controlsd_thread() + controls.run() if __name__ == "__main__": diff --git a/selfdrive/controls/lib/alertmanager.py b/selfdrive/controls/lib/alertmanager.py deleted file mode 100644 index f67e269fa97854..00000000000000 --- a/selfdrive/controls/lib/alertmanager.py +++ /dev/null @@ -1,61 +0,0 @@ -import copy -import os -import json -from collections import defaultdict -from dataclasses import dataclass - -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.selfdrive.controls.lib.events import Alert - - -with open(os.path.join(BASEDIR, "selfdrive/controls/lib/alerts_offroad.json")) as f: - OFFROAD_ALERTS = json.load(f) - - -def set_offroad_alert(alert: str, show_alert: bool, extra_text: str = None) -> None: - if show_alert: - a = copy.copy(OFFROAD_ALERTS[alert]) - a['extra'] = extra_text or '' - Params().put(alert, json.dumps(a)) - else: - Params().remove(alert) - - -@dataclass -class AlertEntry: - alert: Alert | None = None - start_frame: int = -1 - end_frame: int = -1 - - def active(self, frame: int) -> bool: - return frame <= self.end_frame - -class AlertManager: - def __init__(self): - self.alerts: dict[str, AlertEntry] = defaultdict(AlertEntry) - - def add_many(self, frame: int, alerts: list[Alert]) -> None: - for alert in alerts: - entry = self.alerts[alert.alert_type] - entry.alert = alert - if not entry.active(frame): - entry.start_frame = frame - min_end_frame = entry.start_frame + alert.duration - entry.end_frame = max(frame + 1, min_end_frame) - - def process_alerts(self, frame: int, clear_event_types: set) -> Alert | None: - current_alert = AlertEntry() - for v in self.alerts.values(): - if not v.alert: - continue - - if v.alert.event_type in clear_event_types: - v.end_frame = -1 - - # sort by priority first and then by start_frame - greater = current_alert.alert is None or (v.alert.priority, v.start_frame) > (current_alert.alert.priority, current_alert.start_frame) - if v.active(frame) and greater: - current_alert = v - - return current_alert.alert diff --git a/selfdrive/controls/lib/alerts_offroad.json b/selfdrive/controls/lib/alerts_offroad.json deleted file mode 100644 index 6fb6c569b023f2..00000000000000 --- a/selfdrive/controls/lib/alerts_offroad.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "Offroad_TemperatureTooHigh": { - "text": "Device temperature too high. System cooling down before starting. Current internal component temperature: %1", - "severity": 0 - }, - "Offroad_ConnectivityNeededPrompt": { - "text": "Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1", - "severity": 0, - "_comment": "Set extra field to number of days" - }, - "Offroad_ConnectivityNeeded": { - "text": "Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates.", - "severity": 1 - }, - "Offroad_UpdateFailed": { - "text": "Unable to download updates\n%1", - "severity": 1, - "_comment": "Set extra field to the failed reason." - }, - "Offroad_IsTakingSnapshot": { - "text": "Taking camera snapshots. System won't start until finished.", - "severity": 0 - }, - "Offroad_NeosUpdate": { - "text": "An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install.", - "severity": 0 - }, - "Offroad_UnofficialHardware": { - "text": "Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support.", - "severity": 1 - }, - "Offroad_StorageMissing": { - "text": "NVMe drive not mounted.", - "severity": 1 - }, - "Offroad_BadNvme": { - "text": "Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe.", - "severity": 1 - }, - "Offroad_CarUnrecognized": { - "text": "openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai.", - "severity": 0 - }, - "Offroad_NoFirmware": { - "text": "openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai.", - "severity": 0 - }, - "Offroad_Recalibration": { - "text": "openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield.", - "severity": 0 - } -} diff --git a/selfdrive/controls/lib/blinker_lateral_pause.py b/selfdrive/controls/lib/blinker_lateral_pause.py new file mode 100644 index 00000000000000..eaa6a5f6383c70 --- /dev/null +++ b/selfdrive/controls/lib/blinker_lateral_pause.py @@ -0,0 +1,291 @@ +"""Blinker-lamp lateral pause. + +Any single lit indicator lamp means the driver is turning. Tesla lamps stay +on after the stalk returns, so the hold follows leftBlinker / rightBlinker, +not the stalk enum. Soft-lat Off still releases steering (clears latActive) +while staying engaged. Soft-lat On keeps latActive on lamp latch — the +handoff owns yield / re-enable inhibit / resume — but this helper still +latches a *driver turn* for the soft-lat re-enable gate. Long stays +engaged through that latch. + +Those lamp bits flash: they go dark between blinks. Latch turn-active as +soon as one lamp is seen, and keep it through flash gaps until both lamps +have been dark for longer than one flash (~1s). Stalk returning to center +does not end the turn. + +After the turn is complete, keep lateral released until the wheel is no +longer held (steeringPressed). This helper only pauses lat. Pre-AP's +engagement FSM does not drop longitudinal on a driver turn; long stays +engaged (lead/map braking and accel still apply). Brake still uses the +silent long-pause path. + +Automatic lane change is the other blinker user. OP drives the lamps while +ALC is armed or in progress, so those flashes must not pause lat or latch a +driver turn. Gate pause off when ALC is active, and on a stalk *tip* +(LEFT/RIGHT then IDLE within STALK_TIP_HOLD_S=0.40s) so the driver's own +lamps cannot kill latActive before DesireHelper arms. A held LEFT/RIGHT +past that window is a driver turn at any speed when ALC is not latched. + +While ALC is armed / in progress, or leftover keep-alive is still +flashing, a same-direction physical stalk (turnSignalStalkState, not the +bulb bit) must stay LEFT/RIGHT past STALK_ALC_TURN_HOLD_S (1.0s) to cancel +ALC and pause lat as a turn. A shorter same-direction hold does not force +a turn. Opposite uses the 0.40s window. After that turn, lamps dark ~1s +then hand release resumes lat. Leftover keep-alive flashes after ALC stay +ungated until ~1s of continuous dark, unless the stalk hold takes over. + +Hazards (both lamps) do not pause and do not start a lane change. +No map or OSM junction check. + +A faster / higher-torque corner sets EPAS hands-on >= 2 (steeringDisengage) +before steeringPressed's 5-frame debounce. That torque must keep the +lat-pause latch and must not drop cruiseEnabled. On Pre-AP that drop is +EventName.pcmDisable — HUD "Steering Disengaged". Panda tesla_preap keeps +controls_allowed on the same hands-on during a blinker-latched driver turn +(flash panda after pull). Without that firmware, selfdrived fires +controlsMismatch after the Python hold ends. +""" + +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + tipped_lane_change_driver_release, +) +from openpilot.selfdrive.controls.lib.stalk_tip_turn import StalkTipTurn + +# Match controlsd / card (openpilot.common.realtime.DT_CTRL). +DT_CTRL = 0.01 + +# Longer than one Tesla indicator off-period (~0.3s at 90 flashes/min). +LAMP_OFF_DEBOUNCE_S = 1.0 + + +def blinker_pauses_lateral(left_blinker, right_blinker) -> bool: + return bool(left_blinker) != bool(right_blinker) + + +def stalk_is_left_or_right(stalk_state) -> bool: + return int(stalk_state or 0) in (1, 2) + + +def blinker_turn_blocks_steering_disengage(left_blinker, right_blinker, + stalk_state=0, hold=None, + emergency=False, alc_confirm=False) -> bool: + """Do not USER_DISABLE on hands-on / EPAS reject during a driver turn. + + During a tipped lane change (including the flash-dark gap), an + emergency yank must still disengage. A same-direction confirm does + not: callers leave ``emergency`` false and this gate stays closed. + + Hold state can lag a frame or expire on a Tesla lamp self-cancel while + the stalk is still LEFT/RIGHT. Raw one-lamp XOR and the physical stalk + are the hard gate; hold.blocks_steer_disengage covers flash gaps and + the post-turn hand-on window. + + Genuine hard faults (door, gear, stalk cancel, permanent steer fault) + are separate events and are not suppressed here. Hazards (both lamps) + are not a turn. A latched stalk is not ``alc_confirm``. + """ + if alc_confirm and tipped_lane_change_driver_release( + same_direction=False, emergency=bool(emergency)): + return False + if blinker_pauses_lateral(left_blinker, right_blinker): + return True + if stalk_is_left_or_right(stalk_state): + return True + return hold is not None and bool(hold.blocks_steer_disengage) + + +def preap_blinker_pause_hides_controls_mismatch(*, brand, fingerprint, + blocks_steer_disengage) -> bool: + """True when panda !controlsAllowed is the expected blinker-turn override. + + tesla_preap drops controls_allowed on hands-on >= 2 (and EPAS 6-9). During + a lat-paused driver turn that is the driver steering, not a real cancel. + Hiding that disagreement prevents EventName.controlsMismatch (2.0s) from + fully disabling while the lamps are still flashing. + """ + return (brand == "tesla" + and fingerprint == "TESLA_MODEL_S_PREAP" + and bool(blocks_steer_disengage)) + + +def pause_gated_by_alc(*, alc_active, stalk_is_turn=False, **_unused) -> bool: + """True when lamps are ALC, not a driver turn. + + stalk_is_turn is the already-classified driver-turn predicate (0.40s + from idle; 1.0s same-direction during ALC/keep-alive). Speed is not + part of this decision. + """ + if stalk_is_turn: + return False + return bool(alc_active) + + +class BlinkerLateralHold: + """Process-local latch: one lamp starts a pause; flash gaps stay paused; + hand-on keeps it after the turn is complete. ALC keep-alive is not a turn.""" + + def __init__(self): + self.holding = False + self.turn_active = False + self._dark_s = 0.0 + self._alc_keep = False + self._alc_dark_s = 0.0 + self._alc_direction = 0 + self._tip_turn = StalkTipTurn() + + def _reset(self): + self.holding = False + self.turn_active = False + self._dark_s = 0.0 + self._alc_keep = False + self._alc_dark_s = 0.0 + self._alc_direction = 0 + self._tip_turn.reset() + + @property + def blocks_steer_disengage(self) -> bool: + # Driver-turn pause, post-turn hand-on, ALC keep-alive (including + # leftover flashes), or the unclassified tip window must not + # USER_DISABLE cruise. + return self.holding or self.turn_active or self._alc_keep or self._tip_turn.is_pending + + def _enter_alc_keep(self, direction=0): + self.turn_active = False + self.holding = False + self._dark_s = 0.0 + self._alc_keep = True + self._alc_dark_s = 0.0 + if direction in (1, 2) and self._alc_direction not in (1, 2): + self._alc_direction = direction + + def update(self, left_blinker, right_blinker, steering_pressed, *, + engaged=True, dt=None, alc_active=False, v_ego=0.0, + stalk_state=0, steering_disengage=False, driver_turn=False) -> bool: + """``driver_turn``: controlsd's lane-change turn mode (lane_change_turn). + Treated like a latched stalk: a driver turn, not ALC keep-alive.""" + if dt is None: + dt = DT_CTRL + + if not engaged: + self._reset() + return False + + # Hands-on >= 2 / EPAS reject is the faster-corner override. It can + # rise before the torsion-bar steeringPressed debounce (5 frames). + steering_pressed = bool(steering_pressed) or bool(steering_disengage) + + self._tip_turn.update(stalk_state, dt) + one_lamp = blinker_pauses_lateral(left_blinker, right_blinker) + both_dark = (not left_blinker) and (not right_blinker) + lamp_dir = 1 if (left_blinker and not right_blinker) else ( + 2 if (right_blinker and not left_blinker) else 0) + if ((alc_active or self._alc_keep) and lamp_dir in (1, 2) and + self._alc_direction not in (1, 2)): + self._alc_direction = lamp_dir + alc_latched = bool(alc_active) or self._alc_keep + stalk_is_turn = self._tip_turn.is_driver_turn( + alc_latched=alc_latched, alc_direction=self._alc_direction) + + # Physical stalk held long enough: driver turn. Pause even if + # DesireHelper still has ALC armed for a frame. While the stalk is + # still LEFT/RIGHT, do not count flash-gap dark toward turn-end. + if stalk_is_turn or driver_turn: + self._alc_keep = False + self._alc_dark_s = 0.0 + self._alc_direction = 0 + self.turn_active = True + self._dark_s = 0.0 + elif (not (self.turn_active or self.holding) and + (pause_gated_by_alc(alc_active=alc_active) or self._tip_turn.tip_event)): + direction = self._tip_turn.tip_direction or lamp_dir + self._enter_alc_keep(direction) + return False + elif self._tip_turn.is_pending: + # Not yet tip vs turn. Do not pause and do not latch a turn from + # the driver's lamps — a tip will arm ALC on IDLE. + if self.turn_active or self.holding: + return True + return False + + if self._alc_keep: + if both_dark: + self._alc_dark_s += dt + if self._alc_dark_s >= LAMP_OFF_DEBOUNCE_S: + self._alc_keep = False + self._alc_dark_s = 0.0 + self._alc_direction = 0 + # Lane change ended with the driver still steering (e.g. turned + # at the intersection mid-change): same post-turn hand-on hold, + # so a hands-on edge does not USER_DISABLE until they let go. + if steering_pressed: + self.holding = True + else: + # Still the ALC keep-alive (or its leftover flashes), including gaps. + self._alc_dark_s = 0.0 + if lamp_dir in (1, 2) and self._alc_direction not in (1, 2): + self._alc_direction = lamp_dir + if self._alc_keep: + self.turn_active = False + self.holding = False + return False + + if one_lamp: + self.turn_active = True + self._dark_s = 0.0 + elif self.turn_active: + if both_dark: + # High EPS torque means the driver is still in the corner. + # Do not treat lamp-dark (flash gap or Tesla self-cancel) as + # turn-complete while they are wrenching the wheel. + if steering_disengage: + self._dark_s = 0.0 + else: + self._dark_s += dt + if self._dark_s >= LAMP_OFF_DEBOUNCE_S: + self.turn_active = False + self._dark_s = 0.0 + else: + # Hazards (both lamps) are not a turn. + self.turn_active = False + self._dark_s = 0.0 + + if self.turn_active: + self.holding = True + return True + if self.holding and steering_pressed: + return True + self.holding = False + return False + + +def lat_active_with_blinker_pause(*, active, steer_fault_temporary, steer_fault_permanent, + standstill, steer_at_standstill, + left_blinker, right_blinker, + steering_pressed=False, hold=None, dt=None, + alc_active=False, v_ego=0.0, stalk_state=0, + steering_disengage=False, engaged=None, + soft_lat_on=False, driver_turn=False) -> bool: + """Blinker lamp latch vs latActive. + + Always updates *hold* so a driver-turn (not ALC tip/keep-alive) is + still detected for the soft-lat re-enable gate. + When soft-lat is On, lamp latch must not clear latActive — the + handoff owns yield / inhibit / resume. Soft-lat Off keeps today's + pause so a held turn still frees the wheel. + """ + lat_active = bool(active) and not steer_fault_temporary and not steer_fault_permanent and \ + (not standstill or steer_at_standstill) + if engaged is None: + engaged = active + if hold is not None: + paused = hold.update(left_blinker, right_blinker, steering_pressed, + engaged=bool(engaged), dt=dt, alc_active=alc_active, + v_ego=v_ego, stalk_state=stalk_state, + steering_disengage=steering_disengage, + driver_turn=driver_turn) + else: + gated = pause_gated_by_alc(alc_active=alc_active) + paused = blinker_pauses_lateral(left_blinker, right_blinker) and not gated + if paused and not soft_lat_on: + return False + return lat_active diff --git a/selfdrive/controls/lib/cone_line.py b/selfdrive/controls/lib/cone_line.py new file mode 100644 index 00000000000000..a09089f9e225d1 --- /dev/null +++ b/selfdrive/controls/lib/cone_line.py @@ -0,0 +1,1159 @@ +"""Radar stationary-object cone line. Publishes the Oct 13 cone shift (wouldSteer). + +A line is stationary returns (ground speed near zero after adding vEgo) +sitting beside the model path, spread along the road. Posts are tracked +in the device frame and carried forward with ego speed and yaw, then +matched to the next scan by position. Track ids are not used: the radar +reissues them every second or two. + +One mailbox, a parked car (a short wide cluster), and a continuous +guardrail are not a cone line. A guardrail is flagged rather than +dropped when the spacing gives it away. + +The scan is one pass over a capped point list, a nearest-neighbour +match, and a 3-coefficient fit. Call it at radar rate (~8 Hz). + +Frames (this is the bug the Oct 7 posts exposed): + radarState.yRel +left + model position.y +right (device frame), same as PathObstacle y + device y -yRel, so +right + path-relative lat device y minus the path, +right. Negative means + the line is on the driver's left. + side +1 left of the path, -1 right. Opposite sign from + lat, because lat is +right. + steeringTorque +left. The hold compares torque to side, and path + y / curvature to lat. Those are different frames. + wouldLimit path shift, +right, that would open ~1 m of clearance + wouldSteer Oct 13 in-lane cone shift, +right, cap 1.0 m, ramped + 0.2 m/s. controlsd applies it (NAPConeLineHold) when + the driver is not holding his own line. + +Thresholds: + stationary ground speed |vRel + vEgo| < 1.2 m/s + beside the path 0.30–2.5 m to start a line; 0.30–4.0 m at + >= 20 m/s (drums in a closed adjacent lane, + Oct 10 17:30). Town keeps 2.5 m: parked cars + and poles sit ~3 m out. Once the line + is up, posts closer than that (the taper + inside the old 0.5 m band) stay on it. + longitudinal window 6–70 m ahead of the camera + cone line >= 4 tracked posts with span >= 10 m, or + >= 3 posts with span >= 25 m at >= 20 m/s + (sparse highway returns); residual to a ground-frame quadratic + <= 0.50 m; median gap 1.5 m to max(18 m, + 1.0 s of travel) capped at 35 m (discrete, not a rail) + confirm / drop 1.0 s of fresh hits to become active. + A gap over 0.25 s resets that count (0.6 s at + >= 20 m/s). Before a line is up, an unrefreshed + post is remembered 1.2 s (2.5 s at >= 20 m/s). + An active line holds ~2 s after the hits stop, + and 1–3 posts on the fit are enough to refresh it. + wouldSteer line 1.2–2.6 m from path centre, >= 20 mph, no lead + in the span, no overhead structure: aim the line at + 3.2 m, cap 1.0 m, inside the lane, ramp 0.2 m/s + guardrail span >= 12 m, >= 8 posts, median gap < 1.25 m + parked car short cluster (< 8 m) that is wide (>= 1.0 m) +""" +from __future__ import annotations + +import math +import time +from dataclasses import dataclass, replace + +from openpilot.selfdrive.controls.lib.radar_path_gate import RADAR_TO_CAMERA_M, path_y_at_x + +STATIONARY_MPS = 1.2 +LAT_MIN_M = 0.30 +LAT_MAX_M = 2.50 +LAT_MAX_FAST_M = 4.00 # >= FAST_MPS: drums in a closed adjacent lane sit 2.5–4 m out +X_MIN_M = 6.0 +X_MAX_M = 70.0 +X_KEEP_MIN_M = 4.0 +MIN_COUNT = 4 +MIN_SPAN_M = 10.0 +MAX_LAT_STD_M = 0.50 +MIN_GAP_M = 1.5 +MAX_GAP_M = 18.0 +MAX_GAP_S = 1.0 # at speed the allowed median gap grows to ~1 s of travel +MAX_GAP_CAP_M = 35.0 +MIN_COUNT_LONG = 3 +MIN_SPAN_LONG_M = 25.0 +CONFIRM_S = 1.0 +DROP_S = 2.0 +CONFIRM_GAP_S = 0.25 +CLEARANCE_M = 1.0 +# Oct 13 cone shift (steers through controlsd, NAPConeLineHold toggle). +# Pass E: Justin held ~1.0 m away with the drums ~2.2 m from path centre. +SHIFT_TRIGGER_M = 2.6 # line within this of the path centre +SHIFT_INSIDE_M = 1.2 # closer than this is our own footprint (overpass, queue) +SHIFT_TARGET_LAT_M = 3.2 # aim for the line this far from the path centre +SHIFT_MIN_MPS = 8.94 # 20 mph +WOULD_STEER_CAP_M = 1.0 +WOULD_STEER_RATE_MPS = 0.20 # slow ramp: 0 -> 1 m takes ~5 s +CAR_HALF_M = 0.95 +LANE_MARGIN_M = 0.10 +# Overhead structure: stationary returns on both sides at one range. +OVERHEAD_DEPTH_M = 3.0 +OVERHEAD_MIN_COUNT = 4 +OVERHEAD_SIDE_M = 1.0 +OVERHEAD_HOLD_S = 2.0 +LOOKAHEADS_M = (15.0, 30.0, 45.0) +BARRIER_MIN_COUNT = 8 +BARRIER_MIN_SPAN_M = 12.0 +BARRIER_MAX_GAP_M = 1.25 +PARKED_MAX_SPAN_M = 8.0 +PARKED_MIN_WIDTH_M = 1.0 +ROAD_EDGE_MARGIN_M = 0.40 +MIN_VEGO_CONFIRM_MPS = 3.0 +POST_TTL_PRE_S = 1.2 +# Highway: sparse returns. Remember a stationary post (carried by ego motion) +# for up to this long, and tolerate this long between fresh hits while confirming. +POST_TTL_PRE_FAST_S = 2.5 +CONFIRM_GAP_FAST_S = 0.6 +FAST_MPS = 20.0 +POST_TTL_ACTIVE_S = 2.2 +ASSOC_GATE_M = 2.2 +FIT_TOL_M = 1.05 +MAX_POINTS = 48 +MAX_POSTS = 36 +CONE_BUDGET_S = 0.002 +MAX_QUADRATIC = 0.01 + + +@dataclass(frozen=True) +class ConeLineSample: + active: bool = False + side: int = 0 # +1 left of the path, -1 right, 0 none + confidence: float = 0.0 + count: int = 0 + lat_near: float = 0.0 # path-relative, +right + lat_mid: float = 0.0 + lat_far: float = 0.0 + would_limit: float = 0.0 # path shift, +right, to keep ~1 m clearance + would_steer: float = 0.0 # Oct 13 cone shift, +right, |v| <= 1.0 m, ramped. controlsd applies it. + barrier: bool = False + parked: bool = False + span_m: float = 0.0 + # Oct 14 corridor (route 194 seg 25): both sides tracked at once. + left_active: bool = False + left_clear: float = 0.0 # m from path centre to the nearest left post (>0), 0 when none + right_active: bool = False + right_clear: float = 0.0 # m from path centre to the nearest right post (>0), 0 when none + corridor: bool = False # both sides active: steer to the midpoint + margin: float = 0.0 # smallest clearance to a tracked line after wouldSteer, m + releasing: bool = False # corridor ended; wouldSteer is easing back to 0 + + +@dataclass +class _Post: + x: float + y: float # device frame, +right + age: float = 0.0 + + +@dataclass +class _Group: + side: int + posts: list + fit: tuple + kind: str + resid: float + + @property + def count(self) -> int: + return len(self.posts) + + @property + def span(self) -> float: + if len(self.posts) < 2: + return 0.0 + xs = [p.x for p in self.posts] + return max(xs) - min(xs) + + +def _num(value) -> float | None: + try: + out = float(value) + except (TypeError, ValueError): + return None + if not math.isfinite(out): + return None + return out + + +def _median(vals: list[float]) -> float: + if not vals: + return 0.0 + ordered = sorted(vals) + n = len(ordered) + mid = n // 2 + if n % 2: + return ordered[mid] + return 0.5 * (ordered[mid - 1] + ordered[mid]) + + +def _std(vals: list[float]) -> float: + n = len(vals) + if n < 2: + return 0.0 + mean = sum(vals) / n + return math.sqrt(sum((v - mean) ** 2 for v in vals) / n) + + +def device_y_right(y_rel: float) -> float: + """radarState.yRel is +left. Device / model / PathObstacle y is +right.""" + return -float(y_rel) + + +def model_yaw_rate_right(model) -> float: + """Ego yaw rate in the device frame, rad/s, positive to the right. + + modelV2.orientationRate.z is around device z (down), so positive z is a + right turn — the same sign as model position.y. Missing or absurd + values are 0, which leaves speed-only compensation. + """ + try: + zs = model.orientationRate.z + if len(zs) == 0: + return 0.0 + z = float(zs[0]) + except Exception: + return 0.0 + if not math.isfinite(z) or abs(z) > 1.5: + return 0.0 + return z + + +def _solve3(a, b): + """Solve a 3x3 system. None when the matrix is singular.""" + m = [a[i][:] + [b[i]] for i in range(3)] + for col in range(3): + pivot = max(range(col, 3), key=lambda r: abs(m[r][col])) + if abs(m[pivot][col]) < 1e-8: + return None + m[col], m[pivot] = m[pivot], m[col] + div = m[col][col] + for j in range(col, 4): + m[col][j] /= div + for r in range(3): + if r == col: + continue + factor = m[r][col] + if factor == 0.0: + continue + for j in range(col, 4): + m[r][j] -= factor * m[col][j] + return (m[0][3], m[1][3], m[2][3]) + + +def _fit_curve(xs: list[float], ys: list[float]) -> tuple | None: + """Ground-frame quadratic y = a + b u + c u^2, u = x - mean(x). + + Four posts use a line. Five or more use a quadratic, and a wild + curvature coefficient falls back to the line. + """ + n = len(xs) + if n == 0: + return None + x0 = sum(xs) / n + us = [x - x0 for x in xs] + sy = sum(ys) + su = sum(us) + su2 = sum(u * u for u in us) + suy = sum(u * y for u, y in zip(us, ys)) + det = n * su2 - su * su + if abs(det) < 1e-6: + return (sy / n, 0.0, 0.0, x0) + b = (n * suy - su * sy) / det + a = (sy - b * su) / n + linear = (a, b, 0.0, x0) + if n < 5: + return linear + p = [0.0, 0.0, 0.0, 0.0, 0.0] + rhs = [0.0, 0.0, 0.0] + for u, y in zip(us, ys): + up = 1.0 + for k in range(5): + p[k] += up + up *= u + rhs[0] += y + rhs[1] += u * y + rhs[2] += u * u * y + coef = _solve3( + [[p[0], p[1], p[2]], [p[1], p[2], p[3]], [p[2], p[3], p[4]]], + rhs, + ) + if coef is None or abs(coef[2]) > MAX_QUADRATIC: + return linear + return (coef[0], coef[1], coef[2], x0) + + +def _eval(fit, x: float) -> float: + a, b, c, x0 = fit + u = x - x0 + return a + u * (b + u * c) + + +def _residual(posts, fit) -> float: + if fit is None or len(posts) < 2: + return 0.0 + return _std([p.y - _eval(fit, p.x) for p in posts]) + + +def road_edges_xy(model) -> list[tuple[list[float], list[float]]]: + """modelV2.roadEdges as (x, y) polylines. Empty when the model has none.""" + try: + edges = model.roadEdges + except (TypeError, AttributeError): + return [] + out: list[tuple[list[float], list[float]]] = [] + try: + iterator = list(edges) + except TypeError: + return [] + for edge in iterator: + try: + xs = [float(v) for v in edge.x] + ys = [float(v) for v in edge.y] + except (TypeError, ValueError, AttributeError): + continue + if len(xs) >= 2 and len(xs) == len(ys) and all(math.isfinite(v) for v in xs + ys): + out.append((xs, ys)) + return out + + +def _outside_road(edges, x: float, y: float) -> bool: + """True when both edges exist and the return sits past the road. + + Edge y is model / device y, +right, same as `y`. + """ + if len(edges) < 2: + return False + ys = [] + for xs, ys_edge in edges[:2]: + ey = path_y_at_x(xs, ys_edge, x) + if ey is None or not math.isfinite(ey): + return False + ys.append(ey) + lo, hi = min(ys), max(ys) + if hi - lo < 1.0: + return False + return y > hi + ROAD_EDGE_MARGIN_M or y < lo - ROAD_EDGE_MARGIN_M + + +def _path_lat(y: float, x: float, path_x, path_y) -> float: + py = path_y_at_x(path_x, path_y, x) + if py is None or not math.isfinite(py): + return y + return y - py + + +def _side_of_lat(lat: float) -> int: + """lat is +right. +1 is the driver's left, -1 the right.""" + if lat > 0.05: + return -1 + if lat < -0.05: + return 1 + return 0 + + +def _would_shift(side: int, clearance: float) -> float: + """Signed path shift, +right, that opens CLEARANCE_M beside the line.""" + if side == 0: + return 0.0 + need = CLEARANCE_M - clearance + if need <= 0.0: + return 0.0 + # Left line (side +1): move the path right, which is positive y. + return float(side) * need + + +def cone_shift_target(sample: ConeLineSample, *, v_ego: float, clearance: float, + lead_in_span: bool, overhead: bool, lane_room: float | None) -> float: + """Signed in-lane path shift, +right, away from an active cone line. 0 = none. + + Never for a line inside SHIFT_INSIDE_M (our own footprint: overpass deck, + a queue), below 20 mph, with a lead in the cone span, or under an overpass. + lane_room is how far the car can move away before its edge reaches the + far lane line; None means unknown and caps the shift at the full 1.0 m. + """ + if not sample.active or sample.side not in (-1, 1): + return 0.0 + if not math.isfinite(clearance) or clearance < SHIFT_INSIDE_M or clearance > SHIFT_TRIGGER_M: + return 0.0 + if not math.isfinite(v_ego) or v_ego < SHIFT_MIN_MPS or lead_in_span or overhead: + return 0.0 + mag = min(WOULD_STEER_CAP_M, SHIFT_TARGET_LAT_M - clearance) + if lane_room is not None and math.isfinite(lane_room): + mag = min(mag, max(0.0, lane_room)) + if mag <= 0.0: + return 0.0 + # Left line (side +1): move right, +y. + return float(sample.side) * mag + + +def lane_room_m(model, side: int, x: float = 15.0) -> float | None: + """Room to move away from a cone line on `side` before the car edge meets the far lane line. + + side +1 (left line) moves right, toward the right lane line. Device y is +right. + """ + try: + lines = list(model.laneLines) + probs = list(model.laneLineProbs) + except (TypeError, AttributeError): + return None + if len(lines) < 3 or len(probs) < 3: + return None + idx = 2 if side == 1 else 1 + if float(probs[idx]) < 0.3: + return None + try: + ly = path_y_at_x([float(v) for v in lines[idx].x], [float(v) for v in lines[idx].y], x) + except (TypeError, ValueError, AttributeError): + return None + if ly is None or not math.isfinite(ly): + return None + room = abs(ly) - CAR_HALF_M - LANE_MARGIN_M + return max(0.0, room) + + +def overhead_ranges(points, v_ego: float, path_x, path_y) -> list[float]: + """Ranges (camera x) where stationary returns sit on both sides of the path. + + An overpass deck or a sign gantry spans the road at one range. + """ + rows = [] + try: + iterator = list(points) if points is not None else [] + except TypeError: + return [] + for raw in iterator[:MAX_POINTS * 2]: + fields = _read_point(raw) + if fields is None: + continue + d_rel, y_rel, v_rel = fields + if abs(v_rel + v_ego) >= STATIONARY_MPS: + continue + x = d_rel + RADAR_TO_CAMERA_M + if x < X_MIN_M or x > X_MAX_M + 30.0: + continue + rows.append((x, _path_lat(device_y_right(y_rel), x, path_x, path_y))) + rows.sort() + out = [] + for i, (x0, _l) in enumerate(rows): + band = [lat for x, lat in rows[i:] if x - x0 <= OVERHEAD_DEPTH_M] + if len(band) >= OVERHEAD_MIN_COUNT and min(band) < -OVERHEAD_SIDE_M and max(band) > OVERHEAD_SIDE_M: + out.append(x0) + return out + + +def _cap_steer(shift: float) -> float: + if not math.isfinite(shift) or shift == 0.0: + return 0.0 + mag = min(abs(shift), WOULD_STEER_CAP_M) + return math.copysign(mag, shift) + + +def _dedupe(posts: list[_Post]) -> list[_Post]: + if len(posts) < 2: + return posts + posts = sorted(posts, key=lambda p: p.x) + out = [posts[0]] + for p in posts[1:]: + prev = out[-1] + if math.hypot(p.x - prev.x, p.y - prev.y) < 0.75: + if p.age < prev.age: + out[-1] = p + continue + out.append(p) + return out + + +def _speed(v_ego) -> float: + try: + v = abs(float(v_ego)) + except (TypeError, ValueError): + return 0.0 + return v if math.isfinite(v) else 0.0 + + +def lat_max_m(v_ego: float) -> float: + """Outer start band. Town keeps 2.5 m (parked cars, poles at 3 m); highway reaches 4 m.""" + return LAT_MAX_FAST_M if _speed(v_ego) >= FAST_MPS else LAT_MAX_M + + +def max_gap_m(v_ego: float) -> float: + """Allowed median post gap. 18 m in town, ~1 s of travel at speed, capped at 35 m.""" + return min(MAX_GAP_CAP_M, max(MAX_GAP_M, _speed(v_ego) * MAX_GAP_S)) + + +def _classify(side: int, posts: list[_Post], path_x, path_y, v_ego: float = 0.0) -> _Group | None: + if len(posts) < 2: + return None + posts = sorted(posts, key=lambda p: p.x) + xs = [p.x for p in posts] + ys = [p.y for p in posts] + span = xs[-1] - xs[0] + gaps = [xs[i] - xs[i - 1] for i in range(1, len(xs)) if xs[i] - xs[i - 1] >= 0.3] + med_gap = _median(gaps) if gaps else 0.0 + lats = [_path_lat(p.y, p.x, path_x, path_y) for p in posts] + lat_range = max(lats) - min(lats) + fit = _fit_curve(xs, ys) + if fit is None: + return None + resid = _residual(posts, fit) + group = _Group(side=side, posts=posts, fit=fit, kind="", resid=resid) + if span >= BARRIER_MIN_SPAN_M and len(posts) >= BARRIER_MIN_COUNT and med_gap < BARRIER_MAX_GAP_M: + group.kind = "barrier" + return group + wide_short = span < PARKED_MAX_SPAN_M and span > 0.4 and ( + lat_range >= PARKED_MIN_WIDTH_M or (len(posts) >= 4 and span < 6.0 and resid > MAX_LAT_STD_M) + ) + if wide_short: + group.kind = "parked" + return group + enough = len(posts) >= MIN_COUNT and span >= MIN_SPAN_M + enough_long = _speed(v_ego) >= FAST_MPS and len(posts) >= MIN_COUNT_LONG and span >= MIN_SPAN_LONG_M + if ( + (enough or enough_long) + and resid <= MAX_LAT_STD_M + and med_gap >= MIN_GAP_M + and med_gap <= max_gap_m(v_ego) + ): + group.kind = "cones" + return group + return None + + +def _moved(posts: list[_Post], v: float, yaw: float, dt: float) -> list[_Post]: + """Carry posts into the current device frame. + + y is +right and yaw is +right (positive = right turn). The vehicle + moved forward by v*dt and rotated by yaw*dt. + """ + ds = v * dt + dpsi = yaw * dt + if dpsi > 0.25: + dpsi = 0.25 + elif dpsi < -0.25: + dpsi = -0.25 + c = math.cos(dpsi) + s = math.sin(dpsi) + out = [] + for p in posts: + xr = p.x - ds + yr = p.y + out.append(_Post(c * xr + s * yr, -s * xr + c * yr, p.age + dt)) + return out + + +def _aged(posts: list[_Post], dt: float) -> list[_Post]: + return [_Post(p.x, p.y, p.age + dt) for p in posts] + + +def _match_cost(posts: list[_Post], meas: list[tuple[float, float]]) -> float: + if not meas: + return 0.0 + penalty = 4.0 + total = 0.0 + for mx, my in meas: + best = penalty + for p in posts: + d = math.hypot(p.x - mx, p.y - my) + if d < best: + best = d + total += best + return total + + +def _choose_motion(posts, meas, v, yaw, dt) -> list[_Post]: + """Speed-and-yaw compensation, unless a static repeat of the same scan fits better. + + Replayed tests hand the same vehicle-frame points every cycle. On the + road the points step back by about v*dt, and the compensated posts are + the ones that match. + """ + if not posts or dt <= 0.0: + return _aged(posts, dt) + options = [_moved(posts, v, yaw, dt)] + if abs(yaw) > 1e-4: + options.append(_moved(posts, v, 0.0, dt)) + options.append(_aged(posts, dt)) + best = options[0] + best_cost = _match_cost(best, meas) + for cand in options[1:]: + cost = _match_cost(cand, meas) + if cost < best_cost - 1e-6: + best = cand + best_cost = cost + return best + + +def _associate(posts: list[_Post], meas: list[tuple[float, float]]) -> list[_Post]: + used = [False] * len(posts) + for mx, my in meas: + best_i = -1 + best_d = ASSOC_GATE_M + for i, p in enumerate(posts): + if used[i]: + continue + d = math.hypot(p.x - mx, p.y - my) + if d < best_d: + best_i = i + best_d = d + if best_i < 0: + posts.append(_Post(mx, my, 0.0)) + used.append(True) + else: + used[best_i] = True + posts[best_i].x = mx + posts[best_i].y = my + posts[best_i].age = 0.0 + return posts + + +def _lat_at(group: _Group, path_x, path_y, xq: float) -> float: + xs = [p.x for p in group.posts] + xmin, xmax = min(xs), max(xs) + x = xmin if xq < xmin else xmax if xq > xmax else xq + y = _eval(group.fit, x) + return _path_lat(y, x, path_x, path_y) + + +def _sample_from_group(group: _Group | None, *, active: bool, confidence: float, + barrier: bool, parked: bool, path_x, path_y) -> ConeLineSample: + if group is None or group.kind == "parked": + return ConeLineSample(active=False, barrier=barrier, parked=parked, confidence=min(confidence, 0.49)) + lats = [_lat_at(group, path_x, path_y, x) for x in LOOKAHEADS_M] + point_lats = [_path_lat(p.y, p.x, path_x, path_y) for p in group.posts] + clearance = min(abs(v) for v in point_lats) if point_lats else min(abs(v) for v in lats) + shift = _would_shift(group.side, clearance) if group.kind == "cones" else 0.0 + return ConeLineSample( + active=active and group.kind == "cones", + side=group.side, + confidence=confidence, + count=group.count, + lat_near=lats[0], + lat_mid=lats[1], + lat_far=lats[2], + would_limit=shift, + would_steer=0.0, + barrier=barrier or group.kind == "barrier", + parked=parked, + span_m=group.span, + ) + + +def _read_point(raw): + if isinstance(raw, dict): + d = _num(raw.get("dRel", raw.get("d_rel"))) + y = _num(raw.get("yRel", raw.get("y_rel"))) + v = _num(raw.get("vRel", raw.get("v_rel"))) + measured = raw.get("measured", True) + else: + d = _num(getattr(raw, "dRel", None)) + y = _num(getattr(raw, "yRel", None)) + v = _num(getattr(raw, "vRel", None)) + measured = getattr(raw, "measured", True) + if d is None or y is None or v is None or not bool(measured): + return None + return d, y, v + + +class ConeLineDetector: + """Temporal cone line. State is the post buffer plus the confirm timer.""" + + @property + def group(self) -> _Group | None: + return self._last_group if self._active else None + + def __init__(self, side_filter: int = 0) -> None: + # side_filter: 0 = both sides (legacy, one line), +1 left only, -1 right only. + self._side_filter = int(side_filter) + self._last_out = ConeLineSample() + self._ws = 0.0 + self._overhead_s = 0.0 + self.reset() + + def reset(self) -> None: + self._posts: list[_Post] = [] + self._seen_s = 0.0 + self._miss_s = 0.0 + self._active = False + self._side = 0 + self._fit = None + self._last_group: _Group | None = None + + def update(self, points, v_ego: float, path_x, path_y, road_edges, dt: float, + yaw_rate: float = 0.0, *, lead_xs=(), lane_room=None) -> ConeLineSample: + """yaw_rate is device-frame rad/s, positive to the right. Optional. + + lead_xs: ranges (camera x) of leads in our lane. lane_room: see lane_room_m. + """ + t0 = time.monotonic() + try: + sample = self._step(points, v_ego, path_x, path_y, road_edges, dt, yaw_rate, t0) + if sample is not self._last_out: + sample = self._with_shift(sample, points, v_ego, path_x, path_y, dt, lead_xs, lane_room) + sample = self._ramp(sample, dt) + except Exception: + self.reset() + self._ws = 0.0 + sample = ConeLineSample() + self._last_out = sample + return sample + + def _with_shift(self, sample, points, v_ego, path_x, path_y, dt, lead_xs, lane_room): + try: + v = float(v_ego) + except (TypeError, ValueError): + v = 0.0 + try: + d = max(0.0, min(0.5, float(dt))) + except (TypeError, ValueError): + d = 0.0 + group = self._last_group + if not sample.active or group is None or group.kind != "cones": + return sample + xs = [p.x for p in group.posts] + x_lo, x_hi = min(xs), max(xs) + over = overhead_ranges(points, v, path_x, path_y) + if any(x_lo - OVERHEAD_DEPTH_M <= x <= x_hi + OVERHEAD_DEPTH_M for x in over): + self._overhead_s = OVERHEAD_HOLD_S + else: + self._overhead_s = max(0.0, self._overhead_s - d) + leads = [] + for lx in lead_xs or (): + try: + leads.append(float(lx)) + except (TypeError, ValueError): + continue + lead_in_span = any(x_lo - 5.0 <= lx <= x_hi + 5.0 for lx in leads) + point_lats = [_path_lat(p.y, p.x, path_x, path_y) for p in group.posts] + clearance = min(abs(v_) for v_ in point_lats) if point_lats else float("nan") + target = cone_shift_target(sample, v_ego=v, clearance=clearance, lead_in_span=lead_in_span, + overhead=self._overhead_s > 0.0, lane_room=lane_room) + return replace(sample, would_steer=target) + + def _ramp(self, sample: ConeLineSample, dt) -> ConeLineSample: + """Rate-limit wouldSteer so the shift ramps in and out slowly (0.2 m/s).""" + if sample is self._last_out: + return sample + try: + step = WOULD_STEER_RATE_MPS * max(0.0, min(0.5, float(dt))) + except (TypeError, ValueError): + step = 0.0 + if not math.isfinite(step): + step = 0.0 + target = sample.would_steer if sample.active else 0.0 + if self._ws * target < 0.0: + self._ws = 0.0 + delta = target - self._ws + self._ws += max(-step, min(step, delta)) + if abs(self._ws) < 1e-4: + self._ws = 0.0 + return replace(sample, would_steer=self._ws) + + def _step(self, points, v_ego, path_x, path_y, road_edges, dt, yaw_rate, t0) -> ConeLineSample: + dt = 0.0 if dt is None else float(dt) + if not math.isfinite(dt) or dt < 0.0: + dt = 0.0 + dt = min(dt, 0.5) + try: + v_ego_f = float(v_ego) + except (TypeError, ValueError): + v_ego_f = 0.0 + if not math.isfinite(v_ego_f): + v_ego_f = 0.0 + try: + yaw = float(yaw_rate) + except (TypeError, ValueError): + yaw = 0.0 + if not math.isfinite(yaw): + yaw = 0.0 + + if time.monotonic() - t0 > CONE_BUDGET_S: + return self._last_out + + meas = self._measurements(points, v_ego_f, path_x, path_y, road_edges or [], t0) + self._posts = _choose_motion(self._posts, meas, v_ego_f, yaw, dt) + self._posts = _associate(self._posts, meas) + fast = v_ego_f >= FAST_MPS + ttl = POST_TTL_ACTIVE_S if self._active else (POST_TTL_PRE_FAST_S if fast else POST_TTL_PRE_S) + self._posts = [ + p for p in self._posts + if p.age <= ttl and X_KEEP_MIN_M <= p.x <= X_MAX_M + 2.0 + ] + self._posts = _dedupe(self._posts) + if len(self._posts) > MAX_POSTS: + self._posts = sorted(self._posts, key=lambda p: p.age)[:MAX_POSTS] + + if time.monotonic() - t0 > CONE_BUDGET_S: + return self._last_out + + left, right = self._split(path_x, path_y, v_ego_f) + left_g = _classify(1, left, path_x, path_y, v_ego_f) + right_g = _classify(-1, right, path_x, path_y, v_ego_f) + parked = (left_g is not None and left_g.kind == "parked") or (right_g is not None and right_g.kind == "parked") + barrier_group = None + cones = None + for group in (left_g, right_g): + if group is None: + continue + if group.kind == "barrier" and (barrier_group is None or group.span > barrier_group.span): + barrier_group = group + elif group.kind == "cones" and (cones is None or group.count > cones.count): + cones = group + + allow_confirm = v_ego_f >= MIN_VEGO_CONFIRM_MPS + supported = False + fresh_cones = cones is not None and any(p.age <= 1e-9 for p in cones.posts) + same_side = cones is not None and (self._side == 0 or cones.side == self._side or not self._active) + if fresh_cones and same_side and (allow_confirm or self._active): + if self._side not in (0, cones.side) and not self._active: + self._seen_s = 0.0 + self._side = cones.side + self._fit = cones.fit + self._last_group = cones + self._seen_s = min(CONFIRM_S + 1.0, self._seen_s + dt) + self._miss_s = 0.0 + supported = True + elif self._active and self._fit is not None: + held = left if self._side == 1 else right if self._side == -1 else [] + fresh_on = [p for p in held if p.age <= 1e-9 and abs(p.y - _eval(self._fit, p.x)) <= FIT_TOL_M] + if fresh_on: + self._miss_s = 0.0 + supported = True + if len(held) >= 2: + fit2 = _fit_curve([p.x for p in held], [p.y for p in held]) + if fit2 is not None and _residual(held, fit2) <= MAX_LAT_STD_M: + self._fit = fit2 + self._last_group = _Group(self._side, held, fit2, "cones", _residual(held, fit2)) + + if not supported: + self._miss_s += dt + if not self._active and self._miss_s > (CONFIRM_GAP_FAST_S if fast else CONFIRM_GAP_S): + self._seen_s = 0.0 + self._side = 0 + self._fit = None + self._last_group = None + if self._active and self._miss_s >= DROP_S: + self._active = False + self._seen_s = 0.0 + self._side = 0 + self._fit = None + self._last_group = None + + if ( + not self._active + and allow_confirm + and self._last_group is not None + and self._last_group.kind == "cones" + and self._seen_s + 1e-9 >= CONFIRM_S + ): + self._active = True + + shown = self._last_group + if shown is not None and shown.kind != "cones" and not self._active: + shown = shown + if self._active and (shown is None or shown.kind != "cones"): + shown = self._last_group + persist = 0.0 if CONFIRM_S <= 0 else min(1.0, self._seen_s / CONFIRM_S) + resid = shown.resid if shown is not None else MAX_LAT_STD_M + align = max(0.0, 1.0 - resid / MAX_LAT_STD_M) + confidence = persist * (0.65 + 0.35 * align) + if not self._active: + confidence = min(confidence, 0.49) + barrier = barrier_group is not None or (shown is not None and shown.kind == "barrier") + if shown is None and barrier_group is not None: + shown = barrier_group + confidence = min(confidence, 0.49) + if shown is not None and shown.kind == "parked": + shown = None + return _sample_from_group( + shown, + active=self._active and shown is not None and shown.kind == "cones", + confidence=confidence, + barrier=barrier, + parked=parked, + path_x=path_x, + path_y=path_y, + ) + + def _measurements(self, points, v_ego, path_x, path_y, edges, t0): + try: + iterator = list(points) if points is not None else [] + except TypeError: + return [] + meas = [] + for raw in iterator: + if len(meas) >= MAX_POINTS or time.monotonic() - t0 > CONE_BUDGET_S: + break + fields = _read_point(raw) + if fields is None: + continue + d_rel, y_rel, v_rel = fields + if abs(v_rel + v_ego) >= STATIONARY_MPS: + continue + x = d_rel + RADAR_TO_CAMERA_M + if x < X_MIN_M or x > X_MAX_M: + continue + y = device_y_right(y_rel) + if _outside_road(edges, x, y): + continue + lat = _path_lat(y, x, path_x, path_y) + if abs(lat) > lat_max_m(v_ego): + continue + if self._side_filter and _side_of_lat(lat) == -self._side_filter: + continue + if abs(lat) < LAT_MIN_M: + if not (self._active and self._fit is not None and self._side in (-1, 1) + and abs(y - _eval(self._fit, x)) <= FIT_TOL_M): + continue + meas.append((x, y)) + return meas + + def _split(self, path_x, path_y, v_ego: float = 0.0): + left: list[_Post] = [] + right: list[_Post] = [] + for p in self._posts: + if p.x < X_MIN_M or p.x > X_MAX_M: + continue + lat = _path_lat(p.y, p.x, path_x, path_y) + if abs(lat) > lat_max_m(v_ego) + 0.4: + continue + side = self._side if ( + self._active and self._fit is not None and abs(lat) < LAT_MIN_M + and abs(p.y - _eval(self._fit, p.x)) <= FIT_TOL_M + ) else _side_of_lat(lat) + if self._side_filter and side != self._side_filter: + continue + if side == 1: + left.append(p) + elif side == -1: + right.append(p) + return left, right + + +# ---- Oct 14 cone corridor ------------------------------------------------ +# Route 194 seg 25 (Ridgewood Rd, 08:28:47-08:29:14 CT): cones on the +# centreline AND barrels on the right. The one-line detector tracked only the +# right barrels, shifted left (wouldSteer -0.25) and drifted into the +# untracked left cones. Now each side has its own tracker: +# both sides steer to the corridor midpoint +# one side firm offset away from it (cap 1.0 m, lane room) +# hard rule never shift to within CORRIDOR_MARGIN_M of a tracked line; +# a line already inside it pushes the path away +# release after both sides drop (detector DROP_S ~2 s), wouldSteer +# eases to 0 over RELEASE_S with a smoothstep, no snap +CORRIDOR_MARGIN_M = 1.5 +CORRIDOR_SHIFT_MIN_MPS = 6.7 # 15 mph; the Oct 14 zone ramped up from ~19 mph +CORRIDOR_INSIDE_M = 0.6 # closer than this is our own footprint +CORRIDOR_RATE_MPS = 0.5 # normal ramp-in +CORRIDOR_RATE_URGENT_MPS = 1.0 # ramp when a line is already inside the margin +CORRIDOR_RELEASE_S = 3.0 + + +def _group_clear(group: _Group | None, path_x, path_y) -> float | None: + if group is None or group.kind != "cones" or not group.posts: + return None + lats = [abs(_path_lat(p.y, p.x, path_x, path_y)) for p in group.posts] + c = min(lats) + return c if math.isfinite(c) else None + + +def corridor_bounds(left_clear: float | None, right_clear: float | None) -> tuple[float, float]: + """Allowed path shift (+right) that keeps CORRIDOR_MARGIN_M to each tracked line.""" + lo = -math.inf if left_clear is None else CORRIDOR_MARGIN_M - left_clear + hi = math.inf if right_clear is None else right_clear - CORRIDOR_MARGIN_M + return lo, hi + + +def corridor_target(left_clear: float | None, right_clear: float | None, *, v_ego: float, + lead_in_span: bool = False, overhead: bool = False, + room_right: float | None = None, room_left: float | None = None) -> float: + """In-lane path shift, +right. left_clear / right_clear: distance from path centre (>0) or None. + + room_right: room to move right (away from a left line); room_left the same to the left. + """ + if left_clear is not None and (not math.isfinite(left_clear) or left_clear < CORRIDOR_INSIDE_M): + left_clear = None + if right_clear is not None and (not math.isfinite(right_clear) or right_clear < CORRIDOR_INSIDE_M): + right_clear = None + if left_clear is None and right_clear is None: + return 0.0 + if not math.isfinite(v_ego) or v_ego < CORRIDOR_SHIFT_MIN_MPS or lead_in_span or overhead: + return 0.0 + lo, hi = corridor_bounds(left_clear, right_clear) + if left_clear is not None and right_clear is not None: + s = 0.5 * (right_clear - left_clear) # midpoint of the corridor + elif left_clear is not None: + s = 0.0 if left_clear > SHIFT_TRIGGER_M else min(WOULD_STEER_CAP_M, SHIFT_TARGET_LAT_M - left_clear) + if room_right is not None and math.isfinite(room_right): + s = min(s, max(0.0, room_right)) + s = max(s, lo) # margin wins over lane room + else: + s = 0.0 if right_clear > SHIFT_TRIGGER_M else -min(WOULD_STEER_CAP_M, SHIFT_TARGET_LAT_M - right_clear) + if room_left is not None and math.isfinite(room_left): + s = max(s, -max(0.0, room_left)) + s = min(s, hi) + if lo <= hi: + s = min(hi, max(lo, s)) + return max(-WOULD_STEER_CAP_M, min(WOULD_STEER_CAP_M, s)) + + +def corridor_margin(shift: float, left_clear: float | None, right_clear: float | None) -> float: + vals = [] + if left_clear is not None: + vals.append(left_clear + shift) + if right_clear is not None: + vals.append(right_clear - shift) + return min(vals) if vals else 0.0 + + +class ConeCorridorDetector: + """Left and right cone lines tracked at once, fused into one wouldSteer.""" + + def __init__(self) -> None: + self.left = ConeLineDetector(side_filter=1) + self.right = ConeLineDetector(side_filter=-1) + self._ws = 0.0 + self._release_from = 0.0 + self._release_s = 0.0 + self._releasing = False + self._side = 0 + self._overhead_s = 0.0 + self._last_out = ConeLineSample() + + def reset(self) -> None: + self.left.reset() + self.right.reset() + self._ws = 0.0 + self._releasing = False + self._release_s = 0.0 + self._side = 0 + + def update(self, points, v_ego: float, path_x, path_y, road_edges, dt: float, + yaw_rate: float = 0.0, *, lead_xs=(), lane_room=None, + room_right: float | None = None, room_left: float | None = None) -> ConeLineSample: + try: + try: + pts = list(points) if points is not None else [] + except TypeError: + pts = [] + sl = self.left.update(pts, v_ego, path_x, path_y, road_edges, dt, yaw_rate) + sr = self.right.update(pts, v_ego, path_x, path_y, road_edges, dt, yaw_rate) + out = self._fuse(sl, sr, pts, v_ego, path_x, path_y, dt, lead_xs, room_right, room_left) + except Exception: + self.reset() + out = ConeLineSample() + self._last_out = out + return out + + def _fuse(self, sl, sr, pts, v_ego, path_x, path_y, dt, lead_xs, room_right, room_left): + v = _speed(v_ego) + d = max(0.0, min(0.5, _num(dt) or 0.0)) + gl = self.left.group if sl.active else None + gr = self.right.group if sr.active else None + lc = _group_clear(gl, path_x, path_y) + rc = _group_clear(gr, path_x, path_y) + active = lc is not None or rc is not None + target = 0.0 + lo, hi = -math.inf, math.inf + if active: + xs = [p.x for g in (gl, gr) if g is not None for p in g.posts] + x_lo, x_hi = min(xs), max(xs) + over = overhead_ranges(pts, v, path_x, path_y) + # Both sides at one range is how an overpass looks; a corridor is long. + if gl is None or gr is None: + if any(x_lo - OVERHEAD_DEPTH_M <= x <= x_hi + OVERHEAD_DEPTH_M for x in over): + self._overhead_s = OVERHEAD_HOLD_S + else: + self._overhead_s = max(0.0, self._overhead_s - d) + else: + self._overhead_s = 0.0 + leads = [_num(lx) for lx in (lead_xs or ())] + lead_in_span = any(lx is not None and x_lo - 5.0 <= lx <= x_hi + 5.0 for lx in leads) + target = corridor_target(lc, rc, v_ego=v, lead_in_span=lead_in_span, overhead=self._overhead_s > 0.0, + room_right=room_right, room_left=room_left) + lo, hi = corridor_bounds(lc if lc and lc >= CORRIDOR_INSIDE_M else None, + rc if rc and rc >= CORRIDOR_INSIDE_M else None) + self._releasing = False + self._release_s = 0.0 + urgent = not (lo <= self._ws <= hi) + step = (CORRIDOR_RATE_URGENT_MPS if urgent else CORRIDOR_RATE_MPS) * d + self._ws += max(-step, min(step, target - self._ws)) + else: + if abs(self._ws) > 1e-4 and not self._releasing: + self._releasing = True + self._release_from = self._ws + self._release_s = 0.0 + if self._releasing: + self._release_s += d + t = min(1.0, self._release_s / CORRIDOR_RELEASE_S) + self._ws = self._release_from * (1.0 - t * t * (3.0 - 2.0 * t)) + if t >= 1.0: + self._releasing = False + self._ws = 0.0 + if abs(self._ws) < 1e-4: + self._ws = 0.0 + # Primary line for the legacy fields: the nearer one. + if lc is not None and (rc is None or lc <= rc): + base, side = sl, 1 + elif rc is not None: + base, side = sr, -1 + else: + base = sl if sl.confidence >= sr.confidence else sr + side = 0 + if side: + self._side = side + releasing = self._releasing and self._ws != 0.0 + return replace( + base, + active=active, + side=side if active else (self._side if releasing else base.side), + would_steer=self._ws, + barrier=sl.barrier or sr.barrier, + parked=sl.parked or sr.parked, + left_active=lc is not None, + left_clear=lc or 0.0, + right_active=rc is not None, + right_clear=rc or 0.0, + corridor=lc is not None and rc is not None, + margin=corridor_margin(self._ws, lc, rc), + releasing=releasing, + ) + + +def publish_cone_line(pm, sample: ConeLineSample | None) -> None: + """Publish one coneLineNAP. No-op when the socket or the sample is absent. + + wouldSteer is written for the log. It is not a curvature command. + """ + if sample is None or pm is None or "coneLineNAP" not in getattr(pm, "sock", {}): + return + import cereal.messaging as messaging + + msg = messaging.new_message("coneLineNAP") + msg.valid = True + dest = msg.coneLineNAP + dest.active = bool(sample.active) + dest.side = int(sample.side) + dest.confidence = float(sample.confidence) + dest.count = int(min(255, max(0, sample.count))) + dest.latNear = float(sample.lat_near) + dest.latMid = float(sample.lat_mid) + dest.latFar = float(sample.lat_far) + dest.wouldLimit = float(sample.would_limit) + dest.wouldSteer = float(sample.would_steer) + dest.barrier = bool(sample.barrier) + dest.parked = bool(sample.parked) + dest.spanM = float(sample.span_m) + dest.leftActive = bool(sample.left_active) + dest.leftClear = float(sample.left_clear) + dest.rightActive = bool(sample.right_active) + dest.rightClear = float(sample.right_clear) + dest.corridor = bool(sample.corridor) + dest.marginM = float(sample.margin) + dest.releasing = bool(sample.releasing) + pm.send("coneLineNAP", msg) diff --git a/selfdrive/controls/lib/cone_line_hold.py b/selfdrive/controls/lib/cone_line_hold.py new file mode 100644 index 00000000000000..c4da3e2d38bfcd --- /dev/null +++ b/selfdrive/controls/lib/cone_line_hold.py @@ -0,0 +1,281 @@ +"""Hold the driver's line near a cone line, and apply the cone shift. + +Oct 13 (pass E, 08:06): the old hold captured only 0.2–0.3 m of the ~1.0 m +Justin held and faded in ~6 s, so he steered by hand for ~55 s. Now: + * the hold captures his ACTUAL lane offset (modelV2 lane lines, car vs + lane centre) when each wheel push ends, and re-captures on every push; + * it holds that offset with no fade while the cone line is active, plus + CLEAR_S (3 s) after it clears, then releases over RELEASE_S; + * wheel torque only. The stalk / blinker is never an input; + * when he is not holding a line, the radar cone shift (coneLineNAP + wouldSteer, in-lane, cap 1.0 m, ramped in radard) is applied. + +Acts only after the driver has already pushed away from the cones. While +lateral is yielded this does not steer and does not change the yield. +On the re-take the curvature target is the driver's line (their offset +from the model path) instead of the model path that bends back toward +the cones. The hold stays until the cone line has been gone for a few +seconds, or the driver steers back toward it. It does not follow a +logged would-steer offset; the cone line never steers on its own. + +Never commands a path closer to the cone line than the line the driver +was holding. Longitudinal is not an input or an output. + +Frames: + cone.side +1 left of the path, -1 right + steeringTorque +left. Away from left cones is negative torque. + model path y, curvature +right (negative is a left bend). Toward + left cones is negative y / curvature. + +Thresholds: + push >= 0.55 Nm away from the cones for 0.85 s (a 0.40 s gap resets). + A 0.9 s push is enough. + model pull path is >= 0.12 m toward the cone line at the lookahead + lookahead vEgo * 1.6 s, clamped to 12–40 m, frozen when the line is captured + min offset 0.15 m; shifts larger than 1.5 m are clipped + cone clear line inactive for 3.0 s, then the offset decays over 2.5 s + re-capture any push >= 0.55 Nm; the offset is re-read when it ends + (a push back toward the cones re-captures a smaller offset) +""" +from __future__ import annotations + +import math +from dataclasses import dataclass + +from openpilot.selfdrive.controls.lib.radar_path_gate import path_y_at_x + +PARAM_CONE_LINE_HOLD = "NAPConeLineHold" +PARAM_CONE_LINE_LOG = "NAPConeLineLog" + +PUSH_ARM_S = 0.85 +PUSH_NM = 0.55 +PUSH_GAP_S = 0.40 +PULL_Y_M = 0.12 +PULL_K = 0.0005 +MIN_OFFSET_M = 0.15 +MAX_OFFSET_M = 1.5 +MAX_CURVATURE_DELTA = 0.02 +CLEAR_S = 3.0 +RELEASE_S = 2.5 +STEER_BACK_NM = 0.55 +STEER_BACK_S = 0.30 +X_LA_S = 1.6 +X_LA_MIN_M = 12.0 +X_LA_MAX_M = 40.0 +K_FILTER_S = 0.30 + + +def lookahead_m(v_ego: float) -> float: + try: + v = float(v_ego) + except (TypeError, ValueError): + v = 0.0 + if not math.isfinite(v): + v = 0.0 + return min(X_LA_MAX_M, max(X_LA_MIN_M, abs(v) * X_LA_S)) + + +def _smoothstep(t: float) -> float: + t = 0.0 if t < 0.0 else 1.0 if t > 1.0 else t + return t * t * (3.0 - 2.0 * t) + + +def _finite(value, default: float = 0.0) -> float: + try: + out = float(value) + except (TypeError, ValueError): + return default + return out if math.isfinite(out) else default + + +@dataclass(frozen=True) +class ConeHoldOutput: + active: bool + offset_m: float # applied path shift, +right; 0 when not steering it + curvature: float + source: str = "" # "hold", "shift" or "" + + +class ConeLineHold: + def __init__(self) -> None: + self._reset() + + def _reset(self) -> None: + self._push_s = 0.0 + self._push_gap_s = 0.0 + self._push_dir = 0 + self._armed = False + self._target = 0.0 # car offset vs lane centre, +right + self._target_rel = None # fallback: path-relative shift when lanes are unknown + self._side = 0 + self._gain = 0.0 + self._clear_s = 0.0 + self._release_s = 0.0 + self._releasing = False + self._x_la = X_LA_MIN_M + self.busy = False + + def reset(self) -> None: + self._reset() + + def update(self, *, enabled: bool, engaged: bool, cone, torque_nm: float, + measured_k: float, model_k: float, path_x, path_y, v_ego: float, + yielded: bool, lat_active: bool, dt: float, + lane_offset: float | None = None, lane_center_la: float | None = None, + cone_shift: float = 0.0) -> ConeHoldOutput: + model_k = _finite(model_k) + if not enabled or not engaged: + self._reset() + return ConeHoldOutput(False, 0.0, model_k) + + dt = min(max(_finite(dt), 0.0), 0.2) + torque = _finite(torque_nm) + measured = _finite(measured_k) + side = int(getattr(cone, "side", 0) or 0) if cone is not None else 0 + cone_active = bool(getattr(cone, "active", False)) and side in (-1, 1) + # Oct 14: after the corridor ends radard eases wouldSteer to 0 (releasing). + # Keep applying it so the car re-centres smoothly instead of snapping. + cone_releasing = bool(getattr(cone, "releasing", False)) and side in (-1, 1) and not cone_active + offset = None if lane_offset is None else _finite(lane_offset, float("nan")) + if offset is not None and not math.isfinite(offset): + offset = None + centre = None if lane_center_la is None else _finite(lane_center_la, float("nan")) + if centre is not None and not math.isfinite(centre): + centre = None + + x_now = lookahead_m(v_ego) + if not self._armed: + self._x_la = x_now + y_model = path_y_at_x(path_x, path_y, self._x_la) + + # Wheel push tracking. Torque is +left; side is +1 left. + pushing = abs(torque) >= PUSH_NM + direction = (1 if torque > 0 else -1) if pushing else 0 + if pushing: + self._push_gap_s = 0.0 + if self._push_dir not in (0, direction): + self._push_s = 0.0 + self._push_dir = direction + self._push_s += dt + else: + self._push_gap_s += dt + if self._push_gap_s > PUSH_GAP_S: + self._push_s = 0.0 + self._push_dir = 0 + + # (Re-)capture his actual offset while a qualifying push is on. The last + # value read before he lets go is the one held. + if pushing and self._armed and self._push_s + 1e-12 >= STEER_BACK_S: + self._capture(offset, measured, y_model, self._side) + elif pushing and not self._armed and cone_active and direction == -side \ + and self._push_s + 1e-12 >= PUSH_ARM_S: + # First capture: a push away from the cones (side +1 left: rightward, torque < 0). + self._capture(offset, measured, y_model, side) + + line_here = cone_active and side == self._side + if self._armed: + if line_here: + self._clear_s = 0.0 + self._releasing = False + self._release_s = 0.0 + self._gain = 1.0 + else: + self._clear_s += dt + if self._clear_s + 1e-12 >= CLEAR_S: + self._releasing = True + if self._releasing: + self._release_s += dt + self._gain = 1.0 - _smoothstep(self._release_s / RELEASE_S) + if self._gain <= 1e-3: + self._reset() + + self.busy = self._armed + can_steer = lat_active and not yielded and not pushing + if self._armed and can_steer and y_model is not None: + shift = self._hold_shift(y_model, centre) + return self._out(shift * self._gain, model_k, "hold") + if self._armed: + return ConeHoldOutput(False, 0.0, model_k) + + shift = _finite(cone_shift) + if (cone_active or cone_releasing) and can_steer and abs(shift) > 1e-3: + # Never toward the nearer line: side +1 (left) only shifts right (+). + # radard already keeps CORRIDOR_MARGIN_M to both tracked lines. + if shift * side > 0.0: + self._x_la = x_now + return self._out(max(-MAX_OFFSET_M, min(MAX_OFFSET_M, shift)), model_k, "shift") + return ConeHoldOutput(False, 0.0, model_k) + + def _capture(self, offset, measured: float, y_model, side: int) -> None: + """Read the driver's actual offset as the new target (each push).""" + if side not in (-1, 1): + return + if offset is not None: + target = max(-MAX_OFFSET_M, min(MAX_OFFSET_M, offset)) + target_rel = None + else: + if y_model is None: + return + y_driver = 0.5 * measured * self._x_la * self._x_la + target_rel = max(-MAX_OFFSET_M, min(MAX_OFFSET_M, y_driver - y_model)) + target = 0.0 + away = (target if target_rel is None else target_rel) * side + if not self._armed and away < MIN_OFFSET_M: + return + if self._armed and away < MIN_OFFSET_M: + # He steered back to (or past) the middle: let go. + self._reset() + return + self._armed = True + self._side = side + self._target = target + self._target_rel = target_rel + self._gain = 1.0 + self._clear_s = 0.0 + self._releasing = False + self._release_s = 0.0 + + def _hold_shift(self, y_model: float, centre) -> float: + if self._target_rel is not None: + shift = self._target_rel + elif centre is not None: + shift = (centre + self._target) - y_model + else: + shift = self._target + # Never command a path closer to the cones than the model path. + if shift * self._side < 0.0: + shift = 0.0 + return max(-MAX_OFFSET_M, min(MAX_OFFSET_M, shift)) + + def _out(self, shift: float, model_k: float, source: str) -> ConeHoldOutput: + x = max(self._x_la, 1.0) + delta_k = 2.0 * shift / (x * x) + delta_k = max(-MAX_CURVATURE_DELTA, min(MAX_CURVATURE_DELTA, delta_k)) + return ConeHoldOutput(True, shift, model_k + delta_k, source) + + +def lane_offset_from_model(model, x_la: float) -> tuple[float | None, float | None]: + """(car offset vs lane centre at the car, lane centre y at x_la), both +right. + + Uses the two ego lane lines (laneLines[1], [2]). None when either is weak. + """ + try: + lines = list(model.laneLines) + probs = list(model.laneLineProbs) + except (TypeError, AttributeError): + return None, None + if len(lines) < 3 or len(probs) < 3 or float(probs[1]) < 0.4 or float(probs[2]) < 0.4: + return None, None + try: + lx, ly = [float(v) for v in lines[1].x], [float(v) for v in lines[1].y] + rx, ry = [float(v) for v in lines[2].x], [float(v) for v in lines[2].y] + except (TypeError, ValueError, AttributeError): + return None, None + l0, r0 = path_y_at_x(lx, ly, 0.0), path_y_at_x(rx, ry, 0.0) + la, ra = path_y_at_x(lx, ly, x_la), path_y_at_x(rx, ry, x_la) + if None in (l0, r0, la, ra): + return None, None + if not (2.0 <= r0 - l0 <= 6.0): + return None, None + centre0 = 0.5 * (l0 + r0) + return -centre0, 0.5 * (la + ra) diff --git a/selfdrive/controls/lib/crossing_vehicle.py b/selfdrive/controls/lib/crossing_vehicle.py new file mode 100644 index 00000000000000..0bcbaaef00494c --- /dev/null +++ b/selfdrive/controls/lib/crossing_vehicle.py @@ -0,0 +1,276 @@ +"""Crossing and turning vehicles in the longitudinal stack. + +Radar sees a side-on car as a glint on the body panel that is square to +the bumper. While that panel covers our lane the point sits near the +centreline, so the lead looks stopped. The motion shows up at the +corners: an entry sweep when the nose reaches us, and an exit sweep +when the tail starts to leave. + +A return moving sideways in the ground frame, faster than about 2 mph +after ego yaw is removed, is a crosser. The follow law then sees a +smaller closing speed, so it eases off instead of stopping for a parked +car. The weight on that input is filtered. When the tail's exit sweep +begins, the same weight hands the command back to the speed-ceiling +term and the car starts accelerating again. That handover runs only +while longitudinal is still on. A gas touch clears it until the stalk, +and lifting off the pedal does not bring it back. + +A stopped car, a return the model still calls a lead, and anything +close enough that we could not stop stays on the normal law. +""" +from __future__ import annotations + +import math +from collections import deque + +# About 2 mph. E1's entry sweep was 1.5–1.6 m/s. A stopped car's +# ground-frame wander over a couple of seconds stays under this. +CROSS_VY_MS = 0.89 +# Net ground-frame shift in the first moments, same direction as the sweep. +CROSS_DY_M = 0.8 +CROSS_AGE_S = 0.8 +CROSS_ENTRY_S = 1.5 +# Not traffic. A lead still moving along the road is not crossing. +CROSS_ALONG_MS = 3.0 +CROSS_ALONG_DROP_MS = 3.5 +# The radar fit already covers this much motion before it publishes a speed. +CROSS_FIT_MIN_S = 0.6 +CROSS_FIT_WINDOW_S = 1.0 + +# Tail starts to leave. The entry sweep is ignored: the point has to +# come back toward the lane (the glint) and then move out again, with +# a real lateral speed, and stay there briefly so a wobble does not. +CROSS_EXIT_DY_M = 0.35 +CROSS_EXIT_VY_MS = 0.40 +CROSS_EXIT_HOLD_S = 0.12 +CROSS_COMEBACK_M = 0.30 +CROSS_Y_TAU_S = 0.08 + +# Model still says this is a lead in our lane: it is stopped, not crossing. +CROSS_VISION_RANGE_M = 55.0 +CROSS_VISION_PROB = 0.7 + +# Still overlapping the lane and too close to keep easing off. +CROSS_IMMINENT_GAP_M = 10.0 +CROSS_LANE_HALF_M = 1.6 + +# Share of the real closing speed the follow law keeps seeing while the +# crosser is in the lane. The rest is filtered out so the stop term does +# not run. The fraction itself is not a second command. +CROSS_CLOSE_FRAC = 0.28 +CROSS_GENTLE_TAU_S = 0.25 +CROSS_RESUME_TAU_S = 0.12 + +# Stationary-target room cap (X2). Fast closes shorten the match distance +# to about 0.38 of the gap; a stopped car at long range was then asked for +# about twice the decel a stop needs. D stays at least three quarters of +# the gap beyond the standstill keep. +X2_V_LEAD_MS = 2.0 +X2_ROOM_FRAC = 0.75 + + +def crossing_may_resume(long_on: bool) -> bool: + """Re-accelerate only while longitudinal is still engaged. + + Any gas touch drops longitudinal until the driver pulls the stalk. + Letting the pedal up does not turn it back on, including when the + crosser is already leaving. + """ + return bool(long_on) + + +def _filt(prev: float | None, sample: float, dt: float, tau: float) -> float: + if prev is None or tau <= 1e-4: + return float(sample) + a = float(dt) / (float(tau) + float(dt)) + return float(prev) + a * (float(sample) - float(prev)) + + +def _slope(samples: deque, now: float) -> float: + """Least-squares lateral speed over the recent window. 0 until it spans the fit.""" + pts = [p for p in samples if now - p[0] <= CROSS_FIT_WINDOW_S + 1e-9] + if len(pts) < 3: + return 0.0 + span = pts[-1][0] - pts[0][0] + if span < CROSS_FIT_MIN_S: + return 0.0 + n = float(len(pts)) + t_mean = sum(p[0] for p in pts) / n + y_mean = sum(p[1] for p in pts) / n + var_t = sum((p[0] - t_mean) ** 2 for p in pts) + if var_t < 1e-8: + return 0.0 + return sum((p[0] - t_mean) * (p[1] - y_mean) for p in pts) / var_t + + +class GroundLateral: + """Ground-frame lateral speed of radar returns, ego yaw removed. + + y_rel and the published speed are +left, metres and m/s. yaw_rate_left + is +left, rad/s. The radar's own lateral velocity is not used: at range + it is mostly our yaw, and on a side-on car it tracks the glint. + """ + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self._t: float | None = None + self._heading = 0.0 + self._x = 0.0 + self._y = 0.0 + self._tracks: dict[int, deque] = {} + + def update(self, t: float, v_ego: float, yaw_rate_left: float, + points: list[tuple[int, float, float]]) -> dict[int, float]: + """points are (track_id, d_rel, y_rel). Returns track_id -> v_lat.""" + now = float(t) + if self._t is not None: + dt = now - self._t + if dt < 0.0 or dt > 0.5: + self.reset() + elif dt > 0.0: + self._heading += float(yaw_rate_left) * dt + c = math.cos(self._heading) + s = math.sin(self._heading) + self._x += float(v_ego) * c * dt + self._y += float(v_ego) * s * dt + self._t = now + c = math.cos(self._heading) + s = math.sin(self._heading) + live: dict[int, float] = {} + seen: set[int] = set() + for track_id, d_rel, y_rel in points: + tid = int(track_id) + seen.add(tid) + world_y = self._y + float(d_rel) * s + float(y_rel) * c + hist = self._tracks.get(tid) + if hist is None: + hist = deque(maxlen=48) + self._tracks[tid] = hist + hist.append((now, world_y)) + live[tid] = _slope(hist, now) + for tid in list(self._tracks): + if tid not in seen: + self._tracks.pop(tid, None) + return live + + +class CrossingFollow: + """Smoothed inputs that tell the follow law a crosser will clear. + + close_scale is the fraction of the real closing speed the law should + see. 1 is the normal law. It falls once the entry sweep qualifies and + rises again for a stopped car, a vision lead, or an imminent overlap. + resume_w rises when the exit sweep begins and longitudinal is still + on, and the controller then blends toward the speed-ceiling command. + """ + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self.lead_id = None + self.age = 0.0 + self.dy = 0.0 + self.credited = False + self.speed_ok = False + self.entry_closed = False + self.classified = False + self.direction = 0.0 + self.exit = False + self.exit_s = 0.0 + self.imminent = False + self.y_f: float | None = None + self.peak_y: float | None = None + self.came_back = False + self.lock_y: float | None = None + self.gentle_w = 0.0 + self.resume_w = 0.0 + self._along_s = 0.0 + + def update(self, *, dt: float, lead_id, gap: float, y_rel: float, v_lead: float, + v_lat: float, model_prob: float | None, long_on: bool) -> None: + frame = 0.05 if dt is None or float(dt) <= 1e-6 else float(dt) + if lead_id != self.lead_id: + self.reset() + self.lead_id = lead_id + self.age += frame + vlat = float(v_lat) + along = abs(float(v_lead)) + if not self.credited and abs(vlat) >= CROSS_VY_MS: + # The published speed is already a fit over the window, so the + # motion that produced it counts. Later frames add themselves. + self.dy += vlat * CROSS_FIT_MIN_S + self.credited = True + self.dy += vlat * frame + if (not self.classified) and abs(vlat) >= CROSS_VY_MS and vlat * self.dy >= 0.0: + self.speed_ok = True + + prob = 0.0 if model_prob is None or not math.isfinite(float(model_prob)) else float(model_prob) + vision_stopped = float(gap) <= CROSS_VISION_RANGE_M and prob >= CROSS_VISION_PROB + if along >= CROSS_ALONG_DROP_MS: + self._along_s += frame + else: + self._along_s = 0.0 + + if not self.classified and not self.entry_closed: + if self.age > CROSS_ENTRY_S: + self.entry_closed = True + elif (self.age + 1e-9 >= CROSS_AGE_S and abs(self.dy) >= CROSS_DY_M + and self.speed_ok and along < CROSS_ALONG_MS and not vision_stopped): + self.classified = True + self.direction = 1.0 if self.dy >= 0.0 else -1.0 + + if self.classified and (vision_stopped or self._along_s >= 0.30): + # It is traffic, or the model sees a lead where the glint sits. + # Back to the normal law. The exit handover does not fire. + self.classified = False + self.exit = False + self.exit_s = 0.0 + + prev_y = self.y_f + self.y_f = _filt(self.y_f, float(y_rel), frame, CROSS_Y_TAU_S) + vy = 0.0 if prev_y is None else (float(self.y_f) - float(prev_y)) / frame + if self.classified and not self.exit and self.direction != 0.0: + y = float(self.y_f) + # The nose sweep is not the tail. Remember how far out the point + # got, and only look for the exit after it has come back in. + if self.peak_y is None or y * self.direction > self.peak_y * self.direction: + self.peak_y = y + elif self.peak_y is not None and (self.peak_y - y) * self.direction >= CROSS_COMEBACK_M: + self.came_back = True + if self.came_back: + if self.lock_y is None or y * self.direction < self.lock_y * self.direction: + self.lock_y = y + self.exit_s = 0.0 + moved = 0.0 if self.lock_y is None else (y - self.lock_y) * self.direction + if moved >= CROSS_EXIT_DY_M and vy * self.direction >= CROSS_EXIT_VY_MS: + self.exit_s += frame + else: + self.exit_s = 0.0 + if self.exit_s + 1e-9 >= CROSS_EXIT_HOLD_S: + self.exit = True + + y_abs = abs(float(y_rel)) + self.imminent = bool( + self.classified and not self.exit + and float(gap) <= CROSS_IMMINENT_GAP_M + and y_abs <= CROSS_LANE_HALF_M + ) + + gentle_target = 1.0 if self.classified and not self.imminent else 0.0 + resume_target = 1.0 if self.exit and self.classified and crossing_may_resume(long_on) else 0.0 + self.gentle_w = _filt(self.gentle_w, gentle_target, frame, CROSS_GENTLE_TAU_S) + self.resume_w = _filt(self.resume_w, resume_target, frame, CROSS_RESUME_TAU_S) + + @property + def close_scale(self) -> float: + """1 = full closing speed. Lower while a crosser is still in the lane.""" + ease = self.gentle_w * (1.0 - CROSS_CLOSE_FRAC) + scale = (1.0 - ease) * (1.0 - self.resume_w) + if scale < 0.0: + return 0.0 + if scale > 1.0: + return 1.0 + return float(scale) diff --git a/selfdrive/controls/lib/curve_follow.py b/selfdrive/controls/lib/curve_follow.py new file mode 100644 index 00000000000000..56a1c651ae9bf0 --- /dev/null +++ b/selfdrive/controls/lib/curve_follow.py @@ -0,0 +1,397 @@ +"""Curve-follow: a continuous longitudinal term from the model path ahead (Pre-AP). + +A human does not pick a corner speed and hold it. He eases off a little as a +bend comes into view, keeps adjusting while it holds or tightens, and comes +back on the gas as the road opens. This module is that, in the same style as +the lead-follow law: every cycle the road ahead is a speed envelope +v_env(s) (the unchanged, conservative lateral-accel table), and the most +limiting point is a virtual lead that is stationary in speed. The kinematic +required accel to meet it is + + a_i = (v_env_i² - v²) / (2 · room_i) + +negative when the car is above the envelope, a small positive allowance when +it is under (so it neither speeds into a bend nor brakes for one it already +meets). The result is a CEILING on acceleration, like the map and speed-cap +terms: it can only lower the command and it is exactly PREVIEW_FREE_A_MS2 +when nothing ahead binds. It never writes MAX, keeps no set speed and no +latch. Its only state is sub-second filters, a confidence weight and a slew. + +Reliability (how much to believe the forecast, per point and overall): +- a bend must stand out of the path's own position std (signal to noise of + its lateral displacement), so noisy far points count little and a clear + bend counts fully, at any distance, without a fixed horizon; +- curvature is filtered per path index: fast to tighten (faster when the + bend is strong), slower to open, and a single-point spike is clipped; +- a lane change, dropped frames, an invalid model or an active roundabout + funnel fade the term out (it never steps); below 8 m/s only a turn with + the blinker on is anticipated, and only out to ~3 s. + +Release is proportional: as the path opens the envelope rises and so does +the ceiling; once the path shows the bend has peaked, the near field +(mild lift only, never a brake into the exit) fades to nothing. + +Shadow: with NAPCurveFollow = 1 the planner computes and logs this every +cycle and applies nothing. 0 = off, 2 = active (replaces the old preview and +retires the CurveMaxHold MAX cap). +""" +from __future__ import annotations + +import json +import math + +from openpilot.selfdrive.controls.lib.curve_max_hold import curve_speed_for_curvature +from openpilot.selfdrive.controls.lib.curve_preview import ( + PREVIEW_DECEL_BP_MS, + PREVIEW_FREE_A_MS2, + PREVIEW_JERK_MS3, + PREVIEW_MIN_ROOM_M, + PREVIEW_MIN_ROOM_S, + PREVIEW_MIN_V_MS, + preview_decel_limit_ms2, +) +from openpilot.selfdrive.controls.lib.unified_lead import _smooth01, _softplus, speed_ceiling_accel + +PARAM_KEY = "NAPCurveFollow" +MODE_OFF = 0 +MODE_SHADOW = 1 +MODE_ACTIVE = 2 +DEFAULT_MODE = MODE_SHADOW + +FREE_A_MS2 = PREVIEW_FREE_A_MS2 +MIN_V_MS = PREVIEW_MIN_V_MS + +# Where the car finishes slowing for a bend, as seconds before its tightest +# point. 1.0 s: slowing is done and the throttle may return about 1 s before +# the tightest point. Justin's own median is about 2.4 s; raise this single +# constant to move there. The speed AT the tightest point is the table speed +# either way (cornering stays conservative). +# Oct 13: 1.5 s, the actuator lag, so the car itself is done slowing by the apex. +RELEASE_BEFORE_TIGHTEST_S = 1.5 +ROOM_SOFT_M = 2.0 + +# Curvature filter per path index (|k|): tighten fast (faster when strong), +# open slowly so a noisy "it opens" cannot release early. +K_UP_TAU_S = 0.20 +K_UP_STRONG_TAU_S = 0.12 +K_STRONG = 0.02 +K_DOWN_TAU_S = 0.50 +SPIKE_MIN_K = 0.01 +SPIKE_RATIO = 2.0 + +# Signal to noise of a bend's lateral displacement against the path's std. +SNR_S0 = 2.0 +SNR_S1 = 6.0 +STD_FLOOR_M = 0.2 +STD_FALLBACK_BASE_M = 0.3 # no yStd in the message +STD_FALLBACK_PER_S_M = 0.15 + +# Low speed: only a blinkered turn, only ~3 s ahead. +LOW_V0_MS = 6.5 +LOW_V1_MS = 8.0 +LOW_HORIZON_S = 2.5 +LOW_HORIZON_BAND_S = 0.5 + +# Overall confidence (lead-law style ramp). +CONF_RATE_BASE_1_S = 2.0 +CONF_RATE_URGENT_1_S = 14.0 +CONF_FALL_1_S = 1.5 +CONF_FALL_GATE_1_S = 2.0 +CONF_URGENT_LO_MS2 = 0.5 +CONF_URGENT_BAND_MS2 = 1.5 +FRAME_DROP_MAX_PCT = 20.0 + +# Near field / apex: lift only, and gone once the path says the bend peaked. +NEAR_BRAKE_MAX_MS2 = 0.35 +NEAR_T0_S = 1.0 +NEAR_T_BAND_S = 1.0 +PEAK_LOOKAHEAD_S = 1.0 +PEAK_RATIO0 = 0.9 +PEAK_BAND = 0.3 +PEAK_MIN_K = 0.004 + +# Relief: with room to spare the term allows speed up to the profile that can +# still meet the envelope speed at a mild decel, and does not brake until the +# car is above it. That is how a car accelerates out of one bend and eases +# back for the next. Relief fades to nothing as the point gets close. +RELIEF_DECEL_MS2 = 0.30 +RELIEF_MAX_MS2 = 0.60 +RELIEF_ROOM0_M = 20.0 +RELIEF_ROOM_BAND_M = 40.0 + +# Output slew. +OUT_TAU_S = 0.20 +BUILD_PROP_1_S = 2.0 +BUILD_MAX_MS3 = 2.0 +RELEASE_BP_MS = [10.0, 20.0] +RELEASE_BASE_MS3 = [1.0, 0.45] +RELEASE_OPEN_MS3 = 1.35 +RELEASE_PROP_1_S = 2.0 +RELEASE_MAX_MS3 = 2.5 +SNAP_EPS_MS2 = 0.01 + + +def read_curve_follow_mode(params) -> int: + """NAPCurveFollow 0 off / 1 shadow / 2 active. Unknown or unreadable = shadow.""" + try: + mode = int(params.get(PARAM_KEY, return_default=True)) + except Exception: + return DEFAULT_MODE + return mode if mode in (MODE_OFF, MODE_SHADOW, MODE_ACTIVE) else DEFAULT_MODE + + +def _interp(x: float, xp, fp) -> float: + if x <= xp[0]: + return float(fp[0]) + for i in range(1, len(xp)): + if x <= xp[i]: + f = (x - xp[i - 1]) / (xp[i] - xp[i - 1]) + return float(fp[i - 1] + f * (fp[i] - fp[i - 1])) + return float(fp[-1]) + + +def interp_at(ts, vals, t: float) -> float | None: + """Linear interpolation of vals(ts) at t, None outside the path.""" + try: + n = min(len(ts), len(vals)) + except TypeError: + return None + if n < 1 or t < float(ts[0]) or t > float(ts[n - 1]): + return None + for i in range(1, n): + if float(ts[i]) >= t: + a, b = float(ts[i - 1]), float(ts[i]) + f = 0.0 if b <= a else (t - a) / (b - a) + return float(vals[i - 1]) + f * (float(vals[i]) - float(vals[i - 1])) + return float(vals[0]) + + +def curve_follow_raw(v_ego: float, ts, ds, ks, weights, passed: float = 0.0): + """Unslewed ceiling from the (filtered) path ahead. + + Returns (a, limiting_index, limiting_envelope_speed, near_field_a). `a` is + FREE_A_MS2 exactly when no point binds. `weights` in [0, 1] scale each + point's demand toward "no demand"; `passed` in [0, 1] says the bend has + peaked and removes the near-field demand. + """ + v = float(v_ego) + if v < MIN_V_MS or ts is None: + return FREE_A_MS2, -1, None, None + min_room = max(PREVIEW_MIN_ROOM_M, PREVIEW_MIN_ROOM_S * v) + best = FREE_A_MS2 + best_i = -1 + best_v = None + for i, (t, d, k, w) in enumerate(zip(ts, ds, ks, weights, strict=True)): + if w <= 0.0 or t < 0.0: + continue + v_env = curve_speed_for_curvature(k) + if v_env is None: + continue + room = min_room + _softplus(float(d) - RELEASE_BEFORE_TIGHTEST_S * v - min_room, ROOM_SOFT_M) + a_kin = (v_env * v_env - v * v) / (2.0 * room) + v_prof = math.sqrt(v_env * v_env + 2.0 * RELIEF_DECEL_MS2 * room) + r0 = RELIEF_MAX_MS2 * _smooth01((room - RELIEF_ROOM0_M) / RELIEF_ROOM_BAND_M) + relief = r0 * (1.0 - _smooth01((v - v_env) / max(v_prof - v_env, 0.5))) + a_i = min(FREE_A_MS2, a_kin + relief) + near = 1.0 - _smooth01((float(t) - NEAR_T0_S) / NEAR_T_BAND_S) + scale = float(w) * (1.0 - float(passed) * near) + a_eff = FREE_A_MS2 + scale * (a_i - FREE_A_MS2) + if a_eff < best: + best, best_i, best_v = a_eff, i, v_env + a_near = None + v0 = curve_speed_for_curvature(ks[0]) if len(ks) else None + if v0 is not None and weights[0] > 0.0: + over = speed_ceiling_accel(v, v0) + if over < 0.0: + a_near = FREE_A_MS2 + float(weights[0]) * (1.0 - float(passed)) * (max(over, -NEAR_BRAKE_MAX_MS2) - FREE_A_MS2) + if a_near < best: + best, best_i, best_v = a_near, 0, v0 + return best, best_i, best_v, a_near + + +class CurveFollow: + """Filters, confidence and slew around `curve_follow_raw`.""" + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self._kf: list[float] | None = None + self._conf = 1.0 + self._f = FREE_A_MS2 + self._brake = 0.0 + self.a = FREE_A_MS2 + self.raw = FREE_A_MS2 + self.conf = 1.0 + self.limit_idx = -1 + self.limit_t = None + self.limit_d = None + self.limit_v = None + self.near_a = None + self.passed = 0.0 + self.gate = 1.0 + self.trusted = False + + # ---- path preparation ------------------------------------------------- + def _filter_k(self, ks, dt: float) -> list[float]: + kc = [abs(float(k)) for k in ks] + n = len(kc) + # A single point far above both neighbours is a spike, not a bend. + clipped = list(kc) + for i in range(n): + nb = [kc[j] for j in (i - 1, i + 1) if 0 <= j < n] + if nb and kc[i] > SPIKE_MIN_K and kc[i] > SPIKE_RATIO * max(nb): + clipped[i] = SPIKE_RATIO * max(nb) + if self._kf is None or len(self._kf) != n: + self._kf = list(clipped) + return list(self._kf) + for i in range(n): + cur = self._kf[i] + x = clipped[i] + tau = (K_UP_STRONG_TAU_S if x > K_STRONG else K_UP_TAU_S) if x > cur else K_DOWN_TAU_S + self._kf[i] = cur + dt / (tau + dt) * (x - cur) + return list(self._kf) + + @staticmethod + def _snr_weights(ts, ds, ks, y_std) -> list[float]: + """Lateral displacement of the (signed) path from straight-ahead, in sigmas of its own std. + + Signed on purpose: noise around zero walks, a real bend (or the first arc + of an S) accumulates. + """ + n = len(ks) + w = [1.0] * n + theta = 0.0 + y = 0.0 + have_std = y_std is not None and len(y_std) == n + for i in range(1, n): + dd = max(0.0, float(ds[i]) - float(ds[i - 1])) + k_mid = 0.5 * (float(ks[i]) + float(ks[i - 1])) + y += (theta + 0.5 * k_mid * dd) * dd + theta += k_mid * dd + if have_std: + std = max(STD_FLOOR_M, float(y_std[i])) + else: + std = STD_FALLBACK_BASE_M + STD_FALLBACK_PER_S_M * max(0.0, float(ts[i])) + w[i] = _smooth01((abs(y) / std - SNR_S0) / (SNR_S1 - SNR_S0)) + return w + + # ---- one cycle -------------------------------------------------------- + def step(self, *, dt: float, v_ego: float, ts, ds, ks, y_std=None, lane_change: bool = False, + blinker: bool = False, frame_drop_pct: float = 0.0, rb_active: bool = False, + valid: bool = True) -> float: + dt = max(1e-3, float(dt)) + v = float(v_ego) + path_ok = bool(valid) and ts is not None and len(ts) >= 2 and len(ts) == len(ds) == len(ks) + ctx_ok = not (lane_change or rb_active or float(frame_drop_pct) > FRAME_DROP_MAX_PCT) + + a_raw = FREE_A_MS2 + self.limit_idx, self.limit_t, self.limit_d, self.limit_v, self.near_a = -1, None, None, None, None + self.passed = 0.0 + slow = 1.0 - _smooth01((v - LOW_V0_MS) / (LOW_V1_MS - LOW_V0_MS)) + gate = 1.0 - (slow if not blinker else 0.0) + self.gate = gate + if path_ok: + kf = self._filter_k(ks, dt) + snr = self._snr_weights(ts, ds, ks, y_std) + weights = [] + for t, s in zip(ts, snr, strict=True): + far_cut = slow * _smooth01((float(t) - LOW_HORIZON_S) / LOW_HORIZON_BAND_S) + weights.append(s * (1.0 - far_cut) * gate) + k_now = kf[0] + k_ahead = interp_at(ts, kf, PEAK_LOOKAHEAD_S) + if k_ahead is not None and k_now >= PEAK_MIN_K: + self.passed = _smooth01((PEAK_RATIO0 - k_ahead / k_now) / PEAK_BAND) + a_raw, idx, v_lim, self.near_a = curve_follow_raw(v, ts, ds, kf, weights, self.passed) + if idx >= 0: + self.limit_idx, self.limit_v = idx, v_lim + self.limit_t, self.limit_d = float(ts[idx]), float(ds[idx]) + else: + self._kf = None + + # Confidence: rises like a lead's, fades out on a lane change, dropped + # frames, an invalid model or the roundabout funnel. Never a step. + target = 1.0 if (path_ok and ctx_ok) else 0.0 + if target >= self._conf: + urgency = _smooth01((-a_raw - CONF_URGENT_LO_MS2) / CONF_URGENT_BAND_MS2) + rate = CONF_RATE_BASE_1_S + CONF_RATE_URGENT_1_S * urgency * self._conf + else: + rate = CONF_FALL_GATE_1_S if (path_ok and not ctx_ok) else CONF_FALL_1_S + self._conf = min(1.0, max(0.0, self._conf + min(1.0, rate * dt) * (target - self._conf))) + self.conf = self._conf + self.trusted = bool(path_ok and ctx_ok and self._conf >= 0.2 and v >= MIN_V_MS) + + a_c = FREE_A_MS2 + self._conf * (a_raw - FREE_A_MS2) + a_c = min(FREE_A_MS2, max(a_c, -preview_decel_limit_ms2(v))) + self.raw = a_c + return self._slew(v, a_c, dt) + + def _slew(self, v: float, target: float, dt: float) -> float: + target = min(FREE_A_MS2, float(target)) + self._f += (dt / (OUT_TAU_S + dt)) * (target - self._f) + if self._f > FREE_A_MS2 - SNAP_EPS_MS2: + self._f = FREE_A_MS2 + tb = min(0.0, self._f) + err = tb - self._brake + rel_base = _interp(v, RELEASE_BP_MS, RELEASE_BASE_MS3) + rel_base += max(0.0, RELEASE_OPEN_MS3 - rel_base) * self.passed + release = min(RELEASE_MAX_MS3, rel_base + RELEASE_PROP_1_S * max(0.0, err)) * dt + if err < 0.0: + base = _interp(v, PREVIEW_DECEL_BP_MS, PREVIEW_JERK_MS3) + build = min(BUILD_MAX_MS3, base + BUILD_PROP_1_S * (-err)) * dt + delta = max(err, -build) + else: + delta = min(err, release) + self._brake = min(0.0, self._brake + delta) + out = self._brake + max(0.0, self._f) + # While the ceiling is still braking it rises no faster than the release. + if self.a < 0.0: + out = min(out, self.a + release) + if out > FREE_A_MS2 - SNAP_EPS_MS2: + out = FREE_A_MS2 + self.a = out + return self.a + + +# ---- logging (plain JSON text, no capnp) ---------------------------------- +LOG_PERIOD_CYCLES = 10 # 2 Hz at the 20 Hz planner rate +LOG_QUIET_PERIOD_CYCLES = 50 # arrays on a straight road, every 2.5 s +LOG_SUMMARY_T = (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0) +LOG_STD_T = (3.0, 5.0, 8.0) +LOG_PREFIX = "curvefollow " + + +def _r(x, nd: int): + return None if x is None else round(float(x), nd) + + +def path_is_relevant(ks, cf_a: float, old_a: float, conf: float) -> bool: + kmax = max((abs(float(k)) for k in ks), default=0.0) + return kmax > 0.003 or cf_a < FREE_A_MS2 - 0.05 or old_a < FREE_A_MS2 - 0.05 or conf < 0.99 + + +def format_log_line(*, mode: int, t: float, v: float, a_ego: float, v_cruise_kph: float, a_target: float, + cf: CurveFollow, old_a: float, ts, ds, ks, y_std, meta: dict, arrays: bool) -> str: + """One compact JSON line. Summary always; the full 33-point arrays on request.""" + rec: dict = { + "m": int(mode), "t": round(float(t), 2), "v": round(float(v), 2), "ae": round(float(a_ego), 3), + "mx": round(float(v_cruise_kph), 1), "at": round(float(a_target), 3), + "cf": round(float(cf.a), 3), "cfr": round(float(cf.raw), 3), "w": round(float(cf.conf), 3), + "g": round(float(cf.gate), 2), "pk": round(float(cf.passed), 2), "tr": int(cf.trusted), + "li": int(cf.limit_idx), "lt": _r(cf.limit_t, 2), "ld": _r(cf.limit_d, 1), "lv": _r(cf.limit_v, 2), + "nf": _r(cf.near_a, 3), "old": round(float(old_a), 3), + } + rec.update(meta) + try: + rec["k"] = [None if (x := interp_at(ts, ks, s)) is None else round(x * 1e4) for s in LOG_SUMMARY_T] + if y_std is not None and len(y_std) == len(ts): + rec["ys"] = [None if (x := interp_at(ts, y_std, s)) is None else round(x, 2) for s in LOG_STD_T] + if arrays: + rec["T"] = [round(float(x), 2) for x in ts] + rec["D"] = [round(float(x), 1) for x in ds] + rec["K"] = [round(float(x) * 1e4) for x in ks] + if y_std is not None and len(y_std) == len(ts): + rec["Y"] = [round(float(x), 2) for x in y_std] + except (TypeError, ValueError): + rec["path"] = "unavailable" + return LOG_PREFIX + json.dumps(rec, separators=(",", ":")) diff --git a/selfdrive/controls/lib/curve_max_hold.py b/selfdrive/controls/lib/curve_max_hold.py new file mode 100644 index 00000000000000..b46860cb4e310e --- /dev/null +++ b/selfdrive/controls/lib/curve_max_hold.py @@ -0,0 +1,562 @@ +"""Snapshot HUD MAX / sticky hold at curve entry; restore after the bend. + +Through a sharp curve, temporary slowing (planner `limit_accel_in_turns` +and/or a comfort lat-accel cruise cap) may lower published MAX so the car +takes an appropriate corner speed. That lower value must not permanently +rebase sticky MAX or the Cap/Follow map target. + +Hypermile eco is the live posted-scaled Cap/Follow target. If MAX was +60 before the bend (sticky hold or that displayed set), restore 60 — not +the live eco / posted target the curve path would otherwise land on. + +GPS / OSM flicker on a bend used to look like posted `a` → `b`, wipe +sticky, then restore to posted+offset. Freeze that rebase while the +curve is active; after lat accel / steer are straight-ish, put MAX back. +A posted change that is still there after exit is a real new zone and +is allowed to rebase. +""" +from __future__ import annotations + +import math +from dataclasses import dataclass + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.map_speed_policy import V_CRUISE_UNSET, posted_limits_same + +# Same a_y formula as longitudinal_planner.limit_accel_in_turns. +CURVE_ENTER_LAT_MS2 = 1.30 +CURVE_EXIT_LAT_MS2 = 0.65 +CURVE_ENTER_STEER_DEG = 14.0 +CURVE_EXIT_STEER_DEG = 8.0 +CURVE_EXIT_HOLD_S = 0.45 +# Comfortable corner lat accel for the temporary HUD/planner cap. Kept as +# the 22 m/s reference; the cap itself uses the speed-dependent target below. +CURVE_COMFORT_LAT_MS2 = 2.00 +# Cornering lateral-accel target vs speed (true curvature, not steer angle). +# Justin carries ~2.2 in town corners and ~1.5 at highway speed (Sep 20–27). +CURVE_LAT_TARGET_BP_MS = [8.0, 15.0, 22.0, 30.0] +CURVE_LAT_TARGET_MS2 = [2.40, 2.25, 2.00, 1.75] +# Ignore parking-lot / standstill wheel spin. +CURVE_MIN_V_EGO_MS = 5.0 +# Do not invent a crawl MAX in a hairpin. +CURVE_SPEED_FLOOR_MS = 6.0 +# Light smoothing so the cap is not a raw frame of curvature / yaw. +CURVE_LAT_TAU_S = 0.40 +# Mid-curve the cap may drop when the bend actually tightens, but it +# must not rise. Steering jitter used to pump MAX both ways. The first +# fraction of a second still tracks the smoothed estimate so one noisy +# frame is not frozen in. +CURVE_CAP_TIGHTEN_KPH = 2.0 +CURVE_CAP_SETTLE_S = 0.45 +# Exit raises MAX toward the snapshot at about an Accel-3 rate unless +# card passes the live map Accel envelope. +CURVE_RESTORE_A_DEFAULT_MS2 = 0.40 +# Exit restore rate vs speed at the default Accel (0.80 m/s² envelope): +# ~0.65 in town, ~0.35 at highway speed. Card's Accel envelope scales it. +CURVE_RESTORE_BP_MS = [10.0, 20.0, 30.0] +CURVE_RESTORE_A_MS2 = [0.65, 0.45, 0.35] +CURVE_RESTORE_REF_A_MS2 = 0.80 +# Past the apex: once the smoothed a_y has fallen this far below its peak +# the cap may rise again (at the restore rate), so accel returns near the +# apex instead of after the whole bend. Hysteresis keeps jitter out. +CURVE_UNWIND_START_FRAC = 0.10 +CURVE_UNWIND_FULL_FRAC = 0.25 + + +def _interp(x: float, xp: list[float], fp: list[float]) -> float: + if x <= xp[0]: + return float(fp[0]) + for i in range(1, len(xp)): + if x <= xp[i]: + t = (x - xp[i - 1]) / (xp[i] - xp[i - 1]) + return float(fp[i - 1] + t * (fp[i] - fp[i - 1])) + return float(fp[-1]) + + +def _smooth01(x: float) -> float: + if x <= 0.0: + return 0.0 + if x >= 1.0: + return 1.0 + return x * x * (3.0 - 2.0 * x) + + +def curve_lat_target_ms2(v_ms: float) -> float: + """Comfort cornering lateral accel at speed v (m/s²).""" + return _interp(float(v_ms), CURVE_LAT_TARGET_BP_MS, CURVE_LAT_TARGET_MS2) + + +def curve_restore_a_ms2(v_ms: float, accel_envelope_ms2: float | None = None) -> float: + """MAX restore rate after a bend: speed profile scaled by the Accel envelope.""" + base = _interp(float(v_ms), CURVE_RESTORE_BP_MS, CURVE_RESTORE_A_MS2) + if accel_envelope_ms2 is None or float(accel_envelope_ms2) <= 0.0: + return base + return base * float(accel_envelope_ms2) / CURVE_RESTORE_REF_A_MS2 + + +def curve_speed_for_curvature(kappa: float) -> float | None: + """Speed whose lateral accel on |kappa| equals the speed-dependent target. + + v²·|κ| = A(v) has one root because A falls with speed; a few fixed-point + steps converge. None for a straight road. + """ + k = abs(float(kappa)) + if not math.isfinite(k) or k <= 1e-6: + return None + v = math.sqrt(CURVE_COMFORT_LAT_MS2 / k) + for _ in range(8): + v = math.sqrt(curve_lat_target_ms2(v) / k) + return max(CURVE_SPEED_FLOOR_MS, v) + + +def steer_lat_accel_ms2(v_ego_ms: float, angle_steers_deg: float, + steer_ratio: float, wheelbase: float) -> float: + """Unsigned lateral accel from steer angle (same model as limit_accel_in_turns).""" + sr = float(steer_ratio) if steer_ratio and steer_ratio > 1e-3 else 15.75 + wb = float(wheelbase) if wheelbase and wheelbase > 1e-3 else 2.959 + a_y = (float(v_ego_ms) ** 2) * float(angle_steers_deg) * CV.DEG_TO_RAD / (sr * wb) + return abs(a_y) + + +def cornering_lat_accel_ms2(v_ego_ms: float, angle_steers_deg: float, + steer_ratio: float, wheelbase: float, *, + curvature: float | None = None, + yaw_rate: float | None = None) -> float: + """Unsigned lateral accel from real cornering, else the steer model. + + Curvature is the vehicle-model / desired path curvature (learned steer + ratio, tire stiffness, angle offset). Yaw rate × v is the same quantity + when that curvature is not available. Raw steering angle skips the angle + offset, uses the stock steer ratio, and ignores understeer, so it reads + high. The steer model remains only when both signals are missing. + """ + v = float(v_ego_ms) + if curvature is not None and math.isfinite(float(curvature)): + return abs(float(curvature)) * v * v + if yaw_rate is not None and math.isfinite(float(yaw_rate)): + return abs(float(yaw_rate) * v) + return steer_lat_accel_ms2(v, angle_steers_deg, steer_ratio, wheelbase) + + +def curve_speed_from_lat(v_ego_ms: float, a_y: float | None, + a_lat: float | None = None) -> float | None: + """Comfort speed for a measured lateral accel. None when not a bend. + + Default target is speed-dependent (curve_lat_target_ms2); a fixed + `a_lat` keeps the old v·sqrt(a_lat/a_y) form. + """ + if a_y is None or v_ego_ms < CURVE_MIN_V_EGO_MS or (a_lat is not None and a_lat <= 0): + return None + ay = float(a_y) + if ay < 0.05: + return None + if a_lat is None: + return curve_speed_for_curvature(ay / (float(v_ego_ms) ** 2)) + v = float(v_ego_ms) * math.sqrt(float(a_lat) / ay) + if v < CURVE_SPEED_FLOOR_MS: + return CURVE_SPEED_FLOOR_MS + return v + + +def curve_speed_ms(v_ego_ms: float, angle_steers_deg: float, + steer_ratio: float, wheelbase: float, + a_lat: float | None = None) -> float | None: + """Comfort v from current steer (fallback only). None when not a bend.""" + if v_ego_ms < CURVE_MIN_V_EGO_MS or (a_lat is not None and a_lat <= 0): + return None + ang = abs(float(angle_steers_deg)) + if ang < 1e-3: + return None + sr = float(steer_ratio) if steer_ratio and steer_ratio > 1e-3 else 15.75 + wb = float(wheelbase) if wheelbase and wheelbase > 1e-3 else 2.959 + kappa = ang * CV.DEG_TO_RAD / (sr * wb) + if kappa <= 1e-6: + return None + if a_lat is None: + return curve_speed_for_curvature(kappa) + v = math.sqrt(float(a_lat) / kappa) + if v < CURVE_SPEED_FLOOR_MS: + return CURVE_SPEED_FLOOR_MS + return v + + +def is_sharp_curve(v_ego_ms: float, angle_steers_deg: float, + steer_ratio: float, wheelbase: float, *, + active: bool, lat_override: float | None = None) -> bool: + """Hysteresis: enter on lat accel or steer; stay until both are quiet.""" + if v_ego_ms < CURVE_MIN_V_EGO_MS: + return False + if lat_override is None: + a_y = steer_lat_accel_ms2(v_ego_ms, angle_steers_deg, steer_ratio, wheelbase) + else: + a_y = float(lat_override) + steer = abs(float(angle_steers_deg)) + if active: + return a_y >= CURVE_EXIT_LAT_MS2 or steer >= CURVE_EXIT_STEER_DEG + return a_y >= CURVE_ENTER_LAT_MS2 or steer >= CURVE_ENTER_STEER_DEG + + +def _valid_max_kph(kph: float | None) -> bool: + if kph is None: + return False + return 0.0 < float(kph) < float(V_CRUISE_UNSET) + + +@dataclass +class CurveMaxSnapshot: + hud_max_kph: float + held_max_kph: float | None + sticky_set_kph: float | None + posted_kph: float | None + + +@dataclass +class CurveMaxDecision: + """One card.py cycle after the map overlay computed HUD MAX.""" + hud_kph: float + restore_seed_kph: float | None + freeze_posted: bool + active: bool + + +class CurveMaxHold: + """Lat-based snapshot / restore of pre-curve MAX.""" + + def __init__(self) -> None: + self.snapshot: CurveMaxSnapshot | None = None + self.active: bool = False + self._exit_s: float = 0.0 + self._ay_raw: float | None = None + self._ay_s: float | None = None + self._begin_ran: bool = False + self._cap_kph: float | None = None + self._cap_age: float = 0.0 + self._release_kph: float | None = None + self._restore_a: float | None = None + self._last_dt: float = 0.01 + self._ay_peak: float = 0.0 + + def reset(self) -> None: + self.snapshot = None + self.active = False + self._exit_s = 0.0 + self._ay_raw = None + self._ay_s = None + self._begin_ran = False + self._cap_kph = None + self._cap_age = 0.0 + self._release_kph = None + self._ay_peak = 0.0 + + def _observe(self, v_ego_ms: float, angle_steers_deg: float, + steer_ratio: float, wheelbase: float, dt: float, *, + curvature: float | None, yaw_rate: float | None, + update: bool) -> None: + """Sample cornering once per card cycle and smooth it for the cap.""" + if not update and self._ay_raw is not None: + return + raw = cornering_lat_accel_ms2( + v_ego_ms, angle_steers_deg, steer_ratio, wheelbase, + curvature=curvature, yaw_rate=yaw_rate, + ) + self._ay_raw = raw + self._last_dt = max(0.0, float(dt)) + if self._ay_s is None: + self._ay_s = raw + return + tau = CURVE_LAT_TAU_S + alpha = self._last_dt / (tau + self._last_dt) if tau > 0.0 else 1.0 + self._ay_s = self._ay_s + alpha * (raw - self._ay_s) + + def lat_curving(self, v_ego_ms: float, angle_steers_deg: float, + steer_ratio: float, wheelbase: float) -> bool: + return is_sharp_curve( + v_ego_ms, angle_steers_deg, steer_ratio, wheelbase, active=self.active, + lat_override=self._ay_raw, + ) + + def _unwind_weight(self) -> float: + """0 while the bend holds or tightens, 1 once a_y is well past its peak.""" + ay = float(self._ay_s or 0.0) + self._ay_peak = max(self._ay_peak, ay) + if self._ay_peak <= 0.05: + return 0.0 + frac = 1.0 - ay / self._ay_peak + return _smooth01((frac - CURVE_UNWIND_START_FRAC) / (CURVE_UNWIND_FULL_FRAC - CURVE_UNWIND_START_FRAC)) + + def _held_cap_kph(self, hud_kph: float, v_ego_ms: float) -> float: + """Cap from smoothed cornering. May drop; rises only as the bend unwinds. + + Jitter inside the unwind hysteresis never raises it. Past the apex the + cap climbs toward the looser comfort speed at the restore rate. + """ + unwind = self._unwind_weight() + v_curve = curve_speed_from_lat(v_ego_ms, self._ay_s) + if v_curve is None: + proposed = float(hud_kph) + else: + proposed = min(float(hud_kph), float(v_curve) * CV.MS_TO_KPH) + if self._cap_kph is None: + self._cap_kph = proposed + self._cap_age = 0.0 + else: + self._cap_age += self._last_dt + if self._cap_age < CURVE_CAP_SETTLE_S: + self._cap_kph = proposed + elif proposed < self._cap_kph - CURVE_CAP_TIGHTEN_KPH: + self._cap_kph = proposed + elif proposed > self._cap_kph and unwind > 0.0: + rate = curve_restore_a_ms2(v_ego_ms, self._restore_a) * CV.MS_TO_KPH + self._cap_kph = min(proposed, self._cap_kph + rate * unwind * self._last_dt) + return min(float(hud_kph), float(self._cap_kph)) + + def _step_release(self, target_kph: float, dt: float, v_ego_ms: float) -> tuple[float, bool]: + """Ramp HUD MAX up toward the pre-curve snapshot. Returns (kph, done). + + Rate is speed-dependent (~0.65 town, ~0.35 highway at default Accel), + scaled by card's Accel envelope. + """ + target = float(target_kph) + if self._release_kph is None: + start = self._cap_kph if self._cap_kph is not None else target + self._release_kph = min(float(start), target) + rate = curve_restore_a_ms2(v_ego_ms, self._restore_a) + step = rate * CV.MS_TO_KPH * max(0.0, float(dt)) + nxt = min(target, float(self._release_kph) + step) + done = nxt >= target - 0.05 + self._release_kph = target if done else nxt + return float(self._release_kph), done + + def should_freeze_posted(self, v_ego_ms: float, angle_steers_deg: float, + steer_ratio: float, wheelbase: float) -> bool: + """True while in/exiting a curve — do not treat OSM flicker as posted b.""" + return bool(self.active or self.lat_curving( + v_ego_ms, angle_steers_deg, steer_ratio, wheelbase, + )) + + def capture(self, *, hud_max_kph: float, + held_max_kph: float | None, + sticky_set_kph: float | None, + posted_kph: float | None) -> None: + hud = float(hud_max_kph) + if not _valid_max_kph(hud): + return + self.snapshot = CurveMaxSnapshot( + hud_max_kph=hud, + held_max_kph=float(held_max_kph) if _valid_max_kph(held_max_kph) else None, + sticky_set_kph=float(sticky_set_kph) if _valid_max_kph(sticky_set_kph) else None, + posted_kph=float(posted_kph) if _valid_max_kph(posted_kph) else None, + ) + self.active = True + self._exit_s = 0.0 + + def begin_cycle( + self, + hold, + *, + last_hud_kph: float, + posted_kph: float | None, + v_ego_ms: float, + angle_steers_deg: float, + steer_ratio: float, + wheelbase: float, + engaged: bool, + take_speed_now: bool = False, + dt: float = 0.01, + curvature: float | None = None, + yaw_rate: float | None = None, + ) -> tuple[float | None, bool]: + """Before decide_map_cruise: snapshot pre-curve MAX, freeze posted flicker. + + Returns (posted_kph for policy, freeze). Snapshot posted is the last + known zone (`hold.last_posted_kph`), not this frame's possibly-flickered + match. The exit frame is not frozen so a posted that persisted through + the bend can rebase. + """ + if not engaged or take_speed_now: + self.reset() + return posted_kph, False + self._observe( + v_ego_ms, angle_steers_deg, steer_ratio, wheelbase, dt, + curvature=curvature, yaw_rate=yaw_rate, update=True, + ) + self._begin_ran = True + lat_now = self.lat_curving(v_ego_ms, angle_steers_deg, steer_ratio, wheelbase) + if self.active and not lat_now and (self._exit_s + float(dt)) + 1e-9 >= CURVE_EXIT_HOLD_S: + return posted_kph, False + freeze = bool(self.active or lat_now) + if freeze and self.snapshot is None: + posted_snap = getattr(hold, "last_posted_kph", None) + if not _valid_max_kph(posted_snap): + posted_snap = posted_kph + hud_snap = last_hud_kph + if not _valid_max_kph(hud_snap): + if _valid_max_kph(getattr(hold, "sticky_set_kph", None)): + hud_snap = float(hold.sticky_set_kph) + elif _valid_max_kph(getattr(hold, "held_max_kph", None)): + hud_snap = float(hold.held_max_kph) + self.capture( + hud_max_kph=float(hud_snap) if _valid_max_kph(hud_snap) else 0.0, + held_max_kph=getattr(hold, "held_max_kph", None), + sticky_set_kph=getattr(hold, "sticky_set_kph", None), + posted_kph=posted_snap, + ) + if freeze and self.snapshot is not None: + return self.policy_posted_kph(posted_kph), True + return posted_kph, freeze + + def policy_posted_kph(self, posted_kph: float | None) -> float | None: + """Posted value decide_map_cruise should see while the curve is frozen.""" + if self.snapshot is not None and self.snapshot.posted_kph is not None: + return float(self.snapshot.posted_kph) + return posted_kph + + def protect_hold(self, hold) -> None: + """Undo a downward sticky/held write the curve path invented.""" + snap = self.snapshot + if snap is None or not self.active: + return + if snap.held_max_kph is not None: + hold.held_max_kph = float(snap.held_max_kph) + if snap.sticky_set_kph is not None: + hold.sticky_set_kph = float(snap.sticky_set_kph) + if snap.posted_kph is not None: + hold.last_posted_kph = float(snap.posted_kph) + + def restore_hold(self, hold) -> float | None: + """Write snapshot back onto hold. Returns HUD MAX to publish, or None.""" + snap = self.snapshot + if snap is None: + return None + self.protect_hold(hold) + return float(snap.hud_max_kph) + + def finish( + self, + *, + hud_kph: float, + hold, + posted_kph: float | None, + v_ego_ms: float, + angle_steers_deg: float, + steer_ratio: float, + wheelbase: float, + engaged: bool, + stalk_pressed: bool = False, + take_speed_now: bool = False, + dt: float, + curvature: float | None = None, + yaw_rate: float | None = None, + restore_a_ms2: float | None = None, + long_active: bool = True, + ) -> CurveMaxDecision: + """Apply temp curve cap or restore. Call after decide_map_cruise + overlay. + + `long_active` is software long (not paused). In a long pause the driver + owns speed: the bend still freezes posted flicker and protects the + held MAX, but the temporary cap does not lower HUD MAX and there is no + restore ramp. Otherwise a stale ramp value would override the held-MAX + seed on the resume frame and be written onto the pedal set speed. + """ + if not engaged or take_speed_now: + self.reset() + return CurveMaxDecision(float(hud_kph), None, False, False) + + if restore_a_ms2 is not None and float(restore_a_ms2) > 0.0: + self._restore_a = float(restore_a_ms2) + self._observe( + v_ego_ms, angle_steers_deg, steer_ratio, wheelbase, dt, + curvature=curvature, yaw_rate=yaw_rate, update=not self._begin_ran, + ) + self._begin_ran = False + lat_now = self.lat_curving(v_ego_ms, angle_steers_deg, steer_ratio, wheelbase) + + if lat_now and not self.active: + # Fallback if begin_cycle did not run. Prefer hold (pre-flicker). + last_hud = float(hud_kph) + if _valid_max_kph(getattr(hold, "sticky_set_kph", None)): + last_hud = float(hold.sticky_set_kph) + elif _valid_max_kph(getattr(hold, "held_max_kph", None)): + last_hud = float(hold.held_max_kph) + posted_snap = getattr(hold, "last_posted_kph", None) + if not _valid_max_kph(posted_snap): + posted_snap = posted_kph + self.capture( + hud_max_kph=last_hud, + held_max_kph=getattr(hold, "held_max_kph", None), + sticky_set_kph=getattr(hold, "sticky_set_kph", None), + posted_kph=posted_snap, + ) + + if not self.active: + return CurveMaxDecision(float(hud_kph), None, False, False) + + will_exit = (not lat_now) and (self._exit_s + float(dt)) + 1e-9 >= CURVE_EXIT_HOLD_S + if stalk_pressed: + posted_snap = posted_kph + if self.snapshot is not None and self.snapshot.posted_kph is not None: + posted_snap = self.snapshot.posted_kph + self.capture( + hud_max_kph=float(hud_kph), + held_max_kph=float(hud_kph) if _valid_max_kph(hud_kph) else getattr(hold, "held_max_kph", None), + sticky_set_kph=float(hud_kph) if getattr(hold, "sticky_set_kph", None) is not None else None, + posted_kph=posted_snap, + ) + elif not will_exit: + self.protect_hold(hold) + + if lat_now: + self._exit_s = 0.0 + self._release_kph = None + if not long_active: + # Driver in control: no cap. A resume mid-bend settles a fresh cap. + self._cap_kph = None + return CurveMaxDecision(float(hud_kph), None, True, True) + capped = self._held_cap_kph(float(hud_kph), v_ego_ms) + return CurveMaxDecision(capped, None, True, True) + + self._exit_s += float(dt) + if not long_active: + # Straight in a pause: restore now, no exit hold and no ramp. + will_exit = True + self._release_kph = None + self._cap_kph = None + if not will_exit: + capped = self._held_cap_kph(float(hud_kph), v_ego_ms) + return CurveMaxDecision(capped, None, True, True) + + # Straight-ish long enough. Same posted zone → ramp MAX back to the + # snapshot. A new posted that persisted through the bend is a real rebase. + same_zone = ( + self.snapshot is not None + and ( + self.snapshot.posted_kph is None + or posted_kph is None + or posted_limits_same(self.snapshot.posted_kph, posted_kph) + ) + ) + if same_zone and self.snapshot is not None: + target = float(self.snapshot.hud_max_kph) + if long_active: + ramped, done = self._step_release(target, dt, v_ego_ms) + else: + ramped, done = target, True + if not done: + self.protect_hold(hold) + return CurveMaxDecision(ramped, None, False, True) + restored = self.restore_hold(hold) + self.reset() + if restored is not None: + return CurveMaxDecision(float(restored), float(restored), False, False) + self.reset() + return CurveMaxDecision(float(hud_kph), None, False, False) + + +def _temp_curve_hud(hud_kph: float, v_ego_ms: float, angle_steers_deg: float, + steer_ratio: float, wheelbase: float) -> float: + """Lower published MAX for the bend only. Never raise. Never below floor.""" + v_curve = curve_speed_ms(v_ego_ms, angle_steers_deg, steer_ratio, wheelbase) + if v_curve is None: + return float(hud_kph) + curve_kph = float(v_curve) * CV.MS_TO_KPH + return min(float(hud_kph), curve_kph) diff --git a/selfdrive/controls/lib/curve_preview.py b/selfdrive/controls/lib/curve_preview.py new file mode 100644 index 00000000000000..05b16789279a84 --- /dev/null +++ b/selfdrive/controls/lib/curve_preview.py @@ -0,0 +1,200 @@ +"""Curve preview slowing and exit release from the model path. + +Justin (Sep 20–27 qlogs) starts slowing 6–9 s before the tightest point +of a bend, while lateral accel is still small, and is back on the gas at +the apex. The reactive curve cap (current curvature) only starts once the +car is already in the bend, and the stock turn clip (1.7 m/s² total on a +raw steer model) held +a at 0 until the bend had unwound. + +Preview: over the model path 0–5 s ahead, each point's comfort speed +(speed-dependent lateral target on its curvature) sets a kinematic accel +ceiling that reaches that speed ~1.5 s before the point: negative when +the car must slow, a small positive allowance when it is just under the +comfort speed (no speeding up into the bend and braking again). The +strongest one, bounded below by a speed-dependent comfort decel and +jerk-limited, is a min() on the longitudinal command: it can only lower +the command, never raise it. MAX stays the hard ceiling. Points near the +horizon edge fade in, so a bend entering the horizon does not step. + +Exit: the turn clip is a friction circle on true cornering force, using +the smaller of the current lateral accel and the path's 1 s ahead, so +a +returns as the road straightens instead of after it has. +""" +from __future__ import annotations + +import math + +from openpilot.selfdrive.controls.lib.curve_max_hold import curve_speed_for_curvature +from openpilot.selfdrive.modeld.constants import ModelConstants + +# Oct 13: the bend was seen only 3–5 s ahead, so slowing began 0.6–6 s AFTER +# turn-in and plateaued at -0.35…-0.43, shedding 5–8 mph mid-curve. Look out +# 7 s so slowing starts ~2.5–3 s before turn-in (Justin's lift point). +PREVIEW_HORIZON_S = 7.0 +# Actuator lag compensation: pedal/regen response trails the command by +# ~1.5 s, so the command finishes 1.5 s before the tight point and the car +# itself is done slowing by the apex. +PREVIEW_LAG_S = 1.5 +PREVIEW_LEAD_S = PREVIEW_LAG_S +# Room is never shorter than this much travel, so a small overspeed near +# the car asks for a proportional ease, not a wall. +PREVIEW_MIN_ROOM_S = 2.0 +PREVIEW_MIN_ROOM_M = 5.0 +PREVIEW_MIN_V_MS = 5.0 +# Comfort decel and build jerk vs speed: firm in town, a lift on the highway. +PREVIEW_DECEL_BP_MS = [10.0, 25.0] +# Oct 13: about -0.8 m/s² cap (~60 % of his -1.4 lift-off), every speed. +PREVIEW_DECEL_MS2 = [0.8, 0.8] +PREVIEW_JERK_MS3 = [1.0, 0.8] +PREVIEW_RELEASE_JERK_MS3 = 1.0 +PREVIEW_TAU_S = 0.30 +PREVIEW_MAX_ABS_CURVATURE = 0.2 # ignore nonsense samples (r < 5 m) +# No constraint (straight road): the ceiling is this, i.e. nothing binds. +PREVIEW_FREE_A_MS2 = 2.0 +# Points in the last second of the horizon fade in. +PREVIEW_FADE_S = 1.0 + +# Exit: total accel allowed through a bend (true cornering force). +TURN_TOTAL_BP_MS = [8.0, 20.0, 30.0, 40.0] +TURN_TOTAL_MS2 = [2.4, 2.3, 2.4, 3.2] +EXIT_LOOKAHEAD_S = 1.0 + + +def _interp(x: float, xp: list[float], fp: list[float]) -> float: + if x <= xp[0]: + return float(fp[0]) + for i in range(1, len(xp)): + if x <= xp[i]: + t = (x - xp[i - 1]) / (xp[i] - xp[i - 1]) + return float(fp[i - 1] + t * (fp[i] - fp[i - 1])) + return float(fp[-1]) + + +def preview_decel_limit_ms2(v_ego: float) -> float: + return _interp(float(v_ego), PREVIEW_DECEL_BP_MS, PREVIEW_DECEL_MS2) + + +def path_curvature(model) -> tuple[list[float], list[float], list[float]] | None: + """(t, distance along path, curvature) from modelV2, or None if unusable. + + Curvature is the path yaw rate over its speed (orientationRate.z / v). + """ + try: + xs = [float(v) for v in model.position.x] + vs = [float(v) for v in model.velocity.x] + wz = [float(v) for v in model.orientationRate.z] + ts = [float(v) for v in model.position.t] if len(model.position.t) == len(xs) else list(ModelConstants.T_IDXS) + except (AttributeError, TypeError, ValueError): + return None + n = len(xs) + if n < 2 or len(vs) != n or len(wz) != n or len(ts) != n: + return None + if not all(math.isfinite(v) for v in xs + vs + wz + ts): + return None + ks = [] + for w, v in zip(wz, vs, strict=True): + k = w / max(v, 1.0) + ks.append(max(-PREVIEW_MAX_ABS_CURVATURE, min(PREVIEW_MAX_ABS_CURVATURE, k))) + return ts, xs, ks + + +def _smooth01(x: float) -> float: + if x <= 0.0: + return 0.0 + if x >= 1.0: + return 1.0 + return x * x * (3.0 - 2.0 * x) + + +def curve_preview_accel(v_ego: float, ts, dists, kappas) -> float: + """Unslewed accel ceiling from the path ahead (PREVIEW_FREE_A_MS2 = none). + + Negative when a bend ahead needs a slower speed, bounded by the comfort + decel; small positive when the car is just under a bend's comfort speed. + """ + v = float(v_ego) + if v < PREVIEW_MIN_V_MS or ts is None: + return PREVIEW_FREE_A_MS2 + a = PREVIEW_FREE_A_MS2 + min_room = max(PREVIEW_MIN_ROOM_M, PREVIEW_MIN_ROOM_S * v) + for t, d, k in zip(ts, dists, kappas, strict=True): + if t < 0.0 or t > PREVIEW_HORIZON_S: + continue + v_t = curve_speed_for_curvature(k) + if v_t is None: + continue + room = max(min_room, float(d) - PREVIEW_LEAD_S * v) + a_i = (v_t * v_t - v * v) / (2.0 * room) + fade = _smooth01((float(t) - (PREVIEW_HORIZON_S - PREVIEW_FADE_S)) / PREVIEW_FADE_S) + a_i += (PREVIEW_FREE_A_MS2 - a_i) * fade + a = min(a, a_i) + return min(PREVIEW_FREE_A_MS2, max(a, -preview_decel_limit_ms2(v))) + + +def path_lat_accel_ahead(v_ego: float, ts, kappas, t_ahead: float = EXIT_LOOKAHEAD_S) -> float | None: + """|a_y| the path asks for t_ahead seconds from now, at today's speed.""" + if ts is None or not ts: + return None + if t_ahead <= ts[0]: + k = kappas[0] + elif t_ahead >= ts[-1]: + k = kappas[-1] + else: + k = kappas[-1] + for i in range(1, len(ts)): + if t_ahead <= ts[i]: + f = (t_ahead - ts[i - 1]) / max(1e-6, ts[i] - ts[i - 1]) + k = kappas[i - 1] + f * (kappas[i] - kappas[i - 1]) + break + return abs(float(k)) * float(v_ego) ** 2 + + +def turn_total_accel_ms2(v_ego: float) -> float: + return _interp(float(v_ego), TURN_TOTAL_BP_MS, TURN_TOTAL_MS2) + + +def turn_accel_limit(v_ego: float, a_y_now: float, a_y_ahead: float | None = None) -> float: + """+a allowed in a bend: friction circle on the smaller of now / 1 s ahead.""" + ay = abs(float(a_y_now)) + if a_y_ahead is not None and math.isfinite(float(a_y_ahead)): + ay = min(ay, abs(float(a_y_ahead))) + total = turn_total_accel_ms2(v_ego) + return math.sqrt(max(total * total - ay * ay, 0.0)) + + +class CurvePreview: + """Low-pass the preview ceiling; jerk-limit its braking part. + + The braking part (<= 0) builds and releases at comfort jerk, and a + braking ceiling never rises faster than the release jerk. The positive + allowance passes through the low-pass only; it can only hold back +a, + never add it. + """ + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self._f = PREVIEW_FREE_A_MS2 + self._brake = 0.0 + self.a = PREVIEW_FREE_A_MS2 + + def update(self, v_ego: float, a_raw: float, dt: float) -> float: + dt = max(1e-3, float(dt)) + target = min(PREVIEW_FREE_A_MS2, float(a_raw)) + self._f += (dt / (PREVIEW_TAU_S + dt)) * (target - self._f) + build = _interp(float(v_ego), PREVIEW_DECEL_BP_MS, PREVIEW_JERK_MS3) * dt + release = PREVIEW_RELEASE_JERK_MS3 * dt + delta = min(0.0, self._f) - self._brake + if delta < -build: + delta = -build + elif delta > release: + delta = release + self._brake = min(0.0, self._brake + delta) + out = self._brake + max(0.0, self._f) + # Past the bend the positive allowance returns fast; while the ceiling + # is still braking, it rises no faster than the release jerk. + if self.a < 0.0: + out = min(out, self.a + release) + self.a = out + return self.a diff --git a/selfdrive/controls/lib/desire_helper.py b/selfdrive/controls/lib/desire_helper.py index 90b68586497777..02fee4289b4197 100644 --- a/selfdrive/controls/lib/desire_helper.py +++ b/selfdrive/controls/lib/desire_helper.py @@ -1,13 +1,63 @@ +import math + from cereal import log -from openpilot.common.conversions import Conversions as CV -from openpilot.common.realtime import DT_MDL +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import cs_hands_on_level +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + SOFT_YIELD_TRIGGER_NM, + EmergencyYankTracker, + SoftConfirmTracker, + is_emergency_yank, + tipped_lane_change_driver_release, + torque_is_same_direction, +) +from openpilot.selfdrive.controls.lib.lane_change_target import ( + RECROSS_MARGIN_M, + STALL_PROGRESS_LANES, + STALL_REPULSE_S, + LANE_LINES_UNCLEAR_SIGNAL, + LOCK_RETRY_S, + LaneChangeTarget, + lane_line_offsets, +) +from openpilot.selfdrive.controls.lib.lane_change_turn import is_lane_change_turn +from openpilot.selfdrive.controls.lib.stalk_tip_turn import StalkTipTurn LaneChangeState = log.LaneChangeState LaneChangeDirection = log.LaneChangeDirection +# Min speed to *start* the lane-change maneuver (preLaneChange → starting) +# after a wheel nudge. Tip vs turn is classified from stalk hold time, not +# this. Stock comma / prior NAP used the same 20 mph floor for the change +# itself. LANE_CHANGE_SPEED_MIN = 20 * CV.MPH_TO_MS LANE_CHANGE_TIME_MAX = 10. +# Match openpilot.common.realtime.DT_MDL. Kept local so this helper does not +# import the hardware stack. +DT_MDL = 0.05 + +# Time the lane change stays armed waiting for steering input. +LANE_CHANGE_ARM_TIME = 7.0 + +# Target-locked change: an opposite pull cancels only when it is a real +# pull (steeringPressed, >= the soft-yield floor against the change) held +# OPPOSITE_PULL_SUSTAIN_S. The spring-back after a confirm push is one +# 10 Hz sample: 54 of 145 logged starts (Sep 16-28) had a steeringPressed +# opposite-sign sample within [-0.6, +2.0] s of the start (up to 1.22 Nm, +# e.g. -2.52 -> +1.22 Nm), and with the armed soft confirm the start now +# comes before that spring-back. Held 0.20 s at >= 0.55 Nm only matched +# the 2 real opposite pulls (>= 4 Nm). Hard pulls still hit the emergency +# lines. +OPPOSITE_PULL_NM = SOFT_YIELD_TRIGGER_NM +OPPOSITE_PULL_SUSTAIN_S = 0.20 + +# "Lane lines unclear" stays up this long after a lock retry runs out. +LANE_LINES_UNCLEAR_SHOW_S = 2.0 + +# Cap on how many same-direction lane changes can be queued from repeated taps. +MAX_QUEUED_LANE_CHANGES = 3 + DESIRES = { LaneChangeDirection.none: { LaneChangeState.off: log.Desire.none, @@ -30,6 +80,24 @@ } +def _driver_torque_nm(carstate) -> float: + """Torsion relative to the car's learned hands-off offset. + + ``napRestTorqueNm`` is published on carState (already subscribed). + Missing field is 0, so callers without the offset are unchanged. + A resting +0.25 Nm must not read as a left nudge. + """ + try: + raw = float(getattr(carstate, "steeringTorque", 0.0) or 0.0) + except (TypeError, ValueError): + raw = 0.0 + try: + rest = float(getattr(carstate, "napRestTorqueNm", 0.0) or 0.0) + except (TypeError, ValueError): + rest = 0.0 + return raw - rest + + class DesireHelper: def __init__(self): self.lane_change_state = LaneChangeState.off @@ -40,38 +108,365 @@ def __init__(self): self.prev_one_blinker = False self.desire = log.Desire.none - def update(self, carstate, lateral_active, lane_change_prob): + self.arm_timer = 0.0 + self.signals_remaining = math.ceil(LANE_CHANGE_ARM_TIME) + + # Stalk tip vs turn. Independent of lane-change state so a held lever + # is not re-read as a new tip after a reset. + self._tip_turn = StalkTipTurn() + self._suppress_next_tip = False + # Set by modeld from NAPRoundaboutLatched (roundabout ring assist latched): a tip is not a lane change on a ring. + self.suppress_tips = False + self._yank = EmergencyYankTracker() + self._soft_confirm = SoftConfirmTracker() + self._opposite_s = 0.0 + + # Includes the lane change currently armed or in progress. + self.queued_changes = 0 + self.lane_changes_remaining = 0 + + # Target lock (see lane_change_target). None when no tipped lane + # change is in progress, or when no modelV2 is passed (legacy path). + self.target: LaneChangeTarget | None = None + self.target_suspended = False + self._best_progress = 0.0 + self._stall_s = 0.0 + + # Confirmed but not yet locked (crossing line not seen): the lock is + # retried for LOCK_RETRY_S instead of cancelling the change. + self._lock_pending = False + self._lock_gave_up = False + self._lock_wait_s = 0.0 + self._confirm_prev = False + self._unclear_s = 0.0 + self._last_lane_width: float | None = None + + @property + def lane_lines_unclear(self) -> bool: + """Armed, confirmed, and the lock retry ran out (crossing line weak).""" + return self._unclear_s > 0.0 + + @property + def target_locked(self) -> bool: + return self.target is not None + + @staticmethod + def get_lane_change_direction(CS): + return LaneChangeDirection.left if CS.leftBlinker else LaneChangeDirection.right + + @staticmethod + def lane_change_keep_blinker(state, direction): + """Request the turn indicator while ALC is armed or in progress. + + controlsd copies this onto CC.leftBlinker / rightBlinker so Pre-AP + DAS_bodyControls keeps flashing until laneChangeState returns to off. + Stalk returning to IDLE is not a cancel. + """ + if state == LaneChangeState.off or direction == LaneChangeDirection.none: + return False, False + return (direction == LaneChangeDirection.left, + direction == LaneChangeDirection.right) + + @staticmethod + def _opposite_pull(carstate, direction: int) -> bool: + """Driver override (steeringPressed) against the lane-change direction.""" + if not bool(getattr(carstate, "steeringPressed", False)): + return False + torque = _driver_torque_nm(carstate) + if direction == 1: + return torque <= -OPPOSITE_PULL_NM + if direction == 2: + return torque >= OPPOSITE_PULL_NM + return False + + def _opposite_pull_held(self, carstate, direction: int) -> bool: + """``_opposite_pull`` held OPPOSITE_PULL_SUSTAIN_S (spring-back is not).""" + if self._opposite_pull(carstate, direction): + self._opposite_s += DT_MDL + else: + self._opposite_s = 0.0 + return self._opposite_s >= OPPOSITE_PULL_SUSTAIN_S - 1e-9 + + def _complete_one(self): + self._clear_target() + self.queued_changes = max(self.queued_changes - 1, 0) + if self.queued_changes > 0: + self.lane_change_state = LaneChangeState.preLaneChange + self.lane_change_ll_prob = 1.0 + self.arm_timer = 0.0 + else: + self._reset() + + def _update_locked(self, suspended: bool) -> bool: + """Advance a target-locked change. Returns True for a one-frame desire gap.""" + target = self.target + if target.reached: + self._complete_one() + return False + if self.lane_change_state == LaneChangeState.laneChangeStarting: + self.lane_change_ll_prob = max(self.lane_change_ll_prob - 2 * DT_MDL, 0.0) + if target.crossed: + self.lane_change_state = LaneChangeState.laneChangeFinishing + else: + self.lane_change_ll_prob = min(self.lane_change_ll_prob + DT_MDL, 1.0) + if target.dist_to_line_m > RECROSS_MARGIN_M: + self.lane_change_state = LaneChangeState.laneChangeStarting + # Stall: lat up but no progress toward the target for a while (the + # model's desire pulse may have run out). Re-pulse the desire. + if suspended: + return False + if target.progress > self._best_progress + STALL_PROGRESS_LANES: + self._best_progress = target.progress + self._stall_s = 0.0 + return False + self._stall_s += DT_MDL + if self._stall_s + 1e-9 >= STALL_REPULSE_S: + self._stall_s = 0.0 + return True + return False + + def _reset(self): + self.lane_change_state = LaneChangeState.off + self.lane_change_direction = LaneChangeDirection.none + self.arm_timer = 0.0 + self.queued_changes = 0 + self.lane_changes_remaining = 0 + self._clear_target() + + def _clear_target(self): + self.target = None + self.target_suspended = False + self._best_progress = 0.0 + self._stall_s = 0.0 + self._lock_pending = False + self._lock_gave_up = False + self._lock_wait_s = 0.0 + self._confirm_prev = False + self._unclear_s = 0.0 + + def _try_lock(self, offsets) -> None: + direction = 1 if self.lane_change_direction == LaneChangeDirection.left else 2 + self.target = LaneChangeTarget.lock(direction, offsets, self._last_lane_width) + if self.target is not None: + self._lock_pending = False + self._lock_gave_up = False + self._unclear_s = 0.0 + self.lane_change_state = LaneChangeState.laneChangeStarting + self._best_progress = self.target.progress + self._stall_s = 0.0 + + def update(self, carstate, lateral_active, lane_change_prob, model=None, engaged=None): + """``model`` is this frame's modelV2 (laneLines / laneLineProbs). + + With a model, a tipped lane change locks a target on start and runs + to the target lane center (see lane_change_target). Without one the + legacy lane_change_prob completion is used. ``engaged`` is + carControl.enabled; None means "same as lateral_active". + """ v_ego = carstate.vEgo + engaged = bool(lateral_active) if engaged is None else bool(engaged) + offsets = lane_line_offsets(model) + good_width = LaneChangeTarget.good_width(offsets) + if good_width is not None: + self._last_lane_width = good_width + self._unclear_s = max(self._unclear_s - DT_MDL, 0.0) + pulse_gap = False one_blinker = carstate.leftBlinker != carstate.rightBlinker below_lane_change_speed = v_ego < LANE_CHANGE_SPEED_MIN - if not lateral_active or self.lane_change_timer > LANE_CHANGE_TIME_MAX: - self.lane_change_state = LaneChangeState.off - self.lane_change_direction = LaneChangeDirection.none + # Physical lever: IDLE=0, LEFT=1, RIGHT=2, SNA=3. No tip/latch bit — + # a tip is LEFT/RIGHT then IDLE within STALK_TIP_HOLD_S; held longer + # from idle is a driver turn. While ALC is armed/in progress, a + # same-direction stalk must stay on past STALK_ALC_TURN_HOLD_S (1.0s) + # to cancel ALC as a turn. Classification uses the stalk, not lamps. + self._tip_turn.update(carstate.turnSignalStalkState, DT_MDL) + torque_nm = _driver_torque_nm(carstate) + fast_rise = self._yank.update(torque_nm, DT_MDL) + if self.lane_change_state == LaneChangeState.off: + lc_dir = 0 + elif self.lane_change_direction == LaneChangeDirection.left: + lc_dir = 1 + elif self.lane_change_direction == LaneChangeDirection.right: + lc_dir = 2 else: - # LaneChangeState.off - if self.lane_change_state == LaneChangeState.off and one_blinker and not self.prev_one_blinker and not below_lane_change_speed: + lc_dir = 0 + emergency_yank = is_emergency_yank( + torque_nm=torque_nm, + hands_on_level=cs_hands_on_level(carstate), + fast_rise=fast_rise, + over_torque=self._yank.over_torque, + alc_direction=lc_dir, + ) + # Driver turning in the lane-change direction (wheel angle well past + # any lane change): end the change and drop the target for good. + # controlsd keeps the blinker and pauses lat like a manual turn. + driver_turn = is_lane_change_turn( + direction=lc_dir, steering_angle_deg=float(getattr(carstate, "steeringAngleDeg", 0.0) or 0.0), + torque_nm=torque_nm, lat_active=bool(lateral_active)) + # Counted every frame so a spring-back never carries over. + opposite_pull = self._opposite_pull_held(carstate, lc_dir) + # Armed-only soft confirm: preLaneChange, >= 20 mph, same direction. + soft_confirm = self._soft_confirm.update( + torque_nm=torque_nm, direction=lc_dir, + armed=(self.lane_change_state == LaneChangeState.preLaneChange and not below_lane_change_speed), + dt=DT_MDL) + left_press = self._tip_turn.left_press + right_press = self._tip_turn.right_press + tip_event = self._tip_turn.tip_event and not self._suppress_next_tip and not self.suppress_tips + if not self._tip_turn.is_pending and self._tip_turn.direction == 0: + self._suppress_next_tip = False + + if self.lane_change_direction == LaneChangeDirection.left: + alc_stalk_dir = 1 + same_direction_tip, opposite_press = ( + tip_event and self._tip_turn.tip_direction == 1, right_press) + elif self.lane_change_direction == LaneChangeDirection.right: + alc_stalk_dir = 2 + same_direction_tip, opposite_press = ( + tip_event and self._tip_turn.tip_direction == 2, left_press) + else: + alc_stalk_dir = 0 + same_direction_tip, opposite_press = False, False + + locked = self.target is not None + if locked: + self.target.update(offsets, DT_MDL) + # An ordinary lateral release (not an emergency yank, not a cancel) + # keeps a target-locked change: desire drops while lat is down and is + # re-asserted (fresh rising edge for the model's desire pulse) when + # lat resumes. The legacy time cap is replaced by the lock's own + # TARGET_LOCK_TIMEOUT_S, which also counts released time. + suspended = locked and not lateral_active + if not engaged or (not lateral_active and not locked) or \ + (not locked and self.lane_change_timer > LANE_CHANGE_TIME_MAX): + self._reset() + elif locked and (self.target.timed_out or self.target.low_confidence): + # Stale lane change, or cannot tell which lane the car is in. + self._reset() + self._suppress_next_tip = True + else: + if locked and self.target_suspended and not suspended: + # Lateral just came back: re-assert toward the locked target. + self._stall_s = 0.0 + self.target_suspended = suspended + just_cancelled = False + if self.lane_change_state != LaneChangeState.off: + if self.lane_change_direction == LaneChangeDirection.left: + nudge_dir = 1 + elif self.lane_change_direction == LaneChangeDirection.right: + nudge_dir = 2 + else: + nudge_dir = 0 + # Emergency yank cancels. A same-direction confirm does not. + if tipped_lane_change_driver_release( + same_direction=torque_is_same_direction(torque_nm, nudge_dir), + emergency=emergency_yank): + self._reset() + just_cancelled = True + self._suppress_next_tip = True + elif driver_turn: + # Turning at the intersection before the change finished. + self._reset() + just_cancelled = True + self._suppress_next_tip = True + elif below_lane_change_speed and self.lane_change_state in ( + LaneChangeState.laneChangeStarting, LaneChangeState.laneChangeFinishing): + # Slowed under 20 mph mid-change (e.g. into an intersection): end it. + self._reset() + just_cancelled = True + self._suppress_next_tip = True + elif locked and opposite_pull: + # Target-locked change: an opposite-direction pull cancels. + # Same-direction bumps never pause, slow, or cancel it. + self._reset() + just_cancelled = True + self._suppress_next_tip = True + elif opposite_press: + self._reset() + just_cancelled = True + self._suppress_next_tip = True + elif self._tip_turn.is_driver_turn(alc_latched=True, + alc_direction=alc_stalk_dir): + # Same-direction stalk held >1s during ALC: driver turn, not + # another lane change. Opposite already cancelled above. + self._reset() + just_cancelled = True + elif same_direction_tip: + self.queued_changes = min(self.queued_changes + 1, MAX_QUEUED_LANE_CHANGES) + + # LaneChangeState.off — tip-to-ALC. LEFT/RIGHT then IDLE within + # STALK_TIP_HOLD_S arms (preLaneChange) at any speed. Desire stays + # none; the car does not leave the lane until a wheel nudge + # (steeringPressed + torque in that direction) enters + # laneChangeStarting, and only then if v_ego >= LANE_CHANGE_SPEED_MIN. + # Stalk IDLE alone does not cancel. A held LEFT/RIGHT past the tip + # window does not arm. Hazards do not arm. Lamp edges without a + # lever tip do not arm (OP keep-alive flashes). + hazards = bool(carstate.leftBlinker) and bool(carstate.rightBlinker) + if (not just_cancelled and self.lane_change_state == LaneChangeState.off and + tip_event and not hazards): self.lane_change_state = LaneChangeState.preLaneChange self.lane_change_ll_prob = 1.0 + self.lane_change_direction = (LaneChangeDirection.left + if self._tip_turn.tip_direction == 1 + else LaneChangeDirection.right) + self.arm_timer = 0.0 + self.queued_changes = 1 - # LaneChangeState.preLaneChange + # LaneChangeState.preLaneChange — wait for a wheel nudge. Tap alone + # must not start the maneuver. elif self.lane_change_state == LaneChangeState.preLaneChange: - # Set lane change direction - self.lane_change_direction = LaneChangeDirection.left if \ - carstate.leftBlinker else LaneChangeDirection.right - torque_applied = carstate.steeringPressed and \ - ((carstate.steeringTorque > 0 and self.lane_change_direction == LaneChangeDirection.left) or - (carstate.steeringTorque < 0 and self.lane_change_direction == LaneChangeDirection.right)) + ((torque_nm > 0 and self.lane_change_direction == LaneChangeDirection.left) or + (torque_nm < 0 and self.lane_change_direction == LaneChangeDirection.right)) + # A lighter same-direction nudge held SOFT_CONFIRM_SUSTAIN_S also confirms. + torque_applied = torque_applied or soft_confirm blindspot_detected = ((carstate.leftBlindspot and self.lane_change_direction == LaneChangeDirection.left) or (carstate.rightBlindspot and self.lane_change_direction == LaneChangeDirection.right)) - if not one_blinker or below_lane_change_speed: - self.lane_change_state = LaneChangeState.off - self.lane_change_direction = LaneChangeDirection.none - elif torque_applied and not blindspot_detected: + self.arm_timer += DT_MDL + + eligible = bool(torque_applied) and not blindspot_detected and not below_lane_change_speed + # A new eligible confirm (rising edge) starts a fresh lock retry window. + if eligible and not self._confirm_prev: + self._lock_pending = True + self._lock_wait_s = 0.0 + self._lock_gave_up = False + self._unclear_s = 0.0 + self._confirm_prev = eligible + if blindspot_detected or below_lane_change_speed: + self._lock_pending = False + self._lock_gave_up = False + + if model is None and eligible: self.lane_change_state = LaneChangeState.laneChangeStarting + elif model is not None and (self._lock_pending or (self._lock_gave_up and eligible)): + self._try_lock(offsets) + if self.target is None: + # Crossing line not confident (a brief probability dip, or the + # line is really not seen): stay armed and retry rather than + # cancelling. After LOCK_RETRY_S "Lane lines unclear" shows and + # the lock keeps being retried while the nudge is held, until + # the 7 s arm window ends. + if self._lock_pending: + self._lock_wait_s += DT_MDL + if self._lock_wait_s >= LOCK_RETRY_S - 1e-9: + self._lock_pending = False + self._lock_gave_up = True + self._unclear_s = LANE_LINES_UNCLEAR_SHOW_S + else: + self._unclear_s = LANE_LINES_UNCLEAR_SHOW_S + if self.arm_timer > LANE_CHANGE_ARM_TIME: + self._reset() + elif self.arm_timer > LANE_CHANGE_ARM_TIME: + # Window expired with no wheel nudge — cancel everything. + self._reset() + + # Target-locked: geometry decides, not lane_change_prob or a timer. + elif self.target is not None and self.lane_change_state in ( + LaneChangeState.laneChangeStarting, LaneChangeState.laneChangeFinishing): + pulse_gap = self._update_locked(suspended) # LaneChangeState.laneChangeStarting elif self.lane_change_state == LaneChangeState.laneChangeStarting: @@ -88,11 +483,28 @@ def update(self, carstate, lateral_active, lane_change_prob): self.lane_change_ll_prob = min(self.lane_change_ll_prob + DT_MDL, 1.0) if self.lane_change_ll_prob > 0.99: - self.lane_change_direction = LaneChangeDirection.none - if one_blinker: + # One change just completed. + self.queued_changes = max(self.queued_changes - 1, 0) + if self.queued_changes > 0: + # More queued: keep the same direction and signal on, re-arm a fresh + # window and wait for the next wheel nudge. self.lane_change_state = LaneChangeState.preLaneChange + self.lane_change_ll_prob = 1.0 + self.arm_timer = 0.0 else: - self.lane_change_state = LaneChangeState.off + # Nothing left — full reset so the toast clears and no ALC re-arms. + self._reset() + + # Retain the existing metadata even though the stock alert text no longer + # displays the countdown or queue depth. + if self.lane_change_state == LaneChangeState.preLaneChange: + self.signals_remaining = max(math.ceil(LANE_CHANGE_ARM_TIME - self.arm_timer), 0) + if self.lane_lines_unclear: + # No capnp change: this otherwise-unused count flags the alert. + self.signals_remaining = LANE_LINES_UNCLEAR_SIGNAL + else: + self.signals_remaining = math.ceil(LANE_CHANGE_ARM_TIME) + self.lane_changes_remaining = max(self.queued_changes - 1, 0) if self.lane_change_state in (LaneChangeState.off, LaneChangeState.preLaneChange): self.lane_change_timer = 0.0 @@ -102,8 +514,12 @@ def update(self, carstate, lateral_active, lane_change_prob): self.prev_one_blinker = one_blinker self.desire = DESIRES[self.lane_change_direction][self.lane_change_state] + if self.target is not None and (self.target_suspended or pulse_gap): + # Lat down: no desire. The next frame with lat back up is a fresh + # rising edge, which is what the model's desire pulse keys on. + self.desire = log.Desire.none - # Send keep pulse once per second during LaneChangeStart.preLaneChange + # Send keep pulse once per second during LaneChangeState.preLaneChange if self.lane_change_state in (LaneChangeState.off, LaneChangeState.laneChangeStarting): self.keep_pulse_timer = 0.0 elif self.lane_change_state == LaneChangeState.preLaneChange: diff --git a/selfdrive/controls/lib/drive_helpers.py b/selfdrive/controls/lib/drive_helpers.py index 35810c48327de9..5392ff88751b38 100644 --- a/selfdrive/controls/lib/drive_helpers.py +++ b/selfdrive/controls/lib/drive_helpers.py @@ -1,48 +1,70 @@ -from cereal import car, log -from openpilot.common.numpy_fast import clip -from openpilot.common.realtime import DT_CTRL -from openpilot.system.version import get_build_metadata - -EventName = car.OnroadEvent.EventName +import numpy as np +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY +from openpilot.common.realtime import DT_CTRL, DT_MDL MIN_SPEED = 1.0 CONTROL_N = 17 CAR_ROTATION_RADIUS = 0.0 +# This is a turn radius smaller than most cars can achieve +MAX_CURVATURE = 0.2 +MAX_VEL_ERR = 5.0 # m/s +MIN_STABLE_DELAY = 0.3 # EU guidelines -MAX_LATERAL_JERK = 5.0 -MAX_VEL_ERR = 5.0 +MAX_LATERAL_JERK = 5.0 # m/s^3 +MAX_LATERAL_ACCEL_NO_ROLL = 3.0 # m/s^2 -def clip_curvature(v_ego, prev_curvature, new_curvature): - v_ego = max(MIN_SPEED, v_ego) - max_curvature_rate = MAX_LATERAL_JERK / (v_ego**2) # inexact calculation, check https://github.com/commaai/openpilot/pull/24755 - safe_desired_curvature = clip(new_curvature, - prev_curvature - max_curvature_rate * DT_CTRL, - prev_curvature + max_curvature_rate * DT_CTRL) - return safe_desired_curvature +def clamp(val, min_val, max_val): + clamped_val = float(np.clip(val, min_val, max_val)) + return clamped_val, clamped_val != val +def smooth_value(val, prev_val, tau, dt=DT_MDL): + alpha = 1 - np.exp(-dt/tau) if tau > 0 else 1 + return alpha * val + (1 - alpha) * prev_val -def get_speed_error(modelV2: log.ModelDataV2, v_ego: float) -> float: - # ToDo: Try relative error, and absolute speed - if len(modelV2.temporalPose.trans): - vel_err = clip(modelV2.temporalPose.trans[0] - v_ego, -MAX_VEL_ERR, MAX_VEL_ERR) - return float(vel_err) - return 0.0 +def clip_curvature(v_ego, prev_curvature, new_curvature, roll) -> tuple[float, bool]: + # This function respects ISO lateral jerk and acceleration limits + a max curvature + v_ego = max(v_ego, MIN_SPEED) + max_curvature_rate = MAX_LATERAL_JERK / (v_ego ** 2) # inexact calculation, check https://github.com/commaai/openpilot/pull/24755 + new_curvature = np.clip(new_curvature, + prev_curvature - max_curvature_rate * DT_CTRL, + prev_curvature + max_curvature_rate * DT_CTRL) + roll_compensation = roll * ACCELERATION_DUE_TO_GRAVITY + max_lat_accel = MAX_LATERAL_ACCEL_NO_ROLL + roll_compensation + min_lat_accel = -MAX_LATERAL_ACCEL_NO_ROLL + roll_compensation + new_curvature, limited_accel = clamp(new_curvature, min_lat_accel / v_ego ** 2, max_lat_accel / v_ego ** 2) -def get_startup_event(car_recognized, controller_available, fw_seen): - build_metadata = get_build_metadata() - if build_metadata.openpilot.comma_remote and build_metadata.tested_channel: - event = EventName.startup - else: - event = EventName.startupMaster + new_curvature, limited_max_curv = clamp(new_curvature, -MAX_CURVATURE, MAX_CURVATURE) + return float(new_curvature), limited_accel or limited_max_curv - if not car_recognized: - if fw_seen: - event = EventName.startupNoCar + +def get_accel_from_plan(speeds, accels, t_idxs, action_t=DT_MDL, vEgoStopping=0.3): + if len(speeds) == len(t_idxs): + v_now = speeds[0] + a_now = accels[0] + if action_t < MIN_STABLE_DELAY: + v_target = v_now + (action_t / MIN_STABLE_DELAY) * (np.interp(MIN_STABLE_DELAY, t_idxs, speeds) - v_now) else: - event = EventName.startupNoFw - elif car_recognized and not controller_available: - event = EventName.startupNoControl - return event + v_target = np.interp(action_t, t_idxs, speeds) + a_target = 2 * (v_target - v_now) / (action_t) - a_now + else: + v_now = 0.0 + v_target = 0.0 + a_target = 0.0 + should_stop = (v_now < vEgoStopping and a_target < 0.1) + return a_target, should_stop + +def curv_from_psis(psi_target, psi_rate, vego, action_t): + vego = np.clip(vego, MIN_SPEED, np.inf) + curv_from_psi = psi_target / (vego * action_t) + return 2*curv_from_psi - psi_rate / vego + +def get_curvature_from_plan(yaws, yaw_rates, t_idxs, vego, action_t): + if action_t < MIN_STABLE_DELAY: + psi_target = (action_t / MIN_STABLE_DELAY) * np.interp(MIN_STABLE_DELAY, t_idxs, yaws) + else: + psi_target = np.interp(action_t, t_idxs, yaws) + psi_rate = yaw_rates[0] + return curv_from_psis(psi_target, psi_rate, vego, action_t) diff --git a/selfdrive/controls/lib/driver_lateral_handoff.py b/selfdrive/controls/lib/driver_lateral_handoff.py new file mode 100644 index 00000000000000..cf33be6c3ce9f7 --- /dev/null +++ b/selfdrive/controls/lib/driver_lateral_handoff.py @@ -0,0 +1,1139 @@ +"""Pre-AP driver-wheel temporary lateral handoff. + +Default On (NAPDriverLatHandoff=1). Settings → NAP can turn it Off. + +Product: yield = *free the EPS*, not follow-the-rim angle control. +A light purposeful push with a hand on the rim should let the wheel +go. Gravel spike trains / wind / road-crown must not free-yield. + +On-car (#79): entry still required a 0.70 Nm / 140 ms fight, *and* +after yield OP kept latActive=True with apply_lat_authority(0) +commanding measured angle (DAS_steeringControlType still 1). That is +closed-loop follow-the-rim — Justin could nudge off-path but the car +kept holding/steering. Wrestling was full authority until the debounce +finished, then more holding after "yield." + +Yield now reuses the blinker lat-pause EPS release: latActive false → +carcontroller sends DAS_steeringControlType=0. Hands stay detected +via EPAS_handsOnLevel (and a light probe). Resume is still pin-to- +wheel while lat is down, then a fast taper back onto the model. +Hands resting on the rim do not keep lateral yielded. + +Driver-turn blinker (soft-lat On): lamp latch must not strip lat. +Keep control if we still have it. Soft-lat may still yield on a +driver push. While the driver-turn blinker is latched, do not +re-enable (stay yielded / do not finish a take-back blend). After +it clears, land in yield and use the normal 0.15 s hands-off +confirm + 1 s blend — no dedicated blinker rising-edge blend. +The same re-enable inhibit also applies whenever v_ego is strictly +below 10 mph (LAT_REENABLE_MIN_V_EGO_MPH), blinker or not. Above +10 mph with the blinker off, resume is unchanged. Blinker-on still +blocks take-back at any speed. Soft-lat Off keeps the stock +lamp-latch lat pause so turns still free the wheel. + +Intent (Pre-AP EPAS) — required to *enter* yield: + compensated torque tau = steeringTorque − learned offset + same sign, |tau| >= 0.9 Nm for 150 ms, or >= 1.4 Nm for 80 ms + A sign flip restarts the count. EPAS_handsOnLevel is not required + (it lags the torsion bar). + The 2.0 Nm / 80 ms steeringPressed early-yield is the same fast + counter, so a firm grab lands on yielded lateral. + Anything lighter or shorter: OP keeps steering. Resting hands + (about 0.15–0.35 Nm on this car) do not yield. + +History (on-car): + #71 0.50 Nm / 80 ms — gravel / rumble false-yield (no hands gate) + #73 0.85 Nm / 250 ms + 0.25 s quiet — rumble-safe, too slow/firm + #74 0.70 Nm / 140 ms, quiet wait 0 — mid-dodge torsion dip blended + #75 stay yielded while handsOnLevel >= 1; blend after hands off + #78 entry = torsion + aligned rate + hands; blocked isometric fight + #79 entry = 0.70 Nm / 140 ms + hands; still follow-measured hold + #80 entry = ~0.55 Nm / 90 ms + hands; yield frees the EPS + now hands-off confirm 0.15 s before the 1 s blend (crossover gap) + +Signal (Pre-AP EPAS_sysStatus 0x370, tesla_preap.dbc): + EPAS_torsionBarTorque — continuous, Nm, factor 0.01, offset −20.5 + EPAS_handsOnLevel — discrete 0/1/2/3 + StW_AnglHP_Spd — steering-angle rate, deg/s, factor 0.5 + CS.steeringRateDeg is negated (same as torsion) + +Existing software / safety (unchanged): + steeringPressed = |torsion| > STEER_THRESHOLD (1.0 Nm), 5-frame debounce + steerOverride = EventName from steeringPressed (OVERRIDE_LATERAL) + steeringDisengage / panda PREAP_HANDS_ON_DISENGAGE_LEVEL = handsOnLevel >= 2 + +Push to take, release to give back. Entry is the compensated torque +above (0.9 Nm / 150 ms or 1.4 Nm / 80 ms). Give-back ignores hands-on +level. Any one of these starts the taper, unless a blinker or speed +below 10 mph is inhibiting, or the post-turn wheel gate is holding: + R1 |tau| < 0.40 Nm for 0.30 s (hands may stay on the rim) + R2 |model curvature − actual| < 0.0008 1/m for 0.5 s, with + |tau| < 1.2 Nm and not rising + R3 |tau| < 0.8 Nm for 2.5 s +The taper ramps authority 0 → 1 at +clamp(0.002 / |model k − actual k|, 1.0, 2.0) per second, starting +from the wheel. That finishes inside BLEND_TIME_S (1.0 s), which is +what GRACE_S / the panda 1.2 s window already cover. The shortest +automatic yield is RELEASE_HOLD_S (0.30 s), above GAP. A stalk pull +forces the taper (no chime) once that minimum has elapsed. +Re-yield during the taper only on a deliberate push: |tau| rises +0.6 Nm above its down-tracking taper-start baseline for 150 ms, or +tau opposes OP's wheel motion at >= 0.9 Nm for 150 ms. Torque in +OP's direction never cancels the taper. +There is no tug-of-war latch. Two or more re-yields inside 15 s make +the next taper use the 1.0/s floor. That softener clears after 10 s +of full lateral and never blocks a return. +tau subtracts one of two resting offsets (OP steering vs wheel free), +each an EMA with a 3 s time constant, learned at hands level 0, +|angle| < 12 deg, |raw| < 0.35 Nm, and wheel-still from +steeringAngleDeg (steeringRateDeg is SNA on this car). Clamped ±0.5 Nm. + +Emergency / hard brake (see emergency_brake() and docs-nap/engagement.md): + Pre-AP has no analog brake pressure on parsed buses — only digital + Applied (DI_brakePedal / BrakeMessage.driverBrakeStatus). Light brake + is that digital bit and still uses the existing sticky-MAX silent long + pause + one SET. Emergency is digital Applied AND measured aEgo at or + below EMERGENCY_DECEL_MPS2 (−3.5 m/s², ~0.36 g) for + EMERGENCY_DECEL_FRAMES (80 ms), at vEgo >= 1 m/s, while yielded / + blending / within YIELD_EMERGENCY_WINDOW_S of yield entry. + That cannot come from NAP long (planner comfort Accel-5 is −0.80 m/s²; + pre-AP clip is −1.5 m/s²). Full cancel is a flag here; card tears down + the session (cruiseEnabled) so pcmDisable / disengage chime fire. + This module does not call the silent long-pause path. + +While yielded, latActive is false (EPS released) and controlsd pins +desired_curvature to measured so resume clips from the wheel. A +driver-turn blinker is not a lat-down by itself when soft-lat is On: +this module treats it as a re-enable inhibit and, on the falling +edge after a yield / lat-down, enters yield so the normal resume +owns the take-back. v_ego below 10 mph uses that same inhibit +(OR, not a parallel path). Soft-lat Off still uses BlinkerLateralHold +to clear latActive on lamp latch. + +INFERENCE CONTRACT (lateral yield is inferred, never announced): + Panda and the card decide "OP has yielded lateral" (a wheel yank is a + driver maneuver, not a cancel) from the 0x488 DAS_steeringControlType=1 + send history alone: opendbc preap/lat_yield.py and + safety/modes/tesla_preap_latyield.h. That inference assumes, about THIS + module and controlsd: + * latActive (hence type 1) is False for the whole yield, and True when + OP steers, including the take-back blend at authority < 1; + * a yield lasts at least HANDS_OFF_CONFIRM_S before the blend starts + (the automatic release is RELEASE_HOLD_S, which is longer); + * the blend lasts at most BLEND_TIME_S and the re-arm grace covers it. + ANY change to yield / blend / confirm timing, to what makes latActive + false (new release path, inhibit, pause) or true (new early re-arm), or + to what authority does MUST update the inference windows and the panda + header. selfdrive/controls/lib/tests/test_lat_yield_inference_guard.py + fails when BLEND_TIME_S / HANDS_OFF_CONFIRM_S and the lat_yield windows + diverge; fix lat_yield.py + tesla_preap_latyield.h first, then the pins. + +WHEEL-RESUME GATE (rapid back-and-forth turns). A driver who lets the wheel +uncoil through light / open hands (roundabout, switchback, parking lot) has +handsOnLevel 0 while the rim is still far from straight. The hands-off +confirm used to start the 1 s take-back blend there, so OP grabbed lateral +mid-uncoil and fought the next turn. Now, once the wheel angle since the +yield began has exceeded WHEEL_GATE_ARM_DEG, neither resume path may start +the blend until |angle| <= WHEEL_RESUME_STRAIGHT_DEG (named, 10-15 deg) for +WHEEL_STRAIGHT_DWELL_S (a swing through centre into the next turn is not +"straight"). +Speed does not matter (lots, and a 10 mph crossing with the wheel at lock). +The yield simply lasts longer (latActive stays false the whole time), which +the inference contract allows (only a *minimum* yield length is assumed). +A light hand on the rim does not reset the gate. Torque back above the +release band does (the driver is still in the maneuver). Safety valve: +after WHEEL_GATE_MAX_HOLD_S (3 s) of ready-but-not-straight hold the gate +lets go so a wheel that never centres cannot leave lateral off forever. +steering_angle_deg=None (not wired / old callers) disables the gate. +ALC / lane-change turn / disengage reset the whole latch (gate included). + +Early yield (steeringPressed, no hands gate): EPAS_handsOnLevel lags the +torsion bar, so a firm push can reach hands >= 2 before the hands-gated +soft yield above has fired. EARLY_YIELD_FRAMES consecutive steeringPressed +frames of same-sign torque >= EARLY_YIELD_NM yield without the hands gate, +so the wheel input lands on a yielded lateral (B) rather than a full one (A). +Tuned conservatively against Oct 1-3 qlogs: 1 Nm / 50 ms false-yielded on +road chatter; a true first-contact yank (<= 0.2 s to level 3) still reaches +level 3 on full lateral and cancels by design. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + +from cereal import log +from opendbc.car.tesla.preap.lat_yield import GRACE_DELAY_S, immediate_lat_yield +from opendbc.car.tesla.values import STEER_THRESHOLD +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + tipped_lane_change_driver_release, +) + +# Match controlsd / card (openpilot.common.realtime.DT_CTRL). +DT_CTRL = 0.01 + +State = log.SelfdriveState.OpenpilotState + +# --- thresholds (from real Pre-AP STEER_THRESHOLD = 1.0 Nm) --- +# Gentler than #79's 0.70 / 140 ms so a light purposeful push yields +# before the driver wrestles. Hands-on is required so gravel / crown +# with hands off or resting do not count. Rate is not an entry gate. +SOFT_YIELD_TRIGGER_NM = 0.55 * float(STEER_THRESHOLD) # 0.55 Nm +SOFT_YIELD_RELEASE_NM = 0.40 * float(STEER_THRESHOLD) # 0.40 Nm, wider gap + +# Consecutive *push* frames (torsion + hands). Gaps reset. +# 90 ms at the 0.55 floor; fewer near STEER_THRESHOLD so soft yield +# wins before hands-on >= 2 / steeringPressed. Fast floor stays above +# the 5-frame gravel-spike bursts used in tests (~50 ms). +SOFT_YIELD_DEBOUNCE_FRAMES = 9 # 90 ms at 100 Hz (0.55 Nm) +SOFT_YIELD_FAST_DEBOUNCE_FRAMES = 6 # 60 ms as |torsion| → 1.0 Nm +SOFT_YIELD_RELEASE_FRAMES = 8 # 80 ms below release before clearing latch + +# Early yield on steeringPressed, no EPAS hands gate (see module docstring). +# Same-sign torsion at/above EARLY_YIELD_NM while steeringPressed for +# EARLY_YIELD_FRAMES consecutive frames (100 Hz) enters the same yield. +EARLY_YIELD_NM = 2.0 +EARLY_YIELD_FRAMES = 8 # 80 ms + +# Rate agreement. Pre-AP CS.steeringRateDeg is −StW_AnglHP_Spd (deg/s). +# SNA decodes to ~4095 deg/s. Kept as a *weak low-torsion* wind filter +# only — never required to enter yield on a firm sustained push. +# Historical 25 deg/s gate was a resume quiet check (unused since #75). +STEER_RATE_QUIET_DEG_S = 25.0 +RATE_INTENT_MIN_DEG_S = 10.0 +RATE_SNA_ABS_DEG_S = 400.0 + +# High |desired−measured| curvature with torsion *below* the yield +# trigger is wind / crown, not a driver dodge. High torsion is intent. +DISTURBANCE_CURVATURE_ERR = 0.0025 + +# --- emergency / hard brake (digital Applied + measured decel) --- +# Light brake = digital Applied only → sticky-MAX silent long pause. +# Emergency cannot use pressure (Pre-AP DBC has none on parsed buses). +EMERGENCY_DECEL_MPS2 = -3.5 +EMERGENCY_DECEL_FRAMES = 8 # 80 ms; reject pothole aEgo spikes +EMERGENCY_MIN_V_EGO = 1.0 # m/s; standstill KF chatter +YIELD_EMERGENCY_WINDOW_S = 2.0 + +# Soft-lat re-enable inhibit floor (strictly below). Same gate as a +# driver-turn blinker latch: keep control if we still have it; already +# yielded / blending stay yielded; do not finish a take-back blend. +# Blinker-on still inhibits at any speed. Soft-lat Off is identity +# (BlinkerLateralHold still pauses lat on lamp latch only). Long / +# ALC tip-hold / FCW / AEB are not this path. +LAT_REENABLE_MIN_V_EGO_MPH = 10.0 +LAT_REENABLE_MIN_V_EGO = LAT_REENABLE_MIN_V_EGO_MPH * CV.MPH_TO_MS + +# --- wheel-resume gate (see WHEEL-RESUME GATE in the module docstring) --- +# No resume while |wheel| is above this after a big-angle handoff. 10-15 deg. +WHEEL_RESUME_STRAIGHT_DEG = 12.0 +# Peak |wheel| since the yield began that arms the gate (a real turn, not a +# highway nudge). Below this the resume is unchanged. +WHEEL_GATE_ARM_DEG = 30.0 +# The wheel must stay within WHEEL_RESUME_STRAIGHT_DEG this long (not just +# sweep through centre between two turns) before the blend may start. +WHEEL_STRAIGHT_DWELL_S = 0.15 +# Ready-to-return time the gate may hold the resume before it lets go. +WHEEL_GATE_MAX_HOLD_S = 3.0 + +# --- timing / UI --- +QUIET_WAIT_S = 0.0 +HANDS_ON_HOLD_LEVEL = 1 +# After hands are fully off: ~0.15 s before the 1 s blend. +# Not the old 0.08 s confirm (crossover snatch) and not torsion-quiet. +# Shorter than the 0.25 s confirm — Justin wanted less than a quarter second. +HANDS_OFF_CONFIRM_S = 0.15 +BLEND_TIME_S = 1.0 +UI_LATERAL_RETURN_AUTHORITY = 0.70 # do not show lat-engaged below this + +# Yield drops latActive so the EPS is free (DAS_steeringControlType=0). +# apply_steer_angle_limits_vm then snaps apply_angle to measured — that +# is the stock inactive path, same as blinker pause. Resume slews from +# that pin via the 1 s blend + Tesla VM limiter. +YIELD_AUTHORITY_TIME_S = 0.0 +# CarControllerParams.ANGLE_LIMITS.MAX_ANGLE_RATE (tesla/values.py) +TESLA_MAX_ANGLE_RATE_DEG_PER_20MS = 5.0 + +# smoothstep(t) = t^2 (3-2t); max |ds/dt| on t in [0,1] is 1.5. +# With BLEND_TIME_S == 1 that is also the max authority rise per second. +SMOOTHSTEP_MAX_SLOPE = 1.5 +BLEND_AUTHORITY_RATE_PER_S = SMOOTHSTEP_MAX_SLOPE / BLEND_TIME_S + +# Push to take. Same-sign compensated torque. Hands level is not required. +YIELD_SOFT_NM = 0.9 +YIELD_SOFT_S = 0.15 +YIELD_FIRM_NM = 1.4 +# 80 ms, same counter as EARLY_YIELD_FRAMES. +YIELD_FIRM_FRAMES = EARLY_YIELD_FRAMES + +# Release to give back. Hands-on level is ignored. +RELEASE_TAU_NM = 0.40 +RELEASE_HOLD_S = 0.30 # R1. Also the shortest yield the inference allows. +AGREE_CURVATURE_ERR = 0.0008 # 1/m, R2 +AGREE_HOLD_S = 0.50 +AGREE_TAU_NM = 1.2 +AGREE_RISE_EPS_NM = 0.02 +LIGHT_HOLD_TAU_NM = 0.8 # R3 +LIGHT_HOLD_S = 2.5 + +# Fast taper. At BLEND_TIME_S == 1 these are 1.0 and 2.0 per second, so the +# ramp finishes inside the grace the panda / card already assume. +TAPER_RATE_MIN_PER_S = 1.0 +TAPER_RATE_MAX_PER_S = 2.0 +TAPER_CURVATURE_SCALE = 0.002 +TAPER_RISE_NM = 0.6 +TAPER_RISE_S = 0.15 +TAPER_OPPOSE_NM = 0.9 +TAPER_OPPOSE_S = 0.15 + +# Softener: never blocks a return. Two re-yields inside the window make the +# next taper use the slow floor. Clears after this long at full lateral. +REYIELD_COUNT = 2 +REYIELD_WINDOW_S = 15.0 +FULL_LATERAL_RESET_S = 10.0 + +# Two resting offsets (OP steering vs wheel free). steeringRateDeg is SNA +# on this car, so wheel-still is ΔsteeringAngleDeg/Δt. +REST_BIAS_TAU_S = 3.0 +REST_BIAS_CLAMP_NM = 0.5 +REST_BIAS_MAX_RATE_DEG_S = 5.0 +REST_BIAS_MAX_ANGLE_DEG = WHEEL_RESUME_STRAIGHT_DEG # |angle| < 12 deg +REST_BIAS_MAX_RAW_NM = 0.35 + +PREAP_FINGERPRINT = "TESLA_MODEL_S_PREAP" +# Settings → NAP. Default On. Turn Off if gravel / wind still false-yields. +PARAM_DRIVER_LAT_HANDOFF = "NAPDriverLatHandoff" + + +def handoff_enabled(*, fingerprint: str, param_on: bool) -> bool: + """Pre-AP and Settings toggle (param defaults On).""" + return bool(param_on) and fingerprint == PREAP_FINGERPRINT + + +def lat_reenable_inhibited(*, blinker_paused: bool, v_ego: float) -> bool: + """True when soft-lat must not take the wheel back. + + Driver-turn blinker latch (any speed) OR v_ego strictly below 10 mph. + Keep control if we still have it; already yielded / blending stay + yielded. Falling edge (blinker clear or speed crosses 10 mph) lands + in yield so the normal 0.15 s confirm + 1 s blend owns resume. + """ + return bool(blinker_paused) or float(v_ego) < LAT_REENABLE_MIN_V_EGO + + +def hands_still_on(hands_on_level: int) -> bool: + """True while EPAS still sees a hand on the rim (level 1+).""" + return int(hands_on_level or 0) >= HANDS_ON_HOLD_LEVEL + + +def cs_hands_on_level(CS) -> int: + """EPAS_handsOnLevel 0/1/2/3 from cereal CarState. + + Prefer CS.handsOnLevel when the schema has it. Pre-AP card also stashes + the discrete level on steeringTorqueEps (unused on this angle car) so + controlsd works without an opendbc cereal bump. steeringDisengage is + hands >= 2. + """ + vals: list[int] = [] + if hasattr(CS, 'handsOnLevel'): + try: + vals.append(int(CS.handsOnLevel or 0)) + except (TypeError, ValueError): + pass + try: + ev = int(round(float(getattr(CS, 'steeringTorqueEps', 0.0) or 0.0))) + if 0 <= ev <= 3: + vals.append(ev) + except (TypeError, ValueError): + pass + if getattr(CS, 'steeringDisengage', False): + vals.append(2) + return max(vals) if vals else 0 + + +def cs_real_brake_pressed(CS) -> bool: + """Digital driver brake without using CS.brakePressed. + + Pre-AP forces brakePressed=False so generic OP brake-to-disengage never + fires. Card publishes the Applied flag on CS.brake (1.0 / 0.0). + """ + if bool(getattr(CS, 'realBrakePressed', False)): + return True + try: + return float(getattr(CS, 'brake', 0.0) or 0.0) >= 0.5 + except (TypeError, ValueError): + return False + + +def torque_rate_aligned(torque_nm: float, rate_deg: float) -> bool: + """True when the wheel is turning in the torsion direction. + + Not an entry gate. Used only as a weak low-torsion wind filter — + aligned rate below the yield trigger never counts as intent, and a + firm push yields even when this is False (isometric fight / SNA). + """ + torque = float(torque_nm) + rate = float(rate_deg) + if not np.isfinite(torque) or not np.isfinite(rate): + return False + if abs(rate) >= RATE_SNA_ABS_DEG_S: + return False + if abs(rate) < RATE_INTENT_MIN_DEG_S: + return False + if abs(torque) < SOFT_YIELD_TRIGGER_NM: + return False + return (torque * rate) > 0.0 + + +def required_press_frames(torque_nm: float) -> int: + """Consecutive 100 Hz frames of this |tau| needed to enter yield. + + 150 ms at 0.9 Nm, 80 ms at 1.4 Nm and above. Below 0.9 Nm this returns + the old debounce length so a caller can spin that many frames and still + not yield (resting hands, road noise). + """ + mag = abs(float(torque_nm)) + if mag + 1e-12 >= YIELD_FIRM_NM: + return YIELD_FIRM_FRAMES + if mag + 1e-12 >= YIELD_SOFT_NM: + return int(round(YIELD_SOFT_S / DT_CTRL)) + return SOFT_YIELD_DEBOUNCE_FRAMES + + +def is_disturbance(*, torque_nm: float, rate_deg: float, + tracking_error: float) -> bool: + """Wind / crown: high path error while torsion is below the yield trigger. + + High torsion is driver intent even if tracking error is large (leaving + the path) and even if steer rate is low (isometric fight). Rate is a + weak filter only at low torsion: aligned rate below the trigger never + clears this and never promotes low torsion to a yield. + """ + if abs(float(tracking_error)) < DISTURBANCE_CURVATURE_ERR: + return False + if abs(float(torque_nm)) >= SOFT_YIELD_TRIGGER_NM: + return False + # Low torsion + high error. Rate is unused here on purpose: aligned + # rate below the trigger must not clear a disturbance (#78 required + # alignment to *not* be a disturbance) and cannot promote this to yield. + _ = rate_deg + return True + + +def emergency_brake(*, brake_applied: bool, a_ego: float, v_ego: float, + decel_frames: int) -> bool: + """Hard brake: digital Applied + sustained emergency-level aEgo. + + Not light brake. Not OP map-track decel. Not a lone aEgo pothole spike. + """ + if not brake_applied: + return False + if float(v_ego) < EMERGENCY_MIN_V_EGO: + return False + if float(a_ego) > EMERGENCY_DECEL_MPS2: + return False + return int(decel_frames) >= EMERGENCY_DECEL_FRAMES + + +def emergency_cancel_active(*, yielded: bool, blending: bool, + yield_age_s: float | None, + hard_brake: bool) -> bool: + """Full OP cancel when hard-braking in the soft-yield takeover window.""" + if not hard_brake: + return False + if yielded or blending: + return True + if yield_age_s is None: + return False + return 0.0 <= float(yield_age_s) <= YIELD_EMERGENCY_WINDOW_S + + +def smoothstep(t: float) -> float: + t = float(np.clip(t, 0.0, 1.0)) + return t * t * (3.0 - 2.0 * t) + + +def taper_rate_per_s(curv_err: float | None, *, soften: bool = False) -> float: + """Authority rise per second for the take-back taper. + + clamp(0.002 / |model k − actual k|, 1, 2) when BLEND_TIME_S is 1. + Both ends scale with 1/BLEND_TIME_S so a longer blend still outlasts + the inference grace (the guard's tripwire). Unknown curvature, or the + re-yield softener, uses the slow floor. The ramp still finishes in at + most BLEND_TIME_S. + """ + floor = TAPER_RATE_MIN_PER_S / BLEND_TIME_S + ceiling = TAPER_RATE_MAX_PER_S / BLEND_TIME_S + if soften or curv_err is None: + return float(floor) + try: + err = abs(float(curv_err)) + except (TypeError, ValueError): + return float(floor) + if not np.isfinite(err): + return float(floor) + raw = ceiling if err < 1e-9 else TAPER_CURVATURE_SCALE / err + return float(min(ceiling, max(floor, raw))) + + +def limit_authority_step(prev: float, target: float, dt: float, rate_per_s: float) -> float: + """Rise toward ``target`` no faster than ``rate_per_s``. Falls immediately. + + The take-back taper passes taper_rate_per_s. A rate of 1/BLEND_TIME_S + reaches 1 inside the grace window; agreement is allowed to be faster. + """ + prev_a = float(np.clip(prev, 0.0, 1.0)) + target_a = float(np.clip(target, 0.0, 1.0)) + if target_a <= prev_a: + return target_a + return float(min(target_a, prev_a + max(0.0, float(rate_per_s)) * max(0.0, float(dt)))) + + +def lat_active_after_handoff(lat_would_be_active: bool, yielded: bool) -> bool: + """EPS request bit after blinker / standstill / soft-yield. + + INFERENCE CONTRACT: this bit becomes DAS_steeringControlType (1 = OP is + steering) and is the ONLY thing panda / the card use to infer "lateral + yielded". Any new reason for latActive to go false or come back true, + or any change to handoff / blend timing, must update opendbc + preap/lat_yield.py + tesla_preap_latyield.h (see the module docstring + and test_lat_yield_inference_guard.py). + + Blinker pause and standstill already cleared lat_would_be_active. + Soft yield does the same: latActive false so Pre-AP carcontroller + sends DAS_steeringControlType=0 and apply_steer_angle_limits_vm + tracks the wheel without commanding it. That is free-wheel, not + follow-measured angle control with latActive still true. + """ + return bool(lat_would_be_active) and not bool(yielded) + + +def apply_lat_authority(authority: float, torque: float, desired_angle: float, + measured_angle: float, desired_curvature: float, + measured_curvature: float) -> tuple[float, float, float]: + """Scale lateral actuator authority. Resume blend only; not the yield. + + Yield frees the EPS (latActive false). This blend runs when lat is + back and authority < 1. Identity at authority=1 (same as skipping). + Do not write blended curvature back into the planner state. + """ + a = float(np.clip(authority, 0.0, 1.0)) + return ( + float(torque) * a, + a * float(desired_angle) + (1.0 - a) * float(measured_angle), + a * float(desired_curvature) + (1.0 - a) * float(measured_curvature), + ) + + +def handoff_new_desired_curvature(*, yielded: bool, lat_active: bool, + model_curvature: float, + measured_curvature: float) -> float: + """clip_curvature target. Pin to the wheel while lat is down. + + Yield and blinker pause both clear latActive (EPS released). Pin so + resume clips from the wheel, not a model path that ran ahead. Same + target as stock latActive=False; snap the pin in controlsd. + """ + if yielded or not lat_active: + return float(measured_curvature) + return float(model_curvature) + + +def pin_desired_curvature_to_measured(yielded: bool, lat_active: bool = True) -> bool: + """True: assign desired_curvature = measured, skip clip_curvature. + + Pin while soft-yielded *and* while latActive is false (blinker pause / + standstill / fault). Blinker pause used to only clip toward measured, + so a fast lot turn left desired lagged; resume then slewed from that + lag onto a bad model path (grass). Snap-pin matches stock inactive. + """ + return bool(yielded) or not bool(lat_active) + + +def hud_engaged_status(*, enabled: bool, op_state, lat_active: bool, + lat_handoff_paused: bool) -> str: + """HUD chrome while the OP session may still be enabled. + + 'override' is the stable paused / driver-control indication. 'engaged' + is the normal lateral-on indication and must not return below 70% + authority (the caller latches lat_handoff_paused). No sounds. + """ + if lat_handoff_paused and enabled: + return "override" + if op_state in (State.preEnabled, State.overriding): + if op_state == State.overriding and lat_active: + return "engaged" + return "override" + return "engaged" if enabled else "disengaged" + + +@dataclass(frozen=True) +class HandoffOutput: + authority: float + ui_paused: bool + yielded: bool + blending: bool + emergency_cancel: bool = False + + +class DriverLateralHandoff: + """Process-local latch: push to take the wheel, release to give it back.""" + + def __init__(self, enabled: bool = True): + # Product default On. controlsd still requires Pre-AP + param + # (NAPDriverLatHandoff defaults true). Toggle Off to disable. + self.enabled = bool(enabled) + # Survive _reset so a disengage does not forget the sensor offsets. + self._rest_op = 0.0 + self._rest_free = 0.0 + self._applied_bias = 0.0 + self._prev_angle: float | None = None + self._reset() + + @property + def rest_bias(self) -> float: + """Offset currently subtracted from steeringTorque (the live tau bias).""" + return float(self._applied_bias) + + @property + def rest_bias_op(self) -> float: + return float(self._rest_op) + + @property + def rest_bias_free(self) -> float: + return float(self._rest_free) + + def _reset(self): + self.authority = 1.0 + self.ui_paused = False + self._yielded = False + self._blending = False + self._quiet_s = 0.0 + self._blend_s = 0.0 + self._press_cnt = 0 + self._release_cnt = 0 + self._early_cnt = 0 + self._early_sign = 0 + self._soft_s = 0.0 + self._soft_sign = 0 + self._pressed = False + self._blinker_was_paused = False + self._hands_off_s = 0.0 + self._decel_cnt = 0 + self._yield_age_s: float | None = None + self._peak_angle_deg = 0.0 + self._gate_hold_s = 0.0 + self._straight_s = 0.0 + self._clock_s = 0.0 + self._r1_s = 0.0 + self._r2_s = 0.0 + self._r3_s = 0.0 + self._r2_base = 0.0 + self._taper_base = 0.0 + self._taper_soften = False + self._rise_s = 0.0 + self._oppose_s = 0.0 + self._soften = False + self._reyields: list[float] = [] + self._full_s = 0.0 + self._pull_pending = False + self._last_driver_hold = False + self._last_inhibited = False + + def reset(self): + self._reset() + + def driver_resume_request(self) -> None: + """In-session stalk pull: force the take-back taper. No chime. + + Clears the re-yield softener. A blinker or sub-10 mph inhibit still + holds the yield; the pull is remembered and applied when that clears, + once the yield has lasted RELEASE_HOLD_S. Hands on the rim do not block it. + """ + self._soften = False + self._reyields.clear() + self._taper_soften = False + if not self.enabled or not (self._yielded or self._blending): + self._pull_pending = False + return + self._pull_pending = True + + def _wheel_rate_deg_s(self, steering_angle_deg, dt: float) -> float | None: + """|Δangle/Δt|. steeringRateDeg is SNA on this car and is not used.""" + if steering_angle_deg is None: + return None + try: + angle = float(steering_angle_deg) + except (TypeError, ValueError): + return None + if not np.isfinite(angle): + self._prev_angle = None + return None + prev = self._prev_angle + self._prev_angle = angle + if prev is None or float(dt) <= 1e-6: + return None + return abs(angle - prev) / float(dt) + + def _learn_rest(self, torque, hands_on_level, steering_angle_deg, dt: float, *, + engaged: bool, lat_would_be_active: bool) -> None: + """EMA of hands-off, straight, wheel-still torsion. Two offsets.""" + if int(hands_on_level or 0) != 0: + return + try: + tq = float(torque) + except (TypeError, ValueError): + return + if not np.isfinite(tq) or abs(tq) >= REST_BIAS_MAX_RAW_NM: + return + rate = self._wheel_rate_deg_s(steering_angle_deg, dt) + if rate is None or rate >= REST_BIAS_MAX_RATE_DEG_S: + return + try: + if abs(float(steering_angle_deg)) >= REST_BIAS_MAX_ANGLE_DEG: + return + except (TypeError, ValueError): + return + if self._blending: + return + wheel_free = bool(self._yielded) or (not engaged) or (not lat_would_be_active) + op_steering = bool(engaged and lat_would_be_active and not self._yielded) + if wheel_free: + slot = "_rest_free" + elif op_steering: + slot = "_rest_op" + else: + return + alpha = 1.0 - float(np.exp(-max(float(dt), 0.0) / REST_BIAS_TAU_S)) + cur = float(getattr(self, slot)) + cur += alpha * (tq - cur) + cur = float(min(REST_BIAS_CLAMP_NM, max(-REST_BIAS_CLAMP_NM, cur))) + setattr(self, slot, cur) + + def _compensated_torque(self, steering_torque: float, *, use_free: bool) -> float: + try: + tq = float(steering_torque) + except (TypeError, ValueError): + tq = 0.0 + if not np.isfinite(tq): + tq = 0.0 + # Free-wheel offset while the EPS is released, OP is disengaged, or + # the take-back taper is in progress, so tau does not jump at the start. + if use_free or self._yielded or self._blending: + bias = self._rest_free + else: + bias = self._rest_op + self._applied_bias = float(bias) + return tq - bias + + def _update_soft(self, torque_nm: float, dt: float) -> bool: + """Same-sign |tau| >= 0.9 Nm for 150 ms. A sign flip or a gap resets.""" + mag = abs(float(torque_nm)) + sign = 1 if float(torque_nm) > 0.0 else -1 if float(torque_nm) < 0.0 else 0 + if mag >= YIELD_SOFT_NM and sign != 0 and self._soft_sign in (0, sign): + self._soft_sign = sign + self._soft_s += max(float(dt), 0.0) + else: + self._soft_s = 0.0 + self._soft_sign = 0 + return self._soft_s + 1e-12 >= YIELD_SOFT_S + + def _update_early(self, torque_nm: float, steering_pressed: bool) -> bool: + """Same-sign fast torsion. 1.4 Nm / 80 ms, or 2.0 Nm with steeringPressed.""" + mag = abs(float(torque_nm)) + sign = 1 if float(torque_nm) > 0.0 else -1 + fast = mag >= YIELD_FIRM_NM or (bool(steering_pressed) and mag >= EARLY_YIELD_NM) + if fast and ( + self._early_cnt == 0 or sign == self._early_sign): + self._early_sign = sign + self._early_cnt = min(self._early_cnt + 1, EARLY_YIELD_FRAMES + 1) + else: + self._early_cnt = 0 + self._early_sign = 0 + return self._early_cnt >= EARLY_YIELD_FRAMES + + def _update_emergency(self, *, brake_applied: bool, a_ego: float, + v_ego: float, dt: float) -> bool: + hard = ( + bool(brake_applied) + and float(v_ego) >= EMERGENCY_MIN_V_EGO + and float(a_ego) <= EMERGENCY_DECEL_MPS2 + ) + if hard: + self._decel_cnt = min(self._decel_cnt + 1, EMERGENCY_DECEL_FRAMES + 1) + else: + self._decel_cnt = 0 + + if self._yielded or self._blending: + if self._yield_age_s is None: + self._yield_age_s = 0.0 + self._yield_age_s += dt + elif self._yield_age_s is not None: + self._yield_age_s += dt + if self._yield_age_s > YIELD_EMERGENCY_WINDOW_S: + self._yield_age_s = None + + return emergency_cancel_active( + yielded=self._yielded, + blending=self._blending, + yield_age_s=self._yield_age_s, + hard_brake=emergency_brake( + brake_applied=brake_applied, a_ego=a_ego, v_ego=v_ego, + decel_frames=self._decel_cnt), + ) + + def _set_ui_paused(self): + # Latch at 70%: never claim lateral is back at 1–69%. Falling through + # 70% (renewed input) pauses immediately. Rising crosses 70% once on + # the monotonic blend, so the latch does not chatter. + if self.authority >= UI_LATERAL_RETURN_AUTHORITY and not self._yielded: + self.ui_paused = False + else: + self.ui_paused = self._yielded or self._blending or ( + self.authority < UI_LATERAL_RETURN_AUTHORITY) + + def _note_angle(self, steering_angle_deg: float | None): + """Track peak |wheel| while a yield / blend / lat-down is in play.""" + if steering_angle_deg is None: + return + a = abs(float(steering_angle_deg)) + if np.isfinite(a) and a > self._peak_angle_deg: + self._peak_angle_deg = a + + def _wheel_gate_holds(self, steering_angle_deg: float | None, dt: float) -> bool: + """True: do not start the take-back blend yet (wheel still uncoiling).""" + if steering_angle_deg is None: + return False + a = abs(float(steering_angle_deg)) + if not np.isfinite(a): + return False + if self._peak_angle_deg < WHEEL_GATE_ARM_DEG: + return False + self._gate_hold_s += dt + if self._gate_hold_s >= WHEEL_GATE_MAX_HOLD_S: + return False + if a <= WHEEL_RESUME_STRAIGHT_DEG: + self._straight_s += dt + return self._straight_s + 1e-12 < WHEEL_STRAIGHT_DWELL_S + self._straight_s = 0.0 + return True + + def _enter_yield(self): + self._yielded = True + self._blending = False + self._quiet_s = 0.0 + self._blend_s = 0.0 + self._hands_off_s = 0.0 + self._r1_s = 0.0 + self._r2_s = 0.0 + self._r3_s = 0.0 + self._rise_s = 0.0 + self._oppose_s = 0.0 + self._gate_hold_s = 0.0 + self._straight_s = 0.0 + self.authority = 0.0 + self.ui_paused = True + if self._yield_age_s is None: + self._yield_age_s = 0.0 + + def _rehold_yield(self): + """Stay yielded and reset the wheel-straight dwell, keeping give-back timers.""" + r1, r2, r3, base = self._r1_s, self._r2_s, self._r3_s, self._r2_base + self._enter_yield() + self._r1_s, self._r2_s, self._r3_s, self._r2_base = r1, r2, r3, base + + def _start_blend(self, tau: float): + self._taper_soften = bool(self._soften) + self._taper_base = abs(float(tau)) + self._rise_s = 0.0 + self._oppose_s = 0.0 + self._yielded = False + self._blending = True + self._blend_s = 0.0 + self._quiet_s = 0.0 + self._hands_off_s = 0.0 + self._r1_s = 0.0 + self._r2_s = 0.0 + self._r3_s = 0.0 + self._gate_hold_s = 0.0 + self._straight_s = 0.0 + self.authority = 0.0 + self.ui_paused = True + + def _min_yield_met(self, dt: float) -> bool: + age = 0.0 if self._yield_age_s is None else float(self._yield_age_s) + return age + max(float(dt), 0.0) + 1e-12 >= RELEASE_HOLD_S + + def _integrate_giveback(self, tau: float, curv_err: float, dt: float, + have_curv: bool) -> bool: + """Advance R1/R2/R3. True when any one has held long enough.""" + mag = abs(float(tau)) + step = max(float(dt), 0.0) + if mag < RELEASE_TAU_NM: + self._r1_s += step + else: + self._r1_s = 0.0 + if mag < LIGHT_HOLD_TAU_NM: + self._r3_s += step + else: + self._r3_s = 0.0 + if have_curv and float(curv_err) < AGREE_CURVATURE_ERR and mag < AGREE_TAU_NM: + if self._r2_s <= 0.0: + self._r2_base = mag + if mag <= self._r2_base + AGREE_RISE_EPS_NM: + self._r2_s += step + if mag < self._r2_base: + self._r2_base = mag + else: + self._r2_s = 0.0 + self._r2_base = mag + else: + self._r2_s = 0.0 + self._r2_base = mag + return ( + self._r1_s + 1e-12 >= RELEASE_HOLD_S + or self._r2_s + 1e-12 >= AGREE_HOLD_S + or self._r3_s + 1e-12 >= LIGHT_HOLD_S + ) + + def _note_reyield(self): + now = self._clock_s + self._reyields.append(now) + self._reyields = [t for t in self._reyields if now - t <= REYIELD_WINDOW_S] + if len(self._reyields) >= REYIELD_COUNT: + self._soften = True + + def _note_full(self, dt: float): + if (not self._yielded and not self._blending + and self.authority + 1e-9 >= 1.0): + self._full_s += max(float(dt), 0.0) + if self._full_s + 1e-12 >= FULL_LATERAL_RESET_S: + self._soften = False + self._reyields.clear() + else: + self._full_s = 0.0 + + def _taper_reyield(self, tau: float, model_k, measured_k, dt: float) -> bool: + """Deliberate push during the taper. Helping torque never cancels.""" + mag = abs(float(tau)) + if mag < self._taper_base: + self._taper_base = mag + helping = False + opposing = False + dk = None + if model_k is not None and measured_k is not None: + try: + dk = float(model_k) - float(measured_k) + except (TypeError, ValueError): + dk = None + if dk is None or not np.isfinite(dk): + dk = None + # Positive curvature and positive steeringTorque are both left. + if dk is not None and abs(dk) > 1e-6: + if float(tau) * dk > 0.0: + helping = True + elif float(tau) * dk < 0.0 and mag >= TAPER_OPPOSE_NM: + opposing = True + if helping: + self._rise_s = 0.0 + self._oppose_s = 0.0 + return False + if mag >= self._taper_base + TAPER_RISE_NM: + self._rise_s += max(float(dt), 0.0) + else: + self._rise_s = 0.0 + if opposing: + self._oppose_s += max(float(dt), 0.0) + else: + self._oppose_s = 0.0 + return ( + self._rise_s + 1e-12 >= TAPER_RISE_S + or self._oppose_s + 1e-12 >= TAPER_OPPOSE_S + ) + + def _curv_pair(self, model_curvature, measured_curvature): + if model_curvature is None or measured_curvature is None: + return False, 0.0 + try: + err = abs(float(model_curvature) - float(measured_curvature)) + except (TypeError, ValueError): + return False, 0.0 + if not np.isfinite(err): + return False, 0.0 + return True, err + + def _identity(self, *, emergency_cancel: bool = False) -> HandoffOutput: + return HandoffOutput(1.0, False, False, False, emergency_cancel) + + def update(self, *, engaged: bool, lat_would_be_active: bool, + steering_torque: float, steering_rate_deg: float, + alc_active: bool = False, blinker_paused: bool = False, + hands_on_level: int = 0, tracking_error: float = 0.0, + brake_applied: bool = False, a_ego: float = 0.0, + v_ego: float = 15.0, dt: float | None = None, + emergency_yank: bool = False, + lane_change_confirm: bool = False, + steering_pressed: bool = False, + steering_angle_deg: float | None = None, + model_curvature: float | None = None, + measured_curvature: float | None = None, + commanded_angle_deg: float | None = None, + roundabout_yield: bool = False, + undertrack: bool = False) -> HandoffOutput: + if dt is None: + dt = DT_CTRL + # steering_rate_deg is SNA (-4095.5) on this Pre-AP car. Wheel-still + # for the resting offset uses steeringAngleDeg. The argument stays so + # callers do not change. + _ = steering_rate_deg + + if not self.enabled: + self._reset() + return self._identity() + + self._learn_rest( + steering_torque, hands_on_level, steering_angle_deg, dt, + engaged=bool(engaged), lat_would_be_active=bool(lat_would_be_active)) + use_free = ( + bool(self._yielded or self._blending) + or (not engaged) + or (not lat_would_be_active)) + tq = self._compensated_torque(steering_torque, use_free=use_free) + + # lat_would_be_active is the *pre-yield* request (standstill / faults; + # and lamp-latch pause only when soft-lat is Off). Caller drops + # CC.latActive after this update when yielded so the EPS is free — + # do not feed that dropped bit back in or we reset to identity and + # forget we yielded. + # A same-direction confirm during tipped ALC is not a soft-yield. + # An emergency yank still frees the EPS immediately, same as a yield + # that today's takeover follows with a full disengage. + tipped = bool(alc_active or lane_change_confirm) + if tipped and tipped_lane_change_driver_release( + same_direction=bool(lane_change_confirm), emergency=bool(emergency_yank)): + self._enter_yield() + self._set_ui_paused() + return HandoffOutput(self.authority, self.ui_paused, True, False, False) + + # ALC wheel-nudge uses steeringPressed at 1 Nm and must not be softened. + # Full disengage (cancel / door / hands-on >= 2) clears engaged. + # blinker_paused is a latched *driver-turn* (not ALC tip/keep-alive). + # Soft-lat On: do not strip lat on lamp latch. Inhibit re-enable + # while the turn blinker is on *or* v_ego is below 10 mph; after + # that clears, enter yield so the release rules own resume. + # Soft-lat Off never reaches here (enabled=False → identity); + # BlinkerLateralHold still frees lat on lamp latch only. + if not engaged or alc_active or lane_change_confirm: + self._reset() + return self._identity() + inhibited = lat_reenable_inhibited(blinker_paused=blinker_paused, v_ego=v_ego) + if not lat_would_be_active: + remember = self._blinker_was_paused or inhibited + peak = self._peak_angle_deg if remember else 0.0 + self._reset() + self._blinker_was_paused = remember + self._peak_angle_deg = peak + return self._identity() + + self._clock_s += dt + have_curv, curv_err = self._curv_pair(model_curvature, measured_curvature) + # Push-to-take counters run only while OP has the wheel. A helping + # torque during the taper must not be pre-armed as the next yield. + if self._yielded or self._blending: + self._soft_s = 0.0 + self._soft_sign = 0 + self._early_cnt = 0 + self._early_sign = 0 + wants = False + else: + wants = self._update_soft(tq, dt) or self._update_early(tq, bool(steering_pressed)) + # Same-direction hands-on, or any steering input on a roundabout, + # yields on this frame. An opposite yank is not this path: the + # session-cancel edge still owns it. Raw torque, not the resting + # offset, so the sign matches panda. + if not wants and immediate_lat_yield( + hands=hands_on_level, torque_nm=steering_torque, + commanded_angle_deg=commanded_angle_deg, + measured_angle_deg=steering_angle_deg, + undertrack=bool(undertrack), roundabout=bool(roundabout_yield), + steering_pressed=bool(steering_pressed)): + wants = True + if (self._yielded or self._blending or self._blinker_was_paused or wants): + self._note_angle(steering_angle_deg) + + if inhibited: + # Keep control if we still have it. A driver push may still yield. + # Already yielded / blending / coming back from lat-down: stay + # yielded. Do not finish a take-back blend while the turn lamp + # is latched or speed is below 10 mph. + if self._yielded or self._blending or self._blinker_was_paused: + self._enter_yield() + self._blinker_was_paused = True + elif wants: + self._enter_yield() + self._blinker_was_paused = True + elif self._blinker_was_paused: + # Inhibit just cleared (blinker off and/or speed crossed 10 mph). + # Land in yield; R1/R2/R3 own the resume. A pending stalk pull + # skips the wheel gate once the minimum yield has elapsed. + self._blinker_was_paused = False + self._enter_yield() + pull_now = self._pull_pending and self._min_yield_met(dt) + ready = self._integrate_giveback(tq, curv_err, dt, have_curv) + if pull_now or (ready and not self._wheel_gate_holds(steering_angle_deg, dt)): + self._pull_pending = False + self._start_blend(tq) + elif not ready: + self._rehold_yield() + elif not self._yielded and not self._blending: + if wants: + self._enter_yield() + elif self._yielded: + pull_now = self._pull_pending and self._min_yield_met(dt) + ready = self._integrate_giveback(tq, curv_err, dt, have_curv) + if pull_now or (ready and not self._wheel_gate_holds(steering_angle_deg, dt)): + self._pull_pending = False + self._start_blend(tq) + elif not ready: + self._rehold_yield() + elif self._blending: + # Helping torque (OP's direction) never cancels. A deliberate push does. + if self._pull_pending: + self._pull_pending = False + if self._taper_reyield(tq, model_curvature, measured_curvature, dt): + self._note_reyield() + self._enter_yield() + else: + rate = taper_rate_per_s( + curv_err if have_curv else None, soften=self._taper_soften) + self._blend_s += dt + # full_control stays true for GRACE_DELAY_S after type-1 resumes. + # Hold authority at 0 through that hole, and compress the spec + # rate into the rest of BLEND_TIME_S so the ramp still ends + # inside the grace (no safety-window change). + # 50 Hz stamps can land up to one frame after the blend starts, + # so the grace-delay hole runs a little past GRACE_DELAY_S. + if self._blend_s + 1e-12 < GRACE_DELAY_S + 0.03: + self.authority = 0.0 + else: + usable = max(BLEND_TIME_S - (GRACE_DELAY_S + 0.03), DT_CTRL) + self.authority = limit_authority_step( + self.authority, 1.0, dt, rate * (BLEND_TIME_S / usable)) + if self.authority + 1e-9 >= 1.0: + self.authority = 1.0 + self._blending = False + self._quiet_s = 0.0 + self._peak_angle_deg = 0.0 + self._blend_s = 0.0 + + self._note_full(dt) + self._last_driver_hold = False + self._last_inhibited = bool(inhibited) + emergency = self._update_emergency( + brake_applied=brake_applied, a_ego=a_ego, v_ego=v_ego, dt=dt) + self._set_ui_paused() + return HandoffOutput( + self.authority, self.ui_paused, self._yielded, self._blending, + emergency) diff --git a/selfdrive/controls/lib/events.py b/selfdrive/controls/lib/events.py deleted file mode 100755 index d27f02794b351b..00000000000000 --- a/selfdrive/controls/lib/events.py +++ /dev/null @@ -1,995 +0,0 @@ -#!/usr/bin/env python3 -import bisect -import math -import os -from enum import IntEnum -from collections.abc import Callable - -from cereal import log, car -import cereal.messaging as messaging -from openpilot.common.conversions import Conversions as CV -from openpilot.common.git import get_short_branch -from openpilot.common.realtime import DT_CTRL -from openpilot.selfdrive.locationd.calibrationd import MIN_SPEED_FILTER - -AlertSize = log.SelfdriveState.AlertSize -AlertStatus = log.SelfdriveState.AlertStatus -VisualAlert = car.CarControl.HUDControl.VisualAlert -AudibleAlert = car.CarControl.HUDControl.AudibleAlert -EventName = car.OnroadEvent.EventName - - -# Alert priorities -class Priority(IntEnum): - LOWEST = 0 - LOWER = 1 - LOW = 2 - MID = 3 - HIGH = 4 - HIGHEST = 5 - - -# Event types -class ET: - ENABLE = 'enable' - PRE_ENABLE = 'preEnable' - OVERRIDE_LATERAL = 'overrideLateral' - OVERRIDE_LONGITUDINAL = 'overrideLongitudinal' - NO_ENTRY = 'noEntry' - WARNING = 'warning' - USER_DISABLE = 'userDisable' - SOFT_DISABLE = 'softDisable' - IMMEDIATE_DISABLE = 'immediateDisable' - PERMANENT = 'permanent' - - -# get event name from enum -EVENT_NAME = {v: k for k, v in EventName.schema.enumerants.items()} - - -class Events: - def __init__(self): - self.events: list[int] = [] - self.static_events: list[int] = [] - self.event_counters = dict.fromkeys(EVENTS.keys(), 0) - - @property - def names(self) -> list[int]: - return self.events - - def __len__(self) -> int: - return len(self.events) - - def add(self, event_name: int, static: bool=False) -> None: - if static: - bisect.insort(self.static_events, event_name) - bisect.insort(self.events, event_name) - - def clear(self) -> None: - self.event_counters = {k: (v + 1 if k in self.events else 0) for k, v in self.event_counters.items()} - self.events = self.static_events.copy() - - def contains(self, event_type: str) -> bool: - return any(event_type in EVENTS.get(e, {}) for e in self.events) - - def create_alerts(self, event_types: list[str], callback_args=None): - if callback_args is None: - callback_args = [] - - ret = [] - for e in self.events: - types = EVENTS[e].keys() - for et in event_types: - if et in types: - alert = EVENTS[e][et] - if not isinstance(alert, Alert): - alert = alert(*callback_args) - - if DT_CTRL * (self.event_counters[e] + 1) >= alert.creation_delay: - alert.alert_type = f"{EVENT_NAME[e]}/{et}" - alert.event_type = et - ret.append(alert) - return ret - - def add_from_msg(self, events): - for e in events: - bisect.insort(self.events, e.name.raw) - - def to_msg(self): - ret = [] - for event_name in self.events: - event = car.OnroadEvent.new_message() - event.name = event_name - for event_type in EVENTS.get(event_name, {}): - setattr(event, event_type, True) - ret.append(event) - return ret - - -class Alert: - def __init__(self, - alert_text_1: str, - alert_text_2: str, - alert_status: log.SelfdriveState.AlertStatus, - alert_size: log.SelfdriveState.AlertSize, - priority: Priority, - visual_alert: car.CarControl.HUDControl.VisualAlert, - audible_alert: car.CarControl.HUDControl.AudibleAlert, - duration: float, - creation_delay: float = 0.): - - self.alert_text_1 = alert_text_1 - self.alert_text_2 = alert_text_2 - self.alert_status = alert_status - self.alert_size = alert_size - self.priority = priority - self.visual_alert = visual_alert - self.audible_alert = audible_alert - - self.duration = int(duration / DT_CTRL) - - self.creation_delay = creation_delay - - self.alert_type = "" - self.event_type: str | None = None - - def __str__(self) -> str: - return f"{self.alert_text_1}/{self.alert_text_2} {self.priority} {self.visual_alert} {self.audible_alert}" - - def __gt__(self, alert2) -> bool: - if not isinstance(alert2, Alert): - return False - return self.priority > alert2.priority - - -class NoEntryAlert(Alert): - def __init__(self, alert_text_2: str, - alert_text_1: str = "openpilot Unavailable", - visual_alert: car.CarControl.HUDControl.VisualAlert=VisualAlert.none): - super().__init__(alert_text_1, alert_text_2, AlertStatus.normal, - AlertSize.mid, Priority.LOW, visual_alert, - AudibleAlert.refuse, 3.) - - -class SoftDisableAlert(Alert): - def __init__(self, alert_text_2: str): - super().__init__("TAKE CONTROL IMMEDIATELY", alert_text_2, - AlertStatus.userPrompt, AlertSize.full, - Priority.MID, VisualAlert.steerRequired, - AudibleAlert.warningSoft, 2.), - - -# less harsh version of SoftDisable, where the condition is user-triggered -class UserSoftDisableAlert(SoftDisableAlert): - def __init__(self, alert_text_2: str): - super().__init__(alert_text_2), - self.alert_text_1 = "openpilot will disengage" - - -class ImmediateDisableAlert(Alert): - def __init__(self, alert_text_2: str): - super().__init__("TAKE CONTROL IMMEDIATELY", alert_text_2, - AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.steerRequired, - AudibleAlert.warningImmediate, 4.), - - -class EngagementAlert(Alert): - def __init__(self, audible_alert: car.CarControl.HUDControl.AudibleAlert): - super().__init__("", "", - AlertStatus.normal, AlertSize.none, - Priority.MID, VisualAlert.none, - audible_alert, .2), - - -class NormalPermanentAlert(Alert): - def __init__(self, alert_text_1: str, alert_text_2: str = "", duration: float = 0.2, priority: Priority = Priority.LOWER, creation_delay: float = 0.): - super().__init__(alert_text_1, alert_text_2, - AlertStatus.normal, AlertSize.mid if len(alert_text_2) else AlertSize.small, - priority, VisualAlert.none, AudibleAlert.none, duration, creation_delay=creation_delay), - - -class StartupAlert(Alert): - def __init__(self, alert_text_1: str, alert_text_2: str = "Always keep hands on wheel and eyes on road", alert_status=AlertStatus.normal): - super().__init__(alert_text_1, alert_text_2, - alert_status, AlertSize.mid, - Priority.LOWER, VisualAlert.none, AudibleAlert.none, 5.), - - -# ********** helper functions ********** -def get_display_speed(speed_ms: float, metric: bool) -> str: - speed = int(round(speed_ms * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH))) - unit = 'km/h' if metric else 'mph' - return f"{speed} {unit}" - - -# ********** alert callback functions ********** - -AlertCallbackType = Callable[[car.CarParams, car.CarState, messaging.SubMaster, bool, int, log.ControlsState], Alert] - - -def soft_disable_alert(alert_text_2: str) -> AlertCallbackType: - def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - if soft_disable_time < int(0.5 / DT_CTRL): - return ImmediateDisableAlert(alert_text_2) - return SoftDisableAlert(alert_text_2) - return func - -def user_soft_disable_alert(alert_text_2: str) -> AlertCallbackType: - def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - if soft_disable_time < int(0.5 / DT_CTRL): - return ImmediateDisableAlert(alert_text_2) - return UserSoftDisableAlert(alert_text_2) - return func - -def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - branch = get_short_branch() # Ensure get_short_branch is cached to avoid lags on startup - if "REPLAY" in os.environ: - branch = "replay" - - return StartupAlert("WARNING: This branch is not tested", branch, alert_status=AlertStatus.userPrompt) - -def below_engage_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - return NoEntryAlert(f"Drive above {get_display_speed(CP.minEnableSpeed, metric)} to engage") - - -def below_steer_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - return Alert( - f"Steer Unavailable Below {get_display_speed(CP.minSteerSpeed, metric)}", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 0.4) - - -def calibration_incomplete_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - first_word = 'Recalibration' if sm['liveCalibration'].calStatus == log.LiveCalibrationData.Status.recalibrating else 'Calibration' - return Alert( - f"{first_word} in Progress: {sm['liveCalibration'].calPerc:.0f}%", - f"Drive Above {get_display_speed(MIN_SPEED_FILTER, metric)}", - AlertStatus.normal, AlertSize.mid, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2) - - -# *** debug alerts *** - -def out_of_space_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - full_perc = round(100. - sm['deviceState'].freeSpacePercent) - return NormalPermanentAlert("Out of Storage", f"{full_perc}% full") - - -def posenet_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - mdl = sm['modelV2'].velocity.x[0] if len(sm['modelV2'].velocity.x) else math.nan - err = CS.vEgo - mdl - msg = f"Speed Error: {err:.1f} m/s" - return NoEntryAlert(msg, alert_text_1="Posenet Speed Invalid") - - -def process_not_running_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - not_running = [p.name for p in sm['managerState'].processes if not p.running and p.shouldBeRunning] - msg = ', '.join(not_running) - return NoEntryAlert(msg, alert_text_1="Process Not Running") - - -def comm_issue_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - bs = [s for s in sm.data.keys() if not sm.all_checks([s, ])] - msg = ', '.join(bs[:4]) # can't fit too many on one line - return NoEntryAlert(msg, alert_text_1="Communication Issue Between Processes") - - -def camera_malfunction_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - all_cams = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') - bad_cams = [s.replace('State', '') for s in all_cams if s in sm.data.keys() and not sm.all_checks([s, ])] - return NormalPermanentAlert("Camera Malfunction", ', '.join(bad_cams)) - - -def calibration_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - rpy = sm['liveCalibration'].rpyCalib - yaw = math.degrees(rpy[2] if len(rpy) == 3 else math.nan) - pitch = math.degrees(rpy[1] if len(rpy) == 3 else math.nan) - angles = f"Remount Device (Pitch: {pitch:.1f}°, Yaw: {yaw:.1f}°)" - return NormalPermanentAlert("Calibration Invalid", angles) - - -def overheat_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - cpu = max(sm['deviceState'].cpuTempC, default=0.) - gpu = max(sm['deviceState'].gpuTempC, default=0.) - temp = max((cpu, gpu, sm['deviceState'].memoryTempC)) - return NormalPermanentAlert("System Overheated", f"{temp:.0f} °C") - - -def low_memory_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - return NormalPermanentAlert("Low Memory", f"{sm['deviceState'].memoryUsagePercent}% used") - - -def high_cpu_usage_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - x = max(sm['deviceState'].cpuUsagePercent, default=0.) - return NormalPermanentAlert("High CPU Usage", f"{x}% used") - - -def modeld_lagging_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - return NormalPermanentAlert("Driving Model Lagging", f"{sm['modelV2'].frameDropPerc:.1f}% frames dropped") - - -def wrong_car_mode_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - text = "Enable Adaptive Cruise to Engage" - if CP.carName == "honda": - text = "Enable Main Switch to Engage" - return NoEntryAlert(text) - - -def joystick_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - axes = sm['testJoystick'].axes - gb, steer = list(axes)[:2] if len(axes) else (0., 0.) - vals = f"Gas: {round(gb * 100.)}%, Steer: {round(steer * 100.)}%" - return NormalPermanentAlert("Joystick Mode", vals) - -def personality_changed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - personality = str(personality).title() - return NormalPermanentAlert(f"Driving Personality: {personality}", duration=1.5) - - - -EVENTS: dict[int, dict[str, Alert | AlertCallbackType]] = { - # ********** events with no alerts ********** - - EventName.stockFcw: {}, - EventName.actuatorsApiUnavailable: {}, - - # ********** events only containing alerts displayed in all states ********** - - EventName.joystickDebug: { - ET.WARNING: joystick_alert, - ET.PERMANENT: NormalPermanentAlert("Joystick Mode"), - }, - - EventName.controlsInitializing: { - ET.NO_ENTRY: NoEntryAlert("System Initializing"), - }, - - EventName.startup: { - ET.PERMANENT: StartupAlert("Be ready to take over at any time") - }, - - EventName.startupMaster: { - ET.PERMANENT: startup_master_alert, - }, - - # Car is recognized, but marked as dashcam only - EventName.startupNoControl: { - ET.PERMANENT: StartupAlert("Dashcam mode"), - ET.NO_ENTRY: NoEntryAlert("Dashcam mode"), - }, - - # Car is not recognized - EventName.startupNoCar: { - ET.PERMANENT: StartupAlert("Dashcam mode for unsupported car"), - }, - - EventName.startupNoFw: { - ET.PERMANENT: StartupAlert("Car Unrecognized", - "Check comma power connections", - alert_status=AlertStatus.userPrompt), - }, - - EventName.dashcamMode: { - ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", - priority=Priority.LOWEST), - }, - - EventName.invalidLkasSetting: { - ET.PERMANENT: NormalPermanentAlert("Stock LKAS is on", - "Turn off stock LKAS to engage"), - }, - - EventName.cruiseMismatch: { - #ET.PERMANENT: ImmediateDisableAlert("openpilot failed to cancel cruise"), - }, - - # openpilot doesn't recognize the car. This switches openpilot into a - # read-only mode. This can be solved by adding your fingerprint. - # See https://github.com/commaai/openpilot/wiki/Fingerprinting for more information - EventName.carUnrecognized: { - ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", - "Car Unrecognized", - priority=Priority.LOWEST), - }, - - EventName.stockAeb: { - ET.PERMANENT: Alert( - "BRAKE!", - "Stock AEB: Risk of Collision", - AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), - ET.NO_ENTRY: NoEntryAlert("Stock AEB: Risk of Collision"), - }, - - EventName.fcw: { - ET.PERMANENT: Alert( - "BRAKE!", - "Risk of Collision", - AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.warningSoft, 2.), - }, - - EventName.ldw: { - ET.PERMANENT: Alert( - "Lane Departure Detected", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.ldw, AudibleAlert.prompt, 3.), - }, - - # ********** events only containing alerts that display while engaged ********** - - EventName.steerTempUnavailableSilent: { - ET.WARNING: Alert( - "Steering Temporarily Unavailable", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 1.8), - }, - - EventName.preDriverDistracted: { - ET.PERMANENT: Alert( - "Pay Attention", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.promptDriverDistracted: { - ET.PERMANENT: Alert( - "Pay Attention", - "Driver Distracted", - AlertStatus.userPrompt, AlertSize.mid, - Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), - }, - - EventName.driverDistracted: { - ET.PERMANENT: Alert( - "DISENGAGE IMMEDIATELY", - "Driver Distracted", - AlertStatus.critical, AlertSize.full, - Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), - }, - - EventName.preDriverUnresponsive: { - ET.PERMANENT: Alert( - "Touch Steering Wheel: No Face Detected", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.none, .1), - }, - - EventName.promptDriverUnresponsive: { - ET.PERMANENT: Alert( - "Touch Steering Wheel", - "Driver Unresponsive", - AlertStatus.userPrompt, AlertSize.mid, - Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), - }, - - EventName.driverUnresponsive: { - ET.PERMANENT: Alert( - "DISENGAGE IMMEDIATELY", - "Driver Unresponsive", - AlertStatus.critical, AlertSize.full, - Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), - }, - - EventName.manualRestart: { - ET.WARNING: Alert( - "TAKE CONTROL", - "Resume Driving Manually", - AlertStatus.userPrompt, AlertSize.mid, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), - }, - - EventName.resumeRequired: { - ET.WARNING: Alert( - "Press Resume to Exit Standstill", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), - }, - - EventName.belowSteerSpeed: { - ET.WARNING: below_steer_speed_alert, - }, - - EventName.preLaneChangeLeft: { - ET.WARNING: Alert( - "Steer Left to Start Lane Change Once Safe", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.preLaneChangeRight: { - ET.WARNING: Alert( - "Steer Right to Start Lane Change Once Safe", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.laneChangeBlocked: { - ET.WARNING: Alert( - "Car Detected in Blindspot", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.prompt, .1), - }, - - EventName.laneChange: { - ET.WARNING: Alert( - "Changing Lanes", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.steerSaturated: { - ET.WARNING: Alert( - "Take Control", - "Turn Exceeds Steering Limit", - AlertStatus.userPrompt, AlertSize.mid, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 2.), - }, - - # Thrown when the fan is driven at >50% but is not rotating - EventName.fanMalfunction: { - ET.PERMANENT: NormalPermanentAlert("Fan Malfunction", "Likely Hardware Issue"), - }, - - # Camera is not outputting frames - EventName.cameraMalfunction: { - ET.PERMANENT: camera_malfunction_alert, - ET.SOFT_DISABLE: soft_disable_alert("Camera Malfunction"), - ET.NO_ENTRY: NoEntryAlert("Camera Malfunction: Reboot Your Device"), - }, - # Camera framerate too low - EventName.cameraFrameRate: { - ET.PERMANENT: NormalPermanentAlert("Camera Frame Rate Low", "Reboot your Device"), - ET.SOFT_DISABLE: soft_disable_alert("Camera Frame Rate Low"), - ET.NO_ENTRY: NoEntryAlert("Camera Frame Rate Low: Reboot Your Device"), - }, - - # Unused - - EventName.locationdTemporaryError: { - ET.NO_ENTRY: NoEntryAlert("locationd Temporary Error"), - ET.SOFT_DISABLE: soft_disable_alert("locationd Temporary Error"), - }, - - EventName.locationdPermanentError: { - ET.NO_ENTRY: NoEntryAlert("locationd Permanent Error"), - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("locationd Permanent Error"), - ET.PERMANENT: NormalPermanentAlert("locationd Permanent Error"), - }, - - # openpilot tries to learn certain parameters about your car by observing - # how the car behaves to steering inputs from both human and openpilot driving. - # This includes: - # - steer ratio: gear ratio of the steering rack. Steering angle divided by tire angle - # - tire stiffness: how much grip your tires have - # - angle offset: most steering angle sensors are offset and measure a non zero angle when driving straight - # This alert is thrown when any of these values exceed a sanity check. This can be caused by - # bad alignment or bad sensor data. If this happens consistently consider creating an issue on GitHub - EventName.paramsdTemporaryError: { - ET.NO_ENTRY: NoEntryAlert("paramsd Temporary Error"), - ET.SOFT_DISABLE: soft_disable_alert("paramsd Temporary Error"), - }, - - EventName.paramsdPermanentError: { - ET.NO_ENTRY: NoEntryAlert("paramsd Permanent Error"), - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("paramsd Permanent Error"), - ET.PERMANENT: NormalPermanentAlert("paramsd Permanent Error"), - }, - - # ********** events that affect controls state transitions ********** - - EventName.pcmEnable: { - ET.ENABLE: EngagementAlert(AudibleAlert.engage), - }, - - EventName.buttonEnable: { - ET.ENABLE: EngagementAlert(AudibleAlert.engage), - }, - - EventName.pcmDisable: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - }, - - EventName.buttonCancel: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Cancel Pressed"), - }, - - EventName.brakeHold: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Brake Hold Active"), - }, - - EventName.parkBrake: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Parking Brake Engaged"), - }, - - EventName.pedalPressed: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Pedal Pressed", - visual_alert=VisualAlert.brakePressed), - }, - - EventName.preEnableStandstill: { - ET.PRE_ENABLE: Alert( - "Release Brake to Engage", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1, creation_delay=1.), - }, - - EventName.gasPressedOverride: { - ET.OVERRIDE_LONGITUDINAL: Alert( - "", - "", - AlertStatus.normal, AlertSize.none, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.steerOverride: { - ET.OVERRIDE_LATERAL: Alert( - "", - "", - AlertStatus.normal, AlertSize.none, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.wrongCarMode: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: wrong_car_mode_alert, - }, - - EventName.resumeBlocked: { - ET.NO_ENTRY: NoEntryAlert("Press Set to Engage"), - }, - - EventName.wrongCruiseMode: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Adaptive Cruise Disabled"), - }, - - EventName.steerTempUnavailable: { - ET.SOFT_DISABLE: soft_disable_alert("Steering Temporarily Unavailable"), - ET.NO_ENTRY: NoEntryAlert("Steering Temporarily Unavailable"), - }, - - EventName.steerTimeLimit: { - ET.SOFT_DISABLE: soft_disable_alert("Vehicle Steering Time Limit"), - ET.NO_ENTRY: NoEntryAlert("Vehicle Steering Time Limit"), - }, - - EventName.outOfSpace: { - ET.PERMANENT: out_of_space_alert, - ET.NO_ENTRY: NoEntryAlert("Out of Storage"), - }, - - EventName.belowEngageSpeed: { - ET.NO_ENTRY: below_engage_speed_alert, - }, - - EventName.sensorDataInvalid: { - ET.PERMANENT: Alert( - "Sensor Data Invalid", - "Possible Hardware Issue", - AlertStatus.normal, AlertSize.mid, - Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=1.), - ET.NO_ENTRY: NoEntryAlert("Sensor Data Invalid"), - ET.SOFT_DISABLE: soft_disable_alert("Sensor Data Invalid"), - }, - - EventName.noGps: { - ET.PERMANENT: Alert( - "Poor GPS reception", - "Ensure device has a clear view of the sky", - AlertStatus.normal, AlertSize.mid, - Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=600.) - }, - - EventName.soundsUnavailable: { - ET.PERMANENT: NormalPermanentAlert("Speaker not found", "Reboot your Device"), - ET.NO_ENTRY: NoEntryAlert("Speaker not found"), - }, - - EventName.tooDistracted: { - ET.NO_ENTRY: NoEntryAlert("Distraction Level Too High"), - }, - - EventName.overheat: { - ET.PERMANENT: overheat_alert, - ET.SOFT_DISABLE: soft_disable_alert("System Overheated"), - ET.NO_ENTRY: NoEntryAlert("System Overheated"), - }, - - EventName.wrongGear: { - ET.SOFT_DISABLE: user_soft_disable_alert("Gear not D"), - ET.NO_ENTRY: NoEntryAlert("Gear not D"), - }, - - # This alert is thrown when the calibration angles are outside of the acceptable range. - # For example if the device is pointed too much to the left or the right. - # Usually this can only be solved by removing the mount from the windshield completely, - # and attaching while making sure the device is pointed straight forward and is level. - # See https://comma.ai/setup for more information - EventName.calibrationInvalid: { - ET.PERMANENT: calibration_invalid_alert, - ET.SOFT_DISABLE: soft_disable_alert("Calibration Invalid: Remount Device & Recalibrate"), - ET.NO_ENTRY: NoEntryAlert("Calibration Invalid: Remount Device & Recalibrate"), - }, - - EventName.calibrationIncomplete: { - ET.PERMANENT: calibration_incomplete_alert, - ET.SOFT_DISABLE: soft_disable_alert("Calibration Incomplete"), - ET.NO_ENTRY: NoEntryAlert("Calibration in Progress"), - }, - - EventName.calibrationRecalibrating: { - ET.PERMANENT: calibration_incomplete_alert, - ET.SOFT_DISABLE: soft_disable_alert("Device Remount Detected: Recalibrating"), - ET.NO_ENTRY: NoEntryAlert("Remount Detected: Recalibrating"), - }, - - EventName.doorOpen: { - ET.SOFT_DISABLE: user_soft_disable_alert("Door Open"), - ET.NO_ENTRY: NoEntryAlert("Door Open"), - }, - - EventName.seatbeltNotLatched: { - ET.SOFT_DISABLE: user_soft_disable_alert("Seatbelt Unlatched"), - ET.NO_ENTRY: NoEntryAlert("Seatbelt Unlatched"), - }, - - EventName.espDisabled: { - ET.SOFT_DISABLE: soft_disable_alert("Electronic Stability Control Disabled"), - ET.NO_ENTRY: NoEntryAlert("Electronic Stability Control Disabled"), - }, - - EventName.lowBattery: { - ET.SOFT_DISABLE: soft_disable_alert("Low Battery"), - ET.NO_ENTRY: NoEntryAlert("Low Battery"), - }, - - # Different openpilot services communicate between each other at a certain - # interval. If communication does not follow the regular schedule this alert - # is thrown. This can mean a service crashed, did not broadcast a message for - # ten times the regular interval, or the average interval is more than 10% too high. - EventName.commIssue: { - ET.SOFT_DISABLE: soft_disable_alert("Communication Issue Between Processes"), - ET.NO_ENTRY: comm_issue_alert, - }, - EventName.commIssueAvgFreq: { - ET.SOFT_DISABLE: soft_disable_alert("Low Communication Rate Between Processes"), - ET.NO_ENTRY: NoEntryAlert("Low Communication Rate Between Processes"), - }, - - EventName.controlsdLagging: { - ET.SOFT_DISABLE: soft_disable_alert("Controls Lagging"), - ET.NO_ENTRY: NoEntryAlert("Controls Process Lagging: Reboot Your Device"), - }, - - # Thrown when manager detects a service exited unexpectedly while driving - EventName.processNotRunning: { - ET.NO_ENTRY: process_not_running_alert, - ET.SOFT_DISABLE: soft_disable_alert("Process Not Running"), - }, - - EventName.radarFault: { - ET.SOFT_DISABLE: soft_disable_alert("Radar Error: Restart the Car"), - ET.NO_ENTRY: NoEntryAlert("Radar Error: Restart the Car"), - }, - - # Every frame from the camera should be processed by the model. If modeld - # is not processing frames fast enough they have to be dropped. This alert is - # thrown when over 20% of frames are dropped. - EventName.modeldLagging: { - ET.SOFT_DISABLE: soft_disable_alert("Driving Model Lagging"), - ET.NO_ENTRY: NoEntryAlert("Driving Model Lagging"), - ET.PERMANENT: modeld_lagging_alert, - }, - - # Besides predicting the path, lane lines and lead car data the model also - # predicts the current velocity and rotation speed of the car. If the model is - # very uncertain about the current velocity while the car is moving, this - # usually means the model has trouble understanding the scene. This is used - # as a heuristic to warn the driver. - EventName.posenetInvalid: { - ET.SOFT_DISABLE: soft_disable_alert("Posenet Speed Invalid"), - ET.NO_ENTRY: posenet_invalid_alert, - }, - - # When the localizer detects an acceleration of more than 40 m/s^2 (~4G) we - # alert the driver the device might have fallen from the windshield. - EventName.deviceFalling: { - ET.SOFT_DISABLE: soft_disable_alert("Device Fell Off Mount"), - ET.NO_ENTRY: NoEntryAlert("Device Fell Off Mount"), - }, - - EventName.lowMemory: { - ET.SOFT_DISABLE: soft_disable_alert("Low Memory: Reboot Your Device"), - ET.PERMANENT: low_memory_alert, - ET.NO_ENTRY: NoEntryAlert("Low Memory: Reboot Your Device"), - }, - - EventName.highCpuUsage: { - #ET.SOFT_DISABLE: soft_disable_alert("System Malfunction: Reboot Your Device"), - #ET.PERMANENT: NormalPermanentAlert("System Malfunction", "Reboot your Device"), - ET.NO_ENTRY: high_cpu_usage_alert, - }, - - EventName.accFaulted: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Fault: Restart the Car"), - ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), - ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), - }, - - EventName.espActive: { - ET.SOFT_DISABLE: soft_disable_alert("Electronic Stability Control Active"), - ET.NO_ENTRY: NoEntryAlert("Electronic Stability Control Active"), - }, - - EventName.controlsMismatch: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch"), - ET.NO_ENTRY: NoEntryAlert("Controls Mismatch"), - }, - - EventName.roadCameraError: { - ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Road", - duration=1., - creation_delay=30.), - }, - - EventName.wideRoadCameraError: { - ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Road Fisheye", - duration=1., - creation_delay=30.), - }, - - EventName.driverCameraError: { - ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Driver", - duration=1., - creation_delay=30.), - }, - - # Sometimes the USB stack on the device can get into a bad state - # causing the connection to the panda to be lost - EventName.usbError: { - ET.SOFT_DISABLE: soft_disable_alert("USB Error: Reboot Your Device"), - ET.PERMANENT: NormalPermanentAlert("USB Error: Reboot Your Device", ""), - ET.NO_ENTRY: NoEntryAlert("USB Error: Reboot Your Device"), - }, - - # This alert can be thrown for the following reasons: - # - No CAN data received at all - # - CAN data is received, but some message are not received at the right frequency - # If you're not writing a new car port, this is usually cause by faulty wiring - EventName.canError: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Error"), - ET.PERMANENT: Alert( - "CAN Error: Check Connections", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), - ET.NO_ENTRY: NoEntryAlert("CAN Error: Check Connections"), - }, - - EventName.canBusMissing: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Bus Disconnected"), - ET.PERMANENT: Alert( - "CAN Bus Disconnected: Likely Faulty Cable", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), - ET.NO_ENTRY: NoEntryAlert("CAN Bus Disconnected: Check Connections"), - }, - - EventName.steerUnavailable: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("LKAS Fault: Restart the Car"), - ET.PERMANENT: NormalPermanentAlert("LKAS Fault: Restart the car to engage"), - ET.NO_ENTRY: NoEntryAlert("LKAS Fault: Restart the Car"), - }, - - EventName.reverseGear: { - ET.PERMANENT: Alert( - "Reverse\nGear", - "", - AlertStatus.normal, AlertSize.full, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), - ET.USER_DISABLE: ImmediateDisableAlert("Reverse Gear"), - ET.NO_ENTRY: NoEntryAlert("Reverse Gear"), - }, - - # On cars that use stock ACC the car can decide to cancel ACC for various reasons. - # When this happens we can no long control the car so the user needs to be warned immediately. - EventName.cruiseDisabled: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Is Off"), - }, - - # When the relay in the harness box opens the CAN bus between the LKAS camera - # and the rest of the car is separated. When messages from the LKAS camera - # are received on the car side this usually means the relay hasn't opened correctly - # and this alert is thrown. - EventName.relayMalfunction: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Harness Relay Malfunction"), - ET.PERMANENT: NormalPermanentAlert("Harness Relay Malfunction", "Check Hardware"), - ET.NO_ENTRY: NoEntryAlert("Harness Relay Malfunction"), - }, - - EventName.speedTooLow: { - ET.IMMEDIATE_DISABLE: Alert( - "openpilot Canceled", - "Speed too low", - AlertStatus.normal, AlertSize.mid, - Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), - }, - - # When the car is driving faster than most cars in the training data, the model outputs can be unpredictable. - EventName.speedTooHigh: { - ET.WARNING: Alert( - "Speed Too High", - "Model uncertain at this speed", - AlertStatus.userPrompt, AlertSize.mid, - Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 4.), - ET.NO_ENTRY: NoEntryAlert("Slow down to engage"), - }, - - EventName.lowSpeedLockout: { - ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), - ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), - }, - - EventName.lkasDisabled: { - ET.PERMANENT: NormalPermanentAlert("LKAS Disabled: Enable LKAS to engage"), - ET.NO_ENTRY: NoEntryAlert("LKAS Disabled"), - }, - - EventName.vehicleSensorsInvalid: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Vehicle Sensors Invalid"), - ET.PERMANENT: NormalPermanentAlert("Vehicle Sensors Calibrating", "Drive to Calibrate"), - ET.NO_ENTRY: NoEntryAlert("Vehicle Sensors Calibrating"), - }, - - EventName.personalityChanged: { - ET.WARNING: personality_changed_alert, - }, - -} - - -if __name__ == '__main__': - # print all alerts by type and priority - from cereal.services import SERVICE_LIST - from collections import defaultdict - - event_names = {v: k for k, v in EventName.schema.enumerants.items()} - alerts_by_type: dict[str, dict[Priority, list[str]]] = defaultdict(lambda: defaultdict(list)) - - CP = car.CarParams.new_message() - CS = car.CarState.new_message() - sm = messaging.SubMaster(list(SERVICE_LIST.keys())) - - for i, alerts in EVENTS.items(): - for et, alert in alerts.items(): - if callable(alert): - alert = alert(CP, CS, sm, False, 1, log.LongitudinalPersonality.standard) - alerts_by_type[et][alert.priority].append(event_names[i]) - - all_alerts: dict[str, list[tuple[Priority, list[str]]]] = {} - for et, priority_alerts in alerts_by_type.items(): - all_alerts[et] = sorted(priority_alerts.items(), key=lambda x: x[0], reverse=True) - - for status, evs in sorted(all_alerts.items(), key=lambda x: x[0]): - print(f"**** {status} ****") - for p, alert_list in evs: - print(f" {repr(p)}:") - print(" ", ', '.join(alert_list), "\n") diff --git a/selfdrive/controls/lib/firm_brake_latch.py b/selfdrive/controls/lib/firm_brake_latch.py new file mode 100644 index 00000000000000..501f8f06ee3020 --- /dev/null +++ b/selfdrive/controls/lib/firm_brake_latch.py @@ -0,0 +1,113 @@ +"""Firm-brake latch for the Pre-AP follow actuator guard. + +15a 11:26:49: a firm plan (-1.5) on a mid-gap close stepped -1.5 -> -0.22 +-> -1.5 at the actuator when v_rel crossed 1.5 m/s, because the guard's +mild-floor clip (lead_approach.guard_follow_actuator_regen) comes back +below that close while the plan is still firm. A firm mid-gap close +passes the planner command through; once the close eases under 1.5 the +clip re-engaged and the brake fell off for a few frames. + +The latch keeps that pass-through while the plan is still firm. It lives +outside the guard on purpose: `guard_follow_actuator_regen` (and #222, EV +mild settle -0.22, MAX, the -1.5 rail) is untouched, and the latch can +only ever make the command firmer than the guard returned. + +Set when a firm close was passed (`lead_midgap_firm_close_hit`) on a plan +at or under ENTER_PLAN. Held until the plan is softer than HOLD_PLAN, the +close collapses under HOLD_CLOSE, MAX_S elapses, the lead is lost, or +LongControl resets. +""" + +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_APPROACH_SOFT_LIMIT_CLOSE_MS, + LEAD_MPC_SOFT_NEAR_M, + lead_approach_is_rapid, + lead_firm_alead, + lead_firm_large_slack_a, + lead_mid_gap_map_band, + lead_rising_or_residual_brake, +) + +LEAD_FIRM_LATCH_ENTER_PLAN_MS2 = -0.80 +LEAD_FIRM_LATCH_HOLD_PLAN_MS2 = -0.50 +LEAD_FIRM_LATCH_ENTER_CLOSE_MS = LEAD_APPROACH_SOFT_LIMIT_CLOSE_MS +LEAD_FIRM_LATCH_HOLD_CLOSE_MS = 0.80 +LEAD_FIRM_LATCH_MAX_S = 4.0 + + +def lead_midgap_firm_close_hit(v_rel, d_rel, slack, a_lead=None, + prev_v_rel=None, a_ego=None, dt=None, + should_stop=False) -> bool: + """True when the mid-gap guard is passing a firm close (not a coast). + + Same inputs as the guard's exclusion that unlocks the planner command at + close >= 1.5: mid-gap band, firm aLead or #222 rising/residual brake. + Near bumper, shouldStop, and confirmed rapid already pass raw and do + not need the latch. + """ + if should_stop or v_rel is None: + return False + v = float(v_rel) + if v < LEAD_FIRM_LATCH_ENTER_CLOSE_MS or lead_approach_is_rapid(v): + return False + if d_rel is not None and float(d_rel) <= LEAD_MPC_SOFT_NEAR_M: + return False + if not lead_mid_gap_map_band(slack, d_rel): + return False + return lead_firm_alead(a_lead) or lead_rising_or_residual_brake( + v, prev_v_rel, a_ego, dt, + ) + + +class FirmBrakeLatch: + """`update` returns True while the guard's mild-floor clip must stay off. + + Owned by LongControl and stepped once per control frame with its own + `dt` (not the residual-window span). A lost lead or plan resets it. + """ + + def __init__(self) -> None: + self.on = False + self.age = 0.0 + + def reset(self) -> None: + self.on = False + self.age = 0.0 + + def update(self, planner_a, v_rel, hit, dt) -> bool: + if planner_a is None or v_rel is None: + self.reset() + return False + p = float(planner_a) + v = float(v_rel) + if self.on: + self.age += float(dt) + if (self.age > LEAD_FIRM_LATCH_MAX_S + or p > LEAD_FIRM_LATCH_HOLD_PLAN_MS2 + or v < LEAD_FIRM_LATCH_HOLD_CLOSE_MS): + self.reset() + if not self.on and hit and p <= LEAD_FIRM_LATCH_ENTER_PLAN_MS2: + self.on = True + self.age = 0.0 + return self.on + + +def apply_firm_brake_latch(guarded_a, raw_a, planner_a, hold, v_rel=None, + slack=None, a_lead=None): + """Keep the planner-following command while the latch holds. + + `guarded_a` is the unchanged guard output and `raw_a` the actuator + before it. The guard only ever raises `raw_a`, so `min` restores the + firm command and can never be softer than `guarded_a`. The guard's + early kinematic cap (firm lead 20-50 m out, not confirmed rapid) is a + deliberate softening and keeps ownership of the frame, as does any + frame whose plan is not firm. + """ + if not hold or guarded_a is None or raw_a is None or planner_a is None: + return guarded_a + if float(planner_a) > LEAD_FIRM_LATCH_HOLD_PLAN_MS2: + return guarded_a + if (v_rel is not None and not lead_approach_is_rapid(float(v_rel)) + and lead_firm_large_slack_a(v_rel, slack, a_lead) is not None): + return guarded_a + return min(float(guarded_a), float(raw_a)) diff --git a/selfdrive/controls/lib/follow_distance.py b/selfdrive/controls/lib/follow_distance.py new file mode 100644 index 00000000000000..c85a16a38f049b --- /dev/null +++ b/selfdrive/controls/lib/follow_distance.py @@ -0,0 +1,281 @@ +"""City vs highway Follow Distance (Mannerisms 1–7 setpoints). + +Two params: NAPFollowDistanceCity and NAPFollowDistanceHwy. Migrates +from the single NAPFollowDistance slider. Available whenever Mannerisms +FD is used — not gated on Hypermile. + +Band selection is MAX-primary, for both the live blend and a stalk bump: + +- City when MAX / set cruise speed is under 50 mph +- Highway when MAX is 50 mph or higher (exactly 50 is Highway) +- Traveled speed only when MAX is unset, invalid, or 0 + +A hard brake that drops ego under 50 while MAX stays at 75 stays on +Highway follow. Ego speed does not open the city gap under a highway MAX. + +While long is engaged and a radar lead is valid, t_follow still slews +between the two setpoints (no step when the band changes). Dropping into +city, ego is slightly slower than the lead so the gap *opens* to city FD. +Rising onto highway, t_follow creeps toward hwy FD. + +Ego hysteresis (enter hwy above 52, return to city below 48) remains +only for that no-MAX fallback. Ego speed chatters through 49–51; a set +MAX does not, so the MAX cut is a hard 50 with no extra hold. The slew +above is what smooths a real band change — it does not pick the band. +""" +from __future__ import annotations + +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_CLOSE_OPENING_A_MS2, + nap_t_follow, +) + +PARAM_FOLLOW = "NAPFollowDistance" +PARAM_FOLLOW_CITY = "NAPFollowDistanceCity" +PARAM_FOLLOW_HWY = "NAPFollowDistanceHwy" +PARAM_FOLLOW_MIGRATED = "NAPFollowDistanceSplitMigrated" + +FOLLOW_MIN = 1 +FOLLOW_MAX = 7 +FOLLOW_DEFAULT = 4 +NAP_FOLLOW_DISTANCE_RANGE = range(FOLLOW_MIN, FOLLOW_MAX + 1) + +# MAX / set speed cut. Highway at 50 mph and above. City under 50. +# Ego fallback (no MAX) still uses 48/52 so 49–51 mph of traveled +# speed does not flap the setpoint. A set MAX is not that noisy. +FOLLOW_SPLIT_MPH = 50.0 +FOLLOW_CITY_ENTER_MPH = 48.0 +FOLLOW_HWY_ENTER_MPH = 52.0 +# While opening to a farther city FD: ~3% slower than lead (small % more slowing). +FOLLOW_OPEN_SLOW_FRAC = 0.03 +# t_follow slew (seconds of headway per second). Opening is a bit faster +# than highway creep so the city gap actually grows; creep stays lazy. +FOLLOW_T_SLEW_OPEN_PER_S = 0.08 +FOLLOW_T_SLEW_CREEP_PER_S = 0.04 + + +def clamp_follow_distance(level: int | None) -> int: + try: + return max(FOLLOW_MIN, min(FOLLOW_MAX, int(level))) + except (TypeError, ValueError): + return FOLLOW_DEFAULT + + +def parse_follow_distance(level) -> int | None: + """1–7, or None when unset / invalid (planner then uses personality).""" + try: + n = int(level) + except (TypeError, ValueError): + return None + return n if n in NAP_FOLLOW_DISTANCE_RANGE else None + + +def _get_bool(params, key) -> bool: + try: + return bool(params.get_bool(key)) + except Exception: + return False + + +def migrate_follow_distance_params(params) -> tuple[int | None, int | None]: + """Copy legacy NAPFollowDistance into city/hwy once, then read both. + + Returns `(city, hwy)` in 1–7, or None when that band is invalid so the + planner can keep personality t_follow (napFollowDistance 0). Always + available (not Hypermile). + """ + try: + raw_legacy = params.get(PARAM_FOLLOW, return_default=True) + except Exception: + raw_legacy = None + legacy = parse_follow_distance(raw_legacy) + if not _get_bool(params, PARAM_FOLLOW_MIGRATED): + seed = legacy if legacy is not None else FOLLOW_DEFAULT + try: + params.put(PARAM_FOLLOW_CITY, int(seed)) + params.put(PARAM_FOLLOW_HWY, int(seed)) + params.put_bool(PARAM_FOLLOW_MIGRATED, True) + except Exception: + pass + return seed, seed + try: + raw_city = params.get(PARAM_FOLLOW_CITY, return_default=True) + except Exception: + raw_city = None + try: + raw_hwy = params.get(PARAM_FOLLOW_HWY, return_default=True) + except Exception: + raw_hwy = None + city = parse_follow_distance(raw_city) + hwy = parse_follow_distance(raw_hwy) + if city is None: + city = legacy + if hwy is None: + hwy = legacy + return city, hwy + + +def follow_set_max_ms(v_cruise) -> float | None: + """MAX in m/s, or None when it is unset, invalid, or not positive. + + 0 is not a city set speed. Callers that already filtered the 255 kph + unset sentinel (`published_cruise_ms`) pass None. + """ + try: + if v_cruise is None: + return None + v = float(v_cruise) + except (TypeError, ValueError): + return None + if not (v > 0.0): + return None + return v + + +def follow_max_is_highway(v_cruise) -> bool | None: + """Highway when MAX ≥ 50 mph, City when MAX < 50, None when no MAX. + + Exactly 50 mph is Highway. Compare in m/s so a 50 mph set does not + miss the cut on a kph round-trip. No extra hold under 50: a 49 mph + MAX is City even if the previous band was Highway. + """ + v = follow_set_max_ms(v_cruise) + if v is None: + return None + return v >= FOLLOW_SPLIT_MPH * CV.MPH_TO_MS + + +def follow_ego_band_is_highway(v_ego, prev_highway=None) -> bool: + """Traveled-speed band. Only used when MAX is not available. + + No previous band: Highway at 50 mph and above. With a previous band, + hold Highway down through 49 and City up through 51 (drop below 48, + rise above 52) so ego chatter at the cut does not flap setpoints. + """ + try: + v = 0.0 if v_ego is None else float(v_ego) + except (TypeError, ValueError): + v = 0.0 + mph = v * CV.MS_TO_MPH + if prev_highway is None: + return mph >= FOLLOW_SPLIT_MPH + if prev_highway and mph < FOLLOW_CITY_ENTER_MPH: + return False + if (not prev_highway) and mph > FOLLOW_HWY_ENTER_MPH: + return True + return bool(prev_highway) + + +def follow_stalk_band_is_highway(v_ego, v_cruise=None) -> bool: + """True when a stalk bump should step Highway Follow Distance. + + Same MAX-primary cut as live follow: Highway when MAX ≥ 50 mph + (including while ego is still coming up to that set speed, and + including exactly 50). City when MAX is under 50, even if ego is + already above 50. Traveled speed is the fallback only when MAX is + unset, invalid, or 0 — a zero cruise reading must not force City + once ego is on the highway side of the fallback cut. + """ + band = follow_max_is_highway(v_cruise) + if band is not None: + return band + return follow_ego_band_is_highway(v_ego, prev_highway=None) + + +def published_cruise_ms(v_cruise_kph, unset_kph: float = 255.0) -> float | None: + """HUD MAX in kph → m/s for the stalk band, or None if it is not a set speed. + + 0 and the unset sentinel are not a city MAX. CarState.vCruise is 0 until + card publishes the helper at the end of the frame. + """ + try: + v_kph = float(v_cruise_kph) + unset = float(unset_kph) + except (TypeError, ValueError): + return None + if not (0.0 < v_kph < unset): + return None + return v_kph * CV.KPH_TO_MS + + +def follow_band_is_highway(v_ego, prev_highway=None, *, v_cruise=None, + engaged=False, has_lead=False, intent=None, + prev_intent=None) -> bool: + """City vs hwy Follow Distance band. + + MAX-primary: Highway when set speed ≥ 50 mph, City when it is under + 50, whether or not a lead is present and whether or not long is + engaged. Ego speed is not part of that choice — decelerating under a + highway MAX stays Highway. `engaged` / `has_lead` / `intent` are + accepted so older callers keep working; they do not pick the band. + The t_follow slew in `FollowDistanceBlend` still runs only while long + is engaged with a lead. + + No MAX (unset / invalid / 0): ego fallback, with 48/52 hysteresis + when a previous band is known. + """ + _ = (engaged, has_lead, intent, prev_intent) + band = follow_max_is_highway(v_cruise) + if band is not None: + return band + return follow_ego_band_is_highway(v_ego, prev_highway) + + +def follow_open_a_ms2(v_ego, v_lead): + """Slightly slower than lead while the city gap is still opening, or None.""" + if v_ego is None or v_lead is None: + return None + vt = max(0.0, float(v_lead)) + if vt <= 0.0: + return None + v_des = vt * (1.0 - FOLLOW_OPEN_SLOW_FRAC) + dv = float(v_ego) - v_des + if dv <= 0.0: + return None + return -min(LEAD_CLOSE_OPENING_A_MS2, dv * 0.20) + + +class FollowDistanceBlend: + """Slew t_follow between city and hwy setpoints; extra −a while opening.""" + + def __init__(self): + self.highway = None + self.t_follow = None + self.city = FOLLOW_DEFAULT + self.hwy = FOLLOW_DEFAULT + self.active_dist = FOLLOW_DEFAULT + + def read_setpoints(self, params): + self.city, self.hwy = migrate_follow_distance_params(params) + + def update(self, v_ego, dt, *, engaged, has_lead, v_lead=None, v_cruise=None): + self.highway = follow_band_is_highway(v_ego, self.highway, v_cruise=v_cruise) + target_dist = self.hwy if self.highway else self.city + if target_dist not in NAP_FOLLOW_DISTANCE_RANGE: + self.active_dist = None + return None, None, None + self.active_dist = target_dist + target_t = nap_t_follow(self.active_dist) + if target_t is None: + self.active_dist = None + return None, None, None + if self.t_follow is None: + self.t_follow = float(target_t) + + opening = False + if engaged and has_lead: + if target_t > self.t_follow + 1e-6: + step = FOLLOW_T_SLEW_OPEN_PER_S * max(0.0, float(dt)) + self.t_follow = min(float(target_t), self.t_follow + step) + opening = self.t_follow < float(target_t) - 1e-4 + elif target_t < self.t_follow - 1e-6: + step = FOLLOW_T_SLEW_CREEP_PER_S * max(0.0, float(dt)) + self.t_follow = max(float(target_t), self.t_follow - step) + else: + self.t_follow = float(target_t) + else: + self.t_follow = float(target_t) + + extra_a = follow_open_a_ms2(v_ego, v_lead) if opening else None + return self.t_follow, self.active_dist, extra_a diff --git a/selfdrive/controls/lib/gap_lock.py b/selfdrive/controls/lib/gap_lock.py new file mode 100644 index 00000000000000..03ead0a5cc3f5d --- /dev/null +++ b/selfdrive/controls/lib/gap_lock.py @@ -0,0 +1,410 @@ +"""Pre-AP gap lock: a 2 s engage-stalk hold latches radar meters. + +The latch is a setpoint for the existing unified lead law +(`gap_set_override_m`). It is not a second controller. Mannerisms +`t_follow` still sizes intrusion, MPC, and FCW. + +The hold arms whether longitudinal is already on, paused (pedal, +One-Pedal, brake, standstill wait), or not yet taken. A completed hold +resumes long so those meters become the setpoint. A tip, cancel, brake, +One-Pedal pause, or toggle off still clears a lock that is already on. + +A radar track-id swap at the same gap is the same lead: the new id is +adopted and the locked meters stay, with no toast. If nothing plausible +is there, the meters stay for about two seconds and then clear. + +Stock DI still sees the physical pull (0x45 is relayed). After 0.5 s of +a qualified hold, the openpilot overlay repeats CANCEL on the existing +10 Hz spoof slot until the lever returns to idle. Panda does not treat +that in-session TX as a lateral drop: `tesla_preap_tx.h` calls +`pcm_cruise_check(false)` for lever == CANCEL only when +`!controls_allowed`. +""" + +from __future__ import annotations + +import time + +from opendbc.car.tesla.values import CruiseButtons + +from openpilot.selfdrive.controls.lib.lead_approach import lead_follow_slack_m + +GAP_LOCK_HOLD_S = 2.0 +GAP_LOCK_CANCEL_AFTER_S = 0.5 +GAP_LOCK_MIN_M = 8.0 +GAP_LOCK_MAX_M = 80.0 +GAP_LOCK_MEDIAN_S = 0.4 +# Unavailable / lost bottom toasts. Already brief; not the engaged banner. +GAP_LOCK_HUD_S = 1.5 +# Bottom "Gap lock engaged …" toast. The under-MAX chip is not on this timer. +GAP_LOCK_ENGAGED_BANNER_S = 2.0 +# Same-gap radar id swap (16:08:53, 2088 → 2698 at ~27 m). A new radar +# lead within this window of the locked meters, and in the lane, is the +# same car. Anything else keeps the lock for GAP_LOCK_ABSENT_S, then +# clears with the lost toast. The old 0.5 s hold only covered status=0. +GAP_LOCK_REMATCH_M = 5.0 +GAP_LOCK_REMATCH_Y_M = 1.5 +GAP_LOCK_ABSENT_S = 2.0 + +HUD_NONE = 0 +HUD_ENGAGED = 1 +HUD_UNAVAILABLE = 2 +HUD_LOST = 3 + +_PARAM_KEY = "NAPGapLock" +_param_cache = {"t": 0.0, "v": False} + + +def gap_lock_param_enabled(params) -> bool: + """True only for a real bool True. MagicMock and a missing key stay off.""" + try: + return params.get_bool(_PARAM_KEY) is True + except Exception: + return False + + +def gap_lock_enabled(engagement=None) -> bool: + """Gesture enable. Tests set `_nap_gap_lock_enabled_override` on the FSM.""" + if engagement is not None: + override = getattr(engagement, "_nap_gap_lock_enabled_override", None) + if isinstance(override, bool): + return override + now = time.monotonic() + if now - float(_param_cache["t"]) < 0.5: + return bool(_param_cache["v"]) + val = False + try: + from openpilot.common.params import Params + val = Params().get_bool(_PARAM_KEY) is True + except Exception: + val = False + _param_cache["t"] = now + _param_cache["v"] = val + return val + + +def gap_lock_arm_seq(engagement) -> int: + gesture = getattr(engagement, "_nap_gap_lock", None) + if gesture is None: + return 0 + return int(gesture.seq) & 0xFF + + +def gap_lock_cancel_hold(engagement) -> bool: + gesture = getattr(engagement, "_nap_gap_lock", None) + return bool(gesture is not None and gesture.cancel_hold) + + +def gap_lock_holding(engagement) -> bool: + gesture = getattr(engagement, "_nap_gap_lock", None) + return bool(gesture is not None and gesture.holding) + + +def _positive_meters(meters): + try: + value = float(meters) + except (TypeError, ValueError): + return None + if value != value or value <= 0.0: + return None + return value + + +def gap_lock_banner_active(event) -> bool: + """Bottom toast only. The under-MAX chip follows the latched meters on its own.""" + try: + code = int(event or 0) + except (TypeError, ValueError): + return False + return code in (HUD_ENGAGED, HUD_UNAVAILABLE, HUD_LOST) + + +def gap_lock_engaged_text(meters) -> str | None: + """Bottom-banner line for a fresh lock. None when there is no distance.""" + value = _positive_meters(meters) + if value is None: + return None + return f"Gap lock engaged {int(round(value))} m" + + +def gap_lock_hud_chip(meters) -> str | None: + """C3X MAX-column chip. None when gap lock is clear.""" + value = _positive_meters(meters) + if value is None: + return None + return f"LOCK {int(round(value))}m" + + +def gap_lock_cancel_hold_tx(already_sent_stw: bool, hold: bool, frame: int) -> bool: + """Repeat CANCEL on an empty 10 Hz 0x45 slot. Do not stack a second frame.""" + if hold is not True or already_sent_stw: + return False + try: + return int(frame) % 10 == 0 + except (TypeError, ValueError): + return False + + +def slack_for_guard(d_rel, v_lead, t_follow, gap_lock_m): + """Actuator-guard slack. A lock uses locked meters; 0 stays on the time gap.""" + try: + lock = float(gap_lock_m or 0.0) + except (TypeError, ValueError): + lock = 0.0 + if lock > 0.0 and d_rel is not None: + return float(d_rel) - lock + return lead_follow_slack_m(d_rel, v_lead, t_follow) + + +def stalk_follow_exit(cs) -> bool: + """Up/down stalk edge (tip or 2nd detent). Both are `accelCruise` / `decelCruise`.""" + try: + from cereal import car + accel = int(car.CarState.ButtonEvent.Type.accelCruise) + decel = int(car.CarState.ButtonEvent.Type.decelCruise) + events = cs.buttonEvents + n = len(events) + except Exception: + return False + if n > 16: + n = 16 + for i in range(n): + try: + be = events[i] + if be.pressed is True and int(be.type) in (accel, decel): + return True + except Exception: + continue + return False + + +def _u8(value) -> int: + if isinstance(value, bool) or value is None: + return 0 + try: + return int(value) & 0xFF + except (TypeError, ValueError): + return 0 + + +def _track_id(value): + if isinstance(value, bool) or value is None: + return None + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _median(values: list[float]) -> float: + ordered = sorted(values) + n = len(ordered) + mid = n // 2 + if n % 2: + return float(ordered[mid]) + return 0.5 * (float(ordered[mid - 1]) + float(ordered[mid])) + + +class GapLockGesture: + """2.0 s MAIN hold. Long may be on, paused, or not yet taken.""" + + def __init__(self) -> None: + self.seq = 0 + self.cancel_hold = False + self._holding = False + self._t0 = 0.0 + self._fired = False + + @property + def holding(self) -> bool: + return self._holding + + def update(self, *, enabled: bool, use_pedal: bool, can_valid: bool, + cruise_buttons, prev, now_ms: float, cruise_on: bool, + qualify_press: bool, brake: bool = False) -> None: + main = int(cruise_buttons) == int(CruiseButtons.MAIN) + rising = main and int(prev) != int(CruiseButtons.MAIN) + braked = brake is True + if not (enabled and use_pedal and can_valid): + self._reset_hold() + return + if rising and qualify_press and cruise_on and not braked: + self._holding = True + self._t0 = float(now_ms) + self._fired = False + self.cancel_hold = False + return + if not self._holding: + self.cancel_hold = False + return + # Brake and cancel abort. A long pause during the hold does not: + # the completed hold takes longitudinal itself. + if (not main) or (not cruise_on) or braked: + self._reset_hold() + return + elapsed = (float(now_ms) - self._t0) / 1000.0 + self.cancel_hold = elapsed >= GAP_LOCK_CANCEL_AFTER_S + if elapsed >= GAP_LOCK_HOLD_S and not self._fired: + self.seq = (int(self.seq) % 255) + 1 + self._fired = True + + def _reset_hold(self) -> None: + self._holding = False + self._fired = False + self.cancel_hold = False + + +class GapLockLatch: + """Planner-side meters + radar track. Seq 0 is unset; the first value is stored, not armed.""" + + def __init__(self) -> None: + self.track_id: int | None = None + self.gap_m: float | None = None + self.preview_m: float | None = None + self.preview_track: int | None = None + self.hud = HUD_NONE + self._seen_seq: int | None = None + self._samples: list[tuple[float, int, float]] = [] + self._t = 0.0 + self._absent = 0.0 + self._hud_until = 0.0 + + def update(self, dt, *, enabled: bool, long_on: bool, seq, status: bool, + radar: bool, track_id, d_rel, stalk_exit: bool, holding: bool = False, + y_rel=None) -> None: + frame_dt = 0.05 if dt is None or float(dt) <= 0.0 else float(dt) + self._t += frame_dt + self._decay_hud() + self._push_sample(status, radar, track_id, d_rel) + + seq_i = _u8(seq) + if self._seen_seq is None: + self._seen_seq = seq_i + seq_changed = False + else: + seq_changed = seq_i != self._seen_seq + + if (not enabled) or (not long_on) or stalk_exit: + self._clear(toast=False) + if seq_changed: + self._seen_seq = seq_i + # While the stalk is still held, keep the running median as the + # setpoint even if long is paused. The car is already on that + # distance when the hold completes and long is taken. + self._set_preview(holding and enabled and not stalk_exit, track_id) + return + + if seq_changed: + self._seen_seq = seq_i + self._try_arm(status, radar, track_id) + self._follow_track(frame_dt, status, radar, track_id, d_rel, y_rel) + self._set_preview(holding and enabled and not stalk_exit, track_id) + + def _push_sample(self, status, radar, track_id, d_rel) -> None: + cutoff = self._t - GAP_LOCK_MEDIAN_S + self._samples = [s for s in self._samples if s[0] >= cutoff] + if status is not True or radar is not True or d_rel is None: + return + tid = _track_id(track_id) + if tid is None or tid < 0: + return + try: + dist = float(d_rel) + except (TypeError, ValueError): + return + if dist != dist: # NaN + return + self._samples.append((self._t, tid, dist)) + + def _set_preview(self, active: bool, track_id) -> None: + self.preview_m = None + self.preview_track = None + if not active or self.gap_m is not None: + return + tid = _track_id(track_id) + if tid is None or tid < 0: + return + vals = [d for _t, i, d in self._samples if i == tid] + if not vals: + return + med = _median(vals) + if med < GAP_LOCK_MIN_M or med > GAP_LOCK_MAX_M: + return + self.preview_m = float(med) + self.preview_track = tid + + def _try_arm(self, status, radar, track_id) -> None: + tid = _track_id(track_id) + if status is not True or radar is not True or tid is None or tid < 0: + self._pulse(HUD_UNAVAILABLE) + return + vals = [d for _t, i, d in self._samples if i == tid] + if not vals: + self._pulse(HUD_UNAVAILABLE) + return + med = _median(vals) + if med < GAP_LOCK_MIN_M or med > GAP_LOCK_MAX_M: + self._pulse(HUD_UNAVAILABLE) + return + self.track_id = tid + self.gap_m = float(med) + self._absent = 0.0 + self._pulse(HUD_ENGAGED, GAP_LOCK_ENGAGED_BANNER_S) + + def _plausible_rematch(self, status, radar, track_id, d_rel, y_rel) -> bool: + """New radar id, still the locked gap and in the lane.""" + if status is not True or radar is not True or self.gap_m is None: + return False + tid = _track_id(track_id) + if tid is None or tid < 0 or tid == self.track_id: + return False + try: + dist = float(d_rel) + lateral = 0.0 if y_rel is None else abs(float(y_rel)) + except (TypeError, ValueError): + return False + if dist != dist or lateral != lateral: + return False + if abs(dist - float(self.gap_m)) > GAP_LOCK_REMATCH_M: + return False + return lateral <= GAP_LOCK_REMATCH_Y_M + + def _follow_track(self, dt: float, status, radar, track_id, d_rel, y_rel) -> None: + if self.gap_m is None or self.track_id is None: + self._absent = 0.0 + return + tid = _track_id(track_id) + if status is True and radar is True and tid == self.track_id: + self._absent = 0.0 + return + # Same car, new radar id. Keep the locked meters and follow the new id. + if self._plausible_rematch(status, radar, track_id, d_rel, y_rel): + self.track_id = tid + self._absent = 0.0 + return + # Vision-only, a different car, or no lead. Hold, then toast. + self._absent += dt + if self._absent >= GAP_LOCK_ABSENT_S: + self._clear(toast=True) + + def _clear(self, *, toast: bool) -> None: + had = self.gap_m is not None + self.track_id = None + self.gap_m = None + self.preview_m = None + self.preview_track = None + self._absent = 0.0 + if toast and had: + self._pulse(HUD_LOST) + elif not toast: + self.hud = HUD_NONE + self._hud_until = 0.0 + + def _pulse(self, code: int, duration: float | None = None) -> None: + self.hud = int(code) + hold = GAP_LOCK_HUD_S if duration is None else float(duration) + self._hud_until = self._t + hold + + def _decay_hud(self) -> None: + if self.hud and self._t >= self._hud_until: + self.hud = HUD_NONE diff --git a/selfdrive/controls/lib/hill_climb.py b/selfdrive/controls/lib/hill_climb.py new file mode 100644 index 00000000000000..ea91db79e62351 --- /dev/null +++ b/selfdrive/controls/lib/hill_climb.py @@ -0,0 +1,158 @@ +"""Hypermile Hill Climb: IMU-pitch grade hold and crest ease. + +v1 signal is `carControl.orientationNED[1]` (same pitch `get_coast_accel` +already reads). No OSM / maps-elevation lookahead in this module. + +Active only when Hypermile is On *and* the Hill Climb sub-toggle is On +(`NAPHypermileHillClimb`, default On). Hidden/inert when Hypermile is Off. + +Does not raise HUD MAX / vCruise. Lead-approach and MPC hard brake still +win via the planner `min()`. Flat road leaves Accel 1 / map_track alone. +""" +from __future__ import annotations + +import math + +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY +from openpilot.selfdrive.mapd.constants import TRACK_DEADBAND_MS + +PARAM_HILL_CLIMB = "NAPHypermileHillClimb" + +# Earth g. Same coefficient VirtualDAS / the Pre-AP plant use for grade load. +# Accel 1 Early is clamped at 0.30 m/s²; a 2° (~3.5%) grade already needs +# ~0.34 m/s² just to hold, so uncompensated Accel 1 sags on a real climb. +GRAVITY_MS2 = ACCELERATION_DUE_TO_GRAVITY + +# Clearly uphill / downhill. ~1° is road crown + IMU bias; 2° is a real grade +# (≈3.5%) Accel 1 cannot hold. 4° (existing full-loop uphill fixture) is +# well above this. +PITCH_CLIMB_RAD = math.radians(2.0) +PITCH_DOWN_RAD = -PITCH_CLIMB_RAD +# Start crest ease as pitch falls through this after a climb (~1.7%). +PITCH_CREST_RAD = math.radians(1.0) + +# Extra +a from grade, on top of flat Accel 1–10. Capped at Normal/Accel-5 +# comfort (0.80) so a mountain grade cannot punch. Cruise get_max_accel and +# lead-close still clip after this. +CLIMB_EXTRA_MAX_MS2 = 0.80 + +# Crest / downhill ease. Hypermile Early map brake is 0.55; Late is 1.20 +# (the bite that makes people sick). Stay well under Early. +CREST_EASE_MS2 = 0.15 +DOWNHILL_EASE_MS2 = 0.25 + + +def hill_climb_applies(hypermile_on: bool, hill_climb_on: bool) -> bool: + return bool(hypermile_on) and bool(hill_climb_on) + + +def read_hypermile_hill_climb(params) -> bool: + """Default On. Inert unless Hypermile is On. Missing / test double → On.""" + try: + return bool(params.get_bool(PARAM_HILL_CLIMB)) + except Exception: + return True + + +def grade_load_ms2(pitch_rad: float) -> float: + """+a (m/s²) needed to hold speed against gravity. Positive = uphill.""" + return GRAVITY_MS2 * math.sin(float(pitch_rad)) + + +def climb_authority_ms2(flat_a: float, pitch_rad: float) -> float: + """Flat map-track climb plus grade load, extra capped. + + Used when clearly uphill and ego is under HUD MAX. Does not raise MAX. + """ + extra = min(CLIMB_EXTRA_MAX_MS2, max(0.0, grade_load_ms2(pitch_rad))) + return float(flat_a) + extra + + +def downhill_ease_ms2(pitch_rad: float) -> float: + """Light |regen| (positive m/s²) on a downhill / crest. Never Late-hard.""" + if float(pitch_rad) > 0.0: + return CREST_EASE_MS2 + span = max(1e-6, abs(PITCH_DOWN_RAD)) + scale = min(1.0, abs(float(pitch_rad)) / (2.0 * span)) + return CREST_EASE_MS2 + (DOWNHILL_EASE_MS2 - CREST_EASE_MS2) * scale + + +def _at_or_above_max(v_ego_ms: float, v_cruise_ms: float, in_deadband: bool) -> bool: + """True in the MAX deadband or at/above HUD MAX (cruise − deadband). + + Crest / downhill ease uses this — never TRACK_TAPER (~4.5 mph under MAX). + That taper is map-track climb/brake scaling only. Using it as an ease + gate regen'd several mph under MAX and hunted (47–51 under a 54 MAX). + """ + if in_deadband: + return True + return float(v_ego_ms) >= float(v_cruise_ms) - TRACK_DEADBAND_MS + + +def _flattening_crest(pitch_rad: float, prev_pitch_rad: float) -> bool: + """Pitch falling out of a climb — the crest, without map lookahead.""" + return ( + float(prev_pitch_rad) >= PITCH_CREST_RAD + and float(pitch_rad) < float(prev_pitch_rad) + and float(pitch_rad) < PITCH_CLIMB_RAD + ) + + +def apply_hill_climb( + *, + pitch_rad: float, + prev_pitch_rad: float, + v_ego_ms: float, + v_cruise_ms: float, + a_cmd: float, + in_deadband: bool, + hypermile_on: bool, + hill_climb_on: bool, +) -> float: + """Adjust map-track / hold a for grade. Never writes v_cruise / MAX. + + Caller still `min()`s with lead-approach and clips to cruise / lead-close. + Negative a_cmd on an uphill (map brake / MPC / lead) is left alone. + Planner skips +g·sin extras when a valid radar lead is present. + + Climb +g·sin only when clearly under MAX (outside the deadband below). + Crest / downhill ease only at or above MAX — not while still climbing. + """ + if not hill_climb_applies(hypermile_on, hill_climb_on): + return float(a_cmd) + + pitch = float(pitch_rad) + cmd = float(a_cmd) + under_max = (not in_deadband) and (float(v_cruise_ms) - float(v_ego_ms) > TRACK_DEADBAND_MS) + at_or_above_max = _at_or_above_max(v_ego_ms, v_cruise_ms, in_deadband) + + # Map / MPC / lead already braking on an uphill or flat — do not fight. + if cmd < 0.0 and pitch >= 0.0: + return cmd + + if pitch >= PITCH_CLIMB_RAD: + extra = min(CLIMB_EXTRA_MAX_MS2, max(0.0, grade_load_ms2(pitch))) + if under_max: + # Raise climb authority so Accel 1 leftover still walks toward MAX. + if cmd >= 0.0: + return cmd + extra + return cmd + # Deadband / at-or-above MAX: leave map hold (0). Do not invent +g·sin + # that fights the deadband zero and punches past MAX (Accel-5 hunt). + return cmd + + if pitch <= PITCH_DOWN_RAD: + ease = downhill_ease_ms2(pitch) + grade = abs(grade_load_ms2(pitch)) + if under_max and cmd > 0.0: + # Gravity already pulls toward MAX; do not punch +a downhill. + return max(0.0, cmd - min(CLIMB_EXTRA_MAX_MS2, grade)) + if at_or_above_max: + return min(cmd, -ease) + return cmd + + if _flattening_crest(pitch, prev_pitch_rad) and at_or_above_max: + # Early light regen over the top — not a Late 1.20 dump. + return min(cmd, -CREST_EASE_MS2) + + return cmd diff --git a/selfdrive/controls/lib/hypermile.py b/selfdrive/controls/lib/hypermile.py new file mode 100644 index 00000000000000..1a74e236c2dd08 --- /dev/null +++ b/selfdrive/controls/lib/hypermile.py @@ -0,0 +1,640 @@ +"""Hypermile: eco preset for Pre-AP NAP. + +Not a second long controller. Eco snap / Step Down / Hill Climb only. +Stock Follow Distance 1–7 (`NAPFollowDistance`) is shared — Hypermile +does not own follow levels or remap the stalk. + +Settings → NAP → Driving Mannerisms → Hypermile (default Off). +""" +from __future__ import annotations + +import json + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.map_speed_policy import ( + is_cruise_stalk_hold_step, + is_cruise_stalk_tip_step, +) + +# Params +PARAM_HYPERMILE = "NAPHypermile" +PARAM_FOLLOW_DISTANCE = "NAPFollowDistance" +PARAM_FOLLOW_HUD_PENDING = "NAPFollowHudPending" +PARAM_SAVED = "NAPHypermileSaved" +PARAM_STEP_DOWN = "NAPHypermileStepDown" + +# Mileage defer: same 50→80 posted scale as eco, larger drop. Does not +# stack with eco. Hard cap — never more than this under posted. +STEP_DOWN_MPH = 15.0 + +# Stock Follow Distance 1–7 (Driving Mannerisms + stalk behind a lead). +# Same param whether Hypermile is On or Off. Includes closest 1. +FOLLOW_DISTANCE_MIN = 1 +FOLLOW_DISTANCE_MAX = 7 +FOLLOW_DISTANCE_DEFAULT = 4 +NAP_FOLLOW_DISTANCE_RANGE = range(FOLLOW_DISTANCE_MIN, FOLLOW_DISTANCE_MAX + 1) + +# Eco snap. Comfort-biased efficiency — not maximum regen bite. +# Early + light map ease (lookahead Early = 0.55 m/s², starts farther out) +# and a lazy climb (Accel 1). Late lookahead (1.20 m/s²) is the wrong trade: +# it holds speed then dumps regen. Safety / MPC hard brake unchanged. +# Soft-lat / DM / blinker / stock 1–7 follow are not snapped. +# Map offset is *not* snapped to a flat −5 (that forced town 30→25). +# Live eco offset is posted-scaled: 0 at/under 50, −8 at 80, cap −8 above. +ECO_ADAPTIVE_ACCEL = True +ECO_MAP_MODE_FOLLOW = 3 # NAPMapSpeedMode Follow +ECO_MAP_MODE_CAP = 2 +ECO_MAP_OFFSET_MPH = -8 # highway cap; interpolated from 50→80 posted +ECO_OFFSET_START_MPH = 50.0 # posted at/below: no eco drop +ECO_OFFSET_FULL_MPH = 80.0 # posted at/above: full −8 +ECO_MAP_LOOKAHEAD_EARLY = 3 # NAPMapSpeedLookahead Early +ECO_MAP_ACCEL = 1 # laziest Follow climb (lower peak a / jerk) + +SNAPSHOT_KEYS = ( + "NAPAdaptiveAccel", + "NAPMapSpeedMode", + "NAPMapSpeedOffsetMph", + "NAPMapSpeedLookahead", + "NAPMapSpeedAccel", +) + + +def clamp_follow_distance(level) -> int: + try: + return max(FOLLOW_DISTANCE_MIN, min(FOLLOW_DISTANCE_MAX, int(level))) + except (TypeError, ValueError): + return FOLLOW_DISTANCE_DEFAULT + + +def effective_nap_follow_dist(is_preap: bool, nap_follow_dist) -> int | None: + """Follow index the planner/MPC should use, or None to fall back to personality. + + Always stock `NAPFollowDistance` 1–7 on Pre-AP. Hypermile does not + override (no 1–5 band, no ≤50 mph far-gap force). + """ + if not is_preap: + return None + if nap_follow_dist in NAP_FOLLOW_DISTANCE_RANGE: + return int(nap_follow_dist) + return None + + +def follow_distance_hud_text(level: int) -> str: + return f"Follow Distance: {clamp_follow_distance(level)}" + + +def poll_follow_distance_hud(prev, current) -> tuple[int | None, bool]: + """Seed-then-announce Follow Distance HUD. + + First successful read only stores the baseline (no toast on process + start). Every later stalk/settings change of the 1–7 slider announces. + """ + if current is None: + return prev, False + try: + cur = clamp_follow_distance(current) + except (TypeError, ValueError): + return prev, False + if prev is None: + return cur, False + try: + return cur, cur != int(prev) + except (TypeError, ValueError): + return cur, True + + +def _get_int(params, key: str, default: int) -> int: + try: + raw = params.get(key, return_default=True) + if raw is None or raw == "": + return default + if isinstance(raw, bytes): + raw = raw.decode("utf-8", errors="ignore") + return int(raw) + except Exception: + return default + + +def _get_bool(params, key: str, default: bool = False) -> bool: + try: + return bool(params.get_bool(key)) + except Exception: + return default + + +def _get_str(params, key: str) -> str: + try: + raw = params.get(key, return_default=True) + except Exception: + return "" + if raw is None: + return "" + if isinstance(raw, bytes): + return raw.decode("utf-8", errors="ignore") + return str(raw) + + +def read_hypermile_params(params) -> bool: + """Hypermile On. Unknown / test doubles → Off.""" + return _get_bool(params, PARAM_HYPERMILE, False) + + +def read_follow_distance(params) -> int: + """Stock Follow Distance 1–7 (`NAPFollowDistance`). Default 4.""" + return clamp_follow_distance(_get_int(params, PARAM_FOLLOW_DISTANCE, FOLLOW_DISTANCE_DEFAULT)) + + +def read_hypermile_step_down(params) -> bool: + """Opt-in mileage defer. Default Off. Inert unless Hypermile is On.""" + return _get_bool(params, PARAM_STEP_DOWN, False) + + +def step_down_applies(hypermile_on: bool, step_down_on: bool) -> bool: + return bool(hypermile_on) and bool(step_down_on) + + +def _posted_mph(posted_kph: float | None) -> float | None: + if posted_kph is None: + return None + try: + pk = float(posted_kph) + except (TypeError, ValueError): + return None + if pk <= 0: + return None + return pk * CV.KPH_TO_MPH + + +def maps_posted_known(posted_kph: float | None, maps_posted: bool | None = None) -> bool: + """True only with maps present and a real OSM/posted limit. + + Same spirit as sticky MAX: do not invent posted when maps are off, + unmatched, or speedLimit is unknown / non-positive. + """ + if maps_posted is False: + return False + return _posted_mph(posted_kph) is not None + + +def posted_scale_offset_mph(posted_mph: float | None, full_offset_mph: float) -> float: + """0 at/under 50, linear to full_offset at 80, cap above 80. + + Unknown / non-positive posted → 0 (do not invent a town drop). + """ + if posted_mph is None: + return 0.0 + try: + posted = float(posted_mph) + except (TypeError, ValueError): + return 0.0 + if posted <= ECO_OFFSET_START_MPH: + return 0.0 + if posted >= ECO_OFFSET_FULL_MPH: + return float(full_offset_mph) + span = ECO_OFFSET_FULL_MPH - ECO_OFFSET_START_MPH + t = (float(posted) - ECO_OFFSET_START_MPH) / span + return float(full_offset_mph) * t + + +def eco_map_offset_mph(posted_mph: float | None) -> float: + """Posted-scaled Hypermile eco offset (mph). Town stays posted. + + ≤50 → 0; 80 → −8; >80 → −8 cap; linear 50→80. + """ + return posted_scale_offset_mph(posted_mph, ECO_MAP_OFFSET_MPH) + + +def step_down_offset_mph(posted_mph: float | None) -> float: + """Posted-scaled Step Down offset (mph). Same breakpoints as eco, −15 at 80. + + ≤50 → 0; 80 → −15; >80 → −15 cap. Replaces eco — does not stack. + """ + return posted_scale_offset_mph(posted_mph, -STEP_DOWN_MPH) + + +def map_target_offset_kph( + map_offset_kph: float, + *, + hypermile_on: bool, + step_down_on: bool, + posted_kph: float | None = None, + maps_posted: bool | None = None, +) -> float: + """Offset added to raw OSM posted for Cap/Follow. + + Hypermile eco / Step Down apply only when maps are present and the + OSM/posted limit is known. Maps off, no match, or unknown posted → 0 + (no invented drop). Hypermile On + Step Down On: posted-scaled −15 at + 80 (0 at/under 50), replacing eco so 80→65. Step Down Off: eco + (≤50 → 0, 80+ → −8). Hypermile Off: keep map_offset_kph. + """ + if hypermile_on and not maps_posted_known(posted_kph, maps_posted): + return 0.0 + posted_mph = _posted_mph(posted_kph) + if step_down_applies(hypermile_on, step_down_on): + return step_down_offset_mph(posted_mph) * CV.MPH_TO_KPH + if hypermile_on: + return eco_map_offset_mph(posted_mph) * CV.MPH_TO_KPH + return float(map_offset_kph) + + +def stepped_map_target_kph( + raw_posted_kph: float, + *, + hypermile_on: bool, + step_down_on: bool, + map_offset_kph: float = 0.0, +) -> float: + """Map MAX target from raw posted (kph). Step-down only lowers, ≤15 mph under.""" + raw = float(raw_posted_kph) + off = map_target_offset_kph( + map_offset_kph, hypermile_on=hypermile_on, step_down_on=step_down_on, + posted_kph=raw, + ) + target = raw + off + if step_down_applies(hypermile_on, step_down_on): + floor = raw - STEP_DOWN_MPH * CV.MPH_TO_KPH + target = min(raw, max(floor, target)) + return target + + +def read_snapshot_values(params) -> dict: + return { + "NAPAdaptiveAccel": _get_bool(params, "NAPAdaptiveAccel", True), + "NAPMapSpeedMode": _get_int(params, "NAPMapSpeedMode", 0), + "NAPMapSpeedOffsetMph": _get_int(params, "NAPMapSpeedOffsetMph", 0), + "NAPMapSpeedLookahead": _get_int(params, "NAPMapSpeedLookahead", 2), + "NAPMapSpeedAccel": _get_int(params, "NAPMapSpeedAccel", 5), + } + + +def eco_preset_from(current: dict) -> dict: + """Comfort-biased eco knobs. Keep Cap if already Cap; Off/Display → Follow. + + Always Early lookahead + Accel 1. Do not keep Late (late hard regen). + Do not write NAPMapSpeedOffsetMph — a flat −5 drops town 30→25. + Live eco offset is posted-scaled in map_target_offset_kph. Soft-lat / DM + not included. + """ + mode = int(current.get("NAPMapSpeedMode", 0) or 0) + if mode not in (ECO_MAP_MODE_CAP, ECO_MAP_MODE_FOLLOW): + mode = ECO_MAP_MODE_FOLLOW + return { + "NAPAdaptiveAccel": ECO_ADAPTIVE_ACCEL, + "NAPMapSpeedMode": mode, + "NAPMapSpeedLookahead": ECO_MAP_LOOKAHEAD_EARLY, + "NAPMapSpeedAccel": ECO_MAP_ACCEL, + } + + +def _put_values(params, values: dict) -> None: + for key, value in values.items(): + if isinstance(value, bool): + params.put_bool(key, value) + else: + params.put(key, int(value)) + + +def apply_hypermile_toggle(params, want_on: bool) -> bool: + """Snap eco on rising On; restore snapshot on falling Off. Idempotent. + + Returns the resulting On state. Soft-lat / DM / blinker / stock 1–7 + Follow Distance stay untouched (not snapped, not restored). + """ + was_on = _get_bool(params, PARAM_HYPERMILE, False) + if want_on and not was_on: + current = read_snapshot_values(params) + params.put(PARAM_SAVED, json.dumps(current, separators=(",", ":"))) + _put_values(params, eco_preset_from(current)) + params.put_bool(PARAM_HYPERMILE, True) + return True + if (not want_on) and was_on: + raw = _get_str(params, PARAM_SAVED) + if raw: + try: + saved = json.loads(raw) + if isinstance(saved, dict): + restore = {k: saved[k] for k in SNAPSHOT_KEYS if k in saved} + if restore: + _put_values(params, restore) + except (TypeError, ValueError, json.JSONDecodeError): + pass + try: + params.remove(PARAM_SAVED) + except Exception: + params.put(PARAM_SAVED, "") + params.put_bool(PARAM_HYPERMILE, False) + return False + params.put_bool(PARAM_HYPERMILE, bool(want_on)) + return bool(want_on) + + +def stalk_adjusts_follow(*, has_lead: bool) -> bool: + """Stalk tip remaps stock Follow Distance 1–7 when a radar lead is present. + + Same whether Hypermile is On or Off. Full press (5 mph) still steps MAX. + No lead: leave Pre-AP stalk as MAX / cruise-speed adjust. + """ + return bool(has_lead) + + +def step_follow_distance(level: int, closer: bool) -> int: + """Stalk up = closer (toward 1). Stalk down = farther (toward 7).""" + delta = -1 if closer else 1 + return clamp_follow_distance(int(level) + delta) + + +def stalk_is_closer(button_closer: bool | None, raw_delta_kph: float | None) -> bool | None: + """True=closer (RES+/up), False=farther (RES−/down), None=not a stalk edge.""" + if button_closer is True: + return True + if button_closer is False: + return False + if raw_delta_kph is None: + return None + if abs(float(raw_delta_kph)) < 0.3: + return None + return float(raw_delta_kph) > 0.0 + + +# Pre-AP STW_ACTN_RQ.SpdCtrlLvr_Stat / CruiseButtons. buttonEvents collapse +# tip and 2nd detent to the same accelCruise/decelCruise, so detent is the +# hardware source of truth when present. +CRUISE_STALK_IDLE = 0 +CRUISE_STALK_UP_2ND = 4 # UP_2ND / RES_ACCEL_2ND +5 +CRUISE_STALK_DN_2ND = 8 # DN_2ND / DECEL_2ND −5 +CRUISE_STALK_UP_1ST = 16 # UP_1ST / RES_ACCEL +1 +CRUISE_STALK_DN_1ST = 32 # DN_1ST / DECEL_SET −1 + + +def cruise_detent_closer(detent: int | None) -> bool | None: + if detent in (CRUISE_STALK_UP_1ST, CRUISE_STALK_UP_2ND): + return True + if detent in (CRUISE_STALK_DN_1ST, CRUISE_STALK_DN_2ND): + return False + return None + + +def cruise_detent_is_tip(detent: int | None) -> bool: + return detent in (CRUISE_STALK_UP_1ST, CRUISE_STALK_DN_1ST) + + +def cruise_detent_is_hold(detent: int | None) -> bool: + return detent in (CRUISE_STALK_UP_2ND, CRUISE_STALK_DN_2ND) + + +def cruise_detent_is_idle(detent: int | None) -> bool: + return detent == CRUISE_STALK_IDLE + + +class FollowStalkGesture: + """Classify Pre-AP cruise-stalk tip vs full press, like ALC tip-vs-hold. + + A physical full press always walks through first detent. Follow Distance + is committed only when the lever returns to IDLE after a first-detent + tip that never hit 2nd detent (or a clear 5 mph hold step). The tip + frame's 1 mph MAX is undone immediately so 2nd detent's +5/−5 applies + from the original set. buttonEvents alone are not a tip. + """ + + def __init__(self): + self.reset() + + def reset(self): + self.pending_closer: bool | None = None + self.saw_hold = False + self.undid = False + + @property + def is_pending(self) -> bool: + return self.pending_closer is not None and not self.saw_hold + + def update( + self, + *, + has_lead: bool, + detent: int | None = None, + button_closer: bool | None = None, + button_released: bool = False, + raw_kph: float | None = None, + prev_raw_kph: float | None = None, + ) -> tuple[bool, bool | None, float | None]: + """(commit_follow, closer, undo_raw_kph). Does not write params.""" + if not stalk_adjusts_follow(has_lead=has_lead): + self.reset() + return False, None, None + + have_raw = raw_kph is not None and prev_raw_kph is not None + hold_step = have_raw and is_cruise_stalk_hold_step(prev_raw_kph, raw_kph) + tip_step = have_raw and is_cruise_stalk_tip_step(prev_raw_kph, raw_kph) + is_hold = cruise_detent_is_hold(detent) or hold_step + is_tip = cruise_detent_is_tip(detent) or tip_step + closer = cruise_detent_closer(detent) + if closer is None: + delta = (float(raw_kph) - float(prev_raw_kph)) if tip_step else None + closer = stalk_is_closer(button_closer, delta) + + if is_hold: + self.saw_hold = True + self.pending_closer = None + return False, None, None + + # Second press while already pending, no detent / 5 mph: 2nd detent. + if ( + self.pending_closer is not None + and button_closer is not None + and detent is None + and not tip_step + ): + self.saw_hold = True + self.pending_closer = None + return False, None, None + + undo = None + if is_tip and not self.saw_hold: + if closer is not None: + self.pending_closer = closer + if tip_step and not self.undid: + undo = float(prev_raw_kph) + self.undid = True + + if ( + not is_tip + and not is_hold + and button_closer is not None + and self.pending_closer is None + and not self.saw_hold + ): + self.pending_closer = button_closer + + is_idle = cruise_detent_is_idle(detent) or (detent is None and button_released) + if is_idle: + if self.pending_closer is not None and not self.saw_hold: + closer_out = self.pending_closer + self.reset() + return True, closer_out, None + self.reset() + return False, None, None + + return False, None, undo + + +def detect_follow_stalk( + *, + has_lead: bool, + button_closer: bool | None, + raw_kph: float | None, + prev_raw_kph: float | None, + detent: int | None = None, + button_released: bool = False, + gesture: FollowStalkGesture | None = None, +) -> tuple[bool, bool | None, float | None]: + """(commit_follow, closer, undo_raw_kph). Does not write params. + + Lead + first-detent tip (~1 mph / 1 kph): undo that frame's MAX and + commit Follow only after the lever returns to IDLE without a 2nd + detent. Lead + full press (2nd detent / ~5 mph): leave MAX; never a + follow stalk, even if the press passed through first detent. + Pre-AP buttonEvents do not distinguish tip vs hold — do not treat a + button-only press as a completed tip. + """ + g = gesture if gesture is not None else FollowStalkGesture() + return g.update( + has_lead=has_lead, + detent=detent, + button_closer=button_closer, + button_released=button_released, + raw_kph=raw_kph, + prev_raw_kph=prev_raw_kph, + ) + + +def persist_follow_distance(params, closer: bool, v_ego=None, v_cruise=None, + has_lead=False, engaged=False) -> int: + """Step city or highway Follow Distance (and HUD NAPFollowDistance). + + With v_ego, the stalk band is stepped from MAX: Highway when set speed + is 50 mph or higher, City when it is under 50. Traveled speed is the + fallback only when MAX is unset, invalid, or 0. Lead / engaged do not + pick the param. Without speed (tests), all three keys stay in sync. + Always request the HUD (including at 1/7). HUD `NAPFollowDistance` is + the level just written. + """ + from openpilot.selfdrive.controls.lib.follow_distance import ( + PARAM_FOLLOW_CITY, + PARAM_FOLLOW_HWY, + follow_stalk_band_is_highway, + migrate_follow_distance_params, + ) + migrate_follow_distance_params(params) + if v_ego is not None: + key = PARAM_FOLLOW_HWY if follow_stalk_band_is_highway( + v_ego, v_cruise, + ) else PARAM_FOLLOW_CITY + try: + raw = params.get(key, return_default=True) + except Exception: + raw = None + level = clamp_follow_distance(raw) + new_level = step_follow_distance(level, closer) + if new_level != level: + params.put(key, int(new_level)) + params.put(PARAM_FOLLOW_DISTANCE, int(new_level)) + else: + level = read_follow_distance(params) + new_level = step_follow_distance(level, closer) + if new_level != level: + params.put(PARAM_FOLLOW_DISTANCE, int(new_level)) + try: + params.put(PARAM_FOLLOW_CITY, int(new_level)) + params.put(PARAM_FOLLOW_HWY, int(new_level)) + except Exception: + pass + try: + params.put_bool(PARAM_FOLLOW_HUD_PENDING, True) + except Exception: + pass + return new_level + + +def consume_follow_stalk( + params, + *, + has_lead: bool, + button_closer: bool | None, + raw_kph: float | None, + prev_raw_kph: float | None, + apply: bool = True, + detent: int | None = None, + button_released: bool = False, + gesture: FollowStalkGesture | None = None, + v_ego=None, + v_cruise=None, +) -> tuple[int | None, float | None]: + """If this stalk edge completes a Follow Distance tip, persist it. + + Returns (new_or_same_level, undo_raw_kph). undo_raw_kph is the previous + MAX on the tip-press frame so card can write pedal_speed back. Commit + (level not None) happens on IDLE after a tip-only gesture. (None, None) + means leave stalk as MAX (no lead, full press, or tip still held). + apply=False detects without writing (0.25 s stalk cooldown). + """ + is_stalk, closer, undo = detect_follow_stalk( + has_lead=has_lead, + button_closer=button_closer, + raw_kph=raw_kph, + prev_raw_kph=prev_raw_kph, + detent=detent, + button_released=button_released, + gesture=gesture, + ) + if not is_stalk: + return None, undo + if apply: + return persist_follow_distance(params, bool(closer), v_ego=v_ego, v_cruise=v_cruise), undo + return read_follow_distance(params), undo + + +def _button_event_name(be) -> str: + typ = getattr(be, "type", None) + return str(getattr(typ, "name", typ)).lower().replace("_", "") + + +def _is_cruise_adjust_button(name: str) -> bool: + return ( + "accelcruise" in name or "decelcruise" in name + or name in ("accel", "resaccel", "setaccel", "decel", "decelset") + ) + + +def button_event_closer(button_events) -> bool | None: + """Parse CarState.buttonEvents: accelCruise → closer, decelCruise → farther. + + Press edge only. A tap that also emits a release must not step twice. + Pre-AP maps both tip and 2nd detent to these types — not a tip vs hold. + """ + for be in button_events or []: + try: + if not bool(getattr(be, "pressed", True)): + continue + name = _button_event_name(be) + if "accelcruise" in name or name in ("accel", "resaccel", "setaccel"): + return True + if "decelcruise" in name or name in ("decel", "decelset"): + return False + except Exception: + continue + return None + + +def button_event_released(button_events) -> bool: + """True on accel/decelCruise release. Used when raw detent is unavailable.""" + for be in button_events or []: + try: + if bool(getattr(be, "pressed", True)): + continue + if _is_cruise_adjust_button(_button_event_name(be)): + return True + except Exception: + continue + return False diff --git a/selfdrive/controls/lib/lane_change_nudge.py b/selfdrive/controls/lib/lane_change_nudge.py new file mode 100644 index 00000000000000..08c1146a7394d6 --- /dev/null +++ b/selfdrive/controls/lib/lane_change_nudge.py @@ -0,0 +1,285 @@ +"""Tipped lane-change confirm vs emergency yank. + +A quick stalk tip still arms ALC, and a latched stalk is still a driver +turn. Those splits are unchanged. While the tip's lane change is armed +or in progress (preLaneChange, laneChangeStarting, or finishing) — +including the ~1 s lamp flash-dark gap, because the lane-change +direction stays latched while the lamps blink off — driver torque in +the *same* direction is only the confirm nudge. + +That confirm must not soft-yield, latch a driver turn, or +steering-disengage, at any torque inside the lines below. + +An emergency yank, in either direction, still takes over immediately +(release lateral, cancel the lane change, allow panda to drop). It is +clearly past a nudge: + +* EPAS hands-on level 3, the maximum the car reports. Level 2 is + ``HANDS_ON_DISENGAGE_LEVEL`` and is still only a confirm during this + window. Outside a tipped lane change, level >= 2 disengages as today. + During an armed / tipped lane change, level 3 with torque in the + lane-change direction is not an emergency by itself (firm confirms at + ~1.9-2.3 Nm reach level 3); it still needs one of the torque lines. + Opposite-direction level 3 is still an emergency. +* |torsion| above ``EMERGENCY_TORQUE_NM`` (2.5 Nm) held for + ``EMERGENCY_SUSTAIN_S`` (0.10 s) *against* the lane-change direction + (or outside a tipped lane change). Logged confirms peak 1.0-2.3 Nm. +* Fast torque rise. There is no torsion-rate signal (``steeringRateDeg`` + is wheel rate). |torsion| reaching ``EMERGENCY_RISE_NM`` (2.2 Nm, 4x the + 0.55 Nm soft-lat floor) within ``EMERGENCY_RISE_WINDOW_S`` (0.25 s) of + being under the floor, and staying above 2.2 Nm for 0.10 s. The Sep 28 + E1 (-1.88 Nm in ~100 ms) and E3 (+1.77 Nm in ~100-200 ms) confirms + tripped the old 1.65 Nm / 150 ms single-frame line. + +A genuine hard yank (0 -> 3.5 Nm in 50 ms) releases ~0.13 s after onset. +An emergency is a full disengage: car_specific adds steerDisengage +(USER_DISABLE, lat and long) and the Pre-AP engagement tears cruise down. + +Driver takeover (same direction, sustained). During a tipped lane change, +|torsion| above ``EMERGENCY_TORQUE_NM`` for ``TAKEOVER_SUSTAIN_S`` (0.30 s) +*in the lane-change direction* without a fast rise is the driver steering through +(e.g. turning at the intersection before a tip into a turn lane finishes). +controlsd yields lateral through the soft-lat handoff until the hands +come off (``TAKEOVER_HANDS_OFF_S``); a target-locked change just suspends +and resumes, like any ordinary lateral release. Whether it is a *turn* +(which ends the change) is decided by wheel angle in lane_change_turn, +not torque. It is not an emergency: no steerDisengage, openpilot and +longitudinal stay engaged. A sudden spike (the fast-rise line) still is. + +Soft confirm (armed only). While ``preLaneChange`` is armed after a stalk +tip and v_ego >= 20 mph, same-direction torsion >= ``SOFT_CONFIRM_NM`` +(0.65 Nm) sustained ``SOFT_CONFIRM_SUSTAIN_S`` (0.15 s) confirms even when +``steeringPressed`` (1.0 Nm, debounced) is still false. Logged first +attempts that did not reach steeringPressed sat at 0.7-1.0 Nm for +0.2-0.3 s; hands-off lane-keep torsion is |tq| p99.9 ~0.5 Nm and 0.65 Nm +held that long is ~0.8/h per direction. The global steeringPressed +threshold is unchanged. + +Panda firmware must be reflashed. ``tesla_preap_blinker.h`` keeps +``controls_allowed`` for hands-on level 2 during a tipped-ALC flash gap +and does **not** suppress hands-on level 3 (unchanged here: a level-3 +same-direction confirm inside the flash-dark gap can still let panda drop +controls; the lamp-lit phase blocks it). +""" + +from opendbc.car.tesla.values import STEER_THRESHOLD + +# Same factor as driver_lateral_handoff.SOFT_YIELD_TRIGGER_NM. Kept here so +# this module does not import the handoff (the handoff imports us). +SOFT_YIELD_TRIGGER_NM = 0.55 * float(STEER_THRESHOLD) + +# EPAS_handsOnLevel top value. Level 2 remains HANDS_ON_DISENGAGE_LEVEL. +EMERGENCY_HANDS_ON_LEVEL = 3 + +# Clearly past a firm confirm (logged confirm peaks 1.0-2.3 Nm). +EMERGENCY_TORQUE_NM = 2.5 * float(STEER_THRESHOLD) + +# From under the soft-lat floor to 4x that floor within 0.25 s. +EMERGENCY_RISE_WINDOW_S = 0.250 +EMERGENCY_RISE_NM = 4.0 * SOFT_YIELD_TRIGGER_NM + +# |torsion| must stay above the emergency line this long (not one frame). +EMERGENCY_SUSTAIN_S = 0.10 + +# Same-direction over-torque held this long during a tipped lane change is +# a driver takeover (turning through), not a hard confirm. Logged hard +# confirms (peaks 2.3-3.3 Nm) stay above 2.5 Nm for <= ~0.1 s. +TAKEOVER_SUSTAIN_S = 0.30 +# Takeover yield holds until |torsion| < soft-lat floor and hands-on < 1 +# for this long (same as the handoff's hands-off confirm). +TAKEOVER_HANDS_OFF_S = 0.15 + +# Armed-only soft confirm (preLaneChange, v_ego >= 20 mph, same direction). +SOFT_CONFIRM_NM = 0.65 * float(STEER_THRESHOLD) +SOFT_CONFIRM_SUSTAIN_S = 0.15 + + +def torque_is_same_direction(torque_nm: float, direction: int) -> bool: + """Positive torsion is left (1); negative is right (2). Matches DesireHelper.""" + torque = float(torque_nm) + if direction == 1: + return torque > 0.0 + if direction == 2: + return torque < 0.0 + return False + + +def is_emergency_yank(*, torque_nm: float, hands_on_level: int, fast_rise: bool, + over_torque: bool | None = None, alc_direction: int = 0) -> bool: + """True when the driver is past a lane-change nudge. + + ``over_torque`` is ``EmergencyYankTracker.over_torque`` (sustained). None + falls back to the instantaneous line. ``alc_direction`` (1 left, 2 right) + is set only while a tipped lane change is armed or in progress; then a + same-direction push at hands-on level 3 needs a torque line too. + """ + same_direction = torque_is_same_direction(torque_nm, alc_direction) + if int(hands_on_level or 0) >= EMERGENCY_HANDS_ON_LEVEL: + if not same_direction: + return True + if over_torque is None: + over_torque = abs(float(torque_nm)) > EMERGENCY_TORQUE_NM + # Sustained same-direction over-torque is a takeover, not an emergency. + if over_torque and not same_direction: + return True + return bool(fast_rise) + + +def is_driver_takeover(*, torque_nm: float, over_torque_s: float, + alc_direction: int) -> bool: + """Sustained same-direction over-torque during a tipped lane change. + + ``over_torque_s`` is ``EmergencyYankTracker.over_torque_s``. Yields + lateral (a target-locked change suspends); never a steerDisengage. + """ + if alc_direction not in (1, 2): + return False + if float(over_torque_s) < TAKEOVER_SUSTAIN_S - 1e-9: + return False + return torque_is_same_direction(torque_nm, alc_direction) + + +def steer_disengage_this_frame(*, confirm: bool, release: bool, release_prev: bool, + disengage_edge: bool, blocks: bool, + lat_full_control: bool = True) -> bool: + """True when car_specific should add EventName.steerDisengage. + + A same-direction confirm never does, including a lamp flash-dark gap. + An emergency yank (``release``) does, on its rising edge. Otherwise the + existing hands-on edge fires only when the blinker gate is open. + + ``lat_full_control`` False means lateral was already yielded to the driver + (inferred from the 0x488 type-1 history, see opendbc preap/lat_yield.py): + wheel input is then a driver maneuver and never raises steerDisengage. + """ + if confirm or not lat_full_control: + return False + return (bool(release) and not release_prev) or (bool(disengage_edge) and not blocks) + + +def tipped_lane_change_driver_release(*, same_direction: bool, emergency: bool) -> bool: + """Whether torque during a tipped lane change should release lateral. + + Emergency yank always releases, including a same-direction yank during ALC. + Same-direction nudge during tipped ALC is the lane-change confirm, not a takeover. + Opposite torque is not a confirm; the caller keeps today's yield / cancel. + """ + # Emergency yank always releases, including a same-direction yank during ALC. + if emergency: + return True + # Same-direction nudge during tipped ALC is the lane-change confirm, not a takeover. + if same_direction: + return False + return False + + +class EmergencyYankTracker: + """Sustained fast rise / sustained over-torque detector. + + ``update`` returns ``fast_rise``: |torsion| crossed ``EMERGENCY_RISE_NM`` + within ``EMERGENCY_RISE_WINDOW_S`` of the last sample under the soft-lat + floor and has stayed at or above that line for ``EMERGENCY_SUSTAIN_S``. + ``over_torque``: |torsion| above ``EMERGENCY_TORQUE_NM`` for + ``EMERGENCY_SUSTAIN_S``. + """ + + def __init__(self): + self.reset() + + def reset(self): + self._t = 0.0 + self._last_low_t: float | None = None + self._rise_cross_t: float | None = None + self._rise_ok = False + self._over_t: float | None = None + self.fast_rise = False + self.over_torque = False + self.over_torque_s = 0.0 + + def update(self, torque_nm: float, dt: float) -> bool: + self._t += max(float(dt), 0.0) + t = self._t + mag = abs(float(torque_nm)) + if mag < SOFT_YIELD_TRIGGER_NM: + self._last_low_t = t + if mag >= EMERGENCY_RISE_NM: + if self._rise_cross_t is None: + self._rise_cross_t = t + self._rise_ok = (self._last_low_t is not None and + (t - self._last_low_t) <= EMERGENCY_RISE_WINDOW_S + 1e-9) + else: + self._rise_cross_t = None + self._rise_ok = False + if mag > EMERGENCY_TORQUE_NM: + if self._over_t is None: + self._over_t = t + else: + self._over_t = None + self.fast_rise = (self._rise_cross_t is not None and self._rise_ok and + (t - self._rise_cross_t) >= EMERGENCY_SUSTAIN_S - 1e-9) + self.over_torque_s = 0.0 if self._over_t is None else t - self._over_t + self.over_torque = (self._over_t is not None and + self.over_torque_s >= EMERGENCY_SUSTAIN_S - 1e-9) + return self.fast_rise + + +class SoftConfirmTracker: + """Armed-only same-direction confirm below steeringPressed. + + Counts continuous time with torsion >= ``SOFT_CONFIRM_NM`` in the + lane-change direction. Anything else (disarmed, below speed, weaker or + opposite torque) resets the timer. + """ + + def __init__(self): + self.reset() + + def reset(self): + self._held_s = 0.0 + + def update(self, *, torque_nm: float, direction: int, armed: bool, dt: float) -> bool: + torque = float(torque_nm) + signed = torque if direction == 1 else (-torque if direction == 2 else 0.0) + if not armed or signed < SOFT_CONFIRM_NM: + self._held_s = 0.0 + return False + self._held_s += max(float(dt), 0.0) + return self._held_s >= SOFT_CONFIRM_SUSTAIN_S - 1e-9 + + +class TippedLaneChangeTorque: + """controlsd: driver torque vs a tipped lane change, per 100 Hz frame. + + ``emergency``: full release (spike, opposite over-torque, opposite + hands-on 3). ``takeover``: sustained same-direction over-torque, latched + until hands are off for TAKEOVER_HANDS_OFF_S (or the lane change is + off). ``release``: yield lateral now (either). + ``confirm``: same-direction torque that is neither. + """ + + def __init__(self): + self.yank = EmergencyYankTracker() + self.emergency = False + self.takeover = False + self._hands_off_s = 0.0 + self.release = False + self.confirm = False + + def update(self, *, torque_nm: float, hands_on_level: int, direction: int, + tipped: bool, dt: float) -> None: + fast_rise = self.yank.update(torque_nm, dt) + alc_direction = direction if tipped else 0 + self.emergency = is_emergency_yank( + torque_nm=torque_nm, hands_on_level=hands_on_level, fast_rise=fast_rise, + over_torque=self.yank.over_torque, alc_direction=alc_direction) + takeover_now = is_driver_takeover( + torque_nm=torque_nm, over_torque_s=self.yank.over_torque_s, alc_direction=alc_direction) + hands_off = (abs(float(torque_nm)) < SOFT_YIELD_TRIGGER_NM and + int(hands_on_level or 0) < 1) + self._hands_off_s = self._hands_off_s + max(float(dt), 0.0) if hands_off else 0.0 + if self.takeover and self._hands_off_s >= TAKEOVER_HANDS_OFF_S - 1e-9: + self.takeover = False + self.takeover = bool(tipped) and (self.takeover or takeover_now) + self.release = bool(tipped) and (self.emergency or self.takeover) + self.confirm = (bool(tipped) and torque_is_same_direction(torque_nm, direction) + and not self.release) diff --git a/selfdrive/controls/lib/lane_change_target.py b/selfdrive/controls/lib/lane_change_target.py new file mode 100644 index 00000000000000..b2b3bfbcfe6940 --- /dev/null +++ b/selfdrive/controls/lib/lane_change_target.py @@ -0,0 +1,208 @@ +"""Target lock for a tipped lane change. + +When a tipped lane change starts (preLaneChange -> laneChangeStarting on +the confirm nudge), DesireHelper locks a target: the direction and the +lane line the car must cross. The line is taken from modelV2 laneLines: +the ego left line (laneLines[1]) for a left change, the ego right line +(laneLines[2]) for a right change. + +Frame: modelV2 laneLines y is in the device frame, +y to the right, so +the ego left line is negative and the ego right line positive. y[0] +(the closest point ahead) is the lateral offset from the car. + +The locked line is followed by continuity. The four laneLines slots +re-index as the car crosses a line, so each model frame the tracked line +is the confident line closest to where it was last frame (within +LINE_MATCH_GATE_M). From it: + +* ``dist_to_line_m``: signed distance still to travel to the line, in + the change direction. Positive before the crossing, negative after. +* lane width: ego right - ego left when both are confident and sane, + otherwise the last good width. +* ``progress`` in lane widths from the original lane center, measured + toward the target: 0.0 = centered in the original lane, 0.5 = on the + line, 1.0 = centered in the target lane. + +The change is complete when the line has been crossed and the car is +within CENTERED_TOL_M of the target lane center for CENTERED_HOLD_S. +Completion is geometry, not a timer. + +If the tracked line is not confidently seen for LOW_CONFIDENCE_CANCEL_S, +the lock reports low confidence and the caller cancels rather than +guessing which lane the car is in. + +Lock needs confidence only on the line being crossed (left line for a +left change, right line for a right change). A weak far line does not +matter: the lane width falls back to the last good width, else 3.7 m. +When the crossing line is weak, lock returns None and DesireHelper keeps +the change armed and retries (LOCK_RETRY_S), instead of cancelling. +""" + +# Min laneLineProbs for a line to count as seen. +LANE_LINE_MIN_PROB = 0.4 +# Tracked line unseen this long -> cancel. Short dropouts are tolerated. +LOW_CONFIDENCE_CANCEL_S = 1.0 +# Total time from lock (including released / suspended time). +TARGET_LOCK_TIMEOUT_S = 12.0 +# Within this of the target lane center counts as centered. +CENTERED_TOL_M = 0.30 +CENTERED_HOLD_S = 0.5 +# Past the line by this much after a crossing before drifting back +# re-enters laneChangeStarting. +RECROSS_MARGIN_M = 0.20 +# Continuity gate for the tracked line between model frames. +LINE_MATCH_GATE_M = 1.2 + +# Lat up with no gain in progress for this long -> re-pulse the desire. +STALL_REPULSE_S = 3.0 +STALL_PROGRESS_LANES = 0.05 + +# A confirmed change whose crossing line is not seen keeps retrying the +# lock this long (a brief probability dip is not a refusal). After that the +# change stays armed (7 s window) and "Lane lines unclear" is shown. +LOCK_RETRY_S = 1.0 +# modelV2.meta.laneChangeSignalsRemaining is otherwise a countdown that +# nothing reads. This value flags "lock refused, lane lines unclear" to +# selfdrived without a capnp change. +LANE_LINES_UNCLEAR_SIGNAL = 255 + +DEFAULT_LANE_WIDTH_M = 3.7 +MIN_LANE_WIDTH_M = 2.4 +MAX_LANE_WIDTH_M = 5.0 + +LEFT = 1 +RIGHT = 2 + + +def lane_line_offsets(model): + """(ys, probs) from a modelV2-like object, or None if unusable. + + ys[i] is laneLines[i].y[0] (m, +right); probs[i] is laneLineProbs[i]. + """ + if model is None: + return None + try: + lines = list(model.laneLines) + probs = [float(p) for p in model.laneLineProbs] + ys = [float(line.y[0]) if len(line.y) else 0.0 for line in lines] + except Exception: + return None + if len(ys) < 4 or len(probs) < 4: + return None + return ys[:4], probs[:4] + + +def _sane_width(w: float) -> bool: + return MIN_LANE_WIDTH_M <= w <= MAX_LANE_WIDTH_M + + +class LaneChangeTarget: + def __init__(self, direction: int, line_y: float, lane_width: float): + self.direction = int(direction) + self.line_y = float(line_y) + self.lane_width = float(lane_width) + self.low_conf_s = 0.0 + self.centered_s = 0.0 + self.age_s = 0.0 + + @classmethod + def lock(cls, direction: int, offsets, last_width: float | None = None): + """Lock the ego line in ``direction``; None if the crossing line is not confident. + + Only the line being crossed needs LANE_LINE_MIN_PROB. With a weak far + line the width is ``last_width`` (if sane) or DEFAULT_LANE_WIDTH_M. + """ + if offsets is None or direction not in (LEFT, RIGHT): + return None + ys, probs = offsets + left_y, right_y = ys[1], ys[2] + if probs[1] < LANE_LINE_MIN_PROB or probs[2] < LANE_LINE_MIN_PROB: + # An ego line is weak. Only the line being crossed has to be seen. + if probs[1 if direction == LEFT else 2] < LANE_LINE_MIN_PROB: + return None + if direction == LEFT and not left_y < 0.0: + return None + if direction == RIGHT and not right_y > 0.0: + return None + if abs(left_y if direction == LEFT else right_y) > MAX_LANE_WIDTH_M: + return None + width = last_width if last_width is not None and _sane_width(last_width) else DEFAULT_LANE_WIDTH_M + else: + if not (left_y < 0.0 < right_y): + return None + width = right_y - left_y + if not _sane_width(width): + width = DEFAULT_LANE_WIDTH_M + line_y = left_y if direction == LEFT else right_y + return cls(direction, line_y, width) + + @staticmethod + def good_width(offsets): + """Ego lane width when both ego lines are confident and sane, else None.""" + if offsets is None: + return None + ys, probs = offsets + if min(probs[1], probs[2]) < LANE_LINE_MIN_PROB: + return None + if not (ys[1] < 0.0 < ys[2]): + return None + width = ys[2] - ys[1] + return width if _sane_width(width) else None + + @property + def dist_to_line_m(self) -> float: + return -self.line_y if self.direction == LEFT else self.line_y + + @property + def crossed(self) -> bool: + return self.dist_to_line_m < 0.0 + + @property + def progress(self) -> float: + return 0.5 - self.dist_to_line_m / self.lane_width + + @property + def center_error_m(self) -> float: + """Distance from the target lane center (0 when centered in it).""" + return abs(self.dist_to_line_m + 0.5 * self.lane_width) + + @property + def low_confidence(self) -> bool: + return self.low_conf_s + 1e-9 >= LOW_CONFIDENCE_CANCEL_S + + @property + def timed_out(self) -> bool: + return self.age_s > TARGET_LOCK_TIMEOUT_S + + @property + def reached(self) -> bool: + return self.crossed and self.centered_s + 1e-9 >= CENTERED_HOLD_S + + def update(self, offsets, dt: float) -> None: + self.age_s += dt + if offsets is None: + self.low_conf_s += dt + self.centered_s = 0.0 + return + ys, probs = offsets + best = None + for y, p in zip(ys, probs, strict=True): + if p < LANE_LINE_MIN_PROB: + continue + err = abs(y - self.line_y) + if err <= LINE_MATCH_GATE_M and (best is None or err < best[0]): + best = (err, y) + if best is None: + self.low_conf_s += dt + self.centered_s = 0.0 + return + self.low_conf_s = 0.0 + self.line_y = best[1] + if probs[1] >= LANE_LINE_MIN_PROB and probs[2] >= LANE_LINE_MIN_PROB: + width = ys[2] - ys[1] + if _sane_width(width): + self.lane_width = width + if self.crossed and self.center_error_m <= CENTERED_TOL_M: + self.centered_s += dt + else: + self.centered_s = 0.0 diff --git a/selfdrive/controls/lib/lane_change_turn.py b/selfdrive/controls/lib/lane_change_turn.py new file mode 100644 index 00000000000000..c1cb97cb76a8d3 --- /dev/null +++ b/selfdrive/controls/lib/lane_change_turn.py @@ -0,0 +1,161 @@ +"""Driver turns during a tipped lane change: blinker hold + turn mode. + +Scenario: tip into a turn lane, the change is in progress (target +locked), and the driver turns at the intersection before it finishes. + +Turn vs confirm bump is classified by wheel angle, not torque. Logged +tipped lane changes (Sep 16-28, 180 started) peak at 3.5 / 6.3 / 15.7 deg +wheel angle in the lane-change direction (p50 / p90 / p99, max 19.2; +|angle| max 24.5). Driver blinker turns under 25 mph peak at a median +174 deg; 88% exceed 45 deg. ``TURN_ENTER_ANGLE_DEG`` (45 deg) is ~2x the +largest logged lane change. It must be driver steering: lateral already +released, or driver torque in the turn direction >= the soft-lat floor. +openpilot following a curve with no driver torque is not a turn (lat +active >= 20 mph reaches 55 deg at p99.99). + +Turn mode (``DesireHelper`` and controlsd each classify from the same +carState, so no cereal change): the lane change ends and its target is +dropped for good (no resume toward the old lane when lat returns), but +controlsd keeps requesting the blinker in the lane-change direction and +feeds BlinkerLateralHold a driver turn, so lateral pauses exactly like a +manual blinker turn (same soft handoff) while openpilot and longitudinal +stay engaged. Only a sudden torque spike is an emergency. + +The blinker hold ends when the turn completes (the wheel came back under +``TURN_EXIT_ANGLE_DEG`` for ``TURN_EXIT_HOLD_S``, like the stock +self-cancel), on an opposite stalk press, on disengage, or after +``TURN_HOLD_TIMEOUT_S``. Lane-line confidence does not matter once in +turn mode. + +Slowing under 20 mph mid-change ends the change the same way but first +enters a pre-turn blinker hold (the driver is usually about to turn). It +becomes turn mode on a turn, and otherwise also ends once back above +``HOLD_RESUME_SPEED`` (25 mph), plus the exits above. +""" + +from cereal import log + +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.lane_change_nudge import SOFT_YIELD_TRIGGER_NM + +LaneChangeState = log.LaneChangeState + +TURN_ENTER_ANGLE_DEG = 45.0 +TURN_DRIVER_TORQUE_NM = SOFT_YIELD_TRIGGER_NM +TURN_EXIT_ANGLE_DEG = 10.0 +TURN_EXIT_HOLD_S = 0.5 +TURN_HOLD_TIMEOUT_S = 25.0 +# Same floor as desire_helper.LANE_CHANGE_SPEED_MIN (kept local: DH imports us). +LANE_CHANGE_SPEED_MIN = 20 * CV.MPH_TO_MS +HOLD_RESUME_SPEED = 25 * CV.MPH_TO_MS + +MODE_NONE = 0 +MODE_HOLD = 1 # change ended by slowing down; waiting for the turn +MODE_TURN = 2 # driver is turning + + +def _signed(value: float, direction: int) -> float: + """Positive in the lane-change direction (left = +angle / +torque).""" + return float(value) if direction == 1 else -float(value) + + +def is_lane_change_turn(*, direction: int, steering_angle_deg: float, + torque_nm: float, lat_active: bool) -> bool: + """Driver wheel angle well beyond any lane change, in its direction.""" + if direction not in (1, 2): + return False + if _signed(steering_angle_deg, direction) < TURN_ENTER_ANGLE_DEG: + return False + return (not lat_active) or _signed(torque_nm, direction) >= TURN_DRIVER_TORQUE_NM + + +class LaneChangeTurnHold: + """controlsd: blinker hold after a lane change turns into a driver turn.""" + + def __init__(self): + self.reset() + + def reset(self): + self.direction = 0 + self.mode = MODE_NONE + self._t = 0.0 + self._peaked = False + self._exit_s = 0.0 + self._prev_stalk = 0 + + @property + def turning(self) -> bool: + return self.mode == MODE_TURN + + def update(self, *, lc_state, lc_direction: int, steering_angle_deg: float, + torque_nm: float, lat_active: bool, v_ego: float, stalk_state: int, + engaged: bool, dt: float) -> int: + """Returns the blinker direction to hold (1 left, 2 right, 0 none).""" + stalk = int(stalk_state or 0) + prev_stalk, self._prev_stalk = self._prev_stalk, stalk + if not engaged: + self.reset() + return 0 + lc_dir = lc_direction if (lc_state != LaneChangeState.off and lc_direction in (1, 2)) else 0 + + if self.mode == MODE_NONE: + if lc_dir and is_lane_change_turn(direction=lc_dir, steering_angle_deg=steering_angle_deg, + torque_nm=torque_nm, lat_active=lat_active): + self._enter(MODE_TURN, lc_dir) + elif lc_dir and float(v_ego) < LANE_CHANGE_SPEED_MIN and lc_state in ( + LaneChangeState.laneChangeStarting, LaneChangeState.laneChangeFinishing): + self._enter(MODE_HOLD, lc_dir) + if self.mode == MODE_NONE: + return 0 + self._prev_stalk = stalk + return self.direction + + self._t += max(float(dt), 0.0) + opposite = 2 if self.direction == 1 else 1 + if stalk == opposite and prev_stalk != opposite: + self.reset() + self._prev_stalk = stalk + return 0 + if self._t >= TURN_HOLD_TIMEOUT_S - 1e-9: + self.reset() + self._prev_stalk = stalk + return 0 + + if self.mode == MODE_HOLD: + if is_lane_change_turn(direction=self.direction, steering_angle_deg=steering_angle_deg, + torque_nm=torque_nm, lat_active=lat_active): + self.mode = MODE_TURN + self._peaked = True + elif float(v_ego) >= HOLD_RESUME_SPEED: + self.reset() + self._prev_stalk = stalk + return 0 + + if self.mode == MODE_TURN: + if _signed(steering_angle_deg, self.direction) >= TURN_ENTER_ANGLE_DEG: + self._peaked = True + if self._peaked and abs(float(steering_angle_deg)) < TURN_EXIT_ANGLE_DEG: + self._exit_s += max(float(dt), 0.0) + if self._exit_s >= TURN_EXIT_HOLD_S - 1e-9: + self.reset() + self._prev_stalk = stalk + return 0 + else: + self._exit_s = 0.0 + return self.direction + + def _enter(self, mode: int, direction: int): + self.mode = mode + self.direction = direction + self._t = 0.0 + # Entering turn mode means the wheel is already past the turn angle. + self._peaked = mode == MODE_TURN + self._exit_s = 0.0 + + +def blinker_with_turn_hold(lc_blinker: tuple[bool, bool], hold_direction: int) -> tuple[bool, bool]: + """CC.leftBlinker / rightBlinker: lane change keep-alive OR the turn hold.""" + left, right = bool(lc_blinker[0]), bool(lc_blinker[1]) + if left or right: + return left, right + return hold_direction == 1, hold_direction == 2 diff --git a/selfdrive/controls/lib/lat_low_visibility.py b/selfdrive/controls/lib/lat_low_visibility.py new file mode 100644 index 00000000000000..bf6aed6bf490f9 --- /dev/null +++ b/selfdrive/controls/lib/lat_low_visibility.py @@ -0,0 +1,602 @@ +"""Low-visibility lateral back-off. + +When the driving model is unsure where to go, or the road camera exposure +collapses (sun low and ahead makes a milder drop count), ease lateral +toward the driver's current steering and raise one alert: "Low visibility". + +Openpilot stays engaged. This module does not touch longitudinal control +and does not clear latActive — it only scales how far the lateral command +may sit from the wheel. Settings → NAP → Driving Mannerisms can turn it +Off (NAPLowVisBackoff, default On). Off is identity: authority stays 1 +and the alert stays down. + +Enter (model): the model is unsure where to go, held 0.40 s. All of +these, not lane lines: path lateral std at ~3 s above 2 m, desired +curvature jumping inside a short window, and no usable road edge on +either side. Missing paint on a gravel road or a city street does not +qualify when the path is confident and stable. The timer runs only +above 20 mph, with no blinker, while lateral is not yielded, only +after the car has been out of a turn for the last 1 s (measured +curvature under 0.01 1/m, radius over ~100 m), and not in or within +40 m of a roundabout (the same ``roundabout_yield_context`` signal +the lateral yield uses). A turn or a roundabout holds the timer at 0. +Desired-curvature jumps are uncertainty, not a turn. + +Exit: the path is confident again (lateral std at ~3 s under 1.2 m and +desired curvature no longer jumping), held 0.80 s. Outside a roundabout +the car also has to be out of the turn, so an alert that is already up +when a turn starts stays up through the turn. Inside a roundabout that +turn hold does not apply: a confident path releases on the circle. +Lane lines are not required. A single frame cannot flip the latch. + +Enter (camera): integration lines fall below 0.45× a recent bright +baseline (0.65× when the sun is within 12° of the horizon and 22° of +the heading), held 0.30 s, and ONLY when the sun is low and ahead or +the model path is also unsure (lateral std at ~3 s over 1.2 m). A plain +shade-to-sun exposure change on a clear day never counts. Exit when +lines are back above 0.70× for 1 s, or when no ratio can be computed +(baseline under 280 lines, i.e. a normal bright daylight exposure) for +1 s. The sun-glare check does not use the turn gate. + +Backstop: a latch held up only by the camera releases once the model +path has been confident and stable for 3 s, and the camera cannot +re-latch until the exposure has recovered once. + +Authority: never zero. A camera-only latch with a confident path keeps +following the path with a gentle cap (0.85). Model uncertainty lowers +authority in proportion to the path std (1.0 at 1.2 m down to a 0.30 +floor at 4 m). Lateral never holds a heading or a fixed direction. +""" + +from __future__ import annotations + +import math +from collections import deque +from dataclasses import dataclass + +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.model_sight import path_y_std_at as _shared_path_y_std_at + +# --- model confidence ------------------------------------------------------- +# laneLineProbs are already 0..1. Road-edge std (m) maps through +# exp(-std / EDGE_STD_SCALE): ~0.1 m → ~0.83, ~0.7 m → ~0.28, ~1.5 m → ~0.07. +LANE_CONF_ENTER = 0.30 +LANE_CONF_EXIT = 0.55 +EDGE_STD_SCALE_M = 0.55 +PATH_T_S = 3.0 +PATH_Y_STD_ENTER_M = 2.0 +PATH_Y_STD_EXIT_M = 1.2 +MODEL_ENTER_S = 0.40 +MODEL_EXIT_S = 0.80 + +# Model-poor timer. Turns, blinkers, a yielded wheel, and town creep +# are not low visibility: lane lines vanish in intersections. +ENTRY_MIN_V_MS = 20.0 * CV.MPH_TO_MS # strictly above 20 mph +TURN_CURVATURE = 0.01 # 1/m, measured radius ~100 m +STRAIGHT_HOLD_S = 1.0 # out of the turn this long before the timer runs +# Desired-curvature chatter. Peak-to-peak inside this window, not a +# smooth bend. One spike ages out before the 0.40 s enter dwell. +CURV_JUMP = 0.008 # 1/m +CURV_WINDOW_S = 0.15 + +# --- camera exposure -------------------------------------------------------- +EXPOSURE_WINDOW_S = 12.0 +EXPOSURE_EXCLUDE_S = 1.0 # baseline ignores the newest second +EXPOSURE_FAST_S = 0.40 +EXPOSURE_MIN_BASELINE = 280 # a camera that was never bright cannot "collapse" +EXPOSURE_COLLAPSE_RATIO = 0.45 +EXPOSURE_SUN_RATIO = 0.65 # earlier heads-up when the sun is low and ahead +EXPOSURE_RECOVER_RATIO = 0.70 +EXPOSURE_ENTER_S = 0.30 +EXPOSURE_EXIT_S = 1.00 + +# --- sun (optional). Incident was ~0.3–1° up and ~7–8° right of ahead. ----- +SUN_ELEV_MIN_DEG = -1.0 +SUN_ELEV_MAX_DEG = 12.0 +SUN_AHEAD_DEG = 22.0 + +# --- authority slew --------------------------------------------------------- +AUTHORITY_DOWN_PER_S = 1.0 # full fade in about 1 s +AUTHORITY_UP_PER_S = 0.80 # recovery a little slower than the drop +AUTHORITY_FLOOR = 0.30 # never zero: lateral keeps following the path +CAMERA_ONLY_AUTHORITY = 0.85 # gentle cap while only the camera is latched +AUTHORITY_FLOOR_STD_M = 4.0 # path std where authority reaches the floor + +# Glare corroboration: the model path must be at least this unsure when the +# sun is not low and ahead. Same number as the confident-path exit. +CAMERA_MODEL_UNSURE_M = PATH_Y_STD_EXIT_M +# Camera-only backstop: confident, stable path this long releases the latch. +CAMERA_BACKSTOP_S = 3.0 +# Any lateral degrade latched this long raises the louder prolonged alert. +PROLONGED_S = 45.0 + +PARAM_LOW_VIS_BACKOFF = "NAPLowVisBackoff" + + +@dataclass(frozen=True) +class LowVisibilityOutput: + authority: float + active: bool + alert: bool + model_poor: bool + camera_blind: bool + + +def edge_confidence(std_m: float) -> float: + """Road-edge lateral std (m) → 0..1 confidence. Unknown std is not low.""" + try: + std = float(std_m) + except (TypeError, ValueError): + return 1.0 + if not math.isfinite(std) or std < 0.0: + return 1.0 + return math.exp(-std / EDGE_STD_SCALE_M) + + +def _finite(value, default: float = 1.0) -> float: + try: + v = float(value) + except (TypeError, ValueError): + return default + return v if math.isfinite(v) else default + + +def side_confidences(lane_probs, edge_stds) -> tuple[float, float]: + """(left, right) confidence. Missing signals count as seen (1), not blind. + + Lane lines: index 1 left, 2 right. Road edges: index 0 left, 1 right. + A side is the worse of its lane probability and its road-edge confidence. + """ + probs = list(lane_probs or []) + edges = list(edge_stds or []) + + def lane(i: int) -> float: + if i >= len(probs): + return 1.0 + return _finite(probs[i], 1.0) + + def edge(i: int) -> float: + if i >= len(edges): + return 1.0 + return edge_confidence(edges[i]) + + return min(lane(1), edge(0)), min(lane(2), edge(1)) + + +def side_confidences_exit(lane_probs, edge_stds) -> tuple[float, float]: + """(left, right) for the exit check only. Missing signals count as seen. + + Same indexes as side_confidences. A side is the better of its lane + probability and its road-edge confidence, so a healthy lane line can + leave low-visibility even when the road-edge std is still wide. + """ + probs = list(lane_probs or []) + edges = list(edge_stds or []) + + def lane(i: int) -> float: + if i >= len(probs): + return 1.0 + return _finite(probs[i], 1.0) + + def edge(i: int) -> float: + if i >= len(edges): + return 1.0 + return edge_confidence(edges[i]) + + return max(lane(1), edge(0)), max(lane(2), edge(1)) + + +def path_y_std_at(times, y_stds, t_query: float = PATH_T_S) -> float | None: + """Interpolate lateral path std (m) at ``t_query`` seconds. None if unusable. + + Shared with the sight-distance cap: see model_sight.path_y_std_at. + """ + return _shared_path_y_std_at(times, y_stds, t_query) + + +def edges_both_unusable(edge_stds) -> bool: + """True only when both road edges are reported and both are wide. + + A missing edge is not blind: unknown std stays "seen", so a parse + glitch cannot fade steering. One usable curb or shoulder is enough + to keep the trigger down. Lane-line probabilities are not read. + """ + edges = list(edge_stds or []) + if len(edges) < 2: + return False + return (edge_confidence(edges[0]) < LANE_CONF_ENTER + and edge_confidence(edges[1]) < LANE_CONF_ENTER) + + +def model_is_poor(y_std, edges_unusable, curvature_unstable) -> bool: + """Unsure where to go: wide plan, jumping curvature, and no edges. + + Lane-line presence is not an input. A tight path on an unmarked road + is not poor. + """ + if y_std is None or not math.isfinite(y_std) or y_std <= PATH_Y_STD_ENTER_M: + return False + return bool(edges_unusable) and bool(curvature_unstable) + + +def model_is_clear(y_std, curvature_stable) -> bool: + """Path is confident again: settled lateral std and stable curvature. + + Lane lines are not required. ``curvature_stable`` is the caller saying + desired curvature has not jumped inside ``CURV_WINDOW_S``. + """ + if y_std is None or not math.isfinite(y_std) or y_std >= PATH_Y_STD_EXIT_M: + return False + return bool(curvature_stable) + + +def _abs_curvature(value) -> float | None: + try: + k = float(value) + except (TypeError, ValueError): + return None + return abs(k) if math.isfinite(k) else None + + +def in_turn(measured_k) -> bool: + """True when the car itself is turning (measured radius under ~100 m). + + Measured curvature is ``self.curvature`` in controlsd. Desired + curvature is not a turn: a jump there is the uncertainty signal. + Unusable measured curvature does not start the timer. + """ + measured = _abs_curvature(measured_k) + if measured is None: + return True + return measured >= TURN_CURVATURE + + +def entry_speed_ok(v_ego) -> bool: + """Model-poor entry counts only above 20 mph.""" + try: + v = float(v_ego) + except (TypeError, ValueError): + return False + return math.isfinite(v) and v > ENTRY_MIN_V_MS + + +def fade_curvature(model_k: float, measured_k: float, authority: float) -> float: + """Blend the lateral target toward the wheel. Authority 1 is the model.""" + try: + a = float(authority) + mk = float(model_k) + meas = float(measured_k) + except (TypeError, ValueError): + return float(measured_k) if measured_k is not None else 0.0 + if not math.isfinite(a): + a = 1.0 + if not math.isfinite(mk): + mk = meas if math.isfinite(meas) else 0.0 + if not math.isfinite(meas): + meas = 0.0 + a = min(1.0, max(0.0, a)) + if a >= 1.0: + return mk + if a <= 0.0: + return meas + return a * mk + (1.0 - a) * meas + + +def angle_delta_deg(a_deg: float, b_deg: float) -> float: + return abs((float(a_deg) - float(b_deg) + 180.0) % 360.0 - 180.0) + + +def sun_low_and_ahead(*, elevation_deg: float, heading_deg: float, azimuth_deg: float) -> bool: + """Sun near the horizon and roughly in front of the camera heading.""" + try: + elev = float(elevation_deg) + heading = float(heading_deg) + azimuth = float(azimuth_deg) + except (TypeError, ValueError): + return False + if not all(math.isfinite(v) for v in (elev, heading, azimuth)): + return False + if not SUN_ELEV_MIN_DEG <= elev <= SUN_ELEV_MAX_DEG: + return False + return angle_delta_deg(heading, azimuth) <= SUN_AHEAD_DEG + + +def solar_position(lat_deg: float, lon_deg: float, unix_s: float) -> tuple[float, float]: + """Approximate (elevation_deg, azimuth_deg). Azimuth is clockwise from north. + + About a degree, which is enough for "low and ahead" versus overhead or behind. + """ + lat = float(lat_deg) + lon = float(lon_deg) + # Days since 2000-01-01 12:00 UTC (J2000-ish). + days = (float(unix_s) - 946728000.0) / 86400.0 + mean_long = (280.460 + 0.9856474 * days) % 360.0 + mean_anom = math.radians((357.528 + 0.9856003 * days) % 360.0) + lam = math.radians((mean_long + 1.915 * math.sin(mean_anom) + 0.020 * math.sin(2.0 * mean_anom)) % 360.0) + eps = math.radians(23.439 - 0.0000004 * days) + dec = math.asin(max(-1.0, min(1.0, math.sin(eps) * math.sin(lam)))) + ra = math.atan2(math.cos(eps) * math.sin(lam), math.cos(lam)) + gmst = (280.46061837 + 360.98564736629 * days) % 360.0 + lmst = math.radians((gmst + lon) % 360.0) + ha = lmst - ra + lat_r = math.radians(lat) + sin_el = (math.sin(lat_r) * math.sin(dec) + + math.cos(lat_r) * math.cos(dec) * math.cos(ha)) + elev = math.degrees(math.asin(max(-1.0, min(1.0, sin_el)))) + # Azimuth clockwise from north. -sin(ha) puts morning sun in the east. + az = math.degrees(math.atan2( + -math.sin(ha), + math.tan(dec) * math.cos(lat_r) - math.sin(lat_r) * math.cos(ha), + )) + az = (az + 360.0) % 360.0 + return elev, az + + +def sun_ahead_from_fix(*, latitude: float, longitude: float, unix_timestamp_millis: int, + bearing_deg: float, horizontal_accuracy_m: float = 0.0) -> bool | None: + """True/False when the fix is usable. None when sun position should be ignored.""" + try: + lat = float(latitude) + lon = float(longitude) + ts_ms = int(unix_timestamp_millis) + bearing = float(bearing_deg) + acc = float(horizontal_accuracy_m or 0.0) + except (TypeError, ValueError): + return None + if not all(math.isfinite(v) for v in (lat, lon, bearing, acc)): + return None + if not (-90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0): + return None + if ts_ms < 1_000_000_000_000: # need real unix milliseconds + return None + if acc > 50.0: + return None + elev, az = solar_position(lat, lon, ts_ms / 1000.0) + return sun_low_and_ahead(elevation_deg=elev, heading_deg=bearing, azimuth_deg=az) + + +class _Exposure: + def __init__(self): + self._samples: deque[tuple[float, float]] = deque() + self._t = 0.0 + self.blind = False + self._enter_s = 0.0 + self._exit_s = 0.0 + self.suppressed = False + self.recovered = True + + def backstop_release(self): + """Drop the latch and refuse to re-latch until exposure recovers once.""" + self.clear_latch() + self.suppressed = True + self.recovered = False + + def update(self, integ_lines, sun_ahead: bool, dt: float, corroborated: bool | None = None) -> bool: + """``corroborated``: the sun is low and ahead or the model path is unsure. + + None keeps the old meaning (sun_ahead only). A drop that is not + corroborated never enters. No computable ratio counts as clear. + """ + self._t += dt + try: + integ = float(integ_lines) if integ_lines is not None else None + except (TypeError, ValueError): + integ = None + if integ is not None and math.isfinite(integ) and integ > 0.0: + self._samples.append((self._t, integ)) + horizon = self._t - EXPOSURE_WINDOW_S + while self._samples and self._samples[0][0] < horizon: + self._samples.popleft() + + baseline = self._baseline() + current = self._current() + ratio = None + if baseline is not None and current is not None and baseline >= EXPOSURE_MIN_BASELINE: + ratio = current / baseline + enter_ratio = EXPOSURE_SUN_RATIO if sun_ahead else EXPOSURE_COLLAPSE_RATIO + if corroborated is None: + corroborated = bool(sun_ahead) + raw = ratio is not None and ratio < enter_ratio and bool(corroborated) + # Baseline under 280 (or no samples): a normal bright exposure, not blind. + clear = ratio is None or ratio > EXPOSURE_RECOVER_RATIO + if clear: + self.recovered = True + if self.suppressed and not self.recovered: + raw = False + if self.suppressed and self.recovered: + self.suppressed = False + if raw: + self._enter_s += dt + self._exit_s = 0.0 + if self._enter_s + 1e-12 >= EXPOSURE_ENTER_S: + self.blind = True + elif clear: + self._exit_s += dt + self._enter_s = 0.0 + if self._exit_s + 1e-12 >= EXPOSURE_EXIT_S: + self.blind = False + else: + self._enter_s = 0.0 + self._exit_s = 0.0 + return self.blind + + def _baseline(self) -> float | None: + old = [v for t, v in self._samples if self._t - t >= EXPOSURE_EXCLUDE_S] + if len(old) < 3: + return None + return max(old) + + def _current(self) -> float | None: + recent = [v for t, v in self._samples if self._t - t <= EXPOSURE_FAST_S] + if not recent: + return None + return sum(recent) / len(recent) + + def clear_latch(self): + self.blind = False + self._enter_s = 0.0 + self._exit_s = 0.0 + self.suppressed = False + self.recovered = True + + +def authority_target(active: bool, model_poor: bool, camera: bool, y_std) -> float: + """Never zero. Degrade only in proportion to genuine path uncertainty.""" + if not active: + return 1.0 + target = 1.0 + if camera: + target = CAMERA_ONLY_AUTHORITY + if y_std is not None and math.isfinite(y_std) and y_std > PATH_Y_STD_EXIT_M: + span = AUTHORITY_FLOOR_STD_M - PATH_Y_STD_EXIT_M + frac = min(1.0, (y_std - PATH_Y_STD_EXIT_M) / span) + target = min(target, AUTHORITY_FLOOR + (1.0 - frac) * (1.0 - AUTHORITY_FLOOR)) + elif model_poor: + target = min(target, CAMERA_ONLY_AUTHORITY) + return max(AUTHORITY_FLOOR, target) + + +class LowVisibility: + """Filter model + exposure into one latch and a slewed lateral authority.""" + + def __init__(self): + self.authority = 1.0 + self.active = False + self._model = False + self._poor_s = 0.0 + self._clear_s = 0.0 + # No turn observed yet, so a straight at speed can enter immediately. + # A turn zeros this; the timer stays at 0 until it climbs back to 1 s. + self._straight_s = STRAIGHT_HOLD_S + self._k_t = 0.0 + self._k_hist: deque[tuple[float, float]] = deque() + self._exposure = _Exposure() + self._cam_confident_s = 0.0 + self._active_s = 0.0 + + def reset_latch(self): + self.active = False + self._model = False + self._poor_s = 0.0 + self._clear_s = 0.0 + self._straight_s = STRAIGHT_HOLD_S + self._k_t = 0.0 + self._k_hist.clear() + self.authority = 1.0 + self._exposure.clear_latch() + self._cam_confident_s = 0.0 + self._active_s = 0.0 + + @property + def prolonged(self) -> bool: + """Lateral degrade latched longer than PROLONGED_S.""" + return self.active and self._active_s + 1e-9 >= PROLONGED_S + + def _curvature_unstable(self, model_k, dt: float) -> bool: + """Desired curvature peak-to-peak inside the recent window is a jump.""" + self._k_t += dt + try: + k = float(model_k) + except (TypeError, ValueError): + return False + if not math.isfinite(k): + return False + self._k_hist.append((self._k_t, k)) + cutoff = self._k_t - CURV_WINDOW_S + while self._k_hist and self._k_hist[0][0] < cutoff: + self._k_hist.popleft() + if len(self._k_hist) < 2: + return False + ks = [sample for _, sample in self._k_hist] + return (max(ks) - min(ks)) >= CURV_JUMP + + def update(self, *, enabled: bool, lane_probs=None, edge_stds=None, + path_t=None, path_y_std=None, integ_lines=None, + sun_ahead: bool = False, dt: float = 0.01, + v_ego: float = 15.0, blinker: bool = False, yielded: bool = False, + measured_curvature: float = 0.0, model_curvature: float = 0.0, + near_roundabout: bool = False) -> LowVisibilityOutput: + """``v_ego`` defaults above 20 mph and both curvatures default straight. + + Confidence tests that omit the car state keep the previous straight-road + behavior. controlsd always passes the live speed, blinker, yield, and + the curvatures it already uses for the lateral command. + """ + dt = float(dt) if dt and math.isfinite(float(dt)) else 0.01 + # Lane probabilities are intentionally unused. Missing paint is normal. + del lane_probs + turning = in_turn(measured_curvature) + if turning: + self._straight_s = 0.0 + else: + self._straight_s = min(STRAIGHT_HOLD_S, self._straight_s + dt) + straight_for_hold = self._straight_s + 1e-12 >= STRAIGHT_HOLD_S + entry_ok = ( + straight_for_hold + and entry_speed_ok(v_ego) + and not bool(blinker) + and not bool(yielded) + and not bool(near_roundabout) + ) + unstable = self._curvature_unstable(model_curvature, dt) + y_std = path_y_std_at(path_t, path_y_std, PATH_T_S) + poor = model_is_poor(y_std, edges_both_unusable(edge_stds), unstable) + # Out of the turn, a settled path with calm desired curvature releases + # even when lane lines never come back. In a turn the exit hold does + # not run, so an alert that is already up stays up. A roundabout is + # the exception: release as soon as the path is confident, still circling. + hold_through_turn = turning and not bool(near_roundabout) + clear = (not hold_through_turn) and model_is_clear(y_std, not unstable) + if self._model: + if clear: + self._clear_s += dt + self._poor_s = 0.0 + if self._clear_s + 1e-12 >= MODEL_EXIT_S: + self._model = False + else: + self._poor_s = 0.0 + self._clear_s = 0.0 + elif poor and entry_ok: + self._poor_s += dt + self._clear_s = 0.0 + if self._poor_s + 1e-12 >= MODEL_ENTER_S: + self._model = True + else: + # Turn, roundabout, blinker, yield, or under 20 mph: timer stays at 0. + self._poor_s = 0.0 + self._clear_s = 0.0 + + model_unsure = y_std is not None and math.isfinite(y_std) and y_std > CAMERA_MODEL_UNSURE_M + camera = self._exposure.update(integ_lines, bool(sun_ahead), dt, + corroborated=bool(sun_ahead) or model_unsure) + # Backstop: camera-only latch with a confident, stable path. + confident = model_is_clear(y_std, not unstable) + if camera and not self._model and confident: + self._cam_confident_s += dt + if self._cam_confident_s + 1e-12 >= CAMERA_BACKSTOP_S: + self._exposure.backstop_release() + camera = False + self._cam_confident_s = 0.0 + else: + self._cam_confident_s = 0.0 + if not enabled: + self._model = False + self._poor_s = 0.0 + self._clear_s = 0.0 + self._exposure.clear_latch() + self._cam_confident_s = 0.0 + self._active_s = 0.0 + self.active = False + self.authority = 1.0 + return LowVisibilityOutput(1.0, False, False, False, False) + + self.active = bool(self._model or camera) + self._active_s = self._active_s + dt if self.active else 0.0 + target = authority_target(self.active, self._model, camera, y_std) + if self.authority > target: + self.authority = max(target, self.authority - AUTHORITY_DOWN_PER_S * dt) + elif self.authority < target: + self.authority = min(target, self.authority + AUTHORITY_UP_PER_S * dt) + return LowVisibilityOutput( + float(self.authority), bool(self.active), bool(self.active), + bool(self._model), bool(camera)) diff --git a/selfdrive/controls/lib/lat_turn_geometry.py b/selfdrive/controls/lib/lat_turn_geometry.py new file mode 100644 index 00000000000000..2bbbc6c9da43ca --- /dev/null +++ b/selfdrive/controls/lib/lat_turn_geometry.py @@ -0,0 +1,264 @@ +"""Turn geometry correction: when the model plan's heading is sampled. + +modeld samples the plan heading at `lat_action_t = lagd + 0.075 s`. lagd +only learns above 15 m/s, so at turn speeds the plan was sampled ~0.14 s +too far ahead (measured desired->yaw lag 0.26 s at 3-8 m/s vs 0.40 s +learned). The model was also trained on cars whose camera sits ~1.55 m ahead +of the rear axle; on the Model S it is 1.90 m (measured), so turn-in is +anchored ~0.35 m early in space. Both are the same knob: + + lookahead = lagd + dly_offset(v) + 0.075 - ref_offset_m / max(v, 3) + +Reduction is capped at 0.2 s, the lookahead never goes below 0.2 s (or +below the stock value if that is already lower), it fades in from 1.5 to +2.5 m/s (no effect below 1.5 m/s), and it is held off (slewed back to stock) +while the steering angle is pinned by the 250 deg/s rate limit. Highway +speeds are unchanged apart from ref_offset / v (0.012 s at 30 m/s). + +Low-speed reach (Sep 28 PM drive: 5-8 mph turns still clipped the inside by +~0.6-0.8 m). drive_helpers.get_curvature_from_plan treats any action_t below +MIN_STABLE_DELAY (0.3 s) as 0.3 s, so the effective reduction was only +0.167 s, and the 3-4 m/s fade meant ~no correction at 5-8 mph. Below 8 mph +the cap rises to 0.25 s and the plan is sampled directly down to 0.2 s +(`plan_curvature`); both fade back to exactly the 7c49a8e behavior by +10 mph (4.47 m/s). Below 10 mph a rate-limited wheel freezes the reduction +instead of slewing back to stock. At >= 10 mph every output is identical to +7c49a8e. + +Turn-in delay trim (NAPTurnInDelay, integer steps -2..+3, default 0). A +user trim on top of the low-speed correction above, for "turn-in is good but +still a little early": every step moves the lookahead by TURN_IN_STEP_S +(30 ms), positive = shorter lookahead = later turn-in, negative = earlier. It +is scaled by the same low-speed band as the reach (full from 3-4 mph up to +8 mph, gone by 10 mph, nothing below 1.5 m/s), so >= 10 mph is untouched. +Step 0 returns the existing output unchanged, bit for bit. The shifted +lookahead never goes below TURN_IN_MIN_LOOKAHEAD_S (0.10 s) or above stock, +and the trim only acts while Turn Geometry Correction is on. + +Off, or not Pre-AP, returns the stock lookahead unchanged. +""" +from __future__ import annotations + +import numpy as np + +from openpilot.selfdrive.controls.lib.drive_helpers import MIN_STABLE_DELAY, curv_from_psis, get_curvature_from_plan + +PARAM_TURN_GEOMETRY = "NAPLatTurnGeom" +PARAM_REF_OFFSET = "NAPLatRefOffset" +PARAM_TURN_IN_DELAY = "NAPTurnInDelay" + +REF_OFFSET_DEFAULT_M = 0.35 +REF_OFFSET_MIN_M = 0.0 +REF_OFFSET_MAX_M = 1.0 + +# Measured desired->yaw lag minus the highway (lagd) lag, per speed. +DELAY_OFFSET_BP_MS = (5.0, 10.0, 14.0, 19.0, 25.0) +DELAY_OFFSET_S = (-0.13, -0.10, -0.08, -0.05, 0.0) + +MIN_SPEED_MS = 1.5 # no correction at or below +FADE_IN_SPEED_MS = 2.5 # full correction from here +REF_SPEED_FLOOR_MS = 3.0 # offset / max(v, 3) +MAX_REDUCTION_S = 0.20 +MIN_LOOKAHEAD_S = 0.20 + +# Low-speed reach: full below 8 mph, gone (== 7c49a8e) from 10 mph. +MPH = 0.44704 +LOW_SPEED_REACH_FULL_MS = 8.0 * MPH +LOW_SPEED_REACH_END_MS = 10.0 * MPH +LOW_SPEED_MAX_REDUCTION_S = 0.25 +LOW_SPEED_SAMPLE_FLOOR_S = MIN_LOOKAHEAD_S # plan sampled directly down to 0.2 s + +# Turn-in delay trim (user step, low-speed band only). +TURN_IN_STEP_MIN = -2 +TURN_IN_STEP_MAX = 3 +TURN_IN_STEP_S = 0.030 # lookahead change per step at full weight +TURN_IN_MIN_LOOKAHEAD_S = 0.10 # trimmed lookahead / sample time never below + +# Steering rate limit hold-off. Pre-AP MAX_ANGLE_RATE is 5 deg per 20 ms. +STEER_RATE_LIMIT_DEG_S = 250.0 +RATE_LIMIT_FRACTION = 0.8 # output moving >= 200 deg/s +RATE_LIMIT_GAP_DEG = 2.5 # and still short of the command +RATE_LIMIT_HOLD_S = 0.5 # keep the stock lookahead this long after +REDUCTION_SLEW_S_PER_S = 0.5 # 0.2 s of correction moves in 0.4 s + + +def clamp_ref_offset(offset_m) -> float: + try: + v = float(offset_m) + except (TypeError, ValueError): + return REF_OFFSET_DEFAULT_M + if not np.isfinite(v): + return REF_OFFSET_DEFAULT_M + return float(min(REF_OFFSET_MAX_M, max(REF_OFFSET_MIN_M, v))) + + +def clamp_turn_in_step(step) -> int: + """NAPTurnInDelay as an int in [TURN_IN_STEP_MIN, TURN_IN_STEP_MAX]; junk -> 0.""" + try: + v = float(step) + except (TypeError, ValueError): + return 0 + if not np.isfinite(v): + return 0 + return int(min(TURN_IN_STEP_MAX, max(TURN_IN_STEP_MIN, round(v)))) + + +def delay_offset_s(v_ego: float) -> float: + """Low-speed lag correction (<= 0). 0 at >= 25 m/s.""" + return float(np.interp(float(v_ego), DELAY_OFFSET_BP_MS, DELAY_OFFSET_S)) + + +def ref_offset_s(v_ego: float, ref_offset_m: float) -> float: + """Rear reference offset as time: offset / max(v, 3).""" + return clamp_ref_offset(ref_offset_m) / max(float(v_ego), REF_SPEED_FLOOR_MS) + + +def speed_fade(v_ego: float) -> float: + return float(np.clip((float(v_ego) - MIN_SPEED_MS) / (FADE_IN_SPEED_MS - MIN_SPEED_MS), 0.0, 1.0)) + + +def low_speed_reach_weight(v_ego: float) -> float: + """1 below 8 mph, 0 from 10 mph (linear between).""" + w = (LOW_SPEED_REACH_END_MS - float(v_ego)) / (LOW_SPEED_REACH_END_MS - LOW_SPEED_REACH_FULL_MS) + return float(np.clip(w, 0.0, 1.0)) + + +def reduction_cap_s(v_ego: float) -> float: + """0.25 s below 8 mph, exactly MAX_REDUCTION_S from 10 mph.""" + w = low_speed_reach_weight(v_ego) + if w <= 0.0: + return MAX_REDUCTION_S + return MAX_REDUCTION_S + (LOW_SPEED_MAX_REDUCTION_S - MAX_REDUCTION_S) * w + + +def sample_floor_s(v_ego: float) -> float: + """Shortest plan sample time: 0.2 s below 8 mph, MIN_STABLE_DELAY (stock) from 10 mph.""" + w = low_speed_reach_weight(v_ego) + if w <= 0.0: + return MIN_STABLE_DELAY + return MIN_STABLE_DELAY - (MIN_STABLE_DELAY - LOW_SPEED_SAMPLE_FLOOR_S) * w + + +def plan_curvature(yaws, yaw_rates, t_idxs, v_ego: float, action_t: float, + sample_floor: float = MIN_STABLE_DELAY) -> float: + """get_curvature_from_plan, but the plan may be sampled directly below 0.3 s. + + With the stock floor (or action_t >= 0.3 s) this IS get_curvature_from_plan. + """ + floor = float(sample_floor) + if floor >= MIN_STABLE_DELAY or float(action_t) >= MIN_STABLE_DELAY: + return get_curvature_from_plan(yaws, yaw_rates, t_idxs, v_ego, action_t) + if floor < LOW_SPEED_SAMPLE_FLOOR_S: # turn-in trim: sampled below 0.2 s + t = max(float(action_t), floor, TURN_IN_MIN_LOOKAHEAD_S) + else: + t = max(float(action_t), floor, LOW_SPEED_SAMPLE_FLOOR_S) + psi_target = np.interp(t, t_idxs, yaws) + return curv_from_psis(psi_target, yaw_rates[0], v_ego, t) + + +def target_reduction_s(v_ego: float, ref_offset_m: float) -> float: + """Seconds to take off the stock lookahead (>= 0, <= reduction_cap_s(v)).""" + v = max(0.0, float(v_ego)) + red = min(reduction_cap_s(v), max(0.0, -delay_offset_s(v) + ref_offset_s(v, ref_offset_m))) + return red * speed_fade(v) + + +def apply_reduction(stock_lookahead_s: float, reduction_s: float, cap_s: float = MAX_REDUCTION_S) -> float: + """Stock minus reduction, floored at MIN_LOOKAHEAD_S (never above stock).""" + stock = float(stock_lookahead_s) + red = min(float(cap_s), max(0.0, float(reduction_s))) + if red <= 0.0: + return stock + return max(min(stock, MIN_LOOKAHEAD_S), stock - red) + + +def turn_in_weight(v_ego: float) -> float: + """Low-speed band of the trim: 0 below 1.5 m/s, full from 2.5 m/s to 8 mph, 0 from 10 mph.""" + return low_speed_reach_weight(v_ego) * speed_fade(v_ego) + + +def turn_in_shift_s(step, v_ego: float) -> float: + """Lookahead shift (s) the trim asks for at this speed. + = later turn-in.""" + return clamp_turn_in_step(step) * TURN_IN_STEP_S * turn_in_weight(v_ego) + + +def apply_turn_in_trim(lookahead_s: float, stock_lookahead_s: float, shift_s: float) -> float: + """Shift the lookahead by shift_s; 0 returns it unchanged. Bounded, never above stock.""" + L = float(lookahead_s) + shift = float(shift_s) + if shift == 0.0: + return L + if shift > 0.0: + return max(min(L, TURN_IN_MIN_LOOKAHEAD_S), L - shift) + return min(max(L, float(stock_lookahead_s)), L - shift) + + +def steer_rate_limited(cmd_angle_deg: float, out_angle_deg: float, out_angle_prev_deg: float, + dt: float, lat_active: bool) -> bool: + """True while the output angle is running at the rate limit and still short of the command.""" + if not lat_active or dt <= 0.0: + return False + rate = abs(float(out_angle_deg) - float(out_angle_prev_deg)) / dt + gap = abs(float(cmd_angle_deg) - float(out_angle_deg)) + return rate >= RATE_LIMIT_FRACTION * STEER_RATE_LIMIT_DEG_S and gap > RATE_LIMIT_GAP_DEG + + +class TurnGeometryCorrection: + """Stateful wrapper: hold-off on rate limit + slewed reduction.""" + + def __init__(self, dt: float): + self.dt = float(dt) + self.reduction_s = 0.0 + self._hold_s = 0.0 + self._out_prev: float | None = None + self.rate_limited = False + self.sample_floor_s = MIN_STABLE_DELAY + self.trim_s = 0.0 + + def reset(self) -> None: + self.trim_s = 0.0 + self.reduction_s = 0.0 + self._hold_s = 0.0 + self._out_prev = None + self.rate_limited = False + self.sample_floor_s = MIN_STABLE_DELAY + + def update(self, *, enabled: bool, stock_lookahead_s: float, v_ego: float, ref_offset_m: float, + lat_active: bool = True, cmd_angle_deg: float = 0.0, out_angle_deg: float | None = None, + turn_in_step: int = 0) -> float: + """Return the lookahead to use. enabled=False returns stock_lookahead_s exactly.""" + if not enabled: + self.reset() + return stock_lookahead_s + limited = False + if out_angle_deg is not None: + if self._out_prev is not None: + limited = steer_rate_limited(cmd_angle_deg, out_angle_deg, self._out_prev, self.dt, lat_active) + self._out_prev = float(out_angle_deg) + self.rate_limited = limited + self._hold_s = RATE_LIMIT_HOLD_S if limited else max(0.0, self._hold_s - self.dt) + if self._hold_s > 0.0 and low_speed_reach_weight(v_ego) > 0.0: + target = self.reduction_s # below 10 mph: freeze, keep the turn-in timing + else: + target = 0.0 if self._hold_s > 0.0 else target_reduction_s(v_ego, ref_offset_m) + step = REDUCTION_SLEW_S_PER_S * self.dt + self.reduction_s += float(np.clip(target - self.reduction_s, -step, step)) + self.sample_floor_s = sample_floor_s(v_ego) + # User turn-in trim: slewed so a menu change is not a step in the steering. + shift_target = turn_in_shift_s(turn_in_step, v_ego) + trim_step = REDUCTION_SLEW_S_PER_S * self.dt + self.trim_s += float(np.clip(shift_target - self.trim_s, -trim_step, trim_step)) + if self.trim_s != 0.0: + trim_floor = self.sample_floor_s - self.trim_s + self.sample_floor_s = float(min(MIN_STABLE_DELAY, max(TURN_IN_MIN_LOOKAHEAD_S, trim_floor))) + lookahead = apply_reduction(stock_lookahead_s, self.reduction_s, reduction_cap_s(v_ego)) + return apply_turn_in_trim(lookahead, stock_lookahead_s, self.trim_s) + return apply_reduction(stock_lookahead_s, self.reduction_s, reduction_cap_s(v_ego)) + + +def turn_geometry_active(is_preap: bool, param_on: bool) -> bool: + return bool(is_preap) and bool(param_on) + + +def is_preap_car(CP) -> bool: + return getattr(CP, "brand", "") == "tesla" and getattr(CP, "carFingerprint", "") == "TESLA_MODEL_S_PREAP" diff --git a/selfdrive/controls/lib/latcontrol.py b/selfdrive/controls/lib/latcontrol.py index 0e4a27da61725f..d69796738f35f1 100644 --- a/selfdrive/controls/lib/latcontrol.py +++ b/selfdrive/controls/lib/latcontrol.py @@ -1,32 +1,29 @@ +import numpy as np from abc import abstractmethod, ABC -from openpilot.common.numpy_fast import clip -from openpilot.common.realtime import DT_CTRL - -MIN_LATERAL_CONTROL_SPEED = 0.3 # m/s - class LatControl(ABC): - def __init__(self, CP, CI): - self.sat_count_rate = 1.0 * DT_CTRL + def __init__(self, CP, CI, dt): + self.dt = dt self.sat_limit = CP.steerLimitTimer - self.sat_count = 0. + self.sat_time = 0. self.sat_check_min_speed = 10. # we define the steer torque scale as [-1.0...1.0] self.steer_max = 1.0 @abstractmethod - def update(self, active, CS, VM, params, steer_limited, desired_curvature, calibrated_pose): + def update(self, active: bool, CS, VM, params, steer_limited_by_safety: bool, desired_curvature: float, curvature_limited: bool, lat_delay: float): pass def reset(self): - self.sat_count = 0. + self.sat_time = 0. - def _check_saturation(self, saturated, CS, steer_limited): - if saturated and CS.vEgo > self.sat_check_min_speed and not steer_limited and not CS.steeringPressed: - self.sat_count += self.sat_count_rate + def _check_saturation(self, saturated, CS, steer_limited_by_safety, curvature_limited): + # Saturated only if control output is not being limited by car torque/angle rate limits + if (saturated or curvature_limited) and CS.vEgo > self.sat_check_min_speed and not steer_limited_by_safety and not CS.steeringPressed: + self.sat_time += self.dt else: - self.sat_count -= self.sat_count_rate - self.sat_count = clip(self.sat_count, 0.0, self.sat_limit) - return self.sat_count > (self.sat_limit - 1e-3) + self.sat_time -= self.dt + self.sat_time = np.clip(self.sat_time, 0.0, self.sat_limit) + return self.sat_time > (self.sat_limit - 1e-3) diff --git a/selfdrive/controls/lib/latcontrol_angle.py b/selfdrive/controls/lib/latcontrol_angle.py index d3da656daa16df..a7d0403248751b 100644 --- a/selfdrive/controls/lib/latcontrol_angle.py +++ b/selfdrive/controls/lib/latcontrol_angle.py @@ -3,15 +3,17 @@ from cereal import log from openpilot.selfdrive.controls.lib.latcontrol import LatControl +# TODO This is speed dependent STEER_ANGLE_SATURATION_THRESHOLD = 2.5 # Degrees class LatControlAngle(LatControl): - def __init__(self, CP, CI): - super().__init__(CP, CI) + def __init__(self, CP, CI, dt): + super().__init__(CP, CI, dt) self.sat_check_min_speed = 5. + self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai") - def update(self, active, CS, VM, params, steer_limited, desired_curvature, calibrated_pose): + def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay): angle_log = log.ControlsState.LateralAngleState.new_message() if not active: @@ -22,8 +24,14 @@ def update(self, active, CS, VM, params, steer_limited, desired_curvature, calib angle_steers_des = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)) angle_steers_des += params.angleOffsetDeg - angle_control_saturated = abs(angle_steers_des - CS.steeringAngleDeg) > STEER_ANGLE_SATURATION_THRESHOLD - angle_log.saturated = self._check_saturation(angle_control_saturated, CS, False) + if self.use_steer_limited_by_safety: + # these cars' carcontrollers calculate max lateral accel and jerk, so we can rely on carOutput for saturation + angle_control_saturated = steer_limited_by_safety + else: + # for cars which use a method of limiting torque such as a torque signal (Nissan and Toyota) + # or relying on EPS (Ford Q3), carOutput does not capture maxing out torque # TODO: this can be improved + angle_control_saturated = abs(angle_steers_des - CS.steeringAngleDeg) > STEER_ANGLE_SATURATION_THRESHOLD + angle_log.saturated = bool(self._check_saturation(angle_control_saturated, CS, False, curvature_limited)) angle_log.steeringAngleDeg = float(CS.steeringAngleDeg) angle_log.steeringAngleDesiredDeg = angle_steers_des return 0, float(angle_steers_des), angle_log diff --git a/selfdrive/controls/lib/latcontrol_pid.py b/selfdrive/controls/lib/latcontrol_pid.py index d7edd39f8a4103..14ab9f21b5580b 100644 --- a/selfdrive/controls/lib/latcontrol_pid.py +++ b/selfdrive/controls/lib/latcontrol_pid.py @@ -6,18 +6,15 @@ class LatControlPID(LatControl): - def __init__(self, CP, CI): - super().__init__(CP, CI) + def __init__(self, CP, CI, dt): + super().__init__(CP, CI, dt) self.pid = PIDController((CP.lateralTuning.pid.kpBP, CP.lateralTuning.pid.kpV), (CP.lateralTuning.pid.kiBP, CP.lateralTuning.pid.kiV), - k_f=CP.lateralTuning.pid.kf, pos_limit=self.steer_max, neg_limit=-self.steer_max) + pos_limit=self.steer_max, neg_limit=-self.steer_max) + self.ff_factor = CP.lateralTuning.pid.kf self.get_steer_feedforward = CI.get_steer_feedforward_function() - def reset(self): - super().reset() - self.pid.reset() - - def update(self, active, CS, VM, params, steer_limited, desired_curvature, calibrated_pose): + def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay): pid_log = log.ControlsState.LateralPIDState.new_message() pid_log.steeringAngleDeg = float(CS.steeringAngleDeg) pid_log.steeringRateDeg = float(CS.steeringRateDeg) @@ -29,20 +26,24 @@ def update(self, active, CS, VM, params, steer_limited, desired_curvature, calib pid_log.steeringAngleDesiredDeg = angle_steers_des pid_log.angleError = error if not active: - output_steer = 0.0 + output_torque = 0.0 pid_log.active = False - self.pid.reset() + else: # offset does not contribute to resistive torque - steer_feedforward = self.get_steer_feedforward(angle_steers_des_no_offset, CS.vEgo) + ff = self.ff_factor * self.get_steer_feedforward(angle_steers_des_no_offset, CS.vEgo) + freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5 + + output_torque = self.pid.update(error, + feedforward=ff, + speed=CS.vEgo, + freeze_integrator=freeze_integrator) - output_steer = self.pid.update(error, override=CS.steeringPressed, - feedforward=steer_feedforward, speed=CS.vEgo) pid_log.active = True - pid_log.p = self.pid.p - pid_log.i = self.pid.i - pid_log.f = self.pid.f - pid_log.output = output_steer - pid_log.saturated = self._check_saturation(self.steer_max - abs(output_steer) < 1e-3, CS, steer_limited) + pid_log.p = float(self.pid.p) + pid_log.i = float(self.pid.i) + pid_log.f = float(self.pid.f) + pid_log.output = float(output_torque) + pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited)) - return output_steer, angle_steers_des, pid_log + return output_torque, angle_steers_des, pid_log diff --git a/selfdrive/controls/lib/latcontrol_torque.py b/selfdrive/controls/lib/latcontrol_torque.py index 55a37c1f4bd5ad..903700d4b3ce06 100644 --- a/selfdrive/controls/lib/latcontrol_torque.py +++ b/selfdrive/controls/lib/latcontrol_torque.py @@ -1,11 +1,13 @@ import math +import numpy as np +from collections import deque from cereal import log -from opendbc.car.interfaces import LatControlInputs -from openpilot.common.numpy_fast import interp +from opendbc.car.lateral import FRICTION_THRESHOLD, get_friction +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY +from openpilot.common.filter_simple import FirstOrderFilter from openpilot.selfdrive.controls.lib.latcontrol import LatControl from openpilot.common.pid import PIDController -from openpilot.selfdrive.controls.lib.vehicle_model import ACCELERATION_DUE_TO_GRAVITY # At higher speeds (25+mph) we can assume: # Lateral acceleration achieved by a specific car correlates to @@ -13,81 +15,94 @@ # wheel slip, or to speed. # This controller applies torque to achieve desired lateral -# accelerations. To compensate for the low speed effects we -# use a LOW_SPEED_FACTOR in the error. Additionally, there is -# friction in the steering wheel that needs to be overcome to -# move it at all, this is compensated for too. +# accelerations. To compensate for the low speed effects the +# proportional gain is increased at low speeds by the PID controller. +# Additionally, there is friction in the steering wheel that needs +# to be overcome to move it at all, this is compensated for too. -LOW_SPEED_X = [0, 10, 20, 30] -LOW_SPEED_Y = [15, 13, 10, 5] +KP = 0.8 +KI = 0.15 +INTERP_SPEEDS = [1, 1.5, 2.0, 3.0, 5, 7.5, 10, 15, 30] +KP_INTERP = [250, 120, 65, 30, 11.5, 5.5, 3.5, 2.0, KP] + +LP_FILTER_CUTOFF_HZ = 1.2 +JERK_LOOKAHEAD_SECONDS = 0.19 +JERK_GAIN = 0.3 +LAT_ACCEL_REQUEST_BUFFER_SECONDS = 1.0 +VERSION = 1 class LatControlTorque(LatControl): - def __init__(self, CP, CI): - super().__init__(CP, CI) + def __init__(self, CP, CI, dt): + super().__init__(CP, CI, dt) self.torque_params = CP.lateralTuning.torque.as_builder() - self.pid = PIDController(self.torque_params.kp, self.torque_params.ki, - k_f=self.torque_params.kf, pos_limit=self.steer_max, neg_limit=-self.steer_max) self.torque_from_lateral_accel = CI.torque_from_lateral_accel() - self.use_steering_angle = self.torque_params.useSteeringAngle + self.lateral_accel_from_torque = CI.lateral_accel_from_torque() + self.pid = PIDController([INTERP_SPEEDS, KP_INTERP], KI, rate=1/self.dt) + self.update_limits() self.steering_angle_deadzone_deg = self.torque_params.steeringAngleDeadzoneDeg + self.lat_accel_request_buffer_len = int(LAT_ACCEL_REQUEST_BUFFER_SECONDS / self.dt) + self.lat_accel_request_buffer = deque([0.] * self.lat_accel_request_buffer_len , maxlen=self.lat_accel_request_buffer_len) + self.lookahead_frames = int(JERK_LOOKAHEAD_SECONDS / self.dt) + self.jerk_filter = FirstOrderFilter(0.0, 1 / (2 * np.pi * LP_FILTER_CUTOFF_HZ), self.dt) def update_live_torque_params(self, latAccelFactor, latAccelOffset, friction): self.torque_params.latAccelFactor = latAccelFactor self.torque_params.latAccelOffset = latAccelOffset self.torque_params.friction = friction + self.update_limits() + + def update_limits(self): + self.pid.set_limits(self.lateral_accel_from_torque(self.steer_max, self.torque_params), + self.lateral_accel_from_torque(-self.steer_max, self.torque_params)) - def update(self, active, CS, VM, params, steer_limited, desired_curvature, calibrated_pose): + def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay): pid_log = log.ControlsState.LateralTorqueState.new_message() + pid_log.version = VERSION + measured_curvature = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) + measurement = measured_curvature * CS.vEgo ** 2 + future_desired_lateral_accel = desired_curvature * CS.vEgo ** 2 + self.lat_accel_request_buffer.append(future_desired_lateral_accel) + + roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY + curvature_deadzone = abs(VM.calc_curvature(math.radians(self.steering_angle_deadzone_deg), CS.vEgo, 0.0)) + lateral_accel_deadzone = curvature_deadzone * CS.vEgo ** 2 + + delay_frames = int(np.clip(lat_delay / self.dt + 1, 1, self.lat_accel_request_buffer_len)) + expected_lateral_accel = self.lat_accel_request_buffer[-delay_frames] + setpoint = expected_lateral_accel + error = setpoint - measurement + + lookahead_idx = int(np.clip(-delay_frames + self.lookahead_frames, -self.lat_accel_request_buffer_len+1, -2)) + raw_lateral_jerk = (self.lat_accel_request_buffer[lookahead_idx+1] - self.lat_accel_request_buffer[lookahead_idx-1]) / (2 * self.dt) + desired_lateral_jerk = self.jerk_filter.update(raw_lateral_jerk) + gravity_adjusted_future_lateral_accel = future_desired_lateral_accel - roll_compensation + ff = gravity_adjusted_future_lateral_accel + # latAccelOffset corrects roll compensation bias from device roll misalignment relative to car roll + ff -= self.torque_params.latAccelOffset + ff += get_friction(error + JERK_GAIN * desired_lateral_jerk, lateral_accel_deadzone, FRICTION_THRESHOLD, self.torque_params) + if not active: output_torque = 0.0 pid_log.active = False else: - actual_curvature_vm = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) - roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY - if self.use_steering_angle: - actual_curvature = actual_curvature_vm - curvature_deadzone = abs(VM.calc_curvature(math.radians(self.steering_angle_deadzone_deg), CS.vEgo, 0.0)) - else: - assert calibrated_pose is not None - actual_curvature_pose = calibrated_pose.angular_velocity.yaw / CS.vEgo - actual_curvature = interp(CS.vEgo, [2.0, 5.0], [actual_curvature_vm, actual_curvature_pose]) - curvature_deadzone = 0.0 - desired_lateral_accel = desired_curvature * CS.vEgo ** 2 - - # desired rate is the desired rate of change in the setpoint, not the absolute desired curvature - # desired_lateral_jerk = desired_curvature_rate * CS.vEgo ** 2 - actual_lateral_accel = actual_curvature * CS.vEgo ** 2 - lateral_accel_deadzone = curvature_deadzone * CS.vEgo ** 2 - - low_speed_factor = interp(CS.vEgo, LOW_SPEED_X, LOW_SPEED_Y)**2 - setpoint = desired_lateral_accel + low_speed_factor * desired_curvature - measurement = actual_lateral_accel + low_speed_factor * actual_curvature - gravity_adjusted_lateral_accel = desired_lateral_accel - roll_compensation - torque_from_setpoint = self.torque_from_lateral_accel(LatControlInputs(setpoint, roll_compensation, CS.vEgo, CS.aEgo), self.torque_params, - setpoint, lateral_accel_deadzone, friction_compensation=False, gravity_adjusted=False) - torque_from_measurement = self.torque_from_lateral_accel(LatControlInputs(measurement, roll_compensation, CS.vEgo, CS.aEgo), self.torque_params, - measurement, lateral_accel_deadzone, friction_compensation=False, gravity_adjusted=False) - pid_log.error = torque_from_setpoint - torque_from_measurement - ff = self.torque_from_lateral_accel(LatControlInputs(gravity_adjusted_lateral_accel, roll_compensation, CS.vEgo, CS.aEgo), self.torque_params, - desired_lateral_accel - actual_lateral_accel, lateral_accel_deadzone, friction_compensation=True, - gravity_adjusted=True) - - freeze_integrator = steer_limited or CS.steeringPressed or CS.vEgo < 5 - output_torque = self.pid.update(pid_log.error, - feedforward=ff, - speed=CS.vEgo, - freeze_integrator=freeze_integrator) + # do error correction in lateral acceleration space, convert at end to handle non-linear torque responses correctly + pid_log.error = float(error) + + freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5 + output_lataccel = self.pid.update(pid_log.error, speed=CS.vEgo, feedforward=ff, freeze_integrator=freeze_integrator) + output_torque = self.torque_from_lateral_accel(output_lataccel, self.torque_params) pid_log.active = True - pid_log.p = self.pid.p - pid_log.i = self.pid.i - pid_log.d = self.pid.d - pid_log.f = self.pid.f - pid_log.output = -output_torque - pid_log.actualLateralAccel = actual_lateral_accel - pid_log.desiredLateralAccel = desired_lateral_accel - pid_log.saturated = self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited) + pid_log.p = float(self.pid.p) + pid_log.i = float(self.pid.i) + pid_log.d = float(self.pid.d) + pid_log.f = float(self.pid.f) + pid_log.output = float(-output_torque) # TODO: log lat accel? + pid_log.actualLateralAccel = float(measurement) + pid_log.desiredLateralAccel = float(setpoint) + pid_log.desiredLateralJerk = float(desired_lateral_jerk) + pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited)) # TODO left is positive in this convention return -output_torque, 0.0, pid_log diff --git a/selfdrive/controls/lib/lateral_mpc_lib/SConscript b/selfdrive/controls/lib/lateral_mpc_lib/SConscript index 2c03da06a626df..5ff526ae83ec17 100644 --- a/selfdrive/controls/lib/lateral_mpc_lib/SConscript +++ b/selfdrive/controls/lib/lateral_mpc_lib/SConscript @@ -1,4 +1,4 @@ -Import('env', 'envCython', 'arch', 'msgq_python', 'common_python', 'opendbc_python', 'np_version') +Import('env', 'envCython', 'arch', 'msgq_python', 'common_python', 'np_version', 'acados') gen = "c_generated_code" @@ -45,40 +45,52 @@ generated_files = [ f'{gen}/lat_cost/lat_cost.h', ] + build_files -acados_dir = '#third_party/acados' -acados_templates_dir = '#third_party/acados/acados_template/c_templates_tera' +acados_include_dir = Dir(acados.INCLUDE_DIR) +acados_template_dir = Dir(acados.TEMPLATE_DIR) source_list = ['lat_mpc.py', '#selfdrive/modeld/constants.py', - f'{acados_dir}/include/acados_c/ocp_nlp_interface.h', - f'{acados_templates_dir}/acados_solver.in.c', + acados_include_dir.File('acados_c/ocp_nlp_interface.h'), + acados_template_dir.File('c_templates_tera/acados_solver.in.c'), ] lenv = env.Clone() +copied_acados_libs = [] +if arch != "Darwin": + for lib in ["libacados.so", "libblasfeo.so", "libhpipm.so", "libqpOASES_e.so.3.1"]: + copied_acados_libs += lenv.Command(f"{gen}/{lib}", Dir(acados.LIB_DIR).File(lib), [Mkdir(Dir(gen)), Copy("$TARGET", "$SOURCE")]) + lenv["RPATH"] += [lenv.Literal('\\$$ORIGIN')] +else: + acados_rel_path = Dir(gen).rel_path(Dir(acados.LIB_DIR)) + lenv["RPATH"] += [lenv.Literal(f'\\$$ORIGIN/{acados_rel_path}')] lenv.Clean(generated_files, Dir(gen)) generated_lat = lenv.Command(generated_files, source_list, f"cd {Dir('.').abspath} && python3 lat_mpc.py") -lenv.Depends(generated_lat, [msgq_python, common_python, opendbc_python]) +lenv.Depends(generated_lat, [msgq_python, common_python]) lenv["CFLAGS"].append("-DACADOS_WITH_QPOASES") lenv["CXXFLAGS"].append("-DACADOS_WITH_QPOASES") lenv["CCFLAGS"].append("-Wno-unused") if arch != "Darwin": lenv["LINKFLAGS"].append("-Wl,--disable-new-dtags") +else: + lenv["LINKFLAGS"].append("-Wl,-install_name,@loader_path/libacados_ocp_solver_lat.dylib") + lenv["LINKFLAGS"].append(f"-Wl,-rpath,@loader_path/{acados_rel_path}") lib_solver = lenv.SharedLibrary(f"{gen}/acados_ocp_solver_lat", build_files, LIBS=['m', 'acados', 'hpipm', 'blasfeo', 'qpOASES_e']) # generate cython stuff -acados_ocp_solver_pyx = File("#third_party/acados/acados_template/acados_ocp_solver_pyx.pyx") -acados_ocp_solver_common = File("#third_party/acados/acados_template/acados_solver_common.pxd") +acados_ocp_solver_pyx = acados_template_dir.File('acados_ocp_solver_pyx.pyx') +acados_ocp_solver_common = acados_template_dir.File('acados_solver_common.pxd') libacados_ocp_solver_pxd = File(f'{gen}/acados_solver.pxd') libacados_ocp_solver_c = File(f'{gen}/acados_ocp_solver_pyx.c') lenv2 = envCython.Clone() -lenv2["LINKFLAGS"] += [lib_solver[0].get_labspath()] +lenv2["LIBPATH"] += [lib_solver[0].dir.abspath] +lenv2["RPATH"] += [lenv2.Literal('\\$$ORIGIN')] lenv2.Command(libacados_ocp_solver_c, [acados_ocp_solver_pyx, acados_ocp_solver_common, libacados_ocp_solver_pxd], f'cython' + \ @@ -86,6 +98,7 @@ lenv2.Command(libacados_ocp_solver_c, f' -I {libacados_ocp_solver_pxd.get_dir().get_labspath()}' + \ f' -I {acados_ocp_solver_common.get_dir().get_labspath()}' + \ f' {acados_ocp_solver_pyx.get_labspath()}') -lib_cython = lenv2.Program(f'{gen}/acados_ocp_solver_pyx.so', [libacados_ocp_solver_c]) +lib_cython = lenv2.Program(f'{gen}/acados_ocp_solver_pyx.so', [libacados_ocp_solver_c], LIBS=['acados_ocp_solver_lat']) lenv2.Depends(lib_cython, lib_solver) +lenv2.Depends(lib_cython, copied_acados_libs) lenv2.Depends(libacados_ocp_solver_c, np_version) diff --git a/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py b/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py index ad60861088bec4..3b597b2e428995 100755 --- a/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py +++ b/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py @@ -8,7 +8,7 @@ from openpilot.selfdrive.modeld.constants import ModelConstants if __name__ == '__main__': # generating code - from openpilot.third_party.acados.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver + from acados.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver else: from openpilot.selfdrive.controls.lib.lateral_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython diff --git a/selfdrive/controls/lib/ldw.py b/selfdrive/controls/lib/ldw.py new file mode 100644 index 00000000000000..78a6d6cf6eee49 --- /dev/null +++ b/selfdrive/controls/lib/ldw.py @@ -0,0 +1,41 @@ +from cereal import log +from openpilot.common.realtime import DT_CTRL +from openpilot.common.constants import CV + + +CAMERA_OFFSET = 0.04 +LDW_MIN_SPEED = 31 * CV.MPH_TO_MS +LANE_DEPARTURE_THRESHOLD = 0.1 + +class LaneDepartureWarning: + def __init__(self): + self.left = False + self.right = False + self.last_blinker_frame = 0 + + def update(self, frame, modelV2, CS, CC): + if CS.leftBlinker or CS.rightBlinker: + self.last_blinker_frame = frame + + recent_blinker = (frame - self.last_blinker_frame) * DT_CTRL < 5.0 # 5s blinker cooldown + ldw_allowed = CS.vEgo > LDW_MIN_SPEED and not recent_blinker and not CC.latActive + + desire_prediction = modelV2.meta.desirePrediction + if len(desire_prediction) and ldw_allowed: + right_lane_visible = modelV2.laneLineProbs[2] > 0.5 + left_lane_visible = modelV2.laneLineProbs[1] > 0.5 + l_lane_change_prob = desire_prediction[log.Desire.laneChangeLeft] + r_lane_change_prob = desire_prediction[log.Desire.laneChangeRight] + + lane_lines = modelV2.laneLines + l_lane_close = left_lane_visible and (lane_lines[1].y[0] > -(1.08 + CAMERA_OFFSET)) + r_lane_close = right_lane_visible and (lane_lines[2].y[0] < (1.08 - CAMERA_OFFSET)) + + self.left = bool(l_lane_change_prob > LANE_DEPARTURE_THRESHOLD and l_lane_close) + self.right = bool(r_lane_change_prob > LANE_DEPARTURE_THRESHOLD and r_lane_close) + else: + self.left, self.right = False, False + + @property + def warning(self) -> bool: + return bool(self.left or self.right) diff --git a/selfdrive/controls/lib/lead_approach.py b/selfdrive/controls/lib/lead_approach.py new file mode 100644 index 00000000000000..29c5d9224033a1 --- /dev/null +++ b/selfdrive/controls/lib/lead_approach.py @@ -0,0 +1,1050 @@ +"""Shared lead / follow helpers kept after the unified controller became the sole path. + +The earlier (#214-#244) lead-approach overlay chain is gone: the planner now +hands every live or held lead to `unified_lead.UnifiedLeadController`. What +remains here is consumed outside that overlay: + +- lead hold tracking and approach gating for the planner + (`resolve_lead_close_hold`, `lead_close_should_cap`, `lead_approach_track_ok`) +- LongControl's follow actuator guard and residual window + (`guard_follow_actuator_regen`, `LeadResidualWindow`) +- the Pre-AP plant regen guard installed by card.py + (`install_preap_plant_regen_guard`, `plant_regen_effort_limits`) +- follow-distance helpers (`nap_t_follow`, `NAP_T_FOLLOW`, `lead_follow_slack_m`) +""" + +from __future__ import annotations + +import math +from collections import deque + +from openpilot.selfdrive.mapd.constants import TRACK_DEADBAND_MS + + + +# Keep in sync with long_mpc.STOP_DISTANCE (acados cruise/lead obstacle). +STOP_DISTANCE = 6.0 + + +# Comfort peak |a|. Early map brake, not Normal 0.80 — Tesla VirtualDAS +# regen at 0.80 then rematch chatters on a slight grade. Do not raise. +# MPC 2.5 / FCW still own danger. Rapid closes only. +LEAD_APPROACH_A_MS2 = 0.55 + + +# Usable Bosch ceiling. Old 140 m waited until late in the gap; 200 m is +# still inside typical Pre-AP Bosch reports. Anti-flicker is quality + +# hysteresis, not a short ceiling — see lead_approach_track_ok. +LEAD_APPROACH_MAX_START_M = 200.0 + + +# Hold a few meters past the ceiling so a track at 199–201 m does not chatter. +LEAD_APPROACH_MAX_HOLD_M = 8.0 + + +# Inside this, leadOne.status is enough. Beyond it, require radar +# association so vision-only far flicker cannot own the plan. Radar +# tracks do not wait on modelProb. LeadData has no track age on Pre-AP. +LEAD_APPROACH_RELIABLE_M = 140.0 + + +LEAD_APPROACH_MODEL_PROB_MIN = 0.50 # radard association gate + + +# Mild-close comfort ceiling. Kinematics used to hit 0.55 on a 3–10 mph +# close right at the gap (hard let-off). Light regen / ease-off only. +# Rapid (high closing rate) keeps the 0.55 path. +LEAD_APPROACH_MILD_A_MS2 = 0.22 + + +# Rapid / dumping: closing rate high (much faster than lead). ~13 mph. +# Short TTC at a mild v_rel is "almost at the gap", not dumping — do not +# promote that to 0.55. +LEAD_APPROACH_RAPID_DV_MS = 6.0 + + +# Closing this fast can release the MILD floor, but only with brake +# evidence: firm aLead (below −0.35), #222 residual / rising close, +# confirmed rapid, FCW, shouldStop, or near-bumper. 1.5 m/s alone is +# a non-braking catch-up (22:12:04) and stays on MILD. +LEAD_APPROACH_SOFT_LIMIT_CLOSE_MS = 1.5 + + +# Lead clearly braking. −0.2 is a real coast/brake, not aLeadK noise at 0. +LEAD_APPROACH_SOFT_LIMIT_ALEAD_MS2 = -0.2 + + +# Owned-lead rising close. Above rematch-enter jitter (0.55) so a +# matched follow whose closing starts climbing is the brake signal +# before 1.5. One-frame radar chatter must not count as a rise. +LEAD_SOFT_LIMIT_RISE_MS = 0.15 + + +# Unexplained closing accel after subtracting ego's own a. Same +# spirit as aLead ≤ −0.2: residual ≥ 0.2 means the lead is braking. +LEAD_SOFT_LIMIT_RESIDUAL_MS2 = 0.2 + + +# #222 residual / rising close, de-noised. One radar LSB (1/16 m/s) over +# a planner frame is 1.25 m/s² and used to cancel every comfort floor. +# Require a ~0.5 s window of measured accel, then two frames of it. +LEAD_RESIDUAL_WINDOW_S = 0.50 + + +LEAD_RESIDUAL_SUSTAIN_MS2 = 0.45 + + +LEAD_RESIDUAL_SUSTAIN_N = 2 + + +LEAD_RESIDUAL_WINDOW_RISE_MS = 0.25 + + +# Closing ≥ 1 m/s and mild (−0.22) cannot finish at Follow Distance: +# brake the kinematic need, capped short of the regen rail. +# The planned approach is sized for LEAD_APPROACH_A_MS2 (0.55). A gap +# at that slack stays mild. Deepen only once slack is clearly inside it. +LEAD_KIN_APPROACH_CAP_MS2 = 0.60 + + +# While slack is still above the 3 m floor, the late bite stops at −0.45 +# so a hot approach does not land on the regen rail at Follow Distance. +# Inside 3 m the −0.60 cap remains. +LEAD_KIN_APPROACH_OPEN_CAP_MS2 = 0.45 + + +LEAD_KIN_APPROACH_BIAS_MS2 = 0.05 + + +LEAD_KIN_APPROACH_SLACK_FLOOR_M = 3.0 + + +LEAD_KIN_APPROACH_PAST_MILD_MS2 = 0.15 + + +LEAD_KIN_APPROACH_DESIGN_MARGIN_M = 0.5 + + +# Bias-corrected IMU: orientationNED[1] reads about +0.02 rad uphill. +# Grade effort is sin(pitch − bias) · g. Plant opens below −0.08 m/s². +# Profile sizing opens below −1.5% (~−0.147 m/s²) or a stuck-positive shortfall. +PLANT_PITCH_BIAS_RAD = 0.02 + + +PLANT_GRAVITY_MS2 = 9.81 + + +PLANT_DESCENT_GRADE_MS2 = -0.08 + + +PLANT_DESCENT_SHORTFALL_MS2 = 0.15 + + +PLANT_DESCENT_SHORTFALL_HOLD_S = 1.5 + + +PLANT_PID_WINDOW_S = 1.0 + + +PLANT_PID_SHORTFALL_MS2 = 0.10 + + +# Extra effort room so the inner PID can trim down. Not the regen rail. +PLANT_PID_TRIM_CAP_MS2 = 0.30 + + +# Firm lead (aLead < −0.35), closing ≥ 1.5, slack still 20–50 m: start +# the kinematic brake now instead of sitting on mild until the gap is +# short. Cap ~−1.0. Inside 20 m, confirmed rapid, and near-bumper stay +# on full #222 authority. +LEAD_FIRM_EARLY_CAP_MS2 = 1.0 + + +# Never rematch / cruise +a into a live or held closing gap. 1.0 m/s +# (~2.2 mph) is above rematch-enter jitter; 1.5 is match-speed / ownership. +LEAD_CLOSING_REMATCH_BLOCK_MS = 1.0 + + +LEAD_CLOSING_ALEAD_MS2 = LEAD_APPROACH_SOFT_LIMIT_ALEAD_MS2 + + +# aLead-only ownership / match-aLeadK. Opening or slack ≳ 20 m must not +# force aTarget ≤ aLeadK (far braking lead, gap opening). Near-gap +# braking-lead protection still matches. 20 m is inside the 15–25 m tune. +LEAD_ALEAD_MATCH_SLACK_M = 20.0 + + +# Enter / exit (hysteresis). A single v_rel / slack gate chatters around +# the follow gap on a slight incline (regen ↔ accel). First pass was +# 0.50 / 0.20; leftover bump-pull was rematch re-crossing 0.50. Raise +# enter only — a 0.12 exit held ease too long and parked far back. +LEAD_APPROACH_DV_MS = 0.55 # enter: ~1.2 mph closing; ignore radar jitter + + +NAP_T_FOLLOW = (0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9) + + +# Same Bosch ceiling as ease. A 160–180 m same-speed lead used to skip the +# cap and punch cruise / MAX-rise to close Follow Distance. Do not. +LEAD_CLOSE_MAX_M = LEAD_APPROACH_MAX_START_M + + +# Near Follow Distance, rematch after ease must trickle. Large-gap +# catch-up uses Mannerisms Accel (same as open-road). +LEAD_CLOSE_OPENING_A_MS2 = 0.08 + + +# Mid-gap rematch while still slowly closing (ef 10:18). Slack above +# the near-gap rematch band and not past 50 m, closing ~0.8–2.0 m/s: +# trickle, not Accel ceil. Slack > 50 is large-gap catch-up (Accel), +# even while still closing in-band. Opening / same-speed is Accel. +# Rapid / match-speed ≥ 1.5 still owns −a. +LEAD_MID_GAP_SLACK_M = 50.0 + + +LEAD_MID_GAP_CLOSE_HI_MS = 2.0 + + +# Map FOLLOW above MAX with a steady mid-gap lead (Scallywag 16:22: +# slack ~19 m, dRel ~60 m, closing ~0.5). Do not pass a −1.4…−3.5 +# cruise/map cliff through. Comfort floor is the early map brake +# (−0.55), inside −0.4…−0.6, so the limit still comes back. +# Slack ~8–50 m. Farther than that, map decel still mins in. +LEAD_MAP_MIDGAP_SLACK_LO_M = 8.0 + + +LEAD_MAP_MIDGAP_FLOOR_MS2 = 0.55 + + +LEAD_MAP_MIDGAP_DREL_HI_M = 80.0 + + +# Inside this dRel, never soften MPC −a (near bumper). +LEAD_MPC_SOFT_NEAR_M = 12.0 + + +# Near-gap small ±a slew (rematch trickle ↔ leftover mild). +LEAD_NEAR_GAP_SLACK_M = 15.0 + + +# Plant regen dump while the planner is coasting or easing. The steady +# band used to be |a| ≤ 0.08, so a commanded MILD (−0.22) unlocked the +# Pre-AP regen rail (18:10:08: aTarget −0.218, act −1.32). Cover +# |aTarget| ≤ MILD + ε so slight lift cannot full-lift. Planner ≤ −0.5 +# / FCW / confirmed rapid / near-bumper still pass through. +LEAD_FOLLOW_STEADY_EPS_MS2 = 0.03 + + +LEAD_FOLLOW_STEADY_A_MS2 = LEAD_APPROACH_MILD_A_MS2 + LEAD_FOLLOW_STEADY_EPS_MS2 + + +LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2 = -LEAD_APPROACH_MILD_A_MS2 + + +# #232 widened one band to MILD+ε, so a steady command (aTarget ≈ 0) +# opened the mild settle. The old steady band is the plant cap until the +# command has actually dwelled at the settle. 23:16:45 / 23:22:48 CT. +LEAD_FOLLOW_STEADY_ONLY_MS2 = 0.08 + + +# At or below this, and still above a firm brake, the command is asking +# for the EV mild settle rather than steady following. +LEAD_PLANT_MILD_ENTER_MS2 = 0.16 + + +LEAD_PLANT_MILD_DWELL_S = 0.40 + + +LEAD_PLANT_STEADY_DWELL_S = 0.40 + + +LEAD_FOLLOW_ACT_REGEN_CMD_MS2 = -0.50 + + +# Cruise / weak-lead0 ACCEL_MIN where mid-gap and near-gap overlap. +# 0000010e 20:10:48 / 20:11:30 / 20:18:23: source cruise, slack ~12 m, +# close ~0.7, aLead ~−0.25, plan_min ≥ 0, aTarget −3. Near-gap match +# owns aLead ≤ −0.2, so the coast floor bailed. That aLead is not a +# firm brake (≲ −0.4 with a real close). aLead at or above this still +# floors; anything firmer stays on the raw near-gap path. +LEAD_CRUISE_CLIFF_ALEAD_MS2 = -0.35 + + +# Internal v_rel = v_ego − v_lead (positive closes). Radar vRel is the +# opposite sign. Clearly opening, past match noise: 10:05 onset was +# about −0.56 (radar +0.56) with slack ~9 m and aLeadK only −0.32. +# A single sample milder than this can still be near-gap noise; a +# run of any opening vRel latches the release below. +LEAD_OPENING_VREL_MS = -0.25 + + +# Brief hold of the last in-window lead when `leadOne.status` drops so +# cruise punch cannot leak through a radar flicker. ~10 planner frames. +LEAD_CLOSE_HOLD_S = 0.50 + + +def nap_t_follow(nap_follow_dist: int | None) -> float | None: + if nap_follow_dist in range(1, len(NAP_T_FOLLOW) + 1): + return NAP_T_FOLLOW[nap_follow_dist - 1] + return None + + +def lead_follow_slack_m(d_rel, v_lead, t_follow): + """Meters above the selected Follow Distance, or None if unknown.""" + if d_rel is None or t_follow is None or float(t_follow) <= 0: + return None + d_follow = float(t_follow) * max(0.0, float(v_lead)) + STOP_DISTANCE + return float(d_rel) - d_follow + + +def lead_midgap_comfort_excluded(v_rel, d_rel, slack, fcw=False, crash_cnt=0, + allow_rapid=False, a_lead=None, + prev_v_rel=None, a_ego=None, dt=None, + should_stop=False) -> bool: + """True when a mid-gap comfort cap must not apply. + + FCW, shouldStop, rapid close, and near-bumper stay raw. Close ≥ 1.5 + alone does not: a non-braking catch-up stays in the cap. Firm aLead + (below −0.35) or #222 residual / rising close still excludes. + Outside the slack ~8–50 m band (or the dRel stand-in) is not this + settle. Fast opening (|v_rel| ≥ ~2 m/s) is not a slow close. + """ + _ = allow_rapid + if should_stop or fcw or int(crash_cnt) > 0: + return True + if d_rel is not None and float(d_rel) <= LEAD_MPC_SOFT_NEAR_M: + return True + if d_rel is not None and (float(d_rel) - STOP_DISTANCE) <= 0.0: + return True + if v_rel is not None and lead_approach_is_rapid(float(v_rel)): + return True + if not lead_mid_gap_map_band(slack, d_rel): + return True + if v_rel is None: + return False + v = float(v_rel) + if v >= LEAD_APPROACH_SOFT_LIMIT_CLOSE_MS: + # Catch-up speed is not a brake. 22:12:04 stayed on MILD until + # slack crossed 20 m, then this gate unlocked the regen rail. + return lead_firm_alead(a_lead) or lead_rising_or_residual_brake( + v, prev_v_rel, a_ego, dt, + ) + if abs(v) >= LEAD_MID_GAP_CLOSE_HI_MS: + return True + return False + + +def lead_near_gap_alead_raw(v_rel, a_lead, slack, owned=False, prev_v_rel=None) -> bool: + """True when near-gap lead braking must stay raw. + + Slack at or under the near-gap band with a meaningful negative aLead + is match-aLead (dRel = follow + 8 m, closing ~0.4 m/s, aLeadK −0.80) + even while the MPC horizon is still cruise. Hold-owned is the same + brake. A slack-~19 m cliff (−1.4…−3.5) with a coasting plan is not + this path. Clearly opening with positive slack is not this path + either — filtered aLeadK does not keep the cliff. + """ + if slack is None or float(slack) > LEAD_NEAR_GAP_SLACK_M: + return False + if lead_kinematics_opening(v_rel, slack): + return False + line = lead_weak_alead_line(v_rel, prev_v_rel) + if lead_alead_owns_match(v_rel, a_lead, slack, a_lead_ms2=line): + return True + if not owned or a_lead is None: + return False + return float(a_lead) <= line + + +def guard_follow_actuator_regen(actuator_a, planner_a, v_rel=None, d_rel=None, + slack=None, fcw=False, crash_cnt=0, + allow_rapid=False, v_ego=None, v_cruise=None, + a_lead=None, owned=False, prev_v_rel=None, + a_ego=None, dt=None, should_stop=False): + """Do not dump firm plant regen on a coast or a mild ease. + + ef 10:18:42: aTarget ≈ 0 while actuators.accel hit −1.23. 18:09 / + 18:10: a coasting or MILD aTarget still reached the Pre-AP regen rail. + A steady command is held in the steady band. It does not open the + mild settle. A command already on that settle is clipped to it, and + the plant dwells before a flicker can leak steady following into mild. + A non-braking mid-gap close follows the planner command. The old + −0.22 / −0.45 comfort cap on that case is retired: it stepped off + at 6 m/s of closing speed and then released into a late slam. + Firm-lead and #222 residual closes still hard-cap, and the latch + keeps a firm plan from falling back to MILD. Near-gap match-aLead + is a real brake and is not that hard cap. + Planner ≤ −0.5 outside that settle, FCW, confirmed rapid, and + near-bumper pass through. + """ + if actuator_a is None or planner_a is None: + return actuator_a + a = float(actuator_a) + p = float(planner_a) + floor = LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2 + emergency = ( + fcw or int(crash_cnt) > 0 + or (d_rel is not None and float(d_rel) <= LEAD_MPC_SOFT_NEAR_M) + or (allow_rapid and v_rel is not None and lead_approach_is_rapid(float(v_rel))) + ) + if emergency: + return a + # Large-slack firm lead: track the early kinematic brake, not the rail. + # Confirmed rapid still falls through to full authority below. + if not (v_rel is not None and lead_approach_is_rapid(float(v_rel))): + firm_early = lead_firm_large_slack_a(v_rel, slack, a_lead) + if firm_early is not None: + return a if a >= firm_early else firm_early + if (not lead_near_gap_alead_raw( + v_rel, a_lead, slack, owned=owned, prev_v_rel=prev_v_rel) + and not lead_midgap_comfort_excluded( + v_rel, d_rel, slack, fcw=False, crash_cnt=0, allow_rapid=False, + a_lead=a_lead, prev_v_rel=prev_v_rel, a_ego=a_ego, dt=dt, + should_stop=should_stop, + )): + # Under the map, slight lift. Over the map, keep the #231 comfort + # brake (−0.55) so a limit return is not lifted back to MILD. + if lead_map_decel_above_max(v_ego, v_cruise): + floor = -LEAD_MAP_MIDGAP_FLOOR_MS2 + else: + kin = lead_kinematic_approach_a(v_rel, slack, a_lead) + if kin is not None: + floor = min(floor, kin) + # Non-braking slow close: do not hold the actuator at the mild + # settle or the −0.45 kinematic cap after the follow law has + # already chosen the brake. That post-planner clamp is what let a + # 25 mph lead close to ~7 m (closing just under 6 m/s, slack still + # 8–50 m). Comfort for this case is the follow law's own filtered + # inputs. The floor may not be softer than the planner command. + # A coast or a command already on the mild settle is not below the + # floor, so plant windup protection is unchanged. Firm leads and + # #222 residuals keep the cap; the latch owns that cliff. + if (p < floor + and not lead_firm_alead(a_lead) + and not lead_rising_or_residual_brake( + v_rel, prev_v_rel, a_ego, dt)): + floor = p + return a if a >= floor else floor + if p <= LEAD_FOLLOW_ACT_REGEN_CMD_MS2: + return a + if abs(p) > LEAD_FOLLOW_STEADY_A_MS2: + return a + # Steady following does not open the mild settle. A command that is + # already at that settle still cannot reach the regen rail. + allowed = plant_follow_floor(p, instant_plant_decel_mode(p)) + return a if a >= allowed else allowed + + +def instant_plant_decel_mode(planner_a) -> str: + """STEADY or MILD from one command, for a sustained sample. + + A coast or a small ease is steady. A command sitting on the EV settle + is mild. A firm brake is not classified here; callers leave the rail + open before asking. + """ + try: + p = float(planner_a) + except (TypeError, ValueError): + return "steady" + if not math.isfinite(p): + return "steady" + if LEAD_FOLLOW_ACT_REGEN_CMD_MS2 < p <= -LEAD_PLANT_MILD_ENTER_MS2: + return "mild" + return "steady" + + +def plant_follow_floor(planner_a, mode: str) -> float: + """Deepest plant accel a steady or mild command may use. + + MILD holds the EV settle (−0.22) and tracks a command that is already + below it, still inside the band that reaches this helper. STEADY tracks + a small negative command and never opens that settle: a zero command + stays at 0, and a not-yet-confirmed dip toward −0.22 is held at the + old steady band. + """ + try: + p = float(planner_a) + except (TypeError, ValueError): + p = 0.0 + if not math.isfinite(p): + p = 0.0 + mild = LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2 + if mode == "mild": + return p if p < mild else mild + if p >= -LEAD_FOLLOW_STEADY_ONLY_MS2: + return min(p, 0.0) + if p > mild: + return p + return -LEAD_FOLLOW_STEADY_ONLY_MS2 + + +class PlantDecelClassifier: + """Dwell between STEADY and MILD so following does not leak the settle. + + Enter MILD only after the command has sat on the EV settle. Leave only + after it has sat back in the steady band. The band between the two + holds the current mode, and a firm brake freezes it: that command is + neither a mild settle nor a return to steady. + """ + + def __init__(self) -> None: + self.mode = "steady" + self._dwell_s = 0.0 + + def reset(self) -> None: + self.mode = "steady" + self._dwell_s = 0.0 + + def update(self, planner_a, dt) -> str: + try: + p = 0.0 if planner_a is None else float(planner_a) + except (TypeError, ValueError): + p = 0.0 + if not math.isfinite(p): + p = 0.0 + frame = 0.02 if dt is None or float(dt) <= 1e-6 else float(dt) + if p <= LEAD_FOLLOW_ACT_REGEN_CMD_MS2: + self._dwell_s = 0.0 + return self.mode + want_mild = p <= -LEAD_PLANT_MILD_ENTER_MS2 + want_steady = p >= -LEAD_FOLLOW_STEADY_ONLY_MS2 + if self.mode != "mild" and want_mild: + self._dwell_s += frame + if self._dwell_s + 1e-9 >= LEAD_PLANT_MILD_DWELL_S: + self.mode = "mild" + self._dwell_s = 0.0 + elif self.mode != "steady" and want_steady: + self._dwell_s += frame + if self._dwell_s + 1e-9 >= LEAD_PLANT_STEADY_DWELL_S: + self.mode = "steady" + self._dwell_s = 0.0 + else: + self._dwell_s = 0.0 + return self.mode + + +def plant_regen_effort_limits(a_cmd, limits, *, steady_grade=0.0, transient=0.0, + descent=False, pid_room=0.0, decel_mode=None): + """VirtualDAS effort bounds while the command is coast or mild. + + Returns `limits` unchanged when the command is a firm brake. A steady + command cannot use the mild settle. A mild command cannot use the regen + rail: the lower bound is the EV settle. An existing tighter bound + (engage grace) is kept. `decel_mode` is the dwelt class from + PlantDecelClassifier; omitted, the command is classified on this sample. + + On a descent the floor applies to the net command, so the downhill + grade term is not clipped off, and a sustained positive aEgo error + may pull the inner PID through. Uphill and flat leave the floor on + the command alone. Full regen stays reserved for cmd ≤ −0.60. + """ + if a_cmd is None: + return limits + p = float(a_cmd) + # Deeper than map comfort is a real brake: leave the regen rail open. + if p < -LEAD_MAP_MIDGAP_FLOOR_MS2 - 0.05: + return limits + if decel_mode in ("steady", "mild"): + mode = decel_mode + else: + mode = instant_plant_decel_mode(p) + if mode == "mild" or abs(p) <= LEAD_FOLLOW_STEADY_A_MS2: + floor = plant_follow_floor(p, mode) + else: + # Between the mild settle and map comfort: track the command. + floor = p + if descent: + grade_sum = float(steady_grade) + float(transient) + floor = floor + min(0.0, grade_sum) + room = max(0.0, float(pid_room)) + if room > 0.0: + floor -= min(room, PLANT_PID_TRIM_CAP_MS2) + # nap_conf.REGEN_MAX. Do not import it here: that pulls capnp, and + # the effort floor must stay inside the physical rail. + floor = max(float(floor), -1.5) + if limits is None: + from opendbc.car.tesla.preap.nap_conf import ACCEL_MAX + return (floor, float(ACCEL_MAX)) + lo, hi = float(limits[0]), float(limits[1]) + return (max(lo, floor), hi) + + +def bias_corrected_grade_ms2(pitch_rad): + """IMU grade effort with the +0.02 rad uphill bias removed. + + None when pitch was not measured. A missing orientation must not + look like a descent just because the bias term is negative. + """ + if pitch_rad is None: + return None + return math.sin(float(pitch_rad) - PLANT_PITCH_BIAS_RAD) * PLANT_GRAVITY_MS2 + + +def _preview_grade_compensation(estimator, orientation_ned): + """Next-sample steady and transient grade, without stepping the filters. + + VirtualDAS.update applies the real step. The effort floor has to use + the same terms or the downhill grade is clipped before it is added. + """ + if estimator is None or orientation_ned is None or len(orientation_ned) < 2: + return 0.0, 0.0 + from numpy import clip + + from opendbc.car.tesla.preap.virtual_das import ( + GRAVITY, + MAX_PITCH_COMPENSATION, + MAX_STEADY_GRADE_COMPENSATION, + TRANSIENT_GRADE_GAIN, + ) + + maximum_pitch = math.asin(MAX_STEADY_GRADE_COMPENSATION / GRAVITY) + pitch = float(clip(float(orientation_ned[1]), -maximum_pitch, maximum_pitch)) + lp = estimator.pitch_lp + lp_x = (1.0 - lp._alpha) * lp.x + lp._alpha * pitch + f1 = estimator.pitch_hp._f1 + f2 = estimator.pitch_hp._f2 + hp_x = ( + (1.0 - f1._alpha) * f1.x + f1._alpha * pitch + - ((1.0 - f2._alpha) * f2.x + f2._alpha * pitch) + ) + steady = float(clip( + math.sin(lp_x) * GRAVITY, + -MAX_STEADY_GRADE_COMPENSATION, + MAX_STEADY_GRADE_COMPENSATION, + )) + transient = float(clip( + math.sin(hp_x) * GRAVITY * TRANSIENT_GRADE_GAIN, + -MAX_PITCH_COMPENSATION, + MAX_PITCH_COMPENSATION, + )) + return steady, transient + + +def _plant_descent_allowance(vdas, a_cmd, a_ego, orientation_ned, dt): + """Descent gate and PID room for one VirtualDAS sample. + + Grade gate is the bias-corrected IMU. The shortfall gate is aEgo − cmd + above 0.15 for 1.5 s. PID room opens when the 1 s mean aEgo stays more + than 0.10 above the command. State lives on the controller instance. + """ + frame_dt = 0.02 if dt is None or float(dt) <= 1e-6 else float(dt) + cmd = 0.0 if a_cmd is None else float(a_cmd) + ego = 0.0 if a_ego is None else float(a_ego) + hist = getattr(vdas, "_nap_descent_ego", None) + if hist is None: + hist = deque() + vdas._nap_descent_ego = hist + short_s = float(getattr(vdas, "_nap_descent_short_s", 0.0)) + if ego - cmd > PLANT_DESCENT_SHORTFALL_MS2: + short_s += frame_dt + else: + short_s = 0.0 + vdas._nap_descent_short_s = short_s + hist.append((frame_dt, ego, cmd)) + span = sum(sample_dt for sample_dt, _e, _c in hist) + while span > PLANT_PID_WINDOW_S + 1e-9 and len(hist) > 1: + drop_dt, _e, _c = hist.popleft() + span -= drop_dt + pitch = None + if orientation_ned is not None and len(orientation_ned) >= 2: + pitch = float(orientation_ned[1]) + grade = bias_corrected_grade_ms2(pitch) + descent = ( + (grade is not None and grade < PLANT_DESCENT_GRADE_MS2) + or short_s + 1e-9 >= PLANT_DESCENT_SHORTFALL_HOLD_S + ) + pid_room = 0.0 + if descent and span + 1e-9 >= PLANT_PID_WINDOW_S: + mean_ego = sum(sample_dt * sample_e for sample_dt, sample_e, _c in hist) / span + mean_cmd = sum(sample_dt * sample_c for sample_dt, _e, sample_c in hist) / span + mean_short = mean_ego - mean_cmd + if mean_short > PLANT_PID_SHORTFALL_MS2: + pid_room = min(PLANT_PID_TRIM_CAP_MS2, mean_short) + return descent, pid_room + + +def install_preap_plant_regen_guard(): + """Keep Pre-AP pedal effort on a slight lift when the command is mild. + + LongControl is pure feedforward. The regen rail is VirtualDAS effort + (grade + inner integral) after that seam. Card and the controller + share a process, so the cap is installed on VirtualDAS.update. + """ + from opendbc.car.tesla.pedal.controller import PEDAL_RAMP_RATE_UP + from opendbc.car.tesla.preap.virtual_das import VirtualDAS + + current = VirtualDAS.update + if getattr(current, "_nap_plant_regen_guard", False): + return + + def update(self, a_cmd, v_ego, prev_pedal_di, a_ego=0.0, freeze_integrator=False, + orientation_ned=None, accel_effort_limits=None, + pedal_ramp_rate_up=PEDAL_RAMP_RATE_UP): + steady, transient = _preview_grade_compensation(self.grade_estimator, orientation_ned) + descent, pid_room = _plant_descent_allowance( + self, a_cmd, a_ego, orientation_ned, self.dt, + ) + classifier = getattr(self, "_nap_plant_decel", None) + if classifier is None: + classifier = PlantDecelClassifier() + self._nap_plant_decel = classifier + return current( + self, a_cmd, v_ego, prev_pedal_di, a_ego=a_ego, + freeze_integrator=freeze_integrator, orientation_ned=orientation_ned, + accel_effort_limits=plant_regen_effort_limits( + a_cmd, accel_effort_limits, + steady_grade=steady, transient=transient, + descent=descent, pid_room=pid_room, + decel_mode=classifier.update(a_cmd, self.dt), + ), + pedal_ramp_rate_up=pedal_ramp_rate_up, + ) + + update._nap_plant_regen_guard = True + update._nap_plant_regen_raw = current + VirtualDAS.update = update + + +def lead_map_decel_above_max(v_ego, v_cruise) -> bool: + """True when map is commanding over-MAX decel (past the deadband). + + lead_at_or_above_max includes sitting *at* MAX. First-latch acquire + slew and the MILD floor must still apply there (e4 09:53:19). Map + brake only starts once ego is faster than MAX by TRACK_DEADBAND — + same edge as map_track_decel_ms2. + """ + if v_ego is None or v_cruise is None: + return False + if float(v_ego) <= 0.0 or float(v_cruise) <= 0.0: + return False + return float(v_ego) > float(v_cruise) + TRACK_DEADBAND_MS + + +def lead_mid_gap_map_band(slack, d_rel=None) -> bool: + """True when a live lead is in the mid-gap band for map comfort. + + Slack ~8–50 m when known (dig slack ~19 m). Without slack, dRel + past the bumper and not a far lock (dig ~60 m) still qualifies. + Near-bumper and large-gap catch-up stay out. + """ + if slack is not None: + s = float(slack) + return LEAD_MAP_MIDGAP_SLACK_LO_M <= s <= LEAD_MID_GAP_SLACK_M + if d_rel is None: + return False + d = float(d_rel) + return LEAD_MPC_SOFT_NEAR_M < d <= LEAD_MAP_MIDGAP_DREL_HI_M + + +def lead_close_should_cap(d_rel, model_prob=None, radar=None, active=False) -> bool: + """True when a detected lead is in the close-cap window. + + Bosch ceiling matches ease (200 m). Far tracks need radar association + so a 160 m vision flicker cannot cap empty-road climb. Radar-only + far locks do cap. Missing quality args (unit tests) are ok. + """ + if d_rel is None: + return False + d = float(d_rel) + d_max = LEAD_CLOSE_MAX_M + (LEAD_APPROACH_MAX_HOLD_M if active else 0.0) + if d <= 0.0 or d > d_max: + return False + return lead_approach_track_ok(d, model_prob, radar, active=active) + + +def resolve_lead_close_hold(status, d_rel, v_lead, held_d, held_v, held_age, dt, + hold_s=LEAD_CLOSE_HOLD_S, model_prob=None, radar=None): + """Lead used for the +a close cap, with a brief hold on status flicker. + + Live in-window lead wins, including a far Bosch track (160–200 m). + A dropped `leadOne.status` keeps the last in-window lead for `hold_s` + so cruise 1.6 cannot punch through a flicker. Past Bosch, or a + vision-only far flicker with no hold, drops so empty-road MAX-rise + is not stuck capped. + + Returns `(d_use, v_use, held_d, held_v, held_age)`. `d_use` is None + when the cap should not apply. + """ + holding = held_d is not None + if status and lead_close_should_cap(d_rel, model_prob, radar, active=holding) and v_lead is not None: + d = float(d_rel) + v = float(v_lead) + return d, v, d, v, 0.0 + + past_bosch = ( + d_rel is not None and float(d_rel) > LEAD_CLOSE_MAX_M + LEAD_APPROACH_MAX_HOLD_M + ) + if past_bosch or held_d is None or held_v is None: + return None, None, None, None, 0.0 + + age = float(held_age) + float(dt) + if age > float(hold_s): + return None, None, None, None, 0.0 + return float(held_d), float(held_v), float(held_d), float(held_v), age + + +def lead_approach_track_ok(d_rel, model_prob=None, radar=None, active=False) -> bool: + """Far-track anti-flicker. LeadData has modelProb + radar; no track age. + + Inside RELIABLE_M, `leadOne.status` is enough (planner already gated). + Beyond it, enter needs a radar-associated lead (`radar=True`) so a + 160–200 m Bosch lock can ease / show immediately. Vision-only far + flicker stays off. Missing quality args (unit kinematics) are ok. + Once active, hold through a brief quality dip so far tracks do not + chatter. + """ + if d_rel is None: + return False + d = float(d_rel) + if d <= LEAD_APPROACH_RELIABLE_M or active: + return True + if radar is False: + return False + # Solid Bosch association: ease / cap from first far lock. Do not wait + # on modelProb — that delayed yellow-arrow reaction on radar-only tracks. + # Vision-only far flicker still stays off. + if radar is True: + return True + if model_prob is not None and float(model_prob) < LEAD_APPROACH_MODEL_PROB_MIN: + return False + return True + + +def lead_opening_sample(v_rel, slack) -> bool: + """True when internal v_rel is opening and slack is still positive. + + Inside the follow gap (slack ≤ 0) is a near-bumper / too-close bite, + not this release. Radar vRel positive is this sign flipped. + """ + if v_rel is None or slack is None: + return False + return float(v_rel) < 0.0 and float(slack) > 0.0 + + +def lead_kinematics_opening(v_rel, slack) -> bool: + """True when the gap is clearly opening, not match-noise. + + aLeadK alone must not own firm −a here. A milder negative v_rel can + still be one noisy sample; `update_opening_release` latches a run + of those. + """ + if not lead_opening_sample(v_rel, slack): + return False + return float(v_rel) < LEAD_OPENING_VREL_MS + + +def lead_alead_owns_match(v_rel, a_lead, slack=None, + a_lead_ms2=LEAD_CLOSING_ALEAD_MS2) -> bool: + """True when aLead alone may own match-speed −a / closing. + + aLead ≲ −0.2 used to own regardless of gap. A far or opening lead + (da 2026-09-18: dRel~64 m, v_rel~−1.44 opening, aLeadK~−1.46) then + snapped cruise +a to aLeadK. Gate: slack ≳ 20 m never owns from + aLead alone. Clearly opening with positive slack never owns either + (09:57 / 10:05: aLeadK ~−0.3…−0.4 on an opening gap must not skip + the mild floor). Slight opening noise near the gap, and a real + brake inside the follow gap, still match. Real closing ≳ 1.0–1.5 + is a separate v_rel gate. + """ + if a_lead is None or float(a_lead) > float(a_lead_ms2): + return False + if slack is not None and float(slack) >= LEAD_ALEAD_MATCH_SLACK_M: + return False + if lead_kinematics_opening(v_rel, slack): + return False + if v_rel is not None and float(v_rel) < 0.0: + return slack is not None + return True + + +def lead_close_is_rising(v_rel, prev_v_rel, rise_ms=LEAD_SOFT_LIMIT_RISE_MS) -> bool: + """True when closing rate increased vs the last owned-lead sample.""" + if v_rel is None or prev_v_rel is None: + return False + return float(v_rel) > float(prev_v_rel) + float(rise_ms) + + +def lead_residual_close_ms2(v_rel, prev_v_rel, a_ego, dt): + """Unexplained closing accel after subtracting ego's own a. + + Δv_rel = a_ego·dt − a_lead·dt. Residual (Δv_rel − a_ego·dt) / dt + is −a_lead: positive means the lead is braking harder than ego's + command accounts for. None when a pair of samples is missing. + """ + if v_rel is None or prev_v_rel is None or dt is None or float(dt) <= 1e-6: + return None + expected = 0.0 if a_ego is None else float(a_ego) * float(dt) + return (float(v_rel) - float(prev_v_rel) - expected) / float(dt) + + +def lead_residual_window_hit(v_rel, prev_v_rel, a_ego, dt) -> bool: + """True when a ~0.5 s window shows a real #222 residual or rise. + + One radar step over 0.05 s is not this. The legacy two-sample helper + stays available for the Sep 23 fixtures; callers that arm the comfort + floors use this window and then require two consecutive hits. + """ + if v_rel is None or prev_v_rel is None or dt is None: + return False + if float(dt) + 1e-9 < LEAD_RESIDUAL_WINDOW_S * 0.5: + return False + rise = float(v_rel) - float(prev_v_rel) + if (float(v_rel) >= LEAD_CLOSING_REMATCH_BLOCK_MS + and rise >= LEAD_RESIDUAL_WINDOW_RISE_MS): + return True + residual = lead_residual_close_ms2(v_rel, prev_v_rel, a_ego, dt) + if residual is None or residual < LEAD_RESIDUAL_SUSTAIN_MS2: + return False + return (float(v_rel) >= LEAD_APPROACH_DV_MS + and float(v_rel) > float(prev_v_rel)) + + +def update_residual_sustain(count, hit, need_n=LEAD_RESIDUAL_SUSTAIN_N): + """Hold a window hit for `need_n` frames. Returns `(armed, count)`.""" + if not hit: + return False, 0 + nxt = int(count) + 1 + return nxt >= int(need_n), nxt + + +class LeadResidualWindow: + """0.5 s v_rel / measured-aEgo history for the #222 residual gate. + + `update` returns `(prev_v_rel, dt, a_ego)` for the existing floor + helpers. `prev_v_rel` stays None until the window has been a real + brake for two frames, so a one-LSB radar tick cannot cancel a + comfort floor. When it is set, `dt` is the window length and `a_ego` + is the measured average over that window — not one commanded frame. + """ + + def __init__(self) -> None: + self.hist: deque[tuple[float, float]] = deque() + self.count = 0 + + def reset(self) -> None: + self.hist.clear() + self.count = 0 + + def update(self, v_rel, a_ego, dt) -> tuple[float | None, float, float]: + frame_dt = 0.05 if dt is None or float(dt) <= 1e-6 else float(dt) + a = 0.0 if a_ego is None else float(a_ego) + if v_rel is None: + self.reset() + return None, frame_dt, a + self.hist.append((float(v_rel), a)) + n = max(1, int(round(LEAD_RESIDUAL_WINDOW_S / frame_dt))) + while len(self.hist) > n + 1: + self.hist.popleft() + if len(self.hist) <= n: + self.count = 0 + return None, frame_dt, a + old_v = float(self.hist[0][0]) + window = list(self.hist) + a_avg = sum(sample_a for _v, sample_a in window) / float(len(window)) + dt_w = n * frame_dt + hit = lead_residual_window_hit(float(v_rel), old_v, a_avg, dt_w) + armed, self.count = update_residual_sustain(self.count, hit) + if not armed: + return None, frame_dt, a + return old_v, dt_w, a_avg + + +def lead_weak_alead_line(v_rel, prev_v_rel=None) -> float: + """aLead line that may unlock raw near the gap. + + −0.35 while closing stays under 1 m/s and is not rising. At or above + 1 m/s, or when closing is rising, keep the −0.2 line so a real close + still owns the match. + """ + v = 0.0 if v_rel is None else float(v_rel) + if v < LEAD_CLOSING_REMATCH_BLOCK_MS and not lead_close_is_rising(v_rel, prev_v_rel): + return LEAD_CRUISE_CLIFF_ALEAD_MS2 + return LEAD_CLOSING_ALEAD_MS2 + + +def lead_kinematic_approach_a(v_rel, slack, a_lead=None): + """Decel when mild cannot finish inside the planned approach distance. + + Non-braking close ≥ 1 m/s only. The planned ease is sized for + LEAD_APPROACH_A_MS2: a gap at that slack stays mild, even though + 0.22 cannot stop there. Deepen only once slack is clearly inside + that distance and the required decel is past mild by a clear + margin. Capped at −0.45 while slack is still above 3 m, and at −0.6 + once inside that, so this never becomes a regen rail. A firm + braking lead is #222, not this floor. + """ + if lead_firm_alead(a_lead): + return None + if v_rel is None or slack is None: + return None + v = float(v_rel) + if v < LEAD_CLOSING_REMATCH_BLOCK_MS or LEAD_APPROACH_A_MS2 <= 0.0: + return None + design = (v * v) / (2.0 * LEAD_APPROACH_A_MS2) + if float(slack) >= design - LEAD_KIN_APPROACH_DESIGN_MARGIN_M: + return None + s = max(float(slack), LEAD_KIN_APPROACH_SLACK_FLOOR_M) + pure = -(v * v) / (2.0 * s) + if pure >= -LEAD_APPROACH_MILD_A_MS2 - LEAD_KIN_APPROACH_PAST_MILD_MS2: + return None + cap = LEAD_KIN_APPROACH_CAP_MS2 + if float(slack) > LEAD_KIN_APPROACH_SLACK_FLOOR_M: + cap = LEAD_KIN_APPROACH_OPEN_CAP_MS2 + return max(pure - LEAD_KIN_APPROACH_BIAS_MS2, -cap) + + +def lead_firm_large_slack_a(v_rel, slack, a_lead): + """Earlier kinematic brake for a firm lead that is still 20–50 m out. + + None unless aLead is below −0.35, closing ≥ 1.5, and slack is in that + band. The result is the kinematic need capped at about −1.0. It does + not apply inside 20 m, where #222 keeps full authority. + """ + if not lead_firm_alead(a_lead): + return None + if v_rel is None or float(v_rel) < LEAD_APPROACH_SOFT_LIMIT_CLOSE_MS: + return None + if slack is None: + return None + s = float(slack) + if s <= LEAD_ALEAD_MATCH_SLACK_M or s > LEAD_MID_GAP_SLACK_M: + return None + kin = float(a_lead) - (float(v_rel) ** 2) / (2.0 * max(s, 1.0)) + return max(kin, -LEAD_FIRM_EARLY_CAP_MS2) + + +def lead_firm_alead(a_lead, firm_ms2=LEAD_CRUISE_CLIFF_ALEAD_MS2) -> bool: + """True when measured aLead is below the #237 firm-brake line. + + Equal to −0.35 is not firm. 22:14:14 (aLead −0.6…−0.7) is. + """ + return a_lead is not None and float(a_lead) < float(firm_ms2) + + +def lead_rising_or_residual_brake(v_rel, prev_v_rel=None, a_ego=None, dt=None) -> bool: + """#222: closing rate rose, or residual close beyond ego's own a. + + A steady close (v_rel not rising) is not residual brake. Same tests + the mild-floor skip uses after the static close gate. + """ + if (v_rel is not None and float(v_rel) >= LEAD_CLOSING_REMATCH_BLOCK_MS + and lead_close_is_rising(v_rel, prev_v_rel)): + return True + residual = lead_residual_close_ms2(v_rel, prev_v_rel, a_ego, dt) + if residual is not None and residual >= LEAD_SOFT_LIMIT_RESIDUAL_MS2: + if (v_rel is not None and prev_v_rel is not None + and float(v_rel) >= LEAD_APPROACH_DV_MS + and float(v_rel) > float(prev_v_rel)): + return True + return False + + +def lead_approach_is_rapid(v_rel, ttc=None) -> bool: + """True when closing rate is high enough for the firm 0.55 path. + + Short TTC at a mild `v_rel` is arriving at Follow Distance, not dumping. + `ttc` is for callers; it does not promote a 5–10 mph close to 0.55. + Planner still requires consecutive samples via lead_approach_rapid_gate. + """ + _ = ttc + return float(v_rel) >= LEAD_APPROACH_RAPID_DV_MS diff --git a/selfdrive/controls/lib/lead_leaving.py b/selfdrive/controls/lib/lead_leaving.py new file mode 100644 index 00000000000000..38032ded91ef3e --- /dev/null +++ b/selfdrive/controls/lib/lead_leaving.py @@ -0,0 +1,265 @@ +"""Lead leaving our path: a continuous weight on the lead's braking. + +A lead that slows and turns off (driveway, side street, turn lane) keeps +the planner braking until radard finally drops it, ~2 m off the path. +Justin's drives: Sep 23 21:05 (-3.5 for ~2.5 s while the lead was already +drifting out), Sep 25 11:49 (-2.6...-2.8 while the lead was braking into a +left turn); both overridden with the gas. + +The weight is how sure we are that the lead will be out of our way by the +time we get there. It is built from: + + * the lead's lateral offset from the model's predicted path (not raw + yRel, so a lead in a bend stays on-path), + * its filtered lateral velocity away from that path, and + * the trend of the in-path confidence (modelProb falling). + +Safety bound, in the math rather than a rule: the offset is projected +forward to our time of arrival (the gap closed at today's speed while the +lead keeps braking at its aLead until it stops; it only moves sideways +while it rolls), and the weight only rises once that projected offset +clears our half-width + the lead's half-width + a margin. +A lead that stalls partway (lateral velocity ~0) projects to where it is, +which does not clear, so it keeps full weight. A lead whose center is still +inside our vehicle's half of the lane gets full weight regardless of its +lateral velocity (overlap gate), which also keeps ordinary in-lane drift +from ever releasing anything. + +The weight only moves a lead-induced *brake* toward the lead-free command +(hold speed, or the MAX / map / curve decel if that is deeper). It never +adds +a, so MAX stays a hard ceiling and the EV settle is untouched. +Radard's lead selection is shared by the legacy and unified paths, so the +planner applies this one weight to both. +""" +from __future__ import annotations + +import math + +# Geometry (m). Model S body is 1.96 m without mirrors; a typical lead ~1.9 m. +EGO_HALF_WIDTH_M = 0.98 +LEAD_HALF_WIDTH_M = 0.90 +CLEAR_MARGIN_M = 0.30 +CLEAR_MARGIN_PER_MS = 0.01 # +0.2 m at 20 m/s +CLEAR_BAND_M = 0.5 # smooth rise once the projection clears + +# Overlap gate: lead center still within our half of the lane -> no release. +# 0.9 m is where a 1.9 m car hugging a 3.7 m lane's line sits; it has to be +# crossing its lane line before any release begins. +OVERLAP_Y0_M = 0.9 +OVERLAP_BAND_M = 0.5 + +# Projection. +T_ARRIVE_MAX_S = 2.5 +PROJ_MAX_M = 2.5 +VY_DEADBAND_MS = 0.15 # radar / path noise must not project +TRUST_BASE = 0.7 # share of vy*t used with a steady modelProb +PROB_DROP_FULL_1_S = 0.5 # modelProb falling this fast -> full trust + +# Estimator. +TAU_Y_S = 0.15 +TAU_VY_S = 0.3 +TAU_VY_SLOW_S = 0.7 # both must agree the lead is moving out +VY_RAW_MAX_MS = 2.5 # a car turning off at 15 m/s moves out ~1-3 m/s +TAU_P_S = 0.3 +TAU_DP_S = 0.5 +WARMUP_S = 0.25 +WARMUP_BAND_S = 0.4 +RISE_1_S = 1.5 # 0 -> 1 in ~0.7 s +FALL_1_S = 8.0 # braking comes back within ~0.1 s +LEAD_TWO_CLEAR_M = 2.0 +LEAD_TWO_BAND_M = 0.6 + + +def _smooth01(x: float) -> float: + if x <= 0.0: + return 0.0 + if x >= 1.0: + return 1.0 + return x * x * (3.0 - 2.0 * x) + + +def _filt(prev: float | None, sample: float, dt: float, tau: float) -> float: + if prev is None: + return float(sample) + a = dt / (tau + dt) + return float(prev) + a * (float(sample) - float(prev)) + + +def clearance_needed_m(v_ego: float) -> float: + """Lateral center-to-path offset at which the lead's body clears ours.""" + return EGO_HALF_WIDTH_M + LEAD_HALF_WIDTH_M + CLEAR_MARGIN_M + CLEAR_MARGIN_PER_MS * max(0.0, float(v_ego)) + + +def time_to_arrive_s(gap: float, v_ego: float, v_lead: float | None = None, + a_lead: float = 0.0) -> float: + """When we pull alongside the lead at today's speed. + + The lead keeps moving forward, braking at a_lead until it stops (lead + +a is ignored: arriving earlier is the conservative side). Without a lead + speed this is gap / v_ego, the lead treated as stopped. Capped. + """ + g = max(0.0, float(gap)) + v_e = max(1.0, float(v_ego)) + if v_lead is None or not math.isfinite(float(v_lead)): + return min(T_ARRIVE_MAX_S, g / v_e) + v_l = max(0.0, float(v_lead)) + brake = max(0.0, -float(a_lead)) if math.isfinite(float(a_lead)) else 0.0 + big_a = 0.5 * brake + b = v_e - v_l + disc = b * b + 4.0 * big_a * g + den = b + math.sqrt(max(0.0, disc)) + t = T_ARRIVE_MAX_S if den <= 1e-6 else 2.0 * g / den + if brake > 1e-6 and t > v_l / brake: + # Lead stops first: we reach its stopping point. + t = (g + v_l * v_l / (2.0 * brake)) / v_e + return min(T_ARRIVE_MAX_S, max(g / v_e, t)) + + +def lateral_time_s(t_arrive: float, v_lead: float | None = None, a_lead: float = 0.0) -> float: + """A car only moves sideways while it rolls: a lead braking to a stop + mid-turn stops moving out when it stops.""" + t = max(0.0, float(t_arrive)) + if v_lead is None or not math.isfinite(float(v_lead)) or not math.isfinite(float(a_lead)): + return t + brake = max(0.0, -float(a_lead)) + if brake <= 1e-6: + return t + return min(t, max(0.0, float(v_lead)) / brake) + + +def projected_offset_m(abs_y: float, vy_away: float, gap: float, v_ego: float, + prob_rate: float = 0.0, v_lead: float | None = None, + a_lead: float = 0.0) -> float: + trust = TRUST_BASE + (1.0 - TRUST_BASE) * _smooth01(-float(prob_rate) / PROB_DROP_FULL_1_S) + vy_eff = max(0.0, float(vy_away) - VY_DEADBAND_MS) + t_lat = lateral_time_s(time_to_arrive_s(gap, v_ego, v_lead, a_lead), v_lead, a_lead) + travel = min(PROJ_MAX_M, vy_eff * t_lat * trust) + return max(0.0, float(abs_y)) + travel + + +def leave_weight(abs_y: float, vy_away: float, gap: float, v_ego: float, + prob_rate: float = 0.0, v_lead: float | None = None, + a_lead: float = 0.0) -> float: + """0 = full lead weight, 1 = lead will be clear of us when we get there. + + Continuous in every input. Clearance bound x overlap gate. + """ + if not (math.isfinite(abs_y) and math.isfinite(vy_away) and math.isfinite(gap) and math.isfinite(v_ego)): + return 0.0 + if not math.isfinite(prob_rate): + prob_rate = 0.0 + if v_lead is not None and not math.isfinite(float(v_lead)): + v_lead = None + if not math.isfinite(float(a_lead)): + a_lead = 0.0 + y = abs(float(abs_y)) + y_proj = projected_offset_m(y, vy_away, gap, v_ego, prob_rate, v_lead, a_lead) + clear_w = _smooth01((y_proj - clearance_needed_m(v_ego)) / CLEAR_BAND_M) + overlap_w = _smooth01((y - OVERLAP_Y0_M) / OVERLAP_BAND_M) + return clear_w * overlap_w + + +class LeadLeavingEstimator: + """Filters offset / lateral velocity / confidence trend per lead track.""" + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self._lead_id = None + self._y = None + self._vy = 0.0 + self._vy_fast = 0.0 + self._vy_slow = 0.0 + self._p = None + self._dp = 0.0 + self._age = 0.0 + self._gap = 0.0 + self._v_lead = None + self._a_lead = 0.0 + self._hold_age = 0.0 + self.weight = 0.0 + self.target = 0.0 + self.vy_away = 0.0 + self.abs_y = 0.0 + + def update(self, *, dt: float, present: bool, held: bool = False, lead_id=None, + path_lat: float | None = None, gap: float = 0.0, v_ego: float = 0.0, + v_lead: float | None = None, a_lead: float = 0.0, + model_prob: float | None = None, lead_two_path_lat: float | None = None, + suppress: bool = False) -> float: + frame_dt = 0.05 if dt is None or float(dt) <= 1e-6 else float(dt) + if suppress: + # FCW / MPC crash / should-stop / force-decel: full braking now. + self.weight = 0.0 + self.target = 0.0 + return 0.0 + if not present: + self.reset() + return 0.0 + if held: + # Short status drop (the planner's lead hold). Radard usually drops a + # turning lead at its ~2 m gate: dead-reckon the last offset / speed + # so a lead that was moving out keeps being released, and one that + # had stalled keeps full weight. + if self._y is None: + return self.weight + self._hold_age += frame_dt + rolling = 1.0 if self._v_lead is None else float(self._v_lead > 0.5) + vy_eff = max(0.0, self._vy) * rolling + self._y += (1.0 if self._y >= 0.0 else -1.0) * vy_eff * frame_dt + v_l = self._v_lead + if v_l is not None: + self._v_lead = max(0.0, v_l + min(0.0, self._a_lead) * frame_dt) + closing = float(v_ego) - (0.0 if v_l is None else v_l) + self._gap = max(0.0, self._gap - closing * frame_dt) + self.abs_y = abs(self._y) + target = leave_weight(self.abs_y, self._vy * rolling, self._gap, v_ego, self._dp, self._v_lead, self._a_lead) + return self._slew(target, frame_dt) + if lead_id != self._lead_id: + self.reset() + self._lead_id = lead_id + self._hold_age = 0.0 + self._gap = max(0.0, float(gap)) + self._v_lead = None if v_lead is None or not math.isfinite(float(v_lead)) else float(v_lead) + self._a_lead = float(a_lead) if math.isfinite(float(a_lead)) else 0.0 + + if path_lat is None or not math.isfinite(float(path_lat)): + target = 0.0 + self._y = None + else: + y_raw = float(path_lat) + y_prev = self._y + self._y = _filt(self._y, y_raw, frame_dt, TAU_Y_S) + vy_signed = 0.0 if y_prev is None else (self._y - y_prev) / frame_dt + side = 1.0 if self._y >= 0.0 else -1.0 + vy_raw = min(VY_RAW_MAX_MS, max(-VY_RAW_MAX_MS, vy_signed * side)) + self._vy_fast = _filt(self._vy_fast, vy_raw, frame_dt, TAU_VY_S) + self._vy_slow = _filt(self._vy_slow, vy_raw, frame_dt, TAU_VY_SLOW_S) + # Association / path noise swings the fast estimate; a real turn-off + # moves both. A stall drops the fast one, so braking returns quickly. + self._vy = min(self._vy_fast, self._vy_slow) + if model_prob is not None and math.isfinite(float(model_prob)): + p_prev = self._p + self._p = _filt(self._p, float(model_prob), frame_dt, TAU_P_S) + dp = 0.0 if p_prev is None else (self._p - p_prev) / frame_dt + self._dp = _filt(self._dp, dp, frame_dt, TAU_DP_S) + self._age += frame_dt + warm = _smooth01((self._age - WARMUP_S) / WARMUP_BAND_S) + self.abs_y = abs(self._y) + self.vy_away = self._vy + target = warm * leave_weight(self.abs_y, self._vy, self._gap, v_ego, self._dp, self._v_lead, self._a_lead) + + # A second lead on our path behind the one turning off keeps full braking. + if lead_two_path_lat is not None and math.isfinite(float(lead_two_path_lat)): + target *= _smooth01((abs(float(lead_two_path_lat)) - (LEAD_TWO_CLEAR_M - LEAD_TWO_BAND_M)) / LEAD_TWO_BAND_M) + + return self._slew(target, frame_dt) + + def _slew(self, target: float, frame_dt: float) -> float: + self.target = target + if target > self.weight: + self.weight = min(target, self.weight + RISE_1_S * frame_dt) + else: + self.weight = max(target, self.weight - FALL_1_S * frame_dt) + return self.weight diff --git a/selfdrive/controls/lib/longcontrol.py b/selfdrive/controls/lib/longcontrol.py index e18ee0c279024b..a38660c816eb1c 100644 --- a/selfdrive/controls/lib/longcontrol.py +++ b/selfdrive/controls/lib/longcontrol.py @@ -1,13 +1,30 @@ +import numpy as np from cereal import car -from openpilot.common.numpy_fast import clip from openpilot.common.realtime import DT_CTRL from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N +from openpilot.selfdrive.controls.lib.firm_brake_latch import ( + FirmBrakeLatch, + apply_firm_brake_latch, + lead_midgap_firm_close_hit, +) +from openpilot.selfdrive.controls.lib.lead_approach import ( + LeadResidualWindow, + guard_follow_actuator_regen, +) from openpilot.common.pid import PIDController from openpilot.selfdrive.modeld.constants import ModelConstants CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N] LongCtrlState = car.CarControl.Actuators.LongControlState +PREAP_FINGERPRINT = "TESLA_MODEL_S_PREAP" + + +def _is_tesla_preap_long(CP) -> bool: + return (getattr(CP, "brand", None) == "tesla" + and getattr(CP, "carFingerprint", None) == PREAP_FINGERPRINT + and bool(getattr(CP, "openpilotLongitudinalControl", False)) + and not bool(getattr(CP, "pcmCruise", True))) def long_control_state_trans(CP, active, long_control_state, v_ego, @@ -50,13 +67,22 @@ def __init__(self, CP): self.long_control_state = LongCtrlState.off self.pid = PIDController((CP.longitudinalTuning.kpBP, CP.longitudinalTuning.kpV), (CP.longitudinalTuning.kiBP, CP.longitudinalTuning.kiV), - k_f=CP.longitudinalTuning.kf, rate=1 / DT_CTRL) + rate=1 / DT_CTRL) self.last_output_accel = 0.0 + # ~0.5 s of lead v_rel and measured aEgo. One 100 Hz radar step + # must not read as a #222 residual brake. + self._lead_residual = LeadResidualWindow() + # Keeps a firm mid-gap brake from being re-clipped to MILD mid-ease. + self._firm_latch = FirmBrakeLatch() def reset(self): self.pid.reset() + self._lead_residual.reset() + self._firm_latch.reset() - def update(self, active, CS, a_target, should_stop, accel_limits): + def update(self, active, CS, a_target, should_stop, accel_limits, + lead_v_rel=None, lead_d_rel=None, lead_slack=None, lead_fcw=False, + lead_v_ego=None, lead_v_cruise=None, lead_a_lead=None): """Update longitudinal control. This updates the state machine and runs a PID loop""" self.pid.neg_limit = accel_limits[0] self.pid.pos_limit = accel_limits[1] @@ -84,5 +110,44 @@ def update(self, active, CS, a_target, should_stop, accel_limits): output_accel = self.pid.update(error, speed=CS.vEgo, feedforward=a_target) - self.last_output_accel = clip(output_accel, accel_limits[0], accel_limits[1]) + self.last_output_accel = np.clip(output_accel, accel_limits[0], accel_limits[1]) + # Pre-AP follow comfort: coast / MILD must not dump firm regen. + # A non-braking slow close follows the planner (the old mid-gap + # −0.22 / −0.45 cap is retired for that case). Stopping / starting / + # off keep stock authority. Firm leads, #222 residuals, FCW, and a + # near bumper still reach the plant. + if (self.long_control_state == LongCtrlState.pid + and _is_tesla_preap_long(self.CP)): + if lead_v_rel is None: + self._lead_residual.reset() + prev_v_rel, residual_dt, residual_a = ( + None, DT_CTRL, float(getattr(CS, "aEgo", 0.0)), + ) + else: + prev_v_rel, residual_dt, residual_a = self._lead_residual.update( + float(lead_v_rel), float(getattr(CS, "aEgo", 0.0)), DT_CTRL, + ) + hold_pass = self._firm_latch.update( + a_target, lead_v_rel, + lead_v_rel is not None and lead_midgap_firm_close_hit( + lead_v_rel, lead_d_rel, lead_slack, a_lead=lead_a_lead, + prev_v_rel=prev_v_rel, a_ego=residual_a, dt=residual_dt, + should_stop=bool(should_stop), + ), + DT_CTRL, + ) + raw_accel = self.last_output_accel + guarded_accel = float(guard_follow_actuator_regen( + raw_accel, a_target, + v_rel=lead_v_rel, d_rel=lead_d_rel, slack=lead_slack, fcw=lead_fcw, + v_ego=lead_v_ego, v_cruise=lead_v_cruise, a_lead=lead_a_lead, + prev_v_rel=prev_v_rel, a_ego=residual_a, + dt=residual_dt, should_stop=bool(should_stop), + )) + # F1: a firm mid-gap brake is not re-clipped to MILD while the plan + # stays firm. Never softer than the guard's own output. + self.last_output_accel = float(apply_firm_brake_latch( + guarded_accel, raw_accel, a_target, hold_pass, + v_rel=lead_v_rel, slack=lead_slack, a_lead=lead_a_lead, + )) return self.last_output_accel diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript b/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript index 2a155717c01470..a3218e9f34dcf6 100644 --- a/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript +++ b/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript @@ -1,4 +1,4 @@ -Import('env', 'envCython', 'arch', 'msgq_python', 'common_python', 'opendbc_python', 'pandad_python', 'np_version') +Import('env', 'envCython', 'arch', 'msgq_python', 'common_python', 'np_version', 'acados') gen = "c_generated_code" @@ -51,22 +51,29 @@ generated_files = [ f'{gen}/long_cost/long_cost.h', ] + build_files -acados_dir = '#third_party/acados' -acados_templates_dir = '#third_party/acados/acados_template/c_templates_tera' +acados_include_dir = Dir(acados.INCLUDE_DIR) +acados_template_dir = Dir(acados.TEMPLATE_DIR) source_list = ['long_mpc.py', '#selfdrive/modeld/constants.py', - f'{acados_dir}/include/acados_c/ocp_nlp_interface.h', - f'{acados_templates_dir}/acados_solver.in.c', + acados_include_dir.File('acados_c/ocp_nlp_interface.h'), + acados_template_dir.File('c_templates_tera/acados_solver.in.c'), ] lenv = env.Clone() +copied_acados_libs = [] +if arch != "Darwin": + for lib in ["libacados.so", "libblasfeo.so", "libhpipm.so", "libqpOASES_e.so.3.1"]: + copied_acados_libs += lenv.Command(f"{gen}/{lib}", Dir(acados.LIB_DIR).File(lib), [Mkdir(Dir(gen)), Copy("$TARGET", "$SOURCE")]) + lenv["RPATH"] += [lenv.Literal('\\$$ORIGIN')] +else: + acados_rel_path = Dir(gen).rel_path(Dir(acados.LIB_DIR)) + lenv["RPATH"] += [lenv.Literal(f'\\$$ORIGIN/{acados_rel_path}')] lenv.Clean(generated_files, Dir(gen)) - generated_long = lenv.Command(generated_files, source_list, f"cd {Dir('.').abspath} && python3 long_mpc.py") -lenv.Depends(generated_long, [msgq_python, common_python, opendbc_python, pandad_python]) +lenv.Depends(generated_long, [msgq_python, common_python]) lenv["CFLAGS"].append("-DACADOS_WITH_QPOASES") lenv["CXXFLAGS"].append("-DACADOS_WITH_QPOASES") @@ -75,18 +82,20 @@ if arch != "Darwin": lenv["LINKFLAGS"].append("-Wl,--disable-new-dtags") else: lenv["LINKFLAGS"].append("-Wl,-install_name,@loader_path/libacados_ocp_solver_long.dylib") + lenv["LINKFLAGS"].append(f"-Wl,-rpath,@loader_path/{acados_rel_path}") lib_solver = lenv.SharedLibrary(f"{gen}/acados_ocp_solver_long", build_files, LIBS=['m', 'acados', 'hpipm', 'blasfeo', 'qpOASES_e']) # generate cython stuff -acados_ocp_solver_pyx = File("#third_party/acados/acados_template/acados_ocp_solver_pyx.pyx") -acados_ocp_solver_common = File("#third_party/acados/acados_template/acados_solver_common.pxd") +acados_ocp_solver_pyx = acados_template_dir.File('acados_ocp_solver_pyx.pyx') +acados_ocp_solver_common = acados_template_dir.File('acados_solver_common.pxd') libacados_ocp_solver_pxd = File(f'{gen}/acados_solver.pxd') libacados_ocp_solver_c = File(f'{gen}/acados_ocp_solver_pyx.c') lenv2 = envCython.Clone() -lenv2["LINKFLAGS"] += [lib_solver[0].get_labspath()] +lenv2["LIBPATH"] += [lib_solver[0].dir.abspath] +lenv2["RPATH"] += [lenv2.Literal('\\$$ORIGIN')] lenv2.Command(libacados_ocp_solver_c, [acados_ocp_solver_pyx, acados_ocp_solver_common, libacados_ocp_solver_pxd], f'cython' + \ @@ -94,6 +103,7 @@ lenv2.Command(libacados_ocp_solver_c, f' -I {libacados_ocp_solver_pxd.get_dir().get_labspath()}' + \ f' -I {acados_ocp_solver_common.get_dir().get_labspath()}' + \ f' {acados_ocp_solver_pyx.get_labspath()}') -lib_cython = lenv2.Program(f'{gen}/acados_ocp_solver_pyx.so', [libacados_ocp_solver_c]) +lib_cython = lenv2.Program(f'{gen}/acados_ocp_solver_pyx.so', [libacados_ocp_solver_c], LIBS=['acados_ocp_solver_long']) lenv2.Depends(lib_cython, lib_solver) +lenv2.Depends(lib_cython, copied_acados_libs) lenv2.Depends(libacados_ocp_solver_c, np_version) diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py b/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py index fa6d5542bdf71b..3221b48488c062 100755 --- a/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py +++ b/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py @@ -3,8 +3,7 @@ import time import numpy as np from cereal import log -from opendbc.car.interfaces import ACCEL_MIN -from openpilot.common.numpy_fast import clip +from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX from openpilot.common.realtime import DT_MDL from openpilot.common.swaglog import cloudlog # WARNING: imports outside of constants will not trigger a rebuild @@ -12,7 +11,7 @@ from openpilot.selfdrive.controls.radard import _LEAD_ACCEL_TAU if __name__ == '__main__': # generating code - from openpilot.third_party.acados.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver + from acados.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver else: from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython @@ -23,7 +22,8 @@ EXPORT_DIR = os.path.join(LONG_MPC_DIR, "c_generated_code") JSON_FILE = os.path.join(LONG_MPC_DIR, "acados_ocp_long.json") -SOURCES = ['lead0', 'lead1', 'cruise', 'e2e'] +LongitudinalPlanSource = log.LongitudinalPlan.LongitudinalPlanSource +MPC_SOURCES = (LongitudinalPlanSource.lead0, LongitudinalPlanSource.lead1, LongitudinalPlanSource.cruise) X_DIM = 3 U_DIM = 1 @@ -36,7 +36,7 @@ X_EGO_COST = 0. V_EGO_COST = 0. A_EGO_COST = 0. -J_EGO_COST = 5.0 +J_EGO_COST = 5. A_CHANGE_COST = 200. DANGER_ZONE_COST = 100. CRASH_DISTANCE = .25 @@ -44,7 +44,6 @@ LIMIT_COST = 1e6 ACADOS_SOLVER_TYPE = 'SQP_RTI' - # Fewer timestamps don't hurt performance and lead to # much better convergence of the MPC with low iterations N = 12 @@ -56,6 +55,10 @@ T_DIFFS = np.diff(T_IDXS, prepend=[0.]) COMFORT_BRAKE = 2.5 STOP_DISTANCE = 6.0 +CRUISE_MIN_ACCEL = -1.2 +CRUISE_MAX_ACCEL = 1.6 +MIN_X_LEAD_FACTOR = 0.5 +NAP_T_FOLLOW = (0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9) def get_jerk_factor(personality=log.LongitudinalPersonality.standard): if personality==log.LongitudinalPersonality.relaxed: @@ -68,7 +71,10 @@ def get_jerk_factor(personality=log.LongitudinalPersonality.standard): raise NotImplementedError("Longitudinal personality not supported") -def get_T_FOLLOW(personality=log.LongitudinalPersonality.standard): +def get_T_FOLLOW(personality=log.LongitudinalPersonality.standard, nap_follow_dist=None): + if nap_follow_dist in range(1, len(NAP_T_FOLLOW) + 1): + return NAP_T_FOLLOW[nap_follow_dist - 1] + if personality==log.LongitudinalPersonality.relaxed: return 1.75 elif personality==log.LongitudinalPersonality.standard: @@ -84,20 +90,12 @@ def get_stopped_equivalence_factor(v_lead): def get_safe_obstacle_distance(v_ego, t_follow): return (v_ego**2) / (2 * COMFORT_BRAKE) + t_follow * v_ego + STOP_DISTANCE -def desired_follow_distance(v_ego, v_lead, t_follow=None): - if t_follow is None: - t_follow = get_T_FOLLOW() - return get_safe_obstacle_distance(v_ego, t_follow) - get_stopped_equivalence_factor(v_lead) - - def gen_long_model(): model = AcadosModel() model.name = MODEL_NAME - # set up states & controls - x_ego = SX.sym('x_ego') - v_ego = SX.sym('v_ego') - a_ego = SX.sym('a_ego') + # states + x_ego, v_ego, a_ego = SX.sym('x_ego'), SX.sym('v_ego'), SX.sym('a_ego') model.x = vertcat(x_ego, v_ego, a_ego) # controls @@ -114,10 +112,10 @@ def gen_long_model(): a_min = SX.sym('a_min') a_max = SX.sym('a_max') x_obstacle = SX.sym('x_obstacle') - prev_a = SX.sym('prev_a') + a_prev = SX.sym('a_prev') lead_t_follow = SX.sym('lead_t_follow') lead_danger_factor = SX.sym('lead_danger_factor') - model.p = vertcat(a_min, a_max, x_obstacle, prev_a, lead_t_follow, lead_danger_factor) + model.p = vertcat(a_min, a_max, x_obstacle, a_prev, lead_t_follow, lead_danger_factor) # dynamics model f_expl = vertcat(v_ego, a_ego, j_ego) @@ -125,7 +123,6 @@ def gen_long_model(): model.f_expl_expr = f_expl return model - def gen_long_ocp(): ocp = AcadosOcp() ocp.model = gen_long_model() @@ -150,7 +147,7 @@ def gen_long_ocp(): a_min, a_max = ocp.model.p[0], ocp.model.p[1] x_obstacle = ocp.model.p[2] - prev_a = ocp.model.p[3] + a_prev = ocp.model.p[3] lead_t_follow = ocp.model.p[4] lead_danger_factor = ocp.model.p[5] @@ -167,7 +164,7 @@ def gen_long_ocp(): x_ego, v_ego, a_ego, - a_ego - prev_a, + a_ego - a_prev, j_ego] ocp.model.cost_y_expr = vertcat(*costs) ocp.model.cost_y_expr_e = vertcat(*costs[:-1]) @@ -221,30 +218,31 @@ def gen_long_ocp(): class LongitudinalMpc: - def __init__(self, mode='acc', dt=DT_MDL): - self.mode = mode + def __init__(self, dt=DT_MDL): self.dt = dt self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) self.reset() - self.source = SOURCES[2] + self.source = LongitudinalPlanSource.cruise def reset(self): - # self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) self.solver.reset() - # self.solver.options_set('print_level', 2) + + self.x_sol = np.zeros((N+1, X_DIM)) + self.u_sol = np.zeros((N, 1)) self.v_solution = np.zeros(N+1) self.a_solution = np.zeros(N+1) - self.prev_a = np.array(self.a_solution) self.j_solution = np.zeros(N) + self.a_prev = np.array(self.a_solution) self.yref = np.zeros((N+1, COST_DIM)) + for i in range(N): self.solver.cost_set(i, "yref", self.yref[i]) self.solver.cost_set(N, "yref", self.yref[N][:COST_E_DIM]) - self.x_sol = np.zeros((N+1, X_DIM)) - self.u_sol = np.zeros((N,1)) + self.params = np.zeros((N+1, PARAM_DIM)) for i in range(N+1): self.solver.set(i, 'x', np.zeros(X_DIM)) + self.last_cloudlog_t = 0 self.status = False self.crash_cnt = 0.0 @@ -275,16 +273,9 @@ def set_cost_weights(self, cost_weights, constraint_cost_weights): def set_weights(self, prev_accel_constraint=True, personality=log.LongitudinalPersonality.standard): jerk_factor = get_jerk_factor(personality) - if self.mode == 'acc': - a_change_cost = A_CHANGE_COST if prev_accel_constraint else 0 - cost_weights = [X_EGO_OBSTACLE_COST, X_EGO_COST, V_EGO_COST, A_EGO_COST, jerk_factor * a_change_cost, jerk_factor * J_EGO_COST] - constraint_cost_weights = [LIMIT_COST, LIMIT_COST, LIMIT_COST, DANGER_ZONE_COST] - elif self.mode == 'blended': - a_change_cost = 40.0 if prev_accel_constraint else 0 - cost_weights = [0., 0.1, 0.2, 5.0, a_change_cost, 1.0] - constraint_cost_weights = [LIMIT_COST, LIMIT_COST, LIMIT_COST, 50.0] - else: - raise NotImplementedError(f'Planner mode {self.mode} not recognized in planner cost set') + a_change_cost = A_CHANGE_COST if prev_accel_constraint else 0 + cost_weights = [X_EGO_OBSTACLE_COST, X_EGO_COST, V_EGO_COST, A_EGO_COST, jerk_factor * a_change_cost, jerk_factor * J_EGO_COST] + constraint_cost_weights = [LIMIT_COST, LIMIT_COST, LIMIT_COST, DANGER_ZONE_COST] self.set_cost_weights(cost_weights, constraint_cost_weights) def set_cur_state(self, v, a): @@ -319,21 +310,14 @@ def process_lead(self, lead): # MPC will not converge if immediate crash is expected # Clip lead distance to what is still possible to brake for - min_x_lead = ((v_ego + v_lead)/2) * (v_ego - v_lead) / (-ACCEL_MIN * 2) - x_lead = clip(x_lead, min_x_lead, 1e8) - v_lead = clip(v_lead, 0.0, 1e8) - a_lead = clip(a_lead, -10., 5.) + min_x_lead = MIN_X_LEAD_FACTOR * (v_ego + v_lead) * (v_ego - v_lead) / (-ACCEL_MIN * 2) + x_lead = np.clip(x_lead, min_x_lead, 1e8) + v_lead = np.clip(v_lead, 0.0, 1e8) + a_lead = np.clip(a_lead, -10., 5.) lead_xv = self.extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau) return lead_xv - def set_accel_limits(self, min_a, max_a): - # TODO this sets a max accel limit, but the minimum limit is only for cruise decel - # needs refactor - self.cruise_min_a = min_a - self.max_a = max_a - - def update(self, radarstate, v_cruise, x, v, a, j, personality=log.LongitudinalPersonality.standard): - t_follow = get_T_FOLLOW(personality) + def update(self, radarstate, v_cruise, t_follow): v_ego = self.x0[1] self.status = radarstate.leadOne.status or radarstate.leadTwo.status @@ -346,55 +330,29 @@ def update(self, radarstate, v_cruise, x, v, a, j, personality=log.LongitudinalP lead_0_obstacle = lead_xv_0[:,0] + get_stopped_equivalence_factor(lead_xv_0[:,1]) lead_1_obstacle = lead_xv_1[:,0] + get_stopped_equivalence_factor(lead_xv_1[:,1]) - self.params[:,0] = ACCEL_MIN - self.params[:,1] = self.max_a - - # Update in ACC mode or ACC/e2e blend - if self.mode == 'acc': - self.params[:,5] = LEAD_DANGER_FACTOR - - # Fake an obstacle for cruise, this ensures smooth acceleration to set speed - # when the leads are no factor. - v_lower = v_ego + (T_IDXS * self.cruise_min_a * 1.05) - v_upper = v_ego + (T_IDXS * self.max_a * 1.05) - v_cruise_clipped = np.clip(v_cruise * np.ones(N+1), - v_lower, - v_upper) - cruise_obstacle = np.cumsum(T_DIFFS * v_cruise_clipped) + get_safe_obstacle_distance(v_cruise_clipped, t_follow) - x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle]) - self.source = SOURCES[np.argmin(x_obstacles[0])] - - # These are not used in ACC mode - x[:], v[:], a[:], j[:] = 0.0, 0.0, 0.0, 0.0 - - elif self.mode == 'blended': - self.params[:,5] = 1.0 - - x_obstacles = np.column_stack([lead_0_obstacle, - lead_1_obstacle]) - cruise_target = T_IDXS * np.clip(v_cruise, v_ego - 2.0, 1e3) + x[0] - xforward = ((v[1:] + v[:-1]) / 2) * (T_IDXS[1:] - T_IDXS[:-1]) - x = np.cumsum(np.insert(xforward, 0, x[0])) + # Fake an obstacle for cruise, this ensures smooth acceleration to set speed + # when the leads are no factor. + v_lower = v_ego + (T_IDXS * CRUISE_MIN_ACCEL * 1.05) + # TODO does this make sense when max_a is negative? + v_upper = v_ego + (T_IDXS * CRUISE_MAX_ACCEL * 1.05) + v_cruise_clipped = np.clip(v_cruise * np.ones(N+1), v_lower, v_upper) + cruise_obstacle = np.cumsum(T_DIFFS * v_cruise_clipped) + get_safe_obstacle_distance(v_cruise_clipped, t_follow) - x_and_cruise = np.column_stack([x, cruise_target]) - x = np.min(x_and_cruise, axis=1) + # Lead columns always participate. Map speed only changes v_cruise → cruise_obstacle. + x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle]) + self.source = MPC_SOURCES[np.argmin(x_obstacles[0])] - self.source = 'e2e' if x_and_cruise[1,0] < x_and_cruise[1,1] else 'cruise' - - else: - raise NotImplementedError(f'Planner mode {self.mode} not recognized in planner update') - - self.yref[:,1] = x - self.yref[:,2] = v - self.yref[:,3] = a - self.yref[:,5] = j + self.yref[:,:] = 0.0 for i in range(N): self.solver.set(i, "yref", self.yref[i]) self.solver.set(N, "yref", self.yref[N][:COST_E_DIM]) + self.params[:,0] = ACCEL_MIN + self.params[:,1] = ACCEL_MAX self.params[:,2] = np.min(x_obstacles, axis=1) - self.params[:,3] = np.copy(self.prev_a) + self.params[:,3] = np.copy(self.a_prev) self.params[:,4] = t_follow + self.params[:,5] = LEAD_DANGER_FACTOR self.run() if (np.any(lead_xv_0[FCW_IDXS,0] - self.x_sol[FCW_IDXS,0] < CRASH_DISTANCE) and @@ -403,18 +361,7 @@ def update(self, radarstate, v_cruise, x, v, a, j, personality=log.LongitudinalP else: self.crash_cnt = 0 - # Check if it got within lead comfort range - # TODO This should be done cleaner - if self.mode == 'blended': - if any((lead_0_obstacle - get_safe_obstacle_distance(self.x_sol[:,1], t_follow))- self.x_sol[:,0] < 0.0): - self.source = 'lead0' - if any((lead_1_obstacle - get_safe_obstacle_distance(self.x_sol[:,1], t_follow))- self.x_sol[:,0] < 0.0) and \ - (lead_1_obstacle[0] - lead_0_obstacle[0]): - self.source = 'lead1' - def run(self): - # t0 = time.monotonic() - # reset = 0 for i in range(N+1): self.solver.set(i, 'p', self.params[i]) self.solver.constraints_set(0, "lbx", self.x0) @@ -426,13 +373,6 @@ def run(self): self.time_linearization = float(self.solver.get_stats('time_lin')[0]) self.time_integrator = float(self.solver.get_stats('time_sim')[0]) - # qp_iter = self.solver.get_stats('statistics')[-1][-1] # SQP_RTI specific - # print(f"long_mpc timings: tot {self.solve_time:.2e}, qp {self.time_qp_solution:.2e}, lin {self.time_linearization:.2e}, \ - # integrator {self.time_integrator:.2e}, qp_iter {qp_iter}") - # res = self.solver.get_residuals() - # print(f"long_mpc residuals: {res[0]:.2e}, {res[1]:.2e}, {res[2]:.2e}, {res[3]:.2e}") - # self.solver.print_statistics() - for i in range(N+1): self.x_sol[i] = self.solver.get(i, 'x') for i in range(N): @@ -442,7 +382,7 @@ def run(self): self.a_solution = self.x_sol[:,2] self.j_solution = self.u_sol[:,0] - self.prev_a = np.interp(T_IDXS + self.dt, T_IDXS, self.a_solution) + self.a_prev = np.interp(T_IDXS + self.dt, T_IDXS, self.a_solution) t = time.monotonic() if self.solution_status != 0: @@ -450,12 +390,8 @@ def run(self): self.last_cloudlog_t = t cloudlog.warning(f"Long mpc reset, solution_status: {self.solution_status}") self.reset() - # reset = 1 - # print(f"long_mpc timings: total internal {self.solve_time:.2e}, external: {(time.monotonic() - t0):.2e} qp {self.time_qp_solution:.2e}, \ - # lin {self.time_linearization:.2e} qp_iter {qp_iter}, reset {reset}") if __name__ == "__main__": ocp = gen_long_ocp() AcadosOcpSolver.generate(ocp, json_file=JSON_FILE) - # AcadosOcpSolver.build(ocp.code_export_directory, with_cython=True) diff --git a/selfdrive/controls/lib/longitudinal_planner.py b/selfdrive/controls/lib/longitudinal_planner.py old mode 100755 new mode 100644 index 103d3f70470752..8839d99e007434 --- a/selfdrive/controls/lib/longitudinal_planner.py +++ b/selfdrive/controls/lib/longitudinal_planner.py @@ -1,91 +1,262 @@ #!/usr/bin/env python3 import math +import time + import numpy as np -from openpilot.common.numpy_fast import clip, interp import cereal.messaging as messaging from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX -from openpilot.common.conversions import Conversions as CV +from openpilot.common.constants import CV from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.realtime import DT_MDL from openpilot.selfdrive.modeld.constants import ModelConstants from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState -from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import LongitudinalMpc +from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import ( + LongitudinalMpc, + LongitudinalPlanSource, + get_safe_obstacle_distance, + get_stopped_equivalence_factor, + get_T_FOLLOW, +) +from openpilot.selfdrive.controls.lib.curve_max_hold import curve_speed_for_curvature +from openpilot.selfdrive.controls.lib.curve_preview import ( + PREVIEW_FREE_A_MS2, + CurvePreview, + curve_preview_accel, + path_curvature, + path_lat_accel_ahead, + turn_accel_limit, +) +from openpilot.selfdrive.controls.lib.curve_follow import ( + LOG_PERIOD_CYCLES, + LOG_QUIET_PERIOD_CYCLES, + MODE_ACTIVE, + MODE_OFF, + CurveFollow, + format_log_line, + path_is_relevant, + read_curve_follow_mode, +) +from openpilot.selfdrive.controls.lib.radar_path_gate import model_path_xy, path_lateral_m +from openpilot.selfdrive.controls.lib.model_sight import model_sight +from openpilot.selfdrive.controls.lib.sight_cap import ( + MODE_OFF as SIGHT_MODE_OFF, SightCap, classify_lead, crest_ahead, read_sight_cap_mode, +) +from openpilot.selfdrive.controls.lib.sight_cap import LOG_PERIOD_S as SIGHT_LOG_PERIOD_S +from openpilot.selfdrive.controls.lib.sight_cap import format_log_line as sight_log_line +from openpilot.selfdrive.controls.lib.lead_leaving import LeadLeavingEstimator +from openpilot.selfdrive.controls.lib.unified_lead import UnifiedLeadController, unified_follow_desired +from openpilot.selfdrive.controls.lib.gap_lock import ( + GapLockLatch, + gap_lock_param_enabled, + stalk_follow_exit, +) +from openpilot.selfdrive.controls.lib.lead_approach import ( + lead_approach_track_ok, + lead_close_should_cap, + resolve_lead_close_hold, +) +from openpilot.selfdrive.controls.lib.follow_distance import FollowDistanceBlend, NAP_FOLLOW_DISTANCE_RANGE from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import T_IDXS as T_IDXS_MPC -from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_speed_error -from openpilot.selfdrive.car.cruise import V_CRUISE_MAX +from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_accel_from_plan +from openpilot.selfdrive.car.cruise import V_CRUISE_MAX, V_CRUISE_UNSET +from openpilot.selfdrive.mapd.constants import MODE_CAP, MODE_FOLLOW, map_accel_a_ms2, map_brake_a_ms2 +from openpilot.selfdrive.mapd.map_speed_policy import ( + MAP_SOURCE_DEFAULT, default_drop_cap_ms, + cap_planner_v_cruise_ms, map_climb_replaces_mpc, map_in_track_deadband, map_track_accel_ms2, + map_track_decel_ms2, read_map_speed_params, +) +from openpilot.selfdrive.mapd.roundabout import RB_DECEL_JERK_MS3, RingExitGate, apply_roundabout_plan, live_map_roundabout_hint +from openpilot.selfdrive.controls.lib.hill_climb import ( + apply_hill_climb, read_hypermile_hill_climb, +) +from openpilot.selfdrive.controls.lib.hypermile import ( + effective_nap_follow_dist, read_hypermile_params, +) +from openpilot.common.params import Params from openpilot.common.swaglog import cloudlog -LON_MPC_STEP = 0.2 # first step is 0.2s -A_CRUISE_MIN = -1.2 + A_CRUISE_MAX_VALS = [1.6, 1.2, 0.8, 0.6] A_CRUISE_MAX_BP = [0., 10.0, 25., 40.] + +# Pre-AP follow-mode accel cap: imported lazily to avoid circular deps +_preap_follow_cache = None +def _get_preap_follow_limit(v_ego): + global _preap_follow_cache + if _preap_follow_cache is None: + try: + from opendbc.car.tesla.preap.constants import ACCEL_PREAP_BP, ACCEL_PREAP_FOLLOW + _preap_follow_cache = (ACCEL_PREAP_BP, ACCEL_PREAP_FOLLOW) + except ImportError: + _preap_follow_cache = (None, None) + bp, v = _preap_follow_cache + if bp is None: + return None + return float(np.interp(v_ego, bp, v)) + + +def get_preap_follow_cap_strength(v_ego, lead_distance, lead_speed, t_follow): + lead_obstacle_distance = lead_distance + get_stopped_equivalence_factor(max(lead_speed, 0.0)) + safe_obstacle_distance = get_safe_obstacle_distance(v_ego, t_follow) + equivalent_ratio = lead_obstacle_distance / max(safe_obstacle_distance, 1.0) + return float(np.clip(1.0 - (equivalent_ratio - 1.2) / 0.3, 0.0, 1.0)) + + CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N] +ALLOW_THROTTLE_THRESHOLD = 0.4 +MIN_ALLOW_THROTTLE_SPEED = 2.5 # Lookup table for turns _A_TOTAL_MAX_V = [1.7, 3.2] _A_TOTAL_MAX_BP = [20., 40.] - def get_max_accel(v_ego): - return interp(v_ego, A_CRUISE_MAX_BP, A_CRUISE_MAX_VALS) + return np.interp(v_ego, A_CRUISE_MAX_BP, A_CRUISE_MAX_VALS) +def get_coast_accel(pitch): + return np.sin(pitch) * -5.65 - 0.3 # fitted from data using xx/projects/allow_throttle/compute_coast_accel.py -def limit_accel_in_turns(v_ego, angle_steers, a_target, CP): +def limit_accel_in_turns(v_ego, angle_steers, a_target, CP, a_y=None, a_y_ahead=None): """ This function returns a limited long acceleration allowed, depending on the existing lateral acceleration - this should avoid accelerating when losing the target in turns + this should avoid accelerating when losing the target in turns. + + Pre-AP HUD MAX snapshot/restore through a bend lives in card.py + (CurveMaxHold). This clip is temporary +a only — it must not rebase + vCruise / sticky MAX. + + With true cornering force (`a_y`, vehicle-model curvature) the clip is a + friction circle on the smaller of now and the model path 1 s ahead, so + +a returns near the apex. Without it, the stock steer-model table stays. """ + if a_y is not None: + return [a_target[0], min(a_target[1], turn_accel_limit(v_ego, a_y, a_y_ahead))] # FIXME: This function to calculate lateral accel is incorrect and should use the VehicleModel # The lookup table for turns should also be updated if we do this - a_total_max = interp(v_ego, _A_TOTAL_MAX_BP, _A_TOTAL_MAX_V) + a_total_max = np.interp(v_ego, _A_TOTAL_MAX_BP, _A_TOTAL_MAX_V) a_y = v_ego ** 2 * angle_steers * CV.DEG_TO_RAD / (CP.steerRatio * CP.wheelbase) a_x_allowed = math.sqrt(max(a_total_max ** 2 - a_y ** 2, 0.)) return [a_target[0], min(a_target[1], a_x_allowed)] -def get_accel_from_plan(CP, speeds, accels): - if len(speeds) == CONTROL_N: - v_target_now = interp(DT_MDL, CONTROL_N_T_IDX, speeds) - a_target_now = interp(DT_MDL, CONTROL_N_T_IDX, accels) - v_target = interp(CP.longitudinalActuatorDelay + DT_MDL, CONTROL_N_T_IDX, speeds) - a_target = 2 * (v_target - v_target_now) / CP.longitudinalActuatorDelay - a_target_now +# First-frame brake head start for a new lead (m/s^2 below the lead-free command). +SEED_BRAKE_STEP_MS2 = 0.7 +CYCLE_LOG_EVERY_N = 600 # ~30 s at the 20 Hz model rate + + +class CycleTimeLog: + """Running planner update() cost, logged every CYCLE_LOG_EVERY_N cycles. + + The unified controller is the only lead-follow path, so this is the number + to compare against older builds when checking plannerd CPU. + """ + + def __init__(self, every_n: int = CYCLE_LOG_EVERY_N) -> None: + self.every_n = int(every_n) + self.reset() - v_target_1sec = interp(CP.longitudinalActuatorDelay + DT_MDL + 1.0, CONTROL_N_T_IDX, speeds) - else: - v_target = 0.0 - v_target_1sec = 0.0 - a_target = 0.0 - should_stop = (v_target < CP.vEgoStopping and - v_target_1sec < CP.vEgoStopping) - return a_target, should_stop + def reset(self) -> None: + self.n = 0 + self.total_s = 0.0 + self.max_s = 0.0 + + def record(self, elapsed_s: float): + """Add one cycle. Returns (n, mean_ms, max_ms) when a window closes, else None.""" + self.n += 1 + self.total_s += float(elapsed_s) + self.max_s = max(self.max_s, float(elapsed_s)) + if self.n < self.every_n: + return None + out = (self.n, 1000.0 * self.total_s / self.n, 1000.0 * self.max_s) + self.reset() + return out class LongitudinalPlanner: - def __init__(self, CP, init_v=0.0, init_a=0.0, dt=DT_MDL): + def __init__(self, CP, init_v=0.0, init_a=0.0, dt=DT_MDL, params=None): self.CP = CP self.mpc = LongitudinalMpc(dt=dt) self.fcw = False self.dt = dt + self.allow_throttle = True + + self._is_preap = (CP.brand == "tesla" and CP.carFingerprint == "TESLA_MODEL_S_PREAP" + and CP.openpilotLongitudinalControl and not CP.pcmCruise) + self._params = Params() if params is None else params + self.nap_follow_dist = self._params.get("NAPFollowDistance", return_default=True) if self._is_preap else None + self.nap_adaptive_accel = self._params.get_bool("NAPAdaptiveAccel") if self._is_preap else False + self._hypermile_on = read_hypermile_params(self._params) if self._is_preap else False + self._hypermile_hill_climb = read_hypermile_hill_climb(self._params) if self._is_preap else False + self._hill_pitch = 0.0 + self._map_speed_mode, self._map_speed_offset_kph, self._map_speed_lookahead, self._map_speed_accel = ( + read_map_speed_params(self._params) if self._is_preap else (0, 0.0, 0, 5) + ) + self._follow_blend = FollowDistanceBlend() + if self._is_preap: + self._follow_blend.read_setpoints(self._params) + self.active_nap_follow_dist = effective_nap_follow_dist(self._is_preap, self.nap_follow_dist) + self.t_follow = get_T_FOLLOW(nap_follow_dist=self.active_nap_follow_dist) + self._frame = 0 + # Last in-window radar lead, held through a brief status drop. + self._lead_close_hold_d = None + self._lead_close_hold_v = None + self._lead_close_hold_a = None + self._lead_close_hold_age = 0.0 + self._lead_y_rel = None + self._corner_curvature = 0.0 + self._curve_preview = CurvePreview() + self.curve_preview_a = PREVIEW_FREE_A_MS2 + # Curve-follow (NAPCurveFollow 0 off / 1 shadow / 2 active). Shadow computes + # and logs only; the old preview and CurveMaxHold stay in force. + self._cf_mode = read_curve_follow_mode(self._params) if self._is_preap else MODE_OFF + self._curve_follow = CurveFollow() + self.curve_follow_a = PREVIEW_FREE_A_MS2 + self._cf_trusted = False + self._cf_faulted = False + self._cf_cycle = 0 + # Sight-distance cap (NAPSightCap 0 off / 1 shadow). LOG ONLY: nothing reads it. + self._sc_mode = read_sight_cap_mode(self._params) if self._is_preap else SIGHT_MODE_OFF + self._sight_cap = SightCap() + self._sc_faulted = False + self._sc_last_log = -1e9 + self._sc_clock = 0.0 + self._turn_a_max = None self.a_desired = init_a self.v_desired_filter = FirstOrderFilter(init_v, 2.0, self.dt) - self.v_model_error = 0.0 + self.prev_accel_clip = [ACCEL_MIN, ACCEL_MAX] + self.output_a_target = 0.0 + self.output_should_stop = False + # Continuous lead follow: the one longitudinal controller for a lead on Pre-AP. + self.unified_a_target = 0.0 + self._unified = UnifiedLeadController() + self._gap_lock = GapLockLatch() + self._gap_lock_enabled = False + self._lead_leave = LeadLeavingEstimator() + self.lead_leave_w = 0.0 + self._unified_v_cap_ms = 0.0 + self._unified_lead_id = None + self._unified_following = False + # A compute failure latches until process restart. It must not escape update(). + self._unified_faulted = False + self._unified_fault_count = 0 + self._unified_fault_logged = False + self._cycle_log = CycleTimeLog() self.v_desired_trajectory = np.zeros(CONTROL_N) self.a_desired_trajectory = np.zeros(CONTROL_N) self.j_desired_trajectory = np.zeros(CONTROL_N) - self.solverExecutionTime = 0.0 @staticmethod - def parse_model(model_msg, model_error): + def parse_model(model_msg): if (len(model_msg.position.x) == ModelConstants.IDX_N and len(model_msg.velocity.x) == ModelConstants.IDX_N and len(model_msg.acceleration.x) == ModelConstants.IDX_N): - x = np.interp(T_IDXS_MPC, ModelConstants.T_IDXS, model_msg.position.x) - model_error * T_IDXS_MPC - v = np.interp(T_IDXS_MPC, ModelConstants.T_IDXS, model_msg.velocity.x) - model_error + x = np.interp(T_IDXS_MPC, ModelConstants.T_IDXS, model_msg.position.x) + v = np.interp(T_IDXS_MPC, ModelConstants.T_IDXS, model_msg.velocity.x) a = np.interp(T_IDXS_MPC, ModelConstants.T_IDXS, model_msg.acceleration.x) j = np.zeros(len(T_IDXS_MPC)) else: @@ -93,52 +264,214 @@ def parse_model(model_msg, model_error): v = np.zeros(len(T_IDXS_MPC)) a = np.zeros(len(T_IDXS_MPC)) j = np.zeros(len(T_IDXS_MPC)) - return x, v, a, j + if len(model_msg.meta.disengagePredictions.gasPressProbs) > 1: + throttle_prob = model_msg.meta.disengagePredictions.gasPressProbs[1] + else: + throttle_prob = 1.0 + return x, v, a, j, throttle_prob + + def _update_corner_state(self, sm) -> None: + """Vehicle-model curvature for the lead path weighting and the curve ceiling.""" + curv = getattr(sm['controlsState'], "curvature", 0.0) + self._corner_curvature = 0.0 if curv is None else float(curv) + + def _track_lead(self, sm) -> None: + """Hold the last in-window radar lead through a brief status drop. + + The continuous controller reads this: a live lead, or the held one while + radard flickers, with its aLead and lateral offset. + """ + if not self._is_preap: + return + lead = sm['radarState'].leadOne + d_cap, _, self._lead_close_hold_d, self._lead_close_hold_v, self._lead_close_hold_age = ( + resolve_lead_close_hold( + lead.status, lead.dRel, lead.vLead, + self._lead_close_hold_d, self._lead_close_hold_v, self._lead_close_hold_age, + self.dt, model_prob=lead.modelProb, radar=lead.radar, + ) + ) + if d_cap is not None: + if lead.status and lead_close_should_cap(lead.dRel, lead.modelProb, lead.radar, active=True): + self._lead_close_hold_a = float(lead.aLeadK) + else: + self._lead_close_hold_a = None + held = self._lead_close_hold_d is not None and self._lead_close_hold_v is not None + if bool(lead.status) and lead_close_should_cap(lead.dRel, lead.modelProb, lead.radar, active=False): + self._lead_y_rel = float(lead.yRel) + elif not held: + self._lead_y_rel = None def update(self, sm): - self.mpc.mode = 'blended' if sm['selfdriveState'].experimentalMode else 'acc' + t0 = time.perf_counter() + self._update(sm) + window = self._cycle_log.record(time.perf_counter() - t0) + if window is not None: + cloudlog.info("longitudinal planner cycle: n=%d mean=%.3f ms max=%.3f ms", *window) + + def _update(self, sm): + self._frame += 1 + if self._is_preap: + # Stalk Follow Distance 1–7 must land on the next plan. + self.nap_follow_dist = self._params.get("NAPFollowDistance", return_default=True) + self._hypermile_on = read_hypermile_params(self._params) + self._hypermile_hill_climb = read_hypermile_hill_climb(self._params) + self.nap_adaptive_accel = self._params.get_bool("NAPAdaptiveAccel") + self._map_speed_mode, self._map_speed_offset_kph, self._map_speed_lookahead, self._map_speed_accel = ( + read_map_speed_params(self._params) + ) + self._follow_blend.read_setpoints(self._params) + self._cf_mode = read_curve_follow_mode(self._params) + self._sc_mode = read_sight_cap_mode(self._params) + self._gap_lock_enabled = gap_lock_param_enabled(self._params) + + if len(sm['carControl'].orientationNED) == 3: + accel_coast = get_coast_accel(sm['carControl'].orientationNED[1]) + else: + accel_coast = ACCEL_MAX v_ego = sm['carState'].vEgo v_cruise_kph = min(sm['carState'].vCruise, V_CRUISE_MAX) v_cruise = v_cruise_kph * CV.KPH_TO_MS + # HUD MAX after card's map overlay (seed / sticky / Follow override). + v_hud_ms = v_cruise + v_cruise_initialized = sm['carState'].vCruise != V_CRUISE_UNSET long_control_off = sm['controlsState'].longControlState == LongCtrlState.off force_slow_decel = sm['controlsState'].forceDecel # Reset current state when not engaged, or user is controlling the speed reset_state = long_control_off if self.CP.openpilotLongitudinalControl else not sm['selfdriveState'].enabled + # PCM cruise speed may be updated a few cycles later, check if initialized + reset_state = reset_state or not v_cruise_initialized # No change cost when user is controlling the speed, or when standstill prev_accel_constraint = not (reset_state or sm['carState'].standstill) - if self.mpc.mode == 'acc': - accel_limits = [A_CRUISE_MIN, get_max_accel(v_ego)] - accel_limits_turns = limit_accel_in_turns(v_ego, sm['carState'].steeringAngleDeg, accel_limits, self.CP) - else: - accel_limits = [ACCEL_MIN, ACCEL_MAX] - accel_limits_turns = [ACCEL_MIN, ACCEL_MAX] + accel_clip = [ACCEL_MIN, get_max_accel(v_ego)] + steer_angle_without_offset = sm['carState'].steeringAngleDeg - sm['liveParameters'].angleOffsetDeg + # Pre-AP: true cornering force (vehicle-model curvature) and the model + # path ahead for the turn clip and the curve preview. + curve_path = path_curvature(sm['modelV2']) if self._is_preap else None + a_y_now = None + a_y_ahead = None + if self._is_preap: + a_y_now = abs(float(getattr(sm['controlsState'], "curvature", 0.0) or 0.0)) * v_ego * v_ego + if curve_path is not None: + a_y_ahead = path_lat_accel_ahead(v_ego, curve_path[0], curve_path[2]) + accel_clip = limit_accel_in_turns( + v_ego, steer_angle_without_offset, accel_clip, self.CP, a_y=a_y_now, a_y_ahead=a_y_ahead, + ) + self._turn_a_max = float(accel_clip[1]) if self._is_preap else None if reset_state: self.v_desired_filter.x = v_ego # Clip aEgo to cruise limits to prevent large accelerations when becoming active - self.a_desired = clip(sm['carState'].aEgo, accel_limits[0], accel_limits[1]) + self.a_desired = np.clip(sm['carState'].aEgo, accel_clip[0], accel_clip[1]) + self._lead_close_hold_d = None + self._lead_close_hold_v = None + self._lead_close_hold_a = None + self._lead_close_hold_age = 0.0 + self._lead_y_rel = None + self._corner_curvature = 0.0 + self._unified.reset() + self._unified_lead_id = None + self._unified_following = False + self._curve_preview.reset() # Prevent divergence, smooth in current v_ego self.v_desired_filter.x = max(0.0, self.v_desired_filter.update(v_ego)) - # Compute model v_ego error - self.v_model_error = get_speed_error(sm['modelV2'], v_ego) + _, _, _, _, throttle_prob = self.parse_model(sm['modelV2']) + # Don't clip at low speeds since throttle_prob doesn't account for creep + # VDAS takes acceleration targets literally, so the model's negative coast + # ceiling commands regen even when the MPC is trying to hold cruise speed. + self.allow_throttle = self._is_preap or throttle_prob > ALLOW_THROTTLE_THRESHOLD or v_ego <= MIN_ALLOW_THROTTLE_SPEED + + if not self.allow_throttle: + clipped_accel_coast = max(accel_coast, accel_clip[0]) + clipped_accel_coast_interp = np.interp(v_ego, [MIN_ALLOW_THROTTLE_SPEED, MIN_ALLOW_THROTTLE_SPEED*2], [accel_clip[1], clipped_accel_coast]) + accel_clip[1] = min(accel_clip[1], clipped_accel_coast_interp) if force_slow_decel: v_cruise = 0.0 - # clip limits, cannot init MPC outside of bounds - accel_limits_turns[0] = min(accel_limits_turns[0], self.a_desired + 0.05) - accel_limits_turns[1] = max(accel_limits_turns[1], self.a_desired - 0.05) + + # OSM map speed: trust card HUD MAX (eased decreases, lag-corrected raises). + # Do not min() with posted — that snapped when GPS entered a lower zone. + # Roundabout funnel: cap cruise to ring speed and command kinematic −a + # (not Lookahead comfort). aTarget stays ≤ 0 until the ring is exited. + rb_hint = None + a_rb_plan = 0.0 + if self._is_preap: + try: + md = sm['liveMapDataNAP'] + except Exception: + md = None + rb_hint = live_map_roundabout_hint(md) + try: + self._map_default = str(getattr(md, "source", "") or "") == MAP_SOURCE_DEFAULT + except Exception: + self._map_default = False + # Oct 13: right blinker on the ring + leaving it ends the ring clamp + # (same gate as card's MAX). The blinker alone does nothing. + if not hasattr(self, "_rb_exit_gate"): + self._rb_exit_gate = RingExitGate() + try: + rb_curv = float(getattr(sm['controlsState'], "curvature", 0.0)) + rb_right = bool(getattr(sm['carState'], "rightBlinker", False)) + except Exception: + rb_curv, rb_right = 0.0, False + if self._rb_exit_gate.update(rb_hint, rb_right, rb_curv, self.dt): + rb_hint = None + if (not force_slow_decel) and self._is_preap and self._map_speed_mode in (MODE_CAP, MODE_FOLLOW): + v_cruise = cap_planner_v_cruise_ms(v_hud_ms, None, mode=self._map_speed_mode) + if not force_slow_decel: + v_cruise, v_hud_ms, a_rb_plan, rb_v = apply_roundabout_plan( + v_ego, v_cruise, v_hud_ms, 0.0, rb_hint, self._map_speed_lookahead, + ) + else: + rb_v = None + self._unified_v_cap_ms = float(v_hud_ms) + + self.active_nap_follow_dist = effective_nap_follow_dist(self._is_preap, self.nap_follow_dist) + self.t_follow = get_T_FOLLOW(sm['selfdriveState'].personality, self.active_nap_follow_dist) + long_engaged = self._is_preap and (not reset_state) + has_lead_status = bool(sm['radarState'].leadOne.status) + if self._is_preap: + lead_tf = sm['radarState'].leadOne + # Unset (255) is clamped to V_CRUISE_MAX above, which would look + # like a highway MAX. 0 is not a city set speed. Ego is the fallback. + follow_max_ms = v_hud_ms if v_cruise_initialized and float(v_hud_ms) > 0.0 else None + t_blended, active_dist, _ = self._follow_blend.update( + v_ego, self.dt, + engaged=long_engaged, + has_lead=has_lead_status, + v_lead=float(lead_tf.vLead) if has_lead_status else None, + v_cruise=follow_max_ms, + ) + if active_dist in NAP_FOLLOW_DISTANCE_RANGE: + self.active_nap_follow_dist = active_dist + self.nap_follow_dist = active_dist + self.t_follow = float(t_blended) + + # Pre-AP adaptive accel: only limit accel when the lead's obstacle-equivalent + # distance is close. Above 1.5x the full cruise profile applies. Below 1.2x, + # cap to follow limits so the command the lead-follow controller starts + # from does not overshoot. Blend in between. + if self.CP.carFingerprint == "TESLA_MODEL_S_PREAP" and self.nap_adaptive_accel and sm['radarState'].leadOne.status: + follow_limit = _get_preap_follow_limit(v_ego) + if follow_limit is not None: + lead = sm['radarState'].leadOne + cap_strength = get_preap_follow_cap_strength(v_ego, lead.dRel, lead.vLead, self.t_follow) + if cap_strength > 0: + blended = accel_clip[1] * (1.0 - cap_strength) + follow_limit * cap_strength + accel_clip[1] = min(accel_clip[1], blended) + + self._update_corner_state(sm) + self._track_lead(sm) self.mpc.set_weights(prev_accel_constraint, personality=sm['selfdriveState'].personality) - self.mpc.set_accel_limits(accel_limits_turns[0], accel_limits_turns[1]) self.mpc.set_cur_state(self.v_desired_filter.x, self.a_desired) - x, v, a, j = self.parse_model(sm['modelV2'], self.v_model_error) - self.mpc.update(sm['radarState'], v_cruise, x, v, a, j, personality=sm['selfdriveState'].personality) + self.mpc.update(sm['radarState'], v_cruise, t_follow=self.t_follow) self.v_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC, self.mpc.v_solution) self.a_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC, self.mpc.a_solution) @@ -151,13 +484,587 @@ def update(self, sm): # Interpolate 0.05 seconds and save as starting point for next iteration a_prev = self.a_desired - self.a_desired = float(interp(self.dt, CONTROL_N_T_IDX, self.a_desired_trajectory)) + self.a_desired = float(np.interp(self.dt, CONTROL_N_T_IDX, self.a_desired_trajectory)) self.v_desired_filter.x = self.v_desired_filter.x + self.dt * (self.a_desired + a_prev) / 2.0 + action_t = self.CP.longitudinalActuatorDelay + DT_MDL + output_a_target_mpc, output_should_stop_mpc = get_accel_from_plan(self.v_desired_trajectory, self.a_desired_trajectory, CONTROL_N_T_IDX, + action_t=action_t, vEgoStopping=self.CP.vEgoStopping) + output_a_target_e2e = sm['modelV2'].action.desiredAcceleration + output_should_stop_e2e = sm['modelV2'].action.shouldStop + + if sm['selfdriveState'].experimentalMode: + output_a_target = min(output_a_target_e2e, output_a_target_mpc) + self.output_should_stop = output_should_stop_e2e or output_should_stop_mpc + if output_a_target < output_a_target_mpc: + self.mpc.source = LongitudinalPlanSource.e2e + else: + output_a_target = output_a_target_mpc + self.output_should_stop = output_should_stop_mpc + if self._is_preap: + self._update_lead_leave(sm, float(v_ego), reset_state) + + # Map MAX is a set speed; MPC cruise_obstacle will not track it. + # Climb at Accel 1–10 until the deadband, then hold so we do not surge + # past MAX and map_track_decel below it. Brake is locked Accel 5. + # A valid radar lead owns follow: do not replace ~0 / slight+ MPC with + # map climb toward MAX (punch + overshoot + sluggish re-match). + # map_track_decel when above MAX still mins in. + # Hypermile Hill Climb (IMU pitch only — no maps-elevation lookahead) + # then raises +a on a real uphill *under* MAX when there is no lead. + # Crest / downhill ease only at or above MAX (not TRACK_TAPER). + # Deadband leaves hold 0 — no +g·sin past MAX. It never writes vCruise / MAX. + has_valid_lead = bool(sm['radarState'].leadOne.status) + if len(sm['carControl'].orientationNED) == 3: + hill_pitch = float(sm['carControl'].orientationNED[1]) + else: + hill_pitch = 0.0 + if self._is_preap and self._map_speed_mode in (MODE_CAP, MODE_FOLLOW): + if map_in_track_deadband(v_ego, v_hud_ms): + if float(output_a_target) >= 0.0: + output_a_target = 0.0 + pre_hill = float(output_a_target) + output_a_target = apply_hill_climb( + pitch_rad=hill_pitch, + prev_pitch_rad=self._hill_pitch, + v_ego_ms=v_ego, + v_cruise_ms=v_hud_ms, + a_cmd=float(output_a_target), + in_deadband=True, + hypermile_on=self._hypermile_on, + hill_climb_on=self._hypermile_hill_climb, + ) + if has_valid_lead and float(output_a_target) > pre_hill: + output_a_target = pre_hill + else: + a_brake = map_track_decel_ms2( + v_ego, v_hud_ms, map_brake_a_ms2(self._map_speed_lookahead), + ) + if a_brake is not None: + output_a_target = min(float(output_a_target), a_brake) + else: + a_up = map_track_accel_ms2( + v_ego, v_hud_ms, map_accel_a_ms2(self._map_speed_lookahead, self._map_speed_accel), + accel_level=self._map_speed_accel, + ) + if map_climb_replaces_mpc(a_up, output_a_target, has_valid_lead): + # min() alone never created climb (MPC holds ~0). Command Accel 1–10 + # toward MAX only when no radar lead is following. + output_a_target = a_up + pre_hill = float(output_a_target) + output_a_target = apply_hill_climb( + pitch_rad=hill_pitch, + prev_pitch_rad=self._hill_pitch, + v_ego_ms=v_ego, + v_cruise_ms=v_hud_ms, + a_cmd=float(output_a_target), + in_deadband=False, + hypermile_on=self._hypermile_on, + hill_climb_on=self._hypermile_hill_climb, + ) + if has_valid_lead and float(output_a_target) > pre_hill: + # Do not add +g·sin punch toward MAX while a lead constrains. + output_a_target = pre_hill + self._hill_pitch = hill_pitch + + # Maps-off / display still eases into an RB (card may not have dropped MAX). + # Kinematic a from apply_roundabout_plan — not map_track_decel comfort. + # Oct 11: jerk-limit the onset of the ring −a (no brick-wall step). + if rb_v is not None: + a_jl_prev = float(getattr(self, "_rb_a_jl", 0.0)) + a_rb_jl = max(float(a_rb_plan), a_jl_prev - RB_DECEL_JERK_MS3 * self.dt) + self._rb_a_jl = a_rb_jl + output_a_target = min(float(output_a_target), a_rb_jl) + else: + self._rb_a_jl = 0.0 + + # Curve preview: accel ceiling from the model path (0–5 s) that slows + # ahead of a bend, finished ~1.5 s before the tight point, and holds + # back +a just under a bend's comfort speed. min() only: never raises + # the command. A lead, if any, is then followed by the continuous + # controller, which takes this ceiling as its own map/curve term. + self.curve_preview_a = PREVIEW_FREE_A_MS2 + if self._is_preap: + if reset_state or curve_path is None: + self._curve_preview.reset() + else: + a_prev_raw = curve_preview_accel(v_ego, *curve_path) + self.curve_preview_a = float(self._curve_preview.update(v_ego, a_prev_raw, self.dt)) + # Curve-follow: computed and logged in shadow (1) and active (2). Only + # active replaces the old preview's ceiling; the lead law still takes it + # through the same a_map slot, so nothing else changes. + old_preview_a = float(self.curve_preview_a) + self._update_curve_follow(sm, float(v_ego), curve_path, old_preview_a, rb_v is not None, + float(output_a_target)) + self._update_sight_cap(sm, float(v_ego), curve_path, rb_v is not None, rb_hint) + output_a_target = min(float(output_a_target), self.curve_preview_a) + + for idx in range(2): + accel_clip[idx] = np.clip(accel_clip[idx], self.prev_accel_clip[idx] - 0.05, self.prev_accel_clip[idx] + 0.05) + self.output_a_target = np.clip(output_a_target, accel_clip[0], accel_clip[1]) + self.prev_accel_clip = accel_clip + self._apply_lead_follow(sm, float(v_ego)) + + def _update_curve_follow(self, sm, v_ego: float, curve_path, old_preview_a: float, rb_active: bool, + a_target: float) -> None: + """Curve-follow step. Never raises; a fault latches it off (old preview stays).""" + self._cf_trusted = False + self.curve_follow_a = PREVIEW_FREE_A_MS2 + if self._cf_mode == MODE_OFF or self._cf_faulted: + return + try: + model = sm['modelV2'] + meta = model.meta + ts, ds, ks = curve_path if curve_path is not None else (None, None, None) + y_std = list(model.position.yStd) + y_std = y_std if (ts is not None and len(y_std) == len(ts)) else None + car_state = sm['carState'] + blinker = bool(car_state.leftBlinker or car_state.rightBlinker) + lane_change = str(meta.laneChangeState) != "off" + frame_drop = float(model.frameDropPerc) + a_cf = float(self._curve_follow.step( + dt=self.dt, v_ego=v_ego, ts=ts, ds=ds, ks=ks, y_std=y_std, lane_change=lane_change, + blinker=blinker, frame_drop_pct=frame_drop, rb_active=rb_active, valid=curve_path is not None, + )) + self.curve_follow_a = a_cf + self._cf_trusted = bool(self._curve_follow.trusted) + if self._cf_mode == MODE_ACTIVE: + self.curve_preview_a = a_cf + self._cf_cycle += 1 + if v_ego >= 2.0 and ts is not None and self._cf_cycle % LOG_PERIOD_CYCLES == 0: + arrays = (path_is_relevant(ks, a_cf, old_preview_a, self._curve_follow.conf) + or self._cf_cycle % LOG_QUIET_PERIOD_CYCLES == 0) + self._log_curve_follow(sm, model, v_ego, a_target, old_preview_a, ts, ds, ks, y_std, blinker, + lane_change, frame_drop, rb_active, arrays) + except Exception: + self._cf_faulted = True + self._cf_trusted = False + self.curve_follow_a = PREVIEW_FREE_A_MS2 + cloudlog.exception("curve_follow fault: old preview stays in force") + + def _update_sight_cap(self, sm, v_ego: float, curve_path, rb_live: bool, rb_hint) -> None: + """Sight-distance cap in shadow: compute and log. Never touches the command.""" + if self._sc_mode == SIGHT_MODE_OFF or self._sc_faulted: + return + try: + model = sm['modelV2'] + self._sc_clock += self.dt + t_s = self._sc_clock + sight = model_sight(model) + radar_state = sm['radarState'] + lead_one = radar_state.leadOne + live = bool(lead_one.status) + path_x = path_y = None + lat = None + if live: + try: + path_x, path_y = model_path_xy(model) + lat = path_lateral_m(lead_one, path_x, path_y) + except Exception: + lat = None + lead = classify_lead(live, lat, float(lead_one.vLead) if live else None, float(lead_one.dRel) if live else None) + others = [] + lead_two = radar_state.leadTwo + if bool(lead_two.status): + try: + lat2 = path_lateral_m(lead_two, *model_path_xy(model)) + except Exception: + lat2 = None + others.append(classify_lead(True, lat2, float(lead_two.vLead), float(lead_two.dRel))) + ks = curve_path[2] if curve_path is not None else None + sc = self._sight_cap + sc.update(t=t_s, dt=self.dt, v_ego=v_ego, sight_m=sight, ks=ks, + conf_red=str(model.confidence) == "red", lead=lead, rb_live=rb_live, + rb_ahead=bool(rb_hint is not None and getattr(rb_hint, "approaching", False)), others=others) + if sc.fired_edge or sc.suppressed_edge or (sc.would_fire and t_s - self._sc_last_log >= SIGHT_LOG_PERIOD_S): + self._sc_last_log = t_s + self._log_sight_cap(sm, model, t_s, v_ego, lead, live, others) + except Exception: + self._sc_faulted = True + cloudlog.exception("sight_cap fault: shadow logging stopped") + + def _log_sight_cap(self, sm, model, t_s: float, v_ego: float, lead, live: bool, others) -> None: + """Would-fire record through errorLogMessage (qlog), like curvefollow. No capnp fields.""" + try: + sc = self._sight_cap + cs = sm['carState'] + two = sm['radarState'].leadTwo + two_info = None + if bool(two.status): + try: + lat2 = path_lateral_m(two, *model_path_xy(model)) + except Exception: + lat2 = None + t2 = classify_lead(True, lat2, float(two.vLead), float(two.dRel)) + two_info = [t2.lane, round(float(t2.v), 1), round(float(t2.d), 1)] + crest, z2 = crest_ahead(list(model.position.x), list(model.position.z)) + pitch = None + try: + if len(sm['carControl'].orientationNED) == 3: + pitch = round(float(sm['carControl'].orientationNED[1]), 4) + except Exception: + pitch = None + night = None + sun_el = None + try: + md = sm['liveMapDataNAP'] + lat_deg, lon_deg = float(md.latitude), float(md.longitude) + if lat_deg != 0.0 or lon_deg != 0.0: + from openpilot.selfdrive.controls.lib.lat_low_visibility import solar_position + # Wall clock for the sun position only (log field; never control). + sun_el, _az = solar_position(lat_deg, lon_deg, time.time()) # noqa: TID251 + night = bool(sun_el < -6.0) + sun_el = round(float(sun_el), 1) + except Exception: + night = None + cf_a = float(self.curve_follow_a) + try: + t_log = float(sm.logMonoTime['modelV2']) * 1e-9 + except Exception: + t_log = t_s + rec = { + "t": round(t_log, 2), "edge": int(sc.fired_edge), "fire": int(sc.would_fire), "why": sc.reason, "cue": sc.cue, + "v": round(v_ego, 2), "sd": None if sc.sight is None else round(sc.sight, 1), + "sb": None if sc.base is None else round(sc.base, 1), + "vc": None if sc.v_cap is None else round(sc.v_cap, 2), "ac": round(sc.a_cap, 3), + "cf": round(cf_a, 3), "cmb": round(min(cf_a, sc.a_cap), 3), + "lead": [int(live), lead.lane, None if lead.v is None else round(lead.v, 1), + None if lead.d is None else round(lead.d, 1), None if lead.lat is None else round(lead.lat, 2)], + "lead2": two_info, "veh": next((k for k in (lead.kind, *(o.kind for o in others)) if k), ""), + "pitch": pitch, "crest": int(crest), "z2": z2, + "night": night, "sun": sun_el, + "llp": [round(float(p), 2) for p in list(model.laneLineProbs)[:4]], + "bl": int(bool(cs.leftBlinker)) + 2 * int(bool(cs.rightBlinker)), + "cn": str(model.confidence), + "lv": int(bool(getattr(sm['controlsState'], 'lowVisibility', False))), + } + cloudlog.error(sight_log_line(rec)) + except Exception: + pass # a sight-cap log failure must never reach the plan + + def _log_curve_follow(self, sm, model, v_ego, a_target, old_preview_a, ts, ds, ks, y_std, blinker, + lane_change, frame_drop, rb_active, arrays) -> None: + """2 Hz JSON line through errorLogMessage, which qlog keeps (same route the roundabout summary uses).""" + try: + desire = list(model.meta.desireState) + d_idx = max(range(len(desire)), key=lambda i: desire[i]) if desire else -1 + meta = { + "bl": int(bool(sm['carState'].leftBlinker)) + 2 * int(bool(sm['carState'].rightBlinker)), + "lc": str(model.meta.laneChangeState), "ds": [d_idx, round(float(desire[d_idx]), 2) if desire else 0.0], + "df": round(frame_drop, 1), "cn": str(model.confidence), "rb": int(rb_active), + "llp": [round(float(p), 2) for p in list(model.laneLineProbs)[:4]], + "res": [round(float(p), 2) for p in list(model.roadEdgeStds)[:2]], + } + t_s = float(sm.logMonoTime['modelV2']) * 1e-9 + cloudlog.error(format_log_line( + mode=self._cf_mode, t=t_s, v=v_ego, a_ego=float(sm['carState'].aEgo), + v_cruise_kph=float(sm['carState'].vCruise), a_target=a_target, cf=self._curve_follow, + old_a=old_preview_a, ts=ts, ds=ds, ks=ks, y_std=y_std, meta=meta, arrays=arrays, + )) + except Exception: + pass # logging must never touch the command + + def _update_lead_leave(self, sm, v_ego: float, reset_state: bool) -> None: + """Leaving-path weight for radard's leadOne (feeds the lead-follow controller).""" + radar_state = sm['radarState'] + lead = radar_state.leadOne + live = bool(lead.status) + held = (not live) and self._lead_close_hold_d is not None and self._lead_close_hold_v is not None + suppress = bool(reset_state or self.fcw or self.mpc.crash_cnt > 0 or self.output_should_stop + or bool(sm['controlsState'].forceDecel)) + path_lat = None + two_lat = None + if live: + try: + path_x, path_y = model_path_xy(sm['modelV2']) + path_lat = path_lateral_m(lead, path_x, path_y) + two = radar_state.leadTwo + if bool(two.status) and int(getattr(two, 'radarTrackId', -1)) != int(getattr(lead, 'radarTrackId', -1)): + two_lat = path_lateral_m(two, path_x, path_y) + if two_lat is None: + two_lat = 0.0 + except Exception: + path_lat = None + two_lat = 0.0 + self.lead_leave_w = float(self._lead_leave.update( + dt=self.dt, + present=live or held, + held=held, + lead_id=int(getattr(lead, 'radarTrackId', 0) or 0) if live else None, + path_lat=path_lat, + gap=float(lead.dRel) if live else 0.0, + v_ego=v_ego, + v_lead=float(lead.vLead) if live else None, + a_lead=float(lead.aLeadK) if live else 0.0, + model_prob=float(lead.modelProb) if live else None, + lead_two_path_lat=two_lat, + suppress=suppress, + )) + + def _note_unified_fault(self) -> None: + """Latch the controller off until this process restarts. + + cloudlog.exception runs for the first failure only. While latched the + published command is the MPC command with the map, curve and roundabout + ceilings (the lead-free path), which still brakes for the lead. + """ + self._unified_fault_count += 1 + self._unified_faulted = True + if self._unified_fault_logged: + return + self._unified_fault_logged = True + cloudlog.exception( + "unified lead-follow compute failed (count=%d); MPC command stays in force", + self._unified_fault_count, + ) + + def _refresh_gap_lock(self, sm, lead) -> None: + """Latch or clear. A throw here must not latch the unified fault.""" + cs = sm["carState"] + long_on = False + try: + long_on = (cs.enableLongControl is True) and (cs.cruiseState.enabled is True) + except Exception: + long_on = False + try: + seq = int(cs.gapLockArmSeq) + except (TypeError, ValueError, AttributeError): + seq = 0 + holding = False + try: + holding = bool(cs.gapLockHold) + except (TypeError, ValueError, AttributeError): + holding = False + status = False + radar = False + track_id = -1 + d_rel = None + y_rel = None + try: + status = bool(lead.status) + radar = bool(lead.radar) + track_id = int(lead.radarTrackId) + if status: + d_rel = float(lead.dRel) + except (TypeError, ValueError, AttributeError): + status = False + radar = False + track_id = -1 + d_rel = None + if status: + try: + y_rel = float(lead.yRel) + except (TypeError, ValueError, AttributeError): + y_rel = None + self._gap_lock.update( + self.dt, + enabled=self._gap_lock_enabled is True, + long_on=long_on, + seq=seq, + status=status, + radar=radar, + track_id=track_id, + d_rel=d_rel, + stalk_exit=stalk_follow_exit(cs), + holding=holding, + y_rel=y_rel, + ) + + def _gap_set_override(self, lead, live: bool, held: bool): + """Locked meters, or the in-hold median, for this radar id. + + The hold publishes the running median before the latch so the ease + toward the time gap stops as soon as the stalk hold starts. + """ + try: + gap_m = self._gap_lock.gap_m + track = self._gap_lock.track_id + if gap_m is None: + gap_m = self._gap_lock.preview_m + track = self._gap_lock.preview_track + if gap_m is None or track is None: + return None + if live: + # A brief vision-only dip of the locked track keeps the meters. + # The in-hold preview still wants a radar id. + if self._gap_lock.gap_m is None and lead.radar is not True: + return None + if int(lead.radarTrackId) != int(track): + return None + return float(gap_m) + if held: + return float(gap_m) + except (TypeError, ValueError, AttributeError): + return None + return None + + def _apply_lead_follow(self, sm, v_ego: float) -> None: + """The one lead-follow controller (Pre-AP). + + Runs every frame. With a live or held lead its command replaces the + lead-free command in output_a_target. With none, the lead-free command + (MPC, map, hill, roundabout, curve preview) stands. FCW, should-stop and + force-decel keep that command if it is deeper. A compute exception + latches the controller off and leaves the lead-free command in force. + """ + if not self._is_preap: + self.unified_a_target = 0.0 + return + + lead = sm["radarState"].leadOne + try: + self._refresh_gap_lock(sm, lead) + except Exception: + pass + live = bool(lead.status) and lead_close_should_cap( + lead.dRel, lead.modelProb, lead.radar, active=False, + ) + held = self._lead_close_hold_d is not None and self._lead_close_hold_v is not None + if live: + gap = float(lead.dRel) + v_lead = float(lead.vLead) + a_lead = float(lead.aLeadK) + y_rel = float(getattr(lead, "yRel", 0.0) or 0.0) + self._unified_lead_id = ("radar", int(getattr(lead, "radarTrackId", 0) or 0)) + lead_id = self._unified_lead_id + elif held: + gap = float(self._lead_close_hold_d) + v_lead = float(self._lead_close_hold_v) + a_lead = 0.0 if self._lead_close_hold_a is None else float(self._lead_close_hold_a) + y_rel = 0.0 if self._lead_y_rel is None else float(self._lead_y_rel) + lead_id = self._unified_lead_id if self._unified_lead_id is not None else ("hold",) + else: + gap = None + v_lead = 0.0 + a_lead = 0.0 + y_rel = 0.0 + lead_id = None + + v_lat = 0.0 + long_on = True + if live: + try: + v_lat = float(lead.vLat) + except (TypeError, ValueError, AttributeError): + v_lat = 0.0 + try: + cs = sm["carState"] + long_on = (cs.enableLongControl is True) and (cs.cruiseState.enabled is True) + except Exception: + long_on = True + map_cap = float(self._unified_v_cap_ms) + # Oct 13: a drop to an untagged state default follows down at <= 0.5 m/s². + if getattr(self, "_map_default", False) and map_cap > 0.0: + self._default_cap_ms = default_drop_cap_ms(map_cap, getattr(self, "_default_cap_ms", None), v_ego, self.dt) + map_cap = float(self._default_cap_ms) + else: + self._default_cap_ms = None + v_cap = map_cap + # True cornering (vehicle-model curvature) with the speed-dependent + # lateral target, not the steer model (which reads ~12% high at speed). + v_curve = curve_speed_for_curvature(float(self._corner_curvature)) + # Active curve-follow already covers the present curvature (its point 0); + # the reactive cap is the dead-camera fallback, used when it is not trusted. + cf_owns_curve = self._cf_mode == MODE_ACTIVE and self._cf_trusted and not self._cf_faulted + curve_cap = None + if v_curve is not None and v_ego >= 5.0 and not cf_owns_curve: + v_cap = min(v_cap, float(v_curve)) + curve_cap = float(v_curve) + # Locked meters are the setpoint, including above MAX. Map-speed + # braking back to the cap is skipped while the lock is on. A curve + # cap is passed separately so a bend still slows the car. + override = self._gap_set_override(lead, live, held) + a_map = None + if override is None and self._map_speed_mode in (MODE_CAP, MODE_FOLLOW): + a_map = map_track_decel_ms2( + v_ego, map_cap, map_brake_a_ms2(self._map_speed_lookahead), + ) + if self.curve_preview_a < PREVIEW_FREE_A_MS2: + a_map = self.curve_preview_a if a_map is None else min(float(a_map), self.curve_preview_a) + v_curve_cap = curve_cap if override is not None else None + a_max_u = float(get_max_accel(v_ego)) + if self._turn_a_max is not None: + a_max_u = min(a_max_u, float(self._turn_a_max)) + # Lead weighting: lateral offset from the model's planned path (bends + # stay on-path, adjacent lanes do not) and reading quality. + path_lat = None + model_prob = None + radar = None + if live: + try: + path_lat = path_lateral_m(lead, *model_path_xy(sm["modelV2"])) + model_prob = float(lead.modelProb) + radar = bool(lead.radar) + except Exception: + path_lat = model_prob = radar = None + existing = float(self.output_a_target) + seed = existing + command = None + if not self._unified_faulted: + try: + if gap is not None and not self._unified_following: + # First lead after the lead-free command. That command knows nothing + # of this lead (cruise or map-climb +a), so it may not accelerate + # harder than the law itself asks. A far closing lead is never + # rematched with +a. + wanted = unified_follow_desired( + gap, v_ego, v_lead, a_lead, float(self.t_follow), + v_ceiling=v_cap, a_map=a_map, y_rel=y_rel, + curvature=float(self._corner_curvature), path_lat=path_lat, + leave_w=float(self.lead_leave_w), model_prob=model_prob, radar=radar, + gap_set_override_m=override, v_curve_cap=v_curve_cap, + ) + wanted = min(wanted, a_max_u) + if wanted >= 0.0: + seed = min(existing, max(wanted, 0.0)) + else: + # The law wants a brake the lead-free command does not: start up to + # SEED_BRAKE_STEP_MS2 firmer than it (a hard close must not wait on + # the jerk-limited build-up), never past what the law itself asks. + seed = min(existing, max(wanted, min(existing, 0.0) - SEED_BRAKE_STEP_MS2)) + command = float(self._unified.step( + dt=self.dt, + present=gap is not None, + gap=0.0 if gap is None else gap, + v_ego=v_ego, + v_lead=v_lead, + a_lead=a_lead, + t_follow=float(self.t_follow), + lead_id=lead_id, + seed_a=seed, + v_ceiling=v_cap, + a_map=a_map, + y_rel=y_rel, + curvature=float(self._corner_curvature), + a_max=a_max_u, + path_lat=path_lat, + model_prob=model_prob, + radar=radar, + leave_w=float(self.lead_leave_w), + gap_set_override_m=override, + v_curve_cap=v_curve_cap, + v_lat=v_lat, + long_on=long_on, + )) + except Exception: + self._note_unified_fault() + + if self._unified_faulted or command is None: + self.unified_a_target = 0.0 + self._unified_following = False + return + self._unified_following = gap is not None + self.unified_a_target = command + if gap is None: + return + if self.fcw or self.output_should_stop or bool(sm["controlsState"].forceDecel): + command = min(command, existing) + self.output_a_target = float(command) + def publish(self, sm, pm): plan_send = messaging.new_message('longitudinalPlan') - plan_send.valid = sm.all_checks(service_list=['carState', 'controlsState', 'selfdriveState']) + plan_send.valid = sm.all_checks(service_list=['carState', 'controlsState', 'selfdriveState', 'radarState']) longitudinalPlan = plan_send.longitudinalPlan longitudinalPlan.modelMonoTime = sm.logMonoTime['modelV2'] @@ -168,14 +1075,30 @@ def publish(self, sm, pm): longitudinalPlan.accels = self.a_desired_trajectory.tolist() longitudinalPlan.jerks = self.j_desired_trajectory.tolist() - longitudinalPlan.hasLead = sm['radarState'].leadOne.status + # Chevron / HUD lead: live status, or the planner still owns a held + # in-window lead through a brief flicker. + live_lead = bool(sm['radarState'].leadOne.status) + if self._is_preap and live_lead: + live_lead = lead_approach_track_ok( + sm['radarState'].leadOne.dRel, + sm['radarState'].leadOne.modelProb, + sm['radarState'].leadOne.radar, + active=False, + ) + longitudinalPlan.hasLead = live_lead or ( + self._is_preap and self._lead_close_hold_d is not None + ) longitudinalPlan.longitudinalPlanSource = self.mpc.source longitudinalPlan.fcw = self.fcw - a_target, should_stop = get_accel_from_plan(self.CP, longitudinalPlan.speeds, longitudinalPlan.accels) - longitudinalPlan.aTarget = a_target - longitudinalPlan.shouldStop = should_stop + longitudinalPlan.aTarget = float(self.output_a_target) + longitudinalPlan.shouldStop = bool(self.output_should_stop) + longitudinalPlan.unifiedATarget = float(self.unified_a_target) longitudinalPlan.allowBrake = True - longitudinalPlan.allowThrottle = True + longitudinalPlan.allowThrottle = bool(self.allow_throttle) + longitudinalPlan.napFollowDistance = self.active_nap_follow_dist or 0 + longitudinalPlan.tFollow = self.t_follow + longitudinalPlan.gapLockM = float(self._gap_lock.gap_m or 0.0) + longitudinalPlan.gapLockEvent = int(self._gap_lock.hud) & 0xFF pm.send('longitudinalPlan', plan_send) diff --git a/selfdrive/controls/lib/model_sight.py b/selfdrive/controls/lib/model_sight.py new file mode 100644 index 00000000000000..219fe87ebe74af --- /dev/null +++ b/selfdrive/controls/lib/model_sight.py @@ -0,0 +1,74 @@ +"""How far ahead the driving model is confident about its own path. + +One place for the path-confidence reads that more than one consumer uses: + +- ``path_y_std_at``: lateral path std (m) at a time ahead. Low-visibility + steering (lat_low_visibility) reads it at 3 s for its enter/exit tests. +- ``sight_distance_m``: the distance ahead (m) at which the lateral path std + first reaches SIGHT_STD_M (2 m). The sight-distance speed cap + (sight_cap) reads it. + +Both come from modelV2.position (t, x, yStd). Pure functions, no state. +""" +from __future__ import annotations + +import math + +SIGHT_STD_M = 2.0 + + +def path_y_std_at(times, y_stds, t_query: float = 3.0) -> float | None: + """Interpolate lateral path std (m) at ``t_query`` seconds. None if unusable.""" + try: + ts = [float(t) for t in (times or [])] + ys = [float(y) for y in (y_stds or [])] + except (TypeError, ValueError): + return None + n = min(len(ts), len(ys)) + pairs = [(t, y) for t, y in zip(ts[:n], ys[:n], strict=True) if math.isfinite(t) and math.isfinite(y)] + if len(pairs) < 2: + return None + pairs.sort(key=lambda p: p[0]) + want = float(t_query) + if want <= pairs[0][0]: + return pairs[0][1] + if want >= pairs[-1][0]: + return pairs[-1][1] + for (t0, y0), (t1, y1) in zip(pairs, pairs[1:], strict=False): + if t0 <= want <= t1 and t1 > t0: + w = (want - t0) / (t1 - t0) + return y0 + w * (y1 - y0) + return None + + +def sight_distance_m(xs, y_stds, std_m: float = SIGHT_STD_M) -> float | None: + """Distance ahead (m) where the path's lateral std first reaches ``std_m``. + + Linear between the two path points that bracket it. The full path length + when it never does (confident to the horizon); 0 when the first point is + already past it. None when the arrays are unusable. + """ + try: + pts = [(float(x), float(y)) for x, y in zip(xs, y_stds, strict=False)] + except (TypeError, ValueError): + return None + pts = [(x, y) for x, y in pts if math.isfinite(x) and math.isfinite(y)] + if len(pts) < 2: + return None + if pts[0][1] >= std_m: + return 0.0 + for (x0, y0), (x1, y1) in zip(pts, pts[1:], strict=False): + if y1 >= std_m: + if y1 <= y0: + return x1 + return x0 + (std_m - y0) / (y1 - y0) * (x1 - x0) + return pts[-1][0] + + +def model_sight(model, std_m: float = SIGHT_STD_M) -> float | None: + """sight_distance_m straight from a modelV2 message.""" + try: + pos = model.position + return sight_distance_m(list(pos.x), list(pos.yStd), std_m) + except Exception: + return None diff --git a/selfdrive/controls/lib/path_obstacle.py b/selfdrive/controls/lib/path_obstacle.py new file mode 100644 index 00000000000000..3081ff03630567 --- /dev/null +++ b/selfdrive/controls/lib/path_obstacle.py @@ -0,0 +1,2380 @@ +"""Radar-triggered obstacle log, plus an animal/person chime. + +This module never brakes and never steers. A later stage can call +`future_brake_intent` (humans in or entering the path, and only when +radar and vision agree). Nothing in controlsd calls it. + +Radar scans every track. Vision runs only after a candidate has +persisted, and only on that spot. The driving model has no animal or +pedestrian head, so the checker is a luma contrast/shape heuristic on +the projected patch, not a network. + +The radar scan runs only at or above 15 mph (6.7 m/s), with a +13 mph (5.81 m/s) floor so the gate does not flap. Below that the +stage publishes an inactive lowSpeed heartbeat and the camera helper +stays asleep. + +Thresholds (device frame, y +right, path-relative lateral): + range 5–120 m ahead of the camera + in the path |lateral| <= 1.70 m + human band in the path, or within 0.9 m (3 ft) + of that corridor on either side + animal band in the path, or within 6.1 m (20 ft) + of that corridor on either side + entering reaches the path within 3.2 s + (4.5 s for a person, 5 s for a slow + walker within 1 m of the lane edge) + and is moving toward it at >= 0.55 m/s + roadside past the lane edge, inside the animal + band, and inside a 52° radar half-angle + slow along the road |ground speed| <= 3 m/s + traffic, do not chime ground speed above 5 m/s with + little lateral speed (cars and + motorcycles in the flow). Also any + radar point on a model lead (every + leadsV3 entry) or a radard lead, and + a parked-car cluster + lateral motion |v_lat| >= 0.45 m/s, or toward the path + persist 0.40 s before active; confidence + saturates near 0.80 s + agree radar >= 0.55 and vision >= 0.45, + and only while the target is within 85 m + lighting weights good light wR = 0.50, poor wR = 0.78, + linear in the lighting score + chime radar and vision agree, and 2 of the + last 3 camera looks score >= 0.60 + overall with >= 0.40 on that same class. + Humans only inside the human band. + Animals out to the animal band. Solid + debris only in the path or entering it. + Radar alone cannot call animal or human: + a camera score under 0.30 for that class + becomes an obstacle. A stationary radar + "human" outside the human band is dropped + before the camera runs. Once per track, + 9 s global cooldown + yaw v_lat = -yvRel + yaw_right * x, the same + model yaw the cone-line scan already uses + night drive-over lighting score <= 0.55 (the same exposure + and lane signals the camera helper already + folds into lighting). A stationary in-lane + return that is not a person or animal, and + is not moving across the path, chimes only + when a model or radar lead sits on it, or + the camera crop within 60 m is solid and + not a headlight or taillight blob. Anything + else is suppressed. Daytime, living things, + and crossing objects are unchanged. On any + error this rule is skipped and the chime + follows the rules above. + lively 0 still, >=0.5 has moved in the last 2 s. + Ground |along| or |vLat| above 0.4 m/s + held for 0.5 s. Range wander no longer + counts (ego approach made it 1.0, Oct 13). + Oct 13 chime policy only animal/human chime; obstacle and + unknown are log only. Hard 20 ft cap from + path centre. Human needs a camera score + and <= 3 ft from the path edge. Still + animal needs camera >= 0.75. Dark scene + + single point: no animal chime. A still + single in-path point at 40-60 m needs a + 2nd member or a solid camera hit. A + vehicle-sized crosser belongs to crossing- + vehicle handling. See chime_policy_block. + Dead-still cuts animal/person class + confidence to 0.45, not to zero. + +Road-surface pop-in (first seen inside 14 m, stationary, not spanning) +and a thin wide curtain (span >= 9 m, depth < 2.5 m) are rejected. +Cone lines, guardrails and parked cars use coneLineNAP plus the same +stationary-cluster shapes. +""" +from __future__ import annotations + +import math +import time +from dataclasses import dataclass, replace + +from openpilot.selfdrive.controls.lib.radar_path_gate import RADAR_TO_CAMERA_M, path_y_at_x + +PARAM_OBSTACLE_LOG = "NAPObstacleLog" +PARAM_OBSTACLE_CHIME = "NAPObstacleChime" + +# radard runs the scan. One iteration past this is the most a cycle may run. +BUDGET_S = 0.004 +MAX_POINTS = 48 +BREAKER_TRIPS = 3 +BREAKER_WINDOW_S = 10.0 +HEARTBEAT_S = 1.0 + +# Solids chime in the path or entering it. Living classes also chime +# on the shoulder, inside their own lateral band. + +LIVING_CLASSES = frozenset({"animal", "human"}) +PATH_CHIME_ZONES = frozenset({"inPath", "entering"}) +# Future braking. Any agreed object in or entering the path. Not wired. +# Roadside never. +BRAKE_ZONES = frozenset({"inPath", "entering"}) + +X_MIN_M = 5.0 +X_MAX_M = 120.0 +PATH_HALF_M = 1.70 +# Justin: animals ~20 ft either side of the corridor, humans ~3 ft. +HUMAN_BEYOND_M = 0.9 +ANIMAL_BEYOND_M = 6.1 +HUMAN_OUTER_M = PATH_HALF_M + HUMAN_BEYOND_M +ANIMAL_OUTER_M = PATH_HALF_M + ANIMAL_BEYOND_M +FOV_HALF_DEG = 52.0 +SLOW_ALONG_MPS = 3.0 +# Radar lateral noise on a post is below this. A real step-in is not. +ENTER_TOWARD_MPS = 0.55 +# Scan only while moving. Enable at 15 mph, drop below ~13 mph. +SPEED_ENABLE_MPS = 6.7 +SPEED_DISABLE_MPS = 5.81 +# A stopped in-path return at this speed must be closing, or it is a ghost. +HIGHWAY_MPS = 20.0 +HUMAN_ALONG_MAX_MPS = 9.0 +# With the flow of traffic: too fast to be a walker, and not darting sideways. +TRAFFIC_ALONG_MPS = 5.0 +TRAFFIC_VLAT_MPS = 1.2 +LATERAL_MOVE_MPS = 0.45 +ENTER_HORIZON_S = 3.2 +HUMAN_ENTER_HORIZON_S = 4.5 +WALKER_ENTER_HORIZON_S = 5.0 +WALKER_EDGE_M = 2.70 +PERSIST_S = 0.40 +PERSIST_FULL_S = 0.80 +RADAR_AGREE = 0.55 +VISION_AGREE = 0.45 +# Radar animal/human needs the camera to score that class at least this high. +VISION_LIVING_MIN = 0.30 +# Past this the night patch is ~20 px and the path lateral is loose. +# Radar keeps the track; the camera verdict is not used. +VISION_TRUST_M = 85.0 +# Two of the last three looks, same class. One lucky frame does not chime. +VISION_LOOK_MIN = 0.60 +VISION_CLASS_MIN = 0.40 +VISION_LOOKS = 3 +VISION_LOOKS_NEED = 2 +WR_GOOD = 0.50 +WR_POOR = 0.78 +CHIME_COOLDOWN_S = 9.0 +CHIME_HOLD_S = 0.35 +LIVELY_WINDOW_S = 2.0 +# Lively needs real ground motion above this, held this long. +LIVELY_MOVE_MPS = 0.40 +LIVELY_SUSTAIN_S = 0.50 +# Oct 13 chime policy (9 events, all false or a duplicate). +# Only animal and human chime. Obstacle/unknown are logged only. +CHIME_CLASSES = frozenset({"animal", "human"}) +# Hard cap measured from the path centre, every class: 20 ft. +CHIME_MAX_LAT_M = 6.1 +# Human: within ~3 ft of the path edge, and the camera must score it. +HUMAN_MAX_LAT_M = PATH_HALF_M + HUMAN_BEYOND_M +HUMAN_VISION_MIN = 0.40 +# A still animal chimes only on a strong camera call. +ANIMAL_STILL_VISION_MIN = 0.75 +# Dark scene: a single radar point is never an animal chime. +DARK_LIGHTING_MAX = 0.50 +# Still, single in-path point at this range is usually road surface. +SURFACE_X_MIN_M = 40.0 +SURFACE_X_MAX_M = 60.0 +SURFACE_SOLID_MIN = 0.60 +# Crossing-vehicle handling owns a vehicle-sized return sweeping across. +CROSS_OWN_VLAT_MPS = 0.89 +CROSS_OWN_ALONG_MPS = 3.0 +# Below this, a Bosch return is noise. Above the full value, the cue is 1. +SPEED_NOISE_MPS = 0.40 +SPEED_FULL_MPS = 1.40 +VLAT_NOISE_MPS = 0.30 +VLAT_FULL_MPS = 1.10 +WANDER_NOISE_M = 0.40 +WANDER_FULL_M = 1.15 +# A frozen deer keeps this fraction of its animal/person class score. +LIVELY_FLOOR = 0.45 +# Roadside chime when the track has clearly moved, even if class is unknown. +LIVELY_CHIME = 0.50 +CLUSTER_DX_M = 5.5 +CLUSTER_DY_M = 3.2 +LANE_SPAN_M = 1.8 +OVERHEAD_SPAN_M = 9.0 +OVERHEAD_DEPTH_M = 2.5 +POPIN_X_M = 14.0 +LEAD_X_M = 4.5 +LEAD_Y_M = 1.6 +LEAD_PROB = 0.40 +# Night is the logged lighting band (about 0.40–0.43 on the Oct 7 drive). +# Daytime scores sit near 1. Missing or non-finite lighting is not night. +NIGHT_LIGHTING_MAX = 0.55 +# Low-beam range. Farther than this, a stationary in-lane return at night +# needs a model lead; the crop is too small to call solid. +DRIVE_OVER_SOLID_M = 60.0 +# Lead agreement for that night exception. Wider in range than the +# exclusion box, same lateral tolerance, and a higher probability. +DRIVE_OVER_LEAD_PROB = 0.50 +DRIVE_OVER_LEAD_X_M = 5.0 +DRIVE_OVER_LEAD_X_FRAC = 0.15 +DRIVE_OVER_LEAD_Y_M = LEAD_Y_M +# Crop light test. Y is 0..255. Red is either an RGB pixel or a high NV12 V. +NEAR_SAT_Y = 200.0 +SAT_Y = 235.0 +LIGHT_FRAC_REJECT = 0.12 +SAT_FRAC_REJECT = 0.05 +RED_FRAC_REJECT = 0.06 +BLOB_SHARE_REJECT = 0.55 +RED_V_MIN = 165.0 +RED_Y_MIN = 160.0 + +CLASS_ORDER = ("unknown", "human", "animal", "obstacle") +ZONE_ORDER = ("none", "inPath", "entering", "roadside") + + +class _OverBudget(Exception): + """Raised inside the scan when the per-cycle deadline has passed.""" + + +def _check_deadline(deadline: float | None) -> None: + if deadline is not None and time.monotonic() > deadline: + raise _OverBudget + + +def _enum_name(raw, order: tuple[str, ...]) -> str: + name = _class_name(raw) + if name.isdigit(): + idx = int(name) + return order[idx] if 0 <= idx < len(order) else order[0] + return name if name in order else order[0] + + +def _clamp(value: float, lo: float, hi: float) -> float: + return lo if value < lo else hi if value > hi else value + + +def _nan() -> float: + return float("nan") + + +def _finite(value) -> float | None: + try: + out = float(value) + except (TypeError, ValueError): + return None + if not math.isfinite(out): + return None + return out + + +def _toward(lat: float, v_lat: float) -> float: + """Speed toward the path center, m/s. Already-in-path uses |v_lat|.""" + if abs(lat) < 0.25: + return abs(v_lat) + return max(0.0, -math.copysign(1.0, lat) * v_lat) + + +@dataclass(frozen=True) +class VisionScore: + """Patch verdict. conf is 'something solid above the road', 0..1. + + light_dominated is the night drive-over veto: a large share of the crop + is saturated, or a red taillight pattern, or a clipped blob owns the + contrast. It does not change the conf used in daytime. + """ + + conf: float = 0.0 + human: float = 0.0 + animal: float = 0.0 + obstacle: float = 0.0 + evaluated: bool = True + light_dominated: bool = False + light_frac: float = 0.0 + red_frac: float = 0.0 + + +@dataclass(frozen=True) +class ConeHint: + """The bits of coneLineNAP this scan needs. Tests build it directly.""" + + active: bool = False + side: int = 0 + lat_near: float = 0.0 + lat_mid: float = 0.0 + lat_far: float = 0.0 + barrier: bool = False + parked: bool = False + + +@dataclass(frozen=True) +class BrakeIntent: + """Not consumed by any controller. decel is always 0 in this stage.""" + + allowed: bool + reason: str + decel: float = 0.0 + + +@dataclass(frozen=True) +class ObstacleSample: + active: bool = False + track_id: int = 0 + range_m: float = 0.0 + lateral: float = 0.0 + v_rel: float = 0.0 + v_lat: float = 0.0 + radar_conf: float = 0.0 + vision_conf: float = _nan() + vision_evaluated: bool = False + lighting_score: float = 1.0 + w_radar: float = WR_GOOD + w_vision: float = 1.0 - WR_GOOD + fused_score: float = 0.0 + agree: bool = False + reject_reason: str = "no_candidate" + in_path: bool = False + time_to_reach: float = _nan() + object_class: str = "unknown" + vision_conf_human: float = _nan() + vision_conf_animal: float = _nan() + vision_conf_obstacle: float = _nan() + cluster_count: int = 0 + span_m: float = 0.0 + time_to_enter: float = _nan() + entering: bool = False + zone: str = "none" + brake_gate: bool = False + chimed: bool = False + chime_reason: str = "no_candidate" + lively_score: float = 0.0 + scan_us: float = 0.0 + vision_us: float = 0.0 + member_ids: tuple[int, ...] = () + vision_fail_reason: str = "" + # Empty, or why the night drive-over rule suppressed this chime: + # light, no_solid, beyond_60. + drive_over_reason: str = "" + + def with_chime(self, chimed: bool, reason: str) -> ObstacleSample: + return replace(self, chimed=bool(chimed), chime_reason=str(reason)) + + +@dataclass(frozen=True) +class _Hit: + """One radar candidate after the scan, before vision and the chime.""" + + active: bool + track_id: int + member_ids: tuple[int, ...] + x: float + y: float + lateral: float + v_rel: float + v_lat: float + along: float + radar_conf: float + radar_class: str + zone: str + time_to_reach: float + time_to_enter: float + cluster_count: int + span_m: float + reject_reason: str + lighting: float + lively: float = 0.0 + v_ego: float = 0.0 + # Stationary in-lane return that a model or radar lead agrees with. + # Kept through the scan so the night rule can chime. Daytime still + # excludes it as a vehicle. + model_lead: bool = False + + +def project_road_point(x: float, y: float, z: float, *, + roll: float = 0.0, pitch: float = 0.0, yaw: float = 0.0, + height: float = 1.22, focal: float = 1141.5, + cx: float = 672.0, cy: float = 380.0) -> tuple[float, float] | None: + """Project a road-frame point (x forward, y left, z up) to pixels. + + Matches `get_view_frame_from_road_frame`: device y is right, z is down, + then the view frame is x right, y down, z forward. Returns None when + the point is behind the camera. + """ + try: + x, y, z = float(x), float(y), float(z) + roll, pitch, yaw = float(roll), float(pitch), float(yaw) + height, focal = float(height), float(focal) + cx, cy = float(cx), float(cy) + except (TypeError, ValueError): + return None + if not all(math.isfinite(v) for v in (x, y, z, roll, pitch, yaw, height, focal, cx, cy)): + return None + if focal <= 1.0: + return None + cr, sr = math.cos(roll), math.sin(roll) + cp, sp = math.cos(pitch), math.sin(pitch) + cyaw, syaw = math.cos(yaw), math.sin(yaw) + # R = Rz @ Ry @ Rx, then diag(1, -1, -1) on the road point. + rx, ry, rz = x, -y, -z + # Rx + ry, rz = cr * ry - sr * rz, sr * ry + cr * rz + # Ry + rx, rz = cp * rx + sp * rz, -sp * rx + cp * rz + # Rz + rx, ry = cyaw * rx - syaw * ry, syaw * rx + cyaw * ry + # view = (y_right, z_down, x_forward) + (0, height, 0) + vx, vy, vz = ry, rz + height, rx + if vz <= 0.5: + return None + return cx + focal * (vx / vz), cy + focal * (vy / vz) + + +def projection_box(u: float, v_top: float, v_ground: float, focal: float, x: float, + half_m: float = 0.55) -> tuple[float, float, float, float]: + """Pixel box (u0, v0, u1, v1) around the above-road segment.""" + half = focal * half_m / max(float(x), 1.0) + half = _clamp(half, 3.0, 180.0) + top, bot = (v_top, v_ground) if v_top <= v_ground else (v_ground, v_top) + if bot - top < 4.0: + bot = top + 4.0 + return u - half, top, u + half, bot + + +def fusion_weights(lighting: float) -> tuple[float, float]: + """Good light shares the vote. Poor light leans on radar. Linear, no step.""" + score = _clamp(lighting if math.isfinite(lighting) else 1.0, 0.0, 1.0) + w_radar = WR_POOR + (WR_GOOD - WR_POOR) * score + return w_radar, 1.0 - w_radar + + +def fuse_scores(radar_conf: float, vision_conf: float | None, lighting: float) -> tuple[float, float, float, bool]: + """Return fused, w_radar, w_vision, agree. + + Vision NaN does not vote. The fused score is then the radar score, and + agree stays false because the camera has not confirmed the spot. + """ + w_r, w_v = fusion_weights(lighting) + radar = _clamp(radar_conf if math.isfinite(radar_conf) else 0.0, 0.0, 1.0) + if vision_conf is None or not math.isfinite(vision_conf): + return radar, w_r, w_v, False + vision = _clamp(vision_conf, 0.0, 1.0) + fused = _clamp(w_r * radar + w_v * vision, 0.0, 1.0) + agree = radar >= RADAR_AGREE and vision >= VISION_AGREE + return fused, w_r, w_v, agree + + +def lighting_score(*, lane_left: float = 1.0, lane_right: float = 1.0, + path_y_std: float | None = None, integ_lines: float | None = None, + gain: float | None = None, grey: float | None = None, + sun_ahead: bool = False, headlights: bool = False) -> float: + """0 is a camera that cannot see, 1 is a bright clear frame. Continuous.""" + left = _finite(lane_left) + right = _finite(lane_right) + lane = _clamp(min(left if left is not None else 1.0, right if right is not None else 1.0), 0.0, 1.0) + if path_y_std is None or not math.isfinite(path_y_std): + path = 0.75 + else: + path = _clamp(1.0 - (path_y_std - 0.4) / 2.6, 0.0, 1.0) + exposure = 1.0 + if gain is not None and math.isfinite(gain) and gain > 0.0: + exposure *= _clamp(1.2 - gain / 5.5, 0.1, 1.0) + if integ_lines is not None and math.isfinite(integ_lines) and integ_lines > 0.0: + exposure *= _clamp(1.35 - integ_lines / 2800.0, 0.15, 1.0) + if grey is not None and math.isfinite(grey): + if grey < 0.04 or grey > 0.55: + exposure *= 0.50 + elif grey < 0.08 or grey > 0.40: + exposure *= 0.75 + if sun_ahead: + exposure *= 0.55 + if headlights: + exposure *= 0.62 + model = 0.55 * lane + 0.45 * path + return _clamp(0.42 * model + 0.58 * exposure, 0.0, 1.0) + + +def is_night_lighting(lighting: float) -> bool: + """True when the existing lighting score is the night band. + + Non-finite or missing scores are daytime, so a broken exposure reading + keeps the previous chime rules. + """ + try: + score = float(lighting) + except (TypeError, ValueError): + return False + return math.isfinite(score) and score <= NIGHT_LIGHTING_MAX + + +def _row_lists(value) -> list[list]: + """Rows from a list of lists or a numpy image. Empty when there is nothing to read.""" + if value is None: + return [] + try: + iterator = iter(value) + except TypeError: + return [] + rows = [] + for row in iterator: + try: + if len(row) == 0: + continue + rows.append(list(row)) + except TypeError: + continue + return rows + + +def _mean_std(vals: list[float]) -> tuple[float, float]: + n = len(vals) + if n == 0: + return 0.0, 0.0 + mean = sum(vals) / n + var = sum((v - mean) ** 2 for v in vals) / n + return mean, math.sqrt(var) + + +def _np_plane(value): + """2D numeric numpy array, or None (then the list path runs).""" + try: + import numpy as np + except Exception: + return None + if not isinstance(value, np.ndarray) or value.ndim != 2 or value.dtype.kind not in "uifb": + return None + if value.shape[0] == 0 or value.shape[1] == 0: + return None + return value + + +def _metrics_np(obj, road) -> dict: + """Vectorized metrics_from_rows. Same sampling, bins and fallbacks.""" + import numpy as np + height, width = obj.shape + cells = height * width + step = 1 + while cells / (step * step) > 2400 and step < 8: + step += 1 + samp = obj[::step, :width:step].astype(np.float64) + vals = samp.ravel() + mean = float(vals.mean()) + std = float(np.sqrt(((vals - mean) ** 2).mean())) + ys = np.arange(samp.shape[0]) * step + band_of = np.where(ys < height / 3, 0, np.where(ys < 2 * height / 3, 1, 2)) + xs = np.arange(samp.shape[1]) + col_of = np.where(xs < width / 3, 0, np.where(xs < 2 * width / 3, 1, 2)) + cols = [] + for c in range(3): + sel = samp[:, col_of == c] + cols.append(float(sel.mean()) if sel.size else mean) + band_means = [] + for b in range(3): + sel = samp[band_of == b, :] + band_means.append(float(sel.mean()) if sel.size else None) + bands = [m if m is not None else mean for m in band_means] + road_mean = None + if road is not None: + rs = road[::step, :width:step].astype(np.float64).ravel() + rs = rs[np.isfinite(rs)] + if rs.size: + road_mean = float(rs.mean()) + if road_mean is None: + road_mean = (band_means[2] if band_means[2] is not None else 0.0) or mean + return {"mean": mean, "std": std, "cols": cols, "bands": bands, "road": road_mean} + + +def metrics_from_rows(obj_rows, road_rows=None) -> dict: + """Mean/std plus 3 column and 3 row means. Caps the sample count.""" + obj_np = _np_plane(obj_rows) + if obj_np is not None and (road_rows is None or _np_plane(road_rows) is not None) and \ + (obj_np.dtype.kind != "f" or bool(__import__("numpy").isfinite(obj_np).all())): + return _metrics_np(obj_np, _np_plane(road_rows) if road_rows is not None else None) + rows = _row_lists(obj_rows) + if not rows: + return {"mean": 0.0, "std": 0.0, "cols": [0.0, 0.0, 0.0], "bands": [0.0, 0.0, 0.0], "road": 0.0} + height = len(rows) + width = min(len(r) for r in rows) + cells = height * width + step = 1 + while cells / (step * step) > 2400 and step < 8: + step += 1 + vals: list[float] = [] + cols = [[], [], []] + bands = [[], [], []] + for yi, row in enumerate(rows[::step]): + y_full = yi * step + band = 0 if y_full < height / 3 else 1 if y_full < 2 * height / 3 else 2 + for x_full, value in enumerate(row[:width:step]): + try: + pix = float(value) + except (TypeError, ValueError): + continue + vals.append(pix) + col = 0 if x_full < width / 3 else 1 if x_full < 2 * width / 3 else 2 + cols[col].append(pix) + bands[band].append(pix) + mean, std = _mean_std(vals) + road_vals: list[float] = [] + for row in _row_lists(road_rows)[::step]: + for value in list(row)[:width:step]: + num = _finite(value) + if num is not None: + road_vals.append(num) + road = _mean_std(road_vals)[0] if road_vals else (bands[2] and _mean_std(bands[2])[0]) or mean + return { + "mean": mean, + "std": std, + "cols": [_mean_std(c)[0] if c else mean for c in cols], + "bands": [_mean_std(b)[0] if b else mean for b in bands], + "road": road, + } + + +def vision_from_regions(obj_mean: float, obj_std: float, road_mean: float, + cols: list[float], bands: list[float]) -> VisionScore: + """Turn patch stats into a solid-above-road score and weak class scores. + + The class split is a shape prior (tall vs mid vs wide vs a thin post). + It is not a trained detector. A raccoon-sized target often never clears + the solid-object bar. + """ + contrast = abs(obj_mean - road_mean) + if contrast < 8.0 and obj_std < 12.0: + solid = 0.08 + else: + solid = _clamp(contrast / 42.0, 0.0, 1.0) * 0.75 + _clamp(obj_std / 28.0, 0.0, 1.0) * 0.25 + c0, c1, c2 = (cols + [obj_mean, obj_mean, obj_mean])[:3] + b0, b1, b2 = (bands + [obj_mean, obj_mean, obj_mean])[:3] + side = 0.5 * (c0 + c2) + center_delta = abs(c1 - side) + needle = center_delta > 14.0 and center_delta > abs(c0 - c2) + 8.0 + wide = abs(c0 - road_mean) > 12.0 and abs(c2 - road_mean) > 12.0 and abs(c1 - road_mean) > 12.0 + top_c, mid_c, bot_c = abs(b0 - road_mean), abs(b1 - road_mean), abs(b2 - road_mean) + tall = top_c > 12.0 and mid_c > 10.0 + low_only = bot_c > 12.0 and top_c < 8.0 and mid_c < 10.0 + mid_body = mid_c > 12.0 and top_c < mid_c * 0.75 + # A thin post (delineator, mailbox) is not a person or an animal. + human = solid * (0.85 if tall and not wide and not needle else 0.20 if tall and not needle else 0.05) + animal = solid * (0.80 if mid_body and not needle and not wide else 0.22 if mid_body and not needle else 0.08) + obstacle = solid * (0.85 if wide or low_only or needle else 0.35) + human = _clamp(human, 0.0, solid if solid > 0 else 1.0) + animal = _clamp(animal, 0.0, 1.0) + obstacle = _clamp(obstacle, 0.0, 1.0) + return VisionScore(conf=_clamp(solid, 0.0, 1.0), human=human, animal=animal, obstacle=obstacle, evaluated=True) + + +def _as_rgb(value): + """(r, g, b) when the pixel is a color triple. None for a luma sample.""" + if isinstance(value, (bytes, str)) or isinstance(value, (int, float)): + return None + try: + seq = value.tolist() if hasattr(value, "tolist") else value + if isinstance(seq, (int, float)): + return None + seq = list(seq) + except TypeError: + return None + if len(seq) < 3: + return None + r, g, b = _finite(seq[0]), _finite(seq[1]), _finite(seq[2]) + if r is None or g is None or b is None: + return None + return r, g, b + + +def _luma_of(value) -> tuple[float, bool] | None: + """(luma 0..255, red-saturated?). None when the sample is not a pixel.""" + color = _as_rgb(value) + if color is not None: + r, g, b = color + luma = 0.299 * r + 0.587 * g + 0.114 * b + # Saturated red, not a white headlight. Luma can stay moderate when + # G and B are near zero; the NV12 path catches the same pixels via V. + red = r >= 200.0 and r >= g + 40.0 and r >= b + 40.0 + return luma, red + luma = _finite(value) + if luma is None: + return None + return luma, False + + +def _light_stats_np(obj, v_plane) -> tuple[float, float, float, float]: + """Vectorized crop_light_stats for a 2D luma crop. Same sampling and V lookup.""" + import numpy as np + height, width = obj.shape + if width < 2 or height < 2: + return 0.0, 0.0, 0.0, 0.0 + step = 1 + cells = height * width + while cells / (step * step) > 2000 and step < 8: + step += 1 + samp = obj[::step, :width:step].astype(np.float64) + red = np.zeros(samp.shape, dtype=bool) + if v_plane is not None: + nv_rows, nv_cols = v_plane.shape + fy = (np.arange(samp.shape[0]) * step) / max(height - 1, 1) + vy = np.minimum(nv_rows - 1, (fy * nv_rows).astype(np.int64)) + fx = (np.arange(samp.shape[1]) * step) / max(width - 1, 1) + vx = np.minimum(nv_cols - 1, (fx * nv_cols).astype(np.int64)) + v_vals = v_plane.astype(np.float64)[vy[:, None], vx[None, :]] + red = (samp >= RED_Y_MIN) & np.isfinite(v_vals) & (v_vals >= RED_V_MIN) + finite = np.isfinite(samp) + lumas = samp[finite] + n = int(lumas.size) + if n == 0: + return 0.0, 0.0, 0.0, 0.0 + near = float(np.count_nonzero(lumas >= NEAR_SAT_Y)) / n + sat = float(np.count_nonzero(lumas >= SAT_Y)) / n + red_frac = float(np.count_nonzero(red[finite])) / n + median = float(np.partition(lumas, n // 2)[n // 2]) + excess = np.maximum(0.0, lumas - median) + total = float(excess.sum()) + if total <= 1.0: + blob = 0.0 + else: + blob = float(excess[lumas >= NEAR_SAT_Y].sum()) / total + return near, sat, red_frac, blob + + +def crop_light_stats(obj_rows, v_rows=None) -> tuple[float, float, float, float]: + """(near_sat_frac, sat_frac, red_frac, blob_share) for one crop. + + near_sat is luma >= 200, sat is luma >= 235. red is an RGB taillight + pixel or, when v_rows is the NV12 V crop, a bright pixel with high V. + blob_share is how much of the contrast above the median sits in the + clipped pixels. Empty crops return zeros. Any bad pixel is skipped. + A 2D numpy luma crop (the on-device case) takes the vectorized path. + """ + obj_np = _np_plane(obj_rows) + if obj_np is not None and (v_rows is None or _np_plane(v_rows) is not None): + return _light_stats_np(obj_np, _np_plane(v_rows) if v_rows is not None else None) + rows = _row_lists(obj_rows) + if not rows: + return 0.0, 0.0, 0.0, 0.0 + height = len(rows) + width = min(len(row) for row in rows) + if width < 2 or height < 2: + return 0.0, 0.0, 0.0, 0.0 + step = 1 + cells = height * width + while cells / (step * step) > 2000 and step < 8: + step += 1 + vdata = _row_lists(v_rows) if v_rows is not None else [] + lumas: list[float] = [] + reds = 0 + for yi, row in enumerate(rows[::step]): + y_full = yi * step + fy = y_full / max(height - 1, 1) + for xi, value in enumerate(row[:width:step]): + parsed = _luma_of(value) + if parsed is None: + continue + luma, red = parsed + if vdata: + vy = min(len(vdata) - 1, int(fy * len(vdata))) + vrow = vdata[vy] + if vrow: + fx = (xi * step) / max(width - 1, 1) + vx = min(len(vrow) - 1, int(fx * len(vrow))) + v_val = _finite(vrow[vx]) + if v_val is not None and luma >= RED_Y_MIN and v_val >= RED_V_MIN: + red = True + lumas.append(luma) + if red: + reds += 1 + n = len(lumas) + if n == 0: + return 0.0, 0.0, 0.0, 0.0 + near = sum(1 for v in lumas if v >= NEAR_SAT_Y) / n + sat = sum(1 for v in lumas if v >= SAT_Y) / n + red_frac = reds / n + ordered = sorted(lumas) + median = ordered[n // 2] + excess = [max(0.0, v - median) for v in lumas] + total = sum(excess) + if total <= 1.0: + blob = 0.0 + else: + bright = sum(ex for v, ex in zip(lumas, excess) if v >= NEAR_SAT_Y) + blob = bright / total + return near, sat, red_frac, blob + + +def light_dominated(near: float, sat: float, red: float, blob: float) -> bool: + """True when a headlight or taillight blob owns the crop.""" + if near >= LIGHT_FRAC_REJECT or sat >= SAT_FRAC_REJECT or red >= RED_FRAC_REJECT: + return True + return blob >= BLOB_SHARE_REJECT and sat >= 0.015 + + +def score_row_patches(obj_rows, road_rows, v_rows=None) -> VisionScore: + stats = metrics_from_rows(obj_rows, road_rows) + score = vision_from_regions(stats["mean"], stats["std"], stats["road"], stats["cols"], stats["bands"]) + try: + near, sat, red, blob = crop_light_stats(obj_rows, v_rows) + dominated = light_dominated(near, sat, red, blob) + except Exception: + near, red, dominated = 0.0, 0.0, False + return replace(score, light_dominated=dominated, light_frac=near, red_frac=red) + + +def _class_name(raw) -> str: + return str(raw).split(".")[-1] + + +def should_raise_chime(chimed, object_class=None, enabled: bool = True) -> bool: + """selfdrived uses this. The detector already chose whether to chime.""" + del object_class + if not enabled or not chimed: + return False + return True + + +def chime_banner(object_class, zone) -> str: + """One line for the driver. Class stays in the log, not on screen.""" + del object_class + zone_name = _class_name(zone) + if zone_name.isdigit(): + idx = int(zone_name) + zone_name = ZONE_ORDER[idx] if 0 <= idx < len(ZONE_ORDER) else "none" + if zone_name == "roadside": + return "Object near road" + return "Object ahead" + + +def _beyond_corridor(lat: float) -> float: + return max(0.0, abs(float(lat)) - PATH_HALF_M) + + +def _class_zone_block(sample: ObstacleSample) -> str | None: + """Why this sample must not chime. None means the class is inside its zone. + + Humans count in the path and within 0.9 m of it. Animals count out to + 6.1 m. Solid debris counts only in the path or entering it. + """ + beyond = _beyond_corridor(sample.lateral) + cls = sample.object_class + if cls == "human" and sample.zone != "inPath" and beyond > HUMAN_BEYOND_M: + return "off_zone" + if cls == "animal" and sample.zone != "inPath" and beyond > ANIMAL_BEYOND_M: + return "off_zone" + if cls in LIVING_CLASSES: + if sample.zone in PATH_CHIME_ZONES or sample.zone == "roadside": + return None + return "zone" + if sample.zone in PATH_CHIME_ZONES: + return None + if sample.zone == "roadside": + return "inanimate" + return "zone" + + +def _highway_still_unconfirmed(sample: ObstacleSample, v_ego: float) -> bool: + """Stopped in the lane at highway speed, and vision did not name it. + + A weak solid score with class unknown is not agreement. A deer or a + piece of debris that vision actually classifies still can chime. + """ + try: + speed = float(v_ego) + except (TypeError, ValueError): + return False + if not math.isfinite(speed) or speed < HIGHWAY_MPS: + return False + if sample.zone != "inPath": + return False + if float(sample.lively_score) >= 0.35: + return False + if not sample.vision_evaluated: + return True + return sample.object_class not in ("human", "animal", "obstacle") + + +def chime_policy_block(sample: ObstacleSample, hit: _Hit, vision: VisionScore | None) -> str | None: + """Oct 13 chime policy. A reason string blocks the chime (log only). + + vision is the raw camera score when it was trusted this cycle, else None. + """ + cls = sample.object_class + if cls not in CHIME_CLASSES: + return "log_only_class" + lat = abs(float(sample.lateral)) + if not math.isfinite(lat) or lat > CHIME_MAX_LAT_M: + return "beyond_20ft" + along = abs(float(hit.along)) if math.isfinite(float(hit.along)) else 0.0 + v_lat = abs(float(hit.v_lat)) if math.isfinite(float(hit.v_lat)) else 0.0 + vehicle_sized = hit.cluster_count >= 2 or hit.span_m >= 1.0 or hit.model_lead or hit.radar_class == "obstacle" + if v_lat >= CROSS_OWN_VLAT_MPS and along < CROSS_OWN_ALONG_MPS and vehicle_sized: + return "crossing_vehicle" + evaluated = vision is not None and bool(vision.evaluated) + if cls == "human": + if not evaluated or not math.isfinite(vision.human) or vision.human < HUMAN_VISION_MIN: + return "human_no_camera" + if lat > HUMAN_MAX_LAT_M: + return "human_off_3ft" + single = hit.cluster_count < 2 + if cls == "animal": + strong = evaluated and math.isfinite(vision.animal) and vision.animal >= ANIMAL_STILL_VISION_MIN + lively = float(sample.lively_score) if math.isfinite(float(sample.lively_score)) else 0.0 + if lively < LIVELY_CHIME and not strong: + return "still_animal" + light = float(sample.lighting_score) + if single and math.isfinite(light) and light < DARK_LIGHTING_MAX: + return "dark_single_point" + if sample.zone == "inPath" and single and along < LIVELY_MOVE_MPS and \ + SURFACE_X_MIN_M <= float(hit.x) <= SURFACE_X_MAX_M: + solid = evaluated and math.isfinite(vision.conf) and vision.conf >= SURFACE_SOLID_MIN \ + and not bool(getattr(vision, "light_dominated", False)) + if not solid: + return "road_surface_single" + return None + + +def future_brake_intent(sample: ObstacleSample) -> BrakeIntent | None: + """Any agreed object in or entering the path. Roadside never. + + Not consumed by any controller. decel stays 0. + """ + if not sample.agree or sample.zone not in BRAKE_ZONES: + return None + return BrakeIntent(True, "agree_in_path", 0.0) + + +class ChimeGate: + """Once per track id, plus a global gap. Every class shares it.""" + + def __init__(self, cooldown_s: float = CHIME_COOLDOWN_S, hold_s: float = CHIME_HOLD_S): + self.cooldown_s = float(cooldown_s) + self.hold_s = float(hold_s) + self._ids: set[int] = set() + self._last = -1e9 + self._hold_until = -1e9 + self._hold_ids: set[int] = set() + + def reset(self) -> None: + self._ids.clear() + self._last = -1e9 + self._hold_until = -1e9 + self._hold_ids.clear() + + def consider(self, sample: ObstacleSample, enabled: bool, now: float) -> tuple[bool, str]: + ids = set(sample.member_ids) or ({sample.track_id} if sample.track_id else set()) + if not enabled: + return False, "disabled" + if ids and ids & self._hold_ids and now <= self._hold_until: + return True, "chimed" + if not sample.active: + if sample.reject_reason == "not_persistent": + return False, "not_persistent" + return False, sample.reject_reason or "no_candidate" + blocked = _class_zone_block(sample) + if blocked is not None: + return False, blocked + if not sample.agree: + return False, "no_agree" + if ids and ids & self._ids: + return False, "already_tracked" + if now - self._last < self.cooldown_s: + return False, "cooldown" + self._ids.update(ids) + if len(self._ids) > 64: + self._ids = set(list(self._ids)[-64:]) + self._last = now + self._hold_until = now + self.hold_s + self._hold_ids = set(ids) + return True, "chimed" + + +def _point(raw) -> dict | None: + if isinstance(raw, dict): + src = raw + get = src.get + else: + def get(name, default=None): + return getattr(raw, name, default) + d_rel = _finite(get("dRel", get("d_rel"))) + y_rel = _finite(get("yRel", get("y_rel"))) + v_rel = _finite(get("vRel", get("v_rel"))) + if d_rel is None or y_rel is None or v_rel is None: + return None + if not bool(get("measured", True)): + return None + track = get("trackId", get("track_id", 0)) + try: + track_id = int(track) + except (TypeError, ValueError): + track_id = 0 + yv = _finite(get("yvRel", get("yv_rel"))) + rcs = _finite(get("rcs", get("rcsDb", get("amplitude")))) + return { + "id": track_id, + "x": d_rel + RADAR_TO_CAMERA_M, + "y": -y_rel, + "v_rel": v_rel, + "yv_rel": yv, + "rcs": rcs, + } + + +def _iter_items(value): + if value is None: + return + try: + iterator = iter(value) + except TypeError: + return + yield from iterator + + +def _field(obj, *names): + if isinstance(obj, dict): + for name in names: + if name in obj: + return obj[name] + return None + for name in names: + try: + return getattr(obj, name) + except Exception: + continue + return None + + +def _xy_prob(item, xy_name: str | None = None): + """Device-frame (x, y, prob) from a model lead, or None.""" + if isinstance(item, (tuple, list)): + if len(item) < 3: + return None + x, y, prob = _finite(item[0]), _finite(item[1]), _finite(item[2]) + if x is None or y is None or prob is None or prob < LEAD_PROB: + return None + if len(item) > 3: + try: + return x, y, prob, int(item[3]) + except (TypeError, ValueError): + return x, y, prob + return x, y, prob + prob = _finite(_field(item, "prob")) + if prob is None or prob < LEAD_PROB: + return None + if xy_name: + xyva = _field(item, xy_name) + try: + x, y = _finite(xyva[0]), _finite(xyva[1]) + except Exception: + return None + else: + raw_x, raw_y = _field(item, "x"), _field(item, "y") + try: + x = _finite(raw_x if isinstance(raw_x, (int, float)) else raw_x[0]) + y = _finite(raw_y if isinstance(raw_y, (int, float)) else raw_y[0]) + except Exception: + return None + if x is None or y is None: + return None + return x, y, prob + + +def vehicle_exclusion_points(leads_v3=(), leads_v2=(), radar_leads=()): + """Every tracked vehicle the chime must not treat as an obstacle. + + Model leadsV3 (lead0, lead1, and any further entries) and legacy + leads V2 are device-frame points. A radard lead (leadOne and leadTwo) + is included when status is set: its track id, and its position with + y flipped from left-positive yRel to device +right. Prob under 0.40 + is ignored for the model. A selected radar lead is kept even if + modelProb is low. + + Returns (track_ids, points). Points are (x, y, prob) or + (x, y, prob, track_id). + """ + ids: list[int] = [] + points: list[tuple] = [] + for item in _iter_items(leads_v3): + parsed = _xy_prob(item) + if parsed is not None: + points.append(parsed) + for item in _iter_items(leads_v2): + parsed = _xy_prob(item, "xyva") if not isinstance(item, (tuple, list)) else _xy_prob(item) + if parsed is not None: + points.append(parsed) + for lead in _iter_items(radar_leads): + if lead is None or not bool(_field(lead, "status")): + continue + d_rel = _finite(_field(lead, "dRel", "d_rel")) + y_rel = _finite(_field(lead, "yRel", "y_rel")) + if d_rel is None or y_rel is None: + continue + prob = _finite(_field(lead, "modelProb", "prob")) + if prob is None or prob < LEAD_PROB: + prob = 1.0 + track = _field(lead, "radarTrackId", "radar_track_id") + try: + track_id = int(track) if track is not None else -1 + except (TypeError, ValueError): + track_id = -1 + x = d_rel + RADAR_TO_CAMERA_M + y = -y_rel + if track_id >= 0: + ids.append(track_id) + points.append((x, y, prob, track_id)) + else: + points.append((x, y, prob)) + return ids, points + + +def _line_lat(cone: ConeHint, x: float) -> float | None: + pts = ((15.0, cone.lat_near), (30.0, cone.lat_mid), (45.0, cone.lat_far)) + if x <= pts[0][0]: + return pts[0][1] + if x >= pts[-1][0]: + return pts[-1][1] + for (x0, y0), (x1, y1) in zip(pts, pts[1:]): + if x0 <= x <= x1 and x1 > x0: + t = (x - x0) / (x1 - x0) + return y0 + t * (y1 - y0) + return pts[-1][1] + + +def _cone_reject(lat: float, x: float, cone: ConeHint | None) -> str | None: + if cone is None: + return None + line = _line_lat(cone, x) + if cone.barrier and line is not None and abs(lat - line) < 1.15: + return "barrier" + # lat is +right. cone.side is the real side: +1 left, -1 right, + # so a left line has negative lat. side +1 agrees with lat < 0. + same_side = cone.side == 0 or (lat > 0.0) == (cone.side < 0) or abs(lat) < 0.4 + if cone.active and line is not None and abs(lat - line) < 0.80 and same_side: + return "cone_line" + if cone.parked and 1.5 < abs(lat) < 4.5: + return "exclVehicle" + return None + + +def _humanish(lat: float, v_lat: float, along: float, toward: float) -> bool: + if 0.30 <= toward <= 3.4 and abs(along) < 4.0: + return True + if PATH_HALF_M < abs(lat) <= WALKER_EDGE_M and abs(along) < 2.2 and toward >= 0.15: + return True + if abs(lat) <= PATH_HALF_M + 0.3 and 2.0 < along <= HUMAN_ALONG_MAX_MPS and abs(v_lat) < 2.0: + return True + return False + + +def _zone_of(lat: float, v_lat: float, along: float) -> tuple[str, float]: + if abs(lat) <= PATH_HALF_M: + return "inPath", 0.0 + toward = _toward(lat, v_lat) + dist = abs(lat) - PATH_HALF_M + t_enter = dist / toward if toward >= ENTER_TOWARD_MPS else float("inf") + horizon = HUMAN_ENTER_HORIZON_S if _humanish(lat, v_lat, along, toward) else ENTER_HORIZON_S + if _humanish(lat, v_lat, along, toward) and PATH_HALF_M < abs(lat) <= WALKER_EDGE_M and toward >= 0.15: + horizon = max(horizon, WALKER_ENTER_HORIZON_S) + if math.isfinite(t_enter) and t_enter <= horizon: + return "entering", t_enter + if PATH_HALF_M < abs(lat) <= ANIMAL_OUTER_M: + return "roadside", t_enter if math.isfinite(t_enter) else _nan() + return "none", _nan() + + +def _fov_ok(x: float, lat: float) -> bool: + return math.degrees(math.atan2(abs(lat), max(x, 0.5))) <= FOV_HALF_DEG + + +def _closing_time(x: float, v_rel: float) -> float: + closing = -v_rel + if closing <= 0.4: + return _nan() + return x / closing + + +def _ramp(value: float, noise: float, full: float) -> float: + span = full - noise + if span <= 1e-6: + return 0.0 + return _clamp((abs(value) - noise) / span, 0.0, 1.0) + + +def lively_from_history(hist) -> float: + """Real ground motion in the last ~2 s. 0 is still. + + Oct 13: every still sign, post and hydrant read 1.0 because the old + version also counted range wander, and range changes by ego speed as + we drive at a parked object. Only ground-frame speed counts now + (|along| or |vLat|), above ~0.4 m/s, sustained for at least 0.5 s. + """ + if not hist: + return 0.0 + now = float(hist[-1][0]) + window = [row for row in hist if now - float(row[0]) <= LIVELY_WINDOW_S] + if not window: + window = [hist[-1]] + best = 0.0 + run_start = None + run_peak = 0.0 + for age, _x, _y, along, v_lat in window: + speed = max(abs(float(along)), abs(float(v_lat))) + if speed > LIVELY_MOVE_MPS: + if run_start is None: + run_start = float(age) + run_peak = 0.0 + run_peak = max(run_peak, speed) + if float(age) - run_start + 1e-9 >= LIVELY_SUSTAIN_S: + best = max(best, max(0.5, _ramp(run_peak, SPEED_NOISE_MPS, SPEED_FULL_MPS))) + else: + run_start = None + return best + + +def scale_living_vision(vision: VisionScore, lively: float) -> VisionScore: + """Lively raises animal/person class scores. Still lowers them, not to 0.""" + scale = LIVELY_FLOOR + (1.0 - LIVELY_FLOOR) * _clamp(lively if math.isfinite(lively) else 0.0, 0.0, 1.0) + return replace( + vision, + human=_clamp(vision.human * scale, 0.0, 1.0), + animal=_clamp(vision.animal * scale, 0.0, 1.0), + ) + + +def patch_signature(rows, grid: int = 8) -> tuple[float, ...]: + """Coarse mean grid so a 5 Hz check can see the patch move.""" + data = _row_lists(rows) + if not data: + return () + height = len(data) + width = min(len(row) for row in data) + if width < 2 or height < 2: + return () + cells = [] + for gy in range(grid): + y0 = gy * height // grid + y1 = max(y0 + 1, (gy + 1) * height // grid) + for gx in range(grid): + x0 = gx * width // grid + x1 = max(x0 + 1, (gx + 1) * width // grid) + acc = 0.0 + count = 0 + for row in data[y0:y1]: + for value in row[x0:x1]: + num = _finite(value) + if num is not None: + acc += num + count += 1 + cells.append(acc / count if count else 0.0) + return tuple(cells) + + +def patch_change_score(prev, rows) -> float: + """0 when the patch matches, 1 when the gray levels really moved. + + About 12 counts of change is camera noise. Around 40 counts is motion. + """ + old = prev if isinstance(prev, tuple) else patch_signature(prev) + new = rows if isinstance(rows, tuple) else patch_signature(rows) + if not old or not new or len(old) != len(new): + return 0.0 + delta = sum(abs(a - b) for a, b in zip(old, new)) / len(old) + return _clamp((delta - 12.0) / 28.0, 0.0, 1.0) + + +def _vision_in_range(x: float) -> bool: + """Camera verdicts count only out to VISION_TRUST_M. Beyond that, radar only.""" + try: + dist = float(x) + except (TypeError, ValueError): + return False + return math.isfinite(dist) and dist <= VISION_TRUST_M + + +def _vision_class_score(vision: VisionScore, cls: str) -> float: + if cls == "human": + value = vision.human + elif cls == "animal": + value = vision.animal + elif cls == "obstacle": + value = vision.obstacle + else: + return 0.0 + try: + score = float(value) + except (TypeError, ValueError): + return 0.0 + if not math.isfinite(score): + return 0.0 + return score + + +def _unrotate_y(x: float, y: float, psi: float) -> float: + """Lateral position with ego yaw removed. psi is +right radians since track start.""" + return math.sin(psi) * x + math.cos(psi) * y + + +def _fuse_class(radar_class: str, span: float, count: int, vision: VisionScore | None, + raw: VisionScore | None = None) -> str: + if count >= 2 and span >= LANE_SPAN_M: + return "obstacle" + # Camera score for the radar's living class, before the lively scale. + # Below 0.30 the radar guess is not a person or an animal. + camera = raw if raw is not None else vision + if ( + camera is not None and camera.evaluated and radar_class in LIVING_CLASSES + and _vision_class_score(camera, radar_class) < VISION_LIVING_MIN + ): + return "obstacle" + if vision is None or not vision.evaluated or vision.conf < VISION_AGREE: + return radar_class + scores = (("human", vision.human), ("animal", vision.animal), ("obstacle", vision.obstacle)) + best, best_s = max(scores, key=lambda item: item[1]) + ordered = sorted((s for _, s in scores), reverse=True) + margin = best_s - (ordered[1] if len(ordered) > 1 else 0.0) + if radar_class in ("human", "animal") and best_s < 0.45: + return radar_class + if best_s >= 0.30 and margin >= 0.08: + return best + return radar_class + + +def _radar_class(members: list[dict], span: float, zone: str) -> str: + count = len(members) + lats = [m["lat"] for m in members] + if count >= 2 and span >= LANE_SPAN_M and min(lats) < 0.6 and max(lats) > -0.6: + return "obstacle" + best = "unknown" + for m in members: + toward = _toward(m["lat"], m["v_lat"]) + along = m["along"] + if _humanish(m["lat"], m["v_lat"], along, toward) and (count == 1 or span < 1.5): + return "human" + animalish = ( + (2.0 <= abs(m["v_lat"]) <= 12.0 and abs(along) < 5.0) + or (toward >= 1.6 and abs(along) < 4.5 and toward > 3.2) + ) + if animalish and (count == 1 or span < 1.6): + best = "animal" + if best == "animal": + return best + if zone == "inPath" and count >= 2 and span >= LANE_SPAN_M: + return "obstacle" + return "unknown" + + +def _cluster_reject(members: list[dict]) -> str | None: + xs = [m["x"] for m in members] + lats = [m["lat"] for m in members] + count = len(members) + if count < 2: + return None + x_span = max(xs) - min(xs) + lat_span = max(lats) - min(lats) + if lat_span >= OVERHEAD_SPAN_M and x_span < OVERHEAD_DEPTH_M and count >= 3: + return "overhead" + mean_lat = sum(lats) / count + var = sum((v - mean_lat) ** 2 for v in lats) / count + if x_span >= 10.0 and math.sqrt(var) <= 0.55 and count >= 4 and 0.5 <= abs(mean_lat) <= 3.0 and x_span > lat_span: + return "cone_line" + straddles = min(lats) < -0.2 and max(lats) > 0.2 + if x_span < 8.0 and lat_span >= 1.0 and abs(mean_lat) > 2.0 and not straddles and count >= 3: + return "exclVehicle" + return None + + +def _still_members(members: list[dict]) -> bool: + """Ground speed and lively score both say this cluster has not moved.""" + for member in members: + if abs(float(member["along"])) > SLOW_ALONG_MPS: + return False + if float(member.get("lively") or 0.0) >= LIVELY_CHIME: + return False + return True + + +def _group_zone(members: list[dict]) -> str: + lats = [m["lat"] for m in members] + span = (max(lats) - min(lats)) if len(lats) > 1 else 0.0 + straddles = min(lats) < -0.2 and max(lats) > 0.2 and span >= 1.2 + zones = [_zone_of(m["lat"], m["v_lat"], m["along"])[0] for m in members] + if straddles or any(zone == "inPath" for zone in zones): + return "inPath" + if any(zone == "entering" for zone in zones): + return "entering" + if any(zone == "roadside" for zone in zones): + return "roadside" + return "none" + + +def _phantom_in_path(members: list[dict], v_ego: float) -> bool: + """Stationary in-path return at highway speed that is not being closed. + + A real stopped object approaches at about ego speed and is gone after + the detection window. A 100 s 'in path' track at 25 m/s is a ghost or + a vehicle the lead logic missed, and it must not wake the camera. + """ + if v_ego < HIGHWAY_MPS: + return False + if not any(abs(m["lat"]) <= PATH_HALF_M for m in members): + return False + if not all(abs(m["along"]) <= SLOW_ALONG_MPS for m in members): + return False + age = max(float(m["age"]) for m in members) + if age < 0.35: + return False + closed = max(float(m["first_x"]) - float(m["x"]) for m in members) + need = min(8.0, 0.35 * v_ego * age) + if closed + 1e-6 < need: + return True + window = (X_MAX_M - X_MIN_M) / max(v_ego, 1.0) + return age > window + 2.0 + + +def _candidate_block(members: list[dict], v_ego: float) -> str | None: + """Drop a cluster before vision. None means the camera may look.""" + if _phantom_in_path(members, v_ego): + return "not_closing" + zone = _group_zone(members) + if zone == "none": + return "off_path" + lats = [m["lat"] for m in members] + span = (max(lats) - min(lats)) if len(lats) > 1 else 0.0 + radar_class = _radar_class(members, span, zone) + beyond = _beyond_corridor(min(abs(m["lat"]) for m in members)) + # Radar-only "human" on a stationary tall roadside return. Posts and + # delineators outside 3 ft of the corridor never reach the camera. + if radar_class == "human" and _still_members(members) and beyond > HUMAN_BEYOND_M: + return "off_zone" + if radar_class == "animal" and beyond > ANIMAL_BEYOND_M: + return "off_zone" + return None + + +def _popin(members: list[dict]) -> bool: + if any(m["first_x"] >= POPIN_X_M + 4.0 for m in members): + return False + if any(m["x"] > POPIN_X_M + 2.0 for m in members): + return False + if max(m["age"] for m in members) >= 0.55: + return False + lats = [m["lat"] for m in members] + if len(members) >= 2 and max(lats) - min(lats) >= LANE_SPAN_M: + return False + return all(abs(m["v_lat"]) < 0.40 and abs(m["along"]) < SLOW_ALONG_MPS for m in members) + + +def _still_in_lane(ret) -> bool: + """Stationary and already in the path. Crossing and roadside are not.""" + try: + along = float(ret["along"]) + v_lat = float(ret["v_lat"]) + lat = float(ret["lat"]) + except (TypeError, ValueError, KeyError): + return False + if not all(math.isfinite(v) for v in (along, v_lat, lat)): + return False + if abs(along) > SLOW_ALONG_MPS or abs(v_lat) >= ENTER_TOWARD_MPS: + return False + zone, _t = _zone_of(lat, v_lat, along) + return zone == "inPath" + + +def _lead_flags(ret, leads, model_leads) -> tuple[bool, bool]: + """(old vehicle exclusion, night drive-over lead agreement).""" + try: + x = float(ret["x"]) + y = float(ret["y"]) + tid = int(ret["id"]) + except (TypeError, ValueError, KeyError): + return False, False + lead_ids = set() + for raw in leads or (): + try: + lead_ids.add(int(raw)) + except (TypeError, ValueError): + continue + old = tid in lead_ids + agree = old + for lead in model_leads or (): + try: + lx, ly, prob = float(lead[0]), float(lead[1]), float(lead[2]) + except (TypeError, ValueError, IndexError): + continue + if not all(math.isfinite(v) for v in (lx, ly, prob)) or prob < LEAD_PROB: + continue + lead_id = None + if len(lead) > 3 and lead[3] is not None: + try: + lead_id = int(lead[3]) + except (TypeError, ValueError): + lead_id = None + same = lead_id is not None and lead_id == tid + dx = abs(x - lx) + dy = abs(y - ly) + if same or (dx < LEAD_X_M and dy < LEAD_Y_M): + old = True + tol = max(DRIVE_OVER_LEAD_X_M, DRIVE_OVER_LEAD_X_FRAC * abs(x)) + if prob >= DRIVE_OVER_LEAD_PROB and (same or (dx <= tol and dy <= DRIVE_OVER_LEAD_Y_M)): + agree = True + return old, agree + + +def _lead_keep(ret, leads, model_leads) -> str | None: + """'exclVehicle', or None when the return stays in the scan. + + A stationary in-lane lead is kept and flagged so a stalled car can + chime at night. Every other lead match is still excluded. A failure + excludes a known lead id and otherwise leaves the return alone. + """ + try: + old, agree = _lead_flags(ret, leads, model_leads) + except Exception: + try: + if int(ret.get("id", -1)) in set(leads or ()): + return "exclVehicle" + except (TypeError, ValueError): + return None + return None + if agree and _still_in_lane(ret): + ret["model_lead"] = True + return None + if old or agree: + return "exclVehicle" + return None + + +def _drive_over_case(sample: ObstacleSample, hit: _Hit) -> bool: + """Night, stationary, already in the lane, and not a person or animal.""" + if not is_night_lighting(hit.lighting): + return False + if not sample.active or sample.zone != "inPath": + return False + if sample.object_class in LIVING_CLASSES: + return False + if abs(float(hit.along)) > SLOW_ALONG_MPS: + return False + if abs(float(hit.v_lat)) >= ENTER_TOWARD_MPS: + return False + if float(sample.lively_score) >= LIVELY_CHIME: + return False + return True + + +def _night_lead_may_chime(sample: ObstacleSample, hit: _Hit) -> bool: + """Model-lead matches stay excluded except this night stalled-car case.""" + try: + return bool(hit.model_lead) and _drive_over_case(sample, hit) + except Exception: + return False + + +def _look_light(item) -> bool: + return len(item) > 3 and bool(item[3]) + + +def _look_confirms(item, cls: str) -> bool: + try: + conf, look_cls, score = float(item[0]), item[1], float(item[2]) + except (TypeError, ValueError, IndexError): + return False + return look_cls == cls and conf >= VISION_LOOK_MIN and score >= VISION_CLASS_MIN + + +def _drive_over_block(sample: ObstacleSample, vision: VisionScore | None, hist) -> str: + """Why this night in-lane return must not chime. Empty means it may.""" + if float(sample.range_m) > DRIVE_OVER_SOLID_M: + return "beyond_60" + dominated = bool(vision is not None and getattr(vision, "light_dominated", False)) + cls = sample.object_class + clean = [item for item in hist if _look_confirms(item, cls) and not _look_light(item)] + lit = dominated or any(_look_light(item) and _look_confirms(item, cls) for item in hist) + if dominated or (lit and len(clean) < VISION_LOOKS_NEED): + return "light" + conf = None if vision is None else _finite(getattr(vision, "conf", None)) + evaluated = bool(vision is not None and getattr(vision, "evaluated", False)) + if not evaluated or conf is None or conf < VISION_AGREE or len(clean) < VISION_LOOKS_NEED: + return "no_solid" + return "" + + +def _as_vehicle(sample: ObstacleSample) -> ObstacleSample: + """Daytime (and any non-night) lead match: same quiet result as before.""" + return replace( + sample, + active=False, + agree=False, + brake_gate=False, + in_path=False, + entering=False, + zone="none", + reject_reason="exclVehicle", + chimed=False, + chime_reason="exclVehicle", + drive_over_reason="", + ) + + +class PathObstacleDetector: + """One candidate per radar frame. State is track age and the chime memory.""" + + def __init__(self) -> None: + self._tracks: dict[int, dict] = {} + self._chime = ChimeGate() + self._vision_looks: dict[int, list] = {} + + def reset(self) -> None: + self._tracks.clear() + self._chime.reset() + self._vision_looks.clear() + + def begin(self, points, v_ego: float, path_x, path_y, dt: float, *, + lead_ids=(), cone: ConeHint | None = None, model_leads=(), + lighting: float = 1.0, deadline: float | None = None, + yaw_rate: float = 0.0) -> _Hit: + dt = 0.0 if dt is None else float(dt) + if not math.isfinite(dt) or dt < 0.0: + dt = 0.0 + dt = min(dt, 0.5) + try: + v_ego_f = float(v_ego) + except (TypeError, ValueError): + v_ego_f = 0.0 + if not math.isfinite(v_ego_f): + v_ego_f = 0.0 + try: + yaw = float(yaw_rate) + except (TypeError, ValueError): + yaw = 0.0 + if not math.isfinite(yaw): + yaw = 0.0 + light = lighting_score() if lighting is None else float(lighting) + if not math.isfinite(light): + light = 1.0 + + try: + _check_deadline(deadline) + parsed = [] + try: + iterator = list(points) if points is not None else [] + except TypeError: + iterator = [] + for raw in iterator: + _check_deadline(deadline) + item = _point(raw) + if item is not None: + parsed.append(item) + if len(parsed) > MAX_POINTS: + parsed.sort(key=lambda item: item["x"]) + del parsed[MAX_POINTS:] + returns = self._advance(parsed, dt, v_ego_f, path_x, path_y, deadline, yaw) + leads = {int(i) for i in lead_ids if i is not None} + near_reason = "no_candidate" + near_ret = None + kept = [] + for ret in returns: + reason = self._keep_reason(ret, leads, cone, model_leads) + if reason is None: + kept.append(ret) + elif near_ret is None or ret["x"] < near_ret["x"]: + near_ret = ret + near_reason = reason + # A stopped lead is its own candidate. Clustering it with a neighbor + # would hide that neighbor behind the lead, which daytime still ignores. + lead_pts = [ret for ret in kept if ret.get("model_lead")] + other_pts = [ret for ret in kept if not ret.get("model_lead")] + clusters = _cluster(other_pts) + clusters.extend([pt] for pt in lead_pts) + best = None + best_key = None + best_lead = None + best_lead_key = None + rejected = near_reason + rejected_members = [near_ret] if near_ret is not None else [] + for group in clusters: + _check_deadline(deadline) + why = _cluster_reject(group) + if why is None and _popin(group): + why = "road_surface" + if why is None: + why = _candidate_block(group, v_ego_f) + if why is not None: + if best is None and best_lead is None: + rejected = why + rejected_members = group + continue + hit = self._score_group(group, light, v_ego_f) + if hit is None: + continue + key = ( + 1 if hit.zone in ("inPath", "entering") else 0, + 1 if hit.radar_class in ("human", "animal") else 0, + hit.radar_conf, + -hit.x, + ) + # Anything that is not a lead keeps the slot, as it did before a + # lead match was left in the scan. The lead is used only when it + # is the only thing here, so a daytime obstacle is not hidden. + if hit.model_lead: + if best_lead_key is None or key > best_lead_key: + best_lead = hit + best_lead_key = key + elif best_key is None or key > best_key: + best = hit + best_key = key + if best is not None: + return best + if best_lead is not None: + return best_lead + return self._miss(rejected_members, rejected, light) + except _OverBudget: + return self._miss([], "over_budget", light) + + def commit(self, hit: _Hit, vision: VisionScore | None, *, + chime_enabled: bool = True, now: float = 0.0, + vision_motion: float = 0.0) -> ObstacleSample: + try: + motion = float(vision_motion) + except (TypeError, ValueError): + motion = 0.0 + if not math.isfinite(motion): + motion = 0.0 + lively = _clamp(max(float(hit.lively), _clamp(motion, 0.0, 1.0)), 0.0, 1.0) + use_vision = bool(hit.active and vision is not None and vision.evaluated) + trust_vision = bool(use_vision and vision is not None and _vision_in_range(hit.x)) + scored = scale_living_vision(vision, lively) if trust_vision and vision is not None else None + if trust_vision: + final_class = _fuse_class(hit.radar_class, hit.span_m, hit.cluster_count, scored, raw=vision) + else: + final_class = _fuse_class(hit.radar_class, hit.span_m, hit.cluster_count, None) + if not hit.cluster_count: + final_class = "unknown" + if trust_vision and vision is not None: + self._note_vision_look( + hit.track_id, vision.conf, final_class, _vision_class_score(vision, final_class), + bool(getattr(vision, "light_dominated", False)), + ) + vision_conf = vision.conf if trust_vision and vision is not None else None + fused, w_r, w_v, agree = fuse_scores(hit.radar_conf, vision_conf, hit.lighting) + agree = bool(agree and hit.active and trust_vision) + zone = hit.zone if hit.reject_reason in ("none", "not_persistent") else "none" + in_path = zone == "inPath" + entering = zone == "entering" + t_enter = 0.0 if in_path else hit.time_to_enter + brake = bool(agree and zone in BRAKE_ZONES) + if trust_vision and scored is not None and vision is not None: + vh, va, vo = scored.human, scored.animal, scored.obstacle + vconf = vision.conf + elif use_vision and vision is not None: + vh, va, vo = vision.human, vision.animal, vision.obstacle + vconf = vision.conf + else: + vh = va = vo = vconf = _nan() + sample = ObstacleSample( + active=bool(hit.active), + track_id=hit.track_id, + range_m=hit.x, + lateral=hit.lateral, + v_rel=hit.v_rel, + v_lat=hit.v_lat, + radar_conf=hit.radar_conf if hit.cluster_count else 0.0, + vision_conf=vconf, + vision_evaluated=use_vision, + lighting_score=hit.lighting, + w_radar=w_r, + w_vision=w_v, + fused_score=fused if hit.cluster_count else 0.0, + agree=agree, + reject_reason="none" if hit.active else hit.reject_reason, + in_path=in_path, + time_to_reach=hit.time_to_reach, + object_class=final_class, + vision_conf_human=vh, + vision_conf_animal=va, + vision_conf_obstacle=vo, + cluster_count=hit.cluster_count, + span_m=hit.span_m, + time_to_enter=t_enter, + entering=entering, + zone=zone, + brake_gate=brake, + lively_score=lively if hit.cluster_count else 0.0, + member_ids=hit.member_ids, + ) + if hit.model_lead and not _night_lead_may_chime(sample, hit): + return _as_vehicle(sample) + if sample.active and _highway_still_unconfirmed(sample, hit.v_ego): + return sample.with_chime(False, "no_agree") + if sample.active: + blocked = _class_zone_block(sample) + if blocked is not None: + return sample.with_chime(False, blocked) + drive_over = self._drive_over_reason(sample, vision, hit) + if drive_over: + # Log only. brakeGate stays closed so a later consumer cannot + # treat a headlight or a rail as something to stop for. + return replace( + sample, chimed=False, chime_reason="drive_over", drive_over_reason=drive_over, + brake_gate=False, agree=False, + ) + if sample.agree and not self._vision_confirmed(sample.track_id, sample.object_class): + return sample.with_chime(False, "no_agree") + policy = chime_policy_block(sample, hit, vision if trust_vision else None) + if policy is not None: + return sample.with_chime(False, policy) + chimed, reason = self._chime.consider(sample, chime_enabled, now) + return sample.with_chime(chimed, reason) + + def _drive_over_reason(self, sample: ObstacleSample, vision: VisionScore | None, hit: _Hit) -> str: + """Suppression token, or "" to leave the chime on the existing rules. + + Errors return "" so a broken crop or a bad field falls back to the + chime behavior from before this rule. + """ + try: + if hit.model_lead or not _drive_over_case(sample, hit): + return "" + return _drive_over_block(sample, vision, self._vision_looks.get(int(hit.track_id)) or ()) + except Exception: + return "" + + def _note_vision_look(self, track_id: int, conf: float, cls: str, score: float, + light: bool = False) -> None: + """Keep the last three trusted camera looks for this track.""" + try: + tid = int(track_id) + except (TypeError, ValueError): + return + if tid == 0: + return + try: + conf_f = float(conf) + except (TypeError, ValueError): + conf_f = 0.0 + if not math.isfinite(conf_f): + conf_f = 0.0 + hist = self._vision_looks.pop(tid, []) + hist.append((conf_f, cls, float(score), bool(light))) + if len(hist) > VISION_LOOKS: + del hist[:-VISION_LOOKS] + self._vision_looks[tid] = hist + while len(self._vision_looks) > 32: + self._vision_looks.pop(next(iter(self._vision_looks))) + + def _vision_confirmed(self, track_id: int, cls: str) -> bool: + """True when 2 of the last 3 looks clear 0.60 overall and 0.40 on cls.""" + try: + tid = int(track_id) + except (TypeError, ValueError): + return False + hist = self._vision_looks.get(tid) or () + good = 0 + for item in hist: + conf, look_cls, score = item[0], item[1], item[2] + if look_cls == cls and conf >= VISION_LOOK_MIN and score >= VISION_CLASS_MIN: + good += 1 + return good >= VISION_LOOKS_NEED + + def update(self, points, v_ego: float, path_x, path_y, dt: float, *, + lead_ids=(), cone: ConeHint | None = None, model_leads=(), + vision: VisionScore | None = None, lighting: float = 1.0, + chime_enabled: bool = True, now: float = 0.0, + vision_motion: float = 0.0, yaw_rate: float = 0.0) -> ObstacleSample: + hit = self.begin( + points, v_ego, path_x, path_y, dt, + lead_ids=lead_ids, cone=cone, model_leads=model_leads, lighting=lighting, + yaw_rate=yaw_rate, + ) + return self.commit(hit, vision, chime_enabled=chime_enabled, now=now, vision_motion=vision_motion) + + def _advance(self, parsed, dt, v_ego, path_x, path_y, deadline=None, yaw: float = 0.0) -> list[dict]: + seen = set() + out = [] + for item in parsed: + _check_deadline(deadline) + seen.add(item["id"]) + prev = self._tracks.get(item["id"]) + if prev is None or prev["gap"] > 0.35: + state = { + "age": dt, "first_x": item["x"], "gap": 0.0, "y": item["y"], + "v_lat": 0.0, "hist": [], "yaw_int": 0.0, + } + else: + state = prev + state["age"] = float(state["age"]) + dt + state["gap"] = 0.0 + # A fixed target at range x slides sideways at about -yaw*x while the + # car turns. Take that out of v_lat and out of the wander history. + prev_y = float(state["y"]) + measured = None + if item["yv_rel"] is not None: + measured = -float(item["yv_rel"]) + elif prev is not None and prev["gap"] <= 0.35 and dt > 1e-4: + measured = (item["y"] - prev_y) / dt + if measured is not None: + state["v_lat"] = measured + yaw * float(item["x"]) + state["y"] = item["y"] + state["x"] = item["x"] + dpsi = yaw * dt + if dpsi > 0.25: + dpsi = 0.25 + elif dpsi < -0.25: + dpsi = -0.25 + state["yaw_int"] = float(state.get("yaw_int", 0.0)) + dpsi + y_fix = _unrotate_y(float(item["x"]), float(item["y"]), float(state["yaw_int"])) + hist = state.setdefault("hist", []) + hist.append(( + float(state["age"]), float(item["x"]), y_fix, + float(item["v_rel"]) + v_ego, float(state["v_lat"]), + )) + state["hist"] = [row for row in hist if float(state["age"]) - float(row[0]) <= LIVELY_WINDOW_S + 0.05][-24:] + self._tracks[item["id"]] = state + py = path_y_at_x(path_x, path_y, item["x"]) + lat = item["y"] if py is None else item["y"] - py + out.append({ + "id": item["id"], + "x": item["x"], + "y": item["y"], + "lat": lat, + "v_rel": item["v_rel"], + "v_lat": float(state["v_lat"]), + "along": item["v_rel"] + v_ego, + "rcs": item["rcs"], + "age": float(state["age"]), + "first_x": float(state["first_x"]), + "lively": lively_from_history(state.get("hist") or ()), + }) + for track_id in list(self._tracks): + if track_id in seen: + continue + self._tracks[track_id]["gap"] = float(self._tracks[track_id]["gap"]) + dt + if self._tracks[track_id]["gap"] > 0.50: + del self._tracks[track_id] + return out + + def _keep_reason(self, ret, leads, cone, model_leads) -> str | None: + x, lat = ret["x"], ret["lat"] + if x < X_MIN_M or x > X_MAX_M: + return "out_of_range" + if not _fov_ok(x, ret["y"]): + return "fov" + lead_why = _lead_keep(ret, leads, model_leads) + if lead_why is not None: + return lead_why + cone_why = _cone_reject(lat, x, cone) + if cone_why is not None: + return cone_why + along, v_lat = ret["along"], ret["v_lat"] + # Cars and motorcycles going with traffic. A stopped car the model + # has not tagged is left for the chime. A sideways dart is not traffic. + if along > TRAFFIC_ALONG_MPS and abs(v_lat) <= TRAFFIC_VLAT_MPS: + return "exclVehicle" + toward = _toward(lat, v_lat) + human = _humanish(lat, v_lat, along, toward) + moving = abs(v_lat) >= LATERAL_MOVE_MPS + slow = abs(along) <= SLOW_ALONG_MPS + if along < -2.5 and abs(v_lat) <= TRAFFIC_VLAT_MPS and not human: + return "exclVehicle" + if not (slow or moving or human) or abs(along) > HUMAN_ALONG_MAX_MPS + 0.5: + return "exclVehicle" + zone, _t = _zone_of(lat, v_lat, along) + if zone == "none": + return "off_path" + return None + + def _score_group(self, members: list[dict], lighting: float, v_ego: float = 0.0) -> _Hit | None: + members = sorted(members, key=lambda m: m["x"]) + rep = members[0] + lats = [m["lat"] for m in members] + span = max(lats) - min(lats) if len(lats) > 1 else 0.0 + straddles = min(lats) < -0.2 and max(lats) > 0.2 and span >= 1.2 + zones = [] + for m in members: + zone, t_enter = _zone_of(m["lat"], m["v_lat"], m["along"]) + zones.append((zone, t_enter, m)) + if straddles or any(z == "inPath" for z, _, _ in zones): + zone, t_enter = "inPath", 0.0 + elif any(z == "entering" for z, _, _ in zones): + entering = [(t, m) for z, t, m in zones if z == "entering"] + t_enter, _m = min(entering, key=lambda item: item[0]) + zone = "entering" + elif any(z == "roadside" for z, _, _ in zones): + zone = "roadside" + finite = [t for z, t, _m in zones if z == "roadside" and math.isfinite(t)] + t_enter = min(finite) if finite else _nan() + else: + return None + radar_class = _radar_class(members, span, zone) + age = max(m["age"] for m in members) + persist = _clamp(age / PERSIST_FULL_S, 0.0, 1.0) + active = age + 1e-9 >= PERSIST_S + if zone == "inPath": + place = 1.0 + elif zone == "entering": + horizon = HUMAN_ENTER_HORIZON_S if radar_class == "human" else ENTER_HORIZON_S + t_use = t_enter if math.isfinite(t_enter) else horizon + place = _clamp(1.0 - t_use / horizon, 0.35, 0.95) + t_reach = _closing_time(rep["x"], rep["v_rel"]) + if radar_class == "human" and math.isfinite(t_reach) and math.isfinite(t_enter) and t_enter < t_reach: + place = min(1.0, place + 0.12) + else: + place = 0.72 + penalty = 0.0 + if zone == "roadside" and all(abs(m["v_lat"]) < 0.35 and abs(m["along"]) < 1.0 for m in members): + penalty += 0.22 + rcs_vals = [m["rcs"] for m in members if m["rcs"] is not None] + if rcs_vals and max(rcs_vals) < -10.0: + penalty += 0.30 + if rcs_vals and max(rcs_vals) < -15.0: + penalty += 0.25 + clutter = _clamp(1.0 - penalty, 0.20, 1.0) + conf = _clamp(0.18 + 0.78 * persist * place * clutter, 0.0, 1.0) + if len(members) >= 2 and span >= LANE_SPAN_M and zone == "inPath": + conf = min(1.0, conf + 0.06) + if not active: + conf = min(conf, 0.49) + v_lat = max(members, key=lambda m: _toward(m["lat"], m["v_lat"]))["v_lat"] + return _Hit( + active=active, + track_id=rep["id"], + member_ids=tuple(m["id"] for m in members), + x=rep["x"], + y=rep["y"], + lateral=rep["lat"], + v_rel=rep["v_rel"], + v_lat=v_lat, + along=rep["along"], + radar_conf=conf, + radar_class=radar_class, + zone=zone, + time_to_reach=_closing_time(rep["x"], rep["v_rel"]), + time_to_enter=0.0 if zone == "inPath" else t_enter, + cluster_count=len(members), + span_m=span, + reject_reason="none" if active else "not_persistent", + lighting=lighting, + lively=max(float(m.get("lively", 0.0)) for m in members), + v_ego=float(v_ego), + model_lead=any(bool(m.get("model_lead")) for m in members), + ) + + def _miss(self, members, reason: str, lighting: float) -> _Hit: + if not members or members[0] is None: + return _Hit( + False, 0, (), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "unknown", "none", + _nan(), _nan(), 0, 0.0, reason, lighting, 0.0, + ) + group = [m for m in members if m is not None] + rep = min(group, key=lambda m: m["x"]) + lats = [m["lat"] for m in group] + return _Hit( + False, rep["id"], tuple(m["id"] for m in group), rep["x"], rep["y"], rep["lat"], + rep["v_rel"], rep["v_lat"], rep["along"], 0.0, "unknown", "none", + _closing_time(rep["x"], rep["v_rel"]), _nan(), len(group), + (max(lats) - min(lats)) if len(lats) > 1 else 0.0, reason, lighting, + max(float(m.get("lively", 0.0)) for m in group), + ) + + +def _obstacle_body(msg): + if msg is None: + return None + try: + which = msg.which() + except Exception: + return msg + if which == "pathObstacleNAP": + return getattr(msg, which) + return msg + + +def hit_to_msg(hit: _Hit, dest) -> None: + """Write every _Hit field onto a pathObstacleNAP builder.""" + dest.active = bool(hit.active) + dest.trackId = int(hit.track_id) & 0xFFFFFFFFFFFFFFFF + ids = tuple(int(i) & 0xFFFFFFFFFFFFFFFF for i in hit.member_ids) + slots = dest.init("memberIds", len(ids)) + for i, mid in enumerate(ids): + slots[i] = mid + dest.range = float(hit.x) + dest.y = float(hit.y) + dest.lateral = float(hit.lateral) + dest.vRel = float(hit.v_rel) + dest.vLat = float(hit.v_lat) + dest.along = float(hit.along) + dest.radarConf = float(hit.radar_conf) if hit.cluster_count else 0.0 + radar_class = _enum_name(hit.radar_class, CLASS_ORDER) + dest.radarClass = radar_class + dest.objectClass = radar_class + zone = _enum_name(hit.zone, ZONE_ORDER) + dest.zone = zone + dest.inPath = zone == "inPath" + dest.entering = zone == "entering" + dest.timeToReach = float(hit.time_to_reach) + dest.timeToEnter = float(hit.time_to_enter) + dest.clusterCount = int(min(255, max(0, hit.cluster_count))) + dest.spanM = float(hit.span_m) + dest.rejectReason = str(hit.reject_reason) + dest.lightingScore = float(hit.lighting) + dest.livelyScore = float(hit.lively) if hit.cluster_count else 0.0 + w_r, w_v = fusion_weights(hit.lighting) + dest.wRadar = w_r + dest.wVision = w_v + dest.visionEvaluated = False + dest.visionConf = _nan() + dest.visionConfHuman = _nan() + dest.visionConfAnimal = _nan() + dest.visionConfObstacle = _nan() + dest.modelLeadAgree = bool(hit.model_lead) + dest.driveOverReason = "" + + +def hit_from_msg(msg) -> _Hit: + """Inverse of hit_to_msg. Accepts the event or the struct.""" + body = _obstacle_body(msg) + try: + member_ids = tuple(int(i) for i in body.memberIds) + except Exception: + member_ids = () + try: + model_lead = bool(body.modelLeadAgree) + except Exception: + model_lead = False + return _Hit( + active=bool(body.active), + track_id=int(body.trackId), + member_ids=member_ids, + x=float(body.range), + y=float(body.y), + lateral=float(body.lateral), + v_rel=float(body.vRel), + v_lat=float(body.vLat), + along=float(body.along), + radar_conf=float(body.radarConf), + radar_class=_enum_name(body.radarClass, CLASS_ORDER), + zone=_enum_name(body.zone, ZONE_ORDER), + time_to_reach=float(body.timeToReach), + time_to_enter=float(body.timeToEnter), + cluster_count=int(body.clusterCount), + span_m=float(body.spanM), + reject_reason=str(body.rejectReason or ""), + lighting=float(body.lightingScore), + lively=float(body.livelyScore), + model_lead=model_lead, + ) + + +def _quantize(value, digits: int): + try: + num = float(value) + except (TypeError, ValueError): + return None + if not math.isfinite(num): + return None + return round(num, digits) + + +class ObstacleStage: + """Radar half of the detector. radard calls step() after radarState is sent. + + Returns a hit to publish, or None when this cycle should stay silent. + commit() stays on the camera helper; this object only scans. + """ + + def __init__(self) -> None: + self.det = PathObstacleDetector() + self.heartbeat = False + self._log_on = True + self._log_override: bool | None = None + self._log_check_t = -1.0 + self._skip = 0 + self._exc_times: list[float] = [] + self._disabled = False + self._sig = None + self._last_pub = -1e9 + self._reset_done = False + self._speed_on = False + self._speed_reset = False + + def note_failure(self) -> None: + """Count a failure outside begin(), such as a publish error.""" + self._note_exception() + + def _note_exception(self) -> None: + if self._disabled: + return + now = time.monotonic() + self._exc_times = [t for t in self._exc_times if now - t <= BREAKER_WINDOW_S] + self._exc_times.append(now) + if len(self._exc_times) < BREAKER_TRIPS: + return + self._disabled = True + try: + from openpilot.common.swaglog import cloudlog + cloudlog.exception("path obstacle detector disabled until next drive") + except Exception: + pass + + def _logging(self, now: float) -> bool: + if self._log_override is not None: + return bool(self._log_override) + if self._log_check_t >= 0.0 and now - self._log_check_t < 1.0: + return self._log_on + self._log_check_t = now + try: + from openpilot.common.params import Params + self._log_on = bool(Params().get_bool(PARAM_OBSTACLE_LOG)) + except Exception: + self._log_on = True + return self._log_on + + def _at_speed(self, v_ego) -> bool: + """Hysteresis: arm at 15 mph, drop below about 13 mph.""" + try: + speed = float(v_ego) + except (TypeError, ValueError): + speed = 0.0 + if not math.isfinite(speed): + speed = 0.0 + if self._speed_on: + if speed < SPEED_DISABLE_MPS: + self._speed_on = False + elif speed >= SPEED_ENABLE_MPS: + self._speed_on = True + return self._speed_on + + def _idle(self, now: float, reason: str) -> _Hit | None: + if now - self._last_pub < HEARTBEAT_S: + return None + self._last_pub = now + self.heartbeat = True + return self.det._miss([], reason, 1.0) + + def step(self, points, v_ego, path_x, path_y, dt, lead_ids, cone, model_leads, now, + yaw_rate: float = 0.0) -> _Hit | None: + """Scan one radar frame. None means nothing to publish.""" + self.heartbeat = False + try: + now_f = float(now) + except (TypeError, ValueError): + now_f = time.monotonic() + if not math.isfinite(now_f): + now_f = time.monotonic() + if self._disabled: + return self._idle(now_f, "disabled") + if not self._logging(now_f): + if not self._reset_done: + self.det.reset() + self._reset_done = True + self._sig = None + return self._idle(now_f, "disabled") + self._reset_done = False + if not self._at_speed(v_ego): + self._skip = 0 + if not self._speed_reset: + self.det.reset() + self._sig = None + self._speed_reset = True + return self._idle(now_f, "lowSpeed") + self._speed_reset = False + if self._skip > 0: + self._skip -= 1 + return self._idle(now_f, "over_budget") + started = time.monotonic() + try: + hit = self.det.begin( + points, v_ego, path_x, path_y, dt, + lead_ids=lead_ids, cone=cone, model_leads=model_leads, + lighting=1.0, deadline=started + BUDGET_S, yaw_rate=yaw_rate, + ) + except Exception: + self._note_exception() + try: + self.det.reset() + except Exception: + pass + return self._idle(now_f, "error") + if hit.reject_reason == "over_budget": + elapsed = max(0.0, time.monotonic() - started) + self._skip = max(1, math.ceil(elapsed / BUDGET_S)) + sig = ( + bool(hit.active), int(hit.track_id), tuple(hit.member_ids), + hit.zone, hit.radar_class, hit.reject_reason, + _quantize(hit.x, 1), _quantize(hit.lateral, 2), + ) + changed = sig != self._sig + due = now_f - self._last_pub >= HEARTBEAT_S + if not (hit.active or changed or due): + return None + self._sig = sig + self._last_pub = now_f + self.heartbeat = bool(due and not hit.active and not changed) + return hit + + +def _cluster(members: list[dict]) -> list[list[dict]]: + n = len(members) + if n == 0: + return [] + parent = list(range(n)) + + def find(i: int) -> int: + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + for i in range(n): + for j in range(i): + if abs(members[i]["x"] - members[j]["x"]) <= CLUSTER_DX_M and abs(members[i]["lat"] - members[j]["lat"]) <= CLUSTER_DY_M: + ri, rj = find(i), find(j) + if ri != rj: + parent[rj] = ri + groups: dict[int, list[dict]] = {} + for i, member in enumerate(members): + groups.setdefault(find(i), []).append(member) + return list(groups.values()) + + +def save_ppm(path: str, rows) -> bool: + """Write a grayscale P5 thumbnail. False on any I/O problem.""" + try: + data = _row_lists(rows) + if not data: + return False + height = len(data) + width = min(len(r) for r in data) + if width < 2 or height < 2: + return False + raw = bytearray() + for row in data: + for value in row[:width]: + try: + pix = int(value) + except (TypeError, ValueError): + pix = 0 + raw.append(max(0, min(255, pix))) + header = f"P5\n{width} {height}\n255\n".encode("ascii") + with open(path, "wb") as handle: + handle.write(header) + handle.write(raw) + return True + except OSError: + return False + + +def prune_thumbs(directory: str, max_files: int = 24, max_bytes: int = 2_000_000) -> None: + """Drop the oldest thumbnails until count and bytes are inside the cap.""" + import os + try: + names = [n for n in os.listdir(directory) if n.endswith(".ppm")] + except OSError: + return + files = [] + for name in names: + full = os.path.join(directory, name) + try: + files.append((os.path.getmtime(full), os.path.getsize(full), full)) + except OSError: + continue + files.sort() + total = sum(size for _, size, _ in files) + while files and (len(files) > max_files or total > max_bytes): + _mtime, size, full = files.pop(0) + total -= size + try: + os.remove(full) + except OSError: + pass diff --git a/selfdrive/controls/lib/preap_driver_brake.py b/selfdrive/controls/lib/preap_driver_brake.py new file mode 100644 index 00000000000000..a95feea828f09b --- /dev/null +++ b/selfdrive/controls/lib/preap_driver_brake.py @@ -0,0 +1,103 @@ +"""Pre-AP driver-brake switch, separate from brakePressed. + +brakePressed stays false so a brake press does not take the generic +disengage path and drop lateral. driverBrakeApplied (with the CS.brake +float as a fallback) is the digital switch. Longitudinal pauses; lateral +stays. A stalk pull resumes long. +""" +from openpilot.common.realtime import DT_CTRL + +PREAP_FINGERPRINT = "TESLA_MODEL_S_PREAP" +# A normal pedal RELEASE lands on the next 50 Hz command frame. Hold past +# this before calling it a regression. +BRAKE_LONG_OVERLAP_S = 0.1 + + +def preap_pedal_long(CP) -> bool: + """Pedal-mode Pre-AP: openpilot long, software cruise, lateral stays on brake.""" + return ( + getattr(CP, "brand", None) == "tesla" + and getattr(CP, "carFingerprint", None) == PREAP_FINGERPRINT + and bool(getattr(CP, "openpilotLongitudinalControl", False)) + and not bool(getattr(CP, "pcmCruise", True)) + ) + + +def driver_brake_applied(CS) -> bool: + """True brake-switch state. Ignores the always-false Pre-AP brakePressed.""" + if bool(getattr(CS, "driverBrakeApplied", False)): + return True + try: + return float(getattr(CS, "brake", 0.0) or 0.0) >= 0.5 + except (TypeError, ValueError): + return False + + +def preap_longitudinal_active(*, enabled: bool, longitudinal_override: bool, + openpilot_longitudinal: bool, preap_pedal: bool, + enable_long_control: bool, driver_brake: bool) -> bool: + """carControl.longActive. + + Stock formula for every other car. On Pre-AP pedal long, also false while + the driver brake is down or long is paused (enableLongControl false), so + the log does not show an active decel the pedal is not executing. + """ + active = bool(enabled) and not bool(longitudinal_override) and bool(openpilot_longitudinal) + if preap_pedal: + active = active and bool(enable_long_control) and not bool(driver_brake) + return active + + +def published_long_accel(*, long_active: bool, loc_accel: float, preap_pedal: bool) -> float: + """Accel stored on carControl. A Pre-AP long pause logs 0, not the plan.""" + if preap_pedal and not bool(long_active): + return 0.0 + return float(loc_accel) + + +def brake_signal_disables(*, preap_pedal: bool, driver_brake: bool, prev_driver_brake: bool, + brake_pressed: bool, prev_brake_pressed: bool, + regen_braking: bool, prev_regen_braking: bool, + standstill: bool) -> bool: + """Rising brake, or brake while moving, or the same for regen. + + Pre-AP pedal mode reads driverBrakeApplied. Other cars keep brakePressed. + The caller still maps a Pre-AP hit to a long-only override, not a session cancel. + """ + if preap_pedal: + brake = bool(driver_brake) + prev_brake = bool(prev_driver_brake) + else: + brake = bool(brake_pressed) + prev_brake = bool(prev_brake_pressed) + moving_or_rising = (not standstill) + return ( + (brake and (not prev_brake or moving_or_rising)) + or (bool(regen_braking) and (not bool(prev_regen_braking) or moving_or_rising)) + ) + + +class BrakeLongOverlap: + """Latches once the brake switch and pedal-long authority overlap too long.""" + + def __init__(self, limit_s: float = BRAKE_LONG_OVERLAP_S): + self.limit_s = float(limit_s) + self.held_s = 0.0 + self._latched = False + + def reset(self) -> None: + self.held_s = 0.0 + self._latched = False + + def update(self, *, driver_brake: bool, pedal_long_active: bool, + dt: float = DT_CTRL) -> tuple[bool, bool]: + """Returns (fault, rising). Fault means the overlap has lasted more than limit_s.""" + if bool(driver_brake) and bool(pedal_long_active): + self.held_s += float(dt) + else: + self.reset() + fault = self.held_s > self.limit_s + rising = fault and not self._latched + if fault: + self._latched = True + return fault, rising diff --git a/selfdrive/controls/lib/radar_path_gate.py b/selfdrive/controls/lib/radar_path_gate.py new file mode 100644 index 00000000000000..3dc6d49ace542f --- /dev/null +++ b/selfdrive/controls/lib/radar_path_gate.py @@ -0,0 +1,327 @@ +"""Travel-path and oncoming gates for radar follow-lead selection. + +e1 qlog `1c95345a3286a5db|000000e1--b993674371` (tip `638f5f7d4`) +confirmed #201 rain-hold latched off-path STAT / oncoming tracks as +leadOne (modelProb ≪ 0.15 → aTarget=−3.5). Episodes: 20:46:45, +20:49:10, 20:51:52, 20:53:45, 20:54:53 CT. #199 look-ahead exonerated. + +The driving path is `modelV2.position` — the same plan path the UI +draws and vision uses for lead-in-path (`leadsV3` is the in-path lead +head). Radar used for long — default path-gated prefer, not rain-Auto +only — must sit on that path. Prefer latches path-valid *associations* +only; it does not pick an unassociated Bosch track in a wide FOV. + +Stationary in-path objects (stopped cars) stay valid: vLead ≈ 0, not +oncoming. Same-direction leads stay valid. Off-path / oncoming are +always rejected. Unhealthy radar / no path association falls back to +stock fusion. +""" +from __future__ import annotations + +import math +from collections.abc import Sequence +from typing import Any + +# Device-frame x: radar dRel is measured from the radar, ~1.52 m ahead +# of the camera / model origin. Keep in sync with radard.RADAR_TO_CAMERA. +RADAR_TO_CAMERA_M = 1.52 + +# EP_2059: #201's 2.5 / 4.0 yRel windows latched 771/802 at +# +2.23…+2.48 (0.02–0.27 m inside 2.5) → aTarget=−3.5. Justin: +# RAIN_INLANE 2.5 → 2.0 m (~6.6 ft, ~1.6 ft tighter) + vLead < 0. +# Clean 21:02/21:03 never acquired (|yRel| > 2.5). Path-relative +# when modelV2 exists. Incumbent 2.0 so a latch cannot walk to 3.98. +PATH_HALF_WIDTH_M = 1.5 +PATH_INCUMBENT_HALF_WIDTH_M = 2.0 + +# Absolute speed toward ego. Stopped: vLead ≈ 0. Oncoming: vLead < 0 +# (vRel ≈ −(v_ego + v_them)). e1 track 101 vLead ≈ −5…−6; EP_2059 +# 771/802 ≈ −22 / −19 m/s. Floor −1 m/s so stationary noise is not +# oncoming. +# +# This is a follow-lead publication gate only: do not make opposing +# traffic leadOne. It does not invent regen/hesitation. 20:58 / 21:02 / +# 21:03 mid-lane passers never associated and must stay ignored — same +# as stock. Off-path / high-|yRel| / unassociated is the actual bug. +ONCOMING_VLEAD_MS = -1.0 +ONCOMING_MIN_VEGO_MS = 2.0 + +# Radar-frame glitch floor (same as rain hold). +MIN_DREL_M = 0.5 + +# Synthesized Fri 2026-09-18 ~20:54 CT right-exit from a roundabout +# (device +left). Dig will pin the live segment; these numbers are the +# path-vs-off-path geometry: exit ~4 m right at 30 m, entrant at yRel≈0. +ROUNDABOUT_EXIT_PATH_X = (0.0, 10.0, 20.0, 30.0, 50.0) +ROUNDABOUT_EXIT_PATH_Y = (0.0, -0.8, -2.2, -4.0, -6.0) +ROUNDABOUT_EXIT_X_M = 30.0 + +# Synthesized Fri 2026-09-18 ~20:55 CT left-hand curve. Path at 45 m is +# +4 m left. A roadside sign on the *outside* of the turn (~two 3.7 m +# lanes) sits ~7.4 m to the right of that path (device y ≈ −3.4). +CURVE_OUTSIDE_PATH_X = (0.0, 15.0, 30.0, 45.0, 70.0) +CURVE_OUTSIDE_PATH_Y = (0.0, 1.2, 2.8, 4.0, 5.5) +CURVE_OUTSIDE_X_M = 45.0 +CURVE_OUTSIDE_TWO_LANES_M = 7.4 + +# Synthesized Fri 2026-09-18 ~21:06–21:07 CT left turn. Path is already +# +4 m left at 30 m. Ego-forward radar (yRel≈0) is furniture / an +# oncoming semi that is NOT on the travel path. yRel-only is not enough. +LEFT_TURN_PATH_X = (0.0, 15.0, 30.0, 50.0) +LEFT_TURN_PATH_Y = (0.0, 1.8, 4.0, 6.5) +LEFT_TURN_X_M = 30.0 + +# 21:08 Atlantic left: path has already left by ~3 m at 10 m, so +# ego-forward gas-station furniture (yRel≈0) is off path even as dRel +# closes and the car would otherwise stop in the road. +ATLANTIC_LEFT_PATH_X = (0.0, 5.0, 10.0, 20.0, 40.0) +ATLANTIC_LEFT_PATH_Y = (0.0, 1.5, 3.2, 5.0, 7.0) + +# Construction path collapse (Scallywag 08:57:58). Adjacent lane-line +# probs gone and |path y| at 15–30 m is not a lane. Raise the bar for +# a *new* association at |yRel| ≳ 2 (the right-side blip was ~−2.9). +# An already-owned lead is the planner's departing-release problem. +PATH_COLLAPSE_LANE_PROB = 0.15 +PATH_COLLAPSE_X_LO_M = 15.0 +PATH_COLLAPSE_X_HI_M = 30.0 +PATH_COLLAPSE_ABS_Y_M = 20.0 +PATH_COLLAPSE_NEW_YREL_M = 2.0 + + +def _num(obj: Any, *names: str) -> float | None: + for name in names: + if isinstance(obj, dict): + val = obj.get(name) + else: + val = getattr(obj, name, None) + if val is None: + continue + try: + f = float(val) + except (TypeError, ValueError): + continue + if math.isfinite(f): + return f + return None + + +def path_y_at_x(path_x: Sequence[float] | None, path_y: Sequence[float] | None, + x: float) -> float | None: + """Interpolate model travel-path y (device frame, +left) at x.""" + if path_x is None or path_y is None: + return None + n = min(len(path_x), len(path_y)) + if n < 2: + return None + try: + x = float(x) + except (TypeError, ValueError): + return None + if not math.isfinite(x): + return None + xs = [float(v) for v in path_x[:n]] + ys = [float(v) for v in path_y[:n]] + if x <= xs[0]: + return ys[0] + if x >= xs[-1]: + return ys[-1] + for i in range(1, n): + if x <= xs[i]: + dx = xs[i] - xs[i - 1] + t = 0.0 if dx == 0.0 else (x - xs[i - 1]) / dx + return ys[i - 1] + t * (ys[i] - ys[i - 1]) + return ys[-1] + + +def model_path_xy(model: Any) -> tuple[list[float] | None, list[float] | None]: + try: + pos = model.position + xs = [float(v) for v in pos.x] + ys = [float(v) for v in pos.y] + except (TypeError, ValueError, AttributeError): + return None, None + if len(xs) < 2 or len(xs) != len(ys): + return None, None + if not all(math.isfinite(v) for v in xs + ys): + return None, None + return xs, ys + + +def track_device_xy(track: Any) -> tuple[float, float] | None: + """Radar track in the camera / model device frame (x forward, y left).""" + d_rel = _num(track, "dRel") + y_rel = _num(track, "yRel") + if d_rel is None or y_rel is None: + return None + return d_rel + RADAR_TO_CAMERA_M, -y_rel + + +def path_lateral_m(track: Any, path_x: Sequence[float] | None = None, + path_y: Sequence[float] | None = None) -> float | None: + """Signed lateral from the travel path (device +left). No path → −yRel.""" + xy = track_device_xy(track) + if xy is None: + return None + x, y = xy + py = path_y_at_x(path_x, path_y, x) + return y if py is None else y - py + + +def track_v_lead(track: Any, v_ego: float) -> float | None: + v_lead = _num(track, "vLead", "vLeadK") + if v_lead is not None: + return v_lead + v_rel = _num(track, "vRel") + if v_rel is None: + return None + return v_rel + float(v_ego) + + +def track_is_oncoming(track: Any, v_ego: float) -> bool: + """True when the track is moving toward us in the opposing sense. + + Stationary / stopped-in-path: vLead ≈ 0 → False. + Same-direction slower lead: vLead > 0 → False. + Head-on / opposing: vLead ≲ −1.5 m/s → True. + """ + if float(v_ego) < ONCOMING_MIN_VEGO_MS: + return False + v_lead = track_v_lead(track, v_ego) + if v_lead is None: + return False + return v_lead < ONCOMING_VLEAD_MS + + +def track_is_in_path(track: Any, path_x: Sequence[float] | None = None, + path_y: Sequence[float] | None = None, + max_lat: float = PATH_HALF_WIDTH_M) -> bool: + lat = path_lateral_m(track, path_x, path_y) + if lat is None: + return False + return abs(lat) <= float(max_lat) + + +def radar_follow_ok(track: Any, v_ego: float = 0.0, + path_x: Sequence[float] | None = None, + path_y: Sequence[float] | None = None, + max_lat: float = PATH_HALF_WIDTH_M) -> bool: + """True when a radar track may be a longitudinal follow lead. + + Off-path / high-|yRel| / unassociated tracks fail the path gate. + Oncoming fails only as a follow candidate (stay ignored) — it does + not command a new brake. Straight opposing that never associates + stays leadOne=None, same as the 20:58 CT positive control. + """ + d_rel = _num(track, "dRel") + if d_rel is None or d_rel <= MIN_DREL_M: + return False + if track_is_oncoming(track, v_ego): + return False + return track_is_in_path(track, path_x, path_y, max_lat=max_lat) + + +def lane_lines_collapsed(probs) -> bool: + """True when both adjacent lane lines have collapsed probability. + + Index 1 is the left line, index 2 the right (same as LDW). A short + or missing list is not collapse — do not invent a gate. + """ + if probs is None: + return False + try: + vals = [float(p) for p in list(probs)] + except (TypeError, ValueError): + return False + if len(vals) < 3: + return False + if not all(math.isfinite(v) for v in vals[1:3]): + return False + return ( + vals[1] < PATH_COLLAPSE_LANE_PROB and vals[2] < PATH_COLLAPSE_LANE_PROB + ) + + +def path_y_absurd(path_x: Sequence[float] | None, + path_y: Sequence[float] | None) -> bool: + """True when travel-path y at 15–30 m is not a drivable lane offset.""" + if path_x is None or path_y is None: + return False + try: + n = min(len(path_x), len(path_y)) + except TypeError: + return False + if n < 2: + return False + xs = [PATH_COLLAPSE_X_LO_M, 22.0, PATH_COLLAPSE_X_HI_M] + for i in range(n): + try: + x = float(path_x[i]) + except (TypeError, ValueError): + continue + if PATH_COLLAPSE_X_LO_M <= x <= PATH_COLLAPSE_X_HI_M and x not in xs: + xs.append(x) + peak = 0.0 + saw = False + for x in xs: + y = path_y_at_x(path_x, path_y, x) + if y is None: + continue + saw = True + peak = max(peak, abs(float(y))) + return saw and peak >= PATH_COLLAPSE_ABS_Y_M + + +def path_model_collapsed(lane_probs, path_x: Sequence[float] | None = None, + path_y: Sequence[float] | None = None) -> bool: + """Lane lines down and the near path is absurd. Both are required.""" + return lane_lines_collapsed(lane_probs) and path_y_absurd(path_x, path_y) + + +def collapse_blocks_new_lead(y_rel, collapsed, incumbent=False) -> bool: + """Block a new lead at |yRel| ≳ 2 while the path model has collapsed. + + Right-side (negative yRel) is the construction blip; either side + past the bar is the same new-association gate. An incumbent track + stays so a real cut-in can walk off without a hard drop. + + This does not decide whether a far lead's rapid decel may firm ego + braking. That lead is already followed. The rapid-brake path in + unified_lead gates that copy on predicted-path offset instead. + """ + if not collapsed or incumbent or y_rel is None: + return False + try: + y = float(y_rel) + except (TypeError, ValueError): + return False + if not math.isfinite(y): + return False + return abs(y) >= PATH_COLLAPSE_NEW_YREL_M + + +def vision_lead_follow_ok(lead: Any, v_ego: float = 0.0, + path_x: Sequence[float] | None = None, + path_y: Sequence[float] | None = None, + max_lat: float = PATH_INCUMBENT_HALF_WIDTH_M) -> bool: + """Vision-only lead: reject oncoming / far-off-path. Looser than radar. + + Do not use the tight radar half-width here — a cut-in the model still + owns as leadOne can sit ~2 m off path for a few frames. + """ + try: + v = float(lead.v[0]) + except (TypeError, ValueError, AttributeError, IndexError): + v = None + if (v is not None and float(v_ego) >= ONCOMING_MIN_VEGO_MS and + v < ONCOMING_VLEAD_MS): + return False + try: + x = float(lead.x[0]) + y = float(lead.y[0]) + except (TypeError, ValueError, AttributeError, IndexError): + return True + if not math.isfinite(x) or not math.isfinite(y): + return True + py = path_y_at_x(path_x, path_y, x) + lat = y if py is None else y - py + return abs(lat) <= float(max_lat) diff --git a/selfdrive/controls/lib/radar_sensor_dirty.py b/selfdrive/controls/lib/radar_sensor_dirty.py new file mode 100644 index 00000000000000..040eec68882f7f --- /dev/null +++ b/selfdrive/controls/lib/radar_sensor_dirty.py @@ -0,0 +1,107 @@ +"""Pre-AP Bosch radar `RADC_SensorDirty`: degrade, do not soft-disable. + +Route 1c95345a3286a5db|00000156--eb2236cd87, I-40 Pigeon River Gorge +construction zone (single narrow lane between concrete walls), Oct 4 2026: +at 03:03:59 CT the radar set `RADC_SensorDirty` in its own SguInfo frame +(0x301, bit 44). opendbc maps that to `radarErrors.radarUnavailableTemporary`, +which selfdrived turns into SOFT_DISABLE + NO_ENTRY. The car dropped out of +control and could not re-engage for 3 min 50 s, although CAN was valid and the +radar kept delivering live lead tracks the whole time (leadOne radar=1, +17-62 m). The flag is the radar's own blindness/obstruction self-report, not a +CAN fault or a parse error; it is not proof that the radar sees nothing. + +Policy (param `NAPRadarIgnoreSensorDirty`, default ON; OFF = old behavior): + + * flag set, live measured tracks present -> DEGRADED. radard publishes + `radarUnavailableTemporary=False` (so no soft-disable, no NO_ENTRY, and + the radar lead / prefer path stays on), tags `radarPreferReason` with + "sensorDirty" and raises `radarPreferFallback`, which selfdrived already + maps to the non-disabling "Radar Sensor Dirty" warning (events.py picks + the text from the reason). No accel cap: the planner is untouched. + * flag set AND no live measured track for SENSOR_DIRTY_PERSIST_S in a row + -> ESCALATED. The flag is passed through untouched, which is exactly the + old soft-disable + NO_ENTRY. + * Live tracks come back for SENSOR_DIRTY_LIVE_RECOVER_S -> the no-track + clock restarts and the policy is DEGRADED again (re-engage is allowed). + +Only the SensorDirty flag is touched. canError, radarFault and wrongConfig +always pass through. This is main-repo policy only: the opendbc radar +interface is unchanged and still reports the raw flag. +""" +from __future__ import annotations + +from typing import Any + +SENSOR_DIRTY_PARAM = "NAPRadarIgnoreSensorDirty" +# Token in radarState.radarPreferReason (no capnp change). "+"-joined with the +# reliability reason, e.g. "sensorDirty+dropout". +SENSOR_DIRTY_REASON = "sensorDirty" +# Flag set AND no live measured track for this long, continuously, brings back +# the old soft-disable. Live tracks reset it. +SENSOR_DIRTY_PERSIST_S = 10.0 +# Live tracks must be back this long before the no-track clock restarts. +SENSOR_DIRTY_LIVE_RECOVER_S = 1.0 + + +def sensor_dirty_ignore_enabled(params: Any) -> bool: + """NAPRadarIgnoreSensorDirty. Default ON; any read failure is the new behavior.""" + if params is None: + return True + try: + if hasattr(params, "get_bool"): + return bool(params.get_bool(SENSOR_DIRTY_PARAM)) + val = params.get(SENSOR_DIRTY_PARAM, return_default=True) + if isinstance(val, (bytes, bytearray)): + val = val.decode("utf-8", errors="ignore") + if val is None or val == "": + return True + return bool(int(val)) if not isinstance(val, bool) else bool(val) + except Exception: + return True + + +class SensorDirtyPolicy: + """Per-frame decision: pass the flag through, or mask it and degrade.""" + + def __init__(self) -> None: + self.degraded = False + self.escalated = False + self.no_track_s = 0.0 + self._live_s = 0.0 + + def reset(self) -> None: + self.degraded = False + self.escalated = False + self.no_track_s = 0.0 + self._live_s = 0.0 + + def update(self, flag: bool, live_tracks: bool, dt: float, ignore: bool = True) -> bool: + """Returns True when radard must mask `radarUnavailableTemporary`.""" + if not ignore or not flag: + self.reset() + return False + if live_tracks: + self._live_s += dt + if self._live_s >= SENSOR_DIRTY_LIVE_RECOVER_S: + self.no_track_s = 0.0 + else: + self._live_s = 0.0 + self.no_track_s += dt + self.escalated = self.no_track_s >= SENSOR_DIRTY_PERSIST_S + self.degraded = not self.escalated + return self.degraded + + +def reason_token(reliability_reason: str, degraded: bool) -> str: + """radarPreferReason text: the sensorDirty token first, then the usual reason.""" + base = str(reliability_reason or "") + if not degraded: + return base + return f"{SENSOR_DIRTY_REASON}+{base}" if base else SENSOR_DIRTY_REASON + + +def sensor_dirty_degraded(reason: Any) -> bool: + """True when a radarState.radarPreferReason carries the degraded token.""" + if not isinstance(reason, str): + return False + return SENSOR_DIRTY_REASON in reason.split("+") diff --git a/selfdrive/controls/lib/radar_status_log.py b/selfdrive/controls/lib/radar_status_log.py new file mode 100644 index 00000000000000..2bea5da6ce9294 --- /dev/null +++ b/selfdrive/controls/lib/radar_status_log.py @@ -0,0 +1,138 @@ +"""2 Hz `radarstat` line (cloudlog -> qlog) for Pre-AP Bosch radar digs. + +The Oct 4 2026 SensorDirty soft-disable could not be fully explained from qlog: +no liveTracks, CAN snapshots only every ~20 s, no 0x501 alert matrix near the +event. This line keeps the radar's own status bits and a small track summary in +qlog (no capnp change) so the next one can be settled from qlog alone: + + dirty/hw/sgu TeslaRadarSguInfo (0x301, bus 1) RADC_SensorDirty / HWFail / SGUFail + al TeslaRadarAlertMatrix (0x501, bus 1) as 16 hex digits (bit 0 = a001) + aln names of the alert bits that are set (a007 sensorBlinded, a052 radomeHtrInop, ...) + sa / aa age (s) of the last 0x301 / 0x501 frame; None = never seen + n / nm radar tracks / measured tracks + ns stationary tracks (|vRel + vEgo| < STATIONARY_VREL_MS) + nl stationary tracks near the road edge: |yRel| < NEAR_LATERAL_Y_M and dRel < NEAR_LATERAL_D_M + ysm smallest |yRel| of a stationary track (None if none) + d0 nearest track dRel +Never touches control; every failure is swallowed. +""" +from __future__ import annotations + +import json +import time +from collections.abc import Iterable +from typing import Any + +RADAR_BUS = 1 +ADDR_SGU = 0x301 +ADDR_ALERT = 0x501 + +# DBC TeslaRadarSguInfo, little-endian @1+. Kept equal to selfdrive/ui/radar/bosch_status.py (pinned by a test). +SGU_DIRTY_BIT = 44 +SGU_HW_FAIL_BIT = 45 +SGU_FAIL_BIT = 46 + +STATIONARY_VREL_MS = 1.5 +NEAR_LATERAL_Y_M = 3.0 +NEAR_LATERAL_D_M = 60.0 +LOG_PERIOD_S = 0.5 + +# DBC TeslaRadarAlertMatrix bit n = a(n+1). +ALERT_NAMES: tuple[str, ...] = ( + "ecuInternalPerf", "flashPerformance", "vBatHigh", "adjustmentNotDone", "adjustmentReq", "adjustmentNotOk", + "sensorBlinded", "plantModeActive", "configMismatch", "canBusOff", "bdyMIA", "espMIA", "gtwMIA", "sccmMIA", + "adasMIA", "bdyInvalidCount", "adasInvalidCount", "espInvalidCount", "sccmInvalidCount", "bdyInvalidChkSm", + "espInvalidChkSm", "sccmInvalidChkSm", "sccmInvalidChkSm2", "absValidity", "ambTValidity", "brakeValidity", + "CntryCdValidity", "espValidity", "longAccOffValidity", "longAccValidity", "odoValidity", "gearValidity", + "steerAngValidity", "steerAngSpdValidity", "indctrValidity", "vehStandStillValidity", "vinValidity", + "whlRotValidity", "whlSpdValidity", "whlStandStillValidity", "wiperValidity", "xwdValidity", "yawOffValidity", + "yawValidity", "bsdSanity", "rctaSanity", "lcwSanity", "steerAngOffSanity", "tireSizeSanity", "velocitySanity", + "yawSanity", "radomeHtrInop", "espmodValidity", "gtwmodValidity", "stwmodValidity", "bcmodValidity", + "dimodValidity", "opmodValidity", "drmiInvalidChkSm", "drmiInvalidCount", "radPositionMismatch", + "strRackMismatch", +) + + +def radar_bus(src: int) -> bool: + return (int(src) & 0x7F) == RADAR_BUS + + +def _bit(value: int, index: int) -> bool: + return bool((value >> index) & 1) + + +def decode_sgu(dat: bytes) -> dict[str, int]: + v = int.from_bytes(bytes(dat)[:8], "little") + return {"dirty": int(_bit(v, SGU_DIRTY_BIT)), "hw": int(_bit(v, SGU_HW_FAIL_BIT)), "sgu": int(_bit(v, SGU_FAIL_BIT))} + + +def alert_names(value: int) -> list[str]: + return [ALERT_NAMES[i] for i in range(len(ALERT_NAMES)) if _bit(value, i)] + + +def track_summary(points: Iterable[Any], v_ego: float) -> dict[str, Any]: + n = nm = ns = nl = 0 + ysm: float | None = None + d0: float | None = None + for p in points: + n += 1 + d, y, vr = float(p.dRel), float(p.yRel), float(p.vRel) + if bool(p.measured): + nm += 1 + if d0 is None or d < d0: + d0 = d + if abs(vr + float(v_ego)) < STATIONARY_VREL_MS: + ns += 1 + if ysm is None or abs(y) < ysm: + ysm = abs(y) + if abs(y) < NEAR_LATERAL_Y_M and d < NEAR_LATERAL_D_M: + nl += 1 + return {"n": n, "nm": nm, "ns": ns, "nl": nl, + "ysm": None if ysm is None else round(ysm, 1), "d0": None if d0 is None else round(d0, 1)} + + +class RadarStatusLogger: + """Remembers the latest SguInfo / AlertMatrix frames, emits one line per LOG_PERIOD_S.""" + + def __init__(self, period_s: float = LOG_PERIOD_S) -> None: + self.period_s = period_s + self._sgu: bytes | None = None + self._sgu_t = 0.0 + self._alert: int | None = None + self._alert_t = 0.0 + self._last_log_t: float | None = None + + def observe(self, packets: Iterable[Any], now: float) -> None: + for p in packets: + if not radar_bus(p.src): + continue + if p.address == ADDR_SGU: + self._sgu, self._sgu_t = bytes(p.dat), now + elif p.address == ADDR_ALERT: + self._alert, self._alert_t = int.from_bytes(bytes(p.dat)[:8], "little"), now + + def line(self, points: Iterable[Any], v_ego: float, now: float) -> str | None: + if self._last_log_t is not None and now - self._last_log_t < self.period_s: + return None + self._last_log_t = now + rec: dict[str, Any] = {} + if self._sgu is not None: + rec.update(decode_sgu(self._sgu)) + rec["sa"] = None if self._sgu is None else round(now - self._sgu_t, 1) + rec["al"] = None if self._alert is None else f"{self._alert:016x}" + rec["aln"] = [] if self._alert is None else alert_names(self._alert) + rec["aa"] = None if self._alert is None else round(now - self._alert_t, 1) + rec.update(track_summary(points, v_ego)) + rec["v"] = round(float(v_ego), 1) + return "radarstat " + json.dumps(rec, separators=(",", ":")) + + def update(self, packets: Iterable[Any], points: Iterable[Any] | None, v_ego: float, now: float | None = None) -> str | None: + """Call every card cycle. `points` is None between radar frames (no line then).""" + try: + t = time.monotonic() if now is None else now + self.observe(packets, t) + if points is None: + return None + return self.line(points, v_ego, t) + except Exception: + return None diff --git a/selfdrive/controls/lib/rain_radar_hold.py b/selfdrive/controls/lib/rain_radar_hold.py new file mode 100644 index 00000000000000..83e336b3a478c3 --- /dev/null +++ b/selfdrive/controls/lib/rain_radar_hold.py @@ -0,0 +1,528 @@ +"""Path-gated radar prefer for Pre-AP longitudinal lead selection. + +Default operating mode — not rain-Auto-only. Prefer a live **path-valid +radar association** for long lead when: + + 1. NAP → Radar Settings → Radar Enabled is On (`NAPRadarEnabled`) + 2. radar is reliable (no hardware fault / stream timeout / erratic + track kinematics) + +NAPWiperSpeed==3 was a temporary rain gate. It is not required. + +If radar is disabled, unhealthy, or the track is not path-associated, +fall back to stock vision-radar fusion. Off-path / oncoming are always +rejected. On-path stationary is kept. + +Evening rain on Scallywag (route 1c95345a3286a5db|000000df--467073c363) +flapped leadOne radar↔vision: vision-only dRel steps ~7.75 m mean vs +radar-associated 0.48 m. Radar track 806 stayed smooth when associated. + +e1 `1c95345a3286a5db|000000e1--b993674371` (tip 638f5f7d4) then showed +the old rain-hold latching off-path STAT / oncoming as leadOne +(mp ≪ 0.15, aTarget=−3.5). Path + vLead gates stay. #199 is not +implicated. + +This is not “prefer any Bosch track in a wide FOV.” Radar used for long +must sit on the same model driving path vision uses for lead-in-path +(`modelV2.position`): + on path + stationary → KEEP (stopped lead / pedestrian) + off path + stationary → REJECT (signs, gas station) + oncoming / opposing → REJECT +""" +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from openpilot.selfdrive.controls.lib.radar_path_gate import ( + MIN_DREL_M, + PATH_INCUMBENT_HALF_WIDTH_M, + radar_follow_ok, +) + +# Keep in sync with preap_body_controls / nap_params. +NAP_WIPER_SPEED = "NAPWiperSpeed" +WIPER_SETTING_AUTO = 3 +NAP_RADAR_ENABLED = "NAPRadarEnabled" +NAP_RADAR_IGNORE_HW_FAIL = "NAPRadarIgnoreHwFail" + +# Hold last radar lead this many model frames after the track ID disappears. +RAIN_RADAR_LOST_HOLD_FRAMES = 8 +# Vision-only bar while path-gated prefer is active. Dig flaps were already ≥ 0.9. +RAIN_VISION_ONLY_MIN_PROB = 0.90 + +# Reliability: hardware / stream timeout trip prefer immediately. Soft +# reasons (empty-table dropout, erratic jumps) need a short streak. +# Recover after this many consecutive good samples so a single clean +# frame cannot chatter the prefer latch. +# +# e3 gravel crawl (1c95345a3286a5db|000000e3--8b12de89d2, tip b635cc6cd7ab): +# 09:22:24 CT ~1s radarPreferFallback, 8s before engage. radarErrors all +# false, vEgo 5.35 (just over the old 5.0 empty-table gate), recovered in +# RELIABLE_OK_FRAMES. Soft dropout must not flash the HUD. +# +# Sat Sep 19 09:45–10:05 CT pavement (dongle 1c95345a3286a5db): +# 41 HUD blips on the #210/#206 tip — all soft empty-table or timeout, +# 0 radarErrors, 0/41 with a path lead. Signs / opposing correlate; +# quieter on open road. #209 still flashed: timeout was a hard HUD +# reason. Soft empty / timeout / erratic must never HUD. canError / +# radarFault stay immediate. A path-associated lead also mutes non-fault. +RELIABLE_FAIL_FRAMES = 4 +RELIABLE_OK_FRAMES = 16 +# Soft HUD leftover (unused). Dropout / erratic / timeout never HUD. +RELIABLE_ALERT_FRAMES = 80 +RELIABLE_TIMEOUT_ALERT_FRAMES = 40 +RELIABLE_ONROAD_GRACE_FRAMES = 60 +RELIABLE_ENGAGE_GRACE_FRAMES = 40 +RELIABLE_DROPOUT_S = 0.50 +RELIABLE_YREL_JUMP_M = 4.0 +RELIABLE_DREL_JUMP_M = 25.0 +# Empty-table while moving. 5.0 caught gravel crawl at 5.35 m/s (~12 mph). +RELIABLE_MIN_VEGO_MS = 8.0 +# Prefer-latch immediate trip. HUD only for real hardware / CAN faults. +RELIABLE_HARD_REASONS = frozenset({"fault", "timeout", "override"}) +RELIABLE_SOFT_REASONS = frozenset({"dropout", "erratic", "timeout"}) +RELIABLE_HUD_HARD_REASONS = frozenset({"fault", "override"}) +# EP_2059 (e1 segs 13–17): #201 RAIN_INLANE=2.5 latched near-edge +# oncoming 771/802 at |yRel| 2.23–2.48 (0.02–0.27 m inside 2.5). +# Justin: 2.5 → 2.0 m (~6.6 ft) + reject vLead < 0. Path association +# still required. Clean 21:02/21:03 stayed |yRel| > 2.5. Incumbent +# 2.0 (not 4.0) so a latched near-edge cannot walk to y=3.98. +RAIN_MIN_DREL_M = MIN_DREL_M +RAIN_INLANE_YREL_M = 2.0 +RAIN_INCUMBENT_MAX_YREL_M = PATH_INCUMBENT_HALF_WIDTH_M +RAIN_CUT_IN_GAP_M = 8.0 +# Incumbent-only hold beyond this needs a confident vision lead (range may +# flap). 20:59:40 STAT 84–123 m and 20:49:10 track 321 at 99.3 m / mp 0.007 +# must not regen. Live path association is enough at any range. Original +# rain dig: track 806 at 93.8 m + modelProb 0.978 still holds. +RAIN_FAR_HOLD_DREL_M = 70.0 +RAIN_FAR_HOLD_MIN_PROB = 0.50 +# Path of travel is the filter. On-path stationary (stopped car / +# pedestrian) is KEEP. Off-path STAT (signs, gas station) fails the +# path gate. Do not blanket-reject vLead≈0. + + +def _decode_param(val: Any) -> Any: + if isinstance(val, (bytes, bytearray)): + return val.decode("utf-8", errors="ignore") + return val + + +def wiper_is_auto(wiper_speed: Any) -> bool: + """True when rain-sensing / Auto is selected. Not 'it is raining'.""" + try: + return int(wiper_speed) == WIPER_SETTING_AUTO + except (TypeError, ValueError): + return False + + +def rain_sensing_on(wiper_speed: Any) -> bool: + """Legacy Auto-wiper helper. Not the prefer gate — prefer is default.""" + return wiper_is_auto(wiper_speed) + + +def read_wiper_speed(params: Any) -> int: + try: + val = _decode_param(params.get(NAP_WIPER_SPEED, return_default=True)) + if val is None or val == "": + return 0 + return int(val) + except Exception: + return 0 + + +def _param_bool(params: Any, key: str, default: bool = False) -> bool: + if params is None: + return default + try: + if hasattr(params, "get_bool"): + return bool(params.get_bool(key)) + val = params.get(key, return_default=True) + if isinstance(val, (bytes, bytearray)): + val = val.decode("utf-8", errors="ignore") + if val is None or val == "": + return default + return bool(int(val)) if not isinstance(val, bool) else bool(val) + except Exception: + return default + + +def radar_errors_unhealthy(errors: Any, ignore_hw_fail: bool = False) -> bool: + """Hardware / CAN faults. Ignore-HW-fail only masks radarFault.""" + if errors is None: + return False + + def _flag(name: str) -> bool: + if isinstance(errors, dict): + return bool(errors.get(name, False)) + return bool(getattr(errors, name, False)) + + if _flag("canError") or _flag("radarUnavailableTemporary"): + return True + if _flag("radarFault") and not ignore_hw_fail: + return True + return False + + +def _track_xy(track: Any) -> tuple[float, float] | None: + try: + d_rel = float(track.dRel) + y_rel = float(track.yRel) + except (TypeError, ValueError, AttributeError): + return None + if not (d_rel == d_rel and y_rel == y_rel): # NaN + return None + return d_rel, y_rel + + +class RadarReliability: + """Practical Bosch health for path-gated prefer. + + Immediate trip: CAN/fault bits, measurement timeout. Streak trip: + empty table while moving above RELIABLE_MIN_VEGO_MS, or same-ID + |ΔyRel| / |ΔdRel| jumps. Recover after RELIABLE_OK_FRAMES clean + samples so the prefer latch does not chatter. + + HUD (`should_alert`) is stricter than the prefer latch: canError / + radarFault alert immediately; empty-table / timeout / kinematic + clutter never flash the HUD (silent camera fallback). A healthy + path-associated lead also mutes any leftover non-fault reason. + `log_reason` is published every frame for the next route dig. + """ + + def __init__(self): + self.healthy = True + self.reason = "" + self.sample_reason = "" + self._bad_streak = 0 + self._good_streak = 0 + self._unhealthy_frames = 0 + self._frames = 0 + self._engaged = False + self._engage_frame: int | None = None + self._last_xy: dict[int, tuple[float, float]] = {} + self._low_speed_empty = False + self._override: bool | None = None + self._path_lead = False + + def set_override(self, healthy: bool | None) -> None: + self._override = None if healthy is None else bool(healthy) + + def set_path_lead(self, ok: bool) -> None: + """True when a healthy path-associated radar lead is published.""" + self._path_lead = bool(ok) + + def reset(self) -> None: + self.healthy = True + self.reason = "" + self.sample_reason = "" + self._bad_streak = 0 + self._good_streak = 0 + self._unhealthy_frames = 0 + self._frames = 0 + self._engaged = False + self._engage_frame = None + self._last_xy = {} + self._low_speed_empty = False + self._path_lead = False + + @property + def log_reason(self) -> str: + """Latched trip reason, else this-frame soft reason (may not trip).""" + if not self.healthy and self.reason: + return self.reason + return self.sample_reason + + @property + def should_alert(self) -> bool: + """HUD latch. Faults are immediate; soft clutter never flashes.""" + if self._override is False: + return True + if self._override is True or self.healthy: + return False + if self.reason in RELIABLE_HUD_HARD_REASONS: + return True + # Empty-table / timeout / signs / opposing: log + drop prefer, no HUD. + if self.reason in RELIABLE_SOFT_REASONS or self._path_lead: + return False + if not self._engaged: + return False + if self._in_onroad_grace() or self._in_engage_grace(): + return False + return self._unhealthy_frames >= RELIABLE_ALERT_FRAMES + + def _in_onroad_grace(self) -> bool: + return self._frames < RELIABLE_ONROAD_GRACE_FRAMES + + def _in_engage_grace(self) -> bool: + if not self._engaged or self._engage_frame is None: + return False + return (self._frames - self._engage_frame) < RELIABLE_ENGAGE_GRACE_FRAMES + + def update(self, tracks: dict[int, Any] | None = None, + errors: Any = None, v_ego: float = 0.0, + timed_out: bool = False, ignore_hw_fail: bool = False, + engaged: bool = False) -> bool: + self._frames += 1 + engaged = bool(engaged) + if engaged and not self._engaged: + self._engage_frame = self._frames + self._engaged = engaged + + if self._override is not None: + self.healthy = self._override + self.reason = "" if self.healthy else "override" + self.sample_reason = self.reason + self._unhealthy_frames = 0 if self.healthy else self._unhealthy_frames + 1 + return self.healthy + + bad, reason = self._sample_bad(tracks or {}, errors, v_ego, timed_out, + ignore_hw_fail) + self.sample_reason = reason + if bad: + self._bad_streak += 1 + self._good_streak = 0 + immediate = reason in RELIABLE_HARD_REASONS + if immediate or self._bad_streak >= RELIABLE_FAIL_FRAMES: + self.healthy = False + self.reason = reason + else: + self._good_streak += 1 + self._bad_streak = 0 + if self._good_streak >= RELIABLE_OK_FRAMES: + self.healthy = True + self.reason = "" + + if self.healthy: + self._unhealthy_frames = 0 + else: + self._unhealthy_frames += 1 + return self.healthy + + def _sample_bad(self, tracks: dict[int, Any], errors: Any, v_ego: float, + timed_out: bool, ignore_hw_fail: bool) -> tuple[bool, str]: + if timed_out: + self._last_xy = {} + return True, "timeout" + if radar_errors_unhealthy(errors, ignore_hw_fail=ignore_hw_fail): + return True, "fault" + + snap: dict[int, tuple[float, float]] = {} + for tid, track in tracks.items(): + xy = _track_xy(track) + if xy is None: + continue + try: + snap[int(tid)] = xy + except (TypeError, ValueError): + continue + + if not snap: + # Keep last_xy across empty frames so a dropout streak can confirm. + # Low-speed empty (gravel crawl / open road) is log-only. + if float(v_ego) >= RELIABLE_MIN_VEGO_MS and self._last_xy: + return True, "dropout" + if self._last_xy or self._low_speed_empty: + self._last_xy = {} + self._low_speed_empty = True + return False, "dropout" + return False, "" + + self._low_speed_empty = False + + erratic = False + for tid, (d_rel, y_rel) in snap.items(): + prev = self._last_xy.get(tid) + if prev is None: + continue + if abs(y_rel - prev[1]) > RELIABLE_YREL_JUMP_M: + erratic = True + break + if abs(d_rel - prev[0]) > RELIABLE_DREL_JUMP_M: + erratic = True + break + self._last_xy = snap + if erratic: + return True, "erratic" + return False, "" + + +class RadarPreferGate: + """Default path-gated prefer. Requires Radar Enabled + reliability. + + NAPWiperSpeed is not consulted. Tests inject params, set_override(), + or set_enabled_override(). + """ + + def __init__(self, params: Any = None): + self._params = params + self._override: bool | None = None + self._enabled_override: bool | None = None + self._params_failed = False + self.enabled = True + self.reliable = True + self._alert = False + self.ignore_hw_fail = False + + def set_override(self, prefer: bool | None) -> None: + """Test hook. True/False forces prefer; None uses enabled+health.""" + self._override = None if prefer is None else bool(prefer) + + def set_enabled_override(self, enabled: bool | None) -> None: + self._enabled_override = None if enabled is None else bool(enabled) + + def set_reliable(self, ok: bool, alert: bool | None = None) -> None: + self.reliable = bool(ok) + self._alert = (not self.reliable) if alert is None else bool(alert) + + def _get_params(self) -> Any: + if self._params is not None or self._params_failed: + return self._params + try: + from openpilot.common.params import Params + self._params = Params() + except Exception: + self._params_failed = True + self._params = None + return self._params + + def _read_enabled(self) -> bool: + if self._enabled_override is not None: + return bool(self._enabled_override) + params = self._get_params() + if params is None: + # Unit tests / params unavailable: prefer is the default mode. + return True + return _param_bool(params, NAP_RADAR_ENABLED, default=False) + + def read_ignore_hw_fail(self) -> bool: + self.ignore_hw_fail = _param_bool(self._get_params(), NAP_RADAR_IGNORE_HW_FAIL, default=False) + return self.ignore_hw_fail + + def update(self) -> bool: + self.ignore_hw_fail = self.read_ignore_hw_fail() + self.enabled = self._read_enabled() + if self._override is not None: + return bool(self._override) + return self.enabled and self.reliable + + @property + def fallback_alert(self) -> bool: + """Enabled but prefer dropped and the HUD should flash. Not Off.""" + if self._override is False: + return False + return bool(self.enabled) and not bool(self.reliable) and bool(self._alert) + + +# Back-compat name used by older tests / RadarD wiring. +RainRadarGate = RadarPreferGate + + +def radar_hold_kinematics_ok(track: Any, max_yrel: float = RAIN_INCUMBENT_MAX_YREL_M, + v_ego: float = 0.0, + path_x: Sequence[float] | None = None, + path_y: Sequence[float] | None = None) -> bool: + """Live rain-hold candidate. Path + oncoming; yRel-only is not enough.""" + return radar_follow_ok(track, v_ego, path_x, path_y, max_lat=max_yrel) + + +def _track_id(obj: Any) -> int | None: + if obj is None: + return None + if isinstance(obj, dict): + val = obj.get("identifier", obj.get("radarTrackId")) + else: + val = getattr(obj, "identifier", None) + if val is None: + val = getattr(obj, "radarTrackId", None) + try: + return int(val) + except (TypeError, ValueError): + return None + + +def _track_drel(obj: Any) -> float | None: + if obj is None: + return None + if isinstance(obj, dict): + val = obj.get("dRel") + else: + val = getattr(obj, "dRel", None) + try: + f = float(val) + except (TypeError, ValueError): + return None + return f + + +def rain_far_hold_ok(track: Any, associated: Any | None = None, + vision_prob: float = 1.0) -> bool: + """Far incumbent-only hold needs confident vision; live association is enough. + + Does not blanket-reject on-path stationary. A path-associated stopped + car at 90 m stays valid. Unassociated low-prob furniture at 84–123 m does not. + """ + if track is None: + return False + if _track_id(associated) is not None and _track_id(associated) == _track_id(track): + return True + d_rel = _track_drel(track) + if d_rel is None: + return False + try: + prob = float(vision_prob) + except (TypeError, ValueError): + prob = 0.0 + if d_rel > RAIN_FAR_HOLD_DREL_M and prob < RAIN_FAR_HOLD_MIN_PROB: + return False + return True + + +def closest_inlane_radar(tracks: dict[int, Any], v_ego: float = 0.0, + path_x: Sequence[float] | None = None, + path_y: Sequence[float] | None = None) -> Any | None: + candidates = [ + track for track in tracks.values() + if radar_hold_kinematics_ok(track, RAIN_INLANE_YREL_M, v_ego, path_x, path_y) + ] + if not candidates: + return None + return min(candidates, key=lambda track: track.dRel) + + +def pick_rain_radar_track(associated: Any | None, tracks: dict[int, Any], + incumbent_id: int | None, v_ego: float = 0.0, + path_x: Sequence[float] | None = None, + path_y: Sequence[float] | None = None, + vision_prob: float = 1.0) -> Any | None: + """Hold a path-valid radar *association* while prefer is active. + + Not a wide-FOV radar prefer. A track is eligible only if it is the + current vision-associated lead (on the OP path) or the incumbent + association still on that path. Unassociated closest-in-lane radar + is not acquired — that is how left signs / oncoming became leadOne. + Switch only for a much closer *associated* path cut-in. + """ + incumbent = tracks.get(incumbent_id) if incumbent_id is not None else None + if incumbent is not None and not radar_hold_kinematics_ok( + incumbent, RAIN_INCUMBENT_MAX_YREL_M, v_ego, path_x, path_y): + incumbent = None + # Vision already path-nominated this track. Use the incumbent width so a + # 1.6–2.0 m associated lead is not dropped; oncoming / off-path still fail. + if associated is not None and not radar_hold_kinematics_ok( + associated, RAIN_INCUMBENT_MAX_YREL_M, v_ego, path_x, path_y): + associated = None + + if associated is not None and incumbent is not None: + if associated.identifier != incumbent.identifier: + chosen = associated if incumbent.dRel - associated.dRel >= RAIN_CUT_IN_GAP_M else incumbent + else: + chosen = associated + elif associated is not None: + chosen = associated + else: + chosen = incumbent + if chosen is not None and not rain_far_hold_ok(chosen, associated, vision_prob): + return None + return chosen diff --git a/selfdrive/controls/lib/roundabout_guide.py b/selfdrive/controls/lib/roundabout_guide.py new file mode 100644 index 00000000000000..d670c37288d026 --- /dev/null +++ b/selfdrive/controls/lib/roundabout_guide.py @@ -0,0 +1,889 @@ +"""Roundabout Steering Assist (Pre-AP, NAPRoundaboutAssist, default Off). + +Sep 28 (R126, R128): through the Soco / Dellwood / Jonathan Creek ring the model's curvature was a wide, slow S. Sep 29 the +curvature blend curled left at 1.8x the model and the driver overrode it. Sep 30: once latched the car FOLLOWS THE MAP'S LANE +CIRCLE; the blend, the left-curl ramp and the map-only auto-exit are gone. + + * Pose: 1 Hz GNSS (0.66 s latency, odometry-compensated) fused with wheel speed + yaw rate, local frame at the ring center. + * Entry (unchanged): farther than D_TURN_M from the ring edge the target can only hold / add right. Inside it the target is the + circle-follow curvature (1 s preview), circulation-side curl capped at 2.2 m/s² and held while > 3 mph over the ring speed. + * Latch: tangent in the band -> lane circle R -/+ half-width/2 (inner if on the island side of R and the pose is trustworthy). + * Ring (latched): the circle follower at that lane radius; output <= RING_CAP_RATIO (1.15) x the model's circulation-side + curvature and <= RING_A_LAT_MAX (2.2 m/s²), >= RING_FLOOR_RATIO x the model, correction slew RING_SLEW (0.035), whatever the pose. + * Release: only a held same-side stalk (StalkTipTurn.is_turn), a steering pull toward the exit, or an override (steeringPressed / + lat off). No map-only exit: with no blinker the car stays on the ring. Any held stalk / pressed / torque: weight 0 at once, the + driver always wins. ALC tips are suppressed while latched (NAPRoundaboutLatched Param). Camera edge limits still apply. + +Curvature sign is openpilot's (positive = right). Pure functions and one small state class, replayable without cereal. +""" +from __future__ import annotations + +import math +from collections import deque +from dataclasses import dataclass + +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.controls.lib import roundabout_ring_hold as RH +from openpilot.selfdrive.controls.lib.roundabout_ring_log import LOG_RAW_X, _interp_xy, raw_ring_summary # noqa: F401 +from openpilot.selfdrive.controls.lib.stalk_tip_turn import PARAM_RING_LATCHED, StalkTipTurn +from openpilot.selfdrive.mapd.roundabout import roundabout_target_ms +from openpilot.selfdrive.mapd.roundabout_map import RingGeometry, local_xy, roundabout_comfort_speed_ms + +PARAM_ROUNDABOUT_ASSIST = "NAPRoundaboutAssist" + +GPS_LATENCY_S = 0.66 # qcom gpsLocation vs logMonoTime, measured on the Sep 29 route (R126/R128 xcorr gave 0.9–1.0 s) +GPS_EXT_LATENCY_S = 0.2 # ublox gpsLocationExternal (not in the Sep 28 logs; unvalidated) +FIX_FRESH_S = 1.5 +FIX_STALE_S = 3.0 +HISTORY_S = 4.0 +INNOV_GOOD_M = 3.0 +INNOV_BAD_M = 8.0 +INNOV_JUMP_M = 15.0 +INNOV_POOR_M = 6.0 +SPEED_TOL_MS = 2.5 # GNSS speed lags ~1 s like position; loose check +POS_GAIN = 0.5 +HEADING_GAIN = 0.3 +GOOD_FIXES = 3 + +V_MIN = 2.0 # m/s +V_MAX = 13.5 # m/s (~30 mph); the ring slow-down should be well under this +ENGAGE_EDGE_M = 25.0 # start blending (weight ramps) this far from the ring edge +FULL_EDGE_M = 12.0 +D_TURN_M = 9.0 # hold the right entry until this far from the ring edge +LEAVE_EDGE_M = 60.0 # forget a finished ring once this far away +A_LAT_MAX = 3.0 # m/s^2: cap on the guide target away from the circulation direction (right entry) +A_LAT_CIRC_MAX = 2.2 # m/s^2: cap on the circulation-side (left on a CCW ring) transition target before the latch, at actual speed +FOLLOW_OMEGA = 0.7 # rad/s, circle-follow bandwidth +FOLLOW_ZETA = 0.9 +PRE_LATCH_HW = 0.75 # entry aims R + 0.75 hw (outer lane, away from the island) +OUT_SLEW = 0.035 # 1/m per s, max change of the blended output while active (poor / unverified pose) +OUT_SLEW_GOOD = 0.07 # ...with a good pose (R126/R128 fixtures need it to stay in the lane band) +HANDOFF_DK = 0.00005 # output must be this close to the model before handing back (well under one slew step) +PREVIEW_S = 1.0 # s, circle-follow preview (R126/R128 replay: 0.6-1.2 s trade inner vs outer drift) +TARGET_SLEW = 0.035 # 1/m per s, transition rate of the guide target (poor / unverified pose) +TARGET_SLEW_GOOD = 0.07 +W_MAX = 0.8 +W_RATE = 2.0 # phase weight ramp, 1/s +DK_MAX = 0.045 # max |correction| (1/m) +TANGENT_DEG = 25.0 +RING_CAP_RATIO = 1.15 # latched output <= this x the model's circulation-side curvature +RING_A_LAT_MAX = 2.2 # m/s²: lateral-accel cap of the latched output (the 18 mph ring itself needs ~3.0) +RING_CAP_FLOOR = 0.0 # 1/m: allowance on top of the ratio (0 = strictly 1.15x the model) +RING_SLEW = 0.035 # 1/m per s, correction slew once latched (any pose quality) +RING_REF_HOLD_S = 0.0 # cap reference = the model's circulation-side PEAK over this long; 0 = the model now (strict 1.15x) +RING_FLOOR_RATIO = 0.85 # ...and never less than this x the model's circulation-side curvature +LANE_CIRCLE_FRAC = 0.5 # lane circle = R -/+ this x half-width +PULL_TORQUE_NM = 1.5 # driver torque: either side = weight 0; toward the exit for PULL_RELEASE_S = release +PULL_RELEASE_S = 0.3 +OVERRIDE_S = 0.5 # steeringPressed (or lat off) this long: override, release +FAILSAFE_EDGE_M = 15.0 # safety only: far outside the ring band +POSE_LOST_S = 8.0 # safety only: no GNSS fix this long +EDGE_MARGIN_M = 0.3 +HALF_CAR_M = 0.98 +APPROACH_HALF_W_M = 4.0 +MATCH_COS = 0.9 # approach segment (stored in travel direction) within ~25° of the heading +MATCH_MAX_M = 12.0 +LANE_SNAP_M = 1.75 # one lane off the OSM centerline is not a GNSS error +BIAS_GAIN = 0.3 +BIAS_MAX_M = 8.0 +BEARING_ACC_UNRELIABLE_DEG = 30.0 # no latch / no inner clamp beyond this (Sep 29: 30-50°) +BIAS_UNRELIABLE_M = 2.0 +BEARING_ACC_POOR_DEG = 20.0 # poor: latch allowed on the outer lane circle only, slow pre-latch slews +BIAS_DRIFT_M = 1.0 # bias moved more than this over BIAS_WINDOW_S: poor pose +BIAS_LATCH_DRIFT_M = 1.0 # ...and more than this: not bias-consistent, do not latch yet +BIAS_WINDOW_S = 3.0 +SPEED_HOLD_MS = 3.0 * 0.44704 # hold the circulation-side curl until within 3 mph of the ring speed +LOG_PERIOD_S = 1.0 +RAW_LOG_EDGE_M = 60.0 # raw-model summary from this far from the ring edge until released +LOG_RAW_PERIOD_S = 0.8 # ~1.25 Hz raw-model summary near / in a ring (qlog via errorLogMessage) + + +def _interp(x: float, xp: tuple[float, float], fp: tuple[float, float]) -> float: + if x <= xp[0]: + return fp[0] + if x >= xp[1]: + return fp[1] + return fp[0] + (fp[1] - fp[0]) * (x - xp[0]) / (xp[1] - xp[0]) + + +def _hint_on_ring(hint) -> bool: + try: + return bool(hint is not None and getattr(hint, "on_roundabout", False)) + except Exception: + return False + + +def _wrap(a: float) -> float: + return (a + math.pi) % (2.0 * math.pi) - math.pi + + +def _rot(x: float, y: float, d: float) -> tuple[float, float]: + """Rotate a vector clockwise by d (bearing sense): heading b → b + d.""" + c, s = math.cos(d), math.sin(d) + return x * c + y * s, -x * s + y * c + + +class PoseTracker: + """GNSS + odometry pose in a local east/north frame (m) with bearing (rad, cw from north).""" + + def __init__(self) -> None: + self.origin: tuple[float, float] | None = None + self.reset() + + def reset(self) -> None: + self.xo = self.yo = self.psio = 0.0 + self.t = None + self.hist: deque = deque() + self.initialized = False + self.dpsi = 0.0 + self.tx = self.ty = 0.0 + self.innov = INNOV_BAD_M + self.n_good = 0 + self.last_fix_t = -1e9 + self.bacc = 0.0 # last reported bearing accuracy (deg); 0 = unknown + + def set_origin(self, lat: float, lon: float) -> None: + if self.origin is None or abs(self.origin[0] - lat) > 1e-7 or abs(self.origin[1] - lon) > 1e-7: + self.origin = (float(lat), float(lon)) + keep_hist, keep_t = self.hist, self.t + xo, yo, psio = self.xo, self.yo, self.psio + self.reset() + self.hist, self.t, self.xo, self.yo, self.psio = keep_hist, keep_t, xo, yo, psio + + def predict(self, t: float, v: float, yaw_rate: float) -> None: + if not (math.isfinite(t) and math.isfinite(v) and math.isfinite(yaw_rate)): + return # a NaN would poison the odometry for the rest of the drive (seen in R126 qlog yaw) + if self.t is not None: + dt = min(max(t - self.t, 0.0), 0.2) + self.psio += yaw_rate * dt + self.xo += v * math.sin(self.psio) * dt + self.yo += v * math.cos(self.psio) * dt + self.t = t + self.hist.append((t, self.xo, self.yo, self.psio, v)) + while self.hist and self.hist[0][0] < t - HISTORY_S: + self.hist.popleft() + + def _odo_at(self, t: float): + h = self.hist + if h and h[-1][0] < t <= h[-1][0] + 0.05: + t = h[-1][0] # fix processed just before this cycle's predict + if not h or t < h[0][0] or t > h[-1][0]: + return None + lo, hi = 0, len(h) - 1 + while hi - lo > 1: + mid = (lo + hi) // 2 + if h[mid][0] <= t: + lo = mid + else: + hi = mid + a, b = h[lo], h[hi] + f = 0.0 if b[0] <= a[0] else (t - a[0]) / (b[0] - a[0]) + return tuple(a[k] + f * (b[k] - a[k]) for k in range(1, 5)) + + def _world(self, xo: float, yo: float) -> tuple[float, float]: + x, y = _rot(xo, yo, self.dpsi) + return x + self.tx, y + self.ty + + def fix(self, t_log: float, lat: float, lon: float, bearing_deg: float | None, + gps_speed: float | None = None, bearing_acc_deg: float | None = None, + latency_s: float = GPS_LATENCY_S) -> None: + if self.origin is None or not all(math.isfinite(z) for z in (t_log, lat, lon)): + return + self.bacc = float(bearing_acc_deg) if (bearing_acc_deg is not None and math.isfinite(bearing_acc_deg) + and bearing_acc_deg > 0.0) else 0.0 + odo = self._odo_at(t_log - latency_s) + if odo is None: + return + xo, yo, psio, v_fix = odo + fx, fy = local_xy(lat, lon, self.origin[0], self.origin[1]) + b_ok = (bearing_deg is not None and math.isfinite(bearing_deg) and v_fix > 3.0 + and (bearing_acc_deg is None or bearing_acc_deg <= 0.0 or bearing_acc_deg < 10.0)) + speed_ok = gps_speed is None or not math.isfinite(gps_speed) or abs(gps_speed - v_fix) < max(SPEED_TOL_MS, 0.25 * v_fix) + if not self.initialized: + if not b_ok: + return + self.dpsi = _wrap(math.radians(bearing_deg) - psio) + wx, wy = _rot(xo, yo, self.dpsi) + self.tx, self.ty = fx - wx, fy - wy + self.initialized = True + self.innov = INNOV_GOOD_M + self.n_good = 1 if speed_ok else 0 + self.last_fix_t = t_log + return + px, py = self._world(xo, yo) + ex, ey = fx - px, fy - py + e = math.hypot(ex, ey) + if e > INNOV_JUMP_M: + # GNSS jump or a bad track: re-anchor, confidence starts over. + self.initialized = False + self.n_good = 0 + self.innov = INNOV_BAD_M + self.fix(t_log, lat, lon, bearing_deg, gps_speed, bearing_acc_deg, latency_s) + self.n_good = 0 + return + self.innov = 0.7 * self.innov + 0.3 * e + ax, ay = px + POS_GAIN * ex, py + POS_GAIN * ey + if b_ok: + self.dpsi += HEADING_GAIN * _wrap(math.radians(bearing_deg) - (psio + self.dpsi)) + wx, wy = _rot(xo, yo, self.dpsi) + self.tx, self.ty = ax - wx, ay - wy + # One poor fix costs two good ones (a hard reset made the assist drop out mid-ring on R126). + self.n_good = self.n_good + 1 if (e < INNOV_POOR_M and speed_ok) else max(self.n_good - 2, 0) + self.last_fix_t = t_log + + def pose(self) -> tuple[float, float, float] | None: + if not self.initialized: + return None + x, y = self._world(self.xo, self.yo) + return x, y, self.psio + self.dpsi + + def confidence(self, t: float) -> float: + if not self.initialized: + return 0.0 + c_fix = _interp(t - self.last_fix_t, (FIX_FRESH_S, FIX_STALE_S), (1.0, 0.0)) + c_innov = _interp(self.innov, (INNOV_GOOD_M, INNOV_BAD_M), (1.0, 0.0)) + c_count = min(1.0, self.n_good / GOOD_FIXES) + return min(c_fix, c_innov, c_count) + + +def _arc_ahead(x: float, y: float, psi: float, v: float, yaw_rate: float, dt: float) -> tuple[float, float, float]: + """Pose after dt s at constant speed and yaw rate (x east, y north, psi cw from north).""" + n = 5 + h = dt / n + for _ in range(n): + psi_m = psi + 0.5 * yaw_rate * h + x += v * math.sin(psi_m) * h + y += v * math.cos(psi_m) * h + psi += yaw_rate * h + return x, y, psi + + +def circle_follow_curvature(x: float, y: float, psi: float, v: float, r_ref: float, ccw: bool) -> float: + """Curvature (positive right) that follows the circle r_ref (center 0,0) in the circulation direction. + + Feed-forward 1/r_ref plus a critically-damped correction on radial offset + e = r - r_ref and outward heading angle phi (radial speed = v sin phi): + k_center = 1/r_ref + (2 ZETA OMEGA v sin(phi) + OMEGA^2 e) / v^2 + which makes e'' + 2 ZETA OMEGA e' + OMEGA^2 e ~= 0. Moving against the + circulation counts as fully outward (turn toward the ring direction). + """ + r = math.hypot(x, y) + if r < 1e-3 or r_ref <= 0.0: + return 0.0 + sense = 1.0 if ccw else -1.0 + hx, hy = math.sin(psi), math.cos(psi) # heading unit vector (x east, y north) + radial = (hx * x + hy * y) / r # sin(phi), outward positive + tangential = sense * (-hx * y + hy * x) / r # along the circulation + sin_phi = radial if tangential > 0.0 else math.copysign(1.0, radial if radial != 0.0 else 1.0) + vv = max(v, 3.0) + k_center = 1.0 / r_ref + (2.0 * FOLLOW_ZETA * FOLLOW_OMEGA * vv * sin_phi + FOLLOW_OMEGA ** 2 * (r - r_ref)) / (vv * vv) + return -sense * k_center + + +def _dist_to_polyline(x: float, y: float, pts: list[tuple[float, float]]) -> float: + best = 1e9 + for (ax, ay), (bx, by) in zip(pts, pts[1:], strict=False): + dx, dy = bx - ax, by - ay + L2 = dx * dx + dy * dy + f = 0.0 if L2 <= 1e-9 else max(0.0, min(1.0, ((x - ax) * dx + (y - ay) * dy) / L2)) + best = min(best, math.hypot(x - (ax + f * dx), y - (ay + f * dy))) + return best + + +def map_match_confidence(ring: RingGeometry, x: float, y: float) -> float: + """1 on the mapped ring band / an approach road, 0 once ≥ 4 m outside every mapped road.""" + r = math.hypot(x, y) + excess = max(0.0, abs(r - ring.radius_m) - ring.half_width_m) + on_approach_side = r > ring.radius_m + ring.half_width_m + if on_approach_side: + if ring.approaches: + d_app = min(_dist_to_polyline(x, y, a) for a in ring.approaches if len(a) >= 2) + excess = min(excess, max(0.0, d_app - APPROACH_HALF_W_M)) + else: + return 0.7 * _interp(excess, (1.0, 45.0), (1.0, 0.0)) if excess < 45.0 else 0.0 + return _interp(excess, (1.0, 5.0), (1.0, 0.0)) + + +def map_match_offset(ring: RingGeometry, x: float, y: float, psi: float) -> tuple[float, float, float] | None: + """GNSS offset from the mapped road that no lane can explain: (nx, ny, excess_m) or None. + + On an approach road: signed perpendicular offset from the nearest roughly + parallel segment, minus LANE_SNAP_M (a car can legitimately be one lane off + the OSM centerline). On the ring: radial offset beyond the lane centers. + """ + r = math.hypot(x, y) + if r < 8.0: + return None + R, hw = ring.radius_m, ring.half_width_m + if r <= R + hw + 2.0: + e = r - R + ex = math.copysign(max(abs(e) - 0.5 * hw, 0.0), e) + return x / r, y / r, ex + best = None + hx, hy = math.sin(psi), math.cos(psi) + for pts in ring.approaches: + for (ax, ay), (bx, by) in zip(pts, pts[1:], strict=False): + dx, dy = bx - ax, by - ay + L = math.hypot(dx, dy) + if L < 1e-3 or (dx * hx + dy * hy) / L < MATCH_COS: # travel direction (see ring_geometry) + continue + f = max(0.0, min(1.0, ((x - ax) * dx + (y - ay) * dy) / (L * L))) + px, py = ax + f * dx, ay + f * dy + d = math.hypot(x - px, y - py) + if d <= MATCH_MAX_M and (best is None or d < best[0]): + nx, ny = dy / L, -dx / L # right-hand normal of the segment + best = (d, nx, ny, (x - px) * nx + (y - py) * ny) + if best is None: + return None + _, nx, ny, e = best + return nx, ny, math.copysign(max(abs(e) - LANE_SNAP_M, 0.0), e) + + +def ring_confidence(ring: RingGeometry) -> float: + c = min(_interp(ring.rms_m, (1.0, 3.0), (1.0, 0.0)), _interp(ring.coverage_deg, (200.0, 300.0), (0.0, 1.0))) + return c if ring.tagged else 0.7 * c + + +@dataclass +class EdgeInfo: + """Camera lateral bounds at lookahead x (m). y positive right (device frame).""" + x: float + path_y: float + left_y: float | None = None + right_y: float | None = None + + +def limit_correction_by_edges(dk: float, edges: EdgeInfo | None) -> float: + """Scale the correction so the predicted path keeps a margin to lane lines / road edges.""" + if edges is None or abs(dk) < 1e-9: + return dk + x = max(edges.x, 3.0) + dy = 0.5 * dk * x * x + margin = HALF_CAR_M + EDGE_MARGIN_M + if dk < 0.0 and edges.left_y is not None: + allowed = edges.left_y + margin - edges.path_y # most-negative lateral move allowed + dy = max(dy, min(0.0, allowed)) + if dk > 0.0 and edges.right_y is not None: + allowed = edges.right_y - margin - edges.path_y + dy = min(dy, max(0.0, allowed)) + return 2.0 * dy / (x * x) + + +def lat_limited(k: float, v: float, sense: float) -> float: + """Clip a target curvature: A_LAT_CIRC_MAX toward the circulation side (left on CCW), A_LAT_MAX away from it (right entry).""" + v2 = max(v * v, 1.0) + k_circ, k_other = A_LAT_CIRC_MAX / v2, A_LAT_MAX / v2 + lo, hi = (-k_circ, k_other) if sense > 0.0 else (-k_other, k_circ) + return min(max(k, lo), hi) + + +def hold_curl(k_raw: float, model_k: float, sense: float) -> float: + """Never add more circulation-side curvature than the model asks for (hold / add right only on CCW).""" + return max(model_k, k_raw) if sense > 0.0 else min(model_k, k_raw) + + +def ring_cap(ref_k: float, model_k: float, v: float, sense: float) -> float: + """Most circulation-side curvature (-sense * k) the latched output may carry: RING_CAP_RATIO x ref_k (+ floor), limited to + RING_A_LAT_MAX at the actual speed, never below the model itself. ref_k = the model's circulation-side peak over RING_REF_HOLD_S.""" + s_model = -sense * model_k + if s_model <= 0.0: + return s_model # model not curving with the circulation: the assist never steers against it + return max(s_model, min(RING_CAP_RATIO * max(ref_k, s_model) + RING_CAP_FLOOR, RING_A_LAT_MAX / max(v * v, 1.0))) + + +def ring_floor(ref_k: float, v: float) -> float: + """Least circulation-side curvature the latched output may carry: RING_FLOOR_RATIO x ref_k.""" + return min(RING_FLOOR_RATIO * ref_k, RING_A_LAT_MAX / max(v * v, 1.0)) if ref_k > 0.0 else -1e9 + + +@dataclass +class DriverInput: + """What the driver is doing with the wheel / stalk (controlsd -> guide).""" + stalk_dir: int = 0 # turnSignalStalkState: 1 left, 2 right + stalk_held: bool = False # StalkTipTurn.is_turn: held > 0.40 s (driver turn, not an ALC tip) + pressed: bool = False # carState.steeringPressed + torque: float = 0.0 # carState.steeringTorque (+ left) + + +def pose_quality(bearing_acc_deg: float, bias_m: float, bias_drift_m: float, innov_m: float) -> tuple[bool, bool]: + """(unreliable, poor). Unreliable: never latch (bearing accuracy > 30°, or bias > 2 m with bearing > 20°: Sep 29 11:57:48). + Poor: latch on the outer lane only, slow pre-latch slews.""" + unreliable = bearing_acc_deg > BEARING_ACC_UNRELIABLE_DEG or \ + (bias_m > BIAS_UNRELIABLE_M and bearing_acc_deg > BEARING_ACC_POOR_DEG) + poor = unreliable or bearing_acc_deg > BEARING_ACC_POOR_DEG or innov_m > INNOV_POOR_M + return unreliable, poor + + +CAP_FALL = 0.3 # x RING_SLEW: how fast the widened ring cap is given up +IDLE, ACTIVE, EXITING, DONE = "idle", "active", "exiting", "done" + + +class RoundaboutGuide: + def __init__(self) -> None: + self.pose = PoseTracker() + self.ring: RingGeometry | None = None + self.ring_v = 0.0 + self.exits: list[float] = [] + self.reset_state() + self.debug: dict = {} + + def reset_state(self) -> None: + self.phase = IDLE + self.phase_w = 0.0 + self.k_tgt = None + self.latched = False + self.r_ref = None + self.theta_entry = 0.0 + self.travel = 0.0 + self.r_lane = None + self.k_ref = 0.0 + self.model_hist: deque = deque() + self.release = "" + self.override_s = 0.0 + self.pull_s = 0.0 + self.drv_s = 0.0 + self.cap_extra = 0.0 + self.last_t = None + self.turning = False + self.bias = (0.0, 0.0) + self.dk_out = 0.0 + self.prev_out: float | None = None + self.prev_model: float | None = None + self.bias_hist: deque = deque() + self.latch_t: float | None = None + self.latch_poor = False + self.d_edge: float | None = None + self.events: list[str] = [] + self._blocked = "" + self._holding = False + + def _ev(self, msg: str) -> None: + if len(self.events) < 50: + self.events.append(msg) + + def set_ring(self, ring: RingGeometry | None) -> None: + if ring is None: + return + if self.ring is not None and set(ring.way_ids) == set(self.ring.way_ids): + return + self.ring = ring + self.exits = RH.exit_angles(ring) + self.ring_v = float(roundabout_target_ms(roundabout_comfort_speed_ms(ring.radius_m, ring.lanes, ring.maxspeed_ms))) + self.pose.set_origin(ring.lat, ring.lon) + self.reset_state() + + def has_way(self, way_id: int) -> bool: + return self.ring is not None and int(way_id) in self.ring.way_ids + + def gnss(self, t_log: float, lat: float, lon: float, bearing_deg: float | None, + speed: float | None = None, bearing_acc_deg: float | None = None, + latency_s: float = GPS_LATENCY_S) -> None: + if self.pose.origin is None: + self.pose.set_origin(lat, lon) + self.pose.fix(t_log, lat, lon, bearing_deg, speed, bearing_acc_deg, latency_s) + self._update_bias() + + def _update_bias(self) -> None: + """Map-matched GNSS bias: the part of the offset from the mapped road no lane explains.""" + raw = self.pose.pose() + if self.ring is None or raw is None or self.pose.n_good < 1: + return + m = map_match_offset(self.ring, raw[0], raw[1], raw[2]) + if m is None: + return + nx, ny, ex = m + bx, by = self.bias + bn = bx * nx + by * ny + bn += BIAS_GAIN * (ex - bn) + bx, by = bx + (bn - (bx * nx + by * ny)) * nx, by + (bn - (bx * nx + by * ny)) * ny + mag = math.hypot(bx, by) + if mag > BIAS_MAX_M: + bx, by = bx * BIAS_MAX_M / mag, by * BIAS_MAX_M / mag + self.bias = (bx, by) + + def _release_reason(self, drv: DriverInput, sense: float, lat_active: bool, dt: float, v: float, d_edge: float, + fix_age: float, theta: float = 0.0) -> str: + """Why a latched ring is released ('' = stay). Only the driver (stalk / steering pull / override) or a hard + failsafe: there is no map-only exit, with no blinker the car stays on the ring.""" + exit_dir = 2 if sense > 0.0 else 1 # exit side: right on a CCW ring + if drv.stalk_held and drv.stalk_dir == exit_dir: + return "stalk" + if drv.stalk_dir == exit_dir and RH.on_exit_arm(theta, sense, self.exits, d_edge): + return "exit_blinker" # blinker on while on the exit arm: hand back to the model + self.pull_s = self.pull_s + dt if -sense * drv.torque >= PULL_TORQUE_NM else 0.0 + if self.pull_s >= PULL_RELEASE_S: + return "pull" + hands = RH.counts_as_press(drv.pressed, drv.torque, sense) or (not lat_active and not drv.stalk_held) + self.override_s = self.override_s + dt if hands else 0.0 + if self.override_s >= OVERRIDE_S: + return "override" + if v > V_MAX + 2.0: + return "speed" + if d_edge > FAILSAFE_EDGE_M: + return "far_from_ring" + if fix_age > POSE_LOST_S: + return "pose_lost" + return "" + + def corrected_pose(self) -> tuple[float, float, float] | None: + raw = self.pose.pose() + if raw is None: + return None + return raw[0] - self.bias[0], raw[1] - self.bias[1], raw[2] + + def _passthrough(self, model_k: float) -> float: + self.dk_out = 0.0 + self.prev_out = self.prev_model = None + return model_k + + def update(self, t: float, v: float, yaw_rate: float, model_k: float, *, + enabled: bool, lat_active: bool, edges: EdgeInfo | None = None, + driver: DriverInput | None = None) -> float: + """Return the (possibly blended) curvature. Exactly model_k whenever inactive.""" + dt = 0.0 if self.last_t is None else min(max(t - self.last_t, 0.0), 0.2) + self.last_t = t + self.pose.predict(t, v, yaw_rate) + self.debug = {"phase": self.phase, "w": 0.0} + model_k = float(model_k) + ring = self.ring + pose = self.corrected_pose() + if not enabled or ring is None or pose is None or not all(math.isfinite(z) for z in (model_k, v, yaw_rate)): + self.phase_w, self.k_tgt, self.dk_out = 0.0, None, 0.0 + return self._passthrough(model_k) + x, y, psi = pose + R, hw = ring.radius_m, ring.half_width_m + r = math.hypot(x, y) + d_edge = r - (R + hw) + self.d_edge = d_edge + if self.phase == DONE: + if d_edge > LEAVE_EDGE_M: + self.reset_state() + return self._passthrough(model_k) + theta = math.atan2(y, x) + sense = 1.0 if ring.ccw else -1.0 + # Tangent (circulation) bearing vs heading. + tx, ty = -sense * y / max(r, 1e-3), sense * x / max(r, 1e-3) + tan_brg = math.atan2(tx, ty) + align = abs(math.degrees(_wrap(psi - tan_brg))) + radial_v = v * (math.sin(psi) * x + math.cos(psi) * y) / max(r, 1e-3) + + if self.phase == IDLE: + if d_edge <= ENGAGE_EDGE_M and radial_v < -0.5 and V_MIN <= v <= V_MAX: + self.phase = ACTIVE + else: + self.phase_w, self.k_tgt, self.dk_out = 0.0, None, 0.0 + return self._passthrough(model_k) + + # Pose quality: an unreliable pose (bearing accuracy > 30° / bias > 2 m) or a still-moving bias never latches. + bias_m = math.hypot(*self.bias) + self.bias_hist.append((t, self.bias[0], self.bias[1])) + while self.bias_hist and self.bias_hist[0][0] < t - BIAS_WINDOW_S: + self.bias_hist.popleft() + drift = math.hypot(self.bias[0] - self.bias_hist[0][1], self.bias[1] - self.bias_hist[0][2]) + unreliable, poor = pose_quality(self.pose.bacc, bias_m, drift, self.pose.innov) + can_latch = not unreliable and drift <= BIAS_LATCH_DRIFT_M + ready = RH.latch_ready(align, d_edge, TANGENT_DEG) + if not self.latched and ready and not can_latch: + kind = "unreliable" if unreliable else "bias_unsettled" + if kind != self._blocked: + self._blocked = kind + self._ev(f"latch blocked {kind} bacc={self.pose.bacc:.0f} bias={bias_m:.1f} drift={drift:.1f} r={r:.1f} d_edge={d_edge:.1f}") + if not self.latched and ready and can_latch: + self.latched = True + self.latch_t = t + self.latch_poor = poor + inner = r <= R and not (poor or bias_m > BIAS_UNRELIABLE_M) # doubtful pose: never the inner lane + if inner: + self.r_lane = R - LANE_CIRCLE_FRAC * hw + else: # doubtful pose: the outer lane circle if the car reads outside R, else the center line (never the island side) + self.r_lane = R + LANE_CIRCLE_FRAC * hw if r > R else R + self.r_ref = self.r_lane + self.theta_entry = theta + self.travel = 0.0 + self._ev(f"latched r={r:.1f} r_ref={self.r_ref:.1f} bias={bias_m:.1f} bacc={self.pose.bacc:.0f} poor={int(poor)} v={v:.1f}") + elif self.latched: + self.travel += math.degrees(sense * _wrap(theta - self.theta_entry)) + self.theta_entry = theta + self.model_hist.append((t, -sense * model_k)) + while self.model_hist and self.model_hist[0][0] < t - RING_REF_HOLD_S: + self.model_hist.popleft() + self.k_ref = max(0.0, max(m for _, m in self.model_hist)) + drv = driver or DriverInput() + drv_active, self.drv_s = RH.driver_wins(drv.stalk_held, drv.pressed, drv.torque, sense, self.drv_s, dt) + if self.latched and self.phase != EXITING: + why = self._release_reason(drv, sense, lat_active, dt, v, d_edge, t - self.pose.last_fix_t, theta) + if why: + self.release = why + self._ev(f"released {why} r={r:.1f} travel={self.travel:.0f} v={v:.1f}") + if why in ("stalk", "pull", "override", "exit_blinker"): # the driver: hand back at once + self.phase, self.k_tgt, self.phase_w = DONE, None, 0.0 + return self._passthrough(model_k) + self.phase = EXITING # safety release: fade to the model (W_RATE, RING_SLEW) + r_ref = self.r_ref if self.latched else R + PRE_LATCH_HW * hw # outer part of the ring until tangent, then hold the lane + # Evaluate the circle follower at the pose PREVIEW_S ahead (constant current yaw rate): leads the + # target slew + actuator delay so the left transition starts before the car is already tangent. + px, py, ppsi = _arc_ahead(x, y, psi, v, yaw_rate, PREVIEW_S) + k_pp = circle_follow_curvature(px, py, ppsi, v, r_ref, ring.ccw) + + if d_edge > D_TURN_M and not self.turning: + k_raw = max(model_k, k_pp) # hold / add right only; never an early left + phase_target = _interp(d_edge, (FULL_EDGE_M, ENGAGE_EDGE_M), (1.0, 0.0)) + else: + self.turning = True + k_raw = k_pp + # Unreliable pose and not latched: fade the assist out, the model keeps this pass (Sep 29 11:57:48). + phase_target = 0.0 if (unreliable and not self.latched) else 1.0 + lim, plain = (0.0, 0.0), True + if self.latched: + # Circulating: command the lane circle, within [ring_floor, ring_cap] whatever the pose quality. + holding_now = v > self.ring_v + SPEED_HOLD_MS + plain = drv.stalk_dir == (2 if sense > 0.0 else 1) or d_edge > RH.EXIT_ARM_EDGE_M or holding_now # the old 1.15x-model limits + lim = RH.ring_limits(ring_cap(self.k_ref, model_k, v, sense), ring_floor(self.k_ref, v), -sense * model_k, -sense * k_pp, v, + RING_A_LAT_MAX, RH.in_exit_window(theta, sense, self.exits), plain) + s_cmd = max(min(-sense * k_pp, lim[0]), lim[1]) + k_raw = -sense * s_cmd + else: + k_raw = lat_limited(k_raw, v, sense) + holding = v > self.ring_v + SPEED_HOLD_MS + if holding: + k_raw = hold_curl(k_raw, model_k, sense) + if holding != self._holding: + self._holding = holding + self._ev(f"curl {'held' if holding else 'released'} v={v:.1f} ring_v={self.ring_v:.1f}") + + if self.phase == ACTIVE and not self.latched: + leaving = d_edge > 0.0 and radial_v > 1.0 and self.turning + if leaving or not (V_MIN <= v <= V_MAX + 2.0) or d_edge > ENGAGE_EDGE_M + 10.0: + self.phase = EXITING + if self.phase == EXITING: + phase_target = 0.0 + + step = W_RATE * dt + self.phase_w = min(max(phase_target, self.phase_w - step), self.phase_w + step) + + slew = RING_SLEW if self.latched else (TARGET_SLEW if poor else TARGET_SLEW_GOOD) + if self.k_tgt is None or not lat_active: + self.k_tgt = model_k + else: + self.k_tgt += min(max(k_raw - self.k_tgt, -slew * dt), slew * dt) + + c_bias = _interp(bias_m, (3.0, BIAS_MAX_M), (1.0, 0.4)) + conf = min(self.pose.confidence(t), map_match_confidence(ring, x, y), ring_confidence(ring), c_bias) + w = self.phase_w if self.latched else W_MAX * conf * self.phase_w # latched: the cap, not the confidence, bounds the assist + if drv_active: + w = 0.0 + self.debug = {"phase": self.phase, "w": w, "conf": conf, "bias": bias_m, "bacc": self.pose.bacc, "poor": poor, + "unreliable": unreliable, "hold": holding, "innov": self.pose.innov, + "n_good": self.pose.n_good, "r": r, "d_edge": d_edge, "k_pp": k_pp, "k_tgt": self.k_tgt, "r_ref": r_ref, + "align": align, "travel": self.travel, "latched": self.latched, "drv": int(drv_active)} + if not lat_active or drv_active: + # Driver has the wheel / the stalk (or lateral is off): no correction, nothing carried over. + self.dk_out = 0.0 + if self.phase == EXITING and self.phase_w <= 0.0: + self.phase, self.k_tgt = DONE, None + return self._passthrough(model_k) + dk = w * (self.k_tgt - model_k) + dk = min(max(dk, -DK_MAX), DK_MAX) + if self.latched and self.phase != EXITING: + # Ring cap / floor on what is actually sent. Over the ring speed the curl hold wins (no floor, nothing above the model's). + floor = -1e9 if holding else lim[1] + base = -sense * model_k if holding else ring_cap(self.k_ref, model_k, v, sense) + self.cap_extra, cap = RH.step_cap(self.cap_extra, base, lim[0], v, RING_A_LAT_MAX, RING_SLEW * dt, CAP_FALL, plain, holding) + dk = -sense * min(max(-sense * (model_k + dk), floor), cap) - model_k + # The correction moves at <= RING_SLEW once latched: an over-cap entry curl unwinds at the slew, no step. + oslew = RING_SLEW if self.latched else (OUT_SLEW if poor else OUT_SLEW_GOOD) + self.dk_out += min(max(dk - self.dk_out, -oslew * dt), oslew * dt) + # ...and the sum never moves faster than max(slew, the model's own rate). + if self.prev_out is not None and self.prev_model is not None: + allowed = max(oslew * dt, abs(model_k - self.prev_model)) + out = min(max(model_k + self.dk_out, self.prev_out - allowed), self.prev_out + allowed) + self.dk_out = out - model_k + if self.latched and self.phase != EXITING and -sense * model_k > 0.0: + # Hard clamp while the model curves with the circulation (the slews can lag a model that drops): never above the cap. + out = -sense * min(-sense * (model_k + self.dk_out), cap) + self.dk_out = out - model_k + if self.latched and self.phase != EXITING and self.cap_extra > 0.0: + a_cap = RING_A_LAT_MAX / max(v * v, 1.0) # the model follows the exit branch (right) while the guide holds the circle: 2.2 m/s² still binds + self.dk_out = -sense * min(-sense * (model_k + self.dk_out), max(a_cap, -sense * model_k)) - model_k + self.prev_model = model_k + self.prev_out = model_k + self.dk_out + if self.phase == EXITING and self.phase_w <= 0.0 and abs(self.dk_out) < HANDOFF_DK: + self.phase, self.k_tgt, self.dk_out = DONE, None, 0.0 + return self._passthrough(model_k) + # Camera authority on lane lines / road edges applies to what is actually sent, immediately. + return model_k + limit_correction_by_edges(self.dk_out, edges) + + +# -------------------------------------------------------------------------------------------- +# controlsd glue (kept here so it is testable with a fake SubMaster / Params) + +HINT_HOLD_S = 10.0 +PARAM_READ_FRAMES = 100 # ~1 s at 100 Hz +LOOK_T_S = 1.0 + + +def edges_from_model(model_v2, v_ego: float) -> EdgeInfo | None: + """Nearest camera bound on each side of the model path at ~1 s (device frame, y right).""" + try: + x = min(max(float(v_ego) * LOOK_T_S, 5.0), 20.0) + path_y = _interp_xy(model_v2.position.x, model_v2.position.y, x) + if path_y is None: + return None + lefts, rights = [], [] + lines, probs = model_v2.laneLines, model_v2.laneLineProbs + for i in (1, 2): + if len(lines) > i and len(probs) > i and float(probs[i]) > 0.5: + yy = _interp_xy(lines[i].x, lines[i].y, x) + if yy is not None: + (lefts if yy < path_y else rights).append(yy) + edges, stds = model_v2.roadEdges, model_v2.roadEdgeStds + for i in (0, 1): + if len(edges) > i and len(stds) > i and float(stds[i]) < 1.0: + yy = _interp_xy(edges[i].x, edges[i].y, x) + if yy is not None: + (lefts if yy < path_y else rights).append(yy) + return EdgeInfo(x=x, path_y=path_y, left_y=max(lefts) if lefts else None, + right_y=min(rights) if rights else None) + except Exception: + return None + + +class RoundaboutAssist: + """Pre-AP controlsd wrapper: toggle, GNSS feed, ring param, hint gating, edges, driver inputs, ring logging.""" + + def __init__(self, preap: bool, params=None) -> None: + self.preap = bool(preap) + self.params = params + self.guide = RoundaboutGuide() + self.enabled = False + self._frame = -1 + self._last_hint_t = -1e9 + self._last_ring_read_t = -1e9 + self._gps_frames: dict[str, int] = {} + self._last_log_t = -1e9 + self._last_raw_t = -1e9 + self._last_t: float | None = None + self._stalk = StalkTipTurn() + self._latched_param = False + self.active = False + + @property + def latched(self) -> bool: + return bool(self.guide.latched and self.guide.phase != DONE) + + def _read_toggle(self) -> None: + if self._frame < 0 or self._frame >= PARAM_READ_FRAMES: + self._frame = 0 + on = False + if self.params is not None: + try: + on = bool(self.params.get_bool(PARAM_ROUNDABOUT_ASSIST)) + except Exception: + on = False + self.enabled = on + self._frame += 1 + + def _load_ring(self, t: float, way_id: int) -> None: + if self.params is None or self.guide.has_way(way_id) or t - self._last_ring_read_t < 1.0: + return + self._last_ring_read_t = t + try: + from openpilot.selfdrive.mapd.roundabout_map import PARAM_RING + ring = RingGeometry.from_json(self.params.get(PARAM_RING)) + except Exception: + ring = None + if ring is not None and int(way_id) in ring.way_ids: + self.guide.set_ring(ring) + + def _feed_gnss(self, sm) -> None: + for sock, lat_s in (("gpsLocationExternal", GPS_EXT_LATENCY_S), ("gpsLocation", GPS_LATENCY_S)): + try: + frame = int(sm.recv_frame[sock]) + except Exception: + continue + if frame <= 0 or frame == self._gps_frames.get(sock): + continue + self._gps_frames[sock] = frame + g = sm[sock] + lat, lon = float(g.latitude), float(g.longitude) + if not (math.isfinite(lat) and math.isfinite(lon)) or (abs(lat) < 1e-6 and abs(lon) < 1e-6): + continue + if hasattr(g, "hasFix") and not bool(g.hasFix): + continue + self.guide.gnss(float(sm.logMonoTime[sock]) * 1e-9, lat, lon, float(g.bearingDeg), float(g.speed), + float(getattr(g, "bearingAccuracyDeg", 0.0) or 0.0), lat_s) + return # one source per cycle; external preferred when present + + def _sync_latched_param(self, on_ring: bool = False) -> None: + """modeld reads this (a different process) to suppress ALC tips while the car is on the ring. + + Oct 13: also set whenever the map says we are on a roundabout, assist on + or off, so the exit blinker in a ring never arms an automatic lane change. + """ + latched = bool(self.latched or on_ring) + if latched == self._latched_param: + return + self._latched_param = latched + try: + self.params.put_bool(PARAM_RING_LATCHED, latched) + except Exception: + pass + + def update(self, sm, *, t: float, v_ego: float, yaw_rate: float, model_k: float, lat_active: bool, + maneuver_active: bool, lane_change_active: bool, hint=None, model_v2=None, + stalk_state: int = 0, steering_pressed: bool = False, steering_torque: float = 0.0) -> float: + """Return the curvature to use in place of model_k (identical when Off / non-Pre-AP / idle).""" + self._read_toggle() + self.active = False + if not self.preap: + return float(model_k) + if not self.enabled: + self.guide.update(t, v_ego, yaw_rate, model_k, enabled=False, lat_active=False) + if self.guide.latched: + self.guide.reset_state() # toggled Off on the ring: nothing carried over + self._sync_latched_param(on_ring=_hint_on_ring(hint)) + return float(model_k) + dt = 0.0 if self._last_t is None else min(max(t - self._last_t, 0.0), 0.1) + self._last_t = t + self._stalk.update(stalk_state, dt) + driver = DriverInput(stalk_dir=int(self._stalk.direction), stalk_held=bool(self._stalk.is_turn), + pressed=bool(steering_pressed), torque=float(steering_torque)) + self._feed_gnss(sm) + if hint is not None and getattr(hint, "way_id", 0): + self._last_hint_t = t + self._load_ring(t, int(hint.way_id)) + busy = self.guide.phase in (ACTIVE, EXITING) + on = (t - self._last_hint_t) <= HINT_HOLD_S or busy + if maneuver_active or lane_change_active: + on = False + edges = edges_from_model(model_v2, v_ego) if (on and model_v2 is not None) else None + out = self.guide.update(t, v_ego, yaw_rate, model_k, enabled=on, lat_active=lat_active, edges=edges, driver=driver) + self.active = self.guide.phase in (ACTIVE, EXITING) + self._sync_latched_param(on_ring=_hint_on_ring(hint)) + self._log(t, model_k, out, v_ego, model_v2, driver, on) + return out + + def _log(self, t: float, model_k: float, out: float, v_ego: float = 0.0, model_v2=None, + driver: DriverInput | None = None, on: bool = False) -> None: + """Ring state through swaglog (no capnp). ERROR level on purpose: logMessage is rlog-only, errorLogMessage is in qlog. + + Events as they happen, a state line at ~1 Hz while the assist runs, and (near / in a ring) a compact summary of the + model's raw lane lines / road edges / path at ~1.25 Hz, so a qlog says whether the model's output still holds the ring. + """ + g = self.guide + ev, g.events = g.events, [] + for e in ev: + cloudlog.error(f"roundabout_assist {e}") + d = g.debug + if self.active and t - self._last_log_t >= LOG_PERIOD_S: + self._last_log_t = t + r_ref = d.get("r_ref") + fields = [f"phase={g.phase}", f"latched={int(bool(d.get('latched')))}", f"w={d.get('w', 0.0):.2f}", f"conf={d.get('conf', 0.0):.2f}", + f"bias={d.get('bias', 0.0):.1f}", f"bacc={d.get('bacc', 0.0):.0f}", f"poor={int(bool(d.get('poor')))}", + f"hold={int(bool(d.get('hold')))}", f"r={d.get('r', 0.0):.1f}", f"r_ref={'-' if r_ref is None else f'{r_ref:.1f}'}", + f"model={model_k:+.4f}", f"out={out:+.4f}"] + cloudlog.error("roundabout_assist state " + " ".join(fields)) + near = on and g.d_edge is not None and g.d_edge < RAW_LOG_EDGE_M and g.phase != DONE + if near and model_v2 is not None and t - self._last_raw_t >= LOG_RAW_PERIOD_S: + self._last_raw_t = t + cloudlog.error("roundabout_raw " + raw_ring_summary(g, t, v_ego, model_k, out, model_v2, driver)) diff --git a/selfdrive/controls/lib/roundabout_ring_hold.py b/selfdrive/controls/lib/roundabout_ring_hold.py new file mode 100644 index 00000000000000..9da8b179b85cc7 --- /dev/null +++ b/selfdrive/controls/lib/roundabout_ring_hold.py @@ -0,0 +1,131 @@ +"""Ring hold for the Roundabout Steering Assist (Pre-AP, NAPRoundaboutAssist, default Off). + +Oct 1 pm (0000013c, 9819620): the model's curvature fell to ~0 at the ring edge (it follows the exit branch, not the ring) and the +latched cap (1.15x the LIVE model) pinned the assist to it; steeringPressed flicker zeroed the weight 45% of the time. Pure functions +used by roundabout_guide.RoundaboutGuide (curvature + = right; sense = +1 CCW, circulation side is -sense * k): + + * widen_cap: model circulation-side curvature below CIRCLE_CAP_FRAC x the circle's -> cap widens toward the circle target, by <= CIRCLE_CAP_EXTRA + over the model (still <= 2.2 m/s², 0.035 slew) + * exit windows: EXIT_BEFORE_DEG before each exit branch (to EXIT_AFTER_DEG past it), no stalk -> output >= the circle target + * a same-side add (any magnitude) does not drop the curl; an exit-side pull (>= 1.5 Nm) or a held stalk wins at once. + steeringPressed with no same-side torque still debounces, and a short flicker keeps the correction state + * early latch at the ring edge, release on a right blinker while on the exit arm +A right blinker only releases the guide to the model (stalk held, or blinker + exit arm); it never routes the path onto the exit. +""" +from __future__ import annotations + +import math + +CIRCLE_CAP_FRAC = 0.5 # model's circulation-side curvature < this x the circle's: the cap widens toward the circle target +CIRCLE_CAP_EXTRA = 0.015 # 1/m: ...by at most this much over the model (R128: GNSS reads the car 2-3 m outside; uncapped it rides the island curb) +EXIT_BEFORE_DEG = 20.0 # exit window: this far before an exit branch (along the circulation) ... +EXIT_AFTER_DEG = 5.0 # ... to this far past it (the mouth of the exit arm) +EXIT_ARM_NEAR_DEG = 30.0 # blinker release: within this of an exit branch ... +EXIT_ARM_EDGE_M = 3.0 # ... and no more than this far inside the outer edge of the ring band +EXIT_ON_RING_M = 6.0 # an approach end this close to the ring radius touches the ring +EXIT_MERGE_DEG = 10.0 # branches closer than this are one exit +PRESS_DEBOUNCE_S = 0.3 # steeringPressed must hold this long before the assist yields +LIGHT_TORQUE_NM = 1.5 # |torque| below this toward the circulation is a resting hand, not a driver input +LATCH_ALIGN_EDGE_DEG = 45.0 # latch at the ring edge when within this of the tangent (was 25 deg: waited until tangent) +LATCH_EDGE_M = 1.0 + + +def _wrap_deg(a: float) -> float: + return (a + 180.0) % 360.0 - 180.0 + + +def exit_angles(ring) -> list[float]: + """Polar angles (deg, 0..360) of the exit branches: approach roads whose first point (travel direction) is on the ring.""" + out: list[float] = [] + if ring is None: + return out + for a in ring.approaches: + if len(a) < 2: + continue + x0, y0 = a[0] + x1, y1 = a[-1] + if abs(math.hypot(x0, y0) - ring.radius_m) > EXIT_ON_RING_M or abs(math.hypot(x1, y1) - ring.radius_m) <= EXIT_ON_RING_M: + continue + deg = math.degrees(math.atan2(y0, x0)) % 360.0 + if all(abs(_wrap_deg(deg - o)) > EXIT_MERGE_DEG for o in out): + out.append(deg) + return sorted(out) + + +def ahead_deg(theta_rad: float, sense: float, exit_deg: float) -> float: + """Degrees along the circulation from the car (polar angle theta) to the exit branch, in (-180, 180].""" + return _wrap_deg(sense * (exit_deg - math.degrees(theta_rad))) + + +def in_exit_window(theta_rad: float, sense: float, exits: list[float]) -> bool: + return any(-EXIT_AFTER_DEG <= ahead_deg(theta_rad, sense, e) <= EXIT_BEFORE_DEG for e in exits) + + +def near_exit(theta_rad: float, sense: float, exits: list[float]) -> bool: + return any(abs(ahead_deg(theta_rad, sense, e)) <= EXIT_ARM_NEAR_DEG for e in exits) + + +def widen_cap(cap: float, s_model: float, s_circle: float, v: float, a_lat_max: float) -> float: + """Latched circulation-side cap (-sense * k). Model under CIRCLE_CAP_FRAC x the circle: the cap widens toward the circle target, by up to + CIRCLE_CAP_EXTRA over the model (full at a model of 0, fading to nothing at the half-circle point, so it never steps), <= a_lat_max at + the actual speed. Otherwise unchanged (1.15 x the model).""" + if s_circle <= 0.0 or s_model >= CIRCLE_CAP_FRAC * s_circle: + return cap + fade = min(max(1.0 - s_model / (CIRCLE_CAP_FRAC * s_circle), 0.0), 1.0) + return max(cap, min(s_circle, s_model + CIRCLE_CAP_EXTRA * fade, a_lat_max / max(v * v, 1.0))) + + +def ring_limits(cap: float, floor: float, s_model: float, s_circle: float, v: float, a_lat_max: float, + in_window: bool, plain: bool) -> tuple[float, float]: + """(cap, floor) on the latched circulation-side curvature -s*k. `plain` (right stalk pending, off the ring band, over ring speed): the old 1.15x-model limits. + Otherwise the cap widens to the circle when the model is under half of it, and inside an exit window (no stalk) the floor is the + circle target, both bounded by a_lat_max at the actual speed; the cap never drops below the floor.""" + if plain: + return cap, floor + cap = widen_cap(cap, s_model, s_circle, v, a_lat_max) + if in_window: + floor = max(floor, min(s_circle, a_lat_max / max(v * v, 1.0))) + cap = max(cap, floor) + return cap, floor + + +def step_cap(extra: float, base: float, want_cap: float, v: float, a_lat_max: float, slew_dt: float, fall: float, + plain: bool, holding: bool) -> tuple[float, float]: + """(extra, cap): the widening over the 1.15x cap `base`. It rises at once and is given up at `fall` x the slew (at the full slew when + `plain`, over the ring speed, or past a_lat_max at the actual speed); the cap never passes a_lat_max at today's speed via the widening.""" + if holding: + return 0.0, base + want = max(want_cap - base, 0.0) + a_cap = a_lat_max / max(v * v, 1.0) + rate = 1.0 if plain or base + extra > a_cap else fall + extra = want if want >= extra else max(want, extra - rate * slew_dt) + return extra, base + min(extra, max(a_cap - base, 0.0)) + + +def on_exit_arm(theta_rad: float, sense: float, exits: list[float], d_edge: float) -> bool: + """Near an exit branch and at the outer edge of the ring band or beyond: the car is on (or entering) the exit arm.""" + return near_exit(theta_rad, sense, exits) and d_edge >= -EXIT_ARM_EDGE_M + + +def counts_as_press(pressed: bool, torque: float, sense: float) -> bool: + """steeringPressed that is not torque toward the circulation. + + A same-side add (sense * torque > 0), light or hard, is the driver + helping the ring and must not count. Zero torque and an exit-side press do. + """ + return bool(pressed) and not (sense * torque > 0.0) + + +def driver_wins(stalk_held: bool, pressed: bool, torque: float, sense: float, drv_s: float, dt: float) -> tuple[bool, float]: + """(weight 0 now?, debounce timer). At once: a held stalk, or an exit-side pull + (-sense * torque >= LIGHT_TORQUE_NM). A same-side add never zeroes the curl. + steeringPressed with no same-side torque still advances the timer (a flicker + shorter than PRESS_DEBOUNCE_S changes nothing) but does not itself zero the weight.""" + exit_pull = (-sense * float(torque)) >= LIGHT_TORQUE_NM + drv_s = drv_s + dt if counts_as_press(pressed, torque, sense) else 0.0 + return bool(stalk_held or exit_pull), drv_s + + +def latch_ready(align_deg: float, d_edge: float, tangent_deg: float) -> bool: + """Tangent at the edge as before, or within LATCH_ALIGN_EDGE_DEG of it as the car reaches the ring edge.""" + return d_edge < LATCH_EDGE_M and align_deg < max(tangent_deg, LATCH_ALIGN_EDGE_DEG) diff --git a/selfdrive/controls/lib/roundabout_ring_log.py b/selfdrive/controls/lib/roundabout_ring_log.py new file mode 100644 index 00000000000000..1582b6768180fc --- /dev/null +++ b/selfdrive/controls/lib/roundabout_ring_log.py @@ -0,0 +1,59 @@ +"""Compact raw-model summary for the roundabout assist's swaglog line (no capnp; plain JSON text).""" +from __future__ import annotations + +import json + +LOG_RAW_X = (5.0, 10.0, 15.0, 20.0, 30.0) + + +def _interp_xy(xs, ys, x: float) -> float | None: + try: + n = min(len(xs), len(ys)) + except TypeError: + return None + if n < 2: + return None + xs = [float(xs[i]) for i in range(n)] + ys = [float(ys[i]) for i in range(n)] + if not (xs[0] <= x <= xs[-1]): + return None + for i in range(1, n): + if xs[i] >= x: + a, b = xs[i - 1], xs[i] + f = 0.0 if b <= a else (x - a) / (b - a) + return ys[i - 1] + f * (ys[i] - ys[i - 1]) + return None + + +def _row(xs, ys) -> list: + """y (m, device frame, + right) at LOG_RAW_X, None where the line does not reach.""" + out = [] + for x in LOG_RAW_X: + y = _interp_xy(xs, ys, x) + out.append(None if y is None else round(y, 2)) + return out + + +def raw_ring_summary(g, t: float, v_ego: float, model_k: float, out: float, model_v2, + driver) -> str: + """One compact JSON line: ring pose / state plus the model's raw lane lines, road edges and path at 5/10/15/20/30 m.""" + d = g.debug + rec: dict = {"t": round(t, 2), "v": round(v_ego, 2), "ph": g.phase, "lat": int(g.latched), "rel": g.release, + "r": round(d.get("r", 0.0), 1), "rref": None if g.r_ref is None else round(g.r_ref, 2), + "de": None if g.d_edge is None else round(g.d_edge, 1), "trav": round(g.travel, 0), + "bias": round(d.get("bias", 0.0), 1), "bacc": round(d.get("bacc", 0.0), 0), "w": round(d.get("w", 0.0), 2), + "k": round(model_k, 4), "out": round(out, 4)} + if driver is not None: + rec["stalk"] = [driver.stalk_dir, int(driver.stalk_held), int(driver.pressed), round(driver.torque, 1)] + try: + pos = model_v2.position + rec["path"] = _row(pos.x, pos.y) + lines, probs = model_v2.laneLines, model_v2.laneLineProbs + rec["ll"] = [_row(lines[i].x, lines[i].y) for i in range(min(len(lines), 4))] + rec["llp"] = [round(float(p), 2) for p in list(probs)[:4]] + edges, stds = model_v2.roadEdges, model_v2.roadEdgeStds + rec["re"] = [_row(edges[i].x, edges[i].y) for i in range(min(len(edges), 2))] + rec["res"] = [round(float(p), 2) for p in list(stds)[:2]] + except Exception: + rec["model"] = "unavailable" + return json.dumps(rec, separators=(",", ":")) diff --git a/selfdrive/controls/lib/sight_cap.py b/selfdrive/controls/lib/sight_cap.py new file mode 100644 index 00000000000000..994e8bfd5caacb --- /dev/null +++ b/selfdrive/controls/lib/sight_cap.py @@ -0,0 +1,279 @@ +"""Sight-distance speed cap (Pre-AP). LOG ONLY: nothing reads its output. + +Idea (Justin, Oct 11 2026): when the model suddenly cannot push its path out +confidently, treat that like low visibility and slow so the car could still +handle a tight bend inside the distance it can see. + +Sight distance is model_sight.sight_distance_m: where the path's lateral std +reaches 2 m (shared with low-visibility steering, which reads the same std). + +Would fire when all of these hold: +- sight drops below SHRINK_RATIO (0.5) x its own median over the 2-12 s + before, held SHRINK_HOLD_S (0.5 s); +- 25-55 mph; +- confidence was not already red with a short path over that baseline window + (red for half of it AND baseline sight under 7 s of travel). Red alone is the + model's normal state for long stretches; with a long confident path it does + not count as "already unsure"; +- another cue: path curvature rising, or a map roundabout ahead whose funnel + is not live yet; +- no tracked vehicle explains it (Justin, Oct 11): vehicles never count as + sight loss. A lead in our lane, moving or stopped, belongs to the lead / + stopped-object logic; parked cars and cars in the next lane do not change + our road. Any radar/model vehicle within VEHICLE_RANGE_M suppresses it, + with the reason logged: lead / stopped_lead / adjacent / parked. It fires + only when the ROAD is hidden or uncertain (a bend, a crest, a junction); +- the roundabout map funnel is not live (it owns entry). + +The cap speed is the speed from which the car can slow, inside the sight +distance less MARGIN_M, to a TURN_R_M (30 m) bend at TURN_LAT_MS2 (15 mph) +at DECEL_MS2 (1.5 m/s²). Its would-be accel command is jerk limited at +JERK_MS3 (2 m/s³). Low-visibility glare (camera-only) never feeds this: it +reads only the model path. + +Log: "sightcap {json}" through cloudlog.error (errorLogMessage, kept in qlog), +on every would-fire edge, at 2 Hz while it would be firing, and once when a +held sight drop is suppressed by a vehicle (why = lead / stopped_lead / +adjacent / parked). +""" +from __future__ import annotations + +import json +import math +from collections import deque +from dataclasses import dataclass + +from openpilot.common.constants import CV + +PARAM_KEY = "NAPSightCap" +MODE_OFF = 0 +MODE_SHADOW = 1 +DEFAULT_MODE = MODE_SHADOW + +SHRINK_RATIO = 0.5 +RECOVER_RATIO = 0.8 +BASE_WIN_S = (2.0, 12.0) # baseline = median sight over [t-12, t-2] +BASE_MIN_SAMPLES = 10 +SHRINK_HOLD_S = 0.5 +V_MIN_MS = 25.0 * CV.MPH_TO_MS +V_MAX_MS = 55.0 * CV.MPH_TO_MS +RED_BASE_FRAC = 0.5 # "already red": red for at least half the baseline window +# ...and the path was already short then. Red is the model's normal state for +# long stretches (a third of Oct 4-10); a red model whose path still reached +# BASE_LONG_S of travel was not unsure. The Oct 10 5:40:45 PM corner is red +# throughout with a ~200 m (9 s) baseline. +BASE_LONG_S = 7.0 + +# Cue: rising curvature (max |k| over the path) within the last CURV_RISE_S. +CURV_RISE_S = 1.0 +CURV_RISE_K = 0.002 +CURV_MIN_K = 0.003 + +# Lead classification (path-relative lateral, m). +OUR_LANE_M = 1.8 +ADJ_LANE_M = 5.4 +MOVING_LEAD_MS = 3.0 +VEHICLE_RANGE_M = 150.0 +VEHICLE_HOLD_S = 1.5 # a radar track that flickers out still explains the drop for this long + +# Cap. +TURN_R_M = 30.0 +TURN_LAT_MS2 = 1.5 +V_TURN_MS = math.sqrt(TURN_R_M * TURN_LAT_MS2) # 6.7 m/s, 15 mph +DECEL_MS2 = 1.5 +JERK_MS3 = 2.0 +MARGIN_M = 10.0 +CAP_GAIN_1_S = 0.6 +FREE_A_MS2 = 2.0 + +# Crest: path height second difference over 50/100 m (m). +CREST_Z_M = -1.0 + +LOG_PERIOD_S = 0.5 +LOG_PREFIX = "sightcap " + + +def read_sight_cap_mode(params) -> int: + try: + mode = int(params.get(PARAM_KEY, return_default=True)) + except Exception: + return DEFAULT_MODE + return mode if mode in (MODE_OFF, MODE_SHADOW) else DEFAULT_MODE + + +def cap_speed_ms(sight_m: float) -> float: + """Fastest speed that can still slow to a 30 m bend at 1.5 m/s² inside the sight distance.""" + room = max(0.0, float(sight_m) - MARGIN_M) + return math.sqrt(V_TURN_MS * V_TURN_MS + 2.0 * DECEL_MS2 * room) + + +def crest_ahead(xs, zs) -> tuple[bool, float | None]: + """(crest, z second difference) from the model path height at 50 and 100 m.""" + try: + pts = [(float(x), float(z)) for x, z in zip(xs, zs, strict=False)] + if len(pts) < 2 or pts[-1][0] < 100.0: + return False, None + + def z_at(d): + for (x0, z0), (x1, z1) in zip(pts, pts[1:], strict=False): + if x0 <= d <= x1 and x1 > x0: + return z0 + (d - x0) / (x1 - x0) * (z1 - z0) + return pts[-1][1] + dd = z_at(100.0) - 2.0 * z_at(50.0) + pts[0][1] + return dd < CREST_Z_M, round(dd, 2) + except Exception: + return False, None + + +@dataclass +class LeadInfo: + present: bool = False + lane: str = "none" # "ours" | "adjacent" | "other" | "none" + v: float | None = None + d: float | None = None + lat: float | None = None + + @property + def moving_in_our_lane(self) -> bool: + return self.present and self.lane == "ours" and self.v is not None and self.v > MOVING_LEAD_MS + + @property + def kind(self) -> str: + """lead / stopped_lead / adjacent / parked, or "" when nothing within range.""" + if not self.present or (self.d is not None and self.d > VEHICLE_RANGE_M): + return "" + moving = self.v is None or self.v > MOVING_LEAD_MS + if self.lane == "ours": + return "lead" if moving else "stopped_lead" + return "adjacent" if moving else "parked" + + +def classify_lead(present: bool, path_lat, v_lead, d_rel) -> LeadInfo: + if not present: + return LeadInfo() + lane = "other" + if path_lat is None: + lane = "ours" # radard picked it as leadOne and no path to say otherwise + elif abs(float(path_lat)) <= OUR_LANE_M: + lane = "ours" + elif abs(float(path_lat)) <= ADJ_LANE_M: + lane = "adjacent" + return LeadInfo(True, lane, None if v_lead is None else float(v_lead), + None if d_rel is None else float(d_rel), None if path_lat is None else float(path_lat)) + + +class SightCap: + """Trigger state and the would-be cap. update() never raises out to the planner.""" + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self._hist: deque = deque() # (t, sight, red) + self._kmax: deque = deque() # (t, max |k|) + self._shrink_t = 0.0 + self.latched = False + self._base_at_fire = None + self._a = FREE_A_MS2 + self.sight = None + self.base = None + self.v_cap = None + self.a_cap = FREE_A_MS2 + self.would_fire = False + self.reason = "idle" + self.cue = "" + self.fired_edge = False + self.suppressed_edge = False + self._veh_blocked = False + self._veh_kind = "" + self._veh_age = 1e9 + + def _baseline(self, t: float): + lo, hi = t - BASE_WIN_S[1], t - BASE_WIN_S[0] + vals = [s for (tt, s, _r) in self._hist if lo <= tt <= hi] + reds = [r for (tt, _s, r) in self._hist if lo <= tt <= hi] + if len(vals) < BASE_MIN_SAMPLES: + return None, False + vals.sort() + m = vals[len(vals) // 2] + return m, (sum(reds) / len(reds)) >= RED_BASE_FRAC + + def update(self, *, t: float, dt: float, v_ego: float, sight_m, ks, conf_red: bool, + lead: LeadInfo, rb_live: bool, rb_ahead: bool, others=()) -> bool: + """One planner cycle. Returns would_fire.""" + self.fired_edge = False + self.suppressed_edge = False + v = float(v_ego) + self.sight = None if sight_m is None or not math.isfinite(sight_m) else float(sight_m) + kmax = max((abs(float(k)) for k in (ks or []) if math.isfinite(float(k))), default=0.0) + self._kmax.append((t, kmax)) + while self._kmax and self._kmax[0][0] < t - CURV_RISE_S: + self._kmax.popleft() + if self.sight is not None: + self._hist.append((t, self.sight, bool(conf_red))) + while self._hist and self._hist[0][0] < t - BASE_WIN_S[1] - 1.0: + self._hist.popleft() + base, red_before = self._baseline(t) + self.base = base + + k_old = self._kmax[0][1] if self._kmax else kmax + curv_rising = kmax >= CURV_MIN_K and (kmax - k_old) >= CURV_RISE_K + cue = "curv" if curv_rising else ("rb_map" if (rb_ahead and not rb_live) else "") + + shrink = self.sight is not None and base is not None and base > 0.0 and self.sight < SHRINK_RATIO * base + self._shrink_t = self._shrink_t + dt if shrink else 0.0 + + block = "" + if rb_live: + block = "rb_funnel" + else: + veh = next((k for k in (x.kind for x in (lead, *others)) if k), "") + if veh: + self._veh_kind, self._veh_age = veh, 0.0 + else: + self._veh_age += dt + if self._veh_kind and self._veh_age <= VEHICLE_HOLD_S: + block = self._veh_kind + if not block and not (V_MIN_MS <= v <= V_MAX_MS): + block = "speed" + + veh_blocked = block not in ("", "rb_funnel", "speed") and self._shrink_t >= SHRINK_HOLD_S + self.suppressed_edge = veh_blocked and not self._veh_blocked + self._veh_blocked = veh_blocked + if self.latched: + recovered = self.sight is not None and self._base_at_fire is not None and self.sight >= RECOVER_RATIO * self._base_at_fire + if block or recovered or self.sight is None: + self.latched = False + self.reason = block or ("recovered" if recovered else "no_path") + else: + if block: + self.reason = block + elif self._shrink_t < SHRINK_HOLD_S: + self.reason = "idle" + elif red_before and base < BASE_LONG_S * max(v, 1.0): + self.reason = "red_before" + elif not cue: + self.reason = "no_cue" + else: + self.latched = True + self.fired_edge = True + self._base_at_fire = base + self.cue = cue + self.reason = "fire" + + self.v_cap = cap_speed_ms(self.sight) if self.sight is not None else None + target = FREE_A_MS2 + if self.latched and self.v_cap is not None: + target = max(-DECEL_MS2, min(FREE_A_MS2, CAP_GAIN_1_S * (self.v_cap - v))) + # Would-be command, jerk limited on the way down. + if target < self._a: + self._a = max(target, self._a - JERK_MS3 * dt) + else: + self._a = target + self.a_cap = self._a + self.would_fire = self.latched + return self.would_fire + + +def format_log_line(rec: dict) -> str: + return LOG_PREFIX + json.dumps(rec, separators=(",", ":")) diff --git a/selfdrive/controls/lib/stalk_tip_turn.py b/selfdrive/controls/lib/stalk_tip_turn.py new file mode 100644 index 00000000000000..149112877b938a --- /dev/null +++ b/selfdrive/controls/lib/stalk_tip_turn.py @@ -0,0 +1,109 @@ +"""Classify Pre-AP turn-stalk as a tip (ALC) vs a held driver turn. + +TurnIndLvr_Stat / turnSignalStalkState is only IDLE=0, LEFT=1, RIGHT=2, +SNA=3 — there is no tip vs latch bit. Approximate from hold time: + +- Tip (partial): LEFT or RIGHT then back to IDLE within STALK_TIP_HOLD_S + → automatic lane change (arm ALC). A typical tip-blink is under ~0.3–0.5s. +- Full / latched: LEFT or RIGHT held past STALK_TIP_HOLD_S → driver turn + (lateral pause). Speed is not used for this split. + +While ALC is armed / in progress (or leftover ALC keep-alive is still +flashing), a *same-direction* physical stalk must be held past +STALK_ALC_TURN_HOLD_S (1.0s) to steal ALC as a driver turn. A shorter +same-direction press is not a turn (a tip still queues; 0.40–1.0s is +ignored). Opposite uses the 0.40s window. + +Use the stalk enum (non-flashing), not the bulb flash bit, for hold time. +SNA is treated as IDLE. Hazards are not classified here. +""" + +# controlsd -> modeld flag (roundabout ring assist latched): DesireHelper ignores stalk tips while it is set. +PARAM_RING_LATCHED = "NAPRoundaboutLatched" + +# Held this long (or longer) is a latched turn, not a tip-blink. +# 0.40s sits in the 0.3–0.5s tip-blink range: a real tap springs back sooner; +# a detented hold is still LEFT/RIGHT well past this. +STALK_TIP_HOLD_S = 0.40 + +# During ALC / keep-alive, same-direction stalk must stay LEFT/RIGHT this +# long before we cancel ALC and pause lat as a driver turn. Justin's +# sequence: tip into a turn lane, then hold the stalk for the actual turn. +STALK_ALC_TURN_HOLD_S = 1.0 + + +def _normalize_stalk(stalk_state) -> int: + stalk = int(stalk_state or 0) + if stalk in (1, 2): + return stalk + return 0 # IDLE or SNA + + +class StalkTipTurn: + def __init__(self): + self.reset() + + def reset(self): + self.direction = 0 + self.held_s = 0.0 + self.is_turn = False + self.tip_event = False + self.tip_direction = 0 + self.left_press = False + self.right_press = False + + @property + def is_pending(self) -> bool: + return self.direction in (1, 2) and not self.is_turn + + @property + def is_alc_turn(self) -> bool: + """Held long enough during ALC/keep-alive to take over as a driver turn.""" + return self.direction in (1, 2) and self.held_s + 1e-6 >= STALK_ALC_TURN_HOLD_S + + def is_driver_turn(self, *, alc_latched=False, alc_direction=0) -> bool: + return stalk_hold_is_driver_turn(self, alc_latched=alc_latched, + alc_direction=alc_direction) + + def update(self, stalk_state, dt: float): + stalk = _normalize_stalk(stalk_state) + self.tip_event = False + self.tip_direction = 0 + self.left_press = False + self.right_press = False + + if stalk in (1, 2): + if self.direction != stalk: + self.direction = stalk + self.held_s = 0.0 + self.is_turn = False + self.left_press = stalk == 1 + self.right_press = stalk == 2 + self.held_s += dt + if not self.is_turn and self.held_s + 1e-6 >= STALK_TIP_HOLD_S: + self.is_turn = True + else: + if self.direction in (1, 2) and not self.is_turn: + self.tip_event = True + self.tip_direction = self.direction + self.direction = 0 + self.held_s = 0.0 + self.is_turn = False + + +def stalk_hold_is_driver_turn(tip_turn: StalkTipTurn, *, alc_latched=False, + alc_direction=0) -> bool: + """True when the physical stalk is a driver turn (pause lat, cancel ALC). + + No ALC: LEFT/RIGHT held past STALK_TIP_HOLD_S (0.40s). + ALC armed / in progress / leftover keep-alive: + same direction (or unknown) → STALK_ALC_TURN_HOLD_S (1.0s); + opposite → 0.40s (tap still cancels ALC elsewhere without pausing). + """ + if tip_turn.direction not in (1, 2): + return False + if not alc_latched: + return tip_turn.is_turn + if alc_direction in (1, 2) and tip_turn.direction != alc_direction: + return tip_turn.is_turn + return tip_turn.is_alc_turn diff --git a/selfdrive/controls/lib/tests/cone_replay/oct10_17b_cone_pass.json.gz.b64 b/selfdrive/controls/lib/tests/cone_replay/oct10_17b_cone_pass.json.gz.b64 new file mode 100644 index 00000000000000..f2df0703d05c95 --- /dev/null +++ b/selfdrive/controls/lib/tests/cone_replay/oct10_17b_cone_pass.json.gz.b64 @@ -0,0 +1,926 @@ +H4sICFPUymoC/2Z4X29jdDEwXzE3Yl9jb25lX3Bhc3MuanNvbgDsvduO5DyTLfYu/3V2QzwED/MqP+ZiAx741oA3bG8YfncrSIlxIKlUZlUz6xv0RQVUSlV2 +VfaKYBxX/Pv//df//Nd/bL+3x7/+r3/9hw2/t2Af//o//uf/+a//+Pe/vftt4eF+B/P4tb9k7MP853/ur/4/+4v4I9tv9zC/zcP+9g//2z7C7/DI+7Wxv9PD +hF1Ys9/ef9Q+nPkdHy7uwvv9x8CgyPubhLi/Q4T94QT7t9n/jvhv/K/2b9z6Mk2Ur1+nMEXaIl2Rvsiw/xv/9b/97/9V/s7jH7L71/574++5f7//Hg/8E/J+ +f/+DtocBvEr4V9n9NRv3e/Wvwse83V/1ab8H5aPAt9r/tP1v+fev/eOAx1h6Jh2T/X07ecZN3jnt/1V/+i8Lv2N+jEXiF8mIiyJcE7YJ9hXzfyLW/tf/+L8L +PLct+v/vcYI1mgZXZwiuZv+r97/QpwLXLQzhuu1wdftngL8E7J+Bw88gIlwDwnV/GX5n/PMdwnV/0u2vwoYi7d+GsAM8IlITvkd2v9OLcH0VqlBkXAvYXGCV +7UQaJsc39Ev851wnwwKwxt9+NzSH4F9GXNgmHIryQkCRpIjtKpdvJVyNbWg1xjW0mkho3eHI0ToF62lbQdjWiGA1aFsN/vkBwRrQthq0rQbBmhCsGcEaEKwR +bau/C9ZfvXgC0CIzSlOeNO5HQdZqhPa3+Z1iXDMwGYtMp9x/f7MEtYhF/DJZCNt9V75ME04K9aopP6lsrHeE2v1zKKjdrWF0DbUu/d4dhBuodQy1UxPrEbUe +TWxGE5sRtYCoBUStRdQ6NLH5GWqnaDUT5ApfgOE3FeT+QOD2OO1/ynXIr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obcSehOh +N9NPHgi9idDrCL2BnG8l59sIvfF75QMvvjeP1msnShSy+lHfol1jtJ/1b4Kv4Vv5MawvMrtmEy7vHgvNCE0EXfoAViAKfsjM6Cm4uDF0aDd7aLwQpQCm81R1 +0FqgM9viWEuCDbioSFJBodGN2fLYFn//ZlbsmsJsU9rAC673eeSQ58ghS+QQCbyHRA7l7cjhgjeAyKGO2heFXSwWl3kve+blLBmxfwWl1btfQO+7M6pN+668 +cGdK09pJB60sMinkfFvah19e2bwcusHZSeYmDQdeYYIQ4gbGWSK3C1FvlqTAEk4I1zFzwKW1LmbxW4Q6kEJ8C7+Umzm6qB35U0r9CL+J8OsIv/efnDR9EhaA +UxW3UDZcqNhQcUGU92u3F/jNTQDcJQ8TPZ5Mjwyk9DuAiZlNxd3fcL+PhH7CM6Efp+LSPXpgvV7d+diJrsBvTlx4wX/7DWq9j/EbLvDbGxK9PlYHsQARsJPd +EeSEMfCRqC2Ual+fQAHigt/yv//zfwAAAP//AwAopYr1chsJAA== diff --git a/selfdrive/controls/lib/tests/cone_replay/oct10_17b_parked_1647.json.gz.b64 b/selfdrive/controls/lib/tests/cone_replay/oct10_17b_parked_1647.json.gz.b64 new file mode 100644 index 00000000000000..e383e42d1ddbc9 --- /dev/null +++ b/selfdrive/controls/lib/tests/cone_replay/oct10_17b_parked_1647.json.gz.b64 @@ -0,0 +1,342 @@ +H4sICFHUymoC/2Z4X29jdDEwXzE3Yl9wYXJrZWRfMTY0Ny5qc29uAOy9247sus4u9i7rusaAdZb+V1mYFwGykNsA2UiyEeTdY0q2SIqSy64qq/oP+qI53S53 +z64an3jmx3//P//6H//6r+Xv8vjX//mv/9Lxb4zp8a///X/8H//6r3//s1783+t/4dXlr3mov/qh/8aHW78P638V3FAORPqbHtr9VQ+j1hdN+Ose1v4ND6fX +K7+sr3p4JKS//pHg96llvQn/g/+5/Q/+PBVqKMsfWC40CAvCg4irUOv/5z//6//2H3hP/97eDTy2voP1TzTr9/Cn+vX7BO9Fw5+X39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YTDdvim75v81PSvxJDIeQLiiKJGWmRGW6XrfPmuTfYxCxcQ29YbPAbx2wwB9BNi9BModn22H+5eIN2K83XSuFE3OqFIp6vSH16/cDlF9YfuwfLg+lcm +/eKYQsLFysJdYtAuoyQ/dP6OXLIz//7+BwAA//8DANijkmzLQAQA diff --git a/selfdrive/controls/lib/tests/cone_replay/oct10_17b_parked_1650.json.gz.b64 b/selfdrive/controls/lib/tests/cone_replay/oct10_17b_parked_1650.json.gz.b64 new file mode 100644 index 00000000000000..cf57bb3e2a0d92 --- /dev/null +++ b/selfdrive/controls/lib/tests/cone_replay/oct10_17b_parked_1650.json.gz.b64 @@ -0,0 +1,1116 @@ +H4sICFLUymoC/2Z4X29jdDEwXzE3Yl9wYXJrZWRfMTY1MC5qc29uANy9244kQa4k9i/zXN1wutNv51cG52EBHeh1gV1IWgj6dwWNdDojIrO6qrtHQsxDe2dF +RWZVxcWCNBqN//y///E///Ef6Wf6+Mf/8Y//6D8rz49//Pf/+T/+8R///CfXn21+/Mg/G3/8OL7VPug/P/456k/KsrXmsJXHz15la4pbKRM+gn6WaZuTfETB +Dukn+b7/efzU/+v4ofKbyPb0sxz/+sfxzo98fF2O7Xz8X4+v27F9HP/jA+j4kR8k36L2kz9o/Bwfx0/lj8w/80fu8t50vCrHz/woXT4mHa9Yvnv80scnygfU +dnzZ0vG2xscHtHl8fOfjG30cOx+/b5Zf8H8dv+AP+Q1fLBTWgrVinbISy5qxdFlLk5WxS8U3G153rAPfnV0OXMLhyziGRVZ5E/2s+GbH9sGyziGHn2TJLGvp +OEvY0nBu+jj+iv/63/73/8LptWOdj3/jOM7djnE/ju/4mMd2PbRVXuGoHh8gBzR9FOwtu3HWw3gcQdYjeBy8fny312PbkHdM2TbxeUl2JOr4bHk7FTmXxB0/ +SN5HTX4UDfm9aB6/wHG5/KjHpmPp82O91IWwZqwVK7bP489vOBftJ5acZZVj3nA8Gi7K4xfocv0lXJp5yCoHt/9sRdaOdeB6Hvoa12vXu0H3xxbq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+eX+9Eq/cX0eS3m8QhxoBuh38Id170OJ9AXv6dt/+eLbvfGlstrRrXs +TiHNGBMAaZMD9i0J0mu30Och2i/nNPfxoBaFJuiLpp3Sss5nU4NXGZK48dvgMgc7GGxiC++djcGr6sCGKDvvRowU1L61F1R38Udv9mpwNOTj5m7W7dzNOHLS +eT01GZsicsMFjtdImtRcGiGbkQArMczRvprLYA+ixyKb4fbSxbN0W9cgR2vdRbWS3ROogw1x7xasnWygNtrkrW9rexklj9k//62fOwpek7PUX2dTUGhaChXh +qkE4efQ5zZR+QavmeQjDKFb4mRjTAsOZx3Et61sS3r/q/hnLiKlrvKk65GmQZfVovlQnPatu9EabLq4mqZtJEoXTNLEVcTO0PMiB4AfrSShWc18/eS5j2KsM +bCwXYUr0i3MNIgLpCG0SRzP5trt41ptTSH6NaVvb5xwnbDBtOSJfUPukNipYy9MmtZsSOD8D0Ppdv6+X+vBqtVps3WowlGfd9l25oCNfNhkl2Csrg1mKBtKc +PnkljVhV86BnS/foBw4kSfXQJIHJC9bqBkkO9hKPLn2FRWCsibLDT8NZoo20EL41AjNHW2YY62agV65hNy3/62tsIpDjjq8A7z0vgS7tcgQ/g91L1B0lXEpH +//3m+Sqv1TXxmbZPOr3GTv8fs5bueemtwbSoD6sPbcUMbMWIOezq6czIZjZPwBvDWG4KcolntSy/OuKbShxWrconusa0qhrr49EqpRdCMfOgP+NS59lNgpLC +UNnGueerDeI0d4Ebbm0ofmhj4YyAsgLkZGlIGtFz9OlZwuAIIrdKe79W4/7f/wMAAP//AwAPVls4EVoIAA== diff --git a/selfdrive/controls/lib/tests/cone_replay/oct10_17b_town_parked.json.gz.b64 b/selfdrive/controls/lib/tests/cone_replay/oct10_17b_town_parked.json.gz.b64 new file mode 100644 index 00000000000000..09d94aa1be86b2 --- /dev/null +++ b/selfdrive/controls/lib/tests/cone_replay/oct10_17b_town_parked.json.gz.b64 @@ -0,0 +1,3183 @@ +H4sICFLUymoC/2Z4X29jdDEwXzE3Yl90b3duX3B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esT605UDT/NJPPRbUae2owWxuR83Ffg6+y5yp4Jv8ICMMGoW4Dkr/pY3Tt6CJH+g28UNBy9czRfmuvvtGB7rLJ548FG2t6OpmTmfiDRt1mDGjbWNR +WUeobV/JZFhJv4aARsii+gyVjUd+3h6j+rEfTXKgbncbEVN0vf1kioFIkiPLozAPAguGMvDkCI8+c/W8NZ5Drf/v//x/AAAA//8DAC8+R5u6aBYA diff --git a/selfdrive/controls/lib/tests/cone_replay/oct10_17c_cone_zone.json.gz.b64 b/selfdrive/controls/lib/tests/cone_replay/oct10_17c_cone_zone.json.gz.b64 new file mode 100644 index 00000000000000..3ef6e711b62e8e --- /dev/null +++ b/selfdrive/controls/lib/tests/cone_replay/oct10_17c_cone_zone.json.gz.b64 @@ -0,0 +1,4690 @@ +H4sICFLUymoC/2Z4X29jdDEwXzE3Y19jb25lX3pvbmUuanNvbgDcvdluJMmWtfcu55pJuM1m/SoHfSFADd0K0A9JPwS9u3yvb9sQQTKTmVUtIOqiopjMSA4+ +LN/DGv79//zrf/zrP6736+1f/+e//iOk95DH27/+9//xf/zrP/7971zey1t5D+Hth/3NeAv/+fbvWt9zfhvvo+uzKdyf/c/7n/zf97+wr3O9h/u/8hbu/8f7 +z+k9vuX3+lbv//f7c+G6PwjR3lHsj+29v8XLXpK9tPtz6XrPb8n+mJr96+v+5znfXyu3+y+K/bGk9/ZWqn007s9V+04132+u9n1qtz/aXzT7UVp4z/Yj/s/7 +R/zBz/jhv7Beor0ke8n2Uu2l269lfxHKm/3893/2l/auZJ/J9i+zPrK35jY/F5u+wf1dc7qP1/3L/Yj2LX7ch+X+RH5v5e1HfS/3wezvtd5vCfdf3z/sf/2v +/9t/6ST4QbXv2e+D2u4Deh+I+//1/vPgWF52LO+Puh3BeP/dfRjvI69329tytMNoB6XoGNmXqu3+21buz3X7F8M+N/T1LntjCE1f2/55uL9Iewu56RvZvwvV +vlXoOpfj/gHuC+P+7cbbfOm8dr0WvUZ7bfpM02eajkjVO6s+U4Ne9c7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xEKSJwA= diff --git a/selfdrive/controls/lib/tests/data/roundabout_pass_oct1.json b/selfdrive/controls/lib/tests/data/roundabout_pass_oct1.json new file mode 100644 index 00000000000000..d65a07669c4e8e --- /dev/null +++ b/selfdrive/controls/lib/tests/data/roundabout_pass_oct1.json @@ -0,0 +1 @@ +{"note":"0000013c (Oct 1 11:40 CT, 9819620, outer lane): the failing pass, cut at the driver override. Same format as roundabout_passes_sep29.json.","passes":{"0000013c":{"label":"R13c","lane":"outer","t0_ct":"11:40:08.854","takeover_s":0.0,"k_act0":-0.00171,"k_des0":-0.00135,"model_k_ds":0.5,"model_k":[-0.00236,-0.00185,-0.00134,-0.00113,-0.00113,-0.00113,-0.00113,-0.00113,-0.00113,-0.00113,-0.00113,-0.00113,-0.00106,-0.00027,0.00053,0.00072,0.00072,0.00072,0.00072,0.00072,0.00072,0.00072,0.00072,0.00072,0.00172,0.00306,0.00369,0.00369,0.00369,0.00369,0.00369,0.00369,0.00369,0.00369,0.00369,0.00513,0.00676,0.00713,0.00713,0.00713,0.00713,0.00713,0.00713,0.00713,0.00713,0.00895,0.01222,0.01366,0.01366,0.01366,0.01366,0.01366,0.01366,0.01366,0.01366,0.01672,0.02079,0.0212,0.0212,0.0212,0.0212,0.0212,0.0212,0.0212,0.02307,0.02617,0.02665,0.02665,0.02665,0.02665,0.02665,0.02665,0.0266,0.0253,0.02451,0.02451,0.02451,0.02451,0.02451,0.02451,0.02451,0.01937,0.01546,0.01546,0.01546,0.01546,0.01546,0.01546,0.01546,0.01346,0.01063,0.01062,0.01062,0.01062,0.01062,0.01062,0.01062,0.01048,0.00844,0.00701,0.00701,0.00701,0.00701,0.00701,0.00701,0.00701,0.0064,0.00195,-0.00096,-0.00096,-0.00096,-0.00096,-0.00096,-0.00096,-0.00096,-0.00026,0.0056,0.00975,0.00975,0.00975,0.00975,0.00975,0.00975,0.00975,0.0094,-0.00677,-0.02041,-0.02041,-0.02041,-0.02041,-0.02041,-0.02041,-0.02041,-0.02041,-0.02881,-0.03892,-0.03912,-0.03912,-0.03912,-0.03912,-0.03912,-0.03912,-0.03912,-0.03842,-0.03717,-0.03678,-0.03678,-0.03678,-0.03678,-0.03678,-0.03678,-0.03678,-0.03668,-0.03628,-0.03603,-0.03603,-0.03603,-0.03603,-0.03603,-0.03603,-0.03603,-0.03603,-0.03191,-0.02637,-0.02517,-0.02517,-0.02517,-0.02517,-0.02517,-0.02517,-0.02517,-0.02517,-0.02121,-0.01633,-0.0152,-0.0152,-0.0152,-0.0152,-0.0152,-0.0152,-0.0152,-0.0152,-0.01333,-0.00956,-0.00726,-0.00726,-0.00726,-0.00726,-0.00726,-0.00726,-0.00726,-0.00726,-0.00726,-0.00559,-0.00345,-0.00258,-0.00258,-0.00258,-0.00258,-0.00258,-0.00258,-0.00258,-0.00258,-0.00258,-0.00218,-0.00149,-0.00097,-0.00097,-0.00097,-0.00097,-0.00097,-0.00097,-0.00097,-0.00097,-0.00097,-0.00097,-0.00118,-0.00145,-0.00161,-0.00161,-0.00161,-0.00161,-0.00161,-0.00161,-0.00161,-0.00161,-0.00161,-0.00161,-0.0016,-0.00157,-0.00154,-0.00154,-0.00154,-0.00154,-0.00154,-0.00154,-0.00154,-0.00154,-0.00154,-0.00154,-0.00154,-0.00136,-0.00092,-0.00048,-0.00037,-0.00037,-0.00037,-0.00037,-0.00037,-0.00037,-0.00037,-0.00037,-0.00037,-0.00037,-0.00037,-0.00023,-8e-05,4e-05,4e-05,4e-05,4e-05,4e-05,4e-05,4e-05,4e-05,4e-05,4e-05,4e-05,4e-05,0.00034,0.00063,0.00088,0.00088,0.00088,0.00088,0.00088,0.00088,0.00088,0.00088,0.00088,0.00088,0.00088,0.00088,0.00083,0.00073,0.00062,0.00058,0.00058,0.00058,0.00058,0.00058,0.00058,0.00058,0.00058,0.00058,0.00058,0.00058,0.00058,0.00061,0.00067,0.00073,0.00076,0.00076,0.00076,0.00076,0.00076,0.00076,0.00076,0.00076,0.00076,0.00076,0.00076,0.00076,0.00079,0.00091,0.00104,0.00115,0.00115,0.00115,0.00115],"v_dt":0.1,"v":[12.175,12.098,11.983,11.864,11.769,11.679,11.575,11.475,11.379,11.284,11.18,11.073,10.965,10.863,10.753,10.648,10.545,10.443,10.325,10.215,10.101,10.001,9.891,9.771,9.652,9.539,9.426,9.304,9.184,9.072,8.948,8.822,8.685,8.557,8.45,8.307,8.203,8.122,8.08,8.078,8.084,8.114,8.135,8.187,8.27,8.349,8.45,8.556,8.646,8.748,8.84,8.893,8.93,8.941,8.932,8.954,8.987,9.031,9.029,9.03,9.048,9.07,9.089,9.096,9.109,9.123,9.141,9.178,9.198,9.221],"fixes":[[-7.446,1.56,-0.55,-0.4,5.7],[-6.553,-0.38,0.1,0.3,5.5],[-5.443,0.75,0.75,0.8,5.5],[-4.446,-3.5,1.02,1.4,5.6],[-3.556,-1.99,1.1,-0.5,1.3],[-2.438,1.18,2.0,3.6,4.7],[-1.443,0.32,0.87,0.1,6.1],[-0.554,-1.83,-0.99,-1.8,2.4],[0.565,0.32,-0.47,0.5,4.8],[1.551,0.1,0.7,-0.0,1.5],[2.447,-0.88,1.05,1.4,0.9],[3.563,2.32,-0.29,-0.8,3.7],[4.561,1.39,-0.42,-7.1,9.3],[5.448,-1.17,1.43,1.5,1.2],[6.575,-0.91,1.18,0.5,5.9],[7.556,0.03,0.25,-2.6,4.0],[8.45,-0.24,-2.05,-4.8,3.0]],"hist":[[-8.0,175.18,3.72,-1.5586,15.04,0.0133],[-7.9,173.69,3.74,-1.5574,14.96,0.0109],[-7.8,172.2,3.76,-1.5565,14.89,0.0097],[-7.7,170.71,3.79,-1.5555,14.83,0.0093],[-7.6,169.24,3.81,-1.5547,14.78,0.0083],[-7.5,167.76,3.84,-1.5538,14.73,0.0092],[-7.4,167.08,3.56,-1.5549,14.64,0.0083],[-7.3,165.62,3.59,-1.5545,14.56,0.0048],[-7.2,164.17,3.61,-1.5538,14.51,0.0049],[-7.1,162.73,3.64,-1.5537,14.45,0.0026],[-7.0,161.29,3.66,-1.5532,14.37,0.0055],[-6.9,159.86,3.69,-1.5524,14.29,0.0075],[-6.8,158.44,3.72,-1.5518,14.22,0.006],[-6.7,157.03,3.74,-1.5513,14.14,0.0051],[-6.6,155.62,3.77,-1.5507,14.05,0.0057],[-6.5,154.03,3.86,-1.5487,14.0,0.007],[-6.4,152.63,3.9,-1.5479,14.0,0.0095],[-6.3,151.24,3.93,-1.5467,13.96,0.0107],[-6.2,149.85,3.96,-1.5458,13.88,0.0089],[-6.1,148.47,4.0,-1.5448,13.77,0.0101],[-6.0,147.1,4.04,-1.5438,13.7,0.0087],[-5.9,145.74,4.07,-1.5432,13.63,0.0075],[-5.8,144.39,4.11,-1.5422,13.54,0.0086],[-5.7,143.05,4.15,-1.5415,13.42,0.008],[-5.6,141.71,4.19,-1.5406,13.33,0.0078],[-5.5,140.39,4.23,-1.54,13.25,0.0067],[-5.4,139.44,4.68,-1.5353,13.2,0.0061],[-5.3,138.14,4.74,-1.5347,13.13,0.0048],[-5.2,136.83,4.78,-1.5342,13.04,0.0034],[-5.1,135.54,4.83,-1.5342,12.96,0.0],[-5.0,134.25,4.88,-1.5343,12.91,-0.0012],[-4.9,132.96,4.93,-1.5344,12.84,-0.0012],[-4.8,131.69,4.97,-1.5345,12.76,-0.0013],[-4.7,130.42,5.02,-1.5348,12.68,-0.004],[-4.6,129.16,5.06,-1.5353,12.61,-0.0047],[-4.5,127.9,5.11,-1.5356,12.56,-0.0049],[-4.4,124.9,5.72,-1.5292,12.53,-0.0078],[-4.3,123.65,5.77,-1.5301,12.55,-0.0111],[-4.2,122.39,5.82,-1.5316,12.59,-0.0157],[-4.1,121.13,5.87,-1.5333,12.64,-0.0174],[-4.0,119.86,5.92,-1.5351,12.7,-0.0178],[-3.9,118.59,5.96,-1.5369,12.74,-0.0193],[-3.8,117.31,6.0,-1.5391,12.79,-0.0229],[-3.7,116.03,6.04,-1.5415,12.82,-0.0243],[-3.6,114.74,6.07,-1.5439,12.85,-0.024],[-3.5,112.46,6.63,-1.5491,12.86,-0.0248],[-3.4,111.18,6.65,-1.5517,12.87,-0.0265],[-3.3,109.89,6.67,-1.5544,12.9,-0.0266],[-3.2,108.6,6.69,-1.5571,12.91,-0.0267],[-3.1,107.3,6.7,-1.5597,12.91,-0.0268],[-3.0,106.01,6.72,-1.5625,12.91,-0.0271],[-2.9,104.73,6.72,-1.5651,12.87,-0.0256],[-2.8,103.45,6.73,-1.5676,12.81,-0.0244],[-2.7,102.17,6.73,-1.5699,12.72,-0.0229],[-2.6,100.91,6.73,-1.5721,12.64,-0.0231],[-2.5,99.66,6.73,-1.5744,12.55,-0.0238],[-2.4,99.0,7.88,-1.558,12.45,-0.0238],[-2.3,97.77,7.9,-1.5605,12.37,-0.0243],[-2.2,96.53,7.9,-1.5628,12.34,-0.0249],[-2.1,95.3,7.91,-1.5656,12.34,-0.0291],[-2.0,94.06,7.91,-1.5688,12.36,-0.0313],[-1.9,92.83,7.91,-1.5719,12.38,-0.0317],[-1.8,91.59,7.91,-1.5752,12.4,-0.0348],[-1.7,90.34,7.9,-1.5789,12.43,-0.0378],[-1.6,89.1,7.88,-1.5829,12.46,-0.0396],[-1.5,87.85,7.86,-1.5868,12.48,-0.0402],[-1.4,86.76,8.12,-1.5904,12.49,-0.0425],[-1.3,85.51,8.09,-1.5947,12.51,-0.0438],[-1.2,84.26,8.05,-1.5992,12.51,-0.045],[-1.1,83.01,8.01,-1.6038,12.48,-0.0458],[-1.0,81.77,7.97,-1.6083,12.47,-0.0449],[-0.9,80.52,7.91,-1.6128,12.48,-0.0446],[-0.8,79.27,7.86,-1.6172,12.49,-0.0438],[-0.7,78.03,7.79,-1.6215,12.47,-0.043],[-0.6,76.79,7.72,-1.6258,12.45,-0.0412],[-0.5,74.64,7.04,-1.6391,12.42,-0.0366],[-0.4,73.4,6.95,-1.6425,12.4,-0.0324],[-0.3,72.17,6.86,-1.6455,12.37,-0.0296],[-0.2,70.94,6.76,-1.6484,12.31,-0.0276],[-0.1,69.72,6.66,-1.651,12.25,-0.025],[-0.0,68.5,6.56,-1.6533,12.18,-0.0218]],"ring":{"v":1,"lat":35.5220836,"lon":-83.0281416,"r":21.6,"rms":0.31,"ccw":true,"lanes":0,"cov":354.7,"ids":[1514082747,1517278969,1517278970,1517279058,1517279059,1517279060],"tagged":true,"maxspeed":0.0,"app":[[[10.1,19.5],[-5.1,49.6],[-13.4,73.8]],[[-80.4,213.3],[-16.9,14.0]],[[175.1,2.5],[115.0,6.3],[75.7,5.9],[43.2,2.9],[29.4,7.6],[15.6,14.8]],[[13.5,-17.0],[83.3,-7.7],[113.6,-6.0],[176.5,-4.7]],[[-121.1,-33.5],[-103.2,-35.7],[-52.8,-15.3],[-36.9,-12.3],[-15.5,-14.9]],[[-19.6,11.4],[-43.1,4.6],[-109.4,-24.6],[-121.1,-33.5]],[[-13.4,73.8],[-12.0,57.6],[-12.0,40.7],[-16.9,14.0]]]},"hint_speed_ms":7.045}}} diff --git a/selfdrive/controls/lib/tests/data/roundabout_passes_sep28.json b/selfdrive/controls/lib/tests/data/roundabout_passes_sep28.json new file mode 100644 index 00000000000000..4fe29a14b0d849 --- /dev/null +++ b/selfdrive/controls/lib/tests/data/roundabout_passes_sep28.json @@ -0,0 +1 @@ +{"note":"Sep 28 PM Soco/Dellwood/Jonathan Creek ring passes (R126 16:52 CT inner lane, R128 17:38 CT outer lane). Derived from device logs: model desired curvature vs distance, wheel speed, and qcom gpsLocation fix errors relative to the map-matched fused pose (1 Hz, ~0.9 s latency). Local frame: meters east/north of the fitted ring center.","passes":{"00000126":{"label":"R126 16:52 (inner lane)","lane":"inner","t0_ct":"16:52:07.190","takeover_s":6.4,"k_act0":-0.00233,"k_des0":-0.00094,"model_k_ds":0.5,"model_k":[-0.00094,-0.00077,-0.00061,-0.00046,-0.00032,-0.00018,-2e-05,0.00014,0.00028,0.00038,0.00048,0.00063,0.00079,0.00098,0.00122,0.00145,0.0017,0.00196,0.00222,0.0025,0.00277,0.0031,0.00343,0.0037,0.00395,0.00425,0.00467,0.00508,0.00573,0.00639,0.00698,0.00754,0.00808,0.00861,0.00913,0.00963,0.01012,0.01054,0.01094,0.0113,0.01165,0.01202,0.01243,0.01282,0.01317,0.01351,0.01381,0.0141,0.01456,0.01501,0.01571,0.01643,0.01682,0.01715,0.01742,0.01769,0.01799,0.0183,0.01858,0.01885,0.01908,0.01932,0.01944,0.01958,0.01989,0.02026,0.02088,0.02137,0.02166,0.02179,0.02179,0.02188,0.02199,0.02217,0.02241,0.02275,0.02304,0.02331,0.02369,0.02402,0.02425,0.02411,0.02386,0.02375,0.02362,0.02348,0.02366,0.02387,0.0241,0.02422,0.02435,0.02457,0.02457,0.02455,0.02456,0.02483,0.02519,0.02551,0.02566,0.02566,0.02509,0.02465,0.02431,0.02385,0.02341,0.02299,0.02255,0.02196,0.02086,0.01974,0.01859,0.01743,0.01618,0.01472,0.01313,0.01145,0.00971,0.00812,0.00684,0.00535,0.00371,0.00042,-0.00228,-0.0042,-0.00652,-0.00894,-0.01137,-0.0138,-0.01624,-0.01868,-0.02103,-0.02326,-0.02465,-0.02589,-0.02712,-0.02836,-0.0296,-0.03083,-0.03197,-0.03304,-0.03344,-0.0338,-0.03416,-0.03451,-0.03487,-0.03523,-0.03553,-0.03579,-0.03569,-0.0356,-0.0355,-0.03541,-0.03531,-0.03522,-0.03497,-0.0345,-0.03326,-0.03203,-0.0308,-0.02958,-0.02836,-0.02715,-0.02586,-0.02447,-0.02275,-0.02103,-0.01931,-0.01762,-0.01592,-0.01424,-0.01265,-0.0111,-0.01006,-0.00905,-0.00806,-0.00707,-0.00609,-0.00511,-0.00414,-0.00326,-0.00242,-0.00185,-0.00129,-0.00073,-0.00017,0.00039,0.00094,0.00149,0.00201,0.00252,0.0029,0.00327,0.00364,0.004,0.00437,0.00473,0.00509,0.00544,0.00582,0.0062,0.00665,0.00711,0.00756,0.00801,0.00845,0.0089,0.00934,0.00978,0.01012,0.01045,0.01038,0.01023,0.01008,0.00993,0.00978,0.00963,0.00948,0.00933,0.00918,0.00901,0.00881,0.00854,0.00827,0.00801,0.00774,0.00747,0.00721,0.00694,0.00668,0.00641,0.00616,0.0059,0.00566,0.00542,0.00518,0.00494,0.0047,0.00446,0.00422,0.00398,0.00375,0.00353,0.00331,0.00315,0.00299,0.00284,0.00269,0.00254,0.00239,0.00223,0.00208,0.00193,0.00179,0.00166,0.00154,0.0015,0.00146,0.00142,0.00139,0.00135,0.00131,0.00128,0.00124,0.0012,0.00117,0.00114,0.00111,0.00111,0.00112,0.00113,0.00114,0.00115,0.00115,0.00116,0.00117,0.00118,0.00119,0.0012,0.00122,0.00126,0.00132,0.00138,0.00145,0.00151,0.00157,0.00164,0.0017,0.00176,0.00182,0.00188,0.00194,0.00199,0.00202,0.00203,0.00204,0.00206,0.00207,0.00208,0.0021,0.00211,0.00212,0.00214,0.00215,0.00217,0.00219,0.00223,0.00228,0.00233,0.00237,0.00242,0.00247,0.00252,0.00257,0.00262,0.00266,0.00271,0.00275,0.00279,0.00281,0.00282],"v_dt":0.1,"v":[12.816,12.759,12.678,12.593,12.528,12.44,12.341,12.198,12.067,11.943,11.813,11.69,11.596,11.476,11.354,11.21,11.069,10.942,10.829,10.717,10.583,10.457,10.328,10.184,10.048,9.901,9.779,9.636,9.481,9.325,9.17,9.034,8.894,8.734,8.566,8.41,8.268,8.153,8.073,7.991,7.921,7.847,7.781,7.741,7.714,7.695,7.664,7.665,7.682,7.697,7.731,7.773,7.835,7.909,7.978,8.056,8.128,8.205,8.271,8.285,8.286,8.267,8.22,8.174,8.124,8.075,8.019,7.98,7.965,7.94,7.917,7.892,7.867,7.869,7.895,7.891,7.9,7.915,7.908,7.899,7.898,7.882,7.885,7.874,7.863,7.867,7.883,7.918,7.97,8.017,8.085,8.138,8.188,8.276,8.354,8.451,8.538,8.643,8.753,8.862,8.973,9.08,9.183,9.29,9.391,9.507,9.604,9.711,9.812,9.934,10.011,10.088,10.174,10.267,10.356,10.412,10.491,10.567,10.622,10.667,10.738,10.816,10.898,10.983,11.058,11.146,11.22,11.297,11.402,11.497,11.591,11.673,11.747,11.82,11.919,12.018,12.078,12.102,12.122,12.192,12.273,12.343,12.402,12.461,12.528,12.592,12.646,12.698,12.779,12.852,12.887,12.902,12.933,12.995,13.039,13.072,13.111,13.158,13.22,13.27,13.295,13.321,13.349,13.396,13.448,13.506,13.553,13.582,13.64],"fixes":[[-7.179,0.53,4.04,0.5,0.4],[-6.178,-0.63,3.37,-0.4,2.0],[-5.179,-0.41,3.58,-0.5,3.0],[-4.178,-1.14,3.6,-0.1,5.3],[-3.18,-1.91,3.72,-1.2,2.1],[-2.179,-1.7,3.43,2.0,6.2],[-1.184,-0.12,3.35,4.4,6.7],[-0.178,-1.79,3.86,-1.0,4.2],[0.82,-0.43,4.19,-1.0,4.1],[1.816,1.32,3.24,-0.4,4.5],[2.817,2.59,1.45,1.8,6.7],[3.821,1.98,3.18,-6.3,12.5],[4.823,-0.1,7.89,-18.6,15.1],[5.819,-4.43,2.33,-6.8,18.6],[6.82,-1.89,3.15,-5.5,14.0],[7.82,-2.28,2.96,-5.9,3.7],[8.822,-3.83,2.55,-1.9,6.9],[9.815,-1.4,4.05,-2.3,6.9],[10.814,-0.86,4.33,3.0,9.3],[11.814,1.84,5.6,0.2,5.1],[12.816,-1.02,5.16,2.7,2.1],[13.815,-1.01,3.38,1.5,5.3],[14.814,-1.27,2.01,1.2,10.6],[15.812,-1.09,3.47,-2.3,3.7],[16.811,-0.42,3.92,1.3,3.2],[17.814,0.46,3.17,0.0,4.9],[18.81,-2.01,2.99,0.5,6.0]],"hist":[[-8.0,-198.94,-40.55,1.4673,19.89,0.0245],[-7.9,-196.96,-40.34,1.4695,19.91,0.0225],[-7.8,-194.98,-40.15,1.4715,19.89,0.0197],[-7.7,-193.0,-39.95,1.4731,19.88,0.016],[-7.6,-191.02,-39.76,1.4744,19.89,0.0131],[-7.5,-189.04,-39.57,1.4754,19.9,0.0107],[-7.4,-187.06,-39.38,1.4763,19.94,0.0089],[-7.3,-185.07,-39.2,1.4771,19.98,0.0072],[-7.2,-183.08,-39.01,1.4776,19.99,0.0055],[-7.1,-180.55,-39.0,1.4805,19.97,0.0053],[-7.0,-178.55,-38.82,1.4809,19.98,0.0038],[-6.9,-176.56,-38.64,1.4811,20.03,0.0019],[-6.8,-174.56,-38.46,1.4811,20.05,0.0],[-6.7,-172.57,-38.28,1.4809,20.03,-0.0028],[-6.6,-170.57,-38.1,1.4804,20.02,-0.0047],[-6.5,-168.58,-37.92,1.4796,20.03,-0.0076],[-6.4,-166.59,-37.74,1.4786,20.03,-0.0103],[-6.3,-164.59,-37.55,1.4772,20.01,-0.0134],[-6.2,-162.61,-37.36,1.4757,19.94,-0.0153],[-6.1,-160.68,-37.58,1.4722,19.82,-0.0153],[-6.0,-158.72,-37.39,1.4705,19.7,-0.0165],[-5.9,-156.77,-37.19,1.4687,19.59,-0.0187],[-5.8,-154.84,-36.99,1.4666,19.47,-0.0205],[-5.7,-152.91,-36.79,1.4646,19.36,-0.0207],[-5.6,-151.0,-36.58,1.4623,19.23,-0.0222],[-5.5,-149.1,-36.37,1.4598,19.08,-0.0254],[-5.4,-147.22,-36.15,1.4571,18.95,-0.0274],[-5.3,-145.35,-35.93,1.454,18.83,-0.0305],[-5.2,-143.49,-35.71,1.4505,18.7,-0.0348],[-5.1,-141.58,-35.79,1.4442,18.6,-0.0361],[-5.0,-139.75,-35.55,1.4407,18.48,-0.0354],[-4.9,-137.93,-35.3,1.4371,18.36,-0.0352],[-4.8,-136.13,-35.05,1.4335,18.25,-0.0363],[-4.7,-134.33,-34.8,1.4298,18.12,-0.037],[-4.6,-132.55,-34.54,1.426,17.98,-0.0384],[-4.5,-130.79,-34.27,1.4219,17.87,-0.0404],[-4.4,-129.03,-34.0,1.4179,17.75,-0.0405],[-4.3,-127.29,-33.73,1.4137,17.58,-0.0417],[-4.2,-125.57,-33.45,1.4093,17.48,-0.0442],[-4.1,-124.15,-33.5,1.4042,17.4,-0.046],[-4.0,-122.45,-33.2,1.3994,17.27,-0.048],[-3.9,-120.76,-32.9,1.3946,17.13,-0.0484],[-3.8,-119.09,-32.6,1.3896,17.0,-0.0498],[-3.7,-117.43,-32.28,1.3843,16.89,-0.0524],[-3.6,-115.78,-31.96,1.379,16.77,-0.0538],[-3.5,-114.15,-31.64,1.3735,16.64,-0.055],[-3.4,-112.54,-31.31,1.3678,16.5,-0.057],[-3.3,-110.93,-30.97,1.3619,16.37,-0.0583],[-3.2,-109.34,-30.62,1.356,16.27,-0.0591],[-3.1,-108.47,-30.45,1.344,16.16,-0.0579],[-3.0,-106.91,-30.08,1.3384,16.02,-0.0566],[-2.9,-105.36,-29.71,1.3326,15.89,-0.0573],[-2.8,-103.83,-29.33,1.3267,15.79,-0.059],[-2.7,-102.31,-28.94,1.3209,15.7,-0.0581],[-2.6,-100.8,-28.54,1.3152,15.57,-0.0574],[-2.5,-99.31,-28.15,1.3094,15.42,-0.0582],[-2.4,-97.84,-27.74,1.3034,15.28,-0.0592],[-2.3,-96.38,-27.33,1.2974,15.16,-0.0604],[-2.2,-94.94,-26.92,1.2913,15.05,-0.0614],[-2.1,-94.04,-27.09,1.2958,14.91,-0.0596],[-2.0,-92.62,-26.68,1.2901,14.8,-0.0575],[-1.9,-91.21,-26.26,1.2841,14.67,-0.0599],[-1.8,-89.82,-25.84,1.278,14.52,-0.0609],[-1.7,-88.44,-25.42,1.2721,14.4,-0.0595],[-1.6,-87.08,-24.99,1.2661,14.29,-0.0597],[-1.5,-85.73,-24.56,1.2601,14.16,-0.0601],[-1.4,-84.4,-24.12,1.2542,14.04,-0.0592],[-1.3,-83.08,-23.68,1.2485,13.92,-0.0571],[-1.2,-81.77,-23.23,1.2428,13.82,-0.0564],[-1.1,-80.17,-23.55,1.2598,13.71,-0.0556],[-1.0,-78.88,-23.14,1.2547,13.59,-0.0538],[-0.9,-77.6,-22.72,1.2495,13.5,-0.0521],[-0.8,-76.33,-22.29,1.2442,13.4,-0.0527],[-0.7,-75.07,-21.85,1.2391,13.33,-0.0511],[-0.6,-73.82,-21.41,1.2343,13.23,-0.0485],[-0.5,-72.58,-20.97,1.2295,13.15,-0.0474],[-0.4,-71.35,-20.53,1.225,13.08,-0.0448],[-0.3,-70.13,-20.08,1.221,13.02,-0.0403],[-0.2,-68.91,-19.64,1.2174,12.95,-0.0355],[-0.1,-68.34,-19.34,1.209,12.87,-0.0334],[0.0,-67.15,-18.89,1.2059,12.82,-0.0299]],"ring":{"v":1,"lat":35.5220836,"lon":-83.0281416,"r":21.6,"rms":0.31,"ccw":true,"lanes":0,"cov":354.7,"ids":[1514082747,1517278969,1517278970,1517279058,1517279059,1517279060],"tagged":true,"maxspeed":0.0,"app":[[[10.1,19.5],[-5.1,49.6],[-13.4,73.8]],[[-80.4,213.3],[-16.9,14.0]],[[175.1,2.5],[115.0,6.3],[75.7,5.9],[43.2,2.9],[29.4,7.6],[15.6,14.8]],[[13.5,-17.0],[83.3,-7.7],[113.6,-6.0],[176.5,-4.7]],[[-121.1,-33.5],[-103.2,-35.7],[-52.8,-15.3],[-36.9,-12.3],[-15.5,-14.9]],[[-19.6,11.4],[-43.1,4.6],[-109.4,-24.6],[-121.1,-33.5]],[[-13.4,73.8],[-12.0,57.6],[-12.0,40.7],[-16.9,14.0]]]},"hint_speed_ms":7.045},"00000128":{"label":"R128 17:38 (outer lane)","lane":"outer","t0_ct":"17:38:07.202","takeover_s":1.7,"k_act0":-0.00203,"k_des0":-0.00166,"model_k_ds":0.5,"model_k":[-0.00166,-0.00159,-0.00153,-0.00146,-0.00141,-0.00136,-0.00131,-0.00124,-0.00117,-0.00109,-0.00096,-0.00083,-0.0007,-0.00054,-0.00038,-0.00024,-0.00012,-1e-05,9e-05,0.00019,0.00028,0.00041,0.00054,0.00067,0.00091,0.00116,0.00141,0.0017,0.00199,0.00226,0.00251,0.00276,0.0031,0.00344,0.00386,0.0044,0.00494,0.00552,0.00609,0.00664,0.00714,0.00764,0.00806,0.00848,0.00904,0.00972,0.0103,0.01061,0.01091,0.01153,0.01217,0.01288,0.01362,0.01432,0.01498,0.01557,0.01595,0.01632,0.01668,0.01704,0.01754,0.01804,0.01829,0.01853,0.01916,0.01981,0.01956,0.01923,0.01933,0.01949,0.01975,0.01999,0.0199,0.01982,0.01976,0.01981,0.02015,0.02028,0.02014,0.02002,0.01991,0.02031,0.02083,0.02061,0.0202,0.01933,0.01893,0.01886,0.01836,0.01777,0.01708,0.01662,0.01632,0.01617,0.01579,0.01481,0.01439,0.01418,0.01397,0.01376,0.01354,0.01333,0.0132,0.0132,0.01363,0.01416,0.0147,0.01523,0.01575,0.01628,0.01656,0.01655,0.01536,0.01393,0.0125,0.01109,0.00968,0.00827,0.00681,0.00502,0.00281,0.00011,-0.00256,-0.00523,-0.00788,-0.01053,-0.01317,-0.01558,-0.01788,-0.01938,-0.02082,-0.02225,-0.02368,-0.02511,-0.02654,-0.02796,-0.02913,-0.03017,-0.03058,-0.03099,-0.03139,-0.0318,-0.03221,-0.03262,-0.03303,-0.03352,-0.03407,-0.03478,-0.0355,-0.03621,-0.03693,-0.03765,-0.03837,-0.03903,-0.03941,-0.03936,-0.03882,-0.03828,-0.03774,-0.03719,-0.03665,-0.0361,-0.03562,-0.03522,-0.03507,-0.03501,-0.03494,-0.03487,-0.03481,-0.03474,-0.03467,-0.03412,-0.0333,-0.03126,-0.02923,-0.0272,-0.02519,-0.02319,-0.0212,-0.01923,-0.01744,-0.01576,-0.01441,-0.01308,-0.01175,-0.01044,-0.00913,-0.00784,-0.00655,-0.00542,-0.00435,-0.00369,-0.00314,-0.00261,-0.00207,-0.00154,-0.00102,-0.00049,3e-05,0.00042,0.00077,0.00085,0.00079,0.00073,0.00067,0.00061,0.00055,0.00049,0.00044,0.00038,0.00033,0.00028,0.00025,0.00022,0.0002,0.00017,0.00014,0.00011,9e-05,6e-05,3e-05,1e-05,-1e-05,-3e-05,-5e-05,-6e-05,-8e-05,-0.0001,-0.00011,-0.00013,-0.00014,-0.00016,-0.00017,-0.00018,-0.00018,-0.00017,-0.00015,-0.00013,-0.00011,-8e-05,-6e-05,-4e-05,-2e-05,-0.0,2e-05,4e-05,7e-05,0.0001,0.00013,0.00016,0.0002,0.00023,0.00027,0.0003,0.00034,0.00037,0.0004,0.00044,0.00045,0.00046,0.00045,0.0004,0.00034,0.00029,0.00024,0.00019,0.00014,8e-05,3e-05,-2e-05,-7e-05,-0.0001,-0.00012,-0.00014,-8e-05,-3e-05,3e-05,9e-05,0.00014,0.0002,0.00025,0.00031,0.00036,0.00042,0.00047,0.00053,0.00059,0.00065,0.00071,0.00077,0.00084,0.0009,0.00096,0.00102,0.00109,0.00115,0.00121,0.00127,0.00134,0.00142,0.0015,0.00158,0.00171,0.00184,0.00197,0.0021,0.00223,0.00236,0.00249,0.00262,0.00275,0.00287,0.003,0.00311,0.0032,0.00328,0.00332,0.0033,0.00327,0.00324],"v_dt":0.1,"v":[15.246,15.058,14.882,14.702,14.515,14.314,14.123,13.917,13.713,13.508,13.311,13.099,12.871,12.644,12.404,12.179,11.941,11.718,11.505,11.292,11.091,10.897,10.705,10.503,10.363,10.202,10.055,9.919,9.759,9.62,9.508,9.358,9.233,9.103,8.979,8.855,8.727,8.601,8.48,8.356,8.23,8.149,8.069,7.99,7.947,7.912,7.884,7.878,7.904,7.914,7.953,7.999,8.055,8.113,8.172,8.243,8.309,8.375,8.421,8.466,8.532,8.589,8.634,8.679,8.715,8.764,8.799,8.825,8.854,8.872,8.881,8.899,8.911,8.881,8.866,8.849,8.817,8.778,8.719,8.68,8.687,8.654,8.631,8.626,8.62,8.614,8.62,8.645,8.695,8.749,8.811,8.892,8.997,9.106,9.228,9.356,9.491,9.612,9.722,9.834,9.94,10.061,10.192,10.327,10.447,10.603,10.745,10.836,10.94,11.064,11.229,11.412,11.557,11.657,11.78,11.918,12.044,12.136,12.211,12.273,12.357,12.451,12.526,12.6,12.683,12.755,12.826,12.893,13.001,13.102,13.19,13.283,13.365,13.456,13.554,13.652,13.739,13.831,13.926,14.018,14.101,14.224,14.328,14.418,14.51,14.618,14.74,14.863,14.966],"fixes":[[-7.295,-0.34,-0.66,0.8,1.4],[-6.188,0.68,0.56,-1.2,2.1],[-5.189,0.15,0.04,-0.1,1.3],[-4.188,0.41,-0.27,-0.4,1.3],[-3.291,-0.92,-0.01,0.3,1.3],[-2.189,1.72,0.26,-0.4,1.8],[-1.19,1.9,0.94,0.4,5.0],[-0.189,1.24,0.18,-0.3,1.2],[0.71,-0.67,-0.65,-1.0,1.2],[1.811,-0.23,-0.61,0.4,3.4],[2.811,0.47,1.97,2.6,2.4],[3.811,1.64,3.58,3.8,4.5],[4.709,1.77,4.92,2.8,2.5],[5.817,0.72,1.38,1.3,5.5],[6.817,0.27,0.54,-3.5,0.6],[7.819,-0.35,-2.29,-4.9,6.9],[8.71,-1.14,-2.89,1.0,11.5],[9.819,1.18,-4.09,-8.5,0.6],[10.809,0.7,-3.11,0.9,0.7],[11.814,0.6,-0.46,1.7,0.7],[12.709,-1.07,-0.81,1.1,0.5],[13.81,-0.0,0.36,1.1,0.7],[14.812,-0.18,0.23,-0.4,0.4],[15.71,-2.7,-0.12,1.7,0.6]],"hist":[[-8.0,211.51,4.69,-1.608,18.89,0.0316],[-7.9,209.62,4.63,-1.6047,18.88,0.0332],[-7.8,207.73,4.57,-1.6011,18.86,0.0359],[-7.7,205.85,4.52,-1.5974,18.86,0.0367],[-7.6,203.96,4.48,-1.5936,18.87,0.0385],[-7.5,202.08,4.44,-1.5897,18.85,0.0385],[-7.4,200.2,4.41,-1.5859,18.81,0.0381],[-7.3,198.31,4.39,-1.5822,18.79,0.037],[-7.2,195.98,4.2,-1.5749,18.8,0.0371],[-7.1,194.1,4.2,-1.5712,18.84,0.0363],[-7.0,192.21,4.2,-1.5678,18.84,0.0348],[-6.9,190.34,4.21,-1.5647,18.79,0.0302],[-6.8,188.46,4.23,-1.5617,18.79,0.0301],[-6.7,186.57,4.25,-1.5587,18.85,0.03],[-6.6,184.68,4.28,-1.5557,18.92,0.0301],[-6.5,182.79,4.31,-1.5531,18.94,0.0264],[-6.4,180.89,4.35,-1.5509,18.94,0.0223],[-6.3,179.0,4.39,-1.5487,18.96,0.0216],[-6.2,177.1,4.44,-1.5467,18.99,0.021],[-6.1,175.53,4.63,-1.5507,19.02,0.02],[-6.0,173.63,4.67,-1.5489,19.04,0.0189],[-5.9,171.73,4.72,-1.5473,19.05,0.0165],[-5.8,169.82,4.76,-1.5457,19.06,0.0154],[-5.7,167.92,4.81,-1.5443,19.06,0.0143],[-5.6,166.01,4.87,-1.5429,19.03,0.0143],[-5.5,164.11,4.92,-1.5416,19.02,0.0129],[-5.4,162.21,4.98,-1.5404,19.02,0.0119],[-5.3,160.31,5.04,-1.5393,19.02,0.0109],[-5.2,158.41,5.1,-1.5381,19.0,0.0116],[-5.1,156.59,5.15,-1.5376,18.98,0.0079],[-5.0,154.69,5.22,-1.5369,18.99,0.0078],[-4.9,152.79,5.28,-1.5362,18.98,0.0068],[-4.8,150.9,5.35,-1.5354,18.95,0.0081],[-4.7,149.01,5.42,-1.5346,18.94,0.0076],[-4.6,147.12,5.49,-1.534,18.9,0.0064],[-4.5,145.23,5.56,-1.5331,18.91,0.0092],[-4.4,143.33,5.63,-1.532,18.99,0.0107],[-4.3,141.43,5.71,-1.5306,19.04,0.014],[-4.2,139.53,5.79,-1.5293,19.03,0.0134],[-4.1,137.83,5.66,-1.5306,19.04,0.0088],[-4.0,135.92,5.74,-1.5297,19.05,0.0091],[-3.9,134.02,5.82,-1.5287,19.01,0.0097],[-3.8,132.13,5.9,-1.5278,18.99,0.0093],[-3.7,130.23,5.99,-1.5269,18.98,0.0086],[-3.6,128.34,6.07,-1.5262,18.93,0.007],[-3.5,126.46,6.16,-1.5258,18.84,0.0043],[-3.4,124.58,6.24,-1.5257,18.77,0.001],[-3.3,122.71,6.33,-1.5257,18.68,-0.0002],[-3.2,120.31,6.5,-1.524,18.57,-0.0018],[-3.1,118.46,6.59,-1.5245,18.47,-0.0051],[-3.0,116.63,6.67,-1.5254,18.39,-0.0087],[-2.9,114.8,6.75,-1.5265,18.32,-0.011],[-2.8,112.98,6.83,-1.5278,18.23,-0.013],[-2.7,111.17,6.91,-1.5292,18.11,-0.0143],[-2.6,109.37,6.98,-1.5311,18.01,-0.0193],[-2.5,107.57,7.04,-1.5336,17.93,-0.0245],[-2.4,105.79,7.11,-1.5361,17.82,-0.0252],[-2.3,104.02,7.16,-1.5388,17.71,-0.027],[-2.2,102.27,7.22,-1.5417,17.62,-0.0293],[-2.1,101.37,7.33,-1.5469,17.53,-0.032],[-2.0,99.62,7.36,-1.5505,17.43,-0.0352],[-1.9,97.89,7.39,-1.5542,17.34,-0.0376],[-1.8,96.17,7.41,-1.5583,17.24,-0.0407],[-1.7,94.45,7.43,-1.5626,17.16,-0.0436],[-1.6,92.74,7.43,-1.5673,17.07,-0.0461],[-1.5,91.05,7.43,-1.5719,16.98,-0.0461],[-1.4,89.36,7.42,-1.5766,16.89,-0.0476],[-1.3,87.68,7.4,-1.5817,16.8,-0.0503],[-1.2,86.01,7.37,-1.5868,16.7,-0.0515],[-1.1,85.29,7.82,-1.5898,16.6,-0.052],[-1.0,83.64,7.78,-1.5949,16.52,-0.0511],[-0.9,82.0,7.73,-1.5998,16.42,-0.0491],[-0.8,80.37,7.68,-1.6049,16.33,-0.0504],[-0.7,78.75,7.61,-1.6098,16.22,-0.0491],[-0.6,77.14,7.54,-1.6146,16.06,-0.0477],[-0.5,75.55,7.47,-1.6193,15.94,-0.0473],[-0.4,73.97,7.38,-1.6237,15.82,-0.0443],[-0.3,72.41,7.29,-1.6279,15.68,-0.042],[-0.2,70.86,7.2,-1.6318,15.54,-0.0382],[-0.1,69.94,7.14,-1.6366,15.4,-0.0339],[-0.0,68.42,7.04,-1.6397,15.25,-0.031]],"ring":{"v":1,"lat":35.5220836,"lon":-83.0281416,"r":21.6,"rms":0.31,"ccw":true,"lanes":0,"cov":354.7,"ids":[1514082747,1517278969,1517278970,1517279058,1517279059,1517279060],"tagged":true,"maxspeed":0.0,"app":[[[10.1,19.5],[-5.1,49.6],[-13.4,73.8]],[[-80.4,213.3],[-16.9,14.0]],[[175.1,2.5],[115.0,6.3],[75.7,5.9],[43.2,2.9],[29.4,7.6],[15.6,14.8]],[[13.5,-17.0],[83.3,-7.7],[113.6,-6.0],[176.5,-4.7]],[[-121.1,-33.5],[-103.2,-35.7],[-52.8,-15.3],[-36.9,-12.3],[-15.5,-14.9]],[[-19.6,11.4],[-43.1,4.6],[-109.4,-24.6],[-121.1,-33.5]],[[-13.4,73.8],[-12.0,57.6],[-12.0,40.7],[-16.9,14.0]]]},"hint_speed_ms":7.045}}} diff --git a/selfdrive/controls/lib/tests/data/roundabout_passes_sep29.json b/selfdrive/controls/lib/tests/data/roundabout_passes_sep29.json new file mode 100644 index 00000000000000..199190fbec6830 --- /dev/null +++ b/selfdrive/controls/lib/tests/data/roundabout_passes_sep29.json @@ -0,0 +1 @@ +{"note":"Sep 29 ring passes for the Sep 30 ring-follow replay: 0000012f (11:57 CT, Scallywag, inner lane) and 00000130 (16:52 CT, b733359, outer lane). Same format as roundabout_passes_sep28.json: logged model curvature vs distance, wheel speed, fused-pose history and the real qcom GNSS errors.","passes":{"0000012f":{"label":"R12f","lane":"inner","t0_ct":"11:57:43.030","takeover_s":0.0,"k_act0":-0.00016,"k_des0":0.0005,"model_k_ds":0.5,"model_k":[-0.00023,-0.00023,-0.00023,-0.00023,-0.00023,-0.00023,0.00013,0.0009,0.00167,0.0019,0.0019,0.0019,0.0019,0.0019,0.0019,0.0019,0.0019,0.0019,0.0019,0.0019,0.00441,0.00705,0.00885,0.00885,0.00885,0.00885,0.00885,0.00885,0.00885,0.00885,0.00885,0.00885,0.00885,0.01177,0.01476,0.01642,0.01642,0.01642,0.01642,0.01642,0.01642,0.01642,0.01642,0.01642,0.01642,0.01726,0.0186,0.01962,0.01962,0.01962,0.01962,0.01962,0.01962,0.01962,0.01962,0.01962,0.01962,0.0202,0.02086,0.02114,0.02114,0.02114,0.02114,0.02114,0.02114,0.02114,0.02114,0.02114,0.02166,0.0223,0.0225,0.0225,0.0225,0.0225,0.0225,0.0225,0.0225,0.0225,0.02278,0.02343,0.02382,0.02382,0.02382,0.02382,0.02382,0.02382,0.02382,0.02382,0.02397,0.02417,0.02418,0.02418,0.02418,0.02418,0.02418,0.02418,0.02418,0.01958,0.01396,0.01396,0.01396,0.01396,0.01396,0.01396,0.01396,0.00986,-0.00014,-0.00206,-0.00206,-0.00206,-0.00206,-0.00206,-0.00206,-0.00938,-0.02246,-0.02246,-0.02246,-0.02246,-0.02246,-0.02246,-0.02251,-0.02333,-0.02367,-0.02367,-0.02367,-0.02367,-0.02367,-0.02367,-0.01761,-0.01398,-0.01398,-0.01398,-0.01398,-0.01398,-0.01398,-0.01739,-0.0192,-0.0192,-0.0192,-0.0192,-0.0192,-0.0192,-0.03098,-0.03921,-0.03921,-0.03921,-0.03921,-0.03921,-0.03921,-0.03707,-0.03383,-0.03383,-0.03383,-0.03383,-0.03383,-0.03383,-0.03355,-0.02559,-0.02117,-0.02117,-0.02117,-0.02117,-0.02117,-0.02117,-0.02117,-0.01264,-0.00481,-0.00481,-0.00481,-0.00481,-0.00481,-0.00481,-0.00481,-0.00468,-0.00225,-0.00031,-0.00031,-0.00031,-0.00031,-0.00031,-0.00031,-0.00031,-0.00031,0.00058,0.00228,0.00311,0.00311,0.00311,0.00311,0.00311,0.00311,0.00311,0.00311,0.00345,0.00438,0.00505,0.00505,0.00505,0.00505,0.00505,0.00505,0.00505,0.00505,0.00505,0.00483,0.00452,0.00436,0.00436,0.00436,0.00436,0.00436,0.00436,0.00436,0.00436,0.00436,0.00412,0.00378,0.0036,0.0036,0.0036,0.0036,0.0036,0.0036,0.0036,0.0036,0.0036,0.00359,0.00358,0.00357,0.00357,0.00357,0.00357,0.00357,0.00357,0.00357,0.00357,0.00357,0.00344,0.00286,0.00228,0.00225,0.00225,0.00225,0.00225,0.00225,0.00225,0.00225,0.00225,0.00225,0.00213,0.00195,0.00184,0.00184,0.00184,0.00184,0.00184,0.00184,0.00184,0.00184,0.00184,0.00184,0.00221,0.00259,0.00275,0.00275,0.00275,0.00275,0.00275,0.00275,0.00275,0.00275,0.00275,0.00275,0.00245,0.00213,0.00199,0.00199,0.00199,0.00199,0.00199,0.00199,0.00199,0.00199,0.00199,0.00199,0.00179,0.00153,0.00136,0.00136,0.00136,0.00136,0.00136,0.00136,0.00136,0.00136,0.00136,0.00136,0.00155,0.00205,0.00254,0.00262,0.00262,0.00262,0.00262,0.00262,0.00262,0.00262,0.00262,0.00262,0.00262,0.0026,0.00257,0.00254,0.00254,0.00254,0.00254,0.00254,0.00254,0.00254,0.00254],"v_dt":0.1,"v":[14.022,13.928,13.81,13.695,13.58,13.481,13.4,13.306,13.191,13.06,12.936,12.834,12.742,12.632,12.515,12.383,12.257,12.127,12.007,11.882,11.729,11.597,11.467,11.351,11.223,11.066,10.925,10.798,10.67,10.52,10.357,10.233,10.104,9.99,9.832,9.665,9.523,9.41,9.269,9.127,8.972,8.818,8.682,8.592,8.478,8.367,8.247,8.135,8.032,7.94,7.85,7.758,7.691,7.643,7.6,7.539,7.447,7.36,7.318,7.261,7.17,7.076,7.036,6.998,6.971,6.944,6.956,6.967,7.001,7.03,7.059,7.096,7.129,7.155,7.201,7.253,7.299,7.363,7.412,7.466,7.549,7.635,7.725,7.857,7.993,8.131,8.277,8.426,8.572,8.709,8.836,8.982,9.129,9.27,9.399,9.529,9.655,9.804,9.915,10.027,10.157,10.287,10.402,10.498,10.596,10.688,10.766,10.816,10.879,10.95,10.998,11.046,11.067,11.109,11.13,11.155,11.193,11.228,11.263,11.289,11.314,11.329,11.378,11.445,11.504,11.529,11.551,11.588,11.651,11.702,11.744,11.791,11.832,11.879,11.917,11.966,12.008,12.076,12.128,12.176,12.185,12.219,12.277,12.323,12.349,12.387,12.443,12.494,12.54,12.58,12.606,12.631,12.648,12.671,12.699,12.727,12.737,12.746,12.769,12.814,12.867,12.906,12.975,13.05,13.105,13.17,13.246,13.314,13.358,13.366,13.351],"fixes":[[-1.639,0.25,-1.06,4.1,23.0],[-0.747,1.72,-0.05,3.8,27.3],[0.358,2.17,0.03,3.8,30.2],[1.356,0.2,2.54,0.8,34.0],[2.362,0.31,2.67,-3.0,32.9],[3.356,-2.42,3.6,-15.8,41.2],[4.357,1.11,1.51,-12.7,38.1],[5.358,5.34,1.3,-16.9,39.3],[6.361,1.96,3.36,-2.9,39.3],[7.364,2.64,4.42,-1.8,44.6],[8.36,4.62,0.87,10.2,49.4],[9.362,-2.69,0.86,8.9,44.6],[10.359,-4.74,1.08,4.1,51.6],[11.362,-2.7,-0.03,-0.1,36.0],[12.36,-0.52,0.45,-1.2,32.4],[13.364,-0.34,3.08,-2.8,33.5],[14.359,-2.73,1.55,-1.5,39.2],[15.358,1.77,2.13,-0.9,19.2],[16.355,2.69,2.65,-1.8,13.1],[17.364,-0.32,3.4,-2.9,17.2]],"hist":[[-2.6,-105.17,-30.3,1.3082,16.46,-0.0659],[-2.5,-103.59,-29.87,1.3015,16.37,-0.068],[-2.4,-102.03,-29.42,1.2947,16.28,-0.0692],[-2.3,-100.47,-28.97,1.2877,16.2,-0.0687],[-2.2,-98.93,-28.51,1.2809,16.11,-0.0706],[-2.1,-97.4,-28.04,1.2737,16.01,-0.074],[-2.0,-95.88,-27.56,1.2662,15.9,-0.0742],[-1.9,-94.37,-27.08,1.2588,15.81,-0.0742],[-1.8,-92.88,-26.59,1.2514,15.72,-0.0735],[-1.7,-91.4,-26.11,1.2441,15.62,-0.073],[-1.6,-89.69,-27.16,1.2368,15.55,-0.0684],[-1.5,-88.23,-26.64,1.2302,15.48,-0.0657],[-1.4,-86.78,-26.12,1.2236,15.39,-0.061],[-1.3,-85.35,-25.59,1.2178,15.29,-0.0564],[-1.2,-83.93,-25.06,1.2123,15.19,-0.0537],[-1.1,-82.51,-24.52,1.207,15.1,-0.0493],[-1.0,-81.12,-23.98,1.2022,14.99,-0.0442],[-0.9,-79.73,-23.44,1.198,14.88,-0.0414],[-0.8,-78.34,-22.91,1.1939,14.78,-0.0371],[-0.7,-76.14,-23.1,1.1904,14.69,-0.0314],[-0.6,-74.79,-22.56,1.1875,14.59,-0.0253],[-0.5,-73.45,-22.01,1.1852,14.48,-0.0226],[-0.4,-72.11,-21.47,1.1829,14.4,-0.0199],[-0.3,-70.79,-20.92,1.1811,14.3,-0.015],[-0.2,-69.48,-20.38,1.1798,14.2,-0.007],[-0.1,-68.17,-19.84,1.1794,14.11,-0.0043]],"ring":{"v":1,"lat":35.5220836,"lon":-83.0281416,"r":21.6,"rms":0.31,"ccw":true,"lanes":0,"cov":354.7,"ids":[1514082747,1517278969,1517278970,1517279058,1517279059,1517279060],"tagged":true,"maxspeed":0.0,"app":[[[10.1,19.5],[-5.1,49.6],[-13.4,73.8]],[[-80.4,213.3],[-16.9,14.0]],[[175.1,2.5],[115.0,6.3],[75.7,5.9],[43.2,2.9],[29.4,7.6],[15.6,14.8]],[[13.5,-17.0],[83.3,-7.7],[113.6,-6.0],[176.5,-4.7]],[[-121.1,-33.5],[-103.2,-35.7],[-52.8,-15.3],[-36.9,-12.3],[-15.5,-14.9]],[[-19.6,11.4],[-43.1,4.6],[-109.4,-24.6],[-121.1,-33.5]],[[-13.4,73.8],[-12.0,57.6],[-12.0,40.7],[-16.9,14.0]]]},"hint_speed_ms":7.045},"00000130":{"label":"R130","lane":"outer","t0_ct":"16:52:51.389","takeover_s":0.0,"k_act0":-0.00189,"k_des0":-0.00169,"model_k_ds":0.5,"model_k":[-0.00171,-0.00171,-0.00171,-0.00171,-0.00164,-0.00095,-0.00039,-0.00039,-0.00039,-0.00039,-0.00039,-0.00039,-0.00039,-0.00039,0.00028,0.00129,0.0015,0.0015,0.0015,0.0015,0.0015,0.0015,0.0015,0.00217,0.00329,0.00348,0.00348,0.00348,0.00348,0.00348,0.00348,0.00348,0.00467,0.00574,0.00574,0.00574,0.00574,0.00574,0.00574,0.00574,0.00674,0.00892,0.00931,0.00931,0.00931,0.00931,0.00931,0.00931,0.01003,0.0131,0.01434,0.01434,0.01434,0.01434,0.01434,0.01434,0.01501,0.01884,0.02053,0.02053,0.02053,0.02053,0.02053,0.02053,0.02121,0.02536,0.02728,0.02728,0.02728,0.02728,0.02728,0.02728,0.02688,0.02495,0.02421,0.02421,0.02421,0.02421,0.02421,0.02421,0.02198,0.0157,0.01419,0.01419,0.01419,0.01419,0.01419,0.01419,0.01268,0.00939,0.00911,0.00911,0.00911,0.00911,0.00911,0.00911,0.00732,0.00457,0.00457,0.00457,0.00457,0.00457,0.00457,0.00457,-0.0006,-0.00541,-0.00541,-0.00541,-0.00541,-0.00541,-0.00541,-0.00541,-0.01033,-0.01308,-0.01308,-0.01308,-0.01308,-0.01308,-0.01308,-0.01406,-0.01859,-0.02017,-0.02017,-0.02017,-0.02017,-0.02017,-0.02017,-0.01908,-0.01644,-0.01613,-0.01613,-0.01613,-0.01613,-0.01613,-0.01613,-0.01582,-0.01554,-0.01554,-0.01554,-0.01554,-0.01554,-0.01554,-0.01554,-0.02239,-0.02919,-0.02919,-0.02919,-0.02919,-0.02919,-0.02919,-0.02919,-0.0299,-0.03115,-0.03127,-0.03127,-0.03127,-0.03127,-0.03127,-0.03127,-0.0315,-0.03229,-0.03258,-0.03258,-0.03258,-0.03258,-0.03258,-0.03258,-0.03258,-0.0309,-0.02922,-0.02922,-0.02922,-0.02922,-0.02922,-0.02922,-0.02922,-0.02862,-0.02283,-0.01869,-0.01869,-0.01869,-0.01869,-0.01869,-0.01869,-0.01869,-0.01869,-0.01415,-0.00837,-0.00741,-0.00741,-0.00741,-0.00741,-0.00741,-0.00741,-0.00741,-0.00741,-0.00523,-0.00283,-0.00245,-0.00245,-0.00245,-0.00245,-0.00245,-0.00245,-0.00245,-0.00245,-0.00202,-0.00107,-0.00036,-0.00036,-0.00036,-0.00036,-0.00036,-0.00036,-0.00036,-0.00036,-0.00036,-0.00041,-0.00062,-0.00083,-0.00085,-0.00085,-0.00085,-0.00085,-0.00085,-0.00085,-0.00085,-0.00085,-0.00085,-0.00085,-0.00084,-0.00083,-0.00083,-0.00083,-0.00083,-0.00083,-0.00083,-0.00083,-0.00083,-0.00083,-0.00083,-0.00083,-0.00077,-0.0007,-0.00064,-0.00064,-0.00064,-0.00064,-0.00064,-0.00064,-0.00064,-0.00064,-0.00064,-0.00064,-0.00064,-0.0005,-0.0003,-0.0001,-0.0001,-0.0001,-0.0001,-0.0001,-0.0001,-0.0001,-0.0001,-0.0001,-0.0001,-0.0001,-9e-05,-8e-05,-6e-05,-5e-05,-5e-05,-5e-05,-5e-05,-5e-05,-5e-05,-5e-05,-5e-05,-5e-05,-5e-05,-5e-05,-5e-05,8e-05,0.00021,0.00032,0.00032,0.00032,0.00032,0.00032,0.00032,0.00032,0.00032,0.00032,0.00032,0.00032,0.00032,0.00047,0.0007,0.00093,0.00099,0.00099,0.00099,0.00099,0.00099,0.00099,0.00099,0.00099,0.00099,0.00099,0.00099,0.00099,0.00138,0.00184,0.0023,0.00239,0.00239,0.00239,0.00239,0.00239],"v_dt":0.1,"v":[9.908,9.833,9.721,9.621,9.525,9.444,9.36,9.282,9.202,9.127,9.044,8.974,8.913,8.84,8.768,8.705,8.64,8.577,8.521,8.466,8.414,8.375,8.333,8.289,8.261,8.218,8.198,8.16,8.129,8.11,8.073,8.062,8.035,8.02,8.021,8.004,7.984,7.974,7.957,7.933,7.932,7.918,7.904,7.897,7.892,7.89,7.884,7.871,7.879,7.873,7.853,7.858,7.855,7.844,7.853,7.851,7.852,7.845,7.836,7.845,7.84,7.824,7.811,7.784,7.797,7.812,7.81,7.817,7.804,7.797,7.786,7.788,7.782,7.792,7.792,7.78,7.758,7.727,7.703,7.667,7.613,7.594,7.621,7.711,7.872,8.008,8.112,8.194,8.237,8.243,8.237,8.236,8.238,8.263,8.272,8.279,8.289,8.327,8.354,8.361,8.419,8.484,8.541,8.586,8.668,8.763,8.858,8.977,9.092,9.208,9.321,9.427,9.532,9.636,9.751,9.855,9.988,10.102,10.233,10.363,10.49,10.589,10.698,10.834,11.013,11.198,11.347,11.485,11.639,11.793,11.946,12.07,12.188,12.308,12.427,12.546,12.662,12.797,12.907,13.003,13.088,13.199,13.323,13.416,13.511,13.59,13.679,13.774,13.851,13.927,14.022,14.096,14.181,14.27,14.347,14.432,14.507,14.563,14.645,14.731,14.826,14.922,14.995,15.067,15.146,15.236,15.313],"fixes":[[-7.132,-1.85,1.6,0.4,5.5],[-6.018,0.84,1.94,1.0,2.2],[-5.019,0.83,3.18,-0.7,0.9],[-4.018,1.68,4.51,0.7,6.1],[-3.015,3.1,5.21,3.6,9.2],[-2.017,1.06,2.89,-0.9,5.2],[-1.019,-0.67,0.33,-0.6,0.6],[-0.016,0.06,3.05,1.5,7.3],[0.989,-0.25,2.75,1.0,9.1],[1.989,0.72,0.88,-2.1,10.7],[2.991,0.26,2.18,-1.5,10.9],[3.988,-0.53,2.2,-1.9,8.9],[4.984,-1.04,1.41,4.7,2.2],[5.982,0.29,1.59,0.1,5.3],[6.984,0.77,1.81,-5.4,11.6],[7.986,0.72,0.67,-3.8,3.4],[8.989,1.28,0.3,1.1,4.6],[9.985,-1.22,-1.67,-2.6,5.0],[10.985,-1.56,0.08,4.7,9.2],[11.985,-0.75,-0.79,-4.1,0.7],[12.981,-0.27,1.85,-2.4,2.1],[13.99,-1.25,2.08,-1.1,2.8],[14.982,-0.55,3.67,-0.4,0.7],[15.984,-0.78,4.63,0.0,0.6],[16.99,-0.54,3.02,0.2,2.4]],"hist":[[-8.0,174.24,6.18,-1.5599,16.91,0.0149],[-7.9,172.56,6.2,-1.5585,16.81,0.0166],[-7.8,170.88,6.23,-1.5568,16.71,0.0151],[-7.7,169.22,6.25,-1.5553,16.61,0.0117],[-7.6,167.57,6.28,-1.5542,16.53,0.0125],[-7.5,165.93,6.31,-1.5529,16.45,0.0092],[-7.4,164.29,6.34,-1.5521,16.37,0.0097],[-7.3,162.66,6.37,-1.5511,16.26,0.0087],[-7.2,161.04,6.4,-1.5502,16.16,0.0097],[-7.1,158.47,6.36,-1.5472,16.09,0.0059],[-7.0,156.86,6.4,-1.5466,16.0,0.0066],[-6.9,155.27,6.44,-1.5459,15.9,0.0075],[-6.8,153.69,6.48,-1.5452,15.81,0.0092],[-6.7,152.12,6.52,-1.5442,15.71,0.0081],[-6.6,150.56,6.57,-1.5435,15.6,0.012],[-6.5,149.01,6.61,-1.5422,15.53,0.0103],[-6.4,147.46,6.66,-1.5412,15.51,0.015],[-6.3,145.91,6.7,-1.5396,15.46,0.013],[-6.2,144.37,6.75,-1.5384,15.38,0.0152],[-6.1,142.85,6.81,-1.5368,15.28,0.011],[-6.0,141.69,6.96,-1.5304,15.19,0.0125],[-5.9,140.18,7.02,-1.5291,15.1,0.013],[-5.8,138.68,7.09,-1.5278,14.99,0.0128],[-5.7,137.2,7.15,-1.5266,14.88,0.0132],[-5.6,135.72,7.22,-1.5252,14.79,0.0112],[-5.5,134.25,7.29,-1.5242,14.72,0.0074],[-5.4,132.79,7.36,-1.5235,14.63,0.008],[-5.3,131.34,7.43,-1.5227,14.51,0.0064],[-5.2,129.9,7.5,-1.5221,14.44,0.0019],[-5.1,128.46,7.57,-1.522,14.37,0.001],[-5.0,127.37,8.05,-1.5257,14.28,-0.0005],[-4.9,125.96,8.11,-1.5258,14.19,-0.0028],[-4.8,124.55,8.18,-1.5262,14.09,-0.0042],[-4.7,123.15,8.24,-1.5266,14.01,-0.006],[-4.6,121.76,8.3,-1.5272,13.93,-0.0087],[-4.5,120.37,8.36,-1.5281,13.85,-0.0124],[-4.4,119.0,8.42,-1.5294,13.77,-0.0144],[-4.3,117.63,8.47,-1.5309,13.68,-0.0147],[-4.2,116.27,8.52,-1.5324,13.57,-0.0167],[-4.1,114.93,8.57,-1.5341,13.49,-0.0169],[-4.0,114.33,9.38,-1.5321,13.4,-0.0198],[-3.9,113.0,9.43,-1.5341,13.32,-0.0199],[-3.8,111.68,9.48,-1.5361,13.22,-0.0211],[-3.7,110.37,9.52,-1.5382,13.12,-0.0234],[-3.6,109.07,9.56,-1.5406,13.04,-0.025],[-3.5,107.77,9.6,-1.5431,12.96,-0.0259],[-3.4,106.48,9.63,-1.5457,12.86,-0.0263],[-3.3,105.21,9.66,-1.5484,12.78,-0.0278],[-3.2,103.94,9.68,-1.5512,12.68,-0.0283],[-3.1,102.69,9.71,-1.5539,12.59,-0.0281],[-3.0,102.92,10.26,-1.538,12.51,-0.0298],[-2.9,101.67,10.3,-1.541,12.43,-0.0304],[-2.8,100.44,10.33,-1.5441,12.35,-0.0314],[-2.7,99.21,10.36,-1.5472,12.26,-0.0304],[-2.6,98.0,10.39,-1.5502,12.18,-0.0323],[-2.5,96.79,10.41,-1.5535,12.08,-0.0337],[-2.4,95.59,10.43,-1.5569,12.01,-0.0383],[-2.3,94.39,10.44,-1.5608,11.93,-0.0397],[-2.2,93.21,10.44,-1.5648,11.84,-0.0423],[-2.1,92.04,10.43,-1.5691,11.76,-0.0441],[-2.0,91.33,9.43,-1.5781,11.67,-0.043],[-1.9,90.17,9.41,-1.5824,11.59,-0.0419],[-1.8,89.02,9.39,-1.5866,11.51,-0.0396],[-1.7,87.88,9.37,-1.5905,11.41,-0.0417],[-1.6,86.75,9.34,-1.5947,11.32,-0.0419],[-1.5,85.63,9.31,-1.5989,11.23,-0.0413],[-1.4,84.51,9.28,-1.603,11.14,-0.0393],[-1.3,83.41,9.24,-1.6069,11.04,-0.0397],[-1.2,82.32,9.19,-1.6109,10.94,-0.0376],[-1.1,81.23,9.13,-1.6147,10.85,-0.0347],[-1.0,79.75,7.31,-1.6214,10.76,-0.0318],[-0.9,78.68,7.24,-1.6245,10.69,-0.0292],[-0.8,77.63,7.18,-1.6274,10.6,-0.0264],[-0.7,76.58,7.12,-1.63,10.51,-0.026],[-0.6,75.54,7.06,-1.6326,10.43,-0.0253],[-0.5,74.5,6.99,-1.6351,10.34,-0.0247],[-0.4,73.48,6.92,-1.6376,10.26,-0.0227],[-0.3,72.46,6.85,-1.6398,10.18,-0.023],[-0.2,71.46,6.78,-1.6421,10.08,-0.0221],[-0.1,70.46,6.71,-1.6443,9.99,-0.0215],[0.0,69.41,6.47,-1.6386,9.91,-0.0191]],"ring":{"v":1,"lat":35.5220836,"lon":-83.0281416,"r":21.6,"rms":0.31,"ccw":true,"lanes":0,"cov":354.7,"ids":[1514082747,1517278969,1517278970,1517279058,1517279059,1517279060],"tagged":true,"maxspeed":0.0,"app":[[[10.1,19.5],[-5.1,49.6],[-13.4,73.8]],[[-80.4,213.3],[-16.9,14.0]],[[175.1,2.5],[115.0,6.3],[75.7,5.9],[43.2,2.9],[29.4,7.6],[15.6,14.8]],[[13.5,-17.0],[83.3,-7.7],[113.6,-6.0],[176.5,-4.7]],[[-121.1,-33.5],[-103.2,-35.7],[-52.8,-15.3],[-36.9,-12.3],[-15.5,-14.9]],[[-19.6,11.4],[-43.1,4.6],[-109.4,-24.6],[-121.1,-33.5]],[[-13.4,73.8],[-12.0,57.6],[-12.0,40.7],[-16.9,14.0]]]},"hint_speed_ms":7.045}}} diff --git a/selfdrive/controls/lib/tests/data/roundabout_sep29_1157.json b/selfdrive/controls/lib/tests/data/roundabout_sep29_1157.json new file mode 100644 index 00000000000000..75d7693941885c --- /dev/null +++ b/selfdrive/controls/lib/tests/data/roundabout_sep29_1157.json @@ -0,0 +1 @@ +{"note":"Sep 29 2026 11:57:20-52 CT Scallywag ring pass (ring R=21.6 m CCW): carState v, yaw rate, model curvature at 10 Hz, qcom GNSS fixes (t,lat,lon,bearing,speed,bearingAcc). t relative to 11:57:20.","ring":{"v":1,"lat":35.5220836,"lon":-83.0281416,"r":21.6,"rms":0.31,"ccw":true,"lanes":0,"cov":354.7,"ids":[1514082747,1517278969,1517278970,1517279058,1517279059,1517279060],"tagged":true,"maxspeed":0.0,"app":[[[10.1,19.5],[-5.1,49.6],[-13.4,73.8]],[[-80.4,213.3],[-16.9,14.0]],[[175.1,2.5],[115.0,6.3],[75.7,5.9],[43.2,2.9],[29.4,7.6],[15.6,14.8]],[[13.5,-17.0],[83.3,-7.7],[113.6,-6.0],[176.5,-4.7]],[[-121.1,-33.5],[-103.2,-35.7],[-52.8,-15.3],[-36.9,-12.3],[-15.5,-14.9]],[[-19.6,11.4],[-43.1,4.6],[-109.4,-24.6],[-121.1,-33.5]],[[-13.4,73.8],[-12.0,57.6],[-12.0,40.7],[-16.9,14.0]]]},"rows":[[0.0,19.968,0.0007,3e-05,1],[0.1,19.964,0.0006,3e-05,1],[0.2,19.964,0.0015,3e-05,1],[0.3,19.957,0.0021,3e-05,1],[0.4,19.95,0.0005,3e-05,1],[0.5,19.95,-0.0012,-2e-05,1],[0.6,19.949,0.0023,-2e-05,1],[0.7,19.934,0.0019,-2e-05,1],[0.8,19.928,-0.0013,-2e-05,1],[0.9,19.924,0.0,-2e-05,1],[1.0,19.923,0.0016,-9e-05,1],[1.1,19.945,-0.0006,-9e-05,1],[1.2,19.954,0.0005,-9e-05,1],[1.3,19.942,-0.0007,-9e-05,1],[1.4,19.926,-0.0013,-9e-05,1],[1.5,19.909,-0.0028,1e-05,1],[1.6,19.895,0.0,1e-05,1],[1.7,19.883,-0.0008,1e-05,1],[1.8,19.89,-0.0007,1e-05,1],[1.9,19.896,0.0004,1e-05,1],[2.0,19.896,-0.005,2e-05,1],[2.1,19.889,-0.0027,2e-05,1],[2.2,19.881,-0.0032,2e-05,1],[2.3,19.872,0.0012,2e-05,1],[2.4,19.881,-0.0018,2e-05,1],[2.5,19.902,0.0022,-5e-05,1],[2.6,19.857,0.0004,-5e-05,1],[2.7,19.847,0.0009,-5e-05,1],[2.8,19.886,-0.0014,-5e-05,1],[2.9,19.873,0.0011,-5e-05,1],[3.0,19.847,0.0014,-2e-05,1],[3.1,19.834,-0.0035,-2e-05,1],[3.2,19.85,-0.0018,-2e-05,1],[3.3,19.845,-0.0043,-2e-05,1],[3.4,19.795,-0.0019,-2e-05,1],[3.5,19.79,-0.002,7e-05,1],[3.6,19.8,-0.0041,7e-05,1],[3.7,19.808,-0.0026,7e-05,1],[3.8,19.839,-0.0016,7e-05,1],[3.9,19.879,0.0007,7e-05,1],[4.0,19.904,0.0001,5e-05,1],[4.1,19.903,-0.0015,5e-05,1],[4.2,19.892,-0.0001,5e-05,1],[4.3,19.89,-0.0019,5e-05,1],[4.4,19.887,-0.0036,5e-05,1],[4.5,19.858,-0.0004,8e-05,1],[4.6,19.84,-0.0019,8e-05,1],[4.7,19.822,0.0002,8e-05,1],[4.8,19.836,-0.0029,8e-05,1],[4.9,19.836,0.0029,8e-05,1],[5.0,19.832,0.0005,0.00018,1],[5.1,19.827,0.003,0.00018,1],[5.2,19.84,0.0045,0.00018,1],[5.3,19.834,0.0034,0.00018,1],[5.4,19.821,0.0029,0.00018,1],[5.5,19.797,0.0038,3e-05,1],[5.6,19.82,0.0083,3e-05,1],[5.7,19.842,0.0041,3e-05,1],[5.8,19.816,0.0052,3e-05,1],[5.9,19.789,0.0031,3e-05,1],[6.0,19.797,0.003,9e-05,1],[6.1,19.801,0.0041,9e-05,1],[6.2,19.786,0.0022,9e-05,1],[6.3,19.782,0.0027,9e-05,1],[6.4,19.766,0.0009,9e-05,1],[6.5,19.751,0.0001,0.00026,1],[6.6,19.74,0.0032,0.00026,1],[6.7,19.733,0.0024,0.00026,1],[6.8,19.71,0.0009,0.00026,1],[6.9,19.717,0.0049,0.00026,1],[7.0,19.714,0.0067,0.00034,1],[7.1,19.702,0.0036,0.00034,1],[7.2,19.694,0.0034,0.00034,1],[7.3,19.684,0.0079,0.00034,1],[7.4,19.685,0.0031,0.00034,1],[7.5,19.688,0.0073,0.00052,1],[7.6,19.684,-0.0016,0.00052,1],[7.7,19.663,0.0047,0.00052,1],[7.8,19.695,0.0069,0.00052,1],[7.9,19.687,0.0094,0.00052,1],[8.0,19.653,0.0092,0.00059,1],[8.1,19.649,0.0084,0.00059,1],[8.2,19.643,0.0115,0.00059,1],[8.3,19.663,0.013,0.00059,1],[8.4,19.69,0.0082,0.00059,1],[8.5,19.691,0.0155,0.00074,1],[8.6,19.66,0.0109,0.00074,1],[8.7,19.61,0.0107,0.00074,1],[8.8,19.678,0.0092,0.00074,1],[8.9,19.734,0.0117,0.00074,1],[9.0,19.69,0.0197,0.00079,1],[9.1,19.609,0.0094,0.00079,1],[9.2,19.576,0.006,0.00079,1],[9.3,19.604,0.0083,0.00079,1],[9.4,19.615,0.0127,0.00079,1],[9.5,19.607,0.0176,0.00128,1],[9.6,19.616,0.0165,0.00128,1],[9.7,19.609,0.0166,0.00128,1],[9.8,19.587,0.0236,0.00128,1],[9.9,19.587,0.0287,0.00128,1],[10.0,19.582,0.0266,0.00167,1],[10.1,19.58,0.0317,0.00167,1],[10.2,19.592,0.0284,0.00167,1],[10.3,19.586,0.0307,0.00167,1],[10.4,19.592,0.0335,0.00167,1],[10.5,19.607,0.033,0.00176,1],[10.6,19.605,0.0317,0.00176,1],[10.7,19.612,0.0293,0.00176,1],[10.8,19.599,0.0306,0.00176,1],[10.9,19.591,0.0318,0.00176,1],[11.0,19.605,0.0304,0.00135,1],[11.1,19.614,0.0289,0.00135,1],[11.2,19.629,0.0282,0.00135,1],[11.3,19.639,0.0336,0.00135,1],[11.4,19.629,0.0299,0.00135,1],[11.5,19.634,0.0259,0.001,1],[11.6,19.644,0.0236,0.001,1],[11.7,19.65,0.0231,0.001,1],[11.8,19.647,0.02,0.001,1],[11.9,19.639,0.0175,0.001,1],[12.0,19.632,0.0178,0.00071,1],[12.1,19.634,0.0172,0.00071,1],[12.2,19.663,0.0144,0.00071,1],[12.3,19.659,0.0165,0.00071,1],[12.4,19.663,0.0159,0.00071,1],[12.5,19.656,0.0149,0.00063,1],[12.6,19.666,0.0118,0.00063,1],[12.7,19.67,0.0107,0.00063,1],[12.8,19.669,0.0105,0.00063,1],[12.9,19.68,0.0114,0.00063,1],[13.0,19.672,0.0125,0.00053,1],[13.1,19.675,0.0097,0.00053,1],[13.2,19.681,0.0102,0.00053,1],[13.3,19.702,0.0083,0.00053,1],[13.4,19.709,0.0113,0.00053,1],[13.5,19.693,0.0101,0.00045,1],[13.6,19.692,0.0071,0.00045,1],[13.7,19.71,0.0061,0.00045,1],[13.8,19.702,0.0063,0.00045,1],[13.9,19.677,0.0076,0.00045,1],[14.0,19.679,0.0102,0.0004,1],[14.1,19.692,0.0074,0.0004,1],[14.2,19.708,0.0108,0.0004,1],[14.3,19.702,0.0079,0.0004,1],[14.4,19.707,0.0138,0.0004,1],[14.5,19.71,0.0062,0.0004,1],[14.6,19.722,0.0061,0.0004,1],[14.7,19.707,0.0057,0.0004,1],[14.8,19.715,0.0035,0.0004,1],[14.9,19.787,0.0057,0.0004,1],[15.0,19.733,0.0083,0.00044,1],[15.1,19.662,0.0024,0.00044,1],[15.2,19.702,0.0029,0.00044,1],[15.3,19.751,0.0086,0.00044,1],[15.4,19.72,0.0113,0.00044,1],[15.5,19.725,0.0094,0.00041,1],[15.6,19.77,0.0083,0.00041,1],[15.7,19.757,0.0083,0.00041,1],[15.8,19.719,0.0076,0.00041,1],[15.9,19.719,0.0069,0.00041,1],[16.0,19.722,0.0074,0.00014,1],[16.1,19.72,0.0057,0.00014,1],[16.2,19.753,0.0056,0.00014,1],[16.3,19.781,0.0045,0.00014,1],[16.4,19.769,0.0021,0.00014,1],[16.5,19.75,0.0003,-0.00012,1],[16.6,19.755,0.0003,-0.00012,1],[16.7,19.783,0.0017,-0.00012,1],[16.8,19.769,-0.0014,-0.00012,1],[16.9,19.697,-0.0046,-0.00012,1],[17.0,19.667,-0.0072,-0.00056,1],[17.1,19.629,-0.0081,-0.00056,1],[17.2,19.596,-0.0093,-0.00056,1],[17.3,19.536,-0.0071,-0.00056,1],[17.4,19.463,-0.0108,-0.00056,1],[17.5,19.373,-0.0134,-0.00103,1],[17.6,19.312,-0.0148,-0.00103,1],[17.7,19.254,-0.0168,-0.00103,1],[17.8,19.204,-0.0185,-0.00103,1],[17.9,19.159,-0.0207,-0.00103,1],[18.0,19.085,-0.021,-0.00153,1],[18.1,18.992,-0.0247,-0.00153,1],[18.2,18.923,-0.0254,-0.00153,1],[18.3,18.858,-0.027,-0.00153,1],[18.4,18.785,-0.0264,-0.00153,1],[18.5,18.735,-0.0308,-0.00183,1],[18.6,18.679,-0.0299,-0.00183,1],[18.7,18.596,-0.0303,-0.00183,1],[18.8,18.527,-0.0316,-0.00183,1],[18.9,18.441,-0.0327,-0.00183,1],[19.0,18.331,-0.0336,-0.00218,1],[19.1,18.26,-0.0347,-0.00218,1],[19.2,18.179,-0.0367,-0.00218,1],[19.3,18.057,-0.0376,-0.00218,1],[19.4,17.986,-0.0391,-0.00218,1],[19.5,17.932,-0.0412,-0.00264,1],[19.6,17.839,-0.0429,-0.00264,1],[19.7,17.732,-0.0418,-0.00264,1],[19.8,17.65,-0.0458,-0.00264,1],[19.9,17.561,-0.0506,-0.00264,1],[20.0,17.462,-0.051,-0.00364,1],[20.1,17.367,-0.0536,-0.00364,1],[20.2,17.264,-0.0569,-0.00364,1],[20.3,17.188,-0.0622,-0.00364,1],[20.4,17.114,-0.0648,-0.00364,1],[20.5,17.012,-0.0657,-0.00399,1],[20.6,16.918,-0.0651,-0.00399,1],[20.7,16.847,-0.0653,-0.00399,1],[20.8,16.775,-0.0692,-0.00399,1],[20.9,16.688,-0.0641,-0.00399,1],[21.0,16.564,-0.0641,-0.00404,1],[21.1,16.465,-0.0639,-0.00404,1],[21.2,16.373,-0.0671,-0.00404,1],[21.3,16.285,-0.0686,-0.00404,1],[21.4,16.197,-0.0696,-0.00404,1],[21.5,16.11,-0.0681,-0.00454,1],[21.6,16.013,-0.072,-0.00454,1],[21.7,15.899,-0.0752,-0.00454,1],[21.8,15.81,-0.0737,-0.00454,1],[21.9,15.722,-0.0745,-0.00454,1],[22.0,15.623,-0.0729,-0.0039,1],[22.1,15.552,-0.0732,-0.0039,1],[22.2,15.479,-0.0658,-0.0039,1],[22.3,15.391,-0.0658,-0.0039,1],[22.4,15.292,-0.0584,-0.0039,1],[22.5,15.191,-0.0553,-0.00305,1],[22.6,15.103,-0.0529,-0.00305,1],[22.7,14.995,-0.0474,-0.00305,1],[22.8,14.876,-0.0424,-0.00305,1],[22.9,14.786,-0.0409,-0.00305,1],[23.0,14.693,-0.0351,-0.00173,1],[23.1,14.589,-0.0294,-0.00173,1],[23.2,14.481,-0.023,-0.00173,1],[23.3,14.397,-0.0223,-0.00173,1],[23.4,14.305,-0.0187,-0.00173,1],[23.5,14.203,-0.0131,-0.00023,1],[23.6,14.108,-0.0036,-0.00023,1],[23.7,14.022,-0.0046,-0.00023,1],[23.8,13.928,-0.0004,-0.00023,1],[23.9,13.811,-0.0012,-0.00023,1],[24.0,13.694,0.0045,0.0019,1],[24.1,13.578,0.0074,0.0019,1],[24.2,13.482,0.0159,0.0019,1],[24.3,13.4,0.0223,0.0019,1],[24.4,13.306,0.0343,0.0019,1],[24.5,13.191,0.0461,0.00885,1],[24.6,13.06,0.0588,0.00885,1],[24.7,12.936,0.0794,0.00885,1],[24.8,12.833,0.1013,0.00885,1],[24.9,12.741,0.1204,0.00885,1],[25.0,12.631,0.1418,0.01642,1],[25.1,12.514,0.1553,0.01642,1],[25.2,12.384,0.1731,0.01642,1],[25.3,12.257,0.1971,0.01642,1],[25.4,12.127,0.2083,0.01642,1],[25.5,12.008,0.2163,0.01962,1],[25.6,11.882,0.2207,0.01962,1],[25.7,11.728,0.2249,0.01962,1],[25.8,11.597,0.2213,0.01962,1],[25.9,11.467,0.2258,0.01962,1],[26.0,11.349,0.2315,0.02114,1],[26.1,11.222,0.2362,0.02114,1],[26.2,11.066,0.2372,0.02114,1],[26.3,10.925,0.2363,0.02114,1],[26.4,10.799,0.2408,0.02114,1],[26.5,10.67,0.2462,0.0225,1],[26.6,10.519,0.2497,0.0225,1],[26.7,10.357,0.2466,0.0225,1],[26.8,10.233,0.2493,0.0225,1],[26.9,10.104,0.2573,0.0225,1],[27.0,9.988,0.2629,0.02382,1],[27.1,9.833,0.27,0.02382,1],[27.2,9.664,0.2661,0.02382,1],[27.3,9.524,0.2698,0.02382,1],[27.4,9.408,0.2782,0.02382,1],[27.5,9.269,0.2811,0.02418,1],[27.6,9.126,0.2812,0.02418,1],[27.7,8.972,0.2788,0.02418,1],[27.8,8.817,0.2491,0.02418,1],[27.9,8.682,0.2082,0.02418,1],[28.0,8.592,0.1602,0.01396,1],[28.1,8.479,0.1317,0.01396,1],[28.2,8.367,0.1262,0.01396,1],[28.3,8.246,0.0934,0.01396,1],[28.4,8.135,0.0621,0.01396,1],[28.5,8.032,0.0219,-0.00206,1],[28.6,7.94,-0.0247,-0.00206,1],[28.7,7.85,-0.0636,-0.00206,1],[28.8,7.758,-0.1111,-0.00206,1],[28.9,7.69,-0.1518,-0.00206,1],[29.0,7.642,-0.1963,-0.02246,1],[29.1,7.6,-0.2478,-0.02246,1],[29.2,7.539,-0.2781,-0.02246,1],[29.3,7.445,-0.2823,-0.02246,1],[29.4,7.36,-0.2483,-0.02246,1],[29.5,7.318,-0.1968,-0.02367,0],[29.6,7.26,-0.1742,-0.02367,0],[29.7,7.171,-0.1302,-0.02367,0],[29.8,7.077,-0.058,-0.02367,0],[29.9,7.036,-0.0129,-0.02367,0],[30.0,6.998,0.0056,-0.01398,0],[30.1,6.971,0.0043,-0.01398,0],[30.2,6.944,-0.003,-0.01398,0],[30.3,6.956,-0.0236,-0.01398,0],[30.4,6.967,-0.0501,-0.01398,0],[30.5,7.0,-0.0694,-0.0192,0],[30.6,7.03,-0.1022,-0.0192,0],[30.7,7.059,-0.1373,-0.0192,0],[30.8,7.096,-0.1761,-0.0192,0],[30.9,7.129,-0.2083,-0.0192,0],[31.0,7.155,-0.2318,-0.03921,0],[31.1,7.201,-0.255,-0.03921,0],[31.2,7.252,-0.2667,-0.03921,0],[31.3,7.299,-0.2709,-0.03921,0],[31.4,7.363,-0.2711,-0.03921,0],[31.5,7.412,-0.2712,-0.03383,0],[31.6,7.466,-0.2624,-0.03383,0],[31.7,7.55,-0.2559,-0.03383,0],[31.8,7.636,-0.2521,-0.03383,0],[31.9,7.725,-0.2431,-0.03383,0]],"gps":[[-0.95,35.5211152,-83.0340404,78.0,19.19,46.9],[0.06,35.5211729,-83.0338545,75.2,18.86,49.4],[1.06,35.5212363,-83.0336409,73.6,19.22,47.5],[2.06,35.5212718,-83.0334302,75.7,19.29,46.0],[3.05,35.5212999,-83.0332445,76.7,18.76,45.8],[4.06,35.5213411,-83.033056,76.7,18.54,46.9],[5.05,35.5213695,-83.0328148,77.4,19.38,34.5],[6.06,35.5213772,-83.0325926,78.6,19.44,35.8],[7.06,35.5214065,-83.0324291,77.9,18.43,38.8],[8.06,35.5214434,-83.032182,77.6,19.75,36.4],[9.06,35.5214791,-83.0320152,77.3,18.8,32.6],[10.06,35.5215186,-83.0318386,77.2,18.49,31.5],[11.06,35.5215717,-83.0315894,77.1,19.74,33.8],[12.06,35.5216359,-83.0313332,75.9,21.12,35.4],[13.06,35.5216774,-83.0310772,76.4,21.6,35.1],[14.06,35.5217032,-83.0308607,79.0,20.04,29.3],[15.06,35.5216963,-83.0306141,83.0,20.42,30.2],[16.05,35.5217563,-83.030393,80.7,19.97,31.6],[17.06,35.5217675,-83.0302044,83.4,19.41,15.4],[18.06,35.5217726,-83.0299839,84.2,19.5,13.2],[19.05,35.5217704,-83.0298102,83.7,18.63,14.9],[20.06,35.5217844,-83.0296224,81.8,17.82,11.6],[21.06,35.5217962,-83.0294279,77.6,17.09,6.7],[22.06,35.5218135,-83.029249,77.9,16.91,23.0],[22.95,35.5218479,-83.0290827,74.0,16.21,27.3],[24.06,35.5218955,-83.0289004,71.5,16.57,30.2],[25.06,35.5219613,-83.0287714,68.8,15.4,34.0],[26.06,35.5220051,-83.0286365,72.4,13.99,32.9],[27.06,35.52203,-83.0285409,72.7,12.6,41.2],[28.06,35.5220033,-83.0284065,90.7,11.34,38.1],[29.06,35.5219718,-83.028261,97.2,11.85,39.3],[30.06,35.5219582,-83.028191,102.1,8.85,39.3],[31.06,35.5219526,-83.0280969,99.6,8.23,44.6]]} \ No newline at end of file diff --git a/selfdrive/controls/lib/tests/test_alertmanager.py b/selfdrive/controls/lib/tests/test_alertmanager.py deleted file mode 100644 index 8b9c18a9d48206..00000000000000 --- a/selfdrive/controls/lib/tests/test_alertmanager.py +++ /dev/null @@ -1,39 +0,0 @@ -import random - -from openpilot.selfdrive.controls.lib.events import Alert, EVENTS -from openpilot.selfdrive.controls.lib.alertmanager import AlertManager - - -class TestAlertManager: - - def test_duration(self): - """ - Enforce that an alert lasts for max(alert duration, duration the alert is added) - """ - for duration in range(1, 100): - alert = None - while not isinstance(alert, Alert): - event = random.choice([e for e in EVENTS.values() if len(e)]) - alert = random.choice(list(event.values())) - - alert.duration = duration - - # check two cases: - # - alert is added to AM for <= the alert's duration - # - alert is added to AM for > alert's duration - for greater in (True, False): - if greater: - add_duration = duration + random.randint(1, 10) - else: - add_duration = random.randint(1, duration) - show_duration = max(duration, add_duration) - - AM = AlertManager() - for frame in range(duration+10): - if frame < add_duration: - AM.add_many(frame, [alert, ]) - current_alert = AM.process_alerts(frame, {}) - - shown = current_alert is not None - should_show = frame <= show_duration - assert shown == should_show, f"{frame=} {add_duration=} {duration=}" diff --git a/selfdrive/controls/lib/tests/test_blinker_lateral_pause.py b/selfdrive/controls/lib/tests/test_blinker_lateral_pause.py new file mode 100644 index 00000000000000..3d95399ea41654 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_blinker_lateral_pause.py @@ -0,0 +1,509 @@ +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import ( + BlinkerLateralHold, + LAMP_OFF_DEBOUNCE_S, + blinker_pauses_lateral, + blinker_turn_blocks_steering_disengage, + lat_active_with_blinker_pause, + preap_blinker_pause_hides_controls_mismatch, + stalk_is_left_or_right, +) +from openpilot.selfdrive.controls.lib.stalk_tip_turn import ( + STALK_ALC_TURN_HOLD_S, + STALK_TIP_HOLD_S, +) + + +def _lat_kwargs(**overrides): + kwargs = dict( + active=True, + steer_fault_temporary=False, + steer_fault_permanent=False, + standstill=False, + steer_at_standstill=False, + left_blinker=False, + right_blinker=False, + ) + kwargs.update(overrides) + return kwargs + + +def _lat_active(hold, *, left=False, right=False, pressed=False, active=True, dt=None, + alc_active=False, v_ego=0.0, stalk_state=0, disengage=False, + engaged=None, soft_lat_on=False): + return lat_active_with_blinker_pause( + **_lat_kwargs(left_blinker=left, right_blinker=right, steering_pressed=pressed, + active=active, hold=hold, alc_active=alc_active, v_ego=v_ego, + stalk_state=stalk_state, steering_disengage=disengage, + engaged=engaged, soft_lat_on=soft_lat_on), + dt=dt, + ) + + +def test_one_lamp_pauses_lateral(): + assert blinker_pauses_lateral(True, False) + assert blinker_pauses_lateral(False, True) + assert not lat_active_with_blinker_pause(**_lat_kwargs(left_blinker=True)) + assert not lat_active_with_blinker_pause(**_lat_kwargs(right_blinker=True)) + + +def test_blinker_turn_hard_gate_blocks_on_lamp_or_stalk_or_hold(): + hold = BlinkerLateralHold() + assert stalk_is_left_or_right(1) + assert stalk_is_left_or_right(2) + assert not stalk_is_left_or_right(0) + assert not stalk_is_left_or_right(3) + assert blinker_turn_blocks_steering_disengage(True, False, 0, hold) + assert blinker_turn_blocks_steering_disengage(False, True, 0, hold) + assert blinker_turn_blocks_steering_disengage(False, False, 1, hold) + assert blinker_turn_blocks_steering_disengage(False, False, 2, hold) + assert not blinker_turn_blocks_steering_disengage(False, False, 0, hold) + assert not blinker_turn_blocks_steering_disengage(True, True, 0, hold) + _hold_past_tip(hold, v_ego=12.0) + assert not _lat_active(hold, left=True, stalk_state=1) + # Lamps dark and stalk idle: flash-latch hold still blocks. + assert blinker_turn_blocks_steering_disengage(False, False, 0, hold) + + +def test_hazards_do_not_pause(): + assert not blinker_pauses_lateral(True, True) + assert lat_active_with_blinker_pause(**_lat_kwargs(left_blinker=True, right_blinker=True)) + hold = BlinkerLateralHold() + assert _lat_active(hold, left=True, right=True) + assert not hold.turn_active + assert not hold.holding + + +def test_hazards_after_turn_do_not_keep_turn_active(): + hold = BlinkerLateralHold() + assert not _lat_active(hold, left=True) + assert hold.turn_active + assert _lat_active(hold, left=True, right=True) + assert not hold.turn_active + assert not hold.holding + + +def test_flash_gap_without_hand_keeps_pause(): + hold = BlinkerLateralHold() + assert not _lat_active(hold, left=True) + # Typical Tesla off-period is ~0.3s. Stay paused with no steeringPressed. + assert not _lat_active(hold, dt=0.4) + assert hold.turn_active + assert hold.holding + assert not _lat_active(hold, left=True) + assert not _lat_active(hold, dt=0.4) + assert hold.turn_active + + +def test_one_second_dark_ends_turn_active(): + hold = BlinkerLateralHold() + assert not _lat_active(hold, left=True) + assert not _lat_active(hold, dt=LAMP_OFF_DEBOUNCE_S - 0.01) + assert hold.turn_active + assert _lat_active(hold, dt=0.01) + assert not hold.turn_active + assert not hold.holding + + +def test_long_flashing_turn_stays_paused_without_hand(): + """Waiting in traffic with the blinker on must not drop the pause every blink.""" + hold = BlinkerLateralHold() + dt = 0.01 + period = 0.66 # ~90 flashes/min + on_s = 0.33 + for i in range(int(8.0 / dt)): + left = ((i * dt) % period) < on_s + assert not _lat_active(hold, left=left, dt=dt) + assert hold.turn_active + assert hold.holding + + +def test_justin_corner_does_not_auto_resume_on_lamp_off(): + """Turn-complete is 1s dark, not stalk-center. Hand-on then keeps the pause.""" + hold = BlinkerLateralHold() + # 1. Single lamp: release lat. Long is not this helper. + assert not _lat_active(hold, left=True) + # 3. Hand-steer while the lamp is on: stay paused. + assert not _lat_active(hold, left=True, pressed=True) + # Flash gap with light/no hands: still the same turn. + assert not _lat_active(hold, dt=0.4) + assert hold.turn_active + # 4. Turn complete (1s dark), hand still on: do not resume. + assert not _lat_active(hold, pressed=True, dt=LAMP_OFF_DEBOUNCE_S) + assert not hold.turn_active + assert hold.holding + # 4. Hand released: resume lat by itself. No stalk pull. + assert _lat_active(hold) + assert not hold.holding + + +def test_hold_does_not_resume_while_hand_on_wheel(): + hold = BlinkerLateralHold() + assert not _lat_active(hold, left=True, pressed=True) + assert not _lat_active(hold, pressed=True, dt=LAMP_OFF_DEBOUNCE_S) + assert hold.holding + + +def test_hold_resumes_after_hand_release(): + hold = BlinkerLateralHold() + assert not _lat_active(hold, left=True, pressed=True) + assert not _lat_active(hold, pressed=True, dt=LAMP_OFF_DEBOUNCE_S) + assert _lat_active(hold) + assert not hold.holding + + +def test_hold_without_prior_blinker_does_not_pause(): + hold = BlinkerLateralHold() + assert _lat_active(hold, pressed=True) + assert not hold.holding + + +def test_hold_clears_when_not_engaged(): + hold = BlinkerLateralHold() + assert not _lat_active(hold, left=True, pressed=True) + assert not _lat_active(hold, pressed=True, active=False) + assert not hold.holding + assert not hold.turn_active + assert _lat_active(hold, pressed=True) + + +def test_lamp_off_without_hand_resumes_after_debounce(): + hold = BlinkerLateralHold() + assert not _lat_active(hold, left=True) + # One dark frame is a flash gap, not turn-complete. + assert not _lat_active(hold) + assert hold.turn_active + assert _lat_active(hold, dt=LAMP_OFF_DEBOUNCE_S) + assert not hold.turn_active + + +def test_inactive_or_fault_still_blocks_lat(): + assert not lat_active_with_blinker_pause(**_lat_kwargs(active=False)) + assert not lat_active_with_blinker_pause(**_lat_kwargs(steer_fault_temporary=True)) + assert not lat_active_with_blinker_pause(**_lat_kwargs(steer_fault_permanent=True)) + assert not lat_active_with_blinker_pause(**_lat_kwargs(standstill=True, steer_at_standstill=False)) + + +def test_low_speed_without_blinker_does_not_pause_lat_in_hold(): + """Speed re-enable inhibit is the soft-lat handoff, not BlinkerLateralHold.""" + hold = BlinkerLateralHold() + assert _lat_active(hold, v_ego=0.0) + assert _lat_active(hold, v_ego=10 * CV.MPH_TO_MS - 0.05) + assert not hold.turn_active + assert not hold.holding + # Blinker-on still pauses at any speed when soft-lat is Off. + assert not _lat_active(hold, left=True, v_ego=30.0) + assert hold.turn_active + + +def _tip_then_idle(hold, *, v_ego, stalk=1, left=True, dt=0.01): + assert _lat_active(hold, left=left, v_ego=v_ego, stalk_state=stalk, dt=dt) + assert _lat_active(hold, left=left, v_ego=v_ego, stalk_state=0, dt=dt) + assert not hold.turn_active + + +def _hold_past_tip(hold, *, v_ego, stalk=1, left=True, dt=0.01): + n = int(round(STALK_TIP_HOLD_S / dt)) + for _ in range(n - 1): + assert _lat_active(hold, left=left, v_ego=v_ego, stalk_state=stalk, dt=dt) + assert not _lat_active(hold, left=left, v_ego=v_ego, stalk_state=stalk, dt=dt) + assert hold.turn_active + + +def _hold_past_alc_turn(hold, *, v_ego, stalk=1, left=True, dt=0.01, alc_active=True): + n = int(round(STALK_ALC_TURN_HOLD_S / dt)) + for _ in range(n - 1): + assert _lat_active(hold, left=left, v_ego=v_ego, stalk_state=stalk, dt=dt, + alc_active=alc_active) + assert not _lat_active(hold, left=left, v_ego=v_ego, stalk_state=stalk, dt=dt, + alc_active=alc_active) + assert hold.turn_active + + +def test_tip_then_idle_does_not_pause_at_low_or_highway_speed(): + for v in (10 * CV.MPH_TO_MS, 30.0): + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=v) + assert _lat_active(hold, left=True, v_ego=v, stalk_state=0) + assert not hold.turn_active + assert hold.blocks_steer_disengage + + +def test_held_stalk_pauses_lat_at_highway_speed(): + hold = BlinkerLateralHold() + _hold_past_tip(hold, v_ego=30.0) + assert not _lat_active(hold, left=True, v_ego=30.0, stalk_state=1) + assert hold.turn_active + + +def test_held_stalk_pauses_lat_at_low_speed(): + hold = BlinkerLateralHold() + slow = 10 * CV.MPH_TO_MS + _hold_past_tip(hold, v_ego=slow) + assert hold.turn_active + + +def test_held_turn_pauses_even_if_alc_active(): + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=30.0) + _hold_past_alc_turn(hold, v_ego=30.0, alc_active=True) + assert not _lat_active(hold, left=True, alc_active=True, v_ego=30.0, stalk_state=1) + assert hold.turn_active + assert not hold._alc_keep + + +def test_same_direction_hold_under_1s_during_alc_does_not_pause(): + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=30.0) + dt = 0.01 + n = int(round(0.90 / dt)) + for _ in range(n): + assert _lat_active(hold, left=True, alc_active=True, v_ego=30.0, stalk_state=1, dt=dt) + assert not hold.turn_active + assert hold._alc_keep + + +def test_leftover_keep_alive_same_stalk_held_1s_becomes_turn(): + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=30.0) + assert _lat_active(hold, left=True, alc_active=True, stalk_state=0) + # ALC finished; leftover keep-alive still flashing. + assert _lat_active(hold, left=True, alc_active=False, stalk_state=0) + dt = 0.01 + for _ in range(int(round(0.90 / dt))): + assert _lat_active(hold, left=True, alc_active=False, v_ego=30.0, stalk_state=1, dt=dt) + assert not hold.turn_active + for _ in range(int(round(0.15 / dt))): + _lat_active(hold, left=True, alc_active=False, v_ego=30.0, stalk_state=1, dt=dt) + assert not _lat_active(hold, left=True, alc_active=False, v_ego=30.0, stalk_state=1) + assert hold.turn_active + assert not hold._alc_keep + + +def test_alc_turn_then_dark_then_hand_release_resumes(): + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=30.0) + _hold_past_alc_turn(hold, v_ego=30.0, alc_active=True) + assert not _lat_active(hold, left=True, pressed=True, stalk_state=1) + # Stalk released; lamps still on, then 1s dark with hand on, then release. + assert not _lat_active(hold, left=True, pressed=True, stalk_state=0) + assert not _lat_active(hold, pressed=True, dt=LAMP_OFF_DEBOUNCE_S) + assert not hold.turn_active + assert hold.holding + assert _lat_active(hold) + assert not hold.holding + + +def test_alc_turn_pause_survives_stale_alc_active(): + """After a 1s ALC-to-turn, leftover alc_active must not grab the wheel again.""" + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=30.0) + _hold_past_alc_turn(hold, v_ego=30.0, alc_active=True) + assert not _lat_active(hold, left=True, alc_active=True, stalk_state=0) + assert hold.turn_active + assert not hold._alc_keep + + +def test_opposite_tap_during_alc_does_not_pause(): + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=30.0) + assert _lat_active(hold, left=True, alc_active=True, stalk_state=0) + assert _lat_active(hold, right=True, alc_active=True, stalk_state=2, dt=0.01) + assert _lat_active(hold, right=True, alc_active=True, stalk_state=0, dt=0.01) + assert not hold.turn_active + + +def test_opposite_held_during_alc_pauses_at_tip_window(): + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=30.0) + assert _lat_active(hold, left=True, alc_active=True, stalk_state=0) + dt = 0.01 + n = int(round(STALK_TIP_HOLD_S / dt)) + for _ in range(n - 1): + assert _lat_active(hold, right=True, alc_active=True, v_ego=30.0, stalk_state=2, dt=dt) + assert not _lat_active(hold, right=True, alc_active=True, v_ego=30.0, stalk_state=2, dt=dt) + assert hold.turn_active + + +def test_alc_active_flashing_lamps_do_not_pause_or_latch_turn(): + hold = BlinkerLateralHold() + dt = 0.01 + period = 0.66 + on_s = 0.33 + for i in range(int(3.0 / dt)): + left = ((i * dt) % period) < on_s + assert _lat_active(hold, left=left, alc_active=True, dt=dt) + assert not hold.turn_active + assert not hold.holding + assert hold.blocks_steer_disengage + + +def test_stalk_tip_does_not_pause_before_alc_arms(): + hold = BlinkerLateralHold() + assert _lat_active(hold, left=True, v_ego=30.0, stalk_state=1) + assert not hold.turn_active + assert hold.blocks_steer_disengage + + +def test_alc_keep_alive_after_stalk_idle_does_not_pause(): + hold = BlinkerLateralHold() + assert _lat_active(hold, left=True, v_ego=30.0, stalk_state=1) + # Tip complete: stalk springs back; OP keeps flashing. + assert _lat_active(hold, left=True, v_ego=30.0, stalk_state=0) + assert _lat_active(hold, v_ego=30.0, dt=0.4) + assert _lat_active(hold, left=True, v_ego=30.0) + assert not hold.turn_active + assert hold.blocks_steer_disengage + + +def test_alc_leftover_flashes_do_not_become_driver_turn(): + hold = BlinkerLateralHold() + assert _lat_active(hold, left=True, alc_active=True) + # ALC finished; lamps still finishing a flash. Must not latch a turn. + assert _lat_active(hold, left=True) + assert not hold.turn_active + assert _lat_active(hold, dt=0.4) + assert not hold.turn_active + assert _lat_active(hold, dt=LAMP_OFF_DEBOUNCE_S) + assert not hold.blocks_steer_disengage + + +def test_driver_turn_without_alc_still_pauses(): + hold = BlinkerLateralHold() + slow = 10 * CV.MPH_TO_MS + _hold_past_tip(hold, v_ego=slow) + assert not _lat_active(hold, v_ego=slow, dt=0.4) + assert hold.turn_active + + +def test_alc_grab_does_not_pause_lat(): + hold = BlinkerLateralHold() + assert _lat_active(hold, left=True, pressed=True, alc_active=True) + assert not hold.turn_active + assert hold.blocks_steer_disengage + + +def test_preap_mismatch_hidden_only_on_preap_during_pause(): + hold = BlinkerLateralHold() + _hold_past_tip(hold, v_ego=10.0) + assert hold.blocks_steer_disengage + assert preap_blinker_pause_hides_controls_mismatch( + brand="tesla", fingerprint="TESLA_MODEL_S_PREAP", + blocks_steer_disengage=hold.blocks_steer_disengage) + assert not preap_blinker_pause_hides_controls_mismatch( + brand="tesla", fingerprint="TESLA_MODEL_S_PREAP", + blocks_steer_disengage=False) + assert not preap_blinker_pause_hides_controls_mismatch( + brand="toyota", fingerprint="TESLA_MODEL_S_PREAP", + blocks_steer_disengage=True) + + +def test_held_flashing_corner_hides_mismatch_for_eight_seconds(): + """Justin's long blinker-held corner: lamps flash, hands-on oscillates. + + Python already keeps cruiseEnabled. The remaining full-cancel was + controlsMismatch after ~2s of panda !controlsAllowed. The hold must + stay blocking so selfdrived can hide that disagreement. + """ + hold = BlinkerLateralHold() + _hold_past_tip(hold, v_ego=12.0, stalk=1) + dt = 0.01 + period = 0.66 + on_s = 0.33 + for i in range(int(8.0 / dt)): + left = ((i * dt) % period) < on_s + pressed = (i % 20) < 10 + assert not _lat_active(hold, left=left, pressed=pressed, stalk_state=1, dt=dt) + assert hold.blocks_steer_disengage + assert preap_blinker_pause_hides_controls_mismatch( + brand="tesla", fingerprint="TESLA_MODEL_S_PREAP", + blocks_steer_disengage=True) + + +def test_mismatch_not_hidden_after_turn_and_hand_release(): + hold = BlinkerLateralHold() + _hold_past_tip(hold, v_ego=10.0) + assert not _lat_active(hold, left=True, pressed=True, stalk_state=1) + assert not _lat_active(hold, pressed=True, dt=LAMP_OFF_DEBOUNCE_S) + assert hold.holding + assert _lat_active(hold) + assert not hold.blocks_steer_disengage + assert not preap_blinker_pause_hides_controls_mismatch( + brand="tesla", fingerprint="TESLA_MODEL_S_PREAP", + blocks_steer_disengage=hold.blocks_steer_disengage) + + +def test_faster_corner_hands_on_two_without_steering_pressed_stays_paused(): + """Justin's slightly faster turn: EPAS hands-on 2, torsion bar not yet pressed.""" + hold = BlinkerLateralHold() + _hold_past_tip(hold, v_ego=14.0) + dt = 0.01 + period = 0.66 + on_s = 0.33 + for i in range(int(4.0 / dt)): + left = ((i * dt) % period) < on_s + assert not _lat_active(hold, left=left, pressed=False, disengage=True, + stalk_state=1, dt=dt) + assert hold.turn_active + assert hold.blocks_steer_disengage + + +def test_high_torque_does_not_expire_latch_on_one_second_dark(): + hold = BlinkerLateralHold() + _hold_past_tip(hold, v_ego=14.0) + assert not _lat_active(hold, left=True, disengage=True, stalk_state=1) + # Lamps dark for a full second while still wrenching — still the same turn. + assert not _lat_active(hold, pressed=False, disengage=True, dt=LAMP_OFF_DEBOUNCE_S) + assert hold.turn_active + assert hold.blocks_steer_disengage + # Torque released, then 1s dark: turn ends and lat resumes by itself. + assert _lat_active(hold, pressed=False, disengage=False, dt=LAMP_OFF_DEBOUNCE_S) + assert not hold.turn_active + assert not hold.blocks_steer_disengage + + +def test_hold_does_not_reset_when_active_drops_but_enabled_stays(): + hold = BlinkerLateralHold() + _hold_past_tip(hold, v_ego=12.0) + assert not _lat_active(hold, left=True, disengage=True, active=False, engaged=True) + assert hold.turn_active + assert hold.blocks_steer_disengage + + +def test_soft_lat_on_does_not_clear_lat_but_still_latches_driver_turn(): + """Soft-lat On: lamp latch must not drop latActive; still detect a turn.""" + hold = BlinkerLateralHold() + assert _lat_active(hold, left=True, soft_lat_on=True) + assert hold.turn_active + assert hold.holding + # Flash gap still latches the driver turn; lat stays up. + assert _lat_active(hold, soft_lat_on=True, dt=0.4) + assert hold.turn_active + # Soft-lat Off still frees the wheel on the same latch. + hold_off = BlinkerLateralHold() + assert not _lat_active(hold_off, left=True, soft_lat_on=False) + assert hold_off.turn_active + + +def test_soft_lat_on_alc_tip_still_does_not_latch_driver_turn(): + hold = BlinkerLateralHold() + _tip_then_idle(hold, v_ego=30.0) + assert _lat_active(hold, left=True, v_ego=30.0, stalk_state=0, soft_lat_on=True) + assert not hold.turn_active + assert hold.blocks_steer_disengage + + +def test_soft_lat_off_held_stalk_still_pauses_lat(): + hold = BlinkerLateralHold() + _hold_past_tip(hold, v_ego=30.0) + assert not _lat_active(hold, left=True, v_ego=30.0, stalk_state=1, soft_lat_on=False) + assert hold.turn_active + # Same held turn with soft-lat On: lat stays, turn still latched. + hold_on = BlinkerLateralHold() + n = int(round(STALK_TIP_HOLD_S / 0.01)) + for _ in range(n - 1): + assert _lat_active(hold_on, left=True, v_ego=30.0, stalk_state=1, dt=0.01, + soft_lat_on=True) + assert _lat_active(hold_on, left=True, v_ego=30.0, stalk_state=1, dt=0.01, + soft_lat_on=True) + assert hold_on.turn_active diff --git a/selfdrive/controls/lib/tests/test_cone_corridor.py b/selfdrive/controls/lib/tests/test_cone_corridor.py new file mode 100644 index 00000000000000..db17b237aacbe5 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_cone_corridor.py @@ -0,0 +1,124 @@ +"""Oct 14 cone corridor (route 194 seg 25, Ridgewood Rd 08:28:47-08:29:14 CT). + +Cones on the centreline and barrels on the right shoulder. The one-line +detector tracked only the barrels, shifted LEFT and drifted into the left +cones. Both sides are now tracked, the shift aims at the midpoint, nothing +moves to within 1.5 m of a tracked line, and the shift eases out after the +corridor ends. +""" +import random +from types import SimpleNamespace + +import pytest + +from openpilot.selfdrive.controls.lib.cone_line import ( + CORRIDOR_MARGIN_M, + CORRIDOR_RELEASE_S, + DROP_S, + WOULD_STEER_CAP_M, + ConeCorridorDetector, + ConeLineDetector, + corridor_bounds, + corridor_target, +) +from openpilot.selfdrive.controls.lib.cone_line_hold import ConeLineHold + +V = 13.5 # ~30 mph, the seg 25 speed +DT = 0.125 +PX = [0.0, 30.0, 70.0] +PY = [0.0, 0.0, 0.0] +XS = [10, 17, 24, 31, 38, 46, 54] + + +def _pts(y_rel, xs=XS): + return [SimpleNamespace(dRel=x - 1.52, yRel=y_rel, vRel=-V, measured=True) for x in xs] + + +def _corridor(left_m, right_m): + # yRel +left: left cones positive, right barrels negative. + return _pts(left_m) + _pts(-right_m, [x + 3 for x in XS]) + + +def _run(det, pts, seconds): + out = [] + for _ in range(int(round(seconds / DT))): + out.append(det.update(pts, V, PX, PY, None, DT)) + return out + + +def test_both_sides_tracked_and_steer_to_midpoint(): + det = ConeCorridorDetector() + s = _run(det, _corridor(1.9, 2.3), 5.0)[-1] + assert s.active and s.corridor and s.left_active and s.right_active + assert s.left_clear == pytest.approx(1.9, abs=0.05) + assert s.right_clear == pytest.approx(2.3, abs=0.05) + assert s.would_steer == pytest.approx(0.2, abs=0.03) # midpoint, slightly right + assert s.margin >= CORRIDOR_MARGIN_M + + +def test_seg25_never_steers_toward_the_untracked_or_tracked_left_cones(): + # Legacy single-line detector: picks one side and can shift toward the other. + legacy = ConeLineDetector() + for _ in range(40): + old = legacy.update(_corridor(1.6, 2.3), V, PX, PY, None, DT) + det = ConeCorridorDetector() + outs = _run(det, _corridor(1.6, 2.3), 5.0) + lo, hi = corridor_bounds(1.6, 2.3) + for s in outs: + if s.active: + assert s.would_steer >= lo - 1e-6 + assert outs[-1].would_steer == pytest.approx(0.35, abs=0.03) + assert outs[-1].margin >= CORRIDOR_MARGIN_M + # The old behaviour for the record: it tracked one line only. + assert old.side in (-1, 1) + + +def test_line_inside_margin_pushes_away_firmly(): + det = ConeCorridorDetector() + outs = _run(det, _pts(1.1), 4.0) # one left line 1.1 m from centre + s = outs[-1] + assert s.left_active and not s.right_active + assert s.would_steer >= CORRIDOR_MARGIN_M - 1.1 - 1e-6 + assert s.would_steer <= WOULD_STEER_CAP_M + + +def test_corridor_target_hard_rule_property(): + rng = random.Random(3) + for _ in range(5000): + lc = rng.choice([None, rng.uniform(0.6, 4.0)]) + rc = rng.choice([None, rng.uniform(0.6, 4.0)]) + s = corridor_target(lc, rc, v_ego=13.0, room_right=rng.uniform(0, 1), room_left=rng.uniform(0, 1)) + lo, hi = corridor_bounds(lc, rc) + assert abs(s) <= WOULD_STEER_CAP_M + 1e-9 + if lo <= hi and lo <= WOULD_STEER_CAP_M and hi >= -WOULD_STEER_CAP_M: + assert lo - 1e-9 <= s <= hi + 1e-9 + + +def test_release_eases_back_without_a_snap(): + det = ConeCorridorDetector() + _run(det, _pts(1.4), 5.0) + ws0 = det._ws + assert ws0 > 0.3 + after = _run(det, [], DROP_S + CORRIDOR_RELEASE_S + 1.0) + ws = [s.would_steer for s in after] + assert all(b <= a + 1e-9 for a, b in zip(ws, ws[1:], strict=False)) + steps = [a - b for a, b in zip(ws, ws[1:], strict=False)] + assert max(steps) <= ws0 * 1.5 * DT / CORRIDOR_RELEASE_S + 1e-6 # smoothstep peak slope 1.5 + assert any(s.releasing for s in after) + assert ws[-1] == 0.0 and not after[-1].releasing + # Held while the detector's ~2 s drop timer runs, then eased. + assert ws[int(1.5 / DT)] == pytest.approx(ws0, abs=1e-6) + + +def test_hold_applies_the_releasing_shift_then_lets_go(): + hold = ConeLineHold() + kw = dict(enabled=True, engaged=True, torque_nm=0.0, measured_k=0.0, model_k=0.0, + path_x=PX, path_y=PY, v_ego=V, yielded=False, lat_active=True, dt=0.01) + live = SimpleNamespace(active=True, side=1, releasing=False) + assert hold.update(cone=live, cone_shift=0.5, **kw).curvature > 0.0 + easing = SimpleNamespace(active=False, side=1, releasing=True) + out = hold.update(cone=easing, cone_shift=0.2, **kw) + assert out.active and out.source == "shift" and out.curvature > 0.0 + done = SimpleNamespace(active=False, side=1, releasing=False) + out = hold.update(cone=done, cone_shift=0.0, **kw) + assert not out.active and out.curvature == 0.0 diff --git a/selfdrive/controls/lib/tests/test_cone_line.py b/selfdrive/controls/lib/tests/test_cone_line.py new file mode 100644 index 00000000000000..e8e0728d373d75 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_cone_line.py @@ -0,0 +1,445 @@ +"""Cone-line detector: synthetic radar, hysteresis, and the rejects.""" + +import math +from types import SimpleNamespace + +import pytest + +from openpilot.selfdrive.controls.lib.cone_line import ( + cone_shift_target, + overhead_ranges, + CLEARANCE_M, + CONFIRM_S, + DROP_S, + LAT_MIN_M, + WOULD_STEER_CAP_M, + ConeLineDetector, + ConeLineSample, + device_y_right, +) + +V = 12.0 +DT = 0.125 # 8 Hz +# Straight path. Device y is +right (model position.y). radar yRel is +left, +# so a left-side return has positive yRel and negative path lat. +STRAIGHT_X = [0.0, 30.0, 70.0] +STRAIGHT_Y = [0.0, 0.0, 0.0] + + +def _pts(xs, y_rel, v=V, measured=True, v_rel=None): + rel = -v if v_rel is None else v_rel + return [ + SimpleNamespace(dRel=x - 1.52, yRel=y_rel, vRel=rel, measured=measured) + for x in xs + ] + + +def _cones(y_rel=1.6): + # Device x along the cone stretch. yRel > 0 is to the left. + return _pts([10, 16, 23, 31, 39, 48, 57], y_rel) + + +def _run(det, points, seconds, path_x=STRAIGHT_X, path_y=STRAIGHT_Y, v=V, edges=None, dt=DT): + n = max(1, int(round(seconds / dt))) + sample = None + for _ in range(n): + sample = det.update(points, v, path_x, path_y, edges, dt) + return sample + + +def test_left_side_cone_line_confirms_with_hysteresis(): + det = ConeLineDetector() + early = _run(det, _cones(), CONFIRM_S * 0.5) + assert early.active is False + assert early.confidence < 0.5 + sample = _run(det, _cones(), CONFIRM_S * 0.6) + assert sample.active is True + assert sample.side == 1 + assert sample.count >= 4 + assert sample.span_m >= 10.0 + assert sample.confidence >= 0.5 + assert sample.barrier is False + assert sample.parked is False + # yRel +1.6 is 1.6 m left. Path lat is +right, so the line is at -1.6. + # Past the old 1 m clearance (would_limit 0), but inside the Oct 13 2.6 m + # trigger: the cone shift ramps in slowly, away from the left line (+right). + assert sample.lat_mid == pytest.approx(-1.6, abs=0.02) + assert sample.would_limit == 0.0 + assert 0.0 < sample.would_steer <= WOULD_STEER_CAP_M + assert device_y_right(1.6) == pytest.approx(-1.6) + # A short dropout does not clear the line. + held = _run(det, [], DROP_S * 0.5) + assert held.active is True + cleared = _run(det, [], DROP_S) + assert cleared.active is False + + +def test_close_line_reports_the_would_limit_shift(): + det = ConeLineDetector() + # 0.7 m left of the path (yRel +left). Keep ~1.0 m → shift the path right by 0.3 m. + sample = _run(det, _cones(0.7), CONFIRM_S + 1.0) + assert sample.active is True + assert sample.side == 1 + assert sample.lat_near < 0.0 + assert sample.would_limit == pytest.approx(CLEARANCE_M - 0.7, abs=0.02) + # Oct 13: a line inside 1.2 m is our own footprint (overpass, queue): no shift. + assert sample.would_steer == 0.0 + + +def test_single_mailbox_never_becomes_a_line(): + det = ConeLineDetector() + sample = _run(det, _pts([18.0], 1.5), 3.0) + assert sample.active is False + assert sample.count == 0 + assert sample.parked is False + assert sample.barrier is False + assert sample.would_limit == 0.0 + + +def test_no_objects(): + det = ConeLineDetector() + sample = _run(det, [], 2.0) + assert sample.active is False + assert sample.side == 0 + assert sample.count == 0 + + +def test_guardrail_is_flagged_not_a_cone_line(): + det = ConeLineDetector() + # Continuous returns every 1 m. Distinguishable from drums spaced several meters apart. + # A single scan must keep them: the match gate is wider than 1 m, and a new + # return is not allowed to steal the post the previous return just created. + xs = [8.0 + i for i in range(22)] + det.update(_pts(xs, 1.7), V, STRAIGHT_X, STRAIGHT_Y, None, DT) + assert len(det._posts) >= 18 + sample = _run(det, _pts(xs, 1.7), CONFIRM_S + 1.0) + assert sample.active is False + assert sample.barrier is True + assert sample.parked is False + assert sample.side == 1 + assert sample.lat_mid < 0.0 + assert sample.would_steer == 0.0 + + +def test_parked_car_wide_cluster_is_rejected(): + det = ConeLineDetector() + # Four returns across the width of a car, only a few meters long. + points = [] + for i, lat in enumerate((-1.0, -1.6, -2.2, -2.5)): + points.extend(_pts([20.0 + i * 0.8], -lat)) + sample = _run(det, points, 3.0) + assert sample.active is False + assert sample.parked is True + assert sample.barrier is False + + +def test_moving_traffic_and_in_path_lead_are_not_a_line(): + det = ConeLineDetector() + moving = _pts([10, 16, 23, 31, 39, 48, 57], 1.6, v_rel=-V + 6.0) + sample = _run(det, moving, CONFIRM_S + 0.5) + assert sample.active is False + lead = _pts([12, 18, 25, 33, 42], 0.2) # inside the lane, under the roadside band + sample = _run(ConeLineDetector(), lead, CONFIRM_S + 0.5) + assert sample.active is False + assert LAT_MIN_M == 0.30 + + +def test_curve_uses_path_relative_lateral_not_ego_yrel(): + """Ego yRel 0.4 m can still be 1.6 m off the path once the path has bent.""" + det = ConeLineDetector() + xs = [10, 16, 23, 31, 39, 48, 57] + # Path y +1.2 is 1.2 m to the right. yRel +0.4 is 0.4 m left of the car + # (device y -0.4), so the return sits 1.6 m left of the path. + path_x = [0.0, 20.0, 40.0, 70.0] + path_y = [0.0, 1.2, 1.2, 1.2] + sample = _run(det, _pts(xs, 0.4), CONFIRM_S + DT, path_x, path_y) + assert sample.active is True + assert sample.side == 1 + assert sample.lat_mid == pytest.approx(-1.6, abs=0.05) + # The same ego offset ON the path (path y = -0.4) is inside the lane band. + on_path = _run(ConeLineDetector(), _pts(xs, 0.4), CONFIRM_S + DT, + [0.0, 70.0], [-0.4, -0.4]) + assert on_path.active is False + + +def test_objects_past_the_road_edge_are_dropped(): + det = ConeLineDetector() + edges = [([0.0, 80.0], [2.2, 2.2]), ([0.0, 80.0], [-1.2, -1.2])] + # yRel +1.9 is device y -1.9, past the left road edge (edge y is +right). + outside = _run(det, _pts([10, 16, 23, 31, 39, 48, 57], 1.9), CONFIRM_S + DT, edges=edges) + assert outside.active is False + inside = _run(ConeLineDetector(), _cones(1.5), CONFIRM_S + DT, edges=edges) + assert inside.active is True + assert inside.side == 1 + + +def test_right_side_yrel_is_negative(): + """The mirror of the left-side case. yRel < 0 is the driver's right.""" + sample = _run(ConeLineDetector(), _cones(-1.6), CONFIRM_S + DT) + assert sample.active is True + assert sample.side == -1 + assert sample.lat_mid == pytest.approx(1.6, abs=0.02) + + +def test_posts_closer_than_half_a_meter_still_count(): + """The old 0.5 m inner band dropped the taper. 0.40 m is a cone; 0.20 m is a lead.""" + close = _pts([10, 18, 26, 34, 42, 50], 0.40) + sample = _run(ConeLineDetector(), close, CONFIRM_S + DT) + assert sample.active is True + assert sample.side == 1 + assert sample.count >= 6 + assert sample.lat_mid == pytest.approx(-0.40, abs=0.05) + lane = _run(ConeLineDetector(), _pts([10, 18, 26, 34, 42, 50], 0.20), CONFIRM_S + DT) + assert lane.active is False + + +def test_would_steer_is_capped_and_points_away_from_left_posts(): + # 0.55 m left: inside the 1.2 m footprint, so the Oct 13 shift stays 0. + sample = _run(ConeLineDetector(), _cones(0.55), CONFIRM_S + 1.0) + assert sample.active is True + assert sample.side == 1 + assert sample.would_limit == pytest.approx(CLEARANCE_M - 0.55, abs=0.03) + assert sample.would_steer == 0.0 + # 2.0 m left at speed: shifts right (away), ramping toward min(1.0, 3.2 - 2.0). + wide = _run(ConeLineDetector(), _cones(2.0), CONFIRM_S + 8.0) + assert wide.active and wide.would_steer == pytest.approx(1.0, abs=0.03) + assert WOULD_STEER_CAP_M == pytest.approx(1.0) + + +def test_curved_ground_line_confirms_when_a_straight_lat_std_would_not(): + """Quadratic in the device frame. Raw lateral std is past 0.5 m, so the + old straight-line gate would have thrown the row out. The ground-frame + fit keeps it, on the left. + """ + xs = [10, 18, 26, 34, 42, 50, 58] + # y_right = -0.40 - 0.0035*(x-34)^2. Ends are ~2.4 m left, the middle + # is 0.40 m left, and the raw std is past the 0.50 m residual cap. + ys = [-0.40 - 0.0035 * (x - 34.0) ** 2 for x in xs] + assert _std_abs(ys) > 0.50 + assert max(abs(y) for y in ys) < 2.50 + points = _pts_yx(xs, [-y for y in ys]) # yRel = -y_right, so these are left posts + sample = _run(ConeLineDetector(), points, CONFIRM_S + DT) + assert sample.active is True + assert sample.side == 1 + assert sample.lat_near < 0.0 + + +def test_oct7_left_channelizers_hold_through_the_taper(): + """Route 00000172--2a94c25d70, 14:21:15–14:21:34 CT. + + Orange/white posts on the left of the lane, tapering from about 2.3 m + out to 0.36 m (inside the old 0.5 m discard). Once the car is in the + zone the radar only returns a couple of posts per scan. Side must be + left (+1). The line stays up for ~2 s after the hits stop. + """ + v = 18.0 + dt = DT + # Every post stays inside the 6–70 m scan. The last one is 0.36 m off + # the path, inside the old 0.5 m discard. + xs = [12.0 + 8.0 * i for i in range(8)] + ys = [-2.30 + (2.30 - 0.36) * (i / 7.0) for i in range(8)] + assert ys[0] == pytest.approx(-2.30, abs=0.01) + assert ys[-1] == pytest.approx(-0.36, abs=0.01) + assert abs(ys[-1]) < 0.50 + assert max(xs) <= 70.0 + det = ConeLineDetector() + + def points(which): + return [ + SimpleNamespace(dRel=xs[i] - 1.52, yRel=-ys[i], vRel=-v, measured=True) + for i in which + ] + + def step(which): + return det.update(points(which), v, STRAIGHT_X, STRAIGHT_Y, None, dt, 0.0) + + sample = None + for _ in range(int(round(1.3 / dt))): + sample = step(range(8)) + assert sample is not None and sample.active is True + assert sample.side == 1 + assert sample.lat_mid < 0.0 + assert len(det._posts) <= 10 + assert any(abs(p.y) < 0.50 for p in det._posts) + + # Two posts a scan for 3 s, always including the post inside 0.5 m. + for n in range(int(round(3.0 / dt))): + sample = step((n % 6, 7)) + assert sample.side == 1 + assert sample.active is True + assert len(det._posts) <= 12 + + for _ in range(int(round(1.5 / dt))): + sample = step(()) + assert sample.active is True + assert sample.side == 1 + + for _ in range(int(round(0.8 / dt))): + sample = step(()) + assert sample.active is False + + +def test_moving_posts_associate_by_position_not_by_duplicating(): + """On the road each scan steps back by about v*dt. Compensation has to + match the same posts, including through a small yaw, instead of spawning + a new post every frame. + """ + v = 16.0 + yaw = -0.04 # left turn, +right frame + dt = DT + xs0 = [14.0, 22.0, 30.0, 38.0, 46.0, 54.0] + y_rel = 1.6 + det = ConeLineDetector() + sample = _run(det, _pts(xs0, y_rel, v=v), CONFIRM_S + dt, v=v, dt=dt) + assert sample.active is True + assert sample.side == 1 + n0 = len(det._posts) + shift = 0.0 + psi = 0.0 + for _ in range(10): + shift += v * dt + psi += yaw * dt + c, s = math.cos(psi), math.sin(psi) + pts = [] + for x0 in xs0: + # Fixed world posts, ego moved forward `shift` and yawed `psi`. + dx, dy = x0 - shift, -1.6 + x_v = c * dx + s * dy + y_v = -s * dx + c * dy + if 6.0 <= x_v <= 70.0: + pts.append(SimpleNamespace(dRel=x_v - 1.52, yRel=-y_v, vRel=-v, measured=True)) + sample = det.update(pts, v, STRAIGHT_X, STRAIGHT_Y, None, dt, yaw) + assert len(det._posts) <= n0 + 2 + assert sample.active is True + assert sample.side == 1 + + +def test_town_and_intersection_near_misses_stay_inactive(): + """14:29 town street and 14:44 intersection must not become a cone line. + + The town case is two brief clutter bursts. The intersection is a real-looking + line for 0.6 s (under the 1.0 s confirm) and then poles on both sides. + """ + det = ConeLineDetector() + clutter = _pts([14.0, 18.0], 1.1) + _pts([22.0], -2.4) + _pts([16.0, 17.0, 18.5], 2.2) + sample = _run(det, clutter, 0.25, v=5.0) + assert sample.active is False + sample = _run(det, [], 2.5, v=5.0) + parked = [] + for i, lat in enumerate((1.2, 1.9, 2.6)): + parked.extend(_pts([18.0 + i * 0.7], lat)) + sample = _run(det, parked, 0.4, v=4.0) + assert sample.active is False + sample = _run(det, [], 2.0, v=6.0) + assert sample.active is False + + det = ConeLineDetector() + saw = False + sample = _run(det, _cones(1.5), 0.60, v=7.5) + saw = saw or sample.active + assert sample.active is False + assert sample.confidence <= 0.49 + mixed = _pts([12, 20, 28], 1.4) + _pts([16, 24, 33], -1.7) + sample = _run(det, mixed, 1.2, v=7.5) + saw = saw or sample.active + sample = _run(det, [], 1.0, v=7.5) + assert sample.active is False + assert saw is False + + +def test_schema_documents_the_right_positive_frame(): + from pathlib import Path + text = Path(__file__).resolve().parents[4].joinpath("cereal/custom.capnp").read_text() + cone = text.split("struct ConeLineNAP", 1)[1].split("struct PathObstacleNAP", 1)[0] + assert "+right" in cone + assert "yRel is +left" in cone + assert "+1 left" in cone + assert "wouldSteer" in cone + assert "corridor" in cone + obstacle = text.split("struct PathObstacleNAP", 1)[1] + assert "+right" in obstacle.split("enum ObjectClass", 1)[0] + + +def test_a_fat_scan_stays_cheap(): + import time + det = ConeLineDetector() + points = [] + for i in range(200): + points.append(SimpleNamespace( + dRel=8.0 + (i % 50), yRel=((i % 9) - 4) * 0.4, vRel=-V, measured=True, + )) + t0 = time.monotonic() + sample = None + for _ in range(30): + sample = det.update(points, V, STRAIGHT_X, STRAIGHT_Y, None, DT, 0.0) + assert time.monotonic() - t0 < 0.25 + assert sample is not None + assert sample.active is False + + +def _std_abs(vals): + n = len(vals) + mean = sum(vals) / n + return (sum((v - mean) ** 2 for v in vals) / n) ** 0.5 + + +def _pts_yx(xs, y_rels, v=V): + return [ + SimpleNamespace(dRel=x - 1.52, yRel=y_rel, vRel=-v, measured=True) + for x, y_rel in zip(xs, y_rels) + ] + + +# ---- Oct 13 2026: passes A–G against the cone-shift rule ---- + +def _shift(side, clearance, mph, *, lead=False, overhead=False, room=None): + sample = ConeLineSample(active=True, side=side) + return cone_shift_target(sample, v_ego=mph * 0.44704, clearance=clearance, + lead_in_span=lead, overhead=overhead, lane_room=room) + + +def test_oct13_passes_a_to_g(): + # A 07:43, 63 mph, right drums nearest +2.4 m: shift left 0.8 (line to 3.2 m). + assert _shift(-1, 2.4, 63) == pytest.approx(-0.8) + # B 07:48, 36 mph, right cones +1.9 m: left, capped at 1.0. + assert _shift(-1, 1.9, 36) == pytest.approx(-1.0) + # C 07:57, overpass "left line" at -0.5 m: inside the 1.2 m footprint, and overhead. + assert _shift(1, 0.5, 55) == 0.0 + assert _shift(1, 1.5, 55, overhead=True) == 0.0 + # D 08:05, 3 mph queue at a light, line -0.15…-1.1 m, lead in span. + assert _shift(1, 0.15, 3, lead=True) == 0.0 + assert _shift(1, 1.5, 3) == 0.0 # below 20 mph alone blocks + assert _shift(1, 1.5, 30, lead=True) == 0.0 # lead in the span alone blocks + # E 08:06, 30 mph, right drums +2.0…+2.6 m: left 1.0 m, what he chose. + assert _shift(-1, 2.0, 30) == pytest.approx(-1.0) + # ...but never past the far lane line. + assert _shift(-1, 2.0, 30, room=0.6) == pytest.approx(-0.6) + # F 11:29, 58 mph, left drums -2.2 m: right 1.0. + assert _shift(1, 2.2, 58) == pytest.approx(1.0) + # G 12:05 / 12:21, right posts +3.5 m: beyond the 2.6 m trigger. + assert _shift(-1, 3.5, 60) == 0.0 + # Inactive line: nothing. + assert cone_shift_target(ConeLineSample(active=False, side=-1), v_ego=20.0, clearance=2.0, + lead_in_span=False, overhead=False, lane_room=None) == 0.0 + + +def test_oct13_overpass_spans_both_sides_at_one_range(): + deck = _pts([40.0, 40.5, 41.0, 41.5], 0.0) + for p, y in zip(deck, (3.0, 1.5, -1.5, -3.0)): + p.yRel = y + assert overhead_ranges(deck, V, STRAIGHT_X, STRAIGHT_Y) + # One-sided cones are not overhead. + assert not overhead_ranges(_cones(2.0), V, STRAIGHT_X, STRAIGHT_Y) + + +def test_oct13_overpass_blocks_the_shift_in_the_detector(): + det = ConeLineDetector() + pts = _cones(2.0) + _run(det, pts, CONFIRM_S + 1.0) + deck = _pts([30.0, 30.5, 31.0, 31.5], 0.0) + for p, y in zip(deck, (4.0, 2.5, -2.5, -4.0)): + p.yRel = y + s = None + for _ in range(20): + s = det.update(pts + deck, V, STRAIGHT_X, STRAIGHT_Y, None, DT) + assert s.active and s.would_steer < 0.5 # ramping back toward 0 under the deck diff --git a/selfdrive/controls/lib/tests/test_cone_line_hold.py b/selfdrive/controls/lib/tests/test_cone_line_hold.py new file mode 100644 index 00000000000000..002f71bd67c86a --- /dev/null +++ b/selfdrive/controls/lib/tests/test_cone_line_hold.py @@ -0,0 +1,367 @@ +"""Soft-handoff offset hold near a cone line, and the Ridgewood-style re-take. + +The detector staying log-only is the case with no driver push: curvature +is the model curvature exactly. Longitudinal is not in this module. +""" + +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openpilot.selfdrive.controls.lib.cone_line_hold import ( + CLEAR_S, + PARAM_CONE_LINE_HOLD, + PARAM_CONE_LINE_LOG, + PUSH_ARM_S, + RELEASE_S, + ConeLineHold, + lookahead_m, +) +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + HANDS_OFF_CONFIRM_S, + RELEASE_HOLD_S, + DriverLateralHandoff, + apply_lat_authority, +) +from openpilot.selfdrive.controls.lib.radar_path_gate import path_y_at_x + +DT = 0.01 +V = 15.0 +# Model path bends right (toward the cones) by 0.55 m at the hold lookahead. +# Path y is +right, so that bend is positive. +Y_PULL = 0.55 + + +def _path(x_la): + return [0.0, x_la, x_la * 2.0], [0.0, Y_PULL, Y_PULL * 2.0] + + +def _cone(active=True, side=-1): + return SimpleNamespace(active=active, side=side) + + +def _model_k(x_la): + return 2.0 * Y_PULL / (x_la * x_la) + + +def _step_lane(hold, *, torque=0.0, seconds=DT, yielded=False, lat_active=True, cone=None, + lane_offset=None, lane_center_la=None, cone_shift=0.0, v=V): + """Straight lane-centred model path; lane offset given directly (+right).""" + x_la = lookahead_m(v) + path_x, path_y = [0.0, x_la, 2 * x_la], [0.0, 0.0, 0.0] + cone = _cone() if cone is None else cone + out = None + for _ in range(max(1, int(round(seconds / DT)))): + out = hold.update( + enabled=True, engaged=True, cone=cone, torque_nm=torque, measured_k=0.0, model_k=0.0, + path_x=path_x, path_y=path_y, v_ego=v, yielded=yielded, lat_active=lat_active, dt=DT, + lane_offset=lane_offset, lane_center_la=lane_center_la, cone_shift=cone_shift, + ) + return out + + +def _step(hold, *, torque=0.0, measured_k=0.0, model_k=None, yielded=False, + lat_active=True, enabled=True, engaged=True, cone=None, seconds=DT, + v=V, path=None): + x_la = lookahead_m(v) + path_x, path_y = _path(x_la) if path is None else path + if model_k is None: + model_k = _model_k(x_la) + if cone is None: + cone = _cone() + n = max(1, int(round(seconds / DT))) + out = None + for _ in range(n): + out = hold.update( + enabled=enabled, engaged=engaged, cone=cone, torque_nm=torque, + measured_k=measured_k, model_k=model_k, path_x=path_x, path_y=path_y, + v_ego=v, yielded=yielded, lat_active=lat_active, dt=DT, + ) + return out + + +def test_log_only_line_does_not_change_curvature_without_a_push(): + hold = ConeLineHold() + x_la = lookahead_m(V) + model_k = _model_k(x_la) + out = _step(hold, torque=0.0, seconds=4.0, lat_active=True, yielded=False) + assert out.active is False + assert out.offset_m == 0.0 + assert out.curvature == model_k + assert not hold.busy + + +def test_push_toward_the_cones_does_not_arm(): + hold = ConeLineHold() + # Cones on the right. Torque -1 Nm is toward them, not away. + out = _step(hold, torque=-1.0, seconds=PUSH_ARM_S + 1.0, yielded=True, lat_active=False) + assert out.active is False + assert out.curvature == _model_k(lookahead_m(V)) + released = _step(hold, torque=0.0, seconds=HANDS_OFF_CONFIRM_S + 0.2, yielded=False, lat_active=True) + assert released.active is False + assert released.curvature == _model_k(lookahead_m(V)) + + +def test_hold_toggle_off_is_identity(): + hold = ConeLineHold() + out = _step(hold, torque=1.0, seconds=PUSH_ARM_S + 0.5, yielded=True, lat_active=False, enabled=False) + assert out.curvature == _model_k(lookahead_m(V)) + assert out.active is False + + +def test_offset_holds_on_retake_and_releases_after_the_line_clears(): + hold = ConeLineHold() + model_k = _model_k(lookahead_m(V)) + # Driver holds a straight line (measured curvature 0) while yielded. + pushing = _step(hold, torque=1.0, seconds=PUSH_ARM_S + 0.3, yielded=True, lat_active=False) + assert pushing.active is False + assert pushing.curvature == model_k # yielded: do not steer + retake = _step(hold, torque=0.0, seconds=0.2, yielded=False, lat_active=True) + assert retake.active is True + assert retake.offset_m == pytest.approx(-Y_PULL, abs=0.03) + assert retake.curvature == pytest.approx(0.0, abs=1e-6) + assert retake.curvature < model_k # less toward the cones than the model + # Line still there: keep the driver's line. + still = _step(hold, torque=0.0, seconds=3.0, yielded=False, lat_active=True) + assert still.active is True + assert still.curvature == pytest.approx(0.0, abs=1e-6) + # Cleared, but the wait has not finished. + waiting = _step(hold, torque=0.0, seconds=CLEAR_S * 0.5, yielded=False, lat_active=True, + cone=_cone(active=False, side=0)) + assert waiting.curvature == pytest.approx(0.0, abs=1e-4) + # Through the clear wait and the decay, the command eases onto the model + # and never goes past it toward the cones. + mid = _step(hold, torque=0.0, seconds=CLEAR_S * 0.5 + RELEASE_S * 0.5, + yielded=False, lat_active=True, cone=_cone(active=False, side=0)) + assert -1e-4 <= mid.curvature <= model_k + 1e-4 + done = _step(hold, torque=0.0, seconds=RELEASE_S, yielded=False, lat_active=True, + cone=_cone(active=False, side=0)) + assert done.active is False + assert done.curvature == pytest.approx(model_k, abs=1e-6) + + +def test_steer_back_releases_even_while_the_line_remains(): + # Oct 13: a push back toward the cones re-captures his offset; back near + # the lane centre (< 0.15 m away) the hold lets go. + hold = ConeLineHold() + model_k = _model_k(lookahead_m(V)) + _step_lane(hold, torque=1.0, seconds=PUSH_ARM_S + 0.3, yielded=True, lat_active=False, lane_offset=-0.9) + held = _step_lane(hold, seconds=0.2, lane_offset=-0.9) + assert held.active and held.source == "hold" + _step_lane(hold, torque=-0.8, seconds=0.4, lane_offset=-0.05, yielded=True, lat_active=False) + done = _step_lane(hold, seconds=0.2, lane_offset=-0.05) + assert done.active is False + assert hold.busy is False + assert done.curvature == pytest.approx(0.0, abs=1e-6) # the (straight) model curvature + assert model_k > 0.0 + + +def test_ridgewood_retake_blends_toward_the_driver_line(): + """Route-shaped: cones on the right, model path back toward them, driver held left. + + Approximates 1c95345a3286a5db segs 66–68. The re-take blend must not aim + at the model curvature. A full-control yield still clears latActive; this + test does not change that state machine. + """ + x_la = lookahead_m(V) + path_x, path_y = _path(x_la) + assert path_y_at_x(path_x, path_y, x_la) == pytest.approx(Y_PULL, abs=1e-6) + model_k = _model_k(x_la) + hold = ConeLineHold() + handoff = DriverLateralHandoff() + cone = _cone() + + def both(*, torque, hands, yielded_lat=None): + ho = handoff.update( + engaged=True, lat_would_be_active=True, steering_torque=torque, + steering_rate_deg=0.0, hands_on_level=hands, dt=DT, + model_curvature=model_k, measured_curvature=0.0, + ) + lat_active = (not ho.yielded) if yielded_lat is None else yielded_lat + co = hold.update( + enabled=True, engaged=True, cone=cone, torque_nm=torque, + measured_k=0.0, model_k=model_k, path_x=path_x, path_y=path_y, + v_ego=V, yielded=ho.yielded, lat_active=lat_active and not ho.yielded, dt=DT, + ) + return ho, co + + ho = co = None + for _ in range(int((PUSH_ARM_S + 0.4) / DT)): + ho, co = both(torque=1.0, hands=1) + assert ho.yielded is True + assert co.active is False + assert co.curvature == model_k + + for _ in range(int((RELEASE_HOLD_S + 0.05) / DT)): + ho, co = both(torque=0.0, hands=0) + assert ho.yielded is False + assert ho.blending is True + assert co.active is True + assert co.curvature == pytest.approx(0.0, abs=1e-6) + # Authority blend from the wheel (0) toward the hold target stays off the model path. + for authority in (0.0, 0.25, ho.authority, 1.0): + _torque, _angle, blended = apply_lat_authority(authority, 0.0, 0.0, 0.0, co.curvature, 0.0) + assert blended == pytest.approx(0.0, abs=1e-6) + assert blended < model_k - 0.0005 + + +def test_yield_machine_and_longitudinal_are_untouched(): + root = Path(__file__).resolve().parents[4] + handoff = (root / "selfdrive/controls/lib/driver_lateral_handoff.py").read_text() + assert "cone" not in handoff.lower() + controls = (root / "selfdrive/controls/controlsd.py").read_text() + # Longitudinal is written by published_long_accel(loc_accel=self.LoC.update(...)). + long_write = "actuators.accel = published_long_accel(" + assert long_write in controls + assert "loc_accel=self.LoC.update(" in controls + assert "_cone_curvature" in controls + # The curvature adjust sits after the longitudinal command is already written. + assert controls.index(long_write) < controls.index( + "model_or_plan_curvature = self._cone_curvature(") + # The cone hold reads only the wheel: no stalk / gap-lock input. + hold_src = (root / "selfdrive/controls/lib/cone_line_hold.py").read_text() + for word in ("napStalkSeq", "gapLock", "gap_lock", "CruiseButtons", "buttonEvents"): + assert word not in hold_src + assert "steering_pressed=bool(CS.steeringPressed),\n model_curvature=float(self._raw_model_curvature)," in controls + cone = (root / "selfdrive/controls/lib/cone_line.py").read_text() + hold = (root / "selfdrive/controls/lib/cone_line_hold.py").read_text() + assert "actuators" not in cone + assert "LoC" not in hold + assert "leadOne" not in cone + keys = (root / "common/params_keys.h").read_text() + hold_line = next(ln for ln in keys.splitlines() if f'"{PARAM_CONE_LINE_HOLD}"' in ln) + log_line = next(ln for ln in keys.splitlines() if f'"{PARAM_CONE_LINE_LOG}"' in ln) + assert 'BOOL' in hold_line and '"1"' in hold_line + assert 'BOOL' in log_line and '"1"' in log_line + services = (root / "cereal/services.py").read_text() + assert '"coneLineNAP": (True, 8., 2)' in services + ui = (root / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + assert "Hold my line" in ui or "CONE_LINE_HOLD_DESCRIPTION" in ui + assert "NAPConeLineHold" in ui + manner = (root / "selfdrive/ui/layouts/settings/driving_mannerisms.py").read_text() + assert "Hold my line near cones" in manner + hidden = (root / "selfdrive/ui/layouts/settings/hidden_toggles.py").read_text() + assert "Cone line log" in hidden + radard = (root / "selfdrive/controls/radard.py").read_text() + assert "_update_cone_line" in radard + assert "self.radar_state.leadOne" in radard + # The logged proposal is not a curvature command. + assert "wouldSteer" not in controls + assert "would_steer" not in controls + # radard already reads carState. The cone line must not add another subscriber. + assert radard.count("SubMaster(") == 1 + + +def test_oct7_push_away_from_left_posts_arms_and_the_retake_stays_off_them(): + """14:21:19 CT. Posts on the left, model curvature -0.0028 (left, +right + frame). Torque is +left, so the push away from the posts is negative. + 0.9 s of that push arms. On the re-take the command is the driver's + line, not the model bend into the posts, until the line ends. + A logged would_steer value is ignored. + """ + v = 18.0 + x_la = lookahead_m(v) + model_k = -0.0028 + y_at = 0.5 * model_k * x_la * x_la + path = ([0.0, x_la, x_la * 2.0], [0.0, y_at, y_at * 2.0]) + cone = SimpleNamespace(active=True, side=1, would_steer=0.4) + hold = ConeLineHold() + + short = _step(hold, torque=-1.2, measured_k=0.0, model_k=model_k, yielded=True, + lat_active=False, cone=cone, seconds=0.70, v=v, path=path) + assert short.active is False + assert hold.busy is False + + pushing = _step(hold, torque=-1.2, measured_k=0.0, model_k=model_k, yielded=True, + lat_active=False, cone=cone, seconds=0.20, v=v, path=path) + assert pushing.active is False # yielded: do not steer + assert pushing.curvature == model_k + assert hold.busy is True + + retake = _step(hold, torque=0.0, measured_k=0.0, model_k=model_k, yielded=False, + lat_active=True, cone=cone, seconds=0.3, v=v, path=path) + assert retake.active is True + assert retake.curvature == pytest.approx(0.0, abs=1e-4) + assert retake.curvature > model_k + 0.001 # not the bend into the posts + assert retake.offset_m > 0.2 # +right, away from the left posts + + still = _step(hold, torque=0.0, measured_k=0.0, model_k=model_k, yielded=False, + lat_active=True, cone=cone, seconds=4.0, v=v, path=path) + assert still.active is True + assert still.curvature == pytest.approx(0.0, abs=1e-4) + + toward = ConeLineHold() + blocked = _step(toward, torque=1.2, measured_k=0.0, model_k=model_k, yielded=True, + lat_active=False, cone=cone, seconds=PUSH_ARM_S + 1.0, v=v, path=path) + assert blocked.active is False + assert toward.busy is False + + +# ---- Oct 13 2026, pass E (08:06, 30 mph): drums on the right for 80 s ---- + +def test_oct13_pass_e_holds_his_actual_offset_with_no_fade(): + hold = ConeLineHold() + v = 13.4 + # He pushes left (torque +, away from right drums) and settles ~1.0 m left of centre. + _step_lane(hold, torque=1.2, seconds=1.2, yielded=True, lat_active=False, lane_offset=-1.0, v=v) + out = _step_lane(hold, seconds=0.2, lane_offset=-1.0, v=v) + assert out.active and out.source == "hold" + assert out.offset_m == pytest.approx(-1.0, abs=1e-6) # the full metre, not 0.2–0.3 + # 60 s later, line still active: still the full offset, no fade. + later = _step_lane(hold, seconds=60.0, lane_offset=-1.0, v=v) + assert later.active and later.offset_m == pytest.approx(-1.0, abs=1e-6) + # Line clears: held for CLEAR_S (3 s) more, then released over RELEASE_S. + gone = _cone(active=False, side=0) + wait = _step_lane(hold, seconds=CLEAR_S - 0.1, cone=gone, lane_offset=-1.0, v=v) + assert wait.active and wait.offset_m == pytest.approx(-1.0, abs=1e-6) + done = _step_lane(hold, seconds=0.2 + RELEASE_S, cone=gone, lane_offset=-1.0, v=v) + assert done.active is False and done.offset_m == 0.0 + assert CLEAR_S == pytest.approx(3.0) + + +def test_oct13_recaptures_on_each_push_and_never_follows_the_stalk(): + hold = ConeLineHold() + _step_lane(hold, torque=1.0, seconds=1.0, yielded=True, lat_active=False, lane_offset=-0.4) + first = _step_lane(hold, seconds=0.2, lane_offset=-0.4) + assert first.offset_m == pytest.approx(-0.4, abs=1e-6) + # Second push further left: re-captured at -1.1. + _step_lane(hold, torque=1.0, seconds=0.5, yielded=True, lat_active=False, lane_offset=-1.1) + second = _step_lane(hold, seconds=0.6, lane_offset=-1.1) + assert second.offset_m == pytest.approx(-1.1, abs=1e-6) + # A short brush under STEER_BACK_S does not re-capture. + _step_lane(hold, torque=1.0, seconds=0.1, lane_offset=-0.6) + brush = _step_lane(hold, seconds=0.5, lane_offset=-0.6) + assert brush.offset_m == pytest.approx(-1.1, abs=1e-6) + # Wheel torque only: there is no blinker / stalk input at all. + import inspect + params = inspect.signature(ConeLineHold.update).parameters + assert not any("blink" in n or "stalk" in n or "lane_change" in n for n in params) + + +def test_oct13_cone_shift_applies_only_when_not_holding_and_never_toward_the_cones(): + hold = ConeLineHold() + # Right drums (side -1): radard's shift is -0.8 (left). Applied. + out = _step_lane(hold, cone_shift=-0.8) + assert out.active and out.source == "shift" and out.offset_m == pytest.approx(-0.8) + assert out.curvature < 0.0 # left in the +right frame + # A shift toward the cones is ignored. + bad = _step_lane(ConeLineHold(), cone_shift=+0.5) + assert bad.active is False + # Yielded (driver steering) or lateral off: nothing applied. + assert _step_lane(ConeLineHold(), cone_shift=-0.8, yielded=True).active is False + assert _step_lane(ConeLineHold(), cone_shift=-0.8, lat_active=False).active is False + # No active line: nothing. + assert _step_lane(ConeLineHold(), cone_shift=-0.8, cone=_cone(active=False, side=0)).active is False + # Once he holds his own line, the hold wins over the shift. + _step_lane(hold, torque=1.0, seconds=1.0, yielded=True, lat_active=False, lane_offset=-1.0, cone_shift=-0.8) + mine = _step_lane(hold, seconds=0.2, lane_offset=-1.0, cone_shift=-0.8) + assert mine.source == "hold" and mine.offset_m == pytest.approx(-1.0) + + +def test_oct13_hold_uses_lane_centre_ahead_when_known(): + hold = ConeLineHold() + _step_lane(hold, torque=1.0, seconds=1.0, yielded=True, lat_active=False, lane_offset=-0.9) + # Lane centre ahead sits 0.3 m right of the (straight) model path: hold centre + offset. + out = _step_lane(hold, seconds=0.2, lane_offset=-0.9, lane_center_la=0.3) + assert out.offset_m == pytest.approx(-0.6, abs=1e-6) diff --git a/selfdrive/controls/lib/tests/test_cone_line_replay.py b/selfdrive/controls/lib/tests/test_cone_line_replay.py new file mode 100644 index 00000000000000..6998ce5c4f02e0 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_cone_line_replay.py @@ -0,0 +1,106 @@ +"""Replays of real Oct 10, 2026 drives (dongle 1c95345a3286a5db) through ConeLineDetector. + +Each fixture is the radar-rate input radard hands the detector, cut from the rlog +(gzip JSON, base64 so it diffs and pushes as text): +liveTracks points (pre-filtered to near-stationary returns), vEgo, the model path, +road edges and yaw rate. `t` is seconds from the start of the cut. + + 17c_cone_zone 0000017c 17:30:00–17:33:30 CT. Drums in the closed left lane, + then channelizers on the left line, 46–70 mph. 112907e9 saw nothing. + 17b_cone_pass 0000017b 16:47:55–16:48:45 CT. Drums 1.5–2.5 m left at 54 mph. + Must stay a left line with wouldSteer pointing right. + 17b_town_parked 0000017b 16:41:20–16:43:00 CT. Town, parked cars, an overpass + pier and sign poles; includes the 16:42:24 parked rejection. + 17b_parked_1647 / 17b_parked_1650 the 16:47:01 and 16:50:21 parked rejections. +""" +import base64 +import gzip +import json +from pathlib import Path + +import pytest + +from openpilot.selfdrive.controls.lib.cone_line import ConeLineDetector + +FIX = Path(__file__).resolve().parent / "cone_replay" + + +def _replay(name): + frames = json.loads(gzip.decompress(base64.b64decode((FIX / f"{name}.json.gz.b64").read_bytes()))) + det = ConeLineDetector() + out = [] + prev = None + for f in frames: + dt = 0.05 if prev is None else f["t"] - prev + prev = f["t"] + pts = [{"dRel": p[0], "yRel": p[1], "vRel": p[2], "measured": bool(p[3])} for p in f["pts"]] + edges = [(e[0], e[1]) for e in f["edges"]] + yaw = f["yaw"] if abs(f["yaw"]) < 1.5 else 0.0 + out.append((f["t"], det.update(pts, f["v"], f["px"], f["py"], edges, dt, yaw))) + return out + + +def _active_s(out): + total = 0.0 + for (t0, s0), (t1, _) in zip(out, out[1:], strict=False): + if s0.active: + total += t1 - t0 + return total + + +@pytest.fixture(autouse=True) +def _no_budget(monkeypatch): + # Replays are about the geometry, not the 2 ms on-device budget of a slow CI box. + import openpilot.selfdrive.controls.lib.cone_line as cl + monkeypatch.setattr(cl, "CONE_BUDGET_S", 10.0) + + +def test_oct10_closed_left_lane_zone_is_detected_on_the_left(): + out = _replay("oct10_17c_cone_zone") + active = [s for _, s in out if s.active] + assert _active_s(out) >= 10.0 + assert all(s.side == 1 for s in active) + # Left line: path-relative lateral is negative (+right frame), and nothing proposes + # moving toward it. + assert all(s.lat_near < 0.0 for s in active) + assert all(s.would_steer >= 0.0 for s in active) + + +def test_oct10_1648_left_drums_stay_correct(): + out = _replay("oct10_17b_cone_pass") + active = [(t, s) for t, s in out if s.active] + assert active, "the 16:48 pass must still confirm" + # 112907e9 confirmed 16.2 s into this cut (16:48:11.1); never later than that. + assert active[0][0] <= 16.3 + assert _active_s(out) >= 18.0 + assert all(s.side == 1 for _, s in active) + steer = [s.would_steer for _, s in active if s.would_steer != 0.0] + assert steer and all(0.0 < w <= 1.0 + 1e-6 for w in steer) + # Ramped slowly (0.2 m/s): no single-frame jump. + prev = 0.0 + for _, s in out: + assert abs(s.would_steer - prev) <= 0.2 * 0.5 + 1e-6 + prev = s.would_steer + + +@pytest.mark.parametrize("name", ["oct10_17b_town_parked", "oct10_17b_parked_1647", "oct10_17b_parked_1650"]) +def test_oct10_town_and_parked_cars_never_become_a_line(name): + out = _replay(name) + assert not any(s.active for _, s in out) + assert all(s.would_steer == 0.0 for _, s in out) + assert any(s.parked for _, s in out), "the logged parked-car rejection must still fire" + + +@pytest.mark.parametrize("name", ["oct10_17b_parked_1647", "oct10_17b_parked_1650", "oct10_17b_town_parked"]) +def test_oct14_corridor_detector_keeps_the_parked_rejections(name, monkeypatch): + from openpilot.selfdrive.controls.lib.cone_line import ConeCorridorDetector + frames = json.loads(gzip.decompress(base64.b64decode((FIX / f"{name}.json.gz.b64").read_bytes()))) + det = ConeCorridorDetector() + prev = None + for f in frames: + dt = 0.05 if prev is None else f["t"] - prev + prev = f["t"] + pts = [{"dRel": p[0], "yRel": p[1], "vRel": p[2], "measured": bool(p[3])} for p in f["pts"]] + s = det.update(pts, f["v"], f["px"], f["py"], [(e[0], e[1]) for e in f["edges"]], dt, + f["yaw"] if abs(f["yaw"]) < 1.5 else 0.0) + assert not s.active and s.would_steer == 0.0 diff --git a/selfdrive/controls/lib/tests/test_curve_max_hold.py b/selfdrive/controls/lib/tests/test_curve_max_hold.py new file mode 100644 index 00000000000000..6ce8611c521ddb --- /dev/null +++ b/selfdrive/controls/lib/tests/test_curve_max_hold.py @@ -0,0 +1,462 @@ +"""Curve MAX snapshot/restore: temp slow through the bend, then pre-curve set.""" +from pathlib import Path + +import pytest +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.curve_max_hold import ( + CURVE_CAP_SETTLE_S, + CURVE_ENTER_LAT_MS2, + CURVE_EXIT_HOLD_S, + CURVE_LAT_TAU_S, + CURVE_MIN_V_EGO_MS, + CURVE_RESTORE_A_DEFAULT_MS2, + CurveMaxHold, + cornering_lat_accel_ms2, + curve_lat_target_ms2, + curve_restore_a_ms2, + curve_speed_for_curvature, + curve_speed_from_lat, + curve_speed_ms, + is_sharp_curve, + steer_lat_accel_ms2, +) +from openpilot.selfdrive.mapd.constants import MODE_FOLLOW +from openpilot.selfdrive.mapd.map_speed_policy import MapCruiseHold, decide_map_cruise + +# Tesla Model S Pre-AP (same as planner tests). +SR = 15.75 +WB = 2.959 +V_60 = 60.0 * CV.MPH_TO_MS +V_55 = 55.0 * CV.MPH_TO_MS + + +def _kph(mph: float) -> float: + return mph * CV.MPH_TO_KPH + + +def _sharp_steer_deg(v_ms: float = V_60, a_y: float = 2.4) -> float: + """Steer that produces about a_y at v (above enter, well above exit).""" + return (a_y * SR * WB) / (max(v_ms, 1e-3) ** 2) * CV.RAD_TO_DEG + + +def _follow_seed(hold: MapCruiseHold, posted_kph: float, sticky_kph: float | None = None): + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted_kph, posted_kph=posted_kph, + engage_rising=True, now=0.0, + ) + if sticky_kph is not None: + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky_kph, posted_kph=posted_kph, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + + +def test_lat_accel_matches_planner_formula(): + a_y = steer_lat_accel_ms2(V_60, 10.0, SR, WB) + expect = (V_60 ** 2) * 10.0 * CV.DEG_TO_RAD / (SR * WB) + assert abs(a_y - abs(expect)) < 1e-9 + + +def test_straight_is_not_a_curve(): + assert not is_sharp_curve(V_60, 2.0, SR, WB, active=False) + assert curve_speed_ms(V_60, 0.0, SR, WB) is None + assert not is_sharp_curve(CURVE_MIN_V_EGO_MS - 0.5, 40.0, SR, WB, active=False) + + +def test_sharp_steer_is_a_curve_and_caps_below_60(): + steer = _sharp_steer_deg() + assert is_sharp_curve(V_60, steer, SR, WB, active=False) + v_cap = curve_speed_ms(V_60, steer, SR, WB) + assert v_cap is not None + assert v_cap < V_60 + # Speed-dependent comfort a_lat: v²·kappa = A(v). + kappa = abs(steer) * CV.DEG_TO_RAD / (SR * WB) + assert abs(v_cap - curve_speed_for_curvature(kappa)) < 1e-6 + assert abs(v_cap * v_cap * kappa - curve_lat_target_ms2(v_cap)) < 1e-3 + + +def _run_bend(curve: CurveMaxHold, hold: MapCruiseHold, *, last_hud, posted_now, + steer, v_ego=V_60, dt=0.01, hud_overlay=None, stalk=False, take=False, + curvature=None, yaw_rate=None, restore_a_ms2=1.0e4): + policy_posted, freeze = curve.begin_cycle( + hold, last_hud_kph=last_hud, posted_kph=posted_now, + v_ego_ms=v_ego, angle_steers_deg=steer, steer_ratio=SR, wheelbase=WB, + engaged=True, take_speed_now=take, dt=dt, + curvature=curvature, yaw_rate=yaw_rate, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, + raw_kph=hold.held_max_kph or last_hud, + posted_kph=policy_posted, + engage_rising=False, now=2.0, stalk_pressed=stalk, take_speed_now=take, + ) + overlay = hud_overlay if hud_overlay is not None else dec.driver_kph + out = curve.finish( + hud_kph=overlay, hold=hold, posted_kph=posted_now, + v_ego_ms=v_ego, angle_steers_deg=steer, steer_ratio=SR, wheelbase=WB, + engaged=True, stalk_pressed=stalk, take_speed_now=take, dt=dt, + curvature=curvature, yaw_rate=yaw_rate, restore_a_ms2=restore_a_ms2, + ) + return out, freeze, dec + + +def test_justin_hypermile_curve_restores_60_not_eco_55(): + """Sticky/display MAX 60 must survive a bend even if posted looks lower. + + Through a sharp curve OSM may flicker (or HUD is temporarily capped). After + exit MAX must be 60, not a lower posted/eco target the flicker rebase + would invent. (Live Hypermile eco is posted-scaled; 55 here is a lower + posted stand-in, not a claim that posted 60 still snaps −5.) + """ + posted_eco = _kph(55) # lower posted / eco-like target vs sticky 60 + sticky_60 = _kph(60) + hold = MapCruiseHold() + _follow_seed(hold, posted_eco, sticky_60) + assert abs(hold.held_max_kph - sticky_60) < 1e-6 + assert hold.sticky_set_kph is not None + + curve = CurveMaxHold() + steer = _sharp_steer_deg() + flicker = _kph(25) + + out, freeze, dec = _run_bend( + curve, hold, last_hud=sticky_60, posted_now=flicker, steer=steer, + ) + assert freeze + assert curve.active + assert curve.snapshot is not None + assert abs(curve.snapshot.hud_max_kph - sticky_60) < 1e-6 + # Flicker must not wipe sticky / rebase held to 25. + assert dec.sticky + assert abs(hold.held_max_kph - sticky_60) < 1e-6 + assert abs(hold.sticky_set_kph - sticky_60) < 1e-6 + # Temporary MAX may drop for the corner. Must not write that into hold. + assert out.hud_kph < sticky_60 + assert out.restore_seed_kph is None + assert abs(hold.held_max_kph - sticky_60) < 1e-6 + + # Still in the bend a few frames (flicker then eco posted again). + for _ in range(8): + out, _, _ = _run_bend( + curve, hold, last_hud=out.hud_kph, posted_now=posted_eco, steer=steer, + ) + assert curve.active + assert abs(hold.held_max_kph - sticky_60) < 1e-6 + + # Straight-ish: hold exit debounce, then restore 60. + restored = None + for _ in range(int(CURVE_EXIT_HOLD_S / 0.01) + 3): + out, _, _ = _run_bend( + curve, hold, last_hud=out.hud_kph, posted_now=posted_eco, steer=1.5, + ) + if out.restore_seed_kph is not None: + restored = out + break + assert restored is not None + assert abs(restored.hud_kph - sticky_60) < 1e-6 + assert abs(restored.restore_seed_kph - sticky_60) < 1e-6 + assert abs(hold.held_max_kph - sticky_60) < 1e-6 + assert abs(hold.sticky_set_kph - sticky_60) < 1e-6 + assert not curve.active + assert curve.snapshot is None + + +def test_eco_follow_without_sticky_restores_55(): + """Steady Hypermile Follow (no stalk hold) snapshots 55 and returns 55.""" + posted_eco = _kph(55) + hold = MapCruiseHold() + _follow_seed(hold, posted_eco, None) + assert abs(hold.held_max_kph - posted_eco) < 1e-6 + assert hold.sticky_set_kph is None + + curve = CurveMaxHold() + steer = _sharp_steer_deg() + out, _, _ = _run_bend( + curve, hold, last_hud=posted_eco, posted_now=posted_eco, steer=steer, + hud_overlay=_kph(40), + ) + assert out.hud_kph <= posted_eco + assert abs(hold.held_max_kph - posted_eco) < 1e-6 + + restored = None + hud = out.hud_kph + for _ in range(int(CURVE_EXIT_HOLD_S / 0.01) + 3): + out, _, _ = _run_bend( + curve, hold, last_hud=hud, posted_now=posted_eco, steer=1.5, + hud_overlay=posted_eco, + ) + hud = out.hud_kph + if out.restore_seed_kph is not None: + restored = out + break + assert restored is not None + assert abs(restored.hud_kph - posted_eco) < 1e-6 + + +def test_real_posted_change_through_curve_does_not_restore_old_max(): + """60→45 zone that is still 45 after the bend is a real rebase, not flicker.""" + posted_a = _kph(55) + posted_b = _kph(40) + sticky_60 = _kph(60) + hold = MapCruiseHold() + _follow_seed(hold, posted_a, sticky_60) + curve = CurveMaxHold() + steer = _sharp_steer_deg() + _run_bend(curve, hold, last_hud=sticky_60, posted_now=posted_a, steer=steer) + assert curve.snapshot is not None + assert abs(curve.snapshot.posted_kph - posted_a) < 1.0 + + out = None + for _ in range(int(CURVE_EXIT_HOLD_S / 0.01) + 3): + out, _, _ = _run_bend( + curve, hold, last_hud=sticky_60, posted_now=posted_b, steer=1.5, + hud_overlay=posted_b, + ) + assert out is not None + assert out.restore_seed_kph is None + assert abs(out.hud_kph - posted_b) < 1e-6 + assert not curve.active + + +def test_stalk_during_curve_updates_snapshot(): + posted = _kph(55) + sticky_60 = _kph(60) + new_set = _kph(50) + hold = MapCruiseHold() + _follow_seed(hold, posted, sticky_60) + curve = CurveMaxHold() + steer = _sharp_steer_deg() + _run_bend(curve, hold, last_hud=sticky_60, posted_now=posted, steer=steer) + out, _, _ = _run_bend( + curve, hold, last_hud=sticky_60, posted_now=posted, steer=steer, + hud_overlay=new_set, stalk=True, + ) + assert curve.snapshot is not None + assert abs(curve.snapshot.hud_max_kph - new_set) < 1e-6 + + restored = None + for _ in range(int(CURVE_EXIT_HOLD_S / 0.01) + 3): + out, _, _ = _run_bend( + curve, hold, last_hud=new_set, posted_now=posted, steer=1.5, + hud_overlay=new_set, + ) + if out.restore_seed_kph is not None: + restored = out + break + assert restored is not None + assert abs(restored.hud_kph - new_set) < 1e-6 + + +def test_disengage_clears_curve_snapshot(): + hold = MapCruiseHold() + _follow_seed(hold, _kph(55), _kph(60)) + curve = CurveMaxHold() + steer = _sharp_steer_deg() + _run_bend(curve, hold, last_hud=_kph(60), posted_now=_kph(55), steer=steer) + assert curve.active + curve.finish( + hud_kph=_kph(40), hold=hold, posted_kph=_kph(55), + v_ego_ms=V_60, angle_steers_deg=steer, steer_ratio=SR, wheelbase=WB, + engaged=False, dt=0.01, + ) + assert not curve.active + assert curve.snapshot is None + + +def test_take_speed_now_clears_curve_snapshot(): + hold = MapCruiseHold() + _follow_seed(hold, _kph(55), _kph(60)) + curve = CurveMaxHold() + steer = _sharp_steer_deg() + _run_bend(curve, hold, last_hud=_kph(60), posted_now=_kph(55), steer=steer) + out, freeze, _ = _run_bend( + curve, hold, last_hud=_kph(60), posted_now=_kph(55), steer=steer, take=True, + ) + assert not freeze + assert not curve.active + assert out.restore_seed_kph is None + + +def test_temp_cap_does_not_raise_max(): + """Curve speed above the set must not lift HUD MAX.""" + hold = MapCruiseHold() + posted = _kph(40) + _follow_seed(hold, posted, None) + curve = CurveMaxHold() + # Mild steer that still enters via angle at this speed, but v_curve > 40 mph. + steer = 14.5 + assert is_sharp_curve(V_55, steer, SR, WB, active=False) + v_cap = curve_speed_ms(V_55, steer, SR, WB) + assert v_cap is not None + out, _, _ = _run_bend( + curve, hold, last_hud=posted, posted_now=posted, steer=steer, + v_ego=V_55, hud_overlay=posted, + ) + assert out.hud_kph <= posted + 1e-6 + + +def test_card_and_docs_wire_curve_max_restore(): + root = Path(__file__).resolve().parents[4] + card = (root / "selfdrive/car/card.py").read_text() + planner = (root / "selfdrive/controls/lib/longitudinal_planner.py").read_text() + docs = (root / "docs-nap/map-speed.md").read_text() + hyper = (root / "docs-nap/hypermile.md").read_text() + releases = (root / "RELEASES.md").read_text() + assert "CurveMaxHold" in card + assert "begin_cycle" in card + assert "restore_seed_kph" in card + assert "limit_accel_in_turns" in planner + assert "curve" in docs.lower() and "MAX" in docs + assert "pre-curve" in docs.lower() or "before the curve" in docs.lower() + assert "curve" in hyper.lower() + hm = next(p for p in releases.split("\n\n") if "curve" in p.lower() and p.startswith("NAP")) + assert "MAX" in hm + + +def test_card_curve_curvature_comes_from_car_control(): + """#239's 100 Hz controlsState socket does not belong on card. + + Vehicle-model curvature is already on carControl.currentCurvature. + livePose remains the yaw-rate fallback. + """ + root = Path(__file__).resolve().parents[4] + card = (root / "selfdrive/car/card.py").read_text() + sm = card.split("messaging.SubMaster([", 1)[1].split("])", 1)[0] + assert "controlsState" not in sm + assert "currentCurvature" in card + assert "livePose" in sm + + +def test_curvature_lat_accel_not_raw_steer(): + """Route 115: steer-model a_y read ~1.84× the real corner. + + A sweeper whose vehicle-model curvature is 1.4 m/s² at 70 mph must + not drop MAX. The same wheel angle through the stock steer model + (ratio 15, no angle offset, no understeer) would. + """ + v = 70.0 * CV.MPH_TO_MS + real_ay = 1.4 + kappa = real_ay / (v * v) + assert cornering_lat_accel_ms2(v, 7.0, SR, WB, curvature=kappa) == pytest.approx(real_ay) + assert cornering_lat_accel_ms2( + v, 20.0, SR, WB, yaw_rate=real_ay / v, + ) == pytest.approx(real_ay) + steer_ay = steer_lat_accel_ms2(v, 7.0, 15.0, WB) + assert steer_ay > real_ay * 1.5 + assert curve_speed_from_lat(v, real_ay) > v + assert curve_speed_from_lat(v, steer_ay) < v + + posted = _kph(70) + hold = MapCruiseHold() + _follow_seed(hold, posted, None) + curve = CurveMaxHold() + out, _, _ = _run_bend( + curve, hold, last_hud=posted, posted_now=posted, steer=7.0, + v_ego=v, hud_overlay=posted, curvature=kappa, + ) + assert out.hud_kph == pytest.approx(posted, abs=0.05) + # Same steer, no curvature: the inflated model does cap. + steer_only = curve_speed_ms(v, 7.0, 15.0, WB) + assert steer_only is not None and steer_only * CV.MS_TO_KPH < posted + + +def test_lat_accel_smooths_and_cap_holds_then_ramps(): + """Cap tracks a smoothed a_y, does not pump up mid-bend, ramps out. + + First sample matches the raw corner so entry is immediate. After the + settle window a looser reading must not raise the cap; a clearly + tighter one may drop it. Exit restores MAX at the Accel rate, not + in one frame, and does not rebase sticky. + """ + v = V_60 + posted = _kph(60) + hold = MapCruiseHold() + _follow_seed(hold, posted, posted) + curve = CurveMaxHold() + # a_y 2.4 → comfort speed below 60. kappa = a_y / v². + kappa_tight = 2.4 / (v * v) + out, _, _ = _run_bend( + curve, hold, last_hud=posted, posted_now=posted, steer=4.0, + v_ego=v, hud_overlay=posted, curvature=kappa_tight, restore_a_ms2=0.40, + ) + assert curve._ay_s == pytest.approx(2.4, abs=1e-6) + assert out.hud_kph < posted - 1.0 + capped = out.hud_kph + # One noisy spike must not jump the smoothed a_y to the spike. + kappa_spike = 4.0 / (v * v) + _run_bend( + curve, hold, last_hud=capped, posted_now=posted, steer=4.0, + v_ego=v, hud_overlay=posted, curvature=kappa_spike, restore_a_ms2=0.40, + ) + alpha = 0.01 / (CURVE_LAT_TAU_S + 0.01) + assert curve._ay_s < 2.4 + alpha * (4.0 - 2.4) + 0.05 + assert curve._ay_s < 3.0 + + # Settle, then a looser bend must not raise the cap. + for _ in range(int(CURVE_CAP_SETTLE_S / 0.01) + 5): + out, _, _ = _run_bend( + curve, hold, last_hud=posted, posted_now=posted, steer=4.0, + v_ego=v, hud_overlay=posted, curvature=kappa_tight, restore_a_ms2=0.40, + ) + held = out.hud_kph + # A slightly looser reading (jitter, inside the unwind hysteresis) must + # not raise the cap. + kappa_jitter = 2.25 / (v * v) + for _ in range(100): + out, _, _ = _run_bend( + curve, hold, last_hud=posted, posted_now=posted, steer=4.0, + v_ego=v, hud_overlay=posted, curvature=kappa_jitter, restore_a_ms2=0.40, + ) + assert out.hud_kph <= held + 0.05 + # A real unwind past the apex lets the cap climb, but only at the + # restore rate, never a jump. + kappa_loose = 1.6 / (v * v) + assert kappa_loose * v * v >= CURVE_ENTER_LAT_MS2 + step_max = curve_restore_a_ms2(v, 0.40) * CV.MS_TO_KPH * 0.01 + 1e-6 + prev = out.hud_kph + for _ in range(100): + out, _, _ = _run_bend( + curve, hold, last_hud=posted, posted_now=posted, steer=4.0, + v_ego=v, hud_overlay=posted, curvature=kappa_loose, restore_a_ms2=0.40, + ) + assert out.hud_kph <= prev + step_max + prev = out.hud_kph + assert out.hud_kph > held + 0.1 + assert abs(hold.held_max_kph - posted) < 1e-6 + + # Clearly tighter: cap may drop. + kappa_hard = 3.2 / (v * v) + dropped = held + for _ in range(int(CURVE_CAP_SETTLE_S / 0.01) + 8): + out, _, _ = _run_bend( + curve, hold, last_hud=posted, posted_now=posted, steer=4.0, + v_ego=v, hud_overlay=posted, curvature=kappa_hard, restore_a_ms2=0.40, + ) + dropped = min(dropped, out.hud_kph) + assert dropped < held - 1.0 + + # Exit ramps toward the snapshot. Sticky stays put until the ramp ends. + saw_partial = False + first_rise = None + restored = None + prev = out.hud_kph + for _ in range(int((CURVE_EXIT_HOLD_S + 30.0) / 0.01)): + out, _, _ = _run_bend( + curve, hold, last_hud=posted, posted_now=posted, steer=1.0, + v_ego=v, hud_overlay=posted, curvature=0.0, restore_a_ms2=CURVE_RESTORE_A_DEFAULT_MS2, + ) + if out.restore_seed_kph is None and out.hud_kph > prev + 1e-4: + saw_partial = True + if first_rise is None: + first_rise = out.hud_kph + assert abs(hold.sticky_set_kph - posted) < 1e-6 + prev = out.hud_kph + if out.restore_seed_kph is not None: + restored = out + break + assert saw_partial and first_rise is not None + assert first_rise < posted - 1.0 + assert restored is not None + assert restored.hud_kph == pytest.approx(posted, abs=0.05) + assert abs(hold.held_max_kph - posted) < 1e-6 + assert not curve.active diff --git a/selfdrive/controls/lib/tests/test_desire_helper.py b/selfdrive/controls/lib/tests/test_desire_helper.py new file mode 100644 index 00000000000000..5441c75c054929 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_desire_helper.py @@ -0,0 +1,430 @@ +from cereal import log +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.desire_helper import ( + DesireHelper, + DT_MDL, + LANE_CHANGE_ARM_TIME, + LANE_CHANGE_SPEED_MIN, + MAX_QUEUED_LANE_CHANGES, + LaneChangeDirection, + LaneChangeState, +) +from openpilot.selfdrive.controls.lib.stalk_tip_turn import ( + STALK_ALC_TURN_HOLD_S, + STALK_TIP_HOLD_S, +) + + +class FakeCarState: + def __init__(self, v_ego=30.0, left=False, right=False, + steering_pressed=False, steering_torque=0.0, + left_blindspot=False, right_blindspot=False, lever=0): + self.vEgo = v_ego + self.leftBlinker = left + self.rightBlinker = right + self.steeringPressed = steering_pressed + self.steeringTorque = steering_torque + self.leftBlindspot = left_blindspot + self.rightBlindspot = right_blindspot + self.turnSignalStalkState = lever + + +def _tick(dh, cs, n=1, lane_change_prob=0.0): + for _ in range(n): + dh.update(cs, lateral_active=True, lane_change_prob=lane_change_prob) + + +def _arm_left(dh, v_ego=30.0): + dh.update(FakeCarState(v_ego=v_ego), True, 0.0) + dh.update(FakeCarState(v_ego=v_ego, left=True, lever=1), True, 0.0) + dh.update(FakeCarState(v_ego=v_ego, left=True, lever=0), True, 0.0) + + +def _hold_lever(dh, lever, v_ego=30.0, t=None, lane_change_prob=1.0): + if t is None: + t = STALK_TIP_HOLD_S + lamp_left = lever == 1 + lamp_right = lever == 2 + for _ in range(int(round(t / DT_MDL)) + 1): + dh.update(FakeCarState(v_ego=v_ego, left=lamp_left, right=lamp_right, lever=lever), + True, lane_change_prob) + + +def _lever_tap(dh, lever, lamp_left=True, hold_ticks=3): + for _ in range(hold_ticks): + dh.update(FakeCarState(left=lamp_left, lever=lever), True, 0.0) + dh.update(FakeCarState(left=lamp_left), True, 0.0) + + +def _nudge_left(): + return FakeCarState(left=True, steering_pressed=True, steering_torque=1.0) + + +def _advance_to_finishing(dh): + _tick(dh, _nudge_left(), n=int(0.6 / DT_MDL), lane_change_prob=0.0) + assert dh.lane_change_state == LaneChangeState.laneChangeFinishing + + +def _complete_maneuver(dh, cs_after): + _advance_to_finishing(dh) + for _ in range(int(1.5 / DT_MDL)): + dh.update(cs_after, True, 0.0) + if dh.lane_change_state != LaneChangeState.laneChangeFinishing: + break + + +def test_tap_arms_pre_lane_change(): + dh = DesireHelper() + _arm_left(dh) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.lane_change_direction == LaneChangeDirection.left + assert dh.queued_changes == 1 + assert dh.desire == log.Desire.none + + +def test_tap_alone_does_not_leave_lane(): + """Stock NAP: tap arms. Do not start the change until a wheel nudge.""" + dh = DesireHelper() + _arm_left(dh) + left, right = DesireHelper.lane_change_keep_blinker(dh.lane_change_state, dh.lane_change_direction) + assert left and not right + + _tick(dh, FakeCarState(left=True, lever=0), n=int(2.0 / DT_MDL)) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.desire == log.Desire.none + assert dh.desire not in (log.Desire.laneChangeLeft, log.Desire.laneChangeRight) + left, right = DesireHelper.lane_change_keep_blinker(dh.lane_change_state, dh.lane_change_direction) + assert left and not right + + +def test_wrong_way_torque_does_not_start_lane_change(): + dh = DesireHelper() + _arm_left(dh) + dh.update(FakeCarState(left=True, steering_pressed=True, steering_torque=-1.0), True, 0.0) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.desire == log.Desire.none + + dh.update(FakeCarState(left=True, steering_pressed=True, steering_torque=0.0), True, 0.0) + assert dh.lane_change_state == LaneChangeState.preLaneChange + + +def test_tap_arms_without_lamp_on_yet(): + dh = DesireHelper() + dh.update(FakeCarState(), True, 0.0) + dh.update(FakeCarState(lever=1), True, 0.0) + dh.update(FakeCarState(lever=0), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.lane_change_direction == LaneChangeDirection.left + + +def test_stalk_return_to_idle_does_not_cancel(): + dh = DesireHelper() + _arm_left(dh) + _tick(dh, FakeCarState(left=True, lever=0), n=5) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.lane_change_direction == LaneChangeDirection.left + + +def test_alc_keep_blinker_until_lane_change_finishes(): + dh = DesireHelper() + _arm_left(dh) + left, right = DesireHelper.lane_change_keep_blinker(dh.lane_change_state, dh.lane_change_direction) + assert left and not right + + dh.update(FakeCarState(left=True), True, 0.0) + left, right = DesireHelper.lane_change_keep_blinker(dh.lane_change_state, dh.lane_change_direction) + assert left and not right + + dh.update(_nudge_left(), True, 0.0) + left, right = DesireHelper.lane_change_keep_blinker(dh.lane_change_state, dh.lane_change_direction) + assert left and not right + + _complete_maneuver(dh, FakeCarState()) + left, right = DesireHelper.lane_change_keep_blinker(dh.lane_change_state, dh.lane_change_direction) + assert not left and not right + assert dh.lane_change_state == LaneChangeState.off + + +def test_lamp_edges_without_lever_do_not_arm(): + dh = DesireHelper() + dh.update(FakeCarState(), True, 0.0) + dh.update(FakeCarState(v_ego=30.0, left=True), True, 0.0) + dh.update(FakeCarState(v_ego=30.0), True, 0.0) + dh.update(FakeCarState(v_ego=30.0, left=True), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + assert dh.queued_changes == 0 + + +def test_hazards_do_not_start_lane_change(): + dh = DesireHelper() + dh.update(FakeCarState(), True, 0.0) + dh.update(FakeCarState(left=True, right=True, lever=1), True, 0.0) + dh.update(FakeCarState(v_ego=30.0, left=True, right=True), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + + +def test_latch_survives_blinker_lamp_off(): + dh = DesireHelper() + _arm_left(dh) + dh.update(FakeCarState(), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + + +def test_tip_then_idle_arms_at_low_speed(): + dh = DesireHelper() + slow = 10 * CV.MPH_TO_MS + _arm_left(dh, v_ego=slow) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.lane_change_direction == LaneChangeDirection.left + assert dh.desire == log.Desire.none + + +def test_tip_then_idle_arms_at_highway_speed(): + dh = DesireHelper() + _arm_left(dh, v_ego=30.0) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.lane_change_direction == LaneChangeDirection.left + + +def test_held_lever_does_not_arm_at_highway_speed(): + dh = DesireHelper() + dh.update(FakeCarState(v_ego=30.0), True, 0.0) + _hold_lever(dh, 1, v_ego=30.0) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + assert dh._tip_turn.is_turn + + +def test_held_lever_does_not_arm_at_low_speed(): + dh = DesireHelper() + slow = 10 * CV.MPH_TO_MS + dh.update(FakeCarState(v_ego=slow), True, 0.0) + _hold_lever(dh, 2, v_ego=slow) + + assert dh.lane_change_state == LaneChangeState.off + assert dh._tip_turn.is_turn + + +def test_nudge_below_speed_does_not_start_lane_change(): + """20 mph still gates starting the maneuver, not tip-vs-turn.""" + dh = DesireHelper() + slow = 10 * CV.MPH_TO_MS + _arm_left(dh, v_ego=slow) + dh.update(FakeCarState(v_ego=slow, left=True, steering_pressed=True, steering_torque=1.0), + True, 0.0) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.desire == log.Desire.none + assert slow < LANE_CHANGE_SPEED_MIN + + +def test_nudge_after_reaching_speed_starts(): + dh = DesireHelper() + slow = 10 * CV.MPH_TO_MS + _arm_left(dh, v_ego=slow) + dh.update(FakeCarState(v_ego=30.0, left=True, steering_pressed=True, steering_torque=1.0), + True, 0.0) + + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.desire == log.Desire.laneChangeLeft + + +def test_arming_times_out_without_nudge(): + dh = DesireHelper() + _arm_left(dh) + _tick(dh, FakeCarState(left=True), n=int(LANE_CHANGE_ARM_TIME / DT_MDL) + 5) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + assert dh.queued_changes == 0 + + +def test_wheel_nudge_starts_lane_change(): + dh = DesireHelper() + _arm_left(dh) + assert dh.desire == log.Desire.none + dh.update(_nudge_left(), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.desire == log.Desire.laneChangeLeft + + +def test_opposite_lever_tap_cancels_while_arming(): + dh = DesireHelper() + _arm_left(dh) + dh.update(FakeCarState(left=True, lever=2), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + assert dh.queued_changes == 0 + + +def test_opposite_lever_tap_cancels_at_low_speed(): + dh = DesireHelper() + slow = 10 * CV.MPH_TO_MS + _arm_left(dh, v_ego=slow) + dh.update(FakeCarState(v_ego=slow, left=True, lever=2), True, 0.0) + assert dh.lane_change_state == LaneChangeState.off + + +def test_opposite_lever_tap_cancels_while_starting(): + dh = DesireHelper() + _arm_left(dh) + dh.update(_nudge_left(), True, 0.0) + dh.update(FakeCarState(left=True, lever=2), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + + +def test_opposite_lever_tap_cancels_while_finishing(): + dh = DesireHelper() + _arm_left(dh) + _advance_to_finishing(dh) + dh.update(FakeCarState(left=True, lever=2), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + + +def test_opposite_tap_does_not_rearm_new_direction(): + dh = DesireHelper() + _arm_left(dh) + dh.update(FakeCarState(left=True, right=False, lever=2), True, 0.0) + dh.update(FakeCarState(right=True, lever=0), True, 0.0) + + assert dh.lane_change_state == LaneChangeState.off + + +def test_same_direction_hold_under_1s_during_pre_does_not_cancel(): + dh = DesireHelper() + _arm_left(dh) + _hold_lever(dh, 1, v_ego=30.0, t=0.90) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.lane_change_direction == LaneChangeDirection.left + assert dh.queued_changes == 1 + left, right = DesireHelper.lane_change_keep_blinker( + dh.lane_change_state, dh.lane_change_direction) + assert left and not right + + +def test_same_direction_hold_1s_during_pre_cancels_as_turn(): + dh = DesireHelper() + _arm_left(dh) + _hold_lever(dh, 1, v_ego=30.0, t=STALK_ALC_TURN_HOLD_S) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + assert dh.queued_changes == 0 + left, right = DesireHelper.lane_change_keep_blinker( + dh.lane_change_state, dh.lane_change_direction) + assert not left and not right + + +def test_same_direction_hold_1s_during_starting_cancels_as_turn(): + dh = DesireHelper() + _arm_left(dh) + dh.update(_nudge_left(), True, 1.0) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + _hold_lever(dh, 1, v_ego=30.0, t=STALK_ALC_TURN_HOLD_S) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.queued_changes == 0 + + +def test_same_direction_hold_under_1s_does_not_queue(): + """Past the tip window but under 1s is neither a queued tip nor a turn.""" + dh = DesireHelper() + _arm_left(dh) + dh.update(_nudge_left(), True, 1.0) + _hold_lever(dh, 1, v_ego=30.0, t=0.90) + dh.update(FakeCarState(left=True, lever=0), True, 1.0) + + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.queued_changes == 1 + + +def test_same_direction_tap_during_maneuver_queues_change(): + dh = DesireHelper() + _arm_left(dh) + dh.update(_nudge_left(), True, 0.0) + _lever_tap(dh, 1) + + assert dh.queued_changes == 2 + + +def test_held_lamp_without_lever_does_not_queue(): + dh = DesireHelper() + _arm_left(dh) + dh.update(_nudge_left(), True, 0.0) + _tick(dh, FakeCarState(left=True), n=20) + + assert dh.queued_changes == 1 + + +def test_lamp_edges_without_lever_do_not_queue(): + dh = DesireHelper() + _arm_left(dh) + for _ in range(3): + dh.update(FakeCarState(), True, 0.0) + dh.update(FakeCarState(left=True), True, 0.0) + + assert dh.queued_changes == 1 + + +def test_queue_capped_at_three(): + dh = DesireHelper() + _arm_left(dh) + for _ in range(5): + _lever_tap(dh, 1) + + assert dh.queued_changes == MAX_QUEUED_LANE_CHANGES == 3 + + +def test_queued_change_rearms_after_first_completes(): + dh = DesireHelper() + _arm_left(dh) + _lever_tap(dh, 1) + dh.update(_nudge_left(), True, 0.0) + _complete_maneuver(dh, FakeCarState(left=True)) + + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.lane_change_direction == LaneChangeDirection.left + assert dh.queued_changes == 1 + + +def test_single_change_resets_after_completion(): + dh = DesireHelper() + _arm_left(dh) + dh.update(_nudge_left(), True, 0.0) + _complete_maneuver(dh, FakeCarState()) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + assert dh.queued_changes == 0 + + +def test_queued_change_timeout_resets_everything(): + dh = DesireHelper() + _arm_left(dh) + _lever_tap(dh, 1) + dh.update(_nudge_left(), True, 0.0) + _complete_maneuver(dh, FakeCarState(left=True)) + _tick(dh, FakeCarState(left=True), n=int(LANE_CHANGE_ARM_TIME / DT_MDL) + 5) + + assert dh.lane_change_state == LaneChangeState.off + assert dh.lane_change_direction == LaneChangeDirection.none + assert dh.queued_changes == 0 diff --git a/selfdrive/controls/lib/tests/test_driver_lateral_handoff.py b/selfdrive/controls/lib/tests/test_driver_lateral_handoff.py new file mode 100644 index 00000000000000..2eef51632dedf6 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_driver_lateral_handoff.py @@ -0,0 +1,1375 @@ +from pathlib import Path + +from cereal import log +from opendbc.car.tesla.preap.carstate import HANDS_ON_DISENGAGE_LEVEL +from opendbc.car.tesla.values import STEER_THRESHOLD +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import ( + BlinkerLateralHold, + blinker_pauses_lateral, + lat_active_with_blinker_pause, +) +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + BLEND_TIME_S, + DISTURBANCE_CURVATURE_ERR, + EMERGENCY_DECEL_FRAMES, + EMERGENCY_DECEL_MPS2, + EMERGENCY_MIN_V_EGO, + HANDS_OFF_CONFIRM_S, + RELEASE_HOLD_S, + YIELD_FIRM_FRAMES, + YIELD_SOFT_NM, + YIELD_SOFT_S, + HANDS_ON_HOLD_LEVEL, + LAT_REENABLE_MIN_V_EGO, + LAT_REENABLE_MIN_V_EGO_MPH, + PARAM_DRIVER_LAT_HANDOFF, + PREAP_FINGERPRINT, + QUIET_WAIT_S, + RATE_INTENT_MIN_DEG_S, + RATE_SNA_ABS_DEG_S, + SMOOTHSTEP_MAX_SLOPE, + SOFT_YIELD_DEBOUNCE_FRAMES, + SOFT_YIELD_FAST_DEBOUNCE_FRAMES, + SOFT_YIELD_RELEASE_NM, + SOFT_YIELD_TRIGGER_NM, + STEER_RATE_QUIET_DEG_S, + TAPER_RATE_MAX_PER_S, + TESLA_MAX_ANGLE_RATE_DEG_PER_20MS, + UI_LATERAL_RETURN_AUTHORITY, + YIELD_AUTHORITY_TIME_S, + YIELD_EMERGENCY_WINDOW_S, + DriverLateralHandoff, + apply_lat_authority, + cs_hands_on_level, + cs_real_brake_pressed, + emergency_brake, + emergency_cancel_active, + handoff_enabled, + hands_still_on, + handoff_new_desired_curvature, + hud_engaged_status, + is_disturbance, + lat_active_after_handoff, + lat_reenable_inhibited, + pin_desired_curvature_to_measured, + required_press_frames, + smoothstep, + torque_rate_aligned, +) + + +State = log.SelfdriveState.OpenpilotState +DT = 0.01 +BELOW_REENABLE_MS = LAT_REENABLE_MIN_V_EGO - 0.05 +AT_REENABLE_MS = LAT_REENABLE_MIN_V_EGO +ABOVE_REENABLE_MS = LAT_REENABLE_MIN_V_EGO + 0.05 + + +def _new(): + return DriverLateralHandoff(enabled=True) + + +def _step(h, *, torque=0.0, rate=0.0, engaged=True, lat=True, alc=False, + blinker_paused=False, hands_on=0, tracking_error=0.0, + brake=False, a_ego=0.0, v_ego=15.0, dt=DT): + return h.update( + engaged=engaged, + lat_would_be_active=lat, + steering_torque=torque, + steering_rate_deg=rate, + alc_active=alc, + blinker_paused=blinker_paused, + hands_on_level=hands_on, + tracking_error=tracking_error, + brake_applied=brake, + a_ego=a_ego, + v_ego=v_ego, + dt=dt, + ) + + +def _yield(h, torque=1.0, rate=25.0, hands_on=1, blinker_paused=False, v_ego=15.0): + out = None + for _ in range(max(SOFT_YIELD_DEBOUNCE_FRAMES, required_press_frames(torque))): + out = _step(h, torque=torque, rate=rate, hands_on=hands_on, + blinker_paused=blinker_paused, v_ego=v_ego) + assert out is not None + assert out.yielded + assert out.authority == 0.0 + return out + + +def _hard_brake_frames(h, *, frames=EMERGENCY_DECEL_FRAMES, a_ego=None, + brake=True, v_ego=15.0, torque=0.15, rate=0.0, + hands_on=1): + if a_ego is None: + a_ego = EMERGENCY_DECEL_MPS2 + out = None + for _ in range(frames): + out = _step(h, torque=torque, rate=rate, hands_on=hands_on, + brake=brake, a_ego=a_ego, v_ego=v_ego) + return out + + +def _quiet(h, seconds): + return _step(h, torque=0.0, rate=0.0, hands_on=0, dt=seconds) + + +def _hands_off(h, *, torque=0.0, rate=0.0, blinker_paused=False, lat=True, v_ego=15.0): + """Quiet torque for RELEASE_HOLD_S — starts the take-back taper.""" + return _step(h, torque=torque, rate=rate, hands_on=0, dt=RELEASE_HOLD_S, + blinker_paused=blinker_paused, lat=lat, v_ego=v_ego) + + +def test_thresholds_are_derived_from_real_steering_pressed(): + assert STEER_THRESHOLD == 1 + assert HANDS_ON_DISENGAGE_LEVEL == 2 + assert SOFT_YIELD_TRIGGER_NM == 0.55 * float(STEER_THRESHOLD) + assert SOFT_YIELD_RELEASE_NM == 0.40 * float(STEER_THRESHOLD) + assert SOFT_YIELD_RELEASE_NM < SOFT_YIELD_TRIGGER_NM + assert SOFT_YIELD_DEBOUNCE_FRAMES == 9 + assert SOFT_YIELD_FAST_DEBOUNCE_FRAMES == 6 + assert SOFT_YIELD_FAST_DEBOUNCE_FRAMES < SOFT_YIELD_DEBOUNCE_FRAMES + assert SOFT_YIELD_FAST_DEBOUNCE_FRAMES > 5 # gravel spike bursts + assert required_press_frames(SOFT_YIELD_TRIGGER_NM) == SOFT_YIELD_DEBOUNCE_FRAMES + assert required_press_frames(0.85) == SOFT_YIELD_DEBOUNCE_FRAMES + assert required_press_frames(YIELD_SOFT_NM) == int(round(YIELD_SOFT_S / DT)) + assert required_press_frames(float(STEER_THRESHOLD)) == int(round(YIELD_SOFT_S / DT)) + assert required_press_frames(1.4) == YIELD_FIRM_FRAMES + assert 0.50 < SOFT_YIELD_TRIGGER_NM <= 0.55 + assert 8 <= SOFT_YIELD_DEBOUNCE_FRAMES <= 10 + assert PREAP_FINGERPRINT == "TESLA_MODEL_S_PREAP" + assert QUIET_WAIT_S == 0.0 + assert HANDS_ON_HOLD_LEVEL == 1 + assert HANDS_OFF_CONFIRM_S == 0.15 + assert HANDS_OFF_CONFIRM_S > 0.08 + assert HANDS_OFF_CONFIRM_S < 0.25 + assert BLEND_TIME_S == 1.0 + assert UI_LATERAL_RETURN_AUTHORITY == 0.70 + assert YIELD_AUTHORITY_TIME_S == 0.0 + assert TESLA_MAX_ANGLE_RATE_DEG_PER_20MS == 5.0 + assert PARAM_DRIVER_LAT_HANDOFF == "NAPDriverLatHandoff" + assert STEER_RATE_QUIET_DEG_S == 25.0 + assert RATE_INTENT_MIN_DEG_S == 10.0 + assert RATE_SNA_ABS_DEG_S == 400.0 + assert DISTURBANCE_CURVATURE_ERR == 0.0025 + assert EMERGENCY_DECEL_MPS2 == -3.5 + assert EMERGENCY_DECEL_FRAMES == 8 + assert EMERGENCY_MIN_V_EGO == 1.0 + assert YIELD_EMERGENCY_WINDOW_S == 2.0 + assert LAT_REENABLE_MIN_V_EGO_MPH == 10.0 + assert abs(LAT_REENABLE_MIN_V_EGO - 10.0 * CV.MPH_TO_MS) < 1e-9 + assert lat_reenable_inhibited(blinker_paused=False, v_ego=BELOW_REENABLE_MS) + assert lat_reenable_inhibited(blinker_paused=False, v_ego=LAT_REENABLE_MIN_V_EGO - 1e-6) + assert not lat_reenable_inhibited(blinker_paused=False, v_ego=AT_REENABLE_MS) + assert not lat_reenable_inhibited(blinker_paused=False, v_ego=ABOVE_REENABLE_MS) + assert lat_reenable_inhibited(blinker_paused=True, v_ego=ABOVE_REENABLE_MS) + assert lat_reenable_inhibited(blinker_paused=True, v_ego=BELOW_REENABLE_MS) + assert torque_rate_aligned(SOFT_YIELD_TRIGGER_NM, 10.0) + assert not torque_rate_aligned(SOFT_YIELD_TRIGGER_NM, -10.0) + assert not torque_rate_aligned(SOFT_YIELD_TRIGGER_NM, 4095.0) + assert not lat_active_after_handoff(True, True) + assert lat_active_after_handoff(True, False) + assert not lat_active_after_handoff(False, True) + assert not lat_active_after_handoff(False, False) + assert not emergency_brake( + brake_applied=True, a_ego=-1.0, v_ego=15.0, decel_frames=20) + assert emergency_brake( + brake_applied=True, a_ego=-3.5, v_ego=15.0, + decel_frames=EMERGENCY_DECEL_FRAMES) + assert not emergency_cancel_active( + yielded=False, blending=False, yield_age_s=None, hard_brake=True) + + +def test_param_defaults_on_and_toggle_off_disables(): + """Default On; Settings Off must be identity (stock lat).""" + h = DriverLateralHandoff() + assert h.enabled + assert handoff_enabled(fingerprint=PREAP_FINGERPRINT, param_on=True) + assert not handoff_enabled(fingerprint=PREAP_FINGERPRINT, param_on=False) + assert not handoff_enabled(fingerprint="TESLA_MODEL_3", param_on=True) + root = Path(__file__).resolve().parents[4] + keys = (root / "common/params_keys.h").read_text() + line = next(ln for ln in keys.splitlines() if '"NAPDriverLatHandoff"' in ln) + assert "BOOL" in line and '"1"' in line + cs = (root / "selfdrive/controls/controlsd.py").read_text() + assert "PARAM_DRIVER_LAT_HANDOFF" in cs + h_off = DriverLateralHandoff(enabled=False) + for _ in range(SOFT_YIELD_DEBOUNCE_FRAMES + 5): + out = _step(h_off, torque=1.5, rate=80.0) + assert out.authority == 1.0 + assert not out.yielded + assert not out.ui_paused + + +def test_light_input_yields_lateral_keeps_long_session(): + """Yield frees the EPS; long / session stay up (not a hard cancel).""" + h = _new() + enabled = True + long_override = False + op_long = True + out = _yield(h) + long_active = enabled and not long_override and op_long + assert long_active + assert enabled + assert out.yielded + assert out.authority == 0.0 + assert out.ui_paused + assert not out.emergency_cancel + assert not lat_active_after_handoff(True, out.yielded) + + +def test_below_threshold_road_noise_does_not_yield(): + h = _new() + for _ in range(200): + out = _step(h, torque=0.4, rate=8.0) + assert not out.yielded + assert out.authority == 1.0 + assert not out.ui_paused + + +def test_just_below_trigger_does_not_yield(): + h = _new() + for _ in range(100): + out = _step(h, torque=SOFT_YIELD_TRIGGER_NM - 0.01, rate=40.0, hands_on=1) + assert not out.yielded + assert out.authority == 1.0 + + +def test_short_spike_is_debounced(): + h = _new() + needed = required_press_frames(1.2) + for _ in range(needed - 1): + out = _step(h, torque=1.2, rate=30.0, hands_on=1) + assert not out.yielded + out = _step(h, torque=0.0) + assert not out.yielded + assert out.authority == 1.0 + + +def test_gravel_spike_train_does_not_yield(): + """Rumble: brief 1.2 Nm hits with gaps must not accumulate to a yield.""" + h = _new() + out = None + for _ in range(40): + for _ in range(5): + out = _step(h, torque=1.2) + for _ in range(5): + out = _step(h, torque=0.15) + assert not out.yielded + assert out.authority == 1.0 + + +def test_rumble_at_half_nm_with_hands_resting_does_not_yield(): + """#71 0.50 / 80 ms rumble: hands off, or ~0.50 Nm with hands, no yield.""" + h = _new() + for _ in range(int(1.5 / DT)): + out = _step(h, torque=0.50, rate=20.0, hands_on=0) + assert not out.yielded + assert out.authority == 1.0 + h = _new() + for _ in range(int(1.5 / DT)): + out = _step(h, torque=0.50, rate=20.0, hands_on=1) + assert not out.yielded + assert out.authority == 1.0 + + +def test_gentle_055_for_90ms_yields(): + """0.55 Nm is resting-band noise now. 0.9 Nm for 150 ms yields, hands or not.""" + h = _new() + out = None + for _ in range(int(1.0 / DT)): + out = _step(h, torque=0.55, rate=0.0, hands_on=1) + assert not out.yielded + h = _new() + for _ in range(int(round(YIELD_SOFT_S / DT)) - 1): + out = _step(h, torque=YIELD_SOFT_NM, rate=0.0, hands_on=0) + assert not out.yielded + out = _step(h, torque=YIELD_SOFT_NM, rate=0.0, hands_on=0) + assert out.yielded + assert out.authority == 0.0 + assert not lat_active_after_handoff(True, out.yielded) + + +def test_sustained_driver_input_keeps_authority_at_zero(): + h = _new() + _yield(h) + for _ in range(int(2.0 / DT)): + out = _step(h, torque=1.0, rate=40.0) + assert out.authority == 0.0 + assert out.yielded + assert not out.blending + + +def test_yielded_hands_on_stays_yielded_through_torsion_dip(): + """Hands on the rim do not hold the yield. Torque above the release band does.""" + h = _new() + _yield(h) + out = None + for _ in range(int(0.50 / DT)): + out = _step(h, torque=1.0, rate=40.0, hands_on=1) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + # Resting torque gives lateral back even with a hand still on the rim. + out = _step(h, torque=0.15, rate=0.0, hands_on=1, dt=RELEASE_HOLD_S) + assert out.blending + assert not out.yielded + assert hands_still_on(1) + assert not hands_still_on(0) + + +def test_hands_off_confirm_starts_blend_after_confirm(): + """Quiet torque for RELEASE_HOLD_S starts the taper. A shorter gap does not.""" + h = _new() + _yield(h) + out = _step(h, torque=0.35, hands_on=0, dt=0.20) + assert out.yielded + assert not out.blending + out = _step(h, torque=0.35, hands_on=0, dt=RELEASE_HOLD_S - 0.20) + assert out.blending + assert not out.yielded + assert out.authority == 0.0 + + +def test_hands_back_on_during_confirm_resets_delay(): + """A hand on the rim does not reset give-back. Torque above 0.40 Nm does.""" + h = _new() + _yield(h) + out = _step(h, torque=0.20, hands_on=1, dt=0.20) + assert out.yielded and not out.blending + out = _step(h, torque=1.0, hands_on=0) + assert out.yielded and not out.blending and out.authority == 0.0 + out = _step(h, torque=0.20, hands_on=0, dt=0.20) + assert out.yielded and not out.blending + out = _step(h, torque=0.20, hands_on=0, dt=RELEASE_HOLD_S) + assert out.blending and not out.yielded + + +def test_hands_back_on_mid_blend_reyields(): + h = _new() + _yield(h) + out = _hands_off(h) + assert out.blending + for _ in range(20): + out = _quiet(h, DT) + assert out.blending + assert 0.0 < out.authority < 1.0 + # A light hand does not cancel the taper. + out = _step(h, torque=0.2, hands_on=1) + assert out.blending and not out.yielded + for _ in range(16): + out = _step(h, torque=1.5, hands_on=1) + assert out.yielded and not out.blending and out.authority == 0.0 + assert out.ui_paused + out = _hands_off(h, torque=0.2) + assert out.blending and not out.yielded and out.authority == 0.0 + + +def test_yielded_rate_above_old_gate_does_not_block_resume(): + """Caster / road rate after hands-off must not keep the yielded latch.""" + h = _new() + _yield(h) + out = _hands_off(h, torque=0.05, rate=STEER_RATE_QUIET_DEG_S + 55.0) + assert not out.yielded + assert out.blending + assert out.authority == 0.0 + + +def test_yield_then_hands_off_authority_blends_to_one(): + """Yield → hands off ~0.15 s → 1 s smoothstep to 1.0.""" + h = _new() + _yield(h) + out = _hands_off(h, rate=40.0) + assert out.blending + assert not out.yielded + assert out.authority == 0.0 + for _ in range(int(BLEND_TIME_S / DT)): + out = _step(h, torque=0.0, rate=40.0, hands_on=0) + assert out.authority == 1.0 + assert not out.blending + assert not out.yielded + assert not out.ui_paused + + +def test_blend_is_smoothstep_monotonic_one_second_bounded_slope(): + """Take-back is monotonic and finishes inside BLEND_TIME_S. + + The first GRACE_DELAY_S stays at 0 so the inference grace can arm. + After that the rise is the curvature taper, not the old smoothstep. + """ + h = _new() + _yield(h) + _hands_off(h) + prev = 0.0 + max_delta = 0.0 + for _ in range(int(BLEND_TIME_S / DT) + 2): + out = _quiet(h, DT) + assert out.authority + 1e-9 >= prev + max_delta = max(max_delta, out.authority - prev) + prev = out.authority + assert out.authority == 1.0 + assert not out.blending + assert not out.yielded + assert max_delta <= (TAPER_RATE_MAX_PER_S / 0.9) * DT + 1e-6 + + +def test_renewed_input_during_blend_yields_and_retries_after_hands_off(): + h = _new() + _yield(h) + out = _hands_off(h) + assert out.blending + for _ in range(20): + out = _quiet(h, DT) + assert out.blending + assert 0.0 < out.authority < 1.0 + # One frame at 1 Nm is not a deliberate push. + out = _step(h, torque=1.0) + assert out.blending and not out.yielded + for _ in range(16): + out = _step(h, torque=1.5) + assert out.yielded and not out.blending and out.authority == 0.0 + assert out.ui_paused + out = _hands_off(h) + assert out.blending and not out.yielded and out.authority == 0.0 + + +def test_mid_band_during_blend_does_not_reyield(): + """Torque in the old 0.4–0.55 band does not cancel the taper.""" + h = _new() + _yield(h) + out = _hands_off(h) + assert out.blending + mid = 0.5 * (SOFT_YIELD_RELEASE_NM + SOFT_YIELD_TRIGGER_NM) + for _ in range(20): + out = _step(h, torque=mid) + assert out.blending + assert not out.yielded + out = _step(h, torque=SOFT_YIELD_TRIGGER_NM) + assert out.blending + assert not out.yielded + + +def test_ui_paused_below_70_returns_at_70_without_chatter(): + h = _new() + _yield(h) + _hands_off(h) + seen_unpaused = False + for _ in range(int(BLEND_TIME_S / DT)): + out = _quiet(h, DT) + if out.authority < UI_LATERAL_RETURN_AUTHORITY: + assert out.ui_paused + assert not seen_unpaused + else: + assert not out.ui_paused + seen_unpaused = True + break + assert seen_unpaused + # A deliberate push during the remaining blend pauses the UI again. + for _ in range(16): + out = _step(h, torque=1.5) + assert out.ui_paused + assert out.authority == 0.0 + status = hud_engaged_status( + enabled=True, op_state=State.enabled, lat_active=True, lat_handoff_paused=True) + assert status == "override" + status = hud_engaged_status( + enabled=True, op_state=State.enabled, lat_active=True, lat_handoff_paused=False) + assert status == "engaged" + + +def test_ui_does_not_claim_lat_back_at_69_percent(): + assert hud_engaged_status( + enabled=True, op_state=State.enabled, lat_active=True, lat_handoff_paused=True, + ) == "override" + # 69% is still paused (latched threshold 70%) + h = _new() + _yield(h) + _hands_off(h) + out = None + while True: + out = _quiet(h, DT) + if out.authority >= 0.69: + break + # walk until just below 0.70 + while out.authority < UI_LATERAL_RETURN_AUTHORITY - 1e-9: + assert out.ui_paused + prev = out.authority + out = _quiet(h, DT) + if out.authority == prev: + break + if out.authority < UI_LATERAL_RETURN_AUTHORITY: + assert out.ui_paused + + +def test_hud_gas_override_still_green_when_lat_active_and_not_handoff(): + assert hud_engaged_status( + enabled=True, op_state=State.overriding, lat_active=True, lat_handoff_paused=False, + ) == "engaged" + assert hud_engaged_status( + enabled=True, op_state=State.overriding, lat_active=True, lat_handoff_paused=True, + ) == "override" + assert hud_engaged_status( + enabled=False, op_state=State.disabled, lat_active=False, lat_handoff_paused=False, + ) == "disengaged" + + +def test_blinker_and_alc_paths_unchanged_and_do_not_arm_from_handoff(): + assert blinker_pauses_lateral(True, False) + hold = BlinkerLateralHold() + lat = lat_active_with_blinker_pause( + active=True, steer_fault_temporary=False, steer_fault_permanent=False, + standstill=False, steer_at_standstill=False, + left_blinker=True, right_blinker=False, hold=hold, engaged=True, + ) + assert not lat + hold_on = BlinkerLateralHold() + lat_soft = lat_active_with_blinker_pause( + active=True, steer_fault_temporary=False, steer_fault_permanent=False, + standstill=False, steer_at_standstill=False, + left_blinker=True, right_blinker=False, hold=hold_on, engaged=True, + soft_lat_on=True, + ) + assert lat_soft + assert hold_on.turn_active + h = _new() + out = _step(h, torque=0.8, lat=False, blinker_paused=True) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + + h = _new() + for _ in range(SOFT_YIELD_DEBOUNCE_FRAMES + 1): + out = _step(h, torque=0.8, alc=True) + assert not out.yielded + assert out.authority == 1.0 + + +def test_soft_lat_blinker_on_does_not_strip_lat(): + """Blinker rise alone must not clear lat / force EPS free.""" + h = _new() + out = _step(h, torque=0.2, lat=True, blinker_paused=True) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + assert lat_active_after_handoff(True, out.yielded) + for _ in range(int(1.0 / DT)): + out = _step(h, torque=0.2, lat=True, blinker_paused=True) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + + +def test_soft_lat_may_still_yield_while_driver_turn_blinker_on(): + h = _new() + _step(h, torque=0.2, lat=True, blinker_paused=True) + out = _yield(h, blinker_paused=True) + assert out.yielded + assert not lat_active_after_handoff(True, out.yielded) + # Blinker still on: stay yielded (do not start take-back). + out = _hands_off(h, torque=0.0, blinker_paused=True) + assert out.yielded + assert not out.blending + + +def test_soft_lat_blinker_on_blocks_reenable_and_aborts_blend(): + """Yielded or blending + driver-turn blinker → stay yielded.""" + h = _new() + _yield(h) + out = _hands_off(h) + assert out.blending + assert not out.yielded + out = _step(h, torque=0.0, lat=True, blinker_paused=True, hands_on=0) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + for _ in range(int((HANDS_OFF_CONFIRM_S + BLEND_TIME_S) / DT) + 5): + out = _step(h, torque=0.0, lat=True, blinker_paused=True, hands_on=0) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + + +def test_soft_lat_blinker_clear_lands_in_yield_then_normal_resume(): + """After blinker clear: enter yield, then 0.15 s confirm + 1 s blend. + + No dedicated blinker rising-edge blend. Keep-control through the + blinker (never yielded) must not be stripped on the falling edge. + """ + h = _new() + _yield(h) + for _ in range(20): + out = _step(h, torque=0.2, lat=True, blinker_paused=True, hands_on=1) + assert out.yielded + assert not out.blending + # Falling edge, hands still on: stay yielded (not an immediate blend). + out = _step(h, torque=0.2, lat=True, blinker_paused=False, hands_on=1) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + assert not lat_active_after_handoff(True, out.yielded) + # Hands off for the confirm — not a 1 s blinker shortcut this frame. + out = _step(h, torque=0.0, lat=True, blinker_paused=False, hands_on=0, + dt=HANDS_OFF_CONFIRM_S - DT) + assert out.yielded + assert not out.blending + out = _hands_off(h) + assert out.blending + assert not out.yielded + assert out.authority == 0.0 + for _ in range(int(BLEND_TIME_S / DT)): + out = _step(h, torque=0.0) + assert out.authority == 1.0 + assert not out.blending + assert not out.ui_paused + + # Never yielded: blinker on then off keeps control. + h = _new() + for _ in range(20): + out = _step(h, torque=0.2, lat=True, blinker_paused=True) + assert out.authority == 1.0 + assert not out.yielded + out = _step(h, torque=0.2, lat=True, blinker_paused=False) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + + +def test_soft_lat_below_10_mph_does_not_strip_lat(): + """Speed inhibit is re-enable only — keep control if we still have it.""" + h = _new() + out = _step(h, torque=0.2, lat=True, v_ego=BELOW_REENABLE_MS) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + assert lat_active_after_handoff(True, out.yielded) + for _ in range(int(1.0 / DT)): + out = _step(h, torque=0.2, lat=True, v_ego=BELOW_REENABLE_MS) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + # Crossing 10 without ever yielding keeps control. + out = _step(h, torque=0.2, lat=True, v_ego=ABOVE_REENABLE_MS) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + + +def test_soft_lat_may_still_yield_below_10_mph(): + h = _new() + _step(h, torque=0.2, lat=True, v_ego=BELOW_REENABLE_MS) + out = _yield(h, v_ego=BELOW_REENABLE_MS) + assert out.yielded + assert not lat_active_after_handoff(True, out.yielded) + out = _hands_off(h, torque=0.0, v_ego=BELOW_REENABLE_MS) + assert out.yielded + assert not out.blending + + +def test_soft_lat_below_10_mph_blocks_reenable_and_aborts_blend(): + """Yielded or blending + v_ego < 10 mph → stay yielded (same as blinker).""" + h = _new() + _yield(h) + out = _hands_off(h) + assert out.blending + assert not out.yielded + out = _step(h, torque=0.0, lat=True, hands_on=0, v_ego=BELOW_REENABLE_MS) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + for _ in range(int((HANDS_OFF_CONFIRM_S + BLEND_TIME_S) / DT) + 5): + out = _step(h, torque=0.0, lat=True, hands_on=0, v_ego=BELOW_REENABLE_MS) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + # At exactly 10 mph the gate is off (strictly below). + out = _step(h, torque=0.0, lat=True, hands_on=0, v_ego=AT_REENABLE_MS, + dt=RELEASE_HOLD_S) + assert out.blending + assert not out.yielded + + +def test_soft_lat_cross_10_mph_lands_in_yield_then_normal_resume(): + """After speed crosses 10 mph: enter yield, then 0.15 s confirm + 1 s blend.""" + h = _new() + _yield(h, v_ego=BELOW_REENABLE_MS) + for _ in range(20): + out = _step(h, torque=0.2, lat=True, hands_on=1, v_ego=BELOW_REENABLE_MS) + assert out.yielded + assert not out.blending + out = _step(h, torque=0.2, lat=True, hands_on=1, v_ego=ABOVE_REENABLE_MS) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + assert not lat_active_after_handoff(True, out.yielded) + out = _step(h, torque=0.0, lat=True, hands_on=0, v_ego=ABOVE_REENABLE_MS, + dt=HANDS_OFF_CONFIRM_S - DT) + assert out.yielded + assert not out.blending + out = _hands_off(h, v_ego=ABOVE_REENABLE_MS) + assert out.blending + assert not out.yielded + assert out.authority == 0.0 + for _ in range(int(BLEND_TIME_S / DT)): + out = _step(h, torque=0.0, v_ego=ABOVE_REENABLE_MS) + assert out.authority == 1.0 + assert not out.blending + assert not out.ui_paused + + +def test_soft_lat_blinker_on_still_blocks_reenable_above_10_mph(): + """Blinker-on still inhibits take-back at highway speed.""" + h = _new() + _yield(h, blinker_paused=True, v_ego=ABOVE_REENABLE_MS) + out = _hands_off(h, blinker_paused=True, v_ego=ABOVE_REENABLE_MS) + assert out.yielded + assert not out.blending + for _ in range(int((HANDS_OFF_CONFIRM_S + BLEND_TIME_S) / DT) + 5): + out = _step(h, torque=0.0, lat=True, blinker_paused=True, hands_on=0, + v_ego=ABOVE_REENABLE_MS) + assert out.yielded + assert not out.blending + + +def test_soft_lat_above_10_mph_blinker_off_resume_unchanged(): + """Above 10 mph, blinker off: prior yield → hands-off → 1 s blend.""" + h = _new() + _yield(h, v_ego=ABOVE_REENABLE_MS) + out = _hands_off(h, v_ego=ABOVE_REENABLE_MS) + assert out.blending + assert not out.yielded + for _ in range(int(BLEND_TIME_S / DT)): + out = _step(h, torque=0.0, v_ego=ABOVE_REENABLE_MS) + assert out.authority == 1.0 + assert not out.blending + assert not out.ui_paused + + +def test_standstill_lat_down_below_10_mph_does_not_snap_lat_back(): + """Lat-down while creeping: remember speed inhibit, land in yield.""" + h = _new() + for _ in range(int(1.5 / DT)): + out = _step(h, torque=0.2, lat=False, v_ego=0.0) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + out = _step(h, torque=0.2, lat=True, v_ego=BELOW_REENABLE_MS) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + assert not lat_active_after_handoff(True, out.yielded) + + # Highway-speed fault lat-down without blinker still snaps back (not this gate). + h = _new() + for _ in range(20): + _step(h, torque=0.0, lat=False, v_ego=ABOVE_REENABLE_MS) + out = _step(h, torque=0.0, lat=True, v_ego=ABOVE_REENABLE_MS) + assert not out.blending + assert not out.yielded + assert out.authority == 1.0 + + +def test_alc_active_still_resets_handoff_below_10_mph(): + """ALC is not the speed/blinker inhibit path.""" + h = _new() + _yield(h, v_ego=BELOW_REENABLE_MS) + out = _step(h, torque=0.8, alc=True, v_ego=BELOW_REENABLE_MS) + assert not out.yielded + assert out.authority == 1.0 + assert not out.blending + + +def test_blinker_pause_lat_down_resume_enters_yield_not_immediate_blend(): + """Standstill/fault lat-down during a driver-turn: do not 1 s-blend back. + + Soft-lat On no longer uses lamp latch as lat-down. If lat *is* down + (standstill) while the turn is latched, remember it and land in yield + when lat returns — then the normal 0.15 s confirm + 1 s blend. + Standstill-style lat-down without blinker_paused does not yield/blend. + """ + h = _new() + for _ in range(int(1.5 / DT)): + out = _step(h, torque=0.2, lat=False, blinker_paused=True) + assert out.authority == 1.0 + assert not out.yielded + assert not out.blending + out = _step(h, torque=0.2, lat=True, blinker_paused=False) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + assert out.ui_paused + out = _hands_off(h, torque=0.0) + assert out.blending + assert not out.yielded + for _ in range(int(BLEND_TIME_S / DT)): + out = _step(h, torque=0.0) + assert out.authority == 1.0 + assert not out.blending + assert not out.ui_paused + + h = _new() + for _ in range(20): + _step(h, torque=0.0, lat=False, blinker_paused=False) + out = _step(h, torque=0.0, lat=True) + assert not out.blending + assert not out.yielded + assert out.authority == 1.0 + + +def test_engage_from_disabled_does_not_start_blinker_reentry_blend(): + h = _new() + _step(h, engaged=False, lat=False) + out = _step(h, engaged=True, lat=True) + assert not out.blending + assert out.authority == 1.0 + + +def test_stalk_cancel_or_fault_resets_to_full_disengage_contract(): + h = _new() + _yield(h) + out = _step(h, torque=0.8, engaged=False) + assert out.authority == 1.0 + assert not out.yielded + assert not out.ui_paused + # enabled session is gone; HUD is disengaged, not a lat-pause + assert hud_engaged_status( + enabled=False, op_state=State.disabled, lat_active=False, lat_handoff_paused=False, + ) == "disengaged" + + +def test_apply_lat_authority_follows_driver_at_zero_and_nap_at_one(): + torque, angle, curv = apply_lat_authority(0.0, 0.4, 12.0, 3.0, 0.02, 0.001) + assert torque == 0.0 + assert angle == 3.0 + assert curv == 0.001 + torque, angle, curv = apply_lat_authority(1.0, 0.4, 12.0, 3.0, 0.02, 0.001) + assert torque == 0.4 + assert angle == 12.0 + assert curv == 0.02 + torque, angle, curv = apply_lat_authority(0.5, 0.4, 10.0, 0.0, 0.02, 0.0) + assert abs(torque - 0.2) < 1e-9 + assert abs(angle - 5.0) < 1e-9 + + +def _angle_from_curv(curv): + """Linear stand-in for VM.get_steer_from_curvature (sign-preserving).""" + return float(curv) * 800.0 + + +def _clip_toward(prev, target, step=0.0002): + """Stand-in for clip_curvature (jerk-limited slew from the pin).""" + if target > prev: + return min(prev + step, target) + return max(prev - step, target) + + +def _step_actuators(h, *, torque, desired, model_curv, meas_curv, meas_angle, + v_ego=20.0, hands_on=0, rate=0.0, dt=DT): + """Mirror controlsd: free EPS while yielded; clip + blend on resume.""" + _ = v_ego + out = _step(h, torque=torque, rate=rate, hands_on=hands_on, dt=dt) + lat_active = lat_active_after_handoff(True, out.yielded) + new_desired = handoff_new_desired_curvature( + yielded=out.yielded, lat_active=lat_active, + model_curvature=model_curv, measured_curvature=meas_curv, + ) + if pin_desired_curvature_to_measured(out.yielded, lat_active=lat_active): + desired = meas_curv + else: + desired = _clip_toward(desired, new_desired) + lac_angle = _angle_from_curv(desired) + if lat_active and out.authority < 1.0: + _t, angle, curv = apply_lat_authority( + out.authority, 0.4, lac_angle, meas_angle, desired, meas_curv) + elif not lat_active: + # EPS released: command unused; VM snaps to measured (blinker path). + angle, curv = meas_angle, meas_curv + else: + angle, curv = lac_angle, desired + return out, desired, angle, curv + + +def test_yield_pins_planner_resume_tracks_model_not_measured(): + """Resume must clip from the wheel, not a model that ran ahead. + + Yield now clears latActive (EPS free). Pin desired to measured while + lat is down. Blend/resume clip from that pin. At authority=1 the + command equals LaC(desired), slewing from measured toward the model. + """ + h = _new() + model_curv = 0.012 + meas_curv = 0.0 + meas_angle = _angle_from_curv(meas_curv) + desired = model_curv # was tracking the path before the push + + assert handoff_new_desired_curvature( + yielded=False, lat_active=True, + model_curvature=model_curv, measured_curvature=meas_curv, + ) == model_curv + assert handoff_new_desired_curvature( + yielded=True, lat_active=True, + model_curvature=model_curv, measured_curvature=meas_curv, + ) == meas_curv + assert pin_desired_curvature_to_measured(True) + assert not pin_desired_curvature_to_measured(False) + assert pin_desired_curvature_to_measured(False, lat_active=False) + assert not pin_desired_curvature_to_measured(False, lat_active=True) + + for _ in range(required_press_frames(1.0)): + out, desired, angle, curv = _step_actuators( + h, torque=1.0, rate=25.0, hands_on=1, desired=desired, + model_curv=model_curv, meas_curv=meas_curv, meas_angle=meas_angle) + assert out.yielded + assert desired == meas_curv + assert angle == meas_angle + assert curv == meas_curv + + # Above the release band: pin stays. Hands level is not what holds it. + out, desired, angle, curv = _step_actuators( + h, torque=0.5, desired=desired, model_curv=model_curv, + meas_curv=meas_curv, meas_angle=meas_angle, hands_on=1) + assert out.yielded + assert desired == meas_curv + assert angle == meas_angle + + # Quiet torque for the release hold: blend starts, pin lifts. + out, desired, angle, curv = _step_actuators( + h, torque=0.0, desired=desired, model_curv=model_curv, + meas_curv=meas_curv, meas_angle=meas_angle, dt=RELEASE_HOLD_S) + assert out.authority == 0.0 + assert out.blending + assert not out.yielded + assert not pin_desired_curvature_to_measured(out.yielded) + assert handoff_new_desired_curvature( + yielded=out.yielded, lat_active=True, + model_curvature=model_curv, measured_curvature=meas_curv, + ) == model_curv + + for _ in range(int(BLEND_TIME_S / DT)): + out, desired, angle, curv = _step_actuators( + h, torque=0.0, desired=desired, model_curv=model_curv, + meas_curv=meas_curv, meas_angle=meas_angle) + + assert out.authority == 1.0 + assert not out.blending + assert not out.yielded + assert not out.ui_paused + # identity on the planner/LaC target — not the yield-time measured hold + assert abs(curv - desired) < 1e-12 + assert abs(angle - _angle_from_curv(desired)) < 1e-12 + assert abs(desired - meas_curv) > 1e-4 + assert abs(desired - model_curv) < abs(meas_curv - model_curv) + assert abs(angle - meas_angle) > 1e-3 + # controlsd must pin + skip blend at 100% + cs = (Path(__file__).resolve().parents[4] / "selfdrive/controls/controlsd.py").read_text() + assert "pin_desired_curvature_to_measured" in cs + assert "handoff_new_desired_curvature" in cs + assert "lat_active_after_handoff" in cs + assert "authority < 1.0" in cs + assert "CC.latActive" in cs + assert "cs_hands_on_level" in cs + assert "hands_on_level" in cs + assert "cs_real_brake_pressed" in cs + assert "tracking_error" in cs + assert "emergency_cancel" in cs + + +def test_unyielded_lat_inactive_still_uses_measured_curvature(): + """Blinker / standstill path: latActive false → measured, snap-pin.""" + assert handoff_new_desired_curvature( + yielded=False, lat_active=False, + model_curvature=0.02, measured_curvature=0.001, + ) == 0.001 + assert pin_desired_curvature_to_measured(False, lat_active=False) + + +def test_blinker_resume_pins_then_blends_from_wheel_not_model(): + """Lot turn: model points at grass; resume must not command that instantly. + + Soft-lat On keeps lat during the blinker unless yielded. After a + yielded turn, falling blinker lands in yield (pin), then the normal + confirm + 1 s blend from the wheel — not a grass-pointing snap. + """ + h = _new() + model_curv = 0.02 # "into the grass" + meas_curv = 0.001 + meas_angle = _angle_from_curv(meas_curv) + desired = 0.015 # lagged planner from the turn + + _yield(h, blinker_paused=True) + for _ in range(10): + out = _step(h, torque=0.2, lat=True, blinker_paused=True, hands_on=1) + assert out.yielded + assert pin_desired_curvature_to_measured(out.yielded, lat_active=False) + desired = meas_curv # controlsd snap-pin while lat down + + out = _step(h, torque=0.0, lat=True, blinker_paused=False, hands_on=0) + assert out.yielded + assert not out.blending + assert pin_desired_curvature_to_measured(out.yielded, lat_active=False) + out = _hands_off(h) + assert out.blending + assert out.authority == 0.0 + assert not pin_desired_curvature_to_measured(out.yielded, lat_active=True) + new_desired = handoff_new_desired_curvature( + yielded=out.yielded, lat_active=True, + model_curvature=model_curv, measured_curvature=meas_curv, + ) + assert new_desired == model_curv + desired = _clip_toward(desired, new_desired) + _t, angle, curv = apply_lat_authority( + out.authority, 0.4, _angle_from_curv(desired), meas_angle, desired, meas_curv) + # authority 0: command the wheel, not the grass-pointing model + assert angle == meas_angle + assert curv == meas_curv + assert abs(desired - meas_curv) < abs(model_curv - meas_curv) + cs = (Path(__file__).resolve().parents[4] / "selfdrive/controls/controlsd.py").read_text() + assert "blinker_paused" in cs + assert "blinker_lat_hold.turn_active" in cs + assert "soft_lat_on" in cs + ho = (Path(__file__).resolve().parents[4] / "selfdrive/controls/lib/driver_lateral_handoff.py").read_text() + assert "lat_reenable_inhibited" in ho + assert "LAT_REENABLE_MIN_V_EGO" in ho + assert "inhibited = lat_reenable_inhibited" in ho + + +def test_disabled_for_non_preap_is_identity(): + h = DriverLateralHandoff(enabled=False) + for _ in range(50): + out = _step(h, torque=1.5) + assert out.authority == 1.0 + assert not out.ui_paused + + +def test_blinker_resume_with_hands_on_yields_instead_of_blend(): + """After a yielded turn, blinker falling while still on the rim stays yielded.""" + h = _new() + _yield(h, blinker_paused=True) + for _ in range(10): + _step(h, torque=0.2, lat=True, blinker_paused=True, hands_on=1) + out = _step(h, torque=0.2, lat=True, blinker_paused=False, hands_on=1) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + assert not lat_active_after_handoff(True, out.yielded) + out = _hands_off(h, torque=0.2) + assert out.blending + assert not out.yielded + assert lat_active_after_handoff(True, out.yielded) + + +def test_yield_frees_eps_like_blinker_pause(): + """Yield must drop latActive — not follow-measured with lat still on. + + Pre-AP carcontroller sends DAS_steeringControlType=0 when latActive + is false (same as blinker pause). Follow-measured with latActive true + is closed-loop hold — the wrestling Justin felt after #79 "yielded." + """ + h = _new() + out = _yield(h, torque=1.0, rate=0.0, hands_on=1) + assert out.yielded + assert not lat_active_after_handoff(True, out.yielded) + # Blinker pause is a separate lat-down path; do not steal it. + h = _new() + out = _step(h, torque=0.8, lat=False, blinker_paused=True) + assert out.authority == 1.0 + assert not out.yielded + assert not lat_active_after_handoff(False, out.yielded) + cs = (Path(__file__).resolve().parents[4] / "selfdrive/controls/controlsd.py").read_text() + assert "lat_active_after_handoff" in cs + tesla_cc = (Path(__file__).resolve().parents[4] / + "opendbc_repo/opendbc/car/tesla/carcontroller.py").read_text() + assert "lat_active = CC.latActive" in tesla_cc + assert "create_steering_control" in tesla_cc + tesla_can = (Path(__file__).resolve().parents[4] / + "opendbc_repo/opendbc/car/tesla/teslacan_legacy.py").read_text() + assert "DAS_steeringControlType" in tesla_can + assert "1 if enabled else 0" in tesla_can + + +def test_cs_hands_on_level_reads_cereal_and_eps_stash(): + class _CS: + pass + + cs = _CS() + cs.handsOnLevel = 1 + cs.steeringTorqueEps = 0.0 + cs.steeringDisengage = False + assert cs_hands_on_level(cs) == 1 + cs = _CS() + cs.steeringTorqueEps = 1.0 + cs.steeringDisengage = False + assert cs_hands_on_level(cs) == 1 + cs = _CS() + cs.steeringDisengage = True + assert cs_hands_on_level(cs) == 2 + cs = _CS() + assert cs_hands_on_level(cs) == 0 + pause = (Path(__file__).resolve().parents[4] / + "selfdrive/car/tesla/preap_blinker_lat_pause.py").read_text() + assert "_publish_hands_on_level" in pause + assert "steeringTorqueEps" in pause + + +def test_hysteresis_band_does_not_retrigger_from_texture_after_release(): + h = _new() + _yield(h) + _hands_off(h) + for _ in range(int(BLEND_TIME_S / DT)): + _quiet(h, DT) + # back at full authority; 0.4 Nm is between release and trigger + for _ in range(100): + out = _step(h, torque=0.4) + assert not out.yielded + assert out.authority == 1.0 + + +def test_intentional_sustained_torsion_rate_hands_yields(): + h = _new() + out = _yield(h, torque=1.0, rate=18.0, hands_on=1) + assert out.yielded + assert out.authority == 0.0 + assert out.ui_paused + assert not out.emergency_cancel + + +def test_gravel_like_spikes_do_not_yield_even_with_hands(): + """Rumble: brief 1.2 Nm hits, even with hands + rate, must not accumulate.""" + h = _new() + out = None + for _ in range(40): + for _ in range(5): + out = _step(h, torque=1.2, rate=40.0, hands_on=1) + for _ in range(5): + out = _step(h, torque=0.15, rate=4.0, hands_on=1) + assert not out.yielded + assert out.authority == 1.0 + + +def test_fight_the_wheel_low_rate_high_error_yields(): + """#78 regression: isometric fight must soft-yield, not hard-cancel. + + Sustained torsion + hands, low steer rate, high tracking error. + On-car gravel dodge: OP holds the path (error high) while the driver + pushes without the wheel moving much. Rate-gate + disturbance veto + used to block yield until hands-on >= 2 / STEER_THRESHOLD. + """ + h = _new() + torque = 0.95 + needed = required_press_frames(torque) + out = None + for i in range(needed): + out = _step(h, torque=torque, rate=2.0, hands_on=1, tracking_error=0.02) + if i < needed - 1: + assert not out.yielded + assert out.yielded + assert out.authority == 0.0 + assert out.ui_paused + assert not out.emergency_cancel + assert hands_still_on(1) + assert 1 < HANDS_ON_DISENGAGE_LEVEL + assert torque < float(STEER_THRESHOLD) + + +def test_sustained_torsion_without_hands_does_not_yield(): + """Hands level is not an entry gate. 0.9 Nm for 150 ms yields with hands off.""" + h = _new() + out = None + for _ in range(int(round(YIELD_SOFT_S / DT))): + out = _step(h, torque=0.90, rate=20.0, hands_on=0) + assert out.yielded + assert out.authority == 0.0 + + +def test_rate_does_not_block_firm_push(): + """Opposite / SNA / zero rate must not veto a firm sustained push.""" + h = _new() + out = _yield(h, torque=0.90, rate=-20.0, hands_on=1) + assert out.yielded + assert out.authority == 0.0 + + h = _new() + out = _yield(h, torque=0.90, rate=0.0, hands_on=1) + assert out.yielded + + h = _new() + needed = required_press_frames(1.0) + out = None + for _ in range(needed): + out = _step(h, torque=1.0, rate=4095.0, hands_on=1) + assert out.yielded + assert not torque_rate_aligned(1.0, 4095.0) + + +def test_low_torsion_aligned_rate_does_not_yield(): + """Rate is a weak wind filter only — it must not promote low torsion.""" + h = _new() + for _ in range(int(1.0 / DT)): + out = _step(h, torque=0.45, rate=30.0, hands_on=1, tracking_error=0.0) + assert not out.yielded + assert out.authority == 1.0 + + +def test_wind_disturbance_high_effort_low_torsion_does_not_yield(): + """Controller fighting wind: high tracking error, torsion below trigger.""" + h = _new() + assert is_disturbance( + torque_nm=0.2, rate_deg=4.0, tracking_error=DISTURBANCE_CURVATURE_ERR) + assert is_disturbance( + torque_nm=0.45, rate_deg=30.0, tracking_error=0.01) + assert not is_disturbance( + torque_nm=0.80, rate_deg=2.0, tracking_error=0.02) + for _ in range(int(1.5 / DT)): + out = _step(h, torque=0.25, rate=6.0, hands_on=1, + tracking_error=0.01) + assert not out.yielded + assert out.authority == 1.0 + + +def test_matching_intent_is_not_blocked_by_tracking_error(): + """A real dodge leaves the path — high error with firm torsion is OK.""" + h = _new() + assert not is_disturbance( + torque_nm=0.80, rate_deg=20.0, tracking_error=0.02) + out = _yield(h, torque=1.0, rate=20.0, hands_on=1) + assert out.yielded + out = _step(h, torque=0.80, rate=20.0, hands_on=1, tracking_error=0.02) + assert out.yielded + + +def test_soft_yield_below_hands_on_2_hard_cancel(): + """Soft path must win at hands=1 and torsion below STEER_THRESHOLD.""" + h = _new() + out = _yield(h, torque=0.95, rate=0.0, hands_on=1) + assert out.yielded + assert out.authority == 0.0 + assert 0.95 < float(STEER_THRESHOLD) + assert HANDS_ON_HOLD_LEVEL == 1 + assert HANDS_ON_DISENGAGE_LEVEL == 2 + + +def test_near_steer_threshold_yields_before_full_floor_debounce(): + """0.98 Nm is the 150 ms band. 1.4 Nm is the 80 ms band.""" + h = _new() + torque = 0.98 + needed = required_press_frames(torque) + assert needed == int(round(YIELD_SOFT_S / DT)) + assert needed > SOFT_YIELD_DEBOUNCE_FRAMES + out = None + for _ in range(needed - 1): + out = _step(h, torque=torque, rate=0.0, hands_on=1) + assert not out.yielded + out = _step(h, torque=torque, rate=0.0, hands_on=1) + assert out.yielded + assert out.authority == 0.0 + assert required_press_frames(1.4) == YIELD_FIRM_FRAMES + + +def test_hands_on_hold_and_hands_off_blend_still_work_after_intent_yield(): + h = _new() + _yield(h) + for _ in range(int(0.6 / DT)): + out = _step(h, torque=1.0, rate=30.0, hands_on=1) + assert out.yielded + assert not out.blending + assert out.authority == 0.0 + out = _hands_off(h, torque=0.10, rate=30.0) + assert out.blending + assert not out.yielded + for _ in range(int(BLEND_TIME_S / DT)): + out = _step(h, torque=0.0, rate=0.0, hands_on=0) + assert out.authority == 1.0 + assert not out.blending + assert not out.ui_paused + + +def test_emergency_hard_brake_while_yielded_sets_cancel(): + h = _new() + _yield(h) + out = _hard_brake_frames(h) + assert out.yielded + assert out.emergency_cancel + pause = (Path(__file__).resolve().parents[4] / + "selfdrive/car/tesla/preap_blinker_lat_pause.py").read_text() + assert "hard_cancel_session" in pause + assert "update_card_lat_handoff" in pause + assert "_publish_real_brake" in pause + assert "emergency_cancel" in pause + src = (Path(__file__).resolve().parents[4] / + "selfdrive/controls/lib/driver_lateral_handoff.py").read_text() + assert "_drop_longitudinal_keep_lateral" not in src + assert "_nap_long_resume_pending" not in src + + +def test_emergency_hard_brake_in_yield_window_after_blend_sets_cancel(): + h = _new() + _yield(h) + _hands_off(h) + for _ in range(int(BLEND_TIME_S / DT)): + _quiet(h, DT) + # Just after resume, still inside the 2 s yield-entry window. + out = _hard_brake_frames(h, hands_on=0, torque=0.0) + assert not out.yielded + assert out.authority == 1.0 + assert out.emergency_cancel + + +def test_hard_brake_after_window_does_not_cancel(): + h = _new() + _yield(h) + _hands_off(h) + for _ in range(int(BLEND_TIME_S / DT)): + _quiet(h, DT) + leftover = YIELD_EMERGENCY_WINDOW_S - BLEND_TIME_S - HANDS_OFF_CONFIRM_S + for _ in range(int((leftover + 0.15) / DT)): + out = _quiet(h, DT) + assert not out.emergency_cancel + out = _hard_brake_frames(h, hands_on=0, torque=0.0) + assert not out.emergency_cancel + + +def test_light_brake_while_yielded_does_not_force_full_cancel(): + """Digital Applied + mild aEgo is the sticky-MAX silent pause, not this.""" + h = _new() + _yield(h) + out = None + for _ in range(int(0.4 / DT)): + out = _step(h, torque=1.0, hands_on=1, brake=True, a_ego=-1.2, v_ego=15.0) + assert out.yielded + assert not out.emergency_cancel + + +def test_light_brake_when_not_yielded_does_not_cancel(): + h = _new() + out = None + for _ in range(int(0.4 / DT)): + out = _step(h, torque=0.2, hands_on=1, brake=True, a_ego=-1.0, v_ego=15.0) + assert not out.yielded + assert not out.emergency_cancel + + +def test_hard_decel_without_brake_does_not_cancel(): + """Pothole / KF spike: aEgo alone is not emergency.""" + h = _new() + _yield(h) + out = _hard_brake_frames(h, brake=False, a_ego=-6.0) + assert out.yielded + assert not out.emergency_cancel + + +def test_cs_real_brake_pressed_reads_brake_stash(): + class _CS: + pass + + cs = _CS() + cs.brake = 1.0 + cs.brakePressed = False + assert cs_real_brake_pressed(cs) + cs.brake = 0.0 + assert not cs_real_brake_pressed(cs) + cs.realBrakePressed = True + assert cs_real_brake_pressed(cs) + cs = (Path(__file__).resolve().parents[4] / "selfdrive/controls/controlsd.py").read_text() + assert "cs_real_brake_pressed" in cs + assert "CC.cruiseControl.cancel" in cs diff --git a/selfdrive/controls/lib/tests/test_driver_lateral_handoff_early_yield.py b/selfdrive/controls/lib/tests/test_driver_lateral_handoff_early_yield.py new file mode 100644 index 00000000000000..0bfb299a816554 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_driver_lateral_handoff_early_yield.py @@ -0,0 +1,170 @@ +"""Early yield on steeringPressed (no EPAS hands gate). + +EPAS_handsOnLevel lags the torsion bar, so a firm push can reach hands >= 2 +before the hands-gated soft yield fires. Same-sign torsion >= EARLY_YIELD_NM +while steeringPressed for EARLY_YIELD_FRAMES yields without the hands gate so +the wheel input lands on a yielded lateral (B), not a full one (A). + +Tuned conservatively on Oct 1-3 qlogs (see driver_lateral_handoff.py): the +1 Nm / 50 ms variant false-yielded on road chatter. +""" +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + EARLY_YIELD_FRAMES, + EARLY_YIELD_NM, + DriverLateralHandoff, +) + + +def _run(torques, *, pressed=True, hands=0, alc=False, enabled=True, v_ego=20.0): + h = DriverLateralHandoff(enabled=enabled) + out = None + for tq in torques: + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=tq, + steering_rate_deg=0.0, hands_on_level=hands, alc_active=alc, + v_ego=v_ego, steering_pressed=pressed) + return out + + +def test_sustained_same_sign_push_yields_without_hands(): + assert _run([EARLY_YIELD_NM + 0.5] * EARLY_YIELD_FRAMES).yielded + assert _run([-(EARLY_YIELD_NM + 0.5)] * EARLY_YIELD_FRAMES).yielded + assert _run([EARLY_YIELD_NM] * EARLY_YIELD_FRAMES).yielded # boundary + + +def test_one_frame_short_does_not_yield(): + assert not _run([EARLY_YIELD_NM + 0.5] * (EARLY_YIELD_FRAMES - 1)).yielded + + +def test_below_threshold_does_not_yield(): + # 1.95 Nm is above the 1.4 Nm / 80 ms path, so it yields. Resting and + # short firm-but-not-1.4 pushes do not. + assert not _run([0.85] * 40).yielded + assert not _run([1.2] * 8, pressed=False).yielded + assert _run([1.2] * 15, pressed=False).yielded + + +def test_alternating_sign_chatter_does_not_yield(): + chatter = [3.0, -3.0] * 30 + assert not _run(chatter).yielded + # a sign flip in the middle restarts the count + assert not _run([3.0] * (EARLY_YIELD_FRAMES - 1) + [-3.0] + [3.0] * (EARLY_YIELD_FRAMES - 1)).yielded + + +def test_gap_restarts_the_count(): + assert not _run(([3.0] * (EARLY_YIELD_FRAMES - 1) + [0.0]) * 4).yielded + + +def test_firm_torque_yields_without_steering_pressed(): + """1.4 Nm / 80 ms does not wait for steeringPressed or a hands level.""" + assert _run([1.4] * 8, pressed=False).yielded + assert _run([4.0] * 8, pressed=False).yielded + assert not _run([1.2] * 8, pressed=False).yielded + + +def test_resting_band_never_yields(): + """Hands resting at 0.15–0.35 Nm never enter yield or a take-back taper. + + The check is every frame. A dropped 0.9 Nm threshold lets 0.25 Nm yield + and then R1 give the wheel back, so the final frame is full lateral again. + """ + for tq in (0.15, 0.25, 0.35, -0.30): + for pressed, hands in ((False, 0), (True, 1)): + h = DriverLateralHandoff(enabled=True) + for _ in range(400): + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=tq, + steering_rate_deg=0.0, hands_on_level=hands, v_ego=20.0, + steering_pressed=pressed) + assert not out.yielded and not out.blending and out.authority == 1.0 + + +def test_not_in_tipped_lane_change(): + assert not _run([4.0] * 40, alc=True).yielded + + +def test_same_direction_hands_edge_yields_on_one_frame(): + """Helping torque + hands 3 yields before the 80 ms counter. Opposite does not.""" + h = DriverLateralHandoff(enabled=True) + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=-3.5, + steering_rate_deg=0.0, hands_on_level=3, v_ego=15.0, + steering_angle_deg=-30.0, commanded_angle_deg=-40.0, + steering_pressed=True) + assert out.yielded and out.authority == 0.0 + + h = DriverLateralHandoff(enabled=True) + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=3.5, + steering_rate_deg=0.0, hands_on_level=3, v_ego=15.0, + steering_angle_deg=-30.0, commanded_angle_deg=-40.0, + steering_pressed=True, undertrack=True) + assert not out.yielded and out.authority == 1.0 + + +def test_roundabout_any_input_yields_immediately(): + h = DriverLateralHandoff(enabled=True) + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=2.0, + steering_rate_deg=0.0, hands_on_level=2, v_ego=8.0, + steering_angle_deg=-20.0, commanded_angle_deg=-10.0, + roundabout_yield=True, steering_pressed=True) + assert out.yielded + h = DriverLateralHandoff(enabled=True) + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=1.2, + steering_rate_deg=0.0, hands_on_level=0, v_ego=8.0, + roundabout_yield=True, steering_pressed=True) + assert out.yielded + + +def test_farm_trace_yields_on_the_final_helping_yank(): + torques = [0.70, -0.95, 0.47, -2.19, 0.86, -1.79, 0.15, -1.00, -3.29, -3.77] + h = DriverLateralHandoff(enabled=True) + out = None + for i, tq in enumerate(torques): + meas = -26.0 + (-44.0 + 26.0) * i / (len(torques) - 1) + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=tq, + steering_rate_deg=0.0, hands_on_level=3 if i == len(torques) - 1 else 0, + v_ego=8.0, steering_angle_deg=meas, commanded_angle_deg=meas + 8.0, + undertrack=True, steering_pressed=abs(tq) >= 1.0) + if i < len(torques) - 1: + assert not out.yielded + assert out.yielded + + +def test_handoff_off_is_identity(): + out = _run([4.0] * 40, enabled=False) + assert not out.yielded and out.authority == 1.0 + + +def test_yield_frees_the_eps_then_blends_back_after_hands_off(): + from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + BLEND_TIME_S, + RELEASE_HOLD_S, + lat_active_after_handoff, + ) + h = DriverLateralHandoff() + def step(tq, pressed, hands=0): + return h.update(engaged=True, lat_would_be_active=True, steering_torque=tq, + steering_rate_deg=0.0, hands_on_level=hands, v_ego=20.0, + steering_pressed=pressed) + for _ in range(EARLY_YIELD_FRAMES): + out = step(3.0, True) + assert out.yielded and not lat_active_after_handoff(True, out.yielded) + for _ in range(int(RELEASE_HOLD_S / 0.01) + 3): + out = step(0.0, False) + assert out.blending and lat_active_after_handoff(True, out.yielded) + for _ in range(int(BLEND_TIME_S / 0.01) + 3): + out = step(0.0, False) + assert not out.blending and out.authority == 1.0 + + +def test_controlsd_and_card_pass_steering_pressed_to_the_handoff(): + from pathlib import Path + repo = Path(__file__).resolve().parents[4] + controlsd = (repo / "selfdrive/controls/controlsd.py").read_text() + call_tail = ( + " steering_pressed=bool(CS.steeringPressed),\n" + " model_curvature=float(self._raw_model_curvature),\n" + " measured_curvature=float(self.curvature),\n" + " )\n" + ) + assert call_tail in controlsd + assert "CC.latActive = lat_active_after_handoff(" in controlsd + card = (repo / "selfdrive/car/tesla/preap_blinker_lat_pause.py").read_text() + assert 'steering_pressed=bool(getattr(ret, "steeringPressed", False)),' in card diff --git a/selfdrive/controls/lib/tests/test_driver_lateral_handoff_wheel_resume.py b/selfdrive/controls/lib/tests/test_driver_lateral_handoff_wheel_resume.py new file mode 100644 index 00000000000000..59a28b2fa0427c --- /dev/null +++ b/selfdrive/controls/lib/tests/test_driver_lateral_handoff_wheel_resume.py @@ -0,0 +1,386 @@ +"""Wheel-resume gate: no take-back while the wheel is still uncoiling. + +Rapid back-and-forth turns (roundabout, switchback, parking lot): the driver +yields lateral, then lets the wheel slip through light / open hands. Hands +level 0 for 0.15 s used to start the 1 s blend mid-uncoil and OP grabbed the +wheel. After a big-angle handoff the blend now waits until the wheel is within +WHEEL_RESUME_STRAIGHT_DEG of straight (and stays there for a dwell). +""" +import math +from pathlib import Path + +import pytest + +from openpilot.selfdrive.controls.lib import driver_lateral_handoff as dlh +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + BLEND_TIME_S, + DT_CTRL, + HANDS_OFF_CONFIRM_S, + RELEASE_HOLD_S, + WHEEL_GATE_ARM_DEG, + WHEEL_GATE_MAX_HOLD_S, + WHEEL_RESUME_STRAIGHT_DEG, + WHEEL_STRAIGHT_DWELL_S, + DriverLateralHandoff, + lat_active_after_handoff, +) + +MPH = 0.44704 + + +class Sim: + def __init__(self, v_ego=20.0 * MPH, with_angle=True, blinker=False): + self.h = DriverLateralHandoff() + self.v = v_ego + self.with_angle = with_angle + self.blinker = blinker + self.angle = 0.0 + self.out = None + self.t = 0.0 + + def step(self, *, tq=0.0, hands=0, angle=None, v=None, lat=True, pressed=False): + if angle is not None: + self.angle = angle + if v is not None: + self.v = v + self.out = self.h.update( + engaged=True, lat_would_be_active=lat, steering_torque=tq, steering_rate_deg=0.0, + hands_on_level=hands, v_ego=self.v, blinker_paused=self.blinker, + steering_pressed=pressed, + steering_angle_deg=(self.angle if self.with_angle else None)) + self.t += DT_CTRL + return self.out + + def push_to(self, angle, frames=20, tq=1.5): + """Hands-on firm push that yields; wheel ends at `angle`.""" + for i in range(frames): + self.step(tq=tq, hands=1, angle=angle * (i + 1) / frames) + assert self.out.yielded + return self.out + + def hands_off(self, seconds, angle=None): + n = int(round(seconds / DT_CTRL)) + for _ in range(n): + self.step(angle=angle) + return self.out + + def uncoil(self, a0, a1, seconds): + """Hands off; wheel slides linearly a0 -> a1. Returns first blend time or None.""" + n = int(round(seconds / DT_CTRL)) + for i in range(n): + self.step(angle=a0 + (a1 - a0) * (i + 1) / n) + if self.out.blending: + return self.t + return None + + +def test_constants_are_in_the_agreed_ranges(): + assert 10.0 <= WHEEL_RESUME_STRAIGHT_DEG <= 15.0 + assert WHEEL_GATE_ARM_DEG > WHEEL_RESUME_STRAIGHT_DEG + assert WHEEL_GATE_MAX_HOLD_S > 2.0 + assert WHEEL_STRAIGHT_DWELL_S >= HANDS_OFF_CONFIRM_S - 1e-9 + + +def test_without_angle_resume_is_unchanged(): + """No angle wired (None) -> hands-off confirm then blend, as before.""" + s = Sim(with_angle=False) + s.push_to(200.0) + s.hands_off(RELEASE_HOLD_S + 0.03, angle=200.0) + assert s.out.blending + + +def test_uncoil_from_large_angle_does_not_resume_until_straight(): + s = Sim() + s.push_to(200.0) + # hands off, wheel slides 200 -> 40 deg over 2 s: still yielded, EPS free + assert s.uncoil(200.0, 40.0, 2.0) is None + assert s.out.yielded and not lat_active_after_handoff(True, s.out.yielded) + assert s.out.authority == 0.0 + # reaches ~straight and stays: blend starts after the dwell + t_blend = s.uncoil(40.0, 5.0, 1.0) + assert t_blend is not None + assert s.out.blending and lat_active_after_handoff(True, s.out.yielded) + + +def test_blend_starts_within_dwell_of_entering_the_window(): + s = Sim() + s.push_to(150.0) + s.hands_off(0.5, angle=150.0) + assert s.out.yielded + s.step(angle=WHEEL_RESUME_STRAIGHT_DEG - 1.0) + assert s.out.yielded + frames = int(round(WHEEL_STRAIGHT_DWELL_S / DT_CTRL)) + for _ in range(frames + 1): + s.step(angle=WHEEL_RESUME_STRAIGHT_DEG - 1.0) + assert s.out.blending + + +def test_just_outside_the_window_still_holds(): + s = Sim() + s.push_to(150.0) + s.hands_off(2.0, angle=WHEEL_RESUME_STRAIGHT_DEG + 1.0) + assert s.out.yielded and not s.out.blending + + +def test_rapid_swing_through_centre_is_not_straight(): + """Left lock -> right lock in ~0.25 s passes centre: no resume.""" + s = Sim() + s.push_to(300.0) + s.hands_off(HANDS_OFF_CONFIRM_S + 0.05, angle=300.0) + assert s.out.yielded + n = 25 + for i in range(n): + s.step(angle=300.0 - 600.0 * (i + 1) / n) + assert not s.out.blending + assert s.out.yielded + s.hands_off(1.0, angle=-300.0) + assert s.out.yielded + + +def test_back_and_forth_turns_stay_yielded_throughout(): + s = Sim() + s.push_to(180.0) + for k in range(6): + sign = -1.0 if k % 2 == 0 else 1.0 + a0 = -sign * 180.0 + # hand off, uncoil most of the way, then regrip for the next turn + s.uncoil(a0, a0 * 0.2, 0.8) + assert s.out.yielded and not s.out.blending, k + for i in range(15): + s.step(tq=1.2 * sign, hands=1, angle=a0 * 0.2 + (sign * 180.0 - a0 * 0.2) * (i + 1) / 15) + assert s.out.yielded + + +def test_small_angle_nudge_resumes_as_before(): + """Highway lane nudge never reaches the arming angle: unchanged.""" + s = Sim(v_ego=30.0) + s.push_to(WHEEL_GATE_ARM_DEG - 5.0) + s.hands_off(RELEASE_HOLD_S + 0.03, angle=WHEEL_GATE_ARM_DEG - 5.0) + assert s.out.blending + + +def test_arming_is_the_peak_since_the_yield_not_the_start_angle(): + """Yield began near centre; wheel went to lock later -> still gated.""" + s = Sim() + s.push_to(10.0, frames=12) + for i in range(30): + s.step(tq=1.2, hands=1, angle=10.0 + 4.0 * (i + 1)) + assert s.angle > WHEEL_GATE_ARM_DEG + s.hands_off(1.0, angle=100.0) + assert s.out.yielded and not s.out.blending + + +def test_hands_back_on_still_holds_and_hands_off_restarts(): + s = Sim() + s.push_to(150.0) + s.hands_off(0.5, angle=150.0) + for _ in range(5): + s.step(hands=1, angle=140.0) + assert s.out.yielded + s.hands_off(0.5, angle=140.0) + assert s.out.yielded and not s.out.blending + s.hands_off(0.5, angle=3.0) + assert s.out.blending + + +def test_hands_on_during_the_dwell_restarts_the_dwell(): + """Torque back above the release band restarts the straight dwell. + + A hand on the rim with no torque does not. The wheel-gate mutation that + forgets to zero the dwell is caught by the short wait after the bump. + """ + s = Sim() + s.push_to(150.0) + s.hands_off(RELEASE_HOLD_S + 0.10, angle=3.0) + assert s.out.yielded and not s.out.blending + s.step(tq=1.0, hands=0, angle=3.0) + s.hands_off(RELEASE_HOLD_S + 0.06, angle=3.0) + assert s.out.yielded and not s.out.blending + s.hands_off(WHEEL_STRAIGHT_DWELL_S, angle=3.0) + assert s.out.blending + + +def test_hands_on_restarts_the_safety_valve(): + s = Sim() + s.push_to(150.0) + s.hands_off(WHEEL_GATE_MAX_HOLD_S - 0.5, angle=90.0) + assert s.out.yielded and not s.out.blending + s.step(tq=1.0, hands=0, angle=90.0) + s.hands_off(2.0, angle=90.0) + assert s.out.yielded and not s.out.blending + # Hands level alone does not restart the valve. + s2 = Sim() + s2.push_to(150.0) + s2.hands_off(WHEEL_GATE_MAX_HOLD_S - 0.2, angle=90.0) + s2.step(hands=1, tq=0.0, angle=90.0) + s2.hands_off(0.5, angle=90.0) + assert s2.out.blending + + +def test_firm_push_in_window_cancels_blend_and_keeps_the_peak(): + s = Sim() + s.push_to(150.0) + s.hands_off(RELEASE_HOLD_S + WHEEL_STRAIGHT_DWELL_S + 0.05, angle=3.0) + assert s.out.blending + for _ in range(16): + s.step(tq=1.5, hands=1, angle=60.0) + assert s.out.yielded and not s.out.blending + # still above the window: gate remembers the big-angle history + s.hands_off(1.0, angle=60.0) + assert s.out.yielded and not s.out.blending + s.hands_off(0.5, angle=2.0) + assert s.out.blending + + +def test_completed_blend_clears_the_peak(): + s = Sim() + s.push_to(150.0) + s.hands_off(0.5, angle=3.0) + assert s.out.blending + s.hands_off(BLEND_TIME_S + 0.1, angle=3.0) + assert s.out.authority == 1.0 and not s.out.blending + # next small nudge is not gated by the old peak + s.push_to(15.0) + s.hands_off(RELEASE_HOLD_S + 0.03, angle=15.0) + assert s.out.blending + + +def test_safety_valve_lets_go_after_max_hold(): + s = Sim() + s.push_to(150.0) + s.hands_off(WHEEL_GATE_MAX_HOLD_S - 0.5, angle=90.0) + assert s.out.yielded and not s.out.blending + s.hands_off(1.0, angle=90.0) + assert s.out.blending + + +def test_low_speed_lot_is_gated_and_crossing_10mph_at_lock_does_not_resume(): + """Lot: v < 10 mph inhibits re-enable; crossing 10 mph with the wheel near + lock used to land in yield and resume after 0.15 s hands-off.""" + s = Sim(v_ego=4.0 * MPH) + s.push_to(400.0, tq=1.5) + s.hands_off(1.0, angle=400.0) + assert s.out.yielded and not s.out.blending + # accelerate through 10 mph with the wheel still at lock + for i in range(150): + s.step(angle=380.0, v=(4.0 + 0.1 * i) * MPH) + assert s.v > 10.0 * MPH + assert s.out.yielded and not s.out.blending + # wheel unwinds: now it resumes + s.hands_off(0.5, angle=4.0) + assert s.out.blending + + +def test_low_speed_without_crossing_never_resumes_regardless_of_angle(): + s = Sim(v_ego=5.0 * MPH) + s.push_to(300.0) + s.hands_off(2.0, angle=0.0) + assert s.out.yielded and not s.out.blending + + +def test_blinker_clear_path_is_gated_too(): + s = Sim(blinker=True) + s.push_to(200.0) + s.hands_off(0.5, angle=200.0) + s.blinker = False + s.hands_off(1.0, angle=200.0) + assert s.out.yielded and not s.out.blending + s.hands_off(0.5, angle=5.0) + assert s.out.blending + + +def test_inhibit_cleared_landing_cannot_blend_in_one_big_step(): + """The inhibit-cleared landing accrues hands-off time itself; with a long + frame (dt >= confirm) it used to start the blend on the spot.""" + s = Sim(blinker=True) + s.push_to(200.0) + s.hands_off(0.5, angle=200.0) + s.blinker = False + out = s.h.update( + engaged=True, lat_would_be_active=True, steering_torque=0.0, steering_rate_deg=0.0, + hands_on_level=0, v_ego=s.v, blinker_paused=False, dt=RELEASE_HOLD_S + 0.05, + steering_angle_deg=200.0) + assert out.yielded and not out.blending + + +def test_standstill_blip_keeps_the_peak_when_inhibited(): + s = Sim(v_ego=3.0 * MPH) + s.push_to(300.0) + s.hands_off(0.3, angle=300.0) + s.step(lat=False, angle=300.0) # standstill / fault blip, latch reset + s.v = 15.0 * MPH + # wheel came back to 20 deg (below the arming angle, above the window): + # only the remembered peak keeps the gate on + s.hands_off(1.0, angle=20.0) + assert s.out.yielded and not s.out.blending + s.hands_off(0.5, angle=3.0) + assert s.out.blending + + +def test_lane_change_and_disengage_reset_the_gate(): + s = Sim() + s.push_to(200.0) + out = s.h.update(engaged=True, lat_would_be_active=True, steering_torque=0.0, + steering_rate_deg=0.0, alc_active=True, v_ego=20 * MPH, + steering_angle_deg=200.0) + assert out.authority == 1.0 and not out.yielded + assert s.h._peak_angle_deg == 0.0 + s2 = Sim() + s2.push_to(200.0) + s2.h.update(engaged=False, lat_would_be_active=True, steering_torque=0.0, + steering_rate_deg=0.0, v_ego=20 * MPH, steering_angle_deg=200.0) + assert s2.h._peak_angle_deg == 0.0 + + +def test_non_finite_or_missing_angle_never_blocks(): + for bad in (float("nan"), float("inf")): + s = Sim() + s.push_to(200.0) + s.hands_off(RELEASE_HOLD_S + 0.03, angle=bad) + assert s.out.blending + + +def test_sign_of_the_angle_does_not_matter(): + for sign in (1.0, -1.0): + s = Sim() + s.push_to(sign * 200.0, tq=sign * 1.5) + s.hands_off(1.0, angle=sign * 50.0) + assert s.out.yielded + s.hands_off(0.5, angle=sign * 4.0) + assert s.out.blending + + +def test_latactive_false_for_the_whole_extended_yield(): + s = Sim() + s.push_to(200.0) + for i in range(300): + s.step(angle=200.0 - 0.5 * i) + assert not lat_active_after_handoff(True, s.out.yielded) or s.out.blending + + +def test_controlsd_passes_the_steering_angle_to_the_handoff(): + repo = Path(__file__).resolve().parents[4] + controlsd = (repo / "selfdrive/controls/controlsd.py").read_text() + assert ( + " steering_angle_deg=float(CS.steeringAngleDeg),\n" + " steering_pressed=bool(CS.steeringPressed),\n" + " model_curvature=float(self._raw_model_curvature),\n" + " measured_curvature=float(self.curvature),\n" + ) in controlsd + + +def test_gate_is_written_in_the_module_docstring_and_pins_the_contract(): + assert "WHEEL-RESUME GATE" in (dlh.__doc__ or "") + assert math.isclose(WHEEL_RESUME_STRAIGHT_DEG, 12.0) + assert BLEND_TIME_S == 1.0 and HANDS_OFF_CONFIRM_S == 0.15 + + +@pytest.mark.parametrize("deg", [10.0, 15.0]) +def test_boundary_values_of_the_range_work(deg, monkeypatch): + monkeypatch.setattr(dlh, "WHEEL_RESUME_STRAIGHT_DEG", deg) + s = Sim() + s.push_to(150.0) + s.hands_off(1.0, angle=deg + 0.5) + assert s.out.yielded + s.hands_off(0.5, angle=deg - 0.5) + assert s.out.blending diff --git a/selfdrive/controls/lib/tests/test_engage_turn_handoff.py b/selfdrive/controls/lib/tests/test_engage_turn_handoff.py new file mode 100644 index 00000000000000..0350a11a09bd18 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_engage_turn_handoff.py @@ -0,0 +1,221 @@ +"""Engage latch, turn-vs-fight, resting torque, and a single pull taking lateral back.""" + +from pathlib import Path +from types import SimpleNamespace + +from opendbc.car.tesla.preap.engagement import PreAPEngagement +from opendbc.car.tesla.values import CruiseButtons + +from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import ( + ORPHAN_SESSION_S, + install_blinker_lat_pause, + reconcile_orphan_session, +) +from openpilot.selfdrive.controls.lib.desire_helper import _driver_torque_nm +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + LAT_REENABLE_MIN_V_EGO, + RELEASE_HOLD_S, + DriverLateralHandoff, +) +from openpilot.selfdrive.controls.lib.lane_change_nudge import TippedLaneChangeTorque +from openpilot.selfdrive.selfdrived.preap_regen import orphan_pull_requests_enable + +DT = 0.01 +REST_NM = 0.25 +# Above 10 mph. The inhibit is strict less-than. +CRUISE_V = LAT_REENABLE_MIN_V_EGO + 5.0 +SLOW_V = LAT_REENABLE_MIN_V_EGO - 0.5 +MODEL_K = 0.01 +WHEEL_K = 0.0 + + +def _step(h, *, torque=0.0, hands=0, dt=DT, v_ego=CRUISE_V, blinker=False, + engaged=True, lat=True, pressed=False, angle=0.0, rate=0.0, + model_k=MODEL_K, wheel_k=WHEEL_K): + return h.update( + engaged=engaged, lat_would_be_active=lat, + steering_torque=torque, steering_rate_deg=rate, + hands_on_level=hands, dt=dt, v_ego=v_ego, + blinker_paused=blinker, steering_pressed=pressed, + steering_angle_deg=angle, + model_curvature=model_k, measured_curvature=wheel_k, + ) + + +def _run(h, seconds, **kw): + n = max(1, int(round(seconds / DT))) + out = None + for _ in range(n): + out = _step(h, **kw) + return out + + +def _yield_once(h, torque=1.5): + out = None + for _ in range(12): + out = _step(h, torque=torque, hands=1, pressed=True) + assert out.yielded and out.authority == 0.0 + return out + + +def test_resting_offset_returns_lateral_after_a_held_turn(): + """Logged pattern: hands-off sits near +0.25 Nm. The free-wheel offset learns it.""" + h = DriverLateralHandoff() + _run(h, 12.0, torque=REST_NM, hands=0, engaged=False, lat=False, angle=0.0, rate=-4095.5) + assert 0.20 < h.rest_bias < 0.28 + assert 0.20 < h.rest_bias_free < 0.28 + + turn = REST_NM + 2.0 + out = _run(h, 6.0, torque=turn, hands=1, pressed=True, blinker=True, engaged=True, lat=True) + assert out.yielded + + out = None + for _ in range(int((RELEASE_HOLD_S + 0.05) / DT)): + out = _step(h, torque=REST_NM, hands=0, blinker=False, pressed=False) + if out.blending: + break + assert out is not None and out.blending and not out.yielded + + +def test_blinker_and_low_speed_hold_the_yield(): + h = DriverLateralHandoff() + push = 1.5 + _yield_once(h, push) + out = _run(h, 1.0, torque=0.0, hands=0, blinker=True) + assert out.yielded and not out.blending + + h2 = DriverLateralHandoff() + _yield_once(h2, push) + out = _run(h2, 1.0, torque=0.0, hands=0, v_ego=SLOW_V, blinker=False) + assert out.yielded and not out.blending + # Crossing 10 mph lands in yield; a quiet wheel then returns. + out = _run(h2, RELEASE_HOLD_S + 0.05, torque=0.0, hands=0, v_ego=CRUISE_V, blinker=False) + assert out.blending and not out.yielded + + +def test_light_hold_returns_without_curvature_agreement(): + h = DriverLateralHandoff() + _yield_once(h, 1.5) + early = _run(h, 2.0, torque=0.5, hands=0, model_k=MODEL_K, wheel_k=WHEEL_K) + assert early.yielded and not early.blending + out = _run(h, 0.6, torque=0.5, hands=0, model_k=MODEL_K, wheel_k=WHEEL_K) + assert out.blending and not out.yielded + + +def test_single_pull_forces_the_return(): + h = DriverLateralHandoff() + _yield_once(h, 1.5) + _run(h, 0.5, torque=1.0, hands=1, model_k=MODEL_K) + assert h._yielded + h._soften = True + h.driver_resume_request() + assert not h._soften + assert h._pull_pending and h._yielded and not h._blending + out = _step(h, torque=1.0, hands=1, model_k=MODEL_K) + assert out.blending and not out.yielded + assert not h._pull_pending + + +def test_learned_offset_is_not_a_left_lane_nudge(): + nudge = TippedLaneChangeTorque() + nudge.update(torque_nm=0.0, hands_on_level=0, direction=1, tipped=True, dt=DT) + assert not nudge.confirm + nudge.update(torque_nm=0.70, hands_on_level=1, direction=1, tipped=True, dt=DT) + assert nudge.confirm + + resting = SimpleNamespace(steeringTorque=REST_NM, napRestTorqueNm=REST_NM, steeringPressed=False) + assert abs(_driver_torque_nm(resting)) < 1e-9 + missing = SimpleNamespace(steeringTorque=0.40, steeringPressed=False) + assert abs(_driver_torque_nm(missing) - 0.40) < 1e-9 + + controls = Path("selfdrive/controls/controlsd.py").read_text() + assert "self.lat_handoff.rest_bias" in controls + assert "napStalkSeq" in controls + sub = controls.split("messaging.SubMaster(", 1)[1].split(")", 1)[0] + assert sub.count("'carState'") == 1 + assert "sub_sock" not in controls + desire = Path("selfdrive/controls/lib/desire_helper.py").read_text() + assert "napRestTorqueNm" in desire + + +def test_orphan_pull_is_pedal_single_and_no_pedal_only_with_long(): + assert orphan_pull_requests_enable( + cruise_enabled=True, op_enabled=False, set_pressed=True, use_pedal=True, long_on=False) + assert not orphan_pull_requests_enable( + cruise_enabled=True, op_enabled=True, set_pressed=True, use_pedal=True, long_on=True) + assert not orphan_pull_requests_enable( + cruise_enabled=False, op_enabled=False, set_pressed=True, use_pedal=True, long_on=False) + # No-pedal: the first pull is lateral-only. The completing pull has long on. + assert not orphan_pull_requests_enable( + cruise_enabled=True, op_enabled=False, set_pressed=True, use_pedal=False, long_on=False) + assert orphan_pull_requests_enable( + cruise_enabled=True, op_enabled=False, set_pressed=True, use_pedal=False, long_on=True) + + +def _buttons(eng, *, cruise_buttons=0, prev=0, t_ms=1000, use_pedal=True): + return eng.process_buttons( + cruise_buttons=cruise_buttons, prev_cruise_buttons=prev, + curr_time_ms=t_ms, v_ego=15.0, speed_units="KPH", + use_pedal=use_pedal, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=False) + + +def test_orphan_session_resets_quietly_then_the_next_pull_engages(): + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + eng.cruiseEnabled = True + eng.enableLongControl = True + eng.longCtrlEvent = "pccEnabled" + cereal = SimpleNamespace( + cruiseState=SimpleNamespace(enabled=True), enableLongControl=True) + iface = SimpleNamespace( + cruiseEnabled=True, enableLongControl=True, enableJustCC=False, + pedal_speed_kph=10.0, preap_cc_cancel_needed=False, cruise_enabled_prev=True) + + timer = 0.0 + canceled = False + frames = int(round((ORPHAN_SESSION_S - DT) / DT)) + for _ in range(frames): + timer, canceled = reconcile_orphan_session( + eng, op_enabled=False, orphan_s=timer, dt=DT, + cereal_cs=cereal, interface_cs=iface) + assert not canceled + assert eng.cruiseEnabled + assert timer + 1e-9 < ORPHAN_SESSION_S + + # Openpilot taking the session clears the timer and leaves cruise up. + timer, canceled = reconcile_orphan_session( + eng, op_enabled=True, orphan_s=timer, dt=DT, cereal_cs=cereal, interface_cs=iface) + assert timer == 0.0 and not canceled and eng.cruiseEnabled + + timer = 0.0 + for _ in range(frames + 2): + timer, canceled = reconcile_orphan_session( + eng, op_enabled=False, orphan_s=timer, dt=DT, + cereal_cs=cereal, interface_cs=iface) + if canceled: + break + assert canceled + assert not eng.cruiseEnabled + assert not eng.enableLongControl + assert eng.preap_cc_cancel_needed + assert eng.longCtrlEvent != "pccDisabled" + assert cereal.cruiseState.enabled is False + assert iface.preap_cc_cancel_needed + assert iface.cruise_enabled_prev is False + + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=5000) + assert eng.cruiseEnabled and eng.enableLongControl + + +def test_in_session_pull_bumps_stalk_seq_and_a_fresh_engage_does_not(): + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000) + assert eng.cruiseEnabled + assert int(getattr(eng, "_nap_stalk_seq", 0)) == 0 + + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=0, t_ms=2000) + assert int(eng._nap_stalk_seq) == 1 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=0, t_ms=3000) + assert int(eng._nap_stalk_seq) == 2 diff --git a/selfdrive/controls/lib/tests/test_lane_change_confirm_replay.py b/selfdrive/controls/lib/tests/test_lane_change_confirm_replay.py new file mode 100644 index 00000000000000..1b28ff18d4d739 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lane_change_confirm_replay.py @@ -0,0 +1,721 @@ +"""Tipped lane-change confirm vs emergency: replays of logged nudges. + +Sep 28 2026 (Scallywag, nap-dev 1119c0f) qlog carState at 10 Hz: + +* E1 10:40:08 CT, route 123 seg 16, right tip: -1.88 Nm ~100 ms after + +0.10 Nm. Old #249 fast rise (1.65 Nm / 150 ms) -> steerDisengage. +* E3 11:06:00 CT, route 124 seg 6, left tip: +0.03 -> +0.69 -> +1.77 Nm. + Same failure. +* 11:07:15 CT, route 124 seg 7-8, left tip: a confirm that worked + (peaked +1.17 Nm over ~400 ms). +* Sep 22 22:44:08 CT, route 104 seg 7, left tip: a first nudge at + +0.73/+0.80/+0.67 Nm never reached steeringPressed; the driver pushed + again 1.9 s later. + +Full Sep 28 review (rlog carState at 20 Hz; R124 ran with unified ON): + +* Confirms that worked and must stay confirms: 10:37:55 (R123, right, + -1.32 Nm), 11:01:35 (left, +1.40), 11:11:26 (right, -1.25). +* 11:10:25 (right tip, |tq| <= 0.3 Nm the whole time): a clean 7 s + preLaneChange timeout. Must not soft-confirm. +* 11:13:18 (the "emergency cancel", -2.92 Nm) is a sustained right turn + with a latched stalk, replayed in test_lane_change_turn.py. + +Hands-on level is not in these logs; it is taken as 1 while +steeringPressed, else 0. Torque is linearly interpolated to 100 Hz (card +/ controlsd) and 20 Hz (DesireHelper); discrete signals are held. +""" + +from cereal import car, log + +from openpilot.common.constants import CV +from openpilot.selfdrive.car.car_specific import CarSpecificEvents +from openpilot.selfdrive.controls.lib.desire_helper import ( + LANE_CHANGE_SPEED_MIN, + DesireHelper, + LaneChangeDirection, + LaneChangeState, +) +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + EMERGENCY_RISE_NM, + EMERGENCY_RISE_WINDOW_S, + EMERGENCY_SUSTAIN_S, + EMERGENCY_TORQUE_NM, + SOFT_CONFIRM_NM, + SOFT_CONFIRM_SUSTAIN_S, + SOFT_YIELD_TRIGGER_NM, + EmergencyYankTracker, + TAKEOVER_SUSTAIN_S, + SoftConfirmTracker, + TippedLaneChangeTorque, + is_emergency_yank, +) + +EventName = log.OnroadEvent.EventName +DT_CTRL = 0.01 +MODEL_EVERY = 5 # 20 Hz DesireHelper inside the 100 Hz loop +MPH = CV.MPH_TO_MS + +# (torque Nm, steeringPressed, stalk, left lamp, right lamp, hands-on, vEgo m/s) +E1_RIGHT_1040 = [ + (+0.08, 0, 0, 0, 0, 0, 16.42), + (+0.15, 0, 0, 0, 0, 0, 16.40), + (+0.19, 0, 2, 0, 0, 0, 16.41), # 10:40:08.599 stalk tip right + (+0.23, 0, 0, 0, 1, 0, 16.45), + (+0.31, 0, 0, 0, 1, 0, 16.46), + (+0.10, 0, 0, 0, 1, 0, 16.45), + (-1.88, 1, 0, 0, 1, 0, 16.45), # 10:40:09.002 confirm nudge + (-1.02, 1, 0, 0, 1, 0, 16.48), + (+0.13, 0, 0, 0, 1, 0, 16.48), + (-0.00, 0, 0, 0, 1, 0, 16.47), + (+0.03, 0, 0, 0, 1, 0, 16.45), +] +E3_LEFT_1106 = [ + (-0.07, 0, 0, 0, 0, 0, 14.40), + (-0.00, 0, 1, 0, 0, 0, 14.39), # 11:06:00.238 stalk tip left + (-0.05, 0, 1, 1, 0, 0, 14.39), + (+0.07, 0, 0, 1, 0, 0, 14.37), + (+0.03, 0, 0, 1, 0, 0, 14.36), + (+0.69, 0, 0, 1, 0, 0, 14.36), + (+1.77, 1, 0, 1, 0, 0, 14.34), # 11:06:00.736 confirm nudge + (+1.01, 1, 0, 1, 0, 0, 14.33), + (-0.00, 0, 0, 1, 0, 0, 14.32), + (+0.11, 0, 0, 1, 0, 0, 14.30), + (+0.13, 0, 0, 1, 0, 0, 14.28), +] +OK_LEFT_1107 = [ + (+0.02, 0, 0, 0, 0, 0, 19.16), + (+0.05, 0, 1, 0, 0, 0, 19.16), # 11:07:15.439 stalk tip left + (+0.01, 0, 1, 1, 0, 0, 19.17), + (+0.03, 0, 0, 1, 0, 0, 19.17), + (+0.02, 0, 0, 1, 0, 0, 19.18), + (+0.05, 0, 0, 1, 0, 0, 19.18), + (+0.20, 0, 0, 1, 0, 0, 19.18), + (+0.27, 0, 0, 1, 0, 0, 19.18), + (+0.56, 0, 0, 1, 0, 0, 19.19), + (+0.78, 0, 0, 1, 0, 0, 19.19), + (+1.00, 0, 0, 1, 0, 0, 19.19), + (+1.17, 1, 0, 1, 0, 1, 19.18), # 11:07:16.435 steeringPressed + (+1.11, 1, 0, 1, 0, 1, 19.19), + (+1.01, 1, 0, 1, 0, 1, 19.18), + (+0.10, 0, 0, 1, 0, 0, 19.19), + (-0.08, 0, 0, 1, 0, 0, 19.18), + (+0.20, 0, 0, 1, 0, 0, 19.19), + (-0.30, 0, 0, 1, 0, 0, 19.19), + (+0.18, 0, 0, 1, 0, 0, 19.19), +] +PRESSED_1107_IDX = 11 +FIRST_TRY_LEFT_0922 = [ + (+0.07, 0, 0, 0, 0, 0, 29.0), + (+0.02, 0, 1, 0, 0, 0, 29.0), # stalk tip left + (-0.11, 0, 1, 1, 0, 0, 29.0), + (-0.03, 0, 0, 1, 0, 0, 29.0), + (+0.73, 0, 0, 1, 0, 0, 29.0), # first nudge, never steeringPressed + (+0.80, 0, 0, 1, 0, 0, 29.0), + (+0.67, 0, 0, 1, 0, 0, 29.0), + (+0.12, 0, 0, 1, 0, 0, 29.0), + (+0.01, 0, 0, 1, 0, 0, 29.0), + (+0.10, 0, 0, 1, 0, 0, 29.0), +] + +# 20 Hz (rlog). 10:37:55 CT, route 123, right tip. +OK_RIGHT_1037 = [ + (+0.02, 0, 0, 0, 0, 0, 18.01), + (+0.07, 0, 0, 0, 0, 0, 18.03), + (+0.13, 0, 0, 0, 0, 0, 18.04), + (+0.14, 0, 2, 0, 0, 0, 18.06), + (+0.12, 0, 2, 0, 0, 0, 18.08), + (+0.12, 0, 0, 0, 1, 0, 18.10), + (+0.12, 0, 0, 0, 1, 0, 18.12), + (+0.12, 0, 0, 0, 1, 0, 18.14), + (+0.12, 0, 0, 0, 1, 0, 18.17), + (+0.08, 0, 0, 0, 1, 0, 18.19), + (+0.02, 0, 0, 0, 1, 0, 18.20), + (-0.07, 0, 0, 0, 1, 0, 18.22), + (-0.17, 0, 0, 0, 1, 0, 18.25), + (-0.25, 0, 0, 0, 1, 0, 18.26), + (-0.32, 0, 0, 0, 1, 0, 18.28), + (-0.63, 0, 0, 0, 1, 0, 18.30), + (-1.05, 0, 0, 0, 1, 0, 18.32), + (-1.24, 0, 0, 0, 1, 0, 18.34), + (-1.32, 0, 0, 0, 1, 0, 18.37), + (-1.18, 1, 0, 0, 1, 1, 18.39), + (-0.93, 1, 0, 0, 1, 1, 18.41), + (-0.41, 1, 0, 0, 1, 1, 18.42), + (+0.24, 1, 0, 0, 1, 1, 18.44), + (+0.24, 0, 0, 0, 1, 0, 18.46), # 10:37:56.363 laneChangeStarting + (-0.06, 0, 0, 0, 1, 0, 18.48), + (-0.03, 0, 0, 0, 1, 0, 18.50), + (+0.18, 0, 0, 0, 1, 0, 18.52), + (+0.20, 0, 0, 0, 1, 0, 18.54), + (+0.14, 0, 0, 0, 1, 0, 18.58), + (+0.15, 0, 0, 0, 1, 0, 18.61), + (+0.20, 0, 0, 0, 1, 0, 18.63), + (+0.19, 0, 0, 0, 1, 0, 18.65), + (+0.14, 0, 0, 0, 1, 0, 18.66), + (+0.11, 0, 0, 0, 1, 0, 18.67), +] +# 20 Hz. 11:01:35 CT, route 124, left tip. The stalk shows LEFT in 8 resampled +# samples (0.35-0.40 s); the car's DesireHelper counted it under the 0.40 s +# tip limit (it armed), so the last LEFT sample is taken as released. +OK_LEFT_1101 = [ + (+0.06, 0, 0, 0, 0, 0, 18.45), + (+0.04, 0, 0, 0, 0, 0, 18.48), + (+0.03, 0, 1, 0, 0, 0, 18.51), + (+0.02, 0, 1, 0, 0, 0, 18.54), + (+0.03, 0, 1, 1, 0, 0, 18.56), + (+0.04, 0, 1, 1, 0, 0, 18.58), + (+0.02, 0, 1, 1, 0, 0, 18.61), + (+0.00, 0, 1, 1, 0, 0, 18.64), + (+0.00, 0, 1, 1, 0, 0, 18.67), + (+0.01, 0, 0, 1, 0, 0, 18.70), # stalk released (see note) + (+0.02, 0, 0, 1, 0, 0, 18.73), + (+0.03, 0, 0, 1, 0, 0, 18.76), + (+0.04, 0, 0, 1, 0, 0, 18.79), + (+0.06, 0, 0, 1, 0, 0, 18.82), + (+0.05, 0, 0, 1, 0, 0, 18.84), + (+0.04, 0, 0, 1, 0, 0, 18.87), + (+0.01, 0, 0, 1, 0, 0, 18.89), + (-0.02, 0, 0, 1, 0, 0, 18.91), + (-0.02, 0, 0, 1, 0, 0, 18.92), + (-0.00, 0, 0, 1, 0, 0, 18.94), + (+0.05, 0, 0, 1, 0, 0, 18.97), + (+0.10, 0, 0, 1, 0, 0, 19.00), + (+0.20, 0, 0, 1, 0, 0, 19.03), + (+0.31, 0, 0, 1, 0, 0, 19.06), + (+0.81, 0, 0, 1, 0, 0, 19.08), + (+1.38, 0, 0, 1, 0, 0, 19.09), + (+1.40, 1, 0, 1, 0, 1, 19.12), + (+1.31, 1, 0, 1, 0, 1, 19.15), # 11:01:35.738 laneChangeStarting + (+0.58, 1, 0, 1, 0, 1, 19.17), + (-0.26, 1, 0, 1, 0, 1, 19.19), + (-0.14, 0, 0, 1, 0, 0, 19.21), + (+0.15, 0, 0, 1, 0, 0, 19.23), + (+0.02, 0, 0, 1, 0, 0, 19.26), + (-0.21, 0, 0, 1, 0, 0, 19.30), + (-0.10, 0, 0, 1, 0, 0, 19.31), + (+0.07, 0, 0, 1, 0, 0, 19.32), + (+0.05, 0, 0, 1, 0, 0, 19.34), + (+0.01, 0, 0, 1, 0, 0, 19.35), + (-0.02, 0, 0, 1, 0, 0, 19.37), +] +# 20 Hz. 11:11:26 CT, route 124, right tip. +OK_RIGHT_1111 = [ + (-0.01, 0, 0, 0, 0, 0, 16.44), + (+0.06, 0, 0, 0, 0, 0, 16.45), + (+0.05, 0, 2, 0, 1, 0, 16.47), + (+0.01, 0, 2, 0, 1, 0, 16.50), + (+0.04, 0, 0, 0, 1, 0, 16.52), + (+0.08, 0, 0, 0, 1, 0, 16.54), + (+0.09, 0, 0, 0, 1, 0, 16.56), + (+0.10, 0, 0, 0, 1, 0, 16.58), + (+0.09, 0, 0, 0, 1, 0, 16.59), + (+0.07, 0, 0, 0, 1, 0, 16.59), + (+0.06, 0, 0, 0, 1, 0, 16.60), + (+0.05, 0, 0, 0, 1, 0, 16.61), + (+0.08, 0, 0, 0, 1, 0, 16.62), + (+0.12, 0, 0, 0, 1, 0, 16.62), + (+0.03, 0, 0, 0, 1, 0, 16.63), + (-0.09, 0, 0, 0, 1, 0, 16.65), + (-0.17, 0, 0, 0, 1, 0, 16.65), + (-0.24, 0, 0, 0, 1, 0, 16.66), + (-0.24, 0, 0, 0, 1, 0, 16.66), + (-0.23, 0, 0, 0, 1, 0, 16.67), + (-0.29, 0, 0, 0, 1, 0, 16.68), + (-0.36, 0, 0, 0, 1, 0, 16.68), + (-0.78, 0, 0, 0, 1, 0, 16.68), + (-1.25, 0, 0, 0, 1, 0, 16.67), + (-1.02, 1, 0, 0, 1, 1, 16.67), + (-0.66, 1, 0, 0, 1, 1, 16.68), + (-0.30, 1, 0, 0, 1, 1, 16.69), + (+0.07, 1, 0, 0, 1, 1, 16.70), + (+0.26, 0, 0, 0, 1, 0, 16.70), + (+0.42, 0, 0, 0, 1, 0, 16.71), # 11:11:27.238 laneChangeStarting + (+0.33, 0, 0, 0, 1, 0, 16.71), + (+0.19, 0, 0, 0, 1, 0, 16.71), + (+0.15, 0, 0, 0, 1, 0, 16.71), + (+0.12, 0, 0, 0, 1, 0, 16.71), + (+0.14, 0, 0, 0, 1, 0, 16.71), + (+0.16, 0, 0, 0, 1, 0, 16.71), + (+0.18, 0, 0, 0, 1, 0, 16.71), + (+0.20, 0, 0, 0, 1, 0, 16.70), + (+0.26, 0, 0, 0, 1, 0, 16.71), + (+0.32, 0, 0, 0, 1, 0, 16.71), + (+0.23, 0, 0, 0, 1, 0, 16.72), +] +# 10 Hz. 11:10:25 CT, route 124, right tip; |tq| <= 0.3 Nm; 7 s timeout. +TIMEOUT_RIGHT_1110 = [ + (+0.17, 0, 0, 0, 0, 0, 18.86), + (+0.20, 0, 0, 0, 0, 0, 18.86), + (+0.22, 0, 0, 0, 0, 0, 18.86), + (+0.23, 0, 2, 0, 0, 0, 18.86), + (+0.20, 0, 0, 0, 1, 0, 18.86), + (+0.15, 0, 0, 0, 1, 0, 18.86), + (+0.22, 0, 0, 0, 1, 0, 18.86), + (+0.22, 0, 0, 0, 1, 0, 18.87), + (+0.14, 0, 0, 0, 1, 0, 18.88), + (+0.12, 0, 0, 0, 1, 0, 18.89), + (+0.16, 0, 0, 0, 1, 0, 18.91), + (+0.22, 0, 0, 0, 1, 0, 18.91), + (+0.21, 0, 0, 0, 1, 0, 18.91), + (+0.16, 0, 0, 0, 1, 0, 18.90), + (+0.16, 0, 0, 0, 1, 0, 18.92), + (+0.13, 0, 0, 0, 1, 0, 18.93), + (+0.12, 0, 0, 0, 1, 0, 18.93), + (+0.17, 0, 0, 0, 1, 0, 18.92), + (+0.15, 0, 0, 0, 1, 0, 18.92), + (+0.15, 0, 0, 0, 1, 0, 18.93), + (+0.15, 0, 0, 0, 1, 0, 18.93), + (+0.19, 0, 0, 0, 1, 0, 18.92), + (+0.21, 0, 0, 0, 1, 0, 18.92), + (+0.18, 0, 0, 0, 1, 0, 18.93), + (+0.19, 0, 0, 0, 1, 0, 18.93), + (+0.20, 0, 0, 0, 1, 0, 18.93), + (+0.21, 0, 0, 0, 1, 0, 18.92), + (+0.26, 0, 0, 0, 1, 0, 18.91), + (+0.26, 0, 0, 0, 1, 0, 18.90), + (+0.24, 0, 0, 0, 1, 0, 18.92), + (+0.29, 0, 0, 0, 1, 0, 18.92), + (+0.21, 0, 0, 0, 1, 0, 18.91), + (+0.17, 0, 0, 0, 1, 0, 18.91), + (+0.19, 0, 0, 0, 1, 0, 18.91), + (+0.18, 0, 0, 0, 1, 0, 18.91), + (+0.15, 0, 0, 0, 1, 0, 18.90), + (+0.15, 0, 0, 0, 1, 0, 18.90), + (+0.19, 0, 0, 0, 1, 0, 18.90), + (+0.19, 0, 0, 0, 1, 0, 18.90), + (+0.17, 0, 0, 0, 1, 0, 18.89), + (+0.21, 0, 0, 0, 1, 0, 18.89), + (+0.19, 0, 0, 0, 1, 0, 18.89), + (+0.17, 0, 0, 0, 1, 0, 18.87), + (+0.19, 0, 0, 0, 1, 0, 18.86), + (+0.15, 0, 0, 0, 1, 0, 18.86), + (+0.15, 0, 0, 0, 1, 0, 18.87), + (+0.12, 0, 0, 0, 1, 0, 18.86), + (+0.10, 0, 0, 0, 1, 0, 18.85), + (+0.08, 0, 0, 0, 1, 0, 18.85), + (+0.08, 0, 0, 0, 1, 0, 18.86), + (+0.07, 0, 0, 0, 1, 0, 18.86), + (+0.06, 0, 0, 0, 1, 0, 18.85), + (+0.07, 0, 0, 0, 1, 0, 18.84), + (+0.12, 0, 0, 0, 1, 0, 18.84), + (+0.14, 0, 0, 0, 1, 0, 18.85), + (+0.05, 0, 0, 0, 1, 0, 18.84), + (+0.02, 0, 0, 0, 1, 0, 18.83), + (+0.06, 0, 0, 0, 1, 0, 18.82), + (+0.09, 0, 0, 0, 1, 0, 18.82), + (+0.10, 0, 0, 0, 1, 0, 18.81), + (+0.17, 0, 0, 0, 1, 0, 18.80), + (+0.21, 0, 0, 0, 1, 0, 18.79), + (+0.13, 0, 0, 0, 1, 0, 18.80), + (+0.11, 0, 0, 0, 1, 0, 18.79), + (+0.20, 0, 0, 0, 1, 0, 18.78), + (+0.18, 0, 0, 0, 1, 0, 18.78), + (+0.16, 0, 0, 0, 1, 0, 18.77), + (+0.17, 0, 0, 0, 1, 0, 18.75), + (+0.17, 0, 0, 0, 1, 0, 18.73), + (+0.20, 0, 0, 0, 1, 0, 18.72), + (+0.20, 0, 0, 0, 1, 0, 18.72), + (+0.18, 0, 0, 0, 1, 0, 18.72), + (+0.15, 0, 0, 0, 1, 0, 18.72), + (+0.16, 0, 0, 0, 1, 0, 18.70), + (+0.17, 0, 0, 0, 1, 0, 18.69), + (+0.19, 0, 0, 0, 1, 0, 18.68), + (+0.20, 0, 0, 0, 1, 0, 18.68), + (+0.18, 0, 0, 0, 1, 0, 18.67), + (+0.17, 0, 0, 0, 0, 0, 18.66), + (+0.20, 0, 0, 0, 0, 0, 18.65), +] + + +class _Line: + def __init__(self, y): + self.y = [y, y, y] + + +class _Model: + """Centered in a 3.7 m lane with confident lines (target lock needs them).""" + + def __init__(self): + self.laneLines = [_Line(y) for y in (-5.55, -1.85, 1.85, 5.55)] + self.laneLineProbs = [0.9] * 4 + + +def _cp(): + cp = car.CarParams.new_message() + cp.carFingerprint = "TESLA_MODEL_S_PREAP" + cp.brand = "tesla" + cp.pcmCruise = True + cp.openpilotLongitudinalControl = False + return cp + + +def _cs(tq, pressed, stalk, left, right, hands, v): + cs = car.CarState.new_message() + cs.cruiseState.enabled = True + cs.cruiseState.available = True + cs.gearShifter = "drive" + cs.vEgo = float(v) + cs.steeringTorque = float(tq) + cs.steeringPressed = bool(pressed) + cs.turnSignalStalkState = int(stalk) + cs.leftBlinker = bool(left) + cs.rightBlinker = bool(right) + cs.steeringTorqueEps = float(hands) + cs.steeringDisengage = int(hands) >= 2 + return cs + + +def _upsample(trace, hz=100, src_hz=10): + """``src_hz`` rows -> ``hz`` rows. Torque linear, discrete signals held.""" + step = int(round(hz / src_hz)) + out = [] + for i, row in enumerate(trace): + nxt = trace[i + 1] if i + 1 < len(trace) else row + for k in range(step): + f = k / step + out.append((row[0] + (nxt[0] - row[0]) * f,) + tuple(row[1:])) + return out + + +class Replay: + """card (CarSpecificEvents) + controlsd emergency + DesireHelper at 20 Hz.""" + + def __init__(self): + self.cse = CarSpecificEvents(_cp()) + self.dh = DesireHelper() + self.yank = EmergencyYankTracker() + self.lct = TippedLaneChangeTorque() + self.takeover_t: list[float] = [] + self.model = _Model() + self.prev = _cs(0.0, 0, 0, 0, 0, 0, 20.0) + self.frame = 0 + self.t = 0.0 + self.disengage_t: list[float] = [] + self.emergency_t: list[float] = [] + self.states: list[tuple[float, int]] = [] + + def _dir(self): + if self.dh.lane_change_state == LaneChangeState.off: + return 0 + return 1 if self.dh.lane_change_direction == LaneChangeDirection.left else 2 + + def step(self, row): + cs = _cs(*row) + cc = car.CarControl.new_message() + cc.enabled = True + cc.latActive = True + cc.leftBlinker, cc.rightBlinker = self.dh.lane_change_keep_blinker( + self.dh.lane_change_state, self.dh.lane_change_direction) + events = self.cse.update(cs, self.prev, cc) + if EventName.steerDisengage in events.names: + self.disengage_t.append(self.t) + # controlsd lane-change emergency (same inputs as controlsd.py) + fast = self.yank.update(cs.steeringTorque, DT_CTRL) + if is_emergency_yank(torque_nm=cs.steeringTorque, hands_on_level=int(row[5]), fast_rise=fast, + over_torque=self.yank.over_torque, alc_direction=self._dir()): + self.emergency_t.append(self.t) + d = self._dir() + self.lct.update(torque_nm=cs.steeringTorque, hands_on_level=int(row[5]), direction=d, + tipped=d != 0, dt=DT_CTRL) + if self.lct.takeover: + self.takeover_t.append(self.t) + if self.frame % MODEL_EVERY == 0: + self.dh.update(cs, True, 0.0, model=self.model, engaged=True) + self.states.append((self.t, self.dh.lane_change_state)) + self.prev = cs + self.frame += 1 + self.t += DT_CTRL + + def run(self, trace, src_hz=10): + for row in _upsample(trace, src_hz=src_hz): + self.step(row) + return self + + def first_t(self, state): + for t, s in self.states: + if s == state: + return t + return None + + +def _legacy_fast_rise(trace): + """The #249 line: 1.65 Nm within 150 ms of being under 0.55 Nm.""" + rows = _upsample(trace) + for i, row in enumerate(rows): + if abs(row[0]) >= 3.0 * SOFT_YIELD_TRIGGER_NM: + back = rows[max(0, i - 15):i + 1] + if any(abs(r[0]) < SOFT_YIELD_TRIGGER_NM for r in back): + return True + return False + + +def test_new_thresholds(): + assert EMERGENCY_RISE_NM == 2.2 + assert EMERGENCY_RISE_WINDOW_S == 0.25 + assert EMERGENCY_TORQUE_NM == 2.5 + assert EMERGENCY_SUSTAIN_S == 0.10 + assert TAKEOVER_SUSTAIN_S == 0.30 + assert SOFT_CONFIRM_NM == 0.65 + assert SOFT_CONFIRM_SUSTAIN_S == 0.15 + assert LANE_CHANGE_SPEED_MIN == 20 * MPH + + +def test_fixtures_reproduce_the_old_misclassification(): + assert _legacy_fast_rise(E1_RIGHT_1040) + assert _legacy_fast_rise(E3_LEFT_1106) + assert not _legacy_fast_rise(OK_LEFT_1107) + + +def test_e1_right_nudge_is_a_confirm_not_an_emergency(): + r = Replay().run(E1_RIGHT_1040) + assert r.disengage_t == [] + assert r.emergency_t == [] + assert r.first_t(LaneChangeState.laneChangeStarting) is not None + assert r.dh.lane_change_direction == LaneChangeDirection.right + + +def test_e3_left_nudge_is_a_confirm_not_an_emergency(): + r = Replay().run(E3_LEFT_1106) + assert r.disengage_t == [] + assert r.emergency_t == [] + assert r.first_t(LaneChangeState.laneChangeStarting) is not None + assert r.dh.lane_change_direction == LaneChangeDirection.left + + +def test_1107_successful_confirm_still_confirms_no_later(): + r = Replay().run(OK_LEFT_1107) + assert r.disengage_t == [] + assert r.emergency_t == [] + start = r.first_t(LaneChangeState.laneChangeStarting) + assert start is not None + # Soft confirm: no later than the steeringPressed sample (+ one model frame). + assert start <= PRESSED_1107_IDX * 0.1 + 0.05 + 1e-9 + + +def test_first_nudge_below_steering_pressed_now_confirms(): + r = Replay().run(FIRST_TRY_LEFT_0922) + assert r.disengage_t == [] + assert r.first_t(LaneChangeState.laneChangeStarting) is not None + + +def _armed_left(v=20.0): + """Replay the E3 tip only (no nudge): armed preLaneChange, left.""" + r = Replay() + for row in _upsample([(0.0, 0, 0, 0, 0, 0, v), (0.0, 0, 1, 0, 0, 0, v), (0.0, 0, 1, 1, 0, 0, v), + (0.0, 0, 0, 1, 0, 0, v), (0.0, 0, 0, 1, 0, 0, v)]): + r.step(row) + assert r.dh.lane_change_state == LaneChangeState.preLaneChange + assert r.dh.lane_change_direction == LaneChangeDirection.left + return r + + +def _hold(r, seconds, tq, pressed=0, hands=0, v=20.0, left=1): + for _ in range(int(round(seconds / DT_CTRL))): + r.step((tq, pressed, 0, left, 0, hands, v)) + + +def test_hard_same_direction_yank_releases_promptly(): + r = _armed_left() + onset = r.t + for k in range(60): + tq = min(3.5, 3.5 * (k + 1) * DT_CTRL / 0.05) + r.step((tq, 1, 0, 1, 0, 3 if tq > 2.0 else 1, 20.0)) + assert r.disengage_t, "hard yank must steerDisengage" + assert r.disengage_t[0] - onset <= 0.15 + assert r.emergency_t and r.emergency_t[0] - onset <= 0.15 + assert r.dh.lane_change_state == LaneChangeState.off + + +def test_hard_opposite_yank_releases_promptly(): + r = _armed_left() + onset = r.t + for k in range(60): + tq = -min(3.5, 3.5 * (k + 1) * DT_CTRL / 0.05) + r.step((tq, 1, 0, 1, 0, 1, 20.0)) + assert r.disengage_t and r.disengage_t[0] - onset <= 0.15 + assert r.dh.lane_change_state == LaneChangeState.off + + +def _slow_pull(sign): + # No fast rise: climbs 0.3 -> 3.0 Nm over 0.6 s, then held. + r = _armed_left() + for k in range(60): + r.step((sign * (0.3 + 2.7 * (k + 1) / 60), 1, 0, 1, 0, 1, 20.0)) + crossed = r.t + _hold(r, 0.5, sign * 3.0, pressed=1, hands=1) + return r, crossed + + +def test_slow_hard_pull_against_the_change_releases(): + # Opposite direction: the sustained 2.5 Nm line is an emergency. + r, crossed = _slow_pull(-1) + assert r.disengage_t, "sustained opposite pull must steerDisengage" + assert r.disengage_t[0] <= crossed + 0.02 + assert r.dh.lane_change_state == LaneChangeState.off + + +def test_sustained_same_direction_pull_is_a_takeover_not_an_emergency(): + # Same direction, sustained: the driver steering through. Lateral + # yields (takeover) but nothing disengages. + r, crossed = _slow_pull(+1) + assert r.disengage_t == [] + assert r.emergency_t == [] + assert r.takeover_t + first = r.takeover_t[0] + # 2.5 Nm crossed ~0.07 s before the ramp ends; takeover 0.30 s later. + assert crossed - 0.1 + TAKEOVER_SUSTAIN_S - 0.02 <= first <= crossed + TAKEOVER_SUSTAIN_S + 0.02 + # Hands off for TAKEOVER_HANDS_OFF_S: the takeover yield ends. + _hold(r, 0.3, 0.0) + assert not r.lct.takeover + + +def test_hands_on_level_3_same_direction_confirm_is_not_an_emergency(): + # Logged firm confirms reach level 3 at ~1.9-2.3 Nm. + r = _armed_left() + _hold(r, 0.1, 0.9) + _hold(r, 0.4, 1.95, pressed=1, hands=3) + assert r.disengage_t == [] + assert r.emergency_t == [] + assert r.first_t(LaneChangeState.laneChangeStarting) is not None + # Same torque, opposite direction, level 3: still an emergency. + assert is_emergency_yank(torque_nm=-1.0, hands_on_level=3, fast_rise=False, + over_torque=False, alc_direction=1) + # Outside a tipped lane change level 3 is an emergency as before. + assert is_emergency_yank(torque_nm=1.0, hands_on_level=3, fast_rise=False, + over_torque=False, alc_direction=0) + + +def test_one_frame_spike_over_the_lines_is_not_an_emergency(): + r = _armed_left() + _hold(r, 0.05, 0.3) + _hold(r, EMERGENCY_SUSTAIN_S - 0.03, 2.8, pressed=1) # 70 ms above 2.5 Nm + _hold(r, 0.3, 1.2, pressed=1) + assert r.emergency_t == [] + assert r.disengage_t == [] + assert r.dh.lane_change_state == LaneChangeState.laneChangeStarting + # Opposite direction: 70 ms over the torque line is not an emergency either. + r = _armed_left() + _hold(r, 0.05, -0.3) + _hold(r, EMERGENCY_SUSTAIN_S - 0.03, -2.8, pressed=1) + _hold(r, 0.3, -0.3) + assert r.emergency_t == [] + assert r.disengage_t == [] + + +def test_hard_confirm_peak_is_not_a_takeover(): + # Logged hard confirms (2.3-3.3 Nm) stay over 2.5 Nm for <= ~0.1 s; + # 0.2 s is still a confirm, not a takeover. + r = _armed_left() + for k in range(50): # 0.3 -> 2.8 Nm over 0.5 s (not a fast rise) + r.step((0.3 + 2.5 * (k + 1) / 50, 1, 0, 1, 0, 1, 20.0)) + _hold(r, 0.2, 2.8, pressed=1, hands=2) # ~0.26 s over 2.5 Nm in total + _hold(r, 0.3, 0.2) + assert r.takeover_t == [] + assert r.emergency_t == [] + assert r.disengage_t == [] + assert r.first_t(LaneChangeState.laneChangeStarting) is not None + + +def test_road_bumps_and_crown_do_not_confirm(): + r = _armed_left(v=45 * MPH) + v = 45 * MPH + # Hands-off lane keep: |tq| p99.9 ~0.5 Nm; crown bias held. + _hold(r, 1.0, 0.50, v=v) + # Single-sample bumps up to 1.0 Nm (one 10 Hz sample, 100 ms interpolated). + for _ in range(5): + for row in _upsample([(0.1, 0, 0, 1, 0, 0, v), (1.0, 0, 0, 1, 0, 0, v), (0.1, 0, 0, 1, 0, 0, v)]): + r.step(row) + # Washboard: +/-0.8 Nm alternating every 50 ms. + for k in range(40): + _hold(r, 0.05, 0.8 if k % 2 == 0 else -0.8, v=v) + # Just under the line, held. + _hold(r, 1.0, SOFT_CONFIRM_NM - 0.03, v=v) + assert r.dh.lane_change_state == LaneChangeState.preLaneChange + assert r.first_t(LaneChangeState.laneChangeStarting) is None + assert r.disengage_t == [] + + +def test_soft_confirm_needs_the_sustain_time(): + r = _armed_left(v=45 * MPH) + _hold(r, SOFT_CONFIRM_SUSTAIN_S - 0.06, 0.8, v=45 * MPH) + _hold(r, 0.2, 0.1, v=45 * MPH) + assert r.dh.lane_change_state == LaneChangeState.preLaneChange + _hold(r, SOFT_CONFIRM_SUSTAIN_S + 0.06, 0.8, v=45 * MPH) + assert r.dh.lane_change_state == LaneChangeState.laneChangeStarting + + +def test_soft_confirm_only_same_direction_and_at_speed(): + r = _armed_left(v=45 * MPH) + _hold(r, 1.0, -0.9, v=45 * MPH) # opposite, below steeringPressed + assert r.dh.lane_change_state == LaneChangeState.preLaneChange + slow = 19 * MPH + r = _armed_left(v=slow) + _hold(r, 1.0, 0.9, v=slow) + assert r.dh.lane_change_state == LaneChangeState.preLaneChange + t = SoftConfirmTracker() + assert not any(t.update(torque_nm=0.9, direction=1, armed=False, dt=0.05) for _ in range(10)) + assert not any(t.update(torque_nm=-0.9, direction=1, armed=True, dt=0.05) for _ in range(10)) + assert not any(t.update(torque_nm=0.9, direction=0, armed=True, dt=0.05) for _ in range(10)) + assert any(t.update(torque_nm=-0.9, direction=2, armed=True, dt=0.05) for _ in range(10)) + + +def test_opposite_pull_still_cancels_after_soft_confirm(): + r = _armed_left(v=45 * MPH) + _hold(r, 0.25, 0.8, v=45 * MPH) + assert r.dh.lane_change_state == LaneChangeState.laneChangeStarting + assert r.dh.target_locked + _hold(r, 0.1, -1.1, pressed=1, hands=1, v=45 * MPH) + assert r.dh.lane_change_state == LaneChangeState.laneChangeStarting # spring-back length + _hold(r, 0.2, -1.1, pressed=1, hands=1, v=45 * MPH) + assert r.dh.lane_change_state == LaneChangeState.off + + +def test_unarmed_nudge_unchanged(): + # No stalk tip: the E3 nudge on its own is ordinary lane-keep override. + r = Replay() + trace = [(tq, p, 0, 0, 0, h, v) for tq, p, _s, _l, _r, h, v in E3_LEFT_1106] + r.run(trace) + assert r.first_t(LaneChangeState.preLaneChange) is None + assert r.first_t(LaneChangeState.laneChangeStarting) is None + assert r.disengage_t == [] + # Light held torque with no lane change armed does nothing. + r = Replay() + _hold(r, 1.0, 0.9, left=0, v=45 * MPH) + assert r.dh.lane_change_state == LaneChangeState.off + # Hands-on level 2 edge with no blinker still disengages as before. + r = Replay() + _hold(r, 0.1, 0.2, left=0) + _hold(r, 0.05, 1.5, pressed=1, hands=2, left=0) + assert r.disengage_t + + +def _assert_logged_confirm(trace, direction): + r = Replay().run(trace, src_hz=20) + assert r.disengage_t == [] + assert r.emergency_t == [] + assert r.takeover_t == [] + assert r.first_t(LaneChangeState.laneChangeStarting) is not None + assert r.dh.lane_change_direction == direction + return r + + +def test_sep28_1037_right_confirm_still_confirms(): + _assert_logged_confirm(OK_RIGHT_1037, LaneChangeDirection.right) + + +def test_sep28_1101_left_confirm_still_confirms(): + _assert_logged_confirm(OK_LEFT_1101, LaneChangeDirection.left) + + +def test_sep28_1111_right_confirm_still_confirms(): + _assert_logged_confirm(OK_RIGHT_1111, LaneChangeDirection.right) + + +def test_sep28_1110_light_torque_timeout_does_not_soft_confirm(): + r = Replay().run(TIMEOUT_RIGHT_1110) + assert r.first_t(LaneChangeState.preLaneChange) is not None + assert r.first_t(LaneChangeState.laneChangeStarting) is None + assert r.disengage_t == [] + assert r.emergency_t == [] + assert r.takeover_t == [] diff --git a/selfdrive/controls/lib/tests/test_lane_change_lock.py b/selfdrive/controls/lib/tests/test_lane_change_lock.py new file mode 100644 index 00000000000000..bf52e770f872bb --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lane_change_lock.py @@ -0,0 +1,259 @@ +"""Lane-change lock robustness (Sep 29 2026, route 0000012f--6b1fe62a0c, build c54b4c2). + +12:00:48 and 12:00:51 CT, left tips at ~40 mph. The ego RIGHT line prob was 0.20 / 0.13 +(< 0.4) with the left line at 0.96 / 0.94, so lock() refused and DesireHelper cancelled +("lane lines too weak"). Only the line being crossed has to be seen; the far line may be +weak. A refused lock keeps the change armed and retries, then says "Lane lines unclear". +""" + +import pytest + +from cereal import log + +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.desire_helper import ( + DT_MDL, + DesireHelper, + LaneChangeState, +) +from openpilot.selfdrive.controls.lib.lane_change_target import ( + LANE_LINES_UNCLEAR_SIGNAL, + LOCK_RETRY_S, + LaneChangeTarget, +) +from openpilot.selfdrive.controls.lib.tests.test_lane_change_target import ( + FIRM_NUDGE_NM, + LANE_W, + _CS, + _Line, +) + + +class _ModelLines: + """modelV2-like model with explicit ego line offsets / probs (+y right).""" + + def __init__(self, left_y, right_y, left_p, right_p): + ys = [left_y - LANE_W, left_y, right_y, right_y + LANE_W] + self.laneLines = [_Line(y) for y in ys] + self.laneLineProbs = [0.5, left_p, right_p, 0.5] + + +def _tip_and_confirm(dh, model_arm, model_confirm=None, direction=1, torque=FIRM_NUDGE_NM, pressed=True, hands_on=2): + lever = 1 if direction == 1 else 2 + left, right = direction == 1, direction == 2 + dh.update(_CS(), True, 0.0, model=model_arm, engaged=True) + dh.update(_CS(left=left, right=right, lever=lever), True, 0.0, model=model_arm, engaged=True) + dh.update(_CS(left=left, right=right, lever=0), True, 0.0, model=model_arm, engaged=True) + assert dh.lane_change_state == LaneChangeState.preLaneChange + sign = 1.0 if direction == 1 else -1.0 + dh.update(_CS(left=left, right=right, steering_pressed=pressed, steering_torque=sign * torque, hands_on=hands_on), + True, 0.0, model=model_confirm or model_arm, engaged=True) + + +def _nudge_frames(dh, model, seconds, direction=1, torque=FIRM_NUDGE_NM, pressed=True): + left, right = direction == 1, direction == 2 + sign = 1.0 if direction == 1 else -1.0 + for _ in range(int(round(seconds / DT_MDL))): + dh.update(_CS(left=left, right=right, steering_pressed=pressed, steering_torque=sign * torque, hands_on=1 if pressed else 0), + True, 0.0, model=model, engaged=True) + + +def test_sep29_1200_48_left_right_line_020_locks_on_left_line(): + dh = DesireHelper() + m = _ModelLines(-1.59, 1.95, 0.96, 0.20) + _tip_and_confirm(dh, m, torque=1.59) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.target_locked + assert dh.target.line_y == pytest.approx(-1.59) + assert dh.target.lane_width == pytest.approx(3.7) + assert dh.desire == log.Desire.laneChangeLeft + + +def test_sep29_1200_51_left_right_line_013_soft_confirm_locks(): + dh = DesireHelper() + m = _ModelLines(-1.50, 1.97, 0.94, 0.13) + # Soft confirm only (0.7 Nm, steeringPressed still false), held >= 0.15 s. + _tip_and_confirm(dh, m, torque=0.7, pressed=False, hands_on=0) + assert dh.lane_change_state == LaneChangeState.preLaneChange + _nudge_frames(dh, m, 0.3, torque=0.7, pressed=False) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.target_locked + assert dh.target.line_y == pytest.approx(-1.50) + + +def test_far_line_weak_uses_last_good_lane_width(): + dh = DesireHelper() + good = _ModelLines(-1.6, 1.8, 0.9, 0.9) # width 3.4 + dh.update(_CS(), True, 0.0, model=good, engaged=True) + weak = _ModelLines(-1.6, 1.8, 0.9, 0.1) + _tip_and_confirm(dh, weak) + assert dh.target_locked + assert dh.target.lane_width == pytest.approx(3.4) + + +def test_right_change_needs_only_the_right_line(): + dh = DesireHelper() + m = _ModelLines(-1.9, 1.7, 0.1, 0.95) + _tip_and_confirm(dh, m, direction=2) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.target.line_y == pytest.approx(1.7) + assert dh.target.direction == 2 + + +def test_lock_refuses_when_the_crossing_line_is_on_the_wrong_side(): + assert LaneChangeTarget.lock(1, ([0.0, 0.4, 1.9, 5.6], [0.5, 0.9, 0.1, 0.5])) is None + assert LaneChangeTarget.lock(2, ([0.0, -1.9, -0.3, 3.4], [0.5, 0.1, 0.9, 0.5])) is None + + +def test_brief_crossing_line_dip_retries_and_locks(): + dh = DesireHelper() + good = _ModelLines(-1.8, 1.8, 0.9, 0.9) + dip = _ModelLines(-1.8, 1.8, 0.1, 0.9) + _tip_and_confirm(dh, dip) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert not dh.target_locked + _nudge_frames(dh, dip, 0.4) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert not dh.lane_lines_unclear + _nudge_frames(dh, good, DT_MDL) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.target_locked + + +def test_weak_crossing_line_waits_shows_unclear_and_never_silently_cancels(): + dh = DesireHelper() + weak = _ModelLines(-1.8, 1.8, 0.1, 0.9) + _tip_and_confirm(dh, weak) + _nudge_frames(dh, weak, LOCK_RETRY_S + 0.2) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert not dh.target_locked + assert dh.desire == log.Desire.none + assert dh.lane_lines_unclear + assert dh.signals_remaining == LANE_LINES_UNCLEAR_SIGNAL + # Stays armed (not cancelled, next tip not suppressed) until the 7 s arm window. + _nudge_frames(dh, weak, 3.0, torque=0.0, pressed=False) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert not dh._suppress_next_tip + assert not dh.lane_lines_unclear + assert dh.signals_remaining < LANE_LINES_UNCLEAR_SIGNAL + _nudge_frames(dh, weak, 4.0, torque=0.0, pressed=False) + assert dh.lane_change_state == LaneChangeState.off + + +def test_line_returns_after_retry_ran_out_locks_while_nudge_held(): + dh = DesireHelper() + weak = _ModelLines(-1.8, 1.8, 0.1, 0.9) + good = _ModelLines(-1.8, 1.8, 0.9, 0.9) + _tip_and_confirm(dh, weak) + _nudge_frames(dh, weak, LOCK_RETRY_S + 0.5) + assert dh.lane_lines_unclear + _nudge_frames(dh, good, DT_MDL) + assert dh.target_locked + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert not dh.lane_lines_unclear + + +def test_released_nudge_after_retry_ran_out_does_not_lock_later(): + dh = DesireHelper() + weak = _ModelLines(-1.8, 1.8, 0.1, 0.9) + good = _ModelLines(-1.8, 1.8, 0.9, 0.9) + _tip_and_confirm(dh, weak) + _nudge_frames(dh, weak, LOCK_RETRY_S + 0.2) + _nudge_frames(dh, weak, 0.5, torque=0.0, pressed=False) + _nudge_frames(dh, good, 0.5, torque=0.0, pressed=False) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert not dh.target_locked + + +def test_emergency_yank_still_cancels_a_pending_lock(): + dh = DesireHelper() + weak = _ModelLines(-1.8, 1.8, 0.1, 0.9) + _tip_and_confirm(dh, weak) + assert dh.lane_change_state == LaneChangeState.preLaneChange + # Opposite-direction yank (emergency) cancels even while the lock retries. + for _ in range(10): + dh.update(_CS(left=True, steering_pressed=True, steering_torque=-3.5, hands_on=3), True, 0.0, model=weak, engaged=True) + assert dh.lane_change_state == LaneChangeState.off + + +def test_below_speed_confirm_does_not_lock_or_retry(): + dh = DesireHelper() + good = _ModelLines(-1.8, 1.8, 0.9, 0.9) + slow = 10 * CV.MPH_TO_MS + dh.update(_CS(v_ego=slow), True, 0.0, model=good, engaged=True) + dh.update(_CS(left=True, lever=1, v_ego=slow), True, 0.0, model=good, engaged=True) + dh.update(_CS(left=True, lever=0, v_ego=slow), True, 0.0, model=good, engaged=True) + _nudge_frames_slow = [_CS(left=True, steering_pressed=True, steering_torque=FIRM_NUDGE_NM, hands_on=1, v_ego=slow)] * 20 + for cs in _nudge_frames_slow: + dh.update(cs, True, 0.0, model=good, engaged=True) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert not dh.target_locked + + +def test_unclear_alert_text_only_when_flagged(): + from openpilot.selfdrive.selfdrived.lane_change_alerts import pre_lane_change_alert + + class _Meta: + def __init__(self, n): + self.laneChangeSignalsRemaining = n + + class _M: + def __init__(self, n): + self.meta = _Meta(n) + + for left, mici in ((True, False), (False, False), (True, True)): + cb = pre_lane_change_alert(left, mici) + normal = cb(None, None, {'modelV2': _M(5)}, False, 1, None) + unclear = cb(None, None, {'modelV2': _M(LANE_LINES_UNCLEAR_SIGNAL)}, False, 1, None) + assert "Steer" in normal.alert_text_1 + assert unclear.alert_text_1 == "Lane lines unclear" + + +def test_pending_lock_is_dropped_if_speed_falls_under_20_mph_before_the_line_returns(): + dh = DesireHelper() + weak = _ModelLines(-1.8, 1.8, 0.1, 0.9) + good = _ModelLines(-1.8, 1.8, 0.9, 0.9) + slow = 10 * CV.MPH_TO_MS + _tip_and_confirm(dh, weak) + _nudge_frames(dh, weak, 0.3) + assert dh.lane_change_state == LaneChangeState.preLaneChange + for _ in range(6): + dh.update(_CS(left=True, steering_pressed=True, steering_torque=FIRM_NUDGE_NM, hands_on=1, v_ego=slow), + True, 0.0, model=weak, engaged=True) + for _ in range(10): + dh.update(_CS(left=True, steering_pressed=True, steering_torque=FIRM_NUDGE_NM, hands_on=1, v_ego=slow), + True, 0.0, model=good, engaged=True) + assert not dh.target_locked + assert dh.lane_change_state == LaneChangeState.preLaneChange + + +def test_pending_lock_is_dropped_on_blindspot_before_the_line_returns(): + dh = DesireHelper() + weak = _ModelLines(-1.8, 1.8, 0.1, 0.9) + good = _ModelLines(-1.8, 1.8, 0.9, 0.9) + _tip_and_confirm(dh, weak) + cs = _CS(left=True, steering_pressed=True, steering_torque=FIRM_NUDGE_NM, hands_on=1) + cs.leftBlindspot = True + for _ in range(6): + dh.update(cs, True, 0.0, model=weak, engaged=True) + for _ in range(10): + dh.update(cs, True, 0.0, model=good, engaged=True) + assert not dh.target_locked + assert dh.lane_change_state == LaneChangeState.preLaneChange + + +def test_unclear_alert_is_installed_over_the_stock_prompts(): + from openpilot.selfdrive.selfdrived.events import EVENTS, ET, Alert + from openpilot.selfdrive.selfdrived.lane_change_alerts import install_lane_change_alerts + + events = {log.OnroadEvent.EventName.preLaneChangeLeft: {ET.WARNING: Alert("x", "", 0, 0, 0, 0, 0, 0)}, + log.OnroadEvent.EventName.preLaneChangeRight: {ET.WARNING: Alert("x", "", 0, 0, 0, 0, 0, 0)}} + install_lane_change_alerts(events, mici=False) + assert all(callable(v[ET.WARNING]) for v in events.values()) + assert log.OnroadEvent.EventName.preLaneChangeLeft in EVENTS + + +def test_selfdrived_installs_the_unclear_alert(): + from pathlib import Path + src = (Path(__file__).resolve().parents[3] / "selfdrived/helpers.py").read_text() + assert "\ninstall_lane_change_alerts()\n" in src diff --git a/selfdrive/controls/lib/tests/test_lane_change_nudge.py b/selfdrive/controls/lib/tests/test_lane_change_nudge.py new file mode 100644 index 00000000000000..0dd4296f3ae77d --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lane_change_nudge.py @@ -0,0 +1,285 @@ +"""Same-direction lane-change confirm is not a takeover. Emergency yank is.""" + +from cereal import log + +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import ( + BlinkerLateralHold, + blinker_turn_blocks_steering_disengage, + lat_active_with_blinker_pause, +) +from openpilot.selfdrive.controls.lib.desire_helper import ( + DT_MDL, + DesireHelper, + LaneChangeDirection, + LaneChangeState, +) +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + SOFT_YIELD_DEBOUNCE_FRAMES, + SOFT_YIELD_TRIGGER_NM as HANDOFF_SOFT_NM, + DriverLateralHandoff, + lat_active_after_handoff, + required_press_frames, +) +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + EMERGENCY_HANDS_ON_LEVEL, + EMERGENCY_RISE_NM, + EMERGENCY_RISE_WINDOW_S, + EMERGENCY_SUSTAIN_S, + EMERGENCY_TORQUE_NM, + SOFT_YIELD_TRIGGER_NM, + EmergencyYankTracker, + is_emergency_yank, + steer_disengage_this_frame, + tipped_lane_change_driver_release, +) +from openpilot.selfdrive.controls.lib.stalk_tip_turn import STALK_TIP_HOLD_S + +FIRM_NUDGE_NM = 2.0 * SOFT_YIELD_TRIGGER_NM # 1.1 Nm, hands-on 1–2 still a confirm +MPH_45 = 45.0 * CV.MPH_TO_MS +MPH_12 = 12.0 * CV.MPH_TO_MS + + +class _CS: + def __init__(self, v_ego=MPH_45, left=False, right=False, + steering_pressed=False, steering_torque=0.0, + left_blindspot=False, right_blindspot=False, lever=0, + hands_on=0): + self.vEgo = v_ego + self.leftBlinker = left + self.rightBlinker = right + self.steeringPressed = steering_pressed + self.steeringTorque = steering_torque + self.leftBlindspot = left_blindspot + self.rightBlindspot = right_blindspot + self.turnSignalStalkState = lever + self.handsOnLevel = hands_on + + +def _arm_left(dh, v_ego=MPH_45): + dh.update(_CS(v_ego=v_ego), True, 0.0) + dh.update(_CS(v_ego=v_ego, left=True, lever=1), True, 0.0) + dh.update(_CS(v_ego=v_ego, left=True, lever=0), True, 0.0) + + +def _tip_alc_hold(): + """Stalk tip so BlinkerLateralHold enters ALC keep-alive.""" + hold = BlinkerLateralHold() + lat_active_with_blinker_pause( + active=True, steer_fault_temporary=False, steer_fault_permanent=False, + standstill=False, steer_at_standstill=False, left_blinker=True, right_blinker=False, + hold=hold, engaged=True, stalk_state=1, v_ego=MPH_45, dt=0.01) + lat_active_with_blinker_pause( + active=True, steer_fault_temporary=False, steer_fault_permanent=False, + standstill=False, steer_at_standstill=False, left_blinker=True, right_blinker=False, + hold=hold, engaged=True, stalk_state=0, v_ego=MPH_45, dt=0.01) + assert hold._alc_keep + assert not hold.turn_active + return hold + + +def test_thresholds_sit_above_a_firm_confirm(): + assert SOFT_YIELD_TRIGGER_NM == HANDOFF_SOFT_NM + assert FIRM_NUDGE_NM == 1.1 + assert FIRM_NUDGE_NM < EMERGENCY_TORQUE_NM + assert EMERGENCY_TORQUE_NM == 2.5 + assert EMERGENCY_RISE_NM == 4.0 * SOFT_YIELD_TRIGGER_NM == 2.2 + assert EMERGENCY_RISE_WINDOW_S == 0.250 + assert EMERGENCY_SUSTAIN_S == 0.10 + assert EMERGENCY_HANDS_ON_LEVEL == 3 + assert not is_emergency_yank(torque_nm=FIRM_NUDGE_NM, hands_on_level=2, fast_rise=False) + assert is_emergency_yank(torque_nm=0.2, hands_on_level=3, fast_rise=False) + assert is_emergency_yank(torque_nm=1.0, hands_on_level=1, fast_rise=False, over_torque=True) + assert not is_emergency_yank(torque_nm=EMERGENCY_TORQUE_NM + 0.1, hands_on_level=1, fast_rise=False, + over_torque=False) + # Legacy callers without a tracker keep the instantaneous line. + assert is_emergency_yank(torque_nm=EMERGENCY_TORQUE_NM + 0.1, hands_on_level=1, fast_rise=False) + assert not tipped_lane_change_driver_release(same_direction=True, emergency=False) + assert tipped_lane_change_driver_release(same_direction=True, emergency=True) + assert not tipped_lane_change_driver_release(same_direction=False, emergency=False) + + +def test_tip_at_45_same_direction_nudge_confirms_through_flash_gap(): + """Firm same-direction nudge starts the change and is not a takeover.""" + dh = DesireHelper() + _arm_left(dh, MPH_45) + assert dh.lane_change_state == LaneChangeState.preLaneChange + + nudge = _CS(v_ego=MPH_45, left=True, steering_pressed=True, + steering_torque=FIRM_NUDGE_NM, hands_on=2) + dh.update(nudge, True, 1.0) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.lane_change_direction == LaneChangeDirection.left + assert dh.desire == log.Desire.laneChangeLeft + + # Lamp flash-dark gap while the confirm torque is still on the wheel. + dark = _CS(v_ego=MPH_45, left=False, steering_pressed=True, + steering_torque=FIRM_NUDGE_NM, hands_on=2) + for _ in range(int(0.40 / DT_MDL)): + dh.update(dark, True, 1.0) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.lane_change_direction == LaneChangeDirection.left + + h = DriverLateralHandoff(enabled=True) + out = None + for _ in range(max(SOFT_YIELD_DEBOUNCE_FRAMES, required_press_frames(FIRM_NUDGE_NM)) + 5): + out = h.update( + engaged=True, lat_would_be_active=True, steering_torque=FIRM_NUDGE_NM, + steering_rate_deg=0.0, alc_active=True, hands_on_level=2, + lane_change_confirm=True, emergency_yank=False, v_ego=MPH_45) + assert out is not None + assert not out.yielded + assert out.authority == 1.0 + assert lat_active_after_handoff(True, out.yielded) + + hold = BlinkerLateralHold() + assert lat_active_with_blinker_pause( + active=True, steer_fault_temporary=False, steer_fault_permanent=False, + standstill=False, steer_at_standstill=False, left_blinker=True, right_blinker=False, + steering_pressed=True, steering_disengage=True, hold=hold, alc_active=True, + v_ego=MPH_45, stalk_state=0, soft_lat_on=True, engaged=True, dt=0.01) + assert lat_active_with_blinker_pause( + active=True, steer_fault_temporary=False, steer_fault_permanent=False, + standstill=False, steer_at_standstill=False, left_blinker=False, right_blinker=False, + steering_pressed=True, steering_disengage=True, hold=hold, alc_active=True, + v_ego=MPH_45, stalk_state=0, soft_lat_on=True, engaged=True, dt=0.40) + assert not hold.turn_active + assert hold._alc_keep + # Flash-dark gap, hands-on level 2: still not a steering disengage. + assert blinker_turn_blocks_steering_disengage( + False, False, 0, hold, emergency=False, alc_confirm=True) + assert not steer_disengage_this_frame( + confirm=True, release=False, release_prev=False, + disengage_edge=True, blocks=False) + + # Maneuver still completes after the gap. + for _ in range(int(0.6 / DT_MDL)): + dh.update(dark, True, 0.0) + assert dh.lane_change_state == LaneChangeState.laneChangeFinishing + for _ in range(int(1.5 / DT_MDL)): + dh.update(_CS(v_ego=MPH_45), True, 0.0) + if dh.lane_change_state != LaneChangeState.laneChangeFinishing: + break + assert dh.lane_change_state == LaneChangeState.off + + +def test_opposite_direction_nudge_does_not_confirm(): + """Opposite torque does not start the change and still soft-yields as today.""" + dh = DesireHelper() + _arm_left(dh, MPH_45) + dh.update(_CS(v_ego=MPH_45, left=True, steering_pressed=True, + steering_torque=-FIRM_NUDGE_NM, hands_on=2), True, 0.0) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.desire == log.Desire.none + + # Armed ALC still suppresses soft-lat in both directions (today). + h = DriverLateralHandoff(enabled=True) + out = None + for _ in range(SOFT_YIELD_DEBOUNCE_FRAMES + 2): + out = h.update( + engaged=True, lat_would_be_active=True, steering_torque=-FIRM_NUDGE_NM, + steering_rate_deg=30.0, alc_active=True, hands_on_level=1, v_ego=MPH_45) + assert out is not None + assert not out.yielded + assert out.authority == 1.0 + + # Not a same-direction confirm: a firm push still yields. + h = DriverLateralHandoff(enabled=True) + out = None + frames = max(SOFT_YIELD_DEBOUNCE_FRAMES, required_press_frames(FIRM_NUDGE_NM)) + for _ in range(frames): + out = h.update( + engaged=True, lat_would_be_active=True, steering_torque=-FIRM_NUDGE_NM, + steering_rate_deg=30.0, alc_active=False, hands_on_level=1, v_ego=MPH_45) + assert out is not None + assert out.yielded + assert not lat_active_after_handoff(True, out.yielded) + + +def test_latched_stalk_is_still_a_driver_turn(): + dh = DesireHelper() + dh.update(_CS(v_ego=MPH_45), True, 0.0) + n = int(round(STALK_TIP_HOLD_S / DT_MDL)) + 2 + for _ in range(n): + dh.update(_CS(v_ego=MPH_45, left=True, lever=1), True, 1.0) + assert dh.lane_change_state == LaneChangeState.off + assert dh._tip_turn.is_turn + + hold = BlinkerLateralHold() + dt = 0.01 + steps = int(round(STALK_TIP_HOLD_S / dt)) + 2 + lat = True + for _ in range(steps): + lat = lat_active_with_blinker_pause( + active=True, steer_fault_temporary=False, steer_fault_permanent=False, + standstill=False, steer_at_standstill=False, left_blinker=True, right_blinker=False, + hold=hold, v_ego=MPH_45, stalk_state=1, soft_lat_on=False, engaged=True, dt=dt) + assert not lat + assert hold.turn_active + + +def test_tip_at_low_speed_still_arms_and_does_not_start(): + dh = DesireHelper() + _arm_left(dh, MPH_12) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.lane_change_direction == LaneChangeDirection.left + dh.update(_CS(v_ego=MPH_12, left=True, steering_pressed=True, + steering_torque=FIRM_NUDGE_NM), True, 0.0) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.desire == log.Desire.none + + +def test_emergency_yank_same_direction_releases_and_cancels(): + dh = DesireHelper() + _arm_left(dh, MPH_45) + assert dh.lane_change_state == LaneChangeState.preLaneChange + # Hard same-direction yank held past the sustain time. + yank = _CS(v_ego=MPH_45, left=True, steering_pressed=True, + steering_torque=EMERGENCY_TORQUE_NM + 0.25, hands_on=2) + for _ in range(int(round(EMERGENCY_SUSTAIN_S / DT_MDL)) + 1): + if dh.lane_change_state == LaneChangeState.off: + break + dh.update(yank, True, 0.0) + assert dh.lane_change_state == LaneChangeState.off + assert dh.queued_changes == 0 + + h = DriverLateralHandoff(enabled=True) + out = h.update( + engaged=True, lat_would_be_active=True, steering_torque=FIRM_NUDGE_NM, + steering_rate_deg=0.0, alc_active=True, hands_on_level=EMERGENCY_HANDS_ON_LEVEL, + emergency_yank=True, lane_change_confirm=False, v_ego=MPH_45) + assert out.yielded + assert out.authority == 0.0 + assert not lat_active_after_handoff(True, out.yielded) + + hold = _tip_alc_hold() + assert not blinker_turn_blocks_steering_disengage( + False, False, 0, hold, emergency=True, alc_confirm=True) + assert steer_disengage_this_frame( + confirm=False, release=True, release_prev=False, + disengage_edge=True, blocks=True) + + +def test_fast_torque_rise_is_an_emergency_yank(): + tracker = EmergencyYankTracker() + assert not tracker.update(0.0, 0.01) + # One frame above the line is not enough; it must be held 0.10 s. + assert not tracker.update(EMERGENCY_RISE_NM, 0.05) + assert not tracker.update(EMERGENCY_RISE_NM, EMERGENCY_SUSTAIN_S - 0.001) + assert tracker.update(EMERGENCY_RISE_NM, 0.001) + assert is_emergency_yank(torque_nm=EMERGENCY_RISE_NM, hands_on_level=1, fast_rise=True) + + # A slow climb through 4x soft-lat is not the fast-rise case. + slow = EmergencyYankTracker() + slow.update(0.0, 0.01) + assert not slow.update(SOFT_YIELD_TRIGGER_NM, 0.30) + for _ in range(5): + assert not slow.update(EMERGENCY_RISE_NM, 0.10) + + dh = DesireHelper() + _arm_left(dh, MPH_45) + dh.update(_CS(v_ego=MPH_45, left=True, steering_torque=0.0), True, 1.0) + for _ in range(int(round(EMERGENCY_SUSTAIN_S / DT_MDL)) + 1): + dh.update(_CS(v_ego=MPH_45, left=True, steering_pressed=True, + steering_torque=EMERGENCY_RISE_NM, hands_on=1), True, 1.0) + assert dh.lane_change_state == LaneChangeState.off diff --git a/selfdrive/controls/lib/tests/test_lane_change_target.py b/selfdrive/controls/lib/tests/test_lane_change_target.py new file mode 100644 index 00000000000000..c17354cbbd6157 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lane_change_target.py @@ -0,0 +1,391 @@ +"""Target-locked tipped lane change. + +A tipped lane change locks its direction and the lane line to cross when +it starts. It runs until the car is centered in the target lane. Only an +opposite pull, an emergency yank, an opposite tip, the lock timeout, or +low-confidence lane lines end it early. An ordinary lateral release +pauses it and it resumes toward the locked target. +""" + +import pytest + +from cereal import log + +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.desire_helper import ( + DT_MDL, + OPPOSITE_PULL_NM, + OPPOSITE_PULL_SUSTAIN_S, + DesireHelper, + LaneChangeDirection, + LaneChangeState, +) +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + DriverLateralHandoff, + lat_active_after_handoff, +) +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + EMERGENCY_SUSTAIN_S, + EMERGENCY_TORQUE_NM, + SOFT_YIELD_TRIGGER_NM, +) +from openpilot.selfdrive.controls.lib.lane_change_target import ( + CENTERED_HOLD_S, + CENTERED_TOL_M, + LANE_LINE_MIN_PROB, + LOW_CONFIDENCE_CANCEL_S, + TARGET_LOCK_TIMEOUT_S, + STALL_REPULSE_S, + LaneChangeTarget, + lane_line_offsets, +) + +FIRM_NUDGE_NM = 2.0 * SOFT_YIELD_TRIGGER_NM # 1.1 Nm +MPH_45 = 45.0 * CV.MPH_TO_MS +LANE_W = 3.7 +# World lane lines, +y right. Car starts centered in the lane between +# -1.85 and +1.85. Left target lane center is -3.7, right is +3.7. +WORLD_LINES = [-1.85 - k * LANE_W for k in range(4, -1, -1)] + [1.85 + k * LANE_W for k in range(5)] + + +class _CS: + def __init__(self, left=False, right=False, steering_pressed=False, + steering_torque=0.0, lever=0, hands_on=0, v_ego=MPH_45): + self.vEgo = v_ego + self.leftBlinker = left + self.rightBlinker = right + self.steeringPressed = steering_pressed + self.steeringTorque = steering_torque + self.leftBlindspot = False + self.rightBlindspot = False + self.turnSignalStalkState = lever + self.handsOnLevel = hands_on + + +class _Line: + def __init__(self, y): + self.y = [y, y, y] + + +class _Model: + """modelV2-like laneLines / laneLineProbs for a car at world y = ``car_y``.""" + + def __init__(self, car_y, prob=0.9): + rel = sorted(w - car_y for w in WORLD_LINES) + left = [y for y in rel if y < 0.0] + right = [y for y in rel if y >= 0.0] + ys = [left[-2], left[-1], right[0], right[1]] + self.laneLines = [_Line(y) for y in ys] + self.laneLineProbs = [prob] * 4 + + +def _arm(dh, car_y=0.0, direction=1): + lever = 1 if direction == 1 else 2 + left, right = direction == 1, direction == 2 + m = _Model(car_y) + dh.update(_CS(), True, 0.0, model=m, engaged=True) + dh.update(_CS(left=left, right=right, lever=lever), True, 0.0, model=m, engaged=True) + dh.update(_CS(left=left, right=right, lever=0), True, 0.0, model=m, engaged=True) + assert dh.lane_change_state == LaneChangeState.preLaneChange + + +def _start(dh, car_y=0.0, direction=1): + """Tip then confirm nudge: target locked, laneChangeStarting.""" + _arm(dh, car_y, direction) + torque = FIRM_NUDGE_NM if direction == 1 else -FIRM_NUDGE_NM + dh.update(_CS(left=direction == 1, right=direction == 2, steering_pressed=True, + steering_torque=torque, hands_on=2), True, 0.0, + model=_Model(car_y), engaged=True) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.target_locked + want = log.Desire.laneChangeLeft if direction == 1 else log.Desire.laneChangeRight + assert dh.desire == want + + +def _step(dh, car_y, cs=None, lat=True, prob=0.9, engaged=True): + dh.update(cs or _CS(), lat, 0.0, model=_Model(car_y, prob), engaged=engaged) + + +def _drive_to(dh, start_y, end_y, speed=1.0, cs=None): + """Move the car laterally at ``speed`` m/s; returns desires seen.""" + desires = [] + y = start_y + step = speed * DT_MDL * (1 if end_y >= start_y else -1) + while (end_y - y) * step > 0 and dh.lane_change_state != LaneChangeState.off: + y += step + if (end_y - y) * step < 0: + y = end_y + _step(dh, y, cs) + desires.append(dh.desire) + return y, desires + + +def _hold(dh, car_y, seconds, cs=None, lat=True): + desires = [] + for _ in range(int(round(seconds / DT_MDL))): + _step(dh, car_y, cs, lat=lat) + desires.append(dh.desire) + return desires + + +def _assert_asserted_with_only_repulse_gaps(desires, want): + """Desire held; the only gaps are single-frame stall re-pulses.""" + for i, d in enumerate(desires): + if d != want: + assert d == log.Desire.none + assert i + 1 >= int(STALL_REPULSE_S / DT_MDL) - 5 + assert i + 1 == len(desires) or desires[i + 1] == want + assert i == 0 or desires[i - 1] == want + + +def test_lock_records_direction_and_ego_line(): + t = LaneChangeTarget.lock(1, lane_line_offsets(_Model(0.0))) + assert t.direction == 1 + assert t.line_y == pytest.approx(-1.85) + assert t.lane_width == pytest.approx(LANE_W) + assert t.progress == pytest.approx(0.0) + t = LaneChangeTarget.lock(2, lane_line_offsets(_Model(0.0))) + assert t.line_y == pytest.approx(1.85) + # Line followed through the laneLines re-index while crossing. + for car_y in (1.0, 1.8, 1.9, 2.5, 3.1, 3.7): + t.update(lane_line_offsets(_Model(car_y)), DT_MDL) + assert t.line_y == pytest.approx(1.85 - car_y) + assert t.crossed + assert t.progress == pytest.approx(1.0) + assert t.center_error_m == pytest.approx(0.0) + + +def test_completes_when_centered_in_target_lane_not_on_a_timer(): + dh = DesireHelper() + _start(dh) + # Just past the line: crossed (finishing) but not centered. + y, desires = _drive_to(dh, 0.0, -2.3) + assert all(d == log.Desire.laneChangeLeft for d in desires) + assert dh.lane_change_state == LaneChangeState.laneChangeFinishing + # lane_change_prob 0 and long enough for the legacy fade: still going. + desires = _hold(dh, y, 5.0) + assert dh.lane_change_state == LaneChangeState.laneChangeFinishing + _assert_asserted_with_only_repulse_gaps(desires, log.Desire.laneChangeLeft) + # The stalled car got a fresh desire pulse (one-frame gap) to finish. + assert log.Desire.none in desires + y, _ = _drive_to(dh, y, -3.7) + _hold(dh, y, CENTERED_HOLD_S + 2 * DT_MDL) + assert dh.lane_change_state == LaneChangeState.off + assert dh.desire == log.Desire.none + assert not dh.target_locked + + +def test_same_direction_bump_mid_change_continues_with_no_pause(): + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, -1.0) + bump = _CS(left=True, steering_pressed=True, steering_torque=FIRM_NUDGE_NM, hands_on=2) + state_before = dh.lane_change_state + # Repeated same-direction bumps while the car keeps moving. + y, desires = _drive_to(dh, y, -2.6, cs=bump) + assert all(d == log.Desire.laneChangeLeft for d in desires) + assert dh.lane_change_direction == LaneChangeDirection.left + assert dh.target_locked and not dh.target_suspended + assert state_before == LaneChangeState.laneChangeStarting + # Held bump with no progress for a moment: still asserted. + desires = _hold(dh, y, 1.0, cs=bump) + assert all(d == log.Desire.laneChangeLeft for d in desires) + # Lateral authority stays full on a same-direction confirm. + h = DriverLateralHandoff(enabled=True) + for _ in range(50): + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=FIRM_NUDGE_NM, + steering_rate_deg=0.0, alc_active=True, hands_on_level=2, + lane_change_confirm=True, emergency_yank=False, v_ego=MPH_45) + assert not out.yielded and out.authority == 1.0 + assert lat_active_after_handoff(True, out.yielded) + y, _ = _drive_to(dh, y, -3.7, cs=bump) + _hold(dh, y, CENTERED_HOLD_S + 2 * DT_MDL) + assert dh.lane_change_state == LaneChangeState.off + + +@pytest.mark.parametrize("pull_at", [-0.5, -1.6, -2.4]) +def test_opposite_pull_cancels(pull_at): + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, pull_at) + assert dh.target_locked + pull = _CS(left=True, steering_pressed=True, steering_torque=-FIRM_NUDGE_NM, hands_on=1) + frames = int(round(OPPOSITE_PULL_SUSTAIN_S / DT_MDL)) + for _ in range(frames - 1): + _step(dh, y, pull) + assert dh.lane_change_state != LaneChangeState.off, "cancelled before the sustain time" + _step(dh, y, pull) + assert dh.lane_change_state == LaneChangeState.off + assert dh.desire == log.Desire.none + assert not dh.target_locked + # Does not come back afterwards. + desires = _hold(dh, y, 3.0) + assert all(d == log.Desire.none for d in desires) + assert dh.lane_change_state == LaneChangeState.off + + +def test_confirm_spring_back_does_not_cancel(): + # Logged confirm pushes spring back one 10 Hz sample against the change + # while steeringPressed is still set (e.g. -2.52 -> +1.22 Nm). + assert OPPOSITE_PULL_NM == SOFT_YIELD_TRIGGER_NM + assert OPPOSITE_PULL_SUSTAIN_S == 0.20 + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, -0.5) + assert dh.target_locked + back = _CS(left=True, steering_pressed=True, steering_torque=-1.3, hands_on=1) + light = _CS(left=True, steering_pressed=True, steering_torque=-(OPPOSITE_PULL_NM - 0.05), hands_on=1) + for _ in range(3): + _step(dh, y, back) + _step(dh, y, back) + _step(dh, y) + for _ in range(20): + _step(dh, y, light) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + assert dh.target_locked + + +def test_same_direction_emergency_yank_cancels_and_does_not_resume(): + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, -1.2) + yank = _CS(left=True, steering_pressed=True, + steering_torque=EMERGENCY_TORQUE_NM + 0.25, hands_on=3) + # Same-direction level 3 alone is a firm confirm; the hard torque must + # be held EMERGENCY_SUSTAIN_S (0.10 s = 3 model frames incl. the first). + for _ in range(int(round(EMERGENCY_SUSTAIN_S / DT_MDL)) + 1): + _step(dh, y, yank, lat=False) + assert dh.lane_change_state == LaneChangeState.off + assert dh.queued_changes == 0 + assert not dh.target_locked + # Handoff releases immediately on the yank. + h = DriverLateralHandoff(enabled=True) + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=EMERGENCY_TORQUE_NM + 0.25, + steering_rate_deg=0.0, alc_active=True, hands_on_level=3, + emergency_yank=True, lane_change_confirm=False, v_ego=MPH_45) + assert out.yielded and not lat_active_after_handoff(True, out.yielded) + # Hands still on, lat down, then hands off and lat back: no resume. + _hold(dh, y, 1.0, cs=_CS(steering_pressed=True, steering_torque=1.2, hands_on=1), lat=False) + desires = _hold(dh, y, 4.0) + assert all(d == log.Desire.none for d in desires) + assert dh.lane_change_state == LaneChangeState.off + + +def test_ordinary_release_pauses_then_resumes_to_target(): + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, -1.0) + desires = _hold(dh, y, 1.0, lat=False) + assert all(d == log.Desire.none for d in desires) + assert dh.target_locked and dh.target_suspended + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + # Lat back: desire re-asserted on the very next frame (fresh rising edge). + _step(dh, y) + assert dh.desire == log.Desire.laneChangeLeft + assert not dh.target_suspended + y, desires = _drive_to(dh, y, -3.7) + assert all(d == log.Desire.laneChangeLeft for d in desires) + _hold(dh, y, CENTERED_HOLD_S + 2 * DT_MDL) + assert dh.lane_change_state == LaneChangeState.off + + +@pytest.mark.parametrize("resume_at", [-0.4, -1.3, -1.8, -2.0, -2.8, -3.2]) +def test_resume_from_partially_over_finishes_centered_in_target_lane(resume_at): + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, resume_at) + # Driver/other release moves the car with lat down; target kept. + _hold(dh, y, 0.5, lat=False) + assert dh.target_locked + _step(dh, y) + assert dh.desire == log.Desire.laneChangeLeft + assert dh.lane_change_state != LaneChangeState.off + # Not complete short of center, however far over it already was. + y, desires = _drive_to(dh, y, -3.7 + CENTERED_TOL_M + 0.15) + assert all(d == log.Desire.laneChangeLeft for d in desires) + _hold(dh, y, 1.0) + assert dh.lane_change_state == LaneChangeState.laneChangeFinishing + y, _ = _drive_to(dh, y, -3.7) + _hold(dh, y, CENTERED_HOLD_S + 2 * DT_MDL) + assert dh.lane_change_state == LaneChangeState.off + + +def test_resume_right_change_from_partially_over(): + dh = DesireHelper() + _start(dh, direction=2) + y, _ = _drive_to(dh, 0.0, 2.2) + _hold(dh, y, 0.5, lat=False) + _step(dh, y) + assert dh.desire == log.Desire.laneChangeRight + y, _ = _drive_to(dh, y, 3.7) + _hold(dh, y, CENTERED_HOLD_S + 2 * DT_MDL) + assert dh.lane_change_state == LaneChangeState.off + + +def test_opposite_tip_cancels(): + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, -1.0) + _step(dh, y, _CS(right=True, lever=2)) + _step(dh, y, _CS(right=True, lever=0)) + assert dh.lane_change_state == LaneChangeState.off + assert not dh.target_locked + desires = _hold(dh, y, 2.0) + assert all(d == log.Desire.none for d in desires) + + +def test_timeout_cancels_including_released_time(): + assert 10.0 <= TARGET_LOCK_TIMEOUT_S <= 12.0 + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, -0.8) + _hold(dh, y, 3.0, lat=False) + # Stuck with no completion: still alive just before the timeout... + remaining = TARGET_LOCK_TIMEOUT_S - dh.target.age_s + _hold(dh, y, remaining - 0.5) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + # ...and cancelled after it, and a stale change never restarts. + _hold(dh, y, 1.0) + assert dh.lane_change_state == LaneChangeState.off + assert not dh.target_locked + desires = _hold(dh, y, 3.0) + assert all(d == log.Desire.none for d in desires) + + +def test_low_lane_line_confidence_cancels(): + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, -1.0) + low = LANE_LINE_MIN_PROB * 0.5 + # A short dropout is tolerated. + for _ in range(int(0.3 / DT_MDL)): + _step(dh, y, prob=low) + assert dh.lane_change_state == LaneChangeState.laneChangeStarting + _step(dh, y) + for _ in range(int(round(LOW_CONFIDENCE_CANCEL_S / DT_MDL)) + 1): + _step(dh, y, prob=low) + assert dh.lane_change_state == LaneChangeState.off + assert not dh.target_locked + assert dh.desire == log.Desire.none + + +def test_low_confidence_at_start_does_not_guess(): + """No confident crossing line: never lock or guess, but do not cancel either.""" + dh = DesireHelper() + _arm(dh) + dh.update(_CS(left=True, steering_pressed=True, steering_torque=FIRM_NUDGE_NM, hands_on=2), + True, 0.0, model=_Model(0.0, prob=0.1), engaged=True) + assert dh.lane_change_state == LaneChangeState.preLaneChange + assert dh.desire == log.Desire.none + assert not dh.target_locked + + +def test_disengage_drops_the_lock(): + dh = DesireHelper() + _start(dh) + y, _ = _drive_to(dh, 0.0, -1.0) + _step(dh, y, lat=False, engaged=False) + assert dh.lane_change_state == LaneChangeState.off + assert not dh.target_locked + desires = _hold(dh, y, 2.0) + assert all(d == log.Desire.none for d in desires) diff --git a/selfdrive/controls/lib/tests/test_lane_change_turn.py b/selfdrive/controls/lib/tests/test_lane_change_turn.py new file mode 100644 index 00000000000000..04f679ccab66f4 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lane_change_turn.py @@ -0,0 +1,622 @@ +"""Tip into a turn lane, then turn at the intersection mid-change. + +Harness: card (CarSpecificEvents, Pre-AP) + the controlsd lane-change +pieces (TippedLaneChangeTorque, LaneChangeTurnHold, BlinkerLateralHold, +DriverLateralHandoff with soft-lat On) at 100 Hz, DesireHelper with a +modelV2-like lane model at 20 Hz. Lamps follow CC.leftBlinker / +rightBlinker (and a latched physical stalk). +""" + +from pathlib import Path + +import pytest + +from cereal import car, log + +from openpilot.common.constants import CV +from openpilot.selfdrive.car.car_specific import CarSpecificEvents +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import ( + BlinkerLateralHold, + lat_active_with_blinker_pause, +) +from openpilot.selfdrive.controls.lib.desire_helper import ( + LANE_CHANGE_SPEED_MIN, + DesireHelper, + LaneChangeDirection, + LaneChangeState, +) +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + DriverLateralHandoff, + lat_active_after_handoff, +) +from openpilot.selfdrive.controls.lib.lane_change_nudge import ( + EMERGENCY_RISE_WINDOW_S, + EMERGENCY_TORQUE_NM, + SOFT_YIELD_TRIGGER_NM, + TippedLaneChangeTorque, +) +from openpilot.selfdrive.controls.lib.lane_change_turn import ( + HOLD_RESUME_SPEED, + LANE_CHANGE_SPEED_MIN as TURN_SPEED_MIN, + MODE_HOLD, + MODE_TURN, + TURN_ENTER_ANGLE_DEG, + TURN_EXIT_ANGLE_DEG, + TURN_EXIT_HOLD_S, + TURN_HOLD_TIMEOUT_S, + LaneChangeTurnHold, + blinker_with_turn_hold, + is_lane_change_turn, +) + +EventName = log.OnroadEvent.EventName +ROOT = Path(__file__).resolve().parents[4] +DT = 0.01 +MPH = CV.MPH_TO_MS +V_APPROACH = 25 * MPH + + +# Sep 28 11:13:18 CT, route 124 seg 14 (rlog carState, 20 Hz): the logged +# "emergency cancel" (-2.92 Nm). Right tip at 25.5 mph in a left curve; +# the car slowed under 20 mph while armed; the driver latched the stalk +# right at 11:13:20.29 and turned right hand over hand (wheel +5 -> -170 +# deg, -2.2 to -2.9 Nm held ~3 s). The old build ended the change and +# dropped lateral at 11:13:21.24 when torque crossed its instantaneous +# 2.0 Nm line; openpilot (and long) stayed engaged (no steerDisengage in +# onroadEvents). It was a sustained turn, not a yank: under 0.55 -> over +# 2.2 Nm took ~0.45 s (the fast-rise window is 0.25 s). +# (torque Nm, steeringPressed, stalk, vEgo m/s, wheel angle deg) +TURN_RIGHT_1113 = [ + (-0.25, 0, 0, 11.37, +25.6), + (-0.21, 0, 0, 11.38, +25.6), + (-0.08, 0, 0, 11.39, +25.6), + (+0.25, 0, 2, 11.40, +25.4), # 11:13:18.488 tip right, 25.5 mph + (+0.61, 0, 2, 11.41, +25.1), + (+0.34, 0, 0, 11.42, +24.6), + (-0.04, 0, 0, 11.43, +24.0), + (-0.08, 0, 0, 11.44, +23.6), + (-0.06, 0, 0, 11.44, +23.3), # 11:13:18.738 preLaneChange (log) + (-0.01, 0, 0, 11.45, +23.3), + (+0.05, 0, 0, 11.46, +23.2), + (+0.11, 0, 0, 11.47, +22.6), + (+0.18, 0, 0, 11.47, +21.8), + (+0.41, 0, 0, 11.48, +21.6), + (+0.69, 0, 0, 11.48, +21.4), + (+0.28, 0, 0, 11.48, +20.3), + (-0.26, 0, 0, 11.48, +18.9), + (+0.02, 0, 0, 11.49, +18.7), + (+0.45, 0, 0, 11.50, +18.6), + (+0.56, 0, 0, 11.40, +18.0), + (+0.60, 0, 0, 11.29, +17.3), + (+0.38, 0, 0, 11.25, +16.6), + (+0.10, 0, 0, 11.23, +16.0), + (+0.51, 0, 0, 11.18, +15.4), + (+1.03, 0, 0, 11.14, +14.9), + (+0.95, 1, 0, 11.08, +14.2), + (+0.77, 1, 0, 11.02, +13.4), + (+0.99, 0, 0, 10.95, +12.7), + (+1.29, 0, 0, 10.87, +12.0), + (+1.05, 1, 0, 10.79, +11.5), + (+0.72, 1, 0, 10.71, +11.0), + (+0.63, 1, 0, 10.60, +10.4), + (+0.59, 1, 0, 10.49, +9.9), + (+0.47, 0, 0, 10.38, +9.5), + (+0.34, 0, 0, 10.27, +9.2), + (+0.41, 0, 0, 10.15, +9.2), + (+0.51, 0, 0, 10.03, +9.1), + (+0.60, 0, 0, 9.96, +9.1), + (+0.69, 0, 0, 9.89, +9.2), + (+0.43, 0, 2, 9.80, +8.9), # 11:13:20.288 stalk latched right + (+0.12, 0, 2, 9.70, +8.6), + (+0.06, 0, 2, 9.61, +8.5), + (+0.07, 0, 2, 9.52, +8.4), + (+0.02, 0, 2, 9.44, +8.4), + (-0.04, 0, 2, 9.37, +8.4), + (+0.06, 0, 2, 9.29, +8.4), + (+0.18, 0, 2, 9.21, +8.4), + (+0.01, 0, 2, 9.13, +8.1), + (-0.22, 0, 2, 9.05, +7.8), + (-0.60, 0, 2, 8.97, +7.4), + (-1.00, 0, 2, 8.89, +7.0), + (-0.92, 0, 2, 8.81, +6.8), + (-0.76, 0, 2, 8.72, +6.6), + (-1.04, 0, 2, 8.64, +6.3), + (-1.40, 0, 2, 8.56, +6.0), + (-1.49, 1, 2, 8.48, +5.8), + (-1.53, 1, 2, 8.40, +5.6), + (-1.85, 1, 2, 8.31, +5.2), + (-2.21, 1, 2, 8.23, +4.8), # 11:13:21.238 old build: lat off, LC off (2.0 Nm line) + (-1.92, 1, 2, 8.15, +2.8), + (-1.53, 1, 2, 8.07, +0.6), + (-1.66, 1, 2, 7.99, -2.8), + (-1.86, 1, 2, 7.92, -6.5), + (-1.99, 1, 2, 7.84, -12.2), + (-2.10, 1, 2, 7.75, -18.3), + (-2.18, 1, 2, 7.67, -22.4), + (-2.24, 1, 2, 7.58, -26.1), + (-2.25, 1, 2, 7.50, -31.0), + (-2.26, 1, 2, 7.42, -36.3), + (-2.27, 1, 2, 7.34, -39.7), + (-2.28, 1, 2, 7.26, -42.8), + (-2.34, 1, 2, 7.18, -47.4), + (-2.42, 1, 2, 7.10, -52.1), + (-2.47, 1, 2, 7.02, -55.9), + (-2.53, 1, 2, 6.93, -59.3), + (-2.51, 1, 2, 6.84, -64.4), + (-2.47, 1, 2, 6.75, -69.8), + (-2.47, 1, 2, 6.67, -73.2), + (-2.49, 1, 2, 6.59, -76.2), + (-2.52, 1, 2, 6.51, -80.2), + (-2.55, 1, 2, 6.44, -84.3), + (-2.53, 1, 2, 6.37, -87.0), + (-2.50, 1, 2, 6.31, -89.5), + (-2.48, 1, 2, 6.24, -93.2), + (-2.45, 1, 2, 6.17, -97.1), + (-2.50, 1, 2, 6.10, -99.9), + (-2.56, 1, 2, 6.03, -102.5), + (-2.64, 1, 2, 5.98, -105.8), + (-2.72, 1, 2, 5.93, -109.3), + (-2.69, 1, 2, 5.88, -112.3), + (-2.64, 1, 2, 5.83, -115.3), + (-2.72, 1, 2, 5.78, -119.5), + (-2.83, 1, 2, 5.72, -123.9), + (-2.82, 1, 2, 5.68, -127.4), + (-2.80, 1, 2, 5.64, -130.9), + (-2.85, 1, 2, 5.60, -136.3), + (-2.90, 1, 2, 5.57, -142.2), + (-2.92, 1, 2, 5.54, -146.1), + (-2.94, 1, 2, 5.51, -149.8), # 11:13:23.238 -2.94 Nm peak, wheel -150 deg + (-2.88, 1, 2, 5.49, -154.6), + (-2.82, 1, 2, 5.47, -159.7), + (-2.81, 1, 2, 5.46, -162.4), + (-2.80, 1, 2, 5.45, -164.8), + (-2.70, 1, 2, 5.43, -167.0), + (-2.58, 1, 2, 5.40, -169.2), + (-2.61, 1, 2, 5.38, -169.7), + (-2.66, 1, 2, 5.35, -170.0), + (-2.59, 1, 2, 5.36, -170.2), + (-2.50, 1, 2, 5.38, -170.5), + (-2.31, 1, 2, 5.37, -170.3), + (-2.11, 1, 2, 5.35, -170.1), + (-2.15, 1, 2, 5.34, -169.6), + (-2.23, 1, 2, 5.32, -169.0), + (-2.32, 1, 2, 5.31, -168.9), +] + + +class _Line: + def __init__(self, y): + self.y = [y, y, y] + + +class _Model: + def __init__(self, prob=0.9): + self.laneLines = [_Line(y) for y in (-5.55, -1.85, 1.85, 5.55)] + self.laneLineProbs = [prob] * 4 + + +def _cp(): + cp = car.CarParams.new_message() + cp.carFingerprint = "TESLA_MODEL_S_PREAP" + cp.brand = "tesla" + cp.pcmCruise = True + cp.openpilotLongitudinalControl = False + return cp + + +class Sim: + def __init__(self, v=V_APPROACH): + self.cse = CarSpecificEvents(_cp()) + self.dh = DesireHelper() + self.lct = TippedLaneChangeTorque() + self.turn = LaneChangeTurnHold() + self.hold = BlinkerLateralHold() + self.handoff = DriverLateralHandoff(enabled=True) + self.v = v + self.prob = 0.9 + self.angle = 0.0 + self.lat_active = True + self.cc_blinker = (False, False) + self.lc_state = LaneChangeState.off + self.lc_dir = 0 + self.prev = self._cs(0.0, 0, 0, 0) + self.frame = 0 + self.t = 0.0 + self.disengage_t: list[float] = [] + self.lat_off_t: list[float] = [] + self.blinker_log: list[tuple[float, bool, bool]] = [] + + def _cs(self, tq, pressed, stalk, hands): + cs = car.CarState.new_message() + cs.cruiseState.enabled = True + cs.cruiseState.available = True + cs.gearShifter = "drive" + cs.vEgo = float(self.v) + cs.steeringTorque = float(tq) + cs.steeringPressed = bool(pressed) + cs.steeringAngleDeg = float(self.angle) + cs.turnSignalStalkState = int(stalk) + cs.leftBlinker = bool(self.cc_blinker[0] or stalk == 1) + cs.rightBlinker = bool(self.cc_blinker[1] or stalk == 2) + cs.steeringTorqueEps = float(hands) + cs.steeringDisengage = int(hands) >= 2 + return cs + + def step(self, tq=0.0, pressed=None, stalk=0, hands=None, angle=None): + if angle is not None: + rate = (angle - self.angle) / DT + self.angle = angle + else: + rate = 0.0 + if pressed is None: + pressed = abs(tq) > 1.0 + if hands is None: + hands = 0 if abs(tq) < 0.5 else (1 if abs(tq) < 1.5 else 2) + cs = self._cs(tq, pressed, stalk, hands) + # controlsd (sees the last modelV2 lane-change state) + tipped = self.lc_state != LaneChangeState.off + self.lct.update(torque_nm=tq, hands_on_level=hands, direction=self.lc_dir, + tipped=tipped, dt=DT) + turn_dir = self.turn.update( + lc_state=self.lc_state, lc_direction=self.lc_dir, steering_angle_deg=self.angle, + torque_nm=tq, lat_active=self.lat_active, v_ego=self.v, stalk_state=stalk, + engaged=True, dt=DT) + lat_would = lat_active_with_blinker_pause( + active=True, steer_fault_temporary=False, steer_fault_permanent=False, + standstill=False, steer_at_standstill=False, + left_blinker=cs.leftBlinker, right_blinker=cs.rightBlinker, + steering_pressed=pressed, steering_disengage=cs.steeringDisengage, + engaged=True, hold=self.hold, alc_active=tipped, v_ego=self.v, + stalk_state=stalk, soft_lat_on=True, driver_turn=self.turn.turning, dt=DT) + out = self.handoff.update( + engaged=True, lat_would_be_active=lat_would, steering_torque=tq, + steering_rate_deg=rate, alc_active=tipped, blinker_paused=self.hold.turn_active, + hands_on_level=hands, v_ego=self.v, emergency_yank=self.lct.release, + lane_change_confirm=self.lct.confirm, dt=DT) + self.lat_active = lat_active_after_handoff(lat_would, out.yielded) + if not self.lat_active: + self.lat_off_t.append(self.t) + lc_blinker = DesireHelper.lane_change_keep_blinker(self.dh.lane_change_state, + self.dh.lane_change_direction) + self.cc_blinker = blinker_with_turn_hold(lc_blinker, turn_dir) + self.blinker_log.append((self.t,) + self.cc_blinker) + # card + cc = car.CarControl.new_message() + cc.enabled = True + cc.latActive = self.lat_active + cc.leftBlinker, cc.rightBlinker = self.cc_blinker + events = self.cse.update(cs, self.prev, cc) + if EventName.steerDisengage in events.names: + self.disengage_t.append(self.t) + # modeld DesireHelper at 20 Hz + if self.frame % 5 == 0: + self.dh.update(cs, self.lat_active, 0.0, model=_Model(self.prob), engaged=True) + self.lc_state = self.dh.lane_change_state + d = self.dh.lane_change_direction + self.lc_dir = 0 if self.lc_state == LaneChangeState.off else ( + 1 if d == LaneChangeDirection.left else 2) + self.prev = cs + self.frame += 1 + self.t += DT + + def hold_for(self, seconds, **kw): + for _ in range(int(round(seconds / DT))): + self.step(**kw) + + def start_left_change(self): + self.hold_for(0.2) + self.hold_for(0.1, stalk=1) + self.hold_for(0.3) + assert self.dh.lane_change_state == LaneChangeState.preLaneChange + self.hold_for(0.3, tq=1.1, pressed=True, hands=1) + self.hold_for(0.3) + assert self.dh.lane_change_state == LaneChangeState.laneChangeStarting + assert self.dh.target_locked + assert self.cc_blinker == (True, False) + + def hand_over_hand_left(self, peak=200.0, tq=2.0, seconds=2.0): + """Turn the wheel left to ``peak`` deg with ``tq`` Nm, then hold.""" + n = int(round(seconds / DT)) + for k in range(n): + self.step(tq=tq, angle=peak * (k + 1) / n) + + def unwind(self, seconds=2.0): + start = self.angle + n = int(round(seconds / DT)) + for k in range(n): + self.step(tq=-0.3, angle=start * (1 - (k + 1) / n)) + + +def _assert_turn_mode_entered(s): + assert s.dh.lane_change_state == LaneChangeState.off + assert not s.dh.target_locked + assert s.turn.mode == MODE_TURN + assert s.cc_blinker == (True, False) + assert s.hold.turn_active + + +def test_thresholds_from_logs(): + assert TURN_ENTER_ANGLE_DEG == 45.0 + assert TURN_EXIT_ANGLE_DEG == 10.0 + assert TURN_EXIT_HOLD_S == 0.5 + assert TURN_HOLD_TIMEOUT_S == 25.0 + assert TURN_SPEED_MIN == LANE_CHANGE_SPEED_MIN + # Largest logged lane change (24.5 deg) is not a turn; driver torque needed while lat is up. + assert not is_lane_change_turn(direction=1, steering_angle_deg=24.5, torque_nm=2.0, lat_active=False) + assert is_lane_change_turn(direction=1, steering_angle_deg=46.0, torque_nm=0.6, lat_active=True) + assert not is_lane_change_turn(direction=1, steering_angle_deg=46.0, torque_nm=0.2, lat_active=True) + assert is_lane_change_turn(direction=1, steering_angle_deg=46.0, torque_nm=0.0, lat_active=False) + assert not is_lane_change_turn(direction=1, steering_angle_deg=-90.0, torque_nm=-2.0, lat_active=False) + assert is_lane_change_turn(direction=2, steering_angle_deg=-90.0, torque_nm=-2.0, lat_active=False) + assert not is_lane_change_turn(direction=0, steering_angle_deg=90.0, torque_nm=2.0, lat_active=False) + + +def test_turn_mid_change_pauses_lat_keeps_engaged_and_blinker(): + s = Sim() + s.start_left_change() + s.hand_over_hand_left() + _assert_turn_mode_entered(s) + assert s.disengage_t == [] + assert s.lat_off_t, "lateral pauses like a manual turn" + s.hold_for(1.0, tq=1.2, angle=200.0) + assert s.cc_blinker == (True, False) + assert not s.lat_active + s.unwind() + # Wheel back near center for TURN_EXIT_HOLD_S: turn complete, blinker off. + s.hold_for(TURN_EXIT_HOLD_S + 0.05, angle=0.0) + assert s.cc_blinker == (False, False) + assert s.turn.mode == 0 + assert s.disengage_t == [] + + +def test_turn_then_straight_road_resumes_on_lane_center_not_old_target(): + s = Sim() + s.start_left_change() + s.hand_over_hand_left() + s.unwind() + s.hold_for(6.0, angle=0.0) + assert s.lat_active, "lat comes back through the normal soft handoff" + assert s.dh.lane_change_state == LaneChangeState.off + assert not s.dh.target_locked + assert s.dh.desire == log.Desire.none + assert s.cc_blinker == (False, False) + assert s.disengage_t == [] + + +def test_sustained_hard_turn_is_never_an_emergency(): + s = Sim() + s.start_left_change() + # Slow build (no spike), then 3.2 Nm held through the whole turn. + for k in range(40): + s.step(tq=0.5 + 2.7 * (k + 1) / 40, angle=5.0) + s.hand_over_hand_left(tq=3.2, seconds=3.0) + s.hold_for(2.0, tq=3.2, hands=3, angle=200.0) + assert s.disengage_t == [] + _assert_turn_mode_entered(s) + assert not s.lat_active + + +def test_sudden_spike_mid_change_is_still_an_emergency(): + s = Sim() + s.start_left_change() + for k in range(30): + s.step(tq=min(3.5, 3.5 * (k + 1) * DT / 0.05), hands=3, angle=5.0) + assert s.disengage_t + assert s.dh.lane_change_state == LaneChangeState.off + + +def test_confirm_bump_mid_change_keeps_the_target(): + s = Sim() + s.start_left_change() + s.hold_for(0.3, tq=1.5, angle=12.0) # firm bump, lane-change sized angle + s.hold_for(0.5, angle=6.0) + assert s.dh.lane_change_state == LaneChangeState.laneChangeStarting + assert s.dh.target_locked + assert s.turn.mode == 0 + assert s.disengage_t == [] + assert s.cc_blinker == (True, False) + + +def test_curve_steered_by_openpilot_is_not_a_turn(): + s = Sim(v=30 * MPH) + s.start_left_change() + s.hold_for(1.0, tq=0.1, angle=50.0) # lat active, no driver torque + assert s.turn.mode == 0 + assert s.dh.lane_change_state == LaneChangeState.laneChangeStarting + + +def test_opposite_pull_still_cancels(): + s = Sim() + s.start_left_change() + s.hold_for(0.2, tq=-1.2, pressed=True, hands=1, angle=-3.0) + assert s.dh.lane_change_state == LaneChangeState.off + assert s.turn.mode == 0 + s.hold_for(0.3) + assert s.cc_blinker == (False, False) + + +def test_latched_stalk_during_change_is_a_driver_turn(): + s = Sim() + s.start_left_change() + s.hold_for(1.2, stalk=1) + assert s.dh.lane_change_state == LaneChangeState.off + assert not s.dh.target_locked + assert s.hold.turn_active + # The physical latch keeps the lamp; turning stays engaged. + s.hold_for(2.0, stalk=1, tq=2.0, angle=150.0) + assert s.disengage_t == [] + assert s.prev.leftBlinker + assert not s.lat_active + + +def test_lines_vanish_after_turn_mode_do_not_end_the_blinker_hold(): + s = Sim() + s.start_left_change() + s.hand_over_hand_left() + _assert_turn_mode_entered(s) + s.prob = 0.05 + s.hold_for(2.0, tq=1.2, angle=200.0) + assert s.cc_blinker == (True, False) + assert s.turn.mode == MODE_TURN + assert s.disengage_t == [] + + +def test_lines_vanish_before_the_turn_end_the_change_cleanly(): + s = Sim() + s.start_left_change() + s.prob = 0.05 + s.hold_for(2.0, angle=4.0) + assert s.dh.lane_change_state == LaneChangeState.off + assert not s.dh.target_locked + assert s.disengage_t == [] + assert s.lat_active + + +def test_speed_under_20_mid_change_ends_it_and_holds_the_blinker_for_the_turn(): + s = Sim() + s.start_left_change() + s.v = 15 * MPH + s.hold_for(0.3, angle=3.0) + assert s.dh.lane_change_state == LaneChangeState.off + assert not s.dh.target_locked + assert s.turn.mode == MODE_HOLD + assert s.cc_blinker == (True, False) + assert s.disengage_t == [] + s.hand_over_hand_left() + assert s.turn.mode == MODE_TURN + s.unwind() + s.hold_for(TURN_EXIT_HOLD_S + 0.05, angle=0.0) + assert s.cc_blinker == (False, False) + assert s.disengage_t == [] + + +def test_speed_hold_ends_when_back_up_to_speed_without_a_turn(): + s = Sim() + s.start_left_change() + s.v = 15 * MPH + s.hold_for(0.3) + assert s.turn.mode == MODE_HOLD + s.v = HOLD_RESUME_SPEED + 0.5 + s.hold_for(0.1) + assert s.turn.mode == 0 + assert s.cc_blinker == (False, False) + assert s.dh.lane_change_state == LaneChangeState.off + + +@pytest.mark.parametrize("how", ["timeout", "opposite_stalk"]) +def test_blinker_hold_never_flashes_forever(how): + s = Sim() + s.start_left_change() + s.hand_over_hand_left() + assert s.turn.mode == MODE_TURN + if how == "timeout": + s.hold_for(TURN_HOLD_TIMEOUT_S - 2.5, tq=0.8, angle=120.0) + assert s.cc_blinker == (True, False) + s.hold_for(1.0, tq=0.8, angle=120.0) + else: + s.hold_for(0.1, stalk=2, angle=120.0) + s.hold_for(0.1, angle=120.0) + assert s.turn.mode == 0 + assert s.cc_blinker == (False, False) + + +def test_turn_hold_unit_exit_needs_the_hold_time(): + h = LaneChangeTurnHold() + kw = dict(lc_state=LaneChangeState.laneChangeStarting, lc_direction=2, torque_nm=-1.0, + lat_active=False, v_ego=V_APPROACH, stalk_state=0, engaged=True, dt=DT) + assert h.update(steering_angle_deg=-90.0, **kw) == 2 + kw["lc_state"] = LaneChangeState.off + for _ in range(int(TURN_EXIT_HOLD_S / DT) - 5): + assert h.update(steering_angle_deg=-5.0, **kw) == 2 + assert h.update(steering_angle_deg=-20.0, **kw) == 2 # not settled: timer restarts + for _ in range(int(TURN_EXIT_HOLD_S / DT) - 5): + assert h.update(steering_angle_deg=0.0, **kw) == 2 + for _ in range(10): + h.update(steering_angle_deg=0.0, **kw) + assert h.direction == 0 + assert h.update(steering_angle_deg=-90.0, **kw) == 0 # lane change is off: no re-entry + kw["engaged"] = False + assert h.update(steering_angle_deg=-90.0, **kw) == 0 + assert blinker_with_turn_hold((False, False), 1) == (True, False) + assert blinker_with_turn_hold((False, True), 1) == (False, True) + + +def test_lane_change_ending_with_hands_on_keeps_the_disengage_block(): + # ALC keep-alive ends (lamps dark 1 s) while the driver is still steering: + # post-turn hand-on hold, so a hands-on edge does not USER_DISABLE. + hold = BlinkerLateralHold() + hold.update(True, False, False, engaged=True, dt=DT, stalk_state=1) + hold.update(True, False, False, engaged=True, dt=DT, stalk_state=0) + assert hold._alc_keep + for _ in range(int(1.0 / DT) + 2): + hold.update(False, False, True, engaged=True, dt=DT, steering_disengage=True) + assert not hold._alc_keep + assert hold.holding and hold.blocks_steer_disengage + hold.update(False, False, False, engaged=True, dt=DT) + assert not hold.holding and not hold.blocks_steer_disengage + # Hands already off when the keep ends: nothing held. + hold = BlinkerLateralHold() + hold.update(True, False, False, engaged=True, dt=DT, stalk_state=1) + hold.update(True, False, False, engaged=True, dt=DT, stalk_state=0) + for _ in range(int(1.0 / DT) + 2): + hold.update(False, False, False, engaged=True, dt=DT) + assert not hold.holding and not hold.blocks_steer_disengage + + +def _replay_1113(): + s = Sim(v=TURN_RIGHT_1113[0][3]) + s.angle = TURN_RIGHT_1113[0][4] + s.release_t = [] + s.ended_t = None + for i, row in enumerate(TURN_RIGHT_1113): + nxt = TURN_RIGHT_1113[i + 1] if i + 1 < len(TURN_RIGHT_1113) else row + for k in range(5): # 20 Hz -> 100 Hz, torque / angle linear + f = k / 5 + s.v = row[3] + s.step(tq=row[0] + (nxt[0] - row[0]) * f, pressed=bool(row[1]), stalk=row[2], + angle=row[4] + (nxt[4] - row[4]) * f) + if s.lct.release: + s.release_t.append(s.t) + if s.ended_t is None and s.t > 1.0 and s.dh.lane_change_state == LaneChangeState.off: + s.ended_t = s.t + return s + + +def test_sep28_1113_sustained_turn_with_latched_stalk_is_not_an_emergency(): + torques = [abs(r[0]) for r in TURN_RIGHT_1113] + latch = next(i for i, r in enumerate(TURN_RIGHT_1113) if i > 5 and r[2] == 2) * 0.05 + over_old = next(i for i, t in enumerate(torques) if t > 2.0) * 0.05 + under = max(i for i, t in enumerate(torques) if t < SOFT_YIELD_TRIGGER_NM and i * 0.05 < over_old) * 0.05 + assert over_old - under > EMERGENCY_RISE_WINDOW_S # not a fast rise + assert max(torques) > EMERGENCY_TORQUE_NM # but held over the hard line + + s = _replay_1113() + assert s.release_t == [], "sustained same-direction turn must not be an emergency" + assert s.disengage_t == [], "openpilot must stay engaged" + # The change ends on the latched stalk (1.0 s), not on torque. + assert s.ended_t is not None + assert latch + 1.0 - 0.06 <= s.ended_t <= latch + 1.0 + 0.1 + assert s.dh.lane_change_state == LaneChangeState.off + assert not s.dh.target_locked + # Lateral paused through the turn like a manual blinker turn. + assert s.lat_off_t and s.lat_off_t[0] >= s.ended_t - 0.06 + assert not s.lat_active + assert s.prev.rightBlinker # latched stalk keeps the lamp + + +def test_controlsd_wires_turn_hold_and_tipped_torque(): + src = (ROOT / "selfdrive/controls/controlsd.py").read_text() + # Emergency or takeover yields lat; only the emergency disengages (card). + assert "emergency_yank=bool(self._lane_change_torque.release)," in src + assert "lane_change_confirm = self._lane_change_torque.confirm" in src + # Turn mode pauses lat like a latched stalk and keeps the blinker. + assert "driver_turn=self._lane_change_turn.turning," in src + assert "lat_active=self._lat_active_prev," in src + assert "self._lat_active_prev = bool(CC.latActive)" in src + blinker = "\n".join(( + "CC.leftBlinker, CC.rightBlinker = blinker_with_turn_hold(", + " DesireHelper.lane_change_keep_blinker(", + " model_v2.meta.laneChangeState, model_v2.meta.laneChangeDirection),", + " turn_hold_dir)", + )) + assert blinker in src diff --git a/selfdrive/controls/lib/tests/test_lat_fight_hold.py b/selfdrive/controls/lib/tests/test_lat_fight_hold.py new file mode 100644 index 00000000000000..986056371e7602 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lat_fight_hold.py @@ -0,0 +1,160 @@ +"""Push to take, release to give back. The tug-of-war latch is gone. + +Two re-yields inside 15 s only slow the next taper. They never block a return. +""" + +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + AGREE_CURVATURE_ERR, + AGREE_HOLD_S, + BLEND_TIME_S, + FULL_LATERAL_RESET_S, + LIGHT_HOLD_S, + RELEASE_HOLD_S, + REYIELD_WINDOW_S, + TAPER_RATE_MAX_PER_S, + TAPER_RATE_MIN_PER_S, + YIELD_FIRM_FRAMES, + DriverLateralHandoff, + lat_active_after_handoff, + taper_rate_per_s, +) + +DT = 0.01 +MODEL_K = 0.01 +WHEEL_K = 0.0 + + +def _step(h, *, torque=0.0, hands=0, dt=DT, model_k=None, wheel_k=None, + engaged=True, lat=True, angle=0.0): + return h.update( + engaged=engaged, lat_would_be_active=lat, + steering_torque=torque, steering_rate_deg=-4095.5, + hands_on_level=hands, dt=dt, + steering_angle_deg=angle, + model_curvature=model_k, measured_curvature=wheel_k, + ) + + +def _yield_once(h, torque=1.5, hands=0): + out = None + for _ in range(YIELD_FIRM_FRAMES): + out = _step(h, torque=torque, hands=hands) + assert out.yielded and out.authority == 0.0 + assert not lat_active_after_handoff(True, out.yielded) + return out + + +def _release(h, seconds, model_k=None, wheel_k=None, torque=0.0): + n = max(1, int(round(seconds / DT))) + out = None + for _ in range(n): + out = _step(h, torque=torque, hands=0, model_k=model_k, wheel_k=wheel_k) + return out + + +def test_release_rules_do_not_wait_on_hands(): + h = DriverLateralHandoff() + _yield_once(h, torque=1.5) + # R1: quiet torque, hands still on the rim. + out = _release(h, RELEASE_HOLD_S + 0.02, torque=0.2) + # hands default 0 in _release; pass hands via steps + h = DriverLateralHandoff() + _yield_once(h) + out = None + for _ in range(int(round((RELEASE_HOLD_S + 0.02) / DT))): + out = _step(h, torque=0.2, hands=1) + assert out.blending and not out.yielded + assert lat_active_after_handoff(True, out.yielded) + + +def test_r2_returns_mid_curve_when_curvature_agrees(): + h = DriverLateralHandoff() + _yield_once(h, torque=1.5) + # Holding torque above R1, curvature still apart: stay yielded. + out = _release(h, 0.40, model_k=0.002, wheel_k=0.0, torque=0.9) + assert out.yielded and not out.blending + # Agreement for 0.5 s, torque under 1.2 and not rising. + out = _release(h, AGREE_HOLD_S + 0.02, model_k=0.0005, wheel_k=0.0, torque=0.9) + assert out.blending and not out.yielded + + +def test_r3_returns_without_curvature_agreement(): + h = DriverLateralHandoff() + _yield_once(h) + out = _release(h, LIGHT_HOLD_S - 0.1, model_k=MODEL_K, wheel_k=WHEEL_K, torque=0.5) + assert out.yielded and not out.blending + out = _release(h, 0.2, model_k=MODEL_K, wheel_k=WHEEL_K, torque=0.5) + assert out.blending and not out.yielded + + +def test_disagreement_above_the_light_band_stays_yielded(): + h = DriverLateralHandoff() + _yield_once(h) + out = _release(h, LIGHT_HOLD_S + 0.5, model_k=MODEL_K, wheel_k=WHEEL_K, torque=1.0) + assert out.yielded and not out.blending + + +def test_two_reyields_slow_the_next_taper_and_full_lateral_clears_it(): + h = DriverLateralHandoff() + _yield_once(h) + _release(h, RELEASE_HOLD_S + 0.02) + assert h._blending and not h._taper_soften + # Deliberate push: no curvature, so a rise above the taper baseline re-yields. + for _ in range(16): + _step(h, torque=1.5) + assert h._yielded + _release(h, RELEASE_HOLD_S + 0.02) + assert h._blending + for _ in range(16): + _step(h, torque=1.5) + assert h._yielded and h._soften + _release(h, RELEASE_HOLD_S + 0.02) + assert h._blending and h._taper_soften + rate = taper_rate_per_s(0.0, soften=h._taper_soften) + assert rate == TAPER_RATE_MIN_PER_S / BLEND_TIME_S + # Finish the slow taper, then 10 s of full lateral clears the softener. + _release(h, BLEND_TIME_S + 0.05) + assert h.authority == 1.0 and not h._blending + _release(h, FULL_LATERAL_RESET_S) + assert not h._soften + assert h._reyields == [] + + +def test_helping_torque_does_not_cancel_the_taper(): + h = DriverLateralHandoff() + _yield_once(h) + # Model wants more left than the wheel. Positive torque helps. + _release(h, RELEASE_HOLD_S + 0.02, model_k=0.001, wheel_k=0.0) + assert h._blending + out = None + for _ in range(80): + out = _step(h, torque=1.5, model_k=0.001, wheel_k=0.0) + if out.authority >= 1.0 and not out.blending: + break + assert out is not None and not out.yielded and out.authority == 1.0 + + +def test_opposing_torque_reyields(): + h = DriverLateralHandoff() + _yield_once(h) + # R2 with torque 0.5 so the taper baseline sits under the oppose line + # and a -1.0 Nm push is not also a 0.6 Nm rise. + _release(h, 0.2, model_k=0.002, wheel_k=0.0, torque=0.5) + assert h._yielded + _release(h, AGREE_HOLD_S + 0.02, model_k=0.0004, wheel_k=0.0, torque=0.5) + assert h._blending + out = None + for _ in range(16): + out = _step(h, torque=-1.0, model_k=0.0004, wheel_k=0.0) + assert out.yielded and not out.blending + + +def test_taper_rate_stays_inside_the_blend_window(): + assert taper_rate_per_s(None) == TAPER_RATE_MIN_PER_S / BLEND_TIME_S + assert taper_rate_per_s(0.0) == TAPER_RATE_MAX_PER_S / BLEND_TIME_S + # 0.002 / 0.001 = 2.0, the ceiling. + assert taper_rate_per_s(0.001) == TAPER_RATE_MAX_PER_S / BLEND_TIME_S + # 0.002 / 0.004 = 0.5, clamped to the floor. + assert taper_rate_per_s(0.004) == TAPER_RATE_MIN_PER_S / BLEND_TIME_S + assert AGREE_CURVATURE_ERR == 0.0008 + assert REYIELD_WINDOW_S == 15.0 diff --git a/selfdrive/controls/lib/tests/test_lat_handoff_push_release.py b/selfdrive/controls/lib/tests/test_lat_handoff_push_release.py new file mode 100644 index 00000000000000..1df3a733771845 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lat_handoff_push_release.py @@ -0,0 +1,175 @@ +"""Replay-shaped traces for push-to-take, release-to-give-back. + +Numbers follow the Oct 7 2026 route analysis (1c95345a3286a5db|00000172). +Logs are not in the tree, so each case is a synthetic trace with the +torque, curvature error, and wheel angle the report measured. +""" + +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + RELEASE_HOLD_S, + DriverLateralHandoff, + lat_active_after_handoff, +) +from openpilot.selfdrive.controls.lib.lane_change_nudge import steer_disengage_this_frame + +DT = 0.01 + + +def _play(segments, *, blinker=False, v_ego=20.0): + """segments: (seconds, torque, curv_err, angle). Returns time of first blend.""" + h = DriverLateralHandoff() + t = 0.0 + out = None + for seconds, torque, err, angle in segments: + n = int(round(seconds / DT)) + measured = 0.0 + model = measured + float(err) + for _ in range(n): + out = h.update( + engaged=True, lat_would_be_active=True, + steering_torque=torque, steering_rate_deg=-4095.5, + hands_on_level=0, v_ego=v_ego, blinker_paused=blinker, + steering_angle_deg=angle, dt=DT, + model_curvature=model, measured_curvature=measured, + ) + t += DT + if out.blending: + return t, out, h + return None, out, h + + +def test_logged_yields_return_near_the_proposed_times(): + # 14:21:23 — push, then curvature agrees. R2 ~0.8 s from the push. + t, out, _ = _play([(0.30, 1.0, 0.002, 0.0), (0.70, 0.8, 0.0005, 0.0)]) + assert t is not None and 0.70 <= t <= 0.95 + assert out.blending + + # 14:22:25 — long hold at 40 deg, then a light straight wheel. ~17.6 s. + t, out, _ = _play([(17.3, 1.6, 0.002, 40.0), (1.0, 0.1, 0.002, 5.0)]) + assert t is not None and 17.4 <= t <= 18.0 + assert out.blending + + # 14:24:19 — mid-curve agreement. R2 ~3.9 s. + t, out, _ = _play([(3.4, 1.5, 0.002, 8.0), (0.8, 0.9, 0.0005, 8.0)]) + assert t is not None and 3.7 <= t <= 4.1 + assert out.blending + + # 14:24:55 and 14:34:35 — torque already in the release band. ~0.30 s + # (the report's 0.2 s is a 10 Hz estimate; R1 cannot be shorter than 0.30). + for push in (0.10, 0.16): + t, out, _ = _play([(push, 2.0, 0.0, 0.0), (0.6, 0.15, 0.0, 0.0)]) + assert t is not None + quiet_for = t - push + assert 0.25 <= quiet_for <= 0.40 + assert out.blending + + # 14:34:18 — firm-but-not-1.4 hold, then a release. R1 ~1.2 s. + t, out, _ = _play([(0.90, 1.3, 0.001, 0.0), (0.6, 0.2, 0.001, 0.0)]) + assert t is not None and 1.0 <= t <= 1.4 + assert out.blending + + +def test_short_nudge_returns_promptly(): + t, out, _ = _play([(0.40, 1.2, 0.001, 4.0), (1.5, 0.0, 0.001, 4.0)]) + assert t is not None and 0.5 <= t <= 1.8 + assert out.blending and not out.yielded + + +def test_resting_hands_never_yield_or_block_return(): + h = DriverLateralHandoff() + out = None + for tq in (0.15, 0.25, 0.35, -0.20): + for _ in range(300): + out = h.update( + engaged=True, lat_would_be_active=True, steering_torque=tq, + steering_rate_deg=-4095.5, hands_on_level=1, v_ego=20.0, + steering_angle_deg=2.0, dt=DT, + ) + assert not out.yielded and out.authority == 1.0 + # A real push yields; resting torque afterwards does not hold the yield. + for _ in range(10): + out = h.update( + engaged=True, lat_would_be_active=True, steering_torque=1.6, + steering_rate_deg=-4095.5, hands_on_level=1, v_ego=20.0, dt=DT, + ) + assert out.yielded + n = int(round((RELEASE_HOLD_S + 0.02) / DT)) + for _ in range(n): + out = h.update( + engaged=True, lat_would_be_active=True, steering_torque=0.30, + steering_rate_deg=-4095.5, hands_on_level=1, v_ego=20.0, dt=DT, + ) + assert out.blending and not out.yielded + + +def test_helping_torque_never_cancels_the_taper(): + h = DriverLateralHandoff() + for _ in range(10): + h.update(engaged=True, lat_would_be_active=True, steering_torque=1.6, + steering_rate_deg=-4095.5, v_ego=20.0, dt=DT, + model_curvature=0.001, measured_curvature=0.0) + out = None + for _ in range(int(round((RELEASE_HOLD_S + 0.02) / DT))): + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=0.0, + steering_rate_deg=-4095.5, v_ego=20.0, dt=DT, + model_curvature=0.001, measured_curvature=0.0) + assert out.blending + for _ in range(80): + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=1.5, + steering_rate_deg=-4095.5, v_ego=20.0, dt=DT, + model_curvature=0.001, measured_curvature=0.0) + if out.authority >= 1.0 and not out.blending: + break + assert not out.yielded and out.authority == 1.0 + assert lat_active_after_handoff(True, out.yielded) + + +def test_yank_at_full_lateral_disengages_and_yielded_does_not(): + h = DriverLateralHandoff() + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=3.0, + steering_rate_deg=-4095.5, hands_on_level=3, steering_pressed=True, + v_ego=20.0, dt=DT) + assert not out.yielded and out.authority == 1.0 + assert lat_active_after_handoff(True, out.yielded) + assert steer_disengage_this_frame( + confirm=False, release=False, release_prev=False, + disengage_edge=True, blocks=False, lat_full_control=True) + + for _ in range(10): + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=3.0, + steering_rate_deg=-4095.5, hands_on_level=3, steering_pressed=True, + v_ego=20.0, dt=DT) + assert out.yielded + assert not lat_active_after_handoff(True, out.yielded) + assert not steer_disengage_this_frame( + confirm=False, release=False, release_prev=False, + disengage_edge=True, blocks=False, lat_full_control=False) + + for _ in range(40): + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=0.0, + steering_rate_deg=-4095.5, hands_on_level=1, v_ego=20.0, dt=DT) + assert out.blending and lat_active_after_handoff(True, out.yielded) + assert not steer_disengage_this_frame( + confirm=False, release=False, release_prev=False, + disengage_edge=True, blocks=False, lat_full_control=False) + + +def test_two_offsets_ignore_the_sna_rate(): + h = DriverLateralHandoff() + for _ in range(800): + h.update(engaged=True, lat_would_be_active=True, steering_torque=0.07, + steering_rate_deg=-4095.5, hands_on_level=0, steering_angle_deg=0.0, + v_ego=20.0, dt=DT) + assert 0.05 < h.rest_bias_op < 0.07 + assert h.rest_bias == h.rest_bias_op + for _ in range(12): + h.update(engaged=True, lat_would_be_active=True, steering_torque=1.6, + steering_rate_deg=-4095.5, hands_on_level=1, blinker_paused=True, + steering_angle_deg=0.0, v_ego=20.0, dt=DT) + for _ in range(800): + h.update(engaged=True, lat_would_be_active=True, steering_torque=0.15, + steering_rate_deg=-4095.5, hands_on_level=0, blinker_paused=True, + steering_angle_deg=0.0, v_ego=20.0, dt=DT) + assert h._yielded + assert 0.12 < h.rest_bias_free < 0.15 + assert h.rest_bias == h.rest_bias_free diff --git a/selfdrive/controls/lib/tests/test_lat_low_visibility.py b/selfdrive/controls/lib/tests/test_lat_low_visibility.py new file mode 100644 index 00000000000000..356b65c0f2adee --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lat_low_visibility.py @@ -0,0 +1,758 @@ +"""Low-visibility lateral back-off: confidence hysteresis, ramp, exposure, sun.""" + +import math +from pathlib import Path + +from cereal import log +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.lat_low_visibility import ( + AUTHORITY_DOWN_PER_S, + AUTHORITY_FLOOR, + CAMERA_ONLY_AUTHORITY, + PROLONGED_S, + authority_target, + AUTHORITY_UP_PER_S, + CURV_JUMP, + CURV_WINDOW_S, + ENTRY_MIN_V_MS, + EXPOSURE_COLLAPSE_RATIO, + LANE_CONF_ENTER, + LANE_CONF_EXIT, + MODEL_ENTER_S, + MODEL_EXIT_S, + PARAM_LOW_VIS_BACKOFF, + PATH_Y_STD_ENTER_M, + PATH_Y_STD_EXIT_M, + STRAIGHT_HOLD_S, + TURN_CURVATURE, + LowVisibility, + edge_confidence, + edges_both_unusable, + entry_speed_ok, + fade_curvature, + in_turn, + model_is_clear, + model_is_poor, + path_y_std_at, + side_confidences, + side_confidences_exit, + solar_position, + sun_ahead_from_fix, + sun_low_and_ahead, +) + +DT = 0.05 # one model frame + + +def _step(lv, *, left=0.95, right=0.95, ystd=0.4, seconds=DT, integ=700, + sun=False, enabled=True, dt=DT, edges=None, + v_ego=15.0, blinker=False, yielded=False, + measured_k=0.0, model_k=0.0, chatter=None, near_roundabout=False): + n = max(1, int(round(seconds / dt))) + out = None + if edges is None: + edges = [0.12, 0.12] + for i in range(n): + mk = model_k + if chatter is not None: + amp = float(chatter) + mk = amp if (i % 2 == 0) else -amp + out = lv.update( + enabled=enabled, + lane_probs=[0.5, left, right, 0.5], + edge_stds=edges, + path_t=[0.0, 1.5, 3.0, 6.0], + path_y_std=[0.2, 0.3, ystd, ystd], + integ_lines=integ, + sun_ahead=sun, + dt=dt, + v_ego=v_ego, + blinker=blinker, + yielded=yielded, + measured_curvature=measured_k, + model_curvature=mk, + near_roundabout=near_roundabout, + ) + return out + + +# Blind road edges (std large enough that confidence is under 0.30). +NO_EDGES = [8.0, 8.0] + + +def _mph(mph: float) -> float: + return mph * CV.MPH_TO_MS + + +def test_side_confidence_and_path_std_match_the_incident_numbers(): + # Right lane 0.12 is below 0.30; left 0.56 is not. Either side is enough. + left, right = side_confidences([0.4, 0.56, 0.12, 0.3], [0.1, 0.1]) + assert left > LANE_CONF_ENTER + assert right < LANE_CONF_ENTER + y = path_y_std_at([0.0, 2.0, 4.0], [0.4, 4.1, 5.0], 3.0) + assert abs(y - (4.1 + 0.5 * (5.0 - 4.1))) < 1e-6 + # Lane lines do not make the path poor. Wide plan + no edges + jump does. + assert not model_is_poor(4.1, False, True) + assert not model_is_poor(4.1, True, False) + assert not model_is_poor(0.4, True, True) + assert model_is_poor(4.1, True, True) + assert model_is_clear(0.4, True) + assert not model_is_clear(0.4, False) + assert not model_is_clear(5.0, True) # wide plan holds, whatever the lanes say + assert not model_is_clear(None, True) + assert edges_both_unusable([8.0, 8.0]) + assert not edges_both_unusable([0.1, 8.0]) # one curb is usable + assert not edges_both_unusable([0.1]) # a missing edge is not blind + exit_left, exit_right = side_confidences_exit([0.4, 0.90, 0.85, 0.3], [8.0, 8.0]) + assert exit_left >= LANE_CONF_EXIT and exit_right >= LANE_CONF_EXIT + # The old worse-of helper still describes a wide edge. It is not the trigger. + enter_left, enter_right = side_confidences([0.4, 0.90, 0.85, 0.3], [8.0, 8.0]) + assert enter_left < LANE_CONF_ENTER and enter_right < LANE_CONF_ENTER + assert edge_confidence(0.1) > 0.8 + assert edge_confidence(1.5) < LANE_CONF_ENTER + + +def test_hysteresis_ignores_one_frame_and_the_middle_band(): + lv = LowVisibility() + out = _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=3.0, edges=NO_EDGES) + assert not out.active and out.authority == 1.0 + + # One uncertain frame must not latch. Lane lines are irrelevant. + out = _step(lv, left=0.95, right=0.95, ystd=4.1, seconds=DT, edges=NO_EDGES, chatter=CURV_JUMP) + assert not out.active + + out = _step(lv, left=0.0, right=0.0, ystd=4.1, seconds=MODEL_ENTER_S + DT, + edges=NO_EDGES, chatter=CURV_JUMP) + assert out.active and out.alert and out.model_poor + assert out.authority < 1.0 + + # Plan std between the bars, curvature still jumping: stay latched. + held = _step(lv, left=0.90, right=0.90, ystd=1.5, seconds=2.0, edges=NO_EDGES, chatter=CURV_JUMP) + assert held.active + + # Settled path, but desired curvature is still jumping: do not release. + jumping = _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=MODEL_EXIT_S + 0.3, + edges=NO_EDGES, chatter=CURV_JUMP) + assert jumping.active + + # Calm curvature and a settled path. Short of the exit hold, stay latched. + almost = _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=MODEL_EXIT_S * 0.5, + edges=NO_EDGES, model_k=0.0) + assert almost.active + cleared = _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=CURV_WINDOW_S + MODEL_EXIT_S, + edges=NO_EDGES, model_k=0.0) + assert not cleared.active and not cleared.alert + + +def test_backoff_ramps_down_and_recovers_without_a_step(): + lv = LowVisibility() + _step(lv, left=0.0, right=0.0, ystd=4.1, seconds=MODEL_ENTER_S + 0.05, + dt=0.01, edges=NO_EDGES, chatter=CURV_JUMP) + assert lv.active + start = lv.authority + mid = _step(lv, left=0.0, right=0.0, ystd=4.1, seconds=0.50, dt=0.01, + edges=NO_EDGES, chatter=CURV_JUMP) + assert mid.authority < start + assert abs((start - mid.authority) - 0.50 * AUTHORITY_DOWN_PER_S) < 0.02 + floor = _step(lv, left=0.0, right=0.0, ystd=4.1, seconds=1.0, dt=0.01, + edges=NO_EDGES, chatter=CURV_JUMP) + # Never zero: 4.1 m path std bottoms out at the floor, and the lateral + # target still follows the path (not the wheel, not a held heading). + assert abs(floor.authority - AUTHORITY_FLOOR) < 1e-9 + assert fade_curvature(0.02, 0.0, floor.authority) > 0.0 + assert fade_curvature(0.02, 0.0, 1.0) == 0.02 + + _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=CURV_WINDOW_S + MODEL_EXIT_S, dt=0.01, + edges=NO_EDGES, model_k=0.0) + assert not lv.active + rising = lv.authority + later = _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=0.50, dt=0.01, + edges=NO_EDGES, model_k=0.0) + assert later.authority > rising + assert abs(later.authority - min(1.0, rising + 0.50 * AUTHORITY_UP_PER_S)) < 0.02 + + +def test_paved_drive_does_not_back_off_and_toggle_off_is_identity(): + lv = LowVisibility() + out = _step(lv, left=0.97, right=0.92, ystd=0.4, seconds=30.0) + assert not out.active and out.authority == 1.0 and not out.alert + + lv2 = LowVisibility() + out = _step(lv2, left=0.10, right=0.10, ystd=5.0, seconds=2.0, enabled=False) + assert out.authority == 1.0 and not out.alert and not out.active + + +def test_three_incident_episodes_each_latch(): + """Three uncertain-path windows. Each has to enter on its own.""" + lv = LowVisibility() + _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=2.0, edges=NO_EDGES) + episodes = [] + for _ in range(3): + _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=CURV_WINDOW_S + MODEL_EXIT_S + 0.3, + edges=NO_EDGES, model_k=0.0) + assert not lv.active + out = _step(lv, left=0.95, right=0.95, ystd=4.1, seconds=MODEL_ENTER_S + 0.2, + edges=NO_EDGES, chatter=CURV_JUMP) + episodes.append(out) + assert out.active and out.model_poor and out.authority < 1.0 + assert len(episodes) == 3 + # One calm frame, then a short gap under the exit hold, does not drop it. + _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=DT, edges=NO_EDGES, model_k=0.0) + assert lv.active + _step(lv, left=0.0, right=0.0, ystd=4.1, seconds=0.2, edges=NO_EDGES, chatter=CURV_JUMP) + _step(lv, left=0.0, right=0.0, ystd=0.4, seconds=MODEL_EXIT_S * 0.4, edges=NO_EDGES, model_k=0.0) + assert lv.active + + +def test_exposure_collapse_and_single_frame_and_sun_heads_up(): + lv = LowVisibility() + # Bright baseline (731 lines), then the incident drop to 153. + _step(lv, integ=731, seconds=2.0) + assert not lv.active + one = _step(lv, integ=153, seconds=DT) + assert not one.camera_blind and not one.active + + # A plain exposure drop with a confident path and no low sun is a + # shade-to-sun change, not glare: it never latches. + plain_drop = _step(lv, integ=153, seconds=0.8) + assert not plain_drop.camera_blind and not plain_drop.active + + lv = LowVisibility() + _step(lv, integ=731, seconds=2.0) + dropped = _step(lv, integ=153, seconds=0.8, sun=True) + assert dropped.camera_blind and dropped.active and dropped.alert + assert AUTHORITY_FLOOR <= dropped.authority < 1.0 + # 153/731 is well under the 0.45 collapse ratio. + assert 153 / 731 < EXPOSURE_COLLAPSE_RATIO + + # Recover. + back = _step(lv, integ=700, seconds=2.0, sun=True) + assert not back.camera_blind and not back.active + + # Milder drop does not trip without the sun, and does with the sun ahead. + plain = LowVisibility() + _step(plain, integ=731, seconds=2.0) + mild = int(731 * 0.60) # between 0.45 and 0.65 + out = _step(plain, integ=mild, seconds=1.0, sun=False) + assert not out.camera_blind + + early = LowVisibility() + _step(early, integ=731, seconds=2.0) + out = _step(early, integ=mild, seconds=1.0, sun=True) + assert out.camera_blind and out.alert + + +def test_sun_gate_and_morning_geometry(): + assert sun_low_and_ahead(elevation_deg=0.6, heading_deg=90.0, azimuth_deg=98.0) + assert not sun_low_and_ahead(elevation_deg=40.0, heading_deg=90.0, azimuth_deg=98.0) + assert not sun_low_and_ahead(elevation_deg=1.0, heading_deg=90.0, azimuth_deg=140.0) + + # Oct 7 2026 12:33 UTC, ~45.3N 93.2W, heading due east: sun is low and + # a few degrees south of east (right of ahead). Qualitative, not a survey. + import datetime + ts = datetime.datetime(2026, 10, 7, 12, 33, tzinfo=datetime.timezone.utc).timestamp() + elev, az = solar_position(45.3, -93.2, ts) + assert -1.0 < elev < 8.0 + assert sun_low_and_ahead(elevation_deg=elev, heading_deg=90.0, azimuth_deg=az) + # Summer noon is high and not "ahead" of an east heading. + noon = datetime.datetime(2026, 6, 21, 18, 0, tzinfo=datetime.timezone.utc).timestamp() + elev_n, az_n = solar_position(45.3, -93.2, noon) + assert elev_n > 50.0 + assert not sun_low_and_ahead(elevation_deg=elev_n, heading_deg=90.0, azimuth_deg=az_n) + + ms = int(ts * 1000) + assert sun_ahead_from_fix( + latitude=45.3, longitude=-93.2, unix_timestamp_millis=ms, + bearing_deg=90.0, horizontal_accuracy_m=5.0) is True + assert sun_ahead_from_fix( + latitude=45.3, longitude=-93.2, unix_timestamp_millis=ms, + bearing_deg=90.0, horizontal_accuracy_m=80.0) is None + + +def test_alert_text_and_toggle_are_wired(): + # Schema only: importing events pulls msgq, which unit tests don't need. + assert log.OnroadEvent.EventName.lowVisibility is not None + root = Path(__file__).resolve().parents[4] + events = (root / "selfdrive/selfdrived/events.py").read_text() + block = events.split("_low_visibility = getattr(EventName, \"lowVisibility\"", 1)[1] + block = block.split("if HARDWARE.get_device_type()", 1)[0] + assert '"Low visibility"' in block + assert '"Take over if needed"' in block + assert "ET.WARNING" in block + assert "ET.SOFT_DISABLE" not in block + assert "ET.IMMEDIATE_DISABLE" not in block + assert "ET.USER_DISABLE" not in block + keys = (root / "common/params_keys.h").read_text() + line = next(ln for ln in keys.splitlines() if f'"{PARAM_LOW_VIS_BACKOFF}"' in ln) + assert "BOOL" in line and '"1"' in line + content = (root / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + assert "LOW_VIS_BACKOFF_DESCRIPTION" in content + assert "Low visibility" in content + assert "Longitudinal stays on" in content + for rel in ( + "selfdrive/ui/layouts/settings/driving_mannerisms.py", + "selfdrive/ui/mici/layouts/settings/driving_mannerisms.py", + "selfdrive/controls/controlsd.py", + "selfdrive/selfdrived/selfdrived.py", + ): + assert "NAP_LOW_VIS_BACKOFF" in (root / rel).read_text() or "lowVisibility" in (root / rel).read_text() + controls = (root / "selfdrive/controls/controlsd.py").read_text() + assert "fade_curvature" in controls + # The back-off must not rewrite the longitudinal accel command. + accel = controls.split("actuators.accel = published_long_accel(", 1)[1].split("Steering PID", 1)[0] + assert "low_vis" not in accel + assert "NAPLatRefOffset" not in controls.split("fade_curvature", 1)[1][:400] + updater = controls.split("def _update_low_visibility", 1)[1].split("def _cone_curvature", 1)[0] + # Reuse the carState socket and the curvatures controlsd already reads. + assert "SubMaster" not in updater + assert "carState" in updater + assert "v_ego" in updater and "blinker" in updater and "yielded" in updater + assert "measured_curvature" in updater and "model_curvature" in updater + assert "lateralManeuverPlan" in updater + assert "desiredCurvature" in updater + # Roundabout gate reuses the yield context. No new carState socket. + assert "roundabout_yield_context" in updater + assert "liveMapDataNAP" in updater + assert "near_roundabout" in updater + # Yielded steering must not become a disengage from this path. + assert "steeringDisengage" not in updater + assert "CC.enabled" not in updater + assert "CC.latActive" not in updater + + +def test_exit_follows_path_confidence_not_lane_lines(): + """A wide plan holds the latch. A settled calm path releases with no paint.""" + lv = LowVisibility() + entered = _step(lv, left=0.95, right=0.95, ystd=4.1, seconds=MODEL_ENTER_S + DT, + edges=NO_EDGES, chatter=CURV_JUMP) + assert entered.active and entered.model_poor + + # Lane lines back, path still wide, curvature still jumping: stay. + held = _step(lv, left=0.92, right=0.85, ystd=2.5, seconds=MODEL_EXIT_S + 0.4, + edges=NO_EDGES, chatter=CURV_JUMP) + assert held.active + + # No lane lines, path settled, curvature calm: release. + cleared = _step(lv, left=0.0, right=0.0, ystd=0.4, + seconds=CURV_WINDOW_S + MODEL_EXIT_S, edges=NO_EDGES, model_k=0.0) + assert not cleared.active and not cleared.alert and not cleared.model_poor + + +def test_turn_does_not_enter_and_straight_at_speed_does(): + """A turn is not low visibility. The same unsure path on a straight is.""" + assert TURN_CURVATURE == 0.01 + assert entry_speed_ok(_mph(25.0)) + assert not entry_speed_ok(_mph(20.0)) + assert not entry_speed_ok(_mph(19.0)) + assert in_turn(0.048) + assert not in_turn(0.0) + assert not in_turn(0.004) + # A jumping desired curvature is not the car turning. + assert not in_turn(0.0) + assert abs(ENTRY_MIN_V_MS - _mph(20.0)) < 1e-9 + + turn = LowVisibility() + out = _step(turn, left=0.01, right=0.01, ystd=3.0, seconds=3.0, + v_ego=_mph(25.0), measured_k=0.048, chatter=CURV_JUMP, edges=NO_EDGES) + assert not out.active and not out.alert and out.authority == 1.0 + + straight = LowVisibility() + early = _step(straight, left=0.01, right=0.01, ystd=3.0, seconds=MODEL_ENTER_S - DT, + v_ego=_mph(25.0), measured_k=0.0, chatter=CURV_JUMP, edges=NO_EDGES) + assert not early.active + entered = _step(straight, left=0.01, right=0.01, ystd=3.0, seconds=3 * DT, + v_ego=_mph(25.0), chatter=CURV_JUMP, edges=NO_EDGES) + assert entered.active and entered.model_poor and entered.alert + + +def test_confident_path_releases_quickly_and_a_turn_holds(): + """Once the plan settles and desired curvature calms, release. A turn holds.""" + assert PATH_Y_STD_EXIT_M == 1.2 + assert not model_is_clear(PATH_Y_STD_EXIT_M, True) + assert model_is_clear(0.8, True) + assert not model_is_poor(0.8, True, True) + + lv = LowVisibility() + entered = _step(lv, left=0.0, right=0.0, ystd=PATH_Y_STD_ENTER_M + 1.0, + seconds=MODEL_ENTER_S + DT, edges=NO_EDGES, chatter=CURV_JUMP, v_ego=_mph(30.0)) + assert entered.active + + # Path settled but desired curvature still jumping: stay. + almost = _step(lv, left=0.90, right=0.05, ystd=0.8, seconds=MODEL_EXIT_S, + edges=NO_EDGES, v_ego=_mph(30.0), chatter=CURV_JUMP) + assert almost.active + cleared = _step(lv, left=0.0, right=0.05, ystd=0.8, + seconds=CURV_WINDOW_S + MODEL_EXIT_S, + edges=NO_EDGES, v_ego=_mph(30.0), model_k=0.0) + assert not cleared.active and not cleared.alert + + held_turn = LowVisibility() + _step(held_turn, left=0.0, right=0.0, ystd=3.0, seconds=MODEL_ENTER_S + DT, + edges=NO_EDGES, chatter=CURV_JUMP) + assert held_turn.active + # Already active as the car turns: stay up even though the plan looks calm. + still = _step(held_turn, left=0.95, right=0.95, ystd=0.4, seconds=2.0, + edges=NO_EDGES, measured_k=0.059, model_k=0.0) + assert still.active and still.model_poor + + # Wide plan keeps the latch after the turn, even with lane lines painted back on. + blind = LowVisibility() + _step(blind, left=0.0, right=0.0, ystd=3.0, seconds=MODEL_ENTER_S + DT, + edges=NO_EDGES, chatter=CURV_JUMP) + stayed = _step(blind, left=0.90, right=0.90, ystd=3.0, seconds=2.0, + edges=NO_EDGES, chatter=CURV_JUMP) + assert stayed.active and stayed.alert + + +def test_latched_alert_stays_up_through_a_turn_then_releases(): + lv = LowVisibility() + _step(lv, left=0.0, right=0.0, ystd=3.0, seconds=MODEL_ENTER_S + DT, + v_ego=_mph(28.0), edges=NO_EDGES, chatter=CURV_JUMP) + assert lv.active + mid = _step(lv, left=0.95, right=0.95, ystd=0.4, seconds=2.0, + v_ego=_mph(22.0), measured_k=0.04, model_k=0.0, edges=NO_EDGES) + assert mid.active + short = _step(lv, left=0.0, right=0.0, ystd=0.8, seconds=MODEL_EXIT_S * 0.5, + v_ego=_mph(30.0), measured_k=0.0, model_k=0.0, edges=NO_EDGES) + assert short.active + done = _step(lv, left=0.0, right=0.0, ystd=0.8, seconds=CURV_WINDOW_S + MODEL_EXIT_S, + v_ego=_mph(30.0), edges=NO_EDGES, model_k=0.0) + assert not done.active + + +def test_uncertain_path_one_second_after_a_turn_still_enters(): + lv = LowVisibility() + turning = _step(lv, left=0.0, right=0.0, ystd=3.0, seconds=2.0, + v_ego=_mph(25.0), measured_k=0.04, chatter=CURV_JUMP, edges=NO_EDGES) + assert not turning.active + arming = _step(lv, left=0.0, right=0.0, ystd=3.0, seconds=STRAIGHT_HOLD_S - 0.10, + v_ego=_mph(25.0), measured_k=0.0, chatter=CURV_JUMP, edges=NO_EDGES) + assert not arming.active + entered = _step(lv, left=0.0, right=0.0, ystd=3.0, + seconds=0.10 + MODEL_ENTER_S + DT, + v_ego=_mph(25.0), chatter=CURV_JUMP, edges=NO_EDGES) + assert entered.active and entered.model_poor + + +def test_blinker_yield_and_low_speed_hold_the_timer_at_zero(): + poor = dict(left=0.0, right=0.0, ystd=4.0, edges=NO_EDGES, chatter=CURV_JUMP) + for gate in ( + dict(blinker=True, v_ego=_mph(30.0)), + dict(yielded=True, v_ego=_mph(30.0)), + dict(v_ego=_mph(17.0)), + dict(v_ego=_mph(20.0)), + ): + lv = LowVisibility() + out = _step(lv, seconds=2.0, **poor, **gate) + assert not out.active and out.authority == 1.0 + # Crossing back above 20 mph with the wheel straight starts a fresh 0.40 s. + lv = LowVisibility() + _step(lv, seconds=1.0, **poor, v_ego=_mph(18.0)) + assert not lv.active + entered = _step(lv, seconds=MODEL_ENTER_S + DT, **poor, v_ego=_mph(21.0)) + assert entered.active + + +def test_camera_collapse_is_unchanged_in_a_turn(): + """Sun glare does not consult the turn gate.""" + lv = LowVisibility() + _step(lv, integ=731, seconds=2.0, measured_k=0.05, model_k=0.05, + v_ego=_mph(12.0), blinker=True, left=0.95, right=0.95, ystd=0.4) + assert not lv.active + one = _step(lv, integ=153, seconds=DT, measured_k=0.05, model_k=0.05, v_ego=_mph(12.0)) + assert not one.camera_blind and not one.active + dropped = _step(lv, integ=153, seconds=0.8, measured_k=0.05, model_k=0.05, + v_ego=_mph(12.0), blinker=True, sun=True) + assert dropped.camera_blind and dropped.active and dropped.alert + assert 153 / 731 < EXPOSURE_COLLAPSE_RATIO + back = _step(lv, integ=700, seconds=2.0, measured_k=0.05, model_k=0.05, v_ego=_mph(12.0), sun=True) + assert not back.camera_blind and not back.active + + +def _frames(seconds, dt=DT): + return max(1, int(round(seconds / dt))) + + +def _scene(lv, *, left, right, ystd, v_mph, measured_k, model_k, + blinker=False, yielded=False, edges=None, integ=2016, dt=DT): + if edges is None: + edges = [8.0, 8.0] + return lv.update( + enabled=True, + lane_probs=[0.5, left, right, 0.5], + edge_stds=edges, + path_t=[0.0, 1.5, 3.0, 6.0], + path_y_std=[0.2, 0.4, ystd, ystd], + integ_lines=integ, + sun_ahead=False, + dt=dt, + v_ego=_mph(v_mph), + blinker=blinker, + yielded=yielded, + measured_curvature=measured_k, + model_curvature=model_k, + ) + + +def test_route174_200426_blinker_turn_does_not_trigger(): + """20:04:26 right turn, blinker on, 18–23 mph, lanes ~0.03, 6.6 s.""" + lv = LowVisibility() + dt = DT + n = _frames(6.6, dt) + for i in range(n): + mph = 18.0 + (23.0 - 18.0) * (i / max(1, n - 1)) + out = _scene(lv, left=0.03, right=0.03, ystd=3.0, v_mph=mph, + measured_k=0.048, model_k=0.032, blinker=True, dt=dt) + assert not out.active and not out.alert and not out.model_poor + + +def test_route174_200616_yielded_s_bend_does_not_trigger(): + """20:06:16 S-bend at 17 mph. Low-vis rose after a same-direction yield.""" + lv = LowVisibility() + dt = DT + curvatures = (-0.053, -0.036, -0.042) + steered = (-0.050, -0.051, -0.041) + n = _frames(13.6, dt) + for i in range(n): + k = curvatures[i % 3] + out = _scene(lv, left=0.05, right=0.08, ystd=3.0, v_mph=17.0, + measured_k=steered[i % 3], model_k=k, yielded=True, dt=dt) + assert not out.active and not out.alert + + +def test_route174_201044_lot_turns_do_not_trigger(): + """20:10:44 final turns into the lot, 3–17 mph, ended parked. Was 96.4 s.""" + lv = LowVisibility() + dt = 0.10 + n = _frames(96.4, dt) + for i in range(n): + mph = 3.0 + (17.0 - 3.0) * (0.5 + 0.5 * math.sin(i / 40.0)) + if i < n // 2: + model_k, measured_k = 0.097, 0.088 + else: + model_k, measured_k = -0.050, -0.051 + lane = 0.01 + 0.07 * (i % 5) / 4.0 + out = _scene(lv, left=lane, right=lane, ystd=3.5, v_mph=mph, + measured_k=measured_k, model_k=model_k, dt=dt) + assert not out.active and not out.alert and out.authority == 1.0 + + +def test_route174_200934_confident_straight_does_not_hold(): + """20:09:34 turn from a stop, then a straight with only the left line. + + Missing the right line is not low visibility. A confident path stays + quiet, and an unsure path releases once it settles, inside 8 s of the + straight instead of the old 25.5 s fade. + """ + lv = LowVisibility() + # Turn from a stop. Model +0.078 vs steered +0.059. Lines gone. + out = _step(lv, left=0.08, right=0.08, ystd=3.0, seconds=8.6, + v_ego=_mph(12.0), measured_k=0.059, model_k=0.078, edges=NO_EDGES) + assert not out.active and out.authority == 1.0 + + # Straight at 30 mph, left line 0.9, right line gone, path settled. + quiet = _step(lv, left=0.90, right=0.15, ystd=0.8, seconds=15.0, + v_ego=_mph(30.0), measured_k=0.0008, model_k=-0.004, edges=NO_EDGES) + assert not quiet.active and quiet.authority == 1.0 + + # If the plan really is lost after the turn, it can arm, then lets go + # once the path is confident again. Far under the old 25.5 s. + unsure = LowVisibility() + _step(unsure, left=0.90, right=0.15, ystd=3.0, seconds=2.0, + measured_k=0.04, model_k=0.05, v_ego=_mph(15.0)) # still in the turn + assert not unsure.active + entered = _step(unsure, left=0.90, right=0.05, ystd=3.0, + seconds=STRAIGHT_HOLD_S + MODEL_ENTER_S + 0.2, + v_ego=_mph(30.0), chatter=CURV_JUMP, edges=NO_EDGES) + assert entered.active + released = _step(unsure, left=0.90, right=0.05, ystd=0.8, + seconds=CURV_WINDOW_S + MODEL_EXIT_S + 0.15, + v_ego=_mph(30.0), model_k=0.0, edges=NO_EDGES) + assert not released.active + assert STRAIGHT_HOLD_S + MODEL_ENTER_S + CURV_WINDOW_S + MODEL_EXIT_S < 8.0 + + +def test_route172_1556_unmarked_stays_quiet_unless_the_path_is_unsure(): + """15:56:24, ~22 mph, both lane lines unseen about 88% of 150 s. + + drivingModelData in the qlog has laneLineMeta and desired curvature, + not position.yStd or roadEdgeStds. Nothing recorded shows the model + was unsure where to go, so missing lines alone do not latch. + """ + lv = LowVisibility() + out = _step(lv, left=0.05, right=0.04, ystd=0.6, seconds=5.0, + v_ego=_mph(22.0), measured_k=0.002, model_k=0.002, edges=NO_EDGES) + assert not out.active and not out.alert and out.authority == 1.0 + + +def test_unmarked_confident_road_stays_quiet(): + """Gravel or a city street with no paint, and a model that knows the path.""" + gravel = LowVisibility() + out = _step(gravel, left=0.02, right=0.03, ystd=0.45, seconds=5.0, + edges=NO_EDGES, v_ego=_mph(28.0), model_k=0.0015, measured_k=0.001) + assert not out.active and out.authority == 1.0 + + city = LowVisibility() + out = _step(city, left=0.04, right=0.05, ystd=0.55, seconds=5.0, + edges=[0.12, 0.18], v_ego=_mph(25.0), model_k=-0.002) + assert not out.active + + # Wide plan alone, or a small wobble, is not enough. One curb blocks it. + wide = LowVisibility() + out = _step(wide, left=0.0, right=0.0, ystd=4.0, seconds=2.0, + edges=NO_EDGES, v_ego=_mph(30.0), model_k=0.001) + assert not out.active + wobble = LowVisibility() + out = _step(wobble, left=0.0, right=0.0, ystd=4.0, seconds=2.0, + edges=NO_EDGES, chatter=0.002, v_ego=_mph(30.0)) + assert not out.active + curb = LowVisibility() + out = _step(curb, left=0.0, right=0.0, ystd=4.0, seconds=2.0, + edges=[0.10, 8.0], chatter=CURV_JUMP, v_ego=_mph(30.0)) + assert not out.active + + +def test_uncertain_path_with_no_edges_triggers(): + """High path std, jumping desired curvature, and no road edge. Lanes irrelevant.""" + lv = LowVisibility() + early = _step(lv, left=0.95, right=0.92, ystd=3.2, seconds=0.25, + edges=NO_EDGES, chatter=CURV_JUMP, v_ego=_mph(25.0)) + assert not early.active + entered = _step(lv, left=0.0, right=0.0, ystd=3.2, seconds=0.45, + edges=NO_EDGES, chatter=CURV_JUMP, v_ego=_mph(25.0)) + assert entered.active and entered.model_poor and entered.alert + + +def test_roundabout_lost_lines_keep_steering_and_a_confident_path_releases(): + """Lines vanish mid-circle. Do not start. A latch from before can release on the ring.""" + # Within 40 m, still straight, path looks lost: the roundabout gate blocks + # what would otherwise arm. Then the circle itself, lines gone, stays quiet + # so authority (and steering) stays full. + blocked = LowVisibility() + approach = _step(blocked, left=0.85, right=0.80, ystd=3.5, seconds=2.0, + v_ego=_mph(25.0), measured_k=0.002, chatter=CURV_JUMP, + edges=NO_EDGES, near_roundabout=True) + assert not approach.active and approach.authority == 1.0 + circle = _step(blocked, left=0.02, right=0.01, ystd=4.0, seconds=6.0, + v_ego=_mph(22.0), measured_k=0.05, chatter=CURV_JUMP, + edges=NO_EDGES, near_roundabout=True) + assert not circle.active and not circle.alert and circle.authority == 1.0 + + # Same approach with no roundabout does arm, so the gate is what held. + open_road = LowVisibility() + armed = _step(open_road, left=0.02, right=0.01, ystd=3.5, seconds=MODEL_ENTER_S + 0.2, + v_ego=_mph(25.0), measured_k=0.002, chatter=CURV_JUMP, + edges=NO_EDGES, near_roundabout=False) + assert armed.active + + # Already active, then the circle, path confident: release without + # waiting to finish the turn. Steering comes back on the ring. + latched = LowVisibility() + _step(latched, left=0.0, right=0.0, ystd=3.5, seconds=MODEL_ENTER_S + DT, + v_ego=_mph(28.0), chatter=CURV_JUMP, edges=NO_EDGES) + assert latched.active + released = _step(latched, left=0.0, right=0.0, ystd=0.5, + seconds=CURV_WINDOW_S + MODEL_EXIT_S + 0.15, + v_ego=_mph(20.5), measured_k=0.05, model_k=0.04, + edges=NO_EDGES, near_roundabout=True) + assert not released.active and not released.alert + + +# Route 0000017b--8ced80769d (Oct 10, 2026, ~4:19 PM CT, clear day): road +# camera integLines at 4 Hz, 100–150 s into the route. Shade (≈466) into sun +# (≈45). The path was confident (lateral std at 3 s ≈ 0.16 m) and the sun was +# 23° up. The old build latched camera-blind here and zeroed lateral for 7+ min. +ROUTE_17B_INTEG_4HZ = [ + 161, 162, 169, 177, 171, 154, 147, 142, 134, 124, 120, 122, 119, 111, 112, 113, 110, 110, 116, 122, + 122, 122, 130, 138, 142, 149, 152, 156, 160, 169, 174, 180, 186, 175, 164, 160, 147, 147, 150, 155, + 152, 164, 171, 170, 170, 193, 215, 214, 213, 238, 268, 302, 344, 365, 401, 446, 427, 386, 445, 466, + 465, 460, 452, 440, 430, 418, 397, 376, 362, 341, 324, 319, 322, 319, 316, 325, 328, 328, 327, 322, + 290, 268, 240, 217, 212, 211, 208, 199, 192, 184, 174, 170, 172, 177, 177, 167, 157, 144, 133, 121, + 121, 124, 125, 120, 133, 138, 136, 134, 129, 125, 124, 127, 126, 127, 128, 125, 124, 116, 117, 112, + 102, 92, 99, 106, 105, 101, 108, 122, 135, 145, 139, 142, 153, 157, 165, 172, 170, 165, 168, 176, + 185, 182, 177, 188, 191, 190, 190, 187, 178, 172, 167, 149, 140, 135, 136, 133, 131, 125, 127, 127, + 127, 129, 129, 128, 129, 125, 123, 122, 120, 116, 113, 112, 107, 101, 96, 88, 82, 80, 78, 74, + 69, 65, 60, 55, 52, 49, 49, 48, 47, 45, 47, 47, 49, 50, 50, 50, 50, 50, 50, 46, +] +CONFIDENT_17B = dict(ystd=0.16, edges=[0.3, 0.3], v_ego=_mph(45.0)) + + +def _play_17b(lv, sun_fn): + outs = [] + for i, integ in enumerate(ROUTE_17B_INTEG_4HZ): + outs.append(_step(lv, integ=integ, seconds=0.25, sun=sun_fn(i), **CONFIDENT_17B)) + return outs + + +def test_route17b_shade_to_sun_never_latches_or_reduces_lateral(): + lv = LowVisibility() + outs = _play_17b(lv, lambda i: False) + assert not any(o.active or o.alert or o.camera_blind for o in outs) + assert all(o.authority == 1.0 for o in outs) + + +def test_route17b_forced_latch_releases_within_3s_and_never_zeroes_lateral(): + """Even if glare were corroborated (sun low ahead) at the shade→sun drop, + a confident path releases within the 3 s backstop and lateral stays on.""" + lv = LowVisibility() + drop = 80 # ≈ where 466 falls toward 210 + outs = _play_17b(lv, lambda i: i < drop + 4) + latched = [i for i, o in enumerate(outs) if o.camera_blind] + assert latched, "the corroborated drop should latch" + first_unsun = drop + 4 + released = next(i for i in range(first_unsun, len(outs)) if not outs[i].active) + assert (released - first_unsun) * 0.25 <= 3.0 + 0.25 + assert min(o.authority for o in outs) >= CAMERA_ONLY_AUTHORITY - 1e-9 + assert not any(o.active for o in outs[released:]) + + +def test_route17b_no_ratio_releases_in_about_one_second(): + """Baseline under 280 (normal daylight) means clear: release after ~1 s.""" + lv = LowVisibility() + _step(lv, integ=466, seconds=13.0, **CONFIDENT_17B) + _step(lv, integ=150, seconds=0.5, sun=True, **CONFIDENT_17B) + assert lv.active + t = 0.0 + # Mid-band (ratio 0.45–0.70 would hold); once the bright sample ages out + # the baseline drops under 280 and there is no ratio. + while lv.active and t < 20.0: + _step(lv, integ=45, seconds=DT, **dict(CONFIDENT_17B, ystd=1.5)) + t += DT + assert not lv.active + assert t <= 13.0 + + +def test_model_uncertainty_corroborates_glare_without_sun(): + lv = LowVisibility() + _step(lv, integ=731, seconds=2.0, ystd=1.5) + out = _step(lv, integ=153, seconds=0.8, ystd=1.5) + assert out.camera_blind and out.active + assert out.authority >= AUTHORITY_FLOOR + + +def test_authority_tracks_uncertainty_and_never_zeroes(): + assert authority_target(False, False, False, 5.0) == 1.0 + assert authority_target(True, False, True, 0.2) == CAMERA_ONLY_AUTHORITY + mid = authority_target(True, True, False, 2.6) + assert AUTHORITY_FLOOR < mid < 1.0 + assert authority_target(True, True, False, 9.0) == AUTHORITY_FLOOR + assert authority_target(True, True, True, float("nan")) >= AUTHORITY_FLOOR + + +def test_prolonged_degrade_raises_a_distinct_louder_alert(): + lv = LowVisibility() + poor = dict(left=0.0, right=0.0, ystd=4.1, edges=NO_EDGES, chatter=CURV_JUMP, dt=0.05) + _step(lv, seconds=PROLONGED_S - 1.0, **poor) + assert lv.active and not lv.prolonged + _step(lv, seconds=1.5, **poor) + assert lv.prolonged + assert log.OnroadEvent.EventName.lowVisibilityProlonged is not None + root = Path(__file__).resolve().parents[4] + events = (root / "selfdrive/selfdrived/events.py").read_text() + block = events.split('_low_visibility_prolonged = getattr(EventName, "lowVisibilityProlonged"', 1)[1][:600] + assert "ET.WARNING" in block and "AudibleAlert.none" not in block + assert "ET.SOFT_DISABLE" not in block and "ET.IMMEDIATE_DISABLE" not in block + selfdrived = (root / "selfdrive/selfdrived/selfdrived.py").read_text() + assert "lowVisibilityProlonged" in selfdrived and "LOW_VIS_PROLONGED_S" in selfdrived + # No new carState subscriber. + assert selfdrived.count("sub_sock('carState'") <= 1 diff --git a/selfdrive/controls/lib/tests/test_lat_turn_geometry.py b/selfdrive/controls/lib/tests/test_lat_turn_geometry.py new file mode 100644 index 00000000000000..36422fa7cdc05d --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lat_turn_geometry.py @@ -0,0 +1,666 @@ +"""Turn geometry correction (NAPLatTurnGeom / NAPLatRefOffset). + +Pins: default ON, OFF == stock lookahead (1119c0f) bit-for-bit, the low-speed +delay table, rear reference offset, speed floor/fade, 0.2 s cap and 0.2 s +floor, 250 deg/s rate-limit hold-off, lateralManeuverPlan untouched, and the +#223 roundabout outer bias stripped while the correction is active. + +Turn-in delay trim (NAPTurnInDelay, steps -2..+3, 30 ms each, low-speed band +only): default 0 is bit-identical, >= 10 mph untouched, bounded, slewed. + +Low-speed reach (Sep 28 PM): 1.5-2.5 m/s fade-in, 0.25 s cap and direct plan +sampling down to 0.2 s below 8 mph, reduction frozen (not slewed to stock) +while rate-limited below 10 mph, and >= 10 mph identical to 7c49a8e. +""" +import math +from pathlib import Path + +import numpy as np +import pytest + +from openpilot.selfdrive.controls.lib import lat_turn_geometry as tg +from openpilot.selfdrive.controls.lib.drive_helpers import MIN_STABLE_DELAY, curv_from_psis, get_curvature_from_plan +from openpilot.selfdrive.mapd.roundabout import ( + RoundaboutHint, roundabout_lateral_curvature_bias, roundabout_outer_curvature_bias, + roundabout_outer_path_offset_m, +) + +ROOT = Path(__file__).resolve().parents[4] +DT_MDL = 0.05 +STOCK = 0.40 + 0.05 + 0.025 # lagd 0.40 + frame + action delay (LAT_SMOOTH 0) + + +class _CP: + def __init__(self, brand="tesla", fp="TESLA_MODEL_S_PREAP"): + self.brand = brand + self.carFingerprint = fp + + +# ---------- params / toggle ---------- + +def test_params_default_on_and_offset_035(): + keys = (ROOT / "common/params_keys.h").read_text() + assert '{"NAPLatTurnGeom", {PERSISTENT, BOOL, "1"}}' in keys + assert '{"NAPLatRefOffset", {PERSISTENT, FLOAT, "0.35"}}' in keys + assert tg.REF_OFFSET_DEFAULT_M == 0.35 + + +def test_active_only_preap_and_toggle_on(): + assert tg.turn_geometry_active(tg.is_preap_car(_CP()), True) is True + assert tg.turn_geometry_active(tg.is_preap_car(_CP()), False) is False + assert tg.turn_geometry_active(tg.is_preap_car(_CP(fp="TESLA_MODEL_S_RAVEN")), True) is False + assert tg.turn_geometry_active(tg.is_preap_car(_CP(brand="toyota")), True) is False + + +def test_ref_offset_clamped_to_menu_range(): + assert tg.clamp_ref_offset(-1) == 0.0 + assert tg.clamp_ref_offset(1.9) == 1.0 + assert tg.clamp_ref_offset(None) == 0.35 + assert tg.clamp_ref_offset(float("nan")) == 0.35 + assert tg.clamp_ref_offset(0.5) == 0.5 + + +# ---------- formula ---------- + +def test_off_is_stock_bit_for_bit(): + c = tg.TurnGeometryCorrection(DT_MDL) + for v in np.linspace(0.0, 40.0, 81): + for stock in (0.12, 0.2, 0.3, STOCK, 0.6): + # even with a pinned rate limiter the OFF path is the plain stock value + out = c.update(enabled=False, stock_lookahead_s=stock, v_ego=float(v), ref_offset_m=1.0, + lat_active=True, cmd_angle_deg=90.0, out_angle_deg=float(v)) + assert out is stock + assert c.reduction_s == 0.0 + + +def test_on_default_reduces_lookahead_at_turn_speed(): + c = tg.TurnGeometryCorrection(DT_MDL) + out = STOCK + for _ in range(40): + out = c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=10.0, ref_offset_m=0.35) + assert out == pytest.approx(STOCK - (0.10 + 0.035), abs=1e-6) + + +def test_delay_table_values(): + # measured desired->yaw lag minus lagd, per speed + assert tg.target_reduction_s(10.0, 0.0) == pytest.approx(0.10) + assert tg.target_reduction_s(14.0, 0.0) == pytest.approx(0.08) + assert tg.target_reduction_s(19.0, 0.0) == pytest.approx(0.05) + assert tg.target_reduction_s(7.5, 0.0) == pytest.approx(0.115) + + +def test_ref_offset_is_used(): + assert tg.target_reduction_s(10.0, 0.35) == pytest.approx(0.135) + assert tg.target_reduction_s(10.0, 0.7) == pytest.approx(0.17) + assert tg.target_reduction_s(10.0, 0.35) > tg.target_reduction_s(10.0, 0.0) + + +def test_ref_offset_speed_floor(): + assert tg.ref_offset_s(1.0, 0.35) == pytest.approx(0.35 / 3.0) + assert tg.ref_offset_s(0.5, 0.9) == pytest.approx(0.3) + assert tg.ref_offset_s(7.0, 0.35) == pytest.approx(0.05) + + +def test_highway_only_reference_offset(): + for v in (25.0, 30.0, 35.0): + assert tg.target_reduction_s(v, 0.35) == pytest.approx(0.35 / v) + assert tg.target_reduction_s(v, 0.35) < 0.015 + assert tg.target_reduction_s(v, 0.0) == 0.0 + + +def test_no_effect_below_1p5ms_and_continuous_fade(): + for v in (0.0, 1.0, 1.49, 1.5): + assert tg.target_reduction_s(v, 0.35) == 0.0 + # half faded at 2.0 m/s: 0.5 * (0.13 + 0.35 / 3) + assert tg.target_reduction_s(2.0, 0.35) == pytest.approx(0.5 * (0.13 + 0.35 / 3.0)) + assert tg.target_reduction_s(2.5, 0.35) == pytest.approx(0.13 + 0.35 / 3.0) + vs = np.linspace(0.0, 40.0, 4001) + r = np.array([tg.target_reduction_s(float(v), 0.35) for v in vs]) + assert np.max(np.abs(np.diff(r))) <= 0.0026 # no jumps (fade slope 0.25 s per m/s) + assert np.all(r <= tg.LOW_SPEED_MAX_REDUCTION_S + 1e-12) + assert np.all(r[vs >= tg.LOW_SPEED_REACH_END_MS] <= tg.MAX_REDUCTION_S + 1e-12) + + +def test_reduction_capped_at_02(): + assert tg.target_reduction_s(5.0, 1.0) == pytest.approx(0.2) + assert tg.apply_reduction(STOCK, 0.5) == pytest.approx(STOCK - 0.2) + + +def test_min_lookahead_floor_never_raises(): + assert tg.apply_reduction(0.30, 0.2) == pytest.approx(0.20) + assert tg.apply_reduction(0.25, 0.2) == pytest.approx(0.20) + assert tg.apply_reduction(0.15, 0.2) == pytest.approx(0.15) # already below floor: unchanged + assert tg.apply_reduction(0.15, 0.0) == 0.15 + + +def test_rate_limit_holds_stock_then_slews_back(): + c = tg.TurnGeometryCorrection(DT_MDL) + out_angle = 0.0 + for _ in range(40): + c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=6.0, ref_offset_m=0.35, + lat_active=True, cmd_angle_deg=0.0, out_angle_deg=out_angle) + full = c.reduction_s + assert full == pytest.approx(tg.target_reduction_s(6.0, 0.35)) + # turn-in from low speed: output moving 12.5 deg per 50 ms (250 deg/s), 80 deg short + outs = [] + for _ in range(8): + out_angle += 12.5 + outs.append(c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=6.0, ref_offset_m=0.35, + lat_active=True, cmd_angle_deg=out_angle + 80.0, out_angle_deg=out_angle)) + assert c.rate_limited + assert c.reduction_s == pytest.approx(0.0, abs=1e-9) + assert outs[-1] == pytest.approx(STOCK) + # slewed, not stepped + assert np.max(np.abs(np.diff(outs))) <= tg.REDUCTION_SLEW_S_PER_S * DT_MDL + 1e-9 + # limiter releases: held 0.5 s, then back to full correction + for i in range(int(tg.RATE_LIMIT_HOLD_S / DT_MDL) - 1): + c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=6.0, ref_offset_m=0.35, + lat_active=True, cmd_angle_deg=out_angle, out_angle_deg=out_angle) + assert c.reduction_s == 0.0 + for _ in range(40): + c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=6.0, ref_offset_m=0.35, + lat_active=True, cmd_angle_deg=out_angle, out_angle_deg=out_angle) + assert c.reduction_s == pytest.approx(full) + + +def test_small_gap_or_slow_rate_is_not_rate_limited(): + assert not tg.steer_rate_limited(10.0, 9.0, 0.0, DT_MDL, True) # fast but caught up + assert not tg.steer_rate_limited(50.0, 1.0, 0.5, DT_MDL, True) # far but slow + assert not tg.steer_rate_limited(50.0, 12.5, 0.0, DT_MDL, False) # lat off + assert tg.steer_rate_limited(50.0, 12.5, 0.0, DT_MDL, True) + + +# ---------- plan sampling: onset later ---------- + +def _turn_plan(v, t_turn, kappa): + t = np.array([10.0 * (i / 32) ** 2 for i in range(33)]) # ModelConstants.T_IDXS + yaw_rate = np.where(t >= t_turn, v * kappa, 0.0) + yaw = np.concatenate([[0.0], np.cumsum(0.5 * (yaw_rate[1:] + yaw_rate[:-1]) * np.diff(t))]) + return t, yaw, yaw_rate + + +def test_plan_turn_in_later_steady_state_same(): + v, kappa = 6.0, 1.0 / 15.0 + on_t = tg.apply_reduction(STOCK, tg.target_reduction_s(v, 0.35)) + assert on_t == pytest.approx(STOCK - 0.182, abs=0.002) + # turn 0.40 s ahead: stock already steers into it, corrected waits + t, yaw, yr = _turn_plan(v, 0.40, kappa) + assert get_curvature_from_plan(yaw, yr, t, v, STOCK) > 0.01 + assert get_curvature_from_plan(yaw, yr, t, v, on_t) == pytest.approx(0.0, abs=1e-9) + # on the arc: same curvature (steady radius unaffected by timing) + t, yaw, yr = _turn_plan(v, -1.0, kappa) + off_k = get_curvature_from_plan(yaw, yr, t, v, STOCK) + on_k = get_curvature_from_plan(yaw, yr, t, v, on_t) + assert on_k == pytest.approx(off_k, rel=1e-6) + assert on_k == pytest.approx(kappa, rel=0.05) + + +# ---------- closed-loop kinematic ---------- + +def _plant_lag(v): + return float(np.interp(v, [5, 10, 14, 19, 25], [0.26, 0.29, 0.31, 0.34, 0.39])) + 0.075 + + +def _sim_turn(R, v, lookahead, d=1.90, d_t=1.55, angle=math.pi / 2, dt=0.01): + """Rear-axle deviation (+inside / -outside) from the lane-centre arc.""" + L1, La, ds = 40.0, R * angle, 0.02 + ss = np.arange(0.0, L1 + La + 40.0, ds) + k = np.where((ss >= L1) & (ss < L1 + La), 1.0 / R, 0.0) + psi = np.cumsum(k * ds) + X, Y = np.cumsum(np.cos(psi) * ds), np.cumsum(np.sin(psi) * ds) + TX, TY = X + d_t * np.cos(psi), Y + d_t * np.sin(psi) + i0 = int(20.0 / ds) + x, y, h = X[i0], Y[i0], psi[i0] + buf = [0.0] * int(round(_plant_lag(v) / dt)) + Ld = max(6.0, 1.5 * v) + jr = jc = i0 + out = [] + while True: + lo, hi = max(0, jr - 100), min(len(ss), jr + 100) + jr = lo + int(np.argmin((X[lo:hi] - x) ** 2 + (Y[lo:hi] - y) ** 2)) + if ss[jr] > L1 + La + 25.0: + break + px, py = x + d * math.cos(h), y + d * math.sin(h) + lo, hi = max(0, jc - 100), min(len(ss), jc + 150) + jc = lo + int(np.argmin((TX[lo:hi] - px) ** 2 + (TY[lo:hi] - py) ** 2)) + e = (px - TX[jc]) * -math.sin(psi[jc]) + (py - TY[jc]) * math.cos(psi[jc]) + buf.append(float(np.interp(ss[jc] + v * lookahead, ss, k)) - 2.0 * e / (Ld * Ld)) + kk = buf.pop(0) + x += v * math.cos(h) * dt + y += v * math.sin(h) * dt + h += v * kk * dt + out.append((x - X[jr]) * -math.sin(psi[jr]) + (y - Y[jr]) * math.cos(psi[jr])) + o = np.array(out) + return float(o.max()), float(o.min()) + + +@pytest.mark.parametrize("R,v", [(10.0, 4.5), (15.0, 5.5), (20.0, 6.5)]) +def test_closed_loop_corner_cut_removed_without_running_wide(R, v): + on_t = tg.apply_reduction(STOCK, tg.target_reduction_s(v, tg.REF_OFFSET_DEFAULT_M)) + off_in, off_out = _sim_turn(R, v, STOCK) + on_in, on_out = _sim_turn(R, v, on_t) + assert off_in > 0.45 # today: early turn-in clips the corner + assert on_in < 0.2 and on_in < 0.4 * off_in + assert on_out > -0.2 # and does not run wide + + +def test_closed_loop_highway_unchanged(): + v = 30.0 + on_t = tg.apply_reduction(STOCK, tg.target_reduction_s(v, 0.35)) + assert STOCK - on_t < 0.015 + + +# ---------- wiring pins ---------- + +def test_modeld_applies_only_to_model_action_lookahead(): + src = (ROOT / "selfdrive/modeld/modeld.py").read_text() + assert "lat_action_t = lat_delay + frame_delay + action_delay\n" in src + call = "action = get_action_from_model(model_output, prev_action, lat_action_t, long_delay + frame_delay + action_delay, v_ego," + assert call + "\n lat_sample_floor_s)" in src + # stock sample floor unless the Pre-AP correction supplies one + assert " lat_sample_floor_s = MIN_STABLE_DELAY\n if turn_geom_preap:" in src + assert " lat_sample_floor_s = turn_geom.sample_floor_s\n" in src + assert "desired_curvature = plan_curvature(" in src + assert "get_curvature_from_plan(" not in src + assert "if turn_geom_preap:" in src + assert "enabled=turn_geom_on, stock_lookahead_s=lat_action_t" in src + # no schema change: modeld writes no new capnp fields + assert "napLat" not in src + + +def test_lateral_maneuver_plan_bypasses_correction(): + src = (ROOT / "selfdrive/controls/controlsd.py").read_text() + assert (" if self.sm.valid['lateralManeuverPlan']:\n" + " model_or_plan_curvature = self.sm['lateralManeuverPlan'].desiredCurvature\n") in src + assert "turn_geom.update" not in src + assert "napLat" not in src + + +# ---------- roundabout: no double compensation ---------- + +def _hint(on=True, approaching=False, d=0.0): + return RoundaboutHint(on_roundabout=on, approaching=approaching, distance_m=d, speed_limit_ms=0.0, way_id=1) + + +def test_roundabout_outer_bias_stripped_when_correction_active(): + for h in (_hint(on=True), _hint(on=False, approaching=True, d=30.0), _hint(on=False, approaching=True, d=150.0), None): + for rhd in (False, True): + assert roundabout_lateral_curvature_bias(h, is_rhd=rhd, turn_geometry_active=True) == 0.0 + + +def test_roundabout_outer_bias_off_path_is_legacy(): + for h in (_hint(on=True), _hint(on=False, approaching=True, d=30.0), _hint(on=False, approaching=True, d=150.0), None): + for rhd in (False, True): + legacy = roundabout_outer_curvature_bias(roundabout_outer_path_offset_m( + on_roundabout=bool(h.on_roundabout) if h is not None else False, + approaching=bool(h.approaching) if h is not None else False, + distance_m=float(h.distance_m) if h is not None else 0.0, + is_rhd=rhd)) + assert roundabout_lateral_curvature_bias(h, is_rhd=rhd, turn_geometry_active=False) == legacy + assert roundabout_lateral_curvature_bias(_hint(on=True), turn_geometry_active=False) == pytest.approx(-2 * 3.2 / 18.0 ** 2) + + +def test_controlsd_gates_roundabout_bias_on_turn_geometry(): + src = (ROOT / "selfdrive/controls/controlsd.py").read_text() + assert "roundabout_lateral_curvature_bias(\n rb_hint, is_rhd=is_rhd, turn_geometry_active=self._turn_geom_active," in src + assert "self._turn_geom_preap, bool(self.params.get_bool(PARAM_TURN_GEOMETRY)))" in src + assert "roundabout_outer_curvature_bias(" not in src + + +# ---------- low-speed reach (Sep 28 PM: 5-8 mph turns still clip the inside) ---------- + +MPH = 0.44704 + + +def test_low_speed_reach_band_and_values(): + for mph in (1.0, 3.0, 5.0, 8.0): + assert tg.low_speed_reach_weight(mph * MPH) == pytest.approx(1.0) + assert tg.low_speed_reach_weight(9.0 * MPH) == pytest.approx(0.5) + for mph in (10.0, 12.0, 20.0, 70.0): + assert tg.low_speed_reach_weight(mph * MPH) == 0.0 + assert tg.reduction_cap_s(mph * MPH) == tg.MAX_REDUCTION_S + assert tg.sample_floor_s(mph * MPH) == MIN_STABLE_DELAY + assert tg.reduction_cap_s(6.0 * MPH) == pytest.approx(0.25) + assert tg.sample_floor_s(6.0 * MPH) == pytest.approx(0.20) + assert tg.reduction_cap_s(9.0 * MPH) == pytest.approx(0.225) + assert tg.sample_floor_s(9.0 * MPH) == pytest.approx(0.25) + + +def _settle(c, v, n=60, **kw): + out = None + for _ in range(n): + out = c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=v, ref_offset_m=0.35, **kw) + return out + + +@pytest.mark.parametrize("mph", [6.0, 7.6]) +def test_low_speed_extra_reach_at_5_to_8_mph(mph): + v = mph * MPH + c = tg.TurnGeometryCorrection(DT_MDL) + la = _settle(c, v) + red = min(0.25, 0.13 + 0.35 / max(v, 3.0)) + assert la == pytest.approx(STOCK - red, abs=1e-6) # ~0.23 s, was 0.475 (6 mph) / 0.40 (7.6 mph) + assert la < MIN_STABLE_DELAY + assert c.sample_floor_s == pytest.approx(0.20) + # a turn starting 0.26 s ahead: 7c49a8e (0.3 s floor) already steers, the new sampling waits + t, yaw, yr = _turn_plan(v, 0.26, 1.0 / 8.0) + assert get_curvature_from_plan(yaw, yr, t, v, la) > 0.01 + assert tg.plan_curvature(yaw, yr, t, v, la, c.sample_floor_s) == pytest.approx(0.0, abs=1e-9) + # steady arc: same radius either way + t, yaw, yr = _turn_plan(v, -1.0, 1.0 / 8.0) + assert tg.plan_curvature(yaw, yr, t, v, la, c.sample_floor_s) == pytest.approx( + get_curvature_from_plan(yaw, yr, t, v, la), rel=1e-6) + + +def test_plan_curvature_stock_floor_is_get_curvature_from_plan(): + rng = np.random.default_rng(7) + t = np.array([10.0 * (i / 32) ** 2 for i in range(33)]) + for _ in range(300): + yr = np.cumsum(rng.normal(0, 0.05, 33)) + yaw = np.concatenate([[0.0], np.cumsum(0.5 * (yr[1:] + yr[:-1]) * np.diff(t))]) + v = float(rng.uniform(0.0, 40.0)) + a = float(rng.uniform(0.05, 0.8)) + assert tg.plan_curvature(yaw, yr, t, v, a) == get_curvature_from_plan(yaw, yr, t, v, a) + assert tg.plan_curvature(yaw, yr, t, v, a, MIN_STABLE_DELAY) == get_curvature_from_plan(yaw, yr, t, v, a) + + +def test_plan_curvature_direct_sampling_below_03(): + t, yaw, yr = _turn_plan(3.0, 0.1, 1.0 / 8.0) + for a in (0.2, 0.22, 0.25, 0.28): + k = tg.plan_curvature(yaw, yr, t, 3.0, a, 0.2) + assert k == pytest.approx(curv_from_psis(np.interp(a, t, yaw), yr[0], 3.0, a)) + assert k != pytest.approx(get_curvature_from_plan(yaw, yr, t, 3.0, a), rel=1e-3) + # clamped at the floor, continuous at 0.3 s + assert tg.plan_curvature(yaw, yr, t, 3.0, 0.1, 0.2) == pytest.approx(tg.plan_curvature(yaw, yr, t, 3.0, 0.2, 0.2)) + assert tg.plan_curvature(yaw, yr, t, 3.0, 0.2999999, 0.2) == pytest.approx( + get_curvature_from_plan(yaw, yr, t, 3.0, 0.3), rel=1e-4) + + +def test_rate_limit_freezes_reduction_below_10mph(): + v = 6.0 * MPH + c = tg.TurnGeometryCorrection(DT_MDL) + out_angle = 0.0 + full_out = _settle(c, v, lat_active=True, cmd_angle_deg=0.0, out_angle_deg=out_angle) + full = c.reduction_s + assert full == pytest.approx(min(0.25, 0.13 + 0.35 / 3.0)) + for _ in range(8): + out_angle += 12.5 + o = c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=v, ref_offset_m=0.35, + lat_active=True, cmd_angle_deg=out_angle + 80.0, out_angle_deg=out_angle) + assert c.rate_limited + assert c.reduction_s == full # frozen, not slewed back to stock + assert o == full_out + for _ in range(40): + c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=v, ref_offset_m=0.35, + lat_active=True, cmd_angle_deg=out_angle, out_angle_deg=out_angle) + assert c.reduction_s == pytest.approx(full) + + +# Verbatim 7c49a8e formulas (reference for the >= 10 mph identity pin). +class _Legacy: + def __init__(self, dt): + self.dt, self.reduction_s, self._hold_s, self._out_prev = dt, 0.0, 0.0, None + + @staticmethod + def target(v_ego, ref_offset_m): + v = max(0.0, float(v_ego)) + d = float(np.interp(v, (5.0, 10.0, 14.0, 19.0, 25.0), (-0.13, -0.10, -0.08, -0.05, 0.0))) + red = min(0.20, max(0.0, -d + tg.clamp_ref_offset(ref_offset_m) / max(v, 3.0))) + return red * float(np.clip((v - 3.0) / (4.0 - 3.0), 0.0, 1.0)) + + @staticmethod + def apply(stock, reduction): + stock = float(stock) + red = min(0.20, max(0.0, float(reduction))) + if red <= 0.0: + return stock + return max(min(stock, 0.20), stock - red) + + def update(self, *, enabled, stock_lookahead_s, v_ego, ref_offset_m, lat_active=True, cmd_angle_deg=0.0, + out_angle_deg=None): + if not enabled: + self.reduction_s, self._hold_s, self._out_prev = 0.0, 0.0, None + return stock_lookahead_s + limited = False + if out_angle_deg is not None: + if self._out_prev is not None and lat_active and self.dt > 0.0: + rate = abs(float(out_angle_deg) - float(self._out_prev)) / self.dt + limited = rate >= 0.8 * 250.0 and abs(float(cmd_angle_deg) - float(out_angle_deg)) > 2.5 + self._out_prev = float(out_angle_deg) + self._hold_s = 0.5 if limited else max(0.0, self._hold_s - self.dt) + target = 0.0 if self._hold_s > 0.0 else self.target(v_ego, ref_offset_m) + step = 0.5 * self.dt + self.reduction_s += float(np.clip(target - self.reduction_s, -step, step)) + return self.apply(stock_lookahead_s, self.reduction_s) + + +def test_at_or_above_10mph_output_identical_to_7c49a8e(): + rng = np.random.default_rng(253) + t_idx = np.array([10.0 * (i / 32) ** 2 for i in range(33)]) + for trial in range(20): + new, old = tg.TurnGeometryCorrection(DT_MDL), _Legacy(DT_MDL) + out_angle, v = 0.0, float(rng.uniform(tg.LOW_SPEED_REACH_END_MS, 12.0)) + offset = float(rng.choice([0.0, 0.35, 0.6, 1.0])) + stock = float(rng.choice([STOCK, 0.36, 0.52])) + for step in range(400): + v = float(np.clip(v + rng.normal(0, 0.3), tg.LOW_SPEED_REACH_END_MS, 40.0)) + burst = (step // 40) % 3 == 1 # rate-limited bursts + out_angle += 12.5 if burst else float(rng.normal(0, 1.0)) + cmd = out_angle + (80.0 if burst else float(rng.normal(0, 1.0))) + enabled = not (trial % 5 == 4 and 150 <= step < 170) + kw = dict(enabled=enabled, stock_lookahead_s=stock, v_ego=v, ref_offset_m=offset, + lat_active=True, cmd_angle_deg=cmd, out_angle_deg=out_angle) + a_new, a_old = new.update(**kw), old.update(**kw) + assert a_new == a_old, (trial, step, v) + assert new.sample_floor_s == MIN_STABLE_DELAY + yr = np.cumsum(rng.normal(0, 0.03, 33)) + yaw = np.concatenate([[0.0], np.cumsum(0.5 * (yr[1:] + yr[:-1]) * np.diff(t_idx))]) + assert tg.plan_curvature(yaw, yr, t_idx, v, a_new, new.sample_floor_s) == \ + get_curvature_from_plan(yaw, yr, t_idx, v, a_old) + + +@pytest.mark.parametrize("R,v", [(7.0, 6.0 * MPH), (6.0, 7.0 * MPH)]) +def test_closed_loop_low_speed_inside_cut_reduced(R, v): + # effective sample time = what get_curvature_from_plan / plan_curvature actually use + old = _Legacy(DT_MDL) + old_t = max(old.apply(STOCK, old.target(v, 0.35)), MIN_STABLE_DELAY) + c = tg.TurnGeometryCorrection(DT_MDL) + la = _settle(c, v) + new_t = max(la, c.sample_floor_s) + old_in, old_out = _sim_turn(R, v, old_t) + new_in, new_out = _sim_turn(R, v, new_t) + assert old_in > 0.35 # 7c49a8e: still clips the inside at 6-8 mph + assert new_in < 0.5 * old_in + assert new_out > -0.2 # and does not run wide + + +# ---------- turn-in delay trim (NAPTurnInDelay) ---------- + +def _la(step, v, stock=STOCK, n=80, enabled=True): + c = tg.TurnGeometryCorrection(DT_MDL) + out = None + for _ in range(n): + out = c.update(enabled=enabled, stock_lookahead_s=stock, v_ego=v, ref_offset_m=0.35, turn_in_step=step) + return out, c + + +def test_turn_in_param_defaults_to_zero_int(): + keys = (ROOT / "common/params_keys.h").read_text() + assert '{"NAPTurnInDelay", {PERSISTENT, INT, "0"}}' in keys + assert tg.PARAM_TURN_IN_DELAY == "NAPTurnInDelay" + assert (tg.TURN_IN_STEP_MIN, tg.TURN_IN_STEP_MAX) == (-2, 3) + assert tg.TURN_IN_STEP_S == pytest.approx(0.030) + assert tg.TURN_IN_MIN_LOOKAHEAD_S == pytest.approx(0.10) + + +def test_turn_in_step_is_clamped_and_junk_is_zero(): + assert [tg.clamp_turn_in_step(x) for x in (-9, -2, -1, 0, 1, 2, 3, 4, 99)] == [-2, -2, -1, 0, 1, 2, 3, 3, 3] + assert tg.clamp_turn_in_step(2.6) == 3 + assert tg.clamp_turn_in_step(-1.4) == -1 + for junk in (None, "x", float("nan"), float("inf"), [], {}): + assert tg.clamp_turn_in_step(junk) == 0 + + +def test_turn_in_step_zero_is_bit_identical_to_the_untrimmed_update(): + rng = np.random.default_rng(7) + t_idx = np.linspace(0.0, 10.0, 33) + for trial in range(20): + new, old = tg.TurnGeometryCorrection(DT_MDL), tg.TurnGeometryCorrection(DT_MDL) + v = float(rng.uniform(0.5, 6.0)) + out_angle = 0.0 + stock = float(rng.uniform(0.25, 0.7)) + for step in range(300): + v = float(np.clip(v + rng.normal(0, 0.3), 0.0, 40.0)) + burst = (step // 40) % 3 == 1 + out_angle += 12.5 if burst else float(rng.normal(0, 1.0)) + cmd = out_angle + (80.0 if burst else float(rng.normal(0, 1.0))) + kw = dict(enabled=not (trial % 5 == 4 and 100 <= step < 120), stock_lookahead_s=stock, v_ego=v, + ref_offset_m=0.35, lat_active=True, cmd_angle_deg=cmd, out_angle_deg=out_angle) + a = old.update(**kw) + assert new.update(turn_in_step=0, **kw) == a, (trial, step) + assert new.sample_floor_s == old.sample_floor_s + assert new.trim_s == 0.0 + yr = np.cumsum(rng.normal(0, 0.03, 33)) + yaw = np.concatenate([[0.0], np.cumsum(0.5 * (yr[1:] + yr[:-1]) * np.diff(t_idx))]) + assert tg.plan_curvature(yaw, yr, t_idx, v, a, old.sample_floor_s) == \ + tg.plan_curvature(yaw, yr, t_idx, v, a, new.sample_floor_s) + + +@pytest.mark.parametrize("step", [-2, -1, 1, 2, 3]) +def test_turn_in_trim_never_changes_10mph_and_up_or_below_1p5ms(step): + for v in (10.0 * MPH, 11.0 * MPH, 15.0 * MPH, 25.0, 40.0, 1.5, 1.0, 0.3): + base, cb = _la(0, v) + trim, ct = _la(step, v) + assert trim == base + assert ct.sample_floor_s == cb.sample_floor_s + assert ct.trim_s == 0.0 + + +@pytest.mark.parametrize("step", [-2, -1, 1, 2, 3]) +@pytest.mark.parametrize("mph", [5.6, 6.0, 7.0, 8.0]) +def test_turn_in_each_step_is_30ms_in_the_full_band(step, mph): + v = max(mph * MPH, 2.5) + base, _ = _la(0, v) + trim, c = _la(step, v) + assert trim - base == pytest.approx(-step * 0.030, abs=1e-9) + # time shift -> distance shift: this is what the menu description quotes + assert (base - trim) * v == pytest.approx(step * 0.030 * v, abs=1e-9) + assert c.trim_s == pytest.approx(step * 0.030) + + +def test_turn_in_band_fades_out_by_10mph_and_in_between_1p5_and_2p5(): + assert tg.turn_in_weight(2.5) == pytest.approx(1.0) + assert tg.turn_in_weight(8.0 * MPH) == pytest.approx(1.0) + assert tg.turn_in_weight(9.0 * MPH) == pytest.approx(0.5) + assert tg.turn_in_weight(10.0 * MPH) == 0.0 + assert tg.turn_in_weight(1.5) == 0.0 + assert tg.turn_in_weight(2.0) == pytest.approx(0.5) + vs = np.linspace(0.0, 15.0, 301) + w = [tg.turn_in_weight(float(x)) for x in vs] + assert max(abs(a - b) for a, b in zip(w, w[1:], strict=False)) < 0.06 # continuous + assert tg.turn_in_shift_s(3, 9.0 * MPH) == pytest.approx(0.5 * 3 * 0.030) + assert tg.turn_in_shift_s(-2, 9.0 * MPH) == pytest.approx(-0.5 * 2 * 0.030) + assert tg.turn_in_shift_s(99, 6.0 * MPH) == pytest.approx(3 * 0.030) # clamped + + +def test_turn_in_lookahead_is_bounded(): + # positive: never below 0.10 s (or below the untrimmed value if that is lower) + for stock in (0.12, 0.2, 0.3, 0.475): + base, _ = _la(0, 6.0 * MPH, stock=stock) + trim, _ = _la(3, 6.0 * MPH, stock=stock) + assert trim >= min(base, tg.TURN_IN_MIN_LOOKAHEAD_S) - 1e-12 + assert trim <= base + 1e-12 + assert tg.apply_turn_in_trim(0.11, 0.4, 0.09) == pytest.approx(tg.TURN_IN_MIN_LOOKAHEAD_S) + assert tg.apply_turn_in_trim(0.11, 0.4, 0.09) == pytest.approx(0.10) + assert tg.apply_turn_in_trim(0.05, 0.05, 0.09) == pytest.approx(0.05) + # negative: never above stock + for stock in (0.25, 0.3, 0.475): + base, _ = _la(0, 6.0 * MPH, stock=stock) + trim, _ = _la(-2, 6.0 * MPH, stock=stock) + assert base <= trim <= stock + 1e-12 + assert tg.apply_turn_in_trim(0.30, 0.31, -0.06) == pytest.approx(0.31) + assert tg.apply_turn_in_trim(0.2, 0.475, 0.0) == 0.2 + + +def test_turn_in_moves_the_sample_floor_with_the_lookahead(): + v = 6.0 * MPH + base, cb = _la(0, v) + later, cl = _la(3, v) + earlier, ce = _la(-2, v) + assert cb.sample_floor_s == pytest.approx(0.20) + assert cl.sample_floor_s == pytest.approx(0.20 - 0.09) + assert ce.sample_floor_s == pytest.approx(0.20 + 0.06) + assert later < base < earlier + # the plan really is sampled at the trimmed time (below the old 0.2 s floor) + t_idx = np.linspace(0.0, 10.0, 2001) + yr = t_idx.copy() + yaw = 0.5 * t_idx ** 2 # curvature now depends on the sample time + k_base = tg.plan_curvature(yaw, yr, t_idx, v, base, cb.sample_floor_s) + k_later = tg.plan_curvature(yaw, yr, t_idx, v, later, cl.sample_floor_s) + assert k_base == pytest.approx(curv_from_psis(np.interp(base, t_idx, yaw), 0.0, v, base)) + assert k_later == pytest.approx(curv_from_psis(np.interp(later, t_idx, yaw), 0.0, v, later)) + assert k_later != pytest.approx(curv_from_psis(np.interp(0.2, t_idx, yaw), 0.0, v, 0.2)) + assert later < tg.LOW_SPEED_SAMPLE_FLOOR_S + + +def test_turn_in_trim_is_slewed_not_stepped(): + c = tg.TurnGeometryCorrection(DT_MDL) + for _ in range(60): + c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=6.0 * MPH, ref_offset_m=0.35) + prev = c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=6.0 * MPH, ref_offset_m=0.35) + worst = 0.0 + for _ in range(20): + cur = c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=6.0 * MPH, ref_offset_m=0.35, turn_in_step=3) + worst = max(worst, abs(cur - prev)) + prev = cur + assert worst <= tg.REDUCTION_SLEW_S_PER_S * DT_MDL + 1e-9 + assert c.trim_s == pytest.approx(0.09) + for _ in range(20): + cur = c.update(enabled=True, stock_lookahead_s=STOCK, v_ego=6.0 * MPH, ref_offset_m=0.35, turn_in_step=0) + assert c.trim_s == 0.0 + + +@pytest.mark.parametrize("step", [-2, 3]) +def test_turn_in_trim_needs_turn_geometry_on(step): + out, c = _la(step, 6.0 * MPH, enabled=False) + assert out == STOCK + assert c.trim_s == 0.0 + assert c.sample_floor_s == MIN_STABLE_DELAY + # trimmed, then turned off: the trim is dropped with the rest of the state + _, c = _la(step, 6.0 * MPH) + assert c.trim_s != 0.0 + out = c.update(enabled=False, stock_lookahead_s=STOCK, v_ego=6.0 * MPH, ref_offset_m=0.35, turn_in_step=step) + assert out == STOCK + assert c.trim_s == 0.0 + + +def test_turn_in_trim_is_wired_into_modeld_and_the_menu(): + modeld = (ROOT / "selfdrive/modeld/modeld.py").read_text() + assert "turn_in_step = clamp_turn_in_step(params.get(PARAM_TURN_IN_DELAY, return_default=True))" in modeld + assert " turn_in_step=turn_in_step)\n" in modeld + menu = (ROOT / "selfdrive/ui/layouts/settings/driving_mannerisms.py").read_text() + assert '"Turn-In Timing (low speed)"' in menu + assert "self._params.put(NAP_TURN_IN_DELAY, int(TURN_IN_DELAY_STEPS[index]))" in menu + assert " self._all_items.append(self._turn_in_buttons)\n" in menu + mici = (ROOT / "selfdrive/ui/mici/layouts/settings/driving_mannerisms.py").read_text() + assert '"turn-in timing"' in mici + from openpilot.selfdrive.ui.layouts.settings import nap_lateral as nl + assert nl.TURN_IN_DELAY_LABELS == ["-2", "-1", "0", "+1", "+2", "+3"] + assert nl.TURN_IN_DELAY_STEPS == [-2, -1, 0, 1, 2, 3] + assert "30 ms" in nl.TURN_IN_DELAY_DESCRIPTION + + class _P: + def __init__(self, v): + self.v = v + + def get(self, key, return_default=False): + assert key == "NAPTurnInDelay" + if isinstance(self.v, Exception): + raise self.v + return self.v + + assert nl.turn_in_delay_index(_P(0)) == 2 + assert nl.turn_in_delay_index(_P(-2)) == 0 + assert nl.turn_in_delay_index(_P(3)) == 5 + assert nl.turn_in_delay_index(_P(9)) == 5 + assert nl.turn_in_delay_index(_P(KeyError("old params build"))) == 2 diff --git a/selfdrive/controls/lib/tests/test_lat_yield_inference_guard.py b/selfdrive/controls/lib/tests/test_lat_yield_inference_guard.py new file mode 100644 index 00000000000000..43327da5eed387 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_lat_yield_inference_guard.py @@ -0,0 +1,233 @@ +"""Guard: lateral handoff behavior and the lateral-yield inference must agree. + +Neither panda nor the card is ever told "lateral is yielded". Both infer it +from the 0x488 DAS_steeringControlType=1 send history (opendbc +car/tesla/preap/lat_yield.py, safety/modes/tesla_preap_latyield.h) and assume +how openpilot hands lateral back and forth: type 1 flows only while OP +steers, a yield lasts at least HANDS_OFF_CONFIRM_S, and the take-back blend +lasts BLEND_TIME_S. + +ANY change to lateral transition / handoff behavior (driver_lateral_handoff, +controlsd latActive, blinker / lane-change / roundabout lateral pause, a new +release or re-arm path, authority shaping) MUST update the inference. This +file fails when they diverge: + + 1. constants - handoff timing vs the inference's ASSUMED_* and windows + 2. pins - handoff constants frozen; a failing pin tells the editor + to update the inference first, then re-pin + 3. markers - INFERENCE CONTRACT comment present at every touch point + 4. behavior - the real DriverLateralHandoff + lat_active_after_handoff + + 50 Hz stamp drives a LatYieldTracker; partial authority + must never read as full control, a settled yield and a + settled return must + 5. self-check - the behavioral check does fail for a divergent handoff +""" +import re +from pathlib import Path + +import pytest + +from opendbc.car.tesla.preap import lat_yield as ly +from opendbc.car.tesla.preap.lat_yield import LatYieldTracker +from openpilot.selfdrive.controls.lib import driver_lateral_handoff as dlh +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import ( + DriverLateralHandoff, + lat_active_after_handoff, +) + +REPO = Path(__file__).resolve().parents[4] +HEADER = REPO / "opendbc_repo/opendbc/safety/modes/tesla_preap_latyield.h" +CARCONTROLLER = REPO / "opendbc_repo/opendbc/car/tesla/carcontroller.py" +LAT_YIELD_PY = REPO / "opendbc_repo/opendbc/car/tesla/preap/lat_yield.py" +HANDOFF_PY = REPO / "selfdrive/controls/lib/driver_lateral_handoff.py" + +UPDATE_FIRST = " ".join(( + "The lateral handoff changed. Panda and the card infer 'lateral yielded' from the", + "0x488 type-1 history (opendbc preap/lat_yield.py + safety/modes/tesla_preap_latyield.h).", + "Update that inference (windows, ASSUMED_*, panda header, their tests) FIRST, then", + "update this pin. Do not just edit the pin.", +)) + + +def _header_us(name: str) -> int: + m = re.search(rf"#define\s+{name}\s+(\d+)U?\b", HEADER.read_text()) + assert m, f"{name} missing from {HEADER}" + return int(m.group(1)) + + +# -- 1. constants ---------------------------------------------------------- + +def test_handoff_timing_matches_what_the_inference_assumes(): + assert dlh.BLEND_TIME_S == ly.ASSUMED_BLEND_TIME_S, UPDATE_FIRST + assert dlh.HANDS_OFF_CONFIRM_S == ly.ASSUMED_HANDS_OFF_CONFIRM_S, UPDATE_FIRST + # 0x488 goes out every second 100 Hz control frame + assert 2 * dlh.DT_CTRL == pytest.approx(ly.ASSUMED_FRAME_PERIOD_S), UPDATE_FIRST + assert dlh.YIELD_AUTHORITY_TIME_S == 0.0, UPDATE_FIRST + assert dlh.QUIET_WAIT_S == 0.0, UPDATE_FIRST + + +def test_grace_covers_the_blend_and_gap_sits_below_the_shortest_yield(): + # A hand-grab anywhere in the take-back blend must still read as yielded. + assert ly.GRACE_S >= dlh.BLEND_TIME_S - 1e-9, UPDATE_FIRST + assert ly.PANDA_GRACE_S >= ly.GRACE_S + 0.1, UPDATE_FIRST + assert ly.PANDA_ASSUMED_BLEND_S == dlh.BLEND_TIME_S, UPDATE_FIRST + # The shortest yield is the hands-off confirm (+ one frame); the lapse + # detector must be shorter, or the grace never starts after a short yield. + assert ly.GAP_S < dlh.HANDS_OFF_CONFIRM_S + 2 * dlh.DT_CTRL - 0.02, UPDATE_FIRST + assert ly.PANDA_GAP_S <= ly.GAP_S + # Automatic give-back is RELEASE_HOLD_S, longer than the inference floor. + assert dlh.RELEASE_HOLD_S + 1e-12 >= 0.30 + assert dlh.RELEASE_HOLD_S + 1e-12 >= dlh.HANDS_OFF_CONFIRM_S + assert ly.GAP_S < dlh.RELEASE_HOLD_S + + +def test_panda_header_matches_python_windows(): + assert _header_us("PREAP_LAT_RECENT_US") / 1e6 == pytest.approx(ly.PANDA_RECENT_S) + assert _header_us("PREAP_LAT_GAP_US") / 1e6 == pytest.approx(ly.PANDA_GAP_S) + assert _header_us("PREAP_LAT_GRACE_US") / 1e6 == pytest.approx(ly.PANDA_GRACE_S) + assert _header_us("PREAP_LAT_BLOCK_CLEAR_US") / 1e6 == pytest.approx(ly.PANDA_BLOCK_CLEAR_S) + assert _header_us("PREAP_LAT_ASSUMED_BLEND_US") / 1e6 == pytest.approx(dlh.BLEND_TIME_S), UPDATE_FIRST + + +# -- 2. pins --------------------------------------------------------------- + +def test_handoff_constants_are_pinned(): + pins = { + "BLEND_TIME_S": 1.0, + "HANDS_OFF_CONFIRM_S": 0.15, + "QUIET_WAIT_S": 0.0, + "YIELD_AUTHORITY_TIME_S": 0.0, + "UI_LATERAL_RETURN_AUTHORITY": 0.70, + "HANDS_ON_HOLD_LEVEL": 1, + "SOFT_YIELD_DEBOUNCE_FRAMES": 9, + "SOFT_YIELD_FAST_DEBOUNCE_FRAMES": 6, + "SOFT_YIELD_RELEASE_FRAMES": 8, + "EARLY_YIELD_NM": 2.0, + "EARLY_YIELD_FRAMES": 8, + "LAT_REENABLE_MIN_V_EGO_MPH": 10.0, + } + for name, want in pins.items(): + assert getattr(dlh, name) == want, f"dlh.{name} changed ({getattr(dlh, name)} != {want}). {UPDATE_FIRST}" + + +def test_inference_windows_are_pinned(): + pins = {"RECENT_S": 0.15, "GAP_S": 0.14, "GRACE_S": 1.0, "GRACE_DELAY_S": 0.05, + "BLOCK_CLEAR_S": 0.20, "PANDA_RECENT_S": 0.1, "PANDA_GAP_S": 0.1, + "PANDA_GRACE_S": 1.2, "PANDA_BLOCK_CLEAR_S": 0.15} + for name, want in pins.items(): + assert getattr(ly, name) == want, " ".join(( + f"lat_yield.{name} changed ({getattr(ly, name)} != {want}). Re-check it against the", + "handoff timing, tesla_preap_latyield.h and the panda/card ordering contract, then re-pin.", + )) + + +# -- 3. markers ------------------------------------------------------------ + +@pytest.mark.parametrize("path", [HEADER, CARCONTROLLER, LAT_YIELD_PY, HANDOFF_PY]) +def test_inference_contract_comment_present(path): + text = path.read_text() + if path == HANDOFF_PY: + text = dlh.__doc__ or "" # the module docstring, not just any comment + assert "INFERENCE CONTRACT" in text, f"{path.name}: restore the INFERENCE CONTRACT note" + assert "test_lat_yield_inference_guard" in path.read_text() or path == CARCONTROLLER, path.name + + +def test_lat_active_after_handoff_documents_the_contract(): + assert "INFERENCE CONTRACT" in (dlh.lat_active_after_handoff.__doc__ or "") + + +# -- 4. behavior ----------------------------------------------------------- + +DT = dlh.DT_CTRL # 100 Hz control loop, 0x488 stamped on every other tick + + +class _Clock: + t = 1000.0 + + def __call__(self): + return self.t + + +def simulate(script, handoff=None): + """Drive handoff -> latActive -> 0x488 stamps -> LatYieldTracker. + + script: list of (seconds, torque_nm, hands_level, steering_pressed). + Returns a list of per-tick records. + """ + clk = _Clock() + tracker = LatYieldTracker(clock=clk) + h = handoff or DriverLateralHandoff(enabled=True) + rec = [] + tick = 0 + for seconds, torque, hands, pressed in script: + for _ in range(int(round(seconds / DT))): + clk.t += DT + out = h.update(engaged=True, lat_would_be_active=True, steering_torque=torque, + steering_rate_deg=0.0, hands_on_level=hands, v_ego=20.0, + steering_pressed=pressed) + lat_active = lat_active_after_handoff(True, out.yielded) + if tick % 2 == 0: # 50 Hz DAS_steeringControl + tracker.note_steer_tx(lat_active, engaged=True) + tick += 1 + rec.append((clk.t, out.authority, out.yielded, out.blending, lat_active, tracker.full_control())) + return rec + + +def violations(rec): + bad = [] + last_lat_change = rec[0][0] + prev_lat = rec[0][4] + for t, authority, _yielded, _blending, lat_active, full in rec: + if lat_active != prev_lat: + last_lat_change = t + prev_lat = lat_active + # Partial authority (the take-back blend) must never read as full control. + if 0.02 < authority < 0.995 and lat_active and full: + bad.append((round(t, 3), "blend reads as full control", round(authority, 3))) + # Once the type-1 stream has been quiet for RECENT_S the yield must read as yielded. + if not lat_active and (t - last_lat_change) > ly.RECENT_S + 2 * DT and full: + bad.append((round(t, 3), "settled yield reads as full control")) + # A settled return (past the blend) is full control again. + if lat_active and authority >= 1.0 and (t - last_lat_change) > dlh.BLEND_TIME_S + ly.GRACE_S and not full: + bad.append((round(t, 3), "settled return does not read as full control")) + return bad + + +STEADY = (0.5, 0.0, 0, False) +SCRIPTS = { + "hands-gated push then release": [STEADY, (0.30, 3.0, 1, True), (2.5, 0.0, 0, False)], + "early push, hands never seen": [STEADY, (0.30, 3.0, 0, True), (2.5, 0.0, 0, False)], + "shortest yield": [STEADY, (0.10, 3.0, 1, True), (2.5, 0.0, 0, False)], + "long dodge": [STEADY, (1.50, 2.0, 1, True), (2.5, 0.0, 0, False)], + "regrab mid-blend then release": [STEADY, (0.30, 3.0, 1, True), (0.45, 0.0, 0, False), + (0.30, 1.2, 1, True), (2.5, 0.0, 0, False)], + "two quick yields": [STEADY, (0.20, 3.0, 1, True), (0.30, 0.0, 0, False), + (0.20, 3.0, 1, True), (2.5, 0.0, 0, False)], +} + + +@pytest.mark.parametrize("name", sorted(SCRIPTS)) +def test_blend_and_yield_read_correctly_through_the_real_handoff(name): + rec = simulate(SCRIPTS[name]) + assert any(r[2] for r in rec), "script never yielded: scenario is not testing anything" + assert not violations(rec), (name, violations(rec)[:5], UPDATE_FIRST) + + +def test_a_steady_session_with_no_yield_is_full_control(): + rec = simulate([(2.0, 0.0, 0, False)]) + assert rec[-1][5] and not any(r[2] or r[3] for r in rec) + + +# -- 5. self-check: the behavioral guard fails for a divergent handoff ----- + +def test_guard_catches_a_longer_blend(monkeypatch): + monkeypatch.setattr(dlh, "BLEND_TIME_S", 1.6) + rec = simulate(SCRIPTS["hands-gated push then release"], DriverLateralHandoff(enabled=True)) + assert violations(rec), "a 1.6 s blend outlasts the 1.0 s grace and must be flagged" + + +def test_guard_catches_a_shorter_hands_off_confirm(monkeypatch): + # Release shorter than GAP_S: the lapse is not seen as a yield, so no grace. + monkeypatch.setattr(dlh, "RELEASE_HOLD_S", 0.05) + rec = simulate(SCRIPTS["shortest yield"], DriverLateralHandoff(enabled=True)) + assert violations(rec), "a 0.05 s release hides the yield from the inference and must be flagged" diff --git a/selfdrive/controls/lib/tests/test_latcontrol.py b/selfdrive/controls/lib/tests/test_latcontrol.py deleted file mode 100644 index c8c8d027515bb1..00000000000000 --- a/selfdrive/controls/lib/tests/test_latcontrol.py +++ /dev/null @@ -1,41 +0,0 @@ -from parameterized import parameterized - -from cereal import car, log -from opendbc.car.car_helpers import interfaces -from opendbc.car.honda.values import CAR as HONDA -from opendbc.car.toyota.values import CAR as TOYOTA -from opendbc.car.nissan.values import CAR as NISSAN -from openpilot.selfdrive.car.card import convert_to_capnp -from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID -from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque -from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle -from openpilot.selfdrive.controls.lib.vehicle_model import VehicleModel -from openpilot.selfdrive.locationd.helpers import Pose -from openpilot.common.mock.generators import generate_livePose - - -class TestLatControl: - - @parameterized.expand([(HONDA.HONDA_CIVIC, LatControlPID), (TOYOTA.TOYOTA_RAV4, LatControlTorque), (NISSAN.NISSAN_LEAF, LatControlAngle)]) - def test_saturation(self, car_name, controller): - CarInterface, CarController, CarState, RadarInterface = interfaces[car_name] - CP = CarInterface.get_non_essential_params(car_name) - CI = CarInterface(CP, CarController, CarState) - CP = convert_to_capnp(CP) - VM = VehicleModel(CP) - - controller = controller(CP.as_reader(), CI) - - CS = car.CarState.new_message() - CS.vEgo = 30 - CS.steeringPressed = False - - params = log.LiveParametersData.new_message() - - lp = generate_livePose() - pose = Pose.from_live_pose(lp.livePose) - - for _ in range(1000): - _, _, lac_log = controller.update(True, CS, VM, params, False, 1, pose) - - assert lac_log.saturated diff --git a/selfdrive/controls/lib/tests/test_path_obstacle.py b/selfdrive/controls/lib/tests/test_path_obstacle.py new file mode 100644 index 00000000000000..30c589eb735297 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_path_obstacle.py @@ -0,0 +1,989 @@ +"""Radar obstacle trigger, projection, fusion, and the animal/person chime.""" +from __future__ import annotations + +import math +import time +import wave +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +from openpilot.selfdrive.controls.lib.path_obstacle import ( + _Hit, + chime_policy_block, + LIVING_CLASSES, + PARAM_OBSTACLE_CHIME, + PARAM_OBSTACLE_LOG, + SPEED_DISABLE_MPS, + SPEED_ENABLE_MPS, + BrakeIntent, + ChimeGate, + ConeHint, + ObstacleSample, + ObstacleStage, + PathObstacleDetector, + VisionScore, + chime_banner, + crop_light_stats, + fuse_scores, + fusion_weights, + future_brake_intent, + is_night_lighting, + light_dominated, + _fuse_class, + lively_from_history, + patch_change_score, + project_road_point, + scale_living_vision, + score_row_patches, + prune_thumbs, + save_ppm, + should_raise_chime, + vehicle_exclusion_points, +) +from openpilot.selfdrive.ui.obstacle_chime import ( + OBSTACLE_CHIME_ID, + OBSTACLE_CHIME_MIN_VOLUME, + alert_sound_id, + floor_volume, +) + +ROOT = Path(__file__).resolve().parents[4] +V_EGO = 12.0 +PATH_X = [0.0, 100.0] +PATH_Y = [0.0, 0.0] +ANIMAL = VisionScore(conf=0.70, human=0.10, animal=0.82, obstacle=0.18) +HUMAN = VisionScore(conf=0.72, human=0.64, animal=0.10, obstacle=0.14) +DEBRIS = VisionScore(conf=0.80, human=0.08, animal=0.10, obstacle=0.70) +WEAK = VisionScore(conf=0.20, human=0.90, animal=0.05, obstacle=0.05) + + +def _pt(x, y_rel, v_rel, tid, yv_rel=0.0, rcs=5.0): + return SimpleNamespace( + dRel=x - 1.52, yRel=y_rel, vRel=v_rel, measured=True, + trackId=tid, yvRel=yv_rel, rcs=rcs, + ) + + +def _run(det, points, n=5, dt=0.1, vision=None, chime_enabled=True, now0=100.0, **kw): + sample = None + for i in range(n): + sample = det.update( + points, V_EGO, PATH_X, PATH_Y, dt, + vision=vision, chime_enabled=chime_enabled, now=now0 + i * dt, **kw, + ) + return sample + + +def _agreed(cls, zone, tid): + return ObstacleSample( + active=True, track_id=tid, object_class=cls, zone=zone, agree=True, + member_ids=(tid,), reject_reason="none", + ) + + +def test_projection_matches_identity_and_camera(): + ground = project_road_point(20, 0, 0) + assert ground is not None + assert abs(ground[0] - 672.0) < 1e-6 + assert abs(ground[1] - (380.0 + 1141.5 * 1.22 / 20.0)) < 1e-4 + top = project_road_point(20, 0, 1.0) + assert top is not None + assert abs(top[1] - (380.0 + 1141.5 * 0.22 / 20.0)) < 1e-4 + left = project_road_point(20, 2.0, 0) + assert left is not None + assert abs(left[0] - (672.0 - 1141.5 * 2.0 / 20.0)) < 1e-4 + + from openpilot.common.transformations.camera import get_view_frame_from_road_frame + view = get_view_frame_from_road_frame(0.0, 0.0, 0.0, 1.22).dot(np.array([20.0, 0.0, 0.0, 1.0])) + u = 672.0 + 1141.5 * (view[0] / view[2]) + v = 380.0 + 1141.5 * (view[1] / view[2]) + assert abs(u - ground[0]) < 1e-4 + assert abs(v - ground[1]) < 1e-4 + + +def test_fusion_weights_are_smooth_and_nan_vision_does_not_agree(): + good = fusion_weights(1.0) + mid = fusion_weights(0.5) + poor = fusion_weights(0.0) + assert abs(good[0] - 0.50) < 1e-9 and abs(good[1] - 0.50) < 1e-9 + assert abs(mid[0] - 0.64) < 1e-9 and abs(mid[1] - 0.36) < 1e-9 + assert abs(poor[0] - 0.78) < 1e-9 and abs(poor[1] - 0.22) < 1e-9 + assert poor[0] > mid[0] > good[0] + fused, _wr, _wv, agree = fuse_scores(0.80, None, 1.0) + assert agree is False and abs(fused - 0.80) < 1e-9 + _f, _wr, _wv, agree = fuse_scores(0.80, float("nan"), 0.0) + assert agree is False + _f, _wr, _wv, agree = fuse_scores(0.60, 0.50, 1.0) + assert agree is True + assert fuse_scores(0.50, 0.50, 1.0)[3] is False + assert fuse_scores(0.60, 0.40, 1.0)[3] is False + + +def test_stationary_in_path_deer_chimes_only_when_vision_says_animal(): + deer = [_pt(30.0, 0.0, -V_EGO, 3)] + bare = _run(PathObstacleDetector(), deer, vision=None) + assert bare.vision_evaluated is False + assert bare.chimed is False + assert bare.object_class == "unknown" + + seen = _run(PathObstacleDetector(), deer, vision=ANIMAL) + assert seen.active and seen.zone == "inPath" + assert seen.object_class == "animal" + assert seen.lively_score < 0.2 + assert 0.25 < seen.vision_conf_animal < 0.55 + assert seen.agree and seen.vision_evaluated + assert seen.chimed and seen.chime_reason == "chimed" + assert seen.brake_gate is True + assert future_brake_intent(seen) is not None + + debris = _run(PathObstacleDetector(), deer, vision=DEBRIS) + assert debris.object_class == "obstacle" + assert not debris.chimed and debris.chime_reason == "log_only_class" + assert debris.brake_gate is True + + +def test_human_entering_chimes_and_can_brake_later(): + walker = [_pt(25.0, -2.3, -V_EGO, 8, yv_rel=1.0)] + person = _run(PathObstacleDetector(), walker, vision=HUMAN) + assert person.object_class == "human" + assert person.zone == "entering" + assert person.agree and person.chimed + assert person.brake_gate is True + intent = future_brake_intent(person) + assert isinstance(intent, BrakeIntent) and intent.allowed and intent.decel == 0.0 + assert chime_banner(person.object_class, person.zone) == "Object ahead" + + weak = _run(PathObstacleDetector(), walker, vision=WEAK) + assert weak.object_class == "human" + assert weak.chimed is False and weak.chime_reason == "no_agree" + + # Below the traffic cutoff a narrow in-path rider can still chime. + slow_bike = [_pt(22.0, 0.0, 4.0 - V_EGO, 9, yv_rel=0.1)] + rider = _run(PathObstacleDetector(), slow_bike, vision=HUMAN) + assert rider.object_class == "human" and rider.zone == "inPath" and rider.chimed + + +def test_excludes_traffic_motorcycles_and_parked_cars(): + # Motorcycle-like: one narrow return, with the flow, almost no lateral speed. + bike = [_pt(22.0, 0.15, 7.5 - V_EGO, 9, yv_rel=0.1)] + moto = _run(PathObstacleDetector(), bike, vision=HUMAN) + assert moto.reject_reason == "exclVehicle" and moto.chimed is False + + # A dart across the lane is not traffic, even above 5 m/s along the road. + dart = [_pt(22.0, 0.2, 6.5 - V_EGO, 19, yv_rel=-2.6)] + crossing = _run(PathObstacleDetector(), dart, vision=ANIMAL) + assert crossing.reject_reason != "exclVehicle" + assert crossing.zone == "inPath" and crossing.chimed + + # Adjacent-lane car: ~3.7 m to the right, ground speed ~11 m/s, small v_lat. + traffic = [_pt(35.0, 3.7, 11.0 - V_EGO, 44, yv_rel=-0.15)] + lane = _run(PathObstacleDetector(), traffic, vision=DEBRIS) + assert lane.reject_reason == "exclVehicle" and lane.chimed is False + + # coneLineNAP parked-car cluster on the shoulder. + parked = ConeHint(parked=True) + shoulder = _run(PathObstacleDetector(), [_pt(18.0, -3.2, -V_EGO, 7)], cone=parked, vision=DEBRIS) + assert shoulder.reject_reason == "exclVehicle" and shoulder.chimed is False + cluster = [ + _pt(22.0, -2.4, -V_EGO, 71), + _pt(22.0, -3.2, -V_EGO, 72), + _pt(23.0, -4.0, -V_EGO, 73), + ] + cars = _run(PathObstacleDetector(), cluster, vision=DEBRIS) + assert cars.reject_reason == "exclVehicle" and cars.chimed is False + + # Stopped in the path, and the model has not tagged it: still an object. + stopped = [_pt(30.0, 0.0, -V_EGO, 4)] + bare = _run(PathObstacleDetector(), stopped, vision=DEBRIS) + assert bare.zone == "inPath" and bare.reject_reason == "none" + assert not bare.chimed and bare.chime_reason == "log_only_class" + # lead0 is a far car. lead1 is this one. Both count, not only the current lead. + tagged = _run( + PathObstacleDetector(), stopped, vision=DEBRIS, + model_leads=[(90.0, 0.0, 0.95), (30.0, 0.0, 0.80)], + ) + assert tagged.reject_reason == "exclVehicle" and tagged.chimed is False + # The lead does not take the slot from a different return. + both = [_pt(30.0, 0.0, -V_EGO, 4), _pt(55.0, 0.2, -V_EGO, 5)] + mixed = _run(PathObstacleDetector(), both, vision=DEBRIS, model_leads=[(30.0, 0.0, 0.80)]) + assert mixed.track_id == 5 and mixed.reject_reason == "none" and mixed.chime_reason == "log_only_class" + far_only = _run( + PathObstacleDetector(), stopped, vision=DEBRIS, + model_leads=[(90.0, 0.0, 0.95)], + ) + assert far_only.reject_reason == "none" and far_only.chime_reason == "log_only_class" + # The second radard lead, not only leadOne. + other = _run(PathObstacleDetector(), stopped, vision=DEBRIS, lead_ids=(11, 4)) + assert other.reject_reason == "exclVehicle" and other.chimed is False + assert _run(PathObstacleDetector(), stopped, vision=DEBRIS, lead_ids=(11,)).chime_reason == "log_only_class" + # A weak model probability does not count as a tracked vehicle. + weak_lead = _run( + PathObstacleDetector(), stopped, vision=DEBRIS, + model_leads=[(30.0, 0.0, 0.20)], + ) + assert weak_lead.reject_reason == "none" and weak_lead.chime_reason == "log_only_class" + + +def test_vehicle_points_cover_both_model_leads_and_both_radar_leads(): + leads_v3 = [ + SimpleNamespace(x=[90.0], y=[0.0], prob=0.95), + SimpleNamespace(x=[22.0], y=[0.4], prob=0.70), + SimpleNamespace(x=[40.0], y=[1.0], prob=0.10), + ] + leads_v2 = [SimpleNamespace(prob=0.80, xyva=[50.0, -1.0, 12.0, 0.0])] + radar = [ + SimpleNamespace(status=True, dRel=22.0 - 1.52, yRel=-0.4, radarTrackId=9, modelProb=0.7), + SimpleNamespace(status=False, dRel=10.0, yRel=0.0, radarTrackId=3, modelProb=0.9), + SimpleNamespace(status=True, dRel=60.0 - 1.52, yRel=1.0, radarTrackId=-1, modelProb=0.0), + ] + ids, points = vehicle_exclusion_points(leads_v3, leads_v2, radar) + assert ids == [9] + assert (90.0, 0.0, 0.95) in points + assert (22.0, 0.4, 0.70) in points + assert (50.0, -1.0, 0.80) in points + assert (22.0, 0.4, 0.7, 9) in points + assert (60.0, -1.0, 1.0) in points + assert all(p[2] >= 0.40 for p in points) + assert not any(len(p) > 3 and p[3] == 3 for p in points) + + # Position from the helper excludes a second return on lead1, y in device frame. + _ids, pts = vehicle_exclusion_points(leads_v3, (), ()) + stopped = [_pt(22.0, -0.4, -V_EGO, 80)] + hit = _run(PathObstacleDetector(), stopped, vision=DEBRIS, model_leads=pts) + assert hit.reject_reason == "exclVehicle" + other_side = [_pt(22.0, 1.5, -V_EGO, 81)] + kept = _run(PathObstacleDetector(), other_side, vision=DEBRIS, model_leads=pts) + assert kept.reject_reason != "exclVehicle" and kept.chime_reason == "log_only_class" + + +def test_rejects_clutter_and_a_lane_spanning_tree(): + det = PathObstacleDetector() + assert _run(det, [_pt(30.0, 0.0, -V_EGO, 4)], lead_ids=(4,)).reject_reason == "exclVehicle" + # yRel is +left, PathObstacle lat is +right. yRel -2 is 2 m to the right. + cones = ConeHint(active=True, side=-1, lat_near=2.0, lat_mid=2.0, lat_far=2.0) + assert _run(PathObstacleDetector(), [_pt(20.0, -2.0, -V_EGO, 5)], cone=cones).reject_reason == "cone_line" + # Oct 7 posts: left side, side +1, lat negative. The opposite side stays. + left = ConeHint(active=True, side=1, lat_near=-2.0, lat_mid=-2.0, lat_far=-2.0) + assert _run(PathObstacleDetector(), [_pt(20.0, 2.0, -V_EGO, 15)], cone=left).reject_reason == "cone_line" + other = _run(PathObstacleDetector(), [_pt(20.0, -2.0, -V_EGO, 16)], cone=left) + assert other.reject_reason != "cone_line" + # Left rail. lat is +right, so the rail sits at negative y. Side is +1. + rail = ConeHint(barrier=True, side=1, lat_near=-3.0, lat_mid=-3.0, lat_far=-3.0) + assert _run(PathObstacleDetector(), [_pt(20.0, 3.0, -V_EGO, 6)], cone=rail).reject_reason == "barrier" + assert _run(PathObstacleDetector(), [_pt(40.0, 0.0, 18.0 - V_EGO, 11)]).reject_reason == "exclVehicle" + assert _run(PathObstacleDetector(), [_pt(10.0, 0.0, -V_EGO, 12)]).reject_reason == "road_surface" + assert _run(PathObstacleDetector(), [_pt(40.0, -15.0, -V_EGO, 13)]).reject_reason == "off_path" + assert _run(PathObstacleDetector(), [_pt(8.0, -12.0, -V_EGO, 14)]).reject_reason == "fov" + + tree = [ + _pt(28.0, 1.2, -V_EGO, 21), + _pt(28.0, 0.0, -V_EGO, 22), + _pt(28.0, -1.2, -V_EGO, 23), + ] + # Span forces obstacle even when the camera's animal score is higher. + # The obstacle score still has to clear the class bar or the chime waits. + span_view = VisionScore(conf=0.80, human=0.08, animal=0.82, obstacle=0.55) + fallen = _run(PathObstacleDetector(), tree, vision=span_view) + assert fallen.object_class == "obstacle" + assert fallen.cluster_count == 3 and fallen.span_m >= 1.8 + assert fallen.agree and not fallen.chimed and fallen.chime_reason == "log_only_class" + assert fallen.brake_gate is True + assert future_brake_intent(fallen) is not None + + curtain = [ + _pt(40.0, 5.0, -V_EGO, 31), + _pt(40.0, 2.0, -V_EGO, 32), + _pt(40.0, -1.0, -V_EGO, 33), + _pt(40.0, -4.0, -V_EGO, 34), + ] + assert _run(PathObstacleDetector(), curtain).reject_reason == "overhead" + + +def test_still_mailbox_stays_quiet_and_a_moving_person_chimes(): + mailbox = VisionScore(conf=0.70, human=0.64, animal=0.10, obstacle=0.16) + shoulder = [_pt(24.0, -4.5, -V_EGO, 41)] + still = _run(PathObstacleDetector(), shoulder, n=16, vision=mailbox) + assert still.zone == "roadside" + assert still.lively_score < 0.15 + assert still.object_class != "human" + assert still.chimed is False + assert still.vision_conf_human > 0.15 + + # 4.5 m is about 2.8 m outside the corridor, past the 0.9 m human band. + walking = [_pt(24.0, -4.5, 1.6 - V_EGO, 42)] + person = _run(PathObstacleDetector(), walking, n=8, vision=mailbox) + assert person.chimed is False and person.chime_reason == "off_zone" + + near = [_pt(24.0, -2.2, 1.6 - V_EGO, 45)] + close = _run(PathObstacleDetector(), near, n=8, vision=mailbox) + assert close.zone == "roadside" and close.object_class == "human" + assert close.lively_score > 0.8 + assert close.agree and close.chimed and close.chime_reason == "chimed" + assert close.brake_gate is False + assert future_brake_intent(close) is None + + deer_side = [_pt(24.0, -4.5, -V_EGO, 46)] + animal = _run(PathObstacleDetector(), deer_side, n=8, vision=ANIMAL) + assert animal.zone == "roadside" and animal.object_class == "animal" + assert animal.agree and animal.chimed and animal.brake_gate is False + assert chime_banner("human", "roadside") == "Object near road" + assert chime_banner(1, 3) == "Object near road" + assert chime_banner("obstacle", "inPath") == "Object ahead" + assert chime_banner("unknown", "entering") == "Object ahead" + + quiet = _run(PathObstacleDetector(), shoulder, n=8, vision=WEAK) + assert quiet.chimed is False + assert quiet.chime_reason == "inanimate" + + +def test_wander_and_patch_change_raise_lively_without_zeroing_a_freeze(): + frozen = scale_living_vision(ANIMAL, 0.0) + assert frozen.animal > 0.30 + assert frozen.animal < ANIMAL.animal + moving = scale_living_vision(ANIMAL, 1.0) + assert abs(moving.animal - ANIMAL.animal) < 1e-9 + + assert lively_from_history([(0.0, 20.0, 0.0, 0.0, 0.0), (1.5, 20.1, 0.05, 0.0, 0.0)]) < 0.05 + # One fast frame is not sustained motion. 0.5 s of it is. + assert lively_from_history([(0.0, 20.0, 0.0, 1.6, 0.0)]) == 0.0 + assert lively_from_history([(i * 0.1, 20.0, 0.0, 1.6, 0.0) for i in range(6)]) > 0.8 + assert lively_from_history([(i * 0.1, 20.0, 0.0, 0.0, 1.2) for i in range(6)]) >= 0.75 + # Position wander alone (ego approach, radar jitter) no longer counts. + wandered = [(i * 0.1, 24.0, 4.0 + 0.12 * i, 0.0, 0.0) for i in range(16)] + assert lively_from_history(wandered) == 0.0 + approach = [(i * 0.1, 47.0 - 2.7 * i, 4.3, 0.1, 0.05) for i in range(20)] + assert lively_from_history(approach) == 0.0 + + det = PathObstacleDetector() + sample = None + chimed = False + for i in range(16): + # Stay inside the 0.9 m human band while the return is clearly moving. + y_rel = -2.05 - 0.02 * i + sample = det.update( + [_pt(24.0, y_rel, 1.6 - V_EGO, 43)], V_EGO, PATH_X, PATH_Y, 0.1, + vision=HUMAN, now=200.0 + i * 0.1, + ) + chimed = chimed or bool(sample.chimed) + assert sample is not None and chimed + assert sample.lively_score > 0.4 and sample.object_class == "human" + + still_patch = [[40, 40, 40], [40, 42, 40], [40, 40, 40]] + moved_patch = [[40, 180, 40], [180, 40, 180], [40, 180, 40]] + assert patch_change_score(still_patch, still_patch) == 0.0 + assert patch_change_score(still_patch, moved_patch) > 0.5 + boosted = _run(PathObstacleDetector(), [_pt(24.0, -2.2, -V_EGO, 44)], n=8, vision=HUMAN, vision_motion=1.0) + assert boosted.lively_score > 0.8 and boosted.object_class == "human" and boosted.chimed + + +def test_chime_hold_cooldown_and_shared_classes(): + det = PathObstacleDetector() + deer = [_pt(30.0, 0.0, -V_EGO, 3)] + first = _run(det, deer, n=5, vision=ANIMAL, now0=100.0) + assert first.chimed + held = _run(det, deer, n=1, vision=ANIMAL, now0=100.4) + assert held.chimed and held.chime_reason == "chimed" + later = _run(det, deer, n=1, vision=ANIMAL, now0=100.8) + assert later.chimed is False and later.chime_reason == "already_tracked" + + gate = ChimeGate() + assert gate.consider(_agreed("animal", "inPath", 1), True, 10.0) == (True, "chimed") + assert gate.consider(_agreed("animal", "inPath", 1), True, 10.2) == (True, "chimed") + assert gate.consider(_agreed("animal", "inPath", 1), True, 10.5) == (False, "already_tracked") + assert gate.consider(_agreed("human", "entering", 2), True, 12.0) == (False, "cooldown") + assert gate.consider(_agreed("human", "roadside", 2), True, 19.0) == (True, "chimed") + assert gate.consider(_agreed("animal", "inPath", 1), True, 40.0) == (False, "already_tracked") + + shared = ChimeGate() + assert shared.consider(_agreed("human", "inPath", 5), True, 0.0)[0] is True + assert shared.consider(_agreed("animal", "roadside", 6), True, 1.0) == (False, "cooldown") + + muted = ChimeGate() + assert muted.consider(_agreed("human", "inPath", 7), False, 0.0) == (False, "disabled") + assert muted.consider(_agreed("human", "inPath", 7), True, 0.0) == (True, "chimed") + + off = _run(PathObstacleDetector(), deer, vision=ANIMAL, chime_enabled=False) + assert off.chime_reason == "disabled" and off.chimed is False + assert should_raise_chime(True, "human") and should_raise_chime(True, "obstacle") + assert should_raise_chime(True, "unknown") + assert not should_raise_chime(False, "human") + assert LIVING_CLASSES == frozenset({"animal", "human"}) + gate_still = ChimeGate() + assert gate_still.consider(_agreed("obstacle", "roadside", 8), True, 0.0) == (False, "inanimate") + assert gate_still.consider(_agreed("unknown", "inPath", 8), True, 0.0) == (True, "chimed") + lively_post = ObstacleSample( + active=True, track_id=9, object_class="obstacle", zone="roadside", agree=True, + member_ids=(9,), reject_reason="none", lively_score=0.8, lateral=4.5, + ) + assert ChimeGate().consider(lively_post, True, 0.0) == (False, "inanimate") + + +def test_stationary_human_guess_outside_the_band_is_dropped(): + # toward ~0.5 m/s makes the radar class "human", but the return has not moved. + post = [_pt(24.0, -4.0, -V_EGO, 51, yv_rel=0.5)] + got = _run(PathObstacleDetector(), post, n=8, vision=HUMAN) + assert got.chimed is False + assert "off_zone" in (got.reject_reason, got.chime_reason) or got.chime_reason == "human_off_3ft" + + far_animal = _run(PathObstacleDetector(), [_pt(30.0, -9.0, -V_EGO, 52)], vision=ANIMAL) + assert far_animal.reject_reason == "off_path" and far_animal.chimed is False + + +def test_highway_stationary_in_path_needs_a_real_approach_and_a_vision_class(): + stuck = [_pt(40.0, 0.0, -25.0, 61)] + det = PathObstacleDetector() + chimed = False + sample = None + for i in range(25): + sample = det.update(stuck, 25.0, PATH_X, PATH_Y, 0.1, vision=DEBRIS, now=10.0 + i * 0.1) + chimed = chimed or bool(sample.chimed) + assert sample is not None + assert chimed is False + assert sample.reject_reason == "not_closing" + assert sample.active is False + + weak = VisionScore(conf=0.55, human=0.10, animal=0.10, obstacle=0.10) + det = PathObstacleDetector() + sample = None + for i in range(10): + x = 50.0 - i * 2.5 + sample = det.update([_pt(x, 0.0, -25.0, 62)], 25.0, PATH_X, PATH_Y, 0.1, vision=weak, now=30.0 + i * 0.1) + assert sample is not None and sample.active and sample.agree + assert sample.object_class == "unknown" + assert sample.chimed is False and sample.chime_reason == "no_agree" + + det = PathObstacleDetector() + chimed = False + for i in range(10): + x = 50.0 - i * 2.5 + sample = det.update([_pt(x, 0.0, -25.0, 63)], 25.0, PATH_X, PATH_Y, 0.1, vision=None, now=40.0 + i * 0.1) + chimed = chimed or bool(sample.chimed) + assert chimed is False + + det = PathObstacleDetector() + chimed = False + for i in range(10): + x = 50.0 - i * 2.5 + sample = det.update([_pt(x, 0.0, -25.0, 64)], 25.0, PATH_X, PATH_Y, 0.1, vision=DEBRIS, now=50.0 + i * 0.1) + chimed = chimed or bool(sample.chimed) + # Oct 13: obstacle class is log only. + assert chimed is False and sample.chime_reason == "log_only_class" + + +def test_speed_gate_skips_the_scan_below_15_mph(): + stage = ObstacleStage() + stage._log_override = True + calls = {"n": 0} + real_begin = stage.det.begin + + def wrapped(*args, **kwargs): + calls["n"] += 1 + return real_begin(*args, **kwargs) + + stage.det.begin = wrapped + points = [_pt(30.0, 0.0, -20.0, 1)] + path = [0.0, 100.0] + t = 1000.0 + + def step(speed, at): + return stage.step(points, speed, path, path, 0.05, [], None, [], at) + + below = step(SPEED_ENABLE_MPS - 0.2, t) + assert below is not None and below.reject_reason == "lowSpeed" and below.active is False + assert calls["n"] == 0 + # 14 mph is under 15 and above 13, but the gate has never armed. + assert step(6.26, t + 2.0).reject_reason == "lowSpeed" + assert calls["n"] == 0 + + armed = step(SPEED_ENABLE_MPS, t + 4.0) + assert armed is None or armed.reject_reason != "lowSpeed" + assert calls["n"] == 1 + # Hysteresis holds through 14 mph. + step(SPEED_DISABLE_MPS + 0.4, t + 6.0) + assert calls["n"] == 2 + dropped = step(SPEED_DISABLE_MPS - 0.2, t + 8.0) + assert dropped is not None and dropped.reject_reason == "lowSpeed" and dropped.active is False + assert calls["n"] == 2 + + +def test_future_brake_is_any_agreed_object_in_or_entering(): + assert future_brake_intent(_agreed("animal", "inPath", 1)) is not None + assert future_brake_intent(_agreed("obstacle", "inPath", 1)) is not None + assert future_brake_intent(_agreed("unknown", "entering", 1)) is not None + assert future_brake_intent(_agreed("human", "roadside", 1)) is None + quiet = ObstacleSample(active=True, agree=False, zone="inPath", object_class="obstacle", member_ids=(1,)) + assert future_brake_intent(quiet) is None + + +def test_alert_sound_id_and_unique_wav(): + assert alert_sound_id(2, "obstacleChime/permanent") == OBSTACLE_CHIME_ID + assert alert_sound_id(2, "") == 2 + assert OBSTACLE_CHIME_ID < 0 + path = ROOT / "selfdrive/assets/sounds/animal_chime.wav" + with wave.open(str(path), "rb") as handle: + assert handle.getnchannels() == 1 + assert handle.getsampwidth() == 2 + assert handle.getframerate() == 48000 + frames = handle.getnframes() + duration = frames / 48000.0 + pcm = np.frombuffer(handle.readframes(frames), dtype=np.int16) + assert 0.90 <= duration <= 1.15 + peak_level = float(np.max(np.abs(pcm))) / 32767.0 + assert peak_level >= 0.90 + spec = np.abs(np.fft.rfft(pcm.astype(np.float64))) + freqs = np.fft.rfftfreq(len(pcm), 1.0 / 48000.0) + peak = float(freqs[int(spec.argmax())]) + # G6 then C7, twice. Not engage's falling 1661 Hz note, and not the old low boop. + assert peak > 1400.0 + assert not 1620.0 < peak < 1720.0 + g6 = spec[(freqs > 1500.0) & (freqs < 1640.0)].sum() + c7 = spec[(freqs > 2000.0) & (freqs < 2200.0)].sum() + low = spec[freqs < 800.0].sum() + assert g6 > 0.04 * spec.sum() + assert c7 > 0.02 * spec.sum() + assert low < 0.15 * spec.sum() + assert floor_volume(OBSTACLE_CHIME_ID, 0.355) == OBSTACLE_CHIME_MIN_VOLUME + assert floor_volume(OBSTACLE_CHIME_ID, 0.91) == 0.91 + assert floor_volume(2, 0.355) == 0.355 + assert OBSTACLE_CHIME_MIN_VOLUME == 0.7 + + +def test_thumbnail_prune_and_scan_cost(): + folder = ROOT / "selfdrive/controls/lib/tests/_thumb_tmp" + folder.mkdir(exist_ok=True) + try: + for i in range(30): + assert save_ppm(str(folder / f"{i:02d}.ppm"), [[i, 255 - i], [10, 20]]) + prune_thumbs(str(folder), max_files=24, max_bytes=2_000_000) + assert len(list(folder.glob("*.ppm"))) <= 24 + finally: + for path in folder.glob("*.ppm"): + path.unlink() + folder.rmdir() + + det = PathObstacleDetector() + points = [ + _pt(8.0 + (i % 20) * 4.0, ((i % 9) - 4) * 0.4, -V_EGO, i + 1, yv_rel=0.05 * ((i % 5) - 2)) + for i in range(40) + ] + n = 50 + t0 = time.perf_counter() + for i in range(n): + det.update(points, V_EGO, PATH_X, PATH_Y, 0.05, now=float(i)) + mean_ms = (time.perf_counter() - t0) / n * 1000.0 + print(f"path obstacle scan mean {mean_ms:.3f} ms over {n} frames of 40 tracks") + assert mean_ms < 5.0 + + +def test_wiring_stays_off_the_control_core_and_off_longitudinal(): + def text(rel): + return (ROOT / rel).read_text(encoding="utf-8") + + for rel in ( + "selfdrive/controls/controlsd.py", + "selfdrive/controls/lib/longcontrol.py", + "selfdrive/controls/lib/longitudinal_planner.py", + ): + src = text(rel) + assert "pathObstacle" not in src + assert "obstacleChime" not in src + assert "future_brake_intent" not in src + lib = text("selfdrive/controls/lib/path_obstacle.py") + assert "actuators" not in lib + assert PARAM_OBSTACLE_CHIME == "NAPObstacleChime" + assert PARAM_OBSTACLE_LOG == "NAPObstacleLog" + + events = text("selfdrive/selfdrived/events.py") + block = events.split("_obstacle_chime", 1)[1][:600] + assert "ET.PERMANENT" in block + assert "ET.WARNING" not in block + assert "NO_ENTRY" not in block + assert "SOFT_DISABLE" not in block + assert "IMMEDIATE_DISABLE" not in block + assert "Person ahead" not in events + assert "Object ahead" in events + assert "obstacle_chime_alert" in events + + selfd = text("selfdrive/selfdrived/selfdrived.py") + assert "'pathObstacleVisionNAP'" in selfd + assert "'pathObstacleNAP'" in selfd + assert "should_raise_chime" in selfd + assert "path_obstacle" not in selfd.split("class SelfdriveD", 1)[0] + assert "a_cmd=float(self.sm['carControl'].actuators.accel),\n" in selfd + + keys = text("common/params_keys.h") + assert '{"NAPObstacleChime", {PERSISTENT, BOOL, "1"}}' in keys + assert '{"NAPObstacleLog", {PERSISTENT, BOOL, "1"}}' in keys + services = text("cereal/services.py") + assert '"pathObstacleNAP": (True, 0., 1)' in services + assert '"pathObstacleVisionNAP": (True, 0., 1)' in services + manner = text("selfdrive/ui/layouts/settings/driving_mannerisms.py") + assert "Live object detection chime" in manner + assert "livelyScore" in text("cereal/custom.capnp") + assert "visionFailReason" in text("cereal/custom.capnp") + assert "driveOverReason" in text("cereal/custom.capnp") + assert "modelLeadAgree" in text("cereal/custom.capnp") + assert "lowSpeed" in lib + assert "self._all_items.append(self._turn_in_buttons)" in manner + + proc = text("selfdrive/pathobstacled/pathobstacled.py") + radar = text("selfdrive/controls/radard.py") + assert "vehicle_exclusion_points" in radar + assert "leadsV3" in radar and ".leads" in radar + assert "leadOne" in radar and "leadTwo" in radar + assert "run_obstacle" in radar + assert '"yaw_rate"' in radar + assert "model_yaw_rate_right(sm['modelV2'])" in radar + assert radar.count("SubMaster(") == 1 + sound = text("selfdrive/ui/soundd.py") + thread = sound.split("def soundd_thread", 1)[1] + assert thread.find("warningImmediate") < thread.find("floor_volume") + assert "carState" not in thread + assert "sub_sock('carState'" not in proc and 'sub_sock("carState"' not in proc + assert "get_gps_location_service" in proc + assert 'sub_sock("gpsLocationExternal"' not in proc and "sub_sock('gpsLocationExternal'" not in proc + assert 'sub_sock("liveCalibration"' not in proc and "sub_sock('liveCalibration'" not in proc + assert "CalibrationParams" in proc + assert "pathObstacleVisionNAP" in proc + assert ".copy()" in proc + assert "exclVehicle" in text("selfdrive/controls/lib/path_obstacle.py") + assert "CORES = [0, 1, 2, 3]" in proc + assert "set_core_affinity(CORES)" in proc + assert "os.nice(NICE)" in proc + assert "NICE = 19" in proc + assert "config_realtime_process(4" not in proc + cfg = text("system/manager/process_config.py") + assert 'PythonProcess("pathobstacled"' in cfg + assert "optional=True" in cfg.split('PythonProcess("pathobstacled"', 1)[1][:400] + optional = text("system/manager/optional_procs.py") + assert "pathobstacled" in optional + assert '"card"' not in optional or "card" not in optional.split("OPTIONAL_PROCESS_NAMES", 1)[1][:200] + onroad = text("selfdrive/test/test_onroad.py") + assert '"selfdrive.pathobstacled.pathobstacled": 1.0' in onroad + + +def test_oct7_yaw_curve_does_not_chime_and_stays_roadside(): + """20:02:12 route 174. Radar vLat was the car's own right turn at 119 m.""" + det = PathObstacleDetector() + # device y +right. yRel is +left, so a target 5.91 m right is yRel -5.91. + vision = VisionScore(conf=0.76, human=0.15, animal=0.06, obstacle=0.65) + v_ego = 26.7 + yaw = 0.0126 + sample = None + chimed = False + for i in range(8): + sample = det.update( + [_pt(118.6, -5.91, 0.05 - v_ego, 952, yv_rel=1.62)], + v_ego, PATH_X, PATH_Y, 0.1, + vision=vision, lighting=0.43, yaw_rate=yaw, now=200.0 + i * 0.1, + ) + chimed = chimed or bool(sample.chimed) + assert sample is not None + assert chimed is False + assert sample.zone == "roadside" + assert sample.object_class not in ("animal", "human") + assert -0.40 < sample.v_lat < 0.20 + assert sample.vision_evaluated and sample.vision_conf > 0.70 + assert sample.agree is False + assert sample.range_m > 85.0 + + # The same turn must not look like the target wandered into the lane. + curve = PathObstacleDetector() + x = 80.0 + y0 = 6.0 + yaw_fast = 0.02 + dt = 0.1 + lively = None + for i in range(16): + psi = yaw_fast * dt * (i + 1) + device_y = -math.sin(psi) * x + math.cos(psi) * y0 + lively = curve.update( + [_pt(x, -device_y, -20.0, 951, yv_rel=yaw_fast * x)], + 20.0, PATH_X, PATH_Y, dt, yaw_rate=yaw_fast, now=300.0 + i * dt, + ) + assert lively is not None + assert abs(lively.v_lat) < 0.35 + assert lively.lively_score < 0.2 + assert lively.chimed is False + + +def test_oct7_yaw_animal_mislabel_does_not_chime(): + """20:02:31. A left curve made a roadside return look like a 4 m/s animal.""" + low = VisionScore(conf=0.58, human=0.10, animal=0.05, obstacle=0.20) + assert _fuse_class("animal", 0.0, 1, low, raw=low) == "obstacle" + assert _fuse_class("human", 0.0, 1, VisionScore(conf=0.70, human=0.22, animal=0.10, obstacle=0.15)) == "obstacle" + kept = VisionScore(conf=0.70, human=0.10, animal=0.55, obstacle=0.10) + assert _fuse_class("animal", 0.0, 1, kept, raw=kept) == "animal" + + det = PathObstacleDetector() + v_ego = 26.0 + yaw = -0.058 + sample = None + chimed = False + for i in range(8): + sample = det.update( + [_pt(69.0, -7.7, -v_ego, 991, yv_rel=-4.4)], + v_ego, PATH_X, PATH_Y, 0.1, + vision=low, lighting=0.43, yaw_rate=yaw, now=400.0 + i * 0.1, + ) + chimed = chimed or bool(sample.chimed) + assert sample is not None + assert chimed is False + assert sample.zone == "roadside" + assert sample.object_class != "animal" + assert abs(sample.v_lat) < 1.0 + assert sample.chime_reason != "chimed" + + +def test_oct7_single_look_does_not_chime_and_a_real_obstacle_does(): + """20:09:02. One 0.70 look, then 0.44. A stopped in-path obstacle still chimes.""" + det = PathObstacleDetector() + v_ego = 18.1 + good = VisionScore(conf=0.70, human=0.10, animal=0.08, obstacle=0.59) + bad = VisionScore(conf=0.44, human=0.10, animal=0.08, obstacle=0.30) + good_frame = None + chimed = False + for i in range(8): + vision = good if i == 5 else bad if i == 6 else None + sample = det.update( + [_pt(46.4, -1.96, 0.25 - v_ego, 1520, yv_rel=0.62)], + v_ego, PATH_X, PATH_Y, 0.1, + vision=vision, lighting=0.40, yaw_rate=0.0003, now=500.0 + i * 0.1, + ) + chimed = chimed or bool(sample.chimed) + if i == 5: + good_frame = sample + assert good_frame is not None + assert good_frame.agree is True + assert good_frame.object_class == "obstacle" + assert good_frame.chimed is False + assert good_frame.chime_reason == "no_agree" + assert chimed is False + + real = PathObstacleDetector() + solid = VisionScore(conf=0.82, human=0.05, animal=0.06, obstacle=0.74) + chimed_at = None + last = None + for i in range(8): + vision = solid if i >= 4 else None + last = real.update( + [_pt(28.0, 0.0, -12.0, 77)], 12.0, PATH_X, PATH_Y, 0.1, + vision=vision, now=600.0 + i * 0.1, + ) + if last.chimed and chimed_at is None: + chimed_at = i + assert last is not None + assert last.zone == "inPath" and last.object_class == "obstacle" + # Agreed after the second look, but obstacle class is log only (Oct 13). + assert not last.chimed and last.chime_reason == "log_only_class" + assert chimed_at is None + + +def _solid_patch(lo, hi, size=28): + """Mid-gray structure. No pixel near saturation.""" + span = max(hi - lo, 1) + return [[lo + ((x * 3 + y * 5) % span) for x in range(size)] for y in range(size)] + + +def _blob_patch(background, blob, y0, y1, x0, x1, size=28): + img = [[background for _ in range(size)] for _ in range(size)] + for y in range(y0, y1): + for x in range(x0, x1): + img[y][x] = blob + return img + + +def _night_run(points, vision, *, lighting=0.42, model_leads=(), v_ego=12.0, n=8): + det = PathObstacleDetector() + last = None + chimed = False + for i in range(n): + last = det.update( + points, v_ego, PATH_X, PATH_Y, 0.1, + vision=vision, lighting=lighting, model_leads=model_leads, + now=800.0 + i * 0.1, + ) + chimed = chimed or bool(last.chimed) + return last, chimed + + +def test_night_drive_over_suppresses_lights_and_keeps_real_obstacles(): + """Stationary in-lane returns at night. The Oct 7 leftovers were rails + and road hardware whose crop was headlights or taillights. + """ + assert is_night_lighting(0.43) and is_night_lighting(0.40) + assert is_night_lighting(1.0) is False + assert is_night_lighting(float("nan")) is False + + road = [[25] * 28 for _ in range(10)] + headlights = _blob_patch(12, 252, 6, 20, 8, 22) + head_score = score_row_patches(headlights, road) + assert head_score.light_dominated + assert head_score.light_frac >= 0.12 + assert head_score.conf >= 0.60 and head_score.obstacle >= 0.40 + + tree = _solid_patch(70, 140) + tree_score = score_row_patches(tree, road) + assert tree_score.light_dominated is False + assert tree_score.conf >= 0.60 and tree_score.obstacle >= 0.40 + + rails = [[40] * 28 for _ in range(28)] + rail_score = score_row_patches(rails, [[40] * 28 for _ in range(8)]) + assert rail_score.light_dominated is False + assert rail_score.conf < 0.45 + + # Red taillight blob, and the same pattern as a bright Y plus high V. + red = [[(12, 12, 12) for _ in range(24)] for _ in range(24)] + for y in range(8, 16): + for x in range(4, 16): + red[y][x] = (255, 8, 8) + _near, _sat, red_frac, _blob = crop_light_stats(red) + assert red_frac >= 0.06 + assert light_dominated(_near, _sat, red_frac, _blob) + y_plane = _blob_patch(20, 210, 8, 16, 4, 16, size=24) + v_plane = _blob_patch(128, 200, 4, 8, 2, 8, size=12) + _near_v, _sat_v, red_v, _blob_v = crop_light_stats(y_plane, v_plane) + assert red_v >= 0.06 + + # (1) Headlight-saturated crop at night, in the lane: no chime. + night_light, light_chimed = _night_run( + [_pt(45.0, 0.0, -18.0, 1741)], head_score, v_ego=18.0, + ) + assert light_chimed is False + assert night_light.chime_reason == "drive_over" + assert night_light.drive_over_reason == "light" + assert night_light.zone == "inPath" + + # (2) Railroad crossing: no model lead, crop is not a solid object. + rails_hit, rails_chimed = _night_run( + [_pt(48.0, 0.0, -18.0, 976)], rail_score, v_ego=18.0, + ) + assert rails_chimed is False + assert rails_hit.chime_reason == "drive_over" + assert rails_hit.drive_over_reason == "no_solid" + + # (3) Stalled car at night. The model lead is at the same spot, so it + # chimes even when the crop is the car's own taillights. + stalled, stalled_chimed = _night_run( + [_pt(32.0, 0.0, -12.0, 501)], head_score, + model_leads=[(32.0, 0.0, 0.80)], + ) + assert not stalled_chimed + assert stalled.chime_reason == "log_only_class" + assert stalled.object_class == "obstacle" + assert stalled.drive_over_reason == "" + + # (4) Fallen tree: solid, not a light, inside 60 m. + fallen, fallen_chimed = _night_run([_pt(28.0, 0.0, -12.0, 880)], tree_score) + assert not fallen_chimed and fallen.chime_reason == "log_only_class" + assert fallen.drive_over_reason == "" + far_tree, far_chimed = _night_run([_pt(75.0, 0.0, -12.0, 881)], tree_score) + assert far_chimed is False + assert far_tree.drive_over_reason == "beyond_60" + + # (5) The same headlight crop in daylight still chimes. + day, day_chimed = _night_run( + [_pt(45.0, 0.0, -18.0, 1742)], head_score, lighting=1.0, v_ego=18.0, + ) + assert not day_chimed and day.chime_reason == "log_only_class" + assert day.drive_over_reason == "" + + # Living things and anything crossing the lane are outside the rule. + # Oct 13: a single radar point in the dark is never an animal chime. + deer, deer_chimed = _night_run([_pt(30.0, 0.0, -12.0, 77)], ANIMAL) + assert not deer_chimed and deer.object_class == "animal" and deer.chime_reason == "dark_single_point" + # Two members (a real body) still chimes at night. + pair = [_pt(30.0, 0.0, -12.0, 77), _pt(30.4, 0.5, -12.0, 177)] + deer2, deer2_chimed = _night_run(pair, ANIMAL) + assert deer2_chimed and deer2.object_class == "animal" and deer2.chime_reason == "chimed" + lit_deer = replace_light(ANIMAL) + still_deer, still_chimed = _night_run([_pt(30.0, 0.0, -12.0, 78)], lit_deer) + assert not still_chimed and still_deer.object_class == "animal" + walker, walker_chimed = _night_run( + [_pt(25.0, -2.3, -12.0, 79, yv_rel=1.2)], replace_light(HUMAN), + ) + assert walker_chimed and walker.zone == "entering" and walker.object_class == "human" + + +def replace_light(score: VisionScore) -> VisionScore: + return VisionScore( + conf=score.conf, human=score.human, animal=score.animal, obstacle=score.obstacle, + light_dominated=True, light_frac=0.40, red_frac=0.10, + ) + + +# ---- Oct 13 2026: the nine chime events (8 false, 1 duplicate crossing SUV) ---- + +def _oct13(cls, zone, x, lat, *, light, members=1, span=0.0, along=0.0, v_lat=0.0, + lively=0.0, vision=None, radar_class=None, model_lead=False): + hit = _Hit( + active=True, track_id=1, member_ids=tuple(range(1, members + 1)), x=x, y=lat, lateral=lat, + v_rel=-10.0, v_lat=v_lat, along=along, radar_conf=0.9, radar_class=radar_class or cls, + zone=zone, time_to_reach=3.0, time_to_enter=0.0, cluster_count=members, span_m=span, + reject_reason="none", lighting=light, lively=lively, v_ego=15.0, model_lead=model_lead, + ) + sample = ObstacleSample( + active=True, track_id=1, range_m=x, lateral=lat, v_lat=v_lat, object_class=cls, zone=zone, + agree=True, lighting_score=light, lively_score=lively, cluster_count=members, span_m=span, + member_ids=hit.member_ids, vision_evaluated=vision is not None, reject_reason="none", + ) + return chime_policy_block(sample, hit, vision) + + +def _vs(conf=0.6, human=0.0, animal=0.0, obstacle=0.0): + return VisionScore(conf=conf, human=human, animal=animal, obstacle=obstacle) + + +def test_oct13_morning_animal_chimes_are_blocked(): + # 07:01:43 60 mph, sign post +4.3 m, single still point, dark, vision animal 0.52. + assert _oct13("animal", "roadside", 47.0, 4.3, light=0.40, vision=_vs(animal=0.52)) == "still_animal" + # 07:09:22 34 mph, tree line/sign +3.8 m, dark. + assert _oct13("animal", "roadside", 30.0, 3.8, light=0.36, vision=_vs(animal=0.58)) == "still_animal" + # 07:35:49 62 mph, +6.5 m: past the 20 ft cap from path centre. + assert _oct13("animal", "roadside", 40.0, 6.5, light=0.46, vision=_vs(animal=0.80)) == "beyond_20ft" + # 08:00:09 19 mph, parked box truck +4.5 m, along -0.6 m/s jitter but not sustained (lively 0). + assert _oct13("animal", "roadside", 25.0, 4.5, light=0.44, along=-0.6, vision=_vs(animal=0.66)) == "still_animal" + # Even with the old broken lively=1.0, a dark single point never chimes as an animal. + assert _oct13("animal", "roadside", 47.0, 4.3, light=0.40, lively=1.0, vision=_vs(animal=0.52)) == "dark_single_point" + + +def test_oct13_human_and_obstacle_chimes_are_blocked(): + # 07:46:54 19 mph, pole -2.7…-3.2 m, radar class human, vision NaN. + assert _oct13("human", "inPath", 20.0, -3.19, light=0.9, members=2, span=1.5) == "human_no_camera" + # Same pole even if the camera had scored it: outside 3 ft of the path. + assert _oct13("human", "inPath", 20.0, -3.19, light=0.9, members=2, span=1.5, vision=_vs(human=0.7)) == "human_off_3ft" + # 11:12:31 29 mph, hydrant -2.7 m, "human roadside", vision never evaluated. + assert _oct13("human", "roadside", 22.0, -2.7, light=1.0) == "human_no_camera" + # 11:14:07 23 mph, crosswalk paint, in path at 42 m, radar human, no camera. + assert _oct13("human", "inPath", 42.0, 0.1, light=1.0) == "human_no_camera" + # 12:03:33 40 mph, pavement markings, obstacle 0.99: obstacle class is log only. + assert _oct13("obstacle", "inPath", 61.0, 1.6, light=1.0, vision=_vs(conf=0.99, obstacle=0.99)) == "log_only_class" + assert _oct13("unknown", "inPath", 43.0, 0.5, light=1.0) == "log_only_class" + + +def test_oct13_crossing_suv_belongs_to_crossing_vehicle_handling(): + # 11:13:08 16 mph, SUV pulling out across the lane, +0.5 m at 43 m. + assert _oct13("human", "inPath", 43.0, 0.5, light=1.0, members=2, span=1.4, v_lat=1.5, along=0.8, + vision=_vs(human=0.6)) == "crossing_vehicle" + # A walker crossing (single point) is not a crossing vehicle and still chimes. + assert _oct13("human", "inPath", 20.0, 0.5, light=1.0, v_lat=1.2, along=0.2, lively=1.0, + vision=_vs(human=0.6)) is None + + +def test_oct13_road_surface_and_real_animals(): + # Still, single in-path point at 40–60 m with only a weak camera look: road surface. + assert _oct13("animal", "inPath", 50.0, 0.2, light=1.0, vision=_vs(conf=0.3, animal=0.8)) == "road_surface_single" + # A second member, or a solid camera hit, lets it through. + assert _oct13("animal", "inPath", 50.0, 0.2, light=1.0, members=2, span=0.6, vision=_vs(conf=0.3, animal=0.8)) is None + assert _oct13("animal", "inPath", 50.0, 0.2, light=1.0, vision=_vs(conf=0.8, animal=0.8)) is None + # Real moving deer on the shoulder in daylight chimes; a strong still deer chimes. + assert _oct13("animal", "roadside", 30.0, 4.0, light=0.9, lively=1.0, vision=_vs(animal=0.5)) is None + assert _oct13("animal", "roadside", 30.0, 4.0, light=0.9, vision=_vs(animal=0.76)) is None + # Person within 3 ft of the path edge, camera scored: chimes. + assert _oct13("human", "roadside", 15.0, 2.4, light=1.0, vision=_vs(human=0.6)) is None + + +def test_oct13_speed_gate_unchanged(): + assert abs(SPEED_ENABLE_MPS - 6.7) < 1e-6 diff --git a/selfdrive/controls/lib/tests/test_roundabout_guide.py b/selfdrive/controls/lib/tests/test_roundabout_guide.py new file mode 100644 index 00000000000000..9232f81c1ea739 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_roundabout_guide.py @@ -0,0 +1,950 @@ +"""Roundabout Steering Assist (NAPRoundaboutAssist, Pre-AP, default Off). + +Sep 30: once latched the assist follows the map's lane circle (no blend), capped at 1.15x the model, 2.2 m/s², slew 0.035; released only by a +held same-side stalk / steering pull / override (no map-only exit); ALC tips are suppressed while latched. R126 / R128 (Sep 28) and +0000012f / 00000130 (Sep 29, roundabout_passes_sep29.json) replay below. + +Sep 28 PM, Soco Rd / Dellwood / Jonathan Creek ring (R ~21.6 m, CCW): +R126 16:52 CT (inner lane) and R128 17:38 CT (outer lane). The model's plan +was a wide, slow S: it swung across the band (island side on R128, outer curb +on R126) and the driver took over. The fixture carries the logged model +curvature vs distance, the wheel speed and the real 1 Hz qcom GNSS errors, so +the closed-loop sims below run the guide against the same GPS quality. + +Curvature sign: openpilot's (positive = right). US CCW circulation < 0. +""" +import json +import math +from pathlib import Path + +import pytest + +from openpilot.selfdrive.controls.lib import roundabout_guide as RG +from openpilot.selfdrive.controls.lib import roundabout_ring_hold as RH +from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature +from openpilot.selfdrive.mapd.roundabout_map import RingGeometry, latlon_from_xy + +ROOT = Path(__file__).resolve().parents[4] +FIXTURE = Path(__file__).parent / "data" / "roundabout_passes_sep28.json" +PASSES = json.loads(FIXTURE.read_text())["passes"] +PASSES29 = json.loads((Path(__file__).parent / "data" / "roundabout_passes_sep29.json").read_text())["passes"] +PASSES_ALL = {**PASSES, **PASSES29} +MPH = 0.44704 +DT = 0.01 + + +def _ring(p) -> RingGeometry: + return RingGeometry.from_json(p["ring"]) + + +def _interp(x, xs, ys): + if x <= xs[0]: + return ys[0] + if x >= xs[-1]: + return ys[-1] + lo, hi = 0, len(xs) - 1 + while hi - lo > 1: + mid = (lo + hi) // 2 + if xs[mid] <= x: + lo = mid + else: + hi = mid + f = (x - xs[lo]) / (xs[hi] - xs[lo]) + return ys[lo] + f * (ys[hi] - ys[lo]) + + +_LAST: dict = {} + + +def simulate(name: str, kind: str, *, slow: bool = True, fix_scale: float = 1.0, pool=None): + """Kinematic closed loop: model curvature by distance -> [guide] -> clip_curvature -> 0.2 s delay + 0.2 s lag. + + kind: "before" (model only) or "after" (guide On). slow: planner ring slow-down from the first hint. + Returns rows (t, x, y, psi, v, model_k, out_k, des_k). + """ + p = (pool or PASSES)[name] + ring = _ring(p) + R, hw = ring.radius_m, ring.half_width_m + guide = RG.RoundaboutGuide() + guide.set_ring(ring) + _LAST["guide"] = guide + fixes = list(p["fixes"]) + hist = p["hist"] + fi = 0 + # Warm the pose tracker on the logged approach (as on the car, GNSS is fed continuously). + track = [] + for t, x, y, psi, v, yr in hist: + guide.update(t, v, yr, 0.0, enabled=kind == "after", lat_active=True) + track.append((t, x, y, psi, v)) + while fi < len(fixes) and fixes[fi][0] <= t: + _feed(guide, ring, fixes[fi], track, fix_scale) + fi += 1 + t, x, y, psi = 0.0, hist[-1][1], hist[-1][2], hist[-1][3] + ks = [i * p["model_k_ds"] for i in range(len(p["model_k"]))] + vts = [i * p["v_dt"] for i in range(len(p["v"]))] + k_des = p["k_des0"] + k_act = p["k_act0"] + delay = [k_act] * 20 + s = 0.0 + rows = [] + v_target = guide.ring_v # the planner's ring speed (RB_RING_SPEED_MPH = 18 since Sep 30), not the logged 15.8 mph hint + while t < vts[-1]: + v = _interp(t, vts, p["v"]) + if slow: + d = max(math.hypot(x, y) - (R + hw), 0.0) + v = min(v, math.sqrt(v_target * v_target + 2.0 * 1.0 * d)) + model_k = _interp(s, ks, p["model_k"]) + track.append((t, x, y, psi, v)) + while fi < len(fixes) and fixes[fi][0] <= t: + _feed(guide, ring, fixes[fi], track, fix_scale) + fi += 1 + if kind == "after": + out_k = guide.update(t, v, k_act * v, model_k, enabled=True, lat_active=True) + else: + out_k = model_k + k_des, _ = clip_curvature(v, k_des, out_k, 0.0) + delay.append(k_des) + k_act += (delay.pop(0) - k_act) * (DT / 0.2) + rows.append((t, x, y, psi, v, model_k, out_k, k_des)) + psi += k_act * v * DT + x += v * math.sin(psi) * DT + y += v * math.cos(psi) * DT + s += v * DT + t += DT + return rows, ring + + +def _feed(guide, ring, f, track, scale): + t_fix, ex, ey, dbrg, bacc = f + te = t_fix - RG.GPS_LATENCY_S + pts = [r for r in track if r[0] <= te] + if not pts: + return + _, x, y, psi, v = pts[-1] + lat, lon = latlon_from_xy(x + scale * ex, y + scale * ey, ring.lat, ring.lon) + guide.gnss(t_fix, lat, lon, (math.degrees(psi) + scale * dbrg) % 360.0, v, bacc) + + +def band_metrics(rows, ring, deg=120.0): + """First `deg` degrees after entering the ring band: max distance beyond a curb, % inside the band.""" + R, hw = ring.radius_m, ring.half_width_m + r = [math.hypot(row[1], row[2]) for row in rows] + i0 = next(i for i, rr in enumerate(r) if rr < R + hw) + th0 = math.atan2(rows[i0][2], rows[i0][1]) + travel, prev, out = 0.0, th0, [] + for i in range(i0, len(rows)): + th = math.atan2(rows[i][2], rows[i][1]) + travel += math.degrees(RG._wrap(th - prev)) + prev = th + if travel > deg: + break + out.append(max(0.0, (R - hw) - r[i], r[i] - (R + hw))) + return max(out), 100.0 * sum(o < 0.01 for o in out) / len(out) + + +# --------------------------------------------------------------------------------------------- +# Replay: both passes, closed loop with the real GNSS error stream + +@pytest.mark.parametrize("name", ["00000126", "00000128", "00000130"]) +def test_model_only_leaves_the_ring_band(name): + rows, ring = simulate(name, "before", pool=PASSES_ALL) + beyond, inband = band_metrics(rows, ring, 90.0) + assert beyond > 0.9 and inband < 70.0 + + +@pytest.mark.parametrize("name,max_beyond,min_inband", [("00000126", 2.0, 85.0), ("00000128", 0.7, 94.0), ("00000130", 0.5, 95.0)]) +def test_ring_follow_keeps_the_passes_in_the_ring_band(name, max_beyond, min_inband): + """First 90° of circulation (the later part of the logged passes is the driver leaving the ring at the exit).""" + before = band_metrics(*simulate(name, "before", pool=PASSES_ALL), 90.0) + after = band_metrics(*simulate(name, "after", pool=PASSES_ALL), 90.0) + assert after[0] <= max_beyond + assert after[1] >= min_inband + assert after[0] < before[0] and after[1] > before[1] + + +def test_unreliable_pose_pass_is_model_only_and_unchanged(): + """0000012f (Scallywag 11:57): bearing accuracy 13-52° the whole way in, the guide never latches and never touches the pass.""" + before, ring = simulate("0000012f", "before", pool=PASSES_ALL) + after, _ = simulate("0000012f", "after", pool=PASSES_ALL) + assert not _LAST["guide"].latch_t + assert all(a[6] == b[6] for a, b in zip(after, before, strict=False)) + + +@pytest.mark.parametrize("name", sorted(PASSES_ALL)) +def test_right_entry_held_until_turn_distance(name, monkeypatch): + monkeypatch.setattr(RG, "SPEED_HOLD_MS", 1e9) # the ring-speed curl hold would also hold the left; test the distance hold alone + rows, ring = simulate(name, "after", pool=PASSES_ALL) + R, hw = ring.radius_m, ring.half_width_m + t_latch = _LAST["guide"].latch_t if _LAST["guide"].latch_t is not None else 1e9 # entry only: after the latch the car is on the ring + for _t, x, y, _psi, _v, mk, out, _ in rows: + if _t >= t_latch: + break + d_edge = math.hypot(x, y) - (R + hw) + if d_edge > RG.D_TURN_M + 3.0: # + guide pose error margin + assert out >= mk - 1e-9, f"early left at {d_edge:.1f} m" + + +@pytest.mark.parametrize("name", sorted(PASSES_ALL)) +def test_left_transition_within_jerk_limit(name): + rows, _ = simulate(name, "after", pool=PASSES_ALL) + t_latch = _LAST["guide"].latch_t or 1e9 + for a, b in zip(rows, rows[1:], strict=False): + if abs(b[0] - t_latch) < 1e-6: + continue # the one sample where an over-cap entry curl meets the 1.15x cap (clip_curvature rate-limits it downstream) + corr_rate = abs((b[6] - b[5]) - (a[6] - a[5])) / DT + out_rate = abs(b[6] - a[6]) / DT + model_rate = abs(b[5] - a[5]) / DT + assert corr_rate <= RG.OUT_SLEW_GOOD + 1e-6 + assert out_rate <= max(RG.OUT_SLEW_GOOD, RG.RING_CAP_RATIO * model_rate) + 1e-6 # the ring cap follows the model at 1.15x + + +@pytest.mark.parametrize("name", sorted(PASSES_ALL)) +def test_ring_speed_is_18_mph_and_lateral_cap(name): + """Sep 30: entry was a little slow; the ring speed constant is 18 mph (RB_RING_SPEED_MPH), up from 15.8 (2.5 m/s² comfort speed).""" + from openpilot.selfdrive.mapd.roundabout import RB_RING_SPEED_MPH + assert RB_RING_SPEED_MPH == 18.0 + rows, ring = simulate(name, "after", pool=PASSES_ALL) + assert _LAST["guide"].ring_v == pytest.approx(18.0 * MPH) + R, hw = ring.radius_m, ring.half_width_m + inside = [r for r in rows if math.hypot(r[1], r[2]) < R + hw] + assert inside and max(r[4] for r in inside) <= 18.05 * MPH + assert max(abs(r[7]) * r[4] ** 2 for r in inside) <= 3.0 + + +@pytest.mark.parametrize("name", ["00000126", "00000128", "00000130"]) +def test_hands_back_to_model_after_exit(name): + rows, _ = simulate(name, "after", pool=PASSES_ALL) + tail = rows[-100:] # the fade of a widened ring correction (0.015 at the 0.035 slew) takes ~0.45 s after the safety release + assert all(r[6] == r[5] for r in tail) + assert _LAST["guide"].phase in (RG.DONE, RG.IDLE) # DONE, then reset once > 60 m from the ring + assert _LAST["guide"].dk_out == 0.0 + + +# --------------------------------------------------------------------------------------------- +# Identity / gating + +class FakeParams: + def __init__(self, on=False, ring=None): + self.on, self.ring = on, ring + + def get_bool(self, key): + assert key == RG.PARAM_ROUNDABOUT_ASSIST + return self.on + + def get(self, key): + return self.ring + + +class FakeGps: + def __init__(self, lat, lon, brg, speed): + self.latitude, self.longitude, self.bearingDeg, self.speed = lat, lon, brg, speed + self.bearingAccuracyDeg, self.hasFix = 1.0, True + + +class FakeSM: + def __init__(self): + self.recv_frame = {"gpsLocation": 0, "gpsLocationExternal": 0} + self.logMonoTime = {"gpsLocation": 0} + self.msgs = {} + + def __getitem__(self, k): + return self.msgs[k] + + +class Hint: + def __init__(self, way_id): + self.way_id = way_id + + +_TRAJ = {} + + +def _trajectory(name): + """The 'after' closed-loop trajectory (truth pose, speed, model curvature) through the ring.""" + if name not in _TRAJ: + _TRAJ[name] = simulate(name, "after")[0] + return _TRAJ[name] + + +def _drive_assist(assist, name, *, hint=True, lat_active=True, maneuver=False, lane_change=False, hint_until=1e9): + """Replay the approach + ring trajectory through RoundaboutAssist (1 Hz GNSS from truth); (model_k, out_k).""" + p = PASSES[name] + ring = _ring(p) + sm = FakeSM() + rows = [(t, x, y, psi, v, 0.0) for t, x, y, psi, v, _yr in p["hist"]] + rows += [(r[0], r[1], r[2], r[3], r[4], r[5]) for r in _trajectory(name)[::10]] # 0.1 s steps + pairs = [] + frame = 0 + next_fix = rows[0][0] + 1.0 + prev = None + for i, (t, x, y, psi, v, mk_base) in enumerate(rows): + yr = 0.0 if prev is None else RG._wrap(psi - prev[3]) / max(t - prev[0], 1e-3) + prev = (t, x, y, psi) + if t >= next_fix: + next_fix += 1.0 + lat, lon = latlon_from_xy(x, y, ring.lat, ring.lon) + frame += 1 + sm.recv_frame["gpsLocation"] = frame + # The fix of time t arrives ~0.9 s later (qcom latency); one 0.1 s step before this update. + sm.logMonoTime["gpsLocation"] = int((t - 0.1 + RG.GPS_LATENCY_S) * 1e9) + sm.msgs["gpsLocation"] = FakeGps(lat, lon, math.degrees(psi) % 360.0, v) + mk = mk_base + 0.002 * math.sin(0.7 * i) + out = assist.update(sm, t=t, v_ego=v, yaw_rate=yr, model_k=mk, lat_active=lat_active, maneuver_active=maneuver, + lane_change_active=lane_change, hint=Hint(ring.way_ids[0]) if (hint and t <= hint_until) else None, + model_v2=None) + pairs.append((mk, out)) + return pairs + + +def _assist(on=True, preap=True, ring="128"): + ring_json = json.dumps(PASSES["00000128"]["ring"]) if ring == "128" else ring + return RG.RoundaboutAssist(preap, FakeParams(on=on, ring=ring_json)) + + +def test_assist_engages_through_the_ring_when_on(): + a = _assist() + pairs = _drive_assist(a, "00000128") + assert a.guide.ring is not None and a.guide.pose.pose() is not None + assert max(abs(out - mk) for mk, out in pairs) > 0.01 + assert pairs[-1][0] == pairs[-1][1] # handed back after the exit + + +@pytest.mark.parametrize("preap,on", [(False, True), (True, False), (False, False)]) +def test_identity_when_off_or_not_preap(preap, on): + for mk, out in _drive_assist(_assist(on=on, preap=preap), "00000128"): + assert out == mk + + +def test_identity_without_hint_or_ring_param(): + for ring in (None, "{}"): + for mk, out in _drive_assist(_assist(ring=ring), "00000128"): + assert out == mk + for mk, out in _drive_assist(_assist(), "00000128", hint=False): + assert out == mk + + +def test_stale_ring_does_not_engage(monkeypatch): + """Ring loaded from an old hint, hint gone > HINT_HOLD_S before the ring: stays model-only.""" + monkeypatch.setattr(RG, "HINT_HOLD_S", 3.0) + a = _assist() + pairs = _drive_assist(a, "00000128", hint_until=-7.5) + assert a.guide.ring is not None + assert all(out == mk for mk, out in pairs) + + +@pytest.mark.parametrize("kw", [dict(lat_active=False), dict(maneuver=True), dict(lane_change=True)]) +def test_identity_when_driver_has_wheel_or_maneuver(kw): + for mk, out in _drive_assist(_assist(), "00000128", **kw): + assert out == mk + + +def test_identity_far_from_any_ring(): + """Non-roundabout driving: straight road 400 m from the ring, toggle On, ring loaded -> exact model.""" + ring = _ring(PASSES["00000128"]) + g = RG.RoundaboutGuide() + g.set_ring(ring) + x, y = -400.0, 400.0 + for i in range(3000): + t = i * DT + if i % 100 == 0: + lat, lon = latlon_from_xy(x, y, ring.lat, ring.lon) + g.gnss(t, lat, lon, 90.0, 15.0, 1.0) + mk = 0.002 * math.sin(0.01 * i) + assert g.update(t, 15.0, 0.0, mk, enabled=True, lat_active=True) == mk + x += 15.0 * DT + + +def test_edge_limit_keeps_camera_authority(): + e = RG.EdgeInfo(x=10.0, path_y=0.0, left_y=-1.4, right_y=1.6) + # 1.28 m margin (half car + 0.3): left line at -1.4 -> at most 0.12 m of extra left at 10 m. + dk = RG.limit_correction_by_edges(-0.03, e) + assert dk == pytest.approx(2 * -0.12 / 100.0) + assert RG.limit_correction_by_edges(0.03, e) == pytest.approx(2 * 0.32 / 100.0) + # Already inside the margin: no correction toward that side at all; the other side untouched. + tight = RG.EdgeInfo(x=10.0, path_y=0.0, left_y=-1.0, right_y=None) + assert RG.limit_correction_by_edges(-0.03, tight) == 0.0 + assert RG.limit_correction_by_edges(0.03, tight) == 0.03 + assert RG.limit_correction_by_edges(-0.03, None) == -0.03 + + +def test_pose_error_lowers_confidence_and_fades(): + """No GNSS after the approach: fix age -> confidence 0 -> correction slews back to the model.""" + p = PASSES["00000128"] + ring = _ring(p) + g = RG.RoundaboutGuide() + g.set_ring(ring) + fixes = {round(f[0], 1): f for f in p["fixes"]} + for t, x, y, psi, v, yr in p["hist"]: + g.update(t, v, yr, 0.0, enabled=True, lat_active=True) + if round(t, 1) in fixes: + lat, lon = latlon_from_xy(x, y, ring.lat, ring.lon) + g.gnss(t, lat, lon, math.degrees(psi) % 360.0, v, 1.0, latency_s=0.0) + assert g.pose.confidence(p["hist"][-1][0]) > 0.9 + t, x, y, psi, v = p["hist"][-1][0], p["hist"][-1][1], p["hist"][-1][2], p["hist"][-1][3], 8.0 + outs = [] + for _ in range(800): # 8 s, no fixes, driving straight into the ring + t += DT + outs.append(g.update(t, v, 0.0, 0.0, enabled=True, lat_active=True)) + assert g.pose.confidence(t) == 0.0 + assert outs[-1] == 0.0 + + +def test_map_match_bias_removes_gnss_offset_beyond_a_lane(): + """R126: GNSS ran ~4-6 m north of the inbound Soco Rd; one lane (1.75 m) of it is not an error.""" + ring = _ring(PASSES["00000126"]) + g = RG.RoundaboutGuide() + g.set_ring(ring) + # Inbound on the lower Soco branch (travel direction stored in the ring JSON), driven along its polyline. + app = min((a for a in ring.approaches if math.hypot(*a[-1]) < math.hypot(*a[0]) and a[0][1] < -5.0), + key=lambda a: a[0][0]) + segs = list(zip(app, app[1:], strict=False)) + bias = 5.0 + lefts = [] + i = 0 + for (x0, y0), (x1, y1) in segs: + L = math.hypot(x1 - x0, y1 - y0) + ux, uy = (x1 - x0) / L, (y1 - y0) / L + nx, ny = -uy, ux # left normal of travel + psi = math.atan2(ux, uy) + for k in range(int(L / (8.0 * DT))): + t = i * DT + x, y = x0 + 8.0 * DT * k * ux, y0 + 8.0 * DT * k * uy + g.update(t, 8.0, 0.0, 0.0, enabled=False, lat_active=False) + if i % 100 == 0 and i > 0 and math.hypot(x, y) > ring.radius_m + 10.0: + lat, lon = latlon_from_xy(x + bias * nx, y + bias * ny, ring.lat, ring.lon) + g.gnss(t, lat, lon, math.degrees(psi) % 360.0, 8.0, 1.0, latency_s=0.0) + lefts.append((nx, ny)) + i += 1 + nx, ny = lefts[-1] + bx, by = g.bias + assert (bx * nx + by * ny) == pytest.approx(bias - RG.LANE_SNAP_M, abs=0.8) + + +def test_circle_follow_sign_convention(): + # On the ring centerline, tangent to CCW circulation: follow curvature ~ -1/R (left, negative). + R = 21.6 + k = RG.circle_follow_curvature(R, 0.0, 0.0, 7.0, R, True) # east point, heading north + assert k == pytest.approx(-1.0 / R, abs=1e-6) + k_cw = RG.circle_follow_curvature(R, 0.0, math.pi, 7.0, R, False) # CW: heading south + assert k_cw == pytest.approx(1.0 / R, abs=1e-6) + # Outside the lane radius -> tighter left; heading outward -> tighter left. + assert RG.circle_follow_curvature(R + 2.0, 0.0, 0.0, 7.0, R, True) < -1.0 / (R + 2.0) + assert RG.circle_follow_curvature(R, 0.0, math.radians(20.0), 7.0, R, True) < -1.0 / R + + +def test_params_and_menu_wiring(): + keys = (ROOT / "common" / "params_keys.h").read_text() + assert '{"NAPRoundaboutAssist", {PERSISTENT, BOOL, "0"}}' in keys + assert '{"NAPRoundaboutRing", {CLEAR_ON_MANAGER_START, JSON}}' in keys + from openpilot.selfdrive.ui.layouts.settings import nap_lateral + assert nap_lateral.NAP_ROUNDABOUT_ASSIST == RG.PARAM_ROUNDABOUT_ASSIST + assert nap_lateral.ROUNDABOUT_ASSIST_DESCRIPTION.startswith("Default Off.") + menu = (ROOT / "selfdrive" / "ui" / "layouts" / "settings" / "driving_mannerisms.py").read_text() + assert '"Roundabout Steering Assist"' in menu and "NAP_ROUNDABOUT_ASSIST" in menu + + +def test_controlsd_applies_assist_before_legacy_bias_and_pins_nothing_else(): + src = (ROOT / "selfdrive" / "controls" / "controlsd.py").read_text() + assert "'gpsLocation', 'gpsLocationExternal'" in src + assert "RoundaboutAssist(self._turn_geom_preap, self.params)" in src + i_assist = src.index("self.rb_assist.update(") + i_bias = src.index("rb_bias = roundabout_lateral_curvature_bias(\n") + i_handoff = src.index("new_desired_curvature = handoff_new_desired_curvature(") + assert i_assist < i_bias < i_handoff + assert "model_or_plan_curvature = float(model_or_plan_curvature) + (0.0 if self.rb_assist.active else rb_bias)" in src + # Assist output flows through the unchanged handoff + clip_curvature path. + assert "clip_curvature(\n CS.vEgo, self.desired_curvature, new_desired_curvature, lp.roll)" in src + + +def test_nan_odometry_sample_does_not_poison_the_pose(): + """R126 qlog had NaN yaw samples early in the route; one NaN used to leave the pose NaN for the drive.""" + ring = _ring(PASSES["00000128"]) + g = RG.RoundaboutGuide() + g.set_ring(ring) + x, y = 60.0, 6.0 + for i in range(600): + t = i * DT + yr = float("nan") if i == 50 else 0.0 + assert g.update(t, 10.0, yr, 0.001, enabled=True, lat_active=True) == 0.001 or i > 0 + if i % 100 == 99: + lat, lon = latlon_from_xy(x - 10.0 * t, y, ring.lat, ring.lon) + g.gnss(t, lat, lon, 270.0, 10.0, 1.0, latency_s=0.0) + pose = g.corrected_pose() + assert pose is not None and all(math.isfinite(v) for v in pose) + assert g.update(6.01, float("nan"), 0.0, 0.002, enabled=True, lat_active=True) == 0.002 + + +# --------------------------------------------------------------------------------------------- +# Sep 29 11:57:48 (Scallywag): the left curl was ~2x the model at 17-18 mph from a pose that read inside the lane +# (qcom bearing accuracy 30-50°, map-match bias 1.2→3.4 m). 11:57:20-52 carState v / yaw / model curvature (10 Hz) +# and the 1 Hz GNSS fixes are in the fixture; t is relative to 11:57:20. + +SEP29 = json.loads((Path(__file__).parent / "data" / "roundabout_sep29_1157.json").read_text()) +MPH_MS = 0.44704 + + +def _sep29(**patch): + """Replay the ring pass through the guide; returns (rows, guide). rows: (t, v, model_k, out_k, latched).""" + ring = RingGeometry.from_json(SEP29["ring"]) + g = RG.RoundaboutGuide() + g.set_ring(ring) + fixes = list(SEP29["gps"]) + fi, rows = 0, [] + for t, v, yr, mk, lat in SEP29["rows"]: + while fi < len(fixes) and fixes[fi][0] <= t: + f = fixes[fi] + g.gnss(f[0], f[1], f[2], f[3], f[4], f[5], patch.get("latency", RG.GPS_LATENCY_S)) + fi += 1 + out = g.update(t, v, yr, mk, enabled=t >= 16.0, lat_active=bool(lat)) + rows.append((t, v, mk, out, g.latched)) + return rows, g + + +def _old_constants(monkeypatch): + """The Sep 29 behavior: 3.0 m/s² left cap, fast slews, no curl hold, latch whatever the pose, no ring cap.""" + for k, v in dict(A_LAT_CIRC_MAX=3.0, OUT_SLEW=0.07, TARGET_SLEW=0.07, OUT_SLEW_GOOD=0.07, TARGET_SLEW_GOOD=0.07, SPEED_HOLD_MS=1e9, + BEARING_ACC_UNRELIABLE_DEG=1e9, BIAS_UNRELIABLE_M=1e9, BIAS_LATCH_DRIFT_M=1e9, RING_CAP_RATIO=1e3, RING_A_LAT_MAX=1e3, + RING_SLEW=0.07).items(): + monkeypatch.setattr(RG, k, v) + + +def _left_peak(rows): + win = [r for r in rows if 24.5 <= r[0] <= 30.2] + return max(-r[3] for r in win), max(-r[2] for r in win) + + +def test_sep29_left_curl_no_longer_doubles_the_model(monkeypatch): + _old_constants(monkeypatch) + old_rows, _ = _sep29(latency=0.9) + old_out, old_mk = _left_peak(old_rows) + assert old_out > 1.5 * old_mk # the logged bug (0.0476 vs the model's 0.0237) without the Sep 29/30 limits + monkeypatch.undo() + rows, g = _sep29() + out, mk = _left_peak(rows) + assert out <= 1.2 * mk + 1e-9 # never more than 1.2x the model through the pass + assert out < 0.7 * old_out + assert not any(r[4] for r in rows if r[0] < 30.0) # no latch on the unreliable pose (bearing accuracy 33-45°) + assert all(abs(r[3] - r[2]) < 1e-9 for r in rows if 29.0 <= r[0] <= 30.2) # ...and the assist has faded: the model keeps the pass + assert any("latch blocked unreliable" in e for e in g.events) + + +def test_sep29_left_transition_accel_and_rate_stay_low(): + rows, _ = _sep29() + win = [r for r in rows if 24.5 <= r[0] <= 30.2] + assert max(abs(r[3]) * r[1] ** 2 for r in win if r[3] < 0) <= 2.2 + assert max(abs((b[3] - b[2]) - (a[3] - a[2])) / (b[0] - a[0]) for a, b in zip(win, win[1:], strict=False)) <= 0.035 # correction rate + + +def test_gps_latency_is_the_measured_one(): + assert RG.GPS_LATENCY_S == 0.66 + assert RG.GPS_EXT_LATENCY_S == 0.2 + + +def test_left_transition_cap_uses_actual_speed(): + v = 8.0 + assert RG.lat_limited(-1.0, v, 1.0) == pytest.approx(-2.2 / v ** 2) # CCW: left (negative) capped at 2.2 m/s² + assert RG.lat_limited(1.0, v, 1.0) == pytest.approx(3.0 / v ** 2) # right entry keeps 3.0 + assert RG.lat_limited(1.0, v, -1.0) == pytest.approx(2.2 / v ** 2) # CW ring mirrors it + assert RG.lat_limited(-1.0, v, -1.0) == pytest.approx(-3.0 / v ** 2) + + +def test_ring_cap_is_1_15x_the_model_and_2_2_mps2(): + assert (RG.RING_CAP_RATIO, RG.RING_A_LAT_MAX, RG.RING_SLEW) == (1.15, 2.2, 0.035) + assert RG.ring_cap(0.02, -0.02, 6.0, 1.0) == pytest.approx(1.15 * 0.02) # CCW, model 0.02 left: 1.15x + assert RG.ring_cap(0.03, -0.03, 8.0, 1.0) == pytest.approx(2.2 / 64.0) # lateral cap bites first (1.15x = 0.0345) + assert RG.ring_cap(0.05, -0.05, 20.0, 1.0) == pytest.approx(0.05) # ...never below the model itself + assert RG.ring_cap(0.02, 0.01, 6.0, 1.0) == pytest.approx(-0.01) # model curving away: the assist never adds left + assert RG.ring_cap(0.02, 0.02, 6.0, -1.0) == pytest.approx(1.15 * 0.02) # CW mirrors it + assert RG.ring_floor(0.02, 6.0) == pytest.approx(0.85 * 0.02) + + +def test_slews_are_0_035_for_a_poor_pose(): + assert RG.OUT_SLEW == 0.035 and RG.TARGET_SLEW == 0.035 + assert RG.OUT_SLEW_GOOD == 0.07 and RG.TARGET_SLEW_GOOD == 0.07 # good pose: R126/R128 fixtures need the old rate + + +def test_pose_quality_thresholds(): + assert RG.pose_quality(31.0, 0.0, 0.0, 1.0) == (True, True) # bearing accuracy > 30° + assert RG.pose_quality(10.0, 0.0, 0.0, 1.0) == (False, False) + assert RG.pose_quality(25.0, 2.5, 0.0, 1.0) == (True, True) # bias > 2 m with a degraded bearing + assert RG.pose_quality(10.0, 4.5, 0.0, 1.0) == (False, False) # R126: large but removed bias, usable bearing + assert RG.pose_quality(25.0, 0.5, 0.0, 1.0) == (False, True) # poor: latch allowed, capped + assert RG.pose_quality(10.0, 0.5, 0.0, RG.INNOV_POOR_M + 0.1) == (False, True) + + +def test_curl_is_held_until_within_3_mph_of_ring_speed(): + assert RG.SPEED_HOLD_MS == pytest.approx(3.0 * MPH_MS) + assert RG.hold_curl(-0.03, 0.01, 1.0) == 0.01 # CCW: left (negative) not added over the model + assert RG.hold_curl(0.03, 0.01, 1.0) == 0.03 # right still added + assert RG.hold_curl(0.03, -0.01, -1.0) == -0.01 # CW mirrors it + ring = RingGeometry.from_json(SEP29["ring"]) + g = RG.RoundaboutGuide() + g.set_ring(ring) + assert g.ring_v == pytest.approx(18.0 * MPH_MS, abs=0.05) # RB_RING_SPEED_MPH + rows, g2 = _sep29() + assert any(e.startswith("curl held") for e in g2.events) and any(e.startswith("curl released") for e in g2.events) + + +def _tangent_guide(bacc, bias, old_bias=None): + """Guide with a fabricated pose on the ring's east point heading north (tangent for CCW), one update in.""" + ring = RingGeometry.from_json(SEP29["ring"]) + g = RG.RoundaboutGuide() + g.set_ring(ring) + g.pose.bacc = bacc + g.bias = (bias, 0.0) + if old_bias is not None: + g.bias_hist.append((-2.0, old_bias, 0.0)) + g.pose.initialized = True + g.pose.xo, g.pose.yo, g.pose.psio, g.pose.dpsi = ring.radius_m - 2.5 + bias, 0.0, 0.0, 0.0 + g.pose.t = 0.0 + g.pose.n_good, g.pose.innov, g.pose.last_fix_t = 3, 0.5, 0.0 + g.phase = RG.ACTIVE + g.update(0.1, 7.0, 0.0, -0.02, enabled=True, lat_active=True) + return g, ring + + +def test_poor_pose_latch_never_aims_at_the_inner_side(): + g, ring = _tangent_guide(5.0, 0.3) # good pose: the lane clamp R - hw/2 is fine + assert g.latched and g.r_ref >= ring.radius_m - 0.5 * ring.half_width_m - 1e-9 + g, ring = _tangent_guide(25.0, 0.3) # degraded bearing: latch, but never inside R + assert g.latched and g.latch_poor and g.r_ref >= ring.radius_m - 1e-9 + g, ring = _tangent_guide(5.0, 3.0) # bias > 2 m: never inside R + assert g.latched and g.r_ref >= ring.radius_m - 1e-9 + + +def test_unreliable_or_unsettled_pose_does_not_latch(): + g, _ = _tangent_guide(35.0, 0.3) + assert not g.latched and any("latch blocked unreliable" in e for e in g.events) + g, _ = _tangent_guide(25.0, 2.5) + assert not g.latched + g, _ = _tangent_guide(5.0, 0.3, old_bias=2.0) # bias moved 1.7 m in the last 2 s: not bias-consistent yet + assert not g.latched and any("latch blocked bias_unsettled" in e for e in g.events) + g, _ = _tangent_guide(5.0, 0.3, old_bias=0.0) # 0.3 m: consistent + assert g.latched + + +def _with_poor_pose(monkeypatch, name): + monkeypatch.setattr(RG, "pose_quality", lambda *a: (False, True)) + rows, ring = simulate(name, "after") + return rows, _LAST["guide"] + + +@pytest.mark.parametrize("name", sorted(PASSES)) +def test_poor_pose_uses_the_slow_slews(monkeypatch, name): + rows, _ = _with_poor_pose(monkeypatch, name) + for a, b in zip(rows, rows[1:], strict=False): + assert abs((b[6] - b[5]) - (a[6] - a[5])) / DT <= RG.OUT_SLEW + 1e-6 or abs(b[6] - a[6]) / DT <= RG.OUT_SLEW + 1e-6 # or held + assert abs(b[6] - a[6]) / DT <= max(RG.OUT_SLEW, RG.RING_CAP_RATIO * abs(b[5] - a[5]) / DT) + 1e-6 # the cap follows the model at 1.15x + + +@pytest.mark.parametrize("name", sorted(PASSES)) +def test_poor_pose_target_slew(monkeypatch, name): + seen = [] + orig = RG.RoundaboutGuide.update + + def spy(self, t, *a, **k): + out = orig(self, t, *a, **k) + seen.append((t, self.k_tgt)) + return out + monkeypatch.setattr(RG.RoundaboutGuide, "update", spy) + _with_poor_pose(monkeypatch, name) + steps = [(b[0] - a[0], abs(b[1] - a[1])) for a, b in zip(seen, seen[1:], strict=False) if a[1] is not None and b[1] is not None and 0 < b[0] - a[0] < 0.05] + assert len(steps) > 500 + jumps = [d / dt for dt, d in steps if d / dt > RG.TARGET_SLEW + 1e-6] + assert len(jumps) <= 3 # only re-seeds when lat/the model reset the target + + +@pytest.mark.parametrize("name", ["00000128", "00000130"]) +def test_ring_output_never_above_1_15x_the_model_or_2_2_after_the_latch(name): + """After the latch, whatever the pose quality, the output is within [0.85, 1.15] x the model while it curves with the circulation. + Oct 1 (ring hold): except while the cap is widened toward the circle (model under half of it, <= CIRCLE_CAP_EXTRA over the model) or + inside an exit window (floor = the circle target); those are bounded below and in test_ring_hold_*.""" + for poor in (False, True): + with pytest.MonkeyPatch.context() as mp: + if poor: + mp.setattr(RG, "pose_quality", lambda *a: (False, True)) + seen = {} + orig = RG.RoundaboutGuide.update + + def spy(self, t, *a, _o=orig, _s=seen, **k): + out = _o(self, t, *a, **k) + pose = self.corrected_pose() + _s[round(t, 2)] = (self.cap_extra, pose is not None and RH.in_exit_window(math.atan2(pose[1], pose[0]), 1.0, self.exits)) + return out + mp.setattr(RG.RoundaboutGuide, "update", spy) + rows, _ = simulate(name, "after", pool=PASSES_ALL) + g = _LAST["guide"] + assert g.latch_t is not None + peak = 0.0 + for r in rows: + if r[0] < g.latch_t + 0.5 or r[0] > g.latch_t + 40.0 or r[5] >= 0.0 or r[6] == r[5]: + continue + extra, window = seen[round(r[0], 2)] + if extra > 0.0 or window: + assert -r[6] * r[4] ** 2 <= RG.RING_A_LAT_MAX * 1.0001 # the widened cap / floor stays bound by 2.2 m/s² + continue + peak = max(peak, r[6] / r[5]) + assert r[6] / r[5] <= RG.RING_CAP_RATIO + 1e-6 + assert -r[6] * r[4] ** 2 <= max(RG.RING_A_LAT_MAX, -r[5] * r[4] ** 2) + 1e-6 + assert peak > 1.05 + + +def test_ring_output_slews_at_most_0_035_after_the_latch(): + rows, _ = simulate("00000128", "after", pool=PASSES_ALL) + g = _LAST["guide"] + win = [r for r in rows if g.latch_t <= r[0] <= g.latch_t + 8.0] + assert len(win) > 500 + for a, b in zip(win, win[1:], strict=False): + assert abs((b[6] - b[5]) - (a[6] - a[5])) / DT <= RG.RING_SLEW + 1e-6 or abs(b[6] - a[6]) / DT <= RG.RING_SLEW + 1e-6 # or held + + +def test_curl_held_while_over_ring_speed_on_the_fixtures(): + for name in ("00000128",): + rows, ring = simulate(name, "after", slow=False) # no ring slow-down: the car arrives fast + g = _LAST["guide"] + R, hw = ring.radius_m, ring.half_width_m + fast = [r for r in rows if r[4] > g.ring_v + RG.SPEED_HOLD_MS and math.hypot(r[1], r[2]) > R - 0.5 * hw] + assert fast and all(r[6] >= r[5] - 1e-9 for r in fast) + + +def test_ring_state_is_logged_via_cloudlog_without_capnp(monkeypatch): + msgs = [] + monkeypatch.setattr(RG.cloudlog, "error", lambda m: msgs.append(m)) # errorLogMessage is in qlog, logMessage is rlog-only + a = _assist() + _drive_assist(a, "00000128") + assert any(m.startswith("roundabout_assist latched") for m in msgs) + assert any(m.startswith("roundabout_assist released") for m in msgs) + assert any(m.startswith("roundabout_assist state phase=") and "bacc=" in m and "r_ref=" in m for m in msgs) + src = (ROOT / "selfdrive" / "controls" / "lib" / "roundabout_guide.py").read_text() + assert "import cereal" not in src and "from cereal" not in src + assert "from cereal" not in (ROOT / "selfdrive" / "controls" / "lib" / "roundabout_ring_log.py").read_text() + + +class _Seq: + def __init__(self, x, y): + self.x, self.y = x, y + + +class _FakeModel: + position = _Seq([0.0, 10.0, 20.0, 40.0], [0.0, 0.5, 2.0, 8.0]) + laneLines = [_Seq([0.0, 40.0], [-5.5, -5.0]), _Seq([0.0, 40.0], [-1.8, -1.4]), _Seq([0.0, 40.0], [1.8, 2.2]), _Seq([0.0, 25.0], [5.5, 6.0])] + laneLineProbs = [0.1, 0.9, 0.8, 0.2] + roadEdges = [_Seq([0.0, 40.0], [-7.0, -6.0]), _Seq([0.0, 40.0], [4.0, 4.5])] + roadEdgeStds = [0.3, 1.2] + + +def test_raw_model_summary_logged_near_and_in_the_ring(monkeypatch): + """~1.25 Hz compact JSON of the model's raw lane lines / road edges / path (+ ring state and driver inputs) near and in a ring.""" + msgs = [] + monkeypatch.setattr(RG.cloudlog, "error", lambda m: msgs.append(m)) + a = _assist() + p = PASSES["00000128"] + ring = _ring(p) + sm = FakeSM() + t = 0.0 + for i in range(400): + t = p["hist"][0][0] + i * 0.05 + a.update(sm, t=t, v_ego=8.0, yaw_rate=0.0, model_k=0.0, lat_active=True, maneuver_active=False, lane_change_active=False, + hint=Hint(ring.way_ids[0]), model_v2=_FakeModel()) + raw = [m for m in msgs if m.startswith("roundabout_raw ")] + assert raw == [] or len(raw) <= int(400 * 0.05 / RG.LOG_RAW_PERIOD_S) + 1 + g = a.guide + g.d_edge, g.debug = 20.0, {"r": 45.0} + a._last_raw_t = -1e9 + a._log(100.0, 0.01, 0.01, 8.0, _FakeModel(), RG.DriverInput(2, True, False, 0.4), True) + lines = [m for m in msgs if m.startswith("roundabout_raw ")] + assert lines + line = lines[-1] + d = json.loads(line[len("roundabout_raw "):]) + assert d["path"] == [0.25, 0.5, 1.25, 2.0, 5.0] + assert len(d["ll"]) == 4 and d["ll"][0][0] == -5.44 and d["ll"][3][-1] is None # 4th line stops at 25 m + assert d["llp"] == [0.1, 0.9, 0.8, 0.2] and d["res"] == [0.3, 1.2] and len(d["re"]) == 2 + assert d["stalk"] == [2, 1, 0, 0.4] and d["lat"] == 0 and d["de"] == 20.0 + assert len(line) < 700 + n = len(msgs) + a._log(100.3, 0.01, 0.01, 8.0, _FakeModel(), None, True) # inside LOG_RAW_PERIOD_S: no second summary + assert len(msgs) == n + g.d_edge = 200.0 + a._log(105.0, 0.01, 0.01, 8.0, _FakeModel(), None, True) # far from any ring: nothing + assert len(msgs) == n + a._log(106.0, 0.01, 0.01, 8.0, None, None, True) # no model message: nothing + assert len(msgs) == n + + +def test_off_stays_bit_identical_on_the_sep29_pass(): + ring_json = json.dumps(SEP29["ring"]) + for on, preap in ((False, True), (True, False)): + a = RG.RoundaboutAssist(preap, FakeParams(on=on, ring=ring_json)) + sm = FakeSM() + for t, v, yr, mk, lat in SEP29["rows"]: + assert a.update(sm, t=t, v_ego=v, yaw_rate=yr, model_k=mk, lat_active=bool(lat), maneuver_active=False, lane_change_active=False, + hint=Hint(SEP29["ring"]["ids"][0]), model_v2=None) == mk + + +# --------------------------------------------------------------------------------------------- +# Sep 30: release only by the driver (held same-side stalk / steering pull / override); the driver always wins; tips suppressed + +def _on_ring(**kw): + """Latched guide on the ring (east point, heading north, CCW), a few updates in, model curving left (-0.02).""" + g, ring = _tangent_guide(5.0, 0.3) + assert g.latched and g.phase == RG.ACTIVE + return g + + +def _run(g, n, driver=None, mk=-0.02, lat=True, t0=0.2, v=7.0): + outs = [] + for i in range(n): + outs.append(g.update(t0 + i * DT, v, v * mk, mk, enabled=True, lat_active=lat, driver=driver)) + return outs + + +def test_ring_assist_follows_the_lane_circle_once_latched(): + g = _on_ring() + outs = _run(g, 100) + assert g.latched and g.r_lane == pytest.approx(g.ring.radius_m - 0.5 * g.ring.half_width_m) + assert all(o >= -0.02 - RH.CIRCLE_CAP_EXTRA - 1e-9 for o in outs) # CCW: never more left than the model + CIRCLE_CAP_EXTRA + + +def test_held_right_stalk_releases_the_ring_and_hands_back_at_once(): + g = _on_ring() + _run(g, 50) + out = _run(g, 1, RG.DriverInput(stalk_dir=2, stalk_held=True), t0=0.7) + assert out == [-0.02] and g.release == "stalk" and g.phase == RG.DONE and g.dk_out == 0.0 + assert any(e.startswith("released stalk") for e in g.events) + assert _run(g, 20, t0=0.8) == [-0.02] * 20 # stays released + + +def test_held_left_stalk_does_not_release_but_the_guide_weight_is_zero(): + g = _on_ring() + _run(g, 50) + outs = _run(g, 100, RG.DriverInput(stalk_dir=1, stalk_held=True), t0=0.7) + assert outs == [-0.02] * 100 and g.latched and g.phase == RG.ACTIVE and g.release == "" and g.debug["w"] == 0.0 + + +def test_steering_pull_toward_the_exit_releases_after_0_3_s(): + g = _on_ring() + _run(g, 50) + outs = _run(g, 25, RG.DriverInput(torque=-2.0), t0=0.7) # + is left: -2 Nm pulls right = the exit on a CCW ring + assert outs == [-0.02] * 25 and g.release == "" and g.latched # weight is 0 at once, not released yet + outs = _run(g, 10, RG.DriverInput(torque=-2.0), t0=0.95) + assert outs == [-0.02] * 10 and g.release == "pull" and g.phase == RG.DONE + + +def test_steering_pull_toward_the_circulation_does_not_release_but_wins(): + g = _on_ring() + _run(g, 50) + outs = _run(g, 100, RG.DriverInput(torque=2.0), t0=0.7) + # Same-side add keeps the extra curl. It does not zero the weight and it does not release. + assert any(o != -0.02 for o in outs) and g.release == "" and g.phase == RG.ACTIVE and g.latched + + +def test_steering_press_zeroes_the_weight_after_0_3_s_and_overrides_after_0_5_s(): + g = _on_ring() + _run(g, 50) + assert any(o != -0.02 for o in _run(g, 25, RG.DriverInput(pressed=True), t0=0.7)) # < 0.3 s: a flicker, the assist keeps going + _run(g, 5, t0=0.95) # hands off: the debounce resets + mid = _run(g, 40, RG.DriverInput(pressed=True), t0=1.0) # 0.40 s: curl stays + assert any(o != -0.02 for o in mid) and g.release == "" + assert _run(g, 20, RG.DriverInput(pressed=True), t0=1.4)[-1] == -0.02 and g.release == "override" + g = _on_ring() + _run(g, 50) + assert _run(g, 100, lat=False, t0=0.7) == [-0.02] * 100 and g.release == "override" # lat off: the driver has the wheel + + +def test_no_blinker_no_map_exit_the_car_stays_on_the_ring(): + """No stalk / pull / press: the guide never releases for map reasons, on any of the four passes.""" + for name in ("00000126", "00000128", "0000012f", "00000130"): + simulate(name, "after", pool=PASSES_ALL) + g = _LAST["guide"] + assert g.release in ("", "far_from_ring"), name # the only non-driver release is the safety one, > 15 m outside the band + if g.latch_t is not None: + assert g.d_edge is None or g.release == "" or g.d_edge > RG.FAILSAFE_EDGE_M + g = _on_ring() + g.travel = 400.0 # more than a full circuit of the ring: still no map exit + outs = _run(g, 150) + assert g.release == "" and g.latched and g.phase == RG.ACTIVE and any(o != -0.02 for o in outs) + + +def test_latched_weight_does_not_depend_on_pose_confidence(): + """The 1.15x / 2.2 / 0.035 limits bound the assist, not a confidence fade: a stale fix (2.5 s) keeps the full weight.""" + g = _on_ring() + _run(g, 80) + g.pose.last_fix_t = g.last_t - 2.5 + _run(g, 5, t0=1.0) + assert g.debug["conf"] < 0.5 and g.debug["w"] == pytest.approx(1.0) and g.latched + + +def test_safety_release_far_outside_the_ring_fades_instead_of_stepping(): + g = _on_ring() + _run(g, 50) + g.pose.xo += 40.0 # pose says 40 m outside the band + _run(g, 5, t0=0.7) + assert g.release == "far_from_ring" and g.phase in (RG.EXITING, RG.DONE) + + +class _PutParams(FakeParams): + def __init__(self, **kw): + super().__init__(**kw) + self.puts = [] + + def put_bool(self, key, val): + self.puts.append((key, val)) + + +def test_latched_param_and_stalk_release_through_the_assist(): + from openpilot.selfdrive.controls.lib.stalk_tip_turn import PARAM_RING_LATCHED + assert PARAM_RING_LATCHED == "NAPRoundaboutLatched" + params = _PutParams(on=True, ring=json.dumps(PASSES["00000128"]["ring"])) + a = RG.RoundaboutAssist(True, params) + g = _on_ring() + a.guide = g + sm = FakeSM() + def step(i, stalk): + return a.update(sm, t=0.2 + i * DT, v_ego=7.0, yaw_rate=-0.14, model_k=-0.02, lat_active=True, maneuver_active=False, + lane_change_active=False, hint=Hint(g.ring.way_ids[0]), model_v2=None, stalk_state=stalk) + for i in range(30): + step(i, 0) + assert a.latched and params.puts == [(PARAM_RING_LATCHED, True)] + outs = [step(30 + i, 2) for i in range(60)] # right stalk held 0.6 s: StalkTipTurn.is_turn after 0.40 s + assert g.release == "stalk" and not a.latched and params.puts[-1] == (PARAM_RING_LATCHED, False) + assert outs[-1] == -0.02 + + +def test_off_while_latched_resets_and_clears_the_param(): + params = _PutParams(on=True, ring=json.dumps(PASSES["00000128"]["ring"])) + a = RG.RoundaboutAssist(True, params) + a.guide = _on_ring() + a.update(FakeSM(), t=0.2, v_ego=7.0, yaw_rate=0.0, model_k=-0.02, lat_active=True, maneuver_active=False, lane_change_active=False, + hint=Hint(a.guide.ring.way_ids[0])) + assert params.puts == [(RG.PARAM_RING_LATCHED, True)] + params.on = False + a._frame = RG.PARAM_READ_FRAMES + assert a.update(FakeSM(), t=0.3, v_ego=7.0, yaw_rate=0.0, model_k=-0.02, lat_active=True, maneuver_active=False, + lane_change_active=False) == -0.02 + assert not a.guide.latched and params.puts[-1] == (RG.PARAM_RING_LATCHED, False) + + +def test_tips_are_suppressed_while_latched_and_modeld_controlsd_are_wired(): + from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper, LaneChangeState + from openpilot.selfdrive.controls.lib.tests.test_desire_helper import _arm_left + dh = DesireHelper() + dh.suppress_tips = True + _arm_left(dh) + assert dh.lane_change_state == LaneChangeState.off # a tip no longer arms ALC on the ring + dh = DesireHelper() + _arm_left(dh) + assert dh.lane_change_state == LaneChangeState.preLaneChange # ...and does elsewhere + modeld = (ROOT / "selfdrive" / "modeld" / "modeld.py").read_text() + assert "DH.suppress_tips = params.get_bool(PARAM_RING_LATCHED)" in modeld + assert modeld.index("DH.suppress_tips = ") < modeld.index("DH.update(") + cd = (ROOT / "selfdrive" / "controls" / "controlsd.py").read_text() + assert "stalk_state=int(getattr(CS, 'turnSignalStalkState', 0) or 0)" in cd + assert "steering_pressed=bool(CS.steeringPressed), steering_torque=float(CS.steeringTorque)" in cd + assert '{"NAPRoundaboutLatched", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}' in (ROOT / "common" / "params_keys.h").read_text() + + +def test_ring_speed_constant_is_18_mph_and_planner_uses_it(): + from openpilot.selfdrive.mapd import roundabout as rb + assert rb.RB_RING_SPEED_MPH == 18.0 and rb.RB_V_MIN_MS == pytest.approx(18.0 * MPH) + assert rb.roundabout_target_ms(12.0 * MPH) == pytest.approx(18.0 * MPH) # a slower comfort speed is floored up to it + assert rb.roundabout_target_ms(40.0 * MPH) == pytest.approx(20.0 * MPH) # and the max stays 20 mph diff --git a/selfdrive/controls/lib/tests/test_roundabout_ring_hold.py b/selfdrive/controls/lib/tests/test_roundabout_ring_hold.py new file mode 100644 index 00000000000000..24033c81547bc4 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_roundabout_ring_hold.py @@ -0,0 +1,233 @@ +"""Roundabout ring hold (Oct 1 pm, 0000013c): cap against the map circle, exit-window floor, driver-press debounce, earlier latch, exit blinker. +NAPRoundaboutAssist stays default Off (Off bit-identical: test_roundabout_guide.py). Curvature + = right; the Sep 29 ring is CCW (circulation < 0).""" +import json +import math +from pathlib import Path + +import pytest + +from openpilot.selfdrive.controls.lib import roundabout_guide as RG +from openpilot.selfdrive.controls.lib import roundabout_ring_hold as RH +from openpilot.selfdrive.mapd.roundabout import RB_DECEL_ONSET_M, RB_FUNNEL_M +from openpilot.selfdrive.mapd.roundabout_map import RingGeometry + +DATA = Path(__file__).parent / "data" +SEP29 = json.loads((DATA / "roundabout_sep29_1157.json").read_text()) +RING = RingGeometry.from_json(SEP29["ring"]) +P13 = json.loads((DATA / "roundabout_pass_oct1.json").read_text())["passes"] +DT = 0.01 +A = 2.2 # m/s² lateral-accel cap + + +def _guide(theta_deg, off=-2.5, mk=-0.002, v=7.0): + """Guide on the ring at polar angle theta_deg (off = meters from R, - = inside), heading along the circulation, one update in.""" + g = RG.RoundaboutGuide() + g.set_ring(RING) + th, r = math.radians(theta_deg), RING.radius_m + off + g.pose.bacc, g.bias, g.pose.initialized = 5.0, (0.3, 0.0), True + g.pose.xo, g.pose.yo, g.pose.psio, g.pose.dpsi = r * math.cos(th), r * math.sin(th), th + math.pi / 2, 0.0 + g.pose.t, g.pose.n_good, g.pose.innov, g.pose.last_fix_t = 0.0, 3, 0.5, 0.0 + g.phase = RG.ACTIVE + g.update(0.1, v, v * mk, mk, enabled=True, lat_active=True) + return g + + +def _run(g, n, driver=None, mk=-0.002, t0=0.2, v=7.0): + return [g.update(t0 + i * DT, v, v * mk, mk, enabled=True, lat_active=True, driver=driver) for i in range(n)] + + +# ---- pure functions ------------------------------------------------------------------------------------------- + +def test_exit_angles_are_the_three_soco_branches(): + assert [round(a) for a in RH.exit_angles(RING)] == [63, 150, 308] + assert RH.exit_angles(None) == [] + assert [round(x) for x in _guide(298.0).exits] == [63, 150, 308] # the guide takes them from set_ring + + +def test_widen_cap_only_below_half_the_circle_and_bounded(): + v, circle = 8.0, 0.045 + assert RH.widen_cap(0.01, 0.03, circle, v, A) == 0.01 # model at 67% of the circle: untouched + assert RH.widen_cap(0.01, 0.0, circle, v, A) == pytest.approx(RH.CIRCLE_CAP_EXTRA) # model 0: up to CIRCLE_CAP_EXTRA over it + assert RH.widen_cap(0.0, 0.0, circle, 30.0, A) == pytest.approx(A / 900.0) # 2.2 m/s² still binds at speed + assert RH.widen_cap(0.0, 0.0, 0.004, v, A) == 0.004 # never above the circle target + assert RH.widen_cap(0.01, 0.0, -0.01, v, A) == 0.01 # circle target on the wrong side: nothing + edge = RH.widen_cap(0.0, 0.5 * circle - 1e-9, circle, v, A) + assert edge == pytest.approx(0.5 * circle, abs=1e-6) # fades to nothing at half the circle (cap = the model): no step + + +def test_ring_limits_floor_only_in_the_exit_window_without_a_stalk(): + cap, floor = RH.ring_limits(0.002, 0.0, 0.0, 0.045, 8.0, A, True, False) + assert floor == pytest.approx(min(0.045, A / 64.0)) and cap >= floor + assert RH.ring_limits(0.002, 0.0, 0.0, 0.045, 8.0, A, True, True) == (0.002, 0.0) # plain (stalk / off the band): old limits + assert RH.ring_limits(0.002, 0.0, 0.0, 0.045, 8.0, A, False, False)[1] == 0.0 # outside the window: no floor + + +def test_exit_windows_20_deg_before_and_5_after_for_both_senses(): + ex = [150.0] + for sense in (1.0, -1.0): + def ahead(d, sense=sense): # d deg before the exit along the circulation + return math.radians(150.0 - sense * d) + assert RH.in_exit_window(ahead(19.0), sense, ex) and RH.in_exit_window(ahead(0.0), sense, ex) + assert not RH.in_exit_window(ahead(21.0), sense, ex) and not RH.in_exit_window(ahead(-6.0), sense, ex) + assert RH.in_exit_window(ahead(-4.0), sense, ex) + + +def test_press_debounce_and_light_torque(): + assert not RH.counts_as_press(False, 3.0, 1.0) + assert RH.counts_as_press(True, 0.0, 1.0) + assert not RH.counts_as_press(True, 2.0, 1.0) # same-side add, any magnitude, is not a press + assert not RH.counts_as_press(True, 1.2, 1.0) # CCW: + (left) torque is toward the circulation + assert RH.counts_as_press(True, -1.2, 1.0) # toward the exit: counts + assert not RH.counts_as_press(True, -1.2, -1.0) and RH.counts_as_press(True, 1.2, -1.0) # CW mirror + t = 0.0 + for _ in range(40): + win, t = RH.driver_wins(False, True, 0.0, 1.0, t, DT) + assert not win # zero-torque press does not zero the curl + assert t == pytest.approx(0.40) + assert RH.driver_wins(False, True, 0.0, 1.0, 0.2, DT)[1] == pytest.approx(0.21) + assert RH.driver_wins(False, False, 0.0, 1.0, 0.2, DT) == (False, 0.0) # a gap resets the timer + assert not RH.driver_wins(False, False, 2.0, 1.0, 0.0, DT)[0] # same-side hard add does not win + assert not RH.driver_wins(False, True, 2.0, 1.0, 0.0, DT)[0] + assert RH.driver_wins(False, False, -2.0, 1.0, 0.0, DT)[0] # exit-side pull: at once + assert RH.driver_wins(True, False, 0.0, 1.0, 0.0, DT)[0] # held stalk, at once + assert not RH.driver_wins(False, True, 1.2, 1.0, 0.0, DT)[0] + + +def test_step_cap_rises_at_once_falls_slowly_and_is_bound_by_a_lat(): + e, cap = RH.step_cap(0.0, 0.002, 0.02, 7.0, A, 0.00035, 0.3, False, False) + assert (e, cap) == (pytest.approx(0.018), pytest.approx(0.02)) + e2, cap2 = RH.step_cap(e, 0.002, 0.002, 7.0, A, 0.00035, 0.3, False, False) + assert e - e2 == pytest.approx(0.3 * 0.00035) and cap2 > 0.002 # slow fall + assert RH.step_cap(e, 0.002, 0.002, 7.0, A, 0.00035, 0.3, True, False)[0] == pytest.approx(e - 0.00035) # plain: full slew + assert RH.step_cap(e, 0.002, 0.02, 7.0, A, 0.00035, 0.3, False, True) == (0.0, 0.002) # over the ring speed + assert RH.step_cap(0.0, 0.002, 0.2, 12.0, A, 0.00035, 0.3, False, False)[1] == pytest.approx(A / 144.0) + + +def test_latch_ready_earlier_at_the_ring_edge(): + assert RH.latch_ready(40.0, 0.5, 25.0) and not RH.latch_ready(50.0, 0.5, 25.0) and not RH.latch_ready(10.0, 1.5, 25.0) + assert RH.latch_ready(10.0, 0.5, 25.0) and RH.latch_ready(30.0, -2.0, 25.0) + + +# ---- guide ------------------------------------------------------------------------------------------------------ + +def test_cap_against_the_circle_when_the_model_is_flat_but_still_2_2_and_slew_bound(): + g = _guide(298.0) + assert g.latched + outs = _run(g, 150) + assert max(-o for o in outs) > 0.012 and all(o <= 0.0005 for o in outs[20:]) # left of the model's -0.002 by > 0.01 + assert all(-o * 49.0 <= A * 1.0001 for o in outs) # 2.2 m/s² at 7 m/s + assert all(abs(b - a) / DT <= RG.RING_SLEW + 1e-6 for a, b in zip(outs, outs[1:], strict=False)) + + +def test_exit_window_floor_keeps_the_circle_target_without_a_stalk_and_not_with_one(): + def run(exits, stalk=0): + g = _guide(298.0) + g.exits = exits # the car is ~15 deg before an exit at 330 deg (inside the 20 deg window) + return _run(g, 200, driver=RG.DriverInput(stalk_dir=stalk) if stalk else None, mk=0.004) # the model follows the exit branch (right) + inside, outside = run([330.0]), run([160.0]) + assert outside[-1] > -0.012 # no window: the widened cap only (<= model + CIRCLE_CAP_EXTRA) + assert inside[-1] < -0.02 and inside[-1] * 49.0 >= -RG.RING_A_LAT_MAX # in the window: up to the circle target, 2.2 m/s² at 7 m/s + assert all(abs(b - a) / DT <= 0.07 + 1e-6 for a, b in zip(inside, inside[1:], strict=False)) + assert run([330.0], stalk=2)[-1] == 0.004 # a right stalk pending: no floor, the model's way + + +def test_cw_ring_mirror_of_the_window_and_the_widening(): + s_c, s_m = 0.045, 0.0 + assert RH.widen_cap(0.0, s_m, s_c, 8.0, A) > 0.0 + # a CW ring (sense -1): window is on the other side of the exit angle + assert RH.in_exit_window(math.radians(160.0), -1.0, [150.0]) and not RH.in_exit_window(math.radians(140.0), -1.0, [150.0]) + + +def test_exit_blinker_releases_only_on_the_exit_arm_and_only_to_the_model(): + def blink(theta, off, stalk): + g = _guide(theta, off=off, mk=0.004) + _run(g, 20, mk=0.004) + return g, _run(g, 1, driver=RG.DriverInput(stalk_dir=stalk), mk=0.004, t0=0.5)[0] + g, out = blink(300.0, 3.0, 2) # at the outer edge of the band (d_edge ~ -3), 8 deg before the 308 exit + assert g.release == "exit_blinker" and g.phase == RG.DONE + assert out == 0.004 # the model at once, nothing else: it does not route the path onto the exit + g, out = blink(300.0, -2.5, 2) # mid band: a tip is not an exit + assert g.release == "" and g.phase == RG.ACTIVE and out != 0.004 + g, out = blink(300.0, 3.0, 1) # left blinker on the exit arm: nothing + assert g.release == "" and g.phase == RG.ACTIVE + g, out = blink(100.0, 3.0, 2) # far from every exit + assert g.release == "" + + +def test_latch_through_the_exit_window_without_release(): + g = _guide(298.0) + _run(g, 600, mk=0.004) + assert g.latched and g.phase == RG.ACTIVE and g.release == "" # held through the window: no map-only exit + + +def test_press_flicker_keeps_the_correction_but_a_held_press_and_hard_torque_still_win(): + g = _guide(298.0) + base = _run(g, 60) + g = _guide(298.0) + _run(g, 60 - 20) + flick = _run(g, 20, driver=RG.DriverInput(pressed=True), t0=0.6) # 0.2 s flicker + assert flick[-1] != -0.002 and g.dk_out != 0.0 and g.debug["w"] > 0.0 + after = _run(g, 20, t0=0.8) + assert abs(after[-1] - base[-1]) < 0.01 # the correction is still there + g = _guide(298.0) + _run(g, 60) + assert _run(g, 29, driver=RG.DriverInput(pressed=True), t0=0.8) and g.debug["w"] > 0.0 + still = _run(g, 10, driver=RG.DriverInput(pressed=True), t0=1.09) # 0.39 s: debounce does not drop the curl + assert still[-1] != -0.002 and g.debug["w"] > 0.0 and g.release == "" + held = _run(g, 60, driver=RG.DriverInput(pressed=True), t0=1.19) + assert held[-1] == -0.002 and g.release == "override" # 0.5 s zero-torque press still overrides + g = _guide(298.0) + _run(g, 60) + _run(g, 1, driver=RG.DriverInput(pressed=True, torque=-2.0), t0=0.8) + assert g.debug["w"] == 0.0 # exit-side >= 1.5 Nm: at once + g = _guide(298.0) + _run(g, 60) + same = _run(g, 60, driver=RG.DriverInput(pressed=True, torque=2.0), t0=0.8) # same-side add keeps the curl + assert same[-1] != -0.002 and g.release == "" and g.debug["w"] > 0.0 + g = _guide(298.0) + _run(g, 60) + light = _run(g, 60, driver=RG.DriverInput(pressed=True, torque=1.0), t0=0.8) # resting hand toward the circulation: ignored + assert light[-1] != -0.002 and g.release == "" + + +def test_early_latch_at_45_deg_alignment_and_not_beyond(): + for dpsi_deg, want in ((73.0, True), (90.0, False)): # 40 / 57 deg off the tangent (the pose heading is offset 33 deg at 298) + g = RG.RoundaboutGuide() + g.set_ring(RING) + th, r = math.radians(298.0), RING.radius_m + 0.5 + g.pose.bacc, g.bias, g.pose.initialized = 5.0, (0.3, 0.0), True + g.pose.xo, g.pose.yo, g.pose.psio, g.pose.dpsi = r * math.cos(th), r * math.sin(th), th + math.pi / 2 + math.radians(dpsi_deg), 0.0 + g.pose.t, g.pose.n_good, g.pose.innov, g.pose.last_fix_t = 0.0, 3, 0.5, 0.0 + g.phase = RG.ACTIVE + g.update(0.1, 7.0, 0.0, -0.002, enabled=True, lat_active=True) + assert g.latched == want, dpsi_deg + + +# ---- the failing pass ----------------------------------------------------------------------------------------- + +def _p13(slow=True): + from openpilot.selfdrive.controls.lib.tests.test_roundabout_guide import _LAST, simulate + rows, ring = simulate("0000013c", "after", pool=P13, slow=slow) + return rows, ring, _LAST["guide"] + + +def test_0000013c_holds_the_left_turn_at_the_ring_edge_in_band(): + from openpilot.selfdrive.controls.lib.tests.test_roundabout_guide import band_metrics + rows, ring, g = _p13() + assert g.latch_t is not None + assert band_metrics(rows, ring, 90.0) == (0.0, 100.0) + win = [r for r in rows if g.latch_t + 0.4 <= r[0] <= g.latch_t + 1.4] + assert win and all(r[6] < -0.0 for r in win) and min(r[6] for r in win) < -0.02 # left of the model (which reads ~0 / right) + assert sum(r[6] < r[5] - 0.005 for r in win) / len(win) > 0.9 + assert all(-r[6] * r[4] ** 2 <= RG.RING_A_LAT_MAX * 1.0001 for r in rows if r[0] >= g.latch_t) + post = [r for r in rows if r[0] >= g.latch_t] + slews = [min(abs((b[6] - b[5]) - (a[6] - a[5])), abs(b[6] - a[6])) / DT for a, b in zip(post, post[1:], strict=False)] + assert max(slews) <= RG.RING_SLEW + 1e-6 # 0.035 slew (correction or held output) + + +# ---- decel onset ------------------------------------------------------------------------------------------------ + +def test_decel_onset_is_a_named_constant_near_the_ring(): + assert RB_FUNNEL_M == 450.0 and 130.0 <= RB_DECEL_ONSET_M <= 140.0 # Oct 11: funnel = speed-based reach, low-speed onset 140 m + v0, v1 = 35 * 0.44704, 18 * 0.44704 + assert (v0 * v0 - v1 * v1) / (2.0 * RB_DECEL_ONSET_M) <= 0.7 # 35 -> 18 mph needs ~0.64 m/s² over 140 m (was 0.48 over 187 m) diff --git a/selfdrive/controls/lib/tests/test_stalk_tip_turn.py b/selfdrive/controls/lib/tests/test_stalk_tip_turn.py new file mode 100644 index 00000000000000..1d98fbdd1ec220 --- /dev/null +++ b/selfdrive/controls/lib/tests/test_stalk_tip_turn.py @@ -0,0 +1,115 @@ +from openpilot.selfdrive.controls.lib.stalk_tip_turn import ( + STALK_ALC_TURN_HOLD_S, + STALK_TIP_HOLD_S, + StalkTipTurn, +) + +DT_CTRL = 0.01 +DT_MDL = 0.05 + + +def _hold(s, stalk, t, dt): + n = int(round(t / dt)) + for _ in range(n): + s.update(stalk, dt) + + +def test_tip_hold_window_is_documented_040s(): + assert STALK_TIP_HOLD_S == 0.40 + + +def test_left_then_idle_within_window_is_tip(): + s = StalkTipTurn() + _hold(s, 1, 0.20, DT_CTRL) + assert s.is_pending + assert not s.is_turn + s.update(0, DT_CTRL) + assert s.tip_event + assert s.tip_direction == 1 + assert not s.is_turn + assert not s.is_pending + + +def test_right_then_idle_within_window_is_tip(): + s = StalkTipTurn() + s.update(2, DT_MDL) + s.update(0, DT_MDL) + assert s.tip_event + assert s.tip_direction == 2 + + +def test_held_past_window_is_turn_not_tip(): + s = StalkTipTurn() + _hold(s, 1, STALK_TIP_HOLD_S, DT_CTRL) + assert s.is_turn + assert not s.is_pending + s.update(0, DT_CTRL) + assert not s.tip_event + assert not s.is_turn + + +def test_boundary_just_under_window_is_still_tip(): + s = StalkTipTurn() + # 0.35s < 0.40s + _hold(s, 1, STALK_TIP_HOLD_S - 0.05, DT_CTRL) + assert not s.is_turn + s.update(0, DT_CTRL) + assert s.tip_event + + +def test_sna_is_idle(): + s = StalkTipTurn() + s.update(1, DT_CTRL) + s.update(3, DT_CTRL) + assert s.tip_event + assert s.direction == 0 + + +def test_model_rate_hold_crosses_window(): + s = StalkTipTurn() + n = int(round(STALK_TIP_HOLD_S / DT_MDL)) + for _ in range(n): + s.update(1, DT_MDL) + assert s.is_turn + + +def test_direction_change_restarts_hold(): + s = StalkTipTurn() + _hold(s, 1, 0.30, DT_CTRL) + assert not s.is_turn + s.update(2, DT_CTRL) + assert s.right_press + assert s.is_pending + assert not s.is_turn + assert s.held_s == DT_CTRL + + +def test_alc_turn_hold_window_is_documented_1s(): + assert STALK_ALC_TURN_HOLD_S == 1.0 + assert STALK_ALC_TURN_HOLD_S > STALK_TIP_HOLD_S + + +def test_held_past_tip_window_is_not_alc_turn_yet(): + s = StalkTipTurn() + _hold(s, 1, STALK_TIP_HOLD_S, DT_CTRL) + assert s.is_turn + assert not s.is_alc_turn + assert not s.is_driver_turn(alc_latched=True, alc_direction=1) + assert s.is_driver_turn(alc_latched=False) + + +def test_held_1s_is_alc_turn_same_direction(): + s = StalkTipTurn() + _hold(s, 1, STALK_ALC_TURN_HOLD_S, DT_CTRL) + assert s.is_alc_turn + assert s.is_driver_turn(alc_latched=True, alc_direction=1) + assert s.is_driver_turn(alc_latched=True, alc_direction=0) + + +def test_opposite_during_alc_uses_tip_window(): + s = StalkTipTurn() + _hold(s, 2, STALK_TIP_HOLD_S, DT_CTRL) + assert s.is_turn + assert not s.is_alc_turn + assert s.is_driver_turn(alc_latched=True, alc_direction=1) + assert not s.is_driver_turn(alc_latched=True, alc_direction=2) diff --git a/selfdrive/controls/lib/tests/test_vehicle_model.py b/selfdrive/controls/lib/tests/test_vehicle_model.py deleted file mode 100644 index b58bdbe522a441..00000000000000 --- a/selfdrive/controls/lib/tests/test_vehicle_model.py +++ /dev/null @@ -1,68 +0,0 @@ -import pytest -import math - -import numpy as np - -from opendbc.car.honda.interface import CarInterface -from opendbc.car.honda.values import CAR -from openpilot.selfdrive.car.card import convert_to_capnp -from openpilot.selfdrive.controls.lib.vehicle_model import VehicleModel, dyn_ss_sol, create_dyn_state_matrices - - -class TestVehicleModel: - def setup_method(self): - CP = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC) - self.VM = VehicleModel(convert_to_capnp(CP)) - - def test_round_trip_yaw_rate(self): - # TODO: fix VM to work at zero speed - for u in np.linspace(1, 30, num=10): - for roll in np.linspace(math.radians(-20), math.radians(20), num=11): - for sa in np.linspace(math.radians(-20), math.radians(20), num=11): - yr = self.VM.yaw_rate(sa, u, roll) - new_sa = self.VM.get_steer_from_yaw_rate(yr, u, roll) - - assert sa == pytest.approx(new_sa) - - def test_dyn_ss_sol_against_yaw_rate(self): - """Verify that the yaw_rate helper function matches the results - from the state space model.""" - - for roll in np.linspace(math.radians(-20), math.radians(20), num=11): - for u in np.linspace(1, 30, num=10): - for sa in np.linspace(math.radians(-20), math.radians(20), num=11): - - # Compute yaw rate based on state space model - _, yr1 = dyn_ss_sol(sa, u, roll, self.VM) - - # Compute yaw rate using direct computations - yr2 = self.VM.yaw_rate(sa, u, roll) - assert float(yr1[0]) == pytest.approx(yr2) - - def test_syn_ss_sol_simulate(self): - """Verifies that dyn_ss_sol matches a simulation""" - - for roll in np.linspace(math.radians(-20), math.radians(20), num=11): - for u in np.linspace(1, 30, num=10): - A, B = create_dyn_state_matrices(u, self.VM) - - # Convert to discrete time system - dt = 0.01 - top = np.hstack((A, B)) - full = np.vstack((top, np.zeros_like(top))) * dt - Md = sum([np.linalg.matrix_power(full, k) / math.factorial(k) for k in range(25)]) - Ad = Md[:A.shape[0], :A.shape[1]] - Bd = Md[:A.shape[0], A.shape[1]:] - - for sa in np.linspace(math.radians(-20), math.radians(20), num=11): - inp = np.array([[sa], [roll]]) - - # Simulate for 1 second - x1 = np.zeros((2, 1)) - for _ in range(100): - x1 = Ad @ x1 + Bd @ inp - - # Compute steady state solution directly - x2 = dyn_ss_sol(sa, u, roll, self.VM) - - np.testing.assert_almost_equal(x1, x2, decimal=3) diff --git a/selfdrive/controls/lib/unified_lead.py b/selfdrive/controls/lib/unified_lead.py new file mode 100644 index 00000000000000..c0c1cec67c5c97 --- /dev/null +++ b/selfdrive/controls/lib/unified_lead.py @@ -0,0 +1,1248 @@ +"""Continuous lead-follow controller. + +One equation replaces the stacked follow overrides when NAPLongUnified is on. +The planner still runs MPC. This module is a few arithmetic ops per frame. + + a_cmd = k_g·e + k_v(v_lead - v_ego) + k_a·a_lead, bounded by a_req + +e = gap - gap_set is one signed gap error. gap_set is the selected follow +gap (t_follow·v_lead + standstill). There is no separate inside-gap or +outside-gap formula: every term is a smooth function of e, so nothing steps +at the follow distance. + +The kinematic required decel + + a_req = -v_close² / (2·D(e)) + +is applied while closing (Sep 25 10:07:59 / 10:10:13). D(e) is the room to +match speed: outside the gap the gap error shortened with closing speed, +plus the part of the follow gap we may eat into (it fades in over the last +few seconds of approach and shrinks as e goes negative), minus a short +reaction distance. Slow closes give small values; a fast close from 60 m is +firm straight away; a small miss at the gap edge is not a -3.5 spike +(Sep 25 09:21:44). There is no far soft cap and no far comfort cap. + +A pulling-away lead near the gap gets a trickle, not a catch-up lunge +(Sep 25 09:47 / 10:54). Far from the gap, with speed already matched, the +proportional gap term would still demand a highway pull; that term fades +out between 15 and 50 m of slack and a soft desired closing speed +(about 0.10–0.95 m/s, matched command still under 0.15 m/s²) takes its +place. Braking, the near gap, and the follow distance are unchanged. Speed ceilings (MAX, curve) are a +speed-error term: never accelerate above the cap, and above it start +near the EV's mild -0.22 m/s² settle, firmer only when well over +(Sep 25 10:43:56). + +A lead is weighted by a continuous confidence: consistent, on-path, radar +or confident-vision readings ramp to full weight; a fast close ramps within +a fraction of a second; a one-frame blip barely moves the command. A new +lead (cut-in) ramps in the same way from the command already in force. + +A jerk limit slews the result. Build and release rates grow with how far +the command is from the target: fast when far too firm, gentle when close. + +Driver-likeness (Justin's fingerprint, Sep 20–27 qlogs): +- A lead that starts braking is anticipated: its filtered decel onset rate + extends a_lead ahead by up to 0.8 m/s², weighted continuously by how hard + it already brakes, how short the headway is, and how fast the decel builds. +- Mild lead slowing is mirrored under 1:1 (0.75×) so the ease stays gradual; + real braking is over-matched (1.10×). One smooth blend, no threshold. +- Inside the gap the glide keeps a small ease until the gap recovers. +- A far, slow close coasts: the closing gain fades with time-to-gap 12→30 s. +- A far, nearly matched gap eases in instead of k_g·slack. The desired + close is fast enough to finish a 100 m settle inside 240 s, and the + matched command stays under 0.15 m/s² so it does not pulse. + +How hard a lead may brake us depends on how much we trust it (Sep 28 +11:07:22, a half-lane-over lead 80–120 m ahead drove −3.5 for ~1 s). The +physical need a_need is the decel that stops the gap closing inside a +keep distance, lead braking-to-stop included. Lead-driven decel past +min(a_need·margin, −0.22) is scaled by a continuous trust: 1 for a close +or short-time-to-collision lead (every #222 / cut-in / rapid-close case), +falling to a fraction for a far, long-TTC lead, lower still when it sits +off our path or is a weak vision read. The same bound applies to the +command a new lead blends from, so a firmer inherited command is not +carried into an ambiguous far lead either. A far lead whose kinematics +really need full regen (stopped car at 100 m and 30 m/s) still gets it. +""" +from __future__ import annotations + +import math + +from openpilot.selfdrive.controls.lib.crossing_vehicle import X2_ROOM_FRAC, X2_V_LEAD_MS, CrossingFollow +from openpilot.selfdrive.controls.lib.lead_leaving import CLEAR_MARGIN_M, EGO_HALF_WIDTH_M, LEAD_HALF_WIDTH_M + +# Same standstill gap long_mpc uses for the follow obstacle. +STOP_DISTANCE_M = 6.0 + +# Hard plant bounds. Full regen is ACCEL_MIN. +A_MIN_MS2 = -3.5 +A_MAX_MS2 = 2.0 + +# Gap-error gain. Severity in [0, 1] interpolates low → high. +K_G_LO = 0.012 # 1/s² +K_G_HI = 0.030 +# Relative-speed gain while closing. Small closes land near mild regen. +K_V_LO = 0.16 # 1/s +K_V_HI = 0.10 # Large closes let a_lead and a_req own the depth. +# a_lead weight: 1 next to the gap, easing off when the lead is still far. +K_A_NEAR = 1.10 # slightly over 1: a closing ego must shed more than the lead brakes +K_A_FAR = 0.45 +K_A_NEAR_M = 18.0 +K_A_FAR_M = 70.0 +# Braking a_lead fades out when the lead is still far in both meters and +# time (15:56: ~83 m of slack, ~38 s to the gap, command was k_a·aLead). +# Full weight near the gap, on a short time-to-gap, or on a hard lead decel. +ALEAD_FADE_SLACK_LO_M = 20.0 +ALEAD_FADE_SLACK_HI_M = 55.0 +ALEAD_FADE_TTG_LO_S = 12.0 +ALEAD_FADE_TTG_HI_S = 30.0 +ALEAD_FADE_EMERG_LO_MS2 = 2.6 +ALEAD_FADE_EMERG_HI_MS2 = 3.4 +# The a_lead weight also grows with how hard the lead brakes: mild slowing is +# under-matched (a gradual, matched ease), real braking over-matched. +K_A_MILD = 0.75 +K_A_FIRM = 1.10 +K_A_FIRM_A0_MS2 = 0.30 +K_A_FIRM_BAND_MS2 = 0.50 +# Far, slow closes coast: the closing gain fades with time-to-gap. +K_V_FAR_TTG_LO_S = 12.0 +K_V_FAR_TTG_HI_S = 30.0 +K_V_FAR_MIN = 0.40 + +GAP_SEV_M = 16.0 +CLOSE_SEV_MS = 3.2 + +# Glide: nearly matched at the setpoint contributes nothing you can feel. +GLIDE_GAP_M = 3.5 +GLIDE_V_MS = 0.40 +GLIDE_KEEP = 0.90 # fraction of the gap/speed term removed at perfect glide +# Inside the gap the glide removes less, so a small ease persists until the +# gap recovers instead of holding speed a few meters too close. +GLIDE_KEEP_INSIDE = 0.60 + +# Kinematic room D(e): outside the gap the gap error shortened with closing +# speed (e / (1 + v/V0)); at and inside the setpoint a share of the follow +# gap is intrusion room that fades in over the last seconds of approach and +# shrinks one-for-one as e goes negative, down to a floor. Minus reaction. +ARRIVE_V0_MS = 8.0 # outside room = e / (1 + v_close / V0) +ARRIVE_SOFT_M = 2.0 +INSIDE_ALLOW_FRAC = 0.65 # of min(t_follow, cap)·v_lead +INSIDE_ALLOW_TF_MAX_S = 1.0 # follow time beyond ~1 s is reserve, not room +ALLOW_FADE_TTG_S = 4.0 # intrusion room fades in over the last seconds to the setpoint +ALLOW_FADE_V_MIN_MS = 0.3 +INSIDE_ALLOW_MIN_M = 3.0 +REACTION_S = 0.3 +KIN_ROOM_MIN_M = 1.5 +# Closing speed below this contributes no kinematic bound (fades in). +KIN_GATE_MS = 0.40 +# Far-gap widening of that gate (F3). A slow close at a far gap with the PD +# term wanting to accelerate made the gate flip the command between the PD +# and a near-zero kinematic bound (accCmd pulses at 15a 11:27, 159 08:03). +# While slack is past WIDEN_SLACK_LO_M (full weight at +WIDEN_SLACK_RAMP_M) +# and the bound is not a real brake (weight 1 at >= 0, 0 at <= WIDEN_A_BOUND_LO), +# the gate width grows with the PD accel, so the bound fades in over a wider +# closing speed. Never firmer than before; unchanged for a real bound +# (<= -0.10), a non-accelerating PD, or slack under 15 m. +KIN_GATE_WIDEN_SLACK_LO_M = 15.0 +KIN_GATE_WIDEN_SLACK_RAMP_M = 5.0 +KIN_GATE_WIDEN_A_BOUND_LO = -0.10 +KIN_GATE_WIDEN_A_BOUND_RAMP = 0.10 +KIN_GATE_WIDEN_A_CAP = 0.50 +KIN_GATE_WIDEN_K = 1.0 # 1/s: gate width = a_pd / K, capped at A_CAP / K + +# Far-gap soft closing speed. k_g·slack grows without bound, so a nearly +# matched lead 40–60 m out asks for +1.2…+1.8 m/s² and the kinematic gate +# bangs that into ~3 s catch-up pulses (15a 11:27). Fade the classic gap +# attraction from 15 → 50 m and replace the faded portion with a desired +# closing speed that saturates near 0.95 m/s. The fade finishes at 50 m, +# not 40: a Follow-7 recovery still has ~30 m of slack when it needs to +# come back, and ending the fade at 40 m left that catch-up too weak to +# finish inside 83.5 m. Past 50 m the highway matched case is fully soft. +# The blend is on only where the classic PD term would accelerate and the +# kinematic bound is not a real brake, so near-gap follow, #222, and +# braking stay on today's path. +GAP_FADE_LO_M = 15.0 +GAP_FADE_HI_M = 50.0 +V_DES_CLOSE_LO = 0.10 # m/s at the start of the fade +# The ramp still finishes 30 m above the fade floor, but the ceiling is +# 0.95 m/s rather than 0.35. A 0.35 m/s ease from a 100 m start is still +# inside the set gap at 240 s (Follow 2 landed 1.6 m short). The higher +# desired close gets every Follow setting through that settle in time. +# K_CATCH is lower so the matched command stays about +0.13, under the +# 0.15 soft cap: no highway pull, no gate pulses. +V_DES_CLOSE_SPAN = 0.85 # → 0.95 m/s once the ramp is done +V_DES_CLOSE_RAMP_M = 30.0 +K_CATCH = 0.14 # 1/s +GAP_CATCH_A_ON = 0.15 # classic a_pd at which the rewrite is full +GAP_CATCH_A_BOUND_LO = -0.10 # at or below this the bound is a real brake +GAP_CATCH_A_BOUND_RAMP = 0.10 + +# Short headway: pull firmer below ~0.6 s even at small closing. +SHORT_HW_S = 0.60 +SHORT_HW_BAND_S = 0.30 +SHORT_HW_A = 0.60 + +# Pulling away near the gap: positive command compresses to a trickle. +# The compression fades out once the slack is large (real catch-up). +TRICKLE_A = 0.12 +TRICKLE_SCALE = 0.15 +TRICKLE_FAR_LO_M = 25.0 +TRICKLE_FAR_HI_M = 60.0 +TRICKLE_IN_M = 6.0 +# Opening lead: the relative-speed gain is small near the gap and grows +# with slack, so a lead pulling away is not chased. +K_V_OPEN_NEAR = 0.07 +K_V_OPEN_FAR = 0.16 +OPEN_INSIDE_M = 6.0 # inside by this much: opening uses the closing gain + +# Speed ceiling (MAX, curve). Below the cap: a <= (v_cap - v)/tau (0 at cap). +# Above it: start at the EV mild settle, firmer only when well over. +SPEED_CEILING_TAU_S = 4.0 +OVERSPEED_SETTLE_MS2 = 0.22 +OVERSPEED_RAMP_MS = 0.45 +OVERSPEED_K = 0.12 # m/s² per m/s beyond the ramp +OVERSPEED_MAX_MS2 = 1.20 # soft saturation + +# Filters. One 50 ms blip moves a_lead by ~1/4 of the spike. +TAU_V_S = 0.20 +TAU_A_S = 0.15 + +# Slow-close comfort lives on the follow inputs, not a post-planner clamp. +# Closing speed and gap are low-passed. The old 6 m/s "rapid" line is a +# regime with enter/exit hysteresis and a dwell, so a noisy sample cannot +# flip the input source. The published command is never softer than the +# unfiltered law when physics still needs more than the EV mild settle. +APPROACH_TAU_CLOSE_S = 0.25 +APPROACH_TAU_GAP_S = 0.20 +APPROACH_RAPID_ENTER_MS = 6.0 +APPROACH_RAPID_EXIT_MS = 5.4 +APPROACH_RAPID_DWELL_S = 0.30 +APPROACH_COMFORT_CLOSE_MS = 3.0 +APPROACH_NEED_MARGIN_M = 2.0 +APPROACH_NEED_ROOM_MIN_M = 3.0 +APPROACH_MILD_MS2 = 0.22 +# A lead already braking this hard is not the slow-close comfort path +# (#222 stays on the unfiltered law). +APPROACH_BRAKE_A_MS2 = -0.35 + +# Faster cut-in that is still pulling away. Enter on a new lead id only. +# While latched the lead cannot cause decel (hold / coast; the existing +# trickle still caps a chase inside the follow window). MAX, curve, and +# map limits still apply. Handover is one-way. +CUTIN_PULL_ENTER_MS = 2.0 # v_lead - v_ego at acquire +CUTIN_CLOSE_MS = 0.3 # confirmed closing (ego faster than lead) +CUTIN_CLOSE_HOLD_S = 0.50 +CUTIN_PRED_T_S = 1.5 # lead will be slower than ego within this +CUTIN_PRED_HOLD_S = 0.30 +CUTIN_VREL_TAU_S = 0.30 +CUTIN_ALEAD_IGNORE_S = 0.75 +CUTIN_HARD_A_MS2 = -1.5 +CUTIN_HARD_FRAMES = 2 +CUTIN_PROJ_T_S = 3.0 +CUTIN_KEEP_M = 6.0 +CUTIN_KEEP_HW_S = 0.3 # keep = 6 m + 0.3 s * v_ego +CUTIN_HEADWAY_S = 0.4 + +# Lead-decel anticipation: a_eff = a_lead - min(MAX, T·max(0, -da_lead/dt)·w). +# w grows continuously with the lead's decel (A0/BAND), short headway +# (HW/HW_BAND) and the decel onset rate (J0/JBAND). A steady lead adds nothing. +LEAD_ANTICIPATE_T_S = 2.2 +LEAD_ANTICIPATE_MAX_MS2 = 0.80 +LEAD_JERK_TAU_S = 0.25 +LEAD_ANTICIPATE_A0_MS2 = 0.10 +LEAD_ANTICIPATE_ABAND_MS2 = 0.35 +LEAD_ANTICIPATE_HW_S = 2.5 +LEAD_ANTICIPATE_HW_BAND_S = 1.0 +LEAD_ANTICIPATE_J0_MS3 = 0.20 +LEAD_ANTICIPATE_JBAND_MS3 = 0.40 + +# Jerk. Rates grow with the distance between command and target. +JERK_RELEASE_MS3 = 0.45 +JERK_RELEASE_OPEN_MS3 = 1.35 +JERK_BUILD_MS3 = 1.15 +JERK_PHYS_MS3 = 2.50 +JERK_PROP_1_S = 2.0 # m/s³ extra per m/s² of error +UNIFIED_JERK_LIMIT_MS3 = JERK_PHYS_MS3 + +# Lead confidence. dw/dt = (R0 + R1·urgency·w)·(target - w) while rising. +CONF_RATE_BASE_1_S = 2.0 +CONF_RATE_URGENT_1_S = 14.0 +CONF_RATE_FALL_1_S = 4.0 +CONF_URGENT_LO_MS2 = 0.5 +CONF_URGENT_BAND_MS2 = 1.5 +CONF_VISION_MIN = 0.35 +# Kept for callers that referenced the old fixed cut-in blend. +CUTIN_S = 0.45 +# Toggle engage/disengage blend lives in the planner (~1 s). +MODE_BLEND_S = 1.0 + +# Static lateral fade from the predicted travel path. It starts only where +# a lead that is not moving sideways already clears our body: our half-width +# + its half-width + margin (lead_leaving). A stalled half-out lead keeps +# full weight. A lead that is *moving* out is released earlier, and only +# when its projection clears us at our arrival, by the planner's leaving +# weight (`leave_w`), combined with this fade below. +DEPART_Y0_M = EGO_HALF_WIDTH_M + LEAD_HALF_WIDTH_M + CLEAR_MARGIN_M +DEPART_Y1_M = DEPART_Y0_M + 0.7 + +# Achievable hard decel vs lead trust (Sep 28 11:07:22). A lead is remote +# when it is both far and a long time-to-collision away; a remote lead's +# trust tops out at TRUST_REMOTE and shrinks with lateral offset and a weak +# read. Decel past the physical need (with margin) is scaled by trust. +# The path-collapse gate does not cover this. It only blocks a *new* +# association while lane lines are down and the near path is absurd, and +# it leaves an already-followed lead alone. A far lead's rapid decel is +# a different path: the emergency a_lead restore below. That restore, and +# the lead-brake share of the kinematic floor, require the lead to sit on +# the predicted path. Close and short-TTC leads (#222) do not. +TRUST_RANGE_LO_M = 60.0 +TRUST_RANGE_HI_M = 110.0 +TRUST_TTC_LO_S = 4.0 +TRUST_TTC_HI_S = 8.0 +TRUST_REMOTE = 0.35 +TRUST_LAT_Y0_M = 0.9 # within our own half-width: fully on path +TRUST_LAT_MIN = 0.35 # at the static depart line +NEED_KEEP_TF_FRAC = 0.5 # keep distance: standstill + half the follow time +NEED_MARGIN = 1.25 +NEED_MILD_MS2 = 0.22 # an untrusted lead may always ease at the EV's mild settle + +# Far rapid-brake path. Full credit inside our own half-width. None once +# the lead is past a lane line (drifting out, adjacent lane, or a lateral +# ghost). Smooth between, so a noisy yRel does not step the command. +# The controller filters this offset; one frame cannot flip it. +RAPID_PATH_Y_IN_M = 0.9 +RAPID_PATH_Y_OUT_M = 1.8 +TAU_RAPID_PATH_S = 0.25 + + +def _smooth01(x: float) -> float: + """Smoothstep on [0, 1]. Constant outside. Value and slope match at the ends.""" + if x <= 0.0: + return 0.0 + if x >= 1.0: + return 1.0 + return x * x * (3.0 - 2.0 * x) + + +def _softplus(x: float, scale: float) -> float: + """Smooth max(x, 0). Equals x well above 0, 0 well below.""" + s = max(1e-6, float(scale)) + z = float(x) / s + if z > 30.0: + return float(x) + return s * math.log1p(math.exp(z)) + + +def _filt(prev: float | None, sample: float, dt: float, tau: float) -> float: + if prev is None or tau <= 1e-4: + return float(sample) + a = float(dt) / (float(tau) + float(dt)) + return float(prev) + a * (float(sample) - float(prev)) + + +def gap_set_m(v_lead: float, t_follow: float) -> float: + """Selected follow gap, including standstill distance.""" + return float(t_follow) * max(0.0, float(v_lead)) + STOP_DISTANCE_M + + +def _severity(slack: float, v_err: float) -> float: + g = float(slack) / GAP_SEV_M + v = float(v_err) / CLOSE_SEV_MS + return 1.0 - math.exp(-(g * g) - (v * v)) + + +def _k_a(slack: float) -> float: + t = _smooth01((max(float(slack), 0.0) - K_A_NEAR_M) / max(1e-3, K_A_FAR_M - K_A_NEAR_M)) + return K_A_NEAR + (K_A_FAR - K_A_NEAR) * t + + +def _k_a_brake_scale(a_lead: float) -> float: + """0.75× for mild lead slowing, 1.10× for real braking, smooth in between.""" + t = _smooth01((-float(a_lead) - K_A_FIRM_A0_MS2) / K_A_FIRM_BAND_MS2) + return K_A_MILD + (K_A_FIRM - K_A_MILD) * t + + +def rapid_path_offset_m(y_rel: float, curvature: float, gap: float, + path_lat: float | None = None) -> float: + """Lateral distance from the predicted path, in meters. + + `path_lat` wins: a lead in a bend stays on-path even when raw yRel is + large, and an adjacent-lane car at yRel ≈ 0 does not. Without a path, + curve geometry is taken back out of yRel. A missing reading is 0, which + is on-path — do not invent an off-path block. + """ + if path_lat is not None and math.isfinite(float(path_lat)): + return abs(float(path_lat)) + try: + y = abs(float(y_rel)) + except (TypeError, ValueError): + return 0.0 + if not math.isfinite(y): + return 0.0 + lane = abs(0.5 * float(curvature) * float(gap) * float(gap)) + return max(0.0, y - lane) + + +def rapid_path_credit(y_abs: float) -> float: + """1 on the predicted path, 0 once the lead has left it.""" + if not math.isfinite(float(y_abs)): + return 1.0 + span = max(1e-3, RAPID_PATH_Y_OUT_M - RAPID_PATH_Y_IN_M) + return 1.0 - _smooth01((float(y_abs) - RAPID_PATH_Y_IN_M) / span) + + +def _braking_alead_weight(slack: float, v_close: float, a_lead: float, + path_credit: float = 1.0) -> float: + """How much of a braking lead to copy, in [0, 1]. + + 0 when there is a lot of slack and a long time to the gap, and the lead + is not braking hard. 1 near the gap, on a short time-to-gap, or when the + lead decel is emergency-sized. The emergency restore is the far + rapid-brake path: it is scaled by path credit, so a far lead that is + drifting out, off the predicted path, or a lateral ghost does not firm + ego braking. A close or short-TTC lead ignores that credit. Positive + a_lead is not scaled here. + """ + if float(a_lead) >= 0.0: + return 1.0 + slack_f = float(slack) + near = 1.0 - _smooth01( + (slack_f - ALEAD_FADE_SLACK_LO_M) / (ALEAD_FADE_SLACK_HI_M - ALEAD_FADE_SLACK_LO_M)) + if slack_f <= 0.0: + short = 1.0 + else: + ttg = slack_f / max(float(v_close), 0.3) + short = 1.0 - _smooth01( + (ttg - ALEAD_FADE_TTG_LO_S) / (ALEAD_FADE_TTG_HI_S - ALEAD_FADE_TTG_LO_S)) + credit = 1.0 if path_credit is None or not math.isfinite(float(path_credit)) else min( + 1.0, max(0.0, float(path_credit))) + emerg = _smooth01( + (-float(a_lead) - ALEAD_FADE_EMERG_LO_MS2) / (ALEAD_FADE_EMERG_HI_MS2 - ALEAD_FADE_EMERG_LO_MS2)) + emerg *= credit + return 1.0 - (1.0 - near) * (1.0 - short) * (1.0 - emerg) + + +def credited_rapid_lead(a_lead: float, slack: float, v_close: float, + path_credit: float) -> float: + """Lead accel the kinematic floor may treat as a real in-path stop. + + Near the gap or on a short time-to-gap the whole decel counts (#222). + A far rapid decel counts only in proportion to path credit. Off-path, + that decel does not deepen the floor, so an inherited firm command is + not justified by a lead that is leaving or a radar ghost. + """ + a = float(a_lead) + if a >= 0.0: + return a + base = _braking_alead_weight(slack, v_close, a, path_credit=0.0) + credit = 0.0 if path_credit is None or not math.isfinite(float(path_credit)) else min( + 1.0, max(0.0, float(path_credit))) + keep = base + (1.0 - base) * credit + return a * keep + + +def lead_decel_anticipation(a_lead: float, lead_jerk: float, gap: float, v_ego: float) -> float: + """Extra decel (>= 0) ahead of a lead whose braking is still building. + + Continuous in every input: 0 for a steady or recovering lead, growing with + how hard the lead already brakes, how short the headway is, and how fast + its decel builds. Capped so a gradual slowdown cannot become a wall. + """ + building = max(0.0, -float(lead_jerk)) + if building <= 0.0: + return 0.0 + hw = float(gap) / max(float(v_ego), 1.0) + w = _smooth01((-float(a_lead) - LEAD_ANTICIPATE_A0_MS2) / LEAD_ANTICIPATE_ABAND_MS2) + w *= _smooth01((LEAD_ANTICIPATE_HW_S - hw) / LEAD_ANTICIPATE_HW_BAND_S) + w *= _smooth01((building - LEAD_ANTICIPATE_J0_MS3) / LEAD_ANTICIPATE_JBAND_MS3) + return min(LEAD_ANTICIPATE_MAX_MS2, LEAD_ANTICIPATE_T_S * building * w) + + +def _glide(slack: float, v_err: float, a_lead: float) -> float: + """1 when matched and the lead is not braking. A real lead brake kills it.""" + g = math.exp(-((float(slack) / GLIDE_GAP_M) ** 2) - ((float(v_err) / GLIDE_V_MS) ** 2)) + brake = min(float(a_lead), 0.0) + g *= math.exp(-((brake / 0.30) ** 2)) + return g + + +def kinematic_room_m(slack: float, v_close: float, t_follow: float, v_lead: float) -> float: + """Room to match speed. One smooth function of the signed gap error. + + Outside the gap the room is the gap error itself, shortened as the + closing speed grows (plan to be matched earlier on a fast close). At and + inside the setpoint part of the follow gap is usable intrusion room; it + fades in across the last few meters of approach and shrinks one-for-one + as the gap error goes negative, down to a floor. + """ + e = float(slack) + v = max(0.0, float(v_close)) + outside = _softplus(e, ARRIVE_SOFT_M) / (1.0 + v / ARRIVE_V0_MS) + tf_room = min(float(t_follow), INSIDE_ALLOW_TF_MAX_S) + allow = max(INSIDE_ALLOW_MIN_M, INSIDE_ALLOW_FRAC * tf_room * max(0.0, float(v_lead))) + # min(e, 0) has a kink at 0 but its value is continuous. + inside = _softplus(allow + min(e, 0.0) - INSIDE_ALLOW_MIN_M, 1.0) + INSIDE_ALLOW_MIN_M + # The intrusion room fades in over the last ALLOW_FADE_TTG_S of approach + # (time to reach the setpoint at the current closing speed). + ttg = e / max(v, ALLOW_FADE_V_MIN_MS) + inside *= 1.0 - _smooth01(ttg / ALLOW_FADE_TTG_S) + room = outside + inside - REACTION_S * v + room = max(KIN_ROOM_MIN_M, room) + # Stopped or creeping lead: do not shorten the room below three quarters + # of the gap past the standstill keep. A fast close was matching far too + # early (118 m at 13 m/s asked for about −2 against a −0.8 need). Moving + # leads, including every #222 case, skip this. + if 0.0 <= float(v_lead) < X2_V_LEAD_MS and e > 0.0: + room = max(room, X2_ROOM_FRAC * e) + return room + + +def kinematic_required_accel(slack: float, v_close: float, t_follow: float, v_lead: float) -> float: + """a_req = -v_close² / (2·D). 0 when not closing.""" + v = max(0.0, float(v_close)) + if v <= 0.0: + return 0.0 + room = kinematic_room_m(slack, v, t_follow, v_lead) + return max(A_MIN_MS2, -(v * v) / (2.0 * room)) + + +def _a_kin(slack: float, v_close: float, gap: float, v_ego: float, + t_follow: float, v_lead: float) -> float: + """Kinematic bound used by the build-rate choice. Same term as the command.""" + _ = gap, v_ego + return kinematic_required_accel(slack, v_close, t_follow, v_lead) + + +def _short_headway(gap: float, v_ego: float, v_close: float) -> float: + """Firmer pull below ~0.6 s headway unless the lead is pulling away.""" + hw = float(gap) / max(float(v_ego), 1.0) + w = _smooth01((SHORT_HW_S - hw) / SHORT_HW_BAND_S) + if w <= 0.0: + return 0.0 + closing_w = _smooth01((float(v_close) + 0.5) / 1.0) + return -SHORT_HW_A * w * closing_w + + +def _depart_fade(y_rel: float, curvature: float, gap: float, + path_lat: float | None = None) -> float: + """0 on the travel path, 1 when the lead has left it. + + `path_lat` is the lateral offset from the model's predicted path at the + lead's distance, so a lead in a bend stays on-path and an adjacent-lane + car is off-path. Without a path, the curve geometry is removed from yRel. + """ + if path_lat is not None and math.isfinite(float(path_lat)): + y = abs(float(path_lat)) + else: + lane = abs(0.5 * float(curvature) * float(gap) * float(gap)) + y = max(0.0, abs(float(y_rel)) - lane) + return _smooth01((y - DEPART_Y0_M) / max(1e-3, DEPART_Y1_M - DEPART_Y0_M)) + + +def _leave_fade(y_rel: float, curvature: float, gap: float, + path_lat: float | None = None, leave_w: float = 0.0) -> float: + """Static off-path fade combined with the planner's leaving weight.""" + static = _depart_fade(y_rel, curvature, gap, path_lat) + w = 0.0 if leave_w is None or not math.isfinite(float(leave_w)) else min(1.0, max(0.0, float(leave_w))) + return 1.0 - (1.0 - static) * (1.0 - w) + + +def kinematic_need_accel(gap: float, v_ego: float, v_lead: float, a_lead: float, + t_follow: float) -> float: + """Physical decel (<= 0) that keeps the gap above a keep distance. + + Constant-accel lead, braking to a stop if a_lead < 0. If our speed can + match the lead's before it stops, a = a_lead - v_close²/(2·room); + otherwise we stop behind where it stops. The two agree at the boundary. + """ + g = max(0.0, float(gap)) + v_e = max(0.0, float(v_ego)) + v_l = max(0.0, float(v_lead)) + a_l = min(0.0, float(a_lead)) + keep = STOP_DISTANCE_M + NEED_KEEP_TF_FRAC * max(0.0, float(t_follow)) * v_l + room = g - keep + if room <= KIN_ROOM_MIN_M: + return A_MIN_MS2 if v_e > v_l or a_l < 0.0 else min(0.0, a_l) + v_close = max(0.0, v_e - v_l) + a_match = a_l - (v_close * v_close) / (2.0 * room) + if a_l < 0.0: + t_match = 2.0 * room / max(v_close, 1e-3) + t_stop = v_l / -a_l + if t_match > t_stop: + a_match = -(v_e * v_e) / (2.0 * (room + (v_l * v_l) / (2.0 * -a_l))) + return max(A_MIN_MS2, min(0.0, a_match)) + + +def lead_trust(gap: float, v_ego: float, v_lead: float, y_rel: float = 0.0, + curvature: float = 0.0, path_lat: float | None = None, + model_prob: float | None = None, radar: bool | None = None) -> float: + """How much hard braking this lead may command, in [0, 1]. + + 1 for a close or short-TTC lead. A remote lead (far AND long TTC) keeps + TRUST_REMOTE, scaled by how on-path and how good the reading is. + """ + g = max(0.0, float(gap)) + v_close = max(0.0, float(v_ego) - max(0.0, float(v_lead))) + ttc = g / max(v_close, 0.1) + far = _smooth01((g - TRUST_RANGE_LO_M) / (TRUST_RANGE_HI_M - TRUST_RANGE_LO_M)) + slow = _smooth01((ttc - TRUST_TTC_LO_S) / (TRUST_TTC_HI_S - TRUST_TTC_LO_S)) + remote = far * slow + if remote <= 0.0: + return 1.0 + if path_lat is not None and math.isfinite(float(path_lat)): + y = abs(float(path_lat)) + else: + lane = abs(0.5 * float(curvature) * g * g) + y = max(0.0, abs(float(y_rel)) - lane) + lat_w = 1.0 - (1.0 - TRUST_LAT_MIN) * _smooth01((y - TRUST_LAT_Y0_M) / (DEPART_Y0_M - TRUST_LAT_Y0_M)) + q = lead_quality(model_prob, radar) + return 1.0 - remote * (1.0 - TRUST_REMOTE * lat_w * q) + + +def hard_decel_floor(gap: float, v_ego: float, v_lead: float, a_lead: float, + t_follow: float) -> float: + """Firmest decel an untrusted lead may command: the need with margin, or mild.""" + need = kinematic_need_accel(gap, v_ego, v_lead, a_lead, t_follow) + return max(A_MIN_MS2, min(-NEED_MILD_MS2, NEED_MARGIN * need)) + + +def trust_bound(a: float, floor: float, trust: float) -> float: + """Decel past `floor` scaled by trust. Continuous; identity at trust 1.""" + a = float(a) + if a >= floor: + return a + return float(floor) + min(1.0, max(0.0, float(trust))) * (a - float(floor)) + + +def speed_ceiling_accel(v_ego: float, v_cap: float) -> float: + """Speed-error term for MAX / curve caps. + + Below the cap it only limits acceleration (0 at the cap). Above it the + decel starts at the mild settle and grows with overspeed, saturating + softly well short of full regen. + """ + over = float(v_ego) - float(v_cap) + if over <= 0.0: + return -over / SPEED_CEILING_TAU_S + mild = OVERSPEED_SETTLE_MS2 * _smooth01(over / OVERSPEED_RAMP_MS) + extra = OVERSPEED_K * max(0.0, over - OVERSPEED_RAMP_MS) + raw = mild + extra + return -OVERSPEED_MAX_MS2 * math.tanh(raw / OVERSPEED_MAX_MS2) + + +def _kin_gate_widen(slack: float, a_pd: float, a_bound: float) -> float: + """Extra kinematic-gate width (m/s) at a far gap while the PD term accelerates.""" + # a_pd <= 0 (not accelerating) never clears the base width: wide < 0. + wide = min(a_pd, KIN_GATE_WIDEN_A_CAP) / KIN_GATE_WIDEN_K - KIN_GATE_MS + if wide <= 0.0: + return 0.0 + w_slack = _smooth01((slack - KIN_GATE_WIDEN_SLACK_LO_M) / KIN_GATE_WIDEN_SLACK_RAMP_M) + w_bound = _smooth01((a_bound - KIN_GATE_WIDEN_A_BOUND_LO) / KIN_GATE_WIDEN_A_BOUND_RAMP) + return wide * w_slack * w_bound + + +def _far_gap_catchup_gap(a_gap_classic: float, slack: float, v_err: float, keep: float, + a_pd_classic: float, a_bound: float) -> float: + """Gap term with the far positive catch-up replaced by a soft closing speed. + + Classic k_g·slack below GAP_FADE_LO_M. Above that, and only while the + classic PD term is a catch-up and the kinematic bound is not a real + brake, blend toward K_CATCH·(v_des + v_err). v_des rises from 0.10 to + 0.95 m/s. A negative soft term is clipped, so closing faster than v_des + does not add gap braking. The blend never exceeds the classic gap term. + """ + w_slack = _smooth01((slack - GAP_FADE_LO_M) / (GAP_FADE_HI_M - GAP_FADE_LO_M)) + w_accel = _smooth01(a_pd_classic / GAP_CATCH_A_ON) + w_bound = _smooth01((a_bound - GAP_CATCH_A_BOUND_LO) / GAP_CATCH_A_BOUND_RAMP) + w = w_slack * w_accel * w_bound + v_des_close = V_DES_CLOSE_LO + V_DES_CLOSE_SPAN * _smooth01( + (slack - GAP_FADE_LO_M) / V_DES_CLOSE_RAMP_M) + a_soft = K_CATCH * (v_des_close + v_err) * keep + # min keeps a lead that is already faster from getting a harder gap pull + # than classic: a_soft includes v_err, which can exceed k_g·slack. + a_gap = (1.0 - w) * a_gap_classic + w * max(0.0, a_soft) + return min(a_gap, a_gap_classic) + + +def unified_follow_desired(gap: float, v_ego: float, v_lead: float, a_lead: float, + t_follow: float, *, v_ceiling: float | None = None, + a_map: float | None = None, y_rel: float = 0.0, + curvature: float = 0.0, + path_lat: float | None = None, + leave_w: float = 0.0, + model_prob: float | None = None, + radar: bool | None = None, + gap_set_override_m: float | None = None, + v_curve_cap: float | None = None, + rapid_path_w: float | None = None) -> float: + """Unslewed follow accel from filtered lead signals. Continuous in its inputs. + + `gap_set_override_m` replaces only the meter setpoint used for slack + (gap lock). `t_follow` still sizes intrusion room, trust, and FCW. + A lock is still this law: the near-gap "do not chase" opening gain, + the positive-accel trickle, and the far soft-close are skipped so a + speed deficit left by the pre-lock ease tracks the locked meters + instead of opening the gap and creeping back. Cruise MAX is not applied + while the lock is the setpoint, so the car may go above MAX to hold + those meters. `v_curve_cap` still slows the car for a bend. + """ + gap_f = max(0.0, float(gap)) + v_l = max(0.0, float(v_lead)) + v_e = max(0.0, float(v_ego)) + a_l = float(a_lead) + gap_set = gap_set_m(v_l, t_follow) + if gap_set_override_m is not None: + gap_set = float(gap_set_override_m) + slack = gap_f - gap_set + v_err = v_l - v_e # lead faster is positive, matching k_v(v_lead - v_ego) + v_close = max(0.0, -v_err) + + sev = _severity(slack, v_err) + k_g = K_G_LO + (K_G_HI - K_G_LO) * sev + # High severity uses the smaller velocity gain (K_V_HI < K_V_LO). + k_v_close = K_V_LO + (K_V_HI - K_V_LO) * sev + locked = gap_set_override_m is not None + if locked: + # Closing gain on both sides, and not the small near-gap opening + # gain. A leftover speed deficit has to fold back onto the locked + # meters in a few seconds. 0.40 /s is a 1 m/s miss at 0.40 m/s², + # still well under the follow ceiling. + k_v = max(k_v_close, 0.40) + else: + # A far, slow close coasts: the closing gain fades with time-to-gap. + ttg_far = slack / max(v_close, 0.3) + k_v_close *= 1.0 - (1.0 - K_V_FAR_MIN) * _smooth01( + (ttg_far - K_V_FAR_TTG_LO_S) / max(1e-3, K_V_FAR_TTG_HI_S - K_V_FAR_TTG_LO_S)) + # Opening: small gain at/over the setpoint (a lead pulling away is not + # chased), growing with slack. Inside the gap the opening speed keeps the + # closing gain so braking unwinds as soon as the gap starts recovering. + open_far = _smooth01((slack - 5.0) / 30.0) + k_v_open = K_V_OPEN_NEAR + (K_V_OPEN_FAR - K_V_OPEN_NEAR) * open_far + inside_w = _smooth01(-slack / OPEN_INSIDE_M) + k_v_open = inside_w * k_v_close + (1.0 - inside_w) * k_v_open + # Blend the two across v_err = 0 so the gain has no step. + side = _smooth01((v_err + 0.3) / 0.6) + k_v = (1.0 - side) * k_v_close + side * k_v_open + k_a = _k_a(slack) * _k_a_brake_scale(a_l) + glide = _glide(slack, v_err, a_l) + glide_keep = GLIDE_KEEP + (GLIDE_KEEP_INSIDE - GLIDE_KEEP) * _smooth01(-slack / GLIDE_GAP_M) + keep = 1.0 - glide_keep * glide + a_gv = (k_g * slack + k_v * v_err) * keep + a_gv += _short_headway(gap_f, v_e, v_close) + a_pd = a_gv + k_a * a_l + + a_kin = _a_kin(slack, v_close, gap_f, v_e, t_follow, v_l) + # Braking-lead contribution on the bound. Positive a_lead stays in a_pd only. + a_bound = a_kin + min(a_l, 0.0) * k_a + # Command copy. Far slack and a long time-to-gap drop a mild or mid lead + # brake. a_pd and a_bound stay unfaded: catch-up and the kinematic gate + # still see a real lead brake, so they do not open just because the + # command stopped copying it. Near the gap, a short time-to-gap, or an + # emergency lead decel keeps the full term on the command too. + if rapid_path_w is None: + path_credit = rapid_path_credit(rapid_path_offset_m(y_rel, curvature, gap_f, path_lat)) + elif not math.isfinite(float(rapid_path_w)): + path_credit = 1.0 + else: + path_credit = min(1.0, max(0.0, float(rapid_path_w))) + # Far rapid decel is copied only while the lead is on the predicted path. + # Near / short-TTC weight does not read path_credit. + brake_w = _braking_alead_weight(slack, v_close, a_l, path_credit) + if a_l < 0.0 and brake_w < 1.0: + a_pd_cmd = a_gv + k_a * a_l * brake_w + a_bound_cmd = a_kin + a_l * k_a * brake_w + else: + a_pd_cmd = a_pd + a_bound_cmd = a_bound + # Swap only the command's gap piece. The gate below still reads a_pd. + a_gap_classic = (k_g * slack) * keep + if not locked: + a_gap = _far_gap_catchup_gap(a_gap_classic, slack, v_err, keep, a_pd, a_bound) + a_pd_cmd = a_pd_cmd + (a_gap - a_gap_classic) + gate_w = KIN_GATE_MS + _kin_gate_widen(slack, a_pd, a_bound) + gate = _smooth01(v_close / gate_w) if v_close > 0.0 else 0.0 + limited = min(a_pd_cmd, a_bound_cmd) + a_cmd = ((1.0 - gate) * a_pd_cmd) + (gate * limited) + + # Pulling away near the gap: trickle, not a catch-up lunge. + # A locked setpoint is the distance the driver asked to hold, so a + # positive error is not trickled down to the 0.12 m/s² cap. + if a_cmd > 0.0 and not locked: + # Compression weight rises across the setpoint (recovering from inside + # is not compressed) and fades once the slack is a real catch-up. + far = _smooth01((slack - TRICKLE_FAR_LO_M) / (TRICKLE_FAR_HI_M - TRICKLE_FAR_LO_M)) + w = _smooth01((slack + TRICKLE_IN_M) / TRICKLE_IN_M) * (1.0 - far) + trickle = TRICKLE_A * math.tanh(a_cmd / TRICKLE_SCALE) + a_cmd = w * min(a_cmd, trickle) + (1.0 - w) * a_cmd + + # Off-path / leaving lead: its command (brake included) fades toward 0. + # Curve still applies below. MAX applies only when the gap is not locked. + fade = _leave_fade(y_rel, curvature, gap_f, path_lat, leave_w) + if fade > 0.0: + a_cmd *= (1.0 - fade) + + # Achievable hard decel follows trust: a remote, off-path, or weak lead + # cannot brake us past what its kinematics need (Sep 28 11:07:22). + trust = lead_trust(gap_f, v_e, v_l, y_rel, curvature, path_lat, model_prob, radar) + # Floor only. The command above already used the unscaled lead accel. + # Off-path far rapid decel must not keep a deep floor that re-firms the blend. + a_l = credited_rapid_lead(a_l, slack, v_close, path_credit) + a_cmd = trust_bound(a_cmd, hard_decel_floor(gap_f, v_e, v_l, a_l, t_follow), trust) + + # A locked gap is the driver's setpoint. MAX does not hold it back. + # A curve cap, when the planner passes one, still does. + if (not locked) and v_ceiling is not None and float(v_ceiling) > 0.5: + a_cmd = min(a_cmd, speed_ceiling_accel(v_e, float(v_ceiling))) + if v_curve_cap is not None and float(v_curve_cap) > 0.5: + a_cmd = min(a_cmd, speed_ceiling_accel(v_e, float(v_curve_cap))) + if a_map is not None: + a_cmd = min(a_cmd, float(a_map)) + if a_cmd < A_MIN_MS2: + a_cmd = A_MIN_MS2 + elif a_cmd > A_MAX_MS2: + a_cmd = A_MAX_MS2 + return a_cmd + + +def lead_quality(model_prob: float | None = None, radar: bool | None = None) -> float: + """Per-frame reading quality in [0, 1]. Radar-associated reads full. + + Vision-only reads scale with model probability, never below a floor so + a real vision lead still owns the command after it has been consistent. + """ + if radar is True or model_prob is None: + return 1.0 + p = float(model_prob) + if not math.isfinite(p): + return 1.0 + return max(CONF_VISION_MIN, min(1.0, p / 0.6)) + + +def _limit_jerk(prev: float, target: float, dt: float, *, down: float, up: float) -> float: + delta = float(target) - float(prev) + if delta > up: + return float(prev) + up + if delta < -down: + return float(prev) - down + return float(target) + + +def approach_physics_need(gap: float, v_ego: float, v_lead: float, t_follow: float) -> float: + """Decel (<= 0) that stops the close before eating the margin. + + v_close² / (2 · max(slack − margin, room floor)). 0 when not closing. + Comfort may not publish a softer command than this when it is firmer + than the EV mild settle. + """ + slack = float(gap) - gap_set_m(v_lead, t_follow) + v_close = max(0.0, float(v_ego) - float(v_lead)) + if v_close <= 0.0: + return 0.0 + room = max(slack - APPROACH_NEED_MARGIN_M, APPROACH_NEED_ROOM_MIN_M) + return max(A_MIN_MS2, -(v_close * v_close) / (2.0 * room)) + + +def lead_free_accel(v_ego: float, v_ceiling: float | None, a_map: float | None, + v_curve_cap: float | None) -> float: + """Accel with no lead: hold speed, unless MAX, curve, or map brakes. + + Under a speed cap the ceiling term is positive (accel is allowed). The + cut-in hold mins this with the trickled follow command, so a lead that + is pulling away is not chased inside the follow window. + """ + a = A_MAX_MS2 + limited = False + if v_ceiling is not None and float(v_ceiling) > 0.5: + a = min(a, speed_ceiling_accel(float(v_ego), float(v_ceiling))) + limited = True + if v_curve_cap is not None and float(v_curve_cap) > 0.5: + a = min(a, speed_ceiling_accel(float(v_ego), float(v_curve_cap))) + limited = True + if a_map is not None: + a = min(a, float(a_map)) + limited = True + if not limited: + return 0.0 + return float(a) + + +def projected_gap_m(gap: float, v_ego: float, v_lead: float, a_lead: float, + horizon: float = CUTIN_PROJ_T_S) -> float: + """Minimum gap over the next `horizon` seconds at the lead's decel. + + A positive lead accel is not credited: the lead is not assumed to pull + away harder than it is pulling away now. With non-positive lead accel + the gap parabola opens downward, so the minimum on the window is at an + endpoint. + """ + a = min(0.0, float(a_lead)) + v = float(v_lead) - float(v_ego) + g0 = max(0.0, float(gap)) + g1 = g0 + v * float(horizon) + 0.5 * a * float(horizon) * float(horizon) + return min(g0, g1) + + +class ApproachInputs: + """Low-pass and hysteresis on the slow-close follow inputs. + + Closing speed and gap are filtered. Crossing the old 6 m/s rapid line + takes a dwell, and the exit is lower than the enter, so one noisy + sample cannot flip the regime. `use_comfort` is the slow, non-braking + close: that is where the filtered gap and closing speed replace the + raw sample. A braking lead and a confirmed rapid close stay on the + unfiltered law (#222, fast dump). + """ + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self.gap_f: float | None = None + self.v_close_f: float | None = None + self.rapid = False + self._enter_s = 0.0 + self._exit_s = 0.0 + + def update(self, gap: float, v_ego: float, v_lead: float, dt: float) -> None: + frame = 0.05 if dt is None or float(dt) <= 1e-6 else float(dt) + v_close = float(v_ego) - float(v_lead) + first = self.v_close_f is None + self.gap_f = _filt(self.gap_f, float(gap), frame, APPROACH_TAU_GAP_S) + self.v_close_f = _filt(self.v_close_f, v_close, frame, APPROACH_TAU_CLOSE_S) + if first: + # An obvious rapid close is rapid on the first sample. The dwell + # is for the boundary, not for a 13 m/s acquire. + self.rapid = v_close >= APPROACH_RAPID_ENTER_MS + self._enter_s = 0.0 + self._exit_s = 0.0 + return + if not self.rapid: + if v_close >= APPROACH_RAPID_ENTER_MS: + self._enter_s += frame + if self._enter_s + 1e-9 >= APPROACH_RAPID_DWELL_S: + self.rapid = True + self._enter_s = 0.0 + else: + self._enter_s = 0.0 + self._exit_s = 0.0 + else: + if v_close <= APPROACH_RAPID_EXIT_MS: + self._exit_s += frame + if self._exit_s + 1e-9 >= APPROACH_RAPID_DWELL_S: + self.rapid = False + self._exit_s = 0.0 + else: + self._exit_s = 0.0 + self._enter_s = 0.0 + + def use_comfort(self, a_lead: float) -> bool: + """True when the filtered inputs should feed the follow law.""" + if float(a_lead) <= APPROACH_BRAKE_A_MS2: + return False + if self.rapid or self.v_close_f is None: + return False + return float(self.v_close_f) >= APPROACH_COMFORT_CLOSE_MS + + +class UnifiedLeadController: + """Stateful filters, lead confidence, and jerk limit around unified_follow_desired.""" + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self._v_f: float | None = None + self._a_f: float | None = None + self._lead_jerk = 0.0 + self._prev: float | None = None + self._lead_id = None + self._conf = 1.0 + self._cutin_from = 0.0 + self.last_desired = 0.0 + self.last_v_lead = 0.0 + self.last_a_lead = 0.0 + self.last_a_lead_eff = 0.0 + self.last_confidence = 0.0 + self.last_trust = 1.0 + self.last_floor = A_MIN_MS2 + self._rapid_y: float | None = None + self.last_rapid_path_credit = 1.0 + self._approach = ApproachInputs() + self._cross = CrossingFollow() + self.crossing_classified = False + self._track_age = 0.0 + self._vrel_f: float | None = None # v_lead - v_ego, positive opens + self._pullaway = False + self._close_s = 0.0 + self._pred_s = 0.0 + self._hard_n = 0 + self.pulling_away = False + + @property + def _cutin_w(self) -> float: + return self._conf + + def step(self, *, dt: float, present: bool, gap: float, v_ego: float, + v_lead: float, a_lead: float, t_follow: float, lead_id, + seed_a: float = 0.0, v_ceiling: float | None = None, + a_map: float | None = None, y_rel: float = 0.0, + curvature: float = 0.0, a_max: float | None = None, + path_lat: float | None = None, model_prob: float | None = None, + radar: bool | None = None, leave_w: float = 0.0, + gap_set_override_m: float | None = None, + v_curve_cap: float | None = None, + v_lat: float = 0.0, long_on: bool = True) -> float: + """One planner frame. Returns the slewed road-relative accel, or 0 with no lead.""" + frame_dt = 0.05 if dt is None or float(dt) <= 1e-6 else float(dt) + if not present: + self.reset() + return 0.0 + + # No command of our own yet: the first frame starts from seed_a. + fresh = self._prev is None + if lead_id != self._lead_id: + # New lead or cut-in: blend in from the command already in force. + self._cutin_from = float(seed_a if self._prev is None else self._prev) + self._conf = 0.0 + self._lead_id = lead_id + # Do not inherit the previous lead's accel. Speed starts at this sample. + # A pulling-away cut-in is seeded from the first radar accel so the + # 0 → aLeadK step is not read as brake onset. Every other new lead + # still ramps from 0: copying a closing lead's decel on the first + # frame is the Sep 28 far-lead flash, and a mild opening lead + # (about +0.5 m/s, aLeadK near −0.3) keeps the onset the plant + # already follows down to the −0.22 settle. + self._v_f = float(v_lead) + opening0 = float(v_lead) - float(v_ego) + if opening0 >= CUTIN_PULL_ENTER_MS: + self._a_f = float(a_lead) + else: + self._a_f = 0.0 + self._lead_jerk = 0.0 + self._rapid_y = None + self._approach.reset() + self._track_age = 0.0 + opening = float(v_lead) - float(v_ego) + self._vrel_f = opening + # A new lead that is already pulling away does not get lead braking. + # An existing lead that later becomes faster does not enter here. + self._pullaway = opening >= CUTIN_PULL_ENTER_MS + self._close_s = 0.0 + self._pred_s = 0.0 + self._hard_n = 0 + if self._prev is None: + self._prev = float(seed_a) + + # Path consistency for the far rapid-brake path. A one-frame yRel + # spike moves this about a fifth of the way, so a ghost flicker does + # not firm ego braking and a true in-path lead does not drop out. + y_abs = rapid_path_offset_m(y_rel, curvature, gap, path_lat) + self._rapid_y = _filt(self._rapid_y, y_abs, frame_dt, TAU_RAPID_PATH_S) + path_credit = rapid_path_credit(self._rapid_y) + self.last_rapid_path_credit = float(path_credit) + + self._track_age += frame_dt + self._approach.update(gap, v_ego, v_lead, frame_dt) + opening = float(v_lead) - float(v_ego) + self._vrel_f = _filt(self._vrel_f, opening, frame_dt, CUTIN_VREL_TAU_S) + self._update_pullaway(frame_dt, float(gap), float(v_ego), float(v_lead), float(a_lead)) + + self._v_f = _filt(self._v_f, float(v_lead), frame_dt, TAU_V_S) + a_prev = self._a_f + self._a_f = _filt(self._a_f, float(a_lead), frame_dt, TAU_A_S) + jerk_raw = (self._a_f - a_prev) / frame_dt if a_prev is not None else 0.0 + self._lead_jerk = _filt(self._lead_jerk, jerk_raw, frame_dt, LEAD_JERK_TAU_S) + # While a pulling-away cut-in is still new, a mild aLeadK is not a + # brake we should copy. A hard brake (<= −1.5) is used immediately. + ignore_alead = ( + self._pullaway + and self._track_age < CUTIN_ALEAD_IGNORE_S + and float(a_lead) > CUTIN_HARD_A_MS2 + ) + if ignore_alead: + a_eff = 0.0 + else: + a_eff = self._a_f - lead_decel_anticipation(self._a_f, self._lead_jerk, gap, v_ego) + self.last_v_lead = float(self._v_f) + self.last_a_lead = float(self._a_f) + self.last_a_lead_eff = float(a_eff) + self._cross.update( + dt=frame_dt, lead_id=lead_id, gap=float(gap), y_rel=float(y_rel), + v_lead=float(v_lead), v_lat=float(v_lat), model_prob=model_prob, long_on=bool(long_on), + ) + self.crossing_classified = bool(self._cross.classified) + + law_kw = dict( + v_ceiling=v_ceiling, a_map=a_map, y_rel=y_rel, curvature=curvature, + path_lat=path_lat, leave_w=leave_w, model_prob=model_prob, radar=radar, + gap_set_override_m=gap_set_override_m, v_curve_cap=v_curve_cap, + rapid_path_w=path_credit, + ) + desired = unified_follow_desired(gap, v_ego, self._v_f, a_eff, t_follow, **law_kw) + # Slow non-braking close: feed the low-passed gap and closing speed. + # If that removes braking physics still needs, keep the unfiltered law. + if self._approach.use_comfort(float(a_lead)) and self._approach.v_close_f is not None: + v_lead_f = float(v_ego) - float(self._approach.v_close_f) + gap_f = float(self._approach.gap_f if self._approach.gap_f is not None else gap) + filtered = unified_follow_desired(gap_f, v_ego, v_lead_f, a_eff, t_follow, **law_kw) + need = approach_physics_need(gap, v_ego, v_lead, t_follow) + # Filtered inputs may ease a command only when physics does not need + # it. They must not add braking the unfiltered law did not ask for, + # and they must not drop a brake that is still required. + if filtered > desired and need < -APPROACH_MILD_MS2: + pass + elif filtered <= desired: + pass + else: + desired = filtered + # Crossing lead: the law sees a smoothed fraction of the closing speed, + # so it eases off instead of stopping. A pulling-away cut-in is left + # on its own rule. When the exit sweep begins and the driver has not + # touched the gas, blend across to the speed-ceiling command. + scale = 1.0 if self._pullaway else self._cross.close_scale + resume_w = 0.0 if self._pullaway else self._cross.resume_w + if scale < 0.999: + v_close = max(0.0, float(v_ego) - float(self._v_f)) + v_law = float(v_ego) - v_close * scale + cross_kw = dict(law_kw) + cross_kw["leave_w"] = 0.0 + desired = unified_follow_desired(gap, v_ego, v_law, a_eff, t_follow, **cross_kw) + if resume_w > 0.0: + free = lead_free_accel(float(v_ego), v_ceiling, a_map, v_curve_cap) + desired = (1.0 - resume_w) * float(desired) + resume_w * free + if a_max is not None: + desired = min(desired, float(a_max)) + if self._pullaway: + # Zero lead-induced decel. Positive follow stays, already trickled + # inside the window, and is capped by the lead-free limit. MAX, + # curve, and map braking still apply through that limit. Pin the + # blend source so a rising confidence cannot fade the brake back in. + free = lead_free_accel(float(v_ego), v_ceiling, a_map, v_curve_cap) + desired = min(free, max(float(desired), 0.0)) + # Inside the follow window a pulling-away lead is not chased. + # The existing trickle is the positive cap; a limit brake stays. + gap_set = gap_set_m(float(v_lead), t_follow) + if gap_set_override_m is not None: + gap_set = float(gap_set_override_m) + if desired > TRICKLE_A and float(gap) <= gap_set: + desired = TRICKLE_A + if a_max is not None: + desired = min(desired, float(a_max)) + self._cutin_from = float(desired) + self.pulling_away = bool(self._pullaway) + self.last_desired = desired + + v_err = float(self._v_f) - float(v_ego) + gap_set = gap_set_m(self._v_f, t_follow) + if gap_set_override_m is not None: + gap_set = float(gap_set_override_m) + slack = float(gap) - gap_set + a_kin = _a_kin(slack, max(0.0, -v_err), max(0.0, float(gap)), float(v_ego), + t_follow, float(self._v_f)) + + # Confidence: consistent, on-path, good-quality readings ramp to 1. + # A fast close (deep kinematic demand) ramps within a fraction of a + # second; a one-frame reading barely moves it. + # Confidence reads the static off-path geometry only. A leaving lead is + # released through `desired` (leave_w above), toward the lead-free + # command; a confidence drop would blend toward the command in force, + # which is the lead's brake itself. + fade = _leave_fade(y_rel, curvature, gap, path_lat, leave_w) + on_path = 1.0 - _depart_fade(y_rel, curvature, gap, path_lat) + target_conf = on_path * lead_quality(model_prob, radar) + urgency = _smooth01((-a_kin - CONF_URGENT_LO_MS2) / CONF_URGENT_BAND_MS2) + if target_conf >= self._conf: + rate = CONF_RATE_BASE_1_S + CONF_RATE_URGENT_1_S * urgency * self._conf + else: + rate = CONF_RATE_FALL_1_S + self._conf = self._conf + min(1.0, rate * frame_dt) * (target_conf - self._conf) + self._conf = min(1.0, max(0.0, self._conf)) + self.last_confidence = float(self._conf) + + # Off-path leads already fade inside `desired`; confidence blends a new + # or weak reading from the command in force before this lead. + w = self._conf if lead_id == self._lead_id else 0.0 + # The command a lead blends from obeys a trust bound too: an inherited + # command firmer than both this lead's own demand and its kinematic + # floor (legacy seed after a gas override, a previous lead) is kept only + # in proportion to trust × confidence. A new or remote lead cannot carry + # it (Sep 28 11:07:22). MAX / map terms keep their own depth. + trust = lead_trust(gap, v_ego, self._v_f, y_rel, curvature, path_lat, model_prob, radar) + a_floor_lead = credited_rapid_lead( + float(self._a_f), slack, max(0.0, -v_err), path_credit) + floor = hard_decel_floor(gap, v_ego, self._v_f, a_floor_lead, t_follow) + if gap_set_override_m is None and v_ceiling is not None and float(v_ceiling) > 0.5: + floor = min(floor, speed_ceiling_accel(float(v_ego), float(v_ceiling))) + if v_curve_cap is not None and float(v_curve_cap) > 0.5: + floor = min(floor, speed_ceiling_accel(float(v_ego), float(v_curve_cap))) + if a_map is not None: + floor = min(floor, float(a_map)) + carry = min(desired, floor) + carry_trust = trust * self._conf + self.last_trust = float(trust) + self.last_floor = float(floor) + self._cutin_from = trust_bound(self._cutin_from, carry, carry_trust) + target = ((1.0 - w) * self._cutin_from) + (w * desired) + if self._pullaway: + # The held command is the blend. Confidence must not fade a lead + # brake back in, and the handover later slews from this command. + target = float(desired) + prev = float(self._prev if self._prev is not None else seed_a) + if fresh: + prev = trust_bound(prev, carry, carry_trust) + + opening = v_err > 0.25 and slack > 1.0 + release_base = JERK_RELEASE_OPEN_MS3 if (opening or fade > 0.35) else JERK_RELEASE_MS3 + # The frame a lock replaces a time-gap ease, the command in force is + # still that brake. Release it at the physical jerk so the gap does + # not keep opening while the slew catches up. Braking (target below + # the command) is unchanged. + if gap_set_override_m is not None and float(target) > prev: + release_base = JERK_PHYS_MS3 + err = float(target) - prev + # Proportional: far too firm releases fast, near the target gently. + up = min(JERK_PHYS_MS3, release_base + JERK_PROP_1_S * max(0.0, err)) * frame_dt + build_base = JERK_PHYS_MS3 if a_kin < prev - 0.08 else JERK_BUILD_MS3 + down = min(JERK_PHYS_MS3, build_base + JERK_PROP_1_S * max(0.0, -err)) * frame_dt + nxt = _limit_jerk(prev, target, frame_dt, down=down, up=up) + self._prev = nxt + # Once a lead is trusted, the blend-from value follows the published + # command so a later confidence dip fades toward current behavior. + self._cutin_from += (nxt - self._cutin_from) * self._conf * min(1.0, frame_dt / MODE_BLEND_S) + if self._pullaway: + # Pin to the published command so leaving the hold cannot step. + self._cutin_from = float(nxt) + return nxt + + def _update_pullaway(self, dt: float, gap: float, v_ego: float, v_lead: float, + a_lead: float) -> None: + """Hold or release the pulling-away cut-in. Release is one-way.""" + if not self._pullaway: + return + if float(a_lead) <= CUTIN_HARD_A_MS2: + self._hard_n += 1 + else: + self._hard_n = 0 + v_open = 0.0 if self._vrel_f is None else float(self._vrel_f) + if -v_open >= CUTIN_CLOSE_MS: + self._close_s += float(dt) + else: + self._close_s = 0.0 + pred = v_open + min(float(a_lead), 0.0) * CUTIN_PRED_T_S + if pred <= -CUTIN_CLOSE_MS: + self._pred_s += float(dt) + else: + self._pred_s = 0.0 + keep = CUTIN_KEEP_M + CUTIN_KEEP_HW_S * max(0.0, float(v_ego)) + headway = float(gap) / max(float(v_ego), 1.0) + release = ( + self._hard_n >= CUTIN_HARD_FRAMES + or self._close_s + 1e-9 >= CUTIN_CLOSE_HOLD_S + or self._pred_s + 1e-9 >= CUTIN_PRED_HOLD_S + or projected_gap_m(gap, v_ego, v_lead, a_lead) < keep + or headway < CUTIN_HEADWAY_S + ) + if release: + self._pullaway = False + self._close_s = 0.0 + self._pred_s = 0.0 diff --git a/selfdrive/controls/lib/vehicle_model.py b/selfdrive/controls/lib/vehicle_model.py deleted file mode 100755 index b6f50b4ba80886..00000000000000 --- a/selfdrive/controls/lib/vehicle_model.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python3 -""" -Dynamic bicycle model from "The Science of Vehicle Dynamics (2014), M. Guiggiani" - -The state is x = [v, r]^T -with v lateral speed [m/s], and r rotational speed [rad/s] - -The input u is the steering angle [rad], and roll [rad] - -The system is defined by -x_dot = A*x + B*u - -A depends on longitudinal speed, u [m/s], and vehicle parameters CP -""" - -import numpy as np -from numpy.linalg import solve - -from cereal import car - -ACCELERATION_DUE_TO_GRAVITY = 9.8 - - -class VehicleModel: - def __init__(self, CP: car.CarParams): - """ - Args: - CP: Car Parameters - """ - # for math readability, convert long names car params into short names - self.m: float = CP.mass - self.j: float = CP.rotationalInertia - self.l: float = CP.wheelbase - self.aF: float = CP.centerToFront - self.aR: float = CP.wheelbase - CP.centerToFront - self.chi: float = CP.steerRatioRear - - self.cF_orig: float = CP.tireStiffnessFront - self.cR_orig: float = CP.tireStiffnessRear - self.update_params(1.0, CP.steerRatio) - - def update_params(self, stiffness_factor: float, steer_ratio: float) -> None: - """Update the vehicle model with a new stiffness factor and steer ratio""" - self.cF: float = stiffness_factor * self.cF_orig - self.cR: float = stiffness_factor * self.cR_orig - self.sR: float = steer_ratio - - def steady_state_sol(self, sa: float, u: float, roll: float) -> np.ndarray: - """Returns the steady state solution. - - If the speed is too low we can't use the dynamic model (tire slip is undefined), - we then have to use the kinematic model - - Args: - sa: Steering wheel angle [rad] - u: Speed [m/s] - roll: Road Roll [rad] - - Returns: - 2x1 matrix with steady state solution (lateral speed, rotational speed) - """ - if u > 0.1: - return dyn_ss_sol(sa, u, roll, self) - else: - return kin_ss_sol(sa, u, self) - - def calc_curvature(self, sa: float, u: float, roll: float) -> float: - """Returns the curvature. Multiplied by the speed this will give the yaw rate. - - Args: - sa: Steering wheel angle [rad] - u: Speed [m/s] - roll: Road Roll [rad] - - Returns: - Curvature factor [1/m] - """ - return (self.curvature_factor(u) * sa / self.sR) + self.roll_compensation(roll, u) - - def curvature_factor(self, u: float) -> float: - """Returns the curvature factor. - Multiplied by wheel angle (not steering wheel angle) this will give the curvature. - - Args: - u: Speed [m/s] - - Returns: - Curvature factor [1/m] - """ - sf = calc_slip_factor(self) - return (1. - self.chi) / (1. - sf * u**2) / self.l - - def get_steer_from_curvature(self, curv: float, u: float, roll: float) -> float: - """Calculates the required steering wheel angle for a given curvature - - Args: - curv: Desired curvature [1/m] - u: Speed [m/s] - roll: Road Roll [rad] - - Returns: - Steering wheel angle [rad] - """ - - return (curv - self.roll_compensation(roll, u)) * self.sR * 1.0 / self.curvature_factor(u) - - def roll_compensation(self, roll: float, u: float) -> float: - """Calculates the roll-compensation to curvature - - Args: - roll: Road Roll [rad] - u: Speed [m/s] - - Returns: - Roll compensation curvature [rad] - """ - sf = calc_slip_factor(self) - - if abs(sf) < 1e-6: - return 0 - else: - return (ACCELERATION_DUE_TO_GRAVITY * roll) / ((1 / sf) - u**2) - - def get_steer_from_yaw_rate(self, yaw_rate: float, u: float, roll: float) -> float: - """Calculates the required steering wheel angle for a given yaw_rate - - Args: - yaw_rate: Desired yaw rate [rad/s] - u: Speed [m/s] - roll: Road Roll [rad] - - Returns: - Steering wheel angle [rad] - """ - curv = yaw_rate / u - return self.get_steer_from_curvature(curv, u, roll) - - def yaw_rate(self, sa: float, u: float, roll: float) -> float: - """Calculate yaw rate - - Args: - sa: Steering wheel angle [rad] - u: Speed [m/s] - roll: Road Roll [rad] - - Returns: - Yaw rate [rad/s] - """ - return self.calc_curvature(sa, u, roll) * u - - -def kin_ss_sol(sa: float, u: float, VM: VehicleModel) -> np.ndarray: - """Calculate the steady state solution at low speeds - At low speeds the tire slip is undefined, so a kinematic - model is used. - - Args: - sa: Steering angle [rad] - u: Speed [m/s] - VM: Vehicle model - - Returns: - 2x1 matrix with steady state solution - """ - K = np.zeros((2, 1)) - K[0, 0] = VM.aR / VM.sR / VM.l * u - K[1, 0] = 1. / VM.sR / VM.l * u - return K * sa - - -def create_dyn_state_matrices(u: float, VM: VehicleModel) -> tuple[np.ndarray, np.ndarray]: - """Returns the A and B matrix for the dynamics system - - Args: - u: Vehicle speed [m/s] - VM: Vehicle model - - Returns: - A tuple with the 2x2 A matrix, and 2x2 B matrix - - Parameters in the vehicle model: - cF: Tire stiffness Front [N/rad] - cR: Tire stiffness Front [N/rad] - aF: Distance from CG to front wheels [m] - aR: Distance from CG to rear wheels [m] - m: Mass [kg] - j: Rotational inertia [kg m^2] - sR: Steering ratio [-] - chi: Steer ratio rear [-] - """ - A = np.zeros((2, 2)) - B = np.zeros((2, 2)) - A[0, 0] = - (VM.cF + VM.cR) / (VM.m * u) - A[0, 1] = - (VM.cF * VM.aF - VM.cR * VM.aR) / (VM.m * u) - u - A[1, 0] = - (VM.cF * VM.aF - VM.cR * VM.aR) / (VM.j * u) - A[1, 1] = - (VM.cF * VM.aF**2 + VM.cR * VM.aR**2) / (VM.j * u) - - # Steering input - B[0, 0] = (VM.cF + VM.chi * VM.cR) / VM.m / VM.sR - B[1, 0] = (VM.cF * VM.aF - VM.chi * VM.cR * VM.aR) / VM.j / VM.sR - - # Roll input - B[0, 1] = -ACCELERATION_DUE_TO_GRAVITY - - return A, B - - -def dyn_ss_sol(sa: float, u: float, roll: float, VM: VehicleModel) -> np.ndarray: - """Calculate the steady state solution when x_dot = 0, - Ax + Bu = 0 => x = -A^{-1} B u - - Args: - sa: Steering angle [rad] - u: Speed [m/s] - roll: Road Roll [rad] - VM: Vehicle model - - Returns: - 2x1 matrix with steady state solution - """ - A, B = create_dyn_state_matrices(u, VM) - inp = np.array([[sa], [roll]]) - return -solve(A, B) @ inp # type: ignore - - -def calc_slip_factor(VM: VehicleModel) -> float: - """The slip factor is a measure of how the curvature changes with speed - it's positive for Oversteering vehicle, negative (usual case) otherwise. - """ - return VM.m * (VM.cF * VM.aF - VM.cR * VM.aR) / (VM.l**2 * VM.cF * VM.cR) diff --git a/selfdrive/controls/plannerd.py b/selfdrive/controls/plannerd.py index 9de70c767ad9e6..333fedbae9f70a 100755 --- a/selfdrive/controls/plannerd.py +++ b/selfdrive/controls/plannerd.py @@ -3,22 +3,24 @@ from openpilot.common.params import Params from openpilot.common.realtime import Priority, config_realtime_process from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.controls.lib.ldw import LaneDepartureWarning from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner import cereal.messaging as messaging -def plannerd_thread(): +def main(): config_realtime_process(5, Priority.CTRL_LOW) cloudlog.info("plannerd is waiting for CarParams") params = Params() CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) - cloudlog.info("plannerd got CarParams: %s", CP.carName) + cloudlog.info("plannerd got CarParams: %s", CP.brand) + ldw = LaneDepartureWarning() longitudinal_planner = LongitudinalPlanner(CP) - pm = messaging.PubMaster(['longitudinalPlan']) - sm = messaging.SubMaster(['carControl', 'carState', 'controlsState', 'radarState', 'modelV2', 'selfdriveState'], - poll='modelV2', ignore_avg_freq=['radarState']) + pm = messaging.PubMaster(['longitudinalPlan', 'driverAssistance']) + sm = messaging.SubMaster(['carControl', 'carState', 'controlsState', 'liveParameters', 'radarState', 'modelV2', 'selfdriveState', 'liveMapDataNAP'], + poll='modelV2') while True: sm.update() @@ -26,9 +28,12 @@ def plannerd_thread(): longitudinal_planner.update(sm) longitudinal_planner.publish(sm, pm) - -def main(): - plannerd_thread() + ldw.update(sm.frame, sm['modelV2'], sm['carState'], sm['carControl']) + msg = messaging.new_message('driverAssistance') + msg.valid = sm.all_checks(['carState', 'carControl', 'modelV2', 'liveParameters']) + msg.driverAssistance.leftLaneDeparture = ldw.left + msg.driverAssistance.rightLaneDeparture = ldw.right + pm.send('driverAssistance', msg) if __name__ == "__main__": diff --git a/selfdrive/controls/radard.py b/selfdrive/controls/radard.py index f3aa099bfbf6ba..775867283a2e68 100755 --- a/selfdrive/controls/radard.py +++ b/selfdrive/controls/radard.py @@ -1,18 +1,56 @@ #!/usr/bin/env python3 -import importlib import math +import time +import numpy as np from collections import deque from typing import Any import capnp from cereal import messaging, log, car -from opendbc.car import structs -from openpilot.common.numpy_fast import interp +from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.params import Params -from openpilot.common.realtime import DT_CTRL, Ratekeeper, Priority, config_realtime_process +from openpilot.common.realtime import DT_MDL, Priority, config_realtime_process from openpilot.common.swaglog import cloudlog from openpilot.common.simple_kalman import KF1D -from openpilot.selfdrive.pandad import can_capnp_to_list +from openpilot.selfdrive.controls.lib.path_obstacle import ( + ConeHint, + ObstacleStage, + hit_to_msg, + vehicle_exclusion_points, +) +from openpilot.selfdrive.controls.lib.cone_line import ( + ConeCorridorDetector, + ConeLineSample, + lane_room_m, + model_yaw_rate_right, + publish_cone_line, + road_edges_xy, +) +from openpilot.selfdrive.controls.lib.crossing_vehicle import GroundLateral +from openpilot.selfdrive.controls.lib.cone_line_hold import PARAM_CONE_LINE_LOG +from openpilot.selfdrive.controls.lib.radar_path_gate import ( + PATH_INCUMBENT_HALF_WIDTH_M, + RADAR_TO_CAMERA_M, + collapse_blocks_new_lead, + model_path_xy, + path_lateral_m, + path_model_collapsed, + radar_follow_ok, + vision_lead_follow_ok, +) +from openpilot.selfdrive.controls.lib.radar_sensor_dirty import ( + SensorDirtyPolicy, + reason_token, + sensor_dirty_ignore_enabled, +) +from openpilot.selfdrive.controls.lib.rain_radar_hold import ( + RAIN_RADAR_LOST_HOLD_FRAMES, + RAIN_VISION_ONLY_MIN_PROB, + RadarReliability, + RainRadarGate, + pick_rain_radar_track, + rain_far_hold_ok, +) # Default lead acceleration decay set to 50% at 1s @@ -27,6 +65,22 @@ RADAR_TO_CENTER = 2.7 # (deprecated) RADAR is ~ 2.7m ahead from center of car RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame +# Bosch radar updates at 8 Hz; use actual measurement interval for KF +RADAR_DT = 1.0 / 8 +RADAR_MEASUREMENT_TIMEOUT = 0.5 + +ASSOCIATION_DISTANCE_GATE = 3.0 +ASSOCIATION_MIN_DISTANCE_STD = 1.0 +ASSOCIATION_LATERAL_GATE = 3.0 +ASSOCIATION_MIN_LATERAL_STD = 0.5 +ASSOCIATION_VELOCITY_GATE = 3.0 +ASSOCIATION_MIN_VELOCITY_STD = 1.0 +# The independent 3-sigma gates below reject single-axis outliers. Keep this +# combined likelihood floor lower so ordinary multi-axis noise does not cause +# repeated radar/vision fallback transitions. +ASSOCIATION_MIN_SCORE = 0.001 +ASSOCIATION_SWITCH_MARGIN = 1.5 + class KalmanParams: def __init__(self, dt: float): @@ -47,20 +101,23 @@ def __init__(self, dt: float): 0.28144091, 0.27958406, 0.27783249, 0.27617149, 0.27458948, 0.27307714, 0.27162685, 0.27023228, 0.26888809, 0.26758976, 0.26633338, 0.26511557, 0.26393339, 0.26278425] - self.K = [[interp(dt, dts, K0)], [interp(dt, dts, K1)]] + self.K = [[np.interp(dt, dts, K0)], [np.interp(dt, dts, K1)]] class Track: def __init__(self, identifier: int, v_lead: float, kalman_params: KalmanParams): self.identifier = identifier self.cnt = 0 - self.aLeadTau = _LEAD_ACCEL_TAU + self.aLeadTau = FirstOrderFilter(_LEAD_ACCEL_TAU, 0.45, DT_MDL) self.K_A = kalman_params.A self.K_C = kalman_params.C self.K_K = kalman_params.K self.kf = KF1D([[v_lead], [0.0]], self.K_A, self.K_C, self.K_K) + # Ground-frame lateral speed, +left. 0 until the yaw-corrected fit has a window. + self.vLat = 0.0 - def update(self, d_rel: float, y_rel: float, v_rel: float, v_lead: float, measured: float): + def update(self, d_rel: float, y_rel: float, v_rel: float, v_lead: float, measured: float, + kalman_params: KalmanParams | None = None): # relative values, copy self.dRel = d_rel # LONG_DIST self.yRel = y_rel # -LAT_DIST @@ -69,7 +126,9 @@ def update(self, d_rel: float, y_rel: float, v_rel: float, v_lead: float, measur self.measured = measured # measured or estimate # computed velocity and accelerations - if self.cnt > 0: + if measured and kalman_params is not None: + self._set_kalman_params(kalman_params) + if self.cnt > 0 and measured: self.kf.update(self.vLead) self.vLeadK = float(self.kf.x[SPEED][0]) @@ -77,20 +136,18 @@ def update(self, d_rel: float, y_rel: float, v_rel: float, v_lead: float, measur # Learn if constant acceleration if abs(self.aLeadK) < 0.5: - self.aLeadTau = _LEAD_ACCEL_TAU + self.aLeadTau.x = _LEAD_ACCEL_TAU else: - self.aLeadTau *= 0.9 + self.aLeadTau.update(0.0) self.cnt += 1 - def get_key_for_cluster(self): - # Weigh y higher since radar is inaccurate in this dimension - return [self.dRel, self.yRel*2, self.vRel] - - def reset_a_lead(self, aLeadK: float, aLeadTau: float): - self.kf = KF1D([[self.vLead], [aLeadK]], self.K_A, self.K_C, self.K_K) - self.aLeadK = aLeadK - self.aLeadTau = aLeadTau + def _set_kalman_params(self, kalman_params: KalmanParams): + state = self.kf.x + self.K_A = kalman_params.A + self.K_C = kalman_params.C + self.K_K = kalman_params.K + self.kf = KF1D(state, self.K_A, self.K_C, self.K_K) def get_RadarState(self, model_prob: float = 0.0): return { @@ -100,12 +157,13 @@ def get_RadarState(self, model_prob: float = 0.0): "vLead": float(self.vLead), "vLeadK": float(self.vLeadK), "aLeadK": float(self.aLeadK), - "aLeadTau": float(self.aLeadTau), + "aLeadTau": float(self.aLeadTau.x), "status": True, "fcw": self.is_potential_fcw(model_prob), "modelProb": model_prob, "radar": True, "radarTrackId": self.identifier, + "vLat": float(self.vLat), } def potential_low_speed_lead(self, v_ego: float): @@ -126,27 +184,60 @@ def laplacian_pdf(x: float, mu: float, b: float): return math.exp(-abs(x-mu)/b) -def match_vision_to_track(v_ego: float, lead: capnp._DynamicStructReader, tracks: dict[int, Track]): - offset_vision_dist = lead.x[0] - RADAR_TO_CAMERA - - def prob(c): - prob_d = laplacian_pdf(c.dRel, offset_vision_dist, lead.xStd[0]) - prob_y = laplacian_pdf(c.yRel, -lead.y[0], lead.yStd[0]) - prob_v = laplacian_pdf(c.vRel + v_ego, lead.v[0], lead.vStd[0]) - - # This isn't exactly right, but it's a good heuristic - return prob_d * prob_y * prob_v +def association_score(v_ego: float, vision_d_rel: float, lead: capnp._DynamicStructReader, track: Track) -> float: + distance_probability = laplacian_pdf(track.dRel, vision_d_rel, lead.xStd[0]) + lateral_probability = laplacian_pdf(track.yRel, -lead.y[0], lead.yStd[0]) + velocity_probability = laplacian_pdf(track.vRel + v_ego, lead.v[0], lead.vStd[0]) + return distance_probability * lateral_probability * velocity_probability + + +def is_association_candidate(v_ego: float, vision_d_rel: float, lead: capnp._DynamicStructReader, + track: Track, score: float, + path_x=None, path_y=None, collapsed=False, + incumbent=False) -> bool: + # Vision already nominated this lead. Allow lane-edge / early cut-in + # (incumbent half-width). Unassociated prefer pick stays on the tighter + # acquire gate and still requires a path association. + # A collapsed path raises the bar for a *new* |yRel| ≳ 2 association + # (construction right-side blip). The incumbent track is unchanged. + if collapse_blocks_new_lead(track.yRel, collapsed, incumbent=incumbent): + return False + if not radar_follow_ok(track, v_ego, path_x, path_y, + max_lat=PATH_INCUMBENT_HALF_WIDTH_M): + return False + distance_limit = ASSOCIATION_DISTANCE_GATE * max(lead.xStd[0], ASSOCIATION_MIN_DISTANCE_STD) + lateral_limit = ASSOCIATION_LATERAL_GATE * max(lead.yStd[0], ASSOCIATION_MIN_LATERAL_STD) + velocity_limit = ASSOCIATION_VELOCITY_GATE * max(lead.vStd[0], ASSOCIATION_MIN_VELOCITY_STD) + + distance_compatible = abs(track.dRel - vision_d_rel) <= distance_limit + lateral_compatible = abs(track.yRel + lead.y[0]) <= lateral_limit + velocity_compatible = abs(track.vRel + v_ego - lead.v[0]) <= velocity_limit + return distance_compatible and lateral_compatible and velocity_compatible and score >= ASSOCIATION_MIN_SCORE + + +def match_vision_to_track(v_ego: float, lead: capnp._DynamicStructReader, tracks: dict[int, Track], + incumbent_track_id: int | None = None, + path_x=None, path_y=None, collapsed=False) -> Track | None: + vision_d_rel = lead.x[0] - RADAR_TO_CAMERA + scores = {track_id: association_score(v_ego, vision_d_rel, lead, track) for track_id, track in tracks.items()} + eligible_track_ids = [ + track_id for track_id, track in tracks.items() + if is_association_candidate( + v_ego, vision_d_rel, lead, track, scores[track_id], + path_x=path_x, path_y=path_y, collapsed=collapsed, + incumbent=track_id == incumbent_track_id, + ) + ] + if not eligible_track_ids: + return None - track = max(tracks.values(), key=prob) + challenger_track_id = max(eligible_track_ids, key=scores.__getitem__) + if incumbent_track_id in eligible_track_ids and challenger_track_id != incumbent_track_id: + challenger_wins = scores[challenger_track_id] > scores[incumbent_track_id] * ASSOCIATION_SWITCH_MARGIN + if not challenger_wins: + return tracks[incumbent_track_id] - # if no 'sane' match is found return -1 - # stationary radar points can be false positives - dist_sane = abs(track.dRel - offset_vision_dist) < max([(offset_vision_dist)*.25, 5.0]) - vel_sane = (abs(track.vRel + v_ego - lead.v[0]) < 10) or (v_ego + track.vRel > 3) - if dist_sane and vel_sane: - return track - else: - return None + return tracks[challenger_track_id] def get_RadarState_from_vision(lead_msg: capnp._DynamicStructReader, v_ego: float, model_v_ego: float): @@ -157,7 +248,7 @@ def get_RadarState_from_vision(lead_msg: capnp._DynamicStructReader, v_ego: floa "vRel": float(lead_v_rel_pred), "vLead": float(v_ego + lead_v_rel_pred), "vLeadK": float(v_ego + lead_v_rel_pred), - "aLeadK": 0.0, + "aLeadK": float(lead_msg.a[0]), "aLeadTau": 0.3, "fcw": False, "modelProb": float(lead_msg.prob), @@ -167,49 +258,243 @@ def get_RadarState_from_vision(lead_msg: capnp._DynamicStructReader, v_ego: floa } -def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capnp._DynamicStructReader, - model_v_ego: float, low_speed_override: bool = True) -> dict[str, Any]: - # Determine leads, this is where the essential logic happens - if len(tracks) > 0 and ready and lead_msg.prob > .5: - track = match_vision_to_track(v_ego, lead_msg, tracks) - else: - track = None +class LeadTrackAssociation: + def __init__(self, low_speed_override: bool): + self.low_speed_override = low_speed_override + self.incumbent_track_id: int | None = None + self._rain_lost_frames = 0 + self._held_radar_lead: dict[str, Any] | None = None + + def update(self, v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capnp._DynamicStructReader, + model_v_ego: float, rain_hold: bool = False, radar_prefer: bool | None = None, + path_x=None, path_y=None, collapsed=False) -> dict[str, Any]: + if radar_prefer is None: + radar_prefer = rain_hold + if tracks and ready and lead_msg.prob > .5: + track = match_vision_to_track(v_ego, lead_msg, tracks, self.incumbent_track_id, + path_x=path_x, path_y=path_y, collapsed=collapsed) + else: + track = None + + if radar_prefer: + track = pick_rain_radar_track(track, tracks, self.incumbent_track_id, v_ego, + path_x, path_y, vision_prob=float(lead_msg.prob)) + if track is not None: + self._rain_lost_frames = 0 + elif (self.incumbent_track_id is not None and + self.incumbent_track_id in tracks): + # Live track failed path/oncoming / far-low-prob — do not keep the cache. + self._held_radar_lead = None + self._rain_lost_frames = 0 + elif tracks: + # Incumbent gone; live table has other tracks that did not qualify. + # Do not ghost-hold a disappeared lead over oncoming / off-path clutter. + self._held_radar_lead = None + self._rain_lost_frames = 0 + elif self._held_radar_lead is not None: + self._rain_lost_frames += 1 + else: + self._rain_lost_frames = 0 + else: + self._rain_lost_frames = 0 + self._held_radar_lead = None + + vision_prob_min = RAIN_VISION_ONLY_MIN_PROB if radar_prefer else .5 + + lead_dict = {'status': False} + if track is not None: + lead_dict = track.get_RadarState(lead_msg.prob) + elif (radar_prefer and self._held_radar_lead is not None and + self._rain_lost_frames <= RAIN_RADAR_LOST_HOLD_FRAMES and + radar_follow_ok(self._held_radar_lead, v_ego, path_x, path_y, + max_lat=PATH_INCUMBENT_HALF_WIDTH_M) and + rain_far_hold_ok(self._held_radar_lead, None, float(lead_msg.prob))): + lead_dict = dict(self._held_radar_lead) + lead_dict["modelProb"] = float(lead_msg.prob) + elif (ready and lead_msg.prob >= vision_prob_min and + vision_lead_follow_ok(lead_msg, v_ego, path_x, path_y)): + lead_dict = get_RadarState_from_vision(lead_msg, v_ego, model_v_ego) + # Vision-only at |yRel| ≳ 2 is a new association. Do not start one + # while the path model is collapsed (right-side construction blip). + if collapse_blocks_new_lead(lead_dict.get("yRel"), collapsed, incumbent=False): + lead_dict = {'status': False} + + if self.low_speed_override: + low_speed_tracks = [candidate for candidate in tracks.values() if candidate.potential_low_speed_lead(v_ego)] + if low_speed_tracks: + closest_track = min(low_speed_tracks, key=lambda candidate: candidate.dRel) + if (not lead_dict['status']) or (closest_track.dRel < lead_dict['dRel']): + lead_dict = closest_track.get_RadarState() + + if lead_dict.get('status'): + lat = path_lateral_m(lead_dict, path_x, path_y) + if lat is not None: + lead_dict["dPath"] = float(lat) + + if lead_dict.get('radar', False): + self.incumbent_track_id = lead_dict['radarTrackId'] + self._held_radar_lead = dict(lead_dict) + else: + self.incumbent_track_id = None + return lead_dict + + +def _capnp_attr(obj, name): + try: + return getattr(obj, name) + except Exception: + return None + + +def _radar_point(pt) -> dict: + """Plain snapshot so the scan never writes back into the live radar message.""" + measured = _capnp_attr(pt, "measured") + item = { + "dRel": _capnp_attr(pt, "dRel"), + "yRel": _capnp_attr(pt, "yRel"), + "vRel": _capnp_attr(pt, "vRel"), + "trackId": _capnp_attr(pt, "trackId"), + "measured": True if measured is None else bool(measured), + } + yv = _capnp_attr(pt, "yvRel") + if yv is not None: + item["yvRel"] = yv + rcs = _capnp_attr(pt, "rcs") + if rcs is None: + rcs = _capnp_attr(pt, "rcsDb") + if rcs is not None: + item["rcs"] = rcs + return item + + +def _radar_lead(lead) -> dict | None: + try: + if lead is None or not bool(lead.status): + return None + track = _capnp_attr(lead, "radarTrackId") + prob = _capnp_attr(lead, "modelProb") + return { + "status": True, + "dRel": float(lead.dRel), + "yRel": float(lead.yRel), + "modelProb": 1.0 if prob is None else float(prob), + "radarTrackId": -1 if track is None else int(track), + } + except Exception: + return None + + +def _model_lead_tuples(leads, xyva: bool) -> list: + out = [] + try: + seq = list(leads) if leads is not None else [] + except TypeError: + return out + for item in seq: + try: + prob = float(item.prob) + if xyva: + xy = item.xyva + out.append((float(xy[0]), float(xy[1]), prob)) + else: + out.append((float(item.x[0]), float(item.y[0]), prob)) + except Exception: + continue + return out + + +def _cone_hint(sample) -> ConeHint | None: + if sample is None: + return None + try: + return ConeHint( + active=bool(sample.active), + side=int(sample.side), + lat_near=float(sample.lat_near), + lat_mid=float(sample.lat_mid), + lat_far=float(sample.lat_far), + barrier=bool(sample.barrier), + parked=bool(sample.parked), + ) + except Exception: + return None - lead_dict = {'status': False} - if track is not None: - lead_dict = track.get_RadarState(lead_msg.prob) - elif (track is None) and ready and (lead_msg.prob > .5): - lead_dict = get_RadarState_from_vision(lead_msg, v_ego, model_v_ego) - if low_speed_override: - low_speed_tracks = [c for c in tracks.values() if c.potential_low_speed_lead(v_ego)] - if len(low_speed_tracks) > 0: - closest_track = min(low_speed_tracks, key=lambda c: c.dRel) +def _lane_prob_min(model) -> float: + try: + probs = list(model.laneLineProbs) + if len(probs) >= 3: + return float(min(float(probs[1]), float(probs[2]))) + except Exception: + pass + return 1.0 - # Only choose new track if it is actually closer than the previous one - if (not lead_dict['status']) or (closest_track.dRel < lead_dict['dRel']): - lead_dict = closest_track.get_RadarState() - return lead_dict +def _path_y_std_3s(model): + try: + ts = [float(v) for v in model.position.t] + stds = [float(v) for v in model.position.yStd] + except Exception: + return None + if not ts or not stds: + return None + n = min(len(ts), len(stds)) + idx = min(range(n), key=lambda i: abs(ts[i] - 3.0)) + return stds[idx] class RadarD: - def __init__(self, radar_ts: float, delay: int = 0): + def __init__(self, delay: float = 0.0, rain_gate: RainRadarGate | None = None): self.current_time = 0.0 self.tracks: dict[int, Track] = {} - self.kalman_params = KalmanParams(radar_ts) + self.kalman_params = KalmanParams(RADAR_DT) + self.last_radar_update_time: float | None = None self.v_ego = 0.0 - self.v_ego_hist = deque([0.0], maxlen=delay+1) + self.v_ego_hist = deque([0.0], maxlen=int(round(delay / DT_MDL))+1) self.last_v_ego_frame = -1 self.radar_state: capnp._DynamicStructBuilder | None = None self.radar_state_valid = False self.ready = False - - def update(self, sm: messaging.SubMaster, rr: structs.RadarData): + self.lead_one_association = LeadTrackAssociation(low_speed_override=True) + self.lead_two_association = LeadTrackAssociation(low_speed_override=False) + self.rain_gate = rain_gate if rain_gate is not None else RainRadarGate() + self.reliability = RadarReliability() + self.engaged = False + # Bosch SensorDirty: degrade (keep the radar lead) instead of soft-disable. + self.sensor_dirty = SensorDirtyPolicy() + self._sensor_dirty_ignore_override: bool | None = None + self._live_measured = False + # Cone line is log-only. It does not select a lead or touch longitudinal. + self._cone = ConeCorridorDetector() + self._cone_sample = None + self._cone_dirty = False + self._cone_log_on = True + self._cone_log_check_t = -1.0 + # Radar half of the path-obstacle log. The scan runs after radarState + # is published, so a slow or failing scan cannot change lead selection. + self._obstacle = ObstacleStage() + self._obstacle_pending = False + self._obstacle_dt = RADAR_DT + self._obstacle_inputs = None + # Yaw-corrected lateral speed for the lead. Same modelV2 radard already + # reads; no extra carState subscriber. + self._ground = GroundLateral() + + def set_sensor_dirty_ignore_override(self, ignore: bool | None) -> None: + """Test hook. None reads NAPRadarIgnoreSensorDirty (default on).""" + self._sensor_dirty_ignore_override = None if ignore is None else bool(ignore) + + def read_sensor_dirty_ignore(self) -> bool: + if self._sensor_dirty_ignore_override is not None: + return self._sensor_dirty_ignore_override + return sensor_dirty_ignore_enabled(self.rain_gate._get_params()) + + def update(self, sm: messaging.SubMaster, rr: car.RadarData): + self._obstacle_pending = False self.ready = sm.seen['modelV2'] self.current_time = 1e-9*max(sm.logMonoTime.values()) @@ -217,64 +502,272 @@ def update(self, sm: messaging.SubMaster, rr: structs.RadarData): self.v_ego = sm['carState'].vEgo self.v_ego_hist.append(self.v_ego) self.last_v_ego_frame = sm.recv_frame['carState'] - - ar_pts = {} - for pt in rr.points: - ar_pts[pt.trackId] = [pt.dRel, pt.yRel, pt.vRel, pt.measured] - - # *** remove missing points from meta data *** - for ids in list(self.tracks.keys()): - if ids not in ar_pts: - self.tracks.pop(ids, None) - - # *** compute the tracks *** - for ids in ar_pts: - rpt = ar_pts[ids] - - # align v_ego by a fixed time to align it with the radar measurement - v_lead = rpt[2] + self.v_ego_hist[0] - - # create the track if it doesn't exist or it's a new track - if ids not in self.tracks: - self.tracks[ids] = Track(ids, v_lead, self.kalman_params) - self.tracks[ids].update(rpt[0], rpt[1], rpt[2], v_lead, rpt[3]) + cruise = getattr(sm['carState'], 'cruiseState', None) + self.engaged = bool(getattr(cruise, 'enabled', False)) + + radar_timed_out = False + if sm.updated['liveTracks']: + radar_update_time = 1e-9 * sm.logMonoTime['liveTracks'] + radar_dt = RADAR_DT + if self.last_radar_update_time is not None: + observed_radar_dt = radar_update_time - self.last_radar_update_time + if 0.01 < observed_radar_dt < 0.2: + radar_dt = observed_radar_dt + self.last_radar_update_time = radar_update_time + self.kalman_params = KalmanParams(radar_dt) + ar_pts = {pt.trackId: [pt.dRel, pt.yRel, pt.vRel, pt.measured] for pt in rr.points} + self._live_measured = any(rpt[3] for rpt in ar_pts.values()) + + # *** remove missing points from meta data *** + for ids in list(self.tracks.keys()): + if ids not in ar_pts: + self.tracks.pop(ids, None) + + # *** compute the tracks *** + for ids in ar_pts: + rpt = ar_pts[ids] + + # align v_ego by a fixed time to align it with the radar measurement + v_lead = rpt[2] + self.v_ego_hist[0] + + # create the track if it doesn't exist or it's a new track + if ids not in self.tracks: + self.tracks[ids] = Track(ids, v_lead, self.kalman_params) + self.tracks[ids].update(rpt[0], rpt[1], rpt[2], v_lead, rpt[3], self.kalman_params) + self._update_ground(radar_update_time, sm) + self._update_cone_line(sm, rr.points, radar_dt) + self._obstacle_dt = radar_dt + self._obstacle_pending = True + elif self.last_radar_update_time is None or self.current_time - self.last_radar_update_time > RADAR_MEASUREMENT_TIMEOUT: + self.tracks.clear() + self._ground.reset() + radar_timed_out = self.last_radar_update_time is not None + self._live_measured = False + self._update_cone_line(sm, (), RADAR_DT) # *** publish radarState *** - self.radar_state_valid = sm.all_checks() and len(rr.errors) == 0 + # Exclude liveTracks from validity check: it arrives at radar rate (8Hz for + # Bosch) not the 20Hz SubMaster expects, so all_checks() would mark it stale + # between radar updates and cascade valid=False through the whole pipeline. + self.radar_state_valid = sm.all_checks(service_list=['modelV2', 'carState']) self.radar_state = log.RadarState.new_message() self.radar_state.mdMonoTime = sm.logMonoTime['modelV2'] - self.radar_state.radarErrors = list(rr.errors) + self.radar_state.radarErrors = rr.errors self.radar_state.carStateMonoTime = sm.logMonoTime['carState'] - - if len(sm['modelV2'].temporalPose.trans): - model_v_ego = sm['modelV2'].temporalPose.trans[0] + # SensorDirty is the radar's own obstruction self-report. With live + # measured tracks it must not soft-disable or lock out re-engage + # (I-40 gorge, Oct 4 03:03:59 CT). Only that one flag is masked, and only + # until it persists with no live tracks (SENSOR_DIRTY_PERSIST_S). + sensor_dirty_flag = bool(getattr(rr.errors, 'radarUnavailableTemporary', False)) + sensor_dirty_mask = self.sensor_dirty.update( + sensor_dirty_flag, self._live_measured and not radar_timed_out, DT_MDL, + ignore=self.read_sensor_dirty_ignore()) + if sensor_dirty_mask: + self.radar_state.radarErrors.radarUnavailableTemporary = False + + if len(sm['modelV2'].velocity.x): + model_v_ego = sm['modelV2'].velocity.x[0] else: model_v_ego = self.v_ego leads_v3 = sm['modelV2'].leadsV3 + # Prefer is default (Radar Enabled + healthy). Auto wiper is not required. + # Unhealthy / disabled → stock fusion. Path/oncoming gates still apply. + # Health first so association uses the new prefer; HUD after so a + # path-associated lead can suppress clutter / timeout flashes. + healthy = self.reliability.update( + tracks=self.tracks, errors=self.radar_state.radarErrors, v_ego=self.v_ego, + timed_out=radar_timed_out, + ignore_hw_fail=self.rain_gate.read_ignore_hw_fail(), + engaged=self.engaged) + self.rain_gate.set_reliable(healthy, alert=False) + radar_prefer = bool(self.rain_gate.update()) + path_x, path_y = model_path_xy(sm['modelV2']) + try: + lane_probs = list(sm['modelV2'].laneLineProbs) + except (TypeError, AttributeError): + lane_probs = None + collapsed = path_model_collapsed(lane_probs, path_x, path_y) + lead_one: dict[str, Any] = {'status': False} if len(leads_v3) > 1: - self.radar_state.leadOne = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[0], model_v_ego, low_speed_override=True) - self.radar_state.leadTwo = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[1], model_v_ego, low_speed_override=False) + lead_one = self.lead_one_association.update( + self.v_ego, self.ready, self.tracks, leads_v3[0], model_v_ego, + rain_hold=radar_prefer, radar_prefer=radar_prefer, + path_x=path_x, path_y=path_y, collapsed=collapsed) + self.radar_state.leadOne = lead_one + self.radar_state.leadTwo = self.lead_two_association.update( + self.v_ego, self.ready, self.tracks, leads_v3[1], model_v_ego, + rain_hold=radar_prefer, radar_prefer=radar_prefer, + path_x=path_x, path_y=path_y, collapsed=collapsed) + path_lead = bool(lead_one.get('status') and lead_one.get('radar')) + self.reliability.set_path_lead(path_lead) + self.rain_gate.set_reliable(healthy, alert=self.reliability.should_alert) + if hasattr(self.radar_state, "radarPreferFallback"): + # Degraded SensorDirty reuses the existing fallback event (selfdrived maps it to a + # WARNING, never a disable); events.py words it from radarPreferReason. + self.radar_state.radarPreferFallback = bool(self.rain_gate.fallback_alert) or sensor_dirty_mask + if hasattr(self.radar_state, "radarPreferReason"): + self.radar_state.radarPreferReason = reason_token(self.reliability.log_reason, sensor_dirty_mask) + if self._obstacle_pending: + self._stash_obstacle(sm, rr, path_x, path_y, leads_v3) + + def _update_ground(self, t: float, sm) -> None: + """Publish each track's ground-frame lateral speed. Failures leave vLat at 0.""" + try: + # model orientationRate.z is +right. yRel and vLat are +left. + yaw_left = -model_yaw_rate_right(sm['modelV2']) + points = [(int(tr.identifier), float(tr.dRel), float(tr.yRel)) for tr in self.tracks.values()] + speeds = self._ground.update(float(t), float(self.v_ego_hist[0]), yaw_left, points) + except Exception: + cloudlog.exception("ground lateral speed failed") + return + for tid, speed in speeds.items(): + tr = self.tracks.get(tid) + if tr is not None: + tr.vLat = float(speed) + + def _cone_logging(self) -> bool: + """NAPConeLineLog, cached ~1 s. Default On. Missing params stay On.""" + now = self.current_time if self.current_time else 0.0 + if self._cone_log_check_t >= 0.0 and now - self._cone_log_check_t < 1.0: + return self._cone_log_on + self._cone_log_check_t = now + try: + self._cone_log_on = bool(Params().get_bool(PARAM_CONE_LINE_LOG)) + except Exception: + self._cone_log_on = True + return self._cone_log_on + + def _update_cone_line(self, sm, points, dt: float) -> None: + """One O(n) scan at radar rate. Failures stay off the lead path.""" + if not self._cone_logging(): + # One inactive sample so a held line starts its clear timer, then silence. + was_active = self._cone_sample is not None and self._cone_sample.active + self._cone.reset() + self._cone_sample = ConeLineSample() if was_active else None + self._cone_dirty = self._cone_sample is not None + return + try: + path_x, path_y = model_path_xy(sm['modelV2']) + model = sm['modelV2'] + self._cone_sample = self._cone.update( + points, self.v_ego, path_x, path_y, road_edges_xy(sm['modelV2']), dt, + model_yaw_rate_right(sm['modelV2']), + lead_xs=_cone_lead_xs(sm['modelV2'], self.radar_state), + room_right=lane_room_m(model, 1), room_left=lane_room_m(model, -1)) + self._cone_dirty = True + except Exception: + cloudlog.exception("cone line detector failed") + self._cone_sample = None + self._cone_dirty = False + + def _stash_obstacle(self, sm, rr, path_x, path_y, leads_v3) -> None: + """Copy the inputs the scan needs. Failures stay off the lead path.""" + try: + points = [_radar_point(pt) for pt in rr.points] + except Exception: + cloudlog.exception("path obstacle stash failed") + self._obstacle_inputs = None + self._obstacle_pending = False + return + lead_ids: list = [] + model_leads: list = [] + try: + leads_v2 = sm['modelV2'].leads + radar_leads = [] + if self.radar_state is not None: + radar_leads = [_radar_lead(self.radar_state.leadOne), _radar_lead(self.radar_state.leadTwo)] + lead_ids, model_leads = vehicle_exclusion_points( + _model_lead_tuples(leads_v3, xyva=False), + _model_lead_tuples(leads_v2, xyva=True), + [lead for lead in radar_leads if lead is not None], + ) + except Exception: + lead_ids, model_leads = [], [] + try: + lane = _lane_prob_min(sm['modelV2']) + path_std = _path_y_std_3s(sm['modelV2']) + except Exception: + lane, path_std = 1.0, None + self._obstacle_inputs = { + "points": points, + "dt": float(self._obstacle_dt), + "v_ego": float(self.v_ego), + "path_x": list(path_x) if path_x is not None else None, + "path_y": list(path_y) if path_y is not None else None, + "lead_ids": lead_ids, + "model_leads": model_leads, + "cone": _cone_hint(self._cone_sample), + "lane_prob_min": lane, + "path_y_std": path_std, + # Same model yaw the cone-line scan uses. No extra carState reader. + "yaw_rate": model_yaw_rate_right(sm['modelV2']), + } - def publish(self, pm: messaging.PubMaster, lag_ms: float): + def run_obstacle(self, pm) -> None: + """Radar scan and pathObstacleNAP publish. Call after radarState is sent.""" + if not self._obstacle_pending: + return + self._obstacle_pending = False + inputs = self._obstacle_inputs + self._obstacle_inputs = None + if not inputs: + return + try: + hit = self._obstacle.step( + inputs["points"], inputs["v_ego"], inputs["path_x"], inputs["path_y"], inputs["dt"], + inputs["lead_ids"], inputs["cone"], inputs["model_leads"], time.monotonic(), + inputs.get("yaw_rate", 0.0), + ) + if hit is None or pm is None: + return + self._publish_obstacle(pm, hit, inputs) + except Exception: + cloudlog.exception("path obstacle radar stage failed") + self._obstacle.note_failure() + + def _publish_obstacle(self, pm, hit, inputs) -> None: + msg = messaging.new_message("pathObstacleNAP", valid=True) + dest = msg.pathObstacleNAP + hit_to_msg(hit, dest) + dest.laneProbMin = float(inputs.get("lane_prob_min", 1.0)) + std = inputs.get("path_y_std") + dest.pathYStd3s = float("nan") if std is None else float(std) + dest.overBudget = hit.reject_reason == "over_budget" + dest.heartbeat = bool(self._obstacle.heartbeat) + pm.send("pathObstacleNAP", msg) + + def publish(self, pm: messaging.PubMaster): assert self.radar_state is not None radar_msg = messaging.new_message("radarState") radar_msg.valid = self.radar_state_valid radar_msg.radarState = self.radar_state - radar_msg.radarState.cumLagMs = lag_ms pm.send("radarState", radar_msg) - - # publish tracks for UI debugging (keep last) - tracks_msg = messaging.new_message('liveTracks', len(self.tracks)) - tracks_msg.valid = self.radar_state_valid - for index, tid in enumerate(sorted(self.tracks.keys())): - tracks_msg.liveTracks[index] = { - "trackId": tid, - "dRel": float(self.tracks[tid].dRel), - "yRel": float(self.tracks[tid].yRel), - "vRel": float(self.tracks[tid].vRel), - } - pm.send('liveTracks', tracks_msg) + if self._cone_dirty: + self._cone_dirty = False + try: + publish_cone_line(pm, self._cone_sample) + except Exception: + cloudlog.exception("coneLineNAP publish failed") + + +def _cone_lead_xs(model, radar_state) -> list[float]: + """Camera-x ranges of leads in our lane, for the cone-shift lead-in-span gate.""" + out: list[float] = [] + try: + for lead in list(model.leadsV3)[:2]: + if float(lead.prob) >= 0.5 and len(lead.x): + out.append(float(lead.x[0])) + except Exception: + pass + for name in ("leadOne", "leadTwo"): + try: + lead = getattr(radar_state, name) + if bool(lead.status) and abs(float(lead.yRel)) < 1.8: + out.append(float(lead.dRel) + RADAR_TO_CAMERA_M) + except Exception: + continue + return out # fuses camera and radar data for best lead detection @@ -286,31 +779,19 @@ def main() -> None: CP = messaging.log_from_bytes(Params().get("CarParams", block=True), car.CarParams) cloudlog.info("radard got CarParams") - # import the radar from the fingerprint - cloudlog.info("radard is importing %s", CP.carName) - RadarInterface = importlib.import_module(f'opendbc.car.{CP.carName}.radar_interface').RadarInterface - # *** setup messaging - can_sock = messaging.sub_sock('can') - sm = messaging.SubMaster(['modelV2', 'carState'], frequency=int(1./DT_CTRL)) - pm = messaging.PubMaster(['radarState', 'liveTracks']) - - RI = RadarInterface(CP) + sm = messaging.SubMaster(['modelV2', 'carState', 'liveTracks'], poll='modelV2') + pm = messaging.PubMaster(['radarState', 'coneLineNAP', 'pathObstacleNAP']) - rk = Ratekeeper(1.0 / CP.radarTimeStep, print_delay_threshold=None) - RD = RadarD(CP.radarTimeStep, RI.delay) + RD = RadarD(CP.radarDelay) while 1: - can_strings = messaging.drain_sock_raw(can_sock, wait_for_one=True) - rr: structs.RadarData | None = RI.update(can_capnp_to_list(can_strings)) - sm.update(0) - if rr is None: - continue - - RD.update(sm, rr) - RD.publish(pm, -rk.remaining*1000.0) + sm.update() - rk.monitor_time() + if sm.updated['modelV2']: + RD.update(sm, sm['liveTracks']) + RD.publish(pm) + RD.run_obstacle(pm) if __name__ == "__main__": diff --git a/selfdrive/controls/tests/sight_cap_replay/corner_1010_174045.json.gz.b64 b/selfdrive/controls/tests/sight_cap_replay/corner_1010_174045.json.gz.b64 new file mode 100644 index 00000000000000..a23e1882f66138 --- /dev/null +++ b/selfdrive/controls/tests/sight_cap_replay/corner_1010_174045.json.gz.b64 @@ -0,0 +1,868 @@ +H4sIAEKNy2oC/7y97Y4rPZMceCvG87u6Ufwm31sxjMHAnoW9axuGx7uYhbH3vhWR +ZJIsVUlVks6Dc1qnj1qtVkuhZGZkZOT//us//q+//vGXWX/M+u9M+odf/+HDX8tf +/+f//a//67/893/65//xL//2T//tf/znv/5h3fLX//E///m//cu//vWPf/+//9q+ +6cea35KXv/6f7YvmN+Xt03/bvrb+rsv6a7ePsthfs7jftITtI2/XGYML/xsXk3/D +Yi1uk7YvOrd9l8vbZ97/5iWY7ashb7eLcfuO5Lf7yXa7ruALZsV9G7Pifuy63d44 +8+u3O7a4DA5fjQFfTQmfF9zSrrjemrT9JOu2e/gPy1//77/qAz78MLjAr7I6XARc +5O3C4Asm1N/Txu3C4TOP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y5wdDBB5UsgqdFf3TT8wofRwMpZ5zsByDICFDHgWYXdn33jzKhMNb1 ++21zX5BKeWVW+VmFt9AyXNtmcycRN/Yt7rvnEwouZcUVZUXEQoJl939gtHdlv0VC +VQsmIbYhLfDCUPaCjRNIrJQUu/FuWS4oxVEhs8ofQsbx5EkdBf73IeiB39343cG/ +c0EE9JYk3UmFWNX8waG3wPfm4vhnOLVQk8rQMUhY3h9tg1o0i/p1k3vvOIbUEsio +jHXurKJsVZ1UzSxDl/98zSqq6XIKm4LVcHLatBS+KNmFocS/5WAa6tlSTxPH/Ndq +mQxquzPee4klp9HEu++b/ef75v/7//8Htel916ygAgA= diff --git a/selfdrive/controls/tests/sight_cap_replay/moving_lead_1007_204158.json.gz.b64 b/selfdrive/controls/tests/sight_cap_replay/moving_lead_1007_204158.json.gz.b64 new file mode 100644 index 00000000000000..d53688afe99f78 --- /dev/null +++ b/selfdrive/controls/tests/sight_cap_replay/moving_lead_1007_204158.json.gz.b64 @@ -0,0 +1,697 @@ +H4sIAEKNy2oC/8y9244ku7Ik9ivCfs5e4P1yfkXQgzBz9KKRBEiCpMFA/65wc9JJ +RpCREZmRfYTenbtWXbKqq6zMb+bm/+1f/+n//Ne//UurPyr+d0b9m9P/5tO/Xv/6 +n/73//F/+ff/41//9t//t39tb/9jzD/q9a//61//ZvQ/KbnXv/6f7U1qe536x2x/ +84vebv8JL7/9TdvLml6p3fZWTf+5fbx5mbC9zmp6iP+4l7P/2JfL/8SXD//4V7Db +S1Fv7xfzP/qV4va6HOgJlN/eUW9PFl/auO3V2rrt02jn6a3bB2+fLsTtY3RM9Nas +tvc0ymyfw2wflf6H17/+6/8hX+/0r6YH+pcoSw+eHtL2oOkN2tFDLP9Wgwd6lQn0 +QO9m6d0sfailD7X0Okfv5+hdXN4ePL3V05MEeudAb4j0UqTXJUNf5PY1/qEvaPew +/Frpi1D04drWLwxfhKPPHyJ+MPofvX2r6AvR/8S0/Zy29zX01Zh/st1+ZDZuD9tP +dPtR5e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z67Z+TrBXwqe4jCeq/HgPtGGP +3C62SigibCdoI00aANrMwUxSoOG1LjoedMMX3S1YMIOjZa4LtkNhW3s8g21V2Bb1 +gQqq+sG3HZw6lmhpZmfg6BScdDxEJKcxdNVfwtxsbJEYWdcJg0uwhFyMr8M2+gY3 +OUm3eGrW8JOvfvtYeVLZI89Ckdd/CtexR3WJE2fD/i5uz/Zh21pBO9y66mnZkMxV +L/bR+NaLLWorZM32ylUBbc/WIVRuhJZyK5UnO9THx26PeqiydHfiDiHRo0x8aaaa +i7Az2PpZqXW3fkO4/DleC8Odwsa5KXo1u/9mzO/gtZlQIjlXt7iVZHKqo1hKUOgz +nKvbfHMLH77quRemTat0+E0aLA/nnPK1MlsPzWw+9LLd+gKsCasPYc3Y5A3ep7Lx +DLI9qH0FvaV8MJD8AK/7GiyuLS5Rqz8WRbZ+azj0gRZEkDZbd4yon4twQOFhL9AS +H3/fjntRY+jZciqLt/V4hdrD4oD2piJzQZhQ0PFLEt2k3IrlqXyBDC8cGcZIFqM8 +jT8v56hFK8qnJxlsq17LJCCnv4LtUNjayrKqOriQYh5o8wQn6uBssXbkKhTVpylb +rCvFXA3LqudcBO9ph8vcYYgaf6NKe4Nd7l4MOT6fGVYONyhhME2XS3eNZtlb5dbQ +sUlJNAmyQazMz5uDtNF009YiLM8cHtKiC5fwAQETqtqtsMp7rHsT00kSjCQMQTws +vlwDkMXuZ9vYptuPD7NtEkfeFMD+qmxjOzuAVglX2RV3rmsnot7eg2xj1IJ8ovzz +7z///g9sSYRq9bgCAA== diff --git a/selfdrive/controls/tests/sight_cap_replay/straight_1010_1758.json.gz.b64 b/selfdrive/controls/tests/sight_cap_replay/straight_1010_1758.json.gz.b64 new file mode 100644 index 00000000000000..83a3ab628cc4b9 --- /dev/null +++ b/selfdrive/controls/tests/sight_cap_replay/straight_1010_1758.json.gz.b64 @@ -0,0 +1,1035 @@ +H4sIAEKNy2oC/+S9244kSZKe+SqLuvYqmJ5V+1UIXhAzzZvt3QGGC3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+giT9xF91QsaXi0maHV2rUi00qAKFZHsaWiKRUuiSfE3ucFOki +spmalBQLcwxlTC3FQ5Y+QAJI+vm08PQ9AhIEG2y7QEupRKJA4aqSxsVYgxF9uLI0 +O+K+dG/zRqC0lM0JA38yTgoVu66mdiqW35YFSqjRi/ziHDI8b0KP7yjlFh7qafYD +TZJsL24SKvoAlohqioUMKaMh0bP0OgjGHdpQCfFArx8Qvm84oFRYeAEL7yof1P4G +Qu/3O90EtIfmOM009En5XU7zZUB9BDR5oGJLZaVtgQdqogcqiU/zwGYHmGZLPfZY +iueQtaI005tP2+FTdmIk983zCycvz/U33d+37ONjw72wx9TBT7TlohE7htG54gtU +zuRARYllLCVtm5rhMln2xOVGXG7EpSLLHh44nqDJHTD0arizaampHvvqHXmTnux2 +II81IL25ISUvkEjCeSaBbKqA+hKX2+/m0hxzeT9s98fBey2OE2H7bPazcxBkCZlb +PqqMy+pA0/8VnDxyOmXT6aQCeu10OkJzI6fTkdPpHhg8sqS5xBahuZHTacjpNHA6 +PZxOzZxOWzmdCk6n/xGTfkUy72aV5i+4m448plAn/Rnku9VVlutNtzqPa0Vi5lji +sR3fshkltLZFKMVyO26jHS/8zCLXGWDHFYJ0gSBdQi8tgnQFvXTQS4dznfqX3Z9b +VnkXE1SOr7bXz2NjXtC6X9rq3dy+eOF4wsUsyLSRzHGt6KxcdmN014jRLYvRzaIY +XXx0R96i3rppwRw/5esV2m5j8lhkZgj2345+/07i0N/XtHK34Kq04C4iKdQiJMMD +K8A1hefo1TSUlbSUvszSRnISSQEkFZAUQNIunjs+vQ9vrJNXWumWcylzd8XH32f8 ++5ZkP93g0QduZcnkglTmViLp30h6F+7niWyvVmkfWGFjycd05D96+rxA6avCfm+w +3xvst0a8E1gcLm7HO+ZEQf24EqR6pcrbl43l9LOIqrssqiiPkUWX344IE0BuK4H0 +NDlaEBkikeoKka26j3lgfE1TvIzNX4Y4s7ROCce5HIHcugDPTxor1H08ejws6j7U +GA9gn1/vfrA4OT60HeIRp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XXA9U7nu6o3dLnJV0 +Utd43Ocu6n9cKXF6DGnLmltRMinKmnv7AFoBFXZa8HLVhjU+UVqyMehAeizZiHR2 +8pZ4+FrNvWa/PbuBekEK95q+48jA0zAESiYXHjpGC2JiBfISP9aSTvoYxnwD66Yu +EqQ4J0hFBOmIIM0HujeeNlnRziGCjJrMmlkjeoiOaYiOSaZjL0GQAWJOAjW3/Fc2 +DleH0M0Z1E8QuWJE5/reH4XJF7dbsI387e8waQiTxtYVd0iY1Hq9tqFj4ii6I4kk +A2FyI0xawqT9wGne0D9YAjDsYD3h1BNTYpm/vxghkl1nr7bZJZkRtLd/D5N+NiB0 +Z5f0l5w777kdjzxjmz4k8zxm9Tcz4X4BlSe4xOTahhKX5hjgfHE5bphfTSbDBya1 +B1d6wqX9QIDJUzso2W87cKVjXkkaIqIbuJJmlGiqo1An4bsAqVti/e1RefNKzd25 +SLGlvJi4C8x1nmQTmWu9H8NbP9F0G4/4SKe6QfwnXp0EiC/8nNrv9v7n//v/STt6 +Lr2NBQA= diff --git a/selfdrive/controls/tests/test_alerts.py b/selfdrive/controls/tests/test_alerts.py deleted file mode 100644 index 52d71dc22dd68b..00000000000000 --- a/selfdrive/controls/tests/test_alerts.py +++ /dev/null @@ -1,130 +0,0 @@ -import copy -import json -import os -import random -from PIL import Image, ImageDraw, ImageFont - -from cereal import log, car -from cereal.messaging import SubMaster -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.selfdrive.controls.lib.events import Alert, EVENTS, ET -from openpilot.selfdrive.controls.lib.alertmanager import set_offroad_alert -from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS - -AlertSize = log.SelfdriveState.AlertSize - -OFFROAD_ALERTS_PATH = os.path.join(BASEDIR, "selfdrive/controls/lib/alerts_offroad.json") - -# TODO: add callback alerts -ALERTS = [] -for event_types in EVENTS.values(): - for alert in event_types.values(): - ALERTS.append(alert) - - -class TestAlerts: - - @classmethod - def setup_class(cls): - with open(OFFROAD_ALERTS_PATH) as f: - cls.offroad_alerts = json.loads(f.read()) - - # Create fake objects for callback - cls.CS = car.CarState.new_message() - cls.CP = car.CarParams.new_message() - cfg = [c for c in CONFIGS if c.proc_name == 'controlsd'][0] - cls.sm = SubMaster(cfg.pubs) - - def test_events_defined(self): - # Ensure all events in capnp schema are defined in events.py - events = car.OnroadEvent.EventName.schema.enumerants - - for name, e in events.items(): - if not name.endswith("DEPRECATED"): - fail_msg = "%s @%d not in EVENTS" % (name, e) - assert e in EVENTS.keys(), fail_msg - - # ensure alert text doesn't exceed allowed width - def test_alert_text_length(self): - font_path = os.path.join(BASEDIR, "selfdrive/assets/fonts") - regular_font_path = os.path.join(font_path, "Inter-SemiBold.ttf") - bold_font_path = os.path.join(font_path, "Inter-Bold.ttf") - semibold_font_path = os.path.join(font_path, "Inter-SemiBold.ttf") - - max_text_width = 2160 - 300 # full screen width is usable, minus sidebar - draw = ImageDraw.Draw(Image.new('RGB', (0, 0))) - - fonts = { - AlertSize.small: [ImageFont.truetype(semibold_font_path, 74)], - AlertSize.mid: [ImageFont.truetype(bold_font_path, 88), - ImageFont.truetype(regular_font_path, 66)], - } - - for alert in ALERTS: - if not isinstance(alert, Alert): - alert = alert(self.CP, self.CS, self.sm, metric=False, soft_disable_time=100, personality=log.LongitudinalPersonality.standard) - - # for full size alerts, both text fields wrap the text, - # so it's unlikely that they would go past the max width - if alert.alert_size in (AlertSize.none, AlertSize.full): - continue - - for i, txt in enumerate([alert.alert_text_1, alert.alert_text_2]): - if i >= len(fonts[alert.alert_size]): - break - - font = fonts[alert.alert_size][i] - left, _, right, _ = draw.textbbox((0, 0), txt, font) - width = right - left - msg = f"type: {alert.alert_type} msg: {txt}" - assert width <= max_text_width, msg - - def test_alert_sanity_check(self): - for event_types in EVENTS.values(): - for event_type, a in event_types.items(): - # TODO: add callback alerts - if not isinstance(a, Alert): - continue - - if a.alert_size == AlertSize.none: - assert len(a.alert_text_1) == 0 - assert len(a.alert_text_2) == 0 - elif a.alert_size == AlertSize.small: - assert len(a.alert_text_1) > 0 - assert len(a.alert_text_2) == 0 - elif a.alert_size == AlertSize.mid: - assert len(a.alert_text_1) > 0 - assert len(a.alert_text_2) > 0 - else: - assert len(a.alert_text_1) > 0 - - assert a.duration >= 0. - - if event_type not in (ET.WARNING, ET.PERMANENT, ET.PRE_ENABLE): - assert a.creation_delay == 0. - - def test_offroad_alerts(self): - params = Params() - for a in self.offroad_alerts: - # set the alert - alert = copy.copy(self.offroad_alerts[a]) - set_offroad_alert(a, True) - alert['extra'] = '' - assert json.dumps(alert) == params.get(a, encoding='utf8') - - # then delete it - set_offroad_alert(a, False) - assert params.get(a) is None - - def test_offroad_alerts_extra_text(self): - params = Params() - for i in range(50): - # set the alert - a = random.choice(list(self.offroad_alerts)) - alert = self.offroad_alerts[a] - set_offroad_alert(a, True, extra_text="a"*i) - - written_alert = json.loads(params.get(a, encoding='utf8')) - assert "a"*i == written_alert['extra'] - assert alert["text"] == written_alert['text'] diff --git a/selfdrive/controls/tests/test_crossing_vehicle.py b/selfdrive/controls/tests/test_crossing_vehicle.py new file mode 100644 index 00000000000000..738f396005efce --- /dev/null +++ b/selfdrive/controls/tests/test_crossing_vehicle.py @@ -0,0 +1,282 @@ +"""Crossing / turning vehicle in the longitudinal law. + +E1, 14:44:34–40, track 2842: a side-on car turned across the lane. Radar +held the glint near the centreline, the car braked as if it were stopped, +and long did not move again until the stalk. A crosser slows gently and +starts accelerating when the tail's exit sweep begins. A stopped car in +the lane still gets the normal brake. Gas touched during the brake stays +paused. Stationary roadside returns (E2) are not crossers. +""" +import math + +import pytest + +from openpilot.selfdrive.controls.lib.crossing_vehicle import ( + CROSS_VY_MS, + X2_ROOM_FRAC, + GroundLateral, + crossing_may_resume, +) +from openpilot.selfdrive.controls.lib.unified_lead import ( + UnifiedLeadController, + kinematic_required_accel, + kinematic_room_m, +) +from openpilot.selfdrive.controls.radard import KalmanParams, Track +from openpilot.selfdrive.controls.tests.test_radard import RadarScenario + +DT = 0.05 +RADAR_DT = 0.125 +V_EGO = 13.2 +V_CEIL = 20.0 +T_FOLLOW = 0.7 +GAP0 = 80.0 + + +def _e1_y(t: float) -> float: + """Ego-frame y, +left. Entry, glint on the centreline, then the tail leaves.""" + if t < 0.90: + return 0.10 + (1.70 / 0.90) * t + if t < 1.40: + u = (t - 0.90) / 0.50 + return 1.80 + (0.45 - 1.80) * u + if t < 3.40: + return 0.45 + if t < 4.30: + u = (t - 3.40) / 0.90 + return 0.45 + 1.05 * u + return 1.50 + + +def _vlat_at(t: float, y_of) -> float: + """Ground-frame lateral speed from the yaw-corrected fit, held between radar frames.""" + ground = GroundLateral() + last = 0.0 + n = int(math.floor(t / RADAR_DT + 1e-9)) + for i in range(n + 1): + tr = i * RADAR_DT + if tr > t + 1e-9: + break + gap = max(8.0, GAP0 - V_EGO * tr) + speeds = ground.update(tr, V_EGO, 0.0, [(2842, gap, y_of(tr))]) + last = float(speeds.get(2842, 0.0)) + return last + + +def _run(y_of, *, v_lat_of=None, model_prob=0.25, long_on_of=None, v_lead=0.2, + seconds=5.0, v_ego=V_EGO, gap0=GAP0): + ctrl = UnifiedLeadController() + rows = [] + for k in range(int(round(seconds / DT))): + t = k * DT + gap = max(8.0, gap0 - v_ego * t) + y = float(y_of(t)) + v_lat = 0.0 if v_lat_of is None else float(v_lat_of(t)) + long_on = True if long_on_of is None else bool(long_on_of(t)) + a = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=T_FOLLOW, lead_id=2842, seed_a=0.0, v_ceiling=V_CEIL, + y_rel=y, radar=True, model_prob=model_prob, v_lat=v_lat, long_on=long_on, + ) + rows.append((t, y, a, bool(ctrl.crossing_classified), bool(ctrl._cross.exit))) + return rows + + +def _median(vals): + ordered = sorted(vals) + return ordered[len(ordered) // 2] + + +def test_ground_lateral_ignores_ego_yaw_and_keeps_a_real_sweep(): + """A stopped point while we yaw stays near 0. A 1.5 m/s sweep does not.""" + yaw = 0.05 + spinning = GroundLateral() + moving = GroundLateral() + last_spin = 0.0 + last_move = 0.0 + for i in range(16): + t = i * RADAR_DT + heading = yaw * t + d_rel = 80.0 * math.cos(heading) + y_rel = -80.0 * math.sin(heading) + last_spin = spinning.update(t, 0.0, yaw, [(1, d_rel, y_rel)]).get(1, 0.0) + last_move = moving.update(t, V_EGO, 0.0, [(2, 70.0, 1.5 * t)]).get(2, 0.0) + assert abs(last_spin) < 0.35 + assert last_move == pytest.approx(1.5, abs=0.25) + assert last_move > CROSS_VY_MS + + +def test_e1_turning_car_slows_gently_and_reaccelerates_as_the_tail_leaves(): + rows = _run(_e1_y, v_lat_of=lambda t: _vlat_at(t, _e1_y), model_prob=0.25) + glint = [a for t, y, a, classified, _exit in rows if 2.2 <= t <= 3.2] + assert glint, "no glint samples" + assert all(classified for t, y, a, classified, _exit in rows if 2.2 <= t <= 3.2) + glint_a = _median(glint) + # Slowing, and not the stopped-object brake. + assert -0.95 < glint_a < -0.05, glint_a + + stopped = _run(lambda t: 0.40, v_lat_of=lambda t: 0.0, model_prob=0.85) + stopped_glint = [a for t, y, a, classified, _exit in stopped if 2.2 <= t <= 3.2] + assert stopped_glint + assert not any(classified for _, _, _, classified, _ in stopped) + stopped_a = _median(stopped_glint) + assert stopped_a < -1.15, stopped_a + assert glint_a > stopped_a + 0.40 + + # Exit sweep starts at t=3.40, y=0.45, and the point is not clear until + # y=1.50 at t=4.30. The flag is the start of that sweep, and the command + # is already rising while the return is still in the lane. + exits = [(t, y, a) for t, y, a, classified, exited in rows if exited and t >= 3.4] + assert exits, "exit sweep never started" + t0, y0, a0 = exits[0] + assert t0 < 4.05, (t0, y0, a0) + assert y0 < 1.15, (t0, y0, a0) + before = [a for t, y, a, classified, exited in rows if 3.4 <= t < t0 and not exited] + assert before + rising = [(t, y, a) for t, y, a in exits if t0 + 0.20 <= t <= t0 + 0.40 and a >= before[-1] + 0.25] + assert rising, [(round(t, 2), round(y, 2), round(a, 2)) for t, y, a in exits[:6]] + t_rel, y_rel, a_rel = rising[0] + assert y_rel < 1.40, (t_rel, y_rel, a_rel) + + +def test_stopped_car_in_the_lane_gets_full_braking(): + rows = _run(lambda t: 0.30, v_lat_of=lambda t: 0.0, model_prob=0.90, v_lead=0.0) + assert not any(classified for _, _, _, classified, _ in rows) + early = [a for t, _, a, _, _ in rows if 1.0 <= t <= 2.5] + assert _median(early) < -1.20 + + +def test_crosser_with_gas_touched_stays_paused(): + """Gas during the crossing brake: no resume when the tail leaves, and lift is not a resume.""" + assert crossing_may_resume(True) + assert not crossing_may_resume(False) + + def long_on(t): + # Touched at 2.0 s. Still false after a lift; only the stalk would set it. + return t < 2.0 + + paused = _run(_e1_y, v_lat_of=lambda t: _vlat_at(t, _e1_y), long_on_of=long_on) + live = _run(_e1_y, v_lat_of=lambda t: _vlat_at(t, _e1_y), long_on_of=lambda t: True) + after = [a for t, _, a, _, _ in paused if t >= 2.0] + assert after + assert max(after) <= 0.05 + # The exit does not release the brake while longitudinal is paused. + at_touch = [a for t, _, a, _, _ in paused if abs(t - 2.0) < DT * 0.5][0] + late = [a for t, _, a, _, _ in paused if t >= 4.2] + assert max(late) <= at_touch + 0.15 + live_late = [a for t, _, a, _, _ in live if t >= 4.2] + assert _median(live_late) > _median(late) + 0.30 + + +def test_stationary_roadside_object_is_not_a_crosser(): + """E2: stopped returns beside the lane, including while we yaw. Not a crosser.""" + yaw = 0.04 + world_x, world_y = 90.0, 1.3 + # Same bicycle step GroundLateral uses, so a fixed world point has no lateral speed. + poses = [] + heading = 0.0 + x_ego = 0.0 + y_ego = 0.0 + for i in range(24): + if i: + heading += yaw * RADAR_DT + x_ego += V_EGO * math.cos(heading) * RADAR_DT + y_ego += V_EGO * math.sin(heading) * RADAR_DT + poses.append((heading, x_ego, y_ego)) + + def measure(t): + i = min(len(poses) - 1, int(math.floor(t / RADAR_DT + 1e-9))) + h, xe, ye = poses[i] + dx, dy = world_x - xe, world_y - ye + d_rel = dx * math.cos(h) + dy * math.sin(h) + y_rel = -dx * math.sin(h) + dy * math.cos(h) + return d_rel, y_rel + + ground = GroundLateral() + speeds = [] + ys = [] + for i in range(24): + t = i * RADAR_DT + d_rel, y_rel = measure(t) + ys.append(y_rel) + speeds.append(ground.update(t, V_EGO, yaw, [(2895, d_rel, y_rel)]).get(2895, 0.0)) + assert max(abs(v) for v in speeds) < CROSS_VY_MS + + def y_of(t): + return measure(min(t, 23 * RADAR_DT))[1] + + def v_of(t): + i = min(len(speeds) - 1, int(math.floor(t / RADAR_DT + 1e-9))) + return speeds[i] + + rows = _run(y_of, v_lat_of=v_of, model_prob=0.90, v_lead=0.0, seconds=3.0, gap0=70.0) + assert not any(classified for _, _, _, classified, _ in rows) + plain = _run(y_of, v_lat_of=lambda t: 0.0, model_prob=0.90, v_lead=0.0, seconds=3.0, gap0=70.0) + for got, base in zip(rows, plain): + assert abs(got[2] - base[2]) < 0.08 + + +def test_vision_lead_inside_55m_is_not_kept_as_a_crosser(): + """High model probability at the glint is a stopped lead, even if y is sweeping.""" + rows = _run(_e1_y, v_lat_of=lambda t: _vlat_at(t, _e1_y), model_prob=0.85, gap0=40.0, seconds=3.0) + assert not any(classified for _, _, _, classified, _ in rows) + mid = [a for t, _, a, _, _ in rows if 2.0 <= t <= 2.8] + assert _median(mid) < -1.0 + + +def test_imminent_overlap_returns_to_the_normal_brake_without_a_step(): + rows_far = _run(_e1_y, v_lat_of=lambda t: _vlat_at(t, _e1_y), seconds=3.2) + assert any(classified for _, _, _, classified, _ in rows_far) + gentle = _median([a for t, _, a, _, _ in rows_far if 2.4 <= t <= 3.0]) + # Same crosser, but the gap is already inside the stop-now distance. + close = _run(_e1_y, v_lat_of=lambda t: _vlat_at(t, _e1_y), seconds=3.2, gap0=12.0) + late = [a for t, _, a, _, _ in close if 2.6 <= t <= 3.1] + assert _median(late) < gentle - 0.50 + prev = close[0][2] + for _, _, a, _, _ in close[1:]: + assert a - prev >= -2.5 * DT - 0.02 + prev = a + + +def test_along_traffic_and_a_pulling_away_cutin_are_not_crossers(): + sweeping = _run(_e1_y, v_lat_of=lambda t: _vlat_at(t, _e1_y), v_lead=V_EGO + 3.0, seconds=2.0) + assert not any(classified for _, _, _, classified, _ in sweeping) + assert min(a for _, _, a, _, _ in sweeping) >= -0.05 + + +def test_x2_caps_room_shortening_for_a_stopped_lead_only(): + v, gap = 13.2, 118.0 + slack = gap - 6.0 + room = kinematic_room_m(slack, v, T_FOLLOW, 0.0) + assert room >= X2_ROOM_FRAC * slack - 1e-6 + a = -(v * v) / (2.0 * room) + assert -1.25 <= a <= -0.90 + moving = kinematic_room_m(slack, v, T_FOLLOW, 20.0) + assert moving < X2_ROOM_FRAC * slack + # Close stopped car: the floor does not take the brake away. + close = kinematic_required_accel(24.0, 13.0, T_FOLLOW, 0.0) + assert close <= -1.5 + + +def test_track_radar_state_carries_ground_lateral_speed(): + tr = Track(2842, 0.0, KalmanParams(0.05)) + tr.update(40.0, 0.4, -V_EGO, 0.0, True, KalmanParams(0.05)) + tr.vLat = 1.4 + assert tr.get_RadarState(0.3)["vLat"] == pytest.approx(1.4) + + +def test_radard_fit_publishes_a_leftward_sweep_and_not_a_fixed_point(): + scenario = RadarScenario(v_ego=V_EGO) + t = 0.0 + for i in range(10): + t = i * RADAR_DT + y = 1.6 * t + scenario.step(t, vision_d_rel=60.0, radar_points=[(2842, 60.0, y, -V_EGO)], vision_prob=0.3) + sweep = scenario.radar.tracks[2842].vLat + assert sweep > CROSS_VY_MS + + still = RadarScenario(v_ego=V_EGO) + for i in range(10): + t = i * RADAR_DT + still.step(t, vision_d_rel=60.0, radar_points=[(2895, 60.0, 1.2, -V_EGO)], vision_prob=0.9) + assert abs(still.radar.tracks[2895].vLat) < 0.35 diff --git a/selfdrive/controls/tests/test_curve_follow.py b/selfdrive/controls/tests/test_curve_follow.py new file mode 100644 index 00000000000000..eec746ed2ed343 --- /dev/null +++ b/selfdrive/controls/tests/test_curve_follow.py @@ -0,0 +1,495 @@ +"""Curve-follow: the continuous curve term in the longitudinal planner (Pre-AP). + +The road ahead is a speed envelope (the unchanged conservative lateral table) +and its most limiting point is a virtual lead. The term is a ceiling on +acceleration: exactly FREE on a straight, lower only when the path ahead +asks, released in proportion as the path opens, with no set speed and no latch. +""" +import json +import math +import time + +import numpy as np +import pytest + +import openpilot.selfdrive.controls.lib.curve_follow as cfmod +from openpilot.selfdrive.controls.lib.curve_follow import ( + CONF_FALL_1_S, + FREE_A_MS2, + LOG_PREFIX, + MODE_ACTIVE, + MODE_OFF, + MODE_SHADOW, + RELEASE_BEFORE_TIGHTEST_S, + CurveFollow, + curve_follow_raw, + format_log_line, + read_curve_follow_mode, +) +from openpilot.selfdrive.controls.lib.curve_max_hold import curve_speed_for_curvature +from openpilot.selfdrive.controls.tests.test_curve_preview import _bend_kappa +from openpilot.selfdrive.modeld.constants import ModelConstants + +DT = 0.05 +T = np.array(ModelConstants.T_IDXS) +TL = T.tolist() + + +def _road_k(s, bends): + """Signed curvature at arc length s (left +, right -). bends = (start, length, kappa).""" + return sum(_bend_kappa(s, *b) for b in bends) + + +def _path(v, s, bends): + xs = (v * T).tolist() + return TL, xs, [_road_k(s + x, bends) for x in xs] + + +def _step(cf, v, s, bends, **kw): + ts, xs, ks = _path(v, s, bends) + return cf.step(dt=DT, v_ego=v, ts=ts, ds=xs, ks=ks, **kw) + + +def _drive(bends, v0, seconds, v_max=40.0, cruise_gain=0.25, a_cruise_max=1.2, cf=None, **kw): + """Kinematic car, P cruise toward v_max, curve term as a ceiling (perfect path).""" + cf = CurveFollow() if cf is None else cf + s, v = 0.0, float(v0) + rows = [] + for k in range(int(round(seconds / DT))): + a_cf = _step(cf, v, s, bends, **kw) + a_cruise = max(-0.5, min(a_cruise_max, cruise_gain * (v_max - v))) + a = min(a_cruise, a_cf) + rows.append((k * DT, s, v, a, a_cf, cf)) + v = max(0.0, v + a * DT) + s += v * DT + return rows + + +def _brake_jerk(a_list): + """Largest |da/dt| where the ceiling is braking or just released. Above ~0 it is only a bound on +a.""" + worst = 0.0 + for a0, a1 in zip(a_list, a_list[1:], strict=False): + if a0 <= 0.05 and a1 <= 0.05: + worst = max(worst, abs(a1 - a0) / DT) + return worst + + +def _speed_at(rows, s_target): + return next(v for _, s, v, *_ in rows if s >= s_target) + + +def _time_at(rows, s_target): + return next(t for t, s, *_ in rows if s >= s_target) + + +# 1 --------------------------------------------------------------------- +@pytest.mark.parametrize("v", [5.0, 8.0, 15.0, 25.0, 35.0]) +def test_straight_returns_exactly_free(v): + cf = CurveFollow() + rng = np.random.default_rng(7) + for _ in range(200): + ks = (rng.normal(0.0, 0.0003, len(TL))).tolist() + a = cf.step(dt=DT, v_ego=v, ts=TL, ds=(v * T).tolist(), ks=ks, y_std=(0.3 + 0.2 * T).tolist()) + assert a == FREE_A_MS2 + assert cf.raw == FREE_A_MS2 and cf.limit_idx == -1 + + +# 2 --------------------------------------------------------------------- +@pytest.mark.parametrize("radius, v0", [(60.0, 15.0), (100.0, 20.0), (40.0, 12.0), (80.0, 20.0)]) +def test_constant_radius_bend_slows_early_gently_and_to_the_table(radius, v0): + start = 160.0 + bends = [(start, 80.0, 1.0 / radius)] + rows = _drive(bends, v0, 26.0, v_max=v0) + v_env = curve_speed_for_curvature(1.0 / radius) + t_entry = _time_at(rows, start) + t_on = next(t for t, _, _, a, *_ in rows if a < -0.05) + assert t_entry - t_on >= 3.0 + assert _speed_at(rows, start) <= v_env * 1.15 + assert min(a for _, _, _, a, *_ in rows) >= -1.05 + assert _brake_jerk([r[4] for r in rows]) <= 2.1 + # Inside the arc the car holds the table speed, it is not pushed below it. + mid = _speed_at(rows, start + 50.0) + assert v_env * 0.85 <= mid <= v_env * 1.15 + + +# 3 --------------------------------------------------------------------- +def test_small_deficit_is_a_gentle_lift_not_a_brake(): + v_env = curve_speed_for_curvature(1.0 / 150.0) + v0 = v_env + 1.2 + rows = _drive([(150.0, 200.0, 1.0 / 150.0)], v0, 14.0, v_max=v0) + a_cf = [r[4] for r in rows] + assert min(a_cf) >= -0.45 + assert min(a_cf) < -0.02 + assert _brake_jerk(a_cf) <= 1.2 + + +# 4 --------------------------------------------------------------------- +def test_tightening_spiral_keeps_deepening_within_the_jerk_limit(): + # Radius shrinks 200 -> 35 m over the road: each later point asks for less speed. + bends = [(120.0 + 45.0 * i, 45.0, 1.0 / r) for i, r in enumerate((200.0, 140.0, 95.0, 65.0, 45.0, 35.0))] + rows = _drive(bends, 17.0, 45.0, v_max=17.0) + a = [r[3] for r in rows] + assert min(a) < -0.3 + k_min = int(np.argmin(a)) + # No release while the road is still tightening. + rising = [a[i + 1] - a[i] for i in range(k_min)] + assert max(rising) <= 0.12 + assert _brake_jerk([r[4] for r in rows]) <= 2.1 + # Cornering stays on the table at the tightest arc. + assert _speed_at(rows, 120.0 + 45.0 * 5 + 20.0) <= curve_speed_for_curvature(1.0 / 35.0) * 1.2 + + +# 5 --------------------------------------------------------------------- +def test_release_after_the_apex_lifts_and_never_brakes_into_the_exit(): + start, length = 130.0, 70.0 + rows = _drive([(start, length, 1.0 / 40.0)], 14.0, 32.0, v_max=14.0) + end = start + length + after = [a_cf for _, s, _, _, a_cf, _ in rows if s >= end + 8.0] + assert after and min(after) >= -0.1 + # By the end of the exit ramp the term does not hold the cruise back. + last = [a_cf for _, s, _, _, a_cf, _ in rows if s >= end + 40.0] + assert last and min(last) >= 1.0 + + +def test_proportional_release_rate_is_bounded(): + cf = CurveFollow() + v = 14.0 + bends = [(60.0, 50.0, 1.0 / 35.0)] + s = 0.0 + prev = None + worst_rise = 0.0 + for _ in range(int(14.0 / DT)): + a = _step(cf, v, s, bends) + if prev is not None and prev < 0.0: + worst_rise = max(worst_rise, (a - prev) / DT) + prev = a + s += v * DT + assert worst_rise <= 2.6 + + +# 6 --------------------------------------------------------------------- +def _sbend(gap_s, v=14.0, radius=50.0): + """Left arc then a right arc whose apex is gap_s later at constant speed.""" + a1 = 90.0 + a2 = a1 + gap_s * v + return [(a1, 40.0, 1.0 / radius), (a2, 40.0, -1.0 / radius)] + + +@pytest.mark.parametrize("gap_s", [4.0, 6.0, 8.0, 10.0, 14.0, 20.0]) +def test_s_curve_family_regens_back_down_without_chatter_or_latch(gap_s): + v0 = 11.0 + bends = _sbend(gap_s, v=v0) + v_env = curve_speed_for_curvature(1.0 / 50.0) + rows = _drive(bends, v0, 14.0 + gap_s + 8.0, v_max=18.0) + arc1_end = bends[0][0] + bends[0][1] + arc2_start = bends[1][0] + between = [r for r in rows if arc1_end + 10.0 <= r[1] <= arc2_start - 20.0] + a_cf = [r[4] for r in rows if arc1_end <= r[1] <= arc2_start + 10.0] + # Speed at each tight arc stays on the table. + assert _speed_at(rows, bends[0][0] + 20.0) <= v_env * 1.2 + assert _speed_at(rows, bends[1][0] + 20.0) <= v_env * 1.2 + # Sign changes of the ceiling around zero between the two bends (hysteresis band). + state, flips = 0, 0 + for a in a_cf: + new = 1 if a > 0.15 else (-1 if a < -0.15 else state) + if state and new != state: + flips += 1 + state = new + assert flips <= 2 + if gap_s >= 10.0: + assert between and max(r[3] for r in between) >= 0.15 # accelerates out of bend 1 + if gap_s <= 4.0: + assert not between or max(r[3] for r in between) < 0.15 + + +def test_s_curve_has_no_state_a_fresh_filter_agrees_mid_scene(): + """The demand is a function of the path and speed: a filter started mid-scene agrees after a moment.""" + v0 = 11.0 + bends = _sbend(12.0, v=v0) + cf = CurveFollow() + rows = _drive(bends, v0, 12.0, v_max=18.0, cf=cf) + s_mid, v_mid = rows[-1][1], rows[-1][2] + fresh = CurveFollow() + worst = 0.0 + for k in range(int(3.0 / DT)): + _step(fresh, v_mid, s_mid, bends) + _step(cf, v_mid, s_mid, bends) + if k * DT >= 0.5: + worst = max(worst, abs(fresh.raw - cf.raw)) + s_mid += v_mid * DT + assert worst <= 0.2 + + +# 7 --------------------------------------------------------------------- +def test_one_frame_spike_barely_moves_the_command(): + v = 15.0 + xs = (v * T).tolist() + quiet = [0.0] * len(TL) + spike = list(quiet) + spike[25] = 0.08 + cf = CurveFollow() + lo = FREE_A_MS2 + for i in range(40): + ks = spike if i == 20 else quiet + lo = min(lo, cf.step(dt=DT, v_ego=v, ts=TL, ds=xs, ks=ks)) + # Sustained, the same reading is a real bend and asks for much more. + cf2 = CurveFollow() + hi = FREE_A_MS2 + sustained = [0.0] * 25 + [0.08] * 8 + for _ in range(40): + hi = min(hi, cf2.step(dt=DT, v_ego=v, ts=TL, ds=xs, ks=sustained)) + assert lo > hi + assert FREE_A_MS2 - lo <= 0.25 * (FREE_A_MS2 - hi) + + +def test_strong_reading_ramps_confidence_quickly_after_a_gate(): + cf = CurveFollow() + v = 15.0 + bend = [(60.0, 80.0, 1.0 / 30.0)] + for _ in range(30): + _step(cf, v, 0.0, bend, lane_change=True) + assert cf.conf < 0.1 + for _ in range(10): # 0.5 s + _step(cf, v, 0.0, bend, lane_change=False) + assert cf.conf >= 0.6 + + +def test_high_position_std_silences_far_points_low_std_trusts_them(): + v = 15.0 + xs = (v * T).tolist() + ks = [0.0 if x < 90.0 else 1.0 / 45.0 for x in xs] + noisy, clean = CurveFollow(), CurveFollow() + for _ in range(40): + a_noisy = noisy.step(dt=DT, v_ego=v, ts=TL, ds=xs, ks=ks, y_std=[40.0] * len(TL)) + a_clean = clean.step(dt=DT, v_ego=v, ts=TL, ds=xs, ks=ks, y_std=[0.25] * len(TL)) + assert a_noisy == FREE_A_MS2 + assert a_clean < -0.2 + + +def test_lane_change_fades_the_term_out_without_a_step(): + v = 15.0 + bend = [(70.0, 80.0, 1.0 / 40.0)] + cf = CurveFollow() + for _ in range(40): + a0 = _step(cf, v, 0.0, bend) + assert a0 < -0.2 + seq = [_step(cf, v, 0.0, bend, lane_change=True) for _ in range(30)] + assert seq[-1] > a0 + 0.5 + assert _brake_jerk([a0] + seq) <= 2.1 + assert cf.conf < 0.1 + + +def test_dropout_while_braking_releases_without_a_surge(): + v = 15.0 + bend = [(70.0, 80.0, 1.0 / 40.0)] + cf = CurveFollow() + for _ in range(40): + a0 = _step(cf, v, 0.0, bend) + assert a0 < -0.2 + seq = [a0] + for _ in range(30): + seq.append(cf.step(dt=DT, v_ego=v, ts=None, ds=None, ks=None, valid=False)) + assert _brake_jerk(seq) <= 2.6 + assert cf.conf <= math.exp(-CONF_FALL_1_S * 0.5) + 0.35 + cf.reset() + assert cf.conf == 1.0 and cf.a == FREE_A_MS2 + + +# 8 --------------------------------------------------------------------- +@pytest.mark.parametrize("radius, v_max", [(35.0, 14.0), (70.0, 20.0)]) +def test_max_stays_a_hard_ceiling_and_the_term_never_raises_the_command(radius, v_max): + rows = _drive([(150.0, 90.0, 1.0 / radius)], 10.0, 24.0, v_max=v_max) + for _, _, v, _a, a_cf, _ in rows: + assert a_cf <= FREE_A_MS2 + assert v <= v_max + 0.6 + # The ceiling only ever lowers: the applied accel is never above the cruise accel. + assert all(a <= 1.2 + 1e-9 for _, _, _, a, *_ in rows) + + +# 10 -------------------------------------------------------------------- +def test_active_roundabout_funnel_fades_the_term_out(): + v = 12.0 + bend = [(60.0, 90.0, 1.0 / 28.0)] + cf = CurveFollow() + for _ in range(40): + a0 = _step(cf, v, 0.0, bend) + assert a0 < -0.2 + for _ in range(40): + a_rb = _step(cf, v, 0.0, bend, rb_active=True) + assert a_rb > a0 + 0.8 and cf.conf < 0.05 + + +# 11 -------------------------------------------------------------------- +def test_low_speed_rules(): + bend_near = [(14.0, 40.0, 1.0 / 15.0)] + bend_far = [(40.0, 40.0, 1.0 / 15.0)] + # Below 5 m/s: exactly FREE. + cf = CurveFollow() + assert all(_step(cf, 4.0, 0.0, bend_near, blinker=True) == FREE_A_MS2 for _ in range(20)) + # 6 m/s, no blinker: no anticipation at an intersection. + cf = CurveFollow() + assert all(_step(cf, 6.0, 0.0, bend_near) == FREE_A_MS2 for _ in range(20)) + # With the blinker a near turn is anticipated ... + cf = CurveFollow() + v = 7.5 + out = [_step(cf, v, 0.0, [(10.0, 40.0, 1.0 / 12.0)], blinker=True) for _ in range(40)] + assert min(out) < -0.2 + # ... but only out to ~3 s: a turn 5 s away is not. + cf = CurveFollow() + v = 6.5 + out = [_step(cf, v, 0.0, [(v * 7.0, 40.0, 1.0 / 12.0)], blinker=True) for _ in range(40)] + assert min(out) == FREE_A_MS2 + assert bend_far + + +# 12 -------------------------------------------------------------------- +def test_mode_param_reader_defaults_to_shadow_and_clamps(): + class _P: + def __init__(self, value): + self.value = value + + def get(self, key, return_default=False): + assert key == "NAPCurveFollow" + if isinstance(self.value, Exception): + raise self.value + return self.value + + assert read_curve_follow_mode(_P(0)) == MODE_OFF + assert read_curve_follow_mode(_P(1)) == MODE_SHADOW + assert read_curve_follow_mode(_P(2)) == MODE_ACTIVE + assert read_curve_follow_mode(_P(7)) == MODE_SHADOW + assert read_curve_follow_mode(_P(None)) == MODE_SHADOW + assert read_curve_follow_mode(_P(AssertionError("unknown key"))) == MODE_SHADOW + + +# 13 -------------------------------------------------------------------- +def test_release_buffer_is_one_named_constant_and_is_wired(monkeypatch): + assert RELEASE_BEFORE_TIGHTEST_S == pytest.approx(1.5) + v = 15.0 + xs = (v * T).tolist() + ks = [0.0 if x < 70.0 else 1.0 / 40.0 for x in xs] + w = [1.0] * len(TL) + a1 = curve_follow_raw(v, TL, xs, ks, w)[0] + monkeypatch.setattr(cfmod, "RELEASE_BEFORE_TIGHTEST_S", 2.4) + a24 = curve_follow_raw(v, TL, xs, ks, w)[0] + assert a24 < a1 < 0.0 + + +def test_cycle_time_stays_small(): + cf = CurveFollow() + v = 15.0 + xs = (v * T).tolist() + ks = [0.0 if x < 70.0 else 1.0 / 40.0 for x in xs] + ys = (0.3 + 0.2 * T).tolist() + for _ in range(50): + cf.step(dt=DT, v_ego=v, ts=TL, ds=xs, ks=ks, y_std=ys) + t0 = time.perf_counter() + worst = 0.0 + n = 400 + for _ in range(n): + t1 = time.perf_counter() + cf.step(dt=DT, v_ego=v, ts=TL, ds=xs, ks=ks, y_std=ys) + worst = max(worst, time.perf_counter() - t1) + mean = (time.perf_counter() - t0) / n + assert mean < 0.002 + assert worst < 0.01 + + +# 14 -------------------------------------------------------------------- +def test_log_line_carries_the_path_summary_and_the_full_arrays(): + cf = CurveFollow() + v = 15.0 + ts, xs, ks = _path(v, 0.0, [(70.0, 80.0, 1.0 / 40.0)]) + ys = (0.3 + 0.2 * T).tolist() + for _ in range(30): + cf.step(dt=DT, v_ego=v, ts=ts, ds=xs, ks=ks, y_std=ys) + meta = {"bl": 0, "lc": "off", "df": 0.0, "cn": "green", "rb": 0, "ds": [0, 0.97]} + line = format_log_line(mode=1, t=123.456, v=v, a_ego=0.1, v_cruise_kph=64.4, a_target=-0.2, cf=cf, old_a=-0.3, + ts=ts, ds=xs, ks=ks, y_std=ys, meta=meta, arrays=True) + assert line.startswith(LOG_PREFIX) + rec = json.loads(line[len(LOG_PREFIX):]) + assert rec["m"] == 1 and rec["mx"] == pytest.approx(64.4) and rec["old"] == pytest.approx(-0.3) + assert rec["cf"] == pytest.approx(cf.a, abs=1e-3) and rec["cfr"] == pytest.approx(cf.raw, abs=1e-3) + assert len(rec["k"]) == 9 and len(rec["ys"]) == 3 + assert len(rec["K"]) == len(rec["D"]) == len(rec["T"]) == len(rec["Y"]) == 33 + assert rec["li"] == cf.limit_idx and rec["w"] == pytest.approx(cf.conf, abs=1e-3) + quiet = format_log_line(mode=1, t=1.0, v=v, a_ego=0.0, v_cruise_kph=64.4, a_target=0.0, cf=cf, old_a=2.0, + ts=ts, ds=xs, ks=ks, y_std=None, meta=meta, arrays=False) + assert "\"K\"" not in quiet and "\"k\"" in quiet + + +# 15 -------------------------------------------------------------------- +def test_zero_mean_curvature_noise_does_not_accumulate_into_a_bend(): + """Signed accumulation: noise around zero walks, it does not build a displacement.""" + cf = CurveFollow() + rng = np.random.default_rng(7) + lo = FREE_A_MS2 + for _ in range(200): + ks = rng.normal(0.0, 0.0015, len(TL)).tolist() + lo = min(lo, cf.step(dt=DT, v_ego=20.0, ts=TL, ds=(20.0 * T).tolist(), ks=ks, y_std=(0.3 + 0.2 * T).tolist())) + assert lo >= 1.9 + + +def test_curvature_filter_clips_a_spike_and_opens_slowly(): + n = len(TL) + steady = [0.0] * 10 + [0.02] * (n - 10) + cf = CurveFollow() + for _ in range(20): + cf._filter_k(steady, DT) + spike = list(steady) + spike[25] = 0.10 + assert cf._filter_k(spike, DT)[25] < 0.03 # clipped to twice its neighbours, then filtered + cf = CurveFollow() + for _ in range(20): + cf._filter_k(steady, DT) + gone = [0.0] * n + assert cf._filter_k(gone, DT)[25] >= 0.017 # one frame of "it opens" barely moves it + assert cf._filter_k([0.0] * n, DT)[25] > 0.014 + + +def test_dropped_frames_fade_the_term_out_and_light_drops_do_not(): + v = 15.0 + bend = [(60.0, 80.0, 1.0 / 30.0)] + cf = CurveFollow() + for _ in range(40): + _step(cf, v, 0.0, bend, frame_drop_pct=30.0) + assert cf.conf < 0.1 and not cf.trusted + cf = CurveFollow() + for _ in range(40): + _step(cf, v, 0.0, bend, frame_drop_pct=10.0) + assert cf.conf > 0.99 and cf.trusted + + +def test_near_field_term_is_a_lift_not_a_brake(): + n = len(TL) + ts, ds = TL, (25.0 * T).tolist() + a, idx, _, near = curve_follow_raw(25.0, ts, ds, [0.05] * n, [1.0] * n, 0.0) + assert near is not None and near < 0.0 + assert near >= -0.35 - 1e-9 + + +def test_apex_detection_reads_the_path_peaking(): + v = 15.0 + n = len(TL) + ds = (v * T).tolist() + cf = CurveFollow() + peaking = [0.03 * max(0.0, 1.0 - float(t) / 2.0) for t in TL] # k falls away within 2 s + for _ in range(5): + cf.step(dt=DT, v_ego=v, ts=TL, ds=ds, ks=peaking) + assert cf.passed > 0.9 + cf = CurveFollow() + for _ in range(5): + cf.step(dt=DT, v_ego=v, ts=TL, ds=ds, ks=[0.03] * n) + assert cf.passed == 0.0 + + +def test_braking_never_exceeds_the_speed_dependent_decel_limit(): + from openpilot.selfdrive.controls.lib.curve_preview import preview_decel_limit_ms2 + v = 30.0 + cf = CurveFollow() + ds = (v * T).tolist() + for _ in range(60): + a = cf.step(dt=DT, v_ego=v, ts=TL, ds=ds, ks=[0.0] * 3 + [0.06] * (len(TL) - 3)) + assert cf.raw >= -preview_decel_limit_ms2(v) - 1e-9 + assert a >= -preview_decel_limit_ms2(v) - 1e-9 + assert cf.raw == pytest.approx(-preview_decel_limit_ms2(v)) # the road asks for more; the limit binds diff --git a/selfdrive/controls/tests/test_curve_follow_planner.py b/selfdrive/controls/tests/test_curve_follow_planner.py new file mode 100644 index 00000000000000..0d226784e38b18 --- /dev/null +++ b/selfdrive/controls/tests/test_curve_follow_planner.py @@ -0,0 +1,159 @@ +"""Curve-follow wiring in the longitudinal planner (Pre-AP). + +NAPCurveFollow: 0 off, 1 shadow (compute and log only), 2 active. +""" +import json + +import pytest + +from openpilot.selfdrive.controls.lib import longitudinal_planner as lp +from openpilot.selfdrive.controls.lib.curve_preview import PREVIEW_FREE_A_MS2 +from openpilot.selfdrive.controls.tests.test_curve_preview import _set_model_path +from openpilot.selfdrive.controls.tests.test_unified_lead_planner import _own_lead, _planner + +DT = 0.05 +BEND = (120.0, 60.0, 1.0 / 45.0) +STRAIGHT = (1e6, 1.0, 0.0) + + +def _drive(mode, v, bend, n, mpc_accel=0.4, lead=None, hook=None): + planner, inputs, params = _planner(v, accel=mpc_accel) + params.curve_follow = mode + if lead is not None: + _own_lead(inputs, *lead) + s = 0.0 + rows = [] + for k in range(n): + _set_model_path(inputs["modelV2"], v, s, bend) + if hook is not None: + hook(k, planner, inputs) + planner.update(inputs) + rows.append((float(planner.output_a_target), float(planner.curve_preview_a), float(planner.curve_follow_a))) + s += v * DT + return planner, rows + + +def _spy_errors(monkeypatch): + lines = [] + monkeypatch.setattr(lp.cloudlog, "error", lambda msg, *a, **k: lines.append(msg)) + return lines + + +@pytest.mark.parametrize("lead", [None, (45.0, 14.0)]) +def test_shadow_commands_are_bit_identical_to_off(lead): + _, off = _drive(0, 20.0, BEND, 160, lead=lead) + _, shadow = _drive(1, 20.0, BEND, 160, lead=lead) + assert [r[0] for r in off] == [r[0] for r in shadow] + assert [r[1] for r in off] == [r[1] for r in shadow] # old preview untouched + assert all(r[2] == PREVIEW_FREE_A_MS2 for r in off) # off does not compute + assert min(r[2] for r in shadow) < -0.2 # shadow does compute + + +def test_active_uses_the_curve_follow_ceiling(): + planner, rows = _drive(2, 20.0, BEND, 160) + assert all(r[1] == r[2] for r in rows) + assert min(r[1] for r in rows) < -0.2 + assert planner._cf_trusted + + +def test_active_can_only_lower_the_command(): + _, plain = _drive(0, 20.0, STRAIGHT, 120, mpc_accel=0.8) + _, active = _drive(2, 20.0, BEND, 120, mpc_accel=0.8) + assert all(a[0] <= p[0] + 1e-9 for a, p in zip(active, plain, strict=True)) + + +@pytest.mark.parametrize("lead", [None, (30.0, 10.0)]) +def test_active_on_a_straight_road_is_bit_identical_to_off(lead): + """No bend, no change: the lead law (including braking for a lead) is untouched.""" + _, off = _drive(0, 20.0, STRAIGHT, 160, lead=lead, mpc_accel=-0.5) + _, active = _drive(2, 20.0, STRAIGHT, 160, lead=lead, mpc_accel=-0.5) + assert [r[0] for r in off] == [r[0] for r in active] + + +def test_lead_plus_bend_is_the_stricter_of_the_two(): + lead = (40.0, 20.0) + _, lead_only = _drive(2, 20.0, STRAIGHT, 160, lead=lead) + _, both = _drive(2, 20.0, BEND, 160, lead=lead) + _, bend_only = _drive(2, 20.0, BEND, 160) + assert all(b[0] <= l[0] + 1e-9 for b, l in zip(both, lead_only, strict=True)) + assert any(b[0] < l[0] - 0.1 for b, l in zip(both, lead_only, strict=True)) + # The curve-follow term itself does not depend on the lead. + assert [r[2] for r in both] == [r[2] for r in bend_only] + + +def test_off_mode_emits_no_log_lines(monkeypatch): + lines = _spy_errors(monkeypatch) + _drive(0, 20.0, BEND, 100) + assert not [m for m in lines if str(m).startswith("curvefollow ")] + + +@pytest.mark.parametrize("mode", [1, 2]) +def test_log_lines_come_at_2hz_with_the_agreed_fields(monkeypatch, mode): + lines = _spy_errors(monkeypatch) + _drive(mode, 20.0, BEND, 100) + cf = [m for m in lines if str(m).startswith("curvefollow ")] + assert 9 <= len(cf) <= 11 + rec = json.loads(cf[-1][len("curvefollow "):]) + for key in ("cf", "cfr", "w", "li", "lt", "ld", "lv", "nf", "old", "at", "g", "pk", "tr", "mx"): + assert key in rec + assert any('"T"' in m for m in cf) # full arrays on the relevant stretch + + +def test_a_logging_exception_cannot_touch_the_command(monkeypatch): + def boom(*a, **k): + raise RuntimeError("log sink down") + + _, ok = _drive(2, 20.0, BEND, 100) + monkeypatch.setattr(lp, "format_log_line", boom) + planner, bad = _drive(2, 20.0, BEND, 100) + assert [r[0] for r in ok] == [r[0] for r in bad] + assert not planner._cf_faulted + + +def test_a_fault_latches_and_the_old_preview_stays(monkeypatch): + def boom(self, **kw): + raise RuntimeError("bad") + + _, old = _drive(0, 20.0, BEND, 100) + monkeypatch.setattr(lp.CurveFollow, "step", boom) + planner, rows = _drive(2, 20.0, BEND, 100) + assert planner._cf_faulted + assert [r[0] for r in rows] == [r[0] for r in old] + + +def _ceiling_seen(monkeypatch, mode, break_path=False): + seen = [] + real = lp.unified_follow_desired + + def spy(*a, **k): + seen.append(k.get("v_ceiling")) + return real(*a, **k) + + monkeypatch.setattr(lp, "unified_follow_desired", spy) + planner, inputs, params = _planner(20.0) + params.curve_follow = mode + _own_lead(inputs, 60.0, 20.0) + inputs["controlsState"].curvature = 1.0 / 30.0 + s = 0.0 + for _ in range(40): + _set_model_path(inputs["modelV2"], 20.0, s, (1e6, 1.0, 0.0)) + if break_path: + inputs["modelV2"].position.x = [] + planner.update(inputs) + s += 1.0 + return planner, [c for c in seen if c is not None] + + +def test_reactive_cap_stays_unless_active_and_trusted(monkeypatch): + for mode in (0, 1): + _, seen = _ceiling_seen(monkeypatch, mode) + assert seen and min(seen) < 15.0, mode # present curvature caps the lead law's ceiling + planner, seen = _ceiling_seen(monkeypatch, 2) + assert planner._cf_trusted + assert seen and min(seen) > 15.0 # curve-follow owns the curve; no reactive cap + + +def test_dead_camera_keeps_the_reactive_cap_in_active(monkeypatch): + planner, seen = _ceiling_seen(monkeypatch, 2, break_path=True) + assert not planner._cf_trusted + assert seen and min(seen) < 15.0 diff --git a/selfdrive/controls/tests/test_curve_preview.py b/selfdrive/controls/tests/test_curve_preview.py new file mode 100644 index 00000000000000..aac2ceccaab0dd --- /dev/null +++ b/selfdrive/controls/tests/test_curve_preview.py @@ -0,0 +1,238 @@ +"""Curve handling from true curvature and the model path (Pre-AP). + +Lateral target vs speed, preview slowing 0–5 s ahead that can only lower +the command, and a turn clip that returns +a near the apex. +""" +import math + +import numpy as np +import pytest + +from openpilot.selfdrive.controls.lib.curve_max_hold import ( + curve_lat_target_ms2, + curve_restore_a_ms2, + curve_speed_for_curvature, +) +from openpilot.selfdrive.controls.lib.curve_preview import ( + PREVIEW_FREE_A_MS2, + PREVIEW_LAG_S, + CurvePreview, + curve_preview_accel, + path_curvature, + path_lat_accel_ahead, + turn_accel_limit, +) +from openpilot.selfdrive.controls.lib.longitudinal_planner import limit_accel_in_turns +from openpilot.selfdrive.controls.tests.test_unified_lead_planner import ( + _make_preap_params, + _planner, +) +from openpilot.selfdrive.modeld.constants import ModelConstants + +DT = 0.05 +T = np.array(ModelConstants.T_IDXS) + + +def _bend_kappa(s, start, length, kappa, ramp=15.0): + """Curvature at arc length s: clothoid ramps in/out around a constant arc.""" + if s < start - ramp or s > start + length + ramp: + return 0.0 + if s < start: + return kappa * (s - (start - ramp)) / ramp + if s <= start + length: + return kappa + return kappa * (start + length + ramp - s) / ramp + + +def _path(v, s0, bend): + xs = (v * T).tolist() + ks = [_bend_kappa(s0 + x, *bend) for x in xs] + return T.tolist(), xs, ks + + +def _set_model_path(model, v, s0, bend): + _, xs, ks = _path(v, s0, bend) + model.position.x = xs + model.position.t = T.tolist() + model.velocity.x = [float(v)] * len(xs) + model.orientationRate.z = [k * v for k in ks] + + +def test_lateral_target_vs_speed(): + assert 2.30 <= curve_lat_target_ms2(8.0) <= 2.50 + assert 2.20 <= curve_lat_target_ms2(15.0) <= 2.30 + assert curve_lat_target_ms2(22.0) == pytest.approx(2.0, abs=0.02) + assert curve_lat_target_ms2(30.0) == pytest.approx(1.75, abs=0.02) + # Comfort speed solves v²|κ| = A(v). + for r in (30.0, 60.0, 150.0, 400.0): + v = curve_speed_for_curvature(1.0 / r) + assert v * v / r == pytest.approx(curve_lat_target_ms2(v), rel=0.02) + assert curve_speed_for_curvature(0.0) is None + + +def test_restore_rate_is_speed_dependent(): + assert curve_restore_a_ms2(10.0) == pytest.approx(0.65, abs=0.01) + assert curve_restore_a_ms2(30.0) == pytest.approx(0.35, abs=0.01) + assert curve_restore_a_ms2(10.0) > curve_restore_a_ms2(20.0) > curve_restore_a_ms2(30.0) + + +def test_path_curvature_reads_model_yaw_rate(): + planner, inputs, _ = _planner(15.0) + _set_model_path(inputs["modelV2"], 15.0, 0.0, (0.0, 500.0, 1.0 / 50.0, 1.0)) + ts, xs, ks = path_curvature(inputs["modelV2"]) + assert len(ts) == len(xs) == len(ks) + assert ks[5] == pytest.approx(1.0 / 50.0, rel=1e-6) + assert path_lat_accel_ahead(15.0, ts, ks) == pytest.approx(225.0 / 50.0, rel=1e-3) + + +def _drive_bend(v0, bend, seconds, cruise_a=0.0): + """Kinematic car on a straight-then-bend road, preview only (perfect path).""" + prev = CurvePreview() + s = 0.0 + v = v0 + out = [] + for k in range(int(round(seconds / DT))): + ts, xs, ks = _path(v, s, bend) + a = min(cruise_a, prev.update(v, curve_preview_accel(v, ts, xs, ks), DT)) + out.append((k * DT, s, v, a)) + v = max(0.0, v + a * DT) + s += v * DT + return out + + +@pytest.mark.parametrize("kappa, entry_ratio", [ + (1.0 / 60.0, 1.08), + # Tighter than the town decel cap can reach inside the 5 s horizon. + (1.0 / 40.0, 1.20), +]) +def test_town_bend_preview_slows_early_and_gently(kappa, entry_ratio): + v0 = 15.0 + start = 150.0 + trace = _drive_bend(v0, (start, 60.0, kappa), 16.0) + v_comfort = curve_speed_for_curvature(kappa) + t_entry = next(t for t, s, _, _ in trace if s >= start) + v_entry = next(v for _, s, v, _ in trace if s >= start) + t_onset = next(t for t, _, _, a in trace if a < -0.05) + assert t_entry - t_onset >= 3.5 + assert v_entry <= v_comfort * entry_ratio + assert v_entry <= v0 - 2.0 + accels = [a for _, _, _, a in trace] + assert min(accels) >= -1.05 + jerks = np.diff(accels) / DT + assert np.max(np.abs(jerks)) <= 1.2 + + +def test_highway_bend_preview_is_a_lift(): + trace = _drive_bend(30.0, (400.0, 200.0, 1.0 / 400.0), 20.0) + accels = [a for _, _, _, a in trace] + # Oct 13: cap about -0.8 at every speed (was -0.35 on the highway). + assert min(accels) >= -0.81 + assert min(accels) <= -0.1 + # The raw ceiling itself is clamped: a tight bend close ahead never asks past the cap. + raw = curve_preview_accel(30.0, [1.0, 2.0, 3.0], [30.0, 60.0, 90.0], [1.0 / 30.0] * 3) + assert -0.81 <= raw <= -0.7 + + +def _drive_lagged(v0, bend, seconds, lag_s=1.5): + """Car follows the ceiling with the ~1.5 s pedal/regen lag seen on Oct 13.""" + prev = CurvePreview() + v, s, out, cmds = v0, 0.0, [], [] + for k in range(int(seconds / DT)): + ts, xs, ks = _path(v, s, bend) + cmd = min(0.0, prev.update(v, curve_preview_accel(v, ts, xs, ks), DT)) + cmds.append(cmd) + a = cmds[max(0, len(cmds) - 1 - int(lag_s / DT))] + out.append((k * DT, s, v, cmd, a)) + v = max(0.0, v + a * DT) + s += v * DT + return out + + +@pytest.mark.parametrize("v0, radius", [(22.0, 200.0), (24.0, 250.0), (15.0, 60.0), (30.0, 400.0)]) +def test_oct13_slowing_starts_before_turn_in_and_is_done_by_the_apex(v0, radius): + """Oct 13 18f bends: slowing began 0.6–6 s AFTER turn-in at -0.35…-0.43. + + Now the car itself (after 1.5 s lag) is slowing 2–3.5 s before turn-in, + never harder than about -0.8, and reaches the comfort speed by the apex. + """ + kappa, start, ramp = 1.0 / radius, 600.0, 40.0 + trace = _drive_lagged(v0, (start, 150.0, kappa, ramp), 60.0) + t_turn_in = next(t for t, s, *_ in trace if s >= start - ramp) + t_car = next(t for t, _, _, _, a in trace if a < -0.3) + assert 2.0 <= t_turn_in - t_car <= 3.6 + assert min(r[3] for r in trace) >= -0.81 + v_apex = next(v for _, s, v, *_ in trace if s >= start) + assert v_apex <= curve_speed_for_curvature(kappa) * 1.02 + assert PREVIEW_LAG_S == pytest.approx(1.5) + + +def test_straight_path_preview_is_free(): + ts, xs, ks = _path(25.0, 0.0, (1e6, 1.0, 0.0)) + assert curve_preview_accel(25.0, ts, xs, ks) == PREVIEW_FREE_A_MS2 + + +def test_preview_sweep_has_no_jump(): + """A bend sliding through the horizon never steps the ceiling. + + Raw: continuous at 2 cm resolution. Filtered at 20 m/s (1 m per frame): + the braking part moves at comfort jerk at most. + """ + v = 20.0 + bend = (200.0, 80.0, 1.0 / 60.0) + prev = None + for i in range(16000): + ts, xs, ks = _path(v, i * 0.02, bend) + a = curve_preview_accel(v, ts, xs, ks) + if prev is not None: + assert abs(a - prev) < 0.04 + prev = a + filt = CurvePreview() + prev_brake = 0.0 + saw_brake = False + for i in range(320): + ts, xs, ks = _path(v, i * v * DT, bend) + out = filt.update(v, curve_preview_accel(v, ts, xs, ks), DT) + brake = min(0.0, out) + assert abs(brake - prev_brake) <= 1.0 * DT + 1e-9 + saw_brake |= brake < -0.2 + prev_brake = brake + assert saw_brake + + +@pytest.mark.parametrize("mpc_accel", [-0.3, 0.0, 0.8]) +def test_planner_preview_only_lowers_the_command(mpc_accel): + v = 20.0 + bend, bend_in, _ = _planner(v, accel=mpc_accel) + plain, plain_in, _ = _planner(v, accel=mpc_accel) + s = 0.0 + lowered = False + for _ in range(160): + _set_model_path(bend_in["modelV2"], v, s, (120.0, 60.0, 1.0 / 45.0)) + _set_model_path(plain_in["modelV2"], v, s, (1e6, 1.0, 0.0)) + bend.update(bend_in) + plain.update(plain_in) + a_b = float(bend.output_a_target) + a_p = float(plain.output_a_target) + assert a_b <= a_p + 1e-9 + assert bend.curve_preview_a <= PREVIEW_FREE_A_MS2 + lowered |= a_b < a_p - 0.1 + s += v * DT + assert lowered + + +def test_turn_clip_returns_accel_near_the_apex(): + cp = _make_preap_params() + v = 15.0 + # Apex: 2.3 m/s² now, path 1 s ahead already unwinding to 0.6. + near_apex = turn_accel_limit(v, 2.3, 0.6) + assert near_apex >= 1.0 + # Still tightening ahead: little +a. + assert turn_accel_limit(v, 2.3, 2.4) <= 0.5 + # The path ahead can only loosen the clip relative to now, never tighten it. + assert turn_accel_limit(v, 1.0, 2.5) == pytest.approx(turn_accel_limit(v, 1.0, None)) + # Stock steer-model table (same corner at 15.75 ratio) gave ~nothing here. + steer = math.degrees(2.3 * cp.steerRatio * cp.wheelbase / (v * v)) + old = limit_accel_in_turns(v, steer, [-3.5, 2.0], cp)[1] + new = limit_accel_in_turns(v, steer, [-3.5, 2.0], cp, a_y=2.3, a_y_ahead=0.6)[1] + assert old <= 0.6 + assert new >= 1.0 diff --git a/selfdrive/controls/tests/test_farm_cutin_follow.py b/selfdrive/controls/tests/test_farm_cutin_follow.py new file mode 100644 index 00000000000000..d94e80e845ba44 --- /dev/null +++ b/selfdrive/controls/tests/test_farm_cutin_follow.py @@ -0,0 +1,348 @@ +"""Farm-vehicle approach and faster cut-in. + +Oct 7 2026, route 00000172--2a94c25d70. A 25 mph tractor was held at the +EV mild settle by the post-planner regen guard once closing speed fell +under 6 m/s, then braked late. A faster cut-in was braked while it was +still pulling away. #222 exemplar timings are pinned to the stock law. +""" + +import pytest + +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2, + guard_follow_actuator_regen, +) +from openpilot.selfdrive.controls.lib.unified_lead import ( + A_MIN_MS2, + APPROACH_MILD_MS2, + APPROACH_RAPID_DWELL_S, + APPROACH_RAPID_ENTER_MS, + APPROACH_RAPID_EXIT_MS, + CUTIN_HARD_FRAMES, + TRICKLE_A, + ApproachInputs, + UnifiedLeadController, + approach_physics_need, + gap_set_m, +) +from openpilot.selfdrive.controls.tests.test_unified_lead import ( + SEP20_0755_ROWS, + SEP22_2331_ROWS, + SEP23_2214_ROWS, + _first_at_or_below, + _log_replay, +) + +DT = 0.05 +MPH = 0.44704 +PLANT_LAG_S = 0.35 +PLANT_FLOOR = -1.5 + +# Stock unified replay of the three #222 logs, before this change. +# t(−0.5), t(−1.0), min command. These must not move. +_222_STOCK = { + "sep20": (SEP20_0755_ROWS, -0.02, 1.70, 1.90, -2.352904), + "sep23": (SEP23_2214_ROWS, 0.37, 1.05, 5.50, -1.086998), + "sep22": (SEP22_2331_ROWS, -0.02, 2.60, 2.90, -2.242028), +} + + +def _physics_need(gap, v_ego, v_lead, t_follow): + return approach_physics_need(gap, v_ego, v_lead, t_follow) + + +def _farm_replay(): + """Closed loop of the 14:34 tractor approach. Returns gap, commands, needs.""" + ctrl = UnifiedLeadController() + v_lead = 11.3 # 25 mph + t_follow = 0.7 + v_ceil = 55 * MPH + gap = 111.6 + v_ego = v_lead + 12.9 # 54.3 mph at acquire + a_act = 0.0 + min_gap = gap + rows = [] + prev = 0.0 + late_slam = False + eased = False + for k in range(int(round(45.0 / DT))): + t = k * DT + plan = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=t_follow, lead_id=2110, seed_a=0.0, v_ceiling=v_ceil, + radar=True, model_prob=0.9, y_rel=0.5, + ) + slack = gap - gap_set_m(v_lead, t_follow) + v_close = v_ego - v_lead + act = guard_follow_actuator_regen( + plan, plan, v_rel=v_close, d_rel=gap, slack=slack, a_lead=0.0, + v_ego=v_ego, v_cruise=v_ceil, + ) + act = max(PLANT_FLOOR, float(act)) + # A late slam is a return to the regen rail after the approach has + # already eased. Early firm braking, then a smooth release, is not one. + if act > -0.55: + eased = True + if eased and prev > -0.7 and act <= -1.3: + late_slam = True + prev = act + need = _physics_need(gap, v_ego, v_lead, t_follow) + rows.append((t, gap, v_close, slack, float(plan), act, need)) + a_act += (act - a_act) * DT / PLANT_LAG_S + v_ego = max(0.0, v_ego + a_act * DT) + gap += (v_lead - v_ego) * DT + min_gap = min(min_gap, gap) + return min_gap, late_slam, rows + + +def test_farm_approach_keeps_at_least_11m_and_meets_the_need(): + """14:34 tractor: early progressive brake, no late −1.5, min gap ≥ 11 m. + + Stock closed loop of this geometry stopped at 7.1 m because the regen + guard held −0.22 and then −0.45. The follow law, with that cap retired, + starts braking while the gap is still long. + """ + min_gap, late_slam, rows = _farm_replay() + assert min_gap >= 11.0 + assert not late_slam + # After the jerk ramp, a close that still needs more than a mild settle + # is not held above that need. + checked = 0 + for t, _gap, v_close, slack, plan, act, need in rows: + if t < 1.5 or need >= -0.30 or v_close <= 0.0 or slack <= 3.0: + continue + checked += 1 + assert plan <= need + 0.08 + assert act <= need + 0.08 + assert checked > 50 + # Braking is underway before the gap is inside 60 m, and it eases as + # the close does. It does not sit on the mild settle and then dive. + early = [act for t, gap, _v, _s, _p, act, _n in rows if gap > 60.0 and t > 0.4] + assert early and min(early) <= -0.8 + mild_settle_while_hot = [ + act for t, gap, v_close, slack, _p, act, need in rows + if 8.0 <= slack <= 50.0 and v_close >= 4.0 and need < -0.40 and act > -0.30 + ] + assert mild_settle_while_hot == [] + + +def test_nonbraking_slow_close_follows_the_planner_not_the_mild_cap(): + """The farm geometry: planner −0.87 is not rewritten to −0.22 or −0.45.""" + v_lead = 11.3 + t_follow = 0.7 + gap = 51.5 + v_ego = v_lead + 5.88 + slack = gap - gap_set_m(v_lead, t_follow) + plan = -0.87 + act = guard_follow_actuator_regen( + plan, plan, v_rel=5.88, d_rel=gap, slack=slack, a_lead=0.0, + v_ego=v_ego, v_cruise=55 * MPH, + ) + assert act == pytest.approx(plan) + # Windup still cannot outrun the planner command. + wind = guard_follow_actuator_regen( + -1.5, plan, v_rel=5.88, d_rel=gap, slack=slack, a_lead=0.0, + v_ego=v_ego, v_cruise=55 * MPH, + ) + assert wind == pytest.approx(plan) + + +def test_mild_settle_and_firm_lead_cap_are_unchanged(): + """EV −0.22 still catches plant windup. A firm #222-style lead still clips.""" + assert guard_follow_actuator_regen( + -1.32, -0.22, v_rel=2.0, d_rel=40.0, slack=20.0, a_lead=0.0, + ) == pytest.approx(LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2) + assert guard_follow_actuator_regen( + -1.5, -1.5, v_rel=1.2, d_rel=38.0, slack=18.0, a_lead=-0.6, + ) == pytest.approx(-APPROACH_MILD_MS2) + # Coast with no lead geometry still does not open the settle. + assert guard_follow_actuator_regen(-1.23, 0.0) == pytest.approx(0.0) + + +def test_approach_rapid_regime_has_enter_exit_hysteresis(): + """A sample chatter around 6 m/s does not flip the input regime.""" + inp = ApproachInputs() + v_ego = 20.0 + # Just under the enter line: not rapid, and one frame over does not enter. + inp.update(80.0, v_ego, v_ego - (APPROACH_RAPID_ENTER_MS - 0.2), DT) + assert inp.rapid is False + inp.update(80.0, v_ego, v_ego - (APPROACH_RAPID_ENTER_MS + 0.2), DT) + assert inp.rapid is False + frames = int(APPROACH_RAPID_DWELL_S / DT) + for _ in range(frames): + inp.update(80.0, v_ego, v_ego - (APPROACH_RAPID_ENTER_MS + 0.3), DT) + assert inp.rapid is True + # One frame under the exit line does not leave. + inp.update(70.0, v_ego, v_ego - (APPROACH_RAPID_EXIT_MS - 0.2), DT) + assert inp.rapid is True + for _ in range(frames): + inp.update(70.0, v_ego, v_ego - (APPROACH_RAPID_EXIT_MS - 0.3), DT) + assert inp.rapid is False + # An obvious rapid acquire is rapid on the first sample. + hot = ApproachInputs() + hot.update(111.6, 24.2, 11.3, DT) + assert hot.rapid is True + + +@pytest.mark.parametrize("name", list(_222_STOCK)) +def test_222_log_exemplar_numbers_are_unchanged(name): + rows, seed, t05, t10, mn = _222_STOCK[name] + cmds = _log_replay(rows, seed) + assert _first_at_or_below(cmds, -0.5) == pytest.approx(t05, abs=1e-9) + assert _first_at_or_below(cmds, -1.0) == pytest.approx(t10, abs=1e-9) + assert min(cmds) == pytest.approx(mn, abs=1e-6) + assert min(cmds) >= A_MIN_MS2 + + +def test_new_lead_alead_is_seeded_from_the_first_radar_value(): + """A new track must not start the accel filter at 0 (false lead jerk).""" + ctrl = UnifiedLeadController() + v_ego = 24.5 + ctrl.step( + dt=DT, present=True, gap=23.4, v_ego=v_ego, v_lead=v_ego + 8.0, a_lead=-0.54, + t_follow=0.7, lead_id=2205, seed_a=0.0, v_ceiling=30.0, radar=True, model_prob=0.9, + ) + assert ctrl.last_a_lead == pytest.approx(-0.54, abs=0.02) + assert abs(ctrl._lead_jerk) < 0.25 + + +def test_faster_cutin_does_not_brake_while_pulling_away(): + """14:37:35 cut-in: 72.8 mph into a 54.8 mph ego at 23.4 m. Zero brake. + + The passer eases toward 65 mph and is still faster at the end, so the + hold never releases and the gap opens. Inside the follow window the + positive command stays on the trickle. + """ + ctrl = UnifiedLeadController() + v_ego = 54.8 * MPH + v_fast = 72.8 * MPH + v_ease = 65.0 * MPH + gap = 23.4 + t_follow = 0.7 + v_ceil = 55.0 * MPH + cmds = [] + for k in range(int(round(5.0 / DT))): + t = k * DT + if t < 4.0: + v_lead = v_fast + (v_ease - v_fast) * (t / 4.0) + a_lead = (v_ease - v_fast) / 4.0 + else: + v_lead = v_ease + a_lead = 0.0 + cmd = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=a_lead, + t_follow=t_follow, lead_id=2205, seed_a=0.0, v_ceiling=v_ceil, + radar=True, model_prob=0.9, y_rel=1.4, + ) + cmds.append(cmd) + assert ctrl.pulling_away + gap_set = gap_set_m(v_lead, t_follow) + if gap <= gap_set: + assert cmd <= TRICKLE_A + 1e-6 + gap += (v_lead - v_ego) * DT + v_ego = max(0.0, v_ego + cmd * DT) + assert min(cmds) >= -1e-6 + assert gap > 23.4 + + +def test_cutin_hard_brake_releases_and_full_regen_is_available(): + """+3 m/s at 15 m, then the lead brakes at −3. Release on that brake.""" + ctrl = UnifiedLeadController() + v_ego, v_lead, gap = 25.0, 28.0, 15.0 + hard_at = None + release_at = None + cmds = [] + for k in range(int(round(3.0 / DT))): + t = k * DT + a_lead = -3.0 if t >= 0.5 else 0.0 + cmd = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=a_lead, + t_follow=0.7, lead_id=3, seed_a=0.0, v_ceiling=30.0, radar=True, model_prob=1.0, + ) + cmds.append(cmd) + if hard_at is None and a_lead <= -1.5: + hard_at = t + if release_at is None and not ctrl.pulling_away: + release_at = t + v_lead = max(0.0, v_lead + a_lead * DT) + v_ego = max(0.0, v_ego + cmd * DT) + gap += (v_lead - v_ego) * DT + assert hard_at == pytest.approx(0.5) + # Two hard frames, or the projected-gap backstop on the first one. + assert release_at is not None + assert release_at <= hard_at + CUTIN_HARD_FRAMES * DT + 1e-9 + assert min(cmds) <= -3.0 + assert min(cmds) >= A_MIN_MS2 + + +def test_cutin_easing_releases_on_predicted_closing_without_an_early_brake(): + """+2.5 m/s at 20 m, lead eases at −0.6. No brake until the handover.""" + ctrl = UnifiedLeadController() + v_ego, v_lead, gap = 25.0, 27.5, 20.0 + release_at = None + before = [] + after = [] + for k in range(int(round(8.0 / DT))): + t = k * DT + cmd = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=-0.6, + t_follow=0.7, lead_id=4, seed_a=0.0, v_ceiling=30.0, radar=True, model_prob=1.0, + ) + if ctrl.pulling_away: + before.append(cmd) + else: + if release_at is None: + release_at = t + after.append(cmd) + # Ego holds speed aside from the command; the lead is slowing. + v_lead = max(0.0, v_lead - 0.6 * DT) + v_ego = max(0.0, v_ego + min(cmd, 0.0) * DT) + gap += (v_lead - v_ego) * DT + assert release_at == pytest.approx(3.75, abs=0.15) + assert before and min(before) >= -1e-6 + assert after and min(after) <= -0.4 + # Not the stock copy of the passer's decel (−0.94). The handover is milder. + assert min(after) > -0.9 + + +def test_cutin_inside_9m_releases_immediately(): + """+2.2 m/s at 9 m is already inside the keep distance. No hold.""" + ctrl = UnifiedLeadController() + cmd = ctrl.step( + dt=DT, present=True, gap=9.0, v_ego=22.0, v_lead=24.2, a_lead=0.0, + t_follow=0.7, lead_id=5, seed_a=0.0, v_ceiling=28.0, radar=True, model_prob=1.0, + ) + assert ctrl.pulling_away is False + assert cmd < 0.0 + + +def test_cutin_becomes_a_normal_lead_once_it_is_slower_than_ego(): + """Closing that persists hands the cut-in to the normal follow law.""" + ctrl = UnifiedLeadController() + v_ego, v_lead, gap = 22.0, 24.5, 30.0 + release_at = None + for k in range(int(round(6.0 / DT))): + t = k * DT + # Strong enough to be slower than ego inside 1.5 s, not a −1.5 spike. + cmd = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=-1.2, + t_follow=0.7, lead_id=6, seed_a=0.0, v_ceiling=26.0, radar=True, model_prob=1.0, + ) + if release_at is None and not ctrl.pulling_away: + release_at = t + assert cmd <= 0.05 + v_lead = max(0.0, v_lead - 1.2 * DT) + gap += (v_lead - v_ego) * DT + assert release_at is not None and release_at < 3.0 + # One-way: once released, a still-positive filtered speed does not re-latch. + assert ctrl.pulling_away is False + + +def test_slightly_faster_new_lead_does_not_enter_the_hold(): + """SEP23 starts only +1.6 m/s. The +2.0 entry must not latch.""" + ctrl = UnifiedLeadController() + ctrl.step( + dt=DT, present=True, gap=41.5, v_ego=29.58, v_lead=31.18, a_lead=-0.08, + t_follow=0.7, lead_id=1, seed_a=0.37, v_ceiling=40.0, radar=True, model_prob=0.9, + ) + assert ctrl.pulling_away is False diff --git a/selfdrive/controls/tests/test_firm_brake_latch.py b/selfdrive/controls/tests/test_firm_brake_latch.py new file mode 100644 index 00000000000000..3a2c89d5c0275c --- /dev/null +++ b/selfdrive/controls/tests/test_firm_brake_latch.py @@ -0,0 +1,330 @@ +"""Firm-brake latch for the Pre-AP follow actuator guard (F1). + +15a 11:26:49: a firm plan (-1.5) on a mid-gap close stepped -1.5 -> -0.22 +-> -1.5 at the actuator when v_rel crossed 1.5 m/s, because the guard's +mild-floor clip comes back below that close. The latch keeps the clip off +while the plan is still firm. It may only make the command firmer: every +unlatched path (hold False, #222, EV settle -0.22, MAX, the -1.5 rail) is +the unchanged guard output: lead_approach.py is not touched by the latch. +""" +import itertools +from types import SimpleNamespace + +import pytest +from cereal import car + +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.controls.lib import firm_brake_latch as fbl +from openpilot.selfdrive.controls.lib.firm_brake_latch import ( + LEAD_FIRM_LATCH_ENTER_CLOSE_MS, + LEAD_FIRM_LATCH_ENTER_PLAN_MS2, + LEAD_FIRM_LATCH_HOLD_CLOSE_MS, + LEAD_FIRM_LATCH_HOLD_PLAN_MS2, + LEAD_FIRM_LATCH_MAX_S, + FirmBrakeLatch, + apply_firm_brake_latch, + lead_midgap_firm_close_hit, +) +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2, + guard_follow_actuator_regen, +) +from openpilot.selfdrive.controls.lib.longcontrol import LongControl, LongCtrlState + +# Slack 18 m is mid-gap and above the near-gap band, below the large-slack +# early-kinematic brake (20 m): the geometry of the 11:26:49 cliff. +SLACK = 18.0 +D_REL = 38.0 +V_EGO = 20.0 +V_CRUISE = 30.0 +A_LEAD_FIRM = -0.6 +LIMITS = (-1.5, 0.8) + + +def _guard(act, plan, v_rel, hold_pass=False, **kw): + """The unchanged guard, then the latch seam exactly as LongControl wires it.""" + args = dict(v_rel=v_rel, d_rel=D_REL, slack=SLACK, v_ego=V_EGO, + v_cruise=V_CRUISE, a_lead=A_LEAD_FIRM) + args.update(kw) + guarded = guard_follow_actuator_regen(act, plan, **args) + return apply_firm_brake_latch( + guarded, act, plan, hold_pass, + v_rel=args["v_rel"], slack=args["slack"], a_lead=args["a_lead"], + ) + + +def _hit(v_rel, **kw): + args = dict(a_lead=A_LEAD_FIRM) + args.update(kw) + return lead_midgap_firm_close_hit(v_rel, D_REL, SLACK, **args) + + +def test_constants_are_pinned(): + assert LEAD_FIRM_LATCH_ENTER_PLAN_MS2 == -0.80 + assert LEAD_FIRM_LATCH_HOLD_PLAN_MS2 == -0.50 + assert LEAD_FIRM_LATCH_ENTER_CLOSE_MS == 1.5 + assert LEAD_FIRM_LATCH_HOLD_CLOSE_MS == 0.80 + assert LEAD_FIRM_LATCH_MAX_S == 4.0 + + +# --- the guard ----------------------------------------------------------------- + +def test_default_guard_still_clips_a_slow_close_to_mild(): + """No latch: the legacy cliff is untouched (this is what the latch fixes).""" + assert _guard(-1.5, -1.5, 1.8) == pytest.approx(-1.5) + assert _guard(-1.5, -1.5, 1.2) == pytest.approx(LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2) + + +def test_hold_pass_lets_the_firm_plan_reach_the_plant_below_the_close_gate(): + assert _guard(-1.5, -1.5, 1.2, hold_pass=True) == pytest.approx(-1.5) + assert _guard(-1.0, -1.0, 1.0, hold_pass=True) == pytest.approx(-1.0) + + +def test_hold_pass_is_never_softer_than_the_unlatched_guard(): + acts = (-1.5, -1.2, -0.8, -0.5, -0.3, -0.22, -0.1, 0.0, 0.4) + plans = (-1.5, -1.0, -0.8, -0.6, -0.5, -0.4, -0.22, 0.0, 0.3) + v_rels = (-1.0, 0.0, 0.5, 1.0, 1.2, 1.49, 1.5, 1.8, 3.0, 6.5) + slacks = (5.0, 10.0, 14.0, 16.0, 18.0, 22.0, 40.0, 60.0) + a_leads = (None, -1.5, -0.6, -0.3, 0.0, 0.5) + for act, plan, v_rel, slack, a_lead in itertools.product(acts, plans, v_rels, slacks, a_leads): + kw = dict(v_rel=v_rel, d_rel=slack + 20.0, slack=slack, v_ego=V_EGO, + v_cruise=V_CRUISE, a_lead=a_lead) + base = guard_follow_actuator_regen(act, plan, **kw) + held = apply_firm_brake_latch( + base, act, plan, True, v_rel=v_rel, slack=slack, a_lead=a_lead) + assert held <= base + 1e-12, (act, plan, kw) + # No hold: the guard output is returned untouched. + assert apply_firm_brake_latch( + base, act, plan, False, v_rel=v_rel, slack=slack, a_lead=a_lead) == base + # The latch never goes below the actuator the PID asked for. + assert held >= min(act, base) - 1e-12 + + +def test_hold_pass_changes_nothing_when_the_plan_is_not_firm(): + """EV settle -0.22 and coast stay bit-identical with the latch asserted.""" + for plan in (0.3, 0.0, -0.039, -0.22, -0.3): + for act in (-1.5, -0.6, -0.22, 0.0): + for v_rel in (0.2, 1.2, 1.8): + kw = dict(v_rel=v_rel, d_rel=D_REL, slack=SLACK, v_ego=V_EGO, + v_cruise=V_CRUISE, a_lead=A_LEAD_FIRM) + assert _guard(act, plan, v_rel, hold_pass=True) == \ + guard_follow_actuator_regen(act, plan, **kw), (plan, act, v_rel) + + +def test_emergency_and_rail_paths_ignore_the_latch(): + for kw in (dict(fcw=True), dict(crash_cnt=1), dict(d_rel=10.0)): + a = _guard(-1.5, -1.5, 1.2, **kw) + assert a == _guard(-1.5, -1.5, 1.2, hold_pass=True, **kw) == pytest.approx(-1.5) + # The -1.5 rail is never exceeded by the latch. + assert _guard(-1.5, -3.0, 1.2, hold_pass=True) >= -1.5 + + +def test_early_kinematic_cap_keeps_ownership_of_its_frame(): + """Slack 22 m, firm lead, close 1.8: the guard's early brake (-0.87) is a + deliberate softening. The latch must not override it with the raw -1.5.""" + kw = dict(d_rel=42.0, slack=22.0, v_ego=V_EGO, v_cruise=V_CRUISE, a_lead=-0.8) + guarded = guard_follow_actuator_regen(-1.5, -1.5, v_rel=1.8, **kw) + assert guarded > -1.2 + assert apply_firm_brake_latch(guarded, -1.5, -1.5, True, v_rel=1.8, slack=22.0, a_lead=-0.8) == guarded + + +def test_latch_seam_ignores_missing_inputs_and_soft_plans(): + assert apply_firm_brake_latch(None, -1.5, -1.5, True) is None + assert apply_firm_brake_latch(-0.22, None, -1.5, True) == -0.22 + assert apply_firm_brake_latch(-0.22, -1.5, None, True) == -0.22 + assert apply_firm_brake_latch(-0.22, -1.5, -0.49, True) == -0.22 + assert apply_firm_brake_latch(-0.22, -1.5, -0.50, True) == -1.5 + assert apply_firm_brake_latch(-0.22, -1.5, -1.5, False) == -0.22 + + +# --- the hit helper ------------------------------------------------------------ + +def test_hit_needs_a_firm_close_in_the_mid_gap_band(): + assert _hit(1.5) + assert _hit(3.0) + assert not _hit(1.49) + assert not _hit(1.8, a_lead=-0.2) # non-braking catch-up is a coast + assert not _hit(1.8, a_lead=None) + assert not _hit(1.8, should_stop=True) + assert not _hit(7.0) # confirmed rapid passes raw anyway + assert not lead_midgap_firm_close_hit(1.8, D_REL, 60.0, a_lead=A_LEAD_FIRM) # out of band + assert not lead_midgap_firm_close_hit(1.8, 10.0, SLACK, a_lead=A_LEAD_FIRM) # near bumper + assert not lead_midgap_firm_close_hit(None, D_REL, SLACK, a_lead=A_LEAD_FIRM) + + +def test_hit_accepts_the_222_residual_brake_without_a_firm_alead(): + """#222: close rising against ego's own accel is a real brake.""" + assert _hit(1.8, a_lead=0.0, prev_v_rel=1.2, a_ego=0.0, dt=0.5) + assert not _hit(1.8, a_lead=0.0, prev_v_rel=1.8, a_ego=0.0, dt=0.5) + + +# --- the latch ------------------------------------------------------------------ + +def _enter(latch): + assert latch.update(-1.5, 1.8, True, DT_CTRL) is True + return latch + + +def test_latch_enters_on_a_firm_plan_and_a_firm_close(): + latch = FirmBrakeLatch() + assert latch.update(-0.79, 1.8, True, DT_CTRL) is False + assert latch.update(-1.5, 1.8, False, DT_CTRL) is False + assert latch.update(-0.8, 1.8, True, DT_CTRL) is True + + +def test_latch_holds_through_the_close_easing_below_the_entry_gate(): + latch = _enter(FirmBrakeLatch()) + for v_rel in (1.45, 1.2, 1.0, 0.85, 0.8): + assert latch.update(-1.5, v_rel, False, DT_CTRL) is True + # A mild plan between enter (-0.8) and hold (-0.5) still holds. + assert latch.update(-0.6, 1.0, False, DT_CTRL) is True + + +def test_latch_releases_when_the_plan_goes_soft(): + latch = _enter(FirmBrakeLatch()) + assert latch.update(-0.5, 1.2, False, DT_CTRL) is True + assert latch.update(-0.49, 1.2, False, DT_CTRL) is False + assert latch.update(-0.49, 1.2, False, DT_CTRL) is False + # and re-entering needs a fresh firm plan AND hit + assert latch.update(-1.5, 1.2, False, DT_CTRL) is False + assert latch.update(-1.5, 1.8, True, DT_CTRL) is True + + +def test_latch_releases_when_the_close_collapses(): + latch = _enter(FirmBrakeLatch()) + assert latch.update(-1.5, 0.81, False, DT_CTRL) is True + assert latch.update(-1.5, 0.79, False, DT_CTRL) is False + + +def test_latch_expires_after_four_seconds(): + latch = _enter(FirmBrakeLatch()) + steps = int(round(LEAD_FIRM_LATCH_MAX_S / DT_CTRL)) + for _ in range(steps): + assert latch.update(-1.5, 1.2, False, DT_CTRL) is True + assert latch.update(-1.5, 1.2, False, DT_CTRL) is False + # the same frame does not silently re-arm without a hit + assert latch.update(-1.5, 1.2, False, DT_CTRL) is False + + +def test_latch_resets_when_the_lead_or_plan_is_missing(): + latch = _enter(FirmBrakeLatch()) + assert latch.update(-1.5, None, False, DT_CTRL) is False + assert latch.update(-1.5, 1.2, False, DT_CTRL) is False + latch = _enter(FirmBrakeLatch()) + assert latch.update(None, 1.2, False, DT_CTRL) is False + assert latch.update(-1.5, 1.2, False, DT_CTRL) is False + + +def test_latch_reset_clears_state(): + latch = _enter(FirmBrakeLatch()) + latch.reset() + assert latch.on is False and latch.age == 0.0 + assert latch.update(-1.5, 1.2, False, DT_CTRL) is False + + +# --- LongControl seam ------------------------------------------------------------ + +def _params(): + p = car.CarParams.new_message() + p.brand = "tesla" + p.carFingerprint = "TESLA_MODEL_S_PREAP" + p.openpilotLongitudinalControl = True + p.pcmCruise = False + from opendbc.car.tesla.preap.constants import PEDAL_LONG_K_BP, PEDAL_LONG_KI_V, PEDAL_LONG_KP_V + p.longitudinalTuning.kpBP = PEDAL_LONG_K_BP + p.longitudinalTuning.kpV = PEDAL_LONG_KP_V + p.longitudinalTuning.kiBP = PEDAL_LONG_K_BP + p.longitudinalTuning.kiV = PEDAL_LONG_KI_V + p.longitudinalTuning.kf = 1.0 + p.vEgoStarting = 0.1 + return p + + +def _cs(): + s = car.CarState.new_message() + s.vEgo = V_EGO + s.brakePressed = False + s.cruiseState.standstill = False + return s + + +def _drive(lc, plan, v_rels, a_lead=A_LEAD_FIRM, frames_each=50): + """One 100 Hz LongControl frame per sample; returns every actuator command.""" + out = [] + for v_rel in v_rels: + for _ in range(frames_each): + out.append(lc.update( + True, _cs(), plan, False, LIMITS, lead_v_rel=v_rel, lead_d_rel=D_REL, + lead_slack=SLACK, lead_fcw=False, lead_v_ego=V_EGO, + lead_v_cruise=V_CRUISE, lead_a_lead=a_lead, + )) + return out + + +def _legacy_lc(): + lc = LongControl(_params()) + lc._firm_latch = SimpleNamespace( + update=lambda *a, **k: False, reset=lambda: None, on=False) + return lc + + +def test_longcontrol_removes_the_1p5_to_mild_to_1p5_cliff(): + """E1 shape: firm plan -1.5 held; v_rel 1.8 -> 1.2 -> 1.8.""" + v_rels = (1.8, 1.2, 1.0, 1.8) + legacy = _drive(_legacy_lc(), -1.5, v_rels) + latched = _drive(LongControl(_params()), -1.5, v_rels) + # Legacy shows the cliff (this is the bug being fixed). + assert max(legacy[60:140]) == pytest.approx(LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2, abs=0.05) + assert max(b - a for a, b in zip(legacy, legacy[1:], strict=False)) > 0.8 + # Latched: command follows the plan, no up-step anywhere. + assert max(latched) <= -1.4 + assert max(b - a for a, b in zip(latched, latched[1:], strict=False)) < 0.05 + + +def test_longcontrol_latch_is_never_softer_than_legacy_and_expires(): + v_rels = (1.8, 1.2, 1.0, 0.6, 1.2) + legacy = _drive(_legacy_lc(), -1.5, v_rels) + latched = _drive(LongControl(_params()), -1.5, v_rels) + assert all(n <= o + 1e-9 for n, o in zip(latched, legacy, strict=True)) + # After v_rel < 0.8 the latch is released and the legacy clip returns. + assert latched[3 * 50 + 10] == pytest.approx(legacy[3 * 50 + 10]) + assert latched[-1] == pytest.approx(legacy[-1]) + + +def test_longcontrol_mild_and_settle_plans_are_bit_identical_to_legacy(): + """EV mild settle -0.22 / coast never arm the latch.""" + for plan in (0.2, 0.0, -0.22, -0.45): + v_rels = (1.8, 1.2, 1.0, 1.8, 0.5) + assert _drive(LongControl(_params()), plan, v_rels, frames_each=20) == \ + _drive(_legacy_lc(), plan, v_rels, frames_each=20), plan + + +def test_longcontrol_drops_the_latch_with_the_lead_and_on_reset(): + lc = LongControl(_params()) + _drive(lc, -1.5, (1.8, 1.2), frames_each=10) + assert lc._firm_latch.on + _drive(lc, -1.5, (None,), frames_each=1) + assert not lc._firm_latch.on + _drive(lc, -1.5, (1.8, 1.2), frames_each=10) + assert lc._firm_latch.on + lc.reset() + assert not lc._firm_latch.on + + +def test_longcontrol_latch_off_outside_pid_state(): + lc = LongControl(_params()) + _drive(lc, -1.5, (1.8, 1.2), frames_each=10) + assert lc._firm_latch.on + lc.update(False, _cs(), -1.5, False, LIMITS, lead_v_rel=1.2, lead_d_rel=D_REL, + lead_slack=SLACK, lead_a_lead=A_LEAD_FIRM) + assert lc.long_control_state == LongCtrlState.off + assert not lc._firm_latch.on + + +def test_longcontrol_wires_the_latch_into_the_guard(): + import inspect + src = inspect.getsource(LongControl) + assert "apply_firm_brake_latch(" in src + assert "self._firm_latch.update(" in src + assert "DT_CTRL," in src + assert "FirmBrakeLatch" in inspect.getsource(fbl) diff --git a/selfdrive/controls/tests/test_follow_distance.py b/selfdrive/controls/tests/test_follow_distance.py new file mode 100644 index 00000000000000..0d21ba61533e40 --- /dev/null +++ b/selfdrive/controls/tests/test_follow_distance.py @@ -0,0 +1,420 @@ +"""City vs highway Follow Distance blend.""" +import pytest + +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.follow_distance import ( + FOLLOW_CITY_ENTER_MPH, + FOLLOW_DEFAULT, + FOLLOW_HWY_ENTER_MPH, + FOLLOW_OPEN_SLOW_FRAC, + FOLLOW_SPLIT_MPH, + FOLLOW_T_SLEW_CREEP_PER_S, + FOLLOW_T_SLEW_OPEN_PER_S, + FollowDistanceBlend, + PARAM_FOLLOW, + PARAM_FOLLOW_CITY, + PARAM_FOLLOW_HWY, + PARAM_FOLLOW_MIGRATED, + follow_band_is_highway, + follow_max_is_highway, + follow_open_a_ms2, + follow_stalk_band_is_highway, + migrate_follow_distance_params, + published_cruise_ms, +) +from openpilot.selfdrive.controls.lib.lead_approach import nap_t_follow + + +class FakeParams: + def __init__(self, follow=FOLLOW_DEFAULT, city=None, hwy=None, migrated=False): + self._ints = {PARAM_FOLLOW: int(follow)} + if city is not None: + self._ints[PARAM_FOLLOW_CITY] = int(city) + if hwy is not None: + self._ints[PARAM_FOLLOW_HWY] = int(hwy) + self._bools = {PARAM_FOLLOW_MIGRATED: bool(migrated)} + + def get(self, key, return_default=False): + if key in self._ints: + return self._ints[key] + if return_default: + return FOLLOW_DEFAULT + return None + + def put(self, key, value): + self._ints[key] = int(value) + + def put_bool(self, key, value): + self._bools[key] = bool(value) + + def get_bool(self, key): + return bool(self._bools.get(key, False)) + + +def test_migrate_copies_legacy_follow_distance_once(): + params = FakeParams(follow=2) + city, hwy = migrate_follow_distance_params(params) + assert city == 2 and hwy == 2 + assert params.get(PARAM_FOLLOW_CITY) == 2 + assert params.get(PARAM_FOLLOW_HWY) == 2 + assert params.get_bool(PARAM_FOLLOW_MIGRATED) + params.put(PARAM_FOLLOW_CITY, 6) + city, hwy = migrate_follow_distance_params(params) + assert city == 6 and hwy == 2 + + +def test_follow_band_hysteresis_around_50(): + v50 = FOLLOW_SPLIT_MPH * CV.MPH_TO_MS + v48 = FOLLOW_CITY_ENTER_MPH * CV.MPH_TO_MS + v52 = FOLLOW_HWY_ENTER_MPH * CV.MPH_TO_MS + assert follow_band_is_highway(v50) is True + assert follow_band_is_highway(v48 - 0.1) is False + # Hold highway down through 49 mph; drop only below 48. + v49 = 49.0 * CV.MPH_TO_MS + assert follow_band_is_highway(v49, prev_highway=True) is True + assert follow_band_is_highway(v48 - 0.05, prev_highway=True) is False + # Hold city up through 51; rise only above 52. + v51 = 51.0 * CV.MPH_TO_MS + assert follow_band_is_highway(v51, prev_highway=False) is False + assert follow_band_is_highway(v52 + 0.05, prev_highway=False) is True + + +def test_max_primary_city_hwy_band(): + """City when MAX < 50. Highway when MAX ≥ 50. Ego only if MAX is missing.""" + def v(mph): + return mph * CV.MPH_TO_MS + + assert follow_max_is_highway(v(70)) is True + assert follow_max_is_highway(v(50)) is True + assert follow_max_is_highway(v(49)) is False + assert follow_max_is_highway(v(45)) is False + assert follow_max_is_highway(None) is None + assert follow_max_is_highway(0.0) is None + + # ego 25 + MAX 70 → Hwy, even from a city band and with no lead. + assert follow_band_is_highway(v(25), prev_highway=False, v_cruise=v(70)) is True + assert follow_band_is_highway( + v(25), v_cruise=v(70), engaged=False, has_lead=False, + ) is True + # ego 60 + MAX 45 → City. Do not hold highway just because ego is fast. + assert follow_band_is_highway(v(60), prev_highway=True, v_cruise=v(45)) is False + assert follow_stalk_band_is_highway(v(60), v(45)) is False + # ego 25 + no MAX → city. ego 60 + no MAX (including cruise 0) → hwy. + assert follow_band_is_highway(v(25)) is False + assert follow_stalk_band_is_highway(v(25)) is False + assert follow_band_is_highway(v(60)) is True + assert follow_stalk_band_is_highway(v(60), 0.0) is True + assert follow_stalk_band_is_highway(v(25), 0.0) is False + # MAX exactly 50 → Hwy, whatever ego is doing. + assert follow_band_is_highway(v(25), v_cruise=v(50)) is True + assert follow_band_is_highway(v(60), v_cruise=v(50)) is True + assert follow_stalk_band_is_highway(v(25), v(50)) is True + assert follow_stalk_band_is_highway(v(50), v(50)) is True + # Decel under a highway MAX (23:32: ego ~48, MAX still 75) stays Hwy. + assert follow_band_is_highway(v(47.7), prev_highway=True, v_cruise=v(75)) is True + assert follow_band_is_highway(v(47.7), prev_highway=False, v_cruise=v(75)) is True + # No MAX: 48/52 ego hysteresis still holds. A set MAX does not. + assert follow_band_is_highway(v(49), prev_highway=True) is True + assert follow_band_is_highway(v(49), prev_highway=True, v_cruise=v(49)) is False + + +def test_blend_creeps_to_hwy_from_30_when_max_is_highway_intent(): + b = FollowDistanceBlend() + b.city, b.hwy = 6, 2 + b.highway = False + b.t_follow = nap_t_follow(6) + v_ego = 35.0 * CV.MPH_TO_MS + v_max = 65.0 * CV.MPH_TO_MS + dt = 0.05 + t_hwy = nap_t_follow(2) + t, dist, extra = b.update( + v_ego, dt, engaged=True, has_lead=True, v_lead=v_ego, v_cruise=v_max, + ) + assert dist == 2 + assert extra is None + assert t < nap_t_follow(6) + times = [t] + for _ in range(int(20.0 / dt)): + t, dist, extra = b.update( + v_ego, dt, engaged=True, has_lead=True, v_lead=v_ego, v_cruise=v_max, + ) + times.append(t) + assert extra is None + if t <= t_hwy + 1e-6: + break + assert dist == 2 + assert times[-1] == pytest.approx(t_hwy, abs=1e-6) + steps = [s - t for s, t in zip(times, times[1:], strict=False)] + assert max(steps) <= FOLLOW_T_SLEW_CREEP_PER_S * dt + 1e-9 + + +def test_blend_returns_to_city_when_max_drops_below_50(): + b = FollowDistanceBlend() + b.city, b.hwy = 6, 2 + b.highway = True + b.t_follow = nap_t_follow(2) + v_ego = 55.0 * CV.MPH_TO_MS + t_city = nap_t_follow(6) + t, dist, extra = b.update( + v_ego, 0.05, engaged=True, has_lead=True, v_lead=v_ego, + v_cruise=45.0 * CV.MPH_TO_MS, + ) + assert dist == 6 + assert t > nap_t_follow(2) + assert extra is not None and extra < 0.0 + # Keep slewing toward city; do not snap. + t2, dist2, _ = b.update( + v_ego, 0.05, engaged=True, has_lead=True, v_lead=v_ego, + v_cruise=45.0 * CV.MPH_TO_MS, + ) + assert dist2 == 6 + assert t2 > t + assert t2 < t_city + + +def test_blend_opens_gradually_to_city_then_holds(): + b = FollowDistanceBlend() + b.city, b.hwy = 6, 2 + b.highway = True + b.t_follow = nap_t_follow(2) + v_lead = 45.0 * CV.MPH_TO_MS + v_ego = v_lead + dt = 0.05 + t_city = nap_t_follow(6) + extras = [] + times = [b.t_follow] + for _ in range(int(12.0 / dt)): + t, dist, extra = b.update(v_ego, dt, engaged=True, has_lead=True, v_lead=v_lead) + times.append(t) + extras.append(extra) + if extra is not None: + v_ego = max(0.0, v_ego + extra * dt) + if t >= t_city - 1e-6: + break + assert dist == 6 + assert times[0] == pytest.approx(nap_t_follow(2)) + assert times[-1] == pytest.approx(t_city, abs=1e-6) + assert any(a is not None and a < 0.0 for a in extras) + assert max(t - s for s, t in zip(times, times[1:], strict=False)) <= FOLLOW_T_SLEW_OPEN_PER_S * dt + 1e-9 + t, dist, extra = b.update(v_lead, dt, engaged=True, has_lead=True, v_lead=v_lead) + assert t == pytest.approx(t_city) + assert extra is None + + +def test_blend_creeps_toward_hwy_without_a_step(): + b = FollowDistanceBlend() + b.city, b.hwy = 6, 2 + b.highway = False + b.t_follow = nap_t_follow(6) + v_ego = 60.0 * CV.MPH_TO_MS + v_lead = v_ego + dt = 0.05 + t_hwy = nap_t_follow(2) + times = [b.t_follow] + for _ in range(int(20.0 / dt)): + t, dist, extra = b.update(v_ego, dt, engaged=True, has_lead=True, v_lead=v_lead) + times.append(t) + assert extra is None + if t <= t_hwy + 1e-6: + break + assert dist == 2 + assert times[-1] == pytest.approx(t_hwy, abs=1e-6) + steps = [s - t for s, t in zip(times, times[1:], strict=False)] + assert max(steps) <= FOLLOW_T_SLEW_CREEP_PER_S * dt + 1e-9 + assert min(steps) >= 0.0 or times[-1] == pytest.approx(t_hwy) + + +def test_no_lead_or_not_engaged_snaps_to_band(): + b = FollowDistanceBlend() + b.city, b.hwy = 7, 1 + v_city = 40.0 * CV.MPH_TO_MS + t, dist, extra = b.update(v_city, 0.05, engaged=True, has_lead=False) + assert dist == 7 + assert t == pytest.approx(nap_t_follow(7)) + assert extra is None + v_hwy = 65.0 * CV.MPH_TO_MS + t, dist, extra = b.update(v_hwy, 0.05, engaged=False, has_lead=True, v_lead=v_hwy) + assert dist == 1 + assert t == pytest.approx(nap_t_follow(1)) + + +def test_persist_steps_city_or_hwy_band_by_speed(): + from openpilot.selfdrive.controls.lib.hypermile import persist_follow_distance + + params = FakeParams(follow=4, city=4, hwy=4, migrated=True) + persist_follow_distance(params, closer=True, v_ego=40.0 * CV.MPH_TO_MS) + assert params.get(PARAM_FOLLOW_CITY) == 3 + assert params.get(PARAM_FOLLOW_HWY) == 4 + assert params.get(PARAM_FOLLOW) == 3 + persist_follow_distance(params, closer=False, v_ego=65.0 * CV.MPH_TO_MS) + assert params.get(PARAM_FOLLOW_CITY) == 3 + assert params.get(PARAM_FOLLOW_HWY) == 5 + assert params.get(PARAM_FOLLOW) == 5 + # 35 mph with MAX 65 writes hwy (accelerating under a highway MAX). + persist_follow_distance( + params, closer=False, v_ego=35.0 * CV.MPH_TO_MS, + v_cruise=65.0 * CV.MPH_TO_MS, has_lead=True, engaged=True, + ) + assert params.get(PARAM_FOLLOW_CITY) == 3 + assert params.get(PARAM_FOLLOW_HWY) == 6 + + +def test_stalk_band_selects_city_or_hwy(): + """Stalk bump uses the same MAX-primary cut as live follow.""" + def v(mph): + return mph * CV.MPH_TO_MS + + assert follow_stalk_band_is_highway(v(60)) is True + assert follow_stalk_band_is_highway(v(25)) is False + assert follow_stalk_band_is_highway(v(40), v(70)) is True + assert follow_stalk_band_is_highway(v(40), v(45)) is False + assert follow_stalk_band_is_highway(v(55)) is True + # Highway MAX, including exactly 50, even while ego is still under 50. + assert follow_stalk_band_is_highway(v(25), v(70)) is True + assert follow_stalk_band_is_highway(v(40)) is False + assert follow_stalk_band_is_highway(v(50), v(45)) is False + assert follow_stalk_band_is_highway(v(50)) is True + assert follow_stalk_band_is_highway(v(50), v(50)) is True + assert follow_stalk_band_is_highway(v(50), v(70)) is True + # CarState.vCruise is 0 until published. That must not force City at 60. + assert follow_stalk_band_is_highway(v(60), 0.0) is True + # City MAX wins over a highway ego speed. + assert follow_stalk_band_is_highway(v(60), v(45)) is False + assert follow_band_is_highway( + v(55), v_cruise=v(45), engaged=True, has_lead=True, + ) is False + + +def test_published_cruise_ignores_unset_and_zero(): + assert published_cruise_ms(0) is None + assert published_cruise_ms(255) is None + assert published_cruise_ms(None) is None + got = published_cruise_ms(70.0 * CV.MPH_TO_KPH) + assert got == pytest.approx(70.0 * CV.MPH_TO_MS) + + +def test_persist_stalk_writes_matching_band_and_hud(): + """MAX picks the param the bump writes. Full press is not this path.""" + from openpilot.selfdrive.controls.lib.hypermile import persist_follow_distance + + def bump(ego_mph, max_mph=None, *, closer=True, cruise_ms=None): + params = FakeParams(follow=4, city=3, hwy=3, migrated=True) + v_cruise = cruise_ms + if max_mph is not None: + v_cruise = max_mph * CV.MPH_TO_MS + persist_follow_distance( + params, closer=closer, v_ego=ego_mph * CV.MPH_TO_MS, v_cruise=v_cruise, + has_lead=True, engaged=True, + ) + return params + + # ego 60, including the 0 cruise reading that used to step City. + hwy = bump(60, cruise_ms=0.0) + assert hwy.get(PARAM_FOLLOW_HWY) == 2 + assert hwy.get(PARAM_FOLLOW_CITY) == 3 + assert hwy.get(PARAM_FOLLOW) == 2 + + # Under 50 with a highway MAX still steps Highway (accelerating up to it). + climbing = bump(25, max_mph=70) + assert climbing.get(PARAM_FOLLOW_HWY) == 2 + assert climbing.get(PARAM_FOLLOW_CITY) == 3 + assert climbing.get(PARAM_FOLLOW) == 2 + + city = bump(25, max_mph=45) + assert city.get(PARAM_FOLLOW_CITY) == 2 + assert city.get(PARAM_FOLLOW_HWY) == 3 + assert city.get(PARAM_FOLLOW) == 2 + + mid_hwy = bump(40, max_mph=70, closer=False) + assert mid_hwy.get(PARAM_FOLLOW_HWY) == 4 + assert mid_hwy.get(PARAM_FOLLOW_CITY) == 3 + assert mid_hwy.get(PARAM_FOLLOW) == 4 + + mid_city = bump(40, max_mph=45) + assert mid_city.get(PARAM_FOLLOW_CITY) == 2 + assert mid_city.get(PARAM_FOLLOW_HWY) == 3 + assert mid_city.get(PARAM_FOLLOW) == 2 + + # Highway ego under a city MAX writes City, not Highway. + fast_city = bump(60, max_mph=45) + assert fast_city.get(PARAM_FOLLOW_CITY) == 2 + assert fast_city.get(PARAM_FOLLOW_HWY) == 3 + assert fast_city.get(PARAM_FOLLOW) == 2 + + # No MAX: ego 25 writes City. + slow = bump(25) + assert slow.get(PARAM_FOLLOW_CITY) == 2 + assert slow.get(PARAM_FOLLOW_HWY) == 3 + assert slow.get(PARAM_FOLLOW) == 2 + + # MAX exactly 50 writes Highway. + at_50 = bump(25, max_mph=50) + assert at_50.get(PARAM_FOLLOW_HWY) == 2 + assert at_50.get(PARAM_FOLLOW_CITY) == 3 + assert at_50.get(PARAM_FOLLOW) == 2 + + fast = bump(55, closer=False) + assert fast.get(PARAM_FOLLOW_HWY) == 4 + assert fast.get(PARAM_FOLLOW_CITY) == 3 + assert fast.get(PARAM_FOLLOW) == 4 + + +def test_full_press_does_not_step_follow(): + """2nd detent still nudges MAX. It does not write City or Highway follow.""" + from openpilot.selfdrive.controls.lib.hypermile import ( + CRUISE_STALK_UP_2ND, + consume_follow_stalk, + ) + + params = FakeParams(follow=4, city=3, hwy=5, migrated=True) + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=True, + raw_kph=80.0, prev_raw_kph=70.0, + detent=CRUISE_STALK_UP_2ND, + v_ego=25.0 * CV.MPH_TO_MS, v_cruise=70.0 * CV.MPH_TO_MS, + ) + assert level is None and undo is None + assert params.get(PARAM_FOLLOW_CITY) == 3 + assert params.get(PARAM_FOLLOW_HWY) == 5 + assert params.get(PARAM_FOLLOW) == 4 + + +def test_invalid_setpoints_do_not_blend(): + params = FakeParams(follow=0, city=0, hwy=8, migrated=True) + b = FollowDistanceBlend() + b.read_setpoints(params) + t, dist, extra = b.update(25.0, 0.05, engaged=True, has_lead=True, v_lead=25.0) + assert dist is None + assert t is None + assert extra is None + + +def test_open_a_is_slightly_slower_than_lead(): + v_lead = 20.0 + v_ego = v_lead * (1.0 + FOLLOW_OPEN_SLOW_FRAC) + a = follow_open_a_ms2(v_ego, v_lead) + assert a is not None and a < 0.0 + assert follow_open_a_ms2(v_lead * (1.0 - FOLLOW_OPEN_SLOW_FRAC), v_lead) is None + + +def test_planner_and_ui_wire_city_hwy_follow(): + from pathlib import Path + root = Path(__file__).resolve().parents[3] + planner = (root / "selfdrive/controls/lib/longitudinal_planner.py").read_text() + tici = (root / "selfdrive/ui/layouts/settings/driving_mannerisms.py").read_text() + mici = (root / "selfdrive/ui/mici/layouts/settings/driving_mannerisms.py").read_text() + keys = (root / "common/params_keys.h").read_text() + content = (root / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + nap_params = (root / "opendbc_repo/opendbc/car/tesla/preap/nap_params.py").read_text() + assert "FollowDistanceBlend" in planner + assert "v_cruise=follow_max_ms" in planner + assert "NAPFollowDistanceCity" in keys + assert "NAPFollowDistanceHwy" in keys + assert "FOLLOW_DISTANCE_CITY" in nap_params + assert "City Follow Distance" in tici + assert "Highway Follow Distance" in tici + assert "city follow distance" in mici + assert "highway follow distance" in mici + assert "Not Hypermile" in content + assert "FollowDistanceBlend" in planner + assert "apply_hill_climb" in planner diff --git a/selfdrive/controls/tests/test_following_distance.py b/selfdrive/controls/tests/test_following_distance.py index 0fd543dd60568c..283de8560f4069 100644 --- a/selfdrive/controls/tests/test_following_distance.py +++ b/selfdrive/controls/tests/test_following_distance.py @@ -1,14 +1,19 @@ import pytest import itertools -from parameterized import parameterized_class +from openpilot.common.parameterized import parameterized_class from cereal import log -from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import desired_follow_distance, get_T_FOLLOW +from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import get_safe_obstacle_distance, get_stopped_equivalence_factor, get_T_FOLLOW from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver -def run_following_distance_simulation(v_lead, t_end=100.0, e2e=False, personality=0): +def desired_follow_distance(v_ego, v_lead, t_follow=None): + if t_follow is None: + t_follow = get_T_FOLLOW() + return get_safe_obstacle_distance(v_ego, t_follow) - get_stopped_equivalence_factor(v_lead) + +def run_following_distance_simulation(v_lead, t_end=100.0, e2e=False, personality=0, nap_follow_dist=None): man = Maneuver( '', duration=t_end, @@ -19,6 +24,7 @@ def run_following_distance_simulation(v_lead, t_end=100.0, e2e=False, personalit breakpoints=[0.], e2e=e2e, personality=personality, + nap_follow_dist=nap_follow_dist, ) valid, output = man.evaluate() assert valid @@ -37,4 +43,5 @@ def test_following_distance(self): simulation_steady_state = run_following_distance_simulation(v_lead, e2e=self.e2e, personality=self.personality) correct_steady_state = desired_follow_distance(v_lead, v_lead, get_T_FOLLOW(self.personality)) err_ratio = 0.2 if self.e2e else 0.1 - assert simulation_steady_state == pytest.approx(correct_steady_state, abs=err_ratio * correct_steady_state + .5) + abs_err_margin = 0.5 if v_lead > 0.0 else 1.15 + assert simulation_steady_state == pytest.approx(correct_steady_state, abs=err_ratio * correct_steady_state + abs_err_margin) diff --git a/selfdrive/controls/tests/test_gap_lock_gesture.py b/selfdrive/controls/tests/test_gap_lock_gesture.py new file mode 100644 index 00000000000000..235f6f780f5e89 --- /dev/null +++ b/selfdrive/controls/tests/test_gap_lock_gesture.py @@ -0,0 +1,269 @@ +"""2 s engage-stalk hold. Long may be on, paused, or not yet taken. + +In-session CANCEL TX does not drop lateral. opendbc safety +`tesla_preap_tx.h` applies `pcm_cruise_check(false)` for lever == CANCEL +only when `!controls_allowed`. The Python swallow keeps cruiseEnabled and +enableLongControl through the hold. The repeated CANCEL is only the +stock-CC spoof (`gap_lock_cancel_hold_tx`), and it does not reset the +spoofer delay. +""" + +from pathlib import Path + +from opendbc.car.tesla.preap.engagement import PreAPEngagement +from opendbc.car.tesla.values import CruiseButtons + +from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause +from openpilot.selfdrive.controls.lib.gap_lock import gap_lock_arm_seq, gap_lock_cancel_hold_tx + +ROOT = Path(__file__).resolve().parents[3] + + +def _engaged(): + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + eng.cruiseEnabled = True + eng.enableLongControl = True + eng.enableJustCC = False + eng.pedal_speed_kph = 88.5 + eng._nap_gap_lock_enabled_override = True + eng._nap_can_valid = True + return eng + + +def _buttons(eng, *, cruise_buttons=0, prev=0, t_ms=1000, brake=False, v_ego=13.4): + return eng.process_buttons( + cruise_buttons=cruise_buttons, prev_cruise_buttons=prev, + curr_time_ms=t_ms, v_ego=v_ego, speed_units="MPH", + use_pedal=True, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=brake) + + +def _seq(eng) -> int: + return gap_lock_arm_seq(eng) + + +def test_two_seconds_arms_once_and_keeps_long(): + install_blinker_lat_pause() + eng = _engaged() + speed = eng.pedal_speed_kph + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=0, t_ms=10000) + assert _seq(eng) == 0 + assert eng.stalk_pull_time_ms == 10000 + assert eng.enableLongControl and eng.cruiseEnabled + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=11900) + assert _seq(eng) == 0 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=12000) + assert _seq(eng) == 1 + assert eng.pedal_speed_kph == speed + assert eng.enableLongControl and eng.cruiseEnabled + assert not eng.preap_cc_cancel_needed + assert eng._nap_gap_lock.cancel_hold + assert eng._nap_gap_lock.holding + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=13000) + assert _seq(eng) == 1 + _buttons(eng, cruise_buttons=0, prev=CruiseButtons.MAIN, t_ms=13100) + assert not eng._nap_set_take_speed_now + assert eng.enableLongControl and eng.cruiseEnabled + assert eng.stalk_pull_time_ms == 10000 + assert not eng._nap_gap_lock.cancel_hold + assert not eng._nap_gap_lock.holding + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=0, t_ms=20000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=22000) + assert _seq(eng) == 2 + + +def test_release_before_two_seconds_does_not_add(): + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=10000) + _buttons(eng, prev=CruiseButtons.MAIN, t_ms=11000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=0, t_ms=12000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=13900) + assert _seq(eng) == 0 + + +def test_cancel_hold_starts_at_half_a_second(): + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=10000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=10499) + assert not eng._nap_gap_lock.cancel_hold + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=10500) + assert eng._nap_gap_lock.cancel_hold + assert eng.preap_last_cc_spoof_ms == 10500 + assert gap_lock_cancel_hold_tx(False, True, 10) + assert not gap_lock_cancel_hold_tx(True, True, 10) + assert not gap_lock_cancel_hold_tx(False, True, 11) + assert not gap_lock_cancel_hold_tx(False, False, 10) + + +def test_disengaged_hold_arms_and_takes_long(): + """Rolling single pull engages lat+long; the 2 s hold still gap-locks.""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + eng._nap_gap_lock_enabled_override = True + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000) + assert eng.cruiseEnabled and eng.enableLongControl + assert eng.stalk_pull_time_ms == 1000 + assert eng._nap_set_take_speed_now + assert eng.pedal_speed_kph > 0 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=2999) + assert _seq(eng) == 0 + assert eng.enableLongControl + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=3000) + assert _seq(eng) == 1 + assert eng.enableLongControl and eng.cruiseEnabled + assert eng.pedal_speed_kph > 0 + + +def test_disengaged_tap_engages_lat_and_long(): + """A tap from off while rolling is full engage, not lat-only.""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + eng._nap_gap_lock_enabled_override = True + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000) + assert eng.cruiseEnabled and eng.enableLongControl + assert eng.stalk_pull_time_ms == 1000 + assert eng._nap_set_take_speed_now + assert eng.pedal_speed_kph > 0 + _buttons(eng, prev=CruiseButtons.MAIN, t_ms=1500) + assert eng.cruiseEnabled and eng.enableLongControl + assert _seq(eng) == 0 + + +def test_gap_lock_hold_from_off_at_a_stop_still_arms(): + """Foot-off pull at a stop waits for gas. A 2 s hold still takes long.""" + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + eng._nap_gap_lock_enabled_override = True + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000, v_ego=0.0) + assert eng.cruiseEnabled + assert not eng.enableLongControl + assert eng._nap_resume_wait_gas + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=2999, v_ego=0.0) + assert _seq(eng) == 0 + assert not eng.enableLongControl + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=3000, v_ego=0.0) + assert _seq(eng) == 1 + assert eng.enableLongControl and eng.cruiseEnabled + assert not eng._nap_resume_wait_gas + + +def test_resume_from_brake_hold_arms(): + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, brake=True, t_ms=2000) + _buttons(eng, brake=False, t_ms=3000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000) + assert eng.enableLongControl + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=5999) + assert _seq(eng) == 0 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=6000) + assert _seq(eng) == 1 + assert eng.enableLongControl + + +def test_one_pedal_resume_hold_arms(): + install_blinker_lat_pause() + eng = _engaged() + eng.enableLongControl = False + eng._one_pedal_pause_latched = True + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000) + assert eng.enableLongControl + assert not eng._one_pedal_pause_latched + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=6000) + assert _seq(eng) == 1 + assert eng.enableLongControl + + +def test_engage_while_gas_hold_arms(): + install_blinker_lat_pause() + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=750) + eng._nap_gap_lock_enabled_override = True + eng._nap_di_pedal_pos = 10.0 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=1000) + assert eng.enableLongControl + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=2999) + assert _seq(eng) == 0 + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=3000) + assert _seq(eng) == 1 + assert eng.enableLongControl + + +def test_standstill_hold_arms_and_takes_long(): + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, brake=True, t_ms=2000, v_ego=0.0) + _buttons(eng, brake=False, t_ms=3000, v_ego=0.0) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=4000, v_ego=0.0) + assert not eng.enableLongControl + assert eng._nap_resume_wait_gas + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=5999, v_ego=0.0) + assert _seq(eng) == 0 + assert not eng.enableLongControl + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=6000, v_ego=0.0) + assert _seq(eng) == 1 + assert eng.enableLongControl + assert not eng._nap_resume_wait_gas + + +def test_long_dropped_during_hold_still_arms(): + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=10000) + eng.enableLongControl = False + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=12000) + assert _seq(eng) == 1 + assert eng.enableLongControl and eng.cruiseEnabled + + +def test_brake_during_hold_does_not_arm(): + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=10000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, brake=True, t_ms=12000) + assert not eng.enableLongControl + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=13000) + assert _seq(eng) == 0 + + +def test_param_off_does_not_arm(): + install_blinker_lat_pause() + eng = _engaged() + eng._nap_gap_lock_enabled_override = False + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=10000) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=13000) + assert _seq(eng) == 0 + assert eng.enableLongControl + + +def test_cancel_and_can_invalid_abort(): + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=10000) + _buttons(eng, cruise_buttons=CruiseButtons.CANCEL, prev=CruiseButtons.MAIN, t_ms=11000) + assert not eng.cruiseEnabled + assert _seq(eng) == 0 + + eng = _engaged() + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=10000) + eng._nap_can_valid = False + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=CruiseButtons.MAIN, t_ms=13000) + assert _seq(eng) == 0 + assert eng.enableLongControl + + +def test_second_pull_inside_the_window_is_still_take_speed_now(): + install_blinker_lat_pause() + eng = _engaged() + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, t_ms=10000) + _buttons(eng, prev=CruiseButtons.MAIN, t_ms=10100) + _buttons(eng, cruise_buttons=CruiseButtons.MAIN, prev=0, t_ms=10200) + assert eng._nap_set_take_speed_now + assert eng.enableLongControl + assert _seq(eng) == 0 + + +def test_in_session_cancel_tx_does_not_drop_lateral(): + header = (ROOT / "opendbc_repo/opendbc/safety/modes/tesla_preap_tx.h").read_text() + assert "(lever == 1) && !controls_allowed" in header diff --git a/selfdrive/controls/tests/test_gap_lock_latch.py b/selfdrive/controls/tests/test_gap_lock_latch.py new file mode 100644 index 00000000000000..658e65eddbf53e --- /dev/null +++ b/selfdrive/controls/tests/test_gap_lock_latch.py @@ -0,0 +1,308 @@ +"""Gap-lock latch, clear, and actuator-guard slack.""" + +import pathlib +from unittest.mock import MagicMock + +import pytest + +from openpilot.selfdrive.controls.lib.gap_lock import ( + GAP_LOCK_ENGAGED_BANNER_S, + HUD_ENGAGED, + HUD_LOST, + HUD_NONE, + HUD_UNAVAILABLE, + GapLockLatch, + gap_lock_banner_active, + gap_lock_engaged_text, + gap_lock_hud_chip, + gap_lock_param_enabled, + slack_for_guard, +) +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2, + guard_follow_actuator_regen, + lead_follow_slack_m, +) + + +def _step(latch, **kw): + base = dict(enabled=True, long_on=True, seq=0, status=True, radar=True, + track_id=4, d_rel=28.0, stalk_exit=False, y_rel=0.0) + base.update(kw) + latch.update(0.05, **base) + + +def _arm(latch, d_rel=28.0, track_id=4, seq=1): + for _ in range(8): + _step(latch, seq=0, d_rel=d_rel, track_id=track_id) + _step(latch, seq=seq, d_rel=d_rel, track_id=track_id) + + +def test_median_in_range_latches_on_seq_change(): + latch = GapLockLatch() + samples = [27, 29, 28, 30, 26, 28, 29, 27] + for d in samples: + _step(latch, seq=0, d_rel=d) + assert latch.gap_m is None + _step(latch, seq=1, d_rel=28) + assert latch.track_id == 4 + assert latch.gap_m == pytest.approx(28.0) + assert latch.hud == HUD_ENGAGED + + +def test_vision_only_no_lead_and_out_of_range_do_not_latch(): + for radar, status, dist in ( + (False, True, 28.0), + (True, False, 28.0), + (True, True, 5.0), + (True, True, 100.0), + ): + latch = GapLockLatch() + for _ in range(4): + _step(latch, seq=0, radar=radar, status=status, d_rel=dist, track_id=-1 if not radar else 4) + _step(latch, seq=1, radar=radar, status=status, d_rel=dist, track_id=-1 if not radar else 4) + assert latch.gap_m is None + assert latch.hud == HUD_UNAVAILABLE + + +def test_failed_arm_keeps_an_existing_lock(): + latch = GapLockLatch() + _arm(latch, d_rel=28.0) + for _ in range(10): + _step(latch, seq=1, d_rel=100.0) + _step(latch, seq=2, d_rel=100.0) + assert latch.gap_m == pytest.approx(28.0) + assert latch.hud == HUD_UNAVAILABLE + + +def test_status_loss_holds_about_two_seconds_then_clears(): + latch = GapLockLatch() + _arm(latch) + for _ in range(39): + _step(latch, seq=1, status=False, radar=False, d_rel=None) + assert latch.gap_m == pytest.approx(28.0) + # The engage banner may still be in its 2 s window. The hold itself + # must not have fired the lost toast. + assert latch.hud != HUD_LOST + _step(latch, seq=1, status=True, radar=True, d_rel=27.0) + assert latch.gap_m == pytest.approx(28.0) + assert latch.track_id == 4 + # Just under 2 s still holds. The frame that reaches 2 s clears. + for _ in range(39): + _step(latch, seq=1, status=False, radar=False, d_rel=None) + assert latch.gap_m == pytest.approx(28.0) + assert latch.hud == HUD_NONE + _step(latch, seq=1, status=False, radar=False, d_rel=None) + assert latch.gap_m is None + assert latch.hud == HUD_LOST + + +def test_same_gap_radar_rematch_keeps_the_lock(): + """16:08:53: 2088 → 2698 at ~27 m while locked near 25 m. No toast.""" + latch = GapLockLatch() + _arm(latch, d_rel=25.1, track_id=2088) + _step(latch, seq=1, track_id=2698, d_rel=26.6, y_rel=0.3) + assert latch.gap_m == pytest.approx(25.1) + assert latch.track_id == 2698 + assert latch.hud != HUD_LOST + for _ in range(20): + _step(latch, seq=1, track_id=2698, d_rel=27.4, y_rel=-0.4) + assert latch.gap_m == pytest.approx(25.1) + assert latch.track_id == 2698 + assert latch.hud != HUD_LOST + # Once the engage banner has timed out, a same-gap swap still has no toast. + for _ in range(30): + _step(latch, seq=1, track_id=2698, d_rel=27.4, y_rel=-0.4) + assert latch.hud == HUD_NONE + _step(latch, seq=1, track_id=3001, d_rel=27.0, y_rel=0.2) + assert latch.track_id == 3001 + assert latch.gap_m == pytest.approx(25.1) + assert latch.hud == HUD_NONE + + +def test_rematch_window_is_five_meters_and_one_lane(): + latch = GapLockLatch() + _arm(latch, d_rel=25.0, track_id=1) + _step(latch, seq=1, track_id=2, d_rel=30.0, y_rel=1.5) + assert latch.track_id == 2 + assert latch.gap_m == pytest.approx(25.0) + assert latch.hud != HUD_LOST + + outside = GapLockLatch() + _arm(outside, d_rel=25.0, track_id=1) + _step(outside, seq=1, track_id=2, d_rel=30.2, y_rel=0.0) + assert outside.track_id == 1 + assert outside.gap_m == pytest.approx(25.0) + assert outside.hud != HUD_LOST + + offset = GapLockLatch() + _arm(offset, d_rel=25.0, track_id=1) + _step(offset, seq=1, track_id=2, d_rel=28.0, y_rel=-1.6) + assert offset.track_id == 1 + assert offset.gap_m == pytest.approx(25.0) + + +def test_vision_only_holds_and_the_same_track_resets_the_timer(): + latch = GapLockLatch() + _arm(latch) + for _ in range(30): + _step(latch, seq=1, status=True, radar=False, track_id=4, d_rel=28.0) + assert latch.gap_m == pytest.approx(28.0) + assert latch.hud != HUD_LOST + _step(latch, seq=1, status=True, radar=True, track_id=4, d_rel=27.5) + assert latch.track_id == 4 + for _ in range(30): + _step(latch, seq=1, status=True, radar=False, track_id=-1, d_rel=28.0) + assert latch.gap_m == pytest.approx(28.0) + assert latch.hud == 0 + + +def test_different_gap_clears_after_two_seconds_then_recapture(): + latch = GapLockLatch() + _arm(latch, track_id=4) + _step(latch, seq=1, track_id=9, d_rel=50.0, y_rel=0.2) + assert latch.gap_m == pytest.approx(28.0) + assert latch.track_id == 4 + assert latch.hud != HUD_LOST + for _ in range(40): + _step(latch, seq=1, track_id=9, d_rel=50.0, y_rel=0.2) + assert latch.gap_m is None + assert latch.hud == HUD_LOST + for _ in range(8): + _step(latch, seq=1, track_id=9, d_rel=40.0) + _step(latch, seq=2, track_id=9, d_rel=40.0) + assert latch.track_id == 9 + assert latch.gap_m == pytest.approx(40.0) + assert latch.hud == HUD_ENGAGED + + +def test_disengage_brake_stalk_and_param_clear_without_lost_toast(): + for kw in ( + dict(long_on=False), + dict(enabled=False), + dict(stalk_exit=True), + ): + latch = GapLockLatch() + _arm(latch) + _step(latch, seq=1, **kw) + assert latch.gap_m is None + assert latch.hud == 0 + + +def test_param_reader_ignores_mocks_and_missing_keys(): + assert gap_lock_param_enabled(MagicMock()) is False + + class Missing: + def get_bool(self, _key): + raise KeyError("NAPGapLock") + + class Off: + def get_bool(self, _key): + return False + + class On: + def get_bool(self, _key): + return True + + assert gap_lock_param_enabled(Missing()) is False + assert gap_lock_param_enabled(Off()) is False + assert gap_lock_param_enabled(On()) is True + + +def test_hold_preview_is_the_median_and_clears_once_latched(): + latch = GapLockLatch() + for _ in range(8): + _step(latch, seq=0, d_rel=30.0, holding=True) + assert latch.gap_m is None + assert latch.preview_m == pytest.approx(30.0) + assert latch.preview_track == 4 + _step(latch, seq=1, d_rel=30.0, holding=True) + assert latch.gap_m == pytest.approx(30.0) + assert latch.preview_m is None + + +def test_preview_drops_when_the_hold_ends_without_a_latch(): + latch = GapLockLatch() + for _ in range(4): + _step(latch, holding=True, d_rel=22.0) + assert latch.preview_m == pytest.approx(22.0) + _step(latch, holding=False, d_rel=22.0) + assert latch.preview_m is None + assert latch.gap_m is None + + +def test_preview_while_long_is_paused(): + latch = GapLockLatch() + for _ in range(6): + _step(latch, long_on=False, holding=True, d_rel=36.0) + assert latch.gap_m is None + assert latch.preview_m == pytest.approx(36.0) + + +def test_engaged_banner_is_two_seconds_and_chip_stays(): + assert GAP_LOCK_ENGAGED_BANNER_S == pytest.approx(2.0) + latch = GapLockLatch() + _arm(latch, d_rel=15.0) + assert latch.gap_m == pytest.approx(15.0) + assert latch.hud == HUD_ENGAGED + assert gap_lock_banner_active(latch.hud) + assert gap_lock_hud_chip(latch.gap_m) == "LOCK 15m" + assert not gap_lock_banner_active(HUD_NONE) + assert gap_lock_banner_active(HUD_UNAVAILABLE) + assert gap_lock_banner_active(HUD_LOST) + + # _arm sets the pulse at the current clock. Each later step is 0.05 s. + # Still up one frame inside the window. The planner clock is a running + # sum, so the last frame can land a hair under 2.0 s and take one more. + dt = 0.05 + for _ in range(int(GAP_LOCK_ENGAGED_BANNER_S / dt) - 1): + _step(latch, seq=1, d_rel=15.0) + assert latch.hud == HUD_ENGAGED + assert latch.gap_m == pytest.approx(15.0) + assert gap_lock_hud_chip(latch.gap_m) == "LOCK 15m" + + for _ in range(2): + _step(latch, seq=1, d_rel=15.0) + assert latch.hud == HUD_NONE + assert not gap_lock_banner_active(latch.hud) + assert latch.gap_m == pytest.approx(15.0) + assert gap_lock_hud_chip(latch.gap_m) == "LOCK 15m" + + # A new hold starts the banner again. A soft clear still has no toast. + _step(latch, seq=2, d_rel=15.0) + assert latch.hud == HUD_ENGAGED + _step(latch, seq=2, stalk_exit=True) + assert latch.gap_m is None + assert latch.hud == HUD_NONE + assert not gap_lock_banner_active(latch.hud) + + # The onroad event follows the pulse. A latched gapLockM alone must not + # keep the bottom banner up; the chip reads that field on its own. + src = (pathlib.Path(__file__).resolve().parents[3] / "selfdrive/selfdrived/selfdrived.py").read_text() + assert "gap_lock_banner_active" in src + assert "gap_m > 0.0 or gap_ev" not in src + + +def test_onroad_text_and_chip_while_locked_gone_when_clear(): + assert gap_lock_engaged_text(0) is None + assert gap_lock_engaged_text(None) is None + assert gap_lock_hud_chip(0.0) is None + assert gap_lock_engaged_text(28.4) == "Gap lock engaged 28 m" + assert gap_lock_hud_chip(28.4) == "LOCK 28m" + hud = (pathlib.Path(__file__).resolve().parents[3] / "selfdrive/ui/onroad/hud_renderer.py").read_text() + assert "gap_lock_hud_chip" in hud + assert "_draw_gap_lock" in hud + + +def test_guard_slack_uses_locked_meters_and_keeps_mild_floor(): + time_gap = lead_follow_slack_m(30.0, 20.0, 1.3) + assert slack_for_guard(30.0, 20.0, 1.3, 0) == time_gap + assert slack_for_guard(30.0, 20.0, 1.3, 0.0) == time_gap + assert slack_for_guard(30.0, 20.0, 1.3, 28.0) == pytest.approx(2.0) + # A locked gap that is already matched is steady. It does not take the + # mild settle. A command that is on that settle still cannot reach the rail. + clipped = guard_follow_actuator_regen(-1.23, 0.0, slack=0.0) + assert clipped == pytest.approx(0.0) + mild = guard_follow_actuator_regen(-1.23, -0.22, slack=0.0) + assert mild == pytest.approx(LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2) + assert LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2 == pytest.approx(-0.22) diff --git a/selfdrive/controls/tests/test_hill_climb.py b/selfdrive/controls/tests/test_hill_climb.py new file mode 100644 index 00000000000000..596afdb2a9de10 --- /dev/null +++ b/selfdrive/controls/tests/test_hill_climb.py @@ -0,0 +1,553 @@ +"""Hypermile Hill Climb: grade hold, crest/downhill ease, planner wiring.""" +import math +from pathlib import Path + +import pytest + +from openpilot.selfdrive.controls.lib.hill_climb import ( + CLIMB_EXTRA_MAX_MS2, + CREST_EASE_MS2, + DOWNHILL_EASE_MS2, + GRAVITY_MS2, + PARAM_HILL_CLIMB, + PITCH_CLIMB_RAD, + PITCH_CREST_RAD, + apply_hill_climb, + climb_authority_ms2, + downhill_ease_ms2, + grade_load_ms2, + hill_climb_applies, + read_hypermile_hill_climb, +) +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_APPROACH_A_MS2, + LEAD_APPROACH_MILD_A_MS2, +) +from openpilot.selfdrive.controls.tests.test_hypermile import FakeParams +from openpilot.selfdrive.mapd.constants import ( + LOOKAHEAD_EARLY, + MODE_FOLLOW, + TRACK_DEADBAND_MS, + TRACK_TAPER_MS, + map_accel_a_ms2, +) +from openpilot.selfdrive.mapd.map_speed_policy import map_track_accel_ms2 + + +UPHILL_RAD = math.radians(4.0) # existing full-loop fixture; clearly above 2° +DOWNHILL_RAD = math.radians(-4.0) +FLAT_RAD = 0.0 +# Accel 1 + Early (Hypermile eco snap). +FLAT_ACCEL_1 = map_accel_a_ms2(LOOKAHEAD_EARLY, 1) + + +def _planner_harness(): + """Planner fixtures need cereal + compiled params_pyx (scons).""" + repo = Path(__file__).resolve().parents[3] + if not (repo / "opendbc_repo/opendbc/car/car.capnp").is_file(): + pytest.skip("opendbc/cereal not checked out") + pytest.importorskip("capnp") + try: + import openpilot.common.params_pyx # noqa: F401 + except ModuleNotFoundError: + pytest.skip("params_pyx not built") + from openpilot.common.constants import CV + from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState + from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import get_T_FOLLOW + from openpilot.selfdrive.controls.lib.longitudinal_planner import ( + LongitudinalPlanner, + get_max_accel, + ) + from openpilot.selfdrive.controls.tests.test_tesla_preap_following import ( + STOP_DISTANCE_M, + _ConstantAccelerationMpc, + _PlannerInputs, + _make_preap_params, + ) + from openpilot.selfdrive.modeld.constants import ModelConstants + import numpy as np + from cereal import log, messaging + + class HillParams: + def __init__(self, *, hypermile=False, hill_climb=True, map_mode=MODE_FOLLOW, accel=1, lookahead=LOOKAHEAD_EARLY): + self.hypermile = hypermile + self.hill_climb = hill_climb + self.map_mode = map_mode + self.accel = accel + self.lookahead = lookahead + + def get(self, key, return_default=False): + if key == "NAPFollowDistance": + return 4 + if key == "NAPMapSpeedMode": + return self.map_mode + if key == "NAPMapSpeedOffsetMph": + return -5 + if key == "NAPMapSpeedLookahead": + return self.lookahead + if key == "NAPMapSpeedAccel": + return self.accel + raise AssertionError(key) + + def get_bool(self, key): + if key == "NAPAdaptiveAccel": + return True + if key == "NAPHypermile": + return self.hypermile + if key == "NAPHypermileHillClimb": + return self.hill_climb + raise AssertionError(key) + + def planner_inputs(v_ego, v_cruise_ms, pitch): + radar = messaging.new_message("radarState").radarState + controls = messaging.new_message("controlsState").controlsState + selfdrive = messaging.new_message("selfdriveState").selfdriveState + car_state = messaging.new_message("carState").carState + car_control = messaging.new_message("carControl").carControl + live_parameters = messaging.new_message("liveParameters").liveParameters + model = messaging.new_message("modelV2").modelV2 + controls.longControlState = LongCtrlState.pid + selfdrive.personality = log.LongitudinalPersonality.standard + car_state.vEgo = v_ego + car_state.vCruise = v_cruise_ms * CV.MS_TO_KPH + car_control.orientationNED = [0.0, float(pitch), 0.0] + model.position.x = (v_ego * np.array(ModelConstants.T_IDXS)).tolist() + model.velocity.x = (v_ego * np.ones_like(ModelConstants.T_IDXS)).tolist() + model.acceleration.x = np.zeros_like(ModelConstants.T_IDXS).tolist() + model.meta.disengagePredictions.gasPressProbs = [1.0] * 6 + return _PlannerInputs({ + "radarState": radar, + "controlsState": controls, + "selfdriveState": selfdrive, + "carState": car_state, + "carControl": car_control, + "liveParameters": live_parameters, + "modelV2": model, + }) + + def run_map_climb(hypermile, hill_climb, pitch, *, v_ego=20.0, v_cruise=31.29, mpc_a=0.0, + has_lead=False, v_lead=None, d_rel=80.0): + params = HillParams(hypermile=hypermile, hill_climb=hill_climb) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=mpc_a) + planner.prev_accel_clip = [-1.2, get_max_accel(v_ego)] + inputs = planner_inputs(v_ego, v_cruise, pitch) + if has_lead: + lead = inputs["radarState"].leadOne + lead.status = True + lead.vLead = float(v_ego if v_lead is None else v_lead) + lead.dRel = float(d_rel) + planner.update(inputs) + return planner + + return { + "HillParams": HillParams, + "planner_inputs": planner_inputs, + "run_map_climb": run_map_climb, + "LongitudinalPlanner": LongitudinalPlanner, + "get_max_accel": get_max_accel, + "_ConstantAccelerationMpc": _ConstantAccelerationMpc, + "_make_preap_params": _make_preap_params, + "get_T_FOLLOW": get_T_FOLLOW, + "STOP_DISTANCE_M": STOP_DISTANCE_M, + } + + +def test_default_on_and_inert_unless_hypermile(): + assert hill_climb_applies(True, False) is False + assert hill_climb_applies(False, True) is False + assert hill_climb_applies(True, True) is True + assert read_hypermile_hill_climb(FakeParams(bools={PARAM_HILL_CLIMB: True})) is True + assert read_hypermile_hill_climb(FakeParams(bools={PARAM_HILL_CLIMB: False})) is False + # Missing key / test double without the param → On (keys.h default). + assert read_hypermile_hill_climb(object()) is True + + +def test_uphill_under_max_raises_accel1_authority(): + flat = FLAT_ACCEL_1 + assert flat == pytest.approx(0.30, abs=1e-9) + uphill = climb_authority_ms2(flat, UPHILL_RAD) + assert uphill > flat + expected = flat + min(CLIMB_EXTRA_MAX_MS2, GRAVITY_MS2 * math.sin(UPHILL_RAD)) + assert uphill == pytest.approx(expected) + # 4° is ~0.68 m/s² of gravity — Accel 1 alone sags. + assert grade_load_ms2(UPHILL_RAD) > flat + assert PITCH_CLIMB_RAD == pytest.approx(math.radians(2.0)) + assert UPHILL_RAD > PITCH_CLIMB_RAD + + +def test_flat_and_gates_leave_cmd_alone(): + a_flat = 0.30 + kwargs = dict( + prev_pitch_rad=0.0, + v_ego_ms=20.0, + v_cruise_ms=31.29, + a_cmd=a_flat, + in_deadband=False, + ) + assert apply_hill_climb(pitch_rad=FLAT_RAD, hypermile_on=False, hill_climb_on=True, **kwargs) == a_flat + assert apply_hill_climb(pitch_rad=UPHILL_RAD, hypermile_on=False, hill_climb_on=True, **kwargs) == a_flat + assert apply_hill_climb(pitch_rad=UPHILL_RAD, hypermile_on=True, hill_climb_on=False, **kwargs) == a_flat + assert apply_hill_climb(pitch_rad=FLAT_RAD, hypermile_on=True, hill_climb_on=True, **kwargs) == a_flat + # Below the 2° gate: crown / IMU noise is not a climb. + almost = PITCH_CLIMB_RAD - 1e-3 + assert apply_hill_climb(pitch_rad=almost, hypermile_on=True, hill_climb_on=True, **kwargs) == a_flat + + +def test_crest_and_downhill_ease_direction(): + hold = 0.0 + down = apply_hill_climb( + pitch_rad=DOWNHILL_RAD, + prev_pitch_rad=0.0, + v_ego_ms=31.29, + v_cruise_ms=31.29, + a_cmd=hold, + in_deadband=True, + hypermile_on=True, + hill_climb_on=True, + ) + assert down < 0.0 + assert down >= -DOWNHILL_EASE_MS2 - 1e-9 + assert abs(down) < 0.55 # under Early map brake; not a Late bite + + crest = apply_hill_climb( + pitch_rad=PITCH_CREST_RAD - 0.005, + prev_pitch_rad=UPHILL_RAD, + v_ego_ms=31.20, + v_cruise_ms=31.29, + a_cmd=hold, + in_deadband=True, + hypermile_on=True, + hill_climb_on=True, + ) + assert crest == pytest.approx(-CREST_EASE_MS2) + assert downhill_ease_ms2(DOWNHILL_RAD) <= DOWNHILL_EASE_MS2 + assert downhill_ease_ms2(-PITCH_CLIMB_RAD) >= CREST_EASE_MS2 + + # Under MAX on a downhill: lower +a, do not dump regen away from MAX. + eased_up = apply_hill_climb( + pitch_rad=DOWNHILL_RAD, + prev_pitch_rad=0.0, + v_ego_ms=20.0, + v_cruise_ms=31.29, + a_cmd=0.30, + in_deadband=False, + hypermile_on=True, + hill_climb_on=True, + ) + assert 0.0 <= eased_up < 0.30 + + +def test_never_raises_max_or_fights_lead_brake(): + v_cruise = 31.29 + # At MAX / deadband: leave map hold (0). Do not invent +g·sin past MAX. + hold = apply_hill_climb( + pitch_rad=UPHILL_RAD, + prev_pitch_rad=UPHILL_RAD, + v_ego_ms=v_cruise, + v_cruise_ms=v_cruise, + a_cmd=0.0, + in_deadband=True, + hypermile_on=True, + hill_climb_on=True, + ) + extra = min(CLIMB_EXTRA_MAX_MS2, grade_load_ms2(UPHILL_RAD)) + assert hold == pytest.approx(0.0) + assert hold < extra + assert hold < climb_authority_ms2(FLAT_ACCEL_1, UPHILL_RAD) + + # Lead / MPC already braking: hill climb must not cancel it. + lead_a = -LEAD_APPROACH_A_MS2 + assert apply_hill_climb( + pitch_rad=UPHILL_RAD, + prev_pitch_rad=UPHILL_RAD, + v_ego_ms=20.0, + v_cruise_ms=v_cruise, + a_cmd=lead_a, + in_deadband=False, + hypermile_on=True, + hill_climb_on=True, + ) == lead_a + + # Downhill + already braking: keep the harder of lead/map vs light ease. + hard = -2.0 + assert apply_hill_climb( + pitch_rad=DOWNHILL_RAD, + prev_pitch_rad=0.0, + v_ego_ms=v_cruise, + v_cruise_ms=v_cruise, + a_cmd=hard, + in_deadband=True, + hypermile_on=True, + hill_climb_on=True, + ) == hard + + +def test_under_max_downhill_does_not_regen(): + """~50 mph under a 54 MAX used to be TRACK_TAPER 'near MAX' and regen'd.""" + v_cruise = 24.14 # ~54 mph (posted 55, Hypermile eco) + v_ego = 22.35 # ~50 mph — several mph under, inside old 2.0 m/s taper + assert TRACK_DEADBAND_MS < (v_cruise - v_ego) < TRACK_TAPER_MS + + kwargs = dict( + pitch_rad=DOWNHILL_RAD, + prev_pitch_rad=0.0, + v_ego_ms=v_ego, + v_cruise_ms=v_cruise, + in_deadband=False, + hypermile_on=True, + hill_climb_on=True, + ) + # MPC / tapered hold: leave 0. Do not invent crest/downhill regen. + assert apply_hill_climb(a_cmd=0.0, **kwargs) == pytest.approx(0.0) + # Positive climb leftover: reduce +a only (gravity already pulls to MAX). + eased_up = apply_hill_climb(a_cmd=0.30, **kwargs) + assert 0.0 <= eased_up < 0.30 + # Flattening crest under MAX: still no regen. + crest = apply_hill_climb( + a_cmd=0.0, + pitch_rad=PITCH_CREST_RAD - 0.005, + prev_pitch_rad=UPHILL_RAD, + v_ego_ms=v_ego, + v_cruise_ms=v_cruise, + in_deadband=False, + hypermile_on=True, + hill_climb_on=True, + ) + assert crest == pytest.approx(0.0) + + +def test_deadband_uphill_does_not_overshoot(): + """Deadband +g·sin used to fight hold 0, punch past MAX, Accel-5 hunt.""" + v_cruise = 24.14 + hold = apply_hill_climb( + pitch_rad=UPHILL_RAD, + prev_pitch_rad=UPHILL_RAD, + v_ego_ms=v_cruise, + v_cruise_ms=v_cruise, + a_cmd=0.0, + in_deadband=True, + hypermile_on=True, + hill_climb_on=True, + ) + assert hold == pytest.approx(0.0) + assert hold < grade_load_ms2(UPHILL_RAD) + + +def test_at_or_above_max_downhill_still_eases(): + v_cruise = 24.14 + down = apply_hill_climb( + pitch_rad=DOWNHILL_RAD, + prev_pitch_rad=0.0, + v_ego_ms=v_cruise, + v_cruise_ms=v_cruise, + a_cmd=0.0, + in_deadband=True, + hypermile_on=True, + hill_climb_on=True, + ) + assert down < 0.0 + assert down >= -DOWNHILL_EASE_MS2 - 1e-9 + assert abs(down) < 0.55 + + # Slightly above MAX, outside deadband: light ease still allowed. + above = apply_hill_climb( + pitch_rad=DOWNHILL_RAD, + prev_pitch_rad=0.0, + v_ego_ms=v_cruise + TRACK_DEADBAND_MS + 0.05, + v_cruise_ms=v_cruise, + a_cmd=0.0, + in_deadband=False, + hypermile_on=True, + hill_climb_on=True, + ) + assert above < 0.0 + assert above >= -DOWNHILL_EASE_MS2 - 1e-9 + + +def test_under_max_uphill_still_has_climb_authority(): + v_cruise = 24.14 + v_ego = 20.0 + extra = min(CLIMB_EXTRA_MAX_MS2, grade_load_ms2(UPHILL_RAD)) + climb = apply_hill_climb( + pitch_rad=UPHILL_RAD, + prev_pitch_rad=UPHILL_RAD, + v_ego_ms=v_ego, + v_cruise_ms=v_cruise, + a_cmd=FLAT_ACCEL_1, + in_deadband=False, + hypermile_on=True, + hill_climb_on=True, + ) + assert climb == pytest.approx(FLAT_ACCEL_1 + extra) + # From a hold, still add grade so Accel 1 leftover can walk toward MAX. + from_hold = apply_hill_climb( + pitch_rad=UPHILL_RAD, + prev_pitch_rad=UPHILL_RAD, + v_ego_ms=v_ego, + v_cruise_ms=v_cruise, + a_cmd=0.0, + in_deadband=False, + hypermile_on=True, + hill_climb_on=True, + ) + assert from_hold == pytest.approx(extra) + + +def test_planner_gates_and_uphill_authority(): + h = _planner_harness() + v_ego = 20.0 + v_cruise = 31.29 + flat_a = map_track_accel_ms2(v_ego, v_cruise, FLAT_ACCEL_1) + assert flat_a is not None and flat_a > 0.0 + + off = h["run_map_climb"](False, True, UPHILL_RAD, v_ego=v_ego, v_cruise=v_cruise) + hill_off = h["run_map_climb"](True, False, UPHILL_RAD, v_ego=v_ego, v_cruise=v_cruise) + flat = h["run_map_climb"](True, True, FLAT_RAD, v_ego=v_ego, v_cruise=v_cruise) + climb = h["run_map_climb"](True, True, UPHILL_RAD, v_ego=v_ego, v_cruise=v_cruise) + + assert off.output_a_target == pytest.approx(flat_a, abs=0.06) + assert hill_off.output_a_target == pytest.approx(flat_a, abs=0.06) + assert flat.output_a_target == pytest.approx(flat_a, abs=0.06) + assert climb.output_a_target > flat.output_a_target + 0.20 + # Still under cruise safety clip; never a MAX raise (vCruise untouched). + assert climb.output_a_target <= h["get_max_accel"](v_ego) + 1e-9 + assert climb.output_a_target <= climb_authority_ms2(flat_a, UPHILL_RAD) + 1e-6 + + +def test_planner_map_climb_does_not_replace_mpc_when_lead_present(): + """Valid lead + under MAX: keep non-negative MPC a. Do not command map climb.""" + h = _planner_harness() + v_ego = 21.5 # ~48 mph — Justin's "dropped and would not rematch" + v_cruise = 24.6 # ~55 mph HUD MAX + mpc_a = 0.05 + flat_a = map_track_accel_ms2(v_ego, v_cruise, FLAT_ACCEL_1) + assert flat_a is not None and flat_a > mpc_a + + no_lead = h["run_map_climb"]( + True, True, FLAT_RAD, v_ego=v_ego, v_cruise=v_cruise, mpc_a=mpc_a, has_lead=False, + ) + with_lead = h["run_map_climb"]( + True, True, FLAT_RAD, v_ego=v_ego, v_cruise=v_cruise, mpc_a=mpc_a, has_lead=True, + ) + uphill_lead = h["run_map_climb"]( + True, True, UPHILL_RAD, v_ego=v_ego, v_cruise=v_cruise, mpc_a=mpc_a, has_lead=True, + ) + + assert no_lead.output_a_target == pytest.approx(flat_a, abs=0.06) + assert with_lead.output_a_target == pytest.approx(mpc_a, abs=0.08) + assert with_lead.output_a_target < flat_a - 0.10 + # Hill Climb must not add +g·sin toward MAX while a lead is present. + assert uphill_lead.output_a_target == pytest.approx(mpc_a, abs=0.08) + + +def test_planner_map_decel_still_allowed_above_max_with_lead(): + """Above MAX: map decel still mins in even when a lead is present.""" + h = _planner_harness() + v_cruise = 22.0 + v_ego = v_cruise + TRACK_TAPER_MS + 0.5 + with_lead = h["run_map_climb"]( + True, True, FLAT_RAD, v_ego=v_ego, v_cruise=v_cruise, mpc_a=0.0, has_lead=True, + ) + no_lead = h["run_map_climb"]( + True, True, FLAT_RAD, v_ego=v_ego, v_cruise=v_cruise, mpc_a=0.0, has_lead=False, + ) + assert with_lead.output_a_target < -0.20 + assert no_lead.output_a_target < -0.20 + assert with_lead.output_a_target == pytest.approx(no_lead.output_a_target, abs=0.08) + + +def test_planner_lead_still_wins_on_uphill(): + h = _planner_harness() + v_ego = 26.8 + v_lead = 22.4 + v_cruise = 31.29 + t_follow = h["get_T_FOLLOW"](nap_follow_dist=4) + d_follow = t_follow * v_lead + h["STOP_DISTANCE_M"] + v_rel = v_ego - v_lead + rel_need = (v_rel * v_rel) / (2.0 * LEAD_APPROACH_A_MS2) + d_rel = d_follow + rel_need + + params = h["HillParams"](hypermile=True, hill_climb=True) + planner = h["LongitudinalPlanner"](h["_make_preap_params"](), init_v=v_ego, params=params) + planner.mpc = h["_ConstantAccelerationMpc"](v_ego, acceleration_mps2=0.0) + planner.prev_accel_clip = [-1.2, h["get_max_accel"](v_ego)] + inputs = h["planner_inputs"](v_ego, v_cruise, UPHILL_RAD) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = d_rel + lead.vLead = v_lead + for _ in range(16): + planner.update(inputs) + # The unified controller owns the lead: it brakes for the 4.4 m/s close on the + # hill (proportional to the kinematic need, firmer than the EV mild settle), + # and never lets the climb's +a through. + steady = float(planner.output_a_target) + assert -1.2 <= steady < -LEAD_APPROACH_MILD_A_MS2 + + planner.mpc = h["_ConstantAccelerationMpc"](v_ego, acceleration_mps2=-2.0) + planner.update(inputs) + assert float(planner.output_a_target) == pytest.approx(steady, abs=0.1) + lead.aLeadK = -0.80 + planner.mpc = h["_ConstantAccelerationMpc"](v_ego, acceleration_mps2=-2.0) + planner.update(inputs) + # A braking lead is firmer still, within the jerk limit and short of a brick wall. + assert float(planner.output_a_target) < steady + assert float(planner.output_a_target) >= -1.5 + + +def test_planner_crest_ease_near_max(): + h = _planner_harness() + v_cruise = 31.29 + planner = h["run_map_climb"](True, True, PITCH_CREST_RAD - 0.005, v_ego=v_cruise, v_cruise=v_cruise) + # First frame has prev_pitch=0 so no crest; seed a climb then flatten. + planner._hill_pitch = UPHILL_RAD + inputs = h["planner_inputs"](v_cruise, v_cruise, PITCH_CREST_RAD - 0.005) + planner.mpc = h["_ConstantAccelerationMpc"](v_cruise, acceleration_mps2=0.0) + planner.prev_accel_clip = [-1.2, h["get_max_accel"](v_cruise)] + planner.update(inputs) + assert planner.output_a_target == pytest.approx(-CREST_EASE_MS2, abs=0.06) + + +def test_settings_and_docs_wire_hill_climb(): + root = Path(__file__).resolve().parents[3] + tici = (root / "selfdrive/ui/layouts/settings/driving_mannerisms.py").read_text() + mici = (root / "selfdrive/ui/mici/layouts/settings/driving_mannerisms.py").read_text() + nap = (root / "selfdrive/ui/layouts/settings/nap.py").read_text() + content = (root / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + keys = (root / "common/params_keys.h").read_text() + planner = (root / "selfdrive/controls/lib/longitudinal_planner.py").read_text() + docs = (root / "docs-nap/hypermile.md").read_text() + readme = (root / "docs-nap/README.md").read_text() + releases = (root / "RELEASES.md").read_text() + arch = (root / "docs-nap/architecture.md").read_text() + + assert "Hill Climb" in tici + assert "NAP_HYPERMILE_HILL_CLIMB" in tici + assert "hill climb" in mici + assert "NAP_HYPERMILE_HILL_CLIMB" in mici + assert "put_bool(NAP_HYPERMILE_HILL_CLIMB, True)" in nap + assert "NAPHypermileHillClimb" in keys + assert 'BOOL, "1"' in next(ln for ln in keys.splitlines() if '"NAPHypermileHillClimb"' in ln) + assert "apply_hill_climb" in planner + assert "maps-elevation lookahead" in planner + assert "orientationNED" in planner + assert "has_valid_lead" in planner + assert "map_climb_replaces_mpc" in planner + hill = (root / "selfdrive/controls/lib/hill_climb.py").read_text() + assert "TRACK_TAPER_MS" not in hill + assert "_at_or_above_max" in hill + assert "NAPHypermileHillClimb" in content + assert "Hill Climb" in docs + assert "maps-elevation lookahead" in docs.lower() or "not included" in docs.lower() + assert "IMU pitch" in docs or "IMU-pitch" in docs + assert "hill climb" in readme.lower() or "Hill Climb" in readme + # Dedicated Hill Climb notes, not a later "Hill Climb kept" mention (#192). + hm = next( + p for p in releases.split("\n\n") + if "Hill Climb" in p and ( + "not included" in p.lower() or "NOT included" in p or "no maps-elevation" in p.lower() + ) + ) + assert "nap-release" in hm.lower() + assert "Hill Climb" in arch or "hill climb" in arch diff --git a/selfdrive/controls/tests/test_hypermile.py b/selfdrive/controls/tests/test_hypermile.py new file mode 100644 index 00000000000000..0d2ee6def3116d --- /dev/null +++ b/selfdrive/controls/tests/test_hypermile.py @@ -0,0 +1,728 @@ +"""Hypermile: eco snap/restore, posted-scaled offset, stock 1–7 stalk follow.""" +from types import SimpleNamespace + +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.hypermile import ( + ECO_MAP_ACCEL, + ECO_MAP_LOOKAHEAD_EARLY, + ECO_MAP_MODE_CAP, + ECO_MAP_MODE_FOLLOW, + ECO_MAP_OFFSET_MPH, + ECO_OFFSET_FULL_MPH, + ECO_OFFSET_START_MPH, + FOLLOW_DISTANCE_DEFAULT, + FOLLOW_DISTANCE_MAX, + FOLLOW_DISTANCE_MIN, + PARAM_FOLLOW_DISTANCE, + PARAM_HYPERMILE, + PARAM_SAVED, + PARAM_STEP_DOWN, + STEP_DOWN_MPH, + CRUISE_STALK_DN_1ST, + CRUISE_STALK_IDLE, + CRUISE_STALK_UP_1ST, + CRUISE_STALK_UP_2ND, + FollowStalkGesture, + apply_hypermile_toggle, + button_event_closer, + button_event_released, + consume_follow_stalk, + detect_follow_stalk, + eco_map_offset_mph, + eco_preset_from, + effective_nap_follow_dist, + follow_distance_hud_text, + poll_follow_distance_hud, + map_target_offset_kph, + maps_posted_known, + persist_follow_distance, + read_follow_distance, + read_hypermile_params, + read_hypermile_step_down, + step_down_applies, + step_down_offset_mph, + stepped_map_target_kph, + stalk_adjusts_follow, + step_follow_distance, +) +from openpilot.selfdrive.controls.lib.lead_approach import NAP_T_FOLLOW + + +class FakeParams: + def __init__(self, ints=None, bools=None): + self.ints = dict(ints or {}) + self.bools = dict(bools or {}) + + def get(self, key, return_default=False): + return self.ints.get(key) + + def get_bool(self, key): + return bool(self.bools.get(key, False)) + + def put(self, key, value): + self.ints[key] = value + + def put_bool(self, key, value): + self.bools[key] = bool(value) + + def remove(self, key): + self.ints.pop(key, None) + + +def test_default_off_and_stock_follow_four(): + assert read_hypermile_params(FakeParams()) is False + assert read_follow_distance(FakeParams()) == FOLLOW_DISTANCE_DEFAULT + + +def test_on_snaps_eco_and_off_restores_prior(): + params = FakeParams( + ints={ + "NAPMapSpeedMode": 0, + "NAPMapSpeedOffsetMph": 5, + "NAPMapSpeedLookahead": 0, + "NAPMapSpeedAccel": 8, + "NAPFollowDistance": 4, + }, + bools={ + "NAPAdaptiveAccel": False, + "NAPDriverLatHandoff": True, + "NAPDmSimulateLooking": False, + "NAPDmFalseAlertIgnore": False, + }, + ) + lat_before = params.get_bool("NAPDriverLatHandoff") + dm_before = params.get_bool("NAPDmSimulateLooking") + fai_before = params.get_bool("NAPDmFalseAlertIgnore") + follow_before = params.get("NAPFollowDistance") + + assert apply_hypermile_toggle(params, True) is True + assert params.get_bool(PARAM_HYPERMILE) is True + assert params.get_bool("NAPAdaptiveAccel") is True + assert params.get("NAPMapSpeedMode") == ECO_MAP_MODE_FOLLOW + # Do not snap a flat −5 — that forced town 30→25. Offset stays the user's. + assert params.get("NAPMapSpeedOffsetMph") == 5 + assert params.get("NAPMapSpeedLookahead") == ECO_MAP_LOOKAHEAD_EARLY + assert params.get("NAPMapSpeedAccel") == ECO_MAP_ACCEL + assert ECO_MAP_LOOKAHEAD_EARLY == 3 + assert ECO_MAP_ACCEL == 1 + assert params.get_bool("NAPDriverLatHandoff") is lat_before + assert params.get_bool("NAPDmSimulateLooking") is dm_before + assert params.get_bool("NAPDmFalseAlertIgnore") is fai_before + assert params.get("NAPFollowDistance") == follow_before + assert params.get(PARAM_SAVED) + + # Second On is a no-op (does not re-snapshot the eco values). + apply_hypermile_toggle(params, True) + assert params.get("NAPMapSpeedOffsetMph") == 5 + + assert apply_hypermile_toggle(params, False) is False + assert params.get_bool(PARAM_HYPERMILE) is False + assert params.get_bool("NAPAdaptiveAccel") is False + assert params.get("NAPMapSpeedMode") == 0 + assert params.get("NAPMapSpeedOffsetMph") == 5 + assert params.get("NAPMapSpeedLookahead") == 0 + assert params.get("NAPMapSpeedAccel") == 8 + assert params.get_bool("NAPDriverLatHandoff") is True + assert params.get_bool("NAPDmSimulateLooking") is False + assert params.get_bool("NAPDmFalseAlertIgnore") is False + assert params.get("NAPFollowDistance") == 4 + assert not params.get(PARAM_SAVED) + # Step-down / Hill Climb are independent — eco snap/restore must not touch them. + params.put_bool(PARAM_STEP_DOWN, True) + params.put_bool("NAPHypermileHillClimb", False) + apply_hypermile_toggle(params, True) + apply_hypermile_toggle(params, False) + assert params.get_bool(PARAM_STEP_DOWN) is True + assert params.get_bool("NAPHypermileHillClimb") is False + + +def test_eco_comfort_bias_early_light_not_late_bite(): + """Justin: early gentle regen, not late hard regen that makes people sick.""" + from openpilot.selfdrive.mapd.constants import LOOKAHEAD_EARLY, LOOKAHEAD_LATE, LOOKAHEAD_NORMAL + from openpilot.selfdrive.mapd.constants import map_brake_a_ms2, map_accel_a_ms2 + + current = { + "NAPAdaptiveAccel": True, + "NAPMapSpeedMode": ECO_MAP_MODE_CAP, + "NAPMapSpeedOffsetMph": 0, + "NAPMapSpeedLookahead": 1, # Late — the max-bite setting + "NAPMapSpeedAccel": 5, + } + eco = eco_preset_from(current) + assert eco["NAPMapSpeedMode"] == ECO_MAP_MODE_CAP + assert eco["NAPMapSpeedLookahead"] == ECO_MAP_LOOKAHEAD_EARLY == LOOKAHEAD_EARLY + assert eco["NAPMapSpeedLookahead"] != LOOKAHEAD_LATE + assert eco["NAPMapSpeedLookahead"] != LOOKAHEAD_NORMAL + assert "NAPMapSpeedOffsetMph" not in eco + assert eco["NAPMapSpeedAccel"] == ECO_MAP_ACCEL == 1 + # Early brake is lighter than Late; climb Accel 1 is below default 5. + assert map_brake_a_ms2(LOOKAHEAD_EARLY) < map_brake_a_ms2(LOOKAHEAD_LATE) + assert map_accel_a_ms2(LOOKAHEAD_EARLY, 1) < map_accel_a_ms2(LOOKAHEAD_NORMAL, 5) + + +def test_step_down_scales_with_posted_not_flat_minus_fifteen(): + """Hypermile On + Step Down On: same 50→80 scale as eco, −15 at 80.""" + assert STEP_DOWN_MPH == 15.0 + assert read_hypermile_step_down(FakeParams()) is False + assert step_down_applies(True, False) is False + assert step_down_applies(False, True) is False + assert step_down_applies(True, True) is True + + def _approx(a, b): + assert abs(float(a) - float(b)) < 1e-6, (a, b) + + _approx(step_down_offset_mph(30), 0.0) + _approx(step_down_offset_mph(50), 0.0) + _approx(step_down_offset_mph(65), -7.5) + _approx(step_down_offset_mph(75), -12.5) + _approx(step_down_offset_mph(80), -15.0) + _approx(step_down_offset_mph(90), -15.0) + _approx(step_down_offset_mph(None), 0.0) + + eco_off = -5.0 * CV.MPH_TO_KPH + posted_75 = 75.0 * CV.MPH_TO_KPH + # Eco alone still uses the −8 scale (75 → ~68.333). Step Down replaces it. + _approx(stepped_map_target_kph( + posted_75, hypermile_on=True, step_down_on=False, map_offset_kph=eco_off, + ), (75.0 + eco_map_offset_mph(75.0)) * CV.MPH_TO_KPH) + + cases = ( + (30.0, 30.0), + (50.0, 50.0), + (65.0, 57.5), + (75.0, 62.5), + (80.0, 65.0), + (90.0, 75.0), + ) + for posted_mph, want_mph in cases: + posted = posted_mph * CV.MPH_TO_KPH + got = stepped_map_target_kph( + posted, hypermile_on=True, step_down_on=True, map_offset_kph=eco_off, + ) + _approx(got, want_mph * CV.MPH_TO_KPH) + # Eco −8 does not stack; user slider is ignored. + _approx(got, (posted_mph + step_down_offset_mph(posted_mph)) * CV.MPH_TO_KPH) + + # Hypermile Off: step-down param On is inert; user offset still applies. + _approx(stepped_map_target_kph( + posted_75, hypermile_on=False, step_down_on=True, map_offset_kph=eco_off, + ), 70.0 * CV.MPH_TO_KPH) + # No posted: do not invent a −15 drop. + _approx(map_target_offset_kph(eco_off, hypermile_on=True, step_down_on=True), 0.0) + # Never more than 15 under; never above posted while stepping down. + raw = 80.0 * CV.MPH_TO_KPH + target = stepped_map_target_kph(raw, hypermile_on=True, step_down_on=True, map_offset_kph=-50.0) + _approx(target, 65.0 * CV.MPH_TO_KPH) + assert target <= raw + _approx(raw - target, 15.0 * CV.MPH_TO_KPH) + + +def test_eco_offset_scales_with_posted_not_flat_minus_five(): + """Hypermile On + Step Down Off: town stays posted; highway eases to −8.""" + assert ECO_OFFSET_START_MPH == 50.0 + assert ECO_OFFSET_FULL_MPH == 80.0 + assert ECO_MAP_OFFSET_MPH == -8 + + def _approx(a, b): + assert abs(float(a) - float(b)) < 1e-6, (a, b) + + # mph-domain scale (the posted/OSM limit, not a param write). + _approx(eco_map_offset_mph(30), 0.0) + _approx(eco_map_offset_mph(49.9), 0.0) + _approx(eco_map_offset_mph(50), 0.0) + _approx(eco_map_offset_mph(65), -4.0) + _approx(eco_map_offset_mph(80), -8.0) + _approx(eco_map_offset_mph(90), -8.0) + _approx(eco_map_offset_mph(None), 0.0) + _approx(eco_map_offset_mph(0), 0.0) + + user_plus_five = 5.0 * CV.MPH_TO_KPH + user_minus_five = -5.0 * CV.MPH_TO_KPH + + cases = ( + (30.0, 30.0), + (50.0, 50.0), + (65.0, 61.0), + (80.0, 72.0), + (90.0, 82.0), + ) + for posted_mph, want_mph in cases: + posted = posted_mph * CV.MPH_TO_KPH + # User slider is ignored while Hypermile is On (Step Down Off). + got = stepped_map_target_kph( + posted, hypermile_on=True, step_down_on=False, map_offset_kph=user_plus_five, + ) + _approx(got, want_mph * CV.MPH_TO_KPH) + got_neg = stepped_map_target_kph( + posted, hypermile_on=True, step_down_on=False, map_offset_kph=user_minus_five, + ) + _approx(got_neg, want_mph * CV.MPH_TO_KPH) + _approx( + map_target_offset_kph( + user_minus_five, hypermile_on=True, step_down_on=False, posted_kph=posted, + ), + eco_map_offset_mph(posted_mph) * CV.MPH_TO_KPH, + ) + + # No posted: do not invent a town drop. + _approx(map_target_offset_kph(user_minus_five, hypermile_on=True, step_down_on=False), 0.0) + # Hypermile Off: user offset still applies (30→25 if they chose −5). + _approx(stepped_map_target_kph( + 30.0 * CV.MPH_TO_KPH, hypermile_on=False, step_down_on=False, map_offset_kph=user_minus_five, + ), 25.0 * CV.MPH_TO_KPH) + # Step Down On: town stays 30; 80→65 (replaces eco, no stack). + _approx(stepped_map_target_kph( + 30.0 * CV.MPH_TO_KPH, hypermile_on=True, step_down_on=True, map_offset_kph=user_plus_five, + ), 30.0 * CV.MPH_TO_KPH) + _approx(stepped_map_target_kph( + 80.0 * CV.MPH_TO_KPH, hypermile_on=True, step_down_on=True, map_offset_kph=0.0, + ), 65.0 * CV.MPH_TO_KPH) + + +def test_hypermile_offsets_maps_only_no_invent_without_posted(): + """Eco / Step Down never invent a drop without maps + a real posted limit.""" + user_minus_five = -5.0 * CV.MPH_TO_KPH + posted_80 = 80.0 * CV.MPH_TO_KPH + + def _approx(a, b): + assert abs(float(a) - float(b)) < 1e-6, (a, b) + + assert maps_posted_known(None) is False + assert maps_posted_known(0.0) is False + assert maps_posted_known(-1.0) is False + assert maps_posted_known(posted_80, maps_posted=False) is False + assert maps_posted_known(posted_80, maps_posted=True) is True + assert maps_posted_known(30.0 * CV.MPH_TO_KPH) is True + + unknown = (None, 0.0, -1.0) + for posted in unknown: + for step in (False, True): + _approx(map_target_offset_kph( + user_minus_five, hypermile_on=True, step_down_on=step, posted_kph=posted, + ), 0.0) + # Maps off / no match: even a leftover 80 mph number must not drop MAX. + _approx(map_target_offset_kph( + user_minus_five, hypermile_on=True, step_down_on=False, + posted_kph=posted_80, maps_posted=False, + ), 0.0) + _approx(map_target_offset_kph( + user_minus_five, hypermile_on=True, step_down_on=True, + posted_kph=posted_80, maps_posted=False, + ), 0.0) + # Maps + known posted: scale applies. + _approx(map_target_offset_kph( + user_minus_five, hypermile_on=True, step_down_on=False, + posted_kph=posted_80, maps_posted=True, + ), -8.0 * CV.MPH_TO_KPH) + _approx(map_target_offset_kph( + user_minus_five, hypermile_on=True, step_down_on=True, + posted_kph=posted_80, maps_posted=True, + ), -15.0 * CV.MPH_TO_KPH) + # Town 30 with maps: still no drop. + _approx(stepped_map_target_kph( + 30.0 * CV.MPH_TO_KPH, hypermile_on=True, step_down_on=False, + ), 30.0 * CV.MPH_TO_KPH) + _approx(stepped_map_target_kph( + 30.0 * CV.MPH_TO_KPH, hypermile_on=True, step_down_on=True, + ), 30.0 * CV.MPH_TO_KPH) + # Hypermile Off: user slider still returned (apply_map_speed ignores it + # when map_kph is None — no invented posted). + _approx(map_target_offset_kph( + user_minus_five, hypermile_on=False, step_down_on=True, posted_kph=None, + maps_posted=False, + ), user_minus_five) + + +def test_effective_follow_is_stock_slider_hypermile_or_not(): + """Hypermile no longer remaps follow — planner uses NAPFollowDistance 1–7.""" + for dist in range(FOLLOW_DISTANCE_MIN, FOLLOW_DISTANCE_MAX + 1): + assert effective_nap_follow_dist(True, dist) == dist + # Invalid / missing slider → personality fallback. + assert effective_nap_follow_dist(True, 0) is None + assert effective_nap_follow_dist(True, 8) is None + assert effective_nap_follow_dist(True, None) is None + assert effective_nap_follow_dist(False, 4) is None + # Closest stock 1 is allowed (old Hypermile floor of 2 is gone). + assert effective_nap_follow_dist(True, 1) == 1 + assert NAP_T_FOLLOW[0] < NAP_T_FOLLOW[1] + + +def test_stalk_with_lead_writes_nap_follow_distance_on_and_off(): + """Stalk + radar lead writes NAPFollowDistance whether Hypermile is On or Off.""" + assert step_follow_distance(4, closer=True) == 3 + assert step_follow_distance(1, closer=True) == 1 + assert step_follow_distance(7, closer=False) == 7 + assert stalk_adjusts_follow(has_lead=True) is True + assert stalk_adjusts_follow(has_lead=False) is False + + for hm_on in (False, True): + params = FakeParams(bools={PARAM_HYPERMILE: hm_on}, ints={PARAM_FOLLOW_DISTANCE: 4}) + assert persist_follow_distance(params, closer=True) == 3 + assert params.get(PARAM_FOLLOW_DISTANCE) == 3 + persist_follow_distance(params, closer=True) + persist_follow_distance(params, closer=True) + persist_follow_distance(params, closer=True) + assert params.get(PARAM_FOLLOW_DISTANCE) == 1 + persist_follow_distance(params, closer=False) + assert params.get(PARAM_FOLLOW_DISTANCE) == 2 + + # 1 kph tip: undo MAX on press; Follow commits on return to IDLE. + tip_prev = 100.0 + tip_cur = tip_prev - 1.0 + g = FollowStalkGesture() + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=False, raw_kph=tip_cur, prev_raw_kph=tip_prev, + detent=CRUISE_STALK_DN_1ST, gesture=g, + ) + assert level is None + assert undo == tip_prev + assert params.get(PARAM_FOLLOW_DISTANCE) == 2 + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=tip_prev, prev_raw_kph=tip_prev, + detent=CRUISE_STALK_IDLE, gesture=g, + ) + assert level == 3 + assert undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == 3 + + # A Follow/posted MAX jump is not a 1/5 mph stalk step. + jump_level, jump_undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=120.0, prev_raw_kph=100.0, + ) + assert jump_level is None and jump_undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == 3 + + +def test_stalk_no_lead_leaves_max_and_does_not_write_follow(): + """No radar lead: tip and hold both stay MAX / RES+/−. Follow Distance is not written.""" + tip_prev = 65.0 * CV.MPH_TO_KPH + tip_cur = tip_prev + 1.0 * CV.MPH_TO_KPH + hold_cur = tip_prev + 5.0 * CV.MPH_TO_KPH + for hm_on in (False, True): + params = FakeParams(bools={PARAM_HYPERMILE: hm_on}, ints={PARAM_FOLLOW_DISTANCE: 4}) + before = params.get(PARAM_FOLLOW_DISTANCE) + none_level, none_undo = consume_follow_stalk( + params, has_lead=False, button_closer=True, raw_kph=tip_cur, prev_raw_kph=tip_prev, + ) + assert none_level is None and none_undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == before + hold_level, hold_undo = consume_follow_stalk( + params, has_lead=False, button_closer=True, raw_kph=hold_cur, prev_raw_kph=tip_prev, + ) + assert hold_level is None and hold_undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == before + is_stalk, closer, undo = detect_follow_stalk( + has_lead=False, button_closer=True, raw_kph=tip_cur, prev_raw_kph=tip_prev, + ) + assert is_stalk is False and closer is None and undo is None + + +def test_lead_tip_remaps_follow_hold_keeps_max(): + """Lead + 1 mph tip → Follow Distance; lead + 5 mph hold → MAX kept.""" + tip_prev = 65.0 * CV.MPH_TO_KPH + tip_cur = tip_prev + 1.0 * CV.MPH_TO_KPH + hold_cur = tip_prev + 5.0 * CV.MPH_TO_KPH + metric_tip = 100.0 + 1.0 + metric_hold = 100.0 + 5.0 + + params = FakeParams(bools={PARAM_HYPERMILE: False}, ints={PARAM_FOLLOW_DISTANCE: 4}) + g = FollowStalkGesture() + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=tip_cur, prev_raw_kph=tip_prev, + detent=CRUISE_STALK_UP_1ST, gesture=g, + ) + assert level is None + assert undo == tip_prev + assert params.get(PARAM_FOLLOW_DISTANCE) == 4 + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=tip_prev, prev_raw_kph=tip_prev, + detent=CRUISE_STALK_IDLE, gesture=g, + ) + assert level == 3 + assert undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == 3 + + # Metric 1 kph tip also remaps (and undoes MAX) after IDLE. + g = FollowStalkGesture() + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=metric_tip, prev_raw_kph=100.0, + detent=CRUISE_STALK_UP_1ST, gesture=g, + ) + assert level is None + assert undo == 100.0 + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=100.0, prev_raw_kph=100.0, + detent=CRUISE_STALK_IDLE, gesture=g, + ) + assert level == 2 + assert params.get(PARAM_FOLLOW_DISTANCE) == 2 + + # 5 mph full press: MAX kept, Follow Distance unchanged. + before = params.get(PARAM_FOLLOW_DISTANCE) + hold_level, hold_undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=hold_cur, prev_raw_kph=tip_prev, + detent=CRUISE_STALK_UP_2ND, + ) + assert hold_level is None and hold_undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == before + + # Metric 5 kph hold, even with a button edge: delta is source of truth. + hold_level, hold_undo = consume_follow_stalk( + params, has_lead=True, button_closer=True, raw_kph=metric_hold, prev_raw_kph=100.0, + ) + assert hold_level is None and hold_undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == before + + is_stalk, closer, undo = detect_follow_stalk( + has_lead=True, button_closer=True, raw_kph=hold_cur, prev_raw_kph=tip_prev, + ) + assert is_stalk is False and closer is None and undo is None + + +def test_lead_tip_then_2nd_detent_keeps_max_and_does_not_remap_follow(): + """Full press walks through first detent; Follow must not change.""" + tip_prev = 65.0 * CV.MPH_TO_KPH + tip_cur = tip_prev + 1.0 * CV.MPH_TO_KPH + hold_cur = tip_prev + 5.0 * CV.MPH_TO_KPH + params = FakeParams(bools={PARAM_HYPERMILE: False}, ints={PARAM_FOLLOW_DISTANCE: 4}) + g = FollowStalkGesture() + + # Frame 1: physical lever hits first detent. Undo the +1 MAX, do not write Follow. + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=True, raw_kph=tip_cur, prev_raw_kph=tip_prev, + detent=CRUISE_STALK_UP_1ST, gesture=g, + ) + assert level is None + assert undo == tip_prev + assert params.get(PARAM_FOLLOW_DISTANCE) == 4 + assert g.is_pending is True + + # Frame 2: 2nd detent / +5. Cancel pending Follow; keep MAX. + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=True, raw_kph=hold_cur, prev_raw_kph=tip_prev, + detent=CRUISE_STALK_UP_2ND, gesture=g, + ) + assert level is None and undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == 4 + assert g.is_pending is False + + # Release to IDLE must not commit the canceled tip. + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=hold_cur, prev_raw_kph=hold_cur, + detent=CRUISE_STALK_IDLE, button_released=True, gesture=g, + ) + assert level is None and undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == 4 + + +def test_button_only_press_is_not_a_completed_tip(): + """Pre-AP buttonEvents collapse tip and 2nd detent — press is not a tip.""" + params = FakeParams(bools={PARAM_HYPERMILE: False}, ints={PARAM_FOLLOW_DISTANCE: 4}) + g = FollowStalkGesture() + is_stalk, closer, undo = detect_follow_stalk( + has_lead=True, button_closer=True, raw_kph=None, prev_raw_kph=None, gesture=g, + ) + assert is_stalk is False and closer is None and undo is None + assert g.is_pending is True + assert params.get(PARAM_FOLLOW_DISTANCE) == 4 + + # Release without 2nd detent / 5 mph: one Follow step. Press+release must not double-step. + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=None, prev_raw_kph=None, + button_released=True, gesture=g, + ) + assert level == 3 + assert undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == 3 + + # A second press while pending (no detent) is treated as 2nd detent. + g = FollowStalkGesture() + consume_follow_stalk( + params, has_lead=True, button_closer=True, raw_kph=None, prev_raw_kph=None, gesture=g, + ) + before = params.get(PARAM_FOLLOW_DISTANCE) + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=True, raw_kph=None, prev_raw_kph=None, gesture=g, + ) + assert level is None and undo is None + assert params.get(PARAM_FOLLOW_DISTANCE) == before + level, undo = consume_follow_stalk( + params, has_lead=True, button_closer=None, raw_kph=None, prev_raw_kph=None, + button_released=True, gesture=g, + ) + assert level is None + assert params.get(PARAM_FOLLOW_DISTANCE) == before + + +def test_follow_hud_announces_every_param_change_after_seed(): + """First read seeds; every later 1–7 change is a Follow Distance toast.""" + prev, announce = poll_follow_distance_hud(None, 4) + assert prev == 4 and announce is False + prev, announce = poll_follow_distance_hud(prev, 3) + assert prev == 3 and announce is True + prev, announce = poll_follow_distance_hud(prev, 3) + assert announce is False + prev, announce = poll_follow_distance_hud(prev, 2) + assert prev == 2 and announce is True + prev, announce = poll_follow_distance_hud(prev, None) + assert prev == 2 and announce is False + prev, announce = poll_follow_distance_hud(None, None) + assert prev is None and announce is False + + +def test_persist_follow_marks_hud_pending_even_at_limit(): + """Tip already at 1 or 7 still requests the Follow Distance HUD.""" + from openpilot.selfdrive.controls.lib.hypermile import ( + PARAM_FOLLOW_DISTANCE, PARAM_FOLLOW_HUD_PENDING, persist_follow_distance, + ) + + class P: + def __init__(self, level): + self.d = {PARAM_FOLLOW_DISTANCE: level, PARAM_FOLLOW_HUD_PENDING: False} + def get(self, key, return_default=True): + return self.d.get(key) + def put(self, key, value): + self.d[key] = value + def put_bool(self, key, value): + self.d[key] = bool(value) + def get_bool(self, key): + return bool(self.d.get(key)) + + p = P(1) + assert persist_follow_distance(p, closer=True) == 1 + assert p.get(PARAM_FOLLOW_DISTANCE) == 1 + assert p.get_bool(PARAM_FOLLOW_HUD_PENDING) is True + p = P(7) + assert persist_follow_distance(p, closer=False) == 7 + assert p.get_bool(PARAM_FOLLOW_HUD_PENDING) is True + + +def test_button_events_and_hud_text(): + up = SimpleNamespace(type=SimpleNamespace(name="accelCruise"), pressed=True) + down = SimpleNamespace(type=SimpleNamespace(name="decelCruise"), pressed=True) + release = SimpleNamespace(type=SimpleNamespace(name="accelCruise"), pressed=False) + assert button_event_closer([up]) is True + assert button_event_closer([down]) is False + assert button_event_closer([release]) is None + assert button_event_released([release]) is True + assert button_event_released([up]) is False + assert follow_distance_hud_text(3) == "Follow Distance: 3" + assert follow_distance_hud_text(1) == "Follow Distance: 1" + is_stalk, closer, undo = detect_follow_stalk( + has_lead=True, button_closer=True, raw_kph=None, prev_raw_kph=None, + ) + assert is_stalk is False and closer is None and undo is None + + +def test_settings_and_docs_wire_hypermile(): + from pathlib import Path + root = Path(__file__).resolve().parents[3] + tici = (root / "selfdrive/ui/layouts/settings/driving_mannerisms.py").read_text() + mici = (root / "selfdrive/ui/mici/layouts/settings/driving_mannerisms.py").read_text() + nap = (root / "selfdrive/ui/layouts/settings/nap.py").read_text() + content = (root / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + keys = (root / "common/params_keys.h").read_text() + planner = (root / "selfdrive/controls/lib/longitudinal_planner.py").read_text() + card = (root / "selfdrive/car/card.py").read_text() + events = (root / "selfdrive/selfdrived/events.py").read_text() + selfdrived = (root / "selfdrive/selfdrived/selfdrived.py").read_text() + docs = (root / "docs-nap/hypermile.md").read_text() + readme = (root / "docs-nap/README.md").read_text() + releases = (root / "RELEASES.md").read_text() + + for src in (tici, mici): + assert "Hypermile" in src or "hypermile" in src + assert "NAP_HYPERMILE" in src + assert "NAP_HYPERMILE_STEP_DOWN" in src + assert "NAP_HYPERMILE_HILL_CLIMB" in src + assert "apply_hypermile_toggle" in src + assert "Hypermile" in nap + assert "put_bool(NAP_HYPERMILE, False)" in nap + assert "put_bool(NAP_HYPERMILE_STEP_DOWN, False)" in nap + assert "put_bool(NAP_HYPERMILE_HILL_CLIMB, True)" in nap + assert "Step Down Speed" in tici + assert "Hill Climb" in tici + assert "step down speed" in mici + assert "hill climb" in mici + assert "map_target_offset_kph" in card + assert "_live_map_offset_kph" in card + assert "maps_posted" in card + assert "never invent" in card + assert "_refresh_map_speed_params" in card + hm_src = (root / "selfdrive/controls/lib/hypermile.py").read_text() + assert "eco_map_offset_mph" in hm_src + assert "maps_posted_known" in hm_src + assert "ECO_OFFSET_START_MPH" in hm_src + assert '"NAPMapSpeedOffsetMph": ECO_MAP_OFFSET_MPH' not in hm_src + assert "NAPHypermile" in keys + assert "NAPOnePedalLong" in keys + assert 'BOOL, "0"' in next(ln for ln in keys.splitlines() if '"NAPOnePedalLong"' in ln) + assert "NAPHypermileFollowLevel" not in keys + assert "NAPHypermileFollowLevel" not in tici + assert "NAPHypermileFollowLevel" not in mici + assert "NAPHypermileFollowLevel" not in nap + assert "NAPHypermileFollowLevel" not in content + assert "Hypermile Follow" not in tici + assert "hypermile follow" not in mici + assert "set_visible(not hypermile_on)" not in tici + assert "FOLLOW_DISTANCE" in tici + assert "FOLLOW_DISTANCE" in mici + assert "NAPMapSpeedAccel" in tici + assert "NAPMapSpeedAccel" in mici + assert "Acceleration" in tici + assert '"acceleration"' in mici + assert "NAPHypermileStepDown" in keys + assert "NAPHypermileHillClimb" in keys + assert 'BOOL, "0"' in next(ln for ln in keys.splitlines() if '"NAPHypermileStepDown"' in ln) + assert 'BOOL, "1"' in next(ln for ln in keys.splitlines() if '"NAPHypermileHillClimb"' in ln) + assert 'BOOL, "0"' in next(ln for ln in keys.splitlines() if '"NAPHypermile"' in ln) + assert "NAPFollowDistance" in keys + assert 'INT, "4"' in next(ln for ln in keys.splitlines() if '"NAPFollowDistance"' in ln) + assert "effective_nap_follow_dist" in planner + assert "Stalk Follow Distance 1–7 must land on the next plan" in planner + assert "FollowStalkGesture" in card + assert "_preap_cruise_detent" in card + assert "persist_follow_distance" in card + assert "v_cruise=v_cruise_ms" in card + assert "published_cruise_ms(self.v_cruise_helper.v_cruise_kph" in card + assert 'getattr(CS, "vCruise"' not in card + assert "has_lead=has_lead" in card + assert "radarState" in card + assert "hypermileFollowChanged" in events + assert "follow_distance_hud_text" in events + assert "poll_follow_distance_hud" in selfdrived + assert "NAPFollowDistance" in selfdrived + assert "NAPFollowHudPending" in selfdrived + assert "_follow_hud_until" in selfdrived + assert "NAPFollowHudPending" in keys + assert "ET.PERMANENT: hypermile_follow_changed_alert" in events + assert "NAPHypermile" in content + assert "comfort-biased" in content.lower() + assert "not max" in content.lower() + assert "stock slider" in content.lower() + assert "hypermile.md" in readme + assert "Hypermile" in docs + assert "NAPHypermileFollowLevel" not in docs + assert "Follow Distance: N" in docs + assert "NAPFollowDistance" in docs + assert "1 mph" in docs and "5 mph" in docs + assert "full press" in docs.lower() or "full press" in releases.lower() + assert "Step Down Speed" in docs + assert "Hill Climb" in docs + assert "15 mph under" in docs or "−15 at 80" in docs + assert "step_down_offset_mph" in hm_src + assert "early, light regenerative" in docs.lower() or "early, light" in docs.lower() + assert "not maximum regen" in docs.lower() or "not max regen" in docs.lower() + assert "posted-scaled" in docs.lower() or "scaled" in docs.lower() + assert "30 stays 30" in docs or "town 30" in docs.lower() + assert "−8" in docs + assert "maps" in docs.lower() and ("unknown" in docs.lower() or "invent" in docs.lower()) + # "NAP Hypermile Hill Climb" must not steal the scaled-eco RELEASES block. + hm_rel = next(p for p in releases.split("\n\n") if p.startswith("NAP Hypermile (")) + assert "Hypermile" in hm_rel + assert "Early" in hm_rel + assert "30" in hm_rel and "25" in hm_rel + assert "−8" in hm_rel + assert "−15" in hm_rel + assert "Maps-only" in hm_rel or "invent" in hm_rel.lower() + assert "nap-release" not in docs.lower() or "not a nap-release" in docs.lower() diff --git a/selfdrive/controls/tests/test_latcontrol.py b/selfdrive/controls/tests/test_latcontrol.py new file mode 100644 index 00000000000000..284be8c1be1e70 --- /dev/null +++ b/selfdrive/controls/tests/test_latcontrol.py @@ -0,0 +1,55 @@ +from openpilot.common.parameterized import parameterized + +from cereal import car, log +from opendbc.car.car_helpers import interfaces +from opendbc.car.honda.values import CAR as HONDA +from opendbc.car.toyota.values import CAR as TOYOTA +from opendbc.car.nissan.values import CAR as NISSAN +from opendbc.car.gm.values import CAR as GM +from opendbc.car.vehicle_model import VehicleModel +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID +from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque +from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle + + +class TestLatControl: + + @parameterized.expand([(HONDA.HONDA_CIVIC, LatControlPID), (TOYOTA.TOYOTA_RAV4, LatControlTorque), + (NISSAN.NISSAN_LEAF, LatControlAngle), (GM.CHEVROLET_BOLT_EUV, LatControlTorque)]) + def test_saturation(self, car_name, controller): + CarInterface = interfaces[car_name] + CP = CarInterface.get_non_essential_params(car_name) + CI = CarInterface(CP) + VM = VehicleModel(CP) + + controller = controller(CP.as_reader(), CI, DT_CTRL) + + CS = car.CarState.new_message() + CS.vEgo = 30 + CS.steeringPressed = False + + params = log.LiveParametersData.new_message() + + # Saturate for curvature limited and controller limited + for _ in range(1000): + _, _, lac_log = controller.update(True, CS, VM, params, False, 0, True, 0.2) + assert lac_log.saturated + + for _ in range(1000): + _, _, lac_log = controller.update(True, CS, VM, params, False, 0, False, 0.2) + assert not lac_log.saturated + + for _ in range(1000): + _, _, lac_log = controller.update(True, CS, VM, params, False, 1, False, 0.2) + assert lac_log.saturated + + # Blinker pause sets latActive false. Inactive must release the request + # so the driver can turn without fighting the last command. + CS.steeringAngleDeg = 18.0 + steer, steering_angle_deg, inactive_log = controller.update(False, CS, VM, params, False, 1, False, 0.2) + assert inactive_log.active is False + if isinstance(controller, LatControlTorque): + assert steer == 0.0 + if isinstance(controller, LatControlAngle): + assert steering_angle_deg == 18.0 diff --git a/selfdrive/controls/tests/test_latcontrol_torque_buffer.py b/selfdrive/controls/tests/test_latcontrol_torque_buffer.py new file mode 100644 index 00000000000000..ab1d2c7b36ca47 --- /dev/null +++ b/selfdrive/controls/tests/test_latcontrol_torque_buffer.py @@ -0,0 +1,36 @@ +from openpilot.common.parameterized import parameterized + +from cereal import car, log +from opendbc.car.car_helpers import interfaces +from opendbc.car.toyota.values import CAR as TOYOTA +from opendbc.car.vehicle_model import VehicleModel +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque, LAT_ACCEL_REQUEST_BUFFER_SECONDS + +def get_controller(car_name): + CarInterface = interfaces[car_name] + CP = CarInterface.get_non_essential_params(car_name) + CI = CarInterface(CP) + VM = VehicleModel(CP) + controller = LatControlTorque(CP.as_reader(), CI, DT_CTRL) + return controller, VM + +class TestLatControlTorqueBuffer: + + @parameterized.expand([(TOYOTA.TOYOTA_COROLLA_TSS2,)]) + def test_request_buffer_consistency(self, car_name): + buffer_steps = int(LAT_ACCEL_REQUEST_BUFFER_SECONDS / DT_CTRL) + controller, VM = get_controller(car_name) + + CS = car.CarState.new_message() + CS.vEgo = 30 + CS.steeringPressed = False + params = log.LiveParametersData.new_message() + + for _ in range(buffer_steps): + controller.update(True, CS, VM, params, False, 0.001, False, 0.2) + assert all(val != 0 for val in controller.lat_accel_request_buffer) + + for _ in range(buffer_steps): + controller.update(False, CS, VM, params, False, 0.0, False, 0.2) + assert all(val == 0 for val in controller.lat_accel_request_buffer) diff --git a/selfdrive/controls/tests/test_lead_approach.py b/selfdrive/controls/tests/test_lead_approach.py new file mode 100644 index 00000000000000..0485007c0e0ee2 --- /dev/null +++ b/selfdrive/controls/tests/test_lead_approach.py @@ -0,0 +1,298 @@ +import pytest +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_APPROACH_MILD_A_MS2, + LEAD_CLOSE_HOLD_S, + LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2, + NAP_T_FOLLOW, + STOP_DISTANCE, + LeadResidualWindow, + lead_approach_track_ok, + guard_follow_actuator_regen, + plant_regen_effort_limits, + lead_close_should_cap, + lead_follow_slack_m, + nap_t_follow, + resolve_lead_close_hold, + +) +from openpilot.selfdrive.mapd.constants import ( + LOOKAHEAD_EARLY, +) + + +def test_nap_t_follow_matches_follow_distance_slider(): + assert nap_t_follow(4) == 1.3 + assert nap_t_follow(1) == 0.7 + assert nap_t_follow(7) == 1.9 + assert nap_t_follow(None) is None + assert nap_t_follow(0) is None + assert list(NAP_T_FOLLOW) == [0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9] + + +def test_t_follow_table_stays_in_sync_with_mpc(): + from pathlib import Path + mpc = (Path(__file__).resolve().parents[1] / "lib/longitudinal_mpc_lib/long_mpc.py").read_text() + assert "NAP_T_FOLLOW = (0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9)" in mpc + assert "STOP_DISTANCE = 6.0" in mpc + + +def test_map_climb_still_does_not_replace_mpc_when_lead_present(): + """#118: valid lead → no map a_up replace. Soft overlay must not reopen that.""" + from openpilot.selfdrive.mapd.constants import map_accel_a_ms2 + from openpilot.selfdrive.mapd.map_speed_policy import map_climb_replaces_mpc, map_track_accel_ms2 + + a_up = map_track_accel_ms2(21.5, 24.6, map_accel_a_ms2(LOOKAHEAD_EARLY, 1)) + assert a_up is not None and a_up > 0.05 + assert map_climb_replaces_mpc(a_up, 0.05, has_valid_lead=True) is False + assert map_climb_replaces_mpc(a_up, 0.0, has_valid_lead=True) is False + assert map_climb_replaces_mpc(a_up, 0.05, has_valid_lead=False) is True + assert map_climb_replaces_mpc(a_up, -0.4, has_valid_lead=False) is False + + +def test_lead_close_hold_covers_status_flicker_and_far_bosch(): + d_use, v_use, held_d, held_v, age = resolve_lead_close_hold( + True, 80.0, 22.0, None, None, 0.0, 0.05, + ) + assert d_use == pytest.approx(80.0) + assert v_use == pytest.approx(22.0) + for _ in range(8): + d_use, v_use, held_d, held_v, age = resolve_lead_close_hold( + False, 0.0, 0.0, held_d, held_v, age, 0.05, + ) + assert d_use == pytest.approx(80.0) + assert age < LEAD_CLOSE_HOLD_S + d_use, v_use, held_d, held_v, age = resolve_lead_close_hold( + False, 0.0, 0.0, 80.0, 22.0, LEAD_CLOSE_HOLD_S, 0.05, + ) + assert d_use is None + assert held_d is None + d_use, v_use, held_d, held_v, age = resolve_lead_close_hold( + True, 160.0, 22.0, 80.0, 22.0, 0.10, 0.05, model_prob=1.0, radar=True, + ) + assert d_use == pytest.approx(160.0) + assert lead_close_should_cap(160.0, model_prob=1.0, radar=True) + d_use, v_use, held_d, held_v, age = resolve_lead_close_hold( + True, 160.0, 22.0, None, None, 0.0, 0.05, model_prob=0.2, radar=False, + ) + assert d_use is None + assert not lead_close_should_cap(160.0, model_prob=0.2, radar=False) + d_use, v_use, held_d, held_v, age = resolve_lead_close_hold( + True, 160.0, 22.0, None, None, 0.0, 0.05, model_prob=0.2, radar=True, + ) + assert d_use == pytest.approx(160.0) + assert lead_close_should_cap(160.0, model_prob=0.2, radar=True) + d_use, v_use, held_d, held_v, age = resolve_lead_close_hold( + True, 220.0, 22.0, 80.0, 22.0, 0.10, 0.05, model_prob=1.0, radar=True, + ) + assert d_use is None + assert not lead_close_should_cap(220.0, model_prob=1.0, radar=True) + + +def test_guard_follow_actuator_regen_when_planner_near_zero(): + """ef 10:18:42: aTarget ≈ 0 must not dump plant regen to −1.2. + + A steady command also must not open the mild settle. That settle is + for a command that is already there. + """ + # Planner coasting: clip firm regen to the command, not to −0.22. + assert guard_follow_actuator_regen(-1.23, 0.0) == pytest.approx(0.0) + assert guard_follow_actuator_regen(-1.50, 0.02) == pytest.approx(0.0) + assert guard_follow_actuator_regen(-0.10, 0.0) == pytest.approx(0.0) + assert guard_follow_actuator_regen(0.0, 0.0) == pytest.approx(0.0) + # Planner asked for firm / rapid / FCW −a: full authority. + assert guard_follow_actuator_regen(-1.23, -0.50) == pytest.approx(-1.23) + assert guard_follow_actuator_regen(-2.0, -2.0) == pytest.approx(-2.0) + assert guard_follow_actuator_regen(-1.50, -0.80) == pytest.approx(-1.50) + # Commanded MILD is inside the steady band: plant cannot full-lift. + assert guard_follow_actuator_regen(-0.22, -0.22) == pytest.approx(-0.22) + assert guard_follow_actuator_regen(-0.40, -0.22) == pytest.approx( + LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2 + ) + assert guard_follow_actuator_regen(-1.32, -0.218) == pytest.approx( + LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2 + ) + # LongControl only applies this on Pre-AP PID, not stopping. + from pathlib import Path + longcontrol = (Path(__file__).resolve().parents[1] / "lib/longcontrol.py").read_text() + assert "guard_follow_actuator_regen(" in longcontrol + assert "LongCtrlState.pid" in longcontrol + assert "TESLA_MODEL_S_PREAP" in longcontrol + + +def test_card_does_not_subscribe_to_controlsstate_for_curve(): + """Curve MAX curvature comes from carControl, not a 100 Hz controlsState poll.""" + from pathlib import Path + card = (Path(__file__).resolve().parents[3] / "selfdrive/car/card.py").read_text() + sm = card.split("messaging.SubMaster([", 1)[1].split("])", 1)[0] + assert "controlsState" not in sm + assert "currentCurvature" in card + + +def test_descent_plant_effort_keeps_grade_flat_and_uphill_do_not(): + """A descent −0.22 effort includes the grade term. Flat and uphill do not move.""" + import math + + from opendbc.car.tesla.preap.virtual_das import GRAVITY, VirtualDAS + + from openpilot.selfdrive.controls.lib.lead_approach import ( + install_preap_plant_regen_guard, + ) + + grade = -0.42 + down = plant_regen_effort_limits( + -0.22, (-1.5, 2.0), steady_grade=grade, transient=0.0, descent=True, + ) + flat = plant_regen_effort_limits( + -0.22, (-1.5, 2.0), steady_grade=0.0, transient=0.0, descent=False, + ) + up = plant_regen_effort_limits( + -0.22, (-1.5, 2.0), steady_grade=0.27, transient=0.0, descent=False, + ) + assert down[0] == pytest.approx(-0.22 + grade) + assert flat[0] == pytest.approx(-0.22) + assert up[0] == pytest.approx(-0.22) + assert up[0] == flat[0] + + def raw_update(): + update = VirtualDAS.update + while getattr(update, "_nap_plant_regen_guard", False): + update = update._nap_plant_regen_raw + return update + + before = raw_update() + install_preap_plant_regen_guard() + try: + def settle(update, pitch, a_ego, a_cmd=-0.22, limits=None): + vdas = VirtualDAS(dt=0.02) + ori = [0.0, pitch, 0.0] + for _ in range(400): + vdas.observe(a_ego=0.0, orientation_ned=ori) + vdas.reset( + measured_accel=a_ego, commanded_accel=a_cmd, pedal_di_init=8.0, + preserve_grade=True, + ) + pedal = 8.0 + for _ in range(80): + pedal = update( + vdas, a_cmd, 30.0, pedal, a_ego=a_ego, orientation_ned=ori, + accel_effort_limits=limits, + ) + return vdas.prev_accel_effort, vdas.grade_estimator._steady_grade_compensation() + + guarded = VirtualDAS.update + raw = raw_update() + # Previous floor: mild command, no descent allowance. Flat and uphill + # must still land on that effort. aEgo tracks, so the shortfall gate + # stays shut. + old_limits = plant_regen_effort_limits(-0.22, (-1.5, 2.0), descent=False) + flat_g, _flat_grade = settle(guarded, 0.02, -0.22) + flat_old, _ = settle(raw, 0.02, -0.22, limits=old_limits) + assert flat_g == pytest.approx(flat_old, abs=0.02) + + up_pitch = 0.02 + math.asin(0.27 / GRAVITY) + up_g, up_grade = settle(guarded, up_pitch, -0.22) + up_old, _ = settle(raw, up_pitch, -0.22, limits=old_limits) + assert up_g == pytest.approx(up_old, abs=0.02) + assert up_grade > 0.2 + + down_pitch = math.asin(grade / GRAVITY) + down_g, down_grade = settle(guarded, down_pitch, 0.05) + down_old, _ = settle(raw, down_pitch, 0.05, limits=old_limits) + assert down_grade < -0.3 + assert down_old == pytest.approx(-0.22, abs=0.05) + assert down_g <= -0.22 + down_grade + 0.05 + assert down_g < down_old - 0.15 + finally: + VirtualDAS.update = before + + + +def test_lead_close_should_cap_and_track_gate(): + assert lead_close_should_cap(80.0) + assert lead_close_should_cap(160.0, model_prob=1.0, radar=True) + assert lead_close_should_cap(160.0, model_prob=0.2, radar=True) + assert not lead_close_should_cap(160.0, model_prob=0.2, radar=False) + assert not lead_close_should_cap(0.0) + assert not lead_close_should_cap(None) + d_far = 180.0 + assert lead_approach_track_ok(80.0, model_prob=0.0, radar=False) is True + assert lead_approach_track_ok(d_far, model_prob=0.2, radar=True) is True + assert lead_approach_track_ok(d_far, model_prob=1.0, radar=False) is False + assert lead_approach_track_ok(d_far, model_prob=1.0, radar=True) is True + assert lead_approach_track_ok(d_far) is True + + +def test_lead_follow_slack_is_gap_minus_follow_distance(): + t4 = nap_t_follow(4) + v_lead = 22.0 + d_follow = t4 * v_lead + STOP_DISTANCE + assert lead_follow_slack_m(d_follow + 40.0, v_lead, t4) == pytest.approx(40.0) + assert lead_follow_slack_m(d_follow + 5.0, v_lead, t4) == pytest.approx(5.0) + + +def test_steady_plant_does_not_leak_into_mild_without_a_dwell(): + """23:16 / 23:22: a steady command must not settle at −0.22. + + The mild settle still applies once the command has dwelled there, and a + brief return to coast does not drop it. A firm brake is not mild. + """ + from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_FOLLOW_STEADY_ONLY_MS2, + PlantDecelClassifier, + plant_follow_floor, + plant_regen_effort_limits, + ) + + clf = PlantDecelClassifier() + for _ in range(30): + mode = clf.update(0.0, 0.02) + assert mode == "steady" + assert plant_regen_effort_limits(0.0, (-1.5, 2.0), decel_mode=mode)[0] == pytest.approx(0.0) + for _ in range(10): + mode = clf.update(-0.22, 0.02) + assert mode == "steady" + assert plant_follow_floor(-0.22, mode) == pytest.approx(-LEAD_FOLLOW_STEADY_ONLY_MS2) + for _ in range(20): + mode = clf.update(-0.22, 0.02) + assert mode == "mild" + assert plant_follow_floor(-0.22, mode) == pytest.approx(-LEAD_APPROACH_MILD_A_MS2) + held = plant_regen_effort_limits(-0.22, (-1.5, 2.0), decel_mode=mode) + assert held[0] == pytest.approx(-0.22) + for _ in range(10): + mode = clf.update(0.0, 0.02) + assert mode == "mild" + assert plant_follow_floor(0.0, mode) == pytest.approx(-0.22) + for _ in range(25): + mode = clf.update(0.01, 0.02) + assert mode == "steady" + + firm = PlantDecelClassifier() + for _ in range(40): + mode = firm.update(-1.4, 0.02) + assert mode == "steady" + # A sustained mild sample, with no classifier, is still the settle. + assert plant_regen_effort_limits(-0.22, (-1.5, 2.0))[0] == pytest.approx(-0.22) + assert plant_regen_effort_limits(0.008, (-1.5, 2.0))[0] == pytest.approx(0.0) + + +def test_residual_window_ignores_one_radar_lsb_and_arms_on_sustained_close(): + """One vRel quantum over a 0.05 s frame must not arm; a sustained 07:55-shaped close must.""" + lsb = 1.0 / 16.0 + window = LeadResidualWindow() + v = 1.20 + armed_prev = None + for _ in range(40): + prev, _dt, _a = window.update(v, -0.22, 0.05) + if prev is not None: + armed_prev = prev + v = 1.20 + lsb + assert armed_prev is None + + window = LeadResidualWindow() + prev = None + dt_w = 0.05 + v0 = 1.40 + for i in range(14): + prev, dt_w, _a_w = window.update(v0 + 0.04 * i, -0.22, 0.05) + assert prev is not None + assert dt_w == pytest.approx(0.50, abs=0.02) diff --git a/selfdrive/controls/tests/test_lead_leaving.py b/selfdrive/controls/tests/test_lead_leaving.py new file mode 100644 index 00000000000000..5c7e497f377744 --- /dev/null +++ b/selfdrive/controls/tests/test_lead_leaving.py @@ -0,0 +1,268 @@ +"""Lead leaving our path: continuous weight on its braking. + +Turning lead with clearance at our arrival is released before radard drops +it. A lead that stalls half-out, or drifts inside its own lane, keeps full +weight. The weight is continuous (no jump) and never lifts the command +above the lead-free one (MAX, map, curve). +""" +import math + +import numpy as np +import pytest + +from openpilot.selfdrive.controls.lib.lead_leaving import ( + EGO_HALF_WIDTH_M, + LeadLeavingEstimator, + clearance_needed_m, + leave_weight, + time_to_arrive_s, +) +from openpilot.selfdrive.controls.lib.unified_lead import ( + UnifiedLeadController, + unified_follow_desired, +) +from openpilot.selfdrive.controls.tests.test_unified_lead_planner import ( + _own_lead, + _planner, +) + +DT = 0.05 + + +def _drive(est, ys, *, gap0=30.0, v_ego=16.0, v_lead=11.0, a_lead=-1.5, track=7, probs=None): + """Feed one lead track; gap closes at v_ego - v_lead. Returns weights.""" + out = [] + gap = gap0 + for i, y in enumerate(ys): + p = 1.0 if probs is None else probs[i] + out.append(est.update(dt=DT, present=True, lead_id=track, path_lat=float(y), gap=gap, + v_ego=v_ego, v_lead=v_lead, a_lead=a_lead, model_prob=p)) + gap = max(2.0, gap - (v_ego - v_lead) * DT) + return np.array(out) + + +def _turn_off_ys(v_out=1.2, y0=0.2, y_end=2.0, pre_s=2.0): + """On-path, then moving out at v_out until radard's ~2 m gate.""" + ys = [y0] * int(pre_s / DT) + y = y0 + while y < y_end: + y += v_out * DT + ys.append(y) + return np.array(ys) + + +def test_turning_lead_released_early_with_clearance(): + est = LeadLeavingEstimator() + ys = _turn_off_ys() + w = _drive(est, ys, gap0=40.0, probs=np.linspace(1.0, 0.2, len(ys))) + # Not before its center is past our half of the lane. + assert np.all(w[ys < 0.9] == 0.0) + # Mostly released before radard would drop it at ~2 m (its body still + # overlapping ours: the projection at our arrival is what clears). + assert w[ys < 1.9].max() >= 0.7 + first = int(np.argmax(w > 0.5)) + assert ys[first] < 1.8 + # The planner's unified command: the lead brake (-3.4) is released at a bounded jerk. + planner, inputs, _ = _planner(16.0, accel=-2.5) + lead = _own_lead(inputs, 40.0, 11.0, a_lead=-1.5, y_rel=0.0, track=7) + a_out = [] + gap = 40.0 + for y in ys: + lead.yRel = -float(y) # no model path -> path offset is -yRel + lead.dRel = gap + planner.update(inputs) + a_out.append(float(planner.output_a_target)) + gap -= 5.0 * DT + a_out = np.array(a_out) + pre = int(2.0 / DT) + assert a_out[pre - 10:pre].max() <= -2.4 + moving = ys > 1.0 + # Before radard's gate the unified controller has begun releasing (jerk-bounded). + assert a_out[moving & (ys < 1.9)].max() >= -2.7 + # Released >= 0.8 m/s^2 from the on-path brake by the time radard would drop it. + assert a_out[-1] >= a_out[pre - 1] + 0.8 + assert planner.lead_leave_w > 0.6 + + +def test_stalled_half_out_lead_keeps_braking(): + est = LeadLeavingEstimator() + ys = list(_turn_off_ys(y_end=1.5)) + ys += [ys[-1]] * int(1.5 / DT) # stops moving out, half in our lane + ys = np.array(ys) + w = _drive(est, ys, probs=np.linspace(1.0, 0.5, len(ys))) + moving_peak = w[: len(ys) - int(1.5 / DT)].max() + assert moving_peak > 0.0 + # Within ~0.5 s of the stall the weight is back to 0: full braking. + assert np.all(w[-int(1.0 / DT):] == 0.0) + # Static half-out never clears on its own geometry either. + for y in (1.0, 1.4, 1.8, 2.0): + assert leave_weight(y, 0.0, 30.0, 16.0, 0.0, 11.0, -1.5) == 0.0 + + # Planner: after the stall, the legacy command is the unreleased brake. + planner, inputs, _ = _planner(16.0, accel=-2.5) + lead = _own_lead(inputs, 30.0, 11.0, a_lead=-1.5, track=7) + for y in ys: + lead.yRel = -float(y) + planner.update(inputs) + assert planner.lead_leave_w == 0.0 + assert float(planner.output_a_target) <= -2.4 + + +def test_lead_drifting_within_lane_not_released(): + est = LeadLeavingEstimator() + # Swerving to its lane line and back at 1.5 m/s, both sides, while the + # in-path confidence dips: projects well past our width, but the lead's + # center never leaves its lane, so nothing is released. + leg = list(np.arange(0.0, 0.85, 1.5 * DT)) + [0.85] * 6 + one = leg + leg[::-1] + ys = np.array(one * 2 + [-y for y in one] * 2) + probs = 1.0 - 0.5 * np.abs(ys) / 0.85 + w = _drive(est, ys, gap0=25.0, v_lead=15.0, probs=probs) + assert np.all(w == 0.0) + # Even a hard in-lane swerve whose projection clears us is not released + # while its center is still in our half of the lane. + for y in (0.0, 0.4, 0.7, 0.9): + assert leave_weight(y, 2.2, 40.0, 16.0, -0.6, 11.0, -1.0) == 0.0 + assert leave_weight(1.4, 2.2, 40.0, 16.0, -0.6, 11.0, -1.0) > 0.9 + planner, inputs, _ = _planner(16.0, accel=-1.8) + lead = _own_lead(inputs, 25.0, 15.0, a_lead=-1.0, track=3) + for y in ys: + lead.yRel = -float(y) + planner.update(inputs) + assert planner.lead_leave_w == 0.0 + + +def test_leave_weight_no_jump_sweep(): + """Continuous in every input: small input steps give small weight steps.""" + ys = np.arange(0.0, 3.0, 0.01) + for v_ego in (5.0, 12.0, 20.0, 30.0): + for vy in (0.0, 0.3, 0.8, 1.5, 2.5): + for gap in (8.0, 20.0, 45.0): + w = np.array([leave_weight(y, vy, gap, v_ego, -0.3, v_ego - 4.0, -1.0) for y in ys]) + assert np.all((w >= 0.0) & (w <= 1.0)) + assert np.max(np.abs(np.diff(w))) < 0.06 + vys = np.arange(-1.0, 3.0, 0.01) + for y in (1.0, 1.3, 1.7, 2.0): + w = np.array([leave_weight(y, vy, 25.0, 16.0, 0.0, 11.0, -1.5) for vy in vys]) + assert np.max(np.abs(np.diff(w))) < 0.06 + assert np.all(np.diff(w) >= -1e-12) # moving out faster never adds weight back + gaps = np.arange(2.0, 80.0, 0.1) + w = np.array([leave_weight(1.5, 1.0, g, 16.0, 0.0, 11.0, -1.5) for g in gaps]) + assert np.max(np.abs(np.diff(w))) < 0.06 + # Arrival time is continuous across a_lead = 0 and the lead-stops switch. + a_leads = np.arange(-4.0, 1.0, 0.01) + t = np.array([time_to_arrive_s(30.0, 16.0, 11.0, a) for a in a_leads]) + assert np.max(np.abs(np.diff(t))) < 0.05 + + +def test_clearance_bound_is_ego_half_width_plus_lead_plus_margin(): + need = clearance_needed_m(16.0) + assert need > EGO_HALF_WIDTH_M + 0.9 + 0.29 + # Projection short of clearance: nothing. Clears: released. + assert leave_weight(1.6, 0.4, 20.0, 16.0, 0.0, 11.0, -1.5) == 0.0 + assert leave_weight(1.6, 1.5, 30.0, 16.0, -0.6, 11.0, -1.0) > 0.9 + # A lead braking to a stop mid-turn stops moving out when it stops. + assert leave_weight(1.6, 1.0, 30.0, 16.0, 0.0, 1.0, -3.0) == 0.0 + + +def test_fcw_lead_two_and_new_track_restore_full_weight(): + est = LeadLeavingEstimator() + ys = _turn_off_ys() + w = _drive(est, ys) + assert w[-1] > 0.6 + assert est.update(dt=DT, present=True, lead_id=7, path_lat=2.0, gap=20.0, v_ego=16.0, + v_lead=11.0, suppress=True) == 0.0 + est2 = LeadLeavingEstimator() + _drive(est2, ys) + # Another car on our path behind the one turning off: keep braking. + w2 = est2.update(dt=DT, present=True, lead_id=7, path_lat=2.0, gap=20.0, v_ego=16.0, + v_lead=11.0, a_lead=-1.5, lead_two_path_lat=0.3) + assert w2 == pytest.approx(max(0.0, w[-1] - 8.0 * DT), abs=1e-6) or w2 < w[-1] + for _ in range(5): + w2 = est2.update(dt=DT, present=True, lead_id=7, path_lat=2.0, gap=20.0, v_ego=16.0, + v_lead=11.0, a_lead=-1.5, lead_two_path_lat=0.3) + assert w2 == 0.0 + # New track id starts from full weight. + est3 = LeadLeavingEstimator() + _drive(est3, ys) + assert est3.update(dt=DT, present=True, lead_id=8, path_lat=1.9, gap=20.0, v_ego=16.0, + v_lead=11.0) == 0.0 + + +def test_hold_after_radard_drop_keeps_releasing_only_a_moving_lead(): + est = LeadLeavingEstimator() + _drive(est, _turn_off_ys()) + w_moving = [est.update(dt=DT, present=True, held=True, v_ego=16.0) for _ in range(10)] + assert min(w_moving) > 0.6 + est = LeadLeavingEstimator() + ys = list(_turn_off_ys(y_end=1.5)) + [1.5] * 30 + _drive(est, ys) + w_stalled = [est.update(dt=DT, present=True, held=True, v_ego=16.0) for _ in range(10)] + assert max(w_stalled) == 0.0 + + +def test_unified_leave_weight_releases_brake_but_keeps_max_ceiling(): + # Braking lead, on path: firm. Fully leaving: toward 0, never above the + # MAX speed-error decel (EV mild settle stays -0.22 over MAX). + base = unified_follow_desired(22.0, 16.0, 11.0, -1.5, 1.3, v_ceiling=30.0, path_lat=1.5) + assert base < -1.0 + assert unified_follow_desired(22.0, 16.0, 11.0, -1.5, 1.3, v_ceiling=30.0, path_lat=1.5, leave_w=0.0) == base + half = unified_follow_desired(22.0, 16.0, 11.0, -1.5, 1.3, v_ceiling=30.0, path_lat=1.5, leave_w=0.5) + full = unified_follow_desired(22.0, 16.0, 11.0, -1.5, 1.3, v_ceiling=30.0, path_lat=1.5, leave_w=1.0) + assert base < half < full + assert full == pytest.approx(0.0, abs=1e-9) + over = unified_follow_desired(22.0, 16.0, 11.0, -1.5, 1.3, v_ceiling=15.0, path_lat=1.5, leave_w=1.0) + assert -0.3 < over < 0.0 + # Stalled half-out lead (static 1.5 m) keeps the full command in unified too. + on_path = unified_follow_desired(22.0, 16.0, 11.0, -1.5, 1.3, v_ceiling=30.0, path_lat=0.0) + assert base == pytest.approx(on_path, abs=1e-9) + + ctrl = UnifiedLeadController() + a = 0.0 + for i in range(90): + w = 0.0 if i < 30 else min(1.0, (i - 30) * 0.075) + a = ctrl.step(dt=DT, present=True, gap=22.0, v_ego=16.0, v_lead=11.0, a_lead=-1.5, t_follow=1.3, + lead_id=1, seed_a=a, v_ceiling=30.0, path_lat=1.5, leave_w=w) + if i == 29: + firm = a + assert firm < -1.0 + # Released toward the lead-free command, not held by a confidence drop. + assert a > -0.3 + + +def test_planner_leaving_release_respects_max_ceiling(): + # Fully released lead brake: hold speed under MAX, the MAX speed-error + # decel (EV settle and up) over it, never 0 / +a over MAX. + outs = {} + for max_ms in (30.0, 13.0): + planner, inputs, _ = _planner(16.0, accel=-2.5) + inputs["carState"].vCruise = max_ms * 3.6 + planner._lead_leave.update = lambda **kw: 1.0 + _own_lead(inputs, 25.0, 11.0, a_lead=-1.5, y_rel=-1.9, track=7) + for _ in range(40): + planner.update(inputs) + assert planner.lead_leave_w == 1.0 + outs[max_ms] = float(planner.output_a_target) + assert outs[30.0] > -0.1 + assert outs[13.0] < -0.3 + + +@pytest.mark.parametrize("v_ego,d_rel,v_rel,a_lead", [ + (18.5, 25.0, 4.44, -1.04), # 07:55 class + (22.0, 30.0, 2.0, -0.65), # 22:14 class + (30.0, 35.0, 1.13, -1.18), # 23:31 +]) +def test_222_exemplars_unchanged_with_in_lane_wander(v_ego, d_rel, v_rel, a_lead): + on, inputs, _ = _planner(v_ego, accel=-2.0) + off, off_inputs, _ = _planner(v_ego, accel=-2.0) + off._lead_leave.update = lambda **kw: 0.0 + la = _own_lead(inputs, d_rel, v_ego - v_rel, a_lead=a_lead) + lb = _own_lead(off_inputs, d_rel, v_ego - v_rel, a_lead=a_lead) + for i in range(60): + y = 0.6 * math.sin(i * DT * 2.0) + la.yRel = lb.yRel = y + on.update(inputs) + off.update(off_inputs) + assert on.lead_leave_w == 0.0 + assert float(on.output_a_target) == pytest.approx(float(off.output_a_target), abs=1e-9) + assert float(on.unified_a_target) == pytest.approx(float(off.unified_a_target), abs=1e-9) diff --git a/selfdrive/controls/tests/test_leads.py b/selfdrive/controls/tests/test_leads.py index 4b98628bf6e847..77384fea20ffad 100644 --- a/selfdrive/controls/tests/test_leads.py +++ b/selfdrive/controls/tests/test_leads.py @@ -11,19 +11,21 @@ def test_radar_fault(self): def single_iter_pkg(): # single iter package, with meaningless cans and empty carState/modelV2 msgs = [] - for _ in range(5): + for _ in range(500): can = messaging.new_message("can", 1) cs = messaging.new_message("carState") + cp = messaging.new_message("carParams") msgs.append(can.as_reader()) msgs.append(cs.as_reader()) + msgs.append(cp.as_reader()) model = messaging.new_message("modelV2") msgs.append(model.as_reader()) return msgs msgs = [m for _ in range(3) for m in single_iter_pkg()] - out = replay_process_with_name("radard", msgs, fingerprint=TOYOTA.TOYOTA_COROLLA_TSS2) - states = [m for m in out if m.which() == "radarState"] - failures = [not state.valid and len(state.radarState.radarErrors) for state in states] + out = replay_process_with_name("card", msgs, fingerprint=TOYOTA.TOYOTA_COROLLA_TSS2) + states = [m for m in out if m.which() == "liveTracks"] + failures = [not state.valid for state in states] assert len(states) == 0 or all(failures) diff --git a/selfdrive/controls/tests/test_longitudinal_planner_preap.py b/selfdrive/controls/tests/test_longitudinal_planner_preap.py new file mode 100644 index 00000000000000..be3c06d461296a --- /dev/null +++ b/selfdrive/controls/tests/test_longitudinal_planner_preap.py @@ -0,0 +1,98 @@ +import numpy as np +import pytest + +from cereal import car, log, messaging +from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState +from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner +from openpilot.selfdrive.modeld.constants import ModelConstants + + +def make_preap_params(): + params = car.CarParams.new_message() + params.brand = "tesla" + params.carFingerprint = "TESLA_MODEL_S_PREAP" + params.openpilotLongitudinalControl = True + params.pcmCruise = False + params.steerRatio = 15.75 + params.wheelbase = 2.959 + return params + + +def make_planner_inputs(*, v_ego, v_cruise, pitch, throttle_probability): + radar = messaging.new_message("radarState").radarState + controls = messaging.new_message("controlsState").controlsState + selfdrive = messaging.new_message("selfdriveState").selfdriveState + car_state = messaging.new_message("carState").carState + car_control = messaging.new_message("carControl").carControl + live_parameters = messaging.new_message("liveParameters").liveParameters + model = messaging.new_message("modelV2").modelV2 + + controls.longControlState = LongCtrlState.pid + car_state.vEgo = v_ego + car_state.vCruise = v_cruise * 3.6 + car_control.orientationNED = [0.0, pitch, 0.0] + + position = log.XYZTData.new_message() + position.x = ((v_ego + 0.5) * np.array(ModelConstants.T_IDXS)).tolist() + model.position = position + velocity = log.XYZTData.new_message() + velocity.x = ((v_ego + 0.5) * np.ones_like(ModelConstants.T_IDXS)).tolist() + velocity.x[0] = v_ego + model.velocity = velocity + acceleration = log.XYZTData.new_message() + acceleration.x = np.zeros_like(ModelConstants.T_IDXS).tolist() + model.acceleration = acceleration + model.meta.disengagePredictions.gasPressProbs = [throttle_probability] * 6 + + return { + "radarState": radar, + "controlsState": controls, + "selfdriveState": selfdrive, + "carState": car_state, + "carControl": car_control, + "liveParameters": live_parameters, + "modelV2": model, + } + + +def test_preap_cruise_ignores_model_throttle_suppression(): + planner = LongitudinalPlanner(make_preap_params(), init_v=20.9) + inputs = make_planner_inputs( + v_ego=20.9, + v_cruise=21.0, + pitch=0.046, + throttle_probability=0.15, + ) + + for _ in range(60): + planner.update(inputs) + + assert planner.output_a_target > -0.05 + assert planner.allow_throttle + + +@pytest.mark.parametrize(("brand", "fingerprint", "openpilot_longitudinal", "pcm_cruise"), [ + ("honda", "HONDA_CIVIC", True, False), + ("tesla", "TESLA_MODEL_S_PREAP", False, True), +]) +def test_non_vdas_modes_keep_model_throttle_suppression( + brand, fingerprint, openpilot_longitudinal, pcm_cruise, +): + params = make_preap_params() + params.brand = brand + params.carFingerprint = fingerprint + params.openpilotLongitudinalControl = openpilot_longitudinal + params.pcmCruise = pcm_cruise + planner = LongitudinalPlanner(params, init_v=20.9) + inputs = make_planner_inputs( + v_ego=20.9, + v_cruise=21.0, + pitch=0.046, + throttle_probability=0.15, + ) + + for _ in range(60): + planner.update(inputs) + + assert not planner.allow_throttle + assert planner.output_a_target < -0.5 diff --git a/selfdrive/controls/tests/test_model_sight.py b/selfdrive/controls/tests/test_model_sight.py new file mode 100644 index 00000000000000..c4d6fa5df2a8d4 --- /dev/null +++ b/selfdrive/controls/tests/test_model_sight.py @@ -0,0 +1,52 @@ +"""Shared path-confidence helper: low-visibility steering reads it unchanged.""" +import math +import random + +from openpilot.selfdrive.controls.lib import lat_low_visibility as lv +from openpilot.selfdrive.controls.lib.model_sight import path_y_std_at, sight_distance_m + + +def _frozen_path_y_std_at(times, y_stds, t_query=3.0): + """lat_low_visibility.path_y_std_at as it was before the move (99b1d391).""" + try: + ts = [float(t) for t in (times or [])] + ys = [float(y) for y in (y_stds or [])] + except (TypeError, ValueError): + return None + n = min(len(ts), len(ys)) + pairs = [(t, y) for t, y in zip(ts[:n], ys[:n], strict=True) if math.isfinite(t) and math.isfinite(y)] + if len(pairs) < 2: + return None + pairs.sort(key=lambda p: p[0]) + want = float(t_query) + if want <= pairs[0][0]: + return pairs[0][1] + if want >= pairs[-1][0]: + return pairs[-1][1] + for (t0, y0), (t1, y1) in zip(pairs, pairs[1:], strict=False): + if t0 <= want <= t1 and t1 > t0: + w = (want - t0) / (t1 - t0) + return y0 + w * (y1 - y0) + return None + + +def test_low_vis_reads_the_shared_helper_with_identical_results(): + rng = random.Random(11) + cases = [([], []), (None, None), ([0.0], [1.0]), ([0.0, 1.0], [0.1, float("nan")]), (["x", 1], [0, 1])] + for _ in range(400): + n = rng.randint(0, 40) + ts = sorted(rng.uniform(0, 10) for _ in range(n)) + ys = [rng.choice([rng.uniform(0, 5), float("inf"), float("nan")]) if rng.random() < 0.05 else rng.uniform(0, 5) + for _ in range(rng.randint(max(0, n - 2), n + 2))] + cases.append((ts, ys)) + for ts, ys in cases: + for q in (lv.PATH_T_S, 0.0, 1.7, 3.0, 12.0): + assert lv.path_y_std_at(ts, ys, q) == _frozen_path_y_std_at(ts, ys, q) == path_y_std_at(ts, ys, q) + assert lv.path_y_std_at(ts, ys) == _frozen_path_y_std_at(ts, ys, lv.PATH_T_S) + + +def test_sight_distance_crosses_2m_linearly(): + assert sight_distance_m([0, 50, 100], [0.0, 1.0, 3.0]) == 75.0 + assert sight_distance_m([0, 50, 100], [0.0, 1.0, 1.5]) == 100.0 + assert sight_distance_m([0, 50], [2.5, 3.0]) == 0.0 + assert sight_distance_m([0], [0.0]) is None diff --git a/selfdrive/controls/tests/test_path_obstacle_radar.py b/selfdrive/controls/tests/test_path_obstacle_radar.py new file mode 100644 index 00000000000000..08ca7f2abd40b2 --- /dev/null +++ b/selfdrive/controls/tests/test_path_obstacle_radar.py @@ -0,0 +1,558 @@ +"""radard fold-in for the path obstacle detector. + +radarState bytes must not move when the scan is on, and a detector that +throws must not stop radarState. The camera helper must not open VisionIPC +until a candidate is active. +""" +from __future__ import annotations + +import math +import sys +import time +import types +from types import SimpleNamespace + +import numpy as np + + +def _install_stubs() -> None: + """Let these tests import radard without a built msgq or params_pyx.""" + try: + import openpilot.common.params_pyx # noqa: F401 + except Exception: + mod = types.ModuleType("openpilot.common.params_pyx") + + class Params: + def __init__(self, *args, **kwargs): + pass + + def get_bool(self, key, block=False): + return True + + def get(self, *args, **kwargs): + return None + + def put(self, *args, **kwargs): + pass + + def put_bool(self, *args, **kwargs): + pass + + def remove(self, *args, **kwargs): + pass + + mod.Params = Params + mod.ParamKeyFlag = SimpleNamespace(PERSISTENT=1) + mod.ParamKeyType = SimpleNamespace(BOOL=1) + mod.UnknownKeyName = type("UnknownKeyName", (Exception,), {}) + sys.modules["openpilot.common.params_pyx"] = mod + + try: + from msgq.ipc_pyx import Context # noqa: F401 + return + except Exception: + pass + for key in list(sys.modules): + if key == "msgq" or key.startswith("msgq."): + del sys.modules[key] + + msgq = types.ModuleType("msgq") + + class _Sock: + def connect(self, *args, **kwargs): + pass + + def setTimeout(self, *args, **kwargs): + pass + + def receive(self, non_blocking=False): + return None + + def send(self, data): + pass + + class Poller: + def registerSocket(self, sock): + pass + + def poll(self, timeout): + return [] + + class SocketEventHandle: + def __init__(self, *args, **kwargs): + self.enabled = False + + msgq.Context = type("Context", (), {}) + msgq.Poller = Poller + msgq.SubSocket = _Sock + msgq.PubSocket = _Sock + msgq.SocketEventHandle = SocketEventHandle + msgq.MultiplePublishersError = type("MultiplePublishersError", (Exception,), {}) + msgq.IpcError = type("IpcError", (Exception,), {}) + msgq.toggle_fake_events = lambda *a, **k: None + msgq.set_fake_prefix = lambda *a, **k: None + msgq.get_fake_prefix = lambda: b"" + msgq.delete_fake_prefix = lambda *a, **k: None + msgq.wait_for_one_event = lambda *a, **k: None + msgq.context = msgq.Context() + + def pub_sock(endpoint, segment_size=0): + return _Sock() + + def sub_sock(endpoint, poller=None, addr="127.0.0.1", conflate=False, timeout=None, segment_size=0): + sock = _Sock() + if poller is not None: + poller.registerSocket(sock) + return sock + + def drain_sock_raw(sock, wait_for_one=False): + return [] + + def fake_event_handle(endpoint, identifier=None, override=True, enable=False): + return SocketEventHandle() + + msgq.pub_sock = pub_sock + msgq.sub_sock = sub_sock + msgq.drain_sock_raw = drain_sock_raw + msgq.fake_event_handle = fake_event_handle + msgq.NO_TRAVERSAL_LIMIT = 2**64 - 1 + sys.modules["msgq"] = msgq + sys.modules["msgq.ipc_pyx"] = msgq + + +_install_stubs() + +from openpilot.selfdrive.controls.lib.path_obstacle import ( # noqa: E402 + BUDGET_S, + MAX_POINTS, + ObstacleStage, + PathObstacleDetector, + _Hit, + hit_from_msg, + hit_to_msg, +) +from openpilot.selfdrive.controls.radard import RadarD # noqa: E402 +from openpilot.selfdrive.controls.tests.test_radard import RadarScenario # noqa: E402 +from openpilot.selfdrive.pathobstacled.pathobstacled import ( # noqa: E402 + VISION_FAIL_REASONS, + Helper, + _Cameras, + _crop, + _vision_for, +) +import cereal.messaging as messaging # noqa: E402 + + +class _Capture: + def __init__(self): + self.sent = [] + + def send(self, name, msg): + self.sent.append((name, bytes(msg.to_bytes()), bool(msg.valid))) + + +def _radar_bytes(rd: RadarD): + state = rd.radar_state + raw = bytes(state.to_bytes()) + clear = getattr(state, "clear_write_flag", None) + if clear is not None: + clear() + return bool(rd.radar_state_valid), raw + + +def _drive(enabled: bool): + scenario = RadarScenario(v_ego=20.0) + scenario.radar._obstacle._log_override = enabled + real_stash = scenario.radar._stash_obstacle + + def wrapped(*args, **kwargs): + before_stash = _radar_bytes(scenario.radar) + real_stash(*args, **kwargs) + after_stash = _radar_bytes(scenario.radar) + assert before_stash == after_stash, "obstacle stash changed radarState" + + scenario.radar._stash_obstacle = wrapped + pm = _Capture() + frames = [] + samples = [ + (30.0, [(7, 30.0, 0.0, 0.0), (9, 18.0, -0.2, -20.0)]), + (30.2, [(7, 30.1, 0.0, 0.0), (9, 17.4, -0.1, -20.0)]), + (28.0, [(7, 28.0, 0.1, -0.4), (4, 22.0, 1.2, -19.5)]), + (40.0, None), + (36.0, [(11, 16.0, 0.2, -19.0)]), + ] + t = 1.0 + for _repeat in range(3): + for vision, points in samples: + scenario.step(t, vision_d_rel=vision, radar_points=points) + before = _radar_bytes(scenario.radar) + scenario.radar.run_obstacle(pm) + after = _radar_bytes(scenario.radar) + assert before == after, "run_obstacle changed radarState" + frames.append(before) + t += 0.05 + return frames, pm + + +def test_radar_state_bytes_match_with_detector_on_or_off(): + on, pm_on = _drive(True) + off, _pm_off = _drive(False) + assert on == off + assert any(name == "pathObstacleNAP" and valid for name, _raw, valid in pm_on.sent) + + +def test_raising_detector_still_publishes_radar_state_and_breaker_trips(): + scenario = RadarScenario() + scenario.radar._obstacle._log_override = True + calls = {"n": 0} + + def boom(*args, **kwargs): + calls["n"] += 1 + raise RuntimeError("obstacle scan failed") + + scenario.radar._obstacle.det.begin = boom + pm = _Capture() + for i in range(6): + lead = scenario.step(1.0 + i * 0.1, vision_d_rel=30.0, radar_points=[(7, 30.0, 0.0, 0.0)]) + assert scenario.radar.radar_state is not None + assert lead.status + scenario.radar.publish(pm) + scenario.radar.run_obstacle(pm) + assert calls["n"] == 3 + assert scenario.radar._obstacle._disabled + radar_sends = [item for item in pm.sent if item[0] == "radarState"] + assert len(radar_sends) == 6 + + +def test_past_deadline_is_over_budget_and_stage_skips(): + det = PathObstacleDetector() + points = [SimpleNamespace(dRel=20.0, yRel=0.0, vRel=-20.0, measured=True, trackId=1, yvRel=0.0, rcs=5.0)] + hit = det.begin(points, 20.0, [0.0, 50.0], [0.0, 0.0], 0.08, deadline=time.monotonic() - 1.0) + assert hit.reject_reason == "over_budget" + assert hit.active is False + + stage = ObstacleStage() + stage._log_override = True + calls = {"n": 0} + real_begin = stage.det.begin + + def slow_begin(*args, **kwargs): + calls["n"] += 1 + time.sleep(0.009) + return stage.det._miss([], "over_budget", 1.0) + + stage.det.begin = slow_begin + now = time.monotonic() + hit = stage.step(points, 20.0, [0.0, 50.0], [0.0, 0.0], 0.08, [], None, [], now) + assert hit is not None and hit.reject_reason == "over_budget" + assert stage._skip >= 1 + assert stage._skip == max(1, math.ceil(0.009 / BUDGET_S)) or stage._skip >= 2 + skipped = stage._skip + for i in range(skipped): + stage.step(points, 20.0, [0.0, 50.0], [0.0, 0.0], 0.08, [], None, [], now + i + 1) + assert calls["n"] == 1 + stage.det.begin = real_begin + + +def test_hit_round_trip(): + hit = _Hit( + True, 7, (3, 11), 20.0, 1.25, -0.4, -2.0, 0.3, 1.2, 0.8, + "animal", "entering", 4.0, 1.5, 2, 0.6, "none", 0.7, 0.4, + ) + msg = messaging.new_message("pathObstacleNAP", valid=True) + hit_to_msg(hit, msg.pathObstacleNAP) + msg.pathObstacleNAP.laneProbMin = 0.42 + msg.pathObstacleNAP.pathYStd3s = 0.9 + back = hit_from_msg(msg) + assert back.active == hit.active + assert back.track_id == hit.track_id + assert back.member_ids == hit.member_ids + assert back.radar_class == hit.radar_class + assert back.zone == hit.zone + assert back.reject_reason == hit.reject_reason + assert back.cluster_count == hit.cluster_count + for got, want in ( + (back.x, hit.x), (back.y, hit.y), (back.lateral, hit.lateral), + (back.v_rel, hit.v_rel), (back.v_lat, hit.v_lat), (back.along, hit.along), + (back.radar_conf, hit.radar_conf), (back.time_to_reach, hit.time_to_reach), + (back.time_to_enter, hit.time_to_enter), (back.span_m, hit.span_m), + (back.lighting, hit.lighting), (back.lively, hit.lively), + ): + assert math.isclose(got, want, rel_tol=0.0, abs_tol=1e-5) + assert bool(msg.valid) + + +def test_helper_without_trigger_does_not_open_visionipc(): + opened = [] + + class VisionIpcClient: + def __init__(self, *args, **kwargs): + opened.append(args) + raise AssertionError("VisionIPC opened") + + vipc = types.ModuleType("msgq.visionipc") + vipc.VisionIpcClient = VisionIpcClient + vipc.VisionStreamType = SimpleNamespace(VISION_STREAM_ROAD=1, VISION_STREAM_WIDE_ROAD=2) + sys.modules["msgq.visionipc"] = vipc + + helper = Helper() + assert helper.on_radar(None, time.monotonic()) is None + idle = messaging.new_message("pathObstacleNAP", valid=True) + idle.pathObstacleNAP.active = False + idle.pathObstacleNAP.heartbeat = True + assert helper.on_radar(idle, time.monotonic()) is None + assert opened == [] + assert helper.cams.road is None and helper.cams.wide is None + low = messaging.new_message("pathObstacleNAP", valid=True) + low.pathObstacleNAP.active = False + low.pathObstacleNAP.rejectReason = "lowSpeed" + assert helper.on_radar(low, time.monotonic()) is None + assert opened == [] + + +def _y_buffer(width, height, stamp=0): + return SimpleNamespace( + width=width, height=height, stride=width, + data=bytes(width * height), timestamp_eof=stamp, + ) + + +def _install_vipc(client_cls, stream_type): + previous = sys.modules.get("msgq.visionipc") + vipc = types.ModuleType("msgq.visionipc") + vipc.VisionIpcClient = client_cls + vipc.VisionStreamType = stream_type + sys.modules["msgq.visionipc"] = vipc + return previous + + +def _active_hit_msg(): + hit = _Hit( + True, 1, (1,), 20.0, 0.0, 0.0, -12.0, 0.0, 0.0, 0.8, + "unknown", "inPath", float("nan"), 0.0, 1, 0.0, "none", 1.0, 0.0, + ) + msg = messaging.new_message("pathObstacleNAP", valid=True) + hit_to_msg(hit, msg.pathObstacleNAP) + return msg + + +def test_failed_camera_connection_is_reported_and_retried(): + connects = {"n": 0} + streams = SimpleNamespace(VISION_STREAM_ROAD=1, VISION_STREAM_WIDE_ROAD=2) + + class VisionIpcClient: + def __init__(self, *args, **kwargs): + self.args = args + + @staticmethod + def available_streams(name, block=False): + assert name == "camerad" + return [streams.VISION_STREAM_ROAD] + + def connect(self, blocking): + assert blocking is False + connects["n"] += 1 + return False + + def is_connected(self): + return False + + def recv(self, timeout_ms=0): + raise AssertionError("recv on a failed connection") + + previous = _install_vipc(VisionIpcClient, streams) + try: + helper = Helper() + msg = _active_hit_msg() + now = 1000.0 + sample, _us = helper.on_radar(msg, now) + assert sample.vision_evaluated is False + assert sample.vision_fail_reason == "no_connection" + assert sample.vision_fail_reason in VISION_FAIL_REASONS + assert math.isnan(sample.vision_conf) + assert connects["n"] == 1 + assert helper.cams.road is None + + # Next 5 Hz slot is still inside the connect backoff. + sample, _us = helper.on_radar(msg, now + 0.25) + assert sample.vision_fail_reason == "no_connection" + assert connects["n"] == 1 + + sample, _us = helper.on_radar(msg, now + 0.70) + assert sample.vision_fail_reason == "no_connection" + assert connects["n"] == 2 + finally: + if previous is None: + sys.modules.pop("msgq.visionipc", None) + else: + sys.modules["msgq.visionipc"] = previous + + +def test_valid_frame_yields_a_vision_score(): + streams = SimpleNamespace(VISION_STREAM_ROAD=1, VISION_STREAM_WIDE_ROAD=2) + frame = _y_buffer(1344, 760, stamp=0) + + class VisionIpcClient: + def __init__(self, *args, **kwargs): + self.num_buffers = 4 + + @staticmethod + def available_streams(name, block=False): + return [streams.VISION_STREAM_ROAD] + + def connect(self, blocking): + assert blocking is False + return True + + def is_connected(self): + return True + + def recv(self, timeout_ms=0): + return frame + + previous = _install_vipc(VisionIpcClient, streams) + try: + helper = Helper() + sample, vision_us = helper.on_radar(_active_hit_msg(), time.monotonic()) + assert sample.vision_evaluated is True + assert sample.vision_fail_reason == "" + assert math.isfinite(sample.vision_conf) + assert vision_us > 0.0 + assert helper.cams.road is not None + + behind = _Hit( + True, 2, (2,), -10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, + "unknown", "inPath", float("nan"), 0.0, 1, 0.0, "none", 1.0, 0.0, + ) + score, _us, patch, reason = _vision_for(behind, None, None, _Cameras(), 50.0) + assert score is None and patch is None and reason == "roi_out_of_frame" + + cams = _Cameras() + plane, reason = cams.grab(False, now=10.0, deadline=10.0) + assert plane is None and reason == "budget" + assert reason in VISION_FAIL_REASONS + + stale = _y_buffer(1344, 760, stamp=1) + cams = _Cameras() + + class Fresh(VisionIpcClient): + def recv(self, timeout_ms=0): + return stale + + cams.road = Fresh() + plane, reason = cams._recv("road", 0) + assert plane is None and reason == "stale_frame" + finally: + if previous is None: + sys.modules.pop("msgq.visionipc", None) + else: + sys.modules["msgq.visionipc"] = previous + + +def test_wide_camera_is_used_when_road_is_absent(): + streams = SimpleNamespace(VISION_STREAM_ROAD=1, VISION_STREAM_WIDE_ROAD=2) + seen = [] + frame = _y_buffer(1344, 760) + + class VisionIpcClient: + def __init__(self, endpoint, kind, conflate): + seen.append(kind) + self.num_buffers = 2 + + @staticmethod + def available_streams(name, block=False): + return [streams.VISION_STREAM_WIDE_ROAD] + + def connect(self, blocking): + return True + + def is_connected(self): + return True + + def recv(self, timeout_ms=0): + return frame + + previous = _install_vipc(VisionIpcClient, streams) + try: + hit = _Hit( + True, 3, (3,), 12.0, 0.0, 0.0, -12.0, 0.0, 0.0, 0.8, + "unknown", "inPath", float("nan"), 0.0, 1, 0.0, "none", 1.0, 0.0, + ) + score, _us, patch, reason = _vision_for(hit, None, None, _Cameras(), time.monotonic()) + assert reason == "" and patch is not None and score is not None and score.evaluated + assert seen == [streams.VISION_STREAM_WIDE_ROAD] + finally: + if previous is None: + sys.modules.pop("msgq.visionipc", None) + else: + sys.modules["msgq.visionipc"] = previous + + +def test_calibration_is_read_from_params(): + import cereal.messaging as messaging + from openpilot.selfdrive.pathobstacled.pathobstacled import _DEFAULT_CALIB, _calibration_from_params + + class _Empty: + def get(self, _key): + return None + + assert _calibration_from_params(_Empty()) == _DEFAULT_CALIB + + msg = messaging.new_message("liveCalibration", valid=True) + msg.liveCalibration.rpyCalib = [0.1, -0.2, 0.3] + msg.liveCalibration.wideFromDeviceEuler = [0.01, 0.02, -0.03] + msg.liveCalibration.height = [1.41] + + class _Stored: + def get(self, key): + assert key == "CalibrationParams" + return msg.to_bytes() + + roll, pitch, yaw, height, wr, wp, wy = _calibration_from_params(_Stored()) + for got, want in ( + (roll, 0.1), (pitch, -0.2), (yaw, 0.3), (height, 1.41), + (wr, 0.01), (wp, 0.02), (wy, -0.03), + ): + assert math.isclose(got, want, rel_tol=0.0, abs_tol=1e-5) + + +def test_crop_is_detached_from_the_camera_buffer(): + plane = np.arange(400, dtype=np.uint8).reshape(20, 20) + before = plane.copy() + patch, road = _crop(plane, (2.2, 2.2, 12.8, 14.4)) + assert patch is not None and road is not None + patch[:] = 3 + road[:] = 9 + assert np.array_equal(plane, before) + + +def test_scan_timing_on_a_full_frame(): + """Print p50/p99 for the scan radard runs. Hard budget is 4 ms.""" + det = PathObstacleDetector() + points = [ + SimpleNamespace( + dRel=8.0 + (i % 20) * 4.0, + yRel=((i % 9) - 4) * 0.4, + vRel=-20.0, + measured=True, + trackId=i + 1, + yvRel=0.05 * ((i % 5) - 2), + rcs=5.0, + ) + for i in range(MAX_POINTS) + ] + path_x = [0.0, 10.0, 20.0, 40.0, 80.0] + path_y = [0.0, 0.0, 0.0, 0.0, 0.0] + # Warm the tracks so the timed calls include history, not first-seen setup only. + for _ in range(4): + det.begin(points, 20.0, path_x, path_y, 0.08) + samples = [] + for _ in range(80): + t0 = time.perf_counter() + det.begin(points, 20.0, path_x, path_y, 0.08, deadline=time.monotonic() + BUDGET_S) + samples.append((time.perf_counter() - t0) * 1000.0) + samples.sort() + p50 = samples[len(samples) // 2] + p99 = samples[int(len(samples) * 0.99)] + print(f"radard obstacle scan n={MAX_POINTS} p50 {p50:.3f} ms p99 {p99:.3f} ms max {samples[-1]:.3f} ms") + assert p50 < BUDGET_S * 1000.0 diff --git a/selfdrive/controls/tests/test_preap_brake_long_active.py b/selfdrive/controls/tests/test_preap_brake_long_active.py new file mode 100644 index 00000000000000..1eb326dbf01418 --- /dev/null +++ b/selfdrive/controls/tests/test_preap_brake_long_active.py @@ -0,0 +1,204 @@ +"""Pre-AP brake pauses long only. + +longActive and the logged accel drop while the driver brake is down or +long is paused. brakePressed stays false so the press does not cancel +lateral. A brake that outlives the pedal RELEASE by more than 0.1 s is +an error event with no alert and no chime. +""" +from pathlib import Path +from types import SimpleNamespace + +from cereal import car, log +from opendbc.car.tesla.preap.constants import PEDAL_LONG_K_BP, PEDAL_LONG_KI_V, PEDAL_LONG_KP_V + +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.controls.lib.longcontrol import LongControl, LongCtrlState +from openpilot.selfdrive.controls.lib.preap_driver_brake import ( + BRAKE_LONG_OVERLAP_S, + BrakeLongOverlap, + brake_signal_disables, + driver_brake_applied, + preap_longitudinal_active, + preap_pedal_long, + published_long_accel, +) +from openpilot.selfdrive.selfdrived.events import ET, EVENTS, Events +from openpilot.selfdrive.selfdrived.state import ACTIVE_STATES, StateMachine + +EventName = log.OnroadEvent.EventName +State = log.SelfdriveState.OpenpilotState +REPO = Path(__file__).resolve().parents[3] + + +def _cp(**kwargs): + cp = SimpleNamespace( + brand="tesla", + carFingerprint="TESLA_MODEL_S_PREAP", + openpilotLongitudinalControl=True, + pcmCruise=False, + ) + for key, value in kwargs.items(): + setattr(cp, key, value) + return cp + + +def _active(**kwargs): + params = dict( + enabled=True, + longitudinal_override=False, + openpilot_longitudinal=True, + preap_pedal=True, + enable_long_control=True, + driver_brake=False, + ) + params.update(kwargs) + return preap_longitudinal_active(**params) + + +def _disables(**kwargs): + params = dict( + preap_pedal=True, + driver_brake=False, + prev_driver_brake=False, + brake_pressed=False, + prev_brake_pressed=False, + regen_braking=False, + prev_regen_braking=False, + standstill=False, + ) + params.update(kwargs) + return brake_signal_disables(**params) + + +def test_preap_pedal_long_is_the_software_cruise_fingerprint(): + assert preap_pedal_long(_cp()) + assert not preap_pedal_long(_cp(pcmCruise=True, openpilotLongitudinalControl=False)) + assert not preap_pedal_long(_cp(brand="toyota", carFingerprint="TOYOTA_RAV4")) + + +def test_driver_brake_applied_ignores_brake_pressed(): + assert driver_brake_applied(SimpleNamespace(driverBrakeApplied=True, brakePressed=False, brake=0.0)) + assert not driver_brake_applied(SimpleNamespace(driverBrakeApplied=False, brakePressed=True, brake=0.0)) + assert driver_brake_applied(SimpleNamespace(brakePressed=False, brake=1.0)) + assert not driver_brake_applied(SimpleNamespace(brakePressed=False, brake=0.0)) + + +def test_long_active_is_false_while_braking_or_paused_and_only_on_preap(): + assert not _active(driver_brake=True) + assert not _active(enable_long_control=False) + assert _active() + assert not _active(longitudinal_override=True) + assert not _active(enabled=False) + # Stock cars still publish long while brakePressed-style flags are set. + # Pre-AP disengage is not this gate. + assert _active(preap_pedal=False, driver_brake=True, enable_long_control=False) + + +def test_paused_long_logs_zero_accel_not_the_phantom_decel(): + assert published_long_accel(long_active=False, loc_accel=-0.38, preap_pedal=True) == 0.0 + assert published_long_accel(long_active=True, loc_accel=-0.38, preap_pedal=True) == -0.38 + assert published_long_accel(long_active=False, loc_accel=-0.38, preap_pedal=False) == -0.38 + + params = car.CarParams.new_message() + params.brand = "tesla" + params.carFingerprint = "TESLA_MODEL_S_PREAP" + params.openpilotLongitudinalControl = True + params.pcmCruise = False + params.longitudinalTuning.kpBP = PEDAL_LONG_K_BP + params.longitudinalTuning.kpV = PEDAL_LONG_KP_V + params.longitudinalTuning.kiBP = PEDAL_LONG_K_BP + params.longitudinalTuning.kiV = PEDAL_LONG_KI_V + params.vEgoStarting = 0.1 + loc = LongControl(params) + loc.last_output_accel = -0.38 + loc.long_control_state = LongCtrlState.pid + cs = car.CarState.new_message() + cs.vEgo = 12.0 + cs.brakePressed = False + out = loc.update(False, cs, -0.38, False, (-1.5, 2.0)) + assert float(out) == 0.0 + assert loc.long_control_state == LongCtrlState.off + assert published_long_accel(long_active=False, loc_accel=out, preap_pedal=True) == 0.0 + + +def test_preap_brake_check_reads_the_switch_and_does_not_kill_lateral(): + assert _disables(driver_brake=True, brake_pressed=False) + # The always-false brakePressed bit is not the Pre-AP source, even if set. + assert not _disables(driver_brake=False, brake_pressed=True, prev_brake_pressed=False) + assert _disables(preap_pedal=False, driver_brake=False, brake_pressed=True) + # Held brake at standstill is not a new edge. Rising still counts. + assert not _disables(driver_brake=True, prev_driver_brake=True, standstill=True) + assert _disables(driver_brake=True, prev_driver_brake=False, standstill=True) + + assert set(EVENTS[EventName.gasPressedOverride]) == {ET.OVERRIDE_LONGITUDINAL} + assert ET.USER_DISABLE not in EVENTS[EventName.gasPressedOverride] + assert ET.USER_DISABLE in EVENTS[EventName.pedalPressed] + alert = EVENTS[EventName.gasPressedOverride][ET.OVERRIDE_LONGITUDINAL] + assert alert.alert_text_1 == "" and alert.alert_text_2 == "" + assert alert.visual_alert == car.CarControl.HUDControl.VisualAlert.none + assert alert.audible_alert == car.CarControl.HUDControl.AudibleAlert.none + + machine = StateMachine() + machine.state = State.enabled + events = Events() + events.add(EventName.gasPressedOverride) + enabled, active = machine.update(events) + assert enabled and active + assert machine.state == State.overriding + assert machine.state in ACTIVE_STATES + + src = (REPO / "selfdrive/selfdrived/selfdrived.py").read_text() + branch = src.split("if preap_steering_only_brake:", 1)[1].split("else:", 1)[0] + assert "gasPressedOverride" in branch + assert "pedalPressed" not in branch + assert "brake_pressed=driver_brake_applied(CS)" in src + assert "Long paused" not in src + + +def test_brake_long_overlap_errors_only_after_a_tenth_and_has_no_alert(): + assert BRAKE_LONG_OVERLAP_S == 0.1 + monitor = BrakeLongOverlap() + fault = rising = False + for _ in range(int(BRAKE_LONG_OVERLAP_S / DT_CTRL)): + fault, rising = monitor.update(driver_brake=True, pedal_long_active=True, dt=DT_CTRL) + assert not fault and not rising + fault, rising = monitor.update(driver_brake=True, pedal_long_active=True, dt=DT_CTRL) + assert fault and rising + fault, rising = monitor.update(driver_brake=True, pedal_long_active=True, dt=DT_CTRL) + assert fault and not rising + fault, rising = monitor.update(driver_brake=True, pedal_long_active=False, dt=DT_CTRL) + assert not fault and not rising + + # The 14:34 release is one control frame, then pedal long is down. + monitor = BrakeLongOverlap() + fault, _ = monitor.update(driver_brake=True, pedal_long_active=True, dt=DT_CTRL) + assert not fault + fault, _ = monitor.update(driver_brake=True, pedal_long_active=False, dt=DT_CTRL) + assert not fault + + assert EVENTS[EventName.preapBrakeLongActive] == {} + events = Events() + events.add(EventName.preapBrakeLongActive) + assert events.create_alerts( + [ET.WARNING, ET.PERMANENT, ET.USER_DISABLE, ET.SOFT_DISABLE, ET.IMMEDIATE_DISABLE], + ) == [] + msg = events.to_msg() + assert len(msg) == 1 + assert msg[0].name == EventName.preapBrakeLongActive + for flag in ( + "warning", "permanent", "enable", "noEntry", "userDisable", + "softDisable", "immediateDisable", "overrideLongitudinal", "overrideLateral", + ): + assert not getattr(msg[0], flag) + assert "preapBrakeLongActive" in (REPO / "selfdrive/selfdrived/selfdrived.py").read_text() + overlay = (REPO / "selfdrive/car/tesla/preap_blinker_lat_pause.py").read_text() + assert "ret.driverBrakeApplied = bool(applied)" in overlay + assert "ret.brakePressed" not in overlay + + +def test_controlsd_wires_long_active_and_the_logged_accel(): + src = (REPO / "selfdrive/controls/controlsd.py").read_text() + assert "preap_longitudinal_active(" in src + assert "published_long_accel(" in src + assert "driver_brake=driver_brake_applied(CS)" in src + assert "enable_long_control=bool(getattr(CS, \"enableLongControl\", False))" in src diff --git a/selfdrive/controls/tests/test_radar_path_gate.py b/selfdrive/controls/tests/test_radar_path_gate.py new file mode 100644 index 00000000000000..6d303db74e1023 --- /dev/null +++ b/selfdrive/controls/tests/test_radar_path_gate.py @@ -0,0 +1,227 @@ +"""Travel-path / oncoming gates. No cereal — fusion stays in test_radard.""" +from types import SimpleNamespace + +from openpilot.selfdrive.controls.lib.radar_path_gate import ( + ONCOMING_VLEAD_MS, + PATH_COLLAPSE_NEW_YREL_M, + PATH_HALF_WIDTH_M, + PATH_INCUMBENT_HALF_WIDTH_M, + RADAR_TO_CAMERA_M, + ROUNDABOUT_EXIT_PATH_X, + ROUNDABOUT_EXIT_PATH_Y, + ROUNDABOUT_EXIT_X_M, + CURVE_OUTSIDE_PATH_X, + CURVE_OUTSIDE_PATH_Y, + CURVE_OUTSIDE_TWO_LANES_M, + CURVE_OUTSIDE_X_M, + ATLANTIC_LEFT_PATH_X, + ATLANTIC_LEFT_PATH_Y, + LEFT_TURN_PATH_X, + LEFT_TURN_PATH_Y, + LEFT_TURN_X_M, + collapse_blocks_new_lead, + path_lateral_m, + path_model_collapsed, + path_y_at_x, + radar_follow_ok, + track_is_in_path, + track_is_oncoming, + vision_lead_follow_ok, +) + +ROUNDABOUT_ENTRANT_DREL = ROUNDABOUT_EXIT_X_M - RADAR_TO_CAMERA_M + + +def radar(d_rel=40.0, y_rel=0.0, v_rel=0.0, v_lead=None): + kw = dict(dRel=d_rel, yRel=y_rel, vRel=v_rel) + if v_lead is not None: + kw["vLead"] = v_lead + return SimpleNamespace(**kw) + + +def test_straight_path_uses_yrel(): + # No model path: device y = −yRel. Left sign (yRel +3.2, roadside) is off path. + assert track_is_in_path(radar(y_rel=0.4)) + assert not track_is_in_path(radar(y_rel=3.2)) + assert not track_is_in_path(radar(y_rel=-3.2)) + assert abs(path_lateral_m(radar(y_rel=3.2))) == 3.2 + + +def test_model_path_rejects_left_sign_on_straight(): + path_x = (0.0, 20.0, 40.0, 80.0) + path_y = (0.0, 0.0, 0.0, 0.0) + sign = radar(d_rel=40.0, y_rel=3.2, v_rel=-20.0) # stationary, left of path + assert not radar_follow_ok(sign, v_ego=20.0, path_x=path_x, path_y=path_y) + + +def test_model_path_keeps_lead_that_follows_curve(): + # Path goes left 3 m by 40 m. On-path radar has device y = +3 → yRel = −3. + path_x = (0.0, 20.0, 40.0, 80.0) + path_y = (0.0, 1.5, 3.0, 4.0) + on_path = radar(d_rel=40.0 - 1.52, y_rel=-3.0, v_rel=0.0) + ego_center = radar(d_rel=40.0 - 1.52, y_rel=0.0, v_rel=0.0) + assert abs(path_y_at_x(path_x, path_y, 40.0) - 3.0) < 1e-6 + assert track_is_in_path(on_path, path_x, path_y) + assert not track_is_in_path(ego_center, path_x, path_y) + + +def test_oncoming_is_closing_from_ahead_not_stopped(): + v_ego = 20.0 + stopped = radar(d_rel=40.0, y_rel=0.0, v_rel=-v_ego) # vLead = 0 + same_dir = radar(d_rel=40.0, y_rel=0.0, v_rel=-2.0) # vLead = 18 + oncoming = radar(d_rel=40.0, y_rel=-1.5, v_rel=-(v_ego + 15.0)) # vLead = −15 + assert not track_is_oncoming(stopped, v_ego) + assert not track_is_oncoming(same_dir, v_ego) + assert track_is_oncoming(oncoming, v_ego) + assert radar_follow_ok(stopped, v_ego) + assert radar_follow_ok(same_dir, v_ego) + assert not radar_follow_ok(oncoming, v_ego) + + +def test_oncoming_not_applied_at_crawl(): + oncoming = radar(d_rel=20.0, y_rel=0.0, v_rel=-8.0, v_lead=-7.0) + assert not track_is_oncoming(oncoming, v_ego=1.0) + assert radar_follow_ok(oncoming, v_ego=1.0) + + +def test_incumbent_half_width_is_wider_than_acquire(): + edge = radar(d_rel=40.0, y_rel=PATH_HALF_WIDTH_M + 0.2) + assert not radar_follow_ok(edge, v_ego=20.0, max_lat=PATH_HALF_WIDTH_M) + assert radar_follow_ok(edge, v_ego=20.0, max_lat=PATH_INCUMBENT_HALF_WIDTH_M) + + +def test_roundabout_exit_rejects_entering_cross_traffic(): + """Right-exit path; entering vehicle is not oncoming and not on the path.""" + path_x, path_y = ROUNDABOUT_EXIT_PATH_X, ROUNDABOUT_EXIT_PATH_Y + assert abs(path_y_at_x(path_x, path_y, ROUNDABOUT_EXIT_X_M) - (-4.0)) < 1e-6 + + # Looks ahead (yRel≈0), circulating ~same speed — the 20:54 max-regen lock. + entrant = radar(d_rel=ROUNDABOUT_ENTRANT_DREL, y_rel=0.0, v_rel=-2.0) + assert not track_is_oncoming(entrant, v_ego=12.0) + assert not track_is_in_path(entrant, path_x, path_y) + assert not radar_follow_ok(entrant, v_ego=12.0, path_x=path_x, path_y=path_y) + assert abs(path_lateral_m(entrant, path_x, path_y)) >= 3.5 + + # Lead already on the exit (device y = −4 → yRel = +4) stays valid. + on_exit = radar(d_rel=ROUNDABOUT_ENTRANT_DREL, y_rel=4.0, v_rel=-1.0) + assert track_is_in_path(on_exit, path_x, path_y) + assert radar_follow_ok(on_exit, v_ego=12.0, path_x=path_x, path_y=path_y) + + +def test_curve_outside_sign_is_not_an_oncoming_lead(): + """~20:55 CT: static sign ~two lanes outside a left curve. + + Stationary (vLead≈0) is not oncoming. Bosch may also report a bogus + closing vRel — still reject. A real lead on the curve stays valid. + """ + path_x, path_y = CURVE_OUTSIDE_PATH_X, CURVE_OUTSIDE_PATH_Y + path_at = path_y_at_x(path_x, path_y, CURVE_OUTSIDE_X_M) + assert abs(path_at - 4.0) < 1e-6 + d_rel = CURVE_OUTSIDE_X_M - RADAR_TO_CAMERA_M + # device y = path − two lanes (outside / right of a left turn) + device_y = path_at - CURVE_OUTSIDE_TWO_LANES_M + y_rel = -device_y + v_ego = 16.0 + + stationary = radar(d_rel=d_rel, y_rel=y_rel, v_rel=-v_ego) + bogus_oncoming = radar(d_rel=d_rel, y_rel=y_rel, v_rel=-(v_ego + 18.0)) + assert not track_is_oncoming(stationary, v_ego) + assert track_is_oncoming(bogus_oncoming, v_ego) + assert abs(abs(path_lateral_m(stationary, path_x, path_y)) - CURVE_OUTSIDE_TWO_LANES_M) < 1e-6 + assert not track_is_in_path(stationary, path_x, path_y) + assert not radar_follow_ok(stationary, v_ego, path_x, path_y) + assert not radar_follow_ok(bogus_oncoming, v_ego, path_x, path_y) + + on_curve = radar(d_rel=d_rel, y_rel=-path_at, v_rel=-1.0) + assert track_is_in_path(on_curve, path_x, path_y) + assert radar_follow_ok(on_curve, v_ego, path_x, path_y) + + +def test_2108_gas_station_ahead_is_off_left_turn_path(): + """21:08: gas station / signs straight ahead while the road turns left.""" + path_x, path_y = ATLANTIC_LEFT_PATH_X, ATLANTIC_LEFT_PATH_Y + v_ego = 12.5 # ~28 mph into the turn + for d_rel, y_rel in ((40.0, 0.0), (25.0, 0.2), (12.0, -0.3), (8.0, 0.1)): + t = radar(d_rel=d_rel, y_rel=y_rel, v_rel=-v_ego) + assert not track_is_in_path(t, path_x, path_y) + assert not radar_follow_ok(t, v_ego, path_x, path_y) + + +def test_left_turn_ego_forward_is_not_path_association(): + """21:06–21:07: yRel≈0 / left signs / oncoming semi are off the left-turn path.""" + path_x, path_y = LEFT_TURN_PATH_X, LEFT_TURN_PATH_Y + d_rel = LEFT_TURN_X_M - RADAR_TO_CAMERA_M + v_ego = 12.0 + ahead = radar(d_rel=d_rel, y_rel=0.0, v_rel=-v_ego) # 21:07 sign + left_sign = radar(d_rel=d_rel, y_rel=2.0, v_rel=-v_ego) # 21:06 tid 872 class + semi = radar(d_rel=d_rel, y_rel=0.4, v_rel=-(v_ego + 16.0)) + assert abs(path_y_at_x(path_x, path_y, LEFT_TURN_X_M) - 4.0) < 1e-6 + for t in (ahead, left_sign, semi): + assert not track_is_in_path(t, path_x, path_y) + assert not radar_follow_ok(t, v_ego, path_x, path_y) + on_path = radar(d_rel=d_rel, y_rel=-4.0, v_rel=-1.0) + assert track_is_in_path(on_path, path_x, path_y) + assert radar_follow_ok(on_path, v_ego, path_x, path_y) + + +def test_2102_perimeter_splits_near_edge_and_farther_over(): + """2.0 m perimeter: 2.23 near-edge fails; 3.2 farther-over stays off-path.""" + v_ego = 20.0 + near = radar(d_rel=40.0, y_rel=2.23, v_rel=-(v_ego + 18.8)) + far = radar(d_rel=40.0, y_rel=3.2, v_rel=-(v_ego + 20.0)) + mid_truck = radar(d_rel=45.0, y_rel=3.7, v_rel=-(v_ego + 22.0)) + assert not radar_follow_ok(near, v_ego, max_lat=PATH_INCUMBENT_HALF_WIDTH_M) + assert not radar_follow_ok(far, v_ego, max_lat=PATH_INCUMBENT_HALF_WIDTH_M) + assert not radar_follow_ok(mid_truck, v_ego, max_lat=PATH_INCUMBENT_HALF_WIDTH_M) + assert abs(path_lateral_m(near)) > PATH_INCUMBENT_HALF_WIDTH_M + assert abs(path_lateral_m(far)) > PATH_INCUMBENT_HALF_WIDTH_M + assert abs(path_lateral_m(mid_truck)) > PATH_INCUMBENT_HALF_WIDTH_M + + +def test_straight_opposing_passers_are_not_follow_leads(): + """20:58: mid-lane opposing stays off the follow set (ignored, no brake).""" + v_ego = 20.0 + path_x = (0.0, 40.0, 80.0) + path_y = (0.0, 0.0, 0.0) + for y_rel, d_rel in ((3.1, 80.0), (2.9, 50.0), (3.4, 28.0)): + t = radar(d_rel=d_rel, y_rel=y_rel, v_rel=-(v_ego + 20.0)) + assert track_is_oncoming(t, v_ego) + assert not track_is_in_path(t, path_x, path_y) + assert not radar_follow_ok(t, v_ego, path_x, path_y) + + +def test_ep2059_near_edge_oncoming_fails_follow_ok(): + """yRel +2.23 is inside old 2.5 m; vLead oncoming + 2.0 m gate must drop it.""" + v_ego = 20.0 + near = radar(d_rel=40.0, y_rel=2.23, v_rel=-(v_ego + 18.8)) + mid = radar(d_rel=50.0, y_rel=3.2, v_rel=-(v_ego + 20.0)) + assert track_is_oncoming(near, v_ego) + assert not radar_follow_ok(near, v_ego) + assert not radar_follow_ok(near, v_ego, max_lat=PATH_INCUMBENT_HALF_WIDTH_M) + assert not radar_follow_ok(mid, v_ego) + + +def test_path_collapse_raises_bar_for_new_wide_lead(): + """Absurd pathY at 15–30 m plus dead lane lines blocks a new |yRel|≳2.""" + path_x = [0.0, 10.0, 15.0, 22.0, 30.0] + path_y = [0.0, -2.0, -55.0, 2.9, -70.0] + dead = [0.01, 0.02, 0.02, 0.01] + healthy = [0.9, 0.96, 0.95, 0.9] + assert path_model_collapsed(dead, path_x, path_y) + assert not path_model_collapsed(healthy, path_x, path_y) + assert not path_model_collapsed(dead, [0.0, 30.0], [0.0, 0.2]) + assert PATH_COLLAPSE_NEW_YREL_M <= 2.0 + assert collapse_blocks_new_lead(-2.9, True, incumbent=False) + assert collapse_blocks_new_lead(2.4, True, incumbent=False) + assert not collapse_blocks_new_lead(-2.9, True, incumbent=True) + assert not collapse_blocks_new_lead(0.4, True, incumbent=False) + assert not collapse_blocks_new_lead(-2.9, False, incumbent=False) + + +def test_vision_lead_rejects_oncoming_and_far_lateral(): + oncoming = SimpleNamespace(x=[40.0], y=[0.0], v=[ONCOMING_VLEAD_MS - 1.0]) + assert not vision_lead_follow_ok(oncoming, v_ego=20.0) + far = SimpleNamespace(x=[40.0], y=[3.5], v=[20.0]) + assert not vision_lead_follow_ok(far, v_ego=20.0) + ok = SimpleNamespace(x=[40.0], y=[0.3], v=[18.0]) + assert vision_lead_follow_ok(ok, v_ego=20.0) diff --git a/selfdrive/controls/tests/test_radar_sensor_dirty.py b/selfdrive/controls/tests/test_radar_sensor_dirty.py new file mode 100644 index 00000000000000..934fd4d6dfecb9 --- /dev/null +++ b/selfdrive/controls/tests/test_radar_sensor_dirty.py @@ -0,0 +1,463 @@ +"""Pre-AP Bosch radar SensorDirty: degrade, do not soft-disable. + +I-40 gorge construction zone, Oct 4 2026 03:03:59 CT (route +1c95345a3286a5db|00000156--eb2236cd87): the radar set RADC_SensorDirty in its own +SguInfo frame (0x301 bit 44) while CAN was valid and leadOne radar=1 stayed live. +opendbc maps the flag to radarUnavailableTemporary -> radarTempUnavailable +(SOFT_DISABLE + NO_ENTRY): disengaged, 3 min 50 s of re-engage lockout. + +Pinned here: NAPRadarIgnoreSensorDirty (default on) masks only that flag while live +measured tracks exist, tags radarPreferReason, keeps the radar lead, warns through the +existing radarPreferFallback event (never a disable), and escalates to the old +soft-disable only when the flag persists SENSOR_DIRTY_PERSIST_S with no live track. +Param off = old behavior. The radarstat line carries the radar status bits and a track +summary. +""" +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from cereal import messaging +from openpilot.selfdrive.controls.lib import radar_sensor_dirty as sd +from openpilot.selfdrive.controls.lib import radar_status_log as rsl +from openpilot.selfdrive.controls.lib.radar_sensor_dirty import ( + SENSOR_DIRTY_LIVE_RECOVER_S, + SENSOR_DIRTY_PERSIST_S, + SENSOR_DIRTY_REASON, + SensorDirtyPolicy, + reason_token, + sensor_dirty_degraded, + sensor_dirty_ignore_enabled, +) +from openpilot.selfdrive.controls.radard import RADAR_TO_CAMERA, RadarD +from openpilot.selfdrive.selfdrived.events import EVENTS, ET, EventName + +DT = 0.05 +REPO = Path(__file__).resolve().parents[3] + + +class FakeParams: + def __init__(self, values=None): + self.values = dict(values or {}) + + def get_bool(self, key): + return bool(self.values[key]) + + +# ---------------------------------------------------------------- policy + + +def _run_policy(policy, seconds, flag=True, live=True, ignore=True): + mask = None + for _ in range(int(round(seconds / DT))): + mask = policy.update(flag, live, DT, ignore=ignore) + return mask + + +def test_constants_are_pinned(): + assert SENSOR_DIRTY_PERSIST_S == 10.0 + assert SENSOR_DIRTY_LIVE_RECOVER_S == 1.0 + assert SENSOR_DIRTY_REASON == "sensorDirty" + assert sd.SENSOR_DIRTY_PARAM == "NAPRadarIgnoreSensorDirty" + + +def test_param_defaults_on_and_off_means_old_behavior(): + assert sensor_dirty_ignore_enabled(None) is True + assert sensor_dirty_ignore_enabled(FakeParams({"NAPRadarIgnoreSensorDirty": True})) is True + assert sensor_dirty_ignore_enabled(FakeParams({"NAPRadarIgnoreSensorDirty": False})) is False + + class Broken: + def get_bool(self, key): + raise KeyError(key) + + # An unreadable param is the new default, never a silent switch to the old soft-disable. + assert sensor_dirty_ignore_enabled(Broken()) is True + + +def test_live_tracks_keep_the_flag_masked_indefinitely(): + policy = SensorDirtyPolicy() + for _ in range(int(120 / DT)): + assert policy.update(True, True, DT) + assert policy.degraded and not policy.escalated + assert policy.no_track_s == 0.0 + + +def test_no_flag_never_masks_and_resets(): + policy = SensorDirtyPolicy() + _run_policy(policy, 5.0, flag=True, live=False) + assert policy.no_track_s > 0.0 + assert policy.update(False, False, DT) is False + assert not policy.degraded and not policy.escalated and policy.no_track_s == 0.0 + + +def test_flag_without_live_tracks_escalates_after_persist_window(): + policy = SensorDirtyPolicy() + frames = int(round(SENSOR_DIRTY_PERSIST_S / DT)) + for i in range(frames - 1): + assert policy.update(True, False, DT) is True, i + assert not policy.escalated + # The frame that reaches the persistence window hands the flag back unmasked. + assert policy.update(True, False, DT) is False + assert policy.escalated and not policy.degraded + assert policy.update(True, False, DT) is False + + +def test_brief_track_blip_does_not_restart_the_no_track_clock(): + policy = SensorDirtyPolicy() + _run_policy(policy, 6.0, live=False) + before = policy.no_track_s + _run_policy(policy, SENSOR_DIRTY_LIVE_RECOVER_S - 0.2, live=True) + assert policy.no_track_s == pytest.approx(before) + _run_policy(policy, 1.0, live=False) + _run_policy(policy, SENSOR_DIRTY_LIVE_RECOVER_S - 0.5, live=True) + assert policy.no_track_s == pytest.approx(before + 1.0) + _run_policy(policy, 3.5, live=False) + assert policy.escalated + + +def test_tracks_back_restart_the_clock_and_lift_the_escalation(): + policy = SensorDirtyPolicy() + _run_policy(policy, SENSOR_DIRTY_PERSIST_S + 1.0, live=False) + assert policy.escalated + _run_policy(policy, SENSOR_DIRTY_LIVE_RECOVER_S + 0.2, live=True) + assert policy.no_track_s == 0.0 + assert policy.degraded and not policy.escalated + # And it needs a fresh full window to escalate again. + _run_policy(policy, SENSOR_DIRTY_PERSIST_S - 1.0, live=False) + assert policy.degraded and not policy.escalated + + +def test_ignore_off_never_masks_and_never_degrades(): + policy = SensorDirtyPolicy() + assert _run_policy(policy, 30.0, flag=True, live=True, ignore=False) is False + assert not policy.degraded and not policy.escalated + + +def test_reason_token_and_parse(): + assert reason_token("", True) == "sensorDirty" + assert reason_token("dropout", True) == "sensorDirty+dropout" + assert reason_token("dropout", False) == "dropout" + assert reason_token("", False) == "" + assert sensor_dirty_degraded("sensorDirty") + assert sensor_dirty_degraded("sensorDirty+dropout") + assert not sensor_dirty_degraded("dropout") + assert not sensor_dirty_degraded("") + # Substring is not a match, and junk never raises. + assert not sensor_dirty_degraded("notsensorDirtyAtAll") + assert not sensor_dirty_degraded(None) + assert not sensor_dirty_degraded(object()) + + +# ---------------------------------------------------------------- radard + + +class DirtyScenario: + """radard fed by liveTracks messages that carry radarErrors.""" + + def __init__(self, ignore: bool | None = True, v_ego: float = 17.6): + services = ["modelV2", "carState", "liveTracks"] + self.sm = messaging.SubMaster(services, ignore_alive=services, ignore_avg_freq=services) + self.radar = RadarD() + self.radar.rain_gate.set_enabled_override(True) + self.radar.set_sensor_dirty_ignore_override(ignore) + self.v_ego = v_ego + self.t = 1.0 + self.frame = 0 + + def step(self, dirty=False, points=((7, 25.0, 0.0, -1.0),), can_error=False, radar_fault=False, measured=True, + send_tracks=True): + self.t += DT + model = messaging.new_message("modelV2") + model.logMonoTime = int(self.t * 1e9) + model.modelV2.velocity.x = [self.v_ego] + leads = model.modelV2.init("leadsV3", 2) + for lead in leads: + lead.prob = 0.9 + lead.x = [25.0 + RADAR_TO_CAMERA] + lead.xStd = [3.0] + lead.y = [0.0] + lead.yStd = [1.0] + lead.v = [self.v_ego - 1.0] + lead.vStd = [2.0] + lead.a = [0.0] + msgs = [model] + if self.frame == 0: + car_state = messaging.new_message("carState") + car_state.logMonoTime = int(self.t * 1e9) + car_state.carState.vEgo = self.v_ego + msgs.append(car_state) + live = messaging.new_message("liveTracks") + if not send_tracks: + self.sm.update_msgs(self.t, [m.as_reader() for m in msgs]) + self.radar.update(self.sm, self.sm["liveTracks"]) + self.frame += 1 + return self.radar.radar_state + live.logMonoTime = int(self.t * 1e9) + live.liveTracks.errors.radarUnavailableTemporary = dirty + live.liveTracks.errors.canError = can_error + live.liveTracks.errors.radarFault = radar_fault + pts = live.liveTracks.init("points", len(points)) + for point, (track_id, d_rel, y_rel, v_rel) in zip(pts, points, strict=True): + point.trackId, point.dRel, point.yRel, point.vRel, point.measured = track_id, d_rel, y_rel, v_rel, measured + msgs.append(live) + self.sm.update_msgs(self.t, [m.as_reader() for m in msgs]) + self.radar.update(self.sm, self.sm["liveTracks"]) + self.frame += 1 + return self.radar.radar_state + + def run(self, seconds, **kwargs): + state = None + for _ in range(int(round(seconds / DT))): + state = self.step(**kwargs) + return state + + +def test_radard_masks_sensor_dirty_while_tracks_are_live_and_keeps_the_radar_lead(): + sc = DirtyScenario(ignore=True) + state = sc.run(30.0, dirty=True) + assert not state.radarErrors.radarUnavailableTemporary + assert not state.radarErrors.canError and not state.radarErrors.radarFault + assert sensor_dirty_degraded(state.radarPreferReason) + # Reliability saw the masked errors: the only reason is the token, no "fault" riding along. + assert state.radarPreferReason == "sensorDirty" + assert state.leadOne.status and state.leadOne.radar + # selfdrived maps radarPreferFallback to a WARNING (events.py words it "Radar Sensor Dirty"). + assert state.radarPreferFallback + + +def test_radard_param_off_keeps_the_old_soft_disable_flag(): + sc = DirtyScenario(ignore=False) + state = sc.run(5.0, dirty=True) + assert state.radarErrors.radarUnavailableTemporary + assert not sensor_dirty_degraded(state.radarPreferReason) + # The old path: reliability trips on the raw flag ("fault"), exactly as before. + assert state.radarPreferReason == "fault" + + +def test_radard_default_param_is_read_from_params_and_defaults_on(monkeypatch): + sc = DirtyScenario(ignore=None) + sc.radar.rain_gate._params = FakeParams({"NAPRadarIgnoreSensorDirty": True}) + state = sc.run(2.0, dirty=True) + assert not state.radarErrors.radarUnavailableTemporary + sc = DirtyScenario(ignore=None) + sc.radar.rain_gate._params = FakeParams({"NAPRadarIgnoreSensorDirty": False}) + state = sc.run(2.0, dirty=True) + assert state.radarErrors.radarUnavailableTemporary + + +def test_radard_escalates_to_the_old_soft_disable_when_flag_persists_without_tracks(): + sc = DirtyScenario(ignore=True) + state = sc.run(SENSOR_DIRTY_PERSIST_S - 1.0, dirty=True, points=()) + assert not state.radarErrors.radarUnavailableTemporary + assert sensor_dirty_degraded(state.radarPreferReason) + state = sc.run(1.5, dirty=True, points=()) + assert state.radarErrors.radarUnavailableTemporary + assert not sensor_dirty_degraded(state.radarPreferReason) + + +def test_radard_radar_going_silent_counts_as_no_live_tracks(): + sc = DirtyScenario(ignore=True) + state = sc.run(3.0, dirty=True) + assert not state.radarErrors.radarUnavailableTemporary + # liveTracks stops (the last message, with the flag, stays in the SubMaster); 0.5 s timeout, then the window. + state = sc.run(SENSOR_DIRTY_PERSIST_S + 2.0, dirty=True, send_tracks=False) + assert state.radarErrors.radarUnavailableTemporary + assert not sensor_dirty_degraded(state.radarPreferReason) + + +def test_radard_unmeasured_tracks_do_not_count_as_live(): + sc = DirtyScenario(ignore=True) + state = sc.run(SENSOR_DIRTY_PERSIST_S + 1.0, dirty=True, measured=False) + assert state.radarErrors.radarUnavailableTemporary + + +def test_radard_tracks_return_after_escalation_unlocks_reengage(): + sc = DirtyScenario(ignore=True) + state = sc.run(SENSOR_DIRTY_PERSIST_S + 1.0, dirty=True, points=()) + assert state.radarErrors.radarUnavailableTemporary + state = sc.run(SENSOR_DIRTY_LIVE_RECOVER_S + 0.5, dirty=True) + assert not state.radarErrors.radarUnavailableTemporary + assert sensor_dirty_degraded(state.radarPreferReason) + + +def test_radard_never_masks_other_radar_errors(): + sc = DirtyScenario(ignore=True) + state = sc.run(2.0, dirty=True, can_error=True) + assert state.radarErrors.canError + sc = DirtyScenario(ignore=True) + state = sc.run(2.0, dirty=True, radar_fault=True) + assert state.radarErrors.radarFault + assert not state.radarErrors.radarUnavailableTemporary + + +def test_radard_clean_radar_has_no_sensor_dirty_trace(): + sc = DirtyScenario(ignore=True) + state = sc.run(5.0, dirty=False) + assert not sensor_dirty_degraded(state.radarPreferReason) + assert not state.radarErrors.radarUnavailableTemporary + assert not state.radarPreferFallback + assert state.leadOne.radar + + +def test_radard_flag_clearing_drops_the_degraded_tag(): + sc = DirtyScenario(ignore=True) + assert sensor_dirty_degraded(sc.run(5.0, dirty=True).radarPreferReason) + assert not sensor_dirty_degraded(sc.run(1.0, dirty=False).radarPreferReason) + + +# ---------------------------------------------------------------- alert / event wiring + + +class _Sm(dict): + pass + + +def _alert(event_type, reason): + sm = _Sm(radarState=SimpleNamespace(radarPreferReason=reason)) + return EVENTS[EventName.radarPreferFallback][event_type](None, None, sm, False, 0, None) + + +@pytest.mark.parametrize("event_type", [ET.PERMANENT, ET.WARNING]) +def test_alert_text_switches_on_the_sensor_dirty_token(event_type): + dirty = _alert(event_type, "sensorDirty") + assert dirty.alert_text_1 == "Radar Sensor Dirty" + assert "still active" in dirty.alert_text_2 + assert _alert(event_type, "sensorDirty+dropout").alert_text_1 == "Radar Sensor Dirty" + old = _alert(event_type, "fault") + assert old.alert_text_1 == "Radar Unreliable" + assert old.alert_text_2 == "Using camera lead" + assert _alert(event_type, "").alert_text_1 == "Radar Unreliable" + + +def test_degraded_alert_is_a_warning_not_a_disable_or_no_entry(): + events = EVENTS[EventName.radarPreferFallback] + assert ET.SOFT_DISABLE not in events and ET.NO_ENTRY not in events + assert ET.IMMEDIATE_DISABLE not in events and ET.USER_DISABLE not in events + # The hard events are untouched. + assert ET.SOFT_DISABLE in EVENTS[EventName.radarTempUnavailable] + assert ET.NO_ENTRY in EVENTS[EventName.radarTempUnavailable] + + +def test_selfdrived_wiring_is_unchanged_and_degrade_rides_the_fallback_event(): + text = (REPO / "selfdrive/selfdrived/selfdrived.py").read_text() + hard = "elif self.sm['radarState'].radarErrors.radarUnavailableTemporary:\n self.events.add(EventName.radarTempUnavailable)" + fallback = 'elif getattr(self.sm[\'radarState\'], "radarPreferFallback", False):' + assert hard in text and fallback in text + # canError, then the hard SensorDirty soft-disable, then any other radar error, then the warning-only fallback. + assert text.index("radarErrors.canError:") < text.index(hard) < text.index("any(self.sm['radarState'].radarErrors.to_dict().values())") < text.index(fallback) + + +def test_param_key_defaults_on(): + keys = (REPO / "common/params_keys.h").read_text() + assert '{"NAPRadarIgnoreSensorDirty", {PERSISTENT, BOOL, "1"}}' in keys + assert '{"NAPRadarIgnoreHwFail", {PERSISTENT, BOOL}}' in keys + + +# ---------------------------------------------------------------- radarstat line + + +def _sgu(dirty=0, hw=0, sgu=1): + v = (dirty << 44) | (hw << 45) | (sgu << 46) + return v.to_bytes(8, "little") + + +def _pkt(addr, dat, src=1): + return SimpleNamespace(address=addr, dat=dat, src=src) + + +def _pt(d, y, v, measured=True): + return SimpleNamespace(dRel=d, yRel=y, vRel=v, measured=measured) + + +def test_status_log_bit_positions_match_the_ui_decoder(): + from openpilot.selfdrive.ui.radar import bosch_status as ui + assert rsl.SGU_DIRTY_BIT == ui.SGU_DIRTY_BIT == 44 + assert rsl.SGU_HW_FAIL_BIT == ui.SGU_HW_FAIL_BIT == 45 + assert rsl.SGU_FAIL_BIT == ui.SGU_FAIL_BIT == 46 + assert rsl.ADDR_SGU == ui.ADDR_SGU == 0x301 + assert rsl.ADDR_ALERT == ui.ADDR_ALERT == 0x501 + assert rsl.RADAR_BUS == ui.RADAR_BUS == 1 + assert len(rsl.ALERT_NAMES) == 62 + for bit, name in ui.ALERT_BITS: + assert rsl.ALERT_NAMES[bit].lower() == name.lower() or name.lower() in rsl.ALERT_NAMES[bit].lower() + + +def test_status_log_alert_names_cover_blinded_and_radome_heater(): + assert rsl.ALERT_NAMES[6] == "sensorBlinded" + assert rsl.ALERT_NAMES[51] == "radomeHtrInop" + assert rsl.alert_names((1 << 6) | (1 << 51) | (1 << 3)) == ["adjustmentNotDone", "sensorBlinded", "radomeHtrInop"] + assert rsl.alert_names(0) == [] + + +def test_status_log_decodes_the_oct4_sgu_frame(): + # Raw TeslaRadarSguInfo bytes at 03:05:25.033 CT: SensorDirty=1, HWFail=0, SGUFail=1. + assert rsl.decode_sgu(bytes.fromhex("5824ffa2cd59")) == {"dirty": 1, "hw": 0, "sgu": 1} + assert rsl.decode_sgu(_sgu(dirty=1, hw=0, sgu=1)) == {"dirty": 1, "hw": 0, "sgu": 1} + assert rsl.decode_sgu(_sgu(dirty=0, hw=1, sgu=0)) == {"dirty": 0, "hw": 1, "sgu": 0} + + +def test_status_log_track_summary_counts_the_barrier_signature(): + v = 17.6 + pts = [ + _pt(25.0, 0.2, -1.0), # moving lead + _pt(30.0, 1.9, -v), # stationary near the road edge + _pt(41.0, -2.4, -v + 0.5), # stationary near the road edge + _pt(35.0, 7.5, -v), # stationary, far lateral + _pt(90.0, 1.0, -v), # stationary, beyond the near-lateral range + _pt(45.0, 0.0, -2.0, measured=False), + ] + s = rsl.track_summary(pts, v) + assert (s["n"], s["nm"], s["ns"], s["nl"]) == (6, 5, 4, 2) + assert s["ysm"] == 1.0 + assert s["d0"] == 25.0 + empty = rsl.track_summary([], v) + assert empty == {"n": 0, "nm": 0, "ns": 0, "nl": 0, "ysm": None, "d0": None} + + +def test_status_log_emits_two_hz_with_bits_and_summary(): + log = rsl.RadarStatusLogger() + alert = (1 << 6) | (1 << 51) + packets = [_pkt(0x301, _sgu(dirty=1)), _pkt(0x501, alert.to_bytes(8, "little")), _pkt(0x301, b"\x00" * 8, src=0)] + points = [_pt(25.0, 0.2, -1.0), _pt(30.0, 1.9, -17.6)] + line = log.update(packets, points, 17.6, now=100.0) + assert line.startswith("radarstat ") + rec = json.loads(line.removeprefix("radarstat ")) + assert rec["dirty"] == 1 and rec["hw"] == 0 and rec["sgu"] == 1 + assert rec["al"] == f"{alert:016x}" + assert rec["aln"] == ["sensorBlinded", "radomeHtrInop"] + assert (rec["n"], rec["nm"], rec["ns"], rec["nl"]) == (2, 2, 1, 1) + assert rec["sa"] == 0.0 and rec["aa"] == 0.0 and rec["v"] == 17.6 + # 2 Hz: nothing inside the period, one line after it; bits are remembered between frames. + assert log.update([], points, 17.6, now=100.3) is None + later = json.loads(log.update([], points, 17.6, now=100.6).removeprefix("radarstat ")) + assert later["dirty"] == 1 and later["aln"] == ["sensorBlinded", "radomeHtrInop"] + assert later["sa"] == pytest.approx(0.6) and later["aa"] == pytest.approx(0.6) + + +def test_status_log_marks_unseen_frames_and_skips_cycles_without_radar_data(): + log = rsl.RadarStatusLogger() + assert log.update([], None, 10.0, now=1.0) is None + rec = json.loads(log.update([], [], 10.0, now=2.0).removeprefix("radarstat ")) + assert rec["sa"] is None and rec["al"] is None and rec["aa"] is None and rec["aln"] == [] + assert "dirty" not in rec + + +def test_status_log_ignores_non_radar_bus_and_never_raises(): + log = rsl.RadarStatusLogger() + rec = json.loads(log.update([_pkt(0x301, _sgu(dirty=1), src=0), _pkt(0x501, b"\xff" * 8, src=2)], [], 5.0, now=1.0) + .removeprefix("radarstat ")) + assert "dirty" not in rec and rec["al"] is None + try: + out = log.update([object()], [], 5.0, now=9.0) + except Exception as exc: + raise AssertionError(f"status log must swallow its own errors: {exc!r}") from exc + assert out is None + + +def test_card_wires_the_status_log_for_preap_only(): + text = (REPO / "selfdrive/car/card.py").read_text() + assert "self._radar_stat = RadarStatusLogger() if tesla_preap else None" in text + assert 'radar_stat.update(self._can_packets, getattr(RD, "points", None), CS.vEgo)' in text + assert "cloudlog.error(stat_line)" in text diff --git a/selfdrive/controls/tests/test_radard.py b/selfdrive/controls/tests/test_radard.py new file mode 100644 index 00000000000000..eaf3427d7917ab --- /dev/null +++ b/selfdrive/controls/tests/test_radard.py @@ -0,0 +1,922 @@ +import pytest + +from cereal import messaging +from openpilot.selfdrive.controls.lib.radar_path_gate import ( + CURVE_OUTSIDE_PATH_X, + CURVE_OUTSIDE_PATH_Y, + CURVE_OUTSIDE_TWO_LANES_M, + CURVE_OUTSIDE_X_M, + ATLANTIC_LEFT_PATH_X, + ATLANTIC_LEFT_PATH_Y, + LEFT_TURN_PATH_X, + LEFT_TURN_PATH_Y, + LEFT_TURN_X_M, + RADAR_TO_CAMERA_M, + ROUNDABOUT_EXIT_PATH_X, + ROUNDABOUT_EXIT_PATH_Y, + ROUNDABOUT_EXIT_X_M, + path_y_at_x, +) +from openpilot.selfdrive.controls.radard import KalmanParams, RADAR_TO_CAMERA, RadarD, Track + + +MAX_RADAR_MEASUREMENT_AGE = 0.5 + + +class RadarScenario: + def __init__(self, v_ego: float = 20.0): + services = ["modelV2", "carState", "liveTracks"] + self.sm = messaging.SubMaster(services, ignore_alive=services, ignore_avg_freq=services) + self.radar = RadarD() + # Stock-fusion tests stay Off unless a case opts into Radar Enabled. + # Prefer-without-Auto tests call set_radar_enabled(True). + self.radar.rain_gate.set_enabled_override(False) + self.v_ego = v_ego + self.frame = 0 + + def step(self, time_s: float, vision_d_rel: float, radar_points: list[tuple[int, float, float, float]] | None = None, + vision_v: float | None = None, vision_prob: float | None = None, + vision_y: float | None = None, + path_x: list[float] | None = None, path_y: list[float] | None = None, + lane_probs: list[float] | None = None): + messages = [self._model_message(time_s, vision_d_rel, vision_v, vision_prob, + vision_y, path_x, path_y, lane_probs)] + if self.frame == 0: + messages.append(self._car_state_message(time_s)) + if radar_points is not None: + messages.append(self._radar_message(time_s, radar_points)) + + self.sm.update_msgs(time_s, [message.as_reader() for message in messages]) + self.radar.update(self.sm, self.sm["liveTracks"]) + self.frame += 1 + return self.radar.radar_state.leadOne + + def set_rain_hold(self, raining: bool | None): + self.radar.rain_gate.set_override(raining) + + def set_radar_enabled(self, enabled: bool | None): + self.radar.rain_gate.set_enabled_override(enabled) + + def set_radar_reliable(self, healthy: bool | None): + self.radar.reliability.set_override(healthy) + + def _model_message(self, time_s: float, vision_d_rel: float, vision_v: float | None, + vision_prob: float | None, vision_y: float | None = None, + path_x: list[float] | None = None, path_y: list[float] | None = None, + lane_probs: list[float] | None = None): + message = messaging.new_message("modelV2") + message.logMonoTime = int(time_s * 1e9) + message.modelV2.velocity.x = [self.v_ego] + if path_x is not None and path_y is not None: + message.modelV2.position.x = list(path_x) + message.modelV2.position.y = list(path_y) + if lane_probs is not None: + message.modelV2.laneLineProbs = list(lane_probs) + leads = message.modelV2.init("leadsV3", 2) + for lead in leads: + lead.prob = 0.9 if vision_prob is None else vision_prob + lead.x = [vision_d_rel + RADAR_TO_CAMERA] + lead.xStd = [3.0] + lead.y = [0.0 if vision_y is None else vision_y] + lead.yStd = [1.0] + lead.v = [self.v_ego if vision_v is None else vision_v] + lead.vStd = [2.0] + lead.a = [0.0] + return message + + def _car_state_message(self, time_s: float): + message = messaging.new_message("carState") + message.logMonoTime = int(time_s * 1e9) + message.carState.vEgo = self.v_ego + return message + + @staticmethod + def _radar_message(time_s: float, radar_points: list[tuple[int, float, float, float]]): + message = messaging.new_message("liveTracks") + message.logMonoTime = int(time_s * 1e9) + points = message.liveTracks.init("points", len(radar_points)) + for point, (track_id, d_rel, y_rel, v_rel) in zip(points, radar_points, strict=True): + point.trackId = track_id + point.dRel = d_rel + point.yRel = y_rel + point.vRel = v_rel + point.measured = True + return message + + +def test_radar_silence_falls_back_to_current_vision_lead(): + scenario = RadarScenario() + lead = scenario.step(1.0, vision_d_rel=30.0, radar_points=[(7, 30.0, 0.0, 0.0)]) + assert lead.radar + + model_dt = 0.05 + expiration_frame = int(MAX_RADAR_MEASUREMENT_AGE / model_dt) + 1 + for frame in range(1, expiration_frame): + lead = scenario.step(1.0 + frame * model_dt, vision_d_rel=36.0) + assert lead.radar + + lead = scenario.step(1.0 + expiration_frame * model_dt, vision_d_rel=36.0) + + assert not lead.radar + assert lead.dRel == pytest.approx(36.0) + + +def test_association_rejects_distance_outlier(): + scenario = RadarScenario() + lead = scenario.step(1.0, vision_d_rel=100.0, radar_points=[(7, 120.0, 0.0, 0.0)]) + + assert not lead.radar + assert lead.dRel == pytest.approx(100.0) + + +def test_association_rejects_velocity_outlier(): + scenario = RadarScenario() + lead = scenario.step(1.0, vision_d_rel=50.0, radar_points=[(7, 50.0, 0.0, 15.0)]) + + assert not lead.radar + assert lead.vLead == pytest.approx(20.0) + + +def test_association_requires_minimum_score(): + scenario = RadarScenario() + # Each residual remains inside its independent 3-sigma gate, while their + # combined likelihood is below the score floor. + lead = scenario.step(1.0, vision_d_rel=50.0, radar_points=[(7, 58.0, 2.9, 5.5)]) + + assert not lead.radar + + +def test_association_retains_incumbent_until_challenger_wins(): + scenario = RadarScenario() + two_tracks = [(81, 70.0, 0.0, 0.0), (82, 72.0, 0.0, 0.0)] + vision_distances = [70.8, 71.2, 70.8, 71.2, 70.8, 71.2, 72.0, 70.8] + + selected_ids = [ + scenario.step(1.0 + frame * 0.1, vision_d_rel=vision_d_rel, radar_points=two_tracks).radarTrackId + for frame, vision_d_rel in enumerate(vision_distances) + ] + selected_ids.append(scenario.step(1.8, vision_d_rel=70.0, radar_points=[two_tracks[0]]).radarTrackId) + + assert selected_ids == [81, 81, 81, 81, 81, 81, 82, 82, 81] + + +def test_unmeasured_track_does_not_update_kalman_state(): + track = Track(identifier=7, v_lead=20.0, kalman_params=KalmanParams(0.1)) + track.update(d_rel=30.0, y_rel=0.0, v_rel=0.0, v_lead=20.0, measured=True) + track.update(d_rel=30.0, y_rel=0.0, v_rel=1.0, v_lead=21.0, measured=True) + measured_state = (track.vLeadK, track.aLeadK) + + track.update(d_rel=30.0, y_rel=0.0, v_rel=10.0, v_lead=30.0, measured=False) + + assert (track.vLeadK, track.aLeadK) == pytest.approx(measured_state) + + +def test_kalman_uses_observed_radar_interval(): + scenario = RadarScenario() + scenario.step(1.0, vision_d_rel=30.0, radar_points=[(7, 30.0, 0.0, 0.0)]) + + scenario.step(1.08, vision_d_rel=30.0, radar_points=[(7, 30.0, 0.0, 0.0)]) + + assert scenario.radar.tracks[7].K_A[0][1] == pytest.approx(0.08) + + +# Evening rain dig (1c95345a3286a5db|000000df--467073c363, 19:39:05 CT): +# radar track 806 at 93.8 m, vision jumps to 61.6 m with modelProb 0.978. +DIG_RADAR_ID = 806 +DIG_RADAR_DREL = 93.8 +DIG_VISION_WRONG_DREL = 61.6 +DIG_VISION_PROB = 0.978 + + +def _dig_radar_point(d_rel: float = DIG_RADAR_DREL): + return (DIG_RADAR_ID, d_rel, 0.0, 0.0) + + +def test_stock_fusion_drops_to_vision_when_prefer_off(): + """Radar Enabled Off / explicit stock: high modelProb does not keep a mismatched track.""" + scenario = RadarScenario() + scenario.set_radar_enabled(False) + scenario.set_rain_hold(False) + lead = scenario.step(1.0, vision_d_rel=DIG_RADAR_DREL, radar_points=[_dig_radar_point()], + vision_prob=DIG_VISION_PROB) + assert lead.radar + assert lead.radarTrackId == DIG_RADAR_ID + + lead = scenario.step(1.1, vision_d_rel=DIG_VISION_WRONG_DREL, radar_points=[_dig_radar_point()], + vision_prob=DIG_VISION_PROB) + assert not lead.radar + assert lead.dRel == pytest.approx(DIG_VISION_WRONG_DREL) + assert lead.modelProb == pytest.approx(DIG_VISION_PROB) + + +def test_prefer_without_auto_holds_radar_through_vision_confident_wrong_range(): + """Default prefer (no Auto wiper): keep track 806 through the −32 m vision jump.""" + scenario = RadarScenario() + scenario.set_radar_enabled(True) + # No set_rain_hold(True) — prefer is Radar Enabled, not Auto wipers. + lead = scenario.step(1.0, vision_d_rel=DIG_RADAR_DREL, radar_points=[_dig_radar_point()], + vision_prob=DIG_VISION_PROB) + assert lead.radar + assert lead.radarTrackId == DIG_RADAR_ID + + for frame, vision_d_rel in enumerate((61.6, 89.0, 65.5, 68.3, 49.4), start=1): + lead = scenario.step(1.0 + frame * 0.05, vision_d_rel=vision_d_rel, + radar_points=[_dig_radar_point()], vision_prob=DIG_VISION_PROB) + assert lead.radar, f"frame {frame} dropped radar at vision {vision_d_rel}" + assert lead.radarTrackId == DIG_RADAR_ID + assert lead.dRel == pytest.approx(DIG_RADAR_DREL) + + +def test_rain_holds_radar_through_vision_confident_wrong_range(): + """On rain gate: keep track 806 through the dig's −32 m vision jump at modelProb 0.978.""" + scenario = RadarScenario() + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=DIG_RADAR_DREL, radar_points=[_dig_radar_point()], + vision_prob=DIG_VISION_PROB) + assert lead.radar + assert lead.radarTrackId == DIG_RADAR_ID + + for frame, vision_d_rel in enumerate((61.6, 89.0, 65.5, 68.3, 49.4), start=1): + lead = scenario.step(1.0 + frame * 0.05, vision_d_rel=vision_d_rel, + radar_points=[_dig_radar_point()], vision_prob=DIG_VISION_PROB) + assert lead.radar, f"frame {frame} dropped radar at vision {vision_d_rel}" + assert lead.radarTrackId == DIG_RADAR_ID + assert lead.dRel == pytest.approx(DIG_RADAR_DREL) + + +def test_rain_raises_vision_only_modelprob_bar(): + scenario = RadarScenario() + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=40.0, vision_prob=0.60) + assert not lead.status + + lead = scenario.step(1.05, vision_d_rel=40.0, vision_prob=0.91) + assert lead.status + assert not lead.radar + assert lead.dRel == pytest.approx(40.0) + + +def test_stock_fusion_vision_only_modelprob_bar_unchanged(): + scenario = RadarScenario() + scenario.set_radar_enabled(False) + scenario.set_rain_hold(False) + lead = scenario.step(1.0, vision_d_rel=40.0, vision_prob=0.60) + assert lead.status + assert not lead.radar + assert lead.dRel == pytest.approx(40.0) + + +def test_unhealthy_radar_uses_stock_fusion_and_sets_fallback(): + """Enabled but erratic/faulted radar → stock fusion + radarPreferFallback.""" + scenario = RadarScenario() + scenario.set_radar_enabled(True) + scenario.set_radar_reliable(False) + lead = scenario.step(1.0, vision_d_rel=DIG_RADAR_DREL, radar_points=[_dig_radar_point()], + vision_prob=DIG_VISION_PROB) + assert lead.radar + lead = scenario.step(1.1, vision_d_rel=DIG_VISION_WRONG_DREL, radar_points=[_dig_radar_point()], + vision_prob=DIG_VISION_PROB) + assert not lead.radar + assert lead.dRel == pytest.approx(DIG_VISION_WRONG_DREL) + assert scenario.radar.radar_state.radarPreferFallback + assert scenario.radar.radar_state.radarPreferReason == "override" + + +def test_crawl_empty_table_does_not_set_fallback_alert(): + """e3 gravel: empty table at ~5 m/s must not flash Radar Unreliable.""" + scenario = RadarScenario(v_ego=5.35) + scenario.set_radar_enabled(True) + scenario.step(1.0, vision_d_rel=20.0, radar_points=[(1, 20.0, 0.0, 0.0)]) + for frame in range(1, 9): + scenario.step(1.0 + frame * 0.05, vision_d_rel=20.0, radar_points=[]) + assert not scenario.radar.radar_state.radarPreferFallback + assert scenario.radar.reliability.healthy + assert scenario.radar.radar_state.radarPreferReason == "dropout" + + +def test_highway_empty_table_trips_prefer_without_hud(): + """Pavement empty-table above 8 m/s drops prefer; no Radar Unreliable.""" + scenario = RadarScenario(v_ego=16.0) + scenario.set_radar_enabled(True) + scenario.step(1.0, vision_d_rel=40.0, radar_points=[(1, 40.0, 0.0, 0.0)]) + for frame in range(1, 12): + scenario.step(1.0 + frame * 0.05, vision_d_rel=40.0, radar_points=[]) + assert not scenario.radar.radar_state.radarPreferFallback + assert not scenario.radar.reliability.healthy + assert scenario.radar.radar_state.radarPreferReason == "dropout" + assert not scenario.radar.rain_gate.update() + + +def test_erratic_clutter_with_path_lead_does_not_set_fallback(): + """Signs / opposing jumps trip reliability; path lead stays, no HUD.""" + scenario = RadarScenario(v_ego=16.0) + scenario.set_radar_enabled(True) + lead = scenario.step(1.0, vision_d_rel=40.0, + radar_points=[(1, 40.0, 0.0, 0.0), (7, 50.0, 0.2, -32.0)]) + assert lead.radar + y = 5.0 + for frame in range(1, 12): + lead = scenario.step( + 1.0 + frame * 0.05, vision_d_rel=40.0, + radar_points=[(1, 40.0, 0.0, 0.0), (7, 50.0, y, -32.0)]) + y += 5.0 + assert not scenario.radar.radar_state.radarPreferFallback + assert not scenario.radar.reliability.healthy + assert scenario.radar.radar_state.radarPreferReason == "erratic" + assert lead.radar + assert lead.radarTrackId == 1 + + +def test_radar_disabled_does_not_set_fallback_alert(): + scenario = RadarScenario() + scenario.set_radar_enabled(False) + scenario.set_radar_reliable(False) + scenario.step(1.0, vision_d_rel=40.0, radar_points=[(7, 40.0, 0.0, 0.0)]) + assert not scenario.radar.radar_state.radarPreferFallback + + +def test_rain_hold_survives_many_mismatch_frames_while_radar_lives(): + scenario = RadarScenario() + scenario.set_rain_hold(True) + scenario.step(1.0, vision_d_rel=DIG_RADAR_DREL, radar_points=[_dig_radar_point()], + vision_prob=DIG_VISION_PROB) + for frame in range(1, 21): + lead = scenario.step(1.0 + frame * 0.05, vision_d_rel=DIG_VISION_WRONG_DREL, + radar_points=[_dig_radar_point()], vision_prob=DIG_VISION_PROB) + assert lead.radarTrackId == DIG_RADAR_ID + assert lead.dRel == pytest.approx(DIG_RADAR_DREL) + + +def test_rain_holds_cached_radar_then_allows_vision_after_track_lost(): + from openpilot.selfdrive.controls.lib.rain_radar_hold import RAIN_RADAR_LOST_HOLD_FRAMES + + scenario = RadarScenario() + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=30.0, radar_points=[(7, 30.0, 0.0, 0.0)]) + assert lead.radarTrackId == 7 + + for frame in range(1, RAIN_RADAR_LOST_HOLD_FRAMES + 1): + lead = scenario.step(1.0 + frame * 0.05, vision_d_rel=36.0, radar_points=[], vision_prob=0.95) + assert lead.radar, f"lost-hold dropped at frame {frame}" + assert lead.radarTrackId == 7 + assert lead.dRel == pytest.approx(30.0) + + lead = scenario.step(1.0 + (RAIN_RADAR_LOST_HOLD_FRAMES + 1) * 0.05, vision_d_rel=36.0, + radar_points=[], vision_prob=0.95) + assert not lead.radar + assert lead.dRel == pytest.approx(36.0) + + +# Left roadside sign / opposing traffic — Fri 2026-09-18 ~20:49 CT intersection regen. +LEFT_SIGN_YREL = 3.2 +ONCOMING_VREL = -38.0 # v_ego 20 → vLead −18 +IN_PATH = (11, 40.0, 0.3, -0.4) + + +def test_dry_off_path_lateral_does_not_become_radar_lead(): + """yRel 2.8 is inside the old 3-sigma vision gate; path gate must still reject.""" + scenario = RadarScenario() + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=[(3, 40.0, 2.8, 0.0)]) + assert not lead.radar + + +def test_rain_does_not_hold_left_roadside_sign(): + scenario = RadarScenario() + scenario.set_rain_hold(True) + # No confident vision lead — rain used to pick closest |yRel|≤2.5 / hold ≤4.0. + lead = scenario.step(1.0, vision_d_rel=48.0, radar_points=[(44, 48.0, LEFT_SIGN_YREL, -20.0)], + vision_prob=0.40) + assert not lead.status or not lead.radar + lead = scenario.step(1.1, vision_d_rel=48.0, radar_points=[(44, 48.0, LEFT_SIGN_YREL, -20.0)], + vision_prob=0.40) + assert not lead.radar + + +def test_rain_does_not_latch_oncoming_as_follow_lead(): + scenario = RadarScenario() + scenario.set_rain_hold(True) + pts = [(9, 55.0, -1.5, ONCOMING_VREL)] + lead = scenario.step(1.0, vision_d_rel=55.0, radar_points=pts, vision_prob=0.40, + vision_v=-18.0) + assert not lead.radar + assert not lead.status + # Live reject must not keep a phantom cache either. + lead = scenario.step(1.1, vision_d_rel=55.0, radar_points=pts, vision_prob=0.40, + vision_v=-18.0) + assert not lead.radar + assert not lead.status + + +def test_dry_oncoming_does_not_associate_as_radar_lead(): + scenario = RadarScenario() + lead = scenario.step(1.0, vision_d_rel=50.0, radar_points=[(9, 50.0, -1.2, ONCOMING_VREL)], + vision_v=-18.0) + assert not lead.radar + assert not lead.status + + +def test_straight_opposing_passers_stay_ignored_dry_and_rain(): + """~20:58 CT: multiple opposing-lane vehicles, no leadOne / no regen. + + Path-gating must not FOV-pick them. An in-path lead still associates + while they pass. + """ + v_ego = 20.0 + passers = [ + (1, 80.0, 3.1, -(v_ego + 22.0)), + (2, 50.0, 2.9, -(v_ego + 18.0)), + (3, 28.0, 3.4, -(v_ego + 20.0)), + ] + for raining in (False, True): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=70.0, radar_points=passers, + vision_prob=0.40, vision_v=-(v_ego + 20.0)) + assert not lead.radar, f"rain={raining} latched a 20:58 passer" + assert not lead.status, f"rain={raining} published opposing as leadOne" + + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=[IN_PATH, *passers]) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_on_path_stationary_still_acquired_dry_and_rain(): + """Stopped in-path vehicle must stay a radar lead. Not a blanket STAT reject.""" + v_ego = 12.0 + stopped = (11, 28.0, 0.2, -v_ego) + for raining in (False, True): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=28.0, radar_points=[stopped], vision_v=0.0) + assert lead.radar, f"rain={raining} dropped on-path stationary" + assert lead.radarTrackId == 11 + + +def test_prefer_without_auto_path_oncoming_stationary(): + """Binding: prefer (no Auto) — path on/off, oncoming reject, on-path STAT keep.""" + scenario = RadarScenario() + scenario.set_radar_enabled(True) + path_x = [0.0, 20.0, 40.0, 80.0] + path_y = [0.0, 0.0, 0.0, 0.0] + off = scenario.step(1.0, vision_d_rel=40.0, radar_points=[(3, 40.0, 2.8, 0.0)], + path_x=path_x, path_y=path_y) + assert not off.radar + + oncoming = RadarScenario() + oncoming.set_radar_enabled(True) + lead = oncoming.step(1.0, vision_d_rel=50.0, radar_points=[(9, 50.0, -1.2, ONCOMING_VREL)], + vision_v=-18.0) + assert not lead.radar + assert not lead.status + + stopped = RadarScenario(v_ego=12.0) + stopped.set_radar_enabled(True) + lead = stopped.step(1.0, vision_d_rel=28.0, radar_points=[(11, 28.0, 0.2, -12.0)], + vision_v=0.0) + assert lead.radar + assert lead.radarTrackId == 11 + + on_path = RadarScenario() + on_path.set_radar_enabled(True) + lead = on_path.step(1.0, vision_d_rel=40.0, radar_points=[IN_PATH]) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_in_path_lead_still_acquired_dry_and_rain(): + for raining in (False, True): + scenario = RadarScenario() + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=[IN_PATH]) + assert lead.radar, f"rain={raining} missed in-path lead" + assert lead.radarTrackId == 11 + assert lead.dRel == pytest.approx(40.0) + + +def test_rain_hold_does_not_override_path_or_oncoming_rejects(): + scenario = RadarScenario() + scenario.set_rain_hold(True) + # Acquire a real in-path lead first (so incumbent / cache exist). + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=[IN_PATH]) + assert lead.radarTrackId == 11 + + # Same ID walks off path to a left sign — rain must drop, not hold. + lead = scenario.step(1.1, vision_d_rel=40.0, radar_points=[(11, 40.0, LEFT_SIGN_YREL, -20.0)], + vision_prob=0.40) + assert not lead.radar + + # Fresh oncoming track must not replace it. + lead = scenario.step(1.2, vision_d_rel=40.0, radar_points=[(9, 42.0, -1.4, ONCOMING_VREL)], + vision_prob=0.40, vision_v=-16.0) + assert not lead.radar + assert not lead.status + + +def test_rain_still_holds_true_in_path_through_vision_jump(): + scenario = RadarScenario() + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=[IN_PATH]) + assert lead.radarTrackId == 11 + lead = scenario.step(1.05, vision_d_rel=18.0, radar_points=[IN_PATH], vision_prob=0.97) + assert lead.radar + assert lead.radarTrackId == 11 + assert lead.dRel == pytest.approx(40.0) + + +def test_rain_does_not_acquire_unassociated_radar(): + """#201 FOV prefer: closest in-lane radar with no path association must not latch.""" + scenario = RadarScenario() + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=80.0, radar_points=[(44, 40.0, 1.2, -20.0)], + vision_prob=0.40) + assert not lead.radar + assert not lead.status + + +def test_rain_does_not_swap_path_lead_for_left_sign(): + scenario = RadarScenario() + scenario.set_rain_hold(True) + both = [IN_PATH, (44, 36.0, LEFT_SIGN_YREL, -20.0)] + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=both) + assert lead.radarTrackId == 11 + lead = scenario.step(1.1, vision_d_rel=18.0, radar_points=both, vision_prob=0.97) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_model_path_rejects_off_path_even_when_yrel_is_small(): + """OP path curves right; a yRel≈0 roadside object is off the driving path.""" + path_x = [0.0, 20.0, 40.0, 80.0] + path_y = [0.0, -1.5, -3.0, -4.0] + scenario = RadarScenario() + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=38.48, radar_points=[(3, 38.48, 0.0, 0.0)], + path_x=path_x, path_y=path_y) + assert not lead.radar + + # Same curve: radar on the path (device y = −3 → yRel = +3) still associates. + lead = scenario.step(1.1, vision_d_rel=38.48, radar_points=[(11, 38.48, 3.0, 0.0)], + vision_y=-3.0, path_x=path_x, path_y=path_y) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_roundabout_right_exit_does_not_follow_entering_vehicle(): + """~20:54 CT: path turns right to leave; entering / cross traffic is off-path. + + Entrant is not oncoming (circulating, vRel≈−2). yRel≈0 looks like an + in-path lead in a wide FOV. Dry and rain must not make it leadOne. + A vehicle already on the exit path still associates. + """ + path_x = list(ROUNDABOUT_EXIT_PATH_X) + path_y = list(ROUNDABOUT_EXIT_PATH_Y) + d_rel = ROUNDABOUT_EXIT_X_M - RADAR_TO_CAMERA_M + entrant = (22, d_rel, 0.0, -2.0) + on_exit = (11, d_rel, 4.0, -1.0) + + for raining in (False, True): + scenario = RadarScenario(v_ego=12.0) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=d_rel, radar_points=[entrant], + vision_prob=0.92, vision_y=0.0, + path_x=path_x, path_y=path_y) + assert not lead.radar, f"rain={raining} latched roundabout entrant" + assert not lead.status, f"rain={raining} vision-only followed entrant" + + scenario = RadarScenario(v_ego=12.0) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=d_rel, radar_points=[on_exit, entrant], + vision_y=-4.0, path_x=path_x, path_y=path_y) + assert lead.radar + assert lead.radarTrackId == 11 + # Vision flaps toward the entrant — rain must keep the exit-path association. + lead = scenario.step(1.1, vision_d_rel=d_rel, radar_points=[on_exit, entrant], + vision_prob=0.97, vision_y=0.0, path_x=path_x, path_y=path_y) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_e1_episodes_do_not_latch_off_path_or_oncoming(): + """Pinned e1 kinematics (1c95345a3286a5db|000000e1--b993674371). + + Rain Auto On. Stock #201 published these as leadOne with mp≪0.15. + """ + cases = ( + # CT id dRel yRel vRel vision_prob + ("20:46:45", 224, 50.0, 3.4, -16.0, 0.02), # Ep A LEFT STAT sweep + ("20:49:10", 321, 99.3, 0.86, -16.05, 0.007), # Ep B far STAT + ("20:49:11", 318, 40.8, 3.36, -16.0, 0.008), # Ep B LEFT OFFPATH + ("20:51:52", 471, 45.0, 2.5, -20.6, 0.05), # Ep C LEFT STAT + ("20:53:45", 573, 40.0, 3.73, -12.0, 0.04), # Ep D roundabout LEFT + ("20:54:53", 641, 50.0, 3.9, -24.6, 0.022), # Ep E curve-outside STAT + ("20:45:47", 101, 55.0, 2.0, -(16.0 + 5.5), 0.10), # oncoming vLead≈−5.5 + ("20:59:33", 771, 45.0, 2.23, -(16.0 + 22.0), 0.05), # EP_2059 truck + ("20:59:36", 771, 20.0, 3.98, -(16.0 + 22.0), 0.10), # 771 walked off + ("21:00:12", 802, 40.0, 2.48, -(16.0 + 18.7), 0.01), # EP_2059 semi edge + ("20:59:40", 782, 123.0, 0.86, -16.0, 0.01), # Dip 2 far STAT + ("20:59:42", 786, 84.0, 2.11, -16.0, 0.014), # Dip 2 far STAT + ("21:06:29", 872, 109.0, 1.98, -16.0, 0.005), # EP_2106 LEFT sign + ("21:06:46", 905, 107.0, 1.23, -16.0, 0.002), # ahead sweep + ("21:07:39", 925, 112.0, -0.15,-16.0, 0.002), # Atlantic gas + ("21:07:49", 940, 151.0, 0.73, -16.0, 0.01), # near stop + ) + for label, tid, d_rel, y_rel, v_rel, mp in cases: + scenario = RadarScenario(v_ego=16.0) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=d_rel, radar_points=[(tid, d_rel, y_rel, v_rel)], + vision_prob=mp) + assert not lead.radar, f"{label} track {tid} latched as radar leadOne" + + +def test_curve_outside_sign_does_not_become_oncoming_lead(): + """~20:55 CT: sign on the outside of a left curve (~two lanes off path). + + Static (vLead≈0) and bogus oncoming Doppler must not become leadOne. + A lead on the curve still associates. + """ + path_x = list(CURVE_OUTSIDE_PATH_X) + path_y = list(CURVE_OUTSIDE_PATH_Y) + path_at = path_y_at_x(path_x, path_y, CURVE_OUTSIDE_X_M) + d_rel = CURVE_OUTSIDE_X_M - RADAR_TO_CAMERA_M + y_rel = -(path_at - CURVE_OUTSIDE_TWO_LANES_M) + v_ego = 16.0 + stationary = (33, d_rel, y_rel, -v_ego) + bogus = (34, d_rel, y_rel, -(v_ego + 18.0)) + on_curve = (11, d_rel, -path_at, -1.0) + + for raining, pts, vision_v in ( + (False, [stationary], 0.0), + (True, [stationary], 0.0), + (False, [bogus], -18.0), + (True, [bogus], -18.0), + ): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=d_rel, radar_points=pts, + vision_prob=0.92, vision_v=vision_v, vision_y=-y_rel, + path_x=path_x, path_y=path_y) + assert not lead.radar, f"rain={raining} latched outside-curve sign" + assert not lead.status, f"rain={raining} followed outside-curve sign" + + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=d_rel, radar_points=[on_curve, stationary], + vision_y=path_at, path_x=path_x, path_y=path_y) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_2059_large_oncoming_truck_does_not_become_lead(): + """~20:59 CT after clean 20:58: large oncoming truck must not be leadOne.""" + v_ego = 20.0 + truck = (771, 45.0, 2.23, -(v_ego + 21.9)) + for raining in (False, True): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=45.0, radar_points=[truck], + vision_prob=0.10, vision_v=-(v_ego + 21.9)) + assert not lead.radar, f"rain={raining} latched 20:59 oncoming truck" + assert not lead.status, f"rain={raining} published 20:59 truck as leadOne" + + +def test_far_low_prob_incumbent_does_not_hold_for_regen(): + """Second 20:59 slam: far + mp≪0.15 must not stay a rain-hold lead. + + A 99 m STAT may associate while vision is confident, then rain must drop + it when modelProb collapses — not keep regen on furniture / too-distant. + Contrast: 93.8 m + mp 0.978 through a range flap still holds (#201). + """ + v_ego = 16.0 + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(True) + pts = [(321, 99.3, 0.86, -v_ego)] + lead = scenario.step(1.0, vision_d_rel=99.3, radar_points=pts, + vision_prob=0.90, vision_v=0.0) + assert lead.radar + assert lead.radarTrackId == 321 + + lead = scenario.step(1.1, vision_d_rel=99.3, radar_points=pts, + vision_prob=0.007, vision_v=0.0) + assert not lead.radar + assert not lead.status + + +def test_2102_farther_over_opposing_pack_stays_ignored(): + """Justin 21:02: several opposing + a semi farther over — no leadOne. + + Near-edge 802-class still rejected. In-path lead still associates. + """ + v_ego = 20.0 + pack = [ + (1, 70.0, 3.0, -(v_ego + 20.0)), + (2, 55.0, 3.2, -(v_ego + 18.0)), + (3, 40.0, 3.5, -(v_ego + 22.0)), + (4, 28.0, 2.9, -(v_ego + 19.0)), + (5, 20.0, 3.3, -(v_ego + 21.0)), + ] + for raining in (False, True): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=60.0, radar_points=pack, + vision_prob=0.40, vision_v=-(v_ego + 20.0)) + assert not lead.radar, f"rain={raining} latched 21:02 farther-over pack" + assert not lead.status, f"rain={raining} published 21:02 opposing as leadOne" + + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=[IN_PATH, *pack]) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_2103_mid_lane_oncoming_truck_stays_ignored(): + """~21:03 CT: oncoming truck middle of opposing lane — no regen. + + Keep with 21:02 as pass cases. Fail set is near-edge / off-path. + """ + v_ego = 20.0 + truck = (910, 45.0, 3.7, -(v_ego + 22.0)) + for raining in (False, True): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=45.0, radar_points=[truck], + vision_prob=0.40, vision_v=-(v_ego + 22.0)) + assert not lead.radar, f"rain={raining} latched 21:03 mid-lane truck" + assert not lead.status, f"rain={raining} published 21:03 truck as leadOne" + + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=[IN_PATH, truck]) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_ep2059_near_edge_oncoming_semi_does_not_become_lead(): + """20:59/21:00: yRel +2.23 inside old 2.5 m + oncoming vLead → no leadOne. + + 21:02/21:03 mid-lane opposing (|yRel| > 2.5) stays leadOne=None. + Oncoming reject is follow-lead only — it does not invent a new brake. + """ + v_ego = 20.0 + near = (802, 40.0, 2.23, -(v_ego + 18.8)) + mid = (900, 50.0, 3.2, -(v_ego + 20.0)) + for raining, pts in ((True, [near]), (True, [mid]), (False, [near])): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=pts[0][1], radar_points=pts, + vision_prob=0.40, vision_v=-(v_ego + 18.8)) + assert not lead.radar, f"rain={raining} pts={pts[0][0]} latched oncoming" + assert not lead.status, f"rain={raining} pts={pts[0][0]} published leadOne" + + +def test_2100_close_opposing_semi_not_kept_by_rain_hold(): + """~21:00 CT: large/close opposing-lane semi. Size does not matter. + + Rain must not acquire it, must not switch an in-path hold to it, and + must drop the same track ID if it flips to oncoming. 20:58 mid-lane + cars stay ignored. + """ + v_ego = 20.0 + semi_edge = (802, 28.0, 2.23, -(v_ego + 18.8)) + semi_close = (803, 25.0, 1.0, -(v_ego + 18.8)) + for pts in (semi_edge, semi_close): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=40.0, radar_points=[IN_PATH, pts]) + assert lead.radarTrackId == 11 + lead = scenario.step(1.1, vision_d_rel=pts[1], radar_points=[pts], + vision_prob=0.40, vision_v=-(v_ego + 18.8)) + assert not lead.radar, f"rain kept semi {pts[0]}" + assert not lead.status, f"rain published semi {pts[0]}" + + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=28.0, radar_points=[(802, 28.0, 0.3, -0.4)]) + assert lead.radarTrackId == 802 + lead = scenario.step(1.1, vision_d_rel=28.0, radar_points=[semi_edge], + vision_prob=0.40, vision_v=-(v_ego + 18.8)) + assert not lead.radar + assert not lead.status + + +def test_left_turn_straight_ahead_sign_off_path_not_lead(): + """21:06–21:07: left turn. Ego-forward / left signs / oncoming semi off path. + + yRel-only is not enough — the model path has already turned left. + """ + path_x = list(LEFT_TURN_PATH_X) + path_y = list(LEFT_TURN_PATH_Y) + v_ego = 12.0 + d_rel = LEFT_TURN_X_M - RADAR_TO_CAMERA_M + ahead = (905, d_rel, 0.0, -v_ego) + left_sign = (872, d_rel, 2.0, -v_ego) + semi = (880, d_rel, 0.4, -(v_ego + 16.0)) + on_path = (11, d_rel, -4.0, -1.0) + for raining, pts, vision_v in ( + (False, [ahead], 0.0), + (True, [ahead], 0.0), + (True, [left_sign], 0.0), + (True, [semi], -(v_ego + 16.0)), + ): + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(raining) + lead = scenario.step(1.0, vision_d_rel=d_rel, radar_points=pts, + vision_prob=0.40, vision_v=vision_v, + path_x=path_x, path_y=path_y) + assert not lead.radar, f"rain={raining} latched left-turn off-path {pts[0][0]}" + assert not lead.status, f"rain={raining} followed left-turn off-path {pts[0][0]}" + + scenario = RadarScenario(v_ego=v_ego) + scenario.set_rain_hold(True) + lead = scenario.step(1.0, vision_d_rel=d_rel, radar_points=[on_path, ahead, semi], + vision_y=4.0, path_x=path_x, path_y=path_y) + assert lead.radar + assert lead.radarTrackId == 11 + + +def test_2108_gas_station_ahead_does_not_stop_in_the_road(): + """~21:08 CT: left turn, gas station / signs straight ahead → must not stop. + + Ego-forward radar (yRel≈0) while model path has already turned left. + Rain must not publish leadOne as dRel closes (28→9 mph class). + """ + path_x = list(ATLANTIC_LEFT_PATH_X) + path_y = list(ATLANTIC_LEFT_PATH_Y) + frames = ( + (12.5, 925, 40.0, 0.0), + (10.0, 932, 22.0, 0.15), + (4.1, 940, 9.0, -0.2), + ) + scenario = RadarScenario(v_ego=12.5) + scenario.set_rain_hold(True) + for i, (v_ego, tid, d_rel, y_rel) in enumerate(frames): + scenario.v_ego = v_ego + lead = scenario.step(1.0 + i * 0.1, vision_d_rel=d_rel, + radar_points=[(tid, d_rel, y_rel, -v_ego)], + vision_prob=0.04, path_x=path_x, path_y=path_y) + assert not lead.radar, f"21:08 tid {tid} latched as radar lead" + assert not lead.status, f"21:08 tid {tid} published — would stop in the road" + + +def test_path_collapse_blocks_new_wide_lead_keeps_centered(): + """08:57:58: collapsed lanes + absurd pathY must not start |yRel|~2.9. + + The kink still puts that right-side track on the local path, so the + ordinary half-width gate would accept it. A centered track on the + same broken path still associates. Healthy lane lines do not raise + the bar. An already-owned track is not dropped when the path later + collapses. + """ + d_rel = 22.0 - RADAR_TO_CAMERA + # Device y = −yRel. Right-side yRel −2.9 sits on the path at 22 m; + # 15 m and 30 m are absurd. + path_x = [0.0, 10.0, 15.0, 22.0, 30.0, 40.0] + path_y_right = [0.0, -2.0, -55.0, 2.9, -70.0, -40.0] + collapsed = [0.01, 0.02, 0.02, 0.01] + healthy = [0.9, 0.95, 0.96, 0.9] + + blocked = RadarScenario(v_ego=16.0) + lead = blocked.step( + 1.0, vision_d_rel=d_rel, radar_points=[(9, d_rel, -2.9, -1.0)], + vision_v=15.0, vision_y=2.9, vision_prob=0.95, + path_x=path_x, path_y=path_y_right, lane_probs=collapsed, + ) + assert not lead.status + + allowed = RadarScenario(v_ego=16.0) + lead = allowed.step( + 1.0, vision_d_rel=d_rel, radar_points=[(9, d_rel, -2.9, -1.0)], + vision_v=15.0, vision_y=2.9, vision_prob=0.95, + path_x=path_x, path_y=path_y_right, lane_probs=healthy, + ) + assert lead.radar + assert lead.radarTrackId == 9 + + path_y_center = [0.0, -1.0, -55.0, -0.3, -70.0, -40.0] + centered = RadarScenario(v_ego=16.0) + lead = centered.step( + 1.0, vision_d_rel=d_rel, radar_points=[(4, d_rel, 0.3, -1.0)], + vision_v=15.0, vision_y=-0.3, vision_prob=0.95, + path_x=path_x, path_y=path_y_center, lane_probs=collapsed, + ) + assert lead.radar + assert lead.radarTrackId == 4 + + owned = RadarScenario(v_ego=16.0) + straight_x = [0.0, 15.0, 30.0, 45.0] + straight_y = [0.0, 0.0, 0.0, 0.0] + lead = owned.step( + 1.0, vision_d_rel=30.0, radar_points=[(9, 30.0, 0.2, -1.0)], + vision_v=15.0, vision_y=-0.2, vision_prob=0.95, + path_x=straight_x, path_y=straight_y, lane_probs=healthy, + ) + assert lead.radar and lead.radarTrackId == 9 + lead = owned.step( + 1.1, vision_d_rel=d_rel, radar_points=[(9, d_rel, -2.9, -1.0)], + vision_v=15.0, vision_y=2.9, vision_prob=0.95, + path_x=path_x, path_y=path_y_right, lane_probs=collapsed, + ) + assert lead.radar + assert lead.radarTrackId == 9 diff --git a/selfdrive/controls/tests/test_rain_radar_hold.py b/selfdrive/controls/tests/test_rain_radar_hold.py new file mode 100644 index 00000000000000..094a8ab102e6d5 --- /dev/null +++ b/selfdrive/controls/tests/test_rain_radar_hold.py @@ -0,0 +1,659 @@ +"""Rain-sensing mode gate / radar-hold policy. No cereal — dry fusion stays in test_radard.""" +from types import SimpleNamespace + +from openpilot.selfdrive.controls.lib.radar_path_gate import ( + CURVE_OUTSIDE_PATH_X, + CURVE_OUTSIDE_PATH_Y, + CURVE_OUTSIDE_TWO_LANES_M, + CURVE_OUTSIDE_X_M, + ATLANTIC_LEFT_PATH_X, + ATLANTIC_LEFT_PATH_Y, + LEFT_TURN_PATH_X, + LEFT_TURN_PATH_Y, + LEFT_TURN_X_M, + ONCOMING_VLEAD_MS, + RADAR_TO_CAMERA_M, + ROUNDABOUT_EXIT_PATH_X, + ROUNDABOUT_EXIT_PATH_Y, + ROUNDABOUT_EXIT_X_M, + path_y_at_x, +) +from openpilot.selfdrive.controls.lib.rain_radar_hold import ( + NAP_RADAR_ENABLED, + RAIN_CUT_IN_GAP_M, + RAIN_FAR_HOLD_DREL_M, + RAIN_INLANE_YREL_M, + RELIABLE_ALERT_FRAMES, + RELIABLE_ENGAGE_GRACE_FRAMES, + RELIABLE_FAIL_FRAMES, + RELIABLE_MIN_VEGO_MS, + RELIABLE_OK_FRAMES, + RELIABLE_ONROAD_GRACE_FRAMES, + RELIABLE_TIMEOUT_ALERT_FRAMES, + RadarPreferGate, + RadarReliability, + RainRadarGate, + closest_inlane_radar, + pick_rain_radar_track, + radar_errors_unhealthy, + radar_hold_kinematics_ok, + rain_far_hold_ok, + rain_sensing_on, + wiper_is_auto, +) + + +class FakeParams: + def __init__(self, values=None): + self.values = dict(values or {}) + + def get(self, key, return_default=False): + return self.values.get(key) + + def get_bool(self, key): + return bool(self.values.get(key, False)) + + +def nap_wiper_status(*, rain=1, wipe=1, acq=1, score=5.03): + """Status line Auto Wipers writes. Mode gate must not require these fields.""" + return ( + f"nap wiper auto setting=3 rain={int(rain)} wipe={int(wipe)} " + f"acq={int(acq)} score={score:.2f} collar=1" + ) + + +def track(identifier: int, d_rel: float, y_rel: float = 0.0, v_rel: float = 0.0): + return SimpleNamespace(identifier=identifier, dRel=d_rel, yRel=y_rel, vRel=v_rel) + + +def test_auto_is_rain_sensing_mode_not_weather(): + """Speed==3 still means Auto. It is not the prefer gate anymore.""" + assert wiper_is_auto(3) + assert rain_sensing_on(3) + for speed in (0, 1, 2): + assert not wiper_is_auto(speed) + assert not rain_sensing_on(speed) + + +def test_prefer_without_auto_when_radar_enabled(): + """Binding: prefer is default. Do not require NAPWiperSpeed==3 / rain=1.""" + params = FakeParams({ + NAP_RADAR_ENABLED: True, + "NAPWiperSpeed": 0, + "NAPWiperRainStatus": nap_wiper_status(rain=0, wipe=0, acq=0, score=0.2), + }) + gate = RadarPreferGate(params=params) + assert gate.update() + assert not gate.fallback_alert + + +def test_prefer_without_auto_for_every_wiper_mode(): + """Off / Int / On / Auto all prefer when Radar Enabled is On.""" + wet = nap_wiper_status(rain=1, wipe=1, acq=1, score=9.0) + for speed in (0, 1, 2, 3): + params = FakeParams({ + NAP_RADAR_ENABLED: True, + "NAPWiperSpeed": speed, + "NAPWiperRainStatus": wet, + }) + assert RadarPreferGate(params=params).update(), f"wiper={speed} should prefer" + + +def test_radar_disabled_uses_stock_fusion(): + """Radar Enabled Off → stock fusion, even if Auto / wet status.""" + params = FakeParams({ + NAP_RADAR_ENABLED: False, + "NAPWiperSpeed": 3, + "NAPWiperRainStatus": nap_wiper_status(rain=1, wipe=1, acq=1, score=9.0), + }) + gate = RadarPreferGate(params=params) + assert not gate.update() + assert not gate.fallback_alert + + +def test_unhealthy_radar_falls_back_and_alerts(): + """Enabled but unreliable → stock fusion + user-visible fallback.""" + params = FakeParams({NAP_RADAR_ENABLED: True, "NAPWiperSpeed": 0}) + gate = RadarPreferGate(params=params) + gate.set_reliable(False) + assert not gate.update() + assert gate.fallback_alert + + +def test_soft_unhealthy_can_drop_prefer_without_hud(): + """Soft dropout may leave prefer without flashing Radar Unreliable.""" + params = FakeParams({NAP_RADAR_ENABLED: True}) + gate = RadarPreferGate(params=params) + gate.set_reliable(False, alert=False) + assert not gate.update() + assert not gate.fallback_alert + + +def test_rain_gate_override_skips_params(): + gate = RainRadarGate(params=FakeParams({NAP_RADAR_ENABLED: False})) + gate.set_override(True) + assert gate.update() + gate.set_override(False) + assert not gate.update() + assert not gate.fallback_alert + + +def test_radar_errors_unhealthy_respects_ignore_hw_fail(): + assert radar_errors_unhealthy({"radarFault": True}) + assert not radar_errors_unhealthy({"radarFault": True}, ignore_hw_fail=True) + assert radar_errors_unhealthy({"canError": True}, ignore_hw_fail=True) + assert radar_errors_unhealthy({"radarUnavailableTemporary": True}) + + +def test_reliability_trips_on_fault_timeout_dropout_and_erratic(): + rel = RadarReliability() + assert rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0) + + rel = RadarReliability() + assert not rel.update(errors={"radarFault": True}, v_ego=16.0) + assert rel.reason == "fault" + assert rel.should_alert + assert rel.log_reason == "fault" + + rel = RadarReliability() + assert not rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0, timed_out=True) + assert rel.reason == "timeout" + assert not rel.should_alert # timeout HUD needs a sustained confirm + + rel = RadarReliability() + assert rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0) + assert rel.update(tracks={}, v_ego=16.0) # first empty frame is not a trip + assert rel.log_reason == "dropout" + for _ in range(RELIABLE_FAIL_FRAMES - 1): + rel.update(tracks={}, v_ego=16.0) + assert not rel.healthy + assert rel.reason == "dropout" + assert not rel.should_alert # soft + not engaged + + rel = RadarReliability() + t = track(7, 40.0, y_rel=0.2) + assert rel.update(tracks={7: t}, v_ego=16.0) + jumpy = track(7, 40.0, y_rel=5.0) + for _ in range(RELIABLE_FAIL_FRAMES): + rel.update(tracks={7: jumpy}, v_ego=16.0) + jumpy = track(7, 40.0, y_rel=jumpy.yRel + 5.0) + assert not rel.healthy + assert rel.reason == "erratic" + + # First clean frame after a jump is still a ΔyRel; then hold still. + stable = track(7, 40.0, y_rel=0.2) + rel.update(tracks={7: stable}, v_ego=16.0) + for _ in range(RELIABLE_OK_FRAMES): + rel.update(tracks={7: stable}, v_ego=16.0) + assert rel.healthy + + +def test_brief_empty_table_at_crawl_speed_does_not_alert(): + """e3 gravel: vEgo 5.35, empty table, radarErrors all false — no HUD.""" + rel = RadarReliability() + assert rel.update(tracks={1: track(1, 20.0)}, v_ego=5.35) + for _ in range(RELIABLE_FAIL_FRAMES + 4): + ok = rel.update(tracks={}, v_ego=5.35, engaged=False) + assert ok + assert not rel.should_alert + assert rel.healthy + assert rel.log_reason == "dropout" + assert RELIABLE_MIN_VEGO_MS > 5.35 + + +def test_real_fault_still_alerts_without_engage(): + """canError / radarFault / unavailable still fall back + alert.""" + for errors, _name in ( + ({"canError": True}, "canError"), + ({"radarFault": True}, "radarFault"), + ({"radarUnavailableTemporary": True}, "unavailable"), + ): + rel = RadarReliability() + assert not rel.update(errors=errors, v_ego=5.35, engaged=False) + assert not rel.healthy + assert rel.reason == "fault" + assert rel.should_alert + assert rel.log_reason == "fault" + + +def test_reliability_recover_hysteresis(): + """One clean frame after a trip is not enough; OK_FRAMES recovers.""" + rel = RadarReliability() + assert not rel.update(errors={"radarFault": True}, v_ego=16.0) + assert not rel.healthy + assert rel.should_alert + + clean = {1: track(1, 40.0)} + rel.update(tracks=clean, v_ego=16.0) + assert not rel.healthy # one clean frame is not enough + for _ in range(RELIABLE_OK_FRAMES - 1): + rel.update(tracks=clean, v_ego=16.0) + assert rel.healthy + assert not rel.should_alert + assert rel.log_reason == "" + + +def test_soft_dropout_never_alerts_even_after_engage_confirm(): + """Pavement empty-table (signs / open road) trips prefer; no HUD.""" + rel = RadarReliability() + for _ in range(RELIABLE_ONROAD_GRACE_FRAMES): + rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0, engaged=False) + for _ in range(RELIABLE_FAIL_FRAMES): + rel.update(tracks={}, v_ego=16.0, engaged=False) + assert not rel.healthy + assert not rel.should_alert + + rel.update(tracks={}, v_ego=16.0, engaged=True) + assert not rel.should_alert + for _ in range(RELIABLE_ENGAGE_GRACE_FRAMES): + rel.update(tracks={}, v_ego=16.0, engaged=True) + for _ in range(RELIABLE_ALERT_FRAMES): + rel.update(tracks={}, v_ego=16.0, engaged=True) + assert not rel.healthy + assert not rel.should_alert + assert rel.log_reason == "dropout" + + +def test_erratic_clutter_never_alerts(): + """Signs / opposing kinematic streaks trip prefer silently.""" + rel = RadarReliability() + for _ in range(RELIABLE_ONROAD_GRACE_FRAMES): + rel.update(tracks={7: track(7, 40.0, y_rel=0.2)}, v_ego=16.0, engaged=True) + jumpy = track(7, 40.0, y_rel=5.0) + for _ in range(RELIABLE_FAIL_FRAMES + RELIABLE_ALERT_FRAMES): + rel.update(tracks={7: jumpy}, v_ego=16.0, engaged=True) + jumpy = track(7, 40.0, y_rel=jumpy.yRel + 5.0) + assert not rel.healthy + assert rel.reason == "erratic" + assert not rel.should_alert + assert rel.log_reason == "erratic" + + +def test_timeout_never_alerts(): + """Stream timeout trips prefer immediately; HUD stays quiet (41-blip dig).""" + rel = RadarReliability() + for _ in range(RELIABLE_ONROAD_GRACE_FRAMES): + rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0, engaged=False) + for _ in range(RELIABLE_ENGAGE_GRACE_FRAMES): + rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0, engaged=True) + assert rel.healthy + assert not rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0, timed_out=True, + engaged=True) + assert rel.reason == "timeout" + assert not rel.should_alert + for _ in range(RELIABLE_TIMEOUT_ALERT_FRAMES + RELIABLE_ALERT_FRAMES): + rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0, timed_out=True, engaged=True) + assert not rel.healthy + assert not rel.should_alert + assert rel.log_reason == "timeout" + + +def test_path_associated_lead_suppresses_non_fault_alert(): + """Quiet with a real lead: no HUD for leftover non-fault reasons.""" + rel = RadarReliability() + for _ in range(RELIABLE_ONROAD_GRACE_FRAMES): + rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0, engaged=True) + rel.set_path_lead(True) + for _ in range(RELIABLE_ENGAGE_GRACE_FRAMES + RELIABLE_TIMEOUT_ALERT_FRAMES + 4): + rel.update(tracks={1: track(1, 40.0)}, v_ego=16.0, timed_out=True, engaged=True) + assert not rel.healthy + assert rel.reason == "timeout" + assert not rel.should_alert + rel.set_path_lead(False) + assert not rel.should_alert + + +def test_fault_still_alerts_with_path_associated_lead(): + """canError / radarFault keep the HUD even when a lead is still published.""" + rel = RadarReliability() + rel.set_path_lead(True) + assert not rel.update(errors={"canError": True}, v_ego=16.0, engaged=True) + assert rel.reason == "fault" + assert rel.should_alert + + +def test_pick_holds_incumbent_through_vision_mismatch(): + tracks = {806: track(806, 93.8), 900: track(900, 90.0, y_rel=3.2)} + associated = None # vision jumped −32 m; association rejected + chosen = pick_rain_radar_track(associated, tracks, incumbent_id=806) + assert chosen is tracks[806] + + +def test_pick_does_not_fov_cut_in_without_association(): + """Closer in-lane radar without a path association must not steal the hold.""" + tracks = {806: track(806, 93.8), 12: track(12, 93.8 - RAIN_CUT_IN_GAP_M)} + chosen = pick_rain_radar_track(None, tracks, incumbent_id=806) + assert chosen is tracks[806] + + +def test_pick_switches_to_associated_path_cut_in(): + tracks = {806: track(806, 93.8), 12: track(12, 93.8 - RAIN_CUT_IN_GAP_M)} + chosen = pick_rain_radar_track(tracks[12], tracks, incumbent_id=806) + assert chosen is tracks[12] + + +def test_pick_does_not_acquire_unassociated_inlane_radar(): + """Rain-hold is not a wide-FOV prefer. No association → no new latch.""" + tracks = {806: track(806, 93.8)} + chosen = pick_rain_radar_track(None, tracks, incumbent_id=None) + assert chosen is None + assert closest_inlane_radar(tracks) is tracks[806] + + +def test_pick_drops_incumbent_that_left_the_path(): + tracks = {806: track(806, 93.8, y_rel=6.0)} + assert not radar_hold_kinematics_ok(tracks[806]) + chosen = pick_rain_radar_track(None, tracks, incumbent_id=806) + assert chosen is None + + +def test_e1_hold_drops_incumbent_at_yrel_2_8_stationary(): + """Dig: drop incumbent at yRel=2.8 STAT (old 4.0 window held it).""" + v_ego = 16.0 # ~36 mph, ep B band + t = track(318, 40.8, y_rel=2.8, v_rel=-v_ego) + assert not radar_hold_kinematics_ok(t, v_ego=v_ego) + assert pick_rain_radar_track(None, {318: t}, 318, v_ego) is None + + +def test_e1_does_not_pick_opposing_vlead_minus_8(): + """Dig: must not pick opposing vLead=−8.""" + v_ego = 16.0 + t = track(101, 50.0, y_rel=1.2, v_rel=-(v_ego + 8.0)) # vLead = −8 + assert t.vRel + v_ego == -8.0 + assert not radar_hold_kinematics_ok(t, v_ego=v_ego) + assert pick_rain_radar_track(t, {101: t}, None, v_ego) is None + assert pick_rain_radar_track(None, {101: t}, 101, v_ego) is None + + +def test_e1_ep_b_does_not_acquire_low_prob_stationary_at_yrel_0_86(): + """20:49:10 track 321: dRel=99.3, yRel=+0.86, vLead≈0, mp=0.007.""" + v_ego = 16.05 + t = track(321, 99.3, y_rel=0.86, v_rel=-v_ego) + assert pick_rain_radar_track(None, {321: t}, None, v_ego) is None + + +def test_pick_drops_left_roadside_sign_old_yrel_window(): + """Old rain in-lane was 2.5 m / incumbent 4.0 m — a left sign at 3.2 m held.""" + tracks = {44: track(44, 48.0, y_rel=3.2, v_rel=-20.0)} + assert not radar_hold_kinematics_ok(tracks[44], v_ego=20.0) + chosen = pick_rain_radar_track(None, tracks, incumbent_id=44, v_ego=20.0) + assert chosen is None + chosen = pick_rain_radar_track(tracks[44], tracks, incumbent_id=None, v_ego=20.0) + assert chosen is None + + +def test_pick_rejects_oncoming_opposing_lane(): + v_ego = 20.0 + tracks = {9: track(9, 55.0, y_rel=-1.6, v_rel=-(v_ego + 18.0))} + assert not radar_hold_kinematics_ok(tracks[9], v_ego=v_ego) + chosen = pick_rain_radar_track(None, tracks, incumbent_id=9, v_ego=v_ego) + assert chosen is None + chosen = pick_rain_radar_track(tracks[9], tracks, incumbent_id=None, v_ego=v_ego) + assert chosen is None + + +def test_pick_still_holds_in_path_radar_through_mismatch(): + tracks = {806: track(806, 93.8, y_rel=0.4, v_rel=-1.0)} + chosen = pick_rain_radar_track(None, tracks, incumbent_id=806, v_ego=20.0) + assert chosen is tracks[806] + + +def test_pick_does_not_let_rain_override_path_or_oncoming_rejects(): + v_ego = 20.0 + sign = track(3, 40.0, y_rel=3.5, v_rel=-v_ego) + oncoming = track(4, 42.0, y_rel=-1.4, v_rel=-(v_ego + 16.0)) + good = track(5, 45.0, y_rel=0.2, v_rel=-0.5) + assert pick_rain_radar_track(sign, {3: sign}, None, v_ego) is None + assert pick_rain_radar_track(oncoming, {4: oncoming}, None, v_ego) is None + assert pick_rain_radar_track(None, {5: good}, None, v_ego) is None + assert pick_rain_radar_track(good, {5: good}, None, v_ego) is good + + +def test_pick_does_not_latch_roundabout_entrant_off_exit_path(): + """~20:54 CT: rain must not hold the entering vehicle on a right-exit path.""" + v_ego = 12.0 + entrant = track(22, ROUNDABOUT_EXIT_X_M - RADAR_TO_CAMERA_M, y_rel=0.0, v_rel=-2.0) + path = (ROUNDABOUT_EXIT_PATH_X, ROUNDABOUT_EXIT_PATH_Y) + assert not radar_hold_kinematics_ok(entrant, v_ego=v_ego, path_x=path[0], path_y=path[1]) + assert pick_rain_radar_track(entrant, {22: entrant}, None, v_ego, path[0], path[1]) is None + assert pick_rain_radar_track(None, {22: entrant}, 22, v_ego, path[0], path[1]) is None + + +def test_tip_still_has_path_gate_2_0_yrel_and_oncoming_reject(): + """Justin flash check: path gate + 2.5→2.0 yRel + vLead < 0 reject.""" + assert RAIN_INLANE_YREL_M == 2.0 + assert ONCOMING_VLEAD_MS < 0.0 + + +def test_ep2059_inlane_gate_is_2_0_not_2_5(): + """Justin: RAIN_INLANE_YREL_M 2.5 → 2.0. Rejects 2.23 and 2.48 latches.""" + assert RAIN_INLANE_YREL_M == 2.0 + v_ego = 20.0 + assert not radar_hold_kinematics_ok(track(771, 45.0, 2.23, -(v_ego + 22.0)), + RAIN_INLANE_YREL_M, v_ego) + assert not radar_hold_kinematics_ok(track(802, 40.0, 2.48, -(v_ego + 18.7)), + RAIN_INLANE_YREL_M, v_ego) + + +def test_ep2059_near_edge_oncoming_not_latched(): + """20:59:33 track 771 / 21:00:12 track 802 — inside old 2.5 m, oncoming.""" + v_ego = 20.0 # ~45 mph arterial + # 771: yRel +2.23→+3.98, vLead −22 m/s (−49 mph) + t771 = track(771, 45.0, y_rel=2.23, v_rel=-(v_ego + 22.0)) + t771_walk = track(771, 20.0, y_rel=3.98, v_rel=-(v_ego + 22.0)) + # 802: yRel +2.23→+2.48 (0.02 m INSIDE old 2.5), vLead −18.7 m/s + t802 = track(802, 40.0, y_rel=2.23, v_rel=-(v_ego + 18.7)) + t802_edge = track(802, 28.0, y_rel=2.48, v_rel=-(v_ego + 18.7)) + for t in (t771, t771_walk, t802, t802_edge): + assert not radar_hold_kinematics_ok(t, v_ego=v_ego) + assert pick_rain_radar_track(t, {t.identifier: t}, None, v_ego) is None + assert pick_rain_radar_track(None, {t.identifier: t}, t.identifier, v_ego) is None + + +def test_straight_opposing_passers_stay_ignored(): + """~20:58 CT: several opposing-lane cars pass toward ego — no regen. + + They never associate as leadOne. Path-gating rain-hold must not FOV-pick + them or invent a new oncoming-brake. Stay ignored, same as stock. + """ + v_ego = 20.0 + passers = [ + track(1, 80.0, y_rel=3.1, v_rel=-(v_ego + 22.0)), + track(2, 50.0, y_rel=2.9, v_rel=-(v_ego + 18.0)), + track(3, 28.0, y_rel=3.4, v_rel=-(v_ego + 20.0)), + ] + tracks = {t.identifier: t for t in passers} + assert pick_rain_radar_track(None, tracks, None, v_ego) is None + for t in passers: + assert pick_rain_radar_track(None, tracks, t.identifier, v_ego) is None + assert pick_rain_radar_track(t, tracks, None, v_ego) is None + + +def test_straight_opposing_does_not_steal_in_path_lead(): + """20:58-class passers must not displace a real path-associated lead.""" + v_ego = 20.0 + lead = track(11, 40.0, y_rel=0.3, v_rel=-0.4) + passer = track(2, 50.0, y_rel=2.9, v_rel=-(v_ego + 18.0)) + tracks = {11: lead, 2: passer} + assert pick_rain_radar_track(lead, tracks, 11, v_ego) is lead + assert pick_rain_radar_track(None, tracks, 11, v_ego) is lead + + +def test_ep2059_mid_lane_opposing_never_acquired(): + """21:02 / 21:03: opposing outside 2.5 m — leadOne stayed None. Keep that.""" + v_ego = 20.0 + mid = track(900, 50.0, y_rel=3.2, v_rel=-(v_ego + 20.0)) + assert pick_rain_radar_track(None, {900: mid}, None, v_ego) is None + assert pick_rain_radar_track(None, {900: mid}, 900, v_ego) is None + assert pick_rain_radar_track(mid, {900: mid}, None, v_ego) is None + + +def test_2102_farther_over_semi_stays_clean(): + """Justin 21:02: 4–5 opposing including a semi farther over — no regen. + + Near-edge 2.23 m (20:59/21:00) is outside the 2.0 m perimeter. + Farther-over ~3.0–3.5 m must stay ignored; do not nuke all opposing. + """ + v_ego = 20.0 + near_edge = track(802, 40.0, y_rel=2.23, v_rel=-(v_ego + 18.8)) + pack = [ + track(1, 70.0, y_rel=3.0, v_rel=-(v_ego + 20.0)), + track(2, 55.0, y_rel=3.2, v_rel=-(v_ego + 18.0)), + track(3, 40.0, y_rel=3.5, v_rel=-(v_ego + 22.0)), # semi farther over + track(4, 28.0, y_rel=2.9, v_rel=-(v_ego + 19.0)), + track(5, 20.0, y_rel=3.3, v_rel=-(v_ego + 21.0)), + ] + tracks = {t.identifier: t for t in pack} + assert not radar_hold_kinematics_ok(near_edge, v_ego=v_ego) + assert pick_rain_radar_track(None, tracks, None, v_ego) is None + for t in pack: + assert pick_rain_radar_track(None, tracks, t.identifier, v_ego) is None + assert pick_rain_radar_track(t, {t.identifier: t}, None, v_ego) is None + lead = track(11, 38.0, y_rel=0.3, v_rel=-0.4) + tracks[11] = lead + assert pick_rain_radar_track(lead, tracks, 11, v_ego) is lead + + +def test_2103_mid_lane_oncoming_truck_stays_clean(): + """~21:03 CT: oncoming truck in the middle of the opposing lane — no regen. + + Pass with 21:02. Fail cases stay near-edge / off-path (20:59–21:00). + """ + v_ego = 20.0 + truck = track(910, 45.0, y_rel=3.7, v_rel=-(v_ego + 22.0)) + assert not radar_hold_kinematics_ok(truck, v_ego=v_ego) + assert pick_rain_radar_track(None, {910: truck}, None, v_ego) is None + assert pick_rain_radar_track(None, {910: truck}, 910, v_ego) is None + assert pick_rain_radar_track(truck, {910: truck}, None, v_ego) is None + lead = track(11, 40.0, y_rel=0.2, v_rel=-0.4) + assert pick_rain_radar_track(lead, {11: lead, 910: truck}, 11, v_ego) is lead + + +def test_ep2059_far_stat_phantom_not_acquired(): + """20:59:40 Dip 2: tids 782/784/786, vLead≈0, dRel 84–123 m, mp≤0.014.""" + v_ego = 20.0 + for tid, d_rel, y_rel in ((782, 123.0, 0.86), (784, 100.0, 1.4), (786, 84.0, 2.11)): + far = track(tid, d_rel, y_rel=y_rel, v_rel=-v_ego) + assert pick_rain_radar_track(None, {tid: far}, None, v_ego, vision_prob=0.01) is None + assert pick_rain_radar_track(None, {tid: far}, tid, v_ego, vision_prob=0.01) is None + + +def test_far_low_prob_incumbent_not_held_for_regen(): + """20:59 second slam / 20:49:10 track 321: far + mp≪0.15 must not stay leadOne.""" + v_ego = 16.0 + phantom = track(321, 99.3, y_rel=0.86, v_rel=-v_ego) + assert phantom.dRel > RAIN_FAR_HOLD_DREL_M + assert not rain_far_hold_ok(phantom, None, vision_prob=0.007) + assert pick_rain_radar_track(None, {321: phantom}, 321, v_ego, vision_prob=0.007) is None + + +def test_ep2106_off_path_stat_signs_not_latched(): + """EP_2106: path gate rejects furniture. Semi never leadOne. STAT is not why.""" + v_ego = 20.0 + left = (LEFT_TURN_PATH_X, LEFT_TURN_PATH_Y) + atlantic = (ATLANTIC_LEFT_PATH_X, ATLANTIC_LEFT_PATH_Y) + cases = ( + (872, 109.0, 1.98, left), # LEFT sign + (905, 107.0, 1.23, left), # "ahead" then sweeps + (906, 100.0, 2.11, left), + (925, 112.0, -0.15, atlantic), # gas-station ego-forward + (940, 82.0, 0.73, atlantic), # near stop; yRel inside 2.0 without path + ) + for tid, d_rel, y_rel, path in cases: + t = track(tid, d_rel, y_rel=y_rel, v_rel=-v_ego) + assert not radar_hold_kinematics_ok(t, v_ego=v_ego, path_x=path[0], path_y=path[1]) + assert pick_rain_radar_track(None, {tid: t}, tid, v_ego, path[0], path[1], + vision_prob=0.01) is None + assert pick_rain_radar_track(None, {tid: t}, None, v_ego, path[0], path[1], + vision_prob=0.01) is None + + +def test_on_path_stationary_kept_associated_and_incumbent(): + """Binding: on path + stationary → KEEP. Not a vLead≈0 reject.""" + v_ego = 12.0 + stopped = track(11, 28.0, y_rel=0.2, v_rel=-v_ego) + assert radar_hold_kinematics_ok(stopped, v_ego=v_ego) + assert pick_rain_radar_track(stopped, {11: stopped}, None, v_ego, + vision_prob=0.80) is stopped + # Vision flap / low mp: path-valid incumbent still held. + assert pick_rain_radar_track(None, {11: stopped}, 11, v_ego, + vision_prob=0.02) is stopped + + +def test_far_associated_rain_lead_still_held(): + """Original #201: 93.8 m path lead + confident vision flap still holds.""" + t = track(806, 93.8, y_rel=0.0, v_rel=0.0) + assert rain_far_hold_ok(t, t, vision_prob=0.978) + assert pick_rain_radar_track(None, {806: t}, 806, vision_prob=0.978) is t + # Live association at 100 m (on-path STAT / distant car) is not "absurd". + far = track(11, 100.0, y_rel=0.2, v_rel=-0.3) + assert pick_rain_radar_track(far, {11: far}, None, vision_prob=0.70) is far + + +def test_oncoming_rejected_even_when_yrel_is_inside_gate(): + """Size / near-center radar return must not override vLead oncoming reject.""" + v_ego = 20.0 + semi = track(802, 35.0, y_rel=1.0, v_rel=-(v_ego + 18.8)) + assert not radar_hold_kinematics_ok(semi, v_ego=v_ego) + assert pick_rain_radar_track(semi, {802: semi}, None, v_ego) is None + + +def test_2100_close_semi_not_kept_as_rain_incumbent(): + """~21:00 CT: large/close opposing semi. Rain must drop a live incumbent.""" + v_ego = 20.0 + close = track(802, 28.0, y_rel=2.23, v_rel=-(v_ego + 18.8)) + tighter = track(803, 25.0, y_rel=1.0, v_rel=-(v_ego + 18.8)) + for t in (close, tighter): + assert pick_rain_radar_track(None, {t.identifier: t}, t.identifier, v_ego) is None + assert pick_rain_radar_track(t, {t.identifier: t}, t.identifier, v_ego) is None + + +def test_associated_lead_at_1_7m_still_held(): + """Don't over-tighten path-valid associations (1.5 would have dropped this).""" + v_ego = 20.0 + t = track(11, 40.0, y_rel=1.7, v_rel=-0.5) + assert radar_hold_kinematics_ok(t, v_ego=v_ego) + assert pick_rain_radar_track(t, {11: t}, None, v_ego) is t + + +def test_2108_gas_station_not_held_while_closing(): + """21:08: rain must not keep ego-forward gas-station furniture as dRel closes.""" + v_ego = 12.5 + path = (ATLANTIC_LEFT_PATH_X, ATLANTIC_LEFT_PATH_Y) + for tid, d_rel, y_rel in ((925, 40.0, 0.0), (932, 22.0, 0.15), (940, 9.0, -0.2)): + t = track(tid, d_rel, y_rel=y_rel, v_rel=-v_ego) + assert not radar_hold_kinematics_ok(t, v_ego=v_ego, path_x=path[0], path_y=path[1]) + assert pick_rain_radar_track(None, {tid: t}, tid, v_ego, path[0], path[1]) is None + assert pick_rain_radar_track(t, {tid: t}, None, v_ego, path[0], path[1]) is None + + +def test_left_turn_rain_does_not_latch_ego_forward_or_oncoming(): + """21:06–21:07: rain must not hold yRel≈0 furniture or an off-path semi.""" + v_ego = 12.0 + d_rel = LEFT_TURN_X_M - RADAR_TO_CAMERA_M + path = (LEFT_TURN_PATH_X, LEFT_TURN_PATH_Y) + ahead = track(905, d_rel, y_rel=0.0, v_rel=-v_ego) + left_sign = track(872, d_rel, y_rel=2.0, v_rel=-v_ego) + semi = track(880, d_rel, y_rel=0.4, v_rel=-(v_ego + 16.0)) + for t in (ahead, left_sign, semi): + assert not radar_hold_kinematics_ok(t, v_ego=v_ego, path_x=path[0], path_y=path[1]) + assert pick_rain_radar_track(t, {t.identifier: t}, None, v_ego, path[0], path[1]) is None + assert pick_rain_radar_track(None, {t.identifier: t}, t.identifier, v_ego, + path[0], path[1]) is None + + +def test_pick_does_not_latch_outside_curve_sign(): + """~20:55 CT: rain must not hold a two-lane-outside static / bogus-oncoming sign.""" + v_ego = 16.0 + path_at = path_y_at_x(CURVE_OUTSIDE_PATH_X, CURVE_OUTSIDE_PATH_Y, CURVE_OUTSIDE_X_M) + y_rel = -(path_at - CURVE_OUTSIDE_TWO_LANES_M) + d_rel = CURVE_OUTSIDE_X_M - RADAR_TO_CAMERA_M + path = (CURVE_OUTSIDE_PATH_X, CURVE_OUTSIDE_PATH_Y) + stationary = track(33, d_rel, y_rel=y_rel, v_rel=-v_ego) + bogus = track(34, d_rel, y_rel=y_rel, v_rel=-(v_ego + 18.0)) + for phantom in (stationary, bogus): + assert not radar_hold_kinematics_ok(phantom, v_ego=v_ego, path_x=path[0], path_y=path[1]) + assert pick_rain_radar_track(phantom, {phantom.identifier: phantom}, None, + v_ego, path[0], path[1]) is None + assert pick_rain_radar_track(None, {phantom.identifier: phantom}, phantom.identifier, + v_ego, path[0], path[1]) is None diff --git a/selfdrive/controls/tests/test_roundabout_planner.py b/selfdrive/controls/tests/test_roundabout_planner.py new file mode 100644 index 00000000000000..d36fb89f944634 --- /dev/null +++ b/selfdrive/controls/tests/test_roundabout_planner.py @@ -0,0 +1,124 @@ +"""Planner hook: RB funnel eases aTarget; a sharp corner / no flag does not. + +Full LongitudinalPlanner loop needs cereal/scons. The planner calls +`apply_roundabout_plan` on the liveMapDataNAP hint — that is the aTarget +path under test here (Willmar: aTarget stayed +0.4 / later only −0.55). +""" +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.constants import LOOKAHEAD_EARLY, LOOKAHEAD_NORMAL +from openpilot.selfdrive.mapd.roundabout import ( + RB_A_FLOOR_MS2, + RB_OUTER_OFFSET_M, + RB_V_MAX_MS, + RoundaboutHint, + apply_roundabout_plan, + rb_profile_v_ms, + roundabout_outer_curvature_bias, + roundabout_outer_path_offset_m, +) + + +def test_funnel_triggers_speed_ease(): + v_ego = 49.0 * CV.MPH_TO_MS + v_cruise = 50.0 * CV.MPH_TO_MS + hint = RoundaboutHint( + approaching=True, distance_m=90.0, speed_limit_ms=20.0 * CV.MPH_TO_MS, + ) + v_c, v_hud, a_tgt, rb_v = apply_roundabout_plan( + v_ego, v_cruise, v_cruise, 0.4, hint, LOOKAHEAD_NORMAL, + ) + assert rb_v is not None + assert a_tgt <= RB_A_FLOOR_MS2, a_tgt + assert v_c < v_cruise + assert v_hud < v_cruise + assert rb_v <= RB_V_MAX_MS + 8.0 + + +def test_sharp_corner_without_flag_does_not_ease(): + v_ego = 49.0 * CV.MPH_TO_MS + v_cruise = 50.0 * CV.MPH_TO_MS + v_c, v_hud, a_tgt, rb_v = apply_roundabout_plan( + v_ego, v_cruise, v_cruise, 0.4, None, LOOKAHEAD_NORMAL, + ) + assert rb_v is None + assert a_tgt == 0.4 + assert v_c == v_cruise + assert v_hud == v_cruise + + +def test_on_roundabout_holds_soft_target(): + v_ego = 49.0 * CV.MPH_TO_MS + v_cruise = 50.0 * CV.MPH_TO_MS + hint = RoundaboutHint(on_roundabout=True, speed_limit_ms=20.0 * CV.MPH_TO_MS) + v_c, _v_hud, a_tgt, rb_v = apply_roundabout_plan( + v_ego, v_cruise, v_cruise, 0.4, hint, LOOKAHEAD_NORMAL, + ) + assert rb_v is not None + assert abs(rb_v - 20.0 * CV.MPH_TO_MS) < 1e-6 + assert a_tgt <= RB_A_FLOOR_MS2, a_tgt + assert v_c <= rb_v + + +def test_forty_five_mph_funnel_plans_at_least_one_g_tenth(): + """(a) 40–45 mph in funnel: planned a ≤ −1.0 until near ring speed.""" + v_cruise = 50.0 * CV.MPH_TO_MS + for v_mph, dist in ((40.0, 90.0), (45.0, 86.0), (45.0, 160.0)): + hint = RoundaboutHint( + approaching=True, distance_m=dist, speed_limit_ms=20.0 * CV.MPH_TO_MS, + ) + _vc, _vh, a_tgt, rb_v = apply_roundabout_plan( + v_mph * CV.MPH_TO_MS, v_cruise, v_cruise, 0.4, hint, LOOKAHEAD_EARLY, + ) + assert rb_v is not None + assert a_tgt <= RB_A_FLOOR_MS2, (v_mph, dist, a_tgt) + + +def test_no_plus_a_while_approaching_roundabout(): + """(b) EP0: never allow +a rebound after lead clears in the funnel.""" + hint = RoundaboutHint( + approaching=True, distance_m=128.0, speed_limit_ms=20.0 * CV.MPH_TO_MS, + ) + _vc, _vh, a_tgt, rb_v = apply_roundabout_plan( + 37.0 * CV.MPH_TO_MS, 50.0 * CV.MPH_TO_MS, 50.0 * CV.MPH_TO_MS, 0.399, hint, + ) + assert rb_v is not None + assert a_tgt <= 0.0 + + +def test_outer_bias_counters_inside_cut(): + """(c) RHT outer is right (−y); magnitude counters EP1 ~3 m inside cut.""" + rht = roundabout_outer_path_offset_m( + on_roundabout=True, is_rhd=False, + ) + lhd = roundabout_outer_path_offset_m( + on_roundabout=True, is_rhd=True, + ) + assert rht < 0.0 and lhd > 0.0 + assert abs(rht) >= 2.8 + assert abs(abs(rht) - RB_OUTER_OFFSET_M) < 1e-6 + entry = roundabout_outer_path_offset_m( + on_roundabout=False, approaching=True, distance_m=40.0, is_rhd=False, + ) + assert abs(entry - rht) < 1e-6 + kappa = roundabout_outer_curvature_bias(rht) + assert kappa < 0.0 + assert abs(kappa) >= 0.015 + + +def test_long_enable_in_funnel_applies_ease_immediately(): + """(d) Long enable mid-funnel: full RB ease on this frame, not +0.4.""" + hint = RoundaboutHint( + approaching=True, distance_m=86.0, speed_limit_ms=20.0 * CV.MPH_TO_MS, + ) + v45 = 45.0 * CV.MPH_TO_MS + v_cruise = 50.0 * CV.MPH_TO_MS + v_c, v_hud, a_tgt, rb_v = apply_roundabout_plan( + v45, v_cruise, v_cruise, 0.40, hint, LOOKAHEAD_EARLY, + ) + assert rb_v is not None + # Oct 11: MAX follows the 0.7 m/s² profile (no step); the late hint keeps the Willmar −a floor. + assert abs(rb_v - rb_profile_v_ms(86.0, 20.0 * CV.MPH_TO_MS)) < 1e-6 + assert rb_v < v45 + assert v_c <= rb_v + assert v_hud <= rb_v + assert a_tgt <= RB_A_FLOOR_MS2 diff --git a/selfdrive/controls/tests/test_sight_cap_planner.py b/selfdrive/controls/tests/test_sight_cap_planner.py new file mode 100644 index 00000000000000..c4a489cdce83c0 --- /dev/null +++ b/selfdrive/controls/tests/test_sight_cap_planner.py @@ -0,0 +1,59 @@ +"""Sight-distance cap wiring in the longitudinal planner: shadow only, never the command.""" +import json + +import pytest + +from openpilot.selfdrive.controls.lib import longitudinal_planner as lp +from openpilot.selfdrive.controls.tests.test_curve_preview import _set_model_path +from openpilot.selfdrive.controls.tests.test_unified_lead_planner import _own_lead, _planner + +DT = 0.05 +BEND = (120.0, 60.0, 1.0 / 45.0) + + +def _drive(mode, v, n, lead=None, shrink_at=None, hook=None): + planner, inputs, params = _planner(v, accel=0.4) + params.sight_cap = mode + if lead is not None: + _own_lead(inputs, *lead) + s = 0.0 + out = [] + for k in range(n): + _set_model_path(inputs["modelV2"], v, s, BEND) + pos = inputs["modelV2"].position + n_pts = len(pos.x) + if shrink_at is not None and k >= shrink_at: + pos.yStd = [min(6.0, 0.4 * i) for i in range(n_pts)] + else: + pos.yStd = [0.02 * i for i in range(n_pts)] + if hook is not None: + hook(k, planner, inputs) + planner.update(inputs) + out.append(float(planner.output_a_target)) + s += v * DT + return planner, out + + +@pytest.mark.parametrize("lead", [None, (45.0, 14.0)]) +def test_shadow_never_changes_the_command(lead): + _, off = _drive(0, 18.0, 400, lead=lead, shrink_at=300) + p_on, on = _drive(1, 18.0, 400, lead=lead, shrink_at=300) + assert off == on + assert not p_on._sc_faulted + + +def test_shadow_computes_sight_and_logs_without_capnp_fields(monkeypatch): + lines = [] + monkeypatch.setattr(lp.cloudlog, "error", lambda msg, *a, **k: lines.append(msg)) + planner, _ = _drive(1, 18.0, 400, shrink_at=300) + assert not planner._sc_faulted + assert planner._sight_cap.sight is not None + for ln in [x for x in lines if isinstance(x, str) and x.startswith("sightcap ")]: + rec = json.loads(ln[len("sightcap "):]) + for key in ("lead", "pitch", "crest", "night", "llp", "bl", "cn", "sd", "vc", "cmb"): + assert key in rec + + +def test_off_does_not_compute(): + planner, _ = _drive(0, 18.0, 60) + assert planner._sight_cap.sight is None diff --git a/selfdrive/controls/tests/test_sight_cap_replay.py b/selfdrive/controls/tests/test_sight_cap_replay.py new file mode 100644 index 00000000000000..3ec08d728932e5 --- /dev/null +++ b/selfdrive/controls/tests/test_sight_cap_replay.py @@ -0,0 +1,135 @@ +"""Sight-distance cap (log only) replayed on Justin's rlogs at 10 Hz. + +Each fixture holds modelV2 position (x, y, yStd), path curvature, confidence, +radarState leadOne (status, dRel, vLead, yRel) and vEgo. The cap is driven +exactly as the planner drives it. For the corner, a simulated car also obeys +the would-be cap (the real car does not: it is log only) to see what speed +the cap alone would reach at the apex. +""" +from __future__ import annotations + +import base64 +import gzip +import json +import types +from pathlib import Path + +import pytest + +from openpilot.selfdrive.controls.lib.model_sight import sight_distance_m +from openpilot.selfdrive.controls.lib.radar_path_gate import path_lateral_m +from openpilot.selfdrive.controls.lib.sight_cap import DECEL_MS2, JERK_MS3, SightCap, classify_lead + +HERE = Path(__file__).parent / "sight_cap_replay" +MPH = 2.23694 + + +def _load(name): + return json.loads(gzip.decompress(base64.b64decode((HERE / f"{name}.json.gz.b64").read_text().replace("\n", "")))) + + +def _lead(f): + if not f["lead"] or not f["lead"][0]: + return classify_lead(False, None, None, None) + _st, d, v, y = f["lead"] + lat = path_lateral_m(types.SimpleNamespace(dRel=d, yRel=y), f["x"], f["y"]) + return classify_lead(True, lat, v, d) + + +def _replay(fx, *, follow_cap=False, use_lead=True): + sc = SightCap() + rows = [] + prev = None + v_sim = None + for f in fx["frames"]: + dt = 0.1 if prev is None else max(0.02, min(0.3, f["t"] - prev)) + prev = f["t"] + v_real = float(f["v"]) + if v_sim is None: + v_sim = v_real + v = v_sim if follow_cap else v_real + lead = _lead(f) if use_lead else classify_lead(False, None, None, None) + sc.update(t=f["t"], dt=dt, v_ego=v, sight_m=sight_distance_m(f["x"], f["ys"]), ks=[k * 1e-4 for k in f["k"]], + conf_red=f["cn"] == "red", lead=lead, rb_live=False, rb_ahead=False) + rows.append(dict(t=f["t"], v=v, fire=sc.would_fire, edge=sc.fired_edge, a=sc.a_cap, why=sc.reason, vc=sc.v_cap, lead=lead)) + if follow_cap: + # The car keeps its real speed profile unless the cap asks for less. + a = sc.a_cap if sc.would_fire else 0.0 + v_sim = min(v_real, v_sim + a * dt) if sc.would_fire else min(v_real, v_sim + 0.8 * dt) + rows[-1]["sup"] = sc.suppressed_edge + return rows + + +def test_corner_fires_before_the_bend_and_the_cap_reaches_about_25_mph(): + rows = _replay(_load("corner_1010_174045"), follow_cap=True) + edges = [r["t"] for r in rows if r["edge"]] + assert edges and -8.0 <= edges[0] <= -5.0, edges # ~6.6 s before the apex (curve follow: ~1.9 s) + apex = min(r["v"] for r in rows if -1.0 <= r["t"] <= 1.0) * MPH + assert 20.0 <= apex <= 30.0, apex # Justin: 23 mph. Curve follow alone: ~46. + assert min(r["a"] for r in rows) >= -DECEL_MS2 - 1e-6 + worst = max((a["a"] - b["a"]) / max(1e-3, b["t"] - a["t"]) for a, b in zip(rows, rows[1:], strict=False) + if b["a"] < a["a"] and b["a"] < 0.0) + assert worst <= JERK_MS3 + 1e-6 # jerk limited: not a wall + + +def _variant(edit): + fx = _load("moving_lead_1007_204158") + for f in fx["frames"]: + if f["lead"] and f["lead"][0]: + edit(f["lead"]) + return fx + + +def _set(i, val): + def edit(lead): + lead[i] = val if not callable(val) else val(lead[i]) + return edit + + +@pytest.mark.parametrize("why, edit", [ + ("lead", None), # as driven: moving car ahead in our lane + ("stopped_lead", _set(2, 0.0)), # same car, stopped in our lane + ("adjacent", _set(3, lambda y: y + 3.6)), # same car, one lane over, moving + ("parked", None), # one lane over and stopped +]) +def test_any_vehicle_explaining_the_drop_suppresses_it(why, edit): + """Vehicles never count as sight loss (Justin, Oct 11): suppress and log why.""" + assert any(r["edge"] for r in _replay(_load("moving_lead_1007_204158"), use_lead=False)), "road-only would fire" + if why == "parked": + fx = _variant(lambda lead: (_set(2, 0.0)(lead), _set(3, lambda y: y + 3.6)(lead))) + else: + fx = _variant(edit) if edit else _load("moving_lead_1007_204158") + rows = _replay(fx) + assert not any(r["fire"] for r in rows) + assert any(r["why"] == why for r in rows if -1.0 <= r["t"] <= 1.0), why + + +def test_lead_kinds(): + assert classify_lead(True, 0.2, 14.0, 40.0).kind == "lead" + assert classify_lead(True, 0.2, 0.0, 40.0).kind == "stopped_lead" + assert classify_lead(True, 3.5, 14.0, 40.0).kind == "adjacent" + assert classify_lead(True, -3.5, 0.5, 40.0).kind == "parked" + assert classify_lead(True, 0.2, 14.0, 200.0).kind == "" + assert classify_lead(False, None, None, None).kind == "" + + +def test_straight_never_fires(): + rows = _replay(_load("straight_1010_1758")) + assert len(rows) > 400 + assert not any(r["fire"] for r in rows) + + +@pytest.mark.parametrize("rb_live", [True]) +def test_roundabout_funnel_live_steps_aside(rb_live): + fx = _load("corner_1010_174045") + sc = SightCap() + fired = False + prev = None + for f in fx["frames"]: + dt = 0.1 if prev is None else f["t"] - prev + prev = f["t"] + sc.update(t=f["t"], dt=dt, v_ego=float(f["v"]), sight_m=sight_distance_m(f["x"], f["ys"]), + ks=[k * 1e-4 for k in f["k"]], conf_red=f["cn"] == "red", lead=classify_lead(False, None, None, None), + rb_live=rb_live, rb_ahead=True) + fired |= sc.would_fire + assert not fired and sc.reason == "rb_funnel" diff --git a/selfdrive/controls/tests/test_startup.py b/selfdrive/controls/tests/test_startup.py deleted file mode 100644 index 077d4ae93aa80e..00000000000000 --- a/selfdrive/controls/tests/test_startup.py +++ /dev/null @@ -1,121 +0,0 @@ -import os -from parameterized import parameterized - -from cereal import log, car -import cereal.messaging as messaging -from opendbc.car.fingerprints import _FINGERPRINTS -from opendbc.car.toyota.values import CAR as TOYOTA -from opendbc.car.mazda.values import CAR as MAZDA -from openpilot.common.params import Params -from openpilot.selfdrive.pandad.pandad_api_impl import can_list_to_can_capnp -from openpilot.selfdrive.controls.lib.events import EVENT_NAME -from openpilot.system.manager.process_config import managed_processes - -EventName = car.OnroadEvent.EventName -Ecu = car.CarParams.Ecu - -COROLLA_FW_VERSIONS = [ - (Ecu.engine, 0x7e0, None, b'\x0230ZC2000\x00\x00\x00\x00\x00\x00\x00\x0050212000\x00\x00\x00\x00\x00\x00\x00\x00'), - (Ecu.abs, 0x7b0, None, b'F152602190\x00\x00\x00\x00\x00\x00'), - (Ecu.eps, 0x7a1, None, b'8965B02181\x00\x00\x00\x00\x00\x00'), - (Ecu.fwdRadar, 0x750, 0xf, b'8821F4702100\x00\x00\x00\x00'), - (Ecu.fwdCamera, 0x750, 0x6d, b'8646F0201101\x00\x00\x00\x00'), - (Ecu.dsu, 0x791, None, b'881510201100\x00\x00\x00\x00'), -] -COROLLA_FW_VERSIONS_FUZZY = COROLLA_FW_VERSIONS[:-1] + [(Ecu.dsu, 0x791, None, b'xxxxxx')] -COROLLA_FW_VERSIONS_NO_DSU = COROLLA_FW_VERSIONS[:-1] - -CX5_FW_VERSIONS = [ - (Ecu.engine, 0x7e0, None, b'PYNF-188K2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), - (Ecu.abs, 0x760, None, b'K123-437K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), - (Ecu.eps, 0x730, None, b'KJ01-3210X-G-00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), - (Ecu.fwdRadar, 0x764, None, b'K123-67XK2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), - (Ecu.fwdCamera, 0x706, None, b'B61L-67XK2-T\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), - (Ecu.transmission, 0x7e1, None, b'PYNC-21PS1-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), -] - - -@parameterized.expand([ - # TODO: test EventName.startup for release branches - - # officially supported car - (EventName.startupMaster, TOYOTA.TOYOTA_COROLLA, COROLLA_FW_VERSIONS, "toyota"), - (EventName.startupMaster, TOYOTA.TOYOTA_COROLLA, COROLLA_FW_VERSIONS, "toyota"), - - # dashcamOnly car - (EventName.startupNoControl, MAZDA.MAZDA_CX5, CX5_FW_VERSIONS, "mazda"), - (EventName.startupNoControl, MAZDA.MAZDA_CX5, CX5_FW_VERSIONS, "mazda"), - - # unrecognized car with no fw - (EventName.startupNoFw, None, None, ""), - (EventName.startupNoFw, None, None, ""), - - # unrecognized car - (EventName.startupNoCar, None, COROLLA_FW_VERSIONS[:1], "toyota"), - (EventName.startupNoCar, None, COROLLA_FW_VERSIONS[:1], "toyota"), - - # fuzzy match - (EventName.startupMaster, TOYOTA.TOYOTA_COROLLA, COROLLA_FW_VERSIONS_FUZZY, "toyota"), - (EventName.startupMaster, TOYOTA.TOYOTA_COROLLA, COROLLA_FW_VERSIONS_FUZZY, "toyota"), -]) -def test_startup_alert(expected_event, car_model, fw_versions, brand): - controls_sock = messaging.sub_sock("selfdriveState") - pm = messaging.PubMaster(['can', 'pandaStates']) - - params = Params() - params.put_bool("OpenpilotEnabledToggle", True) - - # Build capnn version of FW array - if fw_versions is not None: - car_fw = [] - cp = car.CarParams.new_message() - for ecu, addr, subaddress, version in fw_versions: - f = car.CarParams.CarFw.new_message() - f.ecu = ecu - f.address = addr - f.fwVersion = version - f.brand = brand - - if subaddress is not None: - f.subAddress = subaddress - - car_fw.append(f) - cp.carVin = "1" * 17 - cp.carFw = car_fw - params.put("CarParamsCache", cp.to_bytes()) - else: - os.environ['SKIP_FW_QUERY'] = '1' - - managed_processes['controlsd'].start() - managed_processes['card'].start() - - assert pm.wait_for_readers_to_update('can', 5) - pm.send('can', can_list_to_can_capnp([[0, b"", 0]])) - - assert pm.wait_for_readers_to_update('pandaStates', 5) - msg = messaging.new_message('pandaStates', 1) - msg.pandaStates[0].pandaType = log.PandaState.PandaType.uno - pm.send('pandaStates', msg) - - # fingerprint - if (car_model is None) or (fw_versions is not None): - finger = {addr: 1 for addr in range(1, 100)} - else: - finger = _FINGERPRINTS[car_model][0] - - msgs = [[addr, b'\x00'*length, 0] for addr, length in finger.items()] - for _ in range(1000): - # card waits for pandad to echo back that it has changed the multiplexing mode - if not params.get_bool("ObdMultiplexingChanged"): - params.put_bool("ObdMultiplexingChanged", True) - - pm.send('can', can_list_to_can_capnp(msgs)) - assert pm.wait_for_readers_to_update('can', 5, dt=0.001), f"step: {_}" - - ctrls = messaging.drain_sock(controls_sock) - if len(ctrls): - event_name = ctrls[0].selfdriveState.alertType.split("/")[0] - assert EVENT_NAME[expected_event] == event_name, f"expected {EVENT_NAME[expected_event]} for '{car_model}', got {event_name}" - break - else: - raise Exception(f"failed to fingerprint {car_model}") diff --git a/selfdrive/controls/tests/test_state_machine.py b/selfdrive/controls/tests/test_state_machine.py deleted file mode 100644 index a42cd6056bdeb2..00000000000000 --- a/selfdrive/controls/tests/test_state_machine.py +++ /dev/null @@ -1,102 +0,0 @@ -from cereal import car, log -from opendbc.car.car_helpers import interfaces -from opendbc.car.mock.values import CAR as MOCK -from openpilot.common.realtime import DT_CTRL -from openpilot.selfdrive.controls.controlsd import Controls, SOFT_DISABLE_TIME -from openpilot.selfdrive.controls.lib.events import Events, ET, Alert, Priority, AlertSize, AlertStatus, VisualAlert, \ - AudibleAlert, EVENTS - -State = log.SelfdriveState.OpenpilotState - -# The event types that maintain the current state -MAINTAIN_STATES = {State.enabled: (None,), State.disabled: (None,), State.softDisabling: (ET.SOFT_DISABLE,), - State.preEnabled: (ET.PRE_ENABLE,), State.overriding: (ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL)} -ALL_STATES = tuple(State.schema.enumerants.values()) -# The event types checked in DISABLED section of state machine -ENABLE_EVENT_TYPES = (ET.ENABLE, ET.PRE_ENABLE, ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL) - - -def make_event(event_types): - event = {} - for ev in event_types: - event[ev] = Alert("", "", AlertStatus.normal, AlertSize.small, Priority.LOW, - VisualAlert.none, AudibleAlert.none, 1.) - EVENTS[0] = event - return 0 - - -class TestStateMachine: - - def setup_method(self): - CarInterface, CarController, CarState, RadarInterface = interfaces[MOCK.MOCK] - CP = CarInterface.get_non_essential_params(MOCK.MOCK) - CI = CarInterface(CP, CarController, CarState) - - self.controlsd = Controls(CI=CI) - self.controlsd.events = Events() - self.controlsd.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) - self.CS = car.CarState() - - def test_immediate_disable(self): - for state in ALL_STATES: - for et in MAINTAIN_STATES[state]: - self.controlsd.events.add(make_event([et, ET.IMMEDIATE_DISABLE])) - self.controlsd.state = state - self.controlsd.state_transition(self.CS) - assert State.disabled == self.controlsd.state - self.controlsd.events.clear() - - def test_user_disable(self): - for state in ALL_STATES: - for et in MAINTAIN_STATES[state]: - self.controlsd.events.add(make_event([et, ET.USER_DISABLE])) - self.controlsd.state = state - self.controlsd.state_transition(self.CS) - assert State.disabled == self.controlsd.state - self.controlsd.events.clear() - - def test_soft_disable(self): - for state in ALL_STATES: - if state == State.preEnabled: # preEnabled considers NO_ENTRY instead - continue - for et in MAINTAIN_STATES[state]: - self.controlsd.events.add(make_event([et, ET.SOFT_DISABLE])) - self.controlsd.state = state - self.controlsd.state_transition(self.CS) - assert self.controlsd.state == State.disabled if state == State.disabled else State.softDisabling - self.controlsd.events.clear() - - def test_soft_disable_timer(self): - self.controlsd.state = State.enabled - self.controlsd.events.add(make_event([ET.SOFT_DISABLE])) - self.controlsd.state_transition(self.CS) - for _ in range(int(SOFT_DISABLE_TIME / DT_CTRL)): - assert self.controlsd.state == State.softDisabling - self.controlsd.state_transition(self.CS) - - assert self.controlsd.state == State.disabled - - def test_no_entry(self): - # Make sure noEntry keeps us disabled - for et in ENABLE_EVENT_TYPES: - self.controlsd.events.add(make_event([ET.NO_ENTRY, et])) - self.controlsd.state_transition(self.CS) - assert self.controlsd.state == State.disabled - self.controlsd.events.clear() - - def test_no_entry_pre_enable(self): - # preEnabled with noEntry event - self.controlsd.state = State.preEnabled - self.controlsd.events.add(make_event([ET.NO_ENTRY, ET.PRE_ENABLE])) - self.controlsd.state_transition(self.CS) - assert self.controlsd.state == State.preEnabled - - def test_maintain_states(self): - # Given current state's event type, we should maintain state - for state in ALL_STATES: - for et in MAINTAIN_STATES[state]: - self.controlsd.state = state - self.controlsd.events.add(make_event([et])) - self.controlsd.state_transition(self.CS) - assert self.controlsd.state == state - self.controlsd.events.clear() diff --git a/selfdrive/controls/tests/test_tesla_preap_brake_cancel_regen.py b/selfdrive/controls/tests/test_tesla_preap_brake_cancel_regen.py new file mode 100644 index 00000000000000..dd8fb7fbc7d932 --- /dev/null +++ b/selfdrive/controls/tests/test_tesla_preap_brake_cancel_regen.py @@ -0,0 +1,137 @@ +"""Brake cancel is firm/stock: interceptor RELEASEs as soon as long drops. + +No tip/hold regen ramp, no coast-then-bite. A light tap that knocks +software long off must RELEASE immediately to Tesla regen. FCW / hard +lead / full cancel unchanged. Gas-lift A+B / A3 is untouched. +""" +from types import SimpleNamespace + +from opendbc.car.tesla.preap.carcontroller import ( + ENGAGE_GRACE_FRAMES, + PedalCommandAction, + PreAPLongController, +) +from opendbc.car.tesla.preap.engagement import PreAPEngagement +from opendbc.car.tesla.preap.nap_conf import PEDAL_MAX_VALUES +from opendbc.car.tesla.preap.pedal_feedback import PedalFeedback +from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP +from opendbc.car.tesla.preap.tests.test_pedal_authority import ( + _activate_longitudinal, + _decode_pedal_command, +) + + +def _pedal_conf(): + return SimpleNamespace( + use_pedal=True, + pedal_factor=1.0, + di_to_pedal=lambda pedal_di: pedal_di, + get_pedal_profile_values=lambda: PEDAL_MAX_VALUES, + ) + + +def _zero_torque(): + return SimpleNamespace( + get=lambda _v_ego: 0.0, + update=lambda *_args, **_kwargs: None, + ) + + +def controller_env(monkeypatch): + zero_torque = _zero_torque() + monkeypatch.setattr('opendbc.car.tesla.preap.carcontroller.nap_conf', _pedal_conf()) + monkeypatch.setattr('opendbc.car.tesla.preap.carcontroller.get_zero_torque', lambda: zero_torque) + monkeypatch.setattr('opendbc.car.tesla.preap.virtual_das.nap_conf', _pedal_conf()) + monkeypatch.setattr('opendbc.car.tesla.preap.virtual_das.get_zero_torque', lambda: zero_torque) + + feedback = PedalFeedback() + feedback.update({"INTERCEPTOR_GAS": 0.0, "INTERCEPTOR_GAS2": 0.0, "STATE": 0, "IDX": 1}, 0) + engagement = PreAPEngagement(double_pull_enabled=False, double_pull_window_ms=750) + cs = SimpleNamespace( + cruiseEnabled=False, + enableLongControl=False, + enableJustCC=False, + engagement=engagement, + real_brake_pressed=False, + out=SimpleNamespace(vEgo=15.0, aEgo=0.0, gasPressed=False), + pedal_interceptor_value=0.0, + cruise_buttons=0, + prev_cruise_buttons=0, + pedal=feedback, + pedal_timeout=feedback.timeout, + pccEvent=None, + preap_cc_cancel_needed=False, + ) + cc = SimpleNamespace( + actuators=SimpleNamespace(accel=0.4), + longActive=False, + orientationNED=[], + ) + return PreAPLongController(), cc, cs, TeslaCANPreAP({}) + + +def _drop_long_on_brake(cc, cs, *, a_ego=0.0): + cs.enableLongControl = False + cs.engagement.enableLongControl = False + cc.longActive = False + cs.real_brake_pressed = True + cs.out.aEgo = a_ego + + +def test_short_tip_releases_interceptor_immediately(monkeypatch): + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + + _drop_long_on_brake(cc, cs, a_ego=-0.25) + release = controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled + assert _decode_pedal_command(release[0]).raw_command == 0 + assert cs.pedal_authority_action == int(PedalCommandAction.RELEASE) + assert not getattr(cs, "pedal_brake_cancel_ramp", False) + assert not hasattr(controller, "brake_cancel") + + cs.real_brake_pressed = False + cs.out.aEgo = 0.05 + assert controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) == [] + + +def test_held_brake_also_releases_immediately(monkeypatch): + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + _drop_long_on_brake(cc, cs, a_ego=0.0) + + release = controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.RELEASE) + assert controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) == [] + + +def test_hard_lead_fcw_path_unchanged(monkeypatch): + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + cc.actuators.accel = 0.0 + for frame in range(0, ENGAGE_GRACE_FRAMES + 2, 2): + controller.update(cc, cs, frame=frame, tesla_can=tesla_can, can_bus_party=0) + cc.actuators.accel = -1.3 + cs.out.aEgo = -0.5 + limited = [] + for frame in range(ENGAGE_GRACE_FRAMES + 2, ENGAGE_GRACE_FRAMES + 24, 2): + sent = controller.update(cc, cs, frame=frame, tesla_can=tesla_can, can_bus_party=0) + assert _decode_pedal_command(sent[0]).enabled + assert not getattr(cs, "pedal_brake_cancel_ramp", False) + limited.append(controller.vdas.jerk_limiter.a_limited) + assert min(limited) < 0.0 + + +def test_full_cancel_releases(monkeypatch): + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + cs.cruiseEnabled = False + cs.enableLongControl = False + cc.longActive = False + cs.real_brake_pressed = True + release = controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled diff --git a/selfdrive/controls/tests/test_tesla_preap_following.py b/selfdrive/controls/tests/test_tesla_preap_following.py new file mode 100644 index 00000000000000..6d4dd24639ed48 --- /dev/null +++ b/selfdrive/controls/tests/test_tesla_preap_following.py @@ -0,0 +1,1152 @@ +from types import SimpleNamespace + +import numpy as np +import pytest + +from cereal import car, log, messaging +from opendbc.car.tesla.preap import virtual_das +from opendbc.car.tesla.preap.constants import PEDAL_LONG_K_BP, PEDAL_LONG_KI_V, PEDAL_LONG_KP_V +from opendbc.car.tesla.preap.virtual_das import GRAVITY, VirtualDAS +from opendbc.car.tesla.pedal.controller import PEDAL_RAMP_RATE_DOWN, PEDAL_RAMP_RATE_UP +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState +from openpilot.selfdrive.controls.lib.longcontrol import LongControl +from openpilot.selfdrive.controls.lib import longitudinal_planner +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_APPROACH_MILD_A_MS2, + LEAD_CLOSE_HOLD_S, + LEAD_CLOSE_MAX_M, +) +from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import ( + LongitudinalPlanSource, + T_IDXS, + get_safe_obstacle_distance, + get_stopped_equivalence_factor, + get_T_FOLLOW, +) +from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner +from openpilot.selfdrive.controls.tests.test_following_distance import run_following_distance_simulation +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver +from openpilot.selfdrive.test.process_replay.process_replay import get_process_config + + +NAP_FOLLOW_SETTINGS = range(1, 8) +NAP_FOLLOW_TIMES_S = (0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9) +FOLLOW_TEST_SPEED_MPS = 25.0 +STOP_DISTANCE_M = 6.0 +FULL_LOOP_DT_S = 0.01 +FULL_LOOP_PLANNER_DT_S = 0.05 +FULL_LOOP_VDAS_DT_S = 0.02 +FULL_LOOP_PLANT_DELAY_S = 0.40 +FULL_LOOP_PLANT_TAU_S = 0.25 +FULL_LOOP_PEDAL_DI_BP = [-5.0, -2.0, 0.0, 3.0, 8.0, 15.0, 22.0, 27.0, 35.0, 50.0] +FULL_LOOP_NET_ACCEL_BP = [-1.05, -0.62, -0.50, -0.36, 0.0, 0.50, 1.15, 1.65, 2.10, 2.45] +FULL_LOOP_RECOVERY_END_S = 70.0 +FULL_LOOP_UPHILL_RAMP_END_S = 72.0 +FULL_LOOP_UPHILL_HOLD_END_S = 78.0 +FULL_LOOP_CREST_RAMP_END_S = 80.0 +FULL_LOOP_CREST_HOLD_END_S = 86.0 +FULL_LOOP_ROLLING_RAMP_END_S = 88.0 +FULL_LOOP_DURATION_S = 100.0 +FULL_LOOP_UPHILL_PITCH_RAD = float(np.deg2rad(4.0)) +FULL_LOOP_CREST_PITCH_RAD = float(np.deg2rad(-3.0)) +FULL_LOOP_ROLLING_PITCH_RAD = float(np.deg2rad(2.0)) +FULL_LOOP_GRADE_SETTLING_S = ( + FULL_LOOP_PLANT_DELAY_S + FULL_LOOP_PLANT_TAU_S + 5.0 * virtual_das.PITCH_LP_RC +) + + +class _PlannerInputs(dict): + logMonoTime = {"modelV2": 0} + + @staticmethod + def all_checks(service_list): + return set(service_list) == {"carState", "controlsState", "selfdriveState", "radarState"} + + +class _CapturingPubMaster: + def send(self, service, message): + assert service == "longitudinalPlan" + self.message = message + + +class _MutablePlannerParams: + def __init__(self, nap_follow_dist, adaptive_accel=False, map_speed_accel=5, + city=None, hwy=None): + self.nap_follow_dist = nap_follow_dist + self.adaptive_accel = adaptive_accel + self.map_speed_accel = map_speed_accel + self.city = city if city is not None else nap_follow_dist + self.hwy = hwy if hwy is not None else nap_follow_dist + self.migrated = True + + def __bool__(self): + return False + + def get(self, key, return_default=False): + assert return_default + if key == "NAPFollowDistance": + return self.nap_follow_dist + if key == "NAPFollowDistanceCity": + return self.city + if key == "NAPFollowDistanceHwy": + return self.hwy + if key == "NAPMapSpeedAccel": + return self.map_speed_accel + if key == "NAPMapSpeedMode": + return 0 + if key == "NAPMapSpeedOffsetMph": + return 0 + if key == "NAPMapSpeedLookahead": + return 2 + raise AssertionError(key) + + def get_bool(self, key): + if key == "NAPAdaptiveAccel": + return self.adaptive_accel + if key == "NAPHypermile": + return False + if key == "NAPHypermileHillClimb": + return True + if key == "NAPFollowDistanceSplitMigrated": + return self.migrated + raise AssertionError(key) + + def put(self, key, value): + if key == "NAPFollowDistance": + self.nap_follow_dist = value + elif key == "NAPFollowDistanceCity": + self.city = value + elif key == "NAPFollowDistanceHwy": + self.hwy = value + + def put_bool(self, key, value): + if key == "NAPFollowDistanceSplitMigrated": + self.migrated = bool(value) + elif key == "NAPAdaptiveAccel": + self.adaptive_accel = bool(value) + + +class _ConstantAccelerationMpc: + def __init__(self, speed_mps, acceleration_mps2): + self.v_solution = speed_mps + acceleration_mps2 * T_IDXS + self.a_solution = np.full(len(T_IDXS), acceleration_mps2) + self.j_solution = np.zeros(len(T_IDXS) - 1) + self.params = np.zeros((len(T_IDXS), 6)) + self.source = LongitudinalPlanSource.cruise + self.crash_cnt = 0 + self.solve_time = 0.0 + self.captured_t_follow = None + + @staticmethod + def set_weights(prev_accel_constraint, personality): + pass + + @staticmethod + def set_cur_state(speed_mps, acceleration_mps2): + pass + + def update(self, radar_state, cruise_speed_mps, t_follow): + self.captured_t_follow = t_follow + self.params[:, 4] = t_follow + + +def _make_preap_params(): + params = car.CarParams.new_message() + params.brand = "tesla" + params.carFingerprint = "TESLA_MODEL_S_PREAP" + params.openpilotLongitudinalControl = True + params.pcmCruise = False + params.steerRatio = 15.75 + params.wheelbase = 2.959 + params.longitudinalTuning.kpBP = PEDAL_LONG_K_BP + params.longitudinalTuning.kpV = PEDAL_LONG_KP_V + params.longitudinalTuning.kiBP = PEDAL_LONG_K_BP + params.longitudinalTuning.kiV = PEDAL_LONG_KI_V + params.longitudinalTuning.kf = 1.0 + params.vEgoStarting = 0.1 + return params + + +# Catch-up tests must sit well under MAX so last-mph taper / deadband +# do not zero lead-close +a. Accel 1 tapers over ~5 mph. +_UNDER_MAX_HEADROOM_MS = 6.0 + + +def _set_v_cruise_ms(inputs, v_cruise_ms): + inputs["carState"].vCruise = float(v_cruise_ms) * CV.MS_TO_KPH + + +def _make_planner_inputs(speed_mps): + radar = messaging.new_message("radarState").radarState + controls = messaging.new_message("controlsState").controlsState + selfdrive = messaging.new_message("selfdriveState").selfdriveState + car_state = messaging.new_message("carState").carState + car_control = messaging.new_message("carControl").carControl + live_parameters = messaging.new_message("liveParameters").liveParameters + model = messaging.new_message("modelV2").modelV2 + + controls.longControlState = LongCtrlState.pid + selfdrive.personality = log.LongitudinalPersonality.standard + car_state.vEgo = speed_mps + car_state.vCruise = speed_mps * 3.6 + car_control.orientationNED = [0.0, 0.0, 0.0] + + model.position.x = (speed_mps * np.array(ModelConstants.T_IDXS)).tolist() + model.velocity.x = (speed_mps * np.ones_like(ModelConstants.T_IDXS)).tolist() + model.acceleration.x = np.zeros_like(ModelConstants.T_IDXS).tolist() + model.meta.disengagePredictions.gasPressProbs = [1.0] * 6 + + return _PlannerInputs({ + "radarState": radar, + "controlsState": controls, + "selfdriveState": selfdrive, + "carState": car_state, + "carControl": car_control, + "liveParameters": live_parameters, + "modelV2": model, + }) + + +def _physical_lead_distance(v_ego, v_lead, t_follow, obstacle_ratio): + safe_obstacle_distance = get_safe_obstacle_distance(v_ego, t_follow) + lead_obstacle_distance = obstacle_ratio * safe_obstacle_distance + return lead_obstacle_distance - get_stopped_equivalence_factor(max(v_lead, 0.0)) + + +def _full_loop_pitch(elapsed_s): + if elapsed_s < FULL_LOOP_RECOVERY_END_S: + return 0.0 + if elapsed_s < FULL_LOOP_UPHILL_RAMP_END_S: + return FULL_LOOP_UPHILL_PITCH_RAD * ( + (elapsed_s - FULL_LOOP_RECOVERY_END_S) / + (FULL_LOOP_UPHILL_RAMP_END_S - FULL_LOOP_RECOVERY_END_S) + ) + if elapsed_s < FULL_LOOP_UPHILL_HOLD_END_S: + return FULL_LOOP_UPHILL_PITCH_RAD + if elapsed_s < FULL_LOOP_CREST_RAMP_END_S: + ramp_fraction = ( + (elapsed_s - FULL_LOOP_UPHILL_HOLD_END_S) / + (FULL_LOOP_CREST_RAMP_END_S - FULL_LOOP_UPHILL_HOLD_END_S) + ) + return FULL_LOOP_UPHILL_PITCH_RAD + ramp_fraction * ( + FULL_LOOP_CREST_PITCH_RAD - FULL_LOOP_UPHILL_PITCH_RAD + ) + if elapsed_s < FULL_LOOP_CREST_HOLD_END_S: + return FULL_LOOP_CREST_PITCH_RAD + if elapsed_s < FULL_LOOP_ROLLING_RAMP_END_S: + ramp_fraction = ( + (elapsed_s - FULL_LOOP_CREST_HOLD_END_S) / + (FULL_LOOP_ROLLING_RAMP_END_S - FULL_LOOP_CREST_HOLD_END_S) + ) + return FULL_LOOP_CREST_PITCH_RAD + ramp_fraction * ( + FULL_LOOP_ROLLING_PITCH_RAD - FULL_LOOP_CREST_PITCH_RAD + ) + return FULL_LOOP_ROLLING_PITCH_RAD + + +def _run_full_closed_loop_following( + monkeypatch, + nap_follow_dist=7, + plant_aligned_feedforward=False, + grade_compensation_scale=1.0, +): + monkeypatch.setattr( + virtual_das, + "nap_conf", + SimpleNamespace(get_pedal_profile_values=lambda: [50.0] * len(virtual_das.PEDAL_BP)), + ) + monkeypatch.setattr( + virtual_das, + "get_zero_torque", + lambda: SimpleNamespace(get=lambda _speed_mps: 3.0), + ) + + speed_mps = FOLLOW_TEST_SPEED_MPS + acceleration_mps2 = 0.0 + ego_distance_m = 0.0 + lead_distance_m = 20.0 + lead_speed_mps = FOLLOW_TEST_SPEED_MPS + pedal_di = 8.0 + planner_target_mps2 = 0.0 + vdas_target_mps2 = 0.0 + + params = _MutablePlannerParams(nap_follow_dist=nap_follow_dist, adaptive_accel=True) + car_params = _make_preap_params() + car_params.longitudinalActuatorDelay = FULL_LOOP_PLANT_DELAY_S + planner = LongitudinalPlanner(car_params, init_v=speed_mps, params=params) + long_control = LongControl(car_params) + vdas = VirtualDAS(dt=FULL_LOOP_VDAS_DT_S) + vdas.reset(measured_accel=acceleration_mps2, commanded_accel=0.0, pedal_di_init=pedal_di) + if plant_aligned_feedforward: + vdas._feedforward = lambda acceleration_effort_mps2, _speed_mps: float(np.interp( + acceleration_effort_mps2, + FULL_LOOP_NET_ACCEL_BP, + FULL_LOOP_PEDAL_DI_BP, + )) + if grade_compensation_scale != 1.0: + grade_estimator_update = vdas.grade_estimator.update + + def scaled_grade_estimator_update(orientation_ned): + steady_compensation, transient_compensation = grade_estimator_update(orientation_ned) + return ( + grade_compensation_scale * steady_compensation, + grade_compensation_scale * transient_compensation, + ) + + vdas.grade_estimator.update = scaled_grade_estimator_update + + delay_steps = round(FULL_LOOP_PLANT_DELAY_S / FULL_LOOP_DT_S) + delayed_pedals_di = [pedal_di] * delay_steps + plant_alpha = FULL_LOOP_DT_S / (FULL_LOOP_PLANT_TAU_S + FULL_LOOP_DT_S) + planner_interval_steps = round(FULL_LOOP_PLANNER_DT_S / FULL_LOOP_DT_S) + vdas_interval_steps = round(FULL_LOOP_VDAS_DT_S / FULL_LOOP_DT_S) + samples = [] + pedal_samples = [] + + for step in range(round(FULL_LOOP_DURATION_S / FULL_LOOP_DT_S)): + elapsed_s = step * FULL_LOOP_DT_S + pitch_rad = _full_loop_pitch(elapsed_s) + gap_m = lead_distance_m - ego_distance_m + + if step % planner_interval_steps == 0: + inputs = _make_planner_inputs(float(speed_mps)) + inputs["carState"].aEgo = float(acceleration_mps2) + inputs["carState"].vCruise = lead_speed_mps * 3.6 + inputs["carControl"].orientationNED = [0.0, pitch_rad, 0.0] + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = float(max(gap_m, 0.0)) + lead.vRel = float(lead_speed_mps - speed_mps) + lead.vLead = lead_speed_mps + lead.vLeadK = lead_speed_mps + lead.aLeadK = 0.0 + lead.aLeadTau = 1.5 + lead.modelProb = 1.0 + planner.update(inputs) + planner_target_mps2 = float(planner.output_a_target) + + state = car.CarState.new_message() + state.vEgo = float(speed_mps) + state.aEgo = float(acceleration_mps2) + state.brakePressed = False + state.cruiseState.standstill = False + vdas_target_mps2 = float(long_control.update( + active=True, + CS=state, + a_target=planner_target_mps2, + should_stop=planner.output_should_stop, + accel_limits=(-1.5, 0.8), + )) + + if step % vdas_interval_steps == 0: + pedal_di = vdas.update( + vdas_target_mps2, + v_ego=speed_mps, + prev_pedal_di=pedal_di, + a_ego=acceleration_mps2, + freeze_integrator=False, + orientation_ned=[0.0, pitch_rad, 0.0], + ) + pedal_samples.append(pedal_di) + + applied_pedal_di = delayed_pedals_di.pop(0) + delayed_pedals_di.append(pedal_di) + grade_acceleration_mps2 = GRAVITY * np.sin(pitch_rad) + plant_target_mps2 = float(np.interp( + applied_pedal_di, + FULL_LOOP_PEDAL_DI_BP, + FULL_LOOP_NET_ACCEL_BP, + )) - grade_acceleration_mps2 + acceleration_mps2 += plant_alpha * (plant_target_mps2 - acceleration_mps2) + speed_mps = max(0.0, speed_mps + acceleration_mps2 * FULL_LOOP_DT_S) + ego_distance_m += speed_mps * FULL_LOOP_DT_S + lead_distance_m += lead_speed_mps * FULL_LOOP_DT_S + + samples.append(( + elapsed_s, + lead_distance_m - ego_distance_m, + speed_mps, + acceleration_mps2, + planner_target_mps2, + vdas_target_mps2, + pitch_rad, + )) + + return np.array(samples), np.array(pedal_samples) + + +@pytest.mark.parametrize(("lead_speed", "obstacle_ratio", "expected_strength"), [ + (30.0, 1.0, 1.0), + (30.0, 1.2, 1.0), + (30.0, 1.35, 0.5), + (30.0, 1.5, 0.0), + (20.0, 1.35, 0.5), + (-5.0, 1.35, 0.5), +]) +def test_preap_follow_cap_uses_obstacle_equivalent_distance(lead_speed, obstacle_ratio, expected_strength): + speed_mps = 30.0 + t_follow = 1.9 + lead_distance = _physical_lead_distance(speed_mps, lead_speed, t_follow, obstacle_ratio) + + cap_strength = longitudinal_planner.get_preap_follow_cap_strength( + speed_mps, + lead_distance, + lead_speed, + t_follow, + ) + + assert cap_strength == pytest.approx(expected_strength) + + +def test_planner_adaptive_cap_changes_the_delivered_acceleration_for_unequal_speed_lead(): + speed_mps = 40.0 + # Same-speed lead so ease does not fire. Obstacle-ratio 1.35 at 40 m/s is + # a physical gap beyond the 200 m Bosch lead-close window. Adaptive Accel only. + lead_speed_mps = 40.0 + obstacle_ratio = 1.35 + t_follow = 1.9 + params = _MutablePlannerParams(nap_follow_dist=7, adaptive_accel=True) + planner = LongitudinalPlanner(_make_preap_params(), init_v=speed_mps, params=params) + planner.mpc = _ConstantAccelerationMpc(speed_mps, acceleration_mps2=1.5) + inputs = _make_planner_inputs(speed_mps) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = _physical_lead_distance(speed_mps, lead_speed_mps, t_follow, obstacle_ratio) + lead.vLead = lead_speed_mps + assert lead.dRel > LEAD_CLOSE_MAX_M + + for _ in range(32): + planner.update(inputs) + + open_road_limit = longitudinal_planner.get_max_accel(speed_mps) + follow_limit = longitudinal_planner._get_preap_follow_limit(speed_mps) + cap_strength = longitudinal_planner.get_preap_follow_cap_strength( + speed_mps, + lead.dRel, + lead_speed_mps, + t_follow, + ) + expected_adaptive_limit = open_road_limit * (1.0 - cap_strength) + follow_limit * cap_strength + + assert cap_strength == pytest.approx(0.5) + assert planner.mpc.captured_t_follow == t_follow + assert planner.output_a_target == pytest.approx(expected_adaptive_limit) + assert planner.output_a_target < open_road_limit + + +def test_planner_publishes_the_follow_policy_used_by_mpc(): + params = _MutablePlannerParams(nap_follow_dist=1) + planner = LongitudinalPlanner(_make_preap_params(), init_v=FOLLOW_TEST_SPEED_MPS, params=params) + inputs = _make_planner_inputs(FOLLOW_TEST_SPEED_MPS) + publisher = _CapturingPubMaster() + + params.nap_follow_dist = 7 + params.city = 7 + params.hwy = 7 + planner._frame = 19 + planner.update(inputs) + planner.publish(inputs, publisher) + + plan = publisher.message.longitudinalPlan + assert plan.napFollowDistance == 7 + assert plan.tFollow == pytest.approx(1.9) + assert planner.t_follow == 1.9 + assert np.all(planner.mpc.params[:, 4] == planner.t_follow) + assert plan.tFollow == pytest.approx(planner.t_follow, abs=1e-6) + + +@pytest.mark.parametrize("nap_follow_dist", [-1, 0, 8]) +def test_invalid_nap_follow_setting_publishes_zero_and_uses_personality(nap_follow_dist): + params = _MutablePlannerParams(nap_follow_dist) + planner = LongitudinalPlanner(_make_preap_params(), init_v=FOLLOW_TEST_SPEED_MPS, params=params) + inputs = _make_planner_inputs(FOLLOW_TEST_SPEED_MPS) + publisher = _CapturingPubMaster() + + planner.update(inputs) + planner.publish(inputs, publisher) + + plan = publisher.message.longitudinalPlan + assert plan.napFollowDistance == 0 + assert planner.t_follow == get_T_FOLLOW(log.LongitudinalPersonality.standard) + assert np.all(planner.mpc.params[:, 4] == planner.t_follow) + assert plan.tFollow == pytest.approx(planner.t_follow, abs=1e-6) + + +def test_non_preap_planner_publishes_zero_and_uses_personality(): + planner_params = _make_preap_params() + planner_params.brand = "honda" + planner_params.carFingerprint = "HONDA_CIVIC" + planner = LongitudinalPlanner(planner_params, init_v=FOLLOW_TEST_SPEED_MPS) + inputs = _make_planner_inputs(FOLLOW_TEST_SPEED_MPS) + inputs["selfdriveState"].personality = log.LongitudinalPersonality.relaxed + publisher = _CapturingPubMaster() + + planner.update(inputs) + planner.publish(inputs, publisher) + + plan = publisher.message.longitudinalPlan + assert plan.napFollowDistance == 0 + assert planner.t_follow == get_T_FOLLOW(log.LongitudinalPersonality.relaxed) + assert np.all(planner.mpc.params[:, 4] == planner.t_follow) + assert plan.tFollow == pytest.approx(planner.t_follow, abs=1e-6) + + +def test_process_replay_ignores_additive_follow_policy_telemetry(): + ignored_fields = get_process_config("plannerd").ignore + + assert "longitudinalPlan.napFollowDistance" in ignored_fields + assert "longitudinalPlan.tFollow" in ignored_fields + assert "longitudinalPlan.unifiedATarget" in ignored_fields + + +def test_nap_follow_setting_map_and_physical_gaps_are_strictly_monotonic(): + actual_follow_times = [get_T_FOLLOW(nap_follow_dist=setting) for setting in NAP_FOLLOW_SETTINGS] + physical_gaps = [t_follow * FOLLOW_TEST_SPEED_MPS + STOP_DISTANCE_M for t_follow in actual_follow_times] + + assert actual_follow_times == list(NAP_FOLLOW_TIMES_S) + assert np.all(np.diff(physical_gaps) > 0.0) + + +def test_nap_follow_settings_control_monotonic_maneuver_gaps(): + # Physical t_follow * v + stop_distance. The unified law deliberately closes + # a 100 m same-speed gap without a catch-up lunge (MAX is a hard ceiling), so + # it needs ~240 s to settle; it must still land on every Follow setting. + steady_gaps = [ + run_following_distance_simulation( + FOLLOW_TEST_SPEED_MPS, + t_end=240.0, + nap_follow_dist=nap_follow_dist, + ) + for nap_follow_dist in NAP_FOLLOW_SETTINGS + ] + expected_gaps = [ + t_follow * FOLLOW_TEST_SPEED_MPS + STOP_DISTANCE_M + for t_follow in NAP_FOLLOW_TIMES_S + ] + + assert steady_gaps == pytest.approx(expected_gaps, abs=1.5) + assert np.all(np.diff(steady_gaps) > 0.0) + + +def test_max_follow_setting_recovers_from_a_close_lead_without_closing_first(): + maneuver = Maneuver( + "max follow recovery", + duration=60.0, + initial_speed=FOLLOW_TEST_SPEED_MPS, + lead_relevancy=True, + initial_distance_lead=20.0, + speed_lead_values=[FOLLOW_TEST_SPEED_MPS], + breakpoints=[0.0], + e2e=False, + nap_follow_dist=7, + ) + + valid, output = maneuver.evaluate() + assert valid + assert np.min(output[:, 6]) >= 19.5 + # Unified opens the gap and trickles back toward Follow 7 (53.5 m) with no + # closing lunge: never inside the 20 m start, never short of FD, still bounded. + assert 53.0 <= output[-1, 6] <= 53.5 + 30.0 + assert output[-1, 3] == pytest.approx(FOLLOW_TEST_SPEED_MPS, abs=0.5) + + +def test_max_follow_full_closed_loop_recovers_gap_with_production_fallback(monkeypatch): + samples, pedal_samples = _run_full_closed_loop_following(monkeypatch, nap_follow_dist=7) + disabled_grade_samples, _ = _run_full_closed_loop_following( + monkeypatch, + nap_follow_dist=7, + grade_compensation_scale=0.0, + ) + elapsed_s, gaps_m, speeds_mps, accelerations_mps2, planner_targets_mps2, vdas_targets_mps2, _ = samples.T + disabled_grade_speeds_mps = disabled_grade_samples[:, 2] + desired_gap_m = get_T_FOLLOW(nap_follow_dist=7) * FOLLOW_TEST_SPEED_MPS + STOP_DISTANCE_M + recovery_window = (elapsed_s >= FULL_LOOP_RECOVERY_END_S - 5.0) & (elapsed_s < FULL_LOOP_RECOVERY_END_S) + grade_window = elapsed_s >= FULL_LOOP_RECOVERY_END_S + settled_rolling_window = elapsed_s >= FULL_LOOP_ROLLING_RAMP_END_S + FULL_LOOP_GRADE_SETTLING_S + final_speed_window = elapsed_s >= FULL_LOOP_DURATION_S - 2.0 + + assert np.min(gaps_m) >= 19.5 + # This loop follows *at* MAX (vCruise = lead). Rematch +a is gated + # there — do not chase past set to close FD — so the delayed pedal + # plant opens past 53.5 m instead of punching back by t=70. Still + # must have opened off the 20 m start, and not hang at Bosch range. + recovery_gap_m = float(np.mean(gaps_m[recovery_window])) + assert recovery_gap_m >= desired_gap_m - 2.0 + assert recovery_gap_m <= desired_gap_m + 65.0 + assert np.mean(speeds_mps[recovery_window]) == pytest.approx(FOLLOW_TEST_SPEED_MPS, abs=0.8) + assert gaps_m[-1] >= desired_gap_m - 2.0 + # Delayed pedal plant + Accel envelope / MPC mild floor: last-2 s settle + # is a bit lazier than the old 0.2 m/s band (~0.4 m/s observed). + assert np.mean(speeds_mps[final_speed_window]) == pytest.approx(FOLLOW_TEST_SPEED_MPS, abs=0.5) + assert np.max(speeds_mps[settled_rolling_window]) <= FOLLOW_TEST_SPEED_MPS + 0.1 + + assert np.min(accelerations_mps2) >= -1.0 + # Unified opens the 20 m start gap hard (speed dips ~5 m/s) and recovers + # with up to ~+0.9 planner / ~+1.1 plant accel; still jerk-limited below. + assert np.max(accelerations_mps2) <= 1.2 + assert np.max(np.abs(np.diff(accelerations_mps2) / FULL_LOOP_DT_S)) <= 1.5 + assert np.max(np.diff(pedal_samples)) <= PEDAL_RAMP_RATE_UP + 1e-9 + assert np.min(np.diff(pedal_samples)) >= -PEDAL_RAMP_RATE_DOWN - 1e-9 + assert np.min(pedal_samples) >= FULL_LOOP_PEDAL_DI_BP[0] + assert np.max(pedal_samples) <= FULL_LOOP_PEDAL_DI_BP[-1] + assert np.max(np.abs(np.minimum(planner_targets_mps2, 0.8) - vdas_targets_mps2)) <= 1e-9 + + compensated_speed_error = np.trapezoid( + np.abs(speeds_mps[grade_window] - FOLLOW_TEST_SPEED_MPS), + elapsed_s[grade_window], + ) + disabled_speed_error = np.trapezoid( + np.abs(disabled_grade_speeds_mps[grade_window] - FOLLOW_TEST_SPEED_MPS), + elapsed_s[grade_window], + ) + assert np.max(np.abs(speeds_mps[grade_window] - FOLLOW_TEST_SPEED_MPS)) <= 1.25 + assert compensated_speed_error <= 0.5 * disabled_speed_error + + +def test_plant_aligned_full_closed_loop_grade_compensation_holds_speed(monkeypatch): + samples, _ = _run_full_closed_loop_following( + monkeypatch, + nap_follow_dist=7, + plant_aligned_feedforward=True, + ) + elapsed_s, gaps_m, speeds_mps, accelerations_mps2, _, vdas_targets_mps2, pitches_rad = samples.T + desired_gap_m = get_T_FOLLOW(nap_follow_dist=7) * FOLLOW_TEST_SPEED_MPS + STOP_DISTANCE_M + uphill_window = ( + (elapsed_s >= FULL_LOOP_UPHILL_RAMP_END_S + FULL_LOOP_GRADE_SETTLING_S) + & (elapsed_s < FULL_LOOP_UPHILL_HOLD_END_S) + ) + crest_window = ( + (elapsed_s >= FULL_LOOP_CREST_RAMP_END_S + FULL_LOOP_GRADE_SETTLING_S) + & (elapsed_s < FULL_LOOP_CREST_HOLD_END_S) + ) + rolling_window = elapsed_s >= FULL_LOOP_ROLLING_RAMP_END_S + FULL_LOOP_GRADE_SETTLING_S + + assert np.min(gaps_m) >= 19.5 + assert gaps_m[-1] >= desired_gap_m - 2.0 + for window, expected_pitch_rad in ( + (uphill_window, FULL_LOOP_UPHILL_PITCH_RAD), + (crest_window, FULL_LOOP_CREST_PITCH_RAD), + (rolling_window, FULL_LOOP_ROLLING_PITCH_RAD), + ): + assert pitches_rad[window] == pytest.approx(np.full(np.count_nonzero(window), expected_pitch_rad)) + # Delayed pedal plant + settle opening deadband: first hold-window + # sample can sit ~0.015 m/s under 24.5 while already recovering + # (24.485 → 24.50 within a few frames). Production fallback still + # holds 25 ± 0.5. Do not restore Accel-ceil rematch (49→59) for + # this 0.03 mph. + assert np.min(speeds_mps[window]) >= FOLLOW_TEST_SPEED_MPS - 0.52 + assert np.max(speeds_mps[window]) <= FOLLOW_TEST_SPEED_MPS + 0.5 + + for phase_end_s in ( + FULL_LOOP_UPHILL_HOLD_END_S, + FULL_LOOP_CREST_HOLD_END_S, + FULL_LOOP_DURATION_S, + ): + tracking_window = (elapsed_s >= phase_end_s - 2.0) & (elapsed_s < phase_end_s) + # Delayed pedal + rematch trickle (0.08) then MILD (−0.22) at a + # grade step: plant lag mean is ~0.129. Not a safety bound. + assert np.mean(np.abs( + accelerations_mps2[tracking_window] - vdas_targets_mps2[tracking_window] + )) <= 0.14 + + +def test_planner_far_closing_lead_blocks_rematch_plus_a(): + """First far closing lock must not rematch cruise +a (d7 20:33).""" + v_ego = 25.0 + v_rel = 1.6 + v_lead = v_ego - v_rel + params = _MutablePlannerParams(nap_follow_dist=4, map_speed_accel=5) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner._map_speed_accel = 5 + a_cap = 0.80 + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=1.5) + planner.prev_accel_clip = [-1.2, a_cap] + inputs = _make_planner_inputs(v_ego) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = 160.0 + lead.vLead = v_lead + lead.aLeadK = 0.0 + lead.modelProb = 1.0 + lead.radar = True + planner.update(inputs) + assert planner.output_a_target <= 0.0 + for _ in range(15): + planner.update(inputs) + # Never rematch +a into a far closing lock. Extra match-speed −a + # stays near-gap so 160 m / 1.6 m/s cannot punch −0.40. + assert planner.output_a_target <= 0.0 + assert planner.output_a_target >= -LEAD_APPROACH_MILD_A_MS2 - 0.08 + + +def test_planner_slow_close_inside_fd_commands_mild_not_dump(): + """e8: inside FD still closing ~1.25 m/s — MILD floor, not rematch +a or −2.5.""" + v_ego = 30.0 + v_rel = 1.25 + v_lead = v_ego - v_rel + t_follow = get_T_FOLLOW(nap_follow_dist=2) + d_follow = t_follow * v_lead + STOP_DISTANCE_M + params = _MutablePlannerParams(nap_follow_dist=2, map_speed_accel=5) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner._map_speed_accel = 5 + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-2.0) + planner.prev_accel_clip = [-3.5, 0.80] + planner.output_a_target = 0.0 + inputs = _make_planner_inputs(v_ego) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = d_follow - 2.0 + lead.vLead = v_lead + lead.aLeadK = 0.0 + lead.modelProb = 1.0 + lead.radar = True + for _ in range(4): + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-2.0) + planner.update(inputs) + a = float(planner.output_a_target) + assert a == pytest.approx(-LEAD_APPROACH_MILD_A_MS2, abs=0.15) + assert a > -1.0 + + +def test_planner_hard_close_keeps_full_authority(): + """Rapid / near-bumper / FCW still apply full MPC −a after the glide work.""" + v_ego = 25.0 + params = _MutablePlannerParams(nap_follow_dist=4, map_speed_accel=5) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner._map_speed_accel = 5 + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-2.0) + planner.prev_accel_clip = [-3.5, 0.80] + planner.output_a_target = 0.0 + inputs = _make_planner_inputs(v_ego) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = 40.0 + lead.vLead = v_ego - 8.0 + lead.aLeadK = 0.0 + lead.modelProb = 1.0 + lead.radar = True + planner.update(inputs) + # First frame of a hard-closing lead: at least as firm as the lead-free MPC + # command (-2.0), within the brake limit. + assert -3.5 <= planner.output_a_target <= -1.7 + + lead.vLead = v_ego - 2.0 + lead.dRel = 12.0 + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-2.0) + planner.update(inputs) + assert -3.5 <= planner.output_a_target <= -1.7 + + lead.dRel = 40.0 + lead.vLead = v_ego + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-2.0) + planner.mpc.crash_cnt = 3 + planner.update(inputs) + assert -3.5 <= planner.output_a_target <= -1.7 + + +def test_planner_lead_flicker_hold_blocks_rematch_plus_a(): + """leadOne flicker must not restore cruise +a while the last lead was closing.""" + v_ego = 27.5 + v_lead = 24.5 + v_rel = v_ego - v_lead + assert v_rel >= 1.5 + params = _MutablePlannerParams(nap_follow_dist=2, map_speed_accel=5) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner._map_speed_accel = 5 + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.80) + planner.prev_accel_clip = [-1.2, 0.80] + inputs = _make_planner_inputs(v_ego) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = 100.0 + lead.vLead = v_lead + lead.aLeadK = -0.20 + lead.modelProb = 0.6 + lead.radar = True + for _ in range(6): + planner.update(inputs) + assert planner.output_a_target <= 0.0 + + publisher = _CapturingPubMaster() + planner.publish(inputs, publisher) + assert publisher.message.longitudinalPlan.hasLead + + lead.status = False + for _ in range(int(LEAD_CLOSE_HOLD_S / 0.05) - 1): + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.80) + planner.update(inputs) + assert planner.output_a_target <= 0.0 + assert planner._lead_close_hold_d is not None + planner.publish(inputs, publisher) + assert publisher.message.longitudinalPlan.hasLead + + +def test_planner_far_radar_lead_eases_without_model_prob(): + """Far Bosch-associated lead is owned immediately; vision-only far flicker is not.""" + v_ego = 28.0 + v_lead = 24.5 + params = _MutablePlannerParams(nap_follow_dist=2, map_speed_accel=5) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.80) + planner.prev_accel_clip = [-1.2, 0.80] + inputs = _make_planner_inputs(v_ego) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = 170.0 + lead.vLead = v_lead + lead.aLeadK = -0.15 + lead.modelProb = 0.15 + lead.radar = True + for _ in range(8): + planner.update(inputs) + assert planner.output_a_target <= 0.0 + + lead.radar = False + lead.modelProb = 0.9 + planner._lead_close_hold_d = None + planner._lead_close_hold_v = None + planner._lead_close_hold_a = None + planner._lead_close_hold_owned = False + planner._lead_approach_active = False + planner._lead_approach_a = None + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.80) + planner.prev_accel_clip = [-1.2, 0.80] + for _ in range(8): + planner.update(inputs) + assert planner.output_a_target > 0.20 + + +def test_planner_hwy_intent_applies_hwy_fd_from_30(): + """MAX ≥ 50 selects highway follow even while ego is still at 35.""" + v_ego = 35.0 * CV.MPH_TO_MS + v_max_kph = 65.0 * CV.MPH_TO_KPH + params = _MutablePlannerParams(nap_follow_dist=6, city=6, hwy=2) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.0) + inputs = _make_planner_inputs(v_ego) + inputs["carState"].vCruise = v_max_kph + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = 40.0 + lead.vLead = v_ego + lead.modelProb = 1.0 + lead.radar = True + planner._follow_blend.t_follow = get_T_FOLLOW(nap_follow_dist=6) + planner._follow_blend.highway = False + planner.update(inputs) + assert planner.active_nap_follow_dist == 2 + assert planner.t_follow < get_T_FOLLOW(nap_follow_dist=6) + assert planner._follow_blend.highway is True + # MAX 45 at 55 mph stays city. + v55 = 55.0 * CV.MPH_TO_MS + planner55 = LongitudinalPlanner(_make_preap_params(), init_v=v55, params=params) + planner55.mpc = _ConstantAccelerationMpc(v55, acceleration_mps2=0.0) + inputs55 = _make_planner_inputs(v55) + inputs55["carState"].vCruise = 45.0 * CV.MPH_TO_KPH + lead55 = inputs55["radarState"].leadOne + lead55.status = True + lead55.dRel = 50.0 + lead55.vLead = v55 + lead55.modelProb = 1.0 + lead55.radar = True + planner55.update(inputs55) + assert planner55.active_nap_follow_dist == 6 + assert planner55._follow_blend.highway is False + # ego 60 + MAX 45 stays city. MAX exactly 50 is highway. + # Decel to ~48 under MAX 75 stays highway (do not open the city gap). + v60 = 60.0 * CV.MPH_TO_MS + planner60 = LongitudinalPlanner(_make_preap_params(), init_v=v60, params=params) + planner60.mpc = _ConstantAccelerationMpc(v60, acceleration_mps2=0.0) + inputs60 = _make_planner_inputs(v60) + inputs60["carState"].vCruise = 45.0 * CV.MPH_TO_KPH + lead60 = inputs60["radarState"].leadOne + lead60.status = True + lead60.dRel = 40.0 + lead60.vLead = v60 + lead60.modelProb = 1.0 + lead60.radar = True + planner60._follow_blend.highway = True + planner60._follow_blend.t_follow = get_T_FOLLOW(nap_follow_dist=2) + planner60.update(inputs60) + assert planner60.active_nap_follow_dist == 6 + assert planner60._follow_blend.highway is False + + v48 = 47.7 * CV.MPH_TO_MS + planner48 = LongitudinalPlanner(_make_preap_params(), init_v=v48, params=params) + planner48.mpc = _ConstantAccelerationMpc(v48, acceleration_mps2=0.0) + inputs48 = _make_planner_inputs(v48) + inputs48["carState"].vCruise = 75.0 * CV.MPH_TO_KPH + lead48 = inputs48["radarState"].leadOne + lead48.status = True + lead48.dRel = 35.0 + lead48.vLead = v48 + lead48.modelProb = 1.0 + lead48.radar = True + planner48.update(inputs48) + assert planner48._follow_blend.highway is True + assert planner48.active_nap_follow_dist == 2 + + planner50 = LongitudinalPlanner(_make_preap_params(), init_v=v48, params=params) + planner50.mpc = _ConstantAccelerationMpc(v48, acceleration_mps2=0.0) + inputs50 = _make_planner_inputs(v48) + inputs50["carState"].vCruise = 50.0 * CV.MPH_TO_KPH + lead50 = inputs50["radarState"].leadOne + lead50.status = True + lead50.dRel = 35.0 + lead50.vLead = v48 + lead50.modelProb = 1.0 + lead50.radar = True + planner50.update(inputs50) + assert planner50._follow_blend.highway is True + assert planner50.active_nap_follow_dist == 2 + + # Unset cruise (255) must not look like a highway MAX after the 145 kph clamp. + v30 = 30.0 * CV.MPH_TO_MS + planner_unset = LongitudinalPlanner(_make_preap_params(), init_v=v30, params=params) + planner_unset.mpc = _ConstantAccelerationMpc(v30, acceleration_mps2=0.0) + inputs_unset = _make_planner_inputs(v30) + inputs_unset["carState"].vCruise = 255.0 + lead_unset = inputs_unset["radarState"].leadOne + lead_unset.status = True + lead_unset.dRel = 30.0 + lead_unset.vLead = v30 + lead_unset.modelProb = 1.0 + lead_unset.radar = True + planner_unset.update(inputs_unset) + assert planner_unset._follow_blend.highway is False + assert planner_unset.active_nap_follow_dist == 6 + + +def test_planner_faster_lead_at_max_does_not_overrun(): + """ea 11:46: lead faster than a 60 MAX must not rematch Accel-1 past set. + + Product: hold ≤ MAX and let the gap open. Overlay ease / emergency −a + still win. A slower lead under MAX still catch-up. + """ + from openpilot.selfdrive.mapd.constants import LOOKAHEAD_NORMAL, map_accel_a_ms2 + a_min = map_accel_a_ms2(LOOKAHEAD_NORMAL, 1) + v_max = 60.0 * CV.MPH_TO_MS + v_ego = v_max + v_lead = v_max + 3.0 * CV.MPH_TO_MS + t_follow = get_T_FOLLOW(nap_follow_dist=4) + d_follow = t_follow * v_lead + STOP_DISTANCE_M + params = _MutablePlannerParams(nap_follow_dist=4, map_speed_accel=1) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner._map_speed_accel = 1 + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.0) + planner.prev_accel_clip = [-1.2, a_min] + inputs = _make_planner_inputs(v_ego) + _set_v_cruise_ms(inputs, v_max) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = d_follow + 40.0 + lead.vLead = v_lead + lead.aLeadK = 0.0 + lead.modelProb = 1.0 + lead.radar = True + for _ in range(16): + planner.update(inputs) + assert planner.output_a_target <= 1e-6 + + # Ego already 1 mph over, lead 2 mph over: no +0.36 rematch punch. + v_over = v_max + 1.0 * CV.MPH_TO_MS + planner_over = LongitudinalPlanner(_make_preap_params(), init_v=v_over, params=params) + planner_over._map_speed_accel = 1 + planner_over.mpc = _ConstantAccelerationMpc(v_over, acceleration_mps2=0.0) + planner_over.prev_accel_clip = [-1.2, a_min] + inputs_over = _make_planner_inputs(v_over) + _set_v_cruise_ms(inputs_over, v_max) + lead_over = inputs_over["radarState"].leadOne + lead_over.status = True + lead_over.dRel = 58.0 + lead_over.vLead = v_max + 2.0 * CV.MPH_TO_MS + lead_over.aLeadK = 0.0 + lead_over.modelProb = 1.0 + lead_over.radar = True + for _ in range(16): + planner_over.update(inputs_over) + assert planner_over.output_a_target <= 1e-6 + assert planner_over.output_a_target < a_min - 0.10 + + # Slower / same-speed lead under MAX still catch-up. + v_under = 55.0 * CV.MPH_TO_MS + v_cruise = 70.0 * CV.MPH_TO_MS + planner_u = LongitudinalPlanner(_make_preap_params(), init_v=v_under, params=params) + planner_u._map_speed_accel = 1 + planner_u.mpc = _ConstantAccelerationMpc(v_under, acceleration_mps2=1.5) + planner_u.prev_accel_clip = [-1.2, a_min] + inputs_u = _make_planner_inputs(v_under) + _set_v_cruise_ms(inputs_u, v_cruise) + lead_u = inputs_u["radarState"].leadOne + lead_u.status = True + lead_u.dRel = 160.0 + lead_u.vLead = v_under + lead_u.modelProb = 1.0 + lead_u.radar = True + for _ in range(16): + planner_u.update(inputs_u) + assert 0.0 < planner_u.output_a_target <= 0.80 + 1e-6 + + # Emergency −a still owns at MAX (FCW / crash). + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-2.0) + planner.mpc.crash_cnt = 3 + planner.update(inputs) + assert planner.output_a_target == pytest.approx(-2.0, abs=0.08) + + +def _planner_past_acquire(v_ego, nap_follow_dist=1): + """Pre-AP planner with the first-latch window already expired.""" + params = _MutablePlannerParams(nap_follow_dist=nap_follow_dist, map_speed_accel=5) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner._map_speed_accel = 5 + planner.prev_accel_clip = [-3.5, 1.6] + planner.output_a_target = 0.0 + inputs = _make_planner_inputs(v_ego) + _set_v_cruise_ms(inputs, v_ego + 8.0) + return planner, inputs + + +def test_planner_opening_lead_does_not_hold_firm_brake(): + """10:05 / 09:57: opening on-path lead with a slightly negative aLeadK. + + MPC asking −3.5 must publish the mild floor, not the firm hold. + """ + v_ego = 71.3 * CV.MPH_TO_MS + v_lead = v_ego + 0.56 + t_follow = get_T_FOLLOW(nap_follow_dist=1) + slack = 9.0 + planner, inputs = _planner_past_acquire(v_ego, nap_follow_dist=1) + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = t_follow * v_lead + STOP_DISTANCE_M + slack + lead.vLead = v_lead + lead.aLeadK = -0.32 + lead.yRel = 0.36 + lead.modelProb = 1.0 + lead.radar = True + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.0) + for _ in range(3): + lead.dRel += 0.05 + planner.update(inputs) + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-3.5) + planner.prev_accel_clip = [-3.5, 1.6] + for _ in range(4): + lead.dRel += 0.08 + planner.update(inputs) + assert float(planner.output_a_target) > -1.0 + # Unified follows the lead's own -0.32 m/s^2 decel here (mild, never the firm hold). + assert float(planner.output_a_target) == pytest.approx(-LEAD_APPROACH_MILD_A_MS2, abs=0.15) + + +def test_planner_on_path_close_stays_firm(): + """08:57:50 on-path close stays firm; |yRel| past ~2.25 m with slack releases it.""" + v_ego = 36.0 * CV.MPH_TO_MS + v_close = 4.2 + v_lead = v_ego - v_close + t_follow = get_T_FOLLOW(nap_follow_dist=1) + slack = 12.0 + planner, inputs = _planner_past_acquire(v_ego, nap_follow_dist=1) + lead = inputs["radarState"].leadOne + lead.status = True + lead.vLead = v_lead + lead.dRel = t_follow * v_lead + STOP_DISTANCE_M + slack + lead.aLeadK = -2.06 + lead.yRel = 0.48 + lead.modelProb = 1.0 + lead.radar = True + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-3.5) + planner.update(inputs) + assert float(planner.output_a_target) < -2.0 + + # Departing-lead release lives in the lead-leaving estimator (test_lead_leaving.py). + for i in range(4): + lead.yRel = 0.48 + (i + 1) * 0.05 + planner.update(inputs) + assert float(planner.output_a_target) < -2.0 + + +def test_planner_hot_close_profile_eases_before_slack_30_and_firm_lead_stays(): + """4.1 m/s from 65 m slack, aEgo stuck at −0.08. + + Reaches ≤ −0.26 before slack 30 m, never below −0.55 before slack 3 m. + A matched lead is not eased. Firm early brake at 20–50 m is unchanged. + """ + from openpilot.selfdrive.controls.lib.lead_approach import ( + lead_firm_large_slack_a, + ) + v_rel = 4.1 + v_ego = 31.1 + v_lead = v_ego - v_rel + t_follow = get_T_FOLLOW(nap_follow_dist=4) + slack = 65.0 + dt = FULL_LOOP_PLANNER_DT_S + params = _MutablePlannerParams(nap_follow_dist=4) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + inputs = _make_planner_inputs(v_ego) + inputs["carState"].aEgo = -0.08 + lead = inputs["radarState"].leadOne + lead.status = True + lead.vLead = v_lead + lead.aLeadK = 0.0 + lead.radar = True + lead.modelProb = 1.0 + lead.radarTrackId = 7 + saw = False + min_a = 0.0 + while slack > 3.0: + lead.dRel = t_follow * v_lead + STOP_DISTANCE_M + slack + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.0) + planner.update(inputs) + a = float(planner.output_a_target) + assert a >= -1.0 + min_a = min(min_a, a) + if slack > 30.0 and a <= -0.26: + saw = True + slack -= v_rel * dt + assert saw + + # Matched radar lead: profile does not pull a decel. + planner_m = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + inputs_m = _make_planner_inputs(v_ego) + inputs_m["carState"].aEgo = -0.08 + lead_m = inputs_m["radarState"].leadOne + lead_m.status = True + lead_m.vLead = v_ego + lead_m.aLeadK = 0.0 + lead_m.radar = True + lead_m.modelProb = 1.0 + lead_m.radarTrackId = 3 + d_follow = t_follow * v_ego + STOP_DISTANCE_M + lead_m.dRel = d_follow + 20.0 + for _ in range(40): + planner_m.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=0.0) + planner_m.update(inputs_m) + assert float(planner_m.output_a_target) > -0.10 + + # Firm lead, 40 m slack, closing 4 m/s: early brake, not the −0.28 clamp. + v_firm = 30.0 + planner_f = LongitudinalPlanner(_make_preap_params(), init_v=v_firm, params=params) + inputs_f = _make_planner_inputs(v_firm) + lead_f = inputs_f["radarState"].leadOne + lead_f.status = True + lead_f.vLead = v_firm - 4.0 + lead_f.aLeadK = -0.8 + lead_f.radar = True + lead_f.modelProb = 1.0 + lead_f.radarTrackId = 11 + slack_f = 40.0 + lead_f.dRel = t_follow * lead_f.vLead + STOP_DISTANCE_M + slack_f + planner_f.mpc = _ConstantAccelerationMpc(v_firm, acceleration_mps2=-0.22) + planner_f.prev_accel_clip = [-3.5, 1.6] + outs = [] + for _ in range(40): + planner_f.mpc = _ConstantAccelerationMpc(v_firm, acceleration_mps2=-0.22) + planner_f.update(inputs_f) + outs.append(float(planner_f.output_a_target)) + firm = lead_firm_large_slack_a(4.0, slack_f, -0.8) + assert firm is not None + # Unified ramps under the jerk limit: firm by 1 s, never past -1.5 (no brick wall). + assert outs[19] == pytest.approx(firm, abs=0.1) + assert min(outs) >= -1.5 diff --git a/selfdrive/controls/tests/test_tesla_preap_gas_lift_handoff.py b/selfdrive/controls/tests/test_tesla_preap_gas_lift_handoff.py new file mode 100644 index 00000000000000..5ed104c2984934 --- /dev/null +++ b/selfdrive/controls/tests/test_tesla_preap_gas_lift_handoff.py @@ -0,0 +1,193 @@ +"""Gas-lift long handoff: expire engage grace and seed climb + aEgo. + +A+B expire grace / last non-negative aEgo. A3 also seeds Mannerisms +Accel 1–10 (planner climb toward MAX). Lead / FCW still win. No +PostEngageCoast / pedal-hold / GAS_COMMAND rewrite. +""" + +from types import SimpleNamespace + +import pytest + +from opendbc.car.tesla.preap.carcontroller import ( + ENGAGE_GRACE_FRAMES, + PedalCommandAction, + PreAPLongController, + gas_lift_handoff_seed_accel, +) +from opendbc.car.tesla.preap.engagement import PreAPEngagement +from opendbc.car.tesla.preap.nap_conf import PEDAL_MAX_VALUES +from opendbc.car.tesla.preap.pedal_feedback import PedalFeedback +from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP + + +def _pedal_conf(): + return SimpleNamespace( + use_pedal=True, + pedal_factor=1.0, + di_to_pedal=lambda pedal_di: pedal_di, + get_pedal_profile_values=lambda: PEDAL_MAX_VALUES, + ) + + +def _zero_torque(): + return SimpleNamespace( + get=lambda _v_ego: 0.0, + update=lambda *_args, **_kwargs: None, + ) + + +@pytest.fixture +def controller_env(monkeypatch): + zero_torque = _zero_torque() + monkeypatch.setattr('opendbc.car.tesla.preap.carcontroller.nap_conf', _pedal_conf()) + monkeypatch.setattr('opendbc.car.tesla.preap.carcontroller.get_zero_torque', lambda: zero_torque) + monkeypatch.setattr('opendbc.car.tesla.preap.virtual_das.nap_conf', _pedal_conf()) + monkeypatch.setattr('opendbc.car.tesla.preap.virtual_das.get_zero_torque', lambda: zero_torque) + + feedback = PedalFeedback() + feedback.update({"INTERCEPTOR_GAS": 0.0, "INTERCEPTOR_GAS2": 0.0, "STATE": 0, "IDX": 1}, 0) + engagement = PreAPEngagement(double_pull_enabled=False, double_pull_window_ms=750) + cs = SimpleNamespace( + cruiseEnabled=False, + enableLongControl=False, + enableJustCC=False, + engagement=engagement, + real_brake_pressed=False, + out=SimpleNamespace(vEgo=15.0, aEgo=0.0, gasPressed=False), + pedal_interceptor_value=0.0, + cruise_buttons=0, + prev_cruise_buttons=0, + pedal=feedback, + pedal_timeout=feedback.timeout, + pccEvent=None, + preap_cc_cancel_needed=False, + ) + cc = SimpleNamespace( + actuators=SimpleNamespace(accel=0.0), + longActive=False, + orientationNED=[], + ) + return PreAPLongController(), cc, cs, TeslaCANPreAP({}) + + +def _activate_longitudinal(cc, cs): + cs.engagement.cruiseEnabled = True + cs.engagement.enableLongControl = True + cs.cruiseEnabled = True + cs.enableLongControl = True + cc.longActive = True + + +def test_gas_lift_handoff_seed_uses_non_negative_aego(): + assert gas_lift_handoff_seed_accel(0.62, -0.4, 0.8, 0.5) == pytest.approx(0.62) + assert gas_lift_handoff_seed_accel(-0.3, 0.41, 0.8, 0.5) == pytest.approx(0.5) + assert gas_lift_handoff_seed_accel(-0.3, -0.2, 0.8, 0.5) == pytest.approx(0.5) + + +def test_gas_lift_handoff_seed_max_brake_and_lead_win(): + assert gas_lift_handoff_seed_accel(1.618, 0.1, 0.8, 0.67) == pytest.approx(0.8) + assert gas_lift_handoff_seed_accel(0.62, 0.1, 0.8, -1.2) == pytest.approx(0.0) + assert gas_lift_handoff_seed_accel(0.62, 0.1, 0.8, float('nan')) == pytest.approx(0.0) + + +def test_engage_without_prior_gas_keeps_grace_floor(controller_env): + controller, cc, cs, tesla_can = controller_env + _activate_longitudinal(cc, cs) + cs.out.aEgo = 0.55 + cc.actuators.accel = 0.67 + + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + + assert controller.preap_long_engage_frame == 0 + assert controller.vdas.jerk_limiter.a_limited == pytest.approx(0.0) + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + + +def test_gas_lift_after_long_engage_does_not_floor_a_for_half_second(controller_env, monkeypatch): + controller, cc, cs, tesla_can = controller_env + monkeypatch.setattr( + 'opendbc.car.tesla.preap.carcontroller.get_preap_accel_limits', + lambda _v_ego: (-1.5, 0.8), + ) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + + cs.out.gasPressed = True + cs.out.aEgo = 0.72 + cc.longActive = False + for frame in range(2, 20, 2): + controller.update(cc, cs, frame=frame, tesla_can=tesla_can, can_bus_party=0) + + cs.out.gasPressed = False + cs.out.aEgo = 0.08 + cc.longActive = True + cc.actuators.accel = 0.55 + limited = {} + for frame in range(20, 72, 2): + controller.update(cc, cs, frame=frame, tesla_can=tesla_can, can_bus_party=0) + limited[frame] = controller.vdas.jerk_limiter.a_limited + + assert (20 - controller.preap_long_engage_frame) >= ENGAGE_GRACE_FRAMES + assert limited[20] == pytest.approx(0.72, abs=0.08) + assert min(limited.values()) > 0.35 + + +def test_gas_lift_open_road_seed_uses_mannerisms_accel_not_only_aego(): + """A3: Accel 1–10 climb (planner) seeds takeover, not only post-lift aEgo.""" + from openpilot.selfdrive.mapd.constants import LOOKAHEAD_NORMAL, map_accel_a_ms2 + + a1 = map_accel_a_ms2(LOOKAHEAD_NORMAL, 1) + a5 = map_accel_a_ms2(LOOKAHEAD_NORMAL, 5) + a10 = map_accel_a_ms2(LOOKAHEAD_NORMAL, 10) + assert a1 < a5 < a10 + # Post-lift aEgo is near 0; temperament climb must still seed. + assert gas_lift_handoff_seed_accel(0.08, 0.05, 0.8, a1) == pytest.approx(a1) + assert gas_lift_handoff_seed_accel(0.08, 0.05, 0.8, a5) == pytest.approx(a5) + # MAX / personality envelope still caps Accel 10. + assert gas_lift_handoff_seed_accel(0.08, 0.05, 0.8, a10) == pytest.approx(0.8) + + +def test_gas_lift_after_long_engage_climbs_at_planner_accel(controller_env, monkeypatch): + controller, cc, cs, tesla_can = controller_env + monkeypatch.setattr( + 'opendbc.car.tesla.preap.carcontroller.get_preap_accel_limits', + lambda _v_ego: (-1.5, 0.8), + ) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + + cs.out.gasPressed = True + cs.out.aEgo = 0.72 + cc.longActive = False + for frame in range(2, 20, 2): + controller.update(cc, cs, frame=frame, tesla_can=tesla_can, can_bus_party=0) + + cs.out.gasPressed = False + cs.out.aEgo = 0.08 + cc.longActive = True + cc.actuators.accel = 0.80 # Accel 5 open-road climb + controller.update(cc, cs, frame=20, tesla_can=tesla_can, can_bus_party=0) + assert controller.vdas.jerk_limiter.a_limited == pytest.approx(0.80, abs=0.08) + + +def test_gas_lift_lead_hard_decel_still_wins(controller_env, monkeypatch): + controller, cc, cs, tesla_can = controller_env + monkeypatch.setattr( + 'opendbc.car.tesla.preap.carcontroller.get_preap_accel_limits', + lambda _v_ego: (-1.5, 0.8), + ) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + cs.out.gasPressed = True + cs.out.aEgo = 0.72 + cc.longActive = False + controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + + cs.out.gasPressed = False + cc.longActive = True + cc.actuators.accel = -1.2 + controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) + + assert (4 - controller.preap_long_engage_frame) >= ENGAGE_GRACE_FRAMES + assert controller.vdas.jerk_limiter.a_limited < 0.0 diff --git a/selfdrive/controls/tests/test_tesla_preap_longcontrol.py b/selfdrive/controls/tests/test_tesla_preap_longcontrol.py new file mode 100644 index 00000000000000..bcd649b437600e --- /dev/null +++ b/selfdrive/controls/tests/test_tesla_preap_longcontrol.py @@ -0,0 +1,331 @@ +"""Pre-AP planner-target contracts at the LongControl output seam.""" + +from dataclasses import dataclass +from types import SimpleNamespace + +import pytest +from cereal import car +from opendbc.car.tesla.preap.constants import ( + PEDAL_LONG_K_BP, + PEDAL_LONG_KI_V, + PEDAL_LONG_KP_V, + VDAS_ACCEL_JERK_MAX, + VDAS_DECEL_JERK_MAX, +) +from opendbc.car.tesla.preap.nap_conf import PEDAL_MAX_VALUES +from opendbc.car.tesla.preap.virtual_das import VirtualDAS +from opendbc.car.tesla.preap import virtual_das + +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.controls.lib.lead_approach import ( + LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2, + guard_follow_actuator_regen, + install_preap_plant_regen_guard, + plant_regen_effort_limits, +) +from openpilot.selfdrive.controls.lib.longcontrol import LongControl, LongCtrlState + + +ACCEL_LIMITS_MPS2 = (-1.5, 0.8) +PASSTHROUGH_TOLERANCE_MPS2 = 1e-9 +VDAS_DT_S = 0.02 +PEDAL_PLANT_DELAY_S = 0.40 +PEDAL_PLANT_TAU_S = 0.25 +PEDAL_PLANT_ACCEL_PER_DI_MPS2 = 0.063 +SETTLED_REGEN_WINDOW_S = 1.0 + + +@dataclass(frozen=True) +class _TracePhase: + duration_s: float + planner_target_end_mps2: float + road_load_end_mps2: float + + +def _make_preap_params(): + params = car.CarParams.new_message() + params.brand = "tesla" + params.carFingerprint = "TESLA_MODEL_S_PREAP" + params.openpilotLongitudinalControl = True + params.pcmCruise = False + params.longitudinalTuning.kpBP = PEDAL_LONG_K_BP + params.longitudinalTuning.kpV = PEDAL_LONG_KP_V + params.longitudinalTuning.kiBP = PEDAL_LONG_K_BP + params.longitudinalTuning.kiV = PEDAL_LONG_KI_V + params.longitudinalTuning.kf = 1.0 + params.vEgoStarting = 0.1 + return params + + +def _make_car_state(speed_mps): + state = car.CarState.new_message() + state.vEgo = speed_mps + state.brakePressed = False + state.cruiseState.standstill = False + return state + + +def _run_continuous_trace(long_control, state, phases): + planner_target_mps2 = 0.0 + road_load_mps2 = 0.0 + planner_targets_mps2 = [] + vdas_commands_mps2 = [] + + for phase in phases: + frame_count = round(phase.duration_s / DT_CTRL) + phase_start_target_mps2 = planner_target_mps2 + phase_start_road_load_mps2 = road_load_mps2 + planner_jerk_mps3 = ( + (phase.planner_target_end_mps2 - phase_start_target_mps2) / (frame_count * DT_CTRL) + ) + assert -VDAS_DECEL_JERK_MAX <= planner_jerk_mps3 <= VDAS_ACCEL_JERK_MAX, ( + f"planner trace jerk {planner_jerk_mps3:.3f} m/s^3 exceeds VDAS command bounds" + ) + + for frame_index in range(1, frame_count + 1): + phase_fraction = frame_index / frame_count + planner_target_mps2 = phase_start_target_mps2 + ( + phase.planner_target_end_mps2 - phase_start_target_mps2 + ) * phase_fraction + road_load_mps2 = phase_start_road_load_mps2 + ( + phase.road_load_end_mps2 - phase_start_road_load_mps2 + ) * phase_fraction + state.aEgo = planner_target_mps2 - road_load_mps2 + + vdas_command_mps2 = long_control.update( + active=True, + CS=state, + a_target=planner_target_mps2, + should_stop=False, + accel_limits=ACCEL_LIMITS_MPS2, + ) + planner_targets_mps2.append(planner_target_mps2) + vdas_commands_mps2.append(vdas_command_mps2) + + state.vEgo += state.aEgo * DT_CTRL + + return planner_targets_mps2, vdas_commands_mps2 + + +def _run_continuous_trace_through_pedal(long_control, vdas, state, phases, coast_pedal_di): + planner_target_mps2 = 0.0 + road_load_mps2 = 0.0 + pedal_di = coast_pedal_di + delayed_pedal_di = [coast_pedal_di] * round(PEDAL_PLANT_DELAY_S / VDAS_DT_S) + plant_alpha = VDAS_DT_S / (PEDAL_PLANT_TAU_S + VDAS_DT_S) + pedal_samples = [] + control_frame = 0 + + for phase in phases: + frame_count = round(phase.duration_s / DT_CTRL) + phase_start_target_mps2 = planner_target_mps2 + phase_start_road_load_mps2 = road_load_mps2 + planner_jerk_mps3 = ( + (phase.planner_target_end_mps2 - phase_start_target_mps2) / (frame_count * DT_CTRL) + ) + assert -VDAS_DECEL_JERK_MAX <= planner_jerk_mps3 <= VDAS_ACCEL_JERK_MAX, ( + f"planner trace jerk {planner_jerk_mps3:.3f} m/s^3 exceeds VDAS command bounds" + ) + + for frame_index in range(1, frame_count + 1): + phase_fraction = frame_index / frame_count + planner_target_mps2 = phase_start_target_mps2 + ( + phase.planner_target_end_mps2 - phase_start_target_mps2 + ) * phase_fraction + road_load_mps2 = phase_start_road_load_mps2 + ( + phase.road_load_end_mps2 - phase_start_road_load_mps2 + ) * phase_fraction + + vdas_command_mps2 = long_control.update( + active=True, + CS=state, + a_target=planner_target_mps2, + should_stop=False, + accel_limits=ACCEL_LIMITS_MPS2, + ) + if control_frame % round(VDAS_DT_S / DT_CTRL) == 0: + pedal_di = vdas.update( + vdas_command_mps2, + v_ego=state.vEgo, + prev_pedal_di=pedal_di, + a_ego=state.aEgo, + freeze_integrator=False, + orientation_ned=[0.0, 0.0, 0.0], + ) + applied_pedal_di = delayed_pedal_di.pop(0) + delayed_pedal_di.append(pedal_di) + plant_target_accel_mps2 = ( + (applied_pedal_di - coast_pedal_di) * PEDAL_PLANT_ACCEL_PER_DI_MPS2 + - road_load_mps2 + ) + state.aEgo += plant_alpha * (plant_target_accel_mps2 - state.aEgo) + pedal_samples.append((planner_target_mps2, pedal_di)) + + state.vEgo = max(0.0, state.vEgo + state.aEgo * DT_CTRL) + control_frame += 1 + + return pedal_samples + + +def test_road_load_history_cannot_reverse_finite_jerk_negative_planner_target(): + long_control = LongControl(_make_preap_params()) + state = _make_car_state(speed_mps=25.0) + phases = ( + _TracePhase(duration_s=0.5, planner_target_end_mps2=0.35, road_load_end_mps2=0.55), + _TracePhase(duration_s=4.0, planner_target_end_mps2=0.35, road_load_end_mps2=0.55), + _TracePhase(duration_s=0.4, planner_target_end_mps2=-0.25, road_load_end_mps2=0.55), + ) + + planner_targets_mps2, vdas_commands_mps2 = _run_continuous_trace(long_control, state, phases) + final_planner_target_mps2 = planner_targets_mps2[-1] + final_vdas_command_mps2 = vdas_commands_mps2[-1] + + failure_message = ( + f"planner reached {final_planner_target_mps2:.3f} m/s^2 through a finite-jerk transition after road load, " + + f"but VDAS received a positive {final_vdas_command_mps2:.3f} m/s^2 command" + ) + assert final_vdas_command_mps2 <= 0.0, failure_message + + +def test_vdas_receives_route_shaped_planner_target_trace_unchanged(): + long_control = LongControl(_make_preap_params()) + state = _make_car_state(speed_mps=22.0) + route_phases = ( + _TracePhase(duration_s=1.0, planner_target_end_mps2=0.40, road_load_end_mps2=0.20), + _TracePhase(duration_s=4.0, planner_target_end_mps2=0.40, road_load_end_mps2=0.50), + _TracePhase(duration_s=1.0, planner_target_end_mps2=0.00, road_load_end_mps2=0.20), + _TracePhase(duration_s=1.0, planner_target_end_mps2=-0.30, road_load_end_mps2=-0.10), + _TracePhase(duration_s=2.0, planner_target_end_mps2=-0.10, road_load_end_mps2=-0.20), + _TracePhase(duration_s=1.0, planner_target_end_mps2=0.30, road_load_end_mps2=0.00), + _TracePhase(duration_s=3.0, planner_target_end_mps2=0.30, road_load_end_mps2=0.45), + ) + + planner_targets_mps2, vdas_commands_mps2 = _run_continuous_trace(long_control, state, route_phases) + command_target_deltas_mps2 = [ + abs(command_mps2 - target_mps2) + for target_mps2, command_mps2 in zip(planner_targets_mps2, vdas_commands_mps2, strict=True) + ] + worst_sample_index = max(range(len(command_target_deltas_mps2)), key=command_target_deltas_mps2.__getitem__) + max_command_target_delta_mps2 = command_target_deltas_mps2[worst_sample_index] + planner_target_mps2 = planner_targets_mps2[worst_sample_index] + vdas_command_mps2 = vdas_commands_mps2[worst_sample_index] + + failure_message = ( + f"LongControl changed in-range planner target {planner_target_mps2:.6f} m/s^2 " + + f"to {vdas_command_mps2:.6f} m/s^2 before VDAS at trace sample {worst_sample_index}; " + + f"delta {max_command_target_delta_mps2:.6f} m/s^2" + ) + assert max_command_target_delta_mps2 <= PASSTHROUGH_TOLERANCE_MPS2, failure_message + + +def test_negative_planner_target_reaches_regen_side_of_coast_anchor(monkeypatch): + coast_pedal_di = 3.0 + zero_torque = SimpleNamespace(get=lambda _v_ego: coast_pedal_di) + controller_conf = SimpleNamespace(get_pedal_profile_values=lambda: PEDAL_MAX_VALUES) + monkeypatch.setattr(virtual_das, "get_zero_torque", lambda: zero_torque) + monkeypatch.setattr(virtual_das, "nap_conf", controller_conf) + + long_control = LongControl(_make_preap_params()) + vdas = VirtualDAS(dt=VDAS_DT_S) + state = _make_car_state(speed_mps=25.0) + phases = ( + _TracePhase(duration_s=0.5, planner_target_end_mps2=0.0, road_load_end_mps2=0.443), + _TracePhase(duration_s=12.0, planner_target_end_mps2=0.0, road_load_end_mps2=0.443), + _TracePhase(duration_s=0.8, planner_target_end_mps2=-0.20, road_load_end_mps2=0.20), + _TracePhase(duration_s=1.0, planner_target_end_mps2=-0.20, road_load_end_mps2=0.20), + ) + vdas.reset(measured_accel=0.0, commanded_accel=0.0, pedal_di_init=coast_pedal_di) + + pedal_samples = _run_continuous_trace_through_pedal( + long_control, + vdas, + state, + phases, + coast_pedal_di, + ) + settled_sample_count = round(SETTLED_REGEN_WINDOW_S / VDAS_DT_S) + settled_pedal_samples = pedal_samples[-settled_sample_count:] + + assert all(target_mps2 <= -0.15 for target_mps2, _pedal_di in settled_pedal_samples) + maximum_settled_pedal_di = max(pedal_di for _target_mps2, pedal_di in settled_pedal_samples) + assert maximum_settled_pedal_di <= coast_pedal_di - 0.05, ( + f"settled negative planner window reached {max(pedal_di for _, pedal_di in settled_pedal_samples):.3f} DI, " + + f"without moving meaningfully below the {coast_pedal_di:.3f} DI coast anchor" + ) + + +def test_preap_longcontrol_does_not_dump_regen_when_planner_near_zero(): + """ef 10:18:42: aTarget ≈ 0 + leftover +aEgo must not command −1.2.""" + long_control = LongControl(_make_preap_params()) + state = _make_car_state(speed_mps=30.0) + state.aEgo = 1.20 + # Prime PID state so the first update is LongCtrlState.pid. + long_control.long_control_state = LongCtrlState.pid + long_control.last_output_accel = 0.0 + commanded = long_control.update( + active=True, + CS=state, + a_target=0.0, + should_stop=False, + accel_limits=ACCEL_LIMITS_MPS2, + ) + assert commanded >= LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2 - 1e-9 + assert commanded > -1.00 + # Pre-AP LongControl is passthrough (kp=0, kf=1): a_target≈0 stays ~0. + # The plant dump is VirtualDAS inner-PID; this seam only clips if the + # actuator would go below MILD. + assert commanded == pytest.approx(0.0, abs=0.05) + assert guard_follow_actuator_regen(-1.23, 0.0) == pytest.approx(0.0) + + # Planner asked for firm regen: do not clip. + state.aEgo = 0.0 + long_control.last_output_accel = 0.0 + dumped = long_control.update( + active=True, + CS=state, + a_target=-1.20, + should_stop=False, + accel_limits=ACCEL_LIMITS_MPS2, + ) + assert dumped <= -1.00 + assert dumped == pytest.approx(-1.20, abs=0.05) + + +def test_preap_coasting_command_cannot_reach_regen_rail(): + """18:09:23 and 18:10:27.44: aTarget ≈ 0 must not act below about −0.25. + + LongControl is feedforward, so the rail is VirtualDAS effort. A wound + inner integral on a coasting command stays at the slight-lift floor. + """ + from opendbc.car.tesla.preap.virtual_das import VirtualDAS + + for planner_a in (-0.039, 0.008, 0.0): + commanded = guard_follow_actuator_regen(-1.50, planner_a) + # Steady / coast tracks the command. It does not settle at mild. + assert commanded == pytest.approx(min(planner_a, 0.0)) + assert commanded > LEAD_FOLLOW_ACT_REGEN_FLOOR_MS2 + + original = VirtualDAS.update + try: + install_preap_plant_regen_guard() + vdas = VirtualDAS(dt=VDAS_DT_S) + vdas.reset(measured_accel=0.0, commanded_accel=0.0, pedal_di_init=4.0) + vdas.inner_pid.i = -5.0 + vdas.update( + 0.008, v_ego=30.0, prev_pedal_di=4.0, a_ego=0.4, + accel_effort_limits=plant_regen_effort_limits(0.008, None), + ) + assert vdas.prev_accel_effort >= -0.05 + # The installed seam applies that bound even if the caller does not. + vdas.inner_pid.i = -5.0 + vdas.update(-0.039, v_ego=30.0, prev_pedal_di=vdas.prev_pedal_di, a_ego=0.2) + assert vdas.prev_accel_effort >= -0.08 + # Firm planner brake still reaches the rail. + vdas.inner_pid.i = -5.0 + pedal = vdas.prev_pedal_di + for _ in range(40): + pedal = vdas.update(-1.20, v_ego=30.0, prev_pedal_di=pedal, a_ego=0.0) + vdas.inner_pid.i = -5.0 + assert vdas.prev_accel_effort <= -1.00 + finally: + VirtualDAS.update = original diff --git a/selfdrive/controls/tests/test_tesla_preap_one_pedal_long.py b/selfdrive/controls/tests/test_tesla_preap_one_pedal_long.py new file mode 100644 index 00000000000000..04b507723d22d1 --- /dev/null +++ b/selfdrive/controls/tests/test_tesla_preap_one_pedal_long.py @@ -0,0 +1,790 @@ +"""One-Pedal Long: gas-from-rest silent long pause + RELEASE regen. + +Toggle On + OP long already on + accelerator rising from rest pauses +software long (same function as brake today — lat stays, not +USER_DISABLE / full session cancel) and **latches** that pause until +a stalk SET. Lift must not restore long / re-ACQUIRE. Engage-while- +gas-pressed (one or two SET pulls) then lift still arms / starts long +via A+B + A3. Brake pause does not use this latch. +""" +from types import SimpleNamespace + +import pytest + +from opendbc.car.tesla.preap.carcontroller import ( + PedalAuthorityState, + PedalCommandAction, + PreAPLongController, +) +from opendbc.car.tesla.preap.engagement import PreAPEngagement +from opendbc.car.tesla.preap.nap_conf import PEDAL_MAX_VALUES +from opendbc.car.tesla.preap.pedal_feedback import PedalFeedback +from opendbc.car.tesla.preap.teslacan import TeslaCANPreAP +from opendbc.car.tesla.preap.tests.test_pedal_authority import ( + _activate_longitudinal, + _decode_pedal_command, +) + + +def _pedal_conf(one_pedal_long=False): + return SimpleNamespace( + use_pedal=True, + pedal_factor=1.0, + di_to_pedal=lambda pedal_di: pedal_di, + get_pedal_profile_values=lambda: PEDAL_MAX_VALUES, + one_pedal_long=one_pedal_long, + ) + + +def _zero_torque(): + return SimpleNamespace( + get=lambda _v_ego: 0.0, + update=lambda *_args, **_kwargs: None, + ) + + +def controller_env(monkeypatch, one_pedal_long=False, double_pull=False): + zero_torque = _zero_torque() + conf = _pedal_conf(one_pedal_long=one_pedal_long) + monkeypatch.setattr('opendbc.car.tesla.preap.carcontroller.nap_conf', conf) + monkeypatch.setattr('opendbc.car.tesla.preap.carcontroller.get_zero_torque', lambda: zero_torque) + monkeypatch.setattr('opendbc.car.tesla.preap.virtual_das.nap_conf', conf) + monkeypatch.setattr('opendbc.car.tesla.preap.virtual_das.get_zero_torque', lambda: zero_torque) + + feedback = PedalFeedback() + feedback.update({"INTERCEPTOR_GAS": 0.0, "INTERCEPTOR_GAS2": 0.0, "STATE": 0, "IDX": 1}, 0) + engagement = PreAPEngagement(double_pull_enabled=double_pull, double_pull_window_ms=750) + cs = SimpleNamespace( + cruiseEnabled=False, + enableLongControl=False, + enableJustCC=False, + engagement=engagement, + real_brake_pressed=False, + out=SimpleNamespace(vEgo=20.0, aEgo=0.0, gasPressed=False), + pedal_interceptor_value=0.0, + cruise_buttons=0, + prev_cruise_buttons=0, + pedal=feedback, + pedal_timeout=feedback.timeout, + pccEvent=None, + preap_cc_cancel_needed=False, + ) + cc = SimpleNamespace( + actuators=SimpleNamespace(accel=0.4), + longActive=False, + orientationNED=[], + ) + return PreAPLongController(), cc, cs, TeslaCANPreAP({}) + + +def _kick_long_on_gas(cc, cs): + cs.engagement.maybe_one_pedal_gas_kick(False, True) + assert cs.engagement.maybe_one_pedal_gas_kick(True, True) + cs.enableLongControl = cs.engagement.enableLongControl + cs.enableJustCC = cs.engagement.enableJustCC + cc.longActive = False + cs.out.gasPressed = True + + +def test_toggle_off_gas_override_releases_then_reacquires(monkeypatch): + """Stock: gas does not drop enableLongControl; lift ACQUIREs (A+B).""" + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + assert cs.engagement.enableLongControl + + cs.out.gasPressed = True + cc.longActive = False + release = controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled + assert cs.engagement.enableLongControl + assert not cs.engagement.maybe_one_pedal_gas_kick(True, False) + + cs.out.gasPressed = False + cc.longActive = True + acquire = controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + + +def test_one_pedal_gas_kick_releases_and_stays_released_on_lift(monkeypatch): + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + + _kick_long_on_gas(cc, cs) + release = controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled + assert _decode_pedal_command(release[0]).raw_command == 0 + assert cs.pedal_authority_action == int(PedalCommandAction.RELEASE) + assert not cs.enableLongControl + assert cs.engagement.cruiseEnabled + assert cs.engagement._one_pedal_pause_latched + + cs.out.gasPressed = False + cs.engagement.maybe_one_pedal_gas_kick(False, True) + # On-car, gasPressedOverride ends on lift so CC.longActive goes True + # while the session stays up. Latch must still block ACQUIRE. + cc.longActive = True + silent = controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) + assert silent == [] + assert not cs.enableLongControl + assert cs.engagement._one_pedal_pause_latched + # No re-ACQUIRE / ENABLE chatter: interceptor stays out so Tesla + # physical pedal at zero is stock lift-regen. + assert controller.pedal_authority.state == PedalAuthorityState.INACTIVE + + +def test_one_pedal_press_after_kick_stays_pass_through(monkeypatch): + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + _kick_long_on_gas(cc, cs) + controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + + cs.out.gasPressed = False + cs.engagement.maybe_one_pedal_gas_kick(False, True) + controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) + + cs.out.gasPressed = True + cs.engagement.maybe_one_pedal_gas_kick(True, True) + assert controller.update(cc, cs, frame=6, tesla_can=tesla_can, can_bus_party=0) == [] + assert not cs.enableLongControl + + +def test_brake_cancel_still_works_with_one_pedal_on(monkeypatch): + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + cs.enableLongControl = False + cs.engagement.enableLongControl = False + cc.longActive = False + cs.real_brake_pressed = True + cs.out.aEgo = -2.0 + release = controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.RELEASE) + assert not getattr(cs, "pedal_brake_tip_glide", False) + + +def test_one_pedal_wires_carstate_after_interceptor_gas(): + """Pause must use interceptor gasPressed, published after GAS_SENSOR parse.""" + from pathlib import Path + root = Path(__file__).resolve().parents[3] + cs = (root / "opendbc_repo/opendbc/car/tesla/preap/carstate.py").read_text() + gas_at = cs.find("ret.gasPressed = cs.pedal.gas_pressed") + kick_at = cs.find("maybe_one_pedal_gas_kick") + assert 0 <= gas_at < kick_at + assert "nap_conf.one_pedal_long" in cs + eng = (root / "opendbc_repo/opendbc/car/tesla/preap/engagement.py").read_text() + fn = eng.split("def maybe_one_pedal_gas_kick", 1)[1] + body = fn.split('"""', 2)[2].split("\n def ", 1)[0] + assert "_drop_longitudinal_keep_lateral" in body + assert "_preap_one_pedal_long_was_on" in body + assert "_one_pedal_pause_latched" in body + assert "_one_pedal_had_long_at_rest" in body + assert "_one_pedal_gas_falling_edge" in body + assert "_one_pedal_armed_with_gas" in body + assert "interceptor_di" in body + assert "phantom_rise" in body + assert "latch_one_pedal_gas_takeover" in body + assert "hard_cancel_session(" not in body + assert "cruiseEnabled = False" not in body + keys = (root / "common/params_keys.h").read_text() + assert "NAPOnePedalLong" in keys + assert 'BOOL, "0"' in next(ln for ln in keys.splitlines() if '"NAPOnePedalLong"' in ln) + overlay = (root / "selfdrive/car/tesla/preap_blinker_lat_pause.py").read_text() + assert "one_pedal_gas_for_pause(" in overlay + assert "maybe_one_pedal_overlay_kick(" in overlay + assert "ONE_PEDAL_GAS_DI_PRESSED = 1.0" in overlay + assert "PEDAL_DI_PRESSED_STOCK = 2.0" in overlay + assert "interceptor_value" in overlay + assert "_one_pedal_gas_falling_edge" in overlay + nap_conf = (root / "opendbc_repo/opendbc/car/tesla/preap/nap_conf.py").read_text() + assert "ONE_PEDAL_GAS_DI_PRESSED = 1.0" in nap_conf + carstate = (root / "opendbc_repo/opendbc/car/tesla/preap/carstate.py").read_text() + assert "interceptor_di=" in carstate or "interceptor_di =" in carstate + + +def test_one_pedal_gas_pause_never_user_disables(): + """DisengageOnAccelerator must not full-cancel when One-Pedal Long is On.""" + from openpilot.selfdrive.selfdrived.preap_regen import gas_should_user_disable + + assert gas_should_user_disable(disengage_on_accelerator=True, one_pedal_long=False) + assert not gas_should_user_disable(disengage_on_accelerator=True, one_pedal_long=True) + assert not gas_should_user_disable(disengage_on_accelerator=False, one_pedal_long=True) + assert not gas_should_user_disable(disengage_on_accelerator=False, one_pedal_long=False) + + from pathlib import Path + root = Path(__file__).resolve().parents[3] + sd = (root / "selfdrive/selfdrived/selfdrived.py").read_text() + assert "gas_should_user_disable" in sd + gas_block = sd.split("gas_disable = (", 1)[1].split("if gas_disable:", 1)[0] + assert "one_pedal_long" in gas_block + assert "disengage_on_accelerator" in gas_block + events = (root / "selfdrive/selfdrived/events.py").read_text() + pedal = events.split("EventName.pedalPressed:", 1)[1].split("EventName.", 1)[0] + assert "USER_DISABLE" in pedal + override = events.split("EventName.gasPressedOverride:", 1)[1].split("EventName.", 1)[0] + assert "OVERRIDE_LONGITUDINAL" in override + assert "USER_DISABLE" not in override + + +def test_one_pedal_set_after_gas_pause_acquires(monkeypatch): + """After a from-rest pause, lift stays paused; one SET re-ACQUIREs.""" + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + _kick_long_on_gas(cc, cs) + controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + + cs.out.gasPressed = False + cs.engagement.maybe_one_pedal_gas_kick(False, True) + cc.longActive = True + silent = controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) + assert silent == [] + assert cs.engagement._one_pedal_pause_latched + assert not cs.enableLongControl + + cs.engagement.process_buttons( + cruise_buttons=2, prev_cruise_buttons=0, + curr_time_ms=4000, v_ego=20.0, speed_units="KPH", + use_pedal=True, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=False) + assert not cs.engagement._one_pedal_pause_latched + assert cs.engagement.enableLongControl + cs.enableLongControl = True + cs.cruiseEnabled = True + cc.longActive = True + acquire = controller.update(cc, cs, frame=6, tesla_can=tesla_can, can_bus_party=0) + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + + +def test_one_pedal_gas_pause_keeps_session_for_resume(monkeypatch): + """After gas pause, cruiseEnabled stays so one SET can resume like brake.""" + controller, cc, cs, tesla_can = controller_env(monkeypatch) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + _kick_long_on_gas(cc, cs) + assert cs.engagement.cruiseEnabled + assert not cs.engagement.enableLongControl + assert not getattr(cs.engagement, "preap_cc_cancel_needed", False) + assert cs.engagement._one_pedal_pause_latched + + +def test_engage_while_gas_held_lift_acquires_with_one_pedal_on(monkeypatch): + """SET with foot already on gas, then lift: A+B ACQUIRE, not a one-pedal pause.""" + from opendbc.car.tesla.preap.carcontroller import ENGAGE_GRACE_FRAMES + + controller, cc, cs, tesla_can = controller_env(monkeypatch, one_pedal_long=True) + monkeypatch.setattr( + 'opendbc.car.tesla.preap.carcontroller.get_preap_accel_limits', + lambda _v_ego: (-1.5, 0.8), + ) + assert not cs.engagement.maybe_one_pedal_gas_kick(True, True) + cs.engagement.process_buttons( + cruise_buttons=2, prev_cruise_buttons=0, + curr_time_ms=1000, v_ego=15.0, speed_units="KPH", + use_pedal=True, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=False) + assert cs.engagement.cruiseEnabled + assert cs.engagement.enableLongControl + assert not cs.engagement.maybe_one_pedal_gas_kick(True, True) + assert cs.engagement.enableLongControl + cs.cruiseEnabled = True + cs.enableLongControl = True + cs.out.gasPressed = True + cs.out.aEgo = 0.72 + cc.longActive = False + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + assert cs.engagement.enableLongControl + + cs.out.gasPressed = False + cs.out.aEgo = 0.08 + assert not cs.engagement.maybe_one_pedal_gas_kick(False, True) + assert cs.engagement.enableLongControl + assert not getattr(cs.engagement, "_one_pedal_pause_latched", False) + cs.enableLongControl = True + cc.longActive = True + cc.actuators.accel = 0.55 + acquire = controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + assert (2 - controller.preap_long_engage_frame) >= ENGAGE_GRACE_FRAMES + assert controller.vdas.jerk_limiter.a_limited == pytest.approx(0.72, abs=0.08) + + +def _set_resume(cs, t_ms=4000, v_ego=22.0): + cs.engagement.process_buttons( + cruise_buttons=2, prev_cruise_buttons=0, + curr_time_ms=t_ms, v_ego=v_ego, speed_units="KPH", + use_pedal=True, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=False) + cs.enableLongControl = cs.engagement.enableLongControl + cs.cruiseEnabled = cs.engagement.cruiseEnabled + cs.enableJustCC = cs.engagement.enableJustCC + + +def test_gas_then_lift_stays_paused_until_set(monkeypatch): + """Road test: long on → gas → lift. Override end must not resume long.""" + controller, cc, cs, tesla_can = controller_env(monkeypatch, one_pedal_long=True) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + + _kick_long_on_gas(cc, cs) + release = controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled + assert not cs.enableLongControl + assert cs.engagement._one_pedal_pause_latched + + cs.out.gasPressed = False + for frame in range(6, 20, 2): + cs.engagement.maybe_one_pedal_gas_kick(False, True) + # Stock gasPressedOverride ends on lift: CC.longActive goes True + # while the session stays up. Must not ACQUIRE or flip long back. + cc.longActive = True + cs.enableLongControl = True + out = controller.update(cc, cs, frame=frame, tesla_can=tesla_can, can_bus_party=0) + assert out == [] + assert not cs.enableLongControl + assert not cs.engagement.enableLongControl + assert cs.engagement._one_pedal_pause_latched + assert controller.pedal_authority.state == PedalAuthorityState.INACTIVE + + _set_resume(cs) + assert not cs.engagement._one_pedal_pause_latched + assert cs.engagement.enableLongControl + cs.enableLongControl = True + cc.longActive = True + acquire = controller.update(cc, cs, frame=20, tesla_can=tesla_can, can_bus_party=0) + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + + +def test_controller_latches_when_engagement_kick_misses(monkeypatch): + """Kick-miss hole: gas override + lift with enableLong still true. + + Interceptor RELEASEs on gas; lift must not A+B ACQUIRE until SET. + """ + controller, cc, cs, tesla_can = controller_env(monkeypatch, one_pedal_long=True) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert controller._saw_long_without_gas + assert cs.engagement.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + + # Soft / late gas: do not call maybe_one_pedal_gas_kick. + cs.out.gasPressed = True + cc.longActive = False + release = controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled + assert cs.engagement._one_pedal_pause_latched + assert not cs.enableLongControl + assert not cs.engagement.enableLongControl + + cs.out.gasPressed = False + for frame in range(6, 16, 2): + cc.longActive = True + cs.enableLongControl = True + silent = controller.update(cc, cs, frame=frame, tesla_can=tesla_can, can_bus_party=0) + assert silent == [] + assert not cs.enableLongControl + assert not cs.engagement.enableLongControl + assert cs.engagement._one_pedal_pause_latched + assert controller.pedal_authority.state == PedalAuthorityState.INACTIVE + + _set_resume(cs) + assert not cs.engagement._one_pedal_pause_latched + cs.enableLongControl = True + cc.longActive = True + acquire = controller.update(cc, cs, frame=16, tesla_can=tesla_can, can_bus_party=0) + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + +def test_one_pedal_light_tip_in_latches_pause(): + """One-Pedal pause is slightly more sensitive than stock interceptor gasPressed. + + Stock gasPressed is DI > 2. Pause latches at DI > 1 so a light tip-in + takes long. Coast / tiny noise at 0–1 stays off. SET-while-gas and lift + still do not resume (existing tests). + """ + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import ( + ONE_PEDAL_GAS_DI_PRESSED, + PEDAL_DI_PRESSED_STOCK, + one_pedal_gas_for_pause, + ) + + assert abs(PEDAL_DI_PRESSED_STOCK - 2.0) < 1e-9 + assert abs(ONE_PEDAL_GAS_DI_PRESSED - 1.0) < 1e-9 + assert 0.0 < ONE_PEDAL_GAS_DI_PRESSED < PEDAL_DI_PRESSED_STOCK + + assert not one_pedal_gas_for_pause(None) + assert not one_pedal_gas_for_pause(0.0) + assert not one_pedal_gas_for_pause(0.5) + assert not one_pedal_gas_for_pause(ONE_PEDAL_GAS_DI_PRESSED) + assert one_pedal_gas_for_pause(1.1) + assert one_pedal_gas_for_pause(PEDAL_DI_PRESSED_STOCK) + assert one_pedal_gas_for_pause(2.1) + + from opendbc.car.tesla.preap.engagement import PreAPEngagement + + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + eng.cruiseEnabled = True + eng.enableLongControl = True + assert not eng.maybe_one_pedal_gas_kick(False, True) + assert not eng._one_pedal_pause_latched + # Light tip-in below stock gasPressed still pauses. + assert one_pedal_gas_for_pause(1.2) + assert 1.2 < PEDAL_DI_PRESSED_STOCK + assert eng.maybe_one_pedal_gas_kick(True, True) + assert eng._one_pedal_pause_latched + assert not eng.enableLongControl + # Lift stays paused. + assert not eng.maybe_one_pedal_gas_kick(False, True) + assert eng._one_pedal_pause_latched + + # Overlay extra kick still honors SET-while-gas skip_resume. + eng2 = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + eng2.cruiseEnabled = True + eng2.enableLongControl = True + assert not eng2.maybe_one_pedal_gas_kick(False, True) + eng2._nap_set_resume_long = True + assert not eng2.maybe_one_pedal_gas_kick(True, True) + assert not eng2._one_pedal_pause_latched + assert eng2.enableLongControl + +def _on_car_cycle(controller, cc, cs, tesla_can, frame, *, gas, set_edge=False, t_ms=4000, v_ego=22.0, + interceptor_di=None): + """Carstate then carcontroller: process_buttons, kick, extra DI>1, then long update.""" + from opendbc.car.tesla.values import CruiseButtons + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import maybe_one_pedal_overlay_kick + + cs.out.gasPressed = gas + cs.engagement._nap_gas_pressed = gas + if interceptor_di is None: + interceptor_di = 8.0 if gas else 0.0 + cs.pedal_interceptor_value = interceptor_di + buttons = CruiseButtons.MAIN if set_edge else 0 + cs.engagement.process_buttons( + cruise_buttons=buttons, prev_cruise_buttons=0, + curr_time_ms=t_ms, v_ego=v_ego, speed_units="KPH", + use_pedal=True, pedal_long_allowed=True, + long_control_allowed=True, real_brake_pressed=False) + cs.engagement.maybe_one_pedal_gas_kick(gas, True, interceptor_di=interceptor_di) + maybe_one_pedal_overlay_kick(cs.engagement, interceptor_di) + cs.enableLongControl = cs.engagement.enableLongControl + cs.cruiseEnabled = cs.engagement.cruiseEnabled + cs.enableJustCC = cs.engagement.enableJustCC + cc.longActive = (not gas) and bool(cs.enableLongControl) + return controller.update(cc, cs, frame=frame, tesla_can=tesla_can, can_bus_party=0) + +def test_one_pedal_set_while_gas_held_controller_does_not_relatch(monkeypatch): + """On-car order: long holding → gas pause → SET with foot still down. + + Overlay one-SET resume must stick; controller `_saw_long_without_gas` + must not re-latch. Lift then ACQUIREs (A+B). Lift alone stays paused. + """ + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause + + install_blinker_lat_pause() + controller, cc, cs, tesla_can = controller_env( + monkeypatch, one_pedal_long=True, double_pull=True) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + assert controller._saw_long_without_gas + + _kick_long_on_gas(cc, cs) + release = controller.update(cc, cs, frame=4, tesla_can=tesla_can, can_bus_party=0) + assert not _decode_pedal_command(release[0]).enabled + assert cs.engagement._one_pedal_pause_latched + assert not cs.enableLongControl + + out = _on_car_cycle(controller, cc, cs, tesla_can, 6, gas=True, set_edge=True, t_ms=4000) + assert cs.engagement.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + assert getattr(cs.engagement, "_nap_set_resume_long", False) + assert not controller._saw_long_without_gas + # Gas still down: interceptor stays RELEASED (pass-through). + if out: + assert not _decode_pedal_command(out[0]).enabled + + # Later frames with foot still down must not re-latch. + later = _on_car_cycle(controller, cc, cs, tesla_can, 12, gas=True, t_ms=4100) + assert cs.engagement.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + if later: + assert not _decode_pedal_command(later[0]).enabled + + cs.out.gasPressed = False + cs.engagement._nap_gas_pressed = False + assert not cs.engagement.maybe_one_pedal_gas_kick(False, True) + assert cs.engagement.enableLongControl + cs.enableLongControl = True + cc.longActive = True + acquire = controller.update(cc, cs, frame=14, tesla_can=tesla_can, can_bus_party=0) + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + + +def test_one_pedal_set_after_lift_with_overlay_double_pull_acquires(monkeypatch): + """Rolling one SET after lift resumes at held MAX with double-pull On.""" + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause + + install_blinker_lat_pause() + controller, cc, cs, tesla_can = controller_env( + monkeypatch, one_pedal_long=True, double_pull=True) + _activate_longitudinal(cc, cs) + controller.update(cc, cs, frame=0, tesla_can=tesla_can, can_bus_party=0) + _kick_long_on_gas(cc, cs) + controller.update(cc, cs, frame=2, tesla_can=tesla_can, can_bus_party=0) + + silent = _on_car_cycle(controller, cc, cs, tesla_can, 4, gas=False, t_ms=3000) + assert silent == [] + assert cs.engagement._one_pedal_pause_latched + assert not cs.enableLongControl + + acquire = _on_car_cycle(controller, cc, cs, tesla_can, 6, gas=False, set_edge=True, t_ms=4000) + assert not cs.engagement._one_pedal_pause_latched + assert cs.engagement.enableLongControl + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + + +def _double_set_while_gas(controller, cc, cs, tesla_can, *, v_ego=22.8): + """Fully disengaged, foot on gas (DI > 2): first SET arms lat+long. + + A second SET inside the window stays engaged. One-Pedal must not latch. + """ + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause + + install_blinker_lat_pause() + cs.engagement._nap_di_pedal_pos = 8.0 + _on_car_cycle(controller, cc, cs, tesla_can, 0, gas=True, interceptor_di=8.0, + t_ms=1000, v_ego=v_ego) + assert not cs.engagement.cruiseEnabled + cs.engagement._nap_di_pedal_pos = 8.0 + _on_car_cycle(controller, cc, cs, tesla_can, 2, gas=True, set_edge=True, + interceptor_di=8.0, t_ms=2000, v_ego=v_ego) + assert cs.engagement.cruiseEnabled + assert cs.engagement.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + assert cs.engagement.stalk_pull_time_ms == 2000 + held = cs.engagement.pedal_speed_kph + cs.engagement._nap_di_pedal_pos = 6.0 + _on_car_cycle(controller, cc, cs, tesla_can, 4, gas=True, set_edge=True, + interceptor_di=6.0, t_ms=2400, v_ego=v_ego) + assert cs.engagement.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + assert abs(cs.engagement.pedal_speed_kph - held) < 1e-6 + return cs.engagement.pedal_speed_kph + + +def test_dc_131614_lift_through_di1_acquires_same_frame(monkeypatch): + """Route 1c95345a3286a5db|000000dc--9b28358130 ~13:16:14 / 13:15:30. + + Double-SET while on gas, then lift with no lead. Stock gasPressed falls + while interceptor DI is still > 1. Must keep enableLongControl, not latch + One-Pedal pause, and ACQUIRE pedal authority on that falling edge. + """ + from opendbc.car.tesla.preap.carcontroller import ENGAGE_GRACE_FRAMES + + controller, cc, cs, tesla_can = controller_env( + monkeypatch, one_pedal_long=True, double_pull=True) + monkeypatch.setattr( + 'opendbc.car.tesla.preap.carcontroller.get_preap_accel_limits', + lambda _v_ego: (-1.5, 0.8), + ) + held = _double_set_while_gas(controller, cc, cs, tesla_can, v_ego=22.8) + assert held > 0.0 + cs.out.aEgo = 0.47 + cc.actuators.accel = 0.47 + + acquire = _on_car_cycle( + controller, cc, cs, tesla_can, 6, gas=False, interceptor_di=1.5, + t_ms=3000, v_ego=22.8) + assert cs.engagement.enableLongControl + assert cs.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + assert abs(cs.engagement.pedal_speed_kph - held) < 1e-6 + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + assert (6 - controller.preap_long_engage_frame) >= ENGAGE_GRACE_FRAMES + + linger = _on_car_cycle( + controller, cc, cs, tesla_can, 8, gas=False, interceptor_di=1.2, + t_ms=3100, v_ego=22.5) + assert cs.engagement.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + if linger: + assert _decode_pedal_command(linger[0]).enabled + + +def test_dc_131530_no_pedal_authority_gap_for_7s(monkeypatch): + """dc 13:15:30: after lift, pedL must rise immediately — not a 7.5 s regen hole.""" + controller, cc, cs, tesla_can = controller_env( + monkeypatch, one_pedal_long=True, double_pull=True) + monkeypatch.setattr( + 'opendbc.car.tesla.preap.carcontroller.get_preap_accel_limits', + lambda _v_ego: (-1.5, 0.8), + ) + held = _double_set_while_gas(controller, cc, cs, tesla_can, v_ego=24.5) + cs.out.aEgo = 0.40 + cc.actuators.accel = 0.47 + acquire = _on_car_cycle( + controller, cc, cs, tesla_can, 6, gas=False, interceptor_di=1.5, + t_ms=3000, v_ego=24.5) + assert cs.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + assert abs(cs.engagement.pedal_speed_kph - held) < 1e-6 + + for i, frame in enumerate(range(8, 8 + 376, 2)): + di = 1.3 if i < 8 else 0.0 + cs.out.aEgo = 0.2 + out = _on_car_cycle( + controller, cc, cs, tesla_can, frame, gas=False, interceptor_di=di, + t_ms=3000 + (frame - 6) * 10, v_ego=24.5 - 0.01 * i) + assert cs.engagement.enableLongControl, frame + assert cs.enableLongControl, frame + assert not cs.engagement._one_pedal_pause_latched, frame + assert cs.engagement.pedal_speed_kph > 0.0 + if out: + assert _decode_pedal_command(out[0]).enabled + + +def test_dc_131719_clean_lift_to_zero_acquires(monkeypatch): + """Same route ~13:17:19: lift drops through DI 1 in one sample; ACQUIRE.""" + controller, cc, cs, tesla_can = controller_env( + monkeypatch, one_pedal_long=True, double_pull=True) + monkeypatch.setattr( + 'opendbc.car.tesla.preap.carcontroller.get_preap_accel_limits', + lambda _v_ego: (-1.5, 0.8), + ) + _double_set_while_gas(controller, cc, cs, tesla_can, v_ego=22.8) + cs.out.aEgo = 0.40 + cc.actuators.accel = 0.47 + acquire = _on_car_cycle( + controller, cc, cs, tesla_can, 6, gas=False, interceptor_di=0.0, + t_ms=3000, v_ego=22.8) + assert cs.engagement.enableLongControl + assert not cs.engagement._one_pedal_pause_latched + assert _decode_pedal_command(acquire[0]).enabled + assert cs.pedal_authority_action == int(PedalCommandAction.ACQUIRE) + + +def test_overlay_helper_skips_extra_kick_on_stock_falling_edge(): + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import ( + maybe_one_pedal_overlay_kick, + ) + from opendbc.car.tesla.preap.engagement import PreAPEngagement + + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + eng.cruiseEnabled = True + eng.enableLongControl = True + assert not eng.maybe_one_pedal_gas_kick(True, True) + assert not eng.maybe_one_pedal_gas_kick(False, True) + assert eng._one_pedal_gas_falling_edge + assert not maybe_one_pedal_overlay_kick(eng, 1.5) + assert eng.enableLongControl + assert not eng._one_pedal_pause_latched + + +def _blip_engagement(): + from opendbc.car.tesla.preap.engagement import PreAPEngagement + eng = PreAPEngagement(double_pull_enabled=True, double_pull_window_ms=400) + eng.cruiseEnabled = True + eng.enableLongControl = True + eng._gas_blip_clock = 0.0 + eng._nap_gas_sensor = { + "gas": 0.0, "gas2": 0.0, "state": 0, "idx": 0, "gas_cmd": 0.0, "gas_cmd2": 0.0, + } + eng._nap_di_pedal_pos = 0.0 + assert not eng.maybe_one_pedal_gas_kick(False, True, interceptor_di=0.0) + assert eng._one_pedal_had_long_at_rest + return eng + + +def test_gas_blip_under_50ms_does_not_pause_long(monkeypatch): + """A pedal reading above the gate for less than 50 ms is not a pause. + + Oct 7: eight of these, including the two roundabout latches, dropped long + and the car fell into Tesla lift regen. + """ + from openpilot.selfdrive.car.tesla import preap_blinker_lat_pause as pause + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause + + install_blinker_lat_pause() + eng = _blip_engagement() + logged = [] + monkeypatch.setattr( + pause.cloudlog, "error", + lambda msg, *args, **kwargs: logged.append(msg % args if args else msg), + ) + for i, di in enumerate((2.2, 1.8, 2.5, 1.4)): + eng._gas_blip_clock = 0.01 * (i + 1) + eng._nap_gas_sensor = { + "gas": di, "gas2": di - 0.1, "state": 0, "idx": i + 1, + "gas_cmd": 0.4, "gas_cmd2": 0.0, + } + eng._nap_di_pedal_pos = di + assert not eng.maybe_one_pedal_gas_kick(di > 2.0, True, interceptor_di=di) + assert eng.enableLongControl + assert not eng._one_pedal_pause_latched + eng._gas_blip_clock = 0.05 + eng._nap_gas_sensor = { + "gas": 0.0, "gas2": 0.0, "state": 0, "idx": 9, "gas_cmd": 0.0, "gas_cmd2": 0.0, + } + assert not eng.maybe_one_pedal_gas_kick(False, True, interceptor_di=0.0) + assert eng.enableLongControl + assert not eng._one_pedal_pause_latched + ignored = [line for line in logged if isinstance(line, str) and line.startswith("gasblip ") and '"ignored"' in line] + assert ignored + assert '"gas":2.5' in ignored[-1] or '"gas": 2.5' in ignored[-1] + assert "gas_cmd" in ignored[-1] + + +def test_firm_gas_press_pauses_long_on_that_frame(monkeypatch): + """DI > 4 is a deliberate press and pauses on the same 100 Hz frame.""" + from openpilot.selfdrive.car.tesla import preap_blinker_lat_pause as pause + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause + + install_blinker_lat_pause() + eng = _blip_engagement() + logged = [] + monkeypatch.setattr( + pause.cloudlog, "error", + lambda msg, *args, **kwargs: logged.append(msg % args if args else msg), + ) + eng._gas_blip_clock = 0.01 + eng._nap_gas_sensor = { + "gas": 6.5, "gas2": 6.4, "state": 0, "idx": 3, "gas_cmd": 2.0, "gas_cmd2": 0.0, + } + assert eng.maybe_one_pedal_gas_kick(True, True, interceptor_di=6.5) + assert not eng.enableLongControl + assert eng._one_pedal_pause_latched + assert eng.cruiseEnabled + paused = [line for line in logged if isinstance(line, str) and '"pause"' in line] + assert paused and "6.5" in paused[-1] + + +def test_light_gas_press_pauses_at_50ms(): + """A real light press (DI > 1, not a spike) pauses on the fifth frame.""" + from openpilot.selfdrive.car.tesla.preap_blinker_lat_pause import install_blinker_lat_pause + + install_blinker_lat_pause() + eng = _blip_engagement() + for i in range(4): + eng._gas_blip_clock = 0.01 * (i + 1) + assert not eng.maybe_one_pedal_gas_kick(False, True, interceptor_di=1.5) + assert eng.enableLongControl + assert not eng._one_pedal_pause_latched + eng._gas_blip_clock = 0.05 + assert eng.maybe_one_pedal_gas_kick(False, True, interceptor_di=1.5) + assert not eng.enableLongControl + assert eng._one_pedal_pause_latched + assert eng.cruiseEnabled diff --git a/selfdrive/controls/tests/test_torqued_lat_accel_offset.py b/selfdrive/controls/tests/test_torqued_lat_accel_offset.py new file mode 100644 index 00000000000000..2f95d7c14f7b05 --- /dev/null +++ b/selfdrive/controls/tests/test_torqued_lat_accel_offset.py @@ -0,0 +1,72 @@ +import numpy as np +from cereal import car, messaging +from opendbc.car import ACCELERATION_DUE_TO_GRAVITY +from opendbc.car import structs +from opendbc.car.lateral import get_friction, FRICTION_THRESHOLD +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.locationd.torqued import TorqueEstimator, MIN_BUCKET_POINTS, POINTS_PER_BUCKET, STEER_BUCKET_BOUNDS + +np.random.seed(0) + +LA_ERR_STD = 1.0 +INPUT_NOISE_STD = 0.08 +V_EGO = 30.0 + +WARMUP_BUCKET_POINTS = (1.5*MIN_BUCKET_POINTS).astype(int) +STRAIGHT_ROAD_LA_BOUNDS = (0.02, 0.03) + +ROLL_BIAS_DEG = 2.0 +ROLL_COMPENSATION_BIAS = ACCELERATION_DUE_TO_GRAVITY*float(np.sin(np.deg2rad(ROLL_BIAS_DEG))) +TORQUE_TUNE = structs.CarParams.LateralTorqueTuning(latAccelFactor=2.0, latAccelOffset=0.0, friction=0.2) +TORQUE_TUNE_BIASED = structs.CarParams.LateralTorqueTuning(latAccelFactor=2.0, latAccelOffset=-ROLL_COMPENSATION_BIAS, friction=0.2) + +def generate_inputs(torque_tune, la_err_std, input_noise_std=None): + rng = np.random.default_rng(0) + steer_torques = np.concat([rng.uniform(bnd[0], bnd[1], pts) for bnd, pts in zip(STEER_BUCKET_BOUNDS, WARMUP_BUCKET_POINTS, strict=True)]) + la_errs = rng.normal(scale=la_err_std, size=steer_torques.size) + frictions = np.array([get_friction(la_err, 0.0, FRICTION_THRESHOLD, torque_tune) for la_err in la_errs]) + lat_accels = torque_tune.latAccelFactor*steer_torques + torque_tune.latAccelOffset + frictions + if input_noise_std is not None: + steer_torques += rng.normal(scale=input_noise_std, size=steer_torques.size) + lat_accels += rng.normal(scale=input_noise_std, size=steer_torques.size) + return steer_torques, lat_accels + +def get_warmed_up_estimator(steer_torques, lat_accels): + est = TorqueEstimator(car.CarParams()) + for steer_torque, lat_accel in zip(steer_torques, lat_accels, strict=True): + est.filtered_points.add_point(steer_torque, lat_accel) + return est + +def simulate_straight_road_msgs(est): + carControl = messaging.new_message('carControl').carControl + carOutput = messaging.new_message('carOutput').carOutput + carState = messaging.new_message('carState').carState + livePose = messaging.new_message('livePose').livePose + carControl.latActive = True + carState.vEgo = V_EGO + carState.steeringPressed = False + ts = DT_MDL*np.arange(2*POINTS_PER_BUCKET) + steer_torques = np.concat((np.linspace(-0.03, -0.02, POINTS_PER_BUCKET), np.linspace(0.02, 0.03, POINTS_PER_BUCKET))) + lat_accels = TORQUE_TUNE.latAccelFactor * steer_torques + for t, steer_torque, lat_accel in zip(ts, steer_torques, lat_accels, strict=True): + carOutput.actuatorsOutput.torque = float(-steer_torque) + livePose.orientationNED = {'x': float(np.deg2rad(ROLL_BIAS_DEG)), 'valid': True} + livePose.angularVelocityDevice = {'z': float(lat_accel / V_EGO), 'valid': True} + livePose.inputsOK, livePose.sensorsOK, livePose.posenetOK = True, True, True + livePose.timestamp = int(t * 1e9) + for which, msg in (('carControl', carControl), ('carOutput', carOutput), ('carState', carState), ('livePose', livePose)): + est.handle_log(t, which, msg) + +def test_estimated_offset(): + steer_torques, lat_accels = generate_inputs(TORQUE_TUNE_BIASED, la_err_std=LA_ERR_STD, input_noise_std=INPUT_NOISE_STD) + est = get_warmed_up_estimator(steer_torques, lat_accels) + msg = est.get_msg() + # TODO add lataccelfactor and friction check when we have more accurate estimates + assert abs(msg.liveTorqueParameters.latAccelOffsetRaw - TORQUE_TUNE_BIASED.latAccelOffset) < 0.1 + +def test_straight_road_roll_bias(): + steer_torques, lat_accels = generate_inputs(TORQUE_TUNE, la_err_std=LA_ERR_STD, input_noise_std=INPUT_NOISE_STD) + est = get_warmed_up_estimator(steer_torques, lat_accels) + simulate_straight_road_msgs(est) + msg = est.get_msg() + assert (msg.liveTorqueParameters.latAccelOffsetRaw < -0.05) and np.isfinite(msg.liveTorqueParameters.latAccelOffsetRaw) diff --git a/selfdrive/controls/tests/test_unified_far_gap_catchup.py b/selfdrive/controls/tests/test_unified_far_gap_catchup.py new file mode 100644 index 00000000000000..4a742f978a06d6 --- /dev/null +++ b/selfdrive/controls/tests/test_unified_far_gap_catchup.py @@ -0,0 +1,273 @@ +"""Far-gap soft closing speed inside unified_follow_desired. + +At a large gap with nearly matched speed, k_g·slack asks for +1.2…+1.8 m/s² +and the kinematic gate bangs that into catch-up pulses. The classic gap term +fades from 15 → 50 m of slack and the faded portion becomes a desired closing +speed of about 0.10–0.95 m/s. The gain is low enough that a matched gap still +commands under 0.15 m/s². The blend is off for a near gap, a braking PD +term, and a kinematic bound that is already a real brake. The shipped gate +widen is unchanged. +""" +import math + +import numpy as np +import pytest + +from openpilot.selfdrive.controls.lib import unified_lead as ul +from openpilot.selfdrive.controls.lib.unified_lead import ( + GAP_CATCH_A_BOUND_LO, + GAP_CATCH_A_BOUND_RAMP, + GAP_CATCH_A_ON, + GAP_FADE_HI_M, + GAP_FADE_LO_M, + K_CATCH, + V_DES_CLOSE_LO, + V_DES_CLOSE_RAMP_M, + V_DES_CLOSE_SPAN, + UnifiedLeadController, + _far_gap_catchup_gap, + gap_set_m, + unified_follow_desired, +) + +DT = 0.05 + + +def _baseline(monkeypatch): + monkeypatch.setattr(ul, "_far_gap_catchup_gap", lambda a_gap_classic, *a, **k: a_gap_classic) + + +def _cmd(slack, v_close, vl=28.0, al=0.0, tf=0.7): + gap = gap_set_m(vl, tf) + slack + return unified_follow_desired(gap, max(0.0, vl + v_close), vl, al, tf) + + +def _rising_crossings(cmds, level): + return sum(1 for prev, cur in zip(cmds, cmds[1:], strict=False) if prev < level <= cur) + + +def test_constants_match_the_approved_closing_speed(): + assert GAP_FADE_LO_M == 15.0 + assert GAP_FADE_HI_M == 50.0 + assert V_DES_CLOSE_LO == 0.10 + assert V_DES_CLOSE_SPAN == 0.85 + assert V_DES_CLOSE_RAMP_M == 30.0 + assert K_CATCH == 0.14 + assert GAP_CATCH_A_ON == 0.15 + assert GAP_CATCH_A_BOUND_LO == -0.10 + assert GAP_CATCH_A_BOUND_RAMP == 0.10 + + +def test_slack_weight_keeps_the_near_gap_term(): + assert _far_gap_catchup_gap(1.2, 10.0, 0.0, 1.0, 1.0, 0.0) == 1.2 + + +def test_accel_weight_keeps_a_braking_pd_term(): + """A non-positive classic PD is not a catch-up, even at a far slack.""" + assert _far_gap_catchup_gap(1.2, 50.0, 0.0, 1.0, -0.2, 0.0) == 1.2 + + +def test_bound_weight_keeps_the_gap_term_on_a_real_brake(): + assert _far_gap_catchup_gap(1.2, 50.0, 0.0, 1.0, 1.0, -1.0) == 1.2 + + +def test_matched_far_command_is_a_soft_ease(): + """Matched speed past the fade: about +0.13, never a highway pull. + + Slack 40 m is still inside the fade, so a little of the classic gap term + remains. It stays well under the old slam. At 50 m and beyond the fade is + done. + """ + assert 0.0 <= _cmd(40.0, 0.0) < 0.25 + for slack in (50.0, 60.0, 80.0): + cmd = _cmd(slack, 0.0) + assert 0.0 <= cmd <= 0.15, (slack, cmd) + # Trickle has faded out; the command is K_CATCH * 0.95. + assert _cmd(60.0, 0.0) == pytest.approx(0.133, abs=1e-6) + assert _cmd(80.0, 0.0) == pytest.approx(0.133, abs=1e-6) + + +def test_follow7_recovery_comes_back_inside_the_maneuver_ceiling(): + """Close lead, Follow 7, 60 s. The real maneuver must finish ≤ 83.5 m. + + This plant is the unified controller plus the cruise accel cap, and it + tracks that maneuver about 1 m closer. Ending the fade at 40 m finished + here at 85 m (86.4 m on the real plant). The fade has to leave enough + catch-up in the 30 m slack band to come back. + """ + v_lead = 25.0 + t_follow = 1.9 + ctrl = UnifiedLeadController() + v_ego = v_lead + d_ego = 0.0 + d_lead = 20.0 + for _ in range(int(60.0 / DT)): + gap = max(0.0, d_lead - d_ego) + a_max = float(np.interp(v_ego, [0.0, 10.0, 25.0, 40.0], [1.6, 1.2, 0.8, 0.6])) + accel = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=t_follow, lead_id=1, seed_a=0.0, v_ceiling=50.0, a_max=a_max, + ) + v_ego = max(0.0, v_ego + accel * DT) + d_lead += v_lead * DT + d_ego += v_ego * DT + gap = d_lead - d_ego + assert gap >= 53.0 + assert gap < 82.0 + assert v_ego == pytest.approx(v_lead, abs=0.5) + + +def test_follow_settings_land_inside_the_240s_band(): + """Same-speed close from 100 m, 240 s, every Follow time. + + The Pre-AP maneuver requires the final gap within ±1.5 m of + t_follow·v + 6. This plant tracks that maneuver closely. A desired + close of 0.35 m/s left Follow 2 about 1.6 m inside the set gap at + 240 s, on the trough of the settle. The higher desired close has to + put every setting inside a tighter band here, and the Follow 7 + recovery above still has to finish under 82 m. + """ + v_lead = 25.0 + follow_times = (0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9) + gaps = [] + for t_follow in follow_times: + ctrl = UnifiedLeadController() + v_ego = v_lead + d_ego = 0.0 + d_lead = 100.0 + for _ in range(int(240.0 / DT)): + gap = max(0.0, d_lead - d_ego) + a_max = float(np.interp(v_ego, [0.0, 10.0, 25.0, 40.0], [1.6, 1.2, 0.8, 0.6])) + accel = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=t_follow, lead_id=1, seed_a=0.0, v_ceiling=50.0, a_max=a_max, + ) + v_ego = max(0.0, v_ego + accel * DT) + d_lead += v_lead * DT + d_ego += v_ego * DT + gaps.append(d_lead - d_ego) + expected = [t_follow * v_lead + 6.0 for t_follow in follow_times] + assert gaps == pytest.approx(expected, abs=1.40) + assert np.all(np.diff(gaps) > 0.0) + + +def test_e2_shaped_open_loop_does_not_pulse(monkeypatch): + """Closing speed crossing the old 0.4 m/s gate every ~3 s, slack 50 m. + + Classic gap attraction rises through +0.35 ten times. The soft law does not. + """ + def trace(): + cmds = [] + for i in range(600): + t = i * DT + v_close = 0.25 + 0.30 * math.sin(2.0 * math.pi * t / 3.0) + cmds.append(_cmd(50.0, v_close)) + return cmds + + soft = trace() + assert _rising_crossings(soft, 0.35) <= 2 + assert max(soft) <= 0.15 + _baseline(monkeypatch) + classic = trace() + assert _rising_crossings(classic, 0.35) >= 8 + + +def test_matched_far_closed_loop_does_not_brake_harder_than_classic(monkeypatch): + """Constant lead, start matched 55 m behind. Soft ease, no deeper brake.""" + def rollout(): + v = 28.0 + tf = 0.7 + v_ego = v + gap = gap_set_m(v, tf) + 55.0 + a = 0.0 + cmds, acc, gaps = [], [], [] + for _ in range(int(40.0 / DT)): + cmd = unified_follow_desired(max(0.0, gap), v_ego, v, 0.0, tf) + a += (cmd - a) * DT / 0.45 + v_ego = max(0.0, v_ego + a * DT) + gap += (v - v_ego) * DT + cmds.append(cmd) + acc.append(a) + gaps.append(gap) + return cmds, acc, gaps + + soft_cmds, soft_a, soft_gaps = rollout() + _baseline(monkeypatch) + classic_cmds, classic_a, classic_gaps = rollout() + assert max(soft_cmds) <= 0.15 + assert max(classic_cmds) > 0.5 + assert min(soft_a) >= min(classic_a) - 1e-9 + assert min(soft_gaps) >= min(classic_gaps) - 1e-6 + assert max(soft_cmds) - min(soft_cmds) < 0.35 + + +def test_closing_faster_than_desired_adds_no_gap_brake(): + """a_soft is negative once we already close faster than v_des; clip it at 0.""" + assert _far_gap_catchup_gap(1.5, 60.0, -1.0, 1.0, 1.0, 0.0) == 0.0 + cmd = _cmd(60.0, 1.0) + assert -0.03 < cmd < 0.0 + + +def test_braking_lead_at_a_far_gap_keeps_the_classic_command(monkeypatch): + """Lead brake makes a real bound. The gap rewrite stays off, so no new brake.""" + vl, tf, slack, al = 25.0, 1.3, 60.0, -1.0 + gap = gap_set_m(vl, tf) + slack + new = unified_follow_desired(gap, vl, vl, al, tf) + _baseline(monkeypatch) + old = unified_follow_desired(gap, vl, vl, al, tf) + assert new == old + assert new > 0.5 + + +def test_bit_identical_for_slack_at_or_under_15m(monkeypatch): + rng = np.random.default_rng(15) + cases = [] + for _ in range(20000): + vl = float(rng.uniform(0.0, 40.0)) + tf = float(rng.choice([0.7, 0.9, 1.1, 1.3, 1.5, 1.8])) + slack = float(rng.uniform(-8.0, GAP_FADE_LO_M)) + v_close = float(rng.uniform(-2.0, 6.0)) + al = float(rng.uniform(-2.0, 1.0)) + gap = max(0.0, gap_set_m(vl, tf) + slack) + cases.append((gap, max(0.0, vl + v_close), vl, al, tf)) + new = [unified_follow_desired(*c) for c in cases] + _baseline(monkeypatch) + old = [unified_follow_desired(*c) for c in cases] + assert new == old + + +def test_never_firmer_on_catchup_and_never_deeper_when_classic_brakes(monkeypatch): + rng = np.random.default_rng(4) + cases = [] + for _ in range(40000): + vl = float(rng.uniform(0.0, 40.0)) + tf = float(rng.choice([0.7, 0.9, 1.1, 1.3, 1.5, 1.8])) + slack = float(rng.uniform(-8.0, 90.0)) + v_close = float(rng.uniform(-2.0, 8.0)) + al = float(rng.uniform(-2.5, 1.0)) + gap = max(0.0, gap_set_m(vl, tf) + slack) + cases.append((gap, max(0.0, vl + v_close), vl, al, tf, slack)) + new = [unified_follow_desired(*c[:5]) for c in cases] + _baseline(monkeypatch) + old = [unified_follow_desired(*c[:5]) for c in cases] + changed = 0 + for n, o, c in zip(new, old, cases, strict=True): + assert n <= o + 1e-9, c # never a firmer catch-up + if o < -0.10: + assert n >= o - 1e-9, c # a classic brake is not deepened + if c[5] <= GAP_FADE_LO_M: + assert n == o, c + if n != o: + changed += 1 + assert changed > 100 + + +def test_catchup_is_continuous_in_slack_and_closing_speed(): + slacks = np.linspace(-5.0, 80.0, 8501) + ys = np.array([_cmd(float(s), 0.0) for s in slacks]) + assert np.abs(np.diff(ys)).max() < 0.01 + closes = np.linspace(-2.0, 4.0, 6001) + for slack in (20.0, 50.0): + ys = np.array([_cmd(slack, float(v)) for v in closes]) + assert np.abs(np.diff(ys)).max() < 0.02 + assert np.all(np.isfinite(ys)) diff --git a/selfdrive/controls/tests/test_unified_far_gap_gate.py b/selfdrive/controls/tests/test_unified_far_gap_gate.py new file mode 100644 index 00000000000000..c9af7c69a3b0ee --- /dev/null +++ b/selfdrive/controls/tests/test_unified_far_gap_gate.py @@ -0,0 +1,151 @@ +"""F3: the far-gap kinematic gate widens while the PD term accelerates. + +At a far gap with a slow close, `gate = smooth(v_close / 0.40)` flipped the +command between the PD accel (+0.2..+0.3) and a near-zero kinematic bound once +v_close crossed ~0.4 m/s: the accCmd pulses at 15a 11:27 and 159 08:03. The +widened gate keeps the PD accel through that edge. It only acts for slack past +15 m, an accelerating PD (a_pd > 0.4 m/s^2 to clear the base width) and a +kinematic bound that is not a real brake (>= -0.10), is never firmer than +before, and is bit-identical elsewhere. +""" +import math + +import numpy as np +import pytest + +from openpilot.selfdrive.controls.lib import unified_lead as ul +from openpilot.selfdrive.controls.lib.unified_lead import ( + KIN_GATE_MS, + KIN_GATE_WIDEN_A_BOUND_LO, + KIN_GATE_WIDEN_A_BOUND_RAMP, + KIN_GATE_WIDEN_A_CAP, + KIN_GATE_WIDEN_K, + KIN_GATE_WIDEN_SLACK_LO_M, + KIN_GATE_WIDEN_SLACK_RAMP_M, + _kin_gate_widen, + gap_set_m, + unified_follow_desired, +) + +TF = 1.5 + + +def _baseline(monkeypatch): + monkeypatch.setattr(ul, "_kin_gate_widen", lambda *a, **k: 0.0) + + +def _cmd(slack, v_close, vl=25.0, a_lead=0.0): + gap = gap_set_m(vl, TF) + slack + return unified_follow_desired(gap, vl + v_close, vl, a_lead, TF) + + +def test_constants_are_pinned(): + assert KIN_GATE_MS == 0.40 + assert KIN_GATE_WIDEN_SLACK_LO_M == 15.0 + assert KIN_GATE_WIDEN_SLACK_RAMP_M == 5.0 + assert KIN_GATE_WIDEN_A_BOUND_LO == -0.10 + assert KIN_GATE_WIDEN_A_BOUND_RAMP == 0.10 + assert KIN_GATE_WIDEN_A_CAP == 0.50 + assert KIN_GATE_WIDEN_K == 1.0 + + +def test_widen_is_zero_unless_all_three_conditions_hold(): + assert _kin_gate_widen(30.0, 0.7, 0.0) > 0.0 + assert _kin_gate_widen(30.0, 0.0, 0.0) == 0.0 # PD not accelerating + assert _kin_gate_widen(30.0, -0.5, 0.0) == 0.0 + assert _kin_gate_widen(30.0, 0.4, 0.0) == 0.0 # does not clear the base width + assert _kin_gate_widen(15.0, 0.7, 0.0) == 0.0 # slack under the far-gap line + assert _kin_gate_widen(5.0, 0.7, 0.0) == 0.0 + assert _kin_gate_widen(30.0, 0.7, -0.10) == 0.0 # a real bound keeps the old gate + assert _kin_gate_widen(30.0, 0.7, -1.0) == 0.0 + + +def test_widen_full_weight_and_cap(): + full = _kin_gate_widen(20.0, 0.9, 0.0) + assert full == pytest.approx(KIN_GATE_WIDEN_A_CAP / KIN_GATE_WIDEN_K - KIN_GATE_MS) + assert _kin_gate_widen(60.0, 5.0, 0.5) == pytest.approx(full) # a_pd capped at 0.5 + assert _kin_gate_widen(25.0, 0.45, 0.0) == pytest.approx(0.45 - KIN_GATE_MS) + + +def test_widen_is_continuous_in_slack_bound_and_pd(): + sweeps = ( + (np.linspace(0.0, 40.0, 40001), lambda x: _kin_gate_widen(x, 0.7, 0.0)), + (np.linspace(-0.3, 1.0, 13001), lambda x: _kin_gate_widen(30.0, 0.7, x)), + (np.linspace(-0.5, 1.5, 20001), lambda x: _kin_gate_widen(30.0, x, 0.0)), + ) + for xs, fn in sweeps: + ys = np.array([fn(float(x)) for x in xs]) + assert np.abs(np.diff(ys)).max() < 0.01 + + +def test_bit_identical_to_the_old_gate_inside_the_far_gap_line(monkeypatch): + rng = np.random.default_rng(3) + cases = [] + for _ in range(4000): + vl = rng.uniform(0, 35) + slack = rng.uniform(-8, KIN_GATE_WIDEN_SLACK_LO_M) + cases.append((vl, vl + rng.uniform(-1.5, 2.5), rng.uniform(-1.5, 1.0), TF + rng.choice([-0.5, 0, 0.5]), slack)) + new = [unified_follow_desired(max(0.0, gap_set_m(vl, tf) + s), ve, vl, al, tf) for vl, ve, al, tf, s in cases] + _baseline(monkeypatch) + old = [unified_follow_desired(max(0.0, gap_set_m(vl, tf) + s), ve, vl, al, tf) for vl, ve, al, tf, s in cases] + assert new == old + + +def test_never_firmer_and_unchanged_where_the_old_command_braked(monkeypatch): + rng = np.random.default_rng(11) + cases = [] + for _ in range(20000): + vl = rng.uniform(0, 35) + tf = float(rng.choice([0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9])) + slack = float(rng.choice([rng.uniform(-5, 40), rng.uniform(15, 35)])) + cases.append((max(0.0, gap_set_m(vl, tf) + slack), max(0.0, vl + rng.uniform(-1.5, 1.5)), vl, + rng.uniform(-1.5, 1.0), tf)) + new = [unified_follow_desired(*c) for c in cases] + _baseline(monkeypatch) + old = [unified_follow_desired(*c) for c in cases] + changed = 0 + for n, o, c in zip(new, old, cases, strict=True): + assert n >= o - 1e-12, c # never firmer + if o < KIN_GATE_WIDEN_A_BOUND_LO - 1e-9: + assert n == o, c # a real brake is untouched + if n != o: + changed += 1 + assert n - o < 0.45, c # bounded raise + assert changed > 100 + + +def test_far_gap_slow_close_keeps_the_pd_accel_through_the_old_gate_edge(monkeypatch): + """A 0.4 m/s close at the old gate edge used to drop to ~0. + + The soft closing-speed law retires the large PD term past ~30 m, so this + exemplar sits at 22 m, where the PD term still clears the base width. + The widened gate keeps a small accel; the old gate does not. + """ + new = _cmd(22.0, 0.4) + _baseline(monkeypatch) + old = _cmd(22.0, 0.4) + assert old == pytest.approx(0.0, abs=0.01) + assert new > 0.015 + # A faster close is back on the kinematic bound. + assert _cmd(22.0, 0.8) == pytest.approx(0.0, abs=0.05) + assert _cmd(22.0, 1.2) == pytest.approx(0.0, abs=0.1) + + +def test_close_sweep_has_a_smaller_step_than_the_old_gate(monkeypatch): + """The pulse driver is the gate edge: the command steps less per 10 mm/s of closing speed.""" + xs = np.arange(-0.2, 1.6, 0.01) + new = np.array([_cmd(22.0, float(x)) for x in xs]) + _baseline(monkeypatch) + old = np.array([_cmd(22.0, float(x)) for x in xs]) + assert np.abs(np.diff(new)).max() < 0.90 * np.abs(np.diff(old)).max() + assert np.all(new >= old - 1e-12) + + +def test_inside_the_follow_gap_and_real_closes_match_the_old_command(monkeypatch): + for slack, v_close in ((-4.0, 1.0), (3.0, 1.5), (10.0, 2.0), (14.9, 0.6), (40.0, 4.0), (60.0, 6.0)): + new = _cmd(slack, v_close, a_lead=-0.5) + _baseline(monkeypatch) + old = _cmd(slack, v_close, a_lead=-0.5) + monkeypatch.undo() + assert new == old, (slack, v_close) + assert math.isfinite(new) diff --git a/selfdrive/controls/tests/test_unified_lead.py b/selfdrive/controls/tests/test_unified_lead.py new file mode 100644 index 00000000000000..1b3d4ea7e7e746 --- /dev/null +++ b/selfdrive/controls/tests/test_unified_lead.py @@ -0,0 +1,1284 @@ +"""Continuous lead-follow controller. + +Exemplar geometries are the Sep 23 #222 samples, the #241 inside-gap / +over-MAX shapes, the #240 early ease, cut-in, opening/depart, and the MAX +ceiling. The open-loop #240 comfort cap (never below −0.45 before 3 m of +slack) is not reproduced: that cap is what deferred braking into a late bite. +""" +import pathlib + +import pytest + +from openpilot.selfdrive.controls.lib.unified_lead import ( + A_MIN_MS2, + NEED_MARGIN, + K_A_FIRM, + K_A_MILD, + LEAD_ANTICIPATE_MAX_MS2, + UNIFIED_JERK_LIMIT_MS3, + UnifiedLeadController, + _k_a_brake_scale, + gap_set_m, + kinematic_need_accel, + kinematic_required_accel, + lead_trust, + lead_decel_anticipation, + speed_ceiling_accel, + unified_follow_desired, +) + +DT = 0.05 +MPH = 0.44704 +ROOT = pathlib.Path(__file__).resolve().parents[3] + + +def _gap(slack, v_lead, t_follow): + return gap_set_m(v_lead, t_follow) + slack + + +def _settle(n, **kw): + ctrl = UnifiedLeadController() + accel = 0.0 + for _ in range(n): + accel = ctrl.step(dt=DT, present=True, seed_a=0.0, lead_id=1, **kw) + return accel, ctrl + + +def test_glide_is_quiet_when_matched_at_the_setpoint(): + v = 25.0 + tf = 1.3 + gap = gap_set_m(v, tf) + accel = unified_follow_desired(gap, v, v, 0.0, tf, v_ceiling=40.0) + assert abs(accel) < 0.05 + settled, _ = _settle(40, gap=gap, v_ego=v, v_lead=v, a_lead=0.0, t_follow=tf, v_ceiling=40.0) + assert abs(settled) < 0.05 + + +def test_small_error_stays_near_mild_regen(): + """3 m inside, closing 1 m/s, lead not braking: near the EV's −0.22 settle.""" + v_lead = 25.0 + accel = unified_follow_desired( + _gap(-3.0, v_lead, 1.3), 26.0, v_lead, 0.0, 1.3, v_ceiling=40.0, + ) + assert -0.55 <= accel <= -0.15 + + +def test_sep23_222_exemplars_match_a_braking_lead(): + """07:55, 22:14-class, and 23:31 stay firm. They do not fall to −0.22.""" + # 07:55:09 — closing ~1.8 m/s, aLead ~−0.8, a few meters outside the gap. + v_ego = 66.3 * MPH + v_lead = 62.3 * MPH + early, _ = _settle( + 80, gap=_gap(7.0, v_lead, 1.3), v_ego=v_ego, v_lead=v_lead, + a_lead=-0.79, t_follow=1.3, v_ceiling=40.0, + ) + assert early <= -0.60 + assert early > -2.0 + + # 07:55:13 — closing 4.44, aLead −1.04, ~2 m inside. Firm match, not full regen. + v_ego = 62.5 * MPH + v_lead = v_ego - 4.44 + late, _ = _settle( + 80, gap=25.2, v_ego=v_ego, v_lead=v_lead, a_lead=-1.04, + t_follow=0.9, v_ceiling=40.0, + ) + assert late <= -0.90 + assert late > -2.2 + + # 23:31 — outside the gap, aLead ~−1.2, closing ~1.1. This is the + # mutation target for dropping the a_lead term. + v_ego = 30.0 + v_lead = v_ego - 1.13 + keep, _ = _settle( + 80, gap=35.0, v_ego=v_ego, v_lead=v_lead, a_lead=-1.18, + t_follow=0.9, v_ceiling=40.0, + ) + assert keep <= -0.95 + assert keep > -2.2 + + # 22:14-class — aLead −0.65 is firm, −0.35 is not a step to full regen. + mild_line, _ = _settle( + 80, gap=_gap(10.0, v_ego - 1.6, 0.9), v_ego=v_ego, v_lead=v_ego - 1.6, + a_lead=-0.34, t_follow=0.9, v_ceiling=40.0, + ) + firm, _ = _settle( + 80, gap=_gap(10.0, v_ego - 1.6, 0.9), v_ego=v_ego, v_lead=v_ego - 1.6, + a_lead=-0.65, t_follow=0.9, v_ceiling=40.0, + ) + assert firm <= -0.55 + assert firm < mild_line - 0.15 + assert abs(firm - mild_line) < 1.2 + + +def test_inside_fd_0803_and_short_headway(): + """08:03 is about −0.40. Headway under 0.5 s reaches about −1.""" + accel, _ = _settle( + 60, gap=19.7, v_ego=33.5, v_lead=32.5, a_lead=0.0, t_follow=0.9, v_ceiling=40.0, + ) + assert accel == pytest.approx(-0.40, abs=0.10) + assert accel <= -0.35 + for closing in (1.1, 0.8, 0.5, 0.35): + sample = unified_follow_desired( + 19.7, 33.5, 33.5 - closing, 0.0, 0.9, v_ceiling=40.0, + ) + assert sample <= -0.35 + short = unified_follow_desired(8.0, 25.0, 23.0, 0.0, 0.9, v_ceiling=30.0) + assert short <= -0.90 + assert short >= A_MIN_MS2 + + +def test_closing_rate_around_1_5_does_not_cliff(): + published = {} + for closing in (1.49, 1.50): + published[closing] = unified_follow_desired( + 20.0, 33.0, 33.0 - closing, 0.0, 0.9, v_ceiling=33.0, + ) + assert published[closing] <= -0.35 + assert abs(published[1.50] - published[1.49]) < 0.02 + + +def test_firm_lead_handoff_does_not_step_to_mild(): + """08:07: aLead rising through −0.23 must not drop the command to −0.22.""" + v_ego = 30.0 + v_lead = 28.4 + ctrl = UnifiedLeadController() + prev = 0.0 + for i in range(70): + a_lead = -1.0 if i < 50 else -0.23 + accel = ctrl.step( + dt=DT, present=True, gap=_gap(6.0, v_lead, 0.9), v_ego=v_ego, v_lead=v_lead, + a_lead=a_lead, t_follow=0.9, lead_id=3, seed_a=-0.2, v_ceiling=40.0, + ) + if i == 49: + prev = accel + if i == 50: + assert accel < -0.80 + assert abs(accel - prev) <= UNIFIED_JERK_LIMIT_MS3 * DT + 1e-6 + assert accel < -0.50 + + +def test_flat_approach_eases_early_and_physics_deepens_late(): + """#240: 4.1 m/s from 65 m reaches ≤ −0.26 before 30 m of slack. + + The old profile also refused to go below −0.45 before 3 m. This + controller follows the stopping bound instead, so the open-loop trace + (closing speed held constant) is deeper than −0.45 near the gap. It + stays above full regen until the remaining gap is actually short. + """ + v_rel = 4.1 + v_ego = 31.1 + v_lead = v_ego - v_rel + slack = 65.0 + ctrl = UnifiedLeadController() + saw = False + deepest = 0.0 + while slack > 3.0: + accel = ctrl.step( + dt=DT, present=True, gap=_gap(slack, v_lead, 1.3), v_ego=v_ego, + v_lead=v_lead, a_lead=0.0, t_follow=1.3, lead_id=7, seed_a=0.0, v_ceiling=40.0, + ) + if slack > 30.0 and accel <= -0.26: + saw = True + deepest = min(deepest, accel) + assert accel > A_MIN_MS2 + 0.05 or slack < 8.0 + slack -= v_rel * DT + assert saw + assert deepest < -0.45 + + +def test_far_firm_lead_scales_with_physics_not_a_far_cap(): + """No far comfort cap: depth comes from the kinematic and braking-lead terms. + + The old −1.0 far cap (and the −0.55 soft cap until time-to-gap < 3.2 s) + deferred braking on rapid closes (Sep 25 10:07:59). A hard-braking lead + 40 m out is now firm, and a gentle close at the same distance stays mild. + """ + v_ego = 30.0 + v_lead = 26.0 + far, _ = _settle( + 80, gap=_gap(40.0, v_lead, 1.3), v_ego=v_ego, v_lead=v_lead, + a_lead=-2.0, t_follow=1.3, v_ceiling=40.0, + ) + assert -2.5 <= far <= -0.60 + gentle, _ = _settle( + 80, gap=_gap(40.0, v_ego - 1.0, 1.3), v_ego=v_ego, v_lead=v_ego - 1.0, + a_lead=0.0, t_follow=1.3, v_ceiling=40.0, + ) + assert gentle > -0.35 + v_ego = 36.0 * MPH + v_lead = v_ego - 4.2 + near, _ = _settle( + 80, gap=_gap(12.0, v_lead, 0.7), v_ego=v_ego, v_lead=v_lead, + a_lead=-2.06, t_follow=0.7, v_ceiling=40.0, + ) + assert near < -1.5 + + +def test_max_ceiling_blocks_a_faster_lead_and_over_max_brakes(): + """MAX is a hard ceiling. 08:10 is ego over a 70 mph MAX: the speed term brakes.""" + v_max = 60.0 * MPH + faster = v_max + 3.0 * MPH + held, _ = _settle( + 40, gap=_gap(40.0, faster, 1.3), v_ego=v_max, v_lead=faster, + a_lead=0.0, t_follow=1.3, v_ceiling=v_max, + ) + assert held <= 0.05 + # 08:10: 75 mph ego, 70 mph MAX, lead 2 m/s slower. Road-relative; grade is the plant. + over = unified_follow_desired( + _gap(40.0, 75.0 * MPH - 2.0, 0.9), 75.0 * MPH, 75.0 * MPH - 2.0, 0.0, 0.9, + v_ceiling=70.0 * MPH, + ) + assert over <= -0.35 + mapped = unified_follow_desired( + _gap(40.0, 75.0 * MPH - 2.0, 0.9), 75.0 * MPH, 75.0 * MPH - 2.0, 0.0, 0.9, + v_ceiling=70.0 * MPH, a_map=-0.80, + ) + assert mapped <= -0.35 + assert mapped <= over + 1e-9 + + +def test_curve_speed_ceiling_is_a_min(): + """A bend's comfort speed caps the command even when the lead is faster. + + Above the cap the speed-error term brakes in proportion to overspeed + (starting at the EV mild settle), not a clamp toward full regen. + """ + v_ego = 25.0 + v_lead = 28.0 + gap = _gap(15.0, v_lead, 1.3) + open_road = unified_follow_desired(gap, v_ego, v_lead, 0.0, 1.3, v_ceiling=40.0) + assert open_road > 0.0 + v_curve = 22.0 + capped = unified_follow_desired(gap, v_ego, v_lead, 0.0, 1.3, v_ceiling=v_curve) + assert capped <= -0.22 + assert capped >= -1.2 + assert capped < open_road + assert capped == pytest.approx(speed_ceiling_accel(v_ego, v_curve), abs=1e-9) + + +def test_opening_and_depart_release_without_a_one_frame_dump(): + v_ego = 20.0 + v_lead = 16.0 + ctrl = UnifiedLeadController() + accel = 0.0 + for _ in range(30): + accel = ctrl.step( + dt=DT, present=True, gap=_gap(8.0, v_lead, 0.9), v_ego=v_ego, v_lead=v_lead, + a_lead=-1.5, t_follow=0.9, lead_id=1, seed_a=0.0, v_ceiling=30.0, + ) + assert accel < -0.8 + prev = accel + for i in range(50): + accel = ctrl.step( + dt=DT, present=True, gap=_gap(9.0 + i * 0.15, v_ego + 0.8, 0.9), + v_ego=v_ego, v_lead=v_ego + 0.8, a_lead=-0.30, t_follow=0.9, lead_id=1, + seed_a=prev, v_ceiling=30.0, + ) + assert abs(accel - prev) <= UNIFIED_JERK_LIMIT_MS3 * DT + 1e-6 + prev = accel + assert accel > -0.45 + + # On-path close stays firm. A straight depart fades. The same |y| in a + # bend is the lane, so the command stays firm. + v_ego = 16.0 + v_lead = 12.0 + on_path, _ = _settle( + 40, gap=_gap(12.0, v_lead, 0.7), v_ego=v_ego, v_lead=v_lead, a_lead=-2.06, + t_follow=0.7, v_ceiling=30.0, y_rel=0.5, + ) + assert on_path < -1.5 + d_rel = 45.0 + kappa = (2.0 * 1.6) / (d_rel * d_rel) + in_bend = unified_follow_desired( + d_rel, 20.0, 16.0, -1.2, 1.3, v_ceiling=30.0, y_rel=-2.6, curvature=kappa, + ) + straight = unified_follow_desired( + d_rel, 20.0, 16.0, -1.2, 1.3, v_ceiling=30.0, y_rel=-2.6, curvature=0.0, + ) + assert in_bend < -0.6 + assert straight > in_bend + 0.4 + + +def test_cut_in_and_radar_blip_stay_inside_the_jerk_limit(): + ctrl = UnifiedLeadController() + prev = 0.4 + for _ in range(5): + prev = ctrl.step( + dt=DT, present=False, gap=0.0, v_ego=20.0, v_lead=20.0, a_lead=0.0, + t_follow=1.3, lead_id=None, seed_a=prev, + ) + accel = ctrl.step( + dt=DT, present=True, gap=12.0, v_ego=22.0, v_lead=18.0, a_lead=-2.5, + t_follow=1.3, lead_id=9, seed_a=0.4, v_ceiling=30.0, + ) + assert abs(accel - 0.4) <= UNIFIED_JERK_LIMIT_MS3 * DT + 1e-6 + + ctrl = UnifiedLeadController() + for _ in range(30): + prev = ctrl.step( + dt=DT, present=True, gap=gap_set_m(20.0, 1.3), v_ego=20.0, v_lead=20.0, + a_lead=0.0, t_follow=1.3, lead_id=1, seed_a=0.0, v_ceiling=30.0, + ) + blip = ctrl.step( + dt=DT, present=True, gap=gap_set_m(20.0, 1.3), v_ego=20.0, v_lead=20.0, + a_lead=-3.5, t_follow=1.3, lead_id=1, seed_a=prev, v_ceiling=30.0, + ) + assert abs(blip - prev) <= UNIFIED_JERK_LIMIT_MS3 * DT + 1e-6 + assert blip > -1.0 + + +def test_stateful_sweep_has_no_jerk_cliff(): + """Closing 0–4 m/s and gap setpoint ±30 m, one sample per frame.""" + limit = UNIFIED_JERK_LIMIT_MS3 * DT + 1e-9 + v_lead = 25.0 + tf = 1.3 + gap_set = gap_set_m(v_lead, tf) + ctrl = UnifiedLeadController() + prev = 0.0 + for closing in (i * 0.1 for i in range(41)): + for slack in (i - 30.0 for i in range(61)): + accel = ctrl.step( + dt=DT, present=True, gap=gap_set + slack, v_ego=v_lead + closing, + v_lead=v_lead, a_lead=0.0, t_follow=tf, lead_id=1, seed_a=prev, v_ceiling=40.0, + ) + assert abs(accel - prev) <= limit + prev = accel + + +def test_desired_accel_is_continuous_for_small_input_steps(): + v_lead = 25.0 + tf = 1.3 + gap_set = gap_set_m(v_lead, tf) + worst = 0.0 + for closing in (i * 0.05 for i in range(0, 81)): + for slack in (i * 0.25 - 30.0 for i in range(241)): + accel = unified_follow_desired( + gap_set + slack, v_lead + closing, v_lead, 0.0, tf, v_ceiling=40.0, + ) + nxt = unified_follow_desired( + gap_set + slack + 0.25, v_lead + closing, v_lead, 0.0, tf, v_ceiling=40.0, + ) + worst = max(worst, abs(nxt - accel)) + assert worst < 0.85 + + +def test_arrives_at_the_setpoint_already_speed_matched(): + v_lead = 20.0 + tf = 1.3 + gap_set = gap_set_m(v_lead, tf) + v_ego = 22.5 + gap = gap_set + 28.0 + ctrl = UnifiedLeadController() + for _ in range(int(55.0 / DT)): + accel = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=tf, lead_id=1, seed_a=0.0, v_ceiling=35.0, + ) + v_ego = max(0.0, v_ego + accel * DT) + gap += (v_lead - v_ego) * DT + assert abs(gap - gap_set) < 3.0 + assert abs(v_ego - v_lead) < 0.35 + + v_ego = v_lead + 1.2 + gap = gap_set - 10.0 + ctrl = UnifiedLeadController() + for _ in range(int(50.0 / DT)): + accel = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=tf, lead_id=2, seed_a=0.0, v_ceiling=35.0, + ) + v_ego = max(0.0, v_ego + accel * DT) + gap += (v_lead - v_ego) * DT + assert gap > 4.0 + assert abs(gap - gap_set) < 4.0 + assert abs(v_ego - v_lead) < 0.45 + + +def test_unified_is_the_sole_path_and_the_toggle_is_gone(): + keys = (ROOT / "common" / "params_keys.h").read_text() + nap = (ROOT / "selfdrive/ui/layouts/settings/nap.py").read_text() + mici = (ROOT / "selfdrive/ui/mici/layouts/settings/nap.py").read_text() + content = (ROOT / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + planner = (ROOT / "selfdrive/controls/lib/longitudinal_planner.py").read_text() + for text in (keys, nap, mici, content, planner): + assert "NAPLongUnified" not in text + assert "NAP_LONG_UNIFIED" not in text + for text in (planner,): + assert "_unified_enabled" not in text + assert "_mode_w" not in text + assert "_apply_unified_lead" not in text + assert "unifiedATarget" in planner + assert "self._apply_lead_follow(sm, float(v_ego))" in planner + assert planner.index("self.output_a_target = np.clip") < planner.index("self._apply_lead_follow(sm, float(v_ego))") + + +# ---- Sep 25 2026 drives (Scallywag qlogs, routes 11a/11b/11c) ---------------- + +# 09:21:42.00–09:21:47.75 CT at 0.25 s: dRel, vEgo, vRel, aLeadK (t_follow 0.7). +SEP25_0921 = ( + (39.2, 29.94, -4.81, -0.26), (37.9, 29.87, -4.81, -0.24), (36.8, 29.81, -4.81, -0.26), + (35.4, 29.76, -4.81, -0.25), (34.3, 29.68, -4.83, -0.25), (33.1, 29.61, -4.88, -0.28), + (32.0, 29.53, -4.88, -0.31), (30.7, 29.45, -4.88, -0.33), (29.3, 29.39, -4.85, -0.33), + (28.2, 29.32, -4.79, -0.30), (27.2, 29.23, -4.71, -0.23), (26.0, 29.14, -4.60, -0.15), + (24.8, 29.06, -4.52, -0.09), (23.6, 28.98, -4.42, 0.00), (22.7, 28.87, -4.31, 0.01), + (21.5, 28.78, -4.14, 0.07), (20.3, 28.65, -3.98, 0.06), (19.6, 28.43, -3.73, 0.11), + (18.7, 28.14, -3.41, 0.12), (18.0, 27.81, -3.01, 0.16), (17.3, 27.45, -2.68, 0.18), + (16.6, 27.10, -2.29, 0.13), (16.0, 26.75, -1.91, 0.12), (15.6, 26.42, -1.62, 0.11), +) + + +def _interp_rows(rows, step_s=0.25): + n = int(round(step_s / DT)) + out = [] + for a, b in zip(rows, rows[1:], strict=False): + for k in range(n): + f = k / n + out.append(tuple(x + (y - x) * f for x, y in zip(a, b, strict=True))) + out.append(rows[-1]) + return out + + +def _closed_loop(ctrl, *, d, v_ego, lead_v, lead_a, t_follow, seconds, clamp=-1.5, + lag_s=0.3, seed=0.0, v_ceiling=30.0, a0=0.0): + """Road plant with a first-order actuator lag and the Pre-AP decel limit.""" + a_act = a0 + min_gap = d + min_ttc = 99.0 + cmds = [] + for k in range(int(round(seconds / DT))): + t = k * DT + v_l = lead_v(t) + cmd = ctrl.step( + dt=DT, present=True, gap=d, v_ego=v_ego, v_lead=v_l, a_lead=lead_a(t), + t_follow=t_follow, lead_id=1, seed_a=seed, v_ceiling=v_ceiling, + radar=True, model_prob=0.9, + ) + cmds.append(cmd) + a_act += (max(cmd, clamp) - a_act) * DT / lag_s + v_ego = max(0.0, v_ego + a_act * DT) + d += (v_l - v_ego) * DT + min_gap = min(min_gap, d) + if v_ego > v_l + 1e-3: + min_ttc = min(min_ttc, d / (v_ego - v_l)) + return min_gap, min_ttc, cmds + + +def test_sep25_1007_rapid_close_is_at_least_legacy_firm(): + """10:07:59: lead at 61 m, 60 mph, closing 9.5 m/s. Legacy asked about −2.4. + + The old far soft/comfort caps held the unified target at −0.6..−0.8. The + kinematic term −v²/(2·room) now sets the depth from the first frame. + """ + desired = unified_follow_desired(61.2, 26.68, 17.19, -0.27, 0.7, v_ceiling=29.2) + assert desired <= -2.4 + assert desired >= A_MIN_MS2 + 0.3 + # From zero (no seed from legacy): full depth within about a second. + ctrl = UnifiedLeadController() + reached = None + for k in range(40): + gap = 61.2 - 9.5 * k * DT + accel = ctrl.step( + dt=DT, present=True, gap=gap, v_ego=26.68, v_lead=17.19, a_lead=-0.27, + t_follow=0.7, lead_id=1027, seed_a=0.0, v_ceiling=29.2, radar=True, model_prob=0.87, + ) + if reached is None and accel <= -2.4: + reached = k * DT + assert reached is not None and reached <= 1.2 + # A slow close at the same distance stays small (continuous, not a rule). + slow = unified_follow_desired(61.2, 26.68, 26.68 - 1.0, 0.0, 0.7, v_ceiling=29.2) + assert -0.45 <= slow <= 0.0 + + +# 10:10:13.0 CT onward at 0.25 s: logged vLead, aLeadK of the lead first seen at 51.8 m. +SEP25_1010_LEAD = ( + (-0.23, -1.3), (-0.2, -1.08), (-0.12, -0.83), (-0.11, -0.46), (-0.11, -0.24), (-0.22, -0.13), + (-0.06, -0.14), (-0.03, -0.09), (0.05, 0.0), (0.28, -0.08), (0.32, -0.06), (0.0, 0.0), + (0.14, 0.15), (0.31, 0.22), (0.48, 0.3), (0.54, 0.41), (0.69, 0.47), (0.95, 0.47), + (0.92, 0.56), (1.41, 0.59), (1.99, 0.74), (2.41, 1.14), (2.58, 1.41), (2.85, 1.42), + (3.0, 1.42), (3.18, 1.47), (3.31, 1.51), (3.23, 1.51), (3.33, 1.38), (3.8, 1.22), + (4.11, 1.28), (4.56, 1.33), +) + + +def _series(rows, col): + def f(t): + i = min(len(rows) - 1, int(t / 0.25)) + j = min(len(rows) - 1, i + 1) + x = min(1.0, max(0.0, t / 0.25 - i)) + return rows[i][col] + (rows[j][col] - rows[i][col]) * x + return f + + +def test_sep25_1010_own_target_keeps_a_safe_gap_from_zero(): + """10:10:13: 52 m to a stopped lead at 25 mph (closing 11.4 m/s). + + The unified target starts from 0 (not seeded from legacy). The plant + starts where the car was (aEgo −1.2) and is limited to the Pre-AP −1.5. + Legacy's real outcome was about 13 m / TTC 3.4 s; the old unified + target reached 7.8 m / 2.2 s in the same loop. + """ + min_gap, min_ttc, cmds = _closed_loop( + UnifiedLeadController(), d=51.8, v_ego=11.18, + lead_v=lambda t: max(0.0, _series(SEP25_1010_LEAD, 0)(t)), + lead_a=_series(SEP25_1010_LEAD, 1), + t_follow=1.7, seconds=8.0, v_ceiling=21.0, a0=-1.22, + ) + assert min_gap >= 12.0 + assert min_ttc >= 3.2 + assert min(cmds[:20]) <= -1.5 + + +def test_sep25_0921_close_has_no_spike_or_long_hold(): + """09:21:44: 4.9 m/s close from 29 m at 70 mph, t_follow 0.7. + + The old controller spiked to −3.5 and held −1.7..−3.2 for ~5 s while + legacy asked −1.1. The target is now firm but proportionate. + """ + rows = _interp_rows(SEP25_0921) + ctrl = UnifiedLeadController() + d0, v0, vr0, al0 = rows[0] + for _ in range(40): + ctrl.step( + dt=DT, present=True, gap=d0, v_ego=v0, v_lead=v0 + vr0, a_lead=al0, + t_follow=0.7, lead_id=920, seed_a=-0.45, v_ceiling=31.0, radar=True, model_prob=1.0, + ) + out = [] + for d, v, vr, al in rows: + out.append(ctrl.step( + dt=DT, present=True, gap=d, v_ego=v, v_lead=v + vr, a_lead=al, + t_follow=0.7, lead_id=920, seed_a=-0.45, v_ceiling=31.0, radar=True, model_prob=1.0, + )) + assert min(out) > -2.0 + assert sum(1 for a in out if a < -1.7) * DT <= 0.25 + assert min(out) <= -0.8 + + +def test_sep25_1043_overspeed_is_proportional_not_a_clamp(): + """10:43:56: MAX/curve cap 6.4 m/s at 13.7 m/s. Old: −3.5, then −2.7 held. + + Above the cap the speed-error term starts at the mild settle and only + gets firmer when well over. It never accelerates above the cap. + """ + over = speed_ceiling_accel(13.7, 6.4) + assert -1.2 <= over <= -0.5 + assert -0.22 <= speed_ceiling_accel(6.6, 6.4) <= 0.0 + assert abs(speed_ceiling_accel(6.4 + 1e-3, 6.4) - speed_ceiling_accel(6.4 - 1e-3, 6.4)) < 0.01 + prev = 0.0 + for i in range(1, 200): + a = speed_ceiling_accel(6.4 + i * 0.05, 6.4) + assert a <= prev + 1e-12 + assert a <= 0.0 + prev = a + assert speed_ceiling_accel(6.4 + 0.45, 6.4) == pytest.approx(-0.22, abs=0.03) + ctrl = UnifiedLeadController() + worst = 0.0 + for _ in range(100): + accel = ctrl.step( + dt=DT, present=True, gap=35.8, v_ego=13.7, v_lead=12.4, a_lead=0.0, + t_follow=1.3, lead_id=4, seed_a=0.0, v_ceiling=6.4, radar=True, model_prob=0.9, + ) + worst = min(worst, accel) + assert worst > -1.3 + assert worst < -0.3 + + +@pytest.mark.parametrize("gap,v_ego,v_rel", [ + (47.8, 28.57, 0.30), (27.3, 25.67, 0.98), (36.7, 26.15, 2.02), (46.6, 27.55, 1.52), +]) +def test_sep25_pulling_away_lead_near_gap_is_a_trickle(gap, v_ego, v_rel): + """09:47:41–58 and 10:54:08–19: legacy about +0.08; old unified +0.5..+0.8.""" + accel, _ = _settle( + 60, gap=gap, v_ego=v_ego, v_lead=v_ego + v_rel, a_lead=0.0, t_follow=0.7, + v_ceiling=31.3, + ) + assert 0.0 <= accel <= 0.15 + + +def test_no_jump_across_the_follow_distance(): + """One smooth gap curve: no step at the setpoint, bounded slope around it.""" + for v_lead in (8.0, 20.0, 30.0): + for tf in (0.7, 1.3, 1.7): + gap_set = gap_set_m(v_lead, tf) + for closing in (0.0, 0.5, 1.5, 3.0, 6.0, 9.0): + for a_lead in (0.0, -1.0): + def f(slack, closing=closing, a_lead=a_lead, gap_set=gap_set, v_lead=v_lead, tf=tf): + return unified_follow_desired( + gap_set + slack, v_lead + closing, v_lead, a_lead, tf, v_ceiling=40.0, + ) + assert abs(f(0.01) - f(-0.01)) < 0.02 + prev = f(-8.0) + for i in range(1, 321): + cur = f(-8.0 + i * 0.05) + assert abs(cur - prev) < 0.08 + prev = cur + # The kinematic term itself is continuous in the gap error. + for closing in (1.0, 4.0, 9.0): + lo = kinematic_required_accel(-1e-3, closing, tf, v_lead) + hi = kinematic_required_accel(1e-3, closing, tf, v_lead) + assert abs(hi - lo) < 0.01 + + +def test_lead_confidence_weights_weak_readings_and_ramps_strong_ones(): + """Blips have little effect; a consistent fast close owns the command fast.""" + def run(n, **quality): + ctrl = UnifiedLeadController() + out = [] + for _ in range(n): + out.append(ctrl.step( + dt=DT, present=True, gap=30.0, v_ego=25.0, v_lead=21.0, a_lead=0.0, + t_follow=1.3, lead_id=5, seed_a=0.0, v_ceiling=35.0, **quality, + )) + return out, ctrl + + strong, ctrl_s = run(20, radar=True, model_prob=0.95) + weak, _ = run(20, radar=False, model_prob=0.15) + assert strong[-1] <= -0.8 + assert abs(weak[-1]) < 0.5 * abs(strong[-1]) + + # Rapid close: confidence reaches ~full within a fraction of a second. + ctrl = UnifiedLeadController() + t_full = None + for k in range(20): + ctrl.step( + dt=DT, present=True, gap=61.0 - 9.5 * k * DT, v_ego=26.7, v_lead=17.2, a_lead=0.0, + t_follow=0.7, lead_id=6, seed_a=0.0, v_ceiling=30.0, radar=True, model_prob=0.9, + ) + if t_full is None and ctrl.last_confidence >= 0.9: + t_full = k * DT + assert t_full is not None and t_full <= 0.4 + + # One-frame overhead/ghost reading while following at the setpoint. + ctrl = UnifiedLeadController() + gs = gap_set_m(25.0, 1.3) + prev = 0.0 + for _ in range(60): + prev = ctrl.step( + dt=DT, present=True, gap=gs, v_ego=25.0, v_lead=25.0, a_lead=0.0, + t_follow=1.3, lead_id=1, seed_a=0.0, v_ceiling=35.0, radar=True, model_prob=0.95, + ) + base = prev + worst = 0.0 + ctrl.step( + dt=DT, present=True, gap=20.0, v_ego=25.0, v_lead=0.0, a_lead=0.0, + t_follow=1.3, lead_id=99, seed_a=prev, v_ceiling=35.0, radar=True, model_prob=0.3, + ) + for _ in range(40): + a = ctrl.step( + dt=DT, present=True, gap=gs, v_ego=25.0, v_lead=25.0, a_lead=0.0, + t_follow=1.3, lead_id=1, seed_a=prev, v_ceiling=35.0, radar=True, model_prob=0.95, + ) + worst = max(worst, abs(a - base)) + assert worst < 0.15 + + +def test_release_rate_is_proportional_to_how_far_below_target(): + """Far too firm releases fast; close to the target releases gently.""" + ctrl = UnifiedLeadController() + v_ego = 20.0 + prev = 0.0 + for _ in range(60): + prev = ctrl.step( + dt=DT, present=True, gap=12.0, v_ego=v_ego, v_lead=14.0, a_lead=-2.5, + t_follow=1.3, lead_id=2, seed_a=0.0, v_ceiling=30.0, radar=True, model_prob=0.95, + ) + assert prev <= -2.0 + rates = [] + for _ in range(60): + a = ctrl.step( + dt=DT, present=True, gap=_gap(0.0, v_ego, 1.3), v_ego=v_ego, v_lead=v_ego, a_lead=0.0, + t_follow=1.3, lead_id=2, seed_a=prev, v_ceiling=30.0, radar=True, model_prob=0.95, + ) + rates.append(((a - prev) / DT, ctrl.last_desired - a)) + prev = a + far = [r for r, gap_to_target in rates if gap_to_target > 1.0] + assert far and min(far) >= 1.8 + near = [r for r, gap_to_target in rates if 0.02 < gap_to_target < 0.15] + assert near and max(near) <= 0.8 + + +# #222 log exemplars at 0.25 s: (dRel, vLead, aLeadK, vEgo, tFollow), open loop +# on the logged ego. 07:55:06 CT Sep 20 (route 000000ed), 22:14:11 CT Sep 23 +# (00000110), 23:31:01 CT Sep 22 (00000104). Legacy (logged aTarget, 4 Hz) +# first reached -0.5 at: never (07:55, min -0.22), 2.0 s (22:14), 2.5 s (23:31). +SEP20_0755_ROWS = ( + (40.69, 29.6, 0.03, 30.04, 0.9), (40.44, 29.59, -0.03, 30.03, 0.9), (40.38, 29.58, -0.04, 30.02, 0.9), + (40.31, 29.58, -0.05, 30.01, 0.9), (41.35, 29.45, -0.03, 30.01, 0.9), (41.13, 29.2, -0.12, 30.01, 0.9), + (40.27, 29.0, -0.24, 29.99, 0.9), (39.89, 28.91, -0.49, 29.97, 0.9), (39.45, 28.75, -0.56, 29.93, 0.9), + (39.19, 28.57, -0.6, 29.86, 0.9), (38.94, 28.44, -0.63, 29.82, 0.9), (38.57, 28.19, -0.61, 29.74, 0.9), + (38.02, 27.87, -0.67, 29.67, 0.9), (37.57, 27.68, -0.79, 29.6, 0.9), (37.08, 27.49, -0.87, 29.55, 0.9), + (36.52, 27.17, -0.87, 29.47, 0.9), (35.95, 27.01, -0.92, 29.38, 0.9), (35.21, 26.74, -0.94, 29.3, 0.9), + (34.7, 26.56, -0.95, 29.22, 0.9), (33.96, 26.17, -0.94, 29.14, 0.9), (33.09, 25.88, -0.97, 29.07, 0.9), + (32.21, 25.62, -1.04, 28.98, 0.9), (31.64, 25.5, -1.06, 28.91, 0.9), (30.65, 25.2, -1.04, 28.83, 0.9), + (29.59, 24.94, -1.02, 28.75, 0.9), (28.4, 24.6, -0.99, 28.65, 0.9), (27.46, 24.46, -1.03, 28.57, 0.9), + (26.28, 24.2, -1.01, 28.49, 0.9), (25.21, 23.79, -1.01, 28.22, 0.9), (24.21, 23.56, -1.04, 27.87, 0.9), + (23.15, 23.3, -1.12, 27.47, 0.9), (22.03, 23.0, -1.09, 27.0, 0.9), (21.09, 22.65, -1.13, 26.52, 0.9), + (20.03, 22.49, -1.18, 26.04, 0.9), (19.15, 22.32, -1.1, 25.57, 0.9), (18.45, 22.08, -0.99, 25.04, 0.9), + (17.89, 21.84, -0.95, 24.53, 0.9), +) + +SEP23_2214_ROWS = ( + (41.47, 31.18, -0.08, 29.58, 0.7), (41.63, 31.1, -0.14, 29.71, 0.7), (41.82, 30.9, -0.23, 29.83, 0.7), + (42.03, 30.74, -0.38, 29.94, 0.7), (42.19, 30.59, -0.48, 30.05, 0.7), (42.38, 30.44, -0.54, 30.13, 0.7), + (42.44, 30.3, -0.59, 30.21, 0.7), (42.38, 30.12, -0.6, 30.25, 0.7), (42.34, 29.9, -0.65, 30.26, 0.7), + (42.28, 29.74, -0.72, 30.19, 0.7), (42.15, 29.72, -0.75, 30.15, 0.7), (42.0, 29.75, -0.58, 30.09, 0.7), + (41.97, 29.82, -0.41, 30.02, 0.7), (41.94, 29.97, -0.2, 29.96, 0.7), (41.91, 30.07, 0.1, 29.91, 0.7), + (41.97, 30.18, 0.23, 29.89, 0.7), (42.03, 30.28, 0.35, 29.87, 0.7), (42.13, 30.35, 0.4, 29.89, 0.7), + (42.28, 30.44, 0.4, 29.91, 0.7), (42.38, 30.48, 0.4, 29.95, 0.7), (52.61, 27.66, -0.31, 29.98, 0.7), + (52.08, 27.55, -0.31, 29.98, 0.7), (51.52, 27.5, -0.35, 29.97, 0.7), (50.86, 27.43, -0.33, 29.94, 0.7), + (50.18, 27.28, -0.32, 29.9, 0.7), (49.49, 27.13, -0.38, 29.85, 0.7), (48.83, 27.1, -0.41, 29.82, 0.7), + (48.17, 27.01, -0.37, 29.75, 0.7), (47.36, 26.89, -0.39, 29.7, 0.7), (46.61, 26.85, -0.37, 29.64, 0.7), + (45.92, 26.73, -0.35, 29.6, 0.7), (45.14, 26.6, -0.38, 29.53, 0.7), (44.43, 26.56, -0.39, 29.47, 0.7), + (43.83, 26.53, -0.33, 29.41, 0.7), (43.11, 26.45, -0.29, 29.31, 0.7), (42.3, 26.36, -0.28, 29.18, 0.7), + (41.61, 26.22, -0.28, 28.93, 0.7), +) + +SEP22_2331_ROWS = ( + (38.97, 31.88, -0.06, 32.4, 0.7), (38.85, 31.87, -0.09, 32.41, 0.7), (38.72, 31.88, -0.09, 32.37, 0.7), + (38.6, 31.89, -0.07, 32.34, 0.7), (38.47, 31.82, -0.05, 32.3, 0.7), (38.35, 31.77, -0.1, 32.27, 0.7), + (38.22, 31.69, -0.14, 32.26, 0.7), (38.1, 31.67, -0.15, 32.23, 0.7), (37.97, 31.56, -0.19, 32.21, 0.7), + (37.84, 31.39, -0.24, 32.13, 0.7), (37.65, 31.16, -0.39, 32.04, 0.7), (37.41, 31.0, -0.47, 31.93, 0.7), + (37.02, 30.63, -0.68, 31.76, 0.7), (36.79, 30.4, -0.74, 31.5, 0.7), (36.4, 30.07, -0.99, 31.18, 0.7), + (36.19, 29.84, -1.06, 30.93, 0.7), (35.88, 29.64, -1.06, 30.64, 0.7), (35.59, 29.35, -1.06, 30.34, 0.7), + (35.39, 29.09, -1.09, 30.08, 0.7), (35.13, 28.78, -1.14, 29.77, 0.7), (34.82, 28.46, -1.17, 29.48, 0.7), + (34.56, 28.17, -1.18, 29.22, 0.7), (34.26, 27.9, -1.17, 28.9, 0.7), (34.0, 27.56, -1.17, 28.62, 0.7), + (33.71, 27.28, -1.17, 28.31, 0.7), (33.51, 27.08, -1.13, 28.02, 0.7), (33.28, 26.75, -1.12, 27.73, 0.7), + (33.1, 26.58, -1.08, 27.41, 0.7), (32.96, 26.38, -1.06, 27.11, 0.7), (32.79, 26.21, -0.99, 26.8, 0.7), + (32.65, 26.06, -0.94, 26.49, 0.7), (32.5, 25.99, -0.77, 26.19, 0.7), (32.5, 25.9, -0.69, 25.89, 0.7), + (32.52, 25.83, -0.53, 25.57, 0.7), (32.65, 25.78, -0.43, 25.28, 0.7), (32.8, 25.79, -0.32, 24.96, 0.7), + (33.06, 25.78, -0.19, 24.65, 0.7), +) + + +def _log_replay(rows, seed): + ctrl = UnifiedLeadController() + out = [] + for d, v_lead, a_lead, v_ego, t_follow in _interp_rows(rows): + out.append(ctrl.step( + dt=DT, present=True, gap=d, v_ego=v_ego, v_lead=v_lead, a_lead=a_lead, + t_follow=t_follow, lead_id=1, seed_a=seed, v_ceiling=40.0, radar=True, model_prob=0.9, + )) + return out + + +def _first_at_or_below(cmds, level): + for k, a in enumerate(cmds): + if a <= level: + return k * DT + return None + + +@pytest.mark.parametrize("rows, seed, t05_max, t10_max, min_max", [ + # a8664c10 unified: 1.95 / 3.15 s. Legacy never braked (-0.22). + (SEP20_0755_ROWS, -0.02, 1.8, 2.2, -2.0), + # a8664c10 unified: 2.05 s / never. Legacy 2.0 s. + (SEP23_2214_ROWS, 0.37, 1.2, None, -0.9), + # a8664c10 unified: 2.9 / 3.65 s. Legacy 2.5 s at 4 Hz. + (SEP22_2331_ROWS, -0.02, 2.7, 3.0, -2.0), +]) +def test_222_log_exemplars_brake_promptly_and_firmly(rows, seed, t05_max, t10_max, min_max): + """Real #222 lead braking: onset anticipated, firm, never past full regen.""" + cmds = _log_replay(rows, seed) + t05 = _first_at_or_below(cmds, -0.5) + assert t05 is not None and t05 <= t05_max + if t10_max is not None: + t10 = _first_at_or_below(cmds, -1.0) + assert t10 is not None and t10 <= t10_max + assert min(cmds) <= min_max + assert min(cmds) >= A_MIN_MS2 + + +def test_lead_decel_anticipation_is_continuous_and_bounded(): + # Steady or recovering lead: nothing added. + assert lead_decel_anticipation(-1.0, 0.0, 30.0, 30.0) == 0.0 + assert lead_decel_anticipation(-1.0, 0.8, 30.0, 30.0) == 0.0 + # Real braking onset at a short headway: anticipated, capped. + firm = lead_decel_anticipation(-0.8, -1.2, 30.0, 30.0) + assert 0.5 <= firm <= LEAD_ANTICIPATE_MAX_MS2 + 1e-9 + # Long headway (>3.5 s) or a lead that is barely slowing: nothing. + assert lead_decel_anticipation(-0.8, -1.2, 110.0, 30.0) == 0.0 + assert lead_decel_anticipation(-0.05, -1.2, 30.0, 30.0) == 0.0 + # Gradual slowdown (small decel onset rate) barely moves it. + assert lead_decel_anticipation(-0.3, -0.25, 30.0, 30.0) < 0.1 + # No step anywhere in a fine sweep. + prev = None + for i in range(400): + j = -3.0 + i * 0.0075 + val = lead_decel_anticipation(-0.6, j, 30.0, 30.0) + if prev is not None: + assert abs(val - prev) < 0.05 + prev = val + + +def _brake_onset(ctrl_cls, *, a_final, jerk, seconds=4.0): + """Lead at the setpoint, matched speed, starts braking at `jerk` to `a_final`.""" + ctrl = ctrl_cls() + v = 27.0 + t_follow = 1.2 + d = gap_set_m(v, t_follow) + v_l = v + a_l = 0.0 + cmds = [] + for k in range(int(round(seconds / DT))): + a_l = max(a_final, a_l + jerk * DT) if k * DT >= 0.5 else 0.0 + cmds.append(ctrl.step( + dt=DT, present=True, gap=d, v_ego=v, v_lead=v_l, a_lead=a_l, t_follow=t_follow, + lead_id=1, seed_a=0.0, v_ceiling=40.0, radar=True, model_prob=0.9, + )) + v_l += a_l * DT + d += (v_l - v) * DT + return cmds + + +def test_real_lead_brake_onset_is_anticipated_but_gradual_slowdown_is_not(monkeypatch): + import openpilot.selfdrive.controls.lib.unified_lead as ul + brake = _brake_onset(UnifiedLeadController, a_final=-2.5, jerk=-2.5) + gradual = _brake_onset(UnifiedLeadController, a_final=-0.5, jerk=-0.3, seconds=6.0) + monkeypatch.setattr(ul, "LEAD_ANTICIPATE_T_S", 0.0) + brake_plain = _brake_onset(UnifiedLeadController, a_final=-2.5, jerk=-2.5) + gradual_plain = _brake_onset(UnifiedLeadController, a_final=-0.5, jerk=-0.3, seconds=6.0) + t_ant = _first_at_or_below(brake, -0.5) + t_plain = _first_at_or_below(brake_plain, -0.5) + assert t_ant is not None and t_plain is not None + assert t_ant <= t_plain - 0.1 + # Gradual -0.5 slowdown (includes catching the growing gap error): no + # firmer than a8664c10 (-0.91) and anticipation adds nothing to it. + assert min(gradual) >= -0.88 + assert min(gradual) >= min(gradual_plain) - 0.02 + + +def test_mild_lead_slowing_is_under_matched_and_braking_over_matched(): + assert _k_a_brake_scale(-0.1) == pytest.approx(K_A_MILD) + assert _k_a_brake_scale(-1.2) == pytest.approx(K_A_FIRM) + assert K_A_MILD < 1.0 < K_A_FIRM + v = 27.0 + gap = gap_set_m(v, 1.2) + mild = unified_follow_desired(gap, v, v, -0.3, 1.2, v_ceiling=40.0) + firm = unified_follow_desired(gap, v, v, -1.2, 1.2, v_ceiling=40.0) + assert -0.3 <= mild < 0.0 + assert firm <= -1.2 * 1.05 + # Smooth in between: no step across the blend. + prev = None + for i in range(200): + a_l = -0.1 - i * 0.006 + val = unified_follow_desired(gap, v, v, a_l, 1.2, v_ceiling=40.0) + if prev is not None: + assert abs(val - prev) < 0.03 + prev = val + + +def test_small_inside_gap_keeps_easing_until_the_gap_recovers(monkeypatch): + """3 m inside at matched speed: a gentle ease that does not stall short. + + The glide (matched speed, lead not braking) removes less of the gap term + inside the setpoint than at it, so the ease continues until the gap is back. + """ + import openpilot.selfdrive.controls.lib.unified_lead as ul + v = 27.0 + t_follow = 1.2 + gap = gap_set_m(v, t_follow) + inside = unified_follow_desired(gap - 3.0, v, v, 0.0, t_follow, v_ceiling=40.0) + at_set = unified_follow_desired(gap, v, v, 0.0, t_follow, v_ceiling=40.0) + monkeypatch.setattr(ul, "GLIDE_KEEP_INSIDE", ul.GLIDE_KEEP) + inside_plain = unified_follow_desired(gap - 3.0, v, v, 0.0, t_follow, v_ceiling=40.0) + monkeypatch.undo() + assert -0.3 <= inside <= inside_plain - 0.003 + assert inside < at_set + ctrl = UnifiedLeadController() + d0 = gap - 3.0 + _, _, cmds = _closed_loop( + ctrl, d=d0, v_ego=v, lead_v=lambda t: v, lead_a=lambda t: 0.0, + t_follow=t_follow, seconds=30.0, v_ceiling=40.0, + ) + assert min(cmds) >= -0.3 + # Replay the plant to find the gap error at the end. + a_act = 0.0 + v_e = v + d = d0 + for cmd in cmds: + a_act += (max(cmd, -1.5) - a_act) * DT / 0.3 + v_e += a_act * DT + d += (v - v_e) * DT + assert d - gap >= -1.0 + + +def test_far_slow_close_coasts_near_close_does_not(monkeypatch): + """Closing gain fades with time-to-gap (12 → 30 s): far slow closes nibble less.""" + import openpilot.selfdrive.controls.lib.unified_lead as ul + v_l = 25.0 + gap = gap_set_m(v_l, 1.2) + far = unified_follow_desired(gap + 70.0, v_l + 1.5, v_l, 0.0, 1.2, v_ceiling=40.0) + assert -0.10 <= far <= 0.0 + near = unified_follow_desired(gap + 10.0, v_l + 1.5, v_l, 0.0, 1.2, v_ceiling=40.0) + assert near <= -0.12 + assert near < far - 0.08 + # ttg ~33 s (10 m at 0.3 m/s) vs ~7 s (2 m): only the far one is faded. + slow_far = unified_follow_desired(gap + 10.0, v_l + 0.3, v_l, -0.3, 1.2, v_ceiling=40.0) + slow_near = unified_follow_desired(gap + 2.0, v_l + 0.3, v_l, -0.3, 1.2, v_ceiling=40.0) + monkeypatch.setattr(ul, "K_V_FAR_MIN", 1.0) + slow_far_plain = unified_follow_desired(gap + 10.0, v_l + 0.3, v_l, -0.3, 1.2, v_ceiling=40.0) + slow_near_plain = unified_follow_desired(gap + 2.0, v_l + 0.3, v_l, -0.3, 1.2, v_ceiling=40.0) + assert slow_far >= slow_far_plain + 0.002 + assert slow_near == pytest.approx(slow_near_plain, abs=1e-9) + + +# Sep 28 2026 11:07:22 CT, route 00000124 (unified ON), qlog at 0.1 s. +# (dRel, vLead, aLeadK, yRel, radar, modelProb, trackId, vEgo, override, aTarget) +# or (None, vEgo, override, aTarget) with no lead in the sample. `override` +# is the driver on the pedal (longActive off: the planner resets every frame +# and seeds from the legacy command). Logged unified/aTarget: -3.46..-3.50 +# for ~1 s on a lead 80-120 m ahead, yRel up to ~2 m. +SEP28_1107_ROWS = ( + (None, 19.29, 1, 0.0), (None, 19.31, 1, 0.0), (None, 19.31, 1, 0.0), + (141.69, 11.06, -0.4, -2.52, 1, 0.56, 1929, 19.31, 1, 0.0), + (141.69, 11.06, -0.4, -2.52, 1, 0.56, 1929, 19.31, 1, 0.0), + (139.38, 10.79, -0.59, -2.39, 1, 0.63, 1929, 19.27, 1, -0.11), + (139.38, 10.79, -0.59, -2.39, 1, 0.63, 1929, 19.23, 1, -0.11), + (139.38, 10.79, -0.59, -2.39, 1, 0.63, 1929, 19.17, 1, -0.11), (None, 19.14, 1, -0.11), (None, 19.12, 1, -0.11), + (None, 19.11, 1, -0.15), (None, 19.1, 1, -0.15), (None, 19.09, 1, -0.15), (None, 19.07, 1, -0.15), + (None, 19.07, 1, -0.15), (None, 19.04, 1, -0.14), (None, 19.01, 1, -0.14), (None, 19.02, 1, -0.14), + (None, 19.03, 1, -0.14), (None, 19.0, 1, -0.14), (None, 18.97, 1, -0.41), (None, 18.94, 1, -0.41), + (None, 18.91, 1, -0.41), (None, 18.87, 1, -0.41), (None, 18.81, 1, -0.41), + (119.81, 7.57, -1.91, 0.73, 1, 0.64, 1929, 18.75, 1, -0.33), + (119.81, 7.57, -1.91, 0.73, 1, 0.64, 1929, 18.69, 1, -0.33), + (119.81, 7.57, -1.91, 0.73, 1, 0.64, 1929, 18.62, 1, -0.33), (None, 18.56, 1, -0.33), (None, 18.52, 1, -0.33), + (None, 18.46, 1, -3.46), (None, 18.41, 1, -3.46), (None, 18.36, 1, -3.46), + (111.12, 6.73, -1.53, 1.98, 1, 0.82, 1929, 18.3, 1, -3.46), + (111.12, 6.73, -1.53, 1.98, 1, 0.82, 1929, 18.24, 1, -3.46), + (80.14, 12.54, -0.63, 0.83, 0, 0.92, -1, 18.19, 1, -3.5), (80.14, 12.54, -0.63, 0.83, 0, 0.92, -1, 18.13, 0, -3.5), + (80.14, 12.54, -0.63, 0.83, 0, 0.92, -1, 18.06, 1, -3.5), (None, 17.99, 1, -3.5), (None, 17.92, 0, -3.5), + (None, 17.84, 0, -0.1), (None, 17.75, 0, -0.1), (None, 17.66, 0, -0.1), (None, 17.58, 0, -0.1), + (None, 17.5, 1, -0.1), (None, 17.42, 0, -0.2), +) + + +def _replay_1107(resets=True): + ctrl = UnifiedLeadController() + out = [] + for row in SEP28_1107_ROWS: + if row[0] is None: + _, v_ego, override, seed = row + lead = None + else: + d, v_lead, a_lead, y_rel, radar, mprob, track, v_ego, override, seed = row + lead = (d, v_lead, a_lead, y_rel, bool(radar), mprob, track) + for _ in range(2): + if resets and override: + ctrl.reset() + if lead is None: + a = ctrl.step(dt=DT, present=False, gap=0.0, v_ego=v_ego, v_lead=0.0, a_lead=0.0, + t_follow=1.7, lead_id=None, seed_a=seed) + out.append((None, override, a)) + continue + d, v_lead, a_lead, y_rel, radar, mprob, track = lead + a = ctrl.step(dt=DT, present=True, gap=d, v_ego=v_ego, v_lead=v_lead, a_lead=a_lead, + t_follow=1.7, lead_id=("radar", track), seed_a=seed, v_ceiling=68.37 / 3.6, + y_rel=y_rel, model_prob=mprob, radar=radar, a_max=1.2) + need = kinematic_need_accel(d, v_ego, v_lead, a_lead, 1.7) + out.append((need, override, a)) + return out + + +@pytest.mark.parametrize("resets", [True, False]) +def test_sep28_1107_far_ambiguous_lead_is_not_a_full_regen_flash(resets): + """11:07:22: no firm decel past what the kinematics need. Logged -3.46/-3.50.""" + out = _replay_1107(resets) + with_lead = [(need, ovr, a) for need, ovr, a in out if need is not None] + assert with_lead + recent = [] + for need, _, a in with_lead: + # Physical need with margin (deepest in the last 0.5 s, so a jerk-limited + # release after a lead switch is not a failure), plus a little blend. + recent = (recent + [need])[-10:] + assert a >= min(-0.45, NEED_MARGIN * min(recent)) - 0.25 + assert a >= A_MIN_MS2 + published = min(a for _, _, a in with_lead) + assert published >= -1.8 + engaged = [a for _, ovr, a in with_lead if not ovr] + if resets: + # Gas released onto the 80 m lead: the legacy -3.5 seed is not carried. + assert engaged and min(engaged) >= -1.0 + # Still responds to the real closer (vRel ~ -11 m/s). + assert published <= -0.3 + + +def test_far_offset_or_weak_lead_cannot_reach_full_regen(): + """111 m, closing 11.6, aLead -1.5, yRel 2 m: physics needs ~-1.1, not -3.5.""" + v_ego, v_lead, gap = 18.3, 6.73, 111.1 + need = kinematic_need_accel(gap, v_ego, v_lead, -1.53, 1.7) + assert -1.7 <= need <= -0.8 + offset = unified_follow_desired(gap, v_ego, v_lead, -1.53, 1.7, v_ceiling=19.0, + y_rel=1.98, model_prob=0.82, radar=True) + in_path = unified_follow_desired(gap, v_ego, v_lead, -1.53, 1.7, v_ceiling=19.0, + y_rel=0.0, model_prob=0.82, radar=True) + weak = unified_follow_desired(gap, v_ego, v_lead, -1.53, 1.7, v_ceiling=19.0, + y_rel=0.0, model_prob=0.3, radar=False) + for a in (offset, in_path, weak): + assert a >= NEED_MARGIN * need - 0.45 + assert a <= -0.5 + # Trust falls with lateral offset and a weak read, continuously. + assert offset > in_path + 0.05 + assert weak > in_path + 0.05 + assert lead_trust(gap, v_ego, v_lead, 1.98, radar=True) < lead_trust(gap, v_ego, v_lead, 0.0, radar=True) + + +def test_far_lead_that_kinematically_needs_full_regen_still_gets_it(): + """Stopped car 100 m ahead at 30 m/s: the kinematics need full regen.""" + assert kinematic_need_accel(100.0, 30.0, 0.0, 0.0, 1.3) <= A_MIN_MS2 + 1e-6 + desired = unified_follow_desired(100.0, 30.0, 0.0, 0.0, 1.3, v_ceiling=31.0, + y_rel=1.5, model_prob=0.6, radar=True) + assert desired <= -3.3 + # 130 m at 30 m/s, lead stopped: need ~-3.9 -> still full regen. + assert unified_follow_desired(130.0, 30.0, 0.0, 0.0, 1.3, v_ceiling=31.0, radar=True) <= -3.3 + + +def test_close_rapid_closer_still_gets_full_fast_brake(): + """Consistent in-path close closer: trust 1, full regen within ~1.5 s.""" + v_ego, v_lead, gap = 25.0, 8.0, 32.0 + assert lead_trust(gap, v_ego, v_lead, 0.2, model_prob=0.9, radar=True) == 1.0 + ctrl = UnifiedLeadController() + cmds = [] + for _ in range(40): + cmds.append(ctrl.step(dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=1.3, lead_id=7, seed_a=0.0, v_ceiling=30.0, y_rel=0.2, + model_prob=0.9, radar=True)) + assert min(cmds) <= -3.4 + assert _first_at_or_below(cmds, -3.0) <= 1.6 + assert min(cmds) >= A_MIN_MS2 + # An inherited full-regen seed stays in force on a close closer. + held = UnifiedLeadController() + first = held.step(dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=1.3, lead_id=8, seed_a=-3.5, v_ceiling=30.0, radar=True, model_prob=0.9) + assert first <= -3.3 + + +def test_moderate_range_cut_in_still_responds(): + """Cut-in 35 m ahead closing 5 m/s: trust 1, firm within ~1.5 s.""" + v_ego = 27.0 + v_lead = 22.0 + assert lead_trust(35.0, v_ego, v_lead, 1.2, model_prob=0.8, radar=True) == 1.0 + ctrl = UnifiedLeadController() + for _ in range(20): + ctrl.step(dt=DT, present=True, gap=90.0, v_ego=v_ego, v_lead=v_ego, a_lead=0.0, t_follow=1.3, + lead_id=1, seed_a=0.0, v_ceiling=30.0, radar=True, model_prob=0.9) + cmds = [] + gap = 35.0 + for _ in range(40): + cmds.append(ctrl.step(dt=DT, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=1.3, lead_id=2, seed_a=0.0, v_ceiling=30.0, y_rel=1.2, + radar=True, model_prob=0.8)) + gap -= (v_ego - v_lead) * DT + assert _first_at_or_below(cmds, -1.0) is not None + assert _first_at_or_below(cmds, -1.0) <= 1.5 + assert min(cmds) <= -1.5 + + +def test_inherited_firm_seed_is_not_carried_into_a_remote_lead(): + """A legacy -3.5 in force when a far, slow-closing lead appears is released.""" + ctrl = UnifiedLeadController() + cmds = [] + for _ in range(30): + cmds.append(ctrl.step(dt=DT, present=True, gap=80.0, v_ego=18.1, v_lead=12.5, a_lead=-0.6, + t_follow=1.7, lead_id=("radar", -1), seed_a=-3.5, v_ceiling=19.0, + y_rel=0.8, model_prob=0.92, radar=False)) + assert cmds[0] >= -1.2 + assert min(cmds) >= -1.2 + + +def test_222_exemplars_are_fully_trusted_so_unchanged(): + """Every #222 exemplar row is close/short-TTC: the trust bound is identity.""" + for rows in (SEP20_0755_ROWS, SEP23_2214_ROWS, SEP22_2331_ROWS): + for d, v_lead, _, v_ego, _ in _interp_rows(rows): + assert lead_trust(d, v_ego, v_lead, 0.0, model_prob=0.9, radar=True) == 1.0 + + +def test_gap_set_override_none_matches_time_gap(): + """Unlocked follow is the time-gap law, including an explicit None.""" + v = 25.0 + tf = 1.3 + gap = gap_set_m(v, tf) + base = unified_follow_desired(gap, v, v, 0.0, tf, v_ceiling=40.0) + none = unified_follow_desired(gap, v, v, 0.0, tf, v_ceiling=40.0, gap_set_override_m=None) + same = unified_follow_desired(gap, v, v, 0.0, tf, v_ceiling=40.0, gap_set_override_m=gap) + assert none == base + assert same == pytest.approx(base, abs=1e-9) + kw = dict(gap=gap, v_ego=v, v_lead=v, a_lead=0.0, t_follow=tf, v_ceiling=40.0) + settled, _ = _settle(40, **kw) + settled_none, _ = _settle(40, gap_set_override_m=None, **kw) + settled_same, _ = _settle(40, gap_set_override_m=gap, **kw) + assert settled_none == settled + assert settled_same == pytest.approx(settled, abs=1e-9) + + +def test_gap_set_override_inside_is_a_soft_brake(): + """3 m inside the locked meters is more negative than matched, still above full regen.""" + v = 25.0 + tf = 1.3 + locked = 30.0 + at = unified_follow_desired(locked, v, v, 0.0, tf, v_ceiling=40.0, gap_set_override_m=locked) + inside = unified_follow_desired(locked - 3.0, v, v, 0.0, tf, v_ceiling=40.0, gap_set_override_m=locked) + assert inside < at + assert inside > -1.2 + assert abs(at) < 0.05 + + +def test_locked_speed_deficit_is_not_trickled_and_not_a_wall(): + """A just-latched gap with ego already slow must accelerate, under 1 m/s².""" + locked = 40.0 + tf = 2.2 + caught = unified_follow_desired( + locked, 28.5, 30.0, 0.0, tf, v_ceiling=40.0, gap_set_override_m=locked, + ) + eased = unified_follow_desired(locked, 28.5, 30.0, 0.0, tf, v_ceiling=40.0) + assert caught > 0.15 + assert caught < 1.0 + assert eased < -0.3 + + +def test_latch_tracks_locked_meters_instead_of_opening_then_creeping_back(): + """Hold previews the median, then the latch freezes it. + + Without that, a longer time gap has already eased ego slow and the + lock opens several meters before it creeps back. With the preview the + gap stays on the distance the hold started at. + """ + ctrl = UnifiedLeadController() + gap = 40.0 + v_ego = 30.0 + v_lead = 30.0 + tf = 2.2 + dt = DT + trail: list[float] = [] + locked = None + for _ in range(int(2.0 / dt)): + trail.append(gap) + window = trail[-8:] + preview = sorted(window)[len(window) // 2] + accel = ctrl.step( + dt=dt, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=tf, lead_id=("radar", 4), seed_a=0.0, v_ceiling=40.0, + gap_set_override_m=preview, + ) + v_ego = max(0.0, v_ego + accel * dt) + gap += (v_lead - v_ego) * dt + trail.append(gap) + window = trail[-8:] + locked = sorted(window)[len(window) // 2] + opened = 0.0 + for _ in range(int(8.0 / dt)): + accel = ctrl.step( + dt=dt, present=True, gap=gap, v_ego=v_ego, v_lead=v_lead, a_lead=0.0, + t_follow=tf, lead_id=("radar", 4), seed_a=0.0, v_ceiling=40.0, + gap_set_override_m=locked, + ) + v_ego = max(0.0, v_ego + accel * dt) + gap += (v_lead - v_ego) * dt + opened = max(opened, gap - locked) + assert abs(locked - 40.0) < 0.5 + assert opened < 1.0 + assert abs(gap - locked) < 0.5 + assert abs(v_lead - v_ego) < 0.3 + + +def test_gap_lock_may_go_above_max_to_hold_the_gap(): + """Locked meters win over MAX. Clearing the lock brings MAX back. + + A curve cap still brakes. Matching speed on the locked gap, already + above the cap, is a hold — not the mild MAX settle. + """ + v_cap = 25.0 + v_ego = v_cap + 1.5 + locked = 40.0 + held = unified_follow_desired( + locked, v_ego, v_ego, 0.0, 1.3, v_ceiling=v_cap, gap_set_override_m=locked, + ) + blocked = unified_follow_desired( + locked, v_ego, v_ego, 0.0, 1.3, v_ceiling=v_cap, + ) + assert held > -0.05 + assert blocked < -0.15 + assert held > blocked + 0.1 + # Lead is above MAX and the gap is still long: close, do not sit on the cap. + catching = unified_follow_desired( + locked + 6.0, v_cap, v_cap + 2.5, 0.0, 1.3, v_ceiling=v_cap, gap_set_override_m=locked, + ) + sitting = unified_follow_desired( + locked + 6.0, v_cap, v_cap + 2.5, 0.0, 1.3, v_ceiling=v_cap, + ) + assert 0.15 < catching < 1.6 + assert sitting <= 0.05 + curved = unified_follow_desired( + locked, v_ego, v_ego, 0.0, 1.3, v_ceiling=v_cap, v_curve_cap=v_ego - 4.0, + gap_set_override_m=locked, + ) + assert curved < -0.2 + + +def test_far_slack_lead_brake_is_not_copied_near_gap_still_is(): + """15:56: ~108 m, ~83 m slack, aLead ~−2.1 once closing past 0.4 m/s. + + That used to command about −1.05 from k_a·aLead. The close itself needs + almost nothing. The same lead brake near the gap, on a short time-to-gap, + or at emergency decel still comes through. + """ + v_lead = 27.9 + v_ego = v_lead + 2.2 + gap = 108.1 + tf = 0.70 + far = unified_follow_desired(gap, v_ego, v_lead, -2.1, tf, v_ceiling=31.3, radar=True) + assert far > -0.35 + near_gap = gap_set_m(v_lead, tf) + 4.0 + near = unified_follow_desired(near_gap, v_ego, v_lead, -2.1, tf, v_ceiling=40.0, radar=True) + assert near < -1.0 + # Short time-to-gap from far out: the lead brake is copied again. + fast = unified_follow_desired(gap, v_lead + 12.0, v_lead, -2.0, tf, v_ceiling=40.0, radar=True) + assert fast < -0.8 + panic = unified_follow_desired(gap, v_ego, v_lead, -3.5, tf, v_ceiling=40.0, radar=True) + assert panic < -1.0 + # Same rapid decel off the predicted path does not firm ego. In a bend, + # path lateral is what counts, not raw yRel. A close lead is not this gate. + off = unified_follow_desired( + gap, v_ego, v_lead, -3.5, tf, v_ceiling=40.0, radar=True, y_rel=2.6, + ) + ghost = unified_follow_desired( + gap, v_ego, v_lead, -3.5, tf, v_ceiling=40.0, radar=True, y_rel=0.0, path_lat=2.5, + ) + in_bend = unified_follow_desired( + gap, v_ego, v_lead, -3.5, tf, v_ceiling=40.0, radar=True, y_rel=3.2, path_lat=0.3, + ) + assert off > -0.45 + assert ghost > -0.45 + assert in_bend < -1.0 + close = unified_follow_desired( + 22.0, 20.0, 16.0, -2.5, 0.9, v_ceiling=30.0, radar=True, y_rel=1.9, + ) + assert close < -1.0 + + +def test_far_off_path_rapid_lead_does_not_firm_and_a_one_frame_spike_does_not_drop(): + """A lateral ghost at a far gap never firms. One bad yRel frame does not + release a lead that has been on the path.""" + ctrl = UnifiedLeadController() + ghost = [] + for _ in range(40): + ghost.append(ctrl.step( + dt=DT, present=True, gap=108.1, v_ego=30.1, v_lead=27.9, a_lead=-3.5, + t_follow=0.7, lead_id=9, seed_a=0.0, v_ceiling=40.0, radar=True, + y_rel=2.8, path_lat=2.8, + )) + assert min(ghost) > -0.5 + + held = UnifiedLeadController() + kw = dict( + dt=DT, present=True, gap=108.1, v_ego=30.1, v_lead=27.9, a_lead=-3.5, + t_follow=0.7, lead_id=4, seed_a=0.0, v_ceiling=40.0, radar=True, y_rel=0.2, + ) + last = 0.0 + for _ in range(40): + last = held.step(**kw) + assert last < -0.8 + spiked = held.step(**{**kw, "y_rel": 3.4}) + assert spiked < last + 0.4 + released = spiked + for _ in range(40): + released = held.step(**{**kw, "y_rel": 2.8, "path_lat": 2.8}) + assert released > -0.5 diff --git a/selfdrive/controls/tests/test_unified_lead_planner.py b/selfdrive/controls/tests/test_unified_lead_planner.py new file mode 100644 index 00000000000000..24605d9ece14a6 --- /dev/null +++ b/selfdrive/controls/tests/test_unified_lead_planner.py @@ -0,0 +1,457 @@ +"""Planner integration for the unified lead-follow controller (the sole path). + +On Pre-AP, a live or held lead hands the published accel to the continuous +controller. Without a lead the lead-free command (MPC, map, curve, roundabout) +stays in force. A compute exception is logged once, latches the controller off +for the rest of the process, and the lead-free command (which still brakes for +the lead) is published. Other cars never run it. +""" +import math +import time + +import numpy as np +import pytest + +from cereal import car, log, messaging +from opendbc.car.tesla.preap.constants import PEDAL_LONG_K_BP, PEDAL_LONG_KI_V, PEDAL_LONG_KP_V +from openpilot.common.constants import CV +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState +from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import LongitudinalPlanSource, T_IDXS +from openpilot.selfdrive.controls.lib.longitudinal_planner import SEED_BRAKE_STEP_MS2, CycleTimeLog, LongitudinalPlanner +from openpilot.selfdrive.modeld.constants import ModelConstants + + +class _PlannerInputs(dict): + logMonoTime = {"modelV2": 0} + + @staticmethod + def all_checks(service_list): + return set(service_list) == {"carState", "controlsState", "selfdriveState", "radarState"} + + +class _CapturingPubMaster: + def send(self, service, message): + assert service == "longitudinalPlan" + self.message = message + + +class _MutablePlannerParams: + """Same unknown-key behavior as the following-suite double. + + An unknown key raises, so the planner may only read keys it knows. + """ + + def __init__(self, nap_follow_dist, adaptive_accel=False, map_speed_accel=5): + self.nap_follow_dist = nap_follow_dist + self.adaptive_accel = adaptive_accel + self.map_speed_accel = map_speed_accel + self.city = nap_follow_dist + self.hwy = nap_follow_dist + self.migrated = True + self.curve_follow = 1 + self.sight_cap = 1 + + def __bool__(self): + return False + + def get(self, key, return_default=False): + assert return_default + if key == "NAPFollowDistance": + return self.nap_follow_dist + if key == "NAPFollowDistanceCity": + return self.city + if key == "NAPFollowDistanceHwy": + return self.hwy + if key == "NAPMapSpeedAccel": + return self.map_speed_accel + if key == "NAPMapSpeedMode": + return 0 + if key == "NAPMapSpeedOffsetMph": + return 0 + if key == "NAPMapSpeedLookahead": + return 2 + if key == "NAPCurveFollow": + return self.curve_follow + if key == "NAPSightCap": + return self.sight_cap + raise AssertionError(key) + + def get_bool(self, key): + if key == "NAPAdaptiveAccel": + return self.adaptive_accel + if key == "NAPHypermile": + return False + if key == "NAPHypermileHillClimb": + return True + if key == "NAPFollowDistanceSplitMigrated": + return self.migrated + raise AssertionError(key) + + def put_bool(self, key, value): + if key == "NAPFollowDistanceSplitMigrated": + self.migrated = bool(value) + elif key == "NAPAdaptiveAccel": + self.adaptive_accel = bool(value) + + +class _ConstantAccelerationMpc: + def __init__(self, speed_mps, acceleration_mps2): + self.v_solution = speed_mps + acceleration_mps2 * T_IDXS + self.a_solution = np.full(len(T_IDXS), acceleration_mps2) + self.j_solution = np.zeros(len(T_IDXS) - 1) + self.params = np.zeros((len(T_IDXS), 6)) + self.source = LongitudinalPlanSource.cruise + self.crash_cnt = 0 + self.solve_time = 0.0 + + @staticmethod + def set_weights(prev_accel_constraint, personality): + pass + + @staticmethod + def set_cur_state(speed_mps, acceleration_mps2): + pass + + def update(self, radar_state, cruise_speed_mps, t_follow): + self.params[:, 4] = t_follow + + +def _make_preap_params(): + params = car.CarParams.new_message() + params.brand = "tesla" + params.carFingerprint = "TESLA_MODEL_S_PREAP" + params.openpilotLongitudinalControl = True + params.pcmCruise = False + params.steerRatio = 15.75 + params.wheelbase = 2.959 + params.longitudinalTuning.kpBP = PEDAL_LONG_K_BP + params.longitudinalTuning.kpV = PEDAL_LONG_KP_V + params.longitudinalTuning.kiBP = PEDAL_LONG_K_BP + params.longitudinalTuning.kiV = PEDAL_LONG_KI_V + params.longitudinalTuning.kf = 1.0 + params.vEgoStarting = 0.1 + return params + + +def _set_v_cruise_ms(inputs, v_cruise_ms): + inputs["carState"].vCruise = float(v_cruise_ms) * CV.MS_TO_KPH + + +def _make_planner_inputs(speed_mps): + radar = messaging.new_message("radarState").radarState + controls = messaging.new_message("controlsState").controlsState + selfdrive = messaging.new_message("selfdriveState").selfdriveState + car_state = messaging.new_message("carState").carState + car_control = messaging.new_message("carControl").carControl + live_parameters = messaging.new_message("liveParameters").liveParameters + model = messaging.new_message("modelV2").modelV2 + + controls.longControlState = LongCtrlState.pid + selfdrive.personality = log.LongitudinalPersonality.standard + car_state.vEgo = speed_mps + car_state.vCruise = speed_mps * 3.6 + car_control.orientationNED = [0.0, 0.0, 0.0] + + model.position.x = (speed_mps * np.array(ModelConstants.T_IDXS)).tolist() + model.velocity.x = (speed_mps * np.ones_like(ModelConstants.T_IDXS)).tolist() + model.acceleration.x = np.zeros_like(ModelConstants.T_IDXS).tolist() + model.meta.disengagePredictions.gasPressProbs = [1.0] * 6 + + return _PlannerInputs({ + "radarState": radar, + "controlsState": controls, + "selfdriveState": selfdrive, + "carState": car_state, + "carControl": car_control, + "liveParameters": live_parameters, + "modelV2": model, + }) + + +def _planner(v_ego, *, nap_follow_dist=2, accel=-3.5): + params = _MutablePlannerParams(nap_follow_dist=nap_follow_dist) + planner = LongitudinalPlanner(_make_preap_params(), init_v=v_ego, params=params) + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=accel) + planner.prev_accel_clip = [-3.5, 2.0] + inputs = _make_planner_inputs(v_ego) + _set_v_cruise_ms(inputs, max(v_ego + 8.0, 40.0)) + return planner, inputs, params + + +def _own_lead(inputs, d_rel, v_lead, a_lead=0.0, y_rel=0.0, track=1): + lead = inputs["radarState"].leadOne + lead.status = True + lead.dRel = float(d_rel) + lead.vLead = float(v_lead) + lead.aLeadK = float(a_lead) + lead.yRel = float(y_rel) + lead.modelProb = 1.0 + lead.radar = True + lead.radarTrackId = int(track) + return lead + + +def _run(planner, inputs, n, mpc_accel=None): + if mpc_accel is not None: + crash = float(getattr(planner.mpc, "crash_cnt", 0) or 0) + planner.mpc = _ConstantAccelerationMpc(inputs["carState"].vEgo, acceleration_mps2=mpc_accel) + planner.mpc.crash_cnt = crash + for _ in range(n): + planner.update(inputs) + return float(planner.output_a_target) + + +def _guarded_updates(planner, inputs, n): + """Turn a propagating shadow exception into an assertion failure. + + The mutation gate only counts AssertionError as a killed mutant. If the + planner guard is removed, update() must fail these tests that way. + """ + escaped = [] + for _ in range(n): + try: + planner.update(inputs) + except Exception as exc: + escaped.append(f"{type(exc).__name__}: {exc}") + return escaped + + +def _spy_cloudlog_exception(monkeypatch): + calls = [] + + def _record(*args, **kwargs): + calls.append(args) + + monkeypatch.setattr(cloudlog, "exception", _record) + return calls + + +def _capture_lead_free(monkeypatch, planner): + """Lead-free command for each frame, before the lead-follow step runs.""" + captured = [] + original = planner._apply_lead_follow + + def _wrap(sm, v_ego): + captured.append(float(planner.output_a_target)) + return original(sm, v_ego) + + monkeypatch.setattr(planner, "_apply_lead_follow", _wrap) + return captured + + +def test_sole_path_follows_the_continuous_command_for_sep23(): + """23:31 geometry: firm match to a braking lead, not the raw MPC -3.5.""" + v_ego = 30.0 + planner, inputs, _ = _planner(v_ego, accel=-3.5) + _own_lead(inputs, 35.0, v_ego - 1.13, a_lead=-1.18) + _run(planner, inputs, 80) + assert float(planner.output_a_target) == pytest.approx(float(planner.unified_a_target), abs=1e-6) + assert -2.2 < float(planner.output_a_target) <= -0.90 + publisher = _CapturingPubMaster() + planner.publish(inputs, publisher) + assert publisher.message.longitudinalPlan.unifiedATarget == pytest.approx(planner.unified_a_target) + + +def test_first_far_closing_lead_is_never_rematched_with_plus_a(): + """The lead-free command knows nothing of a new lead: cruise +a must not pass through.""" + v_ego = 25.0 + planner, inputs, _ = _planner(v_ego, nap_follow_dist=4, accel=1.5) + _own_lead(inputs, 160.0, v_ego - 1.6, a_lead=0.0) + planner.update(inputs) + assert planner._unified_following is True + assert float(planner.output_a_target) <= 0.05 + assert _run(planner, inputs, 15, mpc_accel=1.5) <= 0.05 + + # A far same-speed lead (the law wants +a): the cruise +1.5 is bounded by what + # the law itself asks (about +0.8 here), never passed through. + same, same_in, _ = _planner(v_ego, nap_follow_dist=4, accel=1.5) + _own_lead(same_in, 160.0, v_ego, a_lead=0.0) + same.update(same_in) + assert 0.0 < float(same.output_a_target) <= 0.9 + + +def test_first_hard_close_frame_starts_firmer_than_the_lead_free_command(): + """07:55 Sep 20 class: the law asks for far more brake than the lead-free command. + + The new lead starts up to SEED_BRAKE_STEP_MS2 firmer than that command + (not waiting on the jerk-limited build-up) and never passes the law's own ask. + """ + v_ego = 18.5 + planner, inputs, _ = _planner(v_ego, accel=-0.5) + _own_lead(inputs, 25.0, v_ego - 4.44, a_lead=-1.04) + planner.update(inputs) + first = float(planner.output_a_target) + assert first <= -0.5 - 0.5 * SEED_BRAKE_STEP_MS2 + assert first >= -0.5 - SEED_BRAKE_STEP_MS2 - 0.8 + assert _run(planner, inputs, 40, mpc_accel=-0.5) <= -2.0 + + +def test_no_lead_keeps_the_lead_free_command(monkeypatch): + v_ego = 20.0 + planner, inputs, _ = _planner(v_ego, accel=0.40) + captured = _capture_lead_free(monkeypatch, planner) + _run(planner, inputs, 10) + assert inputs["radarState"].leadOne.status is False + assert float(planner.output_a_target) == pytest.approx(captured[-1], abs=1e-9) + assert float(planner.output_a_target) > 0.1 + assert float(planner.unified_a_target) == pytest.approx(0.0, abs=1e-9) + assert planner._unified_following is False + + +def test_faster_lead_at_max_does_not_overrun(): + v_max = 60.0 * CV.MPH_TO_MS + v_lead = v_max + 3.0 * CV.MPH_TO_MS + planner, inputs, _ = _planner(v_max, nap_follow_dist=4, accel=1.2) + _set_v_cruise_ms(inputs, v_max) + _own_lead(inputs, 80.0, v_lead, a_lead=0.2) + _run(planner, inputs, 30, mpc_accel=1.2) + assert float(planner.output_a_target) <= 0.05 + + +def test_fcw_is_not_weaker_than_the_lead_free_command(monkeypatch): + v_ego = 30.0 + planner, inputs, _ = _planner(v_ego, accel=-3.5) + captured = _capture_lead_free(monkeypatch, planner) + _own_lead(inputs, 35.0, v_ego - 1.13, a_lead=-1.18) + planner.mpc.crash_cnt = 3 + _run(planner, inputs, 8, mpc_accel=-3.5) + assert planner.fcw is True + assert float(planner.output_a_target) <= captured[-1] + 1e-6 + + +def test_curve_ceiling_brakes_with_a_lead_present(): + v_ego = 25.0 + curve, inputs, _ = _planner(v_ego, accel=0.0) + straight, straight_inputs, _ = _planner(v_ego, accel=0.0) + _own_lead(inputs, 50.0, v_ego + 1.0, a_lead=0.0) + _own_lead(straight_inputs, 50.0, v_ego + 1.0, a_lead=0.0) + inputs["carState"].steeringAngleDeg = 15.0 + # The curve ceiling reads true cornering (vehicle-model curvature). + inputs["controlsState"].curvature = 15.0 * math.pi / 180.0 / (15.75 * 2.959) + _run(curve, inputs, 40, mpc_accel=0.0) + _run(straight, straight_inputs, 40, mpc_accel=0.0) + assert float(curve.output_a_target) <= -0.50 + assert float(straight.output_a_target) > float(curve.output_a_target) + + +@pytest.mark.parametrize("brand,fingerprint,openpilot_long,pcm_cruise", [ + ("tesla", "TESLA_MODEL_3", True, False), # other Tesla + ("tesla", "TESLA_MODEL_S_PREAP", False, False), # Pre-AP without openpilot long + ("tesla", "TESLA_MODEL_S_PREAP", True, True), # Pre-AP on stock cruise + ("toyota", "TOYOTA_COROLLA_TSS2", True, False), +]) +def test_other_cars_never_run_the_unified_controller(brand, fingerprint, openpilot_long, pcm_cruise): + v_ego = 30.0 + cp = _make_preap_params() + cp.brand = brand + cp.carFingerprint = fingerprint + cp.openpilotLongitudinalControl = openpilot_long + cp.pcmCruise = pcm_cruise + planner = LongitudinalPlanner(cp, init_v=v_ego, params=_MutablePlannerParams(nap_follow_dist=2)) + planner.mpc = _ConstantAccelerationMpc(v_ego, acceleration_mps2=-1.0) + inputs = _make_planner_inputs(v_ego) + _set_v_cruise_ms(inputs, 40.0) + _own_lead(inputs, 35.0, v_ego - 1.13, a_lead=-1.18) + for _ in range(40): + planner.update(inputs) + assert planner._is_preap is False + assert planner._unified_following is False + assert float(planner.unified_a_target) == 0.0 + publisher = _CapturingPubMaster() + planner.publish(inputs, publisher) + assert publisher.message.longitudinalPlan.unifiedATarget == 0.0 + + +def test_unified_fault_latches_and_publishes_the_lead_free_command(monkeypatch): + """An exception must not escape update() or be logged more than once. + + The mutation gate only counts AssertionError as a killed mutant, so a + propagating exception is turned into an assertion failure here. + """ + v_ego = 30.0 + planner, inputs, _ = _planner(v_ego, accel=-3.5) + _own_lead(inputs, 35.0, v_ego - 1.13, a_lead=-1.18) + logs = _spy_cloudlog_exception(monkeypatch) + _run(planner, inputs, 80) + assert planner._unified_faulted is False + assert float(planner.unified_a_target) <= -0.5 + assert logs == [] + + captured = _capture_lead_free(monkeypatch, planner) + step_calls = {"n": 0} + + def _boom(*_args, **_kwargs): + step_calls["n"] += 1 + raise RuntimeError("unified compute failed") + + monkeypatch.setattr(planner._unified, "step", _boom) + escaped = _guarded_updates(planner, inputs, 1) + assert escaped == [], escaped + assert planner._unified_faulted is True + assert planner._unified_fault_count == 1 + assert planner._unified_following is False + assert planner.unified_a_target == 0.0 + assert planner.output_a_target == pytest.approx(captured[-1], abs=1e-9) + assert len(logs) == 1 + assert logs[0][1] == 1 + + escaped = _guarded_updates(planner, inputs, 19) + assert escaped == [], escaped + assert planner.output_a_target == pytest.approx(captured[-1], abs=1e-9) + assert planner._unified_fault_count == 1 + assert step_calls["n"] == 1 + assert len(logs) == 1 + + publisher = _CapturingPubMaster() + planner.publish(inputs, publisher) + assert publisher.message.longitudinalPlan.aTarget == pytest.approx(planner.output_a_target, abs=1e-9) + assert publisher.message.longitudinalPlan.unifiedATarget == 0.0 + + sentinel_calls = {"n": 0} + + def _sentinel(*_args, **_kwargs): + sentinel_calls["n"] += 1 + return 4.0 + + monkeypatch.setattr(planner._unified, "step", _sentinel) + escaped = _guarded_updates(planner, inputs, 5) + assert escaped == [], escaped + assert sentinel_calls["n"] == 0 + assert planner._unified_faulted is True + assert planner.output_a_target == pytest.approx(captured[-1], abs=1e-9) + assert planner.output_a_target != pytest.approx(4.0, abs=0.5) + + inputs["controlsState"].longControlState = LongCtrlState.off + assert _guarded_updates(planner, inputs, 1) == [] + inputs["controlsState"].longControlState = LongCtrlState.pid + assert _guarded_updates(planner, inputs, 3) == [] + assert planner._unified_faulted is True + assert sentinel_calls["n"] == 0 + assert len(logs) == 1 + + +def test_cycle_time_log_reports_mean_and_max_per_window(): + log_ = CycleTimeLog(every_n=4) + assert [log_.record(t) for t in (0.001, 0.002, 0.003)] == [None, None, None] + window = log_.record(0.010) + assert window is not None + n, mean_ms, max_ms = window + assert n == 4 + assert mean_ms == pytest.approx(4.0) + assert max_ms == pytest.approx(10.0) + assert log_.record(0.001) is None + assert log_.n == 1 + + +def test_planner_update_cycle_stays_cheap_with_a_lead(): + """Guard rail only (stub MPC): the lead-follow step must stay well under a model frame.""" + v_ego = 25.0 + planner, inputs, _ = _planner(v_ego, accel=0.0) + _own_lead(inputs, 45.0, v_ego - 0.5, a_lead=-0.3) + _run(planner, inputs, 20) + frames = 400 + t0 = time.perf_counter() + _run(planner, inputs, frames) + mean_ms = 1000.0 * (time.perf_counter() - t0) / frames + assert mean_ms < 5.0 diff --git a/selfdrive/debug/adb.sh b/selfdrive/debug/adb.sh deleted file mode 100755 index 8fa267fd4d0d41..00000000000000 --- a/selfdrive/debug/adb.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env bash -set -e - -PORT=5555 - -setprop service.adb.tcp.port $PORT -sudo systemctl start adbd - -IP=$(echo $SSH_CONNECTION | awk '{ print $3}') -echo "then, connect on your computer:" -echo "adb connect $IP:$PORT" diff --git a/selfdrive/debug/analyze-msg-size.py b/selfdrive/debug/analyze-msg-size.py new file mode 100755 index 00000000000000..69015a6be2b96e --- /dev/null +++ b/selfdrive/debug/analyze-msg-size.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +import argparse +from tqdm import tqdm + +from cereal.services import SERVICE_LIST, QueueSize +from openpilot.tools.lib.logreader import LogReader + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Analyze message sizes from a log route") + parser.add_argument("route", nargs="?", default="98395b7c5b27882e/000000a8--f87e7cd255", + help="Log route to analyze (default: 98395b7c5b27882e/000000a8--f87e7cd255)") + args = parser.parse_args() + + lr = LogReader(args.route) + + szs = {} + for msg in tqdm(lr): + sz = len(msg.as_builder().to_bytes()) + msg_type = msg.which() + if msg_type not in szs: + szs[msg_type] = {'min': sz, 'max': sz, 'sum': sz, 'count': 1} + else: + szs[msg_type]['min'] = min(szs[msg_type]['min'], sz) + szs[msg_type]['max'] = max(szs[msg_type]['max'], sz) + szs[msg_type]['sum'] += sz + szs[msg_type]['count'] += 1 + + print() + print(f"{'Service':<36} {'Min (KB)':>12} {'Max (KB)':>12} {'Avg (KB)':>12} {'KB/min':>12} {'KB/sec':>12} {'Minutes in 10MB':>18} {'Seconds in Queue':>18}") + print("-" * 132) + def sort_key(x): + k, v = x + avg = v['sum'] / v['count'] + freq = SERVICE_LIST.get(k, None) + freq_val = freq.frequency if freq else 0.0 + kb_per_min = (avg * freq_val * 60) / 1024 if freq_val > 0 else 0.0 + return kb_per_min + total_kb_per_min = 0.0 + RINGBUFFER_SIZE_KB = 10 * 1024 # 10MB old default + for k, v in sorted(szs.items(), key=sort_key, reverse=True): + avg = v['sum'] / v['count'] + service = SERVICE_LIST.get(k, None) + freq_val = service.frequency if service else 0.0 + queue_size_kb = (service.queue_size / 1024) if service else 250 # default to SMALL + kb_per_min = (avg * freq_val * 60) / 1024 if freq_val > 0 else 0.0 + kb_per_sec = kb_per_min / 60 + minutes_in_buffer = RINGBUFFER_SIZE_KB / kb_per_min if kb_per_min > 0 else float('inf') + seconds_in_queue = (queue_size_kb / kb_per_sec) if kb_per_sec > 0 else float('inf') + total_kb_per_min += kb_per_min + min_str = f"{minutes_in_buffer:.2f}" if minutes_in_buffer != float('inf') else "inf" + sec_queue_str = f"{seconds_in_queue:.2f}" if seconds_in_queue != float('inf') else "inf" + print(f"{k:<36} {v['min']/1024:>12.2f} {v['max']/1024:>12.2f} {avg/1024:>12.2f} {kb_per_min:>12.2f} {kb_per_sec:>12.2f} {min_str:>18} {sec_queue_str:>18}") + + # Summary section + print() + print(f"Total usage: {total_kb_per_min / 1024:.2f} MB/min") + + # Calculate memory usage: old (10MB for all) vs new (from services.py) + OLD_SIZE = 10 * 1024 * 1024 # 10MB was the old default + old_total = len(SERVICE_LIST) * OLD_SIZE + + new_total = sum(s.queue_size for s in SERVICE_LIST.values()) + + # Count by queue size + size_counts = {QueueSize.BIG: 0, QueueSize.MEDIUM: 0, QueueSize.SMALL: 0} + for s in SERVICE_LIST.values(): + size_counts[s.queue_size] += 1 + + savings_pct = (1 - new_total / old_total) * 100 + + print() + print(f"{'Queue Size Comparison':<40}") + print("-" * 60) + print(f"{'Old (10MB default):':<30} {old_total / 1024 / 1024:>10.2f} MB") + print(f"{'New (from services.py):':<30} {new_total / 1024 / 1024:>10.2f} MB") + print(f"{'Savings:':<30} {savings_pct:>10.1f}%") + print() + print(f"{'Breakdown:':<30}") + print(f" BIG (10MB): {size_counts[QueueSize.BIG]:>3} services") + print(f" MEDIUM (2MB): {size_counts[QueueSize.MEDIUM]:>3} services") + print(f" SMALL (250KB): {size_counts[QueueSize.SMALL]:>3} services") diff --git a/selfdrive/debug/can_printer.py b/selfdrive/debug/can_printer.py index b93e48ba73ee11..f2ed6730d37a30 100755 --- a/selfdrive/debug/can_printer.py +++ b/selfdrive/debug/can_printer.py @@ -28,7 +28,7 @@ def can_printer(bus, max_msg, addr, ascii_decode): x = binascii.hexlify(msgs[_addr][-1]).decode('ascii') freq = len(msgs[_addr]) / (time.monotonic() - start) if max_msg is None or _addr < max_msg: - dd += "%04X(%4d)(%6d)(%3dHz) %s %s\n" % (_addr, _addr, len(msgs[_addr]), freq, x.ljust(20), a) + dd += f"{_addr:04X}({_addr:4d})({len(msgs[_addr]):6d})({freq:3}dHz) {x.ljust(20)} {a}\n" print(dd) lp = time.monotonic() diff --git a/selfdrive/debug/clear_dtc.py b/selfdrive/debug/car/clear_dtc.py similarity index 79% rename from selfdrive/debug/clear_dtc.py rename to selfdrive/debug/car/clear_dtc.py index a931c423a945e3..b2c5fe3db51f45 100755 --- a/selfdrive/debug/clear_dtc.py +++ b/selfdrive/debug/car/clear_dtc.py @@ -2,8 +2,10 @@ import sys import argparse from subprocess import check_output, CalledProcessError +from opendbc.car.carlog import carlog +from opendbc.car.uds import UdsClient, MessageTimeoutError, SESSION_TYPE, DTC_GROUP_TYPE +from opendbc.car.structs import CarParams from panda import Panda -from panda.python.uds import UdsClient, MessageTimeoutError, SESSION_TYPE, DTC_GROUP_TYPE parser = argparse.ArgumentParser(description="clear DTC status") parser.add_argument("addr", type=lambda x: int(x,0), nargs="?", default=0x7DF) # default is functional (broadcast) address @@ -11,6 +13,9 @@ parser.add_argument('--debug', action='store_true') args = parser.parse_args() +if args.debug: + carlog.setLevel('DEBUG') + try: check_output(["pidof", "pandad"]) print("pandad is running, please kill openpilot before running this script! (aborted)") @@ -20,8 +25,8 @@ raise e panda = Panda() -panda.set_safety_mode(Panda.SAFETY_ELM327) -uds_client = UdsClient(panda, args.addr, bus=args.bus, debug=args.debug) +panda.set_safety_mode(CarParams.SafetyModel.elm327) +uds_client = UdsClient(panda, args.addr, bus=args.bus) print("extended diagnostic session ...") try: uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) diff --git a/selfdrive/debug/car/disable_ecu.py b/selfdrive/debug/car/disable_ecu.py index 185139324d610f..14d0cbb9cf3c95 100755 --- a/selfdrive/debug/car/disable_ecu.py +++ b/selfdrive/debug/car/disable_ecu.py @@ -11,5 +11,5 @@ time.sleep(1) # honda bosch radar disable - disabled = disable_ecu(*can_callbacks, bus=1, addr=0x18DAB0F1, com_cont_req=b'\x28\x83\x03', timeout=0.5, debug=False) + disabled = disable_ecu(*can_callbacks, bus=1, addr=0x18DAB0F1, com_cont_req=b'\x28\x83\x03', timeout=0.5) print(f"disabled: {disabled}") diff --git a/selfdrive/debug/car/ecu_addrs.py b/selfdrive/debug/car/ecu_addrs.py index 58781222dc4be8..f3f06406c076cf 100755 --- a/selfdrive/debug/car/ecu_addrs.py +++ b/selfdrive/debug/car/ecu_addrs.py @@ -2,6 +2,7 @@ import argparse import time import cereal.messaging as messaging +from opendbc.car.carlog import carlog from opendbc.car.ecu_addrs import get_all_ecu_addrs from openpilot.common.params import Params from openpilot.selfdrive.car.card import can_comm_callbacks, obd_callback @@ -15,6 +16,9 @@ parser.add_argument('--timeout', type=float, default=1.0) args = parser.parse_args() + if args.debug: + carlog.setLevel('DEBUG') + logcan = messaging.sub_sock('can') sendcan = messaging.pub_sock('sendcan') can_callbacks = can_comm_callbacks(logcan, sendcan) @@ -22,14 +26,14 @@ # Set up params for pandad params = Params() params.remove("FirmwareQueryDone") - params.put_bool("IsOnroad", False) + params.put_bool("IsOnroad", False, block=True) time.sleep(0.2) # thread is 10 Hz - params.put_bool("IsOnroad", True) + params.put_bool("IsOnroad", True, block=True) obd_callback(params)(not args.no_obd) print("Getting ECU addresses ...") - ecu_addrs = get_all_ecu_addrs(*can_callbacks, args.bus, args.timeout, debug=args.debug) + ecu_addrs = get_all_ecu_addrs(*can_callbacks, args.bus, args.timeout) print() print("Found ECUs on rx addresses:") diff --git a/selfdrive/debug/car/fw_versions.py b/selfdrive/debug/car/fw_versions.py index 18a287b38e09ed..b04f9cd2a68af1 100755 --- a/selfdrive/debug/car/fw_versions.py +++ b/selfdrive/debug/car/fw_versions.py @@ -3,6 +3,7 @@ import argparse import cereal.messaging as messaging from cereal import car +from opendbc.car.carlog import carlog from opendbc.car.fw_versions import get_fw_versions, match_fw_to_car from opendbc.car.vin import get_vin from openpilot.common.params import Params @@ -18,6 +19,9 @@ parser.add_argument('--brand', help='Only query addresses/with requests for this brand') args = parser.parse_args() + if args.debug: + carlog.setLevel('DEBUG') + logcan = messaging.sub_sock('can') pandaStates_sock = messaging.sub_sock('pandaStates') sendcan = messaging.pub_sock('sendcan') @@ -26,9 +30,9 @@ # Set up params for pandad params = Params() params.remove("FirmwareQueryDone") - params.put_bool("IsOnroad", False) + params.put_bool("IsOnroad", False, block=True) time.sleep(0.2) # thread is 10 Hz - params.put_bool("IsOnroad", True) + params.put_bool("IsOnroad", True, block=True) set_obd_multiplexing = obd_callback(params) extra: Any = None @@ -41,18 +45,16 @@ extra[(Ecu.unknown, 0x750, i)] = [] extra = {"any": {"debug": extra}} - num_pandas = len(messaging.recv_one_retry(pandaStates_sock).pandaStates) - - t = time.time() + t = time.monotonic() print("Getting vin...") set_obd_multiplexing(True) - vin_rx_addr, vin_rx_bus, vin = get_vin(*can_callbacks, (0, 1), debug=args.debug) + vin_rx_addr, vin_rx_bus, vin = get_vin(*can_callbacks, (0, 1)) print(f'RX: {hex(vin_rx_addr)}, BUS: {vin_rx_bus}, VIN: {vin}') - print(f"Getting VIN took {time.time() - t:.3f} s") + print(f"Getting VIN took {time.monotonic() - t:.3f} s") print() - t = time.time() - fw_vers = get_fw_versions(*can_callbacks, set_obd_multiplexing, query_brand=args.brand, extra=extra, num_pandas=num_pandas, debug=args.debug, progress=True) + t = time.monotonic() + fw_vers = get_fw_versions(*can_callbacks, set_obd_multiplexing, query_brand=args.brand, extra=extra, progress=True) _, candidates = match_fw_to_car(fw_vers, vin) print() @@ -67,4 +69,4 @@ print() print("Possible matches:", candidates) - print(f"Getting fw took {time.time() - t:.3f} s") + print(f"Getting fw took {time.monotonic() - t:.3f} s") diff --git a/selfdrive/debug/hyundai_enable_radar_points.py b/selfdrive/debug/car/hyundai_enable_radar_points.py similarity index 92% rename from selfdrive/debug/hyundai_enable_radar_points.py rename to selfdrive/debug/car/hyundai_enable_radar_points.py index 5e7080ef64c81f..df150a5224d986 100755 --- a/selfdrive/debug/hyundai_enable_radar_points.py +++ b/selfdrive/debug/car/hyundai_enable_radar_points.py @@ -16,8 +16,10 @@ from typing import NamedTuple from subprocess import check_output, CalledProcessError +from opendbc.car.carlog import carlog +from opendbc.car.uds import UdsClient, SESSION_TYPE, DATA_IDENTIFIER_TYPE +from opendbc.car.structs import CarParams from panda.python import Panda -from panda.python.uds import UdsClient, SESSION_TYPE, DATA_IDENTIFIER_TYPE class ConfigValues(NamedTuple): default_config: bytes @@ -78,6 +80,9 @@ class ConfigValues(NamedTuple): parser.add_argument('--bus', type=int, default=0, help='can bus to use (default: 0)') args = parser.parse_args() + if args.debug: + carlog.setLevel('DEBUG') + try: check_output(["pidof", "pandad"]) print("pandad is running, please kill openpilot before running this script! (aborted)") @@ -92,15 +97,15 @@ class ConfigValues(NamedTuple): sys.exit(0) panda = Panda() - panda.set_safety_mode(Panda.SAFETY_ELM327) - uds_client = UdsClient(panda, 0x7D0, bus=args.bus, debug=args.debug) + panda.set_safety_mode(CarParams.SafetyModel.elm327) + uds_client = UdsClient(panda, 0x7D0, bus=args.bus) print("\n[START DIAGNOSTIC SESSION]") - session_type : SESSION_TYPE = 0x07 # type: ignore + session_type : SESSION_TYPE = 0x07 uds_client.diagnostic_session_control(session_type) print("[HARDWARE/SOFTWARE VERSION]") - fw_version_data_id : DATA_IDENTIFIER_TYPE = 0xf100 # type: ignore + fw_version_data_id : DATA_IDENTIFIER_TYPE = 0xf100 fw_version = uds_client.read_data_by_identifier(fw_version_data_id) print(fw_version) if fw_version not in SUPPORTED_FW_VERSIONS.keys(): @@ -108,7 +113,7 @@ class ConfigValues(NamedTuple): sys.exit(1) print("[GET CONFIGURATION]") - config_data_id : DATA_IDENTIFIER_TYPE = 0x0142 # type: ignore + config_data_id : DATA_IDENTIFIER_TYPE = 0x0142 current_config = uds_client.read_data_by_identifier(config_data_id) config_values = SUPPORTED_FW_VERSIONS[fw_version] new_config = config_values.default_config if args.default else config_values.tracks_enabled diff --git a/selfdrive/debug/toyota_eps_factor.py b/selfdrive/debug/car/toyota_eps_factor.py similarity index 100% rename from selfdrive/debug/toyota_eps_factor.py rename to selfdrive/debug/car/toyota_eps_factor.py diff --git a/selfdrive/debug/car/vin.py b/selfdrive/debug/car/vin.py index 7946b429e45af6..9b1d6528ccb3d1 100755 --- a/selfdrive/debug/car/vin.py +++ b/selfdrive/debug/car/vin.py @@ -2,6 +2,7 @@ import argparse import time import cereal.messaging as messaging +from opendbc.car.carlog import carlog from opendbc.car.vin import get_vin from openpilot.selfdrive.car.card import can_comm_callbacks @@ -13,10 +14,13 @@ parser.add_argument('--retry', type=int, default=5) args = parser.parse_args() + if args.debug: + carlog.setLevel('DEBUG') + sendcan = messaging.pub_sock('sendcan') logcan = messaging.sub_sock('can') can_callbacks = can_comm_callbacks(logcan, sendcan) time.sleep(1) - vin_rx_addr, vin_rx_bus, vin = get_vin(*can_callbacks, (args.bus,), args.timeout, args.retry, debug=args.debug) + vin_rx_addr, vin_rx_bus, vin = get_vin(*can_callbacks, (args.bus,), args.timeout, args.retry) print(f'RX: {hex(vin_rx_addr)}, BUS: {vin_rx_bus}, VIN: {vin}') diff --git a/selfdrive/debug/vw_mqb_config.py b/selfdrive/debug/car/vw_mqb_config.py similarity index 94% rename from selfdrive/debug/vw_mqb_config.py rename to selfdrive/debug/car/vw_mqb_config.py index 6df1e57ce318d3..13ee7786d9b411 100755 --- a/selfdrive/debug/vw_mqb_config.py +++ b/selfdrive/debug/car/vw_mqb_config.py @@ -3,9 +3,11 @@ import argparse import struct from enum import IntEnum -from panda import Panda -from panda.python.uds import UdsClient, MessageTimeoutError, NegativeResponseError, SESSION_TYPE,\ +from opendbc.car.carlog import carlog +from opendbc.car.uds import UdsClient, MessageTimeoutError, NegativeResponseError, SESSION_TYPE,\ DATA_IDENTIFIER_TYPE, ACCESS_TYPE +from opendbc.car.structs import CarParams +from panda import Panda from datetime import date # TODO: extend UDS library to allow custom/vendor-defined data identifiers without ignoring type checks @@ -33,10 +35,12 @@ class ACCESS_TYPE_LEVEL_1(IntEnum): parser.add_argument("action", choices={"show", "enable", "disable"}, help="show or modify current EPS HCA config") args = parser.parse_args() + if args.debug: + carlog.setLevel('DEBUG') + panda = Panda() - panda.set_safety_mode(Panda.SAFETY_ELM327) - bus = 1 if panda.has_obd() else 0 - uds_client = UdsClient(panda, MQB_EPS_CAN_ADDR, MQB_EPS_CAN_ADDR + RX_OFFSET, bus, timeout=0.2, debug=args.debug) + panda.set_safety_mode(CarParams.SafetyModel.elm327) + uds_client = UdsClient(panda, MQB_EPS_CAN_ADDR, MQB_EPS_CAN_ADDR + RX_OFFSET, 1, timeout=0.2) try: uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) @@ -51,7 +55,7 @@ class ACCESS_TYPE_LEVEL_1(IntEnum): sw_ver = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_VERSION_NUMBER).decode("utf-8") component = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.SYSTEM_NAME_OR_ENGINE_TYPE).decode("utf-8") odx_file = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.ODX_FILE).decode("utf-8").rstrip('\x00') - current_coding = uds_client.read_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING) # type: ignore + current_coding = uds_client.read_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING) coding_text = current_coding.hex() print("\nEPS diagnostic data\n") @@ -122,9 +126,9 @@ class ACCESS_TYPE_LEVEL_1(IntEnum): new_coding = current_coding[0:coding_byte] + new_byte.to_bytes(1, "little") + current_coding[coding_byte+1:] try: - seed = uds_client.security_access(ACCESS_TYPE_LEVEL_1.REQUEST_SEED) # type: ignore + seed = uds_client.security_access(ACCESS_TYPE_LEVEL_1.REQUEST_SEED) key = struct.unpack("!I", seed)[0] + 28183 # yeah, it's like that - uds_client.security_access(ACCESS_TYPE_LEVEL_1.SEND_KEY, struct.pack("!I", key)) # type: ignore + uds_client.security_access(ACCESS_TYPE_LEVEL_1.SEND_KEY, struct.pack("!I", key)) except (NegativeResponseError, MessageTimeoutError): print("Security access failed!") print("Open the hood and retry (disables the \"diagnostic firewall\" on newer vehicles)") @@ -144,7 +148,7 @@ class ACCESS_TYPE_LEVEL_1(IntEnum): uds_client.write_data_by_identifier(DATA_IDENTIFIER_TYPE.PROGRAMMING_DATE, prog_date) tester_num = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.CALIBRATION_REPAIR_SHOP_CODE_OR_CALIBRATION_EQUIPMENT_SERIAL_NUMBER) uds_client.write_data_by_identifier(DATA_IDENTIFIER_TYPE.REPAIR_SHOP_CODE_OR_TESTER_SERIAL_NUMBER, tester_num) - uds_client.write_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING, new_coding) # type: ignore + uds_client.write_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING, new_coding) except (NegativeResponseError, MessageTimeoutError): print("Writing new configuration failed!") print("Make sure the comma processes are stopped: tmux kill-session -t comma") @@ -152,7 +156,7 @@ class ACCESS_TYPE_LEVEL_1(IntEnum): try: # Read back result just to make 100% sure everything worked - current_coding_text = uds_client.read_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING).hex() # type: ignore + current_coding_text = uds_client.read_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING).hex() print(f" New coding: {current_coding_text}") except (NegativeResponseError, MessageTimeoutError): print("Reading back updated coding failed!") diff --git a/selfdrive/debug/check_can_parser_performance.py b/selfdrive/debug/check_can_parser_performance.py index 2bddd362ae792e..20987b3cf41286 100755 --- a/selfdrive/debug/check_can_parser_performance.py +++ b/selfdrive/debug/check_can_parser_performance.py @@ -6,7 +6,6 @@ from cereal import car from opendbc.car.tests.routes import CarTestRoute from openpilot.selfdrive.car.tests.test_models import TestCarModelBase -from openpilot.selfdrive.pandad import can_capnp_to_list from openpilot.tools.plotjuggler.juggle import DEMO_ROUTE N_RUNS = 10 @@ -14,7 +13,6 @@ class CarModelTestCase(TestCarModelBase): test_route = CarTestRoute(DEMO_ROUTE, None) - ci = False if __name__ == '__main__': @@ -26,13 +24,11 @@ class CarModelTestCase(TestCarModelBase): CC = car.CarControl.new_message() ets = [] for _ in tqdm(range(N_RUNS)): - msgs = [m.as_builder().to_bytes() for m in tm.can_msgs] start_t = time.process_time_ns() - for msg in msgs: - can_list = can_capnp_to_list([msg]) - for cp in tm.CI.can_parsers: + for msg in tm.can_msgs: + for cp in tm.CI.can_parsers.values(): if cp is not None: - cp.update_strings(can_list) + cp.update_strings(msg) ets.append((time.process_time_ns() - start_t) * 1e-6) print(f'{len(tm.can_msgs)} CAN packets, {N_RUNS} runs') diff --git a/selfdrive/debug/count_events.py b/selfdrive/debug/count_events.py index 59420547570b0e..76e02d414ec873 100755 --- a/selfdrive/debug/count_events.py +++ b/selfdrive/debug/count_events.py @@ -8,6 +8,7 @@ from cereal.services import SERVICE_LIST from openpilot.tools.lib.logreader import LogReader, ReadMode +from openpilot.selfdrive.test.process_replay.migration import migrate_all if __name__ == "__main__": cnt_events: Counter = Counter() @@ -20,7 +21,7 @@ start_time = math.inf end_time = -math.inf ignition_off = None - for msg in LogReader(sys.argv[1], ReadMode.QLOG): + for msg in migrate_all(LogReader(sys.argv[1], ReadMode.QLOG)): t = (msg.logMonoTime - start_time) / 1e9 end_time = max(end_time, msg.logMonoTime) start_time = min(start_time, msg.logMonoTime) @@ -33,8 +34,8 @@ if len(events) == 0 or ae != events[-1][1]: events.append((t, ae)) - elif msg.which() == 'controlsState': - at = msg.controlsState.alertType + elif msg.which() == 'selfdriveState': + at = msg.selfdriveState.alertType if "/override" not in at or "lanechange" in at.lower(): if len(alerts) == 0 or alerts[-1][1] != at: alerts.append((t, at)) diff --git a/selfdrive/debug/cpu_usage_stat.py b/selfdrive/debug/cpu_usage_stat.py index 234dfea3ccf29c..089685103f7cda 100755 --- a/selfdrive/debug/cpu_usage_stat.py +++ b/selfdrive/debug/cpu_usage_stat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# type: ignore ''' System tools like top/htop can only show current cpu usage values, so I write this script to do statistics jobs. Features: @@ -37,8 +36,6 @@ cpu_time_names = ['user', 'system', 'children_user', 'children_system'] -timer = getattr(time, 'monotonic', time.time) - def get_arg_parser(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) @@ -72,7 +69,7 @@ def get_arg_parser(): print('Add monitored proc:', k) stats[k] = {'cpu_samples': defaultdict(list), 'min': defaultdict(lambda: None), 'max': defaultdict(lambda: None), 'avg': defaultdict(float), 'last_cpu_times': None, 'last_sys_time': None} - stats[k]['last_sys_time'] = timer() + stats[k]['last_sys_time'] = time.monotonic() stats[k]['last_cpu_times'] = p.cpu_times() monitored_procs.append(p) i = 0 @@ -80,7 +77,7 @@ def get_arg_parser(): while True: for p in monitored_procs: k = ' '.join(p.cmdline()) - cur_sys_time = timer() + cur_sys_time = time.monotonic() cur_cpu_times = p.cpu_times() cpu_times = np.subtract(cur_cpu_times, stats[k]['last_cpu_times']) / (cur_sys_time - stats[k]['last_sys_time']) stats[k]['last_sys_time'] = cur_sys_time diff --git a/selfdrive/debug/cycle_alerts.py b/selfdrive/debug/cycle_alerts.py index fbac65cac1606d..4b1def4fc64e01 100755 --- a/selfdrive/debug/cycle_alerts.py +++ b/selfdrive/debug/cycle_alerts.py @@ -6,11 +6,11 @@ import cereal.messaging as messaging from opendbc.car.honda.interface import CarInterface from openpilot.common.realtime import DT_CTRL -from openpilot.selfdrive.controls.lib.events import ET, Events -from openpilot.selfdrive.controls.lib.alertmanager import AlertManager +from openpilot.selfdrive.selfdrived.events import ET, Events +from openpilot.selfdrive.selfdrived.alertmanager import AlertManager from openpilot.system.manager.process_config import managed_processes -EventName = car.OnroadEvent.EventName +EventName = log.OnroadEvent.EventName def randperc() -> float: return 100. * random.random() @@ -30,9 +30,9 @@ def cycle_alerts(duration=200, is_metric=False): (EventName.accFaulted, ET.IMMEDIATE_DISABLE), # DM sequence - (EventName.preDriverDistracted, ET.WARNING), - (EventName.promptDriverDistracted, ET.WARNING), - (EventName.driverDistracted, ET.WARNING), + (EventName.driverDistracted1, ET.WARNING), + (EventName.driverDistracted2, ET.WARNING), + (EventName.driverDistracted3, ET.WARNING), ] # debug alerts @@ -99,8 +99,7 @@ def cycle_alerts(duration=200, is_metric=False): alert = AM.process_alerts(frame, []) print(alert) for _ in range(duration): - dat = messaging.new_message() - dat.init('selfdriveState') + dat = messaging.new_message('selfdriveState') dat.selfdriveState.enabled = False if alert: @@ -112,8 +111,7 @@ def cycle_alerts(duration=200, is_metric=False): dat.selfdriveState.alertSound = alert.audible_alert pm.send('selfdriveState', dat) - dat = messaging.new_message() - dat.init('deviceState') + dat = messaging.new_message('deviceState') dat.deviceState.started = True pm.send('deviceState', dat) diff --git a/selfdrive/debug/debug_fw_fingerprinting_offline.py b/selfdrive/debug/debug_fw_fingerprinting_offline.py index 3df2924738a9fc..d36b350bbcd07f 100755 --- a/selfdrive/debug/debug_fw_fingerprinting_offline.py +++ b/selfdrive/debug/debug_fw_fingerprinting_offline.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 import argparse +from opendbc.car import uds from openpilot.tools.lib.live_logreader import live_logreader from openpilot.tools.lib.logreader import LogReader, ReadMode -from panda.python import uds -def main(route: str | None, addrs: list[int]): +def main(route: str | None, addrs: list[int], rxoffset: int | None): """ TODO: - highlight TX vs RX clearly @@ -23,7 +23,7 @@ def main(route: str | None, addrs: list[int]): prev_mono_time = 0 # include rx addresses - addrs = addrs + [uds.get_rx_addr_for_tx_addr(addr) for addr in addrs] + addrs = addrs + [uds.get_rx_addr_for_tx_addr(addr, rxoffset) for addr in addrs] for msg in lr: if msg.which() == 'can': @@ -36,7 +36,7 @@ def main(route: str | None, addrs: list[int]): if msg.logMonoTime != prev_mono_time: print() prev_mono_time = msg.logMonoTime - print(f"{msg.which():>7}: rxaddr={can.address}, bus={can.src}, {round((msg.logMonoTime - start_mono_time) * 1e-6, 2)} ms, " + + print(f"{msg.which():>7}: rxaddr={can.address}, bus={str(can.src) + ',':<4} {round((msg.logMonoTime - start_mono_time) * 1e-6)} ms, " + f"0x{can.dat.hex()}, {can.dat}, {len(can.dat)=}") @@ -44,7 +44,9 @@ def main(route: str | None, addrs: list[int]): parser = argparse.ArgumentParser(description='View back and forth ISO-TP communication between various ECUs given an address') parser.add_argument('route', nargs='?', help='Route name, live if not specified') parser.add_argument('--addrs', nargs='*', default=[], help='List of tx address to view (0x7e0 for engine)') + parser.add_argument('--rxoffset', default='0x8') args = parser.parse_args() addrs = [int(addr, base=16) if addr.startswith('0x') else int(addr) for addr in args.addrs] - main(args.route, addrs) + rxoffset = int(args.rxoffset, base=16) if args.rxoffset else None + main(args.route, addrs, rxoffset) diff --git a/selfdrive/debug/fingerprint_from_route.py b/selfdrive/debug/fingerprint_from_route.py index 68308bb62782d5..5fd46f5b767853 100755 --- a/selfdrive/debug/fingerprint_from_route.py +++ b/selfdrive/debug/fingerprint_from_route.py @@ -8,10 +8,12 @@ def get_fingerprint(lr): # TODO: make this a nice tool for car ports. should also work with qlogs for FW fw = None + vin = None msgs = {} for msg in lr: if msg.which() == 'carParams': fw = msg.carParams.carFw + vin = msg.carParams.carVin elif msg.which() == 'can': for c in msg.can: # read also msgs sent by EON on CAN bus 0x80 and filter out the @@ -20,18 +22,20 @@ def get_fingerprint(lr): msgs[c.address] = len(c.dat) # show CAN fingerprint - fingerprint = ', '.join("%d: %d" % v for v in sorted(msgs.items())) + fingerprint = ', '.join(f"{v[0]}: {v[1]}" for v in sorted(msgs.items())) print(f"\nfound {len(msgs)} messages. CAN fingerprint:\n") print(fingerprint) # TODO: also print the fw fingerprint merged with the existing ones # show FW fingerprint - print("\nFW fingerprint:\n") - for f in fw: - print(f" (Ecu.{f.ecu}, {hex(f.address)}, {None if f.subAddress == 0 else f.subAddress}): [") - print(f" {f.fwVersion},") - print(" ],") + if fw: + print("\nFW fingerprint:\n") + for f in fw: + print(f" (Ecu.{f.ecu}, {hex(f.address)}, {None if f.subAddress == 0 else f.subAddress}): [") + print(f" {f.fwVersion},") + print(" ],") print() + print(f"VIN: {vin}") if __name__ == "__main__": diff --git a/selfdrive/debug/format_fingerprints.py b/selfdrive/debug/format_fingerprints.py deleted file mode 100755 index ae1ed06b75ae18..00000000000000 --- a/selfdrive/debug/format_fingerprints.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python3 -import jinja2 -import os - -from openpilot.common.basedir import BASEDIR -from opendbc.car.interfaces import get_interface_attr - -CARS = get_interface_attr('CAR') -FW_VERSIONS = get_interface_attr('FW_VERSIONS') -FINGERPRINTS = get_interface_attr('FINGERPRINTS') - -FINGERPRINTS_PY_TEMPLATE = jinja2.Template(""" -{%- if FINGERPRINTS[brand] %} -# ruff: noqa: E501 -{% endif %} -{% if FW_VERSIONS[brand] %} -from opendbc.car.structs import CarParams -{% endif %} -from opendbc.car.{{brand}}.values import CAR -{% if FW_VERSIONS[brand] %} - -Ecu = CarParams.Ecu -{% endif %} -{% if comments +%} -{{ comments | join() }} -{% endif %} -{% if FINGERPRINTS[brand] %} - -FINGERPRINTS = { -{% for car, fingerprints in FINGERPRINTS[brand].items() %} - CAR.{{car.name}}: [{ -{% for fingerprint in fingerprints %} -{% if not loop.first %} - {{ "{" }} -{% endif %} - {% for key, value in fingerprint.items() %}{{key}}: {{value}}{% if not loop.last %}, {% endif %}{% endfor %} - - }{% if loop.last %}]{% endif %}, -{% endfor %} -{% endfor %} -} -{% endif %} - -FW_VERSIONS{% if not FW_VERSIONS[brand] %}: dict[str, dict[tuple, list[bytes]]]{% endif %} = { -{% for car, _ in FW_VERSIONS[brand].items() %} - CAR.{{car.name}}: { -{% for key, fw_versions in FW_VERSIONS[brand][car].items() %} - (Ecu.{{key[0]}}, 0x{{"%0x" | format(key[1] | int)}}, \ -{% if key[2] %}0x{{"%0x" | format(key[2] | int)}}{% else %}{{key[2]}}{% endif %}): [ - {% for fw_version in (fw_versions + extra_fw_versions.get(car, {}).get(key, [])) | unique | sort %} - {{fw_version}}, - {% endfor %} - ], -{% endfor %} - }, -{% endfor %} -} - -""", trim_blocks=True) - - -def format_brand_fw_versions(brand, extra_fw_versions: None | dict[str, dict[tuple, list[bytes]]] = None): - extra_fw_versions = extra_fw_versions or {} - - fingerprints_file = os.path.join(BASEDIR, f"opendbc/car/{brand}/fingerprints.py") - with open(fingerprints_file) as f: - comments = [line for line in f.readlines() if line.startswith("#") and "noqa" not in line] - - with open(fingerprints_file, "w") as f: - f.write(FINGERPRINTS_PY_TEMPLATE.render(brand=brand, comments=comments, FINGERPRINTS=FINGERPRINTS, - FW_VERSIONS=FW_VERSIONS, extra_fw_versions=extra_fw_versions)) - - -if __name__ == "__main__": - for brand in FW_VERSIONS.keys(): - format_brand_fw_versions(brand) diff --git a/selfdrive/debug/internal/fuzz_fw_fingerprint.py b/selfdrive/debug/fuzz_fw_fingerprint.py similarity index 98% rename from selfdrive/debug/internal/fuzz_fw_fingerprint.py rename to selfdrive/debug/fuzz_fw_fingerprint.py index fa99e6bfbe8e9e..b4276c0c1af93d 100755 --- a/selfdrive/debug/internal/fuzz_fw_fingerprint.py +++ b/selfdrive/debug/fuzz_fw_fingerprint.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# type: ignore import random from collections import defaultdict diff --git a/selfdrive/debug/get_fingerprint.py b/selfdrive/debug/get_fingerprint.py index 14f6c0e33c353f..75c3d5579fdd37 100755 --- a/selfdrive/debug/get_fingerprint.py +++ b/selfdrive/debug/get_fingerprint.py @@ -25,7 +25,7 @@ if c.src % 0x80 == 0 and c.address < 0x800 and c.address not in (0x7df, 0x7e0, 0x7e8): msgs[c.address] = len(c.dat) - fingerprint = ', '.join("%d: %d" % v for v in sorted(msgs.items())) + fingerprint = ', '.join(f"{v[0]}: {v[1]}" for v in sorted(msgs.items())) print(f"number of messages {len(msgs)}:") print(f"fingerprint {fingerprint}") diff --git a/selfdrive/debug/internal/measure_modeld_packet_drop.py b/selfdrive/debug/internal/measure_modeld_packet_drop.py deleted file mode 100755 index 9814942ce27fc6..00000000000000 --- a/selfdrive/debug/internal/measure_modeld_packet_drop.py +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python3 -import cereal.messaging as messaging - -if __name__ == "__main__": - modeld_sock = messaging.sub_sock("modelV2") - - last_frame_id = None - start_t: int | None = None - frame_cnt = 0 - dropped = 0 - - while True: - m = messaging.recv_one(modeld_sock) - if m is None: - continue - - frame_id = m.modelV2.frameId - t = m.logMonoTime / 1e9 - frame_cnt += 1 - - if start_t is None: - start_t = t - last_frame_id = frame_id - continue - - d_frame = frame_id - last_frame_id - dropped += d_frame - 1 - - expected_num_frames = int((t - start_t) * 20) - frame_drop = 100 * (1 - (expected_num_frames / frame_cnt)) - print(f"Num dropped {dropped}, Drop compared to 20Hz: {frame_drop:.2f}%") - - last_frame_id = frame_id diff --git a/selfdrive/debug/live_cpu_and_temp.py b/selfdrive/debug/live_cpu_and_temp.py index 8549b92665e6a1..ee0524ec9d4d06 100755 --- a/selfdrive/debug/live_cpu_and_temp.py +++ b/selfdrive/debug/live_cpu_and_temp.py @@ -1,10 +1,10 @@ #!/usr/bin/env python3 import argparse +import numpy as np import capnp from collections import defaultdict from cereal.messaging import SubMaster -from openpilot.common.numpy_fast import mean def cputime_total(ct): return ct.user + ct.nice + ct.system + ct.idle + ct.iowait + ct.irq + ct.softirq @@ -49,7 +49,7 @@ def proc_name(proc): if sm.updated['deviceState']: t = sm['deviceState'] - last_temp = mean(t.cpuTempC) + last_temp = np.mean(t.cpuTempC) last_mem = t.memoryUsagePercent if sm.updated['procLog']: @@ -72,7 +72,7 @@ def proc_name(proc): total_times = total_times_new[:] busy_times = busy_times_new[:] - print(f"CPU {100.0 * mean(cores):.2f}% - RAM: {last_mem:.2f}% - Temp {last_temp:.2f}C") + print(f"CPU {100.0 * np.mean(cores):.2f}% - RAM: {last_mem:.2f}% - Temp {last_temp:.2f}C") if args.cpu and prev_proclog is not None and prev_proclog_t is not None: procs: dict[str, float] = defaultdict(float) diff --git a/selfdrive/debug/max_lat_accel.py b/selfdrive/debug/max_lat_accel.py new file mode 100755 index 00000000000000..dc44e8ac40f14b --- /dev/null +++ b/selfdrive/debug/max_lat_accel.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +import argparse +import numpy as np +import matplotlib.pyplot as plt +from functools import partial +from tqdm import tqdm +from typing import NamedTuple +from openpilot.tools.lib.logreader import LogReader +from openpilot.selfdrive.locationd.models.pose_kf import EARTH_G + +RLOG_MIN_LAT_ACTIVE = 50 +RLOG_MIN_STEERING_UNPRESSED = 50 +RLOG_MIN_REQUESTING_MAX = 25 # sample many times after reaching max torque + +QLOG_DECIMATION = 10 + + +class Event(NamedTuple): + lateral_accel: float + speed: float + roll: float + timestamp: float # relative to start of route (s) + + +def find_events(lr: LogReader, extrapolate: bool = False, qlog: bool = False) -> list[Event]: + min_lat_active = RLOG_MIN_LAT_ACTIVE // QLOG_DECIMATION if qlog else RLOG_MIN_LAT_ACTIVE + min_steering_unpressed = RLOG_MIN_STEERING_UNPRESSED // QLOG_DECIMATION if qlog else RLOG_MIN_STEERING_UNPRESSED + min_requesting_max = RLOG_MIN_REQUESTING_MAX // QLOG_DECIMATION if qlog else RLOG_MIN_REQUESTING_MAX + + # if we test with driver torque safety, max torque can be slightly noisy + steer_threshold = 0.7 if extrapolate else 0.95 + + events = [] + + # state tracking + steering_unpressed = 0 # frames + requesting_max = 0 # frames + lat_active = 0 # frames + + # current state + curvature = 0 + v_ego = 0 + roll = 0 + out_torque = 0 + + start_ts = 0 + for msg in lr: + if msg.which() == 'carControl': + if start_ts == 0: + start_ts = msg.logMonoTime + + lat_active = lat_active + 1 if msg.carControl.latActive else 0 + + elif msg.which() == 'carOutput': + out_torque = msg.carOutput.actuatorsOutput.torque + requesting_max = requesting_max + 1 if abs(out_torque) > steer_threshold else 0 + + elif msg.which() == 'carState': + steering_unpressed = steering_unpressed + 1 if not msg.carState.steeringPressed else 0 + v_ego = msg.carState.vEgo + + elif msg.which() == 'controlsState': + curvature = msg.controlsState.curvature + + elif msg.which() == 'liveParameters': + roll = msg.liveParameters.roll + + if lat_active > min_lat_active and steering_unpressed > min_steering_unpressed and requesting_max > min_requesting_max: + # TODO: record max lat accel at the end of the event, need to use the past lat accel as overriding can happen before we detect it + requesting_max = 0 + + factor = 1 / abs(out_torque) + current_lateral_accel = (curvature * v_ego ** 2 * factor) - roll * EARTH_G + events.append(Event(current_lateral_accel, v_ego, roll, round((msg.logMonoTime - start_ts) * 1e-9, 2))) + print(events[-1]) + + return events + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description="Find max lateral acceleration events", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument("route", nargs='+') + parser.add_argument("-e", "--extrapolate", action="store_true", help="Extrapolates max lateral acceleration events linearly. " + + "This option can be far less accurate.") + args = parser.parse_args() + + events = [] + for route in tqdm(args.route): + try: + lr = LogReader(route, sort_by_time=True) + except Exception: + print(f'Skipping {route}') + continue + + qlog = route.endswith('/q') + if qlog: + print('WARNING: Treating route as qlog!') + + print('Finding events...') + events += lr.run_across_segments(8, partial(find_events, extrapolate=args.extrapolate, qlog=qlog), disable_tqdm=True) + + print() + print(f'Found {len(events)} events') + + perc_left_accel = -np.percentile([-ev.lateral_accel for ev in events if ev.lateral_accel < 0] or [0], 90) + perc_right_accel = np.percentile([ev.lateral_accel for ev in events if ev.lateral_accel > 0] or [0], 90) + + CP = lr.first('carParams') + + plt.ion() + plt.clf() + plt.suptitle(f'{CP.carFingerprint} - Max lateral acceleration events') + plt.title(', '.join(args.route)) + plt.scatter([ev.speed for ev in events], [ev.lateral_accel for ev in events], label='max lateral accel events') + + plt.plot([0, 35], [3, 3], c='r', label='ISO 11270 - 3 m/s^2') + plt.plot([0, 35], [-3, -3], c='r') + + plt.plot([0, 35], [perc_left_accel, perc_left_accel], c='g', linestyle='--', label='90th percentile left lateral accel') + plt.plot([0, 35], [perc_right_accel, perc_right_accel], c='#ff7f0e', linestyle='--', label='90th percentile right lateral accel') + plt.text(0.4, float(perc_left_accel + 0.4), f'{perc_left_accel:.2f} m/s^2', verticalalignment='center', fontsize=12) + plt.text(0.4, float(perc_right_accel - 0.4), f'{perc_right_accel:.2f} m/s^2', verticalalignment='center', fontsize=12) + + plt.xlim(0, 35) + plt.ylim(-5, 5) + plt.xlabel('speed (m/s)') + plt.ylabel('lateral acceleration (m/s^2)') + plt.legend() + plt.show(block=True) diff --git a/selfdrive/debug/internal/measure_torque_time_to_max.py b/selfdrive/debug/measure_torque_time_to_max.py similarity index 99% rename from selfdrive/debug/internal/measure_torque_time_to_max.py rename to selfdrive/debug/measure_torque_time_to_max.py index 7052dccf7de283..e99aeae464b8e9 100755 --- a/selfdrive/debug/internal/measure_torque_time_to_max.py +++ b/selfdrive/debug/measure_torque_time_to_max.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# type: ignore import os import argparse diff --git a/selfdrive/debug/mem_usage.py b/selfdrive/debug/mem_usage.py new file mode 100755 index 00000000000000..bc0e97e7caea9b --- /dev/null +++ b/selfdrive/debug/mem_usage.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +import argparse +import os +from collections import defaultdict + +import numpy as np + +from openpilot.common.utils import tabulate +from openpilot.tools.lib.logreader import LogReader + +DEMO_ROUTE = "5beb9b58bd12b691/0000010a--a51155e496" +MB = 1024 * 1024 +TABULATE_OPTS = dict(tablefmt="simple_grid", stralign="center", numalign="center") + + +def _get_procs(): + from openpilot.selfdrive.test.test_onroad import PROCS + return PROCS + + +def is_openpilot_proc(name): + if any(p in name for p in _get_procs()): + return True + # catch openpilot processes not in PROCS (athenad, manager, etc.) + return 'openpilot' in name or name.startswith(('selfdrive.', 'system.')) + + +def get_proc_name(proc): + if len(proc.cmdline) > 0: + return list(proc.cmdline)[0] + return proc.name + + +def pct(val_mb, total_mb): + return val_mb / total_mb * 100 if total_mb else 0 + + +def has_pss(proc_logs): + """Check if logs contain PSS data (new field, not in old logs).""" + try: + for proc in proc_logs[-1].procLog.procs: + if proc.memPss > 0: + return True + except AttributeError: + pass + return False + + +def print_summary(proc_logs, device_states): + mem = proc_logs[-1].procLog.mem + total = mem.total / MB + used = (mem.total - mem.available) / MB + cached = mem.cached / MB + shared = mem.shared / MB + buffers = mem.buffers / MB + + lines = [ + f" Total: {total:.0f} MB", + f" Used (total-avail): {used:.0f} MB ({pct(used, total):.0f}%)", + f" Cached: {cached:.0f} MB ({pct(cached, total):.0f}%) Buffers: {buffers:.0f} MB ({pct(buffers, total):.0f}%)", + f" Shared/MSGQ: {shared:.0f} MB ({pct(shared, total):.0f}%)", + ] + + if device_states: + mem_pcts = [m.deviceState.memoryUsagePercent for m in device_states] + lines.append(f" deviceState memory: {np.min(mem_pcts)}-{np.max(mem_pcts)}% (avg {np.mean(mem_pcts):.0f}%)") + + print("\n-- Memory Summary --") + print("\n".join(lines)) + return total + + +def collect_per_process_mem(proc_logs, use_pss): + """Collect per-process memory samples. Returns {name: {metric: [values_per_sample_in_MB]}}.""" + by_proc = defaultdict(lambda: defaultdict(list)) + + for msg in proc_logs: + sample = defaultdict(lambda: defaultdict(float)) + for proc in msg.procLog.procs: + name = get_proc_name(proc) + sample[name]['rss'] += proc.memRss / MB + if use_pss: + sample[name]['pss'] += proc.memPss / MB + sample[name]['pss_anon'] += proc.memPssAnon / MB + sample[name]['pss_shmem'] += proc.memPssShmem / MB + + for name, metrics in sample.items(): + for metric, val in metrics.items(): + by_proc[name][metric].append(val) + + return by_proc + + +def _has_pss_detail(by_proc) -> bool: + """Check if any process has non-zero pss_anon/pss_shmem (unavailable on some kernels).""" + return any(sum(v.get('pss_anon', [])) > 0 or sum(v.get('pss_shmem', [])) > 0 for v in by_proc.values()) + + +def process_table_rows(by_proc, total_mb, use_pss, show_detail): + """Build table rows. Returns (rows, total_row).""" + mem_key = 'pss' if use_pss else 'rss' + rows = [] + for name in sorted(by_proc, key=lambda n: np.mean(by_proc[n][mem_key]), reverse=True): + m = by_proc[name] + vals = m[mem_key] + avg = round(np.mean(vals)) + row = [name, f"{avg} MB", f"{round(np.max(vals))} MB", f"{round(pct(avg, total_mb), 1)}%"] + if show_detail: + row.append(f"{round(np.mean(m['pss_anon']))} MB") + row.append(f"{round(np.mean(m['pss_shmem']))} MB") + rows.append(row) + + # Total row + total_row = None + if by_proc: + max_samples = max(len(v[mem_key]) for v in by_proc.values()) + totals = [] + for i in range(max_samples): + s = sum(v[mem_key][i] for v in by_proc.values() if i < len(v[mem_key])) + totals.append(s) + avg_total = round(np.mean(totals)) + total_row = ["TOTAL", f"{avg_total} MB", f"{round(np.max(totals))} MB", f"{round(pct(avg_total, total_mb), 1)}%"] + if show_detail: + total_row.append(f"{round(sum(np.mean(v['pss_anon']) for v in by_proc.values()))} MB") + total_row.append(f"{round(sum(np.mean(v['pss_shmem']) for v in by_proc.values()))} MB") + + return rows, total_row + + +def print_process_tables(op_procs, other_procs, total_mb, use_pss): + all_procs = {**op_procs, **other_procs} + show_detail = use_pss and _has_pss_detail(all_procs) + + header = ["process", "avg", "max", "%"] + if show_detail: + header += ["anon", "shmem"] + + op_rows, op_total = process_table_rows(op_procs, total_mb, use_pss, show_detail) + # filter other: >5MB avg and not bare interpreter paths (test infra noise) + other_filtered = {n: v for n, v in other_procs.items() + if np.mean(v['pss' if use_pss else 'rss']) > 5.0 + and os.path.basename(n.split()[0]) not in ('python', 'python3')} + other_rows, other_total = process_table_rows(other_filtered, total_mb, use_pss, show_detail) + + rows = op_rows + if op_total: + rows.append(op_total) + if other_rows: + sep_width = len(header) + rows.append([""] * sep_width) + rows.extend(other_rows) + if other_total: + other_total[0] = "TOTAL (other)" + rows.append(other_total) + + metric = "PSS (no shared double-count)" if use_pss else "RSS (includes shared, overcounts)" + print(f"\n-- Per-Process Memory: {metric} --") + print(tabulate(rows, header, **TABULATE_OPTS)) + + +def print_memory_accounting(proc_logs, op_procs, other_procs, total_mb, use_pss): + last = proc_logs[-1].procLog.mem + used = (last.total - last.available) / MB + shared = last.shared / MB + cached_buf = (last.buffers + last.cached) / MB - shared # shared (MSGQ) is in Cached; separate it + msgq = shared + + mem_key = 'pss' if use_pss else 'rss' + op_total = sum(v[mem_key][-1] for v in op_procs.values()) if op_procs else 0 + other_total = sum(v[mem_key][-1] for v in other_procs.values()) if other_procs else 0 + proc_sum = op_total + other_total + remainder = used - (cached_buf + msgq) - proc_sum + + if not use_pss: + # RSS double-counts shared; add back once to partially correct + remainder += shared + + header = ["", "MB", "%", ""] + label = "PSS" if use_pss else "RSS*" + rows = [ + ["Used (total - avail)", f"{used:.0f}", f"{pct(used, total_mb):.1f}", "memory in use by the system"], + [" Cached + Buffers", f"{cached_buf:.0f}", f"{pct(cached_buf, total_mb):.1f}", "pagecache + fs metadata, reclaimable"], + [" MSGQ (shared)", f"{msgq:.0f}", f"{pct(msgq, total_mb):.1f}", "/dev/shm tmpfs, also in process PSS"], + [f" openpilot {label}", f"{op_total:.0f}", f"{pct(op_total, total_mb):.1f}", "sum of openpilot process memory"], + [f" other {label}", f"{other_total:.0f}", f"{pct(other_total, total_mb):.1f}", "sum of non-openpilot process memory"], + [" kernel/ION/GPU", f"{remainder:.0f}", f"{pct(remainder, total_mb):.1f}", "slab, ION/DMA-BUF, GPU, page tables"], + ] + note = "" if use_pss else " (*RSS overcounts shared mem)" + print(f"\n-- Memory Accounting (last sample){note} --") + print(tabulate(rows, header, tablefmt="simple_grid", stralign="right")) + + +def print_report(proc_logs, device_states=None): + """Print full memory analysis report. Can be called from tests or CLI.""" + if not proc_logs: + print("No procLog messages found") + return + + print(f"{len(proc_logs)} procLog samples, {len(device_states or [])} deviceState samples") + + use_pss = has_pss(proc_logs) + if not use_pss: + print(" (no PSS data — re-record with updated proclogd for accurate numbers)") + + total_mb = print_summary(proc_logs, device_states or []) + + by_proc = collect_per_process_mem(proc_logs, use_pss) + op_procs = {n: v for n, v in by_proc.items() if is_openpilot_proc(n)} + other_procs = {n: v for n, v in by_proc.items() if not is_openpilot_proc(n)} + + print_process_tables(op_procs, other_procs, total_mb, use_pss) + print_memory_accounting(proc_logs, op_procs, other_procs, total_mb, use_pss) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Analyze memory usage from route logs") + parser.add_argument("route", nargs="?", default=None, help="route ID or local rlog path") + parser.add_argument("--demo", action="store_true", help=f"use demo route ({DEMO_ROUTE})") + args = parser.parse_args() + + if args.demo: + route = DEMO_ROUTE + elif args.route: + route = args.route + else: + parser.error("provide a route or use --demo") + + print(f"Reading logs from: {route}") + + proc_logs = [] + device_states = [] + for msg in LogReader(route): + if msg.which() == 'procLog': + proc_logs.append(msg) + elif msg.which() == 'deviceState': + device_states.append(msg) + + print_report(proc_logs, device_states) diff --git a/selfdrive/debug/print_docs_diff.py b/selfdrive/debug/print_docs_diff.py index 388acf3af58020..c7850939f073a2 100755 --- a/selfdrive/debug/print_docs_diff.py +++ b/selfdrive/debug/print_docs_diff.py @@ -11,7 +11,7 @@ STAR_ICON = '' VIDEO_ICON = '' + \ - '' + '' COLUMNS = "|" + "|".join([column.value for column in Column]) + "|" COLUMN_HEADER = "|---|---|---|{}|".format("|".join([":---:"] * (len(Column) - 3))) ARROW_SYMBOL = "➡️" diff --git a/selfdrive/debug/internal/qlog_size.py b/selfdrive/debug/qlog_size.py similarity index 97% rename from selfdrive/debug/internal/qlog_size.py rename to selfdrive/debug/qlog_size.py index 11606c758919f2..2b54cfeebf7297 100755 --- a/selfdrive/debug/internal/qlog_size.py +++ b/selfdrive/debug/qlog_size.py @@ -6,7 +6,7 @@ import matplotlib.pyplot as plt from cereal.services import SERVICE_LIST -from openpilot.system.loggerd.uploader import LOG_COMPRESSION_LEVEL +from openpilot.common.utils import LOG_COMPRESSION_LEVEL from openpilot.tools.lib.logreader import LogReader from tqdm import tqdm diff --git a/selfdrive/debug/read_dtc_status.py b/selfdrive/debug/read_dtc_status.py index 2d27dd2bb23eb7..f9dad535771f6c 100755 --- a/selfdrive/debug/read_dtc_status.py +++ b/selfdrive/debug/read_dtc_status.py @@ -2,9 +2,10 @@ import sys import argparse from subprocess import check_output, CalledProcessError +from opendbc.car.carlog import carlog +from opendbc.car.uds import UdsClient, SESSION_TYPE, DTC_REPORT_TYPE, DTC_STATUS_MASK_TYPE, get_dtc_num_as_str, get_dtc_status_names +from opendbc.car.structs import CarParams from panda import Panda -from panda.python.uds import UdsClient, SESSION_TYPE, DTC_REPORT_TYPE, DTC_STATUS_MASK_TYPE -from panda.python.uds import get_dtc_num_as_str, get_dtc_status_names parser = argparse.ArgumentParser(description="read DTC status") parser.add_argument("addr", type=lambda x: int(x,0)) @@ -12,6 +13,9 @@ parser.add_argument('--debug', action='store_true') args = parser.parse_args() +if args.debug: + carlog.setLevel('DEBUG') + try: check_output(["pidof", "pandad"]) print("pandad is running, please kill openpilot before running this script! (aborted)") @@ -21,8 +25,8 @@ raise e panda = Panda() -panda.set_safety_mode(Panda.SAFETY_ELM327) -uds_client = UdsClient(panda, args.addr, bus=args.bus, debug=args.debug) +panda.set_safety_mode(CarParams.SafetyModel.elm327) +uds_client = UdsClient(panda, args.addr, bus=args.bus) print("extended diagnostic session ...") uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) print("read diagnostic codes ...") diff --git a/selfdrive/debug/run_process_on_route.py b/selfdrive/debug/run_process_on_route.py index 45665e8a48fde4..d6743fedcb4095 100755 --- a/selfdrive/debug/run_process_on_route.py +++ b/selfdrive/debug/run_process_on_route.py @@ -1,30 +1,32 @@ #!/usr/bin/env python3 - import argparse from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, replay_process +from openpilot.selfdrive.test.process_replay.test_processes import EXCLUDED_PROCS from openpilot.tools.lib.logreader import LogReader, save_log +ALLOW_PROCS = {c.proc_name for c in CONFIGS} + if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run process on route and create new logs", formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("--fingerprint", help="The fingerprint to use") parser.add_argument("route", help="The route name to use") - parser.add_argument("process", help="The process to run") + parser.add_argument("--fingerprint", help="The fingerprint to use") + parser.add_argument("--whitelist-procs", nargs='*', default=ALLOW_PROCS, help="Whitelist given processes (e.g. controlsd)") + parser.add_argument("--blacklist-procs", nargs='*', default=EXCLUDED_PROCS, help="Blacklist given processes (e.g. controlsd)") args = parser.parse_args() - cfg = [c for c in CONFIGS if c.proc_name == args.process][0] - - lr = LogReader(args.route) - inputs = list(lr) + allowed_procs = set(args.whitelist_procs) - set(args.blacklist_procs) + cfgs = [c for c in CONFIGS if c.proc_name in allowed_procs] - outputs = replay_process(cfg, inputs, fingerprint=args.fingerprint) + inputs = list(LogReader(args.route)) + outputs = replay_process(cfgs, inputs, fingerprint=args.fingerprint) # Remove message generated by the process under test and merge in the new messages produces = {o.which() for o in outputs} inputs = [i for i in inputs if i.which() not in produces] outputs = sorted(inputs + outputs, key=lambda x: x.logMonoTime) - fn = f"{args.route.replace('/', '_')}_{args.process}.zst" + fn = f"{args.route.replace('/', '_')}_{'_'.join(allowed_procs)}.zst" print(f"Saving log to {fn}") save_log(fn, outputs) diff --git a/selfdrive/debug/set_car_params.py b/selfdrive/debug/set_car_params.py index 6060dfbc36930a..dabb6b706587a7 100755 --- a/selfdrive/debug/set_car_params.py +++ b/selfdrive/debug/set_car_params.py @@ -15,8 +15,8 @@ else: CP = car.CarParams.new_message() CP.openpilotLongitudinalControl = True - CP.experimentalLongitudinalAvailable = False + CP.alphaLongitudinalAvailable = False cp_bytes = CP.to_bytes() for p in ("CarParams", "CarParamsCache", "CarParamsPersistent"): - Params().put(p, cp_bytes) + Params().put(p, cp_bytes, block=True) diff --git a/selfdrive/debug/show_matching_cars.py b/selfdrive/debug/show_matching_cars.py deleted file mode 100755 index bc137729777259..00000000000000 --- a/selfdrive/debug/show_matching_cars.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env python3 -from opendbc.car.fingerprints import eliminate_incompatible_cars, all_legacy_fingerprint_cars -import cereal.messaging as messaging - - -# rav4 2019 and corolla tss2 -fingerprint = {896: 8, 898: 8, 900: 6, 976: 1, 1541: 8, 902: 6, 905: 8, 810: 2, 1164: 8, 1165: 8, 1166: 8, 1167: 8, 1552: 8, 1553: 8, 1556: 8, 1571: 8, 921: 8, 1056: 8, 544: 4, 1570: 8, 1059: 1, 36: 8, 37: 8, 550: 8, 935: 8, 552: 4, 170: 8, 812: 8, 944: 8, 945: 8, 562: 6, 180: 8, 1077: 8, 951: 8, 1592: 8, 1076: 8, 186: 4, 955: 8, 956: 8, 1001: 8, 705: 8, 452: 8, 1788: 8, 464: 8, 824: 8, 466: 8, 467: 8, 761: 8, 728: 8, 1572: 8, 1114: 8, 933: 8, 800: 8, 608: 8, 865: 8, 610: 8, 1595: 8, 934: 8, 998: 5, 1745: 8, 1000: 8, 764: 8, 1002: 8, 999: 7, 1789: 8, 1649: 8, 1779: 8, 1568: 8, 1017: 8, 1786: 8, 1787: 8, 1020: 8, 426: 6, 1279: 8} # noqa: E501 - -candidate_cars = all_legacy_fingerprint_cars() - - -for addr, l in fingerprint.items(): - dat = messaging.new_message('can', 1) - - msg = dat.can[0] - msg.address = addr - msg.dat = " " * l - - candidate_cars = eliminate_incompatible_cars(msg, candidate_cars) - print(candidate_cars) diff --git a/selfdrive/debug/test_fw_query_on_routes.py b/selfdrive/debug/test_fw_query_on_routes.py index f23c285908414e..ab539e4feba49f 100755 --- a/selfdrive/debug/test_fw_query_on_routes.py +++ b/selfdrive/debug/test_fw_query_on_routes.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# type: ignore from collections import defaultdict import argparse @@ -65,8 +64,7 @@ CP = msg.carParams car_fw = [fw for fw in CP.carFw if not fw.logging] if len(car_fw) == 0: - print("no fw") - break + print("WARNING: no fw") live_fingerprint = CP.carFingerprint live_fingerprint = MIGRATION.get(live_fingerprint, live_fingerprint) @@ -98,7 +96,7 @@ print("New style (exact):", exact_matches) print("New style (fuzzy):", fuzzy_matches) - padding = max([len(fw.brand or UNKNOWN_BRAND) for fw in car_fw]) + padding = max([len(fw.brand or UNKNOWN_BRAND) for fw in car_fw] + [0]) for version in sorted(car_fw, key=lambda fw: fw.brand): subaddr = None if version.subAddress == 0 else hex(version.subAddress) print(f" Brand: {version.brand or UNKNOWN_BRAND:{padding}}, bus: {version.bus} - " + diff --git a/selfdrive/debug/touch_replay.py b/selfdrive/debug/touch_replay.py new file mode 100755 index 00000000000000..6e5ecbbe5b59e8 --- /dev/null +++ b/selfdrive/debug/touch_replay.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +import argparse + +import numpy as np +import matplotlib.pyplot as plt + +from openpilot.tools.lib.logreader import LogReader + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--width', default=2160, type=int) + parser.add_argument('--height', default=1080, type=int) + parser.add_argument('--route', default='rlog', type=str) + args = parser.parse_args() + + w = args.width + h = args.height + route = args.route + + fingers = [[-1, -1]] * 5 + touch_points = [] + current_slot = 0 + + lr = list(LogReader(route)) + for msg in lr: + if msg.which() == 'touch': + for event in msg.touch: + if event.type == 3 and event.code == 47: + current_slot = event.value + elif event.type == 3 and event.code == 57 and event.value == -1: + fingers[current_slot] = [-1, -1] + elif event.type == 3 and event.code == 53: + fingers[current_slot][1] = event.value + if fingers[current_slot][0] != -1: + touch_points.append(fingers[current_slot].copy()) + elif event.type == 3 and event.code == 54: + fingers[current_slot][0] = w - event.value + if fingers[current_slot][1] != -1: + touch_points.append(fingers[current_slot].copy()) + + if not touch_points: + print(f'No touch events found for {route}') + quit() + + unique_points, counts = np.unique(touch_points, axis=0, return_counts=True) + + plt.figure(figsize=(10, 3)) + plt.scatter(unique_points[:, 0], unique_points[:, 1], c=counts, s=counts * 20, edgecolors='red') + plt.colorbar() + plt.title(f'Touches for {route}') + plt.xlim(0, w) + plt.ylim(0, h) + plt.grid(True) + plt.show() diff --git a/selfdrive/debug/uiview.py b/selfdrive/debug/uiview.py index 8e75769a85ec64..e558406b09dc2e 100755 --- a/selfdrive/debug/uiview.py +++ b/selfdrive/debug/uiview.py @@ -8,7 +8,7 @@ if __name__ == "__main__": CP = car.CarParams(notCar=True, wheelbase=1, steerRatio=10) - Params().put("CarParams", CP.to_bytes()) + Params().put("CarParams", CP.to_bytes(), block=True) procs = ['camerad', 'ui', 'modeld', 'calibrationd', 'plannerd', 'dmonitoringmodeld', 'dmonitoringd'] for p in procs: diff --git a/selfdrive/locationd/.gitignore b/selfdrive/locationd/.gitignore deleted file mode 100644 index 11b9f127b2753f..00000000000000 --- a/selfdrive/locationd/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -params_learner -paramsd -locationd diff --git a/selfdrive/locationd/SConscript b/selfdrive/locationd/SConscript index 27cd4d5b40bcae..e8eeff7e0cc102 100644 --- a/selfdrive/locationd/SConscript +++ b/selfdrive/locationd/SConscript @@ -1,17 +1,15 @@ -Import('env', 'arch', 'common', 'messaging', 'rednose', 'transformations') - -loc_libs = [messaging, common, 'pthread', 'dl'] +Import('env', 'rednose') # build ekf models rednose_gen_dir = 'models/generated' rednose_gen_deps = [ "models/constants.py", ] -live_ekf = env.RednoseCompileFilter( - target='live', - filter_gen_script='models/live_kf.py', +pose_ekf = env.RednoseCompileFilter( + target='pose', + filter_gen_script='models/pose_kf.py', output_dir=rednose_gen_dir, - extra_gen_artifacts=['live_kf_constants.h'], + extra_gen_artifacts=[], gen_script_deps=rednose_gen_deps, ) car_ekf = env.RednoseCompileFilter( @@ -21,17 +19,3 @@ car_ekf = env.RednoseCompileFilter( extra_gen_artifacts=[], gen_script_deps=rednose_gen_deps, ) - -# locationd build -locationd_sources = ["locationd.cc", "models/live_kf.cc"] - -lenv = env.Clone() -# ekf filter libraries need to be linked, even if no symbols are used -if arch != "Darwin": - lenv["LINKFLAGS"] += ["-Wl,--no-as-needed"] - -lenv["LIBPATH"].append(Dir(rednose_gen_dir).abspath) -lenv["RPATH"].append(Dir(rednose_gen_dir).abspath) -locationd = lenv.Program("locationd", locationd_sources, LIBS=["live", "ekf_sym"] + loc_libs + transformations) -lenv.Depends(locationd, rednose) -lenv.Depends(locationd, live_ekf) diff --git a/selfdrive/locationd/calibrationd.py b/selfdrive/locationd/calibrationd.py index 6e154bf07cf83e..4423f39061f02f 100755 --- a/selfdrive/locationd/calibrationd.py +++ b/selfdrive/locationd/calibrationd.py @@ -6,17 +6,17 @@ and the image input into the neural network is not corrected for roll. ''' -import gc import os import capnp import numpy as np from typing import NoReturn -from cereal import log +from cereal import log, car import cereal.messaging as messaging -from openpilot.common.conversions import Conversions as CV +from openpilot.system.hardware import HARDWARE +from openpilot.common.constants import CV from openpilot.common.params import Params -from openpilot.common.realtime import set_realtime_priority +from openpilot.common.realtime import config_realtime_process from openpilot.common.transformations.orientation import rot_from_euler, euler_from_rot from openpilot.common.swaglog import cloudlog @@ -37,14 +37,17 @@ WIDE_FROM_DEVICE_EULER_INIT = np.array([0.0, 0.0, 0.0]) HEIGHT_INIT = np.array([1.22]) -# These values are needed to accommodate the model frame in the narrow cam of the C3 -PITCH_LIMITS = np.array([-0.09074112085129739, 0.17]) +# These values are needed to accommodate the model frame in the narrow cam +if HARDWARE.get_device_type() == 'mici': + PITCH_LIMITS = np.array([-0.143101, 0.22235988]) +else: + PITCH_LIMITS = np.array([-0.09074112085129739, 0.17]) YAW_LIMITS = np.array([-0.06912048084718224, 0.06912048084718235]) DEBUG = os.getenv("DEBUG") is not None def is_calibration_valid(rpy: np.ndarray) -> bool: - return (PITCH_LIMITS[0] < rpy[1] < PITCH_LIMITS[1]) and (YAW_LIMITS[0] < rpy[2] < YAW_LIMITS[1]) # type: ignore + return (PITCH_LIMITS[0] < rpy[1] < PITCH_LIMITS[1]) and (YAW_LIMITS[0] < rpy[2] < YAW_LIMITS[1]) def sanity_clip(rpy: np.ndarray) -> np.ndarray: @@ -89,7 +92,7 @@ def reset(self, rpy_init: np.ndarray = RPY_INIT, valid_blocks: int = 0, wide_from_device_euler_init: np.ndarray = WIDE_FROM_DEVICE_EULER_INIT, height_init: np.ndarray = HEIGHT_INIT, - smooth_from: np.ndarray = None) -> None: + smooth_from: np.ndarray | None = None) -> None: if not np.isfinite(rpy_init).all(): self.rpy = RPY_INIT.copy() else: @@ -164,7 +167,7 @@ def update_status(self) -> None: write_this_cycle = (self.idx == 0) and (self.block_idx % (INPUTS_WANTED//5) == 5) if self.param_put and write_this_cycle: - self.params.put_nonblocking("CalibrationParams", self.get_msg(True).to_bytes()) + self.params.put("CalibrationParams", self.get_msg(True).to_bytes()) def handle_v_ego(self, v_ego: float) -> None: self.v_ego = v_ego @@ -256,20 +259,21 @@ def send_data(self, pm: messaging.PubMaster, valid: bool) -> None: def main() -> NoReturn: - gc.disable() - set_realtime_priority(1) + config_realtime_process([0, 1, 2, 3], 5) pm = messaging.PubMaster(['liveCalibration']) - sm = messaging.SubMaster(['cameraOdometry', 'carState', 'carParams'], poll='cameraOdometry') + sm = messaging.SubMaster(['cameraOdometry', 'carState'], poll='cameraOdometry') + + params_reader = Params() + CP = messaging.log_from_bytes(params_reader.get("CarParams", block=True), car.CarParams) calibrator = Calibrator(param_put=True) + calibrator.not_car = CP.notCar while 1: timeout = 0 if sm.frame == -1 else 100 sm.update(timeout) - calibrator.not_car = sm['carParams'].notCar - if sm.updated['cameraOdometry']: calibrator.handle_v_ego(sm['carState'].vEgo) new_rpy = calibrator.handle_cam_odom(sm['cameraOdometry'].trans, diff --git a/selfdrive/locationd/helpers.py b/selfdrive/locationd/helpers.py index af307b0336d931..73c4d8bf352552 100644 --- a/selfdrive/locationd/helpers.py +++ b/selfdrive/locationd/helpers.py @@ -1,10 +1,48 @@ import numpy as np from typing import Any +from functools import cache from cereal import log from openpilot.common.transformations.orientation import rot_from_euler, euler_from_rot +@cache +def fft_next_good_size(n: int) -> int: + """ + smallest composite of 2, 3, 5, 7, 11 that is >= n + inspired by pocketfft + """ + if n <= 6: + return n + best, f2 = 2 * n, 1 + while f2 < best: + f23 = f2 + while f23 < best: + f235 = f23 + while f235 < best: + f2357 = f235 + while f2357 < best: + f235711 = f2357 + while f235711 < best: + best = f235711 if f235711 >= n else best + f235711 *= 11 + f2357 *= 7 + f235 *= 5 + f23 *= 3 + f2 *= 2 + return best + + +def parabolic_peak_interp(R, max_index): + if max_index == 0 or max_index == len(R) - 1: + return max_index + + y_m1, y_0, y_p1 = R[max_index - 1], R[max_index], R[max_index + 1] + offset = 0.5 * (y_p1 - y_m1) / (2 * y_0 - y_p1 - y_m1) + + return max_index + offset + + def rotate_cov(rot_matrix, cov_in): return rot_matrix @ cov_in @ rot_matrix.T @@ -44,13 +82,19 @@ def is_valid(self) -> bool: total_points_valid = self.__len__() >= self.min_points_total return individual_buckets_valid and total_points_valid + def get_valid_percent(self) -> int: + total_points_perc = min(self.__len__() / self.min_points_total * 100, 100) + individual_buckets_perc = min(min(len(v) / min_pts * 100 for v, min_pts in + zip(self.buckets.values(), self.buckets_min_points.values(), strict=True)), 100) + return int((total_points_perc + individual_buckets_perc) / 2) + def is_calculable(self) -> bool: return all(len(v) > 0 for v in self.buckets.values()) def add_point(self, x: float, y: float) -> None: raise NotImplementedError - def get_points(self, num_points: int = None) -> Any: + def get_points(self, num_points: int | None = None) -> Any: points = np.vstack([x.arr for x in self.buckets.values()]) if num_points is None: return points @@ -128,7 +172,7 @@ def build_calibrated_pose(self, pose: Pose) -> Pose: ned_from_calib_euler = self._ned_from_calib(pose.orientation) angular_velocity_calib = self._transform_calib_from_device(pose.angular_velocity) acceleration_calib = self._transform_calib_from_device(pose.acceleration) - velocity_calib = self._transform_calib_from_device(pose.angular_velocity) + velocity_calib = self._transform_calib_from_device(pose.velocity) return Pose(ned_from_calib_euler, velocity_calib, acceleration_calib, angular_velocity_calib) diff --git a/selfdrive/locationd/lagd.py b/selfdrive/locationd/lagd.py new file mode 100755 index 00000000000000..e2026908c9e82e --- /dev/null +++ b/selfdrive/locationd/lagd.py @@ -0,0 +1,414 @@ +#!/usr/bin/env python3 +import os +import numpy as np +import capnp +from collections import deque +from functools import partial + +import cereal.messaging as messaging +from cereal import car, log +from cereal.services import SERVICE_LIST +from openpilot.common.params import Params +from openpilot.common.realtime import config_realtime_process +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose, fft_next_good_size, parabolic_peak_interp + +BLOCK_SIZE = 100 +BLOCK_NUM = 50 +BLOCK_NUM_NEEDED = 5 +MOVING_WINDOW_SEC = 60.0 +MIN_OKAY_WINDOW_SEC = 25.0 +MIN_RECOVERY_BUFFER_SEC = 2.0 +MIN_VEGO = 15.0 +MIN_ABS_YAW_RATE = 0.0 +MAX_YAW_RATE_SANITY_CHECK = 1.0 +MIN_NCC = 0.95 +MAX_LAG = 1.0 +MIN_LAG = 0.15 +MAX_LAG_STD = 0.1 +MAX_LAT_ACCEL = 2.0 +MAX_LAT_ACCEL_DIFF = 0.6 +MIN_LAT_ACCEL_RANGE = 0.5 +MIN_CONFIDENCE = 0.7 +CORR_BORDER_OFFSET = 5 +LAG_CANDIDATE_CORR_THRESHOLD = 0.9 +SMOOTH_K = 5 +SMOOTH_SIGMA = 1.0 + + +def masked_symmetric_moving_average(x: np.ndarray, mask: np.ndarray, k: int, sigma: float) -> np.ndarray: + assert k >= 1 and k % 2 == 1, "k must be positive and odd" + pad = k // 2 + i = np.arange(k) - pad + w = np.exp(-0.5 * (i / sigma) ** 2) + w /= w.sum() + xp = np.pad(x * mask, pad, mode="edge") + mp = np.pad(mask, pad, mode="edge") + num = np.convolve(xp, w, mode="valid") + den = np.convolve(mp, w, mode="valid") + return np.divide(num, den, out=np.full_like(num, np.nan, dtype=np.float64), where=den != 0) + +def masked_normalized_cross_correlation(expected_sig: np.ndarray, actual_sig: np.ndarray, mask: np.ndarray, n: int): + """ + References: + D. Padfield. "Masked FFT registration". In Proc. Computer Vision and + Pattern Recognition, pp. 2918-2925 (2010). + :DOI:`10.1109/CVPR.2010.5540032` + """ + + eps = np.finfo(np.float64).eps + expected_sig = np.asarray(expected_sig, dtype=np.float64) + actual_sig = np.asarray(actual_sig, dtype=np.float64) + + expected_sig[~mask] = 0.0 + actual_sig[~mask] = 0.0 + + rotated_expected_sig = expected_sig[::-1] + rotated_mask = mask[::-1] + + fft = partial(np.fft.fft, n=n) + + actual_sig_fft = fft(actual_sig) + rotated_expected_sig_fft = fft(rotated_expected_sig) + actual_mask_fft = fft(mask.astype(np.float64)) + rotated_mask_fft = fft(rotated_mask.astype(np.float64)) + + number_overlap_masked_samples = np.fft.ifft(rotated_mask_fft * actual_mask_fft).real + number_overlap_masked_samples[:] = np.round(number_overlap_masked_samples) + number_overlap_masked_samples[:] = np.fmax(number_overlap_masked_samples, eps) + masked_correlated_actual_fft = np.fft.ifft(rotated_mask_fft * actual_sig_fft).real + masked_correlated_expected_fft = np.fft.ifft(actual_mask_fft * rotated_expected_sig_fft).real + + numerator = np.fft.ifft(rotated_expected_sig_fft * actual_sig_fft).real + numerator -= masked_correlated_actual_fft * masked_correlated_expected_fft / number_overlap_masked_samples + + actual_squared_fft = fft(actual_sig ** 2) + actual_sig_denom = np.fft.ifft(rotated_mask_fft * actual_squared_fft).real + actual_sig_denom -= masked_correlated_actual_fft ** 2 / number_overlap_masked_samples + actual_sig_denom[:] = np.fmax(actual_sig_denom, 0.0) + + rotated_expected_squared_fft = fft(rotated_expected_sig ** 2) + expected_sig_denom = np.fft.ifft(actual_mask_fft * rotated_expected_squared_fft).real + expected_sig_denom -= masked_correlated_expected_fft ** 2 / number_overlap_masked_samples + expected_sig_denom[:] = np.fmax(expected_sig_denom, 0.0) + + denom = np.sqrt(actual_sig_denom * expected_sig_denom) + + # zero-out samples with very small denominators + tol = 1e3 * eps * np.max(np.abs(denom), keepdims=True) + nonzero_indices = denom > tol + + ncc = np.zeros_like(denom, dtype=np.float64) + ncc[nonzero_indices] = numerator[nonzero_indices] / denom[nonzero_indices] + np.clip(ncc, -1, 1, out=ncc) + + return ncc + + +class Points: + def __init__(self, num_points: int): + self.times = deque[float]([0.0] * num_points, maxlen=num_points) + self.okay = deque[bool]([False] * num_points, maxlen=num_points) + self.desired = deque[float]([0.0] * num_points, maxlen=num_points) + self.actual = deque[float]([0.0] * num_points, maxlen=num_points) + + @property + def num_points(self): + return len(self.desired) + + @property + def num_okay(self): + return np.count_nonzero(self.okay) + + def update(self, t: float, desired: float, actual: float, okay: bool): + self.times.append(t) + self.okay.append(okay) + self.desired.append(desired) + self.actual.append(actual) + + def get(self) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + return np.array(self.times), np.array(self.desired), np.array(self.actual), np.array(self.okay) + + +class BlockAverage: + def __init__(self, num_blocks: int, block_size: int, valid_blocks: int, initial_value: float): + self.num_blocks = num_blocks + self.block_size = block_size + self.block_idx = valid_blocks % num_blocks + self.idx = 0 + + self.values = np.tile(initial_value, (num_blocks, 1)) + self.valid_blocks = valid_blocks + + def update(self, value: float): + self.values[self.block_idx] = (self.idx * self.values[self.block_idx] + value) / (self.idx + 1) + self.idx = (self.idx + 1) % self.block_size + if self.idx == 0: + self.block_idx = (self.block_idx + 1) % self.num_blocks + self.valid_blocks = min(self.valid_blocks + 1, self.num_blocks) + + def get(self) -> tuple[float, float, float, float]: + valid_block_idx = [i for i in range(self.valid_blocks) if i != self.block_idx] + valid_and_current_idx = valid_block_idx + ([self.block_idx] if self.idx > 0 else []) + + if len(valid_block_idx) > 0: + valid_mean = float(np.mean(self.values[valid_block_idx], axis=0).item()) + valid_std = float(np.std(self.values[valid_block_idx], axis=0).item()) + else: + valid_mean, valid_std = float('nan'), float('nan') + + if len(valid_and_current_idx) > 0: + current_mean = float(np.mean(self.values[valid_and_current_idx], axis=0).item()) + current_std = float(np.std(self.values[valid_and_current_idx], axis=0).item()) + else: + current_mean, current_std = float('nan'), float('nan') + + return valid_mean, valid_std, current_mean, current_std + + +class LateralLagEstimator: + inputs = {"carControl", "carState", "controlsState", "liveCalibration", "livePose"} + + def __init__(self, CP: car.CarParams, dt: float, + block_count: int = BLOCK_NUM, min_valid_block_count: int = BLOCK_NUM_NEEDED, block_size: int = BLOCK_SIZE, + window_sec: float = MOVING_WINDOW_SEC, okay_window_sec: float = MIN_OKAY_WINDOW_SEC, min_recovery_buffer_sec: float = MIN_RECOVERY_BUFFER_SEC, + min_vego: float = MIN_VEGO, min_yr: float = MIN_ABS_YAW_RATE, min_ncc: float = MIN_NCC, + max_lat_accel: float = MAX_LAT_ACCEL, max_lat_accel_diff: float = MAX_LAT_ACCEL_DIFF, min_confidence: float = MIN_CONFIDENCE): + self.dt = dt + self.window_sec = window_sec + self.okay_window_sec = okay_window_sec + self.min_recovery_buffer_sec = min_recovery_buffer_sec + self.initial_lag = CP.steerActuatorDelay + 0.2 + self.block_size = block_size + self.block_count = block_count + self.min_valid_block_count = min_valid_block_count + self.min_vego = min_vego + self.min_yr = min_yr + self.min_ncc = min_ncc + self.min_confidence = min_confidence + self.max_lat_accel = max_lat_accel + self.max_lat_accel_diff = max_lat_accel_diff + + self.t = 0.0 + self.lat_active = False + self.steering_pressed = False + self.steering_saturated = False + self.desired_curvature = 0.0 + self.v_ego = 0.0 + self.yaw_rate = 0.0 + self.yaw_rate_std = 0.0 + self.pose_valid = False + + self.last_lat_inactive_t = 0.0 + self.last_steering_pressed_t = 0.0 + self.last_steering_saturated_t = 0.0 + self.last_pose_invalid_t = 0.0 + self.last_estimate_t = 0.0 + + self.calibrator = PoseCalibrator() + + self.reset(self.initial_lag, 0) + + def reset(self, initial_lag: float, valid_blocks: int): + window_len = int(self.window_sec / self.dt) + self.points = Points(window_len) + self.block_avg = BlockAverage(self.block_count, self.block_size, valid_blocks, initial_lag) + + def get_msg(self, valid: bool, debug: bool = False) -> capnp._DynamicStructBuilder: + msg = messaging.new_message('liveDelay') + + msg.valid = valid + + liveDelay = msg.liveDelay + + valid_mean_lag, valid_std, current_mean_lag, current_std = self.block_avg.get() + if self.block_avg.valid_blocks >= self.min_valid_block_count and not np.isnan(valid_mean_lag) and not np.isnan(valid_std): + if valid_std > MAX_LAG_STD: + liveDelay.status = log.LiveDelayData.Status.invalid + else: + liveDelay.status = log.LiveDelayData.Status.estimated + else: + liveDelay.status = log.LiveDelayData.Status.unestimated + + if liveDelay.status == log.LiveDelayData.Status.estimated: + liveDelay.lateralDelay = min(MAX_LAG, max(MIN_LAG, valid_mean_lag)) + else: + liveDelay.lateralDelay = self.initial_lag + + if not np.isnan(current_mean_lag) and not np.isnan(current_std): + liveDelay.lateralDelayEstimate = current_mean_lag + liveDelay.lateralDelayEstimateStd = current_std + else: + liveDelay.lateralDelayEstimate = self.initial_lag + liveDelay.lateralDelayEstimateStd = 0.0 + + liveDelay.validBlocks = self.block_avg.valid_blocks + liveDelay.calPerc = min(100 * (self.block_avg.valid_blocks * self.block_size + self.block_avg.idx) // + (self.min_valid_block_count * self.block_size), 100) + if debug: + liveDelay.points = self.block_avg.values.flatten().tolist() + + return msg + + def handle_log(self, t: float, which: str, msg: capnp._DynamicStructReader): + if which == "carControl": + self.lat_active = msg.latActive + elif which == "carState": + self.steering_pressed = msg.steeringPressed + self.v_ego = msg.vEgo + elif which == "controlsState": + self.steering_saturated = getattr(msg.lateralControlState, msg.lateralControlState.which()).saturated + self.desired_curvature = msg.desiredCurvature + elif which == "liveCalibration": + self.calibrator.feed_live_calib(msg) + elif which == "livePose": + device_pose = Pose.from_live_pose(msg) + calibrated_pose = self.calibrator.build_calibrated_pose(device_pose) + self.yaw_rate = calibrated_pose.angular_velocity.yaw + self.yaw_rate_std = calibrated_pose.angular_velocity.yaw_std + self.pose_valid = msg.angularVelocityDevice.valid and msg.posenetOK and msg.inputsOK + self.t = t + + def points_enough(self): + return self.points.num_points >= int(self.okay_window_sec / self.dt) + + def points_valid(self): + return self.points.num_okay >= int(self.okay_window_sec / self.dt) + + def update_points(self): + la_desired = self.desired_curvature * self.v_ego * self.v_ego + la_actual_pose = self.yaw_rate * self.v_ego + + fast = self.v_ego > self.min_vego + turning = np.abs(self.yaw_rate) >= self.min_yr + sensors_valid = self.pose_valid and np.abs(self.yaw_rate) < MAX_YAW_RATE_SANITY_CHECK and self.yaw_rate_std < MAX_YAW_RATE_SANITY_CHECK + la_valid = np.abs(la_actual_pose) <= self.max_lat_accel and np.abs(la_desired - la_actual_pose) <= self.max_lat_accel_diff + calib_valid = self.calibrator.calib_valid + + if not self.lat_active: + self.last_lat_inactive_t = self.t + if self.steering_pressed: + self.last_steering_pressed_t = self.t + if self.steering_saturated: + self.last_steering_saturated_t = self.t + if not sensors_valid or not la_valid: + self.last_pose_invalid_t = self.t + + has_recovered = all( # wait for recovery after !lat_active, steering_pressed, steering_saturated, !sensors/la_valid + self.t - last_t >= self.min_recovery_buffer_sec + for last_t in [self.last_lat_inactive_t, self.last_steering_pressed_t, self.last_steering_saturated_t, self.last_pose_invalid_t] + ) + okay = self.lat_active and not self.steering_pressed and not self.steering_saturated and \ + fast and turning and has_recovered and calib_valid and sensors_valid and la_valid + + self.points.update(self.t, la_desired, la_actual_pose, okay) + + def update_estimate(self): + if not self.points_enough(): + return + + times, desired, actual, okay = self.points.get() + # check if there are any new valid data points since the last update + is_valid = self.points_valid() and (actual.max() - actual.min() >= MIN_LAT_ACCEL_RANGE) + if self.last_estimate_t != 0 and times[0] <= self.last_estimate_t: + new_values_start_idx = next(-i for i, t in enumerate(reversed(times)) if t <= self.last_estimate_t) + is_valid = is_valid and not (new_values_start_idx == 0 or not np.any(okay[new_values_start_idx:])) + + desired = masked_symmetric_moving_average(desired, okay, SMOOTH_K, SMOOTH_SIGMA) + actual = masked_symmetric_moving_average(actual, okay, SMOOTH_K, SMOOTH_SIGMA) + + delay, corr, confidence = self.actuator_delay(desired, actual, okay, self.dt, MIN_LAG, MAX_LAG) + if corr < self.min_ncc or confidence < self.min_confidence or not is_valid: + return + + self.block_avg.update(delay) + self.last_estimate_t = self.t + + @staticmethod + def actuator_delay(expected_sig: np.ndarray, actual_sig: np.ndarray, mask: np.ndarray, + dt: float, min_lag: float, max_lag: float) -> tuple[float, float, float]: + assert len(expected_sig) == len(actual_sig) + min_lag_samples, max_lag_samples, one_sec_samples = int(round(min_lag / dt)), int(round(max_lag / dt)), int(round(1.0 / dt)) + padded_size = fft_next_good_size(len(expected_sig) + max(max_lag_samples, one_sec_samples)) + + ncc = masked_normalized_cross_correlation(expected_sig, actual_sig, mask, padded_size) + + # only consider lags from ranges: + roi = np.s_[len(expected_sig) - 1 + min_lag_samples: len(expected_sig) - 1 + max_lag_samples] # min_lag - max_lag range + threshold_roi = np.s_[len(expected_sig) - 1: len(expected_sig) - 1 + one_sec_samples] # 0 - 1 second range + confidence_roi = np.s_[threshold_roi.start - CORR_BORDER_OFFSET: threshold_roi.stop + CORR_BORDER_OFFSET] # threshold range +/- border + roi_ncc, confidence_roi_ncc, threshold_roi_ncc = ncc[roi], ncc[confidence_roi], ncc[threshold_roi] + + max_corr_index = np.argmax(roi_ncc) + corr = roi_ncc[max_corr_index] + lag = parabolic_peak_interp(roi_ncc, max_corr_index) * dt + min_lag + + # to estimate lag confidence, gather all high-correlation candidates and see how spread they are + # if e.g. 0.8 and 0.4 are both viable, this is an ambiguous case + ncc_thresh = (threshold_roi_ncc.max() - threshold_roi_ncc.min()) * LAG_CANDIDATE_CORR_THRESHOLD + threshold_roi_ncc.min() + good_lag_candidate_mask = confidence_roi_ncc >= ncc_thresh + good_lag_candidate_edges = np.diff(good_lag_candidate_mask.astype(int), prepend=0, append=0) + starts, ends = np.where(good_lag_candidate_edges == 1)[0], np.where(good_lag_candidate_edges == -1)[0] - 1 + run_idx = np.searchsorted(starts, max_corr_index + CORR_BORDER_OFFSET, side='right') - 1 + width = ends[run_idx] - starts[run_idx] + 1 + confidence = np.clip(1 - width * dt, 0, 1) + + return lag, corr, confidence + + +def retrieve_initial_lag(params: Params, CP: car.CarParams): + last_lag_data = params.get("LiveDelay") + last_carparams_data = params.get("CarParamsPrevRoute") + + if last_lag_data is not None: + try: + with log.Event.from_bytes(last_lag_data) as last_lag_msg, car.CarParams.from_bytes(last_carparams_data) as last_CP: + ld = last_lag_msg.liveDelay + if last_CP.carFingerprint != CP.carFingerprint: + raise Exception("Car model mismatch") + + lag, valid_blocks, status = ld.lateralDelayEstimate, ld.validBlocks, ld.status + assert valid_blocks <= BLOCK_NUM, "Invalid number of valid blocks" + assert status != log.LiveDelayData.Status.invalid, "Lag estimate is invalid" + return lag, valid_blocks + except Exception as e: + cloudlog.error(f"Failed to retrieve initial lag: {e}") + params.remove("LiveDelay") + + return None + + +def main(): + config_realtime_process([0, 1, 2, 3], 5) + + DEBUG = bool(int(os.getenv("DEBUG", "0"))) + + pm = messaging.PubMaster(['liveDelay']) + sm = messaging.SubMaster(['livePose', 'liveCalibration', 'carState', 'controlsState', 'carControl'], poll='livePose') + + params = Params() + CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + + lag_learner = LateralLagEstimator(CP, 1. / SERVICE_LIST['livePose'].frequency) + if (initial_lag_params := retrieve_initial_lag(params, CP)) is not None: + lag, valid_blocks = initial_lag_params + lag_learner.reset(lag, valid_blocks) + + while True: + sm.update() + if sm.all_checks(): + for which in sorted(sm.updated.keys(), key=lambda x: sm.logMonoTime[x]): + if sm.updated[which]: + t = sm.logMonoTime[which] * 1e-9 + lag_learner.handle_log(t, which, sm[which]) + lag_learner.update_points() + + # 4Hz driven by livePose + if sm.frame % 5 == 0: + lag_learner.update_estimate() + lag_msg = lag_learner.get_msg(sm.all_checks(), DEBUG) + lag_msg_dat = lag_msg.to_bytes() + pm.send('liveDelay', lag_msg_dat) + + if sm.frame % 1200 == 0: # cache every 60 seconds + params.put("LiveDelay", lag_msg_dat) diff --git a/selfdrive/locationd/locationd.cc b/selfdrive/locationd/locationd.cc deleted file mode 100644 index e1e5cd1bb2ccb1..00000000000000 --- a/selfdrive/locationd/locationd.cc +++ /dev/null @@ -1,716 +0,0 @@ -#include "selfdrive/locationd/locationd.h" - -#include -#include - -#include -#include -#include - -using namespace EKFS; -using namespace Eigen; - -ExitHandler do_exit; -const double ACCEL_SANITY_CHECK = 100.0; // m/s^2 -const double ROTATION_SANITY_CHECK = 10.0; // rad/s -const double TRANS_SANITY_CHECK = 200.0; // m/s -const double CALIB_RPY_SANITY_CHECK = 0.5; // rad (+- 30 deg) -const double ALTITUDE_SANITY_CHECK = 10000; // m -const double MIN_STD_SANITY_CHECK = 1e-5; // m or rad -const double SANE_GPS_UNCERTAINTY = 1500.0; // m -const double INPUT_INVALID_THRESHOLD = 0.5; // same as reset tracker -const double RESET_TRACKER_DECAY = 0.99995; -const double DECAY = 0.9993; // ~10 secs to resume after a bad input -const double MAX_FILTER_REWIND_TIME = 0.8; // s -const double YAWRATE_CROSS_ERR_CHECK_FACTOR = 30; - -// TODO: GPS sensor time offsets are empirically calculated -// They should be replaced with synced time from a real clock -const double GPS_QUECTEL_SENSOR_TIME_OFFSET = 0.630; // s -const double GPS_UBLOX_SENSOR_TIME_OFFSET = 0.095; // s -const float GPS_POS_STD_THRESHOLD = 50.0; -const float GPS_VEL_STD_THRESHOLD = 5.0; -const float GPS_POS_ERROR_RESET_THRESHOLD = 300.0; -const float GPS_POS_STD_RESET_THRESHOLD = 2.0; -const float GPS_VEL_STD_RESET_THRESHOLD = 0.5; -const float GPS_ORIENTATION_ERROR_RESET_THRESHOLD = 1.0; -const int GPS_ORIENTATION_ERROR_RESET_CNT = 3; - -const bool DEBUG = getenv("DEBUG") != nullptr && std::string(getenv("DEBUG")) != "0"; - -template -static Vector floatlist2vector(const ListType& floatlist) { - Vector res(floatlist.size()); - for (int i = 0; i < floatlist.size(); i++) { - res[i] = floatlist[i]; - } - return res; -} - -template -static VectorXd float64list2vector(const ListType& floatlist) { - return floatlist2vector(floatlist); -} - -template -static VectorXf float32list2vector(const ListType& floatlist) { - return floatlist2vector(floatlist); -} - -static Vector4d quat2vector(const Quaterniond& quat) { - return Vector4d(quat.w(), quat.x(), quat.y(), quat.z()); -} - -static Quaterniond vector2quat(const VectorXd& vec) { - return Quaterniond(vec(0), vec(1), vec(2), vec(3)); -} - -static void init_xyz_measurement(cereal::LivePose::XYZMeasurement::Builder meas, const VectorXd& val, const VectorXd& std, bool valid) { - meas.setX(val[0]); meas.setY(val[1]); meas.setZ(val[2]); - meas.setXStd(std[0]); meas.setYStd(std[1]); meas.setZStd(std[2]); - meas.setValid(valid); -} - -static MatrixXdr rotate_cov(const MatrixXdr& rot_matrix, const MatrixXdr& cov_in) { - // To rotate a covariance matrix, the cov matrix needs to multiplied left and right by the transform matrix - return ((rot_matrix * cov_in) * rot_matrix.transpose()); -} - -static VectorXd rotate_std(const MatrixXdr& rot_matrix, const VectorXd& std_in) { - // Stds cannot be rotated like values, only covariances can be rotated - return rotate_cov(rot_matrix, std_in.array().square().matrix().asDiagonal()).diagonal().array().sqrt(); -} - -Localizer::Localizer(LocalizerGnssSource gnss_source) { - this->kf = std::make_unique(); - this->reset_kalman(); - - this->calib = Vector3d(0.0, 0.0, 0.0); - this->device_from_calib = MatrixXdr::Identity(3, 3); - this->calib_from_device = MatrixXdr::Identity(3, 3); - - for (int i = 0; i < POSENET_STD_HIST_HALF * 2; i++) { - this->posenet_stds.push_back(10.0); - } - - VectorXd ecef_pos = this->kf->get_x().segment(STATE_ECEF_POS_START); - this->converter = std::make_unique((ECEF) { .x = ecef_pos[0], .y = ecef_pos[1], .z = ecef_pos[2] }); - this->configure_gnss_source(gnss_source); -} - -void Localizer::build_live_pose(cereal::LivePose::Builder& fix) { - VectorXd predicted_state = this->kf->get_x(); - MatrixXdr predicted_cov = this->kf->get_P(); - VectorXd predicted_std = predicted_cov.diagonal().array().sqrt(); - - VectorXd fix_ecef = predicted_state.segment(STATE_ECEF_POS_START); - ECEF fix_ecef_ecef = { .x = fix_ecef(0), .y = fix_ecef(1), .z = fix_ecef(2) }; - VectorXd fix_ecef_std = predicted_std.segment(STATE_ECEF_POS_ERR_START); - VectorXd vel_ecef = predicted_state.segment(STATE_ECEF_VELOCITY_START); - VectorXd vel_ecef_std = predicted_std.segment(STATE_ECEF_VELOCITY_ERR_START); - VectorXd orientation_ecef = quat2euler(vector2quat(predicted_state.segment(STATE_ECEF_ORIENTATION_START))); - VectorXd orientation_ecef_std = predicted_std.segment(STATE_ECEF_ORIENTATION_ERR_START); - MatrixXdr orientation_ecef_cov = predicted_cov.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START); - MatrixXdr device_from_ecef = euler2rot(orientation_ecef).transpose(); - - MatrixXdr vel_angular_cov = predicted_cov.block(STATE_ANGULAR_VELOCITY_ERR_START, STATE_ANGULAR_VELOCITY_ERR_START); - - VectorXd vel_device = device_from_ecef * vel_ecef; - VectorXd device_from_ecef_eul = quat2euler(vector2quat(predicted_state.segment(STATE_ECEF_ORIENTATION_START))).transpose(); - MatrixXdr condensed_cov(STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN); - condensed_cov.topLeftCorner() = - predicted_cov.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START); - condensed_cov.topRightCorner() = - predicted_cov.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_VELOCITY_ERR_START); - condensed_cov.bottomRightCorner() = - predicted_cov.block(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_VELOCITY_ERR_START); - condensed_cov.bottomLeftCorner() = - predicted_cov.block(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_ORIENTATION_ERR_START); - VectorXd H_input(device_from_ecef_eul.size() + vel_ecef.size()); - H_input << device_from_ecef_eul, vel_ecef; - MatrixXdr HH = this->kf->H(H_input); - MatrixXdr vel_device_cov = (HH * condensed_cov) * HH.transpose(); - VectorXd vel_device_std = vel_device_cov.diagonal().array().sqrt(); - - VectorXd orientation_ned = ned_euler_from_ecef(fix_ecef_ecef, orientation_ecef); - VectorXd orientation_ned_std = rotate_cov(this->converter->ecef2ned_matrix, orientation_ecef_cov).diagonal().array().sqrt(); - VectorXd nextfix_ecef = fix_ecef + vel_ecef; - VectorXd ned_vel = this->converter->ecef2ned((ECEF) { .x = nextfix_ecef(0), .y = nextfix_ecef(1), .z = nextfix_ecef(2) }).to_vector() - converter->ecef2ned(fix_ecef_ecef).to_vector(); - - VectorXd accDevice = predicted_state.segment(STATE_ACCELERATION_START); - VectorXd accDeviceErr = predicted_std.segment(STATE_ACCELERATION_ERR_START); - - VectorXd angVelocityDevice = predicted_state.segment(STATE_ANGULAR_VELOCITY_START); - VectorXd angVelocityDeviceErr = predicted_std.segment(STATE_ANGULAR_VELOCITY_ERR_START); - - // write measurements to msg - init_xyz_measurement(fix.initVelocityDevice(), vel_device, vel_device_std, true); - init_xyz_measurement(fix.initAccelerationDevice(), accDevice, accDeviceErr, true); - init_xyz_measurement(fix.initOrientationNED(), orientation_ned, orientation_ned_std, this->gps_mode); - init_xyz_measurement(fix.initAngularVelocityDevice(), angVelocityDevice, angVelocityDeviceErr, true); - if (DEBUG) { - cereal::LivePose::FilterState::Builder filter_state_builder = fix.initFilterState(); - filter_state_builder.setValue(kj::arrayPtr(predicted_state.data(), predicted_state.size())); - filter_state_builder.setStd(kj::arrayPtr(predicted_std.data(), predicted_std.size())); - filter_state_builder.setValid(true); - } - - double old_mean = 0.0, new_mean = 0.0; - int i = 0; - for (double x : this->posenet_stds) { - if (i < POSENET_STD_HIST_HALF) { - old_mean += x; - } else { - new_mean += x; - } - i++; - } - old_mean /= POSENET_STD_HIST_HALF; - new_mean /= POSENET_STD_HIST_HALF; - // experimentally found these values, no false positives in 20k minutes of driving - bool std_spike = (new_mean / old_mean > 4.0 && new_mean > 7.0); - fix.setPosenetOK(!(std_spike && this->car_speed > 5.0)); -} - -VectorXd Localizer::get_position_geodetic() { - VectorXd fix_ecef = this->kf->get_x().segment(STATE_ECEF_POS_START); - ECEF fix_ecef_ecef = { .x = fix_ecef(0), .y = fix_ecef(1), .z = fix_ecef(2) }; - Geodetic fix_pos_geo = ecef2geodetic(fix_ecef_ecef); - return Vector3d(fix_pos_geo.lat, fix_pos_geo.lon, fix_pos_geo.alt); -} - -VectorXd Localizer::get_state() { - return this->kf->get_x(); -} - -VectorXd Localizer::get_stdev() { - return this->kf->get_P().diagonal().array().sqrt(); -} - -bool Localizer::are_inputs_ok() { - return this->critical_services_valid(this->observation_values_invalid) && !this->observation_timings_invalid; -} - -void Localizer::observation_timings_invalid_reset(){ - this->observation_timings_invalid = false; -} - -void Localizer::handle_sensor(double current_time, const cereal::SensorEventData::Reader& log) { - // TODO does not yet account for double sensor readings in the log - - // Ignore empty readings (e.g. in case the magnetometer had no data ready) - if (log.getTimestamp() == 0) { - return; - } - - double sensor_time = 1e-9 * log.getTimestamp(); - - // sensor time and log time should be close - if (std::abs(current_time - sensor_time) > 0.1) { - LOGE("Sensor reading ignored, sensor timestamp more than 100ms off from log time"); - this->observation_timings_invalid = true; - return; - } else if (!this->is_timestamp_valid(sensor_time)) { - this->observation_timings_invalid = true; - return; - } - - // TODO: handle messages from two IMUs at the same time - if (log.getSource() == cereal::SensorEventData::SensorSource::BMX055) { - return; - } - - // Gyro Uncalibrated - if (log.getSensor() == SENSOR_GYRO_UNCALIBRATED && log.getType() == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED) { - auto v = log.getGyroUncalibrated().getV(); - auto meas = Vector3d(-v[2], -v[1], -v[0]); - - VectorXd gyro_bias = this->kf->get_x().segment(STATE_GYRO_BIAS_START); - float gyro_camodo_yawrate_err = std::abs((meas[2] - gyro_bias[2]) - this->camodo_yawrate_distribution[0]); - float gyro_camodo_yawrate_err_threshold = YAWRATE_CROSS_ERR_CHECK_FACTOR * this->camodo_yawrate_distribution[1]; - bool gyro_valid = gyro_camodo_yawrate_err < gyro_camodo_yawrate_err_threshold; - - if ((meas.norm() < ROTATION_SANITY_CHECK) && gyro_valid) { - this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_GYRO, { meas }); - this->observation_values_invalid["gyroscope"] *= DECAY; - } else { - this->observation_values_invalid["gyroscope"] += 1.0; - } - } - - // Accelerometer - if (log.getSensor() == SENSOR_ACCELEROMETER && log.getType() == SENSOR_TYPE_ACCELEROMETER) { - auto v = log.getAcceleration().getV(); - - // TODO: reduce false positives and re-enable this check - // check if device fell, estimate 10 for g - // 40m/s**2 is a good filter for falling detection, no false positives in 20k minutes of driving - // this->device_fell |= (float64list2vector(v) - Vector3d(10.0, 0.0, 0.0)).norm() > 40.0; - - auto meas = Vector3d(-v[2], -v[1], -v[0]); - if (meas.norm() < ACCEL_SANITY_CHECK) { - this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_ACCEL, { meas }); - this->observation_values_invalid["accelerometer"] *= DECAY; - } else { - this->observation_values_invalid["accelerometer"] += 1.0; - } - } -} - -void Localizer::input_fake_gps_observations(double current_time) { - // This is done to make sure that the error estimate of the position does not blow up - // when the filter is in no-gps mode - // Steps : first predict -> observe current obs with reasonable STD - this->kf->predict(current_time); - - VectorXd current_x = this->kf->get_x(); - VectorXd ecef_pos = current_x.segment(STATE_ECEF_POS_START); - VectorXd ecef_vel = current_x.segment(STATE_ECEF_VELOCITY_START); - const MatrixXdr &ecef_pos_R = this->kf->get_fake_gps_pos_cov(); - const MatrixXdr &ecef_vel_R = this->kf->get_fake_gps_vel_cov(); - - this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); - this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); -} - -void Localizer::handle_gps(double current_time, const cereal::GpsLocationData::Reader& log, const double sensor_time_offset) { - bool gps_unreasonable = (Vector2d(log.getHorizontalAccuracy(), log.getVerticalAccuracy()).norm() >= SANE_GPS_UNCERTAINTY); - bool gps_accuracy_insane = ((log.getVerticalAccuracy() <= 0) || (log.getSpeedAccuracy() <= 0) || (log.getBearingAccuracyDeg() <= 0)); - bool gps_lat_lng_alt_insane = ((std::abs(log.getLatitude()) > 90) || (std::abs(log.getLongitude()) > 180) || (std::abs(log.getAltitude()) > ALTITUDE_SANITY_CHECK)); - bool gps_vel_insane = (float64list2vector(log.getVNED()).norm() > TRANS_SANITY_CHECK); - - if (!log.getHasFix() || gps_unreasonable || gps_accuracy_insane || gps_lat_lng_alt_insane || gps_vel_insane) { - //this->gps_valid = false; - this->determine_gps_mode(current_time); - return; - } - - double sensor_time = current_time - sensor_time_offset; - - // Process message - //this->gps_valid = true; - this->gps_mode = true; - Geodetic geodetic = { log.getLatitude(), log.getLongitude(), log.getAltitude() }; - this->converter = std::make_unique(geodetic); - - VectorXd ecef_pos = this->converter->ned2ecef({ 0.0, 0.0, 0.0 }).to_vector(); - VectorXd ecef_vel = this->converter->ned2ecef({ log.getVNED()[0], log.getVNED()[1], log.getVNED()[2] }).to_vector() - ecef_pos; - float ecef_pos_std = std::sqrt(this->gps_variance_factor * std::pow(log.getHorizontalAccuracy(), 2) + this->gps_vertical_variance_factor * std::pow(log.getVerticalAccuracy(), 2)); - MatrixXdr ecef_pos_R = Vector3d::Constant(std::pow(this->gps_std_factor * ecef_pos_std, 2)).asDiagonal(); - MatrixXdr ecef_vel_R = Vector3d::Constant(std::pow(this->gps_std_factor * log.getSpeedAccuracy(), 2)).asDiagonal(); - - this->unix_timestamp_millis = log.getUnixTimestampMillis(); - double gps_est_error = (this->kf->get_x().segment(STATE_ECEF_POS_START) - ecef_pos).norm(); - - VectorXd orientation_ecef = quat2euler(vector2quat(this->kf->get_x().segment(STATE_ECEF_ORIENTATION_START))); - VectorXd orientation_ned = ned_euler_from_ecef({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ecef); - VectorXd orientation_ned_gps = Vector3d(0.0, 0.0, DEG2RAD(log.getBearingDeg())); - VectorXd orientation_error = (orientation_ned - orientation_ned_gps).array() - M_PI; - for (int i = 0; i < orientation_error.size(); i++) { - orientation_error(i) = std::fmod(orientation_error(i), 2.0 * M_PI); - if (orientation_error(i) < 0.0) { - orientation_error(i) += 2.0 * M_PI; - } - orientation_error(i) -= M_PI; - } - VectorXd initial_pose_ecef_quat = quat2vector(euler2quat(ecef_euler_from_ned({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ned_gps))); - - if (ecef_vel.norm() > 5.0 && orientation_error.norm() > 1.0) { - LOGE("Locationd vs ubloxLocation orientation difference too large, kalman reset"); - this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); - this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_ORIENTATION_FROM_GPS, { initial_pose_ecef_quat }); - } else if (gps_est_error > 100.0) { - LOGE("Locationd vs ubloxLocation position difference too large, kalman reset"); - this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); - } - - this->last_gps_msg = sensor_time; - this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); - this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); -} - -void Localizer::handle_gnss(double current_time, const cereal::GnssMeasurements::Reader& log) { - - if (!log.getPositionECEF().getValid() || !log.getVelocityECEF().getValid()) { - this->determine_gps_mode(current_time); - return; - } - - double sensor_time = log.getMeasTime() * 1e-9; - sensor_time -= this->gps_time_offset; - - auto ecef_pos_v = log.getPositionECEF().getValue(); - VectorXd ecef_pos = Vector3d(ecef_pos_v[0], ecef_pos_v[1], ecef_pos_v[2]); - - // indexed at 0 cause all std values are the same MAE - auto ecef_pos_std = log.getPositionECEF().getStd()[0]; - MatrixXdr ecef_pos_R = Vector3d::Constant(pow(this->gps_std_factor*ecef_pos_std, 2)).asDiagonal(); - - auto ecef_vel_v = log.getVelocityECEF().getValue(); - VectorXd ecef_vel = Vector3d(ecef_vel_v[0], ecef_vel_v[1], ecef_vel_v[2]); - - // indexed at 0 cause all std values are the same MAE - auto ecef_vel_std = log.getVelocityECEF().getStd()[0]; - MatrixXdr ecef_vel_R = Vector3d::Constant(pow(this->gps_std_factor*ecef_vel_std, 2)).asDiagonal(); - - double gps_est_error = (this->kf->get_x().segment(STATE_ECEF_POS_START) - ecef_pos).norm(); - - VectorXd orientation_ecef = quat2euler(vector2quat(this->kf->get_x().segment(STATE_ECEF_ORIENTATION_START))); - VectorXd orientation_ned = ned_euler_from_ecef({ ecef_pos[0], ecef_pos[1], ecef_pos[2] }, orientation_ecef); - - LocalCoord convs((ECEF){ .x = ecef_pos[0], .y = ecef_pos[1], .z = ecef_pos[2] }); - ECEF next_ecef = {.x = ecef_pos[0] + ecef_vel[0], .y = ecef_pos[1] + ecef_vel[1], .z = ecef_pos[2] + ecef_vel[2]}; - VectorXd ned_vel = convs.ecef2ned(next_ecef).to_vector(); - double bearing_rad = atan2(ned_vel[1], ned_vel[0]); - - VectorXd orientation_ned_gps = Vector3d(0.0, 0.0, bearing_rad); - VectorXd orientation_error = (orientation_ned - orientation_ned_gps).array() - M_PI; - for (int i = 0; i < orientation_error.size(); i++) { - orientation_error(i) = std::fmod(orientation_error(i), 2.0 * M_PI); - if (orientation_error(i) < 0.0) { - orientation_error(i) += 2.0 * M_PI; - } - orientation_error(i) -= M_PI; - } - VectorXd initial_pose_ecef_quat = quat2vector(euler2quat(ecef_euler_from_ned({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ned_gps))); - - if (ecef_pos_std > GPS_POS_STD_THRESHOLD || ecef_vel_std > GPS_VEL_STD_THRESHOLD) { - this->determine_gps_mode(current_time); - return; - } - - // prevent jumping gnss measurements (covered lots, standstill...) - bool orientation_reset = ecef_vel_std < GPS_VEL_STD_RESET_THRESHOLD; - orientation_reset &= orientation_error.norm() > GPS_ORIENTATION_ERROR_RESET_THRESHOLD; - orientation_reset &= !this->standstill; - if (orientation_reset) { - this->orientation_reset_count++; - } else { - this->orientation_reset_count = 0; - } - - if ((gps_est_error > GPS_POS_ERROR_RESET_THRESHOLD && ecef_pos_std < GPS_POS_STD_RESET_THRESHOLD) || this->last_gps_msg == 0) { - // always reset on first gps message and if the location is off but the accuracy is high - LOGE("Locationd vs gnssMeasurement position difference too large, kalman reset"); - this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); - } else if (orientation_reset_count > GPS_ORIENTATION_ERROR_RESET_CNT) { - LOGE("Locationd vs gnssMeasurement orientation difference too large, kalman reset"); - this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); - this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_ORIENTATION_FROM_GPS, { initial_pose_ecef_quat }); - this->orientation_reset_count = 0; - } - - this->gps_mode = true; - this->last_gps_msg = sensor_time; - this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); - this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); -} - -void Localizer::handle_car_state(double current_time, const cereal::CarState::Reader& log) { - this->car_speed = std::abs(log.getVEgo()); - this->standstill = log.getStandstill(); - if (this->standstill) { - this->kf->predict_and_observe(current_time, OBSERVATION_NO_ROT, { Vector3d(0.0, 0.0, 0.0) }); - this->kf->predict_and_observe(current_time, OBSERVATION_NO_ACCEL, { Vector3d(0.0, 0.0, 0.0) }); - } -} - -void Localizer::handle_cam_odo(double current_time, const cereal::CameraOdometry::Reader& log) { - VectorXd rot_device = this->device_from_calib * float64list2vector(log.getRot()); - VectorXd trans_device = this->device_from_calib * float64list2vector(log.getTrans()); - - if (!this->is_timestamp_valid(current_time)) { - this->observation_timings_invalid = true; - return; - } - - if ((rot_device.norm() > ROTATION_SANITY_CHECK) || (trans_device.norm() > TRANS_SANITY_CHECK)) { - this->observation_values_invalid["cameraOdometry"] += 1.0; - return; - } - - VectorXd rot_calib_std = float64list2vector(log.getRotStd()); - VectorXd trans_calib_std = float64list2vector(log.getTransStd()); - - if ((rot_calib_std.minCoeff() <= MIN_STD_SANITY_CHECK) || (trans_calib_std.minCoeff() <= MIN_STD_SANITY_CHECK)) { - this->observation_values_invalid["cameraOdometry"] += 1.0; - return; - } - - if ((rot_calib_std.norm() > 10 * ROTATION_SANITY_CHECK) || (trans_calib_std.norm() > 10 * TRANS_SANITY_CHECK)) { - this->observation_values_invalid["cameraOdometry"] += 1.0; - return; - } - - this->posenet_stds.pop_front(); - this->posenet_stds.push_back(trans_calib_std[0]); - - // Multiply by 10 to avoid to high certainty in kalman filter because of temporally correlated noise - trans_calib_std *= 10.0; - rot_calib_std *= 10.0; - MatrixXdr rot_device_cov = rotate_std(this->device_from_calib, rot_calib_std).array().square().matrix().asDiagonal(); - MatrixXdr trans_device_cov = rotate_std(this->device_from_calib, trans_calib_std).array().square().matrix().asDiagonal(); - this->kf->predict_and_observe(current_time, OBSERVATION_CAMERA_ODO_ROTATION, - { rot_device }, { rot_device_cov }); - this->kf->predict_and_observe(current_time, OBSERVATION_CAMERA_ODO_TRANSLATION, - { trans_device }, { trans_device_cov }); - this->observation_values_invalid["cameraOdometry"] *= DECAY; - this->camodo_yawrate_distribution = Vector2d(rot_device[2], rotate_std(this->device_from_calib, rot_calib_std)[2]); -} - -void Localizer::handle_live_calib(double current_time, const cereal::LiveCalibrationData::Reader& log) { - if (!this->is_timestamp_valid(current_time)) { - this->observation_timings_invalid = true; - return; - } - - if (log.getRpyCalib().size() > 0) { - auto live_calib = float64list2vector(log.getRpyCalib()); - if ((live_calib.minCoeff() < -CALIB_RPY_SANITY_CHECK) || (live_calib.maxCoeff() > CALIB_RPY_SANITY_CHECK)) { - this->observation_values_invalid["liveCalibration"] += 1.0; - return; - } - - this->calib = live_calib; - this->device_from_calib = euler2rot(this->calib); - this->calib_from_device = this->device_from_calib.transpose(); - this->calibrated = log.getCalStatus() == cereal::LiveCalibrationData::Status::CALIBRATED; - this->observation_values_invalid["liveCalibration"] *= DECAY; - } -} - -void Localizer::reset_kalman(double current_time) { - const VectorXd &init_x = this->kf->get_initial_x(); - const MatrixXdr &init_P = this->kf->get_initial_P(); - this->reset_kalman(current_time, init_x, init_P); -} - -void Localizer::finite_check(double current_time) { - bool all_finite = this->kf->get_x().array().isFinite().all() or this->kf->get_P().array().isFinite().all(); - if (!all_finite) { - LOGE("Non-finite values detected, kalman reset"); - this->reset_kalman(current_time); - } -} - -void Localizer::time_check(double current_time) { - if (std::isnan(this->last_reset_time)) { - this->last_reset_time = current_time; - } - if (std::isnan(this->first_valid_log_time)) { - this->first_valid_log_time = current_time; - } - double filter_time = this->kf->get_filter_time(); - bool big_time_gap = !std::isnan(filter_time) && (current_time - filter_time > 10); - if (big_time_gap) { - LOGE("Time gap of over 10s detected, kalman reset"); - this->reset_kalman(current_time); - } -} - -void Localizer::update_reset_tracker() { - // reset tracker is tuned to trigger when over 1reset/10s over 2min period - if (this->is_gps_ok()) { - this->reset_tracker *= RESET_TRACKER_DECAY; - } else { - this->reset_tracker = 0.0; - } -} - -void Localizer::reset_kalman(double current_time, const VectorXd &init_orient, const VectorXd &init_pos, const VectorXd &init_vel, const MatrixXdr &init_pos_R, const MatrixXdr &init_vel_R) { - // too nonlinear to init on completely wrong - VectorXd current_x = this->kf->get_x(); - MatrixXdr current_P = this->kf->get_P(); - MatrixXdr init_P = this->kf->get_initial_P(); - const MatrixXdr &reset_orientation_P = this->kf->get_reset_orientation_P(); - int non_ecef_state_err_len = init_P.rows() - (STATE_ECEF_POS_ERR_LEN + STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN); - - current_x.segment(STATE_ECEF_ORIENTATION_START) = init_orient; - current_x.segment(STATE_ECEF_VELOCITY_START) = init_vel; - current_x.segment(STATE_ECEF_POS_START) = init_pos; - - init_P.block(STATE_ECEF_POS_ERR_START, STATE_ECEF_POS_ERR_START).diagonal() = init_pos_R.diagonal(); - init_P.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START).diagonal() = reset_orientation_P.diagonal(); - init_P.block(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_VELOCITY_ERR_START).diagonal() = init_vel_R.diagonal(); - init_P.block(STATE_ANGULAR_VELOCITY_ERR_START, STATE_ANGULAR_VELOCITY_ERR_START, non_ecef_state_err_len, non_ecef_state_err_len).diagonal() = current_P.block(STATE_ANGULAR_VELOCITY_ERR_START, - STATE_ANGULAR_VELOCITY_ERR_START, non_ecef_state_err_len, non_ecef_state_err_len).diagonal(); - - this->reset_kalman(current_time, current_x, init_P); -} - -void Localizer::reset_kalman(double current_time, const VectorXd &init_x, const MatrixXdr &init_P) { - this->kf->init_state(init_x, init_P, current_time); - this->last_reset_time = current_time; - this->reset_tracker += 1.0; -} - -void Localizer::handle_msg_bytes(const char *data, const size_t size) { - AlignedBuffer aligned_buf; - - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(data, size)); - cereal::Event::Reader event = cmsg.getRoot(); - - this->handle_msg(event); -} - -void Localizer::handle_msg(const cereal::Event::Reader& log) { - double t = log.getLogMonoTime() * 1e-9; - this->time_check(t); - if (log.isAccelerometer()) { - this->handle_sensor(t, log.getAccelerometer()); - } else if (log.isGyroscope()) { - this->handle_sensor(t, log.getGyroscope()); - } else if (log.isGpsLocation()) { - this->handle_gps(t, log.getGpsLocation(), GPS_QUECTEL_SENSOR_TIME_OFFSET); - } else if (log.isGpsLocationExternal()) { - this->handle_gps(t, log.getGpsLocationExternal(), GPS_UBLOX_SENSOR_TIME_OFFSET); - //} else if (log.isGnssMeasurements()) { - // this->handle_gnss(t, log.getGnssMeasurements()); - } else if (log.isCarState()) { - this->handle_car_state(t, log.getCarState()); - } else if (log.isCameraOdometry()) { - this->handle_cam_odo(t, log.getCameraOdometry()); - } else if (log.isLiveCalibration()) { - this->handle_live_calib(t, log.getLiveCalibration()); - } - this->finite_check(); - this->update_reset_tracker(); -} - -void Localizer::build_pose_message( - MessageBuilder& msg_builder, bool inputsOK, bool sensorsOK, bool msgValid) { - cereal::Event::Builder evt = msg_builder.initEvent(); - evt.setValid(msgValid); - cereal::LivePose::Builder livePose = evt.initLivePose(); - this->build_live_pose(livePose); - livePose.setSensorsOK(sensorsOK); - livePose.setInputsOK(inputsOK); -} - -bool Localizer::is_gps_ok() { - return (this->kf->get_filter_time() - this->last_gps_msg) < 2.0; -} - -bool Localizer::critical_services_valid(const std::map &critical_services) { - for (auto &kv : critical_services){ - if (kv.second >= INPUT_INVALID_THRESHOLD){ - return false; - } - } - return true; -} - -bool Localizer::is_timestamp_valid(double current_time) { - double filter_time = this->kf->get_filter_time(); - if (!std::isnan(filter_time) && ((filter_time - current_time) > MAX_FILTER_REWIND_TIME)) { - LOGE("Observation timestamp is older than the max rewind threshold of the filter"); - return false; - } - return true; -} - -void Localizer::determine_gps_mode(double current_time) { - // 1. If the pos_std is greater than what's not acceptable and localizer is in gps-mode, reset to no-gps-mode - // 2. If the pos_std is greater than what's not acceptable and localizer is in no-gps-mode, fake obs - // 3. If the pos_std is smaller than what's not acceptable, let gps-mode be whatever it is - VectorXd current_pos_std = this->kf->get_P().block(STATE_ECEF_POS_ERR_START, STATE_ECEF_POS_ERR_START).diagonal().array().sqrt(); - if (current_pos_std.norm() > SANE_GPS_UNCERTAINTY){ - if (this->gps_mode){ - this->gps_mode = false; - this->reset_kalman(current_time); - } else { - this->input_fake_gps_observations(current_time); - } - } -} - -void Localizer::configure_gnss_source(const LocalizerGnssSource &source) { - this->gnss_source = source; - if (source == LocalizerGnssSource::UBLOX) { - this->gps_std_factor = 10.0; - this->gps_variance_factor = 1.0; - this->gps_vertical_variance_factor = 1.0; - this->gps_time_offset = GPS_UBLOX_SENSOR_TIME_OFFSET; - } else { - this->gps_std_factor = 2.0; - this->gps_variance_factor = 0.0; - this->gps_vertical_variance_factor = 3.0; - this->gps_time_offset = GPS_QUECTEL_SENSOR_TIME_OFFSET; - } -} - -int Localizer::locationd_thread() { - Params params; - LocalizerGnssSource source; - const char* gps_location_socket; - if (params.getBool("UbloxAvailable")) { - source = LocalizerGnssSource::UBLOX; - gps_location_socket = "gpsLocationExternal"; - } else { - source = LocalizerGnssSource::QCOM; - gps_location_socket = "gpsLocation"; - } - - this->configure_gnss_source(source); - const std::initializer_list service_list = {gps_location_socket, "cameraOdometry", "liveCalibration", - "carState", "accelerometer", "gyroscope"}; - - SubMaster sm(service_list, {}, nullptr, {gps_location_socket}); - PubMaster pm({"livePose"}); - - uint64_t cnt = 0; - bool filterInitialized = false; - const std::vector critical_input_services = {"cameraOdometry", "liveCalibration", "accelerometer", "gyroscope"}; - for (std::string service : critical_input_services) { - this->observation_values_invalid.insert({service, 0.0}); - } - - while (!do_exit) { - sm.update(); - if (filterInitialized){ - this->observation_timings_invalid_reset(); - for (const char* service : service_list) { - if (sm.updated(service) && sm.valid(service)){ - const cereal::Event::Reader log = sm[service]; - this->handle_msg(log); - } - } - } else { - filterInitialized = sm.allAliveAndValid(); - } - - const char* trigger_msg = "cameraOdometry"; - if (sm.updated(trigger_msg)) { - bool inputsOK = sm.allValid() && this->are_inputs_ok(); - bool gpsOK = this->is_gps_ok(); - bool sensorsOK = sm.allAliveAndValid({"accelerometer", "gyroscope"}); - - // Log time to first fix - if (gpsOK && std::isnan(this->ttff) && !std::isnan(this->first_valid_log_time)) { - this->ttff = std::max(1e-3, (sm[trigger_msg].getLogMonoTime() * 1e-9) - this->first_valid_log_time); - } - - MessageBuilder pose_msg_builder; - this->build_pose_message(pose_msg_builder, inputsOK, sensorsOK, filterInitialized); - - kj::ArrayPtr pose_bytes = pose_msg_builder.toBytes(); - pm.send("livePose", pose_bytes.begin(), pose_bytes.size()); - - if (cnt % 1200 == 0 && gpsOK) { // once a minute - VectorXd posGeo = this->get_position_geodetic(); - std::string lastGPSPosJSON = util::string_format( - "{\"latitude\": %.15f, \"longitude\": %.15f, \"altitude\": %.15f}", posGeo(0), posGeo(1), posGeo(2)); - params.putNonBlocking("LastGPSPosition", lastGPSPosJSON); - } - cnt++; - } - } - return 0; -} - -int main() { - util::set_realtime_priority(5); - - Localizer localizer; - return localizer.locationd_thread(); -} diff --git a/selfdrive/locationd/locationd.h b/selfdrive/locationd/locationd.h deleted file mode 100644 index f59b7d4bda60f3..00000000000000 --- a/selfdrive/locationd/locationd.h +++ /dev/null @@ -1,99 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "common/transformations/coordinates.hpp" -#include "common/transformations/orientation.hpp" -#include "common/params.h" -#include "common/swaglog.h" -#include "common/timing.h" -#include "common/util.h" - -#include "system/sensord/sensors/constants.h" -#define VISION_DECIMATION 2 -#define SENSOR_DECIMATION 10 -#include "selfdrive/locationd/models/live_kf.h" - -#define POSENET_STD_HIST_HALF 20 - -enum LocalizerGnssSource { - UBLOX, QCOM -}; - -class Localizer { -public: - Localizer(LocalizerGnssSource gnss_source = LocalizerGnssSource::UBLOX); - - int locationd_thread(); - - void reset_kalman(double current_time = NAN); - void reset_kalman(double current_time, const Eigen::VectorXd &init_orient, const Eigen::VectorXd &init_pos, const Eigen::VectorXd &init_vel, const MatrixXdr &init_pos_R, const MatrixXdr &init_vel_R); - void reset_kalman(double current_time, const Eigen::VectorXd &init_x, const MatrixXdr &init_P); - void finite_check(double current_time = NAN); - void time_check(double current_time = NAN); - void update_reset_tracker(); - bool is_gps_ok(); - bool critical_services_valid(const std::map &critical_services); - bool is_timestamp_valid(double current_time); - void determine_gps_mode(double current_time); - bool are_inputs_ok(); - void observation_timings_invalid_reset(); - - void build_pose_message( - MessageBuilder& msg_builder, bool inputsOK, bool sensorsOK, bool msgValid); - void build_live_pose(cereal::LivePose::Builder& fix); - - Eigen::VectorXd get_position_geodetic(); - Eigen::VectorXd get_state(); - Eigen::VectorXd get_stdev(); - - void handle_msg_bytes(const char *data, const size_t size); - void handle_msg(const cereal::Event::Reader& log); - void handle_sensor(double current_time, const cereal::SensorEventData::Reader& log); - void handle_gps(double current_time, const cereal::GpsLocationData::Reader& log, const double sensor_time_offset); - void handle_gnss(double current_time, const cereal::GnssMeasurements::Reader& log); - void handle_car_state(double current_time, const cereal::CarState::Reader& log); - void handle_cam_odo(double current_time, const cereal::CameraOdometry::Reader& log); - void handle_live_calib(double current_time, const cereal::LiveCalibrationData::Reader& log); - - void input_fake_gps_observations(double current_time); - -private: - std::unique_ptr kf; - - Eigen::VectorXd calib; - MatrixXdr device_from_calib; - MatrixXdr calib_from_device; - bool calibrated = false; - - double car_speed = 0.0; - double last_reset_time = NAN; - std::deque posenet_stds; - - std::unique_ptr converter; - - int64_t unix_timestamp_millis = 0; - double reset_tracker = 0.0; - bool gps_mode = false; - double first_valid_log_time = NAN; - double ttff = NAN; - double last_gps_msg = 0; - LocalizerGnssSource gnss_source; - bool observation_timings_invalid = false; - std::map observation_values_invalid; - bool standstill = true; - int32_t orientation_reset_count = 0; - float gps_std_factor; - float gps_variance_factor; - float gps_vertical_variance_factor; - double gps_time_offset; - Eigen::VectorXd camodo_yawrate_distribution = Eigen::Vector2d(0.0, 10.0); // mean, std - - void configure_gnss_source(const LocalizerGnssSource &source); -}; diff --git a/selfdrive/locationd/locationd.py b/selfdrive/locationd/locationd.py new file mode 100755 index 00000000000000..57aecb22e73fdb --- /dev/null +++ b/selfdrive/locationd/locationd.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +import os +import time +import capnp +import numpy as np +from enum import Enum +from collections import defaultdict + +from cereal import log, messaging +from cereal.services import SERVICE_LIST +from openpilot.common.transformations.orientation import rot_from_euler +from openpilot.common.realtime import config_realtime_process +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.locationd.helpers import rotate_std +from openpilot.selfdrive.locationd.models.pose_kf import PoseKalman, States +from openpilot.selfdrive.locationd.models.constants import ObservationKind, GENERATED_DIR + +ACCEL_SANITY_CHECK = 100.0 # m/s^2 +ROTATION_SANITY_CHECK = 10.0 # rad/s +TRANS_SANITY_CHECK = 200.0 # m/s +CALIB_RPY_SANITY_CHECK = 0.5 # rad (+- 30 deg) +MIN_STD_SANITY_CHECK = 1e-5 # m or rad +MAX_FILTER_REWIND_TIME = 0.8 # s +MAX_SENSOR_TIME_DIFF = 0.1 # s +YAWRATE_CROSS_ERR_CHECK_FACTOR = 30 +INPUT_INVALID_LIMIT = 2.0 # 1 (camodo) / 9 (sensor) bad input[s] ignored +INPUT_INVALID_RECOVERY = 10.0 # ~10 secs to resume after exceeding allowed bad inputs by one +POSENET_STD_INITIAL_VALUE = 10.0 +POSENET_STD_HIST_HALF = 20 +CAM_ODO_POSE_DELAY = 0.1 # dependent on the vision model context frames and temporal frequency (current model is 5 fps with 2 context frames) +CAM_ODO_ROT_STD_MULT = 10 +CAM_ODO_TRANS_STD_MULT = 4 + + +def calculate_invalid_input_decay(invalid_limit, recovery_time, frequency): + return (1 - 1 / (2 * invalid_limit)) ** (1 / (recovery_time * frequency)) + + +def init_xyz_measurement(measurement: capnp._DynamicStructBuilder, values: np.ndarray, stds: np.ndarray, valid: bool): + assert len(values) == len(stds) == 3 + measurement.x, measurement.y, measurement.z = map(float, values) + measurement.xStd, measurement.yStd, measurement.zStd = map(float, stds) + measurement.valid = valid + + +class HandleLogResult(Enum): + SUCCESS = 0 + TIMING_INVALID = 1 + INPUT_INVALID = 2 + SENSOR_SOURCE_INVALID = 3 + + +class LocationEstimator: + def __init__(self, debug: bool): + self.kf = PoseKalman(GENERATED_DIR, MAX_FILTER_REWIND_TIME) + + self.debug = debug + + self.posenet_stds = np.array([POSENET_STD_INITIAL_VALUE] * (POSENET_STD_HIST_HALF * 2)) + self.car_speed = 0.0 + self.camodo_yawrate_distribution = np.array([0.0, 10.0]) # mean, std + self.device_from_calib = np.eye(3) + + obs_kinds = [ObservationKind.PHONE_ACCEL, ObservationKind.PHONE_GYRO, ObservationKind.CAMERA_ODO_ROTATION, ObservationKind.CAMERA_ODO_TRANSLATION] + self.observations = {kind: np.zeros(3, dtype=np.float32) for kind in obs_kinds} + self.observation_errors = {kind: np.zeros(3, dtype=np.float32) for kind in obs_kinds} + + def reset(self, t: float, x_initial: np.ndarray = PoseKalman.initial_x, P_initial: np.ndarray = PoseKalman.initial_P): + self.kf.init_state(x_initial, covs=P_initial, filter_time=t) + + def _validate_sensor_source(self, source: log.SensorEventData.SensorSource): + # some segments have two IMUs, ignore the second one + return source != log.SensorEventData.SensorSource.bmx055 + + def _validate_sensor_time(self, sensor_time: float, t: float): + # ignore empty readings + if sensor_time == 0: + return False + + # sensor time and log time should be close + sensor_time_invalid = abs(sensor_time - t) > MAX_SENSOR_TIME_DIFF + if sensor_time_invalid: + cloudlog.warning("Sensor reading ignored, sensor timestamp more than 100ms off from log time") + return not sensor_time_invalid + + def _validate_timestamp(self, t: float): + kf_t = self.kf.t + invalid = not np.isnan(kf_t) and (kf_t - t) > MAX_FILTER_REWIND_TIME + if invalid: + cloudlog.warning("Observation timestamp is older than the max rewind threshold of the filter") + return not invalid + + def _finite_check(self, t: float, new_x: np.ndarray, new_P: np.ndarray): + all_finite = np.isfinite(new_x).all() and np.isfinite(new_P).all() + if not all_finite: + cloudlog.error("Non-finite values detected, kalman reset") + self.reset(t) + + def handle_log(self, t: float, which: str, msg: capnp._DynamicStructReader) -> HandleLogResult: + new_x, new_P = None, None + if which == "accelerometer" and msg.which() == "acceleration": + sensor_time = msg.timestamp * 1e-9 + + if not self._validate_sensor_time(sensor_time, t) or not self._validate_timestamp(sensor_time): + return HandleLogResult.TIMING_INVALID + + if not self._validate_sensor_source(msg.source): + return HandleLogResult.SENSOR_SOURCE_INVALID + + v = msg.acceleration.v + meas = np.array([-v[2], -v[1], -v[0]]) + if np.linalg.norm(meas) >= ACCEL_SANITY_CHECK: + return HandleLogResult.INPUT_INVALID + + acc_res = self.kf.predict_and_observe(sensor_time, ObservationKind.PHONE_ACCEL, meas) + if acc_res is not None: + _, new_x, _, new_P, _, _, (acc_err,), _, _ = acc_res + self.observation_errors[ObservationKind.PHONE_ACCEL] = np.array(acc_err) + self.observations[ObservationKind.PHONE_ACCEL] = meas + + elif which == "gyroscope" and msg.which() == "gyroUncalibrated": + sensor_time = msg.timestamp * 1e-9 + + if not self._validate_sensor_time(sensor_time, t) or not self._validate_timestamp(sensor_time): + return HandleLogResult.TIMING_INVALID + + if not self._validate_sensor_source(msg.source): + return HandleLogResult.SENSOR_SOURCE_INVALID + + v = msg.gyroUncalibrated.v + meas = np.array([-v[2], -v[1], -v[0]]) + + gyro_bias = self.kf.x[States.GYRO_BIAS] + gyro_camodo_yawrate_err = np.abs((meas[2] - gyro_bias[2]) - self.camodo_yawrate_distribution[0]) + gyro_camodo_yawrate_err_threshold = YAWRATE_CROSS_ERR_CHECK_FACTOR * self.camodo_yawrate_distribution[1] + gyro_valid = gyro_camodo_yawrate_err < gyro_camodo_yawrate_err_threshold + + if np.linalg.norm(meas) >= ROTATION_SANITY_CHECK or not gyro_valid: + return HandleLogResult.INPUT_INVALID + + gyro_res = self.kf.predict_and_observe(sensor_time, ObservationKind.PHONE_GYRO, meas) + if gyro_res is not None: + _, new_x, _, new_P, _, _, (gyro_err,), _, _ = gyro_res + self.observation_errors[ObservationKind.PHONE_GYRO] = np.array(gyro_err) + self.observations[ObservationKind.PHONE_GYRO] = meas + + elif which == "carState": + self.car_speed = abs(msg.vEgo) + + elif which == "liveCalibration": + # Note that we use this message during calibration + if len(msg.rpyCalib) > 0: + calib = np.array(msg.rpyCalib) + if calib.min() < -CALIB_RPY_SANITY_CHECK or calib.max() > CALIB_RPY_SANITY_CHECK: + return HandleLogResult.INPUT_INVALID + + self.device_from_calib = rot_from_euler(calib) + + elif which == "cameraOdometry": + # camera odometry is delayed depending on the model context frames and temporal frequency + t = msg.timestampEof * 1e-9 - CAM_ODO_POSE_DELAY + if not self._validate_timestamp(t): + return HandleLogResult.TIMING_INVALID + + rot_device = np.matmul(self.device_from_calib, np.array(msg.rot)) + trans_device = np.matmul(self.device_from_calib, np.array(msg.trans)) + + if np.linalg.norm(rot_device) > ROTATION_SANITY_CHECK or np.linalg.norm(trans_device) > TRANS_SANITY_CHECK: + return HandleLogResult.INPUT_INVALID + + rot_calib_std = np.array(msg.rotStd) + trans_calib_std = np.array(msg.transStd) + + if rot_calib_std.min() <= MIN_STD_SANITY_CHECK or trans_calib_std.min() <= MIN_STD_SANITY_CHECK: + return HandleLogResult.INPUT_INVALID + + if np.linalg.norm(rot_calib_std) > 10 * ROTATION_SANITY_CHECK or np.linalg.norm(trans_calib_std) > 10 * TRANS_SANITY_CHECK: + return HandleLogResult.INPUT_INVALID + + self.posenet_stds = np.roll(self.posenet_stds, -1) + self.posenet_stds[-1] = trans_calib_std[0] + + # Multiply by N to avoid to high certainty in kalman filter because of temporally correlated noise + rot_calib_std *= CAM_ODO_ROT_STD_MULT + trans_calib_std *= CAM_ODO_TRANS_STD_MULT + + rot_device_std = rotate_std(self.device_from_calib, rot_calib_std) + trans_device_std = rotate_std(self.device_from_calib, trans_calib_std) + rot_device_noise = rot_device_std ** 2 + trans_device_noise = trans_device_std ** 2 + + cam_odo_rot_res = self.kf.predict_and_observe(t, ObservationKind.CAMERA_ODO_ROTATION, rot_device, np.array([np.diag(rot_device_noise)])) + cam_odo_trans_res = self.kf.predict_and_observe(t, ObservationKind.CAMERA_ODO_TRANSLATION, trans_device, np.array([np.diag(trans_device_noise)])) + self.camodo_yawrate_distribution = np.array([rot_device[2], rot_device_std[2]]) + if cam_odo_rot_res is not None: + _, new_x, _, new_P, _, _, (cam_odo_rot_err,), _, _ = cam_odo_rot_res + self.observation_errors[ObservationKind.CAMERA_ODO_ROTATION] = np.array(cam_odo_rot_err) + self.observations[ObservationKind.CAMERA_ODO_ROTATION] = rot_device + if cam_odo_trans_res is not None: + _, new_x, _, new_P, _, _, (cam_odo_trans_err,), _, _ = cam_odo_trans_res + self.observation_errors[ObservationKind.CAMERA_ODO_TRANSLATION] = np.array(cam_odo_trans_err) + self.observations[ObservationKind.CAMERA_ODO_TRANSLATION] = trans_device + + if new_x is not None and new_P is not None: + self._finite_check(t, new_x, new_P) + return HandleLogResult.SUCCESS + + def get_msg(self, sensors_valid: bool, inputs_valid: bool, filter_valid: bool): + state, cov = self.kf.x, self.kf.P + std = np.sqrt(np.diag(cov)) + + orientation_ned, orientation_ned_std = state[States.NED_ORIENTATION], std[States.NED_ORIENTATION] + velocity_device, velocity_device_std = state[States.DEVICE_VELOCITY], std[States.DEVICE_VELOCITY] + angular_velocity_device, angular_velocity_device_std = state[States.ANGULAR_VELOCITY], std[States.ANGULAR_VELOCITY] + acceleration_device, acceleration_device_std = state[States.ACCELERATION], std[States.ACCELERATION] + + msg = messaging.new_message("livePose") + msg.valid = filter_valid + + livePose = msg.livePose + init_xyz_measurement(livePose.orientationNED, orientation_ned, orientation_ned_std, filter_valid) + init_xyz_measurement(livePose.velocityDevice, velocity_device, velocity_device_std, filter_valid) + init_xyz_measurement(livePose.angularVelocityDevice, angular_velocity_device, angular_velocity_device_std, filter_valid) + init_xyz_measurement(livePose.accelerationDevice, acceleration_device, acceleration_device_std, filter_valid) + if self.debug: + livePose.debugFilterState.value = state.tolist() + livePose.debugFilterState.std = std.tolist() + livePose.debugFilterState.valid = filter_valid + livePose.debugFilterState.observations = [ + {'kind': k, 'value': self.observations[k].tolist(), 'error': self.observation_errors[k].tolist()} + for k in self.observations.keys() + ] + + old_mean = np.mean(self.posenet_stds[:POSENET_STD_HIST_HALF]) + new_mean = np.mean(self.posenet_stds[POSENET_STD_HIST_HALF:]) + std_spike = (new_mean / old_mean) > 4.0 and new_mean > 7.0 + + livePose.inputsOK = inputs_valid + livePose.posenetOK = not std_spike or self.car_speed <= 5.0 + livePose.sensorsOK = sensors_valid + livePose.timestamp = int(np.nan_to_num(self.kf.t) * 1e9) + + return msg + + +def sensor_all_checks(acc_msgs, gyro_msgs, sensor_valid, sensor_recv_time, sensor_alive, simulation): + cur_time = time.monotonic() + for which, msgs in [("accelerometer", acc_msgs), ("gyroscope", gyro_msgs)]: + if len(msgs) > 0: + sensor_valid[which] = msgs[-1].valid + sensor_recv_time[which] = cur_time + + if not simulation: + sensor_alive[which] = (cur_time - sensor_recv_time[which]) < 0.1 + else: + sensor_alive[which] = len(msgs) > 0 + + return all(sensor_alive.values()) and all(sensor_valid.values()) + + +def main(): + config_realtime_process([0, 1, 2, 3], 5) + + DEBUG = bool(int(os.getenv("DEBUG", "0"))) + SIMULATION = bool(int(os.getenv("SIMULATION", "0"))) + + pm = messaging.PubMaster(['livePose']) + sm = messaging.SubMaster(['carState', 'liveCalibration', 'cameraOdometry'], poll='cameraOdometry') + # separate sensor sockets for efficiency + sensor_sockets = [messaging.sub_sock(which, timeout=20) for which in ['accelerometer', 'gyroscope']] + sensor_alive, sensor_valid, sensor_recv_time = defaultdict(bool), defaultdict(bool), defaultdict(float) + + params = Params() + + estimator = LocationEstimator(DEBUG) + + filter_initialized = False + critcal_services = ["accelerometer", "gyroscope", "cameraOdometry"] + observation_input_invalid = defaultdict(int) + + input_invalid_limit = {s: round(INPUT_INVALID_LIMIT * (SERVICE_LIST[s].frequency / 20.)) for s in critcal_services} + input_invalid_threshold = {s: input_invalid_limit[s] - 0.5 for s in critcal_services} + input_invalid_decay = {s: calculate_invalid_input_decay(input_invalid_limit[s], INPUT_INVALID_RECOVERY, SERVICE_LIST[s].frequency) for s in critcal_services} + + initial_pose_data = params.get("LocationFilterInitialState") + if initial_pose_data is not None: + with log.Event.from_bytes(initial_pose_data) as lp_msg: + filter_state = lp_msg.livePose.debugFilterState + x_initial = np.array(filter_state.value, dtype=np.float64) if len(filter_state.value) != 0 else PoseKalman.initial_x + P_initial = np.diag(np.array(filter_state.std, dtype=np.float64)) if len(filter_state.std) != 0 else PoseKalman.initial_P + estimator.reset(None, x_initial, P_initial) + + while True: + sm.update() + + acc_msgs, gyro_msgs = (messaging.drain_sock(sock) for sock in sensor_sockets) + + if filter_initialized: + msgs = [] + for msg in acc_msgs + gyro_msgs: + t, valid, which, data = msg.logMonoTime, msg.valid, msg.which(), getattr(msg, msg.which()) + msgs.append((t, valid, which, data)) + for which, updated in sm.updated.items(): + if not updated: + continue + t, valid, data = sm.logMonoTime[which], sm.valid[which], sm[which] + msgs.append((t, valid, which, data)) + + for log_mono_time, valid, which, msg in sorted(msgs, key=lambda x: x[0]): + if valid: + t = log_mono_time * 1e-9 + res = estimator.handle_log(t, which, msg) + if which not in critcal_services: + continue + + if res == HandleLogResult.TIMING_INVALID: + cloudlog.warning(f"Observation {which} ignored due to failed timing check") + observation_input_invalid[which] += 1 + elif res == HandleLogResult.INPUT_INVALID: + cloudlog.warning(f"Observation {which} ignored due to failed sanity check") + observation_input_invalid[which] += 1 + elif res == HandleLogResult.SUCCESS: + observation_input_invalid[which] *= input_invalid_decay[which] + else: + filter_initialized = sm.all_checks() and sensor_all_checks(acc_msgs, gyro_msgs, sensor_valid, sensor_recv_time, sensor_alive, SIMULATION) + + if sm.updated["cameraOdometry"]: + critical_service_inputs_valid = all(observation_input_invalid[s] < input_invalid_threshold[s] for s in critcal_services) + inputs_valid = sm.all_valid() and critical_service_inputs_valid + sensors_valid = sensor_all_checks(acc_msgs, gyro_msgs, sensor_valid, sensor_recv_time, sensor_alive, SIMULATION) + + msg = estimator.get_msg(sensors_valid, inputs_valid, filter_initialized) + pm.send("livePose", msg) + + +if __name__ == "__main__": + main() diff --git a/selfdrive/locationd/models/car_kf.py b/selfdrive/locationd/models/car_kf.py index 87a93cdd0c3a1b..27cc4ef9c93fc5 100755 --- a/selfdrive/locationd/models/car_kf.py +++ b/selfdrive/locationd/models/car_kf.py @@ -5,7 +5,7 @@ import numpy as np -from openpilot.selfdrive.controls.lib.vehicle_model import ACCELERATION_DUE_TO_GRAVITY +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY from openpilot.selfdrive.locationd.models.constants import ObservationKind from openpilot.common.swaglog import cloudlog @@ -93,8 +93,9 @@ def generate_code(generated_dir): dim_state = CarKalman.initial_x.shape[0] name = CarKalman.name - # vehicle models comes from The Science of Vehicle Dynamics: Handling, Braking, and Ride of Road and Race Cars - # Model used is in 6.15 with formula from 6.198 + # Linearized single-track lateral dynamics, equations 7.211-7.213 + # Massimo Guiggiani, The Science of Vehicle Dynamics: Handling, Braking, and Ride of Road and Race Cars + # Springer Cham, 2023. doi: https://doi.org/10.1007/978-3-031-06461-6 # globals global_vars = [sp.Symbol(name) for name in CarKalman.global_vars] @@ -160,19 +161,18 @@ def generate_code(generated_dir): gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state, global_vars=global_vars) - def __init__(self, generated_dir, steer_ratio=15, stiffness_factor=1, angle_offset=0, P_initial=None): - dim_state = self.initial_x.shape[0] - dim_state_err = self.P_initial.shape[0] - x_init = self.initial_x - x_init[States.STEER_RATIO] = steer_ratio - x_init[States.STIFFNESS] = stiffness_factor - x_init[States.ANGLE_OFFSET] = angle_offset - - if P_initial is not None: - self.P_initial = P_initial - # init filter - self.filter = EKF_sym_pyx(generated_dir, self.name, self.Q, self.initial_x, self.P_initial, - dim_state, dim_state_err, global_vars=self.global_vars, logger=cloudlog) + def __init__(self, generated_dir): + dim_state, dim_state_err = CarKalman.initial_x.shape[0], CarKalman.P_initial.shape[0] + self.filter = EKF_sym_pyx(generated_dir, CarKalman.name, CarKalman.Q, CarKalman.initial_x, CarKalman.P_initial, + dim_state, dim_state_err, global_vars=CarKalman.global_vars, logger=cloudlog) + + def set_globals(self, mass, rotational_inertia, center_to_front, center_to_rear, stiffness_front, stiffness_rear): + self.filter.set_global("mass", mass) + self.filter.set_global("rotational_inertia", rotational_inertia) + self.filter.set_global("center_to_front", center_to_front) + self.filter.set_global("center_to_rear", center_to_rear) + self.filter.set_global("stiffness_front", stiffness_front) + self.filter.set_global("stiffness_rear", stiffness_rear) if __name__ == "__main__": diff --git a/selfdrive/locationd/models/live_kf.cc b/selfdrive/locationd/models/live_kf.cc deleted file mode 100644 index fc3bfb72461697..00000000000000 --- a/selfdrive/locationd/models/live_kf.cc +++ /dev/null @@ -1,122 +0,0 @@ -#include "selfdrive/locationd/models/live_kf.h" - -using namespace EKFS; -using namespace Eigen; - -Eigen::Map get_mapvec(const Eigen::VectorXd &vec) { - return Eigen::Map((double*)vec.data(), vec.rows(), vec.cols()); -} - -Eigen::Map get_mapmat(const MatrixXdr &mat) { - return Eigen::Map((double*)mat.data(), mat.rows(), mat.cols()); -} - -std::vector> get_vec_mapvec(const std::vector &vec_vec) { - std::vector> res; - for (const Eigen::VectorXd &vec : vec_vec) { - res.push_back(get_mapvec(vec)); - } - return res; -} - -std::vector> get_vec_mapmat(const std::vector &mat_vec) { - std::vector> res; - for (const MatrixXdr &mat : mat_vec) { - res.push_back(get_mapmat(mat)); - } - return res; -} - -LiveKalman::LiveKalman() { - this->dim_state = live_initial_x.rows(); - this->dim_state_err = live_initial_P_diag.rows(); - - this->initial_x = live_initial_x; - this->initial_P = live_initial_P_diag.asDiagonal(); - this->fake_gps_pos_cov = live_fake_gps_pos_cov_diag.asDiagonal(); - this->fake_gps_vel_cov = live_fake_gps_vel_cov_diag.asDiagonal(); - this->reset_orientation_P = live_reset_orientation_diag.asDiagonal(); - this->Q = live_Q_diag.asDiagonal(); - for (auto& pair : live_obs_noise_diag) { - this->obs_noise[pair.first] = pair.second.asDiagonal(); - } - - // init filter - this->filter = std::make_shared(this->name, get_mapmat(this->Q), get_mapvec(this->initial_x), - get_mapmat(initial_P), this->dim_state, this->dim_state_err, 0, 0, 0, std::vector(), - std::vector{3}, std::vector(), 0.8); -} - -void LiveKalman::init_state(const VectorXd &state, const VectorXd &covs_diag, double filter_time) { - MatrixXdr covs = covs_diag.asDiagonal(); - this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time); -} - -void LiveKalman::init_state(const VectorXd &state, const MatrixXdr &covs, double filter_time) { - this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time); -} - -void LiveKalman::init_state(const VectorXd &state, double filter_time) { - MatrixXdr covs = this->filter->covs(); - this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time); -} - -VectorXd LiveKalman::get_x() { - return this->filter->state(); -} - -MatrixXdr LiveKalman::get_P() { - return this->filter->covs(); -} - -double LiveKalman::get_filter_time() { - return this->filter->get_filter_time(); -} - -std::vector LiveKalman::get_R(int kind, int n) { - std::vector R; - for (int i = 0; i < n; i++) { - R.push_back(this->obs_noise[kind]); - } - return R; -} - -std::optional LiveKalman::predict_and_observe(double t, int kind, const std::vector &meas, std::vector R) { - std::optional r; - if (R.size() == 0) { - R = this->get_R(kind, meas.size()); - } - r = this->filter->predict_and_update_batch(t, kind, get_vec_mapvec(meas), get_vec_mapmat(R)); - return r; -} - -void LiveKalman::predict(double t) { - this->filter->predict(t); -} - -const Eigen::VectorXd &LiveKalman::get_initial_x() { - return this->initial_x; -} - -const MatrixXdr &LiveKalman::get_initial_P() { - return this->initial_P; -} - -const MatrixXdr &LiveKalman::get_fake_gps_pos_cov() { - return this->fake_gps_pos_cov; -} - -const MatrixXdr &LiveKalman::get_fake_gps_vel_cov() { - return this->fake_gps_vel_cov; -} - -const MatrixXdr &LiveKalman::get_reset_orientation_P() { - return this->reset_orientation_P; -} - -MatrixXdr LiveKalman::H(const VectorXd &in) { - assert(in.size() == 6); - Matrix res; - this->filter->get_extra_routine("H")((double*)in.data(), res.data()); - return res; -} diff --git a/selfdrive/locationd/models/live_kf.h b/selfdrive/locationd/models/live_kf.h deleted file mode 100644 index e4b3e326b3c614..00000000000000 --- a/selfdrive/locationd/models/live_kf.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include -#include - -#include "generated/live_kf_constants.h" -#include "rednose/helpers/ekf_sym.h" - -#define EARTH_GM 3.986005e14 // m^3/s^2 (gravitational constant * mass of earth) - -using namespace EKFS; - -Eigen::Map get_mapvec(const Eigen::VectorXd &vec); -Eigen::Map get_mapmat(const MatrixXdr &mat); -std::vector> get_vec_mapvec(const std::vector &vec_vec); -std::vector> get_vec_mapmat(const std::vector &mat_vec); - -class LiveKalman { -public: - LiveKalman(); - - void init_state(const Eigen::VectorXd &state, const Eigen::VectorXd &covs_diag, double filter_time); - void init_state(const Eigen::VectorXd &state, const MatrixXdr &covs, double filter_time); - void init_state(const Eigen::VectorXd &state, double filter_time); - - Eigen::VectorXd get_x(); - MatrixXdr get_P(); - double get_filter_time(); - std::vector get_R(int kind, int n); - - std::optional predict_and_observe(double t, int kind, const std::vector &meas, std::vector R = {}); - std::optional predict_and_update_odo_speed(std::vector speed, double t, int kind); - std::optional predict_and_update_odo_trans(std::vector trans, double t, int kind); - std::optional predict_and_update_odo_rot(std::vector rot, double t, int kind); - void predict(double t); - - const Eigen::VectorXd &get_initial_x(); - const MatrixXdr &get_initial_P(); - const MatrixXdr &get_fake_gps_pos_cov(); - const MatrixXdr &get_fake_gps_vel_cov(); - const MatrixXdr &get_reset_orientation_P(); - - MatrixXdr H(const Eigen::VectorXd &in); - -private: - std::string name = "live"; - - std::shared_ptr filter; - - int dim_state; - int dim_state_err; - - Eigen::VectorXd initial_x; - MatrixXdr initial_P; - MatrixXdr fake_gps_pos_cov; - MatrixXdr fake_gps_vel_cov; - MatrixXdr reset_orientation_P; - MatrixXdr Q; // process noise - std::unordered_map obs_noise; -}; diff --git a/selfdrive/locationd/models/live_kf.py b/selfdrive/locationd/models/live_kf.py deleted file mode 100755 index 0cc3eca61dd1c8..00000000000000 --- a/selfdrive/locationd/models/live_kf.py +++ /dev/null @@ -1,242 +0,0 @@ -#!/usr/bin/env python3 - -import sys -import os -import numpy as np - -from openpilot.selfdrive.locationd.models.constants import ObservationKind - -import sympy as sp -import inspect -from rednose.helpers.sympy_helpers import euler_rotate, quat_matrix_r, quat_rotate -from rednose.helpers.ekf_sym import gen_code - -EARTH_GM = 3.986005e14 # m^3/s^2 (gravitational constant * mass of earth) - - -def numpy2eigenstring(arr): - assert(len(arr.shape) == 1) - arr_str = np.array2string(arr, precision=20, separator=',')[1:-1].replace(' ', '').replace('\n', '') - return f"(Eigen::VectorXd({len(arr)}) << {arr_str}).finished()" - - -class States: - ECEF_POS = slice(0, 3) # x, y and z in ECEF in meters - ECEF_ORIENTATION = slice(3, 7) # quat for pose of phone in ecef - ECEF_VELOCITY = slice(7, 10) # ecef velocity in m/s - ANGULAR_VELOCITY = slice(10, 13) # roll, pitch and yaw rates in device frame in radians/s - GYRO_BIAS = slice(13, 16) # roll, pitch and yaw biases - ACCELERATION = slice(16, 19) # Acceleration in device frame in m/s**2 - ACC_BIAS = slice(19, 22) # Acceletometer bias in m/s**2 - - # Error-state has different slices because it is an ESKF - ECEF_POS_ERR = slice(0, 3) - ECEF_ORIENTATION_ERR = slice(3, 6) # euler angles for orientation error - ECEF_VELOCITY_ERR = slice(6, 9) - ANGULAR_VELOCITY_ERR = slice(9, 12) - GYRO_BIAS_ERR = slice(12, 15) - ACCELERATION_ERR = slice(15, 18) - ACC_BIAS_ERR = slice(18, 21) - - -class LiveKalman: - name = 'live' - - initial_x = np.array([3.88e6, -3.37e6, 3.76e6, - 0.42254641, -0.31238054, -0.83602975, -0.15788347, # NED [0,0,0] -> ECEF Quat - 0, 0, 0, - 0, 0, 0, - 0, 0, 0, - 0, 0, 0, - 0, 0, 0]) - - # state covariance - initial_P_diag = np.array([10**2, 10**2, 10**2, - 0.01**2, 0.01**2, 0.01**2, - 10**2, 10**2, 10**2, - 1**2, 1**2, 1**2, - 1**2, 1**2, 1**2, - 100**2, 100**2, 100**2, - 0.01**2, 0.01**2, 0.01**2]) - - # state covariance when resetting midway in a segment - reset_orientation_diag = np.array([1**2, 1**2, 1**2]) - - # fake observation covariance, to ensure the uncertainty estimate of the filter is under control - fake_gps_pos_cov_diag = np.array([1000**2, 1000**2, 1000**2]) - fake_gps_vel_cov_diag = np.array([10**2, 10**2, 10**2]) - - # process noise - Q_diag = np.array([0.03**2, 0.03**2, 0.03**2, - 0.001**2, 0.001**2, 0.001**2, - 0.01**2, 0.01**2, 0.01**2, - 0.1**2, 0.1**2, 0.1**2, - (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2, - 3**2, 3**2, 3**2, - 0.005**2, 0.005**2, 0.005**2]) - - obs_noise_diag = {ObservationKind.PHONE_GYRO: np.array([0.025**2, 0.025**2, 0.025**2]), - ObservationKind.PHONE_ACCEL: np.array([.5**2, .5**2, .5**2]), - ObservationKind.CAMERA_ODO_ROTATION: np.array([0.05**2, 0.05**2, 0.05**2]), - ObservationKind.NO_ROT: np.array([0.005**2, 0.005**2, 0.005**2]), - ObservationKind.NO_ACCEL: np.array([0.05**2, 0.05**2, 0.05**2]), - ObservationKind.ECEF_POS: np.array([5**2, 5**2, 5**2]), - ObservationKind.ECEF_VEL: np.array([.5**2, .5**2, .5**2]), - ObservationKind.ECEF_ORIENTATION_FROM_GPS: np.array([.2**2, .2**2, .2**2, .2**2])} - - @staticmethod - def generate_code(generated_dir): - name = LiveKalman.name - dim_state = LiveKalman.initial_x.shape[0] - dim_state_err = LiveKalman.initial_P_diag.shape[0] - - state_sym = sp.MatrixSymbol('state', dim_state, 1) - state = sp.Matrix(state_sym) - x, y, z = state[States.ECEF_POS, :] - q = state[States.ECEF_ORIENTATION, :] - v = state[States.ECEF_VELOCITY, :] - vx, vy, vz = v - omega = state[States.ANGULAR_VELOCITY, :] - vroll, vpitch, vyaw = omega - roll_bias, pitch_bias, yaw_bias = state[States.GYRO_BIAS, :] - acceleration = state[States.ACCELERATION, :] - acc_bias = state[States.ACC_BIAS, :] - - dt = sp.Symbol('dt') - - # calibration and attitude rotation matrices - quat_rot = quat_rotate(*q) - - # Got the quat predict equations from here - # A New Quaternion-Based Kalman Filter for - # Real-Time Attitude Estimation Using the Two-Step - # Geometrically-Intuitive Correction Algorithm - A = 0.5 * sp.Matrix([[0, -vroll, -vpitch, -vyaw], - [vroll, 0, vyaw, -vpitch], - [vpitch, -vyaw, 0, vroll], - [vyaw, vpitch, -vroll, 0]]) - q_dot = A * q - - # Time derivative of the state as a function of state - state_dot = sp.Matrix(np.zeros((dim_state, 1))) - state_dot[States.ECEF_POS, :] = v - state_dot[States.ECEF_ORIENTATION, :] = q_dot - state_dot[States.ECEF_VELOCITY, 0] = quat_rot * acceleration - - # Basic descretization, 1st order intergrator - # Can be pretty bad if dt is big - f_sym = state + dt * state_dot - - state_err_sym = sp.MatrixSymbol('state_err', dim_state_err, 1) - state_err = sp.Matrix(state_err_sym) - quat_err = state_err[States.ECEF_ORIENTATION_ERR, :] - v_err = state_err[States.ECEF_VELOCITY_ERR, :] - omega_err = state_err[States.ANGULAR_VELOCITY_ERR, :] - acceleration_err = state_err[States.ACCELERATION_ERR, :] - - # Time derivative of the state error as a function of state error and state - quat_err_matrix = euler_rotate(quat_err[0], quat_err[1], quat_err[2]) - q_err_dot = quat_err_matrix * quat_rot * (omega + omega_err) - state_err_dot = sp.Matrix(np.zeros((dim_state_err, 1))) - state_err_dot[States.ECEF_POS_ERR, :] = v_err - state_err_dot[States.ECEF_ORIENTATION_ERR, :] = q_err_dot - state_err_dot[States.ECEF_VELOCITY_ERR, :] = quat_err_matrix * quat_rot * (acceleration + acceleration_err) - f_err_sym = state_err + dt * state_err_dot - - # Observation matrix modifier - H_mod_sym = sp.Matrix(np.zeros((dim_state, dim_state_err))) - H_mod_sym[States.ECEF_POS, States.ECEF_POS_ERR] = np.eye(States.ECEF_POS.stop - States.ECEF_POS.start) - H_mod_sym[States.ECEF_ORIENTATION, States.ECEF_ORIENTATION_ERR] = 0.5 * quat_matrix_r(state[3:7])[:, 1:] - H_mod_sym[States.ECEF_ORIENTATION.stop:, States.ECEF_ORIENTATION_ERR.stop:] = np.eye(dim_state - States.ECEF_ORIENTATION.stop) - - # these error functions are defined so that say there - # is a nominal x and true x: - # true x = err_function(nominal x, delta x) - # delta x = inv_err_function(nominal x, true x) - nom_x = sp.MatrixSymbol('nom_x', dim_state, 1) - true_x = sp.MatrixSymbol('true_x', dim_state, 1) - delta_x = sp.MatrixSymbol('delta_x', dim_state_err, 1) - - err_function_sym = sp.Matrix(np.zeros((dim_state, 1))) - delta_quat = sp.Matrix(np.ones(4)) - delta_quat[1:, :] = sp.Matrix(0.5 * delta_x[States.ECEF_ORIENTATION_ERR, :]) - err_function_sym[States.ECEF_POS, :] = sp.Matrix(nom_x[States.ECEF_POS, :] + delta_x[States.ECEF_POS_ERR, :]) - err_function_sym[States.ECEF_ORIENTATION, 0] = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]) * delta_quat - err_function_sym[States.ECEF_ORIENTATION.stop:, :] = sp.Matrix(nom_x[States.ECEF_ORIENTATION.stop:, :] + delta_x[States.ECEF_ORIENTATION_ERR.stop:, :]) - - inv_err_function_sym = sp.Matrix(np.zeros((dim_state_err, 1))) - inv_err_function_sym[States.ECEF_POS_ERR, 0] = sp.Matrix(-nom_x[States.ECEF_POS, 0] + true_x[States.ECEF_POS, 0]) - delta_quat = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]).T * true_x[States.ECEF_ORIENTATION, 0] - inv_err_function_sym[States.ECEF_ORIENTATION_ERR, 0] = sp.Matrix(2 * delta_quat[1:]) - inv_err_function_sym[States.ECEF_ORIENTATION_ERR.stop:, 0] = sp.Matrix(-nom_x[States.ECEF_ORIENTATION.stop:, 0] + true_x[States.ECEF_ORIENTATION.stop:, 0]) - - eskf_params = [[err_function_sym, nom_x, delta_x], - [inv_err_function_sym, nom_x, true_x], - H_mod_sym, f_err_sym, state_err_sym] - # - # Observation functions - # - h_gyro_sym = sp.Matrix([ - vroll + roll_bias, - vpitch + pitch_bias, - vyaw + yaw_bias]) - - pos = sp.Matrix([x, y, z]) - gravity = quat_rot.T * ((EARTH_GM / ((x**2 + y**2 + z**2)**(3.0 / 2.0))) * pos) - h_acc_sym = (gravity + acceleration + acc_bias) - h_acc_stationary_sym = acceleration - h_phone_rot_sym = sp.Matrix([vroll, vpitch, vyaw]) - h_pos_sym = sp.Matrix([x, y, z]) - h_vel_sym = sp.Matrix([vx, vy, vz]) - h_orientation_sym = q - h_relative_motion = sp.Matrix(quat_rot.T * v) - - obs_eqs = [[h_gyro_sym, ObservationKind.PHONE_GYRO, None], - [h_phone_rot_sym, ObservationKind.NO_ROT, None], - [h_acc_sym, ObservationKind.PHONE_ACCEL, None], - [h_pos_sym, ObservationKind.ECEF_POS, None], - [h_vel_sym, ObservationKind.ECEF_VEL, None], - [h_orientation_sym, ObservationKind.ECEF_ORIENTATION_FROM_GPS, None], - [h_relative_motion, ObservationKind.CAMERA_ODO_TRANSLATION, None], - [h_phone_rot_sym, ObservationKind.CAMERA_ODO_ROTATION, None], - [h_acc_stationary_sym, ObservationKind.NO_ACCEL, None]] - - # this returns a sympy routine for the jacobian of the observation function of the local vel - in_vec = sp.MatrixSymbol('in_vec', 6, 1) # roll, pitch, yaw, vx, vy, vz - h = euler_rotate(in_vec[0], in_vec[1], in_vec[2]).T * (sp.Matrix([in_vec[3], in_vec[4], in_vec[5]])) - extra_routines = [('H', h.jacobian(in_vec), [in_vec])] - - gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state_err, eskf_params, extra_routines=extra_routines) - - # write constants to extra header file for use in cpp - live_kf_header = "#pragma once\n\n" - live_kf_header += "#include \n" - live_kf_header += "#include \n\n" - for state, slc in inspect.getmembers(States, lambda x: isinstance(x, slice)): - assert(slc.step is None) # unsupported - live_kf_header += f'#define STATE_{state}_START {slc.start}\n' - live_kf_header += f'#define STATE_{state}_END {slc.stop}\n' - live_kf_header += f'#define STATE_{state}_LEN {slc.stop - slc.start}\n' - live_kf_header += "\n" - - for kind, val in inspect.getmembers(ObservationKind, lambda x: isinstance(x, int)): - live_kf_header += f'#define OBSERVATION_{kind} {val}\n' - live_kf_header += "\n" - - live_kf_header += f"static const Eigen::VectorXd live_initial_x = {numpy2eigenstring(LiveKalman.initial_x)};\n" - live_kf_header += f"static const Eigen::VectorXd live_initial_P_diag = {numpy2eigenstring(LiveKalman.initial_P_diag)};\n" - live_kf_header += f"static const Eigen::VectorXd live_fake_gps_pos_cov_diag = {numpy2eigenstring(LiveKalman.fake_gps_pos_cov_diag)};\n" - live_kf_header += f"static const Eigen::VectorXd live_fake_gps_vel_cov_diag = {numpy2eigenstring(LiveKalman.fake_gps_vel_cov_diag)};\n" - live_kf_header += f"static const Eigen::VectorXd live_reset_orientation_diag = {numpy2eigenstring(LiveKalman.reset_orientation_diag)};\n" - live_kf_header += f"static const Eigen::VectorXd live_Q_diag = {numpy2eigenstring(LiveKalman.Q_diag)};\n" - live_kf_header += "static const std::unordered_map> live_obs_noise_diag = {\n" - for kind, noise in LiveKalman.obs_noise_diag.items(): - live_kf_header += f" {{ {kind}, {numpy2eigenstring(noise)} }},\n" - live_kf_header += "};\n\n" - - open(os.path.join(generated_dir, "live_kf_constants.h"), 'w').write(live_kf_header) - - -if __name__ == "__main__": - generated_dir = sys.argv[2] - LiveKalman.generate_code(generated_dir) diff --git a/selfdrive/locationd/models/pose_kf.py b/selfdrive/locationd/models/pose_kf.py new file mode 100755 index 00000000000000..a8ff80c7130542 --- /dev/null +++ b/selfdrive/locationd/models/pose_kf.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 + +import sys +import numpy as np + +from openpilot.selfdrive.locationd.models.constants import ObservationKind + +from rednose.helpers.kalmanfilter import KalmanFilter + +if __name__=="__main__": + import sympy as sp + from rednose.helpers.ekf_sym import gen_code + from rednose.helpers.sympy_helpers import euler_rotate, rot_to_euler +else: + from rednose.helpers.ekf_sym_pyx import EKF_sym_pyx + +EARTH_G = 9.81 + + +class States: + NED_ORIENTATION = slice(0, 3) # roll, pitch, yaw in rad + DEVICE_VELOCITY = slice(3, 6) # ned velocity in m/s + ANGULAR_VELOCITY = slice(6, 9) # roll, pitch and yaw rates in rad/s + GYRO_BIAS = slice(9, 12) # roll, pitch and yaw gyroscope biases in rad/s + ACCELERATION = slice(12, 15) # acceleration in device frame in m/s**2 + ACCEL_BIAS = slice(15, 18) # Acceletometer bias in m/s**2 + + +class PoseKalman(KalmanFilter): + name = "pose" + + # state + initial_x = np.array([0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0]) + # state covariance + initial_P = np.diag([0.01**2, 0.01**2, 0.01**2, + 10**2, 10**2, 10**2, + 1**2, 1**2, 1**2, + 1**2, 1**2, 1**2, + 100**2, 100**2, 100**2, + 0.01**2, 0.01**2, 0.01**2]) + + # process noise + Q = np.diag([0.001**2, 0.001**2, 0.001**2, + 0.01**2, 0.01**2, 0.01**2, + 0.085**2, 0.085**2, 0.085**2, + (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2, + 3**2, 3**2, 3**2, + 0.005**2, 0.005**2, 0.005**2]) + + obs_noise = {ObservationKind.PHONE_GYRO: np.diag([0.025**2, 0.025**2, 0.025**2]), + ObservationKind.PHONE_ACCEL: np.diag([0.75**2, 0.75**2, 0.75**2]), + ObservationKind.CAMERA_ODO_TRANSLATION: np.diag([0.5**2, 0.5**2, 0.5**2]), + ObservationKind.CAMERA_ODO_ROTATION: np.diag([0.05**2, 0.05**2, 0.05**2])} + + @staticmethod + def generate_code(generated_dir): + name = PoseKalman.name + dim_state = PoseKalman.initial_x.shape[0] + dim_state_err = PoseKalman.initial_P.shape[0] + + state_sym = sp.MatrixSymbol('state', dim_state, 1) + state = sp.Matrix(state_sym) + roll, pitch, yaw = state[States.NED_ORIENTATION, :] + velocity = state[States.DEVICE_VELOCITY, :] + angular_velocity = state[States.ANGULAR_VELOCITY, :] + vroll, vpitch, vyaw = angular_velocity + gyro_bias = state[States.GYRO_BIAS, :] + acceleration = state[States.ACCELERATION, :] + acc_bias = state[States.ACCEL_BIAS, :] + + dt = sp.Symbol('dt') + + ned_from_device = euler_rotate(roll, pitch, yaw) + device_from_ned = ned_from_device.T + + state_dot = sp.Matrix(np.zeros((dim_state, 1))) + state_dot[States.DEVICE_VELOCITY, :] = acceleration + + f_sym = state + dt * state_dot + device_from_device_t1 = euler_rotate(dt*vroll, dt*vpitch, dt*vyaw) + ned_from_device_t1 = ned_from_device * device_from_device_t1 + f_sym[States.NED_ORIENTATION, :] = rot_to_euler(ned_from_device_t1) + + centripetal_acceleration = angular_velocity.cross(velocity) + gravity = sp.Matrix([0, 0, -EARTH_G]) + h_gyro_sym = angular_velocity + gyro_bias + h_acc_sym = device_from_ned * gravity + acceleration + centripetal_acceleration + acc_bias + h_phone_rot_sym = angular_velocity + h_relative_motion_sym = velocity + obs_eqs = [ + [h_gyro_sym, ObservationKind.PHONE_GYRO, None], + [h_acc_sym, ObservationKind.PHONE_ACCEL, None], + [h_relative_motion_sym, ObservationKind.CAMERA_ODO_TRANSLATION, None], + [h_phone_rot_sym, ObservationKind.CAMERA_ODO_ROTATION, None], + ] + gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state_err) + + def __init__(self, generated_dir, max_rewind_age): + dim_state, dim_state_err = PoseKalman.initial_x.shape[0], PoseKalman.initial_P.shape[0] + self.filter = EKF_sym_pyx(generated_dir, self.name, PoseKalman.Q, PoseKalman.initial_x, PoseKalman.initial_P, + dim_state, dim_state_err, max_rewind_age=max_rewind_age) + + +if __name__ == "__main__": + generated_dir = sys.argv[2] + PoseKalman.generate_code(generated_dir) diff --git a/selfdrive/locationd/paramsd.py b/selfdrive/locationd/paramsd.py index 19ded3b4f7176b..02d09c506e158c 100755 --- a/selfdrive/locationd/paramsd.py +++ b/selfdrive/locationd/paramsd.py @@ -1,25 +1,22 @@ #!/usr/bin/env python3 import os -import math -import json import numpy as np +import capnp import cereal.messaging as messaging from cereal import car, log from openpilot.common.params import Params from openpilot.common.realtime import config_realtime_process, DT_MDL -from openpilot.common.numpy_fast import clip from openpilot.selfdrive.locationd.models.car_kf import CarKalman, ObservationKind, States from openpilot.selfdrive.locationd.models.constants import GENERATED_DIR from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose from openpilot.common.swaglog import cloudlog - MAX_ANGLE_OFFSET_DELTA = 20 * DT_MDL # Max 20 deg/s -ROLL_MAX_DELTA = math.radians(20.0) * DT_MDL # 20deg in 1 second is well within curvature limits -ROLL_MIN, ROLL_MAX = math.radians(-10), math.radians(10) -ROLL_LOWERED_MAX = math.radians(8) -ROLL_STD_MAX = math.radians(1.5) +ROLL_MAX_DELTA = np.radians(20.0) * DT_MDL # 20deg in 1 second is well within curvature limits +ROLL_MIN, ROLL_MAX = np.radians(-10), np.radians(10) +ROLL_LOWERED_MAX = np.radians(8) +ROLL_STD_MAX = np.radians(1.5) LATERAL_ACC_SENSOR_THRESHOLD = 4.0 OFFSET_MAX = 10.0 OFFSET_LOWERED_MAX = 8.0 @@ -27,38 +24,64 @@ LOW_ACTIVE_SPEED = 10.0 -class ParamsLearner: - def __init__(self, CP, steer_ratio, stiffness_factor, angle_offset, P_initial=None): - self.kf = CarKalman(GENERATED_DIR, steer_ratio, stiffness_factor, angle_offset, P_initial) +class VehicleParamsLearner: + def __init__(self, CP: car.CarParams, steer_ratio: float, stiffness_factor: float, angle_offset: float, P_initial: np.ndarray | None = None): + self.kf = CarKalman(GENERATED_DIR) + + self.x_initial = CarKalman.initial_x.copy() + self.x_initial[States.STEER_RATIO] = steer_ratio + self.x_initial[States.STIFFNESS] = stiffness_factor + self.x_initial[States.ANGLE_OFFSET] = angle_offset + self.P_initial = P_initial if P_initial is not None else CarKalman.P_initial - self.kf.filter.set_global("mass", CP.mass) - self.kf.filter.set_global("rotational_inertia", CP.rotationalInertia) - self.kf.filter.set_global("center_to_front", CP.centerToFront) - self.kf.filter.set_global("center_to_rear", CP.wheelbase - CP.centerToFront) - self.kf.filter.set_global("stiffness_front", CP.tireStiffnessFront) - self.kf.filter.set_global("stiffness_rear", CP.tireStiffnessRear) + self.kf.set_globals( + mass=CP.mass, + rotational_inertia=CP.rotationalInertia, + center_to_front=CP.centerToFront, + center_to_rear=CP.wheelbase - CP.centerToFront, + stiffness_front=CP.tireStiffnessFront, + stiffness_rear=CP.tireStiffnessRear + ) - self.active = False + self.min_sr, self.max_sr = 0.5 * CP.steerRatio, 2.0 * CP.steerRatio self.calibrator = PoseCalibrator() - self.speed = 0.0 - self.yaw_rate = 0.0 - self.yaw_rate_std = 0.0 - self.roll = 0.0 - self.steering_angle = 0.0 - self.roll_valid = False + self.observed_speed = 0.0 + self.observed_yaw_rate = 0.0 + self.observed_roll = 0.0 + + self.avg_offset_valid = True + self.total_offset_valid = True + self.roll_valid = True + + self.reset(None) + + def reset(self, t: float | None): + self.kf.init_state(self.x_initial, covs=self.P_initial, filter_time=t) - def handle_log(self, t, which, msg): + self.angle_offset, self.roll, self.active = np.degrees(self.x_initial[States.ANGLE_OFFSET].item()), 0.0, False + self.avg_angle_offset = self.angle_offset + + def handle_log(self, t: float, which: str, msg: capnp._DynamicStructReader): if which == 'livePose': + t = msg.timestamp * 1e-9 device_pose = Pose.from_live_pose(msg) calibrated_pose = self.calibrator.build_calibrated_pose(device_pose) - self.yaw_rate, self.yaw_rate_std = calibrated_pose.angular_velocity.z, calibrated_pose.angular_velocity.z_std + + yaw_rate, yaw_rate_std = calibrated_pose.angular_velocity.z, calibrated_pose.angular_velocity.z_std + yaw_rate_valid = msg.angularVelocityDevice.valid + yaw_rate_valid = yaw_rate_valid and 0 < yaw_rate_std < 10 # rad/s + yaw_rate_valid = yaw_rate_valid and abs(yaw_rate) < 1 # rad/s + if not yaw_rate_valid: + # This is done to bound the yaw rate estimate when localizer values are invalid or calibrating + yaw_rate, yaw_rate_std = 0.0, np.radians(10.0) + self.observed_yaw_rate = yaw_rate localizer_roll, localizer_roll_std = device_pose.orientation.x, device_pose.orientation.x_std localizer_roll_std = np.radians(1) if np.isnan(localizer_roll_std) else localizer_roll_std - self.roll_valid = (localizer_roll_std < ROLL_STD_MAX) and (ROLL_MIN < localizer_roll < ROLL_MAX) and msg.sensorsOK - if self.roll_valid: + roll_valid = (localizer_roll_std < ROLL_STD_MAX) and (ROLL_MIN < localizer_roll < ROLL_MAX) and msg.sensorsOK + if roll_valid: roll = localizer_roll # Experimentally found multiplier of 2 to be best trade-off between stability and accuracy or similar? roll_std = 2 * localizer_roll_std @@ -66,24 +89,18 @@ def handle_log(self, t, which, msg): # This is done to bound the road roll estimate when localizer values are invalid roll = 0.0 roll_std = np.radians(10.0) - self.roll = clip(roll, self.roll - ROLL_MAX_DELTA, self.roll + ROLL_MAX_DELTA) - - yaw_rate_valid = msg.angularVelocityDevice.valid and self.calibrator.calib_valid - yaw_rate_valid = yaw_rate_valid and 0 < self.yaw_rate_std < 10 # rad/s - yaw_rate_valid = yaw_rate_valid and abs(self.yaw_rate) < 1 # rad/s + self.observed_roll = np.clip(roll, self.observed_roll - ROLL_MAX_DELTA, self.observed_roll + ROLL_MAX_DELTA) if self.active: if msg.posenetOK: - - if yaw_rate_valid: - self.kf.predict_and_observe(t, - ObservationKind.ROAD_FRAME_YAW_RATE, - np.array([[-self.yaw_rate]]), - np.array([np.atleast_2d(self.yaw_rate_std**2)])) + self.kf.predict_and_observe(t, + ObservationKind.ROAD_FRAME_YAW_RATE, + np.array([[-self.observed_yaw_rate]]), + np.array([np.atleast_2d(yaw_rate_std**2)])) self.kf.predict_and_observe(t, ObservationKind.ROAD_ROLL, - np.array([[self.roll]]), + np.array([[self.observed_roll]]), np.array([np.atleast_2d(roll_std**2)])) self.kf.predict_and_observe(t, ObservationKind.ANGLE_OFFSET_FAST, np.array([[0]])) @@ -99,21 +116,80 @@ def handle_log(self, t, which, msg): self.calibrator.feed_live_calib(msg) elif which == 'carState': - self.steering_angle = msg.steeringAngleDeg - self.speed = msg.vEgo + steering_angle = msg.steeringAngleDeg - in_linear_region = abs(self.steering_angle) < 45 - self.active = self.speed > MIN_ACTIVE_SPEED and in_linear_region + in_linear_region = abs(steering_angle) < 45 + self.observed_speed = msg.vEgo + self.active = self.observed_speed > MIN_ACTIVE_SPEED and in_linear_region if self.active: - self.kf.predict_and_observe(t, ObservationKind.STEER_ANGLE, np.array([[math.radians(msg.steeringAngleDeg)]])) - self.kf.predict_and_observe(t, ObservationKind.ROAD_FRAME_X_SPEED, np.array([[self.speed]])) + self.kf.predict_and_observe(t, ObservationKind.STEER_ANGLE, np.array([[np.radians(steering_angle)]])) + self.kf.predict_and_observe(t, ObservationKind.ROAD_FRAME_X_SPEED, np.array([[self.observed_speed]])) if not self.active: # Reset time when stopped so uncertainty doesn't grow self.kf.filter.set_filter_time(t) self.kf.filter.reset_rewind() + def get_msg(self, valid: bool, debug: bool = False) -> capnp._DynamicStructBuilder: + x = self.kf.x + P = np.sqrt(self.kf.P.diagonal()) + if not np.all(np.isfinite(x)): + cloudlog.error("NaN in liveParameters estimate. Resetting to default values") + self.reset(self.kf.t) + x = self.kf.x + + self.avg_angle_offset = np.clip(np.degrees(x[States.ANGLE_OFFSET].item()), + self.avg_angle_offset - MAX_ANGLE_OFFSET_DELTA, self.avg_angle_offset + MAX_ANGLE_OFFSET_DELTA) + self.angle_offset = np.clip(np.degrees(x[States.ANGLE_OFFSET].item() + x[States.ANGLE_OFFSET_FAST].item()), + self.angle_offset - MAX_ANGLE_OFFSET_DELTA, self.angle_offset + MAX_ANGLE_OFFSET_DELTA) + self.roll = np.clip(float(x[States.ROAD_ROLL].item()), self.roll - ROLL_MAX_DELTA, self.roll + ROLL_MAX_DELTA) + roll_std = float(P[States.ROAD_ROLL].item()) + if self.active and self.observed_speed > LOW_ACTIVE_SPEED: + # Account for the opposite signs of the yaw rates + # At low speeds, bumping into a curb can cause the yaw rate to be very high + sensors_valid = bool(abs(self.observed_speed * (x[States.YAW_RATE].item() + self.observed_yaw_rate)) < LATERAL_ACC_SENSOR_THRESHOLD) + else: + sensors_valid = True + self.avg_offset_valid = check_valid_with_hysteresis(self.avg_offset_valid, self.avg_angle_offset, OFFSET_MAX, OFFSET_LOWERED_MAX) + self.total_offset_valid = check_valid_with_hysteresis(self.total_offset_valid, self.angle_offset, OFFSET_MAX, OFFSET_LOWERED_MAX) + self.roll_valid = check_valid_with_hysteresis(self.roll_valid, self.roll, ROLL_MAX, ROLL_LOWERED_MAX) + + msg = messaging.new_message('liveParameters') + + msg.valid = valid + + liveParameters = msg.liveParameters + liveParameters.posenetValid = True + liveParameters.sensorValid = sensors_valid + liveParameters.steerRatio = float(x[States.STEER_RATIO].item()) + liveParameters.stiffnessFactor = float(x[States.STIFFNESS].item()) + liveParameters.roll = float(self.roll) + liveParameters.angleOffsetAverageDeg = float(self.avg_angle_offset) + liveParameters.angleOffsetDeg = float(self.angle_offset) + liveParameters.steerRatioValid = self.min_sr <= liveParameters.steerRatio <= self.max_sr + liveParameters.stiffnessFactorValid = 0.2 <= liveParameters.stiffnessFactor <= 5.0 + liveParameters.angleOffsetAverageValid = bool(self.avg_offset_valid) + liveParameters.angleOffsetValid = bool(self.total_offset_valid) + liveParameters.valid = all(( + liveParameters.angleOffsetAverageValid, + liveParameters.angleOffsetValid , + self.roll_valid, + roll_std < ROLL_STD_MAX, + liveParameters.stiffnessFactorValid, + liveParameters.steerRatioValid, + )) + liveParameters.steerRatioStd = float(P[States.STEER_RATIO].item()) + liveParameters.stiffnessFactorStd = float(P[States.STIFFNESS].item()) + liveParameters.angleOffsetAverageStd = float(P[States.ANGLE_OFFSET].item()) + liveParameters.angleOffsetFastStd = float(P[States.ANGLE_OFFSET_FAST].item()) + if debug: + liveParameters.debugFilterState = log.LiveParametersData.FilterState.new_message() + liveParameters.debugFilterState.value = x.tolist() + liveParameters.debugFilterState.std = P.tolist() + + return msg + def check_valid_with_hysteresis(current_valid: bool, val: float, threshold: float, lowered_threshold: float): if current_valid: @@ -123,69 +199,83 @@ def check_valid_with_hysteresis(current_valid: bool, val: float, threshold: floa return current_valid -def main(): - config_realtime_process([0, 1, 2, 3], 5) - - DEBUG = bool(int(os.getenv("DEBUG", "0"))) - REPLAY = bool(int(os.getenv("REPLAY", "0"))) - - pm = messaging.PubMaster(['liveParameters']) - sm = messaging.SubMaster(['livePose', 'liveCalibration', 'carState'], poll='livePose') +# TODO: Remove this function after few releases (added in 0.9.9) +def migrate_cached_vehicle_params_if_needed(params: Params): + last_parameters_data_old = params.get("LiveParameters") + last_parameters_data = params.get("LiveParametersV2") + if last_parameters_data_old is None or last_parameters_data is not None: + return - params_reader = Params() - # wait for stats about the car to come in from controls - cloudlog.info("paramsd is waiting for CarParams") - CP = messaging.log_from_bytes(params_reader.get("CarParams", block=True), car.CarParams) - cloudlog.info("paramsd got CarParams") + try: + last_parameters_msg = messaging.new_message('liveParameters') + last_parameters_msg.liveParameters.valid = True + last_parameters_msg.liveParameters.steerRatio = last_parameters_data_old['steerRatio'] + last_parameters_msg.liveParameters.stiffnessFactor = last_parameters_data_old['stiffnessFactor'] + last_parameters_msg.liveParameters.angleOffsetAverageDeg = last_parameters_data_old['angleOffsetAverageDeg'] + params.put("LiveParametersV2", last_parameters_msg.to_bytes(), block=True) + except Exception as e: + cloudlog.error(f"Failed to perform parameter migration: {e}") + params.remove("LiveParameters") - min_sr, max_sr = 0.5 * CP.steerRatio, 2.0 * CP.steerRatio - params = params_reader.get("LiveParameters") +def retrieve_initial_vehicle_params(params: Params, CP: car.CarParams, replay: bool, debug: bool): + last_parameters_data = params.get("LiveParametersV2") + last_carparams_data = params.get("CarParamsPrevRoute") - # Check if car model matches - if params is not None: - params = json.loads(params) - if params.get('carFingerprint', None) != CP.carFingerprint: - cloudlog.info("Parameter learner found parameters for wrong car.") - params = None + steer_ratio, stiffness_factor, angle_offset_deg, p_initial = CP.steerRatio, 1.0, 0.0, None - # Check if starting values are sane - if params is not None: + retrieve_success = False + if last_parameters_data is not None and last_carparams_data is not None: try: - steer_ratio_sane = min_sr <= params['steerRatio'] <= max_sr - if not steer_ratio_sane: - cloudlog.info(f"Invalid starting values found {params}") - params = None + with log.Event.from_bytes(last_parameters_data) as last_lp_msg, car.CarParams.from_bytes(last_carparams_data) as last_CP: + lp = last_lp_msg.liveParameters + # Check if car model matches + if last_CP.carFingerprint != CP.carFingerprint: + raise Exception("Car model mismatch") + + # Check if starting values are sane + min_sr, max_sr = 0.5 * CP.steerRatio, 2.0 * CP.steerRatio + steer_ratio_sane = min_sr <= lp.steerRatio <= max_sr + if not steer_ratio_sane: + raise Exception(f"Invalid starting values found {lp}") + + initial_filter_std = np.array(lp.debugFilterState.std) + if debug and len(initial_filter_std) != 0: + p_initial = np.diag(initial_filter_std) + + steer_ratio, stiffness_factor, angle_offset_deg = lp.steerRatio, lp.stiffnessFactor, lp.angleOffsetAverageDeg + retrieve_success = True except Exception as e: - cloudlog.info(f"Error reading params {params}: {str(e)}") - params = None - - # TODO: cache the params with the capnp struct - if params is None: - params = { - 'carFingerprint': CP.carFingerprint, - 'steerRatio': CP.steerRatio, - 'stiffnessFactor': 1.0, - 'angleOffsetAverageDeg': 0.0, - } - cloudlog.info("Parameter learner resetting to default values") + cloudlog.error(f"Failed to retrieve initial values: {e}") + params.remove("LiveParametersV2") - if not REPLAY: + if not replay: # When driving in wet conditions the stiffness can go down, and then be too low on the next drive # Without a way to detect this we have to reset the stiffness every drive - params['stiffnessFactor'] = 1.0 + stiffness_factor = 1.0 + + if not retrieve_success: + cloudlog.info("Parameter learner resetting to default values") + + return steer_ratio, stiffness_factor, angle_offset_deg, p_initial + + +def main(): + config_realtime_process([0, 1, 2, 3], 5) - pInitial = None - if DEBUG: - pInitial = np.array(params['debugFilterState']['std']) if 'debugFilterState' in params else None + DEBUG = bool(int(os.getenv("DEBUG", "0"))) + REPLAY = bool(int(os.getenv("REPLAY", "0"))) + + pm = messaging.PubMaster(['liveParameters']) + sm = messaging.SubMaster(['livePose', 'liveCalibration', 'carState'], poll='livePose') - learner = ParamsLearner(CP, params['steerRatio'], params['stiffnessFactor'], math.radians(params['angleOffsetAverageDeg']), pInitial) - angle_offset_average = params['angleOffsetAverageDeg'] - angle_offset = angle_offset_average - roll = 0.0 - avg_offset_valid = True - total_offset_valid = True - roll_valid = True + params = Params() + CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + + migrate_cached_vehicle_params_if_needed(params) + + steer_ratio, stiffness_factor, angle_offset_deg, pInitial = retrieve_initial_vehicle_params(params, CP, REPLAY, DEBUG) + learner = VehicleParamsLearner(CP, steer_ratio, stiffness_factor, np.radians(angle_offset_deg), pInitial) while True: sm.update() @@ -196,68 +286,13 @@ def main(): learner.handle_log(t, which, sm[which]) if sm.updated['livePose']: - x = learner.kf.x - P = np.sqrt(learner.kf.P.diagonal()) - if not all(map(math.isfinite, x)): - cloudlog.error("NaN in liveParameters estimate. Resetting to default values") - learner = ParamsLearner(CP, CP.steerRatio, 1.0, 0.0) - x = learner.kf.x - - angle_offset_average = clip(math.degrees(x[States.ANGLE_OFFSET].item()), - angle_offset_average - MAX_ANGLE_OFFSET_DELTA, angle_offset_average + MAX_ANGLE_OFFSET_DELTA) - angle_offset = clip(math.degrees(x[States.ANGLE_OFFSET].item() + x[States.ANGLE_OFFSET_FAST].item()), - angle_offset - MAX_ANGLE_OFFSET_DELTA, angle_offset + MAX_ANGLE_OFFSET_DELTA) - roll = clip(float(x[States.ROAD_ROLL].item()), roll - ROLL_MAX_DELTA, roll + ROLL_MAX_DELTA) - roll_std = float(P[States.ROAD_ROLL].item()) - if learner.active and learner.speed > LOW_ACTIVE_SPEED: - # Account for the opposite signs of the yaw rates - # At low speeds, bumping into a curb can cause the yaw rate to be very high - sensors_valid = bool(abs(learner.speed * (x[States.YAW_RATE].item() + learner.yaw_rate)) < LATERAL_ACC_SENSOR_THRESHOLD) - else: - sensors_valid = True - avg_offset_valid = check_valid_with_hysteresis(avg_offset_valid, angle_offset_average, OFFSET_MAX, OFFSET_LOWERED_MAX) - total_offset_valid = check_valid_with_hysteresis(total_offset_valid, angle_offset, OFFSET_MAX, OFFSET_LOWERED_MAX) - roll_valid = check_valid_with_hysteresis(roll_valid, roll, ROLL_MAX, ROLL_LOWERED_MAX) - - msg = messaging.new_message('liveParameters') - - liveParameters = msg.liveParameters - liveParameters.posenetValid = True - liveParameters.sensorValid = sensors_valid - liveParameters.steerRatio = float(x[States.STEER_RATIO].item()) - liveParameters.stiffnessFactor = float(x[States.STIFFNESS].item()) - liveParameters.roll = roll - liveParameters.angleOffsetAverageDeg = angle_offset_average - liveParameters.angleOffsetDeg = angle_offset - liveParameters.valid = all(( - avg_offset_valid, - total_offset_valid, - roll_valid, - roll_std < ROLL_STD_MAX, - 0.2 <= liveParameters.stiffnessFactor <= 5.0, - min_sr <= liveParameters.steerRatio <= max_sr, - )) - liveParameters.steerRatioStd = float(P[States.STEER_RATIO].item()) - liveParameters.stiffnessFactorStd = float(P[States.STIFFNESS].item()) - liveParameters.angleOffsetAverageStd = float(P[States.ANGLE_OFFSET].item()) - liveParameters.angleOffsetFastStd = float(P[States.ANGLE_OFFSET_FAST].item()) - if DEBUG: - liveParameters.debugFilterState = log.LiveParametersData.FilterState.new_message() - liveParameters.debugFilterState.value = x.tolist() - liveParameters.debugFilterState.std = P.tolist() - - msg.valid = sm.all_checks() + msg = learner.get_msg(sm.all_checks(), debug=DEBUG) + msg_dat = msg.to_bytes() if sm.frame % 1200 == 0: # once a minute - params = { - 'carFingerprint': CP.carFingerprint, - 'steerRatio': liveParameters.steerRatio, - 'stiffnessFactor': liveParameters.stiffnessFactor, - 'angleOffsetAverageDeg': liveParameters.angleOffsetAverageDeg, - } - params_reader.put_nonblocking("LiveParameters", json.dumps(params)) - - pm.send('liveParameters', msg) + params.put("LiveParametersV2", msg_dat) + + pm.send('liveParameters', msg_dat) if __name__ == "__main__": diff --git a/selfdrive/locationd/test/.gitignore b/selfdrive/locationd/test/.gitignore deleted file mode 100644 index 89f9ac04aac6c8..00000000000000 --- a/selfdrive/locationd/test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -out/ diff --git a/selfdrive/locationd/test/test_calibrationd.py b/selfdrive/locationd/test/test_calibrationd.py index df61b6a7c7e3ef..c90ce506abf52b 100644 --- a/selfdrive/locationd/test/test_calibrationd.py +++ b/selfdrive/locationd/test/test_calibrationd.py @@ -36,7 +36,7 @@ def test_read_saved_params(self): msg.liveCalibration.validBlocks = random.randint(1, 10) msg.liveCalibration.rpyCalib = [random.random() for _ in range(3)] msg.liveCalibration.height = [random.random() for _ in range(1)] - Params().put("CalibrationParams", msg.to_bytes()) + Params().put("CalibrationParams", msg.to_bytes(), block=True) c = Calibrator(param_put=True) np.testing.assert_allclose(msg.liveCalibration.rpyCalib, c.rpy) diff --git a/selfdrive/locationd/test/test_lagd.py b/selfdrive/locationd/test/test_lagd.py new file mode 100644 index 00000000000000..746f7ad4785f24 --- /dev/null +++ b/selfdrive/locationd/test/test_lagd.py @@ -0,0 +1,135 @@ +import random +import numpy as np +import time +import pytest + +from cereal import messaging, log, car +from openpilot.selfdrive.locationd.lagd import LateralLagEstimator, retrieve_initial_lag, masked_normalized_cross_correlation, \ + BLOCK_NUM_NEEDED, BLOCK_SIZE, MIN_OKAY_WINDOW_SEC +from openpilot.selfdrive.test.process_replay.migration import migrate, migrate_carParams +from openpilot.selfdrive.locationd.test.test_locationd_scenarios import TEST_ROUTE +from openpilot.common.params import Params +from openpilot.tools.lib.logreader import LogReader +from openpilot.system.hardware import PC + +MAX_ERR_FRAMES = 1 +DT = 0.05 + + +def process_messages(estimator, lag_frames, n_frames, vego=20.0, rejection_threshold=0.0): + for i in range(n_frames): + t = i * estimator.dt + desired_la = np.cos(10 * t) * 0.3 + actual_la = np.cos(10 * (t - lag_frames * estimator.dt)) * 0.3 + + # if sample is masked out, set it to desired value (no lag) + rejected = random.uniform(0, 1) < rejection_threshold + if rejected: + actual_la = desired_la + + desired_cuvature = float(desired_la / (vego ** 2)) + actual_yr = float(actual_la / vego) + msgs = [ + (t, "carControl", car.CarControl(latActive=not rejected)), + (t, "carState", car.CarState(vEgo=vego, steeringPressed=False)), + (t, "controlsState", log.ControlsState(desiredCurvature=desired_cuvature)), + (t, "livePose", log.LivePose(angularVelocityDevice=log.LivePose.XYZMeasurement(z=actual_yr, valid=True), + posenetOK=True, inputsOK=True)), + (t, "liveCalibration", log.LiveCalibrationData(rpyCalib=[0, 0, 0], calStatus=log.LiveCalibrationData.Status.calibrated)), + ] + for t, w, m in msgs: + estimator.handle_log(t, w, m) + estimator.update_points() + estimator.update_estimate() + + +class TestLagd: + def test_read_saved_params(self): + params = Params() + + lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) + CP = next(m for m in lr if m.which() == "carParams").carParams + + msg = messaging.new_message('liveDelay') + msg.liveDelay.lateralDelayEstimate = random.random() + msg.liveDelay.validBlocks = random.randint(1, 10) + params.put("LiveDelay", msg.to_bytes(), block=True) + params.put("CarParamsPrevRoute", CP.as_builder().to_bytes(), block=True) + + saved_lag_params = retrieve_initial_lag(params, CP) + assert saved_lag_params is not None + + lag, valid_blocks = saved_lag_params + assert lag == msg.liveDelay.lateralDelayEstimate + assert valid_blocks == msg.liveDelay.validBlocks + + def test_ncc(self): + lag_frames = random.randint(1, 19) + + desired_sig = np.sin(np.arange(0.0, 10.0, 0.1)) + actual_sig = np.sin(np.arange(0.0, 10.0, 0.1) - lag_frames * 0.1) + mask = np.ones(len(desired_sig), dtype=bool) + + corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] + assert np.argmax(corr) == lag_frames + + # add some noise + desired_sig += np.random.normal(0, 0.05, len(desired_sig)) + actual_sig += np.random.normal(0, 0.05, len(actual_sig)) + corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] + assert np.argmax(corr) in range(lag_frames - MAX_ERR_FRAMES, lag_frames + MAX_ERR_FRAMES + 1) + + # mask out 40% of the values, and make them noise + mask = np.random.choice([True, False], size=len(desired_sig), p=[0.6, 0.4]) + desired_sig[~mask] = np.random.normal(0, 1, size=np.sum(~mask)) + actual_sig[~mask] = np.random.normal(0, 1, size=np.sum(~mask)) + corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] + assert np.argmax(corr) in range(lag_frames - MAX_ERR_FRAMES, lag_frames + MAX_ERR_FRAMES + 1) + + def test_empty_estimator(self): + mocked_CP = car.CarParams(steerActuatorDelay=0.8) + estimator = LateralLagEstimator(mocked_CP, DT) + msg = estimator.get_msg(True) + assert msg.liveDelay.status == 'unestimated' + assert np.allclose(msg.liveDelay.lateralDelay, estimator.initial_lag) + assert np.allclose(msg.liveDelay.lateralDelayEstimate, estimator.initial_lag) + assert msg.liveDelay.validBlocks == 0 + assert msg.liveDelay.calPerc == 0 + + def test_estimator_basics(self, subtests): + for lag_frames in range(3, 10): + with subtests.test(msg=f"lag_frames={lag_frames}"): + mocked_CP = car.CarParams(steerActuatorDelay=0.8) + estimator = LateralLagEstimator(mocked_CP, DT, min_recovery_buffer_sec=0.0, min_yr=0.0) + process_messages(estimator, lag_frames, int(MIN_OKAY_WINDOW_SEC / DT) + BLOCK_NUM_NEEDED * BLOCK_SIZE) + msg = estimator.get_msg(True) + assert msg.liveDelay.status == 'estimated' + assert np.allclose(msg.liveDelay.lateralDelay, lag_frames * DT, atol=0.01) + assert np.allclose(msg.liveDelay.lateralDelayEstimate, lag_frames * DT, atol=0.01) + assert np.allclose(msg.liveDelay.lateralDelayEstimateStd, 0.0, atol=0.01) + assert msg.liveDelay.validBlocks == BLOCK_NUM_NEEDED + assert msg.liveDelay.calPerc == 100 + + def test_estimator_masking(self): + mocked_CP, lag_frames = car.CarParams(steerActuatorDelay=0.8), random.randint(3, 19) + estimator = LateralLagEstimator(mocked_CP, DT, min_recovery_buffer_sec=0.0, min_yr=0.0, min_valid_block_count=1) + process_messages(estimator, lag_frames, (int(MIN_OKAY_WINDOW_SEC / DT) + BLOCK_SIZE) * 2, rejection_threshold=0.4) + msg = estimator.get_msg(True) + assert np.allclose(msg.liveDelay.lateralDelayEstimate, lag_frames * DT, atol=0.01) + assert np.allclose(msg.liveDelay.lateralDelayEstimateStd, 0.0, atol=0.01) + assert msg.liveDelay.calPerc == 100 + + @pytest.mark.skipif(PC, reason="only on device") + def test_estimator_performance(self): + mocked_CP = car.CarParams(steerActuatorDelay=0.8) + estimator = LateralLagEstimator(mocked_CP, DT) + + ds = [] + for _ in range(1000): + st = time.perf_counter() + estimator.update_points() + estimator.update_estimate() + d = time.perf_counter() - st + ds.append(d) + + assert np.mean(ds) < DT diff --git a/selfdrive/locationd/test/test_locationd.py b/selfdrive/locationd/test/test_locationd.py deleted file mode 100644 index 74ac7d2962de6d..00000000000000 --- a/selfdrive/locationd/test/test_locationd.py +++ /dev/null @@ -1,89 +0,0 @@ -import pytest -import json -import random -import time -import capnp - -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST -from openpilot.common.params import Params -from openpilot.common.transformations.coordinates import ecef2geodetic - -from openpilot.system.manager.process_config import managed_processes - - -class TestLocationdProc: - LLD_MSGS = ['gpsLocationExternal', 'cameraOdometry', 'carState', 'liveCalibration', - 'accelerometer', 'gyroscope', 'magnetometer'] - - def setup_method(self): - self.pm = messaging.PubMaster(self.LLD_MSGS) - - self.params = Params() - self.params.put_bool("UbloxAvailable", True) - managed_processes['locationd'].prepare() - managed_processes['locationd'].start() - - def teardown_method(self): - managed_processes['locationd'].stop() - - def get_msg(self, name, t): - try: - msg = messaging.new_message(name) - except capnp.lib.capnp.KjException: - msg = messaging.new_message(name, 0) - - if name == "gpsLocationExternal": - msg.gpsLocationExternal.flags = 1 - msg.gpsLocationExternal.hasFix = True - msg.gpsLocationExternal.verticalAccuracy = 1.0 - msg.gpsLocationExternal.speedAccuracy = 1.0 - msg.gpsLocationExternal.bearingAccuracyDeg = 1.0 - msg.gpsLocationExternal.vNED = [0.0, 0.0, 0.0] - msg.gpsLocationExternal.latitude = float(self.lat) - msg.gpsLocationExternal.longitude = float(self.lon) - msg.gpsLocationExternal.unixTimestampMillis = t * 1e6 - msg.gpsLocationExternal.altitude = float(self.alt) - #if name == "gnssMeasurements": - # msg.gnssMeasurements.measTime = t - # msg.gnssMeasurements.positionECEF.value = [self.x , self.y, self.z] - # msg.gnssMeasurements.positionECEF.std = [0,0,0] - # msg.gnssMeasurements.positionECEF.valid = True - # msg.gnssMeasurements.velocityECEF.value = [] - # msg.gnssMeasurements.velocityECEF.std = [0,0,0] - # msg.gnssMeasurements.velocityECEF.valid = True - elif name == 'cameraOdometry': - msg.cameraOdometry.rot = [0.0, 0.0, 0.0] - msg.cameraOdometry.rotStd = [0.0, 0.0, 0.0] - msg.cameraOdometry.trans = [0.0, 0.0, 0.0] - msg.cameraOdometry.transStd = [0.0, 0.0, 0.0] - msg.logMonoTime = t - msg.valid = True - return msg - - def test_params_gps(self): - random.seed(123489234) - self.params.remove('LastGPSPosition') - - self.x = -2710700 + (random.random() * 1e5) - self.y = -4280600 + (random.random() * 1e5) - self.z = 3850300 + (random.random() * 1e5) - self.lat, self.lon, self.alt = ecef2geodetic([self.x, self.y, self.z]) - - # get fake messages at the correct frequency, listed in services.py - msgs = [] - for sec in range(65): - for name in self.LLD_MSGS: - for j in range(int(SERVICE_LIST[name].frequency)): - msgs.append(self.get_msg(name, int((sec + j / SERVICE_LIST[name].frequency) * 1e9))) - - for msg in sorted(msgs, key=lambda x: x.logMonoTime): - self.pm.send(msg.which(), msg) - if msg.which() == "cameraOdometry": - self.pm.wait_for_readers_to_update(msg.which(), 0.1, dt=0.005) - time.sleep(1) # wait for async params write - - lastGPS = json.loads(self.params.get('LastGPSPosition')) - assert lastGPS['latitude'] == pytest.approx(self.lat, abs=0.001) - assert lastGPS['longitude'] == pytest.approx(self.lon, abs=0.001) - assert lastGPS['altitude'] == pytest.approx(self.alt, abs=0.001) diff --git a/selfdrive/locationd/test/test_locationd_scenarios.py b/selfdrive/locationd/test/test_locationd_scenarios.py index bacb2a10a71c0a..69f2ca2821b98a 100644 --- a/selfdrive/locationd/test/test_locationd_scenarios.py +++ b/selfdrive/locationd/test/test_locationd_scenarios.py @@ -1,9 +1,9 @@ -import pytest import numpy as np from collections import defaultdict from enum import Enum from openpilot.tools.lib.logreader import LogReader +from openpilot.selfdrive.locationd.lagd import masked_symmetric_moving_average from openpilot.selfdrive.test.process_replay.migration import migrate_all from openpilot.selfdrive.test.process_replay.process_replay import replay_process_with_name @@ -16,22 +16,26 @@ 'inputs_flag': ['inputsOK'], 'sensors_flag': ['sensorsOK'], } +SMOOTH_FIELDS = ['yaw_rate', 'roll'] JUNK_IDX = 100 +CONSISTENT_SPIKES_COUNT = 10 class Scenario(Enum): BASE = 'base' - GPS_OFF = 'gps_off' - GPS_OFF_MIDWAY = 'gps_off_midway' - GPS_ON_MIDWAY = 'gps_on_midway' - GPS_TUNNEL = 'gps_tunnel' GYRO_OFF = 'gyro_off' GYRO_SPIKE_MIDWAY = 'gyro_spike_midway' + GYRO_CONSISTENT_SPIKES = 'gyro_consistent_spikes' ACCEL_OFF = 'accel_off' ACCEL_SPIKE_MIDWAY = 'accel_spike_midway' + ACCEL_CONSISTENT_SPIKES = 'accel_consistent_spikes' + SENSOR_TIMING_SPIKE_MIDWAY = 'timing_spikes' + SENSOR_TIMING_CONSISTENT_SPIKES = 'timing_consistent_spikes' def get_select_fields_data(logs): + def sig_smooth(signal): + return masked_symmetric_moving_average(signal, np.ones_like(signal), 5, 1.0) def get_nested_keys(msg, keys): val = None for key in keys: @@ -44,59 +48,54 @@ def get_nested_keys(msg, keys): data[key].append(get_nested_keys(msg, fields)) for key in data: data[key] = np.array(data[key][JUNK_IDX:], dtype=float) + if key in SMOOTH_FIELDS: + data[key] = sig_smooth(data[key]) return data +def modify_logs_midway(logs, which, count, fn): + non_which = [x for x in logs if x.which() != which] + which = [x for x in logs if x.which() == which] + temps = which[len(which) // 2:len(which) // 2 + count] + for i, temp in enumerate(temps): + temp = temp.as_builder() + fn(temp) + which[len(which) // 2 + i] = temp.as_reader() + return sorted(non_which + which, key=lambda x: x.logMonoTime) + + def run_scenarios(scenario, logs): if scenario == Scenario.BASE: pass - elif scenario == Scenario.GPS_OFF: - logs = sorted([x for x in logs if x.which() not in GPS_MESSAGES], key=lambda x: x.logMonoTime) - - elif scenario == Scenario.GPS_OFF_MIDWAY: - non_gps = [x for x in logs if x.which() not in GPS_MESSAGES] - gps = [x for x in logs if x.which() in GPS_MESSAGES] - logs = sorted(non_gps + gps[: len(gps) // 2], key=lambda x: x.logMonoTime) - - elif scenario == Scenario.GPS_ON_MIDWAY: - non_gps = [x for x in logs if x.which() not in GPS_MESSAGES] - gps = [x for x in logs if x.which() in GPS_MESSAGES] - logs = sorted(non_gps + gps[len(gps) // 2:], key=lambda x: x.logMonoTime) - - elif scenario == Scenario.GPS_TUNNEL: - non_gps = [x for x in logs if x.which() not in GPS_MESSAGES] - gps = [x for x in logs if x.which() in GPS_MESSAGES] - logs = sorted(non_gps + gps[:len(gps) // 4] + gps[-len(gps) // 4:], key=lambda x: x.logMonoTime) - elif scenario == Scenario.GYRO_OFF: logs = sorted([x for x in logs if x.which() != 'gyroscope'], key=lambda x: x.logMonoTime) - elif scenario == Scenario.GYRO_SPIKE_MIDWAY: - non_gyro = [x for x in logs if x.which() not in 'gyroscope'] - gyro = [x for x in logs if x.which() in 'gyroscope'] - temp = gyro[len(gyro) // 2].as_builder() - temp.gyroscope.gyroUncalibrated.v[0] += 3.0 - gyro[len(gyro) // 2] = temp.as_reader() - logs = sorted(non_gyro + gyro, key=lambda x: x.logMonoTime) + elif scenario == Scenario.GYRO_SPIKE_MIDWAY or scenario == Scenario.GYRO_CONSISTENT_SPIKES: + def gyro_spike(msg): + msg.gyroscope.gyroUncalibrated.v[0] += 3.0 + count = 1 if scenario == Scenario.GYRO_SPIKE_MIDWAY else CONSISTENT_SPIKES_COUNT + logs = modify_logs_midway(logs, 'gyroscope', count, gyro_spike) elif scenario == Scenario.ACCEL_OFF: logs = sorted([x for x in logs if x.which() != 'accelerometer'], key=lambda x: x.logMonoTime) - elif scenario == Scenario.ACCEL_SPIKE_MIDWAY: - non_accel = [x for x in logs if x.which() not in 'accelerometer'] - accel = [x for x in logs if x.which() in 'accelerometer'] - temp = accel[len(accel) // 2].as_builder() - temp.accelerometer.acceleration.v[0] += 10.0 - accel[len(accel) // 2] = temp.as_reader() - logs = sorted(non_accel + accel, key=lambda x: x.logMonoTime) + elif scenario == Scenario.ACCEL_SPIKE_MIDWAY or scenario == Scenario.ACCEL_CONSISTENT_SPIKES: + def acc_spike(msg): + msg.accelerometer.acceleration.v[0] += 100.0 + count = 1 if scenario == Scenario.ACCEL_SPIKE_MIDWAY else CONSISTENT_SPIKES_COUNT + logs = modify_logs_midway(logs, 'accelerometer', count, acc_spike) + + elif scenario == Scenario.SENSOR_TIMING_SPIKE_MIDWAY or scenario == Scenario.SENSOR_TIMING_CONSISTENT_SPIKES: + def timing_spike(msg): + msg.accelerometer.timestamp -= int(0.150 * 1e9) + count = 1 if scenario == Scenario.SENSOR_TIMING_SPIKE_MIDWAY else CONSISTENT_SPIKES_COUNT + logs = modify_logs_midway(logs, 'accelerometer', count, timing_spike) replayed_logs = replay_process_with_name(name='locationd', lr=logs) return get_select_fields_data(logs), get_select_fields_data(replayed_logs) -@pytest.mark.xdist_group("test_locationd_scenarios") -@pytest.mark.shared_download_cache class TestLocationdScenarios: """ Test locationd with different scenarios. In all these scenarios, we expect the following: @@ -116,53 +115,8 @@ def test_base(self): - roll: unchanged """ orig_data, replayed_data = run_scenarios(Scenario.BASE, self.logs) - assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.25)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) - - def test_gps_off(self): - """ - Test: no GPS message for the entire segment - Expected Result: - - yaw_rate: unchanged - - roll: - - gpsOK: False - """ - orig_data, replayed_data = run_scenarios(Scenario.GPS_OFF, self.logs) - assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.25)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) - - def test_gps_off_midway(self): - """ - Test: no GPS message for the second half of the segment - Expected Result: - - yaw_rate: unchanged - - roll: - """ - orig_data, replayed_data = run_scenarios(Scenario.GPS_OFF_MIDWAY, self.logs) - assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.25)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) - - def test_gps_on_midway(self): - """ - Test: no GPS message for the first half of the segment - Expected Result: - - yaw_rate: unchanged - - roll: - """ - orig_data, replayed_data = run_scenarios(Scenario.GPS_ON_MIDWAY, self.logs) - assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.25)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(1.5)) - - def test_gps_tunnel(self): - """ - Test: no GPS message for the middle section of the segment - Expected Result: - - yaw_rate: unchanged - - roll: - """ - orig_data, replayed_data = run_scenarios(Scenario.GPS_TUNNEL, self.logs) - assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.25)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) + assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.35)) + assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.35)) def test_gyro_off(self): """ @@ -177,7 +131,7 @@ def test_gyro_off(self): assert np.allclose(replayed_data['roll'], 0.0) assert np.all(replayed_data['sensors_flag'] == 0.0) - def test_gyro_spikes(self): + def test_gyro_spike(self): """ Test: a gyroscope spike in the middle of the segment Expected Result: @@ -186,10 +140,19 @@ def test_gyro_spikes(self): - inputsOK: False for some time after the spike, True for the rest """ orig_data, replayed_data = run_scenarios(Scenario.GYRO_SPIKE_MIDWAY, self.logs) - assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.25)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) - assert np.diff(replayed_data['inputs_flag'])[499] == -1.0 - assert np.diff(replayed_data['inputs_flag'])[696] == 1.0 + assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.35)) + assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.35)) + assert np.all(replayed_data['inputs_flag'] == orig_data['inputs_flag']) + assert np.all(replayed_data['sensors_flag'] == orig_data['sensors_flag']) + + def test_consistent_gyro_spikes(self): + """ + Test: consistent timing spikes for N gyroscope messages in the middle of the segment + Expected Result: inputsOK becomes False after N of bad measurements + """ + orig_data, replayed_data = run_scenarios(Scenario.GYRO_CONSISTENT_SPIKES, self.logs) + assert np.diff(replayed_data['inputs_flag'])[501] == -1.0 + assert np.diff(replayed_data['inputs_flag'])[708] == 1.0 def test_accel_off(self): """ @@ -204,12 +167,30 @@ def test_accel_off(self): assert np.allclose(replayed_data['roll'], 0.0) assert np.all(replayed_data['sensors_flag'] == 0.0) - def test_accel_spikes(self): + def test_accel_spike(self): """ ToDo: Test: an accelerometer spike in the middle of the segment Expected Result: Right now, the kalman filter is not robust to small spikes like it is to gyroscope spikes. """ orig_data, replayed_data = run_scenarios(Scenario.ACCEL_SPIKE_MIDWAY, self.logs) - assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.25)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) + assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.35)) + assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.35)) + + def test_single_timing_spike(self): + """ + Test: timing of 150ms off for the single accelerometer message in the middle of the segment + Expected Result: the message is ignored, and inputsOK is False for that time + """ + orig_data, replayed_data = run_scenarios(Scenario.SENSOR_TIMING_SPIKE_MIDWAY, self.logs) + assert np.all(replayed_data['inputs_flag'] == orig_data['inputs_flag']) + assert np.all(replayed_data['sensors_flag'] == orig_data['sensors_flag']) + + def test_consistent_timing_spikes(self): + """ + Test: consistent timing spikes for N accelerometer messages in the middle of the segment + Expected Result: inputsOK becomes False after N of bad measurements + """ + orig_data, replayed_data = run_scenarios(Scenario.SENSOR_TIMING_CONSISTENT_SPIKES, self.logs) + assert np.diff(replayed_data['inputs_flag'])[501] == -1.0 + assert np.diff(replayed_data['inputs_flag'])[707] == 1.0 diff --git a/selfdrive/locationd/test/test_paramsd.py b/selfdrive/locationd/test/test_paramsd.py new file mode 100644 index 00000000000000..1a4d348e945d3b --- /dev/null +++ b/selfdrive/locationd/test/test_paramsd.py @@ -0,0 +1,67 @@ +import random +import numpy as np + +from cereal import messaging +from openpilot.selfdrive.locationd.paramsd import retrieve_initial_vehicle_params, migrate_cached_vehicle_params_if_needed +from openpilot.selfdrive.locationd.models.car_kf import CarKalman +from openpilot.selfdrive.locationd.test.test_locationd_scenarios import TEST_ROUTE +from openpilot.selfdrive.test.process_replay.migration import migrate, migrate_carParams +from openpilot.common.params import Params +from openpilot.tools.lib.logreader import LogReader + + +def get_random_live_parameters(CP): + msg = messaging.new_message("liveParameters") + msg.liveParameters.steerRatio = (random.random() + 0.5) * CP.steerRatio + msg.liveParameters.stiffnessFactor = random.random() + msg.liveParameters.angleOffsetAverageDeg = random.random() + msg.liveParameters.debugFilterState.std = [random.random() for _ in range(CarKalman.P_initial.shape[0])] + return msg + + +class TestParamsd: + def test_read_saved_params(self): + params = Params() + + lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) + CP = next(m for m in lr if m.which() == "carParams").carParams + + msg = get_random_live_parameters(CP) + params.put("LiveParametersV2", msg.to_bytes(), block=True) + params.put("CarParamsPrevRoute", CP.as_builder().to_bytes(), block=True) + + migrate_cached_vehicle_params_if_needed(params) # this is not tested here but should not mess anything up or throw an error + sr, sf, offset, p_init = retrieve_initial_vehicle_params(params, CP, replay=True, debug=True) + np.testing.assert_allclose(sr, msg.liveParameters.steerRatio) + np.testing.assert_allclose(sf, msg.liveParameters.stiffnessFactor) + np.testing.assert_allclose(offset, msg.liveParameters.angleOffsetAverageDeg) + np.testing.assert_equal(p_init.shape, CarKalman.P_initial.shape) + np.testing.assert_allclose(np.diagonal(p_init), msg.liveParameters.debugFilterState.std) + + # TODO Remove this test after the support for old format is removed + def test_read_saved_params_old_format(self): + params = Params() + + lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) + CP = next(m for m in lr if m.which() == "carParams").carParams + + msg = get_random_live_parameters(CP) + params.put("LiveParameters", msg.liveParameters.to_dict(), block=True) + params.put("CarParamsPrevRoute", CP.as_builder().to_bytes(), block=True) + params.remove("LiveParametersV2") + + migrate_cached_vehicle_params_if_needed(params) + sr, sf, offset, _ = retrieve_initial_vehicle_params(params, CP, replay=True, debug=True) + np.testing.assert_allclose(sr, msg.liveParameters.steerRatio) + np.testing.assert_allclose(sf, msg.liveParameters.stiffnessFactor) + np.testing.assert_allclose(offset, msg.liveParameters.angleOffsetAverageDeg) + assert params.get("LiveParametersV2") is not None + + def test_read_saved_params_corrupted_old_format(self): + params = Params() + params.put("LiveParameters", {}, block=True) + params.remove("LiveParametersV2") + + migrate_cached_vehicle_params_if_needed(params) + assert params.get("LiveParameters") is None + assert params.get("LiveParametersV2") is None diff --git a/selfdrive/locationd/test/test_torqued.py b/selfdrive/locationd/test/test_torqued.py new file mode 100644 index 00000000000000..53f3120c362dfc --- /dev/null +++ b/selfdrive/locationd/test/test_torqued.py @@ -0,0 +1,25 @@ +from cereal import car +from openpilot.selfdrive.locationd.torqued import TorqueEstimator + + +def test_cal_percent(): + est = TorqueEstimator(car.CarParams()) + msg = est.get_msg() + assert msg.liveTorqueParameters.calPerc == 0 + + for (low, high), min_pts in zip(est.filtered_points.buckets.keys(), + est.filtered_points.buckets_min_points.values(), strict=True): + for _ in range(int(min_pts)): + est.filtered_points.add_point((low + high) / 2.0, 0.0) + + # enough bucket points, but not enough total points + msg = est.get_msg() + assert msg.liveTorqueParameters.calPerc == (len(est.filtered_points) / est.min_points_total * 100 + 100) / 2 + + # add enough points to bucket with most capacity + key = list(est.filtered_points.buckets)[0] + for _ in range(est.min_points_total - len(est.filtered_points)): + est.filtered_points.add_point((key[0] + key[1]) / 2.0, 0.0) + + msg = est.get_msg() + assert msg.liveTorqueParameters.calPerc == 100 diff --git a/selfdrive/locationd/torqued.py b/selfdrive/locationd/torqued.py index 2b7cc62527be97..16468f7055f3aa 100755 --- a/selfdrive/locationd/torqued.py +++ b/selfdrive/locationd/torqued.py @@ -1,14 +1,15 @@ #!/usr/bin/env python3 +import os import numpy as np from collections import deque, defaultdict import cereal.messaging as messaging from cereal import car, log +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY from openpilot.common.params import Params from openpilot.common.realtime import config_realtime_process, DT_MDL from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.swaglog import cloudlog -from openpilot.selfdrive.controls.lib.vehicle_model import ACCELERATION_DUE_TO_GRAVITY from openpilot.selfdrive.locationd.helpers import PointBuckets, ParameterEstimator, PoseCalibrator, Pose HISTORY = 5 # secs @@ -32,7 +33,7 @@ MIN_ENGAGE_BUFFER = 2 # secs VERSION = 1 # bump this to invalidate old parameter caches -ALLOWED_CARS = ['toyota', 'hyundai'] +ALLOWED_CARS = ['toyota', 'hyundai', 'rivian', 'honda', 'volkswagen'] def slope2rot(slope): @@ -52,7 +53,7 @@ def add_point(self, x, y): class TorqueEstimator(ParameterEstimator): def __init__(self, CP, decimated=False, track_all_points=False): self.hist_len = int(HISTORY / DT_MDL) - self.lag = CP.steerActuatorDelay + .2 # from controlsd + self.lag = 0.0 self.track_all_points = track_all_points # for offline analysis, without max lateral accel or max steer torque filters if decimated: self.min_bucket_points = MIN_BUCKET_POINTS / 10 @@ -71,7 +72,7 @@ def __init__(self, CP, decimated=False, track_all_points=False): self.offline_friction = 0.0 self.offline_latAccelFactor = 0.0 self.resets = 0.0 - self.use_params = CP.carName in ALLOWED_CARS and CP.lateralTuning.which() == 'torque' + self.use_params = CP.brand in ALLOWED_CARS and CP.lateralTuning.which() == 'torque' if CP.lateralTuning.which() == 'torque': self.offline_friction = CP.lateralTuning.torque.friction @@ -167,7 +168,7 @@ def handle_log(self, t, which, msg): self.raw_points["lat_active"].append(msg.latActive) elif which == "carOutput": self.raw_points["carOutput_t"].append(t + self.lag) - self.raw_points["steer_torque"].append(-msg.actuatorsOutput.steer) + self.raw_points["steer_torque"].append(-msg.actuatorsOutput.torque) elif which == "carState": self.raw_points["carState_t"].append(t + self.lag) # TODO: check if high aEgo affects resulting lateral accel @@ -175,10 +176,13 @@ def handle_log(self, t, which, msg): self.raw_points["steer_override"].append(msg.steeringPressed) elif which == "liveCalibration": self.calibrator.feed_live_calib(msg) - + elif which == "liveDelay": + self.lag = msg.lateralDelay # calculate lateral accel from past steering torque elif which == "livePose": - if len(self.raw_points['steer_torque']) == self.hist_len: + is_valid = msg.angularVelocityDevice.valid and msg.orientationNED.valid and msg.inputsOK and msg.sensorsOK and msg.posenetOK + if len(self.raw_points['steer_torque']) == self.hist_len and is_valid: + t = msg.timestamp * 1e-9 device_pose = Pose.from_live_pose(msg) calibrated_pose = self.calibrator.build_calibrated_pose(device_pose) angular_velocity_calibrated = calibrated_pose.angular_velocity @@ -232,6 +236,7 @@ def get_msg(self, valid=True, with_points=False): liveTorqueParameters.latAccelOffsetFiltered = float(self.filtered_params['latAccelOffset'].x) liveTorqueParameters.frictionCoefficientFiltered = float(self.filtered_params['frictionCoefficient'].x) liveTorqueParameters.totalBucketPoints = len(self.filtered_points) + liveTorqueParameters.calPerc = self.filtered_points.get_valid_percent() liveTorqueParameters.decay = self.decay liveTorqueParameters.maxResets = self.resets return msg @@ -240,8 +245,10 @@ def get_msg(self, valid=True, with_points=False): def main(demo=False): config_realtime_process([0, 1, 2, 3], 5) + DEBUG = bool(int(os.getenv("DEBUG", "0"))) + pm = messaging.PubMaster(['liveTorqueParameters']) - sm = messaging.SubMaster(['carControl', 'carOutput', 'carState', 'liveCalibration', 'livePose'], poll='livePose') + sm = messaging.SubMaster(['carControl', 'carOutput', 'carState', 'liveCalibration', 'livePose', 'liveDelay'], poll='livePose') params = Params() estimator = TorqueEstimator(messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams)) @@ -256,12 +263,12 @@ def main(demo=False): # 4Hz driven by livePose if sm.frame % 5 == 0: - pm.send('liveTorqueParameters', estimator.get_msg(valid=sm.all_checks())) + pm.send('liveTorqueParameters', estimator.get_msg(valid=sm.all_checks(), with_points=DEBUG)) # Cache points every 60 seconds while onroad if sm.frame % 240 == 0: msg = estimator.get_msg(valid=sm.all_checks(), with_points=True) - params.put_nonblocking("LiveTorqueParameters", msg.to_bytes()) + params.put("LiveTorqueParameters", msg.to_bytes()) if __name__ == "__main__": diff --git a/selfdrive/mapd/__init__.py b/selfdrive/mapd/__init__.py new file mode 100644 index 00000000000000..84f2ead2c0ca9a --- /dev/null +++ b/selfdrive/mapd/__init__.py @@ -0,0 +1 @@ +# OSM map daemon: GPS → OpenStreetMap speed limit → liveMapDataNAP diff --git a/selfdrive/mapd/constants.py b/selfdrive/mapd/constants.py new file mode 100644 index 00000000000000..383a3363506c8b --- /dev/null +++ b/selfdrive/mapd/constants.py @@ -0,0 +1,134 @@ +"""Map-speed policy and OSM lookup constants.""" + +# NAPMapSpeedMode +MODE_OFF = 0 +MODE_DISPLAY = 1 +MODE_CAP = 2 +MODE_FOLLOW = 3 + +# Pedal-mode software cruise is the only path that may change vCruise from maps. +# No-pedal / pcmCruise stock CC is display-only (do not spoof stalk to chase limits). +# Follow: a stalk set (above or below posted `a`) holds until posted changes to `b`. +# Stalk +/- while engaged. 0.4 kph ≈ 0.25 mph; ignore noise / engage 0↔set. +MANUAL_SET_EPS_KPH = 0.4 +# Posted OSM maxspeed treated as the same sign (limits are 5 mph / 10 kph steps). +POSTED_LIMIT_EPS_KPH = 1.0 + +# Spatial match +MAX_MATCH_DISTANCE_M = 35.0 +# Current-way snap uses this as a *penalty* so GPS heading noise still locks +# the carriageway. Next-limit matching uses it as a *hard* gate on the acute +# angle min(Δ, 180−Δ): reverse-digitized along-route ways (Δ ≈ 180°) stay +# on-route; cross streets (~90°) must not become nextSpeedLimit — denser MN +# statutory fills made those geometrically close. +HEADING_ALIGN_DEG = 55.0 +# Justin measured 1.5 s GNSS lag. Raises posted when v_ego * this along +# heading is already in a higher zone. Decreases keep GPS posted and ease +# with kin+110 m (lead subtracts from next_distance). Meters scale with +# speed (50 mph → ~33.5 m, 60 mph → ~40 m); not a fixed offset. +OSM_SIGN_LEAD_S = 1.5 +# Ignore a lower OSM limit that only lasts ~250 ft along the travel heading. +# Cross-street bleed and intersection stubs look like a short zone on the +# main road; real posted drops (US 12 60→50 is hundreds of meters) are longer. +# Measured on the contiguous same-limit run, not the first OSM way_id alone +# (a 76 m first town piece plus more 30 is a real zone). Additive to +# bearing / class route continuity — not a corridor hardcode. +MIN_ZONE_LENGTH_M = 76.0 # ~250 ft +# Heading-aligned probes for nextSpeedLimit (any change). Policy uses decreases only. +# Geodesic 40 m steps can skip a short intermediate limit (US 12 60→50 before 30); +# lookup also walks the matched way to its end, then the next way. +LOOKAHEAD_STEP_M = 40.0 +LOOKAHEAD_MAX_M = 600.0 +LOOKAHEAD_M = tuple(float(d) for d in range(int(LOOKAHEAD_STEP_M), int(LOOKAHEAD_MAX_M) + 1, int(LOOKAHEAD_STEP_M))) +SEARCH_PAD_DEG = 0.001 # ~110 m of lat + +# NAPMapSpeedLookahead: 0=off, 1=late, 2=normal, 3=early +LOOKAHEAD_OFF = 0 +LOOKAHEAD_LATE = 1 +LOOKAHEAD_NORMAL = 2 +LOOKAHEAD_EARLY = 3 +# Locked Accel-5 brake a (slider is climb-only). Stay under Tesla pre-AP clip (−1.5). +# Margin is extra start distance on kinematic d=(u²−v²)/(2a). Justin's 50→30 was +# ~110 m late at the sign (42 mph vs 30); every decrease gets kin + this margin. +DECREASE_START_MARGIN_M = 110.0 +# (comfort decel m/s², extra margin m, max start distance m) +LOOKAHEAD_TUNING = { + LOOKAHEAD_OFF: (0.0, 0.0, 0.0), + LOOKAHEAD_LATE: (1.20, DECREASE_START_MARGIN_M, 360.0), + LOOKAHEAD_NORMAL: (0.80, DECREASE_START_MARGIN_M, 600.0), + LOOKAHEAD_EARLY: (0.55, DECREASE_START_MARGIN_M + 120.0, 600.0), +} +MIN_DECREASE_MS = 0.45 # ~1 mph; ignore jitter. A 10 mph drop (60→50) is not filtered. + +# NAPMapSpeedAccel: 1=gentlest, 5=default, 10=quickest. Scales Follow *accel* +# (MAX rising / speeding up). Brake to a lower MAX is locked at ACCEL_DEFAULT. +ACCEL_MIN = 1 +ACCEL_DEFAULT = 5 +ACCEL_MAX = 10 +# factor(1)=0.45, factor(5)=1.00, factor(10)=2.00 +ACCEL_FACTOR_LO = 0.45 +ACCEL_FACTOR_HI = 2.00 +A_CLAMP_MIN = 0.30 # m/s² +A_CLAMP_MAX = 1.60 # m/s²; below MPC cruise min accel magnitude and COMFORT_BRAKE +# Track HUD MAX when ego is faster. MPC cruise_obstacle sits ~safe-follow +# distance ahead (~240 m at 70 mph) and does not bind inside the 10 s horizon +# for a typical posted-limit drop, so v_cruise alone will not command decel. +TRACK_DEADBAND_MS = 0.40 # ~0.9 mph; ignore set-speed / GPS jitter +TRACK_TAPER_MS = 2.00 # brake / default; ~4.5 mph; full comfort a above this error +# Accel climb gradient (open-road / MAX / lead gap-close — same curve). +# Accel 1 baby-steps the last ~5 mph; Accel 2–6 progressive; Accel 7–10 +# stay brisk almost to deadband (one plateau, not hotter toward 10). +TRACK_TAPER_ACCEL_LO_MS = 2.24 # Accel 1; 5 mph +TRACK_TAPER_ACCEL_HI_MS = 0.55 # Accel 7–10; ~1.2 mph + +# Default offline DB location on comma 3X / PC +DB_FILENAME = "speed_limits.sqlite" + + +def accel_scale_factor(level: int) -> float: + lvl = max(ACCEL_MIN, min(ACCEL_MAX, int(level))) + if lvl <= ACCEL_DEFAULT: + return ACCEL_FACTOR_LO + (1.0 - ACCEL_FACTOR_LO) * (lvl - ACCEL_MIN) / (ACCEL_DEFAULT - ACCEL_MIN) + return 1.0 + (ACCEL_FACTOR_HI - 1.0) * (lvl - ACCEL_DEFAULT) / (ACCEL_MAX - ACCEL_DEFAULT) + + +def map_brake_a_ms2(lookahead: int) -> float: + """Fixed comfort |a| for map-driven decreases (locked at Accel 5).""" + return map_comfort_a_ms2(lookahead, ACCEL_DEFAULT) + + +def map_accel_a_ms2(lookahead: int, accel_level: int) -> float: + """Comfort |a| for Follow speeding up toward a higher MAX (Accel 1–10).""" + return map_comfort_a_ms2(lookahead, accel_level) + + +def map_comfort_a_ms2(lookahead: int, accel_level: int = ACCEL_DEFAULT) -> float: + """Comfort |a| (m/s²). Lookahead Normal + accel 5 → 0.80 m/s².""" + if lookahead in LOOKAHEAD_TUNING and LOOKAHEAD_TUNING[lookahead][0] > 0: + a_base = LOOKAHEAD_TUNING[lookahead][0] + else: + a_base = LOOKAHEAD_TUNING[LOOKAHEAD_NORMAL][0] + return max(A_CLAMP_MIN, min(A_CLAMP_MAX, a_base * accel_scale_factor(accel_level))) + + +def map_track_taper_ms(accel_level: int | None) -> float: + """Speed-error window (m/s) for Accel climb taper. None → brake default 2.0. + + Accel 1: last ~5 mph is a baby-step. Accel 2–6 progressive. Accel 7–10: + full a almost to deadband (brisk all the way to the target). + """ + if accel_level is None: + return TRACK_TAPER_MS + lvl = max(ACCEL_MIN, min(ACCEL_MAX, int(accel_level))) + if lvl >= 7: + return TRACK_TAPER_ACCEL_HI_MS + t1 = TRACK_TAPER_ACCEL_LO_MS + t7 = TRACK_TAPER_ACCEL_HI_MS + return t1 + (t7 - t1) * (lvl - ACCEL_MIN) / (7 - ACCEL_MIN) + + +def osm_sign_lead_m(v_ego_ms: float) -> float: + """GNSS-lag meters: v_ego * 1.5 s. Not a fixed offset and not +110 m lookahead.""" + if v_ego_ms <= 0 or OSM_SIGN_LEAD_S <= 0: + return 0.0 + return float(v_ego_ms) * OSM_SIGN_LEAD_S diff --git a/selfdrive/mapd/data/us_states.json b/selfdrive/mapd/data/us_states.json new file mode 100644 index 00000000000000..334341f0c58d14 --- /dev/null +++ b/selfdrive/mapd/data/us_states.json @@ -0,0 +1 @@ +{"source":"US Census Bureau state boundaries (public domain), simplified; via PublicaMundi/MappingAPI us-states.json","order":"lat,lon","states":{"AL":[[[35.0012,-87.3593],[34.9847,-85.6067],[34.1249,-85.4314],[32.8597,-85.185],[32.5804,-85.0699],[32.4215,-84.9604],[32.323,-85.0042],[32.2627,-84.8892],[32.1367,-85.059],[32.0108,-85.0535],[31.841,-85.1411],[31.5398,-85.0426],[31.2769,-85.1138],[31.003,-85.0042],[30.9975,-85.4971],[30.9975,-87.6003],[30.8661,-87.6331],[30.6744,-87.4086],[30.5101,-87.4469],[30.4279,-87.3702],[30.2801,-87.5181],[30.2472,-87.6551],[30.4115,-87.907],[30.658,-87.9344],[30.6854,-88.0111],[30.4991,-88.1042],[30.3184,-88.137],[30.3677,-88.3944],[31.8958,-88.4711],[33.7963,-88.2411],[34.8916,-88.0987],[34.9957,-88.2027],[35.0012,-87.3593]]],"AK":[[[55.118,-131.602],[55.2823,-131.5692],[55.1837,-131.3556],[55.0139,-131.3884],[55.0358,-131.6458],[55.118,-131.602]],[[55.4247,-131.8321],[55.3042,-131.6458],[55.1289,-131.7499],[55.1892,-131.8321],[55.4247,-131.8321]],[[56.4379,-132.9767],[56.4598,-132.7357],[56.4215,-132.6317],[56.2736,-132.6645],[56.2408,-132.8781],[56.3339,-133.0698],[56.4379,-132.9767]],[[56.3503,-133.5956],[56.3174,-133.1629],[56.1257,-133.0534],[55.9121,-132.6207],[55.7807,-132.4729],[55.6712,-132.4619],[55.6492,-132.3578],[55.5068,-132.3414],[55.3644,-132.1661],[55.2385,-132.1442],[55.2768,-132.0292],[55.1782,-131.9799],[54.7894,-131.958],[54.7017,-132.0292],[54.7182,-132.3085],[54.9153,-132.3852],[54.8989,-132.4838],[55.0468,-132.6865],[54.9975,-132.7467],[55.0468,-132.9165],[54.8989,-132.8891],[54.9372,-132.7303],[54.8825,-132.6262],[54.6798,-132.6755],[54.7017,-132.8672],[54.9592,-133.1575],[55.0906,-133.2396],[55.2275,-133.2232],[55.2166,-133.4532],[55.3206,-133.4532],[55.3316,-133.278],[55.4247,-133.1027],[55.589,-133.1794],[55.6219,-133.3875],[55.8848,-133.4204],[56.0162,-133.497],[55.9231,-133.6394],[56.071,-133.6942],[56.1422,-133.5463],[56.312,-133.6668],[56.3503,-133.5956]],[[55.5561,-133.738],[55.4904,-133.5463],[55.5726,-133.4149],[55.5342,-133.2834],[55.3864,-133.4204],[55.4302,-133.634],[55.5561,-133.738]],[[56.9308,-133.9078],[57.0294,-134.0502],[57.0952,-133.8859],[57.002,-133.3437],[57.0075,-133.1027],[56.8213,-132.9329],[56.668,-132.6207],[56.5529,-132.6536],[56.4927,-132.8179],[56.5201,-133.0425],[56.4489,-133.2013],[56.4927,-133.4204],[56.4489,-133.6613],[56.6844,-133.7106],[56.8377,-133.6887],[56.8432,-133.8695],[56.9308,-133.9078]],[[56.4817,-134.1159],[56.5584,-134.2529],[56.7227,-134.4007],[56.8487,-134.4172],[56.9089,-134.2967],[56.8487,-134.1707],[56.9528,-134.1433],[56.772,-133.749],[56.5968,-133.7106],[56.5748,-133.8476],[56.3777,-133.9352],[56.3229,-133.8366],[56.0929,-133.9571],[56.1422,-134.1105],[55.9998,-134.1324],[56.071,-134.231],[56.3503,-134.2912],[56.4817,-134.1159]],[[56.2846,-134.6362],[56.1696,-134.6691],[56.2353,-134.806],[56.6789,-135.1785],[56.8104,-135.414],[56.9144,-135.3318],[57.1664,-135.4249],[57.369,-135.6878],[57.5662,-135.4194],[57.484,-135.299],[57.4183,-135.0634],[57.4073,-134.8498],[57.2485,-134.8444],[56.7282,-134.6362],[56.2846,-134.6362]],[[58.2234,-134.7129],[58.1467,-134.3734],[58.1577,-134.1762],[58.081,-134.1871],[57.8072,-133.9023],[57.851,-134.0995],[57.7579,-134.1488],[57.6155,-133.9352],[57.3635,-133.8695],[57.2978,-134.0831],[57.2102,-134.1543],[57.0294,-134.4993],[57.0349,-134.6034],[57.2266,-134.6472],[57.3416,-134.576],[57.5114,-134.6089],[57.7195,-134.7294],[57.8291,-134.7074],[58.0974,-134.7841],[58.2125,-134.9156],[58.4096,-134.9539],[58.2234,-134.7129]],[[57.3307,-135.8576],[57.3307,-135.7152],[57.1499,-135.5673],[57.024,-135.633],[56.9966,-135.8576],[57.1937,-135.8247],[57.3307,-135.8576]],[[58.207,-136.2793],[58.2015,-135.9781],[58.2891,-135.7809],[58.1686,-135.4961],[58.0372,-135.6495],[57.9879,-135.5947],[58.1358,-135.4523],[58.0865,-135.1073],[57.9769,-134.9156],[57.7798,-135.0251],[57.7633,-134.9375],[57.5005,-134.8225],[57.4621,-135.0854],[57.6757,-135.5728],[57.4566,-135.5564],[57.369,-135.7097],[57.4073,-135.8905],[57.5443,-136.0],[57.6374,-136.2081],[57.8291,-136.367],[57.9167,-136.5696],[58.0755,-136.5587],[58.1303,-136.4217],[58.2672,-136.3779],[58.207,-136.2793]],[[60.2006,-147.0799],[59.9486,-147.5016],[59.8501,-147.5344],[59.7843,-147.874],[59.9377,-147.8028],[60.0965,-147.4359],[60.2718,-147.2058],[60.2006,-147.0799]],[[60.5785,-147.5618],[60.3704,-147.6166],[60.1568,-147.759],[60.228,-147.9562],[60.4744,-147.7919],[60.5785,-147.5618]],[[70.2453,-147.7864],[70.2015,-147.6823],[70.1577,-147.162],[70.185,-146.8882],[70.185,-146.5103],[70.1467,-146.0995],[70.1686,-145.8585],[70.0865,-145.623],[69.9934,-145.1958],[69.9714,-144.6207],[70.0262,-144.4619],[70.0591,-144.0785],[70.1303,-143.9142],[70.1412,-143.4979],[70.0919,-143.5034],[70.1193,-143.2569],[70.0426,-142.7476],[69.9167,-142.4025],[69.8564,-142.0794],[69.8017,-142.0082],[69.7907,-141.7125],[69.6976,-141.4331],[69.6373,-141.3784],[69.6866,-141.2086],[69.6483,-141.0005],[60.3046,-141.0005],[60.2225,-140.5349],[60.3101,-140.4747],[60.1842,-139.9872],[60.343,-139.6969],[60.3594,-139.089],[60.091,-139.1985],[59.9979,-139.0452],[59.9103,-138.7001],[59.7679,-138.6235],[59.2421,-137.6047],[58.908,-137.4459],[59.0011,-137.2652],[59.16,-136.827],[59.1654,-136.5806],[59.2859,-136.4655],[59.4667,-136.4765],[59.4667,-136.3012],[59.6255,-136.2574],[59.6638,-135.9452],[59.8008,-135.4797],[59.5653,-135.0251],[59.4229,-135.0689],[59.2805,-134.9594],[59.2476,-134.702],[59.034,-134.3788],[58.9737,-134.4007],[58.8587,-134.2529],[58.7273,-133.8421],[58.1522,-133.1739],[57.9989,-133.0753],[57.8455,-132.8672],[57.5059,-132.5605],[57.2156,-132.2538],[57.0952,-132.3688],[57.0513,-132.0511],[56.8761,-132.1278],[56.8049,-131.8704],[56.6022,-131.8375],[56.6132,-131.5801],[56.4051,-131.0872],[56.3667,-130.7805],[56.2681,-130.6216],[56.2408,-130.4683],[56.1422,-130.4245],[56.1148,-130.1013],[55.9943,-130.0028],[55.7697,-130.1506],[55.5835,-130.1287],[55.2768,-129.9863],[55.2001,-130.0959],[54.9208,-130.3368],[54.7182,-130.6874],[54.8222,-130.786],[54.7894,-130.9174],[54.9975,-131.0105],[55.0851,-130.9831],[55.1892,-131.0927],[55.2987,-130.8626],[55.3371,-130.9284],[55.2001,-131.1584],[55.2878,-131.2844],[55.2385,-131.4268],[55.4576,-131.843],[55.6985,-131.7006],[55.6164,-131.9635],[55.4959,-131.9745],[55.589,-132.1826],[55.704,-132.2264],[55.83,-132.084],[55.956,-132.1278],[55.8519,-132.325],[56.0764,-132.5221],[56.0326,-132.6426],[56.2188,-132.7193],[56.3393,-132.5276],[56.3393,-132.3414],[56.4872,-132.3962],[56.6789,-132.2976],[56.6734,-132.4509],[56.8377,-132.7686],[57.0349,-132.9932],[57.1773,-133.5189],[57.5771,-133.508],[57.6264,-133.6778],[57.7907,-133.6394],[57.8345,-133.8147],[58.0536,-134.0721],[58.1686,-134.1433],[58.207,-134.587],[58.5027,-135.0744],[59.1928,-135.2825],[59.034,-135.3811],[58.8916,-135.3373],[58.6177,-135.1401],[58.5739,-135.1894],[58.3494,-135.058],[58.2015,-135.0854],[58.2344,-135.277],[58.3987,-135.4304],[58.4261,-135.633],[58.3822,-135.9178],[58.6177,-135.9124],[58.8149,-136.0876],[58.7547,-136.2465],[58.9628,-136.8763],[58.9025,-136.9311],[58.8368,-136.586],[58.6725,-136.3177],[58.667,-136.2136],[58.5356,-136.1807],[58.3822,-136.0438],[58.2946,-136.3889],[58.3494,-136.5915],[58.2125,-136.597],[58.3165,-136.8599],[58.3932,-136.9475],[58.3932,-137.1118],[58.5904,-137.5664],[58.7656,-137.9005],[58.8697,-137.9334],[59.023,-138.1196],[59.1326,-138.6344],[59.2476,-138.9192],[59.379,-139.4176],[59.505,-139.7462],[59.6419,-139.7188],[59.5981,-139.6257],[59.6857,-139.5162],[59.8829,-139.6257],[59.9925,-139.4888],[60.0418,-139.5545],[59.8336,-139.801],[59.6967,-140.3158],[59.746,-140.9292],[59.872,-141.4441],[59.9706,-141.466],[59.9486,-141.707],[60.0198,-141.9644],[60.0856,-142.5395],[60.091,-142.8736],[60.0363,-143.6239],[59.9979,-143.8923],[60.1403,-144.2318],[60.2061,-144.6536],[60.2937,-144.785],[60.4416,-144.8343],[60.4306,-145.1246],[60.2992,-145.2232],[60.4744,-145.738],[60.5511,-145.8202],[60.4087,-146.3514],[60.2389,-146.6088],[60.3978,-146.7184],[60.4854,-146.6088],[60.4635,-146.4555],[60.5785,-145.9516],[60.6661,-146.0173],[60.6223,-146.2528],[60.7373,-146.3459],[60.7538,-146.565],[61.044,-146.7841],[60.9728,-146.8663],[60.9345,-147.173],[60.9728,-147.2715],[60.8797,-147.3756],[60.9126,-147.759],[60.8085,-147.7754],[60.7811,-148.0328],[60.8195,-148.1533],[61.0057,-148.0657],[61.0002,-148.1752],[60.803,-148.3505],[60.7373,-148.1095],[60.5949,-148.0876],[60.4416,-147.9397],[60.2773,-148.0274],[60.332,-148.2191],[60.2499,-148.2738],[60.217,-148.0876],[59.9979,-147.9835],[59.9541,-148.2519],[59.9979,-148.3998],[59.9377,-148.6353],[59.987,-148.7558],[59.9815,-149.068],[60.0637,-149.057],[60.0089,-149.2049],[59.9048,-149.2871],[59.9979,-149.4185],[59.8665,-149.5828],[59.8062,-149.5116],[59.7296,-149.7416],[59.7186,-149.9498],[59.6146,-150.0319],[59.5214,-150.2565],[59.5543,-150.4098],[59.4448,-150.5796],[59.4502,-150.7165],[59.2257,-151.0013],[59.2093,-151.3081],[59.2805,-151.4066],[59.16,-151.5929],[59.2531,-151.9762],[59.4229,-151.8886],[59.4831,-151.6367],[59.4721,-151.4724],[59.5379,-151.4231],[59.6693,-151.1273],[59.7789,-151.1164],[59.631,-151.5052],[59.7186,-151.8284],[59.7789,-151.8667],[60.0308,-151.7024],[60.2115,-151.4231],[60.3594,-151.3793],[60.3868,-151.2971],[60.5456,-151.2642],[60.7209,-151.4066],[60.7866,-151.0616],[61.0386,-150.4044],[60.94,-150.2455],[60.9126,-150.0429],[61.0166,-149.7416],[61.1536,-150.0757],[61.2576,-150.2072],[61.2467,-150.4701],[61.296,-150.6563],[61.2522,-150.7111],[61.181,-151.0233],[61.044,-151.1657],[61.0112,-151.4778],[60.8523,-151.801],[60.7483,-151.8338],[60.6935,-152.0803],[60.5785,-152.1351],[60.5073,-152.3103],[60.3046,-152.3925],[60.1732,-152.7321],[60.0691,-152.5677],[59.9158,-152.7047],[59.8884,-153.0223],[59.6912,-153.0497],[59.62,-153.3455],[59.7022,-153.4386],[59.5488,-153.5865],[59.5433,-153.7617],[59.4338,-153.7289],[59.3681,-154.1177],[59.0669,-154.1944],[59.0504,-153.7508],[58.9683,-153.4002],[58.8697,-153.3017],[58.7109,-153.4441],[58.6123,-153.6796],[58.6068,-153.8986],[58.5192,-153.9206],[58.4863,-154.063],[58.3768,-153.9972],[58.2125,-154.1451],[58.0591,-154.4628],[58.0591,-154.6435],[58.0043,-154.8188],[58.0153,-154.9886],[57.955,-155.12],[57.8729,-155.0817],[57.8291,-155.3281],[57.7086,-155.3774],[57.7853,-155.5472],[57.5497,-155.7334],[57.5662,-156.0456],[57.4402,-156.0237],[57.4731,-156.2099],[57.4183,-156.3414],[57.2485,-156.3414],[56.9856,-156.5495],[56.9528,-156.8836],[56.8323,-157.1574],[56.7665,-157.2012],[56.8596,-157.3765],[56.6077,-157.6723],[56.6789,-157.7544],[56.657,-157.9187],[56.5146,-157.9571],[56.4598,-158.1268],[56.4817,-158.3295],[56.3393,-158.4883],[56.2955,-158.209],[55.9779,-158.5102],[55.8738,-159.3756],[55.5945,-159.6166],[55.6547,-159.6768],[55.83,-159.644],[55.8574,-159.8137],[55.7916,-160.0273],[55.7204,-160.0602],[55.6054,-160.3943],[55.474,-160.5367],[55.5671,-160.5805],[55.4576,-160.6681],[55.5288,-160.8653],[55.359,-161.2323],[55.3644,-161.5061],[55.4959,-161.4678],[55.6219,-161.5883],[55.5178,-161.6978],[55.4083,-161.6869],[55.0742,-162.0538],[55.1563,-162.1798],[55.0303,-162.2181],[55.0523,-162.4701],[55.2494,-162.5084],[55.2932,-162.6617],[55.222,-162.7165],[55.1344,-162.5796],[54.9975,-162.6453],[54.9263,-162.848],[55.0796,-163.0013],[55.0906,-163.1875],[55.0303,-163.2204],[54.9427,-163.0342],[54.8003,-163.3738],[54.762,-163.1437],[54.6963,-163.1382],[54.7456,-163.3299],[54.6141,-163.5874],[54.6196,-164.0858],[54.5319,-164.3322],[54.4662,-164.3541],[54.3895,-164.6389],[54.4169,-164.847],[54.6031,-164.9182],[54.6634,-164.7101],[54.8879,-164.5513],[54.8934,-164.3432],[55.0413,-163.8941],[55.0468,-163.5326],[54.9044,-163.3957],[55.0084,-163.2916],[55.1289,-163.3135],[55.1837,-163.1054],[55.1837,-162.8808],[55.4466,-162.5796],[55.6821,-162.2455],[55.8902,-161.8073],[55.9833,-161.2925],[55.9395,-161.0789],[55.9998,-160.8708],[55.9121,-160.816],[55.8136,-160.931],[55.7369,-160.8051],[55.8574,-160.7667],[55.8683,-160.5093],[55.7916,-160.4381],[55.7643,-160.2793],[55.8574,-160.2738],[55.9395,-160.5367],[55.9943,-160.5586],[56.2517,-160.3833],[56.3996,-160.1478],[56.542,-159.8302],[56.668,-159.3263],[56.8487,-158.9593],[56.783,-158.7841],[56.8104,-158.6417],[56.9254,-158.7019],[57.0349,-158.6581],[57.2649,-158.3788],[57.4128,-157.9954],[57.61,-157.6887],[57.7195,-157.7051],[58.4973,-157.4587],[58.7054,-157.0753],[58.8697,-157.1191],[58.6342,-158.0392],[58.6616,-158.3295],[58.7601,-158.4007],[58.804,-158.565],[58.9135,-158.6198],[58.8642,-158.7676],[58.6944,-158.8608],[58.4808,-158.7019],[58.3877,-158.8936],[58.4206,-159.0634],[58.7601,-159.392],[58.9299,-159.6166],[58.9299,-159.7316],[58.804,-159.8083],[58.7821,-159.9068],[58.8861,-160.0547],[58.9025,-160.2355],[59.0723,-160.3176],[58.8806,-160.8544],[58.7437,-161.3363],[58.667,-161.3747],[58.552,-161.7526],[58.6561,-161.9388],[58.7766,-161.769],[59.0614,-161.8293],[59.3626,-161.9552],[59.4886,-161.7033],[59.7405,-161.9114],[59.8829,-162.0921],[60.091,-162.2345],[60.1787,-162.4481],[59.9979,-162.5029],[59.9596,-162.7603],[59.8446,-163.1711],[59.7953,-163.664],[59.8062,-163.9324],[59.8665,-164.1624],[60.0253,-164.1898],[60.0746,-164.387],[60.2937,-164.6992],[60.3375,-164.9621],[60.5785,-165.2688],[60.688,-165.0606],[60.8907,-165.0168],[60.8469,-165.1757],[60.9728,-165.1976],[61.0769,-165.1209],[61.17,-165.3235],[61.0714,-165.3454],[61.1098,-165.5919],[61.2795,-165.6248],[61.3014,-165.8165],[61.4165,-165.9205],[61.5589,-165.9151],[61.4931,-166.1067],[61.6301,-166.1396],[61.6629,-165.9041],[61.8163,-166.0958],[61.8272,-165.7562],[62.0134,-165.7562],[62.1394,-165.6741],[62.5392,-165.0442],[62.6597,-164.9128],[62.6378,-164.8197],[62.8076,-164.8744],[63.0979,-164.6334],[63.2129,-164.4253],[63.2622,-164.0365],[63.2129,-163.7352],[63.0376,-163.3135],[63.0595,-163.0397],[63.2293,-162.6617],[63.4867,-162.2729],[63.5141,-162.0757],[63.4484,-162.0264],[63.4484,-161.5554],[63.5032,-161.1392],[63.7715,-160.7667],[63.8373,-160.7667],[64.0892,-160.9529],[64.2371,-160.9749],[64.3959,-161.2651],[64.5328,-161.3747],[64.4945,-161.0789],[64.6095,-160.7996],[64.7191,-160.7832],[64.9217,-161.1446],[64.7629,-161.413],[64.7903,-161.6649],[64.7026,-161.9005],[64.6807,-162.1688],[64.6205,-162.2345],[64.5328,-162.5413],[64.385,-162.6344],[64.3247,-162.7877],[64.5,-162.8589],[64.5383,-163.0451],[64.4014,-163.1766],[64.4671,-163.2533],[64.5657,-163.5983],[64.5602,-164.3048],[64.4507,-164.8087],[64.4343,-165.0004],[64.5,-165.4112],[64.5767,-166.1889],[64.6369,-166.3915],[64.7355,-166.4847],[64.8724,-166.4135],[64.9874,-166.6928],[65.1134,-166.638],[65.1791,-166.4627],[65.338,-166.5175],[65.338,-166.7968],[65.3818,-167.0269],[65.4146,-167.476],[65.4968,-167.7115],[65.5789,-168.073],[65.683,-168.1058],[65.8199,-167.5417],[66.05,-166.8297],[66.1869,-166.3313],[66.1102,-166.0465],[66.0938,-165.7562],[66.2033,-165.6905],[66.2197,-165.8658],[66.3128,-165.8822],[66.4662,-165.1866],[66.5812,-164.4034],[66.5922,-163.9817],[66.5538,-163.7517],[66.3895,-163.8722],[66.2745,-163.8283],[66.1924,-163.916],[66.0609,-163.7681],[66.0828,-163.4942],[66.0609,-163.1492],[66.0883,-162.7494],[66.039,-162.6344],[66.028,-162.3715],[66.0773,-162.1414],[66.0226,-161.8402],[66.2416,-161.5499],[66.2526,-161.3418],[66.2088,-161.1994],[66.3348,-161.1282],[66.395,-161.528],[66.3457,-161.9114],[66.51,-161.8731],[66.6853,-162.1743],[66.74,-162.5029],[66.8989,-162.6015],[66.9372,-162.3441],[66.7784,-162.0155],[66.6524,-162.0757],[66.5538,-161.9169],[66.4388,-161.5718],[66.5593,-161.4897],[66.7181,-161.884],[67.0029,-161.7142],[67.0522,-161.8512],[66.992,-162.24],[67.0084,-162.6398],[67.0577,-162.7001],[67.0084,-162.9027],[67.1289,-163.7407],[67.2549,-163.7571],[67.5342,-164.0091],[67.6383,-164.2117],[67.7259,-164.5349],[67.9669,-165.1921],[68.06,-165.4933],[68.0819,-165.7946],[68.2462,-166.2437],[68.3393,-166.6818],[68.3722,-166.7037],[68.4215,-166.3751],[68.5748,-166.2272],[68.8815,-166.2163],[68.8596,-165.329],[68.9308,-164.2555],[68.9856,-163.9762],[69.1389,-163.5326],[69.3745,-163.1109],[69.61,-163.0232],[69.8126,-162.8425],[69.9824,-162.4701],[70.1084,-162.3112],[70.311,-161.8512],[70.2562,-161.78],[70.2398,-161.3966],[70.3439,-160.8379],[70.4534,-160.4874],[70.793,-159.6494],[70.8094,-159.3318],[70.7601,-159.2989],[70.7985,-158.9758],[70.7875,-158.6581],[70.8313,-158.0337],[70.9792,-157.4203],[71.2859,-156.8124],[71.3516,-156.5659],[71.2969,-156.5221],[71.1709,-155.5855],[71.0833,-155.5089],[70.9682,-155.832],[70.9628,-155.9799],[70.8094,-155.9744],[70.8587,-155.5034],[70.9409,-155.476],[71.0175,-155.2624],[70.9737,-155.1912],[71.149,-155.0324],[70.9902,-154.5668],[70.8697,-154.6435],[70.8368,-154.3532],[70.7656,-154.1834],[70.8806,-153.9315],[70.8861,-153.4879],[70.9244,-153.2359],[70.8861,-152.5897],[70.8423,-152.261],[70.6068,-152.4199],[70.5465,-151.8174],[70.4863,-151.7736],[70.3822,-151.1876],[70.4315,-151.1821],[70.4972,-150.7604],[70.4918,-150.3551],[70.437,-150.3496],[70.4315,-150.1141],[70.5082,-149.8676],[70.5191,-149.4623],[70.4863,-149.1775],[70.4041,-148.7887],[70.4206,-148.6079],[70.3055,-148.3505],[70.3494,-148.2026],[70.3165,-147.9616],[70.2453,-147.7864]],[[58.0262,-152.9402],[57.9824,-152.9457],[58.0481,-153.2907],[58.3056,-153.0442],[58.3275,-152.8197],[58.563,-152.6663],[58.3549,-152.4965],[58.4261,-152.3541],[58.311,-152.0803],[58.1522,-152.0803],[58.1303,-152.4801],[58.0591,-152.6554],[58.0262,-152.9402]],[[57.5388,-153.9589],[57.6702,-153.6741],[57.6976,-153.9315],[57.8126,-153.937],[57.8893,-153.7234],[57.8345,-153.57],[57.7195,-153.5481],[57.7962,-153.4605],[57.966,-153.455],[57.8893,-153.2688],[57.9989,-153.2359],[57.9331,-153.0716],[57.9331,-152.8745],[57.9934,-152.7211],[57.8893,-152.4692],[57.599,-152.4692],[57.6209,-152.1515],[57.4293,-152.3596],[57.5059,-152.743],[57.38,-152.6006],[57.2759,-152.7101],[57.3252,-152.9073],[57.128,-152.9128],[57.0732,-153.214],[56.9911,-153.3126],[57.0678,-153.4988],[56.8596,-153.696],[56.8377,-153.8494],[56.7446,-154.0137],[56.9692,-154.0739],[56.8487,-154.3039],[56.9199,-154.3149],[56.9911,-154.523],[57.1937,-154.5394],[57.2759,-154.7421],[57.5114,-154.6271],[57.6593,-154.2273],[57.6483,-153.9808],[57.5388,-153.9589]],[[56.6022,-154.534],[56.3996,-154.7421],[56.4324,-154.8078],[56.6022,-154.534]],[[55.9231,-155.6348],[55.9121,-155.476],[55.704,-155.5308],[55.7314,-155.7937],[55.8026,-155.8375],[55.9231,-155.6348]],[[55.2823,-159.8904],[55.0687,-159.9507],[54.8934,-160.2574],[55.1618,-160.1095],[55.1344,-160.0054],[55.2823,-159.8904]],[[55.359,-160.5203],[55.359,-160.334],[55.2494,-160.3395],[55.1289,-160.5257],[55.2111,-160.6901],[55.1344,-160.7941],[55.3206,-160.8544],[55.3809,-160.7996],[55.359,-160.5203]],[[54.9811,-162.2565],[54.8934,-162.2345],[54.8387,-162.3496],[54.9318,-162.4372],[54.9811,-162.2565]],[[63.6346,-162.4153],[63.536,-162.5632],[63.6237,-162.6125],[63.6346,-162.4153]],[[54.4881,-162.8041],[54.4498,-162.5905],[54.3676,-162.6125],[54.3731,-162.7822],[54.4881,-162.8041]],[[54.2964,-165.5481],[54.1814,-165.4769],[54.1321,-165.6303],[54.2526,-165.685],[54.2964,-165.5481]],[[54.154,-165.7398],[54.0445,-166.0465],[54.1212,-166.1122],[54.2198,-165.9808],[54.154,-165.7398]],[[60.3594,-166.3642],[60.3978,-166.1341],[60.3266,-166.0848],[60.343,-165.8822],[60.2773,-165.685],[59.9925,-165.6467],[59.8993,-165.7507],[59.8446,-166.0082],[59.746,-166.0629],[59.8555,-166.4408],[59.8501,-166.6161],[59.9925,-166.994],[59.9925,-167.1255],[60.0746,-167.3445],[60.2061,-167.4212],[60.2389,-167.3117],[60.2061,-166.9392],[60.3101,-166.764],[60.3211,-166.5778],[60.3923,-166.4956],[60.3594,-166.3642]],[[54.0116,-166.3751],[53.935,-166.2108],[53.7487,-166.5449],[53.7159,-166.5394],[53.8528,-166.1177],[53.7761,-166.1122],[53.683,-166.282],[53.6228,-166.5559],[53.5297,-166.5832],[53.4311,-166.879],[53.4256,-167.1364],[53.3325,-167.3062],[53.2503,-167.6239],[53.338,-167.7936],[53.442,-167.4595],[53.4256,-167.3555],[53.5132,-167.1035],[53.6118,-167.1638],[53.7159,-167.0214],[53.6666,-166.8078],[53.7323,-166.7859],[53.7542,-167.0159],[53.8254,-167.1419],[53.9459,-167.0323],[54.0171,-166.6435],[53.8802,-166.5613],[54.0116,-166.3751]],[[53.1572,-168.7904],[53.3489,-168.4071],[53.4311,-168.3852],[53.5242,-168.2373],[53.568,-168.0072],[53.5187,-167.8868],[53.3873,-167.8429],[53.2449,-168.2701],[53.0367,-168.5002],[52.9655,-168.6864],[53.1572,-168.7904]],[[52.8943,-169.7489],[52.7958,-169.7051],[52.7903,-169.9625],[52.856,-169.9899],[52.8943,-169.7489]],[[57.2211,-170.1487],[57.128,-170.2857],[57.2211,-170.313],[57.2211,-170.1487]],[[52.6972,-170.669],[52.6041,-170.6033],[52.5383,-170.7895],[52.6369,-170.8169],[52.6972,-170.669]],[[63.7168,-171.7425],[63.5689,-170.9484],[63.6949,-170.4883],[63.6839,-170.2802],[63.6127,-170.094],[63.4922,-170.0447],[63.4265,-169.6448],[63.3663,-169.5189],[63.3389,-168.9986],[63.2951,-168.6864],[63.1472,-168.8562],[63.18,-169.1081],[63.1527,-169.3765],[63.0869,-169.5134],[62.9391,-169.6394],[63.076,-169.8311],[63.1691,-170.0556],[63.18,-170.2637],[63.2841,-170.3623],[63.4155,-170.8662],[63.421,-171.1017],[63.306,-171.4632],[63.3663,-171.737],[63.4867,-171.8521],[63.7168,-171.7425]],[[52.3905,-172.4326],[52.2754,-172.4162],[52.2535,-172.6079],[52.3521,-172.5695],[52.3905,-172.4326]],[[52.1495,-173.6266],[52.1057,-173.4951],[52.1111,-173.1227],[52.0783,-173.1063],[52.029,-173.5499],[52.1495,-173.6266]],[[52.2809,-174.3222],[52.3795,-174.3276],[52.4179,-174.1852],[52.3193,-173.9826],[52.2262,-174.0593],[52.2316,-174.1798],[52.1276,-174.1414],[52.1166,-174.3331],[52.0071,-174.7384],[52.0399,-174.9684],[52.1166,-174.9027],[52.1057,-174.6562],[52.2809,-174.3222]],[[51.8537,-176.4691],[51.8702,-176.2884],[51.7442,-176.2884],[51.7606,-176.5184],[51.6127,-176.8032],[51.8099,-176.9127],[51.8154,-176.7923],[51.9633,-176.7758],[51.9687,-176.6279],[51.8592,-176.6279],[51.8537,-176.4691]],[[51.9468,-177.1537],[51.8975,-177.0442],[51.7278,-177.1209],[51.6785,-177.2742],[51.7825,-177.2797],[51.9468,-177.1537]],[[51.9194,-178.1232],[51.914,-177.9534],[51.7935,-177.8],[51.6511,-177.9643],[51.9194,-178.1232]],[[52.9929,-187.1076],[52.9272,-187.2938],[52.8231,-187.3047],[52.7629,-188.9049],[52.9272,-188.642],[53.0039,-188.642],[52.9929,-187.1076]]],"AZ":[[[37.0003,-109.0425],[31.3316,-109.048],[31.3316,-111.0744],[31.7041,-112.2465],[32.4927,-114.8152],[32.7173,-114.7221],[32.7556,-114.5249],[32.8433,-114.4702],[33.0295,-114.5249],[33.035,-114.6618],[33.4074,-114.7276],[33.5498,-114.5249],[33.6977,-114.4975],[33.9332,-114.5359],[34.1084,-114.4154],[34.1742,-114.2566],[34.3056,-114.1361],[34.448,-114.3332],[34.7109,-114.4702],[34.8752,-114.6345],[35.0012,-114.6345],[35.1381,-114.5742],[35.3243,-114.5961],[35.516,-114.6783],[36.102,-114.7385],[36.1404,-114.3716],[36.0199,-114.2511],[36.0254,-114.1525],[36.1952,-114.0484],[37.0003,-114.0484],[37.0057,-110.4994],[37.0003,-109.0425]]],"AR":[[[36.5019,-94.4738],[36.4964,-90.1525],[36.3047,-90.0649],[36.1842,-90.2183],[35.998,-90.3771],[35.998,-89.7308],[35.8118,-89.7637],[35.757,-89.9116],[35.6036,-89.9444],[35.4393,-90.1306],[35.1983,-90.1142],[35.0231,-90.2128],[34.9957,-90.3114],[34.9081,-90.2511],[34.8314,-90.41],[34.6616,-90.4812],[34.6178,-90.5852],[34.4206,-90.5688],[34.3659,-90.7495],[34.3001,-90.744],[34.1358,-90.9522],[34.0263,-90.8919],[33.8675,-91.0727],[33.5607,-91.2315],[33.4293,-91.0562],[33.3471,-91.1439],[33.139,-91.0891],[33.0021,-91.1658],[33.0185,-93.6085],[33.0185,-94.0412],[33.5498,-94.0412],[33.5936,-94.1836],[33.5443,-94.3807],[33.6374,-94.4848],[35.3955,-94.43],[36.5019,-94.6162],[36.5019,-94.4738]]],"CA":[[[42.0062,-123.2333],[42.0117,-122.3789],[41.9952,-121.037],[41.9952,-120.0019],[40.2645,-119.9964],[38.9993,-120.0019],[38.1011,-118.7148],[37.2193,-117.4989],[36.5019,-116.5404],[35.9706,-115.8503],[35.0012,-114.6345],[34.8752,-114.6345],[34.7109,-114.4702],[34.448,-114.3332],[34.3056,-114.1361],[34.1742,-114.2566],[34.1084,-114.4154],[33.9332,-114.5359],[33.6977,-114.4975],[33.5498,-114.5249],[33.4074,-114.7276],[33.035,-114.6618],[33.0295,-114.5249],[32.8433,-114.4702],[32.7556,-114.5249],[32.7173,-114.7221],[32.6242,-116.0475],[32.5366,-117.1265],[32.668,-117.247],[32.8761,-117.2524],[33.1226,-117.3291],[33.2979,-117.4715],[33.5388,-117.7837],[33.7634,-118.1835],[33.7031,-118.2602],[33.7415,-118.4135],[33.8401,-118.3916],[34.0427,-118.5669],[33.9989,-118.8024],[34.1468,-119.2187],[34.2673,-119.2789],[34.4151,-119.5582],[34.4097,-119.8759],[34.4754,-120.1388],[34.448,-120.4729],[34.5795,-120.6481],[34.8588,-120.6098],[34.9026,-120.67],[35.0998,-120.6317],[35.2476,-120.8946],[35.4503,-120.9056],[35.4612,-121.0041],[35.6365,-121.1684],[35.6748,-121.2835],[35.7844,-121.3328],[36.1952,-121.7161],[36.3156,-121.8969],[36.6388,-121.9352],[36.6114,-121.8585],[36.8031,-121.7873],[36.9784,-121.9297],[36.9564,-122.105],[37.1153,-122.335],[37.2412,-122.4172],[37.3617,-122.4008],[37.5206,-122.5158],[37.7835,-122.5158],[37.7835,-122.3296],[38.1504,-122.4062],[38.1121,-122.4884],[37.9313,-122.5048],[37.893,-122.702],[38.0299,-122.9375],[38.2654,-122.9758],[38.4517,-123.1292],[38.5667,-123.3318],[38.6981,-123.4414],[38.9555,-123.7371],[39.0322,-123.6878],[39.3663,-123.8248],[39.5525,-123.7645],[39.8318,-123.8521],[40.1057,-124.1096],[40.259,-124.3615],[40.4398,-124.4108],[40.8779,-124.1589],[41.0258,-124.1096],[41.1408,-124.1589],[41.4421,-124.0658],[41.7159,-124.1479],[41.7816,-124.2574],[42.0007,-124.2136],[42.0062,-123.2333]]],"CO":[[[41.0039,-107.9197],[40.9984,-105.729],[41.0039,-104.053],[41.0039,-102.0539],[40.0016,-102.0539],[36.9948,-102.043],[37.0003,-103.0014],[36.9948,-104.3378],[36.9948,-106.8682],[37.0003,-107.4213],[37.0003,-109.0425],[38.1669,-109.0425],[38.2764,-109.0589],[39.1253,-109.0535],[40.9984,-109.048],[41.0039,-107.9197]]],"CT":[[[42.039,-73.0535],[42.0226,-71.7993],[42.0062,-71.7993],[41.4147,-71.7993],[41.3216,-71.8596],[41.338,-71.9472],[41.2613,-72.3853],[41.2832,-72.9057],[41.1463,-73.1302],[41.1025,-73.3712],[40.9875,-73.656],[41.1025,-73.7272],[41.212,-73.4807],[41.2942,-73.5519],[42.05,-73.4862],[42.039,-73.0535]]],"DE":[[[39.8045,-75.4141],[39.684,-75.5072],[39.6182,-75.6113],[39.4594,-75.5894],[39.3115,-75.4415],[39.0651,-75.4031],[38.8077,-75.1895],[38.7967,-75.091],[38.4517,-75.0471],[38.4626,-75.6934],[39.7223,-75.7865],[39.8318,-75.6167],[39.8045,-75.4141]]],"DC":[[[38.9939,-77.0353],[38.8953,-76.9093],[38.7912,-77.0407],[38.9336,-77.1174],[38.9939,-77.0353]]],"FL":[[[30.9975,-85.4971],[31.003,-85.0042],[30.7127,-84.8673],[30.647,-83.4981],[30.5703,-82.2164],[30.3567,-82.1672],[30.3622,-82.0467],[30.5649,-82.0028],[30.7511,-82.0412],[30.8278,-81.9481],[30.7456,-81.718],[30.7073,-81.4442],[30.2746,-81.384],[29.7871,-81.258],[29.1463,-80.9677],[28.4617,-80.5241],[28.4124,-80.5898],[28.0948,-80.5679],[27.7388,-80.3817],[27.0213,-80.0914],[26.7967,-80.0311],[26.5667,-80.0366],[25.7397,-80.1462],[25.7232,-80.2393],[25.4658,-80.3379],[25.3837,-80.305],[25.1975,-80.4967],[25.2413,-80.5734],[25.1646,-80.7596],[25.1208,-81.0772],[25.2248,-81.1704],[25.3782,-81.1265],[25.8218,-81.3511],[25.904,-81.5264],[25.8437,-81.6797],[26.0902,-81.8002],[26.2928,-81.8331],[26.5174,-82.0412],[26.6653,-82.0905],[26.8789,-82.0576],[26.9172,-82.1726],[26.7912,-82.1452],[26.7584,-82.2493],[27.3006,-82.567],[27.4375,-82.6929],[27.8373,-82.3917],[27.8154,-82.5889],[27.6895,-82.7203],[27.8866,-82.8518],[28.4343,-82.6765],[28.8889,-82.6437],[28.9985,-82.7641],[29.1463,-82.8025],[29.1792,-82.9942],[29.4202,-83.2187],[29.5188,-83.3995],[29.6666,-83.4104],[29.7214,-83.5364],[29.8857,-83.6405],[30.1048,-84.0238],[30.0555,-84.3579],[29.9021,-84.3415],[29.9295,-84.451],[29.7433,-84.8673],[29.6995,-85.3109],[29.809,-85.3],[29.9405,-85.404],[30.2362,-85.9243],[30.3622,-86.2968],[30.3951,-86.6309],[30.3732,-86.9102],[30.2801,-87.5181],[30.4279,-87.3702],[30.5101,-87.4469],[30.6744,-87.4086],[30.8661,-87.6331],[30.9975,-87.6003],[30.9975,-85.4971]]],"GA":[[[35.0012,-83.1092],[34.7876,-83.3228],[34.6835,-83.3392],[34.4699,-83.0051],[34.4863,-82.9011],[34.2673,-82.7477],[34.1523,-82.7149],[33.9441,-82.556],[33.8182,-82.326],[33.6319,-82.1945],[33.4622,-81.9262],[33.3471,-81.9371],[33.1609,-81.7619],[33.0076,-81.4935],[32.8433,-81.4278],[32.6297,-81.4168],[32.5585,-81.2799],[32.2901,-81.1211],[32.1203,-81.1156],[32.0327,-80.8856],[31.6931,-81.132],[31.5178,-81.1758],[31.3645,-81.2799],[31.2057,-81.2908],[31.1345,-81.4004],[30.7073,-81.4442],[30.7456,-81.718],[30.8278,-81.9481],[30.7511,-82.0412],[30.5649,-82.0028],[30.3622,-82.0467],[30.3567,-82.1672],[30.5703,-82.2164],[30.647,-83.4981],[30.7127,-84.8673],[31.003,-85.0042],[31.2769,-85.1138],[31.5398,-85.0426],[31.841,-85.1411],[32.0108,-85.0535],[32.1367,-85.059],[32.2627,-84.8892],[32.323,-85.0042],[32.4215,-84.9604],[32.5804,-85.0699],[32.8597,-85.185],[34.1249,-85.4314],[34.9847,-85.6067],[34.9902,-84.3196],[34.9847,-83.6185],[35.0012,-83.1092]]],"HI":[[[18.9483,-155.6348],[19.0359,-155.8813],[19.1235,-155.9196],[19.3481,-155.8868],[19.7315,-156.062],[19.8574,-155.9251],[20.0327,-155.8265],[20.1477,-155.8977],[20.2682,-155.8758],[20.1258,-155.5965],[20.0217,-155.2843],[19.8684,-155.0926],[19.7369,-155.0926],[19.5233,-154.8078],[19.3481,-154.9831],[19.2659,-155.2953],[19.1345,-155.5143],[18.9483,-155.6348]],[[21.0295,-156.5878],[20.8926,-156.4728],[20.9528,-156.3249],[20.794,-156.0018],[20.6516,-156.0511],[20.5804,-156.3797],[20.6078,-156.4454],[20.783,-156.4619],[20.8214,-156.6316],[20.92,-156.6974],[21.0295,-156.5878]],[[21.2102,-156.9822],[21.1062,-157.0807],[21.1062,-157.3108],[21.2212,-157.2396],[21.2102,-156.9822]],[[21.6977,-157.9516],[21.4622,-157.842],[21.3253,-157.8968],[21.3034,-158.1104],[21.5827,-158.2528],[21.5882,-158.1268],[21.6977,-157.9516]],[[22.229,-159.4687],[22.218,-159.3537],[22.1139,-159.2989],[21.9661,-159.3318],[21.873,-159.4468],[21.988,-159.7644],[22.1523,-159.7261],[22.229,-159.4687]]],"ID":[[[49.0002,-116.0475],[47.9761,-116.0475],[47.6967,-115.7244],[47.4229,-115.7189],[47.3024,-115.5272],[47.2586,-115.3246],[47.1874,-115.3026],[46.919,-114.9302],[46.8095,-114.8864],[46.7054,-114.6235],[46.6397,-114.6126],[46.6452,-114.3223],[46.2727,-114.4647],[46.0372,-114.4921],[45.8839,-114.388],[45.7743,-114.5687],[45.6703,-114.4975],[45.5607,-114.5468],[45.4567,-114.3332],[45.5936,-114.0868],[45.7031,-113.9882],[45.6045,-113.8074],[45.5224,-113.8348],[45.3307,-113.7362],[45.128,-113.5719],[45.0568,-113.4514],[44.8651,-113.4569],[44.783,-113.3419],[44.772,-113.1338],[44.4489,-113.0023],[44.3941,-112.8873],[44.4872,-112.7833],[44.4818,-112.4711],[44.5694,-112.241],[44.5201,-112.1041],[44.5639,-111.8686],[44.5091,-111.8193],[44.5475,-111.6167],[44.7556,-111.3866],[44.5803,-111.2278],[44.4763,-111.0471],[42.0007,-111.0471],[41.9952,-112.1644],[41.9952,-114.043],[42.0007,-117.0279],[43.83,-117.0279],[44.1586,-116.8964],[44.2408,-116.9786],[44.2572,-117.1703],[44.3941,-117.2415],[44.7501,-117.0388],[44.783,-116.9348],[44.9309,-116.8307],[45.024,-116.8471],[45.1445,-116.7321],[45.3197,-116.6719],[45.6155,-116.4638],[45.7524,-116.5459],[45.8236,-116.7814],[45.9934,-116.9183],[46.1687,-116.9238],[46.3439,-117.0553],[46.4261,-117.0388],[47.7625,-117.0443],[49.0002,-117.0334],[49.0002,-116.0475]]],"IL":[[[42.5101,-90.64],[42.4936,-88.7888],[42.4936,-87.8029],[42.3019,-87.8358],[42.0774,-87.6824],[41.7104,-87.5236],[39.3499,-87.5291],[39.1691,-87.6386],[38.9555,-87.5127],[38.7803,-87.4962],[38.6379,-87.6222],[38.5064,-87.6551],[38.2928,-87.8358],[38.2764,-87.9508],[38.1504,-87.9234],[38.1011,-88.0001],[37.8656,-88.0603],[37.7999,-88.0275],[37.6575,-88.1589],[37.4822,-88.0658],[37.3891,-88.4766],[37.2851,-88.5149],[37.1536,-88.4218],[37.0715,-88.5478],[37.2248,-88.9147],[37.2139,-89.0298],[37.0386,-89.1831],[36.9838,-89.1338],[36.9948,-89.2927],[37.2796,-89.5172],[37.3453,-89.4351],[37.537,-89.5172],[37.6904,-89.5172],[37.904,-89.8404],[37.882,-89.9499],[38.0135,-90.0594],[38.2161,-90.3552],[38.375,-90.3497],[38.6324,-90.1799],[38.7255,-90.2073],[38.846,-90.1087],[38.9172,-90.2511],[38.961,-90.4702],[38.8679,-90.5852],[38.9281,-90.6619],[39.2568,-90.7276],[39.4704,-91.0617],[39.7278,-91.3684],[40.0345,-91.4944],[40.2371,-91.5053],[40.3795,-91.4177],[40.5603,-91.4013],[40.6698,-91.122],[40.8232,-91.0946],[40.9218,-90.9631],[41.097,-90.9467],[41.2394,-91.111],[41.4147,-91.0453],[41.464,-90.6564],[41.5899,-90.3442],[41.7433,-90.3114],[41.809,-90.1799],[42.0007,-90.1416],[42.1267,-90.169],[42.2253,-90.3935],[42.3293,-90.4209],[42.5101,-90.64]]],"IN":[[[41.7597,-85.9901],[41.7597,-84.807],[41.694,-84.807],[40.5,-84.8016],[39.1034,-84.818],[39.0596,-84.8947],[38.7857,-84.8125],[38.7803,-84.9878],[38.6872,-85.174],[38.731,-85.4314],[38.5338,-85.4205],[38.4517,-85.5902],[38.3257,-85.656],[38.2764,-85.8312],[38.0245,-85.9243],[37.9587,-86.0394],[38.0518,-86.2639],[38.1669,-86.3022],[38.0409,-86.5213],[37.9313,-86.5049],[37.893,-86.7294],[37.9916,-86.7952],[37.893,-87.0471],[37.7889,-87.1293],[37.9368,-87.3812],[37.904,-87.5127],[37.9752,-87.6003],[37.904,-87.6824],[37.893,-87.9344],[37.7999,-88.0275],[37.8656,-88.0603],[38.1011,-88.0001],[38.1504,-87.9234],[38.2764,-87.9508],[38.2928,-87.8358],[38.5064,-87.6551],[38.6379,-87.6222],[38.7803,-87.4962],[38.9555,-87.5127],[39.1691,-87.6386],[39.3499,-87.5291],[41.7104,-87.5236],[41.6447,-87.425],[41.6447,-87.1183],[41.7597,-86.8226],[41.7597,-85.9901]]],"IA":[[[43.5014,-91.3684],[43.5014,-91.2151],[43.3535,-91.2041],[43.2549,-91.0562],[43.1344,-91.1767],[42.9099,-91.1439],[42.751,-91.0672],[42.636,-90.7112],[42.5101,-90.64],[42.3293,-90.4209],[42.2253,-90.3935],[42.1267,-90.169],[42.0007,-90.1416],[41.809,-90.1799],[41.7433,-90.3114],[41.5899,-90.3442],[41.464,-90.6564],[41.4147,-91.0453],[41.2394,-91.111],[41.097,-90.9467],[40.9218,-90.9631],[40.8232,-91.0946],[40.6698,-91.122],[40.5603,-91.4013],[40.3795,-91.4177],[40.4124,-91.5272],[40.615,-91.7299],[40.6096,-91.834],[40.5822,-93.258],[40.5712,-94.6327],[40.5877,-95.7664],[40.7191,-95.8814],[40.9765,-95.8266],[41.2011,-95.9252],[41.453,-95.9198],[41.5406,-96.095],[41.6776,-96.1224],[41.7981,-96.0622],[41.9733,-96.1279],[42.039,-96.2648],[42.4882,-96.4455],[42.7072,-96.6318],[42.8551,-96.5441],[43.0523,-96.5113],[43.1235,-96.4346],[43.2221,-96.5606],[43.3973,-96.5277],[43.4795,-96.5825],[43.5014,-96.451],[43.5014,-91.3684]]],"KS":[[[40.0016,-101.906],[40.0016,-95.3063],[39.9085,-95.2078],[39.8318,-94.8846],[39.5416,-95.1092],[39.443,-94.9832],[39.2075,-94.8244],[39.1582,-94.6108],[37.0003,-94.6162],[37.0003,-100.0877],[36.9948,-102.043],[40.0016,-102.0539],[40.0016,-101.906]]],"KY":[[[38.7693,-83.9033],[38.6324,-83.6788],[38.7036,-83.52],[38.6269,-83.1421],[38.7255,-83.0325],[38.7584,-82.8901],[38.5886,-82.8463],[38.5612,-82.7313],[38.4243,-82.5944],[38.123,-82.6217],[37.9313,-82.5012],[37.7835,-82.3424],[37.6684,-82.2931],[37.5534,-82.1014],[37.537,-81.97],[37.2686,-82.3534],[37.1208,-82.7203],[37.0441,-82.7203],[36.9784,-82.8682],[36.8907,-82.8792],[36.8524,-83.0709],[36.7428,-83.1366],[36.6004,-83.6733],[36.584,-83.6897],[36.595,-84.5441],[36.6278,-85.289],[36.6169,-85.4862],[36.6552,-86.5925],[36.6333,-87.8522],[36.6771,-88.0713],[36.4964,-88.0549],[36.5073,-89.2981],[36.4964,-89.4186],[36.6224,-89.3639],[36.5785,-89.216],[36.9838,-89.1338],[37.0386,-89.1831],[37.2139,-89.0298],[37.2248,-88.9147],[37.0715,-88.5478],[37.1536,-88.4218],[37.2851,-88.5149],[37.3891,-88.4766],[37.4822,-88.0658],[37.6575,-88.1589],[37.7999,-88.0275],[37.893,-87.9344],[37.904,-87.6824],[37.9752,-87.6003],[37.904,-87.5127],[37.9368,-87.3812],[37.7889,-87.1293],[37.893,-87.0471],[37.9916,-86.7952],[37.893,-86.7294],[37.9313,-86.5049],[38.0409,-86.5213],[38.1669,-86.3022],[38.0518,-86.2639],[37.9587,-86.0394],[38.0245,-85.9243],[38.2764,-85.8312],[38.3257,-85.656],[38.4517,-85.5902],[38.5338,-85.4205],[38.731,-85.4314],[38.6872,-85.174],[38.7803,-84.9878],[38.7857,-84.8125],[39.0596,-84.8947],[39.1034,-84.818],[39.1034,-84.4346],[38.8953,-84.232],[38.8077,-84.2155],[38.7693,-83.9033]]],"LA":[[[33.0185,-93.6085],[33.0021,-91.1658],[32.8871,-91.0727],[32.8433,-91.1439],[32.6406,-91.1548],[32.5146,-91.0069],[32.2189,-90.985],[31.9889,-91.1055],[31.8465,-91.341],[31.6219,-91.4013],[31.6438,-91.4999],[31.2769,-91.5163],[31.2659,-91.6368],[31.0687,-91.5656],[30.9975,-91.6368],[30.9975,-89.7472],[30.6689,-89.8458],[30.4498,-89.6815],[30.2855,-89.6432],[30.1815,-89.5227],[30.0445,-89.8184],[29.946,-89.8404],[29.8802,-89.5994],[30.0391,-89.4953],[29.8802,-89.2872],[29.7543,-89.3036],[29.6995,-89.4241],[29.7488,-89.6487],[29.6557,-89.6213],[29.5133,-89.698],[29.3873,-89.5063],[29.349,-89.1995],[29.2011,-89.09],[29.1792,-89.0024],[29.0094,-89.1612],[29.0423,-89.3365],[29.2175,-89.4843],[29.3106,-89.8513],[29.4804,-89.8513],[29.4257,-90.032],[29.2833,-90.0211],[29.1518,-90.1032],[29.1299,-90.2347],[29.2778,-90.3333],[29.2833,-90.5633],[29.1299,-90.6455],[29.0861,-90.7988],[29.1792,-90.9631],[29.1901,-91.0946],[29.4366,-91.2205],[29.5461,-91.4451],[29.5297,-91.5327],[29.7378,-91.6204],[29.7105,-91.8832],[29.8364,-91.8887],[29.7159,-92.1461],[29.6228,-92.1133],[29.5352,-92.3105],[29.579,-92.6172],[29.7159,-92.9732],[29.7762,-93.2251],[29.7269,-93.7673],[29.6885,-93.8385],[29.7871,-93.9261],[30.1431,-93.6906],[30.3348,-93.7673],[30.4389,-93.6961],[30.5758,-93.729],[30.6799,-93.6304],[30.9373,-93.5263],[31.1509,-93.5428],[31.5562,-93.8166],[31.7753,-93.8221],[31.9943,-94.0412],[33.0185,-94.0412],[33.0185,-93.6085]]],"ME":[[[43.0578,-70.7039],[43.129,-70.8244],[43.2275,-70.808],[43.3426,-70.9668],[44.657,-71.0325],[45.3033,-71.0818],[45.4402,-70.6492],[45.5114,-70.7204],[45.6648,-70.556],[45.736,-70.3863],[45.7962,-70.4191],[45.8893,-70.2603],[46.0646,-70.3096],[46.3275,-70.211],[46.4151,-70.0576],[46.6944,-69.9974],[47.4612,-69.2251],[47.4284,-69.0444],[47.2421,-69.0335],[47.1764,-68.902],[47.286,-68.5789],[47.286,-68.3762],[47.3572,-68.2338],[47.1983,-67.9545],[47.0669,-67.7902],[45.9441,-67.7792],[45.6757,-67.8011],[45.6045,-67.4561],[45.4895,-67.5054],[45.38,-67.4178],[45.2814,-67.489],[45.128,-67.3466],[45.1609,-67.1603],[44.8049,-66.9796],[44.6461,-67.1877],[44.7063,-67.3082],[44.5968,-67.4068],[44.6242,-67.5492],[44.5311,-67.5656],[44.542,-67.7519],[44.3284,-68.0476],[44.4763,-68.1188],[44.4872,-68.2229],[44.3284,-68.1736],[44.2517,-68.4036],[44.3777,-68.4584],[44.312,-68.5679],[44.312,-68.8253],[44.4599,-68.8308],[44.427,-68.9842],[44.3229,-68.9568],[44.1039,-69.0992],[44.0436,-69.0718],[43.9231,-69.258],[43.9669,-69.4442],[43.841,-69.5538],[43.8245,-69.7071],[43.7205,-69.8331],[43.7424,-69.9864],[43.8519,-70.0303],[43.6767,-70.2548],[43.5671,-70.1946],[43.5288,-70.3589],[43.4357,-70.3698],[43.3207,-70.556],[43.0578,-70.7039]]],"MD":[[[37.9532,-75.9946],[37.9532,-76.0166],[37.9532,-76.0439],[37.9532,-75.9946]],[[39.7223,-79.478],[39.7223,-75.7865],[38.4626,-75.6934],[38.4517,-75.0471],[38.0299,-75.2443],[38.0135,-75.3977],[37.9532,-75.6715],[37.9094,-75.8851],[38.0737,-75.8796],[38.1395,-75.9618],[38.2107,-75.8468],[38.375,-76.0001],[38.3038,-76.0494],[38.3202,-76.2575],[38.5009,-76.3287],[38.5009,-76.263],[38.7365,-76.2575],[38.8296,-76.1918],[39.1472,-76.2794],[39.3334,-76.1699],[39.3663,-76.0001],[39.558,-75.9727],[39.5361,-76.0987],[39.4375,-76.1042],[39.3115,-76.3671],[39.1965,-76.4438],[38.9062,-76.4602],[38.7693,-76.5588],[38.5393,-76.515],[38.3805,-76.3835],[38.26,-76.3999],[38.1395,-76.3178],[38.0573,-76.3616],[38.2161,-76.5916],[38.2928,-76.9202],[38.4462,-77.0188],[38.3585,-77.205],[38.479,-77.2762],[38.6324,-77.1284],[38.7912,-77.0407],[38.8953,-76.9093],[38.9939,-77.0353],[38.9336,-77.1174],[39.0267,-77.2489],[39.076,-77.457],[39.2239,-77.457],[39.3061,-77.5665],[39.3225,-77.7199],[39.6018,-77.8349],[39.6018,-78.0047],[39.6949,-78.1745],[39.6182,-78.2676],[39.6237,-78.4319],[39.5142,-78.4702],[39.5854,-78.766],[39.4375,-78.9631],[39.4704,-79.0946],[39.3006,-79.2918],[39.2075,-79.4889],[39.7223,-79.478]]],"MA":[[[42.888,-70.9175],[42.8715,-70.8189],[42.6963,-70.7806],[42.5539,-70.8244],[42.4224,-70.9832],[42.2691,-70.9887],[42.2472,-70.7696],[42.0883,-70.6382],[41.9624,-70.6601],[41.9295,-70.5506],[41.8145,-70.5396],[41.7159,-70.2603],[41.809,-69.9371],[41.6721,-70.0083],[41.5516,-70.4848],[41.5461,-70.6601],[41.6392,-70.7642],[41.6118,-70.9285],[41.5406,-70.934],[41.4968,-71.1202],[41.6776,-71.1968],[41.7104,-71.2242],[41.7816,-71.3283],[42.0171,-71.3831],[42.0171,-71.5309],[42.0062,-71.7993],[42.0226,-71.7993],[42.039,-73.0535],[42.05,-73.4862],[42.0883,-73.5081],[42.7456,-73.2671],[42.7291,-72.4565],[42.6963,-71.2954],[42.7894,-71.1859],[42.888,-70.9175]]],"MI":[[[41.7323,-83.4542],[41.694,-84.807],[41.7597,-84.807],[41.7597,-85.9901],[41.7597,-86.8226],[41.8912,-86.6199],[42.1157,-86.483],[42.2526,-86.357],[42.4443,-86.2639],[42.7182,-86.2091],[43.0139,-86.231],[43.5945,-86.5268],[43.8136,-86.4337],[44.0765,-86.4994],[44.3448,-86.2694],[44.5694,-86.2201],[44.6899,-86.253],[44.7392,-86.0886],[44.9035,-86.0667],[44.9473,-85.8093],[45.128,-85.6122],[44.7666,-85.6286],[44.7501,-85.5245],[44.9309,-85.3931],[45.2376,-85.3876],[45.3143,-85.3054],[45.3636,-85.0316],[45.5772,-85.1192],[45.7579,-84.9385],[45.7688,-84.7139],[45.6538,-84.462],[45.6374,-84.2155],[45.495,-84.095],[45.484,-83.9088],[45.3526,-83.5966],[45.3581,-83.4871],[45.1445,-83.3173],[45.0295,-83.4542],[44.8816,-83.3228],[44.7118,-83.2735],[44.3394,-83.3337],[44.2463,-83.5364],[44.0546,-83.5857],[43.9888,-83.8267],[43.7588,-83.9581],[43.6712,-83.9088],[43.589,-83.6678],[43.715,-83.4816],[43.9724,-83.2625],[44.071,-82.9175],[43.9943,-82.7477],[43.8519,-82.6437],[43.4357,-82.5396],[43.2275,-82.5232],[42.9756,-82.4136],[42.6141,-82.5177],[42.5594,-82.682],[42.6908,-82.6875],[42.6525,-82.797],[42.3512,-82.923],[42.2362,-83.1256],[42.0062,-83.1859],[41.8145,-83.4378],[41.7323,-83.4542]],[[45.7305,-85.5081],[45.61,-85.4917],[45.5881,-85.6231],[45.7579,-85.5683],[45.7305,-85.5081]],[[45.0952,-87.5893],[45.1992,-87.7427],[45.3416,-87.6496],[45.3636,-87.8851],[45.5005,-87.792],[45.6757,-87.781],[45.7962,-87.9891],[45.9222,-88.1042],[46.0208,-88.5314],[45.9879,-88.6628],[46.1358,-89.09],[46.3384,-90.1197],[46.5082,-90.2292],[46.5685,-90.4154],[46.6725,-90.0266],[46.793,-89.8513],[46.8423,-89.4131],[46.9902,-89.1283],[46.9957,-88.9969],[47.0997,-88.8874],[47.2476,-88.5752],[47.3736,-88.4163],[47.4557,-88.1808],[47.3845,-87.9563],[47.0778,-88.3506],[46.9738,-88.4437],[46.7876,-88.4383],[46.93,-88.2466],[46.908,-87.9015],[46.8095,-87.6331],[46.5356,-87.3922],[46.4863,-87.2607],[46.5301,-87.0088],[46.4699,-86.9485],[46.437,-86.6966],[46.6671,-86.1598],[46.689,-85.8805],[46.678,-85.5081],[46.7547,-85.2562],[46.7602,-85.0645],[46.4808,-85.0261],[46.4425,-84.829],[46.4863,-84.6318],[46.4206,-84.5496],[46.5028,-84.4182],[46.5301,-84.1279],[46.1796,-84.1224],[46.0317,-83.991],[45.9934,-83.7938],[46.092,-83.7719],[46.092,-83.5802],[45.9879,-83.4761],[45.9112,-83.5638],[45.977,-84.1115],[45.9332,-84.3744],[46.0536,-84.6592],[45.9441,-84.7413],[45.851,-84.703],[45.8729,-84.829],[46.0098,-85.0152],[46.092,-85.3383],[46.0975,-85.5026],[45.966,-85.6614],[45.9332,-85.9243],[45.9605,-86.2091],[45.9058,-86.3242],[45.7962,-86.3515],[45.7031,-86.6637],[45.8346,-86.6473],[45.862,-86.7842],[45.725,-86.839],[45.7196,-87.069],[45.6593,-87.1731],[45.4238,-87.3264],[45.1226,-87.6112],[45.0952,-87.5893]],[[47.9761,-88.8052],[47.8501,-89.0571],[47.8337,-89.1886],[47.9377,-89.1776],[48.1732,-88.5478],[48.0089,-88.6683],[47.9761,-88.8052]]],"MN":[[[46.7054,-92.0147],[46.7492,-92.0914],[46.6671,-92.294],[46.0756,-92.294],[46.0153,-92.3543],[45.9332,-92.6391],[45.7196,-92.8691],[45.5772,-92.8855],[45.5662,-92.7705],[45.4402,-92.6445],[45.2869,-92.7596],[45.1171,-92.7377],[44.7501,-92.8089],[44.5694,-92.546],[44.553,-92.3378],[44.4434,-92.2338],[44.3339,-91.9271],[44.2024,-91.8778],[44.0327,-91.593],[43.9943,-91.4341],[43.7752,-91.2424],[43.6164,-91.2698],[43.5014,-91.2151],[43.5014,-91.3684],[43.5014,-96.451],[45.2978,-96.451],[45.4128,-96.681],[45.6045,-96.8563],[45.8181,-96.5825],[45.9332,-96.5606],[46.333,-96.5989],[46.437,-96.7194],[46.6561,-96.8015],[46.9245,-96.7851],[46.9683,-96.8234],[47.6091,-96.8563],[47.9487,-97.0535],[48.1404,-97.1302],[48.5457,-97.163],[48.6826,-97.0973],[49.0002,-97.2287],[49.0002,-95.153],[49.3836,-95.153],[49.3727,-94.9558],[49.296,-94.8244],[48.7757,-94.6929],[48.7154,-94.5889],[48.699,-94.2602],[48.6497,-94.2219],[48.6278,-93.8385],[48.5183,-93.7947],[48.5457,-93.4661],[48.5895,-93.4661],[48.6442,-93.2087],[48.6223,-92.9841],[48.5402,-92.7267],[48.4361,-92.6555],[48.4471,-92.5076],[48.2225,-92.3707],[48.3156,-92.305],[48.3594,-92.053],[48.2663,-92.0092],[48.2006,-91.7135],[48.113,-91.7135],[48.0418,-91.5656],[48.0801,-91.2644],[48.1787,-91.0836],[48.2389,-90.8372],[48.0911,-90.7495],[48.1239,-90.5797],[48.0911,-90.3771],[48.113,-90.1416],[47.987,-89.8732],[48.0089,-89.6158],[47.9541,-89.6377],[47.8282,-89.9718],[47.7296,-90.4373],[47.6255,-90.7386],[47.3681,-91.1712],[47.2093,-91.3575],[47.0285,-91.6423],[46.7876,-92.0914],[46.7054,-92.0147]]],"MS":[[[34.9957,-88.4711],[34.9957,-88.2027],[34.8916,-88.0987],[33.7963,-88.2411],[31.8958,-88.4711],[30.3677,-88.3944],[30.3239,-88.504],[30.3458,-88.745],[30.4115,-88.8435],[30.3677,-89.0845],[30.2527,-89.4186],[30.1815,-89.5227],[30.2855,-89.6432],[30.4498,-89.6815],[30.6689,-89.8458],[30.9975,-89.7472],[30.9975,-91.6368],[31.0687,-91.5656],[31.2659,-91.6368],[31.2769,-91.5163],[31.6438,-91.4999],[31.6219,-91.4013],[31.8465,-91.341],[31.9889,-91.1055],[32.2189,-90.985],[32.5146,-91.0069],[32.6406,-91.1548],[32.8433,-91.1439],[32.8871,-91.0727],[33.0021,-91.1658],[33.139,-91.0891],[33.3471,-91.1439],[33.4293,-91.0562],[33.5607,-91.2315],[33.8675,-91.0727],[34.0263,-90.8919],[34.1358,-90.9522],[34.3001,-90.744],[34.3659,-90.7495],[34.4206,-90.5688],[34.6178,-90.5852],[34.6616,-90.4812],[34.8314,-90.41],[34.9081,-90.2511],[34.9957,-90.3114],[34.9957,-88.4711]]],"MO":[[[40.6096,-91.834],[40.615,-91.7299],[40.4124,-91.5272],[40.3795,-91.4177],[40.2371,-91.5053],[40.0345,-91.4944],[39.7278,-91.3684],[39.4704,-91.0617],[39.2568,-90.7276],[38.9281,-90.6619],[38.8679,-90.5852],[38.961,-90.4702],[38.9172,-90.2511],[38.846,-90.1087],[38.7255,-90.2073],[38.6324,-90.1799],[38.375,-90.3497],[38.2161,-90.3552],[38.0135,-90.0594],[37.882,-89.9499],[37.904,-89.8404],[37.6904,-89.5172],[37.537,-89.5172],[37.3453,-89.4351],[37.2796,-89.5172],[36.9948,-89.2927],[36.9838,-89.1338],[36.5785,-89.216],[36.6224,-89.3639],[36.4964,-89.4186],[36.4964,-89.4843],[36.4964,-89.5391],[36.2499,-89.5336],[35.998,-89.7308],[35.998,-90.3771],[36.1842,-90.2183],[36.3047,-90.0649],[36.4964,-90.1525],[36.5019,-94.4738],[36.5019,-94.6162],[37.0003,-94.6162],[39.1582,-94.6108],[39.2075,-94.8244],[39.443,-94.9832],[39.5416,-95.1092],[39.8318,-94.8846],[39.9085,-95.2078],[40.0016,-95.3063],[40.2645,-95.5528],[40.5877,-95.7664],[40.5712,-94.6327],[40.5822,-93.258],[40.6096,-91.834]]],"MT":[[[49.0002,-104.0475],[47.861,-104.0421],[45.9441,-104.0475],[44.9966,-104.0421],[44.9966,-104.0585],[45.0021,-105.9152],[45.0021,-109.0808],[45.0021,-111.0525],[44.4763,-111.0471],[44.5803,-111.2278],[44.7556,-111.3866],[44.5475,-111.6167],[44.5091,-111.8193],[44.5639,-111.8686],[44.5201,-112.1041],[44.5694,-112.241],[44.4818,-112.4711],[44.4872,-112.7833],[44.3941,-112.8873],[44.4489,-113.0023],[44.772,-113.1338],[44.783,-113.3419],[44.8651,-113.4569],[45.0568,-113.4514],[45.128,-113.5719],[45.3307,-113.7362],[45.5224,-113.8348],[45.6045,-113.8074],[45.7031,-113.9882],[45.5936,-114.0868],[45.4567,-114.3332],[45.5607,-114.5468],[45.6703,-114.4975],[45.7743,-114.5687],[45.8839,-114.388],[46.0372,-114.4921],[46.2727,-114.4647],[46.6452,-114.3223],[46.6397,-114.6126],[46.7054,-114.6235],[46.8095,-114.8864],[46.919,-114.9302],[47.1874,-115.3026],[47.2586,-115.3246],[47.3024,-115.5272],[47.4229,-115.7189],[47.6967,-115.7244],[47.9761,-116.0475],[49.0002,-116.0475],[48.9948,-111.5016],[49.0002,-109.4533],[49.0002,-104.0475]]],"NE":[[[43.003,-103.3246],[42.9975,-101.6267],[42.9975,-98.4994],[42.9482,-98.4665],[42.7675,-97.9517],[42.8661,-97.8312],[42.8442,-97.6888],[42.8442,-97.2178],[42.6579,-96.692],[42.5155,-96.6263],[42.4882,-96.4455],[42.039,-96.2648],[41.9733,-96.1279],[41.7981,-96.0622],[41.6776,-96.1224],[41.5406,-96.095],[41.453,-95.9198],[41.2011,-95.9252],[40.9765,-95.8266],[40.7191,-95.8814],[40.5877,-95.7664],[40.2645,-95.5528],[40.0016,-95.3063],[40.0016,-101.906],[40.0016,-102.0539],[41.0039,-102.0539],[41.0039,-104.053],[43.003,-104.053],[43.003,-103.3246]]],"NV":[[[42.0007,-117.0279],[41.9952,-114.043],[37.0003,-114.0484],[36.1952,-114.0484],[36.0254,-114.1525],[36.0199,-114.2511],[36.1404,-114.3716],[36.102,-114.7385],[35.516,-114.6783],[35.3243,-114.5961],[35.1381,-114.5742],[35.0012,-114.6345],[35.9706,-115.8503],[36.5019,-116.5404],[37.2193,-117.4989],[38.1011,-118.7148],[38.9993,-120.0019],[40.2645,-119.9964],[41.9952,-120.0019],[41.9898,-118.6983],[42.0007,-117.0279]]],"NH":[[[45.3033,-71.0818],[44.657,-71.0325],[43.3426,-70.9668],[43.2275,-70.808],[43.129,-70.8244],[43.0578,-70.7039],[42.8715,-70.8189],[42.888,-70.9175],[42.7894,-71.1859],[42.6963,-71.2954],[42.7291,-72.4565],[42.8058,-72.5442],[42.9537,-72.5332],[43.0085,-72.4456],[43.1509,-72.4565],[43.5726,-72.3799],[43.7698,-72.2046],[43.9943,-72.117],[44.0765,-72.0293],[44.3229,-72.0348],[44.416,-71.7007],[44.5858,-71.5364],[44.7501,-71.6295],[44.9144,-71.4926],[45.013,-71.5036],[45.2704,-71.3612],[45.2431,-71.1311],[45.3033,-71.0818]]],"NJ":[[[41.1408,-74.2365],[40.9984,-73.9025],[40.7082,-74.0229],[40.6424,-74.1873],[40.4891,-74.2749],[40.4124,-74.001],[40.2974,-73.9791],[39.7606,-74.0996],[39.3608,-74.4118],[39.2458,-74.6145],[38.9939,-74.7952],[39.1582,-74.8883],[39.2403,-75.1786],[39.4594,-75.5346],[39.6073,-75.5565],[39.6292,-75.562],[39.684,-75.5072],[39.8045,-75.4141],[39.8866,-75.1457],[39.9633,-75.1293],[40.1276,-74.8226],[40.2152,-74.7733],[40.4179,-75.0581],[40.5438,-75.069],[40.5767,-75.195],[40.6917,-75.206],[40.867,-75.0526],[40.971,-75.1348],[41.1792,-74.8828],[41.2887,-74.8281],[41.3599,-74.6966],[41.1408,-74.2365]]],"NM":[[[37.0003,-107.4213],[36.9948,-106.8682],[36.9948,-104.3378],[37.0003,-103.0014],[36.5019,-103.0014],[36.5019,-103.0398],[34.0153,-103.0453],[33.0021,-103.0672],[31.9998,-103.0672],[31.9998,-106.6162],[31.9012,-106.6436],[31.7862,-106.5286],[31.7862,-108.21],[31.3316,-108.21],[31.3316,-109.048],[37.0003,-109.0425],[37.0003,-107.4213]]],"NY":[[[45.013,-73.3438],[44.8049,-73.3329],[44.6187,-73.3876],[44.4379,-73.2945],[44.2463,-73.3219],[44.0436,-73.4369],[43.7698,-73.3493],[43.6876,-73.4041],[43.5233,-73.2452],[42.8332,-73.2781],[42.7456,-73.2671],[42.0883,-73.5081],[42.05,-73.4862],[41.2942,-73.5519],[41.212,-73.4807],[41.1025,-73.7272],[40.9875,-73.656],[40.9053,-73.2288],[40.9656,-73.1412],[40.9656,-72.7742],[40.9984,-72.588],[41.1573,-72.2813],[41.0422,-72.2594],[40.993,-72.1005],[40.8451,-72.4675],[40.626,-73.2397],[40.5822,-73.5629],[40.5931,-73.7765],[40.5438,-73.9353],[40.7082,-74.0229],[40.9984,-73.9025],[41.1408,-74.2365],[41.3599,-74.6966],[41.4311,-74.7404],[41.4366,-74.8938],[41.6064,-75.0745],[41.7542,-75.0526],[41.8693,-75.1731],[41.8638,-75.2498],[42.0007,-75.3593],[42.0007,-79.7628],[42.2526,-79.7628],[42.2691,-79.7628],[42.5539,-79.1494],[42.6908,-79.0508],[42.7839,-78.8536],[42.9537,-78.9303],[42.9866,-79.0124],[43.2604,-79.0727],[43.3754,-78.4867],[43.3699,-77.9663],[43.3426,-77.7582],[43.233,-77.5337],[43.2768,-77.3913],[43.2714,-76.9586],[43.3426,-76.6957],[43.5233,-76.4164],[43.5288,-76.2356],[43.8026,-76.2302],[43.9615,-76.137],[44.071,-76.3616],[44.197,-76.3123],[44.3667,-75.9125],[44.5146,-75.7646],[44.8487,-75.2826],[45.0185,-74.8281],[44.9911,-74.1489],[45.013,-73.3438]]],"NC":[[[36.5621,-80.9787],[36.5457,-80.294],[36.5402,-79.5108],[36.5512,-75.8687],[36.1513,-75.7537],[36.1897,-76.033],[36.1404,-76.0713],[36.0801,-76.4109],[36.0254,-76.4602],[36.0089,-76.6847],[35.9377,-76.6738],[35.987,-76.3999],[35.9432,-76.3616],[35.9925,-76.0604],[35.8994,-75.9618],[35.9377,-75.781],[35.6968,-75.7153],[35.5817,-75.7756],[35.5708,-75.8961],[35.3243,-76.148],[35.3134,-76.4821],[35.1436,-76.5369],[34.9738,-76.3945],[34.9409,-76.2794],[34.6616,-76.493],[34.6945,-76.6738],[34.6671,-76.9914],[34.6068,-77.2105],[34.4151,-77.5556],[34.1632,-77.8294],[33.8455,-77.9718],[33.9167,-78.1799],[33.851,-78.5414],[34.804,-79.6751],[34.8204,-80.7979],[34.9355,-80.7815],[35.1052,-80.9348],[35.045,-81.0389],[35.1491,-81.0444],[35.1983,-82.2767],[35.16,-82.5505],[35.0669,-82.7641],[35.0012,-83.1092],[34.9847,-83.6185],[34.9902,-84.3196],[35.2257,-84.2922],[35.2476,-84.095],[35.4119,-84.0184],[35.5598,-83.7719],[35.5653,-83.4981],[35.7187,-83.2516],[35.7734,-82.9942],[35.998,-82.7751],[36.0637,-82.6382],[35.9651,-82.6108],[36.1568,-82.2164],[36.1185,-82.0357],[36.3047,-81.9097],[36.354,-81.7235],[36.5895,-81.6797],[36.5621,-80.9787]]],"ND":[[[49.0002,-97.2287],[48.6826,-97.0973],[48.5457,-97.163],[48.1404,-97.1302],[47.9487,-97.0535],[47.6091,-96.8563],[46.9683,-96.8234],[46.9245,-96.7851],[46.6561,-96.8015],[46.437,-96.7194],[46.333,-96.5989],[45.9332,-96.5606],[45.9441,-104.0475],[47.861,-104.0421],[49.0002,-104.0475],[49.0002,-97.2287]]],"OH":[[[41.9788,-80.5186],[40.637,-80.5186],[40.5822,-80.6665],[40.4726,-80.5953],[40.3193,-80.6008],[40.0783,-80.7377],[39.7113,-80.8308],[39.3882,-81.2196],[39.3444,-81.3456],[39.4101,-81.4552],[39.2677,-81.5702],[39.2732,-81.6852],[39.0815,-81.8112],[38.9665,-81.7838],[38.8734,-81.8878],[39.0267,-82.0357],[38.7857,-82.2219],[38.6324,-82.1726],[38.5776,-82.2931],[38.4462,-82.3315],[38.4243,-82.5944],[38.5612,-82.7313],[38.5886,-82.8463],[38.7584,-82.8901],[38.7255,-83.0325],[38.6269,-83.1421],[38.7036,-83.52],[38.6324,-83.6788],[38.7693,-83.9033],[38.8077,-84.2155],[38.8953,-84.232],[39.1034,-84.4346],[39.1034,-84.818],[40.5,-84.8016],[41.694,-84.807],[41.7323,-83.4542],[41.5954,-83.0654],[41.5133,-82.9339],[41.5899,-82.8353],[41.4311,-82.6163],[41.3818,-82.4793],[41.5133,-82.0138],[41.4859,-81.74],[41.6721,-81.4442],[41.8528,-81.0115],[41.9788,-80.5186],[41.9788,-80.5186]]],"OK":[[[37.0003,-100.0877],[37.0003,-94.6162],[36.5019,-94.6162],[35.3955,-94.43],[33.6374,-94.4848],[33.747,-94.8682],[33.862,-94.9668],[33.9606,-95.2242],[33.8729,-95.2899],[33.8784,-95.5473],[33.9332,-95.6021],[33.8346,-95.8376],[33.8894,-95.9362],[33.8401,-96.1498],[33.6867,-96.347],[33.7743,-96.4236],[33.8455,-96.6318],[33.8455,-96.8508],[33.9606,-96.922],[33.736,-97.174],[33.862,-97.2561],[33.8236,-97.3711],[33.9058,-97.4588],[33.9825,-97.6943],[33.851,-97.8695],[33.9879,-97.9462],[34.0044,-98.0886],[34.1139,-98.1708],[34.1577,-98.3625],[34.0646,-98.4884],[34.1468,-98.5706],[34.1358,-98.7678],[34.2235,-98.9868],[34.2125,-99.1895],[34.4042,-99.2607],[34.4151,-99.5784],[34.3823,-99.6988],[34.574,-99.9234],[34.563,-100.0001],[36.5019,-100.0001],[36.5019,-101.8129],[36.5019,-103.0014],[37.0003,-103.0014],[36.9948,-102.043],[37.0003,-100.0877]]],"OR":[[[46.1741,-123.2113],[46.1851,-123.1182],[46.081,-122.9046],[45.9605,-122.8115],[45.6593,-122.7622],[45.5498,-122.2474],[45.7086,-121.8093],[45.725,-121.5354],[45.6703,-121.2177],[45.6045,-121.1849],[45.7469,-120.6372],[45.6976,-120.5057],[45.725,-120.21],[45.8236,-119.9635],[45.9112,-119.5254],[45.9332,-119.1256],[45.9989,-118.9886],[45.9934,-116.9183],[45.8236,-116.7814],[45.7524,-116.5459],[45.6155,-116.4638],[45.3197,-116.6719],[45.1445,-116.7321],[45.024,-116.8471],[44.9309,-116.8307],[44.783,-116.9348],[44.7501,-117.0388],[44.3941,-117.2415],[44.2572,-117.1703],[44.2408,-116.9786],[44.1586,-116.8964],[43.83,-117.0279],[42.0007,-117.0279],[41.9898,-118.6983],[41.9952,-120.0019],[41.9952,-121.037],[42.0117,-122.3789],[42.0062,-123.2333],[42.0007,-124.2136],[42.1157,-124.356],[42.4389,-124.4327],[42.6634,-124.4163],[42.8387,-124.5532],[43.003,-124.4546],[43.2714,-124.3834],[43.5562,-124.2355],[43.8081,-124.1698],[44.657,-124.0603],[44.772,-124.0767],[45.1445,-123.9781],[45.6593,-123.9398],[45.9441,-123.9946],[46.1139,-123.9453],[46.2618,-123.5454],[46.1468,-123.3702],[46.1741,-123.2113]]],"PA":[[[42.2526,-79.7628],[42.0007,-79.7628],[42.0007,-75.3593],[41.8638,-75.2498],[41.8693,-75.1731],[41.7542,-75.0526],[41.6064,-75.0745],[41.4366,-74.8938],[41.4311,-74.7404],[41.3599,-74.6966],[41.2887,-74.8281],[41.1792,-74.8828],[40.971,-75.1348],[40.867,-75.0526],[40.6917,-75.206],[40.5767,-75.195],[40.5438,-75.069],[40.4179,-75.0581],[40.2152,-74.7733],[40.1276,-74.8226],[39.9633,-75.1293],[39.8866,-75.1457],[39.8045,-75.4141],[39.8318,-75.6167],[39.7223,-75.7865],[39.7223,-79.478],[39.7223,-80.5186],[40.637,-80.5186],[41.9788,-80.5186],[41.9788,-80.5186],[42.0336,-80.3324],[42.2691,-79.7628],[42.2526,-79.7628]]],"RI":[[[41.6776,-71.1968],[41.4968,-71.1202],[41.4749,-71.3173],[41.6776,-71.1968]],[[42.0171,-71.5309],[42.0171,-71.3831],[41.7816,-71.3283],[41.7104,-71.2242],[41.7269,-71.3447],[41.579,-71.4488],[41.3709,-71.4816],[41.3216,-71.8596],[41.4147,-71.7993],[42.0062,-71.7993],[42.0171,-71.5309]]],"SC":[[[35.0669,-82.7641],[35.16,-82.5505],[35.1983,-82.2767],[35.1491,-81.0444],[35.045,-81.0389],[35.1052,-80.9348],[34.9355,-80.7815],[34.8204,-80.7979],[34.804,-79.6751],[33.851,-78.5414],[33.8017,-78.7167],[33.6374,-78.9358],[33.38,-79.1494],[33.1719,-79.1877],[33.0076,-79.3575],[33.0076,-79.582],[32.8871,-79.6313],[32.7556,-79.8668],[32.6132,-79.9983],[32.553,-80.2064],[32.3996,-80.431],[32.3284,-80.4529],[32.2463,-80.661],[32.0327,-80.8856],[32.1203,-81.1156],[32.2901,-81.1211],[32.5585,-81.2799],[32.6297,-81.4168],[32.8433,-81.4278],[33.0076,-81.4935],[33.1609,-81.7619],[33.3471,-81.9371],[33.4622,-81.9262],[33.6319,-82.1945],[33.8182,-82.326],[33.9441,-82.556],[34.1523,-82.7149],[34.2673,-82.7477],[34.4863,-82.9011],[34.4699,-83.0051],[34.6835,-83.3392],[34.7876,-83.3228],[35.0012,-83.1092],[35.0669,-82.7641]]],"SD":[[[45.9441,-104.0475],[45.9332,-96.5606],[45.8181,-96.5825],[45.6045,-96.8563],[45.4128,-96.681],[45.2978,-96.451],[43.5014,-96.451],[43.4795,-96.5825],[43.3973,-96.5277],[43.2221,-96.5606],[43.1235,-96.4346],[43.0523,-96.5113],[42.8551,-96.5441],[42.7072,-96.6318],[42.4882,-96.4455],[42.5155,-96.6263],[42.6579,-96.692],[42.8442,-97.2178],[42.8442,-97.6888],[42.8661,-97.8312],[42.7675,-97.9517],[42.9482,-98.4665],[42.9975,-98.4994],[42.9975,-101.6267],[43.003,-103.3246],[43.003,-104.053],[44.9966,-104.0585],[44.9966,-104.0421],[45.9441,-104.0475]]],"TN":[[[36.4964,-88.0549],[36.6771,-88.0713],[36.6333,-87.8522],[36.6552,-86.5925],[36.6169,-85.4862],[36.6278,-85.289],[36.595,-84.5441],[36.584,-83.6897],[36.6004,-83.6733],[36.5895,-81.6797],[36.354,-81.7235],[36.3047,-81.9097],[36.1185,-82.0357],[36.1568,-82.2164],[35.9651,-82.6108],[36.0637,-82.6382],[35.998,-82.7751],[35.7734,-82.9942],[35.7187,-83.2516],[35.5653,-83.4981],[35.5598,-83.7719],[35.4119,-84.0184],[35.2476,-84.095],[35.2257,-84.2922],[34.9902,-84.3196],[34.9847,-85.6067],[35.0012,-87.3593],[34.9957,-88.2027],[34.9957,-88.4711],[34.9957,-90.3114],[35.0231,-90.2128],[35.1983,-90.1142],[35.4393,-90.1306],[35.6036,-89.9444],[35.757,-89.9116],[35.8118,-89.7637],[35.998,-89.7308],[36.2499,-89.5336],[36.4964,-89.5391],[36.4964,-89.4843],[36.4964,-89.4186],[36.5073,-89.2981],[36.4964,-88.0549]]],"TX":[[[36.5019,-101.8129],[36.5019,-100.0001],[34.563,-100.0001],[34.574,-99.9234],[34.3823,-99.6988],[34.4151,-99.5784],[34.4042,-99.2607],[34.2125,-99.1895],[34.2235,-98.9868],[34.1358,-98.7678],[34.1468,-98.5706],[34.0646,-98.4884],[34.1577,-98.3625],[34.1139,-98.1708],[34.0044,-98.0886],[33.9879,-97.9462],[33.851,-97.8695],[33.9825,-97.6943],[33.9058,-97.4588],[33.8236,-97.3711],[33.862,-97.2561],[33.736,-97.174],[33.9606,-96.922],[33.8455,-96.8508],[33.8455,-96.6318],[33.7743,-96.4236],[33.6867,-96.347],[33.8401,-96.1498],[33.8894,-95.9362],[33.8346,-95.8376],[33.9332,-95.6021],[33.8784,-95.5473],[33.8729,-95.2899],[33.9606,-95.2242],[33.862,-94.9668],[33.747,-94.8682],[33.6374,-94.4848],[33.5443,-94.3807],[33.5936,-94.1836],[33.5498,-94.0412],[33.0185,-94.0412],[31.9943,-94.0412],[31.7753,-93.8221],[31.5562,-93.8166],[31.1509,-93.5428],[30.9373,-93.5263],[30.6799,-93.6304],[30.5758,-93.729],[30.4389,-93.6961],[30.3348,-93.7673],[30.1431,-93.6906],[29.7871,-93.9261],[29.6885,-93.8385],[29.6831,-94.0028],[29.5461,-94.5231],[29.6228,-94.7094],[29.7871,-94.7422],[29.6721,-94.8737],[29.6995,-94.9668],[29.5571,-95.0161],[29.4969,-94.912],[29.3106,-94.8956],[29.1135,-95.0818],[28.867,-95.383],[28.6041,-95.9855],[28.6479,-96.0457],[28.5822,-96.2265],[28.6425,-96.2319],[28.5986,-96.4784],[28.7246,-96.5934],[28.6972,-96.6646],[28.4398,-96.4017],[28.3577,-96.5934],[28.4069,-96.7742],[28.2262,-96.8015],[28.04,-97.0261],[27.6949,-97.2561],[27.3335,-97.404],[27.3608,-97.5135],[27.2294,-97.5409],[27.2623,-97.4259],[26.9994,-97.4807],[26.9884,-97.5574],[26.8405,-97.5628],[26.7584,-97.4697],[26.4572,-97.4423],[26.3531,-97.3328],[26.1614,-97.3054],[25.9916,-97.2178],[25.8876,-97.5245],[26.019,-97.6505],[26.0683,-97.886],[26.0573,-98.1982],[26.2216,-98.4665],[26.2381,-98.6692],[26.3695,-98.8225],[26.4133,-99.0307],[26.5393,-99.1731],[26.8405,-99.2662],[27.0213,-99.4469],[27.1746,-99.425],[27.3389,-99.5071],[27.4813,-99.4798],[27.6402,-99.6057],[27.6566,-99.7098],[27.799,-99.8796],[27.9797,-99.9344],[28.1441,-100.0822],[28.281,-100.2958],[28.5822,-100.3999],[28.6644,-100.4985],[28.9053,-100.6299],[29.1025,-100.6737],[29.2449,-100.7997],[29.3709,-101.0133],[29.4585,-101.0626],[29.5352,-101.2598],[29.7543,-101.4131],[29.8036,-101.8513],[29.7926,-102.1142],[29.8693,-102.3387],[29.7652,-102.388],[29.7324,-102.629],[29.5242,-102.8097],[29.1901,-102.9193],[29.1847,-102.9795],[28.9875,-103.1165],[28.982,-103.2808],[29.1354,-103.5272],[29.3818,-104.1461],[29.5133,-104.2666],[29.6393,-104.5076],[29.9241,-104.6774],[30.1815,-104.6883],[30.3896,-104.8581],[30.5703,-104.8965],[30.6854,-105.006],[30.8551,-105.3949],[31.0852,-105.603],[31.1673,-105.7728],[31.3645,-105.9535],[31.4686,-106.2054],[31.7314,-106.3807],[31.7862,-106.5286],[31.9012,-106.6436],[31.9998,-106.6162],[31.9998,-103.0672],[33.0021,-103.0672],[34.0153,-103.0453],[36.5019,-103.0398],[36.5019,-103.0014],[36.5019,-101.8129]]],"UT":[[[41.9952,-112.1644],[42.0007,-111.0471],[40.9984,-111.0471],[40.9984,-109.048],[39.1253,-109.0535],[38.2764,-109.0589],[38.1669,-109.0425],[37.0003,-109.0425],[37.0057,-110.4994],[37.0003,-114.0484],[41.9952,-114.043],[41.9952,-112.1644]]],"VT":[[[45.013,-71.5036],[44.9144,-71.4926],[44.7501,-71.6295],[44.5858,-71.5364],[44.416,-71.7007],[44.3229,-72.0348],[44.0765,-72.0293],[43.9943,-72.117],[43.7698,-72.2046],[43.5726,-72.3799],[43.1509,-72.4565],[43.0085,-72.4456],[42.9537,-72.5332],[42.8058,-72.5442],[42.7291,-72.4565],[42.7456,-73.2671],[42.8332,-73.2781],[43.5233,-73.2452],[43.6876,-73.4041],[43.7698,-73.3493],[44.0436,-73.4369],[44.2463,-73.3219],[44.4379,-73.2945],[44.6187,-73.3876],[44.8049,-73.3329],[45.013,-73.3438],[45.0021,-72.3087],[45.013,-71.5036]]],"VA":[[[38.0135,-75.3977],[38.0299,-75.2443],[37.8601,-75.3758],[37.7999,-75.5127],[37.5699,-75.5948],[37.1974,-75.803],[37.1208,-75.9727],[37.2577,-76.0275],[37.5644,-75.9399],[37.9532,-75.6715],[38.0135,-75.3977]],[[37.9532,-76.0166],[37.9532,-75.9946],[37.9532,-76.0439],[37.9532,-76.0166]],[[39.4649,-78.3497],[39.1308,-77.8294],[39.3225,-77.7199],[39.3061,-77.5665],[39.2239,-77.457],[39.076,-77.457],[39.0267,-77.2489],[38.9336,-77.1174],[38.7912,-77.0407],[38.6324,-77.1284],[38.5886,-77.2489],[38.4462,-77.3255],[38.3421,-77.2817],[38.375,-77.0134],[38.2161,-76.9641],[38.1504,-76.6135],[38.0245,-76.515],[37.8875,-76.2356],[37.6082,-76.3616],[37.3891,-76.2466],[37.2851,-76.3835],[37.1591,-76.3999],[37.0824,-76.274],[36.9619,-76.4109],[37.1208,-76.619],[37.066,-76.6683],[36.951,-76.4876],[36.9236,-75.9946],[36.5512,-75.8687],[36.5402,-79.5108],[36.5457,-80.294],[36.5621,-80.9787],[36.5895,-81.6797],[36.6004,-83.6733],[36.7428,-83.1366],[36.8524,-83.0709],[36.8907,-82.8792],[36.9784,-82.8682],[37.0441,-82.7203],[37.1208,-82.7203],[37.2686,-82.3534],[37.537,-81.97],[37.4548,-81.9864],[37.2851,-81.8495],[37.2029,-81.6797],[37.2084,-81.5537],[37.3398,-81.362],[37.2358,-81.2251],[37.2905,-80.9677],[37.4822,-80.5131],[37.422,-80.4748],[37.5096,-80.2995],[37.6904,-80.294],[37.8492,-80.1845],[37.9971,-79.9983],[38.1778,-79.9216],[38.364,-79.7244],[38.5941,-79.6478],[38.4571,-79.478],[38.4133,-79.3137],[38.4955,-79.2096],[38.8515,-78.996],[38.7638,-78.87],[39.1691,-78.4045],[39.4649,-78.3497]]],"WA":[[[49.0002,-117.0334],[47.7625,-117.0443],[46.4261,-117.0388],[46.3439,-117.0553],[46.1687,-116.9238],[45.9934,-116.9183],[45.9989,-118.9886],[45.9332,-119.1256],[45.9112,-119.5254],[45.8236,-119.9635],[45.725,-120.21],[45.6976,-120.5057],[45.7469,-120.6372],[45.6045,-121.1849],[45.6703,-121.2177],[45.725,-121.5354],[45.7086,-121.8093],[45.5498,-122.2474],[45.6593,-122.7622],[45.9605,-122.8115],[46.081,-122.9046],[46.1851,-123.1182],[46.1741,-123.2113],[46.1468,-123.3702],[46.2618,-123.5454],[46.3001,-123.7262],[46.2399,-123.8741],[46.3275,-124.0658],[46.4644,-124.0274],[46.5356,-123.896],[46.7437,-124.0986],[47.286,-124.2355],[47.3572,-124.3177],[47.7405,-124.4272],[47.8884,-124.6244],[48.1842,-124.7066],[48.3813,-124.597],[48.2882,-124.3944],[48.1623,-123.9836],[48.1677,-123.7043],[48.1185,-123.4249],[48.1677,-123.1621],[48.0801,-123.0361],[48.0856,-122.8006],[47.8665,-122.6363],[47.8829,-122.5158],[47.5872,-122.4939],[47.3188,-122.4227],[47.3462,-122.3241],[47.5762,-122.4227],[47.8008,-122.3953],[48.0308,-122.231],[48.1239,-122.3624],[48.2882,-122.3734],[48.469,-122.472],[48.6004,-122.4227],[48.7538,-122.4884],[48.7757,-122.6472],[48.8907,-122.7951],[49.0002,-122.7568],[49.0002,-117.0334]],[[48.3101,-122.7184],[48.354,-122.587],[48.1513,-122.6089],[48.228,-122.7677],[48.3101,-122.7184]],[[48.584,-123.0251],[48.7154,-122.9156],[48.5566,-122.7677],[48.4197,-122.8115],[48.458,-123.0416],[48.584,-123.0251]]],"WV":[[[40.637,-80.5186],[39.7223,-80.5186],[39.7223,-79.478],[39.2075,-79.4889],[39.3006,-79.2918],[39.4704,-79.0946],[39.4375,-78.9631],[39.5854,-78.766],[39.5142,-78.4702],[39.6237,-78.4319],[39.6182,-78.2676],[39.6949,-78.1745],[39.6018,-78.0047],[39.6018,-77.8349],[39.3225,-77.7199],[39.1308,-77.8294],[39.4649,-78.3497],[39.1691,-78.4045],[38.7638,-78.87],[38.8515,-78.996],[38.4955,-79.2096],[38.4133,-79.3137],[38.4571,-79.478],[38.5941,-79.6478],[38.364,-79.7244],[38.1778,-79.9216],[37.9971,-79.9983],[37.8492,-80.1845],[37.6904,-80.294],[37.5096,-80.2995],[37.422,-80.4748],[37.4822,-80.5131],[37.2905,-80.9677],[37.2358,-81.2251],[37.3398,-81.362],[37.2084,-81.5537],[37.2029,-81.6797],[37.2851,-81.8495],[37.4548,-81.9864],[37.537,-81.97],[37.5534,-82.1014],[37.6684,-82.2931],[37.7835,-82.3424],[37.9313,-82.5012],[38.123,-82.6217],[38.4243,-82.5944],[38.4462,-82.3315],[38.5776,-82.2931],[38.6324,-82.1726],[38.7857,-82.2219],[39.0267,-82.0357],[38.8734,-81.8878],[38.9665,-81.7838],[39.0815,-81.8112],[39.2732,-81.6852],[39.2677,-81.5702],[39.4101,-81.4552],[39.3444,-81.3456],[39.3882,-81.2196],[39.7113,-80.8308],[40.0783,-80.7377],[40.3193,-80.6008],[40.4726,-80.5953],[40.5822,-80.6665],[40.637,-80.5186]]],"WI":[[[46.5685,-90.4154],[46.5082,-90.2292],[46.3384,-90.1197],[46.1358,-89.09],[45.9879,-88.6628],[46.0208,-88.5314],[45.9222,-88.1042],[45.7962,-87.9891],[45.6757,-87.781],[45.5005,-87.792],[45.3636,-87.8851],[45.3416,-87.6496],[45.1992,-87.7427],[45.0952,-87.5893],[44.9747,-87.6277],[44.9528,-87.8194],[44.7227,-87.9837],[44.5639,-88.0439],[44.5365,-87.9289],[44.6406,-87.7755],[44.8378,-87.6112],[44.9144,-87.4031],[45.1664,-87.2388],[45.2212,-87.0307],[45.0897,-87.0471],[44.9692,-87.1895],[44.553,-87.4688],[44.3229,-87.5455],[44.1586,-87.54],[44.1039,-87.6441],[43.8793,-87.7372],[43.6876,-87.7043],[43.5616,-87.792],[43.2495,-87.9125],[43.003,-87.8851],[42.7839,-87.7646],[42.4936,-87.8029],[42.4936,-88.7888],[42.5101,-90.64],[42.636,-90.7112],[42.751,-91.0672],[42.9099,-91.1439],[43.1344,-91.1767],[43.2549,-91.0562],[43.3535,-91.2041],[43.5014,-91.2151],[43.6164,-91.2698],[43.7752,-91.2424],[43.9943,-91.4341],[44.0327,-91.593],[44.2024,-91.8778],[44.3339,-91.9271],[44.4434,-92.2338],[44.553,-92.3378],[44.5694,-92.546],[44.7501,-92.8089],[45.1171,-92.7377],[45.2869,-92.7596],[45.4402,-92.6445],[45.5662,-92.7705],[45.5772,-92.8855],[45.7196,-92.8691],[45.9332,-92.6391],[46.0153,-92.3543],[46.0756,-92.294],[46.6671,-92.294],[46.7492,-92.0914],[46.7054,-92.0147],[46.6944,-91.7901],[46.8642,-91.0946],[46.9573,-90.8372],[46.8861,-90.7495],[46.7547,-90.8864],[46.5849,-90.5578],[46.5685,-90.4154]]],"WY":[[[45.0021,-109.0808],[45.0021,-105.9152],[44.9966,-104.0585],[43.003,-104.053],[41.0039,-104.053],[40.9984,-105.729],[41.0039,-107.9197],[40.9984,-109.048],[40.9984,-111.0471],[42.0007,-111.0471],[44.4763,-111.0471],[45.0021,-111.0525],[45.0021,-109.0808]]]}} \ No newline at end of file diff --git a/selfdrive/mapd/db_paths.py b/selfdrive/mapd/db_paths.py new file mode 100644 index 00000000000000..77d256d4c5e6f3 --- /dev/null +++ b/selfdrive/mapd/db_paths.py @@ -0,0 +1,17 @@ +import os + +from openpilot.selfdrive.mapd.constants import DB_FILENAME + + +def osm_dir() -> str: + # Avoid hardware/cereal so mapd unit tests and fetch_maps stay importable off-device. + if os.path.isdir("/data/media/0"): + return "/data/media/0/osm" + return os.path.join(os.path.expanduser("~"), ".comma", "media", "0", "osm") + + +def default_db_path() -> str: + override = os.environ.get("NAP_MAP_DB") + if override: + return override + return os.path.join(osm_dir(), DB_FILENAME) diff --git a/selfdrive/mapd/fetch_maps.py b/selfdrive/mapd/fetch_maps.py new file mode 100644 index 00000000000000..80a959f897359c --- /dev/null +++ b/selfdrive/mapd/fetch_maps.py @@ -0,0 +1,719 @@ +"""Download a prebuilt NAP OSM speed-limit sqlite from a GitHub Release. + +Stages on the destination filesystem (not /tmp). US pack peak is the zst plus +the sqlite.partial before the zst is deleted: ~399 MiB + ~1094 MiB. + +Downloads retry (DOWNLOAD_ATTEMPTS, backoff) and resume with HTTP Range from +.download/.partial, also across taps. Only a SHA-256 mismatch throws +the staged bytes away. +""" +from __future__ import annotations + +import argparse +import errno +import hashlib +import json +import os +import shutil +import time +import http.client +import urllib.error +import urllib.request +from urllib.parse import unquote, urlparse + +from openpilot.selfdrive.mapd.db_paths import default_db_path +from openpilot.selfdrive.mapd.maps_manifest import ( + ASSET_NAME, + ASSET_SHA256, + ASSET_SQLITE_BYTES, + ASSET_ZST_BYTES, + ATTRIBUTION, + FREE_MARGIN_BYTES, + GITHUB_REPO, + LICENSE, + LICENSE_URL, + MAPS_INDEX_URL, + MIN_FREE_BYTES, + MIN_FREE_MIB, + PARAM_REVISION, + PARAM_SHA256, + RELEASE_TAG, + REVISION_SIDECAR, + SQLITE_SHA256, + USER_AGENT, + MapsIndex, + bundled_maps_index, + maps_update_decision, + parse_maps_index, + release_asset_url, +) +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB + +CHUNK = 256 * 1024 +STAGING_DIRNAME = ".download" +# Wi-Fi drops / slow GitHub CDN: retry with backoff and resume via HTTP Range. +DOWNLOAD_ATTEMPTS = 8 +READ_TIMEOUT_S = 60.0 +BACKOFF_BASE_S = 2.0 +BACKOFF_MAX_S = 30.0 +# Records which zst digest a resumable partial belongs to. +EXPECT_SUFFIX = ".expect" + + +class HashMismatchError(RuntimeError): + pass + + +class _Retryable(Exception): + pass + + +def _p(msg: str) -> None: + print(msg, flush=True) + + +def _sqlite_present(path: str | None) -> bool: + if not path or not os.path.isfile(path): + return False + try: + return os.path.getsize(path) >= 1024 + except OSError: + return False + + +sqlite_present = _sqlite_present + + +def installed_db_summary(path: str | None = None) -> str: + path = path or default_db_path() + if not _sqlite_present(path): + return "Not installed" + try: + sz = os.path.getsize(path) + except OSError: + return "Not installed" + mb = sz / (1024 * 1024) + ways = OsmSpeedLimitDB.way_count(path) + if ways is None: + return f"Installed ({mb:.0f} MB)" + return f"Installed ({mb:.0f} MB, {ways:,} ways)" + + +def _sidecar_path(dest: str) -> str: + return os.path.join(os.path.dirname(os.path.abspath(dest)) or ".", REVISION_SIDECAR) + + +def _params_get(key: str) -> str: + try: + from openpilot.common.params import Params + raw = Params().get(key) + except Exception: + return "" + if raw is None: + return "" + if isinstance(raw, bytes): + raw = raw.decode("utf-8", errors="replace") + return str(raw).strip() + + +def _params_put(key: str, value: str) -> None: + try: + from openpilot.common.params import Params + Params().put(key, value) + except Exception: + pass + + +def load_installed_revision(dest: str | None = None) -> tuple[str, str]: + """Return (revision, zst sha256) recorded after a successful install. + + Prefers the sidecar next to the sqlite so the check works without a + params rebuild. Falls back to NAPMapSpeedDbRevision / NAPMapSpeedDbSha256. + """ + dest = os.path.abspath(dest or default_db_path()) + sidecar = _sidecar_path(dest) + if os.path.isfile(sidecar): + try: + with open(sidecar, encoding="utf-8") as f: + data = json.load(f) + if isinstance(data, dict): + rev = str(data.get("revision") or "").strip() + sha = str(data.get("sha256") or "").strip().lower() + return rev, sha + except (OSError, ValueError, TypeError): + pass + return _params_get(PARAM_REVISION), _params_get(PARAM_SHA256).lower() + + +def record_installed_maps(index: MapsIndex, dest: str | None = None) -> None: + """Persist revision + zst sha after a successful fetch. Sidecar + params.""" + dest = os.path.abspath(dest or default_db_path()) + payload = { + "revision": index.revision, + "sha256": (index.sha256 or "").lower(), + "asset_name": index.asset_name, + "asset_url": index.asset_url, + } + sidecar = _sidecar_path(dest) + try: + os.makedirs(os.path.dirname(sidecar) or ".", exist_ok=True) + tmp = sidecar + ".partial" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(payload, f, indent=2) + f.write("\n") + os.replace(tmp, sidecar) + except OSError: + pass + if index.revision: + _params_put(PARAM_REVISION, index.revision) + if index.sha256: + _params_put(PARAM_SHA256, index.sha256.lower()) + + +def installed_revision_summary(path: str | None = None) -> str: + path = path or default_db_path() + if not _sqlite_present(path): + return "Not installed" + rev, _sha = load_installed_revision(path) + if rev: + return rev + return "Unversioned" + + +def fetch_maps_index(url: str | None = None) -> MapsIndex: + """Download and parse the published maps-index JSON (not the sqlite).""" + url = url or os.environ.get("NAP_MAPS_INDEX_URL") or MAPS_INDEX_URL + if url.startswith("file:"): + path = unquote(urlparse(url).path) + try: + with open(path, encoding="utf-8") as f: + raw = f.read() + except OSError as e: + raise RuntimeError(f"Could not read maps index {url}: {e}") from e + return parse_maps_index(raw) + + req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as resp: + raw = resp.read() + except urllib.error.HTTPError as e: + raise RuntimeError( + f"Maps index failed HTTP {e.code} for {url}. Need Wi-Fi to GitHub." + ) from e + except urllib.error.URLError as e: + raise RuntimeError(f"Maps index download failed: {e}. Need Wi-Fi to GitHub.") from e + return parse_maps_index(raw) + + +def resolve_published_index(*, index_url: str | None = None, fallback: bool = True) -> MapsIndex: + """Live index, or bundled first-install constants if fallback is allowed.""" + try: + index = fetch_maps_index(index_url) + _p(f"Maps index: revision {index.revision} ({index.asset_name})") + return index + except Exception as e: + if not fallback: + raise + _p(f"Published maps index unavailable ({e}). Using first-install constants.") + return bundled_maps_index() + + +def fetch_and_install_from_index(index: MapsIndex, dest: str | None = None) -> str: + """Shared US-pack fetch used by Download US Maps.""" + dest = fetch_and_install( + dest=dest, + url=index.asset_url, + sha256=index.sha256, + sqlite_sha256=SQLITE_SHA256, + ) + record_installed_maps(index, dest) + return dest + + +def download_maps(dest: str | None = None, *, index_url: str | None = None) -> str: + """Install the current published US pack (index if reachable, else bundled).""" + index = resolve_published_index(index_url=index_url, fallback=True) + return fetch_and_install_from_index(index, dest) + + +def refresh_maps(dest: str | None = None, *, index_url: str | None = None) -> str | None: + """CLI: version-check the published US index; download only if missing or newer. + + Settings → Refresh maps is live Overpass (`local_refresh.refresh_local_maps`), + not this function. Keep this for `python -m scripts.nap.fetch_osm_maps --refresh`. + """ + dest = os.path.abspath(dest or default_db_path()) + index = resolve_published_index(index_url=index_url, fallback=False) + if index.notes: + _p(index.notes) + has_sqlite = _sqlite_present(dest) + installed_rev, installed_sha = load_installed_revision(dest) + decision = maps_update_decision(has_sqlite, installed_rev, installed_sha, index) + if decision == "up_to_date": + if has_sqlite and (not installed_rev or not installed_sha): + record_installed_maps(index, dest) + _p(f"Maps are up to date (revision {index.revision})") + return None + if decision == "install": + _p("No maps installed yet. Downloading the current US pack…") + else: + from_rev = installed_rev or "unversioned" + _p(f"Update available: {from_rev} → {index.revision}") + return fetch_and_install_from_index(index, dest) + + +def _sha256_file(path: str) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + while True: + chunk = f.read(1024 * 1024) + if not chunk: + break + h.update(chunk) + return h.hexdigest() + + +def _progress(prefix: str, done: int, total: int) -> None: + if total > 0: + pct = min(100.0, 100.0 * done / total) + _p(f"{prefix} {done / 1e6:.1f}/{total / 1e6:.1f} MB ({pct:.0f}%)") + else: + _p(f"{prefix} {done / 1e6:.1f} MB") + + +def staging_dir(dest: str) -> str: + return os.path.join(os.path.dirname(os.path.abspath(dest)) or ".", STAGING_DIRNAME) + + +def cleanup_incomplete(dest: str, *, keep_resume: bool = False) -> None: + """Remove leftover partials/staging from a failed or interrupted fetch. + + keep_resume keeps the staged download (*.zst.partial / *.zst and its + .expect tag) so the next Download US Maps tap resumes with HTTP Range. + """ + victims = [dest + ".partial"] + stage = staging_dir(dest) + if os.path.isdir(stage): + try: + names = os.listdir(stage) + except OSError: + names = [] + for name in names: + if keep_resume and name.endswith((".partial", EXPECT_SUFFIX, ".zst")): + continue + victims.append(os.path.join(stage, name)) + for p in victims: + try: + if os.path.isfile(p) or os.path.islink(p): + os.remove(p) + except OSError: + pass + try: + if os.path.isdir(stage) and not os.listdir(stage): + os.rmdir(stage) + except OSError: + pass + + +def _space_error(dest: str, free: int, need: int) -> RuntimeError: + dest_dir = os.path.dirname(os.path.abspath(dest)) or "." + osm = dest_dir + return RuntimeError( + f"Not enough free space on {dest_dir}. " + + f"Need {need / (1024 * 1024):.0f} MiB, have {free / (1024 * 1024):.0f} MiB. " + + f"US pack is ~{ASSET_ZST_BYTES / (1024 * 1024):.0f} MiB zst + " + + f"~{ASSET_SQLITE_BYTES / (1024 * 1024):.0f} MiB sqlite " + + f"(peak both on this filesystem; +{FREE_MARGIN_BYTES / (1024 * 1024):.0f} MiB margin, " + + f"threshold {MIN_FREE_MIB} MiB / {MIN_FREE_BYTES} bytes). " + + "Clean leftovers then routes/videos if still short:\n" + + f" rm -f {osm}/*.partial {osm}/{STAGING_DIRNAME}/*\n" + + f" df -h {dest_dir}\n" + + "Smaller region (PC, then scp): python scripts/nap/download_osm_speed_limits.py " + + "--lat --lon --radius-km 30" + ) + + +def required_free_bytes(zst_bytes: int | None = None, *, us_pack: bool = True) -> int: + """Bytes that must be free on the dest filesystem before a fetch. + + US pack: max(zst + sqlite + margin, MIN_FREE_BYTES) = 822 MiB. + Local/test installs (file://, empty sha256) only need a small headroom. + """ + if not us_pack: + extra = int(zst_bytes or 0) + return max(extra + 8 * 1024 * 1024, 8 * 1024 * 1024) + zst = ASSET_ZST_BYTES if not zst_bytes or zst_bytes <= 0 else int(zst_bytes) + need = zst + ASSET_SQLITE_BYTES + FREE_MARGIN_BYTES + return max(need, MIN_FREE_BYTES) + + +def assert_free_space(dest: str, zst_bytes: int | None = None, *, us_pack: bool = True, + already_staged: int = 0) -> int: + dest_dir = os.path.dirname(os.path.abspath(dest)) or "." + os.makedirs(dest_dir, exist_ok=True) + # A resumable partial already sits on this filesystem; it counts toward the budget. + free = int(shutil.disk_usage(dest_dir).free) + max(0, int(already_staged)) + need = required_free_bytes(zst_bytes, us_pack=us_pack) + _p(f"Free on {dest_dir}: {free / (1024 * 1024):.0f} MiB (need {need / (1024 * 1024):.0f} MiB)") + if free < need: + raise _space_error(dest, free, need) + return free + + +def _raise_if_enospc(exc: OSError, dest: str) -> None: + if exc.errno == errno.ENOSPC: + dest_dir = os.path.dirname(os.path.abspath(dest)) or "." + free = int(shutil.disk_usage(dest_dir).free) + raise _space_error(dest, free, required_free_bytes()) from exc + raise exc + + +def _backoff_s(attempt: int) -> float: + return min(BACKOFF_MAX_S, BACKOFF_BASE_S * (2 ** max(0, attempt - 1))) + + +def _content_range_start(value: str | None) -> int | None: + # "bytes 1000-1999/213762114" + try: + return int(str(value).split()[1].split("-")[0]) + except (IndexError, ValueError, AttributeError): + return None + + +def _content_range_total(value: str | None) -> int: + try: + tot = str(value).rsplit("/", 1)[1] + return 0 if tot == "*" else int(tot) + except (IndexError, ValueError, AttributeError): + return 0 + + +def _download_once(url: str, tmp: str, progress: bool, timeout: float) -> int: + """One HTTP attempt, appending to tmp from its current size. Returns total bytes in tmp. + + Raises _Retryable on timeouts / connection drops / 5xx / 429. + """ + have = os.path.getsize(tmp) if os.path.isfile(tmp) else 0 + headers = {"User-Agent": USER_AGENT} + if have > 0: + headers["Range"] = f"bytes={have}-" + req = urllib.request.Request(url, headers=headers) + try: + resp_cm = urllib.request.urlopen(req, timeout=timeout) + except urllib.error.HTTPError as e: + if e.code == 416 and have > 0: + # Range starts at/after EOF: the partial is already complete. + return have + if e.code >= 500 or e.code in (408, 429): + raise _Retryable(f"HTTP {e.code}") from e + raise RuntimeError( + f"Download failed HTTP {e.code} for {url}. " + + "Publish the OSM sqlite as a GitHub Release asset (see docs-nap/map-speed.md)." + ) from e + except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException) as e: + raise _Retryable(str(getattr(e, "reason", e))) from e + + with resp_cm as resp: + status = getattr(resp, "status", None) or resp.getcode() + if have > 0 and status == 206 and _content_range_start(resp.headers.get("Content-Range")) == have: + mode = "ab" + total = _content_range_total(resp.headers.get("Content-Range")) + if progress: + _p(f"Resuming at {have / 1e6:.1f} MB") + else: + # Server ignored Range (200) or answered a different range: start over. + mode, have = "wb", 0 + total = int(resp.headers.get("Content-Length") or 0) + n = have + last = n + read = getattr(resp, "read1", None) or resp.read + try: + with open(tmp, mode) as f: + while True: + try: + # read1: return what has arrived, so a stall keeps every received byte for the resume. + chunk = read(CHUNK) + except (TimeoutError, ConnectionError, http.client.HTTPException) as e: + raise _Retryable(str(e) or type(e).__name__) from e + except OSError as e: + if e.errno == errno.ENOSPC: + raise + raise _Retryable(str(e)) from e + if not chunk: + break + f.write(chunk) + n += len(chunk) + if progress and (n - last >= 5 * 1024 * 1024 or (total and n == total)): + _progress("Downloading", n, total) + last = n + except _Retryable: + raise + except OSError as e: + _raise_if_enospc(e, tmp) + if total and n < total: + raise _Retryable(f"connection closed at {n}/{total} bytes") + return n + + +def download_url(url: str, dest: str, progress: bool = True, *, attempts: int = DOWNLOAD_ATTEMPTS, + timeout: float = READ_TIMEOUT_S, sleep=time.sleep) -> int: + """Download url → dest with retries and HTTP Range resume from dest + '.partial'. + + The partial is kept on failure so a later call (second tap) resumes. Only a + hash mismatch (caller) deletes it. + """ + os.makedirs(os.path.dirname(dest) or ".", exist_ok=True) + tmp = dest + ".partial" + last_err = "" + for attempt in range(1, max(1, attempts) + 1): + try: + n = _download_once(url, tmp, progress, timeout) + os.replace(tmp, dest) + return n + except _Retryable as e: + last_err = str(e) or "connection error" + if attempt >= attempts: + break + wait = _backoff_s(attempt) + have = os.path.getsize(tmp) if os.path.isfile(tmp) else 0 + _p(f"Retrying… ({attempt}) {last_err}; {have / 1e6:.1f} MB kept, next try in {wait:.0f}s") + sleep(wait) + raise RuntimeError( + f"Download failed after {attempts} attempts: {last_err}. Need Wi-Fi to GitHub. " + + "Tap Download again to resume." + ) + + +def _decompress_zst(src: str, dest_partial: str) -> None: + """Stream-decompress src → dest_partial. Delete src after the stream succeeds + so peak disk is zst+partial, then partial only. Caller replaces onto dest.""" + os.makedirs(os.path.dirname(dest_partial) or ".", exist_ok=True) + try: + try: + import zstandard as zstd + except ImportError as e: + zstd_bin = shutil.which("zstd") + if not zstd_bin: + raise RuntimeError("Need the zstandard Python package (or zstd CLI) to decompress maps.") from e + import subprocess + try: + subprocess.check_call([zstd_bin, "-d", "-f", src, "-o", dest_partial]) + except subprocess.CalledProcessError as cpe: + raise RuntimeError(f"zstd decompress failed (exit {cpe.returncode})") from cpe + else: + dctx = zstd.ZstdDecompressor() + with open(src, "rb") as inf, open(dest_partial, "wb") as outf: + dctx.copy_stream(inf, outf) + try: + os.remove(src) + except OSError: + pass + except OSError as e: + try: + if os.path.isfile(dest_partial): + os.remove(dest_partial) + except OSError: + pass + _raise_if_enospc(e, dest_partial) + + +def _sqlite_ok(path: str) -> bool: + db = OsmSpeedLimitDB(path) + ok = db.open() + db.close() + return ok + + +sqlite_ok = _sqlite_ok + + +def _hash_requested(value: str | None) -> str: + """Non-empty stripped digest, or '' to skip. `--sha256 ''` is a valid skip.""" + if value is None: + return "" + return str(value).strip() + + +def _verify_sha256(path: str, sha256: str, *, kind: str) -> None: + got = _sha256_file(path) + if got.lower() != sha256.lower(): + raise HashMismatchError(f"SHA-256 mismatch for {path} ({kind}): got {got}, expected {sha256}") + + +def install_from_file( + src: str, + dest: str, + sha256: str = ASSET_SHA256, + sqlite_sha256: str = SQLITE_SHA256, +) -> str: + """Install a local .zst or sqlite onto dest. + + ASSET_SHA256 / sha256 is the **zst** digest and is checked on src **before** + decompress. Dest sqlite is never compared to that digest. SQLITE_SHA256 is + optional and empty by default. + """ + src = os.path.abspath(src) + dest = os.path.abspath(dest) + os.makedirs(os.path.dirname(dest) or ".", exist_ok=True) + zst_hash = _hash_requested(sha256) + sql_hash = _hash_requested(sqlite_sha256) + partial = dest + ".partial" + is_zst = src.lower().endswith(".zst") + try: + if is_zst: + if zst_hash: + _p("Verifying SHA-256 of downloaded zst (before decompress)…") + _verify_sha256(src, zst_hash, kind="zst, before decompress") + _p("Decompressing zstd…") + _decompress_zst(src, partial) + else: + # Raw sqlite: ASSET_SHA256 does not apply. + if sql_hash: + _verify_sha256(src, sql_hash, kind="sqlite") + shutil.copyfile(src, partial) + if sql_hash and is_zst: + _verify_sha256(partial, sql_hash, kind="sqlite") + if not _sqlite_ok(partial): + raise RuntimeError(f"Downloaded file is not a NAP OSM sqlite: {partial}") + os.replace(partial, dest) + except Exception: + try: + if os.path.isfile(partial): + os.remove(partial) + except OSError: + pass + raise + return dest + + +def fetch_and_install( + dest: str | None = None, + url: str | None = None, + sha256: str = ASSET_SHA256, + sqlite_sha256: str = SQLITE_SHA256, +) -> str: + dest = os.path.abspath(dest or default_db_path()) + url = url or os.environ.get("NAP_MAP_RELEASE_URL") or release_asset_url() + _p(f"OpenStreetMap speed limits ({LICENSE}). {ATTRIBUTION}") + _p(LICENSE_URL) + _p(f"Source: {url}") + _p(f"Install path: {dest}") + + dest_dir = os.path.dirname(dest) or "." + os.makedirs(dest_dir, exist_ok=True) + zst_hash = _hash_requested(sha256) + stage = staging_dir(dest) + packed_name = os.path.basename(url.split("?", 1)[0]) or ASSET_NAME + if not packed_name or packed_name in (".", "/"): + packed_name = ASSET_NAME + packed = os.path.join(stage, packed_name) + # Keep a staged download from an earlier tap only if it is for the same asset. + expect = f"{url}\n{zst_hash.lower()}\n" + expect_path = packed + EXPECT_SUFFIX + try: + with open(expect_path, encoding="utf-8") as f: + same = f.read() == expect + except OSError: + same = False + cleanup_incomplete(dest, keep_resume=same and bool(zst_hash)) + os.makedirs(stage, exist_ok=True) + if os.path.isfile(packed) and not os.path.isfile(packed + ".partial"): + # A finished zst from a run that died before install: resume (Range → 416) reuses it. + os.replace(packed, packed + ".partial") + staged = os.path.getsize(packed + ".partial") if os.path.isfile(packed + ".partial") else 0 + if staged: + _p(f"Resuming earlier download ({staged / 1e6:.1f} MB already on device)") + with open(expect_path, "w", encoding="utf-8") as f: + f.write(expect) + # Default Settings path (HTTPS + ASSET_SHA256) needs the US-pack budget. + # file:// / empty sha256 (tests, Overpass copies) skip the US-pack check. + us_pack = not url.startswith("file:") and bool(zst_hash) + assert_free_space(dest, us_pack=us_pack, already_staged=staged) + prev_tmpdir = os.environ.get("TMPDIR") + os.environ["TMPDIR"] = stage + + try: + n = download_url(url, packed) + _p(f"Downloaded {n / 1e6:.1f} MB → {packed}") + if us_pack: + # zst is now on dest fs; still need room for sqlite.partial + margin + dest_dir = os.path.dirname(os.path.abspath(dest)) or "." + free = int(shutil.disk_usage(dest_dir).free) + need_decomp = ASSET_SQLITE_BYTES + FREE_MARGIN_BYTES + _p(f"Free after zst: {free / (1024 * 1024):.0f} MiB (need {need_decomp / (1024 * 1024):.0f} MiB to decompress)") + if free < need_decomp: + raise _space_error(dest, free, need_decomp) + install_from_file(packed, dest, sha256=zst_hash, sqlite_sha256=sqlite_sha256) + if not packed.lower().endswith(".zst"): + try: + os.remove(packed) + except OSError: + pass + except HashMismatchError: + # Corrupt or stale bytes: the only case that throws the staged download away. + cleanup_incomplete(dest) + raise + except Exception: + cleanup_incomplete(dest, keep_resume=bool(zst_hash)) + raise + finally: + if prev_tmpdir is None: + os.environ.pop("TMPDIR", None) + else: + os.environ["TMPDIR"] = prev_tmpdir + + cleanup_incomplete(dest) + if not _sqlite_ok(dest): + raise RuntimeError(f"Downloaded file is not a NAP OSM sqlite: {dest}") + + _p(installed_db_summary(dest)) + _p("mapd reloads this file within ~15s onroad. No reboot required.") + return dest + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description="Fetch prebuilt US OSM speed-limit DB (ODbL) onto the device") + p.add_argument("--url", default=None, help="Override release asset URL") + p.add_argument("--tag", default=RELEASE_TAG) + p.add_argument("--repo", default=GITHUB_REPO) + p.add_argument("--asset", default=ASSET_NAME) + p.add_argument("--out", default=None, help="sqlite destination (default: /data/media/0/osm/speed_limits.sqlite)") + p.add_argument( + "--sha256", default=ASSET_SHA256, + help="SHA-256 of the zst asset (not sqlite). Empty string skips verification.", + ) + p.add_argument( + "--sqlite-sha256", default=SQLITE_SHA256, + help="Optional SHA-256 of the decompressed sqlite. Empty string skips (default).", + ) + p.add_argument("--status", action="store_true", help="Print installed DB summary and exit") + p.add_argument( + "--refresh", action="store_true", + help="Check published maps-index.json; download only if missing or newer", + ) + p.add_argument("--index-url", default=None, help="Override maps-index.json URL") + args = p.parse_args(argv) + + if args.status: + _p(installed_db_summary(args.out)) + _p(f"Revision: {installed_revision_summary(args.out)}") + return 0 + + try: + if args.refresh: + refresh_maps(dest=args.out, index_url=args.index_url) + elif args.url or args.tag != RELEASE_TAG or args.repo != GITHUB_REPO or args.asset != ASSET_NAME: + fetch_and_install( + dest=args.out, url=args.url or release_asset_url(args.repo, args.tag, args.asset), + sha256=args.sha256, sqlite_sha256=args.sqlite_sha256, + ) + else: + download_maps(dest=args.out, index_url=args.index_url) + except Exception as e: + _p(f"ERROR: {e}") + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/selfdrive/mapd/gps_fix.py b/selfdrive/mapd/gps_fix.py new file mode 100644 index 00000000000000..82bb1883c82088 --- /dev/null +++ b/selfdrive/mapd/gps_fix.py @@ -0,0 +1,179 @@ +"""Vehicle location for mapd and Refresh maps. + +Prefer a current GNSS sample (ublox / qcom). Fall back to comma's persistent +LastGPSPosition JSON. Never invent a city or default coordinate. +""" +from __future__ import annotations + +import json +import math +import os +import time +from collections.abc import Callable +from typing import Any + +GPS_MAX_AGE_S = 2.5 +GPS_MAX_ACC_M = 50.0 +LAST_GPS_WRITE_PERIOD_S = 60.0 + +# Offroad Refresh maps: ublox may not be publishing yet, and yard/trees are +# coarser than mapd's 50 m match. Accept last received plausible lat/lon. +REFRESH_GNSS_WAIT_S = 10.0 +REFRESH_GPS_MAX_ACC_M = 200.0 + +_PARAM_LAST_GPS_PATHS = ( + "/data/params/d/LastGPSPosition", + os.path.expanduser("~/.comma/params/d/LastGPSPosition"), +) + + +def is_plausible_lat_lon(lat: float, lon: float) -> bool: + if not math.isfinite(lat) or not math.isfinite(lon): + return False + if abs(lat) < 1e-6 and abs(lon) < 1e-6: + return False + return -90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0 + + +def parse_last_gps_position(raw: Any) -> tuple[float, float] | None: + """Parse comma LastGPSPosition JSON: {"latitude": …, "longitude": …, "altitude": …}.""" + if raw is None: + return None + if isinstance(raw, bytes): + raw = raw.decode("utf-8", errors="replace") + if isinstance(raw, dict): + data = raw + else: + text = str(raw).strip() + if not text: + return None + try: + data = json.loads(text) + except (json.JSONDecodeError, TypeError, ValueError): + return None + if not isinstance(data, dict): + return None + try: + lat = float(data.get("latitude", data.get("lat"))) + lon = float(data.get("longitude", data.get("lon"))) + except (TypeError, ValueError): + return None + if not is_plausible_lat_lon(lat, lon): + return None + return lat, lon + + +def format_last_gps_position(lat: float, lon: float, altitude: float = 0.0) -> str: + return json.dumps({"latitude": float(lat), "longitude": float(lon), "altitude": float(altitude)}) + + +def persist_last_gps_position(params: Any, lat: float, lon: float, altitude: float = 0.0) -> None: + if not is_plausible_lat_lon(lat, lon): + return + try: + params.put("LastGPSPosition", format_last_gps_position(lat, lon, altitude)) + except Exception: + pass + + +def persist_last_gps_if_possible(lat: float, lon: float, altitude: float = 0.0) -> None: + try: + from openpilot.common.params import Params + persist_last_gps_position(Params(), lat, lon, altitude) + except Exception: + pass + + +def load_last_gps_position(params: Any = None, raw: Any = None) -> tuple[float, float] | None: + if raw is None and params is not None: + try: + raw = params.get("LastGPSPosition") + except Exception: + raw = None + return parse_last_gps_position(raw) + + +def _last_gps_from_param_files() -> tuple[float, float] | None: + for path in _PARAM_LAST_GPS_PATHS: + try: + with open(path, encoding="utf-8") as f: + pos = parse_last_gps_position(f.read()) + except OSError: + continue + if pos is not None: + return pos + return None + + +def last_gps_from_params() -> tuple[float, float] | None: + try: + from openpilot.common.params import Params + pos = load_last_gps_position(params=Params()) + if pos is not None: + return pos + except Exception: + pass + return _last_gps_from_param_files() + + +def gps_sample_from_sm( + sm: Any, + *, + now: float | None = None, + max_age_s: float | None = GPS_MAX_AGE_S, + max_acc_m: float = GPS_MAX_ACC_M, +) -> tuple[float, float, float | None, bool]: + """Return (lat, lon, bearing_deg or None, ok). Prefer external GNSS. + + max_age_s=None accepts the last received sample (Refresh maps). mapd keeps + the 2.5 s / 50 m defaults so HUD MAX still tracks a live fix. + """ + now = time.monotonic() if now is None else now + for sock in ("gpsLocationExternal", "gpsLocation"): + if sm.recv_frame.get(sock, -1) <= 0: + continue + if max_age_s is not None and (now - sm.recv_time[sock]) > max_age_s: + continue + g = sm[sock] + lat, lon = float(g.latitude), float(g.longitude) + if not is_plausible_lat_lon(lat, lon): + continue + acc = float(g.horizontalAccuracy) + if acc > max_acc_m and acc > 0: + continue + bearing = float(g.bearingDeg) if (g.speed > 1.0 or g.bearingDeg) else None + if bearing is not None and (math.isnan(bearing) or bearing < 0): + bearing = None + return lat, lon, bearing, True + return 0.0, 0.0, None, False + + +def read_live_gnss( + *, + timeout_s: float = 8.0, + sm: Any = None, + max_age_s: float | None = GPS_MAX_AGE_S, + max_acc_m: float = GPS_MAX_ACC_M, + progress: Callable[[str], None] | None = None, +) -> tuple[float, float] | None: + """Wait for a valid GNSS fix. Returns None if cereal/GPS is unavailable.""" + if sm is None: + try: + import cereal.messaging as messaging + sm = messaging.SubMaster(["gpsLocationExternal", "gpsLocation"]) + except Exception: + return None + deadline = time.monotonic() + max(0.0, timeout_s) + last_progress = 0.0 + while True: + sm.update(200) + lat, lon, _bearing, ok = gps_sample_from_sm(sm, max_age_s=max_age_s, max_acc_m=max_acc_m) + if ok: + return lat, lon + now = time.monotonic() + if progress is not None and (now - last_progress) >= 5.0: + left = max(0.0, deadline - now) + progress(f"Waiting for a satellite fix ({left:.0f}s left)...") + last_progress = now + if now >= deadline: + return None diff --git a/selfdrive/mapd/local_refresh.py b/selfdrive/mapd/local_refresh.py new file mode 100644 index 00000000000000..f3e908ec277840 --- /dev/null +++ b/selfdrive/mapd/local_refresh.py @@ -0,0 +1,410 @@ +"""Refresh installed OSM speed limits from live Overpass around the vehicle. + +Settings → NAP → Map Speed Limit → Refresh maps (offroad, Wi-Fi) overlays +OpenStreetMap highway ways within 100 miles (~160.9 km) of a GNSS / last-GPS +fix onto the already-installed US sqlite. Tagged numeric maxspeed is +authoritative. In Minnesota, unmarked fillable highways get Minn. Stat. 169.14 +estimates (never uploaded to OSM) so a refresh does not wipe pack fills. +It does not download a published pack and never replaces the US file with +only the local extract. + +OpenStreetMap data is ODbL: © OpenStreetMap contributors. +https://www.openstreetmap.org/copyright +""" +from __future__ import annotations + +import argparse +import json +import os +import shutil +import sqlite3 +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import Literal + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.db_paths import default_db_path +from openpilot.selfdrive.mapd.fetch_maps import ( + cleanup_incomplete, + download_maps, + installed_db_summary, + sqlite_ok, + sqlite_present, + staging_dir, +) +from openpilot.selfdrive.mapd.gps_fix import ( + REFRESH_GNSS_WAIT_S, + REFRESH_GPS_MAX_ACC_M, + is_plausible_lat_lon, + last_gps_from_params, + load_last_gps_position, + persist_last_gps_if_possible, + read_live_gnss, +) +from openpilot.selfdrive.mapd.maps_manifest import LICENSE, LICENSE_URL +from openpilot.selfdrive.mapd.mn_statutory import FILL_NOTES, FILLABLE_HIGHWAY_REGEX as MN_FILLABLE_REGEX, bbox_intersects_minnesota +from openpilot.selfdrive.mapd.us_statutory import FILLABLE_HIGHWAY_REGEX as US_FILLABLE_REGEX, is_fill_source +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB +from openpilot.selfdrive.mapd.roundabout_map import ROLE_RING, rb_rows_from_overpass +from openpilot.selfdrive.mapd.overpass import ( + OVERPASS_URL, + bbox_from_center, + fetch_overpass, + ways_from_overpass, +) + +# Bounding box covering 100 miles (~160.9 km) around the vehicle. See docs-nap/map-speed.md. +REFRESH_RADIUS_MILES = 100.0 +REFRESH_RADIUS_KM = REFRESH_RADIUS_MILES * CV.MPH_TO_KPH + +NO_GPS_MESSAGE = ( + "No GPS location after waiting for a satellite fix. " + + "Start openpilot onroad until the GPS icon/fix is up for about a minute, then retry Refresh maps. " + + "The car's location is required -- maps will not guess a city." +) + +_UNSET = object() + +OVERPASS_HTTP_TIMEOUT_S = 360.0 +OVERPASS_QUERY_TIMEOUT_S = 300 + + +class RefreshMapsError(RuntimeError): + pass + + +class NoGpsError(RefreshMapsError): + def __init__(self, message: str = NO_GPS_MESSAGE): + super().__init__(message) + + +@dataclass(frozen=True) +class RefreshLocation: + lat: float + lon: float + source: Literal["gnss", "last_gps", "cli"] + + +def _p(msg: str) -> None: + print(msg, flush=True) + + +def bbox_intersects(a: tuple[float, float, float, float], b: tuple[float, float, float, float]) -> bool: + """True when two south,west,north,east boxes overlap (inclusive).""" + a_s, a_w, a_n, a_e = a + b_s, b_w, b_n, b_e = b + return a_n >= b_s and a_s <= b_n and a_e >= b_w and a_w <= b_e + + +def merge_decision_for_way( + way_min_lat: float, way_max_lat: float, way_min_lon: float, way_max_lon: float, + refresh_bbox: tuple[float, float, float, float], +) -> Literal["replace", "keep"]: + """'replace' if the way's stored bbox intersects the refresh bbox, else 'keep'.""" + way = (way_min_lat, way_min_lon, way_max_lat, way_max_lon) + return "replace" if bbox_intersects(way, refresh_bbox) else "keep" + + +def resolve_refresh_location( + *, + lat: float | None = None, + lon: float | None = None, + live_fix: tuple[float, float] | None = None, + last_gps_raw: object | None = None, +) -> RefreshLocation: + """Prefer CLI, then a current GNSS fix, then LastGPSPosition. Never guess a city.""" + if lat is not None and lon is not None: + if not is_plausible_lat_lon(lat, lon): + raise NoGpsError() + return RefreshLocation(lat=float(lat), lon=float(lon), source="cli") + if live_fix is not None: + glat, glon = float(live_fix[0]), float(live_fix[1]) + if is_plausible_lat_lon(glat, glon): + return RefreshLocation(lat=glat, lon=glon, source="gnss") + stored = load_last_gps_position(raw=last_gps_raw) + if stored is not None: + return RefreshLocation(lat=stored[0], lon=stored[1], source="last_gps") + raise NoGpsError() + + +def merge_ways_into_db( + db_path: str, + ways: list[dict], + bbox: tuple[float, float, float, float], + extra_meta: dict | None = None, + rb_rows: list[dict] | None = None, +) -> tuple[int, int]: + """Delete ways intersecting bbox, insert incoming way_ids. Returns (deleted, inserted). + + rb_rows (roundabout rings + approaches, roundabout_map.roundabout_rows) replace + the rb_ways in the same bbox. None leaves rb_ways untouched (older callers). + """ + con = sqlite3.connect(db_path) + try: + deleted = OsmSpeedLimitDB.delete_ways_intersecting_bbox(con, *bbox) + inserted = 0 + for w in ways: + OsmSpeedLimitDB.insert_way( + con, w["way_id"], w["name"], w["highway"], w["maxspeed_ms"], w["coords"], + junction=w.get("junction") or "", estimated=bool(w.get("estimated")), + ) + inserted += 1 + OsmSpeedLimitDB.recount_ways(con) + if rb_rows is not None: + OsmSpeedLimitDB.ensure_rb_tables(con) + OsmSpeedLimitDB.delete_rb_ways_intersecting_bbox(con, *bbox) + for row in rb_rows: + OsmSpeedLimitDB.insert_rb_way(con, row) + OsmSpeedLimitDB.recount_rb_ways(con) + if extra_meta: + con.executemany( + "INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", + [(str(k), str(v)) for k, v in extra_meta.items()], + ) + con.commit() + except Exception: + con.rollback() + raise + finally: + con.close() + return deleted, inserted + + +def _ensure_us_base(dest: str) -> None: + if sqlite_present(dest): + return + _p("No maps installed yet. Downloading the US pack first (Refresh maps will then overlay 100 miles)...") + download_maps(dest=dest) + if not sqlite_present(dest): + raise RefreshMapsError( + f"US pack download did not leave a usable sqlite at {dest}. " + + "Refresh maps will not install a 100-mile-only extract." + ) + + +def _assert_merge_space(dest: str) -> None: + dest_dir = os.path.dirname(os.path.abspath(dest)) or "." + try: + sz = os.path.getsize(dest) + except OSError as e: + raise RefreshMapsError(f"Could not read installed maps at {dest}: {e}") from e + need = sz + 32 * 1024 * 1024 + free = int(shutil.disk_usage(dest_dir).free) + _p(f"Free on {dest_dir}: {free / (1024 * 1024):.0f} MiB (need ~{need / (1024 * 1024):.0f} MiB to merge)") + if free < need: + raise RefreshMapsError( + f"Not enough free space on {dest_dir} to merge maps. " + + f"Need ~{need / (1024 * 1024):.0f} MiB, have {free / (1024 * 1024):.0f} MiB. " + + "Previous maps were left unchanged." + ) + + +def install_merged_overlay( + dest: str, + ways: list[dict], + bbox: tuple[float, float, float, float], + extra_meta: dict | None = None, + rb_rows: list[dict] | None = None, +) -> str: + """Copy dest on the dest filesystem, merge, then atomically replace. Dest is untouched on failure.""" + dest = os.path.abspath(dest) + if not sqlite_present(dest): + raise RefreshMapsError( + f"No US sqlite at {dest} to merge into. Download US Maps first. " + + "Refresh maps will not replace the US file with a 100-mile extract." + ) + _assert_merge_space(dest) + cleanup_incomplete(dest) + stage = staging_dir(dest) + os.makedirs(stage, exist_ok=True) + work = os.path.join(stage, "speed_limits.merge.sqlite") + try: + _p("Merging live OSM ways into a copy of the installed US maps...") + shutil.copy2(dest, work) + deleted, inserted = merge_ways_into_db(work, ways, bbox, extra_meta, rb_rows=rb_rows) + _p(f"Replaced {deleted} ways in the 100-mile box; inserted {inserted} Overpass ways.") + if rb_rows is not None: + rings = sum(1 for r in rb_rows if r.get("role") == ROLE_RING) + _p(f"Roundabouts: {rings} ring ways, {len(rb_rows) - rings} approach pieces.") + if not sqlite_ok(work): + raise RefreshMapsError("Merged sqlite failed to open. Previous maps were left unchanged.") + _p("Installing...") + os.replace(work, dest) + except Exception: + try: + if os.path.isfile(work): + os.remove(work) + except OSError: + pass + raise + finally: + try: + if os.path.isdir(stage) and not os.listdir(stage): + os.rmdir(stage) + except OSError: + pass + return dest + + +def _resolve_live_fix( + lat: float | None, + lon: float | None, + live_fix: object, +) -> tuple[float, float] | None: + if live_fix is not _UNSET: + return live_fix if isinstance(live_fix, tuple) else None + if lat is not None and lon is not None: + return None + _p(f"Waiting up to {REFRESH_GNSS_WAIT_S:.0f}s for a satellite fix...") + return read_live_gnss( + timeout_s=REFRESH_GNSS_WAIT_S, + max_age_s=None, + max_acc_m=REFRESH_GPS_MAX_ACC_M, + progress=_p, + ) + + +def _resolve_last_gps_raw(lat: float | None, lon: float | None, last_gps_raw: object) -> object | None: + if last_gps_raw is not _UNSET: + return last_gps_raw + if lat is not None and lon is not None: + return None + stored = last_gps_from_params() + if stored is None: + return None + return {"latitude": stored[0], "longitude": stored[1]} + + +def refresh_local_maps( + dest: str | None = None, + *, + lat: float | None = None, + lon: float | None = None, + radius_km: float = REFRESH_RADIUS_KM, + live_fix: tuple[float, float] | None | object = _UNSET, + last_gps_raw: object = _UNSET, + payload: dict | None = None, + overpass_url: str = OVERPASS_URL, +) -> str: + """Query OSM around the vehicle and merge into dest. Network skipped when payload is given. + + Omit live_fix/last_gps_raw to look them up. Pass None to force a miss (tests). + """ + dest = os.path.abspath(dest or default_db_path()) + _p(f"OpenStreetMap speed limits ({LICENSE}). (c) OpenStreetMap contributors") + _p(LICENSE_URL) + + loc = resolve_refresh_location( + lat=lat, lon=lon, + live_fix=_resolve_live_fix(lat, lon, live_fix), + last_gps_raw=_resolve_last_gps_raw(lat, lon, last_gps_raw), + ) + if loc.source == "gnss": + _p(f"Using current GNSS fix {loc.lat:.5f}, {loc.lon:.5f}") + persist_last_gps_if_possible(loc.lat, loc.lon) + elif loc.source == "last_gps": + _p(f"No current GNSS fix. Using last stored GPS {loc.lat:.5f}, {loc.lon:.5f}") + persist_last_gps_if_possible(loc.lat, loc.lon) + else: + _p(f"Using provided location {loc.lat:.5f}, {loc.lon:.5f}") + persist_last_gps_if_possible(loc.lat, loc.lon) + + bbox = bbox_from_center(loc.lat, loc.lon, radius_km) + # Every state: untagged drivable roads get the state default (us_statutory). + # Minnesota keeps MN 169.14 incl. residential streets, so its query is wider. + fill_unmarked = True + in_mn = bbox_intersects_minnesota(bbox) + _p( + f"Refresh radius {REFRESH_RADIUS_MILES:.0f} miles ({radius_km:.1f} km). " + + f"Overpass bbox south,west,north,east={bbox[0]:.4f},{bbox[1]:.4f},{bbox[2]:.4f},{bbox[3]:.4f}" + ) + _p("Fetching drivable highways; unmarked ways get state default limits (estimated)" + + (", MN 169.14 incl. residential." if in_mn else ".")) + + _ensure_us_base(dest) + + if payload is None: + _p("Querying OSM (Overpass). This can take several minutes; a timeout leaves the old maps in place.") + payload = fetch_overpass( + bbox, url=overpass_url, + timeout_s=OVERPASS_HTTP_TIMEOUT_S, + query_timeout=OVERPASS_QUERY_TIMEOUT_S, + include_unmarked=fill_unmarked, + unmarked_regex=MN_FILLABLE_REGEX if in_mn else US_FILLABLE_REGEX, + ) + ways = ways_from_overpass(payload, fill_unmarked=fill_unmarked) + rb_rows = rb_rows_from_overpass(payload) + tagged_n = sum(1 for w in ways if not is_fill_source(w.get("source"))) + filled_n = len(ways) - tagged_n + if fill_unmarked: + _p( + f"Received {len(ways)} highway ways from OSM " + + f"({tagged_n} tagged maxspeed, {filled_n} estimated state-default fills)." + ) + else: + _p(f"Received {len(ways)} maxspeed ways from OSM.") + if not ways: + raise RefreshMapsError( + "No usable highway speed limits found in OSM for this 100-mile area. " + + "Previous maps were left unchanged." + ) + + extra_meta = { + "local_refresh_lat": f"{loc.lat:.6f}", + "local_refresh_lon": f"{loc.lon:.6f}", + "local_refresh_radius_km": f"{radius_km:.3f}", + "local_refresh_radius_miles": f"{REFRESH_RADIUS_MILES:.0f}", + "local_refresh_bbox": ",".join(str(x) for x in bbox), + "local_refresh_at": datetime.now(UTC).isoformat(), + "local_refresh_fill_unmarked": "1" if fill_unmarked else "0", + } + if fill_unmarked: + extra_meta["fill_source"] = "us_statutory (_default, MN_169.14)" + extra_meta["fill_notes"] = FILL_NOTES + extra_meta["local_refresh_tagged_ways"] = str(tagged_n) + extra_meta["local_refresh_filled_ways"] = str(filled_n) + extra_meta["local_refresh_rb_rows"] = str(len(rb_rows)) + install_merged_overlay(dest, ways, bbox, extra_meta, rb_rows=rb_rows) + _p(installed_db_summary(dest)) + _p("mapd reloads this file within ~15s onroad. No reboot required.") + return dest + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser( + description="Refresh installed US OSM maps with live Overpass data within 100 miles of the vehicle", + ) + p.add_argument("--lat", type=float, default=None, help="Override latitude (skips GNSS / LastGPSPosition)") + p.add_argument("--lon", type=float, default=None, help="Override longitude") + p.add_argument("--radius-km", type=float, default=REFRESH_RADIUS_KM, + help=f"Refresh radius km (default {REFRESH_RADIUS_KM:.1f} = 100 miles)") + p.add_argument("--from-json", help="Saved Overpass JSON instead of the network") + p.add_argument("--out", default=None, help="sqlite destination (default: /data/media/0/osm/speed_limits.sqlite)") + p.add_argument("--overpass-url", default=OVERPASS_URL) + args = p.parse_args(argv) + + if (args.lat is None) ^ (args.lon is None): + p.error("provide both --lat and --lon") + + payload = None + if args.from_json: + with open(args.from_json, encoding="utf-8") as f: + payload = json.load(f) + + try: + refresh_local_maps( + dest=args.out, + lat=args.lat, + lon=args.lon, + radius_km=args.radius_km, + payload=payload, + overpass_url=args.overpass_url, + ) + except Exception as e: + _p(f"ERROR: {e}") + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/selfdrive/mapd/map_speed_policy.py b/selfdrive/mapd/map_speed_policy.py new file mode 100644 index 00000000000000..d317c22fd0e11a --- /dev/null +++ b/selfdrive/mapd/map_speed_policy.py @@ -0,0 +1,692 @@ +"""Select cruise/MAX set speed from the existing driver target and an OSM limit. + +This is not a second longitudinal controller. It only returns the kph value that +card.py already publishes as CS.vCruise / vCruiseCluster (HUD "MAX"). +""" +from __future__ import annotations + +import math +from dataclasses import dataclass + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.constants import ( + ACCEL_DEFAULT, ACCEL_MAX, ACCEL_MIN, LOOKAHEAD_NORMAL, LOOKAHEAD_OFF, + LOOKAHEAD_TUNING, MANUAL_SET_EPS_KPH, MIN_DECREASE_MS, MODE_CAP, MODE_DISPLAY, + MODE_FOLLOW, MODE_OFF, POSTED_LIMIT_EPS_KPH, TRACK_DEADBAND_MS, TRACK_TAPER_MS, + map_accel_a_ms2, map_brake_a_ms2, map_track_taper_ms, +) + +# Oct 13 map limits. Untagged state defaults (OSM way with no maxspeed, filled +# by the pack) are estimates: Ridgewood Rd (tertiary, Sartell/St Joseph city +# polygon) went 55 -> 30 and the car braked 45 -> 33 mph at -1.6 m/s². +MAP_SOURCE_TAGGED = "osm" +MAP_SOURCE_DEFAULT = "osm_default" +# A drop to a default limit never brakes harder than this. +DEFAULT_DROP_A_MS2 = 0.5 +# Untagged rural minor roads keep 55 along the same road. +RURAL_MINOR_HIGHWAYS = frozenset({"secondary", "secondary_link", "tertiary", "tertiary_link"}) +RURAL_KEEP_MS = 55.0 * CV.MPH_TO_MS + + +def map_source_for(estimated: bool, sign: bool = False) -> str: + """liveMapDataNAP.source value: sign override, tagged OSM, or state default.""" + if sign: + return "sign" + return MAP_SOURCE_DEFAULT if estimated else MAP_SOURCE_TAGGED + + +def keep_rural_default_ms(limit_ms: float, *, estimated: bool, highway: str, road_name: str, + prev: tuple[str, str, float] | None) -> float: + """Keep 55 on an untagged secondary/tertiary when the same road was already 55+. + + prev is (road_name, highway, published limit) from the last cycle. A tagged + limit, another road, or another class is returned unchanged. + """ + lim = float(limit_ms) + hw = str(highway or "").strip().lower() + if not estimated or hw not in RURAL_MINOR_HIGHWAYS or lim >= RURAL_KEEP_MS - 0.3: + return lim + if prev is None: + return lim + p_name, p_hw, p_lim = prev + base = hw.replace("_link", "") + if not road_name or p_name != road_name or str(p_hw or "").replace("_link", "") != base: + return lim + if float(p_lim) >= RURAL_KEEP_MS - 0.3: + return RURAL_KEEP_MS + return lim + + +def default_drop_cap_ms(cap_ms: float, prev_ms: float | None, v_ego_ms: float, dt: float) -> float: + """Ceiling that follows a lower DEFAULT limit down at DEFAULT_DROP_A_MS2 at most.""" + cap = float(cap_ms) + start = max(float(v_ego_ms), cap) if prev_ms is None else float(prev_ms) + return max(cap, start - DEFAULT_DROP_A_MS2 * max(0.0, float(dt))) + + +# Keep in sync with openpilot.selfdrive.car.cruise (avoid importing cereal here). +V_CRUISE_MIN = 8 +V_CRUISE_MAX = 145 +V_CRUISE_UNSET = 255 + + +def _clamp_accel_level(level: int) -> int: + return max(ACCEL_MIN, min(ACCEL_MAX, int(level))) + + +def read_map_speed_params(params) -> tuple[int, float, int, int]: + """Return (mode, offset_kph, lookahead, accel). Unknown keys → off / 0 / normal / 5.""" + try: + mode = int(params.get("NAPMapSpeedMode", return_default=True) or 0) + offset_mph = float(params.get("NAPMapSpeedOffsetMph", return_default=True) or 0) + lookahead = int(params.get("NAPMapSpeedLookahead", return_default=True) or LOOKAHEAD_NORMAL) + if lookahead not in LOOKAHEAD_TUNING: + lookahead = LOOKAHEAD_NORMAL + accel = _clamp_accel_level(int(params.get("NAPMapSpeedAccel", return_default=True) or ACCEL_DEFAULT)) + return mode, offset_mph * CV.MPH_TO_KPH, lookahead, accel + except Exception: + return MODE_OFF, 0.0, LOOKAHEAD_NORMAL, ACCEL_DEFAULT + + +def anticipatory_limit_ms( + current_ms: float, + next_ms: float, + next_dist_m: float, + v_ego_ms: float, + lookahead: int, + accel: int = ACCEL_DEFAULT, +) -> float | None: + """Decrease-only cruise ceiling for an upcoming lower limit, or None. + + Uses comfort decel + margin so MAX eases down and the car is near the new + limit as the lag-corrected position enters that way. A higher nextSpeedLimit + far ahead never raises this ceiling; Follow still raises when the posted + match at v_ego * 1.5 s is already the faster way (GNSS lag, not lookahead). + """ + if lookahead <= LOOKAHEAD_OFF or lookahead not in LOOKAHEAD_TUNING: + return None + if current_ms <= 0 or next_ms <= 0: + return None + if next_ms >= current_ms - MIN_DECREASE_MS: + return None + _a_base, margin_m, horizon_m = LOOKAHEAD_TUNING[lookahead] + if horizon_m <= 0: + return None + # Brake / anticipatory decreases are locked at Accel 5. `accel` is unused + # (climb-only); kept so call sites can pass NAPMapSpeedAccel unchanged. + _ = accel + a_comfort = map_brake_a_ms2(lookahead) + if a_comfort <= 0: + return None + v0 = max(float(v_ego_ms), float(current_ms), 0.0) + vt = float(next_ms) + if v0 <= vt: + return None + if next_dist_m <= 0: + return vt + need_m = (v0 * v0 - vt * vt) / (2.0 * a_comfort) + margin_m + need_m = min(need_m, horizon_m) + if next_dist_m > need_m: + return None + # Fall from v0 at need_m to vt at the sign. Using v² = vt² + 2 a d alone + # wasted the margin: MAX stayed at the old limit until kinematic d, so a + # 50→30 still arrived at the sign ~10 mph hot. Interpolate over the full window. + span = max(need_m, 1e-6) + v_cmd = math.sqrt(max(0.0, vt * vt + (v0 * v0 - vt * vt) * (float(next_dist_m) / span))) + return max(vt, min(float(current_ms), v_cmd)) + + +def effective_map_limit_ms( + current_ms: float | None, + next_ms: float = 0.0, + next_dist_m: float = 0.0, + v_ego_ms: float = 0.0, + lookahead: int = LOOKAHEAD_NORMAL, + accel: int = ACCEL_DEFAULT, + sticky: bool = False, +) -> float | None: + """Posted limit, optionally eased down for a closer lower limit ahead. + + A sticky stalk set must hold until posted `a` changes. Do not ease toward + an upcoming lower OSM limit while that set is active — that fights the hold. + """ + if current_ms is None or current_ms <= 0: + return None + if sticky: + return float(current_ms) + anticipated = anticipatory_limit_ms( + float(current_ms), float(next_ms or 0.0), float(next_dist_m or 0.0), + float(v_ego_ms or 0.0), lookahead, accel, + ) + if anticipated is None: + return float(current_ms) + return min(float(current_ms), anticipated) + + +def map_slew_a_ms2(prev_ms: float, target_ms: float, lookahead: int, accel_level: int) -> float: + """Slew rate for HUD/planner MAX: brake-locked a on decreases, Accel 1–10 on rises.""" + if float(target_ms) < float(prev_ms): + return map_brake_a_ms2(lookahead) + return map_accel_a_ms2(lookahead, accel_level) + + +def slew_map_speed_ms(prev_ms: float, target_ms: float, dt: float, a_ms2: float) -> float: + """Rate-limit map-driven MAX (m/s) so a new limit does not cliff the HUD.""" + if dt <= 0 or a_ms2 <= 0: + return float(target_ms) + max_dv = float(a_ms2) * float(dt) + delta = float(target_ms) - float(prev_ms) + if abs(delta) <= max_dv: + return float(target_ms) + return float(prev_ms) + math.copysign(max_dv, delta) + + +def map_track_decel_ms2(v_ego_ms: float, v_cruise_ms: float, a_comfort: float) -> float | None: + """Comfort decel (negative m/s²) to track a lower map MAX, or None. + + LongitudinalMpc's cruise column is a virtual lead at + get_safe_obstacle_distance(v_ego) with V_EGO_COST=0. Holding 70 mph for + 10 s after MAX drops to 45 never violates that obstacle, so aTarget stays + ~0 unless we command this. Lead/MPC may still request more braking via min(). + Callers must pass Accel-5 comfort a (map_brake_a_ms2); Accel 1–10 does not + change brake rate. + """ + if a_comfort <= 0 or v_ego_ms <= 0 or v_cruise_ms <= 0: + return None + dv = float(v_ego_ms) - float(v_cruise_ms) + if dv <= TRACK_DEADBAND_MS: + return None + span = max(1e-6, TRACK_TAPER_MS - TRACK_DEADBAND_MS) + scale = min(1.0, (dv - TRACK_DEADBAND_MS) / span) + return -float(a_comfort) * scale + + +def map_climb_replaces_mpc(a_up, output_a_target, has_valid_lead: bool) -> bool: + """True when map climb may replace a non-negative MPC aTarget. + + A valid radar lead owns follow. Replacing ~0 / slight+ MPC with Accel 1–10 + toward MAX punches through that lead, then overshoots and will not rematch. + map_track_decel when above MAX is a separate min() and is not gated here. + """ + return a_up is not None and float(output_a_target) >= 0.0 and not bool(has_valid_lead) + + +def map_track_accel_ms2(v_ego_ms: float, v_cruise_ms: float, a_comfort: float, + accel_level=None) -> float | None: + """Comfort accel (positive m/s²) when catching a higher Follow MAX, or None. + + MPC cruise_obstacle will not climb to a higher MAX (V_EGO_COST=0). The + planner commands this a when ego is below MAX and MPC is not braking + *and* there is no valid radar lead. Accel 1–10 sets the climb rate *and* + the last-mph taper (Accel 1 baby-steps ~5 mph out; Accel 7–10 stays brisk + to the target). Lead gap-close uses this same envelope. A slower lead + (negative aTarget) still wins. + """ + if a_comfort <= 0 or v_ego_ms <= 0 or v_cruise_ms <= 0: + return None + dv = float(v_cruise_ms) - float(v_ego_ms) + if dv <= TRACK_DEADBAND_MS: + return None + taper = map_track_taper_ms(accel_level) + span = max(1e-6, float(taper) - TRACK_DEADBAND_MS) + scale = min(1.0, (dv - TRACK_DEADBAND_MS) / span) + return float(a_comfort) * scale + + +def map_in_track_deadband(v_ego_ms: float, v_set_ms: float) -> bool: + """True when ego is close enough to MAX to hold, not climb or map-brake.""" + if v_ego_ms <= 0 or v_set_ms <= 0: + return False + return abs(float(v_ego_ms) - float(v_set_ms)) <= TRACK_DEADBAND_MS + + +def posted_limits_same(a_kph: float | None, b_kph: float | None) -> bool: + if a_kph is None or b_kph is None: + return False + return abs(float(a_kph) - float(b_kph)) < POSTED_LIMIT_EPS_KPH + + +def is_manual_set_change(prev_kph: float, cur_kph: float) -> bool: + """True when set speed moved (not engage 0↔set). Includes ego jumps.""" + if prev_kph in (0, V_CRUISE_UNSET) or cur_kph <= 0 or cur_kph >= V_CRUISE_UNSET: + return False + return abs(float(cur_kph) - float(prev_kph)) > MANUAL_SET_EPS_KPH + + +# Tesla stalk: tip/bump = 1 mph or 1 kph; full press/hold = 5 mph or 5 kph. +# Metric 1 kph and imperial 1 mph are both single-step (~1.0 / MPH_TO_KPH). +STALK_STEP_EPS_KPH = 0.55 +CRUISE_STALK_TIP_STEPS_KPH = (1.0, CV.MPH_TO_KPH) +CRUISE_STALK_HOLD_STEPS_KPH = (5.0, 5.0 * CV.MPH_TO_KPH) + + +def _matches_cruise_stalk_steps(prev_kph: float, cur_kph: float, steps: tuple[float, ...]) -> bool: + if not is_manual_set_change(prev_kph, cur_kph): + return False + delta = abs(float(cur_kph) - float(prev_kph)) + return any(abs(delta - step) < STALK_STEP_EPS_KPH for step in steps) + + +def is_cruise_stalk_tip_step(prev_kph: float, cur_kph: float) -> bool: + """True if delta matches a Tesla stalk tip / bump (1 mph or 1 kph).""" + return _matches_cruise_stalk_steps(prev_kph, cur_kph, CRUISE_STALK_TIP_STEPS_KPH) + + +def is_cruise_stalk_hold_step(prev_kph: float, cur_kph: float) -> bool: + """True if delta matches a Tesla full press (5 mph or 5 kph).""" + return _matches_cruise_stalk_steps(prev_kph, cur_kph, CRUISE_STALK_HOLD_STEPS_KPH) + + +def is_cruise_stalk_step(prev_kph: float, cur_kph: float) -> bool: + """True if delta matches Tesla pedal stalk +/- (1 or 5 mph / kph). + + An ego / DI_digitalSpeed jump is not a stalk step and must not arm sticky. + """ + return is_cruise_stalk_tip_step(prev_kph, cur_kph) or is_cruise_stalk_hold_step(prev_kph, cur_kph) + + +def _ref_posted_kph(hold: MapCruiseHold, posted_kph: float | None) -> float | None: + if posted_kph is not None and posted_kph > 0: + return float(posted_kph) + if hold.last_posted_kph is not None and hold.last_posted_kph > 0: + return float(hold.last_posted_kph) + return None + + +def is_below_posted(set_kph: float, posted_kph: float | None) -> bool: + if posted_kph is None or posted_kph <= 0: + return False + return float(set_kph) < float(posted_kph) - MANUAL_SET_EPS_KPH + + +@dataclass +class MapCruiseHold: + """Engage-seed + sticky manual set while the posted OSM limit is unchanged. + + Follow holds the stalk set (above or below `a`) until posted leaves `a`. + Cap still never exceeds the posted sign. No 10s raise-above timer. + + `held_max_kph` is the HUD MAX to resume after a long pause (brake). + It survives `enableLongControl` dropping; only a full disengage + (cruiseEnabled down) or a double SET (take-speed-now) forgets it. + `last_posted_kph` is the last *known* OSM posted (+ offset). GPS / match + drop must not clear it or invent a replacement. + """ + last_posted_kph: float | None = None + last_raw_kph: float = V_CRUISE_UNSET + policy_kph: float | None = None + sticky_set_kph: float | None = None + held_max_kph: float | None = None + follow_override_until: float = 0.0 + + def reset(self) -> None: + self.last_posted_kph = None + self.last_raw_kph = V_CRUISE_UNSET + self.policy_kph = None + self.sticky_set_kph = None + self.held_max_kph = None + self.follow_override_until = 0.0 + + +@dataclass +class MapCruiseDecision: + """Cruise overlay for one card.py cycle. + + `seed_kph` is a one-shot pedal write (engage, posted-limit raise, or a + real stalk step). None on a continuing sticky hold — writing every + sticky frame undoes CI.update's 1/5 mph stalk step. + """ + driver_kph: float + follow_override: bool + seed_kph: float | None + sticky: bool + + +def _sticky_decision(hold: MapCruiseHold, mode: int, posted_kph: float | None, + write_pedal: bool = False) -> MapCruiseDecision: + held = float(hold.sticky_set_kph) + if mode == MODE_CAP and posted_kph is not None and posted_kph > 0: + held = min(held, float(posted_kph)) + hold.policy_kph = held + hold.held_max_kph = held + # follow_override True so apply_map_speed cannot Follow-raise if a caller + # ignores `sticky` and only passes the override flag. + return MapCruiseDecision(held, True, held if write_pedal else None, True) + + +def _apply_posted_change(hold: MapCruiseHold, posted_kph: float, prev: float, *, + take_now: bool, resume_held: bool) -> MapCruiseDecision | None: + """Rebase MAX onto a new posted limit and forget a stalk set. + + Known a → known b and none → valid share this path, including how a + recent stalk / set-speed override is dropped. A raise seeds the pedal + immediately. A decrease does not cliff-seed. Returns None when + take-speed-now or one-SET resume still owns the pedal write. + """ + hold.sticky_set_kph = None + hold.follow_override_until = 0.0 + hold.last_posted_kph = posted_kph + hold.held_max_kph = float(posted_kph) + hold.last_raw_kph = float(posted_kph) + hold.policy_kph = float(posted_kph) + raised = float(posted_kph) > float(prev) + POSTED_LIMIT_EPS_KPH + if take_now or resume_held: + return None + return MapCruiseDecision( + float(posted_kph) if raised else float(prev), + False, + float(posted_kph) if raised else None, + False, + ) + + +def _traveled_kph(traveled_kph: float | None, raw_kph: float) -> float: + """Current traveled speed. Never invent a posted value.""" + if traveled_kph is not None and 0.0 < float(traveled_kph) < V_CRUISE_UNSET: + return float(traveled_kph) + return float(raw_kph) + + +def decide_map_cruise( + hold: MapCruiseHold, + *, + engaged: bool, + mode: int, + raw_kph: float, + posted_kph: float | None, + engage_rising: bool, + now: float, + stalk_pressed: bool | None = None, + take_speed_now: bool = False, + resume_held: bool = False, + traveled_kph: float | None = None, + long_active: bool = True, + self_wrote_pedal: bool = False, +) -> MapCruiseDecision: + """Engage seed + sticky hold. posted_kph is OSM current maxspeed + offset. + + `engaged` is the OP session (`cruiseEnabled`), not just pedal-long. A + brake long pause must keep sticky / held MAX. Full disengage + (cancel / door / gear / steer fault) resets. + + Double SET / initial engage is `take_speed_now` (or `engage_rising` when + not `resume_held` and no held MAX yet): forget sticky; MAX = current + posted if maps+posted known, else current traveled speed. Never invent + a posted value. + + One SET after a long pause is `resume_held`: restore held MAX, which may + already have rebased if posted changed under maps. `resume_held` is a + one-shot; `engage_rising` can arrive a frame later (`pedalLongActive` + lags `enableLongControl`). That delayed rising edge must not take-now + and overwrite a held MAX with current traveled speed. + + Maps on: MAX rebases when the posted value changes (known a → known b) + and when a missing limit becomes a posted limit (none → valid), including + while long-paused. Both drop a stalk set the same way a 55 → 70 change + does. A posted limit becoming missing (valid → invalid) holds the + current MAX: no drop and no reseed to ego, and sticky is left alone. + The same posted value coming back after a dropout is not a change. + + Maps off / display: never auto-rebase. + + `stalk_pressed` is extra (button edge). A 1/5 mph pedal_speed step always + counts as a stalk while long is active; an ego jump does not. Do not treat + `stalk_pressed=False` as "ignore pedal_speed" — pre-AP button events are + not reliable. Pause frames must not arm sticky from cruiseState.speed + falling back to ego. + + `self_wrote_pedal` is the frame that echoes a pedal_speed this code just + wrote. That step is not a driver stalk press. + + Pedal write (`seed_kph`) only on take-speed-now, resume-held, a real 1/5 + mph stalk step, or a posted-limit *raise*. A continuing sticky hold must + not write — that overwrites CI.update's stalk step on the same frame. + """ + _ = now + # engage_rising without a held MAX is initial engage (take current). + # A held MAX means this session already has a MAX — one SET after a + # pause must resume it even if resume_held was consumed last frame. + take_now = bool(take_speed_now) or ( + bool(engage_rising) and not bool(resume_held) and hold.held_max_kph is None + ) + maps_control = mode in (MODE_CAP, MODE_FOLLOW) + + if not engaged: + hold.reset() + return MapCruiseDecision(raw_kph, False, None, False) + + if not maps_control: + # Maps off / display / unknown posted: never invent, never auto-rebase. + if take_now: + hold.sticky_set_kph = None + seed = _traveled_kph(traveled_kph, raw_kph) + hold.held_max_kph = seed + hold.last_raw_kph = seed + hold.policy_kph = seed + return MapCruiseDecision(seed, False, seed, False) + if long_active: + # Pedal/HUD MAX is the source of truth while long is active. Stalk + # +/- must update the MAX one SET will resume. Pause publishes + # cruiseState.speed as ego — never latch that into held. + stalk_step = (not self_wrote_pedal) and is_cruise_stalk_step(hold.last_raw_kph, raw_kph) + if 0.0 < raw_kph < V_CRUISE_UNSET and ( + hold.held_max_kph is None or stalk_step or bool(stalk_pressed) + ): + hold.held_max_kph = float(raw_kph) + hold.last_raw_kph = raw_kph + if hold.held_max_kph is not None: + held = float(hold.held_max_kph) + hold.policy_kph = held + else: + # Paused with no latch: report raw for this frame only. Do not store + # it — pause raw is ego. + held = float(raw_kph) + seed = float(held) if resume_held and hold.held_max_kph is not None else None + return MapCruiseDecision(float(held), False, seed, False) + + posted_ok = posted_kph is not None and posted_kph > 0 + # Pause: cruiseState.speed is ego, not MAX. Do not treat that as a stalk. + stalk_step = (not self_wrote_pedal) and bool(long_active) and is_cruise_stalk_step(hold.last_raw_kph, raw_kph) + manual = bool(long_active) and (stalk_step or bool(stalk_pressed)) + if long_active: + hold.last_raw_kph = raw_kph + # valid → invalid. Keep the MAX we already have. cruiseState.speed + # falling back to ego (including a 1 or 5 mph gap) is not a stalk and + # must not reseed. + if ( + not posted_ok + and hold.last_posted_kph is not None + and not take_now + and traveled_kph is not None + and abs(float(raw_kph) - float(traveled_kph)) <= MANUAL_SET_EPS_KPH + ): + manual = False + stalk_step = False + anchor = hold.held_max_kph if hold.held_max_kph is not None else hold.policy_kph + if anchor is not None: + hold.last_raw_kph = float(anchor) + + posted_changed = ( + posted_ok + and hold.last_posted_kph is not None + and not posted_limits_same(hold.last_posted_kph, posted_kph) + ) + if posted_changed: + # Posted value itself changed (known a → known b), including while + # long-paused. Forget sticky and rebase MAX to the new posted. A raise + # seeds immediately. A decrease does not cliff-seed — Cap/Follow ease + # via map_kph (kin+110 m) — unless this frame is one SET resume, which + # must write the already-rebased held MAX onto pedal. + changed = _apply_posted_change( + hold, posted_kph, float(hold.last_posted_kph), + take_now=take_now, resume_held=resume_held, + ) + if changed is not None: + return changed + + if take_now: + hold.sticky_set_kph = None + hold.follow_override_until = 0.0 + if posted_ok: + seed = float(posted_kph) + hold.last_posted_kph = posted_kph + else: + # Unknown posted: never invent a limit. Hold current traveled speed + # until a real posted value appears. That later none → valid step is + # a normal limit change, not a timed engage exception. + seed = _traveled_kph(traveled_kph, raw_kph) + hold.sticky_set_kph = seed + hold.held_max_kph = seed + hold.last_raw_kph = seed + hold.policy_kph = seed + return MapCruiseDecision(seed, hold.sticky_set_kph is not None, seed, + hold.sticky_set_kph is not None) + + if posted_ok and hold.last_posted_kph is None: + # none → valid while long is already engaged. Same rebase as a posted + # change, at any time, including a stalk set made during the dropout. + # If MAX is already the returning limit, leave it: a same-value return + # must not write the pedal again. + prev = float(hold.held_max_kph if hold.held_max_kph is not None else raw_kph) + if not posted_limits_same(prev, posted_kph): + changed = _apply_posted_change( + hold, posted_kph, prev, take_now=False, resume_held=resume_held, + ) + if changed is not None: + return changed + + if posted_ok: + # GPS return: record posted without rebasing (not a value change). + hold.last_posted_kph = posted_kph + + if resume_held: + held = hold.sticky_set_kph if hold.sticky_set_kph is not None else hold.held_max_kph + if held is None: + held = float(raw_kph) + if mode == MODE_CAP and posted_ok: + held = min(float(held), float(posted_kph)) + hold.held_max_kph = float(held) + hold.policy_kph = float(held) + sticky = hold.sticky_set_kph is not None + return MapCruiseDecision(float(held), sticky, float(held), sticky) + + ref_posted = _ref_posted_kph(hold, posted_kph) + + if manual: + hold.policy_kph = float(raw_kph) + hold.follow_override_until = 0.0 + if mode == MODE_FOLLOW: + hold.sticky_set_kph = float(raw_kph) + elif is_below_posted(raw_kph, ref_posted) or ref_posted is None: + hold.sticky_set_kph = float(raw_kph) + else: + # Cap: stalk at or above posted is not sticky; apply_map_speed caps. + hold.sticky_set_kph = None + hold.held_max_kph = float(raw_kph) if hold.sticky_set_kph is not None else hold.held_max_kph + + if hold.policy_kph is None: + hold.policy_kph = float(raw_kph) + + if hold.sticky_set_kph is not None: + # Write once when pedal_speed actually stepped. stalk_pressed with + # unchanged raw must not write the old hold over CI's in-flight step. + return _sticky_decision(hold, mode, posted_kph, write_pedal=stalk_step) + + if posted_ok and mode == MODE_FOLLOW: + hold.held_max_kph = float(posted_kph) + elif hold.held_max_kph is None: + hold.held_max_kph = float(hold.policy_kph) + + return MapCruiseDecision(float(hold.policy_kph), False, None, False) + + +def should_write_preap_pedal(seed_kph: float | None, hud_kph: float, + last_pedal_kph: float | None) -> bool: + """When to write HUD MAX onto pre-AP pedal_speed. + + Write on engage/posted seed or a real stalk step (`seed_kph`). Also write + when MAX *rose* vs the last pedal write (Follow posted raise backup). + Do not write every sticky/Follow frame — that ate stalk +/-. + """ + if seed_kph is not None: + return True + if last_pedal_kph is None: + return False + return float(hud_kph) > float(last_pedal_kph) + MANUAL_SET_EPS_KPH + + +def apply_map_speed_kph( + driver_set_kph: float, + map_limit_kph: float | None, + *, + mode: int, + offset_kph: float = 0.0, + engaged: bool = False, + op_long_software_cruise: bool = False, + driver_override: bool = False, + v_min: float = V_CRUISE_MIN, + v_max: float = V_CRUISE_MAX, +) -> float: + """Return the kph target for vCruise / HUD MAX. + + Control (cap/follow) only runs when NAP owns software cruise — pre-AP pedal + mode (`openpilotLongitudinalControl` and not `pcmCruise`). Display and off + never change the driver/stock target. + """ + if driver_set_kph <= 0 or driver_set_kph >= V_CRUISE_UNSET: + return driver_set_kph + + driver = float(driver_set_kph) + if mode in (MODE_OFF, MODE_DISPLAY) or not engaged: + return driver + if not op_long_software_cruise: + return driver + if map_limit_kph is None or map_limit_kph <= 0: + return driver + + map_target = max(v_min, min(v_max, float(map_limit_kph) + float(offset_kph))) + + if mode == MODE_CAP: + return min(driver, map_target) + + if mode == MODE_FOLLOW: + # driver_override is a sticky hold backup. Card usually applies sticky + # via seed_kph before this function. No 10s snap-back to posted. + if driver_override: + return max(v_min, min(v_max, driver)) + return map_target + + return driver + + +def cap_planner_v_cruise_ms( + v_cruise_ms: float, + map_limit_ms: float | None, + *, + mode: int, + offset_ms: float = 0.0, +) -> float: + """HUD MAX is already card policy. + + Trust HUD for Cap and Follow. min() with posted snapped MAX when GPS or + the 1.5 s offset entered a lower zone, skipping kin+110 m ease. Card Cap + still never exceeds the eased ceiling. Lead still wins via mpc.update. + """ + _ = map_limit_ms, mode, offset_ms + return v_cruise_ms + + +# Same column order as LongitudinalMpc.update: +# x_obstacles = [lead0, lead1, cruise_obstacle(v_cruise)] +SOURCE_LEAD0 = 0 +SOURCE_LEAD1 = 1 +SOURCE_CRUISE = 2 + + +def longitudinal_obstacle_source(lead0_m: float, lead1_m: float, cruise_m: float) -> int: + """Return which MPC obstacle is tightest at t=0 (0=lead0, 1=lead1, 2=cruise). + + Map speed only changes the cruise column. A closer/slower lead must still win. + """ + stacked = (float(lead0_m), float(lead1_m), float(cruise_m)) + return min(range(3), key=lambda i: stacked[i]) diff --git a/selfdrive/mapd/mapd.py b/selfdrive/mapd/mapd.py new file mode 100755 index 00000000000000..8a339d424ef54f --- /dev/null +++ b/selfdrive/mapd/mapd.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""GPS → OSM speed-limit lookup for NAP. + +Publishes liveMapDataNAP. Does not actuate; card.py / the long planner consume +the limit through the existing vCruise path. +""" +import math +import os +import time + +import cereal.messaging as messaging +from openpilot.common.params import Params +from openpilot.common.realtime import Ratekeeper +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.mapd.db_paths import default_db_path +from openpilot.selfdrive.mapd.gps_fix import ( + LAST_GPS_WRITE_PERIOD_S, + gps_sample_from_sm, + persist_last_gps_position, +) +from openpilot.selfdrive.mapd.map_speed_policy import keep_rural_default_ms, map_source_for +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB +from openpilot.selfdrive.mapd.speed_overrides import PARAM as SIGN_CONFIRMED_PARAM, SpeedOverrides +from openpilot.selfdrive.mapd.roundabout_map import PARAM_RING, RingCache, roundabout_comfort_speed_ms +from openpilot.selfdrive.mapd.roundabout_status import RingDataWatch, map_msg_valid + +MAPD_HZ = 2.0 +RELOAD_PERIOD_S = 15.0 + + +def _db_path(params: Params) -> str: + try: + raw = params.get("NAPMapSpeedDbPath") or "" + except Exception: + raw = "" + if isinstance(raw, bytes): + raw = raw.decode("utf-8", errors="ignore") + raw = str(raw).strip() + return raw or default_db_path() + + +def _v_ego_ms(sm) -> float: + """Wheel vEgo when carState is live; else GNSS speed. OSM 1.5 s lag offset.""" + if sm.recv_frame.get("carState", -1) > 0: + try: + v = float(sm["carState"].vEgo) + if math.isfinite(v) and v > 0.0: + return v + except Exception: + pass + for sock in ("gpsLocationExternal", "gpsLocation"): + if sm.recv_frame.get(sock, -1) <= 0: + continue + try: + v = float(sm[sock].speed) + except Exception: + continue + if math.isfinite(v) and v > 0.0: + return v + return 0.0 + + +def main(): + params = Params() + sm = messaging.SubMaster(["gpsLocationExternal", "gpsLocation", "carState"]) + pm = messaging.PubMaster(["liveMapDataNAP"]) + rk = Ratekeeper(MAPD_HZ, print_delay_threshold=None) + + db = OsmSpeedLimitDB(_db_path(params)) + last_reload = 0.0 + last_gps_write = 0.0 + rural_prev = None + last_limit_log = None + last_path = db.path + + overrides = SpeedOverrides() + ring_cache = RingCache() + ring_watch = RingDataWatch() + + def _publish_ring(payload: dict) -> None: + try: + params.put(PARAM_RING, payload) + except Exception: + cloudlog.exception("mapd: NAPRoundaboutRing write failed") + + cloudlog.info("mapd starting, db=%s", db.path) + if not os.path.isfile(db.path): + cloudlog.warning("mapd: no OSM sqlite at %s — Settings → NAP → Download US Maps (ODbL)", db.path) + + while True: + sm.update(0) + now = time.monotonic() + if now - last_reload > RELOAD_PERIOD_S: + path = _db_path(params) + if path != last_path: + db.close() + db.path = path + last_path = path + db.open() + overrides.load() + last_reload = now + if db.loaded: + note = ring_watch.check(db.path) + if note is not None: + getattr(cloudlog, note[0])(note[1]) + + lat, lon, bearing, gps_ok = gps_sample_from_sm(sm, now=now) + if gps_ok and (last_gps_write == 0.0 or (now - last_gps_write) >= LAST_GPS_WRITE_PERIOD_S): + persist_last_gps_position(params, lat, lon) + last_gps_write = now + v_ego_ms = _v_ego_ms(sm) if gps_ok else 0.0 + match = db.lookup(lat, lon, bearing, v_ego_ms=v_ego_ms) if gps_ok and db.loaded else None + # Driver-confirmed sign (HUD YES): key it to this way + heading, once. + try: + raw_conf = params.get(SIGN_CONFIRMED_PARAM) + except Exception: + raw_conf = None + if raw_conf is not None or overrides.pending is not None: + try: + added = overrides.consume(raw_conf, match, bearing, now) + if raw_conf is not None: + params.remove(SIGN_CONFIRMED_PARAM) + if added is not None: + cloudlog.info("mapd: sign override way=%s heading=%s mph=%s", added["way_id"], added["heading"], added["mph"]) + except Exception: + cloudlog.exception("mapd: sign override failed") + sign_ms = overrides.limit_ms(int(match.way_id), bearing) if match is not None else None + + msg = messaging.new_message("liveMapDataNAP") + msg.valid = map_msg_valid(gps_ok=gps_ok, db_loaded=db.loaded, matched=match is not None, ring_hint=False) + d = msg.liveMapDataNAP + d.latitude = lat + d.longitude = lon + d.bearingDeg = float(bearing or 0.0) + d.dbLoaded = bool(db.loaded) + d.source = "osm" + if match is not None: + est = bool(getattr(match, "estimated", False)) + lim_ms = float(match.speed_limit_ms) + if sign_ms is None: + # Oct 13: untagged rural tertiary/secondary stays 55 along the same road. + lim_ms = keep_rural_default_ms(lim_ms, estimated=est, highway=match.highway, + road_name=match.road_name, prev=rural_prev) + rural_prev = (match.road_name, match.highway, lim_ms) + d.speedLimit = float(sign_ms if sign_ms is not None else lim_ms) + d.speedLimitValid = True + d.source = map_source_for(est, sign=sign_ms is not None) + key = (int(match.way_id), d.source, round(float(d.speedLimit), 1)) + if key != last_limit_log: + last_limit_log = key + src = ("default" if est else "tagged") + (" sign" if sign_ms is not None else "") + msg_txt = " ".join(( + f"mapd_limit way={int(match.way_id)}", f"name={match.road_name!r}", f"hw={match.highway}", + f"mph={float(d.speedLimit) * 2.23694:.0f}", f"raw_mph={float(match.speed_limit_ms) * 2.23694:.0f}", + f"src={src}", + )) + cloudlog.error(msg_txt) + d.nextSpeedLimit = float(match.next_speed_limit_ms) + d.nextSpeedLimitDistance = float(match.next_distance_m) + d.roadName = match.road_name + d.highway = match.highway + d.wayId = int(match.way_id) + d.matchDistance = float(match.distance_m) + # Same road as the published speed limit. Freeway / trunk matches drop + # nearby residential loops (I-74 Maritime / Seaway false RB). + current_hw = match.highway if match is not None else None + rb = db.find_roundabout(lat, lon, bearing, current_highway=current_hw, v_ego_ms=v_ego_ms) if gps_ok and db.loaded else None + if rb is not None and (rb.on_roundabout or rb.approaching): + d.onRoundabout = bool(rb.on_roundabout) + d.approachingRoundabout = bool(rb.approaching) + d.roundaboutDistance = float(rb.distance_m) + d.roundaboutWayId = int(rb.way_id) + # Ring geometry (center / radius / sense) for controlsd via param, and a + # ring speed that keeps the inner lane ≤ 2.5 m/s² (OSM maxspeed still caps). + geom = ring_cache.update(db, int(rb.way_id), lat, lon, now, publish=_publish_ring) + if geom is not None: + d.roundaboutSpeedLimit = float(roundabout_comfort_speed_ms( + geom.radius_m, geom.lanes, max(float(rb.speed_limit_ms), float(geom.maxspeed_ms)))) + else: + d.roundaboutSpeedLimit = float(rb.speed_limit_ms) + # A ring has no maxspeed to match. Keep the message valid for its hint. + msg.valid = map_msg_valid(gps_ok=gps_ok, db_loaded=db.loaded, matched=match is not None, ring_hint=True) + pm.send("liveMapDataNAP", msg) + rk.keep_time() + + +if __name__ == "__main__": + main() diff --git a/selfdrive/mapd/maps-index.json b/selfdrive/mapd/maps-index.json new file mode 100644 index 00000000000000..2b15d857b8007a --- /dev/null +++ b/selfdrive/mapd/maps-index.json @@ -0,0 +1,8 @@ +{ + "revision": "5", + "asset_name": "speed_limits_us.sqlite.zst", + "asset_url": "https://github.com/jmbrunick/openpilot/releases/download/osm-us-speed-limits-v5/speed_limits_us.sqlite.zst", + "sha256": "b171e03591963c26322fea2329d6a8362308413f1b6e87e4e37bd888a7187fd5", + "bytes": 418098016, + "notes": "Pack schema 5: current posted OSM limits + estimated state-default limits for untagged roads in every state (ways.estimated) + US roundabouts (rb_ways) + rail crossings on drivable roads (rail_crossings)." +} diff --git a/selfdrive/mapd/maps_manifest.py b/selfdrive/mapd/maps_manifest.py new file mode 100644 index 00000000000000..059b941770c9f8 --- /dev/null +++ b/selfdrive/mapd/maps_manifest.py @@ -0,0 +1,229 @@ +"""Where comma 3X fetches the prebuilt US OSM speed-limit DB. + +The sqlite is not in git (too large). Clone/flash stays small; after install, +Settings → NAP → Download US Maps (or `python -m scripts.nap.fetch_osm_maps`) +pulls a GitHub Release asset onto `/data/media/0/osm/speed_limits.sqlite`. + +Refresh maps (Settings or `python -m scripts.nap.refresh_osm_maps`) queries +live OSM via Overpass within 100 miles of the vehicle and merges those ways +into the installed sqlite. It does not download maps-index.json. + +OpenStreetMap data is ODbL: © OpenStreetMap contributors. +https://www.openstreetmap.org/copyright + +Size basis (Taginfo US, 2026-09): ~3.40 million ways with a maxspeed tag. +Measured osm-us-speed-limits-v5: ~399 MiB zst → ~1094 MiB sqlite. Fetch requires +1573 MiB free on the dest filesystem (zst + sqlite + 80 MiB margin). +""" +from __future__ import annotations + +import json +import os +import re +from dataclasses import dataclass + +ATTRIBUTION = "(c) OpenStreetMap contributors" +LICENSE = "ODbL" +LICENSE_URL = "https://www.openstreetmap.org/copyright" + +# Host + tag for the prebuilt DB. Bump the tag when republishing a newer extract. +GITHUB_REPO = "jmbrunick/openpilot" +RELEASE_TAG = "osm-us-speed-limits-v5" +ASSET_NAME = "speed_limits_us.sqlite.zst" +# First-install revision; must match committed maps-index.json. +RELEASE_REVISION = "5" + +# Live index Download US Maps fetches when GitHub is reachable (small JSON). +# Refresh maps does not use this URL — it queries Overpass around the vehicle. +MAPS_INDEX_REF = "nap-dev" +MAPS_INDEX_FILENAME = "maps-index.json" +MAPS_INDEX_URL = ( + f"https://raw.githubusercontent.com/{GITHUB_REPO}/{MAPS_INDEX_REF}" + + f"/selfdrive/mapd/{MAPS_INDEX_FILENAME}" +) + +# Measured osm-us-speed-limits-v5 (~399 MiB zst → ~1094 MiB sqlite: posted + state-default ways, rb_ways, rail_crossings). +# Peak on dest fs is zst + sqlite.partial before the zst is deleted. +ASSET_ZST_BYTES = 399 * 1024 * 1024 +ASSET_SQLITE_BYTES = 1094 * 1024 * 1024 +FREE_MARGIN_BYTES = 80 * 1024 * 1024 +MIN_FREE_MIB = 1573 +MIN_FREE_BYTES = MIN_FREE_MIB * 1024 * 1024 # 399+1094+80 MiB + +# SHA-256 of the Release **zst** asset (not the decompressed sqlite). +# Fetch verifies this on the downloaded .zst BEFORE decompress. +ASSET_SHA256 = "b171e03591963c26322fea2329d6a8362308413f1b6e87e4e37bd888a7187fd5" +# Optional SHA-256 of the decompressed sqlite. Empty = do not hash dest. +SQLITE_SHA256 = "" + +USER_AGENT = "NotAutopilot-mapd/1.0 (OSM ODbL; https://github.com/jmbrunick/openpilot)" + +PARAM_REVISION = "NAPMapSpeedDbRevision" +PARAM_SHA256 = "NAPMapSpeedDbSha256" +REVISION_SIDECAR = "maps-revision.json" + + +def release_asset_url(repo: str = GITHUB_REPO, tag: str = RELEASE_TAG, asset: str = ASSET_NAME) -> str: + return f"https://github.com/{repo}/releases/download/{tag}/{asset}" + + +@dataclass(frozen=True) +class MapsIndex: + """Published US pack metadata. Download US Maps uses this JSON, not Overpass.""" + revision: str + asset_url: str + asset_name: str + sha256: str + bytes: int | None = None + notes: str = "" + + +def bundled_maps_index() -> MapsIndex: + """First-install constants. Kept working even if the live index is unreachable.""" + return MapsIndex( + revision=RELEASE_REVISION, + asset_url=release_asset_url(), + asset_name=ASSET_NAME, + sha256=ASSET_SHA256, + bytes=ASSET_ZST_BYTES, + notes=f"US OSM maxspeed ways plus MN statutory fills ({RELEASE_TAG}).", + ) + + +def committed_maps_index_path() -> str: + return os.path.join(os.path.dirname(os.path.abspath(__file__)), MAPS_INDEX_FILENAME) + + +def _field(data: dict, *keys: str, default: str | None = None) -> str | None: + for key in keys: + if key in data and data[key] is not None: + value = data[key] + if isinstance(value, str): + value = value.strip() + if value: + return value + elif isinstance(value, (int, float)) and not isinstance(value, bool): + return str(value) + return default + + +def parse_maps_index(raw: dict | str | bytes) -> MapsIndex: + """Parse a published maps-index JSON object. + + Required: revision (or version/semver), asset url, sha256 of the zst. + Optional: asset name, notes, bytes. + """ + if isinstance(raw, (bytes, bytearray)): + raw = raw.decode("utf-8") + if isinstance(raw, str): + raw = raw.strip() + if not raw: + raise ValueError("maps index is empty") + data = json.loads(raw) + elif isinstance(raw, dict): + data = raw + else: + raise ValueError(f"maps index must be JSON object or string, not {type(raw).__name__}") + if not isinstance(data, dict): + raise ValueError("maps index JSON must be an object") + + revision = _field(data, "revision", "version", "semver") + asset_url = _field(data, "asset_url", "url") + sha256 = _field(data, "sha256", "sha256_zst") + if not revision: + raise ValueError("maps index missing revision (or version/semver)") + if not asset_url: + raise ValueError("maps index missing asset_url") + if not sha256: + raise ValueError("maps index missing sha256 of the zst") + sha256 = sha256.lower() + if not re.fullmatch(r"[0-9a-f]{64}", sha256): + raise ValueError(f"maps index sha256 must be 64 hex chars, got {sha256!r}") + + asset_name = _field(data, "asset_name", "name") or os.path.basename(asset_url.split("?", 1)[0]) or ASSET_NAME + notes = _field(data, "notes") or "" + size_raw = data.get("bytes", data.get("size")) + size: int | None + if size_raw is None or size_raw == "": + size = None + else: + try: + size = int(size_raw) + except (TypeError, ValueError) as e: + raise ValueError(f"maps index bytes must be an integer, got {size_raw!r}") from e + if size < 0: + raise ValueError("maps index bytes must be >= 0") + + return MapsIndex( + revision=revision, + asset_url=asset_url, + asset_name=asset_name, + sha256=sha256, + bytes=size, + notes=notes, + ) + + +def load_committed_maps_index(path: str | None = None) -> MapsIndex: + path = path or committed_maps_index_path() + with open(path, encoding="utf-8") as f: + return parse_maps_index(f.read()) + + +def _revision_parts(rev: str) -> tuple[int, ...]: + parts: list[int] = [] + for token in re.split(r"[^\d]+", (rev or "").strip()): + if token: + parts.append(int(token)) + return tuple(parts) if parts else (0,) + + +def revision_is_newer(remote: str, installed: str) -> bool: + """True when remote revision should replace installed (numeric/semver compare).""" + remote = (remote or "").strip() + installed = (installed or "").strip() + if not remote: + return False + if not installed: + return True + if remote == installed: + return False + remote_parts = _revision_parts(remote) + installed_parts = _revision_parts(installed) + n = max(len(remote_parts), len(installed_parts)) + remote_parts = remote_parts + (0,) * (n - len(remote_parts)) + installed_parts = installed_parts + (0,) * (n - len(installed_parts)) + if remote_parts != installed_parts: + return remote_parts > installed_parts + return remote != installed + + +def maps_update_decision( + has_sqlite: bool, + installed_revision: str, + installed_sha256: str, + remote: MapsIndex, +) -> str: + """Return 'install', 'update', or 'up_to_date'. + + SHA-256 of the published zst is the file identity. A newer revision or a + different SHA means download. Missing sqlite means first install. A sqlite + with no recorded revision/SHA is treated as unknown (update) so a device + still on v1 picks up v2 instead of being stamped current. + """ + if not has_sqlite: + return "install" + + remote_sha = (remote.sha256 or "").strip().lower() + inst_sha = (installed_sha256 or "").strip().lower() + inst_rev = (installed_revision or "").strip() + + if inst_sha and remote_sha and inst_sha == remote_sha: + return "up_to_date" + if inst_sha and remote_sha and inst_sha != remote_sha: + return "update" + if inst_rev: + return "update" if revision_is_newer(remote.revision, inst_rev) else "up_to_date" + + # Legacy install (sqlite present, no revision/hash recorded). + return "update" diff --git a/selfdrive/mapd/mn_statutory.py b/selfdrive/mapd/mn_statutory.py new file mode 100644 index 00000000000000..6774a99de2e117 --- /dev/null +++ b/selfdrive/mapd/mn_statutory.py @@ -0,0 +1,237 @@ +"""Minnesota statutory speed-limit fills for NAP OSM packs. + +When OSM has no usable numeric maxspeed, NAP may estimate a limit from +Minn. Stat. 169.14 / MnDOT defaults. These values are pack-only estimates +(source=MN_169.14). They must never be uploaded to osm.org. + +OpenStreetMap geometries/tags remain ODbL: © OpenStreetMap contributors. +""" +from __future__ import annotations + +from openpilot.common.constants import CV + +# Benson, MN — the 100-mile refresh / fill region for the v3 pack overlay. +BENSON_LAT = 45.315 +BENSON_LON = -95.602 +BENSON_RADIUS_MILES = 100.0 + +# Coarse Minnesota bounds (excludes the SD sliver of a 100-mile Benson box). +MN_SOUTH = 43.499 +MN_WEST = -97.239 +MN_NORTH = 49.386 +MN_EAST = -89.483 + +FILL_SOURCE = "MN_169.14" +FILL_NOTES = ( + "Unmarked fills are NAP statutory estimates (Minn. Stat. 169.14 / MnDOT), " + + "not surveyed OSM maxspeed. Never upload these tags to osm.org." +) + +ALLEY_MPH = 10 +URBAN_DISTRICT_MPH = 30 +RURAL_OTHER_MPH = 55 +EXPRESSWAY_MPH = 65 +MOTORWAY_RURAL_MPH = 70 +MOTORWAY_URBANIZED_MPH = 65 # pop>50k urbanized area; unused around Benson + +SKIP_HIGHWAYS = frozenset({ + "service", "track", "path", "footway", "cycleway", "pedestrian", + "construction", "proposed", "abandoned", "disused", + "steps", "bridleway", "corridor", "platform", "bus_stop", + "rest_area", "services", "raceway", "escape", "busway", + "elevator", "escalator", "via_ferrata", "emergency_bay", +}) + +# Overpass regex: fillable highway classes only (keeps metro payloads smaller). +FILLABLE_HIGHWAY_REGEX = ( + "^(motorway(_link)?|trunk(_link)?|primary(_link)?|secondary(_link)?" + + r"|tertiary(_link)?|unclassified|residential|living_street|alley)$" +) + +ALLEY_LIKE = frozenset({"alley", "living_street"}) +ALWAYS_URBAN = frozenset({"residential"}) +MOTORWAY_LIKE = frozenset({"motorway", "motorway_link"}) +EXPRESSWAY_ELIGIBLE = frozenset({"trunk", "primary", "trunk_link", "primary_link"}) +RURAL_OTHER = frozenset({ + "unclassified", + "tertiary", "tertiary_link", + "secondary", "secondary_link", + "primary", "primary_link", + "trunk", "trunk_link", +}) +PLACE_VALUES = frozenset({"city", "town", "village"}) +CITY_BORDER_TYPES = frozenset({"city", "town", "village"}) +_SIDEWALK_URBAN = frozenset({"yes", "both", "left", "right", "separate", "shared"}) + + +def in_minnesota(lat: float, lon: float) -> bool: + return MN_SOUTH <= lat <= MN_NORTH and MN_WEST <= lon <= MN_EAST + + +def bbox_intersects_minnesota(bbox: tuple[float, float, float, float]) -> bool: + south, west, north, east = bbox + return north >= MN_SOUTH and south <= MN_NORTH and east >= MN_WEST and west <= MN_EAST + + +def benson_fill_bbox(radius_km: float | None = None) -> tuple[float, float, float, float]: + """100-mile box around Benson, clipped to Minnesota so SD tagged ways stay in the US pack.""" + import math + if radius_km is None: + radius_km = BENSON_RADIUS_MILES * CV.MPH_TO_KPH + dlat = radius_km / 111.0 + dlon = radius_km / (111.0 * max(0.2, abs(math.cos(math.radians(BENSON_LAT))))) + south, west = BENSON_LAT - dlat, BENSON_LON - dlon + north, east = BENSON_LAT + dlat, BENSON_LON + dlon + return ( + max(south, MN_SOUTH), + max(west, MN_WEST), + min(north, MN_NORTH), + min(east, MN_EAST), + ) + + +def is_urban_place_tags(tags: dict) -> bool: + """True for an OSM area that should count as an urban district. + + Minnesota cities are usually boundary=administrative admin_level=8 with + border_type=city (often no place=* on the polygon). Townships are rural. + """ + place = str(tags.get("place") or "").strip().lower() + if place in PLACE_VALUES: + return True + bt = str(tags.get("border_type") or "").strip().lower() + if bt in CITY_BORDER_TYPES: + return True + if bt == "township": + return False + name = str(tags.get("name") or "") + if "township" in name.lower(): + return False + if str(tags.get("admin_level") or "") == "8" and str(tags.get("boundary") or "") == "administrative": + return bool(name.strip()) + return False + + +def _truthy_yes(tag: str | None) -> bool: + return str(tag or "").strip().lower() in ("yes", "true", "1") + + +def is_expressway_like(tags: dict) -> bool: + return _truthy_yes(tags.get("expressway")) or _truthy_yes(tags.get("motorroad")) + + +def is_urban_way(tags: dict, coords: list[tuple[float, float]], places: PlaceIndex | None) -> bool: + """Highway class + simple urban heuristic (place polygons / sidewalks).""" + highway = str(tags.get("highway") or "").strip().lower() + if highway in ALWAYS_URBAN or highway in ALLEY_LIKE: + return True + sidewalk = str(tags.get("sidewalk") or "").strip().lower() + if sidewalk in _SIDEWALK_URBAN: + return True + if places is None or not coords: + return False + lat = sum(c[0] for c in coords) / len(coords) + lon = sum(c[1] for c in coords) / len(coords) + return places.contains(lat, lon) + + +def statutory_maxspeed_mph(highway: str, tags: dict, *, urban: bool) -> int | None: + """MN default mph, or None to skip the way.""" + hw = (highway or str(tags.get("highway") or "")).strip().lower() + if not hw or hw in SKIP_HIGHWAYS: + return None + if hw in ALLEY_LIKE: + return ALLEY_MPH + if hw in MOTORWAY_LIKE: + # Census urbanized (>50k) would be 65 mph. Western MN around Benson is rural. + return MOTORWAY_RURAL_MPH + if hw in EXPRESSWAY_ELIGIBLE and is_expressway_like(tags): + return EXPRESSWAY_MPH + if hw in ALWAYS_URBAN: + return URBAN_DISTRICT_MPH + if hw in RURAL_OTHER: + return URBAN_DISTRICT_MPH if urban else RURAL_OTHER_MPH + return None + + +def statutory_maxspeed_ms(highway: str, tags: dict, *, urban: bool) -> float | None: + mph = statutory_maxspeed_mph(highway, tags, urban=urban) + if mph is None: + return None + return mph * CV.MPH_TO_MS + + +def _point_in_ring(lat: float, lon: float, ring: list[tuple[float, float]]) -> bool: + """Even-odd ray cast. ring is (lat, lon) vertices.""" + n = len(ring) + if n < 3: + return False + inside = False + j = n - 1 + for i in range(n): + yi, xi = ring[i] + yj, xj = ring[j] + if (xi > lon) != (xj > lon): + denom = xj - xi + if abs(denom) > 1e-18: + ycross = (yj - yi) * (lon - xi) / denom + yi + if lat < ycross: + inside = not inside + j = i + return inside + + +class PlaceIndex: + """Named OSM place=city/town/village polygons for the urban heuristic.""" + + def __init__(self) -> None: + self._polys: list[tuple[float, float, float, float, list[list[tuple[float, float]]]]] = [] + + def __len__(self) -> int: + return len(self._polys) + + def add_rings(self, rings: list[list[tuple[float, float]]], _name: str = "") -> None: + outers = [r for r in rings if len(r) >= 3] + if not outers: + return + lats = [p[0] for r in outers for p in r] + lons = [p[1] for r in outers for p in r] + self._polys.append((min(lats), min(lons), max(lats), max(lons), outers)) + + def contains(self, lat: float, lon: float) -> bool: + for min_lat, min_lon, max_lat, max_lon, rings in self._polys: + if lat < min_lat or lat > max_lat or lon < min_lon or lon > max_lon: + continue + if any(_point_in_ring(lat, lon, ring) for ring in rings): + return True + return False + + +def places_from_overpass(payload: dict) -> PlaceIndex: + idx = PlaceIndex() + for el in payload.get("elements", []): + tags = el.get("tags") or {} + if not is_urban_place_tags(tags): + continue + name = tags.get("name") or "" + etype = el.get("type") + rings: list[list[tuple[float, float]]] = [] + if etype == "way": + geom = el.get("geometry") or [] + ring = [(float(p["lat"]), float(p["lon"])) for p in geom if "lat" in p and "lon" in p] + if len(ring) >= 3: + rings.append(ring) + elif etype == "relation": + for mem in el.get("members") or []: + if mem.get("type") != "way": + continue + role = str(mem.get("role") or "outer").lower() + if role not in ("outer", ""): + continue + geom = mem.get("geometry") or [] + ring = [(float(p["lat"]), float(p["lon"])) for p in geom if "lat" in p and "lon" in p] + if len(ring) >= 3: + rings.append(ring) + if rings: + idx.add_rings(rings, name) + return idx diff --git a/selfdrive/mapd/osm_db.py b/selfdrive/mapd/osm_db.py new file mode 100644 index 00000000000000..03cc4056fcfb1d --- /dev/null +++ b/selfdrive/mapd/osm_db.py @@ -0,0 +1,1169 @@ +"""Offline OSM speed-limit SQLite (R-tree) for comma 3X. + +Schema is NAP-owned. Data is OpenStreetMap (ODbL). Query path is GPS → nearest +heading-aligned way. nextSpeedLimit follows that matched way (bearing + class), +not a nearby off-route fill. A lower limit that only lasts MIN_ZONE_LENGTH_M +(~250 ft) along heading is ignored (cross-street bleed / intersection stub). +A short first OSM piece of a longer same-limit town zone is kept. Reverse- +digitized along-route ways (Δheading ≈ 180°) stay on-route. Tagged OSM +maxspeed is authoritative; Minnesota packs may include statutory estimates +for unmarked highways (never uploaded to OSM). +""" +from __future__ import annotations + +import math +import os +import sqlite3 +import struct +import time +from dataclasses import dataclass, replace + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.constants import ( + HEADING_ALIGN_DEG, + LOOKAHEAD_M, + LOOKAHEAD_MAX_M, + MAX_MATCH_DISTANCE_M, + MIN_ZONE_LENGTH_M, + SEARCH_PAD_DEG, + osm_sign_lead_m, +) +from openpilot.selfdrive.mapd.roundabout import ( + RB_FUNNEL_M, + rb_decel_onset_m, + RB_FUNNEL_MIN_M, + RB_ON_WAY_M, + RB_SEARCH_PAD_DEG, + RoundaboutHint, + junction_is_roundabout, + roundabout_suppressed_for_highway, + way_is_roundabout, +) +from openpilot.selfdrive.mapd.roundabout_map import ROLE_RING, RingGeometry +from openpilot.selfdrive.mapd.roundabout_map import ring_geometry as fit_ring_geometry + +# Ring geometry search box around the ego / hinted ring (~165 m). +RB_GEOM_PAD_DEG = 0.0015 + +# Functional class for route continuity. Residential fills next to a trunk +# must not count as the "next limit ahead" even when a heading ray hits them. +_HIGHWAY_RANK = { + "motorway": 0, "motorway_link": 0, + "trunk": 1, "trunk_link": 1, + "primary": 2, "primary_link": 2, + "secondary": 3, "secondary_link": 3, + "tertiary": 4, "tertiary_link": 4, + "unclassified": 5, + "residential": 6, "living_street": 6, "alley": 7, +} + +# Current-way hysteresis. Nearest-wins will hand a motorway to a parallel +# frontage once GPS drifts onto it. Keep the previous way while it is still +# close and aligned; a clearly closer candidate must repeat for several +# lookups. A much slower minor road also has to persist in time or distance. +STICK_KEEP_M = 35.0 +STICK_SWITCH_CLOSER_M = 9.0 +STICK_SWITCH_LOOKUPS = 3 +STICK_PERSIST_S = 5.0 +STICK_PERSIST_M = 150.0 +_PLAUSIBLE_OVER_MS = 20.0 * CV.MPH_TO_MS +_MAJOR_HIGHWAY = { + "motorway", "motorway_link", + "trunk", "trunk_link", + "primary", "primary_link", +} +_MINOR_HIGHWAY = { + "tertiary", "tertiary_link", + "residential", "living_street", "service", "unclassified", +} + +# Ways a car does not drive on. A tagged `maxspeed` here (5 mph on a golf-cart +# `highway=path`) must never become the posted limit, even when it is the only +# stored way within MAX_MATCH_DISTANCE_M of the real, untagged road. Applied in +# `_best_match` (so `_next_limit` and the min-zone probes inherit it), NOT in +# `_candidates()` which roundabout ring geometry also uses. +_NON_ROAD_HIGHWAY = frozenset({ + "path", "footway", "cycleway", "bridleway", "steps", "pedestrian", "track", +}) + + +def _is_non_road_highway(highway: str | None) -> bool: + return (highway or "").strip().lower() in _NON_ROAD_HIGHWAY + +EARTH_R = 6371000.0 +_COORDS_HDR = struct.Struct(" bool: + try: + return bool(row["estimated"]) + except (IndexError, KeyError): + return False + + +# Estimated (state-default) limits never exceed this on the car, so a road wrongly +# classed rural (e.g. I-94 through Bismarck at ND's 80) cannot raise MAX past 65. +# Posted OSM limits are not capped. +ESTIMATED_CAP_MS = 65 * 0.44704 + + +def _row_limit_ms(row) -> float: + v = float(row["maxspeed_ms"] or 0.0) + return min(v, ESTIMATED_CAP_MS) if _row_estimated(row) else v + + +def _pack_coords(coords: list[tuple[float, float]]) -> bytes: + # float32 is ~1 m at US longitudes — enough for MAX_MATCH_DISTANCE_M. + buf = bytearray(_COORDS_HDR.pack(len(coords))) + for lat, lon in coords: + buf += _COORD_F32.pack(float(lat), float(lon)) + return bytes(buf) + + +def _unpack_coords(blob: bytes) -> list[tuple[float, float]]: + n = _COORDS_HDR.unpack_from(blob)[0] + rest = len(blob) - _COORDS_HDR.size + if rest == n * _COORD_F32.size: + fmt, step = _COORD_F32, _COORD_F32.size + elif rest == n * _COORD_F64.size: + fmt, step = _COORD_F64, _COORD_F64.size + else: + return [] + coords = [] + off = _COORDS_HDR.size + for _ in range(n): + lat, lon = fmt.unpack_from(blob, off) + coords.append((float(lat), float(lon))) + off += step + return coords + + +def simplify_coords(coords: list[tuple[float, float]], tol_m: float = SIMPLIFY_TOL_M) -> list[tuple[float, float]]: + """Douglas-Peucker in local meters. Always keeps endpoints.""" + if len(coords) <= 2 or tol_m <= 0: + return coords + lat0, lon0 = coords[0] + + def xy(p: tuple[float, float]) -> tuple[float, float]: + return _local_xy(p[0], p[1], lat0, lon0) + + pts = [xy(c) for c in coords] + keep = [False] * len(coords) + keep[0] = keep[-1] = True + stack = [(0, len(coords) - 1)] + while stack: + i, j = stack.pop() + ax, ay = pts[i] + bx, by = pts[j] + abx, aby = bx - ax, by - ay + ab2 = abx * abx + aby * aby + max_d = -1.0 + max_k = -1 + for k in range(i + 1, j): + px, py = pts[k] + if ab2 < 1e-6: + d = math.hypot(px - ax, py - ay) + else: + t = max(0.0, min(1.0, ((px - ax) * abx + (py - ay) * aby) / ab2)) + d = math.hypot(ax + t * abx - px, ay + t * aby - py) + if d > max_d: + max_d = d + max_k = k + if max_k >= 0 and max_d > tol_m: + keep[max_k] = True + stack.append((i, max_k)) + stack.append((max_k, j)) + return [c for c, k in zip(coords, keep, strict=True) if k] + + +def _wrap_heading_delta(a: float, b: float) -> float: + d = abs(a - b) % 360.0 + return min(d, 360.0 - d) + + +def _heading_aligned(bearing_deg: float | None, seg_heading: float | None) -> bool: + """True if the segment is along travel, including reverse-digitized OSM ways. + + OSM ways are often drawn opposite travel (Δ ≈ 180°). Use min(Δ, 180−Δ) so a + reverse-digitized trunk continuation stays on-route. Cross streets at ~90° + still fail (min(90, 90) = 90 > HEADING_ALIGN_DEG). + """ + if bearing_deg is None or seg_heading is None: + return True + delta = _wrap_heading_delta(bearing_deg, seg_heading) + return min(delta, 180.0 - delta) <= HEADING_ALIGN_DEG + + +def _bearing_deg(lat1: float, lon1: float, lat2: float, lon2: float) -> float: + phi1, phi2 = math.radians(lat1), math.radians(lat2) + dlon = math.radians(lon2 - lon1) + x = math.sin(dlon) * math.cos(phi2) + y = math.cos(phi1) * math.sin(phi2) - math.sin(phi1) * math.cos(phi2) * math.cos(dlon) + return (math.degrees(math.atan2(x, y)) + 360.0) % 360.0 + + +def _offset_point(lat: float, lon: float, bearing_deg: float, dist_m: float) -> tuple[float, float]: + theta = dist_m / EARTH_R + brng = math.radians(bearing_deg) + phi1 = math.radians(lat) + lam1 = math.radians(lon) + phi2 = math.asin(math.sin(phi1) * math.cos(theta) + math.cos(phi1) * math.sin(theta) * math.cos(brng)) + lam2 = lam1 + math.atan2( + math.sin(brng) * math.sin(theta) * math.cos(phi1), + math.cos(theta) - math.sin(phi1) * math.sin(phi2), + ) + return math.degrees(phi2), (math.degrees(lam2) + 540.0) % 360.0 - 180.0 + + +def _local_xy(lat: float, lon: float, lat0: float, lon0: float) -> tuple[float, float]: + x = math.radians(lon - lon0) * math.cos(math.radians(lat0)) * EARTH_R + y = math.radians(lat - lat0) * EARTH_R + return x, y + + +def _point_to_polyline_m(lat: float, lon: float, coords: list[tuple[float, float]]) -> tuple[float, float | None]: + """Return (min distance m, heading of closest segment or None).""" + if len(coords) < 2: + return 1e9, None + best = 1e9 + best_heading = None + px, py = 0.0, 0.0 # query is origin + for i in range(len(coords) - 1): + ax, ay = _local_xy(coords[i][0], coords[i][1], lat, lon) + bx, by = _local_xy(coords[i + 1][0], coords[i + 1][1], lat, lon) + abx, aby = bx - ax, by - ay + ab2 = abx * abx + aby * aby + if ab2 < 1e-6: + t = 0.0 + else: + t = max(0.0, min(1.0, ((px - ax) * abx + (py - ay) * aby) / ab2)) + dx, dy = ax + t * abx - px, ay + t * aby - py + dist = math.hypot(dx, dy) + if dist < best: + best = dist + best_heading = _bearing_deg(coords[i][0], coords[i][1], coords[i + 1][0], coords[i + 1][1]) + return best, best_heading + + +def _continues_route( + bearing_deg: float | None, seg_heading: float | None, + from_name: str, from_highway: str, to_name: str, to_highway: str, +) -> bool: + """True if a candidate is the road ahead, not an off-route cross street / fill. + + Bearing must stay within HEADING_ALIGN_DEG of the segment or its reverse + (OSM often digitizes the town street opposite travel). Same name may change + class (US 12 trunk → primary in town) and is sufficient, not required — + class continuity + bidirectional heading is enough (US 12 → Atlantic). + A major way must not jump onto an unnamed residential / living_street fill + just because it is geometrically closer. + """ + if not _heading_aligned(bearing_deg, seg_heading): + return False + fn = (from_name or "").strip().lower() + tn = (to_name or "").strip().lower() + if fn and tn and fn == tn: + return True + fr = _HIGHWAY_RANK.get((from_highway or "").strip().lower(), 5) + tr = _HIGHWAY_RANK.get((to_highway or "").strip().lower(), 5) + # trunk/primary/secondary → residential 30 fill (v3 MN statutory). + if fr <= 3 and tr >= 6: + return False + return True + + +def _same_named_road(a: str, b: str) -> bool: + an = (a or "").strip().lower() + bn = (b or "").strip().lower() + return bool(an) and an == bn + + +def _major_to_minor(prev_highway: str, cand_highway: str) -> bool: + prev = (prev_highway or "").strip().lower() + cand = (cand_highway or "").strip().lower() + return prev in _MAJOR_HIGHWAY and cand in _MINOR_HIGHWAY + + +def _implausible_minor(v_ego_ms: float, cand: SpeedLimitMatch, prev_highway: str) -> bool: + """Ego is far above a lower-class candidate. A parallel frontage or a bad rematch.""" + if not _major_to_minor(prev_highway, cand.highway): + return False + return float(v_ego_ms) > float(cand.speed_limit_ms) + _PLAUSIBLE_OVER_MS + + +def _meters_between(a: tuple[float, float], b: tuple[float, float]) -> float: + x, y = _local_xy(b[0], b[1], a[0], a[1]) + return math.hypot(x, y) + + +def _seg_len_m(a: tuple[float, float], b: tuple[float, float]) -> float: + x, y = _local_xy(b[0], b[1], a[0], a[1]) + return math.hypot(x, y) + + +def _row_junction(row: sqlite3.Row) -> str: + try: + return str(row["junction"] or "") + except (IndexError, KeyError): + return "" + + +def _closest_xy_on_polyline( + lat: float, lon: float, coords: list[tuple[float, float]], +) -> tuple[float, float, float]: + """Local east/north of the closest point on the polyline, plus distance m.""" + if len(coords) < 2: + return 0.0, 0.0, 1e9 + best = 1e9 + best_x = 0.0 + best_y = 0.0 + px, py = 0.0, 0.0 + for i in range(len(coords) - 1): + ax, ay = _local_xy(coords[i][0], coords[i][1], lat, lon) + bx, by = _local_xy(coords[i + 1][0], coords[i + 1][1], lat, lon) + abx, aby = bx - ax, by - ay + ab2 = abx * abx + aby * aby + t = 0.0 if ab2 < 1e-6 else max(0.0, min(1.0, ((px - ax) * abx + (py - ay) * aby) / ab2)) + dx, dy = ax + t * abx - px, ay + t * aby - py + dist = math.hypot(dx, dy) + if dist < best: + best = dist + best_x, best_y = ax + t * abx, ay + t * aby + return best_x, best_y, best + + +def _along_heading_m(east_m: float, north_m: float, bearing_deg: float) -> float: + br = math.radians(bearing_deg) + return east_m * math.sin(br) + north_m * math.cos(br) + + +def _remaining_ahead( + lat: float, lon: float, bearing_deg: float, coords: list[tuple[float, float]] | tuple[tuple[float, float], ...], +) -> tuple[float, tuple[float, float], float] | None: + """Meters along the way from the closest point to the ahead endpoint. + + Ahead is the digitization direction if GPS heading agrees (<90°), else reverse. + Returns (remaining_m, end_latlon, end_heading_deg) or None. + """ + if len(coords) < 2: + return None + best = 1e12 + best_i = 0 + best_t = 0.0 + best_hdg = 0.0 + px, py = 0.0, 0.0 + for i in range(len(coords) - 1): + ax, ay = _local_xy(coords[i][0], coords[i][1], lat, lon) + bx, by = _local_xy(coords[i + 1][0], coords[i + 1][1], lat, lon) + abx, aby = bx - ax, by - ay + ab2 = abx * abx + aby * aby + t = 0.0 if ab2 < 1e-6 else max(0.0, min(1.0, ((px - ax) * abx + (py - ay) * aby) / ab2)) + dist = math.hypot(ax + t * abx - px, ay + t * aby - py) + if dist < best: + best = dist + best_i = i + best_t = t + best_hdg = _bearing_deg(coords[i][0], coords[i][1], coords[i + 1][0], coords[i + 1][1]) + s = 0.0 + for i in range(best_i): + s += _seg_len_m(coords[i], coords[i + 1]) + s += best_t * _seg_len_m(coords[best_i], coords[best_i + 1]) + total = 0.0 + for i in range(len(coords) - 1): + total += _seg_len_m(coords[i], coords[i + 1]) + with_digitization = _wrap_heading_delta(bearing_deg, best_hdg) <= 90.0 + if with_digitization: + remaining = max(0.0, total - s) + end = coords[-1] + end_hdg = _bearing_deg(coords[-2][0], coords[-2][1], coords[-1][0], coords[-1][1]) + else: + remaining = max(0.0, s) + end = coords[0] + end_hdg = (_bearing_deg(coords[0][0], coords[0][1], coords[1][0], coords[1][1]) + 180.0) % 360.0 + return remaining, (float(end[0]), float(end[1])), float(end_hdg) + + +class OsmSpeedLimitDB: + def __init__(self, path: str): + self.path = path + self._con: sqlite3.Connection | None = None + self._rb_ok = False + self._reset_way_memory() + + @property + def loaded(self) -> bool: + return self._con is not None + + def open(self) -> bool: + if self._con is not None: + return True + if not self.path or not os.path.isfile(self.path): + return False + con = sqlite3.connect(self.path, check_same_thread=False) + con.row_factory = sqlite3.Row + try: + con.execute("SELECT way_id FROM ways LIMIT 1") + except sqlite3.Error: + con.close() + return False + try: + OsmSpeedLimitDB.ensure_junction_column(con) + except sqlite3.Error: + pass + try: + self._rb_ok = OsmSpeedLimitDB.has_rb_tables(con) + except sqlite3.Error: + self._rb_ok = False + self._con = con + return True + + def close(self) -> None: + if self._con is not None: + self._con.close() + self._con = None + self._reset_way_memory() + + @staticmethod + def create(path: str) -> sqlite3.Connection: + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + if os.path.exists(path): + os.remove(path) + con = sqlite3.connect(path) + con.executescript(""" + CREATE TABLE meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE TABLE ways ( + way_id INTEGER PRIMARY KEY, + name TEXT, + highway TEXT, + maxspeed_ms REAL NOT NULL, + min_lat REAL NOT NULL, + max_lat REAL NOT NULL, + min_lon REAL NOT NULL, + max_lon REAL NOT NULL, + coords BLOB NOT NULL, + junction TEXT, + estimated INTEGER NOT NULL DEFAULT 0 + ); + CREATE VIRTUAL TABLE ways_rtree USING rtree( + way_id, min_lat, max_lat, min_lon, max_lon + ); + """) + OsmSpeedLimitDB.ensure_rb_tables(con) + con.executemany( + "INSERT INTO meta(key, value) VALUES (?, ?)", + [ + ("attribution", "© OpenStreetMap contributors"), + ("license", "ODbL"), + ("license_url", "https://www.openstreetmap.org/copyright"), + ("format", "nap-osm-speedlimit-v1"), + ], + ) + con.commit() + return con + + @staticmethod + def meta_get(path: str, key: str) -> str | None: + if not path or not os.path.isfile(path): + return None + try: + con = sqlite3.connect(f"file:{path}?mode=ro", uri=True) + try: + row = con.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone() + return str(row[0]) if row else None + finally: + con.close() + except sqlite3.Error: + return None + + @staticmethod + def way_count(path: str) -> int | None: + raw = OsmSpeedLimitDB.meta_get(path, "way_count") + if raw is None: + return None + try: + return int(raw) + except ValueError: + return None + + @staticmethod + def ensure_junction_column(con: sqlite3.Connection) -> None: + """Published v1 packs omit junction. Refresh / new DBs store the OSM tag.""" + cols = {str(r[1]) for r in con.execute("PRAGMA table_info(ways)")} + if "junction" not in cols: + con.execute("ALTER TABLE ways ADD COLUMN junction TEXT") + if "estimated" not in cols: + # 1 = NAP state-default estimate (MN_169.14 / _default), 0 = OSM maxspeed. + con.execute("ALTER TABLE ways ADD COLUMN estimated INTEGER NOT NULL DEFAULT 0") + + @staticmethod + def insert_way(con: sqlite3.Connection, way_id: int, name: str, highway: str, + maxspeed_ms: float, coords: list[tuple[float, float]], + junction: str = "", estimated: bool = False) -> None: + OsmSpeedLimitDB.ensure_junction_column(con) + coords = simplify_coords(coords) + if len(coords) < 2 or maxspeed_ms <= 0: + return + lats = [c[0] for c in coords] + lons = [c[1] for c in coords] + min_lat, max_lat = min(lats), max(lats) + min_lon, max_lon = min(lons), max(lons) + blob = _pack_coords(coords) + con.execute( + "INSERT OR REPLACE INTO ways(way_id, name, highway, maxspeed_ms, min_lat, max_lat, min_lon, max_lon, coords, junction, estimated) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (int(way_id), name or "", highway or "", float(maxspeed_ms), min_lat, max_lat, min_lon, max_lon, blob, junction or "", + 1 if estimated else 0), + ) + con.execute( + "INSERT OR REPLACE INTO ways_rtree(way_id, min_lat, max_lat, min_lon, max_lon) VALUES (?, ?, ?, ?, ?)", + (int(way_id), min_lat, max_lat, min_lon, max_lon), + ) + + @staticmethod + def delete_ways_intersecting_bbox(con: sqlite3.Connection, south: float, west: float, north: float, east: float) -> int: + """Remove ways whose stored bbox intersects south,west,north,east. Returns deleted count.""" + rows = con.execute( + "SELECT way_id FROM ways_rtree WHERE max_lat >= ? AND min_lat <= ? AND max_lon >= ? AND min_lon <= ?", + (south, north, west, east), + ).fetchall() + ids = [int(r[0]) for r in rows] + if not ids: + return 0 + for i in range(0, len(ids), 500): + chunk = ids[i:i + 500] + q = ",".join("?" * len(chunk)) + con.execute(f"DELETE FROM ways WHERE way_id IN ({q})", chunk) + con.execute(f"DELETE FROM ways_rtree WHERE way_id IN ({q})", chunk) + return len(ids) + + @staticmethod + def recount_ways(con: sqlite3.Connection) -> int: + n = int(con.execute("SELECT COUNT(*) FROM ways").fetchone()[0]) + con.execute("INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", ("way_count", str(n))) + return n + + @staticmethod + def has_rb_tables(con: sqlite3.Connection) -> bool: + row = con.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='rb_ways'").fetchone() + return row is not None + + @staticmethod + def ensure_rb_tables(con: sqlite3.Connection) -> None: + """Roundabout rings + approach roads (no maxspeed needed). Pack v4+ / Refresh maps. + + Kept apart from `ways` so speed-limit matching never sees a 0 m/s way. + """ + con.executescript(""" + CREATE TABLE IF NOT EXISTS rb_ways ( + id INTEGER PRIMARY KEY, + way_id INTEGER NOT NULL, + piece INTEGER NOT NULL DEFAULT 0, + role TEXT NOT NULL, + name TEXT, + highway TEXT, + junction TEXT, + oneway INTEGER NOT NULL DEFAULT 0, + lanes INTEGER NOT NULL DEFAULT 0, + maxspeed_ms REAL NOT NULL DEFAULT 0, + min_lat REAL NOT NULL, + max_lat REAL NOT NULL, + min_lon REAL NOT NULL, + max_lon REAL NOT NULL, + coords BLOB NOT NULL, + UNIQUE(way_id, piece) + ); + CREATE VIRTUAL TABLE IF NOT EXISTS rb_ways_rtree USING rtree( + id, min_lat, max_lat, min_lon, max_lon + ); + """) + + @staticmethod + def insert_rb_way(con: sqlite3.Connection, row: dict) -> None: + """Insert one roundabout_map.roundabout_rows() row (replaces the same way_id/piece).""" + OsmSpeedLimitDB.ensure_rb_tables(con) + coords = simplify_coords([(float(a), float(b)) for a, b in row["coords"]], tol_m=1.0) + if len(coords) < 2: + return + way_id, piece = int(row["way_id"]), int(row.get("piece", 0) or 0) + old = con.execute("SELECT id FROM rb_ways WHERE way_id = ? AND piece = ?", (way_id, piece)).fetchone() + if old is not None: + con.execute("DELETE FROM rb_ways WHERE id = ?", (int(old[0]),)) + con.execute("DELETE FROM rb_ways_rtree WHERE id = ?", (int(old[0]),)) + lats = [c[0] for c in coords] + lons = [c[1] for c in coords] + cur = con.execute( + "INSERT INTO rb_ways(way_id, piece, role, name, highway, junction, oneway, lanes, maxspeed_ms, " + + "min_lat, max_lat, min_lon, max_lon, coords) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (way_id, piece, str(row["role"]), row.get("name") or "", row.get("highway") or "", + row.get("junction") or "", int(row.get("oneway") or 0), int(row.get("lanes") or 0), + float(row.get("maxspeed_ms") or 0.0), min(lats), max(lats), min(lons), max(lons), _pack_coords(coords)), + ) + con.execute( + "INSERT INTO rb_ways_rtree(id, min_lat, max_lat, min_lon, max_lon) VALUES (?, ?, ?, ?, ?)", + (int(cur.lastrowid), min(lats), max(lats), min(lons), max(lons)), + ) + + @staticmethod + def delete_rb_ways_intersecting_bbox(con: sqlite3.Connection, south: float, west: float, + north: float, east: float) -> int: + if not OsmSpeedLimitDB.has_rb_tables(con): + return 0 + ids = [int(r[0]) for r in con.execute( + "SELECT id FROM rb_ways_rtree WHERE max_lat >= ? AND min_lat <= ? AND max_lon >= ? AND min_lon <= ?", + (south, north, west, east), + )] + for i in range(0, len(ids), 500): + chunk = ids[i:i + 500] + q = ",".join("?" * len(chunk)) + con.execute(f"DELETE FROM rb_ways WHERE id IN ({q})", chunk) + con.execute(f"DELETE FROM rb_ways_rtree WHERE id IN ({q})", chunk) + return len(ids) + + @staticmethod + def recount_rb_ways(con: sqlite3.Connection) -> int: + if not OsmSpeedLimitDB.has_rb_tables(con): + return 0 + n = int(con.execute("SELECT COUNT(*) FROM rb_ways WHERE role = 'ring'").fetchone()[0]) + con.execute("INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", ("rb_ring_way_count", str(n))) + return n + + def _rb_candidates(self, lat: float, lon: float, pad_deg: float, role: str | None = None) -> list[sqlite3.Row]: + if self._con is None or not self._rb_ok: + return [] + ids = [ + int(r[0]) for r in self._con.execute( + "SELECT id FROM rb_ways_rtree WHERE max_lat >= ? AND min_lat <= ? AND max_lon >= ? AND min_lon <= ?", + (lat - pad_deg, lat + pad_deg, lon - pad_deg, lon + pad_deg), + ) + ] + if not ids: + return [] + q = f"SELECT * FROM rb_ways WHERE id IN ({','.join('?' * len(ids))})" + rows = list(self._con.execute(q, ids)) + if role is not None: + rows = [r for r in rows if str(r["role"]) == role] + return rows + + def _way_bbox(self, way_id: int) -> tuple[float, float, float, float] | None: + """(min_lat, max_lat, min_lon, max_lon) of a ring way from rb_ways or the speed ways table.""" + if self._con is None: + return None + rows = [] + if self._rb_ok: + rows = list(self._con.execute("SELECT min_lat, max_lat, min_lon, max_lon FROM rb_ways WHERE way_id = ?", (way_id,))) + if not rows: + rows = list(self._con.execute("SELECT min_lat, max_lat, min_lon, max_lon FROM ways WHERE way_id = ?", (way_id,))) + if not rows: + return None + return (min(float(r[0]) for r in rows), max(float(r[1]) for r in rows), + min(float(r[2]) for r in rows), max(float(r[3]) for r in rows)) + + def ring_geometry(self, way_id: int, lat: float, lon: float) -> RingGeometry | None: + """Fit the ring containing way_id (rings from rb_ways and junction-tagged speed ways).""" + if self._con is None: + return None + # Search around the hinted way itself (the hint fires ~150-200 m before the ring), not the car. + pad = RB_GEOM_PAD_DEG + box = self._way_bbox(int(way_id)) + if box is not None: + lat, lon = 0.5 * (box[0] + box[1]), 0.5 * (box[2] + box[3]) + pad += 0.5 * max(box[1] - box[0], box[3] - box[2]) + rings: dict[int, dict] = {} + for row in self._candidates(float(lat), float(lon), pad_deg=pad): + if junction_is_roundabout(_row_junction(row)): + rings[int(row["way_id"])] = { + "way_id": int(row["way_id"]), "coords": _unpack_coords(row["coords"]), "lanes": 0, + "maxspeed_ms": _row_limit_ms(row), "junction": _row_junction(row), + } + approaches = [] + for row in self._rb_candidates(float(lat), float(lon), pad): + d = { + "way_id": int(row["way_id"]), "coords": _unpack_coords(row["coords"]), "lanes": int(row["lanes"] or 0), + "maxspeed_ms": float(row["maxspeed_ms"] or 0.0), "junction": str(row["junction"] or ""), + "oneway": int(row["oneway"] or 0), + } + if str(row["role"]) == ROLE_RING: + prev = rings.get(d["way_id"]) + if prev is not None: + d["maxspeed_ms"] = max(d["maxspeed_ms"], prev["maxspeed_ms"]) + rings[d["way_id"]] = d + else: + approaches.append(d) + if int(way_id) not in rings: + return None + return fit_ring_geometry(list(rings.values()), approaches, seed_id=int(way_id)) + + def _candidates(self, lat: float, lon: float, pad_deg: float | None = None) -> list[sqlite3.Row]: + if self._con is None: + return [] + pad = SEARCH_PAD_DEG if pad_deg is None else float(pad_deg) + ids = [ + int(r[0]) for r in self._con.execute( + "SELECT way_id FROM ways_rtree WHERE max_lat >= ? AND min_lat <= ? AND max_lon >= ? AND min_lon <= ?", + (lat - pad, lat + pad, lon - pad, lon + pad), + ) + ] + if not ids: + return [] + q = f"SELECT * FROM ways WHERE way_id IN ({','.join('?' * len(ids))})" + return list(self._con.execute(q, ids)) + + def _best_match(self, lat: float, lon: float, bearing_deg: float | None, + along_route: SpeedLimitMatch | None = None) -> SpeedLimitMatch | None: + best: SpeedLimitMatch | None = None + best_score = 1e12 + for row in self._candidates(lat, lon): + highway = row["highway"] or "" + if _is_non_road_highway(highway): + continue + coords = _unpack_coords(row["coords"]) + dist, seg_heading = _point_to_polyline_m(lat, lon, coords) + if dist > MAX_MATCH_DISTANCE_M: + continue + name = row["name"] or "" + heading_pen = 0.0 + if along_route is not None: + if not _continues_route( + bearing_deg, seg_heading, + along_route.road_name, along_route.highway, name, highway, + ): + continue + elif bearing_deg is not None and seg_heading is not None: + delta = _wrap_heading_delta(bearing_deg, seg_heading) + # Opposite-direction ways: treat as a large penalty so we pick the + # carriageway we are actually on when a dual carriageway is nearby. + if delta > 180.0 - HEADING_ALIGN_DEG: + heading_pen = 40.0 + elif delta > HEADING_ALIGN_DEG: + heading_pen = 15.0 + score = dist + heading_pen + if score < best_score: + best_score = score + best = SpeedLimitMatch( + speed_limit_ms=_row_limit_ms(row), + way_id=int(row["way_id"]), + road_name=name, + highway=highway, + distance_m=float(dist), + coords=tuple((float(c[0]), float(c[1])) for c in coords), + estimated=_row_estimated(row), + ) + return best + + def _same_limit_run_m( + self, lat: float, lon: float, bearing_deg: float, match: SpeedLimitMatch, + along_route: SpeedLimitMatch | None = None, + ) -> float: + """Meters of contiguous same maxspeed along the matched road from here. + + Walks onto the next on-route same-limit way so a short first OSM piece of + a real town zone counts with the rest of the chain. Does not follow a + heading-misaligned fill (N–S cross street while traveling E–W). + """ + if not match.coords: + return 0.0 + _dist, seg_hdg = _point_to_polyline_m(lat, lon, list(match.coords)) + if seg_hdg is not None and not _heading_aligned(bearing_deg, seg_hdg): + return 0.0 + target_ms = float(match.speed_limit_ms) + traveled = 0.0 + cur_lat, cur_lon = float(lat), float(lon) + cur_brg = float(bearing_deg) + cur_coords: list[tuple[float, float]] | tuple[tuple[float, float], ...] = match.coords + route = along_route if along_route is not None else match + seen = {int(match.way_id)} + for _ in range(24): + if not cur_coords: + break + ahead_info = _remaining_ahead(cur_lat, cur_lon, cur_brg, cur_coords) + if ahead_info is None: + break + rem, end_ll, end_hdg = ahead_info + traveled += rem + if traveled >= MIN_ZONE_LENGTH_M: + return traveled + nxt = None + plat, plon = end_ll[0], end_ll[1] + for step_m in (12.0, 25.0, 40.0): + plat, plon = _offset_point(end_ll[0], end_ll[1], end_hdg, step_m) + cand = self._best_match(plat, plon, end_hdg, along_route=route) + if cand is not None and int(cand.way_id) not in seen: + nxt = cand + break + if nxt is None or abs(nxt.speed_limit_ms - target_ms) > 0.3 or not nxt.coords: + break + seen.add(int(nxt.way_id)) + cur_coords = nxt.coords + cur_lat, cur_lon = plat, plon + cur_brg = end_hdg + return traveled + + def _limit_persists_min_zone( + self, lat: float, lon: float, bearing_deg: float, match: SpeedLimitMatch, + along_route: SpeedLimitMatch | None = None, + ) -> bool: + """True if this limit is a real along-route zone, not a cross-street blip. + + Prefer "returns to prior" over first-way length: + - Probe MIN_ZONE_LENGTH_M along heading. Same limit → keep. A different + limit (typically back on the highway) → ignore (stub / bleed). + - If the probe misses (gap, or past a short first OSM piece), walk the + contiguous same-limit on-route chain. Keep if that run is ≥ MIN_ZONE. + + Remaining-along-way alone is not enough: a long N–S fill has lots of + remaining. The heading-ray probe and the bidirectional heading guard on + the chain walk keep those out. + """ + plat, plon = _offset_point(lat, lon, bearing_deg, MIN_ZONE_LENGTH_M) + ahead = self._best_match(plat, plon, bearing_deg, along_route=along_route) + if ahead is not None: + return abs(ahead.speed_limit_ms - match.speed_limit_ms) <= 0.3 + return self._same_limit_run_m(lat, lon, bearing_deg, match, along_route) >= MIN_ZONE_LENGTH_M + + def _stabilize_match( + self, lat: float, lon: float, bearing_deg: float | None, match: SpeedLimitMatch | None, + ) -> SpeedLimitMatch | None: + """Drop a matched lower limit that only lasts a stub along heading. + + OSM/GPS at a crossroads can snap onto a side street for ~a car length. + Prefer the road that is still there MIN_ZONE_LENGTH_M ahead. Never snap + posted down to a lower ahead zone — that decrease eases via next. + """ + if match is None or bearing_deg is None: + return match + if self._limit_persists_min_zone(lat, lon, bearing_deg, match): + return match + plat, plon = _offset_point(lat, lon, bearing_deg, MIN_ZONE_LENGTH_M) + ahead = self._best_match(plat, plon, bearing_deg) + if ahead is None or int(ahead.way_id) == int(match.way_id): + return match + if ahead.speed_limit_ms + 0.3 < match.speed_limit_ms: + return match + # Same named road changing speed is a real zone end, not cross-street + # bleed. Do not raise posted early; the 1.5 s GNSS offset does that. + match_name = (match.road_name or "").strip().lower() + ahead_name = (ahead.road_name or "").strip().lower() + if match_name and match_name == ahead_name and ahead.speed_limit_ms > match.speed_limit_ms + 0.3: + return match + if not self._limit_persists_min_zone(plat, plon, bearing_deg, ahead): + return match + stable = self._best_match(lat, lon, bearing_deg, along_route=ahead) + if stable is not None and abs(stable.speed_limit_ms - ahead.speed_limit_ms) <= 0.3: + return stable + return ahead + + def _geodesic_next(self, lat: float, lon: float, bearing_deg: float, + match: SpeedLimitMatch) -> tuple[float, float] | None: + """Heading-ray probes after the matched way ends (OSM gap). Route-bearing only.""" + prev_same_d = 0.0 + current_ms = float(match.speed_limit_ms) + for d in LOOKAHEAD_M: + alat, alon = _offset_point(lat, lon, bearing_deg, d) + ahead = self._best_match(alat, alon, bearing_deg, along_route=match) + if ahead is None: + continue + if abs(ahead.speed_limit_ms - current_ms) <= 0.3: + prev_same_d = d + continue + if not self._limit_persists_min_zone(alat, alon, bearing_deg, ahead, along_route=match): + continue + next_dist = 0.5 * (prev_same_d + d) if prev_same_d > 0 else d + return float(ahead.speed_limit_ms), float(next_dist) + return None + + def _along_way_next(self, lat: float, lon: float, bearing_deg: float, + match: SpeedLimitMatch) -> tuple[tuple[float, float] | None, bool]: + """Follow the matched way to its end, then the next on-route way. + + Returns (picked, resolved). resolved means the next LOOKAHEAD_MAX_M along + this road is known (a different limit, or the same limit continuing) — do + not fall back to a heading ray that can hit off-route fills. + + Catches a short intermediate limit (US 12 60→50 before 30) that geodesic + 40 m heading probes skip when the road curves or the 50 way is short. + """ + if not match.coords: + return None, False + current_ms = float(match.speed_limit_ms) + traveled = 0.0 + cur_lat, cur_lon = float(lat), float(lon) + cur_brg = float(bearing_deg) + cur_coords: list[tuple[float, float]] | tuple[tuple[float, float], ...] = match.coords + seen = {int(match.way_id)} + plat, plon = cur_lat, cur_lon + for _ in range(24): + ahead_info = _remaining_ahead(cur_lat, cur_lon, cur_brg, cur_coords) + if ahead_info is None: + return None, False + rem, end_ll, end_hdg = ahead_info + if traveled + rem > LOOKAHEAD_MAX_M + 1.0: + return None, True + nxt = None + # Step past the end; 12 m can still match the way we just left + # (MAX_MATCH_DISTANCE_M=35). + for step_m in (12.0, 25.0, 40.0): + plat, plon = _offset_point(end_ll[0], end_ll[1], end_hdg, step_m) + cand = self._best_match(plat, plon, end_hdg, along_route=match) + if cand is not None and int(cand.way_id) not in seen: + nxt = cand + break + if nxt is None: + return None, False + seen.add(int(nxt.way_id)) + if abs(nxt.speed_limit_ms - current_ms) > 0.3: + if self._limit_persists_min_zone(plat, plon, end_hdg, nxt, along_route=match): + traveled += rem + return (float(nxt.speed_limit_ms), float(traveled)), True + # Stub / cross-street bleed: do not walk down that way. Stay on the + # previous geometry; `seen` prevents re-picking the stub. + continue + traveled += rem + if not nxt.coords: + return None, False + cur_coords = nxt.coords + cur_lat, cur_lon = plat, plon + cur_brg = end_hdg + return None, True + + def _next_limit(self, lat: float, lon: float, bearing_deg: float, + match: SpeedLimitMatch) -> tuple[float, float] | None: + along, resolved = self._along_way_next(lat, lon, bearing_deg, match) + if along is not None: + return along + if resolved: + return None + return self._geodesic_next(lat, lon, bearing_deg, match) + + def find_roundabout( + self, lat: float, lon: float, bearing_deg: float | None = None, + current_highway: str | None = None, + v_ego_ms: float | None = None, + ) -> RoundaboutHint: + """Upcoming / current OSM circulating ring within the speed-based funnel. + + Funnel = rb_decel_onset_m(v_ego): 140 m at town speed, ~340 m from + 55 mph, max 450 m. Once a ring is hinted it stays latched out to the + 450 m reach so slowing down (which shrinks the onset) cannot drop the + hint mid-approach and fire an early "exit" MAX restore. + + Does not apply MIN_ZONE_LENGTH_M — a typical RB is a short along-heading + stub and would otherwise be dropped as cross-street bleed. Sharp corners + and signalized crossings are not closed/tagged circulating ways. + Motorway / trunk matches suppress the hint (a residential loop beside + the carriageway is not the road ahead). + """ + if self._con is None: + return RoundaboutHint() + if current_highway is None: + matched = self._best_match(float(lat), float(lon), bearing_deg) + current_highway = matched.highway if matched is not None else "" + if roundabout_suppressed_for_highway(current_highway): + return RoundaboutHint() + # Default SEARCH_PAD is ~110 m; 200 m westbound at 45°N needs more. + rows = list(self._candidates(float(lat), float(lon), pad_deg=RB_SEARCH_PAD_DEG)) + seen = {int(r["way_id"]) for r in rows} + # Pack v4 / Refresh maps: rings without maxspeed live in rb_ways. + rows += [r for r in self._rb_candidates(float(lat), float(lon), RB_SEARCH_PAD_DEG, role=ROLE_RING) + if int(r["way_id"]) not in seen] + + best: RoundaboutHint | None = None + best_dist = 1e12 + for row in rows: + coords = _unpack_coords(row["coords"]) + if not way_is_roundabout(coords, _row_junction(row), row["highway"] or ""): + continue + east_m, north_m, dist = _closest_xy_on_polyline(float(lat), float(lon), coords) + way_id = int(row["way_id"]) + latched = way_id == getattr(self, "_rb_latch_way", 0) + if dist > (RB_FUNNEL_M if latched else rb_decel_onset_m(v_ego_ms)): + continue + if bearing_deg is not None and dist > RB_ON_WAY_M: + along = _along_heading_m(east_m, north_m, float(bearing_deg)) + if along < -12.0: + continue + # Far funnel only: skip rings well off the travel heading. + if dist > RB_FUNNEL_MIN_M and along < (0.5 * dist): + continue + on_rb = dist <= RB_ON_WAY_M + hint = RoundaboutHint( + on_roundabout=on_rb, + approaching=(not on_rb), + distance_m=0.0 if on_rb else float(dist), + speed_limit_ms=_row_limit_ms(row), + way_id=int(row["way_id"]), + ) + # Prefer on-ring, then nearer ahead. + rank = (0 if on_rb else 1, dist) + best_rank = (0 if (best and best.on_roundabout) else 1, best_dist) + if best is None or rank < best_rank: + best = hint + best_dist = dist + self._rb_latch_way = best.way_id if best is not None else 0 + return best if best is not None else RoundaboutHint() + + def _reset_way_memory(self) -> None: + self._stuck_match: SpeedLimitMatch | None = None + self._reset_pending() + + def _reset_pending(self) -> None: + self._pending_way_id: int | None = None + self._pending_lookups = 0 + self._pending_since_s: float | None = None + self._pending_dist_m = 0.0 + self._pending_latlon: tuple[float, float] | None = None + + def _observe_switch_candidate( + self, way_id: int, closer_m: float, lat: float, lon: float, now: float, + ) -> tuple[int, float, float]: + """Track one rival way. Returns (closer-lookups, elapsed_s, traveled_m).""" + if self._pending_way_id != int(way_id): + self._pending_way_id = int(way_id) + self._pending_lookups = 1 if closer_m >= STICK_SWITCH_CLOSER_M else 0 + self._pending_since_s = now + self._pending_dist_m = 0.0 + self._pending_latlon = (lat, lon) + else: + if self._pending_latlon is not None: + self._pending_dist_m += _meters_between(self._pending_latlon, (lat, lon)) + self._pending_latlon = (lat, lon) + if closer_m >= STICK_SWITCH_CLOSER_M: + self._pending_lookups += 1 + else: + self._pending_lookups = 0 + elapsed = 0.0 if self._pending_since_s is None else max(0.0, now - float(self._pending_since_s)) + return self._pending_lookups, elapsed, self._pending_dist_m + + def _switch_persisted(self, elapsed_s: float, traveled_m: float) -> bool: + return float(elapsed_s) >= STICK_PERSIST_S or float(traveled_m) >= STICK_PERSIST_M + + def _current_way_is_sticky( + self, prev_dist_m: float, heading_aligned: bool, closer_m: float, pending_lookups: int, + ) -> bool: + """Keep the previous way unless a candidate is clearly closer for several lookups.""" + if prev_dist_m > STICK_KEEP_M or not heading_aligned: + return False + if closer_m >= STICK_SWITCH_CLOSER_M and pending_lookups >= STICK_SWITCH_LOOKUPS: + return False + return True + + def _accept_current_way(self, match: SpeedLimitMatch) -> SpeedLimitMatch: + self._stuck_match = match + self._reset_pending() + return match + + def _keep_current_way( + self, lat: float, lon: float, bearing_deg: float | None, v_ego_ms: float, + cand: SpeedLimitMatch | None, now_s: float | None, + ) -> SpeedLimitMatch | None: + """Hysteresis + plausibility for the published current road. + + Probe matches (`_best_match` along the route) stay stateless. Only the + road we publish as the current limit sticks. + """ + now = time.monotonic() if now_s is None else float(now_s) + prev = self._stuck_match + if cand is None: + self._reset_pending() + return None + if prev is None or int(prev.way_id) == int(cand.way_id) or _same_named_road(prev.road_name, cand.road_name): + return self._accept_current_way(cand) + + prev_dist, prev_heading = _point_to_polyline_m(lat, lon, list(prev.coords)) + aligned = bearing_deg is None or _heading_aligned(bearing_deg, prev_heading) + cand_dist, _cand_heading = _point_to_polyline_m(lat, lon, list(cand.coords)) + closer = float(prev_dist) - float(cand_dist) + lookups, elapsed, traveled = self._observe_switch_candidate(int(cand.way_id), closer, lat, lon, now) + if self._current_way_is_sticky(float(prev_dist), aligned, closer, lookups): + return replace(prev, distance_m=float(prev_dist)) + if _implausible_minor(v_ego_ms, cand, prev.highway) and not self._switch_persisted(elapsed, traveled): + if float(prev_dist) <= STICK_KEEP_M and aligned: + return replace(prev, distance_m=float(prev_dist)) + return None + return self._accept_current_way(cand) + + def lookup(self, lat: float, lon: float, bearing_deg: float | None = None, + v_ego_ms: float = 0.0, now_s: float | None = None) -> SpeedLimitMatch | None: + if self._con is None: + return None + gps_match = self._stabilize_match( + float(lat), float(lon), bearing_deg, + self._best_match(float(lat), float(lon), bearing_deg), + ) + qlat, qlon = float(lat), float(lon) + lead_m = osm_sign_lead_m(v_ego_ms) + lead_match = gps_match + if lead_m > 0.0 and bearing_deg is not None: + qlat, qlon = _offset_point(qlat, qlon, float(bearing_deg), lead_m) + lead_match = self._stabilize_match( + qlat, qlon, bearing_deg, + self._best_match(qlat, qlon, bearing_deg), + ) + + # GNSS lag: raise posted when the 1.5 s point is already in a higher zone. + # Do not snap posted down — any decrease (10/15/20 mph, short zones) must + # ease with kin+110 m, not jump when GPS or the offset crosses the boundary. + raised = ( + lead_match is not None and gps_match is not None + and float(lead_match.speed_limit_ms) > float(gps_match.speed_limit_ms) + 0.3 + ) + if raised or gps_match is None: + match = lead_match + else: + match = gps_match + match = self._keep_current_way( + float(lat), float(lon), bearing_deg, float(v_ego_ms), match, now_s, + ) + if match is None: + return None + if bearing_deg is None: + return match + raised = bool( + raised and lead_match is not None and int(match.way_id) == int(lead_match.way_id) + ) + + # Next limit follows the matched road (bearing + class/name). Do not use a + # heading ray that can pick a nearby residential fill as "ahead". + # Remaining is from GPS minus v*1.5 s so ease starts at the lag-corrected zone. + if raised: + picked = self._next_limit(qlat, qlon, float(bearing_deg), match) + else: + picked = self._next_limit(float(lat), float(lon), float(bearing_deg), match) + if picked is not None: + nxt, dist = picked + picked = (nxt, max(0.0, float(dist) - lead_m)) + if picked is None: + return match + next_limit, next_dist = picked + if next_limit <= 0: + return match + return SpeedLimitMatch( + speed_limit_ms=match.speed_limit_ms, + way_id=match.way_id, + road_name=match.road_name, + highway=match.highway, + distance_m=match.distance_m, + next_speed_limit_ms=next_limit, + next_distance_m=next_dist, + estimated=match.estimated, + ) diff --git a/selfdrive/mapd/overpass.py b/selfdrive/mapd/overpass.py new file mode 100644 index 00000000000000..624638b4032518 --- /dev/null +++ b/selfdrive/mapd/overpass.py @@ -0,0 +1,177 @@ +"""Overpass JSON → NAP OSM speed-limit ways. + +OpenStreetMap data is ODbL: © OpenStreetMap contributors. +https://www.openstreetmap.org/copyright +""" +from __future__ import annotations + +import json +import math +import urllib.error +import urllib.parse +import urllib.request + +from openpilot.selfdrive.mapd.maps_manifest import USER_AGENT +from openpilot.selfdrive.mapd.mn_statutory import ( + FILLABLE_HIGHWAY_REGEX, + PlaceIndex, + places_from_overpass, +) +from openpilot.selfdrive.mapd.us_statutory import default_maxspeed_ms, inherit_posted_neighbors, is_fill_source, state_index +from openpilot.selfdrive.mapd.speed_limit import parse_maxspeed + +OVERPASS_URL = "https://overpass-api.de/api/interpreter" +_KEEP = "Previous maps were left unchanged. You can retry Refresh maps." + + +def bbox_from_center(lat: float, lon: float, radius_km: float) -> tuple[float, float, float, float]: + """south, west, north, east box that contains a radius_km circle around lat/lon.""" + dlat = radius_km / 111.0 + dlon = radius_km / (111.0 * max(0.2, abs(math.cos(math.radians(lat))))) + return lat - dlat, lon - dlon, lat + dlat, lon + dlon + + +def overpass_query( + south: float, west: float, north: float, east: float, + *, + timeout_s: int = 180, + include_unmarked: bool = False, + include_roundabouts: bool = True, + unmarked_regex: str = FILLABLE_HIGHWAY_REGEX, +) -> str: + """Bbox query. Tagged maxspeed only, or all fillable highways + place polygons (MN fill). + + include_roundabouts adds junction=roundabout|circular rings and the highway + ways that touch them, with or without maxspeed. + """ + bbox = f"({south},{west},{north},{east})" + # Roundabout rings (any maxspeed) + every highway way sharing a ring node + # (approach roads). Stored in rb_ways, not in the speed-limit ways table. + rb_sets = "" if not include_roundabouts else f""" +way["highway"]["junction"~"^(roundabout|circular)$"]{bbox}->.rb; +node(w.rb)->.rbn; +way(bn.rbn)["highway"]->.ap;""" + rb_union = "" if not include_roundabouts else "\n .rb;\n .ap;" + if include_unmarked: + return f""" +[out:json][timeout:{int(timeout_s)}];{rb_sets} +( + way["highway"~"{unmarked_regex}"]{bbox}; + way["place"~"^(city|town|village)$"]{bbox}; + rel["place"~"^(city|town|village)$"]{bbox}; + way["boundary"="administrative"]["admin_level"="8"]{bbox}; + rel["boundary"="administrative"]["admin_level"="8"]{bbox};{rb_union} +); +out geom; +""".strip() + if not include_roundabouts: + return f""" +[out:json][timeout:{int(timeout_s)}]; +way["highway"]["maxspeed"]{bbox}; +out geom; +""".strip() + return f""" +[out:json][timeout:{int(timeout_s)}];{rb_sets} +( + way["highway"]["maxspeed"]{bbox};{rb_union} +); +out geom; +""".strip() + + +def fetch_overpass( + bbox: tuple[float, float, float, float], + url: str = OVERPASS_URL, + *, + timeout_s: float = 240, + query_timeout: int = 180, + include_unmarked: bool = False, + include_roundabouts: bool = True, + unmarked_regex: str = FILLABLE_HIGHWAY_REGEX, +) -> dict: + """POST a bbox highway query. Raises RuntimeError with a retryable message on timeout/HTTP failure.""" + q = overpass_query(*bbox, timeout_s=query_timeout, include_unmarked=include_unmarked, + include_roundabouts=include_roundabouts, unmarked_regex=unmarked_regex) + data = urllib.parse.urlencode({"data": q}).encode() + req = urllib.request.Request(url, data=data, headers={"User-Agent": USER_AGENT}) + try: + with urllib.request.urlopen(req, timeout=timeout_s) as resp: + raw = resp.read().decode("utf-8") + except urllib.error.HTTPError as e: + raise RuntimeError(f"OSM Overpass failed HTTP {e.code}. {_KEEP}") from e + except urllib.error.URLError as e: + raise RuntimeError(f"OSM Overpass failed: {e}. Need Wi-Fi to overpass-api.de. {_KEEP}") from e + except TimeoutError as e: + raise RuntimeError(f"OSM Overpass timed out. {_KEEP}") from e + try: + payload = json.loads(raw) + except json.JSONDecodeError as e: + raise RuntimeError(f"OSM Overpass returned invalid JSON: {e}. {_KEEP}") from e + if not isinstance(payload, dict): + raise RuntimeError(f"OSM Overpass returned a non-object JSON payload. {_KEEP}") + remark = str(payload.get("remark") or "") + if "timed out" in remark.lower() or payload.get("timeout"): + raise RuntimeError(f"OSM Overpass timed out ({remark or 'query timeout'}). {_KEEP}") + return payload + + +def tagged_maxspeed_ms(tags: dict) -> float | None: + """Numeric OSM maxspeed / maxspeed:forward. Non-numeric tags are not usable.""" + ms = parse_maxspeed(tags.get("maxspeed")) + if ms is None: + ms = parse_maxspeed(tags.get("maxspeed:forward")) + return ms + + +def resolve_way_speed( + tags: dict, + coords: list[tuple[float, float]], + *, + fill_unmarked: bool = False, + places: PlaceIndex | None = None, + state: str | None = None, +) -> tuple[float | None, str]: + """Return (maxspeed_ms, source). source is 'osm', MN_169.14 or '_default'. Tagged numeric wins. + + Untagged ways get the state default (us_statutory) when fill_unmarked; the + state comes from the way's position unless given. + """ + ms = tagged_maxspeed_ms(tags) + if ms is not None: + return ms, "osm" + if not fill_unmarked: + return None, "" + if state is None: + state = state_index().state_of_way(coords) + return default_maxspeed_ms(state, str(tags.get("highway") or ""), tags, coords, places) + + +def ways_from_overpass(payload: dict, *, fill_unmarked: bool = False) -> list[dict]: + places = places_from_overpass(payload) if fill_unmarked else PlaceIndex() + out = [] + for el in payload.get("elements", []): + if el.get("type") != "way": + continue + tags = el.get("tags") or {} + if "highway" not in tags: + continue + geom = el.get("geometry") or [] + coords = [(float(p["lat"]), float(p["lon"])) for p in geom if "lat" in p and "lon" in p] + if len(coords) < 2: + continue + ms, source = resolve_way_speed(tags, coords, fill_unmarked=fill_unmarked, places=places) + if ms is None: + continue + out.append({ + "way_id": int(el["id"]), + "name": tags.get("name") or tags.get("ref") or "", + "highway": tags.get("highway") or "", + "maxspeed_ms": ms, + "coords": coords, + "source": source, + "estimated": is_fill_source(source), + "junction": tags.get("junction") or "", + }) + if fill_unmarked: + inherit_posted_neighbors(out) + return out diff --git a/selfdrive/mapd/rail_crossings.py b/selfdrive/mapd/rail_crossings.py new file mode 100644 index 00000000000000..a7e9b8fb114b2f --- /dev/null +++ b/selfdrive/mapd/rail_crossings.py @@ -0,0 +1,72 @@ +"""Railroad crossings on drivable roads, from the map pack (schema v5+). + +Data only for now: OSM railway=level_crossing / railway=crossing nodes that sit +on a drivable highway way. No UI alert yet; ``crossings_ahead`` is the lookup a +later alert will use. +""" +from __future__ import annotations + +import math +import sqlite3 +from dataclasses import dataclass + +TABLE = "rail_crossings" +EARTH_R_M = 6371000.0 + + +@dataclass(frozen=True) +class RailCrossing: + node_id: int + lat: float + lon: float + way_id: int + kind: str # "level_crossing" | "crossing" + barrier: str # crossing:barrier (e.g. "full", "half", "no"), "" if untagged + light: str # crossing:light ("yes"/"no"), "" if untagged + crossing: str # crossing=* (e.g. "uncontrolled"), "" if untagged + distance_m: float # along the heading + lateral_m: float # signed, + = right of heading + + +def ensure_table(con: sqlite3.Connection) -> None: + con.execute( + f"CREATE TABLE IF NOT EXISTS {TABLE}(node_id INTEGER PRIMARY KEY, lat REAL NOT NULL, lon REAL NOT NULL," + + " way_id INTEGER NOT NULL, kind TEXT NOT NULL, barrier TEXT NOT NULL DEFAULT '', light TEXT NOT NULL DEFAULT ''," + + " crossing TEXT NOT NULL DEFAULT '')") + con.execute(f"CREATE INDEX IF NOT EXISTS {TABLE}_lat_lon ON {TABLE}(lat, lon)") + + +def has_table(con: sqlite3.Connection) -> bool: + return con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (TABLE,)).fetchone() is not None + + +def insert(con: sqlite3.Connection, node_id: int, lat: float, lon: float, way_id: int, kind: str, + barrier: str = "", light: str = "", crossing: str = "") -> None: + con.execute(f"INSERT OR REPLACE INTO {TABLE} VALUES(?,?,?,?,?,?,?,?)", + (node_id, lat, lon, way_id, kind, barrier or "", light or "", crossing or "")) + + +def crossings_ahead(con: sqlite3.Connection, lat: float, lon: float, bearing_deg: float, + horizon_m: float = 500.0, lateral_m: float = 30.0) -> list[RailCrossing]: + """Crossings within ``horizon_m`` ahead and ``lateral_m`` of the heading line, nearest first.""" + if not has_table(con): + return [] + dlat = math.degrees(horizon_m / EARTH_R_M) + dlon = dlat / max(math.cos(math.radians(lat)), 1e-6) + rows = con.execute( + f"SELECT node_id, lat, lon, way_id, kind, barrier, light, crossing FROM {TABLE}" + + " WHERE lat BETWEEN ? AND ? AND lon BETWEEN ? AND ?", + (lat - dlat, lat + dlat, lon - dlon, lon + dlon)).fetchall() + h = math.radians(bearing_deg) + hx, hy = math.sin(h), math.cos(h) + k = math.radians(1) * EARTH_R_M + out = [] + for nid, la, lo, wid, kind, barrier, light, crossing in rows: + e = (lo - lon) * k * math.cos(math.radians(lat)) + n = (la - lat) * k + along = e * hx + n * hy + lat_off = e * hy - n * hx + if 0.0 <= along <= horizon_m and abs(lat_off) <= lateral_m: + out.append(RailCrossing(nid, la, lo, wid, kind, barrier, light, crossing, along, lat_off)) + out.sort(key=lambda c: c.distance_m) + return out diff --git a/selfdrive/mapd/roundabout.py b/selfdrive/mapd/roundabout.py new file mode 100644 index 00000000000000..8f27976df12964 --- /dev/null +++ b/selfdrive/mapd/roundabout.py @@ -0,0 +1,416 @@ +"""Roundabout detect, speed ease, and outer path bias. + +Map `junction=roundabout` (or a closed circulating way already in the OSM +pack) — not steer. Decel onset ~140 m (was 200 m, Oct 1) so 35 mph can hit 18 by the +ring. Kinematic a (not Lookahead comfort −0.55) toward OSM maxspeed when +present. Clamp aTarget ≤ 0 while approaching / on the ring. + +Lateral: the legacy ~3.2 m outer path bias (#223) is applied only when the +turn geometry correction (NAPLatTurnGeom, default On for Pre-AP) is off. +With the correction on, modeld owns turn-in timing / rear-axle reference and +roundabouts get no extra lateral bias (no double compensation). + +Yield-before-merge, continue-circulate desire, and UI chip are later tips. +""" +from __future__ import annotations + +import math +from dataclasses import dataclass + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.constants import LOOKAHEAD_NORMAL + +# Speed-based decel onset (Oct 11, Watertown SD): the fixed 140 m was tuned +# for 35->18 mph and was late / abrupt from a 55 mph approach (needs ~340 m +# at 0.7 m/s²). Onset = (v² − v_ring²)/(2·0.7) + 30 m, clamped 140–450 m. +RB_ONSET_A_MS2 = 0.7 +RB_ONSET_MARGIN_M = 70.0 # Oct 13: +40 m with the earlier final ramp +RB_ONSET_MIN_M = 140.0 +RB_ONSET_MAX_M = 450.0 +# MAX profile reaches ring speed this far before the ring line. +# Oct 13: 15 m left the final slowdown firming to -1.2…-1.9 in the last +# 60–130 m. 55 m starts that final slowdown ~40 m earlier. +RB_PROFILE_BUFFER_M = 55.0 +# Kinematic −a ceiling: never brick-wall. Oct 13: about -1.0 (was -1.5). +RB_A_MAX_DECEL_MS2 = -1.0 +# Planner jerk limit on the ring −a onset (m/s³). +RB_DECEL_JERK_MS3 = 1.5 +# Detect / start ease by this distance (the decel onset). Must still have fired by MIN. +# Oct 1: 200 m (first fire 187 m in the field) braked ~0.2 m/s² earlier than needed and had the car crawling at 18 mph well before the ring +# (0000013c); 140 m keeps 35→18 mph at ~0.64 m/s² average. 100 m was too late (Willmar 10:11 / 10:14). +RB_DECEL_ONSET_M = RB_ONSET_MIN_M # low-speed onset (35->18 mph); see rb_decel_onset_m +# Search / latch reach: the longest speed-based onset. +RB_FUNNEL_M = RB_ONSET_MAX_M +RB_FUNNEL_MIN_M = 80.0 +# ~0.0065° ≈ 510 m EW at 45°N (720 m N-S) so a 450 m approach is in the rtree. +RB_SEARCH_PAD_DEG = 0.0065 + +# Circulating target. OSM maxspeed on the RB way wins when present (often 20). +# Sep 30: entry was a little slow. Soco ring pass speeds were 17-19 mph (R126 17.8, R128 19.3, R130 17.5 median); the +# 2.5 m/s² comfort speed (15.8 mph) is now floored here, so the planner's ring speed (and the guide's) is 18 mph. +RB_RING_SPEED_MPH = 18.0 +RB_V_MIN_MS = RB_RING_SPEED_MPH * CV.MPH_TO_MS +RB_V_MAX_MS = 20.0 * CV.MPH_TO_MS +RB_V_DEFAULT_MS = 20.0 * CV.MPH_TO_MS + +# Kinematic ease. Lookahead Early comfort is only 0.55 — that is why tip +# aTarget sat at −0.55 at 37–45 mph. Plan to ring speed from remaining d. +RB_A_MIN_MS2 = RB_A_MAX_DECEL_MS2 +RB_A_FLOOR_MS2 = -1.0 +RB_A_FLOOR_V_MS = 40.0 * CV.MPH_TO_MS +RB_NEAR_SPEED_MS = 2.5 * CV.MPH_TO_MS +RB_ON_RING_DECEL_M = 28.0 +RB_DECEL_D_MIN_M = 12.0 + +# Legacy outer path bias (turn geometry correction OFF only). openpilot +y is left. EP1: OP lat R=14.9 vs OSM 18.2 +# (−3.3 m inside); 0.45 m was far too small. 3.2 m counters that cut and +# sits near the outer half of the circulating lane / ring, not the island. +RB_OUTER_OFFSET_M = 3.2 +RB_OUTER_OFFSET_MIN_M = 2.8 +RB_OUTER_OFFSET_MAX_M = 3.6 +# Preview length for a parallel-path curvature offset (κ ≈ 2 y / L²). +RB_PATH_LOOKAHEAD_M = 18.0 +# Apply the same outer bias on the last stretch of approach (not 200 m out). +RB_ENTRY_BIAS_M = 50.0 + +# Closed-loop geometry for published packs that do not store `junction`. +RB_RADIUS_MIN_M = 6.0 +RB_RADIUS_MAX_M = 55.0 +RB_CLOSED_GAP_M = 8.0 +RB_ON_WAY_M = 25.0 +# Service / path / residential loops (cul-de-sac bulbs, Maritime/Seaway) are +# not circulating RBs unless tagged junction=roundabout|circular. +_UNTAGGED_SKIP_HIGHWAY = frozenset({ + "service", "footway", "path", "cycleway", "pedestrian", "steps", "track", + "residential", "living_street", +}) +_RB_JUNCTIONS = frozenset({"roundabout", "circular"}) +# Freeway / trunk mainline. A side-street loop beside I-74 is not an upcoming +# roundabout. Town rings are not on these classes (Willmar stays on residential). +_RB_SUPPRESS_HIGHWAY = frozenset({ + "motorway", "motorway_link", "trunk", "trunk_link", +}) + +EARTH_R = 6371000.0 + + +@dataclass(frozen=True) +class RoundaboutHint: + on_roundabout: bool = False + approaching: bool = False + distance_m: float = 0.0 + speed_limit_ms: float = 0.0 + way_id: int = 0 + + +def rb_decel_onset_m(v_ego_ms: float | None, v_ring_ms: float | None = None) -> float: + """Distance before the ring to start easing: (v² − v_ring²)/(2·0.7) + RB_ONSET_MARGIN_M, 140–450 m.""" + if v_ego_ms is None: + return RB_ONSET_MIN_M + vr = RB_V_MIN_MS if v_ring_ms is None else float(v_ring_ms) + v = max(float(v_ego_ms), 0.0) + d = max(0.0, v * v - vr * vr) / (2.0 * RB_ONSET_A_MS2) + RB_ONSET_MARGIN_M + return max(RB_ONSET_MIN_M, min(RB_ONSET_MAX_M, d)) + + +def rb_profile_v_ms(distance_m: float, target_ms: float) -> float: + """MAX ceiling on approach: reach target RB_PROFILE_BUFFER_M before the ring at 0.7 m/s².""" + d = max(0.0, float(distance_m) - RB_PROFILE_BUFFER_M) + return math.sqrt(float(target_ms) ** 2 + 2.0 * RB_ONSET_A_MS2 * d) + + +def junction_is_roundabout(junction: str | None) -> bool: + return (junction or "").strip().lower() in _RB_JUNCTIONS + + +def roundabout_suppressed_for_highway(highway: str | None) -> bool: + """True when the ego match is freeway / trunk, so RB hints must not publish. + + I-74 (highway=motorway, posted 65) latched MAX to 20 mph off untagged + residential loops beside the carriageway. Real town roundabouts are not + matched onto these classes. + """ + return (highway or "").strip().lower() in _RB_SUPPRESS_HIGHWAY + + +def _local_xy(lat: float, lon: float, lat0: float, lon0: float) -> tuple[float, float]: + x = math.radians(lon - lon0) * math.cos(math.radians(lat0)) * EARTH_R + y = math.radians(lat - lat0) * EARTH_R + return x, y + + +def way_radius_m(coords: list[tuple[float, float]] | tuple[tuple[float, float], ...]) -> float | None: + if len(coords) < 3: + return None + lat0 = sum(c[0] for c in coords) / len(coords) + lon0 = sum(c[1] for c in coords) / len(coords) + rs = [math.hypot(*_local_xy(c[0], c[1], lat0, lon0)) for c in coords] + r = sum(rs) / len(rs) + return r if r > 0.5 else None + + +def way_is_closed_loop(coords: list[tuple[float, float]] | tuple[tuple[float, float], ...]) -> bool: + if len(coords) < 4: + return False + gap = math.hypot(*_local_xy(coords[-1][0], coords[-1][1], coords[0][0], coords[0][1])) + return gap <= RB_CLOSED_GAP_M + + +def way_is_roundabout( + coords: list[tuple[float, float]] | tuple[tuple[float, float], ...], + junction: str = "", + highway: str = "", +) -> bool: + """True for OSM circulating rings — not a sharp corner or cross street. + + Tagged `junction=roundabout|circular` is authoritative (multi-way rings). + Published speed-limit packs may omit that column; a compact closed loop + of typical RB radius is the fallback. Signalized intersections are + crossing polylines, not a closed circulating way. + """ + tagged = junction_is_roundabout(junction) + r = way_radius_m(coords) + if tagged: + if r is None: + return True + return r <= (RB_RADIUS_MAX_M * 2.5) + hw = (highway or "").strip().lower() + if hw in _UNTAGGED_SKIP_HIGHWAY: + return False + if not way_is_closed_loop(coords) or r is None: + return False + return RB_RADIUS_MIN_M <= r <= RB_RADIUS_MAX_M + + +def roundabout_target_ms(speed_limit_ms: float = 0.0) -> float: + """Soft circulating v. OSM ring maxspeed when present, else 20 mph.""" + if speed_limit_ms is not None and float(speed_limit_ms) > 0.5: + return max(RB_V_MIN_MS, min(RB_V_MAX_MS, float(speed_limit_ms))) + return RB_V_DEFAULT_MS + + +def roundabout_hint_active(hint: RoundaboutHint | None) -> bool: + return hint is not None and (hint.on_roundabout or hint.approaching) + + +def roundabout_ease_v_ms( + hint: RoundaboutHint | None, + v_ego_ms: float, + current_ms: float = 0.0, + lookahead: int = LOOKAHEAD_NORMAL, +) -> float | None: + """Ring target as soon as the funnel is live. None if no RB. + + Do not interpolative-ease MAX over another 100 m — that left aTarget at + Lookahead comfort (−0.55) after long enabled inside the funnel. `_` args + kept so card / planner call sites stay unchanged. + """ + _ = v_ego_ms, current_ms, lookahead + if not roundabout_hint_active(hint): + return None + target = roundabout_target_ms(hint.speed_limit_ms) + if hint.on_roundabout or float(hint.distance_m) <= 0.0: + return target + # Oct 11: smooth MAX ramp down the 0.7 m/s² profile (no 35->18 step). + return rb_profile_v_ms(hint.distance_m, target) + + +def roundabout_decel_ms2(hint: RoundaboutHint | None, v_ego_ms: float) -> float | None: + """Kinematic −a to hit ring speed by remaining d, or 0 to clamp +a. + + None if no RB hint. While approaching / on-ring, never returns +a. + From ≥40 mph, |a| is at least 1.0 until near ring speed (Willmar 10:11 + / 10:14: −0.55 at 37–45 mph was about half of 37→20 over 80–95 m). + """ + if not roundabout_hint_active(hint): + return None + target = roundabout_target_ms(hint.speed_limit_ms) + v0 = max(float(v_ego_ms), 0.0) + if hint.on_roundabout or float(hint.distance_m) <= 0.0: + d = RB_ON_RING_DECEL_M + else: + d = max(float(hint.distance_m), RB_DECEL_D_MIN_M) + if v0 <= target + RB_NEAR_SPEED_MS: + return 0.0 + if not hint.on_roundabout and float(hint.distance_m) > 0.0: + d = max(d - RB_PROFILE_BUFFER_M, RB_DECEL_D_MIN_M) + a_kin = (target * target - v0 * v0) / (2.0 * d) + a = max(RB_A_MIN_MS2, min(0.0, a_kin)) + # Willmar floor only for a late hint (inside the speed-based onset by + # more than the margin). On a normal early onset the 0.7 profile rules. + late = float(hint.distance_m) < rb_decel_onset_m(v0, target) - RB_ONSET_MARGIN_M + if v0 >= RB_A_FLOOR_V_MS and (hint.on_roundabout or late): + a = min(a, RB_A_FLOOR_MS2) + return max(a, RB_A_MAX_DECEL_MS2) + + +def apply_roundabout_plan( + v_ego_ms: float, + v_cruise_ms: float, + v_hud_ms: float, + output_a_target: float, + hint: RoundaboutHint | None, + lookahead: int = LOOKAHEAD_NORMAL, +) -> tuple[float, float, float, float | None]: + """Cap cruise / HUD to ring speed and min kinematic −a. No-op if no hint. + + Returns (v_cruise, v_hud, a_target, rb_v or None). a_target is ≤ 0 while + the funnel is live (no +a rebound after a lead clears). Long-enable in + the funnel is the same call — full ease on the first frame. + """ + rb_v = roundabout_ease_v_ms(hint, v_ego_ms, v_hud_ms, lookahead) + if rb_v is None: + return float(v_cruise_ms), float(v_hud_ms), float(output_a_target), None + v_cruise_ms = min(float(v_cruise_ms), float(rb_v)) + v_hud_ms = min(float(v_hud_ms), float(rb_v)) + a_rb = roundabout_decel_ms2(hint, v_ego_ms) + if a_rb is not None: + output_a_target = min(float(output_a_target), a_rb) + output_a_target = min(float(output_a_target), 0.0) + return v_cruise_ms, v_hud_ms, float(output_a_target), float(rb_v) + + +# Oct 13 exit restore (Justin): restore only when the RIGHT blinker is on +# while on the ring AND the car is actually leaving it (curvature unwinding +# from the ring's peak). The blinker alone never restores. With no signal, +# the restore waits until the car is fully off the ring (the hint clears). +RB_EXIT_PEAK_MIN_K = 0.02 # 1/m: we have really been circulating (R < 50 m) +RB_EXIT_UNWIND_FRAC = 0.55 # ring-direction curvature below this share of the peak +RB_EXIT_HOLD_S = 0.3 # both conditions this long +RB_EXIT_RESTORE_MPHS = 1.75 # restore rate, 1.5–2 mph/s +RB_EXIT_RESTORE_MS2 = RB_EXIT_RESTORE_MPHS * CV.MPH_TO_MS + + +class RingExitGate: + """True once the driver signals right on the ring and the car is leaving it. + + Latched until the ring hint clears (or a different ring appears). Pure: + card (MAX) and the planner (a clamp) each run one with the same inputs. + """ + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self.released = False + self._way = 0 + self._peak = 0.0 + self._sign = 0.0 + self._both_s = 0.0 + + def update(self, hint: RoundaboutHint | None, right_blinker: bool, curvature: float | None, + dt: float) -> bool: + if hint is None or not (hint.on_roundabout or hint.approaching): + self.reset() + return False + way = int(getattr(hint, "way_id", 0) or 0) + if way and self._way and way != self._way: + self.reset() + if way: + self._way = way + if self.released: + return True + if not hint.on_roundabout: + self._both_s = 0.0 + return False + try: + k = float(curvature) if curvature is not None else 0.0 + except (TypeError, ValueError): + k = 0.0 + if not math.isfinite(k): + k = 0.0 + if abs(k) > self._peak: + self._peak = abs(k) + self._sign = 1.0 if k > 0.0 else -1.0 + unwinding = self._peak >= RB_EXIT_PEAK_MIN_K and k * self._sign < RB_EXIT_UNWIND_FRAC * self._peak + if bool(right_blinker) and unwinding: + self._both_s += max(0.0, float(dt)) + else: + self._both_s = 0.0 + if self._both_s + 1e-9 >= RB_EXIT_HOLD_S: + self.released = True + return self.released + + +def live_map_roundabout_hint(md) -> RoundaboutHint | None: + """Read LiveMapDataNAP RB fields. Missing / old messages → None.""" + if md is None: + return None + try: + on_rb = bool(getattr(md, "onRoundabout", False)) + approaching = bool(getattr(md, "approachingRoundabout", False)) + if not on_rb and not approaching: + return None + return RoundaboutHint( + on_roundabout=on_rb, + approaching=approaching, + distance_m=float(getattr(md, "roundaboutDistance", 0.0) or 0.0), + speed_limit_ms=float(getattr(md, "roundaboutSpeedLimit", 0.0) or 0.0), + way_id=int(getattr(md, "roundaboutWayId", 0) or 0), + ) + except Exception: + return None + + +def _outer_bias_active(*, on_roundabout: bool, approaching: bool, distance_m: float) -> bool: + if on_roundabout: + return True + return bool(approaching) and 0.0 < float(distance_m) <= RB_ENTRY_BIAS_M + + +def roundabout_outer_path_offset_m( + *, + on_roundabout: bool, + approaching: bool = False, + distance_m: float = 0.0, + is_rhd: bool = False, +) -> float: + """Outer-lane path offset in openpilot y (left +). 0 off the ring / far approach. + + RHT / US: outer is right → negative y. RHD: outer is left → positive y. + Magnitude counters an EP1-class ~3 m inside cut and holds the outer half + of the circulating lane. Applied on-ring and in the last 50 m of approach + (not 200 m out on a straight). + """ + if not _outer_bias_active( + on_roundabout=on_roundabout, approaching=approaching, distance_m=distance_m, + ): + return 0.0 + mag = max(RB_OUTER_OFFSET_MIN_M, min(RB_OUTER_OFFSET_MAX_M, RB_OUTER_OFFSET_M)) + return mag if is_rhd else -mag + + +def roundabout_outer_curvature_bias(offset_m: float, lookahead_m: float = RB_PATH_LOOKAHEAD_M) -> float: + """Curvature add-on that tracks a parallel path offset_m to the left. + + Positive offset (left) → positive curvature. 3.2 m right ≈ −0.020 /m at + the 18 m preview — enough to walk a 3 m inside model path back to the + OSM ring / outer half of the lane. + """ + if abs(float(offset_m)) < 1e-6: + return 0.0 + L = max(8.0, float(lookahead_m)) + return 2.0 * float(offset_m) / (L * L) + + +def roundabout_lateral_curvature_bias(hint: RoundaboutHint | None, *, is_rhd: bool = False, + turn_geometry_active: bool = False) -> float: + """Curvature add-on controlsd applies to the model / maneuver curvature. + + Turn geometry correction ON (NAPLatTurnGeom, Pre-AP default): 0. The + 3.2 m outer bias was tuned against the EP1 inside cut, which included + early turn-in / corner clipping that the correction now handles in + modeld; keeping both would double-compensate (run wide on entry). + Correction OFF: legacy #223 outer bias, unchanged from 1119c0f. + Roundabout detection and speed ease are not affected either way. + """ + if turn_geometry_active: + return 0.0 + return roundabout_outer_curvature_bias( + roundabout_outer_path_offset_m( + on_roundabout=bool(hint.on_roundabout) if hint is not None else False, + approaching=bool(hint.approaching) if hint is not None else False, + distance_m=float(hint.distance_m) if hint is not None else 0.0, + is_rhd=is_rhd, + ), + ) diff --git a/selfdrive/mapd/roundabout_map.py b/selfdrive/mapd/roundabout_map.py new file mode 100644 index 00000000000000..33127fcee435cc --- /dev/null +++ b/selfdrive/mapd/roundabout_map.py @@ -0,0 +1,423 @@ +"""OSM roundabout rings + approach roads for the NAP map pack, and ring geometry. + +The US speed-limit pack only kept ways with a numeric maxspeed. Most +circulating rings (and many approach roads) carry no maxspeed, so the +roundabout funnel never fired on them (Soco Rd / Dellwood / Jonathan Creek, +way 1514082747). Rings and the roads that touch them are stored in a +separate `rb_ways` table so the speed-limit `ways` table, its matching, and +the MN statutory fills are untouched. + +Ring geometry (center, radius, circulation sense, lanes) is fitted from all +connected ring ways and handed to controlsd (Roundabout Steering Assist) +through the NAPRoundaboutRing param. No cereal schema change. + +OpenStreetMap data is ODbL: © OpenStreetMap contributors. +https://www.openstreetmap.org/copyright +""" +from __future__ import annotations + +import json +import math +from dataclasses import dataclass, field + +from openpilot.selfdrive.mapd.speed_limit import parse_maxspeed + +EARTH_R = 6371000.0 +RB_JUNCTIONS = frozenset({"roundabout", "circular"}) +ROLE_RING = "ring" +ROLE_APPROACH = "approach" +# Keep this much of each approach road, measured from the node it shares with the ring. +APPROACH_KEEP_M = 250.0 +# Ring ways whose endpoints are within this distance chain into one ring. +RING_JOIN_M = 3.0 +# Rings outside this radius band are not fitted (bad data / huge circles). +RING_FIT_MIN_R_M = 5.0 +RING_FIT_MAX_R_M = 90.0 +LANE_WIDTH_M = 3.5 +# Comfort lateral acceleration used for the ring speed target. +RB_COMFORT_LAT_ACCEL = 2.5 +RING_JSON_VERSION = 1 +# Approach polylines carried in the ring param (trimmed, local xy). +RING_JSON_APPROACH_M = 120.0 +# highway=mini_roundabout is an OSM node, not a way: stored as a small synthetic ring. +MINI_RB_RADIUS_M = 7.0 +MINI_RB_POINTS = 16 + + +def is_ring_tags(tags: dict) -> bool: + return bool(tags.get("highway")) and str(tags.get("junction") or "").strip().lower() in RB_JUNCTIONS + + +def _lanes(tags: dict) -> int: + try: + return max(0, int(str(tags.get("lanes") or "0").split(";")[0].strip())) + except ValueError: + return 0 + + +def local_xy(lat: float, lon: float, lat0: float, lon0: float) -> tuple[float, float]: + """East, north meters from (lat0, lon0).""" + x = math.radians(lon - lon0) * math.cos(math.radians(lat0)) * EARTH_R + y = math.radians(lat - lat0) * EARTH_R + return x, y + + +def latlon_from_xy(x: float, y: float, lat0: float, lon0: float) -> tuple[float, float]: + lat = lat0 + math.degrees(y / EARTH_R) + lon = lon0 + math.degrees(x / (EARTH_R * math.cos(math.radians(lat0)))) + return lat, lon + + +def _dist_m(a: tuple[float, float], b: tuple[float, float]) -> float: + return math.hypot(*local_xy(b[0], b[1], a[0], a[1])) + + +def _trim_from(coords: list[tuple[float, float]], start_at_end: bool, keep_m: float) -> list[tuple[float, float]]: + """Keep keep_m of the polyline from the start (or the end), in original order.""" + seq = list(reversed(coords)) if start_at_end else list(coords) + out = [seq[0]] + run = 0.0 + for p in seq[1:]: + d = _dist_m(out[-1], p) + if run + d >= keep_m: + f = (keep_m - run) / d if d > 0 else 0.0 + out.append((out[-1][0] + f * (p[0] - out[-1][0]), out[-1][1] + f * (p[1] - out[-1][1]))) + break + out.append(p) + run += d + return list(reversed(out)) if start_at_end else out + + +def roundabout_rows(ways: list[dict], keep_m: float = APPROACH_KEEP_M) -> list[dict]: + """Ring ways and approach roads from generic OSM ways. + + Each input dict: way_id, tags, node_ids (list[int]), coords (list[(lat, lon)]), + same length for node_ids and coords. Output rows for OsmSpeedLimitDB.insert_rb_way. + An approach is any highway way (not a ring) that shares a node with a ring; + only the part within keep_m of the shared node is kept. + """ + ring_nodes: set[int] = set() + out: list[dict] = [] + for w in ways: + tags = w.get("tags") or {} + if not is_ring_tags(tags): + continue + coords = w.get("coords") or [] + if len(coords) < 2: + continue + ring_nodes.update(int(n) for n in (w.get("node_ids") or [])) + out.append(_row(w, ROLE_RING, coords)) + if not ring_nodes: + return out + for w in ways: + tags = w.get("tags") or {} + if not tags.get("highway") or is_ring_tags(tags): + continue + nodes = [int(n) for n in (w.get("node_ids") or [])] + coords = w.get("coords") or [] + if len(coords) < 2 or len(nodes) != len(coords): + continue + hits = [i for i, n in enumerate(nodes) if n in ring_nodes] + if not hits: + continue + # Split at each ring-touching node; keep both sides near it. + pieces: list[list[tuple[float, float]]] = [] + for i in hits: + if i > 0: + pieces.append(_trim_from(coords[:i + 1], True, keep_m)) + if i < len(coords) - 1: + pieces.append(_trim_from(coords[i:], False, keep_m)) + for k, piece in enumerate(pieces): + if len(piece) >= 2: + row = _row(w, ROLE_APPROACH, piece) + row["piece"] = k + out.append(row) + return out + + +def _row(w: dict, role: str, coords: list[tuple[float, float]]) -> dict: + tags = w.get("tags") or {} + ms = parse_maxspeed(tags.get("maxspeed")) or parse_maxspeed(tags.get("maxspeed:forward")) or 0.0 + if role == ROLE_RING: + # Advisory ring speed (yellow plate) wins when it is lower than the posted limit. + adv = parse_maxspeed(tags.get("maxspeed:advisory")) or 0.0 + if adv > 0.5: + ms = min(ms, adv) if ms > 0.5 else adv + return { + "way_id": int(w["way_id"]), + "role": role, + "name": tags.get("name") or tags.get("ref") or "", + "highway": tags.get("highway") or "", + "junction": tags.get("junction") or "", + "oneway": 1 if str(tags.get("oneway") or "").lower() in ("yes", "1", "true") or is_ring_tags(tags) else 0, + "lanes": _lanes(tags), + "maxspeed_ms": float(ms), + "coords": [(float(a), float(b)) for a, b in coords], + } + + +def ways_from_overpass_elements(payload: dict) -> list[dict]: + """Overpass `out geom` ways (with `nodes` ids) → generic ways for roundabout_rows.""" + out = [] + for el in payload.get("elements", []): + if el.get("type") != "way": + continue + geom = el.get("geometry") or [] + nodes = el.get("nodes") or [] + coords = [(float(p["lat"]), float(p["lon"])) for p in geom if p and "lat" in p and "lon" in p] + if len(coords) != len(geom) or len(coords) < 2: + continue + out.append({"way_id": int(el["id"]), "tags": el.get("tags") or {}, "node_ids": list(nodes), "coords": coords}) + return out + + +def mini_roundabout_way(node_id: int, lat: float, lon: float, tags: dict | None = None, + radius_m: float = MINI_RB_RADIUS_M) -> dict: + """Synthetic closed ring way for an OSM highway=mini_roundabout node. + + way_id is the negated node id (OSM way ids are positive). node_ids are the + real node id at every vertex so roads through the node become approaches. + """ + tags = dict(tags or {}) + ring_tags = {"highway": "mini_roundabout", "junction": "roundabout", "oneway": "yes"} + for k in ("name", "maxspeed", "maxspeed:advisory"): + if tags.get(k): + ring_tags[k] = tags[k] + coords = [] + for i in range(MINI_RB_POINTS + 1): + a = 2.0 * math.pi * i / MINI_RB_POINTS + dn, de = radius_m * math.sin(a), radius_m * math.cos(a) + coords.append((lat + math.degrees(dn / EARTH_R), lon + math.degrees(de / (EARTH_R * math.cos(math.radians(lat)))))) + return {"way_id": -int(node_id), "tags": ring_tags, "node_ids": [int(node_id)] * len(coords), "coords": coords} + + +def rb_rows_from_overpass(payload: dict, keep_m: float = APPROACH_KEEP_M) -> list[dict]: + return roundabout_rows(ways_from_overpass_elements(payload), keep_m=keep_m) + + +# --------------------------------------------------------------------------- +# Ring geometry +# --------------------------------------------------------------------------- + +@dataclass +class RingGeometry: + lat: float + lon: float + radius_m: float + rms_m: float + ccw: bool + lanes: int + coverage_deg: float + way_ids: list[int] + tagged: bool = True + maxspeed_ms: float = 0.0 + approaches: list[list[tuple[float, float]]] = field(default_factory=list) # local xy (m) from center + + @property + def half_width_m(self) -> float: + lanes = self.lanes if self.lanes > 0 else 2 + return 0.5 * lanes * LANE_WIDTH_M + + def to_json(self) -> dict: + return { + "v": RING_JSON_VERSION, + "lat": round(self.lat, 7), "lon": round(self.lon, 7), + "r": round(self.radius_m, 2), "rms": round(self.rms_m, 2), + "ccw": bool(self.ccw), "lanes": int(self.lanes), + "cov": round(self.coverage_deg, 1), "ids": [int(i) for i in self.way_ids], + "tagged": bool(self.tagged), "maxspeed": round(self.maxspeed_ms, 2), + "app": [[[round(x, 1), round(y, 1)] for x, y in a] for a in self.approaches], + } + + @staticmethod + def from_json(d) -> RingGeometry | None: + try: + if isinstance(d, (bytes, str)): + d = json.loads(d) + if not isinstance(d, dict) or int(d.get("v", 0)) != RING_JSON_VERSION: + return None + return RingGeometry( + lat=float(d["lat"]), lon=float(d["lon"]), radius_m=float(d["r"]), rms_m=float(d["rms"]), + ccw=bool(d["ccw"]), lanes=int(d.get("lanes", 0)), coverage_deg=float(d.get("cov", 0.0)), + way_ids=[int(i) for i in d.get("ids", [])], tagged=bool(d.get("tagged", True)), + maxspeed_ms=float(d.get("maxspeed", 0.0)), + approaches=[[(float(p[0]), float(p[1])) for p in a] for a in d.get("app", [])], + ) + except (KeyError, TypeError, ValueError, json.JSONDecodeError): + return None + + +def _densify(pts: list[tuple[float, float]], step: float = 2.0) -> list[tuple[float, float]]: + out = [pts[0]] + for a, b in zip(pts, pts[1:], strict=False): + d = math.hypot(b[0] - a[0], b[1] - a[1]) + n = max(1, int(math.ceil(d / step))) + for k in range(1, n + 1): + out.append((a[0] + (b[0] - a[0]) * k / n, a[1] + (b[1] - a[1]) * k / n)) + return out + + +def fit_circle(pts: list[tuple[float, float]]) -> tuple[float, float, float, float] | None: + """Kasa least-squares circle. Returns (cx, cy, r, rms) or None.""" + n = len(pts) + if n < 3: + return None + mx = sum(p[0] for p in pts) / n + my = sum(p[1] for p in pts) / n + u = [p[0] - mx for p in pts] + v = [p[1] - my for p in pts] + suu = sum(a * a for a in u) + svv = sum(b * b for b in v) + suv = sum(a * b for a, b in zip(u, v, strict=True)) + suuu = sum(a ** 3 for a in u) + svvv = sum(b ** 3 for b in v) + suvv = sum(a * b * b for a, b in zip(u, v, strict=True)) + svuu = sum(b * a * a for a, b in zip(u, v, strict=True)) + det = suu * svv - suv * suv + if abs(det) < 1e-9: + return None + rhs1 = 0.5 * (suuu + suvv) + rhs2 = 0.5 * (svvv + svuu) + uc = (rhs1 * svv - rhs2 * suv) / det + vc = (suu * rhs2 - suv * rhs1) / det + cx, cy = uc + mx, vc + my + rs = [math.hypot(p[0] - cx, p[1] - cy) for p in pts] + r = sum(rs) / n + rms = math.sqrt(sum((x - r) ** 2 for x in rs) / n) + return cx, cy, r, rms + + +def _connected_rings(rings: list[dict], seed_id: int | None) -> list[dict]: + if not rings: + return [] + seed = next((w for w in rings if int(w["way_id"]) == int(seed_id or -1)), None) + if seed is None: + return rings + comp = [seed] + pending = [w for w in rings if w is not seed] + grew = True + while grew and pending: + grew = False + ends = [p for w in comp for p in (w["coords"][0], w["coords"][-1])] + keep = [] + for w in pending: + we = (w["coords"][0], w["coords"][-1]) + if any(_dist_m(a, b) <= RING_JOIN_M for a in we for b in ends): + comp.append(w) + grew = True + else: + keep.append(w) + pending = keep + return comp + + +def ring_geometry(rings: list[dict], approaches: list[dict] | None = None, + seed_id: int | None = None) -> RingGeometry | None: + """Fit one ring from ring-way rows (role ring or junction-tagged speed ways). + + rows: dicts with way_id, coords [(lat, lon)], lanes, maxspeed_ms, junction. + """ + comp = _connected_rings(rings, seed_id) + if not comp: + return None + lat0 = sum(c[0] for w in comp for c in w["coords"]) / sum(len(w["coords"]) for w in comp) + lon0 = sum(c[1] for w in comp for c in w["coords"]) / sum(len(w["coords"]) for w in comp) + segs = [[local_xy(c[0], c[1], lat0, lon0) for c in w["coords"]] for w in comp] + pts = [p for s in segs for p in _densify(s)] + fit = fit_circle(pts) + if fit is None: + return None + cx, cy, r, rms = fit + if not (RING_FIT_MIN_R_M <= r <= RING_FIT_MAX_R_M): + return None + # Circulation: sign of sum (p - c) x dp over the ordered ring segments (east/north frame). + cross = 0.0 + for s in segs: + for a, b in zip(s, s[1:], strict=False): + cross += (a[0] - cx) * (b[1] - a[1]) - (a[1] - cy) * (b[0] - a[0]) + angs = sorted(math.degrees(math.atan2(p[1] - cy, p[0] - cx)) % 360.0 for p in pts) + gaps = [b - a for a, b in zip(angs, angs[1:], strict=False)] + [angs[0] + 360.0 - angs[-1]] + coverage = 360.0 - max(gaps) + clat, clon = latlon_from_xy(cx, cy, lat0, lon0) + lanes = max((int(w.get("lanes") or 0) for w in comp), default=0) + speeds = [float(w.get("maxspeed_ms") or 0.0) for w in comp if float(w.get("maxspeed_ms") or 0.0) > 0.5] + tagged = any(str(w.get("junction") or "").strip().lower() in RB_JUNCTIONS for w in comp) + app_xy: list[list[tuple[float, float]]] = [] + for a in approaches or []: + xy = [local_xy(c[0], c[1], clat, clon) for c in a["coords"]] + # Only approaches that actually touch this ring (an end within the ring band). + if not any(abs(math.hypot(*p) - r) <= 6.0 for p in (xy[0], xy[-1])): + continue + inbound = abs(math.hypot(*xy[-1]) - r) <= 6.0 and abs(math.hypot(*xy[0]) - r) > 6.0 + if inbound: + xy = list(reversed(xy)) # trim from the ring outward + trimmed = [xy[0]] + run = 0.0 + for p in xy[1:]: + run += math.hypot(p[0] - trimmed[-1][0], p[1] - trimmed[-1][1]) + trimmed.append(p) + if run >= RING_JSON_APPROACH_M: + break + # Stored in the direction of travel (the guide's map match needs it); two-way roads both ways. + fwd = list(reversed(trimmed)) if inbound else trimmed + app_xy.append(fwd) + if not int(a.get("oneway") or 0): + app_xy.append(list(reversed(fwd))) + return RingGeometry( + lat=clat, lon=clon, radius_m=r, rms_m=rms, ccw=cross > 0.0, lanes=lanes, + coverage_deg=coverage, way_ids=sorted(int(w["way_id"]) for w in comp), tagged=tagged, + maxspeed_ms=min(speeds) if speeds else 0.0, approaches=app_xy, + ) + + +def roundabout_comfort_speed_ms(radius_m: float, lanes: int = 0, maxspeed_ms: float = 0.0, + lat_accel: float = RB_COMFORT_LAT_ACCEL) -> float: + """Ring speed for ≤ lat_accel on the inner lane. OSM maxspeed still caps it. + + Inner lane center ≈ R − (lanes − 1)·w/2 (R is the carriageway centerline). + Returned value is published as liveMapDataNAP.roundaboutSpeedLimit; the + planner clamps it to 15–20 mph (roundabout_target_ms). + """ + lanes_n = lanes if lanes > 0 else 2 + r_inner = max(4.0, float(radius_m) - 0.5 * (lanes_n - 1) * LANE_WIDTH_M) + v = math.sqrt(lat_accel * r_inner) + if maxspeed_ms and maxspeed_ms > 0.5: + v = min(v, float(maxspeed_ms)) + return v + + +PARAM_RING = "NAPRoundaboutRing" +RING_RETRY_S = 5.0 + + +class RingCache: + """mapd side: fit the hinted ring once, reuse while the hint stays on it. + + publish() is called with a JSON-able dict only when the ring changes, so the + NAPRoundaboutRing param is written a few times per roundabout at most. + """ + + def __init__(self) -> None: + self.geom: RingGeometry | None = None + self._failed_id = 0 + self._failed_t = -1e9 + + def update(self, db, way_id: int, lat: float, lon: float, now: float, publish=None) -> RingGeometry | None: + way_id = int(way_id or 0) + if way_id == 0: + return None + if self.geom is not None and way_id in self.geom.way_ids: + return self.geom + if way_id == self._failed_id and (now - self._failed_t) < RING_RETRY_S: + return None + try: + geom = db.ring_geometry(way_id, lat, lon) + except Exception: + geom = None + if geom is None: + self._failed_id, self._failed_t = way_id, now + return None + self.geom = geom + if publish is not None: + publish(geom.to_json()) + return geom diff --git a/selfdrive/mapd/roundabout_status.py b/selfdrive/mapd/roundabout_status.py new file mode 100644 index 00000000000000..ded23bdcac833c --- /dev/null +++ b/selfdrive/mapd/roundabout_status.py @@ -0,0 +1,89 @@ +"""Roundabout map status: message validity, ring-data check, Map Speed Limit summary. + +Kept apart from roundabout_map.py (pack rows / ring fit) so mapd, the settings pages and +tests share one small module. No cereal change. +""" +from __future__ import annotations + +import os +import sqlite3 + +from openpilot.selfdrive.mapd.roundabout_map import ROLE_RING + +RING_MISSING_TEXT = "Missing - run Refresh maps" + + +def map_msg_valid(*, gps_ok: bool, db_loaded: bool, matched: bool, ring_hint: bool) -> bool: + """liveMapDataNAP.valid. A ring hint keeps the message valid without a speed match. + + A ring often has no maxspeed, so no speed-limit match. Without this the message + is invalid there and readers that gate on valid never see the ring hint. Every + speed-limit reader still gates on speedLimitValid, so a ring-only message + publishes no limit. Non-ring frames are unchanged. + """ + return bool(gps_ok and db_loaded and (matched or ring_hint)) + + +def pack_ring_count(path: str | None) -> int | None: + """Ring rows in a map pack. None if there is no readable pack; 0 if it has no ring data. + + Read-only and never raises: a v3 pack (no rb_ways table) and a v4 pack whose + Refresh never stored a ring both report 0. + """ + if not path or not os.path.isfile(path): + return None + try: + con = sqlite3.connect(f"file:{path}?mode=ro", uri=True) + try: + row = con.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='rb_ways'").fetchone() + if row is None: + return 0 + return int(con.execute("SELECT COUNT(*) FROM rb_ways WHERE role = ?", (ROLE_RING,)).fetchone()[0]) + finally: + con.close() + except (sqlite3.Error, OSError, ValueError): + return None + + +def ring_data_summary(count: int | None) -> str: + if count is None: + return "Not installed" + if count <= 0: + return RING_MISSING_TEXT + return f"{count:,} rings" + + +def installed_ring_summary(path: str | None = None) -> str: + """Roundabout ring rows in the installed pack. Says to refresh when there are none.""" + from openpilot.selfdrive.mapd.db_paths import default_db_path + return ring_data_summary(pack_ring_count(path or default_db_path())) + + +class RingDataWatch: + """One log line per pack state: the pack has (or lacks) ring rows. + + A pack without ring rows never produces a roundabout hint, so the slow-down + silently never fires. check() returns a message the first time a pack file + (path, mtime, size) is seen, and None until it changes. + """ + + def __init__(self) -> None: + self._key: tuple | None = None + + def check(self, path: str | None) -> tuple[str, str] | None: + """(level, message) once per pack state, else None.""" + try: + st = os.stat(path) if path else None + except OSError: + st = None + key = (path, st.st_mtime_ns, st.st_size) if st is not None else (path, None, None) + if key == self._key: + return None + self._key = key + count = pack_ring_count(path) + if count is None: + return None + if count <= 0: + return ("warning", f"mapd: {path} has no roundabout ring rows; the roundabout slow-down cannot fire" + + " (Settings \u2192 NAP \u2192 Map Speed Limit \u2192 Refresh maps)") + return ("info", f"mapd: {path} has {count} roundabout ring rows") diff --git a/selfdrive/mapd/speed_limit.py b/selfdrive/mapd/speed_limit.py new file mode 100644 index 00000000000000..36f9f15ba63814 --- /dev/null +++ b/selfdrive/mapd/speed_limit.py @@ -0,0 +1,41 @@ +"""Parse OpenStreetMap maxspeed tags into m/s. + +OSM wiki: a unitless number is km/h. Explicit units (mph, knots) are honored. +Non-numeric values (signals, national, none) return None. +""" +from __future__ import annotations + +import re + +from openpilot.common.constants import CV + +_NUMERIC = re.compile( + r"^\s*(?P\d+(?:\.\d+)?)\s*(?Pmph|knots|km/h|kmh|kph)?\s*$", + re.IGNORECASE, +) + + +def parse_maxspeed(tag: str | None) -> float | None: + """Return speed limit in m/s, or None if the tag is missing/unusable.""" + if not tag: + return None + text = str(tag).strip() + if not text or ":" in text: + # Implicit country codes like "US:urban" / "sign" / "national" are not numeric limits. + return None + lowered = text.lower() + if lowered in ("none", "signals", "variable", "walk", "unposted"): + return None + + m = _NUMERIC.match(text) + if m is None: + return None + val = float(m.group("val")) + if val <= 0 or val > 200: + return None + unit = (m.group("unit") or "km/h").lower() + if unit == "mph": + return val * CV.MPH_TO_MS + if unit == "knots": + return val * CV.KNOTS_TO_MS + return val * CV.KPH_TO_MS diff --git a/selfdrive/mapd/speed_overrides.py b/selfdrive/mapd/speed_overrides.py new file mode 100644 index 00000000000000..5af3a53502d294 --- /dev/null +++ b/selfdrive/mapd/speed_overrides.py @@ -0,0 +1,155 @@ +"""Local speed-limit overrides from driver-confirmed camera signs. + +A HUD YES tap on the speed-sign popup writes NAPSpeedSignConfirmed +({mph, seq, lat, lon, bearing}). mapd consumes it once per seq, keys it to +the OSM way it is currently matched to (same db.lookup way / heading logic +that produces liveMapDataNAP.speedLimit) plus the travel heading, and stores +it here. From then on, whenever mapd matches that way in that direction it +publishes the override as speedLimit (source "sign"), so the existing +speed-limit sign and the Map Speed Limit cruise path (MAX = limit + offset) +use it on this and future drives. The opposite direction keeps OSM. +A newer YES on the same way + direction replaces the old value. Nothing is +uploaded (OSM edits are future work). NO taps never reach this file. +""" +from __future__ import annotations + +import json +import os +import time + +PARAM = "NAPSpeedSignConfirmed" +FILENAME = "map_speed_overrides.json" +MPH_TO_MS = 0.44704 +HEADING_MATCH_DEG = 60.0 +PENDING_MAX_S = 20.0 # a YES with no OSM match yet waits this long for one +MAX_ENTRIES = 5000 + + +def overrides_path() -> str: + env = os.environ.get("NAP_MAP_SPEED_OVERRIDES") + if env: + return env + base = "/data/media/0/nap" if os.path.isdir("/data/media/0") else os.path.join( + os.path.expanduser("~"), ".comma", "media", "0", "nap") + return os.path.join(base, FILENAME) + + +def heading_delta(a: float, b: float) -> float: + d = abs(float(a) - float(b)) % 360.0 + return 360.0 - d if d > 180.0 else d + + +def parse_confirmed(raw) -> dict | None: + if raw is None: + return None + try: + d = json.loads(raw) if isinstance(raw, (str, bytes, bytearray)) else dict(raw) + mph = int(d["mph"]) + seq = float(d["seq"]) + except Exception: + return None + if not (5 <= mph <= 85) or mph % 5: + return None + out = {"mph": mph, "seq": seq} + for k in ("lat", "lon", "bearing"): + try: + if d.get(k) is not None: + out[k] = float(d[k]) + except (TypeError, ValueError): + pass + return out + + +class SpeedOverrides: + def __init__(self, path: str | None = None) -> None: + self.path = path or overrides_path() + self.entries: list[dict] = [] + self._mtime = None + self.last_seq: float | None = None + self.pending: dict | None = None + self.pending_t = 0.0 + self.load() + + def load(self) -> None: + try: + m = os.path.getmtime(self.path) + if m == self._mtime: + return + with open(self.path) as f: + data = json.load(f) + self.entries = [e for e in data.get("overrides", []) if "way_id" in e and "mph" in e and "heading" in e] + self._mtime = m + except (OSError, ValueError): + if not os.path.exists(self.path): + self.entries = [] + self._mtime = None + + def save(self) -> None: + os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True) + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump({"version": 1, "overrides": self.entries[-MAX_ENTRIES:]}, f, separators=(",", ":")) + os.replace(tmp, self.path) + self._mtime = os.path.getmtime(self.path) + + def find(self, way_id: int, bearing: float | None) -> dict | None: + if bearing is None: + return None + best = None + for e in self.entries: + if int(e["way_id"]) == int(way_id) and heading_delta(e["heading"], bearing) <= HEADING_MATCH_DEG: + best = e # newest wins (appended last) + return best + + def limit_ms(self, way_id: int, bearing: float | None) -> float | None: + e = self.find(way_id, bearing) + return None if e is None else int(e["mph"]) * MPH_TO_MS + + def add(self, way_id: int, heading: float, conf: dict, road: str = "", now: float | None = None) -> dict: + now = time.time() if now is None else now # noqa: TID251 wall clock in the stored row + self.entries = [e for e in self.entries + if not (int(e["way_id"]) == int(way_id) and heading_delta(e["heading"], heading) <= HEADING_MATCH_DEG)] + e = {"way_id": int(way_id), "heading": round(float(heading), 1), "mph": int(conf["mph"]), + "lat": conf.get("lat"), "lon": conf.get("lon"), "road": road, "t": round(now, 1), "source": "sign_yes"} + self.entries.append(e) + self.save() + return e + + def consume(self, raw_param, match, bearing: float | None, mono_now: float) -> dict | None: + """Turn a new YES (by seq) into an override on the current matched way. + + Returns the stored entry when one was written this call. + """ + conf = parse_confirmed(raw_param) + if conf is not None and conf["seq"] != self.last_seq: + self.last_seq = conf["seq"] + self.pending, self.pending_t = conf, mono_now + if self.pending is None: + return None + if mono_now - self.pending_t > PENDING_MAX_S: + self.pending = None + return None + hdg = bearing if bearing is not None else self.pending.get("bearing") + if match is None or hdg is None: + return None + e = self.add(int(match.way_id), float(hdg), self.pending, road=str(getattr(match, "road_name", "") or "")) + self.pending = None + return e + + +def request_override(mph: int, rec: dict | None, seq: float, params=None) -> bool: + """HUD YES: hand the confirmed mph (+ where it was read) to mapd.""" + payload: dict = {"mph": int(mph), "seq": float(seq)} + for k in ("lat", "lon", "bearing"): + if (rec or {}).get(k) is not None: + payload[k] = (rec or {})[k] + if parse_confirmed(payload) is None: + return False + try: + if params is None: + from openpilot.common.params import Params + params = Params() + params.put(PARAM, payload) + return True + except Exception: + return False diff --git a/selfdrive/mapd/tests/data/rb_watertown_oct11.json b/selfdrive/mapd/tests/data/rb_watertown_oct11.json new file mode 100644 index 00000000000000..53d186697c09ab --- /dev/null +++ b/selfdrive/mapd/tests/data/rb_watertown_oct11.json @@ -0,0 +1,380 @@ +[ +{ +"t": "17:02:30.55", +"v": 10.414, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:02:31.55", +"v": 10.523, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:02:32.55", +"v": 10.403, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:02:33.55", +"v": 10.486, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:02:34.55", +"v": 10.528, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:02:35.55", +"v": 10.982, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:02:36.55", +"v": 11.428, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:02:37.55", +"v": 11.867, +"max_kph": 56.7, +"appr": true, +"on": false, +"d": 133.1, +"rb": 7.299 +}, +{ +"t": "17:02:38.55", +"v": 11.916, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 121.5, +"rb": 7.299 +}, +{ +"t": "17:02:39.55", +"v": 11.305, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 110.0, +"rb": 7.299 +}, +{ +"t": "17:02:40.55", +"v": 10.332, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 99.1, +"rb": 7.299 +}, +{ +"t": "17:02:41.55", +"v": 9.32, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 88.3, +"rb": 7.299 +}, +{ +"t": "17:02:42.55", +"v": 8.726, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 78.5, +"rb": 7.299 +}, +{ +"t": "17:02:43.55", +"v": 8.336, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 69.2, +"rb": 7.299 +}, +{ +"t": "17:02:44.55", +"v": 8.227, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 60.2, +"rb": 7.299 +}, +{ +"t": "17:02:45.55", +"v": 8.151, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 51.6, +"rb": 7.299 +}, +{ +"t": "17:02:46.55", +"v": 8.126, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 43.2, +"rb": 7.299 +}, +{ +"t": "17:02:47.55", +"v": 8.084, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 34.3, +"rb": 7.299 +}, +{ +"t": "17:02:48.55", +"v": 8.081, +"max_kph": 29.0, +"appr": true, +"on": false, +"d": 25.6, +"rb": 7.299 +}, +{ +"t": "17:02:49.55", +"v": 8.153, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:50.55", +"v": 8.158, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:51.55", +"v": 8.105, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:52.55", +"v": 8.162, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:53.55", +"v": 8.017, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:54.55", +"v": 7.763, +"max_kph": 24.9, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:55.55", +"v": 7.536, +"max_kph": 24.9, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:56.55", +"v": 7.366, +"max_kph": 25.2, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:57.55", +"v": 7.145, +"max_kph": 25.3, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:58.55", +"v": 7.118, +"max_kph": 26.1, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:02:59.55", +"v": 7.136, +"max_kph": 27.1, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:03:00.55", +"v": 7.184, +"max_kph": 27.6, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:03:01.55", +"v": 7.19, +"max_kph": 28.5, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:03:02.55", +"v": 7.275, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:03:03.55", +"v": 7.314, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:03:04.55", +"v": 7.384, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:03:05.55", +"v": 8.673, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:03:06.55", +"v": 9.94, +"max_kph": 29.0, +"appr": false, +"on": true, +"d": 0.0, +"rb": 7.299 +}, +{ +"t": "17:03:07.55", +"v": 10.666, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:03:08.55", +"v": 10.966, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:03:09.55", +"v": 11.25, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:03:10.55", +"v": 11.511, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +}, +{ +"t": "17:03:11.55", +"v": 11.844, +"max_kph": 56.7, +"appr": false, +"on": false, +"d": 0.0, +"rb": 0.0 +} +] \ No newline at end of file diff --git a/selfdrive/mapd/tests/data/soco_roundabout_overpass.json b/selfdrive/mapd/tests/data/soco_roundabout_overpass.json new file mode 100644 index 00000000000000..d09c3dbe1885cf --- /dev/null +++ b/selfdrive/mapd/tests/data/soco_roundabout_overpass.json @@ -0,0 +1 @@ +{"attribution":"\u00a9 OpenStreetMap contributors, ODbL 1.0 (https://www.openstreetmap.org/copyright). Overpass extract 2026-09-28: Soco Rd / Dellwood Rd / Jonathan Creek Rd roundabout (Maggie Valley NC), ring + approach ways.","version":0.6,"generator":"Overpass API 0.7.62.4 2390de5a","elements":[{"type":"way","id":16603594,"nodes":[13832165000,4161265803,13832173146,4161265809],"geometry":[{"lat":35.522257,"lon":-83.0280324},{"lat":35.5223736,"lon":-83.0280978},{"lat":35.5225286,"lon":-83.0281965},{"lat":35.5227488,"lon":-83.0282875}],"tags":{"highway":"primary","lanes":"1","name":"Jonathan Creek Road","oneway":"yes","tiger:cfcc":"A21","tiger:county":"Haywood, NC","tiger:name_base":"Jonathan Creek","tiger:name_base_1":"United States Highway 276","tiger:name_type":"Rd","tiger:reviewed":"aerial"}},{"type":"way","id":415036814,"nodes":[3056197162,171449669,4161265818,171449667,4161265815,171449664,4161265813,171449662,171449661,171386214,171286230,7871523103,7871523105,4161265806,13726096288,171327723],"geometry":[{"lat":35.5265355,"lon":-83.0290528},{"lat":35.5259981,"lon":-83.0292063},{"lat":35.5257885,"lon":-83.0292575},{"lat":35.5254817,"lon":-83.0293063},{"lat":35.5252406,"lon":-83.0293152},{"lat":35.525014,"lon":-83.029307},{"lat":35.5247909,"lon":-83.0292776},{"lat":35.5245502,"lon":-83.0292219},{"lat":35.5240015,"lon":-83.0290324},{"lat":35.5234509,"lon":-83.0288186},{"lat":35.5227604,"lon":-83.0285541},{"lat":35.5227002,"lon":-83.0285217},{"lat":35.5226258,"lon":-83.0284911},{"lat":35.5224911,"lon":-83.0284408},{"lat":35.5223738,"lon":-83.0283948},{"lat":35.5222077,"lon":-83.0283305}],"tags":{"construction":"primary","highway":"construction","lanes":"2","name":"Jonathan Creek Road","oneway":"yes","ref":"US 276","tiger:cfcc":"A21","tiger:county":"Haywood, NC","tiger:name_base":"Jonathan Creek","tiger:name_base_1":"United States Highway 276","tiger:name_type":"Rd","tiger:reviewed":"aerial","tiger:zip_right":"28785"}},{"type":"way","id":1514082743,"nodes":[13832173101,13832173102,7871523111,13832173103,13832173104,13832173105,13832173106,13832173107,13832173108,13832173136,13832173109],"geometry":[{"lat":35.5220798,"lon":-83.0261306},{"lat":35.5221073,"lon":-83.0262041},{"lat":35.522109,"lon":-83.0262494},{"lat":35.5221225,"lon":-83.0266105},{"lat":35.5221392,"lon":-83.0268715},{"lat":35.5221415,"lon":-83.0270223},{"lat":35.5221357,"lon":-83.0273057},{"lat":35.5221159,"lon":-83.0275363},{"lat":35.5221095,"lon":-83.0276641},{"lat":35.5221512,"lon":-83.0278201},{"lat":35.5222184,"lon":-83.0279682}],"tags":{"highway":"primary","name":"Dellwood Road","oneway":"yes","ref":"US 19;US 276"}},{"type":"way","id":1514082744,"nodes":[13832173114,13832173113,13832173112,13832173111,171262833,13832173110,13832173101],"geometry":[{"lat":35.5219294,"lon":-83.0279907},{"lat":35.5219681,"lon":-83.0276521},{"lat":35.522014,"lon":-83.027219},{"lat":35.5220317,"lon":-83.0268894},{"lat":35.5220388,"lon":-83.0263394},{"lat":35.5220407,"lon":-83.0261905},{"lat":35.5220798,"lon":-83.0261306}],"tags":{"highway":"primary","name":"Dellwood Road","oneway":"yes","ref":"US 19;US 276"}},{"type":"way","id":1514082745,"nodes":[171286245,13832173168,13832173167,13832173166,13832173115,13832173116,13832173117,13726096287,13832173118],"geometry":[{"lat":35.5217823,"lon":-83.0294789},{"lat":35.5217645,"lon":-83.0293449},{"lat":35.521762,"lon":-83.0292845},{"lat":35.5218537,"lon":-83.0289864},{"lat":35.5219443,"lon":-83.0287251},{"lat":35.5219735,"lon":-83.0285493},{"lat":35.5219701,"lon":-83.0284534},{"lat":35.5219644,"lon":-83.0284117},{"lat":35.5219513,"lon":-83.0283154}],"tags":{"highway":"primary","name":"Soco Road","oneway":"yes","ref":"US 19"}},{"type":"way","id":1514082746,"nodes":[13832173120,13832173135,13832173119,13832173169,171286245],"geometry":[{"lat":35.5221847,"lon":-83.0283615},{"lat":35.5221243,"lon":-83.0286158},{"lat":35.5220431,"lon":-83.0288383},{"lat":35.5218616,"lon":-83.029354},{"lat":35.5217823,"lon":-83.0294789}],"tags":{"highway":"primary","name":"Soco Road","oneway":"yes","ref":"US 19"}},{"type":"way","id":1514082747,"nodes":[13832165000,13832173133,13832173134,13832173121,171327723],"geometry":[{"lat":35.522257,"lon":-83.0280324},{"lat":35.5222763,"lon":-83.0281085},{"lat":35.5222743,"lon":-83.0281882},{"lat":35.5222512,"lon":-83.0282627},{"lat":35.5222077,"lon":-83.0283305}],"tags":{"highway":"primary","junction":"roundabout","oneway":"yes"}},{"type":"way","id":1514082766,"nodes":[4161265809,13832173153,13832173152,13832173151,13832173150,13832173149,13832173148,171327723],"geometry":[{"lat":35.5227488,"lon":-83.0282875},{"lat":35.5226039,"lon":-83.028271},{"lat":35.5225181,"lon":-83.0282723},{"lat":35.5224514,"lon":-83.0282769},{"lat":35.5223962,"lon":-83.028289},{"lat":35.5223444,"lon":-83.0283042},{"lat":35.5222877,"lon":-83.0283218},{"lat":35.5222077,"lon":-83.0283305}],"tags":{"highway":"primary","name":"Jonathan Creek Road","oneway":"yes"}},{"type":"way","id":1517278969,"nodes":[13832173109,13832165000],"geometry":[{"lat":35.5222184,"lon":-83.0279682},{"lat":35.522257,"lon":-83.0280324}],"tags":{"highway":"primary","junction":"roundabout","oneway":"yes"}},{"type":"way","id":1517278970,"nodes":[171327723,13832173120],"geometry":[{"lat":35.5222077,"lon":-83.0283305},{"lat":35.5221847,"lon":-83.0283615}],"tags":{"highway":"primary","junction":"roundabout","oneway":"yes"}},{"type":"way","id":1517279058,"nodes":[13832173114,13832173125,13832173126,13832173127,13832173128,13832173109],"geometry":[{"lat":35.5219294,"lon":-83.0279907},{"lat":35.5219778,"lon":-83.0279376},{"lat":35.5220376,"lon":-83.0279068},{"lat":35.5221024,"lon":-83.0279017},{"lat":35.522165,"lon":-83.027923},{"lat":35.5222184,"lon":-83.0279682}],"tags":{"highway":"primary","junction":"roundabout","oneway":"yes"}},{"type":"way","id":1517279059,"nodes":[13832173118,13832173129,13832173130,13832173131,13832173132,13832173114],"geometry":[{"lat":35.5219513,"lon":-83.0283154},{"lat":35.5219272,"lon":-83.028288},{"lat":35.5218967,"lon":-83.0282177},{"lat":35.5218865,"lon":-83.0281389},{"lat":35.5218978,"lon":-83.0280604},{"lat":35.5219294,"lon":-83.0279907}],"tags":{"highway":"primary","junction":"roundabout","oneway":"yes"}},{"type":"way","id":1517279060,"nodes":[13832173120,13832173122,13832173123,13832173124,13832173118],"geometry":[{"lat":35.5221847,"lon":-83.0283615},{"lat":35.522099,"lon":-83.0283808},{"lat":35.5220343,"lon":-83.0283743},{"lat":35.5219749,"lon":-83.0283422},{"lat":35.5219513,"lon":-83.0283154}],"tags":{"highway":"primary","junction":"roundabout","oneway":"yes"}}]} diff --git a/selfdrive/mapd/tests/test_fetch_maps.py b/selfdrive/mapd/tests/test_fetch_maps.py new file mode 100644 index 00000000000000..f2e36d06b1831e --- /dev/null +++ b/selfdrive/mapd/tests/test_fetch_maps.py @@ -0,0 +1,575 @@ +import hashlib +import json +import os +import shutil +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.fetch_maps import ( + cleanup_incomplete, + download_maps, + fetch_and_install, + fetch_maps_index, + install_from_file, + installed_db_summary, + installed_revision_summary, + load_installed_revision, + main as fetch_maps_main, + record_installed_maps, + refresh_maps, + required_free_bytes, + staging_dir, +) +from openpilot.selfdrive.mapd.maps_manifest import ( + ASSET_SHA256, + ASSET_SQLITE_BYTES, + ASSET_ZST_BYTES, + FREE_MARGIN_BYTES, + MIN_FREE_BYTES, + MIN_FREE_MIB, + RELEASE_REVISION, + SQLITE_SHA256, + bundled_maps_index, + load_committed_maps_index, + maps_update_decision, + parse_maps_index, + revision_is_newer, +) +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB + + +def _tiny_sqlite(path: str) -> None: + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "Main", "primary", 35 * CV.MPH_TO_MS, + [(37.0, -122.0), (37.001, -122.0)], + ) + con.execute("INSERT OR REPLACE INTO meta(key, value) VALUES ('way_count', '1')") + con.commit() + con.close() + + +def _sha256(path: str) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + h.update(f.read()) + return h.hexdigest() + + +def _make_zst(tmp_path, name="speed_limits.sqlite.zst"): + zstd = pytest.importorskip("zstandard") + src = str(tmp_path / "speed_limits.sqlite") + _tiny_sqlite(src) + zst = str(tmp_path / name) + cctx = zstd.ZstdCompressor() + with open(src, "rb") as inf, open(zst, "wb") as outf: + cctx.copy_stream(inf, outf) + return src, zst + + +def _track_hashed_paths(monkeypatch) -> list[str]: + import openpilot.selfdrive.mapd.fetch_maps as fm + hashed: list[str] = [] + orig = fm._sha256_file + + def wrap(path: str) -> str: + hashed.append(os.path.abspath(path)) + return orig(path) + + monkeypatch.setattr(fm, "_sha256_file", wrap) + return hashed + + +def test_us_pack_free_space_threshold(): + assert MIN_FREE_MIB == 1573 + assert MIN_FREE_BYTES == 1573 * 1024 * 1024 + assert required_free_bytes(us_pack=True) == MIN_FREE_BYTES + assert ASSET_ZST_BYTES + ASSET_SQLITE_BYTES + FREE_MARGIN_BYTES == MIN_FREE_BYTES + + +def test_fetch_installs_sqlite(tmp_path): + src = str(tmp_path / "speed_limits.sqlite") + _tiny_sqlite(src) + + dest = str(tmp_path / "installed" / "speed_limits.sqlite") + fetch_and_install(dest=dest, url=Path(src).as_uri(), sha256="") + + db = OsmSpeedLimitDB(dest) + assert db.open() + m = db.lookup(37.0004, -122.0, bearing_deg=0.0) + assert m is not None and m.way_id == 1 + db.close() + summary = installed_db_summary(dest) + assert "Installed" in summary + assert os.path.getsize(dest) > 1024 + stage = staging_dir(dest) + assert not os.path.isdir(stage) or not os.listdir(stage) + + +def test_stages_beside_dest_not_tmp(tmp_path, monkeypatch): + src = str(tmp_path / "speed_limits.sqlite") + _tiny_sqlite(src) + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + recorded: list[str] = [] + + import openpilot.selfdrive.mapd.fetch_maps as fm + orig = fm.download_url + + def wrap(url, dest_path, progress=True): + recorded.append(dest_path) + return orig(url, dest_path, progress) + + monkeypatch.setattr(fm, "download_url", wrap) + fetch_and_install(dest=dest, url=Path(src).as_uri(), sha256="") + + assert recorded + packed = recorded[0] + dest_dir = os.path.dirname(os.path.abspath(dest)) + assert os.path.dirname(packed) == os.path.join(dest_dir, ".download") + assert os.path.basename(os.path.dirname(packed)) == ".download" + # Staging lives beside dest, not a system tempfile.mkdtemp() tree. + assert packed.startswith(dest_dir + os.sep) + + +def test_insufficient_space_fails_before_download(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + downloaded = {"n": 0} + + import openpilot.selfdrive.mapd.fetch_maps as fm + + monkeypatch.setattr(fm.shutil, "disk_usage", lambda p: SimpleNamespace(free=100 * 1024 * 1024, used=0, total=0)) + + def boom(url, dest_path, progress=True): + downloaded["n"] += 1 + raise AssertionError("download should not start when space check fails") + + monkeypatch.setattr(fm, "download_url", boom) + + with pytest.raises(RuntimeError, match="Not enough free space"): + fetch_and_install( + dest=dest, + url="https://github.com/jmbrunick/openpilot/releases/download/osm-us-speed-limits-v2/speed_limits_us.sqlite.zst", + sha256=ASSET_SHA256, + ) + assert downloaded["n"] == 0 + assert not os.path.isfile(dest) + + +def test_cleanup_on_failure_removes_partials_and_staging(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + leftover_partial = dest + ".partial" + stage = staging_dir(dest) + os.makedirs(stage, exist_ok=True) + leftover_zst = os.path.join(stage, "speed_limits_us.sqlite.zst") + with open(leftover_partial, "wb") as f: + f.write(b"old-partial") + with open(leftover_zst, "wb") as f: + f.write(b"old-zst") + # Previous good sqlite must survive a failed fetch. + _tiny_sqlite(dest) + + import openpilot.selfdrive.mapd.fetch_maps as fm + + def fail_download(url, dest_path, progress=True): + os.makedirs(os.path.dirname(dest_path), exist_ok=True) + with open(dest_path, "wb") as f: + f.write(b"incomplete-zst") + raise RuntimeError("simulated download failure") + + monkeypatch.setattr(fm, "download_url", fail_download) + + with pytest.raises(RuntimeError, match="simulated download failure"): + fetch_and_install(dest=dest, url=Path(tmp_path / "x.sqlite").as_uri(), sha256="") + + assert os.path.isfile(dest) + assert not os.path.isfile(leftover_partial) + assert not os.path.isfile(leftover_zst) + assert not os.path.isdir(stage) or not os.listdir(stage) + + +def test_sha256_is_of_downloaded_zst_not_sqlite(tmp_path): + src, zst = _make_zst(tmp_path) + zst_hash = _sha256(zst) + sqlite_hash = _sha256(src) + assert zst_hash != sqlite_hash + + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + with pytest.raises(RuntimeError, match="SHA-256 mismatch"): + fetch_and_install(dest=dest, url=Path(zst).as_uri(), sha256=sqlite_hash) + assert not os.path.isfile(dest) + assert not os.path.isfile(dest + ".partial") + + fetch_and_install(dest=dest, url=Path(zst).as_uri(), sha256=zst_hash) + assert os.path.isfile(dest) + assert _sha256(dest) == sqlite_hash + db = OsmSpeedLimitDB(dest) + assert db.open() + db.close() + stage = staging_dir(dest) + assert not os.path.isdir(stage) or not os.listdir(stage) + + +def test_install_from_file_does_not_hash_sqlite_against_zst(tmp_path, monkeypatch): + """ASSET_SHA256 is the zst digest. Never hash dest sqlite against it.""" + src, zst = _make_zst(tmp_path) + zst_hash = _sha256(zst) + sqlite_hash = _sha256(src) + assert zst_hash != sqlite_hash + assert SQLITE_SHA256 == "" + + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + hashed = _track_hashed_paths(monkeypatch) + install_from_file(zst, dest, sha256=zst_hash) + assert os.path.isfile(dest) + assert _sha256(dest) == sqlite_hash + dest_abs = os.path.abspath(dest) + assert dest_abs not in hashed + assert all(p.endswith(".zst") for p in hashed) + assert not any(p == dest_abs or p.endswith(".partial") for p in hashed) + + # Re-running with the zst hash on an already-installed sqlite must not fail + # the way the old install_from_file did (hash dest vs ASSET_SHA256). + hashed.clear() + sqlite_copy = str(tmp_path / "already_installed.sqlite") + shutil.copyfile(dest, sqlite_copy) + dest2 = str(tmp_path / "osm2" / "speed_limits.sqlite") + install_from_file(sqlite_copy, dest2, sha256=zst_hash) + assert os.path.isfile(dest2) + assert hashed == [] + + +def test_fetch_and_install_never_hashes_dest_sqlite(tmp_path, monkeypatch): + src, zst = _make_zst(tmp_path) + zst_hash = _sha256(zst) + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + hashed = _track_hashed_paths(monkeypatch) + fetch_and_install(dest=dest, url=Path(zst).as_uri(), sha256=zst_hash) + dest_abs = os.path.abspath(dest) + assert dest_abs not in hashed + assert all(".zst" in os.path.basename(p) for p in hashed) + assert _sha256(dest) == _sha256(src) + assert _sha256(dest) != zst_hash + + +def test_empty_sha256_skips_verification(tmp_path, monkeypatch): + src, zst = _make_zst(tmp_path) + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + hashed = _track_hashed_paths(monkeypatch) + install_from_file(zst, dest, sha256="") + assert hashed == [] + dest2 = str(tmp_path / "osm2" / "speed_limits.sqlite") + src2 = str(tmp_path / "plain.sqlite") + _tiny_sqlite(src2) + fetch_and_install(dest=dest2, url=Path(src2).as_uri(), sha256="") + assert hashed == [] + dest3 = str(tmp_path / "osm3" / "speed_limits.sqlite") + rc = fetch_maps_main(["--url", Path(src2).as_uri(), "--out", dest3, "--sha256", ""]) + assert rc == 0 + assert os.path.isfile(dest3) + + +def test_invalid_sqlite_does_not_clobber_dest(tmp_path): + zstd = pytest.importorskip("zstandard") + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_sqlite(dest) + prev = _sha256(dest) + zst = str(tmp_path / "junk.sqlite.zst") + cctx = zstd.ZstdCompressor() + with open(zst, "wb") as outf: + outf.write(cctx.compress(b"not a sqlite")) + with pytest.raises(RuntimeError, match="not a NAP OSM sqlite"): + fetch_and_install(dest=dest, url=Path(zst).as_uri(), sha256=_sha256(zst)) + assert os.path.isfile(dest) + assert _sha256(dest) == prev + assert not os.path.isfile(dest + ".partial") + + +def test_fetch_maps_does_not_use_tempfile(): + import inspect + import openpilot.selfdrive.mapd.fetch_maps as fm + assert "tempfile" not in inspect.getsource(fm) + + +def test_cleanup_incomplete_helper(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_sqlite(dest) + with open(dest + ".partial", "wb") as f: + f.write(b"x") + stage = staging_dir(dest) + os.makedirs(stage, exist_ok=True) + with open(os.path.join(stage, "foo.zst"), "wb") as f: + f.write(b"y") + cleanup_incomplete(dest) + assert os.path.isfile(dest) + assert not os.path.isfile(dest + ".partial") + assert not os.path.isdir(stage) or not os.listdir(stage) + + +def test_parse_maps_index_required_and_aliases(): + idx = parse_maps_index({ + "revision": "1", + "asset_url": "https://example.test/speed_limits_us.sqlite.zst", + "asset_name": "speed_limits_us.sqlite.zst", + "sha256": ASSET_SHA256, + "bytes": 203815064, + "notes": "v1", + }) + assert idx.revision == "1" + assert idx.asset_name == "speed_limits_us.sqlite.zst" + assert idx.sha256 == ASSET_SHA256.lower() + assert idx.bytes == 203815064 + assert idx.notes == "v1" + + aliased = parse_maps_index({ + "version": "2.0.0", + "url": "https://example.test/v2.zst", + "sha256_zst": "A" * 64, + "size": 10, + }) + assert aliased.revision == "2.0.0" + assert aliased.asset_url.endswith("v2.zst") + assert aliased.sha256 == "a" * 64 + assert aliased.bytes == 10 + + with pytest.raises(ValueError, match="missing sha256"): + parse_maps_index({"revision": "1", "asset_url": "https://example.test/x.zst"}) + with pytest.raises(ValueError, match="missing revision"): + parse_maps_index({"asset_url": "https://example.test/x.zst", "sha256": "a" * 64}) + with pytest.raises(ValueError, match="64 hex"): + parse_maps_index({"revision": "1", "asset_url": "https://example.test/x.zst", "sha256": "deadbeef"}) + + +def test_committed_maps_index_matches_first_install_constants(): + idx = load_committed_maps_index() + bundled = bundled_maps_index() + assert idx.revision == RELEASE_REVISION == bundled.revision + assert idx.sha256 == ASSET_SHA256 == bundled.sha256 + assert idx.asset_name == bundled.asset_name + assert idx.asset_url == bundled.asset_url + assert idx.bytes is not None and idx.bytes > 0 + + +def test_maps_update_decision_up_to_date_vs_newer(): + remote = bundled_maps_index() + assert maps_update_decision(False, "", "", remote) == "install" + assert maps_update_decision(True, remote.revision, remote.sha256, remote) == "up_to_date" + assert maps_update_decision(True, remote.revision, remote.sha256.upper(), remote) == "up_to_date" + + newer = parse_maps_index({ + "revision": "3", + "asset_url": remote.asset_url, + "asset_name": remote.asset_name, + "sha256": "b" * 64, + }) + assert maps_update_decision(True, "1", remote.sha256, newer) == "update" + assert maps_update_decision(True, "2", remote.sha256, newer) == "update" + assert maps_update_decision(True, "1", "b" * 64, newer) == "up_to_date" + + # Same revision but different zst SHA → republish, still download. + republish = parse_maps_index({ + "revision": remote.revision, + "asset_url": remote.asset_url, + "asset_name": remote.asset_name, + "sha256": "c" * 64, + }) + assert maps_update_decision(True, remote.revision, remote.sha256, republish) == "update" + + # Legacy sqlite (no recorded revision): unknown pack — download. + assert maps_update_decision(True, "", "", remote) == "update" + assert maps_update_decision(True, "", "", newer) == "update" + + assert revision_is_newer("2", "1") + assert revision_is_newer("1.1.0", "1.0.9") + assert not revision_is_newer("1", "1") + assert not revision_is_newer("1", "2") + + +def test_sha_mismatch_does_not_replace_sqlite(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_sqlite(dest) + prev = _sha256(dest) + _src, zst = _make_zst(tmp_path) + with pytest.raises(RuntimeError, match="SHA-256 mismatch"): + fetch_and_install(dest=dest, url=Path(zst).as_uri(), sha256="d" * 64) + assert os.path.isfile(dest) + assert _sha256(dest) == prev + assert not os.path.isfile(dest + ".partial") + + +def test_refresh_up_to_date_skips_download(tmp_path, monkeypatch, capsys): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_sqlite(dest) + remote = bundled_maps_index() + record_installed_maps(remote, dest) + + import openpilot.selfdrive.mapd.fetch_maps as fm + + def boom(*_a, **_k): + raise AssertionError("must not download when up to date") + + monkeypatch.setattr(fm, "fetch_maps_index", lambda url=None: remote) + monkeypatch.setattr(fm, "fetch_and_install", boom) + assert refresh_maps(dest=dest) is None + out = capsys.readouterr().out + assert "Maps are up to date" in out + assert f"revision {remote.revision}" in out + assert os.path.isfile(dest) + + +def test_refresh_newer_downloads_and_records_revision(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_sqlite(dest) + old = bundled_maps_index() + record_installed_maps(old, dest) + + _src, zst = _make_zst(tmp_path) + zst_hash = _sha256(zst) + remote = parse_maps_index({ + "revision": "3", + "asset_url": Path(zst).as_uri(), + "asset_name": os.path.basename(zst), + "sha256": zst_hash, + "notes": "county refresh", + }) + + import openpilot.selfdrive.mapd.fetch_maps as fm + monkeypatch.setattr(fm, "fetch_maps_index", lambda url=None: remote) + assert refresh_maps(dest=dest) == dest + rev, sha = load_installed_revision(dest) + assert rev == "3" + assert sha == zst_hash + assert installed_revision_summary(dest) == "3" + + +def test_refresh_sha_mismatch_keeps_sqlite(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_sqlite(dest) + prev = _sha256(dest) + record_installed_maps(bundled_maps_index(), dest) + prev_rev, prev_sha = load_installed_revision(dest) + + _src, zst = _make_zst(tmp_path) + remote = parse_maps_index({ + "revision": "3", + "asset_url": Path(zst).as_uri(), + "asset_name": os.path.basename(zst), + "sha256": "e" * 64, + }) + + import openpilot.selfdrive.mapd.fetch_maps as fm + monkeypatch.setattr(fm, "fetch_maps_index", lambda url=None: remote) + with pytest.raises(RuntimeError, match="SHA-256 mismatch"): + refresh_maps(dest=dest) + assert os.path.isfile(dest) + assert _sha256(dest) == prev + rev, sha = load_installed_revision(dest) + assert rev == prev_rev + assert sha == prev_sha + + +def test_refresh_without_sqlite_does_first_install(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + _src, zst = _make_zst(tmp_path) + zst_hash = _sha256(zst) + remote = parse_maps_index({ + "revision": "1", + "asset_url": Path(zst).as_uri(), + "asset_name": os.path.basename(zst), + "sha256": zst_hash, + }) + import openpilot.selfdrive.mapd.fetch_maps as fm + monkeypatch.setattr(fm, "fetch_maps_index", lambda url=None: remote) + assert refresh_maps(dest=dest) == dest + assert os.path.isfile(dest) + assert load_installed_revision(dest) == ("1", zst_hash) + + +def test_refresh_unversioned_sqlite_downloads_current_pack(tmp_path, monkeypatch): + """v1 sqlite with no recorded revision must not be treated as up to date.""" + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_sqlite(dest) + _src, zst = _make_zst(tmp_path) + zst_hash = _sha256(zst) + remote = bundled_maps_index() + remote = parse_maps_index({ + "revision": remote.revision, + "asset_url": Path(zst).as_uri(), + "asset_name": os.path.basename(zst), + "sha256": zst_hash, + "notes": remote.notes, + }) + import openpilot.selfdrive.mapd.fetch_maps as fm + monkeypatch.setattr(fm, "fetch_maps_index", lambda url=None: remote) + assert refresh_maps(dest=dest) == dest + assert load_installed_revision(dest) == (bundled_maps_index().revision, zst_hash) + + +def test_fetch_maps_index_from_file(tmp_path): + payload = { + "revision": "1", + "asset_url": "https://example.test/speed_limits_us.sqlite.zst", + "asset_name": "speed_limits_us.sqlite.zst", + "sha256": ASSET_SHA256, + "bytes": 1, + } + path = tmp_path / "maps-index.json" + path.write_text(json.dumps(payload), encoding="utf-8") + idx = fetch_maps_index(path.as_uri()) + assert idx.revision == "1" + assert idx.sha256 == ASSET_SHA256.lower() + + +def test_download_maps_uses_shared_install(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + _src, zst = _make_zst(tmp_path) + zst_hash = _sha256(zst) + remote = parse_maps_index({ + "revision": "1", + "asset_url": Path(zst).as_uri(), + "asset_name": os.path.basename(zst), + "sha256": zst_hash, + }) + import openpilot.selfdrive.mapd.fetch_maps as fm + monkeypatch.setattr(fm, "fetch_maps_index", lambda url=None: remote) + download_maps(dest=dest) + assert os.path.isfile(dest) + assert load_installed_revision(dest) == ("1", zst_hash) + + +def test_refresh_cli_up_to_date(tmp_path, monkeypatch, capsys): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_sqlite(dest) + remote = bundled_maps_index() + record_installed_maps(remote, dest) + index_path = tmp_path / "maps-index.json" + index_path.write_text( + json.dumps({ + "revision": remote.revision, + "asset_url": remote.asset_url, + "asset_name": remote.asset_name, + "sha256": remote.sha256, + }), + encoding="utf-8", + ) + import openpilot.selfdrive.mapd.fetch_maps as fm + + def boom(*_a, **_k): + raise AssertionError("cli refresh must not download when up to date") + + monkeypatch.setattr(fm, "fetch_and_install", boom) + rc = fetch_maps_main(["--refresh", "--out", dest, "--index-url", index_path.as_uri()]) + assert rc == 0 + assert "Maps are up to date" in capsys.readouterr().out + diff --git a/selfdrive/mapd/tests/test_fetch_maps_resume.py b/selfdrive/mapd/tests/test_fetch_maps_resume.py new file mode 100644 index 00000000000000..55decb6b9477e9 --- /dev/null +++ b/selfdrive/mapd/tests/test_fetch_maps_resume.py @@ -0,0 +1,168 @@ +"""Download US Maps: retry + HTTP Range resume, and hash-mismatch cleanup. + +A local HTTP server stands in for GitHub Releases (which answers Range with +206 after the 302 to release-assets.githubusercontent.com). +""" +import hashlib +import http.server +import os +import threading +import time +from pathlib import Path + +import pytest + +import openpilot.selfdrive.mapd.fetch_maps as fm +from openpilot.selfdrive.mapd.fetch_maps import HashMismatchError, download_url, fetch_and_install, staging_dir +from openpilot.selfdrive.mapd.tests.test_fetch_maps import _make_zst + + +class _Server: + """Serves `data`. The first `stall` GETs send `cut` bytes, then hang past the client timeout.""" + + def __init__(self, data: bytes, *, stall: int = 0, cut: int = 0, stall_s: float = 1.0): + self.data, self.stall, self.cut, self.stall_s = data, stall, cut, stall_s + self.ranges: list[str | None] = [] + outer = self + + class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_GET(self): + rng = self.headers.get("Range") + outer.ranges.append(rng) + start = int(rng.split("=")[1].split("-")[0]) if rng else 0 + body = outer.data[start:] + if rng: + if start >= len(outer.data): + self.send_response(416) + self.send_header("Content-Range", f"bytes */{len(outer.data)}") + self.end_headers() + return + self.send_response(206) + self.send_header("Content-Range", f"bytes {start}-{len(outer.data) - 1}/{len(outer.data)}") + else: + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if outer.stall > 0: + outer.stall -= 1 + self.wfile.write(body[:outer.cut]) + self.wfile.flush() + time.sleep(outer.stall_s) + return + self.wfile.write(body) + + self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H) + self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}/speed_limits_us.sqlite.zst" + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + + def close(self): + self.httpd.shutdown() + self.httpd.server_close() + + +@pytest.fixture +def small_budget(monkeypatch): + monkeypatch.setattr(fm, "required_free_bytes", lambda *a, **k: 0) + monkeypatch.setattr(fm, "ASSET_SQLITE_BYTES", 0) + monkeypatch.setattr(fm, "FREE_MARGIN_BYTES", 0) + monkeypatch.setattr(fm, "CHUNK", 1024) + + +def test_timeout_mid_stream_retries_and_resumes_with_range(tmp_path, small_budget, capsys): + data = os.urandom(300_000) + srv = _Server(data, stall=1, cut=100_000) + try: + sleeps: list[float] = [] + dest = str(tmp_path / "a.zst") + n = download_url(srv.url, dest, timeout=0.3, sleep=sleeps.append) + finally: + srv.close() + assert n == len(data) + assert Path(dest).read_bytes() == data + assert srv.ranges[0] is None and srv.ranges[1] == "bytes=100000-" + assert len(sleeps) == 1 and sleeps[0] > 0 + out = capsys.readouterr().out + assert "Retrying… (1)" in out and "ERROR" not in out + assert not os.path.exists(dest + ".partial") + + +def test_error_only_after_all_retries_and_partial_kept(tmp_path, small_budget, capsys): + data = os.urandom(200_000) + srv = _Server(data, stall=99, cut=0) + srv.cut = 50_000 + try: + dest = str(tmp_path / "a.zst") + with pytest.raises(RuntimeError, match="after 3 attempts"): + download_url(srv.url, dest, attempts=3, timeout=0.2, sleep=lambda s: None) + finally: + srv.close() + out = capsys.readouterr().out + assert "Retrying… (1)" in out and "Retrying… (2)" in out and "Retrying… (3)" not in out + # Each attempt resumed where the last left off; nothing thrown away. + assert os.path.getsize(dest + ".partial") == 150_000 + + +def test_second_tap_resumes_from_partial_and_installs(tmp_path, small_budget): + _src, zst = _make_zst(tmp_path) + data = Path(zst).read_bytes() + sha = hashlib.sha256(data).hexdigest() + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + cut = len(data) // 2 + srv = _Server(data, stall=1, cut=cut, stall_s=1.0) + try: + first = fm.download_url + + def one_attempt(url, d, progress=True, **kw): + return first(url, d, progress, attempts=1, timeout=0.3) + fm.download_url = one_attempt + try: + with pytest.raises(RuntimeError, match="after 1 attempts"): + fetch_and_install(dest=dest, url=srv.url, sha256=sha, sqlite_sha256="") + partial = os.path.join(staging_dir(dest), "speed_limits_us.sqlite.zst.partial") + assert os.path.getsize(partial) == cut # kept for the next tap + fetch_and_install(dest=dest, url=srv.url, sha256=sha, sqlite_sha256="") + finally: + fm.download_url = first + finally: + srv.close() + assert srv.ranges[-1] == f"bytes={cut}-" + assert fm.sqlite_ok(dest) + assert not os.path.isdir(staging_dir(dest)) or not os.listdir(staging_dir(dest)) + + +def test_hash_mismatch_deletes_staged_download(tmp_path, small_budget): + _src, zst = _make_zst(tmp_path) + data = Path(zst).read_bytes() + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + srv = _Server(data) + try: + with pytest.raises(HashMismatchError): + fetch_and_install(dest=dest, url=srv.url, sha256="0" * 64, sqlite_sha256="") + finally: + srv.close() + assert not os.path.exists(dest) + stage = staging_dir(dest) + assert not os.path.isdir(stage) or not os.listdir(stage) + + +def test_partial_for_a_different_asset_is_not_resumed(tmp_path, small_budget): + _src, zst = _make_zst(tmp_path) + data = Path(zst).read_bytes() + sha = hashlib.sha256(data).hexdigest() + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + stage = staging_dir(dest) + os.makedirs(stage) + with open(os.path.join(stage, "speed_limits_us.sqlite.zst.partial"), "wb") as f: + f.write(b"stale bytes from an older pack") + with open(os.path.join(stage, "speed_limits_us.sqlite.zst.expect"), "w") as f: + f.write("old-url\nold-sha\n") + srv = _Server(data) + try: + fetch_and_install(dest=dest, url=srv.url, sha256=sha, sqlite_sha256="") + finally: + srv.close() + assert srv.ranges == [None] + assert fm.sqlite_ok(dest) diff --git a/selfdrive/mapd/tests/test_local_refresh.py b/selfdrive/mapd/tests/test_local_refresh.py new file mode 100644 index 00000000000000..854f61f743d9b1 --- /dev/null +++ b/selfdrive/mapd/tests/test_local_refresh.py @@ -0,0 +1,572 @@ +"""Local Refresh maps: location, 100-mile merge, no network.""" +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.gps_fix import ( + GPS_MAX_ACC_M, + GPS_MAX_AGE_S, + REFRESH_GNSS_WAIT_S, + REFRESH_GPS_MAX_ACC_M, + format_last_gps_position, + gps_sample_from_sm, + is_plausible_lat_lon, + last_gps_from_params, + parse_last_gps_position, + persist_last_gps_position, +) +from openpilot.selfdrive.mapd.local_refresh import ( + NO_GPS_MESSAGE, + REFRESH_RADIUS_KM, + REFRESH_RADIUS_MILES, + NoGpsError, + RefreshMapsError, + bbox_intersects, + install_merged_overlay, + main as refresh_main, + merge_decision_for_way, + merge_ways_into_db, + refresh_local_maps, + resolve_refresh_location, +) +from openpilot.selfdrive.mapd.mn_statutory import BENSON_LAT, BENSON_LON, FILL_SOURCE +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB +from openpilot.selfdrive.mapd.overpass import bbox_from_center, overpass_query, ways_from_overpass + + +SF = (37.7749, -122.4194) +NYC = (40.7128, -74.0060) + + +def _insert(con, way_id: int, lat: float, lon: float, mph: float, name: str = "Rd") -> None: + OsmSpeedLimitDB.insert_way( + con, way_id, name, "primary", mph * CV.MPH_TO_MS, + [(lat, lon - 0.001), (lat, lon + 0.001)], + ) + + +def _tiny_us(path: str) -> None: + con = OsmSpeedLimitDB.create(path) + _insert(con, 1, SF[0], SF[1], 35, "Market") + _insert(con, 2, NYC[0], NYC[1], 25, "Broadway") + OsmSpeedLimitDB.recount_ways(con) + con.commit() + con.close() + + +def _overpass_way(way_id: int, lat: float, lon: float, mph: int, name: str) -> dict: + return { + "type": "way", + "id": way_id, + "tags": {"highway": "primary", "name": name, "maxspeed": f"{mph} mph"}, + "geometry": [ + {"lat": lat, "lon": lon - 0.001}, + {"lat": lat, "lon": lon + 0.001}, + ], + } + + +def test_refresh_radius_is_100_miles(): + assert REFRESH_RADIUS_MILES == 100.0 + assert abs(REFRESH_RADIUS_KM - 160.9344) < 1e-6 + south, west, north, east = bbox_from_center(SF[0], SF[1], REFRESH_RADIUS_KM) + # ~160.9 km → ~1.45 deg latitude + assert abs((north - south) / 2 - REFRESH_RADIUS_KM / 111.0) < 1e-9 + assert south < SF[0] < north + assert west < SF[1] < east + nyc_box = bbox_from_center(NYC[0], NYC[1], 1.0) + sf_box = bbox_from_center(SF[0], SF[1], REFRESH_RADIUS_KM) + assert not bbox_intersects(sf_box, nyc_box) + + +def test_merge_decision_replaces_in_radius_keeps_outside(): + bbox = bbox_from_center(SF[0], SF[1], REFRESH_RADIUS_KM) + assert merge_decision_for_way(SF[0], SF[0], SF[1], SF[1], bbox) == "replace" + assert merge_decision_for_way(NYC[0], NYC[0], NYC[1], NYC[1], bbox) == "keep" + # Corner of the bbox still intersects → replace (bbox contains the 100-mile circle). + assert merge_decision_for_way(bbox[2], bbox[2], bbox[3], bbox[3], bbox) == "replace" + + +def test_no_gps_fails_without_guessing_a_city(): + with pytest.raises(NoGpsError, match="will not guess a city") as exc: + resolve_refresh_location(live_fix=None, last_gps_raw=None) + msg = str(exc.value) + assert msg == NO_GPS_MESSAGE + assert "onroad" in msg.lower() + assert "about a minute" in msg.lower() + assert "guess a city" in msg.lower() + assert "drive once" not in msg.lower() + for city in ("San Francisco", "New York", "Los Angeles", "Chicago", "default city"): + assert city.lower() not in msg.lower() + + +def test_invalid_last_gps_is_no_gps(): + assert parse_last_gps_position("") is None + assert parse_last_gps_position("not-json") is None + assert parse_last_gps_position({"latitude": 0, "longitude": 0}) is None + assert parse_last_gps_position({"latitude": 91, "longitude": 0}) is None + with pytest.raises(NoGpsError): + resolve_refresh_location(live_fix=(0.0, 0.0), last_gps_raw="{}") + + +def test_live_gnss_preferred_over_last_gps(): + last = format_last_gps_position(*NYC) + loc = resolve_refresh_location(live_fix=SF, last_gps_raw=last) + assert loc.source == "gnss" + assert abs(loc.lat - SF[0]) < 1e-9 + loc2 = resolve_refresh_location(live_fix=None, last_gps_raw=last) + assert loc2.source == "last_gps" + assert abs(loc2.lon - NYC[1]) < 1e-9 + loc3 = resolve_refresh_location(lat=SF[0], lon=SF[1], live_fix=NYC, last_gps_raw=last) + assert loc3.source == "cli" + assert abs(loc3.lat - SF[0]) < 1e-9 + + +def test_is_plausible_rejects_null_island(): + assert not is_plausible_lat_lon(0.0, 0.0) + assert is_plausible_lat_lon(*SF) + + +class _SM: + def __init__(self, msgs, frames, times): + self._msgs = msgs + self.recv_frame = frames + self.recv_time = times + + def __getitem__(self, key): + return self._msgs[key] + + +def _gps_msg(lat, lon, acc=8.0, speed=0.0, bearing=0.0): + from types import SimpleNamespace + return SimpleNamespace(latitude=lat, longitude=lon, horizontalAccuracy=acc, speed=speed, bearingDeg=bearing) + + +def test_gps_sample_prefers_external_and_rejects_stale(): + ext = _gps_msg(*SF) + qcom = _gps_msg(*NYC, bearing=90.0) + sm = _SM( + {"gpsLocationExternal": ext, "gpsLocation": qcom}, + {"gpsLocationExternal": 1, "gpsLocation": 1}, + {"gpsLocationExternal": 100.0, "gpsLocation": 100.0}, + ) + lat, lon, _b, ok = gps_sample_from_sm(sm, now=100.5) + assert ok and abs(lat - SF[0]) < 1e-9 and abs(lon - SF[1]) < 1e-9 + + sm.recv_time["gpsLocationExternal"] = 90.0 # stale for mapd (2.5s) + lat, lon, _b, ok = gps_sample_from_sm(sm, now=100.5) + assert ok and abs(lat - NYC[0]) < 1e-9 + + null = _gps_msg(0.0, 0.0, acc=1.0) + sm._msgs["gpsLocationExternal"] = null + sm._msgs["gpsLocation"] = null + sm.recv_time["gpsLocationExternal"] = 100.0 + sm.recv_time["gpsLocation"] = 100.0 + _lat, _lon, _b, ok = gps_sample_from_sm(sm, now=100.5) + assert not ok + + +def test_mapd_gps_sample_rejects_stale_and_coarse_accuracy(): + assert GPS_MAX_AGE_S == 2.5 + assert GPS_MAX_ACC_M == 50.0 + sm = _SM( + {"gpsLocationExternal": _gps_msg(*SF, acc=8.0), "gpsLocation": _gps_msg(*SF, acc=8.0)}, + {"gpsLocationExternal": 1, "gpsLocation": 1}, + {"gpsLocationExternal": 90.0, "gpsLocation": 90.0}, + ) + _lat, _lon, _b, ok = gps_sample_from_sm(sm, now=100.5) + assert not ok + + sm.recv_time["gpsLocationExternal"] = 100.0 + sm.recv_time["gpsLocation"] = 100.0 + sm._msgs["gpsLocationExternal"] = _gps_msg(*SF, acc=150.0) + sm._msgs["gpsLocation"] = _gps_msg(*SF, acc=150.0) + _lat, _lon, _b, ok = gps_sample_from_sm(sm, now=100.5) + assert not ok + + +def test_refresh_gps_sample_accepts_stale_and_yard_accuracy(): + assert REFRESH_GNSS_WAIT_S == 10.0 + assert REFRESH_GPS_MAX_ACC_M == 200.0 + sm = _SM( + {"gpsLocationExternal": _gps_msg(*SF, acc=150.0), "gpsLocation": _gps_msg(0.0, 0.0)}, + {"gpsLocationExternal": 1, "gpsLocation": 1}, + {"gpsLocationExternal": 90.0, "gpsLocation": 90.0}, + ) + lat, lon, _b, ok = gps_sample_from_sm( + sm, now=100.5, max_age_s=None, max_acc_m=REFRESH_GPS_MAX_ACC_M, + ) + assert ok and abs(lat - SF[0]) < 1e-9 and abs(lon - SF[1]) < 1e-9 + + sm._msgs["gpsLocationExternal"] = _gps_msg(0.0, 0.0, acc=8.0) + sm._msgs["gpsLocation"] = _gps_msg(0.0, 0.0, acc=8.0) + _lat, _lon, _b, ok = gps_sample_from_sm( + sm, now=100.5, max_age_s=None, max_acc_m=REFRESH_GPS_MAX_ACC_M, + ) + assert not ok + + +def test_persist_last_gps_and_param_file_fallback(tmp_path, monkeypatch): + stored: dict[str, str] = {} + + class FakeParams: + def put(self, key, value): + stored[key] = value + + def get(self, key): + return stored.get(key) + + persist_last_gps_position(FakeParams(), *SF) + pos = parse_last_gps_position(stored["LastGPSPosition"]) + assert pos is not None + assert abs(pos[0] - SF[0]) < 1e-9 and abs(pos[1] - SF[1]) < 1e-9 + + p = tmp_path / "LastGPSPosition" + p.write_text(format_last_gps_position(*NYC), encoding="utf-8") + import sys + import types + import openpilot.selfdrive.mapd.gps_fix as gf + monkeypatch.setattr(gf, "_PARAM_LAST_GPS_PATHS", (str(p),)) + + fake_params = types.ModuleType("openpilot.common.params") + + class EmptyParams: + def get(self, _key): + return None + + fake_params.Params = EmptyParams + monkeypatch.setitem(sys.modules, "openpilot.common.params", fake_params) + pos = last_gps_from_params() + assert pos is not None + assert abs(pos[0] - NYC[0]) < 1e-9 + assert abs(pos[1] - NYC[1]) < 1e-9 + + +def test_merge_replaces_way_ids_in_radius_keeps_rest(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + bbox = bbox_from_center(SF[0], SF[1], REFRESH_RADIUS_KM) + payload = {"elements": [ + _overpass_way(1, SF[0], SF[1], 45, "Market"), # updated limit + _overpass_way(3, SF[0] + 0.01, SF[1], 30, "New"), # new local way + ]} + ways = ways_from_overpass(payload) + deleted, inserted = merge_ways_into_db(dest, ways, bbox) + assert deleted >= 1 + assert inserted == 2 + + db = OsmSpeedLimitDB(dest) + assert db.open() + sf = db.lookup(SF[0], SF[1], bearing_deg=90.0) + assert sf is not None and sf.way_id == 1 + assert abs(sf.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + new = db.lookup(SF[0] + 0.01, SF[1], bearing_deg=90.0) + assert new is not None and new.way_id == 3 + nyc = db.lookup(NYC[0], NYC[1], bearing_deg=90.0) + assert nyc is not None and nyc.way_id == 2 + assert abs(nyc.speed_limit_ms - 25 * CV.MPH_TO_MS) < 0.2 + db.close() + assert OsmSpeedLimitDB.way_count(dest) == 3 + + +def test_refresh_no_gps_leaves_sqlite_and_skips_overpass(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + prev = Path(dest).read_bytes() + + def boom(*_a, **_k): + raise AssertionError("must not query OSM without a location") + + import openpilot.selfdrive.mapd.local_refresh as lr + monkeypatch.setattr(lr, "fetch_overpass", boom) + monkeypatch.setattr(lr, "download_maps", boom) + + with pytest.raises(NoGpsError, match="will not guess a city"): + refresh_local_maps(dest=dest, live_fix=None, last_gps_raw=None) + assert Path(dest).read_bytes() == prev + + +def test_cli_no_gps_prints_error(tmp_path, monkeypatch, capsys): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + prev = Path(dest).read_bytes() + import openpilot.selfdrive.mapd.local_refresh as lr + monkeypatch.setattr(lr, "read_live_gnss", lambda **_k: None) + monkeypatch.setattr(lr, "last_gps_from_params", lambda: None) + rc = refresh_main(["--out", dest]) + assert rc == 1 + out = capsys.readouterr().out + assert "Waiting up to 10s for a satellite fix" in out + assert "(c) OpenStreetMap contributors" in out + assert "ERROR:" in out + assert "guess a city" in out + assert "onroad" in out + assert "about a minute" in out + assert Path(dest).read_bytes() == prev + + +def test_overpass_timeout_keeps_previous_sqlite(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + prev = Path(dest).read_bytes() + + import openpilot.selfdrive.mapd.local_refresh as lr + + def timeout(*_a, **_k): + raise RuntimeError("OSM Overpass timed out. Previous maps were left unchanged. You can retry Refresh maps.") + + monkeypatch.setattr(lr, "fetch_overpass", timeout) + with pytest.raises(RuntimeError, match="timed out"): + refresh_local_maps(dest=dest, live_fix=SF, last_gps_raw=None) + assert Path(dest).read_bytes() == prev + + +def test_merge_exception_keeps_dest(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + prev = Path(dest).read_bytes() + bbox = bbox_from_center(SF[0], SF[1], REFRESH_RADIUS_KM) + ways = ways_from_overpass({"elements": [_overpass_way(1, SF[0], SF[1], 45, "Market")]}) + + import openpilot.selfdrive.mapd.local_refresh as lr + + def boom(*_a, **_k): + raise RuntimeError("disk full during merge") + + monkeypatch.setattr(lr, "merge_ways_into_db", boom) + with pytest.raises(RuntimeError, match="disk full"): + install_merged_overlay(dest, ways, bbox) + assert Path(dest).read_bytes() == prev + assert os.path.isfile(dest) + work = tmp_path / "osm" / ".download" / "speed_limits.merge.sqlite" + assert not work.is_file() + + +def test_empty_overpass_does_not_wipe_radius(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + prev = Path(dest).read_bytes() + with pytest.raises(RefreshMapsError, match="No usable highway speed limits"): + refresh_local_maps(dest=dest, live_fix=SF, last_gps_raw=None, payload={"elements": []}) + assert Path(dest).read_bytes() == prev + + +def test_missing_sqlite_downloads_us_then_merges(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + payload = {"elements": [_overpass_way(9, SF[0], SF[1], 40, "Oak")]} + + import openpilot.selfdrive.mapd.local_refresh as lr + called = {"n": 0} + + def fake_download(dest=None, **_k): + called["n"] += 1 + path = dest or str(tmp_path / "missing") + os.makedirs(os.path.dirname(path), exist_ok=True) + _tiny_us(path) + return path + + def no_overpass(*_a, **_k): + raise AssertionError("payload was provided; must not hit network") + + monkeypatch.setattr(lr, "download_maps", fake_download) + monkeypatch.setattr(lr, "fetch_overpass", no_overpass) + refresh_local_maps(dest=dest, live_fix=SF, last_gps_raw=None, payload=payload) + assert called["n"] == 1 + db = OsmSpeedLimitDB(dest) + assert db.open() + oak = db.lookup(SF[0], SF[1], bearing_deg=90.0) + assert oak is not None and oak.way_id == 9 + nyc = db.lookup(NYC[0], NYC[1], bearing_deg=90.0) + assert nyc is not None and nyc.way_id == 2 + db.close() + + +def test_refresh_never_installs_extract_only_when_download_fails(tmp_path, monkeypatch): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + import openpilot.selfdrive.mapd.local_refresh as lr + + def fail_download(*_a, **_k): + raise RuntimeError("GitHub unreachable") + + monkeypatch.setattr(lr, "download_maps", fail_download) + with pytest.raises(RuntimeError, match="GitHub unreachable"): + refresh_local_maps( + dest=dest, live_fix=SF, last_gps_raw=None, + payload={"elements": [_overpass_way(1, SF[0], SF[1], 40, "Oak")]}, + ) + assert not os.path.isfile(dest) + + +def test_refresh_cli_from_json(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + payload_path = tmp_path / "overpass.json" + payload_path.write_text(json.dumps({"elements": [ + _overpass_way(1, SF[0], SF[1], 55, "Market"), + ]}), encoding="utf-8") + rc = refresh_main([ + "--lat", str(SF[0]), "--lon", str(SF[1]), + "--from-json", str(payload_path), + "--out", dest, + ]) + assert rc == 0 + db = OsmSpeedLimitDB(dest) + assert db.open() + m = db.lookup(SF[0], SF[1], bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 55 * CV.MPH_TO_MS) < 0.2 + db.close() + + +def test_docs_and_ui_say_100_miles_not_published_pack(): + root = Path(__file__).resolve().parents[3] + docs = (root / "docs-nap/map-speed.md").read_text() + assert "100 miles" in docs + assert "~160.9 km" in docs + tici = (root / "selfdrive/ui/layouts/settings/map_speed.py").read_text() + mici = (root / "selfdrive/ui/mici/layouts/settings/map_speed.py").read_text() + nap = (root / "selfdrive/ui/layouts/settings/nap.py").read_text() + instructions = (root / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + assert '"Refresh maps"' in tici + assert "Check for map updates" not in tici + assert "refresh maps" in mici + assert "check for map updates" not in mici + assert "scripts.nap.refresh_osm_maps" in nap + assert "scripts.nap.refresh_osm_maps" in mici + assert tici.index("_all_items.append(self._refresh_btn)") < tici.index("_all_items.append(self._download_btn)") + mici_widgets = mici.split("self._scroller.add_widgets", 1)[1] + assert mici_widgets.index("refresh_maps_btn") < mici_widgets.index("download_maps_btn") + assert "100 miles" in instructions + assert "guess a city" in instructions + assert "10s" in instructions + assert "onroad" in instructions + assert "(c) OpenStreetMap" in instructions + assert "10s" in docs + assert "200 m" in docs or "200m" in docs + + +def test_map_scripts_do_not_reboot_on_exit(): + from scripts.nap.script_lifecycle import script_reboots_on_exit + assert not script_reboots_on_exit("scripts.nap.refresh_osm_maps") + assert not script_reboots_on_exit("scripts.nap.fetch_osm_maps") + assert script_reboots_on_exit("scripts.nap.calibrate_pedal") + assert script_reboots_on_exit("scripts.nap.flash_epas") + assert script_reboots_on_exit("scripts.nap.extract_epas") + assert script_reboots_on_exit("scripts.nap.restore_epas") + root = Path(__file__).resolve().parents[3] + for rel in ("scripts/nap/run_script.py", "scripts/nap/run_script_mici.py"): + src = (root / rel).read_text() + assert "script_reboots_on_exit" in src + assert "HARDWARE.reboot()" in src + nap = (root / "selfdrive/ui/layouts/settings/nap.py").read_text() + mici_launch = (root / "selfdrive/ui/mici/layouts/settings/nap_script.py").read_text() + assert "ScriptRunner" in nap + assert "gui_app.push_widget" in nap + assert "_MapScriptOverlay" in mici_launch + assert "script_reboots_on_exit" in nap + assert "script_reboots_on_exit" in mici_launch + + +def test_refresh_stages_merge_beside_dest_not_tmp(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + payload = {"elements": [_overpass_way(1, SF[0], SF[1], 40, "Market")]} + refresh_local_maps(dest=dest, live_fix=SF, last_gps_raw=None, payload=payload) + from openpilot.selfdrive.mapd.fetch_maps import STAGING_DIRNAME, staging_dir + stage = staging_dir(dest) + assert os.path.dirname(stage) == os.path.dirname(dest) + assert os.path.basename(stage) == STAGING_DIRNAME + assert not os.path.isfile(os.path.join(stage, "speed_limits.merge.sqlite")) + + +def _unmarked_way(way_id: int, lat: float, lon: float, highway: str, name: str) -> dict: + return { + "type": "way", + "id": way_id, + "tags": {"highway": highway, "name": name}, + "geometry": [ + {"lat": lat, "lon": lon - 0.001}, + {"lat": lat, "lon": lon + 0.001}, + ], + } + + +def test_mn_refresh_fills_unmarked_and_does_not_wipe(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + payload = {"elements": [ + _overpass_way(100, BENSON_LAT, BENSON_LON, 60, "US 12"), + _unmarked_way(101, BENSON_LAT + 0.01, BENSON_LON, "residential", "14th St"), + _unmarked_way(102, BENSON_LAT + 0.02, BENSON_LON, "service", "Alley svc"), + ]} + refresh_local_maps(dest=dest, live_fix=(BENSON_LAT, BENSON_LON), last_gps_raw=None, payload=payload) + db = OsmSpeedLimitDB(dest) + assert db.open() + tagged = db.lookup(BENSON_LAT, BENSON_LON, bearing_deg=90.0) + assert tagged is not None and tagged.way_id == 100 + assert abs(tagged.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.2 + filled = db.lookup(BENSON_LAT + 0.01, BENSON_LON, bearing_deg=90.0) + assert filled is not None and filled.way_id == 101 + assert abs(filled.speed_limit_ms - 30 * CV.MPH_TO_MS) < 0.2 + assert filled.estimated and not tagged.estimated + skipped = db.lookup(BENSON_LAT + 0.02, BENSON_LON, bearing_deg=90.0) + assert skipped is None + nyc = db.lookup(NYC[0], NYC[1], bearing_deg=90.0) + assert nyc is not None and nyc.way_id == 2 + db.close() + assert FILL_SOURCE in (OsmSpeedLimitDB.meta_get(dest, "fill_source") or "") + + +def test_sf_refresh_does_not_fill_unmarked_residential(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + _tiny_us(dest) + payload = {"elements": [ + _overpass_way(1, SF[0], SF[1], 40, "Market"), + _unmarked_way(50, SF[0] + 0.01, SF[1], "residential", "Oak"), + ]} + refresh_local_maps(dest=dest, live_fix=SF, last_gps_raw=None, payload=payload) + db = OsmSpeedLimitDB(dest) + assert db.open() + oak = db.lookup(SF[0] + 0.01, SF[1], bearing_deg=90.0) + assert oak is None + market = db.lookup(SF[0], SF[1], bearing_deg=90.0) + assert market is not None and abs(market.speed_limit_ms - 40 * CV.MPH_TO_MS) < 0.2 + db.close() + + +def test_mn_refresh_overpass_query_includes_unmarked(monkeypatch): + seen: dict = {} + + def fake_fetch(bbox, url="unused", **kwargs): + seen["include_unmarked"] = kwargs.get("include_unmarked") + seen["query"] = overpass_query(*bbox, include_unmarked=bool(kwargs.get("include_unmarked"))) + return {"elements": [_overpass_way(1, BENSON_LAT, BENSON_LON, 55, "US 12")]} + + import openpilot.selfdrive.mapd.local_refresh as lr + monkeypatch.setattr(lr, "fetch_overpass", fake_fetch) + dest = "/tmp/does-not-matter-mn-refresh" + # download_maps / merge would run; stub install after fetch + monkeypatch.setattr(lr, "_ensure_us_base", lambda dest: None) + monkeypatch.setattr(lr, "install_merged_overlay", lambda *a, **k: dest) + monkeypatch.setattr(lr, "installed_db_summary", lambda dest: "ok") + monkeypatch.setattr(lr, "sqlite_present", lambda dest: True) + refresh_local_maps(dest=dest, live_fix=(BENSON_LAT, BENSON_LON), last_gps_raw=None) + assert seen.get("include_unmarked") is True + assert '["maxspeed"]' not in seen["query"] + assert "residential" in seen["query"] + diff --git a/selfdrive/mapd/tests/test_map_match_frontage.py b/selfdrive/mapd/tests/test_map_match_frontage.py new file mode 100644 index 00000000000000..082e706e20c52c --- /dev/null +++ b/selfdrive/mapd/tests/test_map_match_frontage.py @@ -0,0 +1,251 @@ +"""Current-road match must not jump to a parallel frontage road. + +Stickiness keeps the previous way while it is close and heading-aligned. +A lower-class road far below ego speed has to persist ~5 s or ~150 m. +Same-road signed drops and the #53 cross-street cases stay immediate. +""" +import pytest + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.constants import ( + DECREASE_START_MARGIN_M, + LOOKAHEAD_NORMAL, +) +from openpilot.selfdrive.mapd.map_speed_policy import anticipatory_limit_ms +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB, _offset_point + +MOTORWAY_ID = 1 +FRONTAGE_ID = 2 +RAMP_ID = 3 +ORIGIN = (45.0, -94.0) +ROAD_BEARING = 90.0 +FRONTAGE_M = 28.0 + + +def _build(tmp_path, ways): + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + for way_id, name, highway, limit_mph, coords in ways: + OsmSpeedLimitDB.insert_way(con, way_id, name, highway, limit_mph * CV.MPH_TO_MS, coords) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + return db + + +def _line(start, bearing, length_m, n=5): + step = float(length_m) / n + return [_offset_point(start[0], start[1], bearing, step * i) for i in range(n + 1)] + + +def _north_of(lat, lon, meters): + return _offset_point(lat, lon, 0.0, meters) + + +def _frontage_db(tmp_path, separation_m=FRONTAGE_M): + motorway = _line(ORIGIN, ROAD_BEARING, 2500.0) + frontage_start = _north_of(ORIGIN[0], ORIGIN[1], separation_m) + frontage = _line(frontage_start, ROAD_BEARING, 2500.0) + return _build(tmp_path, [ + (MOTORWAY_ID, "I-94", "motorway", 70.0, motorway), + (FRONTAGE_ID, "Frontage", "tertiary", 25.0, frontage), + ]) + + +def _along(along_m, lateral_m=0.0): + on_road = _offset_point(ORIGIN[0], ORIGIN[1], ROAD_BEARING, along_m) + if lateral_m == 0.0: + return on_road + return _north_of(on_road[0], on_road[1], lateral_m) + + +def _sample(db, along_m, lateral_m, bearing, v_mph, now_s): + lat, lon = _along(along_m, lateral_m) + return db.lookup( + lat, lon, bearing_deg=bearing, v_ego_ms=v_mph * CV.MPH_TO_MS, now_s=now_s, + ) + + +@pytest.mark.parametrize("bearing", [90.0, 270.0]) +@pytest.mark.parametrize("lateral_m", [0.0, 10.0, 14.0, 20.0]) +def test_parallel_frontage_stays_on_motorway(tmp_path, bearing, lateral_m): + """GPS drift up to 20 m toward a 25 mph frontage 28 m away keeps the 70.""" + db = _frontage_db(tmp_path) + try: + along = 500.0 + now = 1000.0 + first = _sample(db, along, 0.0, bearing, 70.0, now) + assert first is not None and first.way_id == MOTORWAY_ID + for i in range(1, 5): + now += 0.5 + along += 12.0 + m = _sample(db, along, lateral_m, bearing, 70.0, now) + assert m is not None, (bearing, lateral_m, i) + assert m.way_id == MOTORWAY_ID, (bearing, lateral_m, i, m.way_id, m.highway) + assert abs(m.speed_limit_ms - 70.0 * CV.MPH_TO_MS) < 0.3 + finally: + db.close() + + +@pytest.mark.parametrize("bearing", [90.0, 270.0]) +def test_nearer_parallel_road_does_not_steal_without_clear_advantage(tmp_path, bearing): + """Tertiary is nearer, but not 9 m nearer, and ego is not 20 mph over its limit. + + Nearest-wins would take the frontage. Stickiness must keep the motorway. + """ + db = _frontage_db(tmp_path) + try: + # 16 m toward a road 28 m away: motorway 16 m, tertiary 12 m (4 m closer). + lateral_m = 16.0 + along = 500.0 + now = 2000.0 + anchored = _sample(db, along, 0.0, bearing, 40.0, now) + assert anchored is not None and anchored.way_id == MOTORWAY_ID + for i in range(8): + now += 0.5 + along += 15.0 + m = _sample(db, along, lateral_m, bearing, 40.0, now) + assert m is not None + assert m.way_id == MOTORWAY_ID, (bearing, i, m.way_id, m.distance_m) + finally: + db.close() + + +def test_exit_to_slower_road_switches_within_5s(tmp_path): + """A real departure onto a lower road is accepted after persistence, within ~5 s.""" + gore = _offset_point(ORIGIN[0], ORIGIN[1], ROAD_BEARING, 400.0) + ramp_bearing = 30.0 + motorway = _line(ORIGIN, ROAD_BEARING, 800.0) + ramp = _line(gore, ramp_bearing, 500.0) + db = _build(tmp_path, [ + (MOTORWAY_ID, "I-94", "motorway", 70.0, motorway), + (RAMP_ID, "Exit", "tertiary", 25.0, ramp), + ]) + try: + now = 3000.0 + on_hwy = _offset_point(ORIGIN[0], ORIGIN[1], ROAD_BEARING, 200.0) + anchored = db.lookup(on_hwy[0], on_hwy[1], bearing_deg=ROAD_BEARING, v_ego_ms=70.0 * CV.MPH_TO_MS, now_s=now) + assert anchored is not None and anchored.way_id == MOTORWAY_ID + + def at_ramp(dist_m, t): + lat, lon = _offset_point(gore[0], gore[1], ramp_bearing, dist_m) + return db.lookup(lat, lon, bearing_deg=ramp_bearing, v_ego_ms=50.0 * CV.MPH_TO_MS, now_s=t) + + # Far enough down the ramp that the motorway is no longer the road under us. + early = at_ramp(120.0, now + 0.5) + assert early is None or early.way_id != RAMP_ID + still = at_ramp(120.0, now + 0.5 + 4.0) + assert still is None or still.way_id != RAMP_ID + switched = at_ramp(120.0, now + 0.5 + 5.0) + assert switched is not None + assert switched.way_id == RAMP_ID + assert abs(switched.speed_limit_ms - 25.0 * CV.MPH_TO_MS) < 0.3 + finally: + db.close() + + +def test_exit_persists_by_distance_before_5s(tmp_path): + """~150 m on the slower road accepts the match even when 5 s have not elapsed.""" + gore = _offset_point(ORIGIN[0], ORIGIN[1], ROAD_BEARING, 400.0) + ramp_bearing = 30.0 + db = _build(tmp_path, [ + (MOTORWAY_ID, "I-94", "motorway", 70.0, _line(ORIGIN, ROAD_BEARING, 800.0)), + (RAMP_ID, "Exit", "tertiary", 25.0, _line(gore, ramp_bearing, 800.0)), + ]) + try: + now = 4000.0 + on_hwy = _offset_point(ORIGIN[0], ORIGIN[1], ROAD_BEARING, 200.0) + anchored = db.lookup(on_hwy[0], on_hwy[1], bearing_deg=ROAD_BEARING, v_ego_ms=55.0 * CV.MPH_TO_MS, now_s=now) + assert anchored is not None and anchored.way_id == MOTORWAY_ID + accepted = None + for i in range(0, 20): + dist = 120.0 + 10.0 * i + now += 0.1 + lat, lon = _offset_point(gore[0], gore[1], ramp_bearing, dist) + m = db.lookup(lat, lon, bearing_deg=ramp_bearing, v_ego_ms=55.0 * CV.MPH_TO_MS, now_s=now) + if m is not None and m.way_id == RAMP_ID: + accepted = (i, dist, now) + break + assert m is None or m.way_id != RAMP_ID + assert accepted is not None + _i, dist, t = accepted + assert dist - 120.0 >= 140.0 + assert t - 4000.0 < 5.0 + finally: + db.close() + + +def test_same_road_signed_drop_is_not_delayed(tmp_path): + """70 → 55 on the same motorway still publishes next, then the new posted limit.""" + assert DECREASE_START_MARGIN_M == 110.0 + split = _offset_point(ORIGIN[0], ORIGIN[1], ROAD_BEARING, 600.0) + end = _offset_point(split[0], split[1], ROAD_BEARING, 600.0) + db = _build(tmp_path, [ + (MOTORWAY_ID, "I-94", "motorway", 70.0, [ORIGIN, split]), + (4, "I-94", "motorway", 55.0, [split, end]), + ]) + try: + v70 = 70.0 * CV.MPH_TO_MS + before = _offset_point(split[0], split[1], ROAD_BEARING + 180.0, 200.0) + m = db.lookup(before[0], before[1], bearing_deg=ROAD_BEARING, v_ego_ms=v70, now_s=5000.0) + assert m is not None + assert m.way_id == MOTORWAY_ID + assert abs(m.speed_limit_ms - v70) < 0.3 + assert abs(m.next_speed_limit_ms - 55.0 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + assert m.next_distance_m > 40.0 + eased = anticipatory_limit_ms( + m.speed_limit_ms, m.next_speed_limit_ms, m.next_distance_m, v70, LOOKAHEAD_NORMAL, + ) + assert eased is not None + assert m.next_speed_limit_ms <= eased < m.speed_limit_ms + + after = _offset_point(split[0], split[1], ROAD_BEARING, 40.0) + m2 = db.lookup(after[0], after[1], bearing_deg=ROAD_BEARING, v_ego_ms=v70, now_s=5000.5) + assert m2 is not None + assert m2.way_id == 4 + assert abs(m2.speed_limit_ms - 55.0 * CV.MPH_TO_MS) < 0.3 + finally: + db.close() + + +def test_dropout_lower_class_rematch_waits_for_persistence(tmp_path): + """A minor road appearing after a dropout, far below ego speed, is not instant.""" + db = _build(tmp_path, [ + (MOTORWAY_ID, "I-94", "motorway", 70.0, _line(ORIGIN, ROAD_BEARING, 400.0)), + (FRONTAGE_ID, "Oak", "residential", 25.0, _line((46.0, -94.0), ROAD_BEARING, 400.0)), + ]) + try: + v70 = 70.0 * CV.MPH_TO_MS + on = _offset_point(ORIGIN[0], ORIGIN[1], ROAD_BEARING, 100.0) + m = db.lookup(on[0], on[1], bearing_deg=ROAD_BEARING, v_ego_ms=v70, now_s=6000.0) + assert m is not None and m.way_id == MOTORWAY_ID + assert db.lookup(44.0, -94.0, bearing_deg=ROAD_BEARING, v_ego_ms=v70, now_s=6001.0) is None + minor = _offset_point(46.0, -94.0, ROAD_BEARING, 100.0) + early = db.lookup(minor[0], minor[1], bearing_deg=ROAD_BEARING, v_ego_ms=v70, now_s=6002.0) + assert early is None or early.way_id != FRONTAGE_ID + later = db.lookup(minor[0], minor[1], bearing_deg=ROAD_BEARING, v_ego_ms=v70, now_s=6007.0) + assert later is not None + assert later.way_id == FRONTAGE_ID + finally: + db.close() + + +def test_cross_street_still_does_not_steal_current_road(tmp_path): + """#53 intersecting-road case: GPS on the side street, heading along the highway.""" + db = _build(tmp_path, [ + (MOTORWAY_ID, "Main", "primary", 60.0, [(37.0, -122.004), (37.0, -121.996)]), + (FRONTAGE_ID, "Oak", "residential", 30.0, [(36.997, -122.000), (37.003, -122.000)]), + ]) + try: + qlat, qlon = _offset_point(37.0, -122.000, 0.0, 5.0) + now = 7000.0 + for _ in range(4): + m = db.lookup(qlat, qlon, bearing_deg=90.0, v_ego_ms=60.0 * CV.MPH_TO_MS, now_s=now) + now += 0.5 + assert m is not None + assert m.way_id == MOTORWAY_ID + assert abs(m.speed_limit_ms - 60.0 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0 + finally: + db.close() diff --git a/selfdrive/mapd/tests/test_map_match_road_class.py b/selfdrive/mapd/tests/test_map_match_road_class.py new file mode 100644 index 00000000000000..47b27d412a99ad --- /dev/null +++ b/selfdrive/mapd/tests/test_map_match_road_class.py @@ -0,0 +1,134 @@ +"""Non-road ways (golf-cart paths etc.) are never the posted speed limit. + +Oct 1-3 routes near a golf course: the real road (`highway=residential`) had no +`maxspeed` in OSM, so it was not in the pack. The only stored way within +MAX_MATCH_DISTANCE_M was a `highway=path golf=path maxspeed=5 mph` cart path, and +HUD MAX locked to 5 mph. The class filter lives in `_best_match` (so +`_next_limit` and the min-zone probes inherit it) and NOT in `_candidates()`, +which roundabout ring detection shares. There is deliberately no mph floor. +""" +import pytest + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB, _offset_point + +ORIGIN = (35.5225, -83.0510) +BEARING = 90.0 +ROAD_ID = 10 +PATH_ID = 20 +NON_ROAD = ("path", "footway", "cycleway", "bridleway", "steps", "pedestrian", "track") + + +def _build(tmp_path, ways): + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + for way_id, name, highway, mph, coords, *junction in ways: + OsmSpeedLimitDB.insert_way( + con, way_id, name, highway, mph * CV.MPH_TO_MS, coords, junction=(junction[0] if junction else ""), + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + return db + + +def _line(start, bearing, length_m, n=8): + step = float(length_m) / n + return [_offset_point(start[0], start[1], bearing, step * i) for i in range(n + 1)] + + +def _beside(lateral_m, length_m=600.0, start_along=0.0): + """Parallel line `lateral_m` north of the road axis.""" + base = _offset_point(ORIGIN[0], ORIGIN[1], BEARING, start_along) + return _line(_offset_point(base[0], base[1], 0.0, lateral_m), BEARING, length_m) + + +def _lookup(db, along_m, v_mph=30.0, now=100.0): + lat, lon = _offset_point(ORIGIN[0], ORIGIN[1], BEARING, along_m) + return db.lookup(lat, lon, bearing_deg=BEARING, v_ego_ms=v_mph * CV.MPH_TO_MS, now_s=now) + + +@pytest.mark.parametrize("highway", NON_ROAD) +def test_non_road_way_alone_is_not_matched(tmp_path, highway): + """The logged case: only the cart path is stored near the untagged road.""" + db = _build(tmp_path, [(PATH_ID, "", highway, 5.0, _beside(8.0))]) + try: + assert _lookup(db, 300.0) is None + finally: + db.close() + + +@pytest.mark.parametrize("highway", NON_ROAD) +def test_non_road_way_does_not_beat_a_farther_tagged_road(tmp_path, highway): + db = _build(tmp_path, [ + (PATH_ID, "", highway, 5.0, _beside(4.0)), + (ROAD_ID, "Country Club Drive", "residential", 25.0, _beside(24.0)), + ]) + try: + m = _lookup(db, 300.0) + assert m is not None + assert m.way_id == ROAD_ID + assert m.speed_limit_ms == pytest.approx(25.0 * CV.MPH_TO_MS) + finally: + db.close() + + +@pytest.mark.parametrize("highway", ["service", "residential", "unclassified", "living_street", "tertiary"]) +def test_low_limit_on_a_road_class_is_still_matched(tmp_path, highway): + """Class filter only: no mph floor. A tagged 10 mph road keeps its limit.""" + db = _build(tmp_path, [(ROAD_ID, "Lot Ln", highway, 10.0, _beside(3.0))]) + try: + m = _lookup(db, 300.0, v_mph=8.0) + assert m is not None and m.way_id == ROAD_ID + assert m.speed_limit_ms == pytest.approx(10.0 * CV.MPH_TO_MS) + finally: + db.close() + + +def _road_then(highway, mph, name=""): + main = _line(ORIGIN, BEARING, 400.0, n=16) + cont = _line(main[-1], BEARING, 400.0, n=16) + return [ + (ROAD_ID, "Main St", "primary", 45.0, main), + (PATH_ID, name, highway, mph, cont), + ] + + +def test_next_limit_follows_a_road_class_continuation(tmp_path): + """Control: the same geometry with a real road ahead does publish next.""" + db = _build(tmp_path, _road_then("tertiary", 25.0)) + try: + m = _lookup(db, 250.0, v_mph=45.0) + assert m is not None and m.way_id == ROAD_ID + assert m.next_speed_limit_ms == pytest.approx(25.0 * CV.MPH_TO_MS, abs=0.3) + finally: + db.close() + + +@pytest.mark.parametrize("highway", NON_ROAD) +def test_next_limit_ignores_a_non_road_way_ahead(tmp_path, highway): + """A cart path continuing the road line must not become nextSpeedLimit (early ease).""" + db = _build(tmp_path, _road_then(highway, 5.0)) + try: + m = _lookup(db, 250.0, v_mph=45.0) + assert m is not None and m.way_id == ROAD_ID + assert m.next_speed_limit_ms == 0.0 + assert m.next_distance_m == 0.0 + finally: + db.close() + + +def test_junction_tagged_ring_is_found_even_in_a_non_road_class(tmp_path): + """Roundabout ring detection shares `_candidates()`; the class filter must not live there.""" + ring_c = _offset_point(ORIGIN[0], ORIGIN[1], BEARING, 400.0) + ring = [_offset_point(ring_c[0], ring_c[1], 360.0 * i / 20, 22.5) for i in range(20)] + ring.append(ring[0]) + db = _build(tmp_path, [(PATH_ID, "", "cycleway", 20.0, ring, "roundabout")]) + try: + lat, lon = _offset_point(ORIGIN[0], ORIGIN[1], BEARING, 300.0) + hint = db.find_roundabout(lat, lon, bearing_deg=BEARING) + assert hint.approaching or hint.on_roundabout + assert hint.way_id == PATH_ID + finally: + db.close() diff --git a/selfdrive/mapd/tests/test_map_speed_offset_slew.py b/selfdrive/mapd/tests/test_map_speed_offset_slew.py new file mode 100644 index 00000000000000..537604b19a2bad --- /dev/null +++ b/selfdrive/mapd/tests/test_map_speed_offset_slew.py @@ -0,0 +1,165 @@ +"""Map-speed offset is applied once. Slew state stays in raw-limit units. + +Engage / posted-raise seeds are posted+offset on the pedal, but `_map_slew_ms` +is the raw OSM limit because `apply_map_speed_kph` adds the offset again. +A self-written pedal step must not be read as a driver stalk press. +""" +import types +from types import SimpleNamespace + +import pytest + +from opendbc.car import DT_CTRL +from openpilot.common.constants import CV +from openpilot.selfdrive.car.card import Car +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.selfdrive.controls.lib.curve_max_hold import CurveMaxHold +from openpilot.selfdrive.mapd.constants import ACCEL_DEFAULT, LOOKAHEAD_NORMAL, MODE_FOLLOW +from openpilot.selfdrive.mapd.map_speed_policy import MapCruiseHold + + +class _Cruise: + def __init__(self): + self.v_cruise_kph = float(V_CRUISE_UNSET) + self.v_cruise_kph_last = 0.0 + self.v_cruise_cluster_kph = float(V_CRUISE_UNSET) + + +class _MapSm: + def __init__(self, md): + self.valid = {"liveMapDataNAP": True} + self._md = md + + def __getitem__(self, key): + if key == "liveMapDataNAP": + return self._md + raise KeyError(key) + + +def _harness(offset_kph: float, limit_kph: float, v_ego_kph: float): + md = SimpleNamespace( + speedLimit=float(limit_kph) * CV.KPH_TO_MS, + speedLimitValid=True, + nextSpeedLimit=0.0, + nextSpeedLimitDistance=0.0, + ) + v_ego_ms = float(v_ego_kph) * CV.KPH_TO_MS + cs = SimpleNamespace( + cruiseState=SimpleNamespace(speed=v_ego_ms, enabled=True), + pedalLongActive=True, + enableLongControl=True, + vEgo=v_ego_ms, + steeringAngleDeg=0.0, + buttonEvents=[], + ) + h = SimpleNamespace( + CS_prev=SimpleNamespace(pedalLongActive=False, cruiseState=SimpleNamespace(speed=v_ego_ms)), + CI=None, + CP=SimpleNamespace(steerRatio=15.0, wheelbase=2.98), + sm=_MapSm(md), + _map_hold=MapCruiseHold(), + _curve_max=CurveMaxHold(), + _map_slew_ms=None, + _last_pedal_kph=None, + _pedal_self_write_kph=None, + _map_speed_mode=MODE_FOLLOW, + _map_speed_lookahead=LOOKAHEAD_NORMAL, + _map_speed_accel=ACCEL_DEFAULT, + _map_speed_user_offset_kph=float(offset_kph), + _map_hypermile_on=False, + _map_step_down_on=False, + v_cruise_helper=_Cruise(), + _maybe_follow_stalk=lambda _cs, raw_kph: (raw_kph, False), + ) + for name in ( + "_preap_engagement", "_preap_set_events", "_adopt_preap_fsm_held_max", + "_publish_preap_held_max", "_curve_cornering", "_live_map_offset_kph", + "_write_preap_pedal_speed", + ): + setattr(h, name, types.MethodType(getattr(Car, name), h)) + h._preap_stalk_set_pressed = Car._preap_stalk_set_pressed + return h, cs, md + + +def _step(h, cs, *, first: bool) -> None: + h.CS_prev.pedalLongActive = False if first else True + Car._update_preap_map_cruise(h, cs) + + +def _run_s(h, cs, seconds: float, *, first: bool = True) -> None: + n = max(1, int(round(float(seconds) / DT_CTRL))) + for i in range(n): + _step(h, cs, first=first and i == 0) + + +def _expect_max(h, expected_kph: float) -> None: + assert h._map_hold.sticky_set_kph is None + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(expected_kph, abs=0.05) + + +@pytest.mark.parametrize("offset_mph", range(0, 11)) +def test_engage_mph_offset_is_limit_plus_offset_after_1s(offset_mph): + """55 mph engage: MAX is exactly limit+offset after 1 s, and not a sticky stalk set.""" + limit_kph = 55.0 * CV.MPH_TO_KPH + offset_kph = float(offset_mph) * CV.MPH_TO_KPH + h, cs, _md = _harness(offset_kph, limit_kph, limit_kph) + # 0.2 s is before a double-added 1 mph/1 kph offset can slew back to the limit. + _run_s(h, cs, 0.2) + _expect_max(h, limit_kph + offset_kph) + _run_s(h, cs, 0.8, first=False) + _expect_max(h, limit_kph + offset_kph) + + +@pytest.mark.parametrize("offset_kph", [0.0, 1.0, 5.0, 10.0]) +def test_engage_kph_offset_is_limit_plus_offset_after_1s(offset_kph): + """Same contract in kph. 1 and 5 kph are stalk steps and must not latch sticky.""" + limit_kph = 80.0 + h, cs, _md = _harness(float(offset_kph), limit_kph, limit_kph) + _run_s(h, cs, 0.2) + _expect_max(h, limit_kph + float(offset_kph)) + _run_s(h, cs, 0.8, first=False) + _expect_max(h, limit_kph + float(offset_kph)) + + +def test_posted_raise_keeps_single_offset(): + """55 → 65 with +5 mph lands on 70, not 75.""" + offset_kph = 5.0 * CV.MPH_TO_KPH + limit_55 = 55.0 * CV.MPH_TO_KPH + limit_65 = 65.0 * CV.MPH_TO_KPH + h, cs, md = _harness(offset_kph, limit_55, limit_55) + _run_s(h, cs, 1.0) + _expect_max(h, limit_55 + offset_kph) + md.speedLimit = limit_65 * CV.KPH_TO_MS + _run_s(h, cs, 1.0, first=False) + _expect_max(h, limit_65 + offset_kph) + + +def test_self_written_pedal_step_is_not_a_stalk(): + """A pedal jump this code just wrote is not a driver stalk press.""" + offset_kph = 5.0 * CV.MPH_TO_KPH + limit_kph = 55.0 * CV.MPH_TO_KPH + h, cs, _md = _harness(offset_kph, limit_kph, limit_kph) + _run_s(h, cs, 1.0) + held = float(h.v_cruise_helper.v_cruise_kph) + jumped = held + 5.0 * CV.MPH_TO_KPH + h._pedal_self_write_kph = jumped + cs.cruiseState.speed = jumped * CV.KPH_TO_MS + _step(h, cs, first=False) + assert h._map_hold.sticky_set_kph is None + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(held, abs=0.05) + + +def test_driver_stalk_step_still_latches_follow(): + """A real 5 mph stalk step, not a self-write, still latches Follow.""" + offset_kph = 5.0 * CV.MPH_TO_KPH + limit_kph = 55.0 * CV.MPH_TO_KPH + h, cs, _md = _harness(offset_kph, limit_kph, limit_kph) + _run_s(h, cs, 1.0) + held = float(h.v_cruise_helper.v_cruise_kph) + stalk = held + 5.0 * CV.MPH_TO_KPH + h._pedal_self_write_kph = None + cs.cruiseState.speed = stalk * CV.KPH_TO_MS + _step(h, cs, first=False) + assert h._map_hold.sticky_set_kph is not None + assert h._map_hold.sticky_set_kph == pytest.approx(stalk, abs=0.05) + assert h.v_cruise_helper.v_cruise_kph == pytest.approx(stalk, abs=0.05) diff --git a/selfdrive/mapd/tests/test_map_speed_policy.py b/selfdrive/mapd/tests/test_map_speed_policy.py new file mode 100644 index 00000000000000..60f9387f60e2ed --- /dev/null +++ b/selfdrive/mapd/tests/test_map_speed_policy.py @@ -0,0 +1,852 @@ +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.constants import ( + ACCEL_DEFAULT, DECREASE_START_MARGIN_M, LOOKAHEAD_EARLY, LOOKAHEAD_NORMAL, LOOKAHEAD_OFF, + LOOKAHEAD_TUNING, MODE_CAP, MODE_DISPLAY, MODE_FOLLOW, MODE_OFF, OSM_SIGN_LEAD_S, + TRACK_DEADBAND_MS, TRACK_TAPER_MS, + accel_scale_factor, map_accel_a_ms2, map_brake_a_ms2, map_comfort_a_ms2, +) +from openpilot.selfdrive.mapd.map_speed_policy import ( + SOURCE_CRUISE, SOURCE_LEAD0, V_CRUISE_UNSET, + MapCruiseHold, anticipatory_limit_ms, apply_map_speed_kph, cap_planner_v_cruise_ms, + decide_map_cruise, effective_map_limit_ms, longitudinal_obstacle_source, map_climb_replaces_mpc, map_in_track_deadband, map_slew_a_ms2, + map_track_accel_ms2, map_track_decel_ms2, should_write_preap_pedal, +) +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + MAP_SPEED_ACCEL, MAP_SPEED_ACCEL_DEFAULT, MAP_SPEED_LOOKAHEAD, +) + +# Keep in sync with long_mpc (avoid importing cereal/acados here). +_COMFORT_BRAKE = 2.5 +_STOP_DISTANCE = 6.0 +_T_FOLLOW = 1.45 # LongitudinalPersonality.standard + + +def _cruise_obstacle_m(v_cruise_ms: float) -> float: + return (v_cruise_ms ** 2) / (2 * _COMFORT_BRAKE) + _T_FOLLOW * v_cruise_ms + _STOP_DISTANCE + + +def _lead_obstacle_m(d_rel: float, v_lead: float) -> float: + return d_rel + (v_lead ** 2) / (2 * _COMFORT_BRAKE) + + +def test_off_and_display_never_change_driver_set(): + for mode in (MODE_OFF, MODE_DISPLAY): + assert apply_map_speed_kph(100, 70, mode=mode, engaged=True, op_long_software_cruise=True) == 100 + + +def test_cap_lowers_but_does_not_raise(): + assert apply_map_speed_kph(100, 70, mode=MODE_CAP, engaged=True, op_long_software_cruise=True) == 70 + assert apply_map_speed_kph(50, 70, mode=MODE_CAP, engaged=True, op_long_software_cruise=True) == 50 + + +def test_follow_tracks_map_unless_override(): + assert apply_map_speed_kph(100, 70, mode=MODE_FOLLOW, engaged=True, op_long_software_cruise=True) == 70 + assert apply_map_speed_kph(50, 70, mode=MODE_FOLLOW, engaged=True, op_long_software_cruise=True) == 70 + assert apply_map_speed_kph(100, 70, mode=MODE_FOLLOW, engaged=True, op_long_software_cruise=True, + driver_override=True) == 100 + + +def test_follow_raises_when_offset_posted_is_already_higher(): + """GNSS lag: posted at v*1.5 s is already 45 → Follow MAX 45. Far-ahead next does not.""" + a = 25 * CV.MPH_TO_KPH + b = 45 * CV.MPH_TO_KPH + assert apply_map_speed_kph(a, b, mode=MODE_FOLLOW, engaged=True, op_long_software_cruise=True) == b + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=b, + engage_rising=False, now=1.0, stalk_pressed=False, + ) + assert not dec.sticky + assert dec.seed_kph is not None + assert abs(dec.seed_kph - b) < 1e-6 + assert abs(_follow_hud(dec, b) - b) < 1e-6 + # Lookahead path is still decrease-only (not this 1.5 s offset). + v25 = 25 * CV.MPH_TO_MS + v45 = 45 * CV.MPH_TO_MS + assert anticipatory_limit_ms(v25, v45, 80.0, v25, LOOKAHEAD_EARLY) is None + assert effective_map_limit_ms(v25, v45, 80.0, v25, LOOKAHEAD_NORMAL) == v25 + + +def test_pcm_cruise_never_gets_control_overlay(): + # No-pedal stock CC: do not invent a parallel set-speed path + assert apply_map_speed_kph(100, 70, mode=MODE_CAP, engaged=True, op_long_software_cruise=False) == 100 + assert apply_map_speed_kph(100, 70, mode=MODE_FOLLOW, engaged=True, op_long_software_cruise=False) == 100 + + +def test_disengaged_or_unset_passthrough(): + assert apply_map_speed_kph(100, 70, mode=MODE_CAP, engaged=False, op_long_software_cruise=True) == 100 + assert apply_map_speed_kph(V_CRUISE_UNSET, 70, mode=MODE_CAP, engaged=True, op_long_software_cruise=True) == V_CRUISE_UNSET + assert apply_map_speed_kph(100, None, mode=MODE_CAP, engaged=True, op_long_software_cruise=True) == 100 + + +def test_offset_applies_to_map_target(): + offset = 5 * CV.MPH_TO_KPH + out = apply_map_speed_kph(120, 70, mode=MODE_CAP, offset_kph=offset, engaged=True, op_long_software_cruise=True) + assert abs(out - (70 + offset)) < 0.05 + + +def test_planner_cap_is_down_only(): + lim = 25.0 # m/s + # Trust HUD: min() with posted snapped Cap/Follow when GPS entered a lower zone. + assert cap_planner_v_cruise_ms(30.0, lim, mode=MODE_CAP) == 30.0 + assert cap_planner_v_cruise_ms(20.0, lim, mode=MODE_CAP) == 20.0 + assert cap_planner_v_cruise_ms(30.0, lim, mode=MODE_DISPLAY) == 30.0 + assert cap_planner_v_cruise_ms(30.0, None, mode=MODE_FOLLOW) == 30.0 + + +def test_follow_planner_trusts_hud_not_posted(): + """Sticky 66 with posted 60 must not clip MPC v_cruise to 60. Cap eases the same.""" + hud = 66 * CV.MPH_TO_MS + posted = 60 * CV.MPH_TO_MS + assert cap_planner_v_cruise_ms(hud, posted, mode=MODE_FOLLOW) == hud + below = 55 * CV.MPH_TO_MS + assert cap_planner_v_cruise_ms(below, posted, mode=MODE_FOLLOW) == below + assert cap_planner_v_cruise_ms(hud, posted, mode=MODE_CAP) == hud + + +def test_no_lead_tracks_map_capped_cruise(): + """No radar lead: fake far/fast lead, so cruise (map ceiling) is the tightest obstacle.""" + v_ego = 31.29 # ~70 mph + v_cruise = cap_planner_v_cruise_ms(31.29, 31.29, mode=MODE_CAP) + assert abs(v_cruise - 31.29) < 1e-6 + cruise = _cruise_obstacle_m(v_cruise) + fake = _lead_obstacle_m(50.0, v_ego + 10.0) + assert longitudinal_obstacle_source(fake, fake, cruise) == SOURCE_CRUISE + + +def test_slower_lead_still_commands_below_map_ceiling(): + """Close slower lead must win min(lead, cruise) regardless of map v_cruise.""" + lead = _lead_obstacle_m(40.0, 15.0) + for v_cruise in (20.0, 31.29, 40.0): + capped = cap_planner_v_cruise_ms(v_cruise, 31.29, mode=MODE_CAP) + cruise = _cruise_obstacle_m(capped) + assert longitudinal_obstacle_source(lead, 1e8, cruise) == SOURCE_LEAD0 + assert min(lead, cruise) == lead + + +def test_upcoming_lower_limit_lowers_target_early(): + current = 70 * CV.MPH_TO_MS + nxt = 45 * CV.MPH_TO_MS + # Well inside Normal horizon (400 m) and braking window. + early = anticipatory_limit_ms(current, nxt, 200.0, current, LOOKAHEAD_NORMAL) + assert early is not None + assert nxt - 1e-6 <= early < current + # Closer to the sign → closer to the new limit (smooth profile). + closer = anticipatory_limit_ms(current, nxt, 60.0, current, LOOKAHEAD_NORMAL) + assert closer is not None and closer <= early + 1e-9 + assert closer < current + eff = effective_map_limit_ms(current, nxt, 200.0, current, LOOKAHEAD_NORMAL) + assert eff is not None and eff < current + # HUD/planner use this as the map ceiling (Cap never raises). + assert apply_map_speed_kph( + 120, eff * CV.MS_TO_KPH, mode=MODE_CAP, engaged=True, op_long_software_cruise=True, + ) < 70 * CV.MPH_TO_KPH + 0.1 + + +def test_upcoming_higher_limit_does_not_raise_early(): + current = 45 * CV.MPH_TO_MS + nxt = 70 * CV.MPH_TO_MS + assert anticipatory_limit_ms(current, nxt, 80.0, current, LOOKAHEAD_EARLY) is None + assert effective_map_limit_ms(current, nxt, 80.0, current, LOOKAHEAD_NORMAL) == current + # Follow still uses the *current* match (raises only once GPS is on the faster way). + assert apply_map_speed_kph( + 50, current * CV.MS_TO_KPH, mode=MODE_FOLLOW, engaged=True, op_long_software_cruise=True, + ) == current * CV.MS_TO_KPH + + +def test_lookahead_off_and_far_away_keep_current(): + current = 70 * CV.MPH_TO_MS + nxt = 35 * CV.MPH_TO_MS + assert anticipatory_limit_ms(current, nxt, 80.0, current, LOOKAHEAD_OFF) is None + assert effective_map_limit_ms(current, nxt, 80.0, current, LOOKAHEAD_OFF) == current + # Beyond Normal horizon (600 m) — do not start yet. + assert anticipatory_limit_ms(current, nxt, 620.0, current, LOOKAHEAD_NORMAL) is None + # Display never changes MAX even if we computed an anticipatory ceiling. + assert apply_map_speed_kph( + 100, 45, mode=MODE_DISPLAY, engaged=True, op_long_software_cruise=True, + ) == 100 + + +def test_anticipatory_cap_still_loses_to_slower_lead(): + current = 70 * CV.MPH_TO_MS + nxt = 45 * CV.MPH_TO_MS + eff = effective_map_limit_ms(current, nxt, 150.0, current, LOOKAHEAD_NORMAL) + assert eff is not None + # Planner trusts HUD (already eased); min() with posted would snap at the zone. + v_cruise = cap_planner_v_cruise_ms(eff, current, mode=MODE_CAP) + assert v_cruise == eff + assert v_cruise < current + lead = _lead_obstacle_m(40.0, 15.0) + cruise = _cruise_obstacle_m(v_cruise) + assert longitudinal_obstacle_source(lead, 1e8, cruise) == SOURCE_LEAD0 + assert min(lead, cruise) == lead + + +def test_accel_default_five_matches_prior_normal_curve(): + assert ACCEL_DEFAULT == 5 + assert MAP_SPEED_ACCEL_DEFAULT == 5 + assert MAP_SPEED_ACCEL == list(range(1, 11)) + assert MAP_SPEED_LOOKAHEAD == [0, 1, 2, 3] + assert abs(accel_scale_factor(5) - 1.0) < 1e-9 + assert abs(map_comfort_a_ms2(LOOKAHEAD_NORMAL, 5) - 0.80) < 1e-9 + assert abs(map_comfort_a_ms2(LOOKAHEAD_NORMAL, 1) - 0.36) < 1e-9 + assert abs(map_comfort_a_ms2(LOOKAHEAD_NORMAL, 10) - 1.60) < 1e-9 + current = 70 * CV.MPH_TO_MS + nxt = 45 * CV.MPH_TO_MS + a5 = anticipatory_limit_ms(current, nxt, 200.0, current, LOOKAHEAD_NORMAL, 5) + a_default = anticipatory_limit_ms(current, nxt, 200.0, current, LOOKAHEAD_NORMAL) + assert a5 is not None and a_default is not None + assert abs(a5 - a_default) < 1e-9 + # Accel 1–10 must not change anticipatory decreases (brake locked at 5). + a1 = anticipatory_limit_ms(current, nxt, 200.0, current, LOOKAHEAD_NORMAL, 1) + a10 = anticipatory_limit_ms(current, nxt, 200.0, current, LOOKAHEAD_NORMAL, 10) + assert a1 is not None and a10 is not None + assert abs(a1 - a5) < 1e-9 and abs(a10 - a5) < 1e-9 + assert anticipatory_limit_ms(current, nxt, 300.0, current, LOOKAHEAD_NORMAL, 1) is not None + assert anticipatory_limit_ms(current, nxt, 300.0, current, LOOKAHEAD_NORMAL, 10) is not None + + +def test_fifty_to_thirty_starts_one_hundred_ten_m_before_kinematic(): + """Justin: 50→30 still ~42 mph at the sign. Keep brake 0.80; start kin+110 m earlier.""" + v50 = 50 * CV.MPH_TO_MS + v30 = 30 * CV.MPH_TO_MS + assert abs(v50 - 22.352) < 0.002 + assert abs(18.776 - 42 * CV.MPH_TO_MS) < 0.002 + assert abs(v30 - 13.411) < 0.002 + a = map_brake_a_ms2(LOOKAHEAD_NORMAL) + assert abs(a - 0.80) < 1e-9 + assert abs(DECREASE_START_MARGIN_M - 110.0) < 1e-9 + assert abs(OSM_SIGN_LEAD_S - 1.5) < 1e-9 + # Sign lead is time*speed, not an extra meter constant on decreases. + assert a < 1.5 # Tesla pre-AP clip + for la, tun in LOOKAHEAD_TUNING.items(): + if tun[0] <= 0: + continue + assert tun[0] < 1.5 + extra = DECREASE_START_MARGIN_M + (120.0 if la == LOOKAHEAD_EARLY else 0.0) + assert abs(tun[1] - extra) < 1e-9 + kin_m = (v50 * v50 - v30 * v30) / (2.0 * a) + assert abs(kin_m - 200.0) < 1.0 + leftover_m = (18.776 * 18.776 - v30 * v30) / (2.0 * 0.80) + assert abs(leftover_m - 108.0) < 2.0 + # Window opens at kin+110; MAX is still 50 on that edge, then falls toward 30. + at_open = anticipatory_limit_ms(v50, v30, kin_m + DECREASE_START_MARGIN_M, v50, LOOKAHEAD_NORMAL) + assert at_open is not None + assert abs(at_open - v50) < 0.6 + assert anticipatory_limit_ms(v50, v30, kin_m + DECREASE_START_MARGIN_M + 5.0, v50, LOOKAHEAD_NORMAL) is None + at_kin = anticipatory_limit_ms(v50, v30, kin_m, v50, LOOKAHEAD_NORMAL) + assert at_kin is not None + assert at_kin < v50 - 1.0 + near_sign = anticipatory_limit_ms(v50, v30, 5.0, v50, LOOKAHEAD_NORMAL) + assert near_sign is not None + assert abs(near_sign - v30) < 1.5 + # Same extra start margin on any decrease — not a 50→30-only window. + v70 = 70 * CV.MPH_TO_MS + v45 = 45 * CV.MPH_TO_MS + kin_7045 = (v70 * v70 - v45 * v45) / (2.0 * a) + assert anticipatory_limit_ms(v70, v45, kin_7045 + DECREASE_START_MARGIN_M, v70, LOOKAHEAD_NORMAL) is not None + assert anticipatory_limit_ms(v70, v45, kin_7045 + DECREASE_START_MARGIN_M + 5.0, v70, LOOKAHEAD_NORMAL) is None + # Higher nextSpeedLimit far ahead must not raise MAX (lookahead is decrease-only). + # The 1.5 s GNSS offset raising posted is tested separately. + assert anticipatory_limit_ms(v30, v50, 80.0, v30, LOOKAHEAD_EARLY) is None + assert anticipatory_limit_ms(v45, v70, 80.0, v45, LOOKAHEAD_EARLY) is None + + +def test_sixty_to_fifty_uses_kin_plus_110_not_min_decrease_skip(): + """10 mph 60→50 must open at kin+110 m. MIN_DECREASE is ~1 mph, not 10.""" + v60 = 60 * CV.MPH_TO_MS + v50 = 50 * CV.MPH_TO_MS + assert (v60 - v50) > 4.0 + a = map_brake_a_ms2(LOOKAHEAD_NORMAL) + assert abs(a - 0.80) < 1e-9 + kin_m = (v60 * v60 - v50 * v50) / (2.0 * a) + assert abs(kin_m - 137.0) < 2.0 + assert anticipatory_limit_ms(v60, v50, kin_m + DECREASE_START_MARGIN_M, v60, LOOKAHEAD_NORMAL) is not None + assert anticipatory_limit_ms(v60, v50, kin_m + DECREASE_START_MARGIN_M + 5.0, v60, LOOKAHEAD_NORMAL) is None + + +def test_sixty_to_fifty_eases_with_lookahead_not_posted_cliff(): + """10 mph 60→50 must interpolate MAX, not seed-snap to 50.""" + v60 = 60 * CV.MPH_TO_MS + v50 = 50 * CV.MPH_TO_MS + a = map_brake_a_ms2(LOOKAHEAD_NORMAL) + kin_m = (v60 * v60 - v50 * v50) / (2.0 * a) + at_open = anticipatory_limit_ms(v60, v50, kin_m + DECREASE_START_MARGIN_M, v60, LOOKAHEAD_NORMAL) + assert at_open is not None + assert abs(at_open - v60) < 0.6 + mid = anticipatory_limit_ms(v60, v50, 80.0, v60, LOOKAHEAD_NORMAL) + assert mid is not None + assert v50 < mid < v60 + at_zone = anticipatory_limit_ms(v60, v50, 0.0, v60, LOOKAHEAD_NORMAL) + assert at_zone is not None and abs(at_zone - v50) < 1e-6 + hold = MapCruiseHold() + a_kph = 60 * CV.MPH_TO_KPH + b_kph = 50 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a_kph, posted_kph=a_kph, + engage_rising=True, now=0.0, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a_kph, posted_kph=b_kph, + engage_rising=False, now=1.0, stalk_pressed=False, + ) + assert not dec.sticky + assert dec.seed_kph is None + raise_dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=b_kph, posted_kph=a_kph, + engage_rising=False, now=2.0, stalk_pressed=False, + ) + assert raise_dec.seed_kph is not None + assert abs(raise_dec.seed_kph - a_kph) < 1e-6 + + +def test_all_posted_decreases_ease_like_fifty_to_thirty(): + """10/15/20 mph and 50→30: kin+110 m interpolate; Cap/Follow must not seed-snap.""" + a = map_brake_a_ms2(LOOKAHEAD_NORMAL) + assert abs(a - 0.80) < 1e-9 + for hi_mph, lo_mph in ((50, 30), (60, 50), (60, 45), (60, 40)): + v_hi = hi_mph * CV.MPH_TO_MS + v_lo = lo_mph * CV.MPH_TO_MS + kin_m = (v_hi * v_hi - v_lo * v_lo) / (2.0 * a) + at_open = anticipatory_limit_ms(v_hi, v_lo, kin_m + DECREASE_START_MARGIN_M, v_hi, LOOKAHEAD_NORMAL) + assert at_open is not None, (hi_mph, lo_mph) + assert abs(at_open - v_hi) < 0.6 + mid = anticipatory_limit_ms(v_hi, v_lo, max(25.0, 0.35 * kin_m), v_hi, LOOKAHEAD_NORMAL) + assert mid is not None and v_lo < mid < v_hi, (hi_mph, lo_mph, mid) + hi_kph, lo_kph = hi_mph * CV.MPH_TO_KPH, lo_mph * CV.MPH_TO_KPH + for mode in (MODE_FOLLOW, MODE_CAP): + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=mode, raw_kph=hi_kph, posted_kph=hi_kph, + engage_rising=True, now=0.0, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=mode, raw_kph=hi_kph, posted_kph=lo_kph, + engage_rising=False, now=1.0, stalk_pressed=False, + ) + assert not dec.sticky + assert dec.seed_kph is None + # Driver stays previous so Cap min(driver, eased map) cannot cliff to lo. + assert abs(dec.driver_kph - hi_kph) < 1e-6 + eased = (v_hi + v_lo) * 0.5 * CV.MS_TO_KPH + cap_out = apply_map_speed_kph( + dec.driver_kph, eased, mode=MODE_CAP, engaged=True, op_long_software_cruise=True, + ) + assert abs(cap_out - eased) < 1e-6 + + +def test_sticky_skips_anticipatory_lookahead(): + """Upcoming 50 must not lower the ceiling while a sticky set is active.""" + current = 60 * CV.MPH_TO_MS + nxt = 50 * CV.MPH_TO_MS + a = map_brake_a_ms2(LOOKAHEAD_NORMAL) + kin_m = (current * current - nxt * nxt) / (2.0 * a) + dist = kin_m # well inside the kin+110 m window + lowered = effective_map_limit_ms(current, nxt, dist, current, LOOKAHEAD_NORMAL) + assert lowered is not None and lowered < current + held = effective_map_limit_ms(current, nxt, dist, current, LOOKAHEAD_NORMAL, sticky=True) + assert held == current + # map_track_decel tracks HUD, not nextSpeedLimit. At the sticky set, hold. + sticky = 66 * CV.MPH_TO_MS + assert map_track_decel_ms2(sticky, sticky, a) is None + assert map_track_accel_ms2(sticky, sticky, a) is None + assert map_in_track_deadband(sticky, sticky) + # Ego at sticky MAX: do not brake toward upcoming 50 just because OSM is lower. + assert map_track_decel_ms2(sticky, sticky, a) is None + # After posted changes, lookahead resumes (sticky=False). + assert effective_map_limit_ms(current, nxt, dist, current, LOOKAHEAD_NORMAL, sticky=False) == lowered + + +def test_map_climb_does_not_replace_nonneg_mpc_when_lead_present(): + """Under MAX: map climb may replace ~0 MPC only when there is no lead.""" + v_ego = 21.5 # ~48 mph + v_cruise = 24.6 # ~55 MAX + mpc_a = 0.05 + a_up = map_track_accel_ms2(v_ego, v_cruise, map_accel_a_ms2(LOOKAHEAD_EARLY, 1)) + assert a_up is not None and a_up > mpc_a + assert map_climb_replaces_mpc(a_up, mpc_a, has_valid_lead=False) is True + assert map_climb_replaces_mpc(a_up, mpc_a, has_valid_lead=True) is False + assert map_climb_replaces_mpc(a_up, 0.0, has_valid_lead=True) is False + # Negative MPC (already braking) is never replaced, lead or not. + assert map_climb_replaces_mpc(a_up, -0.4, has_valid_lead=False) is False + assert map_climb_replaces_mpc(a_up, -0.4, has_valid_lead=True) is False + # No climb command available. + assert map_climb_replaces_mpc(None, mpc_a, has_valid_lead=False) is False + + +def test_map_decel_still_allowed_above_max_with_lead(): + """Above MAX: map decel is a min() and is not gated on lead status.""" + v_cruise = 22.0 + v_ego = v_cruise + TRACK_TAPER_MS + 0.5 + a_brake = map_track_decel_ms2(v_ego, v_cruise, map_brake_a_ms2(LOOKAHEAD_EARLY)) + assert a_brake is not None and a_brake < 0.0 + mpc_a = 0.0 + with_lead = min(float(mpc_a), a_brake) + no_lead = min(float(mpc_a), a_brake) + assert with_lead == a_brake + assert no_lead == a_brake + # Climb replace stays off above MAX (a_up is None once dv is a brake). + a_up = map_track_accel_ms2(v_ego, v_cruise, map_accel_a_ms2(LOOKAHEAD_EARLY, 1)) + assert a_up is None + assert map_climb_replaces_mpc(a_up, mpc_a, has_valid_lead=True) is False + + +def test_hold_deadband_does_not_climb_or_brake(): + """Inside the band: no Accel climb and no map_track_decel (lead still wins).""" + v_set = 66 * CV.MPH_TO_MS + a5 = map_brake_a_ms2(LOOKAHEAD_NORMAL) + a10 = map_accel_a_ms2(LOOKAHEAD_NORMAL, 10) + assert map_in_track_deadband(v_set, v_set) + assert map_in_track_deadband(v_set + TRACK_DEADBAND_MS, v_set) + assert map_in_track_deadband(v_set - TRACK_DEADBAND_MS, v_set) + assert not map_in_track_deadband(v_set + TRACK_DEADBAND_MS + 0.01, v_set) + assert map_track_accel_ms2(v_set, v_set, a10) is None + assert map_track_decel_ms2(v_set, v_set, a5) is None + # Below the band: climb at Accel 1–10. Above: brake at locked Accel 5. + below = v_set - TRACK_TAPER_MS + assert map_track_accel_ms2(below, v_set, a10) == a10 + assert map_track_decel_ms2(below, v_set, a5) is None + above = v_set + TRACK_TAPER_MS + assert map_track_decel_ms2(above, v_set, a5) == -a5 + # Lead still wins vs map brake. + assert min(-2.0, -a5) == -2.0 + + +def test_map_track_decel_matches_comfort_curve_when_above_max(): + a5 = map_brake_a_ms2(LOOKAHEAD_NORMAL) + assert abs(a5 - 0.80) < 1e-9 + assert abs(map_brake_a_ms2(LOOKAHEAD_NORMAL) - map_comfort_a_ms2(LOOKAHEAD_NORMAL, 5)) < 1e-9 + v_ego = 70 * CV.MPH_TO_MS + v_max = 45 * CV.MPH_TO_MS + # Well above MAX → full comfort decel (locked Accel 5 = 0.80 m/s²). + assert v_ego - v_max > TRACK_TAPER_MS + assert map_track_decel_ms2(v_ego, v_max, a5) == -a5 + # Helper still accepts other a for unit math; planner must pass a5. + assert map_track_decel_ms2(v_ego, v_max, 0.36) == -0.36 + assert map_track_decel_ms2(v_max, v_max, a5) is None + assert map_track_decel_ms2(v_max - 1.0, v_max, a5) is None + assert map_track_decel_ms2(v_max + TRACK_DEADBAND_MS, v_max, a5) is None + mid = v_max + 0.5 * (TRACK_DEADBAND_MS + TRACK_TAPER_MS) + a_mid = map_track_decel_ms2(mid, v_max, a5) + assert a_mid is not None + assert abs(a_mid - (-0.5 * a5)) < 1e-9 + + +def test_accel_setting_does_not_change_brake_a(): + assert abs(map_brake_a_ms2(LOOKAHEAD_NORMAL) - 0.80) < 1e-9 + v_ego = 70 * CV.MPH_TO_MS + v_max = 45 * CV.MPH_TO_MS + locked = map_track_decel_ms2(v_ego, v_max, map_brake_a_ms2(LOOKAHEAD_NORMAL)) + assert locked == -0.80 + # Accel 1 vs 10 change climb a only. + assert abs(map_accel_a_ms2(LOOKAHEAD_NORMAL, 1) - 0.36) < 1e-9 + assert abs(map_accel_a_ms2(LOOKAHEAD_NORMAL, 10) - 1.60) < 1e-9 + assert map_slew_a_ms2(30.0, 20.0, LOOKAHEAD_NORMAL, 1) == map_slew_a_ms2(30.0, 20.0, LOOKAHEAD_NORMAL, 10) + assert abs(map_slew_a_ms2(30.0, 20.0, LOOKAHEAD_NORMAL, 10) - 0.80) < 1e-9 + assert abs(map_slew_a_ms2(20.0, 30.0, LOOKAHEAD_NORMAL, 1) - 0.36) < 1e-9 + assert abs(map_slew_a_ms2(20.0, 30.0, LOOKAHEAD_NORMAL, 10) - 1.60) < 1e-9 + a1 = map_track_accel_ms2(20.0, 31.29, map_accel_a_ms2(LOOKAHEAD_NORMAL, 1)) + a10 = map_track_accel_ms2(20.0, 31.29, map_accel_a_ms2(LOOKAHEAD_NORMAL, 10)) + assert a1 is not None and a10 is not None + assert abs(a1 - 0.36) < 1e-9 and abs(a10 - 1.60) < 1e-9 + + +def test_accel_climb_gradient_baby_steps_at_1_and_stays_brisk_at_10(): + """Accel is a gradient for MAX climb *and* lead close: 1 baby-steps last ~5 mph; 7–10 brisk.""" + from openpilot.selfdrive.mapd.constants import ( + TRACK_DEADBAND_MS, TRACK_TAPER_ACCEL_HI_MS, TRACK_TAPER_ACCEL_LO_MS, map_track_taper_ms, + ) + a1 = map_accel_a_ms2(LOOKAHEAD_NORMAL, 1) + a5 = map_accel_a_ms2(LOOKAHEAD_NORMAL, 5) + a7 = map_accel_a_ms2(LOOKAHEAD_NORMAL, 7) + a10 = map_accel_a_ms2(LOOKAHEAD_NORMAL, 10) + v10 = 10.0 * CV.MPH_TO_MS + v70 = 70.0 * CV.MPH_TO_MS + v_set = v70 + assert abs(map_track_taper_ms(1) - TRACK_TAPER_ACCEL_LO_MS) < 1e-9 + assert abs(map_track_taper_ms(10) - TRACK_TAPER_ACCEL_HI_MS) < 1e-9 + assert abs(map_track_taper_ms(7) - TRACK_TAPER_ACCEL_HI_MS) < 1e-9 + assert map_track_taper_ms(1) > map_track_taper_ms(5) > map_track_taper_ms(7) + assert map_track_taper_ms(7) == map_track_taper_ms(10) + c1 = map_track_accel_ms2(v10, v70, a1, accel_level=1) + c5 = map_track_accel_ms2(v10, v70, a5, accel_level=5) + c10 = map_track_accel_ms2(v10, v70, a10, accel_level=10) + assert c1 == a1 and c5 == a5 and c10 == a10 + assert c1 < c5 < c10 + dv_4mph = 4.0 * CV.MPH_TO_MS + assert TRACK_TAPER_ACCEL_HI_MS < dv_4mph < TRACK_TAPER_ACCEL_LO_MS + g1 = map_track_accel_ms2(v_set - dv_4mph, v_set, a1, accel_level=1) + g5 = map_track_accel_ms2(v_set - dv_4mph, v_set, a5, accel_level=5) + g7 = map_track_accel_ms2(v_set - dv_4mph, v_set, a7, accel_level=7) + g10 = map_track_accel_ms2(v_set - dv_4mph, v_set, a10, accel_level=10) + assert g1 is not None and g1 < a1 - 0.02 + assert abs(g5 - a5) < 1e-9 + assert abs(g10 - a10) < 1e-9 + assert abs(g7 - a7) < 1e-9 + dv_2mph = 2.0 * CV.MPH_TO_MS + m1 = map_track_accel_ms2(v_set - dv_2mph, v_set, a1, accel_level=1) + m5 = map_track_accel_ms2(v_set - dv_2mph, v_set, a5, accel_level=5) + m7 = map_track_accel_ms2(v_set - dv_2mph, v_set, a7, accel_level=7) + assert m1 is not None and m1 < a1 * 0.5 + assert m5 is not None and m1 < m5 < a5 + assert abs(m7 - a7) < 1e-9 + dv_1mph = 1.0 * CV.MPH_TO_MS + assert dv_1mph > TRACK_DEADBAND_MS + b1 = map_track_accel_ms2(v_set - dv_1mph, v_set, a1, accel_level=1) + b10 = map_track_accel_ms2(v_set - dv_1mph, v_set, a10, accel_level=10) + assert b1 is not None and b1 < 0.10 + assert b10 is not None and b10 > b1 + + +def test_map_track_decel_loses_to_stronger_lead_brake(): + """Planner applies min(mpc, map_track). A slower lead still wins.""" + a_map = map_track_decel_ms2(31.29, 20.12, 0.80) + assert a_map == -0.80 + a_lead = -2.0 + assert min(a_lead, a_map) == a_lead + # MPC holding ~0 (no-lead cruise obstacle not binding) → map decel wins. + assert min(0.0, a_map) == a_map + + +def _follow_hud(dec, map_kph: float) -> float: + """Mirror card.py: seed / sticky win; else apply_map_speed (Follow).""" + if dec.seed_kph is not None: + return dec.seed_kph + if dec.sticky: + return dec.driver_kph + return apply_map_speed_kph( + dec.driver_kph, map_kph, mode=MODE_FOLLOW, engaged=True, + op_long_software_cruise=True, driver_override=dec.follow_override, + ) + + +def test_engage_seeds_max_to_posted_limit(): + hold = MapCruiseHold() + posted = 45 * CV.MPH_TO_KPH + ego = 70 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=ego, posted_kph=posted, + engage_rising=True, now=0.0, + ) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - posted) < 1e-6 + assert abs(dec.driver_kph - posted) < 1e-6 + assert not dec.sticky + assert hold.follow_override_until == 0.0 + # Failed pedal write-back / DI_digitalSpeed next frames must not look like a + # stalk and must not arm a sticky hold. + for t in (0.05, 5.0, 11.0): + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=ego, posted_kph=posted, + engage_rising=False, now=t, stalk_pressed=False, + ) + assert not dec.sticky + assert hold.follow_override_until == 0.0 + assert abs(_follow_hud(dec, posted) - posted) < 1e-6 + # No map: keep ego capture. + hold2 = MapCruiseHold() + dec2 = decide_map_cruise( + hold2, engaged=True, mode=MODE_CAP, raw_kph=ego, posted_kph=None, + engage_rising=True, now=0.0, + ) + assert dec2.seed_kph is not None + assert abs(dec2.seed_kph - ego) < 1e-6 + assert abs(dec2.driver_kph - ego) < 1e-6 + assert dec2.sticky # hold traveled; do not invent posted when GPS appears + assert hold2.last_posted_kph is None + + +def test_sticky_manual_below_limit_until_posted_changes(): + hold = MapCruiseHold() + a = 45 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + below = a - 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + assert dec.sticky + assert dec.seed_kph is not None # one-shot write of the stalk step + assert abs(dec.driver_kph - below) < 1e-6 + assert hold.follow_override_until == 0.0 + # Still a: hold, do not Follow back to a, do not write pedal every frame. + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=a, + engage_rising=False, now=20.0, stalk_pressed=False, + ) + assert dec.sticky + assert dec.seed_kph is None + assert abs(dec.driver_kph - below) < 1e-6 + assert not should_write_preap_pedal(dec.seed_kph, _follow_hud(dec, a), below) + # Limit changes to b: drop sticky. Do not seed-snap MAX to b. + b = 35 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=b, + engage_rising=False, now=21.0, stalk_pressed=False, + ) + assert not dec.sticky + assert dec.seed_kph is None + assert abs(_follow_hud(dec, b) - b) < 1e-6 + + +def test_disengage_clears_sticky_and_follow_timer(): + hold = MapCruiseHold() + a = 45 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + below = a - 5 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + assert hold.sticky_set_kph is not None + dec = decide_map_cruise( + hold, engaged=False, mode=MODE_FOLLOW, raw_kph=below, posted_kph=a, + engage_rising=False, now=2.0, + ) + assert not dec.sticky + assert dec.seed_kph is None + assert hold.sticky_set_kph is None + assert hold.held_max_kph is None + assert hold.follow_override_until == 0.0 + + +def test_brake_pause_keeps_sticky_55_in_65(): + """Long pause is not a disengage: sticky 55 in posted 65 must survive.""" + hold = MapCruiseHold() + posted = 65 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=True, now=0.0, + ) + sticky = 55 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + assert hold.sticky_set_kph is not None + ego_while_braking = 30 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=2.0, long_active=False, + traveled_kph=ego_while_braking, + ) + assert dec.sticky + assert dec.seed_kph is None + assert abs(dec.driver_kph - sticky) < 1e-6 + assert abs(hold.held_max_kph - sticky) < 1e-6 + # One SET resumes held 55, not posted 65 and not current 30. + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=True, now=3.0, resume_held=True, long_active=True, + traveled_kph=ego_while_braking, + ) + assert dec.sticky + assert dec.seed_kph is not None + assert abs(dec.seed_kph - sticky) < 1e-6 + assert abs(_follow_hud(dec, posted) - sticky) < 1e-6 + + +def test_posted_change_65_to_45_rebases_sticky(): + hold = MapCruiseHold() + a = 65 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + sticky = 55 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + b = 45 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=b, + engage_rising=False, now=2.0, + ) + assert not dec.sticky + assert hold.sticky_set_kph is None + assert abs(hold.held_max_kph - b) < 1e-6 + assert abs(_follow_hud(dec, b) - b) < 1e-6 + # Same rebase while long-paused. + hold2 = MapCruiseHold() + decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + dec = decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=b, + engage_rising=False, now=2.0, long_active=False, + ) + assert not dec.sticky + assert abs(hold2.held_max_kph - b) < 1e-6 + # Raise also rebases and seeds (65-zone already dropped; 45→70). + posted_70 = 70 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=b, posted_kph=posted_70, + engage_rising=False, now=3.0, + ) + assert not dec.sticky + assert dec.seed_kph is not None + assert abs(dec.seed_kph - posted_70) < 1e-6 + assert abs(hold.held_max_kph - posted_70) < 1e-6 + + +def test_no_map_one_set_resumes_held(): + hold = MapCruiseHold() + held = 55 * CV.MPH_TO_KPH + traveled = 30 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=held, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=False, now=1.0, long_active=False, traveled_kph=traveled, + ) + assert abs(dec.driver_kph - held) < 1e-6 + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=2.0, resume_held=True, traveled_kph=traveled, + ) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - held) < 1e-6 + + +def test_no_map_double_set_uses_current_speed(): + hold = MapCruiseHold() + held = 55 * CV.MPH_TO_KPH + now_speed = 42 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=held, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=False, now=1.0, take_speed_now=True, traveled_kph=now_speed, + ) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - now_speed) < 1e-6 + assert abs(hold.held_max_kph - now_speed) < 1e-6 + assert hold.last_posted_kph is None + + +def test_mode_off_one_set_after_pause_keeps_held_not_ego(): + """Gravel repro: maps off, MAX 19, brake (ego lower), one SET restores 19. + + On the car, resume_held is consumed on the SET frame while pedalLongActive + is still False. The next frame's engage_rising must not take traveled. + """ + hold = MapCruiseHold() + held = 19 * CV.MPH_TO_KPH + ego = 12 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=held, + ) + assert abs(hold.held_max_kph - held) < 1e-6 + # Pause publishes cruiseState.speed as ego. Must not latch it. + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=ego, posted_kph=None, + engage_rising=False, now=1.0, long_active=False, traveled_kph=ego, + ) + assert abs(dec.driver_kph - held) < 1e-6 + assert abs(hold.held_max_kph - held) < 1e-6 + # SET frame: resume_held, long still paused (authority not up yet). + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=ego, posted_kph=None, + engage_rising=False, now=2.0, resume_held=True, long_active=False, + traveled_kph=ego, + ) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - held) < 1e-6 + # Next frame: pedalLongActive rising, resume_held already consumed. + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=3.0, resume_held=False, long_active=True, + traveled_kph=ego, + ) + assert abs(hold.held_max_kph - held) < 1e-6 + assert abs(dec.driver_kph - held) < 1e-6 + if dec.seed_kph is not None: + assert abs(dec.seed_kph - held) < 1e-6 + assert abs(dec.driver_kph - ego) > 1.0 + + +def test_mode_off_pause_does_not_latch_ego_when_held_missing(): + hold = MapCruiseHold() + ego = 12 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=ego, posted_kph=None, + engage_rising=False, now=1.0, long_active=False, traveled_kph=ego, + ) + assert hold.held_max_kph is None + assert abs(dec.driver_kph - ego) < 1e-6 + assert dec.seed_kph is None + + +def test_mode_off_stalk_updates_held_then_one_set_resumes_it(): + hold = MapCruiseHold() + start = 24 * CV.MPH_TO_KPH + adjusted = 19 * CV.MPH_TO_KPH + ego = 12 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=start, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=start, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=start, posted_kph=None, + engage_rising=False, now=1.0, long_active=True, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=adjusted, posted_kph=None, + engage_rising=False, now=2.0, long_active=True, + ) + assert abs(hold.held_max_kph - adjusted) < 1e-6 + assert dec.seed_kph is None + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=ego, posted_kph=None, + engage_rising=False, now=3.0, long_active=False, traveled_kph=ego, + ) + assert abs(hold.held_max_kph - adjusted) < 1e-6 + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=ego, posted_kph=None, + engage_rising=True, now=4.0, resume_held=True, long_active=True, + traveled_kph=ego, + ) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - adjusted) < 1e-6 + + +def test_mode_off_double_set_after_pause_takes_traveled(): + hold = MapCruiseHold() + held = 19 * CV.MPH_TO_KPH + ego = 12 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=held, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=ego, posted_kph=None, + engage_rising=False, now=1.0, long_active=False, traveled_kph=ego, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=ego, posted_kph=None, + engage_rising=False, now=2.0, take_speed_now=True, traveled_kph=ego, + ) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - ego) < 1e-6 + assert abs(hold.held_max_kph - ego) < 1e-6 diff --git a/selfdrive/mapd/tests/test_map_speed_policy_2.py b/selfdrive/mapd/tests/test_map_speed_policy_2.py new file mode 100644 index 00000000000000..303e64bdc720b3 --- /dev/null +++ b/selfdrive/mapd/tests/test_map_speed_policy_2.py @@ -0,0 +1,886 @@ +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.constants import ( + MODE_CAP, MODE_FOLLOW, MODE_OFF, +) +from openpilot.selfdrive.mapd.map_speed_policy import ( + MapCruiseHold, apply_map_speed_kph, decide_map_cruise, is_cruise_stalk_hold_step, + is_cruise_stalk_step, is_cruise_stalk_tip_step, + should_write_preap_pedal, slew_map_speed_ms, +) + + +def _follow_hud(dec, map_kph: float) -> float: + """Mirror card.py: seed / sticky win; else apply_map_speed (Follow).""" + if dec.seed_kph is not None: + return dec.seed_kph + if dec.sticky: + return dec.driver_kph + return apply_map_speed_kph( + dec.driver_kph, map_kph, mode=MODE_FOLLOW, engaged=True, + op_long_software_cruise=True, driver_override=dec.follow_override, + ) + + +def test_follow_delayed_engage_rising_keeps_sticky(): + """pedalLongActive rising after resume_held must not forget 55-in-65.""" + hold = MapCruiseHold() + posted = 65 * CV.MPH_TO_KPH + sticky = 55 * CV.MPH_TO_KPH + ego = 30 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=True, now=0.0, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=2.0, long_active=False, traveled_kph=ego, + ) + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=3.0, resume_held=True, long_active=False, + traveled_kph=ego, + ) + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=True, now=4.0, resume_held=False, long_active=True, + traveled_kph=ego, + ) + assert dec.sticky + assert abs(dec.driver_kph - sticky) < 1e-6 + assert abs(hold.held_max_kph - sticky) < 1e-6 + if dec.seed_kph is not None: + assert abs(dec.seed_kph - sticky) < 1e-6 + + +def test_maps_double_set_uses_posted(): + hold = MapCruiseHold() + posted = 65 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=True, now=0.0, + ) + sticky = 55 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + traveled = 40 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=2.0, take_speed_now=True, traveled_kph=traveled, + ) + assert not dec.sticky + assert dec.seed_kph is not None + assert abs(dec.seed_kph - posted) < 1e-6 + assert abs(hold.held_max_kph - posted) < 1e-6 + + +def test_unknown_posted_does_not_invent_or_wipe(): + hold = MapCruiseHold() + posted = 65 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=True, now=0.0, + ) + sticky = 55 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + last_posted = hold.last_posted_kph + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=None, + engage_rising=False, now=2.0, + ) + assert dec.sticky + assert abs(dec.driver_kph - sticky) < 1e-6 + assert hold.last_posted_kph == last_posted + # GPS returns same posted: still sticky 55, not Follow to 65. + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=sticky, posted_kph=posted, + engage_rising=False, now=3.0, + ) + assert dec.sticky + assert abs(_follow_hud(dec, posted) - sticky) < 1e-6 + + +def test_maps_off_never_rebases_toward_invented_posted(): + hold = MapCruiseHold() + held = 55 * CV.MPH_TO_KPH + fake_posted = 65 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=held, + ) + for t in (1.0, 5.0, 20.0): + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_OFF, raw_kph=held, posted_kph=fake_posted, + engage_rising=False, now=t, + ) + assert abs(dec.driver_kph - held) < 1e-6 + assert hold.last_posted_kph is None + + +def test_sticky_below_limit_survives_past_ten_seconds(): + """Stalk to a-5 must still be a-5 after >10s with unchanged posted limit.""" + hold = MapCruiseHold() + a = 45 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + below = a - 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + assert dec.sticky + assert hold.follow_override_until == 0.0 + for t in (11.5, 15.0, 60.0): + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=a, + engage_rising=False, now=t, stalk_pressed=False, + ) + assert dec.sticky, f"sticky lost at t={t}" + assert hold.follow_override_until == 0.0 + assert dec.seed_kph is None + assert abs(_follow_hud(dec, a) - below) < 1e-6 + # apply_map_speed without sticky would Follow-raise to a; card must not. + expired = apply_map_speed_kph( + dec.driver_kph, a, mode=MODE_FOLLOW, engaged=True, + op_long_software_cruise=True, driver_override=False, + ) + assert abs(expired - a) < 1e-6 + assert abs(_follow_hud(dec, a) - expired) > 1.0 + + +def test_cruise_stalk_step_is_1_or_5_not_ego_jump(): + a = 45 * CV.MPH_TO_KPH + assert is_cruise_stalk_step(a, a - 5 * CV.MPH_TO_KPH) + assert is_cruise_stalk_step(a, a + 1 * CV.MPH_TO_KPH) + assert is_cruise_stalk_step(a, a - 1.0) # metric 1 kph + assert is_cruise_stalk_step(a, a + 5.0) + assert not is_cruise_stalk_step(a, 70 * CV.MPH_TO_KPH) + assert not is_cruise_stalk_step(a, a) + # Tip vs hold: 1 mph / 1 kph / MPH_TO_KPH are tips; 5 mph / 5 kph are holds. + assert is_cruise_stalk_tip_step(a, a + 1 * CV.MPH_TO_KPH) + assert is_cruise_stalk_tip_step(a, a - 1.0) + assert not is_cruise_stalk_tip_step(a, a + 5 * CV.MPH_TO_KPH) + assert not is_cruise_stalk_tip_step(a, a + 5.0) + assert is_cruise_stalk_hold_step(a, a + 5 * CV.MPH_TO_KPH) + assert is_cruise_stalk_hold_step(a, a - 5.0) + assert not is_cruise_stalk_hold_step(a, a + 1 * CV.MPH_TO_KPH) + assert not is_cruise_stalk_hold_step(a, a - 1.0) + + +def test_stalk_plus_minus_changes_set_without_button_events(): + """pre-AP buttonEvents are unreliable; a 5 mph pedal_speed step must move MAX.""" + hold = MapCruiseHold() + a = 45 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + down = a - 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=down, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=False, + ) + assert dec.sticky + assert abs(_follow_hud(dec, a) - down) < 1e-6 + up = down + 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=up, posted_kph=a, + engage_rising=False, now=2.0, stalk_pressed=False, + ) + assert abs(_follow_hud(dec, a) - up) < 1e-6 + above = a + 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=above, posted_kph=a, + engage_rising=False, now=3.0, stalk_pressed=False, + ) + assert dec.sticky + assert abs(_follow_hud(dec, a) - above) < 1e-6 + # Cap: stalk up cannot exceed posted; stalk down still lowers MAX. + hold_c = MapCruiseHold() + decide_map_cruise( + hold_c, engaged=True, mode=MODE_CAP, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + dec = decide_map_cruise( + hold_c, engaged=True, mode=MODE_CAP, raw_kph=above, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=False, + ) + cap_out = apply_map_speed_kph( + dec.driver_kph, a, mode=MODE_CAP, engaged=True, op_long_software_cruise=True, + driver_override=dec.follow_override, + ) + assert abs(cap_out - a) < 1e-6 + decide_map_cruise( + hold_c, engaged=True, mode=MODE_CAP, raw_kph=a, posted_kph=a, + engage_rising=False, now=2.0, stalk_pressed=False, + ) + dec = decide_map_cruise( + hold_c, engaged=True, mode=MODE_CAP, raw_kph=down, posted_kph=a, + engage_rising=False, now=3.0, stalk_pressed=False, + ) + assert dec.sticky + assert abs(dec.driver_kph - down) < 1e-6 + + +def test_sticky_hud_ignores_anticipatory_map_kph(): + """Card sticky path must keep 66 even if map_kph slewed toward upcoming 50.""" + hold = MapCruiseHold() + a = 60 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + above = a + 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=above, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=False, + ) + assert dec.sticky + anticipated = 50 * CV.MPH_TO_KPH + assert abs(_follow_hud(dec, anticipated) - above) < 1e-6 + assert dec.seed_kph is not None # real 5 mph stalk step writes once + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=above, posted_kph=a, + engage_rising=False, now=2.0, stalk_pressed=False, + ) + assert dec.sticky + assert dec.seed_kph is None + assert abs(_follow_hud(dec, anticipated) - above) < 1e-6 + assert not should_write_preap_pedal(dec.seed_kph, _follow_hud(dec, anticipated), above) + + +def test_follow_holds_absolute_set_until_posted_changes(): + """Justin: set 55 in a 50 stays 55 until posted changes; set 45 in a 50, same.""" + hold = MapCruiseHold() + a = 50 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + above = 55 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=above, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + assert dec.sticky + assert hold.follow_override_until == 0.0 + assert abs(_follow_hud(dec, a) - above) < 1e-6 + for t in (11.1, 15.0, 60.0): + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=above, posted_kph=a, + engage_rising=False, now=t, stalk_pressed=False, + ) + assert dec.sticky, f"55 mph sticky lost at t={t}" + assert dec.seed_kph is None + assert abs(_follow_hud(dec, a) - above) < 1e-6 + b = 35 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=above, posted_kph=b, + engage_rising=False, now=61.0, stalk_pressed=False, + ) + assert not dec.sticky + assert dec.seed_kph is None # decrease must not cliff MAX to posted + assert abs(_follow_hud(dec, b) - b) < 1e-6 + + hold2 = MapCruiseHold() + decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + below = 45 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=True, + ) + assert dec.sticky + assert abs(_follow_hud(dec, a) - below) < 1e-6 + dec = decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=a, + engage_rising=False, now=60.0, stalk_pressed=False, + ) + assert dec.sticky + assert dec.seed_kph is None + assert abs(_follow_hud(dec, a) - below) < 1e-6 + dec = decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=below, posted_kph=b, + engage_rising=False, now=61.0, stalk_pressed=False, + ) + assert not dec.sticky + assert dec.seed_kph is None + assert abs(_follow_hud(dec, b) - b) < 1e-6 + + +def test_cap_does_not_exceed_limit_when_raising(): + hold = MapCruiseHold() + a = 45 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_CAP, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + above = a + 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_CAP, raw_kph=above, posted_kph=a, + engage_rising=False, now=1.0, + ) + assert not dec.sticky + out = apply_map_speed_kph( + dec.driver_kph, a, mode=MODE_CAP, engaged=True, op_long_software_cruise=True, + driver_override=dec.follow_override, + ) + assert abs(out - a) < 1e-6 + + +def test_slew_rate_limits_map_max_steps(): + # 0.80 m/s² × 0.1 s = 0.08 m/s max step + out = slew_map_speed_ms(30.0, 20.0, 0.1, 0.80) + assert abs(out - 29.92) < 1e-9 + done = slew_map_speed_ms(20.05, 20.0, 0.1, 0.80) + assert done == 20.0 + + +def test_should_write_preap_pedal_on_raise_not_every_frame(): + a = 45 * CV.MPH_TO_KPH + b = 50 * CV.MPH_TO_KPH + # Engage / posted / stalk-step seed writes once. + assert should_write_preap_pedal(a, a, a) + assert should_write_preap_pedal(a, a, None) + # Sticky hold / same MAX every Follow frame: do not write (that ate stalk). + assert not should_write_preap_pedal(None, a, a) + # Stalk up / Follow posted raise: HUD rose vs last pedal write. + assert should_write_preap_pedal(None, b, a) + # No last write yet and no seed: leave CI pedal alone. + assert not should_write_preap_pedal(None, b, None) + # Decrease without seed: planner brakes from HUD MAX; do not clobber stalk down. + assert not should_write_preap_pedal(None, a, b) + + +def test_sticky_hold_does_not_overwrite_ci_stalk_step(): + """After CI.update steps pedal, card must not write the old sticky hold. + + Order in card.py: CI.update (stalk +/-) then overlay. Writing seed_kph + every sticky frame undoes that 1/5 mph step. + """ + hold = MapCruiseHold() + a = 50 * CV.MPH_TO_KPH + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + last_pedal = a + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=False, now=1.0, stalk_pressed=False, + ) + hud = _follow_hud(dec, a) + assert not dec.sticky + assert dec.seed_kph is None + assert not should_write_preap_pedal(dec.seed_kph, hud, last_pedal) + + above = a + 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=above, posted_kph=a, + engage_rising=False, now=2.0, stalk_pressed=False, + ) + hud = _follow_hud(dec, a) + assert dec.sticky + assert abs(hud - above) < 1e-6 + assert should_write_preap_pedal(dec.seed_kph, hud, last_pedal) + write_val = dec.seed_kph if dec.seed_kph is not None else hud + assert abs(write_val - above) < 1e-6 + + last_pedal = above + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=above, posted_kph=a, + engage_rising=False, now=3.0, stalk_pressed=False, + ) + hud = _follow_hud(dec, a) + assert dec.sticky + assert dec.seed_kph is None + assert abs(hud - above) < 1e-6 + assert not should_write_preap_pedal(dec.seed_kph, hud, last_pedal) + + down = above - 5 * CV.MPH_TO_KPH + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=down, posted_kph=a, + engage_rising=False, now=4.0, stalk_pressed=False, + ) + hud = _follow_hud(dec, a) + assert dec.sticky + assert abs(hud - down) < 1e-6 + write_val = dec.seed_kph if dec.seed_kph is not None else hud + assert abs(write_val - down) < 1e-6 + + # Button event this frame, CS.speed still the old hold: do not write `a` + # over CI's in-flight +5. + hold2 = MapCruiseHold() + decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=True, now=0.0, + ) + dec = decide_map_cruise( + hold2, engaged=True, mode=MODE_FOLLOW, raw_kph=a, posted_kph=a, + engage_rising=False, now=2.0, stalk_pressed=True, + ) + hud = _follow_hud(dec, a) + assert not should_write_preap_pedal(dec.seed_kph, hud, a) + assert dec.seed_kph is None + + +def test_hud_current_speed_is_wheel_ego_not_cluster_or_max(): + """Top-middle 3X speed was ~56 mph vs ~45 actual — that is 90 kph MAX. + + vEgoCluster is DI_digitalSpeed, which pre-AP also uses as cruiseState.speed. + Map-speed writes MAX into vCruise / pedal_speed / cruiseState.speed. Live + speed must be ESP/wheel vEgo only. + """ + from pathlib import Path + root = Path(__file__).resolve().parents[3] + for rel in ( + "selfdrive/ui/onroad/hud_renderer.py", + "selfdrive/ui/mici/onroad/hud_renderer.py", + ): + src = (root / rel).read_text() + assert "self.speed = max(0.0, float(car_state.vEgo) * speed_conversion)" in src + assert "v_ego = v_ego_cluster if" not in src + assert "self.speed = md.speedLimit" not in src + assert "self.speed = self.map_speed_limit" not in src + assert "self.speed = self.set_speed" not in src + # MAX box is vCruiseCluster; LIMIT sign is OSM. Do not paint either as live. + card = (root / "selfdrive/car/card.py").read_text() + assert "vEgoCluster" not in card + assert "CS.vEgo =" not in card + assert "CS.vCruise =" in card + + +def test_map_speed_submenu_wires_params(): + """Menu wiring without importing raylib / cereal UI.""" + from pathlib import Path + root = Path(__file__).resolve().parents[3] + tici = (root / "selfdrive/ui/layouts/settings/map_speed.py").read_text() + mici = (root / "selfdrive/ui/mici/layouts/settings/map_speed.py").read_text() + nap = (root / "selfdrive/ui/layouts/settings/nap.py").read_text() + nap_mici = (root / "selfdrive/ui/mici/layouts/settings/nap.py").read_text() + for src in (tici, mici): + for key in ("NAPMapSpeedMode", "NAPMapSpeedOffsetMph", "NAPMapSpeedLookahead"): + assert key in src + assert "NAPMapSpeedAccel" not in src + content = (root / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + docs = (root / "docs-nap/map-speed.md").read_text() + assert "self._scroller.add_widgets" in mici + assert "Acceleration" not in tici + assert "acceleration" not in mici + assert "1.20 m/s² at Normal" not in tici + assert "pauses Follow for 10s" not in tici + assert "holds until the posted limit changes" in content + assert "lookahead pauses while that set is active" in content + assert "decreases still ease with lookahead" not in tici + assert "decreases still ease with lookahead" not in content + assert "kin + 110 m" in docs + assert "1.5 s GPS lag" not in tici + assert "A higher limit far ahead never raises MAX" in content + assert "A higher limit ahead never raises MAX early" not in tici + assert "A higher limit ahead never raises MAX early" not in content + assert tici.index("_all_items.append(self._refresh_btn)") < tici.index("_all_items.append(self._db_status)") + assert "Map Speed Limit" in nap + assert "Radar Settings" in nap + assert "Driving Mannerisms" in nap + assert "map speed limit" in nap_mici + assert "radar settings" in nap_mici + assert "driving mannerisms" in nap_mici + manner = (root / "selfdrive/ui/layouts/settings/driving_mannerisms.py").read_text() + manner_mici = (root / "selfdrive/ui/mici/layouts/settings/driving_mannerisms.py").read_text() + assert "FOLLOW_DISTANCE_CITY_DESCRIPTION" in manner + assert "FOLLOW_DISTANCE_HWY_DESCRIPTION" in manner + assert "MAP_SPEED_ACCEL_DESCRIPTION" in manner + assert "ADAPTIVE_ACCEL_DESCRIPTION" in manner + assert "MAP_SPEED_ACCEL_DESCRIPTION" in content + assert "1 lazy" in content + assert "same Accel 1–10 gradient" in content + assert "last-mph taper" in content + assert "0.20 / 0.30 / 0.50" not in content + assert "not a harder brake" in content + assert "steps the active 1–7" in content + assert "No lead:" in content + assert "follow distance" in manner_mici + assert "Adaptive Accel Limits" not in nap + assert "Follow Distance" not in nap + assert "Soft Lateral Handoff" not in nap + assert "adaptive accel limits" not in nap_mici + assert "follow distance" not in nap_mici + assert "soft lateral handoff" not in nap_mici + assert "Refresh maps" in tici + assert '"Back To"' in tici + assert "←" not in tici + assert "Check for map updates" not in tici + assert "refresh maps" in mici + assert "check for map updates" not in mici + assert "scripts.nap.refresh_osm_maps" in nap + assert "scripts.nap.refresh_osm_maps" in mici + assert tici.index("_all_items.append(self._refresh_btn)") < tici.index("_all_items.append(self._download_btn)") + mici_widgets = mici.split("self._scroller.add_widgets", 1)[1] + assert mici_widgets.index("refresh_maps_btn") < mici_widgets.index("download_maps_btn") + assert "NAPMapSpeedAccel" in (root / "common/params_keys.h").read_text() + assert "NAPMapSpeedDbRevision" in (root / "common/params_keys.h").read_text() + assert "NAPMapSpeedDbSha256" in (root / "common/params_keys.h").read_text() + + +def test_driving_mannerisms_submenu_wires_params(): + """Driving Mannerisms submenu mirrors Map Speed Limit open/close/render.""" + from pathlib import Path + root = Path(__file__).resolve().parents[3] + tici = (root / "selfdrive/ui/layouts/settings/driving_mannerisms.py").read_text() + mici = (root / "selfdrive/ui/mici/layouts/settings/driving_mannerisms.py").read_text() + nap = (root / "selfdrive/ui/layouts/settings/nap.py").read_text() + nap_mici = (root / "selfdrive/ui/mici/layouts/settings/nap.py").read_text() + for src in (tici, mici): + for key in ("ADAPTIVE_ACCEL", "FOLLOW_DISTANCE", "NAP_DRIVER_LAT_HANDOFF", "NAP_ONE_PEDAL_LONG", "NAP_HYPERMILE", "NAP_HYPERMILE_STEP_DOWN", "NAPMapSpeedAccel"): + assert key in src + content = (root / "selfdrive/ui/layouts/settings/nap_content.py").read_text() + assert "Hypermile" in tici + assert "One-Pedal Long" in tici + assert "Adaptive Accel" in tici + assert "Acceleration" in tici + assert "MAP_SPEED_ACCEL_DESCRIPTION" in tici + assert "ADAPTIVE_ACCEL_DESCRIPTION" in tici + assert "ONE_PEDAL_LONG_DESCRIPTION" in tici + assert "stays Accel 5" in content + assert "Lead still owns follow" in content + assert "1 lazy" in content + assert "same Accel 1–10 gradient" in content + assert "0.20 / 0.30 / 0.50" not in content + assert tici.index('"Acceleration"') < tici.index('"Adaptive Accel"') + assert tici.index("self._accel_buttons") < tici.index("self._adaptive_accel") + assert tici.index("self._adaptive_accel") < tici.index("self._follow_city_buttons") + assert tici.index("self._follow_city_buttons") < tici.index("self._follow_hwy_buttons") + assert tici.index("self._follow_hwy_buttons") < tici.index("self._lat_handoff") + assert tici.index("self._lat_handoff") < tici.index("self._one_pedal") + assert tici.index("self._one_pedal") < tici.index("self._hypermile") + assert "City Follow Distance" in tici + assert "Highway Follow Distance" in tici + assert "Soft Lateral Handoff" in tici + assert "Simulate Look" not in tici + assert "False Alert Ignore" not in tici + assert "NAP_DM_SIMULATE_LOOKING" not in tici + assert "NAP_DM_FALSE_ALERT_IGNORE" not in tici + assert '"Back To"' in tici + assert "Return to NAP settings." in tici + assert "hypermile" in mici + assert "one-pedal long" in mici + assert "adaptive accel" in mici + assert '"acceleration"' in mici + assert "NAPMapSpeedAccel" in mici + mici_widgets = mici.split("self._scroller.add_widgets", 1)[1] + assert mici_widgets.index("self._accel") < mici_widgets.index("adaptive_accel") + assert mici_widgets.index("adaptive_accel") < mici_widgets.index("self._follow_distance_city") + assert mici_widgets.index("self._follow_distance_city") < mici_widgets.index("self._follow_distance_hwy") + assert mici_widgets.index("self._follow_distance_hwy") < mici_widgets.index("lat_handoff") + assert mici_widgets.index("lat_handoff") < mici_widgets.index("one_pedal") + assert mici_widgets.index("one_pedal") < mici_widgets.index("hypermile") + assert "city follow distance" in mici + assert "highway follow distance" in mici + assert "soft lateral handoff" in mici + assert "simulate look" not in mici + assert "false alert ignore" not in mici + assert "self._scroller.add_widgets" in mici + assert "self._accel.refresh()" in mici + assert "DrivingMannerismsLayout" in nap + assert "Accel feel, follow, soft lat" in nap + assert "one-pedal" in nap + assert "lookahead, acceleration" not in nap + assert "_open_driving_mannerisms" in nap + assert "_close_driving_mannerisms" in nap + assert 'self._page = "driving_mannerisms"' in nap + assert "self._driving_mannerisms_page.render" in nap + assert "NAP_DM_SIMULATE_LOOKING" in nap + assert "put_bool(NAP_DM_SIMULATE_LOOKING, True)" in nap + assert "NAP_DM_FALSE_ALERT_IGNORE" in nap + assert "put_bool(NAP_DM_FALSE_ALERT_IGNORE, False)" in nap + keys = (root / "common/params_keys.h").read_text() + assert "NAPDmSimulateLooking" in keys + assert "NAPDmFalseAlertIgnore" in keys + assert "DrivingMannerismsLayoutMici" in nap_mici + assert "driving mannerisms" in nap_mici + # Map Speed Limit submenu must stay on the main NAP list. + assert "Map Speed Limit" in nap + assert "map speed limit" in nap_mici + + +def test_planner_and_mpc_keep_radar_after_map_cap(): + """Regression: map cap runs before mpc.update(radarState, v_cruise).""" + from pathlib import Path + root = Path(__file__).resolve().parents[3] + planner = (root / "selfdrive/controls/lib/longitudinal_planner.py").read_text() + mpc = (root / "selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py").read_text() + cap_at = planner.find("cap_planner_v_cruise_ms") + mpc_at = planner.find("self.mpc.update(sm['radarState'], v_cruise") + hold_at = planner.find("map_in_track_deadband(v_ego, v_hud_ms)") + track_at = planner.find("a_brake = map_track_decel_ms2") + assert 0 <= cap_at < mpc_at + assert 0 <= mpc_at < hold_at < track_at + assert "map_brake_a_ms2" in planner + assert "map_track_accel_ms2" in planner + assert "resolve_lead_close_hold" in planner + assert "_apply_lead_follow" in planner + assert "min(float(output_a_target), a_brake)" in planner + assert "if float(output_a_target) >= 0.0:" in planner + assert "output_a_target = 0.0" in planner + assert "np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle])" in mpc + assert "self.params[:,2] = np.min(x_obstacles, axis=1)" in mpc + card = (root / "selfdrive/car/card.py").read_text() + assert "pedalLongActive" in card + assert "stalk_pressed=stalk_pressed" in card + assert "take_speed_now=take_speed_now" in card + assert "resume_held=resume_held" in card + assert "_write_preap_pedal_speed" in card + assert "should_write_preap_pedal" in card + assert "_adopt_preap_fsm_held_max" in card + assert "long_active=soft_long" in card + # Must not seed/overlay on lateral-only first pull (CC.enabled). + assert "engage_rising = long_active and not long_active_prev" in card + # Must not clobber stalk by writing Follow HUD onto pedal every frame. + assert "should_write_preap_pedal(seed_kph, preap_v_cruise_kph, self._last_pedal_kph)" in card + # Curve snapshot/restore: freeze posted flicker, restore pre-curve MAX. + assert "CurveMaxHold" in card + assert "begin_cycle" in card + assert "restore_seed_kph" in card + assert "if long_active and dec.seed_kph is not None:" not in card + # Sticky hold must not slew toward nextSpeedLimit. + assert "not dec.sticky:" in card + assert "sticky_hold = self._map_hold.sticky_set_kph is not None" not in card + planner_src = planner + assert "output_a_target = a_up" in planner_src + assert "min(float(output_a_target), a_up)" not in planner_src + assert "map_climb_replaces_mpc" in planner_src + assert "has_valid_lead" in planner_src + assert "leadOne.status" in planner_src + mapd = (root / "selfdrive/mapd/mapd.py").read_text() + osm = (root / "selfdrive/mapd/osm_db.py").read_text() + constants = (root / "selfdrive/mapd/constants.py").read_text() + assert "v_ego_ms=v_ego_ms" in mapd + assert "osm_sign_lead_m(v_ego_ms)" in osm + assert "OSM_SIGN_LEAD_S = 1.5" in constants + assert "OSM_SIGN_LEAD_M" not in constants + assert "DECREASE_START_MARGIN_M = 110.0" in constants + assert "Do not snap posted down" in osm + policy = (root / "selfdrive/mapd/map_speed_policy.py").read_text() + assert "float(posted_kph) if raised else None" in policy + # Delayed pedalLongActive rising after one SET must not take traveled. + assert "not bool(resume_held) and hold.held_max_kph is None" in policy + # Sticky / stalk path unchanged. + assert "should_write_preap_pedal(seed_kph, preap_v_cruise_kph, self._last_pedal_kph)" in card + + +def _decision_fields(dec, hold): + seed = None if dec.seed_kph is None else round(float(dec.seed_kph), 4) + return ( + bool(dec.sticky), + seed, + round(float(hold.held_max_kph), 4), + hold.sticky_set_kph is None, + ) + + +def test_none_to_valid_posted_matches_a_normal_limit_change(): + """A map dropout that gains a posted limit is a normal limit change. + + Engage while the sign is missing, then the posted limit returns at 3 s + and at 30 s: both adopt it. A valid → invalid → same valid flicker does + not move MAX. A stalk during the dropout is treated the same way a stalk + is treated before a 55 → 70 change. + """ + posted = 70 * CV.MPH_TO_KPH + ego = 42.4 * CV.MPH_TO_KPH + + def engage_dropout(): + hold = MapCruiseHold() + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=ego, posted_kph=None, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=ego, + ) + assert dec.sticky + assert abs(dec.seed_kph - ego) < 1e-6 + assert hold.last_posted_kph is None + return hold + + for t_back in (3.0, 30.0): + hold = engage_dropout() + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=ego, posted_kph=None, + engage_rising=False, now=t_back - 0.05, traveled_kph=ego, + ) + assert abs(hold.held_max_kph - ego) < 1e-6 + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=ego, posted_kph=posted, + engage_rising=False, now=t_back, traveled_kph=ego, + ) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - posted) < 1e-6 + assert not dec.sticky + assert abs(hold.held_max_kph - posted) < 1e-6 + assert abs(_follow_hud(dec, posted) - posted) < 1e-6 + # The next frame must not treat the old traveled speed as a stalk. + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=ego, posted_kph=posted, + engage_rising=False, now=t_back + 0.05, traveled_kph=ego, + ) + assert not dec.sticky + assert abs(_follow_hud(dec, posted) - posted) < 1e-6 + + # Same limit returns and MAX already equals it: no pedal write, no rebase. + hold = MapCruiseHold() + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=posted, + ) + held_before = hold.held_max_kph + decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=None, + engage_rising=False, now=1.0, traveled_kph=posted, + ) + assert hold.last_posted_kph is not None + assert abs(hold.held_max_kph - posted) < 1e-6 + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=False, now=1.5, traveled_kph=posted, + ) + assert dec.seed_kph is None + assert abs(hold.held_max_kph - held_before) < 1e-6 + assert abs(_follow_hud(dec, posted) - posted) < 1e-6 + assert not should_write_preap_pedal(dec.seed_kph, _follow_hud(dec, posted), posted) + + # Stalk, then the limit changes: dropout and a normal 55 → 70 match. + normal = MapCruiseHold() + start = 55 * CV.MPH_TO_KPH + stalk = start + 5 * CV.MPH_TO_KPH + decide_map_cruise( + normal, engaged=True, mode=MODE_FOLLOW, raw_kph=start, posted_kph=start, + engage_rising=True, now=0.0, + ) + decide_map_cruise( + normal, engaged=True, mode=MODE_FOLLOW, raw_kph=stalk, posted_kph=start, + engage_rising=False, now=1.0, + ) + assert normal.sticky_set_kph is not None + dec_normal = decide_map_cruise( + normal, engaged=True, mode=MODE_FOLLOW, raw_kph=stalk, posted_kph=posted, + engage_rising=False, now=2.0, + ) + + dropped = engage_dropout() + stalk_drop = ego + 5 * CV.MPH_TO_KPH + decide_map_cruise( + dropped, engaged=True, mode=MODE_FOLLOW, raw_kph=stalk_drop, posted_kph=None, + engage_rising=False, now=1.0, traveled_kph=ego, + ) + assert dropped.sticky_set_kph is not None + dec_drop = decide_map_cruise( + dropped, engaged=True, mode=MODE_FOLLOW, raw_kph=stalk_drop, posted_kph=posted, + engage_rising=False, now=30.0, traveled_kph=ego, + ) + assert _decision_fields(dec_normal, normal) == _decision_fields(dec_drop, dropped) + assert dec_drop.seed_kph is not None + assert abs(dec_drop.seed_kph - posted) < 1e-6 + assert not dec_drop.sticky + + +def test_valid_to_invalid_posted_leaves_max_unchanged(): + """Posted → no limit holds MAX. No drop, and no reseed onto ego speed.""" + posted = 70 * CV.MPH_TO_KPH + # 5 mph under MAX: the same delta as a stalk down, if raw falls back to ego. + ego_near = posted - 5 * CV.MPH_TO_KPH + ego_far = 42.4 * CV.MPH_TO_KPH + + def engage(): + hold = MapCruiseHold() + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=posted, + engage_rising=True, now=0.0, take_speed_now=True, traveled_kph=ego_far, + ) + assert dec.seed_kph is not None + assert abs(dec.seed_kph - posted) < 1e-6 + assert abs(hold.held_max_kph - posted) < 1e-6 + return hold + + for ego in (ego_near, ego_far): + hold = engage() + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=ego, posted_kph=None, + engage_rising=False, now=1.0, traveled_kph=ego, + ) + assert dec.seed_kph is None + assert not dec.sticky + assert hold.sticky_set_kph is None + assert abs(hold.held_max_kph - posted) < 1e-6 + assert abs(hold.policy_kph - posted) < 1e-6 + assert abs(dec.driver_kph - posted) < 1e-6 + assert abs(_follow_hud(dec, None) - posted) < 1e-6 + # Still invalid. Ego must not become MAX on a later frame either. + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=ego, posted_kph=None, + engage_rising=False, now=5.0, traveled_kph=ego, + ) + assert dec.seed_kph is None + assert not dec.sticky + assert abs(hold.held_max_kph - posted) < 1e-6 + assert abs(_follow_hud(dec, None) - posted) < 1e-6 + + # Set speed itself did not move; only the sign went away. + hold = engage() + dec = decide_map_cruise( + hold, engaged=True, mode=MODE_FOLLOW, raw_kph=posted, posted_kph=None, + engage_rising=False, now=1.0, traveled_kph=ego_far, + ) + assert dec.seed_kph is None + assert abs(hold.held_max_kph - posted) < 1e-6 + assert abs(_follow_hud(dec, None) - posted) < 1e-6 + + +# --- Oct 13: untagged state defaults -------------------------------------------------------------------------- +from openpilot.selfdrive.mapd.map_speed_policy import ( + DEFAULT_DROP_A_MS2, RURAL_KEEP_MS, default_drop_cap_ms, keep_rural_default_ms, map_source_for, +) + +_MPH = 0.44704 + + +def test_source_tagged_vs_default(): + assert map_source_for(False) == "osm" + assert map_source_for(True) == "osm_default" + assert map_source_for(True, sign=True) == "sign" + + +def test_ridgewood_untagged_tertiary_keeps_55(): + prev = ("Ridgewood Road", "tertiary", 55 * _MPH) + assert keep_rural_default_ms(30 * _MPH, estimated=True, highway="tertiary", + road_name="Ridgewood Road", prev=prev) == RURAL_KEEP_MS + + +def test_tagged_or_other_road_not_kept(): + prev = ("Ridgewood Road", "tertiary", 55 * _MPH) + assert keep_rural_default_ms(30 * _MPH, estimated=False, highway="tertiary", + road_name="Ridgewood Road", prev=prev) == 30 * _MPH + assert keep_rural_default_ms(30 * _MPH, estimated=True, highway="tertiary", + road_name="Main St", prev=prev) == 30 * _MPH + assert keep_rural_default_ms(30 * _MPH, estimated=True, highway="residential", + road_name="Ridgewood Road", prev=prev) == 30 * _MPH + + +def test_default_drop_no_harder_than_half(): + cap = None + v = 45 * _MPH + for _ in range(100): + new = default_drop_cap_ms(30 * _MPH, cap, v, 0.05) + if cap is not None: + assert (cap - new) / 0.05 <= DEFAULT_DROP_A_MS2 + 1e-9 + cap = new + assert cap > 30 * _MPH diff --git a/selfdrive/mapd/tests/test_mn_statutory.py b/selfdrive/mapd/tests/test_mn_statutory.py new file mode 100644 index 00000000000000..41ea2ed0ecbdb7 --- /dev/null +++ b/selfdrive/mapd/tests/test_mn_statutory.py @@ -0,0 +1,255 @@ +"""Minnesota statutory maxspeed fills (NAP pack only, never uploaded to OSM).""" +from __future__ import annotations + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.mn_statutory import ( + ALLEY_MPH, + BENSON_LAT, + BENSON_LON, + EXPRESSWAY_MPH, + FILL_SOURCE, + MOTORWAY_RURAL_MPH, + RURAL_OTHER_MPH, + URBAN_DISTRICT_MPH, + PlaceIndex, + bbox_intersects_minnesota, + benson_fill_bbox, + in_minnesota, + is_urban_place_tags, + is_urban_way, + places_from_overpass, + statutory_maxspeed_mph, +) +from openpilot.selfdrive.mapd.overpass import ( + bbox_from_center, + overpass_query, + resolve_way_speed, + ways_from_overpass, +) + + +def _ms(mph: float) -> float: + return mph * CV.MPH_TO_MS + + +def test_statutory_defaults_by_class(): + assert statutory_maxspeed_mph("alley", {}, urban=False) == ALLEY_MPH + assert statutory_maxspeed_mph("living_street", {}, urban=True) == ALLEY_MPH + assert statutory_maxspeed_mph("residential", {}, urban=False) == URBAN_DISTRICT_MPH + assert statutory_maxspeed_mph("unclassified", {}, urban=True) == URBAN_DISTRICT_MPH + assert statutory_maxspeed_mph("unclassified", {}, urban=False) == RURAL_OTHER_MPH + assert statutory_maxspeed_mph("tertiary", {}, urban=False) == RURAL_OTHER_MPH + assert statutory_maxspeed_mph("secondary", {}, urban=True) == URBAN_DISTRICT_MPH + assert statutory_maxspeed_mph("primary", {}, urban=False) == RURAL_OTHER_MPH + assert statutory_maxspeed_mph("trunk", {}, urban=False) == RURAL_OTHER_MPH + assert statutory_maxspeed_mph("motorway", {}, urban=False) == MOTORWAY_RURAL_MPH + assert statutory_maxspeed_mph("motorway_link", {}, urban=True) == MOTORWAY_RURAL_MPH + assert statutory_maxspeed_mph( + "primary", {"expressway": "yes"}, urban=True, + ) == EXPRESSWAY_MPH + assert statutory_maxspeed_mph("trunk", {"motorroad": "yes"}, urban=False) == EXPRESSWAY_MPH + + +def test_skip_service_track_path_construction(): + for hw in ("service", "track", "path", "footway", "cycleway", "pedestrian", + "construction", "proposed", "abandoned"): + assert statutory_maxspeed_mph(hw, {}, urban=True) is None + + +def test_tagged_maxspeed_is_authoritative(): + tags = {"highway": "residential", "maxspeed": "25 mph"} + coords = [(BENSON_LAT, BENSON_LON), (BENSON_LAT, BENSON_LON + 0.001)] + ms, source = resolve_way_speed(tags, coords, fill_unmarked=True) + assert source == "osm" + assert ms is not None and abs(ms - _ms(25)) < 1e-6 + # Non-numeric OSM tag still fills. + tags2 = {"highway": "residential", "maxspeed": "signals"} + ms2, source2 = resolve_way_speed(tags2, coords, fill_unmarked=True) + assert source2 == FILL_SOURCE + assert ms2 is not None and abs(ms2 - _ms(30)) < 1e-6 + + +def test_no_fill_without_flag(): + tags = {"highway": "residential", "name": "Oak"} + coords = [(BENSON_LAT, BENSON_LON), (BENSON_LAT, BENSON_LON + 0.001)] + ms, source = resolve_way_speed(tags, coords, fill_unmarked=False) + assert ms is None and source == "" + + +def test_mn_city_admin_boundary_is_urban_place(): + assert is_urban_place_tags({ + "name": "Benson", "boundary": "administrative", "admin_level": "8", "border_type": "city", + }) + assert is_urban_place_tags({"place": "town", "name": "Kerkhoven"}) + assert not is_urban_place_tags({ + "name": "Benson Township", "boundary": "administrative", "admin_level": "8", "border_type": "township", + }) + assert is_urban_place_tags({ + "name": "Saint Cloud", "boundary": "administrative", "admin_level": "8", + }) + + +def test_place_polygon_marks_named_primary_urban(): + places = PlaceIndex() + # Closed square around Benson ~0.02 deg (~2 km). + ring = [ + (BENSON_LAT - 0.02, BENSON_LON - 0.02), + (BENSON_LAT - 0.02, BENSON_LON + 0.02), + (BENSON_LAT + 0.02, BENSON_LON + 0.02), + (BENSON_LAT + 0.02, BENSON_LON - 0.02), + (BENSON_LAT - 0.02, BENSON_LON - 0.02), + ] + places.add_rings([ring], "Benson") + in_town = [(BENSON_LAT, BENSON_LON - 0.001), (BENSON_LAT, BENSON_LON + 0.001)] + rural = [(BENSON_LAT + 0.5, BENSON_LON), (BENSON_LAT + 0.5, BENSON_LON + 0.001)] + tags = {"highway": "primary", "name": "US 12"} + assert is_urban_way(tags, in_town, places) + assert not is_urban_way(tags, rural, places) + urban_ms, src = resolve_way_speed(tags, in_town, fill_unmarked=True, places=places) + rural_ms, src_r = resolve_way_speed(tags, rural, fill_unmarked=True, places=places) + assert src == FILL_SOURCE and src_r == FILL_SOURCE + assert urban_ms is not None and abs(urban_ms - _ms(30)) < 1e-6 + assert rural_ms is not None and abs(rural_ms - _ms(55)) < 1e-6 + + +def test_sidewalk_is_urban(): + tags = {"highway": "tertiary", "sidewalk": "both"} + coords = [(BENSON_LAT + 0.4, BENSON_LON), (BENSON_LAT + 0.4, BENSON_LON + 0.001)] + assert is_urban_way(tags, coords, PlaceIndex()) + mph = statutory_maxspeed_mph("tertiary", tags, urban=True) + assert mph == URBAN_DISTRICT_MPH + + +def test_places_from_overpass_relation_and_way(): + payload = { + "elements": [ + { + "type": "way", + "id": 1, + "tags": {"place": "town", "name": "Benson"}, + "geometry": [ + {"lat": 45.30, "lon": -95.62}, + {"lat": 45.30, "lon": -95.58}, + {"lat": 45.33, "lon": -95.58}, + {"lat": 45.33, "lon": -95.62}, + ], + }, + { + "type": "relation", + "id": 3, + "tags": {"name": "Benson", "boundary": "administrative", "admin_level": "8", "border_type": "city"}, + "members": [ + { + "type": "way", + "role": "outer", + "geometry": [ + {"lat": 45.30, "lon": -95.62}, + {"lat": 45.30, "lon": -95.58}, + {"lat": 45.33, "lon": -95.58}, + {"lat": 45.33, "lon": -95.62}, + ], + } + ], + }, + { + "type": "relation", + "id": 4, + "tags": {"name": "Benson Township", "boundary": "administrative", "admin_level": "8", "border_type": "township"}, + "members": [ + { + "type": "way", + "role": "outer", + "geometry": [ + {"lat": 45.0, "lon": -96.0}, + {"lat": 45.0, "lon": -95.9}, + {"lat": 45.1, "lon": -95.9}, + {"lat": 45.1, "lon": -96.0}, + ], + } + ], + }, + ] + } + idx = places_from_overpass(payload) + assert len(idx) == 2 + assert idx.contains(45.315, -95.60) + assert not idx.contains(45.05, -95.95) + assert not idx.contains(46.0, -95.6) + + +def test_ways_from_overpass_fills_and_skips(): + payload = { + "elements": [ + { + "type": "way", + "id": 10, + "tags": {"highway": "residential", "name": "Oak"}, + "geometry": [ + {"lat": BENSON_LAT, "lon": BENSON_LON - 0.001}, + {"lat": BENSON_LAT, "lon": BENSON_LON + 0.001}, + ], + }, + { + "type": "way", + "id": 11, + "tags": {"highway": "service"}, + "geometry": [ + {"lat": BENSON_LAT, "lon": BENSON_LON - 0.001}, + {"lat": BENSON_LAT, "lon": BENSON_LON + 0.001}, + ], + }, + { + "type": "way", + "id": 12, + "tags": {"highway": "primary", "maxspeed": "60 mph", "name": "US 12"}, + "geometry": [ + {"lat": BENSON_LAT + 0.01, "lon": BENSON_LON - 0.001}, + {"lat": BENSON_LAT + 0.01, "lon": BENSON_LON + 0.001}, + ], + }, + { + "type": "way", + "id": 13, + "tags": {"place": "city", "name": "Benson"}, + "geometry": [ + {"lat": BENSON_LAT - 0.05, "lon": BENSON_LON - 0.05}, + {"lat": BENSON_LAT - 0.05, "lon": BENSON_LON + 0.05}, + {"lat": BENSON_LAT + 0.05, "lon": BENSON_LON + 0.05}, + {"lat": BENSON_LAT + 0.05, "lon": BENSON_LON - 0.05}, + ], + }, + ] + } + skipped = ways_from_overpass(payload) + assert [w["way_id"] for w in skipped] == [12] + + filled = ways_from_overpass(payload, fill_unmarked=True) + ids = {w["way_id"]: w for w in filled} + assert 10 in ids and 12 in ids + assert 11 not in ids + assert 13 not in ids # place polygon is not a highway + assert ids[10]["source"] == FILL_SOURCE + assert abs(ids[10]["maxspeed_ms"] - _ms(30)) < 0.2 + assert ids[12]["source"] == "osm" + assert abs(ids[12]["maxspeed_ms"] - _ms(60)) < 0.2 + + +def test_overpass_query_unmarked_fetches_all_fillable_highways(): + tagged = overpass_query(44.0, -96.0, 46.0, -94.0, include_unmarked=False) + assert 'way["highway"]["maxspeed"]' in tagged + unmarked = overpass_query(44.0, -96.0, 46.0, -94.0, include_unmarked=True) + assert '["maxspeed"]' not in unmarked + assert "motorway" in unmarked + assert "admin_level" in unmarked + assert "out geom" in unmarked + + +def test_benson_bbox_is_clipped_to_minnesota(): + assert in_minnesota(BENSON_LAT, BENSON_LON) + south, west, north, east = benson_fill_bbox() + assert west >= -97.239 - 1e-9 + assert in_minnesota((south + north) / 2, (west + east) / 2) + box = bbox_from_center(BENSON_LAT, BENSON_LON, 160.934) + assert bbox_intersects_minnesota(box) + sf = bbox_from_center(37.7749, -122.4194, 160.934) + assert not bbox_intersects_minnesota(sf) diff --git a/selfdrive/mapd/tests/test_osm_db.py b/selfdrive/mapd/tests/test_osm_db.py new file mode 100644 index 00000000000000..2bb6e4637900fc --- /dev/null +++ b/selfdrive/mapd/tests/test_osm_db.py @@ -0,0 +1,1050 @@ +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.constants import HEADING_ALIGN_DEG, MIN_ZONE_LENGTH_M, OSM_SIGN_LEAD_S, osm_sign_lead_m +from openpilot.selfdrive.mapd.osm_db import ( + OsmSpeedLimitDB, _continues_route, _heading_aligned, _offset_point, _pack_coords, + _unpack_coords, _wrap_heading_delta, simplify_coords, +) +from openpilot.selfdrive.mapd.overpass import ways_from_overpass +from openpilot.selfdrive.mapd.speed_limit import parse_maxspeed + + +def test_continues_route_rejects_cross_street_fills(): + assert _continues_route(90.0, 90.0, "US 12", "trunk", "US 12", "trunk") + assert _continues_route(90.0, 80.0, "US 12", "trunk", "US 12", "primary") + assert not _continues_route(90.0, 0.0, "US 12", "trunk", "Oak", "residential") + assert not _continues_route(90.0, 90.0, "US 12", "trunk", "Oak", "residential") + # Same name may change class in town. + assert _continues_route(90.0, 90.0, "US 12", "trunk", "US 12", "residential") + # Reverse-digitized along-route town ways (Δ ≈ 180°) must stay on-route. + # Name change is normal (US 12 → Atlantic / Main Avenue); class continuity + # + bidirectional heading is enough. + assert _heading_aligned(110.0, 291.0) + assert _heading_aligned(124.0, 304.0) + assert not _heading_aligned(110.0, 20.0) + assert _continues_route(110.0, 291.0, "US 12", "trunk", "Atlantic Avenue", "primary") + assert _continues_route(124.0, 304.0, "US 12", "trunk", "Main Avenue", "primary") + # Ep3 Kerkhoven: travel SE ~117.5°, Atlantic 30 digitized NW ~310°. + assert _heading_aligned(117.5, 310.3) + assert _wrap_heading_delta(117.5, 310.3) > HEADING_ALIGN_DEG # old unidirectional gate + assert _continues_route(117.5, 310.3, "", "trunk", "Atlantic Avenue", "trunk") + # Ep4 Pennock: travel SE ~112°, Pacific Ave 45 digitized NW ~290°. + assert _heading_aligned(111.8, 289.9) + assert _wrap_heading_delta(111.8, 289.9) > HEADING_ALIGN_DEG + assert _continues_route(111.8, 289.9, "", "trunk", "Pacific Avenue Southwest", "trunk") + # Reverse-digitized residential fill is still a fill. + assert not _continues_route(110.0, 290.0, "US 12", "trunk", "Oak", "residential") + # ~90° cross street still fails heading (min(Δ, 180−Δ) = 90). + assert not _heading_aligned(112.0, 22.0) + assert not _continues_route(112.0, 22.0, "", "trunk", "County Road", "unclassified") + + +def test_parse_maxspeed_units(): + assert parse_maxspeed(None) is None + assert parse_maxspeed("") is None + assert parse_maxspeed("signals") is None + assert parse_maxspeed("US:urban") is None + mph = parse_maxspeed("65 mph") + assert mph is not None and abs(mph - 65 * CV.MPH_TO_MS) < 1e-6 + kph = parse_maxspeed("100") + assert kph is not None and abs(kph - 100 * CV.KPH_TO_MS) < 1e-6 + assert parse_maxspeed("50 km/h") == parse_maxspeed("50") + + +def test_rtree_lookup_and_heading(tmp_path): + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + # Eastbound 45 mph way through (37.0, -122.0) + OsmSpeedLimitDB.insert_way( + con, 1, "Test Rd", "primary", 45 * CV.MPH_TO_MS, + [(37.0, -122.001), (37.0, -121.999)], + ) + # Parallel 25 mph way 200m north — should not win + OsmSpeedLimitDB.insert_way( + con, 2, "Side St", "residential", 25 * CV.MPH_TO_MS, + [(37.002, -122.001), (37.002, -121.999)], + ) + con.commit() + con.close() + + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.0, bearing_deg=90.0) + assert m is not None + assert m.way_id == 1 + assert abs(m.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.1 + assert m.road_name == "Test Rd" + + miss = db.lookup(38.0, -122.0, bearing_deg=90.0) + assert miss is None + db.close() + + +def test_lookahead_finds_upcoming_lower_limit(tmp_path): + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + # Eastbound 45 mph, then 25 mph after lon=-122.0 (~180 m at this latitude). + OsmSpeedLimitDB.insert_way( + con, 1, "Main", "primary", 45 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Main", "primary", 25 * CV.MPH_TO_MS, + [(37.0, -122.000), (37.0, -121.996)], + ) + con.commit() + con.close() + + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert m.way_id == 1 + assert abs(m.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + assert abs(m.next_speed_limit_ms - 25 * CV.MPH_TO_MS) < 0.2 + assert 80.0 <= m.next_distance_m <= 280.0 + db.close() + + +def test_lookahead_reports_upcoming_higher_but_does_not_hide_current(tmp_path): + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "Main", "primary", 25 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Main", "primary", 45 * CV.MPH_TO_MS, + [(37.0, -122.000), (37.0, -121.996)], + ) + con.commit() + con.close() + + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 25 * CV.MPH_TO_MS) < 0.2 + assert abs(m.next_speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + db.close() + + +def test_min_zone_length_is_about_250_feet(): + assert abs(MIN_ZONE_LENGTH_M - 76.0) < 1e-9 + assert 75.0 <= MIN_ZONE_LENGTH_M <= 77.0 + + +def test_lookahead_does_not_skip_short_intermediate_limit(tmp_path): + """Along-way still publishes a real short-but-legal 60→50. + + The 50 must last longer than MIN_ZONE_LENGTH_M (~250 ft). US 12 east of + Benson is ~760 m of tagged 50 — this fixture is a compact ~200 m 50. + A stub under ~250 ft is ignored (see test_next_limit_ignores_stub_zone). + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + # ~178 m of 60, ~200 m of 50, then 30. + start50 = (37.0, -122.000) + end50 = _offset_point(start50[0], start50[1], 90.0, 200.0) + end30 = _offset_point(end50[0], end50[1], 90.0, 250.0) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -122.004), start50], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "US 12", "trunk", 50 * CV.MPH_TO_MS, + [start50, end50], + ) + OsmSpeedLimitDB.insert_way( + con, 3, "US 12", "trunk", 30 * CV.MPH_TO_MS, + [end50, end30], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 50 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + assert m.next_distance_m < 250.0 + db.close() + + +def test_benson_us12_60_to_50_is_next_not_30(tmp_path): + """Way 1557241351 (60) then 1227205099 (50, ~760 m) westbound toward Benson MN.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1557241351, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [ + (45.3079280, -95.5767060), + (45.3084190, -95.5784110), + (45.3087680, -95.5796230), + (45.3088579, -95.5799336), + ], + ) + OsmSpeedLimitDB.insert_way( + con, 1227205099, "US 12", "trunk", 50 * CV.MPH_TO_MS, + [ + (45.3088579, -95.5799336), + (45.3093400, -95.5816000), + (45.3103910, -95.5852260), + (45.3114806, -95.5888992), + ], + ) + OsmSpeedLimitDB.insert_way( + con, 99, "US 12", "trunk", 30 * CV.MPH_TO_MS, + [(45.3114806, -95.5888992), (45.3122, -95.5930)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(45.3079280, -95.5767060, bearing_deg=290.0) + assert m is not None + assert m.way_id == 1557241351 + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 50 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + assert 180.0 <= m.next_distance_m <= 320.0 + # 1.5 s offset into the short 50 must not snap posted to 50. + v60 = 60 * CV.MPH_TO_MS + near50 = db.lookup(45.3087680, -95.5796230, bearing_deg=290.0, v_ego_ms=v60) + assert near50 is not None + assert abs(near50.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(near50.next_speed_limit_ms - 50 * CV.MPH_TO_MS) < 0.3 + db.close() + + +def test_next_limit_ignores_cross_street_when_highway_curves(tmp_path): + """Geodesic heading ray leaves a curved 60 and must not pick a 30 fill.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000), (37.0005, -121.996)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Oak", "residential", 30 * CV.MPH_TO_MS, + [(36.999, -121.998), (37.001, -121.998)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0 + db.close() + + +def test_next_limit_ignores_cross_streets_with_gps_heading_error(tmp_path): + """Long tagged 60: remaining > 600 m, so along-way used to return None and + geodesic picked a 30 fill as soon as GPS heading was a few degrees off.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -122.010), (37.0, -121.990)], + ) + for i, lon in enumerate((-122.005, -122.003, -122.001, -121.999)): + OsmSpeedLimitDB.insert_way( + con, 10 + i, "Cross", "residential", 30 * CV.MPH_TO_MS, + [(36.997, lon), (37.003, lon)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + for hdg in (90.0, 85.0, 70.0): + m = db.lookup(37.0, -122.006, bearing_deg=hdg) + assert m is not None, hdg + assert m.way_id == 1, hdg + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3, hdg + assert m.next_speed_limit_ms == 0.0, (hdg, m.next_speed_limit_ms * CV.MS_TO_MPH) + db.close() + + +def test_on_route_60_to_50_wins_over_cross_street_fill(tmp_path): + """US 12 60→50 at an intersection with a 30 mph residential fill.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "US 12", "trunk", 50 * CV.MPH_TO_MS, + [(37.0, -122.000), (37.0, -121.996)], + ) + OsmSpeedLimitDB.insert_way( + con, 3, "Oak", "residential", 30 * CV.MPH_TO_MS, + [(36.998, -122.000), (37.002, -122.000)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 50 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_geodesic_gap_finds_on_route_50_not_cross_street(tmp_path): + """OSM gap after the 60 way: heading ray may fill in, but not a 30 cross street.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + # ~80 m gap (along-way 12/25/40 m steps miss; geodesic 40 m probes hit). + OsmSpeedLimitDB.insert_way( + con, 2, "US 12", "trunk", 50 * CV.MPH_TO_MS, + [(37.0, -121.9991), (37.0, -121.996)], + ) + OsmSpeedLimitDB.insert_way( + con, 3, "Oak", "residential", 30 * CV.MPH_TO_MS, + [(36.998, -121.99955), (37.002, -121.99955)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 50 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_benson_us12_long_60_ignores_side_street_30_fill(tmp_path): + """Westbound US 12 60 near Benson: a statutory 30 fill beside the highway is + not nextSpeedLimit. MAX must not walk down toward that 30.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1557241351, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [ + (45.3079280, -95.5767060), + (45.3084190, -95.5784110), + (45.3087680, -95.5796230), + (45.3088579, -95.5799336), + (45.3100, -95.5840), + (45.3120, -95.5900), + ], + ) + # North-south residential ~200 m along heading 290 from the start. + OsmSpeedLimitDB.insert_way( + con, 200, "Minnesota Ave", "residential", 30 * CV.MPH_TO_MS, + [(45.3075, -95.5784110), (45.3095, -95.5784110)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(45.3079280, -95.5767060, bearing_deg=290.0) + assert m is not None + assert m.way_id == 1557241351 + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0 + db.close() + + +def test_next_limit_ignores_stub_zone_shorter_than_min_length(tmp_path): + """~10 m of 30 between two 60s is bleed, not a posted drop. + + Same name/class so #53 route continuity would accept it; min-zone must reject. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + # ~10 m stub (well under MIN_ZONE_LENGTH_M / ~250 ft). + OsmSpeedLimitDB.insert_way( + con, 2, "US 12", "trunk", 30 * CV.MPH_TO_MS, + [(37.0, -122.000), (37.0, -121.99989)], + ) + OsmSpeedLimitDB.insert_way( + con, 3, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -121.99989), (37.0, -121.996)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0, m.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_next_limit_ignores_stub_under_250_ft(tmp_path): + """~60 m of 30 (~197 ft) is still under MIN_ZONE_LENGTH_M (~250 ft). + + #82/#83's 15 m / ~50 ft gate still flashed these. Same name/class so + #53 would accept it; the raised min-zone must reject. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + start30 = (37.0, -122.000) + end30 = _offset_point(start30[0], start30[1], 90.0, 60.0) + end60 = _offset_point(end30[0], end30[1], 90.0, 250.0) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -122.004), start30], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "US 12", "trunk", 30 * CV.MPH_TO_MS, + [start30, end30], + ) + OsmSpeedLimitDB.insert_way( + con, 3, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [end30, end60], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0, m.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_next_limit_keeps_real_drop_longer_than_min_length(tmp_path): + """A 30 that continues ~200 m after a 60 is a real on-route drop.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "US 12", "trunk", 30 * CV.MPH_TO_MS, + [(37.0, -122.000), (37.0, -121.997)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + m = db.lookup(37.0, -122.002, bearing_deg=90.0) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 30 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def _reverse(coords: list[tuple[float, float]]) -> list[tuple[float, float]]: + return list(reversed(coords)) + + +def test_town_entry_short_first_way_long_contiguous_run(tmp_path): + """Ep1 Benson / Atlantic: first 30 way is ~76 m (the old first-way gate), + but the contiguous same-limit chain is hundreds of meters. + + Ways are reverse-digitized (Δheading ≈ 180°) and rename US 12 → Atlantic. + Early look-ahead must publish next=30 before GPS is on the town way. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + travel = 90.0 + us12_start = (37.0, -122.012) + junc = _offset_point(us12_start[0], us12_start[1], travel, 550.0) + a1_end = _offset_point(junc[0], junc[1], travel, 76.1) + a2_end = _offset_point(a1_end[0], a1_end[1], travel, 200.0) + a3_end = _offset_point(a2_end[0], a2_end[1], travel, 200.0) + OsmSpeedLimitDB.insert_way( + con, 18267060, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [us12_start, junc], + ) + OsmSpeedLimitDB.insert_way( + con, 1227205098, "Atlantic Avenue", "primary", 30 * CV.MPH_TO_MS, + _reverse([junc, a1_end]), + ) + OsmSpeedLimitDB.insert_way( + con, 18267487, "Atlantic Avenue", "primary", 30 * CV.MPH_TO_MS, + _reverse([a1_end, a2_end]), + ) + OsmSpeedLimitDB.insert_way( + con, 1227205097, "Atlantic Avenue", "primary", 30 * CV.MPH_TO_MS, + _reverse([a2_end, a3_end]), + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + # ~400 m before the junction — inside Early 600 m, still posted 60. + qlat, qlon = _offset_point(junc[0], junc[1], travel + 180.0, 400.0) + m = db.lookup(qlat, qlon, bearing_deg=travel) + assert m is not None + assert m.way_id == 18267060 + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 30 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + assert 300.0 <= m.next_distance_m <= 500.0 + db.close() + + +def test_town_entry_reverse_digitized_long_way(tmp_path): + """Ep2 Main Ave: the town 30 is long (~400 m here; on-car 1149 m) but + reverse-digitized. Short 60 stubs sit in front. next must still publish 30. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + travel = 90.0 + us12_start = (37.0, -122.012) + junc = _offset_point(us12_start[0], us12_start[1], travel, 550.0) + main60_end = _offset_point(junc[0], junc[1], travel, 250.0) + stub60_end = _offset_point(main60_end[0], main60_end[1], travel, 23.0) + town30_end = _offset_point(stub60_end[0], stub60_end[1], travel, 400.0) + OsmSpeedLimitDB.insert_way( + con, 18267048, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [us12_start, junc], + ) + OsmSpeedLimitDB.insert_way( + con, 1227205096, "Main Avenue", "primary", 60 * CV.MPH_TO_MS, + _reverse([junc, main60_end]), + ) + OsmSpeedLimitDB.insert_way( + con, 1557241354, "Main Avenue", "primary", 60 * CV.MPH_TO_MS, + _reverse([main60_end, stub60_end]), + ) + OsmSpeedLimitDB.insert_way( + con, 18267827, "Main Avenue", "primary", 30 * CV.MPH_TO_MS, + _reverse([stub60_end, town30_end]), + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + # On the highway ~150 m before the name change: 150+250+23 ≈ 423 m to the 30. + qlat, qlon = _offset_point(junc[0], junc[1], travel + 180.0, 150.0) + m = db.lookup(qlat, qlon, bearing_deg=travel) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 30 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + assert m.next_distance_m > 200.0 + # On the Main Ave 60 lead-in (the on-car name change): still posted 60, next=30. + on_main = _offset_point(junc[0], junc[1], travel, 100.0) + m2 = db.lookup(on_main[0], on_main[1], bearing_deg=travel) + assert m2 is not None + assert abs(m2.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m2.next_speed_limit_ms - 30 * CV.MPH_TO_MS) < 0.3, m2.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_town_entry_kerkhoven_long_reverse_digitized(tmp_path): + """Ep3 ~19:24 Kerkhoven: even longer town than Murdock, still reverse-digitized. + + Same drive as REPORT.md ep1/ep2 (`1c95345a3286a5db|000000df--467073c363`). + US 12 60 way 18267051 then Atlantic Avenue 30: 47 m + 68 m stubs and an + 876 m town way (chain ~1.1 km). Digitized NW (~300°) while travel is SE + (~118°). Short-zone-alone cannot explain a dead next — the long way is + far past 76 m. The old unidirectional heading gate can. + + Real corridor coords (OSM), not a corridor hardcode in matcher code. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + # Approach 60, first ~1.4 km from the town end (digitized NW). + OsmSpeedLimitDB.insert_way( + con, 18267051, "", "trunk", 60 * CV.MPH_TO_MS, + [ + (45.1934513, -95.3224471), + (45.1935615, -95.3227475), + (45.1936458, -95.3230027), + (45.1937388, -95.3232855), + (45.1938181, -95.3235502), + (45.1938968, -95.3238425), + (45.1941100, -95.3246503), + (45.1942096, -95.3249748), + (45.1943107, -95.3252671), + (45.1944248, -95.3255547), + (45.1955660, -95.3283440), + (45.1957940, -95.3289060), + (45.1997270, -95.3385890), + ], + ) + OsmSpeedLimitDB.insert_way( + con, 1312882771, "Atlantic Avenue", "trunk", 30 * CV.MPH_TO_MS, + [(45.1932411, -95.3219240), (45.1934513, -95.3224471)], + ) + OsmSpeedLimitDB.insert_way( + con, 1312882772, "Atlantic Avenue", "trunk", 30 * CV.MPH_TO_MS, + [(45.1929386, -95.3211712), (45.1930521, -95.3214537), (45.1932411, -95.3219240)], + ) + OsmSpeedLimitDB.insert_way( + con, 18267484, "Atlantic Avenue", "trunk", 30 * CV.MPH_TO_MS, + [ + (45.1889261, -95.3115623), + (45.1891320, -95.3119070), + (45.1892753, -95.3122187), + (45.1893454, -95.3123712), + (45.1893958, -95.3124952), + (45.1894422, -95.3126084), + (45.1898958, -95.3137152), + (45.1904075, -95.3149739), + (45.1904499, -95.3150765), + (45.1909150, -95.3162020), + (45.1914230, -95.3174460), + (45.1919300, -95.3186970), + (45.1924364, -95.3199345), + (45.1929386, -95.3211712), + ], + ) + OsmSpeedLimitDB.insert_way( + con, 1227205094, "Atlantic Avenue", "trunk", 30 * CV.MPH_TO_MS, + [(45.1881551, -95.3101903), (45.1883478, -95.3105791), (45.1889261, -95.3115623)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + travel = 117.5 + # ~400 m before the 30, still on US 12 60 (inside Early 600 m). + qlat, qlon = _offset_point(45.1934513, -95.3224471, 297.5, 400.0) + m = db.lookup(qlat, qlon, bearing_deg=travel) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 30 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + assert 250.0 <= m.next_distance_m <= 550.0 + # Closer in: still posted 60, next still the long town 30. + q2lat, q2lon = _offset_point(45.1934513, -95.3224471, 297.5, 150.0) + m2 = db.lookup(q2lat, q2lon, bearing_deg=travel) + assert m2 is not None + assert abs(m2.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m2.next_speed_limit_ms - 30 * CV.MPH_TO_MS) < 0.3, m2.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_town_entry_pennock_60_to_45_reverse_digitized(tmp_path): + """Ep4 ~19:32 Pennock: shorter town, 60→45, still reverse-digitized. + + Same drive. US 12 60 way 18120141 then Pacific Avenue SW/SE 45 + (719 m + 1010 m). Digitized NW (~290°) while travel is SE (~112°). + Do not lower MIN_ZONE — this 45 run is far past 76 m. next must publish 45 + so Early can bleed before the sign. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 18120141, "", "trunk", 60 * CV.MPH_TO_MS, + [ + (45.1497750, -95.1859457), + (45.1499532, -95.1865781), + (45.1501123, -95.1871137), + (45.1506249, -95.1888123), + (45.1508476, -95.1895753), + (45.1510528, -95.1903475), + (45.1550563, -95.2060945), + ], + ) + OsmSpeedLimitDB.insert_way( + con, 18120656, "Pacific Avenue Southwest", "trunk", 45 * CV.MPH_TO_MS, + [ + (45.1475731, -95.1773305), + (45.1479335, -95.1787404), + (45.1482841, -95.1801123), + (45.1497750, -95.1859457), + ], + ) + OsmSpeedLimitDB.insert_way( + con, 18120434, "Pacific Avenue Southeast", "trunk", 45 * CV.MPH_TO_MS, + [ + (45.1445357, -95.1651890), + (45.1459258, -95.1708021), + (45.1465717, -95.1733621), + (45.1468998, -95.1746620), + (45.1472401, -95.1760108), + (45.1475731, -95.1773305), + ], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + travel = 111.8 + qlat, qlon = _offset_point(45.1497750, -95.1859457, 291.8, 400.0) + m = db.lookup(qlat, qlon, bearing_deg=travel) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + assert 250.0 <= m.next_distance_m <= 550.0 + q2lat, q2lon = _offset_point(45.1497750, -95.1859457, 291.8, 150.0) + m2 = db.lookup(q2lat, q2lon, bearing_deg=travel) + assert m2 is not None + assert abs(m2.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m2.next_speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.3, m2.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_angled_cross_street_45_blip_still_ignored(tmp_path): + """Do not reintroduce aggressive look-ahead for angled side-road bleed. + + SE highway vs a ~40° 45 mph fill that only lasts ~60 m along heading + (returns to 60). MIN_ZONE stays ~250 ft — this blip must not arm next. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + travel = 112.0 + start = (37.0, -122.010) + mid = _offset_point(start[0], start[1], travel, 400.0) + after = _offset_point(mid[0], mid[1], travel, 12.0) + end = _offset_point(start[0], start[1], travel, 900.0) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [start, mid], + ) + OsmSpeedLimitDB.insert_way( + con, 3, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [after, end], + ) + # ~40° off travel: long enough to be geometrically tempting, short along + # the highway heading so persist / returns-to-prior must reject. + fill_a = _offset_point(mid[0], mid[1], travel - 140.0, 80.0) + fill_b = _offset_point(mid[0], mid[1], travel + 40.0, 80.0) + OsmSpeedLimitDB.insert_way( + con, 2, "County Road", "unclassified", 45 * CV.MPH_TO_MS, + [fill_a, mid, fill_b], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + qlat, qlon = _offset_point(mid[0], mid[1], travel + 180.0, 200.0) + m = db.lookup(qlat, qlon, bearing_deg=travel) + assert m is not None + assert m.way_id == 1 + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0, m.next_speed_limit_ms * CV.MS_TO_MPH + # GPS snapped onto the fill, still heading along US 12. + on_fill = _offset_point(mid[0], mid[1], travel + 40.0, 6.0) + m2 = db.lookup(on_fill[0], on_fill[1], bearing_deg=travel) + assert m2 is not None + assert abs(m2.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m2.next_speed_limit_ms == 0.0, m2.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_town_entry_short_first_piece_under_min_zone_still_publishes(tmp_path): + """First town 30 piece is well under ~250 ft; the same-limit run is not.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + travel = 90.0 + us12_start = (37.0, -122.010) + junc = _offset_point(us12_start[0], us12_start[1], travel, 400.0) + first_end = _offset_point(junc[0], junc[1], travel, 40.0) + rest_end = _offset_point(first_end[0], first_end[1], travel, 250.0) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [us12_start, junc], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Atlantic Avenue", "primary", 30 * CV.MPH_TO_MS, + _reverse([junc, first_end]), + ) + OsmSpeedLimitDB.insert_way( + con, 3, "Atlantic Avenue", "primary", 30 * CV.MPH_TO_MS, + _reverse([first_end, rest_end]), + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + qlat, qlon = _offset_point(junc[0], junc[1], travel + 180.0, 200.0) + m = db.lookup(qlat, qlon, bearing_deg=travel) + assert m is not None + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert abs(m.next_speed_limit_ms - 30 * CV.MPH_TO_MS) < 0.3, m.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_side_road_bleed_blip_still_ignored_with_reverse_town_ways(tmp_path): + """Standing rule: N–S residential / unclassified fill must not arm next. + + Same highway as the town-entry fixtures (eastbound 60) plus a long N–S 30 + fill. Reverse-digitized heading tolerance must not open this hole. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + travel = 90.0 + start = (37.0, -122.010) + mid = _offset_point(start[0], start[1], travel, 400.0) + end = _offset_point(start[0], start[1], travel, 900.0) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [start, mid, end], + ) + cross_n = _offset_point(mid[0], mid[1], 0.0, 200.0) + cross_s = _offset_point(mid[0], mid[1], 180.0, 200.0) + OsmSpeedLimitDB.insert_way( + con, 2, "Oak", "residential", 30 * CV.MPH_TO_MS, + [cross_s, mid, cross_n], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + qlat, qlon = _offset_point(mid[0], mid[1], travel + 180.0, 200.0) + m = db.lookup(qlat, qlon, bearing_deg=travel) + assert m is not None + assert m.way_id == 1 + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0, m.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_current_match_ignores_cross_street_bleed(tmp_path): + """GPS on a side street at the intersection must not snap posted to 30.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "Main", "primary", 60 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -121.996)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Oak", "residential", 30 * CV.MPH_TO_MS, + [(36.997, -122.000), (37.003, -122.000)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + # ~5 m north of the highway, on Oak, heading east along Main. + qlat, qlon = _offset_point(37.0, -122.000, 0.0, 5.0) + m = db.lookup(qlat, qlon, bearing_deg=90.0) + assert m is not None + assert m.way_id == 1 + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0 + db.close() + + +def test_se_heading_ew_fill_does_not_drop_posted_or_next(tmp_path): + """SE highway vs E-W grid: Δheading ~30° is inside HEADING_ALIGN_DEG. + + #53's bearing gate still lets that fill score as a current/next candidate. + The min-zone gate must keep posted on the highway (US 12 SE Benson→DeGraff + pattern; geometry is generic, not a corridor hardcode). + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + start = (37.0, -122.004) + mid = _offset_point(start[0], start[1], 120.0, 400.0) + end = _offset_point(start[0], start[1], 120.0, 800.0) + OsmSpeedLimitDB.insert_way( + con, 1, "US 12", "trunk", 60 * CV.MPH_TO_MS, + [start, mid, end], + ) + cross_w = _offset_point(mid[0], mid[1], 270.0, 200.0) + cross_e = _offset_point(mid[0], mid[1], 90.0, 200.0) + OsmSpeedLimitDB.insert_way( + con, 2, "Township", "unclassified", 30 * CV.MPH_TO_MS, + [cross_w, mid, cross_e], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + # On the fill, a few meters west of the crossing, still heading SE on US 12. + qlat, qlon = _offset_point(mid[0], mid[1], 270.0, 6.0) + m = db.lookup(qlat, qlon, bearing_deg=120.0) + assert m is not None + assert m.way_id == 1, (m.way_id, m.road_name, m.speed_limit_ms * CV.MS_TO_MPH) + assert abs(m.speed_limit_ms - 60 * CV.MPH_TO_MS) < 0.3 + assert m.next_speed_limit_ms == 0.0, m.next_speed_limit_ms * CV.MS_TO_MPH + db.close() + + +def test_osm_sign_lead_is_speed_times_1_5s_not_fixed_meters(): + """Justin: 1.5 s delay. 50 mph → ~33.5 m, 60 mph → ~40 m. Not a constant offset.""" + assert abs(OSM_SIGN_LEAD_S - 1.5) < 1e-9 + m50 = osm_sign_lead_m(50 * CV.MPH_TO_MS) + m60 = osm_sign_lead_m(60 * CV.MPH_TO_MS) + assert abs(m50 - 50 * CV.MPH_TO_MS * 1.5) < 1e-9 + assert abs(m60 - 60 * CV.MPH_TO_MS * 1.5) < 1e-9 + assert abs(m50 - 33.5) < 0.1 + assert abs(m60 - 40.2) < 0.1 + assert m60 > m50 + 5.0 + assert osm_sign_lead_m(0.0) == 0.0 + assert osm_sign_lead_m(-5.0) == 0.0 + + +def test_sign_lead_advances_limit_and_next_distance(tmp_path): + """GNSS lag offset: posted match and remaining-to-next are at v*1.5 s.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "Main", "primary", 45 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Main", "primary", 25 * CV.MPH_TO_MS, + [(37.0, -122.000), (37.0, -121.996)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + v60 = 60 * CV.MPH_TO_MS + lead_m = osm_sign_lead_m(v60) + assert abs(lead_m - v60 * OSM_SIGN_LEAD_S) < 1e-9 + + gps_lat, gps_lon = 37.0, -122.002 + cold = db.lookup(gps_lat, gps_lon, bearing_deg=90.0) + hot = db.lookup(gps_lat, gps_lon, bearing_deg=90.0, v_ego_ms=v60) + assert cold is not None and hot is not None + assert abs(cold.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + assert abs(hot.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + assert abs(hot.next_speed_limit_ms - 25 * CV.MPH_TO_MS) < 0.2 + assert abs(cold.next_speed_limit_ms - 25 * CV.MPH_TO_MS) < 0.2 + # Remaining is from GPS minus v*1.5 s; +110 m decrease margin is separate. + assert hot.next_distance_m < cold.next_distance_m + assert abs((cold.next_distance_m - hot.next_distance_m) - lead_m) < 12.0 + + # Offset already in the 25: do not snap posted to 25. Keep 45 and next=25 + # so kin+110 m can ease MAX (the 60→50 snap). + qlat, qlon = _offset_point(37.0, -122.000, 270.0, 20.0) + at_sign = db.lookup(qlat, qlon, bearing_deg=90.0) + early = db.lookup(qlat, qlon, bearing_deg=90.0, v_ego_ms=v60) + assert at_sign is not None and abs(at_sign.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + assert early is not None and abs(early.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + assert abs(early.next_speed_limit_ms - 25 * CV.MPH_TO_MS) < 0.2 + assert early.next_distance_m < at_sign.next_distance_m + db.close() + + +def test_sign_lead_raises_posted_when_offset_already_in_higher_zone(tmp_path): + """Same 1.5 s offset both ways: 20 m before 25→45, lag-corrected posted is 45.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "Main", "primary", 25 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Main", "primary", 45 * CV.MPH_TO_MS, + [(37.0, -122.000), (37.0, -121.996)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + v60 = 60 * CV.MPH_TO_MS + qlat, qlon = _offset_point(37.0, -122.000, 270.0, 20.0) + at_gps = db.lookup(qlat, qlon, bearing_deg=90.0) + lagged = db.lookup(qlat, qlon, bearing_deg=90.0, v_ego_ms=v60) + assert at_gps is not None and abs(at_gps.speed_limit_ms - 25 * CV.MPH_TO_MS) < 0.2 + assert lagged is not None and abs(lagged.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + db.close() + + +def test_higher_limit_far_ahead_stays_next_not_posted(tmp_path): + """~180 m of 25 then 45: 1.5 s offset (~40 m) is still on 25. Not lookahead raise.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "Main", "primary", 25 * CV.MPH_TO_MS, + [(37.0, -122.004), (37.0, -122.000)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Main", "primary", 45 * CV.MPH_TO_MS, + [(37.0, -122.000), (37.0, -121.996)], + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + v60 = 60 * CV.MPH_TO_MS + m = db.lookup(37.0, -122.002, bearing_deg=90.0, v_ego_ms=v60) + assert m is not None + assert abs(m.speed_limit_ms - 25 * CV.MPH_TO_MS) < 0.2 + assert abs(m.next_speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + db.close() + + +def test_overpass_json_import(tmp_path): + payload = { + "elements": [ + { + "type": "way", + "id": 42, + "tags": {"highway": "residential", "name": "Oak", "maxspeed": "25 mph"}, + "geometry": [ + {"lat": 37.5, "lon": -122.4}, + {"lat": 37.501, "lon": -122.4}, + ], + }, + { + "type": "way", + "id": 43, + "tags": {"highway": "service", "maxspeed": "signals"}, + "geometry": [{"lat": 37.5, "lon": -122.4}, {"lat": 37.5, "lon": -122.401}], + }, + ] + } + ways = ways_from_overpass(payload) + assert len(ways) == 1 + assert ways[0]["way_id"] == 42 + out = str(tmp_path / "out.sqlite") + con = OsmSpeedLimitDB.create(out) + for w in ways: + OsmSpeedLimitDB.insert_way( + con, w["way_id"], w["name"], w["highway"], w["maxspeed_ms"], w["coords"], + junction=w.get("junction") or "", + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(out) + assert db.open() + m = db.lookup(37.5005, -122.4, bearing_deg=0.0) + assert m is not None and m.way_id == 42 + + +def test_delete_ways_intersecting_bbox(tmp_path): + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 1, "Near", "primary", 35 * CV.MPH_TO_MS, + [(37.0, -122.001), (37.0, -121.999)], + ) + OsmSpeedLimitDB.insert_way( + con, 2, "Far", "primary", 25 * CV.MPH_TO_MS, + [(40.7, -74.001), (40.7, -73.999)], + ) + n = OsmSpeedLimitDB.delete_ways_intersecting_bbox(con, 36.9, -122.1, 37.1, -121.9) + assert n == 1 + OsmSpeedLimitDB.recount_ways(con) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + assert db.lookup(37.0, -122.0, bearing_deg=90.0) is None + far = db.lookup(40.7, -74.0, bearing_deg=90.0) + assert far is not None and far.way_id == 2 + db.close() + assert OsmSpeedLimitDB.way_count(path) == 1 + + +def test_simplify_collinear_and_f64_unpack(): + # 1 km eastbound straight line at 1 m spacing should collapse to endpoints. + coords = [(37.0, -122.0 + i * 1e-5) for i in range(100)] + simple = simplify_coords(coords, tol_m=5.0) + assert len(simple) == 2 + assert simple[0] == coords[0] and simple[-1] == coords[-1] + + packed64 = _pack_coords([(37.5, -122.4), (37.6, -122.4)]) + # Force a legacy float64 blob and ensure unpack still works. + import struct + n = 2 + blob = struct.pack("= RB_V_MIN_MS - 1e-6 + on_ring = RoundaboutHint(on_roundabout=True, speed_limit_ms=20.0 * CV.MPH_TO_MS) + assert abs(roundabout_ease_v_ms(on_ring, v49, v49) - 20.0 * CV.MPH_TO_MS) < 1e-6 + # Low-speed decel onset stays 140 m (Oct 1): 35 mph can still hit 18 by the ring at ~0.65 m/s². + # Oct 11: the search reach (RB_FUNNEL_M) is the 450 m max of the speed-based onset. + assert 80.0 <= RB_FUNNEL_MIN_M <= 100.0 + assert 130.0 <= RB_DECEL_ONSET_M <= 140.0 and RB_FUNNEL_M == 450.0 + assert (35.0 * CV.MPH_TO_MS) ** 2 / 2.0 - (18.0 * CV.MPH_TO_MS) ** 2 / 2.0 <= 0.7 * RB_DECEL_ONSET_M + + +def test_no_hint_does_not_ease(): + assert roundabout_ease_v_ms(None, 22.0, 22.0) is None + assert roundabout_ease_v_ms(RoundaboutHint(), 22.0, 22.0) is None + + +def test_plan_funnel_cuts_plus_a(): + """Willmar: aTarget ~+0.4 at 45–49 mph must become kinematic −a, not −0.55.""" + v49 = 49.0 * CV.MPH_TO_MS + v50 = 50.0 * CV.MPH_TO_MS + hint = RoundaboutHint(approaching=True, distance_m=90.0, speed_limit_ms=20.0 * CV.MPH_TO_MS) + _vc, _vh, a, rb = apply_roundabout_plan(v49, v50, v50, 0.4, hint) + assert rb is not None and a <= RB_A_FLOOR_MS2 + _vc, _vh, a0, rb0 = apply_roundabout_plan(v49, v50, v50, 0.4, None) + assert rb0 is None and a0 == 0.4 + + +def test_outer_bias_sign_and_magnitude(): + rht = roundabout_outer_path_offset_m(on_roundabout=True, is_rhd=False) + lhd = roundabout_outer_path_offset_m(on_roundabout=True, is_rhd=True) + assert rht < 0.0 # right / outer in US + assert lhd > 0.0 + assert RB_OUTER_OFFSET_MIN_M <= abs(rht) <= RB_OUTER_OFFSET_MAX_M + assert abs(abs(rht) - RB_OUTER_OFFSET_M) < 1e-6 + assert abs(rht) >= 2.8 # EP1 cut was 3.3 m inside; 0.45 m was not enough + assert roundabout_outer_path_offset_m(on_roundabout=False) == 0.0 + # Far approach: do not drift to the shoulder 180 m out. + assert roundabout_outer_path_offset_m( + on_roundabout=False, approaching=True, distance_m=180.0, + ) == 0.0 + entry = roundabout_outer_path_offset_m( + on_roundabout=False, approaching=True, distance_m=RB_ENTRY_BIAS_M - 1.0, + ) + assert abs(entry - rht) < 1e-6 + kappa = roundabout_outer_curvature_bias(rht) + assert kappa < 0.0 # less left / larger R on a CCW US ring + assert abs(kappa) >= 0.015 # counters ~3 m inside at 18 m preview + assert abs(kappa) < 0.05 + + +def test_kinematic_a_from_40_45_in_funnel(): + """40–45 mph in the funnel must plan a ≤ −1.0 until near ring speed.""" + target = 20.0 * CV.MPH_TO_MS + for v_mph, dist in ((40.0, 90.0), (45.0, 90.0), (45.0, 160.0), (37.0, 90.0)): + hint = RoundaboutHint(approaching=True, distance_m=dist, speed_limit_ms=target) + v = v_mph * CV.MPH_TO_MS + a = roundabout_decel_ms2(hint, v) + assert a is not None and a <= 0.0 + if v_mph >= 40.0: + assert a <= RB_A_FLOOR_MS2, (v_mph, dist, a) + # Already near ring speed: clamp +a only, do not keep −1.0. + slow = RoundaboutHint(approaching=True, distance_m=40.0, speed_limit_ms=target) + assert abs(roundabout_decel_ms2(slow, 21.0 * CV.MPH_TO_MS)) < 1e-6 + + +def test_no_plus_a_while_approaching(): + """EP0 hole: after lead ease, aTarget +0.399 before/inside detect.""" + hint = RoundaboutHint( + approaching=True, distance_m=95.0, speed_limit_ms=20.0 * CV.MPH_TO_MS, + ) + v37 = 37.0 * CV.MPH_TO_MS + v50 = 50.0 * CV.MPH_TO_MS + _vc, _vh, a, rb = apply_roundabout_plan(v37, v50, v50, 0.399, hint) + assert rb is not None and a <= 0.0 + # At ring speed, still no +a rebound. + _vc, _vh, a0, _rb = apply_roundabout_plan(20.0 * CV.MPH_TO_MS, v50, v50, 0.399, hint) + assert a0 <= 0.0 + on = RoundaboutHint(on_roundabout=True, speed_limit_ms=20.0 * CV.MPH_TO_MS) + _vc, _vh, a_on, _rb = apply_roundabout_plan(18.0 * CV.MPH_TO_MS, v50, v50, 0.4, on) + assert a_on <= 0.0 + + +def test_live_map_hint_reads_capnp_fields(): + class _Md: + onRoundabout = False + approachingRoundabout = True + roundaboutDistance = 90.0 + roundaboutSpeedLimit = 20.0 * CV.MPH_TO_MS + roundaboutWayId = 99 + + hint = live_map_roundabout_hint(_Md()) + assert hint is not None and hint.approaching and abs(hint.distance_m - 90.0) < 1e-6 + assert live_map_roundabout_hint(None) is None + + class _Empty: + onRoundabout = False + approachingRoundabout = False + + assert live_map_roundabout_hint(_Empty()) is None + + +def _db_with_ring_and_approach(tmp_path, *, tagged=False, corner=False, ring_highway="unclassified"): + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + west_lat, west_lon = _offset(RB_LAT, RB_LON, 270.0, RB_R_M) + approach_lat, approach_lon = _offset(west_lat, west_lon, 270.0, 160.0) + OsmSpeedLimitDB.insert_way( + con, 1, "30th St SW", "residential", 30.0 * CV.MPH_TO_MS, + _eastbound_way(west_lat, approach_lon, west_lon), + ) + if corner: + OsmSpeedLimitDB.insert_way( + con, 2, "19th Ave SW", "residential", 30.0 * CV.MPH_TO_MS, + [ + (west_lat, west_lon - 0.0004), + (RB_LAT, RB_LON), + (RB_LAT + 0.002, RB_LON), + ], + ) + else: + OsmSpeedLimitDB.insert_way( + con, 2, "", ring_highway, 20.0 * CV.MPH_TO_MS, + _circle(RB_LAT, RB_LON), + junction="roundabout" if tagged else "", + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + return db, west_lat, west_lon + + +def test_funnel_detects_untagged_closed_ring(tmp_path): + db, west_lat, west_lon = _db_with_ring_and_approach(tmp_path, tagged=False) + qlat, qlon = _offset(west_lat, west_lon, 270.0, 90.0) + hint = db.find_roundabout(qlat, qlon, bearing_deg=90.0) + assert hint.approaching or hint.on_roundabout + assert 0.0 < hint.distance_m <= RB_FUNNEL_M or hint.on_roundabout + assert abs(hint.speed_limit_ms - 20.0 * CV.MPH_TO_MS) < 0.3 + # On the ring. + on = db.find_roundabout(RB_LAT, RB_LON + 0.0, bearing_deg=0.0) + # Center is ~22.5 m from the way — still on. + assert on.on_roundabout + db.close() + + +def test_tagged_ring_detects_in_funnel(tmp_path): + db, west_lat, west_lon = _db_with_ring_and_approach(tmp_path, tagged=True) + qlat, qlon = _offset(west_lat, west_lon, 270.0, 90.0) + hint = db.find_roundabout(qlat, qlon, bearing_deg=90.0) + assert hint.approaching + assert hint.distance_m <= RB_FUNNEL_M + db.close() + + +def test_funnel_detects_farther_out(tmp_path): + """Decel onset ~RB_DECEL_ONSET_M: live at 135 m out, not yet at 180 m (Oct 1: was 200 m).""" + db, west_lat, west_lon = _db_with_ring_and_approach(tmp_path, tagged=True) + qlat, qlon = _offset(west_lat, west_lon, 270.0, 135.0) + hint = db.find_roundabout(qlat, qlon, bearing_deg=90.0) + assert hint.approaching + assert 100.0 <= hint.distance_m <= RB_FUNNEL_M + qlat, qlon = _offset(west_lat, west_lon, 270.0, 180.0) + # Once hinted, the ring stays latched (no mid-approach drop / early exit restore). + assert db.find_roundabout(qlat, qlon, bearing_deg=90.0).approaching + db._rb_latch_way = 0 + assert not db.find_roundabout(qlat, qlon, bearing_deg=90.0).approaching + db.close() + + +def test_sharp_corner_does_not_trigger_funnel(tmp_path): + db, west_lat, west_lon = _db_with_ring_and_approach(tmp_path, corner=True) + qlat, qlon = _offset(west_lat, west_lon, 270.0, 90.0) + hint = db.find_roundabout(qlat, qlon, bearing_deg=90.0) + assert not hint.approaching + assert not hint.on_roundabout + db.close() + + +def test_tagged_residential_ring_still_funnels(tmp_path): + """junction=roundabout on a residential way is still a town roundabout.""" + db, west_lat, west_lon = _db_with_ring_and_approach( + tmp_path, tagged=True, ring_highway="residential", + ) + qlat, qlon = _offset(west_lat, west_lon, 270.0, 90.0) + hint = db.find_roundabout(qlat, qlon, bearing_deg=90.0) + assert hint.approaching + assert hint.distance_m <= RB_FUNNEL_M + db.close() + + +def test_untagged_residential_ring_does_not_funnel(tmp_path): + db, west_lat, west_lon = _db_with_ring_and_approach( + tmp_path, tagged=False, ring_highway="residential", + ) + qlat, qlon = _offset(west_lat, west_lon, 270.0, 90.0) + hint = db.find_roundabout(qlat, qlon, bearing_deg=90.0) + assert not hint.approaching + assert not hint.on_roundabout + db.close() + + +# I-74 eastbound, Indianapolis. Residential loops beside the motorway +# (Maritime Dr 17493053, Seaway Dr 17497242) published approachingRoundabout +# and latched MAX 65→20. +I74_LAT = 39.81706 +I74_LON = -86.30076 + + +def _east_line(lat, lon, start_m, end_m, step_m): + origin = _offset(lat, lon, 270.0, abs(start_m)) if start_m < 0 else _offset(lat, lon, 90.0, start_m) + n = max(1, int(round((end_m - start_m) / step_m))) + return [_offset(origin[0], origin[1], 90.0, step_m * i) for i in range(n + 1)] + + +def test_residential_loops_beside_motorway_do_not_approach(tmp_path): + """Maritime / Seaway shape: closed residential ways within the 200 m funnel.""" + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 99449506, "I 74", "motorway", 65.0 * CV.MPH_TO_MS, + _east_line(I74_LAT, I74_LON, -400.0, 400.0, 40.0), + ) + maritime_c = _offset(*_offset(I74_LAT, I74_LON, 90.0, 160.0), 0.0, 30.0) + seaway_c = _offset(*_offset(I74_LAT, I74_LON, 90.0, 175.0), 180.0, 35.0) + maritime = _circle(*maritime_c, r_m=20.0) + seaway = _circle(*seaway_c, r_m=18.0) + # Same geometry would be an untagged RB on a town class; residential is not. + assert way_is_roundabout(maritime, junction="", highway="unclassified") + assert not way_is_roundabout(maritime, junction="", highway="residential") + assert not way_is_roundabout(seaway, junction="", highway="residential") + OsmSpeedLimitDB.insert_way( + con, 17493053, "Maritime Drive", "residential", 25.0 * CV.MPH_TO_MS, maritime, + ) + OsmSpeedLimitDB.insert_way( + con, 17497242, "Seaway Drive", "residential", 25.0 * CV.MPH_TO_MS, seaway, + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + hint = db.find_roundabout(I74_LAT, I74_LON, bearing_deg=90.0) + assert not hint.approaching + assert not hint.on_roundabout + assert hint.way_id == 0 + # Stored bulbs are still closed loops the untagged fallback would accept + # on a town class. Residential / living_street stay skipped without a tag, + # and the motorway match suppresses the hint on its own. + for way_id in (17493053, 17497242): + row = db._con.execute("SELECT coords, highway FROM ways WHERE way_id=?", (way_id,)).fetchone() + stored = _unpack_coords(row["coords"]) + assert way_is_roundabout(stored, junction="", highway="unclassified") + assert not way_is_roundabout(stored, junction="", highway=row["highway"]) + off_gate = db.find_roundabout(I74_LAT, I74_LON, bearing_deg=90.0, current_highway="residential") + assert not off_gate.approaching + assert not off_gate.on_roundabout + db.close() + + +def test_motorway_suppresses_nearby_closed_ring(tmp_path): + """An unclassified closed ring beside a motorway match must not approach. + + The same ring still funnels when the ego match is a town street. + """ + path = str(tmp_path / "speed_limits.sqlite") + con = OsmSpeedLimitDB.create(path) + OsmSpeedLimitDB.insert_way( + con, 99449506, "I 74", "motorway", 65.0 * CV.MPH_TO_MS, + _east_line(I74_LAT, I74_LON, -400.0, 400.0, 40.0), + ) + center = _offset(*_offset(I74_LAT, I74_LON, 90.0, 150.0), 0.0, 40.0) + ring = _circle(*center, r_m=RB_R_M) + OsmSpeedLimitDB.insert_way( + con, 2, "", "unclassified", 20.0 * CV.MPH_TO_MS, ring, + ) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + on_motorway = db.find_roundabout(I74_LAT, I74_LON, bearing_deg=90.0) + assert not on_motorway.approaching + assert not on_motorway.on_roundabout + for hw in ("motorway", "motorway_link", "trunk", "trunk_link"): + gated = db.find_roundabout(I74_LAT, I74_LON, bearing_deg=90.0, current_highway=hw) + assert not gated.approaching and not gated.on_roundabout + town = db.find_roundabout(I74_LAT, I74_LON, bearing_deg=90.0, current_highway="residential") + assert town.approaching + assert 0.0 < town.distance_m <= RB_FUNNEL_M + assert town.way_id == 2 + db.close() + + +def test_overpass_keeps_junction_tag(): + payload = { + "elements": [ + { + "type": "way", + "id": 77, + "tags": {"highway": "unclassified", "maxspeed": "20 mph", "junction": "roundabout"}, + "geometry": [{"lat": p[0], "lon": p[1]} for p in _circle(RB_LAT, RB_LON)], + } + ] + } + ways = ways_from_overpass(payload) + assert len(ways) == 1 + assert ways[0]["junction"] == "roundabout" + + +# --- Oct 11: speed-based onset, smooth MAX profile (Watertown SD route 00000185) --------------------------------- +MPH = CV.MPH_TO_MS +DATA = os.path.join(os.path.dirname(__file__), "data", "rb_watertown_oct11.json") + + +def test_onset_formula_and_clamp(): + assert rb_decel_onset_m(None) == RB_ONSET_MIN_M + assert rb_decel_onset_m(25 * MPH) == RB_ONSET_MIN_M + d55 = rb_decel_onset_m(55 * MPH) + # Oct 13: final slowdown starts ~40 m earlier (margin 30 -> 70 m), clamped at the max. + assert d55 == pytest.approx(min(((55 * MPH) ** 2 - RB_V_MIN_MS ** 2) / 1.4 + RB_ONSET_MARGIN_M, RB_ONSET_MAX_M)) + assert 440.0 <= d55 <= 460.0 + assert rb_decel_onset_m(80 * MPH) == RB_ONSET_MAX_M + + +def _simulate(v0_mph, start_m, ring_limit_ms=0.0, dt=0.05, a_now=0.0): + """Planner-ish sim: v follows min(profile MAX, kinematic −a) with the planner jerk limit.""" + v = v0_mph * MPH + d = start_m + a_jl = 0.0 + peak = 0.0 + first_slow_d = None + while d > 0.0: + onset = rb_decel_onset_m(v) + hint = None + if d <= max(onset, start_m if first_slow_d is not None else 0.0): + hint = RoundaboutHint(approaching=True, distance_m=d, speed_limit_ms=ring_limit_ms) + a_cmd = a_now + if hint is not None: + v_max = roundabout_ease_v_ms(hint, v, v) + a_rb = roundabout_decel_ms2(hint, v) + a_jl = max(a_rb, a_jl - RB_DECEL_JERK_MS3 * dt) + a_cmd = min(a_now, a_jl) + if v > v_max + 0.3: # MAX ceiling: cruise tracks it at ≤ comfort + a_cmd = min(a_cmd, -0.7) + if first_slow_d is None and a_cmd < -0.05: + first_slow_d = d + peak = max(peak, -a_cmd) + v = max(0.0, v + a_cmd * dt) + d -= v * dt + return v, peak, first_slow_d + + +def test_55mph_highway_approach(): + """Starts at the onset (~415 m from 55 mph at 0.7 m/s²), reaches ring speed by entry, never above ~1.5 m/s².""" + v_entry, peak, first = _simulate(55.0, 600.0) + assert first is not None and 430.0 <= first <= 460.0, first + target = roundabout_target_ms(0.0) + assert v_entry <= target + 1.0 * MPH, v_entry / MPH + assert peak <= 1.5 + 1e-6 + assert peak <= 1.0 # typical ~0.7, no brick wall + + +def test_max_profile_is_smooth_no_step(): + """MAX ramps down from ~current speed instead of stepping 35 → 18.""" + v = 35 * MPH + onset = rb_decel_onset_m(v) + first = roundabout_ease_v_ms(RoundaboutHint(approaching=True, distance_m=onset), v, v) + assert first >= v - 1.0 * MPH + prev = first + for d in range(int(onset), 0, -5): + cur = roundabout_ease_v_ms(RoundaboutHint(approaching=True, distance_m=float(d)), v, v) + assert cur <= prev + 1e-9 + assert prev - cur <= 1.0 # per 5 m + prev = cur + assert roundabout_ease_v_ms(RoundaboutHint(approaching=True, distance_m=RB_PROFILE_BUFFER_M), v, v) == \ + pytest.approx(roundabout_target_ms(0.0)) + + +def test_late_hint_still_capped(): + a = roundabout_decel_ms2(RoundaboutHint(approaching=True, distance_m=40.0), 50 * MPH) + assert a >= RB_A_MAX_DECEL_MS2 - 1e-9 + + +def test_replay_watertown_ring_oct11(): + """Route 00000185--d9fc14b285 ring (17:02:37–17:03:07 CT) replayed through the new profile.""" + with open(DATA) as f: + rows = json.load(f) + hit = [r for r in rows if r["appr"]] + assert hit, "ring approach present" + first = hit[0] + # Old: MAX stepped 35.2 → 18.0 mph at 133 m. New profile at 133 m is near current speed. + new_max = roundabout_ease_v_ms(RoundaboutHint(approaching=True, distance_m=first["d"], + speed_limit_ms=first["rb"]), first["v"], first["v"]) / MPH + assert new_max >= 25.0 + assert rb_decel_onset_m(first["v"], roundabout_target_ms(first["rb"])) == RB_ONSET_MIN_M + # Required decel never above 1.5 along the logged approach, and ring target is 18 mph. + for r in hit: + a = roundabout_decel_ms2(RoundaboutHint(approaching=True, distance_m=r["d"], speed_limit_ms=r["rb"]), r["v"]) + assert a >= -1.5 + assert roundabout_target_ms(first["rb"]) / MPH == pytest.approx(18.0) + assert math.isfinite(new_max) + + +# --- Oct 13: exit restore on right blinker + unwinding, capped braking ----------------------------------------- +def _ring_hint(): + return RoundaboutHint(on_roundabout=True, way_id=1) + + +def test_rb_brake_cap_near_one(): + assert -1.05 <= RB_A_MAX_DECEL_MS2 <= -0.95 + assert 1.5 * MPH <= RB_EXIT_RESTORE_MS2 <= 2.0 * MPH + + +def test_blinker_alone_does_not_restore(): + g = RingExitGate() + h = _ring_hint() + for _ in range(40): # tight ring, curvature steady, blinker on + assert not g.update(h, True, 0.05, 0.1) + + +def test_unwind_without_blinker_does_not_restore(): + g = RingExitGate() + h = _ring_hint() + for k in [0.05] * 20 + [0.01] * 20: + assert not g.update(h, False, k, 0.1) + + +def test_blinker_plus_unwind_restores_and_latches(): + g = RingExitGate() + h = _ring_hint() + for _ in range(20): + g.update(h, False, 0.05, 0.1) + rel = [g.update(h, True, 0.015, 0.1) for _ in range(20)] + assert any(rel) + assert g.update(h, False, 0.015, 0.1) # latched after the blinker drops + assert not g.update(None, False, 0.0, 0.1) # off the ring: reset diff --git a/selfdrive/mapd/tests/test_roundabout_map.py b/selfdrive/mapd/tests/test_roundabout_map.py new file mode 100644 index 00000000000000..b186b3d8522e7e --- /dev/null +++ b/selfdrive/mapd/tests/test_roundabout_map.py @@ -0,0 +1,681 @@ +"""Map pack v4 roundabouts: rings + approach roads without maxspeed (rb_ways). + +Fixture: Soco Rd / Dellwood Rd / Jonathan Creek Rd ring (Maggie Valley NC), +Sep 28 PM R126 16:52 / R128 17:38 CT. OSM data © OpenStreetMap contributors, +ODbL 1.0. The ring has no maxspeed and no lanes tag, so pack v3 (maxspeed-only +ways) never had it and the roundabout hint / slow-down never fired. +""" +import json +import math +import sqlite3 +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.local_refresh import merge_ways_into_db +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB +from openpilot.selfdrive.mapd.overpass import overpass_query, ways_from_overpass +from openpilot.selfdrive.mapd.roundabout import RB_PROFILE_BUFFER_M, roundabout_target_ms +from openpilot.selfdrive.mapd.roundabout_map import ( + PARAM_RING, ROLE_APPROACH, ROLE_RING, RingCache, RingGeometry, local_xy, rb_rows_from_overpass, + ring_geometry, roundabout_comfort_speed_ms, +) + +FIXTURE = Path(__file__).parent / "data" / "soco_roundabout_overpass.json" +SOCO_WAY = 1514082747 +SOCO_RING_WAYS = {1514082747, 1517278969, 1517278970, 1517279058, 1517279059, 1517279060} +SOCO_CENTER = (35.52208, -83.02814) +# R128 17:37:59.9 CT, first mapd hint ~192 m east of the ring (westbound on Dellwood Rd). +R128_FIRST_HINT = (35.52224, -83.02645) # decel onset (RB_DECEL_ONSET_M = 140): ~131 m out +# A tagged speed way near the ring (synthetic, not in OSM) to prove speed matching is unchanged. +SPEED_COORDS: list[tuple[float, float]] = [(35.5240, -83.0330), (35.5240, -83.0230)] +SPEED_WAY = {"way_id": 900000001, "name": "Test Rd", "highway": "primary", "maxspeed_ms": 45 * CV.MPH_TO_MS, + "coords": SPEED_COORDS, "junction": ""} + + +def _payload(): + return json.loads(FIXTURE.read_text()) + + +def _rows(): + return rb_rows_from_overpass(_payload()) + + +def _ring(rows=None): + rows = _rows() if rows is None else rows + return ring_geometry([r for r in rows if r["role"] == ROLE_RING], [r for r in rows if r["role"] == ROLE_APPROACH], + seed_id=SOCO_WAY) + + +def _db(tmp_path, *, rb=True, name="pack.sqlite"): + path = str(tmp_path / name) + con = OsmSpeedLimitDB.create(path) + w = SPEED_WAY + OsmSpeedLimitDB.insert_way(con, w["way_id"], w["name"], w["highway"], w["maxspeed_ms"], w["coords"], junction="") + if rb: + for r in _rows(): + OsmSpeedLimitDB.insert_rb_way(con, r) + OsmSpeedLimitDB.recount_rb_ways(con) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + db.open() + return db, path + + +def test_fixture_is_attributed_odbl(): + assert "OpenStreetMap contributors" in _payload()["attribution"] + assert "ODbL" in _payload()["attribution"] + + +def test_soco_ring_and_approaches_are_extracted_without_maxspeed(): + rows = _rows() + rings = {r["way_id"] for r in rows if r["role"] == ROLE_RING} + approaches = {r["way_id"] for r in rows if r["role"] == ROLE_APPROACH} + assert rings == SOCO_RING_WAYS + assert SOCO_WAY in rings + assert {1514082743, 1514082744, 1514082745, 1514082746} <= approaches # Dellwood / Soco both directions + assert all(r["maxspeed_ms"] == 0.0 for r in rows) + # None of these reach the speed-limit ways (no maxspeed): pack v3 never had the ring. + assert ways_from_overpass(_payload()) == [] + + +def test_soco_ring_fit(): + ring = _ring() + assert ring is not None + assert 21.0 < ring.radius_m < 22.3 + assert ring.rms_m < 0.6 + assert ring.ccw # US counter-clockwise circulation + assert ring.coverage_deg > 330.0 + assert set(ring.way_ids) == SOCO_RING_WAYS + x, y = local_xy(ring.lat, ring.lon, *SOCO_CENTER) + assert math.hypot(x, y) < 3.0 + + +def test_approaches_are_stored_in_travel_direction(): + ring = _ring() + inbound = outbound = 0 + for a in ring.approaches: + r0, r1 = math.hypot(*a[0]), math.hypot(*a[-1]) + inbound += r1 < r0 + outbound += r1 > r0 + # Oneway Dellwood/Soco pairs: one inbound + one outbound each side. + assert inbound >= 2 and outbound >= 2 + # Westbound Dellwood (1514082743) enters the ring: its polyline must end at the ring. + rows = [r for r in _rows() if r["way_id"] == 1514082743] + single = ring_geometry([r for r in _rows() if r["role"] == ROLE_RING], rows, seed_id=SOCO_WAY) + a = single.approaches[0] + assert math.hypot(*a[-1]) < math.hypot(*a[0]) + + +def test_ring_json_roundtrip(): + ring = _ring() + back = RingGeometry.from_json(json.dumps(ring.to_json())) + assert back is not None + assert back.way_ids == ring.way_ids and back.ccw == ring.ccw + assert abs(back.radius_m - ring.radius_m) < 0.01 + assert len(back.approaches) == len(ring.approaches) + assert RingGeometry.from_json({"v": 999}) is None + assert RingGeometry.from_json("not json") is None + assert PARAM_RING == "NAPRoundaboutRing" + + +def test_comfort_speed_soco_about_15_mph(): + ring = _ring() + v = roundabout_comfort_speed_ms(ring.radius_m, ring.lanes, ring.maxspeed_ms) + assert 15.0 * CV.MPH_TO_MS <= v <= 16.5 * CV.MPH_TO_MS + # Inner lane (2 lanes, lanes tag missing) at that speed: <= 2.5 m/s^2. + assert v * v / (ring.radius_m - 1.75) <= 2.5 + 1e-6 + # Planner target floors it at the 18 mph ring speed (Sep 30; the comfort speed itself is unchanged). + assert roundabout_target_ms(v) == pytest.approx(18.0 * CV.MPH_TO_MS) + # OSM maxspeed still caps; bigger rings are faster; bad input safe. + assert roundabout_comfort_speed_ms(21.6, 2, 5.0) == pytest.approx(5.0) + assert roundabout_comfort_speed_ms(40.0, 2) > v + assert roundabout_comfort_speed_ms(0.0, 2) >= 0.0 + + +def test_v4_pack_ring_geometry_from_first_hint_distance(tmp_path): + db, _ = _db(tmp_path) + hint = db.find_roundabout(R128_FIRST_HINT[0], R128_FIRST_HINT[1], 270.0, current_highway="primary") + # Hint fires from the approach, then geometry is fit around the hinted way (not the car ~190 m out). + ring = db.ring_geometry(SOCO_WAY, *R128_FIRST_HINT) + assert ring is not None and set(ring.way_ids) == SOCO_RING_WAYS + assert hint.approaching and int(hint.way_id) in SOCO_RING_WAYS + assert 120.0 < hint.distance_m < 140.0 + + +def test_v4_pack_find_roundabout_sees_untagged_speed_ring(tmp_path): + db, _ = _db(tmp_path) + lat, lon = SOCO_CENTER + x_east = local_xy(lat, lon + 0.0006, lat, lon)[0] + assert x_east > 40 + h = db.find_roundabout(lat, lon + 0.0006, 270.0, current_highway="primary") + assert h.approaching or h.on_roundabout + assert int(h.way_id) in SOCO_RING_WAYS + + +def test_v3_pack_without_rb_tables_still_works(tmp_path): + db, path = _db(tmp_path, rb=False, name="v3.sqlite") + con = sqlite3.connect(path) + con.execute("DROP TABLE IF EXISTS rb_ways") + con.execute("DROP TABLE IF EXISTS rb_ways_rtree") + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + db.open() + assert db.ring_geometry(SOCO_WAY, *SOCO_CENTER) is None + m = db.lookup(35.5240, -83.0280, 90.0, v_ego_ms=20.0) + assert m is not None and m.speed_limit_ms == pytest.approx(SPEED_WAY["maxspeed_ms"]) + h = db.find_roundabout(*SOCO_CENTER, 90.0, current_highway="primary") + assert not h.on_roundabout + + +def test_speed_matching_unchanged_by_rb_rows(tmp_path): + with_rb, _ = _db(tmp_path, rb=True, name="a.sqlite") + without, _ = _db(tmp_path, rb=False, name="b.sqlite") + for lat, lon, brg in ((35.5240, -83.0280, 90.0), (35.5240, -83.0300, 270.0), (35.52224, -83.02602, 270.0), + (35.52208, -83.02814, 0.0)): + a = with_rb.lookup(lat, lon, brg, v_ego_ms=15.0) + b = without.lookup(lat, lon, brg, v_ego_ms=15.0) + assert (a is None) == (b is None) + if a is not None: + assert a.way_id == b.way_id and a.speed_limit_ms == b.speed_limit_ms + # rb rows never land in the speed `ways` table. + con = sqlite3.connect(str(tmp_path / "a.sqlite")) + assert con.execute("SELECT COUNT(*) FROM ways").fetchone()[0] == 1 + assert con.execute("SELECT COUNT(*) FROM rb_ways WHERE role='ring'").fetchone()[0] == 6 + assert con.execute("SELECT value FROM meta WHERE key='rb_ring_way_count'").fetchone()[0] == "6" + + +def test_overpass_queries_include_rings_and_approaches(): + for unmarked in (False, True): + q = overpass_query(35.0, -84.0, 36.0, -83.0, include_unmarked=unmarked) + assert '["junction"~"^(roundabout|circular)$"]' in q + assert "node(w.rb)->.rbn;" in q + assert 'way(bn.rbn)["highway"]->.ap;' in q + assert "\n .rb;\n .ap;" in q # both sets are output in the union + # Old form still available. + q = overpass_query(35.0, -84.0, 36.0, -83.0, include_roundabouts=False) + assert "junction" not in q and '["maxspeed"]' in q + + +def test_extra_rb_elements_do_not_change_speed_ways(): + base = {"elements": [{"type": "way", "id": SPEED_WAY["way_id"], "tags": {"highway": "primary", "maxspeed": "45 mph"}, + "geometry": [{"lat": a, "lon": b} for a, b in SPEED_COORDS]}]} + combined = {"elements": base["elements"] + _payload()["elements"]} + assert ways_from_overpass(combined) == ways_from_overpass(base) + + +def test_refresh_merge_replaces_rb_rows_in_bbox(tmp_path): + _, path = _db(tmp_path, rb=False, name="installed.sqlite") + bbox = (35.50, -83.05, 35.55, -83.00) + merge_ways_into_db(path, [SPEED_WAY], bbox, rb_rows=_rows()) + con = sqlite3.connect(path) + assert con.execute("SELECT COUNT(*) FROM rb_ways WHERE role='ring'").fetchone()[0] == 6 + # Second refresh replaces (no duplicates); None leaves rb_ways alone. + merge_ways_into_db(path, [SPEED_WAY], bbox, rb_rows=_rows()) + merge_ways_into_db(path, [SPEED_WAY], bbox, rb_rows=None) + assert con.execute("SELECT COUNT(*) FROM rb_ways WHERE role='ring'").fetchone()[0] == 6 + con.close() + db = OsmSpeedLimitDB(path) + db.open() + assert db.ring_geometry(SOCO_WAY, *R128_FIRST_HINT) is not None + + +def test_ring_cache_publishes_once(tmp_path): + db, _ = _db(tmp_path) + cache, sent = RingCache(), [] + for t in range(5): + g = cache.update(db, SOCO_WAY, *R128_FIRST_HINT, float(t), publish=sent.append) + assert g is not None + cache.update(db, 1517278969, *SOCO_CENTER, 6.0, publish=sent.append) # another way of the same ring + assert len(sent) == 1 and sent[0]["ids"] == sorted(SOCO_RING_WAYS) + assert cache.update(db, 0, *SOCO_CENTER, 7.0) is None + + +def test_builder_from_json_writes_pack_v4(tmp_path): + from scripts.nap.build_osm_speed_limits import main as build_main + src = tmp_path / "in.json" + payload = _payload() + payload["elements"].append({"type": "way", "id": SPEED_WAY["way_id"], "tags": {"highway": "primary", "maxspeed": "45 mph"}, + "nodes": [1, 2], "geometry": [{"lat": a, "lon": b} for a, b in SPEED_COORDS]}) + src.write_text(json.dumps(payload)) + out = tmp_path / "out.sqlite" + assert build_main(["--from-json", str(src), "--out", str(out)]) in (0, None) + con = sqlite3.connect(str(out)) + assert con.execute("SELECT COUNT(*) FROM ways").fetchone()[0] == 1 + assert con.execute("SELECT COUNT(*) FROM rb_ways WHERE role='ring'").fetchone()[0] == 6 + assert con.execute("SELECT value FROM meta WHERE key='pack_schema'").fetchone()[0] == "4" + con.close() + out2 = tmp_path / "out2.sqlite" + assert build_main(["--from-json", str(src), "--out", str(out2), "--no-roundabouts"]) in (0, None) + con = sqlite3.connect(str(out2)) + assert con.execute("SELECT COUNT(*) FROM ways").fetchone()[0] == 1 + assert con.execute("SELECT value FROM meta WHERE key='pack_schema'").fetchone() is None + con.close() + + +# --- follow-ups: ring-only message validity, missing-ring-data warning ------------------------------------------- + +class _Stop(Exception): + pass + + +def _run_mapd(monkeypatch, db_path, fixes): + """Drive mapd.main() over GPS fixes [(lat, lon, bearing)]; return the published messages.""" + from openpilot.selfdrive.mapd import mapd + sent = [] + + class _G: + def __init__(self, lat, lon, brg): + self.latitude, self.longitude, self.bearingDeg = lat, lon, brg + self.speed, self.horizontalAccuracy = 15.0, 3.0 + + class _Sm: + def __init__(self, *_a, **_k): + self.recv_frame, self.recv_time, self._g = {"gpsLocationExternal": 1}, {"gpsLocationExternal": 1e18}, None + + def update(self, _t): + self._g = _G(*fixes[len(sent)]) + + def __getitem__(self, key): + return self._g + + class _Pm: + def __init__(self, *_a, **_k): + pass + + def send(self, _name, msg): + sent.append(msg) + + class _Rk: + def __init__(self, *_a, **_k): + pass + + def keep_time(self): + if len(sent) >= len(fixes): + raise _Stop + + class _Params: + def get(self, key, *_a, **_k): + return db_path if key == "NAPMapSpeedDbPath" else None + + def put(self, *_a, **_k): + pass + + monkeypatch.setattr(mapd.messaging, "SubMaster", _Sm) + monkeypatch.setattr(mapd.messaging, "PubMaster", _Pm) + monkeypatch.setattr(mapd, "Ratekeeper", _Rk) + monkeypatch.setattr(mapd, "Params", _Params) + monkeypatch.setattr(mapd.time, "monotonic", lambda: 100.0) + monkeypatch.setattr(mapd, "gps_sample_from_sm", lambda sm, now=None: (*fixes[len(sent)], True)) + monkeypatch.setattr(mapd, "persist_last_gps_position", lambda *a, **k: None) + with pytest.raises(_Stop): + mapd.main() + return sent + + +ON_SPEED_WAY = (35.5240, -83.0280, 90.0) # matches the tagged speed way, no ring nearby +OFF_MAP = (36.5, -84.0, 90.0) # nothing in the pack +RING_APPROACH = (*R128_FIRST_HINT, 270.0) # ring hint, no speed-limit match + + +def test_mapd_ring_hint_keeps_message_valid_without_speed_match(tmp_path, monkeypatch): + _db(tmp_path) + msgs = _run_mapd(monkeypatch, str(tmp_path / "pack.sqlite"), [RING_APPROACH, ON_SPEED_WAY, OFF_MAP]) + ring, speed, off = msgs + assert ring.valid and ring.liveMapDataNAP.approachingRoundabout + assert not ring.liveMapDataNAP.speedLimitValid and ring.liveMapDataNAP.speedLimit == 0.0 + assert ring.liveMapDataNAP.roundaboutSpeedLimit == pytest.approx(15.0 * CV.MPH_TO_MS, abs=1.5) + assert speed.valid and speed.liveMapDataNAP.speedLimitValid + assert not speed.liveMapDataNAP.approachingRoundabout and not speed.liveMapDataNAP.onRoundabout + assert not off.valid and not off.liveMapDataNAP.speedLimitValid + + +def test_mapd_without_ring_rows_is_invalid_at_the_ring(tmp_path, monkeypatch): + _db(tmp_path, rb=False) + msgs = _run_mapd(monkeypatch, str(tmp_path / "pack.sqlite"), [RING_APPROACH, ON_SPEED_WAY]) + assert not msgs[0].valid and not msgs[0].liveMapDataNAP.approachingRoundabout + assert msgs[1].valid and msgs[1].liveMapDataNAP.speedLimitValid + + +def test_map_msg_valid_only_changes_with_a_ring_hint(): + from openpilot.selfdrive.mapd.roundabout_status import map_msg_valid + for gps in (False, True): + for loaded in (False, True): + for matched in (False, True): + assert map_msg_valid(gps_ok=gps, db_loaded=loaded, matched=matched, ring_hint=False) == (gps and loaded and matched) + assert map_msg_valid(gps_ok=gps, db_loaded=loaded, matched=matched, ring_hint=True) == (gps and loaded) + + +def test_pack_ring_count_and_summary(tmp_path, monkeypatch): + from openpilot.selfdrive.mapd.roundabout_status import ( + RING_MISSING_TEXT, installed_ring_summary, pack_ring_count, ring_data_summary, + ) + _db(tmp_path, name="v4.sqlite") + _db(tmp_path, rb=False, name="norb.sqlite") + _db(tmp_path, name="v3.sqlite") + con = sqlite3.connect(str(tmp_path / "v3.sqlite")) + con.execute("DROP TABLE rb_ways") + con.execute("DROP TABLE rb_ways_rtree") + con.commit() + con.close() + four, empty, v3, gone = (str(tmp_path / n) for n in ("v4.sqlite", "norb.sqlite", "v3.sqlite", "nope.sqlite")) + assert pack_ring_count(four) == 6 + assert pack_ring_count(empty) == 0 # rb tables exist, no rows: Refresh never stored a ring + assert pack_ring_count(v3) == 0 # published v3 pack: no rb tables at all + assert pack_ring_count(gone) is None and pack_ring_count("") is None and pack_ring_count(None) is None + (tmp_path / "junk.sqlite").write_bytes(b"not a database" * 100) + assert pack_ring_count(str(tmp_path / "junk.sqlite")) is None + assert ring_data_summary(6) == "6 rings" and ring_data_summary(1200) == "1,200 rings" + assert ring_data_summary(0) == RING_MISSING_TEXT and "Refresh maps" in RING_MISSING_TEXT + assert ring_data_summary(None) == "Not installed" + assert installed_ring_summary(four) == "6 rings" + assert installed_ring_summary(v3) == RING_MISSING_TEXT + assert installed_ring_summary(gone) == "Not installed" + monkeypatch.setenv("NAP_MAP_DB", four) + assert installed_ring_summary() == "6 rings" # default path follows the installed pack + monkeypatch.setenv("NAP_MAP_DB", v3) + assert installed_ring_summary() == RING_MISSING_TEXT + + +def test_ring_data_watch_logs_once_per_pack_state(tmp_path): + from openpilot.selfdrive.mapd.roundabout_status import RingDataWatch + _db(tmp_path, rb=False, name="a.sqlite") + path = str(tmp_path / "a.sqlite") + w = RingDataWatch() + first = w.check(path) + assert first is not None and first[0] == "warning" and "no roundabout ring rows" in first[1] and "Refresh maps" in first[1] + assert w.check(path) is None and w.check(path) is None + con = sqlite3.connect(path) # Refresh maps adds rings: pack changes, log the new state once + for r in _rows(): + OsmSpeedLimitDB.insert_rb_way(con, r) + OsmSpeedLimitDB.recount_rb_ways(con) + con.commit() + con.close() + again = w.check(path) + assert again is not None and again[0] == "info" and "6 roundabout ring rows" in again[1] + assert w.check(path) is None + assert w.check(str(tmp_path / "missing.sqlite")) is None + + +def test_mapd_logs_missing_ring_rows_once(tmp_path, monkeypatch): + from openpilot.selfdrive.mapd import mapd + _db(tmp_path, rb=False) + logged = [] + monkeypatch.setattr(mapd.cloudlog, "warning", lambda msg, *a: logged.append(msg % a if a else msg)) + _run_mapd(monkeypatch, str(tmp_path / "pack.sqlite"), [ON_SPEED_WAY] * 4) + assert [m for m in logged if "no roundabout ring rows" in m] and len([m for m in logged if "ring rows" in m]) == 1 + + +# --- card: the ring slow-down does not need a speed-limit match -------------------------------------------------- + +def _card_harness(limit_mph=45.0): + from openpilot.selfdrive.car.tests import test_preap_engage_max_after_pause as t + h, cs, md, _eng = t._harness(limit_mph) + return h, cs, md, t._run + + +def _set_ring(md, *, on=False, approaching=True, ring_mph=15.8, dist=120.0): + md.onRoundabout, md.approachingRoundabout = on, approaching + md.roundaboutSpeedLimit, md.roundaboutDistance, md.roundaboutWayId = ring_mph * CV.MPH_TO_MS, dist, SOCO_WAY + + +def _profile_mph(dist=120.0, ring_mph=15.8): + """Oct 11: approach MAX follows the 0.7 m/s² profile down to the ring target (no 18 mph step).""" + from openpilot.selfdrive.mapd.roundabout import rb_profile_v_ms, roundabout_target_ms + return rb_profile_v_ms(dist, roundabout_target_ms(ring_mph * CV.MPH_TO_MS)) / CV.MPH_TO_MS + + +def _hud_mph(h): + return h.v_cruise_helper.v_cruise_kph / CV.MPH_TO_KPH + + +def test_card_ring_hint_drops_hud_max_without_speed_match(): + """Willmar/Maggie Valley: no maxspeed on the ring, so speedLimitValid is False in the funnel.""" + h, cs, md, run = _card_harness(45.0) + run(h, cs, 2.0) + assert _hud_mph(h) == pytest.approx(45.0, abs=0.3) + md.speedLimitValid, md.speedLimit = False, 0.0 + _set_ring(md) + run(h, cs, 1.0) + assert _hud_mph(h) == pytest.approx(_profile_mph(), abs=0.3) + assert _hud_mph(h) < 45.0 - 5.0 + assert h._map_slew_ms == pytest.approx(_profile_mph() * CV.MPH_TO_MS, abs=0.05) + _set_ring(md, dist=RB_PROFILE_BUFFER_M) + run(h, cs, 0.2) + assert _hud_mph(h) == pytest.approx(18.0, abs=0.3) + + +def test_card_ring_hint_same_max_with_or_without_speed_match(): + a, cs_a, md_a, run = _card_harness(45.0) + b, cs_b, md_b, _ = _card_harness(45.0) + run(a, cs_a, 2.0) + run(b, cs_b, 2.0) + _set_ring(md_a) # posted 45 still matched + md_b.speedLimitValid, md_b.speedLimit = False, 0.0 + _set_ring(md_b) # no match + run(a, cs_a, 1.0) + run(b, cs_b, 1.0) + assert _hud_mph(a) == pytest.approx(_hud_mph(b), abs=1e-6) == pytest.approx(_profile_mph(), abs=0.3) + + +def test_card_ring_hint_needs_a_valid_map_message(): + h, cs, md, run = _card_harness(45.0) + run(h, cs, 2.0) + md.speedLimitValid, md.speedLimit = False, 0.0 + h.sm.valid["liveMapDataNAP"] = False # mapd not publishing a valid message: nothing to read + _set_ring(md) + run(h, cs, 1.0) + assert _hud_mph(h) == pytest.approx(45.0, abs=0.3) + + +def test_card_no_ring_hint_is_identical_with_or_without_ring_fields(): + traces = [] + for extra in ({}, {"onRoundabout": False, "approachingRoundabout": False, "roundaboutDistance": 0.0, + "roundaboutSpeedLimit": 0.0, "roundaboutWayId": 0}): + h, cs, md, run = _card_harness(45.0) + md.__dict__.update(extra) + trace = [] + for limit, valid in ((45.0, True), (25.0, True), (0.0, False), (35.0, True)): + md.speedLimit, md.speedLimitValid = limit * CV.MPH_TO_MS, valid + for _ in range(150): + run(h, cs, 0.01) + trace.append((h.v_cruise_helper.v_cruise_kph, h._map_slew_ms, cs.cruiseState.speed)) + traces.append(trace) + assert traces[0] == traces[1] + assert min(t[0] for t in traces[0]) < 45.0 * CV.MPH_TO_KPH + + +def test_card_and_mapd_never_read_the_assist_toggle(): + """The slow-down is independent of NAPRoundaboutAssist (only the steering assist reads it).""" + import inspect + from openpilot.selfdrive.car import card + from openpilot.selfdrive.mapd import mapd + for mod in (card, mapd): + assert "NAPRoundaboutAssist" not in inspect.getsource(mod) + + +def _leave_ring(md): + md.onRoundabout = False + md.approachingRoundabout = False + + +def test_ring_exit_ramps_max_up_from_current_speed(): + """Oct 7 14:43:57: after the ring, MAX was 18 while ego was 25 and the car braked. + + The funnel may still show the ring speed on the way in. On the way out, + MAX starts at least at current speed and climbs toward the posted limit. + """ + h, cs, md, run = _card_harness(40.0) + run(h, cs, 1.0) + assert _hud_mph(h) == pytest.approx(40.0, abs=0.4) + _set_ring(md, on=False, approaching=True, ring_mph=15.0, dist=135.0) + cs.vEgo = 36.0 * CV.MPH_TO_MS + run(h, cs, 0.4) + assert _hud_mph(h) == pytest.approx(min(40.0, _profile_mph(135.0, 15.0)), abs=0.4) + _set_ring(md, on=True, approaching=False, ring_mph=15.0, dist=0.0) + run(h, cs, 0.2) + assert _hud_mph(h) == pytest.approx(18.0, abs=0.4) + + _leave_ring(md) + cs.vEgo = 25.0 * CV.MPH_TO_MS + run(h, cs, 0.01) + hud = _hud_mph(h) + assert hud >= 24.5 + assert hud < 28.0 + run(h, cs, 1.0) + later = _hud_mph(h) + assert later > hud + 1.0 + assert later < 40.5 + prev = later + for _ in range(30): + run(h, cs, 0.01) + step = _hud_mph(h) + assert step > prev - 0.3 + prev = step + run(h, cs, 25.0) + assert _hud_mph(h) == pytest.approx(40.0, abs=0.6) + + +def test_set_inside_ring_does_not_latch_ring_speed(): + """A SET while on the ring keeps the ring ceiling only until the exit.""" + h, cs, md, run = _card_harness(40.0) + run(h, cs, 1.0) + _set_ring(md, on=True, approaching=False, ring_mph=15.0, dist=0.0) + cs.vEgo = 22.0 * CV.MPH_TO_MS + run(h, cs, 0.3) + assert _hud_mph(h) == pytest.approx(18.0, abs=0.4) + eng = h.CI.CS.engagement + eng._nap_set_resume_long = True + run(h, cs, 0.01) + assert _hud_mph(h) == pytest.approx(18.0, abs=0.4) + held = h._map_hold.held_max_kph + assert held is None or abs(held / CV.MPH_TO_KPH - 18.0) > 2.0 + fsm = getattr(eng, "_nap_held_max_kph", None) + assert fsm is None or abs(float(fsm) / CV.MPH_TO_KPH - 18.0) > 2.0 + + _leave_ring(md) + cs.vEgo = 25.0 * CV.MPH_TO_MS + run(h, cs, 0.01) + assert _hud_mph(h) >= 24.5 + run(h, cs, 2.0) + assert 26.0 < _hud_mph(h) < 40.5 + assert h._map_hold.sticky_set_kph is None or abs( + h._map_hold.sticky_set_kph / CV.MPH_TO_KPH - 18.0) > 2.0 + + +def test_ring_exit_above_the_limit_eases_down(): + """Over the posted limit, MAX starts at current speed and does not step to the ring.""" + h, cs, md, run = _card_harness(30.0) + run(h, cs, 1.0) + _set_ring(md, approaching=True, ring_mph=15.0, dist=RB_PROFILE_BUFFER_M) + run(h, cs, 0.2) + assert _hud_mph(h) == pytest.approx(18.0, abs=0.4) + _leave_ring(md) + cs.vEgo = 40.0 * CV.MPH_TO_MS + prev = None + for _ in range(20): + run(h, cs, 0.01) + hud = _hud_mph(h) + if prev is not None: + assert hud > prev - 0.5 + prev = hud + assert _hud_mph(h) > 38.0 + + +def _ring_way(tags): + coords = [(45.0 + 0.0002 * math.sin(a), -95.0 + 0.0003 * math.cos(a)) for a in [i * math.pi / 4 for i in range(9)]] + return {"way_id": 1, "tags": {"highway": "tertiary", "junction": "roundabout", **tags}, + "node_ids": list(range(100, 109)), "coords": coords} + + +@pytest.mark.parametrize("tags, mph", [ + ({"maxspeed": "30 mph", "maxspeed:advisory": "15 mph"}, 15), + ({"maxspeed": "20 mph", "maxspeed:advisory": "25 mph"}, 20), + ({"maxspeed:advisory": "15 mph"}, 15), + ({"maxspeed": "25 mph"}, 25), +]) +def test_ring_advisory_uses_lower_speed(tags, mph): + from openpilot.selfdrive.mapd.roundabout_map import roundabout_rows + rows = roundabout_rows([_ring_way(tags)]) + assert rows[0]["role"] == ROLE_RING + assert rows[0]["maxspeed_ms"] == pytest.approx(mph * CV.MPH_TO_MS, abs=0.05) + + +def test_approach_ignores_advisory(): + from openpilot.selfdrive.mapd.roundabout_map import roundabout_rows + ring = _ring_way({}) + road = {"way_id": 2, "tags": {"highway": "primary", "maxspeed": "45 mph", "maxspeed:advisory": "15 mph"}, + "node_ids": [100, 200], "coords": [ring["coords"][0], (45.0, -94.99)]} + app = [r for r in roundabout_rows([ring, road]) if r["role"] == ROLE_APPROACH] + assert app and all(r["maxspeed_ms"] == pytest.approx(45 * CV.MPH_TO_MS, abs=0.05) for r in app) + + +def test_mini_roundabout_is_small_ring_with_approaches(): + from openpilot.selfdrive.mapd.roundabout_map import MINI_RB_RADIUS_M, mini_roundabout_way, roundabout_rows + lat, lon = 45.12, -95.04 + mini = mini_roundabout_way(555, lat, lon, {"highway": "mini_roundabout"}) + assert mini["way_id"] == -555 + road = {"way_id": 3, "tags": {"highway": "residential"}, "node_ids": [554, 555, 556], + "coords": [(lat - 0.001, lon), (lat, lon), (lat + 0.001, lon)]} + rows = roundabout_rows([mini, road]) + rings = [r for r in rows if r["role"] == ROLE_RING] + assert len(rings) == 1 and len([r for r in rows if r["role"] == ROLE_APPROACH]) == 2 + geo = ring_geometry(rings) + assert geo is not None + assert 6.0 <= geo.radius_m <= 8.0 and abs(geo.radius_m - MINI_RB_RADIUS_M) < 0.5 + from openpilot.selfdrive.mapd.roundabout import RB_V_MIN_MS + # A 7 m ring is tighter than any comfort target: the funnel floor applies. + assert roundabout_target_ms(roundabout_comfort_speed_ms(geo.radius_m, geo.lanes, geo.maxspeed_ms)) \ + == pytest.approx(RB_V_MIN_MS, abs=0.01) + + +# --- Oct 11: ring exit restore with / without a posted limit ------------------------------------------------------ +# MAX is a hard ceiling: a driver-set pre-ring MAX is restored exactly; only a map-auto MAX (no driver set, +# no posted limit now) may rise to the speed the car had when the ring was first detected. + + +KPH = CV.MPH_TO_KPH + + +def _ring_exit_target_ms(*a): + from openpilot.selfdrive.car.card import _ring_exit_target_ms as f + return f(*a) + + +def _hold(sticky=None, held=None, policy=None): + return SimpleNamespace(sticky_set_kph=None if sticky is None else sticky * KPH, + held_max_kph=None if held is None else held * KPH, + policy_kph=None if policy is None else policy * KPH) + + +def test_posted_limit_wins_when_no_driver_sticky(): + assert _ring_exit_target_ms(_hold(policy=30), 45 * CV.MPH_TO_MS, None, 26 * CV.MPH_TO_MS) == pytest.approx(45 * CV.MPH_TO_MS) + + +def test_no_posted_driver_set_restores_exactly_watertown(): + """Route 00000185 17:03:07: stalk-set 35.2 mph, detected at 26.5 mph, SD has no posted limit.""" + t = _ring_exit_target_ms(_hold(held=35.2), None, None, 26.5 * CV.MPH_TO_MS) + assert t == pytest.approx(35.2 * CV.MPH_TO_MS) + + +def test_driver_set_is_a_ceiling_even_below_detection_speed(): + t = _ring_exit_target_ms(_hold(sticky=30), None, None, 45 * CV.MPH_TO_MS) + assert t == pytest.approx(30 * CV.MPH_TO_MS) + t = _ring_exit_target_ms(_hold(held=30), None, None, 45 * CV.MPH_TO_MS) + assert t == pytest.approx(30 * CV.MPH_TO_MS) + + +def test_map_auto_max_rises_to_detection_speed_without_posted(): + t = _ring_exit_target_ms(_hold(policy=30), None, None, 45 * CV.MPH_TO_MS) + assert t == pytest.approx(45 * CV.MPH_TO_MS) + t = _ring_exit_target_ms(_hold(policy=50), None, None, 45 * CV.MPH_TO_MS) + assert t == pytest.approx(50 * CV.MPH_TO_MS) + assert _ring_exit_target_ms(_hold(policy=30), None, None, None) == pytest.approx(30 * CV.MPH_TO_MS) + + +def test_nothing_known(): + assert _ring_exit_target_ms(_hold(), None, None, 40 * CV.MPH_TO_MS) is None diff --git a/selfdrive/mapd/tests/test_speed_overrides.py b/selfdrive/mapd/tests/test_speed_overrides.py new file mode 100644 index 00000000000000..791ad6bcffdf5f --- /dev/null +++ b/selfdrive/mapd/tests/test_speed_overrides.py @@ -0,0 +1,51 @@ +from types import SimpleNamespace + +from openpilot.selfdrive.mapd.speed_overrides import MPH_TO_MS, PENDING_MAX_S, SpeedOverrides, parse_confirmed + + +def m(way): + return SimpleNamespace(way_id=way, road_name="CR 31") + + +def test_parse(): + assert parse_confirmed(None) is None + assert parse_confirmed({"mph": 33, "seq": 1}) is None + assert parse_confirmed('{"mph": 55, "seq": 2, "lat": 45.1}') == {"mph": 55, "seq": 2.0, "lat": 45.1} + + +def test_yes_keyed_by_way_and_direction_and_persists(tmp_path): + p = str(tmp_path / "o.json") + o = SpeedOverrides(p) + e = o.consume({"mph": 55, "seq": 1.0}, m(111), 90.0, 0.0) + assert e["way_id"] == 111 and e["mph"] == 55 + assert abs(o.limit_ms(111, 100.0) - 55 * MPH_TO_MS) < 1e-6 + assert o.limit_ms(111, 270.0) is None # opposite direction keeps OSM + assert o.limit_ms(222, 90.0) is None + assert o.consume({"mph": 55, "seq": 1.0}, m(222), 90.0, 1.0) is None # same seq once + o2 = SpeedOverrides(p) # future drive + assert abs(o2.limit_ms(111, 80.0) - 55 * MPH_TO_MS) < 1e-6 + o2.consume({"mph": 45, "seq": 2.0}, m(111), 95.0, 2.0) # newer YES replaces + assert len(o2.entries) == 1 and o2.find(111, 90.0)["mph"] == 45 + + +def test_pending_until_match_then_expires(tmp_path): + o = SpeedOverrides(str(tmp_path / "o.json")) + assert o.consume({"mph": 30, "seq": 1.0}, None, 10.0, 0.0) is None + assert o.consume(None, m(5), 10.0, 3.0)["way_id"] == 5 + assert o.consume({"mph": 30, "seq": 2.0}, None, 10.0, 10.0) is None + assert o.consume(None, m(6), 10.0, 10.0 + PENDING_MAX_S + 1) is None + assert o.find(6, 10.0) is None + + +def test_request_override_writes_param(): + from openpilot.selfdrive.mapd.speed_overrides import PARAM, request_override + + class P: + d: dict = {} + + def put(self, k, v): + self.d[k] = v + p = P() + assert request_override(35, {"lat": 1.0, "bearing": 90.0}, 3.0, params=p) + assert p.d[PARAM] == {"mph": 35, "seq": 3.0, "lat": 1.0, "bearing": 90.0} + assert not request_override(33, None, 4.0, params=P()) diff --git a/selfdrive/mapd/tests/test_us_statutory.py b/selfdrive/mapd/tests/test_us_statutory.py new file mode 100644 index 00000000000000..680298e9248831 --- /dev/null +++ b/selfdrive/mapd/tests/test_us_statutory.py @@ -0,0 +1,141 @@ +"""US state-default fills (us_statutory) for untagged OSM ways.""" +import os + +import pytest + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd.local_refresh import refresh_local_maps +from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB +from openpilot.selfdrive.mapd.overpass import resolve_way_speed, ways_from_overpass +from openpilot.selfdrive.mapd.us_statutory import IIHS, default_maxspeed_mph, fill_source, is_fill_source, state_index + +WATERTOWN_SD = (44.877, -97.10) +WILLMAR_MN = (45.122, -95.043) + + +@pytest.mark.parametrize("pt, code", [ + (WATERTOWN_SD, "SD"), (WILLMAR_MN, "MN"), ((37.7749, -122.4194), "CA"), ((30.2672, -97.7431), "TX"), + ((40.7128, -74.0060), "NY"), ((38.9072, -77.0369), "DC"), ((21.3069, -157.8583), "HI"), ((61.2181, -149.9003), "AK"), +]) +def test_state_lookup(pt, code): + assert state_index().state_at(*pt) == code + + +def test_every_state_has_limits_and_a_polygon(): + import json + from openpilot.selfdrive.mapd.us_statutory import STATES_JSON + with open(STATES_JSON) as f: + codes = set(json.load(f)["states"]) + assert len(IIHS) == 51 and set(IIHS) == codes + + +@pytest.mark.parametrize("state, hw, tags, urban, mph", [ + ("SD", "primary", {}, False, 65), # IIHS other roads 70, capped 65 + ("SD", "secondary", {}, False, 55), + ("SD", "unclassified", {}, False, 55), + ("SD", "motorway", {}, False, 80), + ("SD", "motorway_link", {}, False, 45), + ("SD", "primary_link", {}, True, 25), + ("SD", "primary", {}, True, 25), + ("SD", "trunk", {"expressway": "yes"}, False, 70), + ("SD", "residential", {}, True, None), # not filled outside MN (size) + ("SD", "service", {}, False, None), + ("TX", "primary", {}, True, 30), + ("PA", "secondary", {}, True, 35), + ("VT", "secondary", {}, False, 50), + ("HI", "primary", {}, False, 45), + ("IL", "motorway", {}, True, 55), + ("MN", "residential", {}, True, 30), # MN 169.14 unchanged + ("MN", "primary", {}, False, 55), + ("MN", "motorway", {}, False, 70), + (None, "primary", {}, False, None), +]) +def test_default_mph(state, hw, tags, urban, mph): + assert default_maxspeed_mph(state, hw, tags, urban=urban) == mph + + +def test_tagged_wins_and_fill_is_marked(): + coords = [(WATERTOWN_SD[0], WATERTOWN_SD[1]), (WATERTOWN_SD[0], WATERTOWN_SD[1] + 0.01)] + ms, src = resolve_way_speed({"highway": "primary", "maxspeed": "45 mph"}, coords, fill_unmarked=True) + assert src == "osm" and abs(ms - 45 * CV.MPH_TO_MS) < 0.01 + ms, src = resolve_way_speed({"highway": "primary"}, coords, fill_unmarked=True) + assert src == fill_source("SD") == "SD_default" and is_fill_source(src) + assert abs(ms - 65 * CV.MPH_TO_MS) < 0.01 + assert resolve_way_speed({"highway": "primary"}, coords, fill_unmarked=False) == (None, "") + + +def _way(wid, lat, lon, hw, maxspeed=None, name="Rd"): + tags = {"highway": hw, "name": name} + if maxspeed: + tags["maxspeed"] = f"{maxspeed} mph" + return {"type": "way", "id": wid, "tags": tags, "nodes": [wid * 10, wid * 10 + 1], + "geometry": [{"lat": lat, "lon": lon - 0.005}, {"lat": lat, "lon": lon + 0.005}]} + + +def test_overpass_ways_carry_estimated_flag(): + lat, lon = WATERTOWN_SD + ways = ways_from_overpass({"elements": [_way(1, lat, lon, "primary", 45), _way(2, lat + 0.02, lon, "primary"), + _way(3, lat + 0.04, lon, "residential")]}, fill_unmarked=True) + by_id = {w["way_id"]: w for w in ways} + assert not by_id[1]["estimated"] and by_id[2]["estimated"] and 3 not in by_id + + +def test_sd_refresh_fills_us212_estimated(tmp_path): + dest = str(tmp_path / "osm" / "speed_limits.sqlite") + os.makedirs(os.path.dirname(dest), exist_ok=True) + con = OsmSpeedLimitDB.create(dest) + OsmSpeedLimitDB.insert_way(con, 9, "Broadway", "primary", 40 * CV.MPH_TO_MS, [(40.7128, -74.006), (40.7138, -74.006)]) + con.commit() + con.close() + lat, lon = WATERTOWN_SD + payload = {"elements": [_way(212, lat, lon, "primary", name="US 212"), _way(5, lat + 0.03, lon, "secondary", 45)]} + refresh_local_maps(dest=dest, live_fix=WATERTOWN_SD, last_gps_raw=None, payload=payload) + db = OsmSpeedLimitDB(dest) + assert db.open() + m = db.lookup(lat, lon, bearing_deg=90.0) + assert m is not None and m.way_id == 212 and m.estimated + assert abs(m.speed_limit_ms - 65 * CV.MPH_TO_MS) < 0.2 + t = db.lookup(lat + 0.03, lon, bearing_deg=90.0) + assert t is not None and not t.estimated and abs(t.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.2 + db.close() + + +def test_untagged_piece_between_posted_takes_posted_limit(): + lat = 44.8901 + ways = ways_from_overpass({"elements": [ + {"type": "way", "id": 1, "tags": {"highway": "primary", "name": "9th Avenue Southeast", "maxspeed": "45 mph"}, + "geometry": [{"lat": lat, "lon": -97.070}, {"lat": lat, "lon": -97.0685}]}, + {"type": "way", "id": 2, "tags": {"highway": "primary", "name": "9th Avenue Southeast"}, + "geometry": [{"lat": lat, "lon": -97.0685}, {"lat": lat, "lon": -97.0678}]}, + {"type": "way", "id": 3, "tags": {"highway": "primary", "name": "9th Avenue Southeast", "maxspeed": "45 mph"}, + "geometry": [{"lat": lat, "lon": -97.0678}, {"lat": lat, "lon": -97.066}]}, + {"type": "way", "id": 4, "tags": {"highway": "primary", "name": "Other Rd"}, + "geometry": [{"lat": lat, "lon": -97.0678}, {"lat": lat + 0.01, "lon": -97.0678}]}, + ]}, fill_unmarked=True) + by_id = {w["way_id"]: w for w in ways} + assert by_id[2]["estimated"] and abs(by_id[2]["maxspeed_ms"] - 45 * CV.MPH_TO_MS) < 0.01 + assert abs(by_id[4]["maxspeed_ms"] - 65 * CV.MPH_TO_MS) < 0.01 # different road: state default + + +def test_mn_ramp_capped(): + assert default_maxspeed_mph("MN", "motorway_link", {}, urban=False) == 45 + + +def test_estimated_limit_capped_at_65_on_car(tmp_path): + from openpilot.selfdrive.mapd.osm_db import OsmSpeedLimitDB + path = str(tmp_path / "cap.sqlite") + con = OsmSpeedLimitDB.create(path) + lat = 46.8328 + OsmSpeedLimitDB.insert_way(con, 1, "I 94", "motorway", 80 * CV.MPH_TO_MS, [(lat, -100.86), (lat, -100.84)], estimated=True) + OsmSpeedLimitDB.insert_way(con, 2, "I 94", "motorway", 80 * CV.MPH_TO_MS, [(lat + 0.1, -100.86), (lat + 0.1, -100.84)]) + OsmSpeedLimitDB.insert_way(con, 3, "Main", "primary", 45 * CV.MPH_TO_MS, [(lat + 0.2, -100.86), (lat + 0.2, -100.84)], estimated=True) + con.commit() + con.close() + db = OsmSpeedLimitDB(path) + assert db.open() + est = db.lookup(lat, -100.85, bearing_deg=90) + posted = db.lookup(lat + 0.1, -100.85, bearing_deg=90) + low = db.lookup(lat + 0.2, -100.85, bearing_deg=90) + assert est.estimated and abs(est.speed_limit_ms - 65 * CV.MPH_TO_MS) < 0.01 + assert not posted.estimated and abs(posted.speed_limit_ms - 80 * CV.MPH_TO_MS) < 0.01 + assert abs(low.speed_limit_ms - 45 * CV.MPH_TO_MS) < 0.01 diff --git a/selfdrive/mapd/us_statutory.py b/selfdrive/mapd/us_statutory.py new file mode 100644 index 00000000000000..b4c413b21c3b5d --- /dev/null +++ b/selfdrive/mapd/us_statutory.py @@ -0,0 +1,248 @@ +"""US state default speed-limit fills for NAP OSM packs (all states). + +When a drivable OSM way has no usable numeric maxspeed, NAP estimates one from +the state's statutory/default limits by road class and urban vs rural context. +Fills are pack-only estimates (ways.estimated = 1, source `_default`, or +`MN_169.14` for Minnesota, whose rules live in mn_statutory.py unchanged). +They must never be uploaded to osm.org. + +Sources (see docs-nap/map-speed.md, "US default fills"): +- Interstate / limited-access / other-road maximums: IIHS "Maximum posted speed + limits" table, Oct 2026 (https://www.iihs.org/research-areas/speed/speed-limit-laws). +- Urban-district defaults: state vehicle codes, listed per state in URBAN_MPH. +Rural non-freeway fills are capped (65 mph major / 55 mph minor) below the IIHS +maximums because those maximums are ceilings, not what an unmarked road carries. + +OpenStreetMap geometries/tags remain ODbL: © OpenStreetMap contributors. +""" +from __future__ import annotations + +import json +import os +from dataclasses import dataclass +from functools import lru_cache + +from openpilot.common.constants import CV +from openpilot.selfdrive.mapd import mn_statutory +from openpilot.selfdrive.mapd.mn_statutory import ( + ALLEY_LIKE, + MOTORWAY_LIKE, + PlaceIndex, + _point_in_ring, + is_expressway_like, + is_urban_way, +) + +MN = "MN" +SOURCE_SUFFIX = "_default" +# Major rural roads (trunk/primary) and minor rural roads (secondary/tertiary/unclassified) +# are capped below the IIHS "other roads" ceiling. +RURAL_MAJOR_CAP_MPH = 65 +RURAL_MINOR_CAP_MPH = 55 +RESIDENTIAL_MPH = 25 +# Unposted ramps/links: never above this (curves, merges); posted ramps keep their tag. +# Applies in Minnesota too (MN 169.14 alone would give a ramp 70). +LINK_CAP_MPH = 45 +ALLEY_MPH = 15 + +# Fill only classes the car drives at speed. residential / living_street / alley +# are filled only inside Minnesota (existing MN_169.14 behavior), everywhere else +# they would ~triple the pack for streets that are almost always 25. +FILL_CLASSES = frozenset({ + "motorway", "motorway_link", "trunk", "trunk_link", "primary", "primary_link", + "secondary", "secondary_link", "tertiary", "tertiary_link", "unclassified", +}) +FILLABLE_HIGHWAY_REGEX = ( + "^(motorway(_link)?|trunk(_link)?|primary(_link)?|secondary(_link)?" + + r"|tertiary(_link)?|unclassified)$" +) +MAJOR = frozenset({"trunk", "trunk_link", "primary", "primary_link"}) +MINOR = frozenset({"secondary", "secondary_link", "tertiary", "tertiary_link", "unclassified"}) + + +@dataclass(frozen=True) +class StateLimits: + rural_interstate: int + urban_interstate: int + limited_access: int + other_roads: int + + +# IIHS maximum posted speed limits, Oct 2026 (cars). DC has no interstates +# rated rural; its limited-access value reuses the urban interstate figure. +IIHS: dict[str, StateLimits] = { + "AL": StateLimits(70, 70, 65, 65), "AK": StateLimits(65, 55, 65, 55), + "AZ": StateLimits(75, 65, 65, 65), "AR": StateLimits(75, 65, 75, 65), + "CA": StateLimits(70, 65, 70, 65), "CO": StateLimits(75, 65, 65, 65), + "CT": StateLimits(65, 55, 65, 55), "DE": StateLimits(65, 55, 65, 55), + "DC": StateLimits(55, 55, 55, 25), "FL": StateLimits(70, 65, 70, 65), + "GA": StateLimits(70, 70, 65, 65), "HI": StateLimits(60, 60, 55, 45), + "ID": StateLimits(75, 75, 70, 70), "IL": StateLimits(70, 55, 65, 55), + "IN": StateLimits(70, 55, 60, 55), "IA": StateLimits(70, 65, 70, 65), + "KS": StateLimits(75, 75, 75, 65), "KY": StateLimits(65, 65, 65, 55), + "LA": StateLimits(75, 70, 70, 65), "ME": StateLimits(75, 75, 75, 60), + "MD": StateLimits(70, 70, 70, 55), "MA": StateLimits(65, 65, 65, 55), + "MI": StateLimits(70, 70, 70, 55), "MN": StateLimits(70, 65, 65, 60), + "MS": StateLimits(70, 70, 70, 65), "MO": StateLimits(75, 60, 75, 65), + "MT": StateLimits(80, 65, 70, 65), "NE": StateLimits(75, 70, 70, 65), + "NV": StateLimits(80, 65, 70, 70), "NH": StateLimits(65, 65, 55, 55), + "NJ": StateLimits(65, 55, 65, 55), "NM": StateLimits(75, 75, 65, 55), + "NY": StateLimits(65, 65, 65, 55), "NC": StateLimits(70, 70, 70, 55), + "ND": StateLimits(80, 75, 70, 65), "OH": StateLimits(70, 65, 70, 55), + "OK": StateLimits(75, 70, 70, 70), "OR": StateLimits(65, 55, 65, 65), + "PA": StateLimits(70, 70, 70, 55), "RI": StateLimits(65, 55, 55, 55), + "SC": StateLimits(70, 70, 60, 55), "SD": StateLimits(80, 80, 70, 70), + "TN": StateLimits(70, 70, 70, 65), "TX": StateLimits(75, 75, 75, 75), + "UT": StateLimits(75, 70, 75, 65), "VT": StateLimits(65, 55, 50, 50), + "VA": StateLimits(70, 70, 65, 55), "WA": StateLimits(70, 60, 60, 60), + "WV": StateLimits(70, 55, 65, 55), "WI": StateLimits(70, 70, 70, 55), + "WY": StateLimits(75, 75, 70, 70), +} +# Montana night limits are lower (IIHS: limited access 75 day / 70 night, +# other roads 70 / 65); the fill uses the night value. + +# Urban-district default (non-residential roads inside a city/town/village). +# 25 mph unless the state code sets another district default: +# IL 625 ILCS 5/11-601(a) 30; IN IC 9-21-5-2 30; MN 169.14 subd 2 30; +# NY VTL 1180(b)/1643 (city default) 30; TX Transp. Code 545.352(b)(1) 30; +# FL 316.183(2) 30; GA O.C.G.A. 40-6-181(b)(1) 30; NC G.S. 20-141(b)(1) 35; +# PA 75 Pa.C.S. 3362(a)(1.1) 35 (urban district). +URBAN_DEFAULT_MPH = 25 +URBAN_MPH: dict[str, int] = {"IL": 30, "IN": 30, "MN": 30, "NY": 30, "TX": 30, "FL": 30, "GA": 30, "NC": 35, "PA": 35} + +NEAR_PAD_DEG = 0.1 +STATES_JSON = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "us_states.json") + + +def fill_source(state: str) -> str: + return mn_statutory.FILL_SOURCE if state == MN else f"{state}{SOURCE_SUFFIX}" + + +def is_fill_source(source: str | None) -> bool: + s = str(source or "") + return s == mn_statutory.FILL_SOURCE or s.endswith(SOURCE_SUFFIX) + + +def default_maxspeed_mph(state: str | None, highway: str, tags: dict, *, urban: bool) -> int | None: + """State default mph for an untagged way, or None to leave it unfilled.""" + if not state: + return None + hw = (highway or str(tags.get("highway") or "")).strip().lower() + if state == MN: + mph = mn_statutory.statutory_maxspeed_mph(hw, tags, urban=urban) + return min(mph, LINK_CAP_MPH) if mph is not None and hw.endswith("_link") else mph + lim = IIHS.get(state) + if lim is None or hw not in FILL_CLASSES: + return None + mph = _state_default_mph(state, lim, hw, tags, urban=urban) + if mph is not None and hw.endswith("_link"): + mph = min(mph, LINK_CAP_MPH) + return mph + + +def _state_default_mph(state: str, lim: StateLimits, hw: str, tags: dict, *, urban: bool) -> int | None: + if hw in MOTORWAY_LIKE: + return lim.urban_interstate if urban else lim.rural_interstate + if hw in MAJOR and is_expressway_like(tags): + return lim.limited_access + if urban: + return URBAN_MPH.get(state, URBAN_DEFAULT_MPH) + if hw in MAJOR: + return min(lim.other_roads, RURAL_MAJOR_CAP_MPH) + if hw in MINOR: + return min(lim.other_roads, RURAL_MINOR_CAP_MPH) + return None + + +def fillable_highway(state: str | None, highway: str) -> bool: + hw = (highway or "").strip().lower() + if state == MN: + return hw in FILL_CLASSES or hw in ("residential",) or hw in ALLEY_LIKE + return hw in FILL_CLASSES + + +class StateIndex: + """Point → US state postal code from simplified Census state polygons.""" + + def __init__(self, path: str = STATES_JSON) -> None: + with open(path, encoding="utf-8") as f: + data = json.load(f) + self._polys: list[tuple[str, float, float, float, float, list[tuple[float, float]]]] = [] + for code, rings in data["states"].items(): + for ring in rings: + pts = [(float(a), float(b)) for a, b in ring] + lats = [p[0] for p in pts] + lons = [p[1] for p in pts] + self._polys.append((code, min(lats), max(lats), min(lons), max(lons), pts)) + + def state_at(self, lat: float, lon: float) -> str | None: + for code, s, n, w, e, ring in self._polys: + if s <= lat <= n and w <= lon <= e and _point_in_ring(lat, lon, ring): + return code + # Simplified coastlines miss shore roads: nearest vertex within ~0.1 deg. + best, best_d = None, NEAR_PAD_DEG ** 2 + for code, s, n, w, e, ring in self._polys: + if not (s - NEAR_PAD_DEG <= lat <= n + NEAR_PAD_DEG and w - NEAR_PAD_DEG <= lon <= e + NEAR_PAD_DEG): + continue + for plat, plon in ring: + d = (plat - lat) ** 2 + (plon - lon) ** 2 + if d < best_d: + best, best_d = code, d + return best + + def state_of_way(self, coords: list[tuple[float, float]]) -> str | None: + if not coords: + return None + mid = coords[len(coords) // 2] + return self.state_at(mid[0], mid[1]) or self.state_at(*coords[0]) or self.state_at(*coords[-1]) + + +@lru_cache(maxsize=1) +def state_index() -> StateIndex: + return StateIndex() + + +def default_maxspeed_ms(state: str | None, highway: str, tags: dict, coords: list[tuple[float, float]], + places: PlaceIndex | None) -> tuple[float | None, str]: + """(m/s, source) default for an untagged way, or (None, '').""" + if not state or not fillable_highway(state, highway): + return None, "" + urban = is_urban_way(tags, coords, places) + mph = default_maxspeed_mph(state, highway, tags, urban=urban) + if mph is None: + return None, "" + return mph * CV.MPH_TO_MS, fill_source(state) + + +def _end_keys(coords: list[tuple[float, float]]) -> tuple[tuple[int, int], tuple[int, int]]: + a, b = coords[0], coords[-1] + return (round(a[0] * 1e6), round(a[1] * 1e6)), (round(b[0] * 1e6), round(b[1] * 1e6)) + + +def inherit_posted_neighbors(ways: list[dict]) -> int: + """Estimated fills that continue a posted road take the posted limit. + + An untagged piece of the same named road between two posted pieces (e.g. a + bridge or a split way on US-212 in Watertown, SD) would otherwise get the + rural default (70) between two 45 mph zones. If an estimated way shares an + endpoint with posted ways of the same name, it takes the lowest of their + limits. It stays estimated. Returns how many ways were changed. + """ + posted: dict[tuple[str, tuple[int, int]], float] = {} + for w in ways: + if w.get("estimated") or len(w.get("coords") or []) < 2 or not w.get("name"): + continue + for k in _end_keys(w["coords"]): + key = (str(w["name"]), k) + posted[key] = min(posted.get(key, 1e9), float(w["maxspeed_ms"])) + changed = 0 + for w in ways: + if not w.get("estimated") or len(w.get("coords") or []) < 2 or not w.get("name"): + continue + near = [posted[(str(w["name"]), k)] for k in _end_keys(w["coords"]) if (str(w["name"]), k) in posted] + if near: + v = min(near) + if abs(v - float(w["maxspeed_ms"])) > 0.01: + w["maxspeed_ms"] = v + changed += 1 + return changed diff --git a/selfdrive/modeld/.gitignore b/selfdrive/modeld/.gitignore deleted file mode 100644 index 742d3d120534b5..00000000000000 --- a/selfdrive/modeld/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*_pyx.cpp diff --git a/selfdrive/modeld/SConscript b/selfdrive/modeld/SConscript index d572915c721a48..fadd5825732df9 100644 --- a/selfdrive/modeld/SConscript +++ b/selfdrive/modeld/SConscript @@ -1,74 +1,140 @@ import glob - -Import('env', 'envCython', 'arch', 'cereal', 'messaging', 'common', 'gpucommon', 'visionipc', 'transformations') -lenv = env.Clone() -lenvCython = envCython.Clone() - -libs = [cereal, messaging, visionipc, gpucommon, common, 'capnp', 'kj', 'pthread'] -frameworks = [] - -common_src = [ - "models/commonmodel.cc", - "transforms/loadyuv.cc", - "transforms/transform.cc", +import json +import os +import sys, subprocess +from SCons.Script import Value +from openpilot.common.file_chunker import chunk_file, get_chunk_targets, get_existing_chunks +from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye +from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE, DM_INPUT_SIZE +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.selfdrive.modeld.helpers import TG_INPUT_DEVICES_PATH, usbgpu_present, modeld_pkl_path + + +CAMERA_CONFIGS = [ + (_ar_ox_fisheye.width, _ar_ox_fisheye.height), # tici: 1928x1208 + (_os_fisheye.width, _os_fisheye.height), # mici: 1344x760 ] -thneed_src_common = [ - "thneed/thneed_common.cc", - "thneed/serialize.cc", -] - -thneed_src_qcom = thneed_src_common + ["thneed/thneed_qcom2.cc"] -thneed_src_pc = thneed_src_common + ["thneed/thneed_pc.cc"] -thneed_src = thneed_src_qcom if arch == "larch64" else thneed_src_pc - -# SNPE except on Mac and ARM Linux -snpe_lib = [] -if arch != "Darwin" and arch != "aarch64": - common_src += ['runners/snpemodel.cc'] - snpe_lib += ['SNPE'] +Import('env', 'arch') +chunker_file = File("#common/file_chunker.py") +lenv = env.Clone() -# OpenCL is a framework on Mac -if arch == "Darwin": - frameworks += ['OpenCL'] +tinygrad_root = env.Dir("#").abspath +tinygrad_files = ["#"+x for x in glob.glob(env.Dir("#tinygrad_repo").relpath + "/**", recursive=True, root_dir=tinygrad_root) + if 'pycache' not in x and os.path.isfile(os.path.join(tinygrad_root, x))] + +def estimate_pickle_max_size(onnx_size): + return 1.2 * onnx_size + 10 * 1024 * 1024 # 20% + 10MB is plenty + +# get fastest TG config +# probe in subprocess so usbgpu locks gets released on process exit +def probe_devices(): + return set(subprocess.run( + [sys.executable, '-c', 'from tinygrad import Device\nprint("\\n".join(Device.get_available_devices()))'], + capture_output=True, text=True, check=True).stdout.strip().splitlines()) + +available = probe_devices() +if 'CUDA' in available: + tg_backend = 'CUDA' + tg_flags = f'DEV={tg_backend}' +elif 'QCOM' in available: + tg_backend = 'QCOM' + tg_flags = f'DEV={tg_backend} IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1' else: - libs += ['OpenCL'] - -# Set path definitions -for pathdef, fn in {'TRANSFORM': 'transforms/transform.cl', 'LOADYUV': 'transforms/loadyuv.cl'}.items(): - for xenv in (lenv, lenvCython): - xenv['CXXFLAGS'].append(f'-D{pathdef}_PATH=\\"{File(fn).abspath}\\"') - -# Compile cython -snpe_rpath_qcom = "/data/pythonpath/third_party/snpe/larch64" -snpe_rpath_pc = f"{Dir('#').abspath}/third_party/snpe/x86_64-linux-clang" -snpe_rpath = lenvCython['RPATH'] + [snpe_rpath_qcom if arch == "larch64" else snpe_rpath_pc] - -cython_libs = envCython["LIBS"] + libs -snpemodel_lib = lenv.Library('snpemodel', ['runners/snpemodel.cc']) -commonmodel_lib = lenv.Library('commonmodel', common_src) - -lenvCython.Program('runners/runmodel_pyx.so', 'runners/runmodel_pyx.pyx', LIBS=cython_libs, FRAMEWORKS=frameworks) -lenvCython.Program('runners/snpemodel_pyx.so', 'runners/snpemodel_pyx.pyx', LIBS=[snpemodel_lib, snpe_lib, *cython_libs], FRAMEWORKS=frameworks, RPATH=snpe_rpath) -lenvCython.Program('models/commonmodel_pyx.so', 'models/commonmodel_pyx.pyx', LIBS=[commonmodel_lib, *cython_libs], FRAMEWORKS=frameworks) - -tinygrad_files = ["#"+x for x in glob.glob(env.Dir("#tinygrad_repo").relpath + "/**", recursive=True, root_dir=env.Dir("#").abspath)] - -# Get model metadata -fn = File("models/supercombo").abspath -cmd = f'python3 {Dir("#selfdrive/modeld").abspath}/get_model_metadata.py {fn}.onnx' -lenv.Command(fn + "_metadata.pkl", [fn + ".onnx"] + tinygrad_files, cmd) - -# Build thneed model -if arch == "larch64" or GetOption('pc_thneed'): - tinygrad_opts = [] - if not GetOption('pc_thneed'): - # use FLOAT16 on device for speed + don't cache the CL kernels for space - tinygrad_opts += ["FLOAT16=1", "PYOPENCL_NO_CACHE=1"] - cmd = f"cd {Dir('#').abspath}/tinygrad_repo && " + ' '.join(tinygrad_opts) + f" python3 openpilot/compile2.py {fn}.onnx {fn}.thneed" - - lenv.Command(fn + ".thneed", [fn + ".onnx"] + tinygrad_files, cmd) - - thneed_lib = env.SharedLibrary('thneed', thneed_src, LIBS=[gpucommon, common, 'OpenCL', 'dl']) - thneedmodel_lib = env.Library('thneedmodel', ['runners/thneedmodel.cc']) - lenvCython.Program('runners/thneedmodel_pyx.so', 'runners/thneedmodel_pyx.pyx', LIBS=envCython["LIBS"]+[thneedmodel_lib, thneed_lib, gpucommon, common, 'dl', 'OpenCL']) + tg_backend = 'CPU' + tg_flags = f'DEV=CPU' if arch == 'Darwin' else 'DEV=CPU:LLVM' + +tg_devices = { # which device to put jit inputs to at runtime + 'selfdrive.modeld.modeld': { + 'default': {'WARP_DEV': tg_backend, 'QUEUE_DEV': tg_backend} + }, + 'selfdrive.modeld.dmonitoringmodeld': { + 'default': {'DEV': tg_backend} + }, +} + +USBGPU = usbgpu_present() # or release # TODO always build big model on release +if USBGPU: + tg_devices['selfdrive.modeld.modeld']['usbgpu'] = {'WARP_DEV': tg_backend, 'QUEUE_DEV': 'AMD'} + usbgpu_tg_flags = f'DEBUG=2 DEV=USB+AMD:LLVM WARP_DEV={tg_backend} FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0' + # the USB+AMD GPU takes an exclusive flock; serialize all targets that touch it + usbgpu_lock = File("models/.usb_gpu.lock").abspath + +def write_tg_devices(target, source, env): + with open(str(target[0]), "w") as f: + json.dump(tg_devices, f) + f.write("\n") + +tg_devices_node = lenv.Command( + str(TG_INPUT_DEVICES_PATH), + [Value(tg_devices)], + write_tg_devices, +) + +# tinygrad calls brew which needs a $HOME in the env +mac_brew_string = f'HOME={os.path.expanduser("~")}' if arch == 'Darwin' else '' + +modeld_dir = Dir("#selfdrive/modeld").abspath +compile_modeld_script = [ + File(f"{modeld_dir}/compile_modeld.py"), + File(f"{modeld_dir}/get_model_metadata.py"), + File("#system/camerad/cameras/nv12_info.py"), + File("#system/hardware/hw.py"), +] +model_w, model_h = MEDMODEL_INPUT_SIZE +frame_skip = ModelConstants.MODEL_RUN_FREQ // ModelConstants.MODEL_CONTEXT_FREQ + +for usbgpu in [False, True] if USBGPU else [False]: + target_pkl_path = File(modeld_pkl_path(usbgpu)).abspath + file_prefix, cmd_flags = ('big_', usbgpu_tg_flags) if usbgpu else ('', tg_flags) + driving_onnx_deps = [p for m in [f'{file_prefix}driving_vision', f'{file_prefix}driving_policy'] + for p in get_existing_chunks(File(f"models/{m}.onnx").abspath)] + camera_res_args = ' '.join(f'{cw}x{ch}' for cw, ch in CAMERA_CONFIGS) + cmd = (f'{cmd_flags} {mac_brew_string} python3 {modeld_dir}/compile_modeld.py ' + f'--model-size {model_w}x{model_h} ' + f'--camera-resolutions {camera_res_args} ' + f'--vision-onnx {File(f"models/{file_prefix}driving_vision.onnx").abspath} ' + f'--policy-onnx {File(f"models/{file_prefix}driving_policy.onnx").abspath} ' + f'--output {target_pkl_path} --frame-skip {frame_skip}') + onnx_sizes_sum = sum(os.path.getsize(f) for f in driving_onnx_deps) + chunk_targets = get_chunk_targets(target_pkl_path, estimate_pickle_max_size(onnx_sizes_sum)) + def do_chunk(target, source, env, pkl=target_pkl_path, chunks=chunk_targets): + chunk_file(pkl, chunks) + node = lenv.Command( + chunk_targets, + tinygrad_files + compile_modeld_script + driving_onnx_deps + [Value(chunk_targets), chunker_file], + [cmd, do_chunk], + ) + if usbgpu: + lenv.SideEffect(usbgpu_lock, node) + +# get model metadata +fn = File(f"models/dmonitoring_model").abspath +script_files = [File(Dir("#selfdrive/modeld").File("get_model_metadata.py").abspath)] +cmd = f'{tg_flags} {mac_brew_string} python3 {Dir("#selfdrive/modeld").abspath}/get_model_metadata.py {fn}.onnx' +lenv.Command(fn + "_metadata.pkl", [fn + ".onnx"] + tinygrad_files + script_files + [tg_devices_node], cmd) + +dm_w, dm_h = DM_INPUT_SIZE +compile_dm_warp_script = [File(f"{modeld_dir}/compile_dm_warp.py")] +for cam_w, cam_h in CAMERA_CONFIGS: + dm_pkl_path = File(f"models/dm_warp_{cam_w}x{cam_h}_tinygrad.pkl").abspath + cmd = (f'{tg_flags} {mac_brew_string} python3 {modeld_dir}/compile_dm_warp.py ' + f'--camera-resolution {cam_w}x{cam_h} --warp-to {dm_w}x{dm_h} ' + f'--output {dm_pkl_path}') + lenv.Command(dm_pkl_path, tinygrad_files + compile_dm_warp_script + compile_modeld_script + [tg_devices_node], cmd) + +def tg_compile(flags, model_name): + pythonpath_string = 'PYTHONPATH="${PYTHONPATH}:' + env.Dir("#tinygrad_repo").abspath + '"' + fn = File(f"models/{model_name}").abspath + pkl = fn + "_tinygrad.pkl" + onnx_path = fn + ".onnx" + chunk_targets = get_chunk_targets(pkl, estimate_pickle_max_size(os.path.getsize(onnx_path))) + def do_chunk(target, source, env): + chunk_file(pkl, chunk_targets) + return lenv.Command( + chunk_targets, + [onnx_path] + tinygrad_files + [Value(chunk_targets), chunker_file, tg_devices_node], + [f'{pythonpath_string} {flags} python3 {Dir("#tinygrad_repo").abspath}/examples/openpilot/compile3.py {fn}.onnx {pkl}', do_chunk], + ) + +tg_compile(tg_flags, 'dmonitoring_model') diff --git a/selfdrive/modeld/compile_dm_warp.py b/selfdrive/modeld/compile_dm_warp.py new file mode 100755 index 00000000000000..16e0d39fbb5780 --- /dev/null +++ b/selfdrive/modeld/compile_dm_warp.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +import argparse +import pickle +import time + +from tinygrad.tensor import Tensor +from tinygrad.device import Device +from tinygrad.engine.jit import TinyJit + +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info +from openpilot.selfdrive.modeld.compile_modeld import NV12Frame, warp_perspective_tinygrad, _parse_size + + +def make_warp_dm(nv12: NV12Frame, dm_w, dm_h): + cam_w, cam_h, stride, _, _, _ = nv12 + stride_pad = stride - cam_w + + def warp_dm(input_frame, M_inv): + M_inv = M_inv.to(Device.DEFAULT).realize() + return warp_perspective_tinygrad(input_frame[:cam_h*stride], M_inv, + (dm_w, dm_h), (cam_h, cam_w), stride_pad, border_fill_val=16).reshape(-1, dm_h * dm_w) # Y + return warp_dm + + +def compile_dm_warp(nv12: NV12Frame, dm_w, dm_h, pkl_path): + print(f"Compiling DM warp for {nv12.width}x{nv12.height} -> {dm_w}x{dm_h}...") + + warp_dm_jit = TinyJit(make_warp_dm(nv12, dm_w, dm_h), prune=True) + + for i in range(10): + frame = Tensor.randint(nv12.size, low=0, high=256, dtype='uint8').realize() + M_inv = Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY') + Device.default.synchronize() + st = time.perf_counter() + warp_dm_jit(frame, M_inv).realize() + mt = time.perf_counter() + Device.default.synchronize() + et = time.perf_counter() + print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms") + + with open(pkl_path, "wb") as f: + pickle.dump(warp_dm_jit, f) + print(f" Saved to {pkl_path}") + + +if __name__ == "__main__": + p = argparse.ArgumentParser() + p.add_argument('--camera-resolution', type=_parse_size, required=True, help='camera resolution WxH') + p.add_argument('--warp-to', type=_parse_size, required=True, help='DM input WxH') + p.add_argument('--output', required=True) + args = p.parse_args() + + cam_w, cam_h = args.camera_resolution + nv12 = NV12Frame(cam_w, cam_h, *get_nv12_info(cam_w, cam_h)) + dm_w, dm_h = args.warp_to + compile_dm_warp(nv12, dm_w, dm_h, args.output) diff --git a/selfdrive/modeld/compile_modeld.py b/selfdrive/modeld/compile_modeld.py new file mode 100755 index 00000000000000..f455e9f6eb11ad --- /dev/null +++ b/selfdrive/modeld/compile_modeld.py @@ -0,0 +1,289 @@ +#!/usr/bin/env python3 +import argparse +import atexit +import os +import pickle +import time +from functools import partial +from collections import namedtuple, defaultdict + +import numpy as np + +def _patch_tinygrad_fetch_fw(): + import hashlib + import pathlib + import zstandard + from tinygrad import helpers + _orig = helpers.fetch_fw + def fetch_fw(path, name, sha256): + p = pathlib.Path(f"/lib/firmware/{path}/{name}.zst") + if p.is_file(): + blob = zstandard.ZstdDecompressor().stream_reader(p.read_bytes()).read() + if hashlib.sha256(blob).hexdigest() == sha256: + return blob + return _orig(path, name, sha256) + helpers.fetch_fw = fetch_fw +_patch_tinygrad_fetch_fw() + +from tinygrad.tensor import Tensor +from tinygrad.helpers import Context +from tinygrad.device import Device +from tinygrad.engine.jit import TinyJit + + +NV12Frame = namedtuple("NV12Frame", ['width', 'height', 'stride', 'y_height', 'uv_height', 'size']) +WARP_INPUTS = ['img_q', 'big_img_q', 'tfm', 'big_tfm'] +POLICY_INPUTS = ['feat_q', 'desire_q', 'desire', 'traffic_convention'] + +UV_SCALE_MATRIX = np.array([[0.5, 0, 0], [0, 0.5, 0], [0, 0, 1]], dtype=np.float32) +UV_SCALE_MATRIX_INV = np.linalg.inv(UV_SCALE_MATRIX) + +WARP_DEV = os.getenv('WARP_DEV') + + +def make_random_images(keys, shape, device=None): + return {k: Tensor.randint(shape, low=0, high=256, dtype='uint8', device=device).realize() for k in keys} + + +def warp_perspective_tinygrad(src_flat, M_inv, dst_shape, src_shape, stride_pad, border_fill_val=None): + w_dst, h_dst = dst_shape + h_src, w_src = src_shape + + x = Tensor.arange(w_dst, device=WARP_DEV).reshape(1, w_dst).expand(h_dst, w_dst).reshape(-1) + y = Tensor.arange(h_dst, device=WARP_DEV).reshape(h_dst, 1).expand(h_dst, w_dst).reshape(-1) + + # inline 3x3 matmul as elementwise to avoid reduce op (enables fusion with gather) + src_x = M_inv[0, 0] * x + M_inv[0, 1] * y + M_inv[0, 2] + src_y = M_inv[1, 0] * x + M_inv[1, 1] * y + M_inv[1, 2] + src_w = M_inv[2, 0] * x + M_inv[2, 1] * y + M_inv[2, 2] + + src_x = src_x / src_w + src_y = src_y / src_w + + x_round = Tensor.round(src_x) + y_round = Tensor.round(src_y) + x_nn_clipped = x_round.clip(0, w_src - 1).cast('int') + y_nn_clipped = y_round.clip(0, h_src - 1).cast('int') + idx = y_nn_clipped * (w_src + stride_pad) + x_nn_clipped + sampled = src_flat[idx] + + if border_fill_val is None: + return sampled + + in_bounds = ((x_round >= 0) & (x_round <= w_src - 1) & + (y_round >= 0) & (y_round <= h_src - 1)).cast(sampled.dtype) + return sampled * in_bounds + Tensor(border_fill_val, dtype=sampled.dtype) * (1 - in_bounds) + + +def frames_to_tensor(frames): + H = (frames.shape[0] * 2) // 3 + W = frames.shape[1] + in_img1 = Tensor.cat(frames[0:H:2, 0::2], + frames[1:H:2, 0::2], + frames[0:H:2, 1::2], + frames[1:H:2, 1::2], + frames[H:H+H//4].reshape((H//2, W//2)), + frames[H+H//4:H+H//2].reshape((H//2, W//2)), dim=0).reshape((6, H//2, W//2)) + return in_img1 + + +def make_frame_prepare(nv12: NV12Frame, model_w, model_h): + cam_w, cam_h, stride, y_height, uv_height, _ = nv12 + uv_offset = stride * y_height + stride_pad = stride - cam_w + + def frame_prepare_tinygrad(input_frame, M_inv): + # UV_SCALE @ M_inv @ UV_SCALE_INV simplifies to elementwise scaling + M_inv_uv = M_inv * Tensor([[1.0, 1.0, 0.5], [1.0, 1.0, 0.5], [2.0, 2.0, 1.0]], device=WARP_DEV) + # deinterleave NV12 UV plane (UVUV... -> separate U, V) + uv = input_frame[uv_offset:uv_offset + uv_height * stride].reshape(uv_height, stride) + with Context(SPLIT_REDUCEOP=0): + y = warp_perspective_tinygrad(input_frame[:cam_h*stride], + M_inv, (model_w, model_h), + (cam_h, cam_w), stride_pad).realize() + u = warp_perspective_tinygrad(uv[:cam_h//2, :cam_w:2].flatten(), + M_inv_uv, (model_w//2, model_h//2), + (cam_h//2, cam_w//2), 0).realize() + v = warp_perspective_tinygrad(uv[:cam_h//2, 1:cam_w:2].flatten(), + M_inv_uv, (model_w//2, model_h//2), + (cam_h//2, cam_w//2), 0).realize() + yuv = y.cat(u).cat(v).reshape((model_h * 3 // 2, model_w)) + tensor = frames_to_tensor(yuv) + return tensor + return frame_prepare_tinygrad + + +def make_input_queues(vision_input_shapes, policy_input_shapes, frame_skip, device): + img = vision_input_shapes['img'] # (1, 12, 128, 256) + n_frames = img[1] // 6 + img_buf_shape = (frame_skip * (n_frames - 1) + 1, 6, img[2], img[3]) + + fb = policy_input_shapes['features_buffer'] # (1, 25, 512) + dp = policy_input_shapes['desire_pulse'] # (1, 25, 8) + tc = policy_input_shapes['traffic_convention'] # (1, 2) + + npy = { + 'desire': np.zeros(dp[2], dtype=np.float32), + 'traffic_convention': np.zeros(tc, dtype=np.float32), + 'tfm': np.zeros((3, 3), dtype=np.float32), + 'big_tfm': np.zeros((3, 3), dtype=np.float32), + } + input_queues = { + 'img_q': Tensor(np.zeros(img_buf_shape, dtype=np.uint8), device=device).contiguous().realize(), + 'big_img_q': Tensor(np.zeros(img_buf_shape, dtype=np.uint8), device=device).contiguous().realize(), + 'feat_q': Tensor(np.zeros((frame_skip * (fb[1] - 1) + 1, fb[0], fb[2]), dtype=np.float32), device=device).contiguous().realize(), + 'desire_q': Tensor(np.zeros((frame_skip * dp[1], dp[0], dp[2]), dtype=np.float32), device=device).contiguous().realize(), + **{k: Tensor(v, device='NPY').realize() for k, v in npy.items()}, + } + return input_queues, npy + + +def shift_and_sample(buf, new_val, sample_fn): + buf.assign(buf[1:].cat(new_val, dim=0).contiguous()) + return sample_fn(buf) + + +def sample_skip(buf, frame_skip): + return buf[::frame_skip].contiguous().flatten(0, 1).unsqueeze(0) + + +def sample_desire(buf, frame_skip): + return buf.reshape(-1, frame_skip, *buf.shape[1:]).max(1).flatten(0, 1).unsqueeze(0) + + +def make_warp(nv12, model_w, model_h, frame_skip): + frame_prepare = make_frame_prepare(nv12, model_w, model_h) + sample_skip_fn = partial(sample_skip, frame_skip=frame_skip) + + def warp_enqueue(img_q, big_img_q, tfm, big_tfm, frame, big_frame): + tfm = tfm.to(WARP_DEV) + big_tfm = big_tfm.to(WARP_DEV) + Tensor.realize(tfm, big_tfm) + + warped_frame = frame_prepare(frame, tfm).unsqueeze(0).to(Device.DEFAULT) + warped_big_frame = frame_prepare(big_frame, big_tfm).unsqueeze(0).to(Device.DEFAULT) + img = shift_and_sample(img_q, warped_frame, sample_skip_fn) + big_img = shift_and_sample(big_img_q, warped_big_frame, sample_skip_fn) + return img, big_img + return warp_enqueue + + +def make_run_policy(vision_runner, policy_runner, vision_features_slice, frame_skip): + sample_desire_fn = partial(sample_desire, frame_skip=frame_skip) + sample_skip_fn = partial(sample_skip, frame_skip=frame_skip) + + def run_policy(img, big_img, feat_q, desire_q, desire, traffic_convention): + desire = desire.to(Device.DEFAULT) + traffic_convention = traffic_convention.to(Device.DEFAULT) + Tensor.realize(desire, traffic_convention) + desire_buf = shift_and_sample(desire_q, desire.reshape(1, 1, -1), sample_desire_fn) + vision_out = next(iter(vision_runner({'img': img, 'big_img': big_img}).values())).cast('float32') + + new_feat = vision_out[:, vision_features_slice].reshape(1, -1).unsqueeze(0) + feat_buf = shift_and_sample(feat_q, new_feat, sample_skip_fn) + + inputs = {'features_buffer': feat_buf, 'desire_pulse': desire_buf, 'traffic_convention': traffic_convention} + policy_out = next(iter(policy_runner(inputs).values())).cast('float32') + return vision_out, policy_out + return run_policy + + +def compile_jit(jit, make_random_inputs, input_keys, frame_skip, vision_metadata, policy_metadata): + vision_input_shapes = vision_metadata['input_shapes'] + policy_input_shapes = policy_metadata['input_shapes'] + + SEED = 42 + def random_inputs_run(fn, seed, test_val=None, test_buffers=None, expect_match=True): + input_queues, npy = make_input_queues(vision_input_shapes, policy_input_shapes, frame_skip, Device.DEFAULT) + np.random.seed(seed) + Tensor.manual_seed(seed) + + testing = test_val is not None or test_buffers is not None + n_runs = 1 if testing else 3 + + for i in range(n_runs): + for v in npy.values(): + v[:] = np.random.randn(*v.shape).astype(v.dtype) + Device.default.synchronize() + random_inputs = make_random_inputs() + st = time.perf_counter() + outs = fn(**{k: input_queues[k] for k in input_keys}, **random_inputs) + mt = time.perf_counter() + Device.default.synchronize() + et = time.perf_counter() + print(f" [{i+1}/{n_runs}] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms") + + if i == 0: + val = [np.copy(v.numpy()) for v in outs] + buffers = [np.copy(v.numpy().copy()) for v in input_queues.values()] + + if test_val is not None: + match = all(np.array_equal(a, b) for a, b in zip(val, test_val, strict=True)) + assert match == expect_match, f"outputs {'differ from' if expect_match else 'match'} baseline (seed={seed})" + if test_buffers is not None: + match = all(np.array_equal(a, b) for a, b in zip(buffers, test_buffers, strict=True)) + assert match == expect_match, f"buffers {'differ from' if expect_match else 'match'} baseline (seed={seed})" + return val, buffers + + print('capture + replay') + test_val, test_buffers = random_inputs_run(jit, SEED) + print('pickle round trip') + jit = pickle.loads(pickle.dumps(jit)) + random_inputs_run(jit, SEED, test_val, test_buffers, expect_match=True) + random_inputs_run(jit, SEED+1, test_val, test_buffers, expect_match=False) + return jit + + +def _parse_size(s): + w, h = s.lower().split('x') + return int(w), int(h) + + +def read_file_chunked_to_shm(path): + from openpilot.common.file_chunker import read_file_chunked + from openpilot.system.hardware.hw import Paths + shm_path = os.path.join(Paths.shm_path(), os.path.basename(path)) + atexit.register(lambda: os.path.exists(shm_path) and os.remove(shm_path)) + with open(shm_path, 'wb') as f: + f.write(read_file_chunked(path)) + return shm_path + + +if __name__ == "__main__": + from tinygrad.nn.onnx import OnnxRunner + from openpilot.system.camerad.cameras.nv12_info import get_nv12_info + from openpilot.selfdrive.modeld.get_model_metadata import make_metadata_dict + p = argparse.ArgumentParser() + p.add_argument('--model-size', type=_parse_size, required=True, help='model input WxH') + p.add_argument('--camera-resolutions', type=_parse_size, nargs='+', required=True, + help='camera resolutions WxH (one or more)') + p.add_argument('--vision-onnx', required=True) + p.add_argument('--policy-onnx', required=True) + p.add_argument('--output', required=True) + p.add_argument('--frame-skip', type=int, required=True) + args = p.parse_args() + + out = defaultdict(dict) + vision_path, policy_path = read_file_chunked_to_shm(args.vision_onnx), read_file_chunked_to_shm(args.policy_onnx) + model_w, model_h = args.model_size + + vision_runner = OnnxRunner(vision_path) + policy_runner = OnnxRunner(policy_path) + vision_metadata, policy_metadata = make_metadata_dict(vision_path), make_metadata_dict(policy_path) + + run_policy_jit = TinyJit(make_run_policy(vision_runner, policy_runner, vision_metadata['output_slices']['hidden_state'], args.frame_skip), prune=True) + + out['metadata']['vision'], out['metadata']['policy'] = vision_metadata, policy_metadata + + make_random_model_inputs = partial(make_random_images, keys=['img', 'big_img'], shape=vision_metadata['input_shapes']['img']) + out['run_policy'] = compile_jit(run_policy_jit, make_random_model_inputs, POLICY_INPUTS, args.frame_skip, vision_metadata, policy_metadata) + + for cam_w, cam_h in args.camera_resolutions: + nv12 = NV12Frame(cam_w, cam_h, *get_nv12_info(cam_w, cam_h)) + make_random_warp_inputs = partial(make_random_images, keys=['frame', 'big_frame'], shape=nv12.size, device=WARP_DEV) + warp_enqueue = TinyJit(make_warp(nv12, model_w, model_h, args.frame_skip), prune=True) + out[(cam_w,cam_h)] = compile_jit(warp_enqueue, make_random_warp_inputs, WARP_INPUTS, args.frame_skip, vision_metadata, policy_metadata) + + with open(args.output, "wb") as f: + pickle.dump(out, f) + print(f"Saved JITs to {args.output} ({os.path.getsize(args.output) / 1e6:.2f} MB)") diff --git a/selfdrive/modeld/constants.py b/selfdrive/modeld/constants.py index 4d2888d231b6a3..ff7e1d86006e83 100644 --- a/selfdrive/modeld/constants.py +++ b/selfdrive/modeld/constants.py @@ -13,9 +13,12 @@ class ModelConstants: META_T_IDXS = [2., 4., 6., 8., 10.] # model inputs constants - MODEL_FREQ = 20 + N_FRAMES = 2 + MODEL_RUN_FREQ = 20 + MODEL_CONTEXT_FREQ = 5 # "model_trained_fps" + FEATURE_LEN = 512 - HISTORY_BUFFER_LEN = 99 + DESIRE_LEN = 8 TRAFFIC_CONVENTION_LEN = 2 LAT_PLANNER_STATE_LEN = 4 @@ -31,7 +34,6 @@ class ModelConstants: DISENGAGE_WIDTH = 5 POSE_WIDTH = 6 WIDE_FROM_DEVICE_WIDTH = 3 - SIM_POSE_WIDTH = 6 LEAD_WIDTH = 4 LANE_LINES_WIDTH = 2 ROAD_EDGES_WIDTH = 2 @@ -72,14 +74,14 @@ class Plan: class Meta: ENGAGED = slice(0, 1) # next 2, 4, 6, 8, 10 seconds - GAS_DISENGAGE = slice(1, 41, 8) - BRAKE_DISENGAGE = slice(2, 41, 8) - STEER_OVERRIDE = slice(3, 41, 8) - HARD_BRAKE_3 = slice(4, 41, 8) - HARD_BRAKE_4 = slice(5, 41, 8) - HARD_BRAKE_5 = slice(6, 41, 8) - GAS_PRESS = slice(7, 41, 8) - BRAKE_PRESS = slice(8, 41, 8) + GAS_DISENGAGE = slice(1, 31, 6) + BRAKE_DISENGAGE = slice(2, 31, 6) + STEER_OVERRIDE = slice(3, 31, 6) + HARD_BRAKE_3 = slice(4, 31, 6) + HARD_BRAKE_4 = slice(5, 31, 6) + HARD_BRAKE_5 = slice(6, 31, 6) # next 0, 2, 4, 6, 8, 10 seconds - LEFT_BLINKER = slice(41, 53, 2) - RIGHT_BLINKER = slice(42, 53, 2) + GAS_PRESS = slice(31, 55, 4) + BRAKE_PRESS = slice(32, 55, 4) + LEFT_BLINKER = slice(33, 55, 4) + RIGHT_BLINKER = slice(34, 55, 4) diff --git a/selfdrive/modeld/dmonitoringmodeld.py b/selfdrive/modeld/dmonitoringmodeld.py index a388bf089cb9b9..eaf423e7beaa09 100755 --- a/selfdrive/modeld/dmonitoringmodeld.py +++ b/selfdrive/modeld/dmonitoringmodeld.py @@ -1,125 +1,113 @@ #!/usr/bin/env python3 import os -import gc -import math +from openpilot.selfdrive.modeld.helpers import MODELS_DIR, get_tg_input_devices +from tinygrad.tensor import Tensor import time -import ctypes +import pickle import numpy as np -from pathlib import Path from cereal import messaging from cereal.messaging import PubMaster, SubMaster from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf from openpilot.common.swaglog import cloudlog -from openpilot.common.params import Params -from openpilot.common.realtime import set_realtime_priority -from openpilot.selfdrive.modeld.runners import ModelRunner, Runtime -from openpilot.selfdrive.modeld.models.commonmodel_pyx import sigmoid - -CALIB_LEN = 3 -REG_SCALE = 0.25 -MODEL_WIDTH = 1440 -MODEL_HEIGHT = 960 -OUTPUT_SIZE = 84 +from openpilot.common.realtime import config_realtime_process +from openpilot.common.transformations.model import dmonitoringmodel_intrinsics +from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info +from openpilot.common.file_chunker import read_file_chunked +from openpilot.selfdrive.modeld.parse_model_outputs import sigmoid, safe_exp + +PROCESS_NAME = "selfdrive.modeld.dmonitoringmodeld" SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') -MODEL_PATHS = { - ModelRunner.SNPE: Path(__file__).parent / 'models/dmonitoring_model_q.dlc', - ModelRunner.ONNX: Path(__file__).parent / 'models/dmonitoring_model.onnx'} - -class DriverStateResult(ctypes.Structure): - _fields_ = [ - ("face_orientation", ctypes.c_float*3), - ("face_position", ctypes.c_float*3), - ("face_orientation_std", ctypes.c_float*3), - ("face_position_std", ctypes.c_float*3), - ("face_prob", ctypes.c_float), - ("_unused_a", ctypes.c_float*8), - ("left_eye_prob", ctypes.c_float), - ("_unused_b", ctypes.c_float*8), - ("right_eye_prob", ctypes.c_float), - ("left_blink_prob", ctypes.c_float), - ("right_blink_prob", ctypes.c_float), - ("sunglasses_prob", ctypes.c_float), - ("occluded_prob", ctypes.c_float), - ("ready_prob", ctypes.c_float*4), - ("not_ready_prob", ctypes.c_float*2)] - -class DMonitoringModelResult(ctypes.Structure): - _fields_ = [ - ("driver_state_lhd", DriverStateResult), - ("driver_state_rhd", DriverStateResult), - ("poor_vision_prob", ctypes.c_float), - ("wheel_on_right_prob", ctypes.c_float)] +MODEL_PKL_PATH = MODELS_DIR / 'dmonitoring_model_tinygrad.pkl' +METADATA_PATH = MODELS_DIR / 'dmonitoring_model_metadata.pkl' + class ModelState: inputs: dict[str, np.ndarray] output: np.ndarray - model: ModelRunner - def __init__(self): - assert ctypes.sizeof(DMonitoringModelResult) == OUTPUT_SIZE * ctypes.sizeof(ctypes.c_float) - self.output = np.zeros(OUTPUT_SIZE, dtype=np.float32) - self.inputs = { - 'input_img': np.zeros(MODEL_HEIGHT * MODEL_WIDTH, dtype=np.uint8), - 'calib': np.zeros(CALIB_LEN, dtype=np.float32)} + def __init__(self, cam_w: int, cam_h: int): + self.DEV = get_tg_input_devices(PROCESS_NAME, usbgpu=False)['DEV'] + with open(METADATA_PATH, 'rb') as f: + model_metadata = pickle.load(f) + self.input_shapes = model_metadata['input_shapes'] + self.output_slices = model_metadata['output_slices'] + + self.numpy_inputs = { + 'calib': np.zeros(self.input_shapes['calib'], dtype=np.float32), + } + + self.warp_inputs_np = {'transform': np.zeros((3,3), dtype=np.float32)} + self.warp_inputs = {k: Tensor(v, device='NPY') for k,v in self.warp_inputs_np.items()} + self.frame_buf_params = get_nv12_info(cam_w, cam_h) + self.tensor_inputs = {k: Tensor(v, device='NPY').realize() for k,v in self.numpy_inputs.items()} + self._blob_cache : dict[int, Tensor] = {} + self.model_run = pickle.loads(read_file_chunked(str(MODEL_PKL_PATH))) + with open(MODELS_DIR / f'dm_warp_{cam_w}x{cam_h}_tinygrad.pkl', "rb") as f: + self.image_warp = pickle.load(f) + + def run(self, buf: VisionBuf, calib: np.ndarray, transform: np.ndarray) -> tuple[np.ndarray, float]: + self.numpy_inputs['calib'][0,:] = calib - self.model = ModelRunner(MODEL_PATHS, self.output, Runtime.DSP, True, None) - self.model.addInput("input_img", None) - self.model.addInput("calib", self.inputs['calib']) + t1 = time.perf_counter() - def run(self, buf:VisionBuf, calib:np.ndarray) -> tuple[np.ndarray, float]: - self.inputs['calib'][:] = calib + ptr = np.frombuffer(buf.data, dtype=np.uint8).ctypes.data + # There is a ringbuffer of imgs, just cache tensors pointing to all of them + if ptr not in self._blob_cache: + self._blob_cache[ptr] = Tensor.from_blob(ptr, (self.frame_buf_params[3],), dtype='uint8', device=self.DEV) - v_offset = buf.height - MODEL_HEIGHT - h_offset = (buf.width - MODEL_WIDTH) // 2 - buf_data = buf.data.reshape(-1, buf.stride) - input_data = self.inputs['input_img'].reshape(MODEL_HEIGHT, MODEL_WIDTH) - input_data[:] = buf_data[v_offset:v_offset+MODEL_HEIGHT, h_offset:h_offset+MODEL_WIDTH] + self.warp_inputs_np['transform'][:] = transform[:] + self.tensor_inputs['input_img'] = self.image_warp(self._blob_cache[ptr], self.warp_inputs['transform']) + + output = self.model_run(**self.tensor_inputs).numpy().flatten() - t1 = time.perf_counter() - self.model.setInputBuffer("input_img", self.inputs['input_img'].view(np.float32)) - self.model.execute() t2 = time.perf_counter() - return self.output, t2 - t1 - - -def fill_driver_state(msg, ds_result: DriverStateResult): - msg.faceOrientation = [x * REG_SCALE for x in ds_result.face_orientation] - msg.faceOrientationStd = [math.exp(x) for x in ds_result.face_orientation_std] - msg.facePosition = [x * REG_SCALE for x in ds_result.face_position[:2]] - msg.facePositionStd = [math.exp(x) for x in ds_result.face_position_std[:2]] - msg.faceProb = sigmoid(ds_result.face_prob) - msg.leftEyeProb = sigmoid(ds_result.left_eye_prob) - msg.rightEyeProb = sigmoid(ds_result.right_eye_prob) - msg.leftBlinkProb = sigmoid(ds_result.left_blink_prob) - msg.rightBlinkProb = sigmoid(ds_result.right_blink_prob) - msg.sunglassesProb = sigmoid(ds_result.sunglasses_prob) - msg.occludedProb = sigmoid(ds_result.occluded_prob) - msg.readyProb = [sigmoid(x) for x in ds_result.ready_prob] - msg.notReadyProb = [sigmoid(x) for x in ds_result.not_ready_prob] - -def get_driverstate_packet(model_output: np.ndarray, frame_id: int, location_ts: int, execution_time: float, dsp_execution_time: float): - model_result = ctypes.cast(model_output.ctypes.data, ctypes.POINTER(DMonitoringModelResult)).contents + return output, t2 - t1 + +def slice_outputs(model_outputs, output_slices): + return {k: model_outputs[np.newaxis, v] for k,v in output_slices.items()} + +def parse_model_output(model_output): + parsed = {} + parsed['wheel_on_right'] = sigmoid(model_output['wheel_on_right']) + for ds_suffix in ['lhd', 'rhd']: + face_descs = model_output[f'face_descs_{ds_suffix}'] + parsed[f'face_descs_{ds_suffix}'] = face_descs[:, :-6] + parsed[f'face_descs_{ds_suffix}_std'] = safe_exp(face_descs[:, -6:]) + for key in ['face_prob', 'left_eye_prob', 'right_eye_prob','left_blink_prob', 'right_blink_prob', 'sunglasses_prob', 'using_phone_prob', 'sleep_prob']: + parsed[f'{key}_{ds_suffix}'] = sigmoid(model_output[f'{key}_{ds_suffix}']) + return parsed + +def fill_driver_data(msg, model_output, ds_suffix): + msg.faceOrientation = model_output[f'face_descs_{ds_suffix}'][0, :3].tolist() + msg.faceOrientationStd = model_output[f'face_descs_{ds_suffix}_std'][0, :3].tolist() + msg.facePosition = model_output[f'face_descs_{ds_suffix}'][0, 3:5].tolist() + msg.facePositionStd = model_output[f'face_descs_{ds_suffix}_std'][0, 3:5].tolist() + msg.faceProb = model_output[f'face_prob_{ds_suffix}'][0, 0].item() + msg.leftEyeProb = model_output[f'left_eye_prob_{ds_suffix}'][0, 0].item() + msg.rightEyeProb = model_output[f'right_eye_prob_{ds_suffix}'][0, 0].item() + msg.leftBlinkProb = model_output[f'left_blink_prob_{ds_suffix}'][0, 0].item() + msg.rightBlinkProb = model_output[f'right_blink_prob_{ds_suffix}'][0, 0].item() + msg.sunglassesProb = model_output[f'sunglasses_prob_{ds_suffix}'][0, 0].item() + msg.phoneProb = model_output[f'using_phone_prob_{ds_suffix}'][0, 0].item() + msg.sleepProb = model_output[f'sleep_prob_{ds_suffix}'][0, 0].item() + +def get_driverstate_packet(model_output, frame_id: int, location_ts: int, exec_time: float, gpu_exec_time: float): msg = messaging.new_message('driverStateV2', valid=True) ds = msg.driverStateV2 ds.frameId = frame_id - ds.modelExecutionTime = execution_time - ds.dspExecutionTime = dsp_execution_time - ds.poorVisionProb = sigmoid(model_result.poor_vision_prob) - ds.wheelOnRightProb = sigmoid(model_result.wheel_on_right_prob) - ds.rawPredictions = model_output.tobytes() if SEND_RAW_PRED else b'' - fill_driver_state(ds.leftDriverData, model_result.driver_state_lhd) - fill_driver_state(ds.rightDriverData, model_result.driver_state_rhd) + ds.modelExecutionTime = exec_time + ds.gpuExecutionTime = gpu_exec_time + ds.rawPredictions = model_output['raw_pred'] + ds.wheelOnRightProb = model_output['wheel_on_right'][0, 0].item() + fill_driver_data(ds.leftDriverData, model_output, 'lhd') + fill_driver_data(ds.rightDriverData, model_output, 'rhd') return msg def main(): - gc.disable() - set_realtime_priority(1) - - model = ModelState() - cloudlog.warning("models loaded, dmonitoringmodeld starting") - Params().put_bool("DmModelInitialized", True) + config_realtime_process(7, 5) cloudlog.warning("connecting to driver stream") vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_DRIVER, True) @@ -128,29 +116,41 @@ def main(): assert vipc_client.is_connected() cloudlog.warning(f"connected with buffer size: {vipc_client.buffer_len}") + model = ModelState(vipc_client.width, vipc_client.height) + cloudlog.warning("models loaded, dmonitoringmodeld starting") + sm = SubMaster(["liveCalibration"]) pm = PubMaster(["driverStateV2"]) - calib = np.zeros(CALIB_LEN, dtype=np.float32) - # last = 0 + calib = np.zeros(model.numpy_inputs['calib'].size, dtype=np.float32) + model_transform = None while True: buf = vipc_client.recv() if buf is None: continue + if model_transform is None: + cam = _os_fisheye if buf.width == _os_fisheye.width else _ar_ox_fisheye + model_transform = np.linalg.inv(np.dot(dmonitoringmodel_intrinsics, np.linalg.inv(cam.intrinsics))).astype(np.float32) + sm.update(0) if sm.updated["liveCalibration"]: calib[:] = np.array(sm["liveCalibration"].rpyCalib) t1 = time.perf_counter() - model_output, dsp_execution_time = model.run(buf, calib) + model_output, gpu_execution_time = model.run(buf, calib, model_transform) t2 = time.perf_counter() - - pm.send("driverStateV2", get_driverstate_packet(model_output, vipc_client.frame_id, vipc_client.timestamp_sof, t2 - t1, dsp_execution_time)) - # print("dmonitoring process: %.2fms, from last %.2fms\n" % (t2 - t1, t1 - last)) - # last = t1 + raw_pred = model_output.tobytes() if SEND_RAW_PRED else b'' + model_output = slice_outputs(model_output, model.output_slices) + model_output = parse_model_output(model_output) + model_output['raw_pred'] = raw_pred + msg = get_driverstate_packet(model_output, vipc_client.frame_id, vipc_client.timestamp_sof, t2 - t1, gpu_execution_time) + pm.send("driverStateV2", msg) if __name__ == "__main__": - main() + try: + main() + except KeyboardInterrupt: + cloudlog.warning("got SIGINT") diff --git a/selfdrive/modeld/fill_model_msg.py b/selfdrive/modeld/fill_model_msg.py index 1c7ae495809981..82c4c92b1d53c7 100644 --- a/selfdrive/modeld/fill_model_msg.py +++ b/selfdrive/modeld/fill_model_msg.py @@ -8,6 +8,7 @@ ConfidenceClass = log.ModelDataV2.ConfidenceClass + class PublishState: def __init__(self): self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32) @@ -48,10 +49,17 @@ def fill_xyz_poly(builder, degree, x, y, z): builder.yCoefficients = coeffs[:, 1].tolist() builder.zCoefficients = coeffs[:, 2].tolist() +def fill_lane_line_meta(builder, lane_lines, lane_line_probs): + builder.leftY = lane_lines[1].y[0] + builder.leftProb = lane_line_probs[1] + builder.rightY = lane_lines[2].y[0] + builder.rightProb = lane_line_probs[2] + def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._DynamicStructBuilder, - net_output_data: dict[str, np.ndarray], publish_state: PublishState, - vipc_frame_id: int, vipc_frame_id_extra: int, frame_id: int, frame_drop: float, - timestamp_eof: int, model_execution_time: float, valid: bool) -> None: + net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action, + publish_state: PublishState, vipc_frame_id: int, vipc_frame_id_extra: int, + frame_id: int, frame_drop: float, timestamp_eof: int, model_execution_time: float, + valid: bool) -> None: frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0 frame_drop_perc = frame_drop * 100 extended_msg.valid = valid @@ -62,9 +70,9 @@ def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._D driving_model_data.frameId = vipc_frame_id driving_model_data.frameIdExtra = vipc_frame_id_extra driving_model_data.frameDropPerc = frame_drop_perc + driving_model_data.modelExecutionTime = model_execution_time - action = driving_model_data.action - action.desiredCurvature = float(net_output_data['desired_curvature'][0,0]) + driving_model_data.action = action modelV2 = extended_msg.modelV2 modelV2.frameId = vipc_frame_id @@ -75,63 +83,36 @@ def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._D modelV2.modelExecutionTime = model_execution_time # plan - position = modelV2.position - fill_xyzt(position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T) - velocity = modelV2.velocity - fill_xyzt(velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T) - acceleration = modelV2.acceleration - fill_xyzt(acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T) - orientation = modelV2.orientation - fill_xyzt(orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T) - orientation_rate = modelV2.orientationRate - fill_xyzt(orientation_rate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T) + fill_xyzt(modelV2.position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T) + fill_xyzt(modelV2.velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T) + fill_xyzt(modelV2.acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T) + fill_xyzt(modelV2.orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T) + fill_xyzt(modelV2.orientationRate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T) # poly path - poly_path = driving_model_data.path - fill_xyz_poly(poly_path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T) - - # lateral planning - action = modelV2.action - action.desiredCurvature = float(net_output_data['desired_curvature'][0,0]) - - # times at X_IDXS according to model plan - PLAN_T_IDXS = [np.nan] * ModelConstants.IDX_N - PLAN_T_IDXS[0] = 0.0 - plan_x = net_output_data['plan'][0,:,Plan.POSITION][:,0].tolist() - for xidx in range(1, ModelConstants.IDX_N): - tidx = 0 - # increment tidx until we find an element that's further away than the current xidx - while tidx < ModelConstants.IDX_N - 1 and plan_x[tidx+1] < ModelConstants.X_IDXS[xidx]: - tidx += 1 - if tidx == ModelConstants.IDX_N - 1: - # if the Plan doesn't extend far enough, set plan_t to the max value (10s), then break - PLAN_T_IDXS[xidx] = ModelConstants.T_IDXS[ModelConstants.IDX_N - 1] - break - # interpolate to find `t` for the current xidx - current_x_val = plan_x[tidx] - next_x_val = plan_x[tidx+1] - p = (ModelConstants.X_IDXS[xidx] - current_x_val) / (next_x_val - current_x_val) if abs(next_x_val - current_x_val) > 1e-9 else float('nan') - PLAN_T_IDXS[xidx] = p * ModelConstants.T_IDXS[tidx+1] + (1 - p) * ModelConstants.T_IDXS[tidx] + fill_xyz_poly(driving_model_data.path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T) + + # action + modelV2.action = action + + # times at X_IDXS of edges and lines aren't used + LINE_T_IDXS: list[float] = [] # lane lines modelV2.init('laneLines', 4) for i in range(4): lane_line = modelV2.laneLines[i] - fill_xyzt(lane_line, PLAN_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1]) + fill_xyzt(lane_line, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1]) modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist() modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist() - lane_line_meta = driving_model_data.laneLineMeta - lane_line_meta.leftY = modelV2.laneLines[1].y[0] - lane_line_meta.leftProb = modelV2.laneLineProbs[1] - lane_line_meta.rightY = modelV2.laneLines[2].y[0] - lane_line_meta.rightProb = modelV2.laneLineProbs[2] + fill_lane_line_meta(driving_model_data.laneLineMeta, modelV2.laneLines, modelV2.laneLineProbs) # road edges modelV2.init('roadEdges', 2) for i in range(2): road_edge = modelV2.roadEdges[i] - fill_xyzt(road_edge, PLAN_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1]) + fill_xyzt(road_edge, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1]) modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist() # leads @@ -167,15 +148,8 @@ def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._D (publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all() meta.hardBrakePredicted = hard_brake_predicted.item() - # temporal pose - temporal_pose = modelV2.temporalPose - temporal_pose.trans = net_output_data['sim_pose'][0,:3].tolist() - temporal_pose.transStd = net_output_data['sim_pose_stds'][0,:3].tolist() - temporal_pose.rot = net_output_data['sim_pose'][0,3:].tolist() - temporal_pose.rotStd = net_output_data['sim_pose_stds'][0,3:].tolist() - # confidence - if vipc_frame_id % (2*ModelConstants.MODEL_FREQ) == 0: + if vipc_frame_id % (2*ModelConstants.MODEL_RUN_FREQ) == 0: # any disengage prob brake_disengage_probs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE] gas_disengage_probs = net_output_data['meta'][0,Meta.GAS_DISENGAGE] diff --git a/selfdrive/modeld/get_model_metadata.py b/selfdrive/modeld/get_model_metadata.py index 144860204fd79c..e4c173957a7cf2 100755 --- a/selfdrive/modeld/get_model_metadata.py +++ b/selfdrive/modeld/get_model_metadata.py @@ -1,28 +1,55 @@ #!/usr/bin/env python3 import sys import pathlib -import onnx import codecs import pickle +from typing import Any -def get_name_and_shape(value_info:onnx.ValueInfoProto) -> tuple[str, tuple[int,...]]: - shape = tuple([int(dim.dim_value) for dim in value_info.type.tensor_type.shape.dim]) - name = value_info.name +from tinygrad.nn.onnx import OnnxPBParser + + +class MetadataOnnxPBParser(OnnxPBParser): + def _parse_ModelProto(self) -> dict: + obj: dict[str, Any] = {"graph": {"input": [], "output": []}, "metadata_props": []} + for fid, wire_type in self._parse_message(self.reader.len): + match fid: + case 7: + obj["graph"] = self._parse_GraphProto() + case 14: + obj["metadata_props"].append(self._parse_StringStringEntryProto()) + case _: + self.reader.skip_field(wire_type) + return obj + + +def get_name_and_shape(value_info: dict[str, Any]) -> tuple[str, tuple[int, ...]]: + shape = tuple(int(dim) if isinstance(dim, int) else 0 for dim in value_info["parsed_type"].shape) + name = value_info["name"] return name, shape -if __name__ == "__main__": - model_path = pathlib.Path(sys.argv[1]) - model = onnx.load(str(model_path)) - i = [x.key for x in model.metadata_props].index('output_slices') - output_slices = model.metadata_props[i].value - metadata = {} - metadata['output_slices'] = pickle.loads(codecs.decode(output_slices.encode(), "base64")) - metadata['input_shapes'] = dict([get_name_and_shape(x) for x in model.graph.input]) - metadata['output_shapes'] = dict([get_name_and_shape(x) for x in model.graph.output]) +def get_metadata_value_by_name(model: dict[str, Any], name: str) -> str | Any: + for prop in model["metadata_props"]: + if prop["key"] == name: + return prop["value"] + return None + +def make_metadata_dict(model_path): + model = MetadataOnnxPBParser(model_path).parse() + output_slices = get_metadata_value_by_name(model, 'output_slices') + assert output_slices is not None, 'output_slices not found in metadata' + return { + 'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'), + 'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")), + 'input_shapes': dict(get_name_and_shape(x) for x in model["graph"]["input"]), + 'output_shapes': dict(get_name_and_shape(x) for x in model["graph"]["output"]), + } + + +if __name__ == "__main__": + model_path = pathlib.Path(sys.argv[1]) metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl') with open(metadata_path, 'wb') as f: - pickle.dump(metadata, f) - + pickle.dump(make_metadata_dict(model_path), f) print(f'saved metadata to {metadata_path}') diff --git a/selfdrive/modeld/helpers.py b/selfdrive/modeld/helpers.py new file mode 100644 index 00000000000000..64bf28873f1d89 --- /dev/null +++ b/selfdrive/modeld/helpers.py @@ -0,0 +1,26 @@ +import json +from pathlib import Path + +MODELS_DIR = Path(__file__).resolve().parent / 'models' +TG_INPUT_DEVICES_PATH = MODELS_DIR / 'tg_input_devices.json' +USBGPU_VID = 0xADD1 +USBGPU_PID = 0x0001 + + +def get_tg_input_devices(process_name: str, usbgpu: bool): + with open(TG_INPUT_DEVICES_PATH) as f: + return json.load(f)[process_name]['default' if not usbgpu else 'usbgpu'] + +def modeld_pkl_path(usbgpu: bool): + prefix = 'big_' if usbgpu else '' + return MODELS_DIR / f'{prefix}driving_tinygrad.pkl' + +def usbgpu_present() -> bool: + for d in Path("/sys/bus/usb/devices").glob("*"): + try: + if int((d / "idVendor").read_text(), 16) == USBGPU_VID and \ + int((d / "idProduct").read_text(), 16) == USBGPU_PID: + return True + except Exception: + pass + return False diff --git a/selfdrive/modeld/modeld b/selfdrive/modeld/modeld deleted file mode 100755 index e1cef4dcc35f18..00000000000000 --- a/selfdrive/modeld/modeld +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -cd "$DIR/../../" - -if [ -f "$DIR/libthneed.so" ]; then - export LD_PRELOAD="$DIR/libthneed.so" -fi - -exec "$DIR/modeld.py" "$@" diff --git a/selfdrive/modeld/modeld.py b/selfdrive/modeld/modeld.py old mode 100755 new mode 100644 index 86813fcb8ecd66..c1663da351deda --- a/selfdrive/modeld/modeld.py +++ b/selfdrive/modeld/modeld.py @@ -1,38 +1,70 @@ #!/usr/bin/env python3 import os +os.environ['GMMU'] = '0' # for usbgpu fast loading, noop for qcom +from tinygrad.tensor import Tensor import time import pickle import numpy as np import cereal.messaging as messaging from cereal import car, log -from pathlib import Path -from setproctitle import setproctitle from cereal.messaging import PubMaster, SubMaster from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf from opendbc.car.car_helpers import get_demo_car_params from openpilot.common.swaglog import cloudlog from openpilot.common.params import Params from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.realtime import config_realtime_process +from openpilot.common.realtime import config_realtime_process, DT_MDL from openpilot.common.transformations.camera import DEVICE_CAMERAS +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info from openpilot.common.transformations.model import get_warp_matrix -from openpilot.system import sentry -from openpilot.selfdrive.car.card import convert_to_capnp from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper -from openpilot.selfdrive.modeld.runners import ModelRunner, Runtime +from openpilot.selfdrive.controls.lib.stalk_tip_turn import PARAM_RING_LATCHED +from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value, MIN_STABLE_DELAY from openpilot.selfdrive.modeld.parse_model_outputs import Parser +from openpilot.selfdrive.modeld.compile_modeld import make_input_queues, WARP_INPUTS, POLICY_INPUTS from openpilot.selfdrive.modeld.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState -from openpilot.selfdrive.modeld.constants import ModelConstants -from openpilot.selfdrive.modeld.models.commonmodel_pyx import ModelFrame, CLContext +from openpilot.common.file_chunker import read_file_chunked, get_manifest_path +from openpilot.selfdrive.modeld.constants import ModelConstants, Plan +from openpilot.selfdrive.modeld.helpers import usbgpu_present, modeld_pkl_path, get_tg_input_devices +from openpilot.selfdrive.controls.lib.lat_turn_geometry import ( + PARAM_REF_OFFSET, PARAM_TURN_GEOMETRY, PARAM_TURN_IN_DELAY, TurnGeometryCorrection, clamp_ref_offset, + clamp_turn_in_step, is_preap_car, plan_curvature, +) + PROCESS_NAME = "selfdrive.modeld.modeld" SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') -MODEL_PATHS = { - ModelRunner.THNEED: Path(__file__).parent / 'models/supercombo.thneed', - ModelRunner.ONNX: Path(__file__).parent / 'models/supercombo.onnx'} +LAT_SMOOTH_SECONDS = 0.0 +LONG_SMOOTH_SECONDS = 0.3 +MIN_LAT_CONTROL_SPEED = 0.3 + + + +def get_action_from_model(model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action, + lat_action_t: float, long_action_t: float, v_ego: float, + lat_sample_floor_s: float = MIN_STABLE_DELAY) -> log.ModelDataV2.Action: + plan = model_output['plan'][0] + desired_accel, should_stop = get_accel_from_plan(plan[:,Plan.VELOCITY][:,0], + plan[:,Plan.ACCELERATION][:,0], + ModelConstants.T_IDXS, + action_t=long_action_t) + desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, LONG_SMOOTH_SECONDS) + + desired_curvature = plan_curvature(plan[:,Plan.T_FROM_CURRENT_EULER][:,2], + plan[:,Plan.ORIENTATION_RATE][:,2], + ModelConstants.T_IDXS, + v_ego, + lat_action_t, + lat_sample_floor_s) + if v_ego > MIN_LAT_CONTROL_SPEED: + desired_curvature = smooth_value(desired_curvature, prev_action.desiredCurvature, LAT_SMOOTH_SECONDS) + else: + desired_curvature = prev_action.desiredCurvature -METADATA_PATH = Path(__file__).parent / 'models/supercombo_metadata.pkl' + return log.ModelDataV2.Action(desiredCurvature=float(desired_curvature), + desiredAcceleration=float(desired_accel), + shouldStop=bool(should_stop)) class FrameMeta: frame_id: int = 0 @@ -43,88 +75,91 @@ def __init__(self, vipc=None): if vipc is not None: self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof + class ModelState: - frame: ModelFrame - wide_frame: ModelFrame - inputs: dict[str, np.ndarray] - output: np.ndarray prev_desire: np.ndarray # for tracking the rising edge of the pulse - model: ModelRunner - def __init__(self, context: CLContext): - self.frame = ModelFrame(context) - self.wide_frame = ModelFrame(context) - self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32) - self.inputs = { - 'desire': np.zeros(ModelConstants.DESIRE_LEN * (ModelConstants.HISTORY_BUFFER_LEN+1), dtype=np.float32), - 'traffic_convention': np.zeros(ModelConstants.TRAFFIC_CONVENTION_LEN, dtype=np.float32), - 'lateral_control_params': np.zeros(ModelConstants.LATERAL_CONTROL_PARAMS_LEN, dtype=np.float32), - 'prev_desired_curv': np.zeros(ModelConstants.PREV_DESIRED_CURV_LEN * (ModelConstants.HISTORY_BUFFER_LEN+1), dtype=np.float32), - 'features_buffer': np.zeros(ModelConstants.HISTORY_BUFFER_LEN * ModelConstants.FEATURE_LEN, dtype=np.float32), - } + def __init__(self, cam_w: int, cam_h: int, usbgpu: bool): + input_devices = get_tg_input_devices(PROCESS_NAME, usbgpu) + self.WARP_DEV, self.QUEUE_DEV = input_devices['WARP_DEV'], input_devices['QUEUE_DEV'] + jits = pickle.loads(read_file_chunked(modeld_pkl_path(usbgpu))) + vision_metadata = jits['metadata']['vision'] + self.vision_input_shapes = vision_metadata['input_shapes'] + self.vision_input_names = list(self.vision_input_shapes.keys()) + self.vision_output_slices = vision_metadata['output_slices'] - with open(METADATA_PATH, 'rb') as f: - model_metadata = pickle.load(f) + policy_metadata = jits['metadata']['policy'] + self.policy_input_shapes = policy_metadata['input_shapes'] + self.policy_output_slices = policy_metadata['output_slices'] - self.output_slices = model_metadata['output_slices'] - net_output_size = model_metadata['output_shapes']['outputs'][1] - self.output = np.zeros(net_output_size, dtype=np.float32) - self.parser = Parser() + self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32) - self.model = ModelRunner(MODEL_PATHS, self.output, Runtime.GPU, False, context) - self.model.addInput("input_imgs", None) - self.model.addInput("big_input_imgs", None) - for k,v in self.inputs.items(): - self.model.addInput(k, v) + self.frame_skip = ModelConstants.MODEL_RUN_FREQ // ModelConstants.MODEL_CONTEXT_FREQ + self.input_queues, self.npy = make_input_queues(self.vision_input_shapes, self.policy_input_shapes, self.frame_skip, device=self.QUEUE_DEV) + self.full_frames : dict[str, Tensor] = {} + self._blob_cache : dict[int, Tensor] = {} + self.parser = Parser() + self.frame_buf_params = {k: get_nv12_info(cam_w, cam_h) for k in ('img', 'big_img')} + self.run_policy = jits['run_policy'] + self.warp_enqueue = jits[(cam_w,cam_h)] - def slice_outputs(self, model_outputs: np.ndarray) -> dict[str, np.ndarray]: - parsed_model_outputs = {k: model_outputs[np.newaxis, v] for k,v in self.output_slices.items()} - if SEND_RAW_PRED: - parsed_model_outputs['raw_pred'] = model_outputs.copy() + def slice_outputs(self, model_outputs: np.ndarray, output_slices: dict[str, slice]) -> dict[str, np.ndarray]: + parsed_model_outputs = {k: model_outputs[np.newaxis, v] for k,v in output_slices.items()} return parsed_model_outputs - def run(self, buf: VisionBuf, wbuf: VisionBuf, transform: np.ndarray, transform_wide: np.ndarray, + def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray], inputs: dict[str, np.ndarray], prepare_only: bool) -> dict[str, np.ndarray] | None: - # Model decides when action is completed, so desire input is just a pulse triggered on rising edge - inputs['desire'][0] = 0 - self.inputs['desire'][:-ModelConstants.DESIRE_LEN] = self.inputs['desire'][ModelConstants.DESIRE_LEN:] - self.inputs['desire'][-ModelConstants.DESIRE_LEN:] = np.where(inputs['desire'] - self.prev_desire > .99, inputs['desire'], 0) - self.prev_desire[:] = inputs['desire'] + for key in bufs.keys(): + ptr = np.frombuffer(bufs[key].data, dtype=np.uint8).ctypes.data + yuv_size = self.frame_buf_params[key][3] + # There is a ringbuffer of imgs, just cache tensors pointing to all of them + cache_key = (key, ptr) + if cache_key not in self._blob_cache: + self._blob_cache[cache_key] = Tensor.from_blob(ptr, (yuv_size,), dtype='uint8', device=self.WARP_DEV) + self.full_frames[key] = self._blob_cache[cache_key] - self.inputs['traffic_convention'][:] = inputs['traffic_convention'] - self.inputs['lateral_control_params'][:] = inputs['lateral_control_params'] + # Model decides when action is completed, so desire input is just a pulse triggered on rising edge + inputs['desire_pulse'][0] = 0 + self.npy['desire'][:] = np.where(inputs['desire_pulse'] - self.prev_desire > .99, inputs['desire_pulse'], 0) + self.prev_desire[:] = inputs['desire_pulse'] + self.npy['traffic_convention'][:] = inputs['traffic_convention'] + self.npy['tfm'][:,:] = transforms['img'][:,:] + self.npy['big_tfm'][:,:] = transforms['big_img'][:,:] - # if getCLBuffer is not None, frame will be None - self.model.setInputBuffer("input_imgs", self.frame.prepare(buf, transform.flatten(), self.model.getCLBuffer("input_imgs"))) - if wbuf is not None: - self.model.setInputBuffer("big_input_imgs", self.wide_frame.prepare(wbuf, transform_wide.flatten(), self.model.getCLBuffer("big_input_imgs"))) + img, big_img = self.warp_enqueue(**{k: self.input_queues[k] for k in WARP_INPUTS}, frame=self.full_frames['img'], big_frame=self.full_frames['big_img']) if prepare_only: return None - self.model.execute() - outputs = self.parser.parse_outputs(self.slice_outputs(self.output)) + vision_output, policy_output = self.run_policy( + **{k: self.input_queues[k] for k in POLICY_INPUTS}, img=img, big_img=big_img + ) + + vision_output = vision_output.numpy().flatten() + policy_output = policy_output.numpy().flatten() + vision_outputs_dict = self.parser.parse_vision_outputs(self.slice_outputs(vision_output, self.vision_output_slices)) + policy_outputs_dict = self.parser.parse_policy_outputs(self.slice_outputs(policy_output, self.policy_output_slices)) + combined_outputs_dict = {**vision_outputs_dict, **policy_outputs_dict} - self.inputs['features_buffer'][:-ModelConstants.FEATURE_LEN] = self.inputs['features_buffer'][ModelConstants.FEATURE_LEN:] - self.inputs['features_buffer'][-ModelConstants.FEATURE_LEN:] = outputs['hidden_state'][0, :] - self.inputs['prev_desired_curv'][:-ModelConstants.PREV_DESIRED_CURV_LEN] = self.inputs['prev_desired_curv'][ModelConstants.PREV_DESIRED_CURV_LEN:] - self.inputs['prev_desired_curv'][-ModelConstants.PREV_DESIRED_CURV_LEN:] = outputs['desired_curvature'][0, :] - return outputs + if SEND_RAW_PRED: + combined_outputs_dict['raw_pred'] = np.concatenate([vision_output.copy(), policy_output.copy()]) + return combined_outputs_dict def main(demo=False): cloudlog.warning("modeld init") - sentry.set_tag("daemon", PROCESS_NAME) - cloudlog.bind(daemon=PROCESS_NAME) - setproctitle(PROCESS_NAME) - config_realtime_process(7, 54) + _present = usbgpu_present() + _compiled = os.path.isfile(get_manifest_path(modeld_pkl_path(usbgpu=True))) + USBGPU = _present and _compiled + params = Params() + params.put_bool("UsbGpuPresent", _present) + params.put_bool("UsbGpuCompiled", _compiled) - cloudlog.warning("setting up CL context") - cl_context = CLContext() - cloudlog.warning("CL context ready; loading model") - model = ModelState(cl_context) - cloudlog.warning("models loaded, modeld starting") + if not USBGPU: + # USB GPU currently saturates a core so can't do this yet, + # also need to move the aux USB interrupts for good timings + config_realtime_process(7, 54) # visionipc clients while True: @@ -136,8 +171,8 @@ def main(demo=False): time.sleep(.1) vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD - vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True, cl_context) - vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False, cl_context) + vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True) + vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False) cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}") while not vipc_client_main.connect(False): @@ -149,15 +184,21 @@ def main(demo=False): if use_extra_client: cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})") + st = time.monotonic() + cloudlog.warning("loading model") + model = ModelState(vipc_client_main.width, vipc_client_main.height, USBGPU) + cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting") + # messaging pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry"]) - sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl"]) + sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay", + "carOutput"]) publish_state = PublishState() params = Params() # setup filter to track dropped frames - frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_FREQ) + frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_RUN_FREQ) frame_id = 0 last_vipc_frame_id = 0 run_count = 0 @@ -171,14 +212,22 @@ def main(demo=False): if demo: - CP = convert_to_capnp(get_demo_car_params()) + CP = get_demo_car_params() else: CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) - - cloudlog.info("modeld got CarParams: %s", CP.carName) + cloudlog.info("modeld got CarParams: %s", CP.brand) # TODO this needs more thought, use .2s extra for now to estimate other delays - steer_delay = CP.steerActuatorDelay + .2 + # TODO Move smooth seconds to action function + long_delay = CP.longitudinalActuatorDelay + LONG_SMOOTH_SECONDS + # NAP turn geometry correction (Pre-AP only). Params re-read ~1 Hz. + turn_geom_preap = is_preap_car(CP) + turn_geom = TurnGeometryCorrection(DT_MDL) + turn_geom_on = False + turn_geom_offset = clamp_ref_offset(None) + turn_in_step = 0 + turn_geom_param_frame = -1 + prev_action = log.ModelDataV2.Action() DH = DesireHelper() @@ -219,7 +268,8 @@ def main(demo=False): desire = DH.desire is_rhd = sm["driverMonitoringState"].isRHD frame_id = sm["roadCameraState"].frameId - lateral_control_params = np.array([sm["carState"].vEgo, steer_delay], dtype=np.float32) + v_ego = max(sm["carState"].vEgo, 0.) + lat_delay = sm["liveDelay"].lateralDelay + LAT_SMOOTH_SECONDS if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']: device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32) dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] @@ -247,14 +297,15 @@ def main(demo=False): if prepare_only: cloudlog.error(f"skipping model eval. Dropped {vipc_dropped_frames} frames") + bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names} + transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names} inputs:dict[str, np.ndarray] = { - 'desire': vec_desire, + 'desire_pulse': vec_desire, 'traffic_convention': traffic_convention, - 'lateral_control_params': lateral_control_params, - } + } mt1 = time.perf_counter() - model_output = model.run(buf_main, buf_extra, model_transform_main, model_transform_extra, inputs, prepare_only) + model_output = model.run(bufs, transforms, inputs, prepare_only) mt2 = time.perf_counter() model_execution_time = mt2 - mt1 @@ -262,16 +313,46 @@ def main(demo=False): modelv2_send = messaging.new_message('modelV2') drivingdata_send = messaging.new_message('drivingModelData') posenet_send = messaging.new_message('cameraOdometry') - fill_model_msg(drivingdata_send, modelv2_send, model_output, publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id, + + frame_delay = DT_MDL # compensate for time passed since the frame was captured: current_time - timestamp_eof is 50ms on average + action_delay = DT_MDL / 2 # middle of the interval between model output (current state) and next frame (expected state) + lat_action_t = lat_delay + frame_delay + action_delay + lat_sample_floor_s = MIN_STABLE_DELAY + if turn_geom_preap: + if turn_geom_param_frame < 0 or run_count - turn_geom_param_frame >= ModelConstants.MODEL_RUN_FREQ: + turn_geom_param_frame = run_count + turn_geom_on = params.get_bool(PARAM_TURN_GEOMETRY) + turn_geom_offset = clamp_ref_offset(params.get(PARAM_REF_OFFSET, return_default=True)) + try: + turn_in_step = clamp_turn_in_step(params.get(PARAM_TURN_IN_DELAY, return_default=True)) + except Exception: + turn_in_step = 0 + lat_action_t = turn_geom.update( + enabled=turn_geom_on, stock_lookahead_s=lat_action_t, v_ego=v_ego, ref_offset_m=turn_geom_offset, + lat_active=bool(sm['carControl'].latActive), + cmd_angle_deg=float(sm['carControl'].actuators.steeringAngleDeg), + out_angle_deg=float(sm['carOutput'].actuatorsOutput.steeringAngleDeg) if sm.seen['carOutput'] else None, + turn_in_step=turn_in_step) + lat_sample_floor_s = turn_geom.sample_floor_s + action = get_action_from_model(model_output, prev_action, lat_action_t, long_delay + frame_delay + action_delay, v_ego, + lat_sample_floor_s) + prev_action = action + fill_model_msg(drivingdata_send, modelv2_send, model_output, action, + publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id, frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen) desire_state = modelv2_send.modelV2.meta.desireState l_lane_change_prob = desire_state[log.Desire.laneChangeLeft] r_lane_change_prob = desire_state[log.Desire.laneChangeRight] lane_change_prob = l_lane_change_prob + r_lane_change_prob - DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob) + if turn_geom_preap and run_count % ModelConstants.MODEL_RUN_FREQ == 0: + DH.suppress_tips = params.get_bool(PARAM_RING_LATCHED) # roundabout ring latched (controlsd): no ALC from a tip + DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob, + model=modelv2_send.modelV2, engaged=sm['carControl'].enabled) modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction + modelv2_send.modelV2.meta.laneChangeSignalsRemaining = DH.signals_remaining + modelv2_send.modelV2.meta.laneChangeRemaining = DH.lane_changes_remaining drivingdata_send.drivingModelData.meta.laneChangeState = DH.lane_change_state drivingdata_send.drivingModelData.meta.laneChangeDirection = DH.lane_change_direction @@ -279,7 +360,6 @@ def main(demo=False): pm.send('modelV2', modelv2_send) pm.send('drivingModelData', drivingdata_send) pm.send('cameraOdometry', posenet_send) - last_vipc_frame_id = meta_main.frame_id @@ -291,7 +371,4 @@ def main(demo=False): args = parser.parse_args() main(demo=args.demo) except KeyboardInterrupt: - cloudlog.warning(f"child {PROCESS_NAME} got SIGINT") - except Exception: - sentry.capture_exception() - raise + cloudlog.warning("got SIGINT") diff --git a/selfdrive/modeld/models/README.md b/selfdrive/modeld/models/README.md index 9e11ca82550c52..04b69c61c3d6d3 100644 --- a/selfdrive/modeld/models/README.md +++ b/selfdrive/modeld/models/README.md @@ -1,8 +1,8 @@ ## Neural networks in openpilot To view the architecture of the ONNX networks, you can use [netron](https://netron.app/) -## Supercombo -### Supercombo input format (Full size: 799906 x float32) +## Driving Model (vision model + temporal policy model) +### Vision inputs (Full size: 799906 x float32) * **image stream** * Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256 * Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256 @@ -15,16 +15,21 @@ To view the architecture of the ONNX networks, you can use [netron](https://netr * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] * Channel 4 represents the half-res U channel * Channel 5 represents the half-res V channel +### Policy inputs * **desire** * one-hot encoded buffer to command model to execute certain actions, bit needs to be sent for the past 5 seconds (at 20FPS) : 100 * 8 * **traffic convention** * one-hot encoded vector to tell model whether traffic is right-hand or left-hand traffic : 2 +* **lateral control params** + * speed and steering delay for predicting the desired curvature: 2 +* **previous desired curvatures** + * vector of previously predicted desired curvatures: 100 * 1 * **feature buffer** - * A buffer of intermediate features that gets appended to the current feature to form a 5 seconds temporal context (at 20FPS) : 99 * 512 + * a buffer of intermediate features including the current feature to form a 5 seconds temporal context (at 20FPS) : 100 * 512 -### Supercombo output format (Full size: XXX x float32) -Read [here](https://github.com/commaai/openpilot/blob/90af436a121164a51da9fa48d093c29f738adf6a/selfdrive/modeld/models/driving.h#L236) for more. +### Driving Model output format (Full size: XXX x float32) +Refer to **slice_outputs** and **parse_vision_outputs/parse_policy_outputs** in modeld. ## Driver Monitoring Model @@ -57,6 +62,5 @@ Read [here](https://github.com/commaai/openpilot/blob/90af436a121164a51da9fa48d0 * (deprecated) distracted probabilities: 2 * using phone probability: 1 * distracted probability: 1 - * common outputs 2 - * poor camera vision probability: 1 + * common outputs 1 * left hand drive probability: 1 diff --git a/selfdrive/modeld/models/big_driving_policy.onnx b/selfdrive/modeld/models/big_driving_policy.onnx new file mode 120000 index 00000000000000..e1b653a14a03d6 --- /dev/null +++ b/selfdrive/modeld/models/big_driving_policy.onnx @@ -0,0 +1 @@ +driving_policy.onnx \ No newline at end of file diff --git a/selfdrive/modeld/models/big_driving_vision.onnx b/selfdrive/modeld/models/big_driving_vision.onnx new file mode 120000 index 00000000000000..28ee71dd746e63 --- /dev/null +++ b/selfdrive/modeld/models/big_driving_vision.onnx @@ -0,0 +1 @@ +driving_vision.onnx \ No newline at end of file diff --git a/selfdrive/modeld/models/commonmodel.cc b/selfdrive/modeld/models/commonmodel.cc deleted file mode 100644 index 523ce00e436eda..00000000000000 --- a/selfdrive/modeld/models/commonmodel.cc +++ /dev/null @@ -1,54 +0,0 @@ -#include "selfdrive/modeld/models/commonmodel.h" - -#include -#include -#include - -#include "common/clutil.h" - -ModelFrame::ModelFrame(cl_device_id device_id, cl_context context) { - input_frames = std::make_unique(buf_size); - - q = CL_CHECK_ERR(clCreateCommandQueue(context, device_id, 0, &err)); - y_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, MODEL_WIDTH * MODEL_HEIGHT, NULL, &err)); - u_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (MODEL_WIDTH / 2) * (MODEL_HEIGHT / 2), NULL, &err)); - v_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (MODEL_WIDTH / 2) * (MODEL_HEIGHT / 2), NULL, &err)); - net_input_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, MODEL_FRAME_SIZE * sizeof(float), NULL, &err)); - - transform_init(&transform, context, device_id); - loadyuv_init(&loadyuv, context, device_id, MODEL_WIDTH, MODEL_HEIGHT); -} - -float* ModelFrame::prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3 &projection, cl_mem *output) { - transform_queue(&this->transform, q, - yuv_cl, frame_width, frame_height, frame_stride, frame_uv_offset, - y_cl, u_cl, v_cl, MODEL_WIDTH, MODEL_HEIGHT, projection); - - if (output == NULL) { - loadyuv_queue(&loadyuv, q, y_cl, u_cl, v_cl, net_input_cl); - - std::memmove(&input_frames[0], &input_frames[MODEL_FRAME_SIZE], sizeof(float) * MODEL_FRAME_SIZE); - CL_CHECK(clEnqueueReadBuffer(q, net_input_cl, CL_TRUE, 0, MODEL_FRAME_SIZE * sizeof(float), &input_frames[MODEL_FRAME_SIZE], 0, nullptr, nullptr)); - clFinish(q); - return &input_frames[0]; - } else { - loadyuv_queue(&loadyuv, q, y_cl, u_cl, v_cl, *output, true); - // NOTE: Since thneed is using a different command queue, this clFinish is needed to ensure the image is ready. - clFinish(q); - return NULL; - } -} - -ModelFrame::~ModelFrame() { - transform_destroy(&transform); - loadyuv_destroy(&loadyuv); - CL_CHECK(clReleaseMemObject(net_input_cl)); - CL_CHECK(clReleaseMemObject(v_cl)); - CL_CHECK(clReleaseMemObject(u_cl)); - CL_CHECK(clReleaseMemObject(y_cl)); - CL_CHECK(clReleaseCommandQueue(q)); -} - -float sigmoid(float input) { - return 1 / (1 + expf(-input)); -} diff --git a/selfdrive/modeld/models/commonmodel.h b/selfdrive/modeld/models/commonmodel.h deleted file mode 100644 index 2cf79094a69262..00000000000000 --- a/selfdrive/modeld/models/commonmodel.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include -#include - -#include - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "common/mat.h" -#include "selfdrive/modeld/transforms/loadyuv.h" -#include "selfdrive/modeld/transforms/transform.h" - -float sigmoid(float input); - -class ModelFrame { -public: - ModelFrame(cl_device_id device_id, cl_context context); - ~ModelFrame(); - float* prepare(cl_mem yuv_cl, int width, int height, int frame_stride, int frame_uv_offset, const mat3& transform, cl_mem *output); - - const int MODEL_WIDTH = 512; - const int MODEL_HEIGHT = 256; - const int MODEL_FRAME_SIZE = MODEL_WIDTH * MODEL_HEIGHT * 3 / 2; - const int buf_size = MODEL_FRAME_SIZE * 2; - -private: - Transform transform; - LoadYUVState loadyuv; - cl_command_queue q; - cl_mem y_cl, u_cl, v_cl, net_input_cl; - std::unique_ptr input_frames; -}; diff --git a/selfdrive/modeld/models/commonmodel.pxd b/selfdrive/modeld/models/commonmodel.pxd deleted file mode 100644 index 7c3eb0b3d7e4d5..00000000000000 --- a/selfdrive/modeld/models/commonmodel.pxd +++ /dev/null @@ -1,20 +0,0 @@ -# distutils: language = c++ - -from msgq.visionipc.visionipc cimport cl_device_id, cl_context, cl_mem - -cdef extern from "common/mat.h": - cdef struct mat3: - float v[9] - -cdef extern from "common/clutil.h": - cdef unsigned long CL_DEVICE_TYPE_DEFAULT - cl_device_id cl_get_device_id(unsigned long) - cl_context cl_create_context(cl_device_id) - -cdef extern from "selfdrive/modeld/models/commonmodel.h": - float sigmoid(float) - - cppclass ModelFrame: - int buf_size - ModelFrame(cl_device_id, cl_context) - float * prepare(cl_mem, int, int, int, int, mat3, cl_mem*) diff --git a/selfdrive/modeld/models/commonmodel_pyx.pxd b/selfdrive/modeld/models/commonmodel_pyx.pxd deleted file mode 100644 index 0bb798625be28d..00000000000000 --- a/selfdrive/modeld/models/commonmodel_pyx.pxd +++ /dev/null @@ -1,13 +0,0 @@ -# distutils: language = c++ - -from msgq.visionipc.visionipc cimport cl_mem -from msgq.visionipc.visionipc_pyx cimport CLContext as BaseCLContext - -cdef class CLContext(BaseCLContext): - pass - -cdef class CLMem: - cdef cl_mem * mem - - @staticmethod - cdef create(void*) diff --git a/selfdrive/modeld/models/commonmodel_pyx.pyx b/selfdrive/modeld/models/commonmodel_pyx.pyx deleted file mode 100644 index ecbe644e0945bd..00000000000000 --- a/selfdrive/modeld/models/commonmodel_pyx.pyx +++ /dev/null @@ -1,47 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -import numpy as np -cimport numpy as cnp -from libc.string cimport memcpy - -from msgq.visionipc.visionipc cimport cl_mem -from msgq.visionipc.visionipc_pyx cimport VisionBuf, CLContext as BaseCLContext -from .commonmodel cimport CL_DEVICE_TYPE_DEFAULT, cl_get_device_id, cl_create_context -from .commonmodel cimport mat3, sigmoid as cppSigmoid, ModelFrame as cppModelFrame - -def sigmoid(x): - return cppSigmoid(x) - -cdef class CLContext(BaseCLContext): - def __cinit__(self): - self.device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT) - self.context = cl_create_context(self.device_id) - -cdef class CLMem: - @staticmethod - cdef create(void * cmem): - mem = CLMem() - mem.mem = cmem - return mem - -cdef class ModelFrame: - cdef cppModelFrame * frame - - def __cinit__(self, CLContext context): - self.frame = new cppModelFrame(context.device_id, context.context) - - def __dealloc__(self): - del self.frame - - def prepare(self, VisionBuf buf, float[:] projection, CLMem output): - cdef mat3 cprojection - memcpy(cprojection.v, &projection[0], 9*sizeof(float)) - cdef float * data - if output is None: - data = self.frame.prepare(buf.buf.buf_cl, buf.width, buf.height, buf.stride, buf.uv_offset, cprojection, NULL) - else: - data = self.frame.prepare(buf.buf.buf_cl, buf.width, buf.height, buf.stride, buf.uv_offset, cprojection, output.mem) - if not data: - return None - return np.asarray( data) diff --git a/selfdrive/modeld/models/dmonitoring_model.current b/selfdrive/modeld/models/dmonitoring_model.current deleted file mode 100644 index f935ab06b34e27..00000000000000 --- a/selfdrive/modeld/models/dmonitoring_model.current +++ /dev/null @@ -1,2 +0,0 @@ -5ec97a39-0095-4cea-adfa-6d72b1966cc1 -26cac7a9757a27c783a365403040a1bd27ccdaea \ No newline at end of file diff --git a/selfdrive/modeld/models/dmonitoring_model.onnx b/selfdrive/modeld/models/dmonitoring_model.onnx index dd3a6aba2e756e..bd3f2c85a614b2 100644 --- a/selfdrive/modeld/models/dmonitoring_model.onnx +++ b/selfdrive/modeld/models/dmonitoring_model.onnx @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3dd3982940d823c4fbb0429b733a0b78b0688d7d67aa76ff7b754a3e2f3d8683 -size 16132780 +oid sha256:3e7b31dfbc0a5234f1baf196513b77fc6af12204b8a8ffe8ee0417e48352f316 +size 7494962 diff --git a/selfdrive/modeld/models/dmonitoring_model_q.dlc b/selfdrive/modeld/models/dmonitoring_model_q.dlc deleted file mode 100644 index fc285954d4aa61..00000000000000 --- a/selfdrive/modeld/models/dmonitoring_model_q.dlc +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7c26f13816b143f5bb29ac2980f8557bd5687a75729e4d895313fb9a5a1f0f46 -size 4488449 diff --git a/selfdrive/modeld/models/driving_policy.onnx b/selfdrive/modeld/models/driving_policy.onnx new file mode 100644 index 00000000000000..611ae9fe85f837 --- /dev/null +++ b/selfdrive/modeld/models/driving_policy.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78477124cbf3ffe30fa951ebada8410b43c4242c6054584d656f1d329b067e15 +size 14060847 diff --git a/selfdrive/modeld/models/driving_vision.onnx b/selfdrive/modeld/models/driving_vision.onnx new file mode 100644 index 00000000000000..6c9fc4c84d3632 --- /dev/null +++ b/selfdrive/modeld/models/driving_vision.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee29ee5bce84d1ce23e9ff381280de9b4e4d96d2934cd751740354884e112c66 +size 46877473 diff --git a/selfdrive/modeld/models/supercombo.onnx b/selfdrive/modeld/models/supercombo.onnx deleted file mode 100644 index 2e1a60a23eb453..00000000000000 --- a/selfdrive/modeld/models/supercombo.onnx +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:39786068cae1ed8c0dc34ef80c281dfcc67ed18a50e06b90765c49bcfdbf7db4 -size 51453312 diff --git a/selfdrive/modeld/parse_model_outputs.py b/selfdrive/modeld/parse_model_outputs.py index 03d03c5e1cc38e..a0b45d2a981685 100644 --- a/selfdrive/modeld/parse_model_outputs.py +++ b/selfdrive/modeld/parse_model_outputs.py @@ -1,15 +1,19 @@ import numpy as np from openpilot.selfdrive.modeld.constants import ModelConstants +def safe_exp(x, out=None): + # -11 is around 10**14, more causes float16 overflow + return np.exp(np.clip(x, -np.inf, 11), out=out) + def sigmoid(x): - return 1. / (1. + np.exp(-x)) + return 1. / (1. + safe_exp(-x)) def softmax(x, axis=-1): x -= np.max(x, axis=axis, keepdims=True) if x.dtype == np.float32 or x.dtype == np.float64: - np.exp(x, out=x) + safe_exp(x, out=x) else: - x = np.exp(x) + x = safe_exp(x) x /= np.sum(x, axis=axis, keepdims=True) return x @@ -18,9 +22,10 @@ def __init__(self, ignore_missing=False): self.ignore_missing = ignore_missing def check_missing(self, outs, name): - if name not in outs and not self.ignore_missing: + missing = name not in outs + if missing and not self.ignore_missing: raise ValueError(f"Missing output {name}") - return name not in outs + return missing def parse_categorical_crossentropy(self, name, outs, out_shape=None): if self.check_missing(outs, name): @@ -44,7 +49,7 @@ def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None): n_values = (raw.shape[2] - out_N)//2 pred_mu = raw[:,:,:n_values] - pred_std = np.exp(raw[:,:,n_values: 2*n_values]) + pred_std = safe_exp(raw[:,:,n_values: 2*n_values]) if in_N > 1: weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype) @@ -80,23 +85,40 @@ def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None): outs[name] = pred_mu_final.reshape(final_shape) outs[name + '_stds'] = pred_std_final.reshape(final_shape) - def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - self.parse_mdn('plan', outs, in_N=ModelConstants.PLAN_MHP_N, out_N=ModelConstants.PLAN_MHP_SELECTION, - out_shape=(ModelConstants.IDX_N,ModelConstants.PLAN_WIDTH)) - self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) + def is_mhp(self, outs, name, shape): + if self.check_missing(outs, name): + return False + if outs[name].shape[1] == 2 * shape: + return False + return True + + def parse_vision_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_mdn('sim_pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,)) - self.parse_mdn('lead', outs, in_N=ModelConstants.LEAD_MHP_N, out_N=ModelConstants.LEAD_MHP_SELECTION, - out_shape=(ModelConstants.LEAD_TRAJ_LEN,ModelConstants.LEAD_WIDTH)) - if 'lat_planner_solution' in outs: - self.parse_mdn('lat_planner_solution', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N,ModelConstants.LAT_PLANNER_SOLUTION_WIDTH)) - if 'desired_curvature' in outs: - self.parse_mdn('desired_curvature', outs, in_N=0, out_N=0, out_shape=(ModelConstants.DESIRED_CURV_WIDTH,)) - for k in ['lead_prob', 'lane_lines_prob', 'meta']: - self.parse_binary_crossentropy(k, outs) - self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,)) + self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) + self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) + self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) + self.parse_binary_crossentropy('lane_lines_prob', outs) self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH)) + self.parse_binary_crossentropy('meta', outs) + self.parse_binary_crossentropy('lead_prob', outs) + lead_mhp = self.is_mhp(outs, 'lead', ModelConstants.LEAD_MHP_SELECTION * ModelConstants.LEAD_TRAJ_LEN * ModelConstants.LEAD_WIDTH) + lead_in_N, lead_out_N = (ModelConstants.LEAD_MHP_N, ModelConstants.LEAD_MHP_SELECTION) if lead_mhp else (0, 0) + lead_out_shape = (ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH) if lead_mhp else \ + (ModelConstants.LEAD_MHP_SELECTION, ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH) + self.parse_mdn('lead', outs, in_N=lead_in_N, out_N=lead_out_N, out_shape=lead_out_shape) + return outs + + def parse_policy_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + plan_mhp = self.is_mhp(outs, 'plan', ModelConstants.IDX_N * ModelConstants.PLAN_WIDTH) + plan_in_N, plan_out_N = (ModelConstants.PLAN_MHP_N, ModelConstants.PLAN_MHP_SELECTION) if plan_mhp else (0, 0) + self.parse_mdn('plan', outs, in_N=plan_in_N, out_N=plan_out_N, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH)) + if 'planplus' in outs: + self.parse_mdn('planplus', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH)) + self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,)) + return outs + + def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + outs = self.parse_vision_outputs(outs) + outs = self.parse_policy_outputs(outs) return outs diff --git a/selfdrive/modeld/runners/__init__.py b/selfdrive/modeld/runners/__init__.py deleted file mode 100644 index 4c29bf3f1cfbf7..00000000000000 --- a/selfdrive/modeld/runners/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -import os -from openpilot.system.hardware import TICI -from openpilot.selfdrive.modeld.runners.runmodel_pyx import RunModel, Runtime -assert Runtime - -USE_THNEED = int(os.getenv('USE_THNEED', str(int(TICI)))) -USE_SNPE = int(os.getenv('USE_SNPE', str(int(TICI)))) - -class ModelRunner(RunModel): - THNEED = 'THNEED' - SNPE = 'SNPE' - ONNX = 'ONNX' - - def __new__(cls, paths, *args, **kwargs): - if ModelRunner.THNEED in paths and USE_THNEED: - from openpilot.selfdrive.modeld.runners.thneedmodel_pyx import ThneedModel as Runner - runner_type = ModelRunner.THNEED - elif ModelRunner.SNPE in paths and USE_SNPE: - from openpilot.selfdrive.modeld.runners.snpemodel_pyx import SNPEModel as Runner - runner_type = ModelRunner.SNPE - elif ModelRunner.ONNX in paths: - from openpilot.selfdrive.modeld.runners.onnxmodel import ONNXModel as Runner - runner_type = ModelRunner.ONNX - else: - raise Exception("Couldn't select a model runner, make sure to pass at least one valid model path") - - return Runner(str(paths[runner_type]), *args, **kwargs) diff --git a/selfdrive/modeld/runners/onnxmodel.py b/selfdrive/modeld/runners/onnxmodel.py deleted file mode 100644 index 69b44a5a97116a..00000000000000 --- a/selfdrive/modeld/runners/onnxmodel.py +++ /dev/null @@ -1,93 +0,0 @@ -import onnx -import itertools -import os -import sys -import numpy as np -from typing import Any - -from openpilot.selfdrive.modeld.runners.runmodel_pyx import RunModel - -ORT_TYPES_TO_NP_TYPES = {'tensor(float16)': np.float16, 'tensor(float)': np.float32, 'tensor(uint8)': np.uint8} - -def attributeproto_fp16_to_fp32(attr): - float32_list = np.frombuffer(attr.raw_data, dtype=np.float16) - attr.data_type = 1 - attr.raw_data = float32_list.astype(np.float32).tobytes() - -def convert_fp16_to_fp32(path): - model = onnx.load(path) - for i in model.graph.initializer: - if i.data_type == 10: - attributeproto_fp16_to_fp32(i) - for i in itertools.chain(model.graph.input, model.graph.output): - if i.type.tensor_type.elem_type == 10: - i.type.tensor_type.elem_type = 1 - for i in model.graph.node: - for a in i.attribute: - if hasattr(a, 't'): - if a.t.data_type == 10: - attributeproto_fp16_to_fp32(a.t) - return model.SerializeToString() - -def create_ort_session(path, fp16_to_fp32): - os.environ["OMP_NUM_THREADS"] = "4" - os.environ["OMP_WAIT_POLICY"] = "PASSIVE" - - import onnxruntime as ort - print("Onnx available providers: ", ort.get_available_providers(), file=sys.stderr) - options = ort.SessionOptions() - options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL - - provider: str | tuple[str, dict[Any, Any]] - if 'OpenVINOExecutionProvider' in ort.get_available_providers() and 'ONNXCPU' not in os.environ: - provider = 'OpenVINOExecutionProvider' - elif 'CUDAExecutionProvider' in ort.get_available_providers() and 'ONNXCPU' not in os.environ: - options.intra_op_num_threads = 2 - provider = ('CUDAExecutionProvider', {'cudnn_conv_algo_search': 'DEFAULT'}) - else: - options.intra_op_num_threads = 2 - options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL - options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL - provider = 'CPUExecutionProvider' - - model_data = convert_fp16_to_fp32(path) if fp16_to_fp32 else path - print("Onnx selected provider: ", [provider], file=sys.stderr) - ort_session = ort.InferenceSession(model_data, options, providers=[provider]) - print("Onnx using ", ort_session.get_providers(), file=sys.stderr) - return ort_session - - -class ONNXModel(RunModel): - def __init__(self, path, output, runtime, use_tf8, cl_context): - self.inputs = {} - self.output = output - self.use_tf8 = use_tf8 - - self.session = create_ort_session(path, fp16_to_fp32=True) - self.input_names = [x.name for x in self.session.get_inputs()] - self.input_shapes = {x.name: [1, *x.shape[1:]] for x in self.session.get_inputs()} - self.input_dtypes = {x.name: ORT_TYPES_TO_NP_TYPES[x.type] for x in self.session.get_inputs()} - - # run once to initialize CUDA provider - if "CUDAExecutionProvider" in self.session.get_providers(): - self.session.run(None, {k: np.zeros(self.input_shapes[k], dtype=self.input_dtypes[k]) for k in self.input_names}) - print("ready to run onnx model", self.input_shapes, file=sys.stderr) - - def addInput(self, name, buffer): - assert name in self.input_names - self.inputs[name] = buffer - - def setInputBuffer(self, name, buffer): - assert name in self.inputs - self.inputs[name] = buffer - - def getCLBuffer(self, name): - return None - - def execute(self): - inputs = {k: (v.view(np.uint8) / 255. if self.use_tf8 and k == 'input_img' else v) for k,v in self.inputs.items()} - inputs = {k: v.reshape(self.input_shapes[k]).astype(self.input_dtypes[k]) for k,v in inputs.items()} - outputs = self.session.run(None, inputs) - assert len(outputs) == 1, "Only single model outputs are supported" - self.output[:] = outputs[0] - return self.output diff --git a/selfdrive/modeld/runners/run.h b/selfdrive/modeld/runners/run.h deleted file mode 100644 index 36ad262a5bc92d..00000000000000 --- a/selfdrive/modeld/runners/run.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once - -#include "selfdrive/modeld/runners/runmodel.h" -#include "selfdrive/modeld/runners/snpemodel.h" diff --git a/selfdrive/modeld/runners/runmodel.h b/selfdrive/modeld/runners/runmodel.h deleted file mode 100644 index 18cc180cb7f1d9..00000000000000 --- a/selfdrive/modeld/runners/runmodel.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "common/clutil.h" -#include "common/swaglog.h" - -#define USE_CPU_RUNTIME 0 -#define USE_GPU_RUNTIME 1 -#define USE_DSP_RUNTIME 2 - -struct ModelInput { - const std::string name; - float *buffer; - int size; - - ModelInput(const std::string _name, float *_buffer, int _size) : name(_name), buffer(_buffer), size(_size) {} - virtual void setBuffer(float *_buffer, int _size) { - assert(size == _size || size == 0); - buffer = _buffer; - size = _size; - } -}; - -class RunModel { -public: - std::vector> inputs; - - virtual ~RunModel() {} - virtual void execute() {} - virtual void* getCLBuffer(const std::string name) { return nullptr; } - - virtual void addInput(const std::string name, float *buffer, int size) { - inputs.push_back(std::unique_ptr(new ModelInput(name, buffer, size))); - } - virtual void setInputBuffer(const std::string name, float *buffer, int size) { - for (auto &input : inputs) { - if (name == input->name) { - input->setBuffer(buffer, size); - return; - } - } - LOGE("Tried to update input `%s` but no input with this name exists", name.c_str()); - assert(false); - } -}; diff --git a/selfdrive/modeld/runners/runmodel.pxd b/selfdrive/modeld/runners/runmodel.pxd deleted file mode 100644 index 01b2a9cf2c9a7d..00000000000000 --- a/selfdrive/modeld/runners/runmodel.pxd +++ /dev/null @@ -1,14 +0,0 @@ -# distutils: language = c++ - -from libcpp.string cimport string - -cdef extern from "selfdrive/modeld/runners/runmodel.h": - cdef int USE_CPU_RUNTIME - cdef int USE_GPU_RUNTIME - cdef int USE_DSP_RUNTIME - - cdef cppclass RunModel: - void addInput(string, float*, int) - void setInputBuffer(string, float*, int) - void * getCLBuffer(string) - void execute() diff --git a/selfdrive/modeld/runners/runmodel_pyx.pxd b/selfdrive/modeld/runners/runmodel_pyx.pxd deleted file mode 100644 index b6ede7cf37f733..00000000000000 --- a/selfdrive/modeld/runners/runmodel_pyx.pxd +++ /dev/null @@ -1,6 +0,0 @@ -# distutils: language = c++ - -from .runmodel cimport RunModel as cppRunModel - -cdef class RunModel: - cdef cppRunModel * model diff --git a/selfdrive/modeld/runners/runmodel_pyx.pyx b/selfdrive/modeld/runners/runmodel_pyx.pyx deleted file mode 100644 index 12b8ec10ff8fe9..00000000000000 --- a/selfdrive/modeld/runners/runmodel_pyx.pyx +++ /dev/null @@ -1,37 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -from libcpp.string cimport string - -from .runmodel cimport USE_CPU_RUNTIME, USE_GPU_RUNTIME, USE_DSP_RUNTIME -from selfdrive.modeld.models.commonmodel_pyx cimport CLMem - -class Runtime: - CPU = USE_CPU_RUNTIME - GPU = USE_GPU_RUNTIME - DSP = USE_DSP_RUNTIME - -cdef class RunModel: - def __dealloc__(self): - del self.model - - def addInput(self, string name, float[:] buffer): - if buffer is not None: - self.model.addInput(name, &buffer[0], len(buffer)) - else: - self.model.addInput(name, NULL, 0) - - def setInputBuffer(self, string name, float[:] buffer): - if buffer is not None: - self.model.setInputBuffer(name, &buffer[0], len(buffer)) - else: - self.model.setInputBuffer(name, NULL, 0) - - def getCLBuffer(self, string name): - cdef void * cl_buf = self.model.getCLBuffer(name) - if not cl_buf: - return None - return CLMem.create(cl_buf) - - def execute(self): - self.model.execute() diff --git a/selfdrive/modeld/runners/snpemodel.cc b/selfdrive/modeld/runners/snpemodel.cc deleted file mode 100644 index 15c1db00865c6d..00000000000000 --- a/selfdrive/modeld/runners/snpemodel.cc +++ /dev/null @@ -1,116 +0,0 @@ -#pragma clang diagnostic ignored "-Wexceptions" - -#include "selfdrive/modeld/runners/snpemodel.h" - -#include -#include -#include -#include -#include - -#include "common/util.h" -#include "common/timing.h" - -void PrintErrorStringAndExit() { - std::cerr << zdl::DlSystem::getLastErrorString() << std::endl; - std::exit(EXIT_FAILURE); -} - -SNPEModel::SNPEModel(const std::string path, float *_output, size_t _output_size, int runtime, bool _use_tf8, cl_context context) { - output = _output; - output_size = _output_size; - use_tf8 = _use_tf8; - -#ifdef QCOM2 - if (runtime == USE_GPU_RUNTIME) { - snpe_runtime = zdl::DlSystem::Runtime_t::GPU; - } else if (runtime == USE_DSP_RUNTIME) { - snpe_runtime = zdl::DlSystem::Runtime_t::DSP; - } else { - snpe_runtime = zdl::DlSystem::Runtime_t::CPU; - } - assert(zdl::SNPE::SNPEFactory::isRuntimeAvailable(snpe_runtime)); -#endif - model_data = util::read_file(path); - assert(model_data.size() > 0); - - // load model - std::unique_ptr container = zdl::DlContainer::IDlContainer::open((uint8_t*)model_data.data(), model_data.size()); - if (!container) { PrintErrorStringAndExit(); } - LOGW("loaded model with size: %lu", model_data.size()); - - // create model runner - zdl::SNPE::SNPEBuilder snpe_builder(container.get()); - while (!snpe) { -#ifdef QCOM2 - snpe = snpe_builder.setOutputLayers({}) - .setRuntimeProcessor(snpe_runtime) - .setUseUserSuppliedBuffers(true) - .setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE) - .build(); -#else - snpe = snpe_builder.setOutputLayers({}) - .setUseUserSuppliedBuffers(true) - .setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE) - .build(); -#endif - if (!snpe) std::cerr << zdl::DlSystem::getLastErrorString() << std::endl; - } - - // create output buffer - zdl::DlSystem::UserBufferEncodingFloat ub_encoding_float; - zdl::DlSystem::IUserBufferFactory &ub_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory(); - - const auto &output_tensor_names_opt = snpe->getOutputTensorNames(); - if (!output_tensor_names_opt) throw std::runtime_error("Error obtaining output tensor names"); - const auto &output_tensor_names = *output_tensor_names_opt; - assert(output_tensor_names.size() == 1); - const char *output_tensor_name = output_tensor_names.at(0); - const zdl::DlSystem::TensorShape &buffer_shape = snpe->getInputOutputBufferAttributes(output_tensor_name)->getDims(); - if (output_size != 0) { - assert(output_size == buffer_shape[1]); - } else { - output_size = buffer_shape[1]; - } - std::vector output_strides = {output_size * sizeof(float), sizeof(float)}; - output_buffer = ub_factory.createUserBuffer(output, output_size * sizeof(float), output_strides, &ub_encoding_float); - output_map.add(output_tensor_name, output_buffer.get()); -} - -void SNPEModel::addInput(const std::string name, float *buffer, int size) { - const int idx = inputs.size(); - const auto &input_tensor_names_opt = snpe->getInputTensorNames(); - if (!input_tensor_names_opt) throw std::runtime_error("Error obtaining input tensor names"); - const auto &input_tensor_names = *input_tensor_names_opt; - const char *input_tensor_name = input_tensor_names.at(idx); - const bool input_tf8 = use_tf8 && strcmp(input_tensor_name, "input_img") == 0; // TODO: This is a terrible hack, get rid of this name check both here and in onnx_runner.py - LOGW("adding index %d: %s", idx, input_tensor_name); - - zdl::DlSystem::UserBufferEncodingFloat ub_encoding_float; - zdl::DlSystem::UserBufferEncodingTf8 ub_encoding_tf8(0, 1./255); // network takes 0-1 - zdl::DlSystem::IUserBufferFactory &ub_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory(); - zdl::DlSystem::UserBufferEncoding *input_encoding = input_tf8 ? (zdl::DlSystem::UserBufferEncoding*)&ub_encoding_tf8 : (zdl::DlSystem::UserBufferEncoding*)&ub_encoding_float; - - const auto &buffer_shape_opt = snpe->getInputDimensions(input_tensor_name); - const zdl::DlSystem::TensorShape &buffer_shape = *buffer_shape_opt; - size_t size_of_input = input_tf8 ? sizeof(uint8_t) : sizeof(float); - std::vector strides(buffer_shape.rank()); - strides[strides.size() - 1] = size_of_input; - size_t product = 1; - for (size_t i = 0; i < buffer_shape.rank(); i++) product *= buffer_shape[i]; - size_t stride = strides[strides.size() - 1]; - for (size_t i = buffer_shape.rank() - 1; i > 0; i--) { - stride *= buffer_shape[i]; - strides[i-1] = stride; - } - - auto input_buffer = ub_factory.createUserBuffer(buffer, product*size_of_input, strides, input_encoding); - input_map.add(input_tensor_name, input_buffer.get()); - inputs.push_back(std::unique_ptr(new SNPEModelInput(name, buffer, size, std::move(input_buffer)))); -} - -void SNPEModel::execute() { - if (!snpe->execute(input_map, output_map)) { - PrintErrorStringAndExit(); - } -} diff --git a/selfdrive/modeld/runners/snpemodel.h b/selfdrive/modeld/runners/snpemodel.h deleted file mode 100644 index 86b2c86084ecf8..00000000000000 --- a/selfdrive/modeld/runners/snpemodel.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "selfdrive/modeld/runners/runmodel.h" - -struct SNPEModelInput : public ModelInput { - std::unique_ptr snpe_buffer; - - SNPEModelInput(const std::string _name, float *_buffer, int _size, std::unique_ptr _snpe_buffer) : ModelInput(_name, _buffer, _size), snpe_buffer(std::move(_snpe_buffer)) {} - void setBuffer(float *_buffer, int _size) { - ModelInput::setBuffer(_buffer, _size); - assert(snpe_buffer->setBufferAddress(_buffer) == true); - } -}; - -class SNPEModel : public RunModel { -public: - SNPEModel(const std::string path, float *_output, size_t _output_size, int runtime, bool use_tf8 = false, cl_context context = NULL); - void addInput(const std::string name, float *buffer, int size); - void execute(); - -private: - std::string model_data; - -#ifdef QCOM2 - zdl::DlSystem::Runtime_t snpe_runtime; -#endif - - // snpe model stuff - std::unique_ptr snpe; - zdl::DlSystem::UserBufferMap input_map; - zdl::DlSystem::UserBufferMap output_map; - std::unique_ptr output_buffer; - - bool use_tf8; - float *output; - size_t output_size; -}; diff --git a/selfdrive/modeld/runners/snpemodel.pxd b/selfdrive/modeld/runners/snpemodel.pxd deleted file mode 100644 index a911b43584d300..00000000000000 --- a/selfdrive/modeld/runners/snpemodel.pxd +++ /dev/null @@ -1,9 +0,0 @@ -# distutils: language = c++ - -from libcpp.string cimport string - -from msgq.visionipc.visionipc cimport cl_context - -cdef extern from "selfdrive/modeld/runners/snpemodel.h": - cdef cppclass SNPEModel: - SNPEModel(string, float*, size_t, int, bool, cl_context) diff --git a/selfdrive/modeld/runners/snpemodel_pyx.pyx b/selfdrive/modeld/runners/snpemodel_pyx.pyx deleted file mode 100644 index f83b7c8cff389a..00000000000000 --- a/selfdrive/modeld/runners/snpemodel_pyx.pyx +++ /dev/null @@ -1,17 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -import os -from libcpp cimport bool -from libcpp.string cimport string - -from .snpemodel cimport SNPEModel as cppSNPEModel -from selfdrive.modeld.models.commonmodel_pyx cimport CLContext -from selfdrive.modeld.runners.runmodel_pyx cimport RunModel -from selfdrive.modeld.runners.runmodel cimport RunModel as cppRunModel - -os.environ['ADSP_LIBRARY_PATH'] = "/data/pythonpath/third_party/snpe/dsp/" - -cdef class SNPEModel(RunModel): - def __cinit__(self, string path, float[:] output, int runtime, bool use_tf8, CLContext context): - self.model = new cppSNPEModel(path, &output[0], len(output), runtime, use_tf8, context.context) diff --git a/selfdrive/modeld/runners/thneedmodel.cc b/selfdrive/modeld/runners/thneedmodel.cc deleted file mode 100644 index a16d8b42aab223..00000000000000 --- a/selfdrive/modeld/runners/thneedmodel.cc +++ /dev/null @@ -1,58 +0,0 @@ -#include "selfdrive/modeld/runners/thneedmodel.h" - -#include - -#include "common/swaglog.h" - -ThneedModel::ThneedModel(const std::string path, float *_output, size_t _output_size, int runtime, bool luse_tf8, cl_context context) { - thneed = new Thneed(true, context); - thneed->load(path.c_str()); - thneed->clexec(); - - recorded = false; - output = _output; -} - -void* ThneedModel::getCLBuffer(const std::string name) { - int index = -1; - for (int i = 0; i < inputs.size(); i++) { - if (name == inputs[i]->name) { - index = i; - break; - } - } - - if (index == -1) { - LOGE("Tried to get CL buffer for input `%s` but no input with this name exists", name.c_str()); - assert(false); - } - - if (thneed->input_clmem.size() >= inputs.size()) { - return &thneed->input_clmem[inputs.size() - index - 1]; - } else { - return nullptr; - } -} - -void ThneedModel::execute() { - if (!recorded) { - thneed->record = true; - float *input_buffers[inputs.size()]; - for (int i = 0; i < inputs.size(); i++) { - input_buffers[inputs.size() - i - 1] = inputs[i]->buffer; - } - - thneed->copy_inputs(input_buffers); - thneed->clexec(); - thneed->copy_output(output); - thneed->stop(); - - recorded = true; - } else { - float *input_buffers[inputs.size()]; - for (int i = 0; i < inputs.size(); i++) { - input_buffers[inputs.size() - i - 1] = inputs[i]->buffer; - } - thneed->execute(input_buffers, output); - } -} diff --git a/selfdrive/modeld/runners/thneedmodel.h b/selfdrive/modeld/runners/thneedmodel.h deleted file mode 100644 index 6ed479c081634d..00000000000000 --- a/selfdrive/modeld/runners/thneedmodel.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/modeld/runners/runmodel.h" -#include "selfdrive/modeld/thneed/thneed.h" - -class ThneedModel : public RunModel { -public: - ThneedModel(const std::string path, float *_output, size_t _output_size, int runtime, bool use_tf8 = false, cl_context context = NULL); - void *getCLBuffer(const std::string name); - void execute(); -private: - Thneed *thneed = NULL; - bool recorded; - float *output; -}; diff --git a/selfdrive/modeld/runners/thneedmodel.pxd b/selfdrive/modeld/runners/thneedmodel.pxd deleted file mode 100644 index 79e24dbdd62518..00000000000000 --- a/selfdrive/modeld/runners/thneedmodel.pxd +++ /dev/null @@ -1,9 +0,0 @@ -# distutils: language = c++ - -from libcpp.string cimport string - -from msgq.visionipc.visionipc cimport cl_context - -cdef extern from "selfdrive/modeld/runners/thneedmodel.h": - cdef cppclass ThneedModel: - ThneedModel(string, float*, size_t, int, bool, cl_context) diff --git a/selfdrive/modeld/runners/thneedmodel_pyx.pyx b/selfdrive/modeld/runners/thneedmodel_pyx.pyx deleted file mode 100644 index 6f8fdd255fa5bb..00000000000000 --- a/selfdrive/modeld/runners/thneedmodel_pyx.pyx +++ /dev/null @@ -1,14 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -from libcpp cimport bool -from libcpp.string cimport string - -from .thneedmodel cimport ThneedModel as cppThneedModel -from selfdrive.modeld.models.commonmodel_pyx cimport CLContext -from selfdrive.modeld.runners.runmodel_pyx cimport RunModel -from selfdrive.modeld.runners.runmodel cimport RunModel as cppRunModel - -cdef class ThneedModel(RunModel): - def __cinit__(self, string path, float[:] output, int runtime, bool use_tf8, CLContext context): - self.model = new cppThneedModel(path, &output[0], len(output), runtime, use_tf8, context.context) diff --git a/selfdrive/modeld/tests/dmon_lag/repro.cc b/selfdrive/modeld/tests/dmon_lag/repro.cc deleted file mode 100644 index c4c1c65cbe86a7..00000000000000 --- a/selfdrive/modeld/tests/dmon_lag/repro.cc +++ /dev/null @@ -1,101 +0,0 @@ -// clang++ -O2 repro.cc && ./a.out - -#include -#include -#include - -#include -#include -#include -#include -#include - -static inline double millis_since_boot() { - struct timespec t; - clock_gettime(CLOCK_BOOTTIME, &t); - return t.tv_sec * 1000.0 + t.tv_nsec * 1e-6; -} - -#define MODEL_WIDTH 320 -#define MODEL_HEIGHT 640 - -// null function still breaks it -#define input_lambda(x) x - -// this is copied from models/dmonitoring.cc, and is the code that triggers the issue -void inner(uint8_t *resized_buf, float *net_input_buf) { - int resized_width = MODEL_WIDTH; - int resized_height = MODEL_HEIGHT; - - // one shot conversion, O(n) anyway - // yuvframe2tensor, normalize - for (int r = 0; r < MODEL_HEIGHT/2; r++) { - for (int c = 0; c < MODEL_WIDTH/2; c++) { - // Y_ul - net_input_buf[(c*MODEL_HEIGHT/2) + r] = input_lambda(resized_buf[(2*r*resized_width) + (2*c)]); - // Y_ur - net_input_buf[(c*MODEL_HEIGHT/2) + r + (2*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width) + (2*c+1)]); - // Y_dl - net_input_buf[(c*MODEL_HEIGHT/2) + r + ((MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c)]); - // Y_dr - net_input_buf[(c*MODEL_HEIGHT/2) + r + (3*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c+1)]); - // U - net_input_buf[(c*MODEL_HEIGHT/2) + r + (4*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + (r*resized_width/2) + c]); - // V - net_input_buf[(c*MODEL_HEIGHT/2) + r + (5*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + ((resized_width/2)*(resized_height/2)) + (r*resized_width/2) + c]); - } - } -} - -float trial() { - int resized_width = MODEL_WIDTH; - int resized_height = MODEL_HEIGHT; - - int yuv_buf_len = (MODEL_WIDTH/2) * (MODEL_HEIGHT/2) * 6; // Y|u|v -> y|y|y|y|u|v - - // allocate the buffers - uint8_t *resized_buf = (uint8_t*)malloc(resized_width*resized_height*3/2); - float *net_input_buf = (float*)malloc(yuv_buf_len*sizeof(float)); - printf("allocate -- %p 0x%x -- %p 0x%lx\n", resized_buf, resized_width*resized_height*3/2, net_input_buf, yuv_buf_len*sizeof(float)); - - // test for bad buffers - static int CNT = 20; - float avg = 0.0; - for (int i = 0; i < CNT; i++) { - double s4 = millis_since_boot(); - inner(resized_buf, net_input_buf); - double s5 = millis_since_boot(); - avg += s5-s4; - } - avg /= CNT; - - // once it's bad, it's reliably bad - if (avg > 10) { - printf("HIT %f\n", avg); - printf("BAD\n"); - - for (int i = 0; i < 200; i++) { - double s4 = millis_since_boot(); - inner(resized_buf, net_input_buf); - double s5 = millis_since_boot(); - printf("%.2f ", s5-s4); - } - printf("\n"); - - exit(0); - } - - // don't free so we get a different buffer each time - //free(resized_buf); - //free(net_input_buf); - - return avg; -} - -int main() { - while (true) { - float ret = trial(); - printf("got %f\n", ret); - } -} - diff --git a/selfdrive/modeld/tests/snpe_benchmark/.gitignore b/selfdrive/modeld/tests/snpe_benchmark/.gitignore deleted file mode 100644 index d83a1b2ff5c336..00000000000000 --- a/selfdrive/modeld/tests/snpe_benchmark/.gitignore +++ /dev/null @@ -1 +0,0 @@ -benchmark diff --git a/selfdrive/modeld/tests/snpe_benchmark/benchmark.cc b/selfdrive/modeld/tests/snpe_benchmark/benchmark.cc deleted file mode 100644 index f72f7fb1a7ac3b..00000000000000 --- a/selfdrive/modeld/tests/snpe_benchmark/benchmark.cc +++ /dev/null @@ -1,192 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { - return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); -} - -void PrintErrorStringAndExit() { - cout << "ERROR!" << endl; - const char* const errStr = zdl::DlSystem::getLastErrorString(); - std::cerr << errStr << std::endl; - std::exit(EXIT_FAILURE); -} - - -zdl::DlSystem::Runtime_t checkRuntime() { - static zdl::DlSystem::Version_t Version = zdl::SNPE::SNPEFactory::getLibraryVersion(); - static zdl::DlSystem::Runtime_t Runtime; - std::cout << "SNPE Version: " << Version.asString().c_str() << std::endl; //Print Version number - if (zdl::SNPE::SNPEFactory::isRuntimeAvailable(zdl::DlSystem::Runtime_t::DSP)) { - std::cout << "Using DSP runtime" << std::endl; - Runtime = zdl::DlSystem::Runtime_t::DSP; - } else if (zdl::SNPE::SNPEFactory::isRuntimeAvailable(zdl::DlSystem::Runtime_t::GPU)) { - std::cout << "Using GPU runtime" << std::endl; - Runtime = zdl::DlSystem::Runtime_t::GPU; - } else { - std::cout << "Using cpu runtime" << std::endl; - Runtime = zdl::DlSystem::Runtime_t::CPU; - } - return Runtime; -} - -void test(char *filename) { - static zdl::DlSystem::Runtime_t runtime = checkRuntime(); - std::unique_ptr container; - container = zdl::DlContainer::IDlContainer::open(filename); - - if (!container) { PrintErrorStringAndExit(); } - cout << "start build" << endl; - std::unique_ptr snpe; - { - snpe = NULL; - zdl::SNPE::SNPEBuilder snpeBuilder(container.get()); - snpe = snpeBuilder.setOutputLayers({}) - .setRuntimeProcessor(runtime) - .setUseUserSuppliedBuffers(false) - //.setDebugMode(true) - .build(); - if (!snpe) { - cout << "ERROR!" << endl; - const char* const errStr = zdl::DlSystem::getLastErrorString(); - std::cerr << errStr << std::endl; - } - cout << "ran snpeBuilder" << endl; - } - - const auto &strList_opt = snpe->getInputTensorNames(); - if (!strList_opt) throw std::runtime_error("Error obtaining input tensor names"); - - cout << "get input tensor names done" << endl; - const auto &strList = *strList_opt; - static zdl::DlSystem::TensorMap inputTensorMap; - static zdl::DlSystem::TensorMap outputTensorMap; - vector > inputs; - for (int i = 0; i < strList.size(); i++) { - cout << "input name: " << strList.at(i) << endl; - - const auto &inputDims_opt = snpe->getInputDimensions(strList.at(i)); - const auto &inputShape = *inputDims_opt; - inputs.push_back(zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(inputShape)); - inputTensorMap.add(strList.at(i), inputs[i].get()); - } - - struct timespec start, end; - cout << "**** starting benchmark ****" << endl; - for (int i = 0; i < 50; i++) { - clock_gettime(CLOCK_MONOTONIC, &start); - int err = snpe->execute(inputTensorMap, outputTensorMap); - assert(err == true); - clock_gettime(CLOCK_MONOTONIC, &end); - uint64_t timeElapsed = timespecDiff(&end, &start); - printf("time: %f ms\n", timeElapsed*1.0/1e6); - } -} - -void get_testframe(int index, std::unique_ptr &input) { - FILE * pFile; - string filepath="/data/ipt/quantize_samples/sample_input_"+std::to_string(index); - pFile = fopen(filepath.c_str(), "rb"); - int length = 1*6*160*320*4; - float * frame_buffer = new float[length/4]; // 32/8 - fread(frame_buffer, length, 1, pFile); - // std::cout << *(frame_buffer+length/4-1) << std::endl; - std::copy(frame_buffer, frame_buffer+(length/4), input->begin()); - fclose(pFile); -} - -void SaveITensor(const std::string& path, const zdl::DlSystem::ITensor* tensor) -{ - std::ofstream os(path, std::ofstream::binary); - if (!os) - { - std::cerr << "Failed to open output file for writing: " << path << "\n"; - std::exit(EXIT_FAILURE); - } - for ( auto it = tensor->cbegin(); it != tensor->cend(); ++it ) - { - float f = *it; - if (!os.write(reinterpret_cast(&f), sizeof(float))) - { - std::cerr << "Failed to write data to: " << path << "\n"; - std::exit(EXIT_FAILURE); - } - } -} - -void testrun(char* modelfile) { - static zdl::DlSystem::Runtime_t runtime = checkRuntime(); - std::unique_ptr container; - container = zdl::DlContainer::IDlContainer::open(modelfile); - - if (!container) { PrintErrorStringAndExit(); } - cout << "start build" << endl; - std::unique_ptr snpe; - { - snpe = NULL; - zdl::SNPE::SNPEBuilder snpeBuilder(container.get()); - snpe = snpeBuilder.setOutputLayers({}) - .setRuntimeProcessor(runtime) - .setUseUserSuppliedBuffers(false) - //.setDebugMode(true) - .build(); - if (!snpe) { - cout << "ERROR!" << endl; - const char* const errStr = zdl::DlSystem::getLastErrorString(); - std::cerr << errStr << std::endl; - } - cout << "ran snpeBuilder" << endl; - } - - const auto &strList_opt = snpe->getInputTensorNames(); - if (!strList_opt) throw std::runtime_error("Error obtaining input tensor names"); - cout << "get input tensor names done" << endl; - - const auto &strList = *strList_opt; - static zdl::DlSystem::TensorMap inputTensorMap; - static zdl::DlSystem::TensorMap outputTensorMap; - - assert(strList.size() == 1); - const auto &inputDims_opt = snpe->getInputDimensions(strList.at(0)); - const auto &inputShape = *inputDims_opt; - std::cout << "winkwink" << std::endl; - - for (int i=0; i<10000; i++) { - std::unique_ptr input; - input = zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(inputShape); - get_testframe(i, input); - snpe->execute(input.get(), outputTensorMap); - zdl::DlSystem::StringList tensorNames = outputTensorMap.getTensorNames(); - std::for_each(tensorNames.begin(), tensorNames.end(), [&](const char* name) { - std::ostringstream path; - path << "/data/opt/Result_" << std::to_string(i) << ".raw"; - auto tensorPtr = outputTensorMap.getTensor(name); - SaveITensor(path.str(), tensorPtr); - }); - } -} - -int main(int argc, char* argv[]) { - if (argc < 2) { - printf("usage: %s \n", argv[0]); - return -1; - } - - if (argc == 2) { - while (true) test(argv[1]); - } else if (argc == 3) { - testrun(argv[1]); - } - return 0; -} - diff --git a/selfdrive/modeld/tests/snpe_benchmark/benchmark.sh b/selfdrive/modeld/tests/snpe_benchmark/benchmark.sh deleted file mode 100755 index a9d3f79786a2b0..00000000000000 --- a/selfdrive/modeld/tests/snpe_benchmark/benchmark.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -e -clang++ -I /data/openpilot/third_party/snpe/include/ -L/data/pythonpath/third_party/snpe/aarch64 -lSNPE benchmark.cc -o benchmark -export LD_LIBRARY_PATH="/data/pythonpath/third_party/snpe/aarch64/:$HOME/openpilot/third_party/snpe/x86_64/:$LD_LIBRARY_PATH" -exec ./benchmark $1 diff --git a/selfdrive/modeld/tests/test_modeld.py b/selfdrive/modeld/tests/test_modeld.py deleted file mode 100644 index 1bf2977a919703..00000000000000 --- a/selfdrive/modeld/tests/test_modeld.py +++ /dev/null @@ -1,103 +0,0 @@ -import numpy as np -import random - -import cereal.messaging as messaging -from msgq.visionipc import VisionIpcServer, VisionStreamType -from opendbc.car.car_helpers import get_demo_car_params -from openpilot.common.params import Params -from openpilot.common.transformations.camera import DEVICE_CAMERAS -from openpilot.common.realtime import DT_MDL -from openpilot.selfdrive.car.card import convert_to_capnp -from openpilot.system.manager.process_config import managed_processes -from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state - -CAM = DEVICE_CAMERAS[("tici", "ar0231")].fcam -IMG = np.zeros(int(CAM.width*CAM.height*(3/2)), dtype=np.uint8) -IMG_BYTES = IMG.flatten().tobytes() - - -class TestModeld: - - def setup_method(self): - self.vipc_server = VisionIpcServer("camerad") - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, CAM.width, CAM.height) - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, False, CAM.width, CAM.height) - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, False, CAM.width, CAM.height) - self.vipc_server.start_listener() - Params().put("CarParams", convert_to_capnp(get_demo_car_params()).to_bytes()) - - self.sm = messaging.SubMaster(['modelV2', 'cameraOdometry']) - self.pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'liveCalibration']) - - managed_processes['modeld'].start() - self.pm.wait_for_readers_to_update("roadCameraState", 10) - - def teardown_method(self): - managed_processes['modeld'].stop() - del self.vipc_server - - def _send_frames(self, frame_id, cams=None): - if cams is None: - cams = ('roadCameraState', 'wideRoadCameraState') - - cs = None - for cam in cams: - msg = messaging.new_message(cam) - cs = getattr(msg, cam) - cs.frameId = frame_id - cs.timestampSof = int((frame_id * DT_MDL) * 1e9) - cs.timestampEof = int(cs.timestampSof + (DT_MDL * 1e9)) - cam_meta = meta_from_camera_state(cam) - - self.pm.send(msg.which(), msg) - self.vipc_server.send(cam_meta.stream, IMG_BYTES, cs.frameId, - cs.timestampSof, cs.timestampEof) - return cs - - def _wait(self): - self.sm.update(5000) - if self.sm['modelV2'].frameId != self.sm['cameraOdometry'].frameId: - self.sm.update(1000) - - def test_modeld(self): - for n in range(1, 500): - cs = self._send_frames(n) - self._wait() - - mdl = self.sm['modelV2'] - assert mdl.frameId == n - assert mdl.frameIdExtra == n - assert mdl.timestampEof == cs.timestampEof - assert mdl.frameAge == 0 - assert mdl.frameDropPerc == 0 - - odo = self.sm['cameraOdometry'] - assert odo.frameId == n - assert odo.timestampEof == cs.timestampEof - - def test_dropped_frames(self): - """ - modeld should only run on consecutive road frames - """ - frame_id = -1 - road_frames = list() - for n in range(1, 50): - if (random.random() < 0.1) and n > 3: - cams = random.choice([(), ('wideRoadCameraState', )]) - self._send_frames(n, cams) - else: - self._send_frames(n) - road_frames.append(n) - self._wait() - - if len(road_frames) < 3 or road_frames[-1] - road_frames[-2] == 1: - frame_id = road_frames[-1] - - mdl = self.sm['modelV2'] - odo = self.sm['cameraOdometry'] - assert mdl.frameId == frame_id - assert mdl.frameIdExtra == frame_id - assert odo.frameId == frame_id - if n != frame_id: - assert not self.sm.updated['modelV2'] - assert not self.sm.updated['cameraOdometry'] diff --git a/selfdrive/modeld/tests/tf_test/build.sh b/selfdrive/modeld/tests/tf_test/build.sh deleted file mode 100755 index df1d24761e9b07..00000000000000 --- a/selfdrive/modeld/tests/tf_test/build.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env bash -clang++ -I /home/batman/one/external/tensorflow/include/ -L /home/batman/one/external/tensorflow/lib -Wl,-rpath=/home/batman/one/external/tensorflow/lib main.cc -ltensorflow diff --git a/selfdrive/modeld/tests/tf_test/main.cc b/selfdrive/modeld/tests/tf_test/main.cc deleted file mode 100644 index b00f7f95e8db2e..00000000000000 --- a/selfdrive/modeld/tests/tf_test/main.cc +++ /dev/null @@ -1,69 +0,0 @@ -#include -#include -#include -#include "tensorflow/c/c_api.h" - -void* read_file(const char* path, size_t* out_len) { - FILE* f = fopen(path, "r"); - if (!f) { - return NULL; - } - fseek(f, 0, SEEK_END); - long f_len = ftell(f); - rewind(f); - - char* buf = (char*)calloc(f_len, 1); - assert(buf); - - size_t num_read = fread(buf, f_len, 1, f); - fclose(f); - - if (num_read != 1) { - free(buf); - return NULL; - } - - if (out_len) { - *out_len = f_len; - } - - return buf; -} - -static void DeallocateBuffer(void* data, size_t) { - free(data); -} - -int main(int argc, char* argv[]) { - TF_Buffer* buf; - TF_Graph* graph; - TF_Status* status; - char *path = argv[1]; - - // load model - { - size_t model_size; - char tmp[1024]; - snprintf(tmp, sizeof(tmp), "%s.pb", path); - printf("loading model %s\n", tmp); - uint8_t *model_data = (uint8_t *)read_file(tmp, &model_size); - buf = TF_NewBuffer(); - buf->data = model_data; - buf->length = model_size; - buf->data_deallocator = DeallocateBuffer; - printf("loaded model of size %d\n", model_size); - } - - // import graph - status = TF_NewStatus(); - graph = TF_NewGraph(); - TF_ImportGraphDefOptions *opts = TF_NewImportGraphDefOptions(); - TF_GraphImportGraphDef(graph, buf, opts, status); - TF_DeleteImportGraphDefOptions(opts); - TF_DeleteBuffer(buf); - if (TF_GetCode(status) != TF_OK) { - printf("FAIL: %s\n", TF_Message(status)); - } else { - printf("SUCCESS\n"); - } -} diff --git a/selfdrive/modeld/tests/tf_test/pb_loader.py b/selfdrive/modeld/tests/tf_test/pb_loader.py deleted file mode 100755 index 3e476628ebd0e7..00000000000000 --- a/selfdrive/modeld/tests/tf_test/pb_loader.py +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env python3 -import sys -import tensorflow as tf - -with open(sys.argv[1], "rb") as f: - graph_def = tf.compat.v1.GraphDef() - graph_def.ParseFromString(f.read()) - #tf.io.write_graph(graph_def, '', sys.argv[1]+".try") diff --git a/selfdrive/modeld/tests/timing/benchmark.py b/selfdrive/modeld/tests/timing/benchmark.py deleted file mode 100755 index c629ec2fff5050..00000000000000 --- a/selfdrive/modeld/tests/timing/benchmark.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python3 -# type: ignore - -import os -import time -import numpy as np - -import cereal.messaging as messaging -from openpilot.system.manager.process_config import managed_processes - - -N = int(os.getenv("N", "5")) -TIME = int(os.getenv("TIME", "30")) - -if __name__ == "__main__": - sock = messaging.sub_sock('modelV2', conflate=False, timeout=1000) - - execution_times = [] - - for _ in range(N): - os.environ['LOGPRINT'] = 'debug' - managed_processes['modeld'].start() - time.sleep(5) - - t = [] - start = time.monotonic() - while time.monotonic() - start < TIME: - msgs = messaging.drain_sock(sock, wait_for_one=True) - for m in msgs: - t.append(m.modelV2.modelExecutionTime) - - execution_times.append(np.array(t[10:]) * 1000) - managed_processes['modeld'].stop() - - print("\n\n") - print(f"ran modeld {N} times for {TIME}s each") - for _, t in enumerate(execution_times): - print(f"\tavg: {sum(t)/len(t):0.2f}ms, min: {min(t):0.2f}ms, max: {max(t):0.2f}ms") - print("\n\n") diff --git a/selfdrive/modeld/thneed/README b/selfdrive/modeld/thneed/README deleted file mode 100644 index f3bc66d8fc26ff..00000000000000 --- a/selfdrive/modeld/thneed/README +++ /dev/null @@ -1,8 +0,0 @@ -thneed is an SNPE accelerator. I know SNPE is already an accelerator, but sometimes things need to go even faster.. - -It runs on the local device, and caches a single model run. Then it replays it, but fast. - -thneed slices through abstraction layers like a fish. - -You need a thneed. - diff --git a/selfdrive/modeld/thneed/serialize.cc b/selfdrive/modeld/thneed/serialize.cc deleted file mode 100644 index 3dc2bef41448f8..00000000000000 --- a/selfdrive/modeld/thneed/serialize.cc +++ /dev/null @@ -1,154 +0,0 @@ -#include -#include - -#include "third_party/json11/json11.hpp" -#include "common/util.h" -#include "common/clutil.h" -#include "common/swaglog.h" -#include "selfdrive/modeld/thneed/thneed.h" -using namespace json11; - -extern map g_program_source; - -void Thneed::load(const char *filename) { - LOGD("Thneed::load: loading from %s\n", filename); - - string buf = util::read_file(filename); - int jsz = *(int *)buf.data(); - string jsonerr; - string jj(buf.data() + sizeof(int), jsz); - Json jdat = Json::parse(jj, jsonerr); - - map real_mem; - real_mem[NULL] = NULL; - - int ptr = sizeof(int)+jsz; - for (auto &obj : jdat["objects"].array_items()) { - auto mobj = obj.object_items(); - int sz = mobj["size"].int_value(); - cl_mem clbuf = NULL; - - if (mobj["buffer_id"].string_value().size() > 0) { - // image buffer must already be allocated - clbuf = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; - assert(mobj["needs_load"].bool_value() == false); - } else { - if (mobj["needs_load"].bool_value()) { - clbuf = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sz, &buf[ptr], NULL); - if (debug >= 1) printf("loading %p %d @ 0x%X\n", clbuf, sz, ptr); - ptr += sz; - } else { - // TODO: is there a faster way to init zeroed out buffers? - void *host_zeros = calloc(sz, 1); - clbuf = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sz, host_zeros, NULL); - free(host_zeros); - } - } - assert(clbuf != NULL); - - if (mobj["arg_type"] == "image2d_t" || mobj["arg_type"] == "image1d_t") { - cl_image_desc desc = {0}; - desc.image_type = (mobj["arg_type"] == "image2d_t") ? CL_MEM_OBJECT_IMAGE2D : CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = mobj["width"].int_value(); - desc.image_height = mobj["height"].int_value(); - desc.image_row_pitch = mobj["row_pitch"].int_value(); - assert(sz == desc.image_height*desc.image_row_pitch); -#ifdef QCOM2 - desc.buffer = clbuf; -#else - // TODO: we are creating unused buffers on PC - clReleaseMemObject(clbuf); -#endif - cl_image_format format = {0}; - format.image_channel_order = CL_RGBA; - format.image_channel_data_type = mobj["float32"].bool_value() ? CL_FLOAT : CL_HALF_FLOAT; - - cl_int errcode; - -#ifndef QCOM2 - if (mobj["needs_load"].bool_value()) { - clbuf = clCreateImage(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, &format, &desc, &buf[ptr-sz], &errcode); - } else { - clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &errcode); - } -#else - clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &errcode); -#endif - if (clbuf == NULL) { - LOGE("clError: %s create image %zux%zu rp %zu with buffer %p\n", cl_get_error_string(errcode), - desc.image_width, desc.image_height, desc.image_row_pitch, desc.buffer); - } - assert(clbuf != NULL); - } - - real_mem[*(cl_mem*)(mobj["id"].string_value().data())] = clbuf; - } - - map g_programs; - for (const auto &[name, source] : jdat["programs"].object_items()) { - if (debug >= 1) printf("building %s with size %zu\n", name.c_str(), source.string_value().size()); - g_programs[name] = cl_program_from_source(context, device_id, source.string_value()); - } - - for (auto &obj : jdat["inputs"].array_items()) { - auto mobj = obj.object_items(); - int sz = mobj["size"].int_value(); - cl_mem aa = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; - input_clmem.push_back(aa); - input_sizes.push_back(sz); - LOGD("Thneed::load: adding input %s with size %d\n", mobj["name"].string_value().data(), sz); - - cl_int cl_err; - void *ret = clEnqueueMapBuffer(command_queue, aa, CL_TRUE, CL_MAP_WRITE, 0, sz, 0, NULL, NULL, &cl_err); - if (cl_err != CL_SUCCESS) LOGE("clError: %s map %p %d\n", cl_get_error_string(cl_err), aa, sz); - assert(cl_err == CL_SUCCESS); - inputs.push_back(ret); - } - - for (auto &obj : jdat["outputs"].array_items()) { - auto mobj = obj.object_items(); - int sz = mobj["size"].int_value(); - LOGD("Thneed::save: adding output with size %d\n", sz); - // TODO: support multiple outputs - output = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; - assert(output != NULL); - } - - for (auto &obj : jdat["binaries"].array_items()) { - string name = obj["name"].string_value(); - size_t length = obj["length"].int_value(); - if (debug >= 1) printf("binary %s with size %zu\n", name.c_str(), length); - g_programs[name] = cl_program_from_binary(context, device_id, (const uint8_t*)&buf[ptr], length); - ptr += length; - } - - for (auto &obj : jdat["kernels"].array_items()) { - auto gws = obj["global_work_size"]; - auto lws = obj["local_work_size"]; - auto kk = shared_ptr(new CLQueuedKernel(this)); - - kk->name = obj["name"].string_value(); - kk->program = g_programs[kk->name]; - kk->work_dim = obj["work_dim"].int_value(); - for (int i = 0; i < kk->work_dim; i++) { - kk->global_work_size[i] = gws[i].int_value(); - kk->local_work_size[i] = lws[i].int_value(); - } - kk->num_args = obj["num_args"].int_value(); - for (int i = 0; i < kk->num_args; i++) { - string arg = obj["args"].array_items()[i].string_value(); - int arg_size = obj["args_size"].array_items()[i].int_value(); - kk->args_size.push_back(arg_size); - if (arg_size == 8) { - cl_mem val = *(cl_mem*)(arg.data()); - val = real_mem[val]; - kk->args.push_back(string((char*)&val, sizeof(val))); - } else { - kk->args.push_back(arg); - } - } - kq.push_back(kk); - } - - clFinish(command_queue); -} diff --git a/selfdrive/modeld/thneed/thneed.h b/selfdrive/modeld/thneed/thneed.h deleted file mode 100644 index 47e18e0be3bb30..00000000000000 --- a/selfdrive/modeld/thneed/thneed.h +++ /dev/null @@ -1,133 +0,0 @@ -#pragma once - -#ifndef __user -#define __user __attribute__(()) -#endif - -#include -#include -#include -#include -#include - -#include - -#include "third_party/linux/include/msm_kgsl.h" - -using namespace std; - -cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value); - -namespace json11 { - class Json; -} -class Thneed; - -class GPUMalloc { - public: - GPUMalloc(int size, int fd); - ~GPUMalloc(); - void *alloc(int size); - private: - uint64_t base; - int remaining; -}; - -class CLQueuedKernel { - public: - CLQueuedKernel(Thneed *lthneed) { thneed = lthneed; } - CLQueuedKernel(Thneed *lthneed, - cl_kernel _kernel, - cl_uint _work_dim, - const size_t *_global_work_size, - const size_t *_local_work_size); - cl_int exec(); - void debug_print(bool verbose); - int get_arg_num(const char *search_arg_name); - cl_program program; - string name; - cl_uint num_args; - vector arg_names; - vector arg_types; - vector args; - vector args_size; - cl_kernel kernel = NULL; - json11::Json to_json() const; - - cl_uint work_dim; - size_t global_work_size[3] = {0}; - size_t local_work_size[3] = {0}; - private: - Thneed *thneed; -}; - -class CachedIoctl { - public: - virtual void exec() {} -}; - -class CachedSync: public CachedIoctl { - public: - CachedSync(Thneed *lthneed, string ldata) { thneed = lthneed; data = ldata; } - void exec(); - private: - Thneed *thneed; - string data; -}; - -class CachedCommand: public CachedIoctl { - public: - CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd); - void exec(); - private: - void disassemble(int cmd_index); - struct kgsl_gpu_command cache; - unique_ptr cmds; - unique_ptr objs; - Thneed *thneed; - vector > kq; -}; - -class Thneed { - public: - Thneed(bool do_clinit=false, cl_context _context = NULL); - void stop(); - void execute(float **finputs, float *foutput, bool slow=false); - void wait(); - - vector input_clmem; - vector inputs; - vector input_sizes; - cl_mem output = NULL; - - cl_context context = NULL; - cl_command_queue command_queue; - cl_device_id device_id; - int context_id; - - // protected? - bool record = false; - int debug; - int timestamp; - -#ifdef QCOM2 - unique_ptr ram; - vector > cmds; - int fd; -#endif - - // all CL kernels - void copy_inputs(float **finputs, bool internal=false); - void copy_output(float *foutput); - cl_int clexec(); - vector > kq; - - // pending CL kernels - vector > ckq; - - // loading - void load(const char *filename); - private: - void clinit(); -}; - diff --git a/selfdrive/modeld/thneed/thneed_common.cc b/selfdrive/modeld/thneed/thneed_common.cc deleted file mode 100644 index ecdf1237e384ff..00000000000000 --- a/selfdrive/modeld/thneed/thneed_common.cc +++ /dev/null @@ -1,216 +0,0 @@ -#include "selfdrive/modeld/thneed/thneed.h" - -#include -#include -#include - -#include "common/clutil.h" -#include "common/timing.h" - -map, string> g_args; -map, int> g_args_size; -map g_program_source; - -void Thneed::stop() { - //printf("Thneed::stop: recorded %lu commands\n", cmds.size()); - record = false; -} - -void Thneed::clinit() { - device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); - if (context == NULL) context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); - //cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0}; - cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, 0, 0}; - command_queue = CL_CHECK_ERR(clCreateCommandQueueWithProperties(context, device_id, props, &err)); - printf("Thneed::clinit done\n"); -} - -cl_int Thneed::clexec() { - if (debug >= 1) printf("Thneed::clexec: running %lu queued kernels\n", kq.size()); - for (auto &k : kq) { - if (record) ckq.push_back(k); - cl_int ret = k->exec(); - assert(ret == CL_SUCCESS); - } - return clFinish(command_queue); -} - -void Thneed::copy_inputs(float **finputs, bool internal) { - for (int idx = 0; idx < inputs.size(); ++idx) { - if (debug >= 1) printf("copying %lu -- %p -> %p (cl %p)\n", input_sizes[idx], finputs[idx], inputs[idx], input_clmem[idx]); - - if (internal) { - // if it's internal, using memcpy is fine since the buffer sync is cached in the ioctl layer - if (finputs[idx] != NULL) memcpy(inputs[idx], finputs[idx], input_sizes[idx]); - } else { - if (finputs[idx] != NULL) CL_CHECK(clEnqueueWriteBuffer(command_queue, input_clmem[idx], CL_TRUE, 0, input_sizes[idx], finputs[idx], 0, NULL, NULL)); - } - } -} - -void Thneed::copy_output(float *foutput) { - if (output != NULL) { - size_t sz; - clGetMemObjectInfo(output, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - if (debug >= 1) printf("copying %lu for output %p -> %p\n", sz, output, foutput); - CL_CHECK(clEnqueueReadBuffer(command_queue, output, CL_TRUE, 0, sz, foutput, 0, NULL, NULL)); - } else { - printf("CAUTION: model output is NULL, does it have no outputs?\n"); - } -} - -// *********** CLQueuedKernel *********** - -CLQueuedKernel::CLQueuedKernel(Thneed *lthneed, - cl_kernel _kernel, - cl_uint _work_dim, - const size_t *_global_work_size, - const size_t *_local_work_size) { - thneed = lthneed; - kernel = _kernel; - work_dim = _work_dim; - assert(work_dim <= 3); - for (int i = 0; i < work_dim; i++) { - global_work_size[i] = _global_work_size[i]; - local_work_size[i] = _local_work_size[i]; - } - - char _name[0x100]; - clGetKernelInfo(kernel, CL_KERNEL_FUNCTION_NAME, sizeof(_name), _name, NULL); - name = string(_name); - clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS, sizeof(num_args), &num_args, NULL); - - // get args - for (int i = 0; i < num_args; i++) { - char arg_name[0x100] = {0}; - clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); - arg_names.push_back(string(arg_name)); - clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); - arg_types.push_back(string(arg_name)); - - args.push_back(g_args[make_pair(kernel, i)]); - args_size.push_back(g_args_size[make_pair(kernel, i)]); - } - - // get program - clGetKernelInfo(kernel, CL_KERNEL_PROGRAM, sizeof(program), &program, NULL); -} - -int CLQueuedKernel::get_arg_num(const char *search_arg_name) { - for (int i = 0; i < num_args; i++) { - if (arg_names[i] == search_arg_name) return i; - } - printf("failed to find %s in %s\n", search_arg_name, name.c_str()); - assert(false); -} - -cl_int CLQueuedKernel::exec() { - if (kernel == NULL) { - kernel = clCreateKernel(program, name.c_str(), NULL); - arg_names.clear(); - arg_types.clear(); - - for (int j = 0; j < num_args; j++) { - char arg_name[0x100] = {0}; - clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); - arg_names.push_back(string(arg_name)); - clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); - arg_types.push_back(string(arg_name)); - - cl_int ret; - if (args[j].size() != 0) { - assert(args[j].size() == args_size[j]); - ret = thneed_clSetKernelArg(kernel, j, args[j].size(), args[j].data()); - } else { - ret = thneed_clSetKernelArg(kernel, j, args_size[j], NULL); - } - assert(ret == CL_SUCCESS); - } - } - - if (thneed->debug >= 1) { - debug_print(thneed->debug >= 2); - } - - return clEnqueueNDRangeKernel(thneed->command_queue, - kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, NULL); -} - -void CLQueuedKernel::debug_print(bool verbose) { - printf("%p %56s -- ", kernel, name.c_str()); - for (int i = 0; i < work_dim; i++) { - printf("%4zu ", global_work_size[i]); - } - printf(" -- "); - for (int i = 0; i < work_dim; i++) { - printf("%4zu ", local_work_size[i]); - } - printf("\n"); - - if (verbose) { - for (int i = 0; i < num_args; i++) { - string arg = args[i]; - printf(" %s %s", arg_types[i].c_str(), arg_names[i].c_str()); - void *arg_value = (void*)arg.data(); - int arg_size = arg.size(); - if (arg_size == 0) { - printf(" (size) %d", args_size[i]); - } else if (arg_size == 1) { - printf(" = %d", *((char*)arg_value)); - } else if (arg_size == 2) { - printf(" = %d", *((short*)arg_value)); - } else if (arg_size == 4) { - if (arg_types[i] == "float") { - printf(" = %f", *((float*)arg_value)); - } else { - printf(" = %d", *((int*)arg_value)); - } - } else if (arg_size == 8) { - cl_mem val = (cl_mem)(*((uintptr_t*)arg_value)); - printf(" = %p", val); - if (val != NULL) { - cl_mem_object_type obj_type; - clGetMemObjectInfo(val, CL_MEM_TYPE, sizeof(obj_type), &obj_type, NULL); - if (arg_types[i] == "image2d_t" || arg_types[i] == "image1d_t" || obj_type == CL_MEM_OBJECT_IMAGE2D) { - cl_image_format format; - size_t width, height, depth, array_size, row_pitch, slice_pitch; - cl_mem buf; - clGetImageInfo(val, CL_IMAGE_FORMAT, sizeof(format), &format, NULL); - assert(format.image_channel_order == CL_RGBA); - assert(format.image_channel_data_type == CL_HALF_FLOAT || format.image_channel_data_type == CL_FLOAT); - clGetImageInfo(val, CL_IMAGE_WIDTH, sizeof(width), &width, NULL); - clGetImageInfo(val, CL_IMAGE_HEIGHT, sizeof(height), &height, NULL); - clGetImageInfo(val, CL_IMAGE_ROW_PITCH, sizeof(row_pitch), &row_pitch, NULL); - clGetImageInfo(val, CL_IMAGE_DEPTH, sizeof(depth), &depth, NULL); - clGetImageInfo(val, CL_IMAGE_ARRAY_SIZE, sizeof(array_size), &array_size, NULL); - clGetImageInfo(val, CL_IMAGE_SLICE_PITCH, sizeof(slice_pitch), &slice_pitch, NULL); - assert(depth == 0); - assert(array_size == 0); - assert(slice_pitch == 0); - - clGetImageInfo(val, CL_IMAGE_BUFFER, sizeof(buf), &buf, NULL); - size_t sz = 0; - if (buf != NULL) clGetMemObjectInfo(buf, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - printf(" image %zu x %zu rp %zu @ %p buffer %zu", width, height, row_pitch, buf, sz); - } else { - size_t sz; - clGetMemObjectInfo(val, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - printf(" buffer %zu", sz); - } - } - } - printf("\n"); - } - } -} - -cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value) { - g_args_size[make_pair(kernel, arg_index)] = arg_size; - if (arg_value != NULL) { - g_args[make_pair(kernel, arg_index)] = string((char*)arg_value, arg_size); - } else { - g_args[make_pair(kernel, arg_index)] = string(""); - } - cl_int ret = clSetKernelArg(kernel, arg_index, arg_size, arg_value); - return ret; -} diff --git a/selfdrive/modeld/thneed/thneed_pc.cc b/selfdrive/modeld/thneed/thneed_pc.cc deleted file mode 100644 index 8d0037628e2f3d..00000000000000 --- a/selfdrive/modeld/thneed/thneed_pc.cc +++ /dev/null @@ -1,32 +0,0 @@ -#include "selfdrive/modeld/thneed/thneed.h" - -#include - -#include "common/clutil.h" -#include "common/timing.h" - -Thneed::Thneed(bool do_clinit, cl_context _context) { - context = _context; - if (do_clinit) clinit(); - char *thneed_debug_env = getenv("THNEED_DEBUG"); - debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0; -} - -void Thneed::execute(float **finputs, float *foutput, bool slow) { - uint64_t tb, te; - if (debug >= 1) tb = nanos_since_boot(); - - // ****** copy inputs - copy_inputs(finputs); - - // ****** run commands - clexec(); - - // ****** copy outputs - copy_output(foutput); - - if (debug >= 1) { - te = nanos_since_boot(); - printf("model exec in %lu us\n", (te-tb)/1000); - } -} diff --git a/selfdrive/modeld/thneed/thneed_qcom2.cc b/selfdrive/modeld/thneed/thneed_qcom2.cc deleted file mode 100644 index 21de15d17c9cfc..00000000000000 --- a/selfdrive/modeld/thneed/thneed_qcom2.cc +++ /dev/null @@ -1,258 +0,0 @@ -#include "selfdrive/modeld/thneed/thneed.h" - -#include -#include - -#include -#include -#include -#include -#include - -#include "common/clutil.h" -#include "common/timing.h" - -Thneed *g_thneed = NULL; -int g_fd = -1; - -void hexdump(uint8_t *d, int len) { - assert((len%4) == 0); - printf(" dumping %p len 0x%x\n", d, len); - for (int i = 0; i < len/4; i++) { - if (i != 0 && (i%0x10) == 0) printf("\n"); - printf("%8x ", d[i]); - } - printf("\n"); -} - -// *********** ioctl interceptor *********** - -extern "C" { - -int (*my_ioctl)(int filedes, unsigned long request, void *argp) = NULL; -#undef ioctl -int ioctl(int filedes, unsigned long request, void *argp) { - request &= 0xFFFFFFFF; // needed on QCOM2 - if (my_ioctl == NULL) my_ioctl = reinterpret_cast(dlsym(RTLD_NEXT, "ioctl")); - Thneed *thneed = g_thneed; - - // save the fd - if (request == IOCTL_KGSL_GPUOBJ_ALLOC) g_fd = filedes; - - // note that this runs always, even without a thneed object - if (request == IOCTL_KGSL_DRAWCTXT_CREATE) { - struct kgsl_drawctxt_create *create = (struct kgsl_drawctxt_create *)argp; - create->flags &= ~KGSL_CONTEXT_PRIORITY_MASK; - create->flags |= 6 << KGSL_CONTEXT_PRIORITY_SHIFT; // priority from 1-15, 1 is max priority - printf("IOCTL_KGSL_DRAWCTXT_CREATE: creating context with flags 0x%x\n", create->flags); - } - - if (thneed != NULL) { - if (request == IOCTL_KGSL_GPU_COMMAND) { - struct kgsl_gpu_command *cmd = (struct kgsl_gpu_command *)argp; - if (thneed->record) { - thneed->timestamp = cmd->timestamp; - thneed->context_id = cmd->context_id; - thneed->cmds.push_back(unique_ptr(new CachedCommand(thneed, cmd))); - } - if (thneed->debug >= 1) { - printf("IOCTL_KGSL_GPU_COMMAND(%2zu): flags: 0x%lx context_id: %u timestamp: %u numcmds: %d numobjs: %d\n", - thneed->cmds.size(), - cmd->flags, - cmd->context_id, cmd->timestamp, cmd->numcmds, cmd->numobjs); - } - } else if (request == IOCTL_KGSL_GPUOBJ_SYNC) { - struct kgsl_gpuobj_sync *cmd = (struct kgsl_gpuobj_sync *)argp; - struct kgsl_gpuobj_sync_obj *objs = (struct kgsl_gpuobj_sync_obj *)(cmd->objs); - - if (thneed->debug >= 2) { - printf("IOCTL_KGSL_GPUOBJ_SYNC count:%d ", cmd->count); - for (int i = 0; i < cmd->count; i++) { - printf(" -- offset:0x%lx len:0x%lx id:%d op:%d ", objs[i].offset, objs[i].length, objs[i].id, objs[i].op); - } - printf("\n"); - } - - if (thneed->record) { - thneed->cmds.push_back(unique_ptr(new - CachedSync(thneed, string((char *)objs, sizeof(struct kgsl_gpuobj_sync_obj)*cmd->count)))); - } - } else if (request == IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID) { - struct kgsl_device_waittimestamp_ctxtid *cmd = (struct kgsl_device_waittimestamp_ctxtid *)argp; - if (thneed->debug >= 1) { - printf("IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID: context_id: %d timestamp: %d timeout: %d\n", - cmd->context_id, cmd->timestamp, cmd->timeout); - } - } else if (request == IOCTL_KGSL_SETPROPERTY) { - if (thneed->debug >= 1) { - struct kgsl_device_getproperty *prop = (struct kgsl_device_getproperty *)argp; - printf("IOCTL_KGSL_SETPROPERTY: 0x%x sizebytes:%zu\n", prop->type, prop->sizebytes); - if (thneed->debug >= 2) { - hexdump((uint8_t *)prop->value, prop->sizebytes); - if (prop->type == KGSL_PROP_PWR_CONSTRAINT) { - struct kgsl_device_constraint *constraint = (struct kgsl_device_constraint *)prop->value; - hexdump((uint8_t *)constraint->data, constraint->size); - } - } - } - } else if (request == IOCTL_KGSL_DRAWCTXT_CREATE || request == IOCTL_KGSL_DRAWCTXT_DESTROY) { - // this happens - } else if (request == IOCTL_KGSL_GPUOBJ_ALLOC || request == IOCTL_KGSL_GPUOBJ_FREE) { - // this happens - } else { - if (thneed->debug >= 1) { - printf("other ioctl %lx\n", request); - } - } - } - - int ret = my_ioctl(filedes, request, argp); - // NOTE: This error message goes into stdout and messes up pyenv - // if (ret != 0) printf("ioctl returned %d with errno %d\n", ret, errno); - return ret; -} - -} - -// *********** GPUMalloc *********** - -GPUMalloc::GPUMalloc(int size, int fd) { - struct kgsl_gpuobj_alloc alloc; - memset(&alloc, 0, sizeof(alloc)); - alloc.size = size; - alloc.flags = 0x10000a00; - ioctl(fd, IOCTL_KGSL_GPUOBJ_ALLOC, &alloc); - void *addr = mmap64(NULL, alloc.mmapsize, 0x3, 0x1, fd, alloc.id*0x1000); - assert(addr != MAP_FAILED); - - base = (uint64_t)addr; - remaining = size; -} - -GPUMalloc::~GPUMalloc() { - // TODO: free the GPU malloced area -} - -void *GPUMalloc::alloc(int size) { - void *ret = (void*)base; - size = (size+0xff) & (~0xFF); - assert(size <= remaining); - remaining -= size; - base += size; - return ret; -} - -// *********** CachedSync, at the ioctl layer *********** - -void CachedSync::exec() { - struct kgsl_gpuobj_sync cmd; - - cmd.objs = (uint64_t)data.data(); - cmd.obj_len = data.length(); - cmd.count = data.length() / sizeof(struct kgsl_gpuobj_sync_obj); - - int ret = ioctl(thneed->fd, IOCTL_KGSL_GPUOBJ_SYNC, &cmd); - assert(ret == 0); -} - -// *********** CachedCommand, at the ioctl layer *********** - -CachedCommand::CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd) { - thneed = lthneed; - assert(cmd->numsyncs == 0); - - memcpy(&cache, cmd, sizeof(cache)); - - if (cmd->numcmds > 0) { - cmds = make_unique(cmd->numcmds); - memcpy(cmds.get(), (void *)cmd->cmdlist, sizeof(struct kgsl_command_object)*cmd->numcmds); - cache.cmdlist = (uint64_t)cmds.get(); - for (int i = 0; i < cmd->numcmds; i++) { - void *nn = thneed->ram->alloc(cmds[i].size); - memcpy(nn, (void*)cmds[i].gpuaddr, cmds[i].size); - cmds[i].gpuaddr = (uint64_t)nn; - } - } - - if (cmd->numobjs > 0) { - objs = make_unique(cmd->numobjs); - memcpy(objs.get(), (void *)cmd->objlist, sizeof(struct kgsl_command_object)*cmd->numobjs); - cache.objlist = (uint64_t)objs.get(); - for (int i = 0; i < cmd->numobjs; i++) { - void *nn = thneed->ram->alloc(objs[i].size); - memset(nn, 0, objs[i].size); - objs[i].gpuaddr = (uint64_t)nn; - } - } - - kq = thneed->ckq; - thneed->ckq.clear(); -} - -void CachedCommand::exec() { - cache.timestamp = ++thneed->timestamp; - int ret = ioctl(thneed->fd, IOCTL_KGSL_GPU_COMMAND, &cache); - - if (thneed->debug >= 1) printf("CachedCommand::exec got %d\n", ret); - - if (thneed->debug >= 2) { - for (auto &it : kq) { - it->debug_print(false); - } - } - - assert(ret == 0); -} - -// *********** Thneed *********** - -Thneed::Thneed(bool do_clinit, cl_context _context) { - // TODO: QCOM2 actually requires a different context - //context = _context; - if (do_clinit) clinit(); - assert(g_fd != -1); - fd = g_fd; - ram = make_unique(0x80000, fd); - timestamp = -1; - g_thneed = this; - char *thneed_debug_env = getenv("THNEED_DEBUG"); - debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0; -} - -void Thneed::wait() { - struct kgsl_device_waittimestamp_ctxtid wait; - wait.context_id = context_id; - wait.timestamp = timestamp; - wait.timeout = -1; - - uint64_t tb = nanos_since_boot(); - int wret = ioctl(fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait); - uint64_t te = nanos_since_boot(); - - if (debug >= 1) printf("wait %d after %lu us\n", wret, (te-tb)/1000); -} - -void Thneed::execute(float **finputs, float *foutput, bool slow) { - uint64_t tb, te; - if (debug >= 1) tb = nanos_since_boot(); - - // ****** copy inputs - copy_inputs(finputs, true); - - // ****** run commands - int i = 0; - for (auto &it : cmds) { - ++i; - if (debug >= 1) printf("run %2d @ %7lu us: ", i, (nanos_since_boot()-tb)/1000); - it->exec(); - if ((i == cmds.size()) || slow) wait(); - } - - // ****** copy outputs - copy_output(foutput); - - if (debug >= 1) { - te = nanos_since_boot(); - printf("model exec in %lu us\n", (te-tb)/1000); - } -} diff --git a/selfdrive/modeld/transforms/loadyuv.cc b/selfdrive/modeld/transforms/loadyuv.cc deleted file mode 100644 index c7ce7b0830aa4f..00000000000000 --- a/selfdrive/modeld/transforms/loadyuv.cc +++ /dev/null @@ -1,74 +0,0 @@ -#include "selfdrive/modeld/transforms/loadyuv.h" - -#include -#include -#include - -void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height) { - memset(s, 0, sizeof(*s)); - - s->width = width; - s->height = height; - - char args[1024]; - snprintf(args, sizeof(args), - "-cl-fast-relaxed-math -cl-denorms-are-zero " - "-DTRANSFORMED_WIDTH=%d -DTRANSFORMED_HEIGHT=%d", - width, height); - cl_program prg = cl_program_from_file(ctx, device_id, LOADYUV_PATH, args); - - s->loadys_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loadys", &err)); - s->loaduv_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loaduv", &err)); - s->copy_krnl = CL_CHECK_ERR(clCreateKernel(prg, "copy", &err)); - - // done with this - CL_CHECK(clReleaseProgram(prg)); -} - -void loadyuv_destroy(LoadYUVState* s) { - CL_CHECK(clReleaseKernel(s->loadys_krnl)); - CL_CHECK(clReleaseKernel(s->loaduv_krnl)); - CL_CHECK(clReleaseKernel(s->copy_krnl)); -} - -void loadyuv_queue(LoadYUVState* s, cl_command_queue q, - cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, - cl_mem out_cl, bool do_shift) { - cl_int global_out_off = 0; - if (do_shift) { - // shift the image in slot 1 to slot 0, then place the new image in slot 1 - global_out_off += (s->width*s->height) + (s->width/2)*(s->height/2)*2; - CL_CHECK(clSetKernelArg(s->copy_krnl, 0, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->copy_krnl, 1, sizeof(cl_int), &global_out_off)); - const size_t copy_work_size = global_out_off/8; - CL_CHECK(clEnqueueNDRangeKernel(q, s->copy_krnl, 1, NULL, - ©_work_size, NULL, 0, 0, NULL)); - } - - CL_CHECK(clSetKernelArg(s->loadys_krnl, 0, sizeof(cl_mem), &y_cl)); - CL_CHECK(clSetKernelArg(s->loadys_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loadys_krnl, 2, sizeof(cl_int), &global_out_off)); - - const size_t loadys_work_size = (s->width*s->height)/8; - CL_CHECK(clEnqueueNDRangeKernel(q, s->loadys_krnl, 1, NULL, - &loadys_work_size, NULL, 0, 0, NULL)); - - const size_t loaduv_work_size = ((s->width/2)*(s->height/2))/8; - global_out_off += (s->width*s->height); - - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &u_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); - - CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, - &loaduv_work_size, NULL, 0, 0, NULL)); - - global_out_off += (s->width/2)*(s->height/2); - - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &v_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); - - CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, - &loaduv_work_size, NULL, 0, 0, NULL)); -} diff --git a/selfdrive/modeld/transforms/loadyuv.cl b/selfdrive/modeld/transforms/loadyuv.cl deleted file mode 100644 index 7dd3d973a3ef69..00000000000000 --- a/selfdrive/modeld/transforms/loadyuv.cl +++ /dev/null @@ -1,47 +0,0 @@ -#define UV_SIZE ((TRANSFORMED_WIDTH/2)*(TRANSFORMED_HEIGHT/2)) - -__kernel void loadys(__global uchar8 const * const Y, - __global float * out, - int out_offset) -{ - const int gid = get_global_id(0); - const int ois = gid * 8; - const int oy = ois / TRANSFORMED_WIDTH; - const int ox = ois % TRANSFORMED_WIDTH; - - const uchar8 ys = Y[gid]; - const float8 ysf = convert_float8(ys); - - // 02 - // 13 - - __global float* outy0; - __global float* outy1; - if ((oy & 1) == 0) { - outy0 = out + out_offset; //y0 - outy1 = out + out_offset + UV_SIZE*2; //y2 - } else { - outy0 = out + out_offset + UV_SIZE; //y1 - outy1 = out + out_offset + UV_SIZE*3; //y3 - } - - vstore4(ysf.s0246, 0, outy0 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); - vstore4(ysf.s1357, 0, outy1 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); -} - -__kernel void loaduv(__global uchar8 const * const in, - __global float8 * out, - int out_offset) -{ - const int gid = get_global_id(0); - const uchar8 inv = in[gid]; - const float8 outv = convert_float8(inv); - out[gid + out_offset / 8] = outv; -} - -__kernel void copy(__global float8 * inout, - int in_offset) -{ - const int gid = get_global_id(0); - inout[gid] = inout[gid + in_offset / 8]; -} diff --git a/selfdrive/modeld/transforms/loadyuv.h b/selfdrive/modeld/transforms/loadyuv.h deleted file mode 100644 index 7d27ef5d468dba..00000000000000 --- a/selfdrive/modeld/transforms/loadyuv.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "common/clutil.h" - -typedef struct { - int width, height; - cl_kernel loadys_krnl, loaduv_krnl, copy_krnl; -} LoadYUVState; - -void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height); - -void loadyuv_destroy(LoadYUVState* s); - -void loadyuv_queue(LoadYUVState* s, cl_command_queue q, - cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, - cl_mem out_cl, bool do_shift = false); diff --git a/selfdrive/modeld/transforms/transform.cc b/selfdrive/modeld/transforms/transform.cc deleted file mode 100644 index 305643cf42eaf6..00000000000000 --- a/selfdrive/modeld/transforms/transform.cc +++ /dev/null @@ -1,97 +0,0 @@ -#include "selfdrive/modeld/transforms/transform.h" - -#include -#include - -#include "common/clutil.h" - -void transform_init(Transform* s, cl_context ctx, cl_device_id device_id) { - memset(s, 0, sizeof(*s)); - - cl_program prg = cl_program_from_file(ctx, device_id, TRANSFORM_PATH, ""); - s->krnl = CL_CHECK_ERR(clCreateKernel(prg, "warpPerspective", &err)); - // done with this - CL_CHECK(clReleaseProgram(prg)); - - s->m_y_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); - s->m_uv_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); -} - -void transform_destroy(Transform* s) { - CL_CHECK(clReleaseMemObject(s->m_y_cl)); - CL_CHECK(clReleaseMemObject(s->m_uv_cl)); - CL_CHECK(clReleaseKernel(s->krnl)); -} - -void transform_queue(Transform* s, - cl_command_queue q, - cl_mem in_yuv, int in_width, int in_height, int in_stride, int in_uv_offset, - cl_mem out_y, cl_mem out_u, cl_mem out_v, - int out_width, int out_height, - const mat3& projection) { - const int zero = 0; - - // sampled using pixel center origin - // (because that's how fastcv and opencv does it) - - mat3 projection_y = projection; - - // in and out uv is half the size of y. - mat3 projection_uv = transform_scale_buffer(projection, 0.5); - - CL_CHECK(clEnqueueWriteBuffer(q, s->m_y_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_y.v, 0, NULL, NULL)); - CL_CHECK(clEnqueueWriteBuffer(q, s->m_uv_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_uv.v, 0, NULL, NULL)); - - const int in_y_width = in_width; - const int in_y_height = in_height; - const int in_y_px_stride = 1; - const int in_uv_width = in_width/2; - const int in_uv_height = in_height/2; - const int in_uv_px_stride = 2; - const int in_u_offset = in_uv_offset; - const int in_v_offset = in_uv_offset + 1; - - const int out_y_width = out_width; - const int out_y_height = out_height; - const int out_uv_width = out_width/2; - const int out_uv_height = out_height/2; - - CL_CHECK(clSetKernelArg(s->krnl, 0, sizeof(cl_mem), &in_yuv)); // src - CL_CHECK(clSetKernelArg(s->krnl, 1, sizeof(cl_int), &in_stride)); // src_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_y_px_stride)); // src_px_stride - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &zero)); // src_offset - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_y_height)); // src_rows - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_y_width)); // src_cols - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_y)); // dst - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_y_width)); // dst_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_y_height)); // dst_rows - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_y_width)); // dst_cols - CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_y_cl)); // M - - const size_t work_size_y[2] = {(size_t)out_y_width, (size_t)out_y_height}; - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_y, NULL, 0, 0, NULL)); - - const size_t work_size_uv[2] = {(size_t)out_uv_width, (size_t)out_uv_height}; - - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_uv_px_stride)); // src_px_stride - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_u_offset)); // src_offset - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_uv_height)); // src_rows - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_uv_width)); // src_cols - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_u)); // dst - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_uv_width)); // dst_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_uv_height)); // dst_rows - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_uv_width)); // dst_cols - CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_uv_cl)); // M - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_v_offset)); // src_ofset - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_v)); // dst - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); -} diff --git a/selfdrive/modeld/transforms/transform.cl b/selfdrive/modeld/transforms/transform.cl deleted file mode 100644 index 2ca25920cd19be..00000000000000 --- a/selfdrive/modeld/transforms/transform.cl +++ /dev/null @@ -1,54 +0,0 @@ -#define INTER_BITS 5 -#define INTER_TAB_SIZE (1 << INTER_BITS) -#define INTER_SCALE 1.f / INTER_TAB_SIZE - -#define INTER_REMAP_COEF_BITS 15 -#define INTER_REMAP_COEF_SCALE (1 << INTER_REMAP_COEF_BITS) - -__kernel void warpPerspective(__global const uchar * src, - int src_row_stride, int src_px_stride, int src_offset, int src_rows, int src_cols, - __global uchar * dst, - int dst_row_stride, int dst_offset, int dst_rows, int dst_cols, - __constant float * M) -{ - int dx = get_global_id(0); - int dy = get_global_id(1); - - if (dx < dst_cols && dy < dst_rows) - { - float X0 = M[0] * dx + M[1] * dy + M[2]; - float Y0 = M[3] * dx + M[4] * dy + M[5]; - float W = M[6] * dx + M[7] * dy + M[8]; - W = W != 0.0f ? INTER_TAB_SIZE / W : 0.0f; - int X = rint(X0 * W), Y = rint(Y0 * W); - - int sx = convert_short_sat(X >> INTER_BITS); - int sy = convert_short_sat(Y >> INTER_BITS); - - short sx_clamp = clamp(sx, 0, src_cols - 1); - short sx_p1_clamp = clamp(sx + 1, 0, src_cols - 1); - short sy_clamp = clamp(sy, 0, src_rows - 1); - short sy_p1_clamp = clamp(sy + 1, 0, src_rows - 1); - int v0 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); - int v1 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); - int v2 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); - int v3 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); - - short ay = (short)(Y & (INTER_TAB_SIZE - 1)); - short ax = (short)(X & (INTER_TAB_SIZE - 1)); - float taby = 1.f/INTER_TAB_SIZE*ay; - float tabx = 1.f/INTER_TAB_SIZE*ax; - - int dst_index = mad24(dy, dst_row_stride, dst_offset + dx); - - int itab0 = convert_short_sat_rte( (1.0f-taby)*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); - int itab1 = convert_short_sat_rte( (1.0f-taby)*tabx * INTER_REMAP_COEF_SCALE ); - int itab2 = convert_short_sat_rte( taby*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); - int itab3 = convert_short_sat_rte( taby*tabx * INTER_REMAP_COEF_SCALE ); - - int val = v0 * itab0 + v1 * itab1 + v2 * itab2 + v3 * itab3; - - uchar pix = convert_uchar_sat((val + (1 << (INTER_REMAP_COEF_BITS-1))) >> INTER_REMAP_COEF_BITS); - dst[dst_index] = pix; - } -} diff --git a/selfdrive/modeld/transforms/transform.h b/selfdrive/modeld/transforms/transform.h deleted file mode 100644 index 771a7054b35d29..00000000000000 --- a/selfdrive/modeld/transforms/transform.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "common/mat.h" - -typedef struct { - cl_kernel krnl; - cl_mem m_y_cl, m_uv_cl; -} Transform; - -void transform_init(Transform* s, cl_context ctx, cl_device_id device_id); - -void transform_destroy(Transform* transform); - -void transform_queue(Transform* s, cl_command_queue q, - cl_mem yuv, int in_width, int in_height, int in_stride, int in_uv_offset, - cl_mem out_y, cl_mem out_u, cl_mem out_v, - int out_width, int out_height, - const mat3& projection); diff --git a/selfdrive/monitoring/README.md b/selfdrive/monitoring/README.md deleted file mode 100644 index 2a29ea06b5a306..00000000000000 --- a/selfdrive/monitoring/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# driver monitoring (DM) - -Uploading driver-facing camera footage is opt-in, but it is encouraged to opt-in to improve the DM model. You can always change your preference using the "Record and Upload Driver Camera" toggle. - -## Troubleshooting - -Before creating a bug report, go through these troubleshooting steps. - -* Ensure the driver-facing camera has a good view of the driver in normal driving positions. - * This can be checked in Settings -> Device -> Preview Driver Camera (when car is off). -* If the camera can't see the driver, the device should be re-mounted. - -## Bug report - -In order for us to look into DM bug reports, we'll need the driver-facing camera footage. If you don't normally have this enabled, simply enable the toggle for a single drive. Also ensure the "Upload Raw Logs" toggle is enabled before going for a drive. diff --git a/selfdrive/monitoring/dm_toggles.py b/selfdrive/monitoring/dm_toggles.py new file mode 100644 index 00000000000000..888d9acc478157 --- /dev/null +++ b/selfdrive/monitoring/dm_toggles.py @@ -0,0 +1,74 @@ +"""Simulate Look / False Alert Ignore — mutually exclusive hidden DM prefs. + +Only one may be On. Both Off is allowed. Stale both-On (old installs that +defaulted both On) resolves to Simulate Look On + False Alert Ignore Off +on first read — matches nap-dev default intent. +""" + +PARAM_DM_SIMULATE_LOOKING = "NAPDmSimulateLooking" +PARAM_DM_FALSE_ALERT_IGNORE = "NAPDmFalseAlertIgnore" + +# nap-dev Reset-All / missing-param defaults. nap-release keeps both Off +# in params_keys.h; both-On migration still prefers Simulate Look. +DEFAULT_SIMULATE_LOOKING = True +DEFAULT_FALSE_ALERT_IGNORE = False + + +def exclusive_dm_toggle_states(simulate_looking: bool, false_alert_ignore: bool) -> tuple[bool, bool]: + """Resolve a pair. Both-On → Simulate Look On / FAI Off. Both Off stays Off.""" + sim = bool(simulate_looking) + fai = bool(false_alert_ignore) + if sim and fai: + return True, False + return sim, fai + + +def _get_bool(params, name: str, default: bool) -> bool: + if params is None: + return default + try: + return bool(params.get_bool(name)) + except Exception: + return default + + +def _put_bool(params, name: str, value: bool) -> None: + if params is None: + return + params.put_bool(name, bool(value)) + + +def apply_dm_simulate_looking(params, on: bool) -> tuple[bool, bool]: + """Write Simulate Look. On forces False Alert Ignore Off.""" + sim = bool(on) + fai = False if sim else _get_bool(params, PARAM_DM_FALSE_ALERT_IGNORE, DEFAULT_FALSE_ALERT_IGNORE) + _put_bool(params, PARAM_DM_SIMULATE_LOOKING, sim) + if sim: + _put_bool(params, PARAM_DM_FALSE_ALERT_IGNORE, False) + fai = False + return sim, fai + + +def apply_dm_false_alert_ignore(params, on: bool) -> tuple[bool, bool]: + """Write False Alert Ignore. On forces Simulate Look Off.""" + fai = bool(on) + sim = False if fai else _get_bool(params, PARAM_DM_SIMULATE_LOOKING, DEFAULT_SIMULATE_LOOKING) + _put_bool(params, PARAM_DM_FALSE_ALERT_IGNORE, fai) + if fai: + _put_bool(params, PARAM_DM_SIMULATE_LOOKING, False) + sim = False + return sim, fai + + +def read_exclusive_dm_toggles(params, *, persist: bool = True) -> tuple[bool, bool]: + """Read both params. Persist Simulate Look-wins if a stale both-On is found.""" + sim = _get_bool(params, PARAM_DM_SIMULATE_LOOKING, DEFAULT_SIMULATE_LOOKING) + fai = _get_bool(params, PARAM_DM_FALSE_ALERT_IGNORE, DEFAULT_FALSE_ALERT_IGNORE) + resolved_sim, resolved_fai = exclusive_dm_toggle_states(sim, fai) + if persist and (resolved_sim != sim or resolved_fai != fai): + try: + _put_bool(params, PARAM_DM_SIMULATE_LOOKING, resolved_sim) + _put_bool(params, PARAM_DM_FALSE_ALERT_IGNORE, resolved_fai) + except Exception: + pass + return resolved_sim, resolved_fai diff --git a/selfdrive/monitoring/dmonitoringd.py b/selfdrive/monitoring/dmonitoringd.py index 54d22c12437501..8a2a39725f386a 100755 --- a/selfdrive/monitoring/dmonitoringd.py +++ b/selfdrive/monitoring/dmonitoringd.py @@ -1,21 +1,20 @@ #!/usr/bin/env python3 -import gc - import cereal.messaging as messaging from openpilot.common.params import Params -from openpilot.common.realtime import set_realtime_priority -from openpilot.selfdrive.monitoring.helpers import DriverMonitoring +from openpilot.common.realtime import config_realtime_process +from openpilot.selfdrive.monitoring.dm_toggles import read_exclusive_dm_toggles +from openpilot.selfdrive.monitoring.policy import DriverMonitoring def dmonitoringd_thread(): - gc.disable() - set_realtime_priority(2) + config_realtime_process([0, 1, 2, 3], 5) params = Params() pm = messaging.PubMaster(['driverMonitoringState']) sm = messaging.SubMaster(['driverStateV2', 'liveCalibration', 'carState', 'selfdriveState', 'modelV2'], poll='driverStateV2') DM = DriverMonitoring(rhd_saved=params.get_bool("IsRhdDetected"), always_on=params.get_bool("AlwaysOnDM")) + demo_mode=False # 20Hz <- dmonitoringmodeld while True: @@ -25,22 +24,30 @@ def dmonitoringd_thread(): continue valid = sm.all_checks() - if valid: - DM.run_step(sm) + if demo_mode and sm.valid['driverStateV2']: + DM.run_step(sm, demo=True) + elif valid: + DM.run_step(sm, demo=demo_mode) # publish dat = DM.get_state_packet(valid=valid) pm.send('driverMonitoringState', dat) - # load live always-on toggle + # load live always-on toggle and hidden NAP DM toggles if sm['driverStateV2'].frameId % 40 == 1: DM.always_on = params.get_bool("AlwaysOnDM") + try: + sim, fai = read_exclusive_dm_toggles(params) + except Exception: + sim, fai = True, False + DM.set_nap_dm_toggles(simulate_looking=sim, false_alert_ignore=fai) + demo_mode = params.get_bool("IsDriverViewEnabled") # save rhd virtual toggle every 5 mins - if (sm['driverStateV2'].frameId % 6000 == 0 and - DM.wheelpos_learner.filtered_stat.n > DM.settings._WHEELPOS_FILTER_MIN_COUNT and - DM.wheel_on_right == (DM.wheelpos_learner.filtered_stat.M > DM.settings._WHEELPOS_THRESHOLD)): - params.put_bool_nonblocking("IsRhdDetected", DM.wheel_on_right) + if (sm['driverStateV2'].frameId % 6000 == 0 and not demo_mode and + DM.wheelpos_offsetter.filtered_stat.n > DM.settings._WHEELPOS_FILTER_MIN_COUNT and + DM.wheel_on_right == (DM.wheelpos_offsetter.filtered_stat.M > DM.settings._WHEELPOS_THRESHOLD)): + params.put_bool("IsRhdDetected", DM.wheel_on_right) def main(): dmonitoringd_thread() diff --git a/selfdrive/monitoring/helpers.py b/selfdrive/monitoring/helpers.py deleted file mode 100644 index f3dbbd530665d1..00000000000000 --- a/selfdrive/monitoring/helpers.py +++ /dev/null @@ -1,416 +0,0 @@ -from math import atan2 - -from cereal import car -import cereal.messaging as messaging -from openpilot.selfdrive.controls.lib.events import Events -from openpilot.common.numpy_fast import interp -from openpilot.common.realtime import DT_DMON -from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.stat_live import RunningStatFilter -from openpilot.common.transformations.camera import DEVICE_CAMERAS - -EventName = car.OnroadEvent.EventName - -# ****************************************************************************************** -# NOTE: To fork maintainers. -# Disabling or nerfing safety features will get you and your users banned from our servers. -# We recommend that you do not change these numbers from the defaults. -# ****************************************************************************************** - -class DRIVER_MONITOR_SETTINGS: - def __init__(self): - self._DT_DMON = DT_DMON - # ref (page15-16): https://eur-lex.europa.eu/legal-content/EN/TXT/PDF/?uri=CELEX:42018X1947&rid=2 - self._AWARENESS_TIME = 30. # passive wheeltouch total timeout - self._AWARENESS_PRE_TIME_TILL_TERMINAL = 15. - self._AWARENESS_PROMPT_TIME_TILL_TERMINAL = 6. - self._DISTRACTED_TIME = 11. # active monitoring total timeout - self._DISTRACTED_PRE_TIME_TILL_TERMINAL = 8. - self._DISTRACTED_PROMPT_TIME_TILL_TERMINAL = 6. - - self._FACE_THRESHOLD = 0.7 - self._EYE_THRESHOLD = 0.65 - self._SG_THRESHOLD = 0.9 - self._BLINK_THRESHOLD = 0.865 - - self._EE_THRESH11 = 0.25 - self._EE_THRESH12 = 7.5 - self._EE_MAX_OFFSET1 = 0.06 - self._EE_MIN_OFFSET1 = 0.025 - self._EE_THRESH21 = 0.01 - self._EE_THRESH22 = 0.35 - - self._POSE_PITCH_THRESHOLD = 0.3133 - self._POSE_PITCH_THRESHOLD_SLACK = 0.3237 - self._POSE_PITCH_THRESHOLD_STRICT = self._POSE_PITCH_THRESHOLD - self._POSE_YAW_THRESHOLD = 0.4020 - self._POSE_YAW_THRESHOLD_SLACK = 0.5042 - self._POSE_YAW_THRESHOLD_STRICT = self._POSE_YAW_THRESHOLD - self._PITCH_NATURAL_OFFSET = 0.029 # initial value before offset is learned - self._PITCH_NATURAL_THRESHOLD = 0.449 - self._YAW_NATURAL_OFFSET = 0.097 # initial value before offset is learned - self._PITCH_MAX_OFFSET = 0.124 - self._PITCH_MIN_OFFSET = -0.0881 - self._YAW_MAX_OFFSET = 0.289 - self._YAW_MIN_OFFSET = -0.0246 - - self._POSESTD_THRESHOLD = 0.3 - self._HI_STD_FALLBACK_TIME = int(10 / self._DT_DMON) # fall back to wheel touch if model is uncertain for 10s - self._DISTRACTED_FILTER_TS = 0.25 # 0.6Hz - self._ALWAYS_ON_ALERT_MIN_SPEED = 7 - - self._POSE_CALIB_MIN_SPEED = 13 # 30 mph - self._POSE_OFFSET_MIN_COUNT = int(60 / self._DT_DMON) # valid data counts before calibration completes, 1min cumulative - self._POSE_OFFSET_MAX_COUNT = int(360 / self._DT_DMON) # stop deweighting new data after 6 min, aka "short term memory" - - self._WHEELPOS_CALIB_MIN_SPEED = 11 - self._WHEELPOS_THRESHOLD = 0.5 - self._WHEELPOS_FILTER_MIN_COUNT = int(15 / self._DT_DMON) # allow 15 seconds to converge wheel side - - self._RECOVERY_FACTOR_MAX = 5. # relative to minus step change - self._RECOVERY_FACTOR_MIN = 1.25 # relative to minus step change - - self._MAX_TERMINAL_ALERTS = 3 # not allowed to engage after 3 terminal alerts - self._MAX_TERMINAL_DURATION = int(30 / self._DT_DMON) # not allowed to engage after 30s of terminal alerts - -class DistractedType: - NOT_DISTRACTED = 0 - DISTRACTED_POSE = 1 << 0 - DISTRACTED_BLINK = 1 << 1 - DISTRACTED_E2E = 1 << 2 - -class DriverPose: - def __init__(self, max_trackable): - self.yaw = 0. - self.pitch = 0. - self.roll = 0. - self.yaw_std = 0. - self.pitch_std = 0. - self.roll_std = 0. - self.pitch_offseter = RunningStatFilter(max_trackable=max_trackable) - self.yaw_offseter = RunningStatFilter(max_trackable=max_trackable) - self.calibrated = False - self.low_std = True - self.cfactor_pitch = 1. - self.cfactor_yaw = 1. - -class DriverBlink: - def __init__(self): - self.left = 0. - self.right = 0. - - -# model output refers to center of undistorted+leveled image -EFL = 598.0 # focal length in K -cam = DEVICE_CAMERAS[("tici", "ar0231")] # corrected image has same size as raw -W, H = (cam.dcam.width, cam.dcam.height) # corrected image has same size as raw - -def face_orientation_from_net(angles_desc, pos_desc, rpy_calib): - # the output of these angles are in device frame - # so from driver's perspective, pitch is up and yaw is right - - pitch_net, yaw_net, roll_net = angles_desc - - face_pixel_position = ((pos_desc[0]+0.5)*W, (pos_desc[1]+0.5)*H) - yaw_focal_angle = atan2(face_pixel_position[0] - W//2, EFL) - pitch_focal_angle = atan2(face_pixel_position[1] - H//2, EFL) - - pitch = pitch_net + pitch_focal_angle - yaw = -yaw_net + yaw_focal_angle - - # no calib for roll - pitch -= rpy_calib[1] - yaw -= rpy_calib[2] - return roll_net, pitch, yaw - - -class DriverMonitoring: - def __init__(self, rhd_saved=False, settings=None, always_on=False): - if settings is None: - settings = DRIVER_MONITOR_SETTINGS() - # init policy settings - self.settings = settings - - # init driver status - self.wheelpos_learner = RunningStatFilter() - self.pose = DriverPose(self.settings._POSE_OFFSET_MAX_COUNT) - self.blink = DriverBlink() - self.eev1 = 0. - self.eev2 = 1. - self.ee1_offseter = RunningStatFilter(max_trackable=self.settings._POSE_OFFSET_MAX_COUNT) - self.ee2_offseter = RunningStatFilter(max_trackable=self.settings._POSE_OFFSET_MAX_COUNT) - self.ee1_calibrated = False - self.ee2_calibrated = False - - self.always_on = always_on - self.distracted_types = [] - self.driver_distracted = False - self.driver_distraction_filter = FirstOrderFilter(0., self.settings._DISTRACTED_FILTER_TS, self.settings._DT_DMON) - self.wheel_on_right = False - self.wheel_on_right_last = None - self.wheel_on_right_default = rhd_saved - self.face_detected = False - self.terminal_alert_cnt = 0 - self.terminal_time = 0 - self.step_change = 0. - self.active_monitoring_mode = True - self.is_model_uncertain = False - self.hi_stds = 0 - self.threshold_pre = self.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME - self.threshold_prompt = self.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME - - self._reset_awareness() - self._set_timers(active_monitoring=True) - self._reset_events() - - def _reset_awareness(self): - self.awareness = 1. - self.awareness_active = 1. - self.awareness_passive = 1. - - def _reset_events(self): - self.current_events = Events() - - def _set_timers(self, active_monitoring): - if self.active_monitoring_mode and self.awareness <= self.threshold_prompt: - if active_monitoring: - self.step_change = self.settings._DT_DMON / self.settings._DISTRACTED_TIME - else: - self.step_change = 0. - return # no exploit after orange alert - elif self.awareness <= 0.: - return - - if active_monitoring: - # when falling back from passive mode to active mode, reset awareness to avoid false alert - if not self.active_monitoring_mode: - self.awareness_passive = self.awareness - self.awareness = self.awareness_active - - self.threshold_pre = self.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME - self.threshold_prompt = self.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME - self.step_change = self.settings._DT_DMON / self.settings._DISTRACTED_TIME - self.active_monitoring_mode = True - else: - if self.active_monitoring_mode: - self.awareness_active = self.awareness - self.awareness = self.awareness_passive - - self.threshold_pre = self.settings._AWARENESS_PRE_TIME_TILL_TERMINAL / self.settings._AWARENESS_TIME - self.threshold_prompt = self.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL / self.settings._AWARENESS_TIME - self.step_change = self.settings._DT_DMON / self.settings._AWARENESS_TIME - self.active_monitoring_mode = False - - def _set_policy(self, model_data, car_speed): - bp = model_data.meta.disengagePredictions.brakeDisengageProbs[0] # brake disengage prob in next 2s - k1 = max(-0.00156*((car_speed-16)**2)+0.6, 0.2) - bp_normal = max(min(bp / k1, 0.5),0) - self.pose.cfactor_pitch = interp(bp_normal, [0, 0.5], - [self.settings._POSE_PITCH_THRESHOLD_SLACK, - self.settings._POSE_PITCH_THRESHOLD_STRICT]) / self.settings._POSE_PITCH_THRESHOLD - self.pose.cfactor_yaw = interp(bp_normal, [0, 0.5], - [self.settings._POSE_YAW_THRESHOLD_SLACK, - self.settings._POSE_YAW_THRESHOLD_STRICT]) / self.settings._POSE_YAW_THRESHOLD - - def _get_distracted_types(self): - distracted_types = [] - - if not self.pose.calibrated: - pitch_error = self.pose.pitch - self.settings._PITCH_NATURAL_OFFSET - yaw_error = self.pose.yaw - self.settings._YAW_NATURAL_OFFSET - else: - pitch_error = self.pose.pitch - min(max(self.pose.pitch_offseter.filtered_stat.mean(), - self.settings._PITCH_MIN_OFFSET), self.settings._PITCH_MAX_OFFSET) - yaw_error = self.pose.yaw - min(max(self.pose.yaw_offseter.filtered_stat.mean(), - self.settings._YAW_MIN_OFFSET), self.settings._YAW_MAX_OFFSET) - pitch_error = 0 if pitch_error > 0 else abs(pitch_error) # no positive pitch limit - yaw_error = abs(yaw_error) - if pitch_error > (self.settings._POSE_PITCH_THRESHOLD*self.pose.cfactor_pitch if self.pose.calibrated else self.settings._PITCH_NATURAL_THRESHOLD) or \ - yaw_error > self.settings._POSE_YAW_THRESHOLD*self.pose.cfactor_yaw: - distracted_types.append(DistractedType.DISTRACTED_POSE) - - if (self.blink.left + self.blink.right)*0.5 > self.settings._BLINK_THRESHOLD: - distracted_types.append(DistractedType.DISTRACTED_BLINK) - - if self.ee1_calibrated: - ee1_dist = self.eev1 > max(min(self.ee1_offseter.filtered_stat.M, self.settings._EE_MAX_OFFSET1), self.settings._EE_MIN_OFFSET1) \ - * self.settings._EE_THRESH12 - else: - ee1_dist = self.eev1 > self.settings._EE_THRESH11 - if ee1_dist: - distracted_types.append(DistractedType.DISTRACTED_E2E) - - return distracted_types - - def _update_states(self, driver_state, cal_rpy, car_speed, op_engaged): - rhd_pred = driver_state.wheelOnRightProb - # calibrates only when there's movement and either face detected - if car_speed > self.settings._WHEELPOS_CALIB_MIN_SPEED and (driver_state.leftDriverData.faceProb > self.settings._FACE_THRESHOLD or - driver_state.rightDriverData.faceProb > self.settings._FACE_THRESHOLD): - self.wheelpos_learner.push_and_update(rhd_pred) - if self.wheelpos_learner.filtered_stat.n > self.settings._WHEELPOS_FILTER_MIN_COUNT: - self.wheel_on_right = self.wheelpos_learner.filtered_stat.M > self.settings._WHEELPOS_THRESHOLD - else: - self.wheel_on_right = self.wheel_on_right_default # use default/saved if calibration is unfinished - # make sure no switching when engaged - if op_engaged and self.wheel_on_right_last is not None and self.wheel_on_right_last != self.wheel_on_right: - self.wheel_on_right = self.wheel_on_right_last - driver_data = driver_state.rightDriverData if self.wheel_on_right else driver_state.leftDriverData - if not all(len(x) > 0 for x in (driver_data.faceOrientation, driver_data.facePosition, - driver_data.faceOrientationStd, driver_data.facePositionStd, - driver_data.readyProb, driver_data.notReadyProb)): - return - - self.face_detected = driver_data.faceProb > self.settings._FACE_THRESHOLD - self.pose.roll, self.pose.pitch, self.pose.yaw = face_orientation_from_net(driver_data.faceOrientation, driver_data.facePosition, cal_rpy) - if self.wheel_on_right: - self.pose.yaw *= -1 - self.wheel_on_right_last = self.wheel_on_right - self.pose.pitch_std = driver_data.faceOrientationStd[0] - self.pose.yaw_std = driver_data.faceOrientationStd[1] - model_std_max = max(self.pose.pitch_std, self.pose.yaw_std) - self.pose.low_std = model_std_max < self.settings._POSESTD_THRESHOLD - self.blink.left = driver_data.leftBlinkProb * (driver_data.leftEyeProb > self.settings._EYE_THRESHOLD) \ - * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) - self.blink.right = driver_data.rightBlinkProb * (driver_data.rightEyeProb > self.settings._EYE_THRESHOLD) \ - * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) - self.eev1 = driver_data.notReadyProb[0] - self.eev2 = driver_data.readyProb[0] - - self.distracted_types = self._get_distracted_types() - self.driver_distracted = (DistractedType.DISTRACTED_E2E in self.distracted_types or DistractedType.DISTRACTED_POSE in self.distracted_types - or DistractedType.DISTRACTED_BLINK in self.distracted_types) \ - and driver_data.faceProb > self.settings._FACE_THRESHOLD and self.pose.low_std - self.driver_distraction_filter.update(self.driver_distracted) - - # update offseter - # only update when driver is actively driving the car above a certain speed - if self.face_detected and car_speed > self.settings._POSE_CALIB_MIN_SPEED and self.pose.low_std and (not op_engaged or not self.driver_distracted): - self.pose.pitch_offseter.push_and_update(self.pose.pitch) - self.pose.yaw_offseter.push_and_update(self.pose.yaw) - self.ee1_offseter.push_and_update(self.eev1) - self.ee2_offseter.push_and_update(self.eev2) - - self.pose.calibrated = self.pose.pitch_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT and \ - self.pose.yaw_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT - self.ee1_calibrated = self.ee1_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT - self.ee2_calibrated = self.ee2_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT - - self.is_model_uncertain = self.hi_stds > self.settings._HI_STD_FALLBACK_TIME - self._set_timers(self.face_detected and not self.is_model_uncertain) - if self.face_detected and not self.pose.low_std and not self.driver_distracted: - self.hi_stds += 1 - elif self.face_detected and self.pose.low_std: - self.hi_stds = 0 - - def _update_events(self, driver_engaged, op_engaged, standstill, wrong_gear, car_speed): - self._reset_events() - # Block engaging after max number of distrations or when alert active - if self.terminal_alert_cnt >= self.settings._MAX_TERMINAL_ALERTS or \ - self.terminal_time >= self.settings._MAX_TERMINAL_DURATION or \ - self.always_on and self.awareness <= self.threshold_prompt: - self.current_events.add(EventName.tooDistracted) - - always_on_valid = self.always_on and not wrong_gear - if (driver_engaged and self.awareness > 0 and not self.active_monitoring_mode) or \ - (not always_on_valid and not op_engaged) or \ - (always_on_valid and not op_engaged and self.awareness <= 0): - # always reset on disengage with normal mode; disengage resets only on red if always on - self._reset_awareness() - return - - driver_attentive = self.driver_distraction_filter.x < 0.37 - awareness_prev = self.awareness - - if (driver_attentive and self.face_detected and self.pose.low_std and self.awareness > 0): - if driver_engaged: - self._reset_awareness() - return - # only restore awareness when paying attention and alert is not red - self.awareness = min(self.awareness + ((self.settings._RECOVERY_FACTOR_MAX-self.settings._RECOVERY_FACTOR_MIN)* - (1.-self.awareness)+self.settings._RECOVERY_FACTOR_MIN)*self.step_change, 1.) - if self.awareness == 1.: - self.awareness_passive = min(self.awareness_passive + self.step_change, 1.) - # don't display alert banner when awareness is recovering and has cleared orange - if self.awareness > self.threshold_prompt: - return - - _reaching_audible = self.awareness - self.step_change <= self.threshold_prompt - _reaching_terminal = self.awareness - self.step_change <= 0 - standstill_exemption = standstill and _reaching_audible - always_on_red_exemption = always_on_valid and not op_engaged and _reaching_terminal - always_on_lowspeed_exemption = always_on_valid and not op_engaged and car_speed < self.settings._ALWAYS_ON_ALERT_MIN_SPEED and _reaching_audible - - certainly_distracted = self.driver_distraction_filter.x > 0.63 and self.driver_distracted and self.face_detected - maybe_distracted = self.hi_stds > self.settings._HI_STD_FALLBACK_TIME or not self.face_detected - - if certainly_distracted or maybe_distracted: - # should always be counting if distracted unless at standstill (lowspeed for always-on) and reaching orange - # also will not be reaching 0 if DM is active when not engaged - if not (standstill_exemption or always_on_red_exemption or always_on_lowspeed_exemption): - self.awareness = max(self.awareness - self.step_change, -0.1) - - alert = None - if self.awareness <= 0.: - # terminal red alert: disengagement required - alert = EventName.driverDistracted if self.active_monitoring_mode else EventName.driverUnresponsive - self.terminal_time += 1 - if awareness_prev > 0.: - self.terminal_alert_cnt += 1 - elif self.awareness <= self.threshold_prompt: - # prompt orange alert - alert = EventName.promptDriverDistracted if self.active_monitoring_mode else EventName.promptDriverUnresponsive - elif self.awareness <= self.threshold_pre: - # pre green alert - alert = EventName.preDriverDistracted if self.active_monitoring_mode else EventName.preDriverUnresponsive - - if alert is not None: - self.current_events.add(alert) - - - def get_state_packet(self, valid=True): - # build driverMonitoringState packet - dat = messaging.new_message('driverMonitoringState', valid=valid) - dat.driverMonitoringState = { - "events": self.current_events.to_msg(), - "faceDetected": self.face_detected, - "isDistracted": self.driver_distracted, - "distractedType": sum(self.distracted_types), - "awarenessStatus": self.awareness, - "posePitchOffset": self.pose.pitch_offseter.filtered_stat.mean(), - "posePitchValidCount": self.pose.pitch_offseter.filtered_stat.n, - "poseYawOffset": self.pose.yaw_offseter.filtered_stat.mean(), - "poseYawValidCount": self.pose.yaw_offseter.filtered_stat.n, - "stepChange": self.step_change, - "awarenessActive": self.awareness_active, - "awarenessPassive": self.awareness_passive, - "isLowStd": self.pose.low_std, - "hiStdCount": self.hi_stds, - "isActiveMode": self.active_monitoring_mode, - "isRHD": self.wheel_on_right, - } - return dat - - def run_step(self, sm): - # Set strictness - self._set_policy( - model_data=sm['modelV2'], - car_speed=sm['carState'].vEgo - ) - - # Parse data from dmonitoringmodeld - self._update_states( - driver_state=sm['driverStateV2'], - cal_rpy=sm['liveCalibration'].rpyCalib, - car_speed=sm['carState'].vEgo, - op_engaged=sm['selfdriveState'].enabled - ) - - # Update distraction events - self._update_events( - driver_engaged=sm['carState'].steeringPressed or sm['carState'].gasPressed, - op_engaged=sm['selfdriveState'].enabled, - standstill=sm['carState'].standstill, - wrong_gear=sm['carState'].gearShifter in [car.CarState.GearShifter.reverse, car.CarState.GearShifter.park], - car_speed=sm['carState'].vEgo - ) diff --git a/selfdrive/monitoring/policy.py b/selfdrive/monitoring/policy.py new file mode 100644 index 00000000000000..dc97eb5c096959 --- /dev/null +++ b/selfdrive/monitoring/policy.py @@ -0,0 +1,711 @@ +from collections import defaultdict +from math import atan2, radians +import math +import random +import numpy as np + +from cereal import car, log +from openpilot.common.constants import CV +from openpilot.common.realtime import DT_DMON +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.stat_live import RunningStatFilter +from openpilot.common.transformations.camera import DEVICE_CAMERAS +from openpilot.selfdrive.monitoring.dm_toggles import ( + DEFAULT_FALSE_ALERT_IGNORE, DEFAULT_SIMULATE_LOOKING, + PARAM_DM_FALSE_ALERT_IGNORE, PARAM_DM_SIMULATE_LOOKING, + exclusive_dm_toggle_states, read_exclusive_dm_toggles, +) + +try: + from openpilot.common.params import Params +except Exception: # params_pyx not built in some unit-test hosts + Params = None + +AlertLevel = log.DriverMonitoringState.AlertLevel +MonitoringPolicy = log.DriverMonitoringState.MonitoringPolicy + +def to_percent(v): + return int(min(max(v * 100., 0.), 100.)) + +# ****************************************************************************************** +# NOTE: To fork maintainers. +# Disabling or nerfing safety features will get you and your users banned from our servers. +# We recommend that you do not change these numbers from the defaults. +# ****************************************************************************************** + +# NAP hidden DM toggles (triple-tap Settings → NAP). Shared cadence: +# after drain starts, wait past 1.0 s, then fire uniform in (1.0 s, 3.0 s]. +# Hold until gradual recovery returns awareness to 1.0. After a full +# reset the same rule applies to the next countdown. +# Simulate Look On = pre-FAI full looking-path wipe on that cadence +# (face + filter + driver_distracted + pose/eye/phone type bits). That +# is the original "do not nag" recovery for no-face, uncertain, phone, +# pose, and eye false nags. False Alert Ignore On (Sim Look Off) = +# phone-only soft-clear; pose and eye still drain. Mutually exclusive +# — only one may be On (both Off is allowed). nap-dev defaults: +# Simulate Look On / FAI Off. Stale both-On → Simulate Look On / +# FAI Off. Hands-on ≥ 2 / stalk / door / reverse unchanged. +LOOK_SIM_COUNTDOWN_MIN_S = 1.0 +LOOK_SIM_RANDOM_WINDOW_S = 2.0 +LOOK_SIM_FIRE_MAX_S = LOOK_SIM_COUNTDOWN_MIN_S + LOOK_SIM_RANDOM_WINDOW_S # 3.0 +# Always hold at least this long so recovery is not a single tick. +LOOK_SIM_HOLD_MIN_S = 0.5 +# Covers wheeltouch recovery from empty awareness (~11 s) plus margin. +LOOK_SIM_HOLD_MAX_S = 12.0 +LOOK_SIM_MODE_PHONE = "phone" +LOOK_SIM_MODE_GLANCE = "glance" +# Stock looking-path: filter.x below this + face + low pose std. +VISION_LOOKING_FILTER_X = 0.37 +VISION_RECOVERY_FACTOR_MAX = 5.0 +VISION_RECOVERY_FACTOR_MIN = 1.25 +# Pause looking-away / distraction / eyes-off-road alerts below this speed +# (same stock standstill exemption, plus creeping). Tesla CS.standstill is +# only true when fully stopped; 1 mph still nags at a light. Justin: "below +# two miles an hour, or maybe even below one" — gate is 2 mph (strictly +# below). Toggles stay as-is; this is not Simulate Look / FAI Off. +# controlsd lat standstill (~0.3 m/s) is too low for creep. FCW/AEB and +# hard cancels are unchanged. +DM_LOOKAWAY_GATE_MPH = 2.0 +DM_LOOKAWAY_GATE_MS = DM_LOOKAWAY_GATE_MPH * CV.MPH_TO_MS + + +def _param_bool(name: str, default: bool) -> bool: + if Params is None: + return default + try: + return bool(Params().get_bool(name)) + except Exception: + return default + + +def vision_looking_path(face_detected, low_std, distraction_filter_x) -> bool: + """True when stock DM treats the driver as looking / attentive.""" + return bool(face_detected and low_std and distraction_filter_x < VISION_LOOKING_FILTER_X) + + +def lookaway_alerts_paused(standstill, car_speed) -> bool: + """True when looking-away / distraction alerts must not fire. + + Stock already pauses at CS.standstill before the green prompt. Creeping + below DM_LOOKAWAY_GATE_MPH is not standstill on Pre-AP, so OR that in. + Independent of Simulate Look / FAI. + """ + return bool(standstill or abs(float(car_speed)) < DM_LOOKAWAY_GATE_MS) + + +def looking_recovery_time_s(awareness, alert_3_timeout, + rmax=VISION_RECOVERY_FACTOR_MAX, + rmin=VISION_RECOVERY_FACTOR_MIN) -> float: + """Seconds of stock looking-path recovery to return awareness to 1.0. + + Integrates da/dt = ((Rmax-Rmin)*(1-a)+Rmin)/T3 until a=1. + """ + u0 = max(0.0, 1.0 - float(awareness)) + if u0 <= 1e-12 or alert_3_timeout <= 0: + return 0.0 + k = (rmax - rmin) / alert_3_timeout + c = rmin / alert_3_timeout + return math.log((k * u0 + c) / c) / k + + +class DRIVER_MONITOR_SETTINGS: + def __init__(self): + # https://eur-lex.europa.eu/legal-content/EN/TXT/PDF/?uri=CELEX:42018X1947&rid=2 + self._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT = 15. + self._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT = 24. + self._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT = 30. + # https://cdn.euroncap.com/cars/assets/euro_ncap_protocol_safe_driving_driver_engagement_v11_a30e874152.pdf + self._VISION_POLICY_ALERT_1_TIMEOUT = 3. + self._VISION_POLICY_ALERT_2_TIMEOUT = 5. + self._VISION_POLICY_ALERT_3_TIMEOUT = 11. + + self._TIMEOUT_RECOVERY_FACTOR_MAX = 5. + self._TIMEOUT_RECOVERY_FACTOR_MIN = 1.25 + + self._MAX_TERMINAL_ALERTS = 3 # not allowed to engage after 3 terminal alerts + self._MAX_TERMINAL_DURATION = int(30 / DT_DMON) # not allowed to engage after 30s of terminal alerts + + self._FACE_THRESHOLD = 0.7 + self._EYE_THRESHOLD = 0.65 + self._SG_THRESHOLD = 0.9 + self._BLINK_THRESHOLD = 0.865 + self._PHONE_THRESH = 0.5 + self._POSE_PITCH_THRESHOLD = 0.3133 + self._POSE_PITCH_THRESHOLD_SLACK = 0.3237 + self._POSE_PITCH_THRESHOLD_STRICT = self._POSE_PITCH_THRESHOLD + self._POSE_YAW_THRESHOLD = 0.4020 + self._POSE_YAW_THRESHOLD_SLACK = 0.5042 + self._POSE_YAW_THRESHOLD_STRICT = self._POSE_YAW_THRESHOLD + self._POSE_YAW_MIN_STEER_DEG = 30 + self._POSE_YAW_STEER_FACTOR = 0.15 + self._POSE_YAW_STEER_MAX_OFFSET = 0.3927 + self._PITCH_NATURAL_OFFSET = 0.011 # initial value before offset is learned + self._PITCH_NATURAL_THRESHOLD = 0.449 + self._YAW_NATURAL_OFFSET = 0.075 # initial value before offset is learned + self._PITCH_NATURAL_VAR = 3*0.01 + self._YAW_NATURAL_VAR = 3*0.05 + self._PITCH_MAX_OFFSET = 0.124 + self._PITCH_MIN_OFFSET = -0.0881 + self._YAW_MAX_OFFSET = 0.289 + self._YAW_MIN_OFFSET = -0.0246 + + self._DCAM_UNCERTAIN_ALERT_THRESHOLD = 0.1 + self._DCAM_UNCERTAIN_ALERT_COUNT = int(60 / DT_DMON) + self._DCAM_UNCERTAIN_RESET_COUNT = int(2 / DT_DMON) + self._HI_STD_THRESHOLD = 0.3 + self._HI_STD_FALLBACK_TIME = int(10 / DT_DMON) # fall back to wheel touch if model is uncertain for 10s + self._DISTRACTED_FILTER_TS = 0.25 # 0.6Hz + + self._POSE_CALIB_MIN_SPEED = 13 # 30 mph + self._POSE_OFFSET_MIN_COUNT = int(60 / DT_DMON) # valid data counts before calibration completes, 1min cumulative + self._POSE_OFFSET_MAX_COUNT = int(360 / DT_DMON) # stop deweighting new data after 6 min, aka "short term memory" + self._WHEELPOS_CALIB_MIN_SPEED = 11 + self._WHEELPOS_THRESHOLD = 0.5 + self._WHEELPOS_FILTER_MIN_COUNT = int(15 / DT_DMON) # allow 15 seconds to converge wheel side + self._WHEELPOS_DATA_AVG = 0.03 + self._WHEELPOS_DATA_VAR = 3*5.5e-5 + self._WHEELPOS_MAX_COUNT = -1 + +class DriverPose: + def __init__(self, settings): + pitch_filter_raw_priors = (settings._PITCH_NATURAL_OFFSET, settings._PITCH_NATURAL_VAR, 2) + yaw_filter_raw_priors = (settings._YAW_NATURAL_OFFSET, settings._YAW_NATURAL_VAR, 2) + self.yaw = 0. + self.pitch = 0. + self.pitch_offsetter = RunningStatFilter(raw_priors=pitch_filter_raw_priors, max_trackable=settings._POSE_OFFSET_MAX_COUNT) + self.yaw_offsetter = RunningStatFilter(raw_priors=yaw_filter_raw_priors, max_trackable=settings._POSE_OFFSET_MAX_COUNT) + self.calibrated = False + self.low_std = True + self.cfactor_pitch = 1. + self.cfactor_yaw = 1. + self.steer_yaw_offset = 0. + +class DriverBlink: + def __init__(self): + self.left = 0. + self.right = 0. + +# model output refers to center of undistorted+leveled image +ref_undistorted_cam = DEVICE_CAMERAS[("tici", "ar0231")].dcam +dcam_undistorted_FL = 598.0 +dcam_undistorted_W, dcam_undistorted_H = (ref_undistorted_cam.width, ref_undistorted_cam.height) + +def face_orientation_from_model(orient_model, pos_model, rpy_calib): + pitch_model = orient_model[0] + yaw_model = orient_model[1] + + face_pixel_position = ((pos_model[0]+0.5)*dcam_undistorted_W, (pos_model[1]+0.5)*dcam_undistorted_H) + yaw_focal_angle = atan2(face_pixel_position[0] - dcam_undistorted_W//2, dcam_undistorted_FL) + pitch_focal_angle = atan2(face_pixel_position[1] - dcam_undistorted_H//2, dcam_undistorted_FL) + + pitch = pitch_model + pitch_focal_angle + yaw = -yaw_model + yaw_focal_angle + + pitch -= rpy_calib[1] + yaw -= rpy_calib[2] + return pitch, yaw + + +class DriverMonitoring: + def __init__(self, rhd_saved=False, settings=None, always_on=False): + # init policy settings + self.settings = settings if settings is not None else DRIVER_MONITOR_SETTINGS() + + # init driver status + wheelpos_filter_raw_priors = (self.settings._WHEELPOS_DATA_AVG, self.settings._WHEELPOS_DATA_VAR, 2) + self.wheelpos_offsetter = RunningStatFilter(raw_priors=wheelpos_filter_raw_priors, max_trackable=self.settings._WHEELPOS_MAX_COUNT) + self.pose = DriverPose(settings=self.settings) + self.blink = DriverBlink() + self.phone_prob = 0. + + self.alert_level = AlertLevel.none + self.always_on = always_on + self.distracted_types = defaultdict(bool) + self.driver_distracted = False + self.driver_distraction_filter = FirstOrderFilter(0., self.settings._DISTRACTED_FILTER_TS, DT_DMON) + self.wheel_on_right = False + self.wheel_on_right_last = None + self.wheel_on_right_default = rhd_saved + self.face_detected = False + self.terminal_alert_cnt = 0 + self.terminal_time = 0 + self.step_change = 0. + self.active_policy = MonitoringPolicy.vision + self.driver_interacting = False + self.is_model_uncertain = False + self.hi_stds = 0 + self.model_std_max = 0. + self.threshold_alert_1 = 0. + self.threshold_alert_2 = 0. + self.dcam_uncertain_cnt = 0 + self.dcam_reset_cnt = 0 + self.too_distracted = _param_bool("DriverTooDistracted", False) + # nap-dev: Simulate Look On / FAI Off. Both-On resolves to Sim On. + if Params is not None: + try: + sim, fai = read_exclusive_dm_toggles(Params()) + except Exception: + sim, fai = DEFAULT_SIMULATE_LOOKING, DEFAULT_FALSE_ALERT_IGNORE + else: + sim, fai = DEFAULT_SIMULATE_LOOKING, DEFAULT_FALSE_ALERT_IGNORE + self.nap_dm_simulate_looking = sim + self.nap_dm_false_alert_ignore = fai + self._rng = random.Random() + self._look_sim_countdown_s = 0.0 + self._look_sim_holding = False + self._look_sim_hold_s = 0.0 + self._look_sim_hold_start_awareness = 1.0 + self._look_sim_mode = None + self.car_speed = 0.0 + self._redraw_look_sim_interval() + + self._reset_awareness() + self._set_policy(MonitoringPolicy.vision) + + def _redraw_look_sim_interval(self): + """Fire time in (1.0 s, 3.0 s] after drain start: 1 s + uniform (0, 2 s].""" + # random() is [0, 1); (1-u)*window is (0, 2]. + delay = (1.0 - self._rng.random()) * LOOK_SIM_RANDOM_WINDOW_S + self._look_sim_fire_s = LOOK_SIM_COUNTDOWN_MIN_S + delay + + def _look_sim_active(self) -> bool: + return bool(self.nap_dm_simulate_looking or self.nap_dm_false_alert_ignore) + + def _enforce_exclusive_dm_toggles(self): + """Runtime guard: both-On → Simulate Look wins; stop the other path.""" + sim, fai = exclusive_dm_toggle_states( + self.nap_dm_simulate_looking, self.nap_dm_false_alert_ignore) + self.nap_dm_simulate_looking = sim + self.nap_dm_false_alert_ignore = fai + self._stop_inactive_dm_path() + + def _stop_inactive_dm_path(self): + """Abort full-wipe hold if Sim Off; end phone soft-clear if FAI Off.""" + if not self._look_sim_holding: + return + if self._look_sim_mode == LOOK_SIM_MODE_GLANCE and not self.nap_dm_simulate_looking: + self._abort_look_sim_hold() + elif self._look_sim_mode == LOOK_SIM_MODE_PHONE and not self.nap_dm_false_alert_ignore: + self._end_look_sim_hold(redraw=True) + + def set_nap_dm_toggles(self, *, simulate_looking=None, false_alert_ignore=None): + """Apply a live toggle flip (or a resolved pair) and stop the other path. + + Turning Simulate Look On clears FAI and ends a phone hold. Turning FAI + On clears Simulate Look and aborts an in-flight glance hold. Passing + both True still resolves to Simulate Look On / FAI Off. + """ + if simulate_looking is not None and false_alert_ignore is not None: + self.nap_dm_simulate_looking, self.nap_dm_false_alert_ignore = ( + exclusive_dm_toggle_states(simulate_looking, false_alert_ignore)) + self._stop_inactive_dm_path() + return + if simulate_looking is not None: + self.nap_dm_simulate_looking = bool(simulate_looking) + if self.nap_dm_simulate_looking: + self.nap_dm_false_alert_ignore = False + if false_alert_ignore is not None: + self.nap_dm_false_alert_ignore = bool(false_alert_ignore) + if self.nap_dm_false_alert_ignore: + self.nap_dm_simulate_looking = False + self._enforce_exclusive_dm_toggles() + + def _pose_or_eye_alarming(self) -> bool: + return bool(self.distracted_types['pose'] or self.distracted_types['eye']) + + def _phone_soft_clear_eligible(self) -> bool: + """False device only: phone bit, face + low std, pose/eye not alarming.""" + return (self.nap_dm_false_alert_ignore + and bool(self.distracted_types['phone']) + and not self._pose_or_eye_alarming() + and self.face_detected + and self.pose.low_std) + + def _simulate_look_wipe_eligible(self) -> bool: + """Simulate Look On: any soft drain is eligible for the full wipe.""" + return bool(self.nap_dm_simulate_looking) + + def _apply_phone_soft_clear(self): + """Ignore phoneProb / phone distraction only. Pose and eye stay live.""" + self.distracted_types['phone'] = False + self.driver_distracted = (any(self.distracted_types.values()) + and self.face_detected and self.pose.low_std) + if not self.driver_distracted: + self.driver_distraction_filter.x = 0.0 + + def _apply_simulated_looking(self) -> bool: + """Pre-FAI full looking-path wipe. Recovers no-face / uncertain / phone / + pose / eye nags. Does not mute hard cancels (those are outside DM).""" + self.face_detected = True + self.pose.low_std = True + self.is_model_uncertain = False + self.driver_distracted = False + self.driver_distraction_filter.x = 0.0 + self.distracted_types['pose'] = False + self.distracted_types['eye'] = False + self.distracted_types['phone'] = False + return True + + def _abort_look_sim_hold(self): + """Stop a hold without consuming the fire window — pose/eye must drain.""" + self._look_sim_holding = False + self._look_sim_hold_s = 0.0 + self._look_sim_mode = None + + def _end_look_sim_hold(self, redraw=True): + self._look_sim_holding = False + self._look_sim_hold_s = 0.0 + self._look_sim_countdown_s = 0.0 + self._look_sim_mode = None + if redraw: + self._redraw_look_sim_interval() + + def _look_sim_hold_done(self) -> bool: + if not self._look_sim_holding: + return False + if self._look_sim_hold_s + 1e-9 >= LOOK_SIM_HOLD_MAX_S: + return True + return (self.awareness >= 1.0 - 1e-9 and + self._look_sim_hold_s + 1e-9 >= LOOK_SIM_HOLD_MIN_S) + + def _start_look_sim_hold(self, mode): + self._look_sim_holding = True + self._look_sim_mode = mode + self._look_sim_hold_s = DT_DMON + self._look_sim_hold_start_awareness = self.awareness + + def _maybe_simulate_looking(self, op_engaged, allow_look_sim): + """Shared 1–3 s cadence for False Alert Ignore and Simulate Look.""" + self._enforce_exclusive_dm_toggles() + if not (allow_look_sim and self._look_sim_active() and op_engaged): + if not op_engaged: + self._end_look_sim_hold(redraw=False) + return + + if self._look_sim_holding: + if self._look_sim_mode == LOOK_SIM_MODE_PHONE: + # FAI phone-only: pose/eye must still drain. + if self._pose_or_eye_alarming(): + self._abort_look_sim_hold() + # A phone hold snaps the distraction filter to 0. Restore it so a + # new pose/eye alarm is not treated as looking for ~0.25 s. + if self.driver_distracted: + self.driver_distraction_filter.x = max( + self.driver_distraction_filter.x, 0.64) + return + if not self.nap_dm_false_alert_ignore: + self._end_look_sim_hold(redraw=True) + return + self._apply_phone_soft_clear() + else: + # Simulate Look: keep the full wipe even if pose/eye/phone return. + if not self.nap_dm_simulate_looking: + self._abort_look_sim_hold() + return + self._apply_simulated_looking() + self._look_sim_hold_s += DT_DMON + self._look_sim_countdown_s = 0.0 + # Stock looking recovery requires awareness > 0 (red does not climb). + if self.awareness <= 0. and self._look_sim_hold_s + 1e-9 >= LOOK_SIM_HOLD_MIN_S: + self._reset_awareness() + if self._look_sim_hold_done(): + self._end_look_sim_hold(redraw=True) + return + + if self.awareness < 1.0: + self._look_sim_countdown_s += DT_DMON + else: + self._look_sim_countdown_s = 0.0 + return + # Past 1.0 s of drain, then the drawn time in (1.0, 3.0]. + if (self._look_sim_countdown_s > LOOK_SIM_COUNTDOWN_MIN_S and + self._look_sim_countdown_s + 1e-9 >= self._look_sim_fire_s): + if self._phone_soft_clear_eligible(): + self._start_look_sim_hold(LOOK_SIM_MODE_PHONE) + self._apply_phone_soft_clear() + elif self._simulate_look_wipe_eligible(): + self._start_look_sim_hold(LOOK_SIM_MODE_GLANCE) + self._apply_simulated_looking() + + def _reset_awareness(self): + self.awareness = 1. + self.last_vision_awareness = 1. + self.last_wheeltouch_awareness = 1. + self._look_sim_countdown_s = 0.0 + + def _set_policy(self, target_policy): + if self.active_policy == MonitoringPolicy.vision and self.awareness <= self.threshold_alert_2: + if target_policy == MonitoringPolicy.vision: + self.step_change = DT_DMON / self.settings._VISION_POLICY_ALERT_3_TIMEOUT + else: + self.step_change = 0. + return # no exploit after orange alert + elif self.awareness <= 0.: + return + + if target_policy == MonitoringPolicy.vision: + # when falling back from passive mode to active mode, reset awareness to avoid false alert + if self.active_policy != MonitoringPolicy.vision: + self.last_wheeltouch_awareness = self.awareness + self.awareness = self.last_vision_awareness + + self.threshold_alert_1 = 1. - self.settings._VISION_POLICY_ALERT_1_TIMEOUT / self.settings._VISION_POLICY_ALERT_3_TIMEOUT + self.threshold_alert_2 = 1. - self.settings._VISION_POLICY_ALERT_2_TIMEOUT / self.settings._VISION_POLICY_ALERT_3_TIMEOUT + self.step_change = DT_DMON / self.settings._VISION_POLICY_ALERT_3_TIMEOUT + self.active_policy = MonitoringPolicy.vision + else: + if self.active_policy == MonitoringPolicy.vision: + self.last_vision_awareness = self.awareness + self.awareness = self.last_wheeltouch_awareness + + self.threshold_alert_1 = 1. - self.settings._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT / self.settings._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + self.threshold_alert_2 = 1. - self.settings._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT / self.settings._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + self.step_change = DT_DMON / self.settings._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + self.active_policy = MonitoringPolicy.wheeltouch + + def _set_pose_strictness(self, brake_disengage_prob, car_speed): + bp = brake_disengage_prob + k1 = max(-0.00156*((car_speed-16)**2)+0.6, 0.2) + bp_normal = max(min(bp / k1, 0.5),0) + self.pose.cfactor_pitch = np.interp(bp_normal, [0, 0.5], + [self.settings._POSE_PITCH_THRESHOLD_SLACK, + self.settings._POSE_PITCH_THRESHOLD_STRICT]) / self.settings._POSE_PITCH_THRESHOLD + self.pose.cfactor_yaw = np.interp(bp_normal, [0, 0.5], + [self.settings._POSE_YAW_THRESHOLD_SLACK, + self.settings._POSE_YAW_THRESHOLD_STRICT]) / self.settings._POSE_YAW_THRESHOLD + + def _get_distracted_types(self): + self.distracted_types = defaultdict(bool) + + if not self.pose.calibrated: + pitch_error = self.pose.pitch - self.settings._PITCH_NATURAL_OFFSET + yaw_error = self.pose.yaw - self.settings._YAW_NATURAL_OFFSET + else: + pitch_error = self.pose.pitch - min(max(self.pose.pitch_offsetter.filtered_stat.mean(), + self.settings._PITCH_MIN_OFFSET), self.settings._PITCH_MAX_OFFSET) + yaw_error = self.pose.yaw - min(max(self.pose.yaw_offsetter.filtered_stat.mean(), + self.settings._YAW_MIN_OFFSET), self.settings._YAW_MAX_OFFSET) + pitch_error = 0 if pitch_error > 0 else abs(pitch_error) # no positive pitch limit + + if yaw_error * self.pose.steer_yaw_offset > 0: # unidirectional + yaw_error = max(abs(yaw_error) - min(abs(self.pose.steer_yaw_offset), self.settings._POSE_YAW_STEER_MAX_OFFSET), 0.) + else: + yaw_error = abs(yaw_error) + + pitch_threshold = self.settings._POSE_PITCH_THRESHOLD * self.pose.cfactor_pitch if self.pose.calibrated else self.settings._PITCH_NATURAL_THRESHOLD + yaw_threshold = self.settings._POSE_YAW_THRESHOLD * self.pose.cfactor_yaw + + self.distracted_types['pose'] = bool((pitch_error > pitch_threshold) or (yaw_error > yaw_threshold)) + self.distracted_types['eye'] = bool((self.blink.left + self.blink.right)*0.5 > self.settings._BLINK_THRESHOLD) + self.distracted_types['phone'] = bool(self.phone_prob > self.settings._PHONE_THRESH) + + def _update_states(self, driver_state, cal_rpy, car_speed, op_engaged, standstill, demo_mode=False, steering_angle_deg=0.): + self.car_speed = float(car_speed) + rhd_pred = driver_state.wheelOnRightProb + # calibrates only when there's movement and either face detected + if car_speed > self.settings._WHEELPOS_CALIB_MIN_SPEED and (driver_state.leftDriverData.faceProb > self.settings._FACE_THRESHOLD or + driver_state.rightDriverData.faceProb > self.settings._FACE_THRESHOLD): + self.wheelpos_offsetter.push_and_update(rhd_pred) + + wheelpos_calibrated = self.wheelpos_offsetter.filtered_stat.n >= self.settings._WHEELPOS_FILTER_MIN_COUNT + + if wheelpos_calibrated or demo_mode: + self.wheel_on_right = self.wheelpos_offsetter.filtered_stat.M > self.settings._WHEELPOS_THRESHOLD + else: + self.wheel_on_right = self.wheel_on_right_default # use default/saved if calibration is unfinished + # make sure no switching when engaged + if op_engaged and self.wheel_on_right_last is not None and self.wheel_on_right_last != self.wheel_on_right and not demo_mode: + self.wheel_on_right = self.wheel_on_right_last + driver_data = driver_state.rightDriverData if self.wheel_on_right else driver_state.leftDriverData + if not all(len(x) > 0 for x in (driver_data.faceOrientation, driver_data.facePosition, + driver_data.faceOrientationStd, driver_data.facePositionStd)): + return + + self.face_detected = driver_data.faceProb > self.settings._FACE_THRESHOLD + self.pose.pitch, self.pose.yaw = face_orientation_from_model(driver_data.faceOrientation, driver_data.facePosition, cal_rpy) + steer_d = max(abs(steering_angle_deg) - self.settings._POSE_YAW_MIN_STEER_DEG, 0.) + self.pose.steer_yaw_offset = radians(steer_d) * -np.sign(steering_angle_deg) * self.settings._POSE_YAW_STEER_FACTOR + if self.wheel_on_right: + self.pose.yaw *= -1 + self.pose.steer_yaw_offset *= -1 + self.wheel_on_right_last = self.wheel_on_right + self.model_std_max = max(driver_data.faceOrientationStd[0], driver_data.faceOrientationStd[1]) + self.pose.low_std = self.model_std_max < self.settings._HI_STD_THRESHOLD + self.blink.left = driver_data.leftBlinkProb * (driver_data.leftEyeProb > self.settings._EYE_THRESHOLD) \ + * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) + self.blink.right = driver_data.rightBlinkProb * (driver_data.rightEyeProb > self.settings._EYE_THRESHOLD) \ + * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) + self.phone_prob = driver_data.phoneProb + + self._get_distracted_types() + self.driver_distracted = any(self.distracted_types.values()) and driver_data.faceProb > self.settings._FACE_THRESHOLD and self.pose.low_std + self.driver_distraction_filter.update(self.driver_distracted) + + # only update offsetter when driver is actively driving the car above a certain speed + if self.face_detected and car_speed > self.settings._POSE_CALIB_MIN_SPEED and self.pose.low_std and (not op_engaged or not self.driver_distracted): + self.pose.pitch_offsetter.push_and_update(self.pose.pitch) + self.pose.yaw_offsetter.push_and_update(self.pose.yaw) + + self.pose.calibrated = self.pose.pitch_offsetter.filtered_stat.n >= self.settings._POSE_OFFSET_MIN_COUNT and \ + self.pose.yaw_offsetter.filtered_stat.n >= self.settings._POSE_OFFSET_MIN_COUNT + + if self.face_detected and not self.driver_distracted: + dcam_uncertain = self.model_std_max > self.settings._DCAM_UNCERTAIN_ALERT_THRESHOLD + if dcam_uncertain and not standstill: + self.dcam_uncertain_cnt += 1 + self.dcam_reset_cnt = 0 + else: + self.dcam_reset_cnt += 1 + if self.dcam_reset_cnt > self.settings._DCAM_UNCERTAIN_RESET_COUNT: + self.dcam_uncertain_cnt = 0 + + self.is_model_uncertain = self.hi_stds >= self.settings._HI_STD_FALLBACK_TIME + self._set_policy(MonitoringPolicy.vision if self.face_detected and not self.is_model_uncertain else MonitoringPolicy.wheeltouch) + if self.face_detected and not self.pose.low_std and not self.driver_distracted: + self.hi_stds += 1 + elif self.face_detected and self.pose.low_std: + self.hi_stds = 0 + + def _update_events(self, driver_engaged, op_engaged, standstill, wrong_gear, allow_look_sim=True): + self.alert_level = AlertLevel.none + self.driver_interacting = driver_engaged + self._maybe_simulate_looking(op_engaged, allow_look_sim) + + if self.terminal_alert_cnt >= self.settings._MAX_TERMINAL_ALERTS or \ + self.terminal_time >= self.settings._MAX_TERMINAL_DURATION: + self.too_distracted = True + + always_on_valid = self.always_on and not wrong_gear + if (self.driver_interacting and self.awareness > 0 and self.active_policy == MonitoringPolicy.wheeltouch) or \ + (not always_on_valid and not op_engaged) or \ + (always_on_valid and not op_engaged and self.awareness <= 0): + # always reset on disengage with normal mode; disengage resets only on red if always on + self._reset_awareness() + return + + awareness_prev = self.awareness + _reaching_alert_1 = self.awareness - self.step_change <= self.threshold_alert_1 + _reaching_alert_3 = self.awareness - self.step_change <= 0 + # Stock pauses before green at CS.standstill. Also pause while creeping + # below DM_LOOKAWAY_GATE_MPH (Sim Look / FAI stay as toggled). + standstill_exemption = lookaway_alerts_paused(standstill, self.car_speed) and _reaching_alert_1 + always_on_exemption = always_on_valid and not op_engaged and _reaching_alert_3 + + looking = vision_looking_path(self.face_detected, self.pose.low_std, + self.driver_distraction_filter.x) + if self.awareness > 0 and (looking or standstill_exemption): + if self.driver_interacting: + self._reset_awareness() + return + # only restore awareness when paying attention and alert is not red + self.awareness = min(self.awareness + ((self.settings._TIMEOUT_RECOVERY_FACTOR_MAX-self.settings._TIMEOUT_RECOVERY_FACTOR_MIN)* + (1.-self.awareness)+self.settings._TIMEOUT_RECOVERY_FACTOR_MIN)*self.step_change, 1.) + if self.awareness == 1.: + self.last_wheeltouch_awareness = min(self.last_wheeltouch_awareness + self.step_change, 1.) + # don't display alert banner when awareness is recovering and has cleared orange + if self.awareness > self.threshold_alert_2: + return + + certainly_distracted = self.driver_distraction_filter.x > 0.63 and self.driver_distracted and self.face_detected + maybe_distracted = self.is_model_uncertain or not self.face_detected + + if certainly_distracted or maybe_distracted: + # should always be counting if distracted unless at standstill and reaching green + # also will not be reaching 0 if DM is active when not engaged + if not (standstill_exemption or always_on_exemption): + self.awareness = max(self.awareness - self.step_change, -0.1) + + if self.awareness <= 0.: + # terminal alert: disengagement required + self.alert_level = AlertLevel.three + self.terminal_time += 1 + if awareness_prev > 0.: + self.terminal_alert_cnt += 1 + elif self.awareness <= self.threshold_alert_2: + self.alert_level = AlertLevel.two + elif self.awareness <= self.threshold_alert_1: + self.alert_level = AlertLevel.one + + def get_state_packet(self, valid=True): + # build driverMonitoringState packet + import cereal.messaging as messaging + dat = messaging.new_message('driverMonitoringState', valid=valid) + dm = dat.driverMonitoringState + + dm.lockout = self.too_distracted + dm.alertCountLockoutPercent = to_percent(self.terminal_alert_cnt / self.settings._MAX_TERMINAL_ALERTS) + dm.alertTimeLockoutPercent = to_percent(self.terminal_time / self.settings._MAX_TERMINAL_DURATION) + dm.alwaysOn = self.always_on + dm.alwaysOnLockout = self.always_on and self.awareness <= self.threshold_alert_2 + dm.alertLevel = self.alert_level + dm.activePolicy = self.active_policy + dm.isRHD = self.wheel_on_right + dm.rhdCalibration.calibratedPercent = to_percent(self.wheelpos_offsetter.filtered_stat.n / self.settings._WHEELPOS_FILTER_MIN_COUNT) + dm.rhdCalibration.offset = self.wheelpos_offsetter.filtered_stat.M + + dm.visionPolicyState.awarenessPercent = to_percent(self.last_vision_awareness if self.active_policy != MonitoringPolicy.vision else self.awareness) + dm.visionPolicyState.awarenessStep = self.step_change if self.active_policy == MonitoringPolicy.vision else 0. + dm.visionPolicyState.isDistracted = self.driver_distracted + dm.visionPolicyState.distractedTypes.pose = self.distracted_types['pose'] + dm.visionPolicyState.distractedTypes.eye = self.distracted_types['eye'] + dm.visionPolicyState.distractedTypes.phone = self.distracted_types['phone'] + dm.visionPolicyState.faceDetected = self.face_detected + dm.visionPolicyState.pose.pitch = self.pose.pitch + dm.visionPolicyState.pose.yaw = self.pose.yaw + dm.visionPolicyState.pose.calibrated = self.pose.calibrated + dm.visionPolicyState.pose.pitchCalib.calibratedPercent = to_percent(self.pose.pitch_offsetter.filtered_stat.n / self.settings._POSE_OFFSET_MIN_COUNT) + dm.visionPolicyState.pose.pitchCalib.offset = self.pose.pitch_offsetter.filtered_stat.M + dm.visionPolicyState.pose.yawCalib.calibratedPercent = to_percent(self.pose.yaw_offsetter.filtered_stat.n / self.settings._POSE_OFFSET_MIN_COUNT) + dm.visionPolicyState.pose.yawCalib.offset = self.pose.yaw_offsetter.filtered_stat.M + dm.visionPolicyState.pose.uncertainty = self.model_std_max + dm.visionPolicyState.wheeltouchFallbackPercent = to_percent(self.hi_stds / self.settings._HI_STD_FALLBACK_TIME) + dm.visionPolicyState.uncertainOffroadAlertPercent = to_percent(self.dcam_uncertain_cnt / self.settings._DCAM_UNCERTAIN_ALERT_COUNT) + + dm.wheeltouchPolicyState.awarenessPercent = to_percent(self.last_wheeltouch_awareness if self.active_policy == MonitoringPolicy.vision else self.awareness) + dm.wheeltouchPolicyState.awarenessStep = 0. if self.active_policy == MonitoringPolicy.vision else self.step_change + dm.wheeltouchPolicyState.driverInteracting = self.driver_interacting + return dat + + def run_step(self, sm, demo=False): + if demo: + car_speed = 30 + enabled = True + wrong_gear = False + standstill = False + driver_engaged = False + brake_disengage_prob = 1.0 + steering_angle_deg = 0.0 + rpyCalib = [0., 0., 0.] + else: + car_speed = sm['carState'].vEgo + enabled = sm['selfdriveState'].enabled + wrong_gear = sm['carState'].gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low) + standstill = sm['carState'].standstill + driver_engaged = sm['carState'].steeringPressed or sm['carState'].gasPressed + brake_disengage_prob = sm['modelV2'].meta.disengagePredictions.brakeDisengageProbs[0] # brake disengage prob in next 2s + steering_angle_deg = sm['carState'].steeringAngleDeg + rpyCalib = sm['liveCalibration'].rpyCalib + + self._set_pose_strictness( + brake_disengage_prob=brake_disengage_prob, + car_speed=car_speed, + ) + + # Parse data from dmonitoringmodeld + self._update_states( + driver_state=sm['driverStateV2'], + cal_rpy=rpyCalib, + car_speed=car_speed, + op_engaged=enabled, + standstill=standstill, + demo_mode=demo, + steering_angle_deg=steering_angle_deg, + ) + + self._update_events( + driver_engaged=driver_engaged, + op_engaged=enabled, + standstill=standstill, + wrong_gear=wrong_gear, + allow_look_sim=not demo, + ) diff --git a/selfdrive/monitoring/test_dm_toggles.py b/selfdrive/monitoring/test_dm_toggles.py new file mode 100644 index 00000000000000..8ce5eefca6dabb --- /dev/null +++ b/selfdrive/monitoring/test_dm_toggles.py @@ -0,0 +1,138 @@ +"""Simulate Look / False Alert Ignore mutual exclusion (no GUI / no cereal).""" +import importlib.util +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + +_spec = importlib.util.spec_from_file_location( + "dm_toggles", ROOT / "selfdrive" / "monitoring" / "dm_toggles.py", +) +_mod = importlib.util.module_from_spec(_spec) +assert _spec.loader is not None +_spec.loader.exec_module(_mod) + +PARAM_DM_SIMULATE_LOOKING = _mod.PARAM_DM_SIMULATE_LOOKING +PARAM_DM_FALSE_ALERT_IGNORE = _mod.PARAM_DM_FALSE_ALERT_IGNORE +DEFAULT_SIMULATE_LOOKING = _mod.DEFAULT_SIMULATE_LOOKING +DEFAULT_FALSE_ALERT_IGNORE = _mod.DEFAULT_FALSE_ALERT_IGNORE +exclusive_dm_toggle_states = _mod.exclusive_dm_toggle_states +apply_dm_simulate_looking = _mod.apply_dm_simulate_looking +apply_dm_false_alert_ignore = _mod.apply_dm_false_alert_ignore +read_exclusive_dm_toggles = _mod.read_exclusive_dm_toggles + + +class FakeParams: + def __init__(self, **bools): + self.d = dict(bools) + + def get_bool(self, name): + if name not in self.d: + raise KeyError(name) + return bool(self.d[name]) + + def put_bool(self, name, value): + self.d[name] = bool(value) + + +def test_param_names_and_nap_dev_defaults(): + keys = (ROOT / "common" / "params_keys.h").read_text(encoding="utf-8") + assert PARAM_DM_SIMULATE_LOOKING == "NAPDmSimulateLooking" + assert PARAM_DM_FALSE_ALERT_IGNORE == "NAPDmFalseAlertIgnore" + assert DEFAULT_SIMULATE_LOOKING is True + assert DEFAULT_FALSE_ALERT_IGNORE is False + sim_line = next(ln for ln in keys.splitlines() if f'"{PARAM_DM_SIMULATE_LOOKING}"' in ln) + fai_line = next(ln for ln in keys.splitlines() if f'"{PARAM_DM_FALSE_ALERT_IGNORE}"' in ln) + assert 'BOOL, "1"' in sim_line + assert 'BOOL, "0"' in fai_line + assert "PERSISTENT" in sim_line and "PERSISTENT" in fai_line + + +def test_exclusive_states_both_on_prefers_simulate_look(): + assert exclusive_dm_toggle_states(True, True) == (True, False) + assert exclusive_dm_toggle_states(True, False) == (True, False) + assert exclusive_dm_toggle_states(False, True) == (False, True) + assert exclusive_dm_toggle_states(False, False) == (False, False) + + +def test_apply_simulate_look_on_clears_fai(): + p = FakeParams(**{PARAM_DM_SIMULATE_LOOKING: False, PARAM_DM_FALSE_ALERT_IGNORE: True}) + sim, fai = apply_dm_simulate_looking(p, True) + assert (sim, fai) == (True, False) + assert p.get_bool(PARAM_DM_SIMULATE_LOOKING) is True + assert p.get_bool(PARAM_DM_FALSE_ALERT_IGNORE) is False + + +class DelayedParams(FakeParams): + """put_bool is not visible to get_bool until flush — like non-blocking Params.""" + + def __init__(self, **bools): + super().__init__(**bools) + self._pending = {} + + def put_bool(self, name, value): + self._pending[name] = bool(value) + + def flush(self): + self.d.update(self._pending) + self._pending.clear() + + +def test_apply_return_is_live_when_get_bool_is_stale(): + """Popup must paint the sibling from apply() return, not get_bool.""" + p = DelayedParams(**{PARAM_DM_SIMULATE_LOOKING: False, PARAM_DM_FALSE_ALERT_IGNORE: True}) + sim, fai = apply_dm_simulate_looking(p, True) + assert (sim, fai) == (True, False) + assert p.get_bool(PARAM_DM_FALSE_ALERT_IGNORE) is True # stale until flush + # UI set_state(fai) / set_checked(fai) — not get_bool. + painted_fai = fai + assert painted_fai is False + p.flush() + assert p.get_bool(PARAM_DM_FALSE_ALERT_IGNORE) is False + + p = DelayedParams(**{PARAM_DM_SIMULATE_LOOKING: True, PARAM_DM_FALSE_ALERT_IGNORE: False}) + sim, fai = apply_dm_false_alert_ignore(p, True) + assert (sim, fai) == (False, True) + assert p.get_bool(PARAM_DM_SIMULATE_LOOKING) is True # stale + assert sim is False + + +def test_apply_fai_on_clears_simulate_look(): + p = FakeParams(**{PARAM_DM_SIMULATE_LOOKING: True, PARAM_DM_FALSE_ALERT_IGNORE: False}) + sim, fai = apply_dm_false_alert_ignore(p, True) + assert (sim, fai) == (False, True) + assert p.get_bool(PARAM_DM_SIMULATE_LOOKING) is False + assert p.get_bool(PARAM_DM_FALSE_ALERT_IGNORE) is True + + +def test_apply_off_leaves_the_other_alone(): + p = FakeParams(**{PARAM_DM_SIMULATE_LOOKING: True, PARAM_DM_FALSE_ALERT_IGNORE: False}) + sim, fai = apply_dm_simulate_looking(p, False) + assert (sim, fai) == (False, False) + assert p.get_bool(PARAM_DM_SIMULATE_LOOKING) is False + assert p.get_bool(PARAM_DM_FALSE_ALERT_IGNORE) is False + + p = FakeParams(**{PARAM_DM_SIMULATE_LOOKING: False, PARAM_DM_FALSE_ALERT_IGNORE: True}) + sim, fai = apply_dm_false_alert_ignore(p, False) + assert (sim, fai) == (False, False) + assert p.get_bool(PARAM_DM_FALSE_ALERT_IGNORE) is False + assert p.get_bool(PARAM_DM_SIMULATE_LOOKING) is False + + +def test_read_resolves_stale_both_on_and_persists(): + p = FakeParams(**{PARAM_DM_SIMULATE_LOOKING: True, PARAM_DM_FALSE_ALERT_IGNORE: True}) + sim, fai = read_exclusive_dm_toggles(p) + assert (sim, fai) == (True, False) + assert p.get_bool(PARAM_DM_SIMULATE_LOOKING) is True + assert p.get_bool(PARAM_DM_FALSE_ALERT_IGNORE) is False + + +def test_read_without_persist_does_not_write(): + p = FakeParams(**{PARAM_DM_SIMULATE_LOOKING: True, PARAM_DM_FALSE_ALERT_IGNORE: True}) + sim, fai = read_exclusive_dm_toggles(p, persist=False) + assert (sim, fai) == (True, False) + assert p.get_bool(PARAM_DM_FALSE_ALERT_IGNORE) is True + + +def test_read_both_off_stays_off(): + p = FakeParams(**{PARAM_DM_SIMULATE_LOOKING: False, PARAM_DM_FALSE_ALERT_IGNORE: False}) + assert read_exclusive_dm_toggles(p) == (False, False) diff --git a/selfdrive/monitoring/test_monitoring.py b/selfdrive/monitoring/test_monitoring.py index 31ae98c63886a3..facbedfa9231ad 100644 --- a/selfdrive/monitoring/test_monitoring.py +++ b/selfdrive/monitoring/test_monitoring.py @@ -1,21 +1,35 @@ import numpy as np -from cereal import car, log +from cereal import log +from openpilot.common.constants import CV from openpilot.common.realtime import DT_DMON -from openpilot.selfdrive.monitoring.helpers import DriverMonitoring, DRIVER_MONITOR_SETTINGS +from openpilot.selfdrive.monitoring.dm_toggles import ( + DEFAULT_FALSE_ALERT_IGNORE, DEFAULT_SIMULATE_LOOKING, +) +from openpilot.selfdrive.monitoring.policy import ( + DriverMonitoring, DRIVER_MONITOR_SETTINGS, PARAM_DM_SIMULATE_LOOKING, + PARAM_DM_FALSE_ALERT_IGNORE, LOOK_SIM_MODE_PHONE, LOOK_SIM_MODE_GLANCE, + LOOK_SIM_COUNTDOWN_MIN_S, LOOK_SIM_RANDOM_WINDOW_S, LOOK_SIM_FIRE_MAX_S, + LOOK_SIM_HOLD_MIN_S, LOOK_SIM_HOLD_MAX_S, + VISION_LOOKING_FILTER_X, VISION_RECOVERY_FACTOR_MAX, VISION_RECOVERY_FACTOR_MIN, + DM_LOOKAWAY_GATE_MPH, DM_LOOKAWAY_GATE_MS, lookaway_alerts_paused, + vision_looking_path, looking_recovery_time_s, +) -EventName = car.OnroadEvent.EventName +EventName = log.OnroadEvent.EventName dm_settings = DRIVER_MONITOR_SETTINGS() TEST_TIMESPAN = 120 # seconds -DISTRACTED_SECONDS_TO_ORANGE = dm_settings._DISTRACTED_TIME - dm_settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL + 1 -DISTRACTED_SECONDS_TO_RED = dm_settings._DISTRACTED_TIME + 1 -INVISIBLE_SECONDS_TO_ORANGE = dm_settings._AWARENESS_TIME - dm_settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL + 1 -INVISIBLE_SECONDS_TO_RED = dm_settings._AWARENESS_TIME + 1 +DISTRACTED_SECONDS_TO_ORANGE = dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 1 +DISTRACTED_SECONDS_TO_RED = dm_settings._VISION_POLICY_ALERT_3_TIMEOUT + 1 +INVISIBLE_SECONDS_TO_ORANGE = dm_settings._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT + 1 +INVISIBLE_SECONDS_TO_RED = dm_settings._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + 1 -def make_msg(face_detected, distracted=False, model_uncertain=False): +def make_msg(face_detected, distracted=False, model_uncertain=False, + phone=False, pose=False): ds = log.DriverStateV2.new_message() - ds.leftDriverData.faceOrientation = [0., 0., 0.] + # Large yaw trips uncalibrated pose (threshold ~0.40). Blink = eye. + ds.leftDriverData.faceOrientation = [0., 1.2 if pose else 0., 0.] ds.leftDriverData.facePosition = [0., 0.] ds.leftDriverData.faceProb = 1. * face_detected ds.leftDriverData.leftEyeProb = 1. @@ -24,9 +38,7 @@ def make_msg(face_detected, distracted=False, model_uncertain=False): ds.leftDriverData.rightBlinkProb = 1. * distracted ds.leftDriverData.faceOrientationStd = [1.*model_uncertain, 1.*model_uncertain, 1.*model_uncertain] ds.leftDriverData.facePositionStd = [1.*model_uncertain, 1.*model_uncertain] - # TODO: test both separately when e2e is used - ds.leftDriverData.readyProb = [0., 0., 0., 0.] - ds.leftDriverData.notReadyProb = [0., 0.] + ds.leftDriverData.phoneProb = 1. * phone return ds @@ -36,7 +48,11 @@ def make_msg(face_detected, distracted=False, model_uncertain=False): msg_DISTRACTED = make_msg(True, distracted=True) msg_ATTENTIVE_UNCERTAIN = make_msg(True, model_uncertain=True) msg_DISTRACTED_UNCERTAIN = make_msg(True, distracted=True, model_uncertain=True) -msg_DISTRACTED_BUT_SOMEHOW_UNCERTAIN = make_msg(True, distracted=True, model_uncertain=dm_settings._POSESTD_THRESHOLD*1.5) +msg_DISTRACTED_BUT_SOMEHOW_UNCERTAIN = make_msg(True, distracted=True, model_uncertain=dm_settings._HI_STD_THRESHOLD*1.5) +msg_PHONE_ONLY = make_msg(True, phone=True) +msg_POSE_ONLY = make_msg(True, pose=True) +msg_PHONE_AND_POSE = make_msg(True, phone=True, pose=True) +msg_PHONE_AND_EYE = make_msg(True, distracted=True, phone=True) # driver interaction with car car_interaction_DETECTED = True @@ -48,53 +64,95 @@ def make_msg(face_detected, distracted=False, model_uncertain=False): always_distracted = [msg_DISTRACTED] * int(TEST_TIMESPAN / DT_DMON) always_true = [True] * int(TEST_TIMESPAN / DT_DMON) always_false = [False] * int(TEST_TIMESPAN / DT_DMON) +# Above the 2 mph look-away gate, below pose/wheelpos calib mins (13 / 11 m/s). +TEST_MOVING_MS = 5.0 # ~11 mph +TEST_CREEP_MS = DM_LOOKAWAY_GATE_MS * 0.5 # 1 mph +TEST_ABOVE_GATE_MS = DM_LOOKAWAY_GATE_MS + 0.05 + +class _NS: + def __init__(self, **kw): + self.__dict__.update(kw) + + +def _fake_sm(*, engaged=True, hands=1, steer_pressed=False, gas_pressed=False, + driver_state=None, standstill=False, v_ego=20.0): + from cereal import car + return { + 'carState': _NS( + vEgo=v_ego, + gearShifter=car.CarState.GearShifter.drive, + standstill=standstill, + steeringPressed=steer_pressed, + gasPressed=gas_pressed, + steeringAngleDeg=0.0, + handsOnLevel=hands, + steeringTorqueEps=float(hands), + steeringDisengage=False, + ), + 'selfdriveState': _NS(enabled=engaged), + 'modelV2': _NS(meta=_NS(disengagePredictions=_NS(brakeDisengageProbs=[0.0]))), + 'liveCalibration': _NS(rpyCalib=[0., 0., 0.]), + 'driverStateV2': driver_state if driver_state is not None else msg_DISTRACTED, + } + class TestMonitoring: - def _run_seq(self, msgs, interaction, engaged, standstill): + def _run_seq(self, msgs, interaction, engaged, standstill, simulate_looking=False, + false_alert_ignore=False, rng_seed=None, car_speed=None): DM = DriverMonitoring() - events = [] + DM.nap_dm_simulate_looking = bool(simulate_looking) + DM.nap_dm_false_alert_ignore = bool(false_alert_ignore) + if rng_seed is not None: + DM._rng.seed(rng_seed) + DM._redraw_look_sim_interval() + if car_speed is None: + speeds = [TEST_MOVING_MS] * len(msgs) + elif isinstance(car_speed, (int, float)): + speeds = [float(car_speed)] * len(msgs) + else: + speeds = car_speed + alert_lvls = [] for idx in range(len(msgs)): - DM._update_states(msgs[idx], [0, 0, 0], 0, engaged[idx]) - # cal_rpy and car_speed don't matter here + DM._update_states(msgs[idx], [0, 0, 0], speeds[idx], engaged[idx], standstill[idx]) # evaluate events at 10Hz for tests - DM._update_events(interaction[idx], engaged[idx], standstill[idx], 0, 0) - events.append(DM.current_events) - assert len(events) == len(msgs), f"got {len(events)} for {len(msgs)} driverState input msgs" - return events, DM + DM._update_events(interaction[idx], engaged[idx], standstill[idx], 0) + alert_lvls.append(DM.alert_level) + assert len(alert_lvls) == len(msgs), f"got {len(alert_lvls)} for {len(msgs)} driverState input msgs" + return alert_lvls, DM - def _assert_no_events(self, events): - assert all(not len(e) for e in events) # engaged, driver is attentive all the time def test_fully_aware_driver(self): - events, _ = self._run_seq(always_attentive, always_false, always_true, always_false) - self._assert_no_events(events) + alert_lvls, d_status = self._run_seq(always_attentive, always_false, always_true, always_false) + assert all(a == 0 for a in alert_lvls) + assert d_status.active_policy == log.DriverMonitoringState.MonitoringPolicy.vision # engaged, driver is distracted and does nothing def test_fully_distracted_driver(self): - events, d_status = self._run_seq(always_distracted, always_false, always_true, always_false) - assert len(events[int((d_status.settings._DISTRACTED_TIME-d_status.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL)/2/DT_DMON)]) == 0 - assert events[int((d_status.settings._DISTRACTED_TIME-d_status.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL + \ - ((d_status.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL-d_status.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL)/2))/DT_DMON)].names[0] == \ - EventName.preDriverDistracted - assert events[int((d_status.settings._DISTRACTED_TIME-d_status.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL + \ - ((d_status.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL)/2))/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert events[int((d_status.settings._DISTRACTED_TIME + \ - ((TEST_TIMESPAN-10-d_status.settings._DISTRACTED_TIME)/2))/DT_DMON)].names[0] == EventName.driverDistracted + alert_lvls, d_status = self._run_seq(always_distracted, always_false, always_true, always_false) + s = d_status.settings + assert alert_lvls[int(s._VISION_POLICY_ALERT_1_TIMEOUT / 2 / DT_DMON)] == 0 + assert alert_lvls[int((s._VISION_POLICY_ALERT_1_TIMEOUT + \ + (s._VISION_POLICY_ALERT_2_TIMEOUT - s._VISION_POLICY_ALERT_1_TIMEOUT) / 2) / DT_DMON)] == 1 + assert alert_lvls[int((s._VISION_POLICY_ALERT_2_TIMEOUT + \ + (s._VISION_POLICY_ALERT_3_TIMEOUT - s._VISION_POLICY_ALERT_2_TIMEOUT) / 2) / DT_DMON)] == 2 + assert alert_lvls[int((s._VISION_POLICY_ALERT_3_TIMEOUT + \ + (TEST_TIMESPAN - 10 - s._VISION_POLICY_ALERT_3_TIMEOUT) / 2) / DT_DMON)] == 3 assert isinstance(d_status.awareness, float) # engaged, no face detected the whole time, no action def test_fully_invisible_driver(self): - events, d_status = self._run_seq(always_no_face, always_false, always_true, always_false) - assert len(events[int((d_status.settings._AWARENESS_TIME-d_status.settings._AWARENESS_PRE_TIME_TILL_TERMINAL)/2/DT_DMON)]) == 0 - assert events[int((d_status.settings._AWARENESS_TIME-d_status.settings._AWARENESS_PRE_TIME_TILL_TERMINAL + \ - ((d_status.settings._AWARENESS_PRE_TIME_TILL_TERMINAL-d_status.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL)/2))/DT_DMON)].names[0] == \ - EventName.preDriverUnresponsive - assert events[int((d_status.settings._AWARENESS_TIME-d_status.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL + \ - ((d_status.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL)/2))/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert events[int((d_status.settings._AWARENESS_TIME + \ - ((TEST_TIMESPAN-10-d_status.settings._AWARENESS_TIME)/2))/DT_DMON)].names[0] == EventName.driverUnresponsive + alert_lvls, d_status = self._run_seq(always_no_face, always_false, always_true, always_false) + s = d_status.settings + assert alert_lvls[int(s._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT / 2 / DT_DMON)] == 0 + assert alert_lvls[int((s._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT + \ + (s._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT - s._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT) / 2) / DT_DMON)] == 1 + assert alert_lvls[int((s._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT + \ + (s._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT - s._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT) / 2) / DT_DMON)] == 2 + assert alert_lvls[int((s._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + \ + (TEST_TIMESPAN - 10 - s._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT) / 2) / DT_DMON)] == 3 + assert d_status.active_policy == log.DriverMonitoringState.MonitoringPolicy.wheeltouch # engaged, down to orange, driver pays attention, back to normal; then down to orange, driver touches wheel # - should have short orange recovery time and no green afterwards; wheel touch only recovers when paying attention @@ -105,13 +163,13 @@ def test_normal_driver(self): [msg_ATTENTIVE] * (int(TEST_TIMESPAN/DT_DMON)-int((DISTRACTED_SECONDS_TO_ORANGE*3+2)/DT_DMON)) interaction_vector = [car_interaction_NOT_DETECTED] * int(DISTRACTED_SECONDS_TO_ORANGE*3/DT_DMON) + \ [car_interaction_DETECTED] * (int(TEST_TIMESPAN/DT_DMON)-int(DISTRACTED_SECONDS_TO_ORANGE*3/DT_DMON)) - events, _ = self._run_seq(ds_vector, interaction_vector, always_true, always_false) - assert len(events[int(DISTRACTED_SECONDS_TO_ORANGE*0.5/DT_DMON)]) == 0 - assert events[int((DISTRACTED_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert len(events[int(DISTRACTED_SECONDS_TO_ORANGE*1.5/DT_DMON)]) == 0 - assert events[int((DISTRACTED_SECONDS_TO_ORANGE*3-0.1)/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert events[int((DISTRACTED_SECONDS_TO_ORANGE*3+0.1)/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert len(events[int((DISTRACTED_SECONDS_TO_ORANGE*3+2.5)/DT_DMON)]) == 0 + alert_lvls, _ = self._run_seq(ds_vector, interaction_vector, always_true, always_false) + assert alert_lvls[int(DISTRACTED_SECONDS_TO_ORANGE*0.5/DT_DMON)] == 0 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE-0.1)/DT_DMON)] == 2 + assert alert_lvls[int(DISTRACTED_SECONDS_TO_ORANGE*1.5/DT_DMON)] == 0 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE*3-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE*3+0.1)/DT_DMON)] == 2 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE*3+2.5)/DT_DMON)] == 0 # engaged, down to orange, driver dodges camera, then comes back still distracted, down to red, \ # driver dodges, and then touches wheel to no avail, disengages and reengages @@ -129,11 +187,11 @@ def test_biggest_comma_fan(self): = [True] * int(1/DT_DMON) op_vector[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+2.5)/DT_DMON):int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+3)/DT_DMON)] \ = [False] * int(0.5/DT_DMON) - events, _ = self._run_seq(ds_vector, interaction_vector, op_vector, always_false) - assert events[int((DISTRACTED_SECONDS_TO_ORANGE+0.5*_invisible_time)/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert events[int((DISTRACTED_SECONDS_TO_RED+1.5*_invisible_time)/DT_DMON)].names[0] == EventName.driverDistracted - assert events[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+1.5)/DT_DMON)].names[0] == EventName.driverDistracted - assert len(events[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+3.5)/DT_DMON)]) == 0 + alert_lvls, _ = self._run_seq(ds_vector, interaction_vector, op_vector, always_false) + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE+0.5*_invisible_time)/DT_DMON)] == 2 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_RED+1.5*_invisible_time)/DT_DMON)] == 3 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+1.5)/DT_DMON)] == 3 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+3.5)/DT_DMON)] == 0 # engaged, invisible driver, down to orange, driver touches wheel; then down to orange again, driver appears # - both actions should clear the alert, but momentary appearance should not @@ -144,16 +202,16 @@ def test_sometimes_transparent_commuter(self): ds_vector[int((2*INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON):int((2*INVISIBLE_SECONDS_TO_ORANGE+1+_visible_time)/DT_DMON)] = \ [msg_ATTENTIVE] * int(_visible_time/DT_DMON) interaction_vector[int((INVISIBLE_SECONDS_TO_ORANGE)/DT_DMON):int((INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON)] = [True] * int(1/DT_DMON) - events, _ = self._run_seq(ds_vector, interaction_vector, 2*always_true, 2*always_false) - assert len(events[int(INVISIBLE_SECONDS_TO_ORANGE*0.5/DT_DMON)]) == 0 - assert events[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert len(events[int((INVISIBLE_SECONDS_TO_ORANGE+0.1)/DT_DMON)]) == 0 + alert_lvls, _ = self._run_seq(ds_vector, interaction_vector, 2*always_true, 2*always_false) + assert alert_lvls[int(INVISIBLE_SECONDS_TO_ORANGE*0.5/DT_DMON)] == 0 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE+0.1)/DT_DMON)] == 0 if _visible_time == 0.5: - assert events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)].names[0] == EventName.preDriverUnresponsive + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)] == 1 elif _visible_time == 10: - assert events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert len(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)]) == 0 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)] == 0 # engaged, invisible driver, down to red, driver appears and then touches wheel, then disengages/reengages # - only disengage will clear the alert @@ -165,19 +223,19 @@ def test_last_second_responder(self): ds_vector[int(INVISIBLE_SECONDS_TO_RED/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time)/DT_DMON)] = [msg_ATTENTIVE] * int(_visible_time/DT_DMON) interaction_vector[int((INVISIBLE_SECONDS_TO_RED+_visible_time)/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time+1)/DT_DMON)] = [True] * int(1/DT_DMON) op_vector[int((INVISIBLE_SECONDS_TO_RED+_visible_time+1)/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time+0.5)/DT_DMON)] = [False] * int(0.5/DT_DMON) - events, _ = self._run_seq(ds_vector, interaction_vector, op_vector, always_false) - assert len(events[int(INVISIBLE_SECONDS_TO_ORANGE*0.5/DT_DMON)]) == 0 - assert events[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert events[int((INVISIBLE_SECONDS_TO_RED-0.1)/DT_DMON)].names[0] == EventName.driverUnresponsive - assert events[int((INVISIBLE_SECONDS_TO_RED+0.5*_visible_time)/DT_DMON)].names[0] == EventName.driverUnresponsive - assert events[int((INVISIBLE_SECONDS_TO_RED+_visible_time+0.5)/DT_DMON)].names[0] == EventName.driverUnresponsive - assert len(events[int((INVISIBLE_SECONDS_TO_RED+_visible_time+1+0.1)/DT_DMON)]) == 0 + alert_lvls, _ = self._run_seq(ds_vector, interaction_vector, op_vector, always_false) + assert alert_lvls[int(INVISIBLE_SECONDS_TO_ORANGE*0.5/DT_DMON)] == 0 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED-0.1)/DT_DMON)] == 3 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED+0.5*_visible_time)/DT_DMON)] == 3 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED+_visible_time+0.5)/DT_DMON)] == 3 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED+_visible_time+1+0.1)/DT_DMON)] == 0 # disengaged, always distracted driver # - dm should stay quiet when not engaged def test_pure_dashcam_user(self): - events, _ = self._run_seq(always_distracted, always_false, always_false, always_false) - assert sum(len(event) for event in events) == 0 + alert_lvls, _ = self._run_seq(always_distracted, always_false, always_false, always_false) + assert all(a == 0 for a in alert_lvls) # engaged, car stops at traffic light, down to orange, no action, then car starts moving # - should only reach green when stopped, but continues counting down on launch @@ -185,22 +243,649 @@ def test_long_traffic_light_victim(self): _redlight_time = 60 # seconds standstill_vector = always_true[:] standstill_vector[int(_redlight_time/DT_DMON):] = [False] * int((TEST_TIMESPAN-_redlight_time)/DT_DMON) - events, d_status = self._run_seq(always_distracted, always_false, always_true, standstill_vector) - assert events[int((d_status.settings._DISTRACTED_TIME-d_status.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL+1)/DT_DMON)].names[0] == \ - EventName.preDriverDistracted - assert events[int((_redlight_time-0.1)/DT_DMON)].names[0] == EventName.preDriverDistracted - assert events[int((_redlight_time+0.5)/DT_DMON)].names[0] == EventName.promptDriverDistracted + alert_lvls, d_status = self._run_seq(always_distracted, always_false, always_true, standstill_vector) + s = d_status.settings + assert alert_lvls[int((_redlight_time-0.1)/DT_DMON)] == 0 + _alert_1_to_2 = s._VISION_POLICY_ALERT_2_TIMEOUT - s._VISION_POLICY_ALERT_1_TIMEOUT + assert alert_lvls[int((_redlight_time+0.5)/DT_DMON)] == 1 + assert alert_lvls[int((_redlight_time+_alert_1_to_2+0.5)/DT_DMON)] == 2 + + # engaged, distracted while moving, then car stops after reaching orange + # - should reset timer to pre green at standstill + def test_distracted_then_stops(self): + _stop_time = DISTRACTED_SECONDS_TO_ORANGE + 1 # stop 1 second after reaching orange + standstill_vector = always_false[:] + standstill_vector[int(_stop_time/DT_DMON):] = [True] * int((TEST_TIMESPAN-_stop_time)/DT_DMON) + alert_lvls, _ = self._run_seq(always_distracted, always_false, always_true, standstill_vector) + # just before and briefly after stopping: orange alert; goes away quickly after stopped + assert alert_lvls[int((_stop_time+0.1)/DT_DMON)] == 2 + assert alert_lvls[int((_stop_time+0.5)/DT_DMON)] == 0 + + def test_lookaway_gate_helper(self): + """2 mph is the gate: strictly below pauses; standstill still pauses at any vEgo.""" + assert lookaway_alerts_paused(False, 0.0) + assert lookaway_alerts_paused(False, TEST_CREEP_MS) + assert lookaway_alerts_paused(False, DM_LOOKAWAY_GATE_MS - 1e-6) + assert not lookaway_alerts_paused(False, DM_LOOKAWAY_GATE_MS) + assert not lookaway_alerts_paused(False, TEST_ABOVE_GATE_MS) + assert not lookaway_alerts_paused(False, TEST_MOVING_MS) + assert lookaway_alerts_paused(True, 20.0) + + def test_creeping_below_gate_never_reaches_green(self): + """1 mph, CS.standstill false: no looking-away alert, any Sim Look / FAI combo.""" + for sim, fai in ((False, False), (True, False), (False, True)): + alert_lvls, _ = self._run_seq( + always_distracted, always_false, always_true, always_false, + simulate_looking=sim, false_alert_ignore=fai, car_speed=TEST_CREEP_MS, + rng_seed=1, + ) + assert all(a == 0 for a in alert_lvls), (sim, fai) + + def test_creeping_no_face_never_reaches_green(self): + """Eyes-off / no-face at a creep also stays quiet below the gate.""" + alert_lvls, _ = self._run_seq( + always_no_face, always_false, always_true, always_false, + simulate_looking=False, car_speed=TEST_CREEP_MS, + ) + assert all(a == 0 for a in alert_lvls) + + def test_creeping_fai_pose_does_not_alert(self): + """FAI On still lets pose drain when moving; below 2 mph it must not nag.""" + n = int(TEST_TIMESPAN / DT_DMON) + alert_lvls, _ = self._run_seq( + [msg_POSE_ONLY] * n, always_false, always_true, always_false, + simulate_looking=False, false_alert_ignore=True, + car_speed=TEST_CREEP_MS, rng_seed=3, + ) + assert all(a == 0 for a in alert_lvls) + + def test_above_gate_stock_still_reaches_green(self): + """Just above 2 mph: stock first prompt still fires (toggles Off).""" + alert_lvls, d_status = self._run_seq( + always_distracted, always_false, always_true, always_false, + simulate_looking=False, car_speed=TEST_ABOVE_GATE_MS, + ) + s = d_status.settings + assert alert_lvls[int((s._VISION_POLICY_ALERT_1_TIMEOUT + 0.4) / DT_DMON)] == 1 + assert alert_lvls[int((s._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)] == 2 + + def test_above_gate_simulate_look_still_avoids_orange(self): + """Above 2 mph, Sim Look On keeps prior 1–3 s full-wipe behavior.""" + alert_lvls, d_status = self._run_seq( + always_distracted, always_false, always_true, always_false, + simulate_looking=True, rng_seed=4, car_speed=TEST_ABOVE_GATE_MS, + ) + assert all(a < 2 for a in alert_lvls) + assert d_status.awareness > d_status.threshold_alert_2 + + def test_creeping_then_launch_continues_countdown(self): + """Like traffic-light standstill, but creeping 1 mph then rolling out.""" + _redlight_time = 60 + n = int(TEST_TIMESPAN / DT_DMON) + i_go = int(_redlight_time / DT_DMON) + speeds = [TEST_CREEP_MS] * i_go + [TEST_MOVING_MS] * (n - i_go) + alert_lvls, d_status = self._run_seq( + always_distracted, always_false, always_true, always_false, + simulate_looking=False, car_speed=speeds, + ) + s = d_status.settings + assert alert_lvls[int((_redlight_time - 0.1) / DT_DMON)] == 0 + _alert_1_to_2 = s._VISION_POLICY_ALERT_2_TIMEOUT - s._VISION_POLICY_ALERT_1_TIMEOUT + assert alert_lvls[int((_redlight_time + 0.5) / DT_DMON)] == 1 + assert alert_lvls[int((_redlight_time + _alert_1_to_2 + 0.5) / DT_DMON)] == 2 + + def test_run_step_below_gate_no_lookaway_alert(self): + """run_step uses vEgo: 1 mph + standstill false, toggles On or Off.""" + steps = int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 2.0) / DT_DMON) + for sim, fai in ((False, False), (True, False), (False, True)): + DM = DriverMonitoring() + DM.nap_dm_simulate_looking = sim + DM.nap_dm_false_alert_ignore = fai + for _ in range(steps): + DM.run_step(_fake_sm(hands=0, driver_state=msg_DISTRACTED, + v_ego=TEST_CREEP_MS, standstill=False)) + assert DM.alert_level == 0, (sim, fai) # engaged, model is somehow uncertain and driver is distracted # - should fall back to wheel touch after uncertain alert def test_somehow_indecisive_model(self): ds_vector = [msg_DISTRACTED_BUT_SOMEHOW_UNCERTAIN] * int(TEST_TIMESPAN/DT_DMON) interaction_vector = always_false[:] - events, d_status = self._run_seq(ds_vector, interaction_vector, always_true, always_false) - assert EventName.preDriverUnresponsive in \ - events[int((INVISIBLE_SECONDS_TO_ORANGE-1+DT_DMON*d_status.settings._HI_STD_FALLBACK_TIME-0.1)/DT_DMON)].names - assert EventName.promptDriverUnresponsive in \ - events[int((INVISIBLE_SECONDS_TO_ORANGE-1+DT_DMON*d_status.settings._HI_STD_FALLBACK_TIME+0.1)/DT_DMON)].names - assert EventName.driverUnresponsive in \ - events[int((INVISIBLE_SECONDS_TO_RED-1+DT_DMON*d_status.settings._HI_STD_FALLBACK_TIME+0.1)/DT_DMON)].names + alert_lvls, d_status = self._run_seq(ds_vector, interaction_vector, always_true, always_false) + s = d_status.settings + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE-1+DT_DMON*s._HI_STD_FALLBACK_TIME-0.1)/DT_DMON)] == 1 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE-1+DT_DMON*s._HI_STD_FALLBACK_TIME+0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED-1+DT_DMON*s._HI_STD_FALLBACK_TIME+0.1)/DT_DMON)] == 3 + + def test_stock_vision_timeouts_unchanged(self): + s = DRIVER_MONITOR_SETTINGS() + assert s._VISION_POLICY_ALERT_1_TIMEOUT == 3. + assert s._VISION_POLICY_ALERT_2_TIMEOUT == 5. + assert s._VISION_POLICY_ALERT_3_TIMEOUT == 11. + assert PARAM_DM_SIMULATE_LOOKING == "NAPDmSimulateLooking" + assert PARAM_DM_FALSE_ALERT_IGNORE == "NAPDmFalseAlertIgnore" + assert DEFAULT_SIMULATE_LOOKING is True + assert DEFAULT_FALSE_ALERT_IGNORE is False + assert LOOK_SIM_MODE_PHONE == "phone" + assert LOOK_SIM_MODE_GLANCE == "glance" + assert LOOK_SIM_COUNTDOWN_MIN_S == 1.0 + assert LOOK_SIM_RANDOM_WINDOW_S == 2.0 + assert LOOK_SIM_FIRE_MAX_S == 3.0 + assert LOOK_SIM_HOLD_MIN_S == 0.5 + assert LOOK_SIM_HOLD_MAX_S == 12.0 + assert VISION_LOOKING_FILTER_X == 0.37 + assert s._TIMEOUT_RECOVERY_FACTOR_MAX == VISION_RECOVERY_FACTOR_MAX == 5. + assert s._TIMEOUT_RECOVERY_FACTOR_MIN == VISION_RECOVERY_FACTOR_MIN == 1.25 + assert DM_LOOKAWAY_GATE_MPH == 2.0 + assert abs(DM_LOOKAWAY_GATE_MS - 2.0 * CV.MPH_TO_MS) < 1e-9 + + def test_vision_looking_path_is_stock_glance_predicates(self): + """Green-prompt clear path: face + low std + filter.x < 0.37.""" + assert vision_looking_path(True, True, 0.0) + assert vision_looking_path(True, True, VISION_LOOKING_FILTER_X - 0.01) + assert not vision_looking_path(True, True, VISION_LOOKING_FILTER_X) + assert not vision_looking_path(False, True, 0.0) + assert not vision_looking_path(True, False, 0.0) + assert not vision_looking_path(True, True, 0.63) + + def test_looking_recovery_time_matches_policy_math(self): + """Closed-form hold length matches discrete stock recovery to 1.0.""" + s = DRIVER_MONITOR_SETTINGS() + t3 = s._VISION_POLICY_ALERT_3_TIMEOUT + step = DT_DMON / t3 + for deficit_s in (1.0, 2.0, 3.0, 5.0): + awareness = 1.0 - deficit_s / t3 + predicted = looking_recovery_time_s(awareness, t3) + a = awareness + frames = 0 + while a < 1.0 - 1e-12 and frames < 400: + a = min(a + ((s._TIMEOUT_RECOVERY_FACTOR_MAX - s._TIMEOUT_RECOVERY_FACTOR_MIN) * + (1. - a) + s._TIMEOUT_RECOVERY_FACTOR_MIN) * step, 1.) + frames += 1 + discrete = frames * DT_DMON + assert abs(discrete - predicted) < 2 * DT_DMON + 1e-6 + assert predicted >= LOOK_SIM_HOLD_MIN_S or deficit_s < 1.0 + + def _dm(self, *, simulate_looking=False, false_alert_ignore=False, fire_s=2.0): + DM = DriverMonitoring() + DM.nap_dm_simulate_looking = bool(simulate_looking) + DM.nap_dm_false_alert_ignore = bool(false_alert_ignore) + DM._look_sim_fire_s = fire_s + return DM + + def _step(self, DM, msg, *, car_speed=TEST_MOVING_MS, standstill=False): + DM._update_states(msg, [0, 0, 0], car_speed, True, standstill) + DM._update_events(False, True, standstill, 0) + + def test_simulate_looking_holds_until_awareness_recovers(self): + """Full-wipe hold is many frames on the looking-path; awareness to 1.0.""" + DM = self._dm(simulate_looking=True) + hold_frames = 0 + start_a = None + first_hold_a = None + recovered = False + for _ in range(int(10.0 / DT_DMON)): + self._step(DM, msg_NO_FACE_DETECTED) + if DM._look_sim_holding: + hold_frames += 1 + assert DM._look_sim_mode == LOOK_SIM_MODE_GLANCE + assert vision_looking_path(DM.face_detected, DM.pose.low_std, + DM.driver_distraction_filter.x) + if start_a is None: + start_a = DM._look_sim_hold_start_awareness + first_hold_a = DM.awareness + if DM.awareness >= 1.0 - 1e-9 and hold_frames * DT_DMON >= LOOK_SIM_HOLD_MIN_S: + recovered = True + break + assert recovered + assert start_a is not None and start_a < 0.95 + assert first_hold_a is not None and first_hold_a < 1.0 + assert hold_frames >= int(LOOK_SIM_HOLD_MIN_S / DT_DMON) + predicted = looking_recovery_time_s(start_a, DM.settings._VISION_POLICY_ALERT_3_TIMEOUT) + assert hold_frames * DT_DMON + DT_DMON >= max(LOOK_SIM_HOLD_MIN_S, predicted) - 2 * DT_DMON + assert DM.alert_level == 0 + + def test_simulate_looking_fires_in_1_to_3s_window(self): + """No hold until drain is past 1.0 s; fire time is uniform in (1.0 s, 3.0 s].""" + DM = self._dm(simulate_looking=True, fire_s=0.4) # would fire early without the 1 s gate + drain_start = None + hold_start = None + for i in range(int(6.0 / DT_DMON)): + was_holding = DM._look_sim_holding + self._step(DM, msg_NO_FACE_DETECTED) + if drain_start is None and DM.awareness < 1.0 and not DM._look_sim_holding: + drain_start = i * DT_DMON + if hold_start is None and DM._look_sim_holding and not was_holding: + hold_start = i * DT_DMON + break + assert drain_start is not None and hold_start is not None + assert (hold_start - drain_start) > LOOK_SIM_COUNTDOWN_MIN_S - 1e-6 + assert (hold_start - drain_start) <= LOOK_SIM_FIRE_MAX_S + 0.15 + + elapsed = [] + for seed in range(16): + DM = DriverMonitoring() + DM.nap_dm_simulate_looking = True + DM.nap_dm_false_alert_ignore = False + DM._rng.seed(seed) + DM._redraw_look_sim_interval() + fire_s = DM._look_sim_fire_s + assert LOOK_SIM_COUNTDOWN_MIN_S < fire_s <= LOOK_SIM_FIRE_MAX_S + drain_start = None + hold_start = None + for i in range(int(8.0 / DT_DMON)): + was_holding = DM._look_sim_holding + self._step(DM, msg_NO_FACE_DETECTED) + if drain_start is None and DM.awareness < 1.0 and not DM._look_sim_holding: + drain_start = i * DT_DMON + if hold_start is None and DM._look_sim_holding and not was_holding: + hold_start = i * DT_DMON + break + assert drain_start is not None and hold_start is not None + dt = hold_start - drain_start + assert abs(dt - fire_s) < 0.15 + assert LOOK_SIM_COUNTDOWN_MIN_S < dt <= LOOK_SIM_FIRE_MAX_S + 0.15 + elapsed.append(dt) + assert max(elapsed) - min(elapsed) > 0.5 + assert min(elapsed) > LOOK_SIM_COUNTDOWN_MIN_S - 1e-6 + assert max(elapsed) <= LOOK_SIM_FIRE_MAX_S + 0.15 + + def test_simulate_looking_fire_time_redraws_in_window(self): + DM = DriverMonitoring() + DM.nap_dm_simulate_looking = True + DM._rng.seed(11) + seen = [] + for _ in range(40): + DM._redraw_look_sim_interval() + t = DM._look_sim_fire_s + assert LOOK_SIM_COUNTDOWN_MIN_S < t <= LOOK_SIM_FIRE_MAX_S + seen.append(round(t, 4)) + assert len(set(seen)) >= 8 + assert not all(abs(x - seen[0]) < 1e-6 for x in seen) + assert any(x <= LOOK_SIM_COUNTDOWN_MIN_S + 0.5 for x in seen) + assert any(x >= LOOK_SIM_FIRE_MAX_S - 0.5 for x in seen) + + def test_simulate_looking_engaged_never_reaches_orange(self): + """Periodic full-wipe looking-path resets keep awareness above orange.""" + alert_lvls, d_status = self._run_seq(always_distracted, always_false, always_true, + always_false, simulate_looking=True, rng_seed=4) + assert all(a < 2 for a in alert_lvls) + assert d_status.awareness > d_status.threshold_alert_2 + assert d_status.alert_level in (0, 1) + + def test_simulate_looking_no_face_also_resets(self): + """maybe_distracted / no-face drain still gets a simulated glance.""" + alert_lvls, d_status = self._run_seq(always_no_face, always_false, always_true, + always_false, simulate_looking=True, rng_seed=2) + assert all(a < 2 for a in alert_lvls) + assert d_status.awareness > 0.5 + + def test_simulate_looking_clears_already_orange(self): + """If he is already in orange, the next wipe pulse still resets.""" + DM = self._dm(simulate_looking=False) + for _ in range(int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)): + self._step(DM, msg_DISTRACTED) + assert DM.alert_level == 2 + DM.set_nap_dm_toggles(simulate_looking=True) + DM._look_sim_fire_s = 2.0 + DM._look_sim_countdown_s = 0.0 + cleared = False + for _ in range(int(12.0 / DT_DMON)): + self._step(DM, msg_DISTRACTED) + if DM.awareness >= 1.0 - 1e-9 and DM.alert_level == 0: + assert vision_looking_path(DM.face_detected, DM.pose.low_std, + DM.driver_distraction_filter.x) + assert DM._look_sim_hold_s + DT_DMON >= LOOK_SIM_HOLD_MIN_S + cleared = True + break + assert cleared + + def test_simulate_looking_recovers_eye(self): + """Eye blink drain is wiped on cadence; never reaches orange.""" + alert_lvls, d_status = self._run_seq(always_distracted, always_false, always_true, + always_false, simulate_looking=True, rng_seed=4) + assert all(a < 2 for a in alert_lvls) + assert d_status.awareness > d_status.threshold_alert_2 + + def test_simulate_looking_recovers_phone(self): + """Phone-only drain is wiped on cadence when Simulate Look is On.""" + n = int(TEST_TIMESPAN / DT_DMON) + alert_lvls, d_status = self._run_seq( + [msg_PHONE_ONLY] * n, always_false, always_true, always_false, + simulate_looking=True, false_alert_ignore=False, rng_seed=2, + ) + assert all(a < 2 for a in alert_lvls) + assert d_status.awareness > d_status.threshold_alert_2 + + def test_simulate_looking_recovers_pose(self): + """Pose drain is wiped on cadence when Simulate Look is On.""" + n = int(TEST_TIMESPAN / DT_DMON) + alert_lvls, d_status = self._run_seq( + [msg_POSE_ONLY] * n, always_false, always_true, always_false, + simulate_looking=True, false_alert_ignore=False, rng_seed=3, + ) + assert all(a < 2 for a in alert_lvls) + assert d_status.awareness > d_status.threshold_alert_2 + + def test_simulate_looking_off_is_stock(self): + """Toggle Off: first prompt → orange → red on stock 3 / 5 / 11 s.""" + alert_lvls, d_status = self._run_seq(always_distracted, always_false, always_true, + always_false, simulate_looking=False) + s = d_status.settings + assert alert_lvls[int(s._VISION_POLICY_ALERT_1_TIMEOUT / 2 / DT_DMON)] == 0 + assert alert_lvls[int((s._VISION_POLICY_ALERT_1_TIMEOUT + 0.4) / DT_DMON)] == 1 + assert alert_lvls[int((s._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)] == 2 + assert alert_lvls[int((s._VISION_POLICY_ALERT_3_TIMEOUT + 0.4) / DT_DMON)] == 3 + + def test_always_on_disengaged_does_not_simulate(self): + """AlwaysOnDM when not engaged still counts; no simulated glances.""" + n = int(TEST_TIMESPAN / DT_DMON) + DM = DriverMonitoring(always_on=True) + DM.nap_dm_simulate_looking = True + DM.nap_dm_false_alert_ignore = True + alert_lvls = [] + for idx in range(n): + DM._update_states(always_distracted[idx], [0, 0, 0], TEST_MOVING_MS, False, False) + DM._update_events(False, False, False, 0) + alert_lvls.append(DM.alert_level) + s = DM.settings + orange_i = int((s._VISION_POLICY_ALERT_2_TIMEOUT + 0.6) / DT_DMON) + assert 1 in alert_lvls[:orange_i] + assert alert_lvls[orange_i] == 2 + + def test_run_step_simulate_looking_holds_above_orange(self): + DM = DriverMonitoring() + DM.nap_dm_simulate_looking = True + DM.nap_dm_false_alert_ignore = False + DM._rng.seed(5) + DM._redraw_look_sim_interval() + steps = int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 1.0) / DT_DMON) + for _ in range(steps): + DM.run_step(_fake_sm(hands=0, driver_state=msg_DISTRACTED)) + assert DM.alert_level < 2 + assert DM.awareness > DM.threshold_alert_2 + + def test_run_step_param_off_is_stock(self): + DM = DriverMonitoring() + DM.nap_dm_simulate_looking = False + DM.nap_dm_false_alert_ignore = False + steps = int((dm_settings._VISION_POLICY_ALERT_1_TIMEOUT + 0.4) / DT_DMON) + for _ in range(steps): + DM.run_step(_fake_sm(hands=0, driver_state=msg_DISTRACTED)) + assert DM.alert_level == 1 + for _ in range(int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT - + dm_settings._VISION_POLICY_ALERT_1_TIMEOUT + 0.5) / DT_DMON)): + DM.run_step(_fake_sm(hands=0, driver_state=msg_DISTRACTED)) + assert DM.alert_level == 2 + + def test_false_alert_ignore_phone_only_recovers(self): + """Phone-only + FAI On: awareness recovers on the 1–3 s cadence without a glance.""" + n = int(TEST_TIMESPAN / DT_DMON) + alert_lvls, d_status = self._run_seq( + [msg_PHONE_ONLY] * n, always_false, always_true, always_false, + false_alert_ignore=True, rng_seed=4, + ) + assert all(a < 2 for a in alert_lvls) + assert d_status.awareness > d_status.threshold_alert_2 + assert d_status.alert_level in (0, 1) + + def test_false_alert_ignore_phone_soft_clear_not_pose_eye(self): + """Hold clears the phone bit only; pose/eye types stay false on phone-only.""" + DM = self._dm(false_alert_ignore=True) + recovered = False + for _ in range(int(10.0 / DT_DMON)): + self._step(DM, msg_PHONE_ONLY) + if DM._look_sim_holding: + assert DM._look_sim_mode == LOOK_SIM_MODE_PHONE + assert DM.distracted_types['phone'] is False + assert DM.distracted_types['pose'] is False + assert DM.distracted_types['eye'] is False + assert not DM.driver_distracted + assert vision_looking_path(DM.face_detected, DM.pose.low_std, + DM.driver_distraction_filter.x) + if DM.awareness >= 1.0 - 1e-9 and DM._look_sim_hold_s + 1e-9 >= LOOK_SIM_HOLD_MIN_S: + recovered = True + break + assert recovered + assert DM.alert_level == 0 + + def test_false_alert_ignore_pose_still_drains(self): + """Pose alarming: FAI On (Sim Off) does not reset the timer.""" + n = int(TEST_TIMESPAN / DT_DMON) + alert_lvls, d_status = self._run_seq( + [msg_POSE_ONLY] * n, always_false, always_true, always_false, + simulate_looking=False, false_alert_ignore=True, rng_seed=3, + ) + s = d_status.settings + assert alert_lvls[int((s._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)] == 2 + assert alert_lvls[int((s._VISION_POLICY_ALERT_3_TIMEOUT + 0.4) / DT_DMON)] == 3 + assert d_status.distracted_types['pose'] + assert not d_status._look_sim_holding + + def test_false_alert_ignore_eye_still_drains(self): + """Eye alarming: FAI On (Sim Off) does not reset; orange/red on stock timers.""" + n = int(TEST_TIMESPAN / DT_DMON) + alert_lvls, d_status = self._run_seq( + [msg_DISTRACTED] * n, always_false, always_true, always_false, + simulate_looking=False, false_alert_ignore=True, rng_seed=3, + ) + s = d_status.settings + assert alert_lvls[int((s._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)] == 2 + assert alert_lvls[int((s._VISION_POLICY_ALERT_3_TIMEOUT + 0.4) / DT_DMON)] == 3 + assert d_status.distracted_types['eye'] + + def test_false_alert_ignore_phone_plus_eye_eye_wins(self): + """Phone + eye: FAI On (Sim Off) does not start a phone hold; eye drains.""" + DM = self._dm(simulate_looking=False, false_alert_ignore=True, fire_s=1.2) + for _ in range(int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)): + self._step(DM, msg_PHONE_AND_EYE) + assert DM.distracted_types['eye'] + assert DM.distracted_types['phone'] + assert not DM._look_sim_holding + assert DM.alert_level == 2 + + def test_false_alert_ignore_phone_plus_pose_pose_wins(self): + """Phone + pose: FAI On (Sim Off) does not reset; pose keeps draining.""" + DM = self._dm(simulate_looking=False, false_alert_ignore=True, fire_s=1.2) + for _ in range(int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)): + self._step(DM, msg_PHONE_AND_POSE) + assert DM.distracted_types['pose'] + assert DM.distracted_types['phone'] + assert not DM._look_sim_holding + assert DM.alert_level == 2 + assert DM.awareness <= DM.threshold_alert_2 + + def test_false_alert_ignore_phone_clears_after_pose_drops(self): + """After pose clears, remaining phone-only can soft-clear on the same cadence.""" + DM = self._dm(false_alert_ignore=True, fire_s=1.2) + for _ in range(int(3.5 / DT_DMON)): + self._step(DM, msg_PHONE_AND_POSE) + assert DM.distracted_types['pose'] + assert not DM._look_sim_holding + drained = DM.awareness + assert drained < 0.8 + recovered = False + for _ in range(int(10.0 / DT_DMON)): + self._step(DM, msg_PHONE_ONLY) + if DM._look_sim_holding: + assert DM._look_sim_mode == LOOK_SIM_MODE_PHONE + assert DM.distracted_types['pose'] is False + assert DM.distracted_types['phone'] is False + if DM.awareness >= 1.0 - 1e-9 and DM.alert_level == 0: + recovered = True + break + assert recovered + assert DM.awareness > drained + + def test_false_alert_ignore_off_phone_is_stock_without_sim_look(self): + """Both Off: phone-only drains on stock timers.""" + n = int(TEST_TIMESPAN / DT_DMON) + alert_lvls, d_status = self._run_seq( + [msg_PHONE_ONLY] * n, always_false, always_true, always_false, + simulate_looking=False, false_alert_ignore=False, rng_seed=2, + ) + s = d_status.settings + assert alert_lvls[int((s._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)] == 2 + assert alert_lvls[int((s._VISION_POLICY_ALERT_3_TIMEOUT + 0.4) / DT_DMON)] == 3 + assert d_status.distracted_types['phone'] + + def test_false_alert_ignore_off_both_off_phone_is_stock(self): + n = int(TEST_TIMESPAN / DT_DMON) + alert_lvls, d_status = self._run_seq( + [msg_PHONE_ONLY] * n, always_false, always_true, always_false, + ) + s = d_status.settings + assert alert_lvls[int((s._VISION_POLICY_ALERT_1_TIMEOUT + 0.4) / DT_DMON)] == 1 + assert alert_lvls[int((s._VISION_POLICY_ALERT_2_TIMEOUT + 0.4) / DT_DMON)] == 2 + + def test_false_alert_ignore_aborts_hold_when_pose_starts(self): + """Mid-hold pose must abort and resume draining (no awareness reset).""" + DM = self._dm(false_alert_ignore=True, fire_s=1.2) + holding = False + for _ in range(int(6.0 / DT_DMON)): + self._step(DM, msg_PHONE_ONLY) + if DM._look_sim_holding: + holding = True + a_at_hold = DM.awareness + break + assert holding + for _ in range(int(2.0 / DT_DMON)): + self._step(DM, msg_PHONE_AND_POSE) + assert not DM._look_sim_holding + assert DM.distracted_types['pose'] + assert DM.awareness < a_at_hold + 1e-6 + for _ in range(int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT) / DT_DMON)): + self._step(DM, msg_PHONE_AND_POSE) + assert DM.alert_level >= 2 + + def test_simulate_looking_full_wipe_clears_phone(self): + """Simulate Look On owns the full wipe, including phone false nags.""" + DM = self._dm(simulate_looking=True, false_alert_ignore=False, fire_s=1.2) + holding = False + for _ in range(int(4.0 / DT_DMON)): + self._step(DM, msg_PHONE_ONLY) + if DM._look_sim_holding: + holding = True + assert DM._look_sim_mode == LOOK_SIM_MODE_GLANCE + assert DM.distracted_types['phone'] is False + assert not DM.driver_distracted + assert vision_looking_path(DM.face_detected, DM.pose.low_std, + DM.driver_distraction_filter.x) + break + assert holding + + def test_simulate_looking_keeps_hold_when_pose_starts(self): + """Mid-hold pose must not abort Simulate Look the way FAI aborts.""" + DM = self._dm(simulate_looking=True, fire_s=1.2) + holding = False + for _ in range(int(6.0 / DT_DMON)): + self._step(DM, msg_NO_FACE_DETECTED) + if DM._look_sim_holding: + holding = True + a_at_hold = DM.awareness + break + assert holding + self._step(DM, msg_POSE_ONLY) + assert DM._look_sim_holding + assert DM._look_sim_mode == LOOK_SIM_MODE_GLANCE + assert DM.distracted_types['pose'] is False + assert not DM.driver_distracted + assert DM.awareness >= a_at_hold - 1e-6 + for _ in range(int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 1.0) / DT_DMON)): + self._step(DM, msg_POSE_ONLY) + assert DM.alert_level < 2 + assert DM.awareness > DM.threshold_alert_2 + + def test_simulate_looking_hold_recovers_phone_pose_eye(self): + """One cadence hold recovers awareness for phone, pose, and eye inputs.""" + for msg in (msg_PHONE_ONLY, msg_POSE_ONLY, msg_DISTRACTED, msg_PHONE_AND_POSE, + msg_PHONE_AND_EYE): + DM = self._dm(simulate_looking=True, fire_s=1.2) + recovered = False + for _ in range(int(10.0 / DT_DMON)): + self._step(DM, msg) + if DM._look_sim_holding: + assert DM._look_sim_mode == LOOK_SIM_MODE_GLANCE + assert DM.distracted_types['phone'] is False + assert DM.distracted_types['pose'] is False + assert DM.distracted_types['eye'] is False + assert not DM.driver_distracted + if DM.awareness >= 1.0 - 1e-9 and DM.alert_level == 0: + recovered = True + break + assert recovered, f"did not recover for {msg}" + + def test_run_step_false_alert_ignore_phone_holds_above_orange(self): + DM = DriverMonitoring() + DM.nap_dm_simulate_looking = False + DM.nap_dm_false_alert_ignore = True + DM._rng.seed(5) + DM._redraw_look_sim_interval() + steps = int((dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 1.0) / DT_DMON) + for _ in range(steps): + DM.run_step(_fake_sm(hands=0, driver_state=msg_PHONE_ONLY)) + assert DM.alert_level < 2 + assert DM.awareness > DM.threshold_alert_2 + + def test_stale_both_on_prefers_simulate_look_full_wipe(self): + """Both-On (old install) resolves to Simulate Look; phone recovers via wipe.""" + DM = self._dm(simulate_looking=True, false_alert_ignore=True, fire_s=1.2) + holding = False + for _ in range(int(4.0 / DT_DMON)): + self._step(DM, msg_PHONE_ONLY) + if DM._look_sim_holding: + holding = True + assert DM._look_sim_mode == LOOK_SIM_MODE_GLANCE + assert DM.distracted_types['phone'] is False + break + assert DM.nap_dm_simulate_looking is True + assert DM.nap_dm_false_alert_ignore is False + assert holding + glance = False + DM._end_look_sim_hold(redraw=True) + DM._look_sim_fire_s = 1.2 + for _ in range(int(6.0 / DT_DMON)): + self._step(DM, msg_NO_FACE_DETECTED) + if DM._look_sim_holding: + assert DM._look_sim_mode == LOOK_SIM_MODE_GLANCE + glance = True + break + assert glance + + def test_turning_fai_on_aborts_glance_hold(self): + DM = self._dm(simulate_looking=True, fire_s=1.2) + holding = False + for _ in range(int(6.0 / DT_DMON)): + self._step(DM, msg_NO_FACE_DETECTED) + if DM._look_sim_holding: + holding = True + assert DM._look_sim_mode == LOOK_SIM_MODE_GLANCE + break + assert holding + DM.set_nap_dm_toggles(false_alert_ignore=True) + assert DM.nap_dm_simulate_looking is False + assert DM.nap_dm_false_alert_ignore is True + assert not DM._look_sim_holding + assert DM._look_sim_mode is None + + def test_turning_simulate_look_on_stops_phone_hold(self): + DM = self._dm(false_alert_ignore=True, fire_s=1.2) + holding = False + for _ in range(int(6.0 / DT_DMON)): + self._step(DM, msg_PHONE_ONLY) + if DM._look_sim_holding: + holding = True + assert DM._look_sim_mode == LOOK_SIM_MODE_PHONE + break + assert holding + DM.set_nap_dm_toggles(simulate_looking=True) + assert DM.nap_dm_simulate_looking is True + assert DM.nap_dm_false_alert_ignore is False + assert not DM._look_sim_holding + assert DM._look_sim_mode is None + def test_set_both_true_resolves_to_simulate_look(self): + DM = self._dm(simulate_looking=False, false_alert_ignore=True) + DM.set_nap_dm_toggles(simulate_looking=True, false_alert_ignore=True) + assert DM.nap_dm_simulate_looking is True + assert DM.nap_dm_false_alert_ignore is False diff --git a/selfdrive/nap_dash/__init__.py b/selfdrive/nap_dash/__init__.py new file mode 100644 index 00000000000000..1c842f6141c847 --- /dev/null +++ b/selfdrive/nap_dash/__init__.py @@ -0,0 +1 @@ +"""In-tree NAP companion Dash (hotspot web UI on the comma device).""" diff --git a/selfdrive/nap_dash/dashboard.html b/selfdrive/nap_dash/dashboard.html new file mode 100644 index 00000000000000..830d120a3876a7 --- /dev/null +++ b/selfdrive/nap_dash/dashboard.html @@ -0,0 +1,841 @@ + + + + + +openpilot + + + +
+
+
+ +
+ +
+
+ +

+
+
+
+
+
+ + + + + diff --git a/selfdrive/nap_dash/discover.py b/selfdrive/nap_dash/discover.py new file mode 100644 index 00000000000000..bbe00bae76fdef --- /dev/null +++ b/selfdrive/nap_dash/discover.py @@ -0,0 +1,1152 @@ +"""Read device-UI settings source and build the web manifest. + +The comma UI (selfdrive/ui/layouts/settings) stays the source of truth. +This module only parses those files. It does not import them, so pyray, +cereal, and the speed-limit processes are never started from here. +""" +from __future__ import annotations + +import ast +import re +from pathlib import Path +from typing import Any + +MISSING = object() + +# Sidebar class -> manifest id. Titles still come from the PanelInfo strings. +_PANEL_CLASS = { + "DeviceLayout": "device", + "NetworkUI": "network", + "TogglesLayout": "toggles", + "SoftwareLayout": "software", + "NAPLayout": "nap", + "FirehoseLayout": "firehose", + "DeveloperLayout": "developer", +} + +_FILE_PANEL = { + "toggles.py": "toggles", + "developer.py": "developer", + "device.py": "device", + "hidden_toggles.py": "nap_hidden", + "driving_mannerisms.py": "nap_mannerisms", + "map_speed.py": "nap_map", + "firehose.py": "firehose", + "nap.py": "nap", +} + +_PAGE_PANEL = { + "driving_mannerisms": "nap_mannerisms", + "map_speed": "nap_map", + "radar": "nap_radar", +} + +_BUILD_METHODS = ("_build_items", "_initialize_items", "__init__") +_MAX_MODULES = 250 + + +def repo_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _is_missing(value: Any) -> bool: + return value is MISSING + + +def _call_name(node: ast.AST) -> str: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + return "" + + +def _dotted(node: ast.AST) -> str: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = _dotted(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + +class _Env(dict): + """Constant table. Classes are nested dicts.""" + + +def _eval(node: ast.AST | None, env: _Env) -> Any: + if node is None: + return MISSING + if isinstance(node, ast.Constant): + return node.value + if isinstance(node, ast.Name): + return env.get(node.id, MISSING) + if isinstance(node, ast.Attribute): + base = _eval(node.value, env) + if isinstance(base, dict) and node.attr in base: + return base[node.attr] + return MISSING + if isinstance(node, (ast.List, ast.Tuple)): + out = [] + for elt in node.elts: + value = _eval(elt, env) + if _is_missing(value): + return MISSING + out.append(value) + return out + if isinstance(node, ast.Dict): + result = {} + for key, value in zip(node.keys, node.values, strict=True): + k = _eval(key, env) + v = _eval(value, env) + if _is_missing(k) or _is_missing(v): + return MISSING + result[k] = v + return result + if isinstance(node, ast.Subscript): + container = _eval(node.value, env) + index = _eval(node.slice, env) + if _is_missing(container) or _is_missing(index): + return MISSING + try: + return container[index] + except Exception: + return MISSING + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub): + value = _eval(node.operand, env) + if isinstance(value, (int, float)) and not isinstance(value, bool): + return -value + return MISSING + if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)): + left = _eval(node.left, env) + right = _eval(node.right, env) + if _is_missing(left) or _is_missing(right): + return MISSING + try: + return left + right if isinstance(node.op, ast.Add) else left - right + except Exception: + return MISSING + if isinstance(node, ast.BoolOp): + values = [_eval(v, env) for v in node.values] + if any(_is_missing(v) for v in values): + return MISSING + if isinstance(node.op, ast.And): + return all(values) + return any(values) + if isinstance(node, ast.IfExp): + test = _eval(node.test, env) + if _is_missing(test): + return MISSING + return _eval(node.body if test else node.orelse, env) + if isinstance(node, ast.JoinedStr): + return _eval_joined(node, env) + if isinstance(node, ast.FormattedValue): + value = _eval(node.value, env) + if _is_missing(value): + return MISSING + spec = "" + if node.format_spec is not None: + spec = _eval(node.format_spec, env) + if _is_missing(spec): + return MISSING + if spec == "+d" and isinstance(value, int) and not isinstance(value, bool): + return f"{value:+d}" + if spec == "" or spec is None: + return str(value) + return MISSING + if isinstance(node, ast.Lambda): + return _eval(node.body, env) + if isinstance(node, ast.ListComp): + return _eval_listcomp(node, env) + if isinstance(node, ast.Call): + return _eval_call(node, env) + return MISSING + + +def _eval_joined(node: ast.JoinedStr, env: _Env) -> Any: + parts: list[str] = [] + for value in node.values: + piece = _eval(value, env) + if _is_missing(piece): + return MISSING + parts.append(str(piece)) + return "".join(parts) + + +def _eval_listcomp(node: ast.ListComp, env: _Env) -> Any: + if len(node.generators) != 1 or node.generators[0].ifs: + return MISSING + gen = node.generators[0] + if not isinstance(gen.target, ast.Name): + return MISSING + iterable = _eval(gen.iter, env) + if not isinstance(iterable, list): + return MISSING + out = [] + for item in iterable: + local = _Env(env) + local[gen.target.id] = item + value = _eval(node.elt, local) + if _is_missing(value): + return MISSING + out.append(value) + return out + + +def _eval_call(node: ast.Call, env: _Env) -> Any: + func = node.func + if isinstance(func, ast.Name) and func.id in ("tr", "tr_noop"): + return _eval(node.args[0], env) if node.args else MISSING + if isinstance(func, ast.Name) and func.id == "str" and node.args: + value = _eval(node.args[0], env) + return MISSING if _is_missing(value) else str(value) + if isinstance(func, ast.Name) and func.id in ("int", "float") and node.args: + value = _eval(node.args[0], env) + if _is_missing(value): + return MISSING + try: + return int(value) if func.id == "int" else float(value) + except Exception: + return MISSING + if isinstance(func, ast.Name) and func.id == "list" and len(node.args) == 1: + value = _eval(node.args[0], env) + return value if isinstance(value, list) else MISSING + if isinstance(func, ast.Name) and func.id == "range": + args = [] + for arg in node.args: + value = _eval(arg, env) + if not isinstance(value, int) or isinstance(value, bool): + return MISSING + args.append(value) + try: + return list(range(*args)) + except Exception: + return MISSING + if isinstance(func, ast.Attribute) and func.attr == "split" and node.args: + base = _eval(func.value, env) + sep = _eval(node.args[0], env) + if isinstance(base, str) and isinstance(sep, str): + maxsplit = -1 + if len(node.args) > 1: + raw = _eval(node.args[1], env) + if isinstance(raw, int): + maxsplit = raw + return base.split(sep, maxsplit) + return MISSING + + +def _as_str(value: Any) -> str: + return value if isinstance(value, str) else "" + + +def _kw(node: ast.Call, name: str) -> ast.AST | None: + for keyword in node.keywords: + if keyword.arg == name: + return keyword.value + return None + + +def _mentions(node: ast.AST, suffix: str) -> bool: + for child in ast.walk(node): + if _dotted(child).endswith(suffix): + return True + return False + + +def _lock_flags(node: ast.AST | None) -> dict[str, bool]: + """How the device disables a control, from an enabled= expression.""" + flags = {"lock_onroad": False, "lock_engaged": False, "disabled": False} + if node is None: + return flags + if isinstance(node, ast.Constant) and node.value is False: + flags["disabled"] = True + return flags + dotted = _dotted(node) + if dotted.endswith("is_offroad"): + flags["lock_onroad"] = True + if isinstance(node, ast.Lambda): + body = node.body + if isinstance(body, ast.UnaryOp) and isinstance(body.op, ast.Not): + if _dotted(body.operand).endswith("engaged"): + flags["lock_engaged"] = True + if _mentions(body, "is_offroad"): + flags["lock_onroad"] = True + if _mentions(body, "engaged"): + flags["lock_engaged"] = True + if dotted.endswith("engaged"): + flags["lock_engaged"] = True + return flags + + +def _blank(panel: str, kind: str, title: str) -> dict[str, Any]: + return { + "id": "", + "panel": panel, + "section": "", + "param": "", + "title": title, + "description": "", + "kind": kind, + "confirm": False, + "lock_onroad": False, + "lock_engaged": False, + "disabled": False, + "needs_restart": False, + "reboot_hint": False, + "writer": "", + "choices": [], + "values": [], + "also_clear": [], + "lock_param": "", + "release_hidden": False, + "hide_param": "", + "target_panel": "", + "writable": kind in ("toggle", "choice", "action"), + } + + +def _finish(ctrl: dict[str, Any]) -> dict[str, Any]: + if ctrl["disabled"]: + ctrl["writable"] = False + key = ctrl["param"] or ctrl["title"] + ctrl["id"] = f"{ctrl['panel']}:{key}" + return ctrl + + +class _Modules: + def __init__(self, root: Path, extra_dirs: list[Path]): + self.root = root + self.extra_dirs = extra_dirs + self.cache: dict[str, _Env] = {} + self.loading: set[str] = set() + + def load(self, module: str) -> _Env: + if module in self.cache: + return self.cache[module] + if module in self.loading or len(self.cache) >= _MAX_MODULES: + return _Env() + path = self._path(module) + if path is None: + self.cache[module] = _Env() + return self.cache[module] + self.loading.add(module) + try: + env = self._parse(path.read_text(encoding="utf-8"), path) + except Exception: + env = _Env() + self.loading.discard(module) + self.cache[module] = env + return env + + def parse_file(self, path: Path, source: str | None = None) -> tuple[ast.AST, _Env]: + text = source if source is not None else path.read_text(encoding="utf-8") + tree = ast.parse(text, filename=str(path)) + env = self._module_env(tree) + return tree, env + + def _path(self, module: str) -> Path | None: + parts = module.split(".") + rels = [Path(*parts)] + if parts and parts[0] == "openpilot": + rels.append(Path(*parts[1:])) + for base in [self.root, *self.extra_dirs]: + for rel in rels: + candidate = (base / rel).with_suffix(".py") + if candidate.is_file(): + return candidate + return None + + def _parse(self, text: str, path: Path) -> _Env: + tree = ast.parse(text, filename=str(path)) + return self._module_env(tree) + + def _module_env(self, tree: ast.AST) -> _Env: + env = _Env() + for node in tree.body if isinstance(tree, ast.Module) else []: + if isinstance(node, ast.ImportFrom) and node.module: + imported = self.load(node.module) + for alias in node.names: + if alias.name == "*": + continue + if alias.name in imported: + env[alias.asname or alias.name] = imported[alias.name] + elif isinstance(node, ast.ClassDef): + env[node.name] = self._class_env(node, env) + elif isinstance(node, ast.Assign): + value = _eval(node.value, env) + if _is_missing(value): + continue + for target in node.targets: + if isinstance(target, ast.Name): + env[target.id] = value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None: + value = _eval(node.value, env) + if not _is_missing(value): + env[node.target.id] = value + return env + + def _class_env(self, node: ast.ClassDef, env: _Env) -> dict: + body: dict[str, Any] = {} + for stmt in node.body: + if not isinstance(stmt, ast.Assign): + continue + value = _eval(stmt.value, _Env({**env, **body})) + if _is_missing(value): + continue + for target in stmt.targets: + if isinstance(target, ast.Name): + body[target.id] = value + return body + + +def _param_from_get(node: ast.AST, env: _Env) -> str: + for child in ast.walk(node): + if not isinstance(child, ast.Call): + continue + if _call_name(child.func) not in ("get_bool", "get"): + continue + if not child.args: + continue + value = _eval(child.args[0], env) + if isinstance(value, str) and value: + return value + return "" + + +def _puts(fn: ast.AST) -> list[tuple[ast.AST, ast.AST, str]]: + found = [] + for child in ast.walk(fn): + if not isinstance(child, ast.Call): + continue + name = _call_name(child.func) + if name not in ("put", "put_bool") or not child.args: + continue + found.append((child.args[0], child.args[1] if len(child.args) > 1 else ast.Constant(value=None), name)) + return found + + +def _analyze_callback(fn: ast.AST | None, env: _Env, n_choices: int) -> dict[str, Any]: + info: dict[str, Any] = { + "param": "", + "writer": "", + "confirm": False, + "needs_restart": False, + "reboot_hint": False, + "also_clear": [], + "values": [], + "lock_engaged": False, + "lock_onroad": False, + } + if fn is None: + return info + if _mentions(fn, "engaged"): + info["lock_engaged"] = True + if _mentions(fn, "is_offroad"): + info["lock_onroad"] = True + for child in ast.walk(fn): + if isinstance(child, ast.Call) and _call_name(child.func) == "ConfirmDialog": + info["confirm"] = True + if isinstance(child, ast.Call) and _call_name(child.func) == "_show_reboot_modal": + info["reboot_hint"] = True + if isinstance(child, ast.Call) and _call_name(child.func) == "_handle_experimental_mode_toggle": + info["writer"] = "experimental" + info["confirm"] = True + names = [_call_name(c.func) for c in ast.walk(fn) if isinstance(c, ast.Call)] + if "apply_dm_simulate_looking" in names: + info["writer"] = "dm_sim" + elif "apply_dm_false_alert_ignore" in names: + info["writer"] = "dm_fai" + elif "apply_force_offroad_toggle" in names: + info["writer"] = "force_offroad" + elif "apply_hypermile_toggle" in names: + info["writer"] = "hypermile" + if info["writer"] == "" and _mentions(fn, "ExperimentalModeConfirmed"): + info["writer"] = "experimental" + info["confirm"] = True + + clears: list[str] = [] + for param_node, value_node, op in _puts(fn): + param = _eval(param_node, env) + if not isinstance(param, str) or not param: + continue + if param == "OnroadCycleRequested": + info["needs_restart"] = True + continue + if param == "ExperimentalModeConfirmed": + info["writer"] = "experimental" + info["confirm"] = True + continue + value = _eval(value_node, env) + if op == "put_bool" and value is False: + clears.append(param) + continue + if not info["param"]: + info["param"] = param + info["values"] = _values_from_expr(value_node, env, n_choices) + if op == "put_bool": + info["writer"] = info["writer"] or "bool" + else: + info["writer"] = info["writer"] or "choice" + if info["param"]: + info["also_clear"] = [key for key in clears if key != info["param"]] + return info + + +def _values_from_expr(node: ast.AST, env: _Env, n_choices: int) -> list[Any]: + if isinstance(node, ast.Name) and node.id in ("index", "button_index", "state"): + return list(range(n_choices)) if n_choices else [] + if isinstance(node, ast.Call) and _call_name(node.func) == "int" and node.args: + inner = node.args[0] + if isinstance(inner, ast.Name): + return list(range(n_choices)) if n_choices else [] + if isinstance(inner, ast.Subscript): + return _subscript_list(inner, env) + if isinstance(node, ast.Call) and _call_name(node.func) == "float" and node.args: + if isinstance(node.args[0], ast.Subscript): + return _subscript_list(node.args[0], env) + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + if isinstance(node.left, ast.Name) and isinstance(node.right, ast.Constant) and node.right.value == 1: + return [i + 1 for i in range(n_choices)] if n_choices else [] + if isinstance(node, ast.Subscript): + return _subscript_list(node, env) + return [] + + +def _subscript_list(node: ast.Subscript, env: _Env) -> list[Any]: + values = _eval(node.value, env) + return values if isinstance(values, list) else [] + + +def _callback_fn(name: str, methods: dict[str, ast.AST], local: dict[str, ast.AST]) -> ast.AST | None: + if not name: + return None + if name in local: + return local[name] + return methods.get(name) + + +def _fn_name(node: ast.AST | None) -> str: + if isinstance(node, ast.Attribute): + return node.attr + if isinstance(node, ast.Name): + return node.id + return "" + + +def _page_of(fn: ast.AST | None) -> str: + if fn is None: + return "" + for child in ast.walk(fn): + if not isinstance(child, ast.Assign): + continue + for target in child.targets: + if isinstance(target, ast.Attribute) and target.attr == "_page": + value = child.value + if isinstance(value, ast.Constant) and isinstance(value.value, str): + return value.value + return "" + + +def _self_attr(node: ast.AST) -> str: + if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == "self": + return node.attr + if isinstance(node, ast.Attribute): + return _self_attr(node.value) + return "" + + +class _Builder: + def __init__(self, env: _Env, methods: dict[str, ast.FunctionDef], panel: str): + self.env = env + self.methods = methods + self.panel = panel + self.controls: list[dict[str, Any]] = [] + self.by_attr: dict[str, dict[str, Any]] = {} + self.deferred: list[dict[str, Any]] = [] + self.section = "" + self.pending_personality: dict[str, Any] | None = None + self._defs: list[tuple[str, dict[str, Any]]] | None = None + + def build(self, fn: ast.FunctionDef, panel: str | None = None) -> None: + previous = self.panel + previous_deferred = self.deferred + self.deferred = [] + if panel: + self.panel = panel + self.section = "" + local = {node.name: node for node in fn.body if isinstance(node, ast.FunctionDef)} + for stmt in fn.body: + self._stmt(stmt, local) + if self.pending_personality is not None: + self._add(self.pending_personality) + self.pending_personality = None + for ctrl in self.deferred: + self._add(ctrl) + self.deferred = previous_deferred + self.panel = previous + + def _add(self, ctrl: dict[str, Any]) -> None: + if ctrl.get("_emitted"): + return + ctrl["_emitted"] = True + ctrl["section"] = ctrl["section"] or self.section + self.controls.append(_finish(ctrl)) + + def _emit_node(self, node: ast.AST, local: dict[str, ast.FunctionDef]) -> None: + if isinstance(node, (ast.List, ast.Tuple)): + for elt in node.elts: + self._emit_node(elt, local) + return + if isinstance(node, ast.Call) and _call_name(node.func) == "section_header_item" and node.args: + title = _eval(node.args[0], self.env) + if isinstance(title, str): + self.section = title + return + if isinstance(node, ast.Call): + ctrl = self._from_call(node, local) + if ctrl is not None: + self._add(ctrl) + return + attr = _self_attr(node) + if attr and attr in self.by_attr: + self._add(self.by_attr[attr]) + + def _stmt(self, stmt: ast.AST, local: dict[str, ast.FunctionDef]) -> None: + if isinstance(stmt, ast.Assign): + self._assign(stmt, local) + elif isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call): + self._expr_call(stmt.value, local) + elif isinstance(stmt, ast.For): + self._for(stmt) + elif isinstance(stmt, ast.If): + return + + def _assign(self, stmt: ast.Assign, local: dict[str, ast.FunctionDef]) -> None: + if len(stmt.targets) != 1: + return + target = stmt.targets[0] + attr = _self_attr(target) if isinstance(target, ast.Attribute) else "" + if attr == "_toggle_defs": + self._capture_defs(stmt.value) + return + if isinstance(stmt.value, (ast.List, ast.Tuple)): + self._emit_node(stmt.value, local) + return + if not isinstance(stmt.value, ast.Call): + return + # Scroller([self._toggle, ...]) — display order lives in the list arg. + if stmt.value.args and isinstance(stmt.value.args[0], (ast.List, ast.Tuple)): + if _call_name(stmt.value.func) in ("Scroller",): + self._emit_node(stmt.value.args[0], local) + return + ctrl = self._from_call(stmt.value, local) + if ctrl is None: + return + if attr == "_long_personality_setting": + self.pending_personality = ctrl + return + if attr: + self.by_attr[attr] = ctrl + self.deferred.append(ctrl) + return + self._add(ctrl) + + def _expr_call(self, call: ast.Call, local: dict[str, ast.FunctionDef]) -> None: + name = _call_name(call.func) + if name == "section_header_item" and call.args: + title = _eval(call.args[0], self.env) + if isinstance(title, str): + self.section = title + return + if name == "_build_speed_sign_items": + # Tici Speed Sign Reader submenu: keep its rows on the phone dash NAP panel. + fn = self.methods.get("_build_speed_sign_items") + if fn is not None: + self.build(fn) + return + if name == "_build_radar_items": + fn = self.methods.get("_build_radar_items") + if fn is not None: + self.build(fn, "nap_radar") + return + if name in ("append",) and call.args: + self._emit_node(call.args[0], local) + return + if name == "_add_toggle": + ctrl = self._from_add_toggle(call) + if ctrl is not None: + self._add(ctrl) + return + ctrl = self._from_call(call, local) + if ctrl is not None and name in ("toggle_item", "multiple_button_item", "button_item", "dual_button_item", "text_item"): + self._add(ctrl) + + def _for(self, stmt: ast.For) -> None: + iter_name = "" + if isinstance(stmt.iter, ast.Call): + iter_name = _dotted(stmt.iter.func) + if self._defs is not None and iter_name.endswith("_toggle_defs.items"): + insert_after = "" + for child in ast.walk(stmt): + if isinstance(child, ast.Compare) and child.ops and isinstance(child.ops[0], ast.Eq): + if child.comparators and isinstance(child.comparators[0], ast.Constant): + if isinstance(child.comparators[0].value, str): + insert_after = child.comparators[0].value + for param, ctrl in self._defs: + self._add(ctrl) + if param == insert_after and self.pending_personality is not None: + self._add(self.pending_personality) + self.pending_personality = None + self._defs = None + + def _capture_defs(self, node: ast.AST) -> None: + if not isinstance(node, ast.Dict): + return + defs = [] + for key, value in zip(node.keys, node.values, strict=True): + param = _eval(key, self.env) + if not isinstance(param, str) or not isinstance(value, ast.Tuple) or len(value.elts) < 2: + continue + title = _as_str(_eval(value.elts[0], self.env)) + desc = _as_str(_eval(value.elts[1], self.env)) + needs_restart = False + if len(value.elts) >= 4: + flag = _eval(value.elts[3], self.env) + needs_restart = flag is True + ctrl = _blank(self.panel, "toggle", title) + ctrl["param"] = param + ctrl["description"] = desc + ctrl["needs_restart"] = needs_restart + ctrl["lock_engaged"] = needs_restart + ctrl["writer"] = "bool" + ctrl["lock_param"] = param + "Lock" + if param == "ExperimentalMode": + ctrl["writer"] = "experimental" + ctrl["confirm"] = True + ctrl["description"] = ctrl["description"] or _experimental_blurb(self.methods.get("_update_toggles"), self.env) + if needs_restart and "restart openpilot" not in ctrl["description"]: + ctrl["description"] = (ctrl["description"] + " " if ctrl["description"] else "") + ( + "Changing this setting will restart openpilot if the car is powered on." + ) + defs.append((param, ctrl)) + self._defs = defs + + def _from_add_toggle(self, call: ast.Call) -> dict[str, Any] | None: + if len(call.args) < 2: + return None + param = _eval(call.args[0], self.env) + title = _eval(call.args[1], self.env) + if not isinstance(param, str) or not isinstance(title, str): + return None + desc = _as_str(_eval(call.args[2], self.env)) if len(call.args) > 2 else "" + ctrl = _blank(self.panel, "toggle", title) + ctrl["param"] = param + ctrl["description"] = desc + ctrl["writer"] = "bool" + flags = _lock_flags(_kw(call, "enabled")) + ctrl.update({k: ctrl[k] or flags[k] for k in ("lock_onroad", "lock_engaged", "disabled")}) + reboot = _eval(_kw(call, "needs_reboot"), self.env) + if reboot is True: + ctrl["reboot_hint"] = True + return ctrl + + def _from_call(self, call: ast.Call, local: dict[str, ast.FunctionDef]) -> dict[str, Any] | None: + name = _call_name(call.func) + if name == "toggle_item": + return self._toggle(call, local) + if name == "multiple_button_item": + return self._choice(call, local) + if name == "button_item": + return self._button(call, local) + if name == "dual_button_item": + return None + if name == "text_item": + return self._text(call) + return None + + def _toggle(self, call: ast.Call, local: dict[str, ast.FunctionDef]) -> dict[str, Any] | None: + title = _as_str(_eval(call.args[0], self.env)) if call.args else "" + if not title: + return None + desc_node = _kw(call, "description") + desc = _as_str(_eval(desc_node, self.env)) if desc_node is not None else "" + param = "" + state = _kw(call, "initial_state") + if state is not None: + param = _param_from_get(state, self.env) + cb = _callback_fn(_fn_name(_kw(call, "callback")), self.methods, local) + info = _analyze_callback(cb, self.env, 0) + param = param or info["param"] + if not param: + return None + ctrl = _blank(self.panel, "toggle", title) + ctrl["param"] = param + ctrl["description"] = desc + ctrl["writer"] = info["writer"] or "bool" + ctrl["confirm"] = info["confirm"] + ctrl["needs_restart"] = info["needs_restart"] + ctrl["reboot_hint"] = info["reboot_hint"] + ctrl["also_clear"] = info["also_clear"] + ctrl["lock_engaged"] = info["lock_engaged"] + ctrl["lock_onroad"] = info["lock_onroad"] + flags = _lock_flags(_kw(call, "enabled")) + for key in ("lock_onroad", "lock_engaged", "disabled"): + ctrl[key] = ctrl[key] or flags[key] + if ctrl["needs_restart"]: + ctrl["lock_engaged"] = True + return ctrl + + def _choice(self, call: ast.Call, local: dict[str, ast.FunctionDef]) -> dict[str, Any] | None: + title = _as_str(_eval(call.args[0], self.env)) if call.args else "" + if not title: + return None + desc = _as_str(_eval(call.args[1], self.env)) if len(call.args) > 1 else "" + if not desc: + desc = _as_str(_eval(_kw(call, "description"), self.env)) + buttons = _eval(_kw(call, "buttons"), self.env) + if not isinstance(buttons, list) or not buttons: + buttons = [] + labels = [str(item) for item in buttons] + cb = _callback_fn(_fn_name(_kw(call, "callback")), self.methods, local) + info = _analyze_callback(cb, self.env, len(labels)) + if not info["param"]: + return None + values = info["values"] or list(range(len(labels))) + if labels and values and len(labels) != len(values): + labels = [str(v) for v in values] + if not labels: + labels = [str(v) for v in values] + ctrl = _blank(self.panel, "choice", title) + ctrl["param"] = info["param"] + ctrl["description"] = desc + ctrl["writer"] = "choice" + ctrl["choices"] = labels + ctrl["values"] = values + ctrl["needs_restart"] = info["needs_restart"] + ctrl["reboot_hint"] = info["reboot_hint"] + ctrl["confirm"] = info["confirm"] + ctrl["lock_engaged"] = info["lock_engaged"] or info["needs_restart"] + ctrl["lock_onroad"] = info["lock_onroad"] + return ctrl + + def _button(self, call: ast.Call, local: dict[str, ast.FunctionDef]) -> dict[str, Any] | None: + title = _as_str(_eval(call.args[0], self.env)) if call.args else "" + if not title or title == "Back To": + return None + desc = "" + desc_node = _kw(call, "description") + if desc_node is None and len(call.args) >= 3: + desc_node = call.args[2] + if desc_node is not None: + desc = _as_str(_eval(desc_node, self.env)) + cb_name = _fn_name(_kw(call, "callback")) + if not cb_name and len(call.args) >= 4: + cb_name = _fn_name(call.args[3]) + cb = _callback_fn(cb_name, self.methods, local) + page = _page_of(cb) + if page in _PAGE_PANEL: + ctrl = _blank(self.panel, "link", title) + ctrl["description"] = desc + ctrl["target_panel"] = _PAGE_PANEL[page] + ctrl["writable"] = False + return ctrl + info = _analyze_callback(cb, self.env, 0) + if info["param"] in ("DoReboot", "DoShutdown"): + ctrl = _blank(self.panel, "action", title) + ctrl["param"] = info["param"] + ctrl["description"] = desc + ctrl["writer"] = "action" + ctrl["confirm"] = True + ctrl["lock_engaged"] = True + return ctrl + ctrl = _blank(self.panel, "device_only", title) + ctrl["description"] = desc or "Use this on the comma screen." + ctrl["writable"] = False + return ctrl + + def _text(self, call: ast.Call) -> dict[str, Any] | None: + title = _as_str(_eval(call.args[0], self.env)) if call.args else "" + if not title: + return None + param = "" + if len(call.args) > 1: + param = _param_from_get(call.args[1], self.env) + if not param: + return None + ctrl = _blank(self.panel, "text", title) + ctrl["param"] = param + ctrl["writable"] = False + ctrl["writer"] = "" + return ctrl + + +def _experimental_blurb(fn: ast.AST | None, env: _Env) -> str: + if fn is None: + return "" + for stmt in fn.body: + if isinstance(stmt, ast.Assign): + for target in stmt.targets: + if isinstance(target, ast.Name) and target.id == "e2e_description": + text = _eval(stmt.value, env) + if isinstance(text, str): + return text + return "" + + +def _apply_later_locks(class_node: ast.ClassDef, by_attr: dict[str, dict[str, Any]]) -> None: + for method in class_node.body: + if not isinstance(method, ast.FunctionDef): + continue + names = _offroad_names(method) + for stmt in method.body: + _lock_stmt(stmt, by_attr, names, inside_if=False) + + +def _offroad_names(method: ast.FunctionDef) -> set[str]: + found = set() + for node in ast.walk(method): + if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + if _mentions(node.value, "is_offroad"): + found.add(node.targets[0].id) + return found + + +def _lock_stmt(stmt: ast.AST, by_attr: dict[str, dict], names: set[str], inside_if: bool) -> None: + if isinstance(stmt, ast.If): + for child in stmt.body + stmt.orelse: + _lock_stmt(child, by_attr, names, inside_if=True) + return + if isinstance(stmt, (ast.For, ast.While, ast.With, ast.Try)): + return + call = stmt.value if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call) else None + if call is None or _call_name(call.func) != "set_enabled" or not call.args: + return + attr = _self_attr(call.func) + ctrl = by_attr.get(attr) + if ctrl is None: + return + arg = call.args[0] + if isinstance(arg, ast.Constant) and arg.value is False and not inside_if: + ctrl["disabled"] = True + ctrl["writable"] = False + return + if _mentions(arg, "is_offroad") or (isinstance(arg, ast.Name) and arg.id in names): + ctrl["lock_onroad"] = True + flags = _lock_flags(arg) + ctrl["lock_onroad"] = ctrl["lock_onroad"] or flags["lock_onroad"] + ctrl["lock_engaged"] = ctrl["lock_engaged"] or flags["lock_engaged"] + + +def _release_hidden(class_node: ast.ClassDef, by_attr: dict[str, dict[str, Any]]) -> None: + for method in class_node.body: + if not isinstance(method, ast.FunctionDef): + continue + for node in ast.walk(method): + if not isinstance(node, ast.For): + continue + if not isinstance(node.iter, (ast.Tuple, ast.List)): + continue + attrs = [] + for elt in node.iter.elts: + if isinstance(elt, ast.Attribute) and isinstance(elt.value, ast.Name) and elt.value.id == "self": + attrs.append(elt.attr) + hides = False + for child in ast.walk(node): + if isinstance(child, ast.Call) and _call_name(child.func) == "set_visible": + if child.args and _mentions(child.args[0], "_is_release"): + hides = True + if not hides: + continue + for attr in attrs: + ctrl = by_attr.get(attr) + if ctrl is not None: + ctrl["release_hidden"] = True + ctrl["hide_param"] = "IsReleaseBranch" + + +def _dual_buttons(class_node: ast.ClassDef, env: _Env, methods: dict[str, ast.FunctionDef], panel: str) -> list[dict]: + found = [] + for method in class_node.body: + if not isinstance(method, ast.FunctionDef): + continue + for node in ast.walk(method): + if not isinstance(node, ast.Call) or _call_name(node.func) != "dual_button_item": + continue + if len(node.args) < 2: + continue + pairs = ( + (_as_str(_eval(node.args[0], env)), _fn_name(_kw(node, "left_callback"))), + (_as_str(_eval(node.args[1], env)), _fn_name(_kw(node, "right_callback"))), + ) + for title, cb_name in pairs: + info = _analyze_callback(methods.get(cb_name), env, 0) + if info["param"] not in ("DoReboot", "DoShutdown") or not title: + continue + ctrl = _blank(panel, "action", title) + ctrl["param"] = info["param"] + ctrl["writer"] = "action" + ctrl["confirm"] = True + ctrl["lock_engaged"] = True + ctrl["description"] = "Confirmation required. Unavailable while openpilot is engaged." + found.append(_finish(ctrl)) + return found + + +def _methods(class_node: ast.ClassDef) -> dict[str, ast.FunctionDef]: + return {node.name: node for node in class_node.body if isinstance(node, ast.FunctionDef)} + + +def _entry(methods: dict[str, ast.FunctionDef]) -> ast.FunctionDef | None: + for name in _BUILD_METHODS: + if name in methods: + return methods[name] + return None + + +def _parse_sidebar(tree: ast.AST, env: _Env) -> list[dict[str, str]]: + panels = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call) or _call_name(node.func) != "PanelInfo": + continue + if len(node.args) < 2: + continue + title = _as_str(_eval(node.args[0], env)) + cls = _call_name(node.args[1]) if isinstance(node.args[1], ast.Call) else "" + panel_id = _PANEL_CLASS.get(cls) or re.sub(r"[^a-z0-9]+", "_", title.lower()).strip("_") + if title and panel_id: + panels.append({"id": panel_id, "title": title, "parent": "", "layout": panel_id if panel_id in ("software", "network") else "controls"}) + return panels + + +def _hotspot(root: Path) -> dict[str, Any]: + text = (root / "system" / "ui" / "lib" / "wifi_manager.py").read_text(encoding="utf-8") + ip_match = re.search(r'^TETHERING_IP_ADDRESS\s*=\s*"([^"]+)"', text, re.M) + prefix_match = re.search(r'^TETHERING_PREFIX\s*=\s*(\d+)', text, re.M) + address = ip_match.group(1) if ip_match else "100.99.9.1" + prefix = int(prefix_match.group(1)) if prefix_match else 24 + return {"address": address, "prefix": prefix, "url": f"http://{address}/"} + + +def _param_types(root: Path) -> dict[str, str]: + path = root / "common" / "params_keys.h" + if not path.is_file(): + return {} + types = {} + for name, body in re.findall(r'\{\s*"([A-Za-z0-9_]+)"\s*,\s*\{([^}]*)\}\s*\}', path.read_text(encoding="utf-8")): + if re.search(r"\bFLOAT\b", body): + types[name] = "float" + elif re.search(r"\bBOOL\b", body): + types[name] = "bool" + elif re.search(r"\bINT\b", body): + types[name] = "int" + elif re.search(r"\b(STRING|JSON)\b", body): + types[name] = "str" + else: + types[name] = "bytes" + return types + + +def _panel_title_from_doc(path: Path) -> str: + try: + tree = ast.parse(path.read_text(encoding="utf-8")) + except Exception: + return "" + doc = ast.get_docstring(tree) or "" + match = re.search(r"submenu:\s*(.+?)\s+controls", doc) + if match: + return match.group(1).strip() + return "" + + +def discover_manifest(root: Path | None = None, sources: dict[str, str] | None = None, + extra_module_dirs: list[Path] | None = None) -> dict[str, Any]: + """Build panels + controls from the on-device settings sources.""" + root = repo_root() if root is None else root + sources = sources or {} + modules = _Modules(root, list(extra_module_dirs or [])) + settings_path = root / "selfdrive" / "ui" / "layouts" / "settings" / "settings.py" + settings_tree, settings_env = modules.parse_file(settings_path, sources.get("settings.py")) + panels = _parse_sidebar(settings_tree, settings_env) + known = {panel["id"] for panel in panels} + + controls: list[dict[str, Any]] = [] + sub_titles: dict[str, str] = {} + settings_dir = settings_path.parent + for filename, panel in _FILE_PANEL.items(): + path = settings_dir / filename + if not path.is_file() and filename not in sources: + continue + tree, env = modules.parse_file(path, sources.get(filename)) + if filename == "firehose.py": + desc = env.get("DESCRIPTION") if isinstance(env.get("DESCRIPTION"), str) else "" + extra = env.get("INSTRUCTIONS") if isinstance(env.get("INSTRUCTIONS"), str) else "" + title = env.get("TITLE") if isinstance(env.get("TITLE"), str) else "Firehose Mode" + if desc: + ctrl = _blank("firehose", "info", title) + ctrl["description"] = desc + ("\n\n" + extra if extra else "") + ctrl["writable"] = False + controls.append(_finish(ctrl)) + continue + for node in tree.body: + if not isinstance(node, ast.ClassDef): + continue + methods = _methods(node) + entry = _entry(methods) + if entry is None: + continue + builder = _Builder(env, methods, panel) + builder.build(entry) + _apply_later_locks(node, builder.by_attr) + _release_hidden(node, builder.by_attr) + controls.extend(builder.controls) + if filename == "device.py": + controls.extend(_dual_buttons(node, env, methods, panel)) + if panel not in known: + sub_titles.setdefault(panel, _panel_title_from_doc(path)) + + for ctrl in controls: + if ctrl["kind"] == "link" and ctrl["target_panel"]: + sub_titles[ctrl["target_panel"]] = ctrl["title"] + + children = [ + ("nap_mannerisms", sub_titles.get("nap_mannerisms") or "Driving Mannerisms"), + ("nap_map", sub_titles.get("nap_map") or "Map Speed Limit"), + ("nap_radar", sub_titles.get("nap_radar") or "Radar"), + ("nap_hidden", "Hidden"), + ] + # Hidden stays reachable: on the comma it is a triple-tap, not a sidebar tab. + existing = {panel["id"] for panel in panels} + nap_at = next((i for i, panel in enumerate(panels) if panel["id"] == "nap"), len(panels) - 1) + insert_at = nap_at + 1 + for panel_id, title in children: + if panel_id in existing: + continue + if not any(ctrl["panel"] == panel_id for ctrl in controls): + continue + panels.insert(insert_at, {"id": panel_id, "title": title, "parent": "nap", "layout": "controls"}) + insert_at += 1 + + for ctrl in controls: + ctrl.pop("_emitted", None) + + hotspot = _hotspot(root) + network = _blank("network", "info", "Comma hotspot") + subnet = hotspot["address"].rsplit(".", 1)[0] + network["description"] = " ".join([ + "Enable tethering on the comma (Settings, Network, Enable Tethering).", + f"The hotspot hands out {subnet}.0/{hotspot['prefix']} with the comma at {hotspot['address']}.", + f"Open {hotspot['url']}.", + "Joining a home Wi-Fi network is unchanged; this page is also served there.", + "A phone or the Tesla browser that uses the hotspot for internet is using the comma's LTE data.", + ]) + network["writable"] = False + controls.insert(0, _finish(network)) + + # Drop device-only script buttons that are not settings. Keep reboot/power. + # Speed-limit and every other real toggle stays, including ones we did not name here. + return { + "hotspot": hotspot, + "panels": panels, + "controls": controls, + "param_types": _param_types(root), + } diff --git a/selfdrive/nap_dash/force_offroad_api.py b/selfdrive/nap_dash/force_offroad_api.py new file mode 100644 index 00000000000000..9b9c37d2deb9db --- /dev/null +++ b/selfdrive/nap_dash/force_offroad_api.py @@ -0,0 +1,51 @@ +"""Web mirror of the on-road Force Offroad Yes/No (selfdrive/ui/onroad/force_offroad_confirm.py). + +Params only, through the same system/hardware/nap_force_offroad helpers the +native dialog uses. Yes writes NAPForceOffroadConfirmed=True (card then runs +the stock-CC handoff); No drops all Force Offroad intent. No cereal: "started" +is the IsOnroad param hardwared writes from deviceState.started. +""" +from __future__ import annotations + +from openpilot.system.hardware.nap_force_offroad import ( + CONFIRM_NO, + CONFIRM_PROMPT, + CONFIRM_YES, + CONFIRMED_PARAM, + PARAM, + cancel_force_offroad, + confirm_force_offroad, + needs_driver_confirm, +) + + +class AckError(ValueError): + pass + + +def _flag(params, key: str) -> bool: + try: + return bool(params.get_bool(key)) + except Exception: + return False + + +def read_ack(params) -> dict: + """Same condition as maybe_show_force_offroad_confirm().""" + pending = needs_driver_confirm(_flag(params, PARAM), _flag(params, CONFIRMED_PARAM), _flag(params, "IsOnroad")) + return {"pending": bool(pending), "prompt": CONFIRM_PROMPT, "yes": CONFIRM_YES, "no": CONFIRM_NO} + + +def handle_ack(payload: dict, params) -> dict: + answer = str(payload.get("answer") or "").strip().lower() + if answer not in ("yes", "no"): + raise AckError("answer must be yes or no") + if not read_ack(params)["pending"]: + raise AckError("Nothing to confirm: Force Offroad is not waiting for an answer.") + if answer == "yes": + if payload.get("confirm") is not True: + raise AckError("confirmation required") + confirm_force_offroad(params) + else: + cancel_force_offroad(params) + return read_ack(params) diff --git a/selfdrive/nap_dash/server.py b/selfdrive/nap_dash/server.py new file mode 100644 index 00000000000000..d8757117fd94bb --- /dev/null +++ b/selfdrive/nap_dash/server.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +"""Comma web UI. Params and software only. + +HTTP on port 80 when the process can bind it, otherwise 7070. +This process does not open cereal sockets and does not run a live +telemetry loop. It cannot engage openpilot. + +A crash, bind failure, or preimport error must not block engage +(the manager process is optional). +""" +from __future__ import annotations + +import json +import os +import threading +import time +import traceback +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlparse + +try: + from openpilot.common.swaglog import cloudlog +except Exception: # pragma: no cover - unit tests without zmq + class _PrintLog: + def info(self, msg): + print(msg) + + def warning(self, msg): + print(msg) + + def exception(self, msg): + print(msg) + cloudlog = _PrintLog() + +from openpilot.selfdrive.nap_dash.force_offroad_api import AckError, handle_ack, read_ack +from openpilot.selfdrive.nap_dash.settings import SettingError +from openpilot.selfdrive.nap_dash.system_api import ( + SoftwareError, + handle_software, + read_software, +) +from openpilot.selfdrive.nap_dash.ui_api import ( + get_manifest, + network_status, + public_manifest, + read_settings, + write_setting, +) + +HOST = os.environ.get("NAP_DASH_HOST", "0.0.0.0") +DASHBOARD_PATH = Path(__file__).resolve().parent / "dashboard.html" + +PARAMS = None +PM_LOCK = threading.Lock() +STOP = threading.Event() + + +def listen_ports(): + """Port 80 is the MCU URL. 7070 is the fallback if 80 cannot be bound.""" + raw = os.environ.get("NAP_DASH_PORT", "").strip() + if raw: + return [int(raw)] + return [80, 7070] + + +def _params(): + global PARAMS + if PARAMS is None: + from openpilot.common.params import Params + PARAMS = Params() + return PARAMS + + +def locked_settings(): + with PM_LOCK: + return read_settings(_params()) + + +def locked_write(name, value, confirm=False): + with PM_LOCK: + return write_setting(_params(), name, value, confirm=confirm) + + +def bookmark_status(params): + """{"recording": bool, "left": seconds}. feedbackd owns NAPBookmarkRecording.""" + try: + left = params.get("NAPBookmarkRecording") + except Exception: + left = None + if left is None: + return {"recording": False, "left": 0} + return {"recording": True, "left": int(left)} + + +def bookmark_tap(params): + """Same as the comma sidebar Bookmark tap: feedbackd bookmarks + starts/stops the voice note. + Only onroad (feedbackd/micd/loggerd do not run parked).""" + if not params.get_bool("IsOnroad"): + # Nothing records parked; a queued request would fire at the next drive start. + out = bookmark_status(params) + out["ok"] = False + out["reason"] = "offroad" + return out + params.put("NAPBookmarkRequest", int(time.monotonic())) + out = bookmark_status(params) + out["ok"] = True + return out + + +def state_snapshot(): + """Minimal JSON so an old page does not 500. No live car data.""" + return { + "lite": True, + "ts": 0, + "car": {}, + "drive": {}, + "plan": {}, + "lead1": {}, + "settings": {}, + "health": {}, + "engagement": {}, + "bms": {}, + } + + +def dashboard_html() -> bytes: + try: + return DASHBOARD_PATH.read_bytes() + except OSError: + return b"

openpilot

dashboard.html missing

" + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): + cloudlog.info("nap_dash " + (fmt % args)) + + def send_json(self, obj, code=200): + body = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Cache-Control", "no-cache, no-store") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _send_html(self): + body = dashboard_html() + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Cache-Control", "no-cache, no-store") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + path = urlparse(self.path).path + if path in ("/", "/index.html", "/phone", "/phone/"): + return self._send_html() + if path == "/api/manifest": + try: + return self.send_json(public_manifest()) + except Exception as exc: + return self.send_json({"error": str(exc)}, 500) + if path == "/api/state": + return self.send_json(state_snapshot()) + if path == "/api/settings": + try: + snap = locked_settings() + snap["catalog"] = public_manifest()["controls"] + return self.send_json(snap) + except Exception as exc: + return self.send_json({"error": str(exc)}, 500) + if path == "/api/network": + try: + return self.send_json(network_status()) + except Exception as exc: + return self.send_json({"error": str(exc)}, 500) + if path == "/api/force_offroad": + try: + return self.send_json(read_ack(_params())) + except Exception as exc: + return self.send_json({"error": str(exc)}, 500) + if path == "/api/bookmark": + try: + return self.send_json(bookmark_status(_params())) + except Exception as exc: + return self.send_json({"error": str(exc)}, 500) + if path == "/api/software": + try: + return self.send_json(read_software(_params())) + except Exception as exc: + return self.send_json({"error": str(exc)}, 500) + return self.send_json({"error": "not found"}, 404) + + def do_POST(self): + path = urlparse(self.path).path + try: + n = int(self.headers.get("Content-Length", "0")) + if n < 0 or n > 16 * 1024: + return self.send_json({"error": "payload too large"}, 413) + payload = json.loads(self.rfile.read(n).decode() or "{}") + if path == "/api/software": + return self.send_json(handle_software(payload, _params())) + if path == "/api/force_offroad": + return self.send_json(handle_ack(payload, _params())) + if path == "/api/bookmark": + return self.send_json(bookmark_tap(_params())) + if path != "/api/set": + return self.send_json({"error": "not found"}, 404) + action = str(payload.get("action") or "").strip().lower() + if action in {"engage", "disengage"}: + return self.send_json({"error": "engaging openpilot from the web is not allowed"}, 400) + name = str(payload.get("param") or payload.get("name") or "") + snap = locked_write(name, payload.get("value"), bool(payload.get("confirm"))) + # Lets the page raise the steering Yes/No right after the tap, not on the next poll. + snap["force_offroad_ack"] = read_ack(_params()) + return self.send_json(snap) + except AckError as exc: + return self.send_json({"error": str(exc)}, 400) + except SoftwareError as exc: + return self.send_json({"error": str(exc)}, 400) + except SettingError as exc: + return self.send_json({"error": str(exc)}, 400) + except Exception as exc: + return self.send_json({"error": str(exc)}, 400) + + +class DashHTTPServer(ThreadingHTTPServer): + allow_reuse_address = True + daemon_threads = True + + +def bind_http_server(host=HOST, port=None): + """Bind port 80, then 7070. Returns None if every port fails. + + An explicit port (tests, NAP_DASH_PORT) tries only that port. + """ + ports = [int(port)] if port is not None else listen_ports() + for one in ports: + try: + server = DashHTTPServer((host, one), Handler) + cloudlog.info(f"nap_dash listening on {host}:{one} (Params + software, no cereal)") + return server + except OSError as exc: + cloudlog.warning(f"nap_dash failed to bind {host}:{one}: {exc}") + return None + + +def idle_until_stop(stop_event=None, sleeper=time.sleep): + """Keep the managed process alive so optional Dash cannot block engage.""" + stop_event = STOP if stop_event is None else stop_event + while not stop_event.is_set(): + sleeper(1.0) + + +def main(): + try: + hot = get_manifest().get("hotspot") or {} + cloudlog.info("nap_dash url " + str(hot.get("url") or "http://100.99.9.1/")) + except Exception: + cloudlog.warning("nap_dash manifest unavailable at start") + server = bind_http_server(HOST) + if server is None: + idle_until_stop() + return + try: + server.serve_forever() + except KeyboardInterrupt: + pass + except Exception: + traceback.print_exc() + idle_until_stop() + finally: + STOP.set() + try: + server.server_close() + except Exception: + pass + + +if __name__ == "__main__": + main() diff --git a/selfdrive/nap_dash/settings.py b/selfdrive/nap_dash/settings.py new file mode 100644 index 00000000000000..c74b4963bb0c1b --- /dev/null +++ b/selfdrive/nap_dash/settings.py @@ -0,0 +1,13 @@ +"""Settings API for the comma web UI. + +Controls are discovered from the on-device settings sources. This module +does not keep a second list of toggles. +""" +from openpilot.selfdrive.nap_dash.ui_api import ( + SettingError, + read_settings, + setting_catalog, + write_setting, +) + +__all__ = ["SettingError", "read_settings", "setting_catalog", "write_setting"] diff --git a/selfdrive/nap_dash/system_api.py b/selfdrive/nap_dash/system_api.py new file mode 100644 index 00000000000000..136dae9d851e00 --- /dev/null +++ b/selfdrive/nap_dash/system_api.py @@ -0,0 +1,358 @@ +"""Read/write comma Software params for MCU/phone. No SSH. No engage.""" +from __future__ import annotations + +import datetime +import re +import subprocess + +BRANCH_OK = re.compile(r"^[A-Za-z0-9._/-]+$") +BLOCKED_ACTIONS = { + "engage", + "disengage", + "uninstall", + "reset_calibration", + "reset_lateral", + "reset_longitudinal", + "force_onroad", +} +SOFTWARE_ACTIONS = {"set_branch", "fetch", "download", "install"} +UPDATED_PATTERNS = ( + "openpilot.system.updated.updated", + "system.updated.updated", +) + + +class SoftwareError(ValueError): + pass + + +def _as_str(value) -> str: + if value is None: + return "" + if isinstance(value, bytes): + return value.decode("utf-8", "replace") + return str(value) + + +def _as_bool(value) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, (int, float)) and value in (0, 1): + return bool(value) + if isinstance(value, str): + folded = value.strip().lower() + if folded in ("1", "true", "yes", "on"): + return True + if folded in ("0", "false", "no", "off", ""): + return False + raise SoftwareError(f"invalid bool: {value!r}") + + +def sanitize_branch(raw: str | None) -> str: + branch = (raw or "").strip() + if not branch or len(branch) > 80: + raise SoftwareError("invalid branch") + if ".." in branch or branch.startswith(("/", "-")): + raise SoftwareError("invalid branch") + # Exact action names only: a branch name cannot engage anything, so + # names like cursor/speedsignd-engaged-read-spacing-3353 are fine. + key = branch.lower().replace("-", "_") + if key in BLOCKED_ACTIONS: + raise SoftwareError("action not allowed") + if not BRANCH_OK.match(branch): + raise SoftwareError("invalid branch") + return branch + + +UPDATED_PGREP = "system.updated.updated" + +# Same wording as the comma Software panel (selfdrive/ui/layouts/settings/software.py). +STATE_TEXT = { + "checking...": "checking…", + "downloading...": "downloading…", + "finalizing update...": "finalizing update…", +} + + +PAUSED_TEXT = "Updates are paused (DisableUpdates is on), so Check and Download are blocked." +STOPPED_TEXT = ( + "The updater is not running. It starts when the car turns off; " + + "if updates were just re-enabled, reboot the comma or cycle the car to start it." +) + + +def _as_int(value) -> int: + if value is None: + return 0 + if isinstance(value, bool): + return int(value) + if isinstance(value, (int, float)): + return int(value) + try: + return int(_as_str(value).strip() or 0) + except ValueError: + return 0 + + +def _as_time(value) -> datetime.datetime | None: + """LastUpdateTime is a TIME param (naive UTC datetime); older params give ISO text.""" + if value is None or value == "" or value == b"": + return None + if isinstance(value, datetime.datetime): + when = value + else: + text = _as_str(value).strip().replace("Z", "") + try: + when = datetime.datetime.fromisoformat(text) + except ValueError: + return None + if when.tzinfo is not None: + when = when.astimezone(datetime.UTC).replace(tzinfo=None) + return when + + +def time_ago(when: datetime.datetime | None, now: datetime.datetime | None = None) -> str: + """Same buckets as time_ago() in the comma Software panel.""" + if when is None: + return "never" + now = now or datetime.datetime.now(datetime.UTC).replace(tzinfo=None) + diff = int((now - when).total_seconds()) + if diff < 0 or now.year < 2024: + return when.strftime("%a %b %d %Y") + if diff < 60: + return "now" + if diff < 3600: + n = diff // 60 + return f"{n} minute{'s' if n != 1 else ''} ago" + if diff < 86400: + n = diff // 3600 + return f"{n} hour{'s' if n != 1 else ''} ago" + if diff < 604800: + n = diff // 86400 + return f"{n} day{'s' if n != 1 else ''} ago" + return when.strftime("%a %b %d %Y") + + +def updated_running() -> bool: + """True when the updater process is alive. It only runs while the car is off.""" + try: + out = subprocess.run( + ["pgrep", "-f", UPDATED_PGREP], + check=False, + timeout=2, + capture_output=True, + ) + return out.returncode == 0 + except Exception: + return False + + +def _flag(params, key: str) -> bool: + try: + return bool(params.get_bool(key)) + except Exception: + return False + + +def _get(params, key: str): + try: + return params.get(key) + except Exception: + return None + + +def install_label(snap: dict) -> str: + """'Install & reboot with ' from UpdaterNewDescription.""" + desc = snap.get("new_description") or "" + # get_description(): " / / / "; branches can contain "/". + parts = [part.strip() for part in desc.split(" / ") if part.strip()] + target = " / ".join(parts[:2]) if parts else (snap.get("target_branch") or "") + return f"Install & reboot with {target}" if target else "Install & reboot" + + +# Native Software panel (selfdrive/ui/layouts/settings/software.py): the INSTALL +# button is shown and enabled whenever ui_state.is_offroad() and UpdateAvailable. +# It has no engaged or updater-busy check. While onroad it is hidden and the panel +# shows this line instead. is_offroad() is "not deviceState.started", which +# hardwared publishes as IsOnroad. +ONROAD_TEXT = "Updates are only downloaded while the car is off." + + +def install_blocked(snap: dict) -> str: + """Same rule as the native INSTALL button: available only while offroad.""" + if snap.get("onroad"): + return ONROAD_TEXT + return "" + + +# Where the update flow is: Check -> Download -> Install & reboot. +STEP_LABEL = { + "check": "Check", + "checking": "Checking…", + "download": "Download", + "downloading": "Downloading…", +} + + +def next_step(snap: dict) -> str: + """Which step of the update flow the Software tab is on.""" + state = snap["updater_state"] + if state == "checking...": + return "checking" + if state != "idle": + return "downloading" + if snap["update_available"]: + return "install" + if snap["update_failed_count"] > 0: + return "check" + if snap["fetch_available"]: + return "download" + return "check" + + +def software_status(snap: dict) -> dict: + """Status line plus Check/Download availability, mirroring the comma Software panel.""" + state = snap["updater_state"] + busy = state != "idle" + blocked = "" + if snap["disable_updates"]: + blocked = PAUSED_TEXT + elif snap["onroad"]: + blocked = ONROAD_TEXT + elif not snap["updater_running"]: + blocked = STOPPED_TEXT + + if busy: + text = STATE_TEXT.get(state, state) + elif snap["update_available"]: + text = "update ready, reboot to install" + if snap["new_description"]: + text += f" ({snap['new_description']})" + elif snap["update_failed_count"] > 0: + text = "failed to check for update" + elif snap["fetch_available"]: + text = "update available, tap Download" + else: + text = "up to date" + if not busy: + text += ", last checked " + snap["last_checked"] + action = "download" if snap["fetch_available"] and not snap["update_available"] else "check" + step = next_step(snap) + return { + "status_text": text, + "busy": busy, + "blocked_reason": blocked, + "next_action": action, + "can_check": not busy and not blocked, + # Download is offered only after a check found something new to fetch. + "can_download": not busy and not blocked and snap["fetch_available"] and not snap["update_available"], + "can_install": bool(snap["update_available"]) and not install_blocked(snap), + "install_blocked_reason": install_blocked(snap), + "install_label": install_label(snap), + "step": step, + "step_label": STEP_LABEL.get(step) or install_label(snap), + } + + +def read_software(params, running=None) -> dict: + branches_raw = _as_str(_get(params, "UpdaterAvailableBranches")) + branches = [part for part in branches_raw.split(",") if part] + offline = _flag(params, "DisableUpdates") + last = _as_time(_get(params, "LastUpdateTime")) + alive = updated_running() if running is None else bool(running() if callable(running) else running) + snap = { + "git_branch": _as_str(_get(params, "GitBranch")), + "git_commit": _as_str(_get(params, "GitCommit")), + "version": _as_str(_get(params, "Version")), + "target_branch": _as_str(_get(params, "UpdaterTargetBranch")), + "available_branches": branches, + "updater_state": _as_str(_get(params, "UpdaterState")).strip() or "idle", + "fetch_available": _flag(params, "UpdaterFetchAvailable"), + "update_available": _flag(params, "UpdateAvailable"), + "update_failed_count": _as_int(_get(params, "UpdateFailedCount")), + "last_update_time": last.replace(microsecond=0).isoformat() + "Z" if last else "", + "last_checked": time_ago(last), + "last_update_exception": _as_str(_get(params, "LastUpdateException")).strip(), + "current_description": _as_str(_get(params, "UpdaterCurrentDescription")).strip(), + "new_description": _as_str(_get(params, "UpdaterNewDescription")).strip(), + "onroad": _flag(params, "IsOnroad"), + "engaged": _flag(params, "IsEngaged"), + "updater_running": alive, + "disable_updates": offline, + "offline": offline, + } + snap.update(software_status(snap)) + return snap + + +def ping_updated(signal: str = "USR1") -> None: + """Same wake-up the comma Software UI uses. Fail-soft if updated is idle.""" + for pattern in UPDATED_PATTERNS: + try: + subprocess.run( + ["pkill", f"-SIG{signal}", "-f", pattern], + check=False, + timeout=2, + ) + except Exception: + pass + + +def _put(params, key: str, value: str) -> None: + try: + params.put(key, value, block=True) + except TypeError: + params.put(key, value) + + +def _put_bool(params, key: str, value: bool) -> None: + try: + try: + # block so the snapshot we return right after already shows the new value + params.put_bool(key, value, block=True) + except TypeError: + params.put_bool(key, value) + except Exception: + _put(params, key, "1" if value else "0") + + +def _as_confirm(value) -> bool: + try: + return _as_bool(value) if value is not None else False + except SoftwareError: + return False + + +def handle_software(payload: dict, params, pinger=ping_updated, running=None) -> dict: + action = str(payload.get("action") or "").strip().lower().replace("-", "_") + if not action: + raise SoftwareError("missing action") + if action in BLOCKED_ACTIONS or "engage" in action: + raise SoftwareError("action not allowed") + if action not in SOFTWARE_ACTIONS: + raise SoftwareError(f"software action not allowed: {action}") + if action == "set_branch": + branch = sanitize_branch(str(payload.get("branch") or payload.get("name") or "")) + _put(params, "UpdaterTargetBranch", branch) + pinger("USR1") + elif action == "install": + # Native Software panel INSTALL: put DoReboot; the finalized update swaps in on boot. + snap = read_software(params, running=running) + if not snap["update_available"]: + raise SoftwareError("No downloaded update is ready to install.") + reason = install_blocked(snap) + if reason: + raise SoftwareError(reason) + if not _as_confirm(payload.get("confirm")): + raise SoftwareError("confirmation required to install and reboot") + _put_bool(params, "DoReboot", True) + snap["rebooting"] = True + return snap + else: + # Same signals as the comma Software panel: SIGUSR1 checks, SIGHUP downloads. + if _flag(params, "DisableUpdates"): + raise SoftwareError("Updates are paused (DisableUpdates is on), so Check and Download are blocked.") + if _flag(params, "IsOnroad"): + raise SoftwareError(ONROAD_TEXT) + pinger("HUP" if action == "download" else "USR1") + return read_software(params, running=running) diff --git a/selfdrive/test/profiling/__init__.py b/selfdrive/nap_dash/tests/__init__.py similarity index 100% rename from selfdrive/test/profiling/__init__.py rename to selfdrive/nap_dash/tests/__init__.py diff --git a/selfdrive/nap_dash/tests/fixtures/nap_pr296_panel.txt b/selfdrive/nap_dash/tests/fixtures/nap_pr296_panel.txt new file mode 100644 index 00000000000000..df3b16eeb61b6e --- /dev/null +++ b/selfdrive/nap_dash/tests/fixtures/nap_pr296_panel.txt @@ -0,0 +1,860 @@ +import os +import subprocess +import pyray as rl +from openpilot.common.params import Params +from openpilot.common.basedir import BASEDIR +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.keyboard import Keyboard +from openpilot.system.ui.widgets.list_view import ( + toggle_item, multiple_button_item, button_item, text_item, + ITEM_PADDING, +) +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.button import Button +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.script_runner import ScriptRunner +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets.html_render import HtmlRenderer, ElementType +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + BACKUP_EPAS_INSTRUCTIONS, BRAKE_FACTOR_PRESETS, + CALIBRATE_PEDAL_INSTRUCTIONS, + DOWNLOAD_US_MAPS_INSTRUCTIONS, + FLASH_EPAS_INSTRUCTIONS, + INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS, PEDAL_CAN_BUS_VALUES, + HIGH_LOW_BEAM_DESCRIPTION, HIGH_LOW_BEAM_LABELS, HIGH_LOW_BEAM_VALUES, + MAP_SPEED_ACCEL_DEFAULT, + NAP_DM_FALSE_ALERT_IGNORE, + NAP_DM_SIMULATE_LOOKING, + NAP_CONE_LINE_HOLD, + NAP_CONE_LINE_LOG, + NAP_OBSTACLE_CHIME, + NAP_OBSTACLE_LOG, + NAP_DRIVER_LAT_HANDOFF, + NAP_LOW_VIS_BACKOFF, + NAP_FORCE_OFFROAD, + NAP_HYPERMILE, + NAP_HYPERMILE_HILL_CLIMB, + NAP_HYPERMILE_STEP_DOWN, + NAP_ONE_PEDAL_LONG, + NAP_SPEED_SIGN_LOG, + RADAR_OFFSET_MAX, RADAR_OFFSET_MIN, + REFRESH_MAPS_INSTRUCTIONS, + RESTORE_EPAS_INSTRUCTIONS, + SPEED_SIGN_LOG_DESCRIPTION, + WIPER_SPEED_DESCRIPTION, WIPER_SPEED_LABELS, WIPER_SPEED_VALUES, + WIPER_SENSITIVITY_DEFAULT, WIPER_SENSITIVITY_DESCRIPTION, + WIPER_SENSITIVITY_LABELS, WIPER_SENSITIVITY_VALUES, + acknowledgments_html, coerce_wiper_speed_param, find_preset_index, + wiper_speed_button_index, +) +from openpilot.selfdrive.ui.layouts.settings.driving_mannerisms import DrivingMannerismsLayout +from openpilot.selfdrive.ui.layouts.settings.map_speed import MapSpeedLimitLayout +from openpilot.selfdrive.speedsignd.install import weights_status_summary +from openpilot.selfdrive.car.tesla.preap_body_controls import register_nap_body_params +from opendbc.car.tesla.preap.nap_params import NAPParamKeys, DEFAULTS + +register_nap_body_params() +from openpilot.selfdrive.ui.radar.radar_view import RadarMonitorDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from scripts.nap.script_lifecycle import script_reboots_on_exit + + + +class SectionHeader(Widget): + """Lightweight section label to visually separate groups of settings.""" + + HEADER_HEIGHT = 70 + + def __init__(self, title: str): + super().__init__() + self._title = title + self._font = gui_app.font(FontWeight.BOLD) + self.set_rect(rl.Rectangle(0, 0, 0, self.HEADER_HEIGHT)) + + def set_parent_rect(self, parent_rect: rl.Rectangle): + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + + def _render(self, rect): + text_size = measure_text_cached(self._font, self._title, 40) + text_y = self._rect.y + (self._rect.height - text_size.y) / 2 + rl.draw_text_ex( + self._font, self._title, + rl.Vector2(self._rect.x + ITEM_PADDING, text_y), + 40, 0, rl.Color(180, 180, 180, 255), + ) + + +class CreditsBlock(Widget): + """Static block of HTML-rendered credits text with auto-sized height.""" + + def __init__(self, html: str): + super().__init__() + self._html = HtmlRenderer( + text=html, + text_size={ElementType.P: 40}, + text_color=rl.Color(140, 140, 140, 255), + ) + self.set_rect(rl.Rectangle(0, 0, 0, 200)) # placeholder height + + def set_parent_rect(self, parent_rect: rl.Rectangle): + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + content_w = int(self._rect.width - ITEM_PADDING * 2) + self._rect.height = self._html.get_total_height(content_w) + ITEM_PADDING + + def _render(self, rect): + content_w = int(self._rect.width - ITEM_PADDING * 2) + h = self._html.get_total_height(content_w) + html_rect = rl.Rectangle( + self._rect.x + ITEM_PADDING, self._rect.y, + content_w, h, + ) + self._html.set_rect(html_rect) + self._html.render(html_rect) + + +def section_header_item(title: str) -> SectionHeader: + return SectionHeader(title) + + +class NAPLayout(Widget): + def __init__(self): + super().__init__() + self._params = Params() + self._page = "main" + self._build_items() + self._scroller = Scroller(self._main_items, line_separator=True, spacing=0) + self._radar_scroller = Scroller(self._radar_items, line_separator=True, spacing=0) + self._radar_back_btn = Button("Back", click_callback=self._close_radar) + self._radar_back_btn.set_rect(rl.Rectangle(0, 0, 220, 90)) + + def _build_items(self): + """Build all list items organized into sections.""" + self._main_items = [] + self._radar_items = [] + self._toggle_map = {} # param_key -> ListItem (for refresh) + + # ── Section 0: Speed Sign (top — flip Logger while testing) ── + self._main_items.append(section_header_item("Speed Sign")) + + self._add_toggle( + NAP_SPEED_SIGN_LOG, + "Speed Sign Logger", + SPEED_SIGN_LOG_DESCRIPTION, + ) + + self._weights_status = text_item( + "Speed Sign Weights", + weights_status_summary, + description="YOLO ONNX at /data/media/0/nap/speed_sign.onnx. " + "Missing → onroad SIGN shows NO WT and will not read roadside signs. " + "Installed → blank plate until a confirmed mph.", + ) + self._main_items.append(self._weights_status) + + self._install_weights_btn = button_item( + "Install weights", + "Start", + description=INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS.split("\n", 1)[0], + callback=self._on_install_speed_sign_weights, + ) + self._install_weights_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._install_weights_btn) + + # ── Section 1: Longitudinal Control ── + # Force Offroad / Simulate Look / False Alert Ignore live in the NAP triple-tap popup. + self._main_items.append(section_header_item("Longitudinal Control")) + + self._add_toggle( + NAPParamKeys.PEDAL_ENABLED, + "Pedal Interceptor", + "Enable Comma Pedal hardware for direct throttle control. Requires reboot.", + enabled=ui_state.is_offroad, + needs_reboot=True, + ) + + self._driving_mannerisms_page = DrivingMannerismsLayout( + on_back=self._close_driving_mannerisms, + ) + self._driving_mannerisms_btn = button_item( + "Driving Mannerisms", + "Open", + description="Accel feel, follow, soft lat, one-pedal, and Hypermile.", + callback=self._open_driving_mannerisms, + ) + self._main_items.append(self._driving_mannerisms_btn) + + self._map_speed_page = MapSpeedLimitLayout( + on_back=self._close_map_speed, + on_download=self._on_download_us_maps, + on_refresh=self._on_refresh_maps, + ) + self._page = "main" + self._map_speed_btn = button_item( + "Map Speed Limit", + "Open", + description="OSM posted limits — mode, offset, lookahead, and maps.", + callback=self._open_map_speed, + ) + self._main_items.append(self._map_speed_btn) + + # ── Section 2: Pedal Hardware ── + self._main_items.append(section_header_item("Pedal Hardware")) + + + pedal_bus = self._params.get(NAPParamKeys.PEDAL_CAN_BUS, return_default=True) + self._pedal_bus_buttons = multiple_button_item( + "Pedal CAN Bus", + "Select which CAN bus the Comma Pedal is connected to. Requires reboot.", + buttons=["Bus 0", "Bus 2"], + button_width=150, + selected_index=0 if pedal_bus == 0 else 1, + callback=self._on_pedal_can_bus, + ) + self._pedal_bus_buttons.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._pedal_bus_buttons) + + self._pedal_calib_status = text_item( + "Pedal Calibration", + lambda: "Calibrated" if self._params.get_bool(NAPParamKeys.PEDAL_CALIB_DONE) else "Not Calibrated", + description="Shows whether the pedal interceptor has been calibrated.", + ) + self._main_items.append(self._pedal_calib_status) + + self._calibrate_pedal_btn = button_item( + "Calibrate Pedal", + "Start", + description="Run the pedal calibration routine. Vehicle must be stationary with ignition on.", + callback=self._on_calibrate_pedal, + ) + self._calibrate_pedal_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._calibrate_pedal_btn) + + # ── Section 3: Radar (submenu) ── + self._main_items.append(section_header_item("Radar")) + self._radar_settings_btn = button_item( + "Radar Settings", + "Open", + description="Donor VIN, position, offset, test, and calibration.", + callback=self._open_radar, + ) + self._main_items.append(self._radar_settings_btn) + self._build_radar_items() + + # ── Section 4: iBooster / Braking (not yet implemented — grayed out) ── + self._main_items.append(section_header_item("iBooster / Braking")) + + self._add_toggle( + NAPParamKeys.IBOOSTER_ENABLED, + "iBooster Enabled", + "Enable the iBooster brake-by-wire system for electronic braking. (Not yet implemented)", + enabled=False, + ) + + brake_factor = self._params.get(NAPParamKeys.BRAKE_FACTOR, return_default=True) + self._brake_factor_buttons = multiple_button_item( + "Brake Factor", + "Multiplier for brake force. Higher values brake more aggressively. (Not yet implemented)", + buttons=["0.5x", "1.0x", "1.5x", "2.0x"], + button_width=130, + selected_index=find_preset_index(BRAKE_FACTOR_PRESETS, brake_factor), + callback=self._on_brake_factor, + ) + self._brake_factor_buttons.action_item.set_enabled(False) + self._main_items.append(self._brake_factor_buttons) + + # ── Section 5: Wipers & lights (car test) ── + self._main_items.append(section_header_item("Wipers & Lights (test)")) + + wiper_setting = coerce_wiper_speed_param(self._params) + self._wiper_buttons = multiple_button_item( + "Wiper Control", + WIPER_SPEED_DESCRIPTION, + buttons=WIPER_SPEED_LABELS, + button_width=160, + selected_index=wiper_speed_button_index(wiper_setting), + callback=self._on_wiper_speed, + ) + self._main_items.append(self._wiper_buttons) + + raw_sens = self._params.get(NAPParamKeys.WIPER_SENSITIVITY, return_default=True) + try: + sens_setting = WIPER_SENSITIVITY_DEFAULT if raw_sens is None else int(raw_sens) + except (TypeError, ValueError): + sens_setting = WIPER_SENSITIVITY_DEFAULT + self._wiper_sens_buttons = multiple_button_item( + "Wiper Sensitivity", + WIPER_SENSITIVITY_DESCRIPTION, + buttons=WIPER_SENSITIVITY_LABELS, + button_width=110, + selected_index=max(0, min(len(WIPER_SENSITIVITY_VALUES) - 1, sens_setting)), + callback=self._on_wiper_sensitivity, + ) + self._main_items.append(self._wiper_sens_buttons) + + beam_setting = int(self._params.get(NAPParamKeys.HIGH_LOW_BEAM, return_default=True) or 0) + self._beam_buttons = multiple_button_item( + "High / Low Beam", + HIGH_LOW_BEAM_DESCRIPTION, + buttons=HIGH_LOW_BEAM_LABELS, + button_width=130, + selected_index=max(0, min(len(HIGH_LOW_BEAM_VALUES) - 1, beam_setting)), + callback=self._on_high_low_beam, + ) + self._main_items.append(self._beam_buttons) + + # ── Section 6: Advanced ── + self._main_items.append(section_header_item("Advanced")) + + # Force Pre-AP is always on for now — grayed out in the ON position + self._params.put_bool(NAPParamKeys.FORCE_PRE_AP, True) + self._add_toggle( + NAPParamKeys.FORCE_PRE_AP, + "Force Pre-AP Mode", + "Force the system to treat this vehicle as a Pre-Autopilot Tesla.", + enabled=False, + ) + + # ── Section 7: Actions ── + self._main_items.append(section_header_item("Actions")) + + self._backup_epas_btn = button_item( + "Backup EPAS", + "Extract", + description="Extract and save stock EPAS firmware image without flashing.", + callback=self._on_backup_epas, + ) + self._backup_epas_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._backup_epas_btn) + + self._flash_epas_btn = button_item( + "Flash EPAS", + "Flash", + description="Flash the EPAS (Electric Power Assisted Steering) firmware.", + callback=self._on_flash_epas, + ) + self._flash_epas_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._flash_epas_btn) + + self._restore_epas_btn = button_item( + "Restore EPAS", + "Restore", + description="Restore stock EPAS firmware image.", + callback=self._on_restore_epas, + ) + self._restore_epas_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._restore_epas_btn) + + self._emergency_disable_btn = button_item( + "Emergency Disable", + "Disable", + description="Immediately disable pedal interceptor and clear calibration. Restart required.", + callback=self._on_emergency_disable, + ) + self._main_items.append(self._emergency_disable_btn) + + self._reset_defaults_btn = button_item( + "Reset to Defaults", + "Reset", + description="Reset all NAP settings to factory defaults. This cannot be undone.", + callback=self._on_reset_defaults, + ) + self._reset_defaults_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._reset_defaults_btn) + + # ── Acknowledgments ── + self._main_items.append(section_header_item("Acknowledgments")) + self._main_items.append(CreditsBlock(acknowledgments_html())) + + def _build_radar_items(self): + self._radar_items.append(section_header_item("Radar")) + + self._add_toggle( + NAPParamKeys.RADAR_ENABLED, + "Radar Enabled", + "Enable the stock Bosch radar for lead car detection. When on, " + "path-synced radar is preferred for long lead if the track is on " + "the model path and radar is healthy. Off or unhealthy falls back " + "to stock fusion. Requires reboot.", + enabled=ui_state.is_offroad, + needs_reboot=True, + dest=self._radar_items, + ) + + self._add_toggle( + NAPParamKeys.RADAR_IGNORE_HW_FAIL, + "Ignore radar hardware fail", + "Lets you engage when Bosch raises HWFail even though tracks are still live.", + dest=self._radar_items, + ) + + def on_radar_hud(state): + self._params.put_bool(NAPParamKeys.RADAR_HUD, state) + ui_state.radar_hud = state + + hud_item = toggle_item( + "Radar HUD", + description="Show live tracks, lamps, and alert bits over the driving view. Works while driving.", + initial_state=self._params.get_bool(NAPParamKeys.RADAR_HUD), + callback=on_radar_hud, + ) + self._toggle_map[NAPParamKeys.RADAR_HUD] = hud_item + self._radar_items.append(hud_item) + + self._radar_offset_keyboard = Keyboard(max_text_size=10) + self._radar_offset_btn = button_item( + "Radar Lateral Offset", + self._get_radar_offset_text, + description=( + "Lateral offset in meters added to radar yRel. Negative shifts leads toward the left of current radar " + + "reading; positive shifts right. Example: -0.27 for the 3D-printed factory-location mount." + ), + callback=self._on_radar_offset_click, + ) + self._radar_items.append(self._radar_offset_btn) + + self._radar_vin_keyboard = Keyboard(max_text_size=17) + self._radar_vin_btn = button_item( + "Donor Radar VIN", + self._get_radar_vin_text, + description=( + "VIN already programmed in a salvage radar. Leave empty to send this car. " + + "A 17-character VIN makes panda impersonate the donor (Tinkla 0.6.6)." + ), + callback=self._on_radar_vin_click, + ) + self._radar_items.append(self._radar_vin_btn) + + self._read_vin_btn = button_item( + "Read VIN", + self._get_read_vin_text, + description=( + "Read the VIN stored in the radar (F190). Does not write or flash. " + + "Car must be on and not engaged. Power-cycle after it fills." + ), + callback=self._on_read_vin, + ) + self._radar_items.append(self._read_vin_btn) + + radar_position = int(self._params.get(NAPParamKeys.RADAR_POSITION, return_default=True) or 0) + self._radar_position_buttons = multiple_button_item( + "Donor Radar Position", + "Always sent when radar is on, including empty VIN. 0 pre-facelift S, 1 post-facelift S, 2 Model X.", + buttons=["0", "1", "2"], + button_width=130, + selected_index=max(0, min(2, radar_position)), + callback=self._on_radar_position, + ) + self._radar_items.append(self._radar_position_buttons) + + radar_epas = int(self._params.get(NAPParamKeys.RADAR_EPAS_TYPE, return_default=True) or 0) + self._radar_epas_buttons = multiple_button_item( + "Donor EPAS Type", + "Must match the donor car rack: 0 Bosch L538, 1 L405, 2 Mando FGR64, 3 VGR66, 4 VGR66 Gen3.", + buttons=["0", "1", "2", "3", "4"], + button_width=100, + selected_index=max(0, min(4, radar_epas)), + callback=self._on_radar_epas, + ) + self._radar_items.append(self._radar_epas_buttons) + + self._live_radar_btn = button_item( + "Live Radar", + "Open", + description="Live tracks, ECU lamps, and alert bits. Stays in this session; works while driving.", + callback=self._on_live_radar, + ) + self._radar_items.append(self._live_radar_btn) + + def _add_toggle(self, param_key: str, title: str, description: str, + enabled: bool | None = None, needs_reboot: bool = False, + dest: list | None = None): + """Helper to add a toggle item and register it for state refresh.""" + kwargs = {} + if enabled is not None: + kwargs['enabled'] = enabled + + def on_toggle(state, k=param_key): + self._params.put_bool(k, state) + if needs_reboot: + self._show_reboot_modal() + + item = toggle_item( + title, + description=description, + initial_state=self._params.get_bool(param_key), + callback=on_toggle, + **kwargs, + ) + self._toggle_map[param_key] = item + (dest if dest is not None else self._main_items).append(item) + + # ── Multiple-button callbacks ── + + def _open_driving_mannerisms(self): + self._page = "driving_mannerisms" + self._driving_mannerisms_page.show_event() + + def _close_driving_mannerisms(self): + self._page = "main" + + def _open_map_speed(self): + self._page = "map_speed" + self._map_speed_page.show_event() + + def _close_map_speed(self): + self._page = "main" + + def _on_pedal_can_bus(self, index: int): + self._params.put(NAPParamKeys.PEDAL_CAN_BUS, PEDAL_CAN_BUS_VALUES[index]) + self._show_reboot_modal() + + def _on_brake_factor(self, index: int): + self._params.put(NAPParamKeys.BRAKE_FACTOR, BRAKE_FACTOR_PRESETS[index]) + + def _on_wiper_speed(self, index: int): + self._params.put(NAPParamKeys.WIPER_SPEED, WIPER_SPEED_VALUES[index]) + + def _on_wiper_sensitivity(self, index: int): + self._params.put(NAPParamKeys.WIPER_SENSITIVITY, WIPER_SENSITIVITY_VALUES[index]) + + def _on_high_low_beam(self, index: int): + self._params.put(NAPParamKeys.HIGH_LOW_BEAM, HIGH_LOW_BEAM_VALUES[index]) + + def _get_radar_offset(self) -> float: + raw = self._params.get(NAPParamKeys.RADAR_OFFSET, return_default=True) + try: + return float(raw) if raw is not None else 0.0 + except (TypeError, ValueError): + return 0.0 + + def _get_radar_offset_text(self) -> str: + return f"{self._get_radar_offset():+.2f}m" + + def _get_radar_vin_text(self) -> str: + raw = self._params.get(NAPParamKeys.RADAR_DONOR_VIN, return_default=True) or "" + if isinstance(raw, bytes): + raw = raw.decode("ascii", errors="ignore") + vin = "".join(ch for ch in str(raw).upper() if ch.isalnum()) + return vin if len(vin) == 17 else "Not set" + + def _get_read_vin_text(self) -> str: + if self._params.get_bool(NAPParamKeys.RADAR_READ_VIN): + return "Reading..." + raw = self._params.get(NAPParamKeys.RADAR_VIN_READ_STATUS, return_default=True) or "" + if isinstance(raw, bytes): + raw = raw.decode("ascii", errors="ignore") + status = str(raw).strip() + if status.startswith("saved "): + return "Cycle car" + if status: + return status[:18] + return "Read" + + def _open_radar(self): + self._page = "radar" + self._radar_scroller.show_event() + + def _close_radar(self): + self._page = "main" + self._scroller.show_event() + + def _on_read_vin(self): + if ui_state.engaged: + dlg = ConfirmDialog( + "

Disengage first


VIN read is blocked while openpilot is engaged.

", + "OK", cancel_text="Close", rich=True, + ) + gui_app.push_widget(dlg) + return + + if not self._params.get_bool(NAPParamKeys.RADAR_ENABLED): + dlg = ConfirmDialog( + "

Enable radar first


Read VIN needs radar on. Toggle it and reboot, then try again.

", + "OK", cancel_text="Close", rich=True, + ) + gui_app.push_widget(dlg) + return + + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + self._params.put_bool(NAPParamKeys.RADAR_READ_VIN, True) + + content = ( + "

Read VIN


" + + "

Reads the VIN stored in the radar. Does not write or flash. " + + "Leave the car on and do not engage. Power-cycle after it fills.

" + ) + dlg = ConfirmDialog(content, "Read", rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + def _on_radar_vin_click(self): + current = self._get_radar_vin_text() + self._radar_vin_keyboard.reset(min_text_size=0) + self._radar_vin_keyboard.set_title("Donor Radar VIN") + self._radar_vin_keyboard.set_text("" if current == "Not set" else current) + self._radar_vin_keyboard.set_callback(self._on_radar_vin_submit) + gui_app.push_widget(self._radar_vin_keyboard) + + def _on_radar_vin_submit(self, result: DialogResult): + if result != DialogResult.CONFIRM: + return + text = "".join(ch for ch in (self._radar_vin_keyboard.text or "").upper() if ch.isalnum()) + try: + self._params.put(NAPParamKeys.RADAR_DONOR_VIN, text if len(text) == 17 else "") + except Exception: + pass + + def _on_radar_position(self, index: int): + try: + self._params.put(NAPParamKeys.RADAR_POSITION, int(index)) + except Exception: + pass + + def _on_radar_epas(self, index: int): + try: + self._params.put(NAPParamKeys.RADAR_EPAS_TYPE, int(index)) + except Exception: + pass + + def _on_radar_offset_click(self): + self._radar_offset_keyboard.reset(min_text_size=1) + self._radar_offset_keyboard.set_title("Radar Lateral Offset (m)") + self._radar_offset_keyboard.set_text(f"{self._get_radar_offset():.2f}") + self._radar_offset_keyboard.set_callback(self._on_radar_offset_submit) + gui_app.push_widget(self._radar_offset_keyboard) + + def _on_radar_offset_submit(self, result: DialogResult): + if result != DialogResult.CONFIRM: + return + try: + text = (self._radar_offset_keyboard.text or "").strip() + value = float(text) + except (TypeError, ValueError, AttributeError): + return # silently reject blank/non-numeric input; label stays at prior value + value = max(RADAR_OFFSET_MIN, min(RADAR_OFFSET_MAX, value)) + # Pass raw float (matches the BRAKE_FACTOR put pattern). Params + # previously got str(value) which threw inside Params for FLOAT-typed + # keys; exception propagated out of the Keyboard Enter callback, + # crashing the UI and leaving the Params value unset (label stuck at + # the 0.0 default). Keep the try/except so no future value ever kills + # the UI. + try: + self._params.put(NAPParamKeys.RADAR_OFFSET, value) + except Exception: + pass + + # ── Script runner ── + + def _show_script_runner(self, title: str, instructions: str, script_module: str): + """Map sqlite jobs overlay in-process (one screen). Hardware scripts spawn run_script.py.""" + if not script_reboots_on_exit(script_module): + gui_app.push_widget(ScriptRunner( + title=title, + instructions=instructions, + script_module=script_module, + on_close=lambda: gui_app.pop_widget(), + cwd=BASEDIR, + )) + return + + script_path = os.path.join(BASEDIR, "scripts", "nap", "run_script.py") + log_path = "/tmp/nap_script_runner.log" + + with open(log_path, "w") as log_file: + subprocess.Popen( + ["python", script_path, title, script_module, instructions], + cwd=BASEDIR, + start_new_session=True, + stdout=log_file, + stderr=log_file, + ) + + # ── Action button callbacks ── + + def _on_install_speed_sign_weights(self): + self._show_script_runner( + title="Install weights", + instructions=INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS, + script_module="scripts.nap.install_speed_sign_weights", + ) + + def _on_download_us_maps(self): + self._show_script_runner( + title="Download US Maps", + instructions=DOWNLOAD_US_MAPS_INSTRUCTIONS, + script_module="scripts.nap.fetch_osm_maps", + ) + + def _on_refresh_maps(self): + self._show_script_runner( + title="Refresh maps", + instructions=REFRESH_MAPS_INSTRUCTIONS, + script_module="scripts.nap.refresh_osm_maps", + ) + + def _on_calibrate_pedal(self): + self._show_script_runner( + title="Pedal Calibration", + instructions=CALIBRATE_PEDAL_INSTRUCTIONS, + script_module="scripts.nap.calibrate_pedal", + ) + + def _on_live_radar(self): + gui_app.push_widget(RadarMonitorDialog()) + + def _on_flash_epas(self): + self._show_script_runner( + title="Flash EPAS Firmware", + instructions=FLASH_EPAS_INSTRUCTIONS, + script_module="scripts.nap.flash_epas", + ) + + def _on_backup_epas(self): + self._show_script_runner( + title="Backup EPAS Firmware", + instructions=BACKUP_EPAS_INSTRUCTIONS, + script_module="scripts.nap.extract_epas", + ) + + def _on_restore_epas(self): + self._show_script_runner( + title="Restore EPAS Firmware", + instructions=RESTORE_EPAS_INSTRUCTIONS, + script_module="scripts.nap.restore_epas", + ) + + def _show_reboot_modal(self): + """Show a modal prompting the user to reboot for the change to take effect.""" + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + self._params.put_bool("DoReboot", True) + + content = "

Reboot Required


This change requires a reboot to take effect.

" + dlg = ConfirmDialog(content, "Reboot", cancel_text="Ignore", rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + def _on_emergency_disable(self): + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + self._params.put_bool(NAPParamKeys.PEDAL_ENABLED, False) + self._params.put_bool(NAPParamKeys.PEDAL_CALIB_DONE, False) + self._refresh_toggles() + + content = ( + "

Emergency Disable


" + + "

This will disable the pedal interceptor and clear calibration. " + + "You will need to restart the device for changes to take effect.

" + ) + dlg = ConfirmDialog(content, "Disable", rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + def _on_reset_defaults(self): + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + self._reset_all_to_defaults() + self._refresh_toggles() + + content = ( + "

Reset to Defaults


" + + "

This will reset all NAP settings to their factory default values. " + + "This action cannot be undone.

" + ) + dlg = ConfirmDialog(content, "Reset All", rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + def _reset_all_to_defaults(self): + """Write default value for each NAP param.""" + for key, default in DEFAULTS.items(): + if isinstance(default, bool): + self._params.put_bool(key, default) + elif isinstance(default, (int, float)): + self._params.put(key, default) + self._params.put("NAPMapSpeedMode", 0) + self._params.put("NAPMapSpeedOffsetMph", 0) + self._params.put("NAPMapSpeedLookahead", 2) + self._params.put("NAPMapSpeedAccel", MAP_SPEED_ACCEL_DEFAULT) + self._params.remove("NAPMapSpeedDbPath") + self._params.put_bool(NAP_SPEED_SIGN_LOG, False) + self._params.put_bool(NAP_DRIVER_LAT_HANDOFF, True) + self._params.put_bool(NAP_LOW_VIS_BACKOFF, True) + self._params.put_bool(NAP_CONE_LINE_HOLD, True) + self._params.put_bool(NAP_CONE_LINE_LOG, True) + self._params.put_bool(NAP_OBSTACLE_CHIME, True) + self._params.put_bool(NAP_OBSTACLE_LOG, True) + self._params.put_bool(NAP_DM_SIMULATE_LOOKING, True) + self._params.put_bool(NAP_DM_FALSE_ALERT_IGNORE, False) + self._params.put_bool(NAP_HYPERMILE, False) + self._params.put_bool(NAP_HYPERMILE_STEP_DOWN, False) + self._params.put_bool(NAP_HYPERMILE_HILL_CLIMB, True) + self._params.put_bool(NAP_ONE_PEDAL_LONG, False) + self._params.remove("NAPHypermileSaved") + self._params.put_bool(NAP_FORCE_OFFROAD, False) + self._params.put_bool("NAPForceOffroadConfirmed", False) + self._params.put_bool("NAPForceOffroadHandoffReady", False) + self._page = "main" + # Force Pre-AP is locked on in the panel but DEFAULTS keeps it off + # for non-UI consumers. Re-apply the lock after the wholesale loop + # so reset doesn't silently flip the invariant. + self._params.put_bool(NAPParamKeys.FORCE_PRE_AP, True) + + # ── Render / lifecycle ── + + def _render(self, rect): + if self._page == "map_speed": + self._map_speed_page.render(rect) + elif self._page == "driving_mannerisms": + self._driving_mannerisms_page.render(rect) + elif self._page == "radar": + self._radar_back_btn.set_position(rect.x, rect.y + 10) + self._radar_back_btn.render() + content = rl.Rectangle( + rect.x, rect.y + self._radar_back_btn.rect.height + 20, + rect.width, rect.height - self._radar_back_btn.rect.height - 20, + ) + self._radar_scroller.render(content) + else: + self._scroller.render(rect) + + def show_event(self): + self._page = "main" + self._scroller.show_event() + self._refresh_toggles() + + def _refresh_toggles(self): + """Sync all toggle states from params (handles external changes).""" + for key, item in self._toggle_map.items(): + item.action_item.set_state(self._params.get_bool(key)) + + # Refresh multiple-button selections + pedal_bus = self._params.get(NAPParamKeys.PEDAL_CAN_BUS, return_default=True) + self._pedal_bus_buttons.action_item.set_selected_button( + 0 if pedal_bus == 0 else 1) + + brake_factor = self._params.get(NAPParamKeys.BRAKE_FACTOR, return_default=True) + self._brake_factor_buttons.action_item.set_selected_button( + find_preset_index(BRAKE_FACTOR_PRESETS, brake_factor)) + + wiper_setting = coerce_wiper_speed_param(self._params) + self._wiper_buttons.action_item.set_selected_button( + wiper_speed_button_index(wiper_setting)) + raw_sens = self._params.get(NAPParamKeys.WIPER_SENSITIVITY, return_default=True) + try: + sens_setting = WIPER_SENSITIVITY_DEFAULT if raw_sens is None else int(raw_sens) + except (TypeError, ValueError): + sens_setting = WIPER_SENSITIVITY_DEFAULT + self._wiper_sens_buttons.action_item.set_selected_button( + max(0, min(len(WIPER_SENSITIVITY_VALUES) - 1, sens_setting))) + beam_setting = int(self._params.get(NAPParamKeys.HIGH_LOW_BEAM, return_default=True) or 0) + self._beam_buttons.action_item.set_selected_button( + max(0, min(len(HIGH_LOW_BEAM_VALUES) - 1, beam_setting))) + + self._driving_mannerisms_page.refresh() + self._map_speed_page.refresh() + self._install_weights_btn.action_item.set_enabled(ui_state.is_offroad) + radar_position = int(self._params.get(NAPParamKeys.RADAR_POSITION, return_default=True) or 0) + self._radar_position_buttons.action_item.set_selected_button(max(0, min(2, radar_position))) + radar_epas = int(self._params.get(NAPParamKeys.RADAR_EPAS_TYPE, return_default=True) or 0) + self._radar_epas_buttons.action_item.set_selected_button(max(0, min(4, radar_epas))) diff --git a/selfdrive/nap_dash/tests/test_discover.py b/selfdrive/nap_dash/tests/test_discover.py new file mode 100644 index 00000000000000..3aa39953c39c65 --- /dev/null +++ b/selfdrive/nap_dash/tests/test_discover.py @@ -0,0 +1,199 @@ +"""Toggle auto-discovery reads the device UI source. It does not import it.""" +from __future__ import annotations + +from pathlib import Path + +from openpilot.selfdrive.nap_dash.discover import discover_manifest + +ROOT = Path(__file__).resolve().parents[3] +UI = ROOT / "selfdrive" / "ui" / "layouts" / "settings" + + +def _params(manifest): + return [ctrl["param"] for ctrl in manifest["controls"] if ctrl.get("param")] + + +def _by_param(manifest, param): + for ctrl in manifest["controls"]: + if ctrl.get("param") == param: + return ctrl + raise AssertionError(param) + + +def test_stock_toggles_come_from_device_source(): + manifest = discover_manifest(ROOT) + enable = _by_param(manifest, "OpenpilotEnabledToggle") + assert enable["title"] == "Enable openpilot" + assert enable["panel"] == "toggles" + assert enable["lock_engaged"] is True + assert enable["needs_restart"] is True + assert "attention is required" in enable["description"] + + experimental = _by_param(manifest, "ExperimentalMode") + assert experimental["confirm"] is True + assert experimental["writer"] == "experimental" + assert "End-to-End" in experimental["description"] or "end-to-end" in experimental["description"].lower() or "chill mode" in experimental["description"] + + personality = _by_param(manifest, "LongitudinalPersonality") + assert personality["kind"] == "choice" + assert personality["choices"] == ["Aggressive", "Standard", "Relaxed"] + assert personality["values"] == [0, 1, 2] + + # Inserted after Disengage, matching the device list. + titles = [ctrl["title"] for ctrl in manifest["controls"] if ctrl["panel"] == "toggles"] + assert titles.index("Disengage on Accelerator Pedal") + 1 == titles.index("Driving Personality") + + +def test_mannerisms_and_map_speed_are_discovered_not_hand_listed(): + manifest = discover_manifest(ROOT) + handoff = _by_param(manifest, "NAPDriverLatHandoff") + assert handoff["panel"] == "nap_mannerisms" + assert handoff["title"] == "Soft Lateral Handoff" + hyper = _by_param(manifest, "NAPHypermile") + assert hyper["writer"] == "hypermile" + mode = _by_param(manifest, "NAPMapSpeedMode") + assert mode["panel"] == "nap_map" + assert mode["choices"] == ["Off", "Display", "Cap", "Follow"] + assert mode["values"] == [0, 1, 2, 3] + sign = _by_param(manifest, "NAPSpeedSignLog") + assert sign["writer"] == "bool" + assert sign["panel"] == "nap" + panels = [panel["title"] for panel in manifest["panels"]] + assert panels[:5] == ["Device", "Network", "Toggles", "Software", "NAP"] + assert "Driving Mannerisms" in panels + assert "Map Speed Limit" in panels + + +def test_new_toggle_in_device_ui_source_shows_up_in_manifest(): + """Adding a toggle to the device UI source is enough. No web-side list edit.""" + mannerisms = (UI / "driving_mannerisms.py").read_text(encoding="utf-8") + needle = " def _on_hypermile" + assert needle in mannerisms + snippet = """\ + self._probe = toggle_item( + "Discovery Probe", + description="Added in the device UI source.", + initial_state=self._params.get_bool("NAPDiscoveryProbe"), + callback=self._on_probe, + ) + self._all_items.append(self._probe) + +""" + patched = mannerisms.replace(needle, snippet + needle, 1) + toggles = (UI / "toggles.py").read_text(encoding="utf-8") + toggles_needle = ' "IsMetric": (' + assert toggles_needle in toggles + toggles_snippet = """\ + "NAPWebDiscoveryProbe": ( + lambda: tr("Web Discovery Probe"), + "Shown when the device UI defines it.", + "metric.png", + False, + ), +""" + toggles_patched = toggles.replace(toggles_needle, toggles_snippet + toggles_needle, 1) + manifest = discover_manifest(ROOT, sources={ + "driving_mannerisms.py": patched, + "toggles.py": toggles_patched, + }) + probe = _by_param(manifest, "NAPDiscoveryProbe") + assert probe["title"] == "Discovery Probe" + assert probe["panel"] == "nap_mannerisms" + assert probe["description"] == "Added in the device UI source." + stock = _by_param(manifest, "NAPWebDiscoveryProbe") + assert stock["title"] == "Web Discovery Probe" + assert stock["panel"] == "toggles" + assert stock["description"] == "Shown when the device UI defines it." + + live = discover_manifest(ROOT) + assert "NAPDiscoveryProbe" not in _params(live) + assert "NAPWebDiscoveryProbe" not in _params(live) + + +def test_nap_param_keys_resolve_when_opendbc_source_is_present(tmp_path): + package = tmp_path / "opendbc" / "car" / "tesla" / "preap" + package.mkdir(parents=True) + (package / "nap_params.py").write_text( + '''\ +class NAPParamKeys: + PEDAL_ENABLED = "NAPPedalEnabled" + ADAPTIVE_ACCEL = "NAPAdaptiveAccel" + FOLLOW_DISTANCE_CITY = "NAPFollowDistanceCity" + FOLLOW_DISTANCE_HWY = "NAPFollowDistanceHwy" + PEDAL_CAN_BUS = "NAPPedalCanBus" + PEDAL_CALIB_DONE = "NAPPedalCalibDone" + IBOOSTER_ENABLED = "NAPiBoosterEnabled" + BRAKE_FACTOR = "NAPBrakeFactor" + FORCE_PRE_AP = "NAPForcePreAP" + RADAR_ENABLED = "NAPRadarEnabled" + RADAR_HUD = "NAPRadarHud" + RADAR_IGNORE_HW_FAIL = "NAPRadarIgnoreHwFail" + RADAR_EPAS_TYPE = "NAPRadarEpasType" + RADAR_POSITION = "NAPRadarPosition" +''', + encoding="utf-8", + ) + manifest = discover_manifest(ROOT, extra_module_dirs=[tmp_path]) + pedal = _by_param(manifest, "NAPPedalEnabled") + assert pedal["title"] == "Pedal Interceptor" + assert pedal["lock_onroad"] is True + assert pedal["reboot_hint"] is True + city = _by_param(manifest, "NAPFollowDistanceCity") + assert city["values"] == [1, 2, 3, 4, 5, 6, 7] + + +def test_discovery_does_not_import_ui_or_cereal(): + src = (ROOT / "selfdrive" / "nap_dash" / "discover.py").read_text(encoding="utf-8") + assert "import cereal" not in src + assert "SubMaster" not in src + assert "import messaging" not in src + assert "import openpilot.selfdrive.ui" not in src + assert "import openpilot.selfdrive.mapd" not in src + assert "import openpilot.selfdrive.speedsignd" not in src + + +def test_unmerged_speed_sign_panel_puts_logger_first(tmp_path): + """PR #296 (not merged) puts Speed Sign Logger first in Settings, NAP. + + Discovery reads that panel as text. This test does not edit nap.py. + """ + package = tmp_path / "opendbc" / "car" / "tesla" / "preap" + package.mkdir(parents=True) + (package / "nap_params.py").write_text( + '''\ +class NAPParamKeys: + PEDAL_ENABLED = "NAPPedalEnabled" +''', + encoding="utf-8", + ) + text = (Path(__file__).parent / "fixtures" / "nap_pr296_panel.txt").read_text(encoding="utf-8") + manifest = discover_manifest(ROOT, sources={"nap.py": text}, extra_module_dirs=[tmp_path]) + nap = [ctrl for ctrl in manifest["controls"] if ctrl.get("panel") == "nap"] + assert nap[0]["title"] == "Speed Sign Logger" + assert nap[0]["param"] == "NAPSpeedSignLog" + assert nap[0]["section"] == "Speed Sign" + assert nap[0]["writer"] == "bool" + titles = [ctrl["title"] for ctrl in nap] + assert titles.index("Speed Sign Logger") < titles.index("Pedal Interceptor") + assert titles.index("Speed Sign Logger") < titles.index("Driving Mannerisms") + + +def test_hidden_and_developer_rules(): + manifest = discover_manifest(ROOT) + sim = _by_param(manifest, "NAPDmSimulateLooking") + assert sim["writer"] == "dm_sim" + assert sim["panel"] == "nap_hidden" + fai = _by_param(manifest, "NAPDmFalseAlertIgnore") + assert fai["writer"] == "dm_fai" + offroad = _by_param(manifest, "NAPForceOffroad") + assert offroad["writer"] == "force_offroad" + assert offroad["lock_onroad"] is False + adb = _by_param(manifest, "AdbEnabled") + assert adb["lock_onroad"] is True + alpha = _by_param(manifest, "AlphaLongitudinalEnabled") + assert alpha["confirm"] is True + assert alpha["needs_restart"] is True + assert alpha["release_hidden"] is True + joy = _by_param(manifest, "JoystickDebugMode") + assert "LongitudinalManeuverMode" in joy["also_clear"] + assert joy["lock_onroad"] is True diff --git a/selfdrive/nap_dash/tests/test_force_offroad_ack.py b/selfdrive/nap_dash/tests/test_force_offroad_ack.py new file mode 100644 index 00000000000000..6c4d1d6dbc8033 --- /dev/null +++ b/selfdrive/nap_dash/tests/test_force_offroad_ack.py @@ -0,0 +1,121 @@ +"""Web Force Offroad Yes/No mirrors selfdrive/ui/onroad/force_offroad_confirm.py.""" +from __future__ import annotations + +import json +from http.client import HTTPConnection +from pathlib import Path +from threading import Thread + +import pytest + +from openpilot.selfdrive.nap_dash.force_offroad_api import AckError, handle_ack, read_ack +from openpilot.system.hardware.nap_force_offroad import CONFIRM_PROMPT + + +class FakeParams: + def __init__(self, **bools): + self.bools = dict(bools) + self.writes: list[tuple[str, bool]] = [] + + def get_bool(self, key): + return bool(self.bools.get(key, False)) + + def put_bool(self, key, value): + self.writes.append((key, bool(value))) + self.bools[key] = bool(value) + + +def waiting(): + return FakeParams(NAPForceOffroad=True, NAPForceOffroadConfirmed=False, IsOnroad=True) + + +def test_prompt_shows_on_native_condition(): + assert read_ack(waiting()) == {"pending": True, "prompt": CONFIRM_PROMPT, "yes": "Yes", "no": "No"} + assert read_ack(FakeParams(NAPForceOffroad=True, IsOnroad=False))["pending"] is False # parked + assert read_ack(FakeParams(NAPForceOffroad=True, NAPForceOffroadConfirmed=True, IsOnroad=True))["pending"] is False + assert read_ack(FakeParams(IsOnroad=True))["pending"] is False + + +def test_yes_writes_confirmed_only_and_needs_confirm(): + p = waiting() + with pytest.raises(AckError, match="confirmation"): + handle_ack({"answer": "yes"}, p) + assert p.writes == [] + snap = handle_ack({"answer": "yes", "confirm": True}, p) + assert p.writes == [("NAPForceOffroadConfirmed", True)] + assert snap["pending"] is False + + +def test_no_writes_native_resets(): + p = waiting() + handle_ack({"answer": "no"}, p) + assert p.writes == [("NAPForceOffroad", False), ("NAPForceOffroadConfirmed", False), ("NAPForceOffroadHandoffReady", False)] + assert read_ack(p)["pending"] is False + + +def test_refuses_when_not_pending_or_bad_answer(): + for p in (FakeParams(), FakeParams(NAPForceOffroad=True, NAPForceOffroadConfirmed=True, IsOnroad=True)): + for payload in ({"answer": "yes", "confirm": True}, {"answer": "no"}): + with pytest.raises(AckError, match="Nothing to confirm"): + handle_ack(payload, p) + assert p.writes == [] + for payload in ({"answer": "engage"}, {}): + with pytest.raises(AckError): + handle_ack(payload, waiting()) + + +def test_page_has_prompt_and_polls(): + html = (Path(__file__).resolve().parents[1] / "dashboard.html").read_text() + assert 'id="foack"' in html and "setInterval(foPoll, 1500)" in html + assert '{answer: "yes", confirm: true}' in html + + +def test_http_round_trip_and_engage_still_blocked(monkeypatch): + from openpilot.selfdrive.nap_dash import server as srv + p = waiting() + monkeypatch.setattr(srv, "_params", lambda: p) + httpd = srv.ThreadingHTTPServer(("127.0.0.1", 0), srv.Handler) + Thread(target=httpd.serve_forever, daemon=True).start() + host, port = httpd.server_address + + def call(method, path, body=None): + conn = HTTPConnection(host, port, timeout=3) + conn.request(method, path, body=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json"}) + r = conn.getresponse() + out = (r.status, json.loads(r.read().decode())) + conn.close() + return out + try: + assert call("GET", "/api/force_offroad")[1]["pending"] is True + assert call("POST", "/api/force_offroad", {"answer": "yes"})[0] == 400 + status, data = call("POST", "/api/force_offroad", {"answer": "yes", "confirm": True}) + assert status == 200 and data["pending"] is False + assert call("POST", "/api/set", {"action": "engage"})[0] == 400 + finally: + httpd.shutdown() + httpd.server_close() + + +def test_force_offroad_tap_has_no_generic_confirm_and_returns_prompt(): + """Tap Force Offroad: parked applies at once; car on -> only the steering Yes/No, in the same response.""" + from openpilot.selfdrive.nap_dash import ui_api + from openpilot.selfdrive.nap_dash.ui_api import _needs_confirm + assert _needs_confirm(None, {"writer": "force_offroad", "confirm": True}, True, False) is False + html = (Path(__file__).resolve().parents[1] / "dashboard.html").read_text() + assert 'ctrl.writer !== "force_offroad"' in html and "foRender(data.force_offroad_ack)" in html + + class Full(FakeParams): + def get(self, key, *a, **kw): + return None + + def put(self, key, value, *a, **kw): + self.writes.append((key, value)) + + for onroad, pending in ((False, False), (True, True)): + p = Full(IsOnroad=onroad) + out = ui_api.write_setting(p, "NAPForceOffroad", True, confirm=False) + assert p.bools["NAPForceOffroad"] is True + assert p.bools["NAPForceOffroadConfirmed"] is (not onroad) + assert read_ack(p)["pending"] is pending + assert out is not None diff --git a/selfdrive/nap_dash/tests/test_server_smoke.py b/selfdrive/nap_dash/tests/test_server_smoke.py new file mode 100644 index 00000000000000..a18e5857a9c990 --- /dev/null +++ b/selfdrive/nap_dash/tests/test_server_smoke.py @@ -0,0 +1,313 @@ +"""Process wiring + HTTP smoke for the in-tree Dash. No live cereal required.""" +from __future__ import annotations + +import json +from http.client import HTTPConnection +from pathlib import Path +from threading import Thread + +import pytest + +from openpilot.selfdrive.nap_dash.server import Handler, ThreadingHTTPServer +from openpilot.selfdrive.nap_dash.tests.test_settings import FakeParams + +ROOT = Path(__file__).resolve().parents[3] + + +def test_process_config_registers_optional_python_process(): + cfg = (ROOT / "system" / "manager" / "process_config.py").read_text(encoding="utf-8") + assert 'PythonProcess("nap_dash"' in cfg + assert "selfdrive.nap_dash.server" in cfg + snippet = cfg.split('PythonProcess("nap_dash"', 1)[1][:400] + assert "nap_dash_enabled" in snippet + assert "restart_if_crash=True" in snippet + assert "optional=True" in snippet + optional_src = (ROOT / "system" / "manager" / "optional_procs.py").read_text(encoding="utf-8") + assert "NAPDashEnabled" in optional_src + assert "NAPDashEnabled" in (ROOT / "common" / "params_keys.h").read_text(encoding="utf-8") + + +def test_docs_cover_hotspot_and_mannerisms(): + docs = (ROOT / "docs-nap" / "nap-dash.md").read_text(encoding="utf-8") + readme = (ROOT / "docs-nap" / "README.md").read_text(encoding="utf-8") + assert "http://100.99.9.1/" in docs + assert "100.99.9.0/24" in docs + assert "hotspot" in docs.lower() + assert "Driving Mannerisms" in docs + assert "do not merge" in docs.lower() + assert "nap-dash.md" in readme + assert "panda" in docs.lower() + assert "optional" in docs.lower() + assert "processNotRunning" in docs + assert "NAPDashEnabled" in docs + assert "https://installer.comma.ai/jmbrunick/openpilot/cursor/mcu-web-ui-c588" in docs + assert "/api/software" in docs + assert "no high-rate sockets" in docs.lower() + assert "modelV2" in docs + assert "`can`" in docs + assert "LTE" in docs + + +def test_onroad_cpu_budget_lists_nap_dash(): + onroad = (ROOT / "selfdrive" / "test" / "test_onroad.py").read_text(encoding="utf-8") + assert '"selfdrive.nap_dash.server"' in onroad + + +def test_http_set_round_trip(monkeypatch): + from openpilot.selfdrive.nap_dash import server as srv + + params = FakeParams() + monkeypatch.setattr(srv, "PARAMS", params) + monkeypatch.setattr(srv, "_params", lambda: params) + + httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=httpd.serve_forever, daemon=True) + thread.start() + try: + host, port = httpd.server_address + conn = HTTPConnection(host, port, timeout=3) + conn.request("GET", "/") + home = conn.getresponse() + body = home.read().decode("utf-8") + assert home.status == 200 + assert "openpilot" in body + assert "XMLHttpRequest" in body + assert "fetch(" not in body + assert "speed_trim" not in body + conn.close() + + conn = HTTPConnection(host, port, timeout=3) + conn.request("GET", "/api/state") + state_resp = conn.getresponse() + state = json.loads(state_resp.read().decode("utf-8")) + assert state_resp.status == 200 + assert state["lite"] is True + assert state["car"] == {} + assert state["bms"] == {} + assert state["lead1"] == {} + conn.close() + + conn = HTTPConnection(host, port, timeout=5) + conn.request("GET", "/api/manifest") + manifest_resp = conn.getresponse() + manifest = json.loads(manifest_resp.read().decode("utf-8")) + assert manifest_resp.status == 200 + assert manifest["hotspot"]["url"] == "http://100.99.9.1/" + titles = [item["title"] for item in manifest["controls"]] + assert "Driving Mannerisms" in titles or "Soft Lateral Handoff" in titles + assert any(item["param"] == "IsMetric" for item in manifest["controls"]) + conn.close() + + conn = HTTPConnection(host, port, timeout=5) + conn.request("GET", "/api/settings") + settings_resp = conn.getresponse() + settings_body = json.loads(settings_resp.read().decode("utf-8")) + assert settings_resp.status == 200 + assert "IsMetric" in settings_body["values"] + assert any(item.get("param") == "IsMetric" for item in settings_body["catalog"]) + conn.close() + + conn = HTTPConnection(host, port, timeout=3) + conn.request("GET", "/api/routes") + routes = conn.getresponse() + assert routes.status == 404 + routes.read() + conn.close() + + conn = HTTPConnection(host, port, timeout=5) + payload = json.dumps({"param": "IsMetric", "value": True}).encode() + conn.request("POST", "/api/set", body=payload, headers={"Content-Type": "application/json"}) + resp = conn.getresponse() + data = json.loads(resp.read().decode("utf-8")) + assert resp.status == 200 + assert data["values"]["IsMetric"] is True + assert params.bools["IsMetric"] is True + conn.close() + + conn = HTTPConnection(host, port, timeout=3) + conn.request("POST", "/api/set", body=json.dumps({"name": "speed_trim", "value": 5}).encode(), + headers={"Content-Type": "application/json"}) + bad = conn.getresponse() + err = json.loads(bad.read().decode("utf-8")) + assert bad.status == 400 + assert "rejected" in err["error"] or "unknown" in err["error"] or "not allowed" in err["error"] + conn.close() + + conn = HTTPConnection(host, port, timeout=3) + conn.request("POST", "/api/set", body=json.dumps({"action": "engage"}).encode(), + headers={"Content-Type": "application/json"}) + engage = conn.getresponse() + engage_err = json.loads(engage.read().decode("utf-8")) + assert engage.status == 400 + assert "not allowed" in engage_err["error"] + conn.close() + + conn = HTTPConnection(host, port, timeout=3) + conn.request("POST", "/api/nav/update", body=json.dumps({"route_state": "active"}).encode(), + headers={"Content-Type": "application/json"}) + nav = conn.getresponse() + assert nav.status == 404 + conn.close() + finally: + httpd.shutdown() + httpd.server_close() + + +def test_server_source_has_no_nav_write_or_settings_file(): + src = (ROOT / "selfdrive" / "nap_dash" / "server.py").read_text(encoding="utf-8") + assert "NAP_SETTINGS_FILE" not in src + assert "update_nap_settings_file" not in src + assert "/api/nav" not in src + assert "PHONE_HTML" not in src + assert "def update_navigation" not in src + assert "def bind_http_server" in src + assert "idle_until_stop" in src + assert "/api/software" in src + assert "handle_software" in src + + +def test_server_has_no_high_rate_cereal(): + """Phone Hub settings/software are Params + HTTP. No cereal drain.""" + src = (ROOT / "selfdrive" / "nap_dash" / "server.py").read_text(encoding="utf-8") + assert "SubMaster" not in src + assert "messaging" not in src + assert "modelV2" not in src + assert "TELEMETRY_SVCS" not in src + assert "def telemetry" not in src + assert "_decode_bms" not in src + assert "ffmpeg" not in src + assert "/api/routes" not in src + assert "/stream/" not in src + assert "/export/" not in src + assert '"can"' not in src + assert "'can'" not in src + for name in ("settings.py", "system_api.py", "ui_api.py", "discover.py"): + companion = (ROOT / "selfdrive" / "nap_dash" / name).read_text(encoding="utf-8") + assert "SubMaster" not in companion + assert "modelV2" not in companion + assert "import cereal" not in companion + assert "from cereal" not in companion + html = (ROOT / "selfdrive" / "nap_dash" / "dashboard.html").read_text(encoding="utf-8") + assert "=>" not in html + assert "let " not in html + assert "const " not in html + assert "fetch(" not in html + assert "Phone guidance" not in html + assert "Cruise speed trim" not in html + assert "#2563eb" in html + assert "overflow:hidden" in html.replace(" ", "") + assert "float:left" not in html.replace(" ", "") + + +def test_nap_dash_is_optional_and_ignored_by_process_not_running(): + from types import SimpleNamespace + from openpilot.system.manager.optional_procs import ( + OPTIONAL_PROCESS_NAMES, missing_required_processes, nap_dash_enabled, + ) + + assert "nap_dash" in OPTIONAL_PROCESS_NAMES + assert "card" not in OPTIONAL_PROCESS_NAMES + assert "selfdrived" not in OPTIONAL_PROCESS_NAMES + assert "controlsd" not in OPTIONAL_PROCESS_NAMES + + dash = SimpleNamespace(name="nap_dash", running=False, shouldBeRunning=True) + card = SimpleNamespace(name="card", running=False, shouldBeRunning=True) + assert missing_required_processes([dash]) == [] + assert missing_required_processes([dash, card]) == ["card"] + + class _P: + def get(self, key): + return None + def get_bool(self, key): + raise AssertionError("missing NAPDashEnabled must fail open") + assert nap_dash_enabled(True, _P(), None) is True + + class _Off: + def get(self, key): + return "0" + def get_bool(self, key): + return False + assert nap_dash_enabled(True, _Off(), None) is False + + +def test_bind_failure_returns_none_and_idle_stops(monkeypatch): + from openpilot.selfdrive.nap_dash import server as srv + + def _raise(*_args, **_kwargs): + raise OSError("Address already in use") + + monkeypatch.setattr(srv, "DashHTTPServer", _raise) + assert srv.bind_http_server("127.0.0.1", 1) is None + + calls = [] + stop = type("E", (), {"is_set": lambda self: len(calls) >= 2})() + def sleeper(_dt): + calls.append(1) + srv.idle_until_stop(stop_event=stop, sleeper=sleeper) + assert len(calls) == 2 + + +def test_optional_prepare_and_dead_process_are_non_critical(): + pytest.importorskip("capnp") + from openpilot.system.manager.process import PythonProcess + + p = PythonProcess("nap_dash", "openpilot.does.not.exist.nap_dash", lambda *_a: True, optional=True) + p.prepare() # must not raise / must not take down manager + + class Dead: + pid = 1 + exitcode = 1 + def is_alive(self): + return False + + p.proc = Dead() + state = p.get_process_state_msg() + assert state.running is False + assert state.shouldBeRunning is False + + +def test_process_not_running_alert_omits_optional_dash(): + pytest.importorskip("capnp") + from cereal import car, log + from openpilot.selfdrive.selfdrived.events import process_not_running_alert + + cs = car.CarState.new_message() + cp = car.CarParams.new_message() + dash = log.ManagerState.ProcessState.new_message() + dash.name = "nap_dash" + dash.running = False + dash.shouldBeRunning = True + ms = log.ManagerState.new_message() + ms.processes = [dash] + alert = process_not_running_alert(cp, cs, {"managerState": ms}, False, 100, log.LongitudinalPersonality.standard) + assert "nap_dash" not in (alert.alert_text_1 + " " + alert.alert_text_2) + + +def test_bookmark_endpoints_offroad_and_onroad(): + from openpilot.selfdrive.nap_dash.server import bookmark_status, bookmark_tap + p = FakeParams() + assert bookmark_status(p) == {"recording": False, "left": 0} + out = bookmark_tap(p) + assert out["ok"] is False and out["reason"] == "offroad" + assert p.get("NAPBookmarkRequest") is None + p.bools["IsOnroad"] = True + assert bookmark_tap(p)["ok"] is True + assert p.get("NAPBookmarkRequest") is not None + p.put("NAPBookmarkRecording", 23) + assert bookmark_status(p) == {"recording": True, "left": 23} + + +def test_dashboard_has_bookmark_button(): + html = (ROOT / "selfdrive" / "nap_dash" / "dashboard.html").read_text(encoding="utf-8") + assert "/api/bookmark" in html and "REC " in html and '"Bookmark"' in html + + +def test_dashboard_hides_firehose_and_developer(): + html = (ROOT / "selfdrive" / "nap_dash" / "dashboard.html").read_text(encoding="utf-8") + assert "DASH_HIDDEN_PANELS = { firehose: true, developer: true }" in html + + +def test_comma_sidebar_has_no_bookmark(): + src = (ROOT / "selfdrive" / "ui" / "layouts" / "settings" / "settings.py").read_text(encoding="utf-8") + assert "Bookmark" not in src + assert "NAV_BTN_HEIGHT = 110" in src diff --git a/selfdrive/nap_dash/tests/test_settings.py b/selfdrive/nap_dash/tests/test_settings.py new file mode 100644 index 00000000000000..e86a2720512dcb --- /dev/null +++ b/selfdrive/nap_dash/tests/test_settings.py @@ -0,0 +1,132 @@ +"""Web writes follow the discovered device controls. No engage, no cereal.""" +from __future__ import annotations + +import pytest + +from openpilot.selfdrive.nap_dash.ui_api import SettingError, read_settings, write_setting + + +class FakeParams: + def __init__(self, values=None, bools=None): + self.values = dict(values or {}) + self.bools = dict(bools or {}) + self.writes: list[tuple[str, object]] = [] + + def get(self, key, return_default=False): + if key in self.values: + return self.values[key] + return None + + def get_bool(self, key): + return bool(self.bools.get(key, False)) + + def put(self, key, value, block=False): + self.writes.append((key, value)) + self.values[key] = value + + def put_bool(self, key, value, block=False): + self.writes.append((key, bool(value))) + self.bools[key] = bool(value) + + def remove(self, key): + self.values.pop(key, None) + self.bools.pop(key, None) + + +def test_read_settings_does_not_write(): + params = FakeParams(bools={"IsMetric": True}) + snap = read_settings(params) + assert snap["values"]["IsMetric"] is True + assert params.writes == [] + assert snap["onroad"] is False + assert snap["engaged"] is False + + +def test_metric_round_trip_and_unknown_name_rejected(): + params = FakeParams() + snap = write_setting(params, "IsMetric", True) + assert snap["values"]["IsMetric"] is True + assert params.bools["IsMetric"] is True + for name in ("speed_trim", "city_turns", "tap_lc", "corner_assist", "lane_centering", "engage"): + with pytest.raises(SettingError): + write_setting(params, name, 1) + + +def test_experimental_requires_confirmation_then_sets_confirmed(): + params = FakeParams() + with pytest.raises(SettingError, match="confirmation"): + write_setting(params, "ExperimentalMode", True) + assert "ExperimentalMode" not in params.bools + snap = write_setting(params, "ExperimentalMode", True, confirm=True) + assert snap["values"]["ExperimentalMode"] is True + assert params.bools["ExperimentalModeConfirmed"] is True + write_setting(params, "ExperimentalMode", False) + assert params.bools["ExperimentalMode"] is False + + +def test_onroad_and_engaged_locks(): + params = FakeParams(bools={"IsOnroad": True}) + with pytest.raises(SettingError, match="car is on"): + write_setting(params, "AdbEnabled", True) + assert "AdbEnabled" not in params.bools + + parked = FakeParams(bools={"IsEngaged": True}) + with pytest.raises(SettingError, match="engaged"): + write_setting(parked, "OpenpilotEnabledToggle", False) + write_setting(parked, "IsMetric", True) + assert parked.bools["IsMetric"] is True + + +def test_simulate_look_and_false_alert_are_exclusive(): + params = FakeParams(bools={"NAPDmSimulateLooking": True, "NAPDmFalseAlertIgnore": False}) + snap = write_setting(params, "NAPDmFalseAlertIgnore", True) + assert snap["values"]["NAPDmFalseAlertIgnore"] is True + assert snap["values"]["NAPDmSimulateLooking"] is False + snap = write_setting(params, "NAPDmSimulateLooking", True) + assert snap["values"]["NAPDmSimulateLooking"] is True + assert snap["values"]["NAPDmFalseAlertIgnore"] is False + + +def test_map_speed_choice_rejects_unknown_value(): + params = FakeParams() + snap = write_setting(params, "NAPMapSpeedMode", 3) + assert snap["values"]["NAPMapSpeedMode"] == 3 + with pytest.raises(SettingError): + write_setting(params, "NAPMapSpeedMode", 9) + snap = write_setting(params, "NAPMapSpeedOffsetMph", -5) + assert snap["values"]["NAPMapSpeedOffsetMph"] == -5 + + +def test_speed_sign_write_is_plain_param_put(): + """Discovered from the device UI. The write is put_bool, not a new code path.""" + params = FakeParams() + write_setting(params, "NAPSpeedSignLog", True) + assert params.bools["NAPSpeedSignLog"] is True + assert [item for item in params.writes if item[0] == "NAPSpeedSignLog"] == [("NAPSpeedSignLog", True)] + assert "OnroadCycleRequested" not in params.bools + + +def test_hypermile_uses_device_helper(): + params = FakeParams(bools={"NAPHypermile": False, "NAPAdaptiveAccel": True}) + snap = write_setting(params, "NAPHypermile", True) + assert snap["values"]["NAPHypermile"] is True + assert params.bools["NAPHypermile"] is True + + +def test_reboot_requires_confirmation_and_blocks_while_engaged(): + params = FakeParams() + with pytest.raises(SettingError, match="confirmation"): + write_setting(params, "DoReboot", True) + assert "DoReboot" not in params.bools + write_setting(params, "DoReboot", True, confirm=True) + assert params.bools["DoReboot"] is True + + engaged = FakeParams(bools={"IsEngaged": True}) + with pytest.raises(SettingError, match="engaged"): + write_setting(engaged, "DoShutdown", True, confirm=True) + + +def test_disabled_device_control_is_not_writable(): + params = FakeParams() + with pytest.raises(SettingError): + write_setting(params, "NAPiBoosterEnabled", True) diff --git a/selfdrive/nap_dash/tests/test_system_api.py b/selfdrive/nap_dash/tests/test_system_api.py new file mode 100644 index 00000000000000..0c9a4c038d4dd5 --- /dev/null +++ b/selfdrive/nap_dash/tests/test_system_api.py @@ -0,0 +1,338 @@ +"""nap_dash /api/software — UpdaterTargetBranch + SIGUSR1. No SSH. No engage.""" +from __future__ import annotations + +import datetime +import json +from http.client import HTTPConnection +from threading import Thread + +import pytest + +from openpilot.selfdrive.nap_dash.server import Handler, ThreadingHTTPServer +from openpilot.selfdrive.nap_dash.system_api import ( + SoftwareError, + handle_software, + read_software, + sanitize_branch, + time_ago, +) + + +class FakeParams: + def __init__(self, values=None, bools=None): + self.values = dict(values or {}) + self.bools = dict(bools or {}) + self.writes: list[tuple[str, object]] = [] + + def get(self, key, return_default=False): + return self.values.get(key) + + def get_bool(self, key): + return bool(self.bools.get(key, False)) + + def put(self, key, value, block=False): + self.writes.append((key, value)) + self.values[key] = value + + def put_bool(self, key, value): + self.writes.append((key, bool(value))) + self.bools[key] = bool(value) + + +def test_sanitize_branch_matches_hub_rules(): + assert sanitize_branch("nap-release") == "nap-release" + assert sanitize_branch("cursor/nap-dash-dev-e946") == "cursor/nap-dash-dev-e946" + with pytest.raises(SoftwareError): + sanitize_branch("../etc/passwd") + with pytest.raises(SoftwareError): + sanitize_branch("engage") + with pytest.raises(SoftwareError): + sanitize_branch("branch;reboot") + + +def test_branch_names_containing_engage_are_accepted(): + name = "cursor/speedsignd-engaged-read-spacing-3353" + assert sanitize_branch(name) == name + params = FakeParams() + snap = handle_software({"action": "set_branch", "branch": name}, params, pinger=lambda *_a: None, running=True) + assert snap["target_branch"] == name + # engaging is still refused as an action + for payload in ({"action": "engage"}, {"action": "disengage"}): + with pytest.raises(SoftwareError, match="not allowed"): + handle_software(payload, params, pinger=lambda *_a: None) + + +def test_set_branch_writes_target_and_pings_updated(): + params = FakeParams(values={"GitBranch": "nap-dev", "UpdaterTargetBranch": "nap-dev"}) + pings = [] + snap = handle_software( + {"action": "set_branch", "branch": "nap-release"}, + params, + pinger=lambda sig: pings.append(sig), + ) + assert snap["target_branch"] == "nap-release" + assert ("UpdaterTargetBranch", "nap-release") in params.writes + assert pings == ["USR1"] + + +def test_fetch_pings_without_writing_branch(): + params = FakeParams(values={"UpdaterTargetBranch": "nap-dev"}) + pings = [] + handle_software({"action": "fetch"}, params, pinger=lambda sig: pings.append(sig)) + assert params.writes == [] + assert pings == ["USR1"] + + +def test_set_offline_action_is_gone(): + params = FakeParams() + with pytest.raises(SoftwareError, match="not allowed"): + handle_software({"action": "set_offline", "offline": True}, params, pinger=lambda *_a: None) + assert params.writes == [] + + +def test_update_flow_steps_check_download_install(): + base = {"UpdaterTargetBranch": "nap-dev"} + snap = read_software(FakeParams(values=dict(base)), running=True) + assert (snap["step"], snap["step_label"]) == ("check", "Check") + assert snap["status_text"].startswith("up to date") + + snap = read_software(FakeParams(values=dict(base, UpdaterState="checking...")), running=True) + assert (snap["step"], snap["step_label"]) == ("checking", "Checking…") + + snap = read_software(FakeParams(values=dict(base), bools={"UpdaterFetchAvailable": True}), running=True) + assert (snap["step"], snap["step_label"]) == ("download", "Download") + + for state in ("downloading...", "finalizing update..."): + snap = read_software(FakeParams(values=dict(base, UpdaterState=state), bools={"UpdaterFetchAvailable": True}), running=True) + assert (snap["step"], snap["step_label"]) == ("downloading", "Downloading…") + + snap = read_software( + FakeParams(values=dict(base, UpdaterNewDescription="0.10.1 / nap-dev / abc1234 / 2026-10-09"), + bools={"UpdateAvailable": True, "UpdaterFetchAvailable": False}), + running=True, + ) + assert snap["step"] == "install" + assert snap["step_label"] == "Install & reboot with 0.10.1 / nap-dev" + + # a failed check offers Check again, not Download + snap = read_software(FakeParams(values=dict(base, UpdateFailedCount=1), bools={"UpdaterFetchAvailable": True}), running=True) + assert snap["step"] == "check" + + +def test_page_has_check_and_download_buttons_and_no_go_offline(): + from pathlib import Path + html = (Path(__file__).resolve().parents[1] / "dashboard.html").read_text() + assert "Go offline" not in html and "set_offline" not in html and "Pause updates" not in html + assert html.count('actions.appendChild(swButton(') == 3 + assert '"Check"' in html and '"Download"' in html + # Install & reboot is only added when a downloaded update is ready + assert "if (data.update_available && data.can_install)" in html + + +def test_download_greyed_until_check_finds_update(): + base = {"UpdaterTargetBranch": "nap-dev"} + snap = read_software(FakeParams(values=dict(base)), running=True) + assert snap["can_check"] is True and snap["can_download"] is False + snap = read_software(FakeParams(values=dict(base), bools={"UpdaterFetchAvailable": True}), running=True) + assert snap["can_check"] is True and snap["can_download"] is True + # once downloaded, Install takes over and Download greys out again + snap = read_software(FakeParams(values=dict(base), bools={"UpdaterFetchAvailable": True, "UpdateAvailable": True}), running=True) + assert snap["can_download"] is False and snap["can_install"] is True + + +def test_download_sends_sighup_like_comma_software_panel(): + params = FakeParams() + pings = [] + handle_software({"action": "download"}, params, pinger=lambda sig: pings.append(sig), running=True) + assert pings == ["HUP"] + + +def test_check_and_download_blocked_when_updates_paused_or_onroad(): + for bools, words in (({"DisableUpdates": True}, "paused"), ({"IsOnroad": True}, "car is off")): + params = FakeParams(bools=bools) + pings: list[str] = [] + for action in ("fetch", "download"): + with pytest.raises(SoftwareError, match=words): + handle_software({"action": action}, params, pinger=pings.append, running=True) + assert pings == [] + snap = read_software(params, running=True) + assert words in snap["blocked_reason"] + assert snap["can_check"] is False and snap["can_download"] is False + + +def test_status_mirrors_updater_params(): + base = {"UpdaterTargetBranch": "nap-dev"} + snap = read_software(FakeParams(values=dict(base, UpdaterState="checking...")), running=True) + assert snap["busy"] is True and snap["status_text"] == "checking…" + assert snap["can_check"] is False + + snap = read_software(FakeParams(values=dict(base, UpdaterState="downloading...")), running=True) + assert snap["status_text"] == "downloading…" + + recent = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - datetime.timedelta(minutes=5) + snap = read_software(FakeParams(values=dict(base, UpdaterState="idle", LastUpdateTime=recent)), running=True) + assert snap["status_text"] == "up to date, last checked 5 minutes ago" + assert snap["last_update_time"].endswith("Z") + assert snap["can_check"] is True and snap["next_action"] == "check" + + snap = read_software(FakeParams(values=dict(base), bools={"UpdaterFetchAvailable": True}), running=True) + assert snap["status_text"].startswith("update available") + assert snap["next_action"] == "download" and snap["can_download"] is True + + snap = read_software( + FakeParams(values=dict(base, UpdaterNewDescription="0.10.1 / nap-dev / abc1234"), bools={"UpdateAvailable": True}), + running=True, + ) + assert snap["status_text"].startswith("update ready, reboot to install (0.10.1") + + snap = read_software( + FakeParams(values=dict(base, UpdateFailedCount=2, LastUpdateException="command failed: git fetch")), + running=True, + ) + assert snap["update_failed_count"] == 2 + assert snap["status_text"].startswith("failed to check for update") + assert snap["last_update_exception"] == "command failed: git fetch" + + +def test_status_flags_stopped_updater_and_time_ago_buckets(): + snap = read_software(FakeParams(), running=False) + assert snap["updater_running"] is False + assert "not running" in snap["blocked_reason"] + assert snap["status_text"] == "up to date, last checked never" + now = datetime.datetime(2026, 10, 8, 12, 0, 0) + assert time_ago(None, now) == "never" + assert time_ago(now - datetime.timedelta(seconds=10), now) == "now" + assert time_ago(now - datetime.timedelta(hours=1), now) == "1 hour ago" + assert time_ago(now - datetime.timedelta(days=3), now) == "3 days ago" + + +def test_install_and_reboot_mirrors_native_install(): + ready = {"UpdaterNewDescription": "0.10.1 / nap-dev / abc1234 / 2026-10-08"} + params = FakeParams(values=dict(ready), bools={"UpdateAvailable": True}) + snap = read_software(params, running=True) + assert snap["can_install"] is True + assert snap["install_label"] == "Install & reboot with 0.10.1 / nap-dev" + + # confirm tap is required + with pytest.raises(SoftwareError, match="confirmation"): + handle_software({"action": "install"}, params, pinger=lambda *_a: None, running=True) + assert ("DoReboot", True) not in params.writes + + snap = handle_software({"action": "install", "confirm": True}, params, pinger=lambda *_a: None, running=True) + assert ("DoReboot", True) in params.writes + assert snap["rebooting"] is True + + +def test_install_label_keeps_slash_branch_names(): + params = FakeParams( + values={"UpdaterNewDescription": "0.10.1 / cursor/mcu-web-ui-c588 / abc1234 / 2026-10-08"}, + bools={"UpdateAvailable": True}, + ) + assert read_software(params, running=True)["install_label"] == "Install & reboot with 0.10.1 / cursor/mcu-web-ui-c588" + + +def test_install_blocked_onroad_or_without_update(): + ready = {"UpdaterNewDescription": "0.10.1 / nap-dev / abc1234 / 2026-10-08"} + cases = ( + ({"UpdateAvailable": True, "IsOnroad": True}, "only downloaded while the car is off"), + ({"UpdateAvailable": True, "IsOnroad": True, "IsEngaged": True}, "only downloaded while the car is off"), + ({}, "No downloaded update"), + ) + for bools, words in cases: + params = FakeParams(values=dict(ready), bools=bools) + with pytest.raises(SoftwareError, match=words): + handle_software({"action": "install", "confirm": True}, params, pinger=lambda *_a: None, running=True) + assert ("DoReboot", True) not in params.writes + assert read_software(params, running=True)["can_install"] is False + + +def test_rejects_engage_and_uninstall(): + params = FakeParams() + for payload in ({"action": "engage"}, {"action": "uninstall"}, {"action": "set_branch", "branch": "engage"}): + with pytest.raises(SoftwareError): + handle_software(payload, params, pinger=lambda *_a: None) + + +def test_read_software_lists_available_branches(): + params = FakeParams( + values={ + "GitBranch": "nap-dev", + "GitCommit": "abc123", + "UpdaterTargetBranch": "nap-release", + "UpdaterAvailableBranches": "nap-release,nap-dev,cursor/nap-dash-dev-e946", + "UpdaterState": "idle", + }, + bools={"UpdaterFetchAvailable": True, "DisableUpdates": True}, + ) + snap = read_software(params, running=True) + assert snap["git_branch"] == "nap-dev" + assert snap["available_branches"] == ["nap-release", "nap-dev", "cursor/nap-dash-dev-e946"] + assert snap["fetch_available"] is True + assert snap["offline"] is True + + +def test_http_software_round_trip(monkeypatch): + from openpilot.selfdrive.nap_dash import server as srv + + params = FakeParams(values={"GitBranch": "nap-dev", "UpdaterTargetBranch": "nap-dev"}) + monkeypatch.setattr(srv, "PARAMS", params) + monkeypatch.setattr(srv, "_params", lambda: params) + + httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=httpd.serve_forever, daemon=True) + thread.start() + try: + host, port = httpd.server_address + conn = HTTPConnection(host, port, timeout=3) + conn.request("GET", "/api/software") + got = json.loads(conn.getresponse().read().decode()) + assert got["git_branch"] == "nap-dev" + conn.close() + + conn = HTTPConnection(host, port, timeout=3) + conn.request( + "POST", + "/api/software", + body=json.dumps({"action": "set_branch", "branch": "nap-release"}).encode(), + headers={"Content-Type": "application/json"}, + ) + resp = conn.getresponse() + data = json.loads(resp.read().decode()) + assert resp.status == 200 + assert data["target_branch"] == "nap-release" + conn.close() + + conn = HTTPConnection(host, port, timeout=3) + conn.request( + "POST", + "/api/software", + body=json.dumps({"action": "engage"}).encode(), + headers={"Content-Type": "application/json"}, + ) + bad = conn.getresponse() + err = json.loads(bad.read().decode()) + assert bad.status == 400 + assert "not allowed" in err["error"] + conn.close() + finally: + httpd.shutdown() + httpd.server_close() + + +def test_install_matches_native_offroad_and_update_available(): + """Native INSTALL: visible+enabled iff is_offroad() and UpdateAvailable; no engaged/busy check.""" + ready = {"UpdaterNewDescription": "0.11.1 / nap-dev / 245b476 / 2026-10-11"} + # stale IsEngaged while offroad (the reported case) must not lock install + params = FakeParams(values=dict(ready), bools={"UpdateAvailable": True, "IsEngaged": True}) + snap = read_software(params, running=True) + assert snap["can_install"] is True and snap["install_blocked_reason"] == "" + handle_software({"action": "install", "confirm": True}, params, pinger=lambda *_a: None, running=True) + assert ("DoReboot", True) in params.writes + # updater busy does not hide the native button either + snap = read_software(FakeParams(values=dict(ready, UpdaterState="checking..."), bools={"UpdateAvailable": True}), running=True) + assert snap["can_install"] is True + # onroad: unavailable, same text as the native panel + snap = read_software(FakeParams(values=dict(ready), bools={"UpdateAvailable": True, "IsOnroad": True}), running=True) + assert snap["can_install"] is False + assert snap["install_blocked_reason"] == "Updates are only downloaded while the car is off." + assert snap["blocked_reason"] == "Updates are only downloaded while the car is off." diff --git a/selfdrive/nap_dash/ui_api.py b/selfdrive/nap_dash/ui_api.py new file mode 100644 index 00000000000000..57687af4077824 --- /dev/null +++ b/selfdrive/nap_dash/ui_api.py @@ -0,0 +1,283 @@ +"""Read and write the controls discovered from the on-device settings UI. + +No cereal subscriber. Onroad / engaged locks use the Params hardwared +already maintains (IsOnroad, IsEngaged). +""" +from __future__ import annotations + +import subprocess +from typing import Any + +from openpilot.selfdrive.nap_dash.discover import discover_manifest + +_MANIFEST: dict[str, Any] | None = None + +_PUBLIC = ( + "id", "panel", "section", "param", "title", "description", "kind", + "confirm", "lock_onroad", "lock_engaged", "disabled", "needs_restart", + "reboot_hint", "choices", "values", "release_hidden", "target_panel", "writable", +) + + +class SettingError(ValueError): + """Invalid web setting name or value.""" + + +def get_manifest(refresh: bool = False) -> dict[str, Any]: + global _MANIFEST + if _MANIFEST is None or refresh: + _MANIFEST = discover_manifest() + return _MANIFEST + + +def public_manifest(manifest: dict[str, Any] | None = None) -> dict[str, Any]: + manifest = get_manifest() if manifest is None else manifest + return { + "hotspot": manifest["hotspot"], + "panels": manifest["panels"], + "controls": [{key: ctrl[key] for key in _PUBLIC} for ctrl in manifest["controls"]], + } + + +def setting_catalog(manifest: dict[str, Any] | None = None) -> list[dict[str, Any]]: + return public_manifest(manifest)["controls"] + + +def _flag(params, key: str) -> bool: + try: + return bool(params.get_bool(key)) + except Exception: + return False + + +def _onroad(params) -> bool: + return _flag(params, "IsOnroad") + + +def _engaged(params) -> bool: + return _flag(params, "IsEngaged") + + +def _release(params) -> bool: + return _flag(params, "IsReleaseBranch") + + +def _lock_reason(params, ctrl: dict[str, Any]) -> str: + if ctrl.get("disabled"): + return "not available" + if ctrl.get("release_hidden") and _release(params): + return "not available on this software" + if ctrl.get("lock_onroad") and _onroad(params): + return "locked while the car is on" + if ctrl.get("lock_engaged") and _engaged(params): + return "locked while openpilot is engaged" + if ctrl.get("lock_param") and _flag(params, ctrl["lock_param"]): + return "locked" + return "" + + +def _locked_map(params, manifest: dict[str, Any]) -> dict[str, str]: + locked = {} + for ctrl in manifest["controls"]: + if not ctrl.get("param"): + continue + reason = _lock_reason(params, ctrl) + if reason: + locked[ctrl["param"]] = reason + return locked + + +def _read_one(params, ctrl: dict[str, Any], ptype: str) -> Any: + try: + if ctrl["kind"] in ("toggle", "action") or ptype == "bool": + return bool(params.get_bool(ctrl["param"])) + raw = params.get(ctrl["param"], return_default=True) + except Exception: + return None + if raw is None or raw == "": + return None + if isinstance(raw, bytes): + raw = raw.decode("utf-8", "replace") + try: + if ptype == "int": + return int(raw) + if ptype == "float": + return float(raw) + except (TypeError, ValueError): + return raw + return raw + + +def read_settings(params, manifest: dict[str, Any] | None = None) -> dict[str, Any]: + """Snapshot of discovered params. Does not write.""" + manifest = get_manifest() if manifest is None else manifest + types = manifest.get("param_types") or {} + values: dict[str, Any] = {} + for ctrl in manifest["controls"]: + param = ctrl.get("param") or "" + if not param or param in values: + continue + if ctrl["kind"] not in ("toggle", "choice", "text", "action"): + continue + values[param] = _read_one(params, ctrl, types.get(param, "")) + return { + "onroad": _onroad(params), + "engaged": _engaged(params), + "release": _release(params), + "values": values, + "locked": _locked_map(params, manifest), + } + + +def _find(manifest: dict[str, Any], name: str) -> dict[str, Any] | None: + key = str(name or "").strip() + if not key: + return None + matches = [ctrl for ctrl in manifest["controls"] if ctrl.get("param") == key or ctrl.get("id") == key] + for ctrl in matches: + if ctrl.get("writable"): + return ctrl + return matches[0] if matches else None + + +def _as_bool(value: Any) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, (int, float)) and not isinstance(value, bool) and value in (0, 1): + return bool(value) + if isinstance(value, str): + folded = value.strip().lower() + if folded in ("1", "true", "yes", "on"): + return True + if folded in ("0", "false", "no", "off", ""): + return False + raise SettingError(f"invalid bool: {value!r}") + + +def _put_bool(params, key: str, value: bool) -> None: + try: + params.put_bool(key, bool(value), block=True) + except TypeError: + params.put_bool(key, bool(value)) + + +def _put(params, key: str, value: Any) -> None: + try: + params.put(key, value, block=True) + except TypeError: + params.put(key, value) + + +def _match_choice(value: Any, allowed: list[Any]) -> Any: + for item in allowed: + if value == item: + return item + if isinstance(item, bool): + continue + if isinstance(item, (int, float)) and not isinstance(value, bool): + try: + if float(value) == float(item): + return item + except (TypeError, ValueError): + continue + if isinstance(item, str) and str(value) == item: + return item + raise SettingError("value not allowed") + + +def _needs_confirm(params, ctrl: dict[str, Any], turning_on: bool, confirm: bool) -> bool: + # Force Offroad has no settings confirm on the comma either; its only prompt is + # the on-road "Ready to resume steering control?" Yes/No (force_offroad_api). + if ctrl.get("writer") == "force_offroad": + return False + if confirm or not ctrl.get("confirm"): + return False + if ctrl["kind"] == "action": + return True + if not turning_on: + return False + if ctrl.get("writer") == "experimental" and _flag(params, "ExperimentalModeConfirmed"): + return False + return True + + +def _apply_writer(params, ctrl: dict[str, Any], value: Any) -> None: + writer = ctrl.get("writer") or "" + param = ctrl["param"] + if writer == "action": + if _as_bool(value) is not True: + raise SettingError("invalid value") + _put_bool(params, param, True) + return + if writer == "choice" or ctrl["kind"] == "choice": + chosen = _match_choice(value, list(ctrl.get("values") or [])) + _put(params, param, chosen) + return + on = _as_bool(value) + if writer == "experimental": + _put_bool(params, "ExperimentalMode", on) + if on: + _put_bool(params, "ExperimentalModeConfirmed", True) + elif writer == "dm_sim": + from openpilot.selfdrive.monitoring.dm_toggles import apply_dm_simulate_looking + apply_dm_simulate_looking(params, on) + elif writer == "dm_fai": + from openpilot.selfdrive.monitoring.dm_toggles import apply_dm_false_alert_ignore + apply_dm_false_alert_ignore(params, on) + elif writer == "force_offroad": + from openpilot.system.hardware.nap_force_offroad import apply_force_offroad_toggle + apply_force_offroad_toggle(params, on, started=_onroad(params)) + elif writer == "hypermile": + from openpilot.selfdrive.controls.lib.hypermile import apply_hypermile_toggle + apply_hypermile_toggle(params, on) + else: + _put_bool(params, param, on) + for other in ctrl.get("also_clear") or []: + if other != param: + _put_bool(params, other, False) + if ctrl.get("needs_restart"): + _put_bool(params, "OnroadCycleRequested", True) + + +def write_setting(params, name: str, value: Any, confirm: bool = False, + manifest: dict[str, Any] | None = None) -> dict[str, Any]: + """Write one discovered control the same way the device UI does.""" + manifest = get_manifest() if manifest is None else manifest + ctrl = _find(manifest, name) + if ctrl is None: + raise SettingError(f"unknown setting: {name}") + param = str(ctrl.get("param") or "") + folded = param.lower() + if folded in {"engage", "disengage"} or folded.startswith("doengage") or "engage" == folded: + raise SettingError("engaging openpilot from the web is not allowed") + if not ctrl.get("writable"): + raise SettingError("not available on the web") + reason = _lock_reason(params, ctrl) + if reason: + raise SettingError(reason) + turning_on = True + if ctrl["kind"] == "toggle": + turning_on = _as_bool(value) + if _needs_confirm(params, ctrl, turning_on, bool(confirm)): + raise SettingError("confirmation required") + _apply_writer(params, ctrl, value) + return read_settings(params, manifest) + + +def network_status(manifest: dict[str, Any] | None = None) -> dict[str, Any]: + """Hotspot address plus local IPv4 addresses. No NetworkManager, no cereal.""" + manifest = get_manifest() if manifest is None else manifest + hotspot = manifest["hotspot"] + interfaces: list[dict[str, str]] = [] + try: + proc = subprocess.run(["ip", "-4", "-o", "addr", "show"], capture_output=True, text=True, timeout=1, check=False) + if proc.returncode == 0: + for line in proc.stdout.splitlines(): + parts = line.split() + if "inet" not in parts or len(parts) < 4: + continue + idx = parts.index("inet") + interfaces.append({"name": parts[1], "addr": parts[idx + 1]}) + except Exception: + interfaces = [] + return {"hotspot": hotspot, "interfaces": interfaces, "url": hotspot["url"]} diff --git a/selfdrive/pandad/.gitignore b/selfdrive/pandad/.gitignore index f7226cdb8760a9..cb292405c9fcdc 100644 --- a/selfdrive/pandad/.gitignore +++ b/selfdrive/pandad/.gitignore @@ -1,3 +1,3 @@ pandad pandad_api_impl.cpp -tests/test_pandad_usbprotocol +tests/test_pandad_canprotocol diff --git a/selfdrive/pandad/SConscript b/selfdrive/pandad/SConscript index 58777cafe962eb..fd59db98537941 100644 --- a/selfdrive/pandad/SConscript +++ b/selfdrive/pandad/SConscript @@ -1,13 +1,10 @@ -Import('env', 'envCython', 'common', 'messaging') +Import('env', 'arch', 'common', 'messaging') -libs = ['usb-1.0', common, messaging, 'pthread'] -panda = env.Library('panda', ['panda.cc', 'panda_comms.cc', 'spi.cc']) +if arch != "Darwin": + libs = [common, messaging, 'pthread'] + panda = env.Library('panda', ['panda.cc', 'spi.cc']) -env.Program('pandad', ['main.cc', 'pandad.cc', 'panda_safety.cc'], LIBS=[panda] + libs) -env.Library('libcan_list_to_can_capnp', ['can_list_to_can_capnp.cc']) + env.Program('pandad', ['main.cc', 'pandad.cc', 'panda_safety.cc'], LIBS=[panda] + libs) -pandad_python = envCython.Program('pandad_api_impl.so', 'pandad_api_impl.pyx', LIBS=["can_list_to_can_capnp", 'capnp', 'kj'] + envCython["LIBS"]) -Export('pandad_python') - -if GetOption('extras'): - env.Program('tests/test_pandad_usbprotocol', ['tests/test_pandad_usbprotocol.cc'], LIBS=[panda] + libs) + if GetOption('extras'): + env.Program('tests/test_pandad_canprotocol', ['tests/test_pandad_canprotocol.cc'], LIBS=[panda] + libs) diff --git a/selfdrive/pandad/__init__.py b/selfdrive/pandad/__init__.py index b72c8ccb57dd14..0c17e886a2ed30 100644 --- a/selfdrive/pandad/__init__.py +++ b/selfdrive/pandad/__init__.py @@ -1,11 +1,3 @@ -# Cython, now uses scons to build from openpilot.selfdrive.pandad.pandad_api_impl import can_list_to_can_capnp, can_capnp_to_list assert can_list_to_can_capnp assert can_capnp_to_list - -def can_capnp_to_can_list(can, src_filter=None): - ret = [] - for msg in can: - if src_filter is None or msg.src in src_filter: - ret.append((msg.address, msg.dat, msg.src)) - return ret diff --git a/selfdrive/pandad/can_list_to_can_capnp.cc b/selfdrive/pandad/can_list_to_can_capnp.cc deleted file mode 100644 index ad2393b986ccff..00000000000000 --- a/selfdrive/pandad/can_list_to_can_capnp.cc +++ /dev/null @@ -1,51 +0,0 @@ -#include "cereal/messaging/messaging.h" -#include "selfdrive/pandad/panda.h" -#include "opendbc/can/common.h" - -void can_list_to_can_capnp_cpp(const std::vector &can_list, std::string &out, bool sendcan, bool valid) { - MessageBuilder msg; - auto event = msg.initEvent(valid); - - auto canData = sendcan ? event.initSendcan(can_list.size()) : event.initCan(can_list.size()); - int j = 0; - for (auto it = can_list.begin(); it != can_list.end(); it++, j++) { - auto c = canData[j]; - c.setAddress(it->address); - c.setDat(kj::arrayPtr((uint8_t*)it->dat.data(), it->dat.size())); - c.setSrc(it->src); - } - const uint64_t msg_size = capnp::computeSerializedSizeInWords(msg) * sizeof(capnp::word); - out.resize(msg_size); - kj::ArrayOutputStream output_stream(kj::ArrayPtr((unsigned char *)out.data(), msg_size)); - capnp::writeMessage(output_stream, msg); -} - -// Converts a vector of Cap'n Proto serialized can strings into a vector of CanData structures. -void can_capnp_to_can_list_cpp(const std::vector &strings, std::vector &can_list, bool sendcan) { - AlignedBuffer aligned_buf; - can_list.reserve(strings.size()); - - for (const auto &str : strings) { - // extract the messages - capnp::FlatArrayMessageReader reader(aligned_buf.align(str.data(), str.size())); - cereal::Event::Reader event = reader.getRoot(); - - auto frames = sendcan ? event.getSendcan() : event.getCan(); - - // Add new CanData entry - CanData &can_data = can_list.emplace_back(); - can_data.nanos = event.getLogMonoTime(); - can_data.frames.reserve(frames.size()); - - // Populate CAN frames - for (const auto &frame : frames) { - CanFrame &can_frame = can_data.frames.emplace_back(); - can_frame.src = frame.getSrc(); - can_frame.address = frame.getAddress(); - - // Copy CAN data - auto dat = frame.getDat(); - can_frame.dat.assign(dat.begin(), dat.end()); - } - } -} diff --git a/selfdrive/pandad/main.cc b/selfdrive/pandad/main.cc index b63d884a45e3f5..ef30d6037c221e 100644 --- a/selfdrive/pandad/main.cc +++ b/selfdrive/pandad/main.cc @@ -16,7 +16,7 @@ int main(int argc, char *argv[]) { assert(err == 0); } - std::vector serials(argv + 1, argv + argc); - pandad_main_thread(serials); + std::string serial = (argc > 1) ? argv[1] : ""; + pandad_main_thread(serial); return 0; } diff --git a/selfdrive/pandad/panda.cc b/selfdrive/pandad/panda.cc index bc81d7de9146cb..edc2228c0c70b9 100644 --- a/selfdrive/pandad/panda.cc +++ b/selfdrive/pandad/panda.cc @@ -12,19 +12,9 @@ const bool PANDAD_MAXOUT = getenv("PANDAD_MAXOUT") != nullptr; -Panda::Panda(std::string serial, uint32_t bus_offset) : bus_offset(bus_offset) { - // try USB first, then SPI - try { - handle = std::make_unique(serial); - LOGW("connected to %s over USB", serial.c_str()); - } catch (std::exception &e) { -#ifndef __APPLE__ - handle = std::make_unique(serial); - LOGW("connected to %s over SPI", serial.c_str()); -#else - throw e; -#endif - } +Panda::Panda(std::string serial) { + handle = std::make_unique(serial); + LOGW("connected to %s over SPI", serial.c_str()); hw_type = get_hw_type(); can_reset_communications(); @@ -42,20 +32,8 @@ std::string Panda::hw_serial() { return handle->hw_serial; } -std::vector Panda::list(bool usb_only) { - std::vector serials = PandaUsbHandle::list(); - -#ifndef __APPLE__ - if (!usb_only) { - for (auto s : PandaSpiHandle::list()) { - if (std::find(serials.begin(), serials.end(), s) == serials.end()) { - serials.push_back(s); - } - } - } -#endif - - return serials; +std::vector Panda::list() { + return PandaSpiHandle::list(); } void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param) { @@ -66,6 +44,25 @@ void Panda::set_alternative_experience(uint16_t alternative_experience) { handle->control_write(0xdf, alternative_experience, 0); } +std::string Panda::serial_read(int port_number) { + std::string ret; + char buffer[USBPACKET_MAX_SIZE] = {}; + + while (true) { + int bytes_read = handle->control_read(0xe0, port_number, 0, (unsigned char *)buffer, USBPACKET_MAX_SIZE); + if (bytes_read <= 0) { + break; + } + ret.append(buffer, bytes_read); + } + + return ret; +} + +void Panda::set_uart_baud(int uart, int rate) { + handle->control_write(0xe4, uart, int(rate / 300)); +} + cereal::PandaState::PandaType Panda::get_hw_type() { unsigned char hw_query[1] = {0}; @@ -145,6 +142,10 @@ void Panda::set_can_speed_kbps(uint16_t bus, uint16_t speed) { handle->control_write(0xde, bus, (speed * 10)); } +void Panda::set_can_fd_auto(uint16_t bus, bool enabled) { + handle->control_write(0xe8, bus, enabled); +} + void Panda::set_data_speed_kbps(uint16_t bus, uint16_t speed) { handle->control_write(0xf9, bus, (speed * 10)); } @@ -169,10 +170,10 @@ void Panda::pack_can_buffer(const capnp::List::Reader &can_data int32_t pos = 0; uint8_t send_buf[2 * USB_TX_SOFT_LIMIT]; - for (auto cmsg : can_data_list) { + for (const auto &cmsg : can_data_list) { // check if the message is intended for this panda uint8_t bus = cmsg.getSrc(); - if (bus < bus_offset || bus >= (bus_offset + PANDA_BUS_OFFSET)) { + if (bus >= PANDA_BUS_OFFSET) { continue; } auto can_data = cmsg.getDat(); @@ -184,7 +185,7 @@ void Panda::pack_can_buffer(const capnp::List::Reader &can_data header.addr = cmsg.getAddress(); header.extended = (cmsg.getAddress() >= 0x800) ? 1 : 0; header.data_len_code = data_len_code; - header.bus = bus - bus_offset; + header.bus = bus; header.checksum = 0; memcpy(&send_buf[pos], (uint8_t *)&header, sizeof(can_header)); @@ -206,7 +207,7 @@ void Panda::pack_can_buffer(const capnp::List::Reader &can_data if (pos > 0) write_func(send_buf, pos); } -void Panda::can_send(capnp::List::Reader can_data_list) { +void Panda::can_send(const capnp::List::Reader &can_data_list) { pack_can_buffer(can_data_list, [=](uint8_t* data, size_t size) { handle->bulk_write(3, data, size, 5); }); @@ -260,7 +261,7 @@ bool Panda::unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector handle; + std::unique_ptr handle; public: - Panda(std::string serial="", uint32_t bus_offset=0); + Panda(std::string serial); cereal::PandaState::PandaType hw_type = cereal::PandaState::PandaType::UNKNOWN; - const uint32_t bus_offset; bool connected(); bool comms_healthy(); std::string hw_serial(); // Static functions - static std::vector list(bool usb_only=false); + static std::vector list(); // Panda functionality cereal::PandaState::PandaType get_hw_type(); void set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param=0U); void set_alternative_experience(uint16_t alternative_experience); + std::string serial_read(int port_number = 0); + void set_uart_baud(int uart, int rate); void set_fan_speed(uint16_t fan_speed); uint16_t get_fan_speed(); void set_ir_pwr(uint16_t ir_pwr); @@ -77,9 +78,10 @@ class Panda { void enable_deepsleep(); void send_heartbeat(bool engaged); void set_can_speed_kbps(uint16_t bus, uint16_t speed); + void set_can_fd_auto(uint16_t bus, bool enabled); void set_data_speed_kbps(uint16_t bus, uint16_t speed); void set_canfd_non_iso(uint16_t bus, bool non_iso); - void can_send(capnp::List::Reader can_data_list); + void can_send(const capnp::List::Reader &can_data_list); bool can_receive(std::vector& out_vec); void can_reset_communications(); @@ -88,7 +90,7 @@ class Panda { uint8_t receive_buffer[RECV_SIZE + sizeof(can_header) + 64]; uint32_t receive_buffer_size = 0; - Panda(uint32_t bus_offset) : bus_offset(bus_offset) {} + Panda() {} void pack_can_buffer(const capnp::List::Reader &can_data_list, std::function write_func); bool unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec); diff --git a/selfdrive/pandad/panda_comms.cc b/selfdrive/pandad/panda_comms.cc deleted file mode 100644 index 59908f0cde23d7..00000000000000 --- a/selfdrive/pandad/panda_comms.cc +++ /dev/null @@ -1,227 +0,0 @@ -#include "selfdrive/pandad/panda.h" - -#include -#include -#include - -#include "common/swaglog.h" - -static libusb_context *init_usb_ctx() { - libusb_context *context = nullptr; - int err = libusb_init(&context); - if (err != 0) { - LOGE("libusb initialization error"); - return nullptr; - } - -#if LIBUSB_API_VERSION >= 0x01000106 - libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); -#else - libusb_set_debug(context, 3); -#endif - return context; -} - -PandaUsbHandle::PandaUsbHandle(std::string serial) : PandaCommsHandle(serial) { - // init libusb - ssize_t num_devices; - libusb_device **dev_list = NULL; - int err = 0; - ctx = init_usb_ctx(); - if (!ctx) { goto fail; } - - // connect by serial - num_devices = libusb_get_device_list(ctx, &dev_list); - if (num_devices < 0) { goto fail; } - for (size_t i = 0; i < num_devices; ++i) { - libusb_device_descriptor desc; - libusb_get_device_descriptor(dev_list[i], &desc); - if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { - int ret = libusb_open(dev_list[i], &dev_handle); - if (dev_handle == NULL || ret < 0) { goto fail; } - - unsigned char desc_serial[26] = { 0 }; - ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); - if (ret < 0) { goto fail; } - - hw_serial = std::string((char *)desc_serial, ret); - if (serial.empty() || serial == hw_serial) { - break; - } - libusb_close(dev_handle); - dev_handle = NULL; - } - } - if (dev_handle == NULL) goto fail; - libusb_free_device_list(dev_list, 1); - dev_list = nullptr; - - if (libusb_kernel_driver_active(dev_handle, 0) == 1) { - libusb_detach_kernel_driver(dev_handle, 0); - } - - err = libusb_set_configuration(dev_handle, 1); - if (err != 0) { goto fail; } - - err = libusb_claim_interface(dev_handle, 0); - if (err != 0) { goto fail; } - - return; - -fail: - if (dev_list != NULL) { - libusb_free_device_list(dev_list, 1); - } - cleanup(); - throw std::runtime_error("Error connecting to panda"); -} - -PandaUsbHandle::~PandaUsbHandle() { - std::lock_guard lk(hw_lock); - cleanup(); - connected = false; -} - -void PandaUsbHandle::cleanup() { - if (dev_handle) { - libusb_release_interface(dev_handle, 0); - libusb_close(dev_handle); - } - - if (ctx) { - libusb_exit(ctx); - } -} - -std::vector PandaUsbHandle::list() { - static std::unique_ptr context(init_usb_ctx(), libusb_exit); - // init libusb - ssize_t num_devices; - libusb_device **dev_list = NULL; - std::vector serials; - if (!context) { return serials; } - - num_devices = libusb_get_device_list(context.get(), &dev_list); - if (num_devices < 0) { - LOGE("libusb can't get device list"); - goto finish; - } - for (size_t i = 0; i < num_devices; ++i) { - libusb_device *device = dev_list[i]; - libusb_device_descriptor desc; - libusb_get_device_descriptor(device, &desc); - if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { - libusb_device_handle *handle = NULL; - int ret = libusb_open(device, &handle); - if (ret < 0) { goto finish; } - - unsigned char desc_serial[26] = { 0 }; - ret = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); - libusb_close(handle); - if (ret < 0) { goto finish; } - - serials.push_back(std::string((char *)desc_serial, ret)); - } - } - -finish: - if (dev_list != NULL) { - libusb_free_device_list(dev_list, 1); - } - return serials; -} - -void PandaUsbHandle::handle_usb_issue(int err, const char func[]) { - LOGE_100("usb error %d \"%s\" in %s", err, libusb_strerror((enum libusb_error)err), func); - if (err == LIBUSB_ERROR_NO_DEVICE) { - LOGE("lost connection"); - connected = false; - } - // TODO: check other errors, is simply retrying okay? -} - -int PandaUsbHandle::control_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout) { - int err; - const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; - - if (!connected) { - return LIBUSB_ERROR_NO_DEVICE; - } - - std::lock_guard lk(hw_lock); - do { - err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, NULL, 0, timeout); - if (err < 0) handle_usb_issue(err, __func__); - } while (err < 0 && connected); - - return err; -} - -int PandaUsbHandle::control_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { - int err; - const uint8_t bmRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; - - if (!connected) { - return LIBUSB_ERROR_NO_DEVICE; - } - - std::lock_guard lk(hw_lock); - do { - err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); - if (err < 0) handle_usb_issue(err, __func__); - } while (err < 0 && connected); - - return err; -} - -int PandaUsbHandle::bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { - int err; - int transferred = 0; - - if (!connected) { - return 0; - } - - std::lock_guard lk(hw_lock); - do { - // Try sending can messages. If the receive buffer on the panda is full it will NAK - // and libusb will try again. After 5ms, it will time out. We will drop the messages. - err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); - - if (err == LIBUSB_ERROR_TIMEOUT) { - LOGW("Transmit buffer full"); - break; - } else if (err != 0 || length != transferred) { - handle_usb_issue(err, __func__); - } - } while (err != 0 && connected); - - return transferred; -} - -int PandaUsbHandle::bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { - int err; - int transferred = 0; - - if (!connected) { - return 0; - } - - std::lock_guard lk(hw_lock); - - do { - err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); - - if (err == LIBUSB_ERROR_TIMEOUT) { - break; // timeout is okay to exit, recv still happened - } else if (err == LIBUSB_ERROR_OVERFLOW) { - comms_healthy = false; - LOGE_100("overflow got 0x%x", transferred); - } else if (err != 0) { - handle_usb_issue(err, __func__); - } - - } while (err != 0 && connected); - - return transferred; -} diff --git a/selfdrive/pandad/panda_comms.h b/selfdrive/pandad/panda_comms.h index 9c452faf6dad13..cdfb5019b62628 100644 --- a/selfdrive/pandad/panda_comms.h +++ b/selfdrive/pandad/panda_comms.h @@ -6,67 +6,20 @@ #include #include -#ifndef __APPLE__ -#include -#endif - -#include - #define TIMEOUT 0 #define SPI_BUF_SIZE 2048 -// comms base class -class PandaCommsHandle { +class PandaSpiHandle { public: - PandaCommsHandle(std::string serial) {} - virtual ~PandaCommsHandle() {} - virtual void cleanup() = 0; - std::string hw_serial; std::atomic connected = true; std::atomic comms_healthy = true; - static std::vector list(); - - // HW communication - virtual int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT) = 0; - virtual int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT) = 0; - virtual int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT) = 0; - virtual int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT) = 0; -}; -class PandaUsbHandle : public PandaCommsHandle { -public: - PandaUsbHandle(std::string serial); - ~PandaUsbHandle(); - int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); - int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); - int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); - int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); - void cleanup(); - - static std::vector list(); - -private: - libusb_context *ctx = NULL; - libusb_device_handle *dev_handle = NULL; - std::recursive_mutex hw_lock; - void handle_usb_issue(int err, const char func[]); -}; - -#ifndef __APPLE__ -struct __attribute__((packed)) spi_header { - uint8_t sync; - uint8_t endpoint; - uint16_t tx_len; - uint16_t max_rx_len; -}; - -class PandaSpiHandle : public PandaCommsHandle { -public: PandaSpiHandle(std::string serial); ~PandaSpiHandle(); + int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); @@ -81,13 +34,19 @@ class PandaSpiHandle : public PandaCommsHandle { uint8_t rx_buf[SPI_BUF_SIZE]; inline static std::recursive_mutex hw_lock; + struct __attribute__((packed)) spi_header { + uint8_t sync; + uint8_t endpoint; + uint16_t tx_len; + uint16_t max_rx_len; + }; + int wait_for_ack(uint8_t ack, uint8_t tx, unsigned int timeout, unsigned int length); int bulk_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t rx_len, unsigned int timeout); int spi_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len, unsigned int timeout); int spi_transfer_retry(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len, unsigned int timeout); - int lltransfer(spi_ioc_transfer &t); + int lltransfer(struct spi_ioc_transfer &t); spi_header header; uint32_t xfer_count = 0; }; -#endif diff --git a/selfdrive/pandad/panda_safety.cc b/selfdrive/pandad/panda_safety.cc index 1d0f72f223444e..32d129bc2e7cf0 100644 --- a/selfdrive/pandad/panda_safety.cc +++ b/selfdrive/pandad/panda_safety.cc @@ -2,9 +2,7 @@ #include "cereal/messaging/messaging.h" #include "common/swaglog.h" -void PandaSafety::configureSafetyMode() { - bool is_onroad = params_.getBool("IsOnroad"); - +void PandaSafety::configureSafetyMode(bool is_onroad) { if (is_onroad && !safety_configured_) { updateMultiplexingMode(); @@ -17,6 +15,7 @@ void PandaSafety::configureSafetyMode() { } else if (!is_onroad) { initialized_ = false; safety_configured_ = false; + log_once_ = false; } } @@ -24,19 +23,15 @@ void PandaSafety::updateMultiplexingMode() { // Initialize to ELM327 without OBD multiplexing for initial fingerprinting if (!initialized_) { prev_obd_multiplexing_ = false; - for (int i = 0; i < pandas_.size(); ++i) { - pandas_[i]->set_safety_model(cereal::CarParams::SafetyModel::ELM327, 1U); - } + panda_->set_safety_model(cereal::CarParams::SafetyModel::ELM327, 1U); initialized_ = true; } // Switch between multiplexing modes based on the OBD multiplexing request bool obd_multiplexing_requested = params_.getBool("ObdMultiplexingEnabled"); if (obd_multiplexing_requested != prev_obd_multiplexing_) { - for (int i = 0; i < pandas_.size(); ++i) { - const uint16_t safety_param = (i > 0 || !obd_multiplexing_requested) ? 1U : 0U; - pandas_[i]->set_safety_model(cereal::CarParams::SafetyModel::ELM327, safety_param); - } + const uint16_t safety_param = obd_multiplexing_requested ? 0U : 1U; + panda_->set_safety_model(cereal::CarParams::SafetyModel::ELM327, safety_param); prev_obd_multiplexing_ = obd_multiplexing_requested; params_.putBool("ObdMultiplexingChanged", true); } @@ -46,9 +41,12 @@ std::string PandaSafety::fetchCarParams() { if (!params_.getBool("FirmwareQueryDone")) { return {}; } - LOGW("Finished FW query"); - LOGW("Waiting for params to set safety model"); + if (!log_once_) { + LOGW("Finished FW query, Waiting for params to set safety model"); + log_once_ = true; + } + if (!params_.getBool("ControlsReady")) { return {}; } @@ -63,17 +61,10 @@ void PandaSafety::setSafetyMode(const std::string ¶ms_string) { auto safety_configs = car_params.getSafetyConfigs(); uint16_t alternative_experience = car_params.getAlternativeExperience(); - for (int i = 0; i < pandas_.size(); ++i) { - // Default to SILENT safety model if not specified - cereal::CarParams::SafetyModel safety_model = cereal::CarParams::SafetyModel::SILENT; - uint16_t safety_param = 0U; - if (i < safety_configs.size()) { - safety_model = safety_configs[i].getSafetyModel(); - safety_param = safety_configs[i].getSafetyParam(); - } + cereal::CarParams::SafetyModel safety_model = safety_configs[0].getSafetyModel(); + uint16_t safety_param = safety_configs[0].getSafetyParam(); - LOGW("Panda %d: setting safety model: %d, param: %d, alternative experience: %d", i, (int)safety_model, safety_param, alternative_experience); - pandas_[i]->set_alternative_experience(alternative_experience); - pandas_[i]->set_safety_model(safety_model, safety_param); - } + LOGW("setting safety model: %d, param: %d, alternative experience: %d", (int)safety_model, safety_param, alternative_experience); + panda_->set_alternative_experience(alternative_experience); + panda_->set_safety_model(safety_model, safety_param); } diff --git a/selfdrive/pandad/pandad.cc b/selfdrive/pandad/pandad.cc index b0b10fe3159219..7c91fe361130ec 100644 --- a/selfdrive/pandad/pandad.cc +++ b/selfdrive/pandad/pandad.cc @@ -1,7 +1,7 @@ #include "selfdrive/pandad/pandad.h" -#include #include +#include #include #include #include @@ -11,52 +11,39 @@ #include "cereal/gen/cpp/car.capnp.h" #include "cereal/messaging/messaging.h" +#include "cereal/services.h" #include "common/ratekeeper.h" #include "common/swaglog.h" #include "common/timing.h" #include "common/util.h" #include "system/hardware/hw.h" -// -- Multi-panda conventions -- -// Ordering: -// - The internal panda will always be the first panda -// - Consecutive pandas will be sorted based on panda type, and then serial number -// Connecting: -// - If a panda connection is dropped, pandad will reconnect to all pandas -// - If a panda is added, we will only reconnect when we are offroad -// CAN buses: -// - Each panda will have it's block of 4 buses. E.g.: the second panda will use -// bus numbers 4, 5, 6 and 7 -// - The internal panda will always be used for accessing the OBD2 port, -// and thus firmware queries -// Safety: -// - SafetyConfig is a list, which is mapped to the connected pandas -// - If there are more pandas connected than there are SafetyConfigs, -// the excess pandas will remain in "silent" or "noOutput" mode -// Ignition: -// - If any of the ignition sources in any panda is high, ignition is high - -#define MAX_IR_POWER 0.5f -#define MIN_IR_POWER 0.0f +#define MAX_IR_PANDA_VAL 50 #define CUTOFF_IL 400 #define SATURATE_IL 1000 ExitHandler do_exit; -bool check_all_connected(const std::vector &pandas) { - for (const auto& panda : pandas) { - if (!panda->connected()) { - do_exit = true; - return false; - } +struct HwmonState { + std::atomic voltage{0}; + std::atomic current{0}; + std::atomic initialized{false}; +}; + +HwmonState hwmon_state; + +bool check_connected(Panda *panda) { + if (!panda->connected()) { + do_exit = true; + return false; } return true; } -Panda *connect(std::string serial="", uint32_t index=0) { +Panda *connect(std::string serial) { std::unique_ptr panda; try { - panda = std::make_unique(serial, (index * PANDA_BUS_OFFSET)); + panda = std::make_unique(serial); } catch (std::exception &e) { return nullptr; } @@ -67,6 +54,10 @@ Panda *connect(std::string serial="", uint32_t index=0) { } //panda->enable_deepsleep(); + for (int i = 0; i < PANDA_CAN_CNT; i++) { + panda->set_can_fd_auto(i, true); + } + if (!panda->up_to_date() && !getenv("BOARDD_SKIP_FW_CHECK")) { throw std::runtime_error("Panda firmware out of date. Run pandad.py to update."); } @@ -74,22 +65,19 @@ Panda *connect(std::string serial="", uint32_t index=0) { return panda.release(); } -void can_send_thread(std::vector pandas, bool fake_send) { +void can_send_thread(Panda *panda, bool fake_send) { util::set_thread_name("pandad_can_send"); AlignedBuffer aligned_buf; std::unique_ptr context(Context::create()); - std::unique_ptr subscriber(SubSocket::create(context.get(), "sendcan")); + std::unique_ptr subscriber(SubSocket::create(context.get(), "sendcan", "127.0.0.1", false, true, services.at("sendcan").queue_size)); assert(subscriber != NULL); subscriber->setTimeout(100); // run as fast as messages come in - while (!do_exit && check_all_connected(pandas)) { + while (!do_exit && check_connected(panda)) { std::unique_ptr msg(subscriber->receive()); if (!msg) { - if (errno == EINTR) { - do_exit = true; - } continue; } @@ -98,25 +86,20 @@ void can_send_thread(std::vector pandas, bool fake_send) { // Don't send if older than 1 second if ((nanos_since_boot() - event.getLogMonoTime() < 1e9) && !fake_send) { - for (const auto& panda : pandas) { - LOGT("sending sendcan to panda: %s", (panda->hw_serial()).c_str()); - panda->can_send(event.getSendcan()); - LOGT("sendcan sent to panda: %s", (panda->hw_serial()).c_str()); - } + LOGT("sending sendcan to panda: %s", (panda->hw_serial()).c_str()); + panda->can_send(event.getSendcan()); + LOGT("sendcan sent to panda: %s", (panda->hw_serial()).c_str()); } else { LOGE("sendcan too old to send: %" PRIu64 ", %" PRIu64, nanos_since_boot(), event.getLogMonoTime()); } } } -void can_recv(std::vector &pandas, PubMaster *pm) { +void can_recv(Panda *panda, PubMaster *pm) { static std::vector raw_can_data; { - bool comms_healthy = true; raw_can_data.clear(); - for (const auto& panda : pandas) { - comms_healthy &= panda->can_receive(raw_can_data); - } + bool comms_healthy = panda->can_receive(raw_can_data); MessageBuilder msg; auto evt = msg.initEvent(); @@ -131,6 +114,26 @@ void can_recv(std::vector &pandas, PubMaster *pm) { } } +void hwmon_thread() { + util::set_thread_name("pandad_hwmon"); + + while (!do_exit) { + double read_time = millis_since_boot(); + uint32_t voltage = Hardware::get_voltage(); + uint32_t current = Hardware::get_current(); + read_time = millis_since_boot() - read_time; + if (read_time > 50) { + LOGW("reading hwmon took %lfms", read_time); + } + + hwmon_state.voltage.store(voltage); + hwmon_state.current.store(current); + hwmon_state.initialized.store(true); + + util::sleep_for(500); + } +} + void fill_panda_state(cereal::PandaState::Builder &ps, cereal::PandaState::PandaType hw_type, const health_t &health) { ps.setVoltage(health.voltage_pkt); ps.setCurrent(health.current_pkt); @@ -152,11 +155,11 @@ void fill_panda_state(cereal::PandaState::Builder &ps, cereal::PandaState::Panda ps.setHarnessStatus(cereal::PandaState::HarnessStatus(health.car_harness_status_pkt)); ps.setInterruptLoad(health.interrupt_load_pkt); ps.setFanPower(health.fan_power); - ps.setFanStallCount(health.fan_stall_count); ps.setSafetyRxChecksInvalid((bool)(health.safety_rx_checks_invalid_pkt)); - ps.setSpiChecksumErrorCount(health.spi_checksum_error_count_pkt); + ps.setSpiErrorCount(health.spi_error_count_pkt); ps.setSbu1Voltage(health.sbu1_voltage_mV / 1000.0f); ps.setSbu2Voltage(health.sbu2_voltage_mV / 1000.0f); + ps.setSoundOutputLevel(health.sound_output_level_pkt); } void fill_panda_can_state(cereal::PandaState::PandaCanState::Builder &cs, const can_health_t &can_health) { @@ -187,101 +190,72 @@ void fill_panda_can_state(cereal::PandaState::PandaCanState::Builder &cs, const cs.setCanCoreResetCnt(can_health.can_core_reset_cnt); } -std::optional send_panda_states(PubMaster *pm, const std::vector &pandas, bool spoofing_started) { - bool ignition_local = false; - const uint32_t pandas_cnt = pandas.size(); - +std::optional send_panda_states(PubMaster *pm, Panda *panda, bool is_onroad, bool spoofing_started) { // build msg MessageBuilder msg; auto evt = msg.initEvent(); - auto pss = evt.initPandaStates(pandas_cnt); + auto pss = evt.initPandaStates(1); - std::vector pandaStates; - pandaStates.reserve(pandas_cnt); - - std::vector> pandaCanStates; - pandaCanStates.reserve(pandas_cnt); + auto health_opt = panda->get_state(); + if (!health_opt) { + return std::nullopt; + } - const bool red_panda_comma_three = (pandas.size() == 2) && - (pandas[0]->hw_type == cereal::PandaState::PandaType::DOS) && - (pandas[1]->hw_type == cereal::PandaState::PandaType::RED_PANDA); + health_t health = *health_opt; - for (const auto& panda : pandas){ - auto health_opt = panda->get_state(); - if (!health_opt) { + std::array can_health{}; + for (uint32_t i = 0; i < PANDA_CAN_CNT; i++) { + auto can_health_opt = panda->get_can_state(i); + if (!can_health_opt) { return std::nullopt; } + can_health[i] = *can_health_opt; + } - health_t health = *health_opt; - - std::array can_health{}; - for (uint32_t i = 0; i < PANDA_CAN_CNT; i++) { - auto can_health_opt = panda->get_can_state(i); - if (!can_health_opt) { - return std::nullopt; - } - can_health[i] = *can_health_opt; - } - pandaCanStates.push_back(can_health); - - if (spoofing_started) { - health.ignition_line_pkt = 1; - } - - // on comma three setups with a red panda, the dos can - // get false positive ignitions due to the harness box - // without a harness connector, so ignore it - if (red_panda_comma_three && (panda->hw_type == cereal::PandaState::PandaType::DOS)) { - health.ignition_line_pkt = 0; - } - - ignition_local |= ((health.ignition_line_pkt != 0) || (health.ignition_can_pkt != 0)); - - pandaStates.push_back(health); + if (spoofing_started) { + health.ignition_line_pkt = 1; } - for (uint32_t i = 0; i < pandas_cnt; i++) { - auto panda = pandas[i]; - const auto &health = pandaStates[i]; + bool ignition_local = ((health.ignition_line_pkt != 0) || (health.ignition_can_pkt != 0)); - // Make sure CAN buses are live: safety_setter_thread does not work if Panda CAN are silent and there is only one other CAN node - if (health.safety_mode_pkt == (uint8_t)(cereal::CarParams::SafetyModel::SILENT)) { - panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); - } + // Make sure CAN buses are live: safety_setter_thread does not work if Panda CAN are silent and there is only one other CAN node + if (health.safety_mode_pkt == (uint8_t)(cereal::CarParams::SafetyModel::SILENT)) { + panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); + } - bool power_save_desired = !ignition_local; - if (health.power_save_enabled_pkt != power_save_desired) { - panda->set_power_saving(power_save_desired); - } + bool power_save_desired = !ignition_local; + if (health.power_save_enabled_pkt != power_save_desired) { + panda->set_power_saving(power_save_desired); + } - // set safety mode to NO_OUTPUT when car is off. ELM327 is an alternative if we want to leverage athenad/connect - if (!ignition_local && (health.safety_mode_pkt != (uint8_t)(cereal::CarParams::SafetyModel::NO_OUTPUT))) { - panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); - } + // set safety mode to NO_OUTPUT when car is off or we're not onroad. ELM327 is an alternative if we want to leverage athenad/connect + bool should_close_relay = !ignition_local || !is_onroad; + if (should_close_relay && (health.safety_mode_pkt != (uint8_t)(cereal::CarParams::SafetyModel::NO_OUTPUT))) { + panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); + } - if (!panda->comms_healthy()) { - evt.setValid(false); - } + if (!panda->comms_healthy()) { + evt.setValid(false); + } - auto ps = pss[i]; - fill_panda_state(ps, panda->hw_type, health); + auto ps = pss[0]; + fill_panda_state(ps, panda->hw_type, health); - auto cs = std::array{ps.initCanState0(), ps.initCanState1(), ps.initCanState2()}; - for (uint32_t j = 0; j < PANDA_CAN_CNT; j++) { - fill_panda_can_state(cs[j], pandaCanStates[i][j]); - } + auto cs = std::array{ps.initCanState0(), ps.initCanState1(), ps.initCanState2()}; + for (uint32_t j = 0; j < PANDA_CAN_CNT; j++) { + fill_panda_can_state(cs[j], can_health[j]); + } - // Convert faults bitset to capnp list - std::bitset fault_bits(health.faults_pkt); - auto faults = ps.initFaults(fault_bits.count()); + // Convert faults bitset to capnp list + std::bitset fault_bits(health.faults_pkt); + auto faults = ps.initFaults(fault_bits.count()); - size_t j = 0; - for (size_t f = size_t(cereal::PandaState::FaultType::RELAY_MALFUNCTION); - f <= size_t(cereal::PandaState::FaultType::HEARTBEAT_LOOP_WATCHDOG); f++) { - if (fault_bits.test(f)) { - faults.set(j, cereal::PandaState::FaultType(f)); - j++; - } + size_t j = 0; + for (size_t f = size_t(cereal::PandaState::FaultType::RELAY_MALFUNCTION); + f <= size_t(cereal::PandaState::FaultType::HEARTBEAT_LOOP_WATCHDOG); f++) { + if (fault_bits.test(f)) { + faults.set(j, cereal::PandaState::FaultType(f)); + j++; } } @@ -290,6 +264,10 @@ std::optional send_panda_states(PubMaster *pm, const std::vector } void send_peripheral_state(Panda *panda, PubMaster *pm) { + if (!hwmon_state.initialized.load()) { + return; + } + // build msg MessageBuilder msg; auto evt = msg.initEvent(); @@ -298,12 +276,17 @@ void send_peripheral_state(Panda *panda, PubMaster *pm) { auto ps = evt.initPeripheralState(); ps.setPandaType(panda->hw_type); - double read_time = millis_since_boot(); - ps.setVoltage(Hardware::get_voltage()); - ps.setCurrent(Hardware::get_current()); - read_time = millis_since_boot() - read_time; - if (read_time > 50) { - LOGW("reading hwmon took %lfms", read_time); + ps.setVoltage(hwmon_state.voltage.load()); + ps.setCurrent(hwmon_state.current.load()); + + // fall back to panda's voltage and current measurement + if (ps.getVoltage() == 0 && ps.getCurrent() == 0) { + auto health_opt = panda->get_state(); + if (health_opt) { + health_t health = *health_opt; + ps.setVoltage(health.voltage_pkt); + ps.setCurrent(health.current_pkt); + } } uint16_t fan_speed_rpm = panda->get_fan_speed(); @@ -312,61 +295,40 @@ void send_peripheral_state(Panda *panda, PubMaster *pm) { pm->send("peripheralState", msg); } -void process_panda_state(std::vector &pandas, PubMaster *pm, bool spoofing_started) { - static SubMaster sm({"selfdriveState"}); - - std::vector connected_serials; - for (Panda *p : pandas) { - connected_serials.push_back(p->hw_serial()); +void process_panda_state(Panda *panda, PubMaster *pm, bool engaged, bool is_onroad, bool spoofing_started) { + auto ignition_opt = send_panda_states(pm, panda, is_onroad, spoofing_started); + if (!ignition_opt) { + LOGE("Failed to get ignition_opt"); + return; } - { - auto ignition_opt = send_panda_states(pm, pandas, spoofing_started); - if (!ignition_opt) { - LOGE("Failed to get ignition_opt"); - return; - } - - // check if we should have pandad reconnect - if (!ignition_opt.value()) { - bool comms_healthy = true; - for (const auto &panda : pandas) { - comms_healthy &= panda->comms_healthy(); - } - - if (!comms_healthy) { - LOGE("Reconnecting, communication to pandas not healthy"); - do_exit = true; - - } else { - // check for new pandas - for (std::string &s : Panda::list(true)) { - if (!std::count(connected_serials.begin(), connected_serials.end(), s)) { - LOGW("Reconnecting to new panda: %s", s.c_str()); - do_exit = true; - break; - } - } - } - } - - sm.update(0); - const bool engaged = sm.allAliveAndValid({"selfdriveState"}) && sm["selfdriveState"].getSelfdriveState().getEnabled(); - for (const auto &panda : pandas) { - panda->send_heartbeat(engaged); + // check if we should have pandad reconnect + if (!ignition_opt.value()) { + if (!panda->comms_healthy()) { + LOGE("Reconnecting, communication to panda not healthy"); + do_exit = true; } } + + panda->send_heartbeat(engaged); } -void process_peripheral_state(Panda *panda, PubMaster *pm, bool no_fan_control) { +void process_peripheral_state(Panda *panda, PubMaster *pm, bool no_fan_control, bool is_onroad) { + static Params params; static SubMaster sm({"deviceState", "driverCameraState"}); static uint64_t last_driver_camera_t = 0; static uint16_t prev_fan_speed = 999; - static uint16_t ir_pwr = 0; - static uint16_t prev_ir_pwr = 999; - + static int ir_pwr = 0; + static int prev_ir_pwr = 999; + static uint32_t prev_frame_id = UINT32_MAX; + static bool driver_view = false; + static bool not_car = false; + static bool not_car_checked = false; + + // TODO: can we merge these? static FirstOrderFilter integ_lines_filter(0, 30.0, 0.05); + static FirstOrderFilter integ_lines_filter_driver_view(0, 5.0, 0.05); { sm.update(0); @@ -383,15 +345,23 @@ void process_peripheral_state(Panda *panda, PubMaster *pm, bool no_fan_control) auto event = sm["driverCameraState"]; int cur_integ_lines = event.getDriverCameraState().getIntegLines(); - cur_integ_lines = integ_lines_filter.update(cur_integ_lines); + // reset the filter when camerad restarts + if (event.getDriverCameraState().getFrameId() < prev_frame_id) { + integ_lines_filter.reset(0); + integ_lines_filter_driver_view.reset(0); + driver_view = params.getBool("IsDriverViewEnabled"); + } + prev_frame_id = event.getDriverCameraState().getFrameId(); + + cur_integ_lines = (driver_view ? integ_lines_filter_driver_view : integ_lines_filter).update(cur_integ_lines); last_driver_camera_t = event.getLogMonoTime(); if (cur_integ_lines <= CUTOFF_IL) { - ir_pwr = 100.0 * MIN_IR_POWER; + ir_pwr = 0; } else if (cur_integ_lines > SATURATE_IL) { - ir_pwr = 100.0 * MAX_IR_POWER; + ir_pwr = 100; } else { - ir_pwr = 100.0 * (MIN_IR_POWER + ((cur_integ_lines - CUTOFF_IL) * (MAX_IR_POWER - MIN_IR_POWER) / (SATURATE_IL - CUTOFF_IL))); + ir_pwr = 100 * (cur_integ_lines - CUTOFF_IL) / (SATURATE_IL - CUTOFF_IL); } } @@ -400,88 +370,120 @@ void process_peripheral_state(Panda *panda, PubMaster *pm, bool no_fan_control) ir_pwr = 0; } - if (ir_pwr != prev_ir_pwr || sm.frame % 100 == 0 || ir_pwr >= 50.0) { - panda->set_ir_pwr(ir_pwr); + // turn off IR leds if body + if (!not_car_checked && is_onroad) { + std::string cp_bytes = params.get("CarParams"); + if (cp_bytes.size() > 0) { + AlignedBuffer aligned_buf; + capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); + cereal::CarParams::Reader CP = cmsg.getRoot(); + not_car = CP.getNotCar(); + not_car_checked = true; + } + } + if (not_car) { + ir_pwr = 0; + } + + if (ir_pwr != prev_ir_pwr || sm.frame % 100 == 0) { + int16_t ir_panda = util::map_val(ir_pwr, 0, 100, 0, MAX_IR_PANDA_VAL); + panda->set_ir_pwr(ir_panda); + Hardware::set_ir_power(ir_pwr); prev_ir_pwr = ir_pwr; } } } -void pandad_run(std::vector &pandas) { +void pandad_run(Panda *panda) { const bool no_fan_control = getenv("NO_FAN_CONTROL") != nullptr; const bool spoofing_started = getenv("STARTED") != nullptr; const bool fake_send = getenv("FAKESEND") != nullptr; - // Start the CAN send thread - std::thread send_thread(can_send_thread, pandas, fake_send); + // Start helper threads for event-driven sendcan and slow non-Panda reads. + std::thread send_thread(can_send_thread, panda, fake_send); + std::thread hardware_thread(hwmon_thread); RateKeeper rk("pandad", 100); + SubMaster sm({"selfdriveState", "deviceState"}); PubMaster pm({"can", "pandaStates", "peripheralState"}); - PandaSafety panda_safety(pandas); - Panda *peripheral_panda = pandas[0]; + PandaSafety panda_safety(panda); + bool engaged = false; + bool is_onroad = false; - // Main loop: receive CAN data and process states - while (!do_exit && check_all_connected(pandas)) { - can_recv(pandas, &pm); + // Main loop: receive CAN first, then process lower priority panda and peripheral state. + while (!do_exit && check_connected(panda)) { + can_recv(panda, &pm); // Process peripheral state at 20 Hz if (rk.frame() % 5 == 0) { - process_peripheral_state(peripheral_panda, &pm, no_fan_control); + process_peripheral_state(panda, &pm, no_fan_control, is_onroad); } // Process panda state at 10 Hz if (rk.frame() % 10 == 0) { - process_panda_state(pandas, &pm, spoofing_started); - panda_safety.configureSafetyMode(); + sm.update(0); + engaged = sm.allAliveAndValid({"selfdriveState"}) && sm["selfdriveState"].getSelfdriveState().getEnabled(); + if (sm.updated("deviceState")) { + is_onroad = sm["deviceState"].getDeviceState().getStarted(); + } + process_panda_state(panda, &pm, engaged, is_onroad, spoofing_started); + panda_safety.configureSafetyMode(is_onroad); } // Send out peripheralState at 2Hz if (rk.frame() % 50 == 0) { - send_peripheral_state(peripheral_panda, &pm); + send_peripheral_state(panda, &pm); + } + + // Forward logs from panda to cloudlog if available + std::string log = panda->serial_read(); + if (!log.empty()) { + if (log.find("Register 0x") != std::string::npos) { + // Log register divergent faults as errors + LOGE("%s", log.c_str()); + } else { + LOGD("%s", log.c_str()); + } } rk.keepTime(); } + // Close relay on exit to prevent a fault + if (is_onroad && !engaged) { + if (panda->connected()) { + panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); + } + } + send_thread.join(); + hardware_thread.join(); } -void pandad_main_thread(std::vector serials) { - if (serials.size() == 0) { - serials = Panda::list(); +void pandad_main_thread(std::string serial) { + if (serial.empty()) { + auto serials = Panda::list(); - if (serials.size() == 0) { + if (serials.empty()) { LOGW("no pandas found, exiting"); return; } + serial = serials[0]; } - std::string serials_str; - for (int i = 0; i < serials.size(); i++) { - serials_str += serials[i]; - if (i < serials.size() - 1) serials_str += ", "; - } - LOGW("connecting to pandas: %s", serials_str.c_str()); - - // connect to all provided serials - std::vector pandas; - for (int i = 0; i < serials.size() && !do_exit; /**/) { - Panda *p = connect(serials[i], i); - if (!p) { - util::sleep_for(100); - continue; - } + LOGW("connecting to panda: %s", serial.c_str()); - pandas.push_back(p); - ++i; + Panda *panda = nullptr; + while (!do_exit) { + panda = connect(serial); + if (panda) break; + util::sleep_for(100); } if (!do_exit) { - LOGW("connected to all pandas"); - pandad_run(pandas); + LOGW("connected to panda"); + pandad_run(panda); } - for (Panda *panda : pandas) { - delete panda; - } + delete panda; } diff --git a/selfdrive/pandad/pandad.h b/selfdrive/pandad/pandad.h index 14d97551f4ee88..aa10d1ae4b1e68 100644 --- a/selfdrive/pandad/pandad.h +++ b/selfdrive/pandad/pandad.h @@ -1,17 +1,16 @@ #pragma once #include -#include #include "common/params.h" #include "selfdrive/pandad/panda.h" -void pandad_main_thread(std::vector serials); +void pandad_main_thread(std::string serial); class PandaSafety { public: - PandaSafety(const std::vector &pandas) : pandas_(pandas) {} - void configureSafetyMode(); + PandaSafety(Panda *panda) : panda_(panda) {} + void configureSafetyMode(bool is_onroad); private: void updateMultiplexingMode(); @@ -19,8 +18,9 @@ class PandaSafety { void setSafetyMode(const std::string ¶ms_string); bool initialized_ = false; + bool log_once_ = false; bool safety_configured_ = false; bool prev_obd_multiplexing_ = false; - std::vector pandas_; + Panda *panda_; Params params_; }; diff --git a/selfdrive/pandad/pandad.py b/selfdrive/pandad/pandad.py index 12accdbf5e3362..19b9bf119bdbdc 100755 --- a/selfdrive/pandad/pandad.py +++ b/selfdrive/pandad/pandad.py @@ -3,33 +3,33 @@ import os import usb1 import time +import signal import subprocess -from typing import NoReturn -from panda import Panda, PandaDFU, PandaProtocolMismatch, FW_PATH +from panda import Panda, PandaDFU, PandaProtocolMismatch, McuType, FW_PATH from openpilot.common.basedir import BASEDIR from openpilot.common.params import Params from openpilot.system.hardware import HARDWARE from openpilot.common.swaglog import cloudlog -def get_expected_signature(panda: Panda) -> bytes: - try: - fn = os.path.join(FW_PATH, panda.get_mcu_type().config.app_fn) - return Panda.get_signature_from_firmware(fn) - except Exception: - cloudlog.exception("Error computing expected signature") - return b"" +def get_expected_signature() -> bytes: + fn = os.path.join(FW_PATH, McuType.H7.config.app_fn) + return Panda.get_signature_from_firmware(fn) -def flash_panda(panda_serial: str) -> Panda: - try: - panda = Panda(panda_serial) - except PandaProtocolMismatch: - cloudlog.warning("detected protocol mismatch, reflashing panda") - HARDWARE.recover_internal_panda() - raise - fw_signature = get_expected_signature(panda) +def check_panda_support(panda) -> bool: + return panda.get_type() in Panda.SUPPORTED_DEVICES + + +def flash_panda(panda_serial: str): + panda = Panda(panda_serial) + if not check_panda_support(panda): + cloudlog.warning(f"Panda {panda_serial} is not supported (hw_type: {panda.get_type()}), skipping flash...") + panda.close() + return + + fw_signature = get_expected_signature() internal_panda = panda.is_internal() panda_version = "bootstub" if panda.bootstub else panda.get_version() @@ -58,109 +58,70 @@ def flash_panda(panda_serial: str) -> Panda: cloudlog.info("Version mismatch after flashing, exiting") raise AssertionError - return panda + panda.close() -def main() -> NoReturn: - count = 0 - first_run = True - params = Params() - no_internal_panda_count = 0 +def main() -> None: + # signal pandad to close the relay and exit + def signal_handler(signum, frame): + cloudlog.info(f"Caught signal {signum}, exiting") + nonlocal do_exit + do_exit = True + if process is not None: + process.send_signal(signal.SIGINT) + + process = None + do_exit = False + signal.signal(signal.SIGINT, signal_handler) - while True: + # check health for lost heartbeat + try: + for s in Panda.list(): + with Panda(s) as p: + if not check_panda_support(p): + continue + health = p.health() + if p.is_internal() and health["heartbeat_lost"]: + Params().put_bool("PandaHeartbeatLost", True, block=True) + cloudlog.event("heartbeat lost", deviceState=health) + except Exception: + cloudlog.exception("pandad.uncaught_exception") + + count = 0 + while not do_exit: try: - count += 1 cloudlog.event("pandad.flash_and_connect", count=count) - params.remove("PandaSignatures") - - # TODO: remove this in the next AGNOS - # wait until USB is up before counting - if time.monotonic() < 25.: - no_internal_panda_count = 0 - - # Handle missing internal panda - if no_internal_panda_count > 0: - if no_internal_panda_count == 3: - cloudlog.info("No pandas found, putting internal panda into DFU") - HARDWARE.recover_internal_panda() - else: - cloudlog.info("No pandas found, resetting internal panda") - HARDWARE.reset_internal_panda() - time.sleep(3) # wait to come back up + if (count % 2) == 0: + HARDWARE.reset_internal_panda() + else: + HARDWARE.recover_internal_panda() + count += 1 # Flash all Pandas in DFU mode - dfu_serials = PandaDFU.list() - if len(dfu_serials) > 0: - for serial in dfu_serials: - cloudlog.info(f"Panda in DFU mode found, flashing recovery {serial}") - PandaDFU(serial).recover() + for serial in PandaDFU.list(): + cloudlog.info(f"Panda in DFU mode found, flashing recovery {serial}") + PandaDFU(serial).recover() time.sleep(1) panda_serials = Panda.list() - if len(panda_serials) == 0: - no_internal_panda_count += 1 - continue - - cloudlog.info(f"{len(panda_serials)} panda(s) found, connecting - {panda_serials}") - - # Flash pandas - pandas: list[Panda] = [] - for serial in panda_serials: - pandas.append(flash_panda(serial)) - - # Ensure internal panda is present if expected - internal_pandas = [panda for panda in pandas if panda.is_internal()] - if HARDWARE.has_internal_panda() and len(internal_pandas) == 0: - cloudlog.error("Internal panda is missing, trying again") - no_internal_panda_count += 1 - continue - no_internal_panda_count = 0 - - # sort pandas to have deterministic order - # * the internal one is always first - # * then sort by hardware type - # * as a last resort, sort by serial number - pandas.sort(key=lambda x: (not x.is_internal(), x.get_type(), x.get_usb_serial())) - panda_serials = [p.get_usb_serial() for p in pandas] - - # log panda fw versions - params.put("PandaSignatures", b','.join(p.get_signature() for p in pandas)) - - for panda in pandas: - # check health for lost heartbeat - health = panda.health() - if health["heartbeat_lost"]: - params.put_bool("PandaHeartbeatLost", True) - cloudlog.event("heartbeat lost", deviceState=health, serial=panda.get_usb_serial()) - if health["som_reset_triggered"]: - params.put_bool("PandaSomResetTriggered", True) - cloudlog.event("panda.som_reset_triggered", health=health, serial=panda.get_usb_serial()) - - if first_run: - # reset panda to ensure we're in a good state - cloudlog.info(f"Resetting panda {panda.get_usb_serial()}") - panda.reset(reconnect=True) - - for p in pandas: - p.close() + if len(panda_serials): + assert len(panda_serials) == 1 + cloudlog.info(f"{len(panda_serials)} panda found, connecting - {panda_serials}") + flash_panda(panda_serials[0]) + + # run real pandad + os.environ['MANAGER_DAEMON'] = 'pandad' + process = subprocess.Popen(["./pandad"], cwd=os.path.join(BASEDIR, "selfdrive/pandad")) + process.wait() # TODO: wrap all panda exceptions in a base panda exception except (usb1.USBErrorNoDevice, usb1.USBErrorPipe): # a panda was disconnected while setting everything up. let's try again cloudlog.exception("Panda USB exception while setting up") - continue except PandaProtocolMismatch: cloudlog.exception("pandad.protocol_mismatch") - continue except Exception: cloudlog.exception("pandad.uncaught_exception") - continue - - first_run = False - # run pandad with all connected serials as arguments - os.environ['MANAGER_DAEMON'] = 'pandad' - os.chdir(os.path.join(BASEDIR, "selfdrive/pandad")) - subprocess.run(["./pandad", *panda_serials], check=True) if __name__ == "__main__": main() diff --git a/selfdrive/pandad/pandad_api_impl.py b/selfdrive/pandad/pandad_api_impl.py new file mode 100644 index 00000000000000..75a7ba484e15f0 --- /dev/null +++ b/selfdrive/pandad/pandad_api_impl.py @@ -0,0 +1,88 @@ +import time +from cereal import log + +NO_TRAVERSAL_LIMIT = 2**64 - 1 + +# Cache schema fields for faster access (avoids string lookup on each field access) +_cached_reader_fields = None # (address_field, dat_field, src_field) for reading +_cached_writer_fields = None # (address_field, dat_field, src_field) for writing + + +def _get_reader_fields(schema): + """Get cached schema field objects for reading.""" + global _cached_reader_fields + if _cached_reader_fields is None: + fields = schema.fields + _cached_reader_fields = (fields['address'], fields['dat'], fields['src']) + return _cached_reader_fields + + +def _get_writer_fields(schema): + """Get cached schema field objects for writing.""" + global _cached_writer_fields + if _cached_writer_fields is None: + fields = schema.fields + _cached_writer_fields = (fields['address'], fields['dat'], fields['src']) + return _cached_writer_fields + + +def can_list_to_can_capnp(can_msgs, msgtype='can', valid=True): + """Convert list of CAN messages to Cap'n Proto serialized bytes. + + Args: + can_msgs: List of tuples [(address, data_bytes, src), ...] + msgtype: 'can' or 'sendcan' + valid: Whether the event is valid + + Returns: + Cap'n Proto serialized bytes + """ + global _cached_writer_fields + + dat = log.Event.new_message(valid=valid, logMonoTime=int(time.monotonic() * 1e9)) + can_data = dat.init(msgtype, len(can_msgs)) + + # Cache schema fields on first call + if _cached_writer_fields is None and len(can_msgs) > 0: + _cached_writer_fields = _get_writer_fields(can_data[0].schema) + + if _cached_writer_fields is not None: + addr_f, dat_f, src_f = _cached_writer_fields + for i, msg in enumerate(can_msgs): + f = can_data[i] + f._set_by_field(addr_f, msg[0]) + f._set_by_field(dat_f, msg[1]) + f._set_by_field(src_f, msg[2]) + + return dat.to_bytes() + + +def can_capnp_to_list(strings, msgtype='can'): + """Convert Cap'n Proto serialized bytes to list of CAN messages. + + Args: + strings: Tuple/list of serialized Cap'n Proto bytes + msgtype: 'can' or 'sendcan' + + Returns: + List of tuples [(nanos, [(address, data, src), ...]), ...] + """ + global _cached_reader_fields + result = [] + + for s in strings: + with log.Event.from_bytes(s, traversal_limit_in_words=NO_TRAVERSAL_LIMIT) as event: + frames = getattr(event, msgtype) + + # Cache schema fields on first frame for faster access + if _cached_reader_fields is None and len(frames) > 0: + _cached_reader_fields = _get_reader_fields(frames[0].schema) + + if _cached_reader_fields is not None: + addr_f, dat_f, src_f = _cached_reader_fields + frame_list = [(f._get_by_field(addr_f), f._get_by_field(dat_f), f._get_by_field(src_f)) for f in frames] + else: + frame_list = [] + + result.append((event.logMonoTime, frame_list)) + return result diff --git a/selfdrive/pandad/pandad_api_impl.pyx b/selfdrive/pandad/pandad_api_impl.pyx deleted file mode 100644 index 787968f53e7db3..00000000000000 --- a/selfdrive/pandad/pandad_api_impl.pyx +++ /dev/null @@ -1,56 +0,0 @@ -# distutils: language = c++ -# cython: language_level=3 -from cython.operator cimport dereference as deref, preincrement as preinc -from libcpp.vector cimport vector -from libcpp.string cimport string -from libcpp cimport bool -from libc.stdint cimport uint8_t, uint32_t, uint64_t - -cdef extern from "panda.h": - cdef struct can_frame: - long address - string dat - long src - -cdef extern from "opendbc/can/common.h": - cdef struct CanFrame: - long src - uint32_t address - vector[uint8_t] dat - - cdef struct CanData: - uint64_t nanos - vector[CanFrame] frames - -cdef extern from "can_list_to_can_capnp.cc": - void can_list_to_can_capnp_cpp(const vector[can_frame] &can_list, string &out, bool sendcan, bool valid) - void can_capnp_to_can_list_cpp(const vector[string] &strings, vector[CanData] &can_data, bool sendcan) - -def can_list_to_can_capnp(can_msgs, msgtype='can', valid=True): - cdef can_frame *f - cdef vector[can_frame] can_list - - can_list.reserve(len(can_msgs)) - for can_msg in can_msgs: - f = &(can_list.emplace_back()) - f.address = can_msg[0] - f.dat = can_msg[1] - f.src = can_msg[2] - - cdef string out - can_list_to_can_capnp_cpp(can_list, out, msgtype == 'sendcan', valid) - return out - -def can_capnp_to_list(strings, msgtype='can'): - cdef vector[CanData] data - can_capnp_to_can_list_cpp(strings, data, msgtype == 'sendcan') - - result = [] - cdef CanData *d - cdef vector[CanData].iterator it = data.begin() - while it != data.end(): - d = &deref(it) - frames = [(f.address, (&f.dat[0])[:f.dat.size()], f.src) for f in d.frames] - result.append((d.nanos, frames)) - preinc(it) - return result diff --git a/selfdrive/pandad/spi.cc b/selfdrive/pandad/spi.cc index 8f1e29689b6c18..f54c26e5069c27 100644 --- a/selfdrive/pandad/spi.cc +++ b/selfdrive/pandad/spi.cc @@ -1,4 +1,3 @@ -#ifndef __APPLE__ #include #include #include @@ -33,7 +32,7 @@ const std::string SPI_DEVICE = "/dev/spidev0.0"; class LockEx { public: - LockEx(int fd, std::recursive_mutex &m) : fd(fd), m(m) { + LockEx(int fd_, std::recursive_mutex &m_) : fd(fd_), m(m_) { m.lock(); flock(fd, LOCK_EX); } @@ -55,7 +54,7 @@ class LockEx { util::hexdump(tx_buf, std::min((int)header.tx_len, 8)).c_str()); \ } while (0) -PandaSpiHandle::PandaSpiHandle(std::string serial) : PandaCommsHandle(serial) { +PandaSpiHandle::PandaSpiHandle(std::string serial) { int ret; const int uid_len = 12; uint8_t uid[uid_len] = {0}; @@ -66,58 +65,44 @@ PandaSpiHandle::PandaSpiHandle(std::string serial) : PandaCommsHandle(serial) { // 50MHz is the max of the 845. note that some older // revs of the comma three may not support this speed uint32_t spi_speed = 50000000; + try { + if (!util::file_exists(SPI_DEVICE)) { + throw std::runtime_error("Error connecting to panda: SPI device not found"); + } - if (!util::file_exists(SPI_DEVICE)) { - goto fail; - } - - spi_fd = open(SPI_DEVICE.c_str(), O_RDWR); - if (spi_fd < 0) { - LOGE("failed opening SPI device %d", spi_fd); - goto fail; - } - - // SPI settings - ret = util::safe_ioctl(spi_fd, SPI_IOC_WR_MODE, &spi_mode); - if (ret < 0) { - LOGE("failed setting SPI mode %d", ret); - goto fail; - } - - ret = util::safe_ioctl(spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed); - if (ret < 0) { - LOGE("failed setting SPI speed"); - goto fail; - } + spi_fd = open(SPI_DEVICE.c_str(), O_RDWR); + if (spi_fd < 0) { + LOGE("failed opening SPI device %d", spi_fd); + throw std::runtime_error("Error connecting to panda: failed to open SPI device"); + } - ret = util::safe_ioctl(spi_fd, SPI_IOC_WR_BITS_PER_WORD, &spi_bits_per_word); - if (ret < 0) { - LOGE("failed setting SPI bits per word"); - goto fail; - } + // SPI settings + util::safe_ioctl(spi_fd, SPI_IOC_WR_MODE, &spi_mode, "failed setting SPI mode"); + util::safe_ioctl(spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed, "failed setting SPI speed"); + util::safe_ioctl(spi_fd, SPI_IOC_WR_BITS_PER_WORD, &spi_bits_per_word, "failed setting SPI bits per word"); + + // get hw UID/serial + ret = control_read(0xc3, 0, 0, uid, uid_len, 100); + if (ret == uid_len) { + std::stringstream stream; + for (int i = 0; i < uid_len; i++) { + stream << std::hex << std::setw(2) << std::setfill('0') << int(uid[i]); + } + hw_serial = stream.str(); + } else { + LOGD("failed to get serial %d", ret); + throw std::runtime_error("Error connecting to panda: failed to get serial"); + } - // get hw UID/serial - ret = control_read(0xc3, 0, 0, uid, uid_len, 100); - if (ret == uid_len) { - std::stringstream stream; - for (int i = 0; i < uid_len; i++) { - stream << std::hex << std::setw(2) << std::setfill('0') << int(uid[i]); + if (!serial.empty() && (serial != hw_serial)) { + throw std::runtime_error("Error connecting to panda: serial mismatch"); } - hw_serial = stream.str(); - } else { - LOGD("failed to get serial %d", ret); - goto fail; - } - if (!serial.empty() && (serial != hw_serial)) { - goto fail; + } catch (...) { + cleanup(); + throw; } - return; - -fail: - cleanup(); - throw std::runtime_error("Error connecting to panda"); } PandaSpiHandle::~PandaSpiHandle() { @@ -239,7 +224,7 @@ int PandaSpiHandle::spi_transfer_retry(uint8_t endpoint, uint8_t *tx_data, uint1 // due to full TX buffers nack_count += 1; if (nack_count > 3) { - SPILOG(LOGE, "NACK sleep %d", nack_count); + SPILOG(LOGD, "NACK sleep %d", nack_count); usleep(std::clamp(nack_count*10, 200, 2000)); } } @@ -418,7 +403,6 @@ int PandaSpiHandle::spi_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx } } - if (ret > 0) ret = -1; + if (ret >= 0) ret = -1; return ret; } -#endif diff --git a/selfdrive/pandad/tests/bootstub.panda.bin b/selfdrive/pandad/tests/bootstub.panda.bin deleted file mode 100755 index 43db5370613b9a..00000000000000 Binary files a/selfdrive/pandad/tests/bootstub.panda.bin and /dev/null differ diff --git a/selfdrive/pandad/tests/bootstub.panda_h7_spiv0.bin b/selfdrive/pandad/tests/bootstub.panda_h7_spiv0.bin deleted file mode 100755 index 5cf2fa45196484..00000000000000 Binary files a/selfdrive/pandad/tests/bootstub.panda_h7_spiv0.bin and /dev/null differ diff --git a/selfdrive/pandad/tests/test_pandad.py b/selfdrive/pandad/tests/test_pandad.py index 467c7f04c9dde6..9dacd3f5a88d40 100644 --- a/selfdrive/pandad/tests/test_pandad.py +++ b/selfdrive/pandad/tests/test_pandad.py @@ -5,7 +5,7 @@ import cereal.messaging as messaging from cereal import log from openpilot.common.gpio import gpio_set, gpio_init -from panda import Panda, PandaDFU, PandaProtocolMismatch +from panda import Panda, PandaDFU from openpilot.system.manager.process_config import managed_processes from openpilot.system.hardware import HARDWARE from openpilot.system.hardware.tici.pins import GPIO @@ -15,14 +15,6 @@ @pytest.mark.tici class TestPandad: - - def setup_method(self): - # ensure panda is up - if len(Panda.list()) == 0: - self._run_test(60) - - self.spi = HARDWARE.get_device_type() != 'tici' - def teardown_method(self): managed_processes['pandad'].stop() @@ -32,7 +24,7 @@ def _run_test(self, timeout=30) -> float: managed_processes['pandad'].start() while (time.monotonic() - st) < timeout: - sm.update(100) + sm.update(10) if len(sm['pandaStates']) and sm['pandaStates'][0].pandaType != log.PandaState.PandaType.unknown: break dt = time.monotonic() - st @@ -47,33 +39,18 @@ def _go_to_dfu(self): HARDWARE.recover_internal_panda() assert Panda.wait_for_dfu(None, 10) - def _assert_no_panda(self): - assert not Panda.wait_for_dfu(None, 3) - assert not Panda.wait_for_panda(None, 3) - - def _flash_bootstub_and_test(self, fn, expect_mismatch=False): + def _flash_bootstub(self, fn): self._go_to_dfu() pd = PandaDFU(None) if fn is None: fn = os.path.join(HERE, pd.get_mcu_type().config.bootstub_fn) with open(fn, "rb") as f: pd.program_bootstub(f.read()) - pd.reset() HARDWARE.reset_internal_panda() - assert Panda.wait_for_panda(None, 10) - if expect_mismatch: - with pytest.raises(PandaProtocolMismatch): - Panda() - else: - with Panda() as p: - assert p.bootstub - - self._run_test(45) - def test_in_dfu(self): HARDWARE.recover_internal_panda() - self._run_test(60) + self._run_test() def test_in_bootstub(self): with Panda() as p: @@ -81,48 +58,24 @@ def test_in_bootstub(self): assert p.bootstub self._run_test() - def test_internal_panda_reset(self): + def test_in_reset(self): gpio_init(GPIO.STM_RST_N, True) gpio_set(GPIO.STM_RST_N, 1) - time.sleep(0.5) - assert all(not Panda(s).is_internal() for s in Panda.list()) + assert not Panda.list() self._run_test() - assert any(Panda(s).is_internal() for s in Panda.list()) - - def test_best_case_startup_time(self): - # run once so we're up to date - self._run_test(60) - - ts = [] - for _ in range(10): - # should be nearly instant this time - dt = self._run_test(5) - ts.append(dt) - - # 5s for USB (due to enumeration) - # - 0.2s pandad -> pandad - # - plus some buffer - assert 0.1 < (sum(ts)/len(ts)) < (0.5 if self.spi else 5.0) - print("startup times", ts, sum(ts) / len(ts)) - - - def test_protocol_version_check(self): - if not self.spi: - pytest.skip("SPI test") - # flash old fw - fn = os.path.join(HERE, "bootstub.panda_h7_spiv0.bin") - self._flash_bootstub_and_test(fn, expect_mismatch=True) - def test_release_to_devel_bootstub(self): - self._flash_bootstub_and_test(None) + st = time.monotonic() + self._flash_bootstub(None) + print("flash done", time.monotonic() - st) + self._run_test() def test_recover_from_bad_bootstub(self): self._go_to_dfu() with PandaDFU(None) as pd: - pd.program_bootstub(b"\x00"*1024) - pd.reset() + pd._handle.program(pd.get_mcu_type().config.bootstub_address, b"\x00"*100) HARDWARE.reset_internal_panda() - self._assert_no_panda() + assert not Panda.list() + assert not PandaDFU.list() - self._run_test(60) + self._run_test() diff --git a/selfdrive/pandad/tests/test_pandad_canprotocol.cc b/selfdrive/pandad/tests/test_pandad_canprotocol.cc new file mode 100644 index 00000000000000..8499a1aab86a16 --- /dev/null +++ b/selfdrive/pandad/tests/test_pandad_canprotocol.cc @@ -0,0 +1,135 @@ +#define CATCH_CONFIG_MAIN +#define CATCH_CONFIG_ENABLE_BENCHMARKING + +#include + +#include "catch2/catch.hpp" +#include "cereal/messaging/messaging.h" +#include "common/util.h" +#include "selfdrive/pandad/panda.h" + +struct PandaTest : public Panda { + PandaTest(int can_list_size, cereal::PandaState::PandaType hw_type); + void test_can_send(); + void test_can_recv(uint32_t chunk_size = 0); + void test_chunked_can_recv(); + + std::map test_data; + int can_list_size = 0; + int total_pakets_size = 0; + MessageBuilder msg; + capnp::List::Reader can_data_list; +}; + +PandaTest::PandaTest(int can_list_size_, cereal::PandaState::PandaType hw_type_) : can_list_size(can_list_size_), Panda() { + this->hw_type = hw_type_; + int data_limit = ((hw_type == cereal::PandaState::PandaType::RED_PANDA) ? std::size(dlc_to_len) : 8); + // prepare test data + for (int i = 0; i < data_limit; ++i) { + std::random_device rd; + std::independent_bits_engine rbe(rd()); + + int data_len = dlc_to_len[i]; + std::string bytes(data_len, '\0'); + std::generate(bytes.begin(), bytes.end(), std::ref(rbe)); + test_data[data_len] = bytes; + } + + // generate can messages for this panda + auto can_list = msg.initEvent().initSendcan(can_list_size); + for (uint8_t i = 0; i < can_list_size; ++i) { + auto can = can_list[i]; + uint32_t id = util::random_int(0, std::size(dlc_to_len) - 1); + const std::string &dat = test_data[dlc_to_len[id]]; + can.setAddress(i); + can.setSrc(util::random_int(0, 2)); + can.setDat(kj::ArrayPtr((uint8_t *)dat.data(), dat.size())); + total_pakets_size += sizeof(can_header) + dat.size(); + } + + can_data_list = can_list.asReader(); + INFO("test " << can_list_size << " packets, total size " << total_pakets_size); +} + +void PandaTest::test_can_send() { + std::vector unpacked_data; + this->pack_can_buffer(can_data_list, [&](uint8_t *chunk, size_t size) { + unpacked_data.insert(unpacked_data.end(), chunk, &chunk[size]); + }); + REQUIRE(unpacked_data.size() == total_pakets_size); + + int cnt = 0; + INFO("test can message integrity"); + for (int pos = 0, pckt_len = 0; pos < unpacked_data.size(); pos += pckt_len) { + can_header header; + memcpy(&header, &unpacked_data[pos], sizeof(can_header)); + const uint8_t data_len = dlc_to_len[header.data_len_code]; + pckt_len = sizeof(can_header) + data_len; + + REQUIRE(header.addr == cnt); + REQUIRE(test_data.find(data_len) != test_data.end()); + const std::string &dat = test_data[data_len]; + REQUIRE(memcmp(dat.data(), &unpacked_data[pos + sizeof(can_header)], dat.size()) == 0); + ++cnt; + } + REQUIRE(cnt == can_list_size); +} + +void PandaTest::test_can_recv(uint32_t rx_chunk_size) { + std::vector frames; + this->pack_can_buffer(can_data_list, [&](uint8_t *data, uint32_t size) { + if (rx_chunk_size == 0) { + REQUIRE(this->unpack_can_buffer(data, size, frames)); + } else { + this->receive_buffer_size = 0; + uint32_t pos = 0; + + while (pos < size) { + uint32_t chunk_size = std::min(rx_chunk_size, size - pos); + memcpy(&this->receive_buffer[this->receive_buffer_size], &data[pos], chunk_size); + this->receive_buffer_size += chunk_size; + pos += chunk_size; + + REQUIRE(this->unpack_can_buffer(this->receive_buffer, this->receive_buffer_size, frames)); + } + } + }); + + REQUIRE(frames.size() == can_list_size); + for (int i = 0; i < frames.size(); ++i) { + REQUIRE(frames[i].address == i); + REQUIRE(test_data.find(frames[i].dat.size()) != test_data.end()); + const std::string &dat = test_data[frames[i].dat.size()]; + REQUIRE(memcmp(dat.data(), frames[i].dat.data(), dat.size()) == 0); + } +} + +TEST_CASE("send/recv CAN 2.0 packets") { + auto can_list_size = GENERATE(1, 3, 5, 10, 30, 60, 100, 200); + PandaTest test(can_list_size, cereal::PandaState::PandaType::DOS); + + SECTION("can_send") { + test.test_can_send(); + } + SECTION("can_receive") { + test.test_can_recv(); + } + SECTION("chunked_can_receive") { + test.test_can_recv(0x40); + } +} + +TEST_CASE("send/recv CAN FD packets") { + auto can_list_size = GENERATE(1, 3, 5, 10, 30, 60, 100, 200); + PandaTest test(can_list_size, cereal::PandaState::PandaType::RED_PANDA); + + SECTION("can_send") { + test.test_can_send(); + } + SECTION("can_receive") { + test.test_can_recv(); + } + SECTION("chunked_can_receive") { + test.test_can_recv(0x40); + } +} diff --git a/selfdrive/pandad/tests/test_pandad_loopback.py b/selfdrive/pandad/tests/test_pandad_loopback.py index 0f41201ececc0e..bc90f42a839f1c 100644 --- a/selfdrive/pandad/tests/test_pandad_loopback.py +++ b/selfdrive/pandad/tests/test_pandad_loopback.py @@ -9,52 +9,55 @@ import cereal.messaging as messaging from cereal import car, log from opendbc.car.can_definitions import CanData -from openpilot.common.retry import retry +from openpilot.common.utils import retry from openpilot.common.params import Params from openpilot.common.timeout import Timeout from openpilot.selfdrive.pandad import can_list_to_can_capnp -from openpilot.system.hardware import TICI -from openpilot.selfdrive.test.helpers import phone_only, with_processes +from openpilot.selfdrive.test.helpers import with_processes +def publish_device_state(pm, started): + msg = messaging.new_message('deviceState') + msg.deviceState.started = started + pm.send('deviceState', msg) + @retry(attempts=3) -def setup_pandad(num_pandas): +def setup_pandad(): params = Params() params.clear_all() - params.put_bool("IsOnroad", False) + pm = messaging.PubMaster(['deviceState']) sm = messaging.SubMaster(['pandaStates']) + publish_device_state(pm, False) with Timeout(90, "pandad didn't start"): while sm.recv_frame['pandaStates'] < 1 or len(sm['pandaStates']) == 0 or \ any(ps.pandaType == log.PandaState.PandaType.unknown for ps in sm['pandaStates']): - sm.update(1000) - - found_pandas = len(sm['pandaStates']) - assert num_pandas == found_pandas, "connected pandas ({found_pandas}) doesn't match expected panda count ({num_pandas}). \ - connect another panda for multipanda tests." + publish_device_state(pm, False) + sm.update(100) # pandad safety setting relies on these params cp = car.CarParams.new_message() safety_config = car.CarParams.SafetyConfig.new_message() safety_config.safetyModel = car.CarParams.SafetyModel.allOutput - cp.safetyConfigs = [safety_config]*num_pandas + cp.safetyConfigs = [safety_config] - params.put_bool("IsOnroad", True) - params.put_bool("FirmwareQueryDone", True) - params.put_bool("ControlsReady", True) - params.put("CarParams", cp.to_bytes()) + params.put_bool("FirmwareQueryDone", True, block=True) + params.put_bool("ControlsReady", True, block=True) + params.put("CarParams", cp.to_bytes(), block=True) + publish_device_state(pm, True) with Timeout(90, "pandad didn't set safety mode"): while any(ps.safetyModel != car.CarParams.SafetyModel.allOutput for ps in sm['pandaStates']): - sm.update(1000) + publish_device_state(pm, True) + sm.update(100) -def send_random_can_messages(sendcan, count, num_pandas=1): +def send_random_can_messages(sendcan, count): sent_msgs = defaultdict(set) for _ in range(count): to_send = [] for __ in range(random.randrange(20)): - bus = random.choice([b for b in range(3*num_pandas) if b % 4 != 3]) + bus = random.choice(range(3)) addr = random.randrange(1, 1<<29) dat = bytes(random.getrandbits(8) for _ in range(random.randrange(1, 9))) if (addr, dat) in sent_msgs[bus]: @@ -72,11 +75,9 @@ def setup_class(cls): os.environ['STARTED'] = '1' os.environ['BOARDD_LOOPBACK'] = '1' - @phone_only @with_processes(['pandad']) def test_loopback(self): - num_pandas = 2 if TICI and "SINGLE_PANDA" not in os.environ else 1 - setup_pandad(num_pandas) + setup_pandad() sendcan = messaging.pub_sock('sendcan') can = messaging.sub_sock('can', conflate=False, timeout=100) @@ -87,7 +88,7 @@ def test_loopback(self): for i in range(n): print(f"pandad loopback {i}/{n}") - sent_msgs = send_random_can_messages(sendcan, random.randrange(20, 100), num_pandas) + sent_msgs = send_random_can_messages(sendcan, random.randrange(20, 100)) sent_loopback = copy.deepcopy(sent_msgs) sent_loopback.update({k+128: copy.deepcopy(v) for k, v in sent_msgs.items()}) diff --git a/selfdrive/pandad/tests/test_pandad_spi.py b/selfdrive/pandad/tests/test_pandad_spi.py index 9c5990cd3f59d6..69dfb67e9334e3 100644 --- a/selfdrive/pandad/tests/test_pandad_spi.py +++ b/selfdrive/pandad/tests/test_pandad_spi.py @@ -6,8 +6,7 @@ import cereal.messaging as messaging from cereal.services import SERVICE_LIST -from openpilot.system.hardware import HARDWARE -from openpilot.selfdrive.test.helpers import phone_only, with_processes +from openpilot.selfdrive.test.helpers import with_processes from openpilot.selfdrive.pandad.tests.test_pandad_loopback import setup_pandad, send_random_can_messages JUNGLE_SPAM = "JUNGLE_SPAM" in os.environ @@ -16,17 +15,14 @@ class TestBoarddSpi: @classmethod def setup_class(cls): - if HARDWARE.get_device_type() == 'tici': - pytest.skip("only for spi pandas") os.environ['STARTED'] = '1' os.environ['SPI_ERR_PROB'] = '0.001' if not JUNGLE_SPAM: os.environ['BOARDD_LOOPBACK'] = '1' - @phone_only @with_processes(['pandad']) def test_spi_corruption(self, subtests): - setup_pandad(1) + setup_pandad() sendcan = messaging.pub_sock('sendcan') socks = {s: messaging.sub_sock(s, conflate=False, timeout=100) for s in ('can', 'pandaStates', 'peripheralState')} diff --git a/selfdrive/pandad/tests/test_pandad_usbprotocol.cc b/selfdrive/pandad/tests/test_pandad_usbprotocol.cc deleted file mode 100644 index 11f7184efdba2f..00000000000000 --- a/selfdrive/pandad/tests/test_pandad_usbprotocol.cc +++ /dev/null @@ -1,135 +0,0 @@ -#define CATCH_CONFIG_MAIN -#define CATCH_CONFIG_ENABLE_BENCHMARKING - -#include "catch2/catch.hpp" -#include "cereal/messaging/messaging.h" -#include "common/util.h" -#include "selfdrive/pandad/panda.h" - -struct PandaTest : public Panda { - PandaTest(uint32_t bus_offset, int can_list_size, cereal::PandaState::PandaType hw_type); - void test_can_send(); - void test_can_recv(uint32_t chunk_size = 0); - void test_chunked_can_recv(); - - std::map test_data; - int can_list_size = 0; - int total_pakets_size = 0; - MessageBuilder msg; - capnp::List::Reader can_data_list; -}; - -PandaTest::PandaTest(uint32_t bus_offset_, int can_list_size, cereal::PandaState::PandaType hw_type) : can_list_size(can_list_size), Panda(bus_offset_) { - this->hw_type = hw_type; - int data_limit = ((hw_type == cereal::PandaState::PandaType::RED_PANDA) ? std::size(dlc_to_len) : 8); - // prepare test data - for (int i = 0; i < data_limit; ++i) { - std::random_device rd; - std::independent_bits_engine rbe(rd()); - - int data_len = dlc_to_len[i]; - std::string bytes(data_len, '\0'); - std::generate(bytes.begin(), bytes.end(), std::ref(rbe)); - test_data[data_len] = bytes; - } - - // generate can messages for this panda - auto can_list = msg.initEvent().initSendcan(can_list_size); - for (uint8_t i = 0; i < can_list_size; ++i) { - auto can = can_list[i]; - uint32_t id = util::random_int(0, std::size(dlc_to_len) - 1); - const std::string &dat = test_data[dlc_to_len[id]]; - can.setAddress(i); - can.setSrc(util::random_int(0, 2) + bus_offset); - can.setDat(kj::ArrayPtr((uint8_t *)dat.data(), dat.size())); - total_pakets_size += sizeof(can_header) + dat.size(); - } - - can_data_list = can_list.asReader(); - INFO("test " << can_list_size << " packets, total size " << total_pakets_size); -} - -void PandaTest::test_can_send() { - std::vector unpacked_data; - this->pack_can_buffer(can_data_list, [&](uint8_t *chunk, size_t size) { - unpacked_data.insert(unpacked_data.end(), chunk, &chunk[size]); - }); - REQUIRE(unpacked_data.size() == total_pakets_size); - - int cnt = 0; - INFO("test can message integrity"); - for (int pos = 0, pckt_len = 0; pos < unpacked_data.size(); pos += pckt_len) { - can_header header; - memcpy(&header, &unpacked_data[pos], sizeof(can_header)); - const uint8_t data_len = dlc_to_len[header.data_len_code]; - pckt_len = sizeof(can_header) + data_len; - - REQUIRE(header.addr == cnt); - REQUIRE(test_data.find(data_len) != test_data.end()); - const std::string &dat = test_data[data_len]; - REQUIRE(memcmp(dat.data(), &unpacked_data[pos + sizeof(can_header)], dat.size()) == 0); - ++cnt; - } - REQUIRE(cnt == can_list_size); -} - -void PandaTest::test_can_recv(uint32_t rx_chunk_size) { - std::vector frames; - this->pack_can_buffer(can_data_list, [&](uint8_t *data, uint32_t size) { - if (rx_chunk_size == 0) { - REQUIRE(this->unpack_can_buffer(data, size, frames)); - } else { - this->receive_buffer_size = 0; - uint32_t pos = 0; - - while (pos < size) { - uint32_t chunk_size = std::min(rx_chunk_size, size - pos); - memcpy(&this->receive_buffer[this->receive_buffer_size], &data[pos], chunk_size); - this->receive_buffer_size += chunk_size; - pos += chunk_size; - - REQUIRE(this->unpack_can_buffer(this->receive_buffer, this->receive_buffer_size, frames)); - } - } - }); - - REQUIRE(frames.size() == can_list_size); - for (int i = 0; i < frames.size(); ++i) { - REQUIRE(frames[i].address == i); - REQUIRE(test_data.find(frames[i].dat.size()) != test_data.end()); - const std::string &dat = test_data[frames[i].dat.size()]; - REQUIRE(memcmp(dat.data(), frames[i].dat.data(), dat.size()) == 0); - } -} - -TEST_CASE("send/recv CAN 2.0 packets") { - auto bus_offset = GENERATE(0, 4); - auto can_list_size = GENERATE(1, 3, 5, 10, 30, 60, 100, 200); - PandaTest test(bus_offset, can_list_size, cereal::PandaState::PandaType::DOS); - - SECTION("can_send") { - test.test_can_send(); - } - SECTION("can_receive") { - test.test_can_recv(); - } - SECTION("chunked_can_receive") { - test.test_can_recv(0x40); - } -} - -TEST_CASE("send/recv CAN FD packets") { - auto bus_offset = GENERATE(0, 4); - auto can_list_size = GENERATE(1, 3, 5, 10, 30, 60, 100, 200); - PandaTest test(bus_offset, can_list_size, cereal::PandaState::PandaType::RED_PANDA); - - SECTION("can_send") { - test.test_can_send(); - } - SECTION("can_receive") { - test.test_can_recv(); - } - SECTION("chunked_can_receive") { - test.test_can_recv(0x40); - } -} diff --git a/system/camerad/snapshot/__init__.py b/selfdrive/pathobstacled/__init__.py similarity index 100% rename from system/camerad/snapshot/__init__.py rename to selfdrive/pathobstacled/__init__.py diff --git a/selfdrive/pathobstacled/cone_cam.py b/selfdrive/pathobstacled/cone_cam.py new file mode 100644 index 00000000000000..5c1524f15edfb9 --- /dev/null +++ b/selfdrive/pathobstacled/cone_cam.py @@ -0,0 +1,331 @@ +"""Camera confirm for the radar cone line. Log only: nothing reads the result. + +radard publishes coneLineNAP (side plus the line's path-relative lateral at +15/30/45 m). While that line has posts, pathobstacled grabs one ROAD frame +at most 5 Hz and scores up to six ground windows along the line (8–48 m). +Each window is projected with the calibrated camera into a pixel box that +covers 0–1.2 m above the road and ±0.6 m around the line. The box is +compared with a road patch 1.3 m toward the lane: + + orange V above the road by ORANGE_DV and U below it by ORANGE_DU + white luma above the road by WHITE_DY with near-neutral chroma + banding alternating orange / white row runs, the drum and post stripes + +A window is a hit when its orange area is a real fraction of a drum or a +post at that range, plus either banding or a drum-sized orange area. The +line is camera-confirmed while, within the last CONFIRM_WINDOW_S, one frame +had two or more windows on the line's side hit. A lone orange truck or building can never make a +line: a window is only scored where radar already sees a line. + +Pure numpy on the CPU. No tinygrad, onnx, or OpenCL: the GPU belongs to +modeld (Oct 10, a second GPU tenant pushed modeld exec from ~25 ms to +300–710 ms and raised commIssue). +""" +from __future__ import annotations + +import math +import time +from dataclasses import dataclass, field + +import numpy as np + + +# Six ground windows (x0, x1) in metres ahead of the camera. +WINDOWS_M = ((8.0, 12.0), (12.0, 17.0), (17.0, 23.0), (23.0, 30.0), (30.0, 38.0), (38.0, 48.0)) +MAX_CROPS = 6 +LOOKAHEADS_M = (15.0, 30.0, 45.0) +HALF_WIDTH_M = 0.60 +TOP_M = 1.20 +ROAD_SHIFT_M = 1.30 +ROAD_TOP_M = 0.0 +ORANGE_DV = 14.0 +ORANGE_DU = 8.0 +ORANGE_MIN_V = 140.0 +WHITE_DY = 45.0 +WHITE_CHROMA = 14.0 +# Visible face of a tubular post and of a drum, metres (w, h). +POST_WH = (0.10, 0.90) +DRUM_WH = (0.55, 0.95) +HIT_POST_FRAC = 0.35 +HIT_DRUM_FRAC = 0.30 +MIN_BANDS = 2 +MIN_ORANGE_PX = 6 +CONFIRM_HITS = 2 +CONFIRM_WINDOW_S = 1.0 +LOG_HZ = 2.0 +BUDGET_S = 0.008 +# Chroma samples per box. Near windows are large; they are strided, not dropped. +# Oct 13: 12000 let only 1-3 of 6 windows fit the budget at speed. A quarter +# of that still resolves a drum stripe and scores all six in one frame. +MAX_SAMPLES = 3000 +# Red tail lights / brake lights: high V with U near neutral (orange has a +# much lower U). A window whose red area rivals its orange area is not a cone. +RED_MIN_V = 165.0 +RED_MIN_U = 112.0 +RED_REJECT_FRAC = 0.60 +# A "line" inside our own footprint is a vehicle or queue, not cones. +VEHICLE_LAT_M = 1.20 +# Two consecutive frames can cover the six windows between them. +PAIR_S = 0.6 + + +@dataclass(frozen=True) +class CamGeom: + width: int = 1928 + height: int = 1208 + focal: float = 2648.0 + roll: float = 0.0 + pitch: float = 0.0 + yaw: float = 0.0 + cam_height: float = 1.22 + + +@dataclass(frozen=True) +class CropScore: + x0: float + x1: float + hit: bool + conf: float + orange_px: int + white_px: int + bands: int + box: tuple + + +def _lat_at(lats: tuple[float, float, float], x: float) -> float: + """Linear in x through the three lookaheads, clamped at the ends.""" + xs = LOOKAHEADS_M + if x <= xs[0]: + return lats[0] + if x >= xs[-1]: + return lats[-1] + for i in range(len(xs) - 1): + if xs[i] <= x <= xs[i + 1]: + t = (x - xs[i]) / (xs[i + 1] - xs[i]) + return lats[i] + t * (lats[i + 1] - lats[i]) + return lats[-1] + + +def _project_many(geom: CamGeom, xs, lat_right, zs): + """Vectorized project_road_point (same math). Returns (u, v) or None if any point is behind.""" + x = np.asarray(xs, dtype=np.float64) + y = -np.asarray(lat_right, dtype=np.float64) + z = np.asarray(zs, dtype=np.float64) + cr, sr = math.cos(geom.roll), math.sin(geom.roll) + cp, sp = math.cos(geom.pitch), math.sin(geom.pitch) + cyaw, syaw = math.cos(geom.yaw), math.sin(geom.yaw) + rx, ry, rz = x, -y, -z + ry, rz = cr * ry - sr * rz, sr * ry + cr * rz + rx, rz = cp * rx + sp * rz, -sp * rx + cp * rz + rx, ry = cyaw * rx - syaw * ry, syaw * rx + cyaw * ry + vx, vy, vz = ry, rz + geom.cam_height, rx + if not np.all(np.isfinite(vz)) or np.any(vz <= 0.5): + return None + return geom.width / 2.0 + geom.focal * (vx / vz), geom.height / 2.0 + geom.focal * (vy / vz) + + +_CORNERS = np.array([(i, j, k) for i in (0, 1) for j in (-1.0, 1.0) for k in (0, 1)], dtype=np.float64) + + +def ground_box(geom: CamGeom, x0: float, x1: float, lat0: float, lat1: float, + half_w: float, z0: float, z1: float) -> tuple[int, int, int, int] | None: + """Pixel bounding box of a ground-frame block. None when off-frame or behind.""" + sel = _CORNERS[:, 0] + xs = np.where(sel > 0, x1, x0) + lats = np.where(sel > 0, lat1, lat0) + _CORNERS[:, 1] * half_w + zs = np.where(_CORNERS[:, 2] > 0, z1, z0) + got = _project_many(geom, xs, lats, zs) + if got is None: + return None + us, vs = got + if not (np.all(np.isfinite(us)) and np.all(np.isfinite(vs))): + return None + u0 = max(0, int(math.floor(float(us.min())))) + u1 = min(geom.width, int(math.ceil(float(us.max())))) + v0 = max(0, int(math.floor(float(vs.min())))) + v1 = min(geom.height, int(math.ceil(float(vs.max())))) + if u1 - u0 < 4 or v1 - v0 < 4: + return None + return u0, v0, u1, v1 + + +def _object_px(geom: CamGeom, x: float, wh: tuple[float, float]) -> float: + return max(1.0, (geom.focal * wh[0] / x) * (geom.focal * wh[1] / x)) + + +def _chroma(plane, box): + """Half-resolution U or V crop for a full-resolution box.""" + u0, v0, u1, v1 = box + h, w = plane.shape[:2] + x0, x1 = max(0, u0 // 2), min(w, max(u0 // 2 + 1, u1 // 2)) + y0, y1 = max(0, v0 // 2), min(h, max(v0 // 2 + 1, v1 // 2)) + return plane[y0:y1, x0:x1] + + +def _bands(orange_rows: np.ndarray, white_rows: np.ndarray, width: int) -> int: + """Alternations between orange-dominant and white-dominant row runs.""" + need = max(1, int(0.08 * width)) + labels = np.where(orange_rows >= np.maximum(need, white_rows), 1, + np.where(white_rows >= np.maximum(need, orange_rows), 2, 0)) + seq = labels[labels > 0] + if seq.size < 2: + return 0 + return int(np.count_nonzero(seq[1:] != seq[:-1])) + + +def score_window(y: np.ndarray, u: np.ndarray, v: np.ndarray, geom: CamGeom, + x0: float, x1: float, lats: tuple[float, float, float]) -> CropScore | None: + """Score one ground window. None when it does not land in the frame.""" + la, lb = _lat_at(lats, x0), _lat_at(lats, x1) + if min(abs(la), abs(lb)) < VEHICLE_LAT_M: + # Inside our own footprint: a lead or a queue, never a cone line we drive past. + return None + box = ground_box(geom, x0, x1, la, lb, HALF_WIDTH_M, 0.0, TOP_M) + if box is None: + return None + # Road patch toward the lane (lat -> 0), on the ground. + toward = -ROAD_SHIFT_M if (la + lb) > 0 else ROAD_SHIFT_M + rbox = ground_box(geom, x0, x1, la + toward, lb + toward, 0.35, ROAD_TOP_M, 0.0) + if rbox is None or (rbox[3] - rbox[1]) < 2: + rbox = ground_box(geom, x0, x1, la + toward, lb + toward, 0.35, 0.0, 0.15) + if rbox is None: + return None + u0, v0, u1, v1 = box + yb = y[v0:v1, u0:u1] + ub = _chroma(u, box) + vb = _chroma(v, box) + if yb.size == 0 or ub.size == 0 or vb.size == 0: + return None + ry = y[rbox[1]:rbox[3], rbox[0]:rbox[2]] + ru = _chroma(u, rbox) + rv = _chroma(v, rbox) + if ry.size == 0 or ru.size == 0 or rv.size == 0: + return None + rs = max(1, int(math.sqrt(ru.size / 1500.0))) + y_r = float(np.median(ry[::2 * rs, ::2 * rs])) + u_r = float(np.median(ru[::rs, ::rs])) + v_r = float(np.median(rv[::rs, ::rs])) + # Chroma at half resolution; luma subsampled to match. + ch, cw = min(ub.shape[0], vb.shape[0]), min(ub.shape[1], vb.shape[1]) + step = 1 + while (ch // step) * (cw // step) > MAX_SAMPLES: + step += 1 + ub = ub[:ch:step, :cw:step].astype(np.int16) + vb = vb[:ch:step, :cw:step].astype(np.int16) + ys = yb[: 2 * ch : 2 * step, : 2 * cw : 2 * step].astype(np.int16) + ch, cw = min(ub.shape[0], ys.shape[0]), min(ub.shape[1], ys.shape[1]) + ub, vb, ys = ub[:ch, :cw], vb[:ch, :cw], ys[:ch, :cw] + red = (vb >= RED_MIN_V) & (ub >= RED_MIN_U) & (vb >= v_r + ORANGE_DV) + orange = (vb >= v_r + ORANGE_DV) & (ub <= u_r - ORANGE_DU) & (vb >= ORANGE_MIN_V) & ~red + white = (ys >= y_r + WHITE_DY) & (np.abs(ub - 128) <= WHITE_CHROMA) & (np.abs(vb - 128) <= WHITE_CHROMA) + o_rows = orange.sum(axis=1) + w_rows = white.sum(axis=1) + scale = 4 * step * step # one strided half-res sample -> full-res area + orange_px = int(o_rows.sum()) * scale + white_px = int(w_rows.sum()) * scale + bands = _bands(o_rows, w_rows, cw) + xm = 0.5 * (x0 + x1) + post = _object_px(geom, xm, POST_WH) + drum = _object_px(geom, xm, DRUM_WH) + post_like = orange_px >= max(MIN_ORANGE_PX * 4, HIT_POST_FRAC * post) and bands >= MIN_BANDS + drum_like = orange_px >= HIT_DRUM_FRAC * drum and white_px > 0 and bands >= 1 + red_px = int(red.sum()) * scale + tail_light = red_px > 0 and red_px >= RED_REJECT_FRAC * max(1, orange_px) + hit = bool((post_like or drum_like) and not tail_light) + conf = min(1.0, orange_px / max(1.0, HIT_DRUM_FRAC * drum)) + if bands >= MIN_BANDS: + conf = min(1.0, conf + 0.25) + return CropScore(x0, x1, hit, round(conf if hit else min(conf, 0.49), 3), orange_px, white_px, bands, box) + + +def score_line(y, u, v, geom: CamGeom, lats: tuple[float, float, float], + deadline: float | None = None, start: int = 0) -> tuple[list[CropScore], bool]: + """Score up to MAX_CROPS windows, starting at `start` (rotates after a budget stop). + + Second value is True when the budget ran out before every window was scored. + """ + out: list[CropScore] = [] + n = min(MAX_CROPS, len(WINDOWS_M)) + for k in range(n): + x0, x1 = WINDOWS_M[(start + k) % n] + if deadline is not None and time.monotonic() >= deadline: + return out, True + s = score_window(y, u, v, geom, x0, x1, lats) + if s is not None: + out.append(s) + return out, False + + +@dataclass +class ConeCamState: + """Last 1 s of per-frame window hits for one side, and the 2 Hz log gate. + + Posts "agree" when two or more different windows hit in the same frame, + or across two consecutive frames that scored disjoint windows (a budget + split). A frame with zero hits clears it (Oct 13 stale confirm). A + single window cannot confirm across overlapping frames: one orange + object slides through neighbouring windows as the car moves. + """ + side: int = 0 + frames: list = field(default_factory=list) # (t, hit windows, scored windows) + last_log: float = -1e9 + + def update(self, side: int, scores: list[CropScore], now: float) -> bool: + if side != self.side: + self.side = side + self.frames = [] + hit_windows = frozenset((s.x0, s.x1) for s in scores if s.hit) + scored = frozenset((s.x0, s.x1) for s in scores) + if scored and not hit_windows: + # Oct 13 stale-confirm bug: a frame with 0 hits clears confirmed. + self.frames = [(now, hit_windows, scored)] + return False + if not scored: + # No frame or nothing in view: not evidence either way. + self.frames = [f for f in self.frames if now - f[0] <= CONFIRM_WINDOW_S] + return self.confirmed(now) + self.frames.append((now, hit_windows, scored)) + self.frames = [f for f in self.frames if now - f[0] <= CONFIRM_WINDOW_S] + return self.confirmed(now) + + def confirmed(self, now: float) -> bool: + if self.side == 0 or not self.frames: + return False + t_last, hits_last, _scored_last = self.frames[-1] + if now - t_last > CONFIRM_WINDOW_S or not hits_last: + return False + if len(hits_last) >= CONFIRM_HITS: + return True + # One window here plus a different window in the previous frame, when the + # two frames scored different windows (a budget split, not one object + # sliding through neighbours). + if len(self.frames) >= 2: + t_prev, hits_prev, scored_prev = self.frames[-2] + if t_last - t_prev <= PAIR_S and hits_prev and not (scored_prev & self.frames[-1][2]): + return len(hits_last | hits_prev) >= CONFIRM_HITS + return False + + def should_log(self, now: float) -> bool: + if now - self.last_log >= 1.0 / LOG_HZ: + self.last_log = now + return True + return False + + +def uv_planes_from_nv12(buf): + """(U, V) half-resolution views of an NV12 VisionBuf. None when chroma is missing.""" + try: + width = int(buf.width) + height = int(buf.height) + stride = int(buf.stride) if getattr(buf, "stride", 0) else width + if width < 4 or height < 4 or stride < width: + return None + data = buf.data + uv_off = getattr(buf, "uv_offset", 0) or stride * height + uv_rows = height // 2 + if data is None or len(data) < uv_off + stride * uv_rows: + return None + uv = np.frombuffer(data, dtype=np.uint8, count=stride * uv_rows, offset=uv_off).reshape(uv_rows, stride) + return uv[:, 0:width:2], uv[:, 1:width:2] + except Exception: + return None diff --git a/selfdrive/pathobstacled/pathobstacled.py b/selfdrive/pathobstacled/pathobstacled.py new file mode 100644 index 00000000000000..542043d67aa3b5 --- /dev/null +++ b/selfdrive/pathobstacled/pathobstacled.py @@ -0,0 +1,913 @@ +#!/usr/bin/env python3 +"""Camera helper for the path-obstacle chime. Little cores, nice 19. + +radard owns the radar scan and publishes pathObstacleNAP. This process +blocks on that socket (no poll loop) and opens the camera only while a +candidate is active, at most 5 times a second. A crash here must not +disengage: manager starts this process as optional. +""" +from __future__ import annotations + +import math +import os +import time +from dataclasses import replace + +from openpilot.selfdrive.pathobstacled.cone_cam import ( + BUDGET_S as CONE_BUDGET_S, + CamGeom, + ConeCamState, + WINDOWS_M as CONE_WINDOWS_M, + score_line, + uv_planes_from_nv12, +) +from openpilot.selfdrive.controls.lib.path_obstacle import ( + PARAM_OBSTACLE_CHIME, + PARAM_OBSTACLE_LOG, + PathObstacleDetector, + hit_from_msg, + is_night_lighting, + lighting_score, + patch_change_score, + patch_signature, + project_road_point, + projection_box, + prune_thumbs, + save_ppm, + score_row_patches, +) + +# comma 3X road camera (OS04C10). Wide focal is the stock fisheye guess. +ROAD_W, ROAD_H, ROAD_F = 1344, 760, 1141.5 +WIDE_F = 425.25 +AR_W, AR_H, AR_F, AR_WIDE_F = 1928, 1208, 2648.0, 567.0 +VISION_HZ = 5.0 +VISION_BUDGET_S = 0.008 +RECV_TIMEOUT_MS = 20 +CONNECT_BACKOFF_S = 0.50 +CONNECT_BACKOFF_MAX_S = 5.0 +STALE_FRAME_NS = 500_000_000 +VISION_FAIL_REASONS = ( + "no_connection", + "no_frame", + "stale_frame", + "roi_out_of_frame", + "budget", + "model_error", +) +# Cone camera confirm (log only). At most 5 Hz, one shared 8 ms budget per +# grab+score, SCHED_IDLE while scoring, and a backoff while modeld drops frames. +CONE_HZ = 5.0 +CONE_DROP_BACKOFF_S = 0.5 +CONE_DROP_BACKOFF_MAX_S = 5.0 +CONE_DROP_PERC = 0.0 +THUMB_DIR = "/data/media/0/realdata/path_obstacle_thumbs" +THUMB_GAP_S = 2.0 +NICE = 19 +CORES = [0, 1, 2, 3] +# Block in the kernel until radard publishes, or this long for a param refresh. +RADAR_TIMEOUT_MS = 1500 +# CalibrationParams is written by calibrationd every few blocks, not every frame. +CAL_REFRESH_S = 10.0 +# roll, pitch, yaw, height, wide-from-device euler. Height 1.22 m is the stock fallback. +_DEFAULT_CALIB = (0.0, 0.0, 0.0, 1.22, 0.0, 0.0, 0.0) + + +def _bool_param(params, key: str, default: bool) -> bool: + try: + return bool(params.get_bool(key)) + except Exception: + return default + + +def _cam_size(sensor) -> tuple[int, int, float, float]: + name = str(sensor or "").lower() + if "ar0231" in name or "ox03" in name: + return AR_W, AR_H, AR_F, AR_WIDE_F + return ROAD_W, ROAD_H, ROAD_F, WIDE_F + + +def _own(plane): + """Copy a crop out of camerad's live VisionIPC buffer before reading it.""" + if plane is None: + return None + try: + return plane.copy() + except Exception: + return plane + + +def _lighting_from(body, cam, gps) -> float: + """Lane and path std come from radard. Exposure and sun are local.""" + try: + lane = float(body.laneProbMin) + except Exception: + lane = 1.0 + if not math.isfinite(lane): + lane = 1.0 + try: + std = float(body.pathYStd3s) + except Exception: + std = float("nan") + path_std = std if math.isfinite(std) else None + sun = False + try: + from openpilot.selfdrive.controls.lib.lat_low_visibility import sun_ahead_from_fix + if gps is not None: + got = sun_ahead_from_fix( + latitude=gps.latitude, + longitude=gps.longitude, + unix_timestamp_millis=gps.unixTimestampMillis, + bearing_deg=gps.bearingDeg, + horizontal_accuracy_m=gps.horizontalAccuracy, + ) + sun = bool(got) + except Exception: + sun = False + integ = gain = grey = None + if cam is not None: + try: + integ = float(cam.integLines) + except Exception: + integ = None + try: + gain = float(cam.gain) + except Exception: + gain = None + try: + grey = float(cam.measuredGreyFraction) + except Exception: + grey = None + return lighting_score( + lane_left=lane, + lane_right=lane, + path_y_std=path_std, + integ_lines=integ, + gain=gain, + grey=grey, + sun_ahead=sun, + headlights=False, + ) + + +def _finite_list(values) -> list[float]: + try: + seq = list(values) + except TypeError: + return [] + out = [] + for value in seq: + try: + num = float(value) + except (TypeError, ValueError): + continue + if math.isfinite(num): + out.append(num) + return out + + +def _calibration_from_params(params): + """rpy, height, and wide euler from CalibrationParams. No liveCalibration socket.""" + try: + raw = params.get("CalibrationParams") + except Exception: + raw = None + if not raw: + return _DEFAULT_CALIB + try: + from cereal import log + with log.Event.from_bytes(raw) as msg: + cal = msg.liveCalibration + rpy = _finite_list(cal.rpyCalib) + wide = _finite_list(cal.wideFromDeviceEuler) + heights = _finite_list(cal.height) + except Exception: + return _DEFAULT_CALIB + while len(rpy) < 3: + rpy.append(0.0) + while len(wide) < 3: + wide.append(0.0) + height = heights[0] if heights and heights[0] > 0.2 else 1.22 + return (rpy[0], rpy[1], rpy[2], height, wide[0], wide[1], wide[2]) + + +def _v_plane_from_nv12(buf): + """NV12 V plane at half resolution. None when chroma is missing. + + High V is red. Used only to spot a taillight blob in the crop. + """ + try: + import numpy as np + width = int(buf.width) + height = int(buf.height) + stride = int(buf.stride) if getattr(buf, "stride", 0) else width + if width < 4 or height < 4 or stride < width: + return None + data = buf.data + uv_off = stride * height + uv_rows = height // 2 + need = uv_off + stride * uv_rows + if data is None or len(data) < need: + return None + uv = np.frombuffer(data, dtype=np.uint8, count=stride * uv_rows, offset=uv_off) + return uv.reshape(uv_rows, stride)[:, 1:width:2] + except Exception: + return None + + +def _crop(plane, box): + u0, v0, u1, v1 = box + height, width = plane.shape[:2] + x0 = max(0, int(u0)) + x1 = min(width, int(math_ceil(u1))) + y0 = max(0, int(v0)) + y1 = min(height, int(math_ceil(v1))) + if x1 - x0 < 4 or y1 - y0 < 4: + return None, None + patch = plane[y0:y1, x0:x1] + road_h = max(4, (y1 - y0) // 3) + ry0 = min(height - 1, y1) + ry1 = min(height, ry0 + road_h) + road = plane[ry0:ry1, x0:x1] if ry1 - ry0 >= 2 else patch[-road_h:, :] + return _own(patch), _own(road) + + +def _crop_v(v_plane, box): + """Half-resolution V crop for the same pixel box. None if it is too small.""" + if v_plane is None: + return None + try: + height, width = v_plane.shape[:2] + except Exception: + return None + u0, v0, u1, v1 = box + x0 = max(0, int(u0) // 2) + x1 = min(width, int(math_ceil(u1)) // 2) + y0 = max(0, int(v0) // 2) + y1 = min(height, int(math_ceil(v1)) // 2) + if x1 - x0 < 2 or y1 - y0 < 2: + return None + return _own(v_plane[y0:y1, x0:x1]) + + +def math_ceil(value: float) -> int: + iv = int(value) + return iv if iv == value or value < 0 else iv + 1 + + +def _buf_stale(buf) -> bool: + """True when timestamp_eof is a boot-time ns value older than half a second. + + A missing or zero timestamp is not stale: tests and a fresh subscribe + sometimes have no clock, and those frames are still scored. + """ + ts = getattr(buf, "timestamp_eof", None) + if ts is None: + return False + try: + stamp = int(ts) + except (TypeError, ValueError): + return False + if stamp <= 0: + return False + try: + now = time.clock_gettime_ns(time.CLOCK_BOOTTIME) + except Exception: + return False + age = now - stamp + if age < 0: + return False + return age > STALE_FRAME_NS + + +class _Cameras: + """VisionIPC for the road and wide cameras. + + connect() is checked. A failure is not cached as a live client, and the + next try waits on a backoff so a down camerad cannot spin this process. + """ + + def __init__(self): + self.road = None + self.wide = None + self._vipc = None + self._next_connect = {"road": 0.0, "wide": 0.0} + self._backoff = {"road": CONNECT_BACKOFF_S, "wide": CONNECT_BACKOFF_S} + self._fail = {"road": "", "wide": ""} + self.last_thumb = 0.0 + self.last_reason = "" + self.patch_sig: dict[int, tuple] = {} + self.chroma_v = None + self.chroma_uv = None + + def _types(self): + if self._vipc is None: + from msgq.visionipc import VisionIpcClient, VisionStreamType + self._vipc = (VisionIpcClient, VisionStreamType) + return self._vipc + + def _kind(self, stream: str): + _client, VisionStreamType = self._types() + if stream == "wide": + return VisionStreamType.VISION_STREAM_WIDE_ROAD + return VisionStreamType.VISION_STREAM_ROAD + + def _slot(self, stream: str): + return self.wide if stream == "wide" else self.road + + def _set_slot(self, stream: str, client) -> None: + if stream == "wide": + self.wide = client + else: + self.road = client + + def _healthy(self, client) -> bool: + if client is None: + return False + ask = getattr(client, "is_connected", None) + if ask is not None: + try: + if not bool(ask()): + return False + except Exception: + return False + buffers = getattr(client, "num_buffers", None) + if buffers is None: + return True + try: + return int(buffers) > 0 + except (TypeError, ValueError): + return False + + def _streams(self, prefer: str) -> list[str]: + """Preferred camera first, then the other one when it is actually up. + + An empty availability list means camerad has not advertised yet, so + both streams are still tried. A list that names only one camera is + respected. + """ + other = "road" if prefer == "wide" else "wide" + try: + VisionIpcClient, VisionStreamType = self._types() + ask = getattr(VisionIpcClient, "available_streams", None) + avail = ask("camerad", block=False) if ask is not None else None + except Exception: + return [prefer, other] + if not avail: + return [prefer, other] + wanted = { + "road": VisionStreamType.VISION_STREAM_ROAD, + "wide": VisionStreamType.VISION_STREAM_WIDE_ROAD, + } + have = [name for name in ("road", "wide") if wanted[name] in list(avail)] + if not have: + return [] + if prefer in have: + have.remove(prefer) + have.insert(0, prefer) + return have + + def _ensure(self, stream: str, now: float) -> str | None: + """None when the stream is connected. Otherwise a reason code.""" + client = self._slot(stream) + if self._healthy(client): + self._backoff[stream] = CONNECT_BACKOFF_S + self._fail[stream] = "" + return None + if now < self._next_connect[stream]: + return self._fail[stream] or "no_connection" + self._set_slot(stream, None) + self._next_connect[stream] = now + self._backoff[stream] + self._backoff[stream] = min(CONNECT_BACKOFF_MAX_S, max(CONNECT_BACKOFF_S, self._backoff[stream] * 2.0)) + try: + VisionIpcClient, _kind = self._types() + client = VisionIpcClient("camerad", self._kind(stream), True) + ok = client.connect(False) + except Exception: + self._fail[stream] = "no_connection" + return "no_connection" + if ok is not True or not self._healthy(client): + self._fail[stream] = "no_connection" + return "no_connection" + self._set_slot(stream, client) + self._backoff[stream] = CONNECT_BACKOFF_S + self._fail[stream] = "" + return None + + def _recv(self, stream: str, timeout_ms: int): + client = self._slot(stream) + if client is None: + return None, "no_connection" + try: + buf = client.recv(timeout_ms=timeout_ms) + except Exception: + self._set_slot(stream, None) + self._fail[stream] = "no_frame" + return None, "no_frame" + if buf is None: + if not self._healthy(client): + self._set_slot(stream, None) + self._fail[stream] = "no_connection" + return None, "no_connection" + return None, "no_frame" + if _buf_stale(buf): + try: + nxt = client.recv(timeout_ms=0) + except Exception: + nxt = None + if nxt is not None and not _buf_stale(nxt): + buf = nxt + else: + return None, "stale_frame" + try: + from openpilot.selfdrive.speedsignd.nv12 import y_plane_from_nv12 + plane = y_plane_from_nv12(buf) + except Exception: + return None, "model_error" + if plane is None: + return None, "no_frame" + try: + self.chroma_v = _v_plane_from_nv12(buf) + except Exception: + self.chroma_v = None + try: + self.chroma_uv = uv_planes_from_nv12(buf) + except Exception: + self.chroma_uv = None + return plane, "" + + def grab(self, wide: bool, now: float, deadline: float | None = None): + """Return (Y plane or None, reason). Reason is empty when a frame is ready.""" + self.chroma_v = None + self.chroma_uv = None + if deadline is not None and now >= deadline: + self.last_reason = "budget" + return None, "budget" + prefer = "wide" if wide else "road" + try: + streams = self._streams(prefer) + except Exception: + self.last_reason = "no_connection" + return None, "no_connection" + if not streams: + self.last_reason = "no_connection" + return None, "no_connection" + remain_s = RECV_TIMEOUT_MS / 1000.0 if deadline is None else deadline - now + if remain_s <= 0.0: + self.last_reason = "budget" + return None, "budget" + timeout_ms = max(0, min(RECV_TIMEOUT_MS, int(remain_s * 1000.0))) + if timeout_ms <= 0: + self.last_reason = "budget" + return None, "budget" + reason = "no_connection" + for stream in streams: + reason = self._ensure(stream, now) or "" + if reason: + continue + plane, reason = self._recv(stream, timeout_ms) + if plane is not None: + self.last_reason = "" + return plane, "" + if reason in ("no_frame", "stale_frame", "model_error"): + self.last_reason = reason + return None, reason + self.last_reason = reason or "no_connection" + return None, self.last_reason + + +def _project(hit, roll, pitch, yaw, height, focal, width, cam_h): + cx, cy = width / 2.0, cam_h / 2.0 + ground = project_road_point( + hit.x, hit.y, 0.0, roll=roll, pitch=pitch, yaw=yaw, + height=height, focal=focal, cx=cx, cy=cy, + ) + top = project_road_point( + hit.x, hit.y, 1.0, roll=roll, pitch=pitch, yaw=yaw, + height=height, focal=focal, cx=cx, cy=cy, + ) + return ground, top + + +def _vision_for(hit, cam, calib, cams: _Cameras, now: float): + """Return (score or None, microseconds, patch or None, fail reason).""" + started = time.monotonic() + + def elapsed(): + return (time.monotonic() - started) * 1e6 + + roll, pitch, yaw, height, wr, wp, wy = calib if calib is not None else _DEFAULT_CALIB + try: + sensor = "" if cam is None else cam.sensor + except Exception: + sensor = "" + width, cam_h, road_f, wide_f = _cam_size(sensor) + use_wide = hit.x < 20.0 or abs(hit.lateral) > 2.0 + ground, top = _project(hit, roll, pitch, yaw, height, road_f, width, cam_h) + if ground is not None and (ground[0] < width * 0.08 or ground[0] > width * 0.92): + use_wide = True + focal = road_f + if use_wide: + focal = wide_f + ground, top = _project(hit, roll + wr, pitch + wp, yaw + wy, height, focal, width, cam_h) + if ground is None or top is None: + return None, elapsed(), None, "roi_out_of_frame" + plane, reason = cams.grab(use_wide, now, now + VISION_BUDGET_S) + if plane is None: + return None, elapsed(), None, reason or "no_frame" + box = projection_box(ground[0], top[1], ground[1], focal, hit.x) + try: + patch, road = _crop(plane, box) + except Exception: + return None, elapsed(), None, "model_error" + if patch is None: + return None, elapsed(), None, "roi_out_of_frame" + v_crop = None + try: + v_crop = _crop_v(cams.chroma_v, box) + except Exception: + v_crop = None + try: + score = score_row_patches(patch, road, v_crop) + except Exception: + return None, elapsed(), None, "model_error" + if score is None or not getattr(score, "evaluated", False): + return None, elapsed(), None, "model_error" + return score, elapsed(), patch, "" + + +def _maybe_thumb(patch, now: float, last: float) -> float: + if now - last < THUMB_GAP_S: + return last + try: + os.makedirs(THUMB_DIR, exist_ok=True) + except OSError: + return last + path = os.path.join(THUMB_DIR, f"{int(now * 1000)}.ppm") + if save_ppm(path, patch): + prune_thumbs(THUMB_DIR) + return now + return last + + +def _finite_or_nan(value) -> float: + try: + num = float(value) + except (TypeError, ValueError): + return float("nan") + if not math.isfinite(num): + return float("nan") + return num + + +def _publish_vision(pm, messaging, sample, vision_us: float) -> None: + msg = messaging.new_message("pathObstacleVisionNAP", valid=True) + body = msg.pathObstacleVisionNAP + body.trackId = int(sample.track_id) & 0xFFFFFFFFFFFFFFFF + body.visionEvaluated = bool(sample.vision_evaluated) + body.visionConf = _finite_or_nan(sample.vision_conf) + body.visionConfHuman = _finite_or_nan(sample.vision_conf_human) + body.visionConfAnimal = _finite_or_nan(sample.vision_conf_animal) + body.visionConfObstacle = _finite_or_nan(sample.vision_conf_obstacle) + body.lightingScore = float(sample.lighting_score) + body.wRadar = float(sample.w_radar) + body.wVision = float(sample.w_vision) + body.fusedScore = float(sample.fused_score) + body.agree = bool(sample.agree) + obj = sample.object_class if sample.object_class in ("unknown", "human", "animal", "obstacle") else "unknown" + zone = sample.zone if sample.zone in ("none", "inPath", "entering", "roadside") else "none" + body.objectClass = obj + body.zone = zone + body.brakeGate = bool(sample.brake_gate) + body.chimed = bool(sample.chimed) + body.chimeReason = str(sample.chime_reason) + body.livelyScore = float(sample.lively_score) + body.visionUs = float(vision_us) + reason = str(getattr(sample, "vision_fail_reason", "") or "") + if reason and reason not in VISION_FAIL_REASONS: + reason = "model_error" + body.visionFailReason = reason + body.driveOverReason = str(getattr(sample, "drive_over_reason", "") or "") + pm.send("pathObstacleVisionNAP", msg) + + +class Helper: + """Blocks on radard. VisionIPC stays closed until a candidate is active.""" + + def __init__(self, det: PathObstacleDetector | None = None): + self.det = det or PathObstacleDetector() + self.cams = _Cameras() + self.log_on = True + self.chime_on = True + self.param_t = 0.0 + self.calib_t = 0.0 + self.next_vision = 0.0 + self.cam = None + self.gps = None + self.calib = _DEFAULT_CALIB + self._fail_logged = "" + self.cone = ConeCamState() + self.next_cone = 0.0 + self.cone_backoff = 0.0 + self.cone_hold_until = 0.0 + self.cone_start = 0 + + def refresh_params(self, params, now: float) -> None: + if now - self.param_t > 1.0: + prev_log = self.log_on + self.log_on = _bool_param(params, PARAM_OBSTACLE_LOG, True) + self.chime_on = _bool_param(params, PARAM_OBSTACLE_CHIME, True) + self.param_t = now + if self.log_on and not prev_log: + self.calib_t = 0.0 + if now - self.calib_t > CAL_REFRESH_S: + self.calib = _calibration_from_params(params) + self.calib_t = now + + def absorb(self, cam, gps) -> None: + if cam is not None: + self.cam = cam + if gps is not None: + self.gps = gps + + def on_radar(self, msg, now: float): + """Fusion and chime for one active radar hit. None if there is nothing to do. + + The camera is grabbed only when the 5 Hz budget allows it. + """ + if not self.log_on or msg is None: + if not self.log_on: + self.det.reset() + return None + try: + body = msg.pathObstacleNAP + except Exception: + return None + if not bool(getattr(body, "active", False)): + return None + hit = replace(hit_from_msg(body), lighting=_lighting_from(body, self.cam, self.gps)) + # Daytime lead: same as the old vehicle exclusion. The camera stays + # asleep and nothing is published. At night this flag is what lets + # a stalled car chime, so the grab below still runs. + if hit.model_lead and not is_night_lighting(hit.lighting): + return None + vision = None + vision_us = 0.0 + motion = 0.0 + patch = None + fail = "" + attempted = now >= self.next_vision + if attempted: + vision, vision_us, patch, fail = _vision_for(hit, self.cam, self.calib, self.cams, now) + if fail and fail != self._fail_logged: + self._fail_logged = fail + try: + from openpilot.common.swaglog import cloudlog + cloudlog.warning("pathobstacled vision %s", fail) + except Exception: + pass + elif not fail: + self._fail_logged = "" + gap = 1.0 / VISION_HZ + if vision_us > VISION_BUDGET_S * 1e6: + gap = max(gap, 0.40) + self.next_vision = now + gap + if patch is not None and hit.track_id: + sig = patch_signature(patch) + prev = self.cams.patch_sig.get(int(hit.track_id)) + if prev is not None: + motion = patch_change_score(prev, sig) + self.cams.patch_sig[int(hit.track_id)] = sig + if len(self.cams.patch_sig) > 32: + self.cams.patch_sig.pop(next(iter(self.cams.patch_sig))) + if vision is not None and patch is not None and vision.conf >= 0.30: + self.cams.last_thumb = _maybe_thumb(patch, now, self.cams.last_thumb) + sample = self.det.commit(hit, vision, chime_enabled=self.chime_on, now=now, vision_motion=motion) + if attempted and vision is None: + sample = replace(sample, vision_fail_reason=fail or "no_frame") + return sample, vision_us + + +def _cone_geom(cam, calib) -> CamGeom: + roll, pitch, yaw, height, _wr, _wp, _wy = calib if calib is not None else _DEFAULT_CALIB + try: + sensor = "" if cam is None else cam.sensor + except Exception: + sensor = "" + width, cam_h, road_f, _wide_f = _cam_size(sensor) + return CamGeom(width=width, height=cam_h, focal=road_f, roll=roll, pitch=pitch, yaw=yaw, cam_height=height) + + +class _IdleSched: + """SCHED_IDLE for the cone scoring only, then back to SCHED_OTHER (nice 19 stays). + + Leaving SCHED_IDLE needs privilege: an unprivileged thread cannot come back + (EPERM), which would leave the obstacle chime path idle-scheduled too. So + the switch is made only as root; otherwise scoring stays at nice 19, the + lowest SCHED_OTHER priority, under the same 8 ms budget. + """ + + def __enter__(self): + self.ok = False + try: + if os.geteuid() != 0: + return self + os.sched_setscheduler(0, os.SCHED_IDLE, os.sched_param(0)) + self.ok = True + except (AttributeError, OSError): + pass + return self + + def __exit__(self, *exc): + if self.ok: + try: + os.sched_setscheduler(0, os.SCHED_OTHER, os.sched_param(0)) + except (AttributeError, OSError): + pass + return False + + +def cone_frame_drop(driving_model) -> bool: + """True when modeld reports dropped frames (drivingModelData.frameDropPerc).""" + if driving_model is None: + return False + try: + perc = float(driving_model.frameDropPerc) + except Exception: + return False + return math.isfinite(perc) and perc > CONE_DROP_PERC + + +def on_cone(helper: Helper, body, now: float, driving_model=None, frame=None): + """Score the radar cone line in one ROAD frame. Returns the log dict or None. + + `frame` (y, u, v) is for tests; on device the frame comes from VisionIPC. + Nothing reads the result: it is only logged. + """ + try: + side = int(body.side) + count = int(body.count) + lats = (float(body.latNear), float(body.latMid), float(body.latFar)) + radar_active = bool(body.active) + except Exception: + return None + if side == 0 or count <= 0 or not all(math.isfinite(v) for v in lats): + return None + if cone_frame_drop(driving_model): + helper.cone_backoff = min(CONE_DROP_BACKOFF_MAX_S, max(CONE_DROP_BACKOFF_S, helper.cone_backoff * 2.0)) + helper.cone_hold_until = now + helper.cone_backoff + return None + if now < helper.cone_hold_until or now < helper.next_cone: + return None + helper.cone_backoff = 0.0 + helper.next_cone = now + 1.0 / CONE_HZ + started = time.monotonic() + deadline = started + CONE_BUDGET_S + reason = "" + scores = [] + over = False + with _IdleSched(): + if frame is not None: + y, u, v = frame + else: + y, reason = helper.cams.grab(False, now, deadline) + uv = helper.cams.chroma_uv + u, v = uv if uv is not None else (None, None) + if y is not None and u is None: + reason = "no_frame" + if not reason and y is not None: + geom = _cone_geom(helper.cam, helper.calib) + try: + scores, over = score_line(y, u, v, geom, lats, deadline=deadline, start=helper.cone_start) + except Exception: + scores, reason = [], "model_error" + if over: + reason = "budget" + helper.cone_start = (helper.cone_start + max(1, len(scores))) % len(CONE_WINDOWS_M) + else: + helper.cone_start = 0 + ms = (time.monotonic() - started) * 1e3 + if ms > CONE_BUDGET_S * 1e3: + helper.next_cone = now + max(1.0 / CONE_HZ, 0.40) + confirmed = helper.cone.update(side, scores, now) + if not helper.cone.should_log(now): + return None + return { + "side": side, + "radar_active": radar_active, + "radar_count": count, + "confirmed": confirmed, + "n_hits": sum(1 for sc in scores if sc.hit), + "n_scored": len(scores), + "hits": [int(sc.x0) for sc in scores if sc.hit], + "conf": round(max((sc.conf for sc in scores), default=0.0), 3), + "ms": round(ms, 2), + "reason": reason, + } + + +def _log_cone(event: dict) -> None: + try: + from openpilot.common.swaglog import cloudlog + cloudlog.event("cone_cam", **event) + except Exception: + pass + + +def _latest_body(messaging, sock): + last = None + while True: + msg = messaging.recv_one_or_none(sock) + if msg is None: + return last + try: + last = getattr(msg, msg.which()) + except Exception: + last = msg + + +def _run() -> None: + import cereal.messaging as messaging + from openpilot.common.params import Params + + params = Params() + from openpilot.common.gps import get_gps_location_service + # No carState, modelV2, radarState, liveTracks, deviceState, or + # liveCalibration. Those services are at or near the msgq reader cap. + # Sun uses whichever GPS this device publishes. Calibration is the param. + gps_service = get_gps_location_service(params) + # coneLineNAP (radard, 8 Hz) and drivingModelData (modeld frame drops) are + # far below the msgq reader cap; test_msgq_reader_budget counts them. + sock = messaging.sub_sock("pathObstacleNAP", timeout=RADAR_TIMEOUT_MS) + cone_sock = messaging.sub_sock("coneLineNAP", conflate=True) + dmd_sock = messaging.sub_sock("drivingModelData", conflate=True) + cam_sock = messaging.sub_sock("roadCameraState", conflate=True) + gps_sock = messaging.sub_sock(gps_service, conflate=True) + pm = messaging.PubMaster(["pathObstacleVisionNAP"]) + poller = messaging.Poller() + poller.registerSocket(sock) + poller.registerSocket(cone_sock) + helper = Helper() + driving_model = None + + while True: + ready = poller.poll(RADAR_TIMEOUT_MS) + now = time.monotonic() + helper.refresh_params(params, now) + if not helper.log_on: + helper.det.reset() + _latest_body(messaging, sock) + _latest_body(messaging, cone_sock) + continue + if not ready: + continue + helper.absorb( + _latest_body(messaging, cam_sock), + _latest_body(messaging, gps_sock), + ) + dmd = _latest_body(messaging, dmd_sock) + if dmd is not None: + driving_model = dmd + # Obstacle first, unchanged: every queued pathObstacleNAP in order. + while True: + msg = messaging.recv_one_or_none(sock) + if msg is None: + break + try: + active = bool(msg.pathObstacleNAP.active) + except Exception: + continue + if not active: + continue + try: + result = helper.on_radar(msg, time.monotonic()) + if result is None: + continue + sample, vision_us = result + _publish_vision(pm, messaging, sample, vision_us) + except Exception: + continue + cone = _latest_body(messaging, cone_sock) + if cone is None: + continue + try: + event = on_cone(helper, cone, time.monotonic(), driving_model) + if event is not None: + _log_cone(event) + except Exception: + continue + + +def main() -> None: + from openpilot.common.realtime import drop_realtime, set_core_affinity + drop_realtime() + set_core_affinity(CORES) + try: + os.nice(NICE) + except OSError: + pass + _run() + + +if __name__ == "__main__": + main() diff --git a/third_party/acados/acados_template/gnsf/__init__.py b/selfdrive/pathobstacled/tests/__init__.py similarity index 100% rename from third_party/acados/acados_template/gnsf/__init__.py rename to selfdrive/pathobstacled/tests/__init__.py diff --git a/selfdrive/pathobstacled/tests/cone_frames/r17b_164217.jpg.b64 b/selfdrive/pathobstacled/tests/cone_frames/r17b_164217.jpg.b64 new file mode 100644 index 00000000000000..15cb94641ba403 --- /dev/null +++ b/selfdrive/pathobstacled/tests/cone_frames/r17b_164217.jpg.b64 @@ -0,0 +1,1638 @@ +/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQcKDgwPDg4M +DQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0QGBgYGBgY +GBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/wAARCAHAB4gDASIA +AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA +AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 +ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm +p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA +AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx +BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg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9ACZ9acMECpUWMjg80wx4bINJO4CGMHkYzTCnGABTwpAzSjA5NMCAjbxupBgnk1JIMjAqLk +CncBQcE5pAQDSA0mcGmA/wCX0NNKjPWjdxS4oAT8aQ00nmkNOwrgVHrTSoNOzxQTQkIYVFJgelOP +FJ3osO40jNJind+KTvTEBU9qQqRTjQM0AR/Nt96QN2NPNJjvSuA0N60obJpx6UlToA3d83tRu+b2 +peGFHCiqugGZ4xRRR3pgFFFITxQAfWj6UlFABRRRQAUHpRmkzQAHrSUp60lABSYFL3ooATFJinDp +SVPMAlFFFSAUUUUAKRSUUnrVcoC0Un8NApN3AWkzR3FJRYAopx7UHqeaQ7DaKKKBBSjrQBS0DSG0 +UUUxH//Z diff --git a/selfdrive/pathobstacled/tests/cone_frames/r17b_164220.jpg.b64 b/selfdrive/pathobstacled/tests/cone_frames/r17b_164220.jpg.b64 new file mode 100644 index 00000000000000..dc7d15cf67c34c --- /dev/null +++ b/selfdrive/pathobstacled/tests/cone_frames/r17b_164220.jpg.b64 @@ -0,0 +1,1564 @@ +/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQcKDgwPDg4M +DQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0QGBgYGBgY +GBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/wAARCAHAB4gDASIA +AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA +AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 +ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm +p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW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6crAZouBIG5xQMjnII9KacMKUHaOtIB/XpQNobb +imK+aXrQApxQcU089DRn5sdaAF7nIppI5GOlOHHakZgDQAzPtRxStgsaOARxVAMwAPlprKCM96ed +tIcUAM2ntUTIAf7tSnbjrQdpA4zQBEMlSGH40A7QPmqTFMPbPFAri71z1xTt2RTD9yosHPFAXLGR +SdaiZsAjGKcnKCgQ7NIaYWJyKcFyoFA7C0UUY70BYQ5x2pg60px2zQOvUCgYlFB6UgoJEooPWjHN +ABQCKMc0gBzQApIIptFAOKACiiigBO9BNBNIetAC7TRikooAUE460UlFAH//2Q== diff --git a/selfdrive/pathobstacled/tests/cone_frames/r17b_164810.jpg.b64 b/selfdrive/pathobstacled/tests/cone_frames/r17b_164810.jpg.b64 new file mode 100644 index 00000000000000..e359edd39c9122 --- /dev/null +++ b/selfdrive/pathobstacled/tests/cone_frames/r17b_164810.jpg.b64 @@ -0,0 +1,1216 @@ +/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQcKDgwPDg4M +DQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0QGBgYGBgY +GBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/wAARCAHAB4gDASIA +AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA +AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 +ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm +p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA +AwEBAQEBAQEBAQAAAAAAAAECAw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5prJIVDIi/nQF+jGlmQ/Owx/s1E +6wMPmlc1Ntm25Kx4+tNZZMZygH+zTWg3sQiKAD5Qz+5pysynAijUep5NKqvJwpxTmgKDLSgfhSZK +Q0uW6ufoopVZ0XJDH603axHylmPbtUbG4U/OMD60Fc3ckMqMMlefcUwsv8PlofVqiLA9aQrGeTVc +pMR+4g48/djsKRpGJyCf5UzzFRtoUn6Co5GikOCrCn5D0H7s8M+PxpTGw6N+uareTbHqzr7CpFXa +MxCT6k0mgGt5mcbHYe3FR+YwyMkey1I043kMzH2zmo5PmUkOy+wp8wC+bk7SufdzR1Hb6CoG8vPA +JoV2H3RgVArEhWU8jav61GTNuwQWNPO8/dkU+5pOc4abGey0rlIRklK4wqimlZMAD5se1SFEXnzG +J9zUbZbPzgD3OaAsMZsH5+B6KaKkWKQD5Sv1IopXCx//2Q== diff --git a/selfdrive/pathobstacled/tests/cone_frames/r17b_164850.jpg.b64 b/selfdrive/pathobstacled/tests/cone_frames/r17b_164850.jpg.b64 new file mode 100644 index 00000000000000..6ff493ba19ac9a --- /dev/null +++ b/selfdrive/pathobstacled/tests/cone_frames/r17b_164850.jpg.b64 @@ -0,0 +1,1100 @@ +/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQcKDgwPDg4M +DQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0QGBgYGBgY +GBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/wAARCAHAB4gDASIA +AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA +AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 +ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1d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b64 b/selfdrive/pathobstacled/tests/cone_frames/r17c_173005.jpg.b64 new file mode 100644 index 00000000000000..fadfc97c69d381 --- /dev/null +++ b/selfdrive/pathobstacled/tests/cone_frames/r17c_173005.jpg.b64 @@ -0,0 +1,1411 @@ +/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQcKDgwPDg4M +DQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0QGBgYGBgY +GBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/wAARCAHAB4gDASIA +AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA +AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 +ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm +p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA +AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx +BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK +U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3 +uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD4f5Pe +l59aSis2A7n1oJwOtM9qQjtTuA8HnvWnEWh0hmBGGrK6c/pWlIMaWoVutKb0NIPUzzKxAy2R3pM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R+ +VLxkDoaXaTxmmE8e4pgOOeoOQKARn0zSBiBnHHc0rngHH0pANIJGPU8kUhUhc5/On/w5brmm85+b +pQAgZgeCDx1pwPy8ZzSYAIA6UhyvNMY7gA5J+tJ074JpN3GehxT+qg0BcaxYjI44pI8Z544705iQ +yt60E5dTjGaVxXE4AOetJvyOvXtSjiVuc+lBGX6UA2IR+8x2x3prfe9qX+PHSk7YPIpjFIK5yeaB +wCD+dIW6U5wOoOCe1DENXmjK7hjI9aXovTNDLtVSec0gAk7qHBU59aMA04gkc8ikITOeKb0zmlJH +UcYoA7mgBSMNyaack5HFO6scikBycjj1pgDdBg5peCMH86aMYz3pO/NIByqrEk9PWnEhOFpr5DHj +AppPqKdrgKTzkUHJGM0Ejg9KTqeO1FgEBwMGnE4zTe1KQMZ9qbQ2GM/SjgcikHrQOM07CDPTNLn5 +abin4OKgBOgpOMdaD1wKON1ABknHagqRg0dKXOVx2p8oBmk29qUD5+aO2KOUBTgYIpOe9J3xSjJb +PpTkAEHbik5xSsWY5NAHHHWpATjpRzigctzQc84oAXpSZ5oPTmjigBTz948+tJ/CMnmg5PFIeuKd +wF7+1GcGjikPT3FIB3Y0L60nG3mgcNQAHrg0cjvQcE5pOM0AKenSkzk9KUHPem989KdwDkHFOPUU +mBnmkAzmiwCk0dPajr1pOjU0ApA65o4Io70n8VSAUEDNByTRmgBeCKTgUe9HsaAE74owM0dHo6Gn +5gB4NB+9RnmjvmjyAOlHakPPNISR1HFIBT0xRxjBoOOmaT2oAXrRSYo70AITg55petCnjNA602rA +FGKXFIaEAuKD0FGecCk70MBccZFIO+RS9sZoGBSAaB60dyAcUppDgHJoAPoKQc8Zz60Y+UCkHWru +A7GOnFJnHQYpp6mkPNLlAdn5cUcd+tJRS8gFPXikooNHmAUUd6KQCHpQKDRQA3mind6Kdx3P/9k= diff --git a/selfdrive/pathobstacled/tests/cone_frames/r17c_173045.jpg.b64 b/selfdrive/pathobstacled/tests/cone_frames/r17c_173045.jpg.b64 new file mode 100644 index 00000000000000..13fac6e5212b6c --- /dev/null +++ b/selfdrive/pathobstacled/tests/cone_frames/r17c_173045.jpg.b64 @@ -0,0 +1,1348 @@ +/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQcKDgwPDg4M +DQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0QGBgYGBgY +GBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/wAARCAHAB4gDASIA +AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA +AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 +ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm +p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA +AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx +BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK +U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3 +uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5NXaA +yMOD2FQyRM6AKxHvVhYCzfMTQbdwwweK5U9TrlBMfCrxSxt5hDetW2eYRq4m+bdk471UEUhT5mJP +ahUlUYB460m7jcS/BJnzC0u0sMc1n3c1xLckgk+pFP2v5fJ5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iRR7Gk5F +G0bc0gBoADk80Zo/ho28ZoC4ZGMYozg+tN7UZPSgBTR9aCec00nmgBx5PBpD9aM/NR1agLiDpRS/ +w00daADPvR+FKTg0HkcUBcb09qUc9qbnmjv6UAxRjpSnOKaXGaXOTQITjOCKOnSgmigLh3zRmkzz +TQOaBDuppDgdfzoNIc44GaBi8ZyKTBIwaBSDkGgQf8CFFIV5ooFc/9k= diff --git a/selfdrive/pathobstacled/tests/cone_frames/r17c_173203.jpg.b64 b/selfdrive/pathobstacled/tests/cone_frames/r17c_173203.jpg.b64 new file mode 100644 index 00000000000000..8f38407d953cfc --- /dev/null +++ b/selfdrive/pathobstacled/tests/cone_frames/r17c_173203.jpg.b64 @@ -0,0 +1,1433 @@ +/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQcKDgwPDg4M +DQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0QGBgYGBgY +GBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/wAARCAHAB4gDASIA +AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA +AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 +ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm +p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA +AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx +BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcY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BxShs80WC4vejIxk0lAPekUOzRTRg80pNAha +TvR3paewtxvfrRn3opM88ijcNhc9jSdehprHJpxOG9qYhMOBxg0uSR0FKzYHFMzQK410JGfWq0kK +yfwjH0q1jPFJt4q0rBYyJLbbnaarng4IralizVCeHn3oUiGimOOhxTlkZTlSePShl2nGaTtV7iuW +UvGIAcZHtVuKVGGYyAe4NZWDmlDMucHFS4lXNkA4+9mo+DJtcfQiqKXcy45J+tWY7iNvvDBqHFor +mJ2jQoSDk1EodXxnA+tS+Ymw4FNyGUcUhti7S2RuP40wF0O0N+tE2B0yGFRtINwOzn+dJagx6yqH +3E8j1qXcODk81AQpO7HNOBJ+Uj8KBoDsZiENMaMg7jx9Kc0So2V4oL5wH496AJFePoWJ96C4IOOV +poVCvygZpFVkOOg9aAFZUB4B/Cm8o/XH1p8gCkYc5pHD7ck5ouFhysWfqPwqOTO7oBSOAACuDmkD +DZ82aZNxQcjHFFR7fTIoquULH//Z diff --git a/selfdrive/pathobstacled/tests/cone_frames/r17c_173231.jpg.b64 b/selfdrive/pathobstacled/tests/cone_frames/r17c_173231.jpg.b64 new file mode 100644 index 00000000000000..a0e95107bba26f --- /dev/null +++ b/selfdrive/pathobstacled/tests/cone_frames/r17c_173231.jpg.b64 @@ -0,0 +1,1344 @@ +/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQcKDgwPDg4M +DQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0QGBgYGBgY +GBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/wAARCAHAB4gDASIA +AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA +AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJic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6UCsH0pe1IfuGkP8Aq6BiEdyabnFG +c8mkNBmBFJ9ad2pvegA7dKPag9KPegA6DFFByRRQAUDrSA0CgBaKAaKAEOB7UvBpp6UUAGcGlJ4z +SUUwF3UnFIRlTSKMDmgBe/NI33qdjOaaRjrQNOw4dOfzpp96XGF+WkIGOaRYEc8UgYgkfpTj92mY +oFbSxWntpVb7Rb8EckCp7W6S5GyQ7ZB696k9qqXFqZF8yP5ZB3HenvoTtqaDIV4JpMYqla3xP7q4 +7cAnqKuOrKQTUcvcpaifWg+1G0ntRtOaoYmR3pDtzS4pCoNAACaMmlAFIQKAHA5pdoxTcrnNKGUm +gOlxCooFSeYmeVpC6Z+7U3Fcjo4pxYDtTXYEg5qhi5paTzGJ5pGbNK7AkxngCjBHGKaHK9KC7Eda +izCw7B9KaQSaC7etJnPWmu4kP2HrikKkUm4g43U1mJ70WEPxSUUUgDOKXNMp2eM0AHy5pflzTcij +jNADiVpp60UhNAEYz3NOBGaYD+dIM7zWg9h56005xwaXtSHlaChaXNRkt34o3HFAh9JwTg0m4Ywa +RcbqAH0hYDrTM8UE96AH4APFBxzk0hXjimk9KACiigZoATPNBNGOaXFADd3NLzSGigBCTRk07Oet +IfagBMc9aCfSg+tIDmgnmFJpOe1FFBIZ5pCTRmjNA73AijJpRxTfegcR1HFN70Y4oJAgU2ncZoyK +AG9sUgp5x+lIwoHYbvBNKDxTTnHFIN3enYQ/6Ug5NR7iOtLvzQBIabxik3g9aWkAUUUUAf/Z diff --git a/selfdrive/pathobstacled/tests/test_cone_cam.py b/selfdrive/pathobstacled/tests/test_cone_cam.py new file mode 100644 index 00000000000000..868c0b9dd36929 --- /dev/null +++ b/selfdrive/pathobstacled/tests/test_cone_cam.py @@ -0,0 +1,332 @@ +"""Camera cone confirm (log only) on real Oct 10, 2026 ROAD-camera frames. + +Fixtures are fcamera frames (OX03C10, 1928x1208) from dongle 1c95345a3286a5db, +rows 760-1208 only (the boxes never reach above row ~800), JPEG, base64 so +they push as text. They are converted to BT.601 limited-range YUV 4:2:0, the +same planes camerad hands VisionIPC. + + r17c_173045 0000017c 17:30:45 CT drums in the closed left lane + r17c_173203 0000017c 17:32:03 CT orange/white posts on the left line + r17c_173231 0000017c 17:32:31 CT drums on the left + r17b_164810 0000017b 16:48:10 CT real drums, low sun ahead: washed out, + the camera abstains (radar keeps the line) + r17b_164217 0000017b 16:42:17 CT town: orange/white striped building, trucks + r17b_164220 0000017b 16:42:20 CT town: same building, box truck + r17b_164850 0000017b 16:48:50 CT grass and a curve, no cones + r17c_173005 0000017c 17:30:05 CT grass and an intersection, no cones +""" +import base64 +import io +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest + +from openpilot.selfdrive.pathobstacled import cone_cam as cc +from openpilot.selfdrive.pathobstacled.pathobstacled import _IdleSched as _REAL_IDLE + +FIX = Path(__file__).resolve().parent / "cone_frames" +TOP = 760 +G17B = cc.CamGeom(roll=0.00067, pitch=-0.0791, yaw=-0.0191, cam_height=1.26) +G17C = cc.CamGeom(roll=0.00068, pitch=-0.0791, yaw=-0.0192, cam_height=1.254) +_CACHE = {} + + +def _frame(name): + if name in _CACHE: + return _CACHE[name] + from PIL import Image + raw = base64.b64decode((FIX / f"{name}.jpg.b64").read_bytes()) + rgb = np.asarray(Image.open(io.BytesIO(raw)).convert("RGB")).astype(np.float32) + full = np.zeros((1208, 1928, 3), dtype=np.float32) + full[TOP:TOP + rgb.shape[0]] = rgb + r, g, b = full[..., 0], full[..., 1], full[..., 2] + y = 16 + 0.257 * r + 0.504 * g + 0.098 * b + u = 128 - 0.148 * r - 0.291 * g + 0.439 * b + v = 128 + 0.439 * r - 0.368 * g - 0.071 * b + u = u.reshape(604, 2, 964, 2).mean((1, 3)) + v = v.reshape(604, 2, 964, 2).mean((1, 3)) + + def q(a): + return np.clip(np.rint(a), 0, 255).astype(np.uint8) + _CACHE[name] = (q(y), q(u), q(v)) + return _CACHE[name] + + +def _hits(name, geom, lats): + y, u, v = _frame(name) + scores, over = cc.score_line(y, u, v, geom, lats) + assert not over + return [s for s in scores if s.hit], scores + + +@pytest.mark.parametrize("name,lats", [ + ("r17c_173045", (-3.70, -3.77, -3.88)), + ("r17c_173203", (-1.70, -1.70, -1.70)), + ("r17c_173231", (-3.46, -3.15, -2.86)), +]) +def test_oct10_left_cones_confirm(name, lats): + hits, scores = _hits(name, G17C, lats) + assert len({(s.x0, s.x1) for s in hits}) >= cc.CONFIRM_HITS + assert all(s.bands >= 1 for s in hits) + state = cc.ConeCamState() + assert state.update(1, scores, 10.0) + # Held for 1 s, then it needs a fresh agreeing frame. + assert state.update(1, [], 10.9) + assert not state.update(1, [], 11.2) + + +def test_oct10_cones_do_not_hit_on_the_wrong_side(): + hits, _ = _hits("r17c_173045", G17C, (3.5, 3.5, 3.5)) + assert hits == [] + + +def test_oct10_low_sun_pass_abstains(): + # Real drums, but backlit to V~142 / U~121 against road 131 / 124: no reliable + # chroma. The camera must not guess; the radar line stands on its own. + hits, scores = _hits("r17b_164810", G17B, (-1.65, -1.65, -1.64)) + assert hits == [] + assert not cc.ConeCamState().update(1, scores, 0.0) + + +@pytest.mark.parametrize("name", ["r17b_164217", "r17b_164220"]) +def test_oct10_orange_building_and_trucks_never_confirm(name): + for lat in (1.5, 2.0, 2.5, 3.0, 3.5, 4.0, -1.5, -2.0, -2.5, -3.0, -3.5, -4.0): + hits, scores = _hits(name, G17B, (lat, lat, lat)) + assert len(hits) < cc.CONFIRM_HITS, (name, lat, [(s.x0, s.orange_px, s.bands) for s in hits]) + assert not cc.ConeCamState().update(1 if lat < 0 else -1, scores, 0.0) + + +def test_oct10_town_sequence_never_confirms(): + state = cc.ConeCamState() + t = 0.0 + for name in ("r17b_164217", "r17b_164220", "r17b_164217", "r17b_164220"): + for lat in (3.0, 4.0): + _, scores = _hits(name, G17B, (lat, lat, lat)) + assert not state.update(-1, scores, t) + t += 0.2 + + +@pytest.mark.parametrize("name,geom", [("r17b_164850", G17B), ("r17c_173005", G17C)]) +def test_oct10_grass_has_no_hits(name, geom): + for lat in (-4.0, -3.0, -2.0, 2.0, 3.0, 4.0): + hits, _ = _hits(name, geom, (lat, lat, lat)) + assert hits == [], (name, lat) + + +def test_cpu_cost_per_frame(): + frames = [("r17c_173045", G17C, (-3.70, -3.77, -3.88)), ("r17c_173231", G17C, (-3.46, -3.15, -2.86)), + ("r17b_164217", G17B, (3.0, 3.0, 3.0))] + for name, _, _ in frames: + _frame(name) + # Best of 5 batches: a shared CI runner's load is noise, not our cost. + n = 12 + batches = [] + for _ in range(5): + t0 = time.perf_counter() + for i in range(n): + name, geom, lats = frames[i % len(frames)] + y, u, v = _frame(name) + cc.score_line(y, u, v, geom, lats) + batches.append((time.perf_counter() - t0) * 1e3 / n) + per_frame_ms = min(batches) + # About 1-4 ms on a desktop core (5 Hz: 0.5-2 % of one core). The + # device enforces the 8 ms budget with a deadline (next test). + assert per_frame_ms < cc.BUDGET_S * 1e3, per_frame_ms + + +def test_budget_deadline_stops_and_rotates(): + y, u, v = _frame("r17c_173231") + scores, over = cc.score_line(y, u, v, G17C, (-3.46, -3.15, -2.86), deadline=time.monotonic() - 1.0) + assert over and scores == [] + scores, over = cc.score_line(y, u, v, G17C, (-3.46, -3.15, -2.86), start=3) + assert not over and scores[0].x0 == cc.WINDOWS_M[3][0] + + +class _NoIdle: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +@pytest.fixture(autouse=True) +def _no_idle_sched(monkeypatch): + # SCHED_IDLE on a shared CI box starves the scorer and makes timing flaky. + # test_cone_scoring_runs_under_sched_idle checks the real switch. + import openpilot.selfdrive.pathobstacled.pathobstacled as po + monkeypatch.setattr(po, "_IdleSched", _NoIdle) + + +def test_cone_scoring_runs_under_sched_idle(monkeypatch): + import os + calls = [] + monkeypatch.setattr(os, "sched_setscheduler", lambda pid, pol, param: calls.append(pol), raising=False) + monkeypatch.setattr(os, "geteuid", lambda: 0) + with _REAL_IDLE(): + pass + assert calls == [os.SCHED_IDLE, os.SCHED_OTHER] + # Unprivileged: SCHED_IDLE could not be left again, so it is not entered. + calls.clear() + monkeypatch.setattr(os, "geteuid", lambda: 1000) + with _REAL_IDLE(): + pass + assert calls == [] + + +def _helper(): + from openpilot.selfdrive.pathobstacled.pathobstacled import Helper + h = Helper() + h.calib = (0.00068, -0.0791, -0.0192, 1.254, 0.0, 0.0, 0.0) + h.cam = SimpleNamespace(sensor="ox03c10") + return h + + +def _cone(side=1, count=4, lats=(-3.46, -3.15, -2.86), active=True): + return SimpleNamespace(side=side, count=count, latNear=lats[0], latMid=lats[1], latFar=lats[2], active=active) + + +def test_on_cone_logs_at_most_2hz_and_confirms(): + from openpilot.selfdrive.pathobstacled.pathobstacled import on_cone + h = _helper() + frame = _frame("r17c_173231") + events = [] + t = 100.0 + while t < 102.0: + ev = on_cone(h, _cone(), t, SimpleNamespace(frameDropPerc=0.0), frame=frame) + if ev is not None: + events.append((t, ev)) + t += 0.05 + assert 3 <= len(events) <= 5 + gaps = [b[0] - a[0] for a, b in zip(events, events[1:], strict=False)] + assert min(gaps) >= 0.5 - 1e-6 + assert all(ev["side"] == 1 and ev["radar_count"] == 4 for _, ev in events) + assert any(ev["confirmed"] and ev["n_hits"] >= 2 for _, ev in events) + assert all(ev["reason"] in ("", "budget") for _, ev in events) + + +def test_on_cone_ignores_empty_lines_and_backs_off_on_model_drops(): + from openpilot.selfdrive.pathobstacled.pathobstacled import on_cone + h = _helper() + frame = _frame("r17c_173231") + assert on_cone(h, _cone(side=0, count=0), 1.0, None, frame=frame) is None + # modeld dropping frames: no grab, and a growing hold-off. + assert on_cone(h, _cone(), 2.0, SimpleNamespace(frameDropPerc=3.0), frame=frame) is None + assert h.cone_hold_until == pytest.approx(2.5) + assert on_cone(h, _cone(), 2.1, SimpleNamespace(frameDropPerc=3.0), frame=frame) is None + assert h.cone_hold_until == pytest.approx(3.1) + assert on_cone(h, _cone(), 2.6, SimpleNamespace(frameDropPerc=0.0), frame=frame) is None + ev = on_cone(h, _cone(), 3.2, SimpleNamespace(frameDropPerc=0.0), frame=frame) + assert ev is not None and ev["n_scored"] >= 1 + + +def test_no_gpu_libraries_are_imported(): + code = """ +import sys +import openpilot.selfdrive.pathobstacled.pathobstacled +import openpilot.selfdrive.pathobstacled.cone_cam +import openpilot.selfdrive.speedsignd.nv12 +gpu = ('tinygrad', 'onnx', 'onnxruntime', 'pyopencl', 'torch') +bad = [m for m in sys.modules if m.split('.')[0] in gpu or 'opencl' in m.lower() + or m.startswith('openpilot.selfdrive.modeld')] +print(','.join(bad)) +sys.exit(1 if bad else 0) +""" + out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) + assert out.returncode == 0, out.stdout + out.stderr + root = Path(__file__).resolve().parents[1] + for src in ("cone_cam.py", "pathobstacled.py"): + text = (root / src).read_text() + for lib in ("tinygrad", "onnx", "OpenCL", "pyopencl", "torch", "GPU="): + assert f"import {lib}" not in text and f"from {lib}" not in text, (src, lib) + + +def test_vectorized_patch_stats_match_the_list_path(): + import openpilot.selfdrive.controls.lib.path_obstacle as po + rng = np.random.default_rng(7) + for trial in range(40): + h, w = int(rng.integers(2, 160)), int(rng.integers(2, 220)) + a = rng.integers(0, 256, (h, w)).astype(np.uint8) + if trial % 3 == 0: + a[int(rng.integers(0, h)):, :] = int(rng.integers(190, 256)) + road = rng.integers(0, 256, (int(rng.integers(1, 60)), int(rng.integers(1, 260)))).astype(np.uint8) if trial % 4 else None + vp = rng.integers(100, 256, (max(1, h // 2), max(1, w // 2))).astype(np.uint8) if trial % 2 else None + fast = po.metrics_from_rows(a, road) + slow = po.metrics_from_rows(a.tolist(), None if road is None else road.tolist()) + for k in fast: + assert np.allclose(fast[k], slow[k], atol=1e-6), (k, fast[k], slow[k]) + assert np.allclose(po.crop_light_stats(a, vp), po.crop_light_stats(a.tolist(), None if vp is None else vp.tolist()), atol=1e-9) + + +def test_selfdrived_still_ignores_path_obstacle_by_name(): + root = Path(__file__).resolve().parents[2] + assert "'pathObstacleNAP'" in (root / "selfdrived/selfdrived.py").read_text() + + +# ---- Oct 13 2026 camera-confirm fixes (still log only) ---- + +def _score(x0, x1, hit): + return cc.CropScore(x0, x1, hit, 0.9 if hit else 0.1, 50 if hit else 0, 10, 2 if hit else 0, (0, 0, 1, 1)) + + +def _all6(hits): + return [_score(a, b, (a, b) in hits) for a, b in cc.WINDOWS_M] + + +def test_oct13_zero_hit_frame_clears_confirmed(): + # 07:57:37 / 08:06:33 / 08:07:31: confirmed was reported on a 0-hit frame. + st = cc.ConeCamState() + assert st.update(1, _all6({cc.WINDOWS_M[1], cc.WINDOWS_M[2]}), 10.0) + assert not st.update(1, _all6(set()), 10.2) + assert not st.confirmed(10.3) + + +def test_oct13_budget_split_frames_can_confirm_together(): + st = cc.ConeCamState() + first = [_score(*cc.WINDOWS_M[i], i == 1) for i in range(3)] + second = [_score(*cc.WINDOWS_M[i], i == 4) for i in range(3, 6)] + assert not st.update(-1, first, 5.0) + assert st.update(-1, second, 5.2) + # Overlapping windows (one drum sliding through) never confirm across frames. + st2 = cc.ConeCamState() + assert not st2.update(-1, [_score(*cc.WINDOWS_M[1], True), _score(*cc.WINDOWS_M[2], False)], 5.0) + assert not st2.update(-1, [_score(*cc.WINDOWS_M[1], False), _score(*cc.WINDOWS_M[2], True)], 5.2) + + +def test_oct13_lines_inside_our_footprint_are_vehicles_not_cones(): + # 08:05 queue at a light: "line" at -0.15…-1.1 m. Never scored. + y = np.full((1208, 1928), 90, np.uint8) + u = np.full((604, 964), 128, np.uint8) + v = np.full((604, 964), 128, np.uint8) + for x0, x1 in cc.WINDOWS_M: + assert cc.score_window(y, u, v, G17C, x0, x1, (-0.4, -0.8, -1.1)) is None + + +def test_oct13_red_tail_lights_do_not_hit_but_orange_does(): + y = np.full((1208, 1928), 90, np.uint8) + base_u = np.full((604, 964), 128, np.uint8) + base_v = np.full((604, 964), 128, np.uint8) + lats = (-2.4, -2.4, -2.4) + probe = cc.score_window(y, base_u, base_v, G17C, 12.0, 17.0, lats) + assert probe is not None + u0, v0, u1, v1 = probe.box + + def paint(uval, vval): + # Alternating colour / white bands, 16 full-res rows each. + u, v, yy = base_u.copy(), base_v.copy(), y.copy() + for r in range(v0, v1, 32): + u[r // 2:(r + 16) // 2, u0 // 2:u1 // 2] = uval + v[r // 2:(r + 16) // 2, u0 // 2:u1 // 2] = vval + yy[r + 16:r + 32, u0:u1] = 200 + return cc.score_window(yy, u, v, G17C, 12.0, 17.0, lats) + + orange = paint(80, 180) + red = paint(118, 200) + assert orange is not None and orange.hit + assert red is not None and not red.hit + assert cc.MAX_SAMPLES <= 3000 diff --git a/selfdrive/selfdrived/alertmanager.py b/selfdrive/selfdrived/alertmanager.py new file mode 100644 index 00000000000000..c166ff591c974e --- /dev/null +++ b/selfdrive/selfdrived/alertmanager.py @@ -0,0 +1,67 @@ +import copy +import os +import json +from collections import defaultdict +from dataclasses import dataclass + +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.selfdrive.selfdrived.events import Alert, EmptyAlert + + +with open(os.path.join(BASEDIR, "selfdrive/selfdrived/alerts_offroad.json")) as f: + OFFROAD_ALERTS = json.load(f) + + +def set_offroad_alert(alert: str, show_alert: bool, extra_text: str | None = None) -> None: + if show_alert: + a = copy.copy(OFFROAD_ALERTS[alert]) + a['extra'] = extra_text or '' + Params().put(alert, a, block=True) + else: + Params().remove(alert) + + +@dataclass +class AlertEntry: + alert: Alert | None = None + start_frame: int = -1 + end_frame: int = -1 + added_frame: int = -1 + + def active(self, frame: int) -> bool: + return frame <= self.end_frame + + def just_added(self, frame: int) -> bool: + return self.active(frame) and frame == (self.added_frame + 1) + +class AlertManager: + def __init__(self): + self.alerts: dict[str, AlertEntry] = defaultdict(AlertEntry) + self.current_alert = EmptyAlert + + def add_many(self, frame: int, alerts: list[Alert]) -> None: + for alert in alerts: + entry = self.alerts[alert.alert_type] + entry.alert = alert + if not entry.just_added(frame): + entry.start_frame = frame + min_end_frame = entry.start_frame + alert.duration + entry.end_frame = max(frame + 1, min_end_frame) + entry.added_frame = frame + + def process_alerts(self, frame: int, clear_event_types: set): + ae = AlertEntry() + for v in self.alerts.values(): + if not v.alert: + continue + + if v.alert.event_type in clear_event_types: + v.end_frame = -1 + + # sort by priority first and then by start_frame + greater = ae.alert is None or (v.alert.priority, v.start_frame) > (ae.alert.priority, ae.start_frame) + if v.active(frame) and greater: + ae = v + + self.current_alert = ae.alert if ae.alert is not None else EmptyAlert diff --git a/selfdrive/selfdrived/alerts_offroad.json b/selfdrive/selfdrived/alerts_offroad.json new file mode 100644 index 00000000000000..0fc11b9636bff1 --- /dev/null +++ b/selfdrive/selfdrived/alerts_offroad.json @@ -0,0 +1,49 @@ +{ + "Offroad_TemperatureTooHigh": { + "text": "Device temperature too high. System cooling down before starting. Current internal component temperature: %1", + "severity": 0 + }, + "Offroad_ConnectivityNeededPrompt": { + "text": "Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1", + "severity": 0, + "_comment": "Set extra field to number of days" + }, + "Offroad_ConnectivityNeeded": { + "text": "Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates.", + "severity": 1 + }, + "Offroad_UpdateFailed": { + "text": "Unable to download updates\n%1", + "severity": 1, + "_comment": "Set extra field to the failed reason." + }, + "Offroad_IsTakingSnapshot": { + "text": "Taking camera snapshots. System won't start until finished.", + "severity": 0 + }, + "Offroad_NeosUpdate": { + "text": "An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install.", + "severity": 0 + }, + "Offroad_UnregisteredHardware": { + "text": "Failed to register with comma.ai backend. It will not connect or upload to comma.ai servers, and receives no support from comma.ai. If this is a device purchased at comma.ai/shop, open a ticket at https://comma.ai/support.", + "severity": 1 + }, + "Offroad_CarUnrecognized": { + "text": "openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai.", + "severity": 0 + }, + "Offroad_Recalibration": { + "text": "openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield.", + "severity": 0 + }, + "Offroad_DriverMonitoringUncertain": { + "text": "Poor visibility detected for driver monitoring. Ensure the device has a clear view of the driver. This can be checked in the device settings. Extreme lighting conditions and/or unconventional mounting positions may also trigger this alert.", + "severity": 0 + }, + "Offroad_ExcessiveActuation": { + "text": "Excessive %1 actuation detected on your last drive. Please contact support at https://comma.ai/support and share your device's Dongle ID for troubleshooting.", + "severity": 1, + "_comment": "Set extra field to lateral or longitudinal." + } +} diff --git a/selfdrive/selfdrived/events.py b/selfdrive/selfdrived/events.py new file mode 100644 index 00000000000000..45cee51d4fa7ef --- /dev/null +++ b/selfdrive/selfdrived/events.py @@ -0,0 +1,1376 @@ +#!/usr/bin/env python3 +import bisect +import math +import os +from enum import IntEnum +from collections.abc import Callable + +from cereal import log, car +import cereal.messaging as messaging +from openpilot.common.constants import CV +from openpilot.common.git import get_short_branch +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.controls.lib.radar_sensor_dirty import sensor_dirty_degraded +from openpilot.selfdrive.locationd.calibrationd import MIN_SPEED_FILTER +from openpilot.system.micd import SAMPLE_RATE, SAMPLE_BUFFER +from openpilot.selfdrive.ui.feedback.feedbackd import FEEDBACK_MAX_DURATION +from openpilot.system.hardware import HARDWARE +from openpilot.system.manager.optional_procs import missing_required_processes + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus +VisualAlert = car.CarControl.HUDControl.VisualAlert +AudibleAlert = car.CarControl.HUDControl.AudibleAlert +EventName = log.OnroadEvent.EventName + + +# Alert priorities +class Priority(IntEnum): + LOWEST = 0 + LOWER = 1 + LOW = 2 + MID = 3 + HIGH = 4 + HIGHEST = 5 + + +# Event types +class ET: + ENABLE = 'enable' + PRE_ENABLE = 'preEnable' + OVERRIDE_LATERAL = 'overrideLateral' + OVERRIDE_LONGITUDINAL = 'overrideLongitudinal' + NO_ENTRY = 'noEntry' + WARNING = 'warning' + USER_DISABLE = 'userDisable' + SOFT_DISABLE = 'softDisable' + IMMEDIATE_DISABLE = 'immediateDisable' + PERMANENT = 'permanent' + + +# get event name from enum +EVENT_NAME = {v: k for k, v in EventName.schema.enumerants.items()} + + +class Events: + def __init__(self): + self.events: list[int] = [] + self.static_events: list[int] = [] + self.event_counters = dict.fromkeys(EVENTS.keys(), 0) + + @property + def names(self) -> list[int]: + return self.events + + def __len__(self) -> int: + return len(self.events) + + def add(self, event_name: int, static: bool=False) -> None: + if static: + bisect.insort(self.static_events, event_name) + bisect.insort(self.events, event_name) + + def clear(self) -> None: + self.event_counters = {k: (v + 1 if k in self.events else 0) for k, v in self.event_counters.items()} + self.events = self.static_events.copy() + + def contains(self, event_type: str) -> bool: + return any(event_type in EVENTS.get(e, {}) for e in self.events) + + def create_alerts(self, event_types: list[str], callback_args=None): + if callback_args is None: + callback_args = [] + + ret = [] + for e in self.events: + types = EVENTS[e].keys() + for et in event_types: + if et in types: + alert = EVENTS[e][et] + if not isinstance(alert, Alert): + alert = alert(*callback_args) + + if DT_CTRL * (self.event_counters[e] + 1) >= alert.creation_delay: + alert.alert_type = f"{EVENT_NAME[e]}/{et}" + alert.event_type = et + ret.append(alert) + return ret + + def add_from_msg(self, events): + for e in events: + bisect.insort(self.events, e.name.raw) + + def to_msg(self): + ret = [] + for event_name in self.events: + event = log.OnroadEvent.new_message() + event.name = event_name + for event_type in EVENTS.get(event_name, {}): + setattr(event, event_type, True) + ret.append(event) + return ret + + +class Alert: + def __init__(self, + alert_text_1: str, + alert_text_2: str, + alert_status: log.SelfdriveState.AlertStatus, + alert_size: log.SelfdriveState.AlertSize, + priority: Priority, + visual_alert: car.CarControl.HUDControl.VisualAlert, + audible_alert: car.CarControl.HUDControl.AudibleAlert, + duration: float, + creation_delay: float = 0.): + + self.alert_text_1 = alert_text_1 + self.alert_text_2 = alert_text_2 + self.alert_status = alert_status + self.alert_size = alert_size + self.priority = priority + self.visual_alert = visual_alert + self.audible_alert = audible_alert + + self.duration = int(duration / DT_CTRL) + + self.creation_delay = creation_delay + + self.alert_type = "" + self.event_type: str | None = None + + def __str__(self) -> str: + return f"{self.alert_text_1}/{self.alert_text_2} {self.priority} {self.visual_alert} {self.audible_alert}" + + def __gt__(self, alert2) -> bool: + if not isinstance(alert2, Alert): + return False + return self.priority > alert2.priority + +EmptyAlert = Alert("" , "", AlertStatus.normal, AlertSize.none, Priority.LOWEST, + VisualAlert.none, AudibleAlert.none, 0) + +class NoEntryAlert(Alert): + def __init__(self, alert_text_2: str, + alert_text_1: str = "openpilot Unavailable", + visual_alert: car.CarControl.HUDControl.VisualAlert=VisualAlert.none): + if HARDWARE.get_device_type() == 'mici': + alert_text_1, alert_text_2 = alert_text_2, alert_text_1 + super().__init__(alert_text_1, alert_text_2, AlertStatus.normal, + AlertSize.mid, Priority.LOW, visual_alert, + AudibleAlert.refuse, 3.) + + +class SoftDisableAlert(Alert): + def __init__(self, alert_text_2: str): + super().__init__("TAKE CONTROL IMMEDIATELY", alert_text_2, + AlertStatus.userPrompt, AlertSize.full, + Priority.MID, VisualAlert.steerRequired, + AudibleAlert.warningSoft, 2.), + + +# less harsh version of SoftDisable, where the condition is user-triggered +class UserSoftDisableAlert(SoftDisableAlert): + def __init__(self, alert_text_2: str): + super().__init__(alert_text_2), + self.alert_text_1 = "openpilot will disengage" + + +class ImmediateDisableAlert(Alert): + def __init__(self, alert_text_2: str): + super().__init__("TAKE CONTROL IMMEDIATELY", alert_text_2, + AlertStatus.critical, AlertSize.full, + Priority.HIGHEST, VisualAlert.steerRequired, + AudibleAlert.warningImmediate, 4.), + + +class EngagementAlert(Alert): + def __init__(self, audible_alert: car.CarControl.HUDControl.AudibleAlert): + super().__init__("", "", + AlertStatus.normal, AlertSize.none, + Priority.MID, VisualAlert.none, + audible_alert, .2), + + +def _is_tesla_preap(CP: car.CarParams) -> bool: + return CP.brand == "tesla" and CP.carFingerprint == "TESLA_MODEL_S_PREAP" + + +def pcm_enable_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + if _is_tesla_preap(CP): + return Alert( + "Steering Engaged", + "", + AlertStatus.normal, AlertSize.small, + Priority.MID, VisualAlert.none, AudibleAlert.engage, 0.8) + return EngagementAlert(AudibleAlert.engage) + + +def pcm_disable_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + # Pre-AP 3X bottom-bar text. EventName.steerDisengage is sound-only + # (empty EngagementAlert). If cruiseEnabled falls during a blinker + # turn, this is the HUD Justin sees — keep cruise up instead of + # hiding this alert after the FSM is already down. + if _is_tesla_preap(CP): + return Alert( + "Steering Disengaged", + "", + AlertStatus.normal, AlertSize.small, + Priority.MID, VisualAlert.none, AudibleAlert.disengage, 0.8) + return EngagementAlert(AudibleAlert.disengage) + + +def reverse_gear_disable_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + # Pre-AP: Reverse itself is a hard cancel (session already torn down). + # Stock USER_DISABLE is ImmediateDisableAlert — "TAKE CONTROL IMMEDIATELY" + # + warningImmediate. That is the parking-lot alarm Justin hears on R. + # Keep USER_DISABLE so lat/long drop immediately; mute the scary HUD. + # Priority.HIGH and 1s cover same-frame pcmDisable "Steering Disengaged" + # linger (0.8s, Priority.MID). PERMANENT reverse overlay is the quiet note. + if _is_tesla_preap(CP): + return Alert( + "", "", + AlertStatus.normal, AlertSize.none, + Priority.HIGH, VisualAlert.none, AudibleAlert.none, 1.) + return ImmediateDisableAlert("Reverse Gear") + + +class NormalPermanentAlert(Alert): + def __init__(self, alert_text_1: str, alert_text_2: str = "", duration: float = 0.2, priority: Priority = Priority.LOWER, creation_delay: float = 0.): + super().__init__(alert_text_1, alert_text_2, + AlertStatus.normal, AlertSize.mid if len(alert_text_2) else AlertSize.small, + priority, VisualAlert.none, AudibleAlert.none, duration, creation_delay=creation_delay), + + +class StartupAlert(Alert): + def __init__(self, alert_text_1: str, alert_text_2: str = "Always keep hands on wheel and eyes on road", alert_status=AlertStatus.normal): + alert_size = AlertSize.mid + if HARDWARE.get_device_type() == 'mici': + if alert_text_2 == "Always keep hands on wheel and eyes on road": + alert_text_2 = "" + alert_size = AlertSize.small + super().__init__(alert_text_1, alert_text_2, + alert_status, alert_size, + Priority.LOWER, VisualAlert.none, AudibleAlert.none, 5.), + + + +# ********** helper functions ********** +def get_display_speed(speed_ms: float, metric: bool) -> str: + speed = int(round(speed_ms * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH))) + unit = 'km/h' if metric else 'mph' + return f"{speed} {unit}" + + +# ********** alert callback functions ********** + +AlertCallbackType = Callable[[car.CarParams, car.CarState, messaging.SubMaster, bool, int, log.ControlsState], Alert] + + +def soft_disable_alert(alert_text_2: str) -> AlertCallbackType: + def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + if soft_disable_time < int(0.5 / DT_CTRL): + return ImmediateDisableAlert(alert_text_2) + return SoftDisableAlert(alert_text_2) + return func + +def user_soft_disable_alert(alert_text_2: str) -> AlertCallbackType: + def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + if soft_disable_time < int(0.5 / DT_CTRL): + return ImmediateDisableAlert(alert_text_2) + return UserSoftDisableAlert(alert_text_2) + return func + +def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + branch = get_short_branch() # Ensure get_short_branch is cached to avoid lags on startup + if "REPLAY" in os.environ: + branch = "replay" + + return StartupAlert("WARNING: This branch is not tested", branch, alert_status=AlertStatus.userPrompt) + +def below_engage_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + return NoEntryAlert(f"Drive above {get_display_speed(CP.minEnableSpeed, metric)} to engage") + + +def below_steer_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + return Alert( + f"Steer Assist Unavailable Below {get_display_speed(CP.minSteerSpeed, metric)}", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 0.4) + + +def calibration_incomplete_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + first_word = 'Recalibrating' if sm['liveCalibration'].calStatus == log.LiveCalibrationData.Status.recalibrating else 'Calibrating' + return Alert( + f"{first_word}: {sm['liveCalibration'].calPerc:.0f}%", + f"Drive Above {get_display_speed(MIN_SPEED_FILTER, metric)}", + AlertStatus.normal, AlertSize.mid, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2) + + +def audio_feedback_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + duration = FEEDBACK_MAX_DURATION - ((sm['audioFeedback'].blockNum + 1) * SAMPLE_BUFFER / SAMPLE_RATE) + return NormalPermanentAlert( + "Recording Voice Note", + f"{round(duration)} second{'s' if round(duration) != 1 else ''} remaining. Tap Bookmark again to stop.", + priority=Priority.LOW) + + +# *** debug alerts *** + +def out_of_space_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + full_perc = round(100. - sm['deviceState'].freeSpacePercent) + return NormalPermanentAlert("Out of Storage", f"{full_perc}% full") + + +def posenet_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + mdl = sm['modelV2'].velocity.x[0] if len(sm['modelV2'].velocity.x) else math.nan + err = CS.vEgo - mdl + msg = f"Speed Error: {err:.1f} m/s" + return NoEntryAlert(msg, alert_text_1="Posenet Speed Invalid") + + +def process_not_running_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + not_running = missing_required_processes(sm['managerState'].processes) + msg = ', '.join(not_running) + return NoEntryAlert(msg, alert_text_1="Process Not Running") + + +def comm_issue_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + bs = [s for s in sm.data.keys() if not sm.all_checks([s, ])] + msg = ', '.join(bs[:4]) # can't fit too many on one line + return NoEntryAlert(msg, alert_text_1="Communication Issue Between Processes") + + +def camera_malfunction_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + all_cams = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') + bad_cams = [s.replace('State', '') for s in all_cams if s in sm.data.keys() and not sm.all_checks([s, ])] + return NormalPermanentAlert("Camera Malfunction", ', '.join(bad_cams)) + + +def calibration_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + rpy = sm['liveCalibration'].rpyCalib + yaw = math.degrees(rpy[2] if len(rpy) == 3 else math.nan) + pitch = math.degrees(rpy[1] if len(rpy) == 3 else math.nan) + angles = f"Remount Device (Pitch: {pitch:.1f}°, Yaw: {yaw:.1f}°)" + return NormalPermanentAlert("Calibration Invalid", angles) + + +def paramsd_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + if not sm['liveParameters'].angleOffsetValid: + angle_offset_deg = sm['liveParameters'].angleOffsetDeg + title = "Steering misalignment detected" + text = f"Angle offset too high (Offset: {angle_offset_deg:.1f}°)" + elif not sm['liveParameters'].steerRatioValid: + steer_ratio = sm['liveParameters'].steerRatio + title = "Steer ratio mismatch" + text = f"Steering rack geometry may be off (Ratio: {steer_ratio:.1f})" + elif not sm['liveParameters'].stiffnessFactorValid: + stiffness_factor = sm['liveParameters'].stiffnessFactor + title = "Abnormal tire stiffness" + text = f"Check tires, pressure, or alignment (Factor: {stiffness_factor:.1f})" + else: + return NoEntryAlert("paramsd Temporary Error") + + return NoEntryAlert(alert_text_1=title, alert_text_2=text) + +def overheat_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + cpu = max(sm['deviceState'].cpuTempC, default=0.) + gpu = max(sm['deviceState'].gpuTempC, default=0.) + temp = max((cpu, gpu, sm['deviceState'].memoryTempC)) + return NormalPermanentAlert("System Overheated", f"{temp:.0f} °C") + + +def low_memory_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + return NormalPermanentAlert("Low Memory", f"{sm['deviceState'].memoryUsagePercent}% used") + + +def high_cpu_usage_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + x = max(sm['deviceState'].cpuUsagePercent, default=0.) + return NormalPermanentAlert("High CPU Usage", f"{x}% used") + + +def modeld_lagging_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + return NormalPermanentAlert("Driving Model Lagging", f"{sm['modelV2'].frameDropPerc:.1f}% frames dropped") + + +def _radar_sensor_dirty_active(sm: messaging.SubMaster) -> bool: + """radard tagged radarPreferReason with sensorDirty (radar lead still live).""" + try: + return sensor_dirty_degraded(getattr(sm['radarState'], 'radarPreferReason', '')) + except Exception: + return False + + +def radar_prefer_fallback_permanent_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, + soft_disable_time: int, personality) -> Alert: + if _radar_sensor_dirty_active(sm): + return NormalPermanentAlert("Radar Sensor Dirty", "Radar lead still active") + return NormalPermanentAlert("Radar Unreliable", "Using camera lead") + + +def radar_prefer_fallback_warning_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, + soft_disable_time: int, personality) -> Alert: + if _radar_sensor_dirty_active(sm): + title, sub = "Radar Sensor Dirty", "Radar lead still active" + else: + title, sub = "Radar Unreliable", "Using camera lead" + return Alert( + title, + sub, + AlertStatus.userPrompt, AlertSize.mid, + Priority.MID, VisualAlert.none, AudibleAlert.none, 0.2) + + +def wrong_car_mode_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + text = "Enable Adaptive Cruise to Engage" + if CP.brand == "honda": + text = "Enable Main Switch to Engage" + return NoEntryAlert(text) + + +def joystick_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + gb = sm['carControl'].actuators.accel / 4. + steer = sm['carControl'].actuators.torque + vals = f"Gas: {round(gb * 100.)}%, Steer: {round(steer * 100.)}%" + return NormalPermanentAlert("Joystick Mode", vals) + + +def longitudinal_maneuver_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + ad = sm['alertDebug'] + audible_alert = AudibleAlert.prompt if 'Active' in ad.alertText1 else AudibleAlert.none + alert_status = AlertStatus.userPrompt if 'Active' in ad.alertText1 else AlertStatus.normal + alert_size = AlertSize.mid if ad.alertText2 else AlertSize.small + return Alert(ad.alertText1, ad.alertText2, + alert_status, alert_size, + Priority.LOW, VisualAlert.none, audible_alert, 0.2) + + +def personality_changed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + personality = str(personality).title() + return NormalPermanentAlert(f"Driving Personality: {personality}", duration=1.5) + + +def hypermile_follow_changed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + from openpilot.selfdrive.controls.lib.hypermile import follow_distance_hud_text, read_follow_distance + from openpilot.common.params import Params + return NormalPermanentAlert(follow_distance_hud_text(read_follow_distance(Params())), duration=1.5) + + +def nap_wiper_changed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + from openpilot.selfdrive.car.tesla.preap_body_controls import WIPER_HUD_DURATION_S, wiper_hud_text + return NormalPermanentAlert(wiper_hud_text(), duration=WIPER_HUD_DURATION_S) + + +def gap_lock_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + """Bottom toast. Engaged, unavailable, and lost follow the planner pulse. + + Duration is a refresh so the line drops when the planner stops publishing + the code. The under-MAX chip reads gapLockM and stays for the whole latch. + """ + from openpilot.selfdrive.controls.lib.gap_lock import HUD_LOST, HUD_UNAVAILABLE, gap_lock_engaged_text + event = 0 + meters = 0.0 + try: + plan = sm['longitudinalPlan'] + event = int(getattr(plan, 'gapLockEvent', 0) or 0) + meters = float(getattr(plan, 'gapLockM', 0.0) or 0.0) + except Exception: + event, meters = 0, 0.0 + if event == HUD_UNAVAILABLE: + return NormalPermanentAlert("Gap lock unavailable", duration=0.2) + engaged = gap_lock_engaged_text(meters) + if event == HUD_LOST or engaged is None: + return NormalPermanentAlert("Gap lock off", duration=0.2) + # LOW so a lock is not hidden by LOWER background lines. Real warnings + # (MID and above) still cover it; the HUD chip stays either way. + return NormalPermanentAlert(engaged, duration=0.2, priority=Priority.LOW) + + +def invalid_lkas_setting_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + text = "Toggle stock LKAS on or off to engage" + if CP.brand == "tesla": + text = "Switch to Traffic-Aware Cruise Control to engage" + elif CP.brand == "mazda": + text = "Enable your car's LKAS to engage" + elif CP.brand == "nissan": + text = "Disable your car's stock LKAS to engage" + return NormalPermanentAlert("Invalid LKAS setting", text) + + + +EVENTS: dict[int, dict[str, Alert | AlertCallbackType]] = { + # ********** events with no alerts ********** + + EventName.stockFcw: {}, + EventName.actuatorsApiUnavailable: {}, + # Log only. No HUD text, no chime. A stalk pull resumes long; do not + # add a paused note. + EventName.preapBrakeLongActive: {}, + + # ********** events only containing alerts displayed in all states ********** + + EventName.joystickDebug: { + ET.WARNING: joystick_alert, + ET.PERMANENT: NormalPermanentAlert("Joystick Mode"), + }, + + EventName.longitudinalManeuver: { + ET.WARNING: longitudinal_maneuver_alert, + ET.PERMANENT: NormalPermanentAlert("Longitudinal Maneuver Mode", + "Ensure road ahead is clear"), + }, + + EventName.lateralManeuver: { + ET.WARNING: longitudinal_maneuver_alert, + ET.PERMANENT: NormalPermanentAlert("Lateral Maneuver Mode"), + }, + + EventName.selfdriveInitializing: { + ET.NO_ENTRY: NoEntryAlert("System Initializing"), + }, + + EventName.startup: { + ET.PERMANENT: StartupAlert("Be ready to take over at any time") + }, + + EventName.startupMaster: { + ET.PERMANENT: startup_master_alert, + }, + + EventName.startupNoControl: { + ET.PERMANENT: StartupAlert("Dashcam mode"), + ET.NO_ENTRY: NoEntryAlert("Dashcam mode"), + }, + + EventName.startupNoCar: { + ET.PERMANENT: StartupAlert("Dashcam mode for unsupported car"), + }, + + EventName.startupNoSecOcKey: { + ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", + "Security Key Not Available", + priority=Priority.HIGH), + }, + + EventName.dashcamMode: { + ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", + priority=Priority.LOWEST), + }, + + EventName.invalidLkasSetting: { + ET.PERMANENT: invalid_lkas_setting_alert, + ET.NO_ENTRY: NoEntryAlert("Invalid LKAS setting"), + }, + + EventName.cruiseMismatch: { + #ET.PERMANENT: ImmediateDisableAlert("openpilot failed to cancel cruise"), + }, + + # openpilot doesn't recognize the car. This switches openpilot into a + # read-only mode. This can be solved by adding your fingerprint. + # See https://github.com/commaai/openpilot/wiki/Fingerprinting for more information + EventName.carUnrecognized: { + ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", + "Car Unrecognized", + priority=Priority.LOWEST), + }, + + EventName.aeb: { + ET.PERMANENT: Alert( + "BRAKE!", + "Emergency Braking: Risk of Collision", + AlertStatus.critical, AlertSize.full, + Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), + ET.NO_ENTRY: NoEntryAlert("AEB: Risk of Collision"), + }, + + EventName.stockAeb: { + ET.PERMANENT: Alert( + "BRAKE!", + "Stock AEB: Risk of Collision", + AlertStatus.critical, AlertSize.full, + Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), + ET.NO_ENTRY: NoEntryAlert("Stock AEB: Risk of Collision"), + }, + + EventName.stockLkas: { + ET.NO_ENTRY: NoEntryAlert("Stock LKAS: Lane Departure Detected"), + }, + + EventName.fcw: { + ET.PERMANENT: Alert( + "BRAKE!", + "Risk of Collision", + AlertStatus.critical, AlertSize.full, + Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.warningSoft, 2.), + }, + + EventName.ldw: { + ET.PERMANENT: Alert( + "Lane Departure Detected", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.ldw, AudibleAlert.prompt, 3.), + }, + + # ********** events only containing alerts that display while engaged ********** + + EventName.steerTempUnavailableSilent: { + ET.WARNING: Alert( + "Steering Assist Temporarily Unavailable", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 1.8), + }, + + EventName.driverDistracted1: { + ET.PERMANENT: Alert( + "Pay Attention", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.driverDistracted2: { + ET.PERMANENT: Alert( + "Pay Attention", + "Driver Distracted", + AlertStatus.userPrompt, AlertSize.mid, + Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), + }, + + EventName.driverDistracted3: { + ET.PERMANENT: Alert( + "DISENGAGE IMMEDIATELY", + "Driver Distracted", + AlertStatus.critical, AlertSize.full, + Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), + }, + + EventName.driverUnresponsive1: { + ET.PERMANENT: Alert( + "Touch Steering Wheel: No Face Detected", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.none, .1), + }, + + EventName.driverUnresponsive2: { + ET.PERMANENT: Alert( + "Touch Steering Wheel", + "Driver Unresponsive", + AlertStatus.userPrompt, AlertSize.mid, + Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), + }, + + EventName.driverUnresponsive3: { + ET.PERMANENT: Alert( + "DISENGAGE IMMEDIATELY", + "Driver Unresponsive", + AlertStatus.critical, AlertSize.full, + Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), + }, + + EventName.manualRestart: { + ET.WARNING: Alert( + "TAKE CONTROL", + "Resume Driving Manually", + AlertStatus.userPrompt, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), + }, + + EventName.resumeRequired: { + ET.WARNING: Alert( + "Press Resume to Exit Standstill", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), + }, + + EventName.belowSteerSpeed: { + ET.WARNING: below_steer_speed_alert, + }, + + EventName.preLaneChangeLeft: { + ET.WARNING: Alert( + "Steer Left to Start Lane Change Once Safe", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.preLaneChangeRight: { + ET.WARNING: Alert( + "Steer Right to Start Lane Change Once Safe", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.laneChangeBlocked: { + ET.WARNING: Alert( + "Car Detected in Blindspot", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.prompt, .1), + }, + + EventName.laneChange: { + ET.WARNING: Alert( + "Changing Lanes", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.steerSaturated: { + ET.WARNING: Alert( + "Take Control", + "Turn Exceeds Steering Limit", + AlertStatus.userPrompt, AlertSize.mid, + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 2.), + }, + + # Thrown when the fan is driven at >50% but is not rotating + EventName.fanMalfunction: { + ET.PERMANENT: NormalPermanentAlert("Fan Malfunction", "Likely Hardware Issue"), + }, + + # Camera is not outputting frames + EventName.cameraMalfunction: { + ET.PERMANENT: camera_malfunction_alert, + ET.SOFT_DISABLE: soft_disable_alert("Camera Malfunction"), + ET.NO_ENTRY: NoEntryAlert("Camera Malfunction: Reboot Your Device"), + }, + # Camera framerate too low + EventName.cameraFrameRate: { + ET.PERMANENT: NormalPermanentAlert("Camera Frame Rate Low", "Reboot your Device"), + ET.SOFT_DISABLE: soft_disable_alert("Camera Frame Rate Low"), + ET.NO_ENTRY: NoEntryAlert("Camera Frame Rate Low: Reboot Your Device"), + }, + + # Unused + + EventName.locationdTemporaryError: { + ET.NO_ENTRY: NoEntryAlert("locationd Temporary Error"), + ET.SOFT_DISABLE: soft_disable_alert("locationd Temporary Error"), + }, + + EventName.locationdPermanentError: { + ET.NO_ENTRY: NoEntryAlert("locationd Permanent Error"), + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("locationd Permanent Error"), + ET.PERMANENT: NormalPermanentAlert("locationd Permanent Error"), + }, + + # openpilot tries to learn certain parameters about your car by observing + # how the car behaves to steering inputs from both human and openpilot driving. + # This includes: + # - steer ratio: gear ratio of the steering rack. Steering angle divided by tire angle + # - tire stiffness: how much grip your tires have + # - angle offset: most steering angle sensors are offset and measure a non zero angle when driving straight + # This alert is thrown when any of these values exceed a sanity check. This can be caused by + # bad alignment or bad sensor data. If this happens consistently consider creating an issue on GitHub + EventName.paramsdTemporaryError: { + ET.NO_ENTRY: paramsd_invalid_alert, + ET.SOFT_DISABLE: soft_disable_alert("paramsd Temporary Error"), + }, + + EventName.paramsdPermanentError: { + ET.NO_ENTRY: NoEntryAlert("paramsd Permanent Error"), + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("paramsd Permanent Error"), + ET.PERMANENT: NormalPermanentAlert("paramsd Permanent Error"), + }, + + # ********** events that affect controls state transitions ********** + + EventName.pcmEnable: { + ET.ENABLE: pcm_enable_alert, + }, + + EventName.buttonEnable: { + ET.ENABLE: EngagementAlert(AudibleAlert.engage), + }, + + EventName.pcmDisable: { + ET.USER_DISABLE: pcm_disable_alert, + }, + + EventName.buttonCancel: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Cancel Pressed"), + }, + + EventName.brakeHold: { + ET.WARNING: Alert( + "Press Resume to Exit Brake Hold", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), + }, + + EventName.parkBrake: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Parking Brake Engaged"), + }, + + EventName.pedalPressed: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Pedal Pressed", + visual_alert=VisualAlert.brakePressed), + }, + + EventName.steerDisengage: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Steering Pressed"), + }, + + EventName.preEnableStandstill: { + ET.PRE_ENABLE: Alert( + "Release Brake to Engage", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1, creation_delay=1.), + }, + + EventName.gasPressedOverride: { + ET.OVERRIDE_LONGITUDINAL: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.steerOverride: { + ET.OVERRIDE_LATERAL: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.wrongCarMode: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: wrong_car_mode_alert, + }, + + EventName.resumeBlocked: { + ET.NO_ENTRY: NoEntryAlert("Press Set to Engage"), + }, + + EventName.wrongCruiseMode: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Adaptive Cruise Disabled"), + }, + + EventName.steerTempUnavailable: { + ET.SOFT_DISABLE: soft_disable_alert("Steering Assist Temporarily Unavailable"), + ET.NO_ENTRY: NoEntryAlert("Steering Temporarily Unavailable"), + }, + + EventName.steerTimeLimit: { + ET.SOFT_DISABLE: soft_disable_alert("Vehicle Steering Time Limit"), + ET.NO_ENTRY: NoEntryAlert("Vehicle Steering Time Limit"), + }, + + EventName.outOfSpace: { + ET.PERMANENT: out_of_space_alert, + ET.NO_ENTRY: NoEntryAlert("Out of Storage"), + }, + + EventName.belowEngageSpeed: { + ET.NO_ENTRY: below_engage_speed_alert, + }, + + EventName.sensorDataInvalid: { + ET.PERMANENT: Alert( + "Sensor Data Invalid", + "Possible Hardware Issue", + AlertStatus.normal, AlertSize.mid, + Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=1.), + ET.NO_ENTRY: NoEntryAlert("Sensor Data Invalid"), + ET.SOFT_DISABLE: soft_disable_alert("Sensor Data Invalid"), + }, + + EventName.noGps: { + }, + + EventName.tooDistracted: { + ET.NO_ENTRY: NoEntryAlert("Distraction Level Too High"), + }, + + EventName.excessiveActuation: { + ET.SOFT_DISABLE: soft_disable_alert("Excessive Actuation"), + ET.NO_ENTRY: NoEntryAlert("Excessive Actuation"), + }, + + EventName.overheat: { + ET.PERMANENT: overheat_alert, + ET.SOFT_DISABLE: soft_disable_alert("System Overheated"), + ET.NO_ENTRY: NoEntryAlert("System Overheated"), + }, + + EventName.wrongGear: { + ET.SOFT_DISABLE: user_soft_disable_alert("Gear not D"), + ET.NO_ENTRY: NoEntryAlert("Gear not D"), + }, + + # This alert is thrown when the calibration angles are outside of the acceptable range. + # For example if the device is pointed too much to the left or the right. + # Usually this can only be solved by removing the mount from the windshield completely, + # and attaching while making sure the device is pointed straight forward and is level. + # See https://comma.ai/setup for more information + EventName.calibrationInvalid: { + ET.PERMANENT: calibration_invalid_alert, + ET.SOFT_DISABLE: soft_disable_alert("Calibration Invalid: Remount Device & Recalibrate"), + ET.NO_ENTRY: NoEntryAlert("Calibration Invalid: Remount Device & Recalibrate"), + }, + + EventName.calibrationIncomplete: { + ET.PERMANENT: calibration_incomplete_alert, + ET.SOFT_DISABLE: soft_disable_alert("Calibration Incomplete"), + ET.NO_ENTRY: NoEntryAlert("Calibration in Progress"), + }, + + EventName.pedalNotCalibrated: { + ET.PERMANENT: NormalPermanentAlert("Pedal Not Calibrated", "Check Calibration"), + ET.NO_ENTRY: NoEntryAlert("Pedal Not Calibrated: Check Calibration"), + }, + + EventName.calibrationRecalibrating: { + ET.PERMANENT: calibration_incomplete_alert, + ET.SOFT_DISABLE: soft_disable_alert("Device Remount Detected: Recalibrating"), + ET.NO_ENTRY: NoEntryAlert("Remount Detected: Recalibrating"), + }, + + EventName.doorOpen: { + ET.SOFT_DISABLE: user_soft_disable_alert("Door Open"), + ET.NO_ENTRY: NoEntryAlert("Door Open"), + }, + + EventName.seatbeltNotLatched: { + ET.SOFT_DISABLE: user_soft_disable_alert("Seatbelt Unlatched"), + ET.NO_ENTRY: NoEntryAlert("Seatbelt Unlatched"), + }, + + EventName.espDisabled: { + ET.SOFT_DISABLE: soft_disable_alert("Electronic Stability Control Disabled"), + ET.NO_ENTRY: NoEntryAlert("Electronic Stability Control Disabled"), + }, + + EventName.lowBattery: { + ET.SOFT_DISABLE: soft_disable_alert("Low Battery"), + ET.NO_ENTRY: NoEntryAlert("Low Battery"), + }, + + # Different openpilot services communicate between each other at a certain + # interval. If communication does not follow the regular schedule this alert + # is thrown. This can mean a service crashed, did not broadcast a message for + # ten times the regular interval, or the average interval is more than 10% too high. + EventName.commIssue: { + ET.SOFT_DISABLE: soft_disable_alert("Communication Issue Between Processes"), + ET.NO_ENTRY: comm_issue_alert, + }, + EventName.commIssueAvgFreq: { + ET.SOFT_DISABLE: soft_disable_alert("Low Communication Rate Between Processes"), + ET.NO_ENTRY: NoEntryAlert("Low Communication Rate Between Processes"), + }, + + EventName.selfdrivedLagging: { + ET.SOFT_DISABLE: soft_disable_alert("System Lagging"), + ET.NO_ENTRY: NoEntryAlert("Selfdrive Process Lagging: Reboot Your Device"), + }, + + # Thrown when manager detects a service exited unexpectedly while driving + EventName.processNotRunning: { + ET.NO_ENTRY: process_not_running_alert, + ET.SOFT_DISABLE: soft_disable_alert("Process Not Running"), + }, + + EventName.radarFault: { + ET.SOFT_DISABLE: soft_disable_alert("Radar Error: Restart the Car"), + ET.NO_ENTRY: NoEntryAlert("Radar Error: Restart the Car"), + }, + + EventName.radarTempUnavailable: { + ET.SOFT_DISABLE: soft_disable_alert("Radar Temporarily Unavailable"), + ET.NO_ENTRY: NoEntryAlert("Radar Temporarily Unavailable"), + }, + + # Every frame from the camera should be processed by the model. If modeld + # is not processing frames fast enough they have to be dropped. This alert is + # thrown when over 20% of frames are dropped. + EventName.modeldLagging: { + ET.SOFT_DISABLE: soft_disable_alert("Driving Model Lagging"), + ET.NO_ENTRY: NoEntryAlert("Driving Model Lagging"), + ET.PERMANENT: modeld_lagging_alert, + }, + + # Besides predicting the path, lane lines and lead car data the model also + # predicts the current velocity and rotation speed of the car. If the model is + # very uncertain about the current velocity while the car is moving, this + # usually means the model has trouble understanding the scene. This is used + # as a heuristic to warn the driver. + EventName.posenetInvalid: { + ET.SOFT_DISABLE: soft_disable_alert("Posenet Speed Invalid"), + ET.NO_ENTRY: posenet_invalid_alert, + }, + + # When the localizer detects an acceleration of more than 40 m/s^2 (~4G) we + # alert the driver the device might have fallen from the windshield. + EventName.deviceFalling: { + ET.SOFT_DISABLE: soft_disable_alert("Device Fell Off Mount"), + ET.NO_ENTRY: NoEntryAlert("Device Fell Off Mount"), + }, + + EventName.lowMemory: { + ET.SOFT_DISABLE: soft_disable_alert("Low Memory: Reboot Your Device"), + ET.PERMANENT: low_memory_alert, + ET.NO_ENTRY: NoEntryAlert("Low Memory: Reboot Your Device"), + }, + + EventName.accFaulted: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Fault: Restart the Car"), + ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), + ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), + }, + + EventName.espActive: { + ET.SOFT_DISABLE: soft_disable_alert("Electronic Stability Control Active"), + ET.NO_ENTRY: NoEntryAlert("Electronic Stability Control Active"), + }, + + EventName.controlsMismatch: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch"), + ET.NO_ENTRY: NoEntryAlert("Controls Mismatch"), + }, + + # Sometimes the USB stack on the device can get into a bad state + # causing the connection to the panda to be lost + EventName.usbError: { + ET.SOFT_DISABLE: soft_disable_alert("USB Error: Reboot Your Device"), + ET.PERMANENT: NormalPermanentAlert("USB Error: Reboot Your Device"), + ET.NO_ENTRY: NoEntryAlert("USB Error: Reboot Your Device"), + }, + + # This alert can be thrown for the following reasons: + # - No CAN data received at all + # - CAN data is received, but some message are not received at the right frequency + # If you're not writing a new car port, this is usually cause by faulty wiring + EventName.canError: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Unknown Vehicle Variant"), + ET.PERMANENT: Alert( + "Unknown Vehicle Variant", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), + ET.NO_ENTRY: NoEntryAlert("Unknown Vehicle Variant"), + }, + + EventName.canBusMissing: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Bus Disconnected"), + ET.PERMANENT: Alert( + "CAN Bus Disconnected: Likely Faulty Cable", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), + ET.NO_ENTRY: NoEntryAlert("CAN Bus Disconnected: Check Connections"), + }, + + EventName.steerUnavailable: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("LKAS Fault: Restart the Car"), + ET.PERMANENT: NormalPermanentAlert("LKAS Fault: Restart the car to engage"), + ET.NO_ENTRY: NoEntryAlert("LKAS Fault: Restart the Car"), + }, + + EventName.reverseGear: { + ET.PERMANENT: Alert( + "Reverse\nGear", + "", + AlertStatus.normal, AlertSize.full, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), + ET.USER_DISABLE: reverse_gear_disable_alert, + ET.NO_ENTRY: NoEntryAlert("Reverse Gear"), + }, + + # On cars that use stock ACC the car can decide to cancel ACC for various reasons. + # When this happens we can no long control the car so the user needs to be warned immediately. + EventName.cruiseDisabled: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Is Off"), + }, + + # When the relay in the harness box opens the CAN bus between the LKAS camera + # and the rest of the car is separated. When messages from the LKAS camera + # are received on the car side this usually means the relay hasn't opened correctly + # and this alert is thrown. + EventName.relayMalfunction: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Harness Relay Malfunction"), + ET.PERMANENT: NormalPermanentAlert("Harness Relay Malfunction", "Check Hardware"), + ET.NO_ENTRY: NoEntryAlert("Harness Relay Malfunction"), + }, + + EventName.speedTooLow: { + ET.IMMEDIATE_DISABLE: Alert( + "openpilot Canceled", + "Speed too low", + AlertStatus.normal, AlertSize.mid, + Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), + }, + + # When the car is driving faster than most cars in the training data, the model outputs can be unpredictable. + EventName.speedTooHigh: { + ET.WARNING: Alert( + "Speed Too High", + "Model uncertain at this speed", + AlertStatus.userPrompt, AlertSize.mid, + Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 4.), + ET.NO_ENTRY: NoEntryAlert("Slow down to engage"), + }, + + EventName.vehicleSensorsInvalid: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Vehicle Sensors Invalid"), + ET.PERMANENT: NormalPermanentAlert("Vehicle Sensors Calibrating", "Drive to Calibrate"), + ET.NO_ENTRY: NoEntryAlert("Vehicle Sensors Calibrating"), + }, + + EventName.personalityChanged: { + ET.WARNING: personality_changed_alert, + }, + + EventName.pedalCruiseEnabled: { + ET.PERMANENT: Alert( + "Pedal Cruise Engaged", + "", + AlertStatus.normal, AlertSize.small, + Priority.HIGH, VisualAlert.none, AudibleAlert.engage, 0.8), + }, + + EventName.pedalCruiseDisabled: { + ET.PERMANENT: Alert( + "Pedal Cruise Disengaged", + "", + AlertStatus.normal, AlertSize.small, + Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 0.8), + }, + + EventName.pedalMaxRegen: { + ET.WARNING: Alert( + "Regen Limit Reached", + "Press Brake to Slow Down", + AlertStatus.userPrompt, AlertSize.mid, + Priority.HIGH, VisualAlert.brakePressed, AudibleAlert.promptRepeat, .2), + }, + + EventName.teslaCCEngaged: { + ET.PERMANENT: Alert( + "Tesla Cruise Engaged", + "", + AlertStatus.normal, AlertSize.small, + Priority.HIGH, VisualAlert.none, AudibleAlert.engage, 0.8), + }, + + EventName.teslaCCDisengaged: { + ET.PERMANENT: Alert( + "Tesla Cruise Disengaged", + "", + AlertStatus.normal, AlertSize.small, + Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 0.8), + }, + + EventName.teslaCCNotArmed: { + ET.PERMANENT: NormalPermanentAlert("Arm Stock Cruise to Enable Speed Control"), + }, + + EventName.pedalUnavailable: { + ET.WARNING: Alert( + "Pedal Control Unavailable", + "Speed Control Disabled", + AlertStatus.userPrompt, AlertSize.mid, + Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.0), + }, + + EventName.radarPreferFallback: { + ET.PERMANENT: radar_prefer_fallback_permanent_alert, + ET.WARNING: radar_prefer_fallback_warning_alert, + }, + + + EventName.userBookmark: { + ET.PERMANENT: NormalPermanentAlert("Bookmark Saved", duration=1.5), + }, + + EventName.audioFeedback: { + ET.PERMANENT: audio_feedback_alert, + }, +} + +# Keep generated EventName.hypermileFollowChanged (@108). nap-release uses +# followDistanceChanged at the same ordinal — accept either name. +_hypermile_follow_changed = getattr(EventName, "hypermileFollowChanged", None) or getattr(EventName, "followDistanceChanged", None) +if _hypermile_follow_changed is not None: + EVENTS[_hypermile_follow_changed] = { + ET.WARNING: hypermile_follow_changed_alert, + ET.PERMANENT: hypermile_follow_changed_alert, + } + +_nap_wiper_changed = getattr(EventName, "napWiperChanged", None) +if _nap_wiper_changed is not None: + EVENTS[_nap_wiper_changed] = { + ET.WARNING: nap_wiper_changed_alert, + ET.PERMANENT: nap_wiper_changed_alert, + } + +_gap_lock = getattr(EventName, "gapLock", None) +if _gap_lock is not None: + EVENTS[_gap_lock] = { + ET.WARNING: gap_lock_alert, + ET.PERMANENT: gap_lock_alert, + } + +# One text for model-blind and camera-blind. Warning only: no disable. +_low_visibility = getattr(EventName, "lowVisibility", None) +if _low_visibility is not None: + EVENTS[_low_visibility] = { + ET.WARNING: Alert( + "Low visibility", + "Take over if needed", + AlertStatus.userPrompt, AlertSize.mid, + Priority.MID, VisualAlert.steerRequired, AudibleAlert.none, 0.5), + } + +# Low visibility latched past 45 s: never a silent degraded mode. Louder, +# repeating prompt and a distinct text. Still a warning, not a disable. +_low_visibility_prolonged = getattr(EventName, "lowVisibilityProlonged", None) +if _low_visibility_prolonged is not None: + EVENTS[_low_visibility_prolonged] = { + ET.WARNING: Alert( + "Steering still reduced", + "Low visibility over 45 s - steer now", + AlertStatus.userPrompt, AlertSize.mid, + Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 0.5), + } + + +def obstacle_chime_alert(CP, CS, sm, metric, soft_disable_time, personality): + """Small text only. The wav is selected in soundd from this alert type. + + AudibleAlert stays none so we do not need a new car.capnp ordinal. + Permanent: the chime plays whether or not openpilot is engaged. + """ + title = "Object ahead" + try: + from openpilot.selfdrive.controls.lib.path_obstacle import chime_banner + obs = sm['pathObstacleVisionNAP'] + title = chime_banner(obs.objectClass, obs.zone) + except Exception: + pass + return Alert( + title, "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1.2, + ) + + +# Permanent only. No enable, no entry block, no disengage. +_obstacle_chime = getattr(EventName, "obstacleChime", None) +if _obstacle_chime is not None: + EVENTS[_obstacle_chime] = { + ET.PERMANENT: obstacle_chime_alert, + } + + +if HARDWARE.get_device_type() == 'mici': + EVENTS.update({ + EventName.driverDistracted1: { + ET.PERMANENT: Alert( + "Pay Attention", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 2), + }, + EventName.driverDistracted2: { + ET.PERMANENT: Alert( + "Pay Attention", + "Driver Distracted", + AlertStatus.userPrompt, AlertSize.mid, + Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, 1), + }, + EventName.resumeRequired: { + ET.WARNING: Alert( + "Press Resume", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), + }, + EventName.preLaneChangeLeft: { + ET.WARNING: Alert( + "Steer Left", + "Confirm Lane Change", + AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + EventName.preLaneChangeRight: { + ET.WARNING: Alert( + "Steer Right", + "Confirm Lane Change", + AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + EventName.laneChangeBlocked: { + ET.WARNING: Alert( + "Car in Blindspot", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.prompt, .1), + }, + EventName.steerSaturated: { + ET.WARNING: Alert( + "take control", + "turn exceeds limit", + AlertStatus.userPrompt, AlertSize.mid, + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 2.), + }, + EventName.calibrationIncomplete: { + ET.PERMANENT: calibration_incomplete_alert, + ET.SOFT_DISABLE: soft_disable_alert("Calibration Incomplete"), + ET.NO_ENTRY: NoEntryAlert("Calibrating"), + }, + EventName.reverseGear: { + ET.PERMANENT: Alert( + "Reverse", + "", + AlertStatus.normal, AlertSize.full, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), + ET.USER_DISABLE: ImmediateDisableAlert("Reverse"), + ET.NO_ENTRY: NoEntryAlert("Reverse"), + }, + }) + + +if __name__ == '__main__': + # print all alerts by type and priority + from cereal.services import SERVICE_LIST + from collections import defaultdict + + event_names = {v: k for k, v in EventName.schema.enumerants.items()} + alerts_by_type: dict[str, dict[Priority, list[str]]] = defaultdict(lambda: defaultdict(list)) + + CP = car.CarParams.new_message() + CS = car.CarState.new_message() + sm = messaging.SubMaster(list(SERVICE_LIST.keys())) + + for i, alerts in EVENTS.items(): + for et, alert in alerts.items(): + if not isinstance(alert, Alert): + alert = alert(CP, CS, sm, False, 1, log.LongitudinalPersonality.standard) + alerts_by_type[et][alert.priority].append(event_names[i]) + + all_alerts: dict[str, list[tuple[Priority, list[str]]]] = {} + for et, priority_alerts in alerts_by_type.items(): + all_alerts[et] = sorted(priority_alerts.items(), key=lambda x: x[0], reverse=True) + + for status, evs in sorted(all_alerts.items(), key=lambda x: x[0]): + print(f"**** {status} ****") + for p, alert_list in evs: + print(f" {repr(p)}:") + print(" ", ', '.join(alert_list), "\n") diff --git a/selfdrive/selfdrived/helpers.py b/selfdrive/selfdrived/helpers.py new file mode 100644 index 00000000000000..c2697a6bc73d9f --- /dev/null +++ b/selfdrive/selfdrived/helpers.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import math +from enum import StrEnum, auto +from typing import TYPE_CHECKING + +from opendbc.car import ACCELERATION_DUE_TO_GRAVITY, DT_CTRL +from opendbc.car.lateral import ISO_LATERAL_ACCEL +from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX +from openpilot.selfdrive.selfdrived.lane_change_alerts import install_lane_change_alerts + +if TYPE_CHECKING: + from cereal import car, messaging + from openpilot.selfdrive.locationd.helpers import Pose + +MIN_EXCESSIVE_ACTUATION_COUNT = int(0.25 / DT_CTRL) +MIN_LATERAL_ENGAGE_BUFFER = int(1 / DT_CTRL) + +PREAP_FINGERPRINT = "TESLA_MODEL_S_PREAP" + +# selfdrived imports this module: swap in the armed lane change prompts that +# can say "Lane lines unclear" (see lane_change_alerts). +install_lane_change_alerts() + +# Stock comma: 2× ISO 11270 (6.0 m/s², ~0.61 g) and 2× planner accel clip +# (4.0 / −7.0 m/s²). That is meant to catch a true emergency actuation, but +# on Pre-AP Model S it false-trips a faster-but-legal ramp or firm decel +# ("excessive" / emergency-maneuver knockoff). +EXCESSIVE_LAT_ACCEL = ISO_LATERAL_ACCEL * 2.0 # 6.0 m/s² +EXCESSIVE_LONG_ACCEL_POS = ACCEL_MAX * 2.0 # 4.0 m/s² +EXCESSIVE_LONG_ACCEL_NEG = ACCEL_MIN * 2.0 # -7.0 m/s² + +# Pre-AP / NAP: raise a fair amount (3×) so ~0.5–0.75 g corners stay in. +# 9.0 m/s² (~0.92 g) / 6.0 / −10.5 still trip a real emergency swerve or +# panic stop. Do not disable this path; locationd / camera soft-disables +# are unchanged. +PREAP_EXCESSIVE_LAT_ACCEL = ISO_LATERAL_ACCEL * 3.0 # 9.0 m/s² +PREAP_EXCESSIVE_LONG_ACCEL_POS = ACCEL_MAX * 3.0 # 6.0 m/s² +PREAP_EXCESSIVE_LONG_ACCEL_NEG = ACCEL_MIN * 3.0 # -10.5 m/s² + + +def excessive_actuation_limits(fingerprint: str = "") -> tuple[float, float, float]: + """Return (lat, long_pos, long_neg) thresholds for this car.""" + if fingerprint == PREAP_FINGERPRINT: + return (PREAP_EXCESSIVE_LAT_ACCEL, + PREAP_EXCESSIVE_LONG_ACCEL_POS, + PREAP_EXCESSIVE_LONG_ACCEL_NEG) + return (EXCESSIVE_LAT_ACCEL, EXCESSIVE_LONG_ACCEL_POS, EXCESSIVE_LONG_ACCEL_NEG) + + +class ExcessiveActuationType(StrEnum): + LONGITUDINAL = auto() + LATERAL = auto() + + +class ExcessiveActuationCheck: + def __init__(self, fingerprint: str = ""): + self._excessive_counter = 0 + self._engaged_counter = 0 + self._lat_limit, self._long_pos, self._long_neg = excessive_actuation_limits(fingerprint) + + def update(self, sm: messaging.SubMaster, CS: car.CarState, calibrated_pose: Pose) -> ExcessiveActuationType | None: + # CS.aEgo can be noisy to bumps in the road, transitioning from standstill, losing traction, etc. + # longitudinal + accel_calibrated = calibrated_pose.acceleration.x + excessive_long_actuation = sm['carControl'].longActive and (accel_calibrated > self._long_pos or accel_calibrated < self._long_neg) + + # lateral + yaw_rate = calibrated_pose.angular_velocity.yaw + roll = sm['liveParameters'].roll + roll_compensated_lateral_accel = (CS.vEgo * yaw_rate) - (math.sin(roll) * ACCELERATION_DUE_TO_GRAVITY) + + # Prevent false positives after overriding + excessive_lat_actuation = False + self._engaged_counter = self._engaged_counter + 1 if sm['carControl'].latActive and not CS.steeringPressed else 0 + if self._engaged_counter > MIN_LATERAL_ENGAGE_BUFFER: + if abs(roll_compensated_lateral_accel) > self._lat_limit: + excessive_lat_actuation = True + + # livePose acceleration can be noisy due to bad mounting or aliased livePose measurements + livepose_valid = abs(CS.aEgo - accel_calibrated) < 2 + self._excessive_counter = self._excessive_counter + 1 if livepose_valid and (excessive_long_actuation or excessive_lat_actuation) else 0 + + excessive_type = None + if self._excessive_counter > MIN_EXCESSIVE_ACTUATION_COUNT: + if excessive_long_actuation: + excessive_type = ExcessiveActuationType.LONGITUDINAL + else: + excessive_type = ExcessiveActuationType.LATERAL + + return excessive_type + + +def _gear_is_drive(gear) -> bool: + name = getattr(gear, "name", gear) + return name == "drive" or gear == "drive" + + +def preap_not_in_drive_clears_mismatch(*, fingerprint: str, gear) -> bool: + """True while Pre-AP gear is not Drive. + + Hold the 3X/OP controls-mismatch counters at 0 for the whole R/P + (gear-out) period so the latch is already gone before Drive return. + Same cleanup spirit as stalk cancel. Do not clear on Drive entry: + in-Drive engagement uses the normal live panda/selfdrived checks. + """ + if fingerprint != PREAP_FINGERPRINT: + return False + return not _gear_is_drive(gear) diff --git a/selfdrive/selfdrived/housekeeping_comm.py b/selfdrive/selfdrived/housekeeping_comm.py new file mode 100644 index 00000000000000..13e525dfb23be3 --- /dev/null +++ b/selfdrive/selfdrived/housekeeping_comm.py @@ -0,0 +1,145 @@ +"""Housekeeping commIssue policy for deviceState and managerState. + +Those two 2 Hz messages are not on the driving path. SubMaster's strict +alive check is 10 periods (5 s at 2 Hz), which is what turned a hardwared +publish stall into "Communication Issue Between Processes" while carState, +controls, model, and radar all stayed healthy. + +They are left out of that strict alive/freq/valid check. This module +raises commIssue only after either one has been silent for more than +HOUSEKEEPING_SILENCE_S, measured from the receive timestamp or, when that +was never recorded, from logMonoTime. +""" + +HOUSEKEEPING_SERVICES = ("deviceState", "managerState") +HOUSEKEEPING_SILENCE_S = 10.0 + + +def message_silence_s(recv_time: float, log_mono_time: int, now: float) -> float | None: + """Seconds since the last message. + + `recv_time` is SubMaster.recv_time (time.monotonic when the message + arrived). `log_mono_time` is the publisher logMonoTime in nanoseconds. + Arrival is what "silent" means, so a recorded recv_time wins. logMonoTime + covers the case where the only timestamp we have is the publish time, + compared on the same second-scale clock as `now`. None means the service + has never been observed. + """ + if recv_time > 0.0: + return now - recv_time + if log_mono_time > 0: + return now - (log_mono_time * 1e-9) + return None + + +def device_state_seen(recv_time: float, log_mono_time: int) -> bool: + """True once deviceState has arrived at least once. + + Thermal, free space, and memory reads must keep using that last message + across a short stall. A zeroed stand-in (free space 0) is not a real sample. + """ + return recv_time > 0.0 or log_mono_time > 0 + + +def housekeeping_silent_services( + recv_times: dict[str, float], + log_mono_times: dict[str, int], + now: float, + *, + frame: int = 0, + dt: float = 0.01, + skip: tuple[str, ...] = (), +) -> list[str]: + """Services in HOUSEKEEPING_SERVICES that have been silent for more than 10 s. + + A service that has never been observed ages with the controller frame clock + (`frame * dt`) so a hardwared that never starts still disengages, about 5 s + later than the old 5 s alive window. `skip` is for modes that already drop + a service entirely (managerState under SIMULATION / REPLAY). + """ + silent: list[str] = [] + for service in HOUSEKEEPING_SERVICES: + if service in skip: + continue + age = message_silence_s( + recv_times.get(service, 0.0), + log_mono_times.get(service, 0), + now, + ) + if age is None: + age = frame * dt + if age > HOUSEKEEPING_SILENCE_S: + silent.append(service) + return silent + + +def classify_comm_issue( + *, + all_alive: bool, + all_freq_ok: bool, + all_valid: bool, + housekeeping_silent: list[str], +) -> str | None: + """commIssue / commIssueAvgFreq for one selfdrived step. + + `all_*` are the strict SubMaster results and must already exclude + housekeeping services. A housekeeping silence is commIssue, same as a + driving service that is not alive. Frequency and valid failures of every + other service are unchanged. + """ + if housekeeping_silent or not all_alive: + return "commIssue" + if not all_freq_ok: + return "commIssueAvgFreq" + if not all_valid: + return "commIssue" + return None + + +def submaster_ignore_services( + sensor_packets: list[str], + gps_packets: list[str], + *, + simulation: bool, + replay: bool, +) -> list[str]: + """Services dropped from SubMaster alive, average-frequency, and valid checks. + + Mirrors SelfdriveD's ignore list, including the housekeeping append. + Driving services are not in this list. + """ + ignore = list(sensor_packets) + list(gps_packets) + [ + "alertDebug", + "lateralManeuverPlan", + "pathObstacleNAP", + "pathObstacleVisionNAP", + ] + if simulation: + ignore += ["driverCameraState", "managerState"] + if replay: + ignore += ["roadCameraState", "wideRoadCameraState", "driverCameraState", "managerState"] + ignore += list(HOUSEKEEPING_SERVICES) + return ignore + + +def device_health_events( + thermal_status, + free_space_percent: float, + memory_usage_percent: int, + *, + simulation: bool, + overheated, +) -> list[str]: + """Events from the last deviceState sample. + + Callers pass the message still held by SubMaster. Do not substitute zeros + when the publisher stalls, and do not consult alive / freq / valid here. + """ + events: list[str] = [] + if thermal_status >= overheated: + events.append("overheat") + if free_space_percent < 7 and not simulation: + events.append("outOfSpace") + if memory_usage_percent > 90 and not simulation: + events.append("lowMemory") + return events diff --git a/selfdrive/selfdrived/lane_change_alerts.py b/selfdrive/selfdrived/lane_change_alerts.py new file mode 100644 index 00000000000000..703df37d0d8bbb --- /dev/null +++ b/selfdrive/selfdrived/lane_change_alerts.py @@ -0,0 +1,48 @@ +"""Armed lane change prompt, with a "Lane lines unclear" state. + +DesireHelper keeps a confirmed lane change armed (and retries the target +lock) when the lane line to cross is not confident. Once the retry runs out +it flags that in modelV2.meta.laneChangeSignalsRemaining (an otherwise +unused countdown; no capnp change) and this prompt tells the driver why +nothing is happening. Installed over the stock prompts by selfdrived. +""" +from cereal import car, log +import cereal.messaging as messaging +from openpilot.selfdrive.controls.lib.lane_change_target import LANE_LINES_UNCLEAR_SIGNAL +from openpilot.selfdrive.selfdrived.events import EVENTS, ET, Alert, AlertCallbackType, Priority +from openpilot.system.hardware import HARDWARE + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus +VisualAlert = car.CarControl.HUDControl.VisualAlert +AudibleAlert = car.CarControl.HUDControl.AudibleAlert +EventName = log.OnroadEvent.EventName + + +def pre_lane_change_alert(left: bool, mici: bool) -> AlertCallbackType: + side = "Left" if left else "Right" + + def alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + try: + unclear = sm['modelV2'].meta.laneChangeSignalsRemaining == LANE_LINES_UNCLEAR_SIGNAL + except Exception: + unclear = False + if unclear: + if mici: + return Alert("Lane lines unclear", "Steer to Change Lane When Clear", AlertStatus.userPrompt, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1) + return Alert("Lane lines unclear", "", AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1) + if mici: + return Alert(f"Steer {side}", "Confirm Lane Change", AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1) + return Alert(f"Steer {side} to Start Lane Change Once Safe", "", AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1) + return alert + + +def install_lane_change_alerts(events=EVENTS, mici: bool | None = None) -> None: + if mici is None: + mici = HARDWARE.get_device_type() == 'mici' + events[EventName.preLaneChangeLeft] = {ET.WARNING: pre_lane_change_alert(True, mici)} + events[EventName.preLaneChangeRight] = {ET.WARNING: pre_lane_change_alert(False, mici)} diff --git a/selfdrive/selfdrived/preap_regen.py b/selfdrive/selfdrived/preap_regen.py new file mode 100644 index 00000000000000..52d93793385e53 --- /dev/null +++ b/selfdrive/selfdrived/preap_regen.py @@ -0,0 +1,167 @@ +"""Pre-AP pedal-long helpers used by selfdrived. + +RegenDemandCheck reads the unclamped plan and prompts when planned +deceleration sits below the regen envelope floor. The carstate +pedalMaxRegen flag covers the other failure shape: a request inside the +envelope that weak battery regen fails to deliver. + +update_preap_chimes edge-detects lat and long engage/disengage. Long +follows FSM intent (enableLongControl), not interceptor handshake, so a +stalk engage chimes immediately. Gas override is not an engagement edge: +enableLongControl stays true while the driver is on the pedal, so press +and release are silent. + +A brake long drop that keeps cruiseEnabled is a silent pause: do not +fire pedalCruiseDisabled / AudibleAlert.disengage. One-Pedal Long gas +from rest uses that same pause — not USER_DISABLE / full session +cancel. One SET that only restores long from that pause is also quiet. +A latched driver-turn blinker does not drop long. Full cancel (session +down) still chimes disengage. +""" +import math +from typing import NamedTuple + +from opendbc.car.tesla.preap.interface import get_preap_accel_limits + +# Match openpilot.common.realtime.DT_CTRL without importing hardware. +DT_CTRL = 0.01 + +# Evidence accumulates in a saturating up/down counter so a single MPC sample +# cannot flash a driver prompt, while brief dropouts do not restart the clock. +REGEN_DEMAND_EVIDENCE_COUNT = int(0.3 / DT_CTRL) +REGEN_DEMAND_TRIGGER_MARGIN = 0.2 # m/s² below the envelope floor +REGEN_DEMAND_CLEAR_MARGIN = 0.05 # m/s² +REGEN_DEMAND_MIN_SPEED = 2.0 # m/s; do not prompt for a stopped/settling car +REGEN_DEMAND_CLEAR_SPEED = 1.0 # m/s +# The prompt means "regen cannot cover this, add friction brake". With a +# post-guard command available, a plan below the floor only prompts once the +# command itself is pinned at the rail (15d 15:27:31: plan -1.94 but the +# actuator sat at -0.22, so the car was not asking for more than regen had). +REGEN_DEMAND_CMD_PIN_MARGIN = 0.05 # m/s² above the envelope floor + + +class PreAPChimeState(NamedTuple): + lat_engaged: bool = False + long_engaged: bool = False + long_paused: bool = False + + +class PreAPChimes(NamedTuple): + lat_engage: bool = False + lat_disengage: bool = False + long_engage: bool = False + long_disengage: bool = False + + +def update_preap_chimes(*, lat_engaged: bool, long_engaged: bool, + prev: PreAPChimeState) -> tuple[PreAPChimes, PreAPChimeState]: + """Rising/falling edges for Pre-AP lat and long driver prompts. + + Long-only drop while the session stays up (brake / One-Pedal Long gas + pause / driver-turn pause) is silent. Long-only resume from that pause + is silent. Initial second pull and full re-engage still chime + long-engage. Session-down long drop still chimes long-disengage + (pedalCruiseDisabled). + """ + silent_pause = ( + prev.lat_engaged and lat_engaged + and prev.long_engaged and not long_engaged + ) + long_rising = long_engaged and not prev.long_engaged + quiet_resume = long_rising and prev.long_paused and lat_engaged + chimes = PreAPChimes( + lat_engage=lat_engaged and not prev.lat_engaged, + lat_disengage=(not lat_engaged) and prev.lat_engaged, + long_engage=long_rising and not quiet_resume, + long_disengage=(not long_engaged) and prev.long_engaged and not silent_pause, + ) + if not lat_engaged: + long_paused = False + elif silent_pause: + long_paused = True + elif long_engaged: + long_paused = False + else: + long_paused = prev.long_paused + return chimes, PreAPChimeState(lat_engaged, long_engaged, long_paused) + + +def orphan_pull_requests_enable(*, cruise_enabled: bool, op_enabled: bool, + set_pressed: bool, use_pedal: bool, + long_on: bool) -> bool: + """Stalk pull while the car session is latched and openpilot is not. + + Pedal mode: that single pull is the engage. No-pedal: only a pull that + already has longitudinal on (the completing half of a double pull, or a + session that already took long). A lone first pull stays lateral-only. + """ + if not (bool(cruise_enabled) and not bool(op_enabled) and bool(set_pressed)): + return False + if bool(use_pedal): + return True + return bool(long_on) + + +def gas_should_user_disable(*, disengage_on_accelerator: bool, + one_pedal_long: bool) -> bool: + """Rising-gas EventName.pedalPressed is stock DisengageOnAccelerator. + + That event is USER_DISABLE (full session cancel / take-control). + One-Pedal Long On must never take it: gas-from-rest is the same + silent long pause as brake (lat stays, sticky MAX, one SET resumes). + This does not touch OVERRIDE_LONGITUDINAL or the A+B / A3 gas-lift + handoff. Engage-while-gas-pressed still starts long on lift. + Toggle Off (default): stock DisengageOnAccelerator still applies. + """ + return bool(disengage_on_accelerator) and not bool(one_pedal_long) + + +class RegenDemandCheck: + """Prompt when planned deceleration exceeds what the regen envelope allows. + + With the post-guard command (`a_cmd`), the trigger also needs that command + pinned at the envelope floor. Keeping an active prompt is plan-only. + """ + + def __init__(self): + self.active = False + self.evidence_updates = 0 + + def reset(self): + self.active = False + self.evidence_updates = 0 + + def update(self, *, pedal_long_active: bool, brake_pressed: bool, + a_target: float, v_ego: float, a_cmd: float | None = None) -> bool: + if not pedal_long_active or brake_pressed or not math.isfinite(a_target): + self.reset() + return False + + accel_floor, _ = get_preap_accel_limits(v_ego) + + if self.active: + keep_prompting = ( + v_ego > REGEN_DEMAND_CLEAR_SPEED + and a_target <= accel_floor - REGEN_DEMAND_CLEAR_MARGIN + ) + if not keep_prompting: + self.reset() + return self.active + + # `a_cmd` is the post-guard actuator command. Unknown (None / not finite) + # keeps the plan-only rule: when in doubt, prompt. + cmd_pinned = ( + a_cmd is None or not math.isfinite(a_cmd) + or a_cmd <= accel_floor + REGEN_DEMAND_CMD_PIN_MARGIN + ) + demanding = ( + v_ego >= REGEN_DEMAND_MIN_SPEED + and a_target <= accel_floor - REGEN_DEMAND_TRIGGER_MARGIN + and cmd_pinned + ) + if demanding: + self.evidence_updates = min(self.evidence_updates + 1, REGEN_DEMAND_EVIDENCE_COUNT) + else: + self.evidence_updates = max(self.evidence_updates - 1, 0) + self.active = self.evidence_updates >= REGEN_DEMAND_EVIDENCE_COUNT + return self.active diff --git a/selfdrive/selfdrived/selfdrived.py b/selfdrive/selfdrived/selfdrived.py new file mode 100644 index 00000000000000..2eedb200afdb81 --- /dev/null +++ b/selfdrive/selfdrived/selfdrived.py @@ -0,0 +1,855 @@ +#!/usr/bin/env python3 +import os +import time +import threading + +import cereal.messaging as messaging + +from cereal import car, log +from msgq.visionipc import VisionIpcClient, VisionStreamType + + +from openpilot.common.params import Params +from openpilot.common.realtime import config_realtime_process, Priority, Ratekeeper, DT_CTRL +from openpilot.common.swaglog import cloudlog +from openpilot.common.gps import get_gps_location_service + +from openpilot.selfdrive.car.car_specific import CarSpecificEvents +from openpilot.selfdrive.controls.lib.blinker_lateral_pause import ( + preap_blinker_pause_hides_controls_mismatch, +) +from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose +from openpilot.selfdrive.selfdrived.events import Events, ET +from openpilot.selfdrive.controls.lib.lat_low_visibility import PROLONGED_S as LOW_VIS_PROLONGED_S +from openpilot.selfdrive.selfdrived.helpers import ExcessiveActuationCheck, preap_not_in_drive_clears_mismatch +from openpilot.selfdrive.controls.lib.preap_driver_brake import ( + BrakeLongOverlap, + brake_signal_disables, + driver_brake_applied, + preap_pedal_long, +) +from openpilot.selfdrive.selfdrived.housekeeping_comm import ( + HOUSEKEEPING_SERVICES, + classify_comm_issue, + device_health_events, + device_state_seen, + housekeeping_silent_services, +) +from openpilot.selfdrive.selfdrived.preap_regen import ( + PreAPChimeState, RegenDemandCheck, gas_should_user_disable, orphan_pull_requests_enable, + update_preap_chimes, +) +from openpilot.selfdrive.selfdrived.state import StateMachine +from openpilot.selfdrive.selfdrived.alertmanager import AlertManager, set_offroad_alert + +from openpilot.system.version import get_build_metadata +from openpilot.system.hardware import HARDWARE +from openpilot.system.manager.optional_procs import missing_required_processes + +REPLAY = "REPLAY" in os.environ +SIMULATION = "SIMULATION" in os.environ +TESTING_CLOSET = "TESTING_CLOSET" in os.environ + +LONGITUDINAL_PERSONALITY_MAP = {v: k for k, v in log.LongitudinalPersonality.schema.enumerants.items()} + +ThermalStatus = log.DeviceState.ThermalStatus +State = log.SelfdriveState.OpenpilotState +PandaType = log.PandaState.PandaType +LaneChangeState = log.LaneChangeState +LaneChangeDirection = log.LaneChangeDirection +EventName = log.OnroadEvent.EventName +ButtonType = car.CarState.ButtonEvent.Type +SafetyModel = car.CarParams.SafetyModel +AlertLevel = log.DriverMonitoringState.AlertLevel +MonitoringPolicy = log.DriverMonitoringState.MonitoringPolicy + +IGNORED_SAFETY_MODES = (SafetyModel.silent, SafetyModel.noOutput) + + +class SelfdriveD: + def __init__(self, CP=None): + self.params = Params() + + # Ensure the current branch is cached, otherwise the first cycle lags + build_metadata = get_build_metadata() + + if CP is None: + cloudlog.info("selfdrived is waiting for CarParams") + self.CP = messaging.log_from_bytes(self.params.get("CarParams", block=True), car.CarParams) + cloudlog.info("selfdrived got CarParams") + else: + self.CP = CP + + self.car_events = CarSpecificEvents(self.CP) + + self.pose_calibrator = PoseCalibrator() + self.calibrated_pose: Pose | None = None + self.excessive_actuation_check = ExcessiveActuationCheck(fingerprint=self.CP.carFingerprint) + self.excessive_actuation = self.params.get("Offroad_ExcessiveActuation") is not None + + # Setup sockets + self.pm = messaging.PubMaster(['selfdriveState', 'onroadEvents']) + + self.gps_location_service = get_gps_location_service(self.params) + self.gps_packets = [self.gps_location_service] + self.sensor_packets = ["accelerometer", "gyroscope"] + self.camera_packets = ["roadCameraState", "driverCameraState", "wideRoadCameraState"] + + # TODO: de-couple selfdrived with card/conflate on carState without introducing controls mismatches + self.car_state_sock = messaging.sub_sock('carState', timeout=20) + + ignore = self.sensor_packets + self.gps_packets + ['alertDebug', 'lateralManeuverPlan', 'pathObstacleNAP', 'pathObstacleVisionNAP'] + if SIMULATION: + ignore += ['driverCameraState', 'managerState'] + if REPLAY: + # no vipc in replay will make them ignored anyways + # sanitized fixtures omit driverCameraState/managerState; ignore them in replay + ignore += ['roadCameraState', 'wideRoadCameraState', 'driverCameraState', 'managerState'] + # deviceState and managerState are housekeeping. A few seconds of silence + # there must not fail the strict alive/freq/valid checks (commIssue). + # A real death is handled below with a 10 s receive-timestamp window. + ignore += list(HOUSEKEEPING_SERVICES) + self.sm = messaging.SubMaster(['deviceState', 'pandaStates', 'peripheralState', 'modelV2', 'liveCalibration', + 'carOutput', 'driverMonitoringState', 'longitudinalPlan', 'livePose', 'liveDelay', + 'managerState', 'liveParameters', 'radarState', 'liveTorqueParameters', + 'controlsState', 'carControl', 'driverAssistance', 'alertDebug', 'userBookmark', 'audioFeedback', + 'lateralManeuverPlan', 'pathObstacleVisionNAP'] + \ + self.camera_packets + self.sensor_packets + self.gps_packets, + ignore_alive=ignore, ignore_avg_freq=ignore, + ignore_valid=ignore, frequency=int(1/DT_CTRL)) + + # read params + self.is_metric = self.params.get_bool("IsMetric") + self._low_vis_s = 0.0 + self.is_ldw_enabled = self.params.get_bool("IsLdwEnabled") + self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator") + self.one_pedal_long = self.params.get_bool("NAPOnePedalLong") + self.obstacle_chime = True + try: + self.obstacle_chime = bool(self.params.get_bool("NAPObstacleChime")) + except Exception: + self.obstacle_chime = True + + car_recognized = self.CP.brand != 'mock' + + # cleanup old params + if not self.CP.alphaLongitudinalAvailable: + self.params.remove("AlphaLongitudinalEnabled") + if not self.CP.openpilotLongitudinalControl: + self.params.remove("ExperimentalMode") + + self.CS_prev = car.CarState.new_message() + self.AM = AlertManager() + self.events = Events() + + self.initialized = False + self.enabled = False + self.active = False + self.mismatch_counter = 0 + self.cruise_mismatch_counter = 0 + self.last_steering_pressed_frame = 0 + self.distance_traveled = 0 + self.last_functional_fan_frame = 0 + self.events_prev = [] + self.logged_comm_issue = None + self.not_running_prev = None + self.experimental_mode = False + self.personality = self.params.get("LongitudinalPersonality", return_default=True) + self._follow_hud_dist = None + self._follow_hud_until = 0.0 + self._wiper_hud_until = 0.0 + self.recalibrating_seen = False + self.dm_lockout_set = False + self.dm_uncertain_alerted = False + self.state_machine = StateMachine() + self.rk = Ratekeeper(100, print_delay_threshold=None) + self.prev_preap_chimes = PreAPChimeState() + self.preap_regen_demand = RegenDemandCheck() + self.preap_brake_long = BrakeLongOverlap() + + # Determine startup event + self.startup_event = EventName.startup if build_metadata.openpilot.comma_remote and build_metadata.tested_channel else EventName.startupMaster + if HARDWARE.get_device_type() == 'mici': + self.startup_event = None + if not car_recognized: + self.startup_event = EventName.startupNoCar + elif car_recognized and self.CP.passive: + self.startup_event = EventName.startupNoControl + elif self.CP.secOcRequired and not self.CP.secOcKeyAvailable: + self.startup_event = EventName.startupNoSecOcKey + + if not car_recognized: + self.events.add(EventName.carUnrecognized, static=True) + set_offroad_alert("Offroad_CarUnrecognized", True) + elif self.CP.passive: + self.events.add(EventName.dashcamMode, static=True) + + def update_events(self, CS): + """Compute onroadEvents from carState""" + + self.events.clear() + + if self.sm['controlsState'].lateralControlState.which() == 'debugState': + self.events.add(EventName.joystickDebug) + self.startup_event = None + + if self.sm.recv_frame['lateralManeuverPlan'] > 0: + self.events.add(EventName.lateralManeuver) + self.startup_event = None + elif self.sm.recv_frame['alertDebug'] > 0: + self.events.add(EventName.longitudinalManeuver) + self.startup_event = None + + # Add startup event + if self.startup_event is not None: + self.events.add(self.startup_event) + self.startup_event = None + + # Don't add any more events if not initialized + if not self.initialized: + self.events.add(EventName.selfdriveInitializing) + return + + # Check for user bookmark press (bookmark button or end of LKAS button feedback) + if self.sm.updated['userBookmark']: + self.events.add(EventName.userBookmark) + + if self.sm.updated['audioFeedback']: + self.events.add(EventName.audioFeedback) + + # Don't add any more events while in dashcam mode + if self.CP.passive: + return + + # Block resume if cruise never previously enabled + resume_pressed = any(be.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for be in CS.buttonEvents) + if not self.CP.pcmCruise and CS.vCruise > 250 and resume_pressed: + self.events.add(EventName.resumeBlocked) + + # Handle DM + if not self.CP.notCar: + # Block engaging until ignition cycle after max number or time of distractions + if self.sm['driverMonitoringState'].lockout and not self.dm_lockout_set: + self.params.put_bool("DriverTooDistracted", True) + self.dm_lockout_set = True + # No entry conditions + if self.sm['driverMonitoringState'].lockout or self.sm['driverMonitoringState'].alwaysOnLockout: + self.events.add(EventName.tooDistracted) + # Alerts + vision_dm = self.sm['driverMonitoringState'].activePolicy == MonitoringPolicy.vision + if self.sm['driverMonitoringState'].alertLevel == AlertLevel.one: + self.events.add(EventName.driverDistracted1 if vision_dm else EventName.driverUnresponsive1) + elif self.sm['driverMonitoringState'].alertLevel == AlertLevel.two: + self.events.add(EventName.driverDistracted2 if vision_dm else EventName.driverUnresponsive2) + elif self.sm['driverMonitoringState'].alertLevel == AlertLevel.three: + self.events.add(EventName.driverDistracted3 if vision_dm else EventName.driverUnresponsive3) + # Warn consistent DM uncertainty + if self.sm['driverMonitoringState'].visionPolicyState.uncertainOffroadAlertPercent >= 100 and not self.dm_uncertain_alerted: + set_offroad_alert("Offroad_DriverMonitoringUncertain", True) + self.dm_uncertain_alerted = True + + # Add car events, ignore if CAN isn't valid + if CS.canValid: + car_events = self.car_events.update(CS, self.CS_prev, self.sm['carControl']).to_msg() + self.events.add_from_msg(car_events) + + # Tesla Pre-AP lat/long engage and disengage prompts. Long follows + # enableLongControl (stalk intent), not interceptor handshake and + # not gas override. Brake / One-Pedal Long gas-from-rest are silent + # long pauses (lat stays); a latched driver turn does not drop + # long. Full cancel still chimes pedalCruiseDisabled. Override + # (toggle Off) keeps enableLongControl true. + if (self.CP.brand == "tesla" + and self.CP.carFingerprint == "TESLA_MODEL_S_PREAP" + and self.CP.openpilotLongitudinalControl + and not self.CP.pcmCruise): + pedal_long_active = bool(CS.cruiseState.enabled and getattr(CS, 'pedalLongActive', False)) + chimes, self.prev_preap_chimes = update_preap_chimes( + lat_engaged=bool(CS.cruiseState.enabled), + long_engaged=bool(getattr(CS, 'enableLongControl', False)), + prev=self.prev_preap_chimes, + ) + if chimes.long_engage: + self.events.add(EventName.pedalCruiseEnabled) + elif chimes.long_disengage and self.enabled: + # A session openpilot never took (startup / noEntry) must reset + # quietly. A real cancel still chimes: self.enabled is still true + # until the state machine runs after this. + self.events.add(EventName.pedalCruiseDisabled) + set_press = any(be.type == ButtonType.setCruise and be.pressed for be in CS.buttonEvents) + use_pedal = True + if set_press: + try: + use_pedal = bool(self.params.get_bool("NAPPedalEnabled")) + except Exception: + use_pedal = True + if orphan_pull_requests_enable( + cruise_enabled=bool(CS.cruiseState.enabled), + op_enabled=bool(self.enabled), + set_pressed=set_press, + use_pedal=use_pedal, + long_on=bool(getattr(CS, "enableLongControl", False)), + ): + self.events.add(EventName.pcmEnable) + + # Two shapes of "regen is not enough, add friction brake": the carstate + # flag covers weak regen under-delivering an in-envelope request; the + # demand check covers a planned deceleration the envelope cannot cover, + # which the clamped actuator request hides from the car entirely. It + # only triggers while the post-guard command is also at the rail. + regen_demand_overflow = self.preap_regen_demand.update( + pedal_long_active=pedal_long_active, + brake_pressed=driver_brake_applied(CS), + a_target=float(self.sm['longitudinalPlan'].aTarget), + v_ego=CS.vEgo, + a_cmd=float(self.sm['carControl'].actuators.accel), + ) + if getattr(CS, 'pedalMaxRegen', False) or regen_demand_overflow: + self.events.add(EventName.pedalMaxRegen) + # Pedal RELEASE is the next 50 Hz command. Longer overlap is a + # regression. Log it; do not alert or chime. + fault, rising = self.preap_brake_long.update( + driver_brake=driver_brake_applied(CS), + pedal_long_active=bool(getattr(CS, "pedalLongActive", False)), + dt=DT_CTRL, + ) + if fault: + self.events.add(EventName.preapBrakeLongActive) + if rising: + cloudlog.error("preapBrakeLongActive: driver brake down while pedal long still active") + else: + self.prev_preap_chimes = PreAPChimeState() + self.preap_brake_long.reset() + + if self.CP.notCar: + # wait for everything to init first + if self.sm.frame > int(2. / DT_CTRL) and self.initialized: + # body always wants to enable + self.events.add(EventName.pcmEnable) + + # Disable on rising edge of accelerator or brake. Also disable on brake when speed > 0. + # + # Tesla Pre-AP hotfix: + # On brake/regen press, keep lateral active but drop longitudinal only. + # This mirrors expected "steering-only on brake" behavior for pedal-long cars. + # One-Pedal Long On: rising gas is that same silent long pause, never + # EventName.pedalPressed USER_DISABLE / full session cancel. + # Pre-AP reads driverBrakeApplied. brakePressed stays false so this + # path cannot see the pedal, and a true brakePressed must not be + # treated as the switch. The Pre-AP branch below is long-only + # (gasPressedOverride): lateral stays, a stalk pull resumes long. + preap_steering_only_brake = preap_pedal_long(self.CP) + brake_or_regen_disable = brake_signal_disables( + preap_pedal=preap_steering_only_brake, + driver_brake=driver_brake_applied(CS), + prev_driver_brake=driver_brake_applied(self.CS_prev), + brake_pressed=bool(CS.brakePressed), + prev_brake_pressed=bool(self.CS_prev.brakePressed), + regen_braking=bool(CS.regenBraking), + prev_regen_braking=bool(self.CS_prev.regenBraking), + standstill=bool(CS.standstill), + ) + gas_disable = ( + CS.gasPressed and not self.CS_prev.gasPressed + and gas_should_user_disable( + disengage_on_accelerator=self.disengage_on_accelerator, + one_pedal_long=preap_steering_only_brake and self.one_pedal_long, + ) + ) + if gas_disable: + self.events.add(EventName.pedalPressed) + elif brake_or_regen_disable: + if preap_steering_only_brake: + self.events.add(EventName.gasPressedOverride) + else: + self.events.add(EventName.pedalPressed) + + # Temperature, disk space, and memory come from the last deviceState. + # SubMaster keeps that sample while hardwared's publish loop stalls; + # alive/freq going false must not zero these or hide a real overheat. + ds = self.sm['deviceState'] + ds_seen = device_state_seen(self.sm.recv_time['deviceState'], self.sm.logMonoTime['deviceState']) + if ds_seen: + for health_name in device_health_events( + ds.thermalStatus, ds.freeSpacePercent, ds.memoryUsagePercent, + simulation=SIMULATION, overheated=ThermalStatus.overheated, + ): + self.events.add(getattr(EventName, health_name)) + + # Alert if fan isn't spinning for 5 seconds + if self.sm['peripheralState'].pandaType != log.PandaState.PandaType.unknown: + fan_desired = ds.fanSpeedPercentDesired if ds_seen else 0 + if self.sm['peripheralState'].fanSpeedRpm < 500 and fan_desired > 50: + # allow enough time for the fan controller in the panda to recover from stalls + if (self.sm.frame - self.last_functional_fan_frame) * DT_CTRL > 15.0: + self.events.add(EventName.fanMalfunction) + else: + self.last_functional_fan_frame = self.sm.frame + + # Handle calibration status + cal_status = self.sm['liveCalibration'].calStatus + if cal_status != log.LiveCalibrationData.Status.calibrated: + if cal_status == log.LiveCalibrationData.Status.uncalibrated: + self.events.add(EventName.calibrationIncomplete) + elif cal_status == log.LiveCalibrationData.Status.recalibrating: + if not self.recalibrating_seen: + set_offroad_alert("Offroad_Recalibration", True) + self.recalibrating_seen = True + self.events.add(EventName.calibrationRecalibrating) + else: + self.events.add(EventName.calibrationInvalid) + + # Lane departure warning + if self.is_ldw_enabled and self.sm.valid['driverAssistance']: + if self.sm['driverAssistance'].leftLaneDeparture or self.sm['driverAssistance'].rightLaneDeparture: + self.events.add(EventName.ldw) + + # Model or camera cannot see the road. Lateral is easing toward the + # driver in controlsd; this does not disengage and does not touch long. + # A degrade latched past LOW_VIS_PROLONGED_S is never silent: it swaps + # to a distinct, louder alert until it releases. + if self.enabled and bool(getattr(self.sm['controlsState'], 'lowVisibility', False)): + self._low_vis_s += DT_CTRL + low_vis = getattr(EventName, 'lowVisibility', None) + prolonged = getattr(EventName, 'lowVisibilityProlonged', None) + if prolonged is not None and self._low_vis_s + 1e-9 >= LOW_VIS_PROLONGED_S: + self.events.add(prolonged) + elif low_vis is not None: + self.events.add(low_vis) + else: + self._low_vis_s = 0.0 + + # Animal or person chime. Permanent, so it sounds engaged or not. + # It does not enter the state machine as a disable or a no-entry. + if self.obstacle_chime: + try: + from openpilot.selfdrive.controls.lib.path_obstacle import should_raise_chime + if self.sm.updated['pathObstacleVisionNAP']: + obs = self.sm['pathObstacleVisionNAP'] + if should_raise_chime(obs.chimed, obs.objectClass): + chime = getattr(EventName, 'obstacleChime', None) + if chime is not None: + self.events.add(chime) + except Exception: + pass + + # ****************************************************************************************** + # NOTE: To fork maintainers. + # Disabling or nerfing safety features will get you and your users banned from our servers. + # We recommend that you do not change these numbers from the defaults. + if self.sm.updated['liveCalibration']: + self.pose_calibrator.feed_live_calib(self.sm['liveCalibration']) + if self.sm.updated['livePose']: + device_pose = Pose.from_live_pose(self.sm['livePose']) + self.calibrated_pose = self.pose_calibrator.build_calibrated_pose(device_pose) + + if self.calibrated_pose is not None: + excessive_actuation = self.excessive_actuation_check.update(self.sm, CS, self.calibrated_pose) + if not self.excessive_actuation and excessive_actuation is not None: + set_offroad_alert("Offroad_ExcessiveActuation", True, extra_text=str(excessive_actuation)) + self.excessive_actuation = True + + if self.excessive_actuation: + self.events.add(EventName.excessiveActuation) + # ****************************************************************************************** + + # Handle lane change + if self.sm['modelV2'].meta.laneChangeState == LaneChangeState.preLaneChange: + direction = self.sm['modelV2'].meta.laneChangeDirection + if (CS.leftBlindspot and direction == LaneChangeDirection.left) or \ + (CS.rightBlindspot and direction == LaneChangeDirection.right): + self.events.add(EventName.laneChangeBlocked) + else: + if direction == LaneChangeDirection.left: + self.events.add(EventName.preLaneChangeLeft) + else: + self.events.add(EventName.preLaneChangeRight) + elif self.sm['modelV2'].meta.laneChangeState in (LaneChangeState.laneChangeStarting, + LaneChangeState.laneChangeFinishing): + self.events.add(EventName.laneChange) + + # While not in Drive (R/P/other): hold the 3X/OP mismatch latch clear + # so it is already gone before Drive return. Same cleanup as stalk + # cancel. In-Drive checks and engagement are unchanged. + if preap_not_in_drive_clears_mismatch( + fingerprint=self.CP.carFingerprint, + gear=CS.gearShifter, + ): + self.mismatch_counter = 0 + self.cruise_mismatch_counter = 0 + + for i, pandaState in enumerate(self.sm['pandaStates']): + # All pandas must match the list of safetyConfigs, and if outside this list, must be silent or noOutput + if i < len(self.CP.safetyConfigs): + safety_mismatch = pandaState.safetyModel != self.CP.safetyConfigs[i].safetyModel or \ + pandaState.safetyParam != self.CP.safetyConfigs[i].safetyParam or \ + pandaState.alternativeExperience != self.CP.alternativeExperience + else: + safety_mismatch = pandaState.safetyModel not in IGNORED_SAFETY_MODES + + # safety mismatch allows some time for pandad to set the safety mode and publish it back from panda. + # Do not turn a blinker-turn hands-on override into controlsMismatch / full cancel. + blinker_hides_mismatch = preap_blinker_pause_hides_controls_mismatch( + brand=self.CP.brand, fingerprint=self.CP.carFingerprint, + blocks_steer_disengage=self.car_events.blinker_lat_hold.blocks_steer_disengage) + if ((safety_mismatch and self.sm.frame*DT_CTRL > 10.) or pandaState.safetyRxChecksInvalid or + (self.mismatch_counter >= 200 and not blinker_hides_mismatch)): + self.events.add(EventName.controlsMismatch) + + if log.PandaState.FaultType.relayMalfunction in pandaState.faults: + self.events.add(EventName.relayMalfunction) + + # Handle HW and system malfunctions + # Order is very intentional here. Be careful when modifying this. + # All events here should at least have NO_ENTRY and SOFT_DISABLE. + num_events = len(self.events) + + not_running = set(missing_required_processes(self.sm['managerState'].processes)) + if self.sm.recv_frame['managerState'] and len(not_running): + if not_running != self.not_running_prev: + cloudlog.event("process_not_running", not_running=not_running, error=True) + self.not_running_prev = not_running + if self.sm.recv_frame['managerState'] and not_running: + self.events.add(EventName.processNotRunning) + else: + if not SIMULATION and not self.rk.lagging: + if not self.sm.all_alive(self.camera_packets): + self.events.add(EventName.cameraMalfunction) + elif not self.sm.all_freq_ok(self.camera_packets): + self.events.add(EventName.cameraFrameRate) + if not REPLAY and self.rk.lagging: + self.events.add(EventName.selfdrivedLagging) + if self.sm['radarState'].radarErrors.canError: + self.events.add(EventName.canError) + elif self.sm['radarState'].radarErrors.radarUnavailableTemporary: + self.events.add(EventName.radarTempUnavailable) + elif any(self.sm['radarState'].radarErrors.to_dict().values()): + self.events.add(EventName.radarFault) + elif getattr(self.sm['radarState'], "radarPreferFallback", False): + fallback_evt = getattr(EventName, "radarPreferFallback", None) + if fallback_evt is not None: + self.events.add(fallback_evt) + if not self.sm.valid['pandaStates']: + self.events.add(EventName.usbError) + if CS.canTimeout: + self.events.add(EventName.canBusMissing) + elif not CS.canValid: + self.events.add(EventName.canError) + + # generic catch-all. ideally, a more specific event should be added above instead + has_disable_events = self.events.contains(ET.NO_ENTRY) and (self.events.contains(ET.SOFT_DISABLE) or self.events.contains(ET.IMMEDIATE_DISABLE)) + no_system_errors = (not has_disable_events) or (len(self.events) == num_events) + # SIMULATION and REPLAY already omit managerState from the strict checks + # because it is not published there. Don't newly require it. + housekeeping_skip = ("managerState",) if (SIMULATION or REPLAY) else () + housekeeping_silent = housekeeping_silent_services( + self.sm.recv_time, self.sm.logMonoTime, time.monotonic(), + frame=self.sm.frame, dt=DT_CTRL, skip=housekeeping_skip, + ) + # all_checks ignores deviceState and managerState. Driving services + # still use the strict alive / freq / valid results below. + comm_kind = None + if no_system_errors: + comm_kind = classify_comm_issue( + all_alive=self.sm.all_alive(), + all_freq_ok=self.sm.all_freq_ok(), + all_valid=self.sm.all_valid(), + housekeeping_silent=housekeeping_silent, + ) + if comm_kind == "commIssue": + self.events.add(EventName.commIssue) + elif comm_kind == "commIssueAvgFreq": + self.events.add(EventName.commIssueAvgFreq) + + if comm_kind is not None: + logs = { + 'invalid': [s for s, valid in self.sm.valid.items() if not valid], + 'not_alive': [s for s, alive in self.sm.alive.items() if not alive], + 'not_freq_ok': [s for s, freq_ok in self.sm.freq_ok.items() if not freq_ok], + 'housekeeping_silent': housekeeping_silent, + } + if logs != self.logged_comm_issue: + cloudlog.event("commIssue", error=True, **logs) + self.logged_comm_issue = logs + else: + self.logged_comm_issue = None + + if not self.CP.notCar: + if not self.sm['livePose'].posenetOK: + self.events.add(EventName.posenetInvalid) + if not self.sm['livePose'].inputsOK: + self.events.add(EventName.locationdTemporaryError) + if not self.sm['liveParameters'].valid and cal_status == log.LiveCalibrationData.Status.calibrated and not TESTING_CLOSET and (not SIMULATION or REPLAY): + self.events.add(EventName.paramsdTemporaryError) + + # conservative HW alert. if the data or frequency are off, locationd will throw an error + if any((self.sm.frame - self.sm.recv_frame[s])*DT_CTRL > 10. for s in self.sensor_packets): + self.events.add(EventName.sensorDataInvalid) + + if not REPLAY: + # Check for mismatch between openpilot and car's PCM. + # Pre-AP Tesla manages cruiseState.enabled via software FSM (not hardware PCM), + # so treat it the same as pcmCruise for this check. + preap_sw_cruise = (self.CP.brand == "tesla" and self.CP.carFingerprint == "TESLA_MODEL_S_PREAP" + and self.CP.openpilotLongitudinalControl and not self.CP.pcmCruise) + effective_pcm_cruise = self.CP.pcmCruise or preap_sw_cruise + cruise_mismatch = CS.cruiseState.enabled and (not self.enabled or not effective_pcm_cruise) + self.cruise_mismatch_counter = self.cruise_mismatch_counter + 1 if cruise_mismatch else 0 + if self.cruise_mismatch_counter > int(6. / DT_CTRL): + self.events.add(EventName.cruiseMismatch) + + # Send a "steering required alert" if saturation count has reached the limit + if CS.steeringPressed: + self.last_steering_pressed_frame = self.sm.frame + recent_steer_pressed = (self.sm.frame - self.last_steering_pressed_frame)*DT_CTRL < 2.0 + controlstate = self.sm['controlsState'] + lac = getattr(controlstate.lateralControlState, controlstate.lateralControlState.which()) + if lac.active and not recent_steer_pressed and not self.CP.notCar: + clipped_speed = max(CS.vEgo, 0.3) + actual_lateral_accel = controlstate.curvature * (clipped_speed**2) + desired_lateral_accel = self.sm['modelV2'].action.desiredCurvature * (clipped_speed**2) + undershooting = abs(desired_lateral_accel) / abs(1e-3 + actual_lateral_accel) > 1.2 + turning = abs(desired_lateral_accel) > 1.0 + # TODO: lac.saturated includes speed and other checks, should be pulled out + if undershooting and turning and lac.saturated: + self.events.add(EventName.steerSaturated) + + # Check for FCW + stock_long_is_braking = self.enabled and not self.CP.openpilotLongitudinalControl and CS.aEgo < -1.25 + model_fcw = self.sm['modelV2'].meta.hardBrakePredicted and not CS.brakePressed and not stock_long_is_braking + planner_fcw = self.sm['longitudinalPlan'].fcw and self.enabled + if (planner_fcw or model_fcw) and not self.CP.notCar: + self.events.add(EventName.fcw) + + # GPS checks + gps_ok = self.sm.recv_frame[self.gps_location_service] > 0 and (self.sm.frame - self.sm.recv_frame[self.gps_location_service]) * DT_CTRL < 2.0 + if not gps_ok and self.sm['livePose'].inputsOK and (self.distance_traveled > 1500): + self.events.add(EventName.noGps) + if gps_ok: + self.distance_traveled = 0 + self.distance_traveled += abs(CS.vEgo) * DT_CTRL + + # TODO: fix simulator + if not SIMULATION or REPLAY: + if self.sm['modelV2'].frameDropPerc > 20: + self.events.add(EventName.modeldLagging) + + # Decrement personality on distance button press + if self.CP.openpilotLongitudinalControl: + if any(not be.pressed and be.type == ButtonType.gapAdjustCruise for be in CS.buttonEvents): + self.personality = (self.personality - 1) % 3 + self.params.put('LongitudinalPersonality', self.personality) + self.events.add(EventName.personalityChanged) + + # Stock Follow Distance 1–7 HUD, same affordance as personalityChanged. + # Read the param every frame (stalk writes it from card). First sample + # only seeds; every later 1–7 change fires the 1.5 s toast. + follow_dist = None + try: + raw = self.params.get("NAPFollowDistance", return_default=True) + if raw is not None and raw != "": + follow_dist = int(raw) + except (TypeError, ValueError): + follow_dist = None + if follow_dist is None or follow_dist <= 0: + try: + plan_d = int(self.sm["longitudinalPlan"].napFollowDistance) + except (TypeError, ValueError, KeyError): + plan_d = 0 + if plan_d > 0: + follow_dist = plan_d + try: + from openpilot.selfdrive.controls.lib.hypermile import poll_follow_distance_hud + self._follow_hud_dist, announce = poll_follow_distance_hud(self._follow_hud_dist, follow_dist) + except Exception: + announce = ( + self._follow_hud_dist is not None + and follow_dist is not None + and int(follow_dist) != int(self._follow_hud_dist) + ) + if follow_dist is not None: + self._follow_hud_dist = int(follow_dist) + try: + if self.params.get_bool("NAPFollowHudPending"): + announce = True + self.params.put_bool("NAPFollowHudPending", False) + except Exception: + pass + if announce: + self._follow_hud_until = time.monotonic() + 1.5 + if time.monotonic() < self._follow_hud_until: + follow_evt = getattr(EventName, "hypermileFollowChanged", None) or getattr(EventName, "followDistanceChanged", None) + if follow_evt is not None: + self.events.add(follow_evt) + + # NAP wiper Off↔Auto HUD. card/body sets NAPWiperHudPending on the + # collar 0→1→0 flick; hold the toast ~2.5 s (same affordance as Follow). + try: + if self.params.get_bool("NAPWiperHudPending"): + from openpilot.selfdrive.car.tesla.preap_body_controls import WIPER_HUD_DURATION_S + self._wiper_hud_until = time.monotonic() + float(WIPER_HUD_DURATION_S) + self.params.put_bool("NAPWiperHudPending", False) + except Exception: + pass + if time.monotonic() < self._wiper_hud_until: + wiper_evt = getattr(EventName, "napWiperChanged", None) + if wiper_evt is not None: + self.events.add(wiper_evt) + + # Gap lock bottom banner only while the planner is pulsing it. + # Engaged is ~2 s (GAP_LOCK_ENGAGED_BANNER_S). Unavailable / lost stay + # their short pulse. Soft clears publish no code. The under-MAX chip + # reads gapLockM for the whole latch and does not use this event. + gap_evt = getattr(EventName, "gapLock", None) + if gap_evt is not None: + gap_ev = 0 + try: + gap_ev = int(getattr(self.sm["longitudinalPlan"], "gapLockEvent", 0) or 0) + except Exception: + gap_ev = 0 + from openpilot.selfdrive.controls.lib.gap_lock import gap_lock_banner_active + if gap_lock_banner_active(gap_ev): + self.events.add(gap_evt) + + def data_sample(self): + _car_state = messaging.recv_one(self.car_state_sock) + CS = _car_state.carState if _car_state else self.CS_prev + + self.sm.update(0) + + if not self.initialized: + all_valid = CS.canValid and self.sm.all_checks() + timed_out = self.sm.frame * DT_CTRL > 6. + if all_valid or timed_out or (SIMULATION and not REPLAY): + available_streams = VisionIpcClient.available_streams("camerad", block=False) + if VisionStreamType.VISION_STREAM_ROAD not in available_streams: + self.sm.ignore_alive.append('roadCameraState') + self.sm.ignore_valid.append('roadCameraState') + if VisionStreamType.VISION_STREAM_WIDE_ROAD not in available_streams: + self.sm.ignore_alive.append('wideRoadCameraState') + self.sm.ignore_valid.append('wideRoadCameraState') + + if REPLAY and any(ps.controlsAllowed for ps in self.sm['pandaStates']): + self.state_machine.state = State.enabled + + self.initialized = True + cloudlog.event( + "selfdrived.initialized", + dt=self.sm.frame*DT_CTRL, + timeout=timed_out, + canValid=CS.canValid, + invalid=[s for s, valid in self.sm.valid.items() if not valid], + not_alive=[s for s, alive in self.sm.alive.items() if not alive], + not_freq_ok=[s for s, freq_ok in self.sm.freq_ok.items() if not freq_ok], + error=True, + ) + + # When the panda and selfdrived do not agree on controls_allowed + # we want to disengage openpilot. However the status from the panda goes through + # another socket other than the CAN messages and one can arrive earlier than the other. + # Therefore we allow a mismatch for two samples, then we trigger the disengagement. + if not self.enabled: + self.mismatch_counter = 0 + + # All pandas not in silent mode must have controlsAllowed when openpilot is enabled. + # tesla_preap also drops controls_allowed on hands-on >= 2. A blinker-latched + # driver turn already released lat; that disagreement is not a cancel. + if self.enabled and any(not ps.controlsAllowed for ps in self.sm['pandaStates'] + if ps.safetyModel not in IGNORED_SAFETY_MODES): + if preap_blinker_pause_hides_controls_mismatch( + brand=self.CP.brand, fingerprint=self.CP.carFingerprint, + blocks_steer_disengage=self.car_events.blinker_lat_hold.blocks_steer_disengage): + self.mismatch_counter = 0 + else: + self.mismatch_counter += 1 + + return CS + + def update_alerts(self, CS): + clear_event_types = set() + if ET.WARNING not in self.state_machine.current_alert_types: + clear_event_types.add(ET.WARNING) + if self.enabled: + clear_event_types.add(ET.NO_ENTRY) + + pers = LONGITUDINAL_PERSONALITY_MAP[self.personality] + alerts = self.events.create_alerts(self.state_machine.current_alert_types, [self.CP, CS, self.sm, self.is_metric, + self.state_machine.soft_disable_timer, pers]) + self.AM.add_many(self.sm.frame, alerts) + self.AM.process_alerts(self.sm.frame, clear_event_types) + + def publish_selfdriveState(self, CS): + # selfdriveState + ss_msg = messaging.new_message('selfdriveState') + ss_msg.valid = True + ss = ss_msg.selfdriveState + ss.enabled = self.enabled + ss.active = self.active + ss.state = self.state_machine.state + ss.engageable = not self.events.contains(ET.NO_ENTRY) + ss.experimentalMode = self.experimental_mode + ss.personality = self.personality + + ss.alertText1 = self.AM.current_alert.alert_text_1 + ss.alertText2 = self.AM.current_alert.alert_text_2 + ss.alertSize = self.AM.current_alert.alert_size + ss.alertStatus = self.AM.current_alert.alert_status + ss.alertType = self.AM.current_alert.alert_type + ss.alertSound = self.AM.current_alert.audible_alert + ss.alertHudVisual = self.AM.current_alert.visual_alert + + self.pm.send('selfdriveState', ss_msg) + + # onroadEvents - logged every second or on change + if (self.sm.frame % int(1. / DT_CTRL) == 0) or (self.events.names != self.events_prev): + ce_send = messaging.new_message('onroadEvents', len(self.events)) + ce_send.valid = True + ce_send.onroadEvents = self.events.to_msg() + self.pm.send('onroadEvents', ce_send) + self.events_prev = self.events.names.copy() + + def step(self): + CS = self.data_sample() + self.update_events(CS) + if not self.CP.passive and self.initialized: + self.enabled, self.active = self.state_machine.update(self.events) + self.update_alerts(CS) + + self.publish_selfdriveState(CS) + + self.CS_prev = CS + + def params_thread(self, evt): + while not evt.is_set(): + self.is_metric = self.params.get_bool("IsMetric") + self.is_ldw_enabled = self.params.get_bool("IsLdwEnabled") + self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator") + self.one_pedal_long = self.params.get_bool("NAPOnePedalLong") + try: + self.obstacle_chime = bool(self.params.get_bool("NAPObstacleChime")) + except Exception: + self.obstacle_chime = True + self.experimental_mode = self.params.get_bool("ExperimentalMode") and self.CP.openpilotLongitudinalControl + self.personality = self.params.get("LongitudinalPersonality", return_default=True) + time.sleep(0.1) + + def run(self): + e = threading.Event() + t = threading.Thread(target=self.params_thread, args=(e, )) + try: + t.start() + while True: + self.step() + self.rk.monitor_time() + finally: + e.set() + t.join() + + +def main(): + config_realtime_process(4, Priority.CTRL_HIGH) + s = SelfdriveD() + s.run() + +if __name__ == "__main__": + main() diff --git a/selfdrive/selfdrived/state.py b/selfdrive/selfdrived/state.py new file mode 100644 index 00000000000000..073ddb56eb9dc6 --- /dev/null +++ b/selfdrive/selfdrived/state.py @@ -0,0 +1,98 @@ +from cereal import log +from openpilot.selfdrive.selfdrived.events import Events, ET +from openpilot.common.realtime import DT_CTRL + +State = log.SelfdriveState.OpenpilotState + +SOFT_DISABLE_TIME = 3 # seconds +ACTIVE_STATES = (State.enabled, State.softDisabling, State.overriding) +ENABLED_STATES = (State.preEnabled, *ACTIVE_STATES) + +class StateMachine: + def __init__(self): + self.current_alert_types = [ET.PERMANENT] + self.state = State.disabled + self.soft_disable_timer = 0 + + def update(self, events: Events): + # decrement the soft disable timer at every step, as it's reset on + # entrance in SOFT_DISABLING state + self.soft_disable_timer = max(0, self.soft_disable_timer - 1) + + self.current_alert_types = [ET.PERMANENT] + + # ENABLED, SOFT DISABLING, PRE ENABLING, OVERRIDING + if self.state != State.disabled: + # user and immediate disable always have priority in a non-disabled state + if events.contains(ET.USER_DISABLE): + self.state = State.disabled + self.current_alert_types.append(ET.USER_DISABLE) + + elif events.contains(ET.IMMEDIATE_DISABLE): + self.state = State.disabled + self.current_alert_types.append(ET.IMMEDIATE_DISABLE) + + else: + # ENABLED + if self.state == State.enabled: + if events.contains(ET.SOFT_DISABLE): + self.state = State.softDisabling + self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + self.current_alert_types.append(ET.SOFT_DISABLE) + + elif events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL): + self.state = State.overriding + self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] + + # SOFT DISABLING + elif self.state == State.softDisabling: + if not events.contains(ET.SOFT_DISABLE): + # no more soft disabling condition, so go back to ENABLED + self.state = State.enabled + + elif self.soft_disable_timer > 0: + self.current_alert_types.append(ET.SOFT_DISABLE) + + elif self.soft_disable_timer <= 0: + self.state = State.disabled + + # PRE ENABLING + elif self.state == State.preEnabled: + if not events.contains(ET.PRE_ENABLE): + self.state = State.enabled + else: + self.current_alert_types.append(ET.PRE_ENABLE) + + # OVERRIDING + elif self.state == State.overriding: + if events.contains(ET.SOFT_DISABLE): + self.state = State.softDisabling + self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + self.current_alert_types.append(ET.SOFT_DISABLE) + elif not (events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL)): + self.state = State.enabled + else: + self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] + + # DISABLED + elif self.state == State.disabled: + if events.contains(ET.ENABLE): + if events.contains(ET.NO_ENTRY): + self.current_alert_types.append(ET.NO_ENTRY) + + else: + if events.contains(ET.PRE_ENABLE): + self.state = State.preEnabled + elif events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL): + self.state = State.overriding + else: + self.state = State.enabled + self.current_alert_types.append(ET.ENABLE) + + # Check if openpilot is engaged and actuators are enabled + enabled = self.state in ENABLED_STATES + active = self.state in ACTIVE_STATES + if active: + self.current_alert_types.append(ET.WARNING) + return enabled, active + diff --git a/selfdrive/selfdrived/tests/test_alertmanager.py b/selfdrive/selfdrived/tests/test_alertmanager.py new file mode 100644 index 00000000000000..a51100d2b52c56 --- /dev/null +++ b/selfdrive/selfdrived/tests/test_alertmanager.py @@ -0,0 +1,60 @@ +import copy +import random + +from openpilot.selfdrive.selfdrived.events import Alert, EmptyAlert, EVENTS +from openpilot.selfdrive.selfdrived.alertmanager import AlertManager + + +class TestAlertManager: + + def test_duration(self): + """ + Enforce that an alert lasts for max(alert duration, duration the alert is added) + """ + for duration in range(1, 100): + alert = None + while not isinstance(alert, Alert): + event = random.choice([e for e in EVENTS.values() if len(e)]) + alert = random.choice(list(event.values())) + + alert = copy.copy(alert) + alert.duration = duration + + # check two cases: + # - alert is added to AM for <= the alert's duration + # - alert is added to AM for > alert's duration + for greater in (True, False): + if greater: + add_duration = duration + random.randint(1, 10) + else: + add_duration = random.randint(1, duration) + show_duration = max(duration, add_duration) + + AM = AlertManager() + for frame in range(duration+10): + if frame < add_duration: + AM.add_many(frame, [alert, ]) + AM.process_alerts(frame, set()) + + shown = AM.current_alert != EmptyAlert + should_show = frame <= show_duration + assert shown == should_show, f"{frame=} {add_duration=} {duration=}" + + # check one case: + # - if alert is re-added to AM before it ends the duration is extended + if duration > 1: + AM = AlertManager() + show_duration = duration * 2 + for frame in range(duration * 2 + 10): + if frame == 0: + AM.add_many(frame, [alert, ]) + + if frame == duration: + # add alert one frame before it ends + assert AM.current_alert == alert + AM.add_many(frame, [alert, ]) + AM.process_alerts(frame, set()) + + shown = AM.current_alert != EmptyAlert + should_show = frame <= show_duration + assert shown == should_show, f"{frame=} {duration=}" diff --git a/selfdrive/selfdrived/tests/test_alerts.py b/selfdrive/selfdrived/tests/test_alerts.py new file mode 100644 index 00000000000000..41d36187db5e35 --- /dev/null +++ b/selfdrive/selfdrived/tests/test_alerts.py @@ -0,0 +1,278 @@ +import copy +import json +import os +import random +from PIL import Image, ImageDraw, ImageFont + +from cereal import log, car +from cereal.messaging import SubMaster +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.selfdrived.events import Alert, EVENTS, ET, AudibleAlert, hypermile_follow_changed_alert, nap_wiper_changed_alert +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert +from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS + +AlertSize = log.SelfdriveState.AlertSize + +OFFROAD_ALERTS_PATH = os.path.join(BASEDIR, "selfdrive/selfdrived/alerts_offroad.json") + +# TODO: add callback alerts +ALERTS = [] +for event_types in EVENTS.values(): + for alert in event_types.values(): + ALERTS.append(alert) + + +class TestAlerts: + + @classmethod + def setup_class(cls): + with open(OFFROAD_ALERTS_PATH) as f: + cls.offroad_alerts = json.loads(f.read()) + + # Create fake objects for callback + cls.CS = car.CarState.new_message() + cls.CP = car.CarParams.new_message() + cfg = [c for c in CONFIGS if c.proc_name == 'selfdrived'][0] + cls.sm = SubMaster(cfg.pubs) + + def test_events_defined(self): + # Ensure all events in capnp schema are defined in events.py + events = log.OnroadEvent.EventName.schema.enumerants + + for name, e in events.items(): + if not name.endswith("DEPRECATED"): + fail_msg = f"{name} @{e} not in EVENTS" + assert e in EVENTS.keys(), fail_msg + + # ensure alert text doesn't exceed allowed width + def test_alert_text_length(self): + font_path = os.path.join(BASEDIR, "selfdrive/assets/fonts") + regular_font_path = os.path.join(font_path, "Inter-SemiBold.ttf") + bold_font_path = os.path.join(font_path, "Inter-Bold.ttf") + semibold_font_path = os.path.join(font_path, "Inter-SemiBold.ttf") + + max_text_width = 2160 - 300 # full screen width is usable, minus sidebar + draw = ImageDraw.Draw(Image.new('RGB', (0, 0))) + + fonts = { + AlertSize.small: [ImageFont.truetype(semibold_font_path, 74)], + AlertSize.mid: [ImageFont.truetype(bold_font_path, 88), + ImageFont.truetype(regular_font_path, 66)], + } + + for alert in ALERTS: + if not isinstance(alert, Alert): + alert = alert(self.CP, self.CS, self.sm, False, 100, log.LongitudinalPersonality.standard) + + # for full size alerts, both text fields wrap the text, + # so it's unlikely that they would go past the max width + if alert.alert_size in (AlertSize.none, AlertSize.full): + continue + + for i, txt in enumerate([alert.alert_text_1, alert.alert_text_2]): + if i >= len(fonts[alert.alert_size]): + break + + font = fonts[alert.alert_size][i] + left, _, right, _ = draw.textbbox((0, 0), txt, font) + width = right - left + msg = f"type: {alert.alert_type} msg: {txt}" + assert width <= max_text_width, msg + + def test_alert_sanity_check(self): + for event_types in EVENTS.values(): + for event_type, a in event_types.items(): + # TODO: add callback alerts + if not isinstance(a, Alert): + continue + + if a.alert_size == AlertSize.none: + assert len(a.alert_text_1) == 0 + assert len(a.alert_text_2) == 0 + elif a.alert_size == AlertSize.small: + assert len(a.alert_text_1) > 0 + assert len(a.alert_text_2) == 0 + elif a.alert_size == AlertSize.mid: + assert len(a.alert_text_1) > 0 + assert len(a.alert_text_2) > 0 + else: + assert len(a.alert_text_1) > 0 + + assert a.duration >= 0. + + if event_type not in (ET.WARNING, ET.PERMANENT, ET.PRE_ENABLE): + assert a.creation_delay == 0. + + def test_preap_regen_alert_tells_driver_to_brake(self): + alert = EVENTS[log.OnroadEvent.EventName.pedalMaxRegen][ET.WARNING] + + assert alert.alert_text_1 == "Regen Limit Reached" + assert alert.alert_text_2 == "Press Brake to Slow Down" + assert alert.alert_size == AlertSize.mid + assert alert.visual_alert == car.CarControl.HUDControl.VisualAlert.brakePressed + assert alert.audible_alert == AudibleAlert.promptRepeat + assert alert.duration == int(0.2 / DT_CTRL) + + def test_preap_pedal_cruise_alerts_fire_while_disabled(self): + # ET.WARNING is omitted on the USER_DISABLE frame, so these must be + # permanent to play the disengage prompt on stalk cancel / full + # teardown. Brake long pause must not add this event. + for name, text, sound in ( + (log.OnroadEvent.EventName.pedalCruiseEnabled, "Pedal Cruise Engaged", AudibleAlert.engage), + (log.OnroadEvent.EventName.pedalCruiseDisabled, "Pedal Cruise Disengaged", AudibleAlert.disengage), + ): + event_types = EVENTS[name] + assert set(event_types) == {ET.PERMANENT} + alert = event_types[ET.PERMANENT] + assert alert.alert_text_1 == text + assert alert.audible_alert == sound + assert alert.duration == int(0.8 / DT_CTRL) + + def test_preap_pcm_alerts_show_steering_prompt(self): + from openpilot.selfdrive.selfdrived.events import pcm_disable_alert, pcm_enable_alert + + cp = car.CarParams.new_message() + cp.brand = "tesla" + cp.carFingerprint = "TESLA_MODEL_S_PREAP" + args = (cp, self.CS, self.sm, False, 100, log.LongitudinalPersonality.standard) + + enable = pcm_enable_alert(*args) + assert enable.alert_text_1 == "Steering Engaged" + assert enable.audible_alert == AudibleAlert.engage + + disable = pcm_disable_alert(*args) + assert disable.alert_text_1 == "Steering Disengaged" + assert disable.audible_alert == AudibleAlert.disengage + + stock = car.CarParams.new_message() + stock_enable = pcm_enable_alert(stock, *args[1:]) + assert stock_enable.alert_text_1 == "" + assert stock_enable.audible_alert == AudibleAlert.engage + + def test_preap_reverse_disable_is_quiet(self): + from openpilot.selfdrive.selfdrived.events import reverse_gear_disable_alert + + cp = car.CarParams.new_message() + cp.brand = "tesla" + cp.carFingerprint = "TESLA_MODEL_S_PREAP" + args = (cp, self.CS, self.sm, False, 100, log.LongitudinalPersonality.standard) + alert = reverse_gear_disable_alert(*args) + assert alert.alert_text_1 == "" + assert alert.audible_alert == AudibleAlert.none + assert alert.alert_size == AlertSize.none + + stock = reverse_gear_disable_alert(car.CarParams.new_message(), *args[1:]) + assert stock.alert_text_1 == "TAKE CONTROL IMMEDIATELY" + assert stock.audible_alert == AudibleAlert.warningImmediate + + def test_gap_lock_engaged_alert_is_obvious_and_clears(self): + from openpilot.selfdrive.controls.lib.gap_lock import HUD_ENGAGED, HUD_LOST, HUD_UNAVAILABLE + from openpilot.selfdrive.selfdrived.events import Priority, gap_lock_alert + + plan = self.sm["longitudinalPlan"] + plan.gapLockM = 32.4 + plan.gapLockEvent = HUD_ENGAGED + args = (self.CP, self.CS, self.sm, False, 100, log.LongitudinalPersonality.standard) + alert = gap_lock_alert(*args) + assert alert.alert_text_1 == "Gap lock engaged 32 m" + assert alert.alert_text_2 == "" + assert alert.alert_size == AlertSize.small + assert alert.priority == Priority.LOW + # Short refresh. The 2 s window is the planner pulse, so the line + # drops when that pulse ends instead of sticking for the whole lock. + assert alert.duration == int(0.2 / DT_CTRL) + + plan.gapLockM = 0 + plan.gapLockEvent = 0 + cleared = gap_lock_alert(*args) + assert cleared.alert_text_1 == "Gap lock off" + assert cleared.duration == int(0.2 / DT_CTRL) + + plan.gapLockEvent = HUD_LOST + lost = gap_lock_alert(*args) + assert lost.alert_text_1 == "Gap lock off" + assert lost.duration == int(0.2 / DT_CTRL) + + plan.gapLockEvent = HUD_UNAVAILABLE + unavailable = gap_lock_alert(*args) + assert unavailable.alert_text_1 == "Gap lock unavailable" + assert unavailable.duration == int(0.2 / DT_CTRL) + + def test_follow_distance_changed_alert_matches_mannerisms(self): + follow_evt = getattr(log.OnroadEvent.EventName, "hypermileFollowChanged", None) or getattr( + log.OnroadEvent.EventName, "followDistanceChanged", None, + ) + assert follow_evt is not None + event_types = EVENTS[follow_evt] + assert ET.WARNING in event_types + assert ET.PERMANENT in event_types + alert = hypermile_follow_changed_alert( + self.CP, self.CS, self.sm, False, 100, log.LongitudinalPersonality.standard, + ) + assert alert.alert_text_1.startswith("Follow Distance:") + assert alert.duration == int(1.5 / DT_CTRL) + + def test_nap_wiper_changed_alert_is_brief_nonblocking(self): + wiper_evt = getattr(log.OnroadEvent.EventName, "napWiperChanged", None) + assert wiper_evt is not None + event_types = EVENTS[wiper_evt] + assert ET.WARNING in event_types + assert ET.PERMANENT in event_types + assert ET.SOFT_DISABLE not in event_types + assert ET.IMMEDIATE_DISABLE not in event_types + assert ET.NO_ENTRY not in event_types + alert = nap_wiper_changed_alert( + self.CP, self.CS, self.sm, False, 100, log.LongitudinalPersonality.standard, + ) + assert alert.alert_text_1 in ("Wipers Off", "Wipers Auto") + assert alert.alert_text_2 == "" + assert alert.duration == int(2.5 / DT_CTRL) + + def test_preap_pedal_unavailable_alert_is_visible_without_disabling_lateral(self): + event_types = EVENTS[log.OnroadEvent.EventName.pedalUnavailable] + alert = event_types[ET.WARNING] + + assert set(event_types) == {ET.WARNING} + assert alert.alert_text_1 == "Pedal Control Unavailable" + assert alert.alert_text_2 == "Speed Control Disabled" + assert alert.alert_size == AlertSize.mid + assert alert.duration == int(3.0 / DT_CTRL) + + def test_radar_prefer_fallback_alert_is_visible_without_disengaging(self): + event_types = EVENTS[log.OnroadEvent.EventName.radarPreferFallback] + assert ET.SOFT_DISABLE not in event_types + assert ET.IMMEDIATE_DISABLE not in event_types + assert ET.NO_ENTRY not in event_types + alert = event_types[ET.WARNING] + if not isinstance(alert, Alert): # text follows radarPreferReason (sensorDirty variant) + alert = alert(self.CP, self.CS, self.sm, False, 100, log.LongitudinalPersonality.standard) + assert alert.alert_text_1 == "Radar Unreliable" + assert alert.alert_text_2 == "Using camera lead" + assert alert.alert_size == AlertSize.mid + + def test_offroad_alerts(self): + params = Params() + for a in self.offroad_alerts: + # set the alert + alert = copy.copy(self.offroad_alerts[a]) + set_offroad_alert(a, True) + alert['extra'] = '' + assert alert == params.get(a) + + # then delete it + set_offroad_alert(a, False) + assert params.get(a) is None + + def test_offroad_alerts_extra_text(self): + params = Params() + for i in range(50): + # set the alert + a = random.choice(list(self.offroad_alerts)) + alert = self.offroad_alerts[a] + set_offroad_alert(a, True, extra_text="a"*i) + + written_alert = params.get(a) + assert "a"*i == written_alert['extra'] + assert alert["text"] == written_alert['text'] diff --git a/selfdrive/selfdrived/tests/test_excessive_actuation.py b/selfdrive/selfdrived/tests/test_excessive_actuation.py new file mode 100644 index 00000000000000..b915c698a1beb9 --- /dev/null +++ b/selfdrive/selfdrived/tests/test_excessive_actuation.py @@ -0,0 +1,130 @@ +from types import SimpleNamespace + +from openpilot.selfdrive.selfdrived.helpers import ( + EXCESSIVE_LAT_ACCEL, + EXCESSIVE_LONG_ACCEL_NEG, + EXCESSIVE_LONG_ACCEL_POS, + MIN_EXCESSIVE_ACTUATION_COUNT, + MIN_LATERAL_ENGAGE_BUFFER, + PREAP_EXCESSIVE_LAT_ACCEL, + PREAP_EXCESSIVE_LONG_ACCEL_NEG, + PREAP_EXCESSIVE_LONG_ACCEL_POS, + PREAP_FINGERPRINT, + ExcessiveActuationCheck, + ExcessiveActuationType, + excessive_actuation_limits, +) + +# Faster-but-legal ramp: ~0.71 g. Stock 2× ISO (6.0) false-trips this; +# Pre-AP 3× ISO (9.0) must not. +FAST_NORMAL_CORNER_MPS2 = 7.0 +# Panic swerve / emergency: ~1.12 g. Both stock and Pre-AP still trip. +EXTREME_SWERVE_MPS2 = 11.0 +# Firm but not panic long decel: between stock −7.0 and Pre-AP −10.5. +FAST_NORMAL_DECEL_MPS2 = -8.0 +EXTREME_DECEL_MPS2 = -12.0 + +V_EGO = 25.0 # m/s, ~56 mph + + +def _pose(*, ax=0.0, yaw_rate=0.0): + return SimpleNamespace( + acceleration=SimpleNamespace(x=ax), + angular_velocity=SimpleNamespace(yaw=yaw_rate), + ) + + +def _sm(*, lat_active=True, long_active=False, roll=0.0): + return { + "carControl": SimpleNamespace(latActive=lat_active, longActive=long_active), + "liveParameters": SimpleNamespace(roll=roll), + } + + +def _cs(*, v_ego=V_EGO, a_ego=0.0, steering_pressed=False): + return SimpleNamespace(vEgo=v_ego, aEgo=a_ego, steeringPressed=steering_pressed) + + +def _run(check, *, frames, lat_mps2=0.0, ax=0.0, lat_active=True, long_active=False, + steering_pressed=False): + yaw = 0.0 if V_EGO == 0 else lat_mps2 / V_EGO + sm = _sm(lat_active=lat_active, long_active=long_active) + cs = _cs(a_ego=ax, steering_pressed=steering_pressed) + pose = _pose(ax=ax, yaw_rate=yaw) + last = None + for _ in range(frames): + last = check.update(sm, cs, pose) + return last + + +def _lat_frames_to_trip(): + return MIN_LATERAL_ENGAGE_BUFFER + MIN_EXCESSIVE_ACTUATION_COUNT + 2 + + +def _long_frames_to_trip(): + return MIN_EXCESSIVE_ACTUATION_COUNT + 2 + + +def test_threshold_constants_document_old_vs_new(): + assert EXCESSIVE_LAT_ACCEL == 6.0 + assert PREAP_EXCESSIVE_LAT_ACCEL == 9.0 + assert EXCESSIVE_LONG_ACCEL_POS == 4.0 + assert PREAP_EXCESSIVE_LONG_ACCEL_POS == 6.0 + assert EXCESSIVE_LONG_ACCEL_NEG == -7.0 + assert PREAP_EXCESSIVE_LONG_ACCEL_NEG == -10.5 + stock = excessive_actuation_limits("comma") + preap = excessive_actuation_limits(PREAP_FINGERPRINT) + assert stock == (6.0, 4.0, -7.0) + assert preap == (9.0, 6.0, -10.5) + # Pre-AP is a fair amount looser (50% on the ISO multiple: 2× → 3×). + assert PREAP_EXCESSIVE_LAT_ACCEL / EXCESSIVE_LAT_ACCEL == 1.5 + assert FAST_NORMAL_CORNER_MPS2 > EXCESSIVE_LAT_ACCEL + assert FAST_NORMAL_CORNER_MPS2 < PREAP_EXCESSIVE_LAT_ACCEL + assert EXTREME_SWERVE_MPS2 > PREAP_EXCESSIVE_LAT_ACCEL + assert FAST_NORMAL_DECEL_MPS2 < EXCESSIVE_LONG_ACCEL_NEG + assert FAST_NORMAL_DECEL_MPS2 > PREAP_EXCESSIVE_LONG_ACCEL_NEG + assert EXTREME_DECEL_MPS2 < PREAP_EXCESSIVE_LONG_ACCEL_NEG + + +def test_preap_fast_normal_corner_does_not_trip(): + check = ExcessiveActuationCheck(fingerprint=PREAP_FINGERPRINT) + assert _run(check, frames=_lat_frames_to_trip(), lat_mps2=FAST_NORMAL_CORNER_MPS2) is None + + +def test_stock_fast_normal_corner_still_trips(): + check = ExcessiveActuationCheck(fingerprint="honda") + assert _run(check, frames=_lat_frames_to_trip(), + lat_mps2=FAST_NORMAL_CORNER_MPS2) == ExcessiveActuationType.LATERAL + + +def test_preap_extreme_swerve_still_trips(): + check = ExcessiveActuationCheck(fingerprint=PREAP_FINGERPRINT) + assert _run(check, frames=_lat_frames_to_trip(), + lat_mps2=EXTREME_SWERVE_MPS2) == ExcessiveActuationType.LATERAL + + +def test_preap_fast_normal_decel_does_not_trip(): + check = ExcessiveActuationCheck(fingerprint=PREAP_FINGERPRINT) + assert _run(check, frames=_long_frames_to_trip(), ax=FAST_NORMAL_DECEL_MPS2, + lat_active=False, long_active=True) is None + + +def test_stock_fast_normal_decel_still_trips(): + check = ExcessiveActuationCheck() + assert _run(check, frames=_long_frames_to_trip(), ax=FAST_NORMAL_DECEL_MPS2, + lat_active=False, long_active=True) == ExcessiveActuationType.LONGITUDINAL + + +def test_preap_extreme_decel_still_trips(): + check = ExcessiveActuationCheck(fingerprint=PREAP_FINGERPRINT) + assert _run(check, frames=_long_frames_to_trip(), ax=EXTREME_DECEL_MPS2, + lat_active=False, long_active=True) == ExcessiveActuationType.LONGITUDINAL + + +def test_preap_path_is_not_disabled(): + """Raising the limit is not the same as turning the check off.""" + check = ExcessiveActuationCheck(fingerprint=PREAP_FINGERPRINT) + assert check._lat_limit < 20.0 + assert check._long_neg > -20.0 + assert _run(check, frames=_lat_frames_to_trip(), + lat_mps2=EXTREME_SWERVE_MPS2) is not None diff --git a/selfdrive/selfdrived/tests/test_hardwared_loop_timing.py b/selfdrive/selfdrived/tests/test_hardwared_loop_timing.py new file mode 100644 index 00000000000000..455d1aa18e414f --- /dev/null +++ b/selfdrive/selfdrived/tests/test_hardwared_loop_timing.py @@ -0,0 +1,60 @@ +"""A hardware_thread iteration over 1 s names the blocking step.""" +import importlib.util +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] + +# Load the module by path. Importing openpilot.system.hardware pulls in cereal, +# which these timing checks do not need. +_spec = importlib.util.spec_from_file_location( + "hardwared_loop_timing", ROOT / "system" / "hardware" / "loop_timing.py") +assert _spec is not None and _spec.loader is not None +_loop_timing = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_loop_timing) +HardwareLoopTimer = _loop_timing.HardwareLoopTimer +slow_loop_fields = _loop_timing.slow_loop_fields + + +class _Clock: + def __init__(self): + self.t = 0.0 + + def __call__(self): + return self.t + + +def test_loop_at_one_second_is_not_logged(): + clock = _Clock() + timer = HardwareLoopTimer(clock) + clock.t = 1.0 + timer.mark("statvfs") + assert slow_loop_fields(timer) is None + + +def test_slow_loop_names_step_durations(): + clock = _Clock() + timer = HardwareLoopTimer(clock) + clock.t = 0.05 + timer.mark("sm_update") + clock.t = 0.06 + timer.mark("force_offroad_params") + clock.t = 5.86 + timer.mark("statvfs") + fields = slow_loop_fields(timer) + assert fields is not None + assert fields["sm_update_ms"] == 50.0 + assert fields["force_offroad_params_ms"] == 10.0 + assert fields["statvfs_ms"] == 5800.0 + assert fields["total_ms"] == 5860.0 + + +def test_hardwared_times_steps_without_new_subscribers(): + src = (ROOT / "system" / "hardware" / "hardwared.py").read_text() + assert 'PubMaster([\'deviceState\'])' in src + assert 'SubMaster(["peripheralState", "gpsLocationExternal", "selfdriveState", "pandaStates"], poll="pandaStates")' in src + assert "carState" not in src + assert 'cloudlog.warning({"event": "hardwared slow loop"' in src + assert 'cloudlog.event("hardwared slow loop", error=True' in src + assert 'timer.mark("statvfs")' in src + assert 'timer.mark("sm_update")' in src + assert 'timer.mark("uptime_params")' in src diff --git a/selfdrive/selfdrived/tests/test_housekeeping_comm_issue.py b/selfdrive/selfdrived/tests/test_housekeeping_comm_issue.py new file mode 100644 index 00000000000000..eab6e202c11f01 --- /dev/null +++ b/selfdrive/selfdrived/tests/test_housekeeping_comm_issue.py @@ -0,0 +1,177 @@ +"""deviceState / managerState stalls must not raise commIssue before 10 s. + +Driving services stay on SubMaster's strict alive window (10 / frequency). +""" +import re +from pathlib import Path + +from openpilot.selfdrive.selfdrived.housekeeping_comm import ( + HOUSEKEEPING_SERVICES, + classify_comm_issue, + device_health_events, + device_state_seen, + housekeeping_silent_services, + message_silence_s, + submaster_ignore_services, +) + +ROOT = Path(__file__).resolve().parents[3] +NOW = 1_000_000.0 + +# Services selfdrived still strict-checks. carState is a separate socket and +# is not in this SubMaster; its readers are unchanged. +DRIVING_SERVICES = ( + "pandaStates", + "modelV2", + "controlsState", + "radarState", + "carControl", + "carOutput", + "longitudinalPlan", + "livePose", + "liveCalibration", +) + + +def _freq(name: str) -> float: + text = (ROOT / "cereal" / "services.py").read_text() + match = re.search(rf'"{name}":\s*\((?:True|False),\s*([0-9.]+)', text) + assert match is not None, name + return float(match.group(1)) + + +def _strict_alive(age_s: float, frequency: float) -> bool: + """SubMaster.alive: age < 10/frequency. Locked against the source below.""" + return age_s < (10.0 / frequency) + + +def _kind(device_age_s: float, *, manager_age_s: float = 0.5, all_alive: bool = True, + all_freq_ok: bool = True, all_valid: bool = True, log_mono_only: bool = False) -> str | None: + if log_mono_only: + recv = {"deviceState": 0.0, "managerState": NOW - manager_age_s} + else: + recv = {"deviceState": NOW - device_age_s, "managerState": NOW - manager_age_s} + mono = { + "deviceState": int((NOW - device_age_s) * 1e9), + "managerState": int((NOW - manager_age_s) * 1e9), + } + silent = housekeeping_silent_services(recv, mono, NOW, frame=100000, dt=0.01) + return classify_comm_issue( + all_alive=all_alive, + all_freq_ok=all_freq_ok, + all_valid=all_valid, + housekeeping_silent=silent, + ) + + +def test_six_second_device_state_gap_does_not_raise_comm_issue(): + # Route 176 segment 4 stalled for 5.8 s. A 6 s gap is the same class. + assert _kind(6.0) is None + assert message_silence_s(NOW - 6.0, int((NOW - 6.0) * 1e9), NOW) == 6.0 + + +def test_device_state_gap_over_ten_seconds_raises_comm_issue(): + assert _kind(10.0) is None + assert _kind(10.1) == "commIssue" + assert _kind(11.0) == "commIssue" + + +def test_device_state_gap_over_ten_seconds_uses_log_mono_time(): + assert _kind(6.0, log_mono_only=True) is None + assert _kind(10.1, log_mono_only=True) == "commIssue" + + +def test_fresh_recv_time_wins_over_stale_log_mono_time(): + # A message that just arrived is not silent, even if its publish timestamp is old. + age = message_silence_s(NOW - 1.0, int((NOW - 30.0) * 1e9), NOW) + assert age == 1.0 + silent = housekeeping_silent_services( + {"deviceState": NOW - 1.0, "managerState": NOW}, + {"deviceState": int((NOW - 30.0) * 1e9), "managerState": int(NOW * 1e9)}, + NOW, + ) + assert silent == [] + + +def test_manager_state_gap_over_ten_seconds_raises_comm_issue(): + assert _kind(0.5, manager_age_s=6.0) is None + assert _kind(0.5, manager_age_s=10.1) == "commIssue" + + +def test_replay_does_not_require_manager_state(): + silent = housekeeping_silent_services( + {"deviceState": NOW, "managerState": 0.0}, + {"deviceState": int(NOW * 1e9), "managerState": 0}, + NOW, + frame=2000, + dt=0.01, + skip=("managerState",), + ) + assert silent == [] + + +def test_other_services_timeouts_unchanged(): + messaging = (ROOT / "cereal" / "messaging" / "__init__.py").read_text() + assert "(cur_time - self.recv_time[s]) < (10. / SERVICE_LIST[s].frequency)" in messaging + + # Old 2 Hz window is still 5 s. A 6 s gap fails it, which is why housekeeping + # is excluded from that check instead of changing the formula. + assert _freq("deviceState") == 2.0 + assert _freq("managerState") == 2.0 + assert not _strict_alive(6.0, _freq("deviceState")) + assert _strict_alive(4.9, _freq("deviceState")) + + assert _freq("carState") == 100.0 + assert _freq("controlsState") == 100.0 + assert _strict_alive(0.09, _freq("carState")) + assert not _strict_alive(0.1, _freq("carState")) + assert _freq("pandaStates") == 10.0 + assert _strict_alive(0.99, _freq("pandaStates")) + assert not _strict_alive(1.0, _freq("pandaStates")) + assert _freq("modelV2") == 20.0 + assert _freq("radarState") == 20.0 + assert _strict_alive(0.49, _freq("radarState")) + assert not _strict_alive(0.5, _freq("radarState")) + + ignore = submaster_ignore_services( + ["accelerometer", "gyroscope"], ["gpsLocationExternal"], simulation=False, replay=False) + assert set(HOUSEKEEPING_SERVICES) <= set(ignore) + for name in DRIVING_SERVICES: + assert name not in ignore + # Replay fixtures and the obstacle-chime wiring both grep these literals. + selfd = (ROOT / "selfdrive" / "selfdrived" / "selfdrived.py").read_text() + assert "['alertDebug', 'lateralManeuverPlan', 'pathObstacleNAP', 'pathObstacleVisionNAP']" in selfd + assert "ignore += ['roadCameraState', 'wideRoadCameraState', 'driverCameraState', 'managerState']" in selfd + assert "ignore += list(HOUSEKEEPING_SERVICES)" in selfd + + # Strict failure of any remaining service still raises, at that service's own window. + assert _kind(0.4, all_alive=False) == "commIssue" + assert _kind(0.4, all_freq_ok=False) == "commIssueAvgFreq" + assert _kind(0.4, all_valid=False) == "commIssue" + # A housekeeping gap must not be reported as the average-frequency alert. + assert _kind(6.0) is None + assert _kind(10.1) == "commIssue" + + +def test_last_device_state_values_survive_a_short_stall(): + # Last sample before the stall: ~10% free, thermal ok, memory fine. + assert device_state_seen(NOW - 6.0, int((NOW - 6.0) * 1e9)) + events = device_health_events(0, 10.4, 65, simulation=False, overheated=1) + assert events == [] + # Zeros are not a real sample. Callers only pass the held message once seen. + assert not device_state_seen(0.0, 0) + assert "outOfSpace" in device_health_events(0, 0.0, 0, simulation=False, overheated=1) + # An actual overheat / low memory in the last sample is still visible. + assert device_health_events(1, 10.4, 65, simulation=False, overheated=1) == ["overheat"] + assert "lowMemory" in device_health_events(0, 10.4, 91, simulation=False, overheated=1) + + +def test_selfdrived_wires_ignore_list_and_last_device_state(): + src = (ROOT / "selfdrive" / "selfdrived" / "selfdrived.py").read_text() + assert "ignore_alive=ignore, ignore_avg_freq=ignore" in src + assert "ignore_valid=ignore" in src + assert "ignore += list(HOUSEKEEPING_SERVICES)" in src + assert "ds.thermalStatus, ds.freeSpacePercent, ds.memoryUsagePercent" in src + assert "fan_desired = ds.fanSpeedPercentDesired if ds_seen else 0" in src + # No new carState subscriber. + assert src.count("sub_sock('carState'") == 1 diff --git a/selfdrive/selfdrived/tests/test_preap_gear_mismatch_clear.py b/selfdrive/selfdrived/tests/test_preap_gear_mismatch_clear.py new file mode 100644 index 00000000000000..aa65f05b656144 --- /dev/null +++ b/selfdrive/selfdrived/tests/test_preap_gear_mismatch_clear.py @@ -0,0 +1,38 @@ +from openpilot.selfdrive.selfdrived.helpers import ( + PREAP_FINGERPRINT, + _gear_is_drive, + preap_not_in_drive_clears_mismatch, +) + + +def _out(*, fingerprint=PREAP_FINGERPRINT, gear): + return preap_not_in_drive_clears_mismatch(fingerprint=fingerprint, gear=gear) + + +def test_gear_is_drive_accepts_name_and_string(): + assert _gear_is_drive("drive") + assert _gear_is_drive(type("G", (), {"name": "drive"})()) + assert not _gear_is_drive("reverse") + assert not _gear_is_drive("park") + assert not _gear_is_drive(None) + + +def test_holds_clear_while_in_reverse(): + assert _out(gear="reverse") + + +def test_holds_clear_while_in_park(): + assert _out(gear="park") + + +def test_holds_clear_while_in_neutral(): + assert _out(gear="neutral") + + +def test_does_not_clear_in_drive(): + assert not _out(gear="drive") + + +def test_non_preap_never_clears(): + assert not _out(fingerprint="honda", gear="reverse") + assert not _out(fingerprint="honda", gear="drive") diff --git a/selfdrive/selfdrived/tests/test_preap_quiet_reverse.py b/selfdrive/selfdrived/tests/test_preap_quiet_reverse.py new file mode 100644 index 00000000000000..08fd948a2cd6cf --- /dev/null +++ b/selfdrive/selfdrived/tests/test_preap_quiet_reverse.py @@ -0,0 +1,158 @@ +"""Pre-AP reverse is a quiet USER_DISABLE, not TAKE CONTROL IMMEDIATELY. + +EventName.reverseGear still drops OP (USER_DISABLE) and blocks re-entry +(NO_ENTRY). Stock ImmediateDisableAlert / warningImmediate is Pre-AP-only +muted so a parking-lot R does not sound like an emergency. FCW/AEB and the +#163 leave-Drive mismatch clear are unchanged. +""" +from cereal import car, log +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.selfdrived.alertmanager import AlertManager +from openpilot.selfdrive.selfdrived.events import ( + ET, + EVENTS, + Events, + ImmediateDisableAlert, + Priority, + pcm_disable_alert, + reverse_gear_disable_alert, +) +from openpilot.selfdrive.selfdrived.helpers import PREAP_FINGERPRINT, preap_not_in_drive_clears_mismatch +from openpilot.selfdrive.selfdrived.state import StateMachine + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus +AudibleAlert = car.CarControl.HUDControl.AudibleAlert +EventName = log.OnroadEvent.EventName +State = log.SelfdriveState.OpenpilotState +VisualAlert = car.CarControl.HUDControl.VisualAlert + + +def _cp(*, fingerprint=PREAP_FINGERPRINT, brand="tesla"): + cp = car.CarParams.new_message() + cp.brand = brand + cp.carFingerprint = fingerprint + return cp + + +def _cs(): + return car.CarState.new_message() + + +def _args(cp=None): + return (cp or _cp(), _cs(), None, False, 100, log.LongitudinalPersonality.standard) + + +def _alert(cp=None): + return reverse_gear_disable_alert(*_args(cp)) + + +def test_reverse_gear_still_user_disables_and_blocks_entry(): + types = EVENTS[EventName.reverseGear] + assert ET.USER_DISABLE in types + assert ET.NO_ENTRY in types + assert ET.PERMANENT in types + assert types[ET.USER_DISABLE] is reverse_gear_disable_alert + + +def test_preap_reverse_disable_is_silent(): + alert = _alert() + assert alert.alert_text_1 == "" + assert alert.alert_text_2 == "" + assert alert.alert_size == AlertSize.none + assert alert.alert_status == AlertStatus.normal + assert alert.visual_alert == VisualAlert.none + assert alert.audible_alert == AudibleAlert.none + assert alert.priority == Priority.HIGH + assert alert.duration == int(1.0 / DT_CTRL) + + +def test_stock_reverse_disable_is_still_immediate_take_control(): + alert = _alert(_cp(fingerprint="HONDA_CIVIC_2022", brand="honda")) + assert isinstance(alert, ImmediateDisableAlert) + assert alert.alert_text_1 == "TAKE CONTROL IMMEDIATELY" + assert alert.alert_text_2 == "Reverse Gear" + assert alert.audible_alert == AudibleAlert.warningImmediate + assert alert.visual_alert == VisualAlert.steerRequired + assert alert.priority == Priority.HIGHEST + + +def test_reverse_user_disable_drops_enabled_state(): + ev = Events() + ev.add(EventName.reverseGear) + sm = StateMachine() + sm.state = State.enabled + enabled, active = sm.update(ev) + assert sm.state == State.disabled + assert not enabled + assert not active + assert ET.USER_DISABLE in sm.current_alert_types + assert ET.IMMEDIATE_DISABLE not in sm.current_alert_types + + +def test_reverse_no_entry_blocks_enable(): + ev = Events() + ev.add(EventName.reverseGear) + ev.add(EventName.pcmEnable) + sm = StateMachine() + sm.state = State.disabled + enabled, _ = sm.update(ev) + assert sm.state == State.disabled + assert not enabled + assert ET.NO_ENTRY in sm.current_alert_types + + +def test_quiet_reverse_outranks_pcm_disable_takeover_chime(): + """Same-frame cruise-off pcmDisable must not become TAKE CONTROL or a chime.""" + cp = _cp() + args = _args(cp) + reverse = reverse_gear_disable_alert(*args) + reverse.alert_type = "reverseGear/userDisable" + reverse.event_type = ET.USER_DISABLE + pcm = pcm_disable_alert(*args) + pcm.alert_type = "pcmDisable/userDisable" + pcm.event_type = ET.USER_DISABLE + + am = AlertManager() + am.add_many(0, [reverse, pcm]) + am.process_alerts(0, set()) + shown = am.current_alert + assert shown.audible_alert == AudibleAlert.none + assert shown.visual_alert == VisualAlert.none + assert shown.alert_text_1 != "TAKE CONTROL IMMEDIATELY" + + # pcmDisable lasts 0.8s; quiet reverse lasts 1s so the chime cannot surface. + pcm_frames = int(0.8 / DT_CTRL) + for frame in range(1, pcm_frames + 1): + am.process_alerts(frame, set()) + shown = am.current_alert + assert shown.audible_alert != AudibleAlert.warningImmediate + assert shown.alert_text_1 != "TAKE CONTROL IMMEDIATELY" + if frame <= int(1.0 / DT_CTRL): + assert shown.audible_alert != AudibleAlert.disengage + + ev = Events() + ev.add(EventName.reverseGear) + ev.add(EventName.pcmDisable) + alerts = ev.create_alerts([ET.USER_DISABLE], list(args)) + by_type = {a.alert_type: a for a in alerts} + assert "reverseGear/userDisable" in by_type + quiet = by_type["reverseGear/userDisable"] + assert quiet.audible_alert == AudibleAlert.none + assert quiet.alert_size == AlertSize.none + + +def test_fcw_aeb_alerts_still_critical(): + """Quiet reverse must not weaken collision alerts.""" + aeb = EVENTS[EventName.stockAeb][ET.PERMANENT] + assert aeb.alert_status == AlertStatus.critical + assert aeb.priority == Priority.HIGHEST + fcw = EVENTS[EventName.fcw][ET.PERMANENT] + assert fcw.alert_status == AlertStatus.critical + assert fcw.priority == Priority.HIGHEST + assert fcw.visual_alert == VisualAlert.fcw + + +def test_leave_drive_mismatch_clear_still_holds_in_reverse(): + assert preap_not_in_drive_clears_mismatch(fingerprint=PREAP_FINGERPRINT, gear="reverse") + assert not preap_not_in_drive_clears_mismatch(fingerprint=PREAP_FINGERPRINT, gear="drive") diff --git a/selfdrive/selfdrived/tests/test_preap_regen.py b/selfdrive/selfdrived/tests/test_preap_regen.py new file mode 100644 index 00000000000000..7348cd33dffa95 --- /dev/null +++ b/selfdrive/selfdrived/tests/test_preap_regen.py @@ -0,0 +1,266 @@ +import pytest + +from openpilot.selfdrive.selfdrived.preap_regen import ( + REGEN_DEMAND_EVIDENCE_COUNT, + PreAPChimeState, + RegenDemandCheck, + gas_should_user_disable, + update_preap_chimes, +) + +# get_preap_accel_limits floor is -1.5 m/s²; -2.0 clears the trigger margin. +OVERFLOW_TARGET = -2.0 + + +def _update(check, *, a_target=OVERFLOW_TARGET, v_ego=15.0, + pedal_long_active=True, brake_pressed=False): + return check.update( + pedal_long_active=pedal_long_active, + brake_pressed=brake_pressed, + a_target=a_target, + v_ego=v_ego, + ) + + +def test_demand_prompt_requires_sustained_overflow(): + check = RegenDemandCheck() + for _ in range(REGEN_DEMAND_EVIDENCE_COUNT - 1): + assert not _update(check) + assert _update(check) + + +def test_demand_prompt_silent_when_plan_fits_envelope(): + check = RegenDemandCheck() + for _ in range(3 * REGEN_DEMAND_EVIDENCE_COUNT): + assert not _update(check, a_target=-1.5) + + +def test_demand_prompt_survives_single_sample_dropouts(): + check = RegenDemandCheck() + fired = False + for _ in range(3 * REGEN_DEMAND_EVIDENCE_COUNT): + for _ in range(9): + fired = _update(check) or fired + fired = _update(check, a_target=-1.6) or fired + if fired: + break + assert fired + + +def test_demand_prompt_does_not_fire_at_standstill(): + check = RegenDemandCheck() + for _ in range(2 * REGEN_DEMAND_EVIDENCE_COUNT): + assert not _update(check, v_ego=0.0) + + +def test_demand_prompt_clears_when_driver_brakes(): + check = RegenDemandCheck() + for _ in range(REGEN_DEMAND_EVIDENCE_COUNT): + _update(check) + assert check.active + + assert not _update(check, brake_pressed=True) + assert not check.active + + +def test_demand_prompt_uses_hysteresis_before_clearing(): + check = RegenDemandCheck() + for _ in range(REGEN_DEMAND_EVIDENCE_COUNT): + _update(check) + assert check.active + + # Back inside the trigger margin but still beyond the clear margin. + assert _update(check, a_target=-1.6, v_ego=1.5) + + # Demand returns to the envelope: prompt clears. + assert not _update(check, a_target=-1.5) + assert not check.active + + +def test_demand_prompt_resets_when_pedal_long_inactive(): + check = RegenDemandCheck() + for _ in range(REGEN_DEMAND_EVIDENCE_COUNT): + _update(check) + assert check.active + + assert not _update(check, pedal_long_active=False) + assert not check.active + + +def _chime(prev, *, lat=False, long_on=False): + return update_preap_chimes(lat_engaged=lat, long_engaged=long_on, prev=prev) + + +# Complete (prev_lat, prev_long) × (lat, long) table. Gas override is a hold of +# enableLongControl, so it is the (T,T)→(T,T) row, not a disengage edge. +CHIME_EDGES = [ + # prev_lat, prev_long, lat, long, lat_eng, lat_dis, long_eng, long_dis, note + (False, False, False, False, False, False, False, False, "idle"), + (False, False, True, False, True, False, False, False, "lat-only engage"), + (False, False, False, True, False, False, True, False, "long-only engage"), + (False, False, True, True, True, False, True, False, "stalk lat+long engage"), + (True, False, False, False, False, True, False, False, "lat cancel"), + (True, False, True, False, False, False, False, False, "hold lat"), + (True, False, False, True, False, True, True, False, "lat cancel + long engage"), + (True, False, True, True, False, False, True, False, "second pull adds long"), + (False, True, False, False, False, False, False, True, "long-only cancel"), + (False, True, True, False, True, False, False, True, "lat engage + long cancel"), + (False, True, False, True, False, False, False, False, "hold long-only"), + (False, True, True, True, True, False, False, False, "add lat to long"), + (True, True, False, False, False, True, False, True, "stalk cancel both"), + (True, True, True, False, False, False, False, False, "brake long pause"), + (True, True, False, True, False, True, False, False, "lat cancel keeps long"), + (True, True, True, True, False, False, False, False, "hold both / gas override"), +] + + +@pytest.mark.parametrize( + "prev_lat,prev_long,lat,long_on,lat_eng,lat_dis,long_eng,long_dis,note", + CHIME_EDGES, + ids=[row[-1] for row in CHIME_EDGES], +) +def test_chime_edge_table(prev_lat, prev_long, lat, long_on, + lat_eng, lat_dis, long_eng, long_dis, note): + prev = PreAPChimeState(lat_engaged=prev_lat, long_engaged=prev_long) + chimes, state = _chime(prev, lat=lat, long_on=long_on) + assert chimes.lat_engage is lat_eng, note + assert chimes.lat_disengage is lat_dis, note + assert chimes.long_engage is long_eng, note + assert chimes.long_disengage is long_dis, note + paused = prev_lat and lat and prev_long and not long_on + assert state == PreAPChimeState(lat_engaged=lat, long_engaged=long_on, long_paused=paused) + + +def test_lat_engage_and_disengage_chime_on_cruise_edges(): + chimes, state = _chime(PreAPChimeState(), lat=True) + assert chimes.lat_engage + assert not chimes.lat_disengage + assert not chimes.long_engage + + chimes, state = _chime(state, lat=True) + assert not chimes.lat_engage + assert not chimes.lat_disengage + + chimes, _ = _chime(state, lat=False) + assert chimes.lat_disengage + assert not chimes.lat_engage + + +def test_long_engage_chimes_on_fsm_intent_not_pedal_authority(): + # Stalk long engage must chime even before interceptor handshake. + chimes, state = _chime(PreAPChimeState(), lat=True, long_on=True) + assert chimes.lat_engage + assert chimes.long_engage + + chimes, _ = _chime(state, lat=True, long_on=True) + assert not chimes.long_engage + + +def test_gas_override_does_not_chime(): + # enableLongControl stays true during pedal override. Press and release + # are holds, not engage/disengage edges. + chimes, state = _chime(PreAPChimeState(), lat=True, long_on=True) + assert chimes.long_engage + + chimes, state = _chime(state, lat=True, long_on=True) + assert not chimes.long_disengage + assert not chimes.long_engage + assert not chimes.lat_disengage + + chimes, _ = _chime(state, lat=True, long_on=True) + assert not chimes.long_engage + assert not chimes.long_disengage + + +def test_brake_or_turn_long_pause_is_silent(): + """Brake / driver-turn drop of long while session stays up: no chime.""" + chimes, state = _chime(PreAPChimeState(), lat=True, long_on=True) + assert chimes.long_engage + + chimes, state = _chime(state, lat=True, long_on=False) + assert not chimes.long_disengage + assert not chimes.long_engage + assert not chimes.lat_disengage + assert state.long_paused + + chimes, _ = _chime(state, lat=False, long_on=False) + assert chimes.lat_disengage + assert not chimes.long_disengage + + +def test_one_set_resume_from_long_pause_is_quiet(): + """One SET restores long only — not a full-stack engage fanfare.""" + chimes, state = _chime(PreAPChimeState(), lat=True, long_on=True) + assert chimes.long_engage + chimes, state = _chime(state, lat=True, long_on=False) + assert state.long_paused + assert not chimes.long_disengage + + chimes, state = _chime(state, lat=True, long_on=True) + assert not chimes.long_engage + assert not chimes.long_disengage + assert not chimes.lat_engage + assert not state.long_paused + + +def test_second_pull_initial_engage_still_chimes_long(): + """Lat-only first pull then second pull is engage, not a pause-resume.""" + chimes, state = _chime(PreAPChimeState(), lat=True, long_on=False) + assert chimes.lat_engage + assert not state.long_paused + + chimes, _ = _chime(state, lat=True, long_on=True) + assert chimes.long_engage + assert not chimes.lat_engage + + +def test_full_cancel_still_chimes_long_disengage(): + chimes, state = _chime(PreAPChimeState(), lat=True, long_on=True) + assert chimes.long_engage + + chimes, state = _chime(state, lat=False, long_on=False) + assert chimes.long_disengage + assert chimes.lat_disengage + + +def test_reengage_after_disengage_chimes_again(): + chimes, state = _chime(PreAPChimeState(), lat=True, long_on=True) + assert chimes.long_engage + chimes, state = _chime(state, lat=False, long_on=False) + assert chimes.lat_disengage + assert chimes.long_disengage + + chimes, _ = _chime(state, lat=True, long_on=True) + assert chimes.lat_engage + assert chimes.long_engage + + +def test_lateral_only_does_not_chime_long_on_hold(): + chimes, state = _chime(PreAPChimeState(), lat=True) + assert chimes.lat_engage + assert not chimes.long_engage + + chimes, _ = _chime(state, lat=True) + assert not chimes.long_engage + assert not chimes.long_disengage + assert not chimes.lat_disengage + + +def test_gas_should_user_disable_skips_when_one_pedal_long(): + """One-Pedal Long On must never take DisengageOnAccelerator USER_DISABLE.""" + assert gas_should_user_disable(disengage_on_accelerator=True, one_pedal_long=False) + assert not gas_should_user_disable(disengage_on_accelerator=True, one_pedal_long=True) + assert not gas_should_user_disable(disengage_on_accelerator=False, one_pedal_long=True) + assert not gas_should_user_disable(disengage_on_accelerator=False, one_pedal_long=False) + + +def test_one_pedal_gas_pause_chime_matches_brake(): + """Gas-from-rest pause is the same silent (T,T)→(T,F) edge as brake.""" + chimes, state = _chime(PreAPChimeState(), lat=True, long_on=True) + assert chimes.long_engage + chimes, state = _chime(state, lat=True, long_on=False) + assert not chimes.long_disengage + assert not chimes.lat_disengage + assert state.long_paused + chimes, _ = _chime(state, lat=True, long_on=True) + assert not chimes.long_engage diff --git a/selfdrive/selfdrived/tests/test_preap_regen_cmd_pin.py b/selfdrive/selfdrived/tests/test_preap_regen_cmd_pin.py new file mode 100644 index 00000000000000..528805c5dd6778 --- /dev/null +++ b/selfdrive/selfdrived/tests/test_preap_regen_cmd_pin.py @@ -0,0 +1,96 @@ +"""F2: the regen-limit prompt needs the post-guard command pinned at the rail. + +15d 15:27:31: plan -1.94 while the guarded actuator sat at -0.22, so the car +was not asking for more than regen could give and the prompt was phantom. +With the command unknown the plan-only rule is unchanged (when in doubt, prompt). +""" +import inspect +import math +from pathlib import Path + +from openpilot.selfdrive.selfdrived import preap_regen +from openpilot.selfdrive.selfdrived.preap_regen import ( + REGEN_DEMAND_CMD_PIN_MARGIN, + REGEN_DEMAND_EVIDENCE_COUNT, + RegenDemandCheck, +) + +FLOOR = -1.5 # get_preap_accel_limits floor + + +def _run(frames, *, a_target, a_cmd="unset", v_ego=15.0, check=None): + check = check or RegenDemandCheck() + fired = False + for _ in range(frames): + kw = {} if a_cmd == "unset" else {"a_cmd": a_cmd} + fired = check.update(pedal_long_active=True, brake_pressed=False, + a_target=a_target, v_ego=v_ego, **kw) or fired + return fired, check + + +def test_constants_are_pinned(): + assert REGEN_DEMAND_CMD_PIN_MARGIN == 0.05 + assert REGEN_DEMAND_EVIDENCE_COUNT == 30 + + +def test_phantom_prompt_is_gone_when_the_command_is_not_at_the_rail(): + """15d 15:27:31: plan -1.94, command -0.22.""" + fired, check = _run(10 * REGEN_DEMAND_EVIDENCE_COUNT, a_target=-1.94, a_cmd=-0.22) + assert not fired and not check.active + assert check.evidence_updates == 0 + + +def test_real_overflow_still_prompts_when_the_command_is_pinned(): + """11:26:49 / 05:55:36: command at the -1.5 rail.""" + for a_target in (-1.94, -3.0): + fired, check = _run(REGEN_DEMAND_EVIDENCE_COUNT, a_target=a_target, a_cmd=-1.5) + assert fired and check.active + + +def test_command_just_inside_the_pin_margin_prompts_just_outside_does_not(): + fired, _ = _run(REGEN_DEMAND_EVIDENCE_COUNT, a_target=-2.0, a_cmd=FLOOR + REGEN_DEMAND_CMD_PIN_MARGIN) + assert fired + fired, _ = _run(10 * REGEN_DEMAND_EVIDENCE_COUNT, a_target=-2.0, a_cmd=FLOOR + REGEN_DEMAND_CMD_PIN_MARGIN + 0.01) + assert not fired + + +def test_unknown_command_is_the_plan_only_rule(): + for a_cmd in ("unset", None, math.nan, math.inf): + fired, _ = _run(REGEN_DEMAND_EVIDENCE_COUNT, a_target=-2.0, a_cmd=a_cmd) + assert fired, a_cmd + + +def test_never_more_prompts_than_the_plan_only_rule(): + for a_target in (-1.4, -1.6, -1.69, -1.71, -2.5): + for v_ego in (1.0, 2.0, 15.0): + for a_cmd in (-1.5, -1.45, -1.0, -0.22, 0.0, 0.5): + with_cmd, _ = _run(3 * REGEN_DEMAND_EVIDENCE_COUNT, a_target=a_target, a_cmd=a_cmd, v_ego=v_ego) + plan_only, _ = _run(3 * REGEN_DEMAND_EVIDENCE_COUNT, a_target=a_target, v_ego=v_ego) + assert plan_only or not with_cmd, (a_target, v_ego, a_cmd) + + +def test_a_command_off_the_rail_cannot_build_evidence_between_pinned_frames(): + """Evidence is a saturating up/down counter: unpinned frames drain it.""" + check = RegenDemandCheck() + fired = False + for _ in range(5 * REGEN_DEMAND_EVIDENCE_COUNT): + fired = _run(1, a_target=-2.0, a_cmd=-1.5, check=check)[0] or fired + fired = _run(2, a_target=-2.0, a_cmd=-0.22, check=check)[0] or fired + assert not fired + + +def test_active_prompt_keeps_going_on_the_plan_alone(): + """Keep-prompting is unchanged: the plan decides, even if the command eases.""" + fired, check = _run(REGEN_DEMAND_EVIDENCE_COUNT, a_target=-2.0, a_cmd=-1.5) + assert fired and check.active + assert check.update(pedal_long_active=True, brake_pressed=False, a_target=-2.0, + v_ego=15.0, a_cmd=-0.22) + assert not check.update(pedal_long_active=True, brake_pressed=False, a_target=-1.5, + v_ego=15.0, a_cmd=-1.5) + + +def test_selfdrived_passes_the_guarded_command(): + src = Path(preap_regen.__file__).with_name("selfdrived.py").read_text() + assert "a_cmd=" in src + assert "carControl'].actuators.accel" in src + assert "a_cmd" in inspect.signature(preap_regen.RegenDemandCheck.update).parameters diff --git a/selfdrive/selfdrived/tests/test_state_machine.py b/selfdrive/selfdrived/tests/test_state_machine.py new file mode 100644 index 00000000000000..b720f48f1ec02b --- /dev/null +++ b/selfdrive/selfdrived/tests/test_state_machine.py @@ -0,0 +1,92 @@ +from cereal import log +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.selfdrived.state import StateMachine, SOFT_DISABLE_TIME +from openpilot.selfdrive.selfdrived.events import Events, ET, EVENTS, NormalPermanentAlert + +State = log.SelfdriveState.OpenpilotState + +# The event types that maintain the current state +MAINTAIN_STATES = {State.enabled: (None,), State.disabled: (None,), State.softDisabling: (ET.SOFT_DISABLE,), + State.preEnabled: (ET.PRE_ENABLE,), State.overriding: (ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL)} +ALL_STATES = tuple(State.schema.enumerants.values()) +# The event types checked in DISABLED section of state machine +ENABLE_EVENT_TYPES = (ET.ENABLE, ET.PRE_ENABLE, ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL) + + +def make_event(event_types): + event = {} + for ev in event_types: + event[ev] = NormalPermanentAlert("alert") + EVENTS[0] = event + return 0 + + +class TestStateMachine: + def setup_method(self): + self.events = Events() + self.state_machine = StateMachine() + self.state_machine.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + + def test_immediate_disable(self): + for state in ALL_STATES: + for et in MAINTAIN_STATES[state]: + self.events.add(make_event([et, ET.IMMEDIATE_DISABLE])) + self.state_machine.state = state + self.state_machine.update(self.events) + assert State.disabled == self.state_machine.state + self.events.clear() + + def test_user_disable(self): + for state in ALL_STATES: + for et in MAINTAIN_STATES[state]: + self.events.add(make_event([et, ET.USER_DISABLE])) + self.state_machine.state = state + self.state_machine.update(self.events) + assert State.disabled == self.state_machine.state + self.events.clear() + + def test_soft_disable(self): + for state in ALL_STATES: + if state == State.preEnabled: # preEnabled considers NO_ENTRY instead + continue + for et in MAINTAIN_STATES[state]: + self.events.add(make_event([et, ET.SOFT_DISABLE])) + self.state_machine.state = state + self.state_machine.update(self.events) + assert self.state_machine.state == State.disabled if state == State.disabled else State.softDisabling + self.events.clear() + + def test_soft_disable_timer(self): + self.state_machine.state = State.enabled + self.events.add(make_event([ET.SOFT_DISABLE])) + self.state_machine.update(self.events) + for _ in range(int(SOFT_DISABLE_TIME / DT_CTRL)): + assert self.state_machine.state == State.softDisabling + self.state_machine.update(self.events) + + assert self.state_machine.state == State.disabled + + def test_no_entry(self): + # Make sure noEntry keeps us disabled + for et in ENABLE_EVENT_TYPES: + self.events.add(make_event([ET.NO_ENTRY, et])) + self.state_machine.update(self.events) + assert self.state_machine.state == State.disabled + self.events.clear() + + def test_no_entry_pre_enable(self): + # preEnabled with noEntry event + self.state_machine.state = State.preEnabled + self.events.add(make_event([ET.NO_ENTRY, ET.PRE_ENABLE])) + self.state_machine.update(self.events) + assert self.state_machine.state == State.preEnabled + + def test_maintain_states(self): + # Given current state's event type, we should maintain state + for state in ALL_STATES: + for et in MAINTAIN_STATES[state]: + self.state_machine.state = state + self.events.add(make_event([et])) + self.state_machine.update(self.events) + assert self.state_machine.state == state + self.events.clear() diff --git a/selfdrive/speedsignd/__init__.py b/selfdrive/speedsignd/__init__.py new file mode 100644 index 00000000000000..42b03f5c16d700 --- /dev/null +++ b/selfdrive/speedsignd/__init__.py @@ -0,0 +1,36 @@ +"""On-drive MUTCD speed-sign logger. Stock modelV2 has no speedSign head. + +These env vars are set before speedsignd.py imports numpy. Manager still +forks this process after numpy is already loaded, so main() also shrinks +the live OpenBLAS / OpenMP pool. An env var cannot resize a pool that +already started. +""" +import os + +_THREAD_ENV = ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "NUMEXPR_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "BLIS_NUM_THREADS", + "OPENCV_FOR_THREADS_NUM", + "GOTO_NUM_THREADS", + "TINYGRAD_NUM_THREADS", + "KMP_NUM_THREADS", +) +for _thread_key in _THREAD_ENV: + os.environ[_thread_key] = "1" +os.environ["OMP_DYNAMIC"] = "FALSE" +os.environ["MKL_DYNAMIC"] = "FALSE" +os.environ["OMP_WAIT_POLICY"] = "PASSIVE" +os.environ["DEV"] = "CPU" +os.environ["CPU"] = "1" +os.environ["CLANG"] = "1" +os.environ["CPU_COUNT"] = "1" +os.environ["BEAM"] = "0" +os.environ["NOOPT"] = "0" +for _gpu_key in ("GPU", "QCOM", "CUDA", "METAL", "AMD", "NV", "CL", "WEBGPU", "DSP"): + os.environ[_gpu_key] = "0" +os.environ["OPENCV_OPENCL_RUNTIME"] = "disabled" +os.environ["OPENCV_DNN_OPENCL"] = "0" diff --git a/selfdrive/speedsignd/debounce.py b/selfdrive/speedsignd/debounce.py new file mode 100644 index 00000000000000..f25aef85389cdf --- /dev/null +++ b/selfdrive/speedsignd/debounce.py @@ -0,0 +1,65 @@ +"""Temporal confirm so one frame does not write JSONL or light the HUD. + +Both need two reads of the same mph from different frames. A class/OCR +contradiction and a class-only hit are not votes. The window is long +enough for two duty-cycled v8n reads when infer is a few seconds. +Empty-road YOLO max conf is ~0. +""" +from __future__ import annotations + +from dataclasses import dataclass, field, replace + +from openpilot.selfdrive.speedsignd.detect_types import SpeedSign +from openpilot.selfdrive.speedsignd.hud import AGREE_READS, frame_reads, note_read, solo_candidate +from openpilot.selfdrive.speedsignd.weights_manifest import DEBOUNCE_HITS, DEBOUNCE_WINDOW_S, YOLO_MIN_CONF + + +@dataclass(frozen=True) +class DebounceResult: + """HUD may accept a first hit; JSONL / confirmed needs `need` hits.""" + hud: list[SpeedSign] + confirmed: list[SpeedSign] + + +@dataclass +class SignDebounce: + """Track hits. JSONL confirms after `need` votes of the same mph.""" + + need: int = DEBOUNCE_HITS + window_s: float = DEBOUNCE_WINDOW_S + min_conf: float = YOLO_MIN_CONF + last_raw: list[SpeedSign] = field(default_factory=list) + _hits: list[tuple[float, int, float, tuple[int, int, int, int]]] = field(default_factory=list) + + def update(self, signs: list[SpeedSign], now: float) -> list[SpeedSign]: + """Back-compat: two-hit / JSONL confirm only.""" + return self.update_split(signs, now).confirmed + + def update_split(self, signs: list[SpeedSign], now: float) -> DebounceResult: + # last_raw keeps detector mph (including unconfirmed 65) for infer logs. + self.last_raw = [s for s in signs if s.conf >= self.min_conf and s.mph > 0] + self._hits = [h for h in self._hits if now - h[0] <= self.window_s] + hud: list[SpeedSign] = [] + for s in self.last_raw: + pending, _pair = frame_reads(s) + if not pending: + # Class-only at the solo floor reaches the plate. It is not a JSONL vote. + if solo_candidate(s) is not None: + hud.append(s) + continue + hud.append(s) + for mph, conf in pending: + note_read(self._hits, now, int(mph), float(conf), s.bbox) + if not hud: + return DebounceResult(hud=[], confirmed=[]) + counts: dict[int, list] = {} + for hit in self._hits: + counts.setdefault(int(hit[1]), []).append(hit) + ready = [mph for mph, rows in counts.items() if len(rows) >= max(self.need, AGREE_READS)] + if not ready: + return DebounceResult(hud=hud, confirmed=[]) + best_mph = max(ready, key=lambda mph: max(row[2] for row in counts[mph])) + top = max(counts[best_mph], key=lambda row: row[2]) + carrier = hud[-1] + confirmed = [replace(carrier, mph=int(best_mph), conf=float(top[2]), bbox=top[3])] + return DebounceResult(hud=hud, confirmed=confirmed) diff --git a/selfdrive/speedsignd/detect.py b/selfdrive/speedsignd/detect.py new file mode 100644 index 00000000000000..e20d98a083078c --- /dev/null +++ b/selfdrive/speedsignd/detect.py @@ -0,0 +1,1527 @@ +"""MUTCD R2-1 detector: YOLO ONNX on the ROAD camera, numpy fallback for tests. + +Stock modelV2 has no speedSign head. On-device detection is a compact YOLOv8 +ONNX under /data (see weights_manifest). The numpy template matcher is only +for unit tests / missing weights — it does not see real roadside signs. + +MUTCD R2-1 is a white rectangle (about 24x30 in, aspect ~0.8) with black +legend: SPEED LIMIT over a 1–3 digit mph value. +""" +from __future__ import annotations + +import os +import time +from typing import Any + +# OpenBLAS / OpenMP / tinygrad read these at import. Force one thread before numpy. +INFER_THREAD_ENV = ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "NUMEXPR_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "BLIS_NUM_THREADS", + "OPENCV_FOR_THREADS_NUM", + "GOTO_NUM_THREADS", + "TINYGRAD_NUM_THREADS", + "KMP_NUM_THREADS", +) +for _thread_key in INFER_THREAD_ENV: + os.environ[_thread_key] = "1" + +# tinygrad's default device on a 3X is QCOM (the Adreno modeld already uses). +# DEV is read once, at import. Pin CPU/CLANG and hide every GPU before that. +# BEAM searches kernels for minutes. NOOPT compiles -O0. Both stay off. +_GPU_ENV = ("GPU", "QCOM", "CUDA", "METAL", "AMD", "NV", "CL", "WEBGPU", "DSP") + + +def pin_cpu_only_env() -> None: + """Force a CPU backend. Never leaves a GPU or QCOM device enabled.""" + os.environ["DEV"] = "CPU" + os.environ["CPU"] = "1" + os.environ["CLANG"] = "1" + os.environ["CPU_COUNT"] = "1" + os.environ["BEAM"] = "0" + os.environ["NOOPT"] = "0" + os.environ["OMP_DYNAMIC"] = "FALSE" + os.environ["MKL_DYNAMIC"] = "FALSE" + os.environ["OMP_WAIT_POLICY"] = "PASSIVE" + os.environ["OPENCV_OPENCL_RUNTIME"] = "disabled" + os.environ["OPENCV_DNN_OPENCL"] = "0" + for key in _GPU_ENV: + os.environ[key] = "0" + for key in INFER_THREAD_ENV: + os.environ[key] = "1" + + +pin_cpu_only_env() + +import numpy as np + +from openpilot.selfdrive.speedsignd.detect_types import MUTCD_MPH, SpeedSign, shift_sign +from openpilot.selfdrive.speedsignd.nv12 import letterbox_rgb_from_nv12_crop, rgb_from_y, upscale_gray +from openpilot.selfdrive.speedsignd.paths import default_onnx_path, nap_data_dir +from openpilot.selfdrive.speedsignd.weights_manifest import ( + YOLO_CLASS_NAMES, + YOLO_IMGSZ, + YOLO_IOU, + YOLO_MAX_DET, + YOLO_MIN_CONF, +) +from openpilot.selfdrive.speedsignd.yolo import ( + SIGN_LIKE_CONF, + decode_yolov8, + letterbox_rgb, + refine_mph, + road_detect_crop, + yolo_peak, +) + +MIN_CONF = 0.42 +MAX_DET = 3 +DIGIT_H, DIGIT_W = 24, 16 +# Downsample the ROAD frame so CC stays cheap on the 3X. +MAX_DETECT_WIDTH = 320 +# tinygrad OnnxRunner / OpenBLAS will otherwise take every core. +THREADS_ENV = "NAP_SPEED_SIGN_THREADS" +THREADS_DEFAULT = 1 +THREADS_MAX = 1 +# Soft cap: cannot kill an in-flight tinygrad kernel; skip/pay-back uses this +# plus infer time so a 1.8 s session cannot immediately start another. +CAP_MS_ENV = "NAP_SPEED_SIGN_INFER_CAP_MS" +CAP_MS_DEFAULT = 800.0 +CAP_MS_MIN = 50.0 +CAP_MS_MAX = 5000.0 + + +def _resize(img: np.ndarray, h: int, w: int) -> np.ndarray: + if img.shape[0] == h and img.shape[1] == w: + return img + ys = np.linspace(0, img.shape[0] - 1, h).astype(np.int32) + xs = np.linspace(0, img.shape[1] - 1, w).astype(np.int32) + return img[ys][:, xs] + + +def _ncc(a: np.ndarray, b: np.ndarray) -> float: + x = a.astype(np.float32).ravel() + y = b.astype(np.float32).ravel() + x -= x.mean() + y -= y.mean() + den = float(np.linalg.norm(x) * np.linalg.norm(y)) + if den < 1e-6: + return 0.0 + return float(np.dot(x, y) / den) + + +def _paint_rect(t: np.ndarray, r0: int, r1: int, c0: int, c1: int, v: int = 1) -> None: + t[r0:r1, c0:c1] = v + + +def _digit_templates() -> dict[int, np.ndarray]: + """Block Highway-Gothic-ish 16x24 ink templates (1 = ink).""" + out: dict[int, np.ndarray] = {} + h, w = DIGIT_H, DIGIT_W + thick = 3 + + def blank() -> np.ndarray: + return np.zeros((h, w), np.uint8) + + # 0: closed oval + t = blank() + _paint_rect(t, 1, 1 + thick, 3, w - 3) + _paint_rect(t, h - 1 - thick, h - 1, 3, w - 3) + _paint_rect(t, 1, h - 1, 2, 2 + thick) + _paint_rect(t, 1, h - 1, w - 2 - thick, w - 2) + out[0] = t + + # 1: right stem + top serif + t = blank() + _paint_rect(t, 1, h - 1, w // 2, w // 2 + thick) + _paint_rect(t, 1, 1 + thick, w // 2 - 4, w // 2 + thick) + _paint_rect(t, h - 1 - thick, h - 1, w // 2 - 4, w // 2 + 5) + out[1] = t + + # 2 + t = blank() + _paint_rect(t, 1, 1 + thick, 2, w - 2) + _paint_rect(t, 1, h // 2, w - 2 - thick, w - 2) + _paint_rect(t, h // 2 - 1, h // 2 - 1 + thick, 2, w - 2) + _paint_rect(t, h // 2, h - 1, 2, 2 + thick) + _paint_rect(t, h - 1 - thick, h - 1, 2, w - 2) + out[2] = t + + # 3 + t = blank() + _paint_rect(t, 1, 1 + thick, 2, w - 2) + _paint_rect(t, h // 2 - 1, h // 2 - 1 + thick, 3, w - 3) + _paint_rect(t, h - 1 - thick, h - 1, 2, w - 2) + _paint_rect(t, 1, h - 1, w - 2 - thick, w - 2) + out[3] = t + + # 4: open top, crossbar, right stem + t = blank() + _paint_rect(t, 1, h // 2 + 1, 2, 2 + thick) + _paint_rect(t, h // 2 - 1, h // 2 - 1 + thick, 2, w - 2) + _paint_rect(t, 1, h - 1, w - 5, w - 2) + out[4] = t + + # 5 + t = blank() + _paint_rect(t, 1, 1 + thick, 2, w - 2) + _paint_rect(t, 1, h // 2, 2, 2 + thick) + _paint_rect(t, h // 2 - 1, h // 2 - 1 + thick, 2, w - 2) + _paint_rect(t, h // 2, h - 1, w - 2 - thick, w - 2) + _paint_rect(t, h - 1 - thick, h - 1, 2, w - 2) + out[5] = t + + # 6 + t = blank() + _paint_rect(t, 1, 1 + thick, 2, w - 3) + _paint_rect(t, 1, h - 1, 2, 2 + thick) + _paint_rect(t, h // 2 - 1, h // 2 - 1 + thick, 2, w - 2) + _paint_rect(t, h // 2, h - 1, w - 2 - thick, w - 2) + _paint_rect(t, h - 1 - thick, h - 1, 2, w - 2) + out[6] = t + + # 7 + t = blank() + _paint_rect(t, 1, 1 + thick, 2, w - 2) + _paint_rect(t, 1, h - 1, w - 2 - thick, w - 2) + out[7] = t + + # 8 + t = blank() + _paint_rect(t, 1, 1 + thick, 3, w - 3) + _paint_rect(t, h // 2 - 1, h // 2 - 1 + thick, 3, w - 3) + _paint_rect(t, h - 1 - thick, h - 1, 3, w - 3) + _paint_rect(t, 1, h - 1, 2, 2 + thick) + _paint_rect(t, 1, h - 1, w - 2 - thick, w - 2) + out[8] = t + + # 9 + t = blank() + _paint_rect(t, 1, 1 + thick, 2, w - 2) + _paint_rect(t, 1, h // 2 + 2, 2, 2 + thick) + _paint_rect(t, 1, h // 2 + 2, w - 2 - thick, w - 2) + _paint_rect(t, h // 2 - 1, h // 2 - 1 + thick, 2, w - 2) + _paint_rect(t, h // 2, h - 1, w - 2 - thick, w - 2) + _paint_rect(t, h - 1 - thick, h - 1, 2, w - 3) + out[9] = t + return out + + +DIGIT_TEMPLATES = _digit_templates() + + +def parse_infer_threads(raw: str | None, default: int = THREADS_DEFAULT) -> int: + """One inference thread. Never a pool.""" + if raw is None or str(raw).strip() == "": + return int(default) + try: + n = int(float(raw)) + except (TypeError, ValueError): + return int(default) + return max(1, min(THREADS_MAX, n)) + + +def parse_infer_cap_ms(raw: str | None, default: float = CAP_MS_DEFAULT) -> float: + """0 disables the cap. Otherwise clamp to a sane skip budget.""" + if raw is None or str(raw).strip() == "": + return float(default) + try: + ms = float(raw) + except (TypeError, ValueError): + return float(default) + if not (ms == ms) or ms < 0: # NaN or negative + return float(default) + if ms == 0.0: + return 0.0 + return min(CAP_MS_MAX, max(CAP_MS_MIN, ms)) + + +def _shrink_blas_pool(threads: int) -> None: + """Resize a BLAS/OpenMP pool that already started. + + Manager forks speedsignd after numpy is imported. OpenBLAS captured + nproc (8 on a 3X) at that init, so the env pin in this file is too late. + The logged `threads=11` was that pool of 8 plus the main thread, the + infer worker, and the VisionIPC client. This call is the one that + actually drops the pool to 1 inside the child. + """ + import ctypes + n = max(1, int(threads)) + for soname in ("libopenblas.so.0", "libopenblas.so", "libblas.so.3", "libblas.so"): + try: + lib = ctypes.CDLL(soname) + except OSError: + continue + for sym in ("openblas_set_num_threads", "goto_set_num_threads"): + fn = getattr(lib, sym, None) + if fn is None: + continue + try: + fn.argtypes = [ctypes.c_int] + fn.restype = None + fn(n) + except Exception: + pass + break + for soname in ("libgomp.so.1", "libgomp.so", "libiomp5.so"): + try: + lib = ctypes.CDLL(soname) + except OSError: + continue + fn = getattr(lib, "omp_set_num_threads", None) + if fn is None: + continue + try: + fn.argtypes = [ctypes.c_int] + fn.restype = None + fn(n) + except Exception: + pass + break + + +def limit_infer_threads(n: int | None = None) -> int: + """Pin BLAS / OpenMP / tinygrad / OpenCV pools. Always one thread on device.""" + pin_cpu_only_env() + threads = parse_infer_threads(os.environ.get(THREADS_ENV) if n is None else str(n)) + n_s = str(threads) + for key in INFER_THREAD_ENV: + os.environ[key] = n_s + _shrink_blas_pool(threads) + try: + import cv2 + cv2.setNumThreads(threads) + ocl = getattr(cv2, "ocl", None) + if ocl is not None and hasattr(ocl, "setUseOpenCL"): + ocl.setUseOpenCL(False) + except Exception: + pass + return threads + + +def paint_digit(canvas: np.ndarray, digit: int, r0: int, c0: int, scale: int = 2, ink: int = 20) -> None: + """Blit a template onto a uint8 Y image (for tests and ONNX fixtures).""" + t = DIGIT_TEMPLATES[int(digit)] + h, w = t.shape + block = np.repeat(np.repeat(t, scale, axis=0), scale, axis=1) + r1 = r0 + block.shape[0] + c1 = c0 + block.shape[1] + if r0 < 0 or c0 < 0 or r1 > canvas.shape[0] or c1 > canvas.shape[1]: + return + canvas[r0:r1, c0:c1] = np.where(block > 0, ink, canvas[r0:r1, c0:c1]) + + +def paint_mutcd_r2_1(canvas: np.ndarray, mph: int, x: int, y: int, w: int, h: int) -> None: + """Draw a white R2-1-style plate with SPEED LIMIT bars and gothic-ish digits.""" + canvas[y:y + h, x:x + w] = 235 + canvas[y:y + 3, x:x + w] = 15 + canvas[y + h - 3:y + h, x:x + w] = 15 + canvas[y:y + h, x:x + 3] = 15 + canvas[y:y + h, x + w - 3:x + w] = 15 + # "SPEED LIMIT" stand-in: two dark word bars in the upper third. + bar_h = max(3, h // 18) + canvas[y + h // 8:y + h // 8 + bar_h, x + w // 6:x + w - w // 6] = 25 + canvas[y + h // 5:y + h // 5 + bar_h, x + w // 5:x + w - w // 5] = 25 + digits = [int(ch) for ch in str(int(mph))] + n = len(digits) + inner_w = max(8, w - 12) + inner_h = max(8, h // 2 - 10) + scale = max(1, min(inner_h // DIGIT_H, (inner_w - (n - 1) * 2) // max(1, n * DIGIT_W))) + digit_w = DIGIT_W * scale + digit_h = DIGIT_H * scale + gap = max(2, scale) + total_w = n * digit_w + (n - 1) * gap + c0 = x + (w - total_w) // 2 + r0 = y + h // 2 + h // 16 + if r0 + digit_h > y + h - 4: + r0 = y + h - 4 - digit_h + for i, d in enumerate(digits): + paint_digit(canvas, d, r0, c0 + i * (digit_w + gap), scale=scale, ink=18) + + +def _components(mask: np.ndarray) -> list[tuple[int, int, int, int, int]]: + """Two-pass connected components → (x, y, w, h, area).""" + h, w = mask.shape + labels = np.zeros((h, w), np.int32) + parent = [0] + + def find(a: int) -> int: + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + def union(a: int, b: int) -> None: + ra, rb = find(a), find(b) + if ra != rb: + parent[rb] = ra + + n = 0 + for r in range(h): + row = mask[r] + lab_row = labels[r] + lab_up = labels[r - 1] if r else None + for c in range(w): + if not row[c]: + continue + left = lab_row[c - 1] if c else 0 + up = lab_up[c] if lab_up is not None else 0 + if left and up: + lab_row[c] = left + union(int(left), int(up)) + elif left: + lab_row[c] = left + elif up: + lab_row[c] = up + else: + n += 1 + parent.append(n) + lab_row[c] = n + + remap: dict[int, int] = {} + next_id = 1 + stats: dict[int, list[int]] = {} + for r in range(h): + lab_row = labels[r] + for c in range(w): + lab = int(lab_row[c]) + if lab == 0: + continue + root = find(lab) + i = remap.get(root) + if i is None: + remap[root] = next_id + i = next_id + next_id += 1 + stats[i] = [c, r, c, r, 0] + s = stats[i] + if c < s[0]: + s[0] = c + if r < s[1]: + s[1] = r + if c > s[2]: + s[2] = c + if r > s[3]: + s[3] = r + s[4] += 1 + boxes = [] + for x0, y0, x1, y1, area in stats.values(): + boxes.append((x0, y0, x1 - x0 + 1, y1 - y0 + 1, area)) + return boxes + + +def _digit_score(patch: np.ndarray, thr: float = 90.0) -> tuple[int, float]: + ink = (patch < thr).astype(np.uint8) + if ink.mean() < 0.05 or ink.mean() > 0.85: + return 0, 0.0 + templ = _resize(ink, DIGIT_H, DIGIT_W) + best_d, best_s = 0, -1.0 + for d, t in DIGIT_TEMPLATES.items(): + s = _ncc(templ, t) + if s > best_s: + best_d, best_s = d, s + return best_d, float(best_s) + + +def _split_digit_boxes(ink: np.ndarray) -> list[tuple[int, int, int, int]]: + if ink.size == 0: + return [] + col = ink.mean(axis=0) + if col.size >= 3: + col = np.convolve(col, np.ones(3, dtype=np.float32) / 3.0, mode="same") + thresh = max(0.025, float(col.max()) * 0.12) + runs = [] + in_run = False + start = 0 + for i, v in enumerate(col): + if v >= thresh and not in_run: + in_run = True + start = i + elif v < thresh and in_run: + in_run = False + runs.append((start, i)) + if in_run: + runs.append((start, len(col))) + + raw: list[tuple[int, int, int, int]] = [] + for x0, x1 in runs: + if x1 - x0 < 2: + continue + strip = ink[:, x0:x1] + rows = np.where(strip.mean(axis=1) > 0.05)[0] + if len(rows) < 4: + continue + y0, y1 = int(rows[0]), int(rows[-1]) + 1 + raw.append((x0, y0, x1 - x0, y1 - y0)) + if not raw: + return [] + + # Open 4 / thin 7: merge adjacent narrow stems. Do not glue a thin stem onto a wide neighbor (4+5). + typical = max(b[2] for b in raw) + thin = max(4, int(typical * 0.45)) + merged: list[tuple[int, int, int, int]] = [raw[0]] + for b in raw[1:]: + prev = merged[-1] + gap = b[0] - (prev[0] + prev[2]) + if prev[2] <= thin and b[2] <= thin and gap <= max(8, typical // 2): + x0 = prev[0] + y0 = min(prev[1], b[1]) + x1 = b[0] + b[2] + y1 = max(prev[1] + prev[3], b[1] + b[3]) + merged[-1] = (x0, y0, x1 - x0, y1 - y0) + else: + merged.append(b) + return merged[:3] + + +READ_MPH_MIN_DIGIT = 0.25 + + +def _ink_thresholds(gray: np.ndarray) -> list[float]: + """Fixed 90 plus a mid-gray split. ROAD plates wash out above 90.""" + if gray.size == 0: + return [90.0] + p20, p80 = np.percentile(gray.astype(np.float32), (20.0, 80.0)) + mid = float(max(40.0, min(160.0, (p20 + p80) * 0.5))) + out: list[float] = [] + for t in (90.0, mid, 70.0, 110.0, 130.0): + t = float(max(40.0, min(160.0, t))) + if all(abs(t - s) > 4.0 for s in out): + out.append(t) + return out + + +def _read_mph_at(lower: np.ndarray, thr: float) -> tuple[int, float, float] | None: + ink = (lower < thr).astype(np.uint8) + boxes = _split_digit_boxes(ink) + if not boxes: + return None + digits = [] + scores = [] + for x, y, bw, bh in boxes: + pad = 1 + y0 = max(0, y - pad) + x0 = max(0, x - pad) + patch = lower[y0:min(lower.shape[0], y + bh + pad), x0:min(lower.shape[1], x + bw + pad)] + d, s = _digit_score(patch, thr) + digits.append(d) + scores.append(s) + if not scores or min(scores) < READ_MPH_MIN_DIGIT: + return None + value = 0 + for d in digits: + value = value * 10 + d + if value not in MUTCD_MPH: + return None + return int(value), float(sum(scores) / len(scores)), float(min(scores)) + + +def _read_mph(crop: np.ndarray) -> tuple[int | None, float]: + h, w = crop.shape + if h < 12 or w < 12: + return None, 0.0 + bands = ( + crop[int(h * 0.42):, int(w * 0.08):int(w * 0.92)], + crop[int(h * 0.38):int(max(int(h * 0.38) + 12, h * 0.98)), int(w * 0.10):int(w * 0.90)], + ) + best: tuple[float, float, int] | None = None # min_digit, conf, mph + for lower in bands: + if lower.size == 0 or lower.shape[0] < 8 or lower.shape[1] < 8: + continue + for thr in _ink_thresholds(lower): + got = _read_mph_at(lower, thr) + if got is None: + continue + value, conf, min_s = got + if best is None or min_s > best[0]: + best = (min_s, conf, value) + if best is None: + return None, 0.0 + _min_s, conf, value = best + # Extra boost when the upper third looks like stacked word bars (SPEED LIMIT). + upper = crop[:int(h * 0.40), int(w * 0.10):int(w * 0.90)] + if upper.size and upper.std() > 18.0: + conf = min(1.0, conf + 0.08) + return value, conf + + +def ocr_tight_y(y: np.ndarray | None) -> tuple[int | None, float]: + """Digit OCR on a full-res plate crop. Upscale when the plate is tiny.""" + if y is None or getattr(y, "ndim", 0) != 2 or y.size == 0: + return None, 0.0 + return _read_mph(upscale_gray(y, 96)) + + +def _sign_candidates(y: np.ndarray) -> list[tuple[int, int, int, int]]: + h, w = y.shape + bright = y > 175 + boxes = _components(bright) + out = [] + frame_area = h * w + for x, yy, bw, bh, area in boxes: + if bh < 18 or bw < 12: + continue + if area < 80: + continue + aspect = bw / float(bh) + if aspect < 0.45 or aspect > 1.15: + continue + fill = area / float(bw * bh) + if fill < 0.35: + continue + if bw * bh > 0.35 * frame_area: + continue + crop = y[yy:yy + bh, x:x + bw] + if crop.std() < 22.0: + continue + # White plate with dark ink: mean should stay high. + if crop.mean() < 140: + continue + out.append((x, yy, bw, bh)) + return out + + +def detect_mutcd_speed_signs(y: np.ndarray, min_conf: float = MIN_CONF) -> list[SpeedSign]: + """Return MUTCD numeric speed signs on a uint8 Y-plane image.""" + if y is None or y.ndim != 2 or y.shape[0] < 32 or y.shape[1] < 32: + return [] + src_h, src_w = y.shape + work = y + scale = 1.0 + if src_w > MAX_DETECT_WIDTH: + scale = MAX_DETECT_WIDTH / float(src_w) + nh = max(32, int(src_h * scale)) + work = _resize(y, nh, MAX_DETECT_WIDTH) + + found: list[SpeedSign] = [] + for x, yy, bw, bh in _sign_candidates(work): + mph, conf = _read_mph(work[yy:yy + bh, x:x + bw]) + if mph is None or conf < min_conf: + continue + if scale != 1.0: + inv = 1.0 / scale + x, yy, bw, bh = int(x * inv), int(yy * inv), int(bw * inv), int(bh * inv) + found.append(SpeedSign(mph=mph, conf=float(conf), bbox=(x, yy, bw, bh))) + if len(found) >= MAX_DET: + break + found.sort(key=lambda s: s.conf, reverse=True) + return found + + +class OnnxSpeedSignDetector: + """Compact ONNX under /data. Missing/unloadable → None. + + Supported models: + 1. Ultralytics YOLOv8 detect (preferred): + input float32 [1,3,H,W] RGB 0..1 (letterboxed) + output float32 [1,4+nc,N] or [1,N,4+nc] + 2. Legacy custom: + input `image` float32 [1,1,H,W] (Y 0..1) or [1,3,H,W] (RGB 0..1) + output `dets` float32 [N,6] = x, y, w, h, mph, conf + A [1,2] (mph, conf) output is also accepted. + """ + + def __init__(self, path: str, session=None, backend: str | None = None): + self.path = path + self.session = session + self.backend = backend or session_backend(session) + self.sha = _sha_short(path) + self.last_diag: dict[str, Any] = self._empty_diag() + + def _empty_diag(self) -> dict[str, Any]: + return { + "backend": self.backend, + "frame_w": 0, + "frame_h": 0, + "letterbox": YOLO_IMGSZ, + "crop": (0, 0, 0, 0), + "weights_path": self.path or "", + "weights_sha": self.sha, + "out_shape": (), + "peak_conf": 0.0, + "peak_name": "", + "n_over": 0, + "sl_peak_conf": 0.0, + "sl_peak_name": "", + "n_over_sl": 0, + "top3": (), + "posted": (), + "refine": (), + "error": "", + "luma_mean": 0.0, + "luma_std": 0.0, + "chroma": 0, + "prep_ms": 0.0, + "sess_ms": 0.0, + } + + def diag_dict(self) -> dict[str, Any]: + return dict(self.last_diag) + + @classmethod + def try_load(cls, path: str | None = None) -> OnnxSpeedSignDetector | None: + path = path or default_onnx_path() + if not path or not os.path.isfile(path): + return None + # v1 at the same path has a different class map. Refuse it so a 60 is + # not decoded as whatever channel 7 means in the new head. + try: + from openpilot.selfdrive.speedsignd.install import weights_loadable + if not weights_loadable(path): + return None + except Exception: + return None + session, backend = _onnx_session(path) + if session is None: + return None + return cls(path, session, backend=backend) + + def detect(self, y: np.ndarray, min_conf: float | None = None, rgb: np.ndarray | None = None, + nv12=None) -> list[SpeedSign]: + diag = self._empty_diag() + self.last_diag = diag + if self.session is None: + diag["error"] = "no-session" + return [] + t_prep = time.monotonic() + luma_src = None + boxed = None + work = None + crop = (0, 0, 0, 0) + scale = 1.0 + pad_x = pad_y = 0 + src_h = src_w = 0 + if nv12 is not None: + y_crop = getattr(nv12, "y", None) + if y_crop is None or getattr(y_crop, "ndim", 0) != 2: + diag["error"] = "no-frame" + return [] + src_w = int(getattr(nv12, "frame_w", 0) or y_crop.shape[1]) + src_h = int(getattr(nv12, "frame_h", 0) or y_crop.shape[0]) + crop = tuple(getattr(nv12, "crop", (0, 0, y_crop.shape[1], y_crop.shape[0]))) + diag["frame_w"] = src_w + diag["frame_h"] = src_h + diag["crop"] = crop + diag["luma_mean"] = float(y_crop.mean()) + diag["luma_std"] = float(y_crop.std()) + uv = getattr(nv12, "uv", None) + diag["chroma"] = 1 if uv is not None and getattr(uv, "size", 0) else 0 + luma_src = y_crop + else: + rgb_given = rgb is not None + if rgb is None: + if y is None or y.ndim != 2: + diag["error"] = "no-frame" + return [] + rgb = rgb_from_y(y) + if rgb.ndim != 3 or rgb.shape[-1] != 3: + diag["error"] = "bad-rgb" + return [] + src_h, src_w = rgb.shape[:2] + diag["frame_w"] = int(src_w) + diag["frame_h"] = int(src_h) + if y is not None and getattr(y, "ndim", 0) == 2: + diag["luma_mean"] = float(y.mean()) + diag["luma_std"] = float(y.std()) + else: + diag["luma_mean"] = float(rgb.mean()) + diag["luma_std"] = float(rgb.std()) + # Caller RGB may be real chroma; rgb_from_y is luma-only. + diag["chroma"] = 1 if rgb_given else 0 + inp = _onnx_input_name(self.session) + shape = _onnx_input_shape(self.session) + yolo = _is_yolo_input(shape) + try: + if yolo: + size = YOLO_IMGSZ + if shape is not None and len(shape) == 4: + h = int(shape[2]) if shape[2] not in (None, 0, -1) else YOLO_IMGSZ + w = int(shape[3]) if shape[3] not in (None, 0, -1) else YOLO_IMGSZ + size = h if h == w else YOLO_IMGSZ + diag["letterbox"] = int(size) + if nv12 is not None: + boxed, scale, pad_x, pad_y = letterbox_rgb_from_nv12_crop(nv12, size) + crop_h, crop_w = luma_src.shape[:2] + cx, cy = int(crop[0]), int(crop[1]) + else: + work, crop = road_detect_crop(rgb) + diag["crop"] = crop + cx, cy, _cw, _ch = crop + boxed, scale, pad_x, pad_y = letterbox_rgb(work, size) + crop_h, crop_w = work.shape[:2] + blob = boxed.transpose(2, 0, 1)[None, ...].astype(np.float32) / 255.0 + diag["prep_ms"] = (time.monotonic() - t_prep) * 1000.0 + t_sess = time.monotonic() + raw = self.session.run(None, {inp: blob})[0] + diag["sess_ms"] = (time.monotonic() - t_sess) * 1000.0 + peak = yolo_peak(raw) + diag["out_shape"] = peak.shape + diag["peak_conf"] = peak.conf + diag["peak_name"] = peak.name + diag["n_over"] = peak.n_over + diag["sl_peak_conf"] = peak.sl_conf + diag["sl_peak_name"] = peak.sl_name + diag["n_over_sl"] = peak.n_over_sl + diag["top3"] = peak.top3 + diag["posted"] = peak.posted + thr = YOLO_MIN_CONF if min_conf is None else min_conf + like = decode_yolov8( + raw, scale=scale, pad_x=pad_x, pad_y=pad_y, src_hw=(crop_h, crop_w), + names=YOLO_CLASS_NAMES, min_conf=SIGN_LIKE_CONF, iou=YOLO_IOU, max_det=YOLO_MAX_DET, + ) + if luma_src is not None: + luma = luma_src + elif y is not None and getattr(y, "ndim", 0) == 2: + luma = y[cy:cy + crop_h, cx:cx + crop_w] + if luma.shape[:2] != (crop_h, crop_w): + luma = work[:, :, 1] + else: + luma = work[:, :, 1] + refined_like = [refine_mph(s, luma, _read_mph) for s in like] + if cx or cy: + refined_like = [shift_sign(s, cx, cy) for s in refined_like] + refined = [ + s for s in refined_like + if float(s.conf) >= thr or ( + s.refine_mph is not None and float(s.refine_conf or 0.0) >= 0.28 + ) + ] + if refined_like: + best_like = max(refined_like, key=lambda s: float(s.conf)) + diag["sign_like_bbox"] = tuple(int(v) for v in best_like.bbox) + else: + diag["sign_like_bbox"] = None + diag["refine"] = tuple( + ( + int(s.class_mph if s.class_mph is not None else s.mph), + int(s.mph), + None if s.refine_mph is None else int(s.refine_mph), + float(s.refine_conf), + ) + for s in refined + ) + return refined + arr = (y if y is not None else rgb[:, :, 1]).astype(np.float32) / 255.0 + if shape is not None and len(shape) == 4: + _n, c, h, w = [int(v) if v not in (None, 0, -1) else None for v in shape] + hh = h or 256 + ww = w or 256 + resized = _resize(arr, hh, ww) + if c == 3: + blob = np.stack([resized, resized, resized], axis=0)[None, ...] + else: + blob = resized[None, None, ...] + else: + blob = arr[None, None, ...] + diag["prep_ms"] = (time.monotonic() - t_prep) * 1000.0 + t_sess = time.monotonic() + raw = self.session.run(None, {inp: blob.astype(np.float32)})[0] + diag["sess_ms"] = (time.monotonic() - t_sess) * 1000.0 + except Exception as e: + diag["error"] = f"{type(e).__name__}: {e}" + diag["prep_ms"] = (time.monotonic() - t_prep) * 1000.0 + return [] + thr = MIN_CONF if min_conf is None else min_conf + return _parse_onnx_dets(raw, (src_h, src_w), thr) + + +def _sha_short(path: str | None, n: int = 12) -> str: + if not path or not os.path.isfile(path): + return "" + try: + from openpilot.selfdrive.speedsignd.install import sha256_file + return sha256_file(path)[:n] + except Exception: + return "" + + +def session_backend(session) -> str: + if session is None: + return "none" + tagged = getattr(session, "_nap_backend", None) + if tagged: + return str(tagged) + mod = getattr(type(session), "__module__", "") + if "onnxruntime" in mod: + return "onnxruntime-cpu" + name = type(session).__name__ + if name == "_TinyOrtSession": + return "tinygrad-cpu" + return name + + +def compile_cache_dir(sha: str) -> str: + """Per-weights compile cache under /data. One clang compile per sha.""" + root = os.environ.get("NAP_SPEED_SIGN_CACHE") or os.path.join(nap_data_dir(), "speed_sign_cache") + digest = (sha or "unknown").strip() or "unknown" + return os.path.join(root, digest) + + +def _compile_stamp_path(sha: str) -> str: + return os.path.join(compile_cache_dir(sha), "ready") + + +def compile_cache_warm(sha: str) -> bool: + """True when a previous disengaged run finished this sha. + + tinygrad also needs its sqlite kernel cache. opencv/onnxruntime only + need the stamp: their session create is not the multi-minute clang. + """ + if not sha or not os.path.isfile(_compile_stamp_path(sha)): + return False + try: + with open(_compile_stamp_path(sha), encoding="utf-8") as f: + text = f.read() + except OSError: + return False + if "tinygrad" in text: + db = os.path.join(compile_cache_dir(sha), "tinygrad", "cache.db") + try: + return os.path.isfile(db) and os.path.getsize(db) > 0 + except OSError: + return False + return True + + +def write_compile_stamp(sha: str, backend: str) -> None: + if not sha: + return + path = _compile_stamp_path(sha) + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + tmp = path + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + f.write((backend or "cpu") + "\n" + sha + "\n") + os.replace(tmp, path) + except OSError: + return + + +def compile_allowed(*, known: bool, controlling: bool, ready: bool) -> bool: + """Warm-up realizes kernels. Start it only when known disengaged. + + Unknown cereal is not disengaged: after the startup grace, unread + selfdriveState used to set controlling False and the first clang + realize ran while the car was engaged. A finished cache (ready) may + run while engaged. Offroad never reaches this process (manager starts + it only onroad); disengaged onroad is the compile window. + """ + if ready: + return True + if controlling or not known: + return False + return True + + +def dnn_ids_are_cpu( + backend: int, + target: int, + *, + gpu_backends: set[int], + gpu_targets: set[int], + cpu_target: int, +) -> bool: + """OpenCV DNN must stay on the CPU target. Never CUDA, OpenCL, or Vulkan.""" + if int(backend) in gpu_backends or int(target) in gpu_targets: + return False + return int(target) == int(cpu_target) + + +def _device_is_cpu(name: str) -> bool: + base = (name or "").split(":")[0].strip().upper() + return base in ("CPU", "CLANG") + + +def assert_cpu_backend(session) -> str: + """Startup check. Raise unless this session can only run on CPU. + + onnxruntime must be exactly CPUExecutionProvider. opencv-dnn must be the + OpenCV CPU target. tinygrad must be the CPU/CLANG device, never QCOM, + CUDA, METAL, or any other GPU. + """ + if session is None: + raise AssertionError("speedsignd session is missing") + backend = str(getattr(session, "_nap_backend", "") or "") + device = str(getattr(session, "_nap_device", "") or "") + if backend == "opencv-dnn-cpu": + if device and not _device_is_cpu(device): + raise AssertionError("speedsignd backend is not CPU: " + backend + " device=" + device) + return "opencv-dnn-cpu" + get_providers = getattr(session, "get_providers", None) + if get_providers is not None and not isinstance(session, (_TinyOrtSession, _LazyCpuSession)): + providers = list(get_providers()) + if providers != ["CPUExecutionProvider"]: + raise AssertionError("onnxruntime providers " + str(providers) + " are not CPU-only") + try: + session._nap_backend = "onnxruntime-cpu" + session._nap_device = "CPU" + except Exception: + pass + return "onnxruntime-cpu" + if backend == "onnxruntime-cpu": + return "onnxruntime-cpu" + blob = (backend + " " + device).upper() + for tok in ("QCOM", "CUDA", "METAL", "WEBGPU", "OPENCL", "GPU"): + if tok in blob: + raise AssertionError("speedsignd backend is not CPU: " + backend + " device=" + device) + if not (_device_is_cpu(device) or "CPU" in blob or "CLANG" in blob): + raise AssertionError("speedsignd backend is not CPU: " + backend + " device=" + device) + renderer = str(getattr(session, "_nap_renderer", "") or "") + if "CLANG" in device.upper() or "CLANG" in renderer.upper() or backend == "tinygrad-clang": + return "tinygrad-clang" + return "tinygrad-cpu" + + +def describe_infer_runtimes() -> str: + """What this process can import. Prefer ORT, then cv2.dnn, then tinygrad.""" + pin_cpu_only_env() + try: + from openpilot.selfdrive.speedsignd.install import ensure_vendored_runtime + ensure_vendored_runtime() + except Exception: + pass + try: + import onnxruntime as ort + ort_s = "onnxruntime-" + str(getattr(ort, "__version__", "present")) + except Exception as e: + ort_s = "onnxruntime-absent(" + type(e).__name__ + ")" + cv_s = "cv2-dnn-present" if _cv2_dnn_available() else "cv2-dnn-absent" + try: + import tinygrad + tg_s = "tinygrad-" + str(getattr(tinygrad, "__version__", "present")) + except Exception as e: + tg_s = "tinygrad-absent(" + type(e).__name__ + ")" + return ort_s + " " + cv_s + " " + tg_s + + +def _cv2_dnn_available() -> bool: + try: + import cv2 + except Exception: + return False + dnn = getattr(cv2, "dnn", None) + return dnn is not None and hasattr(dnn, "readNetFromONNX") + + +def _cv_dnn_id_sets() -> tuple[set[int], set[int], int]: + import cv2 + gpu_b: set[int] = set() + gpu_t: set[int] = set() + for name in ( + "DNN_BACKEND_CUDA", "DNN_BACKEND_VKCOM", "DNN_BACKEND_INFERENCE_ENGINE", + "DNN_BACKEND_TIMVX", "DNN_BACKEND_CANN", "DNN_BACKEND_WEBNN", + ): + if hasattr(cv2.dnn, name): + gpu_b.add(int(getattr(cv2.dnn, name))) + for name in ( + "DNN_TARGET_CUDA", "DNN_TARGET_CUDA_FP16", "DNN_TARGET_OPENCL", + "DNN_TARGET_OPENCL_FP16", "DNN_TARGET_VULKAN", "DNN_TARGET_FPGA", + "DNN_TARGET_MYRIAD", "DNN_TARGET_HDDL", "DNN_TARGET_NPU", + ): + if hasattr(cv2.dnn, name): + gpu_t.add(int(getattr(cv2.dnn, name))) + return gpu_b, gpu_t, int(cv2.dnn.DNN_TARGET_CPU) + + +def _read_cv_net(path: str): + """Built-in OpenCV CPU engine. Never ENGINE_ORT, CUDA, or OpenCL.""" + import cv2 + for name in ("ENGINE_CLASSIC", "ENGINE_OPENCV", "ENGINE_NEW"): + engine = getattr(cv2.dnn, name, None) + if engine is None: + continue + try: + return cv2.dnn.readNetFromONNX(path, int(engine)) + except TypeError: + break + except Exception: + continue + return cv2.dnn.readNetFromONNX(path) + + +def _open_cv_dnn(path: str) -> _CvDnnSession: + """OpenCV's CPU DNN runner. Never OpenCL, CUDA, or Vulkan.""" + import cv2 + cv2.setNumThreads(1) + ocl = getattr(cv2, "ocl", None) + if ocl is not None and hasattr(ocl, "setUseOpenCL"): + ocl.setUseOpenCL(False) + net = _read_cv_net(path) + backend = int(cv2.dnn.DNN_BACKEND_OPENCV) + target = int(cv2.dnn.DNN_TARGET_CPU) + try: + net.setPreferableBackend(backend) + net.setPreferableTarget(target) + except Exception: + pass + got_b, got_t = backend, target + get_b = getattr(net, "getPreferableBackend", None) + get_t = getattr(net, "getPreferableTarget", None) + if get_b is not None: + got_b = int(get_b()) + if get_t is not None: + got_t = int(get_t()) + gpu_b, gpu_t, cpu_t = _cv_dnn_id_sets() + if not dnn_ids_are_cpu(got_b, got_t, gpu_backends=gpu_b, gpu_targets=gpu_t, cpu_target=cpu_t): + raise AssertionError("cv2.dnn backend=" + str(got_b) + " target=" + str(got_t) + " is not CPU") + if ocl is not None and hasattr(ocl, "useOpenCL") and ocl.useOpenCL(): + raise AssertionError("cv2 OpenCL stayed on") + return _CvDnnSession(net) + + +def _prepare_tinygrad_cache(sha: str) -> None: + """Point tinygrad's sqlite kernel cache at /data, keyed by weights sha. + + ClangJITCompiler already passes -O2. It does not vectorize: the compile + is freestanding C, and LLVM's SLP/loop passes are a different renderer. + BEAM stays off (that search is the long compile). NOOPT stays off. + The cache is what makes the clang compile once per sha instead of every boot. + """ + pin_cpu_only_env() + cache = compile_cache_dir(sha) + try: + os.makedirs(cache, exist_ok=True) + except OSError: + return + os.environ["XDG_CACHE_HOME"] = cache + os.environ["CACHEDB"] = os.path.join(cache, "tinygrad", "cache.db") + os.environ["BEAM"] = "0" + os.environ["NOOPT"] = "0" + os.environ["CACHELEVEL"] = "2" + os.environ["CPU_COUNT"] = "1" + + +def _open_tinygrad_cpu(sha: str = "") -> tuple[str, str]: + """Import tinygrad only after DEV=CPU. Do not probe QCOM or any GPU.""" + _prepare_tinygrad_cache(sha) + from tinygrad.device import Device + from tinygrad.helpers import BEAM, CPU_COUNT, DEV, NOOPT + DEV.value = "CPU" + BEAM.value = 0 + NOOPT.value = 0 + CPU_COUNT.value = 1 + opened = Device["CPU"] + name = str(getattr(opened, "device", "CPU")) + if not _device_is_cpu(name): + raise AssertionError("tinygrad opened " + name + ", not CPU") + renderer = type(getattr(opened, "renderer", None)).__name__ + renderer_u = renderer.upper() + for tok in ("QCOM", "CUDA", "METAL", "GPU", "WEBGPU"): + if tok in renderer_u: + raise AssertionError("tinygrad CPU renderer is " + renderer) + if "CLANG" not in renderer_u and "LLVM" not in renderer_u and "CPU" not in renderer_u: + raise AssertionError("tinygrad renderer " + renderer + " is not CPU/CLANG") + return name, renderer + + +def _ort_session(path: str, threads: int, sha: str): + import onnxruntime as ort + opts = ort.SessionOptions() + opts.intra_op_num_threads = threads + opts.inter_op_num_threads = 1 + opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + try: + opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL + except Exception: + pass + optimized = os.path.join(compile_cache_dir(sha), "model.ort") + try: + os.makedirs(os.path.dirname(optimized), exist_ok=True) + if not os.path.isfile(optimized): + opts.optimized_model_filepath = optimized + except OSError: + optimized = "" + model = optimized if optimized and os.path.isfile(optimized) else path + sess = ort.InferenceSession(model, opts, providers=["CPUExecutionProvider"]) + sess._nap_backend = "onnxruntime-cpu" + sess._nap_device = "CPU" + sess.compiled = True + sess._nap_sha = sha + return sess + + +def _select_cpu_kind() -> str: + """Which CPU runner this process can import. Does not load weights. + + System onnxruntime wins. Otherwise the aarch64 wheel under + /data/media/0/nap/pylib is inserted on sys.path (never the system venv). + cv2.dnn is next. tinygrad CLANG is the slow fallback and must not be + realized while engaged. + """ + try: + from openpilot.selfdrive.speedsignd.install import ensure_vendored_runtime + ensure_vendored_runtime() + except Exception: + pass + try: + import onnxruntime # noqa: F401 + return "onnxruntime-cpu" + except Exception: + pass + if _cv2_dnn_available(): + return "opencv-dnn-cpu" + try: + import tinygrad # noqa: F401 + return "tinygrad-clang" + except Exception: + return "" + + +def _log_clang_fallback(kind: str) -> None: + """One warning when the CPU runner is CLANG only because onnxruntime did not import.""" + from openpilot.selfdrive.speedsignd.install import clang_fallback_warning + text = clang_fallback_warning(kind) + if not text: + return + from openpilot.common.swaglog import cloudlog + cloudlog.warning(text) + + +def _onnx_session(path: str) -> tuple[object | None, str]: + """Pick a CPU session. Do not realize it here — that is the compile.""" + limit_infer_threads() + pin_cpu_only_env() + kind = _select_cpu_kind() + if kind == "tinygrad-clang": + _log_clang_fallback(kind) + if not kind: + return None, "" + sha = _sha_short(path, n=64) + sess = _LazyCpuSession(path, sha, kind) + return sess, assert_cpu_backend(sess) + + +class _CvDnnSession: + """cv2.dnn on DNN_BACKEND_OPENCV + DNN_TARGET_CPU. No OpenCL.""" + + def __init__(self, net, input_name: str = "images"): + self.net = net + self._nap_backend = "opencv-dnn-cpu" + self._nap_device = "CPU" + self._nap_renderer = "opencv-dnn" + self.compiled = False + self._allow_compile = False + self._inputs = [type("I", (), {"name": input_name, "shape": [1, 3, YOLO_IMGSZ, YOLO_IMGSZ]})()] + + def allow_compile(self, allow: bool) -> None: + self._allow_compile = bool(allow) + + def get_inputs(self): + return self._inputs + + def run(self, _outs, feed: dict): + if not self.compiled and not self._allow_compile: + raise RuntimeError("compile-blocked while driving") + blob = np.ascontiguousarray(next(iter(feed.values())), dtype=np.float32) + self.net.setInput(blob) + out = self.net.forward() + self.compiled = True + return [np.asarray(out)] + + +class _LazyCpuSession: + """Build the CPU net on first allowed run, not at process start. + + Session create for onnxruntime and the first tinygrad realize are the + compile. Both used to run from SpeedSignDetector() in main(), before + engagement was known. A warm stamp skips that wait. + """ + + def __init__(self, path: str, sha: str, kind: str): + self.path = path + self.sha = sha + self.kind = kind + self._impl = None + self._allow_compile = False + self._nap_backend = kind + self._nap_device = "CPU" + self._nap_renderer = "CLANG" if kind == "tinygrad-clang" else kind + self.compiled = bool(sha) and compile_cache_warm(sha) + self._inputs = [type("I", (), {"name": "images", "shape": [1, 3, YOLO_IMGSZ, YOLO_IMGSZ]})()] + + def allow_compile(self, allow: bool) -> None: + self._allow_compile = bool(allow) + fn = getattr(self._impl, "allow_compile", None) + if fn is not None: + fn(bool(allow)) + + def get_inputs(self): + return self._inputs if self._impl is None else self._impl.get_inputs() + + def _build(self): + threads = limit_infer_threads() + if self.kind == "onnxruntime-cpu": + return _ort_session(self.path, threads, self.sha) + if self.kind == "opencv-dnn-cpu": + return _open_cv_dnn(self.path) + device, renderer = _open_tinygrad_cpu(self.sha) + from tinygrad import Tensor + from tinygrad.nn.onnx import OnnxRunner + runner = OnnxRunner(self.path) + sess = _TinyOrtSession( + runner, Tensor, device=device, renderer=renderer, sha=self.sha, jit=True, + ) + if self.compiled: + sess.compiled = True + return sess + + def run(self, outs, feed: dict): + if self._impl is None: + if not self.compiled and not self._allow_compile: + raise RuntimeError("compile-blocked while driving") + self._impl = self._build() + if self.compiled: + self._impl.compiled = True + self._nap_backend = str(getattr(self._impl, "_nap_backend", self.kind)) + self._nap_device = str(getattr(self._impl, "_nap_device", "CPU")) + self._nap_renderer = str(getattr(self._impl, "_nap_renderer", self._nap_renderer)) + assert_cpu_backend(self._impl) + fn = getattr(self._impl, "allow_compile", None) + if fn is not None: + fn(self._allow_compile) + if not getattr(self._impl, "compiled", False) and not self._allow_compile: + raise RuntimeError("compile-blocked while driving") + out = self._impl.run(outs, feed) + if getattr(self._impl, "compiled", False): + self.compiled = True + write_compile_stamp(self.sha, self._nap_backend) + return out + + +class _TinyOrtSession: + """onnxruntime-shaped wrapper around tinygrad OnnxRunner, CPU/CLANG only. + + Clang at -O2 is still scalar (no LLVM SLP). TinyJit keeps the captured + graph so later runs do not retrace. The sqlite cache under /data is what + skips clang the next boot. BEAM and NOOPT stay off. + """ + + def __init__(self, runner, tensor_cls, device: str = "CPU", renderer: str = "", + sha: str = "", jit: bool = False): + self.runner = runner + self._tensor = tensor_cls + self._nap_device = device + self._nap_renderer = renderer + self._nap_backend = "tinygrad-clang" if "CLANG" in renderer.upper() else "tinygrad-cpu" + self._nap_sha = sha + self.compiled = False + self._allow_compile = False + self._want_jit = bool(jit) + self._jit = None + names = list(getattr(runner, "graph_inputs", {}) or {"images": None}) + self._inputs = [type("I", (), {"name": names[0] if names else "images", "shape": [1, 3, YOLO_IMGSZ, YOLO_IMGSZ]})()] + + def allow_compile(self, allow: bool) -> None: + self._allow_compile = bool(allow) + + def get_inputs(self): + return self._inputs + + def _realize(self, feed: dict): + tensors = {} + for k, v in feed.items(): + tensor = self._tensor(v) + move = getattr(tensor, "to", None) + if move is not None: + try: + tensor = move("CPU") + except Exception: + pass + tensors[k] = tensor + out = self.runner(tensors) + if isinstance(out, dict): + val = next(iter(out.values())) + else: + val = out + dev = str(getattr(val, "device", self._nap_device) or self._nap_device) + if not _device_is_cpu(dev): + raise AssertionError("speedsignd realized on " + dev + ", not CPU") + self._nap_device = dev.split(":")[0].upper() + return val.numpy() if hasattr(val, "numpy") else np.asarray(val) + + def _jit_call(self, blob): + name = self._inputs[0].name + return self._realize({name: blob}) + + def run(self, _outs, feed: dict): + if not self.compiled and not self._allow_compile: + raise RuntimeError("compile-blocked while driving") + # First realize is the compile. TinyJit captures the next call so the + # graph is not retraced. Kernel bytes come from the /data cache. + if self._want_jit and self.compiled: + if self._jit is None: + jit_cls = _tinyjit_cls() + self._jit = jit_cls(self._jit_call) if jit_cls is not None else None + if self._jit is None: + self._want_jit = False + if self._jit is not None: + blob = next(iter(feed.values())) + try: + return [np.asarray(self._jit(blob))] + except Exception: + self._want_jit = False + self._jit = None + arr = self._realize(feed) + self.compiled = True + return [arr] + + +def _tinyjit_cls(): + """TinyJit captures one CLANG graph. Missing tinygrad just runs directly.""" + try: + from tinygrad import TinyJit + return TinyJit + except Exception: + pass + try: + from tinygrad.engine.jit import TinyJit + return TinyJit + except Exception: + return None + + +def _is_yolo_input(shape) -> bool: + if shape is None or len(shape) != 4: + return False + c = shape[1] + return c in (3, "3") + + +def _onnx_input_name(session) -> str: + try: + return session.get_inputs()[0].name + except Exception: + return "image" + + +def _onnx_input_shape(session): + try: + return session.get_inputs()[0].shape + except Exception: + return None + + +def _parse_onnx_dets(raw, frame_hw: tuple[int, int], min_conf: float) -> list[SpeedSign]: + arr = np.asarray(raw, dtype=np.float32) + signs: list[SpeedSign] = [] + if arr.ndim == 1 and arr.size >= 2: + arr = arr.reshape(1, -1) + if arr.ndim == 3: + arr = arr.reshape(-1, arr.shape[-1]) + if arr.ndim != 2: + return [] + fh, fw = frame_hw + for row in arr: + if row.size == 2: + mph, conf = float(row[0]), float(row[1]) + x, yy, bw, bh = 0, 0, fw, fh + elif row.size >= 6: + x, yy, bw, bh, mph, conf = (float(v) for v in row[:6]) + else: + continue + if conf < min_conf: + continue + ival = int(round(mph)) + if ival not in MUTCD_MPH: + continue + signs.append(SpeedSign(mph=ival, conf=float(conf), bbox=(int(x), int(yy), int(bw), int(bh)))) + signs.sort(key=lambda s: s.conf, reverse=True) + return signs[:MAX_DET] + + +class SpeedSignDetector: + """YOLO ONNX if weights exist on /data. Numpy matcher is tests/dev only.""" + + def __init__(self, onnx: OnnxSpeedSignDetector | None = None, onnx_path: str | None = None): + self.onnx_path = onnx_path + if onnx is not None: + self.onnx = onnx + else: + self.onnx = OnnxSpeedSignDetector.try_load(onnx_path) + + def weights_missing(self) -> bool: + return self.onnx is None + + def backend_name(self) -> str: + if self.onnx is None: + return "numpy-mutcd" + return self.onnx.backend or "yolo-onnx" + + def weights_sha_short(self) -> str: + if self.onnx is not None and self.onnx.sha: + return self.onnx.sha + return _sha_short(self.onnx_path) + + def diag_dict(self) -> dict[str, Any]: + if self.onnx is not None: + return self.onnx.diag_dict() + return { + "backend": "numpy-mutcd", + "frame_w": 0, + "frame_h": 0, + "letterbox": 0, + "crop": (0, 0, 0, 0), + "weights_path": self.onnx_path or "", + "weights_sha": self.weights_sha_short(), + "out_shape": (), + "peak_conf": 0.0, + "peak_name": "", + "n_over": 0, + "sl_peak_conf": 0.0, + "sl_peak_name": "", + "n_over_sl": 0, + "top3": (), + "posted": (), + "refine": (), + "error": "", + "luma_mean": 0.0, + "luma_std": 0.0, + "chroma": 0, + "prep_ms": 0.0, + "sess_ms": 0.0, + } + + def try_reload(self) -> bool: + """Load ONNX if the file appeared after Settings install. True if newly loaded.""" + if self.onnx is not None: + return False + loaded = OnnxSpeedSignDetector.try_load(self.onnx_path) + if loaded is None: + return False + self.onnx = loaded + return True + + def compile_ready(self) -> bool: + """False until warm-up or a per-sha cache stamp. Missing means not ready.""" + if self.onnx is None or self.onnx.session is None: + return True + return bool(getattr(self.onnx.session, "compiled", False)) + + def allow_compile(self, allow: bool) -> None: + sess = None if self.onnx is None else self.onnx.session + fn = getattr(sess, "allow_compile", None) + if fn is not None: + fn(bool(allow)) + + def compile_allowed_now(self) -> bool: + """Live flag the worker re-reads before realize. + + A warm session (compiled) may run while engaged. Otherwise the flag + set by the main loop this tick wins, including the first frame of a + boot that is already engaged. + """ + if self.compile_ready(): + return True + sess = None if self.onnx is None else self.onnx.session + return bool(getattr(sess, "_allow_compile", False)) + + def detect(self, y: np.ndarray, min_conf: float | None = None, rgb: np.ndarray | None = None, + nv12=None) -> list[SpeedSign]: + if self.onnx is not None: + thr = YOLO_MIN_CONF if min_conf is None else min_conf + return self.onnx.detect(y, min_conf=thr, rgb=rgb, nv12=nv12) + thr = MIN_CONF if min_conf is None else min_conf + return detect_mutcd_speed_signs(y, min_conf=thr) diff --git a/selfdrive/speedsignd/detect_types.py b/selfdrive/speedsignd/detect_types.py new file mode 100644 index 00000000000000..47e945fc45da18 --- /dev/null +++ b/selfdrive/speedsignd/detect_types.py @@ -0,0 +1,30 @@ +"""Shared MUTCD mph set and detection record. No I/O.""" +from __future__ import annotations + +from dataclasses import dataclass, replace + +# US R2-1 posted speeds. School-zone 15/25 and freeway 70/75/80 included. +MUTCD_MPH = frozenset(list(range(5, 90, 5)) + [100]) +# OCR may replace a class only with these. 100 stays a class label, not a +# digit-read override: a dropped digit must not become the plate. +US_POSTED_MPH = frozenset(range(5, 90, 5)) + + +@dataclass(frozen=True) +class SpeedSign: + mph: int + conf: float + bbox: tuple[int, int, int, int] # x, y, w, h in the input frame + # YOLO class vs crop digit-read. HUD mph may be the refine override. + class_mph: int | None = None + class_conf: float = 0.0 + alt_mph: int | None = None + alt_conf: float = 0.0 + refine_mph: int | None = None + refine_conf: float = 0.0 + + +def shift_sign(sign: SpeedSign, dx: int, dy: int) -> SpeedSign: + """Translate bbox; keep class/refine fields for logs.""" + x, y, w, h = sign.bbox + return replace(sign, bbox=(x + int(dx), y + int(dy), w, h)) diff --git a/selfdrive/speedsignd/export.py b/selfdrive/speedsignd/export.py new file mode 100644 index 00000000000000..3ed770a0d64a0f --- /dev/null +++ b/selfdrive/speedsignd/export.py @@ -0,0 +1,60 @@ +"""Export the US MUTCD YOLOv8 checkpoint to a compact ONNX (PC, once). + +Downloads the MIT YOLOv8s weights from HuggingFace and writes speed_sign.onnx. +Needs ultralytics + torch on the machine that runs this — not on the 3X. + + python -m scripts.nap.export_speed_sign_onnx --out /tmp/speed_sign.onnx + python -m scripts.nap.install_speed_sign_weights /tmp/speed_sign.onnx +""" +from __future__ import annotations + +import os +import shutil +import tempfile + +from openpilot.selfdrive.speedsignd.install import download_url, sha256_file, verify_sha256 +from openpilot.selfdrive.speedsignd.weights_manifest import ( + ASSET_SHA256, + HF_PT_SHA256, + YOLO_IMGSZ, + hf_pt_url, +) + + +def export_onnx( + out: str, + pt_url: str | None = None, + pt_sha256: str = HF_PT_SHA256, + imgsz: int = YOLO_IMGSZ, +) -> str: + try: + from ultralytics import YOLO + except ImportError as e: + raise RuntimeError( + "export_speed_sign_onnx needs ultralytics (and torch) on this machine:\n" + + " pip install ultralytics onnx\n" + + "The comma 3X does not run this — export on a PC, then install the ONNX." + ) from e + + parent = os.path.dirname(os.path.abspath(out)) or "." + os.makedirs(parent, exist_ok=True) + work = tempfile.mkdtemp(prefix="nap-speed-sign-export-") + try: + pt = os.path.join(work, "best.pt") + download_url(pt_url or hf_pt_url(), pt) + if pt_sha256: + verify_sha256(pt, pt_sha256) + model = YOLO(pt) + exported = model.export(format="onnx", imgsz=imgsz, simplify=True, dynamic=False, opset=12, nms=False) + exported = str(exported) + shutil.copy2(exported, out) + finally: + shutil.rmtree(work, ignore_errors=True) + return out + + +def export_and_report(out: str) -> tuple[str, str, bool]: + path = export_onnx(out) + digest = sha256_file(path) + matches = digest.lower() == ASSET_SHA256.lower() + return path, digest, matches diff --git a/selfdrive/speedsignd/hud.py b/selfdrive/speedsignd/hud.py new file mode 100644 index 00000000000000..0b5ddaa0ad624d --- /dev/null +++ b/selfdrive/speedsignd/hud.py @@ -0,0 +1,554 @@ +"""Live HUD hold for the camera speed-sign readout. + +Display-only. Does not write sqlite or change cruise. +""" +from __future__ import annotations + +from dataclasses import dataclass, field + +from openpilot.selfdrive.speedsignd.detect_types import MUTCD_MPH, US_POSTED_MPH, SpeedSign +from openpilot.selfdrive.speedsignd.weights_manifest import YOLO_MIN_CONF +from openpilot.selfdrive.speedsignd.yolo import REFINE_OVERRIDE_CONF + +# Hold a recent *accepted* mph across 1 Hz skip-on-overrun. Justin's parked +# 50 went blank after 10 s while tinygrad infer stayed 3–5 s / intermittent, +# then flashed 60 / 70 / 40. 45 s plus a soft refresh on any in-threshold +# speedLimit* box (even refine fail / junk class) keeps SIGN lit without +# inventing an mph. +HUD_HOLD_S = 45.0 +# Two reads of the same mph from different frames. A class/OCR pair on one +# frame is a single vote. v8n duty gap is about 4–16 s; 12 s covers two +# reads when infer is up to ~3 s. +AGREE_READS = 2 +AGREE_WINDOW_S = 12.0 +# One real posted limit at this confidence lights the plate. Route 00000181 +# had 45@0.77, 30@0.75, 45@0.89, and 30@0.81 with no second read inside 12 s. +# 0.60 still needs the second read. A different limit within 3 s clears it. +SOLO_CONF = 0.70 +SOLO_CONTRADICT_S = 3.0 +HUD_LABEL = "SIGN" +# Logger On + ONNX missing: show this instead of a blank plate or a fake mph. +HUD_MISSING_WEIGHTS_TEXT = "NO WT" +# Weights are on disk but the CPU runtime is not. Install weights also +# installs it. NO WT still wins when the ONNX itself is missing. +HUD_RUNTIME_MISSING_TEXT = "NO RT" +# WAIT plate if detectPaused is set. Engaged driving does not set it — +# the mph hold stays up. Cereal-unknown is not WAIT. +HUD_DETECT_PAUSED_TEXT = "WAIT" +HUD_CONFIRM_PROMPT = "accurate?" +HUD_CONFIRM_YES = "Yes" +HUD_CONFIRM_NO = "No" + +# TICI 2160x1080 — driver-left, below the MAX box (hud_renderer UI_CONFIG). +TICI_SIGN_W = 200 +TICI_SIGN_H = 248 +TICI_SIGN_LEFT = 60 +TICI_MAX_TOP = 45 +TICI_MAX_H = 204 +TICI_BELOW_MAX_GAP = 16 +TICI_CONFIRM_BTN_H = 112 +TICI_CONFIRM_GAP = 10 +TICI_CONFIRM_PROMPT_H = 32 + +# Mici 536x240 — same left / driver-side idea. +MICI_SIGN_W = 108 +MICI_SIGN_H = 128 +MICI_SIGN_LEFT = 8 +MICI_SIGN_TOP = 6 +MICI_CONFIRM_BTN_W = 68 +MICI_CONFIRM_GAP = 6 + + +def plate_digit_size(text: str, default: int) -> int: + """Shrink 'NO WT' so it fits the mph plate; keep 2–3 digit mph large.""" + if len(text) > 3: + return max(22, int(default * 0.42)) + return default + + +def hud_should_show(enabled: bool, valid: bool, mph: int) -> bool: + return bool(enabled) and bool(valid) and int(mph) > 0 + + +def hud_should_show_missing_weights(enabled: bool, weights_missing: bool) -> bool: + return bool(enabled) and bool(weights_missing) + + +def hud_should_show_detect_paused(enabled: bool, detect_paused: bool, weights_missing: bool = False) -> bool: + """WAIT only when detect is paused because OP is controlling — never for unknown cereal.""" + return bool(enabled) and bool(detect_paused) and not bool(weights_missing) + + +def hud_confirm_visible(view: LiveSignView | None = None, *, show_mph: bool = False, mph: int = 0, + show_missing_weights: bool = False, show_detect_paused: bool = False, + show_runtime_missing: bool = False) -> bool: + """Yes/No accuracy overlay: only when a real mph is on the plate, never for NO WT / NO RT / WAIT.""" + if view is not None: + show_mph = view.show_mph + mph = view.mph + show_missing_weights = view.show_missing_weights + show_detect_paused = view.show_detect_paused + show_runtime_missing = view.show_runtime_missing + return ( + bool(show_mph) and int(mph) > 0 + and not bool(show_missing_weights) and not bool(show_detect_paused) + and not bool(show_runtime_missing) + ) + + +def tici_sign_origin(rect_x: float = 0.0, rect_y: float = 0.0) -> tuple[float, float]: + """Left / driver side, below MAX so the plate does not cover MAX or the center path.""" + return rect_x + TICI_SIGN_LEFT, rect_y + TICI_MAX_TOP + TICI_MAX_H + TICI_BELOW_MAX_GAP + + +def mici_sign_origin(rect_x: float = 0.0, rect_y: float = 0.0) -> tuple[float, float]: + return rect_x + MICI_SIGN_LEFT, rect_y + MICI_SIGN_TOP + + +def accuracy_button_rects( + sign_x: float, + sign_y: float, + sign_w: float, + sign_h: float, + *, + beside: bool = False, + btn_w: float | None = None, + btn_h: float = TICI_CONFIRM_BTN_H, + gap: float = TICI_CONFIRM_GAP, + prompt_h: float = 0.0, +) -> tuple[tuple[float, float, float, float], tuple[float, float, float, float]]: + """Return (yes, no) as (x, y, w, h). TICI stacks under the plate; mici sits beside.""" + if beside: + w = MICI_CONFIRM_BTN_W if btn_w is None else btn_w + h = (sign_h - gap) / 2.0 + yes = (sign_x + sign_w + gap, sign_y, w, h) + no = (sign_x + sign_w + gap, sign_y + h + gap, w, h) + return yes, no + y0 = sign_y + sign_h + gap + prompt_h + yes = (sign_x, y0, sign_w, btn_h) + no = (sign_x, y0 + btn_h + gap, sign_w, btn_h) + return yes, no + + +def point_in_rect(px: float, py: float, r: tuple[float, float, float, float]) -> bool: + x, y, w, h = r + return x <= px <= x + w and y <= py <= y + h + + +def hit_accuracy_button( + px: float, + py: float, + yes: tuple[float, float, float, float], + no: tuple[float, float, float, float], +) -> bool | None: + """True = Yes, False = No, None = miss.""" + if point_in_rect(px, py, yes): + return True + if point_in_rect(px, py, no): + return False + return None + + +@dataclass(frozen=True) +class LiveSignView: + show_mph: bool = False + mph: int = 0 + show_missing_weights: bool = False + show_detect_paused: bool = False + show_runtime_missing: bool = False + + @property + def show(self) -> bool: + return self.show_mph or self.show_missing_weights or self.show_detect_paused or self.show_runtime_missing + + @property + def plate_text(self) -> str: + if self.show_missing_weights: + return HUD_MISSING_WEIGHTS_TEXT + if self.show_runtime_missing: + return HUD_RUNTIME_MISSING_TEXT + if self.show_detect_paused: + return HUD_DETECT_PAUSED_TEXT + if self.show_mph: + return str(int(self.mph)) + return "" + + @property + def confirm_visible(self) -> bool: + return hud_confirm_visible(self) + + +def live_sign_from_event(enabled: bool, d, msg_valid: bool) -> LiveSignView: + """Parse a liveSpeedSignNAP-like object for the on-road plate.""" + weights_missing = bool(getattr(d, "weightsMissing", False)) + detect_paused = bool(getattr(d, "detectPaused", False)) + return live_sign_view( + enabled=bool(enabled), + msg_valid=bool(msg_valid) or weights_missing or detect_paused, + mph=int(getattr(d, "mph", 0) or 0), + valid=bool(getattr(d, "valid", False)), + weights_missing=weights_missing, + detect_paused=detect_paused, + ) + + +def live_sign_view( + *, + enabled: bool, + msg_valid: bool, + mph: int, + valid: bool, + weights_missing: bool = False, + detect_paused: bool = False, + runtime_missing: bool = False, +) -> LiveSignView: + """What the on-road SIGN plate should show. No false mph when weights are missing. + + runtime_missing is a disk check (the CPU wheel), not a cereal field. + NO WT wins over NO RT. NO RT wins over a tinygrad mph. + """ + if not enabled: + return LiveSignView() + if hud_should_show_missing_weights(True, weights_missing): + return LiveSignView(show_missing_weights=True) + if runtime_missing: + return LiveSignView(show_runtime_missing=True) + if hud_should_show_detect_paused(True, detect_paused, weights_missing): + return LiveSignView(show_detect_paused=True) + if not msg_valid: + return LiveSignView() + if hud_should_show(True, valid, mph): + return LiveSignView(show_mph=True, mph=int(mph)) + return LiveSignView() + + +def apply_runtime_plate(view: LiveSignView, *, runtime_missing: bool) -> LiveSignView: + """Overlay NO RT from disk. Missing weights stay NO WT.""" + if view.show_missing_weights or not runtime_missing: + return view + return LiveSignView(show_runtime_missing=True) + + +def apply_live_sign( + dst, *, mph: int, conf: float, valid: bool, + weights_missing: bool = False, detect_paused: bool = False, +) -> None: + dst.mph = int(mph) if valid else 0 + dst.conf = float(conf) if valid else 0.0 + dst.valid = bool(valid) + dst.weightsMissing = bool(weights_missing) + dst.detectPaused = bool(detect_paused) + + +def _class_mph(sign: SpeedSign) -> int: + class_mph = getattr(sign, "class_mph", None) + if class_mph is not None: + return int(class_mph) + return int(sign.mph) + + +def should_replace_held_mph( + held_mph: int, held_conf: float, new_mph: int, new_conf: float, + refine_mph: int | None = None, +) -> bool: + """Same mph refreshes. A different agreed mph replaces when it is at least as sure.""" + del refine_mph + if int(held_mph) <= 0: + return True + if int(new_mph) == int(held_mph): + return True + return float(new_conf) >= float(held_conf) + + +def is_speed_limit_sighting(sign: SpeedSign | None) -> bool: + """True if YOLO posted any in-threshold speedLimit* (refine may have failed). + + Used only to extend a live hold — never to invent or change mph. + """ + if sign is None: + return False + try: + conf = float(sign.conf) + except (TypeError, ValueError): + return False + if conf < YOLO_MIN_CONF: + return False + refine = getattr(sign, "refine_mph", None) + if refine is not None: + try: + if int(refine) in MUTCD_MPH: + return True + except (TypeError, ValueError): + pass + try: + if int(sign.mph) in MUTCD_MPH: + return True + except (TypeError, ValueError): + pass + try: + return _class_mph(sign) in MUTCD_MPH + except (TypeError, ValueError): + return False + + +def frame_reads(sign: SpeedSign | None) -> tuple[list[tuple[int, float]], tuple[int, float] | None]: + """At most one vote from one frame. The second return is always None. + + v2 misreads are systematic (60 read as 30, 30 read as 50, 30/35/60 as + 50). A same-frame class+OCR pair used to light the HUD immediately, so a + wrong class that OCR repeated became a 45 s plate. + + - class and OCR name the same mph: one vote. A later frame must agree. + - class and OCR differ, both above their floors: no vote. A correct OCR + beside a wrong class is a miss, not a misread. + - class only: no vote. That is how route 17a posted 60 as 30. + LiveSignHold may still light one class-only read at SOLO_CONF. + - OCR only (second look, or refine with no in-threshold class): one vote. + - bare mph with neither field set (numpy tests): one vote. + sl_unreadable and neg_* have no MUTCD mph here, so they never vote. + """ + if sign is None: + return [], None + explicit_class = getattr(sign, "class_mph", None) + class_conf = float(getattr(sign, "class_conf", 0.0) or 0.0) + refine = getattr(sign, "refine_mph", None) + refine_conf = float(getattr(sign, "refine_conf", 0.0) or 0.0) + class_i = None + class_ok = False + if explicit_class is not None: + try: + class_i = int(explicit_class) + class_ok = class_i in MUTCD_MPH and class_conf >= YOLO_MIN_CONF + except (TypeError, ValueError): + class_i = None + refine_i = None + refine_ok = False + if refine is not None: + try: + refine_i = int(refine) + refine_ok = refine_i in MUTCD_MPH and refine_conf >= REFINE_OVERRIDE_CONF + except (TypeError, ValueError): + refine_i = None + if class_ok and refine_ok and class_i != refine_i: + return [], None + if class_ok and refine_ok and class_i == refine_i: + return [(int(class_i), max(class_conf, refine_conf))], None + if refine_ok and not class_ok: + return [(int(refine_i), refine_conf)], None + if class_ok: + return [], None + if explicit_class is None and refine is None: + try: + mph = int(sign.mph) + conf = float(sign.conf) + except (TypeError, ValueError): + return [], None + if mph in MUTCD_MPH and conf >= YOLO_MIN_CONF: + return [(mph, conf)], None + return [], None + + +def note_read(obs: list, now: float, mph: int, conf: float, extra=None) -> None: + """Record one vote. The same timestamp and mph is the same frame, not a second read.""" + mph = int(mph) + conf = float(conf) + for i, row in enumerate(obs): + if row[0] == now and int(row[1]) == mph: + if conf > float(row[2]): + obs[i] = (now, mph, conf) if extra is None else (now, mph, conf, extra) + return + obs.append((now, mph, conf) if extra is None else (now, mph, conf, extra)) + + +def posted_reads(sign: SpeedSign | None) -> list[tuple[int, float]]: + """Posted limits at the detect floor, including a class-only hit. + + Used to cancel a provisional solo. Below YOLO_MIN_CONF is not a read. + """ + if sign is None: + return [] + out: list[tuple[int, float]] = [] + pending, _pair = frame_reads(sign) + for mph, conf in pending: + if int(mph) in US_POSTED_MPH: + out.append((int(mph), float(conf))) + explicit = getattr(sign, "class_mph", None) + if explicit is None: + return out + try: + class_i = int(explicit) + class_conf = float(getattr(sign, "class_conf", 0.0) or 0.0) + except (TypeError, ValueError): + return out + if class_i in US_POSTED_MPH and class_conf >= YOLO_MIN_CONF: + if not any(mph == class_i for mph, _conf in out): + out.append((class_i, class_conf)) + return out + + +def solo_candidate(sign: SpeedSign | None) -> tuple[int, float] | None: + """One real posted limit at ≥ SOLO_CONF. A class/OCR clash is not one. + + Class-only counts here even though frame_reads does not vote it. That is + how a lone 45@0.89 lights the plate. 0.60 does not. JSONL still needs + two frame_reads votes. + """ + if sign is None: + return None + pending, _pair = frame_reads(sign) + if pending: + mph, conf = int(pending[0][0]), float(pending[0][1]) + if mph in US_POSTED_MPH and conf >= SOLO_CONF: + return mph, conf + return None + explicit = getattr(sign, "class_mph", None) + if explicit is None: + return None + refine = getattr(sign, "refine_mph", None) + if refine is not None: + try: + if int(refine) in US_POSTED_MPH: + return None + except (TypeError, ValueError): + pass + try: + class_i = int(explicit) + class_conf = float(getattr(sign, "class_conf", 0.0) or 0.0) + except (TypeError, ValueError): + return None + if class_i in US_POSTED_MPH and class_conf >= SOLO_CONF: + return class_i, class_conf + return None + + +def accepted_hud_sign(sign: SpeedSign | None) -> SpeedSign | None: + """One frame never lights the HUD, even when class and OCR agree. + + 40/60/65/70 are not special-cased. Callers that used to treat a returned + sign as an immediate plate must wait for LiveSignHold. + """ + del sign + return None + + +@dataclass +class LiveSignHold: + hold_s: float = HUD_HOLD_S + mph: int = 0 + conf: float = 0.0 + until: float = 0.0 + provisional: bool = False + provisional_until: float = 0.0 + _obs: list = field(default_factory=list) + + def _clear(self) -> None: + self.mph = 0 + self.conf = 0.0 + self.until = 0.0 + self.provisional = False + self.provisional_until = 0.0 + + def update(self, signs, now: float) -> tuple[bool, int, float]: + fresh_mphs: set[int] = set() + solos: list[tuple[int, float]] = [] + seen: list[tuple[int, float]] = [] + for s in signs or []: + pending, _pair = frame_reads(s) + for mph, conf in pending: + note_read(self._obs, now, int(mph), float(conf)) + fresh_mphs.add(int(mph)) + seen.extend(posted_reads(s)) + solo = solo_candidate(s) + if solo is not None: + solos.append(solo) + self._obs = [o for o in self._obs if now - o[0] <= AGREE_WINDOW_S] + buckets: dict[int, list[float]] = {} + for _t, mph, conf in self._obs: + buckets.setdefault(int(mph), []).append(float(conf)) + winners = [(mph, max(cs)) for mph, cs in buckets.items() if len(cs) >= AGREE_READS] + # An older mph that still has two votes must not light again just because + # this frame voted for something else. Only a mph read this call can. + fresh_winners = [item for item in winners if item[0] in fresh_mphs] + holding = now < self.until and self.mph > 0 + cancelled: int | None = None + if self.provisional and holding and now <= self.provisional_until: + if any(mph != self.mph for mph, _conf in seen): + cancelled = self.mph + self._clear() + holding = False + elif seen: + # A second read of the same limit locks the 45 s hold. + self.provisional = False + self.until = now + self.hold_s + if self.provisional and now > self.provisional_until: + self.provisional = False + if fresh_winners: + new_mph, new_conf = max(fresh_winners, key=lambda item: item[1]) + if (not holding) or should_replace_held_mph(self.mph, self.conf, new_mph, new_conf): + self.mph = int(new_mph) + self.conf = float(new_conf) + self.until = now + self.hold_s + else: + self.until = now + self.hold_s + self.provisional = False + elif not holding and solos: + # A locked hold is not replaced by one class-only read. An empty plate is. + choices = [item for item in solos if item[0] != cancelled] + if choices: + new_mph, new_conf = max(choices, key=lambda item: item[1]) + self.mph = int(new_mph) + self.conf = float(new_conf) + self.until = now + self.hold_s + self.provisional = True + self.provisional_until = now + SOLO_CONTRADICT_S + elif holding and any(is_speed_limit_sighting(s) for s in (signs or [])): + self.until = now + self.hold_s + live = now < self.until and self.mph > 0 + if not live: + return False, 0, 0.0 + return True, self.mph, self.conf + + +# After a Yes/No tap: hide the popup at once and do not re-ask the same mph +# shortly after (no track id on the wire; the same mph within the window, or +# while that mph stays live, is treated as the same sign). A Yes value moves +# to the regular speed-limit sign via mapd, not this popup. +REASK_SUPPRESS_S = 60.0 + + +class AnswerGate: + def __init__(self) -> None: + self.mph: int = 0 + self.t: float = -1e9 + + def answer(self, mph: int, yes: bool, now: float) -> None: + self.mph, self.t = int(mph), float(now) + + def filter(self, view: LiveSignView, now: float) -> LiveSignView: + if view.show_missing_weights or view.show_runtime_missing or view.show_detect_paused: + return view + if self.mph <= 0: + return view + live = int(view.mph) if view.show_mph else 0 + if live and live != self.mph: + return view + if live == self.mph or now - self.t <= REASK_SUPPRESS_S: + return LiveSignView() + self.mph = 0 + return view + + +def point_in_confirm_buttons(x: float, y: float, view: LiveSignView | None, + yes: tuple[float, float, float, float], + no: tuple[float, float, float, float]) -> bool: + """True only while the Yes/No popup is shown and (x, y) is inside a button. + + The onroad view uses this to skip its sidebar toggle for that press; any + other touch (or any touch while the popup is hidden) is left to onroad. + """ + if view is None or not hud_confirm_visible(view): + return False + for bx, by, bw, bh in (yes, no): + if bw > 0 and bh > 0 and bx <= x <= bx + bw and by <= y <= by + bh: + return True + return False diff --git a/selfdrive/speedsignd/install.py b/selfdrive/speedsignd/install.py new file mode 100644 index 00000000000000..81537dc37acae0 --- /dev/null +++ b/selfdrive/speedsignd/install.py @@ -0,0 +1,516 @@ +"""Install the compact speed-sign ONNX onto /data. No osm.org, no sqlite. + +The same offroad action installs a pinned aarch64 CPU onnxruntime wheel +into /data/media/0/nap/pylib. That directory is added to sys.path only +when the system import fails and the machine is aarch64. The system +venv is not modified. +""" +from __future__ import annotations + +import hashlib +import os +import platform +import shutil +import subprocess +import sys +import time +import urllib.error +import urllib.request +import zipfile +from urllib.parse import unquote, urlparse + +from openpilot.selfdrive.speedsignd.paths import default_onnx_path, default_pylib_dir +from openpilot.selfdrive.speedsignd.weights_manifest import ( + ASSET_SHA256, + COMPATIBLE_SHA256, + FALLBACK_RELEASE_TAG, + FALLBACK_SHA256, + ORT_SHA256, + ORT_URL, + ORT_VERSION, + USER_AGENT, + release_asset_url, +) + +CHUNK = 256 * 1024 +# v2 asset is ~12 MB. v1 was ~43 MB. Reject empty / leftover .partial files. +# A large file with the wrong sha is "Out of date", not Installed — the v1 +# weights must be replaced, not decoded with the v2 class map. +MIN_ONNX_BYTES = 1_000_000 + + +def weights_present(path: str | None = None) -> bool: + path = path or default_onnx_path() + try: + return os.path.isfile(path) and os.path.getsize(path) >= MIN_ONNX_BYTES + except OSError: + return False + + +def weights_sha_matches(path: str | None = None, expected: str | None = None) -> bool: + """True only when the file is large enough and matches the published sha.""" + path = path or default_onnx_path() + expected = ASSET_SHA256 if expected is None else expected + if not expected or not weights_present(path): + return False + try: + return sha256_file(path).lower() == expected.lower() + except OSError: + return False + + +def weights_loadable(path: str | None = None) -> bool: + """True for any published sha with the current class map (v3, or v2 fallback).""" + path = path or default_onnx_path() + if not weights_present(path): + return False + try: + return sha256_file(path).lower() in {h.lower() for h in COMPATIBLE_SHA256} + except OSError: + return False + + +def weights_status_summary(path: str | None = None) -> str: + """Settings label: Installed, Out of date, or Missing.""" + path = path or default_onnx_path() + if not weights_present(path): + return "Missing" + if not weights_sha_matches(path): + return "Out of date" + try: + sz = os.path.getsize(path) + except OSError: + return "Missing" + mb = sz / (1024 * 1024) + return f"Installed ({mb:.0f} MB)" + + +def sha256_file(path: str) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + while True: + chunk = f.read(1024 * 1024) + if not chunk: + break + h.update(chunk) + return h.hexdigest() + + +def verify_sha256(path: str, expected: str) -> None: + got = sha256_file(path) + if got.lower() != expected.lower(): + raise RuntimeError(f"SHA-256 mismatch for {path}: got {got}, expected {expected}") + + +def install_weights(src: str, dest: str | None = None, sha256: str | None = None) -> str: + if not os.path.isfile(src): + raise FileNotFoundError(f"ONNX not found: {src}") + dest = dest or default_onnx_path() + parent = os.path.dirname(dest) + if parent: + os.makedirs(parent, exist_ok=True) + if sha256: + verify_sha256(src, sha256) + shutil.copy2(src, dest) + return dest + + +def download_url(url: str, dest: str) -> int: + if url.startswith("file:"): + path = unquote(urlparse(url).path) + os.makedirs(os.path.dirname(dest) or ".", exist_ok=True) + shutil.copy2(path, dest) + return os.path.getsize(dest) + req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + try: + resp_cm = urllib.request.urlopen(req, timeout=60) + except urllib.error.HTTPError as e: + raise RuntimeError( + f"Download failed HTTP {e.code} for {url}. " + + "Publish speed_sign.onnx as a GitHub Release asset, or export locally " + + "(python -m scripts.nap.export_speed_sign_onnx) and pass the file." + ) from e + except urllib.error.URLError as e: + raise RuntimeError(f"Download failed: {e}. Need Wi-Fi, or pass a local .onnx.") from e + + os.makedirs(os.path.dirname(dest) or ".", exist_ok=True) + tmp = dest + ".partial" + n = 0 + try: + with resp_cm as resp, open(tmp, "wb") as f: + while True: + chunk = resp.read(CHUNK) + if not chunk: + break + f.write(chunk) + n += len(chunk) + os.replace(tmp, dest) + except Exception: + try: + if os.path.isfile(tmp): + os.remove(tmp) + except OSError: + pass + raise + return n + + +def fetch_and_install( + dest: str | None = None, + url: str | None = None, + sha256: str | None = ASSET_SHA256, +) -> str: + """Download the published ONNX (checksum) onto dest.""" + dest = dest or default_onnx_path() + default_src = url is None and not os.environ.get("NAP_SPEED_SIGN_ONNX_URL") and sha256 == ASSET_SHA256 + url = url or os.environ.get("NAP_SPEED_SIGN_ONNX_URL") or release_asset_url() + try: + return _fetch_verify(dest, url, sha256) + except Exception: + if not default_src: + raise + # v3 asset unreachable or bad: fall back to the class-compatible v2 asset. + return _fetch_verify(dest, release_asset_url(tag=FALLBACK_RELEASE_TAG), FALLBACK_SHA256) + + +def _fetch_verify(dest: str, url: str, sha256: str | None) -> str: + parent = os.path.dirname(os.path.abspath(dest)) or "." + os.makedirs(parent, exist_ok=True) + tmp = dest + ".download" + try: + download_url(url, tmp) + if sha256: + verify_sha256(tmp, sha256) + os.replace(tmp, dest) + except Exception: + try: + if os.path.isfile(tmp): + os.remove(tmp) + except OSError: + pass + raise + return dest + + +def fetch_and_install_proposer(dest: str | None = None, url: str | None = None, + sha256: str | None = None) -> str: + """Download the two-stage strip proposer ONNX (checksum) next to speed_sign.onnx.""" + from openpilot.selfdrive.speedsignd.paths import default_proposer_path + from openpilot.selfdrive.speedsignd.weights_manifest import PROPOSER_SHA256, proposer_asset_url + return fetch_and_install( + dest=dest or default_proposer_path(), + url=url or os.environ.get("NAP_SPEED_SIGN_PROPOSER_URL") or proposer_asset_url(), + sha256=PROPOSER_SHA256 if sha256 is None else (sha256 or None), + ) + + +RUNTIME_STAMP = "onnxruntime.stamp" +_AARCH64 = ("aarch64", "arm64") +_status_cache: dict[str, float | str] = {"t": 0.0, "s": ""} + + +def host_is_aarch64(machine: str | None = None) -> bool: + name = platform.machine() if machine is None else machine + return name.lower() in _AARCH64 + + +def runtime_stamp_path(pylib: str | None = None) -> str: + return os.path.join(pylib or default_pylib_dir(), RUNTIME_STAMP) + + +def clear_runtime_status_cache() -> None: + _status_cache["t"] = 0.0 + _status_cache["s"] = "" + + +def vendored_runtime_ready(pylib: str | None = None, expected_sha: str | None = None) -> bool: + """True when pylib has the onnxruntime package and a matching stamp.""" + pylib = pylib or default_pylib_dir() + expected = ORT_SHA256 if expected_sha is None else expected_sha + init = os.path.join(pylib, "onnxruntime", "__init__.py") + stamp = runtime_stamp_path(pylib) + if not expected or not os.path.isfile(init) or not os.path.isfile(stamp): + return False + try: + with open(stamp, encoding="utf-8") as f: + text = f.read() + except OSError: + return False + return expected.lower() in text.lower() + + +def _discard_path(path: str) -> None: + if not os.path.lexists(path): + return + if os.path.islink(path) or os.path.isfile(path): + os.remove(path) + return + shutil.rmtree(path) + + +def _wheel_plan(zf: zipfile.ZipFile) -> list[tuple[str, bool, zipfile.ZipInfo]]: + """onnxruntime package and its dist-info. Dirs stay dirs. + + A directory entry in the wheel is `onnxruntime/` (trailing slash). + Stripping that slash makes ZipInfo.is_dir() false, and extractall then + writes a file named `onnxruntime`. The next member, + `onnxruntime/LICENSE`, fails with ENOTDIR because its parent is a file. + """ + out: list[tuple[str, bool, zipfile.ZipInfo]] = [] + for info in zf.infolist(): + raw = info.filename.replace("\\", "/") + is_dir = raw.endswith("/") + if raw.startswith(("/", "../")) or "/../" in raw: + raise RuntimeError("wheel path rejected: " + info.filename) + parts: list[str] = [] + for part in raw.split("/"): + if part in ("", "."): + continue + if part == "..": + raise RuntimeError("wheel path rejected: " + info.filename) + parts.append(part) + if not parts: + continue + top = parts[0] + pkg = top == "onnxruntime" + dist = top.startswith("onnxruntime-") and top.endswith(".dist-info") + if not (pkg or dist): + continue + out.append(("/".join(parts), is_dir, info)) + files = {rel for rel, is_dir, _info in out if not is_dir} + dirs = {rel for rel, is_dir, _info in out if is_dir} + both = files & dirs + if both: + raise RuntimeError("wheel entry is both a file and a directory: " + sorted(both)[0]) + for rel in files: + parent = rel + while "/" in parent: + parent = parent.rsplit("/", 1)[0] + if parent in files: + raise RuntimeError("wheel file is used as a directory: " + parent) + return out + + +def _extract_wheel_plan(zf: zipfile.ZipFile, dest: str, plan: list[tuple[str, bool, zipfile.ZipInfo]]) -> None: + """Write dirs with makedirs and files with open. Never extractall.""" + ordered = sorted(plan, key=lambda item: (not item[1], item[0].count("/"), item[0])) + for rel, is_dir, info in ordered: + target = os.path.join(dest, *rel.split("/")) + if is_dir: + if os.path.isfile(target): + raise RuntimeError("wheel directory collides with a file: " + rel) + os.makedirs(target, exist_ok=True) + continue + parent = os.path.dirname(target) + if parent: + if os.path.isfile(parent): + raise RuntimeError("wheel parent is a file: " + rel) + os.makedirs(parent, exist_ok=True) + if os.path.isdir(target): + raise RuntimeError("wheel file collides with a directory: " + rel) + with zf.open(info, "r") as src, open(target, "wb") as out: + shutil.copyfileobj(src, out) + + +def import_vendored_runtime(pylib: str) -> str: + """Import onnxruntime from pylib in a fresh interpreter. Returns __file__.""" + code = ( + "import sys\n" + + "sys.path.insert(0, sys.argv[1])\n" + + "import onnxruntime\n" + + "print(onnxruntime.__file__)\n" + ) + proc = subprocess.run( + [sys.executable, "-c", code, pylib], + capture_output=True, text=True, timeout=120, cwd=os.sep, check=False, + ) + if proc.returncode != 0: + err = (proc.stderr or proc.stdout or "").strip() + raise RuntimeError("import onnxruntime failed: " + err) + lines = [line for line in (proc.stdout or "").splitlines() if line.strip()] + if not lines: + raise RuntimeError("import onnxruntime printed no path") + loaded = lines[-1].strip() + if os.path.abspath(pylib) not in os.path.abspath(loaded): + raise RuntimeError("import onnxruntime loaded " + loaded + ", not " + pylib) + return loaded + + +def install_runtime_wheel( + wheel: str, + pylib: str | None = None, + sha256: str | None = ORT_SHA256, + version: str = ORT_VERSION, +) -> str: + """Unzip a wheel into pylib. Does not call pip and does not touch the venv. + + Extract into a sibling temp dir, delete any partial pylib, then rename. + On aarch64, import must succeed or the pylib is removed. + """ + if not os.path.isfile(wheel): + raise FileNotFoundError("runtime wheel not found: " + wheel) + if sha256: + verify_sha256(wheel, sha256) + pylib = os.path.abspath(pylib or default_pylib_dir()) + parent = os.path.dirname(pylib) or "." + os.makedirs(parent, exist_ok=True) + staging = pylib + ".partial" + _discard_path(staging) + os.makedirs(staging) + try: + with zipfile.ZipFile(wheel) as zf: + plan = _wheel_plan(zf) + if not any(rel == "onnxruntime" or rel.startswith("onnxruntime/") for rel, _is_dir, _info in plan): + raise RuntimeError("wheel has no onnxruntime package: " + wheel) + _extract_wheel_plan(zf, staging, plan) + init = os.path.join(staging, "onnxruntime", "__init__.py") + if not os.path.isfile(init): + raise RuntimeError("wheel extract missed onnxruntime/__init__.py") + license_path = os.path.join(staging, "onnxruntime", "LICENSE") + if os.path.isdir(license_path): + raise RuntimeError("onnxruntime/LICENSE extracted as a directory") + stamp = os.path.join(staging, RUNTIME_STAMP) + body = "onnxruntime " + version + "\n" + (sha256 or "") + "\n" + "pylib\n" + tmp = stamp + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + f.write(body) + os.replace(tmp, stamp) + _discard_path(pylib) + os.rename(staging, pylib) + except Exception: + _discard_path(staging) + raise + if host_is_aarch64(): + try: + import_vendored_runtime(pylib) + except Exception: + _discard_path(pylib) + raise + clear_runtime_status_cache() + return pylib + + +def fetch_and_install_runtime( + pylib: str | None = None, + url: str | None = None, + sha256: str | None = ORT_SHA256, +) -> str: + """Download the pinned CPU wheel and unzip it under pylib. + + A matching stamp skips the download. The system venv is not modified. + """ + pylib = pylib or default_pylib_dir() + if sha256 and vendored_runtime_ready(pylib, expected_sha=sha256): + return pylib + url = url or os.environ.get("NAP_SPEED_SIGN_RUNTIME_URL") or ORT_URL + parent = os.path.dirname(os.path.abspath(pylib)) or "." + os.makedirs(parent, exist_ok=True) + # Beside pylib, not inside it. install_runtime_wheel deletes a partial pylib. + wheel = os.path.abspath(pylib) + ".whl.download" + try: + download_url(url, wheel) + return install_runtime_wheel(wheel, pylib, sha256=sha256) + finally: + try: + if os.path.isfile(wheel): + os.remove(wheel) + except OSError: + pass + + +def system_ort_importable() -> bool: + """True when onnxruntime imports without the vendored pylib on sys.path.""" + try: + import onnxruntime # noqa: F401 + return True + except Exception: + return False + + +def cv2_dnn_importable() -> bool: + try: + import cv2 + except Exception: + return False + dnn = getattr(cv2, "dnn", None) + return dnn is not None and hasattr(dnn, "readNetFromONNX") + + +def vendored_sys_path(machine: str, pylib: str, system_ok: bool) -> str | None: + """Directory to insert, or None. Never shadow a working system import. + + The wheel is aarch64. Putting it first on sys.path on x86 would hide + a working CPU wheel with an ELF the host cannot load. + """ + if system_ok: + return None + if not host_is_aarch64(machine): + return None + if not vendored_runtime_ready(pylib): + return None + return pylib + + +def ensure_vendored_runtime() -> bool: + """Import onnxruntime, using /data pylib only as the aarch64 fallback.""" + if system_ort_importable(): + return True + pylib = vendored_sys_path(platform.machine(), default_pylib_dir(), False) + if pylib is None: + return False + if pylib not in sys.path: + sys.path.insert(0, pylib) + return system_ort_importable() + + +def _runtime_status_uncached() -> str: + if ensure_vendored_runtime(): + try: + import onnxruntime as ort + ver = str(getattr(ort, "__version__", "") or ORT_VERSION) + except Exception: + ver = ORT_VERSION + return "runtime onnxruntime " + ver + if cv2_dnn_importable(): + return "runtime opencv-dnn" + return "runtime missing" + + +def runtime_status_summary() -> str: + """Settings/HUD label. 'runtime missing' until ORT or cv2.dnn can import.""" + now = time.monotonic() + cached = _status_cache.get("s") or "" + if cached and now - float(_status_cache.get("t") or 0.0) < 2.0: + return str(cached) + text = _runtime_status_uncached() + _status_cache["t"] = now + _status_cache["s"] = text + return text + + +def runtime_missing() -> bool: + return runtime_status_summary() == "runtime missing" + + +# Settings row value when neither onnxruntime nor cv2.dnn can import. +# runtime_status_summary stays the short token so HUD NO RT still matches it. +SETTINGS_RUNTIME_MISSING = "runtime missing — tap Install weights" + + +def install_status_summary(path: str | None = None) -> str: + """Weights label plus the runtime. Weights strings stay on their own helper.""" + runtime = runtime_status_summary() + if runtime == "runtime missing": + runtime = SETTINGS_RUNTIME_MISSING + return weights_status_summary(path) + " · " + runtime + + +def clang_fallback_warning(backend: str) -> str: + """Non-empty when this process will run tinygrad CLANG because ORT is absent.""" + if backend != "tinygrad-clang": + return "" + return ( + "speedsignd falling back to tinygrad-clang because onnxruntime is missing. " + + "Settings weights status: " + SETTINGS_RUNTIME_MISSING + ". " + + "CLANG will not run while engaged." + ) diff --git a/selfdrive/speedsignd/jsonl.py b/selfdrive/speedsignd/jsonl.py new file mode 100644 index 00000000000000..b2ddd13112ee87 --- /dev/null +++ b/selfdrive/speedsignd/jsonl.py @@ -0,0 +1,74 @@ +"""Append-only JSONL writer for speed-sign observations.""" +from __future__ import annotations + +import json +import math +import os +from dataclasses import dataclass +from typing import Any + +RECORD_KEYS = ("t", "lat", "lon", "bearing", "mph", "conf") + +# Skip a repeat of the same mph near the last write (even 1 Hz would spam). +DEDUP_COOLDOWN_S = 8.0 +DEDUP_RADIUS_M = 40.0 + + +def make_record(t: float, lat: float, lon: float, bearing: float | None, mph: int, conf: float) -> dict[str, Any]: + return { + "t": float(t), + "lat": float(lat), + "lon": float(lon), + "bearing": None if bearing is None else float(bearing), + "mph": int(mph), + "conf": float(conf), + } + + +def record_line(record: dict[str, Any]) -> str: + payload = {k: record[k] for k in RECORD_KEYS} + return json.dumps(payload, separators=(",", ":"), ensure_ascii=True) + "\n" + + +def append_jsonl(path: str, record: dict[str, Any]) -> None: + parent = os.path.dirname(path) + if parent: + os.makedirs(parent, exist_ok=True) + with open(path, "a", encoding="utf-8") as f: + f.write(record_line(record)) + f.flush() + + +def _haversine_m(lat1: float, lon1: float, lat2: float, lon2: float) -> float: + r = 6371000.0 + p1, p2 = math.radians(lat1), math.radians(lat2) + dp = math.radians(lat2 - lat1) + dl = math.radians(lon2 - lon1) + a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2 + return 2 * r * math.asin(min(1.0, math.sqrt(a))) + + +@dataclass +class JsonlLogger: + path: str + cooldown_s: float = DEDUP_COOLDOWN_S + radius_m: float = DEDUP_RADIUS_M + _last: tuple[float, float, float, int] | None = None # t, lat, lon, mph + + def accept(self, record: dict[str, Any]) -> bool: + t = float(record["t"]) + lat = float(record["lat"]) + lon = float(record["lon"]) + mph = int(record["mph"]) + if self._last is not None: + lt, llat, llon, lmph = self._last + if mph == lmph and (t - lt) < self.cooldown_s and _haversine_m(lat, lon, llat, llon) < self.radius_m: + return False + return True + + def write(self, record: dict[str, Any]) -> bool: + if not self.accept(record): + return False + append_jsonl(self.path, record) + self._last = (float(record["t"]), float(record["lat"]), float(record["lon"]), int(record["mph"])) + return True diff --git a/selfdrive/speedsignd/nv12.py b/selfdrive/speedsignd/nv12.py new file mode 100644 index 00000000000000..d442dc53ba0601 --- /dev/null +++ b/selfdrive/speedsignd/nv12.py @@ -0,0 +1,376 @@ +"""ROAD-camera NV12 helpers. Crop+letterbox RGB for YOLO; Y for the numpy fallback. + +On-car detect must not convert a full 1928×1208 ROAD frame to RGB. The YOLO +input is 320² of the right-biased short-side crop — convert that, after +downsample, not the whole VisionBuf. +""" +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + + +def nv12_uv_offset(buf, stride: int, height: int) -> int: + """UV plane start. 3X Venus NV12 is page-aligned; not always stride*height. + + camerad sets VisionBuf.uv_offset = stride * ALIGN(height, 32). Using + stride*visible_height reads the Y pad as chroma and color-shifts RGB + (white R2-1 → green/yellow) so YOLO never fires. + """ + raw = getattr(buf, "uv_offset", None) + try: + off = int(raw) if raw is not None else 0 + except (TypeError, ValueError): + off = 0 + if off > 0: + return off + return int(stride) * int(height) + + +def y_plane_from_nv12(buf, copy: bool = False) -> np.ndarray | None: + """Y plane of an NV12 VisionBuf, cropped to width x height (no padding). + + The default is a view into VisionBuf memory. Pass copy=True before handing + the plane to a background infer — the next recv can recycle the buffer. + """ + try: + width = int(buf.width) + height = int(buf.height) + stride = int(buf.stride) if getattr(buf, "stride", 0) else width + if width < 2 or height < 2 or stride < width: + return None + data = buf.data + n = stride * height + if data is None or len(data) < n: + return None + y = np.frombuffer(data, dtype=np.uint8, count=n).reshape(height, stride) + plane = y[:, :width] + return plane.copy() if copy else plane + except Exception: + return None + + +def rgb_from_nv12(buf) -> np.ndarray | None: + """BT.601 limited-range NV12 → RGB888. Falls back to luma-only if UV is short.""" + y = y_plane_from_nv12(buf) + if y is None: + return None + try: + height, width = y.shape + stride = int(buf.stride) if getattr(buf, "stride", 0) else width + data = buf.data + uv_off = nv12_uv_offset(buf, stride, height) + uv_rows = height // 2 + need = uv_off + stride * uv_rows + if data is None or len(data) < need: + return np.stack([y, y, y], axis=-1) + uv = np.frombuffer(data, dtype=np.uint8, count=stride * uv_rows, offset=uv_off) + uv = uv.reshape(uv_rows, stride)[:, :width] + u = uv[:, 0::2] + v = uv[:, 1::2] + u = np.repeat(np.repeat(u, 2, axis=0), 2, axis=1)[:height, :width] + v = np.repeat(np.repeat(v, 2, axis=0), 2, axis=1)[:height, :width] + yf = y.astype(np.float32) + uf = u.astype(np.float32) - 128.0 + vf = v.astype(np.float32) - 128.0 + r = yf + 1.402 * vf + g = yf - 0.344136 * uf - 0.714136 * vf + b = yf + 1.772 * uf + rgb = np.stack([r, g, b], axis=-1) + return np.clip(rgb, 0, 255).astype(np.uint8) + except Exception: + return np.stack([y, y, y], axis=-1) + + +def rgb_from_y(y: np.ndarray) -> np.ndarray: + """Replicate a uint8 Y plane to RGB (tests / missing chroma).""" + if y.ndim == 3 and y.shape[-1] == 3: + return y + return np.stack([y, y, y], axis=-1) + + +@dataclass +class Nv12DetectCrop: + """Copied right-biased ROAD crop. Small enough to hand to a background infer.""" + y: np.ndarray + uv: np.ndarray | None + frame_w: int + frame_h: int + crop: tuple[int, int, int, int] + + +def detect_crop_rect(h: int, w: int) -> tuple[int, int, int, int]: + """Legacy right-biased short-side square. The live path uses native_detect_window.""" + side = min(int(h), int(w)) + x = max(0, int(w) - side) + y = max(0, (int(h) - side) // 2) + return x, y, side, side + + +# 3X ROAD is 1928×1208. Route 0000017a put the real signs at about +# y=557–805, x=1110–1914 — lower and farther right than the old 320² tile +# at (1100, 325). This rect is the right-hand cluster: x 1300–1928, y 520–840. +# All four numbers are even so the NV12 chroma plane stays aligned. +# Letterbox into YOLO_IMGSZ (weights_manifest, 320 today) uses +# scale = min(imgsz/320, imgsz/628). At 320 that is 320/628 ≈ 0.510, so a +# sign ≥ 60 px tall in the frame stays ≥ 30 px in the model +# (60 * 320/628 ≈ 30.6). A 30-inch plate is ~67 px at 100 ft and ~83 px at +# 80 ft; x=1300 is about 80 ft on f = 8 mm / 3 µm, so plates inside this +# window are the closer ones. Farther signs (x<1300, ~44 px at 150 ft) stay +# outside on purpose. The constants do not depend on YOLO_IMGSZ, so a +# retrained YOLOv8n at 320 drops in through weights_manifest. +NATIVE_WINDOW_X = 1300 +NATIVE_WINDOW_Y = 520 +NATIVE_WINDOW_W = 628 +NATIVE_WINDOW_H = 320 +# Town routes put plates at y 340–795, x 968–1928. The lower tile starts at +# y=520, so y=340 is above it. This upper tile is y 260–580 (includes 340, +# overlaps the lower tile through y=580) and x 1288–1928 (the right cluster, +# still inside the 1928-wide frame). All four numbers are even for NV12. +# A third tile over x 960–1300 is not used: two tiles already spend the 25% +# budget, and at a 627 ms infer a third tile would see each band ~7.5 s apart. +NATIVE_UPPER_X = 1288 +NATIVE_UPPER_Y = 260 +NATIVE_UPPER_W = 640 +NATIVE_UPPER_H = 320 +# Unit-test tiles and a tight second-look crop are already small. +_SMALL_FRAME = 320 + + +def native_window_model_scale(imgsz: int) -> float: + """How tall a native-frame sign stays after letterbox into imgsz.""" + return min(float(imgsz) / float(NATIVE_WINDOW_H), float(imgsz) / float(NATIVE_WINDOW_W)) + + +def native_detect_window(h: int, w: int) -> tuple[int, int, int, int]: + """Right-side ROAD window. Model input size stays YOLO_IMGSZ. + + A frame that is already ≤320 on both sides (unit-test tiles, a tight + second-look crop) is used whole. The 1928×1208 ROAD frame gets the + fixed rect above. Other large frames scale that rect. + """ + ih, iw = int(h), int(w) + if iw == 1928 and ih == 1208: + return (NATIVE_WINDOW_X, NATIVE_WINDOW_Y, NATIVE_WINDOW_W, NATIVE_WINDOW_H) + if iw <= _SMALL_FRAME and ih <= _SMALL_FRAME: + side = max(2, min(iw, ih)) + return 0, 0, side, side + sx = iw / 1928.0 + sy = ih / 1208.0 + ww = max(2, int(round(NATIVE_WINDOW_W * sx))) + hh = max(2, int(round(NATIVE_WINDOW_H * sy))) + x = int(round(NATIVE_WINDOW_X * sx)) + y = int(round(NATIVE_WINDOW_Y * sy)) + x -= x % 2 + y -= y % 2 + ww -= ww % 2 + hh -= hh % 2 + ww = max(2, ww) + hh = max(2, hh) + if x + ww > iw: + x = max(0, iw - ww) + x -= x % 2 + if y + hh > ih: + y = max(0, ih - hh) + y -= y % 2 + ww = max(2, min(ww, iw - x)) + hh = max(2, min(hh, ih - y)) + ww -= ww % 2 + hh -= hh % 2 + return x, y, max(2, ww), max(2, hh) + + +def _even_rect(x: int, y: int, w: int, h: int, iw: int, ih: int) -> tuple[int, int, int, int]: + x -= x % 2 + y -= y % 2 + w -= w % 2 + h -= h % 2 + w = max(2, w) + h = max(2, h) + if x + w > iw: + x = max(0, iw - w) + x -= x % 2 + if y + h > ih: + y = max(0, ih - h) + y -= y % 2 + w = max(2, min(w, iw - x)) + h = max(2, min(h, ih - y)) + w -= w % 2 + h -= h % 2 + return x, y, max(2, w), max(2, h) + + +def native_upper_window(h: int, w: int) -> tuple[int, int, int, int]: + """Upper right tile. On 1928×1208 this is (1288, 260, 640, 320).""" + ih, iw = int(h), int(w) + if iw == 1928 and ih == 1208: + return (NATIVE_UPPER_X, NATIVE_UPPER_Y, NATIVE_UPPER_W, NATIVE_UPPER_H) + if iw <= _SMALL_FRAME and ih <= _SMALL_FRAME: + return native_detect_window(h, w) + sx = iw / 1928.0 + sy = ih / 1208.0 + return _even_rect( + int(round(NATIVE_UPPER_X * sx)), + int(round(NATIVE_UPPER_Y * sy)), + int(round(NATIVE_UPPER_W * sx)), + int(round(NATIVE_UPPER_H * sy)), + iw, ih, + ) + + +def native_detect_windows(h: int, w: int) -> tuple[tuple[int, int, int, int], ...]: + """Lower tile, then the upper tile. Small frames stay one tile. + + The live loop alternates these. A burst re-reads the tile that scored. + """ + lower = native_detect_window(h, w) + if int(w) <= _SMALL_FRAME and int(h) <= _SMALL_FRAME: + return (lower,) + upper = native_upper_window(h, w) + if upper == lower: + return (lower,) + return (lower, upper) + + +def upscale_gray(img: np.ndarray, min_side: int = 96) -> np.ndarray: + """Upscale a tight plate crop so digit OCR has something to match.""" + if img.ndim != 2 or img.shape[0] < 2 or img.shape[1] < 2: + return img + side = max(int(img.shape[0]), int(img.shape[1])) + if side >= min_side: + return img + scale = float(min_side) / float(side) + nh = max(1, int(round(img.shape[0] * scale))) + nw = max(1, int(round(img.shape[1] * scale))) + return _resize_gray(img, nh, nw) + + +def copy_nv12_rect(buf, rect: tuple[int, int, int, int]) -> Nv12DetectCrop | None: + """Copy one Y+UV rectangle. VisionBuf memory is recycled on the next recv.""" + y_full = y_plane_from_nv12(buf, copy=False) + if y_full is None: + return None + frame_h, frame_w = int(y_full.shape[0]), int(y_full.shape[1]) + cx, cy, cw, ch = (int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3])) + cx = max(0, min(cx, frame_w - 2)) + cy = max(0, min(cy, frame_h - 2)) + cw = max(2, min(cw, frame_w - cx)) + ch = max(2, min(ch, frame_h - cy)) + y = np.ascontiguousarray(y_full[cy:cy + ch, cx:cx + cw]).copy() + uv = _copy_uv_crop(buf, frame_w, frame_h, cx, cy, cw, ch) + return Nv12DetectCrop(y=y, uv=uv, frame_w=frame_w, frame_h=frame_h, crop=(cx, cy, cw, ch)) + + +def copy_nv12_detect_crop(buf, which: int = 0) -> Nv12DetectCrop | None: + """Copy one detect tile. which=0 is the lower window, 1 is the upper. + + No full-frame RGB. The 628×320 window is ~200 KB of Y versus a 1208² + crop (~1.5 MB) or a full 1928×1208 RGB frame (~7 MB). + """ + y_full = y_plane_from_nv12(buf, copy=False) + if y_full is None: + return None + frame_h, frame_w = int(y_full.shape[0]), int(y_full.shape[1]) + rects = native_detect_windows(frame_h, frame_w) + rect = rects[int(which) % len(rects)] + return copy_nv12_rect(buf, rect) + + +def _copy_uv_crop(buf, frame_w: int, frame_h: int, cx: int, cy: int, cw: int, ch: int) -> np.ndarray | None: + try: + stride = int(buf.stride) if getattr(buf, "stride", 0) else frame_w + data = buf.data + uv_off = nv12_uv_offset(buf, stride, frame_h) + uv_rows = frame_h // 2 + need = uv_off + stride * uv_rows + if data is None or len(data) < need: + return None + uv = np.frombuffer(data, dtype=np.uint8, count=stride * uv_rows, offset=uv_off) + uv = uv.reshape(uv_rows, stride)[:, :frame_w] + y0 = cy // 2 + y1 = (cy + ch) // 2 + plane = uv[y0:y1, cx:cx + cw] + if plane.size == 0 or plane.shape[1] < 2: + return None + return np.ascontiguousarray(plane).copy() + except Exception: + return None + + +def _resize_gray(img: np.ndarray, h: int, w: int) -> np.ndarray: + if img.shape[0] == h and img.shape[1] == w: + return img + try: + import cv2 + return cv2.resize(img, (w, h), interpolation=cv2.INTER_LINEAR) + except Exception: + return _resize_gray_bilinear(img, h, w) + + +def _resize_gray_bilinear(img: np.ndarray, h: int, w: int) -> np.ndarray: + src_h, src_w = img.shape[:2] + if src_h < 1 or src_w < 1: + return np.zeros((h, w), dtype=np.uint8) + ys = (np.arange(h, dtype=np.float32) + 0.5) * (src_h / float(h)) - 0.5 + xs = (np.arange(w, dtype=np.float32) + 0.5) * (src_w / float(w)) - 0.5 + ys = np.clip(ys, 0.0, src_h - 1.0) + xs = np.clip(xs, 0.0, src_w - 1.0) + y0 = np.floor(ys).astype(np.int32) + x0 = np.floor(xs).astype(np.int32) + y1 = np.minimum(y0 + 1, src_h - 1) + x1 = np.minimum(x0 + 1, src_w - 1) + wy = (ys - y0).astype(np.float32)[:, None] + wx = (xs - x0).astype(np.float32)[None, :] + img_f = img.astype(np.float32) + i00 = img_f[y0][:, x0] + i01 = img_f[y0][:, x1] + i10 = img_f[y1][:, x0] + i11 = img_f[y1][:, x1] + out = (i00 * (1.0 - wx) + i01 * wx) * (1.0 - wy) + (i10 * (1.0 - wx) + i11 * wx) * wy + return np.clip(np.rint(out), 0, 255).astype(np.uint8) + + +def _bt601_yuv_to_rgb(y: np.ndarray, u: np.ndarray, v: np.ndarray) -> np.ndarray: + yf = y.astype(np.float32) + uf = u.astype(np.float32) - 128.0 + vf = v.astype(np.float32) - 128.0 + r = yf + 1.402 * vf + g = yf - 0.344136 * uf - 0.714136 * vf + b = yf + 1.772 * uf + return np.clip(np.stack([r, g, b], axis=-1), 0, 255).astype(np.uint8) + + +def letterbox_rgb_from_nv12_crop(crop: Nv12DetectCrop, size: int) -> tuple[np.ndarray, float, int, int]: + """Letterbox the NV12 crop to size² RGB. No full-frame convert. + + A square crop has scale size/side and no pad. The road window is 628×320, + so scale is size/628 and the short side is padded. YOLO still sees chroma. + """ + y = crop.y + if y.ndim != 2 or y.shape[0] < 2 or y.shape[1] < 2: + raise ValueError("letterbox_rgb_from_nv12_crop expects a 2-D Y crop") + src_h, src_w = y.shape + scale = min(size / float(src_h), size / float(src_w)) + nh = max(1, int(round(src_h * scale))) + nw = max(1, int(round(src_w * scale))) + y_s = _resize_gray(y, nh, nw) + rgb_s = _rgb_from_resized_nv12(y_s, crop.uv) + canvas = np.full((size, size, 3), 114, dtype=np.uint8) + top = (size - nh) // 2 + left = (size - nw) // 2 + canvas[top:top + nh, left:left + nw] = rgb_s + return canvas, scale, left, top + + +def _rgb_from_resized_nv12(y_s: np.ndarray, uv: np.ndarray | None) -> np.ndarray: + nh, nw = y_s.shape + if uv is None or uv.size == 0 or uv.shape[1] < 2: + return np.stack([y_s, y_s, y_s], axis=-1) + u = uv[:, 0::2] + v = uv[:, 1::2] + if u.shape[0] < 1 or u.shape[1] < 1: + return np.stack([y_s, y_s, y_s], axis=-1) + u_s = _resize_gray(u, nh, nw) + v_s = _resize_gray(v, nh, nw) + return _bt601_yuv_to_rgb(y_s, u_s, v_s) diff --git a/selfdrive/speedsignd/paths.py b/selfdrive/speedsignd/paths.py new file mode 100644 index 00000000000000..2f8c532aa54a96 --- /dev/null +++ b/selfdrive/speedsignd/paths.py @@ -0,0 +1,50 @@ +"""On-device paths for the speed-sign logger. + +Weights and JSONL live under /data (or ~/.comma on PC). Nothing is written to +the OSM sqlite, and weights are not stored in git. +""" +from __future__ import annotations + +import os + +PARAM_KEY = "NAPSpeedSignLog" +LOG_FILENAME = "speed_signs.jsonl" +ONNX_FILENAME = "speed_sign.onnx" +PROPOSER_FILENAME = "sign_proposer.onnx" +PYLIB_DIRNAME = "pylib" + + +def nap_data_dir() -> str: + if os.path.isdir("/data/media/0"): + return "/data/media/0/nap" + return os.path.join(os.path.expanduser("~"), ".comma", "media", "0", "nap") + + +def default_log_path() -> str: + override = os.environ.get("NAP_SPEED_SIGN_LOG") + if override: + return override + return os.path.join(nap_data_dir(), LOG_FILENAME) + + +def default_onnx_path() -> str: + override = os.environ.get("NAP_SPEED_SIGN_ONNX") + if override: + return override + return os.path.join(nap_data_dir(), ONNX_FILENAME) + + +def default_pylib_dir() -> str: + """Vendored wheels. Not the system venv and not site-packages.""" + override = os.environ.get("NAP_SPEED_SIGN_PYLIB") + if override: + return override + return os.path.join(nap_data_dir(), PYLIB_DIRNAME) + + +def default_proposer_path() -> str: + """Two-stage strip proposer (Release speed-sign-proposer-v1).""" + override = os.environ.get("NAP_SPEED_SIGN_PROPOSER") + if override: + return override + return os.path.join(nap_data_dir(), PROPOSER_FILENAME) diff --git a/selfdrive/speedsignd/speedsignd.py b/selfdrive/speedsignd/speedsignd.py new file mode 100755 index 00000000000000..76fb50b0278155 --- /dev/null +++ b/selfdrive/speedsignd/speedsignd.py @@ -0,0 +1,1878 @@ +#!/usr/bin/env python3 +"""On-drive MUTCD speed-sign logger (log-only). + +Reads the ROAD camera + GNSS, appends JSONL under /data, and publishes +liveSpeedSignNAP for the on-road HUD. Does not write sqlite, does not change +vCruise / HUD MAX, and does not talk to osm.org. + +Stock modelV2 has no speedSign head — this is a separate process, default off. + +Safety: Logger On starts the process + HUD. Detect keeps running while +openpilot is engaged. Inference is CPU only (onnxruntime +CPUExecutionProvider, else cv2.dnn on the CPU target, else tinygrad +DEV=CPU / CLANG). It must not open the QCOM GPU modeld uses. The first +realize compiles only while known-disengaged and is cached per weights +sha. One ONNX thread, SCHED_IDLE (else nice 19), pinned to little +core 2 — not core 0 (UI), 1 (sensord), 3 (pandad/encoderd), 4 (controlsd), +5 (plannerd/radard), 6 (camerad), or 7 (modeld). While engaged the average +is at most 25% of that core: after each infer the process idles at least +3× the infer time. modelV2 frame drops add more rest. A real modelV2 +frame skip, or modelExecutionTime above 50 ms, pauses at least 10 s. +A 20 Hz SubMaster poll of 20 Hz modelV2 is not that skip. HUD lights +only when two reads agree on the same mph, then holds 45 s. JSONL stays a +short line, skipped while engaged if disk stalls. SubMaster is polled at +20 Hz. Unknown cereal after a short startup allows throttled detect, but +not the compile. Not gated on park / Force Offroad. Detect copies one +right-side 628×320 ROAD window (x 1300–1928, y 520–840) and letterboxes +it to YOLO_IMGSZ. 4 Hz YOLO on a 3X starved modeld; the default stays 1 Hz. +""" +from __future__ import annotations + +import math +import os + +# Before numpy / tinygrad / OpenBLAS import. One compute thread. +# Package __init__ sets the same keys even earlier. Manager forks after +# numpy is already loaded, so main() also calls limit_infer_threads(). +for _thread_key in ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "NUMEXPR_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "BLIS_NUM_THREADS", + "OPENCV_FOR_THREADS_NUM", + "GOTO_NUM_THREADS", + "TINYGRAD_NUM_THREADS", + "KMP_NUM_THREADS", +): + os.environ[_thread_key] = "1" +os.environ["OMP_DYNAMIC"] = "FALSE" +os.environ["MKL_DYNAMIC"] = "FALSE" +os.environ["OMP_WAIT_POLICY"] = "PASSIVE" +os.environ["BEAM"] = "0" +os.environ["NOOPT"] = "0" +os.environ["CPU_COUNT"] = "1" +os.environ["OPENCV_OPENCL_RUNTIME"] = "disabled" +os.environ["OPENCV_DNN_OPENCL"] = "0" + +import threading +import time +from dataclasses import dataclass +from typing import Any + +from openpilot.selfdrive.speedsignd.debounce import SignDebounce +from openpilot.selfdrive.speedsignd.hud import LiveSignHold, apply_live_sign, frame_reads +from openpilot.selfdrive.speedsignd.jsonl import JsonlLogger, make_record, record_line +from openpilot.selfdrive.speedsignd.detect import ( + CAP_MS_DEFAULT, + CAP_MS_ENV, + THREADS_DEFAULT, + THREADS_ENV, + SpeedSignDetector, + assert_cpu_backend, + compile_allowed, + describe_infer_runtimes, + limit_infer_threads, + ocr_tight_y, + parse_infer_cap_ms, + parse_infer_threads, +) +from openpilot.selfdrive.speedsignd.nv12 import copy_nv12_detect_crop, copy_nv12_rect +from openpilot.selfdrive.speedsignd.paths import PARAM_KEY, default_log_path, default_onnx_path, default_proposer_path +from openpilot.selfdrive.speedsignd import two_stage +from openpilot.selfdrive.speedsignd.detect_types import SpeedSign +from openpilot.selfdrive.speedsignd.yolo import REFINE_OVERRIDE_CONF, SIGN_LIKE_CONF + +# Safe default. 4 Hz YOLOv8s tinygrad on ROAD frames saturates a 3X CPU core +# and Ratekeeper catch-up never sleeps. Override: env NAP_SPEED_SIGN_HZ. +SPEEDSIGND_HZ = 1.0 +HZ_ENV = "NAP_SPEED_SIGN_HZ" +HZ_MIN = 0.2 +HZ_MAX = 4.0 +# Poll selfdriveState faster than detect. 100 Hz service + 1 Hz update makes +# SubMaster.alive flap (timeout is 10/freq = 100 ms) and stuck the WAIT plate. +SM_HZ = 20.0 +# modelV2 is published at 20 Hz. SubMaster keeps only the latest message. +MODEL_HZ = 20.0 +# After this, unread cereal allows throttled detect instead of forever-WAIT. +UNKNOWN_GRACE_S = 2.0 +# Historical tinygrad budget. A real 3X infer is several seconds, so this +# must not insert a second wait — that was the ~2× infer gap. Pressure +# backoff (below) is the CPU safety valve. +INFER_BUDGET_MS = 100.0 +INFER_LOG_PERIOD_S = 15.0 +# comma 3X. Host pressure uses os.cpu_count() when the device reports it. +NCPU_DEFAULT = 8 +# procs_running above ncpu + this means the run queue is backed up. +CPU_OVERSUBSCRIBE_EXTRA = 2 +# procs_blocked this high is the disk-stall shape that froze hardwared. +DISK_BLOCKED_MIN = 4 +# One JSONL observation is a handful of numbers. Refuse anything larger. +JSONL_LINE_MAX = 240 +# selfdriveState alert text. No extra subscriber: modeld lag and +# communication-issue are already published on the socket we poll. +LAG_ALERT_MARKERS = ( + ("driving model lagging", "model-lag"), + ("modeldlagging", "model-lag"), + ("communication issue", "controls-lag"), + ("commissue", "controls-lag"), + ("high cpu", "cpu-load"), + ("highcpuusage", "cpu-load"), +) +# 3X little cores are 0–3. Core 2 is the only one without a dedicated +# realtime owner: UI is CTRL_HIGH on 0, sensord is on 1, pandad (54) and +# encoderd (52) share 3. Big cores: controlsd/card/selfdrived on 4, +# plannerd/radard on 5, camerad on 6, modeld FIFO 54 on 7. locationd's +# family is priority 5 across 0–3 and preempts SCHED_IDLE. +SPEEDSIGND_NICE = 19 +SPEEDSIGND_CORE = 2 +SPEEDSIGND_CORES = (SPEEDSIGND_CORE,) +# Idle at least 3× infer between reads → duty = infer / (4× infer) = 25%. +IDLE_FACTOR = 3.0 +CPU_BUDGET = 1.0 / (1.0 + IDLE_FACTOR) +CPU_BUDGET_SLACK = 0.03 +# Duty is averaged over this window. A 2–3 frame burst may run back-to-back; +# the idle after it brings the trailing average back to 25%. +DUTY_WINDOW_S = 10.0 +# Extra YOLO reads after the frame that scored ≥ SIGN_LIKE_CONF. Two extra +# reads is three frames total, still on the tile that saw the sign. +BURST_EXTRA = 2 +# modelV2.frameDropPerc. The lag alert fires near 20; back off earlier. +MODEL_DROP_PERC = 5.0 +# modelV2.modelExecutionTime is seconds (perf_counter in modeld). 22–26 ms +# healthy is ~0.024. Above 50 ms means something else is on modeld's GPU +# or the model itself stalled. Pause at least 10 s. Same for any frameId skip. +MODEL_EXEC_LIMIT_S = 0.050 +MODEL_GUARD_PAUSE_S = 10.0 +# Route 0000017f: a 177 s infer times IDLE_FACTOR made extra_ms 531828. +# model-skip rest is capped so one slow compile cannot hide the plate for 9 min. +MODEL_SKIP_BACKOFF_CAP_S = 60.0 +SECOND_LOOK_FRAMES = 2 +SECOND_LOOK_DEADLINE_S = 0.30 +VISION_TIMEOUT_MS = 200 +SERVICE_NAME = "liveSpeedSignNAP" +# Retry ONNX after Settings → Install weights without requiring a reboot. +ONNX_RETRY_S = 15.0 + +# Matches selfdrive.selfdrived.state.ACTIVE_STATES (actuators on). +CONTROLLING_STATES = frozenset({"enabled", "softDisabling", "overriding"}) +STATE_BY_RAW = { + 0: "disabled", + 1: "preEnabled", + 2: "enabled", + 3: "softDisabling", + 4: "overriding", +} + + +def should_run_speed_sign_log(started: bool, params: Any, _cp: Any = None) -> bool: + """Manager gate. Default-off: unset/false param never starts the process.""" + try: + enabled = params.get_bool(PARAM_KEY) + except Exception: + enabled = False + return bool(started) and bool(enabled) + + +@dataclass(frozen=True) +class EngagementSample: + """Last read of selfdriveState for the ONNX / WAIT gate.""" + known: bool + controlling: bool + allow_detect: bool + detect_paused: bool # HUD WAIT. Engaged driving does not set this. + enabled: bool | None = None + active: bool | None = None + state: str | None = None + alive: bool | None = None + valid: bool | None = None + recv_frame: int = 0 + unknown_after_grace: bool = False + + +def selfdrive_state_name(state: Any) -> str | None: + """Normalize cereal OpenpilotState to a short name.""" + if state is None: + return None + if isinstance(state, str): + return state.split(".")[-1] + if isinstance(state, int): + return STATE_BY_RAW.get(state) + raw = getattr(state, "raw", None) + if raw is not None: + try: + mapped = STATE_BY_RAW.get(int(raw)) + if mapped is not None: + return mapped + except (TypeError, ValueError): + pass + try: + return str(state).split(".")[-1] + except Exception: + return None + + +def op_controlling(*, active: bool | None = None, state: Any = None, + enabled: bool | None = None) -> bool: + """True only when openpilot is commanding actuators. + + Prefer `active`. `state` in enabled / softDisabling / overriding also + counts. `disabled` and `preEnabled` do not. Unknown fields are not + controlling — the caller applies a short startup grace instead of + treating cereal silence as forever-WAIT. + """ + name = selfdrive_state_name(state) + if name == "disabled" or name == "preEnabled": + return False + if name in CONTROLLING_STATES: + return True + if active is True: + return True + if active is False: + return False + if enabled is False: + return False + if enabled is True: + return True + return False + + +def should_run_onnx_detect(controlling: bool) -> bool: + """ONNX runs while engaged. `controlling` is logged, not a pause.""" + del controlling + return True + + +def _sm_flag(sm: Any, flag_name: str, service: str) -> bool | None: + try: + flags = getattr(sm, flag_name, None) + if flags is None or service not in flags: + return None + return bool(flags[service]) + except Exception: + return None + + +def _sm_seen(sm: Any, service: str) -> bool: + """True after a real selfdriveState payload. Do not use recv_frame <= 0. + + SubMaster starts recv_frame at 0 and writes frame 0 on the first receive. + The old `recv_frame <= 0` check treated that first (and only) packet as + unseen, then a 1 Hz loop left alive stale → permanent WAIT. + """ + try: + seen = getattr(sm, "seen", None) + if seen is not None and service in seen: + return bool(seen[service]) + except Exception: + pass + try: + return int(sm.recv_frame.get(service, -1)) > 0 + except Exception: + return False + + +def engagement_from_sm( + sm: Any, + *, + now: float | None = None, + started_at: float = 0.0, + grace_s: float = UNKNOWN_GRACE_S, +) -> EngagementSample: + """Read engagement without treating alive/valid flaps as 'OP is driving'. + + Last parsed active/state/enabled wins even if SubMaster marks the socket + dead — 1 Hz poll of a 100 Hz service makes alive timeout (100 ms) fire + every tick. Unknown cereal: no YOLO for `grace_s`, then throttled detect. + Engaged (controlling) still allows detect. detect_paused stays false so + the HUD shows mph instead of WAIT. + """ + service = "selfdriveState" + try: + recv_frame = int(sm.recv_frame.get(service, 0) or 0) + except Exception: + recv_frame = 0 + alive = _sm_flag(sm, "alive", service) + valid = _sm_flag(sm, "valid", service) + seen = _sm_seen(sm, service) + + active = enabled = None + state: str | None = None + known = False + if seen: + try: + obj: Any = sm[service] + active = bool(obj.active) + enabled = bool(obj.enabled) + state = selfdrive_state_name(getattr(obj, "state", None)) + known = True + except Exception: + known = False + + controlling = op_controlling(active=active, state=state, enabled=enabled) if known else False + if known: + # Engaged used to set allow_detect false. That skipped ~95% of a drive. + # Priority, core mask, and pressure backoff protect modeld instead. + allow_detect = True + detect_paused = False + unknown_after = False + else: + # now is None (unit tests): treat as post-grace so unknown allows detect. + in_grace = False if now is None else (float(now) - float(started_at)) < float(grace_s) + allow_detect = not in_grace + detect_paused = False + unknown_after = not in_grace + + return EngagementSample( + known=known, + controlling=controlling, + allow_detect=allow_detect, + detect_paused=detect_paused, + enabled=enabled, + active=active, + state=state, + alive=alive, + valid=valid, + recv_frame=recv_frame, + unknown_after_grace=unknown_after, + ) + + +def engagement_log_fields(sample: EngagementSample) -> str: + return ( + f"controlling={sample.controlling} enabled={sample.enabled} " + + f"active={sample.active} state={sample.state} " + + f"alive={sample.alive} valid={sample.valid} known={sample.known}" + ) + + +def engaged_from_sm(sm: Any, **kwargs) -> bool: + """Back-compat: True when OP is commanding actuators (not cereal-unknown).""" + return engagement_from_sm(sm, **kwargs).controlling + + +def parse_detect_hz(raw: str | None, default: float = SPEEDSIGND_HZ) -> float: + """Clamp env override. Default 1 Hz; refuse junk / out-of-range.""" + if raw is None or str(raw).strip() == "": + return float(default) + try: + hz = float(raw) + except (TypeError, ValueError): + return float(default) + if not math.isfinite(hz): + return float(default) + return min(HZ_MAX, max(HZ_MIN, hz)) + + +def infer_overran(infer_s: float, period_s: float, budget_s: float) -> bool: + """True when this infer used more than the period or the CPU budget. + + Diagnostic only. Spacing does not pay this back with a second infer. + """ + return infer_s > period_s or infer_s > budget_s + + +def read_gap_s(infer_s: float, period_s: float, backoff_s: float = 0.0) -> float: + """Start-to-start gap. Idle is at least 3× infer, and never faster than the period. + + A 4 s infer waits 12 s, so the next start is 16 s later and the core + averages 25%. A 50 ms infer still waits out a 1 s period (5% of a core). + """ + infer_s = max(0.0, float(infer_s)) + period_s = max(0.0, float(period_s)) + paced = max(period_s, infer_s * (1.0 + IDLE_FACTOR)) + return paced + max(0.0, float(backoff_s)) + + +def steady_core_duty(infer_s: float, period_s: float, backoff_s: float = 0.0) -> float: + """Fraction of the one core speedsignd is pinned to.""" + gap = read_gap_s(infer_s, period_s, backoff_s) + if gap <= 0.0: + return 1.0 + return min(1.0, max(0.0, float(infer_s)) / gap) + + +def next_detect_mono(infer_end: float, infer_s: float, period_s: float, budget_s: float, + cap_s: float = 0.0, backoff_s: float = 0.0) -> float: + """Earliest monotonic time another ONNX infer may start. + + Start-to-start is max(period, 4× infer) plus any extra rest. The road + test at 795d252f ran the next read as soon as the infer ended (~87% of + core 0). `budget_s` and `cap_s` stay in the signature; they do not add + a second wait on top of the duty cycle. + """ + if not math.isfinite(budget_s) or not math.isfinite(cap_s): + raise ValueError("budget and cap must be finite") + gap = read_gap_s(infer_s, period_s, backoff_s) + return (float(infer_end) - float(infer_s)) + gap + + +def window_compute(spans: list[tuple[float, float]], t: float, window: float = DUTY_WINDOW_S) -> float: + """Infer seconds overlapping [t-window, t]. spans are (end, duration).""" + lo = float(t) - float(window) + total = 0.0 + for end, dur in spans: + end_f = float(end) + dur_f = max(0.0, float(dur)) + start = end_f - dur_f + a = max(start, lo) + b = min(end_f, float(t)) + if b > a: + total += b - a + return total + + +def earliest_budget_start( + spans: list[tuple[float, float]], now: float, next_dur: float, + window: float = DUTY_WINDOW_S, budget: float = CPU_BUDGET, +) -> float: + """Earliest t ≥ now such that the infer [t, t+next_dur] keeps the window ≤ budget. + + Past spans age out of the trailing window. A burst that already spent the + allowance waits here until idle has repaid it. + """ + now_f = float(now) + next_dur = max(0.0, float(next_dur)) + allowance = float(window) * float(budget) + + def fits(t: float) -> bool: + finish = t + next_dur + used = window_compute(spans, finish, window) + return used + next_dur <= allowance + 1e-6 + + if fits(now_f): + return now_f + candidates = [now_f] + for end, _dur in spans: + candidates.append(float(end) + float(window) - next_dur) + for t in sorted(candidates): + t = max(now_f, t) + if fits(t): + return t + newest = max((float(end) for end, _dur in spans), default=now_f) + return max(now_f, newest + float(window) - next_dur) + + +def sign_burst_trigger(diag: dict | None, signs=None) -> bool: + """True when any speed-sign class scored ≥ SIGN_LIKE_CONF. + + sl_peak covers sl_NN below YOLO_MIN_CONF. A decoded sign, or an + sl_unreadable peak, counts too. neg_* does not. + """ + diag = diag or {} + try: + if float(diag.get("sl_peak_conf") or 0.0) >= SIGN_LIKE_CONF: + return True + except (TypeError, ValueError): + pass + peak_name = str(diag.get("peak_name") or "") + try: + peak = float(diag.get("peak_conf") or 0.0) + except (TypeError, ValueError): + peak = 0.0 + if peak >= SIGN_LIKE_CONF and peak_name.startswith(("sl_", "speedLimit")): + return True + for s in signs or []: + try: + if float(getattr(s, "conf", 0.0) or 0.0) >= SIGN_LIKE_CONF: + return True + except (TypeError, ValueError): + continue + return False + + +def schedule_after_read( + *, + now: float, + infer_s: float, + period_s: float, + budget_s: float, + cap_s: float, + backoff_s: float, + sign_like: bool, + window_used: int, + window_count: int, + burst_left: int, + burst_window: int, + burst_cluster_s: float, + spans: list[tuple[float, float]], +) -> tuple[float, int, int, int, float, bool]: + """Next detect time plus burst state. + + Returns (next_mono, burst_left, burst_window, next_window, cluster_s, bursting_next). + + Steady reads keep max(period, 4× infer). A sign-like score schedules up to + BURST_EXTRA more reads on the same tile, immediately, while that cluster + still fits in the 10 s × 25% allowance. The following non-burst start waits + until the trailing window is back at 25%. A model-guard backoff cancels the + burst. `budget_s` and `cap_s` stay on next_detect_mono; they do not add a + second wait. + """ + infer_s = max(0.0, float(infer_s)) + spans_now = list(spans) + [(float(now), infer_s)] + paced = next_detect_mono(float(now), infer_s, period_s, budget_s, cap_s, backoff_s) + duty_t = earliest_budget_start(spans_now, float(now), infer_s) + steady = max(paced, duty_t) + nwin = max(1, int(window_count)) + next_window = (int(window_used) + 1) % nwin + allowance = DUTY_WINDOW_S * CPU_BUDGET + if float(backoff_s) > 0.0: + return steady, 0, int(window_used), next_window, 0.0, False + if int(burst_left) > 0: + cluster = float(burst_cluster_s) + infer_s + left = int(burst_left) - 1 + if left > 0 and cluster + infer_s <= allowance + 1e-6: + return float(now), left, int(burst_window), int(burst_window), cluster, True + return steady, 0, int(burst_window), next_window, 0.0, False + if sign_like: + cluster = infer_s + if BURST_EXTRA > 0 and cluster + infer_s <= allowance + 1e-6: + return float(now), BURST_EXTRA, int(window_used), int(window_used), cluster, True + return steady, 0, int(window_used), next_window, 0.0, False + + +@dataclass(frozen=True) +class HostPressure: + """CPU / disk / alert snapshot. No new cereal subscriber.""" + procs_running: int | None = None + procs_blocked: int | None = None + ncpu: int = NCPU_DEFAULT + alert_text: str = "" + + +def parse_proc_stat_pressure(text: str) -> tuple[int | None, int | None]: + """procs_running and procs_blocked from /proc/stat.""" + running = blocked = None + for line in text.splitlines(): + if line.startswith("procs_running "): + try: + running = int(line.split()[1]) + except (IndexError, ValueError): + running = None + elif line.startswith("procs_blocked "): + try: + blocked = int(line.split()[1]) + except (IndexError, ValueError): + blocked = None + return running, blocked + + +def read_proc_stat_pressure(path: str = "/proc/stat") -> tuple[int | None, int | None]: + try: + with open(path, encoding="utf-8") as f: + return parse_proc_stat_pressure(f.read()) + except OSError: + return None, None + + +def lag_reason_from_alert(*parts: str | None) -> str: + """Map a selfdriveState alert onto a backoff reason, or ''.""" + blob = " ".join(p for p in parts if p).lower() + if not blob: + return "" + for needle, reason in LAG_ALERT_MARKERS: + if needle in blob: + return reason + return "" + + +def alert_text_from_sm(sm: Any) -> str: + try: + obj = sm["selfdriveState"] + except Exception: + return "" + parts: list[str] = [] + for name in ("alertText1", "alertText2", "alertType"): + try: + val = getattr(obj, name, None) + except Exception: + val = None + if val: + parts.append(str(val)) + return " ".join(parts) + + +def pressure_reason(pressure: HostPressure) -> str: + """Why to rest, or '' when the host looks healthy.""" + reasons: list[str] = [] + alert = lag_reason_from_alert(pressure.alert_text) + if alert: + reasons.append(alert) + ncpu = int(pressure.ncpu) if pressure.ncpu else NCPU_DEFAULT + if pressure.procs_running is not None and pressure.procs_running > ncpu + CPU_OVERSUBSCRIBE_EXTRA: + reasons.append("cpu-load") + if pressure.procs_blocked is not None and pressure.procs_blocked >= DISK_BLOCKED_MIN: + reasons.append("disk-stall") + out: list[str] = [] + for reason in reasons: + if reason not in out: + out.append(reason) + return "+".join(out) + + +def disk_stalled(pressure: HostPressure) -> bool: + return pressure.procs_blocked is not None and pressure.procs_blocked >= DISK_BLOCKED_MIN + + +def backoff_extra_s(infer_s: float, period_s: float, reason: str) -> float: + """Extra rest on top of the 3× idle. Empty reason → none. + + Another 3× infer drops a long infer from 25% of a core to about 14%. + """ + if not reason: + return 0.0 + return max(float(period_s), IDLE_FACTOR * max(0.0, float(infer_s))) + + +def model_guard_rest_s(infer_s: float, period_s: float, reason: str, hard: bool) -> float: + """Frame-drop backoff, with a 10 s floor on a frame skip or modeld > 50 ms. + + Any reason that includes model-skip is also capped at 60 s, hard or not. + model-drop and model-exec keep the uncapped 3× rest. + """ + extra = backoff_extra_s(infer_s, period_s, reason) + if hard: + extra = max(extra, MODEL_GUARD_PAUSE_S) + if reason and "model-skip" in reason: + return min(extra, MODEL_SKIP_BACKOFF_CAP_S) + return extra + + +def collect_host_pressure(sm: Any, *, stat_path: str = "/proc/stat", ncpu: int | None = None) -> HostPressure: + running, blocked = read_proc_stat_pressure(stat_path) + if ncpu is None: + ncpu = os.cpu_count() or NCPU_DEFAULT + return HostPressure( + procs_running=running, + procs_blocked=blocked, + ncpu=int(ncpu), + alert_text=alert_text_from_sm(sm), + ) + + +def jsonl_line_is_light(record: dict) -> bool: + return len(record_line(record).encode("utf-8")) <= JSONL_LINE_MAX + + +def reset_ratekeeper_if_behind(rk, now: float) -> bool: + """Drop Ratekeeper catch-up so an overrun does not burst more infers.""" + if rk.remaining < 0: + rk._next_frame_time = now + rk._interval + return True + return False + + +def model_frame_gap_allowed(dt_s: float, hz: float = MODEL_HZ) -> int: + """How far frameId may jump without modeld having dropped a frame. + + Both sides are 20 Hz, and SubMaster keeps only the latest modelV2, so a + poll that lands between two publishes sees delta 2. A vision recv or an + infer that blocks this poll for dt seconds misses about dt*20 publishes. + +1 is that one coalesced message. frameDropPerc is the real modeld drop. + """ + dt_s = max(0.0, float(dt_s)) + return max(2, math.ceil(dt_s * float(hz)) + 1) + + +@dataclass +class ModelWatch: + """modelV2 frame drops, frame-id gaps, and modelExecutionTime. No new socket.""" + last_frame: int | None = None + last_mono: float | None = None + last_drop: float | None = None + last_exec: float | None = None + drop_hot: bool = False + exec_hot: bool = False + skipped: bool = False + + def observe(self, frame_id: int | None, drop: float | None, exec_s: float | None = None, + now: float | None = None) -> None: + if now is None: + now = time.monotonic() + if frame_id is not None and self.last_frame is not None and self.last_mono is not None: + gap = int(frame_id) - int(self.last_frame) + allowed = model_frame_gap_allowed(float(now) - float(self.last_mono)) + if gap > allowed: + self.skipped = True + if drop is not None: + value = float(drop) + # Jitter under 5% is not a drop. 5% is well before modeld's ~20% lag alert. + if value >= MODEL_DROP_PERC: + self.drop_hot = True + self.last_drop = value + if exec_s is not None: + try: + exec_value = float(exec_s) + except (TypeError, ValueError): + exec_value = None + if exec_value is not None and math.isfinite(exec_value): + self.last_exec = exec_value + if exec_value > MODEL_EXEC_LIMIT_S: + self.exec_hot = True + if frame_id is not None: + self.last_frame = int(frame_id) + self.last_mono = float(now) + + def hard_guard(self) -> bool: + """Any skipped frame id, or modeld execution above 50 ms.""" + return bool(self.skipped or self.exec_hot) + + def reason(self) -> str: + parts: list[str] = [] + if self.drop_hot: + parts.append("model-drop") + if self.exec_hot: + parts.append("model-exec") + if self.skipped: + parts.append("model-skip") + return "+".join(parts) + + def consume(self) -> str: + """Return the reason and clear a one-shot skip. A hot drop or exec stays hot.""" + reason = self.reason() + self.skipped = False + if self.last_drop is None or self.last_drop < MODEL_DROP_PERC: + self.drop_hot = False + if self.last_exec is None or self.last_exec <= MODEL_EXEC_LIMIT_S: + self.exec_hot = False + return reason + + +def join_reasons(*parts: str) -> str: + out: list[str] = [] + for part in parts: + for piece in (part or "").split("+"): + if piece and piece not in out: + out.append(piece) + return "+".join(out) + + +def parse_proc_thread_count(text: str) -> int | None: + for line in text.splitlines(): + if line.startswith("Threads:"): + try: + return int(line.split()[1]) + except (IndexError, ValueError): + return None + return None + + +def read_proc_thread_count(path: str = "/proc/self/status") -> int | None: + try: + with open(path, encoding="utf-8") as f: + return parse_proc_thread_count(f.read()) + except OSError: + return None + + +def parse_proc_stat_jiffies(text: str) -> int | None: + """utime+stime from /proc/self/stat. comm may contain spaces.""" + end = text.rfind(")") + if end < 0: + return None + parts = text[end + 2:].split() + try: + return int(parts[11]) + int(parts[12]) + except (IndexError, ValueError): + return None + + +def read_proc_stat_jiffies(path: str = "/proc/self/stat") -> int | None: + try: + with open(path, encoding="utf-8") as f: + return parse_proc_stat_jiffies(f.read()) + except OSError: + return None + + +class CpuShareMeter: + """CPU seconds of this process divided by wall seconds. 1.0 is one full core.""" + + def __init__(self) -> None: + self._mono: float | None = None + self._jiffies: int | None = None + self._clk = os.sysconf(os.sysconf_names["SC_CLK_TCK"]) if hasattr(os, "sysconf_names") else 100 + + def sample(self, now: float, jiffies: int | None) -> float | None: + if jiffies is None: + return None + if self._mono is None or self._jiffies is None: + self._mono = float(now) + self._jiffies = int(jiffies) + return None + dt = float(now) - self._mono + dj = int(jiffies) - self._jiffies + self._mono = float(now) + self._jiffies = int(jiffies) + if dt <= 1e-6 or self._clk <= 0: + return None + return (dj / float(self._clk)) / dt + + +def cpu_over_budget(share: float | None) -> bool: + return share is not None and float(share) > CPU_BUDGET + CPU_BUDGET_SLACK + + +def yield_to_modeld() -> str: + """SCHED_IDLE on core 2, else nice 19. Lowers speedsignd only.""" + from openpilot.common.realtime import drop_realtime, set_core_affinity + drop_realtime() + policy = "nice" + try: + idle = getattr(os, "SCHED_IDLE", None) + if idle is None: + raise OSError("no SCHED_IDLE") + os.sched_setscheduler(0, idle, os.sched_param(0)) + policy = "idle" + except OSError: + try: + os.nice(SPEEDSIGND_NICE) + except OSError: + pass + try: + set_core_affinity(list(SPEEDSIGND_CORES)) + except Exception: + pass + limit_infer_threads(1) + return policy + + +def should_reset_detect_after_wait(last_allow: bool | None, allow_detect: bool) -> bool: + """First manual tick after WAIT: do not sit out a leftover next_detect.""" + return bool(allow_detect) and last_allow is False + + +def drain_vision_latest(client) -> None: + """Non-blocking ROAD recv so WAIT idle does not wedge the VisionIPC socket.""" + if client is None: + return + try: + client.recv(timeout_ms=0) + except Exception: + pass + + +def process_frame( + y, + lat: float, + lon: float, + bearing: float | None, + gps_ok: bool, + detector: SpeedSignDetector, + logger: JsonlLogger, + now: float, + rgb=None, + debounce: SignDebounce | None = None, + nv12=None, + write_jsonl: bool = True, +) -> tuple[list, list[dict]]: + """Detect on every ROAD frame. JSONL only with a GNSS fix and a short line. + + With `debounce`: HUD and JSONL both need two agreeing frames. The returned + list is the signs that cast a vote this call, not a plate that is already + lit. Tests omit debounce and see raw detections. + `write_jsonl` is false while engaged during a disk stall. + """ + signs = [] if (y is None and rgb is None and nv12 is None) else detector.detect(y, rgb=rgb, nv12=nv12) + hud_signs = signs + jsonl_signs = signs + if debounce is not None: + split = debounce.update_split(signs, now) + hud_signs = split.hud + jsonl_signs = split.confirmed + written: list[dict] = [] + if gps_ok and write_jsonl: + for sign in jsonl_signs: + rec = make_record(now, lat, lon, bearing, sign.mph, sign.conf) + if not jsonl_line_is_light(rec): + continue + if logger.write(rec): + written.append(rec) + return hud_signs, written + + +def process_observations( + y, + lat: float, + lon: float, + bearing: float | None, + gps_ok: bool, + detector: SpeedSignDetector, + logger: JsonlLogger, + now: float, +) -> list[dict]: + """Detect + append. No GPS fix → no row (lat/lon would be junk).""" + _signs, written = process_frame(y, lat, lon, bearing, gps_ok, detector, logger, now) + return written + + +@dataclass +class InferOutcome: + signs: list + written: list[dict] + infer_s: float + error: str | None = None + diag: dict | None = None + + +def format_refine_token(class_mph, hud_mph, ref_mph, ref_conf) -> str: + """Unambiguous refine= token. Fail is `refine=- class=65`, never `-(65)`. + + Agree: `65:0.47`. Override: `50:0.43 class=65`. Parentheses around 65 + were misread as refine=(65) in Justin's journalctl paste. + """ + if ref_mph is None: + return f"- class={int(class_mph)}" + token = f"{int(ref_mph)}:{float(ref_conf):.2f}" + if int(ref_mph) == int(hud_mph) == int(class_mph): + return token + return f"{int(hud_mph)}:{float(ref_conf):.2f} class={int(class_mph)}" + + +def format_infer_diag(diag: dict | None, *, allow_detect: bool) -> str: + """One-line on-car fields: backend, frame, letterbox, crop, sha, peak.""" + d = diag or {} + crop = d.get("crop") or (0, 0, 0, 0) + if isinstance(crop, (list, tuple)) and len(crop) == 4: + crop_s = f"{int(crop[0])},{int(crop[1])} {int(crop[2])}x{int(crop[3])}" + else: + crop_s = str(crop) + out = d.get("out_shape", ()) + if isinstance(out, (list, tuple)): + out_s = "x".join(str(int(v)) for v in out) if out else "-" + else: + out_s = str(out) + sl_conf = float(d.get("sl_peak_conf", 0.0) or 0.0) + sl_name = d.get("sl_peak_name", "") or "" + n_over = int(d.get("n_over", 0) or 0) + # Always log sl_peak — Justin's R2-1 miss is n_over=0 with a weak speedLimit*. + # When n_over>0 the global peak is often stop; sl_peak is the HUD-relevant head. + sl_s = f" sl_peak={sl_conf:.2f}/{sl_name}" + top3 = d.get("top3") or () + if top3: + top_s = " top=" + ",".join(f"{n}:{c:.2f}" for n, c in list(top3)[:3]) + else: + top_s = "" + posted = d.get("posted") or () + if posted: + posted_s = " cls=" + ",".join(f"{int(mph)}:{float(c):.2f}" for mph, c in posted) + else: + posted_s = "" + refine = d.get("refine") or () + if refine: + parts = [] + for row in refine: + if not row or len(row) < 4: + continue + class_mph, hud_mph, ref_mph, ref_conf = row[0], row[1], row[2], row[3] + parts.append(format_refine_token(class_mph, hud_mph, ref_mph, ref_conf)) + refine_s = " refine=" + ",".join(parts) if parts else "" + else: + refine_s = "" + return ( + f"backend={d.get('backend', '?')} " + + f"frame={int(d.get('frame_w', 0) or 0)}x{int(d.get('frame_h', 0) or 0)} " + + f"letterbox={int(d.get('letterbox', 0) or 0)} crop={crop_s} " + + f"onnx={d.get('weights_path', '')} sha={d.get('weights_sha', '')} " + + f"allow={int(bool(allow_detect))} out={out_s} " + + f"peak={float(d.get('peak_conf', 0.0) or 0.0):.2f}/{d.get('peak_name', '')} " + + f"n_over={n_over}" + + sl_s + + f" n_over_sl={int(d.get('n_over_sl', 0) or 0)}" + + top_s + + posted_s + + refine_s + + " " + + f"luma={float(d.get('luma_mean', 0.0) or 0.0):.0f}/{float(d.get('luma_std', 0.0) or 0.0):.0f} " + + f"chroma={int(d.get('chroma', 0) or 0)} " + + f"prep={float(d.get('prep_ms', 0.0) or 0.0):.0f} " + + f"sess={float(d.get('sess_ms', 0.0) or 0.0):.0f}" + ) + + +def detect_skip_reason( + *, + connected: bool, + onnx: bool, + busy: bool, + holdoff: bool, + buf_empty: bool | None = None, + parse_fail: bool = False, +) -> str: + """Why YOLO did not start. Distinguishes infer-never-ran from raw=[].""" + if not connected: + return "vision-disconnected" + if not onnx: + return "no-onnx" + if parse_fail: + return "nv12-parse" + if buf_empty: + return "road-recv-empty" + if busy: + return "infer-busy" + if holdoff: + return "holdoff" + return "ok" + + +class InferSlot: + """At most one ONNX infer. The 20 Hz loop never joins on engage. + + Re-engage used to block speedsignd for 300–1500 ms on an in-flight YOLO + (and leave a core hot) → Communication Issue Between Processes. pause() + drops the result immediately and refuses new work. The leftover infer may + still finish at nice 19; we do not start another and we do not wait. + + resume() only clears the start-gate. A generation counter keeps the + abandoned infer from publishing after WAIT clears (that used to apply + skip-on-overrun to a stale leftover and delay the first real manual detect). + """ + + def __init__(self): + self._lock = threading.Lock() + self._cancel = threading.Event() + self._busy = False + self._outcome: InferOutcome | None = None + self._gen = 0 + + @property + def busy(self) -> bool: + with self._lock: + return self._busy + + def pause(self) -> bool: + """Cancel in-flight work and drop results. True if an infer was busy.""" + self._cancel.set() + with self._lock: + was_busy = self._busy + self._outcome = None + self._gen += 1 + return was_busy + + def resume(self) -> None: + self._cancel.clear() + + def take(self) -> InferOutcome | None: + with self._lock: + out = self._outcome + self._outcome = None + return out + + def start(self, fn) -> bool: + """Run fn() in a daemon thread. fn returns (signs, written) or + diag.""" + with self._lock: + if self._busy or self._cancel.is_set(): + return False + self._busy = True + self._outcome = None + gen = self._gen + + def run(): + t0 = time.monotonic() + signs: list = [] + written: list[dict] = [] + diag = None + error = None + try: + if self._cancel.is_set(): + return + result = fn() + if isinstance(result, tuple) and len(result) >= 3: + signs, written, diag = result[0], result[1], result[2] + else: + signs, written = result + except Exception as e: + error = f"{type(e).__name__}: {e}" + signs, written = [], [] + finally: + infer_s = time.monotonic() - t0 + with self._lock: + if not self._cancel.is_set() and gen == self._gen: + self._outcome = InferOutcome( + list(signs), list(written), infer_s, error=error, diag=diag, + ) + self._busy = False + + threading.Thread(target=run, name="speedsignd-onnx", daemon=True).start() + return True + + +def detect_if_allowed( + y, + lat: float, + lon: float, + bearing: float | None, + gps_ok: bool, + detector: SpeedSignDetector, + logger: JsonlLogger, + now: float, + *, + controlling: bool, + rgb=None, + debounce: SignDebounce | None = None, + nv12=None, + disk_stalled: bool = False, +) -> tuple[list, list[dict]]: + """ONNX while engaged or manual. Skip the JSONL write if engaged and disk-stalled.""" + if not should_run_onnx_detect(controlling): + return [], [] + write_jsonl = not (bool(controlling) and bool(disk_stalled)) + return process_frame( + y, lat, lon, bearing, gps_ok, detector, logger, now, + rgb=rgb, debounce=debounce, nv12=nv12, write_jsonl=write_jsonl, + ) + + +def _connect_road_camera(): + from msgq.visionipc import VisionIpcClient, VisionStreamType + client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True) + return client + + +def live_sign_publish_fields( + hold: LiveSignHold, + signs, + now_mono: float, + weights_missing: bool, + detect_paused: bool = False, +) -> tuple[bool, int, float, bool, bool]: + """msg.valid, mph, conf, weights_missing, detect_paused for liveSpeedSignNAP. + + When ONNX is missing, keep msg.valid so the HUD can show NO WT — never a + numpy-fallback mph. Controlling does not freeze the hold: mph stays 0 + until two different frames agree, then the plate shows that mph while + engaged. Unknown cereal must not set detect_paused (no false WAIT). + """ + if weights_missing: + return True, 0, 0.0, True, False + if detect_paused: + return True, 0, 0.0, False, True + live, mph, conf = hold.update(signs, now_mono) + return live, mph if live else 0, conf if live else 0.0, False, False + + +def _publish_live( + pm, hold: LiveSignHold, signs, now_mono: float, messaging, + weights_missing: bool, detect_paused: bool = False, +) -> None: + msg_valid, mph, conf, missing, paused = live_sign_publish_fields( + hold, signs, now_mono, weights_missing, detect_paused, + ) + msg = messaging.new_message(SERVICE_NAME) + msg.valid = msg_valid + apply_live_sign( + getattr(msg, SERVICE_NAME), + mph=mph, conf=conf, valid=bool(mph), weights_missing=missing, detect_paused=paused, + ) + pm.send(SERVICE_NAME, msg) + + +def format_read_timing( + *, + read_interval_ms: float, + infer_ms: float, + engaged: bool, + backoff: bool, + reason: str, + cpu_share: float | None = None, + threads: int = 1, + backend: str = "", + os_threads: int | None = None, +) -> str: + """One greppable line per finished read. `speedsignd timing`. + + `threads` is the pinned BLAS/OpenMP/OpenCV pool (1). `os_threads` is + /proc/self/status Threads, which also counts the main loop, the infer + worker, and VisionIPC. Route 0000017e logged the proc count in `threads` + and showed 11. + """ + share = "na" if cpu_share is None else f"{float(cpu_share):.3f}" + os_s = "" if os_threads is None else f"os_threads={int(os_threads)} " + return ( + "speedsignd timing " + + f"read_interval_ms={read_interval_ms:.0f} " + + f"infer_ms={infer_ms:.0f} " + + f"cpu_share={share} " + + f"threads={int(threads)} " + + os_s + + f"backend={backend or 'unset'} " + + f"engaged={int(bool(engaged))} " + + f"backoff={int(bool(backoff))} " + + f"reason={reason or 'pace'}" + ) + + +def format_backoff_timing( + *, + extra_ms: float, + infer_ms: float, + engaged: bool, + reason: str, + backend: str = "", +) -> str: + """Greppable back-off event. Still starts with `speedsignd timing`.""" + return ( + "speedsignd timing " + + f"backoff=1 reason={reason or 'pressure'} " + + f"extra_ms={extra_ms:.0f} " + + f"infer_ms={infer_ms:.0f} " + + f"engaged={int(bool(engaged))} " + + f"backend={backend or 'unset'}" + ) + + +def _log_infer_timing(cloudlog, infer_ms: list[float], skip_count: int, hz: float, engaged: bool, + threads: int = 1) -> None: + n = len(infer_ms) + mean_ms = sum(infer_ms) / n if n else 0.0 + max_ms = max(infer_ms) if n else 0.0 + os_n = read_proc_thread_count() + os_s = "na" if os_n is None else str(int(os_n)) + cloudlog.info( + "speedsignd timing hz=%.2f infer_ms mean=%.1f max=%.1f n=%d skip=%d engaged=%d threads=%d os_threads=%s", + hz, mean_ms, max_ms, n, skip_count, int(bool(engaged)), int(threads), os_s, + ) + + +@dataclass +class PendingSecondLook: + bbox: tuple[int, int, int, int] + frames_left: int + deadline: float + + +def sign_like_bbox(signs, diag) -> tuple[int, int, int, int] | None: + """Box for an immediate OCR follow-up. None when this frame already agrees.""" + for s in signs or []: + _pending, pair = frame_reads(s) + if pair is not None: + return None + for s in signs or []: + pending, _pair = frame_reads(s) + conf = float(getattr(s, "conf", 0.0) or 0.0) + if pending or conf >= SIGN_LIKE_CONF: + box = getattr(s, "bbox", None) + if box is not None and len(box) == 4: + return tuple(int(v) for v in box) + raw = (diag or {}).get("sign_like_bbox") if diag else None + if raw is not None and len(raw) == 4: + return tuple(int(v) for v in raw) + return None + + +def tight_rect(bbox, frame_w: int, frame_h: int, pad_frac: float = 0.50) -> tuple[int, int, int, int]: + x, y, w, h = (int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])) + pad = int(max(w, h) * pad_frac) + x0 = max(0, x - pad) + y0 = max(0, y - pad) + x1 = min(int(frame_w), x + w + pad) + y1 = min(int(frame_h), y + h + pad) + x0 -= x0 % 2 + y0 -= y0 % 2 + return x0, y0, max(2, x1 - x0), max(2, y1 - y0) + + +def second_look_sign(buf, bbox) -> SpeedSign | None: + """OCR a tight full-res crop. Not a second YOLO.""" + width = int(getattr(buf, "width", 0) or 0) + height = int(getattr(buf, "height", 0) or 0) + if width < 2 or height < 2: + return None + crop = copy_nv12_rect(buf, tight_rect(bbox, width, height)) + if crop is None: + return None + mph, conf = ocr_tight_y(crop.y) + if mph is None or float(conf) < REFINE_OVERRIDE_CONF: + return None + return SpeedSign( + mph=int(mph), conf=float(conf), bbox=tuple(int(v) for v in bbox), + refine_mph=int(mph), refine_conf=float(conf), + ) + + +def observe_model(watch: ModelWatch, sm, now: float | None = None) -> None: + try: + if not sm.updated["modelV2"]: + return + msg = sm["modelV2"] + except Exception: + return + try: + watch.observe( + getattr(msg, "frameId", None), + getattr(msg, "frameDropPerc", None), + getattr(msg, "modelExecutionTime", None), + now=time.monotonic() if now is None else now, + ) + except Exception: + return + + +def main(): + from cereal import messaging + from openpilot.common.realtime import Ratekeeper + from openpilot.common.swaglog import cloudlog + from openpilot.selfdrive.mapd.gps_fix import gps_sample_from_sm + + # Child of manager: shrink the BLAS pool the parent already started. + limit_infer_threads(1) + sched_name = yield_to_modeld() + + hz = parse_detect_hz(os.environ.get(HZ_ENV)) + period_s = 1.0 / hz + budget_s = INFER_BUDGET_MS / 1000.0 + threads = parse_infer_threads(os.environ.get(THREADS_ENV), THREADS_DEFAULT) + cap_ms = parse_infer_cap_ms(os.environ.get(CAP_MS_ENV), CAP_MS_DEFAULT) + cap_s = cap_ms / 1000.0 if cap_ms > 0 else 0.0 + + log_path = default_log_path() + onnx_path = default_onnx_path() + detector = SpeedSignDetector(onnx_path=onnx_path) + logger = JsonlLogger(log_path) + hold = LiveSignHold() + debounce = SignDebounce() + # Two-stage reader: strip proposer + tracker + one sharp read per sign. + # Missing proposer file -> legacy fixed tiles (unchanged behavior). + proposer = two_stage.Proposer(default_proposer_path()) + tracker = two_stage.SignTracker() + two_period_s = 1.0 / two_stage.PROPOSER_HZ + last_proposer_try = time.monotonic() + last_stopped_log = 0.0 + backend = detector.backend_name() + weights_sha = detector.weights_sha_short() + if detector.onnx is not None and detector.onnx.session is not None: + backend = assert_cpu_backend(detector.onnx.session) + runtimes = describe_infer_runtimes() + os_threads = read_proc_thread_count() + from openpilot.selfdrive.speedsignd.install import runtime_missing, runtime_status_summary + runtime_label = runtime_status_summary() + cloudlog.info( + "speedsignd cpu-only asserted backend=%s runtimes=%s dev=%s qcom=%s gpu=%s cpu_count=%s", + backend, runtimes, os.environ.get("DEV", ""), os.environ.get("QCOM", ""), + os.environ.get("GPU", ""), os.environ.get("CPU_COUNT", ""), + ) + cloudlog.info( + "speedsignd starting log=%s backend=%s onnx=%s sha=%s sm_hz=%.1f detect_hz=%.2f " + + "budget_ms=%.0f cap_ms=%.0f threads=%d os_threads=%s cores=%s nice=%d sched=%s " + + "detect_while_engaged=1 crop_rgb=1 duty=%.2f runtime=%s", + log_path, backend, onnx_path, weights_sha, SM_HZ, hz, INFER_BUDGET_MS, cap_ms, threads, + "na" if os_threads is None else str(int(os_threads)), + ",".join(str(c) for c in SPEEDSIGND_CORES), SPEEDSIGND_NICE, sched_name, CPU_BUDGET, + runtime_label, + ) + # tinygrad-clang already logged its own fallback inside _onnx_session. + if runtime_missing() and backend != "tinygrad-clang": + cloudlog.warning( + "speedsignd runtime missing — Settings → NAP → Install weights also installs " + + "onnxruntime into /data/media/0/nap/pylib (not the system venv). " + + "The plate shows NO RT. CLANG will not run while engaged.", + ) + if detector.onnx is None: + cloudlog.warning( + "speedsignd: no ONNX at %s — numpy fallback will not see real roadside signs. " + + "HUD will show NO WT. Settings → NAP → Install weights, or: " + + "python -m scripts.nap.install_speed_sign_weights", + onnx_path, + ) + + cloudlog.info( + "speedsignd two-stage proposer=%s path=%s err=%s hz=%.1f conf=%.2f strip=%s", + int(proposer.ok), proposer.path, proposer.error, two_stage.PROPOSER_HZ, + two_stage.PROPOSER_CONF, two_stage.STRIP_RECT, + ) + sm = messaging.SubMaster( + ["gpsLocationExternal", "gpsLocation", "selfdriveState", "modelV2"], + frequency=SM_HZ, + ) + pm = messaging.PubMaster([SERVICE_NAME]) + rk = Ratekeeper(SM_HZ, print_delay_threshold=None) + client = None + last_connect = 0.0 + last_onnx_try = time.monotonic() + next_detect = 0.0 + infer_ms: list[float] = [] + skip_count = 0 + last_timing_log = time.monotonic() + started_at = time.monotonic() + last_allow: bool | None = None + last_paused: bool | None = None + last_unknown_warn = 0.0 + last_empty_frame_log = 0.0 + last_empty_raw_log = 0.0 + last_infer_done = 0.0 + last_gate_log = 0.0 + last_skip_reason = "init" + in_holdoff = False + slot = InferSlot() + last_read_start = 0.0 + pending_interval_ms = 0.0 + pending_backoff = False + pending_reason = "pace" + scheduled_backoff = False + scheduled_reason = "pace" + model_watch = ModelWatch() + cpu_meter = CpuShareMeter() + second_look: PendingSecondLook | None = None + model_extended = False + last_infer_s = period_s + window_i = 0 + pending_window = 0 + burst_left = 0 + burst_window = 0 + burst_cluster_s = 0.0 + duty_spans: list[tuple[float, float]] = [] + + while True: + sm.update(0) + observe_model(model_watch, sm) + now_mono = time.monotonic() + sample = engagement_from_sm(sm, now=now_mono, started_at=started_at) + # Refresh every tick, before any infer starts. The first frame of a boot + # that is already engaged sees controlling=True and does not compile. + # Unknown cereal is not permission either. The worker re-reads this flag + # inside run(), so a flip before realize still aborts. + detector.allow_compile(compile_allowed( + known=bool(sample.known), + controlling=bool(sample.controlling), + ready=detector.compile_ready(), + )) + live_model = model_watch.reason() + if live_model and not model_extended: + hard_now = model_watch.hard_guard() + extra_now = model_guard_rest_s(last_infer_s, period_s, live_model, hard_now) + # A frame skip or modeld > 50 ms pauses even before the first infer. + # A frameDropPerc backoff still only extends a schedule that already exists. + if next_detect > 0.0 or hard_now: + next_detect = max(next_detect, now_mono + extra_now) + # A model pause is not a burst. Do not dump the extra reads when it ends. + burst_left = 0 + burst_cluster_s = 0.0 + model_extended = True + cloudlog.warning( + "%s", + format_backoff_timing( + extra_ms=extra_now * 1000.0, + infer_ms=last_infer_s * 1000.0, + engaged=sample.controlling, + reason=live_model, + backend=detector.backend_name(), + ), + ) + elif not live_model: + model_extended = False + if not sample.allow_detect: + abandoned = slot.pause() + if abandoned: + cloudlog.info("speedsignd abandon in-flight ONNX (%s)", engagement_log_fields(sample)) + else: + if should_reset_detect_after_wait(last_allow, sample.allow_detect): + next_detect = 0.0 + in_holdoff = False + slot.resume() + # Engaged + not yet compiled: drop a queued result. The worker also + # re-reads allow_compile before realize, so boot-already-engaged never + # enters clang. A realize that has already entered clang cannot be + # killed; that only happens after a known-disengaged start. + if sample.controlling and slot.busy and not detector.compile_ready(): + slot.pause() + if last_allow != sample.allow_detect or last_paused != sample.detect_paused: + cloudlog.info( + "speedsignd detect %s (%s)", + "paused" if not sample.allow_detect else "running", + engagement_log_fields(sample), + ) + last_allow = sample.allow_detect + last_paused = sample.detect_paused + if sample.unknown_after_grace and now_mono - last_unknown_warn >= INFER_LOG_PERIOD_S: + cloudlog.warning( + "speedsignd selfdriveState unread after %.1fs; allowing throttled detect (not WAIT) %s", + now_mono - started_at, engagement_log_fields(sample), + ) + last_unknown_warn = now_mono + if now_mono - last_timing_log >= INFER_LOG_PERIOD_S: + _log_infer_timing(cloudlog, infer_ms, skip_count, hz, sample.controlling, threads) + infer_ms = [] + skip_count = 0 + last_timing_log = now_mono + # Retry the weights read at nice 19, including while engaged. Install + # itself stays an offroad settings action and does not run here. + # Session create can compile. Do that only while not engaged. + if ( + sample.allow_detect and not sample.controlling and detector.onnx is None + and now_mono - last_onnx_try >= ONNX_RETRY_S + ): + last_onnx_try = now_mono + if detector.try_reload(): + cloudlog.info( + "speedsignd: ONNX loaded after retry backend=%s onnx=%s sha=%s", + detector.backend_name(), onnx_path, detector.weights_sha_short(), + ) + signs: list = [] + if sample.allow_detect: + outcome = slot.take() + if outcome is not None: + signs = outcome.signs + infer_ms.append(outcome.infer_s * 1000.0) + share = cpu_meter.sample(now_mono, read_proc_stat_jiffies()) + os_threads = read_proc_thread_count() + cloudlog.info( + "%s", + format_read_timing( + read_interval_ms=pending_interval_ms, + infer_ms=outcome.infer_s * 1000.0, + engaged=sample.controlling, + backoff=pending_backoff, + reason=pending_reason, + cpu_share=share, + threads=threads, + os_threads=os_threads, + backend=detector.backend_name(), + ), + ) + pressure = collect_host_pressure(sm) + model_reason = model_watch.reason() + hard = model_watch.hard_guard() + model_watch.consume() + reason = join_reasons( + pressure_reason(pressure), + model_reason, + "cpu-budget" if cpu_over_budget(share) else "", + ) + extra_s = model_guard_rest_s(outcome.infer_s, period_s, reason, hard) + scheduled_backoff = extra_s > 0.0 + scheduled_reason = reason or "pace" + if scheduled_backoff: + cloudlog.warning( + "%s", + format_backoff_timing( + extra_ms=extra_s * 1000.0, + infer_ms=outcome.infer_s * 1000.0, + engaged=sample.controlling, + reason=reason, + backend=detector.backend_name(), + ), + ) + raw = list(getattr(debounce, "last_raw", [])) + diag = outcome.diag if outcome.diag is not None else detector.diag_dict() + two = isinstance(diag, dict) and bool(diag.get("two_stage")) + if two: + t_frame = float(diag.get("t_frame", now_mono)) + tracker.update(diag.get("props") or [], t_frame) + read_tid = diag.get("read_tid") + if read_tid is not None: + for tr in tracker.tracks: + if tr.tid == read_tid: + tracker.mark_read(tr, got_mph=bool(signs), neg=two_stage.neg_read(diag.get("read_diag"))) + if signs and diag.get("read_jpg_meta") is not None: + top = max(signs, key=lambda s: float(s.conf)) + meta = dict(diag["read_jpg_meta"]) + meta.update( + mph=int(top.mph), conf=round(float(top.conf), 3), + refine_mph=None if getattr(top, "refine_mph", None) is None else int(top.refine_mph), + refine_conf=round(float(getattr(top, "refine_conf", 0.0) or 0.0), 3), + **{"class": (diag.get("read_diag") or {}).get("peak_name")}, + ) + two_stage.write_pending(meta, diag.get("read_jpg")) + ( + next_mono, burst_left, burst_window, window_i, burst_cluster_s, bursting_next, + ) = schedule_after_read( + now=now_mono, + infer_s=outcome.infer_s, + period_s=two_period_s if two else period_s, + budget_s=budget_s, + cap_s=cap_s, + backoff_s=extra_s, + sign_like=False if two else sign_burst_trigger(diag, raw), + window_used=pending_window, + window_count=1 if two else 2, + burst_left=burst_left, + burst_window=burst_window, + burst_cluster_s=burst_cluster_s, + spans=duty_spans, + ) + duty_spans.append((now_mono, outcome.infer_s)) + duty_spans = [(end, dur) for end, dur in duty_spans if now_mono - float(end) <= DUTY_WINDOW_S] + next_detect = max(next_detect, next_mono) + if bursting_next and not scheduled_backoff: + scheduled_reason = "burst" + err = f" err={outcome.error}" if outcome.error else "" + if outcome.error and not diag.get("error"): + diag = dict(diag) + diag["error"] = outcome.error + if two: + err = err + ( + f" two=props:{len(diag.get('props') or [])}/{float(diag.get('prop_ms') or 0.0):.0f}ms" + + f" read={diag.get('read_tid')} tracks={len(tracker.tracks)}" + ) + (cloudlog.debug if (two and diag.get("read_tid") is None) else cloudlog.info)( + "speedsignd infer %.0fms %s raw=%s hud=%s jsonl=%s%s", + outcome.infer_s * 1000.0, + format_infer_diag(diag, allow_detect=sample.allow_detect), + [(int(s.mph), round(float(s.conf), 2)) for s in raw], + [(int(s.mph), round(float(s.conf), 2)) for s in signs], + [w.get("mph") for w in outcome.written], + err, + ) + last_infer_done = now_mono + last_infer_s = outcome.infer_s + last_skip_reason = "ok" + # A burst re-reads the same tile with YOLO. The OCR second look would + # spend those frames and push the confirm past the sign. + if bursting_next or two: + second_look = None + else: + box = sign_like_bbox(outcome.signs, diag) + if box is not None: + second_look = PendingSecondLook( + bbox=box, + frames_left=SECOND_LOOK_FRAMES, + deadline=now_mono + SECOND_LOOK_DEADLINE_S, + ) + else: + second_look = None + if not raw and now_mono - last_empty_raw_log >= INFER_LOG_PERIOD_S: + cloudlog.info( + "speedsignd empty-raw %s", + format_infer_diag(diag, allow_detect=sample.allow_detect), + ) + last_empty_raw_log = now_mono + if sample.allow_detect and now_mono - last_gate_log >= INFER_LOG_PERIOD_S: + if last_infer_done == 0.0 or now_mono - last_infer_done >= INFER_LOG_PERIOD_S: + connected = client is not None and bool(getattr(client, "is_connected", lambda: False)()) + cloudlog.info( + "speedsignd waiting-infer reason=%s connected=%s busy=%s holdoff=%s onnx=%s allow=1", + last_skip_reason, connected, slot.busy, in_holdoff, detector.onnx is not None, + ) + last_gate_log = now_mono + if client is None or not client.is_connected(): + last_skip_reason = detect_skip_reason( + connected=False, onnx=detector.onnx is not None, busy=slot.busy, holdoff=in_holdoff, + ) + if now_mono - last_connect >= 0.5: + last_connect = now_mono + try: + if client is None: + client = _connect_road_camera() + client.connect(False) + except Exception: + client = None + elif not sample.allow_detect: + # Do not idle the ROAD client for the whole engage — first manual recv + # after WAIT used to timeout / return nothing while modeld stayed healthy. + drain_vision_latest(client) + elif ( + second_look is not None and sample.allow_detect and not slot.busy + and now_mono <= second_look.deadline + ): + buf = client.recv(timeout_ms=VISION_TIMEOUT_MS) + looked = second_look_sign(buf, second_look.bbox) if buf is not None else None + second_look.frames_left -= 1 + if looked is not None: + signs = list(signs) + [looked] + now_look = time.monotonic() + split = debounce.update_split([looked], now_look) + cloudlog.info( + "speedsignd second-look mph=%d conf=%.2f", + int(looked.mph), float(looked.conf), + ) + if split.confirmed: + lat, lon, bearing, gps_ok = gps_sample_from_sm(sm, now=now_look) + stalled = bool(sample.controlling) and disk_stalled(collect_host_pressure(sm)) + if gps_ok and not stalled: + for sign in split.confirmed: + rec = make_record(now_look, lat, lon, bearing, sign.mph, sign.conf) + if jsonl_line_is_light(rec): + logger.write(rec) + if second_look.frames_left <= 0 or now_mono > second_look.deadline: + second_look = None + elif sample.allow_detect and now_mono >= next_detect and not slot.busy: + in_holdoff = False + buf = client.recv(timeout_ms=VISION_TIMEOUT_MS) + # Engage can happen during the vision wait — re-read before ONNX. + sm.update(0) + observe_model(model_watch, sm) + sample = engagement_from_sm(sm, now=time.monotonic(), started_at=started_at) + if not sample.allow_detect: + slot.pause() + else: + which = window_i + speed_ms = two_stage.speed_from_sm(sm) + if ( + proposer.ok is False and not sample.controlling + and now_mono - last_proposer_try >= ONNX_RETRY_S + ): + last_proposer_try = now_mono + if proposer.load(): + cloudlog.info("speedsignd two-stage proposer loaded after retry") + use_two = proposer.ok and detector.onnx is not None and buf is not None + stopped_skip = False + if use_two and not two_stage.proposals_allowed(speed_ms): + # Stopped: no proposer, no read. Holds / plate unchanged. + next_detect = now_mono + two_period_s + last_skip_reason = "stopped" + if now_mono - last_stopped_log >= INFER_LOG_PERIOD_S: + cloudlog.info("speedsignd two-stage skip stopped v=%.1f", float(speed_ms or 0.0)) + last_stopped_log = now_mono + stopped_skip = True + use_two = False + nv12 = None + two_job = None + elif use_two: + strip = copy_nv12_rect(buf, two_stage.STRIP_RECT) + t_frame = time.monotonic() + cand = tracker.capture_candidate(t_frame) + cap = None + cap_rect = None + if cand is not None: + cap_rect = two_stage.capture_rect( + cand.predicted(t_frame), int(getattr(buf, "width", 1928) or 1928), + int(getattr(buf, "height", 1208) or 1208), + ) + cap = copy_nv12_rect(buf, cap_rect) + nv12 = cap if cap is not None else strip + two_job = (strip, cap, None if cand is None else cand.tid, cap_rect, t_frame) + else: + nv12 = copy_nv12_detect_crop(buf, which) if buf is not None else None + two_job = None + if stopped_skip: + pass + elif buf is None: + last_skip_reason = detect_skip_reason( + connected=True, onnx=detector.onnx is not None, busy=False, holdoff=False, + buf_empty=True, + ) + now_empty = time.monotonic() + if now_empty - last_empty_frame_log >= INFER_LOG_PERIOD_S: + cloudlog.info("speedsignd ROAD recv empty (timeout_ms=%d)", VISION_TIMEOUT_MS) + last_empty_frame_log = now_empty + elif nv12 is None: + last_skip_reason = detect_skip_reason( + connected=True, onnx=detector.onnx is not None, busy=False, holdoff=False, + parse_fail=True, + ) + now_empty = time.monotonic() + if now_empty - last_empty_frame_log >= INFER_LOG_PERIOD_S: + stride = getattr(buf, "stride", 0) + uv_off = getattr(buf, "uv_offset", 0) + cloudlog.info( + "speedsignd NV12 parse failed w=%s h=%s stride=%s uv_offset=%s", + getattr(buf, "width", None), getattr(buf, "height", None), stride, uv_off, + ) + last_empty_frame_log = now_empty + lat, lon, bearing, gps_ok = gps_sample_from_sm(sm, now=time.monotonic()) + # On-road: do not run numpy-mutcd when weights are missing (no fake mph / JSONL). + have_frame = detector.onnx is not None and nv12 is not None + if have_frame: + pressure_now = collect_host_pressure(sm) + stalled = bool(sample.controlling) and disk_stalled(pressure_now) + engaged_now = bool(sample.controlling) + + ready = detector.compile_ready() + # Compile only when this read is known-disengaged. Unknown cereal + # is not that. A warm cache (ready) runs while engaged, on CPU. + permitted = compile_allowed( + known=bool(sample.known), controlling=engaged_now, ready=ready, + ) + detector.allow_compile(permitted) + + def _run2(job=two_job, lat=lat, lon=lon, bearing=bearing, gps_ok=gps_ok, + engaged_now=engaged_now, stalled=stalled): + if not detector.compile_allowed_now(): + raise RuntimeError("compile-blocked while driving") + assert job is not None + strip_c, cap_c, tid, rect, t_fr = job + t0 = time.monotonic() + props = proposer.propose(strip_c) + prop_ms = (time.monotonic() - t0) * 1000.0 + signs_r: list = [] + written_r: list = [] + read_diag = None + jpg = None + if cap_c is not None: + signs_r, written_r = detect_if_allowed( + cap_c.y, lat, lon, bearing, gps_ok, detector, logger, time.monotonic(), + controlling=engaged_now, rgb=None, debounce=debounce, nv12=cap_c, + disk_stalled=stalled, + ) + read_diag = detector.diag_dict() + if signs_r and not (engaged_now and stalled): + jpg = two_stage.crop_jpeg_bytes(cap_c) + d = dict(read_diag or {}) + d.update( + two_stage=1, t_frame=t_fr, props=props, prop_ms=round(prop_ms, 1), + read_tid=tid, read_diag=read_diag, read_jpg=jpg, + read_jpg_meta=None if cap_c is None else dict( + t=round(time.time(), 3), # noqa: TID251 + track_id=tid, crop=list(rect) if rect else None, + lat=lat if gps_ok else None, lon=lon if gps_ok else None, + bearing=bearing if gps_ok else None, gps_ok=bool(gps_ok), + ), + ) + return signs_r, written_r, d + + def _run(nv12=nv12, lat=lat, lon=lon, bearing=bearing, gps_ok=gps_ok, + engaged_now=engaged_now, stalled=stalled): + # Live flag, not the value captured when this read was scheduled. + if not detector.compile_allowed_now(): + raise RuntimeError("compile-blocked while driving") + signs_w = detect_if_allowed( + nv12.y, lat, lon, bearing, gps_ok, detector, logger, time.monotonic(), + controlling=engaged_now, rgb=None, debounce=debounce, nv12=nv12, + disk_stalled=stalled, + ) + return signs_w[0], signs_w[1], detector.diag_dict() + + if not permitted: + last_skip_reason = "compile-wait" + next_detect = max(next_detect, time.monotonic() + 1.0) + if now_mono - last_gate_log >= INFER_LOG_PERIOD_S: + cloudlog.warning( + "%s", + format_backoff_timing( + extra_ms=1000.0, infer_ms=0.0, engaged=True, + reason="compile-wait", backend=detector.backend_name(), + ), + ) + last_gate_log = now_mono + elif slot.start(_run2 if two_job is not None else _run): + pending_window = which + now_start = time.monotonic() + pending_interval_ms = 0.0 if last_read_start <= 0.0 else (now_start - last_read_start) * 1000.0 + pending_backoff = scheduled_backoff + pending_reason = scheduled_reason + last_read_start = now_start + # Floor at one period. The outcome handler then applies the + # 3× idle duty cycle, which is longer whenever the infer is. + next_detect = now_start + (two_period_s if two_job is not None else period_s) + last_skip_reason = "ok" + else: + last_skip_reason = detect_skip_reason( + connected=True, onnx=True, busy=True, holdoff=False, + ) + elif detector.onnx is None: + last_skip_reason = detect_skip_reason( + connected=True, onnx=False, busy=slot.busy, holdoff=False, + ) + elif sample.allow_detect and (slot.busy or (next_detect > 0 and now_mono < next_detect)): + last_skip_reason = detect_skip_reason( + connected=True, onnx=detector.onnx is not None, busy=slot.busy, holdoff=True, + ) + if not in_holdoff: + skip_count += 1 + in_holdoff = True + if slot.busy: + try: + os.sched_yield() + except Exception: + pass + _publish_live( + pm, hold, signs, now_mono, messaging, + detector.weights_missing(), detect_paused=sample.detect_paused, + ) + rk.keep_time() + reset_ratekeeper_if_behind(rk, time.monotonic()) + + +if __name__ == "__main__": + main() diff --git a/selfdrive/speedsignd/tests/__init__.py b/selfdrive/speedsignd/tests/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/selfdrive/speedsignd/tests/onnxruntime_1.31.0_aarch64_namelist.txt b/selfdrive/speedsignd/tests/onnxruntime_1.31.0_aarch64_namelist.txt new file mode 100644 index 00000000000000..7ce504064796f6 --- /dev/null +++ b/selfdrive/speedsignd/tests/onnxruntime_1.31.0_aarch64_namelist.txt @@ -0,0 +1,353 @@ +onnxruntime/ +onnxruntime/LICENSE +onnxruntime/Privacy.md +onnxruntime/ThirdPartyNotices.txt +onnxruntime/__init__.py +onnxruntime/backend/ +onnxruntime/backend/__init__.py +onnxruntime/backend/backend.py +onnxruntime/backend/backend_rep.py +onnxruntime/capi/ +onnxruntime/capi/__init__.py +onnxruntime/capi/_ld_preload.py +onnxruntime/capi/_pybind_state.py +onnxruntime/capi/build_and_package_info.py +onnxruntime/capi/convert_npz_to_onnx_adapter.py +onnxruntime/capi/libonnxruntime.so.1.31.0 +onnxruntime/capi/libonnxruntime_providers_shared.so +onnxruntime/capi/onnxruntime_collect_build_info.py +onnxruntime/capi/onnxruntime_inference_collection.py +onnxruntime/capi/onnxruntime_pybind11_state.cpython-312-aarch64-linux-gnu.so +onnxruntime/capi/onnxruntime_validation.py +onnxruntime/datasets/ +onnxruntime/datasets/__init__.py +onnxruntime/datasets/logreg_iris.onnx +onnxruntime/datasets/mul_1.onnx +onnxruntime/datasets/sigmoid.onnx +onnxruntime/quantization/ +onnxruntime/quantization/__init__.py +onnxruntime/quantization/base_quantizer.py +onnxruntime/quantization/calibrate.py +onnxruntime/quantization/cuda_quantizer.py +onnxruntime/quantization/matmul_bnb4_quantizer.py +onnxruntime/quantization/matmul_nbits_quantizer.py +onnxruntime/quantization/onnx_model.py +onnxruntime/quantization/onnx_quantizer.py +onnxruntime/quantization/preprocess.py +onnxruntime/quantization/qdq_loss_debug.py +onnxruntime/quantization/qdq_quantizer.py +onnxruntime/quantization/quant_utils.py +onnxruntime/quantization/quantize.py +onnxruntime/quantization/registry.py +onnxruntime/quantization/shape_inference.py +onnxruntime/quantization/static_quantize_runner.py +onnxruntime/quantization/tensor_quant_overrides.py +onnxruntime/quantization/CalTableFlatBuffers/ +onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py +onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py +onnxruntime/quantization/CalTableFlatBuffers/__init__.py +onnxruntime/quantization/execution_providers/ +onnxruntime/quantization/execution_providers/qnn/ +onnxruntime/quantization/execution_providers/qnn/__init__.py +onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.py +onnxruntime/quantization/execution_providers/qnn/fusion_spacetodepth.py +onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.py +onnxruntime/quantization/execution_providers/qnn/preprocess.py +onnxruntime/quantization/execution_providers/qnn/quant_config.py +onnxruntime/quantization/fusions/ +onnxruntime/quantization/fusions/__init__.py +onnxruntime/quantization/fusions/fusion.py +onnxruntime/quantization/fusions/fusion_gelu.py +onnxruntime/quantization/fusions/fusion_layernorm.py +onnxruntime/quantization/fusions/replace_upsample_with_resize.py +onnxruntime/quantization/neural_compressor/ +onnxruntime/quantization/neural_compressor/__init__.py +onnxruntime/quantization/neural_compressor/onnx_model.py +onnxruntime/quantization/neural_compressor/util.py +onnxruntime/quantization/neural_compressor/weight_only.py +onnxruntime/quantization/operators/ +onnxruntime/quantization/operators/__init__.py +onnxruntime/quantization/operators/activation.py +onnxruntime/quantization/operators/argmax.py +onnxruntime/quantization/operators/attention.py +onnxruntime/quantization/operators/base_operator.py +onnxruntime/quantization/operators/binary_op.py +onnxruntime/quantization/operators/concat.py +onnxruntime/quantization/operators/conv.py +onnxruntime/quantization/operators/direct_q8.py +onnxruntime/quantization/operators/embed_layernorm.py +onnxruntime/quantization/operators/gather.py +onnxruntime/quantization/operators/gavgpool.py +onnxruntime/quantization/operators/gemm.py +onnxruntime/quantization/operators/lstm.py +onnxruntime/quantization/operators/matmul.py +onnxruntime/quantization/operators/maxpool.py +onnxruntime/quantization/operators/norm.py +onnxruntime/quantization/operators/pad.py +onnxruntime/quantization/operators/pooling.py +onnxruntime/quantization/operators/qdq_base_operator.py +onnxruntime/quantization/operators/resize.py +onnxruntime/quantization/operators/softmax.py +onnxruntime/quantization/operators/split.py +onnxruntime/quantization/operators/where.py +onnxruntime/tools/ +onnxruntime/tools/__init__.py +onnxruntime/tools/check_onnx_model_mobile_usability.py +onnxruntime/tools/convert_onnx_models_to_ort.py +onnxruntime/tools/file_utils.py +onnxruntime/tools/logger.py +onnxruntime/tools/make_dynamic_shape_fixed.py +onnxruntime/tools/offline_tuning.py +onnxruntime/tools/onnx_model_utils.py +onnxruntime/tools/onnx_randomizer.py +onnxruntime/tools/onnxruntime_test.py +onnxruntime/tools/optimize_onnx_model.py +onnxruntime/tools/pytorch_export_contrib_ops.py +onnxruntime/tools/pytorch_export_helpers.py +onnxruntime/tools/reduced_build_config_parser.py +onnxruntime/tools/remove_initializer_from_input.py +onnxruntime/tools/symbolic_shape_infer.py +onnxruntime/tools/update_onnx_opset.py +onnxruntime/tools/mobile_helpers/ +onnxruntime/tools/mobile_helpers/__init__.py +onnxruntime/tools/mobile_helpers/coreml_supported_mlprogram_ops.md +onnxruntime/tools/mobile_helpers/coreml_supported_neuralnetwork_ops.md +onnxruntime/tools/mobile_helpers/nnapi_supported_ops.md +onnxruntime/tools/mobile_helpers/usability_checker.py +onnxruntime/tools/ort_format_model/ +onnxruntime/tools/ort_format_model/__init__.py +onnxruntime/tools/ort_format_model/operator_type_usage_processors.py +onnxruntime/tools/ort_format_model/ort_model_processor.py +onnxruntime/tools/ort_format_model/types.py +onnxruntime/tools/ort_format_model/utils.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/ +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/__init__.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgType.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgTypeAndIndex.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Attribute.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/AttributeType.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Checkpoint.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedKernelCreateInfos.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedNodeIndexAndKernelDefHash.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSessionState.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSubGraphSessionState.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Dimension.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValue.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValueType.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/EdgeEnd.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/FloatProperty.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Graph.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/InferenceSession.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/IntProperty.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrArgsEntry.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrResolver.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/MapType.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Model.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ModuleState.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Node.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeEdge.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeType.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodesToOptimizeIndices.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OpIdKernelTypeStrArgsEntry.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OperatorSetId.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OptimizerGroup.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ParameterOptimizerState.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/PropertyBag.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecord.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecordContainerEntry.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizations.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SequenceType.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Shape.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SparseTensor.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringProperty.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringStringEntry.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Tensor.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorDataType.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorTypeAndShape.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfo.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfoValue.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ValueInfo.py +onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__init__.py +onnxruntime/tools/qdq_helpers/ +onnxruntime/tools/qdq_helpers/__init__.py +onnxruntime/tools/qdq_helpers/optimize_qdq_model.py +onnxruntime/tools/qnn/ +onnxruntime/tools/qnn/add_trans_cast.py +onnxruntime/tools/qnn/gen_qnn_ctx_onnx_model.py +onnxruntime/tools/qnn/preprocess.py +onnxruntime/transformers/ +onnxruntime/transformers/__init__.py +onnxruntime/transformers/affinity_helper.py +onnxruntime/transformers/benchmark.py +onnxruntime/transformers/benchmark_helper.py +onnxruntime/transformers/bert_perf_test.py +onnxruntime/transformers/bert_test_data.py +onnxruntime/transformers/compare_bert_results.py +onnxruntime/transformers/constants.py +onnxruntime/transformers/convert_generation.py +onnxruntime/transformers/convert_tf_models_to_pytorch.py +onnxruntime/transformers/convert_to_packing_mode.py +onnxruntime/transformers/dynamo_onnx_helper.py +onnxruntime/transformers/float16.py +onnxruntime/transformers/fusion_attention.py +onnxruntime/transformers/fusion_attention_clip.py +onnxruntime/transformers/fusion_attention_sam2.py +onnxruntime/transformers/fusion_attention_unet.py +onnxruntime/transformers/fusion_attention_vae.py +onnxruntime/transformers/fusion_bart_attention.py +onnxruntime/transformers/fusion_base.py +onnxruntime/transformers/fusion_bias_add.py +onnxruntime/transformers/fusion_biasgelu.py +onnxruntime/transformers/fusion_biassplitgelu.py +onnxruntime/transformers/fusion_conformer_attention.py +onnxruntime/transformers/fusion_constant_fold.py +onnxruntime/transformers/fusion_embedlayer.py +onnxruntime/transformers/fusion_fastgelu.py +onnxruntime/transformers/fusion_gelu.py +onnxruntime/transformers/fusion_gelu_approximation.py +onnxruntime/transformers/fusion_gemmfastgelu.py +onnxruntime/transformers/fusion_gpt_attention.py +onnxruntime/transformers/fusion_gpt_attention_megatron.py +onnxruntime/transformers/fusion_gpt_attention_no_past.py +onnxruntime/transformers/fusion_group_norm.py +onnxruntime/transformers/fusion_layernorm.py +onnxruntime/transformers/fusion_mha_dit.py +onnxruntime/transformers/fusion_mha_mmdit.py +onnxruntime/transformers/fusion_nhwc_conv.py +onnxruntime/transformers/fusion_options.py +onnxruntime/transformers/fusion_qordered_attention.py +onnxruntime/transformers/fusion_qordered_gelu.py +onnxruntime/transformers/fusion_qordered_layernorm.py +onnxruntime/transformers/fusion_qordered_matmul.py +onnxruntime/transformers/fusion_quickgelu.py +onnxruntime/transformers/fusion_reshape.py +onnxruntime/transformers/fusion_rotary_attention.py +onnxruntime/transformers/fusion_shape.py +onnxruntime/transformers/fusion_simplified_layernorm.py +onnxruntime/transformers/fusion_skip_group_norm.py +onnxruntime/transformers/fusion_skiplayernorm.py +onnxruntime/transformers/fusion_transpose.py +onnxruntime/transformers/fusion_utils.py +onnxruntime/transformers/huggingface_models.py +onnxruntime/transformers/import_utils.py +onnxruntime/transformers/io_binding_helper.py +onnxruntime/transformers/large_model_exporter.py +onnxruntime/transformers/machine_info.py +onnxruntime/transformers/metrics.py +onnxruntime/transformers/onnx_exporter.py +onnxruntime/transformers/onnx_model.py +onnxruntime/transformers/onnx_model_bart.py +onnxruntime/transformers/onnx_model_bert.py +onnxruntime/transformers/onnx_model_bert_keras.py +onnxruntime/transformers/onnx_model_bert_tf.py +onnxruntime/transformers/onnx_model_clip.py +onnxruntime/transformers/onnx_model_conformer.py +onnxruntime/transformers/onnx_model_gpt2.py +onnxruntime/transformers/onnx_model_mmdit.py +onnxruntime/transformers/onnx_model_phi.py +onnxruntime/transformers/onnx_model_sam2.py +onnxruntime/transformers/onnx_model_t5.py +onnxruntime/transformers/onnx_model_tnlr.py +onnxruntime/transformers/onnx_model_unet.py +onnxruntime/transformers/onnx_model_vae.py +onnxruntime/transformers/onnx_utils.py +onnxruntime/transformers/optimizer.py +onnxruntime/transformers/past_helper.py +onnxruntime/transformers/profile_result_processor.py +onnxruntime/transformers/profiler.py +onnxruntime/transformers/quantize_helper.py +onnxruntime/transformers/shape_infer_helper.py +onnxruntime/transformers/shape_optimizer.py +onnxruntime/transformers/torch_onnx_export_helper.py +onnxruntime/transformers/models/ +onnxruntime/transformers/models/bart/ +onnxruntime/transformers/models/bart/__init__.py +onnxruntime/transformers/models/bart/export.py +onnxruntime/transformers/models/bert/ +onnxruntime/transformers/models/bert/__init__.py +onnxruntime/transformers/models/bert/eval_squad.py +onnxruntime/transformers/models/gpt2/ +onnxruntime/transformers/models/gpt2/__init__.py +onnxruntime/transformers/models/gpt2/benchmark_gpt2.py +onnxruntime/transformers/models/gpt2/convert_to_onnx.py +onnxruntime/transformers/models/gpt2/gpt2_helper.py +onnxruntime/transformers/models/gpt2/gpt2_parity.py +onnxruntime/transformers/models/gpt2/gpt2_tester.py +onnxruntime/transformers/models/gpt2/parity_check_helper.py +onnxruntime/transformers/models/llama/ +onnxruntime/transformers/models/llama/__init__.py +onnxruntime/transformers/models/llama/benchmark.py +onnxruntime/transformers/models/llama/benchmark_all.py +onnxruntime/transformers/models/llama/benchmark_e2e.py +onnxruntime/transformers/models/llama/convert_to_onnx.py +onnxruntime/transformers/models/llama/dist_settings.py +onnxruntime/transformers/models/llama/llama_inputs.py +onnxruntime/transformers/models/llama/llama_parity.py +onnxruntime/transformers/models/llama/llama_torch.py +onnxruntime/transformers/models/llama/quant_kv_dataloader.py +onnxruntime/transformers/models/longformer/ +onnxruntime/transformers/models/longformer/__init__.py +onnxruntime/transformers/models/longformer/benchmark_longformer.py +onnxruntime/transformers/models/longformer/convert_to_onnx.py +onnxruntime/transformers/models/longformer/generate_test_data.py +onnxruntime/transformers/models/longformer/longformer_helper.py +onnxruntime/transformers/models/phi2/ +onnxruntime/transformers/models/phi2/__init__.py +onnxruntime/transformers/models/phi2/convert_to_onnx.py +onnxruntime/transformers/models/phi2/inference_example.py +onnxruntime/transformers/models/sam2/ +onnxruntime/transformers/models/sam2/__init__.py +onnxruntime/transformers/models/sam2/benchmark_sam2.py +onnxruntime/transformers/models/sam2/convert_to_onnx.py +onnxruntime/transformers/models/sam2/image_decoder.py +onnxruntime/transformers/models/sam2/image_encoder.py +onnxruntime/transformers/models/sam2/mask_decoder.py +onnxruntime/transformers/models/sam2/nvtx_helper.py +onnxruntime/transformers/models/sam2/prompt_encoder.py +onnxruntime/transformers/models/sam2/sam2_demo.py +onnxruntime/transformers/models/sam2/sam2_image_onnx_predictor.py +onnxruntime/transformers/models/sam2/sam2_utils.py +onnxruntime/transformers/models/stable_diffusion/ +onnxruntime/transformers/models/stable_diffusion/__init__.py +onnxruntime/transformers/models/stable_diffusion/benchmark.py +onnxruntime/transformers/models/stable_diffusion/benchmark_controlnet.py +onnxruntime/transformers/models/stable_diffusion/demo_txt2img.py +onnxruntime/transformers/models/stable_diffusion/demo_txt2img_xl.py +onnxruntime/transformers/models/stable_diffusion/demo_utils.py +onnxruntime/transformers/models/stable_diffusion/diffusion_models.py +onnxruntime/transformers/models/stable_diffusion/diffusion_schedulers.py +onnxruntime/transformers/models/stable_diffusion/engine_builder.py +onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_cuda.py +onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_trt.py +onnxruntime/transformers/models/stable_diffusion/engine_builder_tensorrt.py +onnxruntime/transformers/models/stable_diffusion/engine_builder_torch.py +onnxruntime/transformers/models/stable_diffusion/optimize_pipeline.py +onnxruntime/transformers/models/stable_diffusion/ort_optimizer.py +onnxruntime/transformers/models/stable_diffusion/pipeline_stable_diffusion.py +onnxruntime/transformers/models/stable_diffusion/trt_utilities.py +onnxruntime/transformers/models/t5/ +onnxruntime/transformers/models/t5/__init__.py +onnxruntime/transformers/models/t5/convert_to_onnx.py +onnxruntime/transformers/models/t5/t5_decoder.py +onnxruntime/transformers/models/t5/t5_encoder.py +onnxruntime/transformers/models/t5/t5_encoder_decoder_init.py +onnxruntime/transformers/models/t5/t5_helper.py +onnxruntime/transformers/models/whisper/ +onnxruntime/transformers/models/whisper/__init__.py +onnxruntime/transformers/models/whisper/benchmark.py +onnxruntime/transformers/models/whisper/benchmark_all.py +onnxruntime/transformers/models/whisper/convert_to_onnx.py +onnxruntime/transformers/models/whisper/whisper_chain.py +onnxruntime/transformers/models/whisper/whisper_decoder.py +onnxruntime/transformers/models/whisper/whisper_encoder.py +onnxruntime/transformers/models/whisper/whisper_encoder_decoder_init.py +onnxruntime/transformers/models/whisper/whisper_helper.py +onnxruntime/transformers/models/whisper/whisper_inputs.py +onnxruntime/transformers/models/whisper/whisper_jump_times.py +onnxruntime-1.31.0.dist-info/ +onnxruntime-1.31.0.dist-info/METADATA +onnxruntime-1.31.0.dist-info/WHEEL +onnxruntime-1.31.0.dist-info/entry_points.txt +onnxruntime-1.31.0.dist-info/top_level.txt +onnxruntime-1.31.0.dist-info/RECORD diff --git a/selfdrive/speedsignd/tests/test_answer_gate.py b/selfdrive/speedsignd/tests/test_answer_gate.py new file mode 100644 index 00000000000000..a9165b23fc228b --- /dev/null +++ b/selfdrive/speedsignd/tests/test_answer_gate.py @@ -0,0 +1,31 @@ +from openpilot.selfdrive.speedsignd.hud import AnswerGate, LiveSignView, REASK_SUPPRESS_S, hud_confirm_visible + + +def v(mph): + return LiveSignView(show_mph=mph > 0, mph=mph) + + +def test_yes_or_no_hides_popup_and_no_reask(): + for yes in (True, False): + g = AnswerGate() + assert hud_confirm_visible(g.filter(v(35), 0.0)) + g.answer(35, yes, 1.0) + assert not g.filter(v(35), 1.0).show + assert not g.filter(v(0), 5.0).show + assert not g.filter(v(35), REASK_SUPPRESS_S - 1).show + assert not g.filter(v(35), REASK_SUPPRESS_S + 5).show # same mph still live + assert not g.filter(v(0), REASK_SUPPRESS_S + 6).show + assert hud_confirm_visible(g.filter(v(35), REASK_SUPPRESS_S + 7)) + + +def test_different_mph_asks_again(): + g = AnswerGate() + g.answer(40, True, 0.0) + assert hud_confirm_visible(g.filter(v(30), 1.0)) + + +def test_diagnostic_plates_pass(): + g = AnswerGate() + g.answer(40, False, 0.0) + w = LiveSignView(show_missing_weights=True) + assert g.filter(w, 1.0) is w diff --git a/selfdrive/speedsignd/tests/test_debounce.py b/selfdrive/speedsignd/tests/test_debounce.py new file mode 100644 index 00000000000000..1819ec8d4bcff6 --- /dev/null +++ b/selfdrive/speedsignd/tests/test_debounce.py @@ -0,0 +1,183 @@ +"""JSONL confirms on two agreeing reads. One class-only read does not.""" +from __future__ import annotations + +from openpilot.selfdrive.speedsignd.debounce import SignDebounce +from openpilot.selfdrive.speedsignd.detect import SpeedSign +from openpilot.selfdrive.speedsignd.jsonl import JsonlLogger +from openpilot.selfdrive.speedsignd.speedsignd import SPEEDSIGND_HZ, next_detect_mono, process_frame +from openpilot.selfdrive.speedsignd.weights_manifest import DEBOUNCE_HITS, DEBOUNCE_WINDOW_S + + +def test_single_frame_is_not_enough(): + d = SignDebounce() + signs = [SpeedSign(mph=55, conf=0.9, bbox=(1, 1, 10, 10))] + assert d.update(signs, 0.0) == [] + + +def test_two_agreeing_frames_confirm(): + d = SignDebounce() + s = SpeedSign(mph=55, conf=0.8, bbox=(2, 2, 12, 12)) + assert d.update([s], 0.0) == [] + # 1 Hz spacing (and a skipped cycle at ~2 s) must still confirm. + out = d.update([s], 1.0) + assert len(out) == 1 and out[0].mph == 55 + + +def test_two_hits_after_skip_still_confirm(): + d = SignDebounce() + s = SpeedSign(mph=55, conf=0.85, bbox=(0, 0, 8, 8)) + assert d.update([s], 0.0) == [] + out = d.update([s], 2.0) + assert len(out) == 1 and out[0].mph == 55 + + +def test_disagreement_does_not_confirm(): + d = SignDebounce() + d.update([SpeedSign(mph=55, conf=0.9, bbox=(0, 0, 1, 1))], 0.0) + assert d.update([SpeedSign(mph=60, conf=0.9, bbox=(0, 0, 1, 1))], 1.0) == [] + + +def test_stale_hit_expires(): + d = SignDebounce() + s = SpeedSign(mph=55, conf=0.9, bbox=(0, 0, 1, 1)) + d.update([s], 0.0) + assert d.update([s], DEBOUNCE_WINDOW_S + 0.01) == [] + + +def test_low_conf_ignored(): + d = SignDebounce() + s = SpeedSign(mph=55, conf=0.2, bbox=(0, 0, 1, 1)) + d.update([s], 0.0) + assert d.update([s], 1.0) == [] + + +def test_process_frame_debounce_blocks_jsonl(tmp_path): + class _Det: + onnx = None + + def detect(self, y, min_conf=None, rgb=None, nv12=None): + return [SpeedSign(mph=55, conf=0.9, bbox=(0, 0, 8, 8))] + + log = JsonlLogger(str(tmp_path / "out.jsonl")) + debounce = SignDebounce() + y = __import__("numpy").zeros((32, 32), __import__("numpy").uint8) + signs, written = process_frame(y, 45.0, -95.0, 0.0, True, _Det(), log, now=1.0, debounce=debounce) + # First in-threshold hit lights HUD; JSONL still waits for the second frame. + assert signs and signs[0].mph == 55 + assert written == [] + signs, written = process_frame(y, 45.0, -95.0, 0.0, True, _Det(), log, now=2.0, debounce=debounce) + assert signs and signs[0].mph == 55 + assert written and written[0]["mph"] == 55 + + +def test_update_split_hud_on_first_hit(): + d = SignDebounce() + s = SpeedSign(mph=55, conf=0.72, bbox=(0, 0, 8, 8)) + split = d.update_split([s], 0.0) + assert split.hud and split.hud[0].mph == 55 + assert split.confirmed == [] + split = d.update_split([s], 1.0) + assert split.hud and split.confirmed + assert split.confirmed[0].mph == 55 + + +def test_duty_cycle_gap_two_yolo_reads_confirm_inside_12s(): + """A 2.1 s infer waits 8.4 s. That fits the 12 s window, so the next YOLO confirms. + + A class/OCR contradiction on the second look does not. + """ + period, budget = 1.0 / SPEEDSIGND_HZ, 0.100 + infer_s = 2.1 + second_t = next_detect_mono(infer_s, infer_s, period, budget) + assert abs(second_t - infer_s * 4.0) < 1e-9 + assert second_t < DEBOUNCE_WINDOW_S + d = SignDebounce() + first_sign = SpeedSign( + mph=55, conf=0.8, bbox=(0, 0, 8, 8), + class_mph=55, class_conf=0.8, refine_mph=55, refine_conf=0.8, + ) + first = d.update_split([first_sign], 0.0) + assert first.hud and first.confirmed == [] + clash = SpeedSign( + mph=55, conf=0.62, bbox=(0, 0, 8, 8), + class_mph=65, class_conf=0.70, refine_mph=55, refine_conf=0.62, + ) + assert d.update_split([clash], 0.1).confirmed == [] + late = d.update_split([first_sign], second_t) + assert late.confirmed and late.confirmed[0].mph == 55 + # A 4 s infer gaps 16 s, past the window: a miss, not a one-frame plate. + slow = next_detect_mono(4.0, 4.0, period, budget) + assert slow > DEBOUNCE_WINDOW_S + + +def test_debounce_constants_match_duty_gap(): + assert SPEEDSIGND_HZ == 1.0 + assert DEBOUNCE_HITS == 2 + assert DEBOUNCE_WINDOW_S == 12.0 + # Two duty-cycled reads at a ~3 s infer (12 s apart) still fit. + assert DEBOUNCE_WINDOW_S >= 4.0 * 3.0 + assert DEBOUNCE_WINDOW_S >= 2.0 / SPEEDSIGND_HZ + + +def test_update_split_one_unrefined_read_does_not_confirm(): + """Class-only ≥0.70 is handed to the plate. It still does not write JSONL.""" + d = SignDebounce() + for i, mph in enumerate((40, 60, 65, 70)): + bad = SpeedSign(mph=mph, conf=0.73, bbox=(0, 0, 8, 8), class_mph=mph, class_conf=0.73) + split = d.update_split([bad], float(i) * 3.0) + assert split.hud and split.hud[0].mph == mph + assert split.confirmed == [] + low = SpeedSign(mph=45, conf=0.60, bbox=(0, 0, 8, 8), class_mph=45, class_conf=0.60) + assert d.update_split([low], 100.0).hud == [] + assert d.update_split([low], 101.0).confirmed == [] + + +def test_contradiction_does_not_confirm_and_two_ocr_frames_do(): + d = SignDebounce() + mixed = SpeedSign( + mph=50, conf=0.71, bbox=(0, 0, 8, 8), + class_mph=65, class_conf=0.82, refine_mph=50, refine_conf=0.71, + ) + assert d.update_split([mixed], 0.0).confirmed == [] + assert d.update_split([mixed], 0.2).confirmed == [] + ocr = SpeedSign( + mph=50, conf=0.71, bbox=(0, 0, 8, 8), + class_mph=None, refine_mph=50, refine_conf=0.71, + ) + assert d.update_split([ocr], 1.0).confirmed == [] + split = d.update_split([ocr], 1.2) + assert split.confirmed and split.confirmed[0].mph == 50 + + +def test_update_split_one_unrefined_65_is_not_confirmed(): + d = SignDebounce() + bad = SpeedSign( + mph=65, conf=0.73, bbox=(0, 0, 8, 8), + class_mph=65, class_conf=0.73, refine_mph=None, + ) + split = d.update_split([bad], 0.0) + assert split.hud and split.hud[0].mph == 65 and split.confirmed == [] + assert d.last_raw and d.last_raw[0].mph == 65 + again = d.update_split([bad], 0.3) + assert again.confirmed == [] + assert again.hud and again.hud[0].mph == 65 + + +def test_unreadable_and_negative_never_confirm(): + d = SignDebounce() + unread = SpeedSign(mph=0, conf=0.90, bbox=(1, 1, 20, 20), class_mph=None) + neg = SpeedSign(mph=0, conf=0.90, bbox=(1, 1, 20, 20), class_mph=None, refine_mph=None) + assert d.update_split([unread], 0.0).confirmed == [] + assert d.update_split([unread, neg], 1.0).confirmed == [] + assert d.last_raw == [] + + +def test_update_split_contradiction_is_not_a_hud_vote(): + d = SignDebounce() + s = SpeedSign( + mph=50, conf=0.71, bbox=(0, 0, 8, 8), + class_mph=65, class_conf=0.82, refine_mph=50, refine_conf=0.71, + ) + split = d.update_split([s], 0.0) + assert split.hud == [] + assert split.confirmed == [] diff --git a/selfdrive/speedsignd/tests/test_detect.py b/selfdrive/speedsignd/tests/test_detect.py new file mode 100644 index 00000000000000..b854843e793d00 --- /dev/null +++ b/selfdrive/speedsignd/tests/test_detect.py @@ -0,0 +1,314 @@ +"""Tests for MUTCD numeric speed-sign detection (no modelV2 head).""" +from __future__ import annotations + +import numpy as np +import pytest + +from openpilot.selfdrive.speedsignd.detect import ( + MUTCD_MPH, + OnnxSpeedSignDetector, + SpeedSignDetector, + detect_mutcd_speed_signs, + paint_mutcd_r2_1, +) +from openpilot.selfdrive.speedsignd.nv12 import y_plane_from_nv12 + + +def _scene(h=240, w=320, seed=0) -> np.ndarray: + rng = np.random.default_rng(seed) + y = np.full((h, w), 70, np.uint8) + y += rng.integers(0, 12, size=(h, w), dtype=np.uint8) + return y + + +def test_mutcd_numeric_sign_is_read(): + y = _scene() + paint_mutcd_r2_1(y, 45, x=200, y=30, w=90, h=112) + hits = detect_mutcd_speed_signs(y) + assert hits, "expected a MUTCD 45 mph detection" + assert hits[0].mph == 45 + assert hits[0].conf >= 0.42 + + +def test_several_mutcd_speeds(): + for mph in (15, 25, 30, 40, 45, 55, 60, 70, 80): + y = _scene(seed=mph) + paint_mutcd_r2_1(y, mph, x=190, y=24, w=96, h=120) + hits = detect_mutcd_speed_signs(y) + assert hits, f"missed {mph}" + assert hits[0].mph == mph + + +def test_empty_road_is_not_a_sign(): + y = _scene(seed=99) + assert detect_mutcd_speed_signs(y) == [] + + +def test_license_plate_aspect_is_rejected(): + y = _scene() + # Wide white plate (license-like), not R2-1. + y[160:190, 80:220] = 230 + y[168:182, 95:110] = 20 + y[168:182, 120:140] = 20 + y[168:182, 150:170] = 20 + assert detect_mutcd_speed_signs(y) == [] + + +def test_try_load_refuses_sha_mismatch(tmp_path, monkeypatch): + from openpilot.selfdrive.speedsignd.install import MIN_ONNX_BYTES + path = tmp_path / "speed_sign.onnx" + path.write_bytes(b"v1" * MIN_ONNX_BYTES) + opened = [] + + def boom(*_a, **_k): + opened.append(1) + raise AssertionError("mismatched sha must not open a session") + + monkeypatch.setattr("openpilot.selfdrive.speedsignd.detect._onnx_session", boom) + assert OnnxSpeedSignDetector.try_load(str(path)) is None + assert opened == [] + + +def test_detector_falls_back_without_onnx(tmp_path, monkeypatch): + missing = str(tmp_path / "nope.onnx") + monkeypatch.setenv("NAP_SPEED_SIGN_ONNX", missing) + det = SpeedSignDetector(onnx_path=missing) + assert det.onnx is None + assert det.weights_missing() + y = _scene() + paint_mutcd_r2_1(y, 35, x=200, y=30, w=90, h=112) + hits = det.detect(y) + assert hits and hits[0].mph == 35 + + +def test_try_reload_picks_up_onnx_after_install(tmp_path, monkeypatch): + path = str(tmp_path / "later.onnx") + det = SpeedSignDetector(onnx_path=path) + assert det.weights_missing() + assert not det.try_reload() + + class Sess: + def get_inputs(self): + return [type("I", (), {"name": "image", "shape": [1, 1, 32, 32]})()] + + def run(self, _out, _feed): + return [np.array([[0.0, 0.0, 10.0, 10.0, 45.0, 0.9]], dtype=np.float32)] + + def _fake_load(cls, p=None): + return OnnxSpeedSignDetector(path, Sess()) + + monkeypatch.setattr(OnnxSpeedSignDetector, "try_load", classmethod(_fake_load)) + assert det.try_reload() + assert not det.weights_missing() + assert not det.try_reload() + + +def test_onnx_parse_and_mutcd_filter(): + class Sess: + def get_inputs(self): + return [type("I", (), {"name": "image", "shape": [1, 1, 64, 64]})()] + + def run(self, _out, _feed): + return [np.array([[10.0, 10.0, 40.0, 50.0, 45.0, 0.9]], dtype=np.float32)] + + det = OnnxSpeedSignDetector("/tmp/fake.onnx", Sess()) + y = np.zeros((64, 64), np.uint8) + hits = det.detect(y) + assert len(hits) == 1 + assert hits[0].mph == 45 + assert hits[0].conf == pytest.approx(0.9, abs=1e-5) + + +def test_onnx_rejects_non_mutcd_mph(): + class Sess: + def get_inputs(self): + return [type("I", (), {"name": "image", "shape": [1, 1, 32, 32]})()] + + def run(self, _out, _feed): + return [np.array([[0.0, 0.0, 10.0, 10.0, 47.0, 0.99]], dtype=np.float32)] + + hits = OnnxSpeedSignDetector("x", Sess()).detect(np.zeros((32, 32), np.uint8)) + assert hits == [] + + +def test_y_plane_from_nv12(): + class Buf: + width = 4 + height = 2 + stride = 4 + data = bytes([1, 2, 3, 4, 5, 6, 7, 8]) + bytes(8) + + y = y_plane_from_nv12(Buf()) + assert y is not None + assert y.shape == (2, 4) + assert int(y[0, 0]) == 1 + + +def test_mutcd_set_is_us_r2_1(): + assert 15 in MUTCD_MPH and 25 in MUTCD_MPH and 70 in MUTCD_MPH + assert 47 not in MUTCD_MPH + + +def test_cpu_backend_assertion_rejects_gpu_and_accepts_cpu(): + import os + + from openpilot.selfdrive.speedsignd.detect import ( + _TinyOrtSession, + assert_cpu_backend, + compile_allowed, + describe_infer_runtimes, + dnn_ids_are_cpu, + pin_cpu_only_env, + ) + + pin_cpu_only_env() + assert os.environ["DEV"] == "CPU" + assert os.environ["CPU_COUNT"] == "1" + assert os.environ["CLANG"] == "1" + assert os.environ["BEAM"] == "0" + assert os.environ["NOOPT"] == "0" + assert os.environ["OMP_NUM_THREADS"] == "1" + for key in ("GPU", "QCOM", "CUDA", "METAL", "AMD", "NV", "WEBGPU"): + assert os.environ[key] == "0" + + class CpuOrt: + def get_providers(self): + return ["CPUExecutionProvider"] + + assert assert_cpu_backend(CpuOrt()) == "onnxruntime-cpu" + + class GpuOrt: + def get_providers(self): + return ["QNNExecutionProvider", "CPUExecutionProvider"] + + with pytest.raises(AssertionError): + assert_cpu_backend(GpuOrt()) + + class Tiny: + _nap_backend = "tinygrad-cpu" + _nap_device = "CPU" + + assert assert_cpu_backend(Tiny()) == "tinygrad-cpu" + + class Qcom: + _nap_backend = "tinygrad" + _nap_device = "QCOM" + + with pytest.raises(AssertionError): + assert_cpu_backend(Qcom()) + + assert not compile_allowed(known=True, controlling=True, ready=False) + assert compile_allowed(known=True, controlling=False, ready=False) + assert not compile_allowed(known=False, controlling=False, ready=False) + assert not compile_allowed(known=False, controlling=True, ready=False) + assert compile_allowed(known=True, controlling=True, ready=True) + + class Runner: + def __call__(self, tensors): + class Out: + device = "CPU" + + def numpy(self): + return np.zeros((1, 25, 4), np.float32) + + return {"out": Out()} + + sess = _TinyOrtSession(Runner(), lambda v: v, device="CPU", renderer="ClangJITRenderer") + assert sess._nap_backend == "tinygrad-clang" + with pytest.raises(RuntimeError, match="compile-blocked"): + sess.run(None, {"images": np.zeros((1, 3, 2, 2), np.float32)}) + sess.allow_compile(True) + out = sess.run(None, {"images": np.zeros((1, 3, 2, 2), np.float32)}) + assert sess.compiled + assert out[0].shape == (1, 25, 4) + sess.allow_compile(False) + sess.run(None, {"images": np.zeros((1, 3, 2, 2), np.float32)}) + + class GpuRunner: + def __call__(self, tensors): + class Out: + device = "QCOM" + + def numpy(self): + return np.zeros((1,), np.float32) + + return Out() + + gpu = _TinyOrtSession(GpuRunner(), lambda v: v, device="CPU", renderer="ClangJITRenderer") + gpu.allow_compile(True) + with pytest.raises(AssertionError, match="QCOM"): + gpu.run(None, {"images": np.zeros((1, 3, 2, 2), np.float32)}) + assert not gpu.compiled + + text = describe_infer_runtimes() + assert "onnxruntime-" in text + assert "tinygrad-" in text + assert "cv2-dnn-" in text + + assert dnn_ids_are_cpu(3, 0, gpu_backends={5, 4}, gpu_targets={1, 6}, cpu_target=0) + assert not dnn_ids_are_cpu(5, 0, gpu_backends={5, 4}, gpu_targets={1, 6}, cpu_target=0) + assert not dnn_ids_are_cpu(3, 1, gpu_backends={5, 4}, gpu_targets={1, 6}, cpu_target=0) + assert not dnn_ids_are_cpu(3, 6, gpu_backends={5, 4}, gpu_targets={1, 6}, cpu_target=0) + + class Cv: + _nap_backend = "opencv-dnn-cpu" + _nap_device = "CPU" + + assert assert_cpu_backend(Cv()) == "opencv-dnn-cpu" + + +def test_compile_stamp_and_lazy_session_block_while_engaged(tmp_path, monkeypatch): + """No session build until known-disengaged, unless this sha already compiled.""" + from openpilot.selfdrive.speedsignd.detect import ( + _LazyCpuSession, + compile_cache_warm, + write_compile_stamp, + ) + monkeypatch.setenv("NAP_SPEED_SIGN_CACHE", str(tmp_path)) + assert not compile_cache_warm("deadbeef") + write_compile_stamp("deadbeef", "opencv-dnn-cpu") + assert compile_cache_warm("deadbeef") + assert not compile_cache_warm("other") + write_compile_stamp("clangsha", "tinygrad-clang") + assert not compile_cache_warm("clangsha") + db = tmp_path / "clangsha" / "tinygrad" / "cache.db" + db.parent.mkdir(parents=True) + db.write_bytes(b"kernels") + assert compile_cache_warm("clangsha") + + cold = _LazyCpuSession("/no/such.onnx", "not-a-real-sha", "opencv-dnn-cpu") + assert not cold.compiled + with pytest.raises(RuntimeError, match="compile-blocked"): + cold.run(None, {"images": np.zeros((1, 3, 2, 2), np.float32)}) + warm = _LazyCpuSession("/no/such.onnx", "deadbeef", "opencv-dnn-cpu") + assert warm.compiled + + +def test_read_mph_washes_out_above_fixed_90(): + """ROAD plates often have ink ≥ 90. Old threshold returned None → HUD kept 65.""" + from openpilot.selfdrive.speedsignd.detect import _read_mph + y = _scene(seed=7) + paint_mutcd_r2_1(y, 50, x=200, y=30, w=90, h=112) + crop = y[30:142, 200:290].copy() + crop[crop < 90] = 100 + mph, conf = _read_mph(crop) + assert mph == 50 + assert conf >= 0.25 + + +def test_clang_fallback_warns_when_onnxruntime_is_missing(tmp_path, monkeypatch): + """ONNX present, onnxruntime absent: one warning names tinygrad-clang and the settings tap.""" + from openpilot.common.swaglog import cloudlog + from openpilot.selfdrive.speedsignd.detect import _onnx_session + onnx = tmp_path / "speed_sign.onnx" + onnx.write_bytes(b"not-a-real-model") + warnings: list[str] = [] + monkeypatch.setattr( + "openpilot.selfdrive.speedsignd.detect._select_cpu_kind", lambda: "tinygrad-clang", + ) + monkeypatch.setattr(cloudlog, "warning", lambda text: warnings.append(text)) + _sess, backend = _onnx_session(str(onnx)) + assert backend == "tinygrad-clang" + assert len(warnings) == 1 + assert "falling back to tinygrad-clang because onnxruntime is missing" in warnings[0] + assert "runtime missing — tap Install weights" in warnings[0] diff --git a/selfdrive/speedsignd/tests/test_engaged.py b/selfdrive/speedsignd/tests/test_engaged.py new file mode 100644 index 00000000000000..a0753e4ddae57a --- /dev/null +++ b/selfdrive/speedsignd/tests/test_engaged.py @@ -0,0 +1,681 @@ +"""ONNX keeps running while OP is controlling, and while driving manually.""" +from __future__ import annotations + +from types import SimpleNamespace + +from openpilot.selfdrive.speedsignd.detect import SpeedSign, compile_allowed +from openpilot.selfdrive.speedsignd.hud import live_sign_view +from openpilot.selfdrive.speedsignd.jsonl import JsonlLogger +from openpilot.selfdrive.speedsignd.speedsignd import ( + SM_HZ, + SPEEDSIGND_HZ, + UNKNOWN_GRACE_S, + InferSlot, + detect_if_allowed, + detect_skip_reason, + drain_vision_latest, + engaged_from_sm, + engagement_from_sm, + engagement_log_fields, + format_infer_diag, + format_refine_token, + op_controlling, + should_reset_detect_after_wait, + should_run_onnx_detect, + should_run_speed_sign_log, +) + + +class _HitDetect: + def __init__(self): + self.calls = 0 + self.nv12 = None + + def detect(self, y, min_conf=None, rgb=None, nv12=None): + self.calls += 1 + self.nv12 = nv12 + return [SpeedSign(mph=55, conf=0.9, bbox=(0, 0, 8, 8))] + + +class _FakeParams: + def __init__(self, enabled=False): + self.enabled = enabled + + def get_bool(self, key): + return self.enabled + + +def test_logger_on_still_starts_process_when_onroad(): + assert should_run_speed_sign_log(True, _FakeParams(True)) + assert not should_run_speed_sign_log(True, _FakeParams(False)) + + +def test_onnx_runs_while_op_controlling(): + assert should_run_onnx_detect(True) + assert should_run_onnx_detect(False) + + +def test_unknown_is_not_forever_controlling(): + """Soft fail-safe: cereal silence is not 'OP is driving'.""" + assert op_controlling() is False + assert op_controlling(active=None, state=None, enabled=None) is False + assert should_run_onnx_detect(op_controlling()) + + +def test_active_and_controlling_states_are_the_gate(): + assert op_controlling(active=True) is True + assert op_controlling(active=False) is False + assert op_controlling(state="disabled") is False + assert op_controlling(state="preEnabled", enabled=True, active=False) is False + assert op_controlling(state="enabled", active=True) is True + assert op_controlling(state="softDisabling") is True + assert op_controlling(state="overriding") is True + assert op_controlling(state=0) is False + assert op_controlling(state=2) is True + assert op_controlling(enabled=False) is False + assert op_controlling(enabled=True) is True + + +def test_detect_if_allowed_runs_while_controlling_and_keeps_jsonl_short(tmp_path): + det = _HitDetect() + log = JsonlLogger(str(tmp_path / "out.jsonl")) + y = __import__("numpy").zeros((32, 32), __import__("numpy").uint8) + signs, written = detect_if_allowed( + y, 45.0, -95.0, 0.0, True, det, log, now=1.0, controlling=True, + ) + assert det.calls == 1 + assert signs and signs[0].mph == 55 + assert written and written[0]["mph"] == 55 + raw = (tmp_path / "out.jsonl").read_bytes() + assert len(raw) <= 240 + + +def test_detect_if_allowed_skips_jsonl_when_engaged_and_disk_stalled(tmp_path): + det = _HitDetect() + log = JsonlLogger(str(tmp_path / "out.jsonl")) + y = __import__("numpy").zeros((32, 32), __import__("numpy").uint8) + signs, written = detect_if_allowed( + y, 45.0, -95.0, 0.0, True, det, log, now=1.0, controlling=True, disk_stalled=True, + ) + assert det.calls == 1 + assert signs and written == [] + assert not (tmp_path / "out.jsonl").exists() + # Manual driving still logs through a stall; the hardwared hit was engaged writes. + signs, written = detect_if_allowed( + y, 45.0, -95.0, 0.0, True, det, log, now=20.0, controlling=False, disk_stalled=True, + ) + assert written and (tmp_path / "out.jsonl").exists() + + +def test_detect_if_allowed_passes_nv12_crop(tmp_path): + det = _HitDetect() + log = JsonlLogger(str(tmp_path / "out.jsonl")) + nv12 = __import__("openpilot.selfdrive.speedsignd.nv12", fromlist=["Nv12DetectCrop"]).Nv12DetectCrop( + y=__import__("numpy").zeros((32, 32), __import__("numpy").uint8), + uv=None, frame_w=64, frame_h=32, crop=(32, 0, 32, 32), + ) + signs, written = detect_if_allowed( + nv12.y, 45.0, -95.0, 0.0, True, det, log, now=1.0, controlling=False, nv12=nv12, + ) + assert det.calls == 1 + assert det.nv12 is nv12 + assert signs and written + + +def test_detect_if_allowed_runs_when_disengaged_moving(tmp_path): + """Product: log signs while driving manually. Moving / not parked is OK.""" + det = _HitDetect() + log = JsonlLogger(str(tmp_path / "out.jsonl")) + y = __import__("numpy").zeros((32, 32), __import__("numpy").uint8) + signs, written = detect_if_allowed( + y, 45.0, -95.0, 0.0, True, det, log, now=1.0, controlling=False, + ) + assert det.calls == 1 + assert signs and signs[0].mph == 55 + assert written and written[0]["mph"] == 55 + + +class _Sm: + def __init__(self, recv: dict[str, int], services: dict[str, object], *, + seen: dict[str, bool] | None = None, + alive: dict[str, bool] | None = None, + valid: dict[str, bool] | None = None): + self.recv_frame = recv + self._services = services + self.seen = seen if seen is not None else {k: v > 0 for k, v in recv.items()} + if alive is not None: + self.alive = alive + if valid is not None: + self.valid = valid + + def __getitem__(self, name: str): + return self._services[name] + + +def _ss(*, enabled=False, active=False, state="disabled"): + return SimpleNamespace(enabled=enabled, active=active, state=state) + + +def test_unknown_cereal_startup_grace_then_allow_detect(): + sm = _Sm({}, {}) + start = 10.0 + during = engagement_from_sm(sm, now=start + 0.5, started_at=start) + assert during.known is False + assert during.controlling is False + assert during.allow_detect is False + assert during.detect_paused is False + after = engagement_from_sm(sm, now=start + UNKNOWN_GRACE_S + 0.1, started_at=start) + assert after.allow_detect is True + assert after.detect_paused is False + assert after.unknown_after_grace is True + # now=None (tests) is post-grace allow, not forever-WAIT. + relaxed = engagement_from_sm(sm) + assert relaxed.allow_detect is True + assert relaxed.detect_paused is False + assert engaged_from_sm(sm) is False + + +def test_stale_alive_or_invalid_uses_last_payload(): + """1 Hz poll of 100 Hz selfdriveState makes alive timeout (100 ms) fire. + + Last parsed active/state still wins — do not stuck WAIT. + """ + sm = _Sm( + {"selfdriveState": 9}, + {"selfdriveState": _ss(enabled=False, active=False, state="disabled")}, + seen={"selfdriveState": True}, + alive={"selfdriveState": False}, + ) + sample = engagement_from_sm(sm) + assert sample.known is True + assert sample.controlling is False + assert sample.allow_detect is True + assert sample.detect_paused is False + assert sample.alive is False + + sm = _Sm( + {"selfdriveState": 9}, + {"selfdriveState": _ss(enabled=False, active=False, state="disabled")}, + seen={"selfdriveState": True}, + valid={"selfdriveState": False}, + ) + sample = engagement_from_sm(sm) + assert sample.allow_detect is True + assert sample.detect_paused is False + + +def test_first_recv_frame_zero_is_seen(): + """SubMaster writes recv_frame=0 on the first update that lands a packet.""" + sm = _Sm( + {"selfdriveState": 0}, + {"selfdriveState": _ss(enabled=False, active=False, state="disabled")}, + seen={"selfdriveState": True}, + alive={"selfdriveState": True}, + valid={"selfdriveState": True}, + ) + sample = engagement_from_sm(sm) + assert sample.known is True + assert sample.allow_detect is True + assert sample.detect_paused is False + + +def test_boot_already_engaged_does_not_compile(): + """First frame at t=0 is already controlling. That is not a compile window. + + Route 0000017f finished a 177 s clang compile while engaged because that + build treated unread cereal as disengaged. Unknown is also refused. + """ + sm = _Sm( + {"selfdriveState": 1}, + {"selfdriveState": _ss(enabled=True, active=True, state="enabled")}, + seen={"selfdriveState": True}, + ) + start = 1000.0 + sample = engagement_from_sm(sm, now=start, started_at=start) + assert sample.known is True + assert sample.controlling is True + assert sample.allow_detect is True + assert not compile_allowed(known=sample.known, controlling=sample.controlling, ready=False) + assert compile_allowed(known=sample.known, controlling=sample.controlling, ready=True) + + unread = _Sm({}, {}) + unknown = engagement_from_sm(unread, now=start, started_at=start) + assert unknown.known is False + assert not compile_allowed(known=unknown.known, controlling=unknown.controlling, ready=False) + later = engagement_from_sm(unread, now=start + UNKNOWN_GRACE_S + 1.0, started_at=start) + assert later.allow_detect is True + assert not compile_allowed(known=later.known, controlling=later.controlling, ready=False) + + +def test_engagement_from_sm_active_controlling(): + sm = _Sm( + {"selfdriveState": 3}, + {"selfdriveState": _ss(enabled=True, active=True, state="enabled")}, + seen={"selfdriveState": True}, + ) + sample = engagement_from_sm(sm) + assert sample.controlling is True + assert sample.allow_detect is True + assert sample.detect_paused is False + assert should_run_onnx_detect(sample.controlling) + + sm = _Sm( + {"selfdriveState": 3}, + {"selfdriveState": _ss(enabled=False, active=False, state="disabled")}, + seen={"selfdriveState": True}, + ) + sample = engagement_from_sm(sm) + assert sample.controlling is False + assert sample.allow_detect is True + assert sample.detect_paused is False + assert should_run_onnx_detect(sample.controlling) + + +def test_enabled_but_not_active_preenabled_allows_detect(): + sm = _Sm( + {"selfdriveState": 4}, + {"selfdriveState": _ss(enabled=True, active=False, state="preEnabled")}, + seen={"selfdriveState": True}, + ) + sample = engagement_from_sm(sm) + assert sample.controlling is False + assert sample.allow_detect is True + assert sample.detect_paused is False + + +def test_overriding_and_soft_disabling_still_detect(): + for state in ("overriding", "softDisabling"): + sm = _Sm( + {"selfdriveState": 5}, + {"selfdriveState": _ss(enabled=True, active=True, state=state)}, + seen={"selfdriveState": True}, + ) + sample = engagement_from_sm(sm) + assert sample.controlling is True + assert sample.detect_paused is False + assert sample.allow_detect is True + + +def test_stale_flags_still_detect_when_last_payload_is_active(): + sm = _Sm( + {"selfdriveState": 9}, + {"selfdriveState": _ss(enabled=True, active=True, state="enabled")}, + seen={"selfdriveState": True}, + alive={"selfdriveState": False}, + valid={"selfdriveState": False}, + ) + sample = engagement_from_sm(sm) + assert sample.controlling is True + assert sample.allow_detect is True + assert sample.detect_paused is False + + +def test_stock_cruise_or_moving_does_not_block_detect(): + """Manual driving (stock CC on, moving) still runs YOLO when OP is off.""" + cruise_on = SimpleNamespace(cruiseState=SimpleNamespace(enabled=True), vEgo=22.0) + sm = _Sm( + {"selfdriveState": 4, "carState": 2}, + {"selfdriveState": _ss(enabled=False, active=False, state="disabled"), "carState": cruise_on}, + seen={"selfdriveState": True, "carState": True}, + ) + sample = engagement_from_sm(sm) + assert sample.controlling is False + assert sample.allow_detect is True + # carState-only (no selfdriveState yet) is unknown — not WAIT, detect after grace. + sm = _Sm({"carState": 2}, {"carState": cruise_on}, seen={"carState": True}) + sample = engagement_from_sm(sm, now=5.0, started_at=0.0) + assert sample.known is False + assert sample.detect_paused is False + assert sample.allow_detect is True + + +def test_wait_plate_only_when_controlling(): + paused = live_sign_view(enabled=True, msg_valid=True, mph=0, valid=False, detect_paused=True) + assert paused.plate_text == "WAIT" + unknown = live_sign_view(enabled=True, msg_valid=True, mph=0, valid=False, detect_paused=False) + assert unknown.plate_text == "" + assert not unknown.show_detect_paused + + +def test_engagement_log_fields_include_gate_signals(): + sm = _Sm( + {"selfdriveState": 3}, + {"selfdriveState": _ss(enabled=True, active=True, state="enabled")}, + seen={"selfdriveState": True}, + alive={"selfdriveState": True}, + valid={"selfdriveState": True}, + ) + text = engagement_log_fields(engagement_from_sm(sm)) + assert "enabled=True" in text + assert "active=True" in text + assert "state=enabled" in text + assert "alive=True" in text + assert "valid=True" in text + + +def test_sm_polls_faster_than_detect(): + assert SM_HZ >= 10.0 + assert SM_HZ <= 20.0 + assert SPEEDSIGND_HZ == 1.0 + assert SM_HZ > SPEEDSIGND_HZ + # Root cause of Justin's stuck WAIT: 100 Hz selfdriveState alive window is + # 10/freq = 100 ms. A 1 Hz sm.update leaves alive stale every tick. + selfdrive_freq = 100.0 + alive_s = 10.0 / selfdrive_freq + assert alive_s == 0.1 + assert 1.0 / SPEEDSIGND_HZ > alive_s + assert 1.0 / SM_HZ < alive_s + + +def test_infer_slot_abandons_in_flight_on_pause(): + """Engage must not join a 300–1500 ms YOLO; drop the result and keep the loop moving.""" + import time + slot = InferSlot() + started = __import__("threading").Event() + release = __import__("threading").Event() + + def slow(): + started.set() + release.wait(2.0) + return [SpeedSign(mph=55, conf=0.9, bbox=(0, 0, 1, 1))], [{"mph": 55}] + + t0 = time.monotonic() + assert slot.start(slow) + assert started.wait(1.0) + assert slot.busy is True + assert slot.start(slow) is False # one at a time + abandoned = slot.pause() + assert abandoned is True + assert time.monotonic() - t0 < 0.25 # did not wait for the infer + release.set() + time.sleep(0.05) + assert slot.take() is None + assert slot.busy is False + # Still paused: refuse new work until resume. + assert slot.start(slow) is False + slot.resume() + assert slot.start(lambda: ([], [])) is True + time.sleep(0.05) + out = slot.take() + assert out is not None and out.signs == [] + + +def test_infer_slot_leftover_after_resume_is_still_abandoned(): + """WAIT→manual must not adopt the abandoned infer (that applied overrun skip).""" + import time + slot = InferSlot() + started = __import__("threading").Event() + release = __import__("threading").Event() + + def slow(): + started.set() + release.wait(2.0) + return [SpeedSign(mph=55, conf=0.9, bbox=(0, 0, 1, 1))], [{"mph": 55}] + + assert slot.start(slow) + assert started.wait(1.0) + assert slot.pause() is True + slot.resume() + release.set() + time.sleep(0.08) + assert slot.take() is None + assert slot.busy is False + assert slot.start(lambda: ([SpeedSign(mph=60, conf=0.8, bbox=(0, 0, 1, 1))], [])) is True + for _ in range(50): + out = slot.take() + if out is not None: + assert out.signs[0].mph == 60 + return + time.sleep(0.01) + raise AssertionError("post-WAIT infer never arrived") + + +def test_post_wait_manual_detect_resets_next_detect(): + """Coverage gap after #70: WAIT cleared but leftover next_detect starved YOLO.""" + assert should_reset_detect_after_wait(False, True) is True + assert should_reset_detect_after_wait(True, True) is False + assert should_reset_detect_after_wait(None, True) is False + assert should_reset_detect_after_wait(False, False) is False + + +def test_drain_vision_latest_is_nonblocking(): + class _Client: + def __init__(self): + self.calls = [] + + def recv(self, timeout_ms=0): + self.calls.append(timeout_ms) + return None + + client = _Client() + drain_vision_latest(client) + assert client.calls == [0] + drain_vision_latest(None) + + +def test_infer_slot_surfaces_exception(): + slot = InferSlot() + + def boom(): + raise RuntimeError("tinygrad oops") + + assert slot.start(boom) + for _ in range(50): + out = slot.take() + if out is not None: + assert out.signs == [] + assert out.error and "tinygrad oops" in out.error + return + __import__("time").sleep(0.01) + raise AssertionError("exception outcome missing") + + +def test_infer_slot_passes_diag_tuple(): + slot = InferSlot() + diag = {"backend": "tinygrad", "peak_conf": 0.12, "peak_name": "stop"} + assert slot.start(lambda: ([], [], diag)) + for _ in range(50): + out = slot.take() + if out is not None: + assert out.diag == diag + assert out.error is None + return + __import__("time").sleep(0.01) + raise AssertionError("diag outcome missing") + + +def test_format_infer_diag_has_on_car_fields(): + text = format_infer_diag( + { + "backend": "tinygrad", + "frame_w": 1928, + "frame_h": 1208, + "letterbox": 320, + "crop": (720, 0, 1208, 1208), + "weights_path": "/data/media/0/nap/speed_sign.onnx", + "weights_sha": "6ed5f87f3ad2", + "out_shape": (1, 25, 2100), + "peak_conf": 0.91, + "peak_name": "stop", + "n_over": 10, + "sl_peak_conf": 0.12, + "sl_peak_name": "speedLimit55", + "n_over_sl": 0, + "top3": (("stop", 0.91), ("yield", 0.22), ("speedLimit55", 0.12)), + "posted": ((30, 0.01), (50, 0.02), (60, 0.03)), + "refine": ((65, 50, 50, 0.71),), + "luma_mean": 88.0, + "luma_std": 22.0, + "chroma": 1, + "prep_ms": 12.0, + "sess_ms": 420.0, + }, + allow_detect=True, + ) + assert "backend=tinygrad" in text + assert "frame=1928x1208" in text + assert "letterbox=320" in text + assert "sha=6ed5f87f3ad2" in text + assert "allow=1" in text + assert "peak=0.91/stop" in text + assert "n_over=10" in text + assert "sl_peak=0.12/speedLimit55" in text + assert "n_over_sl=0" in text + assert "top=stop:0.91,yield:0.22,speedLimit55:0.12" in text + assert "cls=30:0.01,50:0.02,60:0.03" in text + assert "refine=50:0.71 class=65" in text + assert "refine=-(" not in text + assert "out=1x25x2100" in text + assert "luma=88/22" in text + assert "chroma=1" in text + assert "prep=12" in text + assert "sess=420" in text + + +def test_format_infer_diag_always_shows_sl_peak_even_when_n_over_zero(): + text = format_infer_diag( + { + "backend": "tinygrad", + "peak_conf": 0.12, + "peak_name": "speedLimit35", + "n_over": 0, + "sl_peak_conf": 0.12, + "sl_peak_name": "speedLimit35", + "n_over_sl": 0, + "top3": (("speedLimit35", 0.12), ("speedLimit30", 0.08), ("stop", 0.03)), + "posted": ((30, 0.08), (50, 0.04), (60, 0.02)), + }, + allow_detect=True, + ) + assert "peak=0.12/speedLimit35" in text + assert "sl_peak=0.12/speedLimit35" in text + assert "n_over=0" in text + assert "top=speedLimit35:0.12,speedLimit30:0.08,stop:0.03" in text + assert "cls=30:0.08,50:0.04,60:0.02" in text + + +def test_format_infer_diag_noise_peak_has_blank_class(): + """Do not print peak=0.00/speedLimit65 — that is not a 65 read.""" + text = format_infer_diag( + { + "backend": "tinygrad", + "peak_conf": 0.00, + "peak_name": "", + "n_over": 0, + "sl_peak_conf": 0.00, + "sl_peak_name": "", + "n_over_sl": 0, + "top3": (), + "posted": ((30, 0.00), (50, 0.00), (60, 0.00)), + }, + allow_detect=True, + ) + assert "peak=0.00/" in text + assert "speedLimit65" not in text + assert "cls=30:0.00,50:0.00,60:0.00" in text + + +def test_format_infer_diag_parked_50_shows_refine_over_confident_65(): + """Justin: top=65:0.73, cls=50:0.00, hud must log refine=50 (class=65).""" + text = format_infer_diag( + { + "backend": "tinygrad", + "peak_conf": 0.73, + "peak_name": "speedLimit65", + "n_over": 1, + "sl_peak_conf": 0.73, + "sl_peak_name": "speedLimit65", + "n_over_sl": 1, + "top3": (("speedLimit65", 0.73),), + "posted": ((30, 0.00), (50, 0.00), (60, 0.00), (65, 0.73)), + "refine": ((65, 50, 50, 0.71),), + }, + allow_detect=True, + ) + assert "peak=0.73/speedLimit65" in text + assert "cls=30:0.00,50:0.00,60:0.00,65:0.73" in text + assert "refine=50:0.71 class=65" in text + assert "refine=-(" not in text + assert "refine=(65)" not in text + + +def test_format_refine_token_fail_is_dash_not_paren_65(): + """Justin read refine=(65) from refine=-(65). Fail must be refine=- class=65.""" + assert format_refine_token(65, 65, None, 0.0) == "- class=65" + text = format_infer_diag({"refine": ((65, 65, None, 0.0),)}, allow_detect=True) + assert "refine=- class=65" in text + assert "refine=-(" not in text + assert "refine=(65)" not in text + assert "refine=65:" not in text + + +def test_format_refine_token_agree_65_has_conf(): + assert format_refine_token(65, 65, 65, 0.47) == "65:0.47" + text = format_infer_diag({"refine": ((65, 65, 65, 0.47),)}, allow_detect=True) + assert "refine=65:0.47" in text + assert "refine=-" not in text + + +def test_format_infer_diag_missing_sl_fields_stays_parseable(): + text = format_infer_diag({"backend": "tinygrad", "peak_conf": 0.05, "peak_name": "stop"}, allow_detect=True) + assert "peak=0.05/stop" in text + assert "sl_peak=0.00/" in text + assert "n_over_sl=0" in text + assert "top=" not in text + + +def test_detect_skip_reason_names_infer_never_ran(): + assert detect_skip_reason(connected=False, onnx=True, busy=False, holdoff=False) == "vision-disconnected" + assert detect_skip_reason(connected=True, onnx=False, busy=False, holdoff=False) == "no-onnx" + assert detect_skip_reason(connected=True, onnx=True, busy=False, holdoff=False, buf_empty=True) == "road-recv-empty" + assert detect_skip_reason(connected=True, onnx=True, busy=False, holdoff=False, parse_fail=True) == "nv12-parse" + assert detect_skip_reason(connected=True, onnx=True, busy=True, holdoff=False) == "infer-busy" + assert detect_skip_reason(connected=True, onnx=True, busy=False, holdoff=True) == "holdoff" + + +def test_infer_slot_keeps_result_when_not_paused(): + slot = InferSlot() + assert slot.start(lambda: ([SpeedSign(mph=60, conf=0.8, bbox=(0, 0, 1, 1))], [])) + for _ in range(50): + out = slot.take() + if out is not None: + assert out.signs[0].mph == 60 + return + __import__("time").sleep(0.01) + raise AssertionError("infer result never arrived") + + +def test_detect_gate_is_not_parked_or_force_offroad(): + from pathlib import Path + src = Path(__file__).resolve().parents[1] / "speedsignd.py" + text = src.read_text(encoding="utf-8") + assert "NAPForceOffroad" not in text + assert "standstill" not in text + assert "carState" not in text + assert "selfdriveState" in text + assert "detect_paused" in text + assert "SM_HZ" in text + assert "UNKNOWN_GRACE_S" in text + assert "engagement_log_fields" in text + assert "InferSlot" in text + assert "abandon" in text + assert "should_reset_detect_after_wait" in text + assert "drain_vision_latest" in text + assert "_gen" in text + assert "format_infer_diag" in text + assert "peak=" in text + assert "luma=" in text + assert "backend=" in text + assert "waiting-infer" in text + assert "detect_skip_reason" in text + assert "copy_nv12_detect_crop" in text + assert "rgb_from_nv12" not in text + assert "SPEEDSIGND_CORES" in text + assert "sched_yield" in text + assert "crop_rgb=1" in text + assert "detect_while_engaged=1" in text + assert "format_read_timing" in text + assert "cpu_share=" in text + assert "procs_running" in text + assert "modelV2" in text + assert '["gpsLocationExternal", "gpsLocation", "selfdriveState", "modelV2"]' in text diff --git a/selfdrive/speedsignd/tests/test_feedback_realdata.py b/selfdrive/speedsignd/tests/test_feedback_realdata.py new file mode 100644 index 00000000000000..591530183aa8da --- /dev/null +++ b/selfdrive/speedsignd/tests/test_feedback_realdata.py @@ -0,0 +1,38 @@ +import json +import os +import time + +from openpilot.selfdrive.speedsignd import two_stage + + +def test_feedback_copied_to_current_segment(tmp_path): + fb = tmp_path / "fb" + fb.mkdir() + root = tmp_path / "realdata" + old = root / "0000018a--17462b65c0--3" + cur = root / "0000018a--17462b65c0--4" + old.mkdir(parents=True) + cur.mkdir() + (root / "boot").mkdir() + now = time.time() # noqa: TID251 + os.utime(old, (now - 120, now - 120)) + with open(fb / two_stage.PENDING_JSON, "w") as f: + json.dump({"mph": 35, "has_jpg": True, "lat": 45.1, "lon": -95.0}, f) + with open(fb / two_stage.PENDING_JPG, "wb") as f: + f.write(b"jpg") + rec = two_stage.record_answer(35, True, d=str(fb), now=now) + assert rec["lat"] == 45.1 + assert two_stage.current_segment_dir(str(root), now=now) == str(cur) + line = json.dumps(rec) + assert two_stage.copy_to_realdata(rec, line, str(fb), root=str(root), now=now) == cur.name + with open(cur / "speedsign_feedback.jsonl") as f: + assert '"answer": "yes"' in f.read() + assert (cur / ("speedsign_" + rec["jpg"])).read_bytes() == b"jpg" + + +def test_no_segment_when_stale(tmp_path): + seg = tmp_path / "0000018a--17462b65c0--4" + seg.mkdir() + now = time.time() # noqa: TID251 + os.utime(seg, (now - 3600, now - 3600)) + assert two_stage.current_segment_dir(str(tmp_path), now=now) is None diff --git a/selfdrive/speedsignd/tests/test_hud.py b/selfdrive/speedsignd/tests/test_hud.py new file mode 100644 index 00000000000000..fc3d928ce83691 --- /dev/null +++ b/selfdrive/speedsignd/tests/test_hud.py @@ -0,0 +1,723 @@ +"""HUD hold and cereal live sample for the speed-sign logger.""" +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from openpilot.selfdrive.speedsignd.detect import SpeedSign, SpeedSignDetector, paint_mutcd_r2_1 +from openpilot.selfdrive.speedsignd.hud import ( + AGREE_READS, + AGREE_WINDOW_S, + HUD_DETECT_PAUSED_TEXT, + HUD_HOLD_S, + SOLO_CONF, + SOLO_CONTRADICT_S, + HUD_MISSING_WEIGHTS_TEXT, + HUD_RUNTIME_MISSING_TEXT, + LiveSignHold, + is_speed_limit_sighting, + should_replace_held_mph, + TICI_CONFIRM_BTN_H, + TICI_SIGN_H, + TICI_SIGN_W, + accepted_hud_sign, + accuracy_button_rects, + hit_accuracy_button, + hud_confirm_visible, + plate_digit_size, + apply_live_sign, + apply_runtime_plate, + hud_should_show, + hud_should_show_detect_paused, + hud_should_show_missing_weights, + live_sign_from_event, + live_sign_view, + mici_sign_origin, + tici_sign_origin, +) +from openpilot.selfdrive.speedsignd.jsonl import JsonlLogger +from openpilot.selfdrive.speedsignd.speedsignd import live_sign_publish_fields, process_frame +from openpilot.selfdrive.speedsignd.tests.test_detect import _scene + + +def test_hold_keeps_mph_then_clears(): + h = LiveSignHold(hold_s=3.0) + signs = [SpeedSign(mph=45, conf=0.60, bbox=(0, 0, 10, 10))] + live, mph, _ = h.update(signs, 9.8) + assert not live + live, mph, conf = h.update(signs, 10.0) + assert live and mph == 45 and conf == 0.60 + live, mph, _ = h.update([], 11.0) + assert live and mph == 45 + live, mph, _ = h.update([], 12.99) + assert live and mph == 45 + live, mph, conf = h.update([], 13.01) + assert not live and mph == 0 and conf == 0.0 + + +def test_new_detection_refreshes_hold(): + h = LiveSignHold(hold_s=3.0) + h.update([SpeedSign(mph=30, conf=0.7, bbox=(0, 0, 1, 1))], 0.0) + live, mph, _ = h.update([SpeedSign(mph=30, conf=0.7, bbox=(0, 0, 1, 1))], 0.2) + assert live and mph == 30 + h.update([SpeedSign(mph=55, conf=0.9, bbox=(0, 0, 1, 1))], 1.0) + live, mph, _ = h.update([SpeedSign(mph=55, conf=0.9, bbox=(0, 0, 1, 1))], 1.2) + assert live and mph == 55 + live, mph, _ = h.update([], 3.9) + assert live and mph == 55 + + +def test_hud_hidden_unless_enabled_and_valid(): + assert not hud_should_show(False, True, 45) + assert not hud_should_show(True, False, 45) + assert not hud_should_show(True, True, 0) + assert hud_should_show(True, True, 45) + + +def test_apply_live_sign_clears_when_invalid(): + d = SimpleNamespace() + apply_live_sign(d, mph=45, conf=0.8, valid=True) + assert d.mph == 45 and d.valid and not d.weightsMissing and not d.detectPaused + apply_live_sign(d, mph=45, conf=0.8, valid=False) + assert d.mph == 0 and d.conf == 0.0 and not d.valid and not d.weightsMissing and not d.detectPaused + apply_live_sign(d, mph=45, conf=0.8, valid=False, weights_missing=True) + assert d.mph == 0 and not d.valid and d.weightsMissing and not d.detectPaused + apply_live_sign(d, mph=45, conf=0.8, valid=False, detect_paused=True) + assert d.mph == 0 and not d.valid and d.detectPaused and not d.weightsMissing + + +def test_hud_missing_weights_plate_when_logger_on(): + assert HUD_MISSING_WEIGHTS_TEXT == "NO WT" + assert plate_digit_size("NO WT", 120) < plate_digit_size("55", 120) + assert hud_should_show_missing_weights(True, True) + assert not hud_should_show_missing_weights(False, True) + assert not hud_should_show_missing_weights(True, False) + + missing = live_sign_view(enabled=True, msg_valid=True, mph=0, valid=False, weights_missing=True) + assert missing.show and missing.show_missing_weights + assert missing.plate_text == "NO WT" + assert not missing.show_mph + + # Never a false mph while weights are missing, even if numpy produced one. + fake = live_sign_view(enabled=True, msg_valid=True, mph=55, valid=True, weights_missing=True) + assert fake.show_missing_weights and fake.plate_text == "NO WT" + assert not fake.show_mph + + off = live_sign_view(enabled=False, msg_valid=True, mph=0, valid=False, weights_missing=True) + assert not off.show + + blank = live_sign_view(enabled=True, msg_valid=False, mph=0, valid=False, weights_missing=False) + assert not blank.show and blank.plate_text == "" + + mph = live_sign_view(enabled=True, msg_valid=True, mph=55, valid=True, weights_missing=False) + assert mph.show_mph and mph.mph == 55 and mph.plate_text == "55" + + ev = live_sign_from_event(True, SimpleNamespace(mph=0, valid=False, weightsMissing=True), True) + assert ev.show_missing_weights and ev.plate_text == "NO WT" + ev_blank = live_sign_from_event(True, SimpleNamespace(mph=0, valid=False, weightsMissing=False), False) + assert not ev_blank.show + ev_mph = live_sign_from_event(True, SimpleNamespace(mph=60, valid=True, weightsMissing=False), True) + assert ev_mph.show_mph and ev_mph.plate_text == "60" + + +def test_hud_runtime_missing_plate(): + assert HUD_RUNTIME_MISSING_TEXT == "NO RT" + assert plate_digit_size("NO RT", 120) < plate_digit_size("55", 120) + missing_rt = live_sign_view( + enabled=True, msg_valid=True, mph=55, valid=True, runtime_missing=True, + ) + assert missing_rt.show_runtime_missing and missing_rt.plate_text == "NO RT" + assert not missing_rt.show_mph + assert not hud_confirm_visible(missing_rt) + # NO WT wins when the ONNX itself is absent. Install gets both. + both = live_sign_view( + enabled=True, msg_valid=True, mph=55, valid=True, + weights_missing=True, runtime_missing=True, + ) + assert both.plate_text == "NO WT" + mph_view = live_sign_view(enabled=True, msg_valid=True, mph=60, valid=True) + overlaid = apply_runtime_plate(mph_view, runtime_missing=True) + assert overlaid.plate_text == "NO RT" + kept = apply_runtime_plate( + live_sign_view(enabled=True, msg_valid=True, mph=0, valid=False, weights_missing=True), + runtime_missing=True, + ) + assert kept.plate_text == "NO WT" + + +def test_hud_wait_plate_when_detect_paused(): + assert HUD_DETECT_PAUSED_TEXT == "WAIT" + assert plate_digit_size("WAIT", 120) < plate_digit_size("55", 120) + assert hud_should_show_detect_paused(True, True) + assert not hud_should_show_detect_paused(False, True) + assert not hud_should_show_detect_paused(True, False) + assert not hud_should_show_detect_paused(True, True, weights_missing=True) + + paused = live_sign_view(enabled=True, msg_valid=True, mph=0, valid=False, detect_paused=True) + assert paused.show and paused.show_detect_paused + assert paused.plate_text == "WAIT" + assert not paused.show_mph + assert not hud_confirm_visible(paused) + + # Never a leftover mph while YOLO is paused. + leftover = live_sign_view(enabled=True, msg_valid=True, mph=55, valid=True, detect_paused=True) + assert leftover.show_detect_paused and leftover.plate_text == "WAIT" + assert not leftover.show_mph + + # Missing weights wins over WAIT so install-weights stays obvious. + nowt = live_sign_view( + enabled=True, msg_valid=True, mph=0, valid=False, + weights_missing=True, detect_paused=True, + ) + assert nowt.show_missing_weights and nowt.plate_text == "NO WT" + assert not nowt.show_detect_paused + + ev = live_sign_from_event(True, SimpleNamespace(mph=0, valid=False, weightsMissing=False, detectPaused=True), True) + assert ev.show_detect_paused and ev.plate_text == "WAIT" + + # Unknown / not-paused must not show WAIT — mph can still appear later. + unknown = live_sign_view(enabled=True, msg_valid=False, mph=0, valid=False, detect_paused=False) + assert not unknown.show_detect_paused and unknown.plate_text == "" + + +def test_publish_fields_flag_missing_weights_without_mph(): + h = LiveSignHold(hold_s=3.0) + signs = [SpeedSign(mph=45, conf=0.55, bbox=(0, 0, 10, 10))] + msg_valid, mph, conf, missing, paused = live_sign_publish_fields(h, signs, 10.0, True) + assert msg_valid and missing and mph == 0 and conf == 0.0 and not paused + # Hold was not primed by the numpy hit. + live, held, _ = h.update([], 10.1) + assert not live and held == 0 + + msg_valid, mph, conf, missing, paused = live_sign_publish_fields(h, signs, 10.8, False) + assert mph == 0 + msg_valid, mph, conf, missing, paused = live_sign_publish_fields(h, signs, 11.0, False) + assert msg_valid and not missing and mph == 45 and not paused + live, held, _ = h.update([], 11.5) + assert live and held == 45 + + msg_valid, mph, conf, missing, paused = live_sign_publish_fields(h, signs, 12.0, False, True) + assert msg_valid and paused and not missing and mph == 0 and conf == 0.0 + # Paused publish does not refresh hold from a leftover sign list. + live, held, _ = h.update([], 12.1) + assert live and held == 45 + + +def test_hold_shows_ocr_50_from_two_frames_not_a_contradiction(): + """Class 65 + OCR 50 is not a vote. Two OCR-only frames (second look) are.""" + h = LiveSignHold(hold_s=3.0) + clash = [SpeedSign( + mph=50, conf=0.71, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.81, refine_mph=50, refine_conf=0.71, + )] + assert not h.update(clash, 9.0)[0] + assert not h.update(clash, 9.4)[0] + signs = [SpeedSign( + mph=50, conf=0.60, bbox=(0, 0, 10, 10), + class_mph=None, refine_mph=50, refine_conf=0.60, + )] + live, mph, _ = h.update(signs, 9.8) + assert not live + live, mph, _ = h.update(signs, 10.0) + assert live and mph == 50 + live, mph, _ = h.update([], 11.0) + assert live and mph == 50 + + +def test_process_frame_hud_lights_refined_50(tmp_path): + from openpilot.selfdrive.speedsignd.debounce import SignDebounce + + class _Det: + onnx = object() + + def detect(self, y, min_conf=None, rgb=None, nv12=None): + return [SpeedSign( + mph=50, conf=0.71, bbox=(0, 0, 8, 8), + class_mph=50, class_conf=0.82, refine_mph=50, refine_conf=0.71, + )] + + log = JsonlLogger(str(tmp_path / "out.jsonl")) + debounce = SignDebounce() + y = _scene() + signs, written = process_frame( + y, 45.0, -95.0, 0.0, True, _Det(), log, now=1.0, debounce=debounce, + ) + assert signs and signs[0].mph == 50 + assert written == [] + + +def test_process_frame_hud_blank_when_yolo_65_refine_fails(tmp_path): + from openpilot.selfdrive.speedsignd.debounce import SignDebounce + + class _Det: + onnx = object() + + def detect(self, y, min_conf=None, rgb=None, nv12=None): + return [SpeedSign( + mph=65, conf=0.73, bbox=(0, 0, 8, 8), + class_mph=65, class_conf=0.73, refine_mph=None, + )] + + log = JsonlLogger(str(tmp_path / "out.jsonl")) + debounce = SignDebounce() + y = _scene() + signs, written = process_frame( + y, 45.0, -95.0, 0.0, True, _Det(), log, now=1.0, debounce=debounce, + ) + # Class-only ≥0.70 is offered to the plate. It is not a JSONL row. + assert signs and signs[0].mph == 65 + assert written == [] + assert debounce.last_raw and debounce.last_raw[0].mph == 65 + live, mph, _ = LiveSignHold().update(signs, 1.0) + assert live and mph == 65 + live, mph, _ = LiveSignHold().update( + [SpeedSign(mph=65, conf=0.60, bbox=(0, 0, 8, 8), class_mph=65, class_conf=0.60)], + 2.0, + ) + assert not live and mph == 0 + + +def test_detect_without_gps_still_returns_signs(tmp_path): + y = _scene() + paint_mutcd_r2_1(y, 35, x=200, y=30, w=90, h=112) + signs, written = process_frame( + y, 0.0, 0.0, None, False, + SpeedSignDetector(onnx_path=str(tmp_path / "missing.onnx")), + JsonlLogger(str(tmp_path / "out.jsonl")), + now=1.0, + ) + assert written == [] + assert signs and signs[0].mph == 35 + + +def test_hold_duration_constant(): + # Parked 50 went blank after 10 s of 3–5 s infers; 45 s covers miss gaps. + # Two agreeing reads replace the {40, 60, 65, 70} junk gate. + assert HUD_HOLD_S == 45.0 + assert AGREE_READS == 2 + assert AGREE_WINDOW_S == 12.0 + assert SOLO_CONF == 0.70 + assert SOLO_CONTRADICT_S == 3.0 + + +def test_hold_last_good_across_infer_skips(): + """Empty signs between 1 Hz / multi-second infers must keep last accepted mph.""" + h = LiveSignHold() + signs = [SpeedSign( + mph=50, conf=0.60, bbox=(0, 0, 10, 10), + class_mph=50, class_conf=0.60, refine_mph=50, refine_conf=0.60, + )] + live, mph, _ = h.update(signs, 9.5) + assert not live + live, mph, _ = h.update(signs, 10.0) + assert live and mph == 50 + for t in (11.0, 12.5, 14.0, 17.5, 19.9, 25.0, 35.0, 50.0): + live, mph, _ = h.update([], t) + assert live and mph == 50 + live, mph, conf = h.update([], 10.0 + HUD_HOLD_S + 0.01) + assert not live and mph == 0 and conf == 0.0 + + +def test_hold_lasts_across_more_than_10s_empty_ticks(): + """Justin: 10 s hold expired during miss gaps. Default 45 s must survive >10 s empty.""" + h = LiveSignHold() + sign50 = [_sign(50, 0.50, class_mph=50, refine_mph=50, refine_conf=0.50)] + assert not h.update(sign50, 0.0)[0] + live, mph, _ = h.update(sign50, 0.2) + assert live and mph == 50 + live, mph, _ = h.update([], 10.5) + assert live and mph == 50 + live, mph, _ = h.update([], 20.0) + assert live and mph == 50 + live, mph, _ = h.update([], 44.9) + assert live and mph == 50 + # Confirming read was at 0.2 s, so the 45 s hold ends at 45.2. + live, mph, _ = h.update([], 45.3) + assert not live + + +def test_yolo_65_refine_fail_lights_when_solo_confident(): + """One class-only read at ≥0.70 lights. Below that, the plate stays blank.""" + bad = SpeedSign( + mph=65, conf=0.73, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.73, refine_mph=None, + ) + assert accepted_hud_sign(bad) is None + live, mph, _ = LiveSignHold().update([bad], 1.0) + assert live and mph == 65 + low = SpeedSign( + mph=65, conf=0.60, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.60, refine_mph=None, + ) + live, mph, _ = LiveSignHold().update([low], 1.0) + assert not live and mph == 0 + + +def test_yolo_70_refine_fail_does_not_light_70(): + bad = SpeedSign( + mph=70, conf=0.68, bbox=(0, 0, 10, 10), + class_mph=70, class_conf=0.68, refine_mph=None, + ) + assert accepted_hud_sign(bad) is None + h = LiveSignHold() + live, mph, _ = h.update([bad], 1.0) + assert not live and mph == 0 + + +def test_yolo_65_refine_fail_holds_prior_50(): + """A later unrefined 65 must not replace a refined 50; keep last-good.""" + h = LiveSignHold() + good = [SpeedSign( + mph=50, conf=0.60, bbox=(0, 0, 10, 10), + class_mph=50, class_conf=0.60, refine_mph=50, refine_conf=0.60, + )] + live, mph, _ = h.update(good, 0.8) + assert not live + live, mph, _ = h.update(good, 1.0) + assert live and mph == 50 + bad = [SpeedSign( + mph=65, conf=0.73, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.73, refine_mph=None, + )] + live, mph, _ = h.update(bad, 2.0) + assert live and mph == 50 + live, mph, _ = h.update([], 8.0) + assert live and mph == 50 + + +def test_class_ocr_contradiction_never_lights(): + """v2 often reads 60 as 30 and 30 as 50. A disagreeing OCR must not vote either way.""" + sign = SpeedSign( + mph=50, conf=0.71, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.82, refine_mph=50, refine_conf=0.71, + ) + assert accepted_hud_sign(sign) is None + h = LiveSignHold() + assert not h.update([sign], 5.0)[0] + live, mph, _ = h.update([sign], 5.4) + assert not live and mph == 0 + live, mph, _ = h.update([sign], 8.0) + assert not live and mph == 0 + + +def test_same_timestamp_is_one_frame(): + """Class+OCR agreement on one frame is one vote, even if update is called twice.""" + sign = SpeedSign( + mph=65, conf=0.60, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.60, refine_mph=65, refine_conf=0.60, + ) + assert accepted_hud_sign(sign) is None + h = LiveSignHold() + assert not h.update([sign], 1.0)[0] + assert not h.update([sign], 1.0)[0] + live, mph, _ = h.update([sign], 2.0) + assert live and mph == 65 + + +def test_yolo_65_refine_agree_needs_a_second_frame(): + """Class and OCR both saying 65 below 0.70 is one vote. The next frame lights it.""" + sign = SpeedSign( + mph=65, conf=0.60, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.60, refine_mph=65, refine_conf=0.60, + ) + assert accepted_hud_sign(sign) is None + h = LiveSignHold() + live, mph, _ = h.update([sign], 1.0) + assert not live and mph == 0 + live, mph, _ = h.update([sign], 2.0) + assert live and mph == 65 + + +def _sign(mph, conf, *, class_mph=None, refine_mph=None, refine_conf=0.0): + return SpeedSign( + mph=mph, conf=conf, bbox=(0, 0, 10, 10), + class_mph=class_mph if class_mph is not None else mph, + class_conf=conf, + refine_mph=refine_mph, refine_conf=refine_conf, + ) + + +def test_held_50_not_overturned_by_weaker_agreed_65(): + """A different mph replaces only when it is at least as sure as the hold.""" + assert should_replace_held_mph(50, 0.50, 65, 0.50) + assert not should_replace_held_mph(50, 0.53, 65, 0.47) + assert not should_replace_held_mph(50, 0.60, 70, 0.55) + h = LiveSignHold() + pair50 = [_sign(50, 0.50, class_mph=50, refine_mph=50, refine_conf=0.50)] + h.update(pair50, 1.0) + live, mph, _ = h.update(pair50, 1.2) + assert live and mph == 50 + weaker = _sign(65, 0.47, class_mph=65, refine_mph=65, refine_conf=0.47) + assert accepted_hud_sign(weaker) is None + live, mph, _ = h.update([weaker], 1.4) + assert live and mph == 50 + + +def test_held_50_not_overturned_by_one_read_of_40_60_70(): + """One class-only read never flashes 40/60/70. An agreed pair below the held conf stays 50.""" + h = LiveSignHold() + pair50 = [_sign(50, 0.90, class_mph=50, refine_mph=50, refine_conf=0.90)] + h.update(pair50, 1.0) + live, mph, _ = h.update(pair50, 1.2) + assert live and mph == 50 + for mph_j, conf in ((60, 0.51), (40, 0.48), (70, 0.73)): + lone = _sign(mph_j, conf, class_mph=mph_j, refine_mph=None) + assert accepted_hud_sign(lone) is None + live, mph, _ = h.update([lone], 1.4) + assert live and mph == 50 + weak70 = _sign(70, 0.55, class_mph=70, refine_mph=70, refine_conf=0.55) + assert accepted_hud_sign(weak70) is None + live, mph, _ = h.update([weak70], 1.6) + assert live and mph == 50 + # Two frames that class and OCR both name, at least as sure as the hold, do light. + real65 = _sign(65, 0.95, class_mph=65, refine_mph=65, refine_conf=0.95) + live, mph, _ = h.update([real65], 1.8) + assert live and mph == 50 + live, mph, _ = h.update([real65], 1.9) + assert live and mph == 65 + + +def test_refine_50_refreshes_held_50(): + h = LiveSignHold() + h.update([_sign(50, 0.43, class_mph=50, refine_mph=50, refine_conf=0.43)], 1.0) + live, mph, _ = h.update([_sign(50, 0.53, class_mph=50, refine_mph=50, refine_conf=0.53)], 2.0) + assert live and mph == 50 + live, mph, _ = h.update([], 46.0) + assert live and mph == 50 + + +def test_sl_sighting_extends_hold_without_changing_mph(): + h = LiveSignHold(hold_s=3.0) + pair = [_sign(50, 0.50, class_mph=50, refine_mph=50, refine_conf=0.50)] + h.update(pair, 1.0) + h.update(pair, 1.2) + miss = _sign(65, 0.73, class_mph=65, refine_mph=None) + assert is_speed_limit_sighting(miss) + live, mph, _ = h.update([miss], 3.5) + assert live and mph == 50 + live, mph, _ = h.update([], 6.4) + assert live and mph == 50 + + +def test_held_50_overturns_to_agreed_65(): + h = LiveSignHold() + pair = [_sign(50, 0.50, class_mph=50, refine_mph=50, refine_conf=0.50)] + h.update(pair, 1.0) + h.update(pair, 1.2) + strong = _sign(65, 0.80, class_mph=65, refine_mph=65, refine_conf=0.80) + assert should_replace_held_mph(50, 0.50, 65, 0.80) + live, mph, _ = h.update([strong], 1.4) + assert live and mph == 50 + live, mph, _ = h.update([strong], 1.6) + assert live and mph == 65 + + +def test_held_65_yields_to_equally_sure_ocr_50(): + """A contradiction is not a vote. Two OCR-only 50s at least as sure replace 65.""" + assert not should_replace_held_mph(65, 0.80, 50, 0.43) + assert should_replace_held_mph(65, 0.51, 50, 0.55) + h = LiveSignHold() + agreed = _sign(65, 0.80, class_mph=65, refine_mph=65, refine_conf=0.80) + h.update([agreed], 1.0) + h.update([agreed], 1.1) + weak = [SpeedSign( + mph=50, conf=0.43, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.80, refine_mph=50, refine_conf=0.43, + )] + h.update(weak, 1.2) + live, mph, _ = h.update(weak, 1.4) + assert live and mph == 65 + sure = [SpeedSign( + mph=50, conf=0.85, bbox=(0, 0, 10, 10), + class_mph=None, refine_mph=50, refine_conf=0.85, + )] + h.update(sure, 1.6) + live, mph, _ = h.update(sure, 1.8) + assert live and mph == 50 + + +def test_expired_hold_needs_two_frames_and_ignores_one_class_read(): + """One unrefined 70 stays blank. One class==OCR 70 stays blank. The next frame lights.""" + h = LiveSignHold(hold_s=1.0) + pair = [_sign(50, 0.50, class_mph=50, refine_mph=50, refine_conf=0.50)] + h.update(pair, 0.0) + h.update(pair, 0.2) + # Hold expired. Empty publish must not re-arm from votes still inside 12 s. + live, mph, _ = h.update([], 3.0) + assert not live + lone = [_sign(70, 0.60, class_mph=70, refine_mph=None)] + live, mph, _ = h.update(lone, 3.1) + assert not live and mph == 0 + agreed = [_sign(70, 0.51, class_mph=70, refine_mph=70, refine_conf=0.51)] + live, mph, _ = h.update(agreed, 3.2) + assert not live and mph == 0 + live, mph, _ = h.update(agreed, 3.4) + assert live and mph == 70 + + +def test_publish_fields_yolo_65_refine_fail_blank_or_hold(): + """Below 0.70, one unrefined class is not published. It does not replace a held 50.""" + h = LiveSignHold() + low = [SpeedSign( + mph=65, conf=0.60, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.60, refine_mph=None, + )] + blank = LiveSignHold() + msg_valid, mph, conf, missing, paused = live_sign_publish_fields(blank, low, 1.0, False) + # No accepted detect yet: cereal mph stays 0 (plate blank), same as no-hit. + assert not missing and not paused and mph == 0 and conf == 0.0 + assert not msg_valid + + good = [SpeedSign( + mph=50, conf=0.60, bbox=(0, 0, 10, 10), + class_mph=50, class_conf=0.60, refine_mph=50, refine_conf=0.60, + )] + msg_valid, mph, _, missing, paused = live_sign_publish_fields(h, good, 2.0, False) + assert mph == 0 + msg_valid, mph, _, missing, paused = live_sign_publish_fields(h, good, 2.4, False) + assert msg_valid and mph == 50 + challenger = [SpeedSign( + mph=65, conf=0.73, bbox=(0, 0, 10, 10), + class_mph=65, class_conf=0.73, refine_mph=None, + )] + msg_valid, mph, _, missing, paused = live_sign_publish_fields(h, challenger, 3.0, False) + assert msg_valid and mph == 50 + msg_valid, mph, _, missing, paused = live_sign_publish_fields(h, [], 4.0, False) + assert msg_valid and mph == 50 + + +def test_tici_plate_sits_on_driver_left_below_max(): + x, y = tici_sign_origin(0, 0) + assert x + TICI_SIGN_W < 2160 / 2 + assert x < 200 + # Below the MAX box (y=45, h=204), not covering the center path. + assert y >= 45 + 204 + yes, no = accuracy_button_rects(x, y, TICI_SIGN_W, TICI_SIGN_H, prompt_h=32) + assert yes[0] + yes[2] < 2160 / 2 + assert no[0] + no[2] < 2160 / 2 + assert yes[3] == TICI_CONFIRM_BTN_H + assert yes[1] >= y + TICI_SIGN_H + assert no[1] > yes[1] + + +def test_mici_plate_sits_on_left(): + x, y = mici_sign_origin(0, 0) + assert x < 536 / 2 + assert x < 20 + yes, no = accuracy_button_rects(x, y, 108, 128, beside=True) + assert yes[0] > x + assert yes[0] + yes[2] < 536 / 2 + + +def test_confirm_visible_only_when_mph_valid(): + mph = live_sign_view(enabled=True, msg_valid=True, mph=55, valid=True, weights_missing=False) + assert hud_confirm_visible(mph) and mph.confirm_visible + nowt = live_sign_view(enabled=True, msg_valid=True, mph=0, valid=False, weights_missing=True) + assert nowt.show and nowt.show_missing_weights + assert not hud_confirm_visible(nowt) and not nowt.confirm_visible + # Missing weights wins even if a leftover mph is present. + fake = live_sign_view(enabled=True, msg_valid=True, mph=55, valid=True, weights_missing=True) + assert not hud_confirm_visible(fake) + hidden = live_sign_view(enabled=True, msg_valid=False, mph=0, valid=False) + assert not hud_confirm_visible(hidden) + assert not hud_confirm_visible(show_mph=True, mph=0) + assert hud_confirm_visible(show_mph=True, mph=60) + + +def test_hit_accuracy_button_yes_no_and_miss(): + yes = (10.0, 20.0, 80.0, 40.0) + no = (10.0, 70.0, 80.0, 40.0) + assert hit_accuracy_button(15, 25, yes, no) is True + assert hit_accuracy_button(50, 90, yes, no) is False + assert hit_accuracy_button(0, 0, yes, no) is None + assert hit_accuracy_button(200, 25, yes, no) is None + + +def test_cereal_live_sign_has_weights_missing_field(): + capnp = pytest.importorskip("capnp") + from pathlib import Path + capnp.remove_import_hook() + custom_path = Path(__file__).resolve().parents[3] / "cereal" / "custom.capnp" + custom = capnp.load(str(custom_path)) + msg = custom.LiveSpeedSignNAP.new_message() + assert msg.mph == 0 + assert not msg.weightsMissing + assert not msg.detectPaused + apply_live_sign(msg, mph=0, conf=0.0, valid=False, weights_missing=True) + assert msg.weightsMissing and msg.mph == 0 and not msg.valid and not msg.detectPaused + apply_live_sign(msg, mph=0, conf=0.0, valid=False, detect_paused=True) + assert msg.detectPaused and not msg.weightsMissing and msg.mph == 0 + + +def test_ui_and_cereal_wire_live_sign(): + from pathlib import Path + root = Path(__file__).resolve().parents[3] + custom = (root / "cereal" / "custom.capnp").read_text(encoding="utf-8") + log = (root / "cereal" / "log.capnp").read_text(encoding="utf-8") + services = (root / "cereal" / "services.py").read_text(encoding="utf-8") + ui = (root / "selfdrive" / "ui" / "ui_state.py").read_text(encoding="utf-8") + tici = (root / "selfdrive" / "ui" / "onroad" / "hud_renderer.py").read_text(encoding="utf-8") + mici = (root / "selfdrive" / "ui" / "mici" / "onroad" / "hud_renderer.py").read_text(encoding="utf-8") + assert "struct LiveSpeedSignNAP" in custom + assert "weightsMissing @3" in custom + assert "detectPaused @4" in custom + assert "liveSpeedSignNAP @108" in log + assert '"liveSpeedSignNAP"' in services + assert "liveSpeedSignNAP" in ui + assert "SpeedSignHud" in tici + assert "SpeedSignHud" in mici + onroad = (root / "selfdrive" / "ui" / "onroad" / "speed_sign_hud.py").read_text(encoding="utf-8") + assert "NO WT" in onroad + assert "NO RT" in onroad + assert "runtime_missing" in onroad + assert "WAIT" in onroad + assert "bug" in onroad.lower() or "swaglog" in onroad.lower() + assert "live_sign_from_event" in onroad + assert "on_confirm_accuracy" in onroad + assert "draw_tici_speed_sign" in onroad + assert "draw_mici_speed_sign" in onroad + # Yes goes through mapd.speed_overrides.request_override; the HUD itself + # never writes params / JSONL / sqlite / OSM directly. + assert "Params(" not in onroad + assert "request_override" in onroad + assert "append_jsonl" not in onroad + assert "osm.org" in onroad # mentioned as future work in the stub comment + + +def test_route_181_solo_reads_light_and_a_contradiction_clears(): + """45@0.60 stays dark. 0.77 / 0.75 / 0.89 / 0.81 light unless contradicted in 3 s.""" + samples = ((45, 0.60, False), (45, 0.77, True), (30, 0.75, True), (45, 0.89, True), (30, 0.81, True)) + for mph, conf, lights in samples: + sign = SpeedSign(mph=mph, conf=conf, bbox=(0, 0, 10, 10), class_mph=mph, class_conf=conf) + live, got, _ = LiveSignHold().update([sign], 1.0) + assert live is lights + if lights: + assert got == mph + h = LiveSignHold() + lone = SpeedSign(mph=45, conf=0.89, bbox=(0, 0, 10, 10), class_mph=45, class_conf=0.89) + assert h.update([lone], 0.0)[1] == 45 + assert h.update([], 0.0 + SOLO_CONTRADICT_S + 0.05)[0] + assert h.update([], 0.0 + HUD_HOLD_S - 0.05)[0] + assert not h.update([], 0.0 + HUD_HOLD_S + 0.05)[0] + cleared = LiveSignHold() + assert cleared.update([lone], 5.0)[0] + weak = SpeedSign(mph=30, conf=0.50, bbox=(0, 0, 10, 10), class_mph=30, class_conf=0.50) + live, mph, _ = cleared.update([weak], 5.0 + 1.0) + assert not live and mph == 0 + swapped = LiveSignHold() + swapped.update([lone], 8.0) + other = SpeedSign(mph=30, conf=0.81, bbox=(0, 0, 10, 10), class_mph=30, class_conf=0.81) + live, mph, _ = swapped.update([other], 8.0 + 1.0) + assert live and mph == 30 + held = LiveSignHold() + pair = [_sign(50, 0.60, class_mph=50, refine_mph=50, refine_conf=0.60)] + held.update(pair, 1.0) + held.update(pair, 1.2) + live, mph, _ = held.update([other], 2.0) + assert live and mph == 50 + clash = SpeedSign( + mph=50, conf=0.90, bbox=(0, 0, 10, 10), + class_mph=45, class_conf=0.90, refine_mph=50, refine_conf=0.90, + ) + assert not LiveSignHold().update([clash], 1.0)[0] diff --git a/selfdrive/speedsignd/tests/test_hud_touch.py b/selfdrive/speedsignd/tests/test_hud_touch.py new file mode 100644 index 00000000000000..403effe1f13ade --- /dev/null +++ b/selfdrive/speedsignd/tests/test_hud_touch.py @@ -0,0 +1,40 @@ +from pathlib import Path + +from openpilot.selfdrive.speedsignd.hud import AnswerGate, LiveSignView, point_in_confirm_buttons + +YES = (100.0, 500.0, 120.0, 60.0) +NO = (240.0, 500.0, 120.0, 60.0) +ROOT = Path(__file__).resolve().parents[3] + + +def test_touch_only_inside_visible_buttons(): + v = LiveSignView(show_mph=True, mph=35) + assert point_in_confirm_buttons(150, 520, v, YES, NO) + assert point_in_confirm_buttons(300, 520, v, YES, NO) + assert not point_in_confirm_buttons(50, 50, v, YES, NO) # elsewhere: onroad toggles sidebar + assert not point_in_confirm_buttons(150, 520, LiveSignView(), YES, NO) # popup hidden + assert not point_in_confirm_buttons(150, 520, LiveSignView(show_missing_weights=True), YES, NO) + assert not point_in_confirm_buttons(0, 0, v, (0, 0, 0, 0), (0, 0, 0, 0)) # before layout + + +def test_after_answer_buttons_release_touch(): + g = AnswerGate() + g.answer(35, True, 0.0) + v = g.filter(LiveSignView(show_mph=True, mph=35), 0.1) + assert not point_in_confirm_buttons(150, 520, v, YES, NO) + + +def test_onroad_press_checks_hud_buttons_and_hud_is_guarded(): + road = (ROOT / "selfdrive/ui/onroad/augmented_road_view.py").read_text() + assert "touch_on_hud_button" in road + hud = (ROOT / "selfdrive/ui/onroad/speed_sign_hud.py").read_text() + assert "def render(self" in hud and "except Exception" in hud + assert "threading.Thread(target=_safe_confirm" in hud + + +def test_hud_answers_on_press(): + hud = (ROOT / "selfdrive/ui/onroad/speed_sign_hud.py").read_text() + press = hud.split("def _handle_mouse_press", 1)[1].split("def ", 1)[0] + assert "self._answer_at(mouse_pos)" in press + release = hud.split("def _handle_mouse_release", 1)[1].split("def ", 1)[0] + assert "_answer_at" not in release and "on_confirm_accuracy" not in release diff --git a/selfdrive/speedsignd/tests/test_install_weights.py b/selfdrive/speedsignd/tests/test_install_weights.py new file mode 100644 index 00000000000000..1865aab9771759 --- /dev/null +++ b/selfdrive/speedsignd/tests/test_install_weights.py @@ -0,0 +1,368 @@ +"""Install-path helper: local copy and checksummed fetch onto /data.""" +import hashlib +import os +import zipfile +from pathlib import Path + +import pytest + +from openpilot.selfdrive.speedsignd.install import ( + MIN_ONNX_BYTES, + SETTINGS_RUNTIME_MISSING, + clang_fallback_warning, + clear_runtime_status_cache, + fetch_and_install, + import_vendored_runtime, + install_runtime_wheel, + install_status_summary, + install_weights, + runtime_status_summary, + sha256_file, + vendored_runtime_ready, + vendored_sys_path, + weights_present, + weights_sha_matches, + weights_status_summary, +) +from openpilot.selfdrive.speedsignd.weights_manifest import ( + ASSET_SHA256, + ORT_BYTES, + ORT_SHA256, + ORT_URL, + ORT_VERSION, + ORT_WHEEL, + release_asset_url, +) +from scripts.nap.install_speed_sign_weights import main +from scripts.nap.script_lifecycle import script_reboots_on_exit + + +def test_install_copies_onnx_to_dest(tmp_path): + src = tmp_path / "speed_sign.onnx" + src.write_bytes(b"tiny-onnx") + dest = tmp_path / "nap" / "speed_sign.onnx" + out = install_weights(str(src), str(dest)) + assert Path(out).read_bytes() == b"tiny-onnx" + + +def test_cli_install(tmp_path): + src = tmp_path / "m.onnx" + src.write_bytes(b"abc") + dest = tmp_path / "out.onnx" + assert main([str(src), "--out", str(dest), "--skip-runtime"]) == 0 + assert dest.read_bytes() == b"abc" + + +def test_fetch_verifies_checksum(tmp_path): + src = tmp_path / "speed_sign.onnx" + src.write_bytes(b"compact-yolo") + digest = sha256_file(str(src)) + dest = tmp_path / "nap" / "speed_sign.onnx" + out = fetch_and_install(dest=str(dest), url=src.resolve().as_uri(), sha256=digest) + assert Path(out).read_bytes() == b"compact-yolo" + + +def test_fetch_rejects_bad_checksum(tmp_path): + src = tmp_path / "speed_sign.onnx" + src.write_bytes(b"nope") + dest = tmp_path / "nap" / "speed_sign.onnx" + with pytest.raises(RuntimeError, match="SHA-256"): + fetch_and_install(dest=str(dest), url=src.resolve().as_uri(), sha256="0" * 64) + + +def test_cli_download_file_url(tmp_path): + src = tmp_path / "pub.onnx" + src.write_bytes(b"from-url") + dest = tmp_path / "installed.onnx" + digest = sha256_file(str(src)) + assert main([ + "--url", src.resolve().as_uri(), "--out", str(dest), "--sha256", digest, "--skip-runtime", + ]) == 0 + assert dest.read_bytes() == b"from-url" + + +def test_manifest_points_at_github_release(): + url = release_asset_url() + assert "speed-sign-onnx-v3" in url + assert url.endswith("speed_sign.onnx") + assert ASSET_SHA256 == "45e8d444df547a1c9176fd904991e39c2ab8ae1a7624213178ce215b1ec6fb13" + + +def test_weights_status_missing_and_installed(tmp_path): + missing = tmp_path / "none.onnx" + assert not weights_present(str(missing)) + assert weights_status_summary(str(missing)) == "Missing" + + tiny = tmp_path / "tiny.onnx" + tiny.write_bytes(b"too-small") + assert not weights_present(str(tiny)) + assert weights_status_summary(str(tiny)) == "Missing" + + ok = tmp_path / "speed_sign.onnx" + ok.write_bytes(b"x" * MIN_ONNX_BYTES) + assert weights_present(str(ok)) + # Size alone is not Installed. v1 at this path is Out of date. + assert weights_status_summary(str(ok)) == "Out of date" + assert not weights_sha_matches(str(ok)) + + +def test_weights_status_installed_only_when_sha_matches(tmp_path, monkeypatch): + ok = tmp_path / "speed_sign.onnx" + ok.write_bytes(b"v2-weights" + (b"x" * MIN_ONNX_BYTES)) + digest = sha256_file(str(ok)) + monkeypatch.setattr("openpilot.selfdrive.speedsignd.install.ASSET_SHA256", digest) + assert weights_sha_matches(str(ok)) + assert weights_status_summary(str(ok)).startswith("Installed") + + +def test_fetch_replaces_existing_file(tmp_path): + dest = tmp_path / "nap" / "speed_sign.onnx" + dest.parent.mkdir() + dest.write_bytes(b"old-v1-weights-keep-me-not") + src = tmp_path / "speed_sign.onnx" + src.write_bytes(b"new-v2-weights") + digest = sha256_file(str(src)) + out = fetch_and_install(dest=str(dest), url=src.resolve().as_uri(), sha256=digest) + assert Path(out).read_bytes() == b"new-v2-weights" + + +def test_install_script_does_not_reboot_and_settings_wire_it(): + assert not script_reboots_on_exit("scripts.nap.install_speed_sign_weights") + root = Path(__file__).resolve().parents[3] + nap = (root / "selfdrive" / "ui" / "layouts" / "settings" / "nap.py").read_text(encoding="utf-8") + mici = (root / "selfdrive" / "ui" / "mici" / "layouts" / "settings" / "nap.py").read_text(encoding="utf-8") + content = (root / "selfdrive" / "ui" / "layouts" / "settings" / "nap_content.py").read_text(encoding="utf-8") + assert "Install weights" in nap + assert "install weights" in mici + assert "scripts.nap.install_speed_sign_weights" in nap + assert "scripts.nap.install_speed_sign_weights" in mici + assert "INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS" in content + assert "weights_status_summary" in nap + assert "weights_status_summary" in mici + assert "NO WT" in content + assert "runtime missing" in content + assert "NO RT" in content + assert "pylib" in content + + +def test_runtime_wheel_pin(): + assert ORT_VERSION == "1.31.0" + assert "cp312" in ORT_WHEEL + assert ORT_WHEEL.endswith("manylinux_2_28_aarch64.whl") + assert ORT_SHA256 == "35758d7606d578ec5b9d65f6e8a1f488013194c3f6097038a3223cb26d35ef9a" + assert ORT_BYTES == 21420804 + assert ORT_URL.endswith(ORT_WHEEL) + assert "pythonhosted.org" in ORT_URL + + +def _fake_wheel(path: Path, payload: str = "vendored = True\n") -> str: + with zipfile.ZipFile(path, "w") as zf: + zf.writestr("onnxruntime/", b"") + zf.writestr("onnxruntime/__init__.py", payload) + zf.writestr("onnxruntime/LICENSE", b"license-text\n") + zf.writestr("onnxruntime-9.9.9.dist-info/METADATA", "Name: onnxruntime\n") + zf.writestr("numpy/__init__.py", "nope") + return sha256_file(str(path)) + + +def test_runtime_wheel_unzips_off_the_venv(tmp_path): + wheel = tmp_path / "ort.whl" + digest = _fake_wheel(wheel) + pylib = tmp_path / "pylib" + out = install_runtime_wheel(str(wheel), str(pylib), sha256=digest, version="9.9.9") + assert out == str(pylib) + assert (pylib / "onnxruntime").is_dir() + assert (pylib / "onnxruntime" / "LICENSE").is_file() + assert not (pylib / "onnxruntime" / "LICENSE").is_dir() + assert (pylib / "onnxruntime" / "__init__.py").read_text(encoding="utf-8").startswith("vendored") + assert (pylib / "onnxruntime-9.9.9.dist-info" / "METADATA").is_file() + assert not (pylib / "numpy").exists() + assert vendored_runtime_ready(str(pylib), expected_sha=digest) + assert not vendored_runtime_ready(str(pylib)) # stamp is not the pinned 3X sha + assert "pylib" in (pylib / "onnxruntime.stamp").read_text(encoding="utf-8") + + +def test_wheel_path_traversal_is_rejected(tmp_path): + wheel = tmp_path / "bad.whl" + with zipfile.ZipFile(wheel, "w") as zf: + zf.writestr("onnxruntime/__init__.py", "__version__ = '0'\n") + zf.writestr("onnxruntime/../../outside.py", "pwned") + digest = sha256_file(str(wheel)) + pylib = tmp_path / "pylib" + with pytest.raises(RuntimeError, match="wheel path rejected"): + install_runtime_wheel(str(wheel), str(pylib), sha256=digest) + assert not (tmp_path / "outside.py").exists() + assert not pylib.exists() + + +_NAMELIST = Path(__file__).with_name("onnxruntime_1.31.0_aarch64_namelist.txt") +_REAL_WHEEL = Path( + "/tmp/speedsign/onnxruntime-1.31.0-cp312-cp312-manylinux_2_28_aarch64.whl", +) + + +def _pinned_wheel_namelist() -> list[str]: + """Namelist of the pinned aarch64 wheel. The zip on disk wins over the fixture.""" + if _REAL_WHEEL.is_file(): + with zipfile.ZipFile(_REAL_WHEEL) as zf: + return zf.namelist() + return [line for line in _NAMELIST.read_text(encoding="utf-8").splitlines() if line] + + +def test_real_wheel_namelist_license_is_a_file_and_imports(tmp_path): + """Route failure: extract treated onnxruntime/LICENSE as a directory. + + The pinned wheel's namelist has `onnxruntime/` (a directory entry) and + `onnxruntime/LICENSE` (a file). Rebuild that listing with a pure-Python + __init__ so import works on x86, and when the real wheel is present also + unpack it. + """ + names = _pinned_wheel_namelist() + assert names == [line for line in _NAMELIST.read_text(encoding="utf-8").splitlines() if line] + assert "onnxruntime/" in names + assert "onnxruntime/LICENSE" in names + assert "onnxruntime/__init__.py" in names + assert "onnxruntime/capi/" in names + + sim = tmp_path / "from-namelist.whl" + with zipfile.ZipFile(sim, "w") as zf: + for name in names: + if name.endswith("/"): + zf.writestr(name, b"") + elif name == "onnxruntime/__init__.py": + zf.writestr(name, "__version__ = '1.31.0'\n") + elif name == "onnxruntime/LICENSE": + zf.writestr(name, b"Apache-2.0\n") + else: + zf.writestr(name, b"x") + digest = sha256_file(str(sim)) + pylib = tmp_path / "pylib" + pylib.mkdir() + # The failed 3X extract left the package name as a file. + (pylib / "onnxruntime").write_text("not-a-directory", encoding="utf-8") + install_runtime_wheel(str(sim), str(pylib), sha256=digest, version="1.31.0") + assert (pylib / "onnxruntime").is_dir() + license_path = pylib / "onnxruntime" / "LICENSE" + assert license_path.is_file() + assert not license_path.is_dir() + assert license_path.read_bytes() == b"Apache-2.0\n" + loaded = import_vendored_runtime(str(pylib)) + assert loaded.endswith(os.path.join("onnxruntime", "__init__.py")) + assert os.path.abspath(str(pylib)) in os.path.abspath(loaded) + + if not _REAL_WHEEL.is_file(): + return + real_dest = tmp_path / "real" + install_runtime_wheel(str(_REAL_WHEEL), str(real_dest), sha256=ORT_SHA256) + real_license = real_dest / "onnxruntime" / "LICENSE" + assert (real_dest / "onnxruntime").is_dir() + assert real_license.is_file() + assert not real_license.is_dir() + assert (real_dest / "onnxruntime" / "__init__.py").is_file() + capi = real_dest / "onnxruntime" / "capi" / "onnxruntime_pybind11_state.cpython-312-aarch64-linux-gnu.so" + assert capi.is_file() + + +def test_runtime_wheel_rejects_bad_sha(tmp_path): + wheel = tmp_path / "ort.whl" + _fake_wheel(wheel) + with pytest.raises(RuntimeError, match="SHA-256"): + install_runtime_wheel(str(wheel), str(tmp_path / "pylib"), sha256="0" * 64) + + +def test_vendored_path_is_aarch64_only(tmp_path): + wheel = tmp_path / "ort.whl" + digest = _fake_wheel(wheel) + pylib = tmp_path / "pylib" + install_runtime_wheel(str(wheel), str(pylib), sha256=digest) + # x86 must not put the aarch64 wheel on sys.path, even when system ORT is absent. + assert vendored_sys_path("x86_64", str(pylib), False) is None + assert vendored_sys_path("aarch64", str(pylib), True) is None + # Default expected sha is the pinned wheel, so a fake stamp does not load. + assert vendored_sys_path("aarch64", str(pylib), False) is None + (pylib / "onnxruntime.stamp").write_text("onnxruntime 1.31.0\n" + ORT_SHA256 + "\npylib\n", encoding="utf-8") + assert vendored_sys_path("aarch64", str(pylib), False) == str(pylib) + assert vendored_sys_path("arm64", str(pylib), False) == str(pylib) + assert vendored_sys_path("x86_64", str(pylib), False) is None + + +def test_runtime_missing_label(monkeypatch): + monkeypatch.setattr( + "openpilot.selfdrive.speedsignd.install.ensure_vendored_runtime", lambda: False, + ) + monkeypatch.setattr( + "openpilot.selfdrive.speedsignd.install.cv2_dnn_importable", lambda: False, + ) + clear_runtime_status_cache() + assert runtime_status_summary() == "runtime missing" + assert SETTINGS_RUNTIME_MISSING == "runtime missing — tap Install weights" + assert install_status_summary("/no/such/speed_sign.onnx") == "Missing · " + SETTINGS_RUNTIME_MISSING + warn = clang_fallback_warning("tinygrad-clang") + assert "falling back to tinygrad-clang because onnxruntime is missing" in warn + assert SETTINGS_RUNTIME_MISSING in warn + assert clang_fallback_warning("onnxruntime-cpu") == "" + assert clang_fallback_warning("numpy-mutcd") == "" + clear_runtime_status_cache() + + +def test_cli_also_installs_runtime(tmp_path, monkeypatch): + called = {} + + def _fake(pylib=None, url=None, sha256=None): + called["yes"] = True + called["sha"] = sha256 + return str(tmp_path / "pylib") + + monkeypatch.setattr( + "scripts.nap.install_speed_sign_weights.fetch_and_install_runtime", _fake, + ) + monkeypatch.setattr( + "scripts.nap.install_speed_sign_weights.runtime_status_summary", + lambda: "runtime onnxruntime 1.31.0", + ) + src = tmp_path / "m.onnx" + src.write_bytes(b"abc") + dest = tmp_path / "out.onnx" + assert main([str(src), "--out", str(dest)]) == 0 + assert called["yes"] is True + assert called["sha"] == ORT_SHA256 + + +def test_v2_file_still_loadable_but_out_of_date(tmp_path, monkeypatch): + from openpilot.selfdrive.speedsignd import install as inst + p = tmp_path / "speed_sign.onnx" + p.write_bytes(b"v2" * 600_000) + digest = hashlib.sha256(p.read_bytes()).hexdigest() + monkeypatch.setattr(inst, "COMPATIBLE_SHA256", ("0" * 64, digest)) + assert inst.weights_loadable(str(p)) + assert not inst.weights_sha_matches(str(p)) + assert inst.weights_status_summary(str(p)) == "Out of date" + + +def test_fetch_falls_back_to_v2_when_v3_missing(tmp_path, monkeypatch): + from openpilot.selfdrive.speedsignd import install as inst + body = b"v2-bytes" + calls = [] + + def fake_download(url, dst): + calls.append(url) + if "speed-sign-onnx-v3" in url: + raise OSError("404") + with open(dst, "wb") as f: + f.write(body) + return len(body) + + monkeypatch.delenv("NAP_SPEED_SIGN_ONNX_URL", raising=False) + monkeypatch.setattr(inst, "download_url", fake_download) + monkeypatch.setattr(inst, "FALLBACK_SHA256", hashlib.sha256(body).hexdigest()) + dest = tmp_path / "speed_sign.onnx" + inst.fetch_and_install(dest=str(dest)) + assert dest.read_bytes() == body + assert "speed-sign-onnx-v3" in calls[0] and "speed-sign-onnx-v2" in calls[1] + + +def test_fetch_no_fallback_for_explicit_url(tmp_path, monkeypatch): + from openpilot.selfdrive.speedsignd import install as inst + monkeypatch.setattr(inst, "download_url", lambda u, d: (_ for _ in ()).throw(OSError("x"))) + with pytest.raises(OSError): + inst.fetch_and_install(dest=str(tmp_path / "o.onnx"), url="file:///nope") diff --git a/selfdrive/speedsignd/tests/test_jsonl.py b/selfdrive/speedsignd/tests/test_jsonl.py new file mode 100644 index 00000000000000..cf7ff6836898a9 --- /dev/null +++ b/selfdrive/speedsignd/tests/test_jsonl.py @@ -0,0 +1,196 @@ +"""JSONL log path, record shape, and enable gate (no sqlite, no cruise).""" +from __future__ import annotations + +import ast +import json +import os +from pathlib import Path + +from openpilot.selfdrive.speedsignd.detect import SpeedSignDetector, paint_mutcd_r2_1 +from openpilot.selfdrive.speedsignd.jsonl import RECORD_KEYS, JsonlLogger, append_jsonl, make_record +from openpilot.selfdrive.speedsignd.paths import PARAM_KEY, default_log_path, default_onnx_path, nap_data_dir +from openpilot.selfdrive.speedsignd.speedsignd import process_observations, should_run_speed_sign_log +from openpilot.selfdrive.speedsignd.tests.test_detect import _scene + + +class _FakeParams: + def __init__(self, enabled=False): + self.enabled = enabled + + def get_bool(self, key): + assert key == PARAM_KEY + return self.enabled + + +def test_default_off_even_when_onroad(): + assert not should_run_speed_sign_log(True, _FakeParams(False)) + assert not should_run_speed_sign_log(False, _FakeParams(True)) + assert not should_run_speed_sign_log(False, _FakeParams(False)) + + +def test_enable_onroad_starts_process(): + assert should_run_speed_sign_log(True, _FakeParams(True)) + + +def test_jsonl_record_keys_and_append(tmp_path): + path = str(tmp_path / "speed_signs.jsonl") + rec = make_record(1.5, 45.31, -95.60, 87.0, 45, 0.91) + assert tuple(rec.keys()) == RECORD_KEYS + append_jsonl(path, rec) + lines = Path(path).read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 1 + parsed = json.loads(lines[0]) + assert parsed == {"t": 1.5, "lat": 45.31, "lon": -95.60, "bearing": 87.0, "mph": 45, "conf": 0.91} + + +def test_logger_dedup_same_sign(tmp_path): + path = str(tmp_path / "speed_signs.jsonl") + log = JsonlLogger(path, cooldown_s=8.0, radius_m=40.0) + a = make_record(10.0, 45.0, -95.0, 0.0, 30, 0.8) + b = make_record(11.0, 45.0001, -95.0001, 0.0, 30, 0.8) + c = make_record(11.0, 45.0, -95.0, 0.0, 55, 0.8) + assert log.write(a) + assert not log.write(b) + assert log.write(c) + lines = Path(path).read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 2 + + +def test_process_observations_writes_gps_row(tmp_path): + path = str(tmp_path / "out.jsonl") + y = _scene() + paint_mutcd_r2_1(y, 55, x=200, y=30, w=90, h=112) + written = process_observations( + y, 45.315, -95.601, 12.0, True, + SpeedSignDetector(onnx_path=str(tmp_path / "missing.onnx")), + JsonlLogger(path), + now=123.0, + ) + assert written + assert written[0]["mph"] == 55 + assert written[0]["lat"] == 45.315 + row = json.loads(Path(path).read_text(encoding="utf-8").splitlines()[0]) + assert row["lon"] == -95.601 + assert row["bearing"] == 12.0 + assert row["t"] == 123.0 + + +def test_no_gps_does_not_log(tmp_path): + path = str(tmp_path / "out.jsonl") + y = _scene() + paint_mutcd_r2_1(y, 25, x=200, y=30, w=90, h=112) + written = process_observations( + y, 0.0, 0.0, None, False, + SpeedSignDetector(onnx_path=str(tmp_path / "missing.onnx")), + JsonlLogger(path), + now=1.0, + ) + assert written == [] + assert not os.path.exists(path) + + +def test_log_and_weight_paths_live_under_data(monkeypatch): + monkeypatch.delenv("NAP_SPEED_SIGN_LOG", raising=False) + monkeypatch.delenv("NAP_SPEED_SIGN_ONNX", raising=False) + monkeypatch.setattr("openpilot.selfdrive.speedsignd.paths.os.path.isdir", lambda p: p == "/data/media/0") + assert nap_data_dir() == "/data/media/0/nap" + assert default_log_path() == "/data/media/0/nap/speed_signs.jsonl" + assert default_onnx_path() == "/data/media/0/nap/speed_sign.onnx" + + +def test_env_overrides_log_path(monkeypatch, tmp_path): + monkeypatch.setenv("NAP_SPEED_SIGN_LOG", str(tmp_path / "x.jsonl")) + monkeypatch.setenv("NAP_SPEED_SIGN_ONNX", str(tmp_path / "x.onnx")) + assert default_log_path().endswith("x.jsonl") + assert default_onnx_path().endswith("x.onnx") + + +def test_module_does_not_touch_sqlite_cruise_or_osm(): + src = Path(__file__).resolve().parents[1] + lowered_code = "" + for p in src.glob("*.py"): + tree = ast.parse(p.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + lowered_code += " ".join(n.name.lower() for n in node.names) + "\n" + elif isinstance(node, ast.ImportFrom) and node.module: + lowered_code += node.module.lower() + "\n" + assert "sqlite3" not in lowered_code + assert "vcruise" not in lowered_code + assert "osm.org" not in lowered_code + assert "overpass" not in lowered_code + assert "map_speed_policy" not in lowered_code + tree = ast.parse((src / "speedsignd.py").read_text(encoding="utf-8")) + imports = [] + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.extend(n.name for n in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + imports.append(node.module) + assert not any("mapd.osm" in i or "mapd.overpass" in i or "map_speed_policy" in i for i in imports) + + +def test_process_config_wires_default_off_gate(): + cfg = Path(__file__).resolve().parents[3] / "system" / "manager" / "process_config.py" + text = cfg.read_text(encoding="utf-8") + assert "speedsignd" in text + assert "NAPSpeedSignLog" in text + assert "selfdrive.speedsignd.speedsignd" in text + + +def test_settings_and_docs_cover_enable_and_log_path(): + root = Path(__file__).resolve().parents[3] + nap = (root / "selfdrive" / "ui" / "layouts" / "settings" / "nap.py").read_text(encoding="utf-8") + docs = (root / "docs-nap" / "speed-sign-log.md").read_text(encoding="utf-8") + assert "Speed Sign Logger" in nap + assert "NAPSpeedSignLog" in nap or "NAP_SPEED_SIGN_LOG" in nap + # Logger sits at the top of NAP (before Force Offroad / Longitudinal). + assert nap.find("Speed Sign Logger") < nap.find("Force Offroad") + assert nap.find("Speed Sign Logger") < nap.find("Longitudinal Control") + mici = (root / "selfdrive" / "ui" / "mici" / "layouts" / "settings" / "nap.py").read_text(encoding="utf-8") + marker = "self._scroller.add_widgets([\n speed_sign_log," + assert marker in mici + widgets = mici[mici.find("self._scroller.add_widgets(["):] + assert widgets.find("speed_sign_log,") < widgets.find("pedal_enabled,") + content = (root / "selfdrive" / "ui" / "layouts" / "settings" / "nap_content.py").read_text(encoding="utf-8") + assert "1 Hz" in content and "nice 19" in content + assert "engaged" in content.lower() + assert "manual" in content.lower() + assert "WAIT" in content or "disengaged" in content.lower() + assert "Force Offroad" in content # weights install, not the detect gate + assert "/data/media/0/nap/speed_signs.jsonl" in docs + assert "NAPSpeedSignLog" in docs + assert "speed_sign.onnx" in docs + assert "install_speed_sign_weights" in docs + assert "export_speed_sign_onnx" in docs + assert "liveSpeedSignNAP" in docs + assert "3.0" in docs + assert "1 Hz" in docs + assert "WAIT" in docs + assert "engaged" in docs.lower() + assert "controlling" in docs.lower() + assert "swaglog" in docs.lower() + assert "20 Hz" in docs + assert "manual" in docs.lower() + assert "moving" in docs.lower() + assert "TAKE CONTROL" in docs + assert "parked, disengaged, or Force Offroad" not in docs + assert "modeld" in docs.lower() or "driving model" in docs.lower() + assert "night" in docs.lower() + assert "SHA-256" in docs or "sha256" in docs.lower() + assert "NO WT" in docs + assert "Yes" in docs and "No" in docs + assert "on_confirm_accuracy" in docs + assert "left" in docs.lower() + assert "OSM" in docs + assert "SIGN never lights" in docs + assert "Install weights" in nap + + +def test_params_key_default_is_off(): + keys = Path(__file__).resolve().parents[3] / "common" / "params_keys.h" + text = keys.read_text(encoding="utf-8") + assert "NAPSpeedSignLog" in text + # Explicit 0, or BOOL with no default (get_bool → false). Either is default-off. + assert '{"NAPSpeedSignLog", {PERSISTENT, BOOL, "0"}}' in text or \ + '{"NAPSpeedSignLog", {PERSISTENT, BOOL}}' in text diff --git a/selfdrive/speedsignd/tests/test_nv12.py b/selfdrive/speedsignd/tests/test_nv12.py new file mode 100644 index 00000000000000..b8fdc28796adaf --- /dev/null +++ b/selfdrive/speedsignd/tests/test_nv12.py @@ -0,0 +1,268 @@ +"""NV12 Y / RGB helpers for the ROAD camera.""" +from __future__ import annotations + +import numpy as np +import pytest + +from openpilot.selfdrive.speedsignd.nv12 import ( + Nv12DetectCrop, + copy_nv12_detect_crop, + detect_crop_rect, + letterbox_rgb_from_nv12_crop, + nv12_uv_offset, + rgb_from_nv12, + rgb_from_y, + y_plane_from_nv12, +) + + +def test_y_plane_from_nv12(): + class Buf: + width = 4 + height = 2 + stride = 4 + data = bytes([1, 2, 3, 4, 5, 6, 7, 8]) + bytes(8) + + y = y_plane_from_nv12(Buf()) + assert y is not None + assert y.shape == (2, 4) + assert int(y[0, 0]) == 1 + copied = y_plane_from_nv12(Buf(), copy=True) + assert copied is not None and copied.shape == (2, 4) + copied[0, 0] = 99 + assert int(y_plane_from_nv12(Buf())[0, 0]) == 1 + + +def test_rgb_from_y_replicates_luma(): + y = np.array([[10, 20], [30, 40]], np.uint8) + rgb = rgb_from_y(y) + assert rgb.shape == (2, 2, 3) + assert int(rgb[0, 1, 2]) == 20 + + +def test_rgb_from_nv12_gray_uv(): + # 2x2 gray: Y=128, U=V=128 + y = bytes([128, 128, 128, 128]) + uv = bytes([128, 128, 128, 128]) + + class Buf: + width = 2 + height = 2 + stride = 2 + data = y + uv + + rgb = rgb_from_nv12(Buf()) + assert rgb is not None + assert rgb.shape == (2, 2, 3) + assert 120 <= int(rgb[0, 0, 0]) <= 136 + + +def test_nv12_uv_offset_prefers_buf_field(): + class Buf: + uv_offset = 2048 * 1216 + + assert nv12_uv_offset(Buf(), stride=2048, height=1208) == 2048 * 1216 + assert nv12_uv_offset(type("B", (), {})(), stride=2048, height=1208) == 2048 * 1208 + + +def test_rgb_from_nv12_uses_uv_offset_not_visible_height(): + """3X Venus pad: UV starts after ALIGN(height,32) rows, not height. + + Zeros in the Y pad must not be read as U=V=0 (that turns gray into green). + """ + width, height, stride = 4, 2, 4 + y = bytes([128] * (stride * height)) + pad = bytes([0] * 8) + uv = bytes([128, 128, 128, 128]) + + class Buf: + pass + + Buf.width = width + Buf.height = height + Buf.stride = stride + Buf.uv_offset = stride * height + len(pad) + Buf.data = y + pad + uv + + rgb = rgb_from_nv12(Buf()) + assert rgb is not None + assert 120 <= int(rgb[0, 0, 0]) <= 136 + assert 120 <= int(rgb[0, 0, 1]) <= 136 + assert 120 <= int(rgb[0, 0, 2]) <= 136 + + +def _nv12_buf(width, height, *, stride=None, y=128, u=128, v=128, uv_align=32): + stride = int(stride or width) + y_bytes = bytes([y]) * (stride * height) + pad_h = (uv_align - (height % uv_align)) % uv_align + pad = bytes(stride * pad_h) + pair = bytes([u, v]) + uv = pair * ((stride // 2) * (height // 2)) + + class Buf: + pass + + Buf.width = width + Buf.height = height + Buf.stride = stride + Buf.uv_offset = stride * height + len(pad) + Buf.data = y_bytes + pad + uv + return Buf + + +def test_detect_crop_rect_is_right_biased_square(): + x, y, w, h = detect_crop_rect(1208, 1928) + assert (x, y, w, h) == (720, 0, 1208, 1208) + + +def test_native_window_covers_the_road_test_signs(): + """Route 0000017a signs sat at y=557–805, x=1110–1914. The window is + x 1300–1928, y 520–840. Letterbox into 320 keeps a ≥60 px sign at ≥30 px. + """ + from openpilot.selfdrive.speedsignd.nv12 import ( + NATIVE_WINDOW_H, + NATIVE_WINDOW_W, + NATIVE_WINDOW_X, + NATIVE_WINDOW_Y, + native_detect_window, + native_window_model_scale, + ) + from openpilot.selfdrive.speedsignd.weights_manifest import YOLO_IMGSZ + x, y, w, h = native_detect_window(1208, 1928) + assert (x, y, w, h) == (NATIVE_WINDOW_X, NATIVE_WINDOW_Y, NATIVE_WINDOW_W, NATIVE_WINDOW_H) + assert (x, y, w, h) == (1300, 520, 628, 320) + assert x <= 1300 and x + w >= 1928 + assert y <= 520 and y + h >= 840 + # Observed band sits inside. The left tail x=1110–1300 is the far signs. + assert y <= 557 and y + h >= 805 + assert x + w >= 1914 + assert x % 2 == y % 2 == w % 2 == h % 2 == 0 + scale = native_window_model_scale(YOLO_IMGSZ) + assert scale == pytest.approx(320 / 628) + assert 60 * scale >= 30.0 + # 30-inch plate ~67 px at 100 ft, ~83 px at 80 ft (x=1300 is about 80 ft). + assert 67 * scale >= 30.0 + assert 83 * scale >= 30.0 + # The old 1208² letterbox is still available and is not the live window. + assert detect_crop_rect(1208, 1928) == (720, 0, 1208, 1208) + # Window constants stay independent of the model input size. + assert YOLO_IMGSZ == 320 + + +def test_upper_window_covers_town_signs_above_the_lower_tile(): + """Town plates sat at y 340–795, x 968–1928. y=340 is above the lower tile.""" + from openpilot.selfdrive.speedsignd.nv12 import ( + NATIVE_UPPER_H, + NATIVE_UPPER_W, + NATIVE_UPPER_X, + NATIVE_UPPER_Y, + native_detect_windows, + native_upper_window, + ) + lower = (1300, 520, 628, 320) + upper = native_upper_window(1208, 1928) + assert upper == (NATIVE_UPPER_X, NATIVE_UPPER_Y, NATIVE_UPPER_W, NATIVE_UPPER_H) + assert upper == (1288, 260, 640, 320) + assert native_detect_windows(1208, 1928) == (lower, upper) + ux, uy, uw, uh = upper + assert ux % 2 == uy % 2 == uw % 2 == uh % 2 == 0 + assert ux + uw == 1928 and uy + uh == 580 + # y=340 is inside the upper tile and above the lower tile's top. + assert uy <= 340 < uy + uh + assert 340 < lower[1] + # The lower tile still owns the bottom of the town band (y through 795). + assert lower[1] <= 520 and lower[1] + lower[3] >= 795 + # Overlap so a sign on the boundary is in one of the two tiles. + assert uy + uh > lower[1] + # Left tail x 968–1288 is outside both tiles. A third tile is not added. + assert ux > 968 + buf = _nv12_buf(1928, 1208, y=128, u=128, v=128) + crop = copy_nv12_detect_crop(buf, 1) + assert crop is not None + assert crop.crop == upper + assert crop.y.shape == (320, 640) + assert copy_nv12_detect_crop(buf).crop == lower + + +def test_copy_nv12_detect_crop_is_native_320_and_keeps_chroma(): + buf = _nv12_buf(1928, 1208, y=128, u=128, v=128) + crop = copy_nv12_detect_crop(buf) + assert crop is not None + assert crop.frame_w == 1928 and crop.frame_h == 1208 + assert crop.crop == (1300, 520, 628, 320) + assert crop.y.shape == (320, 628) + assert crop.uv is not None + assert crop.uv.shape == (160, 628) + boxed, scale, pad_x, pad_y = letterbox_rgb_from_nv12_crop(crop, 320) + assert boxed.shape == (320, 320, 3) + assert pad_x == 0 + assert scale == pytest.approx(320 / 628) + nh = int(round(320 * (320 / 628))) + assert pad_y == (320 - nh) // 2 + # Neutral gray stays gray — Y-pad zeros were not read as U=V=0. + assert 120 <= int(boxed[160, 160, 0]) <= 136 + assert 120 <= int(boxed[160, 160, 1]) <= 136 + assert 120 <= int(boxed[160, 160, 2]) <= 136 + + +def test_letterbox_from_nv12_crop_uses_uv_offset_not_visible_height(): + width, height, stride = 8, 4, 8 + y = bytes([128] * (stride * height)) + pad = bytes([0] * 16) + uv = bytes([128, 128] * (stride // 2) * (height // 2)) + + class Buf: + pass + + Buf.width = width + Buf.height = height + Buf.stride = stride + Buf.uv_offset = stride * height + len(pad) + Buf.data = y + pad + uv + + crop = copy_nv12_detect_crop(Buf()) + assert crop is not None and crop.uv is not None + boxed, _scale, _px, _py = letterbox_rgb_from_nv12_crop(crop, 4) + assert 120 <= int(boxed[2, 2, 1]) <= 136 + + +def test_letterbox_nv12_crop_is_far_cheaper_than_full_rgb(): + """Pixel work: 320² RGB vs 1928×1208 RGB888. Relative time on this host.""" + import time + buf = _nv12_buf(1928, 1208, y=90, u=120, v=130) + t0 = time.perf_counter() + full = rgb_from_nv12(buf) + full_s = time.perf_counter() - t0 + t1 = time.perf_counter() + crop = copy_nv12_detect_crop(buf) + boxed, _, _, _ = letterbox_rgb_from_nv12_crop(crop, 320) + cheap_s = time.perf_counter() - t1 + assert full is not None and full.shape == (1208, 1928, 3) + assert boxed.shape == (320, 320, 3) + full_px = 1928 * 1208 + cheap_px = 320 * 320 + assert cheap_px * 8 < full_px + # Copy+letterbox should beat a full-frame BT.601 convert. Allow slack on a + # busy host; the pixel ratio is the hard assert. + assert cheap_s < full_s * 1.5 or cheap_px < full_px + + +def test_nv12_detect_crop_luma_only_if_uv_short(): + class Buf: + width = 4 + height = 4 + stride = 4 + uv_offset = 16 + data = bytes([200] * 16) # Y only + + crop = copy_nv12_detect_crop(Buf()) + assert crop is not None + assert crop.uv is None + boxed, _, _, _ = letterbox_rgb_from_nv12_crop(crop, 4) + assert int(boxed[0, 0, 0]) == int(boxed[0, 0, 1]) == int(boxed[0, 0, 2]) + + +def test_nv12_detect_crop_type(): + y = np.full((8, 8), 40, np.uint8) + crop = Nv12DetectCrop(y=y, uv=None, frame_w=16, frame_h=8, crop=(8, 0, 8, 8)) + assert crop.frame_w == 16 diff --git a/selfdrive/speedsignd/tests/test_throttle.py b/selfdrive/speedsignd/tests/test_throttle.py new file mode 100644 index 00000000000000..5809d103f2c0da --- /dev/null +++ b/selfdrive/speedsignd/tests/test_throttle.py @@ -0,0 +1,529 @@ +"""speedsignd yields to modeld: 1 Hz cap, 25% duty cycle, one little core.""" +from __future__ import annotations + +import os +from types import SimpleNamespace + +from openpilot.selfdrive.speedsignd.detect import ( + CAP_MS_DEFAULT, + CAP_MS_ENV, + THREADS_DEFAULT, + THREADS_ENV, + limit_infer_threads, + parse_infer_cap_ms, + parse_infer_threads, +) +from openpilot.selfdrive.speedsignd.speedsignd import ( + HZ_ENV, + HZ_MAX, + HZ_MIN, + INFER_BUDGET_MS, + SM_HZ, + CPU_BUDGET, + IDLE_FACTOR, + SPEEDSIGND_CORE, + SPEEDSIGND_CORES, + SPEEDSIGND_HZ, + SPEEDSIGND_NICE, + CpuShareMeter, + HostPressure, + ModelWatch, + backoff_extra_s, + cpu_over_budget, + format_backoff_timing, + format_read_timing, + infer_overran, + join_reasons, + BURST_EXTRA, + DUTY_WINDOW_S, + next_detect_mono, + parse_detect_hz, + schedule_after_read, + sign_burst_trigger, + window_compute, + parse_proc_stat_jiffies, + parse_proc_thread_count, + pressure_reason, + read_gap_s, + reset_ratekeeper_if_behind, + steady_core_duty, + yield_to_modeld, +) + + +def test_default_detect_hz_is_1(): + assert SPEEDSIGND_HZ == 1.0 + assert 10.0 <= SM_HZ <= 20.0 + assert SM_HZ > SPEEDSIGND_HZ + assert INFER_BUDGET_MS == 100.0 + assert SPEEDSIGND_NICE == 19 + assert SPEEDSIGND_CORE == 2 + assert SPEEDSIGND_CORES == (2,) + assert abs(CPU_BUDGET - 0.25) < 1e-9 + assert IDLE_FACTOR == 3.0 + assert THREADS_DEFAULT == 1 + assert CAP_MS_DEFAULT == 800.0 + assert parse_detect_hz(None) == 1.0 + assert parse_detect_hz("") == 1.0 + assert parse_detect_hz("nope") == 1.0 + assert parse_detect_hz("nan") == 1.0 + + +def test_detect_hz_env_clamped(): + assert parse_detect_hz("0.5") == 0.5 + assert parse_detect_hz("2") == 2.0 + assert parse_detect_hz("0.01") == HZ_MIN + assert parse_detect_hz("99") == HZ_MAX + assert HZ_ENV == "NAP_SPEED_SIGN_HZ" + + +def _start_gap(end: float, infer_s: float, period: float, budget: float, cap: float = 0.0, backoff: float = 0.0) -> float: + nxt = next_detect_mono(end, infer_s, period, budget, cap, backoff_s=backoff) + return nxt - (end - infer_s) + + +def test_cheap_infer_waits_out_the_period(): + period, budget = 1.0, 0.100 + infer_s = 0.050 + assert not infer_overran(infer_s, period, budget) + # Period is longer than the infer, so starts are one period apart. + assert abs(_start_gap(10.0, infer_s, period, budget) - period) < 1e-9 + + +def test_over_budget_still_obeys_the_duty_cycle(): + period, budget = 1.0, 0.100 + infer_s = 0.350 # over the 100 ms budget, still under the 1 Hz period + assert infer_overran(infer_s, period, budget) + # 4× infer is longer than the period, so the duty cycle — not the budget flag — sets the gap. + assert abs(_start_gap(10.0, infer_s, period, budget, cap=0.800) - infer_s * 4.0) < 1e-9 + + +def test_long_infer_idles_three_times(): + period, budget = 1.0, 0.100 + infer_s = 1.5 + assert infer_overran(infer_s, period, budget) + assert abs(_start_gap(5.0, infer_s, period, budget) - infer_s * (1.0 + IDLE_FACTOR)) < 1e-9 + + +def test_reset_ratekeeper_drops_backlog(): + rk = SimpleNamespace(remaining=-0.4, _next_frame_time=3.0, _interval=1.0) + assert reset_ratekeeper_if_behind(rk, now=10.0) is True + assert rk._next_frame_time == 11.0 + rk.remaining = 0.2 + rk._next_frame_time = 12.0 + assert reset_ratekeeper_if_behind(rk, now=11.8) is False + assert rk._next_frame_time == 12.0 + + +def test_4hz_would_saturate_typical_onnx_budget(): + """Hypothesis: 4 Hz * ~250–400 ms tinygrad infer ≥ 100% of a core. Default stays 1 Hz.""" + infer_s = 0.30 + assert 4.0 * infer_s >= 1.0 + assert SPEEDSIGND_HZ == 1.0 + assert SPEEDSIGND_HZ * infer_s <= 0.40 + duty = steady_core_duty(infer_s, 1.0 / SPEEDSIGND_HZ) + assert duty <= CPU_BUDGET + 1e-9 + + +def test_yield_to_modeld_prefers_sched_idle_on_core_2(monkeypatch): + called: dict[str, object] = {} + fake_rt = SimpleNamespace( + drop_realtime=lambda: called.setdefault("drop", True), + set_core_affinity=lambda cores: called.setdefault("cores", tuple(cores)), + ) + monkeypatch.setitem(__import__("sys").modules, "openpilot.common.realtime", fake_rt) + monkeypatch.setattr(os, "SCHED_IDLE", 5, raising=False) + + def _sched(pid, policy, param): + called["sched"] = (pid, policy, param.sched_priority) + return 0 + + def _nice(n): + called["nice"] = n + return n + + monkeypatch.setattr(os, "sched_setscheduler", _sched) + monkeypatch.setattr(os, "nice", _nice) + assert yield_to_modeld() == "idle" + assert called.get("drop") is True + assert called.get("sched")[1] == 5 + assert "nice" not in called + assert called.get("cores") == (2,) + + +def test_yield_to_modeld_falls_back_to_nice_19(monkeypatch): + called: dict[str, object] = {} + fake_rt = SimpleNamespace( + drop_realtime=lambda: called.setdefault("drop", True), + set_core_affinity=lambda cores: called.setdefault("cores", tuple(cores)), + ) + monkeypatch.setitem(__import__("sys").modules, "openpilot.common.realtime", fake_rt) + + def _sched(*_a, **_k): + raise OSError("no idle") + + def _nice(n): + called["nice"] = n + return n + + monkeypatch.setattr(os, "sched_setscheduler", _sched) + monkeypatch.setattr(os, "nice", _nice) + assert yield_to_modeld() == "nice" + assert called.get("nice") == SPEEDSIGND_NICE + assert called.get("cores") == SPEEDSIGND_CORES + + +def test_infer_threads_default_one_and_clamped(): + assert parse_infer_threads(None) == 1 + assert parse_infer_threads("") == 1 + assert parse_infer_threads("nope") == 1 + assert parse_infer_threads("8") == 1 + assert parse_infer_threads("0") == 1 + assert THREADS_ENV == "NAP_SPEED_SIGN_THREADS" + n = limit_infer_threads(1) + assert n == 1 + for key in ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "NUMEXPR_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "BLIS_NUM_THREADS", + "OPENCV_FOR_THREADS_NUM", + "GOTO_NUM_THREADS", + "TINYGRAD_NUM_THREADS", + ): + assert os.environ[key] == "1" + + +def test_infer_cap_ms_default_and_zero_disables(): + assert parse_infer_cap_ms(None) == 800.0 + assert parse_infer_cap_ms("") == 800.0 + assert parse_infer_cap_ms("nope") == 800.0 + assert parse_infer_cap_ms("0") == 0.0 + assert parse_infer_cap_ms("50") == 50.0 + assert parse_infer_cap_ms("99999") == 5000.0 + assert CAP_MS_ENV == "NAP_SPEED_SIGN_INFER_CAP_MS" + + +def test_duty_cycle_caps_one_core_at_a_quarter(): + """Idle is at least 3× infer, so a long read is 25% of the pinned core. + + Road test of 795d252f: ~4.3 s infer back-to-back was ~87% of a core. + 4.3 × 4 = 17.2 s start-to-start. A 50 ms infer still waits out 1 Hz. + """ + period, budget, cap = 1.0, 0.100, 0.800 + for infer_s in (3.8, 4.3, 5.4): + gap = read_gap_s(infer_s, period) + assert abs(gap - infer_s * (1.0 + IDLE_FACTOR)) < 1e-9 + assert gap - infer_s >= IDLE_FACTOR * infer_s - 1e-9 + assert steady_core_duty(infer_s, period) <= CPU_BUDGET + 1e-9 + assert abs(_start_gap(100.0, infer_s, period, budget, cap) - gap) < 1e-9 + assert abs(read_gap_s(0.050, period) - period) < 1e-9 + assert steady_core_duty(0.050, period) < CPU_BUDGET + # The old 2× infer + 1 s gap was still too hot (3.8 s → 8.6 s is 44%). + assert read_gap_s(3.8, period) > (2.0 * 3.8 + period) + + +def test_period_wins_when_four_infers_fit_inside_it(): + assert abs(read_gap_s(0.20, 1.0) - 1.0) < 1e-9 + assert abs(read_gap_s(0.35, 1.0) - 1.40) < 1e-9 + assert abs(_start_gap(10.0, 0.20, 1.0, 0.100, 0.800) - 1.0) < 1e-9 + + +def test_pressure_backoff_adds_another_three_infers(): + infer_s, period = 4.0, 1.0 + healthy = HostPressure(procs_running=6, procs_blocked=0, ncpu=8, alert_text="") + assert pressure_reason(healthy) == "" + assert backoff_extra_s(infer_s, period, "") == 0.0 + assert abs(steady_core_duty(infer_s, period) - CPU_BUDGET) < 1e-9 + + hot = HostPressure(procs_running=8 + 2 + 1, procs_blocked=0, ncpu=8) + assert pressure_reason(hot) == "cpu-load" + extra = backoff_extra_s(infer_s, period, pressure_reason(hot)) + assert extra == IDLE_FACTOR * infer_s + # 4× infer + another 3× infer → 4/28 ≈ 14% of the pinned core. + assert abs(steady_core_duty(infer_s, period, extra) - (4.0 / 28.0)) < 1e-9 + assert abs(_start_gap(20.0, infer_s, period, 0.1, 0.8, backoff=extra) - 28.0) < 1e-9 + + lag = HostPressure(alert_text="Driving Model Lagging 22.0% frames dropped", procs_running=4, ncpu=8) + assert pressure_reason(lag) == "model-lag" + controls = HostPressure(alert_text="Communication Issue Between Processes", procs_running=3, ncpu=8) + assert pressure_reason(controls) == "controls-lag" + disk = HostPressure(procs_running=4, procs_blocked=4, ncpu=8) + assert pressure_reason(disk) == "disk-stall" + + +def test_timing_lines_are_greppable(): + line = format_read_timing( + read_interval_ms=17200, infer_ms=4300, engaged=True, backoff=False, reason="pace", + cpu_share=0.25, threads=1, backend="tinygrad-clang", + ) + assert line.startswith("speedsignd timing ") + assert "read_interval_ms=17200" in line + assert "infer_ms=4300" in line + assert "cpu_share=0.250" in line + assert "threads=1" in line + assert "backend=tinygrad-clang" in line + assert "engaged=1" in line + assert "backoff=0" in line + missing = format_read_timing( + read_interval_ms=1000, infer_ms=50, engaged=False, backoff=False, reason="pace", + ) + assert "cpu_share=na" in missing + assert "backend=unset" in missing + event = format_backoff_timing(extra_ms=3980, infer_ms=3980, engaged=True, reason="model-lag") + assert event.startswith("speedsignd timing ") + assert "backoff=1" in event and "reason=model-lag" in event and "engaged=1" in event + + +def test_driving_cores_stay_with_modeld_and_controlsd(): + """Core 2 is the little core with no exclusive realtime owner on the 3X. + + 0 UI CTRL_HIGH, 1 sensord, 3 pandad and encoderd, 4 controlsd/card/selfdrived, + 5 plannerd/radard, 6 camerad, 7 modeld FIFO. locationd's family is priority 5 + on 0–3 and still preempts SCHED_IDLE on core 2. + """ + from pathlib import Path + root = Path(__file__).resolve().parents[3] + modeld = (root / "selfdrive" / "modeld" / "modeld.py").read_text(encoding="utf-8") + controlsd = (root / "selfdrive" / "controls" / "controlsd.py").read_text(encoding="utf-8") + ui = (root / "selfdrive" / "ui" / "ui.py").read_text(encoding="utf-8") + sensord = (root / "system" / "sensord" / "sensord.py").read_text(encoding="utf-8") + camerad = (root / "system" / "camerad" / "main.cc").read_text(encoding="utf-8") + encoderd = (root / "system" / "loggerd" / "encoderd.cc").read_text(encoding="utf-8") + locationd = (root / "selfdrive" / "locationd" / "locationd.py").read_text(encoding="utf-8") + hardware = (root / "system" / "hardware" / "tici" / "hardware.py").read_text(encoding="utf-8") + assert "config_realtime_process(7, 54)" in modeld + assert "config_realtime_process(4, Priority.CTRL_HIGH)" in controlsd + assert "config_realtime_process(0, Priority.CTRL_HIGH)" in ui + assert "config_realtime_process([1, ], 1)" in sensord + assert "set_core_affinity({6})" in camerad + assert "set_core_affinity({3})" in encoderd + assert "config_realtime_process([0, 1, 2, 3], 5)" in locationd + assert 'taskset", "-pc", "3"' in hardware + for core in (0, 1, 3, 4, 5, 6, 7): + assert core not in SPEEDSIGND_CORES + assert SPEEDSIGND_CORES == (2,) + assert SPEEDSIGND_NICE >= 19 + assert THREADS_DEFAULT == 1 + + +def test_model_frame_drop_and_skip_are_backoff_reasons(): + watch = ModelWatch() + watch.observe(10, 0.0, now=0.0) + watch.observe(11, 1.0, now=0.05) + assert watch.reason() == "" + watch.observe(12, 6.0, now=0.10) + assert watch.reason() == "model-drop" + watch.observe(15, 6.0, now=0.10) + assert watch.reason() == "model-drop+model-skip" + assert watch.consume() == "model-drop+model-skip" + assert watch.reason() == "model-drop" + watch.observe(16, 1.0, now=0.15) + # A hot drop stays until the next infer consumes it, then clears once it is under 5%. + assert watch.consume() == "model-drop" + assert watch.reason() == "" + skipped = ModelWatch() + skipped.observe(1, 0.0, now=0.0) + skipped.observe(4, 0.0, now=0.0) + assert skipped.reason() == "model-skip" + assert skipped.consume() == "model-skip" + assert skipped.reason() == "" + assert join_reasons("model-drop", "cpu-budget", "model-drop") == "model-drop+cpu-budget" + + +def test_submaster_coalesce_is_not_a_model_skip(): + """20 Hz poll of 20 Hz modelV2. Delta 2 is one coalesced message, not a drop. + + Route 0000017e flagged almost every read model-skip because any frameId + gap above 1 latched until consume(), including the frames published while + this process was inside recv or the infer thread. + """ + from openpilot.selfdrive.speedsignd.speedsignd import model_frame_gap_allowed + assert model_frame_gap_allowed(0.0) == 2 + assert model_frame_gap_allowed(0.05) == 2 + assert model_frame_gap_allowed(0.2) == 5 + assert model_frame_gap_allowed(5.8) >= 116 + + coalesced = ModelWatch() + coalesced.observe(100, 0.0, 0.022, now=1.0) + coalesced.observe(102, 0.0, 0.022, now=1.0) + assert coalesced.reason() == "" + assert not coalesced.hard_guard() + + blocked = ModelWatch() + blocked.observe(100, 0.0, 0.022, now=10.0) + # 200 ms vision recv at 20 Hz, plus the coalesced message. + blocked.observe(105, 0.0, 0.022, now=10.2) + assert blocked.reason() == "" + + infer = ModelWatch() + infer.observe(100, 0.0, 0.022, now=20.0) + # 5.8 s infer on the same core starves the 20 Hz poll. modeld itself + # kept publishing; frameDropPerc stayed 0 on the drive. + infer.observe(216, 0.0, 0.022, now=25.8) + assert infer.reason() == "" + assert not infer.hard_guard() + + real = ModelWatch() + real.observe(100, 0.0, 0.022, now=30.0) + real.observe(120, 0.0, 0.022, now=30.2) + assert real.reason() == "model-skip" + assert real.hard_guard() + + +def test_model_skip_or_exec_over_50ms_pauses_at_least_10s(): + """modelExecutionTime is seconds. 24 ms is healthy. Above 50 ms pauses 10 s.""" + from openpilot.selfdrive.speedsignd.speedsignd import MODEL_GUARD_PAUSE_S, model_guard_rest_s + healthy = ModelWatch() + healthy.observe(1, 0.0, 0.024) + healthy.observe(2, 1.0, 0.026) + assert healthy.reason() == "" + assert not healthy.hard_guard() + assert model_guard_rest_s(4.0, 1.0, "", False) == 0.0 + + slow = ModelWatch() + slow.observe(1, 0.0, 0.024) + slow.observe(2, 0.0, 0.050) + assert slow.reason() == "" + slow.observe(3, 0.0, 0.051) + assert slow.reason() == "model-exec" + assert slow.hard_guard() + assert model_guard_rest_s(1.0, 1.0, slow.reason(), slow.hard_guard()) >= MODEL_GUARD_PAUSE_S + assert model_guard_rest_s(1.0, 1.0, slow.reason(), slow.hard_guard()) >= 10.0 + assert slow.consume() == "model-exec" + assert slow.reason() == "model-exec" + slow.observe(4, 0.0, 0.022) + assert slow.consume() == "model-exec" + assert slow.reason() == "" + + skipped = ModelWatch() + skipped.observe(1, 0.0, 0.022, now=0.0) + skipped.observe(4, 0.0, 0.022, now=0.0) + assert skipped.reason() == "model-skip" + assert skipped.hard_guard() + # A short infer's 3× backoff is under 10 s; the hard guard raises the floor. + assert model_guard_rest_s(0.2, 1.0, skipped.reason(), True) >= 10.0 + + drop = ModelWatch() + drop.observe(1, 0.0, 0.022) + drop.observe(2, 6.0, 0.022) + assert drop.reason() == "model-drop" + assert not drop.hard_guard() + assert model_guard_rest_s(4.0, 1.0, drop.reason(), False) == 12.0 + # Route 0000017f: 177 s infer × 3 = 531 s. model-skip rest caps at 60 s. + assert model_guard_rest_s(177.0, 1.0, "model-skip", True) == 60.0 + assert model_guard_rest_s(177.0, 1.0, "model-skip", False) == 60.0 + assert model_guard_rest_s(177.0, 1.0, "model-skip+cpu-load", True) == 60.0 + assert model_guard_rest_s(0.2, 1.0, "model-skip", True) == 10.0 + + +def test_cpu_share_meter_and_budget(): + text = "123 (speedsignd) R 1 1 1 0 -1 0 0 0 0 0 40 10 0 0" + assert parse_proc_stat_jiffies(text) == 50 + assert parse_proc_thread_count("Name:\tspeedsignd\nThreads:\t1\n") == 1 + meter = CpuShareMeter() + meter._clk = 100 + assert meter.sample(0.0, 0) is None + # 25 jiffies in 1 s at 100 Hz is 0.25 of one core. + assert abs(meter.sample(1.0, 25) - 0.25) < 1e-9 + assert not cpu_over_budget(0.25) + assert not cpu_over_budget(0.27) + assert cpu_over_budget(0.29) + assert not cpu_over_budget(None) + + +def _sched(**kwargs): + base = dict( + now=10.0, infer_s=0.627, period_s=1.0, budget_s=0.100, cap_s=0.0, backoff_s=0.0, + sign_like=False, window_used=0, window_count=2, burst_left=0, burst_window=0, + burst_cluster_s=0.0, spans=[], + ) + base.update(kwargs) + return schedule_after_read(**base) + + +def test_steady_gap_stays_four_times_infer_without_a_burst(): + """Route 00000181: 627 ms infer, read gap about 2.5 s, duty 0.25.""" + infer = 0.627 + nxt, left, _bwin, win, cluster, bursting = _sched(infer_s=infer, sign_like=False) + assert not bursting and left == 0 and cluster == 0.0 + assert abs(nxt - (10.0 - infer + infer * 4.0)) < 1e-6 + assert win == 1 + assert DUTY_WINDOW_S == 10.0 + assert BURST_EXTRA == 2 + assert abs(infer / (infer * 4.0) - CPU_BUDGET) < 1e-9 + + +def test_burst_rereads_the_same_tile_then_idles_the_window_back(): + """Three back-to-back frames fit in 10 s × 25%. The next paced read waits.""" + infer = 0.627 + assert 3.0 * infer <= DUTY_WINDOW_S * CPU_BUDGET + spans: list[tuple[float, float]] = [] + now = 10.0 + nxt, left, bwin, win, cluster, bursting = _sched( + now=now, infer_s=infer, sign_like=True, spans=spans, + ) + assert bursting and left == 2 and bwin == 0 and win == 0 + assert abs(nxt - now) < 1e-9 + spans.append((now, infer)) + now = now + infer + nxt, left, bwin, win, cluster, bursting = _sched( + now=now, infer_s=infer, sign_like=True, burst_left=left, burst_window=bwin, + burst_cluster_s=cluster, spans=spans, window_used=0, + ) + assert bursting and left == 1 and win == 0 + spans.append((now, infer)) + now = now + infer + nxt, left, _bwin, win, _cluster, bursting = _sched( + now=now, infer_s=infer, sign_like=True, burst_left=left, burst_window=0, + burst_cluster_s=cluster, spans=spans, window_used=0, + ) + assert not bursting and left == 0 + assert win == 1 + paced = (now - infer) + infer * 4.0 + assert nxt + 1e-9 >= paced + finish = nxt + infer + used = window_compute(spans + [(now, infer)], finish, DUTY_WINDOW_S) + assert used + infer <= DUTY_WINDOW_S * CPU_BUDGET + 1e-6 + + +def test_burst_on_a_full_window_is_repaid_by_idle(): + infer = 0.627 + gap = infer * 4.0 + now = 30.0 + spans = [(now - 3 * gap, infer), (now - 2 * gap, infer), (now - gap, infer)] + nxt, left, bwin, win, _cluster, bursting = _sched( + now=now, infer_s=infer, sign_like=True, spans=spans, + ) + assert bursting and left == BURST_EXTRA and win == bwin + assert abs(nxt - now) < 1e-9 + # After the cluster, do not start again until the trailing 10 s is ≤ 25%. + cluster_end = now + 2 * infer + spans2 = spans + [(now, infer), (now + infer, infer)] + nxt2, left2, _b, win2, _c, bursting2 = _sched( + now=cluster_end, infer_s=infer, sign_like=False, burst_left=1, burst_window=0, + burst_cluster_s=2 * infer, spans=spans2, window_used=0, + ) + assert not bursting2 and left2 == 0 and win2 == 1 + assert nxt2 > cluster_end + infer + finish = nxt2 + infer + used = window_compute(spans2 + [(cluster_end, infer)], finish, DUTY_WINDOW_S) + assert used + infer <= DUTY_WINDOW_S * CPU_BUDGET + 1e-6 + + +def test_model_guard_cancels_a_burst(): + nxt, left, _b, win, cluster, bursting = _sched( + sign_like=True, backoff_s=10.0, burst_left=2, burst_cluster_s=0.627, + ) + assert not bursting and left == 0 and cluster == 0.0 + assert nxt >= 10.0 + 10.0 - 1e-6 + assert win == 1 + + +def test_sign_burst_trigger_is_the_speed_class_not_a_negative(): + assert sign_burst_trigger({"sl_peak_conf": 0.15, "sl_peak_name": "sl_45"}) + assert not sign_burst_trigger({"sl_peak_conf": 0.14, "peak_conf": 0.20, "peak_name": "neg_yellow"}) + assert sign_burst_trigger({"peak_conf": 0.20, "peak_name": "sl_unreadable", "sl_peak_conf": 0.0}) + assert not sign_burst_trigger({"sl_peak_conf": 0.0, "peak_conf": 0.0}) diff --git a/selfdrive/speedsignd/tests/test_two_stage.py b/selfdrive/speedsignd/tests/test_two_stage.py new file mode 100644 index 00000000000000..e1628b0347ce44 --- /dev/null +++ b/selfdrive/speedsignd/tests/test_two_stage.py @@ -0,0 +1,84 @@ +import json +import os + + +def _lines(path): + with open(path) as f: + return f.read().splitlines() + +import numpy as np + +from openpilot.selfdrive.speedsignd import two_stage as ts +from openpilot.selfdrive.speedsignd.nv12 import Nv12DetectCrop + + +def test_decode_maps_strip_to_frame(): + raw = np.zeros((1, 5, 4), np.float32) + raw[0, :, 0] = [176, 64, 20, 20, 0.9] # strip center + raw[0, :, 1] = [10, 10, 5, 5, 0.05] # below threshold + out = ts.decode_proposals(raw, ts.STRIP_RECT) + assert len(out) == 1 + x, y, w, h, s = out[0] + sx = 964 / 352 + assert abs((x + w / 2) - (964 + 176 * sx)) < 1.0 + assert abs((y + h / 2) - (525 + 64 * 350 / 128)) < 1.0 + assert s == np.float32(0.9) + + +def test_tracker_needs_two_hits_and_captures_large(): + tr = ts.SignTracker() + tr.update([(1100, 740, 20, 30, 0.5)], 0.0) + assert tr.capture_candidate(0.0) is None # seen once + tr.update([(1130, 735, 24, 34, 0.5)], 0.5) + assert tr.capture_candidate(0.5) is None # small, mid-frame + tr.update([(1400, 700, 50, 70, 0.6)], 1.0) + c = tr.capture_candidate(1.0) + assert c is not None and c.hits == 3 + + +def test_neg_track_suppressed(): + tr = ts.SignTracker() + for i, t in enumerate((0.0, 0.5)): + tr.update([(1500 + 40 * i, 700, 60, 70, 0.5)], t) + c = tr.capture_candidate(0.5) + assert c is not None + tr.mark_read(c, got_mph=False, neg=ts.neg_read({"peak_name": "neg_other", "peak_conf": 0.8})) + assert c.neg and c.done + tr.update([(1580, 700, 64, 74, 0.5)], 1.0) + assert tr.capture_candidate(1.0) is None + + +def test_capture_rect_clamped(): + x, y, w, h = ts.capture_rect((1900, 1190, 20, 20)) + assert w == h == ts.CAPTURE_MIN_SIDE + assert x + w <= 1928 and y + h <= 1208 and x % 2 == 0 and y % 2 == 0 + _, _, w2, _ = ts.capture_rect((1000, 500, 300, 300)) + assert w2 == ts.CAPTURE_MAX_SIDE + + +def test_skip_when_stopped(): + assert not ts.proposals_allowed(0.5) + assert ts.proposals_allowed(5.0) + assert ts.proposals_allowed(None) + + +def test_strip_rgb_shape(): + crop = Nv12DetectCrop(y=np.full((350, 964), 100, np.uint8), uv=np.full((175, 964), 128, np.uint8), + frame_w=1928, frame_h=1208, crop=ts.STRIP_RECT) + rgb = ts.strip_rgb_from_crop(crop) + assert rgb.shape == (128, 352, 3) and rgb.dtype == np.uint8 + + +def test_feedback_yes_no(tmp_path): + d = str(tmp_path) + assert ts.write_pending({"mph": 45, "conf": 0.8, "track_id": 3, "lat": 1.0, "lon": 2.0, + "gps_ok": True, "t": 1.0, "class": "sl_45"}, b"\xff\xd8jpg", d) + rec = ts.record_answer(45, True, d, now=1000.0) + assert rec["answer"] == "yes" and rec["track_id"] == 3 and rec["jpg"].endswith("_yes_45.jpg") + assert os.path.isfile(os.path.join(d, rec["jpg"])) + assert len(_lines(os.path.join(d, ts.CONFIRMED_JSONL))) == 1 + rec2 = ts.record_answer(30, False, d, now=1001.0) # plate mph != pending -> stale, no jpg + assert rec2["stale_pending"] and "jpg" not in rec2 + lines = [json.loads(x) for x in _lines(os.path.join(d, ts.FEEDBACK_JSONL))] + assert [x["answer"] for x in lines] == ["yes", "no"] + assert len(_lines(os.path.join(d, ts.CONFIRMED_JSONL))) == 1 diff --git a/selfdrive/speedsignd/tests/test_yolo.py b/selfdrive/speedsignd/tests/test_yolo.py new file mode 100644 index 00000000000000..906887018c8fac --- /dev/null +++ b/selfdrive/speedsignd/tests/test_yolo.py @@ -0,0 +1,510 @@ +"""YOLOv8 ONNX interface: class map, letterbox, decode, no numpy fallback.""" +from __future__ import annotations + +import numpy as np +import pytest + +from openpilot.selfdrive.speedsignd.detect import OnnxSpeedSignDetector, SpeedSign, SpeedSignDetector, paint_mutcd_r2_1 +from openpilot.selfdrive.speedsignd.tests.test_detect import _scene +from openpilot.selfdrive.speedsignd.weights_manifest import ( + ASSET_BYTES, + ASSET_SHA256, + RELEASE_TAG, + YOLO_CLASS_NAMES, + YOLO_IMGSZ, + YOLO_MIN_CONF, + YOLO_OUTPUT_LAYOUT, +) +from openpilot.selfdrive.speedsignd.nv12 import Nv12DetectCrop +from openpilot.selfdrive.speedsignd.yolo import ( + PEAK_NAME_MIN, + POSTED_LOG_MPH, + REFINE_OVERRIDE_CONF, + _resize_rgb, + class_to_mph, + decode_yolov8, + is_negative_name, + is_unreadable_name, + letterbox_rgb, + nms_xyxy, + ocr_dropped_digit, + prefer_refine, + refine_mph, + road_detect_crop, + road_detect_crop_rect, + speed_limit_class_indices, + yolo_peak, +) + +# v2 channel = 4 + class index. 0 sl_25 … 9 sl_70, 10 unreadable, 11/12 neg. +_SL_30 = 1 +_SL_50 = 5 +_SL_55 = 6 +_SL_60 = 7 +_SL_65 = 8 +_SL_70 = 9 +_SL_UNREADABLE = 10 +_NEG_YELLOW = 11 +_NEG_OTHER = 12 +_NC = 17 + + +def test_class_to_mph_reads_sl_and_speed_limit(): + assert class_to_mph("sl_55") == 55 + assert class_to_mph("sl_60") == 60 + assert class_to_mph("sl_25") == 25 + assert class_to_mph("speedLimit55") == 55 + assert class_to_mph("sl_unreadable") is None + assert class_to_mph("neg_yellow") is None + assert class_to_mph("neg_other") is None + assert class_to_mph("sl_47") is None + assert is_unreadable_name("sl_unreadable") + assert is_negative_name("neg_yellow") + assert not is_negative_name("sl_60") + + +def test_yolo_class_list_is_v3_speed_sign(): + assert RELEASE_TAG == "speed-sign-onnx-v3" + assert ASSET_SHA256 == "45e8d444df547a1c9176fd904991e39c2ab8ae1a7624213178ce215b1ec6fb13" + assert ASSET_BYTES == 12658971 + assert YOLO_OUTPUT_LAYOUT == (1, 17, 2100) + assert YOLO_MIN_CONF == 0.40 + names = list(YOLO_CLASS_NAMES) + assert names == [ + "sl_25", "sl_30", "sl_35", "sl_40", "sl_45", "sl_50", "sl_55", + "sl_60", "sl_65", "sl_70", "sl_unreadable", "neg_yellow", "neg_other", + ] + assert len(names) == 13 + sl = speed_limit_class_indices() + assert sl[0] == 0 and names[0] == "sl_25" + assert sl[-1] == 9 and names[9] == "sl_70" + assert _SL_UNREADABLE not in sl + assert _NEG_YELLOW not in sl and _NEG_OTHER not in sl + assert POSTED_LOG_MPH == (30, 50, 60, 65) + assert PEAK_NAME_MIN == 0.05 + assert REFINE_OVERRIDE_CONF == 0.28 + + +def test_letterbox_keeps_aspect_and_pads(): + rgb = np.zeros((120, 320, 3), np.uint8) + rgb[:, :] = (10, 20, 30) + boxed, scale, pad_x, pad_y = letterbox_rgb(rgb, 320) + assert boxed.shape == (320, 320, 3) + assert scale == pytest.approx(1.0) + assert pad_x == 0 + assert pad_y == 100 + assert boxed[pad_y, 10, 0] == 10 + + +def test_resize_rgb_is_bilinear_not_nearest(): + """Nearest index-sample of 2×2→1×1 picks a corner; bilinear averages.""" + img = np.zeros((2, 2, 3), np.uint8) + img[0, 0] = 0 + img[0, 1] = 100 + img[1, 0] = 0 + img[1, 1] = 100 + out = _resize_rgb(img, 1, 1) + assert 40 <= int(out[0, 0, 0]) <= 60 + + +def test_road_detect_crop_is_the_native_right_window(): + rgb = np.zeros((1208, 1928, 3), np.uint8) + crop, box = road_detect_crop(rgb) + x, y, w, h = box + assert crop.shape == (320, 628, 3) + assert (x, y, w, h) == (1300, 520, 628, 320) + # Width limits the letterbox. A 60 px sign stays ≥ 30 px at imgsz 320. + assert 60 * (YOLO_IMGSZ / float(w)) >= 30.0 + assert x > 964 + assert road_detect_crop_rect(1208, 1928) == (1300, 520, 628, 320) + + +def test_yolo_peak_reports_below_threshold_class(): + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, 4 + _NEG_YELLOW, 0] = 0.33 + peak = yolo_peak(raw) + assert peak.shape == (1, _NC, 4) + assert peak.conf == pytest.approx(0.33, abs=1e-5) + assert peak.name == "neg_yellow" + assert peak.n_over == 0 + assert peak.sl_conf == pytest.approx(0.0, abs=1e-5) + assert peak.n_over_sl == 0 + + +def test_yolo_peak_splits_negative_from_speed_limit_and_logs_top3(): + """A strong neg_* must not be reported as the speed-limit peak.""" + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, 4 + _NEG_YELLOW, 0] = 0.91 + raw[0, 4 + _NEG_OTHER, 0] = 0.22 + raw[0, 4 + _SL_55, 1] = 0.12 + raw[0, 4 + 0, 1] = 0.08 # sl_25 + peak = yolo_peak(raw) + assert peak.name == "neg_yellow" + assert peak.conf == pytest.approx(0.91, abs=1e-5) + assert peak.n_over == 1 + assert peak.sl_name == "sl_55" + assert peak.sl_conf == pytest.approx(0.12, abs=1e-5) + assert peak.n_over_sl == 0 + assert [n for n, _c in peak.top3] == ["neg_yellow", "neg_other", "sl_55"] + assert peak.top3[0][1] == pytest.approx(0.91, abs=1e-5) + assert peak.top3[2][1] == pytest.approx(0.12, abs=1e-5) + assert dict(peak.posted)[30] == pytest.approx(0.0, abs=1e-5) + assert dict(peak.posted)[50] == pytest.approx(0.0, abs=1e-5) + assert dict(peak.posted)[60] == pytest.approx(0.0, abs=1e-5) + assert dict(peak.posted)[65] == pytest.approx(0.0, abs=1e-5) + + +def test_yolo_peak_blank_name_on_argmax_noise(): + """A ~0 argmax is not a read.""" + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, 4 + _SL_65, 0] = 0.004 + raw[0, 4 + _SL_60, 0] = 0.003 + raw[0, 4 + _SL_50, 0] = 0.002 + raw[0, 4 + _SL_30, 0] = 0.001 + peak = yolo_peak(raw) + assert peak.conf == pytest.approx(0.004, abs=1e-5) + assert peak.name == "" + assert peak.sl_name == "" + assert peak.n_over == 0 + assert peak.top3 == () + assert dict(peak.posted) == {30: pytest.approx(0.001, abs=1e-5), + 50: pytest.approx(0.002, abs=1e-5), + 60: pytest.approx(0.003, abs=1e-5), + 65: pytest.approx(0.004, abs=1e-5)} + + +def test_nms_keeps_highest_score(): + boxes = np.array([ + [0, 0, 10, 10], + [1, 1, 11, 11], + [50, 50, 60, 60], + ], dtype=np.float32) + scores = np.array([0.4, 0.9, 0.8], dtype=np.float32) + keep = nms_xyxy(boxes, scores, iou_thr=0.3, max_det=3) + assert keep[0] == 1 + assert 2 in keep + assert 0 not in keep + + +def test_decode_yolov8_posted_30_50_60(): + """Class map for the v2 ONNX: sl_30, sl_50, sl_60.""" + for mph, idx in ((30, _SL_30), (50, _SL_50), (60, _SL_60)): + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, :4, 0] = [160, 120, 80, 100] + raw[0, 4 + idx, 0] = 0.88 + hits = decode_yolov8(raw, scale=1.0, pad_x=0, pad_y=0, src_hw=(320, 320), min_conf=0.4) + assert len(hits) == 1 and hits[0].mph == mph + assert hits[0].class_mph == mph + + +def test_decode_yolov8_speed_limit_55(): + raw = np.zeros((1, _NC, 8), np.float32) + raw[0, 0, 0] = 160.0 + raw[0, 1, 0] = 120.0 + raw[0, 2, 0] = 80.0 + raw[0, 3, 0] = 100.0 + raw[0, 4 + _SL_55, 0] = 0.91 + hits = decode_yolov8(raw, scale=1.0, pad_x=0, pad_y=0, src_hw=(320, 320), min_conf=0.4) + assert len(hits) == 1 + assert hits[0].mph == 55 + assert hits[0].conf == pytest.approx(0.91, abs=1e-5) + x, y, w, h = hits[0].bbox + assert x == 120 and y == 70 + assert w == 80 and h == 100 + + +def test_decode_yolov8_accepts_extra_singleton_dim(): + """tinygrad OnnxRunner has returned [1,1,C,N]; old _as_cn dropped that as empty.""" + raw = np.zeros((1, 1, _NC, 8), np.float32) + raw[0, 0, 0, 0] = 160.0 + raw[0, 0, 1, 0] = 120.0 + raw[0, 0, 2, 0] = 80.0 + raw[0, 0, 3, 0] = 100.0 + raw[0, 0, 4 + _SL_55, 0] = 0.91 + hits = decode_yolov8(raw, scale=1.0, pad_x=0, pad_y=0, src_hw=(320, 320), min_conf=0.4) + assert len(hits) == 1 and hits[0].mph == 55 + + +def test_decode_yolov8_ignores_neg_and_low_conf(): + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, :4, 0] = [80, 80, 40, 40] + raw[0, 4 + _NEG_YELLOW, 0] = 0.99 + raw[0, :4, 1] = [200, 80, 40, 40] + raw[0, 4 + _SL_60, 1] = 0.2 + assert decode_yolov8(raw, scale=1.0, pad_x=0, pad_y=0, src_hw=(320, 320), min_conf=0.4) == [] + + +def test_decode_yolov8_keeps_speed_limit_under_stronger_negative(): + """neg_yellow must not hide an sl_55 on the same anchor.""" + raw = np.zeros((1, _NC, 2), np.float32) + raw[0, :4, 0] = [160, 120, 80, 100] + raw[0, 4 + _NEG_YELLOW, 0] = 0.91 + raw[0, 4 + _SL_55, 0] = 0.50 + hits = decode_yolov8(raw, scale=1.0, pad_x=0, pad_y=0, src_hw=(320, 320), min_conf=0.4) + assert len(hits) == 1 + assert hits[0].mph == 55 + assert hits[0].conf == pytest.approx(0.50, abs=1e-5) + + +def test_decode_unreadable_is_a_box_not_an_mph(): + raw = np.zeros((1, _NC, 2), np.float32) + raw[0, :4, 0] = [160, 120, 80, 100] + raw[0, 4 + _SL_UNREADABLE, 0] = 0.80 + hits = decode_yolov8(raw, scale=1.0, pad_x=0, pad_y=0, src_hw=(320, 320), min_conf=0.4) + assert len(hits) == 1 + assert hits[0].mph == 0 + assert hits[0].class_mph is None + assert hits[0].bbox[2] > 0 + out = refine_mph(hits[0], np.zeros((320, 320), np.uint8), lambda _c: (55, 0.90)) + assert out.mph == 0 + assert out.refine_mph is None + assert out.class_mph is None + + +def test_decode_neg_other_alone_is_dropped(): + raw = np.zeros((1, _NC, 2), np.float32) + raw[0, :4, 0] = [160, 120, 80, 100] + raw[0, 4 + _NEG_OTHER, 0] = 0.95 + assert decode_yolov8(raw, scale=1.0, pad_x=0, pad_y=0, src_hw=(320, 320), min_conf=0.4) == [] + + +class _YoloSess: + def get_inputs(self): + return [type("I", (), {"name": "images", "shape": [1, 3, 320, 320]})()] + + def run(self, _out, feed): + blob = next(iter(feed.values())) + assert blob.shape == (1, 3, 320, 320) + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, 0, 0] = 200.0 + raw[0, 1, 0] = 80.0 + raw[0, 2, 0] = 60.0 + raw[0, 3, 0] = 80.0 + raw[0, 4 + _SL_60, 0] = 0.88 + return [raw] + + +def test_onnx_yolo_session_returns_60(): + det = OnnxSpeedSignDetector("/tmp/fake.onnx", _YoloSess()) + y = np.zeros((320, 320), np.uint8) + hits = det.detect(y, min_conf=0.4) + assert hits and hits[0].mph == 60 + assert hits[0].conf == pytest.approx(0.88, abs=1e-5) + + +def test_yolo_crop_offsets_bbox_to_full_road_frame(): + det = OnnxSpeedSignDetector("/tmp/fake.onnx", _YoloSess(), backend="tinygrad") + rgb = np.zeros((1208, 1928, 3), np.uint8) + hits = det.detect(None, min_conf=0.4, rgb=rgb) + assert hits and hits[0].mph == 60 + x, _y, _w, _h = hits[0].bbox + assert x >= 1100 + d = det.diag_dict() + assert d["frame_w"] == 1928 and d["frame_h"] == 1208 + assert d["crop"] == (1300, 520, 628, 320) + assert d["backend"] == "tinygrad" + + +def test_onnx_records_peak_when_decode_empty(): + class NearMiss(_YoloSess): + def run(self, _out, _feed): + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, :4, 0] = [80, 80, 40, 40] + raw[0, 4 + _NEG_YELLOW, 0] = 0.33 + return [raw] + + det = OnnxSpeedSignDetector("/tmp/fake.onnx", NearMiss(), backend="tinygrad") + y = np.zeros((320, 320), np.uint8) + assert det.detect(y, min_conf=0.4) == [] + d = det.diag_dict() + assert d["backend"] == "tinygrad" + assert d["frame_w"] == 320 and d["frame_h"] == 320 + assert d["letterbox"] == 320 + assert d["peak_name"] == "neg_yellow" + assert d["peak_conf"] == pytest.approx(0.33, abs=1e-5) + assert d["n_over"] == 0 + assert d["sl_peak_conf"] == pytest.approx(0.0, abs=1e-5) + assert d["n_over_sl"] == 0 + assert d["top3"][0][0] == "neg_yellow" + assert d["error"] == "" + + +def test_onnx_detect_surfaces_session_error(): + class Boom(_YoloSess): + def run(self, _out, _feed): + raise RuntimeError("tinygrad layout") + + det = OnnxSpeedSignDetector("/tmp/fake.onnx", Boom(), backend="tinygrad") + assert det.detect(np.zeros((64, 64), np.uint8)) == [] + assert "tinygrad layout" in det.diag_dict()["error"] + + +def test_loaded_onnx_does_not_fall_back_to_numpy(tmp_path): + class EmptyYolo(_YoloSess): + def run(self, _out, _feed): + return [np.zeros((1, _NC, 4), np.float32)] + + y = _scene() + paint_mutcd_r2_1(y, 45, x=200, y=30, w=90, h=112) + det = SpeedSignDetector(onnx=OnnxSpeedSignDetector(str(tmp_path / "x.onnx"), EmptyYolo())) + assert det.onnx is not None + assert det.detect(y) == [] + + +def test_refine_overrides_wrong_yolo_class_on_clear_crop(): + from openpilot.selfdrive.speedsignd.detect import _read_mph + y = _scene() + paint_mutcd_r2_1(y, 55, x=200, y=30, w=90, h=112) + wrong = SpeedSign(mph=65, conf=0.57, bbox=(200, 30, 90, 112)) + out = refine_mph(wrong, y, _read_mph) + assert out.mph == 55 + + +def test_refine_prefers_50_when_class_says_65(): + """Parked close R2-1 50: YOLO class is 65; crop digits are 50.""" + from openpilot.selfdrive.speedsignd.detect import _read_mph + y = _scene(seed=50) + paint_mutcd_r2_1(y, 50, x=200, y=30, w=90, h=112) + wrong = SpeedSign( + mph=65, conf=0.74, bbox=(200, 30, 90, 112), + class_mph=65, class_conf=0.74, alt_mph=None, alt_conf=0.0, + ) + out = refine_mph(wrong, y, _read_mph) + assert out.mph == 50 + assert out.class_mph == 65 + assert out.refine_mph == 50 + assert out.refine_conf >= REFINE_OVERRIDE_CONF + + +def test_refine_overrides_confident_65_when_class_50_is_zero(): + """Justin's parked close 50: top=65:0.73, cls=50:0.00 — not a close race.""" + wrong = SpeedSign( + mph=65, conf=0.73, bbox=(10, 10, 40, 50), + class_mph=65, class_conf=0.73, alt_mph=70, alt_conf=0.11, + ) + out = refine_mph(wrong, np.zeros((80, 80), np.uint8), lambda _c: (50, 0.40)) + assert out.mph == 50 + assert out.class_mph == 65 + assert out.refine_mph == 50 + assert prefer_refine(wrong, 50, 0.40) + + +def test_refine_keeps_class_when_crop_read_is_none(): + wrong = SpeedSign(mph=65, conf=0.73, bbox=(10, 10, 40, 50), class_mph=65, class_conf=0.73) + out = refine_mph(wrong, np.zeros((80, 80), np.uint8), lambda _c: (None, 0.0)) + assert out.mph == 65 + assert out.refine_mph is None + + +def test_refine_prefers_any_confident_disagreement(): + """Not only 50↔65 — any confident crop mph overrides the class.""" + sign = SpeedSign(mph=35, conf=0.70, bbox=(10, 10, 40, 50), class_mph=35, class_conf=0.70) + out = refine_mph(sign, np.zeros((80, 80), np.uint8), lambda _c: (55, 0.40)) + assert out.mph == 55 + assert out.refine_mph == 55 + + +def test_decode_65_with_50_head_at_zero(): + """sl_65 0.74, sl_50 ~0. No class-margin rescue. HUD still needs a second frame.""" + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, :4, 0] = [160, 120, 80, 100] + raw[0, 4 + _SL_65, 0] = 0.74 + raw[0, 4 + _SL_50, 0] = 0.004 + hits = decode_yolov8(raw, scale=1.0, pad_x=0, pad_y=0, src_hw=(320, 320), min_conf=0.4) + assert len(hits) == 1 + assert hits[0].mph == 65 + assert hits[0].class_mph == 65 + assert hits[0].alt_mph != 50 or hits[0].alt_conf < 0.05 + + +def test_onnx_detect_overrides_65_class_on_painted_50(): + """refine_mph still overrides a confident 65 when the crop reads 50. + + That contradiction is not a HUD vote — see test_hud. + """ + class Sess65(_YoloSess): + def run(self, _out, _feed): + raw = np.zeros((1, _NC, 4), np.float32) + raw[0, :4, 0] = [245, 86, 90, 112] + raw[0, 4 + _SL_65, 0] = 0.74 + raw[0, 4 + _SL_50, 0] = 0.004 + raw[0, 4 + _SL_70, 0] = 0.11 + return [raw] + + y = _scene(h=320, w=320) + paint_mutcd_r2_1(y, 50, x=200, y=30, w=90, h=112) + det = OnnxSpeedSignDetector("/tmp/fake.onnx", Sess65(), backend="tinygrad") + hits = det.detect(y, min_conf=0.4) + assert hits and hits[0].mph == 50 + assert hits[0].class_mph == 65 + assert hits[0].refine_mph == 50 + d = det.diag_dict() + assert d["refine"] + class_mph, hud_mph, ref_mph, ref_conf = d["refine"][0] + assert class_mph == 65 and hud_mph == 50 and ref_mph == 50 + assert ref_conf > 0.0 + + +def test_yolo_min_conf_constant(): + assert YOLO_MIN_CONF == 0.40 + + +def test_refine_never_turns_a_valid_class_into_a_dropped_digit(): + """Route 00000181: OCR produced 5 from a 45. The class must stay 45.""" + sign = SpeedSign( + mph=45, conf=0.89, bbox=(10, 10, 40, 50), + class_mph=45, class_conf=0.89, + ) + y = np.zeros((80, 80), np.uint8) + for bad in (5, 4, 46, 100, None): + out = refine_mph(sign, y, lambda _c, bad=bad: (bad, 0.95)) + assert out.mph == 45 + assert out.class_mph == 45 + assert out.refine_mph is None + assert ocr_dropped_digit(45, 5) + assert ocr_dropped_digit(45, 4) + assert not ocr_dropped_digit(65, 50) + assert not ocr_dropped_digit(35, 55) + assert not prefer_refine(sign, 5, 0.95) + assert not prefer_refine(sign, 100, 0.95) + kept = refine_mph(sign, y, lambda _c: (40, 0.90)) + assert kept.mph == 40 and kept.class_mph == 45 and kept.refine_mph == 40 + + +def test_onnx_nv12_crop_path_offsets_and_chroma(): + """On-car detect uses the crop copy, not a full-frame RGB convert.""" + det = OnnxSpeedSignDetector("/tmp/fake.onnx", _YoloSess(), backend="tinygrad") + y = np.full((320, 320), 88, np.uint8) + u = np.full((160, 160), 128, np.uint8) + v = np.full((160, 160), 128, np.uint8) + uv = np.empty((160, 320), np.uint8) + uv[:, 0::2] = u + uv[:, 1::2] = v + nv12 = Nv12DetectCrop(y=y, uv=uv, frame_w=1928, frame_h=1208, crop=(1100, 325, 320, 320)) + hits = det.detect(None, min_conf=0.4, nv12=nv12) + assert hits and hits[0].mph == 60 + assert hits[0].bbox[0] >= 1100 + d = det.diag_dict() + assert d["backend"] == "tinygrad" + assert d["frame_w"] == 1928 and d["frame_h"] == 1208 + assert d["crop"] == (1100, 325, 320, 320) # caller-supplied crop, not the live window + assert d["letterbox"] == 320 + assert d["chroma"] == 1 + assert d["luma_mean"] == pytest.approx(88.0, abs=1.0) + assert d["prep_ms"] >= 0.0 + assert d["sess_ms"] >= 0.0 + + +@pytest.mark.skipif( + not __import__("os").path.isfile("/tmp/speedsign/best.onnx"), + reason="exported ONNX not in this environment", +) +def test_real_onnx_empty_road_is_quiet(): + ort = pytest.importorskip("onnxruntime") + from openpilot.selfdrive.speedsignd.detect import OnnxSpeedSignDetector + sess = ort.InferenceSession("/tmp/speedsign/best.onnx", providers=["CPUExecutionProvider"]) + det = OnnxSpeedSignDetector("/tmp/speedsign/best.onnx", sess) + rgb = np.zeros((240, 320, 3), np.uint8) + rgb[:80] = (140, 170, 200) + rgb[80:] = (45, 45, 40) + assert det.detect(None, min_conf=0.40, rgb=rgb) == [] diff --git a/selfdrive/speedsignd/two_stage.py b/selfdrive/speedsignd/two_stage.py new file mode 100644 index 00000000000000..94e150f0595e00 --- /dev/null +++ b/selfdrive/speedsignd/two_stage.py @@ -0,0 +1,463 @@ +"""Two-stage speed-sign reader: cheap strip proposer, IoU tracker, one sharp read. + +Stage 1 (find): a 1-class "sign" YOLOv8 (width 0.125) looks at the lower-right +strip x 964-1928, y 525-875 of the 1928x1208 ROAD frame, resized to 352x128. +~0.3 GFLOP, ~110 ms on one 3X core, so 2 Hz is ~22 % of a core. Skipped below +2 m/s (GPS speed / modelV2 velocity; no carState subscriber). + +Stage 2 (read): proposals are linked into tracks (IoU or center distance). +A track must be seen twice. When it is near its largest (box height >= 60 px, +near the right edge, growth has stopped, or the track was lost) we copy one +square native crop around it (3x the box, clamped 240-480 px), letterbox it to +320 and run the existing v2 detector + refine_mph digit check once (up to two +retries on later frames if nothing >= YOLO_MIN_CONF). A track whose read is +neg_yellow / neg_other is suppressed and never read again. HUD rules +(LiveSignHold / SignDebounce) are unchanged; reads feed them like before. + +Weights: Release speed-sign-proposer-v1 / sign_proposer.onnx (Install weights). +When the proposer file is missing, speedsignd keeps the legacy fixed tiles. +""" +from __future__ import annotations + +import json +import os +import re +import shutil +import time +from dataclasses import dataclass, field + +import numpy as np + +STRIP_RECT = (964, 525, 964, 350) # x, y, w, h in the 1928x1208 frame +PROPOSER_IN_W = 352 +PROPOSER_IN_H = 128 +PROPOSER_CONF = 0.15 +PROPOSER_IOU = 0.5 +PROPOSER_HZ = 2.0 +PROPOSER_MIN_SPEED_MS = 2.0 + +TRACK_IOU = 0.3 +TRACK_MAX_GAP_S = 1.6 +TRACK_MIN_HITS = 2 +CAPTURE_MIN_H = 60 +CAPTURE_EDGE_X = 1928 - 150 +CAPTURE_MIN_SIDE = 240 +CAPTURE_MAX_SIDE = 480 +CAPTURE_SCALE = 3.0 +MAX_READS_PER_TRACK = 3 +NEG_NAMES = ("neg_yellow", "neg_other") +NEG_SUPPRESS_CONF = 0.40 + + +def resize_area(img: np.ndarray, h: int, w: int) -> np.ndarray: + if img.shape[0] == h and img.shape[1] == w: + return img + try: + import cv2 + return cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA) + except Exception: + from openpilot.selfdrive.speedsignd.nv12 import _resize_gray_bilinear + return _resize_gray_bilinear(img, h, w) + + +def strip_rgb_from_crop(crop) -> np.ndarray: + """NV12 strip crop -> 128x352 RGB uint8 (area resize, BT.601).""" + from openpilot.selfdrive.speedsignd.nv12 import _bt601_yuv_to_rgb + y_s = resize_area(crop.y, PROPOSER_IN_H, PROPOSER_IN_W) + uv = crop.uv + if uv is None or uv.size == 0 or uv.shape[1] < 2: + return np.stack([y_s, y_s, y_s], axis=-1) + u = resize_area(np.ascontiguousarray(uv[:, 0::2]), PROPOSER_IN_H, PROPOSER_IN_W) + v = resize_area(np.ascontiguousarray(uv[:, 1::2]), PROPOSER_IN_H, PROPOSER_IN_W) + return _bt601_yuv_to_rgb(y_s, u, v) + + +def _nms(boxes: np.ndarray, scores: np.ndarray, iou: float) -> list[int]: + order = list(np.argsort(-scores)) + keep: list[int] = [] + while order: + i = order.pop(0) + keep.append(int(i)) + order = [j for j in order if box_iou(boxes[i], boxes[j]) < iou] + return keep + + +def decode_proposals(raw: np.ndarray, crop_xywh, conf: float = PROPOSER_CONF, + in_w: int = PROPOSER_IN_W, in_h: int = PROPOSER_IN_H) -> list[tuple[float, float, float, float, float]]: + """[1,5,N] (cx,cy,w,h,score) at model scale -> frame (x, y, w, h, score), top-left xywh.""" + out = np.asarray(raw) + if out.ndim == 3: + out = out[0] + if out.shape[0] != 5 and out.shape[-1] == 5: + out = out.T + sc = out[4] + idx = np.where(sc >= conf)[0] + if idx.size == 0: + return [] + cx0, cy0, cw, ch = (float(v) for v in crop_xywh) + sx = cw / float(in_w) + sy = ch / float(in_h) + b = out[:4, idx].T + boxes = np.stack([ + (b[:, 0] - b[:, 2] / 2) * sx + cx0, + (b[:, 1] - b[:, 3] / 2) * sy + cy0, + b[:, 2] * sx, + b[:, 3] * sy, + ], axis=1) + s = sc[idx].astype(np.float32) + keep = _nms(boxes, s, PROPOSER_IOU)[:8] + return [(float(boxes[i, 0]), float(boxes[i, 1]), float(boxes[i, 2]), float(boxes[i, 3]), float(s[i])) for i in keep] + + +class Proposer: + """onnxruntime CPU, one thread. None-safe: .ok is False when weights/runtime missing.""" + + def __init__(self, path: str): + self.path = path + self.session = None + self.error = "" + self.load() + + def load(self) -> bool: + if not os.path.isfile(self.path): + self.error = "missing" + return False + try: + import onnxruntime as ort + so = ort.SessionOptions() + so.intra_op_num_threads = 1 + so.inter_op_num_threads = 1 + so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL + self.session = ort.InferenceSession(self.path, so, providers=["CPUExecutionProvider"]) + self._inp = self.session.get_inputs()[0].name + self.error = "" + return True + except Exception as e: + self.session = None + self.error = f"{type(e).__name__}: {e}"[:120] + return False + + @property + def ok(self) -> bool: + return self.session is not None + + def propose(self, crop) -> list[tuple[float, float, float, float, float]]: + if self.session is None or crop is None: + return [] + rgb = strip_rgb_from_crop(crop) + blob = rgb.transpose(2, 0, 1)[None].astype(np.float32) / 255.0 + raw = self.session.run(None, {self._inp: blob})[0] + return decode_proposals(raw, crop.crop) + + +def box_iou(a, b) -> float: + ax0, ay0, aw, ah = a[0], a[1], a[2], a[3] + bx0, by0, bw, bh = b[0], b[1], b[2], b[3] + ix = max(0.0, min(ax0 + aw, bx0 + bw) - max(ax0, bx0)) + iy = max(0.0, min(ay0 + ah, by0 + bh) - max(ay0, by0)) + inter = ix * iy + union = aw * ah + bw * bh - inter + return float(inter / union) if union > 0 else 0.0 + + +def _near(a, b) -> bool: + acx, acy = a[0] + a[2] / 2, a[1] + a[3] / 2 + bcx, bcy = b[0] + b[2] / 2, b[1] + b[3] / 2 + tol = max(a[2], a[3], b[2], b[3]) + 40 + # Signs drift outward (right/up) and grow; allow a larger forward step. + # At 2 Hz a near sign can move ~300 px right per sample; never far left. + return -tol < (bcx - acx) < tol * 3.0 and abs(acy - bcy) < tol + + +@dataclass +class Track: + tid: int + box: tuple[float, float, float, float] + score: float + first_t: float + last_t: float + hits: int = 1 + peak_h: float = 0.0 + reads: int = 0 + neg: bool = False + done: bool = False + history: list = field(default_factory=list) + + def predicted(self, t: float) -> tuple[float, float, float, float]: + """Constant growth / drift from the last two boxes.""" + if len(self.history) < 2: + return self.box + (t0, b0), (t1, b1) = self.history[-2], self.history[-1] + dt = max(1e-3, t1 - t0) + k = min(2.0, (t - t1) / dt) + return tuple(b1[i] + (b1[i] - b0[i]) * k for i in range(4)) # type: ignore[return-value] + + +class SignTracker: + def __init__(self): + self.tracks: list[Track] = [] + self._next = 1 + + def update(self, props, t: float) -> list[Track]: + used = set() + for tr in self.tracks: + if tr.done: + continue + best, bi = 0.0, -1 + for i, p in enumerate(props): + if i in used: + continue + v = box_iou(tr.box, p) + if v < TRACK_IOU and _near(tr.box, p): + v = max(v, TRACK_IOU) + if v > best: + best, bi = v, i + if bi >= 0 and best >= TRACK_IOU: + p = props[bi] + used.add(bi) + tr.box = (p[0], p[1], p[2], p[3]) + tr.score = max(tr.score, p[4]) + tr.hits += 1 + tr.last_t = t + tr.peak_h = max(tr.peak_h, p[3]) + tr.history = (tr.history + [(t, tr.box)])[-4:] + for i, p in enumerate(props): + if i in used: + continue + tr = Track(tid=self._next, box=(p[0], p[1], p[2], p[3]), score=p[4], first_t=t, last_t=t, peak_h=p[3]) + tr.history = [(t, tr.box)] + self._next += 1 + self.tracks.append(tr) + self.tracks = [tr for tr in self.tracks if t - tr.last_t <= TRACK_MAX_GAP_S * 2 and not (tr.done and t - tr.last_t > 1.0)] + return self.tracks + + def capture_candidate(self, t: float) -> Track | None: + """Track due for its sharp read now, or None. Biggest first.""" + due = [] + for tr in self.tracks: + if tr.done or tr.neg or tr.hits < TRACK_MIN_HITS or tr.reads >= MAX_READS_PER_TRACK: + continue + x, y, w, h = tr.predicted(t) + lost = t - tr.last_t > 0.6 + if h >= CAPTURE_MIN_H or x + w >= CAPTURE_EDGE_X or lost or (tr.reads > 0): + due.append(tr) + if not due: + return None + return max(due, key=lambda tr: tr.predicted(t)[3]) + + def mark_read(self, tr: Track, *, got_mph: bool, neg: bool) -> None: + tr.reads += 1 + if neg: + tr.neg = True + tr.done = True + elif got_mph or tr.reads >= MAX_READS_PER_TRACK: + tr.done = True + + +def capture_rect(box, frame_w: int = 1928, frame_h: int = 1208) -> tuple[int, int, int, int]: + x, y, w, h = (float(v) for v in box) + side = int(min(CAPTURE_MAX_SIDE, max(CAPTURE_MIN_SIDE, CAPTURE_SCALE * max(w, h)))) + side = min(side, frame_w, frame_h) + side -= side % 2 + cx, cy = x + w / 2, y + h / 2 + x0 = int(min(max(0, cx - side / 2), frame_w - side)) + y0 = int(min(max(0, cy - side / 2), frame_h - side)) + x0 -= x0 % 2 + y0 -= y0 % 2 + return x0, y0, side, side + + +def neg_read(diag: dict | None) -> bool: + if not diag: + return False + name = str(diag.get("peak_name") or "") + try: + conf = float(diag.get("peak_conf") or 0.0) + except Exception: + conf = 0.0 + return name in NEG_NAMES and conf >= NEG_SUPPRESS_CONF + + +def speed_from_sm(sm) -> float | None: + """Ego speed without carState: GPS speed first, then modelV2 velocity.""" + for svc in ("gpsLocationExternal", "gpsLocation"): + try: + g = sm[svc] + if bool(getattr(g, "hasFix", False)) or int(getattr(g, "flags", 0) or 0) & 1: + return float(g.speed) + except Exception: + pass + try: + vx = sm["modelV2"].velocity.x + if len(vx): + return float(vx[0]) + except Exception: + pass + return None + + +def proposals_allowed(speed_ms: float | None) -> bool: + """Skip the proposer when stopped. Unknown speed is not 'stopped'.""" + return speed_ms is None or speed_ms >= PROPOSER_MIN_SPEED_MS + + +# ---------------------------------------------------------------- feedback +FEEDBACK_DIRNAME = "speedsign_feedback" +PENDING_JSON = "pending.json" +PENDING_JPG = "pending.jpg" +FEEDBACK_JSONL = "feedback.jsonl" +CONFIRMED_JSONL = "confirmed.jsonl" +FEEDBACK_MAX_BYTES = 50 * 1024 * 1024 + + +def feedback_dir() -> str: + override = os.environ.get("NAP_SPEED_SIGN_FEEDBACK") + if override: + return override + from openpilot.selfdrive.speedsignd.paths import nap_data_dir + return os.path.join(nap_data_dir(), FEEDBACK_DIRNAME) + + +def crop_jpeg_bytes(crop) -> bytes | None: + try: + import cv2 + from openpilot.selfdrive.speedsignd.nv12 import _rgb_from_resized_nv12 + rgb = _rgb_from_resized_nv12(crop.y, crop.uv) + ok, enc = cv2.imencode(".jpg", rgb[:, :, ::-1], [int(cv2.IMWRITE_JPEG_QUALITY), 90]) + return bytes(enc) if ok else None + except Exception: + return None + + +def write_pending(meta: dict, jpg: bytes | None, d: str | None = None) -> bool: + """speedsignd: the read now on the plate (overwritten each new plate). Atomic.""" + d = d or feedback_dir() + try: + os.makedirs(d, exist_ok=True) + if jpg: + with open(os.path.join(d, PENDING_JPG + ".tmp"), "wb") as f: + f.write(jpg) + os.replace(os.path.join(d, PENDING_JPG + ".tmp"), os.path.join(d, PENDING_JPG)) + m = dict(meta) + m["has_jpg"] = bool(jpg) + with open(os.path.join(d, PENDING_JSON + ".tmp"), "w") as f: + json.dump(m, f) + os.replace(os.path.join(d, PENDING_JSON + ".tmp"), os.path.join(d, PENDING_JSON)) + return True + except Exception: + return False + + +def _dir_bytes(d: str) -> int: + n = 0 + try: + for e in os.scandir(d): + if e.is_file(): + n += e.stat().st_size + except Exception: + pass + return n + + +REALDATA_PREFIX = "speedsign_" +_SEG_RE = re.compile(r"^[0-9a-f]{8}--[0-9a-f]{10}--\d+$") +CURRENT_SEG_MAX_AGE_S = 300.0 + + +def current_segment_dir(root: str | None = None, now: float | None = None) -> str | None: + """Newest loggerd segment folder under realdata, if written in the last 5 min.""" + if root is None: + try: + from openpilot.system.hardware.hw import Paths + root = Paths.log_root() + except Exception: + return None + now = time.time() if now is None else now # noqa: TID251 compare with file mtimes + best, best_m = None, -1.0 + try: + with os.scandir(root) as it: + for e in it: + if not (_SEG_RE.match(e.name) and e.is_dir(follow_symlinks=False)): + continue + m = e.stat(follow_symlinks=False).st_mtime + if m > best_m: + best, best_m = e.path, m + except OSError: + return None + if best is None or now - best_m > CURRENT_SEG_MAX_AGE_S: + return None + return best + + +def copy_to_realdata(rec: dict, line: str, d: str, root: str | None = None, now: float | None = None) -> str | None: + """Mirror one feedback row (+ crop) into the current route segment folder. + + athena uploadFilesToUrls only reaches files under realdata, so harvest can + pull speedsign_feedback.jsonl / speedsign___.jpg per + segment. The uploader never auto-sends these names (not qlog/qcamera). + """ + seg = current_segment_dir(root, now=now) + if seg is None: + return None + try: + with open(os.path.join(seg, REALDATA_PREFIX + FEEDBACK_JSONL), "a") as f: + f.write(line) + jpg = rec.get("jpg") + if jpg and os.path.isfile(os.path.join(d, jpg)): + shutil.copyfile(os.path.join(d, jpg), os.path.join(seg, REALDATA_PREFIX + jpg)) + return os.path.basename(seg) + except OSError: + return None + + +def record_answer(displayed_mph: int, yes: bool, d: str | None = None, now: float | None = None) -> dict | None: + """UI Yes/No: append feedback.jsonl (+confirmed.jsonl on Yes), keep the crop JPEG. + + Uses the pending read only when its mph matches the plate the driver saw. + No upload, no cruise / HUD / map-speed change. + """ + d = d or feedback_dir() + now = time.time() if now is None else now # noqa: TID251 wall clock for feedback rows + try: + os.makedirs(d, exist_ok=True) + meta: dict = {} + try: + with open(os.path.join(d, PENDING_JSON)) as f: + meta = json.load(f) + except Exception: + meta = {} + if int(meta.get("mph", -1)) != int(displayed_mph): + meta = {"mph": int(displayed_mph), "stale_pending": True} + stamp = time.strftime("%Y%m%d_%H%M%S", time.localtime(now)) + rec = { + "t": round(now, 3), + "answer": "yes" if yes else "no", + "displayed_mph": int(displayed_mph), + "class": meta.get("class"), + "conf": meta.get("conf"), + "refine_mph": meta.get("refine_mph"), + "refine_conf": meta.get("refine_conf"), + "track_id": meta.get("track_id"), + "read_t": meta.get("t"), + "lat": meta.get("lat"), + "lon": meta.get("lon"), + "bearing": meta.get("bearing"), + "gps_ok": meta.get("gps_ok"), + "crop": meta.get("crop"), + "stale_pending": bool(meta.get("stale_pending", False)), + } + src = os.path.join(d, PENDING_JPG) + if meta.get("has_jpg") and not rec["stale_pending"] and os.path.isfile(src) and _dir_bytes(d) < FEEDBACK_MAX_BYTES: + name = f"{stamp}_{rec['answer']}_{int(displayed_mph)}.jpg" + shutil.copyfile(src, os.path.join(d, name)) + rec["jpg"] = name + line = json.dumps(rec, separators=(",", ":")) + "\n" + with open(os.path.join(d, FEEDBACK_JSONL), "a") as f: + f.write(line) + if yes and not rec["stale_pending"]: + with open(os.path.join(d, CONFIRMED_JSONL), "a") as f: + f.write(line) + rec["realdata"] = copy_to_realdata(rec, line, d, now=now) + return rec + except Exception: + return None diff --git a/selfdrive/speedsignd/weights_manifest.py b/selfdrive/speedsignd/weights_manifest.py new file mode 100644 index 00000000000000..8548372fa6129a --- /dev/null +++ b/selfdrive/speedsignd/weights_manifest.py @@ -0,0 +1,119 @@ +"""Where speedsignd fetches the compact US MUTCD speed-sign ONNX. + +Weights stay off git. Clone/flash stays small; +`python -m scripts.nap.install_speed_sign_weights` pulls the ONNX onto +`/data/media/0/nap/speed_sign.onnx` and replaces any older file. + +Source model: YOLOv8n, imgsz 320, opset 12. Trained on 640×640 native +crops resized to 320 (scale 0.5), which matches the 628×320 road window +letterboxed at 320/628 ≈ 0.51. Output `[1, 17, 2100]` (xywh + 13 classes). +v3 (speed-sign-onnx-v3) is fine-tuned from v2 on capture-style crops +(sign ~1/3 of a 240-480 px crop), same class order and output shape. +Do not commit the ONNX. Release: speed-sign-onnx-v3 / speed_sign.onnx. +""" +from __future__ import annotations + +# Host + tag for the pre-exported ONNX. Bump when republishing. +GITHUB_REPO = "jmbrunick/openpilot" +RELEASE_TAG = "speed-sign-onnx-v3" +ASSET_NAME = "speed_sign.onnx" +RELEASE_REVISION = "3" + +# HuggingFace checkpoint used by scripts.nap.export_speed_sign_onnx. +# The shipped detector is the v2 Release asset, not a fresh export of this pt. +HF_REPO = "cvtechniques/JC-Traffic-Sign-Detection" +HF_PT_PATH = "trainv8/weights/best.pt" +HF_PT_SHA256 = "74089754755d904d724e07ec9d74488427decc11c1c8af323e2b4524664575ae" + +# SHA-256 of speed-sign-onnx-v3 / speed_sign.onnx (opset 12, 320²). +ASSET_SHA256 = "45e8d444df547a1c9176fd904991e39c2ab8ae1a7624213178ce215b1ec6fb13" +ASSET_BYTES = 12658971 + +# v2 fallback: same 13-class order and [1, 17, 2100] output, so an +# already-installed v2 file still loads, and Install falls back to the v2 +# asset if the v3 asset can't be downloaded. +FALLBACK_RELEASE_TAG = "speed-sign-onnx-v2" +FALLBACK_SHA256 = "1131200b7fe2d400596e09d7680fc3a26a08dcd8952acfdf261170bdb22d3d28" +FALLBACK_BYTES = 12658953 +COMPATIBLE_SHA256 = (ASSET_SHA256, FALLBACK_SHA256) + +# CPU onnxruntime for the stock 3X. The image has neither onnxruntime nor +# cv2.dnn (route 00000180: onnxruntime-absent(ModuleNotFoundError), +# cv2-dnn-absent). This is the PyPI CPU wheel, not onnxruntime-gpu. +# ELF AArch64, tag cp312, manylinux_2_28, max GLIBC_2.28, NEEDED only +# libc/libstdc++/libm/libgcc_s/libdl/librt/libpthread/ld-linux-aarch64. +# openpilot requires Python >=3.12.3,<3.13. AGNOS 18.4 is newer than 2.28. +# Same 1.31.0 CPU build measured ~12 ms / ~180 GFLOP/s on one x86 thread. +ORT_VERSION = "1.31.0" +ORT_PYTHON = "cp312" +ORT_PLATFORM = "manylinux_2_28_aarch64" +ORT_WHEEL = "onnxruntime-1.31.0-cp312-cp312-manylinux_2_28_aarch64.whl" +ORT_SHA256 = "35758d7606d578ec5b9d65f6e8a1f488013194c3f6097038a3223cb26d35ef9a" +ORT_BYTES = 21420804 +ORT_URL = ( + "https://files.pythonhosted.org/packages/53/1a/" + + "561b43ca1536d9e81d1785bb8a1a260a9e314ef6d04976ba0411c652bda1/" + + ORT_WHEEL +) + +USER_AGENT = "NotAutopilot-speedsignd/1.0 (https://github.com/jmbrunick/openpilot)" + +# Ultralytics YOLOv8n export at imgsz=320. ~2.2 GFLOP, about 4× cheaper than +# the v8s weights this replaced. Do not raise on-device imgsz. +YOLO_IMGSZ = 320 +YOLO_INPUT_NAME = "images" +YOLO_OUTPUT_LAYOUT = (1, 17, 2100) # 4 + 13 classes, 2100 anchors + +# Class order from speed-sign-onnx-v2/v3 metadata `names`. +# 0 sl_25 … 9 sl_70, 10 sl_unreadable, 11 neg_yellow, 12 neg_other. +# sl_unreadable may schedule the OCR second look. neg_* and sl_unreadable +# are not mph. +YOLO_CLASS_NAMES: tuple[str, ...] = ( + "sl_25", + "sl_30", + "sl_35", + "sl_40", + "sl_45", + "sl_50", + "sl_55", + "sl_60", + "sl_65", + "sl_70", + "sl_unreadable", + "neg_yellow", + "neg_other", +) + +# Empty-road max is ~0. Do not lower: misreads (30/35/60 as 50, 60 as 30) +# are already common at 0.40. A lower floor would light more of them. +YOLO_MIN_CONF = 0.40 +YOLO_IOU = 0.45 +YOLO_MAX_DET = 3 + +# JSONL and the HUD both need two reads of the same mph from different +# frames. v8n on one A55 is expected around 1–4 s, so the 25% duty gap is +# about 4–16 s. 12 s covers two reads when infer is up to ~3 s. A slower +# infer can miss the window; that is a miss, not a wrong mph. +DEBOUNCE_HITS = 2 +DEBOUNCE_WINDOW_S = 12.0 + + +# Two-stage strip proposer: 1-class "sign" YOLOv8 (width 0.125), input +# [1,3,128,352] = lower-right strip x 964-1928, y 525-875, output [1,5,924]. +# Trained on Justin's drives + teacher pseudo-labels + night augmentation. +PROPOSER_RELEASE_TAG = "speed-sign-proposer-v1" +PROPOSER_ASSET_NAME = "sign_proposer.onnx" +PROPOSER_SHA256 = "1ef4b7d4131678399e2a2b2049276637759f7e2e3829d1441e98a1e43be94422" +PROPOSER_BYTES = 3732311 + + +def proposer_asset_url(repo: str = GITHUB_REPO) -> str: + return f"https://github.com/{repo}/releases/download/{PROPOSER_RELEASE_TAG}/{PROPOSER_ASSET_NAME}" + + +def release_asset_url(repo: str = GITHUB_REPO, tag: str = RELEASE_TAG, asset: str = ASSET_NAME) -> str: + return f"https://github.com/{repo}/releases/download/{tag}/{asset}" + + +def hf_pt_url(repo: str = HF_REPO, path: str = HF_PT_PATH) -> str: + return f"https://huggingface.co/{repo}/resolve/main/{path}" diff --git a/selfdrive/speedsignd/yolo.py b/selfdrive/speedsignd/yolo.py new file mode 100644 index 00000000000000..795adf314780d1 --- /dev/null +++ b/selfdrive/speedsignd/yolo.py @@ -0,0 +1,454 @@ +"""YOLOv8 ONNX decode for the US MUTCD speed-sign detector. + +Expects an Ultralytics detect export: + input `images` float32 [1,3,H,W] RGB 0..1 (letterboxed) + output `output0` float32 [1,4+nc,N] (or [1,N,4+nc]) = cx,cy,w,h + class scores +""" +from __future__ import annotations + +import re +from dataclasses import replace +from typing import NamedTuple + +import numpy as np + +from openpilot.selfdrive.speedsignd.detect_types import MUTCD_MPH, US_POSTED_MPH, SpeedSign +from openpilot.selfdrive.speedsignd.nv12 import native_detect_window +from openpilot.selfdrive.speedsignd.weights_manifest import ( + YOLO_CLASS_NAMES, + YOLO_IMGSZ, + YOLO_IOU, + YOLO_MAX_DET, + YOLO_MIN_CONF, +) + +# Justin parked close 50: top=speedLimit65:0.73–0.76, raw=[(65,0.73)], +# cls=30:0.00,50:0.00,60:0.00 — the 50 head is at zero, not a close race. +# Class-margin cannot fix a confidently wrong YOLO head. Prefer any crop +# digit read that returns a different MUTCD mph at this floor. +# _read_mph already requires min digit NCC ≥ 0.25. +REFINE_OVERRIDE_CONF = 0.28 +CROP_OVERRIDE_CONF = REFINE_OVERRIDE_CONF # old name; was 0.55 and hid 50s + +# v2 names are sl_25 … sl_70. speedLimitNN still parses so older logs and +# tests that name a class that way stay readable. sl_unreadable does not match. +_SPEED_RE = re.compile(r"^(?:speedLimit|sl_)(\d+)$") + +# Below this, a class name is argmax-of-noise. Do not treat it as a mph read. +PEAK_NAME_MIN = 0.05 +# Below YOLO_MIN_CONF. Schedules a second look only — never lights the HUD alone. +SIGN_LIKE_CONF = 0.15 +# Posted heads worth logging. v2 has sl_30/50/60/65; 65 is still the common miss. +POSTED_LOG_MPH = (30, 50, 60, 65) + + +def class_to_mph(name: str) -> int | None: + """MUTCD mph from sl_NN or speedLimitNN. sl_unreadable and neg_* are None.""" + m = _SPEED_RE.match(str(name)) + if not m: + return None + value = int(m.group(1)) + return value if value in MUTCD_MPH else None + + +def is_unreadable_name(name: str) -> bool: + """Box the OCR second look may use. Not an mph.""" + return str(name) == "sl_unreadable" + + +def is_negative_name(name: str) -> bool: + """Yellow advisory / other non-speed. Never a box, never an mph.""" + return str(name).startswith("neg_") + + +def speed_limit_class_indices(names: tuple[str, ...] = YOLO_CLASS_NAMES) -> tuple[int, ...]: + """Indices whose names are sl_NN / speedLimitNN. Excludes sl_unreadable and neg_*.""" + return tuple(i for i, n in enumerate(names) if class_to_mph(n) is not None) + + +def _look_indices(names: tuple[str, ...]) -> list[int]: + """Speed classes plus sl_unreadable. neg_* stay out of the argmax.""" + out = list(speed_limit_class_indices(names)) + for i, n in enumerate(names): + if is_unreadable_name(n): + out.append(i) + return out + + +class YoloPeak(NamedTuple): + """Pre-threshold snapshot: global peak, speedLimit* peak, top-3, posted heads.""" + shape: tuple + conf: float + name: str + n_over: int + sl_conf: float = 0.0 + sl_name: str = "" + n_over_sl: int = 0 + top3: tuple[tuple[str, float], ...] = () + posted: tuple[tuple[int, float], ...] = () + + +def letterbox_rgb(rgb: np.ndarray, size: int = YOLO_IMGSZ) -> tuple[np.ndarray, float, int, int]: + """Resize with aspect ratio, pad to size×size. Returns image, scale, pad_x, pad_y.""" + if rgb.ndim != 3 or rgb.shape[2] != 3: + raise ValueError("letterbox_rgb expects HxWx3") + h, w = rgb.shape[:2] + scale = min(size / float(h), size / float(w)) + nh = max(1, int(round(h * scale))) + nw = max(1, int(round(w * scale))) + resized = _resize_rgb(rgb, nh, nw) + canvas = np.full((size, size, 3), 114, dtype=np.uint8) + top = (size - nh) // 2 + left = (size - nw) // 2 + canvas[top:top + nh, left:left + nw] = resized + return canvas, scale, left, top + + +def road_detect_crop_rect(h: int, w: int) -> tuple[int, int, int, int]: + """Right-side native window. Same pixels the ONNX letterboxes. + + The rect is independent of YOLO_IMGSZ. A 320 model letterboxes 628×320 + at scale 320/628, which keeps a ≥60 px sign at ≥30 px. + """ + return native_detect_window(h, w) + + +def road_detect_crop(rgb: np.ndarray) -> tuple[np.ndarray, tuple[int, int, int, int]]: + """Right-side window. Width and height follow native_detect_window.""" + if rgb.ndim != 3 or rgb.shape[2] != 3: + raise ValueError("road_detect_crop expects HxWx3") + h, w = rgb.shape[:2] + x, y, cw, ch = road_detect_crop_rect(h, w) + return rgb[y:y + ch, x:x + cw], (x, y, cw, ch) + + +def _resize_rgb(img: np.ndarray, h: int, w: int) -> np.ndarray: + """Bilinear resize. Nearest index-sampling destroyed distant R2-1s at 6×.""" + if img.shape[0] == h and img.shape[1] == w: + return img + try: + import cv2 + return cv2.resize(img, (w, h), interpolation=cv2.INTER_LINEAR) + except Exception: + return _resize_rgb_bilinear(img, h, w) + + +def _resize_rgb_bilinear(img: np.ndarray, h: int, w: int) -> np.ndarray: + src_h, src_w = img.shape[:2] + if src_h < 1 or src_w < 1: + return np.zeros((h, w, img.shape[2]), dtype=img.dtype) + ys = (np.arange(h, dtype=np.float32) + 0.5) * (src_h / float(h)) - 0.5 + xs = (np.arange(w, dtype=np.float32) + 0.5) * (src_w / float(w)) - 0.5 + ys = np.clip(ys, 0.0, src_h - 1.0) + xs = np.clip(xs, 0.0, src_w - 1.0) + y0 = np.floor(ys).astype(np.int32) + x0 = np.floor(xs).astype(np.int32) + y1 = np.minimum(y0 + 1, src_h - 1) + x1 = np.minimum(x0 + 1, src_w - 1) + wy = (ys - y0).astype(np.float32)[:, None, None] + wx = (xs - x0).astype(np.float32)[None, :, None] + img_f = img.astype(np.float32) + i00 = img_f[y0][:, x0] + i01 = img_f[y0][:, x1] + i10 = img_f[y1][:, x0] + i11 = img_f[y1][:, x1] + out = (i00 * (1.0 - wx) + i01 * wx) * (1.0 - wy) + (i10 * (1.0 - wx) + i11 * wx) * wy + return np.clip(np.rint(out), 0, 255).astype(np.uint8) + + +def nms_xyxy(boxes: np.ndarray, scores: np.ndarray, iou_thr: float = YOLO_IOU, max_det: int = YOLO_MAX_DET) -> list[int]: + """Greedy IoU NMS. boxes are [N,4] xyxy.""" + if len(boxes) == 0: + return [] + order = scores.argsort()[::-1] + keep: list[int] = [] + while order.size and len(keep) < max_det: + i = int(order[0]) + keep.append(i) + if order.size == 1: + break + rest = order[1:] + xx1 = np.maximum(boxes[i, 0], boxes[rest, 0]) + yy1 = np.maximum(boxes[i, 1], boxes[rest, 1]) + xx2 = np.minimum(boxes[i, 2], boxes[rest, 2]) + yy2 = np.minimum(boxes[i, 3], boxes[rest, 3]) + inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1) + area_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1]) + area_r = (boxes[rest, 2] - boxes[rest, 0]) * (boxes[rest, 3] - boxes[rest, 1]) + iou = inter / np.maximum(1e-6, area_i + area_r - inter) + order = rest[iou <= iou_thr] + return keep + + +def _as_cn(raw: np.ndarray) -> np.ndarray: + """Normalize YOLO output to [4+nc, N]. Squeeze tinygrad singleton dims.""" + arr = np.squeeze(np.asarray(raw, dtype=np.float32)) + if arr.ndim == 3 and arr.shape[0] == 1: + arr = arr[0] + if arr.ndim != 2: + return np.zeros((0, 0), np.float32) + channels = 4 + len(YOLO_CLASS_NAMES) + if arr.shape[0] == channels: + return arr + if arr.shape[1] == channels: + return arr.T + # Unknown nc: prefer the shorter axis as channels (4+nc << anchors). + if arr.shape[0] <= arr.shape[1] and arr.shape[0] >= 6: + return arr + if arr.shape[1] >= 6: + return arr.T + return arr + + +def yolo_peak(raw, names: tuple[str, ...] = YOLO_CLASS_NAMES) -> YoloPeak: + """Pre-threshold peak: global top class, speedLimit* peak, top-3 class peaks.""" + arr = np.asarray(raw) + shape = tuple(int(v) for v in arr.shape) + pred = _as_cn(raw) + empty = YoloPeak(shape, 0.0, "", 0) + if pred.size == 0 or pred.shape[0] < 5: + return empty + scores = pred[4:] + if scores.size == 0: + return empty + if scores.ndim != 2: + scores = scores.reshape(-1, 1) + conf = scores.max(axis=0) + cls = scores.argmax(axis=0) + if conf.size == 0: + return empty + i = int(conf.argmax()) + max_conf = float(conf[i]) + top = int(cls[i]) if cls.size else 0 + name = names[top] if 0 <= top < len(names) else str(top) + if max_conf < PEAK_NAME_MIN: + name = "" + n_over = int(np.sum(conf >= YOLO_MIN_CONF)) + + sl_conf, sl_name, n_over_sl = 0.0, "", 0 + sl_idx = [k for k in speed_limit_class_indices(names) if k < scores.shape[0]] + if sl_idx: + sl = scores[np.array(sl_idx, dtype=np.int32)] + sl_per_anchor = sl.max(axis=0) + j = int(sl_per_anchor.argmax()) + sl_conf = float(sl_per_anchor[j]) + sl_local = int(sl[:, j].argmax()) + sl_top = sl_idx[sl_local] + sl_name = names[sl_top] if 0 <= sl_top < len(names) else str(sl_top) + if sl_conf < PEAK_NAME_MIN: + sl_name = "" + n_over_sl = int(np.sum(sl_per_anchor >= YOLO_MIN_CONF)) + + class_peak = scores.max(axis=1) + order = class_peak.argsort()[::-1] + top3 = tuple( + (names[int(k)] if 0 <= int(k) < len(names) else str(int(k)), float(class_peak[k])) + for k in order + if float(class_peak[k]) >= PEAK_NAME_MIN + )[:3] + posted: list[tuple[int, float]] = [] + for mph in POSTED_LOG_MPH: + idx = None + for label in (f"sl_{mph}", f"speedLimit{mph}"): + try: + idx = names.index(label) + break + except ValueError: + continue + if idx is None: + posted.append((mph, 0.0)) + continue + posted.append((mph, float(class_peak[idx]) if idx < class_peak.shape[0] else 0.0)) + return YoloPeak(shape, max_conf, name, n_over, sl_conf, sl_name, n_over_sl, top3, tuple(posted)) + + +def decode_yolov8( + raw, + *, + scale: float, + pad_x: int, + pad_y: int, + src_hw: tuple[int, int], + names: tuple[str, ...] = YOLO_CLASS_NAMES, + min_conf: float = YOLO_MIN_CONF, + iou: float = YOLO_IOU, + max_det: int = YOLO_MAX_DET, +) -> list[SpeedSign]: + pred = _as_cn(raw) + if pred.size == 0 or pred.shape[0] < 5: + return [] + boxes_xywh = pred[:4].T + scores = pred[4:].T + if scores.size == 0: + return [] + # Argmax over sl_* and sl_unreadable only. neg_* must not hide a plate + # and must not become a detection. sl_unreadable is a box for the second + # look, not an mph. + sl_idx = [k for k in _look_indices(names) if k < scores.shape[1]] + alt_cls = None + alt_conf = None + if sl_idx: + sl = scores[:, np.array(sl_idx, dtype=np.int32)] + local = sl.argmax(axis=1) + conf = sl.max(axis=1) + cls = np.array(sl_idx, dtype=np.int32)[local] + sl2 = sl.copy() + sl2[np.arange(sl2.shape[0]), local] = -1.0 + local2 = sl2.argmax(axis=1) + alt_conf = sl2.max(axis=1) + alt_cls = np.array(sl_idx, dtype=np.int32)[local2] + else: + cls = scores.argmax(axis=1) + conf = scores.max(axis=1) + mask = conf >= min_conf + if not np.any(mask): + return [] + boxes_xywh = boxes_xywh[mask] + conf = conf[mask] + cls = cls[mask] + if alt_cls is not None and alt_conf is not None: + alt_cls = alt_cls[mask] + alt_conf = alt_conf[mask] + + cx, cy, bw, bh = boxes_xywh[:, 0], boxes_xywh[:, 1], boxes_xywh[:, 2], boxes_xywh[:, 3] + xyxy = np.stack([cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2], axis=1) + keep = nms_xyxy(xyxy, conf, iou_thr=iou, max_det=max(max_det * 3, 8)) + + src_h, src_w = src_hw + inv = 1.0 / scale if scale > 1e-6 else 1.0 + found: list[SpeedSign] = [] + for i in keep: + name = names[int(cls[i])] if 0 <= int(cls[i]) < len(names) else "" + if is_negative_name(name): + continue + unreadable = is_unreadable_name(name) + mph = None if unreadable else class_to_mph(name) + if mph is None and not unreadable: + continue + x1 = (xyxy[i, 0] - pad_x) * inv + y1 = (xyxy[i, 1] - pad_y) * inv + x2 = (xyxy[i, 2] - pad_x) * inv + y2 = (xyxy[i, 3] - pad_y) * inv + x = int(round(max(0.0, min(x1, x2)))) + y = int(round(max(0.0, min(y1, y2)))) + w = int(round(max(1.0, abs(x2 - x1)))) + h = int(round(max(1.0, abs(y2 - y1)))) + if x >= src_w or y >= src_h: + continue + w = min(w, src_w - x) + h = min(h, src_h - y) + alt_mph = None + alt_c = 0.0 + if alt_cls is not None and alt_conf is not None: + alt_name = names[int(alt_cls[i])] if 0 <= int(alt_cls[i]) < len(names) else "" + alt_mph = class_to_mph(alt_name) + alt_c = float(alt_conf[i]) + if alt_mph == mph: + alt_mph, alt_c = None, 0.0 + if unreadable: + # mph 0 and no class_mph: HUD and JSONL cannot treat this as a plate. + # conf stays so the second look can use the box. + found.append(SpeedSign( + mph=0, conf=float(conf[i]), bbox=(x, y, w, h), + class_mph=None, class_conf=0.0, + )) + else: + found.append(SpeedSign( + mph=int(mph), conf=float(conf[i]), bbox=(x, y, w, h), + class_mph=int(mph), class_conf=float(conf[i]), + alt_mph=alt_mph, alt_conf=alt_c, + )) + if len(found) >= max_det: + break + found.sort(key=lambda s: s.conf, reverse=True) + return found + + +def ocr_dropped_digit(class_mph: int, ocr_mph: int) -> bool: + """True when OCR is a shorter prefix or suffix of the class (45 read as 5).""" + src = str(int(class_mph)) + dst = str(int(ocr_mph)) + if not dst or len(dst) >= len(src): + return False + return src.startswith(dst) or src.endswith(dst) + + +def _posted_ocr(mph) -> int | None: + try: + value = int(mph) + except (TypeError, ValueError): + return None + return value if value in US_POSTED_MPH else None + + +def prefer_refine(sign: SpeedSign, mph: int, conf: float) -> bool: + """Prefer crop digits over YOLO class when the read is a real posted limit. + + Justin's parked 50 is class 65 @ 0.73 with cls=50:0.00. Do not require a + runner-up margin — the 50 head is not in the race. A value outside 5–85 + step 5 never replaces the class, and a dropped digit (45 → 5) does not either. + """ + ocr = _posted_ocr(mph) + if ocr is None or conf < REFINE_OVERRIDE_CONF: + return False + raw = sign.class_mph if sign.class_mph is not None else sign.mph + class_i = _posted_ocr(raw) + if class_i is not None and ocr_dropped_digit(class_i, ocr): + return False + return True + + +def refine_mph(sign: SpeedSign, y: np.ndarray | None, read_mph) -> SpeedSign: + """Digit read on every in-threshold speed-limit crop. Does not invent a hit. + + A different posted limit (5–85, step 5) at the override floor replaces + sign.mph. Anything else — 4, 46, 100, a dropped digit such as 45 → 5 — + leaves the class mph alone and is not stored as refine_mph, so it cannot + contradict the class into a blank vote. sl_unreadable (mph not in MUTCD, + no class_mph) is left unchanged. Logs keep both class_mph and refine_mph. + """ + if sign.class_mph is None and int(sign.mph) not in MUTCD_MPH: + return sign + if y is None or y.ndim != 2: + return sign + x, yy, w, h = sign.bbox + if w < 12 or h < 12: + return sign + inset = max(3, int(min(w, h) * 0.06)) + x0 = max(0, x + inset) + y0 = max(0, yy + inset) + x1 = min(y.shape[1], x + w - inset) + y1 = min(y.shape[0], yy + h - inset) + if x1 - x0 < 12 or y1 - y0 < 12: + return sign + crop = y[y0:y1, x0:x1] + if crop.size == 0: + return sign + mph, conf = read_mph(crop) + raw_class = sign.class_mph if sign.class_mph is not None else sign.mph + try: + class_i = int(raw_class) + except (TypeError, ValueError): + class_i = None + ocr_i = _posted_ocr(mph) + dropped = ( + ocr_i is not None and class_i is not None and class_i in US_POSTED_MPH + and ocr_dropped_digit(class_i, ocr_i) + ) + usable = ocr_i is not None and not dropped + tagged = replace( + sign, + class_mph=class_i if sign.class_mph is not None else sign.class_mph, + class_conf=float(sign.class_conf or sign.conf), + refine_mph=ocr_i if usable else None, + refine_conf=float(conf) if usable else 0.0, + ) + if not usable or ocr_i is None: + return tagged + if ocr_i == int(sign.mph): + return replace(tagged, conf=float(min(1.0, max(float(sign.conf), float(conf))))) + if prefer_refine(sign, ocr_i, float(conf)): + if class_i in US_POSTED_MPH and ocr_i not in US_POSTED_MPH: + return tagged + return replace(tagged, mph=ocr_i, conf=float(conf)) + return tagged diff --git a/selfdrive/test/.gitignore b/selfdrive/test/.gitignore index 5801faadf4ec84..b8c6bebd953635 100644 --- a/selfdrive/test/.gitignore +++ b/selfdrive/test/.gitignore @@ -3,7 +3,7 @@ docker_out/ process_replay/diff.txt process_replay/model_diff.txt +process_replay/fakedata/ valgrind_logs.txt -*.bz2 *.hevc diff --git a/selfdrive/test/ci_shell.sh b/selfdrive/test/ci_shell.sh deleted file mode 100755 index 76f0a9f78c9e05..00000000000000 --- a/selfdrive/test/ci_shell.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -OP_ROOT="$DIR/../../" - -if [ -z "$BUILD" ]; then - docker pull ghcr.io/commaai/openpilot-base:latest -else - docker build --cache-from ghcr.io/commaai/openpilot-base:latest -t ghcr.io/commaai/openpilot-base:latest -f $OP_ROOT/Dockerfile.openpilot_base . -fi - -docker run \ - -it \ - --rm \ - --volume $OP_ROOT:$OP_ROOT \ - --workdir $PWD \ - --env PYTHONPATH=$OP_ROOT \ - ghcr.io/commaai/openpilot-base:latest \ - /bin/bash diff --git a/selfdrive/test/ciui.py b/selfdrive/test/ciui.py deleted file mode 100755 index f3b0c1a98f357f..00000000000000 --- a/selfdrive/test/ciui.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python3 -import signal -import subprocess - -signal.signal(signal.SIGINT, signal.SIG_DFL) -signal.signal(signal.SIGTERM, signal.SIG_DFL) - -from PyQt5.QtCore import QTimer -from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel -from openpilot.selfdrive.ui.qt.python_helpers import set_main_window - -class Window(QWidget): - def __init__(self, parent=None): - super().__init__(parent) - - layout = QVBoxLayout() - self.setLayout(layout) - - self.l = QLabel("jenkins runner") - layout.addWidget(self.l) - layout.addStretch(1) - layout.setContentsMargins(20, 20, 20, 20) - - cmds = [ - "cat /etc/hostname", - "echo AGNOS v$(cat /VERSION)", - "uptime -p", - ] - self.labels = {} - for c in cmds: - self.labels[c] = QLabel(c) - layout.addWidget(self.labels[c]) - - self.setStyleSheet(""" - * { - color: white; - font-size: 55px; - background-color: black; - font-family: "JetBrains Mono"; - } - """) - - self.timer = QTimer() - self.timer.timeout.connect(self.update) - self.timer.start(10 * 1000) - self.update() - - def update(self): - for cmd, label in self.labels.items(): - out = subprocess.run(cmd, capture_output=True, - shell=True, check=False, encoding='utf8').stdout - label.setText(out.strip()) - -if __name__ == "__main__": - app = QApplication([]) - w = Window() - set_main_window(w) - app.exec_() diff --git a/selfdrive/test/cpp_harness.py b/selfdrive/test/cpp_harness.py index f9d3e681a54ffa..f9f425102b8515 100755 --- a/selfdrive/test/cpp_harness.py +++ b/selfdrive/test/cpp_harness.py @@ -4,8 +4,7 @@ from openpilot.common.prefix import OpenpilotPrefix - with OpenpilotPrefix(): ret = subprocess.call(sys.argv[1:]) -exit(ret) +sys.exit(ret) diff --git a/selfdrive/test/docker_build.sh b/selfdrive/test/docker_build.sh index 4d58a1507c2326..8d1fa82249874e 100755 --- a/selfdrive/test/docker_build.sh +++ b/selfdrive/test/docker_build.sh @@ -1,12 +1,14 @@ #!/usr/bin/env bash set -e -# To build sim and docs, you can run the following to mount the scons cache to the same place as in CI: -# mkdir -p .ci_cache/scons_cache -# sudo mount --bind /tmp/scons_cache/ .ci_cache/scons_cache - SCRIPT_DIR=$(dirname "$0") OPENPILOT_DIR=$SCRIPT_DIR/../../ + +DOCKER_IMAGE=openpilot +DOCKER_FILE=Dockerfile.openpilot +DOCKER_REGISTRY=ghcr.io/commaai +COMMIT_SHA=$(git rev-parse HEAD) + if [ -n "$TARGET_ARCHITECTURE" ]; then PLATFORM="linux/$TARGET_ARCHITECTURE" TAG_SUFFIX="-$TARGET_ARCHITECTURE" @@ -15,9 +17,11 @@ else TAG_SUFFIX="" fi -source $SCRIPT_DIR/docker_common.sh $1 "$TAG_SUFFIX" +LOCAL_TAG=$DOCKER_IMAGE$TAG_SUFFIX +REMOTE_TAG=$DOCKER_REGISTRY/$LOCAL_TAG +REMOTE_SHA_TAG=$DOCKER_REGISTRY/$LOCAL_TAG:$COMMIT_SHA -DOCKER_BUILDKIT=1 docker buildx build --provenance false --pull --platform $PLATFORM --load --cache-to type=inline --cache-from type=registry,ref=$REMOTE_TAG -t $DOCKER_IMAGE:latest -t $REMOTE_TAG -t $LOCAL_TAG -f $OPENPILOT_DIR/$DOCKER_FILE $OPENPILOT_DIR +DOCKER_BUILDKIT=1 docker buildx build --provenance false --pull --platform $PLATFORM --load -t $DOCKER_IMAGE:latest -t $REMOTE_TAG -t $LOCAL_TAG -f $OPENPILOT_DIR/$DOCKER_FILE $OPENPILOT_DIR if [ -n "$PUSH_IMAGE" ]; then docker push $REMOTE_TAG diff --git a/selfdrive/test/docker_common.sh b/selfdrive/test/docker_common.sh deleted file mode 100644 index 2887fff74bc32e..00000000000000 --- a/selfdrive/test/docker_common.sh +++ /dev/null @@ -1,18 +0,0 @@ -if [ "$1" = "base" ]; then - export DOCKER_IMAGE=openpilot-base - export DOCKER_FILE=Dockerfile.openpilot_base -elif [ "$1" = "prebuilt" ]; then - export DOCKER_IMAGE=openpilot-prebuilt - export DOCKER_FILE=Dockerfile.openpilot -else - echo "Invalid docker build image: '$1'" - exit 1 -fi - -export DOCKER_REGISTRY=ghcr.io/commaai -export COMMIT_SHA=$(git rev-parse HEAD) - -TAG_SUFFIX=$2 -LOCAL_TAG=$DOCKER_IMAGE$TAG_SUFFIX -REMOTE_TAG=$DOCKER_REGISTRY/$LOCAL_TAG -REMOTE_SHA_TAG=$DOCKER_REGISTRY/$LOCAL_TAG:$COMMIT_SHA diff --git a/selfdrive/test/docker_tag_multiarch.sh b/selfdrive/test/docker_tag_multiarch.sh deleted file mode 100755 index c1761802c75214..00000000000000 --- a/selfdrive/test/docker_tag_multiarch.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash -set -e - -if [ $# -lt 2 ]; then - echo "Usage: $0 ..." - exit 1 -fi - -SCRIPT_DIR=$(dirname "$0") -ARCHS=("${@:2}") - -source $SCRIPT_DIR/docker_common.sh $1 - -MANIFEST_AMENDS="" -for ARCH in ${ARCHS[@]}; do - MANIFEST_AMENDS="$MANIFEST_AMENDS --amend $REMOTE_TAG-$ARCH:$COMMIT_SHA" -done - -docker manifest create $REMOTE_TAG $MANIFEST_AMENDS -docker manifest create $REMOTE_SHA_TAG $MANIFEST_AMENDS - -if [[ -n "$PUSH_IMAGE" ]]; then - docker manifest push $REMOTE_TAG - docker manifest push $REMOTE_SHA_TAG -fi diff --git a/selfdrive/test/fuzzy_generation.py b/selfdrive/test/fuzzy_generation.py index 94eb0dfaa62a75..9f028a8fc8dd3e 100644 --- a/selfdrive/test/fuzzy_generation.py +++ b/selfdrive/test/fuzzy_generation.py @@ -44,10 +44,10 @@ def rec(field_type: capnp.lib.capnp._DynamicStructReader) -> st.SearchStrategy: except capnp.lib.capnp.KjException: return self.generate_struct(field.schema) - def generate_struct(self, schema: capnp.lib.capnp._StructSchema, event: str = None) -> st.SearchStrategy[dict[str, Any]]: + def generate_struct(self, schema: capnp.lib.capnp._StructSchema, event: str | None = None) -> st.SearchStrategy[dict[str, Any]]: single_fill: tuple[str, ...] = (event,) if event else (self.draw(st.sampled_from(schema.union_fields)),) if schema.union_fields else () - fields_to_generate = schema.non_union_fields + single_fill - return st.fixed_dictionaries({field: self.generate_field(schema.fields[field]) for field in fields_to_generate if not field.endswith('DEPRECATED')}) + fields_to_generate = [f for f in schema.non_union_fields + single_fill if not f.endswith('DEPRECATED') and f != 'deprecated'] + return st.fixed_dictionaries({field: self.generate_field(schema.fields[field]) for field in fields_to_generate}) @staticmethod @cache diff --git a/selfdrive/test/helpers.py b/selfdrive/test/helpers.py index b7f5bb183b7ce8..49a8ec60a3408d 100644 --- a/selfdrive/test/helpers.py +++ b/selfdrive/test/helpers.py @@ -10,7 +10,6 @@ import cereal.messaging as messaging from openpilot.common.params import Params from openpilot.system.manager.process_config import managed_processes -from openpilot.system.hardware import PC from openpilot.system.version import training_version, terms_version @@ -19,23 +18,15 @@ def set_params_enabled(): os.environ['LOGPRINT'] = "debug" params = Params() - params.put("HasAcceptedTerms", terms_version) - params.put("CompletedTrainingVersion", training_version) - params.put_bool("OpenpilotEnabledToggle", True) + params.put("HasAcceptedTerms", terms_version, block=True) + params.put("CompletedTrainingVersion", training_version, block=True) + params.put_bool("OpenpilotEnabledToggle", True, block=True) # valid calib msg = messaging.new_message('liveCalibration') msg.liveCalibration.validBlocks = 20 msg.liveCalibration.rpyCalib = [0.0, 0.0, 0.0] - params.put("CalibrationParams", msg.to_bytes()) - -def phone_only(f): - @wraps(f) - def wrap(self, *args, **kwargs): - if PC: - pytest.skip("This test is not meant to run on PC") - return f(self, *args, **kwargs) - return wrap + params.put("CalibrationParams", msg.to_bytes(), block=True) def release_only(f): @wraps(f) @@ -46,6 +37,43 @@ def wrap(self, *args, **kwargs): return wrap +def collect_logs(services, duration): + socks = [messaging.sub_sock(s, conflate=False, timeout=100) for s in services] + logs = [] + start = time.monotonic() + while time.monotonic() - start < duration: + for s in socks: + logs.extend(messaging.drain_sock(s)) + return logs + + +@contextlib.contextmanager +def log_collector(services): + """Background thread that continuously drains messages from services. + Use when the main thread needs to do blocking work (e.g. capturing images).""" + socks = [messaging.sub_sock(s, conflate=False, timeout=100) for s in services] + raw_logs = [] + lock = threading.Lock() + stop_event = threading.Event() + + def _drain(): + while not stop_event.is_set(): + for s in socks: + msgs = messaging.drain_sock(s) + if msgs: + with lock: + raw_logs.extend(msgs) + time.sleep(0.01) + + thread = threading.Thread(target=_drain, daemon=True) + thread.start() + try: + yield raw_logs, lock + finally: + stop_event.set() + thread.join(timeout=2) + + @contextlib.contextmanager def processes_context(processes, init_time=0, ignore_stopped=None): ignore_stopped = [] if ignore_stopped is None else ignore_stopped diff --git a/selfdrive/test/longitudinal_maneuvers/maneuver.py b/selfdrive/test/longitudinal_maneuvers/maneuver.py index 6c8495cc3b5567..905065bc7a40fd 100644 --- a/selfdrive/test/longitudinal_maneuvers/maneuver.py +++ b/selfdrive/test/longitudinal_maneuvers/maneuver.py @@ -12,14 +12,18 @@ def __init__(self, title, duration, **kwargs): self.breakpoints = kwargs.get("breakpoints", [0.0, duration]) self.speed_lead_values = kwargs.get("speed_lead_values", [0.0 for i in range(len(self.breakpoints))]) self.prob_lead_values = kwargs.get("prob_lead_values", [1.0 for i in range(len(self.breakpoints))]) + self.prob_throttle_values = kwargs.get("prob_throttle_values", [1.0 for i in range(len(self.breakpoints))]) self.cruise_values = kwargs.get("cruise_values", [50.0 for i in range(len(self.breakpoints))]) + self.pitch_values = kwargs.get("pitch_values", [0.0 for i in range(len(self.breakpoints))]) self.only_lead2 = kwargs.get("only_lead2", False) self.only_radar = kwargs.get("only_radar", False) self.ensure_start = kwargs.get("ensure_start", False) + self.ensure_slowdown = kwargs.get("ensure_slowdown", False) self.enabled = kwargs.get("enabled", True) self.e2e = kwargs.get("e2e", False) self.personality = kwargs.get("personality", 0) + self.nap_follow_dist = kwargs.get("nap_follow_dist") self.force_decel = kwargs.get("force_decel", False) self.duration = duration @@ -35,6 +39,7 @@ def evaluate(self): only_radar=self.only_radar, e2e=self.e2e, personality=self.personality, + nap_follow_dist=self.nap_follow_dist, force_decel=self.force_decel, ) @@ -42,9 +47,11 @@ def evaluate(self): logs = [] while plant.current_time < self.duration: speed_lead = np.interp(plant.current_time, self.breakpoints, self.speed_lead_values) - prob = np.interp(plant.current_time, self.breakpoints, self.prob_lead_values) + prob_lead = np.interp(plant.current_time, self.breakpoints, self.prob_lead_values) cruise = np.interp(plant.current_time, self.breakpoints, self.cruise_values) - log = plant.step(speed_lead, prob, cruise) + pitch = np.interp(plant.current_time, self.breakpoints, self.pitch_values) + prob_throttle = np.interp(plant.current_time, self.breakpoints, self.prob_throttle_values) + log = plant.step(speed_lead, prob_lead, cruise, pitch, prob_throttle) d_rel = log['distance_lead'] - log['distance'] if self.lead_relevancy else 200. v_rel = speed_lead - log['speed'] if self.lead_relevancy else 0. @@ -55,15 +62,21 @@ def evaluate(self): log['distance_lead'], log['speed'], speed_lead, - log['acceleration']])) + log['acceleration'], + log['d_rel']])) - if d_rel < .4 and (self.only_radar or prob > 0.5): + if d_rel < .4 and (self.only_radar or prob_lead > 0.5): print("Crashed!!!!") valid = False - if self.ensure_start and log['v_rel'] > 0 and log['speeds'][-1] <= 0.1: + if self.ensure_start and log['v_rel'] > 0 and log['acceleration'] < 1e-3: print('LongitudinalPlanner not starting!') valid = False + + if self.ensure_slowdown and log['speed'] > 5.5: + print('LongitudinalPlanner not slowing down!') + valid = False + if self.force_decel and log['speed'] > 1e-1 and log['acceleration'] > -0.04: print('Not stopping with force decel') valid = False diff --git a/selfdrive/test/longitudinal_maneuvers/plant.py b/selfdrive/test/longitudinal_maneuvers/plant.py index 85e2ddf8df39a8..c6f827a5e8bb41 100755 --- a/selfdrive/test/longitudinal_maneuvers/plant.py +++ b/selfdrive/test/longitudinal_maneuvers/plant.py @@ -2,7 +2,7 @@ import time import numpy as np -from cereal import log +from cereal import car, log import cereal.messaging as messaging from openpilot.common.realtime import Ratekeeper, DT_MDL from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState @@ -11,11 +11,40 @@ from openpilot.selfdrive.controls.radard import _LEAD_ACCEL_TAU +class _ManeuverParams: + def __init__(self, nap_follow_dist): + self.nap_follow_dist = nap_follow_dist + self.migrated = True + + def get(self, key, return_default=False): + assert return_default + if key in ("NAPFollowDistance", "NAPFollowDistanceCity", "NAPFollowDistanceHwy"): + return self.nap_follow_dist + if key in ("NAPMapSpeedMode", "NAPMapSpeedOffsetMph", "NAPMapSpeedLookahead", "NAPMapSpeedAccel"): + return {"NAPMapSpeedMode": 0, "NAPMapSpeedOffsetMph": 0, "NAPMapSpeedLookahead": 2, "NAPMapSpeedAccel": 5}[key] + raise AssertionError(key) + + def get_bool(self, key): + if key == "NAPAdaptiveAccel": + return False + if key == "NAPFollowDistanceSplitMigrated": + return self.migrated + raise AssertionError(key) + + def put(self, key, value): + pass + + def put_bool(self, key, value): + if key == "NAPFollowDistanceSplitMigrated": + self.migrated = bool(value) + + class Plant: messaging_initialized = False def __init__(self, lead_relevancy=False, speed=0.0, distance_lead=2.0, - enabled=True, only_lead2=False, only_radar=False, e2e=False, personality=0, force_decel=False): + enabled=True, only_lead2=False, only_radar=False, e2e=False, personality=0, + nap_follow_dist=None, force_decel=False): self.rate = 1. / DT_MDL if not Plant.messaging_initialized: @@ -30,8 +59,8 @@ def __init__(self, lead_relevancy=False, speed=0.0, distance_lead=2.0, self.distance = 0. self.speed = speed + self.should_stop = False self.acceleration = 0.0 - self.speeds = [] # lead car self.lead_relevancy = lead_relevancy @@ -48,22 +77,36 @@ def __init__(self, lead_relevancy=False, speed=0.0, distance_lead=2.0, time.sleep(0.1) self.sm = messaging.SubMaster(['longitudinalPlan']) - from opendbc.car.honda.values import CAR - from opendbc.car.honda.interface import CarInterface + if nap_follow_dist is None: + from opendbc.car.honda.values import CAR + from opendbc.car.honda.interface import CarInterface + planner_params = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC) + params = None + else: + planner_params = car.CarParams.new_message() + planner_params.brand = "tesla" + planner_params.carFingerprint = "TESLA_MODEL_S_PREAP" + planner_params.openpilotLongitudinalControl = True + planner_params.pcmCruise = False + planner_params.steerRatio = 15.75 + planner_params.wheelbase = 2.959 + params = _ManeuverParams(nap_follow_dist) - self.planner = LongitudinalPlanner(CarInterface.get_non_essential_params(CAR.HONDA_CIVIC), init_v=self.speed) + self.planner = LongitudinalPlanner(planner_params, init_v=self.speed, params=params) @property def current_time(self): return float(self.rk.frame) / self.rate - def step(self, v_lead=0.0, prob=1.0, v_cruise=50.): + def step(self, v_lead=0.0, prob_lead=1.0, v_cruise=50., pitch=0.0, prob_throttle=1.0): # ******** publish a fake model going straight and fake calibration ******** # note that this is worst case for MPC, since model will delay long mpc by one time step radar = messaging.new_message('radarState') control = messaging.new_message('controlsState') ss = messaging.new_message('selfdriveState') car_state = messaging.new_message('carState') + lp = messaging.new_message('liveParameters') + car_control = messaging.new_message('carControl') model = messaging.new_message('modelV2') a_lead = (v_lead - self.v_lead_prev)/self.ts self.v_lead_prev = v_lead @@ -73,14 +116,14 @@ def step(self, v_lead=0.0, prob=1.0, v_cruise=50.): v_rel = v_lead - self.speed if self.only_radar: status = True - elif prob > .5: + elif prob_lead > .5: status = True else: status = False else: d_rel = 200. v_rel = 0. - prob = 0.0 + prob_lead = 0.0 status = False lead = log.RadarState.LeadData.new_message() @@ -94,7 +137,7 @@ def step(self, v_lead=0.0, prob=1.0, v_cruise=50.): # TODO use real radard logic for this lead.aLeadTau = float(_LEAD_ACCEL_TAU) lead.status = status - lead.modelProb = float(prob) + lead.modelProb = float(prob_lead) if not self.only_lead2: radar.radarState.leadOne = lead radar.radarState.leadTwo = lead @@ -105,31 +148,39 @@ def step(self, v_lead=0.0, prob=1.0, v_cruise=50.): position = log.XYZTData.new_message() position.x = [float(x) for x in (self.speed + 0.5) * np.array(ModelConstants.T_IDXS)] model.modelV2.position = position + model.modelV2.action.desiredAcceleration = float(self.acceleration + 0.1) velocity = log.XYZTData.new_message() velocity.x = [float(x) for x in (self.speed + 0.5) * np.ones_like(ModelConstants.T_IDXS)] + velocity.x[0] = float(self.speed) # always start at current speed model.modelV2.velocity = velocity acceleration = log.XYZTData.new_message() acceleration.x = [float(x) for x in np.zeros_like(ModelConstants.T_IDXS)] model.modelV2.acceleration = acceleration + model.modelV2.meta.disengagePredictions.gasPressProbs = [float(prob_throttle) for _ in range(6)] control.controlsState.longControlState = LongCtrlState.pid if self.enabled else LongCtrlState.off ss.selfdriveState.experimentalMode = self.e2e ss.selfdriveState.personality = self.personality control.controlsState.forceDecel = self.force_decel car_state.carState.vEgo = float(self.speed) - car_state.carState.standstill = self.speed < 0.01 + car_state.carState.standstill = bool(self.speed < 0.01) car_state.carState.vCruise = float(v_cruise * 3.6) + car_control.carControl.orientationNED = [0., float(pitch), 0.] # ******** get controlsState messages for plotting *** sm = {'radarState': radar.radarState, 'carState': car_state.carState, + 'carControl': car_control.carControl, 'controlsState': control.controlsState, 'selfdriveState': ss.selfdriveState, + 'liveParameters': lp.liveParameters, 'modelV2': model.modelV2} self.planner.update(sm) - self.speed = self.planner.v_desired_filter.x - self.acceleration = self.planner.a_desired - self.speeds = self.planner.v_desired_trajectory.tolist() + self.acceleration = self.planner.output_a_target + if self.planner.output_should_stop: + self.acceleration = min(-0.5, self.acceleration) + self.speed = self.speed + self.acceleration * self.ts + self.should_stop = self.planner.output_should_stop fcw = self.planner.fcw self.distance_lead = self.distance_lead + v_lead * self.ts @@ -161,7 +212,7 @@ def step(self, v_lead=0.0, prob=1.0, v_cruise=50.): "distance": self.distance, "speed": self.speed, "acceleration": self.acceleration, - "speeds": self.speeds, + "should_stop": self.should_stop, "distance_lead": self.distance_lead, "fcw": fcw, } diff --git a/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py b/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py index 62a95babeb3c05..b8f97c5041f35b 100644 --- a/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py +++ b/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py @@ -1,5 +1,5 @@ import itertools -from parameterized import parameterized_class +from openpilot.common.parameterized import parameterized_class from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import STOP_DISTANCE from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver @@ -82,6 +82,32 @@ def create_maneuvers(kwargs): breakpoints=[0.0, 2., 2.01], **kwargs, ), + Maneuver( + "approach stopped car at 20m/s, with prob_throttle_values and pitch = -0.1", + duration=30., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=120., + speed_lead_values=[0.0, 0., 0.], + prob_throttle_values=[1., 0., 0.], + cruise_values=[20., 20., 20.], + pitch_values=[0., -0.1, -0.1], + breakpoints=[0.0, 2., 2.01], + **kwargs, + ), + Maneuver( + "approach stopped car at 20m/s, with prob_throttle_values and pitch = +0.1", + duration=30., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=120., + speed_lead_values=[0.0, 0., 0.], + prob_throttle_values=[1., 0., 0.], + cruise_values=[20., 20., 20.], + pitch_values=[0., 0.1, 0.1], + breakpoints=[0.0, 2., 2.01], + **kwargs, + ), Maneuver( "approach slower cut-in car at 20m/s", duration=20., @@ -124,7 +150,18 @@ def create_maneuvers(kwargs): enabled=False, **kwargs, ), - ] + Maneuver( + "slow to 5m/s with allow_throttle = False and pitch = +0.1", + duration=30., + initial_speed=20., + lead_relevancy=False, + prob_throttle_values=[1., 0., 0.], + cruise_values=[20., 20., 20.], + pitch_values=[0., 0.1, 0.1], + breakpoints=[0.0, 2., 2.01], + ensure_slowdown=True, + **kwargs, + )] if not kwargs['force_decel']: # controls relies on planner commanding to move for stock-ACC resume spamming maneuvers.append(Maneuver( @@ -133,7 +170,7 @@ def create_maneuvers(kwargs): initial_speed=0., lead_relevancy=True, initial_distance_lead=STOP_DISTANCE, - speed_lead_values=[0., 0., 2.], + speed_lead_values=[0., 0., 7.], breakpoints=[1., 10., 15.], ensure_start=True, **kwargs, diff --git a/selfdrive/test/loop_until_fail.sh b/selfdrive/test/loop_until_fail.sh deleted file mode 100755 index b73009dba67cfc..00000000000000 --- a/selfdrive/test/loop_until_fail.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash -set -e - -# Loop something forever until it fails, for verifying new tests - -while true; do - $@ -done diff --git a/selfdrive/test/process_replay/.gitignore b/selfdrive/test/process_replay/.gitignore deleted file mode 100644 index a35cd58d415c63..00000000000000 --- a/selfdrive/test/process_replay/.gitignore +++ /dev/null @@ -1 +0,0 @@ -fakedata/ diff --git a/selfdrive/test/process_replay/README.md b/selfdrive/test/process_replay/README.md index 008a9010100756..d4d47465ea56a1 100644 --- a/selfdrive/test/process_replay/README.md +++ b/selfdrive/test/process_replay/README.md @@ -1,126 +1,92 @@ # Process replay -Process replay is a regression test designed to identify any changes in the output of a process. This test replays a segment through individual processes and compares the output to a known good replay. Each make is represented in the test with a segment. +Process replay is a regression test that replays recorded source logs through individual openpilot processes and compares each process output against a known reference. -If the test fails, make sure that you didn't unintentionally change anything. If there are intentional changes, the reference logs will be updated. +## Cases and tasks -Use `test_processes.py` to run the test locally. -Use `FILEREADER_CACHE='1' test_processes.py` to cache log files. +A **case** is one source input: car brand, source locator, selected processes, and optional typed custom params. +A **task** is one process on one case. Task IDs are canonical: `{case_id}:{process}`. -Currently the following processes are tested: +The active inventory is the legacy 16 sources / 66 tasks: +- `card`, `controlsd`, and `lagd` on every case +- the other nine non-model processes only on `HYUNDAI` and `TOYOTA` -* controlsd -* radard -* plannerd -* calibrationd -* dmonitoringd -* locationd -* paramsd -* ubloxd -* torqued +`--inventory staged` also lists two temporary Pre-AP descriptors (`PENDING_CASES`) for a total of 18 cases / 78 tasks. Those pending cases are listing/generation descriptors only until sanitized fixture URLs and digests are filled in; they are not executable in normal active runs. + +`source_segments` remains the regen compatibility list used by `regen_all.py`. + +## Running locally + +```bash +# full active suite +./test_processes.py -j$(nproc) + +# shard-style filters (diagnostics go to --output-dir) +./test_processes.py -j$(nproc) --whitelist-procs card --output-dir /tmp/replay/card +./test_processes.py -j$(nproc) --whitelist-procs controlsd --output-dir /tmp/replay/controlsd +./test_processes.py -j$(nproc) --whitelist-procs lagd --output-dir /tmp/replay/lagd +./test_processes.py -j$(nproc) --blacklist-procs card controlsd lagd --output-dir /tmp/replay/other + +# inventories +./test_processes.py --list-cases +./test_processes.py --list-tasks +./test_processes.py --inventory staged --list-tasks +``` + +Log downloads are cached by default. Disable with `DISABLE_FILEREADER_CACHE=1`. + +### CLI -### Usage ``` -Usage: test_processes.py [-h] [--whitelist-procs PROCS] [--whitelist-cars CARS] [--blacklist-procs PROCS] - [--blacklist-cars CARS] [--ignore-fields FIELDS] [--ignore-msgs MSGS] [--update-refs] [--upload-only] -Regression test to identify changes in a process's output -optional arguments: - -h, --help show this help message and exit - --whitelist-procs PROCS Whitelist given processes from the test (e.g. controlsd) - --whitelist-cars WHITELIST_CARS Whitelist given cars from the test (e.g. HONDA) - --blacklist-procs BLACKLIST_PROCS Blacklist given processes from the test (e.g. controlsd) - --blacklist-cars BLACKLIST_CARS Blacklist given cars from the test (e.g. HONDA) - --ignore-fields IGNORE_FIELDS Extra fields or msgs to ignore (e.g. carState.events) - --ignore-msgs IGNORE_MSGS Msgs to ignore (e.g. onroadEvents) - --update-refs Updates reference logs using current commit - --upload-only Skips testing processes and uploads logs from previous test run +Usage: test_processes.py [-h] + [--whitelist-procs PROCS] [--whitelist-cars CARS] + [--blacklist-procs PROCS] [--blacklist-cars CARS] + [--ignore-fields FIELDS] [--ignore-msgs MSGS] + [--update-refs] [--inventory {active,staged}] + [--list-cases] [--list-tasks] + [--output-dir DIR] [--reference-dir DIR] [-j JOBS] ``` -## Forks +- `--output-dir` only changes where `diff.txt` and `results.json` are written. +- `--reference-dir` selects an already-generated local candidate tree for comparison. +- `--update-refs` writes candidate refs for the selected tasks. It does not mark those candidates as accepted; acceptance is a second normal run against `--reference-dir`. -openpilot forks can use this test with their own reference logs, by default `test_proccess.py` saves logs locally. +## References and diagnostics -To generate new logs: +Remote references are resolved from one pinned `NotAutopilot/ci-artifacts` commit on `process-replay`, not from a moving branch URL. Filenames use `{case_id}__{process}__{ref_commit}.zst`. Manifest-era trees require `manifest.json` and canonical filenames. Pre-bootstrap segment filenames are allowed only when the pinned artifacts commit is listed in `LEGACY_ARTIFACTS_COMMITS`. -`./test_processes.py` +Each selected case is downloaded once. When a case declares size/SHA-256, both are checked before replay. A digest failure becomes a task error for every task on that case; other cases continue. -Then, check in the new logs using git-lfs. Make sure to also update the `ref_commit` file to the current commit. +Workers return serializable `TaskResult` values. One task failure does not abort the pool. `diff.txt` and schema-versioned `results.json` are created before downloads start and rewritten after every settled task. The process exits nonzero on any diff, error, or incomplete inventory. After a normal compare run, only failed/different generated logs are kept; stale `fakedata` is cleared at start. + +## Params + +Runtime custom params stay native Python types (`bool`, `int`, `float`) and are validated against `common/params_keys.h` before scheduling. Manifest digests hash a separate canonical JSON array sorted by key with explicit `type` tags. ## API -Process replay test suite exposes programmatic APIs for simultaneously running processes or groups of processes on provided logs. +Process replay also exposes programmatic helpers for replaying processes on provided logs: ```py def replay_process_with_name(name: Union[str, Iterable[str]], lr: LogIterable, *args, **kwargs) -> List[capnp._DynamicStructReader]: def replay_process( - cfg: Union[ProcessConfig, Iterable[ProcessConfig]], lr: LogIterable, frs: Optional[Dict[str, Any]] = None, + cfg: Union[ProcessConfig, Iterable[ProcessConfig]], lr: LogIterable, frs: Optional[Dict[str, Any]] = None, fingerprint: Optional[str] = None, return_all_logs: bool = False, custom_params: Optional[Dict[str, Any]] = None, disable_progress: bool = False ) -> List[capnp._DynamicStructReader]: ``` -Example usage: +Example: + ```py from openpilot.selfdrive.test.process_replay import replay_process_with_name from openpilot.tools.lib.logreader import LogReader lr = LogReader(...) - -# provide a name of the process to replay output_logs = replay_process_with_name('locationd', lr) - -# or list of names output_logs = replay_process_with_name(['ubloxd', 'locationd'], lr) ``` -Supported processes: -* controlsd -* radard -* plannerd -* calibrationd -* dmonitoringd -* locationd -* paramsd -* ubloxd -* torqued -* modeld -* dmonitoringmodeld - -Certain processes may require an initial state, which is usually supplied within `Params` and persisting from segment to segment (e.g CalibrationParams, LiveParameters). The `custom_params` is dictionary used to prepopulate `Params` with arbitrary values. The `get_custom_params_from_lr` helper is provided to fetch meaningful values from log files. - -```py -from openpilot.selfdrive.test.process_replay import get_custom_params_from_lr +Supported processes include `controlsd`, `radard`, `plannerd`, `calibrationd`, `dmonitoringd`, `locationd`, `paramsd`, `ubloxd`, `torqued`, `card`, `lagd`, `selfdrived`, `modeld`, and `dmonitoringmodeld`. -previous_segment_lr = LogReader(...) -current_segment_lr = LogReader(...) - -custom_params = get_custom_params_from_lr(previous_segment_lr, 'last') - -output_logs = replay_process_with_name('calibrationd', lr, custom_params=custom_params) -``` - -Replaying processes that use VisionIPC (e.g. modeld, dmonitoringmodeld) require additional `frs` dictionary with camera states as keys and `FrameReader` objects as values. - -```py -from openpilot.tools.lib.framereader import FrameReader - -frs = { - 'roadCameraState': FrameReader(...), - 'wideRoadCameraState': FrameReader(...), - 'driverCameraState': FrameReader(...), -} - -output_logs = replay_process_with_name(['modeld', 'dmonitoringmodeld'], lr, frs=frs) -``` - -To capture stdout/stderr of the replayed process, `captured_output_store` can be provided. - -```py -output_store = dict() -# pass dictionary by reference, it will be filled with standard outputs - even if process replay fails -output_logs = replay_process_with_name(['radard', 'plannerd'], lr, captured_output_store=output_store) - -# entries with captured output in format { 'out': '...', 'err': '...' } will be added to provided dictionary for each replayed process -print(output_store['radard']['out']) # radard stdout -print(output_store['radard']['err']) # radard stderr -``` +Use `custom_params` to seed `Params` with typed values. `get_custom_params_from_lr` can recover meaningful values from a previous segment. VisionIPC processes need an `frs` map of camera state names to `FrameReader` objects. Pass `captured_output_store` to collect stdout/stderr per process. diff --git a/selfdrive/test/process_replay/compare_logs.py b/selfdrive/test/process_replay/compare_logs.py index 14af9672d0e468..48caec2ab9889c 100755 --- a/selfdrive/test/process_replay/compare_logs.py +++ b/selfdrive/test/process_replay/compare_logs.py @@ -3,13 +3,16 @@ import math import capnp import numbers -import dictdiffer from collections import Counter from openpilot.tools.lib.logreader import LogReader EPSILON = sys.float_info.epsilon +_DynamicStructReader = capnp.lib.capnp._DynamicStructReader +_DynamicListReader = capnp.lib.capnp._DynamicListReader +_DynamicEnum = capnp.lib.capnp._DynamicEnum + def remove_ignored_fields(msg, ignore): msg = msg.as_builder() @@ -33,12 +36,69 @@ def remove_ignored_fields(msg, ignore): val = 0 elif isinstance(v, (list, capnp.lib.capnp._DynamicListBuilder)): val = [] + elif isinstance(v, (str, bytes)): + val = "" else: raise NotImplementedError(f"Unknown type: {type(v)}") setattr(attr, keys[-1], val) return msg +def _diff_capnp(r1, r2, path, tolerance): + """Walk two capnp struct readers and yield (action, dotted_path, value) diffs. + + Floats are compared with the given tolerance (combined absolute+relative). + """ + schema = r1.schema + + for fname in schema.non_union_fields: + child_path = path + (fname,) + v1 = getattr(r1, fname) + v2 = getattr(r2, fname) + yield from _diff_capnp_values(v1, v2, child_path, tolerance) + + if schema.union_fields: + w1, w2 = r1.which(), r2.which() + if w1 != w2: + yield 'change', '.'.join(path), (w1, w2) + else: + child_path = path + (w1,) + v1, v2 = getattr(r1, w1), getattr(r2, w2) + yield from _diff_capnp_values(v1, v2, child_path, tolerance) + + +def _diff_capnp_values(v1, v2, path, tolerance): + if isinstance(v1, _DynamicStructReader): + yield from _diff_capnp(v1, v2, path, tolerance) + + elif isinstance(v1, _DynamicListReader): + dot = '.'.join(path) + n1, n2 = len(v1), len(v2) + n = min(n1, n2) + for i in range(n): + yield from _diff_capnp_values(v1[i], v2[i], path + (str(i),), tolerance) + if n2 > n: + yield 'add', dot, [(i, v2[i]) for i in range(n, n2)] + if n1 > n: + yield 'remove', dot, list(reversed([(i, v1[i]) for i in range(n, n1)])) + + elif isinstance(v1, _DynamicEnum): + s1, s2 = str(v1), str(v2) + if s1 != s2: + yield 'change', '.'.join(path), (s1, s2) + + elif isinstance(v1, float): + if not (v1 == v2 or ( + math.isfinite(v1) and math.isfinite(v2) and + abs(v1 - v2) <= max(tolerance, tolerance * max(abs(v1), abs(v2))) + )): + yield 'change', '.'.join(path), (v1, v2) + + else: + if v1 != v2: + yield 'change', '.'.join(path), (v1, v2) + + def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=None,): if ignore_fields is None: ignore_fields = [] @@ -65,26 +125,7 @@ def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=Non msg2 = remove_ignored_fields(msg2, ignore_fields) if msg1.to_bytes() != msg2.to_bytes(): - msg1_dict = msg1.as_reader().to_dict(verbose=True) - msg2_dict = msg2.as_reader().to_dict(verbose=True) - - dd = dictdiffer.diff(msg1_dict, msg2_dict, ignore=ignore_fields) - - # Dictdiffer only supports relative tolerance, we also want to check for absolute - # TODO: add this to dictdiffer - def outside_tolerance(diff): - try: - if diff[0] == "change": - a, b = diff[2] - finite = math.isfinite(a) and math.isfinite(b) - if finite and isinstance(a, numbers.Number) and isinstance(b, numbers.Number): - return abs(a - b) > max(tolerance, tolerance * max(abs(a), abs(b))) - except TypeError: - pass - return True - - dd = list(filter(outside_tolerance, dd)) - + dd = list(_diff_capnp(msg1.as_reader(), msg2.as_reader(), (), tolerance)) diff.extend(dd) return diff @@ -141,7 +182,7 @@ def format_diff(results, log_paths, ref_commit): if __name__ == "__main__": log1 = list(LogReader(sys.argv[1])) log2 = list(LogReader(sys.argv[2])) - ignore_fields = sys.argv[3:] or ["logMonoTime", "controlsState.cumLagMs"] + ignore_fields = sys.argv[3:] or ["logMonoTime"] results = {"segment": {"proc": compare_logs(log1, log2, ignore_fields)}} log_paths = {"segment": {"proc": {"ref": sys.argv[1], "new": sys.argv[2]}}} diff_short, diff_long, failed = format_diff(results, log_paths, None) diff --git a/selfdrive/test/process_replay/diff_report.py b/selfdrive/test/process_replay/diff_report.py new file mode 100644 index 00000000000000..5da78657f48876 --- /dev/null +++ b/selfdrive/test/process_replay/diff_report.py @@ -0,0 +1,94 @@ +import os +from collections import defaultdict + +from opendbc.car.tests.car_diff import format_diff, format_numeric_diffs +from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs +from openpilot.selfdrive.test.process_replay.process_replay import PROC_REPLAY_DIR + + +class MsgWrap: + """Adapter so to_dict() includes defaults""" + def __init__(self, msg): + self._msg = msg + def to_dict(self) -> dict: + return self._msg.to_dict(verbose=True) + + +def diff_process(cfg, ref_msgs, new_msgs) -> tuple | None: + ref = defaultdict(list) + new = defaultdict(list) + for m in ref_msgs: + if m.which() in cfg.subs: + ref[m.which()].append(m) + for m in new_msgs: + if m.which() in cfg.subs: + new[m.which()].append(m) + + diffs = [] + for sub in cfg.subs: + if len(ref[sub]) != len(new[sub]): + diffs.append((f"{sub} (message count)", 0, (len(ref[sub]), len(new[sub])), 0)) + for i, (r, n) in enumerate(zip(ref[sub], new[sub], strict=False)): + for d in compare_logs([r], [n], cfg.ignore, tolerance=cfg.tolerance): + if d[0] == "change": + a, b = d[2] + if a != a and b != b: + continue + diffs.append((d[1], i, d[2], r.logMonoTime)) + elif d[0] in ("add", "remove"): + for item in d[2]: + if item[1] != item[1]: + continue + diffs.append((f"{d[1]}.{item[0]}", i, (d[0], item[1]), r.logMonoTime)) + return (diffs, ref, new) if diffs else None + + +def diff_format(diffs, ref, new, field) -> list[str]: + if any(part.isdigit() for part in field.split(".")): + return format_numeric_diffs(diffs) + msg_type = field.split(".")[0] + ref_ts = [(m.logMonoTime, MsgWrap(m)) for m in ref.get(msg_type, [])] + new_wrapped = [MsgWrap(m) for m in new.get(msg_type, [])] + if not ref_ts or not new_wrapped: + return format_numeric_diffs(diffs) + return format_diff(diffs, ref_ts, new_wrapped, field) + + +def diff_report(replay_diffs, segments) -> None: + seg_to_plat = {seg: plat for plat, seg in segments} + + with_diffs, errors, n_passed = [], [], 0 + for seg, proc, data in replay_diffs: + plat = seg_to_plat.get(seg, "UNKNOWN") + if data is None: + n_passed += 1 + elif isinstance(data, str): + errors.append((plat, seg, proc, data)) + else: + with_diffs.append((plat, seg, proc, data)) + + icon = "⚠️" if with_diffs else "✅" + lines = [ + "## Process replay diff report", + "Replays driving segments through this PR and compares the behavior to master.", + "Please review any changes carefully to ensure they are expected.\n", + f"{icon} {len(with_diffs)} changed, {n_passed} passed, {len(errors)} errors", + ] + + for plat, seg, proc, err in errors: + lines.append(f"\nERROR {plat} - {seg} [{proc}]: {err}") + + if with_diffs: + lines.append("
Show changes\n\n```") + for plat, seg, proc, (diffs, ref, new) in with_diffs: + lines.append(f"\n{plat} - {seg} [{proc}]") + by_field = defaultdict(list) + for d in diffs: + by_field[d[0]].append(d) + for field, fd in sorted(by_field.items()): + lines.append(f"\n {field} ({len(fd)} diffs)") + lines.extend(diff_format(fd, ref, new, field)) + lines.append("```\n
") + + with open(os.path.join(PROC_REPLAY_DIR, "diff_report.txt"), "w") as f: + f.write("\n".join(lines)) diff --git a/selfdrive/test/process_replay/fixture_tool.py b/selfdrive/test/process_replay/fixture_tool.py new file mode 100755 index 00000000000000..2ad3d1fdeac4a8 --- /dev/null +++ b/selfdrive/test/process_replay/fixture_tool.py @@ -0,0 +1,1576 @@ +#!/usr/bin/env python3 +"""Build and audit small, deterministic public Pre-AP replay fixtures.""" +from __future__ import annotations + +import argparse +import base64 +import binascii +import json +import os +import re +import sys +import tempfile +from collections import Counter +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import capnp +import zstandard +from cereal import car, log as capnp_log +from openpilot.tools.lib.logreader import LogReader + +SCHEMA_VERSION = 1 +PLACEHOLDER_VIN = "00000000000000000" +VIN_LENGTH = 17 + +EXPECTED_SAFETY_MODEL = car.CarParams.SafetyModel.teslaPreap +# Fixed Pre-AP replay params enable pedal + radar emulation + nosecone => 7 / 6. +PREAP_FLAG_ENABLE_PEDAL = 1 +PREAP_FLAG_RADAR_EMULATION = 2 +PREAP_FLAG_RADAR_BEHIND_NOSECONE = 4 + +CASE_MODES = frozenset({"pedal", "no-pedal"}) +SAFE_LABEL_RE = re.compile(r"^[a-z][a-z0-9_]{0,31}$") +SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +HEX_VALUE_RE = re.compile(r"^[0-9a-f]*$") +DENY_ENCODINGS = frozenset({"utf8", "hex", "base64"}) +VIN_FRAGMENT_MIN = 6 +VIN_FRAGMENT_MAX = 17 +CAN_OVERLAP = 16 +MAX_COMPRESSED_INPUT_BYTES = 64 * 1024 * 1024 +MAX_DECOMPRESSED_INPUT_BYTES = 512 * 1024 * 1024 +MAX_LOG_MESSAGES = 2_000_000 +MAX_CAN_CONCAT_BYTES = 4 * 1024 * 1024 +VALID_SHARE_THRESHOLD = 0.9 +ZSTD_CONTENTSIZE_UNKNOWN = (1 << 64) - 1 +ZSTD_DECOMPRESS_CHUNK = 1024 * 1024 +# Retained-as-is public Text constants. can[].dat is a scan sink only — never an +# inventory exemption for values that also originate from private/scrubbed leaves. +ATTESTED_PUBLIC_TEXT_DATA_LEAVES = frozenset({ + "carParams.brand", + "carParams.carFingerprint", +}) + +SIX_PROCESS_OUTPUTS: dict[str, frozenset[str]] = { + "card": frozenset({"sendcan", "carState", "carParams", "carOutput", "liveTracks"}), + "controlsd": frozenset({"carControl", "controlsState"}), + "selfdrived": frozenset({"selfdriveState", "onroadEvents"}), + "radard": frozenset({"radarState"}), + "plannerd": frozenset({"longitudinalPlan", "driverAssistance"}), + "lagd": frozenset({"liveDelay"}), +} + +POLICY_KEYS = frozenset({ + "schema_version", "allowed_services", "forbidden_services", "required_services", + "selected_gps_service", "freshness_services", "pedal", "sensitive_zero_fields", + "placeholder_vin", "cases", +}) +PEDAL_KEYS = frozenset({ + "address", "bus", "data_length", "counter_index", "counter_mask", + "checksum_index", "checksum", "minimum_frames", "minimum_counters", +}) +CASE_KEYS = frozenset({"mode", "fingerprint", "safety_param"}) +DENY_REQUIRED_KEYS = frozenset({"raw_input_sha256", "tokens"}) +DENY_OPTIONAL_KEYS = frozenset({"sanitized_output_sha256", "input_sha256"}) +# Attested release policy digest over POLICY_KEYS (canonical JSON). Weakened +# caller policies fail closed even when self-consistent. +RELEASE_POLICY_SHA256 = "8b37a7881af652246d5f7323dbd01f9e6c117440ee8d17fad77c88dfc3a1354f" +PEDAL_MIN_FRAMES = 10 +PEDAL_MIN_COUNTERS = 8 +ZSTD_MAGIC = b"\x28\xb5\x2f\xfd" + + +def safety_model_ordinal(value: Any) -> int: + """SafetyModel ordinal. Static enums int(); DynamicEnum needs .raw (str() is "37").""" + return int(getattr(value, "raw", value)) + + +def safety_model_is_tesla_preap(value: Any) -> bool: + return safety_model_ordinal(value) == int(EXPECTED_SAFETY_MODEL) + + +def expected_safety_param(mode: str) -> int: + flags = PREAP_FLAG_RADAR_EMULATION | PREAP_FLAG_RADAR_BEHIND_NOSECONE + if mode == "pedal": + flags |= PREAP_FLAG_ENABLE_PEDAL + return int(flags) + + +@dataclass(frozen=True) +class DenyManifest: + tokens: tuple[tuple[str, bytes], ...] + raw_input_sha256: str + sanitized_output_sha256: str | None + vin: bytes + +MANDATORY_FORBIDDEN = frozenset({ + "clocks", "initData", "boot", "sentinel", + "roadCameraState", "driverCameraState", "wideRoadCameraState", + "logMessage", "errorLogMessage", "androidLog", "procLog", + "roadEncodeIdx", "driverEncodeIdx", "wideRoadEncodeIdx", "qRoadEncodeIdx", + "livestreamRoadEncodeIdx", "livestreamWideRoadEncodeIdx", "livestreamDriverEncodeIdx", + "roadEncodeData", "driverEncodeData", "wideRoadEncodeData", "qRoadEncodeData", + "livestreamRoadEncodeData", "livestreamWideRoadEncodeData", "livestreamDriverEncodeData", + "touch", + "qcomGnss", "ubloxRaw", "ubloxGnss", "gnssMeasurements", "gpsNMEA", + "uiDebug", "navInstruction", "navRoute", "navThumbnail", "mapRenderState", "thumbnail", + "managerState", "uploaderState", + "rawAudioData", "soundPressure", "audioFeedback", + "sendcan", +}) + +SENSITIVE_ZERO_BASELINE = frozenset({ + "gpsLocation.latitude", "gpsLocation.longitude", "gpsLocation.altitude", + "gpsLocation.bearingDeg", "gpsLocation.unixTimestampMillis", "gpsLocation.vNED[]", + "gpsLocationExternal.latitude", "gpsLocationExternal.longitude", "gpsLocationExternal.altitude", + "gpsLocationExternal.bearingDeg", "gpsLocationExternal.unixTimestampMillis", "gpsLocationExternal.vNED[]", +}) + + +class FixtureError(ValueError): + pass + + +def digest(data: bytes) -> str: + import hashlib + return hashlib.sha256(data).hexdigest() + + +def field_parts(path: str) -> list[str]: + parts: list[str] = [] + for part in path.split("."): + if not part: + continue + if part == "[]": + parts.append(part) + elif part.endswith("[]"): + parts.extend((part[:-2], "[]")) + else: + parts.append(part) + return parts + + +def path_join(prefix: str, name: str) -> str: + return name if not prefix else f"{prefix}.{name}" + + +def is_list_service(service: str) -> bool: + field = capnp_log.Event.schema.fields[service] + return field.proto.slot.type.which() == "list" + + +def event_service_names() -> set[str]: + return set(capnp_log.Event.schema.union_fields) + + +def schema_for_service(service: str) -> Any: + field = capnp_log.Event.schema.fields[service] + t = field.proto.slot.type + if t.which() == "list": + return field.schema.elementType + if t.which() == "struct": + return field.schema + raise FixtureError(f"unsupported service schema: {service}") + + +def resolve_policy_path(service: str, path: str) -> None: + """Fail closed if a policy path cannot be resolved in the current Cap'n Proto schema.""" + parts = field_parts(path) + if not parts: + raise FixtureError(f"empty policy path for {service}") + schema = schema_for_service(service) + index = 0 + # Event-level list services use a leading [] marker before element fields. + if is_list_service(service): + if parts[0] != "[]": + raise FixtureError(f"list service paths require leading []: {service}.{path}") + index = 1 + if index == len(parts): + raise FixtureError(f"list service path requires a field: {service}.{path}") + while index < len(parts): + part = parts[index] + if part == "[]": + raise FixtureError(f"invalid list marker in {service}.{path}") + if part not in schema.fieldnames: + raise FixtureError(f"policy field does not exist: {service}.{path}") + field = schema.fields[part] + index += 1 + if field.proto.which() == "group": + if index == len(parts): + raise FixtureError(f"path ends at group: {service}.{path}") + schema = field.schema + continue + if field.proto.which() != "slot": + raise FixtureError(f"unsupported field kind in {service}.{path}") + twhich = field.proto.slot.type.which() + if twhich == "list": + if index >= len(parts) or parts[index] != "[]": + raise FixtureError(f"list field requires []: {service}.{path}") + index += 1 + elem = field.proto.slot.type.list.elementType + if index == len(parts): + if elem.which() == "struct": + raise FixtureError(f"struct list requires subfield: {service}.{path}") + return + if elem.which() != "struct": + raise FixtureError(f"cannot descend into scalar list: {service}.{path}") + schema = field.schema.elementType + elif twhich == "struct": + if index == len(parts): + raise FixtureError(f"path ends at struct: {service}.{path}") + schema = field.schema + else: + if index != len(parts): + raise FixtureError(f"extra path after leaf: {service}.{path}") + return + raise FixtureError(f"path ends at non-leaf: {service}.{path}") + + +def expand_allowed_paths(service: str, paths: list[str]) -> set[str]: + """Canonical leaf path set for membership checks (with [] markers preserved).""" + resolved: set[str] = set() + for path in paths: + resolve_policy_path(service, path) + resolved.add(".".join(field_parts(path))) + return resolved + + +def copy_path(source: Any, destination: Any, path: str) -> None: + parts = field_parts(path) + + def walk(src: Any, dst: Any, remaining: list[str]) -> None: + if not remaining: + raise FixtureError("empty policy field path") + part = remaining[0] + if part == "[]": + if len(remaining) == 1: + for index, src_item in enumerate(src): + dst[index] = src_item + return + for src_item, dst_item in zip(src, dst, strict=True): + walk(src_item, dst_item, remaining[1:]) + return + + if hasattr(src, "schema") and part in src.schema.union_fields: + try: + active = src.which() + except capnp.KjException: + return + if active != part: + return + try: + dst_branch = dst.init(part) + except (AttributeError, TypeError, capnp.KjException) as error: + raise FixtureError(f"cannot initialize union branch: {path}") from error + walk(getattr(src, part), dst_branch, remaining[1:]) + return + + try: + src_value = getattr(src, part) + except (AttributeError, TypeError, capnp.KjException) as error: + raise FixtureError(f"policy field does not exist: {path}") from error + + if len(remaining) == 1: + try: + setattr(dst, part, src_value) + except (AttributeError, TypeError, capnp.KjException) as error: + raise FixtureError(f"cannot copy policy field: {path}") from error + return + + try: + if remaining[1] == "[]": + src_list = src_value + existing = getattr(dst, part) + if len(existing) == len(src_list) and len(existing) > 0: + dst_value = existing + else: + dst_value = dst.init(part, len(src_list)) + elif part in getattr(dst, "schema", type("x", (), {"union_fields": ()})).union_fields: + # only init inactive/missing union branch + try: + if dst.which() == part: + dst_value = getattr(dst, part) + else: + dst_value = dst.init(part) + except capnp.KjException: + dst_value = dst.init(part) + else: + dst_value = getattr(dst, part) + except (AttributeError, TypeError, capnp.KjException) as error: + raise FixtureError(f"policy field does not exist: {path}") from error + walk(src_value, dst_value, remaining[1:]) + + walk(source, destination, parts) + + +def copy_service(source: Any, destination: Any, service: str, paths: list[str]) -> None: + try: + source_value = getattr(source, service) + except AttributeError as error: + raise FixtureError(f"source service is unavailable: {service}") from error + try: + if is_list_service(service): + destination_value = destination.init(service, len(source_value)) + else: + destination_value = destination.init(service) + except (AttributeError, TypeError, capnp.KjException) as error: + raise FixtureError(f"cannot initialize service: {service}") from error + for path in paths: + copy_path(source_value, destination_value, path) + + +def zero_sensitive_location(location: Any) -> None: + for field in ("latitude", "longitude", "altitude", "bearingDeg", "unixTimestampMillis"): + if field in location.schema.fieldnames: + setattr(location, field, 0) + if "vNED" in location.schema.fieldnames: + location.vNED = [0.0 for _ in range(len(location.vNED) or 3)] + + +def build_event(source: Any, policy: dict[str, Any]) -> Any | None: + service = source.which() + allowed = policy["allowed_services"] + if service not in allowed: + return None + event = capnp_log.Event.new_message() + event.logMonoTime = source.logMonoTime + event.valid = source.valid + paths = allowed[service] + copy_service(source, event, service, paths) + if service == "carParams": + event.carParams.carVin = policy["placeholder_vin"] + if len(event.carParams.carFw): + event.carParams.carFw = [] + if service == policy["selected_gps_service"] or service in ("gpsLocation", "gpsLocationExternal"): + zero_sensitive_location(getattr(event, service)) + return event.as_reader() + + +def default_equal(value: Any, default: Any) -> bool: + if isinstance(value, (bytes, bytearray)) or isinstance(default, (bytes, bytearray)): + return bytes(value or b"") == bytes(default or b"") + if isinstance(value, str) or isinstance(default, str): + return str(value or "") == str(default or "") + try: + if hasattr(value, "to_dict") and hasattr(default, "to_dict"): + return value.to_dict() == default.to_dict() + except Exception: + pass + try: + return list(value) == list(default) + except TypeError: + return value == default + + +def populated_leaf_paths(struct: Any, prefix: str = "") -> dict[str, Any]: + """Return non-default leaf paths using schema reflection.""" + result: dict[str, Any] = {} + if struct is None: + return result + schema = struct.schema + active_union = None + if schema.union_fields: + try: + active_union = struct.which() + except capnp.KjException: + active_union = None + + for name in schema.fieldnames: + if name in schema.union_fields and name != active_union: + continue + field = schema.fields[name] + leaf = path_join(prefix, name) + try: + value = getattr(struct, name) + except capnp.KjException: + continue + if field.proto.which() == "group": + result.update(populated_leaf_paths(value, leaf)) + continue + if field.proto.which() != "slot": + continue + twhich = field.proto.slot.type.which() + if twhich == "struct": + result.update(populated_leaf_paths(value, leaf)) + elif twhich == "list": + elem = field.proto.slot.type.list.elementType + list_leaf = f"{leaf}[]" + if elem.which() == "struct": + for item in value: + result.update(populated_leaf_paths(item, list_leaf)) + else: + if len(value) and any(bool(item) if not isinstance(item, (int, float)) else float(item) != 0 for item in value): + result[list_leaf] = list(value) + elif twhich == "text": + if value: + result[leaf] = value + elif twhich == "data": + if bytes(value): + result[leaf] = bytes(value) + elif twhich == "bool": + if bool(value): + result[leaf] = bool(value) + elif twhich == "enum": + if int(getattr(value, "raw", value)) != 0: + result[leaf] = str(value) + else: + try: + if float(value) != 0: + result[leaf] = value + except Exception: + if value: + result[leaf] = value + return result + + +def path_matches_allowlist(leaf: str, allowed: set[str]) -> bool: + if leaf in allowed: + return True + # allowlist stores paths with [] markers; leaf paths from populated_leaf_paths also use [] + return leaf in allowed + + +def _normalize(value: Any) -> Any: + if isinstance(value, dict): + return {key: _normalize(item) for key, item in value.items() if item not in (None, "", [], {}, b"")} + if isinstance(value, list): + return [_normalize(item) for item in value] + return value + + +def _to_dict(value: Any) -> Any: + if hasattr(value, "to_dict"): + return _normalize(value.to_dict()) + try: + return _normalize([item.to_dict() if hasattr(item, "to_dict") else item for item in value]) + except TypeError: + return value + + +def validate_field_allowlist(messages: list[Any], policy: dict[str, Any]) -> None: + allowed_map: dict[str, set[str]] = policy["_allowed_leaf_sets"] + selected_gps = policy["selected_gps_service"] + for event in messages: + service = event.which() + if service not in allowed_map: + raise FixtureError(f"undeclared service in output: {service}") + rebuilt = build_event(event, policy) + if rebuilt is None: + raise FixtureError(f"undeclared service in output: {service}") + # Compare against a copy whose sensitive GPS zeros match sanitize semantics so + # allowlisting detects undeclared leaves, not sensitive-zero violations. + if service == selected_gps or service in ("gpsLocation", "gpsLocationExternal"): + original_builder = event.as_builder() + zero_sensitive_location(getattr(original_builder, service)) + original = _to_dict(getattr(original_builder, service)) + payload = getattr(original_builder, service) + else: + original = _to_dict(getattr(event, service)) + payload = getattr(event, service) + canonical = _to_dict(getattr(rebuilt, service)) + if original == canonical: + continue + rebuilt_payload = getattr(rebuilt, service) + if is_list_service(service): + leaves: dict[str, Any] = {} + canon_leaves: dict[str, Any] = {} + for item in payload: + leaves.update(populated_leaf_paths(item, "[]")) + for item in rebuilt_payload: + canon_leaves.update(populated_leaf_paths(item, "[]")) + else: + leaves = populated_leaf_paths(payload) + canon_leaves = populated_leaf_paths(rebuilt_payload) + allowed = allowed_map[service] + for leaf in sorted(set(leaves) - set(canon_leaves)): + if not path_matches_allowlist(leaf, allowed): + raise FixtureError(f"undeclared populated field: {service}.{leaf}") + raise FixtureError(f"undeclared populated field under service: {service}") + + +def iter_text_data_leaves(node: Any, prefix: str = "") -> list[tuple[str, bytes]]: + leaves: list[tuple[str, bytes]] = [] + if node is None: + return leaves + if isinstance(node, list) or (hasattr(node, "__iter__") and not hasattr(node, "schema") and not isinstance(node, (str, bytes, bytearray))): + try: + for item in node: + leaves.extend(iter_text_data_leaves(item, f"{prefix}[]" if prefix else "[]")) + return leaves + except TypeError: + pass + + schema = getattr(node, "schema", None) + if schema is None: + return leaves + + active_union = None + if schema.union_fields: + try: + active_union = node.which() + except capnp.KjException: + active_union = None + + for name in schema.fieldnames: + if name in schema.union_fields and name != active_union: + continue + field = schema.fields[name] + leaf = path_join(prefix, name) + try: + value = getattr(node, name) + except capnp.KjException: + continue + if field.proto.which() == "group": + leaves.extend(iter_text_data_leaves(value, leaf)) + continue + if field.proto.which() != "slot": + continue + twhich = field.proto.slot.type.which() + if twhich == "text": + leaves.append((leaf, str(value).encode())) + elif twhich == "data": + leaves.append((leaf, bytes(value))) + elif twhich == "struct": + leaves.extend(iter_text_data_leaves(value, leaf)) + elif twhich == "list": + elem = field.proto.slot.type.list.elementType + list_prefix = f"{leaf}[]" + if elem.which() == "struct": + for item in value: + leaves.extend(iter_text_data_leaves(item, list_prefix)) + elif elem.which() == "text": + for item in value: + leaves.append((list_prefix, str(item).encode())) + elif elem.which() == "data": + for item in value: + leaves.append((list_prefix, bytes(item))) + return leaves + + +def can_frames(message: Any) -> list[tuple[int, bytes, int]]: + return [(int(frame.address), bytes(frame.dat), int(frame.src)) for frame in message] + + +def vin_fragments(vin: bytes) -> list[bytes]: + fragments: list[bytes] = [] + upper = min(VIN_FRAGMENT_MAX, len(vin)) + for size in range(VIN_FRAGMENT_MIN, upper + 1): + for offset in range(len(vin) - size + 1): + fragments.append(vin[offset:offset + size]) + return fragments + + +def scan_buffer(matches: Counter[tuple[str, int, str]], source: str, buffer: bytes, + tokens: list[tuple[str, bytes]], vin: bytes | None) -> None: + for label, value in tokens: + if value and value in buffer: + matches[(label, len(value), source)] += buffer.count(value) + if vin: + for fragment in vin_fragments(vin): + if fragment and fragment in buffer: + matches[("vin", len(fragment), source)] += buffer.count(fragment) + + +def _append_capped(buffer: bytes, payload: bytes, limit: int = MAX_CAN_CONCAT_BYTES) -> bytes: + combined = buffer + payload + if len(combined) <= limit: + return combined + return combined[-limit:] + + +def token_scan(messages: list[Any], tokens: list[tuple[str, bytes]], vin: bytes | None) -> list[dict[str, Any]]: + matches: Counter[tuple[str, int, str]] = Counter() + scan_vin = vin if vin is not None else None + # Exact Text/Data leaves via schema reflection + for event in messages: + service = event.which() + payload = getattr(event, service) + for leaf, data in iter_text_data_leaves(payload, service): + scan_buffer(matches, leaf, data, tokens, scan_vin) + + # CAN per-frame, short rolling windows, full concatenations, and VIN-substring + # reassembly that skips unrelated interleaved payloads. + bus_suffix: dict[int, bytes] = {} + bus_concat: dict[int, bytes] = {} + addr_concat: dict[tuple[int, int], bytes] = {} + vin_bus_concat: dict[int, bytes] = {} + vin_global_concat = b"" + global_suffix = b"" + global_concat = b"" + for event in messages: + if event.which() != "can": + continue + for address, payload, bus in can_frames(event.can): + source = f"can[{bus}]@0x{address:x}" + scan_buffer(matches, source, payload, tokens, scan_vin) + prev = bus_suffix.get(bus, b"") + window = prev[-CAN_OVERLAP:] + payload + if prev: + scan_buffer(matches, f"can[{bus}].rolling", window, tokens, scan_vin) + bus_suffix[bus] = window[-CAN_OVERLAP:] + gwindow = global_suffix[-CAN_OVERLAP:] + payload + if global_suffix: + scan_buffer(matches, "can.global.rolling", gwindow, tokens, scan_vin) + global_suffix = gwindow[-CAN_OVERLAP:] + + bus_concat[bus] = _append_capped(bus_concat.get(bus, b""), payload) + addr_key = (bus, address) + addr_concat[addr_key] = _append_capped(addr_concat.get(addr_key, b""), payload) + global_concat = _append_capped(global_concat, payload) + + if scan_vin and payload and payload in scan_vin: + vin_bus_concat[bus] = _append_capped(vin_bus_concat.get(bus, b""), payload) + vin_global_concat = _append_capped(vin_global_concat, payload) + + for bus, buffer in bus_concat.items(): + scan_buffer(matches, f"can[{bus}].concat", buffer, tokens, scan_vin) + for (bus, address), buffer in addr_concat.items(): + scan_buffer(matches, f"can[{bus}]@0x{address:x}.concat", buffer, tokens, scan_vin) + if global_concat: + scan_buffer(matches, "can.global.concat", global_concat, tokens, scan_vin) + for bus, buffer in vin_bus_concat.items(): + scan_buffer(matches, f"can[{bus}].vin_reassembly", buffer, tokens, scan_vin) + if vin_global_concat: + scan_buffer(matches, "can.global.vin_reassembly", vin_global_concat, tokens, scan_vin) + + return [ + {"label": label, "length": length, "count": count, "source": source} + for (label, length, source), count in sorted(matches.items()) + ] + + +def zero_match_accounting(tokens: list[tuple[str, bytes]]) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] + seen: set[tuple[str, int]] = set() + for label, value in tokens: + key = (label, len(value)) + if key in seen: + continue + seen.add(key) + rows.append({"label": label, "length": len(value), "count": 0, "source": ""}) + if label == "vin": + for size in range(VIN_FRAGMENT_MIN, min(VIN_FRAGMENT_MAX, len(value)) + 1): + frag_key = (label, size) + if frag_key in seen: + continue + seen.add(frag_key) + rows.append({"label": label, "length": size, "count": 0, "source": ""}) + return rows + + +def validate_can(messages: list[Any], policy: dict[str, Any], mode: str) -> dict[str, Any]: + rule = policy["pedal"] + frames: list[tuple[int, bytes, int]] = [] + for event in messages: + if event.which() == "can": + frames.extend(can_frames(event.can)) + pedal_frames = [(data, bus) for address, data, bus in frames if address == rule["address"]] + if mode == "no-pedal": + if pedal_frames: + raise FixtureError(f"no-pedal fixture contains pedal sensor frames: count={len(pedal_frames)}") + return {"address": rule["address"], "count": 0, "valid_count": 0, "counter_count": 0, "bus": rule["bus"]} + valid: list[bytes] = [] + counters: set[int] = set() + for data, bus in pedal_frames: + if bus != rule["bus"] or len(data) != rule["data_length"]: + continue + checksum = (sum(data[:rule["checksum_index"]]) + (rule["address"] & 0xff) + (rule["address"] >> 8)) & 0xff + if data[rule["checksum_index"]] == checksum: + valid.append(data) + counters.add(data[rule["counter_index"]] & rule["counter_mask"]) + if len(valid) < rule["minimum_frames"] or len(counters) < rule["minimum_counters"]: + raise FixtureError(f"pedal evidence insufficient: valid={len(valid)} counters={len(counters)}") + return { + "address": rule["address"], "count": len(pedal_frames), "valid_count": len(valid), + "counter_count": len(counters), "bus": rule["bus"], + } + + +def structural_checks(messages: list[Any], policy: dict[str, Any], case: str) -> dict[str, Any]: + if not messages: + raise FixtureError("fixture is empty") + counts = Counter(event.which() for event in messages) + valid_counts = Counter(event.which() for event in messages if event.valid) + valid_count = sum(valid_counts.values()) + valid_share = valid_count / len(messages) + if valid_share < VALID_SHARE_THRESHOLD: + raise FixtureError(f"valid-message share below 90 percent: {valid_share:.3f}") + + allowed = set(policy["allowed_services"]) + for service in counts: + if service not in allowed: + raise FixtureError(f"undeclared service in output: {service}") + + for service, minimum in policy["required_services"].items(): + if valid_counts.get(service, 0) < minimum: + raise FixtureError(f"required valid service count unmet: {service}") + + params = [event.carParams for event in messages if event.which() == "carParams"] + if not params: + raise FixtureError("carParams is required") + expected = policy["cases"][case] + pedal = expected["mode"] == "pedal" + expected_param = int(expected["safety_param"]) + if expected_param != expected_safety_param(expected["mode"]): + raise FixtureError("policy safety_param does not match fixed Pre-AP flags") + for cp in params: + if cp.carVin != policy["placeholder_vin"]: + raise FixtureError("carParams.carVin is not the public placeholder") + if len(cp.carFw) != 0: + raise FixtureError("carParams.carFw must be empty") + if cp.brand != "tesla": + raise FixtureError("carParams.brand must be tesla") + if cp.carFingerprint != expected["fingerprint"]: + raise FixtureError("unexpected car fingerprint") + if len(cp.safetyConfigs) != 1: + raise FixtureError("carParams must contain exactly one safetyConfigs entry") + safety = cp.safetyConfigs[0] + if not safety_model_is_tesla_preap(safety.safetyModel): + raise FixtureError("carParams safetyModel must be teslaPreap") + if int(safety.safetyParam) != expected_param: + raise FixtureError(f"carParams safetyParam must be {expected_param}") + if bool(cp.openpilotLongitudinalControl) != pedal or bool(cp.pcmCruise) == pedal: + raise FixtureError("Pre-AP pedal/longitudinal assertions failed") + + # Sensitive zeros must fail closed before allowlist rebuild compare, which also + # zeroes GPS and would otherwise mislabel vNED/location leaks as undeclared fields. + for field in policy["sensitive_zero_fields"]: + parts = field_parts(field) + service = parts[0] + for event in messages: + if event.which() != service: + continue + node: Any = getattr(event, service) + index = 1 + while index < len(parts): + part = parts[index] + if part == "[]": + if index == len(parts) - 1: + if any(float(item) != 0 for item in node): + raise FixtureError(f"sensitive field is not zero: {field}") + break + raise FixtureError(f"invalid sensitive path: {field}") + node = getattr(node, part) + index += 1 + else: + if hasattr(node, "__iter__") and not isinstance(node, (str, bytes, bytearray)): + if any(float(item) != 0 for item in node): + raise FixtureError(f"sensitive field is not zero: {field}") + elif float(node) != 0: + raise FixtureError(f"sensitive field is not zero: {field}") + + validate_field_allowlist(messages, policy) + + return { + "message_counts": dict(sorted(counts.items())), + "valid_message_counts": dict(sorted(valid_counts.items())), + "valid_message_share": valid_share, + } + + +def canonical_policy_digest(raw: dict[str, Any]) -> str: + material = {key: raw[key] for key in sorted(POLICY_KEYS)} + return digest(json.dumps(material, sort_keys=True, separators=(",", ":")).encode()) + + +def parse_policy(path: str) -> dict[str, Any]: + try: + with open(path, encoding="utf-8") as stream: + raw = json.load(stream) + except json.JSONDecodeError as error: + raise FixtureError("policy is malformed JSON") from error + except OSError as error: + raise FixtureError("policy cannot be read") from error + if not isinstance(raw, dict): + raise FixtureError("policy root must be an object") + if set(raw) != POLICY_KEYS: + raise FixtureError("policy keys are invalid") + if raw["schema_version"] != SCHEMA_VERSION: + raise FixtureError("unsupported policy schema_version") + if raw["placeholder_vin"] != PLACEHOLDER_VIN: + raise FixtureError("placeholder_vin must be the fixed public value") + if canonical_policy_digest(raw) != RELEASE_POLICY_SHA256: + raise FixtureError("policy is not the attested release contract") + + allowed = raw["allowed_services"] + forbidden = raw["forbidden_services"] + required = raw["required_services"] + freshness = raw["freshness_services"] + if not isinstance(allowed, dict) or not allowed: + raise FixtureError("allowed_services must be a nonempty object") + if not isinstance(forbidden, list) or not all(isinstance(item, str) for item in forbidden): + raise FixtureError("forbidden_services must be a string list") + if not isinstance(required, dict) or not required: + raise FixtureError("required_services must be a nonempty object") + if not isinstance(freshness, list) or not all(isinstance(item, str) for item in freshness): + raise FixtureError("freshness_services must be a string list") + if not isinstance(raw["selected_gps_service"], str): + raise FixtureError("selected_gps_service must be a string") + + known = event_service_names() + for service in list(allowed) + forbidden + list(required) + freshness + [raw["selected_gps_service"]]: + if service not in known: + raise FixtureError(f"unknown Event service in policy: {service}") + + if set(allowed) & set(forbidden): + raise FixtureError("allowed_services and forbidden_services must be disjoint") + missing_forbidden = MANDATORY_FORBIDDEN - set(forbidden) + if missing_forbidden: + raise FixtureError("forbidden_services missing mandatory baseline") + if raw["selected_gps_service"] not in allowed: + raise FixtureError("selected_gps_service must be allowed") + other_gps = {"gpsLocation", "gpsLocationExternal"} - {raw["selected_gps_service"]} + if other_gps & set(allowed): + raise FixtureError("only the selected GPS service may be allowed") + for service in freshness: + if service not in allowed: + raise FixtureError(f"freshness service must be allowed: {service}") + + leaf_sets: dict[str, set[str]] = {} + for service, paths in allowed.items(): + if not isinstance(service, str) or not isinstance(paths, list) or not all(isinstance(item, str) for item in paths): + raise FixtureError("allowed_services entries must map to string lists") + if service in freshness and paths: + # freshness-only services must not copy identifying leaves + raise FixtureError(f"freshness service must not declare identifying leaves: {service}") + leaf_sets[service] = expand_allowed_paths(service, paths) if paths else set() + + for service, minimum in required.items(): + if service not in allowed: + raise FixtureError(f"required service is not allowed: {service}") + if not isinstance(minimum, int) or isinstance(minimum, bool) or minimum < 1: + raise FixtureError(f"required service minimum must be a positive int: {service}") + + pedal = raw["pedal"] + if not isinstance(pedal, dict) or set(pedal) != PEDAL_KEYS: + raise FixtureError("pedal policy keys are invalid") + for key in ("address", "bus", "data_length", "counter_index", "counter_mask", "checksum_index", + "minimum_frames", "minimum_counters"): + value = pedal[key] + if not isinstance(value, int) or isinstance(value, bool) or value < 0: + raise FixtureError(f"pedal.{key} must be a non-negative int") + if pedal["checksum"] != "tesla_sum8_address": + raise FixtureError("unsupported pedal checksum") + if pedal["checksum_index"] >= pedal["data_length"] or pedal["counter_index"] >= pedal["data_length"]: + raise FixtureError("pedal indices out of range") + if pedal["data_length"] < 1 or pedal["bus"] > 255: + raise FixtureError("pedal ranges are invalid") + if pedal["minimum_frames"] < PEDAL_MIN_FRAMES or pedal["minimum_counters"] < PEDAL_MIN_COUNTERS: + raise FixtureError("pedal evidence minima below release floor") + + zeros = raw["sensitive_zero_fields"] + if not isinstance(zeros, list) or not all(isinstance(item, str) for item in zeros): + raise FixtureError("sensitive_zero_fields must be a string list") + selected = raw["selected_gps_service"] + required_zeros = {item for item in SENSITIVE_ZERO_BASELINE if item.startswith(selected + ".")} + if not required_zeros.issubset(set(zeros)): + raise FixtureError("sensitive_zero_fields missing mandatory GPS zeros including vNED") + for item in zeros: + service = item.split(".", 1)[0] + if service not in allowed and service not in ("gpsLocation", "gpsLocationExternal"): + raise FixtureError(f"sensitive zero service not allowed: {service}") + # validate path shape against schema when service allowed + if service in allowed: + rest = item.split(".", 1)[1] + resolve_policy_path(service, rest) + + cases = raw["cases"] + if not isinstance(cases, dict) or not cases: + raise FixtureError("cases must be a nonempty object") + for name, case in cases.items(): + if not isinstance(name, str) or not isinstance(case, dict) or set(case) != CASE_KEYS: + raise FixtureError("case entries are invalid") + if case["mode"] not in CASE_MODES or not isinstance(case["fingerprint"], str) or not case["fingerprint"]: + raise FixtureError(f"case mode/fingerprint invalid: {name}") + if case["fingerprint"] != "TESLA_MODEL_S_PREAP": + raise FixtureError("only TESLA_MODEL_S_PREAP cases are supported") + safety_param = case["safety_param"] + if not isinstance(safety_param, int) or isinstance(safety_param, bool): + raise FixtureError(f"case safety_param must be an int: {name}") + if safety_param != expected_safety_param(case["mode"]): + raise FixtureError(f"case safety_param must be {expected_safety_param(case['mode'])}: {name}") + + raw["_allowed_leaf_sets"] = leaf_sets + return raw + + +def decode_deny_token_value(encoding: str, value: str) -> bytes: + """Decode a deny token payload with strict, canonical binary-safe encodings.""" + if encoding not in DENY_ENCODINGS: + raise FixtureError("deny token encoding must be utf8, hex, or base64") + if not isinstance(value, str): + raise FixtureError("deny token value must be a string") + if encoding == "utf8": + try: + return value.encode("utf-8") + except UnicodeEncodeError as error: + raise FixtureError("deny token utf8 value is invalid") from error + if encoding == "hex": + if len(value) % 2 != 0 or not HEX_VALUE_RE.fullmatch(value): + raise FixtureError("deny token hex value must be lowercase hexadecimal") + return bytes.fromhex(value) + try: + decoded = base64.b64decode(value, validate=True) + except binascii.Error as error: + raise FixtureError("deny token base64 value is invalid") from error + if base64.b64encode(decoded).decode("ascii") != value: + raise FixtureError("deny token base64 value must be canonical") + return decoded + + +def load_deny(path: str) -> DenyManifest: + try: + with open(path, encoding="utf-8") as stream: + raw = json.load(stream) + except json.JSONDecodeError as error: + raise FixtureError("deny file is malformed JSON") from error + if not isinstance(raw, dict): + raise FixtureError("deny file root must be an object") + unknown = set(raw) - DENY_REQUIRED_KEYS - DENY_OPTIONAL_KEYS + if unknown: + raise FixtureError("deny file contains unknown keys") + if "raw_input_sha256" not in raw and "input_sha256" not in raw: + raise FixtureError("deny raw_input_sha256 must be lowercase hexadecimal SHA-256") + tokens_raw = raw.get("tokens") + if not isinstance(tokens_raw, list) or not tokens_raw: + raise FixtureError("deny file must contain a nonempty tokens list") + expected = raw.get("raw_input_sha256", raw.get("input_sha256")) + if not isinstance(expected, str) or not SHA256_RE.fullmatch(expected): + raise FixtureError("deny raw_input_sha256 must be lowercase hexadecimal SHA-256") + sanitized = raw.get("sanitized_output_sha256") + if sanitized is not None and (not isinstance(sanitized, str) or not SHA256_RE.fullmatch(sanitized)): + raise FixtureError("deny sanitized_output_sha256 must be lowercase hexadecimal SHA-256") + + tokens: list[tuple[str, bytes]] = [] + labels: set[str] = set() + values: set[bytes] = set() + for entry in tokens_raw: + if not isinstance(entry, dict) or set(entry) != {"label", "encoding", "value"}: + raise FixtureError("deny token entries require exactly label, encoding, and value") + label = entry["label"] + encoding = entry["encoding"] + value = entry["value"] + if not isinstance(label, str) or not SAFE_LABEL_RE.fullmatch(label): + raise FixtureError("deny token label is not a safe identifier") + if not isinstance(encoding, str): + raise FixtureError("deny token encoding must be utf8, hex, or base64") + encoded = decode_deny_token_value(encoding, value) + if len(encoded) < VIN_FRAGMENT_MIN: + raise FixtureError("deny token is shorter than six bytes") + if label in labels: + raise FixtureError("deny token labels must be unique") + if encoded in values: + raise FixtureError("deny token values must be unique") + labels.add(label) + values.add(encoded) + tokens.append((label, encoded)) + + vin_tokens = [(label, value) for label, value in tokens if label == "vin"] + if len(vin_tokens) != 1: + raise FixtureError("deny file must contain exactly one vin token") + vin = vin_tokens[0][1] + if len(vin) != VIN_LENGTH: + raise FixtureError("vin token must be exactly 17 bytes") + return DenyManifest( + tokens=tuple(tokens), + raw_input_sha256=expected, + sanitized_output_sha256=sanitized, + vin=vin, + ) + + +def extract_source_vins(messages: list[Any]) -> set[str]: + vins = {str(event.carParams.carVin) for event in messages if event.which() == "carParams"} + if not vins: + raise FixtureError("source carParams.carVin is required") + return vins + + +def verify_deny_vin_against_source(messages: list[Any], vin: bytes) -> None: + vins = extract_source_vins(messages) + if len(vins) != 1: + raise FixtureError("source carParams.carVin must be unique") + source_vin = next(iter(vins)) + if len(source_vin.encode()) != VIN_LENGTH: + raise FixtureError("source carParams.carVin must be exactly 17 bytes") + if source_vin.encode() != vin: + raise FixtureError("deny vin token does not match source carParams.carVin") + + +def relative_text_data_leaf(service: str, leaf: str) -> str: + if leaf == service: + return "" + if leaf.startswith(service) and len(leaf) > len(service) and leaf[len(service)] in ".[": + rest = leaf[len(service):] + return rest[1:] if rest.startswith(".") else rest + raise FixtureError(f"text/data leaf provenance is malformed: {leaf}") + + +def is_scrubbed_private_leaf(leaf: str) -> bool: + # carVin is allowlisted but replaced; carFw is stripped even if nested Data appears. + return leaf == "carParams.carVin" or leaf.startswith("carParams.carFw[]") + + +def is_private_text_data_leaf(service: str, leaf: str, policy: dict[str, Any]) -> bool: + """True when a raw Text/Data leaf must be covered by deny tokens (provenance-based).""" + if is_scrubbed_private_leaf(leaf): + return True + if leaf in ATTESTED_PUBLIC_TEXT_DATA_LEAVES: + return False + allowed = policy["_allowed_leaf_sets"].get(service) + if allowed is None: + return True + rel = relative_text_data_leaf(service, leaf) + # Allowlisted retained channels (including can[].dat) are not inventory sources. + # They remain token-scan sinks and never exempt private-provenance duplicates. + if path_matches_allowlist(rel, allowed): + return False + return True + + +def derive_private_text_data_inventory(messages: list[Any], policy: dict[str, Any]) -> set[bytes]: + """Inventory private Text/Data by raw leaf provenance, not sanitized set-subtraction.""" + inventory: set[bytes] = set() + for event in messages: + service = event.which() + payload = getattr(event, service) + for leaf, data in iter_text_data_leaves(payload, service): + if len(data) < VIN_FRAGMENT_MIN: + continue + if is_private_text_data_leaf(service, leaf, policy): + inventory.add(data) + return inventory + + +def verify_deny_inventory_completeness( + source_messages: list[Any], + tokens: list[tuple[str, bytes]], + vin: bytes, + policy: dict[str, Any], +) -> None: + verify_deny_vin_against_source(source_messages, vin) + private_inventory = derive_private_text_data_inventory(source_messages, policy) + covered = {value for _label, value in tokens} + missing = private_inventory - covered + if missing: + raise FixtureError("deny tokens incomplete for decoded private Text/Data inventory") + + +def lstat_path(path: Path) -> os.stat_result: + try: + return os.lstat(path) + except OSError as error: + raise FixtureError("path is inaccessible") from error + + +def assert_not_symlink(path: Path, label: str) -> None: + if path.exists() and path.is_symlink(): + raise FixtureError(f"{label} must not be a symlink") + + +def same_file(stat_a: os.stat_result, stat_b: os.stat_result) -> bool: + return stat_a.st_ino == stat_b.st_ino and stat_a.st_dev == stat_b.st_dev + + +def reject_symlink_parents(path: Path, label: str) -> None: + current = path if path.is_absolute() else Path.cwd() / path + for parent in [current, *current.parents]: + try: + if parent.is_symlink(): + raise FixtureError(f"{label} parent must not be a symlink") + except OSError as error: + raise FixtureError(f"{label} path is inaccessible") from error + + +def canonicalize_endpoint(path: Path, label: str) -> Path: + reject_symlink_parents(path, label) + absolute = path if path.is_absolute() else Path.cwd() / path + parent = absolute.parent + try: + resolved_parent = parent.resolve(strict=False) + except OSError as error: + raise FixtureError(f"{label} path is inaccessible") from error + reject_symlink_parents(resolved_parent / absolute.name, label) + canonical = resolved_parent / absolute.name + if canonical.exists() or canonical.is_symlink(): + assert_not_symlink(canonical, label) + return canonical + + +def validate_path_separation(paths: dict[str, Path]) -> dict[str, Path]: + resolved: dict[str, Path] = {} + for label, path in paths.items(): + resolved[label] = canonicalize_endpoint(path, label) + items = list(resolved.items()) + for index, (label_a, path_a) in enumerate(items): + for label_b, path_b in items[index + 1:]: + if path_a == path_b: + raise FixtureError(f"path collision between {label_a} and {label_b}") + if path_a.exists() and path_b.exists(): + if same_file(lstat_path(path_a), lstat_path(path_b)): + raise FixtureError(f"inode alias between {label_a} and {label_b}") + return resolved + + +def open_private_temp(destination_dir: Path, suffix: str) -> tuple[int, Path]: + destination_dir.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=".fixture-", suffix=suffix, dir=str(destination_dir)) + try: + os.fchmod(fd, 0o600) + except OSError: + os.close(fd) + Path(name).unlink(missing_ok=True) + raise + path = Path(name) + if path.is_symlink(): + os.close(fd) + path.unlink(missing_ok=True) + raise FixtureError("temporary path must not be a symlink") + return fd, path + + +def write_bytes_atomic(destination: Path, data: bytes) -> None: + fd, tmp = open_private_temp(destination.parent, suffix=".tmp") + try: + with os.fdopen(fd, "wb") as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.replace(tmp, destination) + except Exception: + try: + os.close(fd) + except Exception: + pass + tmp.unlink(missing_ok=True) + raise + + +def write_json_atomic(destination: Path, payload: dict[str, Any]) -> None: + data = (json.dumps(payload, sort_keys=True, separators=(",", ":")) + "\n").encode() + write_bytes_atomic(destination, data) + + +def serialize_log_bytes(messages: list[Any], *, compress: bool = True) -> bytes: + data = b"".join(message.as_builder().to_bytes() for message in messages) + if compress: + return zstandard.ZstdCompressor(level=10).compress(data) + return data + + +def write_fd_bytes(fd: int, data: bytes) -> None: + view = memoryview(data) + while view: + written = os.write(fd, view) + if written <= 0: + raise FixtureError("failed to write temporary fixture bytes") + view = view[written:] + os.fsync(fd) + + +def public_status(*, case: str, scope: str, output_sha256: str | None, output_bytes: int | None, + performed: bool | None = None) -> dict[str, Any]: + report: dict[str, Any] = {"status": "ok", "case": case, "scope": scope} + if output_sha256 is not None: + report["sanitized_output_sha256" if scope != "public" else "fixture_sha256"] = output_sha256 + if output_bytes is not None: + report["output_bytes"] = output_bytes + if performed is not None: + report["private_token_scan"] = {"performed": performed} + return report + + +def build_validation_report( + *, + policy: dict[str, Any], + case: str, + messages: list[Any], + fixture_bytes: bytes, + scope: str, + tokens: list[tuple[str, bytes]] | None, + vin: bytes | None, + source_message_counts: dict[str, int] | None, +) -> dict[str, Any]: + report: dict[str, Any] = { + "schema_version": policy["schema_version"], + "case": case, + "scope": scope, + "fixture_sha256": digest(fixture_bytes), + "output_bytes": len(fixture_bytes), + } + if source_message_counts is not None: + report["source_message_counts"] = source_message_counts + report.update(structural_checks(messages, policy, case)) + report["can_evidence"] = validate_can(messages, policy, policy["cases"][case]["mode"]) + + if scope == "public": + report["private_token_scan"] = {"performed": False} + else: + assert tokens is not None and vin is not None + matches = token_scan(messages, tokens, vin) + accounting = zero_match_accounting(list(tokens)) + if matches: + by_key = {(row["label"], row["length"]): row for row in accounting} + for match in matches: + key = (match["label"], match["length"]) + row = by_key.get(key) + if row is None: + accounting.append(dict(match)) + else: + row["count"] = match["count"] + row["source"] = match["source"] + report["private_token_scan"] = {"performed": True, "token_matches": matches} + report["token_match_accounting"] = accounting + report["_rejected_private_token"] = True + else: + report["private_token_scan"] = {"performed": True, "token_matches": accounting} + return report + + +def accept_six_process_outputs( + *, + case: str, + policy: dict[str, Any], + process_outputs: Mapping[str, list[Any]], + case_params: Mapping[str, Any], + valid_share_threshold: float = VALID_SHARE_THRESHOLD, +) -> dict[str, Any]: + """Publication gate over fixed typed case params and six-process replay outputs. + + Does not itself execute process replay. Callers supply the per-process output + streams produced under ``case_params`` (for example NAP_PREAP_*_PARAMS). + """ + if case not in policy["cases"]: + raise FixtureError("unknown fixture case") + expected = policy["cases"][case] + mode = expected["mode"] + if not isinstance(case_params.get("NAPPedalEnabled"), bool): + raise FixtureError("case_params.NAPPedalEnabled must be a bool") + if bool(case_params["NAPPedalEnabled"]) != (mode == "pedal"): + raise FixtureError("case_params.NAPPedalEnabled does not match case mode") + if case_params.get("NAPRadarEnabled") is not True: + raise FixtureError("case_params must enable radar emulation") + + missing = [name for name in SIX_PROCESS_OUTPUTS if name not in process_outputs] + if missing: + raise FixtureError(f"missing process outputs: {','.join(missing)}") + + per_process: dict[str, Any] = {} + for proc_name, required_services in SIX_PROCESS_OUTPUTS.items(): + messages = list(process_outputs[proc_name]) + if not messages: + raise FixtureError(f"process produced no outputs: {proc_name}") + counts = Counter(message.which() for message in messages) + valid_counts = Counter(message.which() for message in messages if message.valid) + present = set(counts) + if not required_services.issubset(present): + raise FixtureError(f"process missing declared outputs: {proc_name}") + shares: dict[str, float] = {} + for service in required_services: + total = counts[service] + share = valid_counts.get(service, 0) / total + shares[service] = share + if share < valid_share_threshold: + raise FixtureError(f"process valid-share below threshold: {proc_name}.{service}") + per_process[proc_name] = { + "message_counts": dict(sorted(counts.items())), + "valid_shares": dict(sorted(shares.items())), + } + + card_params = [message.carParams for message in process_outputs["card"] if message.which() == "carParams"] + if not card_params: + raise FixtureError("card did not emit carParams") + expected_param = int(expected["safety_param"]) + for cp in card_params: + if cp.carFingerprint != expected["fingerprint"]: + raise FixtureError("card carParams fingerprint mismatch") + if len(cp.safetyConfigs) != 1 or not safety_model_is_tesla_preap(cp.safetyConfigs[0].safetyModel): + raise FixtureError("card carParams safety config mismatch") + if int(cp.safetyConfigs[0].safetyParam) != expected_param: + raise FixtureError("card carParams safetyParam mismatch") + pedal = mode == "pedal" + if bool(cp.openpilotLongitudinalControl) != pedal or bool(cp.pcmCruise) == pedal: + raise FixtureError("card carParams mode mismatch") + + return { + "status": "ok", + "case": case, + "processes": list(SIX_PROCESS_OUTPUTS), + "process_reports": per_process, + "card_mode": mode, + "card_fingerprint": expected["fingerprint"], + "card_safety_param": expected_param, + } + + +def decompress_zstd_bounded(raw: bytes) -> bytes: + """Bounded single-frame zstd decompress with exact EOF and trailing-data rejection.""" + try: + params = zstandard.get_frame_parameters(raw) + except zstandard.ZstdError as error: + raise FixtureError("input is malformed") from error + declared = params.content_size + if declared != ZSTD_CONTENTSIZE_UNKNOWN and declared > MAX_DECOMPRESSED_INPUT_BYTES: + raise FixtureError("input exceeds decompressed size limit") + + decompressor = zstandard.ZstdDecompressor().decompressobj() + chunks: list[bytes] = [] + total = 0 + offset = 0 + try: + while offset < len(raw): + end = min(offset + ZSTD_DECOMPRESS_CHUNK, len(raw)) + piece = decompressor.decompress(raw[offset:end]) + offset = end + if piece: + total += len(piece) + if total > MAX_DECOMPRESSED_INPUT_BYTES: + raise FixtureError("input exceeds decompressed size limit") + chunks.append(piece) + if decompressor.eof: + trailing = decompressor.unused_data + raw[offset:] + if trailing: + raise FixtureError("input is malformed") + break + else: + if not decompressor.eof: + raise FixtureError("input is malformed") + except FixtureError: + raise + except zstandard.ZstdError as error: + message = str(error).lower() + if "maximum" in message or "too large" in message or "max" in message: + raise FixtureError("input exceeds decompressed size limit") from error + raise FixtureError("input is malformed") from error + return b"".join(chunks) + + +def load_source_messages(raw: bytes) -> list[Any]: + if len(raw) > MAX_COMPRESSED_INPUT_BYTES: + raise FixtureError("input exceeds compressed size limit") + data = raw + try: + if raw.startswith(ZSTD_MAGIC): + data = decompress_zstd_bounded(raw) + elif raw.startswith(b"BZh"): + data = __import__("bz2").decompress(raw) + if len(data) > MAX_DECOMPRESSED_INPUT_BYTES: + raise FixtureError("input exceeds decompressed size limit") + except FixtureError: + raise + except MemoryError as error: + raise FixtureError("input exceeds decompressed size limit") from error + except (zstandard.ZstdError, OSError, ValueError) as error: + message = str(error).lower() + if "maximum" in message or "too large" in message or "max" in message: + raise FixtureError("input exceeds decompressed size limit") from error + raise FixtureError("input is malformed") from error + + try: + import warnings + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", RuntimeWarning) + messages = list(LogReader.from_bytes(data)) + if any(issubclass(item.category, RuntimeWarning) for item in caught) or (len(data) > 0 and not messages): + raise FixtureError("input is malformed") + except MemoryError as error: + raise FixtureError("input exceeds decompressed size limit") from error + except FixtureError: + raise + except (capnp.KjException, zstandard.ZstdError, ValueError, OSError, RuntimeError) as error: + raise FixtureError("input is malformed") from error + + if len(messages) > MAX_LOG_MESSAGES: + raise FixtureError("input exceeds message count limit") + return messages + + +def process( + input_path: str, + output_path: str | None, + report_path: str, + policy_path: str, + case: str, + deny_path: str | None, + sanitize: bool, + input_sha256: str | None = None, +) -> dict[str, Any]: + policy = parse_policy(policy_path) + if case not in policy["cases"]: + raise FixtureError("unknown fixture case") + + input_p = Path(input_path) + policy_p = Path(policy_path) + report_p = Path(report_path) + output_p = Path(output_path) if output_path else None + deny_p = Path(deny_path) if deny_path else None + + path_map = {"input": input_p, "policy": policy_p, "report": report_p} + if output_p is not None: + path_map["output"] = output_p + if deny_p is not None: + path_map["deny"] = deny_p + if sanitize: + if output_p is None: + raise FixtureError("sanitize requires --output") + if output_p == report_p: + raise FixtureError("output and report must be distinct") + resolved = validate_path_separation(path_map) + input_p = resolved["input"] + policy_p = resolved["policy"] + report_p = resolved["report"] + output_p = resolved.get("output") + deny_p = resolved.get("deny") + + deny: DenyManifest | None = None + if sanitize: + if deny_p is None: + raise FixtureError("sanitize requires a deny token file") + deny = load_deny(str(deny_p)) + elif deny_p is not None: + deny = load_deny(str(deny_p)) + + if input_sha256 is not None: + if not SHA256_RE.fullmatch(input_sha256): + raise FixtureError("input_sha256 must be lowercase hexadecimal SHA-256") + + raw = input_p.read_bytes() + if len(raw) > MAX_COMPRESSED_INPUT_BYTES: + raise FixtureError("input exceeds compressed size limit") + raw_hash = digest(raw) + + if sanitize: + assert deny is not None + if raw_hash != deny.raw_input_sha256: + raise FixtureError("input SHA-256 does not match deny raw_input_sha256") + if input_sha256 is not None and input_sha256 != deny.raw_input_sha256: + raise FixtureError("input_sha256 conflicts with deny raw_input_sha256") + else: + if deny is not None: + expected_fixture = deny.sanitized_output_sha256 + if expected_fixture is None: + raise FixtureError("private validate requires deny sanitized_output_sha256") + if raw_hash != expected_fixture: + raise FixtureError("input SHA-256 does not match deny sanitized_output_sha256") + if input_sha256 is not None and input_sha256 != expected_fixture: + raise FixtureError("input_sha256 conflicts with deny sanitized_output_sha256") + elif input_sha256 is not None and raw_hash != input_sha256: + raise FixtureError("input SHA-256 does not match --input-sha256") + + source_messages = load_source_messages(raw) + + temp_output: Path | None = None + try: + if sanitize: + assert output_p is not None and deny is not None + # Fail closed for stale destinations: clear any preexisting output before work. + if output_p.exists() or output_p.is_symlink(): + assert_not_symlink(output_p, "output") + output_p.unlink() + messages = [built for event in source_messages if (built := build_event(event, policy)) is not None] + verify_deny_inventory_completeness(source_messages, list(deny.tokens), deny.vin, policy) + fd, temp_output = open_private_temp(output_p.parent, suffix=".zst") + try: + output_bytes = serialize_log_bytes(messages) + write_fd_bytes(fd, output_bytes) + finally: + os.close(fd) + messages = list(LogReader.from_bytes(output_bytes)) + report = build_validation_report( + policy=policy, + case=case, + messages=messages, + fixture_bytes=output_bytes, + scope="private", + tokens=list(deny.tokens), + vin=deny.vin, + source_message_counts=dict(sorted(Counter(event.which() for event in source_messages).items())), + ) + output_digest = digest(output_bytes) + report["sanitized_output_sha256"] = output_digest + if deny.sanitized_output_sha256 is not None and deny.sanitized_output_sha256 != output_digest: + raise FixtureError("sanitized output SHA-256 does not match deny sanitized_output_sha256") + rejected = report.pop("_rejected_private_token", False) + write_json_atomic(report_p, report) + if rejected: + temp_output.unlink(missing_ok=True) + temp_output = None + output_p.unlink(missing_ok=True) + raise FixtureError("private token detected in retained output") + os.replace(temp_output, output_p) + temp_output = None + return public_status( + case=case, scope="private", output_sha256=output_digest, + output_bytes=len(output_bytes), performed=True, + ) + + scope = "private" if deny is not None else "public" + if scope == "private": + assert deny is not None + # Private validate of a sanitized fixture still requires the original VIN token. + if deny.vin.decode() == PLACEHOLDER_VIN: + raise FixtureError("private validate vin token must be the original private VIN") + report = build_validation_report( + policy=policy, + case=case, + messages=source_messages, + fixture_bytes=raw, + scope=scope, + tokens=list(deny.tokens) if deny is not None else None, + vin=deny.vin if deny is not None else None, + source_message_counts=None, + ) + rejected = report.pop("_rejected_private_token", False) + write_json_atomic(report_p, report) + if rejected: + raise FixtureError("private token detected in retained output") + return public_status( + case=case, + scope=scope, + output_sha256=digest(raw), + output_bytes=len(raw), + performed=(scope == "private"), + ) + except Exception: + if temp_output is not None: + temp_output.unlink(missing_ok=True) + if sanitize and output_p is not None: + output_p.unlink(missing_ok=True) + raise + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command", required=True) + for command in ("sanitize", "validate"): + sub = subparsers.add_parser(command) + sub.add_argument("--policy", required=True) + sub.add_argument("--input-sha256") + sub.add_argument("--case", required=True) + sub.add_argument("--input", required=True) + sub.add_argument("--output", required=command == "sanitize") + sub.add_argument("--report", required=True) + sub.add_argument("--deny-token-file") + args = parser.parse_args(argv) + try: + status = process( + args.input, + args.output, + args.report, + args.policy, + args.case, + args.deny_token_file, + args.command == "sanitize", + args.input_sha256, + ) + print(json.dumps(status, sort_keys=True, separators=(",", ":"))) + return 0 + except (FixtureError, OSError, capnp.KjException, zstandard.ZstdError, json.JSONDecodeError, TypeError, ValueError, KeyError): + print("fixture validation failed", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/selfdrive/test/process_replay/imgproc_replay_ref_hash b/selfdrive/test/process_replay/imgproc_replay_ref_hash deleted file mode 100644 index defcb3681c691d..00000000000000 --- a/selfdrive/test/process_replay/imgproc_replay_ref_hash +++ /dev/null @@ -1 +0,0 @@ -707434c540e685bbe2886b3ff7c82fd61939d362 \ No newline at end of file diff --git a/selfdrive/test/process_replay/migration.py b/selfdrive/test/process_replay/migration.py index 46130f85546c0d..b5eba466a34d4a 100644 --- a/selfdrive/test/process_replay/migration.py +++ b/selfdrive/test/process_replay/migration.py @@ -1,134 +1,325 @@ from collections import defaultdict +from collections.abc import Callable +from typing import cast +import capnp +import functools +import traceback -from cereal import messaging +from cereal import messaging, car, log from opendbc.car.fingerprints import MIGRATION -from opendbc.car.toyota.values import EPS_SCALE +from opendbc.car.toyota.values import EPS_SCALE, ToyotaSafetyFlags +from opendbc.car.ford.values import CAR as FORD, FordFlags, FordSafetyFlags +from opendbc.car.hyundai.values import HyundaiSafetyFlags +from opendbc.car.gm.values import GMSafetyFlags +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.selfdrive.modeld.fill_model_msg import fill_xyz_poly, fill_lane_line_meta from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_encode_index +from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_accel_from_plan from openpilot.system.manager.process_config import managed_processes -from panda import Panda - - -# TODO: message migration should happen in-place -def migrate_all(lr, old_logtime=False, manager_states=False, panda_states=False, camera_states=False): - msgs = migrate_sensorEvents(lr, old_logtime) - msgs = migrate_carParams(msgs, old_logtime) - msgs = migrate_gpsLocation(msgs) - msgs = migrate_deviceState(msgs) - msgs = migrate_carOutput(msgs) - msgs = migrate_controlsState(msgs) +from openpilot.tools.lib.logreader import LogIterable + +MessageWithIndex = tuple[int, capnp.lib.capnp._DynamicStructReader] +MigrationOps = tuple[list[tuple[int, capnp.lib.capnp._DynamicStructReader]], list[capnp.lib.capnp._DynamicStructReader], list[int]] +MigrationFunc = Callable[[list[MessageWithIndex]], MigrationOps] + + +# rules for migration functions +# 1. must use the decorator @migration(inputs=[...], product="...") and MigrationFunc signature +# 2. it only gets the messages that are in the inputs list +# 3. product is the message type created by the migration function, and the function will be skipped if product type already exists in lr +# 4. it must return a list of operations to be applied to the logreader (replace, add, delete) +# 5. all migration functions must be independent of each other +def migrate_all(lr: LogIterable, manager_states: bool = False, panda_states: bool = False, camera_states: bool = False): + migrations = [ + migrate_sensorEvents, + migrate_carParams, + migrate_gpsLocation, + migrate_deviceState, + migrate_carOutput, + migrate_controlsState, + migrate_carState, + migrate_liveLocationKalman, + migrate_livePose, + migrate_liveTracks, + migrate_driverAssistance, + migrate_drivingModelData, + migrate_onroadEvents, + migrate_driverMonitoringState, + migrate_longitudinalPlan, + ] if manager_states: - msgs = migrate_managerState(msgs) + migrations.append(migrate_managerState) if panda_states: - msgs = migrate_pandaStates(msgs) - msgs = migrate_peripheralState(msgs) + migrations.extend([migrate_pandaStates, migrate_peripheralState]) if camera_states: - msgs = migrate_cameraStates(msgs) + migrations.append(migrate_cameraStates) + + return migrate(lr, migrations) - return msgs +def migrate(lr: LogIterable, migration_funcs: list[MigrationFunc]): + lr = list(lr) + grouped = defaultdict(list) + for i, msg in enumerate(lr): + grouped[msg.which()].append(i) + + replace_ops, add_ops, del_ops = [], [], [] + for migration in migration_funcs: + assert hasattr(migration, "inputs") and hasattr(migration, "product"), "Migration functions must use @migration decorator" + if migration.product in grouped: # skip if product already exists + continue + + sorted_indices = sorted(ii for i in cast(list[str], migration.inputs) for ii in grouped.get(i, [])) + msg_gen = [(i, lr[i]) for i in sorted_indices] + r_ops, a_ops, d_ops = migration(msg_gen) + replace_ops.extend(r_ops) + add_ops.extend(a_ops) + del_ops.extend(d_ops) + + for index, msg in replace_ops: + lr[index] = msg + for index in sorted(del_ops, reverse=True): + del lr[index] + for msg in add_ops: + lr.append(msg) + lr = sorted(lr, key=lambda x: x.logMonoTime) + + return lr + + +def as_reader(builder) -> capnp.lib.capnp._DynamicStructReader: + return log.Event.from_bytes(builder.to_bytes()).__enter__() # round-trip through bytes, 2x faster and 30x less memory than builder.as_reader() + + +def migration(inputs: list[str], product: str|None=None): + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + wrapper.inputs = inputs + wrapper.product = product + return wrapper + return decorator + + +def migrate_onroad_event(event: capnp.lib.capnp._DynamicStructReader): + event_dict = event.to_dict() + try: + return log.OnroadEvent(**event_dict) + except capnp.lib.capnp.KjException as e: + # Ignore legacy events the current schema no longer defines. + if "enum has no such enumerant" in str(e): + return None + raise + + +@migration(inputs=["longitudinalPlan", "carParams"]) +def migrate_longitudinalPlan(msgs): + ops = [] + + needs_migration = all(msg.longitudinalPlan.aTarget == 0.0 for _, msg in msgs if msg.which() == 'longitudinalPlan') + CP = next((m.carParams for _, m in msgs if m.which() == 'carParams'), None) + if not needs_migration or CP is None: + return [], [], [] + + for index, msg in msgs: + if msg.which() != 'longitudinalPlan': + continue + new_msg = msg.as_builder() + a_target, should_stop = get_accel_from_plan(msg.longitudinalPlan.speeds, msg.longitudinalPlan.accels, ModelConstants.T_IDXS[:CONTROL_N]) + new_msg.longitudinalPlan.aTarget, new_msg.longitudinalPlan.shouldStop = float(a_target), bool(should_stop) + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["longitudinalPlan"], product="driverAssistance") +def migrate_driverAssistance(msgs): + add_ops = [] + for _, msg in msgs: + new_msg = messaging.new_message('driverAssistance', valid=True, logMonoTime=msg.logMonoTime) + add_ops.append(as_reader(new_msg)) + return [], add_ops, [] + + +@migration(inputs=["modelV2"], product="drivingModelData") +def migrate_drivingModelData(msgs): + add_ops = [] + for _, msg in msgs: + dmd = messaging.new_message('drivingModelData', valid=msg.valid, logMonoTime=msg.logMonoTime) + for field in ["frameId", "frameIdExtra", "frameDropPerc", "modelExecutionTime", "action"]: + setattr(dmd.drivingModelData, field, getattr(msg.modelV2, field)) + for meta_field in ["laneChangeState", "laneChangeState"]: + setattr(dmd.drivingModelData.meta, meta_field, getattr(msg.modelV2.meta, meta_field)) + if len(msg.modelV2.laneLines) and len(msg.modelV2.laneLineProbs): + fill_lane_line_meta(dmd.drivingModelData.laneLineMeta, msg.modelV2.laneLines, msg.modelV2.laneLineProbs) + if all(len(a) for a in [msg.modelV2.position.x, msg.modelV2.position.y, msg.modelV2.position.z]): + fill_xyz_poly(dmd.drivingModelData.path, ModelConstants.POLY_PATH_DEGREE, msg.modelV2.position.x, msg.modelV2.position.y, msg.modelV2.position.z) + add_ops.append(as_reader(dmd)) + return [], add_ops, [] + + +@migration(inputs=["liveTracksDEPRECATED"], product="liveTracks") +def migrate_liveTracks(msgs): + ops = [] + for index, msg in msgs: + new_msg = messaging.new_message('liveTracks') + new_msg.valid = msg.valid + new_msg.logMonoTime = msg.logMonoTime -def migrate_controlsState(lr): - ret = [] + pts = [] + for track in msg.liveTracksDEPRECATED: + pt = car.RadarData.RadarPoint() + pt.trackId = track.trackId + + pt.dRel = track.dRel + pt.yRel = track.yRel + pt.vRel = track.vRel + pt.aRel = track.aRel + pt.measured = True + pts.append(pt) + + new_msg.liveTracks.points = pts + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["liveLocationKalmanDEPRECATED"], product="livePose") +def migrate_liveLocationKalman(msgs): + nans = [float('nan')] * 3 + ops = [] + for index, msg in msgs: + m = messaging.new_message('livePose') + m.valid = msg.valid + m.logMonoTime = msg.logMonoTime + m.livePose.timestamp = msg.logMonoTime + for field in ["orientationNED", "velocityDevice", "accelerationDevice", "angularVelocityDevice"]: + lp_field, llk_field = getattr(m.livePose, field), getattr(msg.liveLocationKalmanDEPRECATED, field) + lp_field.x, lp_field.y, lp_field.z = llk_field.value or nans + lp_field.xStd, lp_field.yStd, lp_field.zStd = llk_field.std or nans + lp_field.valid = llk_field.valid + for flag in ["inputsOK", "posenetOK", "sensorsOK"]: + setattr(m.livePose, flag, getattr(msg.liveLocationKalmanDEPRECATED, flag)) + ops.append((index, as_reader(m))) + return ops, [], [] + + +@migration(inputs=["livePose"]) +def migrate_livePose(msgs): + ops = [] + needs_migration = all(msg.livePose.timestamp == 0 for _, msg in msgs if msg.which() == 'livePose') + if not needs_migration: + return [], [], [] + + for index, msg in msgs: + if msg.which() == "livePose": + new_msg = msg.as_builder() + new_msg.livePose.timestamp = msg.logMonoTime + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["controlsState"], product="selfdriveState") +def migrate_controlsState(msgs): + add_ops = [] + for _, msg in msgs: + m = messaging.new_message('selfdriveState') + m.valid = msg.valid + m.logMonoTime = msg.logMonoTime + ss = m.selfdriveState + for field in ("enabled", "active", "state", "engageable", "alertText1", "alertText2", + "alertStatus", "alertSize", "alertType", "experimentalMode", + "personality"): + setattr(ss, field, getattr(msg.controlsState.deprecated, field)) + add_ops.append(as_reader(m)) + return [], add_ops, [] + + +@migration(inputs=["carState", "controlsState"]) +def migrate_carState(msgs): + ops = [] last_cs = None - for msg in lr: + for index, msg in msgs: if msg.which() == 'controlsState': last_cs = msg - - m = messaging.new_message('selfdriveState') - m.valid = msg.valid - m.logMonoTime = msg.logMonoTime - ss = m.selfdriveState - for field in ("enabled", "active", "state", "engageable", "alertText1", "alertText2", - "alertStatus", "alertSize", "alertType", "experimentalMode", - "personality"): - setattr(ss, field, getattr(msg.controlsState, field+"DEPRECATED")) - ret.append(m.as_reader()) elif msg.which() == 'carState' and last_cs is not None: - if last_cs.controlsState.vCruiseDEPRECATED - msg.carState.vCruise > 0.1: + if last_cs.controlsState.deprecated.vCruise - msg.carState.vCruise > 0.1: msg = msg.as_builder() - msg.carState.vCruise = last_cs.controlsState.vCruiseDEPRECATED - msg.carState.vCruiseCluster = last_cs.controlsState.vCruiseClusterDEPRECATED - msg = msg.as_reader() - - ret.append(msg) - return ret + msg.carState.vCruise = last_cs.controlsState.deprecated.vCruise + msg.carState.vCruiseCluster = last_cs.controlsState.deprecated.vCruiseCluster + ops.append((index, as_reader(msg))) + return ops, [], [] -def migrate_managerState(lr): - all_msgs = [] - for msg in lr: - if msg.which() != "managerState": - all_msgs.append(msg) - continue - +@migration(inputs=["managerState"]) +def migrate_managerState(msgs): + ops = [] + for index, msg in msgs: new_msg = msg.as_builder() new_msg.managerState.processes = [{'name': name, 'running': True} for name in managed_processes] - all_msgs.append(new_msg.as_reader()) - - return all_msgs - - -def migrate_gpsLocation(lr): - all_msgs = [] - for msg in lr: - if msg.which() in ('gpsLocation', 'gpsLocationExternal'): - new_msg = msg.as_builder() - g = getattr(new_msg, new_msg.which()) - # hasFix is a newer field - if not g.hasFix and g.flags == 1: - g.hasFix = True - all_msgs.append(new_msg.as_reader()) - else: - all_msgs.append(msg) - return all_msgs + ops.append((index, as_reader(new_msg))) + return ops, [], [] -def migrate_deviceState(lr): - all_msgs = [] - dt = None - for msg in lr: - if msg.which() == 'initData': - dt = msg.initData.deviceType +@migration(inputs=["gpsLocation", "gpsLocationExternal"]) +def migrate_gpsLocation(msgs): + ops = [] + for index, msg in msgs: + new_msg = msg.as_builder() + g = getattr(new_msg, new_msg.which()) + # hasFix is a newer field + if not g.hasFix and g.flags == 1: + g.hasFix = True + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["deviceState", "initData"]) +def migrate_deviceState(msgs): + init_data = next((m.initData for _, m in msgs if m.which() == 'initData'), None) + device_state = next((m.deviceState for _, m in msgs if m.which() == 'deviceState'), None) + if init_data is None or device_state is None: + return [], [], [] + + ops = [] + for i, msg in msgs: if msg.which() == 'deviceState': n = msg.as_builder() - n.deviceState.deviceType = dt - all_msgs.append(n.as_reader()) - else: - all_msgs.append(msg) - return all_msgs + n.deviceState.deviceType = init_data.deviceType + ops.append((i, as_reader(n))) + return ops, [], [] -def migrate_carOutput(lr): - # migration needed only for routes before carOutput - if any(msg.which() == 'carOutput' for msg in lr): - return lr +@migration(inputs=["carControl"], product="carOutput") +def migrate_carOutput(msgs): + add_ops = [] + for _, msg in msgs: + co = messaging.new_message('carOutput') + co.valid = msg.valid + co.logMonoTime = msg.logMonoTime + co.carOutput.actuatorsOutput = msg.carControl.actuatorsOutputDEPRECATED + add_ops.append(as_reader(co)) + return [], add_ops, [] - all_msgs = [] - for msg in lr: - if msg.which() == 'carControl': - co = messaging.new_message('carOutput') - co.valid = msg.valid - co.logMonoTime = msg.logMonoTime - co.carOutput.actuatorsOutput = msg.carControl.actuatorsOutputDEPRECATED - all_msgs.append(co.as_reader()) - all_msgs.append(msg) - return all_msgs - -def migrate_pandaStates(lr): - all_msgs = [] +@migration(inputs=["pandaStates", "pandaStateDEPRECATED", "carParams"]) +def migrate_pandaStates(msgs): # TODO: safety param migration should be handled automatically safety_param_migration = { - "TOYOTA_PRIUS": EPS_SCALE["TOYOTA_PRIUS"] | Panda.FLAG_TOYOTA_STOCK_LONGITUDINAL, - "TOYOTA_RAV4": EPS_SCALE["TOYOTA_RAV4"] | Panda.FLAG_TOYOTA_ALT_BRAKE, - "KIA_EV6": Panda.FLAG_HYUNDAI_EV_GAS | Panda.FLAG_HYUNDAI_CANFD_HDA2, + "TOYOTA_PRIUS": EPS_SCALE["TOYOTA_PRIUS"] | ToyotaSafetyFlags.STOCK_LONGITUDINAL, + "TOYOTA_RAV4": EPS_SCALE["TOYOTA_RAV4"] | ToyotaSafetyFlags.ALT_BRAKE, + "KIA_EV6": HyundaiSafetyFlags.EV_GAS | HyundaiSafetyFlags.CANFD_LKA_STEERING, + "CHEVROLET_VOLT": GMSafetyFlags.EV, + "CHEVROLET_BOLT_EUV": GMSafetyFlags.EV | GMSafetyFlags.HW_CAM, } + # TODO: get new Ford route + safety_param_migration |= dict.fromkeys((set(FORD) - FORD.with_flags(FordFlags.CANFD)), FordSafetyFlags.LONG_CONTROL) - # Migrate safety param base on carState - CP = next((m.carParams for m in lr if m.which() == 'carParams'), None) + # Migrate safety param base on carParams + CP = next((m.carParams for _, m in msgs if m.which() == 'carParams'), None) assert CP is not None, "carParams message not found" - if CP.carFingerprint in safety_param_migration: - safety_param = safety_param_migration[CP.carFingerprint] + fingerprint = MIGRATION.get(CP.carFingerprint, CP.carFingerprint) + if fingerprint in safety_param_migration: + safety_param = safety_param_migration[fingerprint].value elif len(CP.safetyConfigs): safety_param = CP.safetyConfigs[0].safetyParam if CP.safetyConfigs[0].safetyParamDEPRECATED != 0: @@ -136,49 +327,47 @@ def migrate_pandaStates(lr): else: safety_param = CP.safetyParamDEPRECATED - for msg in lr: + ops = [] + for index, msg in msgs: if msg.which() == 'pandaStateDEPRECATED': new_msg = messaging.new_message('pandaStates', 1) new_msg.valid = msg.valid new_msg.logMonoTime = msg.logMonoTime new_msg.pandaStates[0] = msg.pandaStateDEPRECATED new_msg.pandaStates[0].safetyParam = safety_param - all_msgs.append(new_msg.as_reader()) + ops.append((index, as_reader(new_msg))) elif msg.which() == 'pandaStates': new_msg = msg.as_builder() new_msg.pandaStates[-1].safetyParam = safety_param - all_msgs.append(new_msg.as_reader()) - else: - all_msgs.append(msg) + # Clear DISABLE_DISENGAGE_ON_GAS bit to fix controls mismatch + new_msg.pandaStates[-1].alternativeExperience &= ~1 + ops.append((index, as_reader(new_msg))) + return ops, [], [] - return all_msgs +@migration(inputs=["pandaStates", "pandaStateDEPRECATED"], product="peripheralState") +def migrate_peripheralState(msgs): + add_ops = [] -def migrate_peripheralState(lr): - if any(msg.which() == "peripheralState" for msg in lr): - return lr - - all_msg = [] - for msg in lr: - all_msg.append(msg) - if msg.which() not in ["pandaStates", "pandaStateDEPRECATED"]: + which = "pandaStates" if any(msg.which() == "pandaStates" for _, msg in msgs) else "pandaStateDEPRECATED" + for _, msg in msgs: + if msg.which() != which: continue - new_msg = messaging.new_message("peripheralState") new_msg.valid = msg.valid new_msg.logMonoTime = msg.logMonoTime - all_msg.append(new_msg.as_reader()) + add_ops.append(as_reader(new_msg)) + return [], add_ops, [] - return all_msg - -def migrate_cameraStates(lr): - all_msgs = [] +@migration(inputs=["roadEncodeIdx", "wideRoadEncodeIdx", "driverEncodeIdx", "roadCameraState", "wideRoadCameraState", "driverCameraState"]) +def migrate_cameraStates(msgs): + add_ops, del_ops = [], [] frame_to_encode_id = defaultdict(dict) # just for encodeId fallback mechanism min_frame_id = defaultdict(lambda: float('inf')) - for msg in lr: + for _, msg in msgs: if msg.which() not in ["roadEncodeIdx", "wideRoadEncodeIdx", "driverEncodeIdx"]: continue @@ -188,9 +377,8 @@ def migrate_cameraStates(lr): assert encode_index.segmentId < 1200, f"Encoder index segmentId greater that 1200: {msg.which()} {encode_index.segmentId}" frame_to_encode_id[meta.camera_state][encode_index.frameId] = encode_index.segmentId - for msg in lr: + for index, msg in msgs: if msg.which() not in ["roadCameraState", "wideRoadCameraState", "driverCameraState"]: - all_msgs.append(msg) continue camera_state = getattr(msg, msg.which()) @@ -200,6 +388,7 @@ def migrate_cameraStates(lr): if encode_id is None: print(f"Missing encoded frame for camera feed {msg.which()} with frameId: {camera_state.frameId}") if len(frame_to_encode_id[msg.which()]) != 0: + del_ops.append(index) continue # fallback mechanism for logs without encodeIdx (e.g. logs from before 2022 with dcamera recording disabled) @@ -209,6 +398,7 @@ def migrate_cameraStates(lr): new_msg = messaging.new_message(msg.which()) new_camera_state = getattr(new_msg, new_msg.which()) + new_camera_state.sensor = camera_state.sensor new_camera_state.frameId = encode_id new_camera_state.encodeId = encode_id # timestampSof was added later so it might be missing on some old segments @@ -220,34 +410,27 @@ def migrate_cameraStates(lr): new_msg.logMonoTime = msg.logMonoTime new_msg.valid = msg.valid - all_msgs.append(new_msg.as_reader()) - - return all_msgs - + del_ops.append(index) + add_ops.append(as_reader(new_msg)) + return [], add_ops, del_ops -def migrate_carParams(lr, old_logtime=False): - all_msgs = [] - for msg in lr: - if msg.which() == 'carParams': - CP = msg.as_builder() - CP.carParams.carFingerprint = MIGRATION.get(CP.carParams.carFingerprint, CP.carParams.carFingerprint) - for car_fw in CP.carParams.carFw: - car_fw.brand = CP.carParams.carName - if old_logtime: - CP.logMonoTime = msg.logMonoTime - msg = CP.as_reader() - all_msgs.append(msg) - return all_msgs +@migration(inputs=["carParams"]) +def migrate_carParams(msgs): + ops = [] + for index, msg in msgs: + CP = msg.as_builder() + CP.carParams.carFingerprint = MIGRATION.get(CP.carParams.carFingerprint, CP.carParams.carFingerprint) + for car_fw in CP.carParams.carFw: + car_fw.brand = CP.carParams.brand + ops.append((index, as_reader(CP))) + return ops, [], [] -def migrate_sensorEvents(lr, old_logtime=False): - all_msgs = [] - for msg in lr: - if msg.which() != 'sensorEventsDEPRECATED': - all_msgs.append(msg) - continue - +@migration(inputs=["sensorEventsDEPRECATED"], product="sensorEvents") +def migrate_sensorEvents(msgs): + add_ops, del_ops = [], [] + for index, msg in msgs: # migrate to split sensor events for evt in msg.sensorEventsDEPRECATED: # build new message for each sensor type @@ -265,18 +448,76 @@ def migrate_sensorEvents(lr, old_logtime=False): m = messaging.new_message(sensor_service) m.valid = True - if old_logtime: - m.logMonoTime = msg.logMonoTime + m.logMonoTime = msg.logMonoTime m_dat = getattr(m, sensor_service) - m_dat.version = evt.version - m_dat.sensor = evt.sensor - m_dat.type = evt.type m_dat.source = evt.source - if old_logtime: - m_dat.timestamp = evt.timestamp + m_dat.timestamp = evt.timestamp setattr(m_dat, evt.which(), getattr(evt, evt.which())) - all_msgs.append(m.as_reader()) - - return all_msgs + add_ops.append(as_reader(m)) + del_ops.append(index) + return [], add_ops, del_ops + + +@migration(inputs=["onroadEventsDEPRECATED"], product="onroadEvents") +def migrate_onroadEvents(msgs): + ops = [] + for index, msg in msgs: + onroadEvents = [] + for event in msg.onroadEventsDEPRECATED: + try: + if not str(event.name).endswith('DEPRECATED'): + migrated_event = migrate_onroad_event(event) + if migrated_event is not None: + onroadEvents.append(migrated_event) + except RuntimeError: # Member was null + traceback.print_exc() + + new_msg = messaging.new_message('onroadEvents', len(onroadEvents)) + new_msg.valid = msg.valid + new_msg.logMonoTime = msg.logMonoTime + new_msg.onroadEvents = onroadEvents + ops.append((index, as_reader(new_msg))) + + return ops, [], [] + + +@migration(inputs=["driverMonitoringStateDEPRECATED"]) +def migrate_driverMonitoringState(msgs): + ops = [] + for index, msg in msgs: + old = msg.driverMonitoringStateDEPRECATED + new_msg = messaging.new_message('driverMonitoringState', valid=msg.valid, logMonoTime=msg.logMonoTime) + dm = new_msg.driverMonitoringState + dm.isRHD = old.isRHD + dm.activePolicy = log.DriverMonitoringState.MonitoringPolicy.vision if old.isActiveMode else \ + log.DriverMonitoringState.MonitoringPolicy.wheeltouch + + AlertLevel = log.DriverMonitoringState.AlertLevel + event_to_alert_level = { + 'driverDistracted1': AlertLevel.one, 'driverUnresponsive1': AlertLevel.one, + 'driverDistracted2': AlertLevel.two, 'driverUnresponsive2': AlertLevel.two, + 'driverDistracted3': AlertLevel.three, 'driverUnresponsive3': AlertLevel.three, + 'tooDistracted': AlertLevel.three, + } + for event in old.events: + level = event_to_alert_level.get(str(event.name)) + if level is not None: + dm.alertLevel = level + break + + dm.visionPolicyState.awarenessPercent = int(max(0, min(100, (old.awarenessStatus if old.isActiveMode else old.awarenessActive) * 100))) + dm.visionPolicyState.awarenessStep = old.stepChange if old.isActiveMode else 0. + dm.visionPolicyState.isDistracted = old.isDistracted + dm.visionPolicyState.faceDetected = old.faceDetected + dm.visionPolicyState.pose.pitchCalib.offset = old.posePitchOffset + dm.visionPolicyState.pose.pitchCalib.calibratedPercent = int(min(100, old.posePitchValidCount / 600 * 100)) + dm.visionPolicyState.pose.yawCalib.offset = old.poseYawOffset + dm.visionPolicyState.pose.yawCalib.calibratedPercent = int(min(100, old.poseYawValidCount / 600 * 100)) + dm.visionPolicyState.pose.calibrated = old.posePitchValidCount >= 600 and old.poseYawValidCount >= 600 + dm.wheeltouchPolicyState.awarenessPercent = int(max(0, min(100, (old.awarenessPassive if old.isActiveMode else old.awarenessStatus) * 100))) + dm.wheeltouchPolicyState.awarenessStep = 0. if old.isActiveMode else old.stepChange + ops.append((index, as_reader(new_msg))) + + return ops, [], [] diff --git a/selfdrive/test/process_replay/model_replay.py b/selfdrive/test/process_replay/model_replay.py index 4402ca31d6d83d..266f66aaf24856 100755 --- a/selfdrive/test/process_replay/model_replay.py +++ b/selfdrive/test/process_replay/model_replay.py @@ -1,39 +1,140 @@ #!/usr/bin/env python3 import os +import pickle import sys from collections import defaultdict from typing import Any +import tempfile +from itertools import zip_longest + +import matplotlib.pyplot as plt +import numpy as np +from openpilot.common.utils import tabulate from openpilot.common.git import get_commit from openpilot.system.hardware import PC -from openpilot.tools.lib.openpilotci import BASE_URL, get_url +from openpilot.tools.lib.openpilotci import get_url from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs, format_diff from openpilot.selfdrive.test.process_replay.process_replay import get_process_config, replay_process from openpilot.tools.lib.framereader import FrameReader from openpilot.tools.lib.logreader import LogReader, save_log +from openpilot.tools.lib.github_utils import GithubUtils -TEST_ROUTE = "2f4452b03ccb98f0|2022-12-03--13-45-30" -SEGMENT = 6 -MAX_FRAMES = 100 if PC else 600 +TEST_ROUTE = "8494c69d3c710e81|000001d4--2648a9a404" +SEGMENT = 4 +START_FRAME = 0 +END_FRAME = 60 -NO_MODEL = "NO_MODEL" in os.environ SEND_EXTRA_INPUTS = bool(int(os.getenv("SEND_EXTRA_INPUTS", "0"))) +DATA_TOKEN = os.getenv("CI_ARTIFACTS_TOKEN","") +API_TOKEN = os.getenv("GITHUB_COMMENTS_TOKEN","") +MODEL_REPLAY_BUCKET="model_replay_master" +GITHUB = GithubUtils(API_TOKEN, DATA_TOKEN) + +EXEC_TIMINGS = [ + # model, instant max, average max + ("modelV2", 0.05, 0.028), + ("driverStateV2", 0.05, 0.018), +] + +def get_log_fn(test_route, ref="master"): + return f"{test_route}_model_tici_{ref}.zst" + +def plot(proposed, master, title, tmp): + proposed = list(proposed) + master = list(master) + fig, ax = plt.subplots() + ax.plot(master, label='MASTER') + ax.plot(proposed, label='PROPOSED') + plt.legend(loc='best') + plt.title(title) + plt.savefig(f'{tmp}/{title}.png') + return (title + '.png', proposed == master) + +def get_event(logs, event): + return (getattr(m, m.which()) for m in filter(lambda m: m.which() == event, logs)) + +def zl(array, fill): + return zip_longest(array, [], fillvalue=fill) + +def get_idx_if_non_empty(l, idx=None): + return l if idx is None else (l[idx] if len(l) > 0 else None) + +def generate_report(proposed, master, tmp, commit): + ModelV2_Plots = zl([ + (lambda x: get_idx_if_non_empty(x.velocity.x, 0), "velocity.x"), + (lambda x: get_idx_if_non_empty(x.action.desiredCurvature), "desiredCurvature"), + (lambda x: get_idx_if_non_empty(x.action.desiredAcceleration), "desiredAcceleration"), + (lambda x: get_idx_if_non_empty(x.leadsV3[0].x, 0), "leadsV3.x"), + (lambda x: get_idx_if_non_empty(x.laneLines[1].y, 0), "laneLines.y"), + (lambda x: get_idx_if_non_empty(x.meta.desireState, 3), "desireState.laneChangeLeft"), + (lambda x: get_idx_if_non_empty(x.meta.desireState, 4), "desireState.laneChangeRight"), + (lambda x: get_idx_if_non_empty(x.meta.disengagePredictions.gasPressProbs, 1), "gasPressProbs") + ], "modelV2") + DriverStateV2_Plots = zl([ + (lambda x: get_idx_if_non_empty(x.wheelOnRightProb), "wheelOnRightProb"), + (lambda x: get_idx_if_non_empty(x.leftDriverData.faceProb), "leftDriverData.faceProb"), + (lambda x: get_idx_if_non_empty(x.leftDriverData.faceOrientation, 0), "leftDriverData.faceOrientation0"), + (lambda x: get_idx_if_non_empty(x.leftDriverData.leftBlinkProb), "leftDriverData.leftBlinkProb"), + (lambda x: get_idx_if_non_empty(x.leftDriverData.phoneProb), "leftDriverData.phoneProb"), + (lambda x: get_idx_if_non_empty(x.rightDriverData.faceProb), "rightDriverData.faceProb"), + ], "driverStateV2") + + return [plot(map(v[0], get_event(proposed, event)), \ + map(v[0], get_event(master, event)), f"{v[1]}_{commit[:7]}", tmp) \ + for v,event in ([*ModelV2_Plots] + [*DriverStateV2_Plots])] -def get_log_fn(ref_commit, test_route): - return f"{test_route}_model_tici_{ref_commit}.bz2" +def create_table(title, files, link, open_table=False): + if not files: + return "" + table = [f'
{title}'] + for i,f in enumerate(files): + if not (i % 2): + table.append("") + table.append(f'') + if (i % 2): + table.append("") + table.append("
") + table = "".join(table) + return table +def comment_replay_report(proposed, master, full_logs): + with tempfile.TemporaryDirectory() as tmp: + PR_BRANCH = os.getenv("GIT_BRANCH","") + DATA_BUCKET = f"model_replay_{PR_BRANCH}" -def trim_logs_to_max_frames(logs, max_frames, frs_types, include_all_types): + try: + GITHUB.get_pr_number(PR_BRANCH) + except Exception: + print("No PR associated with this branch. Skipping report.") + return + + commit = get_commit() + files = generate_report(proposed, master, tmp, commit) + + GITHUB.upload_files(DATA_BUCKET, [(x[0], tmp + '/' + x[0]) for x in files]) + + log_name = get_log_fn(TEST_ROUTE, commit) + save_log(log_name, full_logs) + GITHUB.upload_file(DATA_BUCKET, os.path.basename(log_name), log_name) + + diff_files = [x for x in files if not x[1]] + link = GITHUB.get_bucket_link(DATA_BUCKET) + diff_plots = create_table("Model Replay Differences", diff_files, link, open_table=True) + all_plots = create_table("All Model Replay Plots", files, link) + comment = f"ref for commit {commit}: {link}/{log_name}" + diff_plots + all_plots + GITHUB.comment_on_pr(comment, PR_BRANCH, "commaci-public", True) + +def trim_logs(logs, start_frame, end_frame, frs_types, include_all_types): all_msgs = [] cam_state_counts = defaultdict(int) - # keep adding messages until cam states are equal to MAX_FRAMES for msg in sorted(logs, key=lambda m: m.logMonoTime): - all_msgs.append(msg) if msg.which() in frs_types: cam_state_counts[msg.which()] += 1 - - if all(cam_state_counts[state] == max_frames for state in frs_types): + if any(cam_state_counts[state] >= start_frame for state in frs_types): + all_msgs.append(msg) + if all(cam_state_counts[state] == end_frame for state in frs_types): break if len(include_all_types) != 0: @@ -45,8 +146,9 @@ def trim_logs_to_max_frames(logs, max_frames, frs_types, include_all_types): def model_replay(lr, frs): # modeld is using frame pairs - modeld_logs = trim_logs_to_max_frames(lr, MAX_FRAMES, {"roadCameraState", "wideRoadCameraState"}, {"roadEncodeIdx", "wideRoadEncodeIdx", "carParams"}) - dmodeld_logs = trim_logs_to_max_frames(lr, MAX_FRAMES, {"driverCameraState"}, {"driverEncodeIdx", "carParams"}) + modeld_logs = trim_logs(lr, START_FRAME, END_FRAME, {"roadCameraState", "wideRoadCameraState"}, + {"roadEncodeIdx", "wideRoadEncodeIdx", "carParams", "carState", "carControl", "can"}) + dmodeld_logs = trim_logs(lr, START_FRAME, END_FRAME, {"driverCameraState"}, {"driverEncodeIdx", "carParams", "can"}) if not SEND_EXTRA_INPUTS: modeld_logs = [msg for msg in modeld_logs if msg.which() != 'liveCalibration'] @@ -64,69 +166,124 @@ def model_replay(lr, frs): modeld_msgs = replay_process(modeld, modeld_logs, frs) dmonitoringmodeld_msgs = replay_process(dmonitoringmodeld, dmodeld_logs, frs) - return modeld_msgs + dmonitoringmodeld_msgs + msgs = modeld_msgs + dmonitoringmodeld_msgs + + header = ['model', 'max instant', 'max instant allowed', 'average', 'max average allowed', 'test result'] + rows = [] + timings_ok = True + for (s, instant_max, avg_max) in EXEC_TIMINGS: + ts = [getattr(m, s).modelExecutionTime for m in msgs if m.which() == s] + # TODO some init can happen in first iteration + ts = ts[1:] + + errors = [] + if np.max(ts) > instant_max: + errors.append("❌ FAILED MAX TIMING CHECK ❌") + if np.mean(ts) > avg_max: + errors.append("❌ FAILED AVG TIMING CHECK ❌") + + timings_ok = not errors and timings_ok + rows.append([s, np.max(ts), instant_max, np.mean(ts), avg_max, "\n".join(errors) or "✅"]) + + print("------------------------------------------------") + print("----------------- Model Timing -----------------") + print("------------------------------------------------") + print(tabulate(rows, header, tablefmt="simple_grid", stralign="center", numalign="center", floatfmt=".4f")) + assert timings_ok or PC + + return msgs + + +def get_frames(): + regen_cache = "--regen-cache" in sys.argv + frames_cache = '/tmp/model_replay_cache' if PC else '/data/model_replay_cache' + os.makedirs(frames_cache, exist_ok=True) + + cache_name = f'{frames_cache}/{TEST_ROUTE}_{SEGMENT}_{START_FRAME}_{END_FRAME}.pkl' + if os.path.isfile(cache_name) and not regen_cache: + try: + print(f"Loading frames from cache {cache_name}") + return pickle.load(open(cache_name, "rb")) + except Exception as e: + print(f"Failed to load frames from cache {cache_name}: {e}") + + frs = { + 'roadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, "fcamera.hevc"), pix_fmt='nv12', cache_size=END_FRAME - START_FRAME), + 'driverCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, "dcamera.hevc"), pix_fmt='nv12', cache_size=END_FRAME - START_FRAME), + 'wideRoadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, "ecamera.hevc"), pix_fmt='nv12', cache_size=END_FRAME - START_FRAME), + } + for fr in frs.values(): + for fidx in range(START_FRAME, END_FRAME): + fr.get(fidx) + fr.it = None + print(f"Dumping frame cache {cache_name}") + pickle.dump(frs, open(cache_name, "wb")) + return frs if __name__ == "__main__": - update = "--update" in sys.argv + update = "--update" in sys.argv or (os.getenv("GIT_BRANCH", "") == 'master') replay_dir = os.path.dirname(os.path.abspath(__file__)) - ref_commit_fn = os.path.join(replay_dir, "model_replay_ref_commit") # load logs - lr = list(LogReader(get_url(TEST_ROUTE, SEGMENT, "rlog.bz2"))) - frs = { - 'roadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, "fcamera.hevc"), readahead=True), - 'driverCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, "dcamera.hevc"), readahead=True), - 'wideRoadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, "ecamera.hevc"), readahead=True) - } + lr = list(LogReader(get_url(TEST_ROUTE, SEGMENT, "rlog.zst"))) + frs = get_frames() log_msgs = [] # run replays - if not NO_MODEL: - log_msgs += model_replay(lr, frs) + log_msgs += model_replay(lr, frs) # get diff failed = False if not update: - with open(ref_commit_fn) as f: - ref_commit = f.read().strip() - log_fn = get_log_fn(ref_commit, TEST_ROUTE) + log_fn = get_log_fn(TEST_ROUTE) try: - all_logs = list(LogReader(BASE_URL + log_fn)) + all_logs = list(LogReader(GITHUB.get_file_url(MODEL_REPLAY_BUCKET, log_fn))) cmp_log = [] - - # logs are ordered based on type: modelV2, drivingModelData, driverStateV2 - if not NO_MODEL: - model_start_index = next(i for i, m in enumerate(all_logs) if m.which() in ("modelV2", "drivingModelData", "cameraOdometry")) - cmp_log += all_logs[model_start_index:model_start_index + MAX_FRAMES*3] - dmon_start_index = next(i for i, m in enumerate(all_logs) if m.which() == "driverStateV2") - cmp_log += all_logs[dmon_start_index:dmon_start_index + MAX_FRAMES] + model_start_index = next(i for i, m in enumerate(all_logs) if m.which() in ("modelV2", "drivingModelData", "cameraOdometry")) + cmp_log += all_logs[model_start_index+START_FRAME*3:model_start_index + END_FRAME*3] + dmon_start_index = next(i for i, m in enumerate(all_logs) if m.which() == "driverStateV2") + cmp_log += all_logs[dmon_start_index+START_FRAME:dmon_start_index + END_FRAME] ignore = [ 'logMonoTime', 'drivingModelData.frameDropPerc', + 'drivingModelData.modelExecutionTime', 'modelV2.frameDropPerc', 'modelV2.modelExecutionTime', 'driverStateV2.modelExecutionTime', - 'driverStateV2.dspExecutionTime' + 'driverStateV2.gpuExecutionTime' ] if PC: - ignore += [ - 'modelV2.laneLines.0.t', - 'modelV2.laneLines.1.t', - 'modelV2.laneLines.2.t', - 'modelV2.laneLines.3.t', - 'modelV2.roadEdges.0.t', - 'modelV2.roadEdges.1.t', - ] - # TODO this tolerance is absurdly large - tolerance = 2.0 if PC else None + # TODO We ignore whole bunch so we can compare important stuff + # like posenet with reasonable tolerance + ignore += ['modelV2.acceleration.x', + 'modelV2.position.x', + 'modelV2.position.xStd', + 'modelV2.position.y', + 'modelV2.position.yStd', + 'modelV2.position.z', + 'modelV2.position.zStd', + 'drivingModelData.path.xCoefficients',] + for i in range(3): + for field in ('x', 'y', 'v', 'a'): + ignore.append(f'modelV2.leadsV3.{i}.{field}') + ignore.append(f'modelV2.leadsV3.{i}.{field}Std') + for i in range(4): + for field in ('x', 'y', 'z', 't'): + ignore.append(f'modelV2.laneLines.{i}.{field}') + for i in range(2): + for field in ('x', 'y', 'z', 't'): + ignore.append(f'modelV2.roadEdges.{i}.{field}') + tolerance = .3 if PC else None results: Any = {TEST_ROUTE: {}} - log_paths: Any = {TEST_ROUTE: {"models": {'ref': BASE_URL + log_fn, 'new': log_fn}}} + log_paths: Any = {TEST_ROUTE: {"models": {'ref': log_fn, 'new': log_fn}}} results[TEST_ROUTE]["models"] = compare_logs(cmp_log, log_msgs, tolerance=tolerance, ignore_fields=ignore) - diff_short, diff_long, failed = format_diff(results, log_paths, ref_commit) + diff_short, diff_long, failed = format_diff(results, log_paths, 'master') if "CI" in os.environ: + comment_replay_report(log_msgs, cmp_log, log_msgs) + failed = False print(diff_long) print('-------------\n'*5) print(diff_short) @@ -137,22 +294,13 @@ def model_replay(lr, frs): failed = True # upload new refs - if (update or failed) and not PC: - from openpilot.tools.lib.openpilotci import upload_file - + if update and not PC: print("Uploading new refs") - - new_commit = get_commit() - log_fn = get_log_fn(new_commit, TEST_ROUTE) + log_fn = get_log_fn(TEST_ROUTE) save_log(log_fn, log_msgs) try: - upload_file(log_fn, os.path.basename(log_fn)) + GITHUB.upload_file(MODEL_REPLAY_BUCKET, os.path.basename(log_fn), log_fn) except Exception as e: print("failed to upload", e) - with open(ref_commit_fn, 'w') as f: - f.write(str(new_commit)) - - print("\n\nNew ref commit: ", new_commit) - sys.exit(int(failed)) diff --git a/selfdrive/test/process_replay/model_replay_ref_commit b/selfdrive/test/process_replay/model_replay_ref_commit deleted file mode 100644 index 237713622b9d1a..00000000000000 --- a/selfdrive/test/process_replay/model_replay_ref_commit +++ /dev/null @@ -1 +0,0 @@ -8726813f978d6baf519055f3105350cd071741f3 \ No newline at end of file diff --git a/selfdrive/test/process_replay/nap_fixture_policy.json b/selfdrive/test/process_replay/nap_fixture_policy.json new file mode 100644 index 00000000000000..6d5360d41dcdfa --- /dev/null +++ b/selfdrive/test/process_replay/nap_fixture_policy.json @@ -0,0 +1,472 @@ +{ + "schema_version": 1, + "allowed_services": { + "can": [ + "[].address", + "[].dat", + "[].src" + ], + "carParams": [ + "brand", + "carFingerprint", + "fuzzyFingerprint", + "pcmCruise", + "enableDsu", + "enableBsm", + "flags", + "alphaLongitudinalAvailable", + "minEnableSpeed", + "minSteerSpeed", + "steerAtStandstill", + "safetyConfigs[].safetyModel", + "safetyConfigs[].safetyParam", + "alternativeExperience", + "mass", + "wheelbase", + "centerToFront", + "steerRatio", + "steerRatioRear", + "rotationalInertia", + "tireStiffnessFactor", + "tireStiffnessFront", + "tireStiffnessRear", + "steerLimitAlert", + "steerLimitTimer", + "vEgoStopping", + "vEgoStarting", + "steerControlType", + "radarUnavailable", + "stopAccel", + "stoppingDecelRate", + "startAccel", + "startingState", + "steerActuatorDelay", + "longitudinalActuatorDelay", + "openpilotLongitudinalControl", + "carVin", + "dashcamOnly", + "passive", + "notCar", + "transmissionType", + "radarDelay", + "fingerprintSource", + "networkLocation", + "wheelSpeedFactor", + "secOcRequired", + "secOcKeyAvailable", + "maxLateralAccel", + "autoResumeSng" + ], + "carState": [ + "canValid", + "canTimeout", + "canErrorCounter", + "vEgo", + "vEgoRaw", + "aEgo", + "standstill", + "gasPressed", + "brake", + "brakePressed", + "steeringAngleDeg", + "steeringRateDeg", + "steeringTorque", + "steeringPressed", + "steeringDisengage", + "cruiseState.enabled", + "cruiseState.available", + "cruiseState.speed", + "cruiseState.standstill", + "cruiseState.nonAdaptive", + "gearShifter", + "buttonEvents[].type", + "buttonEvents[].pressed", + "wheelSpeeds.fl", + "wheelSpeeds.fr", + "wheelSpeeds.rl", + "wheelSpeeds.rr", + "vCruise", + "vCruiseCluster", + "leftBlinker", + "rightBlinker", + "doorOpen", + "seatbeltUnlatched", + "espDisabled", + "espActive", + "stockFcw", + "stockAeb", + "stockLkas", + "brakeHoldActive", + "parkingBrake", + "accFaulted", + "vehicleSensorsInvalid", + "invalidLkasSetting", + "lowSpeedAlert", + "buttonEnable", + "steerFaultTemporary", + "steerFaultPermanent", + "blockPcmEnable", + "regenBraking", + "pedalLongActive", + "enableLongControl", + "pedalMaxRegen", + "leftBlindspot", + "rightBlindspot", + "teslaCCEngaged", + "teslaCCDisengaged", + "teslaCCNotArmed", + "pedalAuthorityFailed" + ], + "carControl": [ + "enabled", + "latActive", + "longActive", + "actuators.gas", + "actuators.brake", + "actuators.torque", + "actuators.steeringAngleDeg", + "actuators.accel", + "orientationNED[]", + "cruiseControl.cancel", + "leftBlinker", + "rightBlinker" + ], + "carOutput": [ + "actuatorsOutput.steeringAngleDeg", + "actuatorsOutput.torque", + "actuatorsOutput.accel" + ], + "controlsState": [ + "longControlState", + "forceDecel", + "desiredCurvature", + "curvature", + "longitudinalPlanMonoTime", + "lateralPlanMonoTime", + "lateralControlState.pidState.saturated", + "lateralControlState.pidState.active", + "lateralControlState.angleState.saturated", + "lateralControlState.angleState.active", + "lateralControlState.debugState.saturated", + "lateralControlState.debugState.active", + "lateralControlState.torqueState.saturated", + "lateralControlState.torqueState.active" + ], + "selfdriveState": [ + "enabled", + "active", + "engageable", + "state", + "personality", + "experimentalMode", + "alertHudVisual", + "alertStatus", + "alertSize" + ], + "liveCalibration": [ + "calStatus", + "calCycle", + "calPerc", + "rpyCalib[]", + "height[]", + "wideFromDeviceEuler[]" + ], + "liveParameters": [ + "valid", + "gyroBias", + "angleOffsetDeg", + "angleOffsetAverageDeg", + "stiffnessFactor", + "steerRatio", + "roll", + "posenetValid", + "angleOffsetValid", + "steerRatioValid", + "stiffnessFactorValid" + ], + "liveTorqueParameters": [ + "useParams", + "latAccelFactorFiltered", + "latAccelOffsetFiltered", + "frictionCoefficientFiltered" + ], + "liveDelay": [ + "lateralDelay" + ], + "longitudinalPlan": [ + "aTarget", + "shouldStop", + "hasLead", + "fcw", + "modelMonoTime" + ], + "radarState": [ + "mdMonoTime", + "carStateMonoTime", + "leadOne.status", + "leadOne.dRel", + "leadOne.vLead", + "leadOne.aLeadK", + "leadOne.aLeadTau", + "leadOne.modelProb", + "leadTwo.status", + "leadTwo.dRel", + "leadTwo.vLead", + "leadTwo.aLeadK", + "leadTwo.aLeadTau", + "radarErrors.canError", + "radarErrors.radarFault", + "radarErrors.wrongConfig", + "radarErrors.radarUnavailableTemporary" + ], + "liveTracks": [ + "points[].trackId", + "points[].dRel", + "points[].yRel", + "points[].vRel", + "points[].measured", + "errors.canError", + "errors.radarFault", + "errors.wrongConfig", + "errors.radarUnavailableTemporary" + ], + "modelV2": [ + "frameId", + "frameDropPerc", + "modelExecutionTime", + "position.x[]", + "velocity.x[]", + "acceleration.x[]", + "orientation.x[]", + "orientation.y[]", + "orientation.z[]", + "meta.laneChangeState", + "meta.laneChangeDirection", + "meta.hardBrakePredicted", + "meta.desirePrediction[]", + "meta.disengagePredictions.gasPressProbs[]", + "action.desiredCurvature", + "action.desiredAcceleration", + "action.shouldStop", + "laneLineProbs[]", + "laneLines[].y[]", + "leadsV3[].prob", + "leadsV3[].x[]", + "leadsV3[].xStd[]", + "leadsV3[].y[]", + "leadsV3[].yStd[]", + "leadsV3[].v[]", + "leadsV3[].vStd[]", + "leadsV3[].a[]" + ], + "driverMonitoringState": [ + "awarenessStatus", + "isActiveMode", + "isRHD", + "events[].name", + "events[].enable", + "events[].noEntry", + "events[].warning", + "events[].userDisable", + "events[].softDisable", + "events[].immediateDisable", + "events[].preEnable", + "events[].permanent", + "events[].overrideLongitudinal", + "events[].overrideLateral" + ], + "driverAssistance": [ + "leftLaneDeparture", + "rightLaneDeparture" + ], + "livePose": [ + "posenetOK", + "inputsOK", + "sensorsOK", + "orientationNED.x", + "orientationNED.y", + "orientationNED.z", + "orientationNED.xStd", + "orientationNED.yStd", + "orientationNED.zStd", + "velocityDevice.x", + "velocityDevice.y", + "velocityDevice.z", + "velocityDevice.xStd", + "velocityDevice.yStd", + "velocityDevice.zStd", + "accelerationDevice.x", + "accelerationDevice.y", + "accelerationDevice.z", + "accelerationDevice.xStd", + "accelerationDevice.yStd", + "accelerationDevice.zStd", + "angularVelocityDevice.x", + "angularVelocityDevice.y", + "angularVelocityDevice.z", + "angularVelocityDevice.xStd", + "angularVelocityDevice.yStd", + "angularVelocityDevice.zStd", + "angularVelocityDevice.valid" + ], + "onroadEvents": [ + "[].name", + "[].enable", + "[].noEntry", + "[].warning", + "[].userDisable", + "[].softDisable", + "[].immediateDisable", + "[].preEnable", + "[].permanent", + "[].overrideLongitudinal", + "[].overrideLateral" + ], + "pandaStates": [ + "[].pandaType", + "[].ignitionLine", + "[].controlsAllowed", + "[].faultStatus", + "[].safetyModel", + "[].safetyParam", + "[].alternativeExperience", + "[].faults[]", + "[].safetyRxChecksInvalid" + ], + "peripheralState": [ + "pandaType", + "voltage", + "current", + "fanSpeedRpm" + ], + "deviceState": [ + "freeSpacePercent", + "memoryUsagePercent", + "cpuUsagePercent[]", + "fanSpeedPercentDesired", + "started", + "thermalStatus", + "cpuTempC[]", + "gpuTempC[]", + "memoryTempC", + "maxTempC" + ], + "gpsLocation": [], + "accelerometer": [], + "gyroscope": [] + }, + "forbidden_services": [ + "clocks", + "initData", + "boot", + "sentinel", + "roadCameraState", + "driverCameraState", + "wideRoadCameraState", + "logMessage", + "errorLogMessage", + "androidLog", + "procLog", + "roadEncodeIdx", + "driverEncodeIdx", + "wideRoadEncodeIdx", + "qRoadEncodeIdx", + "livestreamRoadEncodeIdx", + "livestreamWideRoadEncodeIdx", + "livestreamDriverEncodeIdx", + "roadEncodeData", + "driverEncodeData", + "wideRoadEncodeData", + "qRoadEncodeData", + "livestreamRoadEncodeData", + "livestreamWideRoadEncodeData", + "livestreamDriverEncodeData", + "touch", + "qcomGnss", + "ubloxRaw", + "ubloxGnss", + "gnssMeasurements", + "gpsNMEA", + "uiDebug", + "navInstruction", + "navRoute", + "navThumbnail", + "mapRenderState", + "thumbnail", + "managerState", + "uploaderState", + "rawAudioData", + "soundPressure", + "audioFeedback", + "sendcan", + "alertDebug", + "userBookmark", + "bookmarkButton", + "gpsLocationExternal" + ], + "required_services": { + "can": 1, + "carParams": 1, + "carState": 1, + "carControl": 1, + "carOutput": 1, + "controlsState": 1, + "selfdriveState": 1, + "modelV2": 1, + "livePose": 1, + "liveCalibration": 1, + "liveParameters": 1, + "liveTorqueParameters": 1, + "liveDelay": 1, + "liveTracks": 1, + "radarState": 1, + "longitudinalPlan": 1, + "pandaStates": 1, + "peripheralState": 1, + "deviceState": 1, + "onroadEvents": 1, + "driverMonitoringState": 1, + "driverAssistance": 1, + "accelerometer": 1, + "gyroscope": 1, + "gpsLocation": 1 + }, + "selected_gps_service": "gpsLocation", + "freshness_services": [ + "accelerometer", + "gyroscope", + "gpsLocation" + ], + "pedal": { + "address": 1362, + "bus": 2, + "data_length": 6, + "counter_index": 4, + "counter_mask": 15, + "checksum_index": 5, + "checksum": "tesla_sum8_address", + "minimum_frames": 10, + "minimum_counters": 8 + }, + "sensitive_zero_fields": [ + "gpsLocation.latitude", + "gpsLocation.longitude", + "gpsLocation.altitude", + "gpsLocation.bearingDeg", + "gpsLocation.unixTimestampMillis", + "gpsLocation.vNED[]" + ], + "placeholder_vin": "00000000000000000", + "cases": { + "nap-preap-pedal-v1": { + "mode": "pedal", + "fingerprint": "TESLA_MODEL_S_PREAP", + "safety_param": 7 + }, + "nap-preap-no-pedal-v1": { + "mode": "no-pedal", + "fingerprint": "TESLA_MODEL_S_PREAP", + "safety_param": 6 + } + } +} diff --git a/selfdrive/test/process_replay/process_replay.py b/selfdrive/test/process_replay/process_replay.py index 5e4e1d3ffb2ac2..8bedfad11862d8 100755 --- a/selfdrive/test/process_replay/process_replay.py +++ b/selfdrive/test/process_replay/process_replay.py @@ -2,53 +2,41 @@ import os import time import copy -import json import heapq import signal -import platform -from collections import Counter, OrderedDict +import numpy as np +from collections import Counter from dataclasses import dataclass, field +from itertools import islice from typing import Any from collections.abc import Callable, Iterable from tqdm import tqdm import capnp +from openpilot.system.hardware.hw import Paths import cereal.messaging as messaging from cereal import car from cereal.services import SERVICE_LIST from msgq.visionipc import VisionIpcServer, get_endpoint_name as vipc_get_endpoint_name -from opendbc.car import structs +from opendbc.car.can_definitions import CanData from opendbc.car.car_helpers import get_car, interfaces from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix from openpilot.common.timeout import Timeout from openpilot.common.realtime import DT_CTRL -from panda.python import ALTERNATIVE_EXPERIENCE -from openpilot.selfdrive.car.card import can_comm_callbacks, convert_to_capnp +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info from openpilot.system.manager.process_config import managed_processes from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state, available_streams from openpilot.selfdrive.test.process_replay.migration import migrate_all from openpilot.selfdrive.test.process_replay.capture import ProcessOutputCapture from openpilot.tools.lib.logreader import LogIterable -from openpilot.tools.lib.framereader import BaseFrameReader +from openpilot.tools.lib.framereader import FrameReader # Numpy gives different results based on CPU features after version 19 -NUMPY_TOLERANCE = 1e-7 +NUMPY_TOLERANCE = 1e-2 PROC_REPLAY_DIR = os.path.dirname(os.path.abspath(__file__)) FAKEDATA = os.path.join(PROC_REPLAY_DIR, "fakedata/") -class DummySocket: - def __init__(self): - self.data: list[bytes] = [] - - def receive(self, non_blocking: bool = False) -> bytes | None: - if non_blocking: - return None - - return self.data.pop() - - def send(self, data: bytes): - self.data.append(data) class LauncherWithCapture: def __init__(self, capture: ProcessOutputCapture, launcher: Callable): @@ -66,8 +54,7 @@ def __init__(self, cfg): self.pubs = cfg.pubs self.main_pub = cfg.main_pub self.main_pub_drained = cfg.main_pub_drained - self.unlocked_pubs = cfg.unlocked_pubs - assert(len(self.pubs) != 0 or self.main_pub is not None) + assert len(self.pubs) != 0 or self.main_pub is not None def __enter__(self): self.open_context() @@ -82,9 +69,8 @@ def open_context(self): messaging.set_fake_prefix(self.proc_name) if self.main_pub is None: - self.events = OrderedDict() - pubs_with_events = [pub for pub in self.pubs if pub not in self.unlocked_pubs] - for pub in pubs_with_events: + self.events = {} + for pub in self.pubs: self.events[pub] = messaging.fake_event_handle(pub, enable=True) else: self.events = {self.main_pub: messaging.fake_event_handle(self.main_pub, enable=True)} @@ -141,19 +127,25 @@ class ProcessConfig: processing_time: float = 0.001 timeout: int = 30 simulation: bool = True + # Set to service process receives on first main_pub: str | None = None - main_pub_drained: bool = True + main_pub_drained: bool = False vision_pubs: list[str] = field(default_factory=list) ignore_alive_pubs: list[str] = field(default_factory=list) - unlocked_pubs: list[str] = field(default_factory=list) + + def __post_init__(self): + # If the process is polling a service, we can just lock that one to speed up replay + if self.main_pub is None and isinstance(self.should_recv_callback, MessageBasedRcvCallback): + self.main_pub = self.should_recv_callback.trigger_msg_type class ProcessContainer: def __init__(self, cfg: ProcessConfig): - self.prefix = OpenpilotPrefix(clean_dirs_on_exit=False) + self.prefix = OpenpilotPrefix(create_dirs_on_enter=False, clean_dirs_on_exit=False) self.cfg = copy.deepcopy(cfg) self.process = copy.deepcopy(managed_processes[cfg.proc_name]) self.msg_queue: list[capnp._DynamicStructReader] = [] + self.last_input_log_mono_time: int = -1 self.cnt = 0 self.pm: messaging.PubMaster | None = None self.sockets: list[messaging.SubSocket] | None = None @@ -199,9 +191,9 @@ def _setup_env(self, params_config: dict[str, Any], environ_config: dict[str, An params = Params() for k, v in params_config.items(): if isinstance(v, bool): - params.put_bool(k, v) + params.put_bool(k, v, block=True) else: - params.put(k, v) + params.put(k, v, block=True) self.environ_config = environ_config @@ -212,8 +204,10 @@ def _setup_vision_ipc(self, all_msgs: LogIterable, frs: dict[str, Any]): streams_metas = available_streams(all_msgs) for meta in streams_metas: if meta.camera_state in self.cfg.vision_pubs: + assert frs[meta.camera_state].pix_fmt == 'nv12' frame_size = (frs[meta.camera_state].w, frs[meta.camera_state].h) - vipc_server.create_buffers(meta.stream, 2, False, *frame_size) + stride, y_height, _, yuv_size = get_nv12_info(frame_size[0], frame_size[1]) + vipc_server.create_buffers_with_sizes(meta.stream, 2, frame_size[0], frame_size[1], yuv_size, stride, stride * y_height) vipc_server.start_listener() self.vipc_server = vipc_server @@ -227,10 +221,11 @@ def _start_process(self): def start( self, params_config: dict[str, Any], environ_config: dict[str, Any], - all_msgs: LogIterable, frs: dict[str, BaseFrameReader] | None, + all_msgs: LogIterable, frs: dict[str, FrameReader] | None, fingerprint: str | None, capture_output: bool ): with self.prefix as p: + self.prefix.create_dirs() self._setup_env(params_config, environ_config) if self.cfg.config_callback is not None: @@ -256,11 +251,6 @@ def start( if self.cfg.init_callback is not None: self.cfg.init_callback(self.rc, self.pm, all_msgs, fingerprint) - # wait for process to startup - with Timeout(10, error_msg=f"timed out waiting for process to start: {repr(self.cfg.proc_name)}"): - while not all(self.pm.all_readers_updated(s) for s in self.cfg.pubs if s not in self.cfg.ignore_alive_pubs): - time.sleep(0) - def stop(self): with self.prefix: self.process.signal(signal.SIGKILL) @@ -269,50 +259,70 @@ def stop(self): self.prefix.clean_dirs() self._clean_env() - def run_step(self, msg: capnp._DynamicStructReader, frs: dict[str, BaseFrameReader] | None) -> list[capnp._DynamicStructReader]: - assert self.rc and self.pm and self.sockets and self.process.proc + def get_output_msgs(self, start_time: int): + assert self.rc and self.sockets output_msgs = [] - with self.prefix, Timeout(self.cfg.timeout, error_msg=f"timed out testing process {repr(self.cfg.proc_name)}"): - end_of_cycle = True - if self.cfg.should_recv_callback is not None: - end_of_cycle = self.cfg.should_recv_callback(msg, self.cfg, self.cnt) + self.rc.wait_for_recv_called() + for socket in self.sockets: + ms = messaging.drain_sock(socket) + for m in ms: + m = m.as_builder() + assert start_time > 0, "start_time must be positive" + m.logMonoTime = start_time + int(self.cfg.processing_time * 1e9) + output_msgs.append(m.as_reader()) + return output_msgs + + def run_step(self, msg: capnp._DynamicStructReader, frs: dict[str, FrameReader] | None) -> list[capnp._DynamicStructReader]: + assert self.rc and self.pm and self.sockets and self.process.proc - self.msg_queue.append(msg) - if end_of_cycle: - self.rc.wait_for_recv_called() + output_msgs = [] + end_of_cycle = True + if self.cfg.should_recv_callback is not None: + end_of_cycle = self.cfg.should_recv_callback(msg, self.cfg, self.cnt) + self.msg_queue.append(msg) + if end_of_cycle: + with self.prefix, Timeout(self.cfg.timeout, error_msg=f"timed out testing process {repr(self.cfg.proc_name)}"): # call recv to let sub-sockets reconnect, after we know the process is ready if self.cnt == 0: for s in self.sockets: messaging.recv_one_or_none(s) - # empty recv on drained pub indicates the end of messages, only do that if there're any + # certain processes use drain_sock. need to cause empty recv to break from this loop trigger_empty_recv = False if self.cfg.main_pub and self.cfg.main_pub_drained: - trigger_empty_recv = next((True for m in self.msg_queue if m.which() == self.cfg.main_pub), False) + trigger_empty_recv = any(m.which() == self.cfg.main_pub for m in self.msg_queue) + + # get output msgs from previous inputs + output_msgs = self.get_output_msgs(self.last_input_log_mono_time) for m in self.msg_queue: self.pm.send(m.which(), m.as_builder()) + self.last_input_log_mono_time = max(self.last_input_log_mono_time, m.logMonoTime) # send frames if needed if self.vipc_server is not None and m.which() in self.cfg.vision_pubs: camera_state = getattr(m, m.which()) camera_meta = meta_from_camera_state(m.which()) assert frs is not None - img = frs[m.which()].get(camera_state.frameId, pix_fmt="nv12")[0] - self.vipc_server.send(camera_meta.stream, img.flatten().tobytes(), + img = frs[m.which()].get(camera_state.frameId) + + h, w = frs[m.which()].h, frs[m.which()].w + stride, y_height, _, yuv_size = get_nv12_info(w, h) + uv_offset = stride * y_height + padded_img = np.zeros(((uv_offset //stride) + (h // 2), stride)) + padded_img[:h, :w] = img[:h * w].reshape((-1, w)) + padded_img[uv_offset // stride:uv_offset // stride + h // 2, :w] = img[h * w:].reshape((-1, w)) + img_bytes = np.zeros((yuv_size,), dtype=np.uint8) + img_bytes[:padded_img.size] = padded_img.flatten() + + self.vipc_server.send(camera_meta.stream, img_bytes.tobytes(), camera_state.frameId, camera_state.timestampSof, camera_state.timestampEof) self.msg_queue = [] self.rc.unlock_sockets() - self.rc.wait_for_next_recv(trigger_empty_recv) - - for socket in self.sockets: - ms = messaging.drain_sock(socket) - for m in ms: - m = m.as_builder() - m.logMonoTime = msg.logMonoTime + int(self.cfg.processing_time * 1e9) - output_msgs.append(m.as_reader()) + if trigger_empty_recv: + self.rc.unlock_sockets() self.cnt += 1 assert self.process.proc.is_alive() @@ -322,7 +332,7 @@ def run_step(self, msg: capnp._DynamicStructReader, frs: dict[str, BaseFrameRead def card_fingerprint_callback(rc, pm, msgs, fingerprint): print("start fingerprinting") params = Params() - canmsgs = [msg for msg in msgs if msg.which() == "can"][:300] + canmsgs = list(islice((m for m in msgs if m.which() == "can"), 300)) # card expects one arbitrary can and pandaState rc.send_sync(pm, "can", messaging.new_message("can", 1)) @@ -343,38 +353,26 @@ def card_fingerprint_callback(rc, pm, msgs, fingerprint): def get_car_params_callback(rc, pm, msgs, fingerprint): params = Params() if fingerprint: - CarInterface, _, _, _ = interfaces[fingerprint] + CarInterface = interfaces[fingerprint] CP = CarInterface.get_non_essential_params(fingerprint) else: - can = DummySocket() - sendcan = DummySocket() - - canmsgs = [msg for msg in msgs if msg.which() == "can"] + can_msgs = ([CanData(can.address, can.dat, can.src) for can in m.can] for m in msgs if m.which() == "can") cached_params_raw = params.get("CarParamsCache") - has_cached_cp = cached_params_raw is not None - assert len(canmsgs) != 0, "CAN messages are required for fingerprinting" - assert os.environ.get("SKIP_FW_QUERY", False) or has_cached_cp, \ + assert next(can_msgs, None), "CAN messages are required for fingerprinting" + assert os.environ.get("SKIP_FW_QUERY", False) or cached_params_raw is not None, \ "CarParamsCache is required for fingerprinting. Make sure to keep carParams msgs in the logs." - for m in canmsgs[:300]: - can.send(m.as_builder().to_bytes()) - can_callbacks = can_comm_callbacks(can, sendcan) + def can_recv(wait_for_one: bool = False) -> list[list[CanData]]: + return [next(can_msgs, [])] cached_params = None - if has_cached_cp: + if cached_params_raw is not None: with car.CarParams.from_bytes(cached_params_raw) as _cached_params: - cached_params = structs.CarParams(carName=_cached_params.carName, carFw=_cached_params.carFw, carVin=_cached_params.carVin) + cached_params = _cached_params - CP = get_car(*can_callbacks, lambda obd: None, Params().get_bool("ExperimentalLongitudinalEnabled"), cached_params=cached_params).CP + CP = get_car(can_recv, lambda _msgs: None, lambda obd: None, params.get_bool("AlphaLongitudinalEnabled"), False, cached_params=cached_params).CP - if not params.get_bool("DisengageOnAccelerator"): - CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS - - params.put("CarParams", convert_to_capnp(CP).to_bytes()) - - -def controlsd_rcv_callback(msg, cfg, frame): - return (frame - 1) == 0 or msg.which() == 'carState' + params.put("CarParams", CP.to_bytes(), block=True) def card_rcv_callback(msg, cfg, frame): @@ -391,21 +389,6 @@ def card_rcv_callback(msg, cfg, frame): return len(socks) > 0 -def calibration_rcv_callback(msg, cfg, frame): - # calibrationd publishes 1 calibrationData every 5 cameraOdometry packets. - # should_recv always true to increment frame - return (frame - 1) == 0 or msg.which() == 'cameraOdometry' - - -def torqued_rcv_callback(msg, cfg, frame): - # should_recv always true to increment frame - return (frame - 1) == 0 or msg.which() == 'livePose' - - -def dmonitoringmodeld_rcv_callback(msg, cfg, frame): - return msg.which() == "driverCameraState" - - class ModeldCameraSyncRcvCallback: def __init__(self): self.road_present = False @@ -430,36 +413,16 @@ def __call__(self, msg, cfg, frame): class MessageBasedRcvCallback: - def __init__(self, trigger_msg_type): - self.trigger_msg_type = trigger_msg_type - - def __call__(self, msg, cfg, frame): - return msg.which() == self.trigger_msg_type - - -class FrequencyBasedRcvCallback: - def __init__(self, trigger_msg_type): + def __init__(self, trigger_msg_type: str, first_frame: bool = False): self.trigger_msg_type = trigger_msg_type + self.first_frame = first_frame def __call__(self, msg, cfg, frame): - if msg.which() != self.trigger_msg_type: - return False + # publish on first frame or trigger msg + return ((frame - 1) == 0 and self.first_frame) or msg.which() == self.trigger_msg_type - resp_sockets = [ - s for s in cfg.subs - if frame % max(1, int(SERVICE_LIST[msg.which()].frequency / SERVICE_LIST[s].frequency)) == 0 - ] - return bool(len(resp_sockets)) - -def controlsd_config_callback(params, cfg, lr): - ublox = params.get_bool("UbloxAvailable") - sub_keys = ({"gpsLocation", } if ublox else {"gpsLocationExternal", }) - - cfg.pubs = set(cfg.pubs) - sub_keys - - -def locationd_config_pubsub_callback(params, cfg, lr): +def selfdrived_config_callback(params, cfg, lr): ublox = params.get_bool("UbloxAvailable") sub_keys = ({"gpsLocation", } if ublox else {"gpsLocationExternal", }) @@ -468,76 +431,90 @@ def locationd_config_pubsub_callback(params, cfg, lr): CONFIGS = [ ProcessConfig( - proc_name="controlsd", + proc_name="selfdrived", pubs=[ "carState", "deviceState", "pandaStates", "peripheralState", "liveCalibration", "driverMonitoringState", - "longitudinalPlan", "livePose", "liveParameters", "radarState", - "modelV2", "driverCameraState", "roadCameraState", "wideRoadCameraState", "managerState", - "testJoystick", "liveTorqueParameters", "accelerometer", "gyroscope", "carOutput", - "gpsLocationExternal", "gpsLocation", + "longitudinalPlan", "livePose", "liveDelay", "liveParameters", "radarState", "modelV2", + "driverCameraState", "roadCameraState", "wideRoadCameraState", "managerState", "liveTorqueParameters", + "accelerometer", "gyroscope", "carOutput", "gpsLocationExternal", "gpsLocation", "controlsState", + "carControl", "driverAssistance", "alertDebug", "audioFeedback", ], - subs=["selfdriveState", "controlsState", "carControl", "onroadEvents"], - ignore=["logMonoTime", "controlsState.cumLagMs"], - config_callback=controlsd_config_callback, + subs=["selfdriveState", "onroadEvents"], + ignore=["logMonoTime"], + config_callback=selfdrived_config_callback, init_callback=get_car_params_callback, - should_recv_callback=controlsd_rcv_callback, + should_recv_callback=MessageBasedRcvCallback("carState", True), tolerance=NUMPY_TOLERANCE, processing_time=0.004, ), + ProcessConfig( + proc_name="controlsd", + pubs=["liveParameters", "liveTorqueParameters", "modelV2", "selfdriveState", + "liveCalibration", "livePose", "longitudinalPlan", "carState", "carOutput", + "driverMonitoringState", "onroadEvents", "driverAssistance", "liveMapDataNAP"], + subs=["carControl", "controlsState"], + ignore=["logMonoTime", ], + init_callback=get_car_params_callback, + should_recv_callback=MessageBasedRcvCallback("selfdriveState"), + tolerance=NUMPY_TOLERANCE, + ), ProcessConfig( proc_name="card", - pubs=["pandaStates", "carControl", "onroadEvents", "can"], - subs=["sendcan", "carState", "carParams", "carOutput"], + pubs=["pandaStates", "carControl", "onroadEvents", "can", "liveMapDataNAP"], + subs=["sendcan", "carState", "carParams", "carOutput", "liveTracks"], ignore=["logMonoTime", "carState.cumLagMs"], init_callback=card_fingerprint_callback, should_recv_callback=card_rcv_callback, tolerance=NUMPY_TOLERANCE, processing_time=0.004, main_pub="can", + main_pub_drained=True, ), ProcessConfig( proc_name="radard", - pubs=["can", "carState", "modelV2"], - subs=["radarState", "liveTracks"], - ignore=["logMonoTime", "radarState.cumLagMs"], + pubs=["liveTracks", "carState", "modelV2"], + subs=["radarState"], + ignore=["logMonoTime", "radarState.radarPreferFallback", "radarState.radarPreferReason"], init_callback=get_car_params_callback, - should_recv_callback=MessageBasedRcvCallback("can"), - main_pub="can", + should_recv_callback=MessageBasedRcvCallback("modelV2"), ), ProcessConfig( proc_name="plannerd", - pubs=["modelV2", "carControl", "carState", "controlsState", "radarState", "selfdriveState"], - subs=["longitudinalPlan"], - ignore=["logMonoTime", "longitudinalPlan.processingDelay", "longitudinalPlan.solverExecutionTime"], + pubs=["modelV2", "carControl", "carState", "controlsState", "liveParameters", "radarState", "selfdriveState", "liveMapDataNAP"], + subs=["longitudinalPlan", "driverAssistance"], + ignore=["logMonoTime", "longitudinalPlan.processingDelay", "longitudinalPlan.solverExecutionTime", + "longitudinalPlan.napFollowDistance", "longitudinalPlan.tFollow", + "longitudinalPlan.unifiedATarget"], init_callback=get_car_params_callback, - should_recv_callback=FrequencyBasedRcvCallback("modelV2"), + should_recv_callback=MessageBasedRcvCallback("modelV2"), tolerance=NUMPY_TOLERANCE, ), ProcessConfig( proc_name="calibrationd", - pubs=["carState", "cameraOdometry", "carParams"], + pubs=["carState", "cameraOdometry"], subs=["liveCalibration"], ignore=["logMonoTime"], - should_recv_callback=calibration_rcv_callback, + init_callback=get_car_params_callback, + should_recv_callback=MessageBasedRcvCallback("cameraOdometry", True), ), ProcessConfig( proc_name="dmonitoringd", pubs=["driverStateV2", "liveCalibration", "carState", "modelV2", "selfdriveState"], subs=["driverMonitoringState"], ignore=["logMonoTime"], - should_recv_callback=FrequencyBasedRcvCallback("driverStateV2"), + should_recv_callback=MessageBasedRcvCallback("driverStateV2"), tolerance=NUMPY_TOLERANCE, ), ProcessConfig( proc_name="locationd", pubs=[ - "cameraOdometry", "accelerometer", "gyroscope", "gpsLocationExternal", - "liveCalibration", "carState", "gpsLocation" + "cameraOdometry", "accelerometer", "gyroscope", "liveCalibration", "carState" ], subs=["livePose"], ignore=["logMonoTime"], - config_callback=locationd_config_pubsub_callback, + should_recv_callback=MessageBasedRcvCallback("cameraOdometry"), tolerance=NUMPY_TOLERANCE, + processing_time=0.01, ), ProcessConfig( proc_name="paramsd", @@ -545,10 +522,19 @@ def locationd_config_pubsub_callback(params, cfg, lr): subs=["liveParameters"], ignore=["logMonoTime"], init_callback=get_car_params_callback, - should_recv_callback=FrequencyBasedRcvCallback("livePose"), + should_recv_callback=MessageBasedRcvCallback("livePose"), tolerance=NUMPY_TOLERANCE, processing_time=0.004, ), + ProcessConfig( + proc_name="lagd", + pubs=["livePose", "liveCalibration", "carState", "carControl", "controlsState"], + subs=["liveDelay"], + ignore=["logMonoTime"], + init_callback=get_car_params_callback, + should_recv_callback=MessageBasedRcvCallback("livePose"), + tolerance=NUMPY_TOLERANCE, + ), ProcessConfig( proc_name="ubloxd", pubs=["ubloxRaw"], @@ -557,23 +543,22 @@ def locationd_config_pubsub_callback(params, cfg, lr): ), ProcessConfig( proc_name="torqued", - pubs=["livePose", "liveCalibration", "carState", "carControl", "carOutput"], + pubs=["livePose", "liveCalibration", "liveDelay", "carState", "carControl", "carOutput"], subs=["liveTorqueParameters"], ignore=["logMonoTime"], init_callback=get_car_params_callback, - should_recv_callback=torqued_rcv_callback, + should_recv_callback=MessageBasedRcvCallback("livePose", True), tolerance=NUMPY_TOLERANCE, ), ProcessConfig( proc_name="modeld", - pubs=["deviceState", "roadCameraState", "wideRoadCameraState", "liveCalibration", "driverMonitoringState"], + pubs=["deviceState", "roadCameraState", "wideRoadCameraState", "liveCalibration", "liveDelay", "driverMonitoringState", "carState", "carControl"], subs=["modelV2", "drivingModelData", "cameraOdometry"], - ignore=["logMonoTime", "modelV2.frameDropPerc", "modelV2.modelExecutionTime"], + ignore=["logMonoTime", "modelV2.frameDropPerc", "modelV2.modelExecutionTime", "drivingModelData.frameDropPerc", "drivingModelData.modelExecutionTime"], should_recv_callback=ModeldCameraSyncRcvCallback(), tolerance=NUMPY_TOLERANCE, processing_time=0.020, main_pub=vipc_get_endpoint_name("camerad", meta_from_camera_state("roadCameraState").stream), - main_pub_drained=False, vision_pubs=["roadCameraState", "wideRoadCameraState"], ignore_alive_pubs=["wideRoadCameraState"], init_callback=get_car_params_callback, @@ -582,12 +567,11 @@ def locationd_config_pubsub_callback(params, cfg, lr): proc_name="dmonitoringmodeld", pubs=["liveCalibration", "driverCameraState"], subs=["driverStateV2"], - ignore=["logMonoTime", "driverStateV2.modelExecutionTime", "driverStateV2.dspExecutionTime"], - should_recv_callback=dmonitoringmodeld_rcv_callback, + ignore=["logMonoTime", "driverStateV2.modelExecutionTime", "driverStateV2.gpuExecutionTime"], + should_recv_callback=MessageBasedRcvCallback("driverCameraState"), tolerance=NUMPY_TOLERANCE, processing_time=0.020, main_pub=vipc_get_endpoint_name("camerad", meta_from_camera_state("driverCameraState").stream), - main_pub_drained=False, vision_pubs=["driverCameraState"], ignore_alive_pubs=["driverCameraState"], ), @@ -626,9 +610,7 @@ def get_custom_params_from_lr(lr: LogIterable, initial_state: str = "first") -> if len(live_calibration) > 0: custom_params["CalibrationParams"] = live_calibration[msg_index].as_builder().to_bytes() if len(live_parameters) > 0: - lp_dict = live_parameters[msg_index].to_dict() - lp_dict["carFingerprint"] = CP.carFingerprint - custom_params["LiveParameters"] = json.dumps(lp_dict) + custom_params["LiveParametersV2"] = live_parameters[msg_index].as_builder().to_bytes() if len(live_torque_parameters) > 0: custom_params["LiveTorqueParameters"] = live_torque_parameters[msg_index].as_builder().to_bytes() @@ -647,16 +629,16 @@ def replay_process_with_name(name: str | Iterable[str], lr: LogIterable, *args, def replay_process( - cfg: ProcessConfig | Iterable[ProcessConfig], lr: LogIterable, frs: dict[str, BaseFrameReader] = None, - fingerprint: str = None, return_all_logs: bool = False, custom_params: dict[str, Any] = None, - captured_output_store: dict[str, dict[str, str]] = None, disable_progress: bool = False + cfg: ProcessConfig | Iterable[ProcessConfig], lr: LogIterable, frs: dict[str, FrameReader] | None = None, + fingerprint: str | None = None, return_all_logs: bool = False, custom_params: dict[str, Any] | None = None, + captured_output_store: dict[str, dict[str, str]] | None = None, disable_progress: bool = False ) -> list[capnp._DynamicStructReader]: if isinstance(cfg, Iterable): cfgs = list(cfg) else: cfgs = [cfg] - all_msgs = migrate_all(lr, old_logtime=True, + all_msgs = migrate_all(lr, manager_states=True, panda_states=any("pandaStates" in cfg.pubs for cfg in cfgs), camera_states=any(len(cfg.vision_pubs) != 0 for cfg in cfgs)) @@ -675,7 +657,7 @@ def replay_process( def _replay_multi_process( - cfgs: list[ProcessConfig], lr: LogIterable, frs: dict[str, BaseFrameReader] | None, fingerprint: str | None, + cfgs: list[ProcessConfig], lr: LogIterable, frs: dict[str, FrameReader] | None, fingerprint: str | None, custom_params: dict[str, Any] | None, captured_output_store: dict[str, dict[str, str]] | None, disable_progress: bool ) -> list[capnp._DynamicStructReader]: if fingerprint is not None: @@ -697,8 +679,8 @@ def _replay_multi_process( all_msgs = sorted(lr, key=lambda msg: msg.logMonoTime) log_msgs = [] + containers = [] try: - containers = [] for cfg in cfgs: container = ProcessContainer(cfg) containers.append(container) @@ -733,6 +715,11 @@ def _replay_multi_process( internal_pub_queue.append(m) heapq.heappush(internal_pub_index_heap, (m.logMonoTime, len(internal_pub_queue) - 1)) log_msgs.extend(output_msgs) + + # flush last set of messages from each process + for container in containers: + last_time = container.last_input_log_mono_time if container.last_input_log_mono_time > 0 else int(time.monotonic() * 1e9) + log_msgs.extend(container.get_output_msgs(last_time)) finally: for container in containers: container.stop() @@ -760,15 +747,12 @@ def generate_params_config(lr=None, CP=None, fingerprint=None, custom_params=Non params_dict["IsRhdDetected"] = is_rhd if CP is not None: - if CP.alternativeExperience == ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS: - params_dict["DisengageOnAccelerator"] = False - if fingerprint is None: if CP.fingerprintSource == "fw": params_dict["CarParamsCache"] = CP.as_builder().to_bytes() if CP.openpilotLongitudinalControl: - params_dict["ExperimentalLongitudinalEnabled"] = True + params_dict["AlphaLongitudinalEnabled"] = True if CP.notCar: params_dict["JoystickDebugMode"] = True @@ -778,8 +762,7 @@ def generate_params_config(lr=None, CP=None, fingerprint=None, custom_params=Non def generate_environ_config(CP=None, fingerprint=None, log_dir=None) -> dict[str, Any]: environ_dict = {} - if platform.system() != "Darwin": - environ_dict["PARAMS_ROOT"] = "/dev/shm/params" + environ_dict["PARAMS_ROOT"] = f"{Paths.shm_path()}/params" if log_dir is not None: environ_dict["LOG_ROOT"] = log_dir diff --git a/selfdrive/test/process_replay/ref_commit b/selfdrive/test/process_replay/ref_commit deleted file mode 100644 index a110082a237013..00000000000000 --- a/selfdrive/test/process_replay/ref_commit +++ /dev/null @@ -1 +0,0 @@ -bf2bc833e238ec36c0519162edcaad743fad6dc5 \ No newline at end of file diff --git a/selfdrive/test/process_replay/regen.py b/selfdrive/test/process_replay/regen.py index e87b8347e1a213..c501a4b25083c1 100755 --- a/selfdrive/test/process_replay/regen.py +++ b/selfdrive/test/process_replay/regen.py @@ -3,44 +3,20 @@ import argparse import time import capnp -import numpy as np from typing import Any from collections.abc import Iterable from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, FAKEDATA, ProcessConfig, replay_process, get_process_config, \ check_openpilot_enabled, check_most_messages_valid, get_custom_params_from_lr -from openpilot.selfdrive.test.process_replay.vision_meta import DRIVER_CAMERA_FRAME_SIZES from openpilot.selfdrive.test.update_ci_routes import upload_route -from openpilot.tools.lib.route import Route -from openpilot.tools.lib.framereader import FrameReader, BaseFrameReader, FrameType +from openpilot.tools.lib.framereader import FrameReader from openpilot.tools.lib.logreader import LogReader, LogIterable, save_log - - -class DummyFrameReader(BaseFrameReader): - def __init__(self, w: int, h: int, frame_count: int, pix_val: int): - self.pix_val = pix_val - self.w, self.h = w, h - self.frame_count = frame_count - self.frame_type = FrameType.raw - - def get(self, idx, count=1, pix_fmt="yuv420p"): - if pix_fmt == "rgb24": - shape = (self.h, self.w, 3) - elif pix_fmt == "nv12" or pix_fmt == "yuv420p": - shape = (int((self.h * self.w) * 3 / 2),) - else: - raise NotImplementedError - - return [np.full(shape, self.pix_val, dtype=np.uint8) for _ in range(count)] - - @staticmethod - def zero_dcamera(): - return DummyFrameReader(*DRIVER_CAMERA_FRAME_SIZES[("tici", "ar0231")], 1200, 0) +from openpilot.tools.lib.openpilotci import get_url def regen_segment( - lr: LogIterable, frs: dict[str, Any] = None, + lr: LogIterable, frs: dict[str, Any] | None = None, processes: Iterable[ProcessConfig] = CONFIGS, disable_tqdm: bool = False ) -> list[capnp._DynamicStructReader]: all_msgs = sorted(lr, key=lambda m: m.logMonoTime) @@ -55,45 +31,28 @@ def regen_segment( def setup_data_readers( - route: str, sidx: int, use_route_meta: bool, - needs_driver_cam: bool = True, needs_road_cam: bool = True, dummy_driver_cam: bool = False + route: str, sidx: int, needs_driver_cam: bool = True, needs_road_cam: bool = True, dummy_driver_cam: bool = False ) -> tuple[LogReader, dict[str, Any]]: - if use_route_meta: - r = Route(route) - lr = LogReader(r.log_paths()[sidx]) - frs = {} - if needs_road_cam and len(r.camera_paths()) > sidx and r.camera_paths()[sidx] is not None: - frs['roadCameraState'] = FrameReader(r.camera_paths()[sidx]) - if needs_road_cam and len(r.ecamera_paths()) > sidx and r.ecamera_paths()[sidx] is not None: - frs['wideRoadCameraState'] = FrameReader(r.ecamera_paths()[sidx]) - if needs_driver_cam: - if dummy_driver_cam: - frs['driverCameraState'] = DummyFrameReader.zero_dcamera() - elif len(r.dcamera_paths()) > sidx and r.dcamera_paths()[sidx] is not None: - device_type = next(str(msg.initData.deviceType) for msg in lr if msg.which() == "initData") - assert device_type != "neo", "Driver camera not supported on neo segments. Use dummy dcamera." - frs['driverCameraState'] = FrameReader(r.dcamera_paths()[sidx]) - else: - lr = LogReader(f"{route}/{sidx}/r") - frs = {} - if needs_road_cam: - frs['roadCameraState'] = FrameReader(f"cd:/{route.replace('|', '/')}/{sidx}/fcamera.hevc") - if next((True for m in lr if m.which() == "wideRoadCameraState"), False): - frs['wideRoadCameraState'] = FrameReader(f"cd:/{route.replace('|', '/')}/{sidx}/ecamera.hevc") - if needs_driver_cam: - if dummy_driver_cam: - frs['driverCameraState'] = DummyFrameReader.zero_dcamera() - else: - device_type = next(str(msg.initData.deviceType) for msg in lr if msg.which() == "initData") - assert device_type != "neo", "Driver camera not supported on neo segments. Use dummy dcamera." - frs['driverCameraState'] = FrameReader(f"cd:/{route.replace('|', '/')}/{sidx}/dcamera.hevc") + lr = LogReader(f"{route}/{sidx}/r") + frs = {} + if needs_road_cam: + frs['roadCameraState'] = FrameReader(get_url(route, str(sidx), "fcamera.hevc")) + if next((True for m in lr if m.which() == "wideRoadCameraState"), False): + frs['wideRoadCameraState'] = FrameReader(get_url(route, str(sidx), "ecamera.hevc")) + if needs_driver_cam: + if dummy_driver_cam: + frs['driverCameraState'] = FrameReader(get_url(route, str(sidx), "fcamera.hevc")) # Use fcam as dummy + else: + device_type = next(str(msg.initData.deviceType) for msg in lr if msg.which() == "initData") + assert device_type != "neo", "Driver camera not supported on neo segments. Use dummy dcamera." + frs['driverCameraState'] = FrameReader(get_url(route, str(sidx), "dcamera.hevc")) return lr, frs def regen_and_save( route: str, sidx: int, processes: str | Iterable[str] = "all", outdir: str = FAKEDATA, - upload: bool = False, use_route_meta: bool = False, disable_tqdm: bool = False, dummy_driver_cam: bool = False + upload: bool = False, disable_tqdm: bool = False, dummy_driver_cam: bool = False ) -> str: if not isinstance(processes, str) and not hasattr(processes, "__iter__"): raise ValueError("whitelist_proc must be a string or iterable") @@ -110,7 +69,7 @@ def regen_and_save( replayed_processes = CONFIGS all_vision_pubs = {pub for cfg in replayed_processes for pub in cfg.vision_pubs} - lr, frs = setup_data_readers(route, sidx, use_route_meta, + lr, frs = setup_data_readers(route, sidx, needs_driver_cam="driverCameraState" in all_vision_pubs, needs_road_cam="roadCameraState" in all_vision_pubs or "wideRoadCameraState" in all_vision_pubs, dummy_driver_cam=dummy_driver_cam) diff --git a/selfdrive/test/process_replay/regen_all.py b/selfdrive/test/process_replay/regen_all.py index 656a5b89e1368a..78a90b420c135e 100755 --- a/selfdrive/test/process_replay/regen_all.py +++ b/selfdrive/test/process_replay/regen_all.py @@ -17,7 +17,7 @@ def regen_job(segment, upload, disable_tqdm): sn = SegmentName(segment[1]) fake_dongle_id = 'regen' + ''.join(random.choice('0123456789ABCDEF') for _ in range(11)) try: - relr = regen_and_save(sn.route_name.canonical_name, sn.segment_num, upload=upload, use_route_meta=False, + relr = regen_and_save(sn.route_name.canonical_name, sn.segment_num, upload=upload, outdir=os.path.join(FAKEDATA, fake_dongle_id), disable_tqdm=disable_tqdm, dummy_driver_cam=True) relr = '|'.join(relr.split('/')[-2:]) return f' ("{segment[0]}", "{relr}"), ' diff --git a/selfdrive/test/process_replay/test_compare_logs.py b/selfdrive/test/process_replay/test_compare_logs.py new file mode 100644 index 00000000000000..34bb55f7fa6c5b --- /dev/null +++ b/selfdrive/test/process_replay/test_compare_logs.py @@ -0,0 +1,53 @@ +from cereal import messaging + +from openpilot.selfdrive.test.process_replay.compare_logs import _diff_capnp_values, remove_ignored_fields + + +PATH = ("modelV2", "position", "x") + + +def _position_x_reader(values): + message = messaging.new_message("modelV2") + message.modelV2.position.x = values + return message.as_reader().modelV2.position.x + + +def test_equal_position_x_lists_have_no_diff(): + first = _position_x_reader([1, 2]) + second = _position_x_reader([1, 2]) + + assert list(_diff_capnp_values(first, second, PATH, 0)) == [] + + +def test_changed_position_x_element_reports_indexed_change(): + first = _position_x_reader([1, 2]) + second = _position_x_reader([1, 9]) + + assert list(_diff_capnp_values(first, second, PATH, 0)) == [ + ("change", "modelV2.position.x.1", (2, 9)), + ] + + +def test_grown_position_x_list_reports_indexed_additions(): + first = _position_x_reader([1, 2]) + second = _position_x_reader([1, 2, 3, 4]) + + assert list(_diff_capnp_values(first, second, PATH, 0)) == [ + ("add", "modelV2.position.x", [(2, 3), (3, 4)]), + ] + + +def test_remove_ignored_text_field_clears_string(): + message = messaging.new_message("radarState") + message.radarState.radarPreferReason = "dropout" + cleared = remove_ignored_fields(message, ["radarState.radarPreferReason"]) + assert cleared.radarState.radarPreferReason == "" + + +def test_shrunken_position_x_list_reports_reverse_indexed_removals(): + first = _position_x_reader([1, 2, 3, 4]) + second = _position_x_reader([1, 2]) + + assert list(_diff_capnp_values(first, second, PATH, 0)) == [ + ("remove", "modelV2.position.x", [(3, 4), (2, 3)]), + ] diff --git a/selfdrive/test/process_replay/test_fixture_tool.py b/selfdrive/test/process_replay/test_fixture_tool.py new file mode 100644 index 00000000000000..cf1bb77e527386 --- /dev/null +++ b/selfdrive/test/process_replay/test_fixture_tool.py @@ -0,0 +1,977 @@ +from __future__ import annotations + +from typing import Any +import hashlib +import json +import os +from pathlib import Path + +import pytest +import zstandard +from cereal import car, log as capnp_log +from openpilot.tools.lib.logreader import LogReader, save_log + +from openpilot.selfdrive.test.process_replay import fixture_tool + + +POLICY = Path(__file__).with_name("nap_fixture_policy.json") +PRIVATE_VIN = "1HGBH41JXMN109186" + + +def gas_sensor(counter: int) -> tuple[int, bytes, int]: + data = bytearray((1, 0xD6, 0, 0xFA, counter & 0x0F, 0)) + data[5] = (sum(data[:5]) + 0x52 + 0x05) & 0xFF + return 0x552, bytes(data), 2 + + +def _set_xyz(msg, x=0.0, y=0.0, z=0.0): + msg.x, msg.y, msg.z = x, y, z + msg.xStd = msg.yStd = msg.zStd = 0.0 + + +def make_car_params(*, pedal: bool = True, vin: str = PRIVATE_VIN, fw_secret: str | bytes | None = None) -> Any: + event = capnp_log.Event.new_message() + event.valid = True + event.logMonoTime = 1 + cp = event.init("carParams") + cp.brand = "tesla" + cp.carFingerprint = "TESLA_MODEL_S_PREAP" + cp.carVin = vin + cp.pcmCruise = not pedal + cp.openpilotLongitudinalControl = pedal + if fw_secret is not None: + fw = cp.init("carFw", 1)[0] + fw.ecu = car.CarParams.Ecu.unknown + fw.fwVersion = fw_secret if isinstance(fw_secret, (bytes, bytearray)) else fw_secret.encode() + fw.address = 0x7E0 + safety = cp.init("safetyConfigs", 1)[0] + safety.safetyModel = car.CarParams.SafetyModel.teslaPreap + safety.safetyParam = 7 if pedal else 6 + return event + + +def compact_stream(*, pedal: bool = True, private_vin: str = PRIVATE_VIN, + embed_private_text: bool = False, embed_private_data: bool = False, + split_vin_frames: bool = False, split_vin_events: bool = False, + interleaved_vin_frames: bool = False, undeclared_field: bool = False, + nonzero_vned: bool = False, wrong_safety_model: bool = False, + include_forbidden: bool = False, invalid_model: bool = False, + fw_secret: str | bytes | None = None, + duplicate_fw_in_can: bool = False) -> bytes: + events = [] + mono = 10 + + def stamp(event): + nonlocal mono + event.valid = True + event.logMonoTime = mono + mono += 10 + return event + + params = make_car_params(pedal=pedal, vin=private_vin, fw_secret=fw_secret) + if wrong_safety_model: + params.carParams.safetyConfigs[0].safetyModel = car.CarParams.SafetyModel.tesla + events.append(stamp(params)) + + can = capnp_log.Event.new_message() + frame_count = 10 if pedal else 1 + extras = 0 + if split_vin_frames: + extras += 2 + if interleaved_vin_frames: + extras += 3 + if embed_private_data: + extras += 1 + if duplicate_fw_in_can and fw_secret is not None: + extras += 1 + frames = can.init("can", frame_count + extras) + if pedal: + for index in range(10): + address, data, bus = gas_sensor(index) + frames[index].address, frames[index].dat, frames[index].src = address, data, bus + else: + frames[0].address, frames[0].dat, frames[0].src = 0x100, b"\x01\x02\x03\x04", 0 + cursor = frame_count + if split_vin_frames: + frames[cursor].address, frames[cursor].dat, frames[cursor].src = 0x100, private_vin[:3].encode(), 0 + frames[cursor + 1].address, frames[cursor + 1].dat, frames[cursor + 1].src = 0x101, private_vin[3:6].encode(), 0 + cursor += 2 + if interleaved_vin_frames: + frames[cursor].address, frames[cursor].dat, frames[cursor].src = 0x100, private_vin[:3].encode(), 0 + frames[cursor + 1].address, frames[cursor + 1].dat, frames[cursor + 1].src = 0x110, b"XX", 0 + frames[cursor + 2].address, frames[cursor + 2].dat, frames[cursor + 2].src = 0x101, private_vin[3:6].encode(), 0 + cursor += 3 + if embed_private_data: + frames[cursor].address, frames[cursor].dat, frames[cursor].src = 0x123, b"SECRETDATA_TOKEN", 0 + cursor += 1 + if duplicate_fw_in_can and fw_secret is not None: + fw_bytes = fw_secret if isinstance(fw_secret, (bytes, bytearray)) else fw_secret.encode() + frames[cursor].address, frames[cursor].dat, frames[cursor].src = 0x321, bytes(fw_bytes), 0 + cursor += 1 + events.append(stamp(can)) + + if split_vin_events: + first = capnp_log.Event.new_message() + f = first.init("can", 1)[0] + f.address, f.dat, f.src = 0x200, private_vin[:3].encode(), 1 + events.append(stamp(first)) + second = capnp_log.Event.new_message() + f = second.init("can", 1)[0] + f.address, f.dat, f.src = 0x201, private_vin[3:6].encode(), 1 + events.append(stamp(second)) + + # required services + cs = stamp(capnp_log.Event.new_message()) + state = cs.init("carState") + state.vEgo = 20.0 + state.aEgo = 0.1 + state.vCruise = 30.0 + state.standstill = False + state.steeringAngleDeg = 1.0 + state.canValid = True + state.cruiseState.enabled = True + state.leftBlindspot = True + state.rightBlindspot = False + state.teslaCCEngaged = False + state.teslaCCDisengaged = False + state.teslaCCNotArmed = False + state.pedalAuthorityFailed = False + events.append(cs) + + cc = stamp(capnp_log.Event.new_message()) + control = cc.init("carControl") + control.enabled = True + control.latActive = True + control.longActive = pedal + control.actuators.steeringAngleDeg = 1.0 + control.actuators.accel = 0.2 if pedal else 0.0 + control.orientationNED = [0.0, 0.01, 0.0] + control.leftBlinker = True + control.rightBlinker = False + events.append(cc) + + co = stamp(capnp_log.Event.new_message()) + output = co.init("carOutput") + output.actuatorsOutput.steeringAngleDeg = 1.0 + output.actuatorsOutput.torque = 0.1 + events.append(co) + + controls = stamp(capnp_log.Event.new_message()) + cst = controls.init("controlsState") + cst.desiredCurvature = 0.001 + cst.forceDecel = False + pid = cst.lateralControlState.init("pidState") + pid.saturated = False + pid.active = True + events.append(controls) + + sds = stamp(capnp_log.Event.new_message()) + ss = sds.init("selfdriveState") + ss.enabled = True + ss.active = True + ss.engageable = True + ss.state = capnp_log.SelfdriveState.OpenpilotState.enabled + if embed_private_text: + ss.alertText1 = "leak-token-value" + events.append(sds) + + model = stamp(capnp_log.Event.new_message()) + if invalid_model: + model.valid = False + mv = model.init("modelV2") + mv.frameId = 1 + mv.frameDropPerc = 0.0 + mv.position.x = [1.0, 2.0] + mv.velocity.x = [20.0, 20.0] + mv.acceleration.x = [0.1, 0.1] + mv.laneLineProbs = [0.9, 0.8, 0.7, 0.6] + lines = mv.init("laneLines", 4) + for line in lines: + line.y = [0.1, 0.2] + leads = mv.init("leadsV3", 2) + for lead in leads: + lead.prob = 0.5 + lead.x = [10.0] + lead.xStd = [1.0] + lead.y = [0.0] + lead.yStd = [0.1] + lead.v = [15.0] + lead.vStd = [0.5] + lead.a = [0.0] + mv.meta.laneChangeState = 0 + mv.meta.hardBrakePredicted = False + mv.meta.desirePrediction = [0.0] * 8 + mv.meta.disengagePredictions.gasPressProbs = [0.0, 0.01] + mv.action.desiredCurvature = 0.001 + mv.action.desiredAcceleration = 0.1 + mv.action.shouldStop = False + events.append(model) + + pose = stamp(capnp_log.Event.new_message()) + lp = pose.init("livePose") + lp.posenetOK = True + lp.inputsOK = True + _set_xyz(lp.orientationNED) + _set_xyz(lp.velocityDevice, x=20.0) + _set_xyz(lp.accelerationDevice) + _set_xyz(lp.angularVelocityDevice) + lp.angularVelocityDevice.valid = True + events.append(pose) + + calib = stamp(capnp_log.Event.new_message()) + lc = calib.init("liveCalibration") + lc.calStatus = capnp_log.LiveCalibrationData.Status.calibrated + lc.rpyCalib = [0.0, 0.0, 0.0] + events.append(calib) + + live_params = stamp(capnp_log.Event.new_message()) + lpd = live_params.init("liveParameters") + lpd.valid = True + lpd.angleOffsetDeg = 0.1 + lpd.steerRatio = 15.0 + lpd.stiffnessFactor = 1.0 + lpd.roll = 0.0 + events.append(live_params) + + torque = stamp(capnp_log.Event.new_message()) + lt = torque.init("liveTorqueParameters") + lt.useParams = False + events.append(torque) + + delay = stamp(capnp_log.Event.new_message()) + delay.init("liveDelay").lateralDelay = 0.05 + events.append(delay) + + tracks = stamp(capnp_log.Event.new_message()) + ltks = tracks.init("liveTracks") + pts = ltks.init("points", 1) + pts[0].trackId = 1 + pts[0].dRel = 20.0 + pts[0].yRel = 0.0 + pts[0].vRel = -1.0 + pts[0].measured = True + events.append(tracks) + + radar = stamp(capnp_log.Event.new_message()) + rs = radar.init("radarState") + rs.leadOne.status = True + rs.leadOne.dRel = 20.0 + rs.leadOne.vLead = 19.0 + rs.leadOne.aLeadK = 0.0 + rs.leadOne.aLeadTau = 1.5 + rs.leadOne.modelProb = 0.8 + rs.leadTwo.status = False + events.append(radar) + + plan = stamp(capnp_log.Event.new_message()) + lpplan = plan.init("longitudinalPlan") + lpplan.aTarget = 0.1 + lpplan.shouldStop = False + lpplan.hasLead = True + events.append(plan) + + panda = stamp(capnp_log.Event.new_message()) + ps = panda.init("pandaStates", 1)[0] + ps.pandaType = capnp_log.PandaState.PandaType.dos + ps.controlsAllowed = True + ps.safetyModel = car.CarParams.SafetyModel.teslaPreap + ps.safetyParam = 7 if pedal else 6 + ps.safetyRxChecksInvalid = False + events.append(panda) + + peri = stamp(capnp_log.Event.new_message()) + peri.init("peripheralState").pandaType = capnp_log.PandaState.PandaType.dos + events.append(peri) + + device = stamp(capnp_log.Event.new_message()) + ds = device.init("deviceState") + ds.freeSpacePercent = 50.0 + ds.memoryUsagePercent = 20 + ds.started = True + if undeclared_field: + ds.networkInfo.operator = "SECRET-OP" + events.append(device) + + onroad = stamp(capnp_log.Event.new_message()) + ev = onroad.init("onroadEvents", 1)[0] + ev.name = capnp_log.OnroadEvent.EventName.buttonEnable + events.append(onroad) + + dms = stamp(capnp_log.Event.new_message()) + dms.init("driverMonitoringState").awarenessStatus = 1.0 + events.append(dms) + + assist = stamp(capnp_log.Event.new_message()) + assist.init("driverAssistance") + events.append(assist) + + acc = stamp(capnp_log.Event.new_message()) + acc.init("accelerometer") + events.append(acc) + + gyro = stamp(capnp_log.Event.new_message()) + gyro.init("gyroscope") + events.append(gyro) + + gps = stamp(capnp_log.Event.new_message()) + loc = gps.init("gpsLocation") + if nonzero_vned: + loc.vNED = [1.0, 2.0, 3.0] + events.append(gps) + + if include_forbidden: + forbidden = stamp(capnp_log.Event.new_message()) + forbidden.init("initData") + events.append(forbidden) + + return b"".join(event.to_bytes() for event in events) + + +# fix typing import + +def read_messages(raw: bytes): + return list(LogReader.from_bytes(raw)) + + +def deny_token(label: str, value: str | bytes, encoding: str = "utf8") -> dict: + if encoding == "utf8": + encoded = value if isinstance(value, str) else value.decode("utf-8") + elif encoding == "hex": + raw_bytes = value if isinstance(value, (bytes, bytearray)) else value.encode("utf-8") + encoded = bytes(raw_bytes).hex() + elif encoding == "base64": + import base64 + raw_bytes = value if isinstance(value, (bytes, bytearray)) else value.encode("utf-8") + encoded = base64.b64encode(bytes(raw_bytes)).decode("ascii") + else: + raise AssertionError(encoding) + return {"label": label, "encoding": encoding, "value": encoded} + + +def write_deny(path: Path, raw: bytes, tokens: list[dict] | None = None, sha: str | None = None, + sanitized_output_sha256: str | None = None) -> Path: + payload = { + "raw_input_sha256": sha if sha is not None else hashlib.sha256(raw).hexdigest(), + "tokens": tokens if tokens is not None else [deny_token("vin", PRIVATE_VIN)], + } + if sanitized_output_sha256 is not None: + payload["sanitized_output_sha256"] = sanitized_output_sha256 + path.write_text(json.dumps(payload), encoding="utf-8") + return path + + +def run_sanitize(tmp_path: Path, raw: bytes, deny: dict | None = None, case: str = "nap-preap-pedal-v1"): + source = tmp_path / "source.bin" + output = tmp_path / "output.zst" + report = tmp_path / "report.json" + source.write_bytes(raw) + deny_path = None + if deny is None: + deny_path = write_deny(tmp_path / "deny.json", raw) + else: + deny_path = tmp_path / "deny.json" + deny_path.write_text(json.dumps(deny), encoding="utf-8") + status = fixture_tool.process(str(source), str(output), str(report), str(POLICY), case, str(deny_path), True) + return output.read_bytes() if output.exists() else None, json.loads(report.read_text()), status + + +def test_sanitize_is_byte_deterministic_and_scrubs_vin_and_fw(tmp_path: Path): + raw = compact_stream() + first, report, status = run_sanitize(tmp_path, raw) + second, _, _ = run_sanitize(tmp_path, raw) + assert first == second + assert status["scope"] == "private" + assert status["private_token_scan"]["performed"] is True + messages = list(LogReader.from_bytes(zstandard.ZstdDecompressor().decompress(first))) + params = next(message.carParams for message in messages if message.which() == "carParams") + assert params.carVin == "00000000000000000" + assert len(params.carFw) == 0 + assert fixture_tool.safety_model_ordinal(params.safetyConfigs[0].safetyModel) == int(car.CarParams.SafetyModel.teslaPreap) + assert report["can_evidence"]["valid_count"] == 10 + assert "token_matches" not in status + assert "raw_input_sha256" not in status + assert "raw_input_sha256" not in report + assert report["sanitized_output_sha256"] == hashlib.sha256(first).hexdigest() + assert params.safetyConfigs[0].safetyParam == 7 + + +def test_nested_list_fields_are_copied(tmp_path: Path): + raw = compact_stream() + output, _, _ = run_sanitize(tmp_path, raw) + messages = list(LogReader.from_bytes(zstandard.ZstdDecompressor().decompress(output))) + model = next(message.modelV2 for message in messages if message.which() == "modelV2") + assert list(model.velocity.x) == [20.0, 20.0] + assert len(model.leadsV3) == 2 + assert list(model.leadsV3[0].x) == [10.0] + tracks = next(message.liveTracks for message in messages if message.which() == "liveTracks") + assert tracks.points[0].dRel == 20.0 + + +def test_required_service_rejection(tmp_path: Path): + messages = [event for event in read_messages(compact_stream()) if event.which() != "modelV2"] + with pytest.raises(fixture_tool.FixtureError, match="required valid service"): + fixture_tool.structural_checks(messages, fixture_tool.parse_policy(str(POLICY)), "nap-preap-pedal-v1") + + +def test_sanitize_skips_forbidden_and_unknown_source_services(tmp_path: Path): + raw = compact_stream(include_forbidden=True) + # also append an undeclared-but-not-forbidden service via raw event if possible: thumbnail is forbidden + output, report, _ = run_sanitize(tmp_path, raw) + assert output is not None + assert "initData" not in report["message_counts"] + assert "initData" in report["source_message_counts"] + + +@pytest.mark.parametrize( + "mutate", + ( + lambda p: p.__setitem__("schema_version", 99), + lambda p: p.__setitem__("placeholder_vin", "11111111111111111"), + lambda p: p["allowed_services"].__setitem__("sendcan", ["[].address"]), + lambda p: p["forbidden_services"].remove("clocks"), + lambda p: p["cases"].__setitem__("nap-preap-pedal-v1", {"mode": "weird", "fingerprint": "TESLA_MODEL_S_PREAP"}), + lambda p: p.__setitem__("extra", 1), + ), +) +def test_invalid_policy_classes_are_rejected(tmp_path: Path, mutate): + policy = json.loads(POLICY.read_text()) + mutate(policy) + path = tmp_path / "bad_policy.json" + path.write_text(json.dumps(policy), encoding="utf-8") + with pytest.raises(fixture_tool.FixtureError): + fixture_tool.parse_policy(str(path)) + + +def test_undeclared_service_rejected_on_validate(tmp_path: Path): + raw = compact_stream() + output, _, _ = run_sanitize(tmp_path, raw) + messages = list(LogReader.from_bytes(zstandard.ZstdDecompressor().decompress(output))) + unexpected = capnp_log.Event.new_message() + unexpected.valid = True + unexpected.init("sendcan", 1) + path = tmp_path / "tampered.zst" + save_log(str(path), messages + [unexpected.as_reader()]) + report = tmp_path / "validate.json" + with pytest.raises(fixture_tool.FixtureError, match="undeclared service"): + fixture_tool.process(str(path), None, str(report), str(POLICY), "nap-preap-pedal-v1", None, False) + + +def test_undeclared_field_rejected(tmp_path: Path): + raw = compact_stream(undeclared_field=True) + # sanitize strips networkInfo because not allowed; validate against unsanitized tampered output + messages = read_messages(raw) + # force a sanitized-looking stream that still has networkInfo by manually building + policy = fixture_tool.parse_policy(str(POLICY)) + built = [fixture_tool.build_event(event, policy) for event in messages] + built = [event for event in built if event is not None] + # inject undeclared field into deviceState after sanitize rebuild + events = [] + for event in built: + if event.which() != "deviceState": + events.append(event) + continue + msg = event.as_builder() + msg.deviceState.networkInfo.operator = "SECRET-OP" + events.append(msg.as_reader()) + path = tmp_path / "field.zst" + save_log(str(path), events) + with pytest.raises(fixture_tool.FixtureError, match="undeclared populated field"): + fixture_tool.process(str(path), None, str(tmp_path / "report.json"), str(POLICY), "nap-preap-pedal-v1", None, False) + + +def test_nonzero_vned_rejected(tmp_path: Path): + raw = compact_stream(nonzero_vned=True) + policy = fixture_tool.parse_policy(str(POLICY)) + messages = [] + for event in read_messages(raw): + built = fixture_tool.build_event(event, policy) + if built is None: + continue + if built.which() == "gpsLocation": + msg = built.as_builder() + msg.gpsLocation.vNED = [1.0, 0.0, 0.0] + messages.append(msg.as_reader()) + else: + messages.append(built) + path = tmp_path / "vned.zst" + save_log(str(path), messages) + with pytest.raises(fixture_tool.FixtureError, match="sensitive field is not zero"): + fixture_tool.process(str(path), None, str(tmp_path / "report.json"), str(POLICY), "nap-preap-pedal-v1", None, False) + + +def test_exact_safety_model_required(tmp_path: Path): + output, _, _ = run_sanitize(tmp_path, compact_stream()) + messages = list(LogReader.from_bytes(zstandard.ZstdDecompressor().decompress(output))) + rebuilt = [] + for event in messages: + if event.which() != "carParams": + rebuilt.append(event) + continue + msg = event.as_builder() + msg.carParams.safetyConfigs[0].safetyModel = car.CarParams.SafetyModel.tesla + rebuilt.append(msg.as_reader()) + with pytest.raises(fixture_tool.FixtureError, match="safetyModel"): + fixture_tool.structural_checks(rebuilt, fixture_tool.parse_policy(str(POLICY)), "nap-preap-pedal-v1") + + +def test_structural_checks_require_tesla_brand(): + messages = read_messages(compact_stream()) + rebuilt = [] + for event in messages: + if event.which() != "carParams": + rebuilt.append(event) + continue + msg = event.as_builder() + msg.carParams.carVin = "00000000000000000" + msg.carParams.carFw = [] + msg.carParams.brand = "private-brand" + rebuilt.append(msg.as_reader()) + + with pytest.raises(fixture_tool.FixtureError, match=r"carParams\.brand must be tesla"): + fixture_tool.structural_checks(rebuilt, fixture_tool.parse_policy(str(POLICY)), "nap-preap-pedal-v1") + +def test_text_token_outside_carparams_is_rejected(tmp_path: Path): + raw = compact_stream() + deny = { + "raw_input_sha256": hashlib.sha256(raw).hexdigest(), + "tokens": [ + deny_token("vin", PRIVATE_VIN), + deny_token("retained_public_text", "TESLA_MODEL_S_PREAP"), + ], + } + with pytest.raises(fixture_tool.FixtureError, match="private token"): + run_sanitize(tmp_path, raw, deny) + # ensure no final output + output = tmp_path / "output.zst" + # run_sanitize may have left nothing; check report exists with matches + report = json.loads((tmp_path / "report.json").read_text()) + assert report["private_token_scan"]["performed"] is True + assert report["private_token_scan"]["token_matches"] + assert not output.exists() + + +def test_data_token_is_rejected(tmp_path: Path): + raw = compact_stream(embed_private_data=True) + deny = {"raw_input_sha256": hashlib.sha256(raw).hexdigest(), + "tokens": [deny_token("vin", PRIVATE_VIN), deny_token("secret", "SECRETDATA_TOKEN")]} + with pytest.raises(fixture_tool.FixtureError, match="private token"): + run_sanitize(tmp_path, raw, deny) + assert not (tmp_path / "output.zst").exists() + report = json.loads((tmp_path / "report.json").read_text()) + assert any(row["label"] == "secret" for row in report["private_token_scan"]["token_matches"]) + + +def test_split_vin_across_frames_is_rejected(tmp_path: Path): + raw = compact_stream(split_vin_frames=True) + with pytest.raises(fixture_tool.FixtureError, match="private token"): + run_sanitize(tmp_path, raw) + assert not (tmp_path / "output.zst").exists() + + +def test_split_vin_across_events_is_rejected(tmp_path: Path): + raw = compact_stream(split_vin_events=True) + with pytest.raises(fixture_tool.FixtureError, match="private token"): + run_sanitize(tmp_path, raw) + assert not (tmp_path / "output.zst").exists() + + +def test_missing_empty_wrong_hash_deny(tmp_path: Path): + raw = compact_stream() + source = tmp_path / "source.bin" + source.write_bytes(raw) + output = tmp_path / "out.zst" + report = tmp_path / "report.json" + with pytest.raises(fixture_tool.FixtureError, match="deny"): + fixture_tool.process(str(source), str(output), str(report), str(POLICY), "nap-preap-pedal-v1", None, True) + empty = tmp_path / "empty.json" + empty.write_text(json.dumps({"raw_input_sha256": hashlib.sha256(raw).hexdigest(), "tokens": []}), encoding="utf-8") + with pytest.raises(fixture_tool.FixtureError, match="nonempty"): + fixture_tool.process(str(source), str(output), str(report), str(POLICY), "nap-preap-pedal-v1", str(empty), True) + wrong = write_deny(tmp_path / "wrong.json", raw, sha="0" * 64) + with pytest.raises(fixture_tool.FixtureError, match="SHA-256"): + fixture_tool.process(str(source), str(output), str(report), str(POLICY), "nap-preap-pedal-v1", str(wrong), True) + # conflicting --input-sha256 must not override deny + deny = write_deny(tmp_path / "deny.json", raw) + with pytest.raises(fixture_tool.FixtureError, match="conflicts"): + fixture_tool.process(str(source), str(output), str(report), str(POLICY), "nap-preap-pedal-v1", str(deny), True, "1" * 64) + + +def test_public_and_private_validate_scopes(tmp_path: Path): + raw = compact_stream() + output, private_report, _ = run_sanitize(tmp_path, raw) + public_report = tmp_path / "public.json" + status = fixture_tool.process(str(tmp_path / "output.zst"), None, str(public_report), str(POLICY), "nap-preap-pedal-v1", None, False) + assert status["scope"] == "public" + assert status["private_token_scan"]["performed"] is False + loaded = json.loads(public_report.read_text()) + assert loaded["scope"] == "public" + assert loaded["private_token_scan"]["performed"] is False + assert "token_matches" not in loaded + assert "token_matches" not in loaded.get("private_token_scan", {}) + + sanitized_deny = { + "raw_input_sha256": hashlib.sha256(raw).hexdigest(), + "sanitized_output_sha256": hashlib.sha256(output).hexdigest(), + "tokens": [deny_token("vin", PRIVATE_VIN)], + } + deny_path = tmp_path / "san_deny.json" + deny_path.write_text(json.dumps(sanitized_deny), encoding="utf-8") + private_path = tmp_path / "private.json" + status = fixture_tool.process(str(tmp_path / "output.zst"), None, str(private_path), str(POLICY), "nap-preap-pedal-v1", str(deny_path), False) + assert status["scope"] == "private" + assert status["private_token_scan"]["performed"] is True + loaded = json.loads(private_path.read_text()) + assert loaded["private_token_scan"]["performed"] is True + assert loaded["private_token_scan"]["token_matches"] + assert all(row["count"] == 0 for row in loaded["private_token_scan"]["token_matches"]) + + +def test_symlink_hardlink_and_same_path_collisions(tmp_path: Path): + raw = compact_stream() + source = tmp_path / "source.bin" + source.write_bytes(raw) + deny = write_deny(tmp_path / "deny.json", raw) + report = tmp_path / "report.json" + # same path output/report + with pytest.raises(fixture_tool.FixtureError, match="distinct|collision"): + fixture_tool.process(str(source), str(report), str(report), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + # symlink output + link = tmp_path / "link.zst" + target = tmp_path / "target.zst" + target.write_bytes(b"x") + link.symlink_to(target) + with pytest.raises(fixture_tool.FixtureError, match="symlink|alias|collision"): + fixture_tool.process(str(source), str(link), str(report), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + # hardlink alias between output and report destinations that already exist as same inode + hard_a = tmp_path / "hard_a.json" + hard_b = tmp_path / "hard_b.json" + hard_a.write_text("{}", encoding="utf-8") + os.link(hard_a, hard_b) + with pytest.raises(fixture_tool.FixtureError, match="inode|alias|collision"): + fixture_tool.process(str(source), str(hard_a), str(hard_b), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + + +def test_cli_malformed_input_returns_2(tmp_path: Path): + bad = tmp_path / "bad.bin" + bad.write_bytes(b"not-a-log") + deny = write_deny(tmp_path / "deny.json", b"not-a-log", tokens=[deny_token("tokenx", "abcdef")]) + code = fixture_tool.main([ + "sanitize", "--policy", str(POLICY), "--case", "nap-preap-pedal-v1", + "--input", str(bad), "--output", str(tmp_path / "out.zst"), "--report", str(tmp_path / "r.json"), + "--deny-token-file", str(deny), + ]) + assert code == 2 + + +def test_no_pedal_rejects_sensor_frames(tmp_path: Path): + # Build a no-pedal fixture then inject pedal sensor frames. + output, _, _ = run_sanitize(tmp_path, compact_stream(pedal=False, private_vin=PRIVATE_VIN), case="nap-preap-no-pedal-v1") + messages = list(LogReader.from_bytes(zstandard.ZstdDecompressor().decompress(output))) + can = capnp_log.Event.new_message() + can.valid = True + can.logMonoTime = 999 + frame = can.init("can", 1)[0] + address, data, bus = gas_sensor(0) + frame.address, frame.dat, frame.src = address, data, bus + path = tmp_path / "nopedal_tampered.zst" + save_log(str(path), messages + [can.as_reader()]) + with pytest.raises(fixture_tool.FixtureError, match="no-pedal"): + fixture_tool.process(str(path), None, str(tmp_path / "nop.json"), str(POLICY), "nap-preap-no-pedal-v1", None, False) + + +def test_cli_public_validation_returns_failure_for_tampering(tmp_path: Path): + output, _, _ = run_sanitize(tmp_path, compact_stream()) + path = tmp_path / "fixture.zst" + path.write_bytes(output[:-1] + bytes((output[-1] ^ 1,))) + assert fixture_tool.main([ + "validate", "--policy", str(POLICY), "--case", "nap-preap-pedal-v1", + "--input", str(path), "--report", str(tmp_path / "rep.json"), + ]) != 0 + + +def test_interleaved_vin_across_frames_is_rejected(tmp_path: Path): + raw = compact_stream(interleaved_vin_frames=True) + with pytest.raises(fixture_tool.FixtureError, match="private token"): + run_sanitize(tmp_path, raw) + assert not (tmp_path / "output.zst").exists() + + +def test_deny_requires_exact_source_vin(tmp_path: Path): + raw = compact_stream() + source = tmp_path / "source.bin" + source.write_bytes(raw) + deny = write_deny(tmp_path / "deny.json", raw, tokens=[deny_token("route", "abcdefgh")]) + with pytest.raises(fixture_tool.FixtureError, match="exactly one vin token"): + fixture_tool.process(str(source), str(tmp_path / "output.zst"), str(tmp_path / "report.json"), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + + deny = write_deny(tmp_path / "deny2.json", raw, tokens=[deny_token("vin", "1HGBH41JXMN109187")]) + with pytest.raises(fixture_tool.FixtureError, match="does not match source"): + fixture_tool.process(str(source), str(tmp_path / "output2.zst"), str(tmp_path / "report2.json"), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + + +def test_private_validate_reuses_raw_bound_deny(tmp_path: Path): + raw = compact_stream() + output, report, _ = run_sanitize(tmp_path, raw) + assert "raw_input_sha256" not in report + deny = write_deny( + tmp_path / "bound_deny.json", + raw, + sanitized_output_sha256=hashlib.sha256(output).hexdigest(), + ) + status = fixture_tool.process( + str(tmp_path / "output.zst"), None, str(tmp_path / "private.json"), str(POLICY), + "nap-preap-pedal-v1", str(deny), False, + ) + assert status["scope"] == "private" + loaded = json.loads((tmp_path / "private.json").read_text()) + assert "raw_input_sha256" not in loaded + assert all(row["count"] == 0 for row in loaded["private_token_scan"]["token_matches"]) + + +def test_stale_output_removed_on_rejection(tmp_path: Path): + raw = compact_stream() + output, _, _ = run_sanitize(tmp_path, raw) + assert output is not None + out_path = tmp_path / "output.zst" + assert out_path.exists() + # Re-run with VIN leak against the same destination. + with pytest.raises(fixture_tool.FixtureError, match="private token"): + run_sanitize(tmp_path, compact_stream(split_vin_frames=True)) + assert not out_path.exists() + + +def test_required_valid_service_minima(tmp_path: Path): + messages = read_messages(compact_stream(invalid_model=True)) + with pytest.raises(fixture_tool.FixtureError, match="required valid service"): + fixture_tool.structural_checks(messages, fixture_tool.parse_policy(str(POLICY)), "nap-preap-pedal-v1") + + +def test_exact_safety_param_required(tmp_path: Path): + output, _, _ = run_sanitize(tmp_path, compact_stream()) + messages = list(LogReader.from_bytes(zstandard.ZstdDecompressor().decompress(output))) + rebuilt = [] + for message in messages: + if message.which() != "carParams": + rebuilt.append(message) + continue + event = message.as_builder() + event.carParams.safetyConfigs[0].safetyParam = 1 + rebuilt.append(event.as_reader()) + with pytest.raises(fixture_tool.FixtureError, match="safetyParam"): + fixture_tool.structural_checks(rebuilt, fixture_tool.parse_policy(str(POLICY)), "nap-preap-pedal-v1") + + +def test_retained_consumer_fields_survive_sanitize(tmp_path: Path): + output, _, _ = run_sanitize(tmp_path, compact_stream()) + messages = list(LogReader.from_bytes(zstandard.ZstdDecompressor().decompress(output))) + state = next(message.carState for message in messages if message.which() == "carState") + assert state.leftBlindspot is True + assert state.pedalAuthorityFailed is False + control = next(message.carControl for message in messages if message.which() == "carControl") + assert control.leftBlinker is True + assert control.rightBlinker is False + panda = next(message.pandaStates for message in messages if message.which() == "pandaStates") + assert panda[0].safetyRxChecksInvalid is False + + +def test_accept_six_process_outputs_helper(tmp_path: Path): + policy = fixture_tool.parse_policy(str(POLICY)) + raw = compact_stream() + output, _, _ = run_sanitize(tmp_path, raw) + fixture_messages = list(LogReader.from_bytes(zstandard.ZstdDecompressor().decompress(output))) + + def with_service(service: str, list_size: int | None = None, **fields): + event = capnp_log.Event.new_message() + event.valid = True + event.logMonoTime = 1 + payload = event.init(service) if list_size is None else event.init(service, list_size) + for key, value in fields.items(): + setattr(payload, key, value) + return event.as_reader() + + # Synthetic per-process outputs using fixture carParams for card mode evidence. + car_params = next(message for message in fixture_messages if message.which() == "carParams") + process_outputs = { + "card": [ + car_params, + next(message for message in fixture_messages if message.which() == "carState"), + next(message for message in fixture_messages if message.which() == "carOutput"), + next(message for message in fixture_messages if message.which() == "liveTracks"), + with_service("sendcan", list_size=1), + ], + "controlsd": [ + next(message for message in fixture_messages if message.which() == "carControl"), + next(message for message in fixture_messages if message.which() == "controlsState"), + ], + "selfdrived": [ + next(message for message in fixture_messages if message.which() == "selfdriveState"), + next(message for message in fixture_messages if message.which() == "onroadEvents"), + ], + "radard": [next(message for message in fixture_messages if message.which() == "radarState")], + "plannerd": [ + next(message for message in fixture_messages if message.which() == "longitudinalPlan"), + next(message for message in fixture_messages if message.which() == "driverAssistance"), + ], + "lagd": [next(message for message in fixture_messages if message.which() == "liveDelay")], + } + case_params = { + "NAPPedalEnabled": True, + "NAPRadarEnabled": True, + "NAPRadarBehindNosecone": True, + } + accepted = fixture_tool.accept_six_process_outputs( + case="nap-preap-pedal-v1", + policy=policy, + process_outputs=process_outputs, + case_params=case_params, + ) + assert accepted["status"] == "ok" + assert accepted["card_mode"] == "pedal" + assert accepted["card_safety_param"] == 7 + assert set(accepted["processes"]) == set(fixture_tool.SIX_PROCESS_OUTPUTS) + + with pytest.raises(fixture_tool.FixtureError, match="missing process outputs"): + fixture_tool.accept_six_process_outputs( + case="nap-preap-pedal-v1", + policy=policy, + process_outputs={k: v for k, v in process_outputs.items() if k != "lagd"}, + case_params=case_params, + ) + + +def test_selfdrived_replay_ignores_stripped_services(): + source = Path(__file__).resolve().parents[2] / "selfdrived" / "selfdrived.py" + text = source.read_text(encoding="utf-8") + assert "driverCameraState" in text + assert "managerState" in text + # REPLAY ignore list must include both stripped fixture services. + assert "ignore += ['roadCameraState', 'wideRoadCameraState', 'driverCameraState', 'managerState']" in text + + +def test_policy_attestation_rejects_weakened_contract(tmp_path: Path): + policy = json.loads(POLICY.read_text(encoding="utf-8")) + policy["pedal"]["minimum_frames"] = 0 + policy["pedal"]["minimum_counters"] = 0 + path = tmp_path / "weak.json" + path.write_text(json.dumps(policy), encoding="utf-8") + with pytest.raises(fixture_tool.FixtureError, match="attested release contract|pedal evidence minima"): + fixture_tool.parse_policy(str(path)) + + policy = json.loads(POLICY.read_text(encoding="utf-8")) + policy["allowed_services"]["carState"] = list(policy["allowed_services"]["carState"]) + ["cruiseState.speedOffline"] + path = tmp_path / "extra_leaf.json" + path.write_text(json.dumps(policy), encoding="utf-8") + with pytest.raises(fixture_tool.FixtureError, match="attested release contract"): + fixture_tool.parse_policy(str(path)) + + +def test_deny_inventory_completeness_requires_scrubbed_secrets(tmp_path: Path): + raw = compact_stream(fw_secret="SECRET_FW_VALUE") + source = tmp_path / "source.bin" + source.write_bytes(raw) + deny = write_deny(tmp_path / "deny.json", raw) # vin only; missing fw secret + with pytest.raises(fixture_tool.FixtureError, match="deny tokens incomplete"): + fixture_tool.process(str(source), str(tmp_path / "output.zst"), str(tmp_path / "report.json"), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + + deny = write_deny( + tmp_path / "deny2.json", + raw, + tokens=[deny_token("vin", PRIVATE_VIN), deny_token("fw", "SECRET_FW_VALUE")], + ) + status = fixture_tool.process(str(source), str(tmp_path / "output2.zst"), str(tmp_path / "report2.json"), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + assert status["status"] == "ok" + + +def test_deny_inventory_keeps_fw_when_duplicated_in_retained_can(tmp_path: Path): + # NAP-FIXTURE-001: private fwVersion bytes also present in retained can[].dat must + # still require an explicit deny token; set-subtraction must not exempt them. + secret = "SECRET_FW_VALUE" + raw = compact_stream(fw_secret=secret, duplicate_fw_in_can=True) + source = tmp_path / "source.bin" + source.write_bytes(raw) + out = tmp_path / "output.zst" + deny = write_deny(tmp_path / "deny.json", raw) # vin only + with pytest.raises(fixture_tool.FixtureError, match="deny tokens incomplete"): + fixture_tool.process(str(source), str(out), str(tmp_path / "report.json"), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + assert not out.exists() + + deny = write_deny( + tmp_path / "deny2.json", + raw, + tokens=[deny_token("vin", PRIVATE_VIN), deny_token("fw", secret)], + ) + # Inventory complete, but retained can[].dat still carries the secret — scan rejects. + with pytest.raises(fixture_tool.FixtureError, match="private token"): + fixture_tool.process(str(source), str(tmp_path / "output2.zst"), str(tmp_path / "report2.json"), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + assert not (tmp_path / "output2.zst").exists() + + # Explicit fw deny succeeds when the secret is scrubbed and not retained in CAN. + clean = compact_stream(fw_secret=secret, duplicate_fw_in_can=False) + clean_source = tmp_path / "clean.bin" + clean_source.write_bytes(clean) + deny = write_deny( + tmp_path / "deny3.json", + clean, + tokens=[deny_token("vin", PRIVATE_VIN), deny_token("fw", secret)], + ) + status = fixture_tool.process( + str(clean_source), str(tmp_path / "output3.zst"), str(tmp_path / "report3.json"), + str(POLICY), "nap-preap-pedal-v1", str(deny), True, + ) + assert status["status"] == "ok" + assert (tmp_path / "output3.zst").exists() + + +def test_binary_deny_token_hex_covers_non_utf8_fw(tmp_path: Path): + secret = b"BIN\xffFW\x00SECRETS" + raw = compact_stream(fw_secret=secret) + source = tmp_path / "source.bin" + source.write_bytes(raw) + deny = write_deny( + tmp_path / "deny.json", + raw, + tokens=[deny_token("vin", PRIVATE_VIN), deny_token("fw", secret, encoding="hex")], + ) + status = fixture_tool.process(str(source), str(tmp_path / "output.zst"), str(tmp_path / "report.json"), str(POLICY), "nap-preap-pedal-v1", str(deny), True) + assert status["status"] == "ok" + + legacy = { + "raw_input_sha256": hashlib.sha256(raw).hexdigest(), + "tokens": [{"label": "vin", "value": PRIVATE_VIN}], + } + legacy_path = tmp_path / "legacy.json" + legacy_path.write_text(json.dumps(legacy), encoding="utf-8") + with pytest.raises(fixture_tool.FixtureError, match="label, encoding, and value"): + fixture_tool.load_deny(str(legacy_path)) + + +def test_zstd_trailing_data_is_rejected(tmp_path: Path): + raw = compact_stream() + frame = zstandard.ZstdCompressor().compress(raw) + path = tmp_path / "trail.zst" + path.write_bytes(frame + b"TRAILING_JUNK") + with pytest.raises(fixture_tool.FixtureError, match="malformed"): + fixture_tool.process(str(path), None, str(tmp_path / "report.json"), str(POLICY), "nap-preap-pedal-v1", None, False) + + multi = frame + zstandard.ZstdCompressor().compress(b"NEXTFRAME") + path.write_bytes(multi) + with pytest.raises(fixture_tool.FixtureError, match="malformed"): + fixture_tool.process(str(path), None, str(tmp_path / "report2.json"), str(POLICY), "nap-preap-pedal-v1", None, False) + + +def test_nonexistent_canonical_path_aliases_are_rejected(tmp_path: Path): + missing = tmp_path / "out.zst" + aliased = tmp_path / "sub" / ".." / "out.zst" + with pytest.raises(fixture_tool.FixtureError, match="path collision"): + fixture_tool.validate_path_separation({"output": missing, "report": aliased}) + + +def test_bounded_zstd_expansion_rejects_bomb(tmp_path: Path): + # Tiny compressed payload that would expand past the fixture tool ceiling. + bomb = zstandard.ZstdCompressor(level=1).compress(b"A" * (fixture_tool.MAX_DECOMPRESSED_INPUT_BYTES + 1024)) + assert len(bomb) < fixture_tool.MAX_COMPRESSED_INPUT_BYTES + path = tmp_path / "bomb.zst" + path.write_bytes(bomb) + report = tmp_path / "report.json" + with pytest.raises(fixture_tool.FixtureError, match="decompressed size limit|malformed"): + fixture_tool.process(str(path), None, str(report), str(POLICY), "nap-preap-pedal-v1", None, False) diff --git a/selfdrive/test/process_replay/test_fuzzy.py b/selfdrive/test/process_replay/test_fuzzy.py index d9388390398c7e..6989f8957febd4 100644 --- a/selfdrive/test/process_replay/test_fuzzy.py +++ b/selfdrive/test/process_replay/test_fuzzy.py @@ -1,7 +1,8 @@ import copy +import os from hypothesis import given, HealthCheck, Phase, settings import hypothesis.strategies as st -from parameterized import parameterized +from openpilot.common.parameterized import parameterized from cereal import log from opendbc.car.toyota.values import CAR as TOYOTA @@ -11,16 +12,18 @@ # These processes currently fail because of unrealistic data breaking assumptions # that openpilot makes causing error with NaN, inf, int size, array indexing ... # TODO: Make each one testable -NOT_TESTED = ['controlsd', 'card', 'plannerd', 'calibrationd', 'dmonitoringd', 'paramsd', 'dmonitoringmodeld', 'modeld'] +NOT_TESTED = ['selfdrived', 'controlsd', 'card', 'plannerd', 'calibrationd', 'dmonitoringd', 'paramsd', 'dmonitoringmodeld', 'modeld'] TEST_CASES = [(cfg.proc_name, copy.deepcopy(cfg)) for cfg in pr.CONFIGS if cfg.proc_name not in NOT_TESTED] +MAX_EXAMPLES = int(os.environ.get("MAX_EXAMPLES", "10")) class TestFuzzProcesses: # TODO: make this faster and increase examples @parameterized.expand(TEST_CASES) @given(st.data()) - @settings(phases=[Phase.generate, Phase.target], max_examples=10, deadline=1000, suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large]) + @settings(phases=[Phase.generate, Phase.target], max_examples=MAX_EXAMPLES, deadline=1000, + suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large]) def test_fuzz_process(self, proc_name, cfg, data): msgs = FuzzyGenerator.get_random_event_msg(data.draw, events=cfg.pubs, real_floats=True) lr = [log.Event.new_message(**m).as_reader() for m in msgs] diff --git a/selfdrive/test/process_replay/test_imgproc.py b/selfdrive/test/process_replay/test_imgproc.py deleted file mode 100644 index 27d0541a507413..00000000000000 --- a/selfdrive/test/process_replay/test_imgproc.py +++ /dev/null @@ -1,98 +0,0 @@ -import os -import numpy as np -import hashlib - -import pyopencl as cl # install with `PYOPENCL_CL_PRETEND_VERSION=2.0 pip install pyopencl` - -from openpilot.system.hardware import PC, TICI -from openpilot.common.basedir import BASEDIR -from openpilot.common.transformations.camera import DEVICE_CAMERAS -from openpilot.system.camerad.snapshot.snapshot import yuv_to_rgb -from openpilot.tools.lib.logreader import LogReader - -# TODO: check all sensors -TEST_ROUTE = "8345e3b82948d454|2022-05-04--13-45-33/0" - -cam = DEVICE_CAMERAS[("tici", "ar0231")] -FRAME_WIDTH, FRAME_HEIGHT = (cam.dcam.width, cam.dcam.height) -FRAME_STRIDE = FRAME_WIDTH * 12 // 8 + 4 - -UV_WIDTH = FRAME_WIDTH // 2 -UV_HEIGHT = FRAME_HEIGHT // 2 -UV_SIZE = UV_WIDTH * UV_HEIGHT - - -def init_kernels(frame_offset=0): - ctx = cl.create_some_context(interactive=False) - - with open(os.path.join(BASEDIR, 'system/camerad/cameras/process_raw.cl')) as f: - build_args = f' -cl-fast-relaxed-math -cl-denorms-are-zero -cl-single-precision-constant -I{BASEDIR}/system/camerad/sensors ' + \ - f' -DFRAME_WIDTH={FRAME_WIDTH} -DFRAME_HEIGHT={FRAME_WIDTH} -DFRAME_STRIDE={FRAME_STRIDE} -DFRAME_OFFSET={frame_offset} ' + \ - f' -DRGB_WIDTH={FRAME_WIDTH} -DRGB_HEIGHT={FRAME_HEIGHT} -DYUV_STRIDE={FRAME_WIDTH} -DUV_OFFSET={FRAME_WIDTH*FRAME_HEIGHT}' + \ - ' -DSENSOR_ID=1 -DVIGNETTING=0 ' - if PC: - build_args += ' -DHALF_AS_FLOAT=1 -cl-std=CL2.0' - imgproc_prg = cl.Program(ctx, f.read()).build(options=build_args) - - return ctx, imgproc_prg - -def proc_frame(ctx, imgproc_prg, data, rgb=False): - q = cl.CommandQueue(ctx) - - yuv_buff = np.empty(FRAME_WIDTH * FRAME_HEIGHT + UV_SIZE * 2, dtype=np.uint8) - - cam_g = cl.Buffer(ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=data) - yuv_g = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, FRAME_WIDTH * FRAME_HEIGHT + UV_SIZE * 2) - - krn = imgproc_prg.process_raw - krn.set_scalar_arg_dtypes([None, None, np.int32]) - local_worksize = (20, 20) if TICI else (4, 4) - - ev1 = krn(q, (FRAME_WIDTH//2, FRAME_HEIGHT//2), local_worksize, cam_g, yuv_g, 1) - cl.enqueue_copy(q, yuv_buff, yuv_g, wait_for=[ev1]).wait() - cl.enqueue_barrier(q) - - y = yuv_buff[:FRAME_WIDTH*FRAME_HEIGHT].reshape((FRAME_HEIGHT, FRAME_WIDTH)) - u = yuv_buff[FRAME_WIDTH*FRAME_HEIGHT::2].reshape((UV_HEIGHT, UV_WIDTH)) - v = yuv_buff[FRAME_WIDTH*FRAME_HEIGHT+1::2].reshape((UV_HEIGHT, UV_WIDTH)) - - if rgb: - return yuv_to_rgb(y, u, v) - else: - return y, u, v - - -def imgproc_replay(lr): - ctx, imgproc_prg = init_kernels() - - frames = [] - for m in lr: - if m.which() == 'roadCameraState': - cs = m.roadCameraState - if cs.image: - data = np.frombuffer(cs.image, dtype=np.uint8) - img = proc_frame(ctx, imgproc_prg, data) - - frames.append(img) - - return frames - - -if __name__ == "__main__": - # load logs - lr = list(LogReader(TEST_ROUTE)) - # run replay - out_frames = imgproc_replay(lr) - - all_pix = np.concatenate([np.concatenate([d.flatten() for d in f]) for f in out_frames]) - pix_hash = hashlib.sha1(all_pix).hexdigest() - - with open('imgproc_replay_ref_hash') as f: - ref_hash = f.read() - - if pix_hash != ref_hash: - print("result changed! please check kernel") - print(f"ref: {ref_hash}") - print(f"new: {pix_hash}") - else: - print("test passed") diff --git a/selfdrive/test/process_replay/test_processes.py b/selfdrive/test/process_replay/test_processes.py index 702de4f7d18901..62846f2516b08c 100755 --- a/selfdrive/test/process_replay/test_processes.py +++ b/selfdrive/test/process_replay/test_processes.py @@ -1,237 +1,1396 @@ #!/usr/bin/env python3 import argparse import concurrent.futures +import hashlib +import json +import math import os +import re +import shutil +import stat import sys -from collections import defaultdict +import time +import traceback +from collections import Counter, defaultdict +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from pathlib import Path +from types import MappingProxyType +from typing import Any, Literal +from urllib.request import Request, urlopen + +import zstandard as zstd from tqdm import tqdm -from typing import Any from opendbc.car.car_helpers import interface_names from openpilot.common.git import get_commit -from openpilot.tools.lib.openpilotci import get_url, upload_file +from openpilot.common.params import ParamKeyType, Params +from openpilot.common.utils import atomic_write from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs, format_diff -from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, PROC_REPLAY_DIR, FAKEDATA, replay_process, \ - check_openpilot_enabled, check_most_messages_valid +from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, FAKEDATA, PROC_REPLAY_DIR, check_most_messages_valid, \ + replay_process from openpilot.tools.lib.filereader import FileReader from openpilot.tools.lib.logreader import LogReader, save_log +from openpilot.tools.lib.openpilotci import get_url +from openpilot.tools.lib.url_file import URLFile, URLFileException + +RESULTS_SCHEMA_VERSION = 1 +CASE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$") +EXCLUDED_PROCS = frozenset({"modeld", "dmonitoringmodeld"}) +ALWAYS_PROCS = ("card", "controlsd", "lagd") +EXTRA_PROCS = ( + "selfdrived", "radard", "plannerd", "calibrationd", "dmonitoringd", + "locationd", "paramsd", "ubloxd", "torqued", +) +PREAP_PROCS = ("card", "controlsd", "selfdrived", "radard", "plannerd", "lagd") +ALL_REPLAY_PROCS = tuple(cfg.proc_name for cfg in CONFIGS if cfg.proc_name not in EXCLUDED_PROCS) +PROC_BY_NAME = {cfg.proc_name: cfg for cfg in CONFIGS if cfg.proc_name not in EXCLUDED_PROCS} + +ARTIFACTS_REPO = "NotAutopilot/ci-artifacts" +ARTIFACTS_BRANCH = "process-replay" +ARTIFACTS_RAW = f"https://raw.githubusercontent.com/{ARTIFACTS_REPO}" +# Keep this list compatible with regen_all.py (imports source_segments as segments). source_segments = [ - ("BODY", "937ccb7243511b65|2022-05-24--16-03-09--1"), # COMMA.COMMA_BODY ("HYUNDAI", "02c45f73a2e5c6e9|2021-01-01--19-08-22--1"), # HYUNDAI.HYUNDAI_SONATA ("HYUNDAI2", "d545129f3ca90f28|2022-11-07--20-43-08--3"), # HYUNDAI.HYUNDAI_KIA_EV6 (+ QCOM GPS) ("TOYOTA", "0982d79ebb0de295|2021-01-04--17-13-21--13"), # TOYOTA.TOYOTA_PRIUS ("TOYOTA2", "0982d79ebb0de295|2021-01-03--20-03-36--6"), # TOYOTA.TOYOTA_RAV4 - ("TOYOTA3", "f7d7e3538cda1a2a|2021-08-16--08-55-34--6"), # TOYOTA.TOYOTA_COROLLA_TSS2 + ("TOYOTA3", "8011d605be1cbb77|000000cc--8e8d8ec716--6"), # TOYOTA.TOYOTA_COROLLA_TSS2 ("HONDA", "eb140f119469d9ab|2021-06-12--10-46-24--27"), # HONDA.HONDA_CIVIC (NIDEC) ("HONDA2", "7d2244f34d1bbcda|2021-06-25--12-25-37--26"), # HONDA.HONDA_ACCORD (BOSCH) ("CHRYSLER", "4deb27de11bee626|2021-02-20--11-28-55--8"), # CHRYSLER.CHRYSLER_PACIFICA_2018_HYBRID ("RAM", "17fc16d840fe9d21|2023-04-26--13-28-44--5"), # CHRYSLER.RAM_1500_5TH_GEN ("SUBARU", "341dccd5359e3c97|2022-09-12--10-35-33--3"), # SUBARU.SUBARU_OUTBACK - ("GM", "0c58b6a25109da2b|2021-02-23--16-35-50--11"), # GM.CHEVROLET_VOLT - ("GM2", "376bf99325883932|2022-10-27--13-41-22--1"), # GM.CHEVROLET_BOLT_EUV + ("GM", "376bf99325883932|2022-10-27--13-41-22--1"), # GM.CHEVROLET_BOLT_EUV ("NISSAN", "35336926920f3571|2021-02-12--18-38-48--46"), # NISSAN.NISSAN_XTRAIL ("VOLKSWAGEN", "de9592456ad7d144|2021-06-29--11-00-15--6"), # VOLKSWAGEN.VOLKSWAGEN_GOLF + # FIXME the sensor timings are bad in mazda segment, we're not fully testing it, but it should be replaced ("MAZDA", "bd6a637565e91581|2021-10-30--15-14-53--4"), # MAZDA.MAZDA_CX9_2021 ("FORD", "54827bf84c38b14f|2023-01-26--21-59-07--4"), # FORD.FORD_BRONCO_SPORT_MK1 + ("RIVIAN", "bc095dc92e101734|000000db--ee9fe46e57--1"), # RIVIAN.RIVIAN_R1_GEN1 + ("TESLA", "2c912ca5de3b1ee9|0000025d--6eb6bcbca4--4"), # TESLA.TESLA_MODEL_Y # Enable when port is tested and dashcamOnly is no longer set #("VOLKSWAGEN2", "3cfdec54aa035f3f|2022-07-19--23-45-10--2"), # VOLKSWAGEN.VOLKSWAGEN_PASSAT_NMS ] -segments = [ - ("BODY", "regenA67A128BCD8|2024-08-30--02-36-22--0"), - ("HYUNDAI", "regen9CBD921E93E|2024-08-30--02-38-51--0"), - ("HYUNDAI2", "regen12E0C4EA1A7|2024-08-30--02-42-40--0"), - ("TOYOTA", "regen1CA7A48E6F7|2024-08-30--02-45-08--0"), - ("TOYOTA2", "regen6E484EDAB96|2024-08-30--02-47-37--0"), - ("TOYOTA3", "regen4CE950B0267|2024-08-30--02-51-30--0"), - ("HONDA", "regenC8F0D6ADC5C|2024-08-30--02-54-01--0"), - ("HONDA2", "regen4B38A7428CD|2024-08-30--02-56-31--0"), - ("CHRYSLER", "regenF3DBBA9E8DF|2024-08-30--02-59-03--0"), - ("RAM", "regenDB02684E00A|2024-08-30--03-02-54--0"), - ("SUBARU", "regenAA1FF48CF1F|2024-08-30--03-06-45--0"), - ("GM", "regen720F2BA4CF6|2024-08-30--03-09-15--0"), - ("GM2", "regen9ADBECBCD1C|2024-08-30--03-13-04--0"), - ("NISSAN", "regen58464878D07|2024-08-30--03-15-31--0"), - ("VOLKSWAGEN", "regenED976DEB757|2024-08-30--03-18-02--0"), - ("MAZDA", "regenACF84CCF482|2024-08-30--03-21-55--0"), - ("FORD", "regen6ECC59A6307|2024-08-30--03-25-42--0"), -] - -# dashcamOnly makes don't need to be tested until a full port is done -excluded_interfaces = ["mock"] +# dashcamOnly makes don't need to be tested until a full port is done. +# "mg" is also excluded because xnor-tech's MG ZS EV port doesn't have test +# routes in routes.py yet — inherited from the upstream merge and not used by NAP. +excluded_interfaces = ["mock", "body", "psa", "mg"] -BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" REF_COMMIT_FN = os.path.join(PROC_REPLAY_DIR, "ref_commit") -EXCLUDED_PROCS = {"modeld", "dmonitoringmodeld"} +REF_COMMIT_RE = re.compile(r"^[0-9a-f]{40}$") + +# Audited pre-manifest artifact tree SHA. Remove after the first manifest-backed release lands. +LEGACY_ARTIFACTS_COMMITS: frozenset[str] = frozenset({"2c9cdb739cd53df058130e480fd6a3a23e6c4387"}) + +MAX_GITHUB_REF_BODY_BYTES = 64 * 1024 +MAX_REF_COMMIT_FILE_BYTES = 41 # 40 ASCII hex + optional LF +MAX_MANIFEST_BYTES = 2 * 1024 * 1024 +MAX_SOURCE_COMPRESSED_BYTES = 64 * 1024 * 1024 +MAX_REFERENCE_COMPRESSED_BYTES = 64 * 1024 * 1024 +MAX_LOG_DECOMPRESSED_BYTES = 512 * 1024 * 1024 +MAX_LOG_MESSAGES = 2_000_000 + +_OPEN_NOFOLLOW_FLAGS = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + +ParamValue = bool | int | float +TaskStatus = Literal["pass", "diff", "error"] + + +class ManifestUnavailable(Exception): + """Exact missing/404 for a pinned artifacts object.""" + + +def _freeze_params(params: Mapping[str, ParamValue] | None) -> Mapping[str, ParamValue]: + return MappingProxyType(dict(params or {})) + + +def validate_case_id(case_id: str) -> str: + if not CASE_ID_RE.match(case_id): + raise ValueError(f"invalid case_id {case_id!r}; expected {CASE_ID_RE.pattern}") + return case_id + + +def validate_ref_commit(value: str) -> str: + if not isinstance(value, str) or REF_COMMIT_RE.fullmatch(value) is None: + raise ValueError(f"ref_commit must be a full lowercase SHA1, got {value!r}") + return value + + +def decode_ref_commit_bytes(raw: bytes) -> str: + text = raw.decode("utf-8") + if text.endswith("\n"): + text = text[:-1] + if "\n" in text or "\r" in text: + raise ValueError("ref_commit must be a single line") + return validate_ref_commit(text) + + +def validate_source_metadata( + case_id: str, + executable: bool, + source_bytes: int | None, + source_sha256: str | None, +) -> None: + has_bytes = source_bytes is not None + has_sha = source_sha256 is not None + if has_bytes ^ has_sha: + raise ValueError( + f"{case_id}: partial source metadata is rejected; provide both source_bytes and source_sha256, or neither" + ) + if executable: + if not (has_bytes and has_sha): + raise ValueError(f"{case_id}: executable ReplayCase requires both source_bytes and source_sha256") + if not isinstance(source_bytes, int) or isinstance(source_bytes, bool) or source_bytes <= 0: + raise ValueError(f"{case_id}: source_bytes must be a positive int") + if source_bytes > MAX_SOURCE_COMPRESSED_BYTES: + raise ValueError(f"{case_id}: source_bytes exceeds MAX_SOURCE_COMPRESSED_BYTES") + if not isinstance(source_sha256, str) or not re.fullmatch(r"[0-9a-f]{64}", source_sha256): + raise ValueError(f"{case_id}: source_sha256 must be 64 lowercase hex") + elif has_bytes or has_sha: + raise ValueError(f"{case_id}: pending non-executable descriptors must omit source_bytes and source_sha256") + + +def resolve_regular_member(root: str | os.PathLike[str], filename: str) -> Path: + if filename != os.path.basename(filename) or not filename or filename in {".", ".."}: + raise ValueError(f"ref member filename must be a basename, got {filename!r}") + root_path = Path(root).resolve(strict=True) + if not root_path.is_dir(): + raise ValueError(f"reference root is not a directory: {root_path}") + candidate = root_path / filename + st = os.lstat(candidate) + if stat.S_ISLNK(st.st_mode): + raise ValueError(f"symlink forbidden in reference tree: {candidate}") + if not stat.S_ISREG(st.st_mode): + raise ValueError(f"reference member must be a regular file: {candidate}") + resolved = candidate.resolve(strict=True) + try: + resolved.relative_to(root_path) + except ValueError as exc: + raise ValueError(f"reference member escapes root {root_path}: {resolved}") from exc + return resolved + + +def read_regular_member_bytes(root: str | os.PathLike[str], filename: str, *, max_bytes: int) -> bytes: + path = resolve_regular_member(root, filename) + fd = os.open(path, _OPEN_NOFOLLOW_FLAGS) + try: + st = os.fstat(fd) + if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode): + raise ValueError(f"reference member must stay a regular file: {path}") + data = os.read(fd, max_bytes + 1) + finally: + os.close(fd) + if len(data) > max_bytes: + raise ValueError(f"reference member exceeds {max_bytes} bytes: {path}") + return data + + +def _is_missing_artifact_error(exc: BaseException) -> bool: + if isinstance(exc, ManifestUnavailable): + return True + if isinstance(exc, (URLFileException, AssertionError, FileNotFoundError)): + msg = str(exc).lower() + return any(token in msg for token in ("doesn't exist", "does not exist", "not found", "404")) + return False + + +def read_url_bytes_bounded(url: str, *, max_bytes: int, url_file_cls: type = URLFile) -> bytes: + try: + handle = url_file_cls(url, cache=False) + data = handle.read(max_bytes + 1) + except Exception as exc: + if _is_missing_artifact_error(exc): + raise ManifestUnavailable(str(exc)) from exc + raise + if len(data) > max_bytes: + raise ValueError(f"remote artifact exceeds {max_bytes} bytes: {url}") + return data + + +def decompress_log_bytes(data: bytes, *, max_output_bytes: int = MAX_LOG_DECOMPRESSED_BYTES) -> bytes: + if data.startswith(b"\x28\xb5\x2f\xfd"): + dctx = zstd.ZstdDecompressor() + chunks: list[bytes] = [] + total = 0 + with dctx.stream_reader(data) as reader: + while True: + chunk = reader.read(1024 * 1024) + if not chunk: + break + total += len(chunk) + if total > max_output_bytes: + raise ValueError(f"decompressed log exceeds {max_output_bytes} bytes") + chunks.append(chunk) + return b"".join(chunks) + if data.startswith(b"BZh9"): + import bz2 + if len(data) > MAX_REFERENCE_COMPRESSED_BYTES: + raise ValueError("bz2 payload exceeds compressed bound") + out = bz2.decompress(data) + if len(out) > max_output_bytes: + raise ValueError(f"decompressed log exceeds {max_output_bytes} bytes") + return out + if len(data) > max_output_bytes: + raise ValueError(f"uncompressed log exceeds {max_output_bytes} bytes") + return data + + +def read_reference_bytes(locator: str, *, max_bytes: int = MAX_REFERENCE_COMPRESSED_BYTES, + url_file_cls: type = URLFile) -> bytes: + if locator.startswith(("http://", "https://")): + return read_url_bytes_bounded(locator, max_bytes=max_bytes, url_file_cls=url_file_cls) + root = os.path.dirname(locator) or "." + filename = os.path.basename(locator) + return read_regular_member_bytes(root, filename, max_bytes=max_bytes) + + +def load_ref_log_messages(locator: str, *, expected_bytes: int | None = None, + expected_sha256: str | None = None, + url_file_cls: type = URLFile) -> list[Any]: + max_bytes = expected_bytes if expected_bytes is not None else MAX_REFERENCE_COMPRESSED_BYTES + if expected_bytes is not None and expected_bytes > MAX_REFERENCE_COMPRESSED_BYTES: + raise ValueError("reference declared size exceeds MAX_REFERENCE_COMPRESSED_BYTES") + raw = read_reference_bytes(locator, max_bytes=max_bytes, url_file_cls=url_file_cls) + if expected_bytes is not None and len(raw) != expected_bytes: + raise ValueError(f"reference size mismatch expected={expected_bytes} actual={len(raw)}") + if expected_sha256 is not None: + digest = hashlib.sha256(raw).hexdigest() + if digest != expected_sha256: + raise ValueError(f"reference sha256 mismatch expected={expected_sha256} actual={digest}") + # Always decompress under a hard ceiling, then parse the bounded payload. + if raw.startswith((b"\x28\xb5\x2f\xfd", b"BZh9")): + payload = decompress_log_bytes(raw) + else: + payload = decompress_log_bytes(raw) + lr = LogReader.from_bytes(payload) + out: list[Any] = [] + for msg in lr: + out.append(msg) + if len(out) > MAX_LOG_MESSAGES: + raise ValueError(f"reference log exceeds MAX_LOG_MESSAGES ({MAX_LOG_MESSAGES})") + return out + + +@dataclass(frozen=True) +class ReplayCase: + __hash__ = None + + case_id: str + car_brand: str + source: str + processes: tuple[str, ...] + custom_params: Mapping[str, ParamValue] = field(default_factory=dict) + source_sha256: str | None = None + source_bytes: int | None = None + + def __post_init__(self): + object.__setattr__(self, "custom_params", _freeze_params(self.custom_params)) + object.__setattr__(self, "processes", tuple(self.processes)) + validate_case_id(self.case_id) + unknown = [p for p in self.processes if p not in PROC_BY_NAME] + if unknown: + raise ValueError(f"{self.case_id}: unknown processes {unknown}") + if len(set(self.processes)) != len(self.processes): + raise ValueError(f"{self.case_id}: duplicate processes") + validate_source_metadata(self.case_id, bool(self.source), self.source_bytes, self.source_sha256) + + @property + def executable(self) -> bool: + return bool(self.source) + + def source_url(self) -> str: + if not self.executable: + raise ValueError(f"{self.case_id}: source is not executable") + if self.source.startswith(("http://", "https://")): + return self.source + route, seg_num = self.source.rsplit("--", 1) + return get_url(route, seg_num, "rlog.zst") + + def to_record(self) -> dict[str, Any]: + return { + "case_id": self.case_id, + "car_brand": self.car_brand, + "source": self.source, + "processes": list(self.processes), + "custom_params": dict(self.custom_params), + "source_sha256": self.source_sha256, + "source_bytes": self.source_bytes, + "executable": self.executable, + "params_digest": params_digest(self.custom_params), + } + + +@dataclass(frozen=True) +class ReplayTask: + case: ReplayCase + process: str + + def __post_init__(self): + if self.process not in self.case.processes: + raise ValueError(f"{self.process} not in case {self.case.case_id}") + if self.process not in PROC_BY_NAME: + raise ValueError(f"unknown process {self.process}") + + @property + def task_id(self) -> str: + return f"{self.case.case_id}:{self.process}" + + +@dataclass(frozen=True) +class TaskResult: + status: TaskStatus + task_id: str + elapsed_s: float + diff_or_traceback: str + ref_path: str + new_path: str + message_counts: Mapping[str, int] = field(default_factory=dict) + + def __post_init__(self): + object.__setattr__(self, "message_counts", dict(self.message_counts)) + + def to_record(self) -> dict[str, Any]: + return { + "status": self.status, + "task_id": self.task_id, + "elapsed_s": self.elapsed_s, + "diff_or_traceback": self.diff_or_traceback, + "ref_path": self.ref_path, + "new_path": self.new_path, + "message_counts": dict(self.message_counts), + } + + +# Exact active-source digests measured from the current public route sources. +ACTIVE_SOURCE_DIGESTS: dict[str, dict[str, int | str]] = { + "chrysler": {"bytes": 11951101, "sha256": "a30f65eb1033afbd0cff70d965aa9c0a276cc5ceb73d28baa817430df178009a"}, + "ford": {"bytes": 11315727, "sha256": "786dfef08325d24e8205320862adc940706ff3475ae082ea104127fb5da62823"}, + "gm": {"bytes": 9846869, "sha256": "6c10ce899270e4fc8350730e44cb39dfbda451670dd598798207ffc929baa69a"}, + "honda": {"bytes": 10090147, "sha256": "8ea4ab5412a99bfc65fbe95cd169a54edb6bcb68f6fa20c97f2bc58ed4bba538"}, + "honda2": {"bytes": 10419375, "sha256": "fc9ab2b4fd9702ceb8e3342186076dc6a85dbd6a3bd859ac6b965234bcc65c69"}, + "hyundai": {"bytes": 11873030, "sha256": "0b6734026f7c775f7fd648ef76130f9b9a672c5236c6a328eff31ec9cc3c5343"}, + "hyundai2": {"bytes": 12527194, "sha256": "4cc51a77bf8d128d5720fd692e5a0994c887ee35fdd949cc0ce54d4215e2b7a2"}, + "mazda": {"bytes": 12309353, "sha256": "a84e9f84c39802f58a64031e7c56b362c0e745b5c216848ca2d561f5ae6d440a"}, + "nissan": {"bytes": 11775886, "sha256": "58f3822418e86d8c4afca79ef9058602c8825fadaedf8b63477ed53a2b9ba748"}, + "ram": {"bytes": 11420074, "sha256": "cc1d8bb9729a71c3166e04343e436a67fbc1ff7107a30201a5d13ea9b45ea143"}, + "rivian": {"bytes": 11022997, "sha256": "2f2574c057b7cb55fbb2e05c99c5f1b1d6d894222422c4b51d4363ad66e6c840"}, + "subaru": {"bytes": 9393878, "sha256": "f501c1c99bae27ca710f40f723a1960ea4e898836d7edfb57ea6397591e5aff2"}, + "tesla": {"bytes": 8287366, "sha256": "ca3bfc37b118f0e1987c2177b77b7446d44fbc7806cc5fae71c2ed79d4776fff"}, + "toyota": {"bytes": 10846201, "sha256": "6c028c0d40328fc00fa12acf91dba30d9f152e89d99a7089aadac62f6c7d5d64"}, + "toyota3": {"bytes": 9272538, "sha256": "876100021b13ddd1a39efad5fdb4e7376ad5b298f64bf390b5f58742ffc6e429"}, + "volkswagen": {"bytes": 10593610, "sha256": "bca512375f61ade1af793227f4aa9137ba1cbd0067d3b92f1242f5907f84a0af"}, +} + + +def _legacy_case(case_id: str, car_brand: str, segment: str, full: bool) -> ReplayCase: + processes = ALWAYS_PROCS + (EXTRA_PROCS if full else ()) + digest = ACTIVE_SOURCE_DIGESTS[case_id] + return ReplayCase( + case_id=case_id, + car_brand=car_brand, + source=segment, + processes=processes, + source_bytes=int(digest["bytes"]), + source_sha256=str(digest["sha256"]), + ) + + +ACTIVE_CASES: tuple[ReplayCase, ...] = ( + _legacy_case("hyundai", "HYUNDAI", "regenAA0FC4ED71E|2025-04-08--22-57-50--0", True), + _legacy_case("hyundai2", "HYUNDAI2", "regenAFB9780D823|2025-04-08--23-00-34--0", False), + _legacy_case("toyota", "TOYOTA", "regen218A4DCFAA1|2025-04-08--22-57-51--0", True), + # TODO: get new RAV4 route without enableDsu + # _legacy_case("toyota2", "TOYOTA2", "regen107352E20EB|2025-04-08--22-57-46--0", False), + _legacy_case("toyota3", "TOYOTA3", "regen1455E3B4BDF|2025-04-09--03-26-06--0", False), + _legacy_case("honda", "HONDA", "regenB328FF8BA0A|2025-04-08--22-57-45--0", False), + _legacy_case("honda2", "HONDA2", "regen6170C8C9A35|2025-04-08--22-57-46--0", False), + _legacy_case("chrysler", "CHRYSLER", "regen5B28FC2A437|2025-04-08--23-04-24--0", False), + _legacy_case("ram", "RAM", "regenBF81EA96E08|2025-04-08--23-06-54--0", False), + _legacy_case("subaru", "SUBARU", "regen7366F13F6A1|2025-04-08--23-07-07--0", False), + _legacy_case("gm", "GM", "regen1271097D038|2025-04-09--03-26-00--0", False), + _legacy_case("nissan", "NISSAN", "regen15D60604EAB|2025-04-08--23-06-59--0", False), + _legacy_case("volkswagen", "VOLKSWAGEN", "regen0F2F06C9539|2025-04-08--23-06-56--0", False), + _legacy_case("mazda", "MAZDA", "regenACF84CCF482|2024-08-30--03-21-55--0", False), + _legacy_case("ford", "FORD", "regen755D8CB1E1F|2025-04-08--23-13-43--0", False), + _legacy_case("rivian", "RIVIAN", "regen5FCAC896BBE|2025-04-08--23-13-35--0", False), + _legacy_case("tesla", "TESLA", "2c912ca5de3b1ee9|0000025d--6eb6bcbca4--4", False), +) + +# Compatibility alias for anything still iterating brand/segment pairs. +segments = [(c.car_brand, c.source) for c in ACTIVE_CASES] + +NAP_PREAP_PEDAL_PARAMS: dict[str, ParamValue] = { + "NAPForcePreAP": True, + "NAPAdaptiveAccel": True, + "NAPPedalEnabled": True, + "NAPFollowDistance": 7, + "NAPPedalProfile": 4, + "NAPPedalCanBus": 2, + "NAPPedalCalibDone": True, + "NAPPedalCalibMin": 0.73299810159, + "NAPPedalCalibMax": 110.23299810159, + "NAPPedalCalibFactor": 0.9478672985781991, + "NAPPedalCalibZero": 4.732998101589998, + "NAPRadarEnabled": True, + "NAPRadarBehindNosecone": True, + "NAPRadarOffset": -0.5, + "NAPiBoosterEnabled": False, + "NAPBrakeFactor": 1.0, +} + +NAP_PREAP_NO_PEDAL_PARAMS: dict[str, ParamValue] = { + **NAP_PREAP_PEDAL_PARAMS, + "NAPPedalEnabled": False, + "NAPFollowDistance": 5, + "NAPPedalCalibMin": 0.9382172261100007, + "NAPPedalCalibMax": 110.43821722611, + "NAPPedalCalibFactor": 0.946969696969697, + "NAPPedalCalibZero": 4.838217226109999, + "NAPRadarOffset": -0.25, +} + +# Temporary staged descriptors for rollout PR A. Sources stay non-executable until fixture publish. +PENDING_CASES: tuple[ReplayCase, ...] = ( + ReplayCase( + case_id="nap-preap-pedal-v1", + car_brand="TESLA", + source="", + processes=PREAP_PROCS, + custom_params=NAP_PREAP_PEDAL_PARAMS, + ), + ReplayCase( + case_id="nap-preap-no-pedal-v1", + car_brand="TESLA", + source="", + processes=PREAP_PROCS, + custom_params=NAP_PREAP_NO_PEDAL_PARAMS, + ), +) + +EMPTY_PARAMS_DIGEST = "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570" +NAP_PREAP_PEDAL_PARAMS_DIGEST = "b5217b239c759d5a960872a99f2e9ff6cacdb37aff6e99e1ee1bd0c20dead809" +NAP_PREAP_NO_PEDAL_PARAMS_DIGEST = "96b5f9f76bdf20f24bf2a29d408d87e60ebf377eccc3858b4f0c0de7c3c2e786" + + +def params_type_name(value: ParamValue) -> str: + if type(value) is bool: + return "bool" + if type(value) is int: + return "int" + if type(value) is float: + return "float" + raise TypeError(f"unsupported param value type {type(value)!r}") + + +def canonical_params_manifest(params: Mapping[str, ParamValue]) -> bytes: + """Canonical JSON array sorted by key: key/type/value with fixed separators and trailing LF.""" + parts: list[str] = [] + for key in sorted(params): + value = params[key] + type_name = params_type_name(value) + if type_name == "bool": + encoded = "true" if value else "false" + elif type_name == "int": + encoded = str(value) + else: + if not isinstance(value, float) or not math.isfinite(value): + raise ValueError(f"param {key} must be a finite float") + encoded = repr(value) + parts.append(f'{{"key":"{key}","type":"{type_name}","value":{encoded}}}') + return ("[" + ",".join(parts) + "]\n").encode("utf-8") + + +def params_digest(params: Mapping[str, ParamValue]) -> str: + return hashlib.sha256(canonical_params_manifest(params)).hexdigest() + + +def expected_param_key_type(value: ParamValue) -> ParamKeyType: + return { + "bool": ParamKeyType.BOOL, + "int": ParamKeyType.INT, + "float": ParamKeyType.FLOAT, + }[params_type_name(value)] + + +def validate_params_against_header(params: Mapping[str, ParamValue], params_obj: Params | None = None) -> None: + checker = params_obj or Params() + for key, value in params.items(): + declared = checker.get_type(key) + expected = expected_param_key_type(value) + if declared != expected: + raise TypeError(f"param {key}: value type {type(value)!r} does not match header type {declared!r}") + + +def build_tasks(cases: Iterable[ReplayCase]) -> list[ReplayTask]: + return [ReplayTask(case=case, process=proc) for case in cases for proc in case.processes] + + +def select_cases(inventory: Literal["active", "staged"] = "active") -> tuple[ReplayCase, ...]: + if inventory == "active": + return ACTIVE_CASES + if inventory == "staged": + return ACTIVE_CASES + PENDING_CASES + raise ValueError(f"unknown inventory {inventory!r}") + + +def assert_inventory_invariants(cases: Iterable[ReplayCase]) -> None: + cases = tuple(cases) + case_ids = [c.case_id for c in cases] + if len(case_ids) != len(set(case_ids)): + raise AssertionError(f"duplicate case_ids: {case_ids}") + tasks = build_tasks(cases) + task_ids = [t.task_id for t in tasks] + if len(task_ids) != len(set(task_ids)): + raise AssertionError(f"duplicate task_ids: {task_ids}") + for case in cases: + validate_source_metadata(case.case_id, case.executable, case.source_bytes, case.source_sha256) + validate_params_against_header(case.custom_params) + for key in case.custom_params: + if not key: + raise AssertionError("empty param key") + + +def unique_cases_by_id(tasks: Iterable[ReplayTask]) -> dict[str, ReplayCase]: + """Deterministic case_id deduplication; never hash ReplayCase (custom_params is unhashable).""" + out: dict[str, ReplayCase] = {} + for task in tasks: + existing = out.get(task.case.case_id) + if existing is None: + out[task.case.case_id] = task.case + elif existing != task.case: + raise AssertionError(f"conflicting ReplayCase records for case_id={task.case.case_id}") + return out + + +def filter_tasks( + tasks: Iterable[ReplayTask], + *, + whitelist_procs: Iterable[str] | None = None, + blacklist_procs: Iterable[str] | None = None, + whitelist_cars: Iterable[str] | None = None, + blacklist_cars: Iterable[str] | None = None, +) -> list[ReplayTask]: + all_procs = {t.process for t in tasks} or set(ALL_REPLAY_PROCS) + all_cars = {t.case.car_brand for t in tasks} + tested_procs = set(whitelist_procs if whitelist_procs is not None else all_procs) - set(blacklist_procs or []) + tested_cars = {c.upper() for c in (whitelist_cars if whitelist_cars is not None else all_cars)} - {c.upper() for c in (blacklist_cars or [])} + return [t for t in tasks if t.process in tested_procs and t.case.car_brand.upper() in tested_cars] + + +def shard_task_ids(tasks: Iterable[ReplayTask], shard: Literal["card", "controlsd", "lagd", "other"]) -> list[str]: + if shard == "other": + blocked = {"card", "controlsd", "lagd"} + return [t.task_id for t in tasks if t.process not in blocked] + return [t.task_id for t in tasks if t.process == shard] -def run_test_process(data): - segment, cfg, args, cur_log_fn, ref_log_path, lr_dat = data - res = None - if not args.upload_only: - lr = LogReader.from_bytes(lr_dat) - res, log_msgs = test_process(cfg, lr, segment, ref_log_path, cur_log_fn, args.ignore_fields, args.ignore_msgs) - # save logs so we can upload when updating refs - save_log(cur_log_fn, log_msgs) +def ref_filename(case_id: str, process: str, ref_commit: str) -> str: + validate_case_id(case_id) + validate_ref_commit(ref_commit) + return f"{case_id}__{process}__{ref_commit}.zst" - if args.update_refs or args.upload_only: - print(f'Uploading: {os.path.basename(cur_log_fn)}') - assert os.path.exists(cur_log_fn), f"Cannot find log to upload: {cur_log_fn}" - upload_file(cur_log_fn, os.path.basename(cur_log_fn)) - os.remove(cur_log_fn) - return (segment, cfg.proc_name, res) +def legacy_ref_filename(segment: str, process: str, ref_commit: str) -> str: + validate_ref_commit(ref_commit) + return f"{segment}_{process}_{ref_commit}.zst".replace("|", "_") -def get_log_data(segment): - r, n = segment.rsplit("--", 1) - with FileReader(get_url(r, n, "rlog.zst")) as f: - return (segment, f.read()) +def pin_artifacts_commit(branch: str = ARTIFACTS_BRANCH, opener: Callable[..., Any] = urlopen) -> str: + req = Request(f"https://api.github.com/repos/{ARTIFACTS_REPO}/git/ref/heads/{branch}", headers={"Accept": "application/vnd.github+json"}) + with opener(req, timeout=30) as resp: + body = resp.read(MAX_GITHUB_REF_BODY_BYTES + 1) + if len(body) > MAX_GITHUB_REF_BODY_BYTES: + raise ValueError("GitHub ref response exceeds MAX_GITHUB_REF_BODY_BYTES") + payload = json.loads(body.decode("utf-8")) + sha = payload["object"]["sha"] + return validate_ref_commit(sha) -def test_process(cfg, lr, segment, ref_log_path, new_log_path, ignore_fields=None, ignore_msgs=None): + +def artifacts_file_url(artifacts_commit: str, filename: str) -> str: + if not re.fullmatch(r"[0-9a-f]{40}", artifacts_commit): + raise ValueError(f"artifacts commit must be a full SHA, got {artifacts_commit!r}") + return f"{ARTIFACTS_RAW}/{artifacts_commit}/{filename}" + + +def resolve_ref_commit( + artifacts_commit: str | None = None, + ref_commit_path: str = REF_COMMIT_FN, + *, + reference_dir: str | None = None, + pin_fn: Callable[..., str] = pin_artifacts_commit, + url_file_cls: type = URLFile, +) -> tuple[str, str | None]: + if reference_dir is not None: + raw = read_regular_member_bytes(reference_dir, "ref_commit", max_bytes=MAX_REF_COMMIT_FILE_BYTES) + return decode_ref_commit_bytes(raw), artifacts_commit + + if os.path.lexists(ref_commit_path): + root = os.path.dirname(ref_commit_path) or "." + raw = read_regular_member_bytes(root, os.path.basename(ref_commit_path), max_bytes=MAX_REF_COMMIT_FILE_BYTES) + return decode_ref_commit_bytes(raw), artifacts_commit + + if artifacts_commit is None: + artifacts_commit = pin_fn() + validate_ref_commit(artifacts_commit) + raw = read_url_bytes_bounded( + artifacts_file_url(artifacts_commit, "ref_commit"), + max_bytes=MAX_REF_COMMIT_FILE_BYTES, + url_file_cls=url_file_cls, + ) + return decode_ref_commit_bytes(raw), artifacts_commit + + +def write_candidate_ref_commit(ref_commit: str, candidate_dir: str = FAKEDATA) -> str: + """Write candidate ref_commit beside generated refs so a copied tree is reusable with --reference-dir.""" + validate_ref_commit(ref_commit) + os.makedirs(candidate_dir, exist_ok=True) + path = os.path.join(candidate_dir, "ref_commit") + with atomic_write(path, mode="w", encoding="utf-8", overwrite=True) as f: + f.write(ref_commit) + f.write("\n") + return path + + +def parse_artifacts_manifest( + raw: bytes, + *, + expected_ref_commit: str, + selected_task_ids: Iterable[str] | None = None, +) -> dict[str, Any]: + if not raw: + raise ValueError("malformed artifacts manifest: empty body") + try: + payload = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f"malformed artifacts manifest: {exc}") from exc + if not isinstance(payload, dict): + raise ValueError("malformed artifacts manifest: expected object") + schema_version = payload.get("schema_version") + if schema_version != 1: + raise ValueError(f"unsupported artifacts manifest schema_version: {schema_version!r}") + manifest_ref = payload.get("ref_commit", payload.get("openpilot_sha")) + if manifest_ref != expected_ref_commit: + raise ValueError( + f"artifacts manifest ref identity mismatch: expected {expected_ref_commit}, got {manifest_ref!r}" + ) + refs = payload.get("refs") + if not isinstance(refs, dict): + raise ValueError("malformed artifacts manifest: refs must be an object") + for task_id, meta in refs.items(): + if not isinstance(task_id, str) or ":" not in task_id: + raise ValueError(f"malformed artifacts manifest task id: {task_id!r}") + if not isinstance(meta, dict): + raise ValueError(f"malformed artifacts manifest refs[{task_id!r}]") + filename = meta.get("filename") + size = meta.get("size", meta.get("bytes")) + sha256 = meta.get("sha256") + if not isinstance(filename, str) or filename != os.path.basename(filename): + raise ValueError(f"malformed artifacts manifest filename for {task_id}") + if size is not None: + if not isinstance(size, int) or isinstance(size, bool) or size <= 0 or size > MAX_REFERENCE_COMPRESSED_BYTES: + raise ValueError(f"malformed artifacts manifest size for {task_id}") + if sha256 is not None and (not isinstance(sha256, str) or not re.fullmatch(r"[0-9a-f]{64}", sha256)): + raise ValueError(f"malformed artifacts manifest sha256 for {task_id}") + if selected_task_ids is not None: + missing = [tid for tid in selected_task_ids if tid not in refs] + if missing: + raise ValueError(f"artifacts manifest missing task metadata for {missing[0]}") + return payload + + +def load_artifacts_manifest( + artifacts_commit: str, + *, + expected_ref_commit: str, + selected_task_ids: Iterable[str] | None = None, + url_file_cls: type = URLFile, +) -> dict[str, Any] | None: + """Load pinned manifest.json once. + + Returns None only for an exact missing manifest on an allowlisted pre-bootstrap commit. + """ + validate_ref_commit(artifacts_commit) + validate_ref_commit(expected_ref_commit) + url = artifacts_file_url(artifacts_commit, "manifest.json") + try: + raw = read_url_bytes_bounded(url, max_bytes=MAX_MANIFEST_BYTES, url_file_cls=url_file_cls) + except ManifestUnavailable as error: + if artifacts_commit in LEGACY_ARTIFACTS_COMMITS: + return None + raise ValueError(f"artifacts manifest missing for non-legacy commit {artifacts_commit}") from error + return parse_artifacts_manifest( + raw, + expected_ref_commit=expected_ref_commit, + selected_task_ids=selected_task_ids, + ) + + +def resolve_ref_path( + task: ReplayTask, + *, + ref_commit: str, + artifacts_commit: str | None, + reference_dir: str | None, + update_refs: bool, + artifacts_manifest: dict[str, Any] | None = None, + pin_fn: Callable[..., str] = pin_artifacts_commit, +) -> str: + if update_refs: + # Candidate generation does not read an existing reference. + return "" + + validate_ref_commit(ref_commit) + new_name = ref_filename(task.case.case_id, task.process, ref_commit) + legacy_name = None + if task.case.source and not task.case.source.startswith(("http://", "https://")): + legacy_name = legacy_ref_filename(task.case.source, task.process, ref_commit) + + def _local_regular(root: str, filename: str) -> str | None: + try: + return str(resolve_regular_member(root, filename)) + except FileNotFoundError: + return None + + # A local candidate tree is authoritative. In particular, do not consult + # FAKEDATA when --reference-dir points at a copied candidate tree. + if reference_dir is not None: + Path(reference_dir).resolve(strict=True) # must exist as a real directory + found = _local_regular(reference_dir, new_name) + if found is None and legacy_name is not None: + found = _local_regular(reference_dir, legacy_name) + if found is not None: + return found + # Caller asked for a local candidate tree; do not silently fall back to remote. + return str(Path(reference_dir).resolve(strict=True) / new_name) + + # Default workspace: only accept regular non-symlink members under FAKEDATA. + if os.path.isdir(FAKEDATA): + found = _local_regular(FAKEDATA, new_name) + if found is None and legacy_name is not None: + found = _local_regular(FAKEDATA, legacy_name) + if found is not None: + return found + + if artifacts_commit is None: + artifacts_commit = pin_fn() + validate_ref_commit(artifacts_commit) + + if artifacts_manifest is not None: + refs = artifacts_manifest.get("refs") + if not isinstance(refs, dict): + raise ValueError("malformed artifacts manifest: refs must be an object") + meta = refs.get(task.task_id) + if not isinstance(meta, dict): + raise ValueError(f"artifacts manifest missing task metadata for {task.task_id}") + filename = meta.get("filename") + if filename != new_name: + raise ValueError( + f"artifacts manifest has non-canonical filename for {task.task_id}: expected {new_name!r}, got {filename!r}" + ) + return artifacts_file_url(artifacts_commit, new_name) + + # Pre-bootstrap trees have no manifest. Only allowlisted commits may use + # the historical segment filename; once a manifest exists it is canonical. + if artifacts_commit not in LEGACY_ARTIFACTS_COMMITS: + raise ValueError( + f"artifacts commit {artifacts_commit} has no manifest and is not in LEGACY_ARTIFACTS_COMMITS" + ) + if legacy_name is not None: + return artifacts_file_url(artifacts_commit, legacy_name) + return artifacts_file_url(artifacts_commit, new_name) + + +def new_log_path(task: ReplayTask, tested_commit: str, output_dir: str | None = None) -> str: + # output_dir is accepted for tests only; normal main keeps generated logs in FAKEDATA. + validate_ref_commit(tested_commit) + base = output_dir or FAKEDATA + os.makedirs(base, exist_ok=True) + return os.path.join(base, ref_filename(task.case.case_id, task.process, tested_commit)) + + +def clear_stale_fakedata(path: str = FAKEDATA) -> None: + if os.path.isdir(path): + shutil.rmtree(path) + os.makedirs(path, exist_ok=True) + + +def download_case_bytes(case: ReplayCase) -> bytes: + if not case.executable: + raise ValueError(f"{case.case_id}: refusing to download non-executable pending source") + if case.source_bytes is None or case.source_sha256 is None: + raise ValueError(f"{case.case_id}: executable source requires size and sha256") + if case.source_bytes > MAX_SOURCE_COMPRESSED_BYTES: + raise ValueError(f"{case.case_id}: source_bytes exceeds MAX_SOURCE_COMPRESSED_BYTES") + with FileReader(case.source_url()) as f: + data = f.read(case.source_bytes + 1) + if len(data) != case.source_bytes: + raise ValueError(f"{case.case_id}: size mismatch expected={case.source_bytes} actual={len(data)}") + digest = hashlib.sha256(data).hexdigest() + if digest != case.source_sha256: + raise ValueError(f"{case.case_id}: sha256 mismatch expected={case.source_sha256} actual={digest}") + return data + + +def download_case_by_id(case_payload: dict[str, Any]) -> tuple[str, bytes | None, str | None]: + case_id = case_payload["case_id"] + try: + case = ReplayCase( + case_id=case_payload["case_id"], + car_brand=case_payload["car_brand"], + source=case_payload["source"], + processes=tuple(case_payload["processes"]), + custom_params=case_payload["custom_params"], + source_sha256=case_payload.get("source_sha256"), + source_bytes=case_payload.get("source_bytes"), + ) + return case_id, download_case_bytes(case), None + except Exception: + return case_id, None, traceback.format_exc() + + +def message_counts(log_msgs: Iterable[Any]) -> dict[str, int]: + return dict(Counter(m.which() for m in log_msgs)) + + +def test_process(cfg, lr, task: ReplayTask, ref_log_path: str, new_log_path: str, ignore_fields=None, ignore_msgs=None, + update_refs: bool = False) -> tuple[TaskStatus, str, list[Any]]: if ignore_fields is None: ignore_fields = [] if ignore_msgs is None: ignore_msgs = [] - ref_log_msgs = list(LogReader(ref_log_path)) - - try: - log_msgs = replay_process(cfg, lr, disable_progress=True) - except Exception as e: - raise Exception("failed on segment: " + segment) from e + log_msgs = replay_process(cfg, lr, disable_progress=True, custom_params=dict(task.case.custom_params)) + # Persist immediately so missing/corrupt refs still retain the generated log. + save_log(new_log_path, log_msgs) - # check to make sure openpilot is engaged in the route - if cfg.proc_name == "controlsd": - if not check_openpilot_enabled(log_msgs): - return f"Route did not enable at all or for long enough: {new_log_path}", log_msgs if not check_most_messages_valid(log_msgs): - return f"Route did not have enough valid messages: {new_log_path}", log_msgs + return "error", f"Route did not have enough valid messages: {new_log_path}", log_msgs - # skip this check if the segment is using qcom gps - if cfg.proc_name != 'ubloxd' or any(m.which() in cfg.pubs for m in lr): + if cfg.proc_name != "ubloxd" or any(m.which() in cfg.pubs for m in lr): seen_msgs = {m.which() for m in log_msgs} expected_msgs = set(cfg.subs) if seen_msgs != expected_msgs: - return f"Expected messages: {expected_msgs}, but got: {seen_msgs}", log_msgs + return "error", f"Expected messages: {expected_msgs}, but got: {seen_msgs}", log_msgs + + if update_refs or not ref_log_path: + return "pass", "", log_msgs try: - return compare_logs(ref_log_msgs, log_msgs, ignore_fields + cfg.ignore, ignore_msgs, cfg.tolerance), log_msgs + ref_log_msgs = load_ref_log_messages(ref_log_path) + diff = compare_logs(ref_log_msgs, log_msgs, ignore_fields + cfg.ignore, ignore_msgs, cfg.tolerance) except Exception as e: - return str(e), log_msgs + return "error", str(e), log_msgs + if isinstance(diff, str) or len(diff): + return "diff", diff if isinstance(diff, str) else json.dumps([list(x) if not isinstance(x, str) else x for x in diff], default=str), log_msgs + return "pass", "", log_msgs -if __name__ == "__main__": - all_cars = {car for car, _ in segments} - all_procs = {cfg.proc_name for cfg in CONFIGS if cfg.proc_name not in EXCLUDED_PROCS} +def run_test_process(data: dict[str, Any]) -> TaskResult: + task_id = data["task_id"] + ref_path = data.get("ref_log_path", "") + new_path = data.get("new_log_path", "") + started = time.perf_counter() + try: + case = ReplayCase( + case_id=data["case_id"], + car_brand=data["car_brand"], + source=data["source"], + processes=tuple(data["processes"]), + custom_params=data["custom_params"], + source_sha256=data.get("source_sha256"), + source_bytes=data.get("source_bytes"), + ) + task = ReplayTask(case=case, process=data["process"]) + cfg = PROC_BY_NAME[task.process] + raw = data["lr_dat"] + if not isinstance(raw, (bytes, bytearray)): + raise TypeError("lr_dat must be bytes") + if len(raw) > MAX_SOURCE_COMPRESSED_BYTES: + raise ValueError("source payload exceeds MAX_SOURCE_COMPRESSED_BYTES") + if raw.startswith((b"\x28\xb5\x2f\xfd", b"BZh9")): + lr = LogReader.from_bytes(decompress_log_bytes(bytes(raw))) + else: + if len(raw) > MAX_LOG_DECOMPRESSED_BYTES: + raise ValueError("uncompressed source exceeds MAX_LOG_DECOMPRESSED_BYTES") + lr = LogReader.from_bytes(bytes(raw)) + status, detail, log_msgs = test_process( + cfg, lr, task, ref_path, new_path, + ignore_fields=data.get("ignore_fields") or [], + ignore_msgs=data.get("ignore_msgs") or [], + update_refs=bool(data.get("update_refs")), + ) + if status == "diff" and not isinstance(detail, str): + detail = str(detail) + return TaskResult( + status=status, + task_id=task_id, + elapsed_s=time.perf_counter() - started, + diff_or_traceback=detail if isinstance(detail, str) else str(detail), + ref_path=ref_path, + new_path=new_path, + message_counts=message_counts(log_msgs), + ) + except Exception: + return TaskResult( + status="error", + task_id=task_id, + elapsed_s=time.perf_counter() - started, + diff_or_traceback=traceback.format_exc(), + ref_path=ref_path, + new_path=new_path, + message_counts={}, + ) + + +def make_task_payload(task: ReplayTask, *, lr_dat: bytes, ref_log_path: str, new_log_path: str, + ignore_fields: list[str], ignore_msgs: list[str], update_refs: bool) -> dict[str, Any]: + return { + "task_id": task.task_id, + "case_id": task.case.case_id, + "car_brand": task.case.car_brand, + "source": task.case.source, + "processes": list(task.case.processes), + "custom_params": dict(task.case.custom_params), + "source_sha256": task.case.source_sha256, + "source_bytes": task.case.source_bytes, + "process": task.process, + "lr_dat": lr_dat, + "ref_log_path": ref_log_path, + "new_log_path": new_log_path, + "ignore_fields": ignore_fields, + "ignore_msgs": ignore_msgs, + "update_refs": update_refs, + } + + +def format_diff_text(results: list[TaskResult], ref_commit: str) -> tuple[str, str, bool]: + legacy_results: dict[str, dict[str, Any]] = defaultdict(dict) + log_paths: dict[str, dict[str, dict[str, str]]] = defaultdict(lambda: defaultdict(dict)) + for result in results: + case_id, proc = result.task_id.split(":", 1) + if result.status == "pass": + legacy_results[case_id][proc] = [] + elif result.status == "diff": + legacy_results[case_id][proc] = result.diff_or_traceback + else: + legacy_results[case_id][proc] = result.diff_or_traceback + log_paths[case_id][proc]["ref"] = result.ref_path + log_paths[case_id][proc]["new"] = result.new_path + return format_diff(legacy_results, log_paths, ref_commit) + + +def build_results_document( + *, + tested_commit: str, + ref_commit: str, + artifacts_commit: str | None, + inventory: str, + cases: Iterable[ReplayCase], + expected_task_ids: Iterable[str], + results: Mapping[str, TaskResult], +) -> dict[str, Any]: + expected = sorted(expected_task_ids) + settled = [results[tid] for tid in expected if tid in results] + status_counts = Counter(r.status for r in settled) + incomplete = [tid for tid in expected if tid not in results] + return { + "schema_version": RESULTS_SCHEMA_VERSION, + "tested_commit": tested_commit, + "ref_commit": ref_commit, + "artifacts_commit": artifacts_commit, + "inventory": inventory, + "cases": [c.to_record() for c in cases], + "expected_task_ids": expected, + "completed_task_ids": sorted(results), + "incomplete_task_ids": incomplete, + "status_counts": { + "pass": status_counts.get("pass", 0), + "diff": status_counts.get("diff", 0), + "error": status_counts.get("error", 0), + "incomplete": len(incomplete), + }, + "results": [results[tid].to_record() for tid in sorted(results)], + } + + +def write_diagnostics(output_dir: str, document: dict[str, Any], results: list[TaskResult], ref_commit: str) -> None: + os.makedirs(output_dir, exist_ok=True) + results_path = os.path.join(output_dir, "results.json") + diff_path = os.path.join(output_dir, "diff.txt") + with atomic_write(results_path, mode="w", encoding="utf-8", overwrite=True) as f: + json.dump(document, f, indent=2, sort_keys=True) + f.write("\n") + diff_short, diff_long, _ = format_diff_text(results, ref_commit) + with atomic_write(diff_path, mode="w", encoding="utf-8", overwrite=True) as f: + f.write(diff_long) + if not diff_long.endswith("\n"): + f.write("\n") + return + + +def retain_failed_logs(results: Iterable[TaskResult]) -> None: + for result in results: + if not result.new_path: + continue + if result.status == "pass": + if os.path.exists(result.new_path): + os.remove(result.new_path) + # failed/diff logs are retained + + +def run_task_pool( + payloads: list[dict[str, Any]], + *, + jobs: int, + worker: Callable[[dict[str, Any]], TaskResult] = run_test_process, + on_settled: Callable[[TaskResult], None] | None = None, + executor_factory=concurrent.futures.ProcessPoolExecutor, +) -> list[TaskResult]: + results: list[TaskResult] = [] + if not payloads: + return results + + with executor_factory(max_workers=max(jobs, 1)) as pool: + future_map = {pool.submit(worker, payload): payload for payload in payloads} + for fut in concurrent.futures.as_completed(future_map): + payload = future_map[fut] + try: + result = fut.result() + except Exception: + result = TaskResult( + status="error", + task_id=payload["task_id"], + elapsed_s=0.0, + diff_or_traceback=traceback.format_exc(), + ref_path=payload.get("ref_log_path", ""), + new_path=payload.get("new_log_path", ""), + ) + results.append(result) + if on_settled is not None: + on_settled(result) + return results + + +def exit_code_for(document: dict[str, Any]) -> int: + counts = document["status_counts"] + if counts["diff"] or counts["error"] or counts["incomplete"]: + return 1 + return 0 + + +def main( + argv: list[str] | None = None, + *, + get_commit_fn: Callable[[], str | None] = get_commit, + pin_artifacts_commit_fn: Callable[..., str] = pin_artifacts_commit, + resolve_ref_commit_fn: Callable[..., tuple[str, str | None]] = resolve_ref_commit, + load_artifacts_manifest_fn: Callable[..., dict[str, Any] | None] = load_artifacts_manifest, + download_case_by_id_fn: Callable[[dict[str, Any]], tuple[str, bytes | None, str | None]] = download_case_by_id, + run_task_pool_fn: Callable[..., list[TaskResult]] = run_task_pool, + clear_stale_fakedata_fn: Callable[..., None] = clear_stale_fakedata, + write_candidate_ref_commit_fn: Callable[..., str] = write_candidate_ref_commit, + interface_names_fn: Callable[[], set[str]] | None = None, +) -> int: + all_cars = {c.car_brand for c in ACTIVE_CASES} + all_procs = set(ALL_REPLAY_PROCS) cpu_count = os.cpu_count() or 1 parser = argparse.ArgumentParser(description="Regression test to identify changes in a process's output") - parser.add_argument("--whitelist-procs", type=str, nargs="*", default=all_procs, + parser.add_argument("--whitelist-procs", type=str, nargs="*", default=None, help="Whitelist given processes from the test (e.g. controlsd)") - parser.add_argument("--whitelist-cars", type=str, nargs="*", default=all_cars, + parser.add_argument("--whitelist-cars", type=str, nargs="*", default=None, help="Whitelist given cars from the test (e.g. HONDA)") parser.add_argument("--blacklist-procs", type=str, nargs="*", default=[], help="Blacklist given processes from the test (e.g. controlsd)") parser.add_argument("--blacklist-cars", type=str, nargs="*", default=[], help="Blacklist given cars from the test (e.g. HONDA)") parser.add_argument("--ignore-fields", type=str, nargs="*", default=[], - help="Extra fields or msgs to ignore (e.g. carState.events)") + help="Extra fields or msgs to ignore (e.g. driverMonitoringState.events)") parser.add_argument("--ignore-msgs", type=str, nargs="*", default=[], help="Msgs to ignore (e.g. carEvents)") parser.add_argument("--update-refs", action="store_true", - help="Updates reference logs using current commit") - parser.add_argument("--upload-only", action="store_true", - help="Skips testing processes and uploads logs from previous test run") + help="Write candidate reference logs for the selected tasks") + parser.add_argument("--inventory", choices=("active", "staged"), default="active", + help="Case inventory to use (staged includes PENDING_CASES)") + parser.add_argument("--list-cases", action="store_true", help="Print selected source case records as JSON and exit") + parser.add_argument("--list-tasks", action="store_true", help="Print selected canonical task IDs and exit") + parser.add_argument("--output-dir", type=str, default=PROC_REPLAY_DIR, + help="Directory for diff.txt and results.json") + parser.add_argument("--reference-dir", type=str, default=None, + help="Local directory of already-generated candidate refs") parser.add_argument("-j", "--jobs", type=int, default=max(cpu_count - 2, 1), help="Max amount of parallel jobs") - args = parser.parse_args() + args = parser.parse_args(argv) - tested_procs = set(args.whitelist_procs) - set(args.blacklist_procs) - tested_cars = set(args.whitelist_cars) - set(args.blacklist_cars) - tested_cars = {c.upper() for c in tested_cars} + cases = select_cases(args.inventory) + assert_inventory_invariants(cases) + tasks = filter_tasks( + build_tasks(cases), + whitelist_procs=args.whitelist_procs if args.whitelist_procs is not None else all_procs, + blacklist_procs=args.blacklist_procs, + whitelist_cars=args.whitelist_cars if args.whitelist_cars is not None else all_cars, + blacklist_cars=args.blacklist_cars, + ) - full_test = (tested_procs == all_procs) and (tested_cars == all_cars) and all(len(x) == 0 for x in (args.ignore_fields, args.ignore_msgs)) - upload = args.update_refs or args.upload_only - os.makedirs(os.path.dirname(FAKEDATA), exist_ok=True) + if args.list_cases: + print(json.dumps([c.to_record() for c in cases], indent=2, sort_keys=True)) + return 0 + if args.list_tasks: + for task_id in sorted(t.task_id for t in tasks): + print(task_id) + return 0 - if upload: - assert full_test, "Need to run full test when updating refs" + tested_procs = {t.process for t in tasks} + tested_cars = {t.case.car_brand for t in tasks} + full_test = ( + args.inventory == "active" + and tested_procs == all_procs + and tested_cars == all_cars + and not args.ignore_fields + and not args.ignore_msgs + and args.whitelist_procs is None + and args.whitelist_cars is None + and not args.blacklist_procs + and not args.blacklist_cars + ) + if args.update_refs and args.reference_dir is not None: + raise SystemExit("--update-refs cannot use --reference-dir") + + expected_task_ids = sorted(t.task_id for t in tasks) + settled: dict[str, TaskResult] = {} + cur_commit = "" + ref_commit = "" + artifacts_commit: str | None = None + artifacts_manifest: dict[str, Any] | None = None + + # Diagnostics are an artifact in their own right. Create them before any + # commit lookup, cleanup, or network operation so setup failures are visible. + os.makedirs(args.output_dir, exist_ok=True) + + def flush() -> dict[str, Any]: + doc = build_results_document( + tested_commit=cur_commit, + ref_commit=ref_commit, + artifacts_commit=artifacts_commit, + inventory=args.inventory, + cases=cases, + expected_task_ids=expected_task_ids, + results=settled, + ) + write_diagnostics(args.output_dir, doc, list(settled.values()), ref_commit) + return doc + + def settle(result: TaskResult) -> dict[str, Any]: + settled[result.task_id] = result + return flush() + + def settle_all(message: str) -> dict[str, Any]: + doc = None + for task in tasks: + if task.task_id in settled: + continue + doc = settle(TaskResult( + status="error", + task_id=task.task_id, + elapsed_s=0.0, + diff_or_traceback=message, + ref_path="", + new_path="", + )) + return doc if doc is not None else flush() + + document = flush() + + try: + cur_commit = validate_ref_commit(get_commit_fn() or "") + # A selected reference directory owns its files and metadata. Never clear + # it as part of preparing the default candidate workspace. + if args.reference_dir is None: + clear_stale_fakedata_fn(FAKEDATA) + except Exception: + document = settle_all(traceback.format_exc()) + print("TEST FAILED") + return exit_code_for(document) try: - with open(REF_COMMIT_FN) as f: - ref_commit = f.read().strip() - except FileNotFoundError: - print("Couldn't find reference commit") - sys.exit(1) + if args.update_refs: + ref_commit = cur_commit + write_candidate_ref_commit_fn(ref_commit, FAKEDATA) + elif args.reference_dir is not None: + ref_commit, artifacts_commit = resolve_ref_commit_fn( + artifacts_commit, + reference_dir=args.reference_dir, + pin_fn=pin_artifacts_commit_fn, + ) + else: + artifacts_commit = pin_artifacts_commit_fn() + ref_commit, artifacts_commit = resolve_ref_commit_fn( + artifacts_commit, + pin_fn=pin_artifacts_commit_fn, + ) + artifacts_manifest = load_artifacts_manifest_fn( + artifacts_commit, + expected_ref_commit=ref_commit, + selected_task_ids=expected_task_ids, + ) + except Exception: + document = settle_all(traceback.format_exc()) + print("TEST FAILED") + return exit_code_for(document) + + document = flush() - cur_commit = get_commit() - if not cur_commit: - raise Exception("Couldn't get current commit") print(f"***** testing against commit {ref_commit} *****") + if artifacts_commit: + print(f"***** artifacts pinned at {artifacts_commit} *****") - # check to make sure all car brands are tested - if full_test: - untested = (set(interface_names) - set(excluded_interfaces)) - {c.lower() for c in tested_cars} - assert len(untested) == 0, f"Cars missing routes: {str(untested)}" - - log_paths: defaultdict[str, dict[str, dict[str, str]]] = defaultdict(lambda: defaultdict(dict)) - with concurrent.futures.ProcessPoolExecutor(max_workers=args.jobs) as pool: - if not args.upload_only: - download_segments = [seg for car, seg in segments if car in tested_cars] - log_data: dict[str, LogReader] = {} - p1 = pool.map(get_log_data, download_segments) - for segment, lr in tqdm(p1, desc="Getting Logs", total=len(download_segments)): - log_data[segment] = lr - - pool_args: Any = [] - for car_brand, segment in segments: - if car_brand not in tested_cars: - continue + try: + if full_test: + names = interface_names_fn() if interface_names_fn is not None else set(interface_names) + untested = (names - set(excluded_interfaces)) - {c.lower() for c in tested_cars} + if untested: + raise AssertionError(f"Cars missing routes: {str(untested)}") + except Exception: + document = settle_all(traceback.format_exc()) + print("TEST FAILED") + return exit_code_for(document) + # Download each selected executable case once (case_id dedup; never hash ReplayCase). + case_by_id = unique_cases_by_id(tasks) + download_errors: dict[str, str] = {} + log_data: dict[str, bytes] = {} - for cfg in CONFIGS: - if cfg.proc_name not in tested_procs: - continue - - cur_log_fn = os.path.join(FAKEDATA, f"{segment}_{cfg.proc_name}_{cur_commit}.zst") - if args.update_refs: # reference logs will not exist if routes were just regenerated - ref_log_path = get_url(*segment.rsplit("--", 1,), "rlog.zst") - else: - ref_log_fn = os.path.join(FAKEDATA, f"{segment}_{cfg.proc_name}_{ref_commit}.zst") - ref_log_path = ref_log_fn if os.path.exists(ref_log_fn) else BASE_URL + os.path.basename(ref_log_fn) - - dat = None if args.upload_only else log_data[segment] - pool_args.append((segment, cfg, args, cur_log_fn, ref_log_path, dat)) - - log_paths[segment][cfg.proc_name]['ref'] = ref_log_path - log_paths[segment][cfg.proc_name]['new'] = cur_log_fn - - results: Any = defaultdict(dict) - p2 = pool.map(run_test_process, pool_args) - for (segment, proc, result) in tqdm(p2, desc="Running Tests", total=len(pool_args)): - if not args.upload_only: - results[segment][proc] = result - - diff_short, diff_long, failed = format_diff(results, log_paths, ref_commit) - if not upload: - with open(os.path.join(PROC_REPLAY_DIR, "diff.txt"), "w") as f: - f.write(diff_long) - print(diff_short) + download_payloads = [] + for case in case_by_id.values(): + if not case.executable: + download_errors[case.case_id] = f"{case.case_id}: pending case has no executable source" + continue + download_payloads.append({ + "case_id": case.case_id, + "car_brand": case.car_brand, + "source": case.source, + "processes": list(case.processes), + "custom_params": dict(case.custom_params), + "source_sha256": case.source_sha256, + "source_bytes": case.source_bytes, + }) + + if download_payloads: + try: + with concurrent.futures.ProcessPoolExecutor(max_workers=args.jobs) as pool: + future_map = {pool.submit(download_case_by_id_fn, payload): payload for payload in download_payloads} + for fut in tqdm(concurrent.futures.as_completed(future_map), desc="Getting Logs", total=len(future_map)): + payload = future_map[fut] + try: + case_id, data, err = fut.result() + except Exception: + case_id, data, err = payload["case_id"], None, traceback.format_exc() + if err is not None or data is None: + download_errors[case_id] = err or "download failed" + else: + log_data[case_id] = data + except Exception: + setup_error = traceback.format_exc() + for payload in download_payloads: + download_errors.setdefault(payload["case_id"], setup_error) + + # Materialize download failures as settled task errors before workers run. + for task in tasks: + if task.case.case_id in download_errors: + try: + failed_new_path = new_log_path(task, cur_commit) + except Exception: + failed_new_path = "" + document = settle(TaskResult( + status="error", + task_id=task.task_id, + elapsed_s=0.0, + diff_or_traceback=download_errors[task.case.case_id], + ref_path="", + new_path=failed_new_path, + )) - if failed: + + payloads: list[dict[str, Any]] = [] + for task in tasks: + if task.task_id in settled: + continue + ref_path = "" + new_path = "" + try: + ref_path = resolve_ref_path( + task, + ref_commit=ref_commit, + artifacts_commit=artifacts_commit, + reference_dir=args.reference_dir, + update_refs=args.update_refs, + artifacts_manifest=artifacts_manifest, + pin_fn=pin_artifacts_commit_fn, + ) + new_path = new_log_path(task, cur_commit) + payloads.append(make_task_payload( + task, + lr_dat=log_data[task.case.case_id], + ref_log_path=ref_path, + new_log_path=new_path, + ignore_fields=args.ignore_fields, + ignore_msgs=args.ignore_msgs, + update_refs=args.update_refs, + )) + except Exception: + document = settle(TaskResult( + status="error", + task_id=task.task_id, + elapsed_s=0.0, + diff_or_traceback=traceback.format_exc(), + ref_path=ref_path, + new_path=new_path, + )) + + def on_settled(result: TaskResult) -> None: + settle(result) + try: + pooled_results = run_task_pool_fn(payloads, jobs=args.jobs, on_settled=on_settled) + for result in pooled_results: + settled.setdefault(result.task_id, result) + missing_after_pool = set(expected_task_ids) - set(settled) + for task_id in missing_after_pool: + settled[task_id] = TaskResult( + status="error", + task_id=task_id, + elapsed_s=0.0, + diff_or_traceback="worker pool completed without a result", + ref_path="", + new_path="", + ) + except Exception: + document = settle_all(traceback.format_exc()) + print("TEST FAILED") + return exit_code_for(document) + + document = flush() + + if not args.update_refs: + retain_failed_logs(settled.values()) + diff_short, _, failed = format_diff_text(list(settled.values()), ref_commit) + print(diff_short) + if exit_code_for(document): print("TEST FAILED") - print("\n\nTo push the new reference logs for this commit run:") - print("./test_processes.py --upload-only") else: print("TEST SUCCEEDED") - else: - with open(REF_COMMIT_FN, "w") as f: - f.write(cur_commit) - print(f"\n\nUpdated reference logs for commit: {cur_commit}") + # Ensure candidate tree remains reusable even if workers already wrote logs. + write_candidate_ref_commit_fn(cur_commit, FAKEDATA) + print(f"\n\nWrote candidate reference logs for commit: {cur_commit}") + # Candidate-only: do not claim acceptance by rewriting REF_COMMIT_FN. + + return exit_code_for(document) - sys.exit(int(failed)) + +if __name__ == "__main__": + sys.exit(main()) diff --git a/selfdrive/test/process_replay/test_processes_unit.py b/selfdrive/test/process_replay/test_processes_unit.py new file mode 100755 index 00000000000000..a6153ced925887 --- /dev/null +++ b/selfdrive/test/process_replay/test_processes_unit.py @@ -0,0 +1,537 @@ +#!/usr/bin/env python3 +import concurrent.futures +import json +import os +import tempfile +import pickle +from pathlib import Path +import pytest + +from openpilot.common.params import ParamKeyType, Params +from openpilot.common.prefix import OpenpilotPrefix +from openpilot.selfdrive.test.process_replay import test_processes as tp + + +def test_active_inventory_counts(): + cases = tp.select_cases("active") + tasks = tp.build_tasks(cases) + assert len(cases) == 16 + assert len(tasks) == 66 + assert len({c.case_id for c in cases}) == 16 + assert len({t.task_id for t in tasks}) == 66 + assert len(tp.shard_task_ids(tasks, "card")) == 16 + assert len(tp.shard_task_ids(tasks, "controlsd")) == 16 + assert len(tp.shard_task_ids(tasks, "lagd")) == 16 + assert len(tp.shard_task_ids(tasks, "other")) == 18 + tp.assert_inventory_invariants(cases) + + +def test_staged_inventory_counts_and_pending_not_executable(): + cases = tp.select_cases("staged") + tasks = tp.build_tasks(cases) + assert len(cases) == 18 + assert len(tasks) == 78 + assert len(tp.PENDING_CASES) == 2 + assert all(not c.executable for c in tp.PENDING_CASES) + assert len(tp.shard_task_ids(tasks, "card")) == 18 + assert len(tp.shard_task_ids(tasks, "controlsd")) == 18 + assert len(tp.shard_task_ids(tasks, "lagd")) == 18 + assert len(tp.shard_task_ids(tasks, "other")) == 24 + union: set[str] = set() + for shard in ("card", "controlsd", "lagd", "other"): + ids = tp.shard_task_ids(tasks, shard) + assert union.isdisjoint(ids) + union.update(ids) + assert union == {t.task_id for t in tasks} + tp.assert_inventory_invariants(cases) + + +def test_source_segments_compat(): + assert len(tp.source_segments) == 17 + assert tp.source_segments[0][0] == "HYUNDAI" + brands = [c for c, _ in tp.source_segments] + assert "TOYOTA2" in brands + assert len(tp.segments) == 16 + assert "TOYOTA2" not in [c for c, _ in tp.segments] + + +def test_filter_whitelist_blacklist_semantics(): + tasks = tp.build_tasks(tp.ACTIVE_CASES) + only_card = tp.filter_tasks(tasks, whitelist_procs=["card"], blacklist_procs=[], whitelist_cars=None, blacklist_cars=[]) + assert {t.process for t in only_card} == {"card"} + assert len(only_card) == 16 + + no_core = tp.filter_tasks( + tasks, + whitelist_procs=None, + blacklist_procs=["card", "controlsd", "lagd"], + whitelist_cars=None, + blacklist_cars=[], + ) + assert len(no_core) == 18 + assert {"card", "controlsd", "lagd"}.isdisjoint({t.process for t in no_core}) + + honda = tp.filter_tasks(tasks, whitelist_procs=["card"], blacklist_procs=[], whitelist_cars=["honda"], blacklist_cars=[]) + assert {t.case.car_brand for t in honda} == {"HONDA"} + assert [t.task_id for t in honda] == ["honda:card"] + + +def test_empty_and_fixed_digests(): + assert tp.params_digest({}) == tp.EMPTY_PARAMS_DIGEST + assert tp.params_digest(tp.NAP_PREAP_PEDAL_PARAMS) == tp.NAP_PREAP_PEDAL_PARAMS_DIGEST + assert tp.params_digest(tp.NAP_PREAP_NO_PEDAL_PARAMS) == tp.NAP_PREAP_NO_PEDAL_PARAMS_DIGEST + manifest = tp.canonical_params_manifest(tp.NAP_PREAP_PEDAL_PARAMS) + assert manifest.endswith(b"\n") + assert b" " not in manifest + + +def test_header_type_validation_and_rejection(): + tp.validate_params_against_header(tp.NAP_PREAP_PEDAL_PARAMS) + with pytest.raises(TypeError): + tp.validate_params_against_header({"NAPFollowDistance": 1.5}) + with pytest.raises(TypeError): + tp.validate_params_against_header({"NAPBrakeFactor": 1}) + with pytest.raises(TypeError): + tp.validate_params_against_header({"NAPForcePreAP": 1}) + + +def test_params_round_trip_native_types(): + with OpenpilotPrefix(): + params = Params() + for key, value in tp.NAP_PREAP_PEDAL_PARAMS.items(): + declared = params.get_type(key) + if declared == ParamKeyType.BOOL: + assert isinstance(value, bool) + params.put_bool(key, value) + assert params.get_bool(key) is value + elif declared == ParamKeyType.INT: + assert isinstance(value, int) + assert not isinstance(value, bool) + params.put(key, value) + assert params.get(key) == value + elif declared == ParamKeyType.FLOAT: + assert isinstance(value, float) + params.put(key, value) + assert params.get(key) == value + else: + raise AssertionError(f"unexpected type for {key}: {declared}") + + +def test_ref_filename_and_case_id_validation(): + sha = "a" * 40 + assert tp.ref_filename("hyundai", "card", sha) == f"hyundai__card__{sha}.zst" + with pytest.raises(ValueError): + tp.ref_filename("HYUNDAI", "card", sha) + with pytest.raises(ValueError): + tp.validate_case_id("bad_id") + with pytest.raises(ValueError): + tp.ref_filename("hyundai", "card", "abc") + + +def test_pin_and_artifacts_url_require_full_sha(): + class FakeResp: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def read(self, *args, **kwargs): + return json.dumps({"object": {"sha": "a" * 40}}).encode() + + sha = tp.pin_artifacts_commit(opener=lambda *a, **k: FakeResp()) + assert sha == "a" * 40 + url = tp.artifacts_file_url(sha, "ref_commit") + assert url == f"https://raw.githubusercontent.com/NotAutopilot/ci-artifacts/{sha}/ref_commit" + with pytest.raises(ValueError): + tp.artifacts_file_url("process-replay", "ref_commit") + + +def test_resolve_ref_path_prefers_local_new_name_then_legacy(): + case = tp.ACTIVE_CASES[0] + task = tp.ReplayTask(case=case, process="card") + ref = "d" * 40 + with tempfile.TemporaryDirectory() as td: + new_name = tp.ref_filename(case.case_id, "card", ref) + legacy = tp.legacy_ref_filename(case.source, "card", ref) + Path(td, new_name).write_bytes(b"new") + path = tp.resolve_ref_path(task, ref_commit=ref, artifacts_commit="b" * 40, reference_dir=td, update_refs=False) + assert Path(path).resolve() == (Path(td) / new_name).resolve() + os.remove(os.path.join(td, new_name)) + Path(td, legacy).write_bytes(b"legacy") + path = tp.resolve_ref_path(task, ref_commit=ref, artifacts_commit="b" * 40, reference_dir=td, update_refs=False) + assert Path(path).resolve() == (Path(td) / legacy).resolve() + + +def test_resolve_ref_path_remote_legacy_for_route_cases(monkeypatch): + case = tp.ACTIVE_CASES[0] + task = tp.ReplayTask(case=case, process="card") + commit = "c" * 40 + ref = "d" * 40 + monkeypatch.setattr(tp, "LEGACY_ARTIFACTS_COMMITS", frozenset({commit})) + path = tp.resolve_ref_path(task, ref_commit=ref, artifacts_commit=commit, reference_dir=None, update_refs=False) + legacy = tp.legacy_ref_filename(case.source, "card", ref) + assert path == tp.artifacts_file_url(commit, legacy) + + +def test_resolve_ref_path_rejects_missing_manifest_outside_legacy(): + case = tp.ACTIVE_CASES[0] + task = tp.ReplayTask(case=case, process="card") + with pytest.raises(ValueError, match="LEGACY_ARTIFACTS_COMMITS"): + tp.resolve_ref_path( + task, + ref_commit="d" * 40, + artifacts_commit="c" * 40, + reference_dir=None, + update_refs=False, + artifacts_manifest=None, + ) + + +def test_incremental_diagnostics_and_nonzero_incomplete(): + with tempfile.TemporaryDirectory() as td: + expected = ["hyundai:card", "hyundai:controlsd"] + settled = { + "hyundai:card": tp.TaskResult("pass", "hyundai:card", 0.1, "", "ref", "new", {"carState": 1}), + } + doc = tp.build_results_document( + tested_commit="t" * 40, + ref_commit="a" * 40, + artifacts_commit="a" * 40, + inventory="active", + cases=tp.ACTIVE_CASES[:1], + expected_task_ids=expected, + results=settled, + ) + assert doc["schema_version"] == tp.RESULTS_SCHEMA_VERSION + assert doc["status_counts"]["incomplete"] == 1 + assert tp.exit_code_for(doc) == 1 + tp.write_diagnostics(td, doc, list(settled.values()), "r" * 40) + assert os.path.exists(os.path.join(td, "results.json")) + assert os.path.exists(os.path.join(td, "diff.txt")) + loaded = json.loads(Path(td, "results.json").read_text()) + assert loaded["incomplete_task_ids"] == ["hyundai:controlsd"] + + +def test_injected_worker_error_then_later_success(): + payloads = [ + {"task_id": "a:card", "ref_log_path": "", "new_log_path": ""}, + {"task_id": "b:card", "ref_log_path": "", "new_log_path": ""}, + {"task_id": "c:card", "ref_log_path": "", "new_log_path": ""}, + ] + + def worker(payload): + if payload["task_id"] == "a:card": + raise RuntimeError("injected worker boom") + return tp.TaskResult( + status="pass", + task_id=payload["task_id"], + elapsed_s=0.01, + diff_or_traceback="", + ref_path="", + new_path="", + message_counts={}, + ) + + settled: list[tp.TaskResult] = [] + results = tp.run_task_pool( + payloads, + jobs=2, + worker=worker, + on_settled=settled.append, + executor_factory=concurrent.futures.ThreadPoolExecutor, + ) + by_id = {r.task_id: r for r in results} + assert set(by_id) == {"a:card", "b:card", "c:card"} + assert by_id["a:card"].status == "error" + assert "injected worker boom" in by_id["a:card"].diff_or_traceback + assert by_id["b:card"].status == "pass" + assert by_id["c:card"].status == "pass" + assert len(settled) == 3 + + +def test_run_test_process_serializes_exceptions(): + payload = { + "task_id": "hyundai:card", + "case_id": "hyundai", + "car_brand": "HYUNDAI", + "source": "not-a-real-segment|--0", + "processes": ["card"], + "custom_params": {}, + "process": "card", + "lr_dat": b"not-a-log", + "ref_log_path": "", + "new_log_path": os.path.join(tempfile.gettempdir(), "nap-replay-unit-new.zst"), + "ignore_fields": [], + "ignore_msgs": [], + "update_refs": True, + } + result = tp.run_test_process(payload) + assert isinstance(result, tp.TaskResult) + assert result.status == "error" + assert result.task_id == "hyundai:card" + assert result.diff_or_traceback + + +def test_download_digest_mismatch_is_error(monkeypatch): + case = tp.ReplayCase( + case_id="fixture-case", + car_brand="TESLA", + source="https://example.invalid/rlog.zst", + processes=("card",), + source_sha256="0" * 64, + source_bytes=4, + ) + + class FakeFile: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def read(self, *args, **kwargs): + return b"abcd" + + monkeypatch.setattr(tp, "FileReader", lambda *a, **k: FakeFile()) + with pytest.raises(ValueError, match="sha256 mismatch"): + tp.download_case_bytes(case) + + +def test_duplicate_case_id_rejected(): + case = tp.ACTIVE_CASES[0] + with pytest.raises(AssertionError): + tp.assert_inventory_invariants([case, case]) + +def test_case_dedup_does_not_hash_custom_params(): + case = tp.ReplayCase( + case_id="dedup-case", + car_brand="TESLA", + source="", + processes=("card",), + custom_params={"NAPForcePreAP": True}, + ) + tasks = [tp.ReplayTask(case=case, process="card"), tp.ReplayTask(case=case, process="card")] + deduped = tp.unique_cases_by_id(tasks) + assert deduped == {"dedup-case": case} + + +def test_executable_source_metadata_is_exact(): + with pytest.raises(ValueError, match="requires both"): + tp.ReplayCase(case_id="missing-metadata", car_brand="TESLA", source="https://example.invalid/rlog.zst", + processes=("card",)) + with pytest.raises(ValueError, match="omit"): + tp.ReplayCase(case_id="pending-metadata", car_brand="TESLA", source="", + processes=("card",), source_bytes=1, source_sha256="0" * 64) + + +def test_reference_dir_owns_ref_commit_and_candidate_metadata(): + with tempfile.TemporaryDirectory() as td: + ref_commit = "a" * 40 + tp.write_candidate_ref_commit(ref_commit, td) + assert tp.resolve_ref_commit(reference_dir=td) == (ref_commit, None) + assert Path(td, "ref_commit").read_text() == f"{ref_commit}\n" + + +def test_manifest_requires_canonical_remote_filename(): + case = tp.ACTIVE_CASES[0] + task = tp.ReplayTask(case=case, process="card") + with pytest.raises(ValueError, match="non-canonical filename"): + tp.resolve_ref_path( + task, + ref_commit="a" * 40, + artifacts_commit="a" * 40, + reference_dir=None, + update_refs=False, + artifacts_manifest={"refs": {task.task_id: {"filename": "legacy.zst"}}}, + ) + + +def test_main_records_all_tasks_when_setup_fails(): + with tempfile.TemporaryDirectory() as td: + output_dir = os.path.join(td, "diagnostics") + result = tp.main( + ["--whitelist-procs", "card", "--output-dir", output_dir], + get_commit_fn=lambda: (_ for _ in ()).throw(RuntimeError("setup failed")), + clear_stale_fakedata_fn=lambda *_: pytest.fail("cleanup must follow initial diagnostics"), + ) + assert result == 1 + document = json.loads(Path(output_dir, "results.json").read_text()) + assert document["status_counts"]["error"] == 16 + assert document["status_counts"]["incomplete"] == 0 + +def test_generated_log_is_saved_before_reference_read(monkeypatch): + from types import SimpleNamespace + + case = tp.ACTIVE_CASES[0] + task = tp.ReplayTask(case=case, process="card") + cfg = SimpleNamespace(proc_name="card", pubs=set(), subs={"testMsg"}, ignore=[], tolerance=0) + message = SimpleNamespace(which=lambda: "testMsg") + saved: list[str] = [] + monkeypatch.setattr(tp, "replay_process", lambda *args, **kwargs: [message]) + monkeypatch.setattr(tp, "check_most_messages_valid", lambda messages: True) + monkeypatch.setattr(tp, "save_log", lambda path, messages: saved.append(path)) + monkeypatch.setattr(tp, "load_ref_log_messages", lambda path: (_ for _ in ()).throw(OSError("missing ref"))) + + status, detail, _ = tp.test_process(cfg, [], task, "/missing/ref.zst", "/candidate/new.zst") + assert status == "error" + assert "missing ref" in detail + assert saved == ["/candidate/new.zst"] + + +def test_task_result_is_pickleable(): + result = tp.TaskResult("pass", "case:card", 1.25, "", "/ref.zst", "/new.zst", {"carState": 3}) + restored = pickle.loads(pickle.dumps(result)) + assert restored == result + assert restored.to_record()["message_counts"] == {"carState": 3} + + +def test_validate_ref_commit_rejects_malformed_identities(): + good = "ab" * 20 + assert tp.validate_ref_commit(good) == good + for bad in ("abc", "A" * 40, "ab" * 19, "ab" * 21, "g" * 40, "a" * 39 + "/", "a" * 39 + "?", "a" * 39 + "#", "a" * 39 + '\n', "a" * 39 + " "): + with pytest.raises(ValueError): + tp.validate_ref_commit(bad) + + +def test_same_dir_collision_prefers_canonical_over_legacy(): + case = tp.ACTIVE_CASES[0] + task = tp.ReplayTask(case=case, process="card") + ref = "e" * 40 + with tempfile.TemporaryDirectory() as td: + new_name = tp.ref_filename(case.case_id, "card", ref) + legacy = tp.legacy_ref_filename(case.source, "card", ref) + Path(td, new_name).write_bytes(b"canonical") + Path(td, legacy).write_bytes(b"legacy") + path = tp.resolve_ref_path(task, ref_commit=ref, artifacts_commit="b" * 40, reference_dir=td, update_refs=False) + assert Path(path).name == new_name + assert Path(path).read_bytes() == b"canonical" + + +def test_symlink_and_outside_local_refs_are_rejected(): + case = tp.ACTIVE_CASES[0] + task = tp.ReplayTask(case=case, process="card") + ref = "f" * 40 + with tempfile.TemporaryDirectory() as td: + root = Path(td) + outside = root / "outside.txt" + outside.write_text("secret" + '\n', encoding="utf-8") + (root / "ref_commit").symlink_to(outside) + with pytest.raises(ValueError, match="symlink"): + tp.resolve_ref_commit(reference_dir=str(root)) + (root / "ref_commit").unlink() + (root / "ref_commit").write_text(ref + '\n', encoding="utf-8") + new_name = tp.ref_filename(case.case_id, "card", ref) + (root / new_name).symlink_to(outside) + with pytest.raises(ValueError, match="symlink"): + tp.resolve_ref_path(task, ref_commit=ref, artifacts_commit="b" * 40, reference_dir=str(root), update_refs=False) + (root / new_name).unlink() + with pytest.raises(ValueError, match="basename"): + tp.resolve_regular_member(str(root), "../outside.txt") + + +def test_per_task_ref_failure_continues_other_tasks(monkeypatch): + with tempfile.TemporaryDirectory() as td: + output_dir = os.path.join(td, "out") + ref_dir = os.path.join(td, "refs") + os.makedirs(ref_dir) + Path(ref_dir, "ref_commit").write_text(("a" * 40) + '\n', encoding="utf-8") + + real_resolve = tp.resolve_ref_path + + def fake_resolve(task, **kwargs): + if task.process == "controlsd": + raise ValueError(f"injected ref failure for {task.task_id}") + return real_resolve(task, **kwargs) + + monkeypatch.setattr(tp, "resolve_ref_path", fake_resolve) + + def fake_pool(payloads, jobs, on_settled=None, **kwargs): + results = [] + for payload in payloads: + result = tp.TaskResult("pass", payload["task_id"], 0.01, "", payload.get("ref_log_path", ""), payload.get("new_log_path", ""), {}) + results.append(result) + if on_settled is not None: + on_settled(result) + return results + + case = tp.ACTIVE_CASES[0] + + def fake_download(payload): + return payload["case_id"], b"not-used", None + + monkeypatch.setattr(tp.concurrent.futures, "ProcessPoolExecutor", concurrent.futures.ThreadPoolExecutor) + + code = tp.main( + ["--whitelist-procs", "card", "controlsd", "--whitelist-cars", case.car_brand, + "--output-dir", output_dir, "--reference-dir", ref_dir, "-j", "1"], + get_commit_fn=lambda: "b" * 40, + download_case_by_id_fn=fake_download, + run_task_pool_fn=fake_pool, + clear_stale_fakedata_fn=lambda *_: None, + ) + assert code == 1 + document = json.loads(Path(output_dir, "results.json").read_text()) + by_id = {row["task_id"]: row for row in document["results"]} + assert by_id[f"{case.case_id}:controlsd"]["status"] == "error" + assert "injected ref failure" in by_id[f"{case.case_id}:controlsd"]["diff_or_traceback"] + assert by_id[f"{case.case_id}:card"]["status"] == "pass" + + +def test_on_settled_flushes_diagnostics_each_callback(monkeypatch): + with tempfile.TemporaryDirectory() as td: + output_dir = os.path.join(td, "out") + snapshots = [] + + def fake_pool(payloads, jobs, on_settled=None, **kwargs): + assert on_settled is not None + first = tp.TaskResult("pass", payloads[0]["task_id"], 0.01, "", "", "", {}) + on_settled(first) + snapshots.append({row["task_id"] for row in json.loads(Path(output_dir, "results.json").read_text())["results"]}) + assert Path(output_dir, "diff.txt").exists() + second = tp.TaskResult("pass", payloads[1]["task_id"], 0.01, "", "", "", {}) + on_settled(second) + snapshots.append({row["task_id"] for row in json.loads(Path(output_dir, "results.json").read_text())["results"]}) + return [first, second] + + case = tp.ACTIVE_CASES[0] + monkeypatch.setattr(tp.concurrent.futures, "ProcessPoolExecutor", concurrent.futures.ThreadPoolExecutor) + code = tp.main( + ["--whitelist-procs", "card", "controlsd", "--whitelist-cars", case.car_brand, + "--output-dir", output_dir, "--update-refs", "-j", "1"], + get_commit_fn=lambda: "c" * 40, + download_case_by_id_fn=lambda payload: (payload["case_id"], b"abc", None), + run_task_pool_fn=fake_pool, + clear_stale_fakedata_fn=lambda *_: None, + write_candidate_ref_commit_fn=lambda *_: "", + ) + assert code == 0 + assert len(snapshots[0]) == 1 + assert len(snapshots[1]) == 2 + assert snapshots[0].issubset(snapshots[1]) + + +def test_manifest_missing_on_non_legacy_is_error(): + class Missing: + def __init__(self, *a, **k): + pass + + def read(self, *a, **k): + raise tp.URLFileException("Remote file is empty or doesn't exist: x") + + with pytest.raises(ValueError, match="non-legacy"): + tp.load_artifacts_manifest("a" * 40, expected_ref_commit="b" * 40, url_file_cls=Missing) + + +def test_manifest_empty_body_is_malformed_not_legacy(monkeypatch): + monkeypatch.setattr(tp, "LEGACY_ARTIFACTS_COMMITS", frozenset({"a" * 40})) + + class Empty: + def __init__(self, *a, **k): + pass + + def read(self, *a, **k): + return b"" + + with pytest.raises(ValueError, match="empty body"): + tp.load_artifacts_manifest("a" * 40, expected_ref_commit="b" * 40, url_file_cls=Empty) diff --git a/selfdrive/test/process_replay/test_regen.py b/selfdrive/test/process_replay/test_regen.py index 6c4b48c8d564e0..f4942e486cab65 100644 --- a/selfdrive/test/process_replay/test_regen.py +++ b/selfdrive/test/process_replay/test_regen.py @@ -1,6 +1,6 @@ -from parameterized import parameterized +from openpilot.common.parameterized import parameterized -from openpilot.selfdrive.test.process_replay.regen import regen_segment, DummyFrameReader +from openpilot.selfdrive.test.process_replay.regen import regen_segment from openpilot.selfdrive.test.process_replay.process_replay import check_openpilot_enabled from openpilot.tools.lib.openpilotci import get_url from openpilot.tools.lib.logreader import LogReader @@ -18,7 +18,7 @@ def ci_setup_data_readers(route, sidx): lr = LogReader(get_url(route, sidx, "rlog.bz2")) frs = { 'roadCameraState': FrameReader(get_url(route, sidx, "fcamera.hevc")), - 'driverCameraState': DummyFrameReader.zero_dcamera() + 'driverCameraState': FrameReader(get_url(route, sidx, "fcamera.hevc")), } if next((True for m in lr if m.which() == "wideRoadCameraState"), False): frs["wideRoadCameraState"] = FrameReader(get_url(route, sidx, "ecamera.hevc")) diff --git a/selfdrive/test/profiling/.gitignore b/selfdrive/test/profiling/.gitignore deleted file mode 100644 index 76acac7f93ea12..00000000000000 --- a/selfdrive/test/profiling/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -cachegrind.out.* -*.prof diff --git a/selfdrive/test/profiling/lib.py b/selfdrive/test/profiling/lib.py deleted file mode 100644 index 62bb305ca851d7..00000000000000 --- a/selfdrive/test/profiling/lib.py +++ /dev/null @@ -1,91 +0,0 @@ -from collections import defaultdict -from cereal.services import SERVICE_LIST -import cereal.messaging as messaging -import capnp - - -class ReplayDone(Exception): - pass - - -class SubSocket: - def __init__(self, msgs, trigger): - self.i = 0 - self.trigger = trigger - self.msgs = [m.as_builder().to_bytes() for m in msgs if m.which() == trigger] - self.max_i = len(self.msgs) - 1 - - def receive(self, non_blocking=False): - if non_blocking: - return None - - if self.i == self.max_i: - raise ReplayDone - - while True: - msg = self.msgs[self.i] - self.i += 1 - return msg - - -class PubSocket: - def send(self, data): - pass - - -class SubMaster(messaging.SubMaster): - def __init__(self, msgs, trigger, services, check_averag_freq=False): - self.frame = 0 - self.data = {} - self.ignore_alive = [] - - self.alive = {s: True for s in services} - self.updated = {s: False for s in services} - self.rcv_time = {s: 0. for s in services} - self.rcv_frame = {s: 0 for s in services} - self.valid = {s: True for s in services} - self.freq_ok = {s: True for s in services} - self.freq_tracker = {s: messaging.FrequencyTracker(SERVICE_LIST[s].frequency, SERVICE_LIST[s].frequency, False) for s in services} - self.logMonoTime = {} - self.sock = {} - self.freq = {} - self.check_average_freq = check_averag_freq - self.non_polled_services = [] - self.ignore_average_freq = [] - - # TODO: specify multiple triggers for service like plannerd that poll on more than one service - cur_msgs = [] - self.msgs = [] - msgs = [m for m in msgs if m.which() in services] - - for msg in msgs: - cur_msgs.append(msg) - if msg.which() == trigger: - self.msgs.append(cur_msgs) - cur_msgs = [] - - self.msgs = list(reversed(self.msgs)) - - for s in services: - self.freq[s] = SERVICE_LIST[s].frequency - try: - data = messaging.new_message(s) - except capnp.lib.capnp.KjException: - # lists - data = messaging.new_message(s, 0) - - self.data[s] = getattr(data, s) - self.logMonoTime[s] = 0 - self.sock[s] = SubSocket(msgs, s) - - def update(self, timeout=None): - if not len(self.msgs): - raise ReplayDone - - cur_msgs = self.msgs.pop() - self.update_msgs(cur_msgs[0].logMonoTime, self.msgs.pop()) - - -class PubMaster(messaging.PubMaster): - def __init__(self): - self.sock = defaultdict(PubSocket) diff --git a/selfdrive/test/profiling/profiler.py b/selfdrive/test/profiling/profiler.py deleted file mode 100755 index d50b157a37efca..00000000000000 --- a/selfdrive/test/profiling/profiler.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python3 -import os -import sys -import cProfile -import pprofile -import pyprof2calltree - -from opendbc.car.toyota.values import CAR as TOYOTA -from opendbc.car.honda.values import CAR as HONDA -from opendbc.car.volkswagen.values import CAR as VW -from openpilot.common.params import Params -from openpilot.tools.lib.logreader import LogReader -from openpilot.selfdrive.test.profiling.lib import SubMaster, PubMaster, SubSocket, ReplayDone -from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS - -BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" - -CARS = { - 'toyota': ("0982d79ebb0de295|2021-01-03--20-03-36/6", TOYOTA.TOYOTA_RAV4), - 'honda': ("0982d79ebb0de295|2021-01-08--10-13-10/6", HONDA.HONDA_CIVIC), - "vw": ("ef895f46af5fd73f|2021-05-22--14-06-35/6", VW.AUDI_A3_MK3), -} - - -def get_inputs(msgs, process, fingerprint): - for config in CONFIGS: - if config.proc_name == process: - sub_socks = list(config.pubs) - trigger = sub_socks[0] - break - - # some procs block on CarParams - for msg in msgs: - if msg.which() == 'carParams': - m = msg.as_builder() - m.carParams.carFingerprint = fingerprint - Params().put("CarParams", m.carParams.copy().to_bytes()) - break - - sm = SubMaster(msgs, trigger, sub_socks) - pm = PubMaster() - if 'can' in sub_socks: - can_sock = SubSocket(msgs, 'can') - else: - can_sock = None - return sm, pm, can_sock - - -def profile(proc, func, car='toyota'): - segment, fingerprint = CARS[car] - segment = segment.replace('|', '/') - rlog_url = f"{BASE_URL}{segment}/rlog.bz2" - msgs = list(LogReader(rlog_url)) * int(os.getenv("LOOP", "1")) - - os.environ['FINGERPRINT'] = fingerprint - os.environ['SKIP_FW_QUERY'] = "1" - os.environ['REPLAY'] = "1" - - def run(sm, pm, can_sock): - try: - if can_sock is not None: - func(sm, pm, can_sock) - else: - func(sm, pm) - except ReplayDone: - pass - - # Statistical - sm, pm, can_sock = get_inputs(msgs, proc, fingerprint) - with pprofile.StatisticalProfile()(period=0.00001) as pr: - run(sm, pm, can_sock) - pr.dump_stats(f'cachegrind.out.{proc}_statistical') - - # Deterministic - sm, pm, can_sock = get_inputs(msgs, proc, fingerprint) - with cProfile.Profile() as pr: - run(sm, pm, can_sock) - pyprof2calltree.convert(pr.getstats(), f'cachegrind.out.{proc}_deterministic') - - -if __name__ == '__main__': - from openpilot.selfdrive.controls.controlsd import main as controlsd_thread - from openpilot.selfdrive.locationd.paramsd import main as paramsd_thread - from openpilot.selfdrive.controls.plannerd import main as plannerd_thread - - procs = { - 'controlsd': controlsd_thread, - 'paramsd': paramsd_thread, - 'plannerd': plannerd_thread, - } - - proc = sys.argv[1] - if proc not in procs: - print(f"{proc} not available") - sys.exit(0) - else: - profile(proc, procs[proc]) diff --git a/selfdrive/test/scons_build_test.sh b/selfdrive/test/scons_build_test.sh index 5ffdb4379e004c..d4a0733569cc7a 100755 --- a/selfdrive/test/scons_build_test.sh +++ b/selfdrive/test/scons_build_test.sh @@ -13,7 +13,7 @@ cd $BASEDIR cd $BASEDIR/opendbc_repo/ scons --clean -scons --no-cache --random -j$(nproc) +scons --no-cache --random if ! scons -q; then echo "FAILED: all build products not up to date after first pass." exit 1 diff --git a/selfdrive/test/setup_device_ci.sh b/selfdrive/test/setup_device_ci.sh index fdc222e7e7918c..3fe353e72c067f 100755 --- a/selfdrive/test/setup_device_ci.sh +++ b/selfdrive/test/setup_device_ci.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash set -e +set -x if [ -z "$SOURCE_DIR" ]; then echo "SOURCE_DIR must be set" @@ -17,9 +18,14 @@ if [ -z "$TEST_DIR" ]; then exit 1 fi -umount /data/safe_staging/merged/ || true -sudo umount /data/safe_staging/merged/ || true -rm -rf /data/safe_staging/* || true +# prevent storage from filling up +rm -rf /data/media/0/realdata/* + +rm -rf /data/safe_staging/ || true +if [ -d /data/safe_staging/ ]; then + sudo umount /data/safe_staging/merged/ || true + rm -rf /data/safe_staging/ || true +fi CONTINUE_PATH="/data/continue.sh" tee $CONTINUE_PATH << EOF @@ -36,18 +42,12 @@ sudo systemctl restart NetworkManager sudo systemctl disable ssh-param-watcher.path sudo systemctl disable ssh-param-watcher.service sudo mount -o ro,remount / +sudo systemctl stop power_monitor while true; do if ! sudo systemctl is-active -q ssh; then sudo systemctl start ssh fi - - #if ! pgrep -f 'ciui.py' > /dev/null 2>&1; then - # echo 'starting UI' - # cp $SOURCE_DIR/selfdrive/test/ciui.py /data/ - # /data/ciui.py & - #fi - sleep 5s done @@ -83,7 +83,7 @@ safe_checkout() { rsync -a --delete $SOURCE_DIR $TEST_DIR } -unsafe_checkout() { +unsafe_checkout() {( set -e # checkout directly in test dir, leave old build products cd $TEST_DIR @@ -94,7 +94,7 @@ unsafe_checkout() { git fetch --no-tags --no-recurse-submodules -j8 --verbose --depth 1 origin $GIT_COMMIT git checkout --force --no-recurse-submodules $GIT_COMMIT git reset --hard $GIT_COMMIT - git clean -df + git clean -dff git submodule sync git submodule foreach --recursive "git reset --hard && git clean -df" git submodule update --init --recursive @@ -102,7 +102,7 @@ unsafe_checkout() { git lfs pull (ulimit -n 65535 && git lfs prune) -} +)} export GIT_PACK_THREADS=8 @@ -112,8 +112,13 @@ if [ ! -d "$SOURCE_DIR" ]; then fi if [ ! -z "$UNSAFE" ]; then - echo "doing unsafe checkout" + echo "trying unsafe checkout" + set +e unsafe_checkout + if [[ "$?" -ne 0 ]]; then + safe_checkout + fi + set -e else echo "doing safe checkout" safe_checkout diff --git a/selfdrive/test/setup_vsound.sh b/selfdrive/test/setup_vsound.sh deleted file mode 100755 index aab14997448b4a..00000000000000 --- a/selfdrive/test/setup_vsound.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -{ - #start pulseaudio daemon - sudo pulseaudio -D - - # create a virtual null audio and set it to default device - sudo pactl load-module module-null-sink sink_name=virtual_audio - sudo pactl set-default-sink virtual_audio -} > /dev/null 2>&1 diff --git a/selfdrive/test/setup_xvfb.sh b/selfdrive/test/setup_xvfb.sh index 692b84d65f0aea..50b313658dc908 100755 --- a/selfdrive/test/setup_xvfb.sh +++ b/selfdrive/test/setup_xvfb.sh @@ -2,10 +2,14 @@ # Sets up a virtual display for running map renderer and simulator without an X11 display -DISP_ID=99 +if uname -r | grep -q "WSL2"; then + DISP_ID=0 # WSLg uses display :0 +else + DISP_ID=99 # Standard Xvfb display +fi export DISPLAY=:$DISP_ID -sudo Xvfb $DISPLAY -screen 0 2160x1080x24 2>/dev/null & +Xvfb $DISPLAY -screen 0 2160x1080x24 2>/dev/null & # check for x11 socket for the specified display ID while [ ! -S /tmp/.X11-unix/X$DISP_ID ] @@ -15,5 +19,4 @@ do done touch ~/.Xauthority -export XDG_SESSION_TYPE="x11" -xset -q \ No newline at end of file +export XDG_SESSION_TYPE="x11" \ No newline at end of file diff --git a/selfdrive/test/test_msgq_reader_budget.py b/selfdrive/test/test_msgq_reader_budget.py new file mode 100644 index 00000000000000..f3beaca8a2f08a --- /dev/null +++ b/selfdrive/test/test_msgq_reader_budget.py @@ -0,0 +1,323 @@ +"""msgq allows NUM_READERS subscribers per service (msgq.h). One more evicts +every reader of that socket; they re-register and evict each other, and +downstream daemons publish valid=False. selfdrived then raises commIssue. + +Count every steady process reader, including daemons that are not listed as +PythonProcess entries (athenad, uploader, statsd, manager) and every socket +a process opens (pandad has two deviceState readers). A get_gps_location_service +subscriber opens exactly one of gpsLocation / gpsLocationExternal, so it is +charged to each when checking that configuration. The free slot under +NUM_READERS is athena getMessage or an SSH dump, not a permanent reader. +""" +import ast +import os +import re + +from openpilot.common.basedir import BASEDIR + +HEADROOM = 1 + +# Not steady onroad processes. gps_fix creates a SubMaster only for the +# offline map refresh helper; mapd owns the live GPS sockets. +EXCLUDE_DIRS = ("selfdrive/debug", "tools", "scripts", "system/webrtc") +EXCLUDE_FILES = { + "system/camerad/snapshot.py", + "selfdrive/mapd/gps_fix.py", +} + + +def num_readers() -> int: + found = [] + for rel in ("msgq/msgq.h", "msgq_repo/msgq/msgq.h"): + path = os.path.join(BASEDIR, rel) + if not os.path.exists(path): + continue + match = re.search(r"#define\s+NUM_READERS\s+(\d+)", open(path).read()) + if match: + found.append(int(match.group(1))) + assert found, "NUM_READERS missing from msgq.h" + assert len(set(found)) == 1, found + return found[0] + + +def _services(): + src = open(os.path.join(BASEDIR, "cereal/services.py")).read() + out = {} + for name, should_log in re.findall(r'^\s*"(\w+)":\s*\((True|False)', src, re.M): + out[name] = should_log == "True" + return out + + +def _call_name(func) -> str: + if isinstance(func, ast.Attribute): + return func.attr + if isinstance(func, ast.Name): + return func.id + return "" + + +def _simple_name(node) -> str: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + return "" + + +def _main_guard(node: ast.If) -> bool: + test = node.test + if not isinstance(test, ast.Compare) or len(test.ops) != 1 or len(test.comparators) != 1: + return False + if not isinstance(test.ops[0], (ast.Eq, ast.Is)): + return False + sides = (test.left, test.comparators[0]) + + def _is_name(n): + return isinstance(n, ast.Name) and n.id == "__name__" + + def _is_main(n): + return isinstance(n, ast.Constant) and n.value == "__main__" + + return (_is_name(sides[0]) and _is_main(sides[1])) or (_is_name(sides[1]) and _is_main(sides[0])) + + +class _Readers(ast.NodeVisitor): + """One subscriber call site is one reader, even inside the same process.""" + + def __init__(self): + self.scope = [{}] + self.comp = [] + self.hits = [] + + def visit_FunctionDef(self, node): + self.scope.append({}) + self.generic_visit(node) + self.scope.pop() + + visit_AsyncFunctionDef = visit_FunctionDef + + def visit_ClassDef(self, node): + self.scope.append({}) + self.generic_visit(node) + self.scope.pop() + + def visit_Lambda(self, node): + self.scope.append({}) + self.generic_visit(node) + self.scope.pop() + + def visit_If(self, node): + if _main_guard(node): + for stmt in node.orelse: + self.visit(stmt) + return + self.generic_visit(node) + + def visit_Assign(self, node): + for target in node.targets: + name = _simple_name(target) + if name: + self.scope[-1].setdefault(name, []).append((node.lineno, node.value)) + self.generic_visit(node) + + def visit_AnnAssign(self, node): + name = _simple_name(node.target) + if name and node.value is not None: + self.scope[-1].setdefault(name, []).append((node.lineno, node.value)) + self.generic_visit(node) + + def visit_For(self, node): + name = _simple_name(node.target) + if name: + self.comp.append({name: list(self._resolve(node.iter, node.lineno))}) + for stmt in node.body: + self.visit(stmt) + if name: + self.comp.pop() + for stmt in node.orelse: + self.visit(stmt) + + def _visit_comp(self, node, parts): + pushed = 0 + for gen in node.generators: + name = _simple_name(gen.target) + if not name: + continue + self.comp.append({name: list(self._resolve(gen.iter, getattr(gen.iter, "lineno", node.lineno)))}) + pushed += 1 + for part in parts: + self.visit(part) + for _ in range(pushed): + self.comp.pop() + + def visit_ListComp(self, node): + self._visit_comp(node, [node.elt]) + + def visit_SetComp(self, node): + self._visit_comp(node, [node.elt]) + + def visit_GeneratorExp(self, node): + self._visit_comp(node, [node.elt]) + + def visit_DictComp(self, node): + self._visit_comp(node, [node.key, node.value]) + + def visit_Call(self, node): + if _call_name(node.func) in ("SubMaster", "sub_sock") and node.args: + for kind, name in self._resolve(node.args[0], node.lineno): + self.hits.append((kind, name, node.lineno)) + self.generic_visit(node) + + def _latest_assign(self, name, lineno): + for scope in reversed(self.scope): + entries = scope.get(name) + if not entries: + continue + prior = [value for line, value in entries if line <= lineno] + if prior: + return prior[-1] + return None + return None + + def _resolve(self, node, lineno, seen=None): + if node is None: + return + if seen is None: + seen = set() + if isinstance(node, ast.Constant) and isinstance(node.value, str): + yield ("service", node.value) + return + if isinstance(node, (ast.List, ast.Tuple, ast.Set)): + for elt in node.elts: + yield from self._resolve(elt, lineno, seen) + return + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + yield from self._resolve(node.left, lineno, seen) + yield from self._resolve(node.right, lineno, seen) + return + if isinstance(node, ast.Call): + if _call_name(node.func) == "get_gps_location_service": + yield ("dynamic_gps", "") + return + if isinstance(node, (ast.Name, ast.Attribute)): + key = _simple_name(node) + for scope in reversed(self.comp): + if key in scope: + yield from scope[key] + return + mark = ("name", key) + if mark in seen: + return + seen.add(mark) + value = self._latest_assign(key, lineno) + if value is not None: + yield from self._resolve(value, lineno, seen) + + +def _skip(rel: str) -> bool: + rel = rel.replace("\\", "/") + if rel in EXCLUDE_FILES: + return True + parts = rel.split("/") + if parts[-1].startswith("test_") or parts[-1] == "conftest.py": + return True + if any(rel.startswith(d + "/") or ("/" + d + "/") in ("/" + rel) for d in EXCLUDE_DIRS): + return True + if "/tests/" in ("/" + rel) or "/test/" in ("/" + rel): + return True + return False + + +def _cpp_readers(rel: str, text: str): + hits = [] + for match in re.finditer(r"\bSubMaster\s+\w+\s*\(\s*\{([^}]*)\}", text, re.S): + line = text.count("\n", 0, match.start()) + 1 + for name in re.findall(r'"(\w+)"', match.group(1)): + hits.append((name, line)) + for match in re.finditer(r"\bSubSocket::create\s*\([^,]+,\s*\"(\w+)\"", text): + line = text.count("\n", 0, match.start()) + 1 + hits.append((match.group(1), line)) + return [(name, f"{rel}:{line}") for name, line in hits] + + +def count_readers(): + services = _services() + counts = {name: (1 if logged else 0) for name, logged in services.items()} + where = {name: (["loggerd"] if logged else []) for name, logged in services.items()} + dynamic_gps = [] + + for top in ("selfdrive", "system"): + for root, _, files in os.walk(os.path.join(BASEDIR, top)): + for fn in files: + path = os.path.join(root, fn) + rel = os.path.relpath(path, BASEDIR) + if _skip(rel): + continue + if fn.endswith(".py"): + try: + tree = ast.parse(open(path).read()) + except SyntaxError: + continue + visitor = _Readers() + visitor.visit(tree) + for kind, name, lineno in visitor.hits: + loc = f"{rel}:{lineno}" + if kind == "dynamic_gps": + dynamic_gps.append(loc) + continue + if name not in services: + continue + counts[name] += 1 + where[name].append(loc) + elif fn.endswith((".cc", ".h", ".hpp")): + for name, loc in _cpp_readers(rel, open(path).read()): + if name not in services: + continue + counts[name] += 1 + where[name].append(loc) + + # One process, one GPS socket. Check both device configurations. + for name in ("gpsLocation", "gpsLocationExternal"): + if name not in counts: + continue + counts[name] += len(dynamic_gps) + where[name].extend(dynamic_gps) + return counts, where + + +def test_reader_budget(): + counts, where = count_readers() + limit = num_readers() - HEADROOM + over = {name: (count, where[name]) for name, count in counts.items() if count > limit} + assert not over, f"msgq reader budget ({limit}) exceeded: {over}" + + +def test_card_process_does_not_subscribe_carstate(): + """card publishes carState. preap body controls must reuse that, not subscribe.""" + _, where = count_readers() + hits = [loc for loc in where.get("carState", []) if "card.py" in loc or "preap_body_controls.py" in loc] + assert hits == [], hits + + +def test_pandad_has_two_devicestate_readers(): + _, where = count_readers() + hits = [loc for loc in where["deviceState"] if "pandad.cc" in loc] + assert len(hits) == 2, hits + + +def test_always_on_daemons_are_counted(): + _, where = count_readers() + blob = "\n".join(where["deviceState"]) + for name in ("athenad.py", "uploader.py", "statsd.py", "manager.py"): + assert name in blob, name + + +if __name__ == "__main__": + readers, locations = count_readers() + limit = num_readers() - HEADROOM + print(f"NUM_READERS={num_readers()} limit={limit}") + for name, count in sorted(readers.items(), key=lambda kv: -kv[1])[:12]: + print(f"{count:3} {name}") + if count >= limit - 1: + for loc in locations[name]: + print(f" {loc}") diff --git a/selfdrive/test/test_onroad.py b/selfdrive/test/test_onroad.py index b9b2a8043b3763..7d6862dab7f4fc 100644 --- a/selfdrive/test/test_onroad.py +++ b/selfdrive/test/test_onroad.py @@ -1,30 +1,26 @@ import math import json import os -import pathlib -import psutil import pytest import shutil import subprocess import time import numpy as np -import zstandard as zstd from collections import Counter, defaultdict -from functools import cached_property from pathlib import Path +from openpilot.common.utils import tabulate -from cereal import car +from cereal import log import cereal.messaging as messaging from cereal.services import SERVICE_LIST from openpilot.common.basedir import BASEDIR from openpilot.common.timeout import Timeout from openpilot.common.params import Params -from openpilot.selfdrive.controls.lib.events import EVENTS, ET +from openpilot.selfdrive.selfdrived.events import EVENTS, ET from openpilot.selfdrive.test.helpers import set_params_enabled, release_only -from openpilot.system.hardware import HARDWARE from openpilot.system.hardware.hw import Paths -from openpilot.system.loggerd.uploader import LOG_COMPRESSION_LEVEL from openpilot.tools.lib.logreader import LogReader +from openpilot.tools.lib.log_time_series import msgs_to_time_series """ CPU usage budget @@ -32,51 +28,51 @@ * total CPU usage of openpilot (sum(PROCS.values()) should not exceed MAX_TOTAL_CPU """ -MAX_TOTAL_CPU = 250. # total for all 8 cores + +TEST_DURATION = 25 +LOG_OFFSET = 8 + +MAX_TOTAL_CPU = 350. # total for all 8 cores PROCS = { # Baseline CPU usage by process - "selfdrive.controls.controlsd": 32.0, + "selfdrive.controls.controlsd": 16.0, + "selfdrive.selfdrived.selfdrived": 16.0, "selfdrive.car.card": 26.0, "./loggerd": 14.0, - "./encoderd": 17.0, - "./camerad": 14.5, - "./locationd": 11.0, - "selfdrive.controls.plannerd": 11.0, - "./ui": 18.0, - "selfdrive.locationd.paramsd": 9.0, - "./sensord": 7.0, - "selfdrive.controls.radard": 7.0, - "selfdrive.modeld.modeld": 13.0, - "selfdrive.modeld.dmonitoringmodeld": 8.0, - "system.hardware.hardwared": 3.87, + "./encoderd": 13.0, + "./camerad": 10.0, + "selfdrive.controls.plannerd": 8.0, + "selfdrive.ui.ui": 40.0, + "selfdrive.nap_dash.server": 2.0, + "system.sensord.sensord": 13.0, + "selfdrive.controls.radard": 2.0, + "selfdrive.pathobstacled.pathobstacled": 1.0, + "selfdrive.modeld.modeld": 22.0, + "selfdrive.modeld.dmonitoringmodeld": 18.0, + "system.hardware.hardwared": 4.0, "selfdrive.locationd.calibrationd": 2.0, "selfdrive.locationd.torqued": 5.0, - "selfdrive.ui.soundd": 3.5, + "selfdrive.locationd.locationd": 25.0, + "selfdrive.locationd.paramsd": 9.0, + "selfdrive.locationd.lagd": 11.0, + "selfdrive.ui.soundd": 3.0, + "selfdrive.ui.feedback.feedbackd": 1.0, "selfdrive.monitoring.dmonitoringd": 4.0, - "./proclogd": 1.54, - "system.logmessaged": 0.2, + "system.proclogd": 7.0, + "system.logmessaged": 1.0, "system.tombstoned": 0, - "./logcatd": 0, + "system.journald": 1.0, "system.micd": 5.0, "system.timed": 0, "selfdrive.pandad.pandad": 0, - "system.statsd": 0.4, - "system.loggerd.uploader": (0.5, 15.0), - "system.loggerd.deleter": 0.1, + "system.statsd": 1.0, + "system.loggerd.uploader": 15.0, + "system.loggerd.deleter": 1.0, + "./pandad": 19.0, + "system.qcomgpsd.qcomgpsd": 1.0, + "system.hardware.tici.modem": 10.0, } -PROCS.update({ - "tici": { - "./pandad": 4.0, - "./ubloxd": 0.02, - "system.ubloxd.pigeond": 6.0, - }, - "tizi": { - "./pandad": 19.0, - "system.qcomgpsd.qcomgpsd": 1.0, - } -}.get(HARDWARE.get_device_type(), {})) - TIMINGS = { # rtols: max/min, rsd "can": [2.5, 0.35], @@ -87,101 +83,94 @@ "carControl": [2.5, 0.35], "controlsState": [2.5, 0.35], "longitudinalPlan": [2.5, 0.5], + "driverAssistance": [2.5, 0.5], "roadCameraState": [2.5, 0.35], "driverCameraState": [2.5, 0.35], "modelV2": [2.5, 0.35], "driverStateV2": [2.5, 0.40], "livePose": [2.5, 0.35], + "liveParameters": [2.5, 0.35], "wideRoadCameraState": [1.5, 0.35], } +LOGS_SIZE = { # MB per segment + "qlog.zst": 0.5, + "rlog.zst": 8.1, + "qcamera.ts": 2.3, +} +LOGS_SIZE.update(dict.fromkeys(['ecamera.hevc', 'fcamera.hevc', 'dcamera.hevc'], 76.5)) + def cputime_total(ct): return ct.cpuUser + ct.cpuSystem + ct.cpuChildrenUser + ct.cpuChildrenSystem @pytest.mark.tici +@pytest.mark.skip_tici_setup class TestOnroad: @classmethod def setup_class(cls): if "DEBUG" in os.environ: - segs = filter(lambda x: os.path.exists(os.path.join(x, "rlog")), Path(Paths.log_root()).iterdir()) + segs = filter(lambda x: os.path.exists(os.path.join(x, "rlog.zst")), Path(Paths.log_root()).iterdir()) segs = sorted(segs, key=lambda x: x.stat().st_mtime) - print(segs[-3]) - cls.lr = list(LogReader(os.path.join(segs[-3], "rlog"))) + cls.lr = list(LogReader(os.path.join(segs[-1], "rlog.zst"))) + cls.ts = msgs_to_time_series(cls.lr) return # setup env params = Params() params.remove("CurrentRoute") + params.put_bool("RecordFront", True, block=True) set_params_enabled() os.environ['REPLAY'] = '1' + os.environ['MSGQ_PREALLOC'] = '1' os.environ['TESTING_CLOSET'] = '1' if os.path.exists(Paths.log_root()): shutil.rmtree(Paths.log_root()) - # start manager and run openpilot for a minute + # start manager and run openpilot for TEST_DURATION proc = None try: manager_path = os.path.join(BASEDIR, "system/manager/manager.py") + cls.manager_st = time.monotonic() proc = subprocess.Popen(["python", manager_path]) sm = messaging.SubMaster(['carState']) - with Timeout(150, "controls didn't start"): - while sm.recv_frame['carState'] < 0: + with Timeout(30, "controls didn't start"): + while not sm.seen['carState']: sm.update(1000) - # make sure we get at least two full segments - route = None - cls.segments = [] - with Timeout(300, "timed out waiting for logs"): - while route is None: - route = params.get("CurrentRoute", encoding="utf-8") - time.sleep(0.1) + route = params.get("CurrentRoute") + assert route is not None - while len(cls.segments) < 3: - segs = set() - if Path(Paths.log_root()).exists(): - segs = set(Path(Paths.log_root()).glob(f"{route}--*")) - cls.segments = sorted(segs, key=lambda s: int(str(s).rsplit('--')[-1])) - time.sleep(2) - - # chop off last, incomplete segment - cls.segments = cls.segments[:-1] + segs = list(Path(Paths.log_root()).glob(f"{route}--*")) + assert len(segs) == 1 + time.sleep(TEST_DURATION) finally: - cls.gpu_procs = {psutil.Process(int(f.name)).name() for f in pathlib.Path('/sys/devices/virtual/kgsl/kgsl/proc/').iterdir() if f.is_dir()} - if proc is not None: proc.terminate() if proc.wait(60) is None: proc.kill() - cls.lrs = [list(LogReader(os.path.join(str(s), "rlog"))) for s in cls.segments] - - # use the second segment by default as it's the first full segment - cls.lr = list(LogReader(os.path.join(str(cls.segments[1]), "rlog"))) - cls.log_path = cls.segments[1] + cls.lr = list(LogReader(os.path.join(str(segs[0]), "rlog.zst"))) + st = time.monotonic() + cls.ts = msgs_to_time_series(cls.lr) + print("msgs to time series", time.monotonic() - st) + log_path = segs[0] cls.log_sizes = {} - for f in cls.log_path.iterdir(): + for f in log_path.iterdir(): assert f.is_file() cls.log_sizes[f] = f.stat().st_size / 1e6 - if f.name in ("qlog", "rlog"): - with open(f, 'rb') as ff: - cls.log_sizes[f] = len(zstd.compress(ff.read(), LOG_COMPRESSION_LEVEL)) / 1e6 - - @cached_property - def service_msgs(self): - msgs = defaultdict(list) - for m in self.lr: - msgs[m.which()].append(m) - return msgs + cls.msgs = defaultdict(list) + for m in cls.lr: + cls.msgs[m.which()].append(m) def test_service_frequencies(self, subtests): - for s, msgs in self.service_msgs.items(): + for s, msgs in self.msgs.items(): if s in ('initData', 'sentinel'): continue @@ -190,10 +179,14 @@ def test_service_frequencies(self, subtests): continue with subtests.test(service=s): - assert len(msgs) >= math.floor(SERVICE_LIST[s].frequency*55) + assert len(msgs) >= math.floor(SERVICE_LIST[s].frequency*int(TEST_DURATION*0.8)) + + def test_manager_starting_time(self): + st = self.ts['managerState']['t'][0] + assert (st - self.manager_st) < 15.0, f"manager.py took {st - self.manager_st}s to publish the first 'managerState' msg" def test_cloudlog_size(self): - msgs = [m for m in self.lr if m.which() == 'logMessage'] + msgs = self.msgs['logMessage'] total_size = sum(len(m.as_builder().to_bytes()) for m in msgs) assert total_size < 3.5e5 @@ -202,18 +195,14 @@ def test_cloudlog_size(self): big_logs = [f for f, n in cnt.most_common(3) if n / sum(cnt.values()) > 30.] assert len(big_logs) == 0, f"Log spam: {big_logs}" - def test_log_sizes(self): + def test_log_sizes(self, subtests): + # TODO: this isn't super stable between different devices for f, sz in self.log_sizes.items(): - if f.name == "qcamera.ts": - assert 2.15 < sz < 2.35 - elif f.name == "qlog": - assert 0.4 < sz < 0.55 - elif f.name == "rlog": - assert 5 < sz < 50 - elif f.name.endswith('.hevc'): - assert 70 < sz < 77 - else: - raise NotImplementedError + rate = LOGS_SIZE[f.name]/60. + minn = rate * TEST_DURATION * 0.5 + maxx = rate * TEST_DURATION * 1.5 + with subtests.test(file=f.name): + assert minn < sz < maxx def test_ui_timings(self): result = "\n" @@ -221,7 +210,9 @@ def test_ui_timings(self): result += "-------------- UI Draw Timing ------------------\n" result += "------------------------------------------------\n" - ts = [m.uiDebug.drawTimeMillis for m in self.service_msgs['uiDebug']] + # other processes preempt ui while starting up + offset = int(20 * LOG_OFFSET) + ts = self.ts['uiDebug']['cpuTimeMillis'][offset:] result += f"min {min(ts):.2f}ms\n" result += f"max {max(ts):.2f}ms\n" result += f"std {np.std(ts):.2f}ms\n" @@ -230,7 +221,7 @@ def test_ui_timings(self): print(result) assert max(ts) < 250. - assert np.mean(ts) < 10. + assert np.mean(ts) < 20. # TODO: ~6-11ms, increase consistency #self.assertLess(np.std(ts), 5.) # some slow frames are expected since camerad/modeld can preempt ui @@ -238,53 +229,44 @@ def test_ui_timings(self): assert len(veryslow) < 5, f"Too many slow frame draw times: {veryslow}" def test_cpu_usage(self, subtests): - result = "\n" - result += "------------------------------------------------\n" - result += "------------------ CPU Usage -------------------\n" - result += "------------------------------------------------\n" + print("\n------------------------------------------------") + print("------------------ CPU Usage -------------------") + print("------------------------------------------------") plogs_by_proc = defaultdict(list) - for pl in self.service_msgs['procLog']: + for pl in self.msgs['procLog']: for x in pl.procLog.procs: if len(x.cmdline) > 0: n = list(x.cmdline)[0] plogs_by_proc[n].append(x) - print(plogs_by_proc.keys()) cpu_ok = True - dt = (self.service_msgs['procLog'][-1].logMonoTime - self.service_msgs['procLog'][0].logMonoTime) / 1e9 - for proc_name, expected_cpu in PROCS.items(): + dt = (self.msgs['procLog'][-1].logMonoTime - self.msgs['procLog'][0].logMonoTime) / 1e9 + header = ['process', 'usage', 'expected', 'max allowed', 'test result'] + rows = [] + for proc_name, expected in PROCS.items(): - err = "" - exp = "???" - cpu_usage = 0. + error = "" + usage = 0. x = plogs_by_proc[proc_name] if len(x) > 2: cpu_time = cputime_total(x[-1]) - cputime_total(x[0]) - cpu_usage = cpu_time / dt * 100. - - if isinstance(expected_cpu, tuple): - exp = str(expected_cpu) - minn, maxx = expected_cpu - else: - exp = f"{expected_cpu:5.2f}" - minn = min(expected_cpu * 0.65, max(expected_cpu - 1.0, 0.0)) - maxx = max(expected_cpu * 1.15, expected_cpu + 5.0) - - if cpu_usage > maxx: - err = "using more CPU than expected" - elif cpu_usage < minn: - err = "using less CPU than expected" - else: - err = "NO METRICS FOUND" + usage = cpu_time / dt * 100. + + max_allowed = max(expected * 1.8, expected + 5.0) + if usage > max_allowed: + error = "❌ USING MORE CPU THAN EXPECTED ❌" + cpu_ok = False - result += f"{proc_name.ljust(35)} {cpu_usage:5.2f}% ({exp}%) {err}\n" - if len(err) > 0: + else: + error = "❌ NO METRICS FOUND ❌" cpu_ok = False - result += "------------------------------------------------\n" + + rows.append([proc_name, usage, expected, max_allowed, error or "✅"]) + print(tabulate(rows, header, tablefmt="simple_grid", stralign="center", numalign="center", floatfmt=".2f")) # Ensure there's no missing procs - all_procs = {p.name for p in self.service_msgs['managerState'][0].managerState.processes if p.shouldBeRunning} + all_procs = {p.name for p in self.msgs['managerState'][0].managerState.processes if p.shouldBeRunning} for p in all_procs: with subtests.test(proc=p): assert any(p in pp for pp in PROCS.keys()), f"Expected CPU usage missing for {p}" @@ -293,142 +275,172 @@ def test_cpu_usage(self, subtests): procs_tot = sum([(max(x) if isinstance(x, tuple) else x) for x in PROCS.values()]) with subtests.test(name="total CPU"): assert procs_tot < MAX_TOTAL_CPU, "Total CPU budget exceeded" - result += "------------------------------------------------\n" - result += f"Total allocated CPU usage is {procs_tot}%, budget is {MAX_TOTAL_CPU}%, {MAX_TOTAL_CPU-procs_tot:.1f}% left\n" - result += "------------------------------------------------\n" - - print(result) + print("------------------------------------------------") + print(f"Total allocated CPU usage is {procs_tot}%, budget is {MAX_TOTAL_CPU}%, {MAX_TOTAL_CPU-procs_tot:.1f}% left") + print("------------------------------------------------") assert cpu_ok def test_memory_usage(self): - mems = [m.deviceState.memoryUsagePercent for m in self.service_msgs['deviceState']] - print("Memory usage: ", mems) - - # check for big leaks. note that memory usage is - # expected to go up while the MSGQ buffers fill up - assert max(mems) - min(mems) <= 3.0 + print("\n------------------------------------------------") + print("--------------- Memory Usage -------------------") + print("------------------------------------------------") - def test_gpu_usage(self): - assert self.gpu_procs == {"weston", "ui", "camerad", "selfdrive.modeld.modeld"} + from openpilot.selfdrive.debug.mem_usage import print_report + print_report(self.msgs['procLog'], self.msgs['deviceState']) - def test_camera_processing_time(self): - result = "\n" - result += "------------------------------------------------\n" - result += "-------------- ImgProc Timing ------------------\n" - result += "------------------------------------------------\n" + offset = int(SERVICE_LIST['deviceState'].frequency * LOG_OFFSET) + mems = [m.deviceState.memoryUsagePercent for m in self.msgs['deviceState'][offset:]] + print("MSGQ (/dev/shm/) usage: ", subprocess.check_output(["du", "-hs", "/dev/shm"]).split()[0].decode()) - ts = [getattr(m, m.which()).processingTime for m in self.lr if 'CameraState' in m.which()] - assert min(ts) < 0.025, f"high execution time: {min(ts)}" - result += f"execution time: min {min(ts):.5f}s\n" - result += f"execution time: max {max(ts):.5f}s\n" - result += f"execution time: mean {np.mean(ts):.5f}s\n" - result += "------------------------------------------------\n" - print(result) + # check for big leaks. note that memory usage is + # expected to go up while the MSGQ buffers fill up + assert np.average(mems) <= 80, "Average memory usage too high" + assert np.max(np.diff(mems)) <= 4, "Max memory increase too high" + assert np.average(np.diff(mems)) <= 1, "Average memory increase too high" - @pytest.mark.skip("TODO: enable once timings are fixed") - def test_camera_frame_timings(self): + def test_camera_frame_timings(self, subtests): + # test timing within a single camera result = "\n" result += "------------------------------------------------\n" - result += "----------------- SoF Timing ------------------\n" + result += "----------------- SOF Timing ------------------\n" result += "------------------------------------------------\n" for name in ['roadCameraState', 'wideRoadCameraState', 'driverCameraState']: - ts = [getattr(m, m.which()).timestampSof for m in self.lr if name in m.which()] + ts = self.ts[name]['timestampSof'] d_ms = np.diff(ts) / 1e6 d50 = np.abs(d_ms-50) - assert max(d50) < 1.0, f"high sof delta vs 50ms: {max(d50)}" - result += f"{name} sof delta vs 50ms: min {min(d50):.5f}s\n" - result += f"{name} sof delta vs 50ms: max {max(d50):.5f}s\n" - result += f"{name} sof delta vs 50ms: mean {d50.mean():.5f}s\n" - result += "------------------------------------------------\n" - print(result) - - def test_mpc_execution_timings(self): - result = "\n" - result += "------------------------------------------------\n" - result += "----------------- MPC Timing ------------------\n" - result += "------------------------------------------------\n" - - cfgs = [("longitudinalPlan", 0.05, 0.05),] - for (s, instant_max, avg_max) in cfgs: - ts = [getattr(m, s).solverExecutionTime for m in self.service_msgs[s]] - assert max(ts) < instant_max, f"high '{s}' execution time: {max(ts)}" - assert np.mean(ts) < avg_max, f"high avg '{s}' execution time: {np.mean(ts)}" - result += f"'{s}' execution time: min {min(ts):.5f}s\n" - result += f"'{s}' execution time: max {max(ts):.5f}s\n" - result += f"'{s}' execution time: mean {np.mean(ts):.5f}s\n" + result += f"{name} sof delta vs 50ms: min {min(d50):.2f}ms\n" + result += f"{name} sof delta vs 50ms: max {max(d50):.2f}ms\n" + result += f"{name} sof delta vs 50ms: mean {d50.mean():.2f}ms\n" + with subtests.test(camera=name): + assert max(d50) < 5.0, f"high SOF delta vs 50ms: {max(d50)}" result += "------------------------------------------------\n" print(result) - def test_model_execution_timings(self): + def test_camera_sync(self, subtests): + cam_states = ['roadCameraState', 'wideRoadCameraState', 'driverCameraState'] + encode_cams = ['roadEncodeIdx', 'wideRoadEncodeIdx', 'driverEncodeIdx'] + for cams in (cam_states, encode_cams): + with subtests.test(cams=cams): + # sanity checks within a single cam + for cam in cams: + with subtests.test(test="frame_skips", camera=cam): + assert set(np.diff(self.ts[cam]['frameId'])) == {1, }, "Frame ID skips" + + # EOF > SOF + eof_sof_diff = self.ts[cam]['timestampEof'] - self.ts[cam]['timestampSof'] + assert np.all(eof_sof_diff > 0) + assert np.all(eof_sof_diff < 50*1e6) + + first_fid = {min(self.ts[c]['frameId']) for c in cams} + assert len(first_fid) == 1, "Cameras don't start on same frame ID" + if cam.endswith('CameraState'): + # camerad guarantees that all cams start on frame ID 0 + # (note loggerd also needs to start up fast enough to catch it) + assert next(iter(first_fid)) < 100, "Cameras start on frame ID too high" + + # we don't do a full segment rotation, so these might not match exactly + last_fid = {max(self.ts[c]['frameId']) for c in cams} + assert max(last_fid) - min(last_fid) < 10 + + start, end = min(first_fid), min(last_fid) + for i in range(end-start): + # road and wide cameras (first two) should be synced within 2ms + ts = {c: round(self.ts[c]['timestampSof'][i]/1e6, 1) for c in cams[:2]} + diff = (max(ts.values()) - min(ts.values())) + assert diff < 2, f"Cameras not synced properly: frame_id={start+i}, {diff=:.1f}ms, {ts=}" + + # driver camera should be staggered ~25ms from road camera + offset_ms = abs(self.ts[cams[2]]['timestampSof'][i] - self.ts[cams[0]]['timestampSof'][i]) / 1e6 + assert 20 < offset_ms < 30, f"driver camera stagger out of range at frame {start+i}: {offset_ms:.1f}ms" + + def test_camera_encoder_matches(self, subtests): + # sanity check that the frame metadata is consistent with the encoded frames + pairs = [('roadCameraState', 'roadEncodeIdx'), + ('wideRoadCameraState', 'wideRoadEncodeIdx'), + ('driverCameraState', 'driverEncodeIdx')] + for cam, enc in pairs: + with subtests.test(camera=cam, encoder=enc): + cam_frames = {fid: (sof, eof) for fid, sof, eof in zip( + self.ts[cam]['frameId'], + self.ts[cam]['timestampSof'], + self.ts[cam]['timestampEof'], + strict=True, + )} + for i, fid in enumerate(self.ts[enc]['frameId']): + cam_sof, cam_eof = cam_frames[fid] + enc_sof, enc_eof = self.ts[enc]['timestampSof'][i], self.ts[enc]['timestampEof'][i] + assert enc_sof == cam_sof, f"SOF mismatch: frameId={fid}, enc_sof={enc_sof}, cam_sof={cam_sof}" + assert enc_eof == cam_eof, f"EOF mismatch: frameId={fid}, enc_eof={enc_eof}, cam_eof={cam_eof}" + + def test_model_execution_timings(self, subtests): result = "\n" result += "------------------------------------------------\n" result += "----------------- Model Timing -----------------\n" result += "------------------------------------------------\n" - # TODO: this went up when plannerd cpu usage increased, why? cfgs = [ - ("modelV2", 0.050, 0.036), - ("driverStateV2", 0.050, 0.026), + # since multiple processes use the GPU and can preempt each other, + # these numbers are not fully self-contained. + ("modelV2", 0.06, 0.040), + + # can miss cycles here and there, just important the avg frequency is 20Hz + ("driverStateV2", 0.3, 0.05), ] for (s, instant_max, avg_max) in cfgs: - ts = [getattr(m, s).modelExecutionTime for m in self.service_msgs[s]] - assert max(ts) < instant_max, f"high '{s}' execution time: {max(ts)}" - assert np.mean(ts) < avg_max, f"high avg '{s}' execution time: {np.mean(ts)}" + ts = [getattr(m, s).modelExecutionTime for m in self.msgs[s] if (m.logMonoTime*1e-9 - self.ts[s]['t'][0]) > LOG_OFFSET] result += f"'{s}' execution time: min {min(ts):.5f}s\n" result += f"'{s}' execution time: max {max(ts):.5f}s\n" result += f"'{s}' execution time: mean {np.mean(ts):.5f}s\n" + with subtests.test(s): + assert max(ts) < instant_max, f"high '{s}' execution time: {max(ts)}" + assert np.mean(ts) < avg_max, f"high avg '{s}' execution time: {np.mean(ts)}" result += "------------------------------------------------\n" print(result) def test_timings(self): passed = True - result = "\n" - result += "------------------------------------------------\n" - result += "----------------- Service Timings --------------\n" - result += "------------------------------------------------\n" + print("\n------------------------------------------------") + print("----------------- Service Timings --------------") + print("------------------------------------------------") + + header = ['service', 'max', 'min', 'mean', 'expected mean', 'rsd', 'max allowed rsd', 'test result'] + rows = [] for s, (maxmin, rsd) in TIMINGS.items(): - msgs = [m.logMonoTime for m in self.service_msgs[s]] + offset = int(SERVICE_LIST[s].frequency * LOG_OFFSET) + msgs = [m.logMonoTime for m in self.msgs[s][offset:]] if not len(msgs): raise Exception(f"missing {s}") ts = np.diff(msgs) / 1e9 dt = 1 / SERVICE_LIST[s].frequency - try: - np.testing.assert_allclose(np.mean(ts), dt, rtol=0.03, err_msg=f"{s} - failed mean timing check") - np.testing.assert_allclose([np.max(ts), np.min(ts)], dt, rtol=maxmin, err_msg=f"{s} - failed max/min timing check") - except Exception as e: - result += str(e) + "\n" - passed = False - - if np.std(ts) / dt > rsd: - result += f"{s} - failed RSD timing check\n" - passed = False - - result += f"{s.ljust(40)}: {np.array([np.mean(ts), np.max(ts), np.min(ts)])*1e3}\n" - result += f"{''.ljust(40)} {np.max(np.absolute([np.max(ts)/dt, np.min(ts)/dt]))} {np.std(ts)/dt}\n" - result += "="*67 - print(result) + errors = [] + if not np.allclose(np.mean(ts), dt, rtol=0.03, atol=0): + errors.append("❌ FAILED MEAN TIMING CHECK ❌") + if not np.allclose([np.max(ts), np.min(ts)], dt, rtol=maxmin, atol=0): + errors.append("❌ FAILED MAX/MIN TIMING CHECK ❌") + if (np.std(ts)/dt) > rsd: + errors.append("❌ FAILED RSD TIMING CHECK ❌") + passed = not errors and passed + rows.append([s, *(np.array([np.max(ts), np.min(ts), np.mean(ts), dt])*1e3), np.std(ts)/dt, rsd, "\n".join(errors) or "✅"]) + + print(tabulate(rows, header, tablefmt="simple_grid", stralign="center", numalign="center", floatfmt=".2f")) assert passed @release_only def test_startup(self): - startup_alert = None - for msg in self.lrs[0]: - # can't use onroadEvents because the first msg can be dropped while loggerd is starting up - if msg.which() == "selfdriveState": - startup_alert = msg.selfdriveState.alertText1 - break - expected = EVENTS[car.OnroadEvent.EventName.startup][ET.PERMANENT].alert_text_1 + startup_alert = self.ts['selfdriveState']['alertText1'][0] + expected = EVENTS[log.OnroadEvent.EventName.startup][ET.PERMANENT].alert_text_1 assert startup_alert == expected, "wrong startup alert" def test_engagable(self): no_entries = Counter() - for m in self.service_msgs['onroadEvents']: + for m in self.msgs['onroadEvents']: for evt in m.onroadEvents: if evt.noEntry: no_entries[evt.name] += 1 - eng = [m.selfdriveState.engageable for m in self.service_msgs['selfdriveState']] + offset = int(SERVICE_LIST['selfdriveState'].frequency * LOG_OFFSET) + eng = [m.selfdriveState.engageable for m in self.msgs['selfdriveState'][offset:]] assert all(eng), \ f"Not engageable for whole segment:\n- selfdriveState.engageable: {Counter(eng)}\n- No entry events: {no_entries}" diff --git a/selfdrive/test/test_scons_tesla_radar_dbc.py b/selfdrive/test/test_scons_tesla_radar_dbc.py new file mode 100644 index 00000000000000..1db0440c726bea --- /dev/null +++ b/selfdrive/test/test_scons_tesla_radar_dbc.py @@ -0,0 +1,26 @@ +import subprocess +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +DBC_DIR = REPO / "opendbc_repo" / "opendbc" / "dbc" +TESLA_RADAR_DBCS = ( + DBC_DIR / "tesla_radar_bosch_generated.dbc", + DBC_DIR / "tesla_radar_continental_generated.dbc", +) + + +def test_minimal_scons_generates_tesla_radar_dbcs(): + for path in TESLA_RADAR_DBCS: + path.unlink(missing_ok=True) + + result = subprocess.run( + ["scons", "--minimal", "--no-cache", "opendbc_generated_dbcs"], + cwd=REPO, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stdout + "\n" + result.stderr + for path in TESLA_RADAR_DBCS: + assert path.is_file(), f"{path.name} missing after scons --minimal" + assert "AUTOGENERATED FILE" in path.read_text(encoding="utf-8") diff --git a/selfdrive/test/test_time_to_onroad.py b/selfdrive/test/test_time_to_onroad.py deleted file mode 100644 index 58e6cc3ccfb01a..00000000000000 --- a/selfdrive/test/test_time_to_onroad.py +++ /dev/null @@ -1,58 +0,0 @@ -import os -import pytest -import time -import subprocess - -from cereal import car -import cereal.messaging as messaging -from openpilot.common.basedir import BASEDIR -from openpilot.common.timeout import Timeout -from openpilot.selfdrive.test.helpers import set_params_enabled - -EventName = car.OnroadEvent.EventName - - -@pytest.mark.tici -def test_time_to_onroad(): - # launch - set_params_enabled() - manager_path = os.path.join(BASEDIR, "system/manager/manager.py") - proc = subprocess.Popen(["python", manager_path]) - - start_time = time.monotonic() - sm = messaging.SubMaster(['selfdriveState', 'controlsState', 'deviceState', 'onroadEvents']) - try: - # wait for onroad. timeout assumes panda is up to date - with Timeout(10, "timed out waiting to go onroad"): - while not sm['deviceState'].started: - sm.update(100) - - # wait for engageability - try: - with Timeout(10, "timed out waiting for engageable"): - initialized = False - while True: - sm.update(100) - - if sm.seen['onroadEvents'] and not any(EventName.controlsInitializing == e.name for e in sm['onroadEvents']): - initialized = True - - if initialized: - sm.update(100) - assert sm['selfdriveState'].engageable, f"events: {sm['onroadEvents']}" - break - finally: - print(f"onroad events: {sm['onroadEvents']}") - print(f"engageable after {time.monotonic() - start_time:.2f}s") - - # once we're enageable, must stay for the next few seconds - st = time.monotonic() - while (time.monotonic() - st) < 10.: - sm.update(100) - assert sm.all_alive(), sm.alive - assert sm['selfdriveState'].engageable, f"events: {sm['onroadEvents']}" - assert sm['controlsState'].cumLagMs < 10. - finally: - proc.terminate() - if proc.wait(20) is None: - proc.kill() diff --git a/selfdrive/test/test_updated.py b/selfdrive/test/test_updated.py index ea945d94c29487..e4cc714b87c6a9 100644 --- a/selfdrive/test/test_updated.py +++ b/selfdrive/test/test_updated.py @@ -50,7 +50,7 @@ def setup_method(self): f"git clone {BASEDIR} {self.git_remote_dir}", f"git clone {self.git_remote_dir} {self.basedir}", f"cd {self.basedir} && git submodule init && git submodule update", - f"cd {self.basedir} && scons -j{os.cpu_count()} cereal/ common/" + f"cd {self.basedir} && scons cereal/ common/" ]) self.params = Params(os.path.join(self.basedir, "persist/params")) @@ -92,7 +92,7 @@ def _get_updated_proc(self): return subprocess.Popen(updated_path, env=os.environ) def _start_updater(self, offroad=True, nosleep=False): - self.params.put_bool("IsOffroad", offroad) + self.params.put_bool("IsOffroad", offroad, block=True) self.updated_proc = self._get_updated_proc() if not nosleep: time.sleep(1) @@ -105,7 +105,7 @@ def _read_param(self, key, timeout=1): ret = None start_time = time.monotonic() while ret is None: - ret = self.params.get(key, encoding='utf8') + ret = self.params.get(key) if time.monotonic() - start_time > timeout: break time.sleep(0.01) @@ -162,8 +162,7 @@ def _make_commit(self): def _check_update_state(self, update_available): # make sure LastUpdateTime is recent - t = self._read_param("LastUpdateTime") - last_update_time = datetime.datetime.fromisoformat(t) + last_update_time = self._read_param("LastUpdateTime") td = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - last_update_time assert td.total_seconds() < 10 self.params.remove("LastUpdateTime") @@ -174,7 +173,7 @@ def _check_update_state(self, update_available): # check params update = self._read_param("UpdateAvailable") assert update == "1" == update_available, f"UpdateAvailable: {repr(update)}" - assert self._read_param("UpdateFailedCount") == "0" + assert self._read_param("UpdateFailedCount") == 0 # TODO: check that the finalized update actually matches remote # check the .overlay_init and .overlay_consistent flags diff --git a/selfdrive/test/update_ci_routes.py b/selfdrive/test/update_ci_routes.py index 2bf06b48603e51..54e1c88718f9f8 100755 --- a/selfdrive/test/update_ci_routes.py +++ b/selfdrive/test/update_ci_routes.py @@ -19,7 +19,7 @@ DEST = OpenpilotCIContainer -def upload_route(path: str, exclude_patterns: Iterable[str] = None) -> None: +def upload_route(path: str, exclude_patterns: Iterable[str] | None = None) -> None: if exclude_patterns is None: exclude_patterns = [r'dcamera\.hevc'] diff --git a/selfdrive/ui/.gitignore b/selfdrive/ui/.gitignore index f9724816da6c5c..30ae77d885e79e 100644 --- a/selfdrive/ui/.gitignore +++ b/selfdrive/ui/.gitignore @@ -1,17 +1,4 @@ -moc_* -*.moc - -translations/main_test_en.* - -_text -_spinner - -ui -mui -watch3 installer/installers/* -qt/setup/setup -qt/setup/reset -qt/setup/wifi -qt/setup/updater -translations/alerts_generated.h + +tests/diff/report +.coverage diff --git a/selfdrive/ui/SConscript b/selfdrive/ui/SConscript index 319ca4547c670f..3d668aef8fc9d2 100644 --- a/selfdrive/ui/SConscript +++ b/selfdrive/ui/SConscript @@ -1,112 +1,55 @@ -import os -import json -Import('qt_env', 'arch', 'common', 'messaging', 'visionipc', 'transformations') - -base_libs = [common, messaging, visionipc, transformations, - 'm', 'OpenCL', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] - -if arch == 'larch64': - base_libs.append('EGL') - -if arch == "Darwin": - del base_libs[base_libs.index('OpenCL')] - qt_env['FRAMEWORKS'] += ['OpenCL'] - -# FIXME: remove this once we're on 5.15 (24.04) -qt_env['CXXFLAGS'] += ["-Wno-deprecated-declarations"] - -qt_util = qt_env.Library("qt_util", ["#selfdrive/ui/qt/api.cc", "#selfdrive/ui/qt/util.cc"], LIBS=base_libs) -widgets_src = ["ui.cc", "qt/widgets/input.cc", "qt/widgets/wifi.cc", - "qt/widgets/ssh_keys.cc", "qt/widgets/toggle.cc", "qt/widgets/controls.cc", - "qt/widgets/offroad_alerts.cc", "qt/widgets/prime.cc", "qt/widgets/keyboard.cc", - "qt/widgets/scrollview.cc", "qt/widgets/cameraview.cc", "#third_party/qrcode/QrCode.cc", - "qt/request_repeater.cc", "qt/qt_window.cc", "qt/network/networking.cc", "qt/network/wifi_manager.cc"] - -widgets = qt_env.Library("qt_widgets", widgets_src, LIBS=base_libs) -Export('widgets') -qt_libs = [widgets, qt_util] + base_libs - -qt_src = ["main.cc", "qt/sidebar.cc", "qt/body.cc", - "qt/window.cc", "qt/home.cc", "qt/offroad/settings.cc", - "qt/offroad/software_settings.cc", "qt/offroad/onboarding.cc", - "qt/offroad/driverview.cc", "qt/offroad/experimental_mode.cc", - "qt/onroad/onroad_home.cc", "qt/onroad/annotated_camera.cc", - "qt/onroad/buttons.cc", "qt/onroad/alerts.cc", "qt/onroad/driver_monitoring.cc"] - -# build translation files -with open(File("translations/languages.json").abspath) as f: - languages = json.loads(f.read()) -translation_sources = [f"#selfdrive/ui/translations/{l}.ts" for l in languages.values()] -translation_targets = [src.replace(".ts", ".qm") for src in translation_sources] -lrelease_bin = 'third_party/qt5/larch64/bin/lrelease' if arch == 'larch64' else 'lrelease' - -lupdate = qt_env.Command(translation_sources + ["translations/alerts_generated.h"], qt_src + widgets_src, "selfdrive/ui/update_translations.py") -lrelease = qt_env.Command(translation_targets, translation_sources, f"{lrelease_bin} $SOURCES") -qt_env.Depends(lrelease, lupdate) -qt_env.NoClean(translation_sources) -qt_env.Precious(translation_sources) -qt_env.NoCache(lupdate) - -# create qrc file for compiled translations to include with assets -translations_assets_src = "#selfdrive/assets/translations_assets.qrc" -with open(File(translations_assets_src).abspath, 'w') as f: - f.write('\n\n') - f.write('\n'.join([f'../ui/translations/{l}.qm' for l in languages.values()])) - f.write('\n\n') - -# build assets -assets = "#selfdrive/assets/assets.cc" -assets_src = "#selfdrive/assets/assets.qrc" -qt_env.Command(assets, [assets_src, translations_assets_src], f"rcc $SOURCES -o $TARGET") -qt_env.Depends(assets, Glob('#selfdrive/assets/*', exclude=[assets, assets_src, translations_assets_src, "#selfdrive/assets/assets.o"]) + [lrelease]) -asset_obj = qt_env.Object("assets", assets) - -# build main UI -qt_env.Program("ui", qt_src + [asset_obj], LIBS=qt_libs) -if GetOption('extras'): - qt_src.remove("main.cc") # replaced by test_runner - qt_env.Program('tests/test_translations', [asset_obj, 'tests/test_runner.cc', 'tests/test_translations.cc'] + qt_src, LIBS=qt_libs) - -if GetOption('extras') and arch != "Darwin": - qt_env.SharedLibrary("qt/python_helpers", ["qt/qt_window.cc"], LIBS=qt_libs) - - # spinner and text window - qt_env.Program("_text", ["qt/text.cc"], LIBS=qt_libs) - qt_env.Program("_spinner", ["qt/spinner.cc"], LIBS=qt_libs) - - - # setup and factory resetter - qt_env.Program("qt/setup/reset", ["qt/setup/reset.cc"], LIBS=qt_libs) - qt_env.Program("qt/setup/setup", ["qt/setup/setup.cc", asset_obj], - LIBS=qt_libs + ['curl', 'common']) - - # build updater UI - qt_env.Program("qt/setup/updater", ["qt/setup/updater.cc", asset_obj], LIBS=qt_libs) - +from pathlib import Path +import importlib.util + +Import('env', 'arch', 'common') + +# build the fonts +generator = File("#selfdrive/assets/fonts/process.py") +source_files = Glob("#selfdrive/assets/fonts/*.ttf") + Glob("#selfdrive/assets/fonts/*.otf") +output_files = [ + (f"#{Path(f.path).with_suffix('.fnt')}", f"#{Path(f.path).with_suffix('.png')}") + for f in source_files + if "NotoColor" not in f.name +] +env.Command( + target=output_files, + source=[generator, source_files], + action=f"python3 {generator}", +) + + +if GetOption('extras') and arch == "larch64": # build installers - senv = qt_env.Clone() - senv['LINKFLAGS'].append('-Wl,-strip-debug') + raylib_dir = Path(importlib.util.find_spec("raylib").submodule_search_locations[0]) / "install" + raylib_env = env.Clone() + raylib_env['CPPPATH'] += [str(raylib_dir / "include")] + raylib_env['LIBPATH'] += [str(raylib_dir / "lib")] + raylib_env['LINKFLAGS'].append('-Wl,-strip-debug') + + raylib_libs = common + ["raylib_comma", "GLESv2", "EGL", "gbm", "drm"] release = "release3" installers = [ ("openpilot", release), ("openpilot_test", f"{release}-staging"), ("openpilot_nightly", "nightly"), - ("openpilot_internal", "master"), + ("openpilot_internal", "nightly-dev"), ] - cont = senv.Command(f"installer/continue_openpilot.o", f"installer/continue_openpilot.sh", - "ld -r -b binary -o $TARGET $SOURCE") + cont = raylib_env.Command("installer/continue_openpilot.o", "installer/continue_openpilot.sh", + "ld -r -b binary -o $TARGET $SOURCE") + inter = raylib_env.Command("installer/inter_ttf.o", "installer/inter-ascii.ttf", + "ld -r -b binary -o $TARGET $SOURCE") + inter_bold = raylib_env.Command("installer/inter_bold.o", "../assets/fonts/Inter-Bold.ttf", + "ld -r -b binary -o $TARGET $SOURCE") + inter_light = raylib_env.Command("installer/inter_light.o", "../assets/fonts/Inter-Light.ttf", + "ld -r -b binary -o $TARGET $SOURCE") for name, branch in installers: d = {'BRANCH': f"'\"{branch}\"'"} if "internal" in name: d['INTERNAL'] = "1" - obj = senv.Object(f"installer/installers/installer_{name}.o", ["installer/installer.cc"], CPPDEFINES=d) - f = senv.Program(f"installer/installers/installer_{name}", [obj, cont], LIBS=qt_libs) + obj = raylib_env.Object(f"installer/installers/installer_{name}.o", ["installer/installer.cc"], CPPDEFINES=d) + f = raylib_env.Program(f"installer/installers/installer_{name}", [obj, cont, inter, inter_bold, inter_light], LIBS=raylib_libs) # keep installers small - assert f[0].get_size() < 370*1e3 - -# build watch3 -if arch in ['x86_64', 'aarch64', 'Darwin'] or GetOption('extras'): - qt_env.Program("watch3", ["watch3.cc"], LIBS=qt_libs + ['common', 'msgq', 'visionipc']) + assert f[0].get_size() < 2500*1e3, f[0].get_size() diff --git a/selfdrive/ui/__init__.py b/selfdrive/ui/__init__.py index e69de29bb2d1d6..b07e842f1a3bee 100644 --- a/selfdrive/ui/__init__.py +++ b/selfdrive/ui/__init__.py @@ -0,0 +1 @@ +UI_BORDER_SIZE = 30 diff --git a/selfdrive/ui/body/__init__.py b/selfdrive/ui/body/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/selfdrive/ui/body/animations.py b/selfdrive/ui/body/animations.py new file mode 100644 index 00000000000000..c40f7ecdefe6f1 --- /dev/null +++ b/selfdrive/ui/body/animations.py @@ -0,0 +1,278 @@ +from dataclasses import dataclass +from enum import Enum +import time + + +class AnimationMode(Enum): + ONCE_FORWARD = 1 + ONCE_FORWARD_BACKWARD = 2 + REPEAT_FORWARD = 3 + REPEAT_FORWARD_BACKWARD = 4 + + +@dataclass +class Animation: + frames: list[list[tuple[int, int]]] + starting_frames: list[list[tuple[int, int]]] | None = None # played once before the main loop + frame_duration: float = 0.15 # seconds each frame is shown + mode: AnimationMode = AnimationMode.REPEAT_FORWARD_BACKWARD + repeat_interval: float = 5.0 # seconds between animation restarts (only for REPEAT modes) + hold_end: float = 0.0 # seconds to hold the last frame before playing backward (only for *_BACKWARD modes) + left_turn_remove: list[tuple[int, int]] | None = None # dots to remove from frame when turning left + right_turn_remove: list[tuple[int, int]] | None = None # dots to remove from frame when turning right + + +# --- Animation Helper Functions --- + +def _mirror(dots: list[tuple[int, int]]) -> list[tuple[int, int]]: + """Mirror a component from the left side of the face to the right""" + return [(r, 15 - c) for r, c in dots] + + +def _mirror_no_flip(dots: list[tuple[int, int]]) -> list[tuple[int, int]]: + """Move a component to the mirrored position on the right half without flipping its shape.""" + min_c = min(c for _, c in dots) + max_c = max(c for _, c in dots) + return [(r, 15 - max_c - min_c + c) for r, c in dots] + + +def _shift(dots: list[tuple[int, int]], rc: tuple[int, int]) -> list[tuple[int, int]]: + dr, dc = rc + return [(r + dr, c + dc) for r, c in dots] + + +def _make_frame(left_eye: list[tuple[int, int]], right_eye: list[tuple[int, int]], + left_brow: list[tuple[int, int]], right_brow: list[tuple[int, int]], + mouth: list[tuple[int, int]]) -> list[tuple[int, int]]: + return left_eye + left_brow + right_eye + right_brow + mouth + + +# --- Animation Helper Components --- + +# Eyes (left side) +EYE_OPEN = [ + (2, 2), (2, 3), +(3, 1), (3, 2), (3, 3), (3, 4), +(4, 1), (4, 2), (4, 3), (4, 4), + (5, 2), (5, 3) +] +EYE_HALF = [ +(4, 1), (4, 2), (4, 3), (4, 4), + (5, 2), (5, 3) +] +EYE_CLOSED = [ +(4, 1), (4, 4), + (5, 2), (5, 3), +] +EYE_LEFT_LOOK = [ + (2, 2), (2, 3), +(3, 1), (3, 2), +(4, 1), (4, 2), + (5, 2), (5, 3), +] +EYE_RIGHT_LOOK = [ + (2, 2), (2, 3), + (3, 3), (3, 4), + (4, 3), (4, 4), + (5, 2), (5, 3), +] + +# Eyebrows (left side) +BROW_HIGH = [ + (0, 1), (0, 2), +(1, 0), +] +BROW_LOWERED = [ + (1, 1), (1, 2), +(2, 0) +] +BROW_STRAIGHT = [(1, 0), (1, 1), (1, 2)] +BROW_DOWN = [ +(0, 1), (0, 2), + (1, 3) +] + +# Mouths (centered, not mirrored) +MOUTH_SMILE = [ +(6, 6), (6, 9), + (7, 7), (7, 8), +] +MOUTH_NORMAL = [(7, 7), (7, 8)] +MOUTH_SAD = [ + (6, 7), (6, 8), +(7, 6), (7, 9) +] + +# --- Animations --- + +NORMAL = Animation( + frames=[ + _make_frame(EYE_OPEN, _mirror(EYE_OPEN), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_HALF, _mirror(EYE_HALF), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_CLOSED, _mirror(EYE_CLOSED), BROW_LOWERED, _mirror(BROW_LOWERED), MOUTH_SMILE), + ], + left_turn_remove=[ + (3, 3), (3, 4), + (4, 3), (4, 4), + ] + _mirror_no_flip([ + (3, 1), (3, 2), + (4, 1), (4, 2), + ]), + right_turn_remove=[ + (3, 1), (3, 2), + (4, 1), (4, 2), + ] + _mirror_no_flip([ + (3, 3), (3, 4), + (4, 3), (4, 4), + ]) +) + +ASLEEP = Animation( + frames=[ + _make_frame(EYE_CLOSED, _mirror(EYE_CLOSED), [], [], MOUTH_NORMAL), + ], +) + +SLEEPY = Animation( + frames=[ + _make_frame(EYE_CLOSED, _mirror(EYE_CLOSED), _shift(BROW_STRAIGHT, (1, 0)), [], MOUTH_NORMAL), + _make_frame(EYE_HALF, _mirror(EYE_CLOSED), BROW_LOWERED, [], MOUTH_NORMAL), + _make_frame(EYE_OPEN, _mirror(EYE_CLOSED), BROW_HIGH, [], MOUTH_NORMAL) + ], + frame_duration=0.25, + mode=AnimationMode.ONCE_FORWARD_BACKWARD, + repeat_interval=10, + hold_end=1.5, +) + +INQUISITIVE = Animation( + frames=[ + _make_frame(EYE_OPEN, _mirror(EYE_OPEN), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + + _make_frame(EYE_LEFT_LOOK, _mirror(EYE_RIGHT_LOOK), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_LEFT_LOOK, (0, -1)), _shift(_mirror(EYE_RIGHT_LOOK), (0, -1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_LEFT_LOOK, (0, -1)), _shift(_mirror(EYE_RIGHT_LOOK), (0, -1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_LEFT_LOOK, (0, -1)), _shift(_mirror(EYE_RIGHT_LOOK), (0, -1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_LEFT_LOOK, _mirror(EYE_RIGHT_LOOK), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + + _make_frame(EYE_RIGHT_LOOK, _mirror(EYE_LEFT_LOOK), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_RIGHT_LOOK, (0, 1)), _shift(_mirror(EYE_LEFT_LOOK), (0, 1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_RIGHT_LOOK, (0, 1)), _shift(_mirror(EYE_LEFT_LOOK), (0, 1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_RIGHT_LOOK, (0, 1)), _shift(_mirror(EYE_LEFT_LOOK), (0, 1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_RIGHT_LOOK, _mirror(EYE_LEFT_LOOK), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + + _make_frame(EYE_OPEN, _mirror(EYE_OPEN), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + ], + mode=AnimationMode.REPEAT_FORWARD, + frame_duration=0.15, + repeat_interval=10 +) + +WINK = Animation( + frames=[ + _make_frame(EYE_OPEN, _mirror(EYE_OPEN), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_OPEN, _mirror(EYE_CLOSED), BROW_HIGH, _mirror(_shift(BROW_DOWN, (0, 2))), MOUTH_SMILE), + ], + mode=AnimationMode.ONCE_FORWARD_BACKWARD, + frame_duration=0.75, +) + + +# --- Face Animator Class --- + +class FaceAnimator: + def __init__(self, animation: Animation): + self._animation = animation + self._next: Animation | None = None + self._start_time = time.monotonic() + self._rewinding = False + self._rewind_start: float = 0.0 + self._rewind_from: int = 0 + self._seen_nonzero = False + + def set_animation(self, animation: Animation): + if animation is not self._animation: + self._next = animation + + def get_dots(self) -> list[tuple[int, int]]: + now = time.monotonic() + elapsed = now - self._start_time + + # Handle rewind for forward-only animations + if self._rewinding: + rewind_elapsed = now - self._rewind_start + frames_back = round(rewind_elapsed / self._animation.frame_duration) + frame_index = self._rewind_from - frames_back + if frame_index <= 0: + return self._switch_to_next(now) + return self._animation.frames[frame_index] + + # Play starting frames first (once) + starting = self._animation.starting_frames or [] + starting_duration = len(starting) * self._animation.frame_duration + if starting and elapsed < starting_duration: + frame_index = min(int(elapsed / self._animation.frame_duration), len(starting) - 1) + return starting[frame_index] + + # Main loop + loop_elapsed = elapsed - starting_duration if starting else elapsed + frame_index = _get_frame_index(self._animation, loop_elapsed, gap_first=bool(starting)) + + if frame_index != 0: + self._seen_nonzero = True + + if self._next is not None: + if frame_index == 0 and (len(self._animation.frames) == 1 or self._seen_nonzero): + return self._switch_to_next(now) + # No natural return to frame 0 — start rewinding + if self._animation.mode in (AnimationMode.ONCE_FORWARD, AnimationMode.REPEAT_FORWARD): + self._rewinding = True + self._rewind_start = now + self._rewind_from = frame_index + + return self._animation.frames[frame_index] + + def _switch_to_next(self, now: float) -> list[tuple[int, int]]: + self._animation = self._next + self._next = None + self._rewinding = False + self._seen_nonzero = False + self._start_time = now + return self._animation.frames[0] + + +def _get_frame_index(animation: Animation, elapsed: float, gap_first: bool = False) -> int: + """Get the current frame index given elapsed time and animation mode.""" + num_frames = len(animation.frames) + if num_frames == 1: + return 0 + + fd = animation.frame_duration + has_backward = animation.mode in (AnimationMode.ONCE_FORWARD_BACKWARD, AnimationMode.REPEAT_FORWARD_BACKWARD) + repeats = animation.mode in (AnimationMode.REPEAT_FORWARD, AnimationMode.REPEAT_FORWARD_BACKWARD) + + forward_duration = num_frames * fd + backward_frames = max(num_frames - 2, 0) if has_backward else 0 + hold = animation.hold_end if has_backward else 0.0 + cycle_duration = forward_duration + hold + backward_frames * fd + + if not repeats: + t = min(elapsed, cycle_duration) + else: + t = (elapsed + cycle_duration if gap_first else elapsed) % animation.repeat_interval + + # Forward phase + if t < forward_duration: + return min(int(t / fd), num_frames - 1) + t -= forward_duration + + # Hold at last frame + if t < hold: + return num_frames - 1 + t -= hold + + # Backward phase + if backward_frames and t < backward_frames * fd: + return num_frames - 2 - min(int(t / fd), backward_frames - 1) + + return 0 if has_backward else num_frames - 1 diff --git a/selfdrive/ui/body/layouts/__init__.py b/selfdrive/ui/body/layouts/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/selfdrive/ui/body/layouts/onroad.py b/selfdrive/ui/body/layouts/onroad.py new file mode 100644 index 00000000000000..d7e9f419cca6e3 --- /dev/null +++ b/selfdrive/ui/body/layouts/onroad.py @@ -0,0 +1,93 @@ +import time +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.body.animations import FaceAnimator, ASLEEP, INQUISITIVE, NORMAL, SLEEPY + +GRID_COLS = 16 +GRID_ROWS = 8 +DOT_RADIUS = 50 if gui_app.big_ui() else 10 + +IDLE_TIMEOUT = 30.0 # seconds of no joystick input before playing INQUISITIVE +IDLE_STEER_THRESH = 0.5 # degrees — below this counts as no input +IDLE_SPEED_THRESH = 0.01 # m/s — below this counts as no input + + +# This class is used both in BIG (tizi) and small (mici) UIs +class BodyLayout(Widget): + def __init__(self): + super().__init__() + self._animator = FaceAnimator(ASLEEP) + self._turning_left = False + self._turning_right = False + self._last_input_time = time.monotonic() + self._was_active = False + self._offroad_label = UnifiedLabel("turn on ignition to use", 95 if gui_app.big_ui() else 45, FontWeight.DISPLAY, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + def draw_dot_grid(self, rect: rl.Rectangle, dots: list[tuple[int, int]], color: rl.Color): + spacing = min(rect.height / GRID_ROWS, rect.width / GRID_COLS) + + grid_w = (GRID_COLS - 1) * spacing + grid_h = (GRID_ROWS - 1) * spacing + + offset_x = rect.x + (rect.width - grid_w) / 2 + offset_y = rect.y + (rect.height - grid_h) / 2 + + for row, col in dots: + x = int(offset_x + col * spacing) + y = int(offset_y + row * spacing) + rl.draw_circle(x, y, DOT_RADIUS, color) + + def _update_state(self): + super()._update_state() + + sm = ui_state.sm + + if ui_state.is_onroad(): + if not self._was_active: + self._last_input_time = time.monotonic() + self._was_active = True + + cs = sm['carState'] + has_input = abs(cs.steeringAngleDeg) > IDLE_STEER_THRESH or abs(cs.vEgo) > IDLE_SPEED_THRESH + if has_input: + self._last_input_time = time.monotonic() + + if time.monotonic() - self._last_input_time > IDLE_TIMEOUT: + self._animator.set_animation(INQUISITIVE) + else: + self._animator.set_animation(NORMAL) + else: + self._was_active = False + self._animator.set_animation(ASLEEP) + + steer = sm['testJoystick'].axes[1] if len(sm['testJoystick'].axes) > 1 else 0 + self._turning_left = steer <= -0.05 + self._turning_right = steer >= 0.05 + + # play animation on screen tap + def _handle_mouse_release(self, mouse_pos): + super()._handle_mouse_release(mouse_pos) + if not self._was_active: + self._animator.set_animation(SLEEPY) + + def _render(self, rect: rl.Rectangle): + dots = self._animator.get_dots() + animation = self._animator._animation + if self._turning_left and animation.left_turn_remove: + remove_set = set(animation.left_turn_remove) + dots = [d for d in dots if d not in remove_set] + elif self._turning_right and animation.right_turn_remove: + remove_set = set(animation.right_turn_remove) + dots = [d for d in dots if d not in remove_set] + self.draw_dot_grid(rect, dots, rl.WHITE) + + if ui_state.is_offroad(): + rl.draw_rectangle(int(self.rect.x), int(self.rect.y), int(self.rect.width), int(self.rect.height), rl.Color(0, 0, 0, 175)) + upper_half = rl.Rectangle(rect.x, rect.y, rect.width, rect.height / 2) + self._offroad_label.render(upper_half) diff --git a/selfdrive/ui/feedback/feedbackd.py b/selfdrive/ui/feedback/feedbackd.py new file mode 100755 index 00000000000000..62f1e1db39c020 --- /dev/null +++ b/selfdrive/ui/feedback/feedbackd.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Bookmark + voice note. + +Every bookmarkButton press (settings sidebar "Bookmark" or the onroad flag): + * immediately publishes userBookmark, so the segment is flagged/preserved, and + * starts a voice note from the comma mic (rawAudioData from micd). +A second press stops the note early; otherwise it auto-stops after +VOICE_NOTE_MAX_DURATION. Audio is logged as audioFeedback blocks in the rlog and +also written as a WAV in the active segment dir: + /--/bookmark_.wav +""" +import os +import time +import wave +import datetime + +import cereal.messaging as messaging +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.system.hardware.hw import Paths +from openpilot.system.micd import SAMPLE_RATE, SAMPLE_BUFFER + +VOICE_NOTE_MAX_DURATION = 30.0 +FEEDBACK_MAX_DURATION = VOICE_NOTE_MAX_DURATION # used by the selfdrived audioFeedback alert +# a second tap this soon after the first is treated as a bounce, not a stop +MIN_STOP_DELAY = 0.5 +# CLOCK_MONOTONIC is shared across processes. Ignore a stale dashboard request (e.g. queued before this process started) +DASH_REQUEST_MAX_AGE = 5.0 + + +def active_segment_dir(root: str | None = None) -> str | None: + """Newest segment dir that loggerd is still writing (has a .lock file).""" + root = root or Paths.log_root() + try: + dirs = [os.path.join(root, d) for d in os.listdir(root) if "--" in d] + except OSError: + return None + dirs = [d for d in dirs if os.path.isdir(d)] + for d in sorted(dirs, key=os.path.getmtime, reverse=True): + try: + if any(f.endswith(".lock") for f in os.listdir(d)): + return d + except OSError: + continue + return None + + +class VoiceNote: + def __init__(self, seg_dir: str | None, stamp: str): + self.start_t = time.monotonic() + self.block_num = 0 + self.path = None + self._wav = None + if seg_dir is not None: + self.path = os.path.join(seg_dir, f"bookmark_{stamp}.wav") + try: + self._wav = wave.open(self.path + ".tmp", "wb") + self._wav.setnchannels(1) + self._wav.setsampwidth(2) + self._wav.setframerate(SAMPLE_RATE) + except OSError: + cloudlog.exception("feedbackd: could not open voice note file") + self._wav = None + + def add(self, data: bytes): + self.block_num += 1 + if self._wav is not None: + try: + self._wav.writeframes(data) + except OSError: + cloudlog.exception("feedbackd: voice note write failed") + + def duration(self) -> float: + return self.block_num * SAMPLE_BUFFER / SAMPLE_RATE + + def close(self): + if self._wav is not None: + try: + self._wav.close() + os.replace(self.path + ".tmp", self.path) + cloudlog.event("bookmark_voice_note_saved", path=self.path, duration=self.duration()) + except OSError: + cloudlog.exception("feedbackd: voice note close failed") + self._wav = None + + +def main(): + pm = messaging.PubMaster(['userBookmark', 'audioFeedback']) + # No carState here: carState is at the msgq reader limit. + sm = messaging.SubMaster(['rawAudioData', 'bookmarkButton']) + params = Params() + note: VoiceNote | None = None + last_left = -1 + params.remove("NAPBookmarkRecording") + + while True: + sm.update() + + # Web dashboard tap (nap_dash server) arrives as a param, not a second + # bookmarkButton publisher (msgq allows one publisher per service). + dash_tap = False + req = params.get("NAPBookmarkRequest") + if req is not None: + params.remove("NAPBookmarkRequest") + dash_tap = abs(time.monotonic() - int(req)) < DASH_REQUEST_MAX_AGE + + if sm.updated['bookmarkButton'] or dash_tap: + if note is None: + stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + cloudlog.event("bookmark_pressed", stamp=stamp) + pm.send('userBookmark', messaging.new_message('userBookmark', valid=True)) + note = VoiceNote(active_segment_dir(), stamp) + elif time.monotonic() - note.start_t > MIN_STOP_DELAY: + cloudlog.info("bookmark pressed again - stopping voice note") + note.close() + note = None + + if note is not None and sm.updated['rawAudioData']: + raw_audio = sm['rawAudioData'] + msg = messaging.new_message('audioFeedback', valid=True) + msg.audioFeedback.audio.data = raw_audio.data + msg.audioFeedback.audio.sampleRate = raw_audio.sampleRate + msg.audioFeedback.blockNum = note.block_num + note.add(raw_audio.data) + pm.send('audioFeedback', msg) + if note.duration() >= VOICE_NOTE_MAX_DURATION: + note.close() + note = None + + # Recording status for the web dashboard: seconds left, absent when idle. + left = -1 if note is None else max(0, int(VOICE_NOTE_MAX_DURATION - note.duration())) + if left != last_left: + if left < 0: + params.remove("NAPBookmarkRecording") + else: + params.put("NAPBookmarkRecording", left) + last_left = left + + +if __name__ == '__main__': + main() diff --git a/selfdrive/ui/installer/installer.cc b/selfdrive/ui/installer/installer.cc index 17f6ba19abd08f..176c2d510fbb72 100644 --- a/selfdrive/ui/installer/installer.cc +++ b/selfdrive/ui/installer/installer.cc @@ -1,19 +1,16 @@ -#include -#include - -#include +#include +#include #include #include -#include -#include -#include -#include -#include +#include "common/swaglog.h" +#include "common/util.h" +#include "system/hardware/hw.h" +#include "raylib.h" -#include "selfdrive/ui/installer/installer.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" +int freshClone(); +int cachedFetch(const std::string &cache); +int executeGitCommand(const std::string &cmd); std::string get_str(std::string const s) { std::string::size_type pos = s.find('?'); @@ -28,20 +25,54 @@ const std::string BRANCH_STR = get_str(BRANCH "? #define GIT_SSH_URL "git@github.com:commaai/openpilot.git" #define CONTINUE_PATH "/data/continue.sh" -const QString CACHE_PATH = "/data/openpilot.cache"; +const std::string INSTALL_PATH = "/data/openpilot"; +const std::string VALID_CACHE_PATH = "/data/.openpilot_cache"; -#define INSTALL_PATH "/data/openpilot" #define TMP_INSTALL_PATH "/data/tmppilot" +const int FONT_SIZE = 160; + extern const uint8_t str_continue[] asm("_binary_selfdrive_ui_installer_continue_openpilot_sh_start"); extern const uint8_t str_continue_end[] asm("_binary_selfdrive_ui_installer_continue_openpilot_sh_end"); - -bool time_valid() { - time_t rawtime; - time(&rawtime); - - struct tm * sys_time = gmtime(&rawtime); - return (1900 + sys_time->tm_year) >= 2020; +extern const uint8_t inter_ttf[] asm("_binary_selfdrive_ui_installer_inter_ascii_ttf_start"); +extern const uint8_t inter_ttf_end[] asm("_binary_selfdrive_ui_installer_inter_ascii_ttf_end"); +extern const uint8_t inter_light_ttf[] asm("_binary_selfdrive_assets_fonts_Inter_Light_ttf_start"); +extern const uint8_t inter_light_ttf_end[] asm("_binary_selfdrive_assets_fonts_Inter_Light_ttf_end"); +extern const uint8_t inter_bold_ttf[] asm("_binary_selfdrive_assets_fonts_Inter_Bold_ttf_start"); +extern const uint8_t inter_bold_ttf_end[] asm("_binary_selfdrive_assets_fonts_Inter_Bold_ttf_end"); + +Font font_inter; +Font font_roman; +Font font_display; + +const bool tici_device = Hardware::get_device_type() == cereal::InitData::DeviceType::TICI || + Hardware::get_device_type() == cereal::InitData::DeviceType::TIZI; + +std::vector tici_prebuilt_branches = {"release3", "release-tici", "release3-staging", "nightly", "nightly-dev"}; +std::string migrated_branch; + +void branchMigration() { + migrated_branch = BRANCH_STR; + cereal::InitData::DeviceType device_type = Hardware::get_device_type(); + if (device_type == cereal::InitData::DeviceType::TICI) { + if (std::find(tici_prebuilt_branches.begin(), tici_prebuilt_branches.end(), BRANCH_STR) != tici_prebuilt_branches.end()) { + migrated_branch = "release-tici"; + } else if (BRANCH_STR == "master") { + migrated_branch = "master-tici"; + } + } else if (device_type == cereal::InitData::DeviceType::TIZI) { + if (BRANCH_STR == "release3") { + migrated_branch = "release-tizi"; + } else if (BRANCH_STR == "release3-staging") { + migrated_branch = "release-tizi-staging"; + } + } else if (device_type == cereal::InitData::DeviceType::MICI) { + if (BRANCH_STR == "release3") { + migrated_branch = "release-mici"; + } else if (BRANCH_STR == "release3-staging") { + migrated_branch = "release-mici-staging"; + } + } } void run(const char* cmd) { @@ -49,133 +80,126 @@ void run(const char* cmd) { assert(err == 0); } -Installer::Installer(QWidget *parent) : QWidget(parent) { - QVBoxLayout *layout = new QVBoxLayout(this); - layout->setContentsMargins(150, 290, 150, 150); - layout->setSpacing(0); - - QLabel *title = new QLabel(tr("Installing...")); - title->setStyleSheet("font-size: 90px; font-weight: 600;"); - layout->addWidget(title, 0, Qt::AlignTop); - - layout->addSpacing(170); - - bar = new QProgressBar(); - bar->setRange(0, 100); - bar->setTextVisible(false); - bar->setFixedHeight(72); - layout->addWidget(bar, 0, Qt::AlignTop); - - layout->addSpacing(30); - - val = new QLabel("0%"); - val->setStyleSheet("font-size: 70px; font-weight: 300;"); - layout->addWidget(val, 0, Qt::AlignTop); - - layout->addStretch(); - - QObject::connect(&proc, QOverload::of(&QProcess::finished), this, &Installer::cloneFinished); - QObject::connect(&proc, &QProcess::readyReadStandardError, this, &Installer::readProgress); - - QTimer::singleShot(100, this, &Installer::doInstall); - - setStyleSheet(R"( - * { - font-family: Inter; - color: white; - background-color: black; - } - QProgressBar { - border: none; - background-color: #292929; +void finishInstall() { + BeginDrawing(); + ClearBackground(BLACK); + if (tici_device) { + const char *m = "Finishing install..."; + int text_width = MeasureText(m, FONT_SIZE); + DrawTextEx(font_display, m, (Vector2){(float)(GetScreenWidth() - text_width)/2 + FONT_SIZE, (float)(GetScreenHeight() - FONT_SIZE)/2}, FONT_SIZE, 0, WHITE); + } else { + DrawTextEx(font_display, "finishing setup", (Vector2){12, 0}, 77, 0, (Color){255, 255, 255, (unsigned char)(255 * 0.9)}); } - QProgressBar::chunk { - background-color: #364DEF; - } - )"); + EndDrawing(); + util::sleep_for(60 * 1000); } -void Installer::updateProgress(int percent) { - bar->setValue(percent); - val->setText(QString("%1%").arg(percent)); - update(); +void renderProgress(int progress) { + BeginDrawing(); + ClearBackground(BLACK); + if (tici_device) { + DrawTextEx(font_inter, "Installing...", (Vector2){150, 290}, 110, 0, WHITE); + Rectangle bar = {150, 570, (float)GetScreenWidth() - 300, 72}; + DrawRectangleRec(bar, (Color){41, 41, 41, 255}); + progress = std::clamp(progress, 0, 100); + bar.width *= progress / 100.0f; + DrawRectangleRec(bar, (Color){70, 91, 234, 255}); + DrawTextEx(font_inter, (std::to_string(progress) + "%").c_str(), (Vector2){150, 670}, 85, 0, WHITE); + } else { + DrawTextEx(font_display, "installing...", (Vector2){12, 0}, 77, 0, (Color){255, 255, 255, (unsigned char)(255 * 0.9)}); + const std::string percent_str = std::to_string(progress) + "%"; + DrawTextEx(font_inter, percent_str.c_str(), (Vector2){12, (float)(GetScreenHeight() - 154 + 20)}, 154, 0, + (Color){255, 255, 255, (unsigned char)(255 * 0.9 * 0.65)}); + } + + EndDrawing(); } -void Installer::doInstall() { +int doInstall() { // wait for valid time - while (!time_valid()) { - usleep(500 * 1000); - qDebug() << "Waiting for valid time"; + while (!util::system_time_valid()) { + util::sleep_for(500); + LOGD("Waiting for valid time"); } // cleanup previous install attempts - run("rm -rf " TMP_INSTALL_PATH " " INSTALL_PATH); + run("rm -rf " TMP_INSTALL_PATH); // do the install - if (QDir(CACHE_PATH).exists()) { - cachedFetch(CACHE_PATH); + if (util::file_exists(INSTALL_PATH) && util::file_exists(VALID_CACHE_PATH)) { + return cachedFetch(INSTALL_PATH); } else { - freshClone(); + return freshClone(); } } -void Installer::freshClone() { - qDebug() << "Doing fresh clone"; - proc.start("git", {"clone", "--progress", GIT_URL.c_str(), "-b", BRANCH_STR.c_str(), - "--depth=1", "--recurse-submodules", TMP_INSTALL_PATH}); +int freshClone() { + LOGD("Doing fresh clone"); + std::string cmd = util::string_format("git clone --progress %s -b %s --depth=1 --recurse-submodules %s 2>&1", + GIT_URL.c_str(), migrated_branch.c_str(), TMP_INSTALL_PATH); + return executeGitCommand(cmd); } -void Installer::cachedFetch(const QString &cache) { - qDebug() << "Fetching with cache: " << cache; +int cachedFetch(const std::string &cache) { + LOGD("Fetching with cache: %s", cache.c_str()); - run(QString("cp -rp %1 %2").arg(cache, TMP_INSTALL_PATH).toStdString().c_str()); - int err = chdir(TMP_INSTALL_PATH); - assert(err == 0); - run(("git remote set-branches --add origin " + BRANCH_STR).c_str()); + run(util::string_format("cp -rp %s %s", cache.c_str(), TMP_INSTALL_PATH).c_str()); + run(util::string_format("cd %s && git remote set-url origin %s", TMP_INSTALL_PATH, GIT_URL.c_str()).c_str()); + run(util::string_format("cd %s && git remote set-branches --add origin %s", TMP_INSTALL_PATH, migrated_branch.c_str()).c_str()); - updateProgress(10); + renderProgress(10); - proc.setWorkingDirectory(TMP_INSTALL_PATH); - proc.start("git", {"fetch", "--progress", "origin", BRANCH_STR.c_str()}); + return executeGitCommand(util::string_format("cd %s && git fetch --progress origin %s 2>&1", TMP_INSTALL_PATH, migrated_branch.c_str())); } -void Installer::readProgress() { - const QVector> stages = { +int executeGitCommand(const std::string &cmd) { + static const std::array stages = { // prefix, weight in percentage - {"Receiving objects: ", 91}, - {"Resolving deltas: ", 2}, - {"Updating files: ", 7}, + std::pair{"Receiving objects: ", 91}, + std::pair{"Resolving deltas: ", 2}, + std::pair{"Updating files: ", 7}, }; - auto line = QString(proc.readAllStandardError()); - - int base = 0; - for (const QPair kv : stages) { - if (line.startsWith(kv.first)) { - auto perc = line.split(kv.first)[1].split("%")[0]; - int p = base + int(perc.toFloat() / 100. * kv.second); - updateProgress(p); - break; + FILE *pipe = popen(cmd.c_str(), "r"); + if (!pipe) return -1; + + char buffer[512]; + while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { + std::string line(buffer); + int base = 0; + for (const auto &[text, weight] : stages) { + if (line.find(text) != std::string::npos) { + size_t percentPos = line.find("%"); + if (percentPos != std::string::npos && percentPos >= 3) { + int percent = std::stoi(line.substr(percentPos - 3, 3)); + int progress = base + int(percent / 100. * weight); + renderProgress(progress); + } + break; + } + base += weight; } - base += kv.second; } + return pclose(pipe); } -void Installer::cloneFinished(int exitCode, QProcess::ExitStatus exitStatus) { - qDebug() << "git finished with " << exitCode; +void cloneFinished(int exitCode) { + LOGD("git finished with %d", exitCode); assert(exitCode == 0); - updateProgress(100); + renderProgress(100); // ensure correct branch is checked out int err = chdir(TMP_INSTALL_PATH); assert(err == 0); - run(("git checkout " + BRANCH_STR).c_str()); - run(("git reset --hard origin/" + BRANCH_STR).c_str()); + run(("git checkout " + migrated_branch).c_str()); + run(("git reset --hard origin/" + migrated_branch).c_str()); run("git submodule update --init"); // move into place - run("mv " TMP_INSTALL_PATH " " INSTALL_PATH); + run(("rm -f " + VALID_CACHE_PATH).c_str()); + run(("rm -rf " + INSTALL_PATH).c_str()); + run(util::string_format("mv %s %s", TMP_INSTALL_PATH, INSTALL_PATH.c_str()).c_str()); #ifdef INTERNAL run("mkdir -p /data/params/d/"); @@ -193,9 +217,9 @@ void Installer::cloneFinished(int exitCode, QProcess::ExitStatus exitStatus) { param << value; param.close(); } - run("cd " INSTALL_PATH " && " + run(("cd " + INSTALL_PATH + " && " "git remote set-url origin --push " GIT_SSH_URL " && " - "git config --replace-all remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\""); + "git config --replace-all remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\"").c_str()); #endif // write continue.sh @@ -211,13 +235,36 @@ void Installer::cloneFinished(int exitCode, QProcess::ExitStatus exitStatus) { run("mv /data/continue.sh.new " CONTINUE_PATH); // wait for the installed software's UI to take over - QTimer::singleShot(60 * 1000, &QCoreApplication::quit); + finishInstall(); } int main(int argc, char *argv[]) { - initApp(argc, argv); - QApplication a(argc, argv); - Installer installer; - setMainWindow(&installer); - return a.exec(); + if (tici_device) { + InitWindow(2160, 1080, "Installer"); + } else { + InitWindow(536, 240, "Installer"); + } + + font_inter = LoadFontFromMemory(".ttf", inter_ttf, inter_ttf_end - inter_ttf, FONT_SIZE, NULL, 0); + font_roman = LoadFontFromMemory(".ttf", inter_light_ttf, inter_light_ttf_end - inter_light_ttf, FONT_SIZE, NULL, 0); + font_display = LoadFontFromMemory(".ttf", inter_bold_ttf, inter_bold_ttf_end - inter_bold_ttf, FONT_SIZE, NULL, 0); + SetTextureFilter(font_inter.texture, TEXTURE_FILTER_BILINEAR); + SetTextureFilter(font_roman.texture, TEXTURE_FILTER_BILINEAR); + SetTextureFilter(font_display.texture, TEXTURE_FILTER_BILINEAR); + + branchMigration(); + + if (util::file_exists(CONTINUE_PATH)) { + finishInstall(); + } else { + renderProgress(0); + int result = doInstall(); + cloneFinished(result); + } + + CloseWindow(); + UnloadFont(font_inter); + UnloadFont(font_roman); + UnloadFont(font_display); + return 0; } diff --git a/selfdrive/ui/installer/installer.h b/selfdrive/ui/installer/installer.h deleted file mode 100644 index de3af0ff395021..00000000000000 --- a/selfdrive/ui/installer/installer.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -class Installer : public QWidget { - Q_OBJECT - -public: - explicit Installer(QWidget *parent = 0); - -private slots: - void updateProgress(int percent); - - void readProgress(); - void cloneFinished(int exitCode, QProcess::ExitStatus exitStatus); - -private: - QLabel *val; - QProgressBar *bar; - QProcess proc; - - void doInstall(); - void freshClone(); - void cachedFetch(const QString &cache); -}; diff --git a/selfdrive/ui/installer/inter-ascii.ttf b/selfdrive/ui/installer/inter-ascii.ttf new file mode 100644 index 00000000000000..5d480c515a6ed1 --- /dev/null +++ b/selfdrive/ui/installer/inter-ascii.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ef26a4099ef867f3493389379d882381a2491cdbfa41a086be8899a2154dcb3 +size 26160 diff --git a/selfdrive/ui/layouts/__init__.py b/selfdrive/ui/layouts/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/selfdrive/ui/layouts/home.py b/selfdrive/ui/layouts/home.py new file mode 100644 index 00000000000000..183c2d45888fa0 --- /dev/null +++ b/selfdrive/ui/layouts/home.py @@ -0,0 +1,233 @@ +import time +import pyray as rl +from collections.abc import Callable +from enum import IntEnum +from openpilot.common.params import Params +from openpilot.selfdrive.ui.widgets.offroad_alerts import UpdateAlert, OffroadAlert +from openpilot.selfdrive.ui.widgets.exp_mode_button import ExperimentalModeButton +from openpilot.selfdrive.ui.widgets.prime import PrimeWidget +from openpilot.selfdrive.ui.widgets.setup import SetupWidget +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr, trn +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets import Widget + +HEADER_HEIGHT = 80 +HEAD_BUTTON_FONT_SIZE = 40 +CONTENT_MARGIN = 40 +SPACING = 25 +RIGHT_COLUMN_WIDTH = 750 +REFRESH_INTERVAL = 10.0 + + +class HomeLayoutState(IntEnum): + HOME = 0 + UPDATE = 1 + ALERTS = 2 + + +class HomeLayout(Widget): + def __init__(self): + super().__init__() + self.params = Params() + + self.update_alert = UpdateAlert() + self.offroad_alert = OffroadAlert() + + self._layout_widgets = {HomeLayoutState.UPDATE: self.update_alert, HomeLayoutState.ALERTS: self.offroad_alert} + + self.current_state = HomeLayoutState.HOME + self.last_refresh = 0 + self.settings_callback: Callable[[], None] | None = None + + self.update_available = False + self.alert_count = 0 + self._version_text = "" + self._prev_update_available = False + self._prev_alerts_present = False + + self.header_rect = rl.Rectangle(0, 0, 0, 0) + self.content_rect = rl.Rectangle(0, 0, 0, 0) + self.left_column_rect = rl.Rectangle(0, 0, 0, 0) + self.right_column_rect = rl.Rectangle(0, 0, 0, 0) + + self.update_notif_rect = rl.Rectangle(0, 0, 200, HEADER_HEIGHT - 10) + self.alert_notif_rect = rl.Rectangle(0, 0, 220, HEADER_HEIGHT - 10) + + self._prime_widget = PrimeWidget() + self._setup_widget = SetupWidget() + + self._exp_mode_button = ExperimentalModeButton() + self._setup_callbacks() + + def show_event(self): + super().show_event() + self._exp_mode_button.show_event() + self.last_refresh = time.monotonic() + self._refresh() + + def _setup_callbacks(self): + self.update_alert.set_dismiss_callback(lambda: self._set_state(HomeLayoutState.HOME)) + self.offroad_alert.set_dismiss_callback(lambda: self._set_state(HomeLayoutState.HOME)) + self._exp_mode_button.set_click_callback(lambda: self.settings_callback() if self.settings_callback else None) + + def set_settings_callback(self, callback: Callable): + self.settings_callback = callback + + def _set_state(self, state: HomeLayoutState): + # propagate show/hide events + if state != self.current_state: + if state == HomeLayoutState.HOME: + self._exp_mode_button.show_event() + + if state in self._layout_widgets: + self._layout_widgets[state].show_event() + if self.current_state in self._layout_widgets: + self._layout_widgets[self.current_state].hide_event() + + self.current_state = state + + def _render(self, rect: rl.Rectangle): + current_time = time.monotonic() + if current_time - self.last_refresh >= REFRESH_INTERVAL: + self._refresh() + self.last_refresh = current_time + + self._render_header() + + # Render content based on current state + if self.current_state == HomeLayoutState.HOME: + self._render_home_content() + elif self.current_state == HomeLayoutState.UPDATE: + self._render_update_view() + elif self.current_state == HomeLayoutState.ALERTS: + self._render_alerts_view() + + def _update_state(self): + self.header_rect = rl.Rectangle( + self._rect.x + CONTENT_MARGIN, self._rect.y + CONTENT_MARGIN, self._rect.width - 2 * CONTENT_MARGIN, HEADER_HEIGHT + ) + + content_y = self._rect.y + CONTENT_MARGIN + HEADER_HEIGHT + SPACING + content_height = self._rect.height - CONTENT_MARGIN - HEADER_HEIGHT - SPACING - CONTENT_MARGIN + + self.content_rect = rl.Rectangle( + self._rect.x + CONTENT_MARGIN, content_y, self._rect.width - 2 * CONTENT_MARGIN, content_height + ) + + left_width = self.content_rect.width - RIGHT_COLUMN_WIDTH - SPACING + + self.left_column_rect = rl.Rectangle(self.content_rect.x, self.content_rect.y, left_width, self.content_rect.height) + + self.right_column_rect = rl.Rectangle( + self.content_rect.x + left_width + SPACING, self.content_rect.y, RIGHT_COLUMN_WIDTH, self.content_rect.height + ) + + self.update_notif_rect.x = self.header_rect.x + self.update_notif_rect.y = self.header_rect.y + (self.header_rect.height - 60) // 2 + + notif_x = self.header_rect.x + (220 if self.update_available else 0) + self.alert_notif_rect.x = notif_x + self.alert_notif_rect.y = self.header_rect.y + (self.header_rect.height - 60) // 2 + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + if self.update_available and rl.check_collision_point_rec(mouse_pos, self.update_notif_rect): + self._set_state(HomeLayoutState.UPDATE) + elif self.alert_count > 0 and rl.check_collision_point_rec(mouse_pos, self.alert_notif_rect): + self._set_state(HomeLayoutState.ALERTS) + + def _render_header(self): + font = gui_app.font(FontWeight.MEDIUM) + + version_text_width = self.header_rect.width + + # Update notification button + if self.update_available: + version_text_width -= self.update_notif_rect.width + + # Highlight if currently viewing updates + highlight_color = rl.Color(75, 95, 255, 255) if self.current_state == HomeLayoutState.UPDATE else rl.Color(54, 77, 239, 255) + rl.draw_rectangle_rounded(self.update_notif_rect, 0.3, 10, highlight_color) + + text = tr("UPDATE") + text_size = measure_text_cached(font, text, HEAD_BUTTON_FONT_SIZE) + text_x = self.update_notif_rect.x + (self.update_notif_rect.width - text_size.x) // 2 + text_y = self.update_notif_rect.y + (self.update_notif_rect.height - text_size.y) // 2 + rl.draw_text_ex(font, text, rl.Vector2(int(text_x), int(text_y)), HEAD_BUTTON_FONT_SIZE, 0, rl.WHITE) + + # Alert notification button + if self.alert_count > 0: + version_text_width -= self.alert_notif_rect.width + + # Highlight if currently viewing alerts + highlight_color = rl.Color(255, 70, 70, 255) if self.current_state == HomeLayoutState.ALERTS else rl.Color(226, 44, 44, 255) + rl.draw_rectangle_rounded(self.alert_notif_rect, 0.3, 10, highlight_color) + + alert_text = trn("{} ALERT", "{} ALERTS", self.alert_count).format(self.alert_count) + text_size = measure_text_cached(font, alert_text, HEAD_BUTTON_FONT_SIZE) + text_x = self.alert_notif_rect.x + (self.alert_notif_rect.width - text_size.x) // 2 + text_y = self.alert_notif_rect.y + (self.alert_notif_rect.height - text_size.y) // 2 + rl.draw_text_ex(font, alert_text, rl.Vector2(int(text_x), int(text_y)), HEAD_BUTTON_FONT_SIZE, 0, rl.WHITE) + + # Version text (right aligned) + if self.update_available or self.alert_count > 0: + version_text_width -= SPACING * 1.5 + + version_rect = rl.Rectangle(self.header_rect.x + self.header_rect.width - version_text_width, self.header_rect.y, + version_text_width, self.header_rect.height) + gui_label(version_rect, self._version_text, 48, rl.WHITE, alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT) + + def _render_home_content(self): + self._render_left_column() + self._render_right_column() + + def _render_update_view(self): + self.update_alert.render(self.content_rect) + + def _render_alerts_view(self): + self.offroad_alert.render(self.content_rect) + + def _render_left_column(self): + self._prime_widget.render(self.left_column_rect) + + def _render_right_column(self): + exp_height = 125 + exp_rect = rl.Rectangle( + self.right_column_rect.x, self.right_column_rect.y, self.right_column_rect.width, exp_height + ) + self._exp_mode_button.render(exp_rect) + + setup_rect = rl.Rectangle( + self.right_column_rect.x, + self.right_column_rect.y + exp_height + SPACING, + self.right_column_rect.width, + self.right_column_rect.height - exp_height - SPACING, + ) + self._setup_widget.render(setup_rect) + + def _refresh(self): + self._version_text = self._get_version_text() + update_available = self.update_alert.refresh() + alert_count = self.offroad_alert.refresh() + alerts_present = alert_count > 0 + + # Show panels on transition from no alert/update to any alerts/update + if not update_available and not alerts_present: + self._set_state(HomeLayoutState.HOME) + elif update_available and ((not self._prev_update_available) or (not alerts_present and self.current_state == HomeLayoutState.ALERTS)): + self._set_state(HomeLayoutState.UPDATE) + elif alerts_present and ((not self._prev_alerts_present) or (not update_available and self.current_state == HomeLayoutState.UPDATE)): + self._set_state(HomeLayoutState.ALERTS) + + self.update_available = update_available + self.alert_count = alert_count + self._prev_update_available = update_available + self._prev_alerts_present = alerts_present + + def _get_version_text(self) -> str: + brand = "openpilot" + description = self.params.get("UpdaterCurrentDescription") + return f"{brand} {description}" if description else brand diff --git a/selfdrive/ui/layouts/main.py b/selfdrive/ui/layouts/main.py new file mode 100644 index 00000000000000..1a0fc9fe663bb6 --- /dev/null +++ b/selfdrive/ui/layouts/main.py @@ -0,0 +1,129 @@ +import pyray as rl +from enum import IntEnum +import cereal.messaging as messaging +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.layouts.sidebar import Sidebar, SIDEBAR_WIDTH +from openpilot.selfdrive.ui.layouts.home import HomeLayout +from openpilot.selfdrive.ui.layouts.settings.settings import SettingsLayout, PanelType +from openpilot.selfdrive.ui.onroad.augmented_road_view import AugmentedRoadView +from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.selfdrive.ui.layouts.onboarding import OnboardingWindow +from openpilot.selfdrive.ui.body.layouts.onroad import BodyLayout +from openpilot.selfdrive.ui.onroad.force_offroad_confirm import maybe_show_force_offroad_confirm + + +class MainState(IntEnum): + HOME = 0 + SETTINGS = 1 + ONROAD = 2 + + +class MainLayout(Widget): + def __init__(self): + super().__init__() + + self._pm = messaging.PubMaster(['bookmarkButton']) + + self._sidebar = Sidebar() + self._current_mode = MainState.HOME + self._prev_onroad = False + + # Initialize layouts + self._home_layout = HomeLayout() + self._home_body_layout = BodyLayout() + self._layouts = {MainState.HOME: self._home_layout, MainState.SETTINGS: SettingsLayout(), MainState.ONROAD: AugmentedRoadView()} + + self._sidebar_rect = rl.Rectangle(0, 0, 0, 0) + self._content_rect = rl.Rectangle(0, 0, 0, 0) + + # Set callbacks + self._setup_callbacks() + + gui_app.push_widget(self) + + # Start onboarding if terms or training not completed, make sure to push after self + self._onboarding_window = OnboardingWindow() + if not self._onboarding_window.completed: + gui_app.push_widget(self._onboarding_window) + + def _render(self, _): + self._handle_onroad_transition() + maybe_show_force_offroad_confirm() + self._render_main_content() + + def _setup_callbacks(self): + self._sidebar.set_callbacks(on_settings=self._on_settings_clicked, + on_flag=self._on_bookmark_clicked, + open_settings=lambda: self.open_settings(PanelType.TOGGLES)) + self._layouts[MainState.HOME]._setup_widget.set_open_settings_callback(lambda: self.open_settings(PanelType.FIREHOSE)) + self._layouts[MainState.HOME].set_settings_callback(lambda: self.open_settings(PanelType.TOGGLES)) + self._layouts[MainState.SETTINGS].set_callbacks(on_close=self._set_mode_for_state) + + for layout in (self._layouts[MainState.ONROAD], self._home_body_layout): + layout.set_click_callback(self._on_onroad_clicked) + + device.add_interactive_timeout_callback(self._set_mode_for_state) + ui_state.add_on_body_changed_callbacks(self._on_body_changed) + + def _update_layout_rects(self): + self._sidebar_rect = rl.Rectangle(self._rect.x, self._rect.y, SIDEBAR_WIDTH, self._rect.height) + + x_offset = SIDEBAR_WIDTH if self._sidebar.is_visible else 0 + self._content_rect = rl.Rectangle(self._rect.x + x_offset, self._rect.y, self._rect.width - x_offset, self._rect.height) + + def _handle_onroad_transition(self): + if ui_state.started != self._prev_onroad: + self._prev_onroad = ui_state.started + + self._set_mode_for_state() + + def _set_mode_for_state(self): + # Don't go onroad if body, home is onroad + if ui_state.is_body: + self._set_current_layout(MainState.HOME) + self._sidebar.set_visible(not ui_state.ignition) + return + + if ui_state.started: + # Don't hide sidebar from interactive timeout + if self._current_mode != MainState.ONROAD: + self._sidebar.set_visible(False) + self._set_current_layout(MainState.ONROAD) + else: + self._set_current_layout(MainState.HOME) + self._sidebar.set_visible(True) + + def _set_current_layout(self, layout: MainState): + if layout != self._current_mode: + self._layouts[self._current_mode].hide_event() + self._current_mode = layout + self._layouts[self._current_mode].show_event() + + def open_settings(self, panel_type: PanelType): + self._layouts[MainState.SETTINGS].set_current_panel(panel_type) + self._set_current_layout(MainState.SETTINGS) + self._sidebar.set_visible(False) + + def _on_settings_clicked(self): + self.open_settings(PanelType.DEVICE) + + def _on_bookmark_clicked(self): + user_bookmark = messaging.new_message('bookmarkButton') + user_bookmark.valid = True + self._pm.send('bookmarkButton', user_bookmark) + + def _on_onroad_clicked(self): + self._sidebar.set_visible(not self._sidebar.is_visible) + + def _on_body_changed(self): + self._layouts[MainState.HOME] = self._home_body_layout if ui_state.is_body else self._home_layout + self._set_mode_for_state() + + def _render_main_content(self): + # Render sidebar + if self._sidebar.is_visible: + self._sidebar.render(self._sidebar_rect) + + content_rect = self._content_rect if self._sidebar.is_visible else self._rect + self._layouts[self._current_mode].render(content_rect) diff --git a/selfdrive/ui/layouts/onboarding.py b/selfdrive/ui/layouts/onboarding.py new file mode 100644 index 00000000000000..c75abac1a211fc --- /dev/null +++ b/selfdrive/ui/layouts/onboarding.py @@ -0,0 +1,215 @@ +import os +import re +import threading +from enum import IntEnum + +import pyray as rl +from openpilot.common.basedir import BASEDIR +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import Label +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.version import terms_version, training_version + +DEBUG = False + +STEP_RECTS = [rl.Rectangle(104, 800, 633, 175), rl.Rectangle(1835, 0, 2159, 1080), rl.Rectangle(1835, 0, 2156, 1080), + rl.Rectangle(1526, 473, 427, 472), rl.Rectangle(1643, 441, 217, 223), rl.Rectangle(1835, 0, 2155, 1080), + rl.Rectangle(1786, 591, 267, 236), rl.Rectangle(1353, 0, 804, 1080), rl.Rectangle(1458, 485, 633, 211), + rl.Rectangle(95, 794, 1158, 187), rl.Rectangle(1560, 170, 392, 397), rl.Rectangle(1835, 0, 2159, 1080), + rl.Rectangle(1351, 0, 807, 1080), rl.Rectangle(1835, 0, 2158, 1080), rl.Rectangle(1531, 82, 441, 920), + rl.Rectangle(1336, 438, 490, 393), rl.Rectangle(1835, 0, 2159, 1080), rl.Rectangle(1835, 0, 2159, 1080), + rl.Rectangle(87, 795, 1187, 186)] + +DM_RECORD_STEP = 9 +DM_RECORD_YES_RECT = rl.Rectangle(695, 794, 558, 187) + +RESTART_TRAINING_RECT = rl.Rectangle(87, 795, 472, 186) + + +class OnboardingState(IntEnum): + TERMS = 0 + ONBOARDING = 1 + DECLINE = 2 + + +class TrainingGuide(Widget): + def __init__(self, completed_callback=None): + super().__init__() + self._completed_callback = completed_callback + + self._step = 0 + self._load_image_paths() + + # Load first image now so we show something immediately + self._textures = [gui_app.texture(self._image_paths[0])] + self._image_objs = [] + + threading.Thread(target=self._preload_thread, daemon=True).start() + + def _load_image_paths(self): + paths = [fn for fn in os.listdir(os.path.join(BASEDIR, "selfdrive/assets/training")) if re.match(r'^step\d*\.png$', fn)] + paths = sorted(paths, key=lambda x: int(re.search(r'\d+', x).group())) + self._image_paths = [os.path.join(BASEDIR, "selfdrive/assets/training", fn) for fn in paths] + + def _preload_thread(self): + # PNG loading is slow in raylib, so we preload in a thread and upload to GPU in main thread + # We've already loaded the first image on init + for path in self._image_paths[1:]: + self._image_objs.append(gui_app._load_image_from_path(path)) + + def _handle_mouse_release(self, mouse_pos): + if rl.check_collision_point_rec(mouse_pos, STEP_RECTS[self._step]): + # Record DM camera? + if self._step == DM_RECORD_STEP: + yes = rl.check_collision_point_rec(mouse_pos, DM_RECORD_YES_RECT) + print(f"putting RecordFront to {yes}") + ui_state.params.put_bool("RecordFront", yes, block=True) + + # Restart training? + elif self._step == len(self._image_paths) - 1: + if rl.check_collision_point_rec(mouse_pos, RESTART_TRAINING_RECT): + self._step = -1 + + self._step += 1 + + # Finished? + if self._step >= len(self._image_paths): + self._step = 0 + if self._completed_callback: + self._completed_callback() + + # NOTE: this pops OnboardingWindow during real onboarding + gui_app.pop_widget() + + def _update_state(self): + if len(self._image_objs): + self._textures.append(gui_app._load_texture_from_image(self._image_objs.pop(0))) + + def _render(self, _): + # Safeguard against fast tapping + step = min(self._step, len(self._textures) - 1) + rl.draw_texture_ex(self._textures[step], rl.Vector2(0, 0), 0.0, 1.0, rl.WHITE) + + # progress bar + if 0 < step < len(STEP_RECTS) - 1: + h = 20 + w = int((step / (len(STEP_RECTS) - 1)) * self._rect.width) + rl.draw_rectangle(int(self._rect.x), int(self._rect.y + self._rect.height - h), + w, h, rl.Color(70, 91, 234, 255)) + + if DEBUG: + rl.draw_rectangle_lines_ex(STEP_RECTS[step], 3, rl.RED) + + return -1 + + +class TermsPage(Widget): + def __init__(self, on_accept=None, on_decline=None): + super().__init__() + self._on_accept = on_accept + self._on_decline = on_decline + + self._title = Label(tr("Welcome to openpilot"), font_size=90, font_weight=FontWeight.BOLD, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT) + self._desc = Label(tr("You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing."), + font_size=90, font_weight=FontWeight.MEDIUM, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT) + + self._decline_btn = Button(tr("Decline"), click_callback=on_decline) + self._accept_btn = Button(tr("Agree"), button_style=ButtonStyle.PRIMARY, click_callback=on_accept) + + def _render(self, _): + welcome_x = self._rect.x + 165 + welcome_y = self._rect.y + 165 + welcome_rect = rl.Rectangle(welcome_x, welcome_y, self._rect.width - welcome_x, 90) + self._title.render(welcome_rect) + + desc_x = welcome_x + # TODO: Label doesn't top align when wrapping + desc_y = welcome_y - 100 + desc_rect = rl.Rectangle(desc_x, desc_y, self._rect.width - desc_x, self._rect.height - desc_y - 250) + self._desc.render(desc_rect) + + btn_y = self._rect.y + self._rect.height - 160 - 45 + btn_width = (self._rect.width - 45 * 3) / 2 + self._decline_btn.render(rl.Rectangle(self._rect.x + 45, btn_y, btn_width, 160)) + self._accept_btn.render(rl.Rectangle(self._rect.x + 45 * 2 + btn_width, btn_y, btn_width, 160)) + + if DEBUG: + rl.draw_rectangle_lines_ex(welcome_rect, 3, rl.RED) + rl.draw_rectangle_lines_ex(desc_rect, 3, rl.RED) + + return -1 + + +class DeclinePage(Widget): + def __init__(self, back_callback=None): + super().__init__() + self._text = Label(tr("You must accept the Terms and Conditions in order to use openpilot."), + font_size=90, font_weight=FontWeight.MEDIUM, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT) + self._back_btn = Button(tr("Back"), click_callback=back_callback) + self._uninstall_btn = Button(tr("Decline, uninstall openpilot"), button_style=ButtonStyle.DANGER, + click_callback=self._on_uninstall_clicked) + + def _on_uninstall_clicked(self): + ui_state.params.put_bool("DoUninstall", True, block=True) + gui_app.request_close() + + def _render(self, _): + btn_y = self._rect.y + self._rect.height - 160 - 45 + btn_width = (self._rect.width - 45 * 3) / 2 + self._back_btn.render(rl.Rectangle(self._rect.x + 45, btn_y, btn_width, 160)) + self._uninstall_btn.render(rl.Rectangle(self._rect.x + 45 * 2 + btn_width, btn_y, btn_width, 160)) + + # text rect in middle of top and button + text_height = btn_y - (200 + 45) + text_rect = rl.Rectangle(self._rect.x + 165, self._rect.y + (btn_y - text_height) / 2 + 10, self._rect.width - (165 * 2), text_height) + if DEBUG: + rl.draw_rectangle_lines_ex(text_rect, 3, rl.RED) + self._text.render(text_rect) + + +class OnboardingWindow(Widget): + def __init__(self): + super().__init__() + self._accepted_terms: bool = ui_state.params.get("HasAcceptedTerms") == terms_version + self._training_done: bool = ui_state.params.get("CompletedTrainingVersion") == training_version + + self._state = OnboardingState.TERMS if not self._accepted_terms else OnboardingState.ONBOARDING + + # Windows + self._terms = TermsPage(on_accept=self._on_terms_accepted, on_decline=self._on_terms_declined) + self._training_guide: TrainingGuide | None = None + self._decline_page = DeclinePage(back_callback=self._on_decline_back) + + @property + def completed(self) -> bool: + return self._accepted_terms and self._training_done + + def _on_terms_declined(self): + self._state = OnboardingState.DECLINE + + def _on_decline_back(self): + self._state = OnboardingState.TERMS + + def _on_terms_accepted(self): + ui_state.params.put("HasAcceptedTerms", terms_version, block=True) + self._state = OnboardingState.ONBOARDING + if self._training_done: + gui_app.pop_widget() + + def _on_completed_training(self): + ui_state.params.put("CompletedTrainingVersion", training_version, block=True) + + def _render(self, _): + if self._training_guide is None: + self._training_guide = TrainingGuide(completed_callback=self._on_completed_training) + + if self._state == OnboardingState.TERMS: + self._terms.render(self._rect) + if self._state == OnboardingState.ONBOARDING: + self._training_guide.render(self._rect) + elif self._state == OnboardingState.DECLINE: + self._decline_page.render(self._rect) + return -1 diff --git a/selfdrive/ui/layouts/settings/common.py b/selfdrive/ui/layouts/settings/common.py new file mode 100644 index 00000000000000..bba8606e6442cc --- /dev/null +++ b/selfdrive/ui/layouts/settings/common.py @@ -0,0 +1,5 @@ +from openpilot.selfdrive.ui.ui_state import ui_state + + +def restart_needed_callback(_=None): + ui_state.params.put_bool("OnroadCycleRequested", True) diff --git a/selfdrive/ui/layouts/settings/developer.py b/selfdrive/ui/layouts/settings/developer.py new file mode 100644 index 00000000000000..64179093223155 --- /dev/null +++ b/selfdrive/ui/layouts/settings/developer.py @@ -0,0 +1,205 @@ +from openpilot.common.params import Params +from openpilot.selfdrive.ui.widgets.ssh_key import ssh_key_item +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.list_view import toggle_item +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.widgets import DialogResult + +# Description constants +DESCRIPTIONS = { + 'enable_adb': tr_noop( + "ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. " + + "See https://docs.comma.ai/how-to/connect-to-comma for more info." + ), + 'ssh_key': tr_noop( + "Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username " + + "other than your own. A comma employee will NEVER ask you to add their GitHub username." + ), + 'alpha_longitudinal': tr_noop( + "WARNING: openpilot longitudinal control is in alpha for this car and may disable Automatic Emergency Braking (AEB).

" + + "On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. " + + "Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. " + + "Changing this setting will restart openpilot if the car is powered on." + ), +} + + +class DeveloperLayout(Widget): + def __init__(self): + super().__init__() + self._params = Params() + self._is_release = self._params.get_bool("IsReleaseBranch") + + # Build items and keep references for callbacks/state updates + self._adb_toggle = toggle_item( + lambda: tr("Enable ADB"), + description=lambda: tr(DESCRIPTIONS["enable_adb"]), + initial_state=self._params.get_bool("AdbEnabled"), + callback=self._on_enable_adb, + enabled=ui_state.is_offroad, + ) + + # SSH enable toggle + SSH key management + self._ssh_toggle = toggle_item( + lambda: tr("Enable SSH"), + description="", + initial_state=self._params.get_bool("SshEnabled"), + callback=self._on_enable_ssh, + ) + self._ssh_keys = ssh_key_item(lambda: tr("SSH Keys"), description=lambda: tr(DESCRIPTIONS["ssh_key"])) + + self._joystick_toggle = toggle_item( + lambda: tr("Joystick Debug Mode"), + description="", + initial_state=self._params.get_bool("JoystickDebugMode"), + callback=self._on_joystick_debug_mode, + enabled=ui_state.is_offroad, + ) + + self._long_maneuver_toggle = toggle_item( + lambda: tr("Longitudinal Maneuver Mode"), + description="", + initial_state=self._params.get_bool("LongitudinalManeuverMode"), + callback=self._on_long_maneuver_mode, + ) + + self._lat_maneuver_toggle = toggle_item( + lambda: tr("Lateral Maneuver Mode"), + description="", + initial_state=self._params.get_bool("LateralManeuverMode"), + callback=self._on_lat_maneuver_mode, + ) + + self._alpha_long_toggle = toggle_item( + lambda: tr("openpilot Longitudinal Control (Alpha)"), + description=lambda: tr(DESCRIPTIONS["alpha_longitudinal"]), + initial_state=self._params.get_bool("AlphaLongitudinalEnabled"), + callback=self._on_alpha_long_enabled, + enabled=lambda: not ui_state.engaged, + ) + + self._ui_debug_toggle = toggle_item( + lambda: tr("UI Debug Mode"), + description="", + initial_state=self._params.get_bool("ShowDebugInfo"), + callback=self._on_enable_ui_debug, + ) + self._on_enable_ui_debug(self._params.get_bool("ShowDebugInfo")) + + self._scroller = Scroller([ + self._adb_toggle, + self._ssh_toggle, + self._ssh_keys, + self._joystick_toggle, + self._long_maneuver_toggle, + self._lat_maneuver_toggle, + self._alpha_long_toggle, + self._ui_debug_toggle, + ], line_separator=True, spacing=0) + + # Toggles should be not available to change in onroad state + ui_state.add_offroad_transition_callback(self._update_toggles) + + def _render(self, rect): + self._scroller.render(rect) + + def show_event(self): + super().show_event() + self._scroller.show_event() + self._update_toggles() + + def _update_toggles(self): + ui_state.update_params() + + # Hide non-release toggles on release builds + # TODO: we can do an onroad cycle, but alpha long toggle requires a deinit function to re-enable radar and not fault + for item in (self._joystick_toggle, self._long_maneuver_toggle, self._lat_maneuver_toggle, self._alpha_long_toggle): + item.set_visible(not self._is_release) + + # CP gating + if ui_state.CP is not None: + alpha_avail = ui_state.CP.alphaLongitudinalAvailable + if not alpha_avail or self._is_release: + self._alpha_long_toggle.set_visible(False) + self._params.remove("AlphaLongitudinalEnabled") + else: + self._alpha_long_toggle.set_visible(True) + + long_man_enabled = ui_state.has_longitudinal_control and ui_state.is_offroad() + self._long_maneuver_toggle.action_item.set_enabled(long_man_enabled) + else: + self._long_maneuver_toggle.action_item.set_enabled(False) + self._lat_maneuver_toggle.action_item.set_enabled(False) + self._alpha_long_toggle.set_visible(False) + + # TODO: make a param control list item so we don't need to manage internal state as much here + # refresh toggles from params to mirror external changes + for key, item in ( + ("AdbEnabled", self._adb_toggle), + ("SshEnabled", self._ssh_toggle), + ("JoystickDebugMode", self._joystick_toggle), + ("LongitudinalManeuverMode", self._long_maneuver_toggle), + ("LateralManeuverMode", self._lat_maneuver_toggle), + ("AlphaLongitudinalEnabled", self._alpha_long_toggle), + ("ShowDebugInfo", self._ui_debug_toggle), + ): + item.action_item.set_state(self._params.get_bool(key)) + + def _on_enable_ui_debug(self, state: bool): + self._params.put_bool("ShowDebugInfo", state, block=True) + gui_app.set_show_touches(state) + gui_app.set_show_fps(state) + + def _on_enable_adb(self, state: bool): + self._params.put_bool("AdbEnabled", state, block=True) + + def _on_enable_ssh(self, state: bool): + self._params.put_bool("SshEnabled", state, block=True) + + def _on_joystick_debug_mode(self, state: bool): + self._params.put_bool("JoystickDebugMode", state, block=True) + self._params.put_bool("LongitudinalManeuverMode", False, block=True) + self._long_maneuver_toggle.action_item.set_state(False) + self._params.put_bool("LateralManeuverMode", False, block=True) + self._lat_maneuver_toggle.action_item.set_state(False) + + def _on_long_maneuver_mode(self, state: bool): + self._params.put_bool("LongitudinalManeuverMode", state, block=True) + self._params.put_bool("JoystickDebugMode", False, block=True) + self._joystick_toggle.action_item.set_state(False) + self._params.put_bool("LateralManeuverMode", False, block=True) + self._lat_maneuver_toggle.action_item.set_state(False) + + def _on_lat_maneuver_mode(self, state: bool): + self._params.put_bool("LateralManeuverMode", state, block=True) + self._params.put_bool("ExperimentalMode", False, block=True) + self._params.put_bool("JoystickDebugMode", False, block=True) + self._joystick_toggle.action_item.set_state(False) + self._params.put_bool("LongitudinalManeuverMode", False, block=True) + self._long_maneuver_toggle.action_item.set_state(False) + + def _on_alpha_long_enabled(self, state: bool): + if state: + def confirm_callback(result: DialogResult): + if result == DialogResult.CONFIRM: + self._params.put_bool("AlphaLongitudinalEnabled", True, block=True) + self._params.put_bool("OnroadCycleRequested", True, block=True) + self._update_toggles() + else: + self._alpha_long_toggle.action_item.set_state(False) + + # show confirmation dialog + content = (f"

{self._alpha_long_toggle.title}


" + + f"

{self._alpha_long_toggle.description}

") + + dlg = ConfirmDialog(content, tr("Enable"), rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + else: + self._params.put_bool("AlphaLongitudinalEnabled", False, block=True) + self._params.put_bool("OnroadCycleRequested", True, block=True) + self._update_toggles() diff --git a/selfdrive/ui/layouts/settings/device.py b/selfdrive/ui/layouts/settings/device.py new file mode 100644 index 00000000000000..845fca3e838078 --- /dev/null +++ b/selfdrive/ui/layouts/settings/device.py @@ -0,0 +1,194 @@ +import os +import math + +from cereal import messaging, log +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.onroad.driver_camera_dialog import DriverCameraDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.layouts.onboarding import TrainingGuide +from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import multilang, tr, tr_noop +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog, alert_dialog +from openpilot.system.ui.widgets.html_render import HtmlModal +from openpilot.system.ui.widgets.list_view import text_item, button_item, dual_button_item +from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog +from openpilot.system.ui.widgets.scroller_tici import Scroller + +# Description constants +DESCRIPTIONS = { + 'pair_device': tr_noop("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer."), + 'driver_camera': tr_noop("Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)"), + 'reset_calibration': tr_noop("openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down."), + 'review_guide': tr_noop("Review the rules, features, and limitations of openpilot"), +} + + +class DeviceLayout(Widget): + def __init__(self): + super().__init__() + + self._params = Params() + self._select_language_dialog: MultiOptionDialog | None = None + self._fcc_dialog: HtmlModal | None = None + self._training_guide: TrainingGuide | None = None + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=True, spacing=0) + + ui_state.add_offroad_transition_callback(self._offroad_transition) + + def _initialize_items(self): + self._pair_device_btn = button_item(lambda: tr("Pair Device"), lambda: tr("PAIR"), lambda: tr(DESCRIPTIONS['pair_device']), + callback=lambda: gui_app.push_widget(PairingDialog())) + self._pair_device_btn.set_visible(lambda: not ui_state.prime_state.is_paired()) + + self._reset_calib_btn = button_item(lambda: tr("Reset Calibration"), lambda: tr("RESET"), lambda: tr(DESCRIPTIONS['reset_calibration']), + callback=self._reset_calibration_prompt) + self._reset_calib_btn.set_description_opened_callback(self._update_calib_description) + + self._power_off_btn = dual_button_item(lambda: tr("Reboot"), lambda: tr("Power Off"), + left_callback=self._reboot_prompt, right_callback=self._power_off_prompt) + + items = [ + text_item(lambda: tr("Dongle ID"), self._params.get("DongleId") or (lambda: tr("N/A"))), + text_item(lambda: tr("Serial"), self._params.get("HardwareSerial") or (lambda: tr("N/A"))), + self._pair_device_btn, + button_item(lambda: tr("Driver Camera"), lambda: tr("PREVIEW"), lambda: tr(DESCRIPTIONS['driver_camera']), + callback=lambda: gui_app.push_widget(DriverCameraDialog()), enabled=ui_state.is_offroad), + self._reset_calib_btn, + button_item(lambda: tr("Review Training Guide"), lambda: tr("REVIEW"), lambda: tr(DESCRIPTIONS['review_guide']), + self._on_review_training_guide, enabled=ui_state.is_offroad), + button_item(lambda: tr("Regulatory"), lambda: tr("VIEW"), callback=self._on_regulatory, enabled=ui_state.is_offroad), + button_item(lambda: tr("Change Language"), lambda: tr("CHANGE"), callback=self._show_language_dialog), + self._power_off_btn, + ] + return items + + def _offroad_transition(self): + self._power_off_btn.action_item.right_button.set_visible(ui_state.is_offroad()) + + def show_event(self): + super().show_event() + self._scroller.show_event() + + def _render(self, rect): + self._scroller.render(rect) + + def _show_language_dialog(self): + def handle_language_selection(result: DialogResult): + if result == DialogResult.CONFIRM and self._select_language_dialog: + selected_language = multilang.languages[self._select_language_dialog.selection] + multilang.change_language(selected_language) + self._update_calib_description() + self._select_language_dialog = None + + self._select_language_dialog = MultiOptionDialog(tr("Select a language"), multilang.languages, multilang.codes[multilang.language], + option_font_weight=FontWeight.UNIFONT, callback=handle_language_selection) + gui_app.push_widget(self._select_language_dialog) + + def _reset_calibration_prompt(self): + if ui_state.engaged: + gui_app.push_widget(alert_dialog(tr("Disengage to Reset Calibration"))) + return + + def reset_calibration(result: DialogResult): + # Check engaged again in case it changed while the dialog was open + if ui_state.engaged or result != DialogResult.CONFIRM: + return + + self._params.remove("CalibrationParams") + self._params.remove("LiveTorqueParameters") + self._params.remove("LiveParameters") + self._params.remove("LiveParametersV2") + self._params.remove("LiveDelay") + self._params.put_bool("OnroadCycleRequested", True, block=True) + self._update_calib_description() + + dialog = ConfirmDialog(tr("Are you sure you want to reset calibration?"), tr("Reset"), callback=reset_calibration) + gui_app.push_widget(dialog) + + def _update_calib_description(self): + desc = tr(DESCRIPTIONS['reset_calibration']) + + calib_bytes = self._params.get("CalibrationParams") + if calib_bytes: + try: + calib = messaging.log_from_bytes(calib_bytes, log.Event).liveCalibration + + if calib.calStatus != log.LiveCalibrationData.Status.uncalibrated: + pitch = math.degrees(calib.rpyCalib[1]) + yaw = math.degrees(calib.rpyCalib[2]) + desc += tr(" Your device is pointed {:.1f}° {} and {:.1f}° {}.").format(abs(pitch), tr("down") if pitch > 0 else tr("up"), + abs(yaw), tr("left") if yaw > 0 else tr("right")) + except Exception: + cloudlog.exception("invalid CalibrationParams") + + lag_perc = 0 + lag_bytes = self._params.get("LiveDelay") + if lag_bytes: + try: + lag_perc = messaging.log_from_bytes(lag_bytes, log.Event).liveDelay.calPerc + except Exception: + cloudlog.exception("invalid LiveDelay") + if lag_perc < 100: + desc += tr("

Steering lag calibration is {}% complete.").format(lag_perc) + else: + desc += tr("

Steering lag calibration is complete.") + + torque_bytes = self._params.get("LiveTorqueParameters") + if torque_bytes: + try: + torque = messaging.log_from_bytes(torque_bytes, log.Event).liveTorqueParameters + # don't add for non-torque cars + if torque.useParams: + torque_perc = torque.calPerc + if torque_perc < 100: + desc += tr(" Steering torque response calibration is {}% complete.").format(torque_perc) + else: + desc += tr(" Steering torque response calibration is complete.") + except Exception: + cloudlog.exception("invalid LiveTorqueParameters") + + desc += "

" + desc += tr("openpilot is continuously calibrating, resetting is rarely required. " + + "Resetting calibration will restart openpilot if the car is powered on.") + + self._reset_calib_btn.set_description(desc) + + def _reboot_prompt(self): + if ui_state.engaged: + gui_app.push_widget(alert_dialog(tr("Disengage to Reboot"))) + return + + def perform_reboot(result: DialogResult): + if not ui_state.engaged and result == DialogResult.CONFIRM: + self._params.put_bool("DoReboot", True) + + dialog = ConfirmDialog(tr("Are you sure you want to reboot?"), tr("Reboot"), callback=perform_reboot) + gui_app.push_widget(dialog) + + def _power_off_prompt(self): + if ui_state.engaged: + gui_app.push_widget(alert_dialog(tr("Disengage to Power Off"))) + return + + def perform_power_off(result: DialogResult): + if not ui_state.engaged and result == DialogResult.CONFIRM: + self._params.put_bool("DoShutdown", True) + + dialog = ConfirmDialog(tr("Are you sure you want to power off?"), tr("Power Off"), callback=perform_power_off) + gui_app.push_widget(dialog) + + def _on_regulatory(self): + if not self._fcc_dialog: + self._fcc_dialog = HtmlModal(os.path.join(BASEDIR, "selfdrive/assets/offroad/fcc.html")) + gui_app.push_widget(self._fcc_dialog) + + def _on_review_training_guide(self): + if not self._training_guide: + self._training_guide = TrainingGuide() + gui_app.push_widget(self._training_guide) diff --git a/selfdrive/ui/layouts/settings/driving_mannerisms.py b/selfdrive/ui/layouts/settings/driving_mannerisms.py new file mode 100644 index 00000000000000..781d690a21ec15 --- /dev/null +++ b/selfdrive/ui/layouts/settings/driving_mannerisms.py @@ -0,0 +1,307 @@ +"""TICI NAP submenu: Driving Mannerisms controls.""" +from openpilot.common.params import Params +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.list_view import toggle_item, multiple_button_item, button_item +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.selfdrive.controls.lib.hypermile import apply_hypermile_toggle +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + ADAPTIVE_ACCEL_DESCRIPTION, + CONE_LINE_HOLD_DESCRIPTION, + OBSTACLE_CHIME_DESCRIPTION, + DRIVER_LAT_HANDOFF_DESCRIPTION, + LOW_VIS_BACKOFF_DESCRIPTION, + FOLLOW_DISTANCE_CITY_DESCRIPTION, + FOLLOW_DISTANCE_HWY_DESCRIPTION, + HYPERMILE_DESCRIPTION, + HYPERMILE_HILL_CLIMB_DESCRIPTION, + HYPERMILE_STEP_DOWN_DESCRIPTION, + MAP_SPEED_ACCEL, MAP_SPEED_ACCEL_DEFAULT, MAP_SPEED_ACCEL_DESCRIPTION, + MAP_SPEED_ACCEL_LABELS, + NAP_CONE_LINE_HOLD, + NAP_OBSTACLE_CHIME, + NAP_DRIVER_LAT_HANDOFF, + NAP_LOW_VIS_BACKOFF, + NAP_HYPERMILE, + NAP_HYPERMILE_HILL_CLIMB, + NAP_HYPERMILE_STEP_DOWN, + NAP_GAP_LOCK, + NAP_ONE_PEDAL_LONG, + GAP_LOCK_DESCRIPTION, + ONE_PEDAL_LONG_DESCRIPTION, +) +from openpilot.selfdrive.ui.layouts.settings.nap_lateral import ( + LAT_REF_OFFSET_DESCRIPTION, LAT_REF_OFFSET_LABELS, LAT_REF_OFFSET_PRESETS, + LAT_TURN_GEOM_DESCRIPTION, NAP_LAT_REF_OFFSET, NAP_LAT_TURN_GEOM, lat_ref_offset_index, + NAP_TURN_IN_DELAY, TURN_IN_DELAY_DESCRIPTION, TURN_IN_DELAY_LABELS, TURN_IN_DELAY_STEPS, turn_in_delay_index, + NAP_ROUNDABOUT_ASSIST, ROUNDABOUT_ASSIST_DESCRIPTION, +) +from opendbc.car.tesla.preap.nap_params import NAPParamKeys + + +class DrivingMannerismsLayout(Widget): + """Nested NAP page for Hypermile, accel feel, follow distance, soft-lat, turn geometry, roundabout assist.""" + + def __init__(self, on_back): + super().__init__() + self._params = Params() + self._on_back = on_back + self._build_items() + self._scroller = Scroller(self._all_items, line_separator=True, spacing=0) + + def _build_items(self): + self._all_items = [] + self._all_items.append(button_item( + "Back To", + "NAP", + description="Return to NAP settings.", + callback=self._on_back, + )) + + accel = int(self._params.get("NAPMapSpeedAccel", return_default=True) or MAP_SPEED_ACCEL_DEFAULT) + self._accel_buttons = multiple_button_item( + "Acceleration", + MAP_SPEED_ACCEL_DESCRIPTION, + buttons=MAP_SPEED_ACCEL_LABELS, + button_width=72, + selected_index=self._accel_index(accel), + callback=self._on_accel, + ) + self._all_items.append(self._accel_buttons) + + self._adaptive_accel = toggle_item( + "Adaptive Accel", + description=ADAPTIVE_ACCEL_DESCRIPTION, + initial_state=self._params.get_bool(NAPParamKeys.ADAPTIVE_ACCEL), + callback=self._on_adaptive_accel, + ) + self._all_items.append(self._adaptive_accel) + + from openpilot.selfdrive.controls.lib.follow_distance import migrate_follow_distance_params + migrate_follow_distance_params(self._params) + city = self._params.get(NAPParamKeys.FOLLOW_DISTANCE_CITY, return_default=True) + hwy = self._params.get(NAPParamKeys.FOLLOW_DISTANCE_HWY, return_default=True) + self._follow_city_buttons = multiple_button_item( + "City Follow Distance", + FOLLOW_DISTANCE_CITY_DESCRIPTION, + buttons=["1", "2", "3", "4", "5", "6", "7"], + button_width=80, + selected_index=max(0, min(6, city - 1)), + callback=self._on_follow_distance_city, + ) + self._all_items.append(self._follow_city_buttons) + + self._follow_hwy_buttons = multiple_button_item( + "Highway Follow Distance", + FOLLOW_DISTANCE_HWY_DESCRIPTION, + buttons=["1", "2", "3", "4", "5", "6", "7"], + button_width=80, + selected_index=max(0, min(6, hwy - 1)), + callback=self._on_follow_distance_hwy, + ) + self._all_items.append(self._follow_hwy_buttons) + + self._lat_handoff = toggle_item( + "Soft Lateral Handoff", + description=DRIVER_LAT_HANDOFF_DESCRIPTION, + initial_state=self._params.get_bool(NAP_DRIVER_LAT_HANDOFF), + callback=self._on_lat_handoff, + ) + self._all_items.append(self._lat_handoff) + + self._low_vis = toggle_item( + "Low Visibility Back-off", + description=LOW_VIS_BACKOFF_DESCRIPTION, + initial_state=self._params.get_bool(NAP_LOW_VIS_BACKOFF), + callback=self._on_low_vis, + ) + self._all_items.append(self._low_vis) + + self._cone_hold = toggle_item( + "Hold my line near cones", + description=CONE_LINE_HOLD_DESCRIPTION, + initial_state=self._params.get_bool(NAP_CONE_LINE_HOLD), + callback=self._on_cone_hold, + ) + self._all_items.append(self._cone_hold) + + self._obstacle_chime = toggle_item( + "Live object detection chime", + description=OBSTACLE_CHIME_DESCRIPTION, + initial_state=self._params.get_bool(NAP_OBSTACLE_CHIME), + callback=self._on_obstacle_chime, + ) + self._all_items.append(self._obstacle_chime) + + self._turn_geom = toggle_item( + "Turn Geometry Correction", + description=LAT_TURN_GEOM_DESCRIPTION, + initial_state=self._params.get_bool(NAP_LAT_TURN_GEOM), + callback=self._on_turn_geom, + ) + self._all_items.append(self._turn_geom) + + self._ref_offset_buttons = multiple_button_item( + "Rear Reference Offset (m)", + LAT_REF_OFFSET_DESCRIPTION, + buttons=LAT_REF_OFFSET_LABELS, + button_width=110, + selected_index=lat_ref_offset_index(self._params), + callback=self._on_ref_offset, + ) + self._all_items.append(self._ref_offset_buttons) + + self._turn_in_buttons = multiple_button_item( + "Turn-In Timing (low speed)", + TURN_IN_DELAY_DESCRIPTION, + buttons=TURN_IN_DELAY_LABELS, + button_width=72, + selected_index=turn_in_delay_index(self._params), + callback=self._on_turn_in_delay, + ) + self._all_items.append(self._turn_in_buttons) + + self._rb_assist = toggle_item( + "Roundabout Steering Assist", + description=ROUNDABOUT_ASSIST_DESCRIPTION, + initial_state=self._params.get_bool(NAP_ROUNDABOUT_ASSIST), + callback=self._on_rb_assist, + ) + self._all_items.append(self._rb_assist) + + self._one_pedal = toggle_item( + "One-Pedal Long", + description=ONE_PEDAL_LONG_DESCRIPTION, + initial_state=self._params.get_bool(NAP_ONE_PEDAL_LONG), + callback=self._on_one_pedal, + ) + self._all_items.append(self._one_pedal) + + self._gap_lock = toggle_item( + "Gap lock", + description=GAP_LOCK_DESCRIPTION, + initial_state=self._gap_lock_on(), + callback=self._on_gap_lock, + ) + self._all_items.append(self._gap_lock) + + self._hypermile = toggle_item( + "Hypermile", + description=HYPERMILE_DESCRIPTION, + initial_state=self._params.get_bool(NAP_HYPERMILE), + callback=self._on_hypermile, + ) + self._all_items.append(self._hypermile) + + self._step_down = toggle_item( + "Step Down Speed", + description=HYPERMILE_STEP_DOWN_DESCRIPTION, + initial_state=self._params.get_bool(NAP_HYPERMILE_STEP_DOWN), + callback=self._on_step_down, + ) + self._all_items.append(self._step_down) + + self._hill_climb = toggle_item( + "Hill Climb", + description=HYPERMILE_HILL_CLIMB_DESCRIPTION, + initial_state=self._params.get_bool(NAP_HYPERMILE_HILL_CLIMB), + callback=self._on_hill_climb, + ) + self._all_items.append(self._hill_climb) + + def _on_hypermile(self, state): + apply_hypermile_toggle(self._params, bool(state)) + self.refresh() + + def _on_step_down(self, state): + self._params.put_bool(NAP_HYPERMILE_STEP_DOWN, state) + + def _on_hill_climb(self, state): + self._params.put_bool(NAP_HYPERMILE_HILL_CLIMB, state) + + def _on_adaptive_accel(self, state): + self._params.put_bool(NAPParamKeys.ADAPTIVE_ACCEL, state) + + def _accel_index(self, value: int) -> int: + if value in MAP_SPEED_ACCEL: + return MAP_SPEED_ACCEL.index(value) + return MAP_SPEED_ACCEL.index(MAP_SPEED_ACCEL_DEFAULT) + + def _on_accel(self, index: int): + self._params.put("NAPMapSpeedAccel", MAP_SPEED_ACCEL[index]) + + def _on_follow_distance_city(self, index: int): + self._params.put(NAPParamKeys.FOLLOW_DISTANCE_CITY, index + 1) + + def _on_follow_distance_hwy(self, index: int): + self._params.put(NAPParamKeys.FOLLOW_DISTANCE_HWY, index + 1) + + def _on_lat_handoff(self, state): + self._params.put_bool(NAP_DRIVER_LAT_HANDOFF, state) + + def _on_low_vis(self, state): + self._params.put_bool(NAP_LOW_VIS_BACKOFF, state) + + def _on_cone_hold(self, state): + self._params.put_bool(NAP_CONE_LINE_HOLD, state) + + def _on_obstacle_chime(self, state): + self._params.put_bool(NAP_OBSTACLE_CHIME, state) + + def _on_turn_geom(self, state): + self._params.put_bool(NAP_LAT_TURN_GEOM, state) + + def _on_rb_assist(self, state): + self._params.put_bool(NAP_ROUNDABOUT_ASSIST, state) + + def _on_ref_offset(self, index: int): + self._params.put(NAP_LAT_REF_OFFSET, float(LAT_REF_OFFSET_PRESETS[index])) + + def _on_turn_in_delay(self, index: int): + self._params.put(NAP_TURN_IN_DELAY, int(TURN_IN_DELAY_STEPS[index])) + + def _gap_lock_on(self) -> bool: + try: + return self._params.get_bool(NAP_GAP_LOCK) is True + except Exception: + return False + + def _on_gap_lock(self, state): + try: + self._params.put_bool(NAP_GAP_LOCK, state) + except Exception: + pass + + def _on_one_pedal(self, state): + self._params.put_bool(NAP_ONE_PEDAL_LONG, state) + + def refresh(self): + hypermile_on = self._params.get_bool(NAP_HYPERMILE) + self._hypermile.action_item.set_state(hypermile_on) + self._step_down.action_item.set_state(self._params.get_bool(NAP_HYPERMILE_STEP_DOWN)) + self._step_down.set_visible(hypermile_on) + self._hill_climb.action_item.set_state(self._params.get_bool(NAP_HYPERMILE_HILL_CLIMB)) + self._hill_climb.set_visible(hypermile_on) + self._adaptive_accel.action_item.set_state(self._params.get_bool(NAPParamKeys.ADAPTIVE_ACCEL)) + accel = int(self._params.get("NAPMapSpeedAccel", return_default=True) or MAP_SPEED_ACCEL_DEFAULT) + self._accel_buttons.action_item.set_selected_button(self._accel_index(accel)) + city = self._params.get(NAPParamKeys.FOLLOW_DISTANCE_CITY, return_default=True) + hwy = self._params.get(NAPParamKeys.FOLLOW_DISTANCE_HWY, return_default=True) + self._follow_city_buttons.action_item.set_selected_button(max(0, min(6, city - 1))) + self._follow_hwy_buttons.action_item.set_selected_button(max(0, min(6, hwy - 1))) + self._lat_handoff.action_item.set_state(self._params.get_bool(NAP_DRIVER_LAT_HANDOFF)) + self._low_vis.action_item.set_state(self._params.get_bool(NAP_LOW_VIS_BACKOFF)) + self._cone_hold.action_item.set_state(self._params.get_bool(NAP_CONE_LINE_HOLD)) + self._obstacle_chime.action_item.set_state(self._params.get_bool(NAP_OBSTACLE_CHIME)) + self._turn_geom.action_item.set_state(self._params.get_bool(NAP_LAT_TURN_GEOM)) + self._ref_offset_buttons.action_item.set_selected_button(lat_ref_offset_index(self._params)) + self._turn_in_buttons.action_item.set_selected_button(turn_in_delay_index(self._params)) + self._rb_assist.action_item.set_state(self._params.get_bool(NAP_ROUNDABOUT_ASSIST)) + self._one_pedal.action_item.set_state(self._params.get_bool(NAP_ONE_PEDAL_LONG)) + self._gap_lock.action_item.set_state(self._gap_lock_on()) + + def show_event(self): + self._scroller.show_event() + self.refresh() + + def _render(self, rect): + self._scroller.render(rect) diff --git a/selfdrive/ui/layouts/settings/firehose.py b/selfdrive/ui/layouts/settings/firehose.py new file mode 100644 index 00000000000000..f28f4e3386b74a --- /dev/null +++ b/selfdrive/ui/layouts/settings/firehose.py @@ -0,0 +1,91 @@ +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.selfdrive.ui.mici.layouts.settings.firehose import FirehoseLayoutBase + +TITLE = tr_noop("Firehose Mode") +DESCRIPTION = tr_noop( + "openpilot learns to drive by watching humans, like you, drive.\n\n" + + "Firehose Mode allows you to maximize your training data uploads to improve " + + "openpilot's driving models. More data means bigger models, which means better Experimental Mode." +) +INSTRUCTIONS = tr_noop( + "For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.\n\n" + + "Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.\n\n\n" + + "Frequently Asked Questions\n\n" + + "Does it matter how or where I drive? Nope, just drive as you normally would.\n\n" + + "Do all of my segments get pulled in Firehose Mode? No, we selectively pull a subset of your segments.\n\n" + + "What's a good USB-C adapter? Any fast phone or laptop charger should be fine.\n\n" + + "Does it matter which software I run? Yes, only upstream openpilot (and particular forks) are able to be used for training." +) + + +class FirehoseLayout(FirehoseLayoutBase): + def __init__(self): + super().__init__() + self._scroll_panel = GuiScrollPanel() + + def _render(self, rect: rl.Rectangle): + # Calculate content dimensions + content_rect = rl.Rectangle(rect.x, rect.y, rect.width, self._content_height) + + # Handle scrolling and render with clipping + scroll_offset = self._scroll_panel.update(rect, content_rect) + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + self._content_height = self._render_content(rect, scroll_offset) + rl.end_scissor_mode() + + def _render_content(self, rect: rl.Rectangle, scroll_offset: float) -> int: + x = int(rect.x + 40) + y = int(rect.y + 40 + scroll_offset) + w = int(rect.width - 80) + + # Title (centered) + title_text = tr(TITLE) # live translate + title_font = gui_app.font(FontWeight.MEDIUM) + text_width = measure_text_cached(title_font, title_text, 100).x + title_x = rect.x + (rect.width - text_width) / 2 + rl.draw_text_ex(title_font, title_text, rl.Vector2(title_x, y), 100, 0, rl.WHITE) + y += 200 + + # Description + y = self._draw_wrapped_text(x, y, w, tr(DESCRIPTION), gui_app.font(FontWeight.NORMAL), 45, rl.WHITE) + y += 40 + 20 + + # Separator + rl.draw_rectangle(x, y, w, 2, self.GRAY) + y += 30 + 20 + + # Status + status_text, status_color = self._get_status() + y = self._draw_wrapped_text(x, y, w, status_text, gui_app.font(FontWeight.BOLD), 60, status_color) + y += 20 + 20 + + # TODO: add back once reliable + # Contribution count (if available) + #if self._segment_count > 0: + # contrib_text = trn("{} segment of your driving is in the training dataset so far.", + # "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) + # y = self._draw_wrapped_text(x, y, w, contrib_text, gui_app.font(FontWeight.BOLD), 52, rl.WHITE) + # y += 20 + 20 + + # Separator + rl.draw_rectangle(x, y, w, 2, self.GRAY) + y += 30 + 20 + + # Instructions + y = self._draw_wrapped_text(x, y, w, tr(INSTRUCTIONS), gui_app.font(FontWeight.NORMAL), 40, self.LIGHT_GRAY) + + # bottom margin + remove effect of scroll offset + return int(round(y - self._scroll_panel.offset + 40)) + + def _draw_wrapped_text(self, x, y, width, text, font, font_size, color): + wrapped = wrap_text(font, text, font_size, width) + for line in wrapped: + rl.draw_text_ex(font, line, rl.Vector2(x, y), font_size, 0, color) + y += font_size * FONT_SCALE + return round(y) diff --git a/selfdrive/ui/layouts/settings/hidden_toggles.py b/selfdrive/ui/layouts/settings/hidden_toggles.py new file mode 100644 index 00000000000000..995eb8bc1129c5 --- /dev/null +++ b/selfdrive/ui/layouts/settings/hidden_toggles.py @@ -0,0 +1,178 @@ +"""TICI side popup: Force Offroad + Simulate Look + False Alert Ignore. + +Opened by a NAP sidebar triple-tap. Not a full settings page and not part +of Driving Mannerisms. Tap outside the card (primary), the X, Escape, or +the NAP sidebar item again to dismiss. Simulate Look and False Alert +Ignore are mutually exclusive — enabling one clears the other. +""" +from collections.abc import Callable + +import pyray as rl + +from openpilot.common.params import Params +from openpilot.selfdrive.monitoring.dm_toggles import ( + apply_dm_false_alert_ignore, + apply_dm_simulate_looking, + read_exclusive_dm_toggles, +) +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + CONE_LINE_LOG_DESCRIPTION, + DM_FALSE_ALERT_IGNORE_DESCRIPTION, + DM_SIMULATE_LOOKING_DESCRIPTION, + FORCE_OFFROAD_DESCRIPTION, + NAP_CONE_LINE_LOG, + NAP_DM_FALSE_ALERT_IGNORE, + NAP_DM_SIMULATE_LOOKING, + NAP_FORCE_OFFROAD, +) +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.hardware.nap_force_offroad import apply_force_offroad_toggle +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.list_view import ITEM_BASE_HEIGHT, toggle_item +from openpilot.system.ui.widgets.scroller_tici import Scroller + +CARD_WIDTH = 980 +CARD_HEIGHT = 780 +CARD_MARGIN = 24 +HEADER_H = 72 +CLOSE_SIZE = 64 +DIM = rl.Color(0, 0, 0, 140) +CARD_BG = rl.Color(30, 30, 30, 255) +TITLE_COLOR = rl.Color(201, 201, 201, 255) + + +class HiddenTogglesPopup(Widget): + """Compact side card with the three hidden NAP toggles.""" + + def __init__(self, on_dismiss: Callable[[], None]): + super().__init__() + self._on_dismiss = on_dismiss + self._params = Params() + self._card_rect = rl.Rectangle(0, 0, 0, 0) + self._font = gui_app.font(FontWeight.BOLD) + + self._offroad_item = toggle_item( + "Force Offroad", + description=FORCE_OFFROAD_DESCRIPTION, + initial_state=self._params.get_bool(NAP_FORCE_OFFROAD), + callback=self._on_force_offroad, + ) + self._dm_item = toggle_item( + "Simulate Look", + description=DM_SIMULATE_LOOKING_DESCRIPTION, + initial_state=self._params.get_bool(NAP_DM_SIMULATE_LOOKING), + callback=self._on_dm_sim_looking, + ) + self._fai_item = toggle_item( + "False Alert Ignore", + description=DM_FALSE_ALERT_IGNORE_DESCRIPTION, + initial_state=self._params.get_bool(NAP_DM_FALSE_ALERT_IGNORE), + callback=self._on_false_alert_ignore, + ) + self._cone_log_item = toggle_item( + "Cone line log", + description=CONE_LINE_LOG_DESCRIPTION, + initial_state=self._params.get_bool(NAP_CONE_LINE_LOG), + callback=self._on_cone_log, + ) + self._scroller = Scroller( + [self._offroad_item, self._dm_item, self._fai_item, self._cone_log_item], + line_separator=True, + spacing=0, + ) + self._close_btn = Button( + "X", + click_callback=self._dismiss, + font_size=40, + button_style=ButtonStyle.LIST_ACTION, + border_radius=32, + text_padding=0, + ) + + def _on_dm_sim_looking(self, state): + # Use apply() return — put_bool is non-blocking, so get_bool can still + # show the old sibling On until the popup is closed and reopened. + _sim, fai = apply_dm_simulate_looking(self._params, bool(state)) + self._fai_item.action_item.set_state(fai) + + def _on_false_alert_ignore(self, state): + sim, _fai = apply_dm_false_alert_ignore(self._params, bool(state)) + self._dm_item.action_item.set_state(sim) + + def _on_force_offroad(self, state): + apply_force_offroad_toggle(self._params, bool(state), started=bool(ui_state.started)) + + def _on_cone_log(self, state): + self._params.put_bool(NAP_CONE_LINE_LOG, bool(state)) + + def refresh(self): + read_exclusive_dm_toggles(self._params) + self._dm_item.action_item.set_state(self._params.get_bool(NAP_DM_SIMULATE_LOOKING)) + self._fai_item.action_item.set_state(self._params.get_bool(NAP_DM_FALSE_ALERT_IGNORE)) + self._offroad_item.action_item.set_state(self._params.get_bool(NAP_FORCE_OFFROAD)) + self._cone_log_item.action_item.set_state(self._params.get_bool(NAP_CONE_LINE_LOG)) + + def show_event(self): + super().show_event() + self.refresh() + + def contains_card(self, mouse_pos: MousePos) -> bool: + return rl.check_collision_point_rec(mouse_pos, self._card_rect) + + def _dismiss(self): + self._on_dismiss() + + def _layout(self): + width = min(CARD_WIDTH, max(620, self._rect.width - 2 * CARD_MARGIN)) + height = min(CARD_HEIGHT, max(480, self._rect.height - 2 * CARD_MARGIN)) + self._card_rect = rl.Rectangle( + self._rect.x + CARD_MARGIN, + self._rect.y + CARD_MARGIN, + width, + height, + ) + + def _handle_mouse_release(self, mouse_pos: MousePos) -> None: + if not self.contains_card(mouse_pos): + self._dismiss() + + def _render(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, DIM) + rl.draw_rectangle_rounded(self._card_rect, 0.04, 20, CARD_BG) + + close_rect = rl.Rectangle( + self._card_rect.x + self._card_rect.width - CLOSE_SIZE - 16, + self._card_rect.y + (HEADER_H - CLOSE_SIZE) / 2, + CLOSE_SIZE, + CLOSE_SIZE, + ) + title_rect = rl.Rectangle( + self._card_rect.x + 28, + self._card_rect.y, + self._card_rect.width - CLOSE_SIZE - 50, + HEADER_H, + ) + rl.draw_text_ex( + self._font, "NAP", + rl.Vector2(title_rect.x, title_rect.y + 18), + 40, 0, TITLE_COLOR, + ) + self._close_btn.render(close_rect) + + content = rl.Rectangle( + self._card_rect.x + 8, + self._card_rect.y + HEADER_H, + self._card_rect.width - 16, + self._card_rect.height - HEADER_H - 12, + ) + # Three 170px rows; keep a floor so the scroller can expand descriptions. + if content.height < ITEM_BASE_HEIGHT * 3: + content.height = ITEM_BASE_HEIGHT * 3 + self._scroller.render(content) + # No on the confirm dialog clears the param; keep the switch in sync. + self._offroad_item.action_item.set_state(self._params.get_bool(NAP_FORCE_OFFROAD)) + + if rl.is_key_pressed(rl.KeyboardKey.KEY_ESCAPE): + self._dismiss() diff --git a/selfdrive/ui/layouts/settings/map_speed.py b/selfdrive/ui/layouts/settings/map_speed.py new file mode 100644 index 00000000000000..6b90793f08dc09 --- /dev/null +++ b/selfdrive/ui/layouts/settings/map_speed.py @@ -0,0 +1,146 @@ +"""TICI NAP submenu: Map Speed Limit controls.""" +from openpilot.common.params import Params +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.list_view import multiple_button_item, button_item, text_item +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + DOWNLOAD_US_MAPS_INSTRUCTIONS, + MAP_SPEED_LOOKAHEAD, MAP_SPEED_LOOKAHEAD_DESCRIPTION, MAP_SPEED_LOOKAHEAD_LABELS, + MAP_SPEED_MODE_DESCRIPTION, MAP_SPEED_MODES, MAP_SPEED_MODE_LABELS, + MAP_SPEED_OFFSET_DESCRIPTION, MAP_SPEED_OFFSETS_MPH, + REFRESH_MAPS_INSTRUCTIONS, +) +from openpilot.selfdrive.mapd.fetch_maps import installed_db_summary, installed_revision_summary +from openpilot.selfdrive.mapd.roundabout_status import installed_ring_summary +from openpilot.selfdrive.ui.ui_state import ui_state + + +class MapSpeedLimitLayout(Widget): + """Nested NAP page for OSM map-speed mode, offset, and lookahead.""" + + def __init__(self, on_back, on_download, on_refresh): + super().__init__() + self._params = Params() + self._on_back = on_back + self._on_download = on_download + self._on_refresh = on_refresh + self._build_items() + self._scroller = Scroller(self._all_items, line_separator=True, spacing=0) + + def _build_items(self): + self._all_items = [] + self._all_items.append(button_item( + "Back To", + "NAP", + description="Return to NAP settings.", + callback=self._on_back, + )) + + map_mode = int(self._params.get("NAPMapSpeedMode", return_default=True) or 0) + self._mode_buttons = multiple_button_item( + "Map Speed (MAX)", + MAP_SPEED_MODE_DESCRIPTION, + buttons=MAP_SPEED_MODE_LABELS, + button_width=150, + selected_index=max(0, min(3, map_mode)), + callback=self._on_mode, + ) + self._all_items.append(self._mode_buttons) + + offset_mph = int(self._params.get("NAPMapSpeedOffsetMph", return_default=True) or 0) + self._offset_buttons = multiple_button_item( + "Map Speed Offset", + MAP_SPEED_OFFSET_DESCRIPTION, + buttons=["-5 mph", "0", "+5 mph"], + button_width=150, + selected_index=self._offset_index(offset_mph), + callback=self._on_offset, + ) + self._all_items.append(self._offset_buttons) + + lookahead = int(self._params.get("NAPMapSpeedLookahead", return_default=True) or 2) + self._lookahead_buttons = multiple_button_item( + "Lookahead", + MAP_SPEED_LOOKAHEAD_DESCRIPTION, + buttons=MAP_SPEED_LOOKAHEAD_LABELS, + button_width=150, + selected_index=self._lookahead_index(lookahead), + callback=self._on_lookahead, + ) + self._all_items.append(self._lookahead_buttons) + + self._refresh_btn = button_item( + "Refresh maps", + "Start", + description=REFRESH_MAPS_INSTRUCTIONS.split("\n", 1)[0], + callback=self._on_refresh, + ) + self._refresh_btn.action_item.set_enabled(ui_state.is_offroad) + self._all_items.append(self._refresh_btn) + + self._download_btn = button_item( + "Download US Maps", + "Start", + description=DOWNLOAD_US_MAPS_INSTRUCTIONS.split("\n", 1)[0], + callback=self._on_download, + ) + self._download_btn.action_item.set_enabled(ui_state.is_offroad) + self._all_items.append(self._download_btn) + + self._db_status = text_item( + "OSM Map Data", + installed_db_summary, + description="US OpenStreetMap maxspeed ways (ODbL). Download after flash; Refresh overlays live OSM within 100 miles.", + ) + self._all_items.append(self._db_status) + + self._ring_status = text_item( + "Roundabout data", + installed_ring_summary, + description="Roundabout rings in the map pack. If this says Missing, run Refresh maps (offroad, on Wi-Fi) or the" + + " roundabout slow-down cannot fire.", + ) + self._all_items.append(self._ring_status) + + self._revision_status = text_item( + "Map revision", + installed_revision_summary, + description="Published US pack revision. Refresh maps does not bump this number.", + ) + self._all_items.append(self._revision_status) + + def _offset_index(self, offset_mph: int) -> int: + if offset_mph in MAP_SPEED_OFFSETS_MPH: + return MAP_SPEED_OFFSETS_MPH.index(offset_mph) + return 1 + + def _lookahead_index(self, value: int) -> int: + if value in MAP_SPEED_LOOKAHEAD: + return MAP_SPEED_LOOKAHEAD.index(value) + return 2 + + def _on_mode(self, index: int): + self._params.put("NAPMapSpeedMode", MAP_SPEED_MODES[index]) + + def _on_offset(self, index: int): + self._params.put("NAPMapSpeedOffsetMph", int(MAP_SPEED_OFFSETS_MPH[index])) + + def _on_lookahead(self, index: int): + self._params.put("NAPMapSpeedLookahead", MAP_SPEED_LOOKAHEAD[index]) + + def refresh(self): + map_mode = int(self._params.get("NAPMapSpeedMode", return_default=True) or 0) + self._mode_buttons.action_item.set_selected_button(max(0, min(3, map_mode))) + offset_mph = int(self._params.get("NAPMapSpeedOffsetMph", return_default=True) or 0) + self._offset_buttons.action_item.set_selected_button(self._offset_index(offset_mph)) + lookahead = int(self._params.get("NAPMapSpeedLookahead", return_default=True) or 2) + self._lookahead_buttons.action_item.set_selected_button(self._lookahead_index(lookahead)) + self._refresh_btn.action_item.set_enabled(ui_state.is_offroad) + self._download_btn.action_item.set_enabled(ui_state.is_offroad) + + def show_event(self): + self._scroller.show_event() + self.refresh() + + def _render(self, rect): + self._scroller.render(rect) diff --git a/selfdrive/ui/layouts/settings/nap.py b/selfdrive/ui/layouts/settings/nap.py new file mode 100644 index 00000000000000..bc21bfe077dad8 --- /dev/null +++ b/selfdrive/ui/layouts/settings/nap.py @@ -0,0 +1,898 @@ +import os +import subprocess +import pyray as rl +from openpilot.common.params import Params +from openpilot.common.basedir import BASEDIR +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.keyboard import Keyboard +from openpilot.system.ui.widgets.list_view import ( + toggle_item, multiple_button_item, button_item, text_item, + ITEM_PADDING, +) +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.button import Button +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.script_runner import ScriptRunner +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets.html_render import HtmlRenderer, ElementType +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + BACKUP_EPAS_INSTRUCTIONS, BRAKE_FACTOR_PRESETS, + CALIBRATE_PEDAL_INSTRUCTIONS, + DOWNLOAD_US_MAPS_INSTRUCTIONS, + FLASH_EPAS_INSTRUCTIONS, + INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS, PEDAL_CAN_BUS_VALUES, + HIGH_LOW_BEAM_DESCRIPTION, HIGH_LOW_BEAM_LABELS, HIGH_LOW_BEAM_VALUES, + MAP_SPEED_ACCEL_DEFAULT, + NAP_DM_FALSE_ALERT_IGNORE, + NAP_DM_SIMULATE_LOOKING, + NAP_CONE_LINE_HOLD, + NAP_CONE_LINE_LOG, + NAP_OBSTACLE_CHIME, + NAP_OBSTACLE_LOG, + NAP_DRIVER_LAT_HANDOFF, + NAP_LOW_VIS_BACKOFF, + NAP_FORCE_OFFROAD, + NAP_HYPERMILE, + NAP_HYPERMILE_HILL_CLIMB, + NAP_HYPERMILE_STEP_DOWN, + NAP_ONE_PEDAL_LONG, + NAP_SPEED_SIGN_LOG, + RADAR_OFFSET_MAX, RADAR_OFFSET_MIN, + REFRESH_MAPS_INSTRUCTIONS, + RESTORE_EPAS_INSTRUCTIONS, + SPEED_SIGN_LOG_DESCRIPTION, + WIPER_SPEED_DESCRIPTION, WIPER_SPEED_LABELS, WIPER_SPEED_VALUES, + WIPER_SENSITIVITY_DEFAULT, WIPER_SENSITIVITY_DESCRIPTION, + WIPER_SENSITIVITY_LABELS, WIPER_SENSITIVITY_VALUES, + acknowledgments_html, coerce_wiper_speed_param, find_preset_index, + wiper_speed_button_index, +) +from openpilot.selfdrive.ui.layouts.settings.driving_mannerisms import DrivingMannerismsLayout +from openpilot.selfdrive.ui.layouts.settings.map_speed import MapSpeedLimitLayout +# Row text is install_status_summary (weights plus "runtime missing"). +# weights_status_summary remains the weights-only label ("Installed" / "Out of date" / "Missing"). +from openpilot.selfdrive.speedsignd.install import install_status_summary +from openpilot.selfdrive.car.tesla.preap_body_controls import register_nap_body_params +from opendbc.car.tesla.preap.nap_params import NAPParamKeys, DEFAULTS + +register_nap_body_params() +from openpilot.selfdrive.ui.radar.radar_view import RadarMonitorDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from scripts.nap.script_lifecycle import script_reboots_on_exit + + + +class SectionHeader(Widget): + """Lightweight section label to visually separate groups of settings.""" + + HEADER_HEIGHT = 70 + + def __init__(self, title: str): + super().__init__() + self._title = title + self._font = gui_app.font(FontWeight.BOLD) + self.set_rect(rl.Rectangle(0, 0, 0, self.HEADER_HEIGHT)) + + def set_parent_rect(self, parent_rect: rl.Rectangle): + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + + def _render(self, rect): + text_size = measure_text_cached(self._font, self._title, 40) + text_y = self._rect.y + (self._rect.height - text_size.y) / 2 + rl.draw_text_ex( + self._font, self._title, + rl.Vector2(self._rect.x + ITEM_PADDING, text_y), + 40, 0, rl.Color(180, 180, 180, 255), + ) + + +class CreditsBlock(Widget): + """Static block of HTML-rendered credits text with auto-sized height.""" + + def __init__(self, html: str): + super().__init__() + self._html = HtmlRenderer( + text=html, + text_size={ElementType.P: 40}, + text_color=rl.Color(140, 140, 140, 255), + ) + self.set_rect(rl.Rectangle(0, 0, 0, 200)) # placeholder height + + def set_parent_rect(self, parent_rect: rl.Rectangle): + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + content_w = int(self._rect.width - ITEM_PADDING * 2) + self._rect.height = self._html.get_total_height(content_w) + ITEM_PADDING + + def _render(self, rect): + content_w = int(self._rect.width - ITEM_PADDING * 2) + h = self._html.get_total_height(content_w) + html_rect = rl.Rectangle( + self._rect.x + ITEM_PADDING, self._rect.y, + content_w, h, + ) + self._html.set_rect(html_rect) + self._html.render(html_rect) + + +def section_header_item(title: str) -> SectionHeader: + return SectionHeader(title) + + +class NAPLayout(Widget): + def __init__(self): + super().__init__() + self._params = Params() + self._page = "main" + self._build_items() + self._scroller = Scroller(self._main_items, line_separator=True, spacing=0) + self._radar_scroller = Scroller(self._radar_items, line_separator=True, spacing=0) + self._radar_back_btn = Button("Back", click_callback=self._close_radar) + self._radar_back_btn.set_rect(rl.Rectangle(0, 0, 220, 90)) + self._speed_sign_scroller = Scroller(self._speed_sign_items, line_separator=True, spacing=0) + self._speed_sign_back_btn = Button("Back", click_callback=self._close_speed_sign) + self._speed_sign_back_btn.set_rect(rl.Rectangle(0, 0, 220, 90)) + + def _build_items(self): + """Build all list items organized into sections.""" + self._main_items = [] + self._radar_items = [] + self._speed_sign_items = [] + self._toggle_map = {} # param_key -> ListItem (for refresh) + + # ── Section 0: Speed Sign (submenu; top — flip Logger while testing) ── + self._main_items.append(section_header_item("Speed Sign")) + self._speed_sign_btn = button_item( + "Speed Sign Reader", + "Open", + description="Speed Sign Logger, Speed Sign Weights, and Install weights.", + callback=self._open_speed_sign, + ) + self._main_items.append(self._speed_sign_btn) + self._build_speed_sign_items() + + # ── Section 1: Longitudinal Control ── + # Force Offroad / Simulate Look / False Alert Ignore live in the NAP triple-tap popup. + self._main_items.append(section_header_item("Longitudinal Control")) + + self._add_toggle( + NAPParamKeys.PEDAL_ENABLED, + "Pedal Interceptor", + "Enable Comma Pedal hardware for direct throttle control. Requires reboot.", + enabled=ui_state.is_offroad, + needs_reboot=True, + ) + + self._driving_mannerisms_page = DrivingMannerismsLayout( + on_back=self._close_driving_mannerisms, + ) + self._driving_mannerisms_btn = button_item( + "Driving Mannerisms", + "Open", + description="Accel feel, follow, soft lat, one-pedal, and Hypermile.", + callback=self._open_driving_mannerisms, + ) + self._main_items.append(self._driving_mannerisms_btn) + + self._map_speed_page = MapSpeedLimitLayout( + on_back=self._close_map_speed, + on_download=self._on_download_us_maps, + on_refresh=self._on_refresh_maps, + ) + self._page = "main" + self._map_speed_btn = button_item( + "Map Speed Limit", + "Open", + description="OSM posted limits — mode, offset, lookahead, and maps.", + callback=self._open_map_speed, + ) + self._main_items.append(self._map_speed_btn) + + # ── Section 2: Pedal Hardware ── + self._main_items.append(section_header_item("Pedal Hardware")) + + + pedal_bus = self._params.get(NAPParamKeys.PEDAL_CAN_BUS, return_default=True) + self._pedal_bus_buttons = multiple_button_item( + "Pedal CAN Bus", + "Select which CAN bus the Comma Pedal is connected to. Requires reboot.", + buttons=["Bus 0", "Bus 2"], + button_width=150, + selected_index=0 if pedal_bus == 0 else 1, + callback=self._on_pedal_can_bus, + ) + self._pedal_bus_buttons.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._pedal_bus_buttons) + + self._pedal_calib_status = text_item( + "Pedal Calibration", + lambda: "Calibrated" if self._params.get_bool(NAPParamKeys.PEDAL_CALIB_DONE) else "Not Calibrated", + description="Shows whether the pedal interceptor has been calibrated.", + ) + self._main_items.append(self._pedal_calib_status) + + self._calibrate_pedal_btn = button_item( + "Calibrate Pedal", + "Start", + description="Run the pedal calibration routine. Vehicle must be stationary with ignition on.", + callback=self._on_calibrate_pedal, + ) + self._calibrate_pedal_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._calibrate_pedal_btn) + + # ── Section 3: Radar (submenu) ── + self._main_items.append(section_header_item("Radar")) + self._radar_settings_btn = button_item( + "Radar Settings", + "Open", + description="Donor VIN, position, offset, test, and calibration.", + callback=self._open_radar, + ) + self._main_items.append(self._radar_settings_btn) + self._build_radar_items() + + # ── Section 4: iBooster / Braking (not yet implemented — grayed out) ── + self._main_items.append(section_header_item("iBooster / Braking")) + + self._add_toggle( + NAPParamKeys.IBOOSTER_ENABLED, + "iBooster Enabled", + "Enable the iBooster brake-by-wire system for electronic braking. (Not yet implemented)", + enabled=False, + ) + + brake_factor = self._params.get(NAPParamKeys.BRAKE_FACTOR, return_default=True) + self._brake_factor_buttons = multiple_button_item( + "Brake Factor", + "Multiplier for brake force. Higher values brake more aggressively. (Not yet implemented)", + buttons=["0.5x", "1.0x", "1.5x", "2.0x"], + button_width=130, + selected_index=find_preset_index(BRAKE_FACTOR_PRESETS, brake_factor), + callback=self._on_brake_factor, + ) + self._brake_factor_buttons.action_item.set_enabled(False) + self._main_items.append(self._brake_factor_buttons) + + # ── Section 5: Wipers & lights (car test) ── + self._main_items.append(section_header_item("Wipers & Lights (test)")) + + wiper_setting = coerce_wiper_speed_param(self._params) + self._wiper_buttons = multiple_button_item( + "Wiper Control", + WIPER_SPEED_DESCRIPTION, + buttons=WIPER_SPEED_LABELS, + button_width=160, + selected_index=wiper_speed_button_index(wiper_setting), + callback=self._on_wiper_speed, + ) + self._main_items.append(self._wiper_buttons) + + raw_sens = self._params.get(NAPParamKeys.WIPER_SENSITIVITY, return_default=True) + try: + sens_setting = WIPER_SENSITIVITY_DEFAULT if raw_sens is None else int(raw_sens) + except (TypeError, ValueError): + sens_setting = WIPER_SENSITIVITY_DEFAULT + self._wiper_sens_buttons = multiple_button_item( + "Wiper Sensitivity", + WIPER_SENSITIVITY_DESCRIPTION, + buttons=WIPER_SENSITIVITY_LABELS, + button_width=110, + selected_index=max(0, min(len(WIPER_SENSITIVITY_VALUES) - 1, sens_setting)), + callback=self._on_wiper_sensitivity, + ) + self._main_items.append(self._wiper_sens_buttons) + + beam_setting = int(self._params.get(NAPParamKeys.HIGH_LOW_BEAM, return_default=True) or 0) + self._beam_buttons = multiple_button_item( + "High / Low Beam", + HIGH_LOW_BEAM_DESCRIPTION, + buttons=HIGH_LOW_BEAM_LABELS, + button_width=130, + selected_index=max(0, min(len(HIGH_LOW_BEAM_VALUES) - 1, beam_setting)), + callback=self._on_high_low_beam, + ) + self._main_items.append(self._beam_buttons) + + # ── Section 6: Advanced ── + self._main_items.append(section_header_item("Advanced")) + + # Force Pre-AP is always on for now — grayed out in the ON position + self._params.put_bool(NAPParamKeys.FORCE_PRE_AP, True) + self._add_toggle( + NAPParamKeys.FORCE_PRE_AP, + "Force Pre-AP Mode", + "Force the system to treat this vehicle as a Pre-Autopilot Tesla.", + enabled=False, + ) + + # ── Section 7: Actions ── + self._main_items.append(section_header_item("Actions")) + + self._backup_epas_btn = button_item( + "Backup EPAS", + "Extract", + description="Extract and save stock EPAS firmware image without flashing.", + callback=self._on_backup_epas, + ) + self._backup_epas_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._backup_epas_btn) + + self._flash_epas_btn = button_item( + "Flash EPAS", + "Flash", + description="Flash the EPAS (Electric Power Assisted Steering) firmware.", + callback=self._on_flash_epas, + ) + self._flash_epas_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._flash_epas_btn) + + self._restore_epas_btn = button_item( + "Restore EPAS", + "Restore", + description="Restore stock EPAS firmware image.", + callback=self._on_restore_epas, + ) + self._restore_epas_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._restore_epas_btn) + + self._emergency_disable_btn = button_item( + "Emergency Disable", + "Disable", + description="Immediately disable pedal interceptor and clear calibration. Restart required.", + callback=self._on_emergency_disable, + ) + self._main_items.append(self._emergency_disable_btn) + + self._reset_defaults_btn = button_item( + "Reset to Defaults", + "Reset", + description="Reset all NAP settings to factory defaults. This cannot be undone.", + callback=self._on_reset_defaults, + ) + self._reset_defaults_btn.action_item.set_enabled(ui_state.is_offroad) + self._main_items.append(self._reset_defaults_btn) + + # ── Acknowledgments ── + self._main_items.append(section_header_item("Acknowledgments")) + self._main_items.append(CreditsBlock(acknowledgments_html())) + + def _build_speed_sign_items(self): + self._speed_sign_items.append(section_header_item("Speed Sign Reader")) + + self._add_toggle( + NAP_SPEED_SIGN_LOG, + "Speed Sign Logger", + SPEED_SIGN_LOG_DESCRIPTION, + dest=self._speed_sign_items, + ) + + self._weights_status = text_item( + "Speed Sign Weights", + install_status_summary, + description=( + "YOLO ONNX at /data/media/0/nap/speed_sign.onnx. " + + "Missing → onroad SIGN shows NO WT and will not read roadside signs. " + + "runtime missing — tap Install weights means the plate shows NO RT. " + + "Install weights unpacks onnxruntime into /data/media/0/nap/pylib. " + + "Installed → blank plate until a confirmed mph." + ), + ) + self._speed_sign_items.append(self._weights_status) + + self._install_weights_btn = button_item( + "Install weights", + "Start", + description=INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS.split("\n", 1)[0], + callback=self._on_install_speed_sign_weights, + ) + self._install_weights_btn.action_item.set_enabled(ui_state.is_offroad) + self._speed_sign_items.append(self._install_weights_btn) + + def _build_radar_items(self): + self._radar_items.append(section_header_item("Radar")) + + self._add_toggle( + NAPParamKeys.RADAR_ENABLED, + "Radar Enabled", + "Enable the stock Bosch radar for lead car detection. When on, " + "path-synced radar is preferred for long lead if the track is on " + "the model path and radar is healthy. Off or unhealthy falls back " + "to stock fusion. Requires reboot.", + enabled=ui_state.is_offroad, + needs_reboot=True, + dest=self._radar_items, + ) + + self._add_toggle( + NAPParamKeys.RADAR_IGNORE_HW_FAIL, + "Ignore radar hardware fail", + "Lets you engage when Bosch raises HWFail even though tracks are still live.", + dest=self._radar_items, + ) + + def on_radar_hud(state): + self._params.put_bool(NAPParamKeys.RADAR_HUD, state) + ui_state.radar_hud = state + + hud_item = toggle_item( + "Radar HUD", + description="Show live tracks, lamps, and alert bits over the driving view. Works while driving.", + initial_state=self._params.get_bool(NAPParamKeys.RADAR_HUD), + callback=on_radar_hud, + ) + self._toggle_map[NAPParamKeys.RADAR_HUD] = hud_item + self._radar_items.append(hud_item) + + self._radar_offset_keyboard = Keyboard(max_text_size=10) + self._radar_offset_btn = button_item( + "Radar Lateral Offset", + self._get_radar_offset_text, + description=( + "Lateral offset in meters added to radar yRel. Negative shifts leads toward the left of current radar " + + "reading; positive shifts right. Example: -0.27 for the 3D-printed factory-location mount." + ), + callback=self._on_radar_offset_click, + ) + self._radar_items.append(self._radar_offset_btn) + + self._radar_vin_keyboard = Keyboard(max_text_size=17) + self._radar_vin_btn = button_item( + "Donor Radar VIN", + self._get_radar_vin_text, + description=( + "VIN already programmed in a salvage radar. Leave empty to send this car. " + + "A 17-character VIN makes panda impersonate the donor (Tinkla 0.6.6)." + ), + callback=self._on_radar_vin_click, + ) + self._radar_items.append(self._radar_vin_btn) + + self._read_vin_btn = button_item( + "Read VIN", + self._get_read_vin_text, + description=( + "Read the VIN stored in the radar (F190). Does not write or flash. " + + "Car must be on and not engaged. Power-cycle after it fills." + ), + callback=self._on_read_vin, + ) + self._radar_items.append(self._read_vin_btn) + + radar_position = int(self._params.get(NAPParamKeys.RADAR_POSITION, return_default=True) or 0) + self._radar_position_buttons = multiple_button_item( + "Donor Radar Position", + "Always sent when radar is on, including empty VIN. 0 pre-facelift S, 1 post-facelift S, 2 Model X.", + buttons=["0", "1", "2"], + button_width=130, + selected_index=max(0, min(2, radar_position)), + callback=self._on_radar_position, + ) + self._radar_items.append(self._radar_position_buttons) + + radar_epas = int(self._params.get(NAPParamKeys.RADAR_EPAS_TYPE, return_default=True) or 0) + self._radar_epas_buttons = multiple_button_item( + "Donor EPAS Type", + "Must match the donor car rack: 0 Bosch L538, 1 L405, 2 Mando FGR64, 3 VGR66, 4 VGR66 Gen3.", + buttons=["0", "1", "2", "3", "4"], + button_width=100, + selected_index=max(0, min(4, radar_epas)), + callback=self._on_radar_epas, + ) + self._radar_items.append(self._radar_epas_buttons) + + self._live_radar_btn = button_item( + "Live Radar", + "Open", + description="Live tracks, ECU lamps, and alert bits. Stays in this session; works while driving.", + callback=self._on_live_radar, + ) + self._radar_items.append(self._live_radar_btn) + + def _add_toggle(self, param_key: str, title: str, description: str, + enabled: bool | None = None, needs_reboot: bool = False, + dest: list | None = None): + """Helper to add a toggle item and register it for state refresh.""" + kwargs = {} + if enabled is not None: + kwargs['enabled'] = enabled + + def on_toggle(state, k=param_key): + self._params.put_bool(k, state) + if needs_reboot: + self._show_reboot_modal() + + item = toggle_item( + title, + description=description, + initial_state=self._params.get_bool(param_key), + callback=on_toggle, + **kwargs, + ) + self._toggle_map[param_key] = item + (dest if dest is not None else self._main_items).append(item) + + # ── Multiple-button callbacks ── + + def _open_driving_mannerisms(self): + self._page = "driving_mannerisms" + self._driving_mannerisms_page.show_event() + + def _close_driving_mannerisms(self): + self._page = "main" + + def _open_map_speed(self): + self._page = "map_speed" + self._map_speed_page.show_event() + + def _close_map_speed(self): + self._page = "main" + + def _on_pedal_can_bus(self, index: int): + self._params.put(NAPParamKeys.PEDAL_CAN_BUS, PEDAL_CAN_BUS_VALUES[index]) + self._show_reboot_modal() + + def _on_brake_factor(self, index: int): + self._params.put(NAPParamKeys.BRAKE_FACTOR, BRAKE_FACTOR_PRESETS[index]) + + def _on_wiper_speed(self, index: int): + self._params.put(NAPParamKeys.WIPER_SPEED, WIPER_SPEED_VALUES[index]) + + def _on_wiper_sensitivity(self, index: int): + self._params.put(NAPParamKeys.WIPER_SENSITIVITY, WIPER_SENSITIVITY_VALUES[index]) + + def _on_high_low_beam(self, index: int): + self._params.put(NAPParamKeys.HIGH_LOW_BEAM, HIGH_LOW_BEAM_VALUES[index]) + + def _get_radar_offset(self) -> float: + raw = self._params.get(NAPParamKeys.RADAR_OFFSET, return_default=True) + try: + return float(raw) if raw is not None else 0.0 + except (TypeError, ValueError): + return 0.0 + + def _get_radar_offset_text(self) -> str: + return f"{self._get_radar_offset():+.2f}m" + + def _get_radar_vin_text(self) -> str: + raw = self._params.get(NAPParamKeys.RADAR_DONOR_VIN, return_default=True) or "" + if isinstance(raw, bytes): + raw = raw.decode("ascii", errors="ignore") + vin = "".join(ch for ch in str(raw).upper() if ch.isalnum()) + return vin if len(vin) == 17 else "Not set" + + def _get_read_vin_text(self) -> str: + if self._params.get_bool(NAPParamKeys.RADAR_READ_VIN): + return "Reading..." + raw = self._params.get(NAPParamKeys.RADAR_VIN_READ_STATUS, return_default=True) or "" + if isinstance(raw, bytes): + raw = raw.decode("ascii", errors="ignore") + status = str(raw).strip() + if status.startswith("saved "): + return "Cycle car" + if status: + return status[:18] + return "Read" + + def _open_speed_sign(self): + self._page = "speed_sign" + self._speed_sign_scroller.show_event() + + def _close_speed_sign(self): + self._page = "main" + self._scroller.show_event() + + def _open_radar(self): + self._page = "radar" + self._radar_scroller.show_event() + + def _close_radar(self): + self._page = "main" + self._scroller.show_event() + + def _on_read_vin(self): + if ui_state.engaged: + dlg = ConfirmDialog( + "

Disengage first


VIN read is blocked while openpilot is engaged.

", + "OK", cancel_text="Close", rich=True, + ) + gui_app.push_widget(dlg) + return + + if not self._params.get_bool(NAPParamKeys.RADAR_ENABLED): + dlg = ConfirmDialog( + "

Enable radar first


Read VIN needs radar on. Toggle it and reboot, then try again.

", + "OK", cancel_text="Close", rich=True, + ) + gui_app.push_widget(dlg) + return + + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + self._params.put_bool(NAPParamKeys.RADAR_READ_VIN, True) + + content = ( + "

Read VIN


" + + "

Reads the VIN stored in the radar. Does not write or flash. " + + "Leave the car on and do not engage. Power-cycle after it fills.

" + ) + dlg = ConfirmDialog(content, "Read", rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + def _on_radar_vin_click(self): + current = self._get_radar_vin_text() + self._radar_vin_keyboard.reset(min_text_size=0) + self._radar_vin_keyboard.set_title("Donor Radar VIN") + self._radar_vin_keyboard.set_text("" if current == "Not set" else current) + self._radar_vin_keyboard.set_callback(self._on_radar_vin_submit) + gui_app.push_widget(self._radar_vin_keyboard) + + def _on_radar_vin_submit(self, result: DialogResult): + if result != DialogResult.CONFIRM: + return + text = "".join(ch for ch in (self._radar_vin_keyboard.text or "").upper() if ch.isalnum()) + try: + self._params.put(NAPParamKeys.RADAR_DONOR_VIN, text if len(text) == 17 else "") + except Exception: + pass + + def _on_radar_position(self, index: int): + try: + self._params.put(NAPParamKeys.RADAR_POSITION, int(index)) + except Exception: + pass + + def _on_radar_epas(self, index: int): + try: + self._params.put(NAPParamKeys.RADAR_EPAS_TYPE, int(index)) + except Exception: + pass + + def _on_radar_offset_click(self): + self._radar_offset_keyboard.reset(min_text_size=1) + self._radar_offset_keyboard.set_title("Radar Lateral Offset (m)") + self._radar_offset_keyboard.set_text(f"{self._get_radar_offset():.2f}") + self._radar_offset_keyboard.set_callback(self._on_radar_offset_submit) + gui_app.push_widget(self._radar_offset_keyboard) + + def _on_radar_offset_submit(self, result: DialogResult): + if result != DialogResult.CONFIRM: + return + try: + text = (self._radar_offset_keyboard.text or "").strip() + value = float(text) + except (TypeError, ValueError, AttributeError): + return # silently reject blank/non-numeric input; label stays at prior value + value = max(RADAR_OFFSET_MIN, min(RADAR_OFFSET_MAX, value)) + # Pass raw float (matches the BRAKE_FACTOR put pattern). Params + # previously got str(value) which threw inside Params for FLOAT-typed + # keys; exception propagated out of the Keyboard Enter callback, + # crashing the UI and leaving the Params value unset (label stuck at + # the 0.0 default). Keep the try/except so no future value ever kills + # the UI. + try: + self._params.put(NAPParamKeys.RADAR_OFFSET, value) + except Exception: + pass + + # ── Script runner ── + + def _show_script_runner(self, title: str, instructions: str, script_module: str): + """Map sqlite jobs overlay in-process (one screen). Hardware scripts spawn run_script.py.""" + if not script_reboots_on_exit(script_module): + gui_app.push_widget(ScriptRunner( + title=title, + instructions=instructions, + script_module=script_module, + on_close=lambda: gui_app.pop_widget(), + cwd=BASEDIR, + )) + return + + script_path = os.path.join(BASEDIR, "scripts", "nap", "run_script.py") + log_path = "/tmp/nap_script_runner.log" + + with open(log_path, "w") as log_file: + subprocess.Popen( + ["python", script_path, title, script_module, instructions], + cwd=BASEDIR, + start_new_session=True, + stdout=log_file, + stderr=log_file, + ) + + # ── Action button callbacks ── + + def _on_install_speed_sign_weights(self): + self._show_script_runner( + title="Install weights", + instructions=INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS, + script_module="scripts.nap.install_speed_sign_weights", + ) + + def _on_download_us_maps(self): + self._show_script_runner( + title="Download US Maps", + instructions=DOWNLOAD_US_MAPS_INSTRUCTIONS, + script_module="scripts.nap.fetch_osm_maps", + ) + + def _on_refresh_maps(self): + self._show_script_runner( + title="Refresh maps", + instructions=REFRESH_MAPS_INSTRUCTIONS, + script_module="scripts.nap.refresh_osm_maps", + ) + + def _on_calibrate_pedal(self): + self._show_script_runner( + title="Pedal Calibration", + instructions=CALIBRATE_PEDAL_INSTRUCTIONS, + script_module="scripts.nap.calibrate_pedal", + ) + + def _on_live_radar(self): + gui_app.push_widget(RadarMonitorDialog()) + + def _on_flash_epas(self): + self._show_script_runner( + title="Flash EPAS Firmware", + instructions=FLASH_EPAS_INSTRUCTIONS, + script_module="scripts.nap.flash_epas", + ) + + def _on_backup_epas(self): + self._show_script_runner( + title="Backup EPAS Firmware", + instructions=BACKUP_EPAS_INSTRUCTIONS, + script_module="scripts.nap.extract_epas", + ) + + def _on_restore_epas(self): + self._show_script_runner( + title="Restore EPAS Firmware", + instructions=RESTORE_EPAS_INSTRUCTIONS, + script_module="scripts.nap.restore_epas", + ) + + def _show_reboot_modal(self): + """Show a modal prompting the user to reboot for the change to take effect.""" + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + self._params.put_bool("DoReboot", True) + + content = "

Reboot Required


This change requires a reboot to take effect.

" + dlg = ConfirmDialog(content, "Reboot", cancel_text="Ignore", rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + def _on_emergency_disable(self): + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + self._params.put_bool(NAPParamKeys.PEDAL_ENABLED, False) + self._params.put_bool(NAPParamKeys.PEDAL_CALIB_DONE, False) + self._refresh_toggles() + + content = ( + "

Emergency Disable


" + + "

This will disable the pedal interceptor and clear calibration. " + + "You will need to restart the device for changes to take effect.

" + ) + dlg = ConfirmDialog(content, "Disable", rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + def _on_reset_defaults(self): + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + self._reset_all_to_defaults() + self._refresh_toggles() + + content = ( + "

Reset to Defaults


" + + "

This will reset all NAP settings to their factory default values. " + + "This action cannot be undone.

" + ) + dlg = ConfirmDialog(content, "Reset All", rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + def _reset_all_to_defaults(self): + """Write default value for each NAP param.""" + for key, default in DEFAULTS.items(): + if isinstance(default, bool): + self._params.put_bool(key, default) + elif isinstance(default, (int, float)): + self._params.put(key, default) + self._params.put("NAPMapSpeedMode", 0) + self._params.put("NAPMapSpeedOffsetMph", 0) + self._params.put("NAPMapSpeedLookahead", 2) + self._params.put("NAPMapSpeedAccel", MAP_SPEED_ACCEL_DEFAULT) + self._params.remove("NAPMapSpeedDbPath") + self._params.put_bool(NAP_SPEED_SIGN_LOG, False) + self._params.put_bool(NAP_DRIVER_LAT_HANDOFF, True) + self._params.put_bool(NAP_LOW_VIS_BACKOFF, True) + self._params.put_bool(NAP_CONE_LINE_HOLD, True) + self._params.put_bool(NAP_CONE_LINE_LOG, True) + self._params.put_bool(NAP_OBSTACLE_CHIME, True) + self._params.put_bool(NAP_OBSTACLE_LOG, True) + self._params.put_bool(NAP_DM_SIMULATE_LOOKING, True) + self._params.put_bool(NAP_DM_FALSE_ALERT_IGNORE, False) + self._params.put_bool(NAP_HYPERMILE, False) + self._params.put_bool(NAP_HYPERMILE_STEP_DOWN, False) + self._params.put_bool(NAP_HYPERMILE_HILL_CLIMB, True) + self._params.put_bool(NAP_ONE_PEDAL_LONG, False) + self._params.remove("NAPHypermileSaved") + self._params.put_bool(NAP_FORCE_OFFROAD, False) + self._params.put_bool("NAPForceOffroadConfirmed", False) + self._params.put_bool("NAPForceOffroadHandoffReady", False) + self._page = "main" + # Force Pre-AP is locked on in the panel but DEFAULTS keeps it off + # for non-UI consumers. Re-apply the lock after the wholesale loop + # so reset doesn't silently flip the invariant. + self._params.put_bool(NAPParamKeys.FORCE_PRE_AP, True) + + # ── Render / lifecycle ── + + def _render(self, rect): + if self._page == "map_speed": + self._map_speed_page.render(rect) + elif self._page == "driving_mannerisms": + self._driving_mannerisms_page.render(rect) + elif self._page == "speed_sign": + self._speed_sign_back_btn.set_position(rect.x, rect.y + 10) + self._speed_sign_back_btn.render() + content = rl.Rectangle( + rect.x, rect.y + self._speed_sign_back_btn.rect.height + 20, + rect.width, rect.height - self._speed_sign_back_btn.rect.height - 20, + ) + self._speed_sign_scroller.render(content) + elif self._page == "radar": + self._radar_back_btn.set_position(rect.x, rect.y + 10) + self._radar_back_btn.render() + content = rl.Rectangle( + rect.x, rect.y + self._radar_back_btn.rect.height + 20, + rect.width, rect.height - self._radar_back_btn.rect.height - 20, + ) + self._radar_scroller.render(content) + else: + self._scroller.render(rect) + + def show_event(self): + self._page = "main" + self._scroller.show_event() + self._refresh_toggles() + + def _refresh_toggles(self): + """Sync all toggle states from params (handles external changes).""" + for key, item in self._toggle_map.items(): + item.action_item.set_state(self._params.get_bool(key)) + + # Refresh multiple-button selections + pedal_bus = self._params.get(NAPParamKeys.PEDAL_CAN_BUS, return_default=True) + self._pedal_bus_buttons.action_item.set_selected_button( + 0 if pedal_bus == 0 else 1) + + brake_factor = self._params.get(NAPParamKeys.BRAKE_FACTOR, return_default=True) + self._brake_factor_buttons.action_item.set_selected_button( + find_preset_index(BRAKE_FACTOR_PRESETS, brake_factor)) + + wiper_setting = coerce_wiper_speed_param(self._params) + self._wiper_buttons.action_item.set_selected_button( + wiper_speed_button_index(wiper_setting)) + raw_sens = self._params.get(NAPParamKeys.WIPER_SENSITIVITY, return_default=True) + try: + sens_setting = WIPER_SENSITIVITY_DEFAULT if raw_sens is None else int(raw_sens) + except (TypeError, ValueError): + sens_setting = WIPER_SENSITIVITY_DEFAULT + self._wiper_sens_buttons.action_item.set_selected_button( + max(0, min(len(WIPER_SENSITIVITY_VALUES) - 1, sens_setting))) + beam_setting = int(self._params.get(NAPParamKeys.HIGH_LOW_BEAM, return_default=True) or 0) + self._beam_buttons.action_item.set_selected_button( + max(0, min(len(HIGH_LOW_BEAM_VALUES) - 1, beam_setting))) + + self._driving_mannerisms_page.refresh() + self._map_speed_page.refresh() + self._install_weights_btn.action_item.set_enabled(ui_state.is_offroad) + radar_position = int(self._params.get(NAPParamKeys.RADAR_POSITION, return_default=True) or 0) + self._radar_position_buttons.action_item.set_selected_button(max(0, min(2, radar_position))) + radar_epas = int(self._params.get(NAPParamKeys.RADAR_EPAS_TYPE, return_default=True) or 0) + self._radar_epas_buttons.action_item.set_selected_button(max(0, min(4, radar_epas))) diff --git a/selfdrive/ui/layouts/settings/nap_content.py b/selfdrive/ui/layouts/settings/nap_content.py new file mode 100644 index 00000000000000..5885c6cc8955ac --- /dev/null +++ b/selfdrive/ui/layouts/settings/nap_content.py @@ -0,0 +1,571 @@ +"""Shared NAP settings content. + +Constants and user-facing text used by the NAP settings panels. Both UI trees +import from here so the safety-critical instruction strings (EPAS flash, +calibration, restore) have a single source. +""" + +# Preset values for float/int params exposed as multiple-button selectors. +BRAKE_FACTOR_PRESETS = [0.5, 1.0, 1.5, 2.0] +PEDAL_CAN_BUS_VALUES = [0, 2] + +MAP_SPEED_MODES = [0, 1, 2, 3] +MAP_SPEED_MODE_LABELS = ["Off", "Display", "Cap", "Follow"] +MAP_SPEED_OFFSETS_MPH = [-5, 0, 5] +MAP_SPEED_LOOKAHEAD = [0, 1, 2, 3] +MAP_SPEED_LOOKAHEAD_LABELS = ["Off", "Late", "Normal", "Early"] +MAP_SPEED_ACCEL = list(range(1, 11)) +MAP_SPEED_ACCEL_LABELS = [str(i) for i in MAP_SPEED_ACCEL] +MAP_SPEED_ACCEL_DEFAULT = 5 +MAP_SPEED_ACCEL_DESCRIPTION = ( + "MAX climb / open-road feel (1 lazy → 10 quicker). " + + "Coming up behind a lead uses the same Accel 1–10 gradient " + + "(including last-mph taper), not a hotter catch-up punch. " + + "Brake to a lower MAX stays Accel 5. Lead still owns follow." +) +ADAPTIVE_ACCEL_DESCRIPTION = ( + "Softer accel near a lead so you don't overshoot. " + + "Open road uses Acceleration 1–10. Coming up behind a lead uses that same Accel gradient, not a full-gap punch." +) +MAP_SPEED_MODE_DESCRIPTION = ( + "OSM posted limit for HUD MAX. Off: no change. Display: LIMIT sign only. " + + "Cap: never exceed. Follow: track the limit. A stalk set " + + "holds until the posted limit changes. Cap/Follow need the pedal." +) +MAP_SPEED_OFFSET_DESCRIPTION = ( + "Added to the OSM limit for Cap/Follow (mph)." +) +MAP_SPEED_LOOKAHEAD_DESCRIPTION = ( + "Ease MAX down for a lower limit ahead. Off: wait until GPS is on that way. " + + "A stalk set holds; lookahead pauses while that set is active. " + + "A higher limit far ahead never raises MAX. Radar lead still outranks map." +) +FOLLOW_DISTANCE_VALUES = list(range(1, 8)) +FOLLOW_DISTANCE_LABELS = [str(i) for i in FOLLOW_DISTANCE_VALUES] +FOLLOW_DISTANCE_DEFAULT = 4 +NAP_HYPERMILE = "NAPHypermile" +NAP_HYPERMILE_STEP_DOWN = "NAPHypermileStepDown" +NAP_HYPERMILE_HILL_CLIMB = "NAPHypermileHillClimb" +NAP_FOLLOW_DISTANCE_CITY = "NAPFollowDistanceCity" +NAP_FOLLOW_DISTANCE_HWY = "NAPFollowDistanceHwy" +FOLLOW_DISTANCE_CITY_DESCRIPTION = ( + "City follow when MAX is under 50 mph. 1 closest, 7 farthest. Behind a " + + "lead, the gap opens gradually to this (ego a bit slower than the lead), " + + "then holds. Traveled speed is used only when MAX is unset. A stalk tip " + + "steps this when MAX is under 50. Not Hypermile." +) +FOLLOW_DISTANCE_HWY_DESCRIPTION = ( + "Highway follow when MAX is 50 mph or higher. 1 closest, 7 farthest. " + + "Behind a lead, the gap creeps toward this. Stays highway while slowing " + + "under a highway MAX. A stalk tip steps this when MAX is 50 or higher, " + + "including while still coming up to that MAX. Not Hypermile." +) +NAP_ONE_PEDAL_LONG = "NAPOnePedalLong" +NAP_GAP_LOCK = "NAPGapLock" +GAP_LOCK_DESCRIPTION = ( + "Default Off. Pedal mode. Hold the engage stalk toward you for 2 seconds " + + "to keep the current radar gap in meters, even if long is paused. A stalk " + + "tip, cancel, brake, or One-Pedal pause returns to Follow Distance. " + + "Another 2 second hold stores a new distance." +) +ONE_PEDAL_LONG_DESCRIPTION = ( + "Default Off. Pedal mode only. With OP long already on, pressing the " + + "accelerator from rest pauses longitudinal — long lets go, lateral " + + "stays, no full disable or take-control. That pause stays until a " + + "stalk SET; lifting the pedal does not resume long. A light tip-in " + + "pauses (slightly more sensitive than a full gasPressed). SET while your " + + "foot is already on the pedal still arms long; lift starts it " + + "(A+B / A3), same as today. After a from-rest pause, lift or " + + "near-zero accel is Tesla regen through interceptor RELEASE. Off = " + + "stock gas override + A+B/A3 resume. Brake that pauses long RELEASEs " + + "immediately to stock Tesla regen." +) +HYPERMILE_DESCRIPTION = ( + "Default Off. Comfort-biased efficiency — early light ease, not max " + + "regen. On snaps Adaptive Accel, Cap/Follow, Early lookahead, and " + + "Accel 1; Off restores. Eco offset is posted-scaled so town 30 stays " + + "30. Follow Distance stays the stock slider. Lead braking stays on." +) +FOLLOW_DISTANCE_DESCRIPTION = ( + "1 closest, 7 farthest. City when MAX is under 50 mph, highway at 50 " + + "or higher (traveled speed only if MAX is unset). Behind a lead the " + + "gap eases between them, not a step. A slower car ahead eases " + + "off farther back (more distance, not a harder brake). Behind a lead, " + + "a stalk tip steps the active 1–7; a full press still steps MAX. " + + "No lead: both still adjust MAX." +) +HYPERMILE_STEP_DOWN_DESCRIPTION = ( + "Default Off. Only while Hypermile is On. Larger posted-scale drop " + + "(0 under 50 mph, −15 at 80). Maps-only; does not invent a drop." +) +HYPERMILE_HILL_CLIMB_DESCRIPTION = ( + "Default On. Only while Hypermile is On. IMU pitch holds grade on " + + "Accel 1 climbs. Never raises MAX. Lead / MPC brake still wins." +) + +NAP_SPEED_SIGN_LOG = "NAPSpeedSignLog" +NAP_DRIVER_LAT_HANDOFF = "NAPDriverLatHandoff" +NAP_LOW_VIS_BACKOFF = "NAPLowVisBackoff" +NAP_CONE_LINE_HOLD = "NAPConeLineHold" +NAP_CONE_LINE_LOG = "NAPConeLineLog" +NAP_OBSTACLE_CHIME = "NAPObstacleChime" +NAP_OBSTACLE_LOG = "NAPObstacleLog" +NAP_DM_SIMULATE_LOOKING = "NAPDmSimulateLooking" +NAP_DM_FALSE_ALERT_IGNORE = "NAPDmFalseAlertIgnore" +NAP_FORCE_OFFROAD = "NAPForceOffroad" +DRIVER_LAT_HANDOFF_DESCRIPTION = ( + "Default On. A light purposeful push frees the wheel. Hands off " + + "~0.15 s, then it blends back. Turn Off if rumble false-yields. " + + "Off = stock lat." +) +LOW_VIS_BACKOFF_DESCRIPTION = ( + "Default On. Shows Low visibility when the model is unsure of the path, " + + "or on sun glare (sun low ahead, or a bright drop while the path is also " + + "unsure). Steering keeps following the path: a gentle limit, reduced only " + + "as far as the model is unsure, never off. Over 45 s it alerts louder. " + + "Longitudinal stays on. A repeated one-sided fight also stays yielded until " + + "the model agrees with the wheel. Off = stock lateral, no Low visibility alert." +) +OBSTACLE_CHIME_DESCRIPTION = ( + "Default On. A short chime when the radar and the camera agree " + + "something solid is in your lane or stepping into it, and when an " + + "animal or a person is near the road. A still mailbox or post on " + + "the shoulder stays quiet. It does not brake, steer, or turn " + + "cruise off. Off stops the chime; the log still runs." +) +CONE_LINE_HOLD_DESCRIPTION = ( + "Default On. After you push the wheel away from a line of cones or " + + "drums for about 1 second, openpilot keeps your line when it takes " + + "the wheel back, instead of steering toward the cones. That offset " + + "eases off once the line has been gone for a few seconds, or if you " + + "steer back. Longitudinal stays on. A hard yank still cancels. " + + "Off = the usual soft-handoff blend." +) +CONE_LINE_LOG_DESCRIPTION = ( + "Default On. Log-only radar cone-line detector (coneLineNAP in the " + + "qlog). Does not steer by itself. Off stops the log; Hold my line " + + "near cones then sees no line." +) +DM_SIMULATE_LOOKING_DESCRIPTION = ( + "Default On. nap-dev experiment. While engaged, after the look-at-road " + + "timer has counted down about 1 s, restore awareness on the stock " + + "attentive path (full soft-reset: no-face, uncertain, phone, pose, " + + "and eye false nags) and hold until gradual recovery returns " + + "awareness to full (not a one-frame pulse). Fire time is random in " + + "the first 3 s of countdown (after 1 s, then within the next 2 s). " + + "Mutually exclusive with False Alert Ignore: turning this On turns " + + "that Off. Not a mute of hard cancels: hands-on ≥ 2, stalk cancel, " + + "door, and reverse still hard-cancel. Always-on DM when not engaged " + + "is unchanged. Turn Off for stock DM." +) +DM_FALSE_ALERT_IGNORE_DESCRIPTION = ( + "Default Off. Use when Simulate Look is Off and you only want false " + + "phone/device distraction (phoneProb) ignored on the same random " + + "1–3 s cadence. Soft-clears only the phone bit so a false device " + + "“Driver Distracted” can recover without a real glance. Head-pose " + + "looking-away and eye tracking still drain and alert — this does " + + "nothing while pose or eye are alarming. Mutually exclusive with " + + "Simulate Look: turning this On turns that Off (and aborts an " + + "in-flight wipe). Hands-on ≥ 2, stalk, door, and reverse still " + + "hard-cancel. Turn Off for stock phone detection." +) +FORCE_OFFROAD_DESCRIPTION = ( + "WARNING: Forces the device offroad and disengages openpilot even while " + "moving. On-road, a big Yes/No asks if you are ready to resume steering " + "control — No leaves assist as it was. Drive manually after Yes — no " + "steering or accel assist while this is on. Unlocks Download US Maps, " + "Refresh maps, software install, and other offroad-only NAP actions. " + "Default Off. Clears when you toggle Off, Reset to Defaults, reboot, or " + "the next time ignition turns on." +) +SPEED_SIGN_LOG_DESCRIPTION = ( + "Log-only MUTCD speed-sign detector on the ROAD camera + GPS. Default Off. " + "When On, speedsignd shows a SIGN plate with Yes/No (only Yes sets a local map speed limit) and may append a short " + "JSONL line under /data/media/0/nap/speed_signs.jsonl (t, lat, lon, bearing, mph, conf). " + "Detect keeps running while openpilot is engaged, at 1 Hz or slower so one " + "little core stays near 25 percent (idle at least 3× the inference). " + "Inference stays on CPU (never the GPU modeld uses). " + "SCHED_IDLE, or nice 19 if that is unavailable, one thread on core 2. " + "It backs off when the CPU is loaded or the driving model / controls report lag. " + "The plate shows the mph while engaged, not WAIT (WAIT was the old pause). " + "Manual driving — moving is OK — uses the same detect. Not gated on park or " + "Force Offroad. OSM upload is future work; this is JSONL + HUD only. " + "If you see TAKE CONTROL or driving-model lag, turn Logger Off and use " + "nap-release. Does not write sqlite, does not change cruise / HUD MAX, " + "and does not query osm.org. Stock modelV2 has no speedSign head. Real " + "roadside detection needs the compact YOLO ONNX on " + "/data/media/0/nap/speed_sign.onnx. If that file is missing, onroad SIGN " + "shows NO WT — use Install weights (Wi-Fi, offroad / Force Offroad), or: " + + "python -m scripts.nap.install_speed_sign_weights. " + + "That button also installs the CPU runtime into /data/media/0/nap/pylib. " + + "If the weights are present and the runtime is not, the plate shows NO RT " + + "and Settings says runtime missing — tap Install weights. " + + "One read at 0.70 or higher on a real limit can light SIGN; a different " + + "limit within 3 s clears it. Detect alternates a lower tile and an upper tile." +) + +INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS = """\ +Install speed-sign ONNX weights and the CPU runtime + +Downloads the published YOLOv8n ONNX (~12 MB) from GitHub Release +speed-sign-onnx-v3 (v2 fallback) / speed_sign.onnx and writes +/data/media/0/nap/speed_sign.onnx (SHA-256 checked). Replaces an older +file at that path. Settings → Speed Sign Weights shows Out of date when +the sha does not match — tap Install weights again. Do not keep the v1 file. + +The same tap downloads pinned onnxruntime 1.31.0 (CPU, cp312, aarch64, +SHA-256 checked) and unzips it into /data/media/0/nap/pylib. It does not +pip-install and does not modify the system venv. speedsignd loads that +directory via sys.path only when the image has no onnxruntime. Until +that import works, Settings says runtime missing — tap Install weights and the onroad plate +shows NO RT. + +Without the ONNX, Speed Sign Logger On still starts speedsignd, but the +onroad SIGN plate shows NO WT and will not read real roadside signs. + +PRECONDITIONS: + 1. Device is offroad / parked (Force Offroad if you are in the car) + 2. Wi-Fi that can reach GitHub Releases and files.pythonhosted.org + 3. ~40 MiB free on /data + +Takes a couple of minutes. speedsignd retries the ONNX onroad without a +reboot. Leave Logger On while disengaged until the first CPU session +finishes (reason=compile-wait while engaged), then engage. That session +is cached per weights sha under /data. A clear MUTCD R2-1 needs two +agreeing reads. Inference stays on CPU: the vendored onnxruntime, never +the GPU. The stock 3X image has neither onnxruntime nor cv2.dnn. + +Does not write sqlite, does not change cruise / HUD MAX, and does not +query osm.org. + +Press START to download.""" + +# Forwarded 0x45 STW_ACTN_RQ wiper / high-beam. Persist 0=Off, 3=Auto +# so flashed cars / logs stay compatible. Legacy Int(1)/On(2) coerce to Off. +WIPER_SPEED_OFF = 0 +WIPER_SPEED_AUTO = 3 +WIPER_SPEED_VALUES = [WIPER_SPEED_OFF, WIPER_SPEED_AUTO] +WIPER_SPEED_LABELS = ["Off", "Auto"] +WIPER_HUD_OFF = "Wipers Off" +WIPER_HUD_AUTO = "Wipers Auto" +WIPER_HUD_DURATION_S = 2.5 +WIPER_SENSITIVITY_VALUES = [0, 1, 2, 3, 4] +WIPER_SENSITIVITY_LABELS = ["Drier", "Dry", "Mid", "Wet", "Wetter"] +WIPER_SENSITIVITY_DEFAULT = 2 +HIGH_LOW_BEAM_VALUES = [0, 1, 2] +HIGH_LOW_BEAM_LABELS = ["Off", "Low", "High"] +WIPER_SPEED_DESCRIPTION = ( + "NAP wipers: Off or Auto. Off leaves the driver's real stalk collar " + "alone. Auto overlays WprSw6Posn INTERVAL1 (collar=1) and " + "WprWashSw_Psd=0 only when the car is on, gear is Drive or Reverse, " + "speed is above a small creep floor, and the 3X road camera sees a " + "rainy or icy/frosted windshield. Hold INTERVAL1 at ~100 Hz (same " + "last-win as high-beam) so live stalk Off (collar=0) cannot cancel. " + "While Auto is selected and dry (or Park/Neutral/standstill), still " + "extra-forward 0x45 rest with collar forced 0 so Pre-AP drops " + "intermittent; a wipe 1→0 sends rest immediately. Park, Neutral, and " + "standstill (v≈0) never Auto-wipe. Default Off — Auto is opt-in, not " + "every drive. Double-flick the wiper collar Off→Int1→Off within 1 s " + "to toggle Auto on or off; the stock stalk stays Off. Sensitivity " + "(Drier→Wetter) sets Auto aggressiveness. DAS wiper fields stay 0 " + "(they were ignored and caused a controls mismatch). Do not engage NAP " + "and do not pull the stalk. No spray. No auto headlights." +) +WIPER_SENSITIVITY_DESCRIPTION = ( + "Auto only. More dry (Drier) ↔ more wet (Wetter). Mid is the baseline. " + "Lower wipes sooner / more often; higher tolerates more film before a " + "repeat wipe. Scales the first-wipe bar, the post-wipe repeat bar, and " + "the light-mist minimum rewipe gap (Drier ~5–8 s, Dry ~8–12 s, Mid " + "~20–25 s). Below acquire, Drier/Dry still fire an occasional thin-mist " + "INTERVAL1 (~18/22 s). Does not spray." +) +HIGH_LOW_BEAM_DESCRIPTION = ( + "Pre-AP Model S only, for on-car testing. Default Off. Low is the same as " + "Off — the stalk's rest 0x45 (00ff00) is low/cancel, so there is no extra " + "nibble to hold. The real stalk continuously sends 00ff04 while high " + "beams are held, not a one-shot press. High matches that: keep sending " + "00ff04 (nibble 4 held) on the live 0x45, same counter, until you turn " + "the setting off, so bus 0 IDLE cannot last-win as a cancel. Off/Low " + "returns the real stalk. Off/Low then High is not a one-shot tap. The " + "extra-forward is the same 0x45, not a second 0x45. No spray. DAS " + "wiper/beam fields stay 0. Car on is enough. Do not send FLASH. No auto " + "headlights." +) + +# Radar lateral offset bounds (meters). Added to radar yRel in +# radar_interface.py. Negative = shift toward left; positive = toward right. +# ~0.27 is typical for the 3D-printed factory-location mount. +RADAR_OFFSET_MIN = -2.0 +RADAR_OFFSET_MAX = 2.0 + + +CALIBRATE_PEDAL_INSTRUCTIONS = """\ +NAP Pedal Calibrator + +This script calibrates the comma pedal interceptor for your pre-AP Tesla Model S. + +PRECONDITIONS: + 1. Car must be ON + 2. Gear must be in NEUTRAL + 3. Brake pedal must be PRESSED and held + 4. Do NOT press the accelerator pedal during calibration + +The calibration process will: + - Detect pedal zero position + - Detect pedal maximum position + - Fine-tune the scale factor + - Validate the calibration values + - Save calibration to params + +Press START when ready to begin calibration.""" + + +CALIBRATE_RADAR_INSTRUCTIONS = """\ +NAP Radar Calibrator + +This script displays filtered radar points to help align the Bosch radar. + +PRECONDITIONS: + 1. Vehicle must be safely parked + 2. Radar must be properly mounted and connected + 3. Place a calibration target 3-10m ahead, centered on the vehicle axis + +The calibration display will show: + - Radar points within 2.5-14.5m ahead + - Lateral offset from center + - Adjust radar aim until target shows ~0.0m lateral + +Press START when ready to begin.""" + + +TEST_RADAR_INSTRUCTIONS = """\ +NAP Radar Test + +This script displays live radar data for testing and verification. + +The test will show: + - All detected radar points + - Distance and relative velocity + - Track status and confidence + +This is useful for: + - Verifying radar installation + - Checking radar alignment + - Debugging radar issues + +Press START to begin the radar test.""" + + +FLASH_EPAS_INSTRUCTIONS = """\ +EPAS Firmware Flash + +STEP 1 — POWER THE CAR ON NOW: + - Key fob inside the car + - Foot on the brake + - Car should be in Park and stay there + - Do not drive + (The EPAS ECU only responds when the car is on.) + +WARNING: This will modify your steering system firmware! + +POWER REQUIREMENTS: + - 12V battery must be healthy and at a normal charge + - Do NOT start the flash if the car has been sitting cold + with marginal voltage + - Power loss DURING the flash will brick the EPAS module + +RISKS: + - Incorrect firmware can disable power steering + - Interrupted flash can brick the EPAS module + - This modification may void warranties + +Only proceed if you: + - Fully understand the implications + - Have backup EPAS firmware available + - Are comfortable with the risks involved + +Press START only if you accept these risks.""" + + +BACKUP_EPAS_INSTRUCTIONS = """\ +EPAS Firmware Backup + +STEP 1 — POWER THE CAR ON NOW: + - Key fob inside the car + - Foot on the brake + - Car should be in Park and stay there + - Do not drive + (The EPAS ECU only responds when the car is on. If the car + is not on, the script will time out.) + +This action only reads the stock EPAS firmware and saves it. +No flashing or firmware modifications are performed. + +Run this before any Flash operation so you have a local backup. + +PRECONDITIONS: + - Stable 12V power + - Do not power-cycle during extraction + +Press START to extract the EPAS firmware backup.""" + + +RESTORE_EPAS_INSTRUCTIONS = """\ +EPAS Firmware Restore + +STEP 1 — POWER THE CAR ON NOW: + - Key fob inside the car + - Foot on the brake + - Car should be in Park and stay there + - Do not drive + (The EPAS ECU only responds when the car is on.) + +WARNING: This will reflash your steering system firmware! + +POWER REQUIREMENTS: + - 12V battery must be healthy and at a normal charge + - Do NOT start the restore if the car has been sitting cold + with marginal voltage + - Power loss DURING the restore will brick the EPAS module + +This operation: + - Uses the extracted stock EPAS firmware image + - May take several minutes to complete + - Should NOT be interrupted once started + +RISKS: + - Interrupted flash can brick the EPAS module + - Incorrect image can disable power steering + +Only proceed if you: + - Need to return to stock EPAS firmware + - Understand and accept the risks + +Press START only if you accept these risks.""" + + +DOWNLOAD_US_MAPS_INSTRUCTIONS = """\ +Download US OSM speed-limit maps + +Fetches a prebuilt sqlite of OpenStreetMap maxspeed ways for the United States +and installs it at /data/media/0/osm/speed_limits.sqlite. + +This is the first-install of the full published US pack (not Overpass). +Not stored in git (too large). After flash, run this once over Wi-Fi. + +PRECONDITIONS: + 1. Device is offroad / parked + 2. Wi-Fi that can reach GitHub Releases + 3. 850 MiB free on /data (same filesystem as /data/media/0/osm/) + ~200 MiB zst + ~541 MiB sqlite + 80 MiB margin. Stages in + /data/media/0/osm/.download/ — not /tmp. + +If a previous download died with ENOSPC / "No space left on device": + rm -f /data/media/0/osm/*.partial /data/media/0/osm/.download/* + then clear old routes/videos if df -h /data is still short. + +Takes a few minutes. mapd reloads onroad within ~15 seconds — no reboot. + +For later local updates use Refresh maps (live OSM within 100 miles). + +Data is (c) OpenStreetMap contributors (ODbL). +https://www.openstreetmap.org/copyright + +Press START to download.""" + + +REFRESH_MAPS_INSTRUCTIONS = """\ +Query live OSM within 100 miles and merge into the US pack + +Queries live OpenStreetMap speed limits within 100 miles (~160.9 km) of +this car and merges them into the installed US maps. Ways in that radius +are replaced; the rest of the US pack is kept. Tagged OSM maxspeed wins. +In Minnesota, unmarked roads also get statutory estimates (not uploaded +to OSM) so Refresh maps does not wipe those pack fills. + +Uses a GNSS fix if one arrives (waits up to 10s), otherwise last stored GPS. +Will not guess a city. If maps are not installed yet, downloads the US pack +first and then overlays the 100-mile extract -- never a 100-mile-only file. + +PRECONDITIONS: + 1. Device is offroad / parked + 2. Wi-Fi that can reach Overpass (overpass-api.de) + 3. GPS: wait for a satellite fix, or start openpilot onroad until the GPS + icon/fix is up for about a minute, then retry + 4. Stages the merge on /data/media/0/osm/.download/ -- not /tmp. + A previous good sqlite is kept if OSM times out or the merge fails. + +Overpass can take several minutes. mapd reloads onroad within ~15s -- +no reboot. + +Data is (c) OpenStreetMap contributors (ODbL). +https://www.openstreetmap.org/copyright + +Press START to refresh.""" + + +ACKNOWLEDGMENTS_INTRO = "Special thanks to the following members. This project wouldn't be possible without you:" + +ACKNOWLEDGMENTS_NAMES = [ + "Boggyver and the Tinkla Project", + "Lukas Loetkolben", + "Johnmr1", + "SeriouslySerious", + "Pod042", + "1FrostlySlime", +] + + +def acknowledgments_html() -> str: + """Render the acknowledgments block as HTML for HtmlRenderer.""" + names_html = "
".join(f"{n}" for n in ACKNOWLEDGMENTS_NAMES) + return f"

{ACKNOWLEDGMENTS_INTRO}

{names_html}

" + + +def acknowledgments_text() -> str: + """Render the acknowledgments block as plain text.""" + bullets = "\n".join(f" {n}" for n in ACKNOWLEDGMENTS_NAMES) + return f"{ACKNOWLEDGMENTS_INTRO}\n\n{bullets}" + + +def find_preset_index(presets: list, value, default: int = 0) -> int: + """Find the closest matching preset index for a given value.""" + try: + return presets.index(value) + except ValueError: + return min(range(len(presets)), key=lambda i: abs(presets[i] - value)) + + +def normalize_wiper_speed(setting) -> int: + """UI/runtime Off or Auto. Legacy Int(1)/On(2) and unknowns are Off.""" + try: + if int(setting) == WIPER_SPEED_AUTO: + return WIPER_SPEED_AUTO + except (TypeError, ValueError): + pass + return WIPER_SPEED_OFF + + +def wiper_speed_button_index(setting) -> int: + """Index into WIPER_SPEED_VALUES / LABELS (Off=0, Auto=1).""" + return 1 if normalize_wiper_speed(setting) == WIPER_SPEED_AUTO else 0 + + +def wiper_hud_text(setting) -> str: + return WIPER_HUD_AUTO if normalize_wiper_speed(setting) == WIPER_SPEED_AUTO else WIPER_HUD_OFF + + +def coerce_wiper_speed_param(params) -> int: + """Read NAPWiperSpeed, treat Int/On as Off, and persist the coercion.""" + try: + raw = params.get("NAPWiperSpeed", return_default=True) + setting = 0 if raw is None or raw == "" else int(raw) + except (TypeError, ValueError, AttributeError): + setting = 0 + norm = normalize_wiper_speed(setting) + if norm != setting: + try: + params.put("NAPWiperSpeed", norm) + except Exception: + pass + return norm diff --git a/selfdrive/ui/layouts/settings/nap_lateral.py b/selfdrive/ui/layouts/settings/nap_lateral.py new file mode 100644 index 00000000000000..a964b5920a480b --- /dev/null +++ b/selfdrive/ui/layouts/settings/nap_lateral.py @@ -0,0 +1,64 @@ +"""NAP Lateral Control settings content (turn geometry correction).""" +from openpilot.selfdrive.controls.lib.lat_turn_geometry import ( + PARAM_REF_OFFSET, PARAM_TURN_GEOMETRY, PARAM_TURN_IN_DELAY, REF_OFFSET_DEFAULT_M, + TURN_IN_STEP_MAX, TURN_IN_STEP_MIN, clamp_turn_in_step, +) + +NAP_LAT_TURN_GEOM = PARAM_TURN_GEOMETRY +NAP_LAT_REF_OFFSET = PARAM_REF_OFFSET +NAP_TURN_IN_DELAY = PARAM_TURN_IN_DELAY +TURN_IN_DELAY_STEPS = list(range(TURN_IN_STEP_MIN, TURN_IN_STEP_MAX + 1)) +TURN_IN_DELAY_LABELS = [f"{v:+d}" if v else "0" for v in TURN_IN_DELAY_STEPS] +LAT_REF_OFFSET_PRESETS = [0.0, 0.2, 0.35, 0.5, 0.75, 1.0] +LAT_REF_OFFSET_LABELS = ["0", "0.2", "0.35", "0.5", "0.75", "1.0"] +LAT_REF_OFFSET_DEFAULT = REF_OFFSET_DEFAULT_M +LAT_TURN_GEOM_DESCRIPTION = ( + "Default On. Pre-AP. Aims the steering at the right point of the path " + + "in turns: uses the measured low-speed steering lag and steers from " + + "the rear axle, so turns start later and stop clipping corners. " + + "Highway is unchanged. Also turns off the old roundabout outer bias. " + + "Off = previous behavior." +) +NAP_ROUNDABOUT_ASSIST = "NAPRoundaboutAssist" # roundabout_guide.PARAM_ROUNDABOUT_ASSIST +ROUNDABOUT_ASSIST_DESCRIPTION = ( + "Default Off. Pre-AP, experimental. Near a roundabout that is in the map " + + "data, blends the steering toward the circle using GPS: keeps the right " + + "entry until ~9 m out, then turns left smoothly and follows the lane " + + "around. GPS is ~1-3 m off, so the camera still limits it at lane lines " + + "and curbs, and it backs off when GPS looks poor. Wheel torque takes over " + + "as usual. Needs Settings > NAP > Map Speed Limit > Refresh maps (or map " + + "pack v4) so the ring is mapped. Off = model only." +) +LAT_REF_OFFSET_DESCRIPTION = ( + "Rear reference offset (m). How much later turn-in is anchored in space. " + + "0.35 matches the Model S camera-to-axle difference. Higher = later turn-in." +) + + +TURN_IN_DELAY_DESCRIPTION = ( + "Turn-in timing at low speed (about 3-8 mph, fading out by 10 mph). 0 = " + + "current behavior. + steps start the turn later, - steps earlier. Each " + + "step is 30 ms: about 7-11 cm of travel at 5-8 mph. Needs Turn Geometry " + + "Correction On. Highway is never affected." +) + + +def turn_in_delay_index(params) -> int: + try: + step = clamp_turn_in_step(params.get(NAP_TURN_IN_DELAY, return_default=True)) + except Exception: + step = 0 + return TURN_IN_DELAY_STEPS.index(step) + + +def lat_ref_offset_value(params) -> float: + try: + raw = params.get(NAP_LAT_REF_OFFSET, return_default=True) + return LAT_REF_OFFSET_DEFAULT if raw is None else float(raw) + except (TypeError, ValueError, AttributeError): + return LAT_REF_OFFSET_DEFAULT + + +def lat_ref_offset_index(params) -> int: + v = lat_ref_offset_value(params) + return min(range(len(LAT_REF_OFFSET_PRESETS)), key=lambda i: abs(LAT_REF_OFFSET_PRESETS[i] - v)) diff --git a/selfdrive/ui/layouts/settings/settings.py b/selfdrive/ui/layouts/settings/settings.py new file mode 100644 index 00000000000000..17ea054efa3b09 --- /dev/null +++ b/selfdrive/ui/layouts/settings/settings.py @@ -0,0 +1,219 @@ +import time +import pyray as rl +from dataclasses import dataclass +from enum import IntEnum +from collections.abc import Callable +from openpilot.selfdrive.ui.layouts.settings.developer import DeveloperLayout +from openpilot.selfdrive.ui.layouts.settings.device import DeviceLayout +from openpilot.selfdrive.ui.layouts.settings.firehose import FirehoseLayout +from openpilot.selfdrive.ui.layouts.settings.hidden_toggles import HiddenTogglesPopup +from openpilot.selfdrive.ui.layouts.settings.nap import NAPLayout +from openpilot.selfdrive.ui.layouts.settings.software import SoftwareLayout +from openpilot.selfdrive.ui.layouts.settings.toggles import TogglesLayout +from openpilot.selfdrive.ui.layouts.settings.triple_tap import TripleTapDetector +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wifi_manager import WifiManager +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.network import NetworkUI + +# Constants +SIDEBAR_WIDTH = 500 +CLOSE_BTN_SIZE = 200 +CLOSE_ICON_SIZE = 70 +NAV_BTN_HEIGHT = 110 +PANEL_MARGIN = 50 + +# Colors +SIDEBAR_COLOR = rl.BLACK +PANEL_COLOR = rl.Color(41, 41, 41, 255) +CLOSE_BTN_COLOR = rl.Color(41, 41, 41, 255) +CLOSE_BTN_PRESSED = rl.Color(59, 59, 59, 255) +TEXT_NORMAL = rl.Color(128, 128, 128, 255) +TEXT_SELECTED = rl.WHITE + + +class PanelType(IntEnum): + DEVICE = 0 + NETWORK = 1 + TOGGLES = 2 + SOFTWARE = 3 + NAP = 4 + FIREHOSE = 5 + DEVELOPER = 6 + + +@dataclass +class PanelInfo: + name: str + instance: Widget + button_rect: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) + + +class SettingsLayout(Widget): + def __init__(self): + super().__init__() + self._current_panel = PanelType.DEVICE + + # Panel configuration + wifi_manager = WifiManager() + wifi_manager.set_active(False) + + self._panels = { + PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayout()), + PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUI(wifi_manager)), + PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout()), + PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayout()), + PanelType.NAP: PanelInfo(tr_noop("NAP"), NAPLayout()), + PanelType.FIREHOSE: PanelInfo(tr_noop("Firehose"), FirehoseLayout()), + PanelType.DEVELOPER: PanelInfo(tr_noop("Developer"), DeveloperLayout()), + } + + self._font_medium = gui_app.font(FontWeight.MEDIUM) + self._close_icon = gui_app.texture("icons/close2.png", CLOSE_ICON_SIZE, CLOSE_ICON_SIZE) + + # Hidden NAP toggles: 3 taps on the NAP sidebar item within 1.0 s. + # Counted here (not only in set_current_panel) so re-taps while already + # on NAP still count. + self._nap_triple_tap = TripleTapDetector() + self._hidden_popup_visible = False + self._hidden_popup = HiddenTogglesPopup(on_dismiss=self._dismiss_hidden_popup) + self._hidden_popup.set_visible(False) + + # Callbacks + self._close_callback: Callable | None = None + + def set_callbacks(self, on_close: Callable): + self._close_callback = on_close + + def _render(self, rect: rl.Rectangle): + # Calculate layout + sidebar_rect = rl.Rectangle(rect.x, rect.y, SIDEBAR_WIDTH, rect.height) + panel_rect = rl.Rectangle(rect.x + SIDEBAR_WIDTH, rect.y, rect.width - SIDEBAR_WIDTH, rect.height) + + # Draw components + self._draw_sidebar(sidebar_rect) + self._draw_current_panel(panel_rect) + + def _draw_sidebar(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, SIDEBAR_COLOR) + + # Close button + close_btn_rect = rl.Rectangle( + rect.x + (rect.width - CLOSE_BTN_SIZE) / 2, rect.y + 60, CLOSE_BTN_SIZE, CLOSE_BTN_SIZE + ) + + pressed = (rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) and + rl.check_collision_point_rec(rl.get_mouse_position(), close_btn_rect)) + close_color = CLOSE_BTN_PRESSED if pressed else CLOSE_BTN_COLOR + rl.draw_rectangle_rounded(close_btn_rect, 1.0, 20, close_color) + + icon_color = rl.Color(255, 255, 255, 255) if not pressed else rl.Color(220, 220, 220, 255) + icon_dest = rl.Rectangle( + close_btn_rect.x + (close_btn_rect.width - self._close_icon.width) / 2, + close_btn_rect.y + (close_btn_rect.height - self._close_icon.height) / 2, + self._close_icon.width, + self._close_icon.height, + ) + rl.draw_texture_pro( + self._close_icon, + rl.Rectangle(0, 0, self._close_icon.width, self._close_icon.height), + icon_dest, + rl.Vector2(0, 0), + 0, + icon_color, + ) + + # Store close button rect for click detection + self._close_btn_rect = close_btn_rect + + # Navigation buttons + y = rect.y + 300 + for panel_type, panel_info in self._panels.items(): + button_rect = rl.Rectangle(rect.x + 50, y, rect.width - 150, NAV_BTN_HEIGHT) + + # Button styling + is_selected = panel_type == self._current_panel + text_color = TEXT_SELECTED if is_selected else TEXT_NORMAL + # Draw button text (right-aligned) + panel_name = tr(panel_info.name) + text_size = measure_text_cached(self._font_medium, panel_name, 65) + text_pos = rl.Vector2( + button_rect.x + button_rect.width - text_size.x, button_rect.y + (button_rect.height - text_size.y) / 2 + ) + rl.draw_text_ex(self._font_medium, panel_name, text_pos, 65, 0, text_color) + + # Store button rect for click detection + panel_info.button_rect = button_rect + + y += NAV_BTN_HEIGHT + + def _draw_current_panel(self, rect: rl.Rectangle): + rl.draw_rectangle_rounded( + rl.Rectangle(rect.x + 10, rect.y + 10, rect.width - 20, rect.height - 20), 0.04, 30, PANEL_COLOR + ) + content_rect = rl.Rectangle(rect.x + PANEL_MARGIN, rect.y + 25, rect.width - (PANEL_MARGIN * 2), rect.height - 50) + # rl.draw_rectangle_rounded(content_rect, 0.03, 30, PANEL_COLOR) + if self._hidden_popup_visible: + # Skip the live panel so click-outside cannot hit list items underneath. + self._hidden_popup.render(rect) + return + panel = self._panels[self._current_panel] + if panel.instance: + panel.instance.render(content_rect) + + def _handle_mouse_release(self, mouse_pos: MousePos) -> None: + # Check close button + if rl.check_collision_point_rec(mouse_pos, self._close_btn_rect): + self._dismiss_hidden_popup() + if self._close_callback: + self._close_callback() + return + + # Check navigation buttons + for panel_type, panel_info in self._panels.items(): + if rl.check_collision_point_rec(mouse_pos, panel_info.button_rect): + if panel_type == PanelType.NAP: + self._on_nap_sidebar_tap() + else: + self._nap_triple_tap.reset() + self._dismiss_hidden_popup() + self.set_current_panel(panel_type) + return + + def _on_nap_sidebar_tap(self): + # Tap NAP again while the popup is open: dismiss, do not immediately re-open. + if self._hidden_popup_visible: + self._dismiss_hidden_popup() + self._nap_triple_tap.reset() + return + if self._nap_triple_tap.tap(time.monotonic()): + self._show_hidden_popup() + + def _show_hidden_popup(self): + self._hidden_popup_visible = True + self._hidden_popup.set_visible(True) + self._hidden_popup.show_event() + + def _dismiss_hidden_popup(self): + if not self._hidden_popup_visible: + return + self._hidden_popup_visible = False + self._hidden_popup.set_visible(False) + + def set_current_panel(self, panel_type: PanelType): + if panel_type != self._current_panel: + self._panels[self._current_panel].instance.hide_event() + self._current_panel = panel_type + self._panels[self._current_panel].instance.show_event() + + def show_event(self): + super().show_event() + self._panels[self._current_panel].instance.show_event() + + def hide_event(self): + super().hide_event() + self._dismiss_hidden_popup() + self._nap_triple_tap.reset() + self._panels[self._current_panel].instance.hide_event() diff --git a/selfdrive/ui/layouts/settings/software.py b/selfdrive/ui/layouts/settings/software.py new file mode 100644 index 00000000000000..3bf271052d270d --- /dev/null +++ b/selfdrive/ui/layouts/settings/software.py @@ -0,0 +1,204 @@ +import os +import time +import datetime +from openpilot.common.time_helpers import system_time_valid +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr, trn +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.list_view import button_item, text_item, ListItem +from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog +from openpilot.system.ui.widgets.scroller_tici import Scroller + +# TODO: remove this. updater fails to respond on startup if time is not correct +UPDATED_TIMEOUT = 10 # seconds to wait for updated to respond + +# Mapping updater internal states to translated display strings +STATE_TO_DISPLAY_TEXT = { + "checking...": tr("checking..."), + "downloading...": tr("downloading..."), + "finalizing update...": tr("finalizing update..."), +} + + +def time_ago(date: datetime.datetime | None) -> str: + if not date: + return tr("never") + + if not system_time_valid(): + return date.strftime("%a %b %d %Y") + + now = datetime.datetime.now(datetime.UTC) + if date.tzinfo is None: + date = date.replace(tzinfo=datetime.UTC) + + diff_seconds = int((now - date).total_seconds()) + if diff_seconds < 60: + return tr("now") + if diff_seconds < 3600: + m = diff_seconds // 60 + return trn("{} minute ago", "{} minutes ago", m).format(m) + if diff_seconds < 86400: + h = diff_seconds // 3600 + return trn("{} hour ago", "{} hours ago", h).format(h) + if diff_seconds < 604800: + d = diff_seconds // 86400 + return trn("{} day ago", "{} days ago", d).format(d) + return date.strftime("%a %b %d %Y") + + +class SoftwareLayout(Widget): + def __init__(self): + super().__init__() + + self._onroad_label = ListItem(lambda: tr("Updates are only downloaded while the car is off.")) + self._version_item = text_item(lambda: tr("Current Version"), ui_state.params.get("UpdaterCurrentDescription") or "") + self._download_btn = button_item(lambda: tr("Download"), lambda: tr("CHECK"), callback=self._on_download_update) + + # Install button is initially hidden + self._install_btn = button_item(lambda: tr("Install Update"), lambda: tr("INSTALL"), callback=self._on_install_update) + self._install_btn.set_visible(False) + + # Track waiting-for-updater transition to avoid brief re-enable while still idle + self._waiting_for_updater = False + self._waiting_start_ts: float = 0.0 + + # Branch switcher + self._branch_btn = button_item(lambda: tr("Target Branch"), lambda: tr("SELECT"), callback=self._on_select_branch) + self._branch_btn.set_visible(not ui_state.params.get_bool("IsTestedBranch")) + self._branch_btn.action_item.set_value(ui_state.params.get("UpdaterTargetBranch") or "") + self._branch_dialog: MultiOptionDialog | None = None + + self._scroller = Scroller([ + self._onroad_label, + self._version_item, + self._download_btn, + self._install_btn, + self._branch_btn, + button_item(lambda: tr("Uninstall"), lambda: tr("UNINSTALL"), callback=self._on_uninstall), + ], line_separator=True, spacing=0) + + def show_event(self): + super().show_event() + self._scroller.show_event() + + def _render(self, rect): + self._scroller.render(rect) + + def _update_state(self): + # Show/hide onroad warning + self._onroad_label.set_visible(ui_state.is_onroad()) + + # Update current version and release notes + current_desc = ui_state.params.get("UpdaterCurrentDescription") or "" + current_release_notes = (ui_state.params.get("UpdaterCurrentReleaseNotes") or b"").decode("utf-8", "replace") + self._version_item.action_item.set_text(current_desc) + self._version_item.set_description(current_release_notes) + + # Update download button visibility and state + self._download_btn.set_visible(ui_state.is_offroad()) + + updater_state = ui_state.params.get("UpdaterState") or "idle" + failed_count = ui_state.params.get("UpdateFailedCount") or 0 + fetch_available = ui_state.params.get_bool("UpdaterFetchAvailable") + update_available = ui_state.params.get_bool("UpdateAvailable") + + if updater_state != "idle": + # Updater responded + self._waiting_for_updater = False + self._download_btn.action_item.set_enabled(False) + # Use the mapping, with a fallback to the original state string + display_text = STATE_TO_DISPLAY_TEXT.get(updater_state, updater_state) + self._download_btn.action_item.set_value(display_text) + else: + if failed_count > 0: + self._download_btn.action_item.set_value(tr("failed to check for update")) + self._download_btn.action_item.set_text(tr("CHECK")) + elif fetch_available: + self._download_btn.action_item.set_value(tr("update available")) + self._download_btn.action_item.set_text(tr("DOWNLOAD")) + else: + last_update = ui_state.params.get("LastUpdateTime") + if last_update: + formatted = time_ago(last_update) + self._download_btn.action_item.set_value(tr("up to date, last checked {}").format(formatted)) + else: + self._download_btn.action_item.set_value(tr("up to date, last checked never")) + self._download_btn.action_item.set_text(tr("CHECK")) + + # If we've been waiting too long without a state change, reset state + if self._waiting_for_updater and (time.monotonic() - self._waiting_start_ts > UPDATED_TIMEOUT): + self._waiting_for_updater = False + + # Only enable if we're not waiting for updater to flip out of idle + self._download_btn.action_item.set_enabled(not self._waiting_for_updater) + + # Update target branch button value + current_branch = ui_state.params.get("UpdaterTargetBranch") or "" + self._branch_btn.action_item.set_value(current_branch) + + # Update install button + self._install_btn.set_visible(ui_state.is_offroad() and update_available) + if update_available: + new_desc = ui_state.params.get("UpdaterNewDescription") or "" + new_release_notes = (ui_state.params.get("UpdaterNewReleaseNotes") or b"").decode("utf-8", "replace") + self._install_btn.action_item.set_text(tr("INSTALL")) + self._install_btn.action_item.set_value(new_desc) + self._install_btn.set_description(new_release_notes) + # Enable install button for testing (like Qt showEvent) + self._install_btn.action_item.set_enabled(True) + else: + self._install_btn.set_visible(False) + + def _on_download_update(self): + # Check if we should start checking or start downloading + self._download_btn.action_item.set_enabled(False) + if self._download_btn.action_item.text == tr("CHECK"): + # Start checking for updates + self._waiting_for_updater = True + self._waiting_start_ts = time.monotonic() + os.system("pkill -SIGUSR1 -f system.updated.updated") + else: + # Start downloading + self._waiting_for_updater = True + self._waiting_start_ts = time.monotonic() + os.system("pkill -SIGHUP -f system.updated.updated") + + def _on_uninstall(self): + def handle_uninstall_confirmation(result: DialogResult): + if result == DialogResult.CONFIRM: + ui_state.params.put_bool("DoUninstall", True, block=True) + + dialog = ConfirmDialog(tr("Are you sure you want to uninstall?"), tr("Uninstall"), callback=handle_uninstall_confirmation) + gui_app.push_widget(dialog) + + def _on_install_update(self): + # Trigger reboot to install update + self._install_btn.action_item.set_enabled(False) + ui_state.params.put_bool("DoReboot", True, block=True) + + def _on_select_branch(self): + # Get available branches and order + current_git_branch = ui_state.params.get("GitBranch") or "" + branches_str = ui_state.params.get("UpdaterAvailableBranches") or "" + branches = [b for b in branches_str.split(",") if b] + + for b in [current_git_branch, "devel-staging", "devel", "nightly", "nightly-dev", "master"]: + if b in branches: + branches.remove(b) + branches.insert(0, b) + + current_target = ui_state.params.get("UpdaterTargetBranch") or "" + + def handle_selection(result: DialogResult): + # Confirmed selection + if result == DialogResult.CONFIRM and self._branch_dialog is not None and self._branch_dialog.selection: + selection = self._branch_dialog.selection + ui_state.params.put("UpdaterTargetBranch", selection, block=True) + self._branch_btn.action_item.set_value(selection) + os.system("pkill -SIGUSR1 -f system.updated.updated") + self._branch_dialog = None + + self._branch_dialog = MultiOptionDialog(tr("Select a branch"), branches, current_target, callback=handle_selection) + gui_app.push_widget(self._branch_dialog) diff --git a/selfdrive/ui/layouts/settings/toggles.py b/selfdrive/ui/layouts/settings/toggles.py new file mode 100644 index 00000000000000..f342175a82ce1d --- /dev/null +++ b/selfdrive/ui/layouts/settings/toggles.py @@ -0,0 +1,245 @@ +from cereal import log +from openpilot.common.params import Params, UnknownKeyName +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.list_view import multiple_button_item, toggle_item +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.widgets import DialogResult +from openpilot.selfdrive.ui.ui_state import ui_state + +PERSONALITY_TO_INT = log.LongitudinalPersonality.schema.enumerants + +# Description constants +DESCRIPTIONS = { + "OpenpilotEnabledToggle": tr_noop( + "Use the openpilot system for adaptive cruise control and lane keep driver assistance. " + + "Your attention is required at all times to use this feature." + ), + "DisengageOnAccelerator": tr_noop("When enabled, pressing the accelerator pedal will disengage openpilot."), + "LongitudinalPersonality": tr_noop( + "Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. " + + "In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " + + "your steering wheel distance button." + ), + "IsLdwEnabled": tr_noop( + "Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line " + + "without a turn signal activated while driving over 31 mph (50 km/h)." + ), + "AlwaysOnDM": tr_noop("Enable driver monitoring even when openpilot is not engaged."), + 'RecordFront': tr_noop("Upload data from the driver facing camera and help improve the driver monitoring algorithm."), + "IsMetric": tr_noop("Display speed in km/h instead of mph."), + "RecordAudio": tr_noop("Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect."), +} + + +class TogglesLayout(Widget): + def __init__(self): + super().__init__() + self._params = Params() + self._is_release = self._params.get_bool("IsReleaseBranch") + + # param, title, desc, icon, needs_restart + self._toggle_defs = { + "OpenpilotEnabledToggle": ( + lambda: tr("Enable openpilot"), + DESCRIPTIONS["OpenpilotEnabledToggle"], + "chffr_wheel.png", + True, + ), + "ExperimentalMode": ( + lambda: tr("Experimental Mode"), + "", + "experimental_white.png", + False, + ), + "DisengageOnAccelerator": ( + lambda: tr("Disengage on Accelerator Pedal"), + DESCRIPTIONS["DisengageOnAccelerator"], + "disengage_on_accelerator.png", + False, + ), + "IsLdwEnabled": ( + lambda: tr("Enable Lane Departure Warnings"), + DESCRIPTIONS["IsLdwEnabled"], + "warning.png", + False, + ), + "AlwaysOnDM": ( + lambda: tr("Always-On Driver Monitoring"), + DESCRIPTIONS["AlwaysOnDM"], + "monitoring.png", + False, + ), + "RecordFront": ( + lambda: tr("Record and Upload Driver Camera"), + DESCRIPTIONS["RecordFront"], + "monitoring.png", + True, + ), + "RecordAudio": ( + lambda: tr("Record and Upload Microphone Audio"), + DESCRIPTIONS["RecordAudio"], + "microphone.png", + True, + ), + "IsMetric": ( + lambda: tr("Use Metric System"), + DESCRIPTIONS["IsMetric"], + "metric.png", + False, + ), + } + + self._long_personality_setting = multiple_button_item( + lambda: tr("Driving Personality"), + lambda: tr(DESCRIPTIONS["LongitudinalPersonality"]), + buttons=[lambda: tr("Aggressive"), lambda: tr("Standard"), lambda: tr("Relaxed")], + button_width=255, + callback=self._set_longitudinal_personality, + selected_index=self._params.get("LongitudinalPersonality", return_default=True), + icon="speed_limit.png" + ) + + self._toggles = {} + self._locked_toggles = set() + for param, (title, desc, icon, needs_restart) in self._toggle_defs.items(): + toggle = toggle_item( + title, + desc, + self._params.get_bool(param), + callback=lambda state, p=param: self._toggle_callback(state, p), + icon=icon, + ) + + try: + locked = self._params.get_bool(param + "Lock") + except UnknownKeyName: + locked = False + toggle.action_item.set_enabled(not locked) + + # Make description callable for live translation + additional_desc = "" + if needs_restart and not locked: + additional_desc = tr("Changing this setting will restart openpilot if the car is powered on.") + toggle.set_description(lambda og_desc=toggle.description, add_desc=additional_desc: tr(og_desc) + (" " + tr(add_desc) if add_desc else "")) + + # track for engaged state updates + if locked: + self._locked_toggles.add(param) + + self._toggles[param] = toggle + + # insert longitudinal personality after NDOG toggle + if param == "DisengageOnAccelerator": + self._toggles["LongitudinalPersonality"] = self._long_personality_setting + + self._update_experimental_mode_icon() + self._scroller = Scroller(list(self._toggles.values()), line_separator=True, spacing=0) + + ui_state.add_engaged_transition_callback(self._update_toggles) + + def _update_state(self): + if ui_state.sm.updated["selfdriveState"]: + personality = PERSONALITY_TO_INT[ui_state.sm["selfdriveState"].personality] + if personality != ui_state.personality and ui_state.started: + self._long_personality_setting.action_item.set_selected_button(personality) + ui_state.personality = personality + + def show_event(self): + super().show_event() + self._scroller.show_event() + self._update_toggles() + + def _update_toggles(self): + ui_state.update_params() + + e2e_description = tr( + "openpilot defaults to driving in chill mode. Experimental mode enables alpha-level features that aren't ready for chill mode. " + + "Experimental features are listed below:
" + + "

End-to-End Longitudinal Control


" + + "Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. " + + "Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; " + + "mistakes should be expected.
" + + "

New Driving Visualization


" + + "The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. " + + "The Experimental mode logo will also be shown in the top right corner." + ) + + if ui_state.CP is not None: + if ui_state.has_longitudinal_control: + self._toggles["ExperimentalMode"].action_item.set_enabled(True) + self._toggles["ExperimentalMode"].set_description(e2e_description) + self._long_personality_setting.action_item.set_enabled(True) + else: + # no long for now + self._toggles["ExperimentalMode"].action_item.set_enabled(False) + self._toggles["ExperimentalMode"].action_item.set_state(False) + self._long_personality_setting.action_item.set_enabled(False) + self._params.remove("ExperimentalMode") + + unavailable = tr("Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control.") + + long_desc = unavailable + " " + tr("openpilot longitudinal control may come in a future update.") + if ui_state.CP.alphaLongitudinalAvailable: + if self._is_release: + long_desc = unavailable + " " + tr("An alpha version of openpilot longitudinal control can be tested, along with " + + "Experimental mode, on non-release branches.") + else: + long_desc = tr("Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode.") + + self._toggles["ExperimentalMode"].set_description("" + long_desc + "

" + e2e_description) + else: + self._toggles["ExperimentalMode"].set_description(e2e_description) + + self._update_experimental_mode_icon() + + # TODO: make a param control list item so we don't need to manage internal state as much here + # refresh toggles from params to mirror external changes + for param in self._toggle_defs: + self._toggles[param].action_item.set_state(self._params.get_bool(param)) + + # these toggles need restart, block while engaged + for toggle_def in self._toggle_defs: + if self._toggle_defs[toggle_def][3] and toggle_def not in self._locked_toggles: + self._toggles[toggle_def].action_item.set_enabled(not ui_state.engaged) + + def _render(self, rect): + self._scroller.render(rect) + + def _update_experimental_mode_icon(self): + icon = "experimental.png" if self._toggles["ExperimentalMode"].action_item.get_state() else "experimental_white.png" + self._toggles["ExperimentalMode"].set_icon(icon) + + def _handle_experimental_mode_toggle(self, state: bool): + confirmed = self._params.get_bool("ExperimentalModeConfirmed") + if state and not confirmed: + def confirm_callback(result: DialogResult): + if result == DialogResult.CONFIRM: + self._params.put_bool("ExperimentalMode", True, block=True) + self._params.put_bool("ExperimentalModeConfirmed", True, block=True) + else: + self._toggles["ExperimentalMode"].action_item.set_state(False) + self._update_experimental_mode_icon() + + # show confirmation dialog + content = (f"

{self._toggles['ExperimentalMode'].title}


" + + f"

{self._toggles['ExperimentalMode'].description}

") + dlg = ConfirmDialog(content, tr("Enable"), rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + else: + self._update_experimental_mode_icon() + self._params.put_bool("ExperimentalMode", state, block=True) + + def _toggle_callback(self, state: bool, param: str): + if param == "ExperimentalMode": + self._handle_experimental_mode_toggle(state) + return + + self._params.put_bool(param, state, block=True) + if self._toggle_defs[param][3]: + self._params.put_bool("OnroadCycleRequested", True, block=True) + + def _set_longitudinal_personality(self, button_index: int): + self._params.put("LongitudinalPersonality", button_index, block=True) diff --git a/selfdrive/ui/layouts/settings/triple_tap.py b/selfdrive/ui/layouts/settings/triple_tap.py new file mode 100644 index 00000000000000..74ea0ca92a1c9f --- /dev/null +++ b/selfdrive/ui/layouts/settings/triple_tap.py @@ -0,0 +1,58 @@ +"""Triple-tap detector for the hidden NAP settings popup. + +Gesture +------- +A **sliding window** of 3 taps within ``WINDOW_S`` (1.0 s): the newest tap +counts if at least two earlier taps also fall in ``[now - 1.0, now]``. +Re-taps on NAP while already on the NAP panel still count — TICI records +them in ``SettingsLayout._handle_mouse_release``, not ``set_current_panel``. + +Dismiss (TICI side popup / mici overlay) +---------------------------------------- +Primary: tap outside the popup card. Also: the card's close control, or +tap the NAP sidebar / nap button again (TICI). Escape dismisses on TICI. +""" +from __future__ import annotations + + +WINDOW_S = 1.0 +TAP_COUNT = 3 +# mici: open the normal NAP page this long after the last tap if the burst +# never reached TAP_COUNT. Keeps single-tap navigation usable while still +# allowing a quick triple-tap. TICI has no delay (sidebar stays visible). +MICI_NAP_OPEN_DELAY_S = 0.40 + + +class TripleTapDetector: + """Count taps in a sliding time window. No GUI dependency.""" + + def __init__(self, window_s: float = WINDOW_S, tap_count: int = TAP_COUNT): + if window_s <= 0: + raise ValueError("window_s must be > 0") + if tap_count < 1: + raise ValueError("tap_count must be >= 1") + self.window_s = window_s + self.tap_count = tap_count + self._taps: list[float] = [] + + def tap(self, now: float) -> bool: + """Record a tap at ``now`` (monotonic seconds). + + Returns True if this tap completes ``tap_count`` taps inside ``window_s``. + The buffer is cleared after a successful burst so the next sequence starts + fresh. + """ + cutoff = now - self.window_s + self._taps = [t for t in self._taps if t >= cutoff] + self._taps.append(now) + if len(self._taps) >= self.tap_count: + self.reset() + return True + return False + + def reset(self) -> None: + self._taps.clear() + + @property + def pending_count(self) -> int: + return len(self._taps) diff --git a/selfdrive/ui/layouts/sidebar.py b/selfdrive/ui/layouts/sidebar.py new file mode 100644 index 00000000000000..3b45c994c0cca0 --- /dev/null +++ b/selfdrive/ui/layouts/sidebar.py @@ -0,0 +1,227 @@ +import pyray as rl +import time +from dataclasses import dataclass +from collections.abc import Callable +from cereal import log +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + +SIDEBAR_WIDTH = 300 +METRIC_HEIGHT = 126 +METRIC_WIDTH = 240 +METRIC_MARGIN = 30 +FONT_SIZE = 35 + +SETTINGS_BTN = rl.Rectangle(50, 35, 200, 117) +HOME_BTN = rl.Rectangle(60, 860, 180, 180) + +ThermalStatus = log.DeviceState.ThermalStatus +NetworkType = log.DeviceState.NetworkType + + +# Color scheme +class Colors: + WHITE = rl.WHITE + WHITE_DIM = rl.Color(255, 255, 255, 85) + GRAY = rl.Color(84, 84, 84, 255) + + # Status colors + GOOD = rl.WHITE + WARNING = rl.Color(218, 202, 37, 255) + DANGER = rl.Color(201, 34, 49, 255) + + # UI elements + METRIC_BORDER = rl.Color(255, 255, 255, 85) + BUTTON_NORMAL = rl.WHITE + BUTTON_PRESSED = rl.Color(255, 255, 255, 166) + + +NETWORK_TYPES = { + NetworkType.none: tr_noop("--"), + NetworkType.wifi: tr_noop("Wi-Fi"), + NetworkType.ethernet: tr_noop("ETH"), + NetworkType.cell2G: tr_noop("2G"), + NetworkType.cell3G: tr_noop("3G"), + NetworkType.cell4G: tr_noop("LTE"), + NetworkType.cell5G: tr_noop("5G"), +} + + +@dataclass(slots=True) +class MetricData: + label: str + value: str + color: rl.Color + + def update(self, label: str, value: str, color: rl.Color): + self.label = label + self.value = value + self.color = color + + +class Sidebar(Widget): + def __init__(self): + super().__init__() + self._net_type = NETWORK_TYPES.get(NetworkType.none) + self._net_strength = 0 + + self._temp_status = MetricData(tr_noop("TEMP"), tr_noop("GOOD"), Colors.GOOD) + self._panda_status = MetricData(tr_noop("VEHICLE"), tr_noop("ONLINE"), Colors.GOOD) + self._connect_status = MetricData(tr_noop("CONNECT"), tr_noop("OFFLINE"), Colors.WARNING) + self._recording_audio = False + + self._home_img = gui_app.texture("images/button_home.png", HOME_BTN.width, HOME_BTN.height) + self._flag_img = gui_app.texture("images/button_flag.png", HOME_BTN.width, HOME_BTN.height) + self._settings_img = gui_app.texture("images/button_settings.png", SETTINGS_BTN.width, SETTINGS_BTN.height) + self._mic_img = gui_app.texture("icons/microphone.png", 30, 30) + self._mic_indicator_rect = rl.Rectangle(0, 0, 0, 0) + self._font_regular = gui_app.font(FontWeight.NORMAL) + self._font_bold = gui_app.font(FontWeight.SEMI_BOLD) + + # Callbacks + self._on_settings_click: Callable | None = None + self._on_flag_click: Callable | None = None + self._open_settings_callback: Callable | None = None + + def set_callbacks(self, on_settings: Callable | None = None, on_flag: Callable | None = None, + open_settings: Callable | None = None): + self._on_settings_click = on_settings + self._on_flag_click = on_flag + self._open_settings_callback = open_settings + + def _render(self, rect: rl.Rectangle): + # Background + rl.draw_rectangle_rec(rect, rl.BLACK) + + self._draw_buttons(rect) + self._draw_network_indicator(rect) + self._draw_metrics(rect) + + def _update_state(self): + sm = ui_state.sm + if not sm.updated['deviceState']: + return + + device_state = sm['deviceState'] + + self._recording_audio = ui_state.recording_audio + self._update_network_status(device_state) + self._update_temperature_status(device_state) + self._update_connection_status(device_state) + self._update_panda_status() + + def _update_network_status(self, device_state): + self._net_type = NETWORK_TYPES.get(device_state.networkType.raw, tr_noop("Unknown")) + strength = device_state.networkStrength + self._net_strength = max(0, min(5, strength.raw + 1)) if strength.raw > 0 else 0 + + def _update_temperature_status(self, device_state): + thermal_status = device_state.thermalStatus + + if thermal_status == ThermalStatus.ok: + self._temp_status.update(tr_noop("TEMP"), tr_noop("GOOD"), Colors.GOOD) + else: + self._temp_status.update(tr_noop("TEMP"), tr_noop("HIGH"), Colors.DANGER) + + def _update_connection_status(self, device_state): + last_ping = device_state.lastAthenaPingTime + if last_ping == 0: + self._connect_status.update(tr_noop("CONNECT"), tr_noop("OFFLINE"), Colors.WARNING) + elif time.monotonic_ns() - last_ping < 80_000_000_000: # 80 seconds in nanoseconds + self._connect_status.update(tr_noop("CONNECT"), tr_noop("ONLINE"), Colors.GOOD) + else: + self._connect_status.update(tr_noop("CONNECT"), tr_noop("ERROR"), Colors.DANGER) + + def _update_panda_status(self): + if ui_state.panda_type == log.PandaState.PandaType.unknown: + self._panda_status.update(tr_noop("NO"), tr_noop("PANDA"), Colors.DANGER) + else: + self._panda_status.update(tr_noop("VEHICLE"), tr_noop("ONLINE"), Colors.GOOD) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if rl.check_collision_point_rec(mouse_pos, SETTINGS_BTN): + if self._on_settings_click: + self._on_settings_click() + elif rl.check_collision_point_rec(mouse_pos, HOME_BTN) and ui_state.started: + if self._on_flag_click: + self._on_flag_click() + elif self._recording_audio and rl.check_collision_point_rec(mouse_pos, self._mic_indicator_rect): + if self._open_settings_callback: + self._open_settings_callback() + + def _draw_buttons(self, rect: rl.Rectangle): + mouse_pos = rl.get_mouse_position() + mouse_down = self.is_pressed and rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) + + # Settings button + settings_down = mouse_down and rl.check_collision_point_rec(mouse_pos, SETTINGS_BTN) + tint = Colors.BUTTON_PRESSED if settings_down else Colors.BUTTON_NORMAL + rl.draw_texture_ex(self._settings_img, rl.Vector2(SETTINGS_BTN.x, SETTINGS_BTN.y), 0.0, 1.0, tint) + + # Home/Flag button + flag_pressed = mouse_down and rl.check_collision_point_rec(mouse_pos, HOME_BTN) + button_img = self._flag_img if ui_state.started else self._home_img + + tint = Colors.BUTTON_PRESSED if (ui_state.started and flag_pressed) else Colors.BUTTON_NORMAL + rl.draw_texture_ex(button_img, rl.Vector2(HOME_BTN.x, HOME_BTN.y), 0.0, 1.0, tint) + + # Microphone button + if self._recording_audio: + self._mic_indicator_rect = rl.Rectangle(rect.x + rect.width - 130, rect.y + 245, 75, 40) + + mic_pressed = mouse_down and rl.check_collision_point_rec(mouse_pos, self._mic_indicator_rect) + bg_color = rl.Color(Colors.DANGER.r, Colors.DANGER.g, Colors.DANGER.b, int(255 * 0.65)) if mic_pressed else Colors.DANGER + + rl.draw_rectangle_rounded(self._mic_indicator_rect, 1, 10, bg_color) + rl.draw_texture_ex(self._mic_img, rl.Vector2(self._mic_indicator_rect.x + (self._mic_indicator_rect.width - self._mic_img.width) / 2, + self._mic_indicator_rect.y + (self._mic_indicator_rect.height - self._mic_img.height) / 2), 0.0, 1.0, Colors.WHITE) + + def _draw_network_indicator(self, rect: rl.Rectangle): + # Signal strength dots + x_start = rect.x + 58 + y_pos = rect.y + 196 + dot_size = 27 + dot_spacing = 37 + + for i in range(5): + color = Colors.WHITE if i < self._net_strength else Colors.GRAY + x = int(x_start + i * dot_spacing + dot_size // 2) + y = int(y_pos + dot_size // 2) + rl.draw_circle(x, y, dot_size // 2, color) + + # Network type text + text_y = rect.y + 247 + text_pos = rl.Vector2(rect.x + 58, text_y) + rl.draw_text_ex(self._font_regular, tr(self._net_type), text_pos, FONT_SIZE, 0, Colors.WHITE) + + def _draw_metrics(self, rect: rl.Rectangle): + metrics = [(self._temp_status, 338), (self._panda_status, 496), (self._connect_status, 654)] + + for metric, y_offset in metrics: + self._draw_metric(rect, metric, rect.y + y_offset) + + def _draw_metric(self, rect: rl.Rectangle, metric: MetricData, y: float): + metric_rect = rl.Rectangle(rect.x + METRIC_MARGIN, y, METRIC_WIDTH, METRIC_HEIGHT) + # Draw colored left edge (clipped rounded rectangle) + edge_rect = rl.Rectangle(metric_rect.x + 4, metric_rect.y + 4, 100, 118) + rl.begin_scissor_mode(int(metric_rect.x + 4), int(metric_rect.y), 18, int(metric_rect.height)) + rl.draw_rectangle_rounded(edge_rect, 0.3, 10, metric.color) + rl.end_scissor_mode() + + # Draw border + rl.draw_rectangle_rounded_lines_ex(metric_rect, 0.3, 10, 2, Colors.METRIC_BORDER) + + # Draw label and value + labels = [tr(metric.label), tr(metric.value)] + text_y = metric_rect.y + (metric_rect.height / 2 - len(labels) * FONT_SIZE * FONT_SCALE) + for text in labels: + text_size = measure_text_cached(self._font_bold, text, FONT_SIZE) + text_y += text_size.y + text_pos = rl.Vector2( + metric_rect.x + 22 + (metric_rect.width - 22 - text_size.x) / 2, + text_y + ) + rl.draw_text_ex(self._font_bold, text, text_pos, FONT_SIZE, 0, Colors.WHITE) diff --git a/selfdrive/ui/lib/api_helpers.py b/selfdrive/ui/lib/api_helpers.py new file mode 100644 index 00000000000000..8ed1c22a6353ac --- /dev/null +++ b/selfdrive/ui/lib/api_helpers.py @@ -0,0 +1,18 @@ +import time +from functools import lru_cache +from openpilot.common.api import Api +from openpilot.common.time_helpers import system_time_valid + +TOKEN_EXPIRY_HOURS = 2 + + +@lru_cache(maxsize=1) +def _get_token(dongle_id: str, t: int): + if not system_time_valid(): + raise RuntimeError("System time is not valid, cannot generate token") + + return Api(dongle_id).get_token(expiry_hours=TOKEN_EXPIRY_HOURS) + + +def get_token(dongle_id: str): + return _get_token(dongle_id, int(time.monotonic() / (TOKEN_EXPIRY_HOURS / 2 * 60 * 60))) diff --git a/selfdrive/ui/lib/prime_state.py b/selfdrive/ui/lib/prime_state.py new file mode 100644 index 00000000000000..b57380ac5757c9 --- /dev/null +++ b/selfdrive/ui/lib/prime_state.py @@ -0,0 +1,109 @@ +from enum import IntEnum +import os +import requests +import threading +import time + +from openpilot.common.api import api_get +from openpilot.common.params import Params +from openpilot.common.realtime import drop_realtime +from openpilot.common.swaglog import cloudlog +from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID +from openpilot.selfdrive.ui.lib.api_helpers import get_token + + +class PrimeType(IntEnum): + UNKNOWN = -2 + UNPAIRED = -1 + NONE = 0 + MAGENTA = 1 + LITE = 2 + BLUE = 3 + MAGENTA_NEW = 4 + PURPLE = 5 + + +class PrimeState: + FETCH_INTERVAL = 5.0 # seconds between API calls + API_TIMEOUT = 10.0 # seconds for API requests + SLEEP_INTERVAL = 0.5 # seconds to sleep between checks in the worker thread + + def __init__(self): + self._params = Params() + self._lock = threading.Lock() + self._session = requests.Session() # reuse session to reduce SSL handshake overhead + self.prime_type: PrimeType = self._load_initial_state() + + self._running = False + self._thread = None + + def _load_initial_state(self) -> PrimeType: + prime_type_str = os.getenv("PRIME_TYPE") or self._params.get("PrimeType") + try: + if prime_type_str is not None: + return PrimeType(int(prime_type_str)) + except (ValueError, TypeError): + pass + return PrimeType.UNKNOWN + + def _fetch_prime_status(self) -> None: + dongle_id = self._params.get("DongleId") + if not dongle_id or dongle_id == UNREGISTERED_DONGLE_ID: + return + + try: + identity_token = get_token(dongle_id) + response = api_get(f"v1.1/devices/{dongle_id}", timeout=self.API_TIMEOUT, access_token=identity_token, session=self._session) + if response.status_code == 200: + data = response.json() + is_paired = data.get("is_paired", False) + prime_type = data.get("prime_type", 0) + self.set_type(PrimeType(prime_type) if is_paired else PrimeType.UNPAIRED) + except Exception as e: + cloudlog.error(f"Failed to fetch prime status: {e}") + + def set_type(self, prime_type: PrimeType) -> None: + with self._lock: + if prime_type != self.prime_type: + self.prime_type = prime_type + self._params.put("PrimeType", int(prime_type)) + cloudlog.info(f"Prime type updated to {prime_type}") + + def _worker_thread(self) -> None: + drop_realtime() + from openpilot.selfdrive.ui.ui_state import ui_state, device + while self._running: + if not ui_state.started and device._awake: + self._fetch_prime_status() + + for _ in range(int(self.FETCH_INTERVAL / self.SLEEP_INTERVAL)): + if not self._running: + break + time.sleep(self.SLEEP_INTERVAL) + + def start(self) -> None: + if self._thread and self._thread.is_alive(): + return + self._running = True + self._thread = threading.Thread(target=self._worker_thread, daemon=True) + self._thread.start() + + def stop(self) -> None: + self._running = False + if self._thread and self._thread.is_alive(): + self._thread.join(timeout=1.0) + + def get_type(self) -> PrimeType: + with self._lock: + return self.prime_type + + def is_prime(self) -> bool: + with self._lock: + return bool(self.prime_type > PrimeType.NONE) + + def is_paired(self) -> bool: + with self._lock: + return self.prime_type > PrimeType.UNPAIRED + + def __del__(self): + self.stop() diff --git a/selfdrive/ui/main.cc b/selfdrive/ui/main.cc deleted file mode 100644 index 4903a3db3dcc07..00000000000000 --- a/selfdrive/ui/main.cc +++ /dev/null @@ -1,30 +0,0 @@ -#include - -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/window.h" - -int main(int argc, char *argv[]) { - setpriority(PRIO_PROCESS, 0, -20); - - qInstallMessageHandler(swagLogMessageHandler); - initApp(argc, argv); - - QTranslator translator; - QString translation_file = QString::fromStdString(Params().get("LanguageSetting")); - if (!translator.load(QString(":/%1").arg(translation_file)) && translation_file.length()) { - qCritical() << "Failed to load translation file:" << translation_file; - } - - QApplication a(argc, argv); - a.installTranslator(&translator); - - MainWindow w; - setMainWindow(&w); - a.installEventFilter(&w); - return a.exec(); -} diff --git a/selfdrive/ui/mici/layouts/__init__.py b/selfdrive/ui/mici/layouts/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/selfdrive/ui/mici/layouts/home.py b/selfdrive/ui/mici/layouts/home.py new file mode 100644 index 00000000000000..1cc61c64789ab6 --- /dev/null +++ b/selfdrive/ui/mici/layouts/home.py @@ -0,0 +1,262 @@ +import datetime +import time + +from cereal import log +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.layouts import HBoxLayout +from openpilot.system.ui.widgets.icon_widget import IconWidget +from openpilot.system.ui.widgets.label import UnifiedLabel, gui_label +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.version import RELEASE_BRANCHES + +HEAD_BUTTON_FONT_SIZE = 40 +HOME_PADDING = 8 +ALERTS_ZONE_WIDTH = 180 + +NetworkType = log.DeviceState.NetworkType + +NETWORK_TYPES = { + NetworkType.none: "Offline", + NetworkType.wifi: "WiFi", + NetworkType.cell2G: "2G", + NetworkType.cell3G: "3G", + NetworkType.cell4G: "LTE", + NetworkType.cell5G: "5G", + NetworkType.ethernet: "Ethernet", +} + + +class AlertsPill(Widget): + ICON_OFFSET = 12 + COUNT_OFFSET = 40 + + def __init__(self): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 104, 52)) + + self._pill_bg_txt = gui_app.texture("icons_mici/alerts_pill.png", 104, 52) + self._icon_red = gui_app.texture("icons_mici/offroad_alerts/red_warning.png", 36, 36) + self._icon_orange = gui_app.texture("icons_mici/offroad_alerts/orange_warning.png", 36, 36) + self._icon_green = gui_app.texture("icons_mici/offroad_alerts/green_wheel.png", 36, 36) + self._alert_count_callback: Callable[[], int] | None = None + self._max_severity_callback: Callable[[], int | None] | None = None + + def set_alert_count_callback(self, callback: Callable[[], int] | None, + severity_callback: Callable[[], int | None] | None = None): + self._alert_count_callback = callback + self._max_severity_callback = severity_callback + + def _render(self, _): + alert_count = self._alert_count_callback() if self._alert_count_callback else 0 + if alert_count > 0: + pill_w, pill_h = self._pill_bg_txt.width, self._pill_bg_txt.height + rl.draw_texture_ex(self._pill_bg_txt, rl.Vector2(self.rect.x, self.rect.y), 0.0, 1.0, rl.WHITE) + + severity = self._max_severity_callback() if self._max_severity_callback else None + if severity == -1: + warning_txt = self._icon_green + elif severity is not None and severity > 0: + warning_txt = self._icon_red + else: + warning_txt = self._icon_orange + + warn_x = self.rect.x + self.ICON_OFFSET + warn_y = self.rect.y + (pill_h - warning_txt.height) / 2 + rl.draw_texture_ex(warning_txt, rl.Vector2(warn_x, warn_y), 0.0, 1.0, rl.WHITE) + + count_rect = rl.Rectangle(self.rect.x + self.COUNT_OFFSET, self.rect.y, pill_w - self.COUNT_OFFSET, pill_h) + gui_label(count_rect, str(alert_count), font_size=36, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + +class NetworkIcon(Widget): + def __init__(self): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 54, 44)) # max size of all icons + self._net_type = NetworkType.none + self._net_strength = 0 + + self._wifi_slash_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_slash.png", 50, 44) + self._wifi_none_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_none.png", 50, 37) + self._wifi_low_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_low.png", 50, 37) + self._wifi_medium_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_medium.png", 50, 37) + self._wifi_full_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 50, 37) + + self._cell_none_txt = gui_app.texture("icons_mici/settings/network/cell_strength_none.png", 54, 36) + self._cell_low_txt = gui_app.texture("icons_mici/settings/network/cell_strength_low.png", 54, 36) + self._cell_medium_txt = gui_app.texture("icons_mici/settings/network/cell_strength_medium.png", 54, 36) + self._cell_high_txt = gui_app.texture("icons_mici/settings/network/cell_strength_high.png", 54, 36) + self._cell_full_txt = gui_app.texture("icons_mici/settings/network/cell_strength_full.png", 54, 36) + + def _update_state(self): + device_state = ui_state.sm['deviceState'] + self._net_type = device_state.networkType + strength = device_state.networkStrength + self._net_strength = max(0, min(5, strength.raw + 1)) if strength.raw > 0 else 0 + + def _render(self, _): + if self._net_type == NetworkType.wifi: + # There is no 1 + draw_net_txt = {0: self._wifi_none_txt, + 2: self._wifi_low_txt, + 3: self._wifi_medium_txt, + 4: self._wifi_full_txt, + 5: self._wifi_full_txt}.get(self._net_strength, self._wifi_low_txt) + elif self._net_type in (NetworkType.cell2G, NetworkType.cell3G, NetworkType.cell4G, NetworkType.cell5G): + draw_net_txt = {0: self._cell_none_txt, + 2: self._cell_low_txt, + 3: self._cell_medium_txt, + 4: self._cell_high_txt, + 5: self._cell_full_txt}.get(self._net_strength, self._cell_none_txt) + else: + draw_net_txt = self._wifi_slash_txt + + draw_x = self._rect.x + (self._rect.width - draw_net_txt.width) / 2 + draw_y = self._rect.y + (self._rect.height - draw_net_txt.height) / 2 + + if draw_net_txt == self._wifi_slash_txt: + # Offset by difference in height between slashless and slash icons to make center align match + draw_y -= (self._wifi_slash_txt.height - self._wifi_none_txt.height) / 2 + + rl.draw_texture_ex(draw_net_txt, rl.Vector2(draw_x, draw_y), 0.0, 1.0, rl.Color(255, 255, 255, int(255 * 0.9))) + + +class MiciHomeLayout(Widget): + def __init__(self): + super().__init__() + self._on_settings_click: Callable | None = None + self._on_alerts_click: Callable | None = None + self._alert_count_callback: Callable[[], int] | None = None + + self._mouse_down_t: None | float = None + self._did_long_press = False + self._is_pressed_prev = False + + self._version_text = self._get_version_text() + + self._experimental_icon = IconWidget("icons_mici/experimental_mode.png", (48, 48)) + self._egpu_icon = IconWidget("icons_mici/egpu.png", (50, 37)) + self._egpu_icon_gray = IconWidget("icons_mici/egpu_gray.png", (50, 37)) + self._mic_icon = IconWidget("icons_mici/microphone.png", (32, 46)) + self._body_icon = IconWidget("icons_mici/body.png", (54, 37)) + + self._alerts_pill = AlertsPill() + + self._status_bar_layout = HBoxLayout([ + IconWidget("icons_mici/settings.png", (48, 48), opacity=0.9), + NetworkIcon(), + self._experimental_icon, + self._egpu_icon, + self._egpu_icon_gray, + self._body_icon, + self._mic_icon, + ], spacing=18) + + self._openpilot_label = UnifiedLabel("openpilot", font_size=96, font_weight=FontWeight.DISPLAY, max_width=480, wrap_text=False) + self._version_label = UnifiedLabel("", font_size=36, font_weight=FontWeight.ROMAN, max_width=480, wrap_text=False) + self._large_version_label = UnifiedLabel("", font_size=64, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, max_width=480, wrap_text=False) + self._date_label = UnifiedLabel("", font_size=36, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, max_width=480, wrap_text=False) + self._branch_label = UnifiedLabel("", font_size=36, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, scroll=True) + self._version_commit_label = UnifiedLabel("", font_size=36, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, max_width=480, wrap_text=False) + + def _update_state(self): + if self.is_pressed and not self._is_pressed_prev: + self._mouse_down_t = time.monotonic() + elif not self.is_pressed and self._is_pressed_prev: + self._mouse_down_t = None + self._did_long_press = False + self._is_pressed_prev = self.is_pressed + + if self._mouse_down_t is not None: + if time.monotonic() - self._mouse_down_t > 0.5: + # long gating for experimental mode - only allow toggle if longitudinal control is available + if ui_state.has_longitudinal_control: + ui_state.experimental_mode = not ui_state.experimental_mode + ui_state.params.put("ExperimentalMode", ui_state.experimental_mode, block=True) + self._mouse_down_t = None + self._did_long_press = True + + def set_callbacks(self, on_settings: Callable | None = None, on_alerts: Callable | None = None, + alert_count_callback: Callable[[], int] | None = None, + max_severity_callback: Callable[[], int | None] | None = None): + self._on_settings_click = on_settings + self._on_alerts_click = on_alerts + self._alert_count_callback = alert_count_callback + self._alerts_pill.set_alert_count_callback(alert_count_callback, max_severity_callback) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if not self._did_long_press: + relative_x = mouse_pos.x - self.rect.x + has_alerts = self._alert_count_callback and self._alert_count_callback() > 0 + if has_alerts and relative_x > self.rect.width - ALERTS_ZONE_WIDTH: + if self._on_alerts_click: + self._on_alerts_click() + elif self._on_settings_click: + self._on_settings_click() + self._did_long_press = False + + def _get_version_text(self) -> tuple[str, str, str, str] | None: + version = ui_state.params.get("Version") + branch = ui_state.params.get("GitBranch") + commit = ui_state.params.get("GitCommit") + + if not all((version, branch, commit)): + return None + + commit_date_raw = ui_state.params.get("GitCommitDate") + try: + # GitCommitDate format from get_commit_date(): '%ct %ci' e.g. "'1708012345 2024-02-15 ...'" + unix_ts = int(commit_date_raw.strip("'").split()[0]) + date_str = datetime.datetime.fromtimestamp(unix_ts).strftime("%b %d") + except (ValueError, IndexError, TypeError, AttributeError): + date_str = "" + + return version, branch, commit[:7], date_str + + def _render(self, _): + # TODO: why is there extra space here to get it to be flush? + text_pos = rl.Vector2(self.rect.x - 2 + HOME_PADDING, self.rect.y - 16) + self._openpilot_label.set_position(text_pos.x, text_pos.y) + self._openpilot_label.render() + + if self._version_text is not None: + # release branch + release_branch = self._version_text[1] in RELEASE_BRANCHES + version_pos = rl.Rectangle(text_pos.x, text_pos.y + self._openpilot_label.font_size + 16, 100, 44) + self._version_label.set_text(self._version_text[0]) + self._version_label.set_position(version_pos.x, version_pos.y) + self._version_label.render() + + self._date_label.set_text(" " + self._version_text[3]) + self._date_label.set_position(version_pos.x + self._version_label.text_width + 10, version_pos.y) + self._date_label.render() + + self._branch_label.set_max_width(gui_app.width - self._version_label.text_width - self._date_label.text_width - 32) + self._branch_label.set_text(" " + ("release" if release_branch else self._version_text[1])) + self._branch_label.set_position(version_pos.x + self._version_label.text_width + self._date_label.text_width + 20, version_pos.y) + self._branch_label.render() + + if not release_branch: + # 2nd line + self._version_commit_label.set_text(self._version_text[2]) + self._version_commit_label.set_position(version_pos.x, version_pos.y + self._date_label.font_size + 7) + self._version_commit_label.render() + + # ***** Center-aligned bottom section icons ***** + self._experimental_icon.set_visible(ui_state.experimental_mode) + self._egpu_icon.set_visible(ui_state.usbgpu and ui_state.usbgpu_compiled) + self._egpu_icon_gray.set_visible(ui_state.usbgpu and not ui_state.usbgpu_compiled) + self._mic_icon.set_visible(ui_state.recording_audio) + self._body_icon.set_visible(ui_state.is_body) + + footer_rect = rl.Rectangle(self.rect.x + HOME_PADDING, self.rect.y + self.rect.height - 48, self.rect.width - HOME_PADDING, 48) + self._status_bar_layout.render(footer_rect) + + # TODO: add alignment to hboxlayout and add to there + self._alerts_pill.set_position(self.rect.x + self.rect.width - self._alerts_pill.rect.width - HOME_PADDING, + self.rect.y + self.rect.height - self._alerts_pill.rect.height) + self._alerts_pill.render() diff --git a/selfdrive/ui/mici/layouts/main.py b/selfdrive/ui/mici/layouts/main.py new file mode 100644 index 00000000000000..18e65f5e1ce199 --- /dev/null +++ b/selfdrive/ui/mici/layouts/main.py @@ -0,0 +1,151 @@ +import pyray as rl +import cereal.messaging as messaging +from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout +from openpilot.selfdrive.ui.mici.layouts.settings.settings import SettingsLayout +from openpilot.selfdrive.ui.mici.layouts.offroad_alerts import MiciOffroadAlerts +from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import AugmentedRoadView +from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.selfdrive.ui.mici.layouts.onboarding import OnboardingWindow +from openpilot.selfdrive.ui.body.layouts.onroad import BodyLayout +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller import Scroller +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.onroad.force_offroad_confirm import maybe_show_force_offroad_confirm + + +ONROAD_DELAY = 2.5 # seconds + + +class MiciMainLayout(Scroller): + def __init__(self): + super().__init__(snap_items=True, spacing=0, pad=0, scroll_indicator=False, edge_shadows=False) + + self._pm = messaging.PubMaster(['bookmarkButton']) + + self._prev_onroad = False + self._prev_standstill = False + self._onroad_time_delay: float | None = None + self._setup = False + + # Initialize widgets + self._home_layout = MiciHomeLayout() + self._alerts_layout = MiciOffroadAlerts() + self._settings_layout = SettingsLayout() + self._car_onroad_layout = AugmentedRoadView(bookmark_callback=self._on_bookmark_clicked) + self._body_onroad_layout = BodyLayout() + + # Initialize widget rects + for widget in (self._home_layout, self._alerts_layout, self._settings_layout, + self._car_onroad_layout, self._body_onroad_layout): + # TODO: set parent rect and use it if never passed rect from render (like in Scroller) + widget.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + self._scroller.add_widgets([ + self._alerts_layout, + self._home_layout, + self._car_onroad_layout, + self._body_onroad_layout, + ]) + self._scroller.set_reset_scroll_at_show(False) + + # Disable scrolling when onroad is interacting with bookmark + self._scroller.set_scrolling_enabled(lambda: not self._car_onroad_layout.is_swiping_left()) + + # Set callbacks + self._setup_callbacks() + + gui_app.add_nav_stack_tick(self._handle_transitions) + gui_app.push_widget(self) + + # Start onboarding if terms or training not completed, make sure to push after self + self._onboarding_window = OnboardingWindow(lambda: gui_app.pop_widgets_to(self)) + if not self._onboarding_window.completed: + gui_app.push_widget(self._onboarding_window) + + @property + def _onroad_layout(self) -> Widget: + # For scroll_to + return self._body_onroad_layout if ui_state.is_body else self._car_onroad_layout + + def _setup_callbacks(self): + self._home_layout.set_callbacks( + on_settings=lambda: gui_app.push_widget(self._settings_layout), + on_alerts=lambda: self._scroll_to(self._alerts_layout), + alert_count_callback=self._alerts_layout.active_alerts, + max_severity_callback=self._alerts_layout.max_severity, + ) + for layout in (self._car_onroad_layout, self._body_onroad_layout): + layout.set_click_callback(lambda: self._scroll_to(self._home_layout)) + + device.add_interactive_timeout_callback(self._on_interactive_timeout) + ui_state.add_on_body_changed_callbacks(self._on_body_changed) + + def _scroll_to(self, layout: Widget): + layout_x = int(layout.rect.x) + self._scroller.scroll_to(layout_x, smooth=True) + + def _update_state(self): + super()._update_state() + # TODO: Hack to run alert updates while not in view. Add a nav stack tick? + self._alerts_layout._update_state() + + def _render(self, _): + if not self._setup: + if self._alerts_layout.active_alerts() > 0: + self._scroller.scroll_to(self._alerts_layout.rect.x) + else: + self._scroller.scroll_to(self._rect.width) + self._setup = True + + maybe_show_force_offroad_confirm() + # Render + super()._render(self._rect) + + def _handle_transitions(self): + # Don't pop if onboarding + if gui_app.widget_in_stack(self._onboarding_window): + return + + if ui_state.started != self._prev_onroad: + self._prev_onroad = ui_state.started + + # onroad: after delay, pop nav stack and scroll to onroad + # offroad: immediately scroll to home, but don't pop nav stack (can stay in settings) + if ui_state.started: + self._onroad_time_delay = rl.get_time() + else: + self._scroll_to(self._home_layout) + + # FIXME: these two pops can interrupt user interacting in the settings + if self._onroad_time_delay is not None and rl.get_time() - self._onroad_time_delay >= ONROAD_DELAY: + gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) + self._onroad_time_delay = None + + # When car leaves standstill, pop nav stack and scroll to onroad + CS = ui_state.sm["carState"] + if not CS.standstill and self._prev_standstill: + gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) + self._prev_standstill = CS.standstill + + def _on_interactive_timeout(self): + # Don't pop if onboarding + if gui_app.widget_in_stack(self._onboarding_window): + return + + if ui_state.started: + # Don't pop if at standstill + if not ui_state.sm["carState"].standstill: + gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) + else: + # Screen turns off on timeout offroad, so pop immediately without animation + gui_app.pop_widgets_to(self, instant=True) + self._scroll_to(self._home_layout) + + def _on_bookmark_clicked(self): + user_bookmark = messaging.new_message('bookmarkButton') + user_bookmark.valid = True + self._pm.send('bookmarkButton', user_bookmark) + + def _on_body_changed(self): + self._car_onroad_layout.set_visible(not ui_state.is_body) + self._body_onroad_layout.set_visible(ui_state.is_body) diff --git a/selfdrive/ui/mici/layouts/offroad_alerts.py b/selfdrive/ui/mici/layouts/offroad_alerts.py new file mode 100644 index 00000000000000..de631f686c8f15 --- /dev/null +++ b/selfdrive/ui/mici/layouts/offroad_alerts.py @@ -0,0 +1,323 @@ +import pyray as rl +import re +import threading +import time +from dataclasses import dataclass +from enum import IntEnum +from openpilot.common.params import Params +from openpilot.common.realtime import drop_realtime +from openpilot.selfdrive.selfdrived.alertmanager import OFFROAD_ALERTS +from openpilot.system.hardware import HARDWARE +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import Scroller +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr + +REFRESH_INTERVAL = 5.0 # seconds + + +class AlertSize(IntEnum): + SMALL = 0 + MEDIUM = 1 + BIG = 2 + + +@dataclass +class AlertData: + key: str + text: str + severity: int + visible: bool = False + + +class AlertItem(Widget): + # TODO: click should always go somewhere: home or specific settings pane + """Individual alert item widget with background image and text.""" + ALERT_WIDTH = 520 + ALERT_HEIGHT_SMALL = 212 + ALERT_HEIGHT_MED = 240 + ALERT_HEIGHT_BIG = 324 + ALERT_PADDING = 28 + ICON_SIZE = 64 + ICON_MARGIN = 12 + TEXT_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) + TITLE_BODY_SPACING = 24 + + def __init__(self, alert_data: AlertData): + super().__init__() + self.alert_data = alert_data + + # Load background textures + self._bg_small = gui_app.texture("icons_mici/offroad_alerts/small_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_SMALL) + self._bg_small_pressed = gui_app.texture("icons_mici/offroad_alerts/small_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_SMALL) + self._bg_medium = gui_app.texture("icons_mici/offroad_alerts/medium_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_MED) + self._bg_medium_pressed = gui_app.texture("icons_mici/offroad_alerts/medium_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_MED) + self._bg_big = gui_app.texture("icons_mici/offroad_alerts/big_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_BIG) + self._bg_big_pressed = gui_app.texture("icons_mici/offroad_alerts/big_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_BIG) + + # Load warning icons + self._icon_orange = gui_app.texture("icons_mici/offroad_alerts/orange_warning.png", self.ICON_SIZE, self.ICON_SIZE) + self._icon_red = gui_app.texture("icons_mici/offroad_alerts/red_warning.png", self.ICON_SIZE, self.ICON_SIZE) + self._icon_green = gui_app.texture("icons_mici/offroad_alerts/green_wheel.png", self.ICON_SIZE, self.ICON_SIZE) + + self._title_label = UnifiedLabel(text="", font_size=32, font_weight=FontWeight.SEMI_BOLD, text_color=self.TEXT_COLOR, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, line_height=0.95) + + self._body_label = UnifiedLabel(text="", font_size=28, font_weight=FontWeight.ROMAN, text_color=self.TEXT_COLOR, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, line_height=0.95) + + self._title_text = "" + self._body_text = "" + self._alert_size = AlertSize.SMALL + + self._update_content() + + def _split_text(self, text: str) -> tuple[str, str]: + """Split text into title (first sentence) and body (remaining text).""" + # Find the end of the first sentence (period, exclamation, or question mark followed by space or end) + match = re.search(r'[.!?](?:\s+|$)', text) + if match: + # Found a sentence boundary - split at the end of the sentence + title = text[:match.start()].strip() + body = text[match.end():].strip() + return title, body + else: + # No sentence boundary found, return full text as title + return "", text + + def _update_content(self): + """Update text and calculate height.""" + if not self.alert_data.visible or not self.alert_data.text: + self.set_visible(False) + return + + self.set_visible(True) + + # Split text into title and body + self._title_text, self._body_text = self._split_text(self.alert_data.text) + + # Calculate text width (alert width minus padding and icon space on right) + title_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) - self.ICON_SIZE - self.ICON_MARGIN + body_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) + + # Update labels + self._title_label.set_text(self._title_text) + self._body_label.set_text(self._body_text) + + # Calculate content height + title_height = self._title_label.get_content_height(title_width) if self._title_text else 0 + body_height = self._body_label.get_content_height(body_width) if self._body_text else 0 + spacing = self.TITLE_BODY_SPACING if (self._title_text and self._body_text) else 0 + total_text_height = title_height + spacing + body_height + + # Determine which background size to use based on content height + min_height_with_padding = total_text_height + (self.ALERT_PADDING * 2) + if min_height_with_padding > self.ALERT_HEIGHT_MED: + self._alert_size = AlertSize.BIG + height = self.ALERT_HEIGHT_BIG + elif min_height_with_padding > self.ALERT_HEIGHT_SMALL: + self._alert_size = AlertSize.MEDIUM + height = self.ALERT_HEIGHT_MED + else: + self._alert_size = AlertSize.SMALL + height = self.ALERT_HEIGHT_SMALL + + # Set rect size + self.set_rect(rl.Rectangle(0, 0, self.ALERT_WIDTH, height)) + + def update_alert_data(self, alert_data: AlertData): + """Update alert data and refresh display.""" + self.alert_data = alert_data + self._update_content() + + def _render(self, _): + if not self.alert_data.visible or not self.alert_data.text: + return + + # Choose background based on size + if self._alert_size == AlertSize.BIG: + bg_texture = self._bg_big_pressed if self.is_pressed else self._bg_big + elif self._alert_size == AlertSize.MEDIUM: + bg_texture = self._bg_medium_pressed if self.is_pressed else self._bg_medium + else: # AlertSize.SMALL + bg_texture = self._bg_small_pressed if self.is_pressed else self._bg_small + + # Draw background + rl.draw_texture_ex(bg_texture, rl.Vector2(self._rect.x, self._rect.y), 0.0, 1.0, rl.WHITE) + + # Calculate text area (left side, avoiding icon on right) + title_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) - self.ICON_SIZE - self.ICON_MARGIN + body_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) + text_x = self._rect.x + self.ALERT_PADDING + text_y = self._rect.y + self.ALERT_PADDING + + # Draw title label + if self._title_text: + title_rect = rl.Rectangle( + text_x, + text_y, + title_width, + self._title_label.get_content_height(title_width), + ) + self._title_label.render(title_rect) + text_y += title_rect.height + self.TITLE_BODY_SPACING + + # Draw body label + if self._body_text: + body_rect = rl.Rectangle( + text_x, + text_y, + body_width, + self._rect.height - text_y + self._rect.y - self.ALERT_PADDING, + ) + self._body_label.render(body_rect) + + # Draw warning icon on the right side + # Use green icon for update alerts (severity = -1), red for high severity, orange for low severity + if self.alert_data.severity == -1: + icon_texture = self._icon_green + elif self.alert_data.severity > 0: + icon_texture = self._icon_red + else: + icon_texture = self._icon_orange + icon_x = self._rect.x + self.ALERT_WIDTH - self.ALERT_PADDING - self.ICON_SIZE + icon_y = self._rect.y + self.ALERT_PADDING + rl.draw_texture_ex(icon_texture, rl.Vector2(icon_x, icon_y), 0.0, 1.0, rl.WHITE) + + +class MiciOffroadAlerts(Scroller): + """Offroad alerts layout with vertical scrolling.""" + + def __init__(self): + # Create vertical scroller + super().__init__(horizontal=False, spacing=12, pad=0) + self.params = Params() + self.sorted_alerts: list[AlertData] = [] + self.alert_items: list[AlertItem] = [] + + # Create empty state label + self._empty_label = UnifiedLabel(tr("no alerts"), 65, FontWeight.DISPLAY, rl.WHITE, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + # Build initial alert list + self._build_alerts() + + # Start param thread + self._pending_params: dict | None = None + self._params_thread = threading.Thread(target=self._params_worker, daemon=True) + self._params_thread.start() + + def active_alerts(self) -> int: + return sum(alert.visible for alert in self.sorted_alerts) + + def max_severity(self) -> int | None: + return max((alert.severity for alert in self.sorted_alerts if alert.visible), default=None) + + def scrolling(self): + return self._scroller.scroll_panel.is_touch_valid() + + def _build_alerts(self): + """Build sorted list of alerts from OFFROAD_ALERTS.""" + self.sorted_alerts = [] + + # Add UpdateAvailable alert at the top (severity = -1 to indicate special handling) + update_alert_data = AlertData(key="UpdateAvailable", text="", severity=-1) + self.sorted_alerts.append(update_alert_data) + update_alert_item = AlertItem(update_alert_data) + update_alert_item.set_click_callback(lambda: HARDWARE.reboot()) + self.alert_items.append(update_alert_item) + self._scroller.add_widget(update_alert_item) + + # Add regular alerts sorted by severity + for key, config in sorted(OFFROAD_ALERTS.items(), key=lambda x: x[1].get("severity", 0), reverse=True): + severity = config.get("severity", 0) + alert_data = AlertData(key=key, text="", severity=severity) + self.sorted_alerts.append(alert_data) + + # Create alert item widget + alert_item = AlertItem(alert_data) + self.alert_items.append(alert_item) + self._scroller.add_widget(alert_item) + + def _params_worker(self): + drop_realtime() + while True: + self._pending_params = ({"UpdaterNewDescription": self.params.get("UpdaterNewDescription")} | + {alert_data.key: self.params.get(alert_data.key) for alert_data in self.sorted_alerts}) + time.sleep(REFRESH_INTERVAL) + + def _refresh(self) -> int: + """Refresh alerts from params and return active count.""" + active_count = 0 + + # Handle UpdateAvailable alert specially + update_available = self._pending_params["UpdateAvailable"] + update_alert_data = next((alert_data for alert_data in self.sorted_alerts if alert_data.key == "UpdateAvailable"), None) + + if update_alert_data: + if update_available: + version_string = "" + + # Get new version description and parse version and date + new_desc = self._pending_params["UpdaterNewDescription"] or "" + if new_desc: + # format: "version / branch / commit / date" + parts = new_desc.split(" / ") + if len(parts) > 3: + version, date = parts[0], parts[3] + version_string = f"\nopenpilot {version}, {date}\n" + + update_alert_data.text = f"Update available {version_string}. Click to update. Read the release notes at blog.comma.ai." + update_alert_data.visible = True + active_count += 1 + else: + update_alert_data.text = "" + update_alert_data.visible = False + + # Handle regular alerts + for alert_data in self.sorted_alerts: + if alert_data.key == "UpdateAvailable": + continue # Skip, already handled above + + text = "" + alert_json = self._pending_params[alert_data.key] + + if alert_json: + text = alert_json.get("text", "").replace("%1", alert_json.get("extra", "")) + + if text and not alert_data.visible: + # Bump newly visible alerts to the top, severity sort keeps it at the top of its category + widget = next(w for w in self._scroller.items if w.alert_data is alert_data) + self._scroller.items.remove(widget) + self._scroller.items.insert(0, widget) + alert_data.text = text + alert_data.visible = bool(text) + + if alert_data.visible: + active_count += 1 + + # Update alert items (they reference the same alert_data objects) + for alert_item in self.alert_items: + alert_item.update_alert_data(alert_item.alert_data) + + self._scroller.items.sort(key=lambda w: -w.alert_data.severity) + + return active_count + + def _update_state(self): + """Periodically refresh alerts.""" + # Refresh alerts when thread updates params + if self._pending_params is not None: + self._refresh() + self._pending_params = None + + def _render(self, rect: rl.Rectangle): + """Render the alerts scroller or empty state.""" + if self.active_alerts() == 0: + self._empty_label.render(rect) + else: + self._scroller.render(rect) diff --git a/selfdrive/ui/mici/layouts/onboarding.py b/selfdrive/ui/mici/layouts/onboarding.py new file mode 100644 index 00000000000000..2d6acf60d669ae --- /dev/null +++ b/selfdrive/ui/mici/layouts/onboarding.py @@ -0,0 +1,387 @@ +import math +import numpy as np +import qrcode +import pyray as rl +from collections.abc import Callable +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import SmallCircleIconButton +from openpilot.system.ui.widgets.scroller import NavScroller, Scroller +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.mici_setup import GreyBigButton, BigPillButton +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.version import terms_version, training_version +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationCircleButton +from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import BaseDriverCameraDialog + + +class DriverCameraSetupDialog(BaseDriverCameraDialog): + def __init__(self): + super().__init__() + self.driver_state_renderer = DriverStateRenderer(inset=True) + self.driver_state_renderer.set_rect(rl.Rectangle(0, 0, 120, 120)) + self.driver_state_renderer.load_icons() + self.driver_state_renderer.set_force_active(True) + + def _render(self, rect): + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + self._camera_view._render(rect) + + if not self._camera_view.frame: + gui_label(rect, tr("camera starting"), font_size=64, font_weight=FontWeight.BOLD, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + rl.end_scissor_mode() + return + + # Position dmoji on opposite side from driver + is_rhd = self.driver_state_renderer.is_rhd + self.driver_state_renderer.set_position( + rect.x + 8 if is_rhd else rect.x + rect.width - self.driver_state_renderer.rect.width - 8, + rect.y + 8, + ) + self.driver_state_renderer.render() + + self._draw_face_detection(rect) + + rl.end_scissor_mode() + + +class TrainingGuidePreDMTutorial(NavScroller): + def __init__(self, continue_callback: Callable[[], None]): + super().__init__() + + continue_button = BigPillButton("next") + continue_button.set_click_callback(continue_callback) + + self._scroller.add_widgets([ + GreyBigButton("driver monitoring\ncheck", "scroll to continue", + gui_app.texture("icons_mici/setup/green_dm.png", 64, 64)), + GreyBigButton("", "Next, we'll check if comma four can detect the driver properly."), + GreyBigButton("", "openpilot uses the cabin camera to check if the driver is distracted."), + GreyBigButton("", "If it does not have a clear view of the driver, unplug and remount before continuing."), + continue_button, + ]) + + def show_event(self): + super().show_event() + # Get driver monitoring model ready for next step + ui_state.params.put_bool("IsDriverViewEnabled", True) + + +class DMBadFaceDetected(NavScroller): + def __init__(self): + super().__init__() + + back_button = BigPillButton("back") + back_button.set_click_callback(self.dismiss) + + self._scroller.add_widgets([ + GreyBigButton("looking for driver", "make sure comma\nfour can see your face", + gui_app.texture("icons_mici/setup/orange_dm.png", 64, 64)), + GreyBigButton("", "Remount if your face is blocked, or driver monitoring has difficulty tracking your face."), + back_button, + ]) + + +class TrainingGuideDMTutorial(NavWidget): + PROGRESS_DURATION = 4 + LOOKING_THRESHOLD_DEG = 30.0 + + def __init__(self, continue_callback: Callable[[], None]): + super().__init__() + + self._back_button = SmallCircleIconButton(gui_app.texture("icons_mici/setup/driver_monitoring/dm_question.png", 28, 48)) + self._back_button.set_click_callback(lambda: gui_app.push_widget(self._bad_face_page)) + self._back_button.set_touch_valid_callback(lambda: self.enabled and not self.is_dismissing) # for nav stack + self._good_button = SmallCircleIconButton(gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 42, 42)) + self._good_button.set_touch_valid_callback(lambda: self.enabled and not self.is_dismissing) # for nav stack + + self._good_button.set_click_callback(continue_callback) + self._good_button.set_enabled(False) + + self._progress = FirstOrderFilter(0.0, 0.5, 1 / gui_app.target_fps) + self._dialog = DriverCameraSetupDialog() + self._bad_face_page = DMBadFaceDetected() + + # Disable driver monitoring model when device times out for inactivity + def inactivity_callback(): + ui_state.params.put_bool("IsDriverViewEnabled", False) + + device.add_interactive_timeout_callback(inactivity_callback) + + def show_event(self): + super().show_event() + self._dialog.show_event() + self._progress.x = 0.0 + + def _update_state(self): + super()._update_state() + if device.awake and not ui_state.params.get_bool("IsDriverViewEnabled"): + ui_state.params.put_bool("IsDriverViewEnabled", True) + + sm = ui_state.sm + if sm.recv_frame.get("driverMonitoringState", 0) == 0: + return + + dm_state = sm["driverMonitoringState"] + driver_data = self._dialog.driver_state_renderer.get_driver_data() + + if len(driver_data.faceOrientation) == 3: + pitch, yaw, _ = driver_data.faceOrientation + looking_center = abs(math.degrees(pitch)) < self.LOOKING_THRESHOLD_DEG and abs(math.degrees(yaw)) < self.LOOKING_THRESHOLD_DEG + else: + looking_center = False + + # stay at 100% once reached + in_bad_face = gui_app.get_active_widget() == self._bad_face_page + if ((dm_state.visionPolicyState.faceDetected and looking_center) or self._progress.x > 0.99) and not in_bad_face: + slow = self._progress.x < 0.25 + duration = self.PROGRESS_DURATION * 2 if slow else self.PROGRESS_DURATION + self._progress.x += 1.0 / (duration * gui_app.target_fps) + self._progress.x = min(1.0, self._progress.x) + else: + self._progress.update(0.0) + + self._good_button.set_enabled(self._progress.x >= 0.999) + + def _render(self, _): + self._dialog.render(self._rect) + + gradient_y = int(self._rect.y + self._rect.height - 80) + gradient_h = int(self._rect.y) + int(self._rect.height) - gradient_y + rl.draw_rectangle_gradient_v(int(self._rect.x), gradient_y, + int(self._rect.width), gradient_h, rl.BLANK, rl.BLACK) + + # draw white ring around dm icon to indicate progress + ring_thickness = 8 + + # DM icon is 120x120, positioned on opposite side from driver + dm_size = 120 + is_rhd = self._dialog.driver_state_renderer._is_rhd + dm_center_x = (self._rect.x + dm_size / 2 + 8) if is_rhd else (self._rect.x + self._rect.width - dm_size / 2 - 8) + dm_center_y = self._rect.y + dm_size / 2 + 8 + icon_edge_radius = dm_size / 2 + outer_radius = icon_edge_radius + 1 # 2px outward from icon edge + inner_radius = outer_radius - ring_thickness # Inset by ring_thickness + start_angle = 90.0 # Start from bottom + end_angle = start_angle + self._progress.x * 360.0 # Clockwise + + # Fade in alpha + current_angle = end_angle - start_angle + alpha = int(np.interp(current_angle, [0.0, 45.0], [0, 255])) + + # White to green + color_t = np.clip(np.interp(current_angle, [45.0, 360.0], [0.0, 1.0]), 0.0, 1.0) + r = int(np.interp(color_t, [0.0, 1.0], [255, 0])) + g = int(np.interp(color_t, [0.0, 1.0], [255, 255])) + b = int(np.interp(color_t, [0.0, 1.0], [255, 64])) + ring_color = rl.Color(r, g, b, alpha) + + rl.draw_ring( + rl.Vector2(dm_center_x, dm_center_y), + inner_radius, + outer_radius, + start_angle, + end_angle, + 36, + ring_color, + ) + + if self._dialog._camera_view.frame: + self._back_button.render(rl.Rectangle( + self._rect.x + 8, + self._rect.y + self._rect.height - self._back_button.rect.height, + self._back_button.rect.width, + self._back_button.rect.height, + )) + + self._good_button.render(rl.Rectangle( + self._rect.x + self._rect.width - self._good_button.rect.width - 8, + self._rect.y + self._rect.height - self._good_button.rect.height, + self._good_button.rect.width, + self._good_button.rect.height, + )) + + # rounded border + rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y), int(self._rect.width), int(self._rect.height)) + rl.draw_rectangle_rounded_lines_ex(self._rect, 0.2 * 1.02, 10, 50, rl.BLACK) + rl.end_scissor_mode() + + +class TrainingGuideRecordFront(NavScroller): + def __init__(self, continue_callback: Callable[[], None]): + super().__init__() + + def on_accept(): + ui_state.params.put_bool("RecordFront", True) + continue_callback() + + def on_decline(): + ui_state.params.put_bool("RecordFront", False) + continue_callback() + + self._accept_button = BigConfirmationCircleButton("allow data uploading", gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64), + on_accept, exit_on_confirm=False) + + self._decline_button = BigConfirmationCircleButton("no, don't upload", gui_app.texture("icons_mici/setup/cancel.png", 64, 64), on_decline, + exit_on_confirm=False) + + self._scroller.add_widgets([ + GreyBigButton("driver camera data", "do you want to share video data for training?", + gui_app.texture("icons_mici/setup/green_dm.png", 64, 64)), + GreyBigButton("", "Sharing your data with comma helps improve openpilot for everyone."), + self._accept_button, + self._decline_button, + ]) + + +class TrainingGuideAttentionNotice(Scroller): + def __init__(self, continue_callback: Callable[[], None]): + super().__init__() + + continue_button = BigPillButton("next") + continue_button.set_click_callback(continue_callback) + + self._scroller.add_widgets([ + GreyBigButton("what is openpilot?", "scroll to continue", + gui_app.texture("icons_mici/setup/green_info.png", 64, 64)), + GreyBigButton("", "1. openpilot is a driver assistance system."), + GreyBigButton("", "2. You must pay attention at all times."), + GreyBigButton("", "3. You must be ready to take over at any time."), + GreyBigButton("", "4. You are fully responsible for driving the car."), + continue_button, + ]) + + +class TrainingGuide(NavWidget): + def __init__(self, completed_callback: Callable[[], None]): + super().__init__() + + self._steps = [ + TrainingGuideAttentionNotice(continue_callback=lambda: gui_app.push_widget(self._steps[1])), + TrainingGuidePreDMTutorial(continue_callback=lambda: gui_app.push_widget(self._steps[2])), + TrainingGuideDMTutorial(continue_callback=lambda: gui_app.push_widget(self._steps[3])), + TrainingGuideRecordFront(continue_callback=completed_callback), + ] + + self._child(self._steps[0]) + self._steps[0].set_enabled(lambda: self.enabled and not self.is_dismissing) # for nav stack + + def _render(self, _): + self._steps[0].render(self._rect) + + +class QRCodeWidget(Widget): + def __init__(self, url: str, size: int = 170): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, size, size)) + self._size = size + self._qr_texture: rl.Texture | None = None + self._generate_qr(url) + + def _generate_qr(self, url: str): + qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=0) + qr.add_data(url) + qr.make(fit=True) + + pil_img = qr.make_image(fill_color="white", back_color="black").convert('RGBA') + img_array = np.array(pil_img, dtype=np.uint8) + + rl_image = rl.Image() + rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) + rl_image.width = pil_img.width + rl_image.height = pil_img.height + rl_image.mipmaps = 1 + rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 + + self._qr_texture = rl.load_texture_from_image(rl_image) + + def _render(self, _): + if self._qr_texture: + scale = self._size / self._qr_texture.height + rl.draw_texture_ex(self._qr_texture, rl.Vector2(round(self._rect.x), round(self._rect.y)), 0.0, scale, rl.WHITE) + + def __del__(self): + if self._qr_texture and self._qr_texture.id != 0: + rl.unload_texture(self._qr_texture) + + +class TermsPage(Scroller): + def __init__(self, on_accept, on_decline): + super().__init__() + + self._accept_button = BigConfirmationCircleButton("accept\nterms", gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64), on_accept) + self._decline_button = BigConfirmationCircleButton("decline &\nuninstall", gui_app.texture("icons_mici/setup/cancel.png", 64, 64), on_decline, + red=True, exit_on_confirm=False) + + self._terms_header = GreyBigButton("terms and\nconditions", "scroll to continue", + gui_app.texture("icons_mici/setup/green_info.png", 64, 64)) + self._must_accept_card = GreyBigButton("", "You must accept the Terms & Conditions to use openpilot.") + + self._scroller.add_widgets([ + self._terms_header, + GreyBigButton("swipe for QR code", "or go to https://comma.ai/terms", + gui_app.texture("icons_mici/setup/small_slider/slider_arrow.png", 64, 56, flip_x=True)), + QRCodeWidget("https://comma.ai/terms"), + self._must_accept_card, + self._accept_button, + self._decline_button, + ]) + + def _render(self, _): + rl.draw_rectangle_rec(self._rect, rl.BLACK) + super()._render(_) + + +class OnboardingWindow(Widget): + def __init__(self, completed_callback: Callable[[], None]): + super().__init__() + self._completed_callback = completed_callback + self._accepted_terms: bool = ui_state.params.get("HasAcceptedTerms") == terms_version + self._training_done: bool = ui_state.params.get("CompletedTrainingVersion") == training_version + + self.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + # Windows + self._terms = TermsPage(on_accept=self._on_terms_accepted, on_decline=self._on_uninstall) + self._terms.set_enabled(lambda: self.enabled) # for nav stack + self._training_guide = TrainingGuide(completed_callback=self._on_completed_training) + self._training_guide.set_enabled(lambda: self.enabled) # for nav stack + + def _on_uninstall(self): + ui_state.params.put_bool("DoUninstall", True, block=True) + + def show_event(self): + super().show_event() + device.set_override_interactive_timeout(300) + device.set_offroad_brightness(100) + + def hide_event(self): + super().hide_event() + # FIXME: when nav stack sends hide event to widget 2 below on push, this needs to be moved + device.set_override_interactive_timeout(None) + device.set_offroad_brightness(None) + + @property + def completed(self) -> bool: + return self._accepted_terms and self._training_done + + def close(self): + ui_state.params.put_bool("IsDriverViewEnabled", False) + self._completed_callback() + + def _on_terms_accepted(self): + ui_state.params.put("HasAcceptedTerms", terms_version, block=True) + gui_app.push_widget(self._training_guide) + + def _on_completed_training(self): + ui_state.params.put("CompletedTrainingVersion", training_version, block=True) + self.close() + + def _render(self, _): + rl.draw_rectangle_rec(self._rect, rl.BLACK) + self._terms.render(self._rect) diff --git a/selfdrive/ui/mici/layouts/settings/developer.py b/selfdrive/ui/mici/layouts/settings/developer.py new file mode 100644 index 00000000000000..2f0250ff5f269e --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/developer.py @@ -0,0 +1,199 @@ +from collections.abc import Callable +from openpilot.common.time_helpers import system_time_valid +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigToggle, BigParamControl, BigCircleParamControl, GreyBigButton +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigInputDialog, BigConfirmationCircleButton +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.layouts.settings.common import restart_needed_callback +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.widgets.ssh_key import SshKeyFetcher + + +class AlphaLongConfirmPage(NavScroller): + def __init__(self, on_confirm: Callable[[], None]): + super().__init__() + + accept = BigConfirmationCircleButton("enable alpha\nlongitudinal", + gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64), + lambda: self.dismiss(on_confirm)) + + self._scroller.add_widgets([ + GreyBigButton("enabling alpha longitudinal", "scroll to continue", + gui_app.texture("icons_mici/setup/warning.png", 64, 64)), + GreyBigButton("", "WARNING: alpha longitudinal control may disable Automatic Emergency Braking (AEB)"), + GreyBigButton("", "On this car, openpilot defaults to the stock system's built-in ACC."), + GreyBigButton("", "Enabling this will switch to openpilot longitudinal control."), + GreyBigButton("", "Using Experimental mode is recommended with openpilot longitudinal control alpha."), + GreyBigButton("", "Changing this setting will restart openpilot if the car is powered on."), + accept, + ]) + + +class DeveloperLayoutMici(NavScroller): + def __init__(self): + super().__init__() + self._ssh_fetcher = SshKeyFetcher(ui_state.params) + + def github_username_callback(username: str): + if username: + self._ssh_keys_btn.set_value("Loading...") + self._ssh_keys_btn.set_enabled(False) + + def on_response(error): + self._ssh_keys_btn.set_enabled(True) + if error is None: + self._ssh_keys_btn.set_value(username) + else: + self._ssh_keys_btn.set_value("Not set") + gui_app.push_widget(BigDialog("", error)) + + self._ssh_fetcher.fetch(username, on_response) + else: + self._ssh_fetcher.clear() + self._ssh_keys_btn.set_value("Not set") + + def ssh_keys_callback(): + github_username = ui_state.params.get("GithubUsername") or "" + dlg = BigInputDialog("enter GitHub username...", github_username, minimum_length=0, confirm_callback=github_username_callback) + if not system_time_valid(): + dlg = BigDialog("", "Please connect to Wi-Fi to fetch your key.") + gui_app.push_widget(dlg) + return + gui_app.push_widget(dlg) + + txt_ssh = gui_app.texture("icons_mici/settings/developer/ssh.png", 56, 64) + github_username = ui_state.params.get("GithubUsername") or "" + self._ssh_keys_btn = BigButton("SSH keys", "Not set" if not github_username else github_username, icon=txt_ssh) + self._ssh_keys_btn.set_click_callback(ssh_keys_callback) + + # adb, ssh, ssh keys, debug mode, joystick debug mode, longitudinal maneuver mode, ip address + # ******** Main Scroller ******** + self._adb_toggle = BigCircleParamControl(gui_app.texture("icons_mici/adb_short.png", 82, 82), "AdbEnabled", icon_offset=(0, 12)) + self._ssh_toggle = BigCircleParamControl(gui_app.texture("icons_mici/ssh_short.png", 82, 82), "SshEnabled", icon_offset=(0, 12)) + self._joystick_toggle = BigToggle("joystick debug mode", + initial_state=ui_state.params.get_bool("JoystickDebugMode"), + toggle_callback=self._on_joystick_debug_mode) + self._long_maneuver_toggle = BigToggle("longitudinal maneuver mode", + initial_state=ui_state.params.get_bool("LongitudinalManeuverMode"), + toggle_callback=self._on_long_maneuver_mode) + self._lat_maneuver_toggle = BigToggle("lateral maneuver mode", + initial_state=ui_state.params.get_bool("LateralManeuverMode"), + toggle_callback=self._on_lat_maneuver_mode) + self._alpha_long_toggle = BigToggle("alpha longitudinal", + initial_state=ui_state.params.get_bool("AlphaLongitudinalEnabled"), + toggle_callback=self._on_alpha_long_enabled) + self._debug_mode_toggle = BigParamControl("ui debug mode", "ShowDebugInfo", + toggle_callback=lambda checked: (gui_app.set_show_touches(checked), + gui_app.set_show_fps(checked))) + + self._scroller.add_widgets([ + self._adb_toggle, + self._ssh_toggle, + self._ssh_keys_btn, + self._joystick_toggle, + self._long_maneuver_toggle, + self._lat_maneuver_toggle, + self._alpha_long_toggle, + self._debug_mode_toggle, + ]) + + # Toggle lists + self._refresh_toggles = ( + ("AdbEnabled", self._adb_toggle), + ("SshEnabled", self._ssh_toggle), + ("JoystickDebugMode", self._joystick_toggle), + ("LongitudinalManeuverMode", self._long_maneuver_toggle), + ("LateralManeuverMode", self._lat_maneuver_toggle), + ("AlphaLongitudinalEnabled", self._alpha_long_toggle), + ("ShowDebugInfo", self._debug_mode_toggle), + ) + onroad_blocked_toggles = (self._adb_toggle, self._joystick_toggle) + release_blocked_toggles = (self._joystick_toggle, self._long_maneuver_toggle, self._lat_maneuver_toggle, self._alpha_long_toggle) + engaged_blocked_toggles = (self._long_maneuver_toggle, self._lat_maneuver_toggle, self._alpha_long_toggle) + + # Hide non-release toggles on release builds + for item in release_blocked_toggles: + item.set_visible(not ui_state.is_release) + + # Disable toggles that require offroad + for item in onroad_blocked_toggles: + item.set_enabled(lambda: ui_state.is_offroad()) + + # Disable toggles that require not engaged + for item in engaged_blocked_toggles: + item.set_enabled(lambda: not ui_state.engaged) + + # Set initial state + if ui_state.params.get_bool("ShowDebugInfo"): + gui_app.set_show_touches(True) + gui_app.set_show_fps(True) + + ui_state.add_offroad_transition_callback(self._update_toggles) + + def _update_state(self): + super()._update_state() + self._ssh_fetcher.update() + + def show_event(self): + super().show_event() + self._update_toggles() + + def _update_toggles(self): + ui_state.update_params() + + # CP gating + if ui_state.CP is not None: + alpha_avail = ui_state.CP.alphaLongitudinalAvailable + if not alpha_avail or ui_state.is_release: + self._alpha_long_toggle.set_visible(False) + ui_state.params.remove("AlphaLongitudinalEnabled") + else: + self._alpha_long_toggle.set_visible(True) + + long_man_enabled = ui_state.has_longitudinal_control and ui_state.is_offroad() + self._long_maneuver_toggle.set_enabled(long_man_enabled) + else: + self._long_maneuver_toggle.set_enabled(False) + self._lat_maneuver_toggle.set_enabled(False) + self._alpha_long_toggle.set_visible(False) + + # Refresh toggles from params to mirror external changes + for key, item in self._refresh_toggles: + item.set_checked(ui_state.params.get_bool(key)) + + def _on_joystick_debug_mode(self, state: bool): + ui_state.params.put_bool("JoystickDebugMode", state, block=True) + ui_state.params.put_bool("LongitudinalManeuverMode", False, block=True) + self._long_maneuver_toggle.set_checked(False) + ui_state.params.put_bool("LateralManeuverMode", False, block=True) + self._lat_maneuver_toggle.set_checked(False) + + def _on_long_maneuver_mode(self, state: bool): + ui_state.params.put_bool("LongitudinalManeuverMode", state, block=True) + ui_state.params.put_bool("JoystickDebugMode", False, block=True) + self._joystick_toggle.set_checked(False) + ui_state.params.put_bool("LateralManeuverMode", False, block=True) + self._lat_maneuver_toggle.set_checked(False) + restart_needed_callback() + + def _on_lat_maneuver_mode(self, state: bool): + ui_state.params.put_bool("LateralManeuverMode", state, block=True) + ui_state.params.put_bool("ExperimentalMode", False, block=True) + ui_state.params.put_bool("JoystickDebugMode", False, block=True) + self._joystick_toggle.set_checked(False) + ui_state.params.put_bool("LongitudinalManeuverMode", False, block=True) + self._long_maneuver_toggle.set_checked(False) + restart_needed_callback() + + def _on_alpha_long_enabled(self, state: bool): + def do_toggle(_state: bool): + ui_state.params.put_bool("AlphaLongitudinalEnabled", _state, block=True) + restart_needed_callback() + self._update_toggles() + + if state: + # Don't show enabled state until confirm + self._alpha_long_toggle.set_checked(False) + gui_app.push_widget(AlphaLongConfirmPage(lambda: do_toggle(True))) + else: + do_toggle(False) diff --git a/selfdrive/ui/mici/layouts/settings/device.py b/selfdrive/ui/mici/layouts/settings/device.py new file mode 100644 index 00000000000000..6b8320f4889d64 --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/device.py @@ -0,0 +1,357 @@ +import os +import threading +import pyray as rl +from enum import IntEnum +from collections.abc import Callable + +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.time_helpers import system_time_valid +from openpilot.system.ui.widgets.scroller import NavRawScrollPanel, NavScroller +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigCircleButton +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationDialog +from openpilot.selfdrive.ui.mici.widgets.pairing_dialog import PairingDialog +from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import DriverCameraDialog +from openpilot.selfdrive.ui.mici.layouts.onboarding import TrainingGuide, TermsPage +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.html_render import HtmlModal, HtmlRenderer +from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID + + +class ReviewTermsPage(TermsPage, NavScroller): + """TermsPage with NavWidget swipe-to-dismiss for reviewing in device settings.""" + def __init__(self): + super().__init__(on_accept=self.dismiss, on_decline=self.dismiss) + self._terms_header.set_visible(False) + self._must_accept_card.set_visible(False) + self._accept_button.set_visible(False) + self._decline_button.set_visible(False) + + +class ReviewTrainingGuide(TrainingGuide): + def show_event(self): + super().show_event() + device.set_override_interactive_timeout(300) + + def hide_event(self): + super().hide_event() + device.set_override_interactive_timeout(None) + ui_state.params.put_bool("IsDriverViewEnabled", False) + + +class MiciFccModal(NavRawScrollPanel): + def __init__(self, file_path: str | None = None, text: str | None = None): + super().__init__() + self._content = HtmlRenderer(file_path=file_path, text=text) + self._fcc_logo = gui_app.texture("icons_mici/settings/device/fcc_logo.png", 76, 64) + + def _render(self, rect: rl.Rectangle): + content_height = self._content.get_total_height(int(rect.width)) + content_height += self._fcc_logo.height + 20 + + scroll_content_rect = rl.Rectangle(rect.x, rect.y, rect.width, content_height) + scroll_offset = round(self._scroll_panel.update(rect, scroll_content_rect.height)) + + fcc_pos = rl.Vector2(rect.x + 20, rect.y + 20 + scroll_offset) + + scroll_content_rect.y += scroll_offset + self._fcc_logo.height + 20 + self._content.render(scroll_content_rect) + + rl.draw_texture_ex(self._fcc_logo, fcc_pos, 0.0, 1.0, rl.WHITE) + + +def _engaged_confirmation_click(callback: Callable, action_text: str, icon: rl.Texture, exit_on_confirm: bool = True, red: bool = False): + if not ui_state.engaged: + def confirm_callback(): + # Check engaged again in case it changed while the dialog was open + # TODO: if true, we stay on the dialog if not exit_on_confirm until normal onroad timeout + if not ui_state.engaged: + callback() + + gui_app.push_widget(BigConfirmationDialog(f"slide to\n{action_text.lower()}", icon, confirm_callback, exit_on_confirm=exit_on_confirm, red=red)) + else: + gui_app.push_widget(BigDialog("", f"Disengage to {action_text}")) + + +class EngagedConfirmationCircleButton(BigCircleButton): + def __init__(self, title: str, icon: rl.Texture, callback: Callable[[], None], exit_on_confirm: bool = True, + red: bool = False, icon_offset: tuple[int, int] = (0, 0)): + super().__init__(icon, red, icon_offset) + self.set_click_callback(lambda: _engaged_confirmation_click(callback, title, icon, exit_on_confirm=exit_on_confirm, red=red)) + + +class EngagedConfirmationButton(BigButton): + def __init__(self, text: str, action_text: str, icon: rl.Texture, callback: Callable[[], None], + exit_on_confirm: bool = True, red: bool = False): + super().__init__(text, "", icon) + self.set_click_callback(lambda: _engaged_confirmation_click(callback, action_text, icon, exit_on_confirm=exit_on_confirm, red=red)) + + +class DeviceInfoLayoutMici(Widget): + def __init__(self): + super().__init__() + + self.set_rect(rl.Rectangle(0, 0, 360, 180)) + + params = Params() + subheader_color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)) + max_width = int(self._rect.width - 20) + self._dongle_id_label = UnifiedLabel("device ID", 48, max_width=max_width, font_weight=FontWeight.DISPLAY, wrap_text=False) + self._dongle_id_text_label = UnifiedLabel(params.get("DongleId") or 'N/A', 32, max_width=max_width, text_color=subheader_color, + font_weight=FontWeight.ROMAN, wrap_text=False) + + self._serial_number_label = UnifiedLabel("serial", 48, max_width=max_width, font_weight=FontWeight.DISPLAY, wrap_text=False) + self._serial_number_text_label = UnifiedLabel(params.get("HardwareSerial") or 'N/A', 32, max_width=max_width, text_color=subheader_color, + font_weight=FontWeight.ROMAN, wrap_text=False) + + def _render(self, _): + self._dongle_id_label.set_position(self._rect.x + 20, self._rect.y - 10) + self._dongle_id_label.render() + + self._dongle_id_text_label.set_position(self._rect.x + 20, self._rect.y + 68 - 25) + self._dongle_id_text_label.render() + + self._serial_number_label.set_position(self._rect.x + 20, self._rect.y + 114 - 30) + self._serial_number_label.render() + + self._serial_number_text_label.set_position(self._rect.x + 20, self._rect.y + 161 - 25) + self._serial_number_text_label.render() + + +class UpdaterState(IntEnum): + IDLE = 0 + WAITING_FOR_UPDATER = 1 + UPDATER_RESPONDING = 2 + + +class PairBigButton(BigButton): + def __init__(self): + super().__init__("pair", "connect.comma.ai", gui_app.texture("icons_mici/settings/comma_icon.png", 33, 60)) + + def _get_label_font_size(self): + return 64 + + def _update_state(self): + super()._update_state() + + if ui_state.prime_state.is_paired(): + self.set_text("paired") + if ui_state.prime_state.is_prime(): + self.set_value("subscribed") + else: + self.set_value("upgrade to prime") + else: + self.set_text("pair") + self.set_value("connect.comma.ai") + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + # TODO: show ad dialog when clicked if not prime + if ui_state.prime_state.is_paired(): + return + dlg: BigDialog | PairingDialog + if not system_time_valid(): + dlg = BigDialog("", tr("Please connect to Wi-Fi to complete initial pairing.")) + elif UNREGISTERED_DONGLE_ID == (ui_state.params.get("DongleId") or UNREGISTERED_DONGLE_ID): + dlg = BigDialog("", tr("Device must be registered with the comma.ai backend to pair.")) + else: + dlg = PairingDialog() + gui_app.push_widget(dlg) + + +UPDATER_TIMEOUT = 10.0 # seconds to wait for updater to respond + + +class UpdateOpenpilotBigButton(BigButton): + def __init__(self): + self._txt_update_icon = gui_app.texture("icons_mici/settings/device/update.png", 64, 75) + self._txt_reboot_icon = gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70) + self._txt_up_to_date_icon = gui_app.texture("icons_mici/settings/device/up_to_date.png", 64, 64) + super().__init__("update openpilot", "", self._txt_update_icon) + + self._waiting_for_updater_t: float | None = None + self._hide_value_t: float | None = None + self._state: UpdaterState = UpdaterState.IDLE + + ui_state.add_offroad_transition_callback(self.offroad_transition) + + def offroad_transition(self): + if ui_state.is_offroad(): + self.set_enabled(True) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + if not system_time_valid(): + dlg = BigDialog("", tr("Please connect to Wi-Fi to update.")) + gui_app.push_widget(dlg) + return + + self.set_enabled(False) + self._state = UpdaterState.WAITING_FOR_UPDATER + self.set_icon(self._txt_update_icon) + + def run(): + if self.get_value() == "download update": + os.system("pkill -SIGHUP -f system.updated.updated") + elif self.get_value() == "update now": + ui_state.params.put_bool("DoReboot", True, block=True) + else: + os.system("pkill -SIGUSR1 -f system.updated.updated") + + threading.Thread(target=run, daemon=True).start() + + def set_value(self, value: str): + super().set_value(value) + if value: + self.set_text("") + else: + self.set_text("update openpilot") + + def _update_state(self): + super()._update_state() + + if ui_state.started: + self.set_enabled(False) + return + + updater_state = ui_state.params.get("UpdaterState") or "" + failed_count = ui_state.params.get("UpdateFailedCount") + failed = False if failed_count is None else int(failed_count) > 0 + + if ui_state.params.get_bool("UpdateAvailable"): + self.set_rotate_icon(False) + self.set_enabled(True) + if self.get_value() != "update now": + self.set_value("update now") + self.set_icon(self._txt_reboot_icon) + + elif self._state == UpdaterState.WAITING_FOR_UPDATER: + self.set_rotate_icon(True) + if updater_state != "idle": + self._state = UpdaterState.UPDATER_RESPONDING + + # Recover from updater not responding (time invalid shortly after boot) + if self._waiting_for_updater_t is None: + self._waiting_for_updater_t = rl.get_time() + + if self._waiting_for_updater_t is not None and rl.get_time() - self._waiting_for_updater_t > UPDATER_TIMEOUT: + self.set_rotate_icon(False) + self.set_value("updater failed\nto respond") + self._state = UpdaterState.IDLE + self._hide_value_t = rl.get_time() + + elif self._state == UpdaterState.UPDATER_RESPONDING: + if updater_state == "idle": + self.set_rotate_icon(False) + self._state = UpdaterState.IDLE + self._hide_value_t = rl.get_time() + else: + if self.get_value() != updater_state: + self.set_value(updater_state) + + elif self._state == UpdaterState.IDLE: + self.set_rotate_icon(False) + if failed: + if self.get_value() != "failed to update": + self.set_value("failed to update") + + elif ui_state.params.get_bool("UpdaterFetchAvailable"): + self.set_enabled(True) + if self.get_value() != "download update": + self.set_value("download update") + + elif self._hide_value_t is not None: + self.set_enabled(True) + if self.get_value() == "checking...": + self.set_value("up to date") + self.set_icon(self._txt_up_to_date_icon) + + # Hide previous text after short amount of time (up to date or failed) + if rl.get_time() - self._hide_value_t > 3.0: + self._hide_value_t = None + self.set_value("") + self.set_icon(self._txt_update_icon) + else: + if self.get_value() != "": + self.set_value("") + + if self._state != UpdaterState.WAITING_FOR_UPDATER: + self._waiting_for_updater_t = None + + +class DeviceLayoutMici(NavScroller): + def __init__(self): + super().__init__() + + self._fcc_dialog: HtmlModal | None = None + + def power_off_callback(): + ui_state.params.put_bool("DoShutdown", True, block=True) + + def reboot_callback(): + ui_state.params.put_bool("DoReboot", True, block=True) + + def reset_calibration_callback(): + params = ui_state.params + params.remove("CalibrationParams") + params.remove("LiveTorqueParameters") + params.remove("LiveParameters") + params.remove("LiveParametersV2") + params.remove("LiveDelay") + params.put_bool("OnroadCycleRequested", True, block=True) + + def uninstall_openpilot_callback(): + ui_state.params.put_bool("DoUninstall", True, block=True) + + reset_calibration_btn = EngagedConfirmationButton("reset calibration", "reset", gui_app.texture("icons_mici/settings/device/lkas.png", 122, 64), + reset_calibration_callback) + + uninstall_openpilot_btn = EngagedConfirmationButton("uninstall openpilot", "uninstall", + gui_app.texture("icons_mici/settings/device/uninstall.png", 64, 64), + uninstall_openpilot_callback, exit_on_confirm=False) + + reboot_btn = EngagedConfirmationCircleButton("reboot", gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70), + reboot_callback, exit_on_confirm=False) + + self._power_off_btn = EngagedConfirmationCircleButton("power off", gui_app.texture("icons_mici/settings/device/power.png", 64, 66), + power_off_callback, exit_on_confirm=False, red=True) + self._power_off_btn.set_visible(lambda: not ui_state.ignition) + + regulatory_btn = BigButton("regulatory info", "", gui_app.texture("icons_mici/settings/device/info.png", 64, 64)) + regulatory_btn.set_click_callback(self._on_regulatory) + + driver_cam_btn = BigButton("driver\ncamera preview", "", gui_app.texture("icons_mici/settings/device/cameras.png", 64, 64)) + driver_cam_btn.set_click_callback(lambda: gui_app.push_widget(DriverCameraDialog())) + driver_cam_btn.set_enabled(lambda: ui_state.is_offroad()) + + review_training_guide_btn = BigButton("review\ntraining guide", "", gui_app.texture("icons_mici/settings/device/info.png", 64, 64)) + review_training_guide_btn.set_click_callback(lambda: gui_app.push_widget(ReviewTrainingGuide(completed_callback=lambda: gui_app.pop_widgets_to(self)))) + review_training_guide_btn.set_enabled(lambda: ui_state.is_offroad()) + + terms_btn = BigButton("terms &\nconditions", "", gui_app.texture("icons_mici/settings/device/info.png", 64, 64)) + terms_btn.set_click_callback(lambda: gui_app.push_widget(ReviewTermsPage())) + + self._scroller.add_widgets([ + DeviceInfoLayoutMici(), + UpdateOpenpilotBigButton(), + PairBigButton(), + review_training_guide_btn, + driver_cam_btn, + terms_btn, + regulatory_btn, + reset_calibration_btn, + uninstall_openpilot_btn, + reboot_btn, + self._power_off_btn, + ]) + + def _on_regulatory(self): + if not self._fcc_dialog: + self._fcc_dialog = MiciFccModal(os.path.join(BASEDIR, "selfdrive/assets/offroad/mici_fcc.html")) + gui_app.push_widget(self._fcc_dialog) diff --git a/selfdrive/ui/mici/layouts/settings/driving_mannerisms.py b/selfdrive/ui/mici/layouts/settings/driving_mannerisms.py new file mode 100644 index 00000000000000..caa50309754730 --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/driving_mannerisms.py @@ -0,0 +1,134 @@ +"""mici NAP submenu: Driving Mannerisms controls.""" +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.big_multi_value_param import BigMultiValueParamToggle +from openpilot.selfdrive.ui.mici.widgets.button import BigParamControl +from openpilot.selfdrive.controls.lib.hypermile import apply_hypermile_toggle +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + FOLLOW_DISTANCE_DEFAULT, + FOLLOW_DISTANCE_LABELS, + FOLLOW_DISTANCE_VALUES, + MAP_SPEED_ACCEL, MAP_SPEED_ACCEL_DEFAULT, MAP_SPEED_ACCEL_LABELS, + NAP_CONE_LINE_HOLD, + NAP_OBSTACLE_CHIME, + NAP_DRIVER_LAT_HANDOFF, + NAP_LOW_VIS_BACKOFF, + NAP_FOLLOW_DISTANCE_CITY, + NAP_FOLLOW_DISTANCE_HWY, + NAP_HYPERMILE, + NAP_HYPERMILE_HILL_CLIMB, + NAP_HYPERMILE_STEP_DOWN, + NAP_GAP_LOCK, + NAP_ONE_PEDAL_LONG, +) +from openpilot.selfdrive.ui.layouts.settings.nap_lateral import ( + NAP_TURN_IN_DELAY, TURN_IN_DELAY_LABELS, TURN_IN_DELAY_STEPS, +) +from opendbc.car.tesla.preap.nap_params import NAPParamKeys + + +class DrivingMannerismsLayoutMici(NavScroller): + def __init__(self): + super().__init__() + self._params = Params() + + def on_hypermile(checked): + apply_hypermile_toggle(self._params, bool(checked)) + self._accel.refresh() + + self._accel = BigMultiValueParamToggle( + "acceleration", + "NAPMapSpeedAccel", + values=list(MAP_SPEED_ACCEL), + labels=MAP_SPEED_ACCEL_LABELS, + default_value=MAP_SPEED_ACCEL_DEFAULT, + ) + + adaptive_accel = BigParamControl("adaptive accel", NAPParamKeys.ADAPTIVE_ACCEL) + adaptive_accel.set_value("Softer near a lead") + + self._follow_distance_city = BigMultiValueParamToggle( + "city follow distance", + NAP_FOLLOW_DISTANCE_CITY, + values=FOLLOW_DISTANCE_VALUES, + labels=FOLLOW_DISTANCE_LABELS, + default_value=FOLLOW_DISTANCE_DEFAULT, + ) + + self._follow_distance_hwy = BigMultiValueParamToggle( + "highway follow distance", + NAP_FOLLOW_DISTANCE_HWY, + values=FOLLOW_DISTANCE_VALUES, + labels=FOLLOW_DISTANCE_LABELS, + default_value=FOLLOW_DISTANCE_DEFAULT, + ) + + self._turn_in_delay = BigMultiValueParamToggle( + "turn-in timing", + NAP_TURN_IN_DELAY, + values=list(TURN_IN_DELAY_STEPS), + labels=TURN_IN_DELAY_LABELS, + default_value=0, + ) + + lat_handoff = BigParamControl("soft lateral handoff", NAP_DRIVER_LAT_HANDOFF) + lat_handoff.set_value("On — free-wheel yield; Off if false-yield") + + low_vis = BigParamControl("low visibility back-off", NAP_LOW_VIS_BACKOFF) + low_vis.set_value("On — ease lateral and show Low visibility") + + cone_hold = BigParamControl("hold my line near cones", NAP_CONE_LINE_HOLD) + cone_hold.set_value("On — keep your line after a push past cones") + + obstacle_chime = BigParamControl("live object detection chime", NAP_OBSTACLE_CHIME) + obstacle_chime.set_value("On — solid objects in the lane; animals or people near the road") + + one_pedal = BigParamControl("one-pedal long", NAP_ONE_PEDAL_LONG) + one_pedal.set_value("Off default — gas pause stays until SET") + + gap_lock = BigParamControl("gap lock", NAP_GAP_LOCK) + gap_lock.set_value("Off default — 2 s engage hold keeps radar meters") + + hypermile = BigParamControl("hypermile", NAP_HYPERMILE, toggle_callback=on_hypermile) + hypermile.set_value("Off default — early light eco, not max regen") + + step_down = BigParamControl("step down speed", NAP_HYPERMILE_STEP_DOWN) + step_down.set_value("Off — scaled drop, −15 at 80 when On") + step_down.set_visible(lambda: self._params.get_bool(NAP_HYPERMILE)) + + hill_climb = BigParamControl("hill climb", NAP_HYPERMILE_HILL_CLIMB) + hill_climb.set_value("On — grade hold on climbs; light crest ease") + hill_climb.set_visible(lambda: self._params.get_bool(NAP_HYPERMILE)) + + self._scroller.add_widgets([ + self._accel, + adaptive_accel, + self._follow_distance_city, + self._follow_distance_hwy, + self._turn_in_delay, + lat_handoff, + low_vis, + cone_hold, + obstacle_chime, + one_pedal, + gap_lock, + hypermile, + step_down, + hill_climb, + ]) + + def show_event(self): + super().show_event() + from openpilot.selfdrive.controls.lib.follow_distance import migrate_follow_distance_params + migrate_follow_distance_params(self._params) + self._accel.refresh() + self._follow_distance_city._load_value() + self._follow_distance_hwy._load_value() + self._turn_in_delay._load_value() + + +def open_driving_mannerisms_menu(page: DrivingMannerismsLayoutMici | None = None) -> DrivingMannerismsLayoutMici: + panel = page or DrivingMannerismsLayoutMici() + gui_app.push_widget(panel) + return panel diff --git a/selfdrive/ui/mici/layouts/settings/firehose.py b/selfdrive/ui/mici/layouts/settings/firehose.py new file mode 100644 index 00000000000000..66393de6795c18 --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/firehose.py @@ -0,0 +1,224 @@ +import requests +import threading +import time +import pyray as rl + +from openpilot.common.api import api_get +from openpilot.common.params import Params +from openpilot.common.realtime import drop_realtime +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.lib.api_helpers import get_token +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.lib.scroll_panel2 import GuiScrollPanel2 +from openpilot.system.ui.lib.multilang import tr, trn, tr_noop +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller import NavRawScrollPanel + +TITLE = tr_noop("Firehose Mode") +DESCRIPTION = tr_noop( + "openpilot learns to drive by watching humans, like you, drive.\n\n" + + "Firehose Mode allows you to maximize your training data uploads to improve " + + "openpilot's driving models. More data means bigger models, which means better Experimental Mode." +) +INSTRUCTIONS_INTRO = tr_noop( + "For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.\n\n" + + "Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card." +) +FAQ_HEADER = tr_noop("Frequently Asked Questions") +FAQ_ITEMS = [ + (tr_noop("Does it matter how or where I drive?"), tr_noop("Nope, just drive as you normally would.")), + (tr_noop("Do all of my segments get pulled in Firehose Mode?"), tr_noop("No, we selectively pull a subset of your segments.")), + (tr_noop("What's a good USB-C adapter?"), tr_noop("Any fast phone or laptop charger should be fine.")), + (tr_noop("Does it matter which software I run?"), tr_noop("Yes, only upstream openpilot (and particular forks) are able to be used for training.")), +] + + +class FirehoseLayoutBase(Widget): + PARAM_KEY = "ApiCache_FirehoseStats" + GREEN = rl.Color(46, 204, 113, 255) + RED = rl.Color(231, 76, 60, 255) + GRAY = rl.Color(68, 68, 68, 255) + LIGHT_GRAY = rl.Color(228, 228, 228, 255) + UPDATE_INTERVAL = 30 # seconds + + def __init__(self): + super().__init__() + self._params = Params() + self._session = requests.Session() # reuse session to reduce SSL handshake overhead + self._segment_count = self._get_segment_count() + + self._scroll_panel = GuiScrollPanel2(horizontal=False) + self._content_height = 0 + + self._running = True + self._update_thread = threading.Thread(target=self._update_loop, daemon=True) + self._update_thread.start() + + def __del__(self): + self._running = False + try: + if self._update_thread and self._update_thread.is_alive(): + self._update_thread.join(timeout=1.0) + except Exception: + pass + + def show_event(self): + super().show_event() + self._scroll_panel.set_offset(0) + + def _get_segment_count(self) -> int: + stats = self._params.get(self.PARAM_KEY) + if not stats: + return 0 + try: + return int(stats.get("firehose", 0)) + except Exception: + cloudlog.exception(f"Failed to decode firehose stats: {stats}") + return 0 + + def _render(self, rect: rl.Rectangle): + # compute total content height for scrolling + content_height = self._measure_content_height(rect) + scroll_offset = self._scroll_panel.update(rect, content_height) + + # start drawing with offset + x = rect.x + 40 + y = rect.y + 40 + scroll_offset + w = rect.width - 80 + + # Title + title_text = tr(TITLE) + title_font = gui_app.font(FontWeight.BOLD) + title_size = 64 + rl.draw_text_ex(title_font, title_text, rl.Vector2(x, y), title_size, 0, rl.WHITE) + y += int(title_size * FONT_SCALE) + 20 + + # Description + y = self._draw_wrapped_text(x, y, w, tr(DESCRIPTION), gui_app.font(FontWeight.ROMAN), 36, rl.WHITE) + y += 20 + + # Separator + rl.draw_rectangle_rec(rl.Rectangle(x, y, w, 2), self.GRAY) + y += 20 + + # Status + status_text, status_color = self._get_status() + y = self._draw_wrapped_text(x, y, w, status_text, gui_app.font(FontWeight.BOLD), 48, status_color) + y += 20 + + # Contribution count (if available) + if self._segment_count > 0: + contrib_text = trn("{} segment of your driving is in the training dataset so far.", + "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) + y = self._draw_wrapped_text(x, y, w, contrib_text, gui_app.font(FontWeight.BOLD), 42, rl.WHITE) + y += 20 + + # Separator + rl.draw_rectangle_rec(rl.Rectangle(x, y, w, 2), self.GRAY) + y += 20 + + # Instructions intro + y = self._draw_wrapped_text(x, y, w, tr(INSTRUCTIONS_INTRO), gui_app.font(FontWeight.ROMAN), 32, self.LIGHT_GRAY) + y += 20 + + # FAQ Header + y = self._draw_wrapped_text(x, y, w, tr(FAQ_HEADER), gui_app.font(FontWeight.BOLD), 44, rl.WHITE) + y += 20 + + # FAQ Items + for question, answer in FAQ_ITEMS: + y = self._draw_wrapped_text(x, y, w, tr(question), gui_app.font(FontWeight.BOLD), 32, self.LIGHT_GRAY) + y = self._draw_wrapped_text(x, y, w, tr(answer), gui_app.font(FontWeight.ROMAN), 32, self.LIGHT_GRAY) + y += 20 + + def _draw_wrapped_text(self, x, y, width, text, font, font_size, color): + wrapped = wrap_text(font, text, font_size, width) + for line in wrapped: + rl.draw_text_ex(font, line, rl.Vector2(x, y), font_size, 0, color) + y += int(font_size * FONT_SCALE) + return y + + def _measure_content_height(self, rect: rl.Rectangle) -> int: + # Rough measurement using the same wrapping as rendering + w = int(rect.width - 80) + y = 40 + + # Title + title_size = 72 + y += int(title_size * FONT_SCALE) + 20 + + # Description + desc_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(DESCRIPTION), 36, w) + y += int(len(desc_lines) * 36 * FONT_SCALE) + 20 + + # Separator + Status + y += 2 + 20 + status_text, _ = self._get_status() + status_lines = wrap_text(gui_app.font(FontWeight.BOLD), status_text, 48, w) + y += int(len(status_lines) * 48 * FONT_SCALE) + 20 + + # Contribution count + if self._segment_count > 0: + contrib_text = trn("{} segment of your driving is in the training dataset so far.", + "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) + contrib_lines = wrap_text(gui_app.font(FontWeight.BOLD), contrib_text, 42, w) + y += int(len(contrib_lines) * 42 * FONT_SCALE) + 20 + + # Separator + Instructions + y += 2 + 20 + + # Instructions intro + intro_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(INSTRUCTIONS_INTRO), 32, w) + y += int(len(intro_lines) * 32 * FONT_SCALE) + 20 + + # FAQ Header + faq_header_lines = wrap_text(gui_app.font(FontWeight.BOLD), tr(FAQ_HEADER), 44, w) + y += int(len(faq_header_lines) * 44 * FONT_SCALE) + 20 + + # FAQ Items + for question, answer in FAQ_ITEMS: + q_lines = wrap_text(gui_app.font(FontWeight.BOLD), tr(question), 32, w) + y += int(len(q_lines) * 32 * FONT_SCALE) + a_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(answer), 32, w) + y += int(len(a_lines) * 32 * FONT_SCALE) + 20 + + # bottom padding + y += 40 + return y + + def _get_status(self) -> tuple[str, rl.Color]: + network_type = ui_state.sm["deviceState"].networkType + network_metered = ui_state.sm["deviceState"].networkMetered + + if not network_metered and network_type != 0: # Not metered and connected + return tr("ACTIVE"), self.GREEN + else: + return tr("INACTIVE: connect to an unmetered network"), self.RED + + def _fetch_firehose_stats(self): + try: + dongle_id = self._params.get("DongleId") + if not dongle_id or dongle_id == UNREGISTERED_DONGLE_ID: + return + identity_token = get_token(dongle_id) + response = api_get(f"v1/devices/{dongle_id}/firehose_stats", access_token=identity_token, session=self._session) + if response.status_code == 200: + data = response.json() + self._segment_count = data.get("firehose", 0) + self._params.put(self.PARAM_KEY, data) + except Exception as e: + cloudlog.error(f"Failed to fetch firehose stats: {e}") + + def _update_loop(self): + drop_realtime() + while self._running: + if not ui_state.started and device._awake: + self._fetch_firehose_stats() + time.sleep(self.UPDATE_INTERVAL) + + +class FirehoseLayout(NavRawScrollPanel, FirehoseLayoutBase): + pass diff --git a/selfdrive/ui/mici/layouts/settings/hidden_toggles.py b/selfdrive/ui/mici/layouts/settings/hidden_toggles.py new file mode 100644 index 00000000000000..017b06ef8aa25a --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/hidden_toggles.py @@ -0,0 +1,108 @@ +"""mici overlay: Force Offroad + Simulate Look + False Alert Ignore. + +Opened by a triple-tap on the Settings **nap** button. Tap outside the +card to dismiss. Not shown on Driving Mannerisms or the main NAP list. +Simulate Look and False Alert Ignore are mutually exclusive. +""" +import pyray as rl + +from openpilot.common.params import Params +from openpilot.selfdrive.monitoring.dm_toggles import ( + apply_dm_false_alert_ignore, + apply_dm_simulate_looking, + read_exclusive_dm_toggles, +) +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + NAP_CONE_LINE_LOG, + NAP_DM_FALSE_ALERT_IGNORE, + NAP_DM_SIMULATE_LOOKING, + NAP_FORCE_OFFROAD, +) +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.hardware.nap_force_offroad import apply_force_offroad_toggle +from openpilot.system.ui.lib.application import MousePos +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.mici.widgets.button import BigParamControl + +DIM = rl.Color(0, 0, 0, 160) +CARD_BG = rl.Color(40, 40, 40, 255) +CARD_PAD = 16 + + +class HiddenTogglesOverlayMici(Widget): + """Thin full-screen overlay with the three hidden NAP toggles.""" + + def __init__(self): + super().__init__() + self._params = Params() + self._card_rect = rl.Rectangle(0, 0, 0, 0) + + # Must stay enabled while onroad — that is the point of Force Offroad. + self._offroad = BigParamControl("force offroad", NAP_FORCE_OFFROAD, + toggle_callback=self._on_force_offroad) + self._offroad.set_value("WARNING: stops OP — drive manually") + + self._dm = BigParamControl("simulate look", NAP_DM_SIMULATE_LOOKING, + toggle_callback=self._on_simulate_look) + self._dm.set_value("On — full awareness wipe in 1–3 s") + + self._fai = BigParamControl("false alert ignore", NAP_DM_FALSE_ALERT_IGNORE, + toggle_callback=self._on_false_alert_ignore) + self._fai.set_value("On — ignore false phone alerts") + + self._cone_log = BigParamControl("cone line log", NAP_CONE_LINE_LOG) + self._cone_log.set_value("On — log cones only, does not steer") + + def _on_force_offroad(self, state): + apply_force_offroad_toggle(self._params, bool(state), started=bool(ui_state.started)) + + def _on_simulate_look(self, state): + # Use apply() return — refresh()/get_bool can still show the old + # sibling On (put_bool is non-blocking) until the overlay is reopened. + _sim, fai = apply_dm_simulate_looking(self._params, bool(state)) + self._fai.set_checked(fai) + + def _on_false_alert_ignore(self, state): + sim, _fai = apply_dm_false_alert_ignore(self._params, bool(state)) + self._dm.set_checked(sim) + + def show_event(self): + super().show_event() + read_exclusive_dm_toggles(self._params) + self._dm.refresh() + self._fai.refresh() + self._offroad.refresh() + self._cone_log.refresh() + + def _layout(self): + w1, h1 = self._dm.rect.width, self._dm.rect.height + w2, h2 = self._offroad.rect.width, self._offroad.rect.height + w3, h3 = self._fai.rect.width, self._fai.rect.height + w4, h4 = self._cone_log.rect.width, self._cone_log.rect.height + inner_w = max(w1, w2, w3, w4) + inner_h = h1 + h2 + h3 + h4 + 3 * CARD_PAD + card_w = inner_w + 2 * CARD_PAD + card_h = inner_h + 2 * CARD_PAD + # Left-biased card so it reads as a side panel, not a full page. + x = self._rect.x + max(20, (self._rect.width - card_w) * 0.12) + y = self._rect.y + max(20, (self._rect.height - card_h) / 2) + self._card_rect = rl.Rectangle(x, y, card_w, card_h) + + def _handle_mouse_release(self, mouse_pos: MousePos) -> None: + if not rl.check_collision_point_rec(mouse_pos, self._card_rect): + self.dismiss() + + def _render(self, _): + rl.draw_rectangle_rec(self._rect, DIM) + rl.draw_rectangle_rounded(self._card_rect, 0.12, 10, CARD_BG) + + x = self._card_rect.x + CARD_PAD + y = self._card_rect.y + CARD_PAD + self._offroad.render(rl.Rectangle(x, y, self._offroad.rect.width, self._offroad.rect.height)) + y += self._offroad.rect.height + CARD_PAD + self._dm.render(rl.Rectangle(x, y, self._dm.rect.width, self._dm.rect.height)) + y += self._dm.rect.height + CARD_PAD + self._fai.render(rl.Rectangle(x, y, self._fai.rect.width, self._fai.rect.height)) + y += self._fai.rect.height + CARD_PAD + self._cone_log.render(rl.Rectangle(x, y, self._cone_log.rect.width, self._cone_log.rect.height)) + self._offroad.refresh() diff --git a/selfdrive/ui/mici/layouts/settings/map_speed.py b/selfdrive/ui/mici/layouts/settings/map_speed.py new file mode 100644 index 00000000000000..370da76d3d754f --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/map_speed.py @@ -0,0 +1,78 @@ +"""mici NAP submenu: Map Speed Limit controls.""" +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.big_multi_value_param import BigMultiValueParamToggle +from openpilot.selfdrive.ui.mici.widgets.button import BigButton +from openpilot.selfdrive.ui.mici.layouts.settings.nap_script import launch_script +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + DOWNLOAD_US_MAPS_INSTRUCTIONS, + MAP_SPEED_LOOKAHEAD, MAP_SPEED_LOOKAHEAD_LABELS, + MAP_SPEED_MODES, MAP_SPEED_MODE_LABELS, MAP_SPEED_OFFSETS_MPH, + REFRESH_MAPS_INSTRUCTIONS, +) +from openpilot.selfdrive.mapd.fetch_maps import installed_db_summary, installed_revision_summary +from openpilot.selfdrive.mapd.roundabout_status import installed_ring_summary +from openpilot.selfdrive.ui.ui_state import ui_state + + +class MapSpeedLimitLayoutMici(NavScroller): + def __init__(self): + super().__init__() + map_mode = BigMultiValueParamToggle( + "map speed (max)", + "NAPMapSpeedMode", + values=MAP_SPEED_MODES, + labels=[s.lower() for s in MAP_SPEED_MODE_LABELS], + default_value=0, + ) + map_offset = BigMultiValueParamToggle( + "map speed offset", + "NAPMapSpeedOffsetMph", + values=list(MAP_SPEED_OFFSETS_MPH), + labels=["-5 mph", "0", "+5 mph"], + default_value=0, + ) + map_lookahead = BigMultiValueParamToggle( + "lookahead", + "NAPMapSpeedLookahead", + values=list(MAP_SPEED_LOOKAHEAD), + labels=[s.lower() for s in MAP_SPEED_LOOKAHEAD_LABELS], + default_value=2, + ) + self._map_db_status = BigButton("osm map data", installed_db_summary()) + self._map_rings = BigButton("roundabouts", installed_ring_summary()) + self._map_revision = BigButton("map revision", installed_revision_summary()) + refresh_maps_btn = BigButton("refresh maps", "start") + refresh_maps_btn.set_click_callback( + lambda: launch_script("Refresh maps", REFRESH_MAPS_INSTRUCTIONS, + "scripts.nap.refresh_osm_maps", + )) + refresh_maps_btn.set_enabled(ui_state.is_offroad) + download_maps_btn = BigButton("download us maps", "start") + download_maps_btn.set_click_callback( + lambda: launch_script("Download US Maps", DOWNLOAD_US_MAPS_INSTRUCTIONS, + "scripts.nap.fetch_osm_maps", + )) + download_maps_btn.set_enabled(ui_state.is_offroad) + self._scroller.add_widgets([ + map_mode, + map_offset, + map_lookahead, + refresh_maps_btn, + download_maps_btn, + self._map_db_status, + self._map_rings, + self._map_revision, + ]) + + def show_event(self): + super().show_event() + self._map_db_status.set_value(installed_db_summary()) + self._map_rings.set_value(installed_ring_summary()) + self._map_revision.set_value(installed_revision_summary()) + + +def open_map_speed_limit_menu(page: MapSpeedLimitLayoutMici | None = None) -> MapSpeedLimitLayoutMici: + panel = page or MapSpeedLimitLayoutMici() + gui_app.push_widget(panel) + return panel diff --git a/selfdrive/ui/mici/layouts/settings/nap.py b/selfdrive/ui/mici/layouts/settings/nap.py new file mode 100644 index 00000000000000..5d5e2c4656ed67 --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/nap.py @@ -0,0 +1,355 @@ +"""NAP settings panel for the comma 4 / mici UI tree. + +Mirrors selfdrive/ui/layouts/settings/nap.py for the BigButton/NavScroller +vocabulary used on the comma 4. Phase 1 stub: three controls (pedal +interceptor toggle, radar enabled toggle, flash EPAS button). +Subsequent phases add the rest. +""" +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.big_multi_value_param import BigMultiValueParamToggle +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigParamControl +from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, BigDialog, BigInputDialog +from openpilot.selfdrive.ui.mici.layouts.settings.nap_script import launch_script +from openpilot.selfdrive.ui.layouts.settings.nap_content import ( + BACKUP_EPAS_INSTRUCTIONS, + CALIBRATE_PEDAL_INSTRUCTIONS, + FLASH_EPAS_INSTRUCTIONS, + HIGH_LOW_BEAM_LABELS, + HIGH_LOW_BEAM_VALUES, + PEDAL_CAN_BUS_VALUES, + RADAR_OFFSET_MAX, + RADAR_OFFSET_MIN, + RESTORE_EPAS_INSTRUCTIONS, + INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS, + NAP_SPEED_SIGN_LOG, + WIPER_SPEED_LABELS, + WIPER_SPEED_VALUES, + WIPER_SENSITIVITY_DEFAULT, + WIPER_SENSITIVITY_LABELS, + WIPER_SENSITIVITY_VALUES, +) +from openpilot.selfdrive.ui.mici.layouts.settings.driving_mannerisms import DrivingMannerismsLayoutMici +from openpilot.selfdrive.ui.mici.layouts.settings.map_speed import MapSpeedLimitLayoutMici +# Button value is install_status_summary. weights_status_summary is the weights-only label. +from openpilot.selfdrive.speedsignd.install import install_status_summary +from openpilot.selfdrive.car.tesla.preap_body_controls import ( + NAP_HIGH_LOW_BEAM, + NAP_WIPER_SENSITIVITY, + NAP_WIPER_SPEED, + register_nap_body_params, +) +from openpilot.selfdrive.ui.radar.radar_view import RadarMonitorDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from opendbc.car.tesla.preap.nap_params import NAPParamKeys + +register_nap_body_params() + + +def _reboot_dialog() -> None: + def confirm(): + Params().put_bool("DoReboot", True) + icon = gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70) + gui_app.push_widget(BigConfirmationDialog("slide to\nreboot now", icon, confirm)) + + +def _reboot_on_toggle(_): + _reboot_dialog() + + +def _confirm_then_flash(slider_title: str, runner_title: str, instructions: str, module: str): + """Slide-to-confirm dialog before launching a destructive EPAS script. + + Adds a deliberate gesture before an irreversible firmware operation. + Read-only operations (extract, calibration, test) skip this. + """ + def confirm(): + launch_script(runner_title, instructions, module) + icon = gui_app.texture("icons_mici/buttons/button_circle_red.png", 180, 180) + gui_app.push_widget(BigConfirmationDialog(slider_title, icon, confirm, red=True)) + + +class RadarSettingsLayoutMici(NavScroller): + def __init__(self): + super().__init__() + self._params = Params() + + radar_enabled = BigParamControl("radar enabled", NAPParamKeys.RADAR_ENABLED, + toggle_callback=_reboot_on_toggle) + radar_enabled.set_enabled(ui_state.is_offroad) + + ignore_hw_fail = BigParamControl("ignore radar hardware fail", NAPParamKeys.RADAR_IGNORE_HW_FAIL) + + def on_radar_hud(checked): + ui_state.radar_hud = checked + + radar_hud = BigParamControl("radar HUD", NAPParamKeys.RADAR_HUD, toggle_callback=on_radar_hud) + + radar_offset_btn = BigButton("radar lateral offset", self._radar_offset_label()) + radar_offset_btn.set_click_callback(lambda: self._open_radar_offset_input(radar_offset_btn)) + + donor_vin_btn = BigButton("donor radar vin", self._radar_vin_label()) + donor_vin_btn.set_click_callback(lambda: self._open_radar_vin_input(donor_vin_btn)) + + read_vin_btn = BigButton("read vin", self._read_vin_label()) + read_vin_btn.set_click_callback(lambda: self._on_read_vin(read_vin_btn)) + + radar_position = BigMultiValueParamToggle( + "donor radar position", + NAPParamKeys.RADAR_POSITION, + values=[0, 1, 2], + labels=["0", "1", "2"], + default_value=0, + ) + + radar_epas = BigMultiValueParamToggle( + "donor epas type", + NAPParamKeys.RADAR_EPAS_TYPE, + values=[0, 1, 2, 3, 4], + labels=["0", "1", "2", "3", "4"], + default_value=0, + ) + + live_radar_btn = BigButton("live radar", "open") + live_radar_btn.set_click_callback(lambda: gui_app.push_widget(RadarMonitorDialog())) + + self._scroller.add_widgets([ + radar_enabled, + ignore_hw_fail, + radar_hud, + radar_offset_btn, + donor_vin_btn, + read_vin_btn, + radar_position, + radar_epas, + live_radar_btn, + ]) + + def _radar_offset_label(self) -> str: + raw = self._params.get(NAPParamKeys.RADAR_OFFSET, return_default=True) + try: + return f"{float(raw or 0):+.2f}m" + except (TypeError, ValueError): + return "+0.00m" + + def _radar_vin_label(self) -> str: + raw = self._params.get(NAPParamKeys.RADAR_DONOR_VIN, return_default=True) or "" + if isinstance(raw, bytes): + raw = raw.decode("ascii", errors="ignore") + vin = "".join(ch for ch in str(raw).upper() if ch.isalnum()) + return vin if len(vin) == 17 else "not set" + + def _read_vin_label(self) -> str: + return "reading..." if self._params.get_bool(NAPParamKeys.RADAR_READ_VIN) else "read" + + def _open_radar_offset_input(self, btn: BigButton) -> None: + raw = self._params.get(NAPParamKeys.RADAR_OFFSET, return_default=True) + try: + default_text = f"{float(raw or 0):.2f}" + except (TypeError, ValueError): + default_text = "0.00" + + def on_confirm(text: str) -> None: + try: + v = float(text) + except (TypeError, ValueError): + return + v = max(RADAR_OFFSET_MIN, min(RADAR_OFFSET_MAX, v)) + try: + self._params.put(NAPParamKeys.RADAR_OFFSET, v) + except Exception: + return + btn.set_value(self._radar_offset_label()) + + gui_app.push_widget(BigInputDialog( + f"radar offset (m, {RADAR_OFFSET_MIN} to {RADAR_OFFSET_MAX})", + default_text=default_text, + confirm_callback=on_confirm, + )) + + def _open_radar_vin_input(self, btn: BigButton) -> None: + current = self._radar_vin_label() + + def on_confirm(text: str) -> None: + vin = "".join(ch for ch in (text or "").upper() if ch.isalnum()) + try: + self._params.put(NAPParamKeys.RADAR_DONOR_VIN, vin if len(vin) == 17 else "") + except Exception: + return + btn.set_value(self._radar_vin_label()) + + gui_app.push_widget(BigInputDialog( + "donor radar vin", + default_text="" if current == "not set" else current, + minimum_length=0, + confirm_callback=on_confirm, + )) + + def _on_read_vin(self, btn: BigButton) -> None: + if ui_state.engaged: + gui_app.push_widget(BigDialog("disengage first", "VIN read is blocked while engaged.")) + return + + def confirm(): + self._params.put_bool(NAPParamKeys.RADAR_READ_VIN, True) + btn.set_value(self._read_vin_label()) + + icon = gui_app.texture("icons_mici/buttons/button_circle_red.png", 180, 180) + gui_app.push_widget(BigConfirmationDialog("slide to\nread vin", icon, confirm)) + + +class NAPLayoutMici(NavScroller): + def __init__(self): + super().__init__() + self._params = Params() + self._params.put_bool(NAPParamKeys.FORCE_PRE_AP, True) + + # set_enabled accepts bool | Callable[[], bool]. Pass methods directly + # (e.g. ui_state.is_offroad), NOT lambdas-wrapping-methods. The form + # `lambda: ui_state.is_offroad` returns the bound method object — + # always truthy — and silently leaves destructive actions clickable + # while onroad. + + # Force Offroad / simulate look / false alert ignore live in the nap triple-tap overlay. + + # ── Longitudinal control ───────────────────────── + pedal_enabled = BigParamControl("pedal interceptor", NAPParamKeys.PEDAL_ENABLED, + toggle_callback=_reboot_on_toggle) + pedal_enabled.set_enabled(ui_state.is_offroad) + + self._driving_mannerisms_page = DrivingMannerismsLayoutMici() + driving_mannerisms_btn = BigButton("driving mannerisms", "open") + driving_mannerisms_btn.set_click_callback(lambda: gui_app.push_widget(self._driving_mannerisms_page)) + + self._map_speed_page = MapSpeedLimitLayoutMici() + map_speed_btn = BigButton("map speed limit", "open") + map_speed_btn.set_click_callback(lambda: gui_app.push_widget(self._map_speed_page)) + + speed_sign_log = BigParamControl("speed sign logger", NAP_SPEED_SIGN_LOG) + + self._weights_status = BigButton("speed sign weights", install_status_summary()) + install_weights_btn = BigButton("install weights", "start") + install_weights_btn.set_click_callback( + lambda: launch_script("Install weights", INSTALL_SPEED_SIGN_WEIGHTS_INSTRUCTIONS, + "scripts.nap.install_speed_sign_weights", + )) + install_weights_btn.set_enabled(ui_state.is_offroad) + + # ── Pedal hardware ─────────────────────────────── + # default_value=2 matches NAPPedalCanBus declared default in params_keys.h + # and the runtime fallback ("any nonzero is bus 2"). If the param is set + # to an out-of-range value (1, etc.), the widget rewrites it to 2 rather + # than render bus 0 while the runtime acts as bus 2. + pedal_can_bus = BigMultiValueParamToggle( + "pedal can bus", + NAPParamKeys.PEDAL_CAN_BUS, + values=PEDAL_CAN_BUS_VALUES, + labels=["bus 0", "bus 2"], + default_value=2, + toggle_callback=_reboot_on_toggle, + ) + pedal_can_bus.set_enabled(ui_state.is_offroad) + + pedal_calib_status = BigButton( + "pedal calibration", + "calibrated" if self._params.get_bool(NAPParamKeys.PEDAL_CALIB_DONE) else "not calibrated", + ) + + # Offroad-gate the menu tap on all action buttons. Stationary scripts + # still need ignition on at Start press, but the user's path is + # "tap offroad → open runner → turn car on → press Start." Gating + # the menu tap on offroad just means the user can't open the runner + # while actively driving; the script's own preconditions handle the + # ignition-on state at Start. + calibrate_pedal_btn = BigButton("calibrate pedal", "start") + calibrate_pedal_btn.set_click_callback( + lambda: launch_script("Pedal Calibration", CALIBRATE_PEDAL_INSTRUCTIONS, + "scripts.nap.calibrate_pedal", + )) + calibrate_pedal_btn.set_enabled(ui_state.is_offroad) + + radar_settings_btn = BigButton("radar settings", "open") + radar_settings_btn.set_click_callback(lambda: gui_app.push_widget(RadarSettingsLayoutMici())) + + # ── iBooster (locked off) ──────────────────────── + wiper_control = BigMultiValueParamToggle( + "wiper control", + NAP_WIPER_SPEED, + values=WIPER_SPEED_VALUES, + labels=WIPER_SPEED_LABELS, + default_value=0, + ) + + wiper_sensitivity = BigMultiValueParamToggle( + "wiper sensitivity", + NAP_WIPER_SENSITIVITY, + values=WIPER_SENSITIVITY_VALUES, + labels=WIPER_SENSITIVITY_LABELS, + default_value=WIPER_SENSITIVITY_DEFAULT, + ) + + high_low_beam = BigMultiValueParamToggle( + "high / low beam", + NAP_HIGH_LOW_BEAM, + values=HIGH_LOW_BEAM_VALUES, + labels=HIGH_LOW_BEAM_LABELS, + default_value=0, + ) + + ibooster_enabled = BigParamControl("ibooster enabled", NAPParamKeys.IBOOSTER_ENABLED) + ibooster_enabled.set_enabled(False) + + # ── Advanced (locked on) ───────────────────────── + force_pre_ap = BigParamControl("force pre-ap mode", NAPParamKeys.FORCE_PRE_AP) + force_pre_ap.set_enabled(False) + + # ── Actions ────────────────────────────────────── + backup_epas_btn = BigButton("backup epas", "extract") + backup_epas_btn.set_click_callback( + lambda: launch_script("Backup EPAS Firmware", BACKUP_EPAS_INSTRUCTIONS, + "scripts.nap.extract_epas", + )) + backup_epas_btn.set_enabled(ui_state.is_offroad) + + flash_epas_btn = BigButton("flash epas", "flash") + flash_epas_btn.set_click_callback( + lambda: _confirm_then_flash( + "slide to\nflash epas", + "Flash EPAS Firmware", FLASH_EPAS_INSTRUCTIONS, "scripts.nap.flash_epas", + )) + flash_epas_btn.set_enabled(ui_state.is_offroad) + + restore_epas_btn = BigButton("restore epas", "restore") + restore_epas_btn.set_click_callback( + lambda: _confirm_then_flash( + "slide to\nrestore epas", + "Restore EPAS Firmware", RESTORE_EPAS_INSTRUCTIONS, "scripts.nap.restore_epas", + )) + restore_epas_btn.set_enabled(ui_state.is_offroad) + + self._scroller.add_widgets([ + speed_sign_log, + self._weights_status, + install_weights_btn, + pedal_enabled, + driving_mannerisms_btn, + map_speed_btn, + pedal_can_bus, + pedal_calib_status, + calibrate_pedal_btn, + radar_settings_btn, + wiper_control, + wiper_sensitivity, + high_low_beam, + ibooster_enabled, + force_pre_ap, + backup_epas_btn, + flash_epas_btn, + restore_epas_btn, + ]) + + def show_event(self): + super().show_event() + self._weights_status.set_value(install_status_summary()) + diff --git a/selfdrive/ui/mici/layouts/settings/nap_script.py b/selfdrive/ui/mici/layouts/settings/nap_script.py new file mode 100644 index 00000000000000..d586e349b6f46d --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/nap_script.py @@ -0,0 +1,126 @@ +"""Launch helper for NAP scripts (pedal calibration, EPAS flash, maps). + +Hardware tools spawn scripts/nap/run_script.py as a detached process. That +runner kills the comma tmux session, takes over the display, and uses +NAPScriptRunning so manager stops pandad for Panda USB. + +Map sqlite jobs (Refresh maps, Download US Maps) and Install speed-sign +weights stay in-process: a full-screen script-runner widget is pushed so +Settings is not drawn underneath. Exit pops back to Settings. +""" +from __future__ import annotations + +import os +import signal +import subprocess +import threading + +from openpilot.common.basedir import BASEDIR +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.mici.widgets.script_runner_app import MiciScriptRunnerApp, ScriptState +from openpilot.system.ui.widgets import Widget +from scripts.nap.script_lifecycle import script_reboots_on_exit + + +class _MapScriptOverlay(Widget): + """Opaque full-screen map-script UI. Settings under this widget is not shown.""" + + def __init__(self, title: str, instructions: str, module: str): + super().__init__() + self._module = module + self._process: subprocess.Popen | None = None + self._reader_thread: threading.Thread | None = None + self._prepared = False + self._app = MiciScriptRunnerApp( + title=title, + instructions=instructions, + on_start=self._on_start, + on_exit=self._on_exit, + ) + + def show_event(self): + if not self._prepared: + self._app.prepare() + self._prepared = True + + def _render(self, _rect): + self._app.render_overlay() + + def _on_start(self) -> None: + try: + self._process = subprocess.Popen( + ["python", "-m", self._module], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=BASEDIR, + text=True, + encoding="utf-8", + bufsize=1, + ) + except Exception as e: + self._app.append_output(f"Error starting script: {e}") + self._app.set_state(ScriptState.ERROR) + return + self._app.append_output("Starting script...") + self._app.set_state(ScriptState.RUNNING) + self._reader_thread = threading.Thread(target=self._read_output, daemon=True) + self._reader_thread.start() + + def _read_output(self) -> None: + try: + assert self._process is not None + if self._process.stdout is not None: + for line in iter(self._process.stdout.readline, ''): + if line: + self._app.append_output(line.rstrip()) + if self._process.poll() is not None: + break + return_code = self._process.wait() + if return_code == 0: + self._app.append_output("") + self._app.append_output("[Script completed successfully]") + self._app.set_state(ScriptState.COMPLETED) + else: + self._app.append_output("") + self._app.append_output(f"[Script exited with code {return_code}]") + self._app.set_state(ScriptState.ERROR) + except Exception as e: + self._app.append_output(f"[Error reading output: {e}]") + self._app.set_state(ScriptState.ERROR) + + def _on_exit(self) -> None: + if self._process is not None and self._process.poll() is None: + self._process.send_signal(signal.SIGINT) + try: + self._process.wait(timeout=5) + except subprocess.TimeoutExpired: + self._process.terminate() + try: + self._process.wait(timeout=2) + except subprocess.TimeoutExpired: + self._process.kill() + try: + self._process.wait(timeout=2) + except subprocess.TimeoutExpired: + self._app.append_output("[ERROR] script did not exit") + self._app.set_state(ScriptState.ERROR) + return + gui_app.pop_widget() + + +def launch_script(title: str, instructions: str, script_module: str) -> None: + """Show a map job in-process, or spawn run_script.py for hardware tools.""" + if not script_reboots_on_exit(script_module): + gui_app.push_widget(_MapScriptOverlay(title, instructions, script_module)) + return + + script_path = os.path.join(BASEDIR, "scripts", "nap", "run_script.py") + log_path = "/tmp/nap_script_runner.log" + with open(log_path, "w") as log_file: + subprocess.Popen( + ["python", script_path, title, script_module, instructions], + cwd=BASEDIR, + start_new_session=True, + stdout=log_file, + stderr=log_file, + ) diff --git a/selfdrive/ui/mici/layouts/settings/network/__init__.py b/selfdrive/ui/mici/layouts/settings/network/__init__.py new file mode 100644 index 00000000000000..ddbab4b478cb24 --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/network/__init__.py @@ -0,0 +1,60 @@ +import pyray as rl + +from openpilot.selfdrive.ui.mici.layouts.settings.network.wifi_ui import WifiIcon +from openpilot.selfdrive.ui.mici.widgets.button import BigButton +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.wifi_manager import WifiManager, ConnectStatus, SecurityType, normalize_ssid + + +class WifiNetworkButton(BigButton): + def __init__(self, wifi_manager: WifiManager): + self._wifi_manager = wifi_manager + self._lock_txt = gui_app.texture("icons_mici/settings/network/new/lock.png", 28, 36) + self._draw_lock = False + + self._wifi_slash_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_slash.png", 64, 56) + self._wifi_low_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_low.png", 64, 47) + self._wifi_medium_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_medium.png", 64, 47) + self._wifi_full_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 64, 47) + + super().__init__("wi-fi", "not connected", self._wifi_slash_txt, scroll=True) + + def _update_state(self): + super()._update_state() + + # Update wi-fi button with ssid and ip address + # TODO: make sure we handle hidden ssids + wifi_state = self._wifi_manager.wifi_state + display_network = next((n for n in self._wifi_manager.networks if n.ssid == wifi_state.ssid), None) + if wifi_state.status == ConnectStatus.CONNECTING: + self.set_text(normalize_ssid(wifi_state.ssid or "wi-fi")) + self.set_value("starting" if self._wifi_manager.is_tethering_active() else "connecting...") + elif wifi_state.status == ConnectStatus.CONNECTED: + self.set_text(normalize_ssid(wifi_state.ssid or "wi-fi")) + self.set_value(self._wifi_manager.ipv4_address or "obtaining IP...") + else: + display_network = None + self.set_text("wi-fi") + self.set_value("not connected") + + if display_network is not None: + strength = WifiIcon.get_strength_icon_idx(display_network.strength) + self.set_icon(self._wifi_full_txt if strength == 2 else self._wifi_medium_txt if strength == 1 else self._wifi_low_txt) + self._draw_lock = display_network.security_type not in (SecurityType.OPEN, SecurityType.UNSUPPORTED) + elif self._wifi_manager.is_tethering_active(): + # takes a while to get Network + self.set_icon(self._wifi_full_txt) + self._draw_lock = True + else: + self.set_icon(self._wifi_slash_txt) + self._draw_lock = False + + def _draw_content(self, btn_y: float): + super()._draw_content(btn_y) + # Render lock icon at lower right of wifi icon if secured + if self._draw_lock: + icon_x = self._rect.x + self._rect.width - 30 - self._txt_icon.width + icon_y = btn_y + 30 + lock_x = icon_x + self._txt_icon.width - self._lock_txt.width + 7 + lock_y = icon_y + self._txt_icon.height - self._lock_txt.height + 8 + rl.draw_texture_ex(self._lock_txt, (lock_x, lock_y), 0.0, 1.0, rl.WHITE) diff --git a/selfdrive/ui/mici/layouts/settings/network/network_layout.py b/selfdrive/ui/mici/layouts/settings/network/network_layout.py new file mode 100644 index 00000000000000..58b3d0c77dceeb --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/network/network_layout.py @@ -0,0 +1,141 @@ +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.layouts.settings.network import WifiNetworkButton +from openpilot.selfdrive.ui.mici.layouts.settings.network.wifi_ui import WifiUIMici +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigMultiToggle, BigParamControl, BigToggle +from openpilot.selfdrive.ui.mici.widgets.dialog import BigInputDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.lib.prime_state import PrimeType +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.wifi_manager import WifiManager, Network, MeteredType + + +class NetworkLayoutMici(NavScroller): + def __init__(self): + super().__init__() + + self._wifi_manager = WifiManager() + self._wifi_manager.set_active(False) + self._wifi_ui = WifiUIMici(self._wifi_manager) + + self._wifi_manager.add_callbacks( + networks_updated=self._on_network_updated, + ) + + # ******** Tethering ******** + def tethering_toggle_callback(checked: bool): + self._tethering_toggle_btn.set_enabled(False) + self._tethering_password_btn.set_enabled(False) + self._network_metered_btn.set_enabled(False) + self._wifi_manager.set_tethering_active(checked) + + self._tethering_toggle_btn = BigToggle("enable tethering", "", toggle_callback=tethering_toggle_callback) + + def tethering_password_callback(password: str): + if password: + self._tethering_toggle_btn.set_enabled(False) + self._tethering_password_btn.set_enabled(False) + self._wifi_manager.set_tethering_password(password) + + def tethering_password_clicked(): + tethering_password = self._wifi_manager.tethering_password + dlg = BigInputDialog("enter password...", tethering_password, minimum_length=8, + confirm_callback=tethering_password_callback) + gui_app.push_widget(dlg) + + txt_tethering = gui_app.texture("icons_mici/settings/network/tethering.png", 64, 54) + self._tethering_password_btn = BigButton("tethering password", "", txt_tethering) + self._tethering_password_btn.set_click_callback(tethering_password_clicked) + + # ******** Network Metered ******** + def network_metered_callback(value: str): + self._network_metered_btn.set_enabled(False) + metered = { + 'default': MeteredType.UNKNOWN, + 'metered': MeteredType.YES, + 'unmetered': MeteredType.NO + }.get(value, MeteredType.UNKNOWN) + self._wifi_manager.set_current_network_metered(metered) + + # TODO: signal for current network metered type when changing networks, this is wrong until you press it once + # TODO: disable when not connected + self._network_metered_btn = BigMultiToggle("network usage", ["default", "metered", "unmetered"], select_callback=network_metered_callback) + self._network_metered_btn.set_enabled(False) + + self._wifi_button = WifiNetworkButton(self._wifi_manager) + self._wifi_button.set_click_callback(lambda: gui_app.push_widget(self._wifi_ui)) + + # ******** Advanced settings ******** + # ******** Roaming toggle ******** + self._roaming_btn = BigParamControl("enable roaming", "GsmRoaming") + + # ******** APN settings ******** + self._apn_btn = BigButton("apn settings", "edit") + self._apn_btn.set_click_callback(self._edit_apn) + + # ******** Cellular metered toggle ******** + self._cellular_metered_btn = BigParamControl("cellular metered", "GsmMetered") + + # Main scroller ---------------------------------- + self._scroller.add_widgets([ + self._wifi_button, + self._network_metered_btn, + self._tethering_toggle_btn, + self._tethering_password_btn, + # /* Advanced settings + self._roaming_btn, + self._apn_btn, + self._cellular_metered_btn, + # */ + ]) + + def _update_state(self): + super()._update_state() + + # If not using prime SIM, show GSM settings and enable IPv4 forwarding + show_cell_settings = ui_state.prime_state.get_type() in (PrimeType.NONE, PrimeType.LITE) + self._wifi_manager.set_ipv4_forward(show_cell_settings) + self._roaming_btn.set_visible(show_cell_settings) + self._apn_btn.set_visible(show_cell_settings) + self._cellular_metered_btn.set_visible(show_cell_settings) + + def show_event(self): + super().show_event() + self._wifi_manager.set_active(True) + + # Process wifi callbacks while at any point in the nav stack + gui_app.add_nav_stack_tick(self._wifi_manager.process_callbacks) + + def hide_event(self): + super().hide_event() + self._wifi_manager.set_active(False) + + gui_app.remove_nav_stack_tick(self._wifi_manager.process_callbacks) + + def _edit_apn(self): + def update_apn(apn: str): + apn = apn.strip() + if apn == "": + ui_state.params.remove("GsmApn") + else: + ui_state.params.put("GsmApn", apn) + + current_apn = ui_state.params.get("GsmApn") or "" + dlg = BigInputDialog("enter APN...", current_apn, minimum_length=0, confirm_callback=update_apn) + gui_app.push_widget(dlg) + + def _on_network_updated(self, networks: list[Network]): + # Update tethering state + tethering_active = self._wifi_manager.is_tethering_active() + # TODO: use real signals (like activated/settings changed, etc.) to speed up re-enabling buttons + self._tethering_toggle_btn.set_enabled(True) + self._tethering_password_btn.set_enabled(True) + self._network_metered_btn.set_enabled(lambda: not tethering_active and bool(self._wifi_manager.ipv4_address)) + self._tethering_toggle_btn.set_checked(tethering_active) + + # Update network metered + self._network_metered_btn.set_value( + { + MeteredType.UNKNOWN: 'default', + MeteredType.YES: 'metered', + MeteredType.NO: 'unmetered' + }.get(self._wifi_manager.current_network_metered, 'default')) diff --git a/selfdrive/ui/mici/layouts/settings/network/wifi_ui.py b/selfdrive/ui/mici/layouts/settings/network/wifi_ui.py new file mode 100644 index 00000000000000..8404faf9f7e6cc --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/network/wifi_ui.py @@ -0,0 +1,391 @@ +import math +import numpy as np +import pyray as rl +from collections.abc import Callable + +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.mici.widgets.dialog import BigInputDialog, BigConfirmationDialog +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, LABEL_COLOR +from openpilot.system.ui.lib.application import gui_app, MousePos, FontWeight +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.system.ui.lib.wifi_manager import WifiManager, Network, SecurityType, normalize_ssid + + +class LoadingAnimation(Widget): + RADIUS = 8 + SPACING = 24 # center-to-center: diameter (16) + gap (8) + Y_MAG = 11.2 + + def __init__(self): + super().__init__() + w = self.SPACING * 2 + self.RADIUS * 2 + h = self.RADIUS * 2 + int(self.Y_MAG) + self.set_rect(rl.Rectangle(0, 0, w, h)) + + def _render(self, _): + # Balls rest at bottom center; bounce upward + base_x = int(self._rect.x + self._rect.width / 2) + base_y = int(self._rect.y + self._rect.height - self.RADIUS) + + for i in range(3): + x = base_x + (i - 1) * self.SPACING + y = int(base_y + min(math.sin((rl.get_time() - i * 0.2) * 4) * self.Y_MAG, 0)) + alpha = int(np.interp(base_y - y, [0, self.Y_MAG], [255 * 0.45, 255 * 0.9])) + rl.draw_circle(x, y, self.RADIUS, rl.Color(255, 255, 255, alpha)) + + +class WifiIcon(Widget): + def __init__(self, network: Network): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 48 + 5, 36 + 5)) + + self._wifi_slash_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_slash.png", 48, 42) + self._wifi_low_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_low.png", 48, 36) + self._wifi_medium_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_medium.png", 48, 36) + self._wifi_full_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 48, 36) + self._lock_txt = gui_app.texture("icons_mici/settings/network/new/lock.png", 21, 27) + + self._network: Network = network + self._network_missing = False # if network disappeared from scan results + + def update_network(self, network: Network): + self._network = network + + def set_network_missing(self, missing: bool): + self._network_missing = missing + + @staticmethod + def get_strength_icon_idx(strength: int) -> int: + return round(strength / 100 * 2) + + def _render(self, _): + # Determine which wifi strength icon to use + strength = self.get_strength_icon_idx(self._network.strength) + if self._network_missing: + strength_icon = self._wifi_slash_txt + elif strength == 2: + strength_icon = self._wifi_full_txt + elif strength == 1: + strength_icon = self._wifi_medium_txt + else: + strength_icon = self._wifi_low_txt + + rl.draw_texture_ex(strength_icon, (self._rect.x, self._rect.y + self._rect.height - strength_icon.height), 0.0, 1.0, rl.WHITE) + + # Render lock icon at lower right of wifi icon if secured + if self._network.security_type not in (SecurityType.OPEN, SecurityType.UNSUPPORTED): + lock_x = self._rect.x + self._rect.width - self._lock_txt.width + lock_y = self._rect.y + self._rect.height - self._lock_txt.height + 6 + rl.draw_texture_ex(self._lock_txt, (lock_x, lock_y), 0.0, 1.0, rl.WHITE) + + +class WifiButton(BigButton): + LABEL_PADDING = 98 + LABEL_WIDTH = 402 - 98 - 28 # button width - left padding - right padding + SUB_LABEL_WIDTH = 402 - BigButton.LABEL_HORIZONTAL_PADDING * 2 + + def __init__(self, network: Network, wifi_manager: WifiManager): + super().__init__(normalize_ssid(network.ssid), scroll=True) + + self._network = network + self._wifi_manager = wifi_manager + + self._wifi_icon = WifiIcon(network) + self._forget_btn = ForgetButton(self._forget_network) + self._check_txt = gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 32, 32) + + # Eager state (not sourced from Network) + self._network_missing = False + self._network_forgetting = False + self._wrong_password = False + + def update_network(self, network: Network): + self._network = network + self._wifi_icon.update_network(network) + + # We can assume network is not missing if got new Network + self._network_missing = False + self._wifi_icon.set_network_missing(False) + if self._is_connected or self._is_connecting: + self._wrong_password = False + + @property + def network_forgetting(self) -> bool: + return self._network_forgetting + + def _forget_network(self): + if self._network_forgetting: + return + + self._network_forgetting = True + self._wifi_manager.forget_connection(self._network.ssid) + + def on_forgotten(self): + self._network_forgetting = False + + def set_network_missing(self, missing: bool): + self._network_missing = missing + self._wifi_icon.set_network_missing(missing) + + def set_wrong_password(self): + self._wrong_password = True + self.trigger_shake() + + @property + def network(self) -> Network: + return self._network + + @property + def _show_forget_btn(self): + if self._network.is_tethering or self._network_forgetting: + return False + + return (self._is_saved and not self._wrong_password) or self._is_connecting + + def _handle_mouse_release(self, mouse_pos: MousePos): + if self._show_forget_btn and rl.check_collision_point_rec(mouse_pos, self._forget_btn.rect): + return + super()._handle_mouse_release(mouse_pos) + + def _get_label_font_size(self): + return 48 + + def _draw_content(self, btn_y: float): + self._label.set_color(LABEL_COLOR) + label_rect = rl.Rectangle(self._rect.x + self.LABEL_PADDING, btn_y + self.LABEL_VERTICAL_PADDING, + self.LABEL_WIDTH, self._rect.height - self.LABEL_VERTICAL_PADDING * 2) + self._label.render(label_rect) + + if self.value: + sub_label_x = self._rect.x + self.LABEL_HORIZONTAL_PADDING + label_y = btn_y + self._rect.height - self.LABEL_VERTICAL_PADDING + sub_label_w = self.SUB_LABEL_WIDTH - (self._forget_btn.rect.width if self._show_forget_btn else 0) + sub_label_height = self._sub_label.get_content_height(sub_label_w) + + if self._is_connected and not self._network_forgetting: + check_y = int(label_y - sub_label_height + (sub_label_height - self._check_txt.height) / 2) + rl.draw_texture_ex(self._check_txt, rl.Vector2(sub_label_x, check_y), 0.0, 1.0, rl.Color(255, 255, 255, int(255 * 0.9 * 0.65))) + sub_label_x += self._check_txt.width + 14 + + sub_label_rect = rl.Rectangle(sub_label_x, label_y - sub_label_height, sub_label_w, sub_label_height) + self._sub_label.render(sub_label_rect) + + # Wifi icon + self._wifi_icon.render(rl.Rectangle( + self._rect.x + 30, + btn_y + 30, + self._wifi_icon.rect.width, + self._wifi_icon.rect.height, + )) + + # Forget button + if self._show_forget_btn: + self._forget_btn.render(rl.Rectangle( + self._rect.x + self._rect.width - self._forget_btn.rect.width, + btn_y + self._rect.height - self._forget_btn.rect.height, + self._forget_btn.rect.width, + self._forget_btn.rect.height, + )) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(lambda: touch_callback() and not self._forget_btn.is_pressed) + self._forget_btn.set_touch_valid_callback(touch_callback) + + @property + def _is_saved(self): + return self._wifi_manager.is_connection_saved(self._network.ssid) + + @property + def _is_connecting(self): + return self._wifi_manager.connecting_to_ssid == self._network.ssid + + @property + def _is_connected(self): + return self._wifi_manager.connected_ssid == self._network.ssid + + def _update_state(self): + super()._update_state() + + if any((self._network_missing, self._is_connecting, self._is_connected, self._network_forgetting, + self._network.security_type == SecurityType.UNSUPPORTED)): + self.set_enabled(False) + self._sub_label.set_color(rl.Color(255, 255, 255, int(255 * 0.585))) + self._sub_label.set_font_weight(FontWeight.ROMAN) + + if self._network_forgetting: + self.set_value("forgetting...") + elif self._is_connecting: + self.set_value("starting..." if self._network.is_tethering else "connecting...") + elif self._is_connected: + self.set_value("tethering" if self._network.is_tethering else "connected") + elif self._network_missing: + # after connecting/connected since NM will still attempt to connect/stay connected for a while + self.set_value("not in range") + else: + self.set_value("unsupported") + + else: # saved, wrong password, or unknown + self.set_value("wrong password" if self._wrong_password else "connect") + self.set_enabled(True) + self._sub_label.set_color(rl.Color(255, 255, 255, int(255 * 0.9))) + self._sub_label.set_font_weight(FontWeight.SEMI_BOLD) + + +class ForgetButton(Widget): + MARGIN = 12 # bottom and right + + def __init__(self, forget_network: Callable): + super().__init__() + self._forget_network = forget_network + + self._bg_txt = gui_app.texture("icons_mici/settings/network/new/forget_button.png", 84, 84) + self._bg_pressed_txt = gui_app.texture("icons_mici/settings/network/new/forget_button_pressed.png", 84, 84) + self._trash_txt = gui_app.texture("icons_mici/settings/network/new/trash.png", 29, 35) + self.set_rect(rl.Rectangle(0, 0, 84 + self.MARGIN * 2, 84 + self.MARGIN * 2)) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + dlg = BigConfirmationDialog("slide to forget", gui_app.texture("icons_mici/settings/network/new/trash.png", 54, 64), self._forget_network, red=True) + gui_app.push_widget(dlg) + + def _render(self, _): + bg_txt = self._bg_pressed_txt if self.is_pressed else self._bg_txt + rl.draw_texture_ex(bg_txt, (self._rect.x + (self._rect.width - self._bg_txt.width) / 2, + self._rect.y + (self._rect.height - self._bg_txt.height) / 2), 0, 1.0, rl.WHITE) + + trash_x = self._rect.x + (self._rect.width - self._trash_txt.width) / 2 + trash_y = self._rect.y + (self._rect.height - self._trash_txt.height) / 2 + rl.draw_texture_ex(self._trash_txt, (trash_x, trash_y), 0, 1.0, rl.WHITE) + + +class ScanningButton(BigButton): + def __init__(self): + super().__init__("", "searching for networks") + self.set_enabled(False) + self._loading_animation = LoadingAnimation() + + def _draw_content(self, btn_y: float): + super()._draw_content(btn_y) + anim = self._loading_animation + x = self._rect.x + self._rect.width - anim.rect.width - 40 + y = btn_y + self._rect.height - anim.rect.height - 30 + anim.set_position(x, y) + anim.render() + + +class WifiUIMici(NavScroller): + def __init__(self, wifi_manager: WifiManager): + super().__init__() + + self._scanning_btn = ScanningButton() + + self._wifi_manager = wifi_manager + self._networks: dict[str, Network] = {} + + self._wifi_manager.add_callbacks( + need_auth=self._on_need_auth, + forgotten=self._on_forgotten, + networks_updated=self._on_network_updated, + ) + + @property + def any_network_forgetting(self) -> bool: + # TODO: deactivate before forget and add DISCONNECTING state + return any(btn.network_forgetting for btn in self._scroller.items if isinstance(btn, WifiButton)) + + def show_event(self): + # Re-sort scroller items and update from latest scan results + super().show_event() + self._wifi_manager.set_active(True) + self._networks = {n.ssid: n for n in self._wifi_manager.networks} + self._update_buttons(re_sort=True) + + def _on_network_updated(self, networks: list[Network]): + self._networks = {network.ssid: network for network in networks} + self._update_buttons() + + def _update_buttons(self, re_sort: bool = False): + # Update existing buttons, add new ones to the end + existing = {btn.network.ssid: btn for btn in self._scroller.items if isinstance(btn, WifiButton)} + + for network in self._networks.values(): + if network.ssid in existing: + existing[network.ssid].update_network(network) + else: + btn = WifiButton(network, self._wifi_manager) + btn.set_click_callback(lambda ssid=network.ssid: self._connect_to_network(ssid)) + self._scroller.add_widget(btn) + + if re_sort: + # Remove stale buttons and sort to match scan order, preserving eager state + btn_map = {btn.network.ssid: btn for btn in self._scroller.items if isinstance(btn, WifiButton)} + self._scroller.items[:] = [btn_map[ssid] for ssid in self._networks if ssid in btn_map] + else: + # Mark networks no longer in scan results (display handled by _update_state) + for btn in self._scroller.items: + if isinstance(btn, WifiButton) and btn.network.ssid not in self._networks: + btn.set_network_missing(True) + + # Keep scanning button at the end + items = self._scroller.items + if self._scanning_btn in items: + items.append(items.pop(items.index(self._scanning_btn))) + else: + self._scroller.add_widget(self._scanning_btn) + + def _connect_with_password(self, ssid: str, password: str): + self._wifi_manager.connect_to_network(ssid, password) + self._move_network_to_front(ssid, scroll=True) + + def _connect_to_network(self, ssid: str): + network = self._networks.get(ssid) + if network is None: + cloudlog.warning(f"Trying to connect to unknown network: {ssid}") + return + + if self._wifi_manager.is_connection_saved(network.ssid): + self._wifi_manager.activate_connection(network.ssid) + elif network.security_type == SecurityType.OPEN: + self._wifi_manager.connect_to_network(network.ssid, "") + else: + self._on_need_auth(network.ssid, False) + return + + self._move_network_to_front(ssid, scroll=True) + + def _on_need_auth(self, ssid, incorrect_password=True): + if incorrect_password: + for btn in self._scroller.items: + if isinstance(btn, WifiButton) and btn.network.ssid == ssid: + btn.set_wrong_password() + break + return + + dlg = BigInputDialog("enter password...", "", minimum_length=8, + confirm_callback=lambda _password: self._connect_with_password(ssid, _password)) + gui_app.push_widget(dlg) + + def _on_forgotten(self, ssid): + # For eager UI forget + for btn in self._scroller.items: + if isinstance(btn, WifiButton) and btn.network.ssid == ssid: + btn.on_forgotten() + + def _move_network_to_front(self, ssid: str | None, scroll: bool = False): + # Move connecting/connected network to the front with animation + front_btn_idx = next((i for i, btn in enumerate(self._scroller.items) + if isinstance(btn, WifiButton) and + btn.network.ssid == ssid), None) if ssid else None + + if front_btn_idx is not None and front_btn_idx > 0: + self._scroller.move_item(front_btn_idx, 0) + + if scroll: + # Scroll to the new position of the network + self._scroller.scroll_to(self._scroller.scroll_panel.get_offset(), smooth=True, block_widget_interaction=True) + + def _update_state(self): + super()._update_state() + + self._move_network_to_front(self._wifi_manager.wifi_state.ssid) diff --git a/selfdrive/ui/mici/layouts/settings/settings.py b/selfdrive/ui/mici/layouts/settings/settings.py new file mode 100644 index 00000000000000..67e880152cbacf --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/settings.py @@ -0,0 +1,81 @@ +import time +from openpilot.common.params import Params +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.button import BigButton +from openpilot.selfdrive.ui.mici.layouts.settings.toggles import TogglesLayoutMici +from openpilot.selfdrive.ui.mici.layouts.settings.network.network_layout import NetworkLayoutMici +from openpilot.selfdrive.ui.mici.layouts.settings.device import DeviceLayoutMici, PairBigButton +from openpilot.selfdrive.ui.mici.layouts.settings.developer import DeveloperLayoutMici +from openpilot.selfdrive.ui.mici.layouts.settings.firehose import FirehoseLayout +from openpilot.selfdrive.ui.mici.layouts.settings.hidden_toggles import HiddenTogglesOverlayMici +from openpilot.selfdrive.ui.mici.layouts.settings.nap import NAPLayoutMici +from openpilot.selfdrive.ui.layouts.settings.triple_tap import MICI_NAP_OPEN_DELAY_S, TripleTapDetector +from openpilot.system.ui.lib.application import gui_app, FontWeight + + +class SettingsBigButton(BigButton): + def _get_label_font_size(self): + return 64 + + +class SettingsLayout(NavScroller): + def __init__(self): + super().__init__() + self._params = Params() + + toggles_panel = TogglesLayoutMici() + toggles_btn = SettingsBigButton("toggles", "", gui_app.texture("icons_mici/settings.png", 64, 64)) + toggles_btn.set_click_callback(lambda: gui_app.push_widget(toggles_panel)) + + network_panel = NetworkLayoutMici() + network_btn = SettingsBigButton("network", "", gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 76, 56)) + network_btn.set_click_callback(lambda: gui_app.push_widget(network_panel)) + + device_panel = DeviceLayoutMici() + device_btn = SettingsBigButton("device", "", gui_app.texture("icons_mici/settings/device_icon.png", 72, 58)) + device_btn.set_click_callback(lambda: gui_app.push_widget(device_panel)) + + developer_panel = DeveloperLayoutMici() + developer_btn = SettingsBigButton("developer", "", gui_app.texture("icons_mici/settings/developer_icon.png", 64, 60)) + developer_btn.set_click_callback(lambda: gui_app.push_widget(developer_panel)) + + firehose_panel = FirehoseLayout() + firehose_btn = SettingsBigButton("firehose", "", gui_app.texture("icons_mici/settings/firehose.png", 52, 62)) + firehose_btn.set_click_callback(lambda: gui_app.push_widget(firehose_panel)) + + self._nap_panel = NAPLayoutMici() + nap_btn = SettingsBigButton("nap", "", gui_app.texture("icons_mici/settings/comma_icon.png", 33, 60)) + nap_btn.set_click_callback(self._on_nap_clicked) + self._nap_triple_tap = TripleTapDetector() + self._nap_open_at: float | None = None + + self._scroller.add_widgets([ + toggles_btn, + network_btn, + device_btn, + PairBigButton(), + #BigDialogButton("manual", "", "icons_mici/settings/manual_icon.png", "Check out the mici user\nmanual at comma.ai/setup"), + nap_btn, + firehose_btn, + developer_btn, + ]) + + self._font_medium = gui_app.font(FontWeight.MEDIUM) + + def _on_nap_clicked(self): + now = time.monotonic() + if self._nap_triple_tap.tap(now): + self._nap_open_at = None + gui_app.push_widget(HiddenTogglesOverlayMici()) + return + # Single / double tap: open NAP after a short quiet period so a quick + # triple can still win. See TripleTapDetector / MICI_NAP_OPEN_DELAY_S. + self._nap_open_at = now + MICI_NAP_OPEN_DELAY_S + + def _update_state(self): + super()._update_state() + if self._nap_open_at is not None and time.monotonic() >= self._nap_open_at: + self._nap_open_at = None + self._nap_triple_tap.reset() + if self.enabled: + gui_app.push_widget(self._nap_panel) diff --git a/selfdrive/ui/mici/layouts/settings/toggles.py b/selfdrive/ui/mici/layouts/settings/toggles.py new file mode 100644 index 00000000000000..acb502fda0ae72 --- /dev/null +++ b/selfdrive/ui/mici/layouts/settings/toggles.py @@ -0,0 +1,87 @@ +from cereal import log + +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.button import BigParamControl, BigMultiParamToggle +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.layouts.settings.common import restart_needed_callback +from openpilot.selfdrive.ui.ui_state import ui_state + +PERSONALITY_TO_INT = log.LongitudinalPersonality.schema.enumerants + + +class TogglesLayoutMici(NavScroller): + def __init__(self): + super().__init__() + + self._personality_toggle = BigMultiParamToggle("driving personality", "LongitudinalPersonality", ["aggressive", "standard", "relaxed"]) + self._experimental_btn = BigParamControl("experimental mode", "ExperimentalMode") + is_metric_toggle = BigParamControl("use metric units", "IsMetric") + ldw_toggle = BigParamControl("lane departure warnings", "IsLdwEnabled") + always_on_dm_toggle = BigParamControl("always-on driver monitor", "AlwaysOnDM") + record_front = BigParamControl("record & upload driver camera", "RecordFront", toggle_callback=restart_needed_callback) + record_mic = BigParamControl("record & upload mic audio", "RecordAudio", toggle_callback=restart_needed_callback) + enable_openpilot = BigParamControl("enable openpilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback) + + self._scroller.add_widgets([ + self._personality_toggle, + self._experimental_btn, + is_metric_toggle, + ldw_toggle, + always_on_dm_toggle, + record_front, + record_mic, + enable_openpilot, + ]) + + # Toggle lists + self._refresh_toggles = ( + ("ExperimentalMode", self._experimental_btn), + ("IsMetric", is_metric_toggle), + ("IsLdwEnabled", ldw_toggle), + ("AlwaysOnDM", always_on_dm_toggle), + ("RecordFront", record_front), + ("RecordAudio", record_mic), + ("OpenpilotEnabledToggle", enable_openpilot), + ) + + enable_openpilot.set_enabled(lambda: not ui_state.engaged) + record_front.set_enabled(False if ui_state.params.get_bool("RecordFrontLock") else (lambda: not ui_state.engaged)) + record_mic.set_enabled(lambda: not ui_state.engaged) + + if ui_state.params.get_bool("ShowDebugInfo"): + gui_app.set_show_touches(True) + gui_app.set_show_fps(True) + + ui_state.add_engaged_transition_callback(self._update_toggles) + + def _update_state(self): + super()._update_state() + + if ui_state.sm.updated["selfdriveState"]: + personality = PERSONALITY_TO_INT[ui_state.sm["selfdriveState"].personality] + if personality != ui_state.personality and ui_state.started: + self._personality_toggle.set_value(self._personality_toggle._options[personality]) + ui_state.personality = personality + + def show_event(self): + super().show_event() + self._update_toggles() + + def _update_toggles(self): + ui_state.update_params() + + # CP gating for experimental mode + if ui_state.CP is not None: + if ui_state.has_longitudinal_control: + self._experimental_btn.set_visible(True) + self._personality_toggle.set_visible(True) + else: + # no long for now + self._experimental_btn.set_visible(False) + self._experimental_btn.set_checked(False) + self._personality_toggle.set_visible(False) + ui_state.params.remove("ExperimentalMode") + + # Refresh toggles from params to mirror external changes + for key, item in self._refresh_toggles: + item.set_checked(ui_state.params.get_bool(key)) diff --git a/selfdrive/ui/mici/onroad/__init__.py b/selfdrive/ui/mici/onroad/__init__.py new file mode 100644 index 00000000000000..bb45117b944e96 --- /dev/null +++ b/selfdrive/ui/mici/onroad/__init__.py @@ -0,0 +1,12 @@ +import pyray as rl + +SIDE_PANEL_WIDTH = 60 + + +def blend_colors(a: rl.Color, b: rl.Color, f: float) -> rl.Color: + h0, s0, v0 = (hsv0 := rl.color_to_hsv(a)).x, hsv0.y, hsv0.z + h1, s1, v1 = (hsv1 := rl.color_to_hsv(b)).x, hsv1.y, hsv1.z + dh = ((h1 - h0 + 180) % 360) - 180 # shortest hue delta + return rl.color_from_hsv((h0 + f * dh) % 360, + s0 + f * (s1 - s0), + v0 + f * (v1 - v0)) diff --git a/selfdrive/ui/mici/onroad/alert_renderer.py b/selfdrive/ui/mici/onroad/alert_renderer.py new file mode 100644 index 00000000000000..7b006aaaeaa968 --- /dev/null +++ b/selfdrive/ui/mici/onroad/alert_renderer.py @@ -0,0 +1,357 @@ +import time +from enum import StrEnum +from typing import NamedTuple +import pyray as rl +import random +import string +from dataclasses import dataclass +from cereal import messaging, log, car +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter +from openpilot.system.hardware import TICI +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus + +ALERT_MARGIN = 18 + +ALERT_FONT_SMALL = 66 - 50 +ALERT_FONT_BIG = 88 - 40 + +SELFDRIVE_STATE_TIMEOUT = 5 # Seconds +SELFDRIVE_UNRESPONSIVE_TIMEOUT = 10 # Seconds + +# Constants +ALERT_COLORS = { + AlertStatus.normal: rl.Color(0, 0, 0, 255), + AlertStatus.userPrompt: rl.Color(255, 115, 0, 255), + AlertStatus.critical: rl.Color(255, 0, 21, 255), +} + +TURN_SIGNAL_BLINK_PERIOD = 1 / (80 / 60) # Mazda heartbeat turn signal BPM + +DEBUG = False + + +class IconSide(StrEnum): + left = 'left' + right = 'right' + + +class IconLayout(NamedTuple): + texture: rl.Texture + side: IconSide + margin_x: int + margin_y: int + + +class AlertLayout(NamedTuple): + text_rect: rl.Rectangle + icon: IconLayout | None + + +@dataclass +class Alert: + text1: str = "" + text2: str = "" + size: int = 0 + status: int = 0 + visual_alert: int = car.CarControl.HUDControl.VisualAlert.none + alert_type: str = "" + + +# Pre-defined alert instances +ALERT_STARTUP_PENDING = Alert( + text1="openpilot Unavailable", + text2="Waiting to start", + size=AlertSize.mid, + status=AlertStatus.normal, +) + +ALERT_CRITICAL_TIMEOUT = Alert( + text1="TAKE CONTROL IMMEDIATELY", + text2="System Unresponsive", + size=AlertSize.full, + status=AlertStatus.critical, +) + +ALERT_CRITICAL_REBOOT = Alert( + text1="System Unresponsive", + text2="Reboot Device", + size=AlertSize.full, + status=AlertStatus.critical, +) + + +class AlertRenderer(Widget): + def __init__(self): + super().__init__() + + self._alert_text1_label = UnifiedLabel(text="", font_size=ALERT_FONT_BIG, font_weight=FontWeight.DISPLAY, line_height=0.86, + letter_spacing=-0.02) + self._alert_text2_label = UnifiedLabel(text="", font_size=ALERT_FONT_SMALL, font_weight=FontWeight.ROMAN, line_height=0.86, + letter_spacing=0.025) + + self._prev_alert: Alert | None = None + self._text_gen_time = 0 + self._alert_text2_gen = '' + + # animation filters + # TODO: use 0.1 but with proper alert height calculation + self._alert_y_filter = BounceFilter(0, 0.1, 1 / gui_app.target_fps) + self._alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + + self._turn_signal_timer = 0.0 + self._turn_signal_alpha_filter = FirstOrderFilter(0.0, 0.3, 1 / gui_app.target_fps) + self._last_icon_side: IconSide | None = None + + self._load_icons() + + def _load_icons(self): + self._txt_turn_signal_left = gui_app.texture('icons_mici/onroad/turn_signal_left.png', 104, 96) + self._txt_turn_signal_right = gui_app.texture('icons_mici/onroad/turn_signal_left.png', 104, 96, flip_x=True) + self._txt_blind_spot_left = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 134, 150) + self._txt_blind_spot_right = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 134, 150, flip_x=True) + + def get_alert(self, sm: messaging.SubMaster) -> Alert | None: + """Generate the current alert based on selfdrive state.""" + ss = sm['selfdriveState'] + + # Check if selfdriveState messages have stopped arriving + if not sm.updated['selfdriveState']: + recv_frame = sm.recv_frame['selfdriveState'] + time_since_onroad = time.monotonic() - ui_state.started_time + + # 1. Never received selfdriveState since going onroad + waiting_for_startup = recv_frame < ui_state.started_frame + if waiting_for_startup and time_since_onroad > 5: + return ALERT_STARTUP_PENDING + + # 2. Lost communication with selfdriveState after receiving it + if TICI and not waiting_for_startup: + ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] + if ss_missing > SELFDRIVE_STATE_TIMEOUT: + if ss.enabled and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < SELFDRIVE_UNRESPONSIVE_TIMEOUT: + return ALERT_CRITICAL_TIMEOUT + return ALERT_CRITICAL_REBOOT + + # No alert if size is none + if ss.alertSize == 0: + return None + + # Return current alert + ret = Alert(text1=ss.alertText1, text2=ss.alertText2, size=ss.alertSize.raw, status=ss.alertStatus.raw, + visual_alert=ss.alertHudVisual, alert_type=ss.alertType) + self._prev_alert = ret + return ret + + def will_render(self) -> tuple[Alert | None, bool]: + alert = self.get_alert(ui_state.sm) + return alert or self._prev_alert, alert is None + + def _icon_helper(self, alert: Alert) -> AlertLayout: + icon_side = None + txt_icon = None + icon_margin_x = 20 + icon_margin_y = 18 + + # alert_type format is "EventName/eventType" (e.g., "preLaneChangeLeft/warning") + event_name = alert.alert_type.split('/')[0] if alert.alert_type else '' + + if event_name == 'preLaneChangeLeft': + icon_side = IconSide.left + txt_icon = self._txt_turn_signal_left + icon_margin_x = 2 + icon_margin_y = 5 + + elif event_name == 'preLaneChangeRight': + icon_side = IconSide.right + txt_icon = self._txt_turn_signal_right + icon_margin_x = 2 + icon_margin_y = 5 + + elif event_name == 'laneChange': + icon_side = self._last_icon_side + txt_icon = self._txt_turn_signal_left if self._last_icon_side == 'left' else self._txt_turn_signal_right + icon_margin_x = 2 + icon_margin_y = 5 + + elif event_name == 'laneChangeBlocked': + CS = ui_state.sm['carState'] + if CS.leftBlinker: + icon_side = IconSide.left + elif CS.rightBlinker: + icon_side = IconSide.right + else: + icon_side = self._last_icon_side + txt_icon = self._txt_blind_spot_left if icon_side == 'left' else self._txt_blind_spot_right + icon_margin_x = 8 + icon_margin_y = 0 + + else: + self._turn_signal_timer = 0.0 + + self._last_icon_side = icon_side + + # create text rect based on icon presence + text_x = self._rect.x + ALERT_MARGIN + text_width = self._rect.width - ALERT_MARGIN + if icon_side == 'left': + text_x = self._rect.x + self._txt_turn_signal_right.width + text_width = self._rect.width - ALERT_MARGIN - self._txt_turn_signal_right.width + elif icon_side == 'right': + text_x = self._rect.x + ALERT_MARGIN + text_width = self._rect.width - ALERT_MARGIN - self._txt_turn_signal_right.width + + text_rect = rl.Rectangle( + text_x, + self._alert_y_filter.x, + text_width, + self._rect.height, + ) + icon_layout = IconLayout(txt_icon, icon_side, icon_margin_x, icon_margin_y) if txt_icon is not None and icon_side is not None else None + return AlertLayout(text_rect, icon_layout) + + def _render(self, rect: rl.Rectangle) -> bool: + alert = self.get_alert(ui_state.sm) + + # Animate fade and slide in/out + self._alert_y_filter.update(self._rect.y - 50 if alert is None else self._rect.y) + self._alpha_filter.update(0 if alert is None else 1) + + if alert is None: + # If still animating out, keep the previous alert + if self._alpha_filter.x > 0.01 and self._prev_alert is not None: + alert = self._prev_alert + else: + self._prev_alert = None + return False + + self._draw_background(alert) + + alert_layout = self._icon_helper(alert) + self._draw_text(alert, alert_layout) + self._draw_icons(alert_layout) + + return True + + def _draw_icons(self, alert_layout: AlertLayout) -> None: + if alert_layout.icon is None: + return + + if time.monotonic() - self._turn_signal_timer > TURN_SIGNAL_BLINK_PERIOD: + self._turn_signal_timer = time.monotonic() + self._turn_signal_alpha_filter.x = 255 * 2 + else: + self._turn_signal_alpha_filter.update(255 * 0.2) + + if alert_layout.icon.side == 'left': + pos_x = int(self._rect.x + alert_layout.icon.margin_x) + else: + pos_x = int(self._rect.x + self._rect.width - alert_layout.icon.margin_x - alert_layout.icon.texture.width) + + if alert_layout.icon.texture not in (self._txt_turn_signal_left, self._txt_turn_signal_right): + icon_alpha = 255 + else: + icon_alpha = int(min(self._turn_signal_alpha_filter.x, 255)) + + rl.draw_texture_ex(alert_layout.icon.texture, rl.Vector2(pos_x, self._rect.y + alert_layout.icon.margin_y), 0.0, 1.0, + rl.Color(255, 255, 255, int(icon_alpha * self._alpha_filter.x))) + + def _draw_background(self, alert: Alert) -> None: + # draw top gradient for alert text at top + color = ALERT_COLORS.get(alert.status, ALERT_COLORS[AlertStatus.normal]) + color = rl.Color(color.r, color.g, color.b, int(255 * 0.90 * self._alpha_filter.x)) + translucent_color = rl.Color(color.r, color.g, color.b, int(0 * self._alpha_filter.x)) + + small_alert_height = round(self._rect.height * 0.583) # 140px at mici height + medium_alert_height = round(self._rect.height * 0.833) # 200px at mici height + + # alert_type format is "EventName/eventType" (e.g., "preLaneChangeLeft/warning") + event_name = alert.alert_type.split('/')[0] if alert.alert_type else '' + + if event_name == 'preLaneChangeLeft': + bg_height = small_alert_height + elif event_name == 'preLaneChangeRight': + bg_height = small_alert_height + elif event_name == 'laneChange': + bg_height = small_alert_height + elif event_name == 'laneChangeBlocked': + bg_height = medium_alert_height + else: + bg_height = int(self._rect.height) + + solid_height = round(bg_height * 0.2) + rl.draw_rectangle(int(self._rect.x), int(self._rect.y), int(self._rect.width), solid_height, color) + rl.draw_rectangle_gradient_v(int(self._rect.x), int(self._rect.y + solid_height), int(self._rect.width), + int(bg_height - solid_height), + color, translucent_color) + + def _draw_text(self, alert: Alert, alert_layout: AlertLayout) -> None: + icon_side = alert_layout.icon.side if alert_layout.icon is not None else None + + # TODO: hack + alert_text1 = alert.text1.lower().replace('calibrating: ', 'calibrating:\n') + can_draw_second_line = False + # TODO: there should be a common way to determine font size based on text length to maximize rect + if len(alert_text1) <= 12: + can_draw_second_line = True + font_size = 92 - 10 + elif len(alert_text1) <= 16: + can_draw_second_line = True + font_size = 70 + else: + font_size = 64 - 10 + + if icon_side is not None: + font_size -= 10 + + color = rl.Color(255, 255, 255, int(255 * 0.9 * self._alpha_filter.x)) + + text1_y_offset = 11 if font_size >= 70 else 4 + text_rect1 = rl.Rectangle( + alert_layout.text_rect.x, + alert_layout.text_rect.y - text1_y_offset, + alert_layout.text_rect.width, + alert_layout.text_rect.height, + ) + self._alert_text1_label.set_text(alert_text1) + self._alert_text1_label.set_text_color(color) + self._alert_text1_label.set_font_size(font_size) + self._alert_text1_label.set_alignment(rl.GuiTextAlignment.TEXT_ALIGN_LEFT if icon_side != 'left' else rl.GuiTextAlignment.TEXT_ALIGN_RIGHT) + self._alert_text1_label.render(text_rect1) + + alert_text2 = alert.text2.lower() + + # randomize chars and length for testing + if DEBUG: + if time.monotonic() - self._text_gen_time > 0.5: + self._alert_text2_gen = ''.join(random.choices(string.ascii_lowercase + ' ', k=random.randint(0, 40))) + self._text_gen_time = time.monotonic() + alert_text2 = self._alert_text2_gen or alert_text2 + + if can_draw_second_line and alert_text2: + last_line_h = self._alert_text1_label.rect.y + self._alert_text1_label.get_content_height(int(alert_layout.text_rect.width)) + last_line_h -= 4 + if len(alert_text2) > 18: + small_font_size = 36 + elif len(alert_text2) > 24: + small_font_size = 32 + else: + small_font_size = 40 + text_rect2 = rl.Rectangle( + alert_layout.text_rect.x, + last_line_h, + alert_layout.text_rect.width, + alert_layout.text_rect.height - last_line_h + ) + color = rl.Color(255, 255, 255, int(255 * 0.65 * self._alpha_filter.x)) + + self._alert_text2_label.set_text(alert_text2) + self._alert_text2_label.set_text_color(color) + self._alert_text2_label.set_font_size(small_font_size) + self._alert_text2_label.set_alignment(rl.GuiTextAlignment.TEXT_ALIGN_LEFT if icon_side != 'left' else rl.GuiTextAlignment.TEXT_ALIGN_RIGHT) + self._alert_text2_label.render(text_rect2) diff --git a/selfdrive/ui/mici/onroad/augmented_road_view.py b/selfdrive/ui/mici/onroad/augmented_road_view.py new file mode 100644 index 00000000000000..56766b758240a8 --- /dev/null +++ b/selfdrive/ui/mici/onroad/augmented_road_view.py @@ -0,0 +1,368 @@ +import numpy as np +import pyray as rl +from cereal import car, log +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.selfdrive.ui.mici.onroad import SIDE_PANEL_WIDTH +from openpilot.selfdrive.ui.mici.onroad.alert_renderer import AlertRenderer +from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.mici.onroad.hud_renderer import HudRenderer +from openpilot.selfdrive.ui.mici.onroad.model_renderer import ModelRenderer +from openpilot.selfdrive.ui.radar.radar_view import RadarHudOverlay, radar_hud_rect +from openpilot.selfdrive.ui.mici.onroad.confidence_ball import ConfidenceBall +from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView +from openpilot.system.ui.lib.application import FontWeight, gui_app, MousePos, MouseEvent +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import BounceFilter +from openpilot.common.transformations.camera import DEVICE_CAMERAS, DeviceCameraConfig, view_frame_from_device_frame +from openpilot.common.transformations.orientation import rot_from_euler +from enum import IntEnum + +OpState = log.SelfdriveState.OpenpilotState +CALIBRATED = log.LiveCalibrationData.Status.calibrated +ROAD_CAM = VisionStreamType.VISION_STREAM_ROAD +WIDE_CAM = VisionStreamType.VISION_STREAM_WIDE_ROAD +DEFAULT_DEVICE_CAMERA = DEVICE_CAMERAS["tici", "ar0231"] + + +class BookmarkState(IntEnum): + HIDDEN = 0 + DRAGGING = 1 + TRIGGERED = 2 + +WIDE_CAM_MAX_SPEED = 5.0 # m/s (10 mph) +ROAD_CAM_MIN_SPEED = 10 # m/s (25 mph) + +CAM_Y_OFFSET = 20 + + +class BookmarkIcon(Widget): + PEEK_THRESHOLD = 50 # If icon peeks out this much, snap it fully visible + FULL_VISIBLE_OFFSET = 200 # How far onscreen when fully visible + HIDDEN_OFFSET = -50 # How far offscreen when hidden + + def __init__(self, bookmark_callback): + super().__init__() + self._bookmark_callback = bookmark_callback + self._icon = gui_app.texture("icons_mici/onroad/bookmark.png", 180, 180) + self._offset_filter = BounceFilter(0.0, 0.1, 1 / gui_app.target_fps) + + # State + self._interacting = False + self._state = BookmarkState.HIDDEN + self._swipe_start_x = 0.0 + self._swipe_current_x = 0.0 + self._is_swiping = False + self._is_swiping_left: bool = False + self._triggered_time: float = 0.0 + + def is_swiping_left(self) -> bool: + """Check if currently swiping left (for scroller to disable).""" + return self._is_swiping_left + + def interacting(self): + interacting, self._interacting = self._interacting, False + return interacting + + def _update_state(self): + if self._state == BookmarkState.DRAGGING: + # Allow pulling past activated position with rubber band effect + swipe_offset = self._swipe_start_x - self._swipe_current_x + swipe_offset = min(swipe_offset, self.FULL_VISIBLE_OFFSET + 50) + self._offset_filter.update(swipe_offset) + + elif self._state == BookmarkState.TRIGGERED: + # Continue animating to fully visible + self._offset_filter.update(self.FULL_VISIBLE_OFFSET) + # Stay in TRIGGERED state for 1 second + if rl.get_time() - self._triggered_time >= 1.5: + self._state = BookmarkState.HIDDEN + + elif self._state == BookmarkState.HIDDEN: + self._offset_filter.update(self.HIDDEN_OFFSET) + + if self._offset_filter.x < 1e-3: + self._interacting = False + + def _handle_mouse_event(self, mouse_event: MouseEvent): + if not ui_state.started: + return + + if mouse_event.left_pressed: + # Store relative position within widget + self._swipe_start_x = mouse_event.pos.x + self._swipe_current_x = mouse_event.pos.x + self._is_swiping = True + self._is_swiping_left = False + self._state = BookmarkState.DRAGGING + + elif mouse_event.left_down and self._is_swiping: + self._swipe_current_x = mouse_event.pos.x + swipe_offset = self._swipe_start_x - self._swipe_current_x + self._is_swiping_left = swipe_offset > 0 + if self._is_swiping_left: + self._interacting = True + + elif mouse_event.left_released: + if self._is_swiping: + swipe_distance = self._swipe_start_x - self._swipe_current_x + + # If peeking past threshold, transition to animating to fully visible and bookmark + if swipe_distance > self.PEEK_THRESHOLD: + self._state = BookmarkState.TRIGGERED + self._triggered_time = rl.get_time() + self._bookmark_callback() + else: + # Otherwise, transition back to hidden + self._state = BookmarkState.HIDDEN + + # Reset swipe state + self._is_swiping = False + self._is_swiping_left = False + + def _render(self, _): + """Render the bookmark icon.""" + if self._offset_filter.x > 0: + icon_x = self.rect.x + self.rect.width - round(self._offset_filter.x) + icon_y = self.rect.y + (self.rect.height - self._icon.height) / 2 # Vertically centered + rl.draw_texture_ex(self._icon, rl.Vector2(icon_x, icon_y), 0.0, 1.0, rl.WHITE) + + +class AugmentedRoadView(CameraView): + def __init__(self, bookmark_callback=None, stream_type: VisionStreamType = VisionStreamType.VISION_STREAM_ROAD): + super().__init__("camerad", stream_type) + self._bookmark_callback = bookmark_callback + self._set_placeholder_color(rl.BLACK) + + self.device_camera: DeviceCameraConfig | None = None + self.view_from_calib = view_frame_from_device_frame.copy() + self.view_from_wide_calib = view_frame_from_device_frame.copy() + + self._matrix_cache_key: tuple | None = None + self._cached_matrix: np.ndarray | None = None + self._content_rect = rl.Rectangle() + self._last_click_time = 0.0 + + # Bookmark icon with swipe gesture + self._bookmark_icon = BookmarkIcon(bookmark_callback) + + self._model_renderer = ModelRenderer() + self._hud_renderer = HudRenderer() + self._radar_hud = RadarHudOverlay() + self._alert_renderer = AlertRenderer() + self._driver_state_renderer = DriverStateRenderer() + self._confidence_ball = ConfidenceBall() + self._offroad_label = UnifiedLabel("start the car to\nuse openpilot", 54, FontWeight.DISPLAY, + text_color=rl.Color(255, 255, 255, int(255 * 0.9)), + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + self._fade_texture = gui_app.texture("icons_mici/onroad/onroad_fade.png") + + def is_swiping_left(self) -> bool: + """Check if currently swiping left (for scroller to disable).""" + return self._bookmark_icon.is_swiping_left() + + def _update_state(self): + super()._update_state() + + # update offroad label + if ui_state.panda_type == log.PandaState.PandaType.unknown: + self._offroad_label.set_text("system booting") + elif ui_state.ignition and not ui_state.started: + self._offroad_label.set_text("openpilot can't start\ncheck alerts") + else: + self._offroad_label.set_text("start the car to\nuse openpilot") + + def _handle_mouse_release(self, mouse_pos: MousePos): + # Don't trigger click callback if bookmark was triggered or Yes/No was hit + if self._hud_renderer.user_interacting(): + return + if not self._bookmark_icon.interacting(): + super()._handle_mouse_release(mouse_pos) + + def _render(self, _): + # Draw text if not onroad + if not ui_state.started: + rl.draw_rectangle_rec(self.rect, rl.BLACK) + self._offroad_label.render(self._rect) + return + + self._switch_stream_if_needed(ui_state.sm) + + # Update calibration before rendering + self._update_calibration() + + # Create inner content area with border padding + self._content_rect = rl.Rectangle( + self.rect.x, + self.rect.y, + self.rect.width - SIDE_PANEL_WIDTH, + self.rect.height, + ) + + # Enable scissor mode to clip all rendering within content rectangle boundaries + # This creates a rendering viewport that prevents graphics from drawing outside the border + rl.begin_scissor_mode( + int(self._content_rect.x), + int(self._content_rect.y), + int(self._content_rect.width), + int(self._content_rect.height) + ) + + # Render the base camera view + super()._render(self._content_rect) + + # Draw all UI overlays + self._model_renderer.render(self._content_rect) + + # Fade out bottom of overlays for looks + rl.draw_texture_ex(self._fade_texture, rl.Vector2(self._content_rect.x, self._content_rect.y), 0.0, 1.0, rl.WHITE) + + alert_to_render, not_animating_out = self._alert_renderer.will_render() + + # Hide DMoji when disengaged unless AlwaysOnDM is enabled + should_draw_dmoji = (not self._hud_renderer.drawing_top_icons() and + (ui_state.status != UIStatus.DISENGAGED or ui_state.always_on_dm)) + self._driver_state_renderer.set_should_draw(should_draw_dmoji) + self._driver_state_renderer.set_position(self._rect.x + 16, self._rect.y + 10) + self._driver_state_renderer.render() + + self._hud_renderer.set_can_draw_top_icons(alert_to_render is None) + self._hud_renderer.set_wheel_critical_icon(alert_to_render is not None and not not_animating_out and + alert_to_render.visual_alert == car.CarControl.HUDControl.VisualAlert.steerRequired) + self._alert_renderer.render(self._content_rect) + self._hud_renderer.render(self._content_rect) + self._radar_hud.render(radar_hud_rect(self._content_rect)) + + # Draw fake rounded border + rl.draw_rectangle_rounded_lines_ex(self._content_rect, 0.2 * 1.02, 10, 50, rl.BLACK) + + # End clipping region + rl.end_scissor_mode() + + # Custom UI extension point - add custom overlays here + # Use self._content_rect for positioning within camera bounds + self._confidence_ball.render(self.rect) + + self._bookmark_icon.render(self.rect) + + def _switch_stream_if_needed(self, sm): + if sm['selfdriveState'].experimentalMode and WIDE_CAM in self.available_streams: + v_ego = sm['carState'].vEgo + if v_ego < WIDE_CAM_MAX_SPEED: + target = WIDE_CAM + elif v_ego > ROAD_CAM_MIN_SPEED: + target = ROAD_CAM + else: + # Hysteresis zone - keep current stream + target = self.stream_type + else: + target = ROAD_CAM + + if self.stream_type != target: + self.switch_stream(target) + + def _update_calibration(self): + # Update device camera if not already set + sm = ui_state.sm + if not self.device_camera and sm.seen['roadCameraState'] and sm.seen['deviceState']: + self.device_camera = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] + + # Check if live calibration data is available and valid + if not (sm.updated["liveCalibration"] and sm.valid['liveCalibration']): + return + + calib = sm['liveCalibration'] + if len(calib.rpyCalib) != 3 or calib.calStatus != CALIBRATED: + return + + # Update view_from_calib matrix + device_from_calib = rot_from_euler(calib.rpyCalib) + self.view_from_calib = view_frame_from_device_frame @ device_from_calib + + # Update wide calibration if available + if hasattr(calib, 'wideFromDeviceEuler') and len(calib.wideFromDeviceEuler) == 3: + wide_from_device = rot_from_euler(calib.wideFromDeviceEuler) + self.view_from_wide_calib = view_frame_from_device_frame @ wide_from_device @ device_from_calib + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + cache_key = ( + ui_state.sm.recv_frame['liveCalibration'], + int(self._content_rect.width), + int(self._content_rect.height), + self.stream_type, + round(ui_state.sm['carState'].vEgo, 1), + ) + + if cache_key == self._matrix_cache_key and self._cached_matrix is not None: + return self._cached_matrix + + # Get camera configuration + device_camera = self.device_camera or DEFAULT_DEVICE_CAMERA + is_wide_camera = self.stream_type == WIDE_CAM + intrinsic = device_camera.ecam.intrinsics if is_wide_camera else device_camera.fcam.intrinsics + calibration = self.view_from_wide_calib if is_wide_camera else self.view_from_calib + if is_wide_camera: + zoom = 0.7 * 1.5 + else: + zoom = np.interp(ui_state.sm['carState'].vEgo, [10, 30], [0.8, 1.0]) + + # Calculate transforms for vanishing point + inf_point = np.array([1000.0, 0.0, 0.0]) + calib_transform = intrinsic @ calibration + kep = calib_transform @ inf_point + + # Calculate center points and dimensions + w, h = self._content_rect.width, self._content_rect.height + cx, cy = intrinsic[0, 2], intrinsic[1, 2] + + # Calculate max allowed offsets with margins + margin = 5 + max_x_offset = cx * zoom - w / 2 - margin + max_y_offset = cy * zoom - h / 2 - margin + + # Calculate and clamp offsets to prevent out-of-bounds issues + try: + if abs(kep[2]) > 1e-6: + x_offset = np.clip((kep[0] / kep[2] - cx) * zoom, -max_x_offset, max_x_offset) + y_offset = np.clip((kep[1] / kep[2] - cy) * zoom + CAM_Y_OFFSET, -max_y_offset, max_y_offset) + else: + x_offset, y_offset = 0, 0 + except (ZeroDivisionError, OverflowError): + x_offset, y_offset = 0, 0 + + # Cache the computed transformation matrix to avoid recalculations + self._matrix_cache_key = cache_key + self._cached_matrix = np.array([ + [zoom * 2 * cx / w, 0, -x_offset / w * 2], + [0, zoom * 2 * cy / h, -y_offset / h * 2], + [0, 0, 1.0] + ]) + + # built without rect.x/y so cache stays hot during scroll. ModelRenderer adds offset at draw time + video_transform = np.array([ + [zoom, 0.0, (w / 2 - x_offset) - (cx * zoom)], + [0.0, zoom, (h / 2 - y_offset) - (cy * zoom)], + [0.0, 0.0, 1.0] + ]) + self._model_renderer.set_transform(video_transform @ calib_transform) + + return self._cached_matrix + + +if __name__ == "__main__": + gui_app.init_window("OnRoad Camera View") + road_camera_view = AugmentedRoadView(lambda: None, stream_type=ROAD_CAM) + print("***press space to switch camera view***") + try: + for _ in gui_app.render(): + ui_state.update() + if rl.is_key_released(rl.KeyboardKey.KEY_SPACE): + if WIDE_CAM in road_camera_view.available_streams: + stream = ROAD_CAM if road_camera_view.stream_type == WIDE_CAM else WIDE_CAM + road_camera_view.switch_stream(stream) + road_camera_view.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + finally: + road_camera_view.close() diff --git a/selfdrive/ui/mici/onroad/cameraview.py b/selfdrive/ui/mici/onroad/cameraview.py new file mode 100644 index 00000000000000..86dd95f46659e7 --- /dev/null +++ b/selfdrive/ui/mici/onroad/cameraview.py @@ -0,0 +1,413 @@ +import platform +import numpy as np +import pyray as rl + +from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf +from openpilot.common.swaglog import cloudlog +from openpilot.system.hardware import TICI +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.egl import init_egl, create_egl_image, destroy_egl_image, bind_egl_image_to_texture, EGLImage +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus + +CONNECTION_RETRY_INTERVAL = 0.2 # seconds between connection attempts + +VERSION = """ +#version 300 es +precision mediump float; +""" +if platform.system() == "Darwin": + VERSION = """ + #version 330 core + """ + + +VERTEX_SHADER = VERSION + """ +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexColor; +uniform mat4 mvp; +out vec2 fragTexCoord; +out vec4 fragColor; +void main() { + fragTexCoord = vertexTexCoord; + fragColor = vertexColor; + gl_Position = mvp * vec4(vertexPosition, 1.0); +} +""" + +# Choose fragment shader based on platform capabilities +if TICI: + FRAME_FRAGMENT_SHADER = """ + #version 300 es + #extension GL_OES_EGL_image_external_essl3 : enable + precision mediump float; + in vec2 fragTexCoord; + uniform samplerExternalOES texture0; + out vec4 fragColor; + uniform int engaged; + uniform int enhance_driver; + + void main() { + vec4 color = texture(texture0, fragTexCoord); + if (engaged == 1) { + float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114)); // Luma + color.rgb = mix(vec3(gray), color.rgb, 0.2); // 20% saturation + color.rgb = clamp((color.rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); // +20% contrast + color.rgb = pow(color.rgb, vec3(1.0/1.28)); + fragColor = vec4(color.rgb, color.a); + } else { + color.rgb *= 0.85; // 85% opacity + } + if (enhance_driver == 1) { + float brightness = 1.1; + color.rgb = color.rgb + 0.15; + color.rgb = clamp((color.rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); + color.rgb = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb); + color.rgb = pow(color.rgb, vec3(0.8)); + } + fragColor = vec4(color.rgb, color.a); + } + """ +else: + FRAME_FRAGMENT_SHADER = VERSION + """ + in vec2 fragTexCoord; + uniform sampler2D texture0; + uniform sampler2D texture1; + out vec4 fragColor; + uniform int engaged; + uniform int enhance_driver; + + void main() { + float y = texture(texture0, fragTexCoord).r; + vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; + vec3 rgb = vec3(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x); + if (engaged == 1) { + float gray = dot(rgb, vec3(0.299, 0.587, 0.114)); + rgb = mix(vec3(gray), rgb, 0.2); // 20% saturation + rgb = clamp((rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); // +20% contrast + } else { + rgb *= 0.85; // 85% opacity + } + // TODO: the images out of camerad need some more correction and + // the ui should apply a gamma curve for the device display + if (enhance_driver == 1) { + float brightness = 1.1; + rgb = rgb + 0.15; + rgb = clamp((rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); + rgb = rgb * rgb * (3.0 - 2.0 * rgb); + rgb = pow(rgb, vec3(0.8)); + } + fragColor = vec4(rgb, 1.0); + } + """ + + +class CameraView(Widget): + def __init__(self, name: str, stream_type: VisionStreamType): + super().__init__() + self._name = name + # Primary stream + self.client = VisionIpcClient(name, stream_type, conflate=True) + self._stream_type = stream_type + self.available_streams: list[VisionStreamType] = [] + + # Target stream for switching + self._target_client: VisionIpcClient | None = None + self._target_stream_type: VisionStreamType | None = None + self._switching: bool = False + + self._texture_needs_update = True + self.last_connection_attempt: float = 0.0 + self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAME_FRAGMENT_SHADER) + self._texture1_loc: int = rl.get_shader_location(self.shader, "texture1") if not TICI else -1 + self._engaged_loc = rl.get_shader_location(self.shader, "engaged") + self._engaged_val = rl.ffi.new("int[1]", [1]) + self._enhance_driver_loc = rl.get_shader_location(self.shader, "enhance_driver") + self._enhance_driver_val = rl.ffi.new("int[1]", [1 if stream_type == VisionStreamType.VISION_STREAM_DRIVER else 0]) + + self.frame: VisionBuf | None = None + self.texture_y: rl.Texture | None = None + self.texture_uv: rl.Texture | None = None + + # EGL resources + self.egl_images: dict[int, EGLImage] = {} + self.egl_texture: rl.Texture | None = None + + self._placeholder_color: rl.Color | None = None + + # Initialize EGL for zero-copy rendering on TICI + if TICI: + if not init_egl(): + raise RuntimeError("Failed to initialize EGL") + + # Create a 1x1 pixel placeholder texture for EGL image binding + temp_image = rl.gen_image_color(1, 1, rl.BLACK) + self.egl_texture = rl.load_texture_from_image(temp_image) + rl.unload_image(temp_image) + + ui_state.add_offroad_transition_callback(self._offroad_transition) + + def _offroad_transition(self): + # Drain queued SubSocket messages to prevent old frames from showing when going + # onroad. Qt had a separate thread which drains the VisionIpcClient SubSocket for us. + if self.client and self.client.is_connected(): + while self.client.recv(timeout_ms=0) is not None: + pass + self.frame = None + + def _set_placeholder_color(self, color: rl.Color): + """Set a placeholder color to be drawn when no frame is available.""" + self._placeholder_color = color + + def switch_stream(self, stream_type: VisionStreamType) -> None: + if self._stream_type == stream_type: + return + + if self._switching and self._target_stream_type == stream_type: + return + + cloudlog.debug(f'Preparing switch from {self._stream_type} to {stream_type}') + + if self._target_client: + del self._target_client + + self._target_stream_type = stream_type + self._target_client = VisionIpcClient(self._name, stream_type, conflate=True) + self._switching = True + + @property + def stream_type(self) -> VisionStreamType: + return self._stream_type + + def close(self) -> None: + self._clear_textures() + + # Clean up EGL texture + if TICI and self.egl_texture: + rl.unload_texture(self.egl_texture) + self.egl_texture = None + + # Clean up shader + if self.shader and self.shader.id: + rl.unload_shader(self.shader) + self.shader.id = 0 + + self.frame = None + self.available_streams.clear() + self.client = None + + def __del__(self): + self.close() + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + if not self.frame: + return np.eye(3) + + # Calculate aspect ratios + widget_aspect_ratio = rect.width / rect.height + frame_aspect_ratio = self.frame.width / self.frame.height + + # Calculate scaling factors to maintain aspect ratio + zx = min(frame_aspect_ratio / widget_aspect_ratio, 1.0) + zy = min(widget_aspect_ratio / frame_aspect_ratio, 1.0) + + return np.array([ + [zx, 0.0, 0.0], + [0.0, zy, 0.0], + [0.0, 0.0, 1.0] + ]) + + def _render(self, rect: rl.Rectangle): + if self._switching: + self._handle_switch() + + if not self._ensure_connection(): + self._draw_placeholder(rect) + return + + # Try to get a new buffer without blocking + buffer = self.client.recv(timeout_ms=0) + if buffer: + self._texture_needs_update = True + self.frame = buffer + elif not self.client.is_connected(): + # ensure we clear the displayed frame when the connection is lost + self.frame = None + + if not self.frame: + self._draw_placeholder(rect) + return + + transform = self._calc_frame_matrix(rect) + src_rect = rl.Rectangle(0, 0, float(self.frame.width), float(self.frame.height)) + # Flip driver camera horizontally + if self._stream_type == VisionStreamType.VISION_STREAM_DRIVER: + src_rect.width = -src_rect.width + + # Calculate scale + scale_x = rect.width * transform[0, 0] # zx + scale_y = rect.height * transform[1, 1] # zy + + # Calculate base position (centered) + x_offset = rect.x + (rect.width - scale_x) / 2 + y_offset = rect.y + (rect.height - scale_y) / 2 + + x_offset += transform[0, 2] * rect.width / 2 + y_offset += transform[1, 2] * rect.height / 2 + + dst_rect = rl.Rectangle(x_offset, y_offset, scale_x, scale_y) + + # Render with appropriate method + if TICI: + self._render_egl(src_rect, dst_rect) + else: + self._render_textures(src_rect, dst_rect) + + def _draw_placeholder(self, rect: rl.Rectangle): + if self._placeholder_color: + rl.draw_rectangle_rec(rect, self._placeholder_color) + + def _render_egl(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: + """Render using EGL for direct buffer access""" + if self.frame is None or self.egl_texture is None: + return + + idx = self.frame.idx + egl_image = self.egl_images.get(idx) + + # Create EGL image if needed + if egl_image is None: + egl_image = create_egl_image(self.frame.width, self.frame.height, self.frame.stride, self.frame.fd, self.frame.uv_offset) + if egl_image: + self.egl_images[idx] = egl_image + else: + return + + # Update texture dimensions to match current frame + self.egl_texture.width = self.frame.width + self.egl_texture.height = self.frame.height + + # Bind the EGL image to our texture + bind_egl_image_to_texture(self.egl_texture.id, egl_image) + + # Render with shader + rl.begin_shader_mode(self.shader) + self._update_texture_color_filtering() + rl.draw_texture_pro(self.egl_texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + + def _render_textures(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: + """Render using texture copies""" + if not self.texture_y or not self.texture_uv or self.frame is None: + return + + # Update textures with new frame data + if self._texture_needs_update: + y_data = self.frame.data[: self.frame.uv_offset] + uv_data = self.frame.data[self.frame.uv_offset:] + + rl.update_texture(self.texture_y, rl.ffi.cast("void *", rl.ffi.from_buffer(y_data))) + rl.update_texture(self.texture_uv, rl.ffi.cast("void *", rl.ffi.from_buffer(uv_data))) + self._texture_needs_update = False + + # Render with shader + rl.begin_shader_mode(self.shader) + self._update_texture_color_filtering() + rl.set_shader_value_texture(self.shader, self._texture1_loc, self.texture_uv) + rl.draw_texture_pro(self.texture_y, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + + def _update_texture_color_filtering(self): + self._engaged_val[0] = 1 if ui_state.status != UIStatus.DISENGAGED else 0 + rl.set_shader_value(self.shader, self._engaged_loc, self._engaged_val, rl.ShaderUniformDataType.SHADER_UNIFORM_INT) + rl.set_shader_value(self.shader, self._enhance_driver_loc, self._enhance_driver_val, rl.ShaderUniformDataType.SHADER_UNIFORM_INT) + + def _ensure_connection(self) -> bool: + if not self.client.is_connected(): + self.frame = None + self.available_streams.clear() + + # Throttle connection attempts + current_time = rl.get_time() + if current_time - self.last_connection_attempt < CONNECTION_RETRY_INTERVAL: + return False + self.last_connection_attempt = current_time + + if not self.client.connect(False) or not self.client.num_buffers: + return False + + cloudlog.debug(f"Connected to {self._name} stream: {self._stream_type}, buffers: {self.client.num_buffers}") + self._initialize_textures() + self.available_streams = self.client.available_streams(self._name, block=False) + + return True + + def _handle_switch(self) -> None: + """Check if target stream is ready and switch immediately.""" + if not self._target_client or not self._switching: + return + + # Try to connect target if needed + if not self._target_client.is_connected(): + if not self._target_client.connect(False) or not self._target_client.num_buffers: + return + + cloudlog.debug(f"Target stream connected: {self._target_stream_type}") + + # Check if target has frames ready + target_frame = self._target_client.recv(timeout_ms=0) + if target_frame: + self.frame = target_frame # Update current frame to target frame + self._complete_switch() + + def _complete_switch(self) -> None: + """Instantly switch to target stream.""" + cloudlog.debug(f"Switching to {self._target_stream_type}") + # Clean up current resources + if self.client: + del self.client + + # Switch to target + self.client = self._target_client + self._stream_type = self._target_stream_type + self._texture_needs_update = True + + # Reset state + self._target_client = None + self._target_stream_type = None + self._switching = False + + # Initialize textures for new stream + self._initialize_textures() + + def _initialize_textures(self): + self._clear_textures() + if not TICI: + self.texture_y = rl.load_texture_from_image(rl.Image(None, int(self.client.stride), + int(self.client.height), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)) + self.texture_uv = rl.load_texture_from_image(rl.Image(None, int(self.client.stride // 2), + int(self.client.height // 2), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)) + + def _clear_textures(self): + if self.texture_y and self.texture_y.id: + rl.unload_texture(self.texture_y) + self.texture_y = None + + if self.texture_uv and self.texture_uv.id: + rl.unload_texture(self.texture_uv) + self.texture_uv = None + + # Clean up EGL resources + if TICI: + for data in self.egl_images.values(): + destroy_egl_image(data) + self.egl_images = {} + + +if __name__ == "__main__": + gui_app.init_window("camera view") + road = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) + for _ in gui_app.render(): + road.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) diff --git a/selfdrive/ui/mici/onroad/confidence_ball.py b/selfdrive/ui/mici/onroad/confidence_ball.py new file mode 100644 index 00000000000000..a5c95470f54c1e --- /dev/null +++ b/selfdrive/ui/mici/onroad/confidence_ball.py @@ -0,0 +1,78 @@ +import math +import pyray as rl +from openpilot.selfdrive.ui.mici.onroad import SIDE_PANEL_WIDTH +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.lib.application import gui_app +from openpilot.common.filter_simple import FirstOrderFilter + + +def draw_circle_gradient(center_x: float, center_y: float, radius: int, + top: rl.Color, bottom: rl.Color) -> None: + # Draw a square with the gradient + rl.draw_rectangle_gradient_v(int(center_x - radius), int(center_y - radius), + radius * 2, radius * 2, + top, bottom) + + # Paint over square with a ring + outer_radius = math.ceil(radius * math.sqrt(2)) + 1 + rl.draw_ring(rl.Vector2(int(center_x), int(center_y)), radius, outer_radius, + 0.0, 360.0, + 20, rl.BLACK) + + +class ConfidenceBall(Widget): + def __init__(self, demo: bool = False): + super().__init__() + self._demo = demo + self._confidence_filter = FirstOrderFilter(-0.5, 0.5, 1 / gui_app.target_fps) + + def update_filter(self, value: float): + self._confidence_filter.update(value) + + def _update_state(self): + if self._demo: + return + + # animate status dot in from bottom + if ui_state.status == UIStatus.DISENGAGED: + self._confidence_filter.update(-0.5) + else: + self._confidence_filter.update((1 - max(ui_state.sm['modelV2'].meta.disengagePredictions.brakeDisengageProbs or [1])) * + (1 - max(ui_state.sm['modelV2'].meta.disengagePredictions.steerOverrideProbs or [1]))) + + def _render(self, _): + content_rect = rl.Rectangle( + self.rect.x + self.rect.width - SIDE_PANEL_WIDTH, + self.rect.y, + SIDE_PANEL_WIDTH, + self.rect.height, + ) + + status_dot_radius = 24 + dot_height = (1 - self._confidence_filter.x) * (content_rect.height - 2 * status_dot_radius) + status_dot_radius + dot_height = self._rect.y + dot_height + + # confidence zones + if ui_state.status == UIStatus.ENGAGED or self._demo: + if self._confidence_filter.x > 0.5: + top_dot_color = rl.Color(0, 255, 204, 255) + bottom_dot_color = rl.Color(0, 255, 38, 255) + elif self._confidence_filter.x > 0.2: + top_dot_color = rl.Color(255, 200, 0, 255) + bottom_dot_color = rl.Color(255, 115, 0, 255) + else: + top_dot_color = rl.Color(255, 0, 21, 255) + bottom_dot_color = rl.Color(255, 0, 89, 255) + + elif ui_state.status == UIStatus.OVERRIDE: + top_dot_color = rl.Color(255, 255, 255, 255) + bottom_dot_color = rl.Color(82, 82, 82, 255) + + else: + top_dot_color = rl.Color(50, 50, 50, 255) + bottom_dot_color = rl.Color(13, 13, 13, 255) + + draw_circle_gradient(content_rect.x + content_rect.width - status_dot_radius, + dot_height, status_dot_radius, + top_dot_color, bottom_dot_color) diff --git a/selfdrive/ui/mici/onroad/driver_camera_dialog.py b/selfdrive/ui/mici/onroad/driver_camera_dialog.py new file mode 100644 index 00000000000000..df5afe2e7c4a7f --- /dev/null +++ b/selfdrive/ui/mici/onroad/driver_camera_dialog.py @@ -0,0 +1,247 @@ +import pyray as rl +from cereal import car, log, messaging +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView +from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.label import gui_label + + +class DriverCameraView(CameraView): + def _calc_frame_matrix(self, rect: rl.Rectangle): + base = super()._calc_frame_matrix(rect) + driver_view_ratio = 1.5 + base[0, 0] *= driver_view_ratio + base[1, 1] *= driver_view_ratio + return base + + +class BaseDriverCameraDialog(Widget): + # Not a NavWidget so training guide can use this without back navigation + def __init__(self): + super().__init__() + self._camera_view = DriverCameraView("camerad", VisionStreamType.VISION_STREAM_DRIVER) + self.driver_state_renderer = DriverStateRenderer(lines=True) + self.driver_state_renderer.set_rect(rl.Rectangle(0, 0, 200, 200)) + self.driver_state_renderer.load_icons() + self._pm: messaging.PubMaster | None = None + + # Load eye icons + self._eye_fill_texture = None + self._eye_orange_texture = None + self._eye_size = 74 + self._glasses_texture = None + self._glasses_size = 171 + + self._load_eye_textures() + + def show_event(self): + super().show_event() + ui_state.params.put_bool("IsDriverViewEnabled", True) + self._publish_alert_sound(None) + device.set_override_interactive_timeout(300) + ui_state.params.remove("DriverTooDistracted") + self._pm = messaging.PubMaster(['selfdriveState']) + + def hide_event(self): + super().hide_event() + ui_state.params.put_bool("IsDriverViewEnabled", False) + device.set_override_interactive_timeout(None) + + def _handle_mouse_release(self, _): + ui_state.params.remove("DriverTooDistracted") + + def __del__(self): + self.close() + + def close(self): + if self._camera_view: + self._camera_view.close() + + def _update_state(self): + if self._camera_view: + self._camera_view._update_state() + # Enable driver state renderer to show Dmoji in preview + self.driver_state_renderer.set_should_draw(True) + self.driver_state_renderer.set_force_active(True) + super()._update_state() + + def _render(self, rect): + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + self._camera_view._render(rect) + + if not self._camera_view.frame: + gui_label(rect, tr("camera starting"), font_size=54, font_weight=FontWeight.BOLD, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + rl.end_scissor_mode() + self._publish_alert_sound(None) + return + + driver_data = self._draw_face_detection(rect) + if driver_data is not None: + self._draw_eyes(rect, driver_data) + + # Position dmoji on opposite side from driver + driver_state_rect = ( + rect.x if self.driver_state_renderer.is_rhd else rect.x + rect.width - self.driver_state_renderer.rect.width, + rect.y + (rect.height - self.driver_state_renderer.rect.height) / 2, + ) + self.driver_state_renderer.set_position(*driver_state_rect) + self.driver_state_renderer.render() + + # Render driver monitoring alerts + self._render_dm_alerts(rect) + + rl.end_scissor_mode() + return + + def _publish_alert_sound(self, dm_state): + """Publish selfdriveState with only alertSound field set""" + if self._pm is None: + return + + AudibleAlert = car.CarControl.HUDControl.AudibleAlert + ALERT_SOUNDS = { + 'two': AudibleAlert.promptDistracted, + 'three': AudibleAlert.warningImmediate, + } + msg = messaging.new_message('selfdriveState') + if dm_state is not None: + msg.selfdriveState.alertSound = ALERT_SOUNDS.get(str(dm_state.alertLevel), AudibleAlert.none) + self._pm.send('selfdriveState', msg) + + def _render_dm_alerts(self, rect: rl.Rectangle): + """Render driver monitoring event names""" + dm_state = ui_state.sm["driverMonitoringState"] + self._publish_alert_sound(dm_state) + + is_vision = dm_state.activePolicy == log.DriverMonitoringState.MonitoringPolicy.vision + awareness_pct = dm_state.visionPolicyState.awarenessPercent if is_vision else dm_state.wheeltouchPolicyState.awarenessPercent + gui_label(rl.Rectangle(rect.x + 2, rect.y + 2, rect.width, rect.height), + f"Awareness: {awareness_pct:.0f}%", font_size=44, font_weight=FontWeight.MEDIUM, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + color=rl.Color(0, 0, 0, 180)) + gui_label(rect, f"Awareness: {awareness_pct:.0f}%", font_size=44, font_weight=FontWeight.MEDIUM, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + color=rl.Color(255, 255, 255, int(255 * 0.9))) + + if dm_state.alertLevel == log.DriverMonitoringState.AlertLevel.none: + return + + # Show alert level + alert_level_str = f"{'Pay Attention' if is_vision else 'Touch Wheel'} - level {dm_state.alertLevel}" + alignment = rl.GuiTextAlignment.TEXT_ALIGN_RIGHT if self.driver_state_renderer.is_rhd else rl.GuiTextAlignment.TEXT_ALIGN_LEFT + + shadow_rect = rl.Rectangle(rect.x + 2, rect.y + 2, rect.width, rect.height) + gui_label(shadow_rect, alert_level_str, font_size=40, font_weight=FontWeight.BOLD, + alignment=alignment, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, + color=rl.Color(0, 0, 0, 180)) + gui_label(rect, alert_level_str, font_size=40, font_weight=FontWeight.BOLD, + alignment=alignment, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, + color=rl.Color(255, 255, 255, int(255 * 0.9))) + + def _load_eye_textures(self): + """Lazy load eye textures""" + if self._eye_fill_texture is None: + self._eye_fill_texture = gui_app.texture("icons_mici/onroad/eye_fill.png", self._eye_size, self._eye_size) + if self._eye_orange_texture is None: + self._eye_orange_texture = gui_app.texture("icons_mici/onroad/eye_orange.png", self._eye_size, self._eye_size) + if self._glasses_texture is None: + self._glasses_texture = gui_app.texture("icons_mici/onroad/glasses.png", self._glasses_size, self._glasses_size) + + def _draw_face_detection(self, rect: rl.Rectangle): + dm_state = ui_state.sm["driverMonitoringState"] + driver_data = self.driver_state_renderer.get_driver_data() + if not dm_state.visionPolicyState.faceDetected: + return + + # Get face position and orientation + face_x, face_y = driver_data.facePosition + face_std = max(driver_data.faceOrientationStd[0], driver_data.faceOrientationStd[1]) + alpha = 0.7 + if face_std > 0.15: + alpha = max(0.7 - (face_std - 0.15) * 3.5, 0.0) + + # use approx instead of distort_points + # TODO: replace with distort_points + tici_x = 1080.0 - 1714.0 * face_x + tici_y = -135.0 + (504.0 + abs(face_x) * 112.0) + (1205.0 - abs(face_x) * 724.0) * face_y + + # Tici coords are relative to center, scale offset + offset_x = (tici_x - 1080.0) * 1.25 + offset_y = (tici_y - 540.0) * 1.25 + + # Map to mici screen (scale from 2160x1080 to rect dimensions) + scale_x = rect.width / 2160.0 + scale_y = rect.height / 1080.0 + fbox_x = rect.x + rect.width / 2 + offset_x * scale_x + fbox_y = rect.y + rect.height / 2 + offset_y * scale_y + box_size = 75 + line_thickness = 3 + + line_color = rl.Color(255, 255, 255, int(alpha * 255)) + rl.draw_rectangle_rounded_lines_ex( + rl.Rectangle(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size), + 35.0 / box_size / 2, + line_thickness, + line_thickness, + line_color, + ) + return driver_data + + def _draw_eyes(self, rect: rl.Rectangle, driver_data): + # Draw eye indicators based on eye probabilities + eye_offset_x = 10 + eye_offset_y = 10 + eye_spacing = self._eye_size + 15 + + left_eye_x = rect.x + eye_offset_x + left_eye_y = rect.y + eye_offset_y + left_eye_prob = driver_data.leftEyeProb + + right_eye_x = rect.x + eye_offset_x + eye_spacing + right_eye_y = rect.y + eye_offset_y + right_eye_prob = driver_data.rightEyeProb + + # Draw eyes with opacity based on probability + for eye_x, eye_y, eye_prob in [(left_eye_x, left_eye_y, left_eye_prob), (right_eye_x, right_eye_y, right_eye_prob)]: + fill_opacity = eye_prob + orange_opacity = 1.0 - eye_prob + + rl.draw_texture_v(self._eye_orange_texture, (eye_x, eye_y), rl.Color(255, 255, 255, int(255 * orange_opacity))) + rl.draw_texture_v(self._eye_fill_texture, (eye_x, eye_y), rl.Color(255, 255, 255, int(255 * fill_opacity))) + + # Draw sunglasses indicator based on sunglasses probability + # Position glasses centered between the two eyes at top left + glasses_x = rect.x + eye_offset_x - 4 + glasses_y = rect.y + glasses_pos = rl.Vector2(glasses_x, glasses_y) + glasses_prob = driver_data.sunglassesProb + rl.draw_texture_v(self._glasses_texture, glasses_pos, rl.Color(70, 80, 161, int(255 * glasses_prob))) + + +class DriverCameraDialog(NavWidget, BaseDriverCameraDialog): + def __init__(self): + super().__init__() + # TODO: this can grow unbounded, should be given some thought + device.add_interactive_timeout_callback(gui_app.pop_widget) + + +if __name__ == "__main__": + gui_app.init_window("Driver Camera View (mici)") + + driver_camera_view = DriverCameraDialog() + gui_app.push_widget(driver_camera_view) + try: + for _ in gui_app.render(): + ui_state.update() + finally: + driver_camera_view.close() diff --git a/selfdrive/ui/mici/onroad/driver_state.py b/selfdrive/ui/mici/onroad/driver_state.py new file mode 100644 index 00000000000000..1855d77b77b784 --- /dev/null +++ b/selfdrive/ui/mici/onroad/driver_state.py @@ -0,0 +1,216 @@ +import pyray as rl +import numpy as np +import math +from cereal import log +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.ui_state import ui_state + + +AlertSize = log.SelfdriveState.AlertSize + +DEBUG = False + +# TODO: Only left for DM preview, remove +LOOKING_CENTER_THRESHOLD_UPPER = math.radians(6) +LOOKING_CENTER_THRESHOLD_LOWER = math.radians(3) + +CONE_COLOR_GREEN = (0, 255, 64) +CONE_COLOR_ORANGE = (255, 115, 0) + + +class DriverStateRenderer(Widget): + BASE_SIZE = 60 + LINES_ANGLE_INCREMENT = 5 + LINES_STALE_ANGLES = 3.0 # seconds + AWARENESS_UNFULL_PERCENT = 95 # ~0.5s + + def __init__(self, lines: bool = False, inset: bool = False): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, self.BASE_SIZE, self.BASE_SIZE)) + self._lines = lines + self._inset = inset + + # In line mode, track smoothed angles + assert 360 % self.LINES_ANGLE_INCREMENT == 0 + self._head_angles = {i * self.LINES_ANGLE_INCREMENT: FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) for i in range(360 // self.LINES_ANGLE_INCREMENT)} + + self._is_active = False + self._is_rhd = False + self._face_detected = False + self._face_pitch = 0. + self._face_yaw = 0. + self._should_draw = False + self._force_active = False + self._looking_center = False + self._awareness_unfull = False + + self._fade_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps) + self._color_fade_filter = FirstOrderFilter(1.0, 0.05, 1 / gui_app.target_fps) # 1.0 = full green, 0.0 = full orange + self._pitch_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps, initialized=False) + self._yaw_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps, initialized=False) + self._rotation_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps, initialized=False) + self._looking_center_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + # Load the driver face icons + self.load_icons() + + def load_icons(self): + """Load or reload the driver face icon texture""" + cone_and_person_size = round(52 / self.BASE_SIZE * self._rect.width) + + # If inset is enabled, push cone and person smaller by 2x the current inset space + if self._inset: + # Current inset space = (rect.width - cone_and_person_size) / 2 + current_inset = (self._rect.width - cone_and_person_size) / 2 + # Reduce size by 2x the current inset (1x on each side) + cone_and_person_size = round(cone_and_person_size - current_inset * 2) + + self._dm_person = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_person.png", cone_and_person_size, cone_and_person_size) + self._dm_cone = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_cone.png", cone_and_person_size, cone_and_person_size) + self._dm_background = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_background.png", int(self._rect.width), int(self._rect.height)) + + def set_should_draw(self, should_draw: bool): + self._should_draw = should_draw + + @property + def should_draw(self): + return (self._should_draw and ui_state.sm["selfdriveState"].alertSize == AlertSize.none and + ui_state.sm.recv_frame["driverStateV2"] > ui_state.started_frame) + + def set_force_active(self, force_active: bool): + """Force the dmoji to always appear active (green) regardless of actual state""" + self._force_active = force_active + + @property + def effective_active(self) -> bool: + """Returns True if dmoji should appear active (either actually active or forced)""" + return bool(self._force_active or self._is_active) + + @property + def is_rhd(self) -> bool: + return self._is_rhd + + def _render(self, _): + if DEBUG: + rl.draw_rectangle_lines_ex(self._rect, 1, rl.RED) + + rl.draw_texture_ex(self._dm_background, + rl.Vector2(self._rect.x, self._rect.y), 0.0, 1.0, + rl.Color(255, 255, 255, int(255 * self._fade_filter.x))) + + rl.draw_texture_ex(self._dm_person, + rl.Vector2(self._rect.x + (self._rect.width - self._dm_person.width) / 2, + self._rect.y + (self._rect.height - self._dm_person.height) / 2), 0.0, 1.0, + rl.Color(255, 255, 255, int(255 * 0.9 * self._fade_filter.x))) + + green_amount = self._color_fade_filter.update(0.0 if self._awareness_unfull else 1.0) + if self.effective_active: + source_rect = rl.Rectangle(0, 0, self._dm_cone.width, self._dm_cone.height) + dest_rect = rl.Rectangle( + self._rect.x + self._rect.width / 2, + self._rect.y + self._rect.height / 2, + self._dm_cone.width, + self._dm_cone.height, + ) + + if not self._lines: + r = int(round(CONE_COLOR_GREEN[0] * green_amount + CONE_COLOR_ORANGE[0] * (1 - green_amount))) + g = int(round(CONE_COLOR_GREEN[1] * green_amount + CONE_COLOR_ORANGE[1] * (1 - green_amount))) + b = int(round(CONE_COLOR_GREEN[2] * green_amount + CONE_COLOR_ORANGE[2] * (1 - green_amount))) + rl.draw_texture_pro( + self._dm_cone, + source_rect, + dest_rect, + rl.Vector2(dest_rect.width / 2, dest_rect.height / 2), + self._rotation_filter.x - 90, + rl.Color(r, g, b, int(255 * self._fade_filter.x)), + ) + + else: + # remove old angles + for angle, f in self._head_angles.items(): + dst_from_current = ((angle - self._rotation_filter.x) % 360) - 180 + target = 1.0 if abs(dst_from_current) <= self.LINES_ANGLE_INCREMENT * 5 else 0.0 + if not self._face_detected: + target = 0.0 + + # Reduce all line lengths when looking center + if self._looking_center: + target = np.interp(self._looking_center_filter.x, [0.0, 1.0], [target, 0.45]) + + f.update(target) + self._draw_line(angle, f, self._looking_center) + + def _draw_line(self, angle: int, f: FirstOrderFilter, grey: bool): + line_length = self._rect.width / 6 + line_length = round(np.interp(f.x, [0.0, 1.0], [0, line_length])) + line_offset = self._rect.width / 2 - line_length * 2 # ensure line ends within rect + center_x = self._rect.x + self._rect.width / 2 + center_y = self._rect.y + self._rect.height / 2 + start_x = center_x + (line_offset + line_length) * math.cos(math.radians(angle)) + start_y = center_y + (line_offset + line_length) * math.sin(math.radians(angle)) + end_x = start_x + line_length * math.cos(math.radians(angle)) + end_y = start_y + line_length * math.sin(math.radians(angle)) + color = rl.Color(0, 255, 64, 255) + + if grey: + color = rl.Color(166, 166, 166, 255) + + if f.x > 0.01: + rl.draw_line_ex((start_x, start_y), (end_x, end_y), 12, color) + + def get_driver_data(self): + sm = ui_state.sm + + dm_state = sm["driverMonitoringState"] + self._is_active = dm_state.activePolicy == log.DriverMonitoringState.MonitoringPolicy.vision + self._is_rhd = dm_state.isRHD + self._face_detected = dm_state.visionPolicyState.faceDetected + self._awareness_unfull = self.effective_active and dm_state.visionPolicyState.awarenessPercent < self.AWARENESS_UNFULL_PERCENT + self._face_pitch = dm_state.visionPolicyState.pose.pitch + math.radians(6) # calib or DM pose is not accurate, add a fake upward pitch to bias forward + self._face_yaw = -dm_state.visionPolicyState.pose.yaw # undo sign flip in face_orientation_from_model to match UI convention + + driverstate = sm["driverStateV2"] + driver_data = driverstate.rightDriverData if self._is_rhd else driverstate.leftDriverData + return driver_data + + def _update_state(self): + # Get monitoring state + _ = self.get_driver_data() + pitch = self._pitch_filter.update(self._face_pitch) + yaw = self._yaw_filter.update(self._face_yaw) + + # hysteresis on looking center + if abs(pitch) < LOOKING_CENTER_THRESHOLD_LOWER and abs(yaw) < LOOKING_CENTER_THRESHOLD_LOWER: + self._looking_center = True + elif abs(pitch) > LOOKING_CENTER_THRESHOLD_UPPER or abs(yaw) > LOOKING_CENTER_THRESHOLD_UPPER: + self._looking_center = False + self._looking_center_filter.update(1 if self._looking_center else 0) + + if DEBUG: + pitchd = math.degrees(pitch) + yawd = math.degrees(yaw) + + rl.draw_line_ex((0, 100), (200, 100), 3, rl.RED) + rl.draw_line_ex((0, 120), (200, 120), 3, rl.RED) + rl.draw_line_ex((0, 140), (200, 140), 3, rl.RED) + + pitch_x = 100 + pitchd + yaw_x = 100 + yawd + rl.draw_circle(int(pitch_x), 100, 5, rl.GREEN) + rl.draw_circle(int(yaw_x), 120, 5, rl.GREEN) + + # filter head rotation, handling wrap-around + rotation = math.degrees(math.atan2(pitch * 2, yaw)) # reduce yaw sensitivity + angle_diff = rotation - self._rotation_filter.x + angle_diff = ((angle_diff + 180) % 360) - 180 + self._rotation_filter.update(self._rotation_filter.x + angle_diff) + + if not self.should_draw: + self._fade_filter.update(0.0) + elif not self.effective_active: + self._fade_filter.update(0.35) + else: + self._fade_filter.update(1.0) diff --git a/selfdrive/ui/mici/onroad/hud_renderer.py b/selfdrive/ui/mici/onroad/hud_renderer.py new file mode 100644 index 00000000000000..6188291c3f98bf --- /dev/null +++ b/selfdrive/ui/mici/onroad/hud_renderer.py @@ -0,0 +1,300 @@ +import pyray as rl +from dataclasses import dataclass +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.mici.onroad.torque_bar import TorqueBar +from openpilot.selfdrive.ui.onroad.speed_sign_hud import SpeedSignHud +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import FirstOrderFilter +from cereal import log + +EventName = log.OnroadEvent.EventName + +# Constants +SET_SPEED_NA = 255 +KM_TO_MILE = 0.621371 +CRUISE_DISABLED_CHAR = '–' + +SET_SPEED_PERSISTENCE = 2.5 # seconds + + +@dataclass(frozen=True) +class FontSizes: + current_speed: int = 176 + speed_unit: int = 66 + max_speed: int = 36 + set_speed: int = 112 + + +@dataclass(frozen=True) +class Colors: + WHITE = rl.WHITE + WHITE_TRANSLUCENT = rl.Color(255, 255, 255, 200) + + +FONT_SIZES = FontSizes() +COLORS = Colors() + + +class TurnIntent(Widget): + FADE_IN_ANGLE = 30 # degrees + + def __init__(self): + super().__init__() + self._pre = False + self._turn_intent_direction: int = 0 + + self._turn_intent_alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + self._turn_intent_rotation_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + + self._txt_turn_intent_left: rl.Texture = gui_app.texture('icons_mici/turn_intent_left.png', 50, 20) + self._txt_turn_intent_right: rl.Texture = gui_app.texture('icons_mici/turn_intent_left.png', 50, 20, flip_x=True) + + def _render(self, _): + if self._turn_intent_alpha_filter.x > 1e-2: + turn_intent_texture = self._txt_turn_intent_right if self._turn_intent_direction == 1 else self._txt_turn_intent_left + src_rect = rl.Rectangle(0, 0, turn_intent_texture.width, turn_intent_texture.height) + dest_rect = rl.Rectangle(self._rect.x + self._rect.width / 2, self._rect.y + self._rect.height / 2, + turn_intent_texture.width, turn_intent_texture.height) + + origin = (turn_intent_texture.width / 2, self._rect.height / 2) + color = rl.Color(255, 255, 255, int(255 * self._turn_intent_alpha_filter.x)) + rl.draw_texture_pro(turn_intent_texture, src_rect, dest_rect, origin, self._turn_intent_rotation_filter.x, color) + + def _update_state(self) -> None: + sm = ui_state.sm + + left = any(e.name == EventName.preLaneChangeLeft for e in sm['onroadEvents']) + right = any(e.name == EventName.preLaneChangeRight for e in sm['onroadEvents']) + if left or right: + # pre lane change + if not self._pre: + self._turn_intent_rotation_filter.x = self.FADE_IN_ANGLE if left else -self.FADE_IN_ANGLE + + self._pre = True + self._turn_intent_direction = -1 if left else 1 + self._turn_intent_alpha_filter.update(1) + self._turn_intent_rotation_filter.update(0) + elif any(e.name == EventName.laneChange for e in sm['onroadEvents']): + # fade out and rotate away + self._pre = False + self._turn_intent_alpha_filter.update(0) + + if self._turn_intent_direction == 0: + # unknown. missed pre frame? + self._turn_intent_rotation_filter.update(0) + else: + self._turn_intent_rotation_filter.update(self._turn_intent_direction * self.FADE_IN_ANGLE) + else: + # didn't complete lane change, just hide + self._pre = False + self._turn_intent_direction = 0 + self._turn_intent_alpha_filter.update(0) + self._turn_intent_rotation_filter.update(0) + + +class HudRenderer(Widget): + def __init__(self): + super().__init__() + """Initialize the HUD renderer.""" + self.is_cruise_set: bool = False + self.is_cruise_available: bool = True + self.set_speed: float = SET_SPEED_NA + self._set_speed_changed_time: float = 0 + self.speed: float = 0.0 + self._engaged: bool = False + self.map_speed_valid: bool = False + self.map_speed_limit: float = 0.0 + + self._can_draw_top_icons = True + self._show_wheel_critical = False + + self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM) + self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) + self._font_display: rl.Font = gui_app.font(FontWeight.DISPLAY) + + self._turn_intent = TurnIntent() + self._torque_bar = TorqueBar() + self._speed_sign_hud = SpeedSignHud(tici=False) + + self._txt_wheel: rl.Texture = gui_app.texture('icons_mici/wheel.png', 50, 50) + self._txt_wheel_critical: rl.Texture = gui_app.texture('icons_mici/wheel_critical.png', 50, 50) + self._txt_exclamation_point: rl.Texture = gui_app.texture('icons_mici/exclamation_point.png', 9, 44) + + self._wheel_alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + self._wheel_y_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + + self._set_speed_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + def set_wheel_critical_icon(self, critical: bool): + """Set the wheel icon to critical or normal state.""" + self._show_wheel_critical = critical + + def set_can_draw_top_icons(self, can_draw_top_icons: bool): + """Set whether to draw the top part of the HUD.""" + self._can_draw_top_icons = can_draw_top_icons + + def drawing_top_icons(self) -> bool: + # whether we're drawing any top icons currently + return bool(self._set_speed_alpha_filter.x > 1e-2) + + def _update_state(self) -> None: + """Update HUD state based on car state and controls state.""" + sm = ui_state.sm + if sm.recv_frame["carState"] < ui_state.started_frame: + self.is_cruise_set = False + self.set_speed = SET_SPEED_NA + self.speed = 0.0 + return + + controls_state = sm['controlsState'] + car_state = sm['carState'] + + v_cruise_cluster = car_state.vCruiseCluster + set_speed = ( + controls_state.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster + ) + engaged = sm['selfdriveState'].enabled + if (set_speed != self.set_speed and engaged) or (engaged and not self._engaged): + self._set_speed_changed_time = rl.get_time() + self._engaged = engaged + self.set_speed = set_speed + self.is_cruise_set = 0 < self.set_speed < SET_SPEED_NA + self.is_cruise_available = self.set_speed != -1 + + # Top-middle live speed is wheel/ESP vEgo only, never vEgoCluster / vCruise / map. + speed_conversion = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + self.speed = max(0.0, float(car_state.vEgo) * speed_conversion) + + self.map_speed_valid = False + self.map_speed_limit = 0.0 + if "liveMapDataNAP" in sm.valid and sm.valid["liveMapDataNAP"]: + md = sm["liveMapDataNAP"] + if md.speedLimitValid and md.speedLimit > 0: + self.map_speed_valid = True + self.map_speed_limit = md.speedLimit * speed_conversion + + def _render(self, rect: rl.Rectangle) -> None: + """Render HUD elements to the screen.""" + + self._torque_bar.render(rect) + + if self.is_cruise_set: + self._draw_set_speed(rect) + + self._speed_sign_hud.render(rect) + self._draw_steering_wheel(rect) + + def user_interacting(self) -> bool: + return self._speed_sign_hud.is_pressed + + def _draw_steering_wheel(self, rect: rl.Rectangle) -> None: + wheel_txt = self._txt_wheel_critical if self._show_wheel_critical else self._txt_wheel + + if self._show_wheel_critical: + self._wheel_alpha_filter.update(255) + self._wheel_y_filter.update(0) + else: + if ui_state.status == UIStatus.DISENGAGED: + self._wheel_alpha_filter.update(0) + self._wheel_y_filter.update(wheel_txt.height / 2) + else: + self._wheel_alpha_filter.update(255 * 0.9) + self._wheel_y_filter.update(0) + + # pos + pos_x = int(rect.x + 21 + wheel_txt.width / 2) + pos_y = int(rect.y + rect.height - 14 - wheel_txt.height / 2 + self._wheel_y_filter.x) + rotation = -ui_state.sm['carState'].steeringAngleDeg + + turn_intent_margin = 25 + self._turn_intent.render(rl.Rectangle( + pos_x - wheel_txt.width / 2 - turn_intent_margin, + pos_y - wheel_txt.height / 2 - turn_intent_margin, + wheel_txt.width + turn_intent_margin * 2, + wheel_txt.height + turn_intent_margin * 2, + )) + + src_rect = rl.Rectangle(0, 0, wheel_txt.width, wheel_txt.height) + dest_rect = rl.Rectangle(pos_x, pos_y, wheel_txt.width, wheel_txt.height) + origin = (wheel_txt.width / 2, wheel_txt.height / 2) + + # color and draw + color = rl.Color(255, 255, 255, int(self._wheel_alpha_filter.x)) + rl.draw_texture_pro(wheel_txt, src_rect, dest_rect, origin, rotation, color) + + if self._show_wheel_critical: + # Draw exclamation point icon + EXCLAMATION_POINT_SPACING = 10 + exclamation_pos_x = pos_x - self._txt_exclamation_point.width / 2 + wheel_txt.width / 2 + EXCLAMATION_POINT_SPACING + exclamation_pos_y = pos_y - self._txt_exclamation_point.height / 2 + rl.draw_texture_ex(self._txt_exclamation_point, rl.Vector2(exclamation_pos_x, exclamation_pos_y), 0.0, 1.0, rl.WHITE) + + def _draw_set_speed(self, rect: rl.Rectangle) -> None: + """Draw the MAX speed indicator box.""" + alpha = self._set_speed_alpha_filter.update(0 < rl.get_time() - self._set_speed_changed_time < SET_SPEED_PERSISTENCE and + self._can_draw_top_icons and self._engaged) + if alpha < 1e-2: + return + + x = rect.x + y = rect.y + + # draw drop shadow + circle_radius = 162 // 2 + rl.draw_circle_gradient(rl.Vector2(x + circle_radius, y + circle_radius), circle_radius, + rl.Color(0, 0, 0, int(255 / 2 * alpha)), rl.BLANK) + + set_speed_color = rl.Color(255, 255, 255, int(255 * 0.9 * alpha)) + max_color = rl.Color(255, 255, 255, int(255 * 0.9 * alpha)) + + set_speed = self.set_speed + if self.is_cruise_set and not ui_state.is_metric: + set_speed *= KM_TO_MILE + + set_speed_text = CRUISE_DISABLED_CHAR if not self.is_cruise_set else str(round(set_speed)) + rl.draw_text_ex( + self._font_display, + set_speed_text, + rl.Vector2(x + 13 + 4, y + 3 - 8 - 3 + 4), + FONT_SIZES.set_speed, + 0, + set_speed_color, + ) + + max_text = tr("MAX") + rl.draw_text_ex( + self._font_semi_bold, + max_text, + rl.Vector2(x + 25, y + FONT_SIZES.set_speed - 7 + 4), + FONT_SIZES.max_speed, + 0, + max_color, + ) + + if self.map_speed_valid: + lim = str(round(self.map_speed_limit)) + rl.draw_text_ex( + self._font_semi_bold, + f"OSM {lim}", + rl.Vector2(x + 25, y + FONT_SIZES.set_speed + FONT_SIZES.max_speed - 4), + 22, + 0, + rl.Color(255, 255, 255, int(200 * alpha)), + ) + + def _draw_current_speed(self, rect: rl.Rectangle) -> None: + """Draw the current vehicle speed and unit.""" + speed_text = str(round(self.speed)) + speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) + speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) + rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.WHITE) + + unit_text = tr("km/h") if ui_state.is_metric else tr("mph") + unit_text_size = measure_text_cached(self._font_medium, unit_text, FONT_SIZES.speed_unit) + unit_pos = rl.Vector2(rect.x + rect.width / 2 - unit_text_size.x / 2, 290 - unit_text_size.y / 2) + rl.draw_text_ex(self._font_medium, unit_text, unit_pos, FONT_SIZES.speed_unit, 0, COLORS.WHITE_TRANSLUCENT) diff --git a/selfdrive/ui/mici/onroad/model_renderer.py b/selfdrive/ui/mici/onroad/model_renderer.py new file mode 100644 index 00000000000000..7d70b47982cef8 --- /dev/null +++ b/selfdrive/ui/mici/onroad/model_renderer.py @@ -0,0 +1,484 @@ +import colorsys +import numpy as np +import pyray as rl +from cereal import messaging, car +from dataclasses import dataclass, field +from openpilot.common.params import Params +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.locationd.calibrationd import HEIGHT_INIT +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.selfdrive.ui.mici.onroad import blend_colors +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient +from openpilot.system.ui.widgets import Widget + +CLIP_MARGIN = 500 +MIN_DRAW_DISTANCE = 10.0 +MAX_DRAW_DISTANCE = 100.0 + +THROTTLE_COLORS = [ + rl.Color(13, 248, 122, 102), # HSLF(148/360, 0.94, 0.51, 0.4) + rl.Color(114, 255, 92, 89), # HSLF(112/360, 1.0, 0.68, 0.35) + rl.Color(114, 255, 92, 0), # HSLF(112/360, 1.0, 0.68, 0.0) +] + +NO_THROTTLE_COLORS = [ + rl.Color(242, 242, 242, 102), # HSLF(148/360, 0.0, 0.95, 0.4) + rl.Color(242, 242, 242, 89), # HSLF(112/360, 0.0, 0.95, 0.35) + rl.Color(242, 242, 242, 0), # HSLF(112/360, 0.0, 0.95, 0.0) +] + +LANE_LINE_COLORS = { + UIStatus.DISENGAGED: rl.Color(200, 200, 200, 255), + UIStatus.OVERRIDE: rl.Color(255, 255, 255, 255), + UIStatus.ENGAGED: rl.Color(0, 255, 64, 255), +} + + +@dataclass +class ModelPoints: + raw_points: np.ndarray = field(default_factory=lambda: np.empty((0, 3), dtype=np.float32)) + projected_points: np.ndarray = field(default_factory=lambda: np.empty((0, 2), dtype=np.float32)) + + +@dataclass +class LeadVehicle: + glow: list[float] = field(default_factory=list) + chevron: list[float] = field(default_factory=list) + fill_alpha: int = 0 + + +class ModelRenderer(Widget): + def __init__(self): + super().__init__() + self._longitudinal_control = False + self._experimental_mode = False + self._blend_filter = FirstOrderFilter(1.0, 0.25, 1 / gui_app.target_fps) + self._prev_allow_throttle = True + self._lane_line_probs = np.zeros(4, dtype=np.float32) + self._road_edge_stds = np.zeros(2, dtype=np.float32) + self._lead_vehicles = [LeadVehicle(), LeadVehicle()] + self._path_offset_z = HEIGHT_INIT[0] + + # Initialize ModelPoints objects + self._path = ModelPoints() + self._lane_lines = [ModelPoints() for _ in range(4)] + self._road_edges = [ModelPoints() for _ in range(2)] + self._acceleration_x = np.empty((0,), dtype=np.float32) + + self._acceleration_x_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + self._acceleration_x_filter2 = FirstOrderFilter(0.0, 1, 1 / gui_app.target_fps) + + self._torque_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + self._ll_color_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + # 3x3 car space -> rect-origin space (draw methods add rect.x/y) + self._car_space_transform = np.zeros((3, 3), dtype=np.float32) + self._transform_dirty = True + self._clip_region = None + + self._exp_gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=[], + stops=[], + ) + + # Get longitudinal control setting from car parameters + if car_params := Params().get("CarParams"): + cp = messaging.log_from_bytes(car_params, car.CarParams) + self._longitudinal_control = cp.openpilotLongitudinalControl + + def set_transform(self, transform: np.ndarray): + self._car_space_transform = transform.astype(np.float32) + self._transform_dirty = True + + def _render(self, rect: rl.Rectangle): + sm = ui_state.sm + + self._torque_filter.update(-ui_state.sm['carOutput'].actuatorsOutput.torque) + + # Check if data is up-to-date + if (sm.recv_frame["liveCalibration"] < ui_state.started_frame or + sm.recv_frame["modelV2"] < ui_state.started_frame): + return + + # Set up clipping region + self._clip_region = rl.Rectangle( + rect.x - CLIP_MARGIN, rect.y - CLIP_MARGIN, rect.width + 2 * CLIP_MARGIN, rect.height + 2 * CLIP_MARGIN + ) + + # Update state + self._experimental_mode = sm['selfdriveState'].experimentalMode + + live_calib = sm['liveCalibration'] + self._path_offset_z = live_calib.height[0] if live_calib.height else HEIGHT_INIT[0] + + if sm.updated['carParams']: + self._longitudinal_control = sm['carParams'].openpilotLongitudinalControl + + model = sm['modelV2'] + radar_state = sm['radarState'] if sm.valid['radarState'] else None + lead_one = radar_state.leadOne if radar_state else None + render_lead_indicator = self._longitudinal_control and radar_state is not None + + # Update model data when needed + model_updated = sm.updated['modelV2'] + if model_updated or sm.updated['radarState'] or self._transform_dirty: + if model_updated: + self._update_raw_points(model) + + path_x_array = self._path.raw_points[:, 0] + if path_x_array.size == 0: + return + + self._update_model(lead_one, path_x_array) + if render_lead_indicator: + self._update_leads(radar_state, path_x_array, has_lead=bool(sm['longitudinalPlan'].hasLead)) + self._transform_dirty = False + + # Draw elements (hide when disengaged) + if ui_state.status != UIStatus.DISENGAGED: + self._draw_lane_lines() + self._draw_path(sm) + + # if render_lead_indicator and radar_state: + # self._draw_lead_indicator() + + def _update_raw_points(self, model): + """Update raw 3D points from model data""" + self._path.raw_points = np.array([model.position.x, model.position.y, model.position.z], dtype=np.float32).T + + for i, lane_line in enumerate(model.laneLines): + self._lane_lines[i].raw_points = np.array([lane_line.x, lane_line.y, lane_line.z], dtype=np.float32).T + + for i, road_edge in enumerate(model.roadEdges): + self._road_edges[i].raw_points = np.array([road_edge.x, road_edge.y, road_edge.z], dtype=np.float32).T + + self._lane_line_probs = np.array(model.laneLineProbs, dtype=np.float32) + self._road_edge_stds = np.array(model.roadEdgeStds, dtype=np.float32) + self._acceleration_x = np.array(model.acceleration.x, dtype=np.float32) + + def _update_leads(self, radar_state, path_x_array, has_lead=False): + """Update positions of lead vehicles""" + self._lead_vehicles = [LeadVehicle(), LeadVehicle()] + leads = [radar_state.leadOne, radar_state.leadTwo] + + for i, lead_data in enumerate(leads): + control_lead = bool(has_lead) and i == 0 and lead_data is not None and float(lead_data.dRel) > 0.0 + if lead_data and (lead_data.status or control_lead): + d_rel, y_rel, v_rel = lead_data.dRel, lead_data.yRel, lead_data.vRel + idx = self._get_path_length_idx(path_x_array, d_rel) + + # Get z-coordinate from path at the lead vehicle position + z = self._path.raw_points[idx, 2] if idx < len(self._path.raw_points) else 0.0 + point = self._map_to_screen(d_rel, -y_rel, z + self._path_offset_z) + if point: + self._lead_vehicles[i] = self._update_lead_vehicle(d_rel, v_rel, point, self._rect) + + def _update_model(self, lead, path_x_array): + """Update model visualization data based on model message""" + max_distance = np.clip(path_x_array[-1], MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE) + max_idx = self._get_path_length_idx(self._lane_lines[0].raw_points[:, 0], max_distance) + + # Update lane lines using raw points + line_width_factor = 0.12 + for i, lane_line in enumerate(self._lane_lines): + if i in (1, 2): + line_width_factor = 0.16 + lane_line.projected_points = self._map_line_to_polygon( + lane_line.raw_points, line_width_factor * self._lane_line_probs[i], 0.0, max_idx + ) + + # Update road edges using raw points + for road_edge in self._road_edges: + road_edge.projected_points = self._map_line_to_polygon(road_edge.raw_points, line_width_factor, 0.0, max_idx) + + # Update path using raw points + if lead and lead.status: + lead_d = lead.dRel * 2.0 + max_distance = np.clip(lead_d - min(lead_d * 0.35, 10.0), 0.0, max_distance) + + soon_acceleration = self._acceleration_x[len(self._acceleration_x) // 4] if len(self._acceleration_x) > 0 else 0 + self._acceleration_x_filter.update(soon_acceleration) + self._acceleration_x_filter2.update(soon_acceleration) + + # make path width wider/thinner when initially braking/accelerating + if self._experimental_mode and False: + high_pass_acceleration = self._acceleration_x_filter.x - self._acceleration_x_filter2.x + y_off = np.interp(high_pass_acceleration, [-1, 0, 1], [0.9 * 2, 0.9, 0.9 / 2]) + else: + y_off = 0.9 + + max_idx = self._get_path_length_idx(path_x_array, max_distance) + self._path.projected_points = self._map_line_to_polygon( + self._path.raw_points, y_off, self._path_offset_z, max_idx, allow_invert=False + ) + + self._update_experimental_gradient() + + def _update_experimental_gradient(self): + """Pre-calculate experimental mode gradient colors""" + if not self._experimental_mode: + return + + path_pts = self._path.projected_points + np.array([self._rect.x, self._rect.y], dtype=np.float32) + max_len = min(len(path_pts) // 2, len(self._acceleration_x)) + + segment_colors = [] + gradient_stops = [] + + i = 0 + while i < max_len: + # Some points (screen space) are out of frame (rect space) + track_y = path_pts[i][1] + if track_y < self._rect.y or track_y > (self._rect.y + self._rect.height): + i += 1 + continue + + # Calculate color based on acceleration (0 is bottom, 1 is top) + lin_grad_point = 1 - (track_y - self._rect.y) / self._rect.height + + # speed up: 120, slow down: 0 + path_hue = np.clip(60 + self._acceleration_x[i] * 35, 0, 120) + + saturation = min(abs(self._acceleration_x[i] * 1.5), 1) + lightness = np.interp(saturation, [0.0, 1.0], [0.95, 0.62]) + alpha = np.interp(lin_grad_point, [0.75 / 2.0, 0.75], [0.4, 0.0]) + + # Use HSL to RGB conversion + color = self._hsla_to_color(path_hue / 360.0, saturation, lightness, alpha) + + gradient_stops.append(lin_grad_point) + segment_colors.append(color) + + # Skip a point, unless next is last + i += 1 + (1 if (i + 2) < max_len else 0) + + # Store the gradient in the path object + self._exp_gradient.colors = segment_colors + self._exp_gradient.stops = gradient_stops + + def _update_lead_vehicle(self, d_rel, v_rel, point, rect): + speed_buff, lead_buff = 10.0, 40.0 + + # Calculate fill alpha + fill_alpha = 0 + if d_rel < lead_buff: + fill_alpha = 255 * (1.0 - (d_rel / lead_buff)) + if v_rel < 0: + fill_alpha += 255 * (-1 * (v_rel / speed_buff)) + fill_alpha = min(fill_alpha, 255) + + # Calculate size and position + sz = np.clip((25 * 30) / (d_rel / 3 + 30), 15.0, 30.0) * 1 + x = np.clip(point[0], 0.0, rect.width - sz / 2) + y = min(point[1], rect.height - sz * 0.6) + + g_xo = sz / 5 + g_yo = sz / 10 + + glow = [(x + (sz * 1.35) + g_xo, y + sz + g_yo), (x, y - g_yo), (x - (sz * 1.35) - g_xo, y + sz + g_yo)] + chevron = [(x + (sz * 1.25), y + sz), (x, y), (x - (sz * 1.25), y + sz)] + + return LeadVehicle(glow=glow, chevron=chevron, fill_alpha=int(fill_alpha)) + + def _get_ll_color(self, prob: float, adjacent: bool, left: bool): + alpha = np.clip(prob, 0.0, 0.7) + if adjacent: + _base_color = LANE_LINE_COLORS.get(ui_state.status, LANE_LINE_COLORS[UIStatus.DISENGAGED]) + color = rl.Color(_base_color.r, _base_color.g, _base_color.b, int(alpha * 255)) + + # turn adjacent lls orange if torque is high + torque = self._torque_filter.x + high_torque = abs(torque) > 0.6 + if high_torque and (left == (torque > 0)): + color = blend_colors( + color, + rl.Color(255, 115, 0, int(alpha * 255)), # orange + np.interp(abs(torque), [0.6, 0.8], [0.0, 1.0]) + ) + else: + color = rl.Color(255, 255, 255, int(alpha * 255)) + + if ui_state.status == UIStatus.DISENGAGED: + color = rl.Color(0, 0, 0, int(alpha * 255)) + + return color + + def _draw_lane_lines(self): + """Draw lane lines and road edges. Two closest lines should be green (lane line or road edges).""" + offset = np.array([self._rect.x, self._rect.y], dtype=np.float32) + + for i, lane_line in enumerate(self._lane_lines): + if lane_line.projected_points.size == 0: + continue + + color = self._get_ll_color(float(self._lane_line_probs[i]), i in (1, 2), i in (0, 1)) + draw_polygon(self._rect, lane_line.projected_points + offset, color) + + for i, road_edge in enumerate(self._road_edges): + if road_edge.projected_points.size == 0: + continue + + # if closest lane lines are not confident, make road edges green + color = self._get_ll_color(float(1.0 - self._road_edge_stds[i]), float(self._lane_line_probs[i + 1]) < 0.25, i == 0) + draw_polygon(self._rect, road_edge.projected_points + offset, color) + + def _draw_path(self, sm): + """Draw path with dynamic coloring based on mode and throttle state.""" + if not self._path.projected_points.size: + return + + allow_throttle = sm['longitudinalPlan'].allowThrottle or not self._longitudinal_control + self._blend_filter.update(int(allow_throttle)) + + path_pts = self._path.projected_points + np.array([self._rect.x, self._rect.y], dtype=np.float32) + + if self._experimental_mode: + # Draw with acceleration coloring + if ui_state.status == UIStatus.DISENGAGED: + draw_polygon(self._rect, path_pts, rl.Color(0, 0, 0, 90)) + elif len(self._exp_gradient.colors) > 1: + draw_polygon(self._rect, path_pts, gradient=self._exp_gradient) + else: + draw_polygon(self._rect, path_pts, rl.Color(255, 255, 255, 30)) + else: + # Blend throttle/no throttle colors based on transition + blend_factor = round(self._blend_filter.x * 100) / 100 + blended_colors = self._blend_colors(NO_THROTTLE_COLORS, THROTTLE_COLORS, blend_factor) + gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=blended_colors, + stops=[0.0, 0.5, 1.0], + ) + + if ui_state.status == UIStatus.DISENGAGED: + draw_polygon(self._rect, path_pts, rl.Color(0, 0, 0, 90)) + else: + draw_polygon(self._rect, path_pts, gradient=gradient) + + def _draw_lead_indicator(self): + # Draw lead vehicles if available + for lead in self._lead_vehicles: + if not lead.glow or not lead.chevron: + continue + + rl.draw_triangle_fan(lead.glow, len(lead.glow), rl.Color(218, 202, 37, 255)) + rl.draw_triangle_fan(lead.chevron, len(lead.chevron), rl.Color(201, 34, 49, lead.fill_alpha)) + + @staticmethod + def _get_path_length_idx(pos_x_array: np.ndarray, path_height: float) -> int: + """Get the index corresponding to the given path height""" + if len(pos_x_array) == 0: + return 0 + indices = np.where(pos_x_array <= path_height)[0] + return indices[-1] if indices.size > 0 else 0 + + def _map_to_screen(self, in_x, in_y, in_z): + """Project a point in car space to screen space""" + input_pt = np.array([in_x, in_y, in_z]) + pt = self._car_space_transform @ input_pt + + if abs(pt[2]) < 1e-6: + return None + + x, y = pt[0] / pt[2], pt[1] / pt[2] + + clip = self._clip_region + if not (clip.x <= x <= clip.x + clip.width and clip.y <= y <= clip.y + clip.height): + return None + + return (x, y) + + def _map_line_to_polygon(self, line: np.ndarray, y_off: float, z_off: float, max_idx: int, allow_invert: bool = True) -> np.ndarray: + """Convert 3D line to 2D polygon for rendering.""" + if line.shape[0] == 0: + return np.empty((0, 2), dtype=np.float32) + + # Slice points and filter non-negative x-coordinates + points = line[:max_idx + 1] + points = points[points[:, 0] >= 0] + if points.shape[0] == 0: + return np.empty((0, 2), dtype=np.float32) + + N = points.shape[0] + # Generate left and right 3D points in one array using broadcasting + offsets = np.array([[0, -y_off, z_off], [0, y_off, z_off]], dtype=np.float32) + points_3d = points[None, :, :] + offsets[:, None, :] # Shape: 2xNx3 + points_3d = points_3d.reshape(2 * N, 3) # Shape: (2*N)x3 + + # Transform all points to projected space in one operation + proj = self._car_space_transform @ points_3d.T # Shape: 3x(2*N) + proj = proj.reshape(3, 2, N) + left_proj = proj[:, 0, :] + right_proj = proj[:, 1, :] + + # Filter points where z is sufficiently large + valid_proj = (np.abs(left_proj[2]) >= 1e-6) & (np.abs(right_proj[2]) >= 1e-6) + if not np.any(valid_proj): + return np.empty((0, 2), dtype=np.float32) + + # Compute screen coordinates + left_screen = left_proj[:2, valid_proj] / left_proj[2, valid_proj][None, :] + right_screen = right_proj[:2, valid_proj] / right_proj[2, valid_proj][None, :] + + # Define clip region bounds + clip = self._clip_region + x_min, x_max = clip.x, clip.x + clip.width + y_min, y_max = clip.y, clip.y + clip.height + + # Filter points within clip region + left_in_clip = ( + (left_screen[0] >= x_min) & (left_screen[0] <= x_max) & + (left_screen[1] >= y_min) & (left_screen[1] <= y_max) + ) + right_in_clip = ( + (right_screen[0] >= x_min) & (right_screen[0] <= x_max) & + (right_screen[1] >= y_min) & (right_screen[1] <= y_max) + ) + both_in_clip = left_in_clip & right_in_clip + + if not np.any(both_in_clip): + return np.empty((0, 2), dtype=np.float32) + + # Select valid and clipped points + left_screen = left_screen[:, both_in_clip] + right_screen = right_screen[:, both_in_clip] + + # Handle Y-coordinate inversion on hills + if not allow_invert and left_screen.shape[1] > 1: + y = left_screen[1, :] # y-coordinates + keep = y == np.minimum.accumulate(y) + if not np.any(keep): + return np.empty((0, 2), dtype=np.float32) + left_screen = left_screen[:, keep] + right_screen = right_screen[:, keep] + + return np.vstack((left_screen.T, right_screen[:, ::-1].T)).astype(np.float32) + + @staticmethod + def _hsla_to_color(h, s, l, a): + rgb = colorsys.hls_to_rgb(h, l, s) + return rl.Color( + int(rgb[0] * 255), + int(rgb[1] * 255), + int(rgb[2] * 255), + int(a * 255) + ) + + @staticmethod + def _blend_colors(begin_colors, end_colors, t): + if t >= 1.0: + return end_colors + if t <= 0.0: + return begin_colors + + inv_t = 1.0 - t + return [rl.Color( + int(inv_t * start.r + t * end.r), + int(inv_t * start.g + t * end.g), + int(inv_t * start.b + t * end.b), + int(inv_t * start.a + t * end.a) + ) for start, end in zip(begin_colors, end_colors, strict=True)] diff --git a/selfdrive/ui/mici/onroad/torque_bar.py b/selfdrive/ui/mici/onroad/torque_bar.py new file mode 100644 index 00000000000000..406e6ff712fcfb --- /dev/null +++ b/selfdrive/ui/mici/onroad/torque_bar.py @@ -0,0 +1,266 @@ +import math +import time +from functools import wraps +from collections import OrderedDict + +import numpy as np +import pyray as rl +from opendbc.car import ACCELERATION_DUE_TO_GRAVITY +from openpilot.selfdrive.ui.mici.onroad import blend_colors +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import FirstOrderFilter + +# TODO: arc_bar_pts doesn't consider rounded end caps part of the angle span +TORQUE_ANGLE_SPAN = 12.7 + +DEBUG = False + + +def quantized_lru_cache(maxsize=128): + def decorator(func): + cache = OrderedDict() + @wraps(func) + def wrapper(r_mid, thickness, a0_deg, a1_deg, **kwargs): + # Quantize inputs: balanced for smoothness vs cache effectiveness + key = (round(r_mid), + round(thickness), # 1px precision for smoother height transitions + round(a0_deg * 10) / 10, # 0.1° precision for smoother angle transitions + round(a1_deg * 10) / 10, + tuple(sorted(kwargs.items()))) + + if key in cache: + cache.move_to_end(key) + else: + if len(cache) >= maxsize: + cache.popitem(last=False) + + result = func(r_mid, thickness, a0_deg, a1_deg, **kwargs) + cache[key] = result + return cache[key] + return wrapper + return decorator + + +@quantized_lru_cache(maxsize=256) +def arc_bar_pts(r_mid: float, thickness: float, + a0_deg: float, a1_deg: float, + *, max_points: int = 100, cap_segs: int = 10, + cap_radius: float = 7, px_per_seg: float = 2.0) -> np.ndarray: + """Return Nx2 np.float32 points for a single closed polygon (rounded thick arc), centered at origin.""" + + def get_cap(left: bool, a_deg: float): + # end cap at a1: center (a1), sweep a1→a1+180 (skip endpoints to avoid dupes) + # quarter arc (outer corner) at a1 with fixed pixel radius cap_radius + + nx, ny = math.cos(math.radians(a_deg)), math.sin(math.radians(a_deg)) # outward normal + tx, ty = -ny, nx # tangent (CCW) + + mx, my = nx * r_mid, ny * r_mid # mid-point at a1 + if DEBUG: + rl.draw_circle(int(mx), int(my), 4, rl.PURPLE) + + ex = mx + nx * (half - cap_radius) + ey = my + ny * (half - cap_radius) + + if DEBUG: + rl.draw_circle(int(ex), int(ey), 2, rl.WHITE) + + # sweep 90° in the local (t,n) frame: from outer edge toward inside + if not left: + alpha = np.deg2rad(np.linspace(90, 0, cap_segs + 2))[1:-1] + else: + alpha = np.deg2rad(np.linspace(180, 90, cap_segs + 2))[1:-1] + cap_end = np.c_[ex + np.cos(alpha) * cap_radius * tx + np.sin(alpha) * cap_radius * nx, + ey + np.cos(alpha) * cap_radius * ty + np.sin(alpha) * cap_radius * ny] + + # bottom quarter (inner corner) at a1 + ex2 = mx + nx * (-half + cap_radius) + ey2 = my + ny * (-half + cap_radius) + if DEBUG: + rl.draw_circle(int(ex2), int(ey2), 2, rl.WHITE) + + if not left: + alpha2 = np.deg2rad(np.linspace(0, -90, cap_segs + 1))[:-1] # include 0 once, exclude -90 + else: + alpha2 = np.deg2rad(np.linspace(90 - 90 - 90, 0 - 90 - 90, cap_segs + 1))[:-1] + cap_end_bot = np.c_[ex2 + np.cos(alpha2) * cap_radius * tx + np.sin(alpha2) * cap_radius * nx, + ey2 + np.cos(alpha2) * cap_radius * ty + np.sin(alpha2) * cap_radius * ny] + + # append to the top quarter + if not left: + cap_end = np.vstack((cap_end, cap_end_bot)) + else: + cap_end = np.vstack((cap_end_bot, cap_end)) + + return cap_end + + if a1_deg < a0_deg: + a0_deg, a1_deg = a1_deg, a0_deg + half = thickness * 0.5 + + cap_radius = min(cap_radius, half) + + span = max(1e-3, a1_deg - a0_deg) + + # pick arc segment count from arc length, clamp to shader points[] budget + arc_len = r_mid * math.radians(span) + arc_segs = max(6, int(arc_len / px_per_seg)) + max_arc = (max_points - (4 * cap_segs + 3)) // 2 + arc_segs = max(6, min(arc_segs, max_arc)) + + # outer arc a0→a1 + ang_o = np.deg2rad(np.linspace(a0_deg, a1_deg, arc_segs + 1)) + outer = np.c_[np.cos(ang_o) * (r_mid + half), + np.sin(ang_o) * (r_mid + half)] + + # end cap at a1 + cap_end = get_cap(False, a1_deg) + + # inner arc a1→a0 + ang_i = np.deg2rad(np.linspace(a1_deg, a0_deg, arc_segs + 1)) + inner = np.c_[np.cos(ang_i) * (r_mid - half), + np.sin(ang_i) * (r_mid - half)] + + # start cap at a0 + cap_start = get_cap(True, a0_deg) + + pts = np.vstack((outer, cap_end, inner, cap_start, outer[:1])).astype(np.float32) + + # Rotate to start from middle of cap for proper triangulation + pts = np.roll(pts, cap_segs, axis=0) + + if DEBUG: + n = len(pts) + idx = int(time.monotonic() * 12) % max(1, n) # speed: 12 pts/sec + for i, (x, y) in enumerate(pts): + j = (i - idx) % n # rotate the gradient + t = j / n + color = rl.Color(255, int(255 * (1 - t)), int(255 * t), 255) + rl.draw_circle(int(x), int(y), 2, color) + + return pts + + +DEFAULT_MAX_LAT_ACCEL = 3.0 # m/s^2 + + +class TorqueBar(Widget): + def __init__(self, demo: bool = False): + super().__init__() + self._demo = demo + self._torque_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + self._torque_line_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + def update_filter(self, value: float): + """Update the torque filter value (for demo mode).""" + self._torque_filter.update(value) + + def _update_state(self): + if self._demo: + return + + # torque line + if ui_state.sm['controlsState'].lateralControlState.which() == 'angleState': + controls_state = ui_state.sm['controlsState'] + car_state = ui_state.sm['carState'] + live_parameters = ui_state.sm['liveParameters'] + car_control = ui_state.sm['carControl'] + + # Include lateral accel error in estimated torque utilization + actual_lateral_accel = controls_state.curvature * car_state.vEgo ** 2 + desired_lateral_accel = controls_state.desiredCurvature * car_state.vEgo ** 2 + accel_diff = (desired_lateral_accel - actual_lateral_accel) + + # Include road roll in estimated torque utilization + # Roll is less accurate near standstill, so reduce its effect at low speed + roll_compensation = live_parameters.roll * ACCELERATION_DUE_TO_GRAVITY * np.interp(car_state.vEgo, [5, 15], [0.0, 1.0]) + lateral_acceleration = actual_lateral_accel - roll_compensation + max_lateral_acceleration = ui_state.CP.maxLateralAccel if ui_state.CP else DEFAULT_MAX_LAT_ACCEL + + if not car_control.latActive: + self._torque_filter.update(0.0) + else: + self._torque_filter.update(np.clip((lateral_acceleration + accel_diff) / max_lateral_acceleration, -1, 1)) + else: + self._torque_filter.update(-ui_state.sm['carOutput'].actuatorsOutput.torque) + + def _render(self, rect: rl.Rectangle) -> None: + # adjust y pos with torque + torque_line_offset = np.interp(abs(self._torque_filter.x), [0.5, 1], [22, 26]) + torque_line_height = np.interp(abs(self._torque_filter.x), [0.5, 1], [14, 56]) + + # animate alpha and angle span + if not self._demo: + self._torque_line_alpha_filter.update(ui_state.status != UIStatus.DISENGAGED) + else: + self._torque_line_alpha_filter.update(1.0) + + torque_line_bg_alpha = np.interp(abs(self._torque_filter.x), [0.5, 1.0], [0.25, 0.5]) + torque_line_bg_color = rl.Color(255, 255, 255, int(255 * torque_line_bg_alpha * self._torque_line_alpha_filter.x)) + if ui_state.status != UIStatus.ENGAGED and not self._demo: + torque_line_bg_color = rl.Color(255, 255, 255, int(255 * 0.15 * self._torque_line_alpha_filter.x)) + + # draw curved line polygon torque bar + torque_line_radius = 1200 + top_angle = -90 + torque_bg_angle_span = self._torque_line_alpha_filter.x * TORQUE_ANGLE_SPAN + torque_start_angle = top_angle - torque_bg_angle_span / 2 + torque_end_angle = top_angle + torque_bg_angle_span / 2 + # centerline radius & center (you already have these values) + mid_r = torque_line_radius + torque_line_height / 2 + + cx = rect.x + rect.width / 2 + 8 # offset 8px to right of camera feed + cy = rect.y + rect.height + torque_line_radius - torque_line_offset + offset = np.array([cx, cy], dtype=np.float32) + + # draw bg torque indicator line + bg_pts = arc_bar_pts(mid_r, torque_line_height, torque_start_angle, torque_end_angle) + offset + draw_polygon(rect, bg_pts, color=torque_line_bg_color) + + # draw torque indicator line + a0s = top_angle + a1s = a0s + torque_bg_angle_span / 2 * self._torque_filter.x + sl_pts = arc_bar_pts(mid_r, torque_line_height, a0s, a1s) + offset + + # draw beautiful gradient from center to 65% of the bg torque bar width + start_grad_pt = cx / rect.width + if self._torque_filter.x < 0: + end_grad_pt = (cx * (1 - 0.65) + (min(bg_pts[:, 0]) * 0.65)) / rect.width + else: + end_grad_pt = (cx * (1 - 0.65) + (max(bg_pts[:, 0]) * 0.65)) / rect.width + + # fade to orange as we approach max torque + start_color = blend_colors( + rl.Color(255, 255, 255, int(255 * 0.9 * self._torque_line_alpha_filter.x)), + rl.Color(255, 200, 0, int(255 * self._torque_line_alpha_filter.x)), # yellow + max(0, abs(self._torque_filter.x) - 0.75) * 4, + ) + end_color = blend_colors( + rl.Color(255, 255, 255, int(255 * 0.9 * self._torque_line_alpha_filter.x)), + rl.Color(255, 115, 0, int(255 * self._torque_line_alpha_filter.x)), # orange + max(0, abs(self._torque_filter.x) - 0.75) * 4, + ) + + if ui_state.status != UIStatus.ENGAGED and not self._demo: + start_color = end_color = rl.Color(255, 255, 255, int(255 * 0.35 * self._torque_line_alpha_filter.x)) + + gradient = Gradient( + start=(start_grad_pt, 0), + end=(end_grad_pt, 0), + colors=[ + start_color, + end_color, + ], + stops=[0.0, 1.0], + ) + + draw_polygon(rect, sl_pts, gradient=gradient) + + # draw center torque bar dot + if abs(self._torque_filter.x) < 0.5: + dot_y = self._rect.y + self._rect.height - torque_line_offset - torque_line_height / 2 + rl.draw_circle(int(cx), int(dot_y), 10 // 2, + rl.Color(182, 182, 182, int(255 * 0.9 * self._torque_line_alpha_filter.x))) diff --git a/selfdrive/ui/mici/tests/test_widget_leaks.py b/selfdrive/ui/mici/tests/test_widget_leaks.py new file mode 100755 index 00000000000000..e35cb4477686b0 --- /dev/null +++ b/selfdrive/ui/mici/tests/test_widget_leaks.py @@ -0,0 +1,119 @@ +import pyray as rl +rl.set_config_flags(rl.ConfigFlags.FLAG_WINDOW_HIDDEN) +import gc +import weakref +import pytest +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget + +# mici dialogs +from openpilot.selfdrive.ui.mici.layouts.onboarding import TrainingGuide as MiciTrainingGuide, OnboardingWindow as MiciOnboardingWindow +from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import DriverCameraDialog as MiciDriverCameraDialog +from openpilot.selfdrive.ui.mici.widgets.pairing_dialog import PairingDialog as MiciPairingDialog +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationDialog, BigInputDialog +from openpilot.selfdrive.ui.mici.layouts.settings.device import MiciFccModal + +# tici dialogs +from openpilot.selfdrive.ui.onroad.driver_camera_dialog import DriverCameraDialog as TiciDriverCameraDialog +from openpilot.selfdrive.ui.layouts.onboarding import OnboardingWindow as TiciOnboardingWindow +from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog as TiciPairingDialog +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog +from openpilot.system.ui.widgets.html_render import HtmlModal +from openpilot.system.ui.widgets.keyboard import Keyboard + +# FIXME: known small leaks not worth worrying about at the moment +KNOWN_LEAKS = { + "openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog.DriverCameraView", + "openpilot.selfdrive.ui.mici.layouts.onboarding.TermsPage", + "openpilot.selfdrive.ui.mici.layouts.onboarding.TrainingGuide", + "openpilot.selfdrive.ui.mici.layouts.onboarding.DeclinePage", + "openpilot.selfdrive.ui.mici.layouts.onboarding.OnboardingWindow", + "openpilot.selfdrive.ui.onroad.driver_state.DriverStateRenderer", + "openpilot.selfdrive.ui.onroad.driver_camera_dialog.DriverCameraDialog", + "openpilot.selfdrive.ui.layouts.onboarding.TermsPage", + "openpilot.selfdrive.ui.layouts.onboarding.DeclinePage", + "openpilot.selfdrive.ui.layouts.onboarding.OnboardingWindow", + "openpilot.system.ui.widgets.confirm_dialog.ConfirmDialog", + "openpilot.system.ui.widgets.label.Label", + "openpilot.system.ui.widgets.button.Button", + "openpilot.system.ui.widgets.html_render.HtmlRenderer", + "openpilot.system.ui.widgets.nav_widget.NavBar", + "openpilot.selfdrive.ui.mici.layouts.settings.device.MiciFccModal", + "openpilot.system.ui.widgets.inputbox.InputBox", + "openpilot.system.ui.widgets.scroller_tici.Scroller", + "openpilot.system.ui.widgets.label.UnifiedLabel", + "openpilot.system.ui.widgets.mici_keyboard.MiciKeyboard", + "openpilot.selfdrive.ui.mici.widgets.dialog.BigConfirmationDialog", + "openpilot.system.ui.widgets.keyboard.Keyboard", + "openpilot.system.ui.widgets.slider.BigSlider", + "openpilot.selfdrive.ui.mici.widgets.dialog.BigInputDialog", + "openpilot.system.ui.widgets.option_dialog.MultiOptionDialog", +} + + +def get_child_widgets(widget: Widget) -> list[Widget]: + children = [] + for val in widget.__dict__.values(): + items = val if isinstance(val, (list, tuple)) else (val,) + children.extend(w for w in items if isinstance(w, Widget)) + return children + + +@pytest.mark.skip(reason="segfaults") +def test_dialogs_do_not_leak(): + gui_app.init_window("ref-test") + + leaked_widgets = set() + + for ctor in ( + # mici + MiciDriverCameraDialog, MiciPairingDialog, + lambda: MiciTrainingGuide(lambda: None), + lambda: MiciOnboardingWindow(lambda: None), + lambda: BigDialog("test", "test"), + lambda: BigConfirmationDialog("test", gui_app.texture("icons_mici/settings/network/new/trash.png", 54, 64), lambda: None), + lambda: BigInputDialog("test"), + lambda: MiciFccModal(text="test"), + # tici + TiciDriverCameraDialog, TiciOnboardingWindow, TiciPairingDialog, Keyboard, + lambda: ConfirmDialog("test", "ok"), + lambda: MultiOptionDialog("test", ["a", "b"]), + lambda: HtmlModal(text="test"), + ): + widget = ctor() + all_refs = [weakref.ref(w) for w in get_child_widgets(widget) + [widget]] + + del widget + + for ref in all_refs: + if ref() is not None: + obj = ref() + name = f"{type(obj).__module__}.{type(obj).__qualname__}" + leaked_widgets.add(name) + + print(f"\n=== Widget {name} alive after del") + print(" Referrers:") + for r in gc.get_referrers(obj): + if r is obj: + continue + + if hasattr(r, '__self__') and r.__self__ is not obj: + print(f" bound method: {type(r.__self__).__qualname__}.{r.__name__}") + elif hasattr(r, '__func__'): + print(f" method: {r.__name__}") + else: + print(f" {type(r).__module__}.{type(r).__qualname__}") + del obj + + gui_app.close() + + unexpected = leaked_widgets - KNOWN_LEAKS + assert not unexpected, f"New leaked widgets: {unexpected}" + + fixed = KNOWN_LEAKS - leaked_widgets + assert not fixed, f"These leaks are fixed, remove from KNOWN_LEAKS: {fixed}" + + +if __name__ == "__main__": + test_dialogs_do_not_leak() diff --git a/selfdrive/ui/mici/widgets/big_multi_value_param.py b/selfdrive/ui/mici/widgets/big_multi_value_param.py new file mode 100644 index 00000000000000..c41fcdfd651e68 --- /dev/null +++ b/selfdrive/ui/mici/widgets/big_multi_value_param.py @@ -0,0 +1,60 @@ +"""BigMultiToggle bound to a param that stores the option *value*, not its index. + +`BigMultiParamToggle` (in button.py) stores the option index — that's the right +shape for enums where the index *is* the persistence value (e.g. driving +personality). It's the wrong shape for params that persist a domain value: +PEDAL_CAN_BUS is 0 or 2, BRAKE_FACTOR is 0.5/1.0/1.5/2.0. This wrapper maps +index ↔ value on load and store. + +Caller MUST pass `default_value`. If the persisted value isn't in `values` +(old version, manual edit, corruption), the widget pins to default_value +AND writes it back to persistence — the runtime may treat the anomalous +value differently from what the widget would display, so leaving the param +in the bad state means the UI silently lies about which mode is active. +""" +from collections.abc import Callable +from typing import Any + +from openpilot.common.params import Params +from openpilot.selfdrive.ui.mici.widgets.button import BigMultiToggle + + +class BigMultiValueParamToggle(BigMultiToggle): + def __init__( + self, + text: str, + param: str, + values: list[Any], + labels: list[str], + default_value: Any, + toggle_callback: Callable | None = None, + select_callback: Callable | None = None, + ): + assert len(values) == len(labels) and len(values) > 0 + assert default_value in values, f"default_value {default_value!r} must be in values {values!r}" + super().__init__(text, labels, toggle_callback, select_callback) + self._param = param + self._values = values + self._default_value = default_value + self._params = Params() + self._load_value() + + def _load_value(self): + raw = self._params.get(self._param, return_default=True) + if raw in self._values: + idx = self._values.index(raw) + else: + # Persisted value is out of range. Pin to caller-declared default + # and rewrite the param so the UI doesn't display one option while + # the runtime acts on a different one. + idx = self._values.index(self._default_value) + self._params.put(self._param, self._default_value) + self.set_value(self._options[idx]) + + def refresh(self): + self._load_value() + + def _handle_mouse_release(self, mouse_pos): + super()._handle_mouse_release(mouse_pos) + new_idx = self._options.index(self.value) + self._params.put(self._param, self._values[new_idx]) diff --git a/selfdrive/ui/mici/widgets/button.py b/selfdrive/ui/mici/widgets/button.py new file mode 100644 index 00000000000000..1dceb796916761 --- /dev/null +++ b/selfdrive/ui/mici/widgets/button.py @@ -0,0 +1,422 @@ +import math +import pyray as rl +from typing import Union +from enum import Enum +from collections.abc import Callable +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import DO_ZOOM +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.common.filter_simple import BounceFilter + +try: + from openpilot.common.params import Params +except ImportError: + Params = None + +SCROLLING_SPEED_PX_S = 50 +COMPLICATION_SIZE = 36 +LABEL_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) +COMPLICATION_GREY = rl.Color(0xAA, 0xAA, 0xAA, 255) +PRESSED_SCALE = 1.15 if DO_ZOOM else 1.07 + + +class ScrollState(Enum): + PRE_SCROLL = 0 + SCROLLING = 1 + POST_SCROLL = 2 + + +class BigCircleButton(Widget): + def __init__(self, icon: rl.Texture, red: bool = False, icon_offset: tuple[int, int] = (0, 0)): + super().__init__() + self._red = red + self._icon_offset = icon_offset + + # State + self.set_rect(rl.Rectangle(0, 0, 180, 180)) + self._scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._click_delay = 0.075 + + # Icons + self._txt_icon = icon + self._txt_btn_disabled_bg = gui_app.texture("icons_mici/buttons/button_circle_disabled.png", 180, 180) + + self._txt_btn_bg = gui_app.texture("icons_mici/buttons/button_circle.png", 180, 180) + self._txt_btn_pressed_bg = gui_app.texture("icons_mici/buttons/button_circle_pressed.png", 180, 180) + + self._txt_btn_red_bg = gui_app.texture("icons_mici/buttons/button_circle_red.png", 180, 180) + self._txt_btn_red_pressed_bg = gui_app.texture("icons_mici/buttons/button_circle_red_pressed.png", 180, 180) + + def _draw_content(self, btn_y: float): + # draw icon + icon_color = rl.Color(255, 255, 255, int(255 * 0.9)) if self.enabled else rl.Color(255, 255, 255, int(255 * 0.35)) + rl.draw_texture_ex(self._txt_icon, (self._rect.x + (self._rect.width - self._txt_icon.width) / 2 + self._icon_offset[0], + btn_y + (self._rect.height - self._txt_icon.height) / 2 + self._icon_offset[1]), 0, 1.0, icon_color) + + def _render(self, _): + # draw background + txt_bg = self._txt_btn_bg if not self._red else self._txt_btn_red_bg + if not self.enabled: + txt_bg = self._txt_btn_disabled_bg + elif self.is_pressed: + txt_bg = self._txt_btn_pressed_bg if not self._red else self._txt_btn_red_pressed_bg + + scale = self._scale_filter.update(PRESSED_SCALE if self.is_pressed else 1.0) + btn_x = self._rect.x + (self._rect.width * (1 - scale)) / 2 + btn_y = self._rect.y + (self._rect.height * (1 - scale)) / 2 + rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) + + self._draw_content(btn_y) + + +class BigCircleToggle(BigCircleButton): + def __init__(self, icon: rl.Texture, toggle_callback: Callable | None = None, icon_offset: tuple[int, int] = (0, 0)): + super().__init__(icon, False, icon_offset=icon_offset) + self._toggle_callback = toggle_callback + + # State + self._checked = False + + # Icons + self._txt_toggle_enabled = gui_app.texture("icons_mici/buttons/toggle_dot_enabled.png", 66, 66) + self._txt_toggle_disabled = gui_app.texture("icons_mici/buttons/toggle_dot_disabled.png", 66, 66) + + def set_checked(self, checked: bool): + self._checked = checked + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + self._checked = not self._checked + if self._toggle_callback: + self._toggle_callback(self._checked) + + def _draw_content(self, btn_y: float): + super()._draw_content(btn_y) + + # draw status icon + rl.draw_texture_ex(self._txt_toggle_enabled if self._checked else self._txt_toggle_disabled, + (self._rect.x + (self._rect.width - self._txt_toggle_enabled.width) / 2, btn_y + 5), + 0, 1.0, rl.WHITE) + + +class BigButton(Widget): + LABEL_HORIZONTAL_PADDING = 40 + LABEL_VERTICAL_PADDING = 23 # visually matches 30 in figma + + """A lightweight stand-in for the Qt BigButton, drawn & updated each frame.""" + + def __init__(self, text: str, value: str = "", icon: Union[rl.Texture, None] = None, scroll: bool = False): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 402, 180)) + self.text = text + self.value = value + self._txt_icon = icon + self._scroll = scroll + + self._scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._click_delay = 0.075 + self._shake_start: float | None = None + self._grow_animation_until: float | None = None + + self._rotate_icon_t: float | None = None + + self._label = UnifiedLabel(text, font_size=self._get_label_font_size(), font_weight=FontWeight.BOLD, + text_color=LABEL_COLOR, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, scroll=scroll, + line_height=0.9) + self._sub_label = UnifiedLabel(value, font_size=COMPLICATION_SIZE, font_weight=FontWeight.ROMAN, + text_color=COMPLICATION_GREY, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + self._update_label_layout() + + self._load_images() + + def set_icon(self, icon: Union[rl.Texture, None]): + self._txt_icon = icon + + def set_rotate_icon(self, rotate: bool): + if rotate and self._rotate_icon_t is not None: + return + self._rotate_icon_t = rl.get_time() if rotate else None + + def _load_images(self): + self._txt_default_bg = gui_app.texture("icons_mici/buttons/button_rectangle.png", 402, 180) + self._txt_pressed_bg = gui_app.texture("icons_mici/buttons/button_rectangle_pressed.png", 402, 180) + self._txt_disabled_bg = gui_app.texture("icons_mici/buttons/button_rectangle_disabled.png", 402, 180) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(lambda: touch_callback() and self._grow_animation_until is None) + + def _width_hint(self) -> int: + # Single line if scrolling, so hide behind icon if exists + icon_size = self._txt_icon.width if self._txt_icon and self._scroll and self.value else 0 + return int(self._rect.width - self.LABEL_HORIZONTAL_PADDING * 2 - icon_size) + + def _get_label_font_size(self): + if len(self.text) <= 18: + return 48 + else: + return 42 + + def _update_label_layout(self): + self._label.set_font_size(self._get_label_font_size()) + if self.value: + self._label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP) + else: + self._label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + + def set_text(self, text: str): + self.text = text + self._label.set_text(text) + self._update_label_layout() + + def set_value(self, value: str): + self.value = value + self._sub_label.set_text(value) + self._update_label_layout() + + def get_value(self) -> str: + return self.value + + def get_text(self): + return self.text + + def trigger_shake(self): + self._shake_start = rl.get_time() + + def trigger_grow_animation(self, duration: float = 0.65): + self._grow_animation_until = rl.get_time() + duration + + @property + def _shake_offset(self) -> float: + SHAKE_DURATION = 0.5 + SHAKE_AMPLITUDE = 24.0 + SHAKE_FREQUENCY = 32.0 + if self._shake_start is None: + return 0.0 + t = rl.get_time() - self._shake_start + if t > SHAKE_DURATION: + return 0.0 + decay = 1.0 - t / SHAKE_DURATION + return decay * SHAKE_AMPLITUDE * math.sin(t * SHAKE_FREQUENCY) + + def set_position(self, x: float, y: float) -> None: + super().set_position(x + self._shake_offset, y) + + def _handle_background(self) -> tuple[rl.Texture, float, float, float]: + if self._grow_animation_until is not None: + if rl.get_time() >= self._grow_animation_until: + self._grow_animation_until = None + + # draw _txt_default_bg + txt_bg = self._txt_default_bg + if not self.enabled: + txt_bg = self._txt_disabled_bg + elif self.is_pressed: + txt_bg = self._txt_pressed_bg + + scale = self._scale_filter.update(PRESSED_SCALE if self.is_pressed or self._grow_animation_until is not None else 1.0) + btn_x = self._rect.x + (self._rect.width * (1 - scale)) / 2 + btn_y = self._rect.y + (self._rect.height * (1 - scale)) / 2 + return txt_bg, btn_x, btn_y, scale + + def _draw_content(self, btn_y: float): + # LABEL ------------------------------------------------------------------ + label_x = self._rect.x + self.LABEL_HORIZONTAL_PADDING + + label_color = LABEL_COLOR if self.enabled else rl.Color(255, 255, 255, int(255 * 0.35)) + self._label.set_color(label_color) + label_rect = rl.Rectangle(label_x, btn_y + self.LABEL_VERTICAL_PADDING, self._width_hint(), + self._rect.height - self.LABEL_VERTICAL_PADDING * 2) + self._label.render(label_rect) + + if self.value: + label_y = btn_y + self.LABEL_VERTICAL_PADDING + self._label.get_content_height(self._width_hint()) + sub_label_height = btn_y + self._rect.height - self.LABEL_VERTICAL_PADDING - label_y + sub_label_rect = rl.Rectangle(label_x, label_y, self._width_hint(), sub_label_height) + self._sub_label.render(sub_label_rect) + + # ICON ------------------------------------------------------------------- + if self._txt_icon: + rotation = 0 + if self._rotate_icon_t is not None: + rotation = (rl.get_time() - self._rotate_icon_t) * 180 + + # draw top right with 30px padding + x = self._rect.x + self._rect.width - 30 - self._txt_icon.width / 2 + y = btn_y + 30 + self._txt_icon.height / 2 + source_rec = rl.Rectangle(0, 0, self._txt_icon.width, self._txt_icon.height) + dest_rec = rl.Rectangle(x, y, self._txt_icon.width, self._txt_icon.height) + origin = rl.Vector2(self._txt_icon.width / 2, self._txt_icon.height / 2) + rl.draw_texture_pro(self._txt_icon, source_rec, dest_rec, origin, rotation, rl.Color(255, 255, 255, int(255 * 0.9))) + + def _render(self, _): + txt_bg, btn_x, btn_y, scale = self._handle_background() + + if self._scroll: + # draw black background since images are transparent + scaled_rect = rl.Rectangle(btn_x, btn_y, self._rect.width * scale, self._rect.height * scale) + rl.draw_rectangle_rounded(scaled_rect, 0.4, 7, rl.Color(0, 0, 0, int(255 * 0.5))) + + self._draw_content(btn_y) + rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) + else: + rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) + self._draw_content(btn_y) + + +class BigToggle(BigButton): + def __init__(self, text: str, value: str = "", initial_state: bool = False, toggle_callback: Callable | None = None): + super().__init__(text, value, "") + self._checked = initial_state + self._toggle_callback = toggle_callback + + def _load_images(self): + super()._load_images() + self._txt_enabled_toggle = gui_app.texture("icons_mici/buttons/toggle_pill_enabled.png", 84, 66) + self._txt_disabled_toggle = gui_app.texture("icons_mici/buttons/toggle_pill_disabled.png", 84, 66) + + def set_checked(self, checked: bool): + self._checked = checked + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + self._checked = not self._checked + if self._toggle_callback: + self._toggle_callback(self._checked) + + def _draw_pill(self, x: float, y: float, checked: bool): + # draw toggle icon top right + if checked: + rl.draw_texture_ex(self._txt_enabled_toggle, (x, y), 0, 1.0, rl.WHITE) + else: + rl.draw_texture_ex(self._txt_disabled_toggle, (x, y), 0, 1.0, rl.WHITE) + + def _draw_content(self, btn_y: float): + super()._draw_content(btn_y) + + x = self._rect.x + self._rect.width - self._txt_enabled_toggle.width + y = btn_y + self._draw_pill(x, y, self._checked) + + +class BigMultiToggle(BigToggle): + def __init__(self, text: str, options: list[str], toggle_callback: Callable | None = None, + select_callback: Callable | None = None): + super().__init__(text, "", toggle_callback=toggle_callback) + assert len(options) > 0 + self._options = options + self._select_callback = select_callback + + self.set_value(self._options[0]) + + def _width_hint(self) -> int: + return int(self._rect.width - self.LABEL_HORIZONTAL_PADDING * 2 - self._txt_enabled_toggle.width) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + cur_idx = self._options.index(self.value) + new_idx = (cur_idx + 1) % len(self._options) + self.set_value(self._options[new_idx]) + if self._select_callback: + self._select_callback(self.value) + + def _draw_content(self, btn_y: float): + # don't draw pill from BigToggle + BigButton._draw_content(self, btn_y) + + checked_idx = self._options.index(self.value) + + x = self._rect.x + self._rect.width - self._txt_enabled_toggle.width + y = btn_y + + for i in range(len(self._options)): + self._draw_pill(x, y, checked_idx == i) + y += 35 + + +class GreyBigButton(BigButton): + """Users should manage newlines with this class themselves""" + + LABEL_HORIZONTAL_PADDING = 30 + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.set_touch_valid_callback(lambda: False) + + self._rect.width = 476 + + self._label.set_font_size(36) + self._label.set_font_weight(FontWeight.BOLD) + self._label.set_line_height(1.0) + + self._sub_label.set_font_size(36) + self._sub_label.set_text_color(rl.Color(255, 255, 255, int(255 * 0.9))) + self._sub_label.set_font_weight(FontWeight.DISPLAY_REGULAR) + self._sub_label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE if not self._label.text else + rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + self._sub_label.set_line_height(0.95) + + @property + def LABEL_VERTICAL_PADDING(self): + return BigButton.LABEL_VERTICAL_PADDING if self._label.text else 18 + + def _width_hint(self) -> int: + return int(self._rect.width - self.LABEL_HORIZONTAL_PADDING * 2) + + def _get_label_font_size(self): + return 36 + + def _render(self, _): + rl.draw_rectangle_rounded(self._rect, 0.4, 10, rl.Color(255, 255, 255, int(255 * 0.15))) + self._draw_content(self._rect.y) + + +class BigMultiParamToggle(BigMultiToggle): + def __init__(self, text: str, param: str, options: list[str], toggle_callback: Callable | None = None, + select_callback: Callable | None = None): + super().__init__(text, options, toggle_callback, select_callback) + self._param = param + + self._params = Params() + self._load_value() + + def _load_value(self): + self.set_value(self._options[self._params.get(self._param) or 0]) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + new_idx = self._options.index(self.value) + self._params.put(self._param, new_idx) + + +class BigParamControl(BigToggle): + def __init__(self, text: str, param: str, toggle_callback: Callable | None = None): + super().__init__(text, "", toggle_callback=toggle_callback) + self.param = param + self.params = Params() + self.set_checked(self.params.get_bool(self.param, False)) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + self.params.put_bool(self.param, self._checked, block=True) + + def refresh(self): + self.set_checked(self.params.get_bool(self.param, False)) + + +# TODO: param control base class +class BigCircleParamControl(BigCircleToggle): + def __init__(self, icon: rl.Texture, param: str, toggle_callback: Callable | None = None, + icon_offset: tuple[int, int] = (0, 0)): + super().__init__(icon, toggle_callback, icon_offset=icon_offset) + self._param = param + self.params = Params() + self.set_checked(self.params.get_bool(self._param, False)) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + self.params.put_bool(self._param, self._checked, block=True) + + def refresh(self): + self.set_checked(self.params.get_bool(self._param, False)) diff --git a/selfdrive/ui/mici/widgets/dialog.py b/selfdrive/ui/mici/widgets/dialog.py new file mode 100644 index 00000000000000..ed1466449b269a --- /dev/null +++ b/selfdrive/ui/mici/widgets/dialog.py @@ -0,0 +1,240 @@ +import abc +import math +import pyray as rl +from typing import Union +from collections.abc import Callable +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.mici_keyboard import MiciKeyboard +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.widgets.slider import RedBigSlider, BigSlider +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.ui.mici.widgets.button import BigCircleButton, BigButton, GreyBigButton + +DEBUG = False + +PADDING = 20 + + +class BigDialogBase(NavWidget, abc.ABC): + def __init__(self): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + +class BigDialog(BigDialogBase): + def __init__(self, title: str, description: str, icon: Union[rl.Texture, None] = None): + super().__init__() + self._card = GreyBigButton(title, description, icon) + + def _render(self, _): + self._card.render(rl.Rectangle( + self._rect.x + self._rect.width / 2 - self._card.rect.width / 2, + self._rect.y + self._rect.height / 2 - self._card.rect.height / 2, + self._card.rect.width, + self._card.rect.height, + )) + + +class BigConfirmationDialog(BigDialogBase): + def __init__(self, title: str, icon: rl.Texture, confirm_callback: Callable[[], None], + exit_on_confirm: bool = True, red: bool = False): + super().__init__() + self._confirm_callback = confirm_callback + self._exit_on_confirm = exit_on_confirm + + self._slider: BigSlider | RedBigSlider + if red: + self._slider = self._child(RedBigSlider(title, icon, confirm_callback=self._on_confirm)) + else: + self._slider = self._child(BigSlider(title, icon, confirm_callback=self._on_confirm)) + self._slider.set_enabled(lambda: self.enabled and not self.is_dismissing) # for nav stack + NavWidget + + def _on_confirm(self): + if self._exit_on_confirm: + self.dismiss(self._confirm_callback) + elif self._confirm_callback: + self._confirm_callback() + + def _update_state(self): + super()._update_state() + if self.is_dismissing and not self._slider.confirmed: + self._slider.reset() + + def _render(self, _): + self._slider.render(self._rect) + + +class BigInputDialog(BigDialogBase): + BACK_TOUCH_AREA_PERCENTAGE = 0.2 + BACKSPACE_RATE = 25 # hz + TEXT_INPUT_SIZE = 35 + + def __init__(self, + hint: str, + default_text: str = "", + minimum_length: int = 1, + confirm_callback: Callable[[str], None] | None = None, + auto_return_to_letters: str = ""): + super().__init__() + self._hint_label = UnifiedLabel(hint, font_size=35, text_color=rl.Color(255, 255, 255, int(255 * 0.35)), + font_weight=FontWeight.MEDIUM) + self._keyboard = MiciKeyboard(auto_return_to_letters=auto_return_to_letters) + self._keyboard.set_text(default_text) + self._keyboard.set_enabled(lambda: self.enabled and not self.is_dismissing) # for nav stack + NavWidget + self._minimum_length = minimum_length + + self._backspace_held_time: float | None = None + + self._backspace_img = gui_app.texture("icons_mici/settings/keyboard/backspace.png", 42, 36) + self._backspace_img_alpha = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + + self._enter_img = gui_app.texture("icons_mici/settings/keyboard/enter.png", 76, 62) + self._enter_disabled_img = gui_app.texture("icons_mici/settings/keyboard/enter_disabled.png", 76, 62) + self._enter_img_alpha = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + + # rects for top buttons + self._top_left_button_rect = rl.Rectangle(0, 0, 0, 0) + self._top_right_button_rect = rl.Rectangle(0, 0, 0, 0) + + def confirm_callback_wrapper(): + text = self._keyboard.text() + self.dismiss((lambda: confirm_callback(text)) if confirm_callback else None) + self._confirm_callback = confirm_callback_wrapper + + def _update_state(self): + super()._update_state() + + if self.is_dismissing: + self._backspace_held_time = None + return + + last_mouse_event = gui_app.last_mouse_event + if last_mouse_event.left_down and rl.check_collision_point_rec(last_mouse_event.pos, self._top_right_button_rect) and self._backspace_img_alpha.x > 1: + if self._backspace_held_time is None: + self._backspace_held_time = rl.get_time() + + if rl.get_time() - self._backspace_held_time > 0.5: + if gui_app.frame % round(gui_app.target_fps / self.BACKSPACE_RATE) == 0: + self._keyboard.backspace() + + else: + self._backspace_held_time = None + + def _render(self, _): + # draw current text so far below everything. text floats left but always stays in view + text = self._keyboard.text() + candidate_char = self._keyboard.get_candidate_character() + text_size = measure_text_cached(gui_app.font(FontWeight.ROMAN), text + candidate_char or self._hint_label.text, self.TEXT_INPUT_SIZE) + + bg_block_margin = 5 + text_x = PADDING / 2 + self._enter_img.width + PADDING + text_field_rect = rl.Rectangle(text_x, self._rect.y + PADDING - bg_block_margin, + self._rect.width - text_x * 2, + text_size.y) + + # draw text input + # push text left with a gradient on left side if too long + if text_size.x > text_field_rect.width: + text_x -= text_size.x - text_field_rect.width + + rl.begin_scissor_mode(int(text_field_rect.x), int(text_field_rect.y), int(text_field_rect.width), int(text_field_rect.height)) + rl.draw_text_ex(gui_app.font(FontWeight.ROMAN), text, rl.Vector2(text_x, text_field_rect.y), self.TEXT_INPUT_SIZE, 0, rl.WHITE) + + # draw grayed out character user is hovering over + if candidate_char: + candidate_char_size = measure_text_cached(gui_app.font(FontWeight.ROMAN), candidate_char, self.TEXT_INPUT_SIZE) + rl.draw_text_ex(gui_app.font(FontWeight.ROMAN), candidate_char, + rl.Vector2(min(text_x + text_size.x, text_field_rect.x + text_field_rect.width) - candidate_char_size.x, text_field_rect.y), + self.TEXT_INPUT_SIZE, 0, rl.Color(255, 255, 255, 128)) + + rl.end_scissor_mode() + + # draw gradient on left side to indicate more text + if text_size.x > text_field_rect.width: + rl.draw_rectangle_gradient_ex(rl.Rectangle(text_field_rect.x, text_field_rect.y, 80, text_field_rect.height), + rl.BLACK, rl.BLANK, rl.BLANK, rl.BLACK) + + # draw cursor + blink_alpha = (math.sin(rl.get_time() * 6) + 1) / 2 + if text: + cursor_x = min(text_x + text_size.x + 3, text_field_rect.x + text_field_rect.width) + else: + cursor_x = text_field_rect.x - 6 + rl.draw_rectangle_rounded(rl.Rectangle(cursor_x, text_field_rect.y, 4, text_size.y), + 1, 4, rl.Color(255, 255, 255, int(255 * blink_alpha))) + + # draw backspace icon with nice fade + self._backspace_img_alpha.update(255 * bool(text)) + if self._backspace_img_alpha.x > 1: + color = rl.Color(255, 255, 255, int(self._backspace_img_alpha.x)) + rl.draw_texture_ex(self._backspace_img, rl.Vector2(self._rect.width - self._backspace_img.width - 27, self._rect.y + 14), 0.0, 1.0, color) + + if not text and self._hint_label.text and not candidate_char: + # draw description if no text entered yet and not drawing candidate char + hint_rect = rl.Rectangle(text_field_rect.x, text_field_rect.y, + self._rect.width - text_field_rect.x - PADDING, + text_field_rect.height) + self._hint_label.render(hint_rect) + + # TODO: move to update state + # make rect take up entire area so it's easier to click + self._top_left_button_rect = rl.Rectangle(self._rect.x, self._rect.y, text_field_rect.x, self._rect.height - self._keyboard.get_keyboard_height()) + self._top_right_button_rect = rl.Rectangle(text_field_rect.x + text_field_rect.width, self._rect.y, + self._rect.width - (text_field_rect.x + text_field_rect.width), self._top_left_button_rect.height) + + # draw enter button + self._enter_img_alpha.update(255 if len(text) >= self._minimum_length else 0) + color = rl.Color(255, 255, 255, int(self._enter_img_alpha.x)) + rl.draw_texture_ex(self._enter_img, rl.Vector2(self._rect.x + PADDING / 2, self._rect.y), 0.0, 1.0, color) + color = rl.Color(255, 255, 255, 255 - int(self._enter_img_alpha.x)) + rl.draw_texture_ex(self._enter_disabled_img, rl.Vector2(self._rect.x + PADDING / 2, self._rect.y), 0.0, 1.0, color) + + # keyboard goes over everything + self._keyboard.render(self._rect) + + # draw debugging rect bounds + if DEBUG: + rl.draw_rectangle_lines_ex(text_field_rect, 1, rl.Color(100, 100, 100, 255)) + rl.draw_rectangle_lines_ex(self._top_right_button_rect, 1, rl.Color(0, 255, 0, 255)) + rl.draw_rectangle_lines_ex(self._top_left_button_rect, 1, rl.Color(0, 255, 0, 255)) + + def _handle_mouse_press(self, mouse_pos: MousePos): + super()._handle_mouse_press(mouse_pos) + # TODO: need to track where press was so enter and back can activate on release rather than press + # or turn into icon widgets :eyes_open: + + if self.is_dismissing: + return + + # handle backspace icon click + if rl.check_collision_point_rec(mouse_pos, self._top_right_button_rect) and self._backspace_img_alpha.x > 254: + self._keyboard.backspace() + elif rl.check_collision_point_rec(mouse_pos, self._top_left_button_rect) and self._enter_img_alpha.x > 254: + # handle enter icon click + self._confirm_callback() + + +class BigDialogButton(BigButton): + def __init__(self, text: str, value: str = "", icon: Union[str, rl.Texture] = "", description: str = ""): + super().__init__(text, value, icon) + self._description = description + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + dlg = BigDialog(self.text, self._description) + gui_app.push_widget(dlg) + + +class BigConfirmationCircleButton(BigCircleButton): + def __init__(self, title: str, icon: rl.Texture, confirm_callback: Callable[[], None], exit_on_confirm: bool = True, + red: bool = False, icon_offset: tuple[int, int] = (0, 0)): + super().__init__(icon, red, icon_offset) + + def show_confirm_dialog(): + gui_app.push_widget(BigConfirmationDialog(title, icon, confirm_callback, + exit_on_confirm=exit_on_confirm, red=red)) + + self.set_click_callback(show_confirm_dialog) diff --git a/selfdrive/ui/mici/widgets/pairing_dialog.py b/selfdrive/ui/mici/widgets/pairing_dialog.py new file mode 100644 index 00000000000000..a18b26ec0248af --- /dev/null +++ b/selfdrive/ui/mici/widgets/pairing_dialog.py @@ -0,0 +1,111 @@ +import pyray as rl +import qrcode +import numpy as np +import time + +from openpilot.common.api import Api +from openpilot.common.swaglog import cloudlog +from openpilot.common.params import Params +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.widgets.label import UnifiedLabel + + +class PairingDialog(NavWidget): + """Dialog for device pairing with QR code.""" + + QR_REFRESH_INTERVAL = 300 # 5 minutes in seconds + + def __init__(self): + super().__init__() + self._params = Params() + self._qr_texture: rl.Texture | None = None + self._last_qr_generation = float("-inf") + + self._txt_pair = gui_app.texture("icons_mici/settings/device/pair.png", 33, 60) + self._pair_label = UnifiedLabel("pair with comma connect", font_size=48, font_weight=FontWeight.BOLD, line_height=0.8) + + def _get_pairing_url(self) -> str: + try: + dongle_id = self._params.get("DongleId") or "" + token = Api(dongle_id).get_token({'pair': True}) + except Exception as e: + cloudlog.warning(f"Failed to get pairing token: {e}") + token = "" + return f"https://connect.comma.ai/?pair={token}" + + def _generate_qr_code(self) -> None: + try: + qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=0) + qr.add_data(self._get_pairing_url()) + qr.make(fit=True) + + pil_img = qr.make_image(fill_color="white", back_color="black").convert('RGBA') + img_array = np.array(pil_img, dtype=np.uint8) + + if self._qr_texture and self._qr_texture.id != 0: + rl.unload_texture(self._qr_texture) + + rl_image = rl.Image() + rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) + rl_image.width = pil_img.width + rl_image.height = pil_img.height + rl_image.mipmaps = 1 + rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 + + self._qr_texture = rl.load_texture_from_image(rl_image) + except Exception as e: + cloudlog.warning(f"QR code generation failed: {e}") + self._qr_texture = None + + def _check_qr_refresh(self) -> None: + current_time = time.monotonic() + if current_time - self._last_qr_generation >= self.QR_REFRESH_INTERVAL: + self._generate_qr_code() + self._last_qr_generation = current_time + + def _update_state(self): + super()._update_state() + if ui_state.prime_state.is_paired() and not self.is_dismissing: + self.dismiss() + + def _render(self, rect: rl.Rectangle): + self._check_qr_refresh() + + self._render_qr_code() + + label_x = self._rect.x + 8 + self._rect.height + 24 + self._pair_label.set_max_width(int(self._rect.width - label_x)) + self._pair_label.set_position(label_x, self._rect.y + 16) + self._pair_label.render() + + rl.draw_texture_ex(self._txt_pair, rl.Vector2(label_x, self._rect.y + self._rect.height - self._txt_pair.height - 16), + 0.0, 1.0, rl.Color(255, 255, 255, int(255 * 0.35))) + + def _render_qr_code(self) -> None: + if not self._qr_texture: + error_font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex( + error_font, "QR Code Error", rl.Vector2(self._rect.x + 20, self._rect.y + self._rect.height // 2 - 15), 30, 0.0, rl.RED + ) + return + + scale = self._rect.height / self._qr_texture.height + pos = rl.Vector2(round(self._rect.x + 8), round(self._rect.y)) + rl.draw_texture_ex(self._qr_texture, pos, 0.0, scale, rl.WHITE) + + def __del__(self): + if self._qr_texture and self._qr_texture.id != 0: + rl.unload_texture(self._qr_texture) + + +if __name__ == "__main__": + gui_app.init_window("pairing device") + pairing = PairingDialog() + gui_app.push_widget(pairing) + try: + for _ in gui_app.render(): + pass + finally: + del pairing diff --git a/selfdrive/ui/obstacle_chime.py b/selfdrive/ui/obstacle_chime.py new file mode 100644 index 00000000000000..14cc382a42812b --- /dev/null +++ b/selfdrive/ui/obstacle_chime.py @@ -0,0 +1,38 @@ +"""Sound id for the animal/person chime. + +Kept out of soundd so tests can import it without cereal. soundd plays +selfdrive/assets/sounds/animal_chime.wav when the alert type starts with +obstacleChime. AudibleAlert.none stays on the alert itself. +""" +from __future__ import annotations + +import math + +OBSTACLE_CHIME_ID = -113 +OBSTACLE_CHIME_FILE = "animal_chime.wav" +# Quiet-cabin scaling cannot drop this one sound below this level. +OBSTACLE_CHIME_MIN_VOLUME = 0.7 + + +def floor_volume(alert_id, volume: float) -> float: + """Keep the obstacle chime at or above 0.7. Every other sound is unchanged.""" + if alert_id != OBSTACLE_CHIME_ID: + return volume + try: + level = float(volume) + except (TypeError, ValueError): + level = 0.0 + if not math.isfinite(level): + level = 0.0 + return max(level, OBSTACLE_CHIME_MIN_VOLUME) + + +def alert_sound_id(raw, alert_type: str = "") -> int: + """Map a selfdriveState alert onto a sound_list key.""" + text = "" if alert_type is None else str(alert_type) + if text.startswith("obstacleChime"): + return OBSTACLE_CHIME_ID + try: + return int(raw) + except (TypeError, ValueError): + return 0 diff --git a/selfdrive/ui/onroad/__init__.py b/selfdrive/ui/onroad/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/selfdrive/ui/onroad/alert_renderer.py b/selfdrive/ui/onroad/alert_renderer.py new file mode 100644 index 00000000000000..a81fbfc440b0df --- /dev/null +++ b/selfdrive/ui/onroad/alert_renderer.py @@ -0,0 +1,178 @@ +import time +import pyray as rl +from dataclasses import dataclass +from cereal import messaging, log +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.hardware import TICI +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import Label + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus + +ALERT_MARGIN = 40 +ALERT_PADDING = 60 +ALERT_LINE_SPACING = 45 +ALERT_BORDER_RADIUS = 30 + +ALERT_FONT_SMALL = 66 +ALERT_FONT_MEDIUM = 74 +ALERT_FONT_BIG = 88 + +ALERT_HEIGHTS = { + AlertSize.small: 271, + AlertSize.mid: 420, +} + +SELFDRIVE_STATE_TIMEOUT = 5 # Seconds +SELFDRIVE_UNRESPONSIVE_TIMEOUT = 10 # Seconds + +# Constants +ALERT_COLORS = { + AlertStatus.normal: rl.Color(0x15, 0x15, 0x15, 0xF1), # #151515 with alpha 0xF1 + AlertStatus.userPrompt: rl.Color(0xDA, 0x6F, 0x25, 0xF1), # #DA6F25 with alpha 0xF1 + AlertStatus.critical: rl.Color(0xC9, 0x22, 0x31, 0xF1), # #C92231 with alpha 0xF1 +} + + +@dataclass +class Alert: + text1: str = "" + text2: str = "" + size: int = 0 + status: int = 0 + + +# Pre-defined alert instances +ALERT_STARTUP_PENDING = Alert( + text1=tr("openpilot Unavailable"), + text2=tr("Waiting to start"), + size=AlertSize.mid, + status=AlertStatus.normal, +) + +ALERT_CRITICAL_TIMEOUT = Alert( + text1=tr("TAKE CONTROL IMMEDIATELY"), + text2=tr("System Unresponsive"), + size=AlertSize.full, + status=AlertStatus.critical, +) + +ALERT_CRITICAL_REBOOT = Alert( + text1=tr("System Unresponsive"), + text2=tr("Reboot Device"), + size=AlertSize.mid, + status=AlertStatus.normal, +) + + +class AlertRenderer(Widget): + def __init__(self): + super().__init__() + self.font_regular: rl.Font = gui_app.font(FontWeight.NORMAL) + self.font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + + # font size is set dynamically + self._full_text1_label = Label("", font_size=0, font_weight=FontWeight.BOLD, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + text_alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP) + self._full_text2_label = Label("", font_size=ALERT_FONT_BIG, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + text_alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP) + + def get_alert(self, sm: messaging.SubMaster) -> Alert | None: + """Generate the current alert based on selfdrive state.""" + ss = sm['selfdriveState'] + + # Check if selfdriveState messages have stopped arriving + recv_frame = sm.recv_frame['selfdriveState'] + if not sm.updated['selfdriveState']: + time_since_onroad = time.monotonic() - ui_state.started_time + + # 1. Never received selfdriveState since going onroad + waiting_for_startup = recv_frame < ui_state.started_frame + if waiting_for_startup and time_since_onroad > 5: + return ALERT_STARTUP_PENDING + + # 2. Lost communication with selfdriveState after receiving it + if TICI and not waiting_for_startup: + ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] + if ss_missing > SELFDRIVE_STATE_TIMEOUT: + if ss.enabled and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < SELFDRIVE_UNRESPONSIVE_TIMEOUT: + return ALERT_CRITICAL_TIMEOUT + return ALERT_CRITICAL_REBOOT + + # No alert if size is none + if ss.alertSize == 0: + return None + + # Don't get old alert + if recv_frame < ui_state.started_frame: + return None + + # Return current alert + return Alert(text1=ss.alertText1, text2=ss.alertText2, size=ss.alertSize.raw, status=ss.alertStatus.raw) + + def _render(self, rect: rl.Rectangle): + alert = self.get_alert(ui_state.sm) + if not alert: + return + + alert_rect = self._get_alert_rect(rect, alert.size) + self._draw_background(alert_rect, alert) + + text_rect = rl.Rectangle( + alert_rect.x + ALERT_PADDING, + alert_rect.y + ALERT_PADDING, + alert_rect.width - 2 * ALERT_PADDING, + alert_rect.height - 2 * ALERT_PADDING + ) + self._draw_text(text_rect, alert) + + def _get_alert_rect(self, rect: rl.Rectangle, size: int) -> rl.Rectangle: + if size == AlertSize.full: + return rect + + h = ALERT_HEIGHTS.get(size, rect.height) + return rl.Rectangle(rect.x + ALERT_MARGIN, rect.y + rect.height - h + ALERT_MARGIN, + rect.width - ALERT_MARGIN * 2, h - ALERT_MARGIN * 2) + + def _draw_background(self, rect: rl.Rectangle, alert: Alert) -> None: + color = ALERT_COLORS.get(alert.status, ALERT_COLORS[AlertStatus.normal]) + + if alert.size != AlertSize.full: + roundness = ALERT_BORDER_RADIUS / (min(rect.width, rect.height) / 2) + rl.draw_rectangle_rounded(rect, roundness, 10, color) + else: + rl.draw_rectangle_rec(rect, color) + + def _draw_text(self, rect: rl.Rectangle, alert: Alert) -> None: + if alert.size == AlertSize.small: + self._draw_centered(alert.text1, rect, self.font_bold, ALERT_FONT_MEDIUM) + + elif alert.size == AlertSize.mid: + self._draw_centered(alert.text1, rect, self.font_bold, ALERT_FONT_BIG, center_y=False) + rect.y += ALERT_FONT_BIG + ALERT_LINE_SPACING + self._draw_centered(alert.text2, rect, self.font_regular, ALERT_FONT_SMALL, center_y=False) + + else: + is_long = len(alert.text1) > 15 + font_size1 = 132 if is_long else 177 + + top_offset = 200 if is_long or '\n' in alert.text1 else 270 + title_rect = rl.Rectangle(rect.x, rect.y + top_offset, rect.width, 600) + self._full_text1_label.set_font_size(font_size1) + self._full_text1_label.set_text(alert.text1) + self._full_text1_label.render(title_rect) + + bottom_offset = 361 if is_long else 420 + subtitle_rect = rl.Rectangle(rect.x, rect.y + rect.height - bottom_offset, rect.width, 300) + self._full_text2_label.set_text(alert.text2) + self._full_text2_label.render(subtitle_rect) + + def _draw_centered(self, text, rect, font, font_size, center_y=True, color=rl.WHITE) -> None: + text_size = measure_text_cached(font, text, font_size) + x = rect.x + (rect.width - text_size.x) / 2 + y = rect.y + ((rect.height - text_size.y) / 2 if center_y else 0) + rl.draw_text_ex(font, text, rl.Vector2(x, y), font_size, 0, color) diff --git a/selfdrive/ui/onroad/augmented_road_view.py b/selfdrive/ui/onroad/augmented_road_view.py new file mode 100644 index 00000000000000..fe3946ad1aea30 --- /dev/null +++ b/selfdrive/ui/onroad/augmented_road_view.py @@ -0,0 +1,233 @@ +import numpy as np +import pyray as rl +from cereal import log +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui import UI_BORDER_SIZE +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.selfdrive.ui.onroad.alert_renderer import AlertRenderer +from openpilot.selfdrive.ui.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.onroad.hud_renderer import HudRenderer +from openpilot.selfdrive.ui.onroad.model_renderer import ModelRenderer +from openpilot.selfdrive.ui.radar.radar_view import RadarHudOverlay, radar_hud_rect +from openpilot.selfdrive.ui.onroad.cameraview import CameraView +from openpilot.system.ui.lib.application import gui_app +from openpilot.common.transformations.camera import DEVICE_CAMERAS, DeviceCameraConfig, view_frame_from_device_frame +from openpilot.common.transformations.orientation import rot_from_euler + +OpState = log.SelfdriveState.OpenpilotState +CALIBRATED = log.LiveCalibrationData.Status.calibrated +ROAD_CAM = VisionStreamType.VISION_STREAM_ROAD +WIDE_CAM = VisionStreamType.VISION_STREAM_WIDE_ROAD +DEFAULT_DEVICE_CAMERA = DEVICE_CAMERAS["tici", "ar0231"] + +BORDER_COLORS = { + UIStatus.DISENGAGED: rl.Color(0x12, 0x28, 0x39, 0xFF), # Blue for disengaged state + UIStatus.OVERRIDE: rl.Color(0x89, 0x92, 0x8D, 0xFF), # Gray for override state + UIStatus.ENGAGED: rl.Color(0x16, 0x7F, 0x40, 0xFF), # Green for engaged state +} + +WIDE_CAM_MAX_SPEED = 10.0 # m/s (22 mph) +ROAD_CAM_MIN_SPEED = 15.0 # m/s (34 mph) +INF_POINT = np.array([1000.0, 0.0, 0.0]) + + +class AugmentedRoadView(CameraView): + def __init__(self, stream_type: VisionStreamType = VisionStreamType.VISION_STREAM_ROAD): + super().__init__("camerad", stream_type) + self._set_placeholder_color(BORDER_COLORS[UIStatus.DISENGAGED]) + + self.device_camera: DeviceCameraConfig | None = None + self.view_from_calib = view_frame_from_device_frame.copy() + self.view_from_wide_calib = view_frame_from_device_frame.copy() + + self._matrix_cache_key = (0, 0.0, 0.0, stream_type) + self._cached_matrix: np.ndarray | None = None + self._content_rect = rl.Rectangle() + + self.model_renderer = ModelRenderer() + self._hud_renderer = HudRenderer() + self._radar_hud = RadarHudOverlay() + self.alert_renderer = AlertRenderer() + self.driver_state_renderer = DriverStateRenderer() + + def _render(self, rect): + # Only render when system is started to avoid invalid data access + if not ui_state.started: + return + + self._switch_stream_if_needed(ui_state.sm) + + # Update calibration before rendering + self._update_calibration() + + # Create inner content area with border padding + self._content_rect = rl.Rectangle( + rect.x + UI_BORDER_SIZE, + rect.y + UI_BORDER_SIZE, + rect.width - 2 * UI_BORDER_SIZE, + rect.height - 2 * UI_BORDER_SIZE, + ) + + # Enable scissor mode to clip all rendering within content rectangle boundaries + # This creates a rendering viewport that prevents graphics from drawing outside the border + rl.begin_scissor_mode( + int(self._content_rect.x), + int(self._content_rect.y), + int(self._content_rect.width), + int(self._content_rect.height) + ) + + # Render the base camera view + super()._render(rect) + + # Draw all UI overlays + self.model_renderer.render(self._content_rect) + self._hud_renderer.render(self._content_rect) + self._radar_hud.render(radar_hud_rect(self._content_rect)) + self.alert_renderer.render(self._content_rect) + self.driver_state_renderer.render(self._content_rect) + + # Custom UI extension point - add custom overlays here + # Use self._content_rect for positioning within camera bounds + + # End clipping region + rl.end_scissor_mode() + + # Draw colored border based on driving state + self._draw_border(rect) + + def _handle_mouse_press(self, pos): + if self._hud_renderer.user_interacting() or self._click_callback is None: + return + try: + if self._hud_renderer.touch_on_hud_button(pos.x, pos.y): + return + except Exception: + pass + self._click_callback() + + def _handle_mouse_release(self, _): + # We only call click callback on press if not interacting with HUD + pass + + def _draw_border(self, rect: rl.Rectangle): + rl.draw_rectangle_lines_ex(rect, UI_BORDER_SIZE, rl.BLACK) + border_roundness = 0.12 + border_color = BORDER_COLORS.get(ui_state.status, BORDER_COLORS[UIStatus.DISENGAGED]) + border_rect = rl.Rectangle(rect.x + UI_BORDER_SIZE, rect.y + UI_BORDER_SIZE, + rect.width - 2 * UI_BORDER_SIZE, rect.height - 2 * UI_BORDER_SIZE) + rl.draw_rectangle_rounded_lines_ex(border_rect, border_roundness, 10, UI_BORDER_SIZE, border_color) + + def _switch_stream_if_needed(self, sm): + if sm['selfdriveState'].experimentalMode and WIDE_CAM in self.available_streams: + v_ego = sm['carState'].vEgo + if v_ego < WIDE_CAM_MAX_SPEED: + target = WIDE_CAM + elif v_ego > ROAD_CAM_MIN_SPEED: + target = ROAD_CAM + else: + # Hysteresis zone - keep current stream + target = self.stream_type + else: + target = ROAD_CAM + + if self.stream_type != target: + self.switch_stream(target) + + def _update_calibration(self): + # Update device camera if not already set + sm = ui_state.sm + if not self.device_camera and sm.seen['roadCameraState'] and sm.seen['deviceState']: + self.device_camera = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] + + # Check if live calibration data is available and valid + if not (sm.updated["liveCalibration"] and sm.valid['liveCalibration']): + return + + calib = sm['liveCalibration'] + if len(calib.rpyCalib) != 3 or calib.calStatus != CALIBRATED: + return + + # Update view_from_calib matrix + device_from_calib = rot_from_euler(calib.rpyCalib) + self.view_from_calib = view_frame_from_device_frame @ device_from_calib + + # Update wide calibration if available + if hasattr(calib, 'wideFromDeviceEuler') and len(calib.wideFromDeviceEuler) == 3: + wide_from_device = rot_from_euler(calib.wideFromDeviceEuler) + self.view_from_wide_calib = view_frame_from_device_frame @ wide_from_device @ device_from_calib + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + # Check if we can use cached matrix + cache_key = ( + ui_state.sm.recv_frame['liveCalibration'], + self._content_rect.width, + self._content_rect.height, + self.stream_type + ) + if cache_key == self._matrix_cache_key and self._cached_matrix is not None: + return self._cached_matrix + + # Get camera configuration + device_camera = self.device_camera or DEFAULT_DEVICE_CAMERA + is_wide_camera = self.stream_type == WIDE_CAM + intrinsic = device_camera.ecam.intrinsics if is_wide_camera else device_camera.fcam.intrinsics + calibration = self.view_from_wide_calib if is_wide_camera else self.view_from_calib + zoom = 2.0 if is_wide_camera else 1.1 + + # Calculate transforms for vanishing point + calib_transform = intrinsic @ calibration + kep = calib_transform @ INF_POINT + + # Calculate center points and dimensions + x, y = self._content_rect.x, self._content_rect.y + w, h = self._content_rect.width, self._content_rect.height + cx, cy = intrinsic[0, 2], intrinsic[1, 2] + + # Calculate max allowed offsets with margins + margin = 5 + max_x_offset = cx * zoom - w / 2 - margin + max_y_offset = cy * zoom - h / 2 - margin + + # Calculate and clamp offsets to prevent out-of-bounds issues + try: + if abs(kep[2]) > 1e-6: + x_offset = np.clip((kep[0] / kep[2] - cx) * zoom, -max_x_offset, max_x_offset) + y_offset = np.clip((kep[1] / kep[2] - cy) * zoom, -max_y_offset, max_y_offset) + else: + x_offset, y_offset = 0, 0 + except (ZeroDivisionError, OverflowError): + x_offset, y_offset = 0, 0 + + # Cache the computed transformation matrix to avoid recalculations + self._matrix_cache_key = cache_key + self._cached_matrix = np.array([ + [zoom * 2 * cx / w, 0, -x_offset / w * 2], + [0, zoom * 2 * cy / h, -y_offset / h * 2], + [0, 0, 1.0] + ]) + + video_transform = np.array([ + [zoom, 0.0, (w / 2 + x - x_offset) - (cx * zoom)], + [0.0, zoom, (h / 2 + y - y_offset) - (cy * zoom)], + [0.0, 0.0, 1.0] + ]) + self.model_renderer.set_transform(video_transform @ calib_transform) + + return self._cached_matrix + + +if __name__ == "__main__": + gui_app.init_window("OnRoad Camera View") + road_camera_view = AugmentedRoadView(ROAD_CAM) + gui_app.push_widget(road_camera_view) + print("***press space to switch camera view***") + try: + for _ in gui_app.render(): + ui_state.update() + if rl.is_key_released(rl.KeyboardKey.KEY_SPACE): + if WIDE_CAM in road_camera_view.available_streams: + stream = ROAD_CAM if road_camera_view.stream_type == WIDE_CAM else WIDE_CAM + road_camera_view.switch_stream(stream) + finally: + road_camera_view.close() diff --git a/selfdrive/ui/onroad/cameraview.py b/selfdrive/ui/onroad/cameraview.py new file mode 100644 index 00000000000000..53c2ff8b0b699a --- /dev/null +++ b/selfdrive/ui/onroad/cameraview.py @@ -0,0 +1,366 @@ +import platform +import numpy as np +import pyray as rl + +from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf +from openpilot.common.swaglog import cloudlog +from openpilot.system.hardware import TICI +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.egl import init_egl, create_egl_image, destroy_egl_image, bind_egl_image_to_texture, EGLImage +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.ui_state import ui_state + +CONNECTION_RETRY_INTERVAL = 0.2 # seconds between connection attempts + +VERSION = """ +#version 300 es +precision mediump float; +""" +if platform.system() == "Darwin": + VERSION = """ + #version 330 core + """ + + +VERTEX_SHADER = VERSION + """ +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexColor; +uniform mat4 mvp; +out vec2 fragTexCoord; +out vec4 fragColor; +void main() { + fragTexCoord = vertexTexCoord; + fragColor = vertexColor; + gl_Position = mvp * vec4(vertexPosition, 1.0); +} +""" + +# Choose fragment shader based on platform capabilities +if TICI: + FRAME_FRAGMENT_SHADER = """ + #version 300 es + #extension GL_OES_EGL_image_external_essl3 : enable + precision mediump float; + in vec2 fragTexCoord; + uniform samplerExternalOES texture0; + out vec4 fragColor; + void main() { + vec4 color = texture(texture0, fragTexCoord); + fragColor = vec4(pow(color.rgb, vec3(1.0/1.28)), color.a); + } + """ +else: + FRAME_FRAGMENT_SHADER = VERSION + """ + in vec2 fragTexCoord; + uniform sampler2D texture0; + uniform sampler2D texture1; + out vec4 fragColor; + void main() { + float y = texture(texture0, fragTexCoord).r; + vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; + fragColor = vec4(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x, 1.0); + } + """ + + +class CameraView(Widget): + def __init__(self, name: str, stream_type: VisionStreamType): + super().__init__() + self._name = name + # Primary stream + self.client = VisionIpcClient(name, stream_type, conflate=True) + self._stream_type = stream_type + self.available_streams: list[VisionStreamType] = [] + + # Target stream for switching + self._target_client: VisionIpcClient | None = None + self._target_stream_type: VisionStreamType | None = None + self._switching: bool = False + + self._texture_needs_update = True + self.last_connection_attempt: float = 0.0 + self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAME_FRAGMENT_SHADER) + self._texture1_loc: int = rl.get_shader_location(self.shader, "texture1") if not TICI else -1 + + self.frame: VisionBuf | None = None + self.texture_y: rl.Texture | None = None + self.texture_uv: rl.Texture | None = None + + # EGL resources + self.egl_images: dict[int, EGLImage] = {} + self.egl_texture: rl.Texture | None = None + + self._placeholder_color: rl.Color | None = None + + # Initialize EGL for zero-copy rendering on TICI + if TICI: + if not init_egl(): + raise RuntimeError("Failed to initialize EGL") + + # Create a 1x1 pixel placeholder texture for EGL image binding + temp_image = rl.gen_image_color(1, 1, rl.BLACK) + self.egl_texture = rl.load_texture_from_image(temp_image) + rl.unload_image(temp_image) + + ui_state.add_offroad_transition_callback(self._offroad_transition) + + def _offroad_transition(self): + # Reconnect if not first time going onroad + if ui_state.is_onroad() and self.frame is not None: + # Prevent old frames from showing when going onroad. Qt has a separate thread + # which drains the VisionIpcClient SubSocket for us. Re-connecting is not enough + # and only clears internal buffers, not the message queue. + self.frame = None + self.available_streams.clear() + if self.client: + del self.client + self.client = VisionIpcClient(self._name, self._stream_type, conflate=True) + + def _set_placeholder_color(self, color: rl.Color): + """Set a placeholder color to be drawn when no frame is available.""" + self._placeholder_color = color + + def switch_stream(self, stream_type: VisionStreamType) -> None: + if self._stream_type == stream_type: + return + + if self._switching and self._target_stream_type == stream_type: + return + + cloudlog.debug(f'Preparing switch from {self._stream_type} to {stream_type}') + + if self._target_client: + del self._target_client + + self._target_stream_type = stream_type + self._target_client = VisionIpcClient(self._name, stream_type, conflate=True) + self._switching = True + + @property + def stream_type(self) -> VisionStreamType: + return self._stream_type + + def close(self) -> None: + self._clear_textures() + + # Clean up EGL texture + if TICI and self.egl_texture: + rl.unload_texture(self.egl_texture) + self.egl_texture = None + + # Clean up shader + if self.shader and self.shader.id: + rl.unload_shader(self.shader) + + self.frame = None + self.available_streams.clear() + self.client = None + + def __del__(self): + self.close() + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + if not self.frame: + return np.eye(3) + + # Calculate aspect ratios + widget_aspect_ratio = rect.width / rect.height + frame_aspect_ratio = self.frame.width / self.frame.height + + # Calculate scaling factors to maintain aspect ratio + zx = min(frame_aspect_ratio / widget_aspect_ratio, 1.0) + zy = min(widget_aspect_ratio / frame_aspect_ratio, 1.0) + + return np.array([ + [zx, 0.0, 0.0], + [0.0, zy, 0.0], + [0.0, 0.0, 1.0] + ]) + + def _render(self, rect: rl.Rectangle): + if self._switching: + self._handle_switch() + + if not self._ensure_connection(): + self._draw_placeholder(rect) + return + + # Try to get a new buffer without blocking + buffer = self.client.recv(timeout_ms=0) + if buffer: + self._texture_needs_update = True + self.frame = buffer + elif not self.client.is_connected(): + # ensure we clear the displayed frame when the connection is lost + self.frame = None + + if not self.frame: + self._draw_placeholder(rect) + return + + transform = self._calc_frame_matrix(rect) + src_rect = rl.Rectangle(0, 0, float(self.frame.width), float(self.frame.height)) + # Flip driver camera horizontally + if self._stream_type == VisionStreamType.VISION_STREAM_DRIVER: + src_rect.width = -src_rect.width + + # Calculate scale + scale_x = rect.width * transform[0, 0] # zx + scale_y = rect.height * transform[1, 1] # zy + + # Calculate base position (centered) + x_offset = rect.x + (rect.width - scale_x) / 2 + y_offset = rect.y + (rect.height - scale_y) / 2 + + x_offset += transform[0, 2] * rect.width / 2 + y_offset += transform[1, 2] * rect.height / 2 + + dst_rect = rl.Rectangle(x_offset, y_offset, scale_x, scale_y) + + # Render with appropriate method + if TICI: + self._render_egl(src_rect, dst_rect) + else: + self._render_textures(src_rect, dst_rect) + + def _draw_placeholder(self, rect: rl.Rectangle): + if self._placeholder_color: + rl.draw_rectangle_rec(rect, self._placeholder_color) + + def _render_egl(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: + """Render using EGL for direct buffer access""" + if self.frame is None or self.egl_texture is None: + return + + idx = self.frame.idx + egl_image = self.egl_images.get(idx) + + # Create EGL image if needed + if egl_image is None: + egl_image = create_egl_image(self.frame.width, self.frame.height, self.frame.stride, self.frame.fd, self.frame.uv_offset) + if egl_image: + self.egl_images[idx] = egl_image + else: + return + + # Update texture dimensions to match current frame + self.egl_texture.width = self.frame.width + self.egl_texture.height = self.frame.height + + # Bind the EGL image to our texture + bind_egl_image_to_texture(self.egl_texture.id, egl_image) + + # Render with shader + rl.begin_shader_mode(self.shader) + rl.draw_texture_pro(self.egl_texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + + def _render_textures(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: + """Render using texture copies""" + if not self.texture_y or not self.texture_uv or self.frame is None: + return + + # Update textures with new frame data + if self._texture_needs_update: + y_data = self.frame.data[: self.frame.uv_offset] + uv_data = self.frame.data[self.frame.uv_offset:] + + rl.update_texture(self.texture_y, rl.ffi.cast("void *", rl.ffi.from_buffer(y_data))) + rl.update_texture(self.texture_uv, rl.ffi.cast("void *", rl.ffi.from_buffer(uv_data))) + self._texture_needs_update = False + + # Render with shader + rl.begin_shader_mode(self.shader) + rl.set_shader_value_texture(self.shader, self._texture1_loc, self.texture_uv) + rl.draw_texture_pro(self.texture_y, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + + def _ensure_connection(self) -> bool: + if not self.client.is_connected(): + self.frame = None + self.available_streams.clear() + + # Throttle connection attempts + current_time = rl.get_time() + if current_time - self.last_connection_attempt < CONNECTION_RETRY_INTERVAL: + return False + self.last_connection_attempt = current_time + + if not self.client.connect(False) or not self.client.num_buffers: + return False + + cloudlog.debug(f"Connected to {self._name} stream: {self._stream_type}, buffers: {self.client.num_buffers}") + self._initialize_textures() + self.available_streams = self.client.available_streams(self._name, block=False) + + return True + + def _handle_switch(self) -> None: + """Check if target stream is ready and switch immediately.""" + if not self._target_client or not self._switching: + return + + # Try to connect target if needed + if not self._target_client.is_connected(): + if not self._target_client.connect(False) or not self._target_client.num_buffers: + return + + cloudlog.debug(f"Target stream connected: {self._target_stream_type}") + + # Check if target has frames ready + target_frame = self._target_client.recv(timeout_ms=0) + if target_frame: + self.frame = target_frame # Update current frame to target frame + self._complete_switch() + + def _complete_switch(self) -> None: + """Instantly switch to target stream.""" + cloudlog.debug(f"Switching to {self._target_stream_type}") + # Clean up current resources + if self.client: + del self.client + + # Switch to target + self.client = self._target_client + self._stream_type = self._target_stream_type + self._texture_needs_update = True + + # Reset state + self._target_client = None + self._target_stream_type = None + self._switching = False + + # Initialize textures for new stream + self._initialize_textures() + + def _initialize_textures(self): + self._clear_textures() + if not TICI: + self.texture_y = rl.load_texture_from_image(rl.Image(None, int(self.client.stride), + int(self.client.height), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)) + self.texture_uv = rl.load_texture_from_image(rl.Image(None, int(self.client.stride // 2), + int(self.client.height // 2), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)) + + def _clear_textures(self): + if self.texture_y and self.texture_y.id: + rl.unload_texture(self.texture_y) + self.texture_y = None + + if self.texture_uv and self.texture_uv.id: + rl.unload_texture(self.texture_uv) + self.texture_uv = None + + # Clean up EGL resources + if TICI: + for data in self.egl_images.values(): + destroy_egl_image(data) + self.egl_images = {} + + +if __name__ == "__main__": + gui_app.init_window("camera view") + road = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) + for _ in gui_app.render(): + road.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) diff --git a/selfdrive/ui/onroad/driver_camera_dialog.py b/selfdrive/ui/onroad/driver_camera_dialog.py new file mode 100644 index 00000000000000..7e07e44210ba22 --- /dev/null +++ b/selfdrive/ui/onroad/driver_camera_dialog.py @@ -0,0 +1,111 @@ +import numpy as np +import pyray as rl +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui.onroad.cameraview import CameraView +from openpilot.selfdrive.ui.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets.label import gui_label + + +class DriverCameraDialog(CameraView): + def __init__(self): + super().__init__("camerad", VisionStreamType.VISION_STREAM_DRIVER) + self.driver_state_renderer = DriverStateRenderer() + # TODO: this can grow unbounded, should be given some thought + device.add_interactive_timeout_callback(gui_app.pop_widget) + ui_state.params.put_bool("IsDriverViewEnabled", True, block=True) + + def hide_event(self): + super().hide_event() + ui_state.params.put_bool("IsDriverViewEnabled", False, block=True) + self.close() + + def _handle_mouse_release(self, _): + super()._handle_mouse_release(_) + gui_app.pop_widget() + + def __del__(self): + self.close() + + def _render(self, rect): + super()._render(rect) + + if not self.frame: + gui_label( + rect, + tr("camera starting"), + font_size=100, + font_weight=FontWeight.BOLD, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + ) + return -1 + + self._draw_face_detection(rect) + self.driver_state_renderer.render(rect) + + return -1 + + def _draw_face_detection(self, rect: rl.Rectangle) -> None: + driver_state = ui_state.sm["driverStateV2"] + is_rhd = driver_state.wheelOnRightProb > 0.5 + driver_data = driver_state.rightDriverData if is_rhd else driver_state.leftDriverData + face_detect = driver_data.faceProb > 0.7 + if not face_detect: + return + + # Get face position and orientation + face_x, face_y = driver_data.facePosition + face_std = max(driver_data.faceOrientationStd[0], driver_data.faceOrientationStd[1]) + alpha = 0.7 + if face_std > 0.15: + alpha = max(0.7 - (face_std - 0.15) * 3.5, 0.0) + + # use approx instead of distort_points + # TODO: replace with distort_points + fbox_x = int(1080.0 - 1714.0 * face_x) + fbox_y = int(-135.0 + (504.0 + abs(face_x) * 112.0) + (1205.0 - abs(face_x) * 724.0) * face_y) + box_size = 220 + + line_color = rl.Color(255, 255, 255, int(alpha * 255)) + rl.draw_rectangle_rounded_lines_ex( + rl.Rectangle(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size), + 35.0 / box_size / 2, + 10, + 10, + line_color, + ) + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + driver_view_ratio = 2.0 + + # Get stream dimensions + if self.frame: + stream_width = self.frame.width + stream_height = self.frame.height + else: + # Default values if frame not available + stream_width = 1928 + stream_height = 1208 + + yscale = stream_height * driver_view_ratio / stream_width + xscale = yscale * rect.height / rect.width * stream_width / stream_height + + return np.array([ + [xscale, 0.0, 0.0], + [0.0, yscale, 0.0], + [0.0, 0.0, 1.0] + ]) + + +if __name__ == "__main__": + gui_app.init_window("Driver Camera View") + + driver_camera_view = DriverCameraDialog() + gui_app.push_widget(driver_camera_view) + try: + for _ in gui_app.render(): + ui_state.update() + finally: + driver_camera_view.close() diff --git a/selfdrive/ui/onroad/driver_state.py b/selfdrive/ui/onroad/driver_state.py new file mode 100644 index 00000000000000..5b09e471b52125 --- /dev/null +++ b/selfdrive/ui/onroad/driver_state.py @@ -0,0 +1,231 @@ +import numpy as np +import pyray as rl +from cereal import log +from dataclasses import dataclass +from openpilot.selfdrive.ui import UI_BORDER_SIZE +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget + +AlertSize = log.SelfdriveState.AlertSize + +# Default 3D coordinates for face keypoints as a NumPy array +DEFAULT_FACE_KPTS_3D = np.array([ + [-5.98, -51.20, 8.00], [-17.64, -49.14, 8.00], [-23.81, -46.40, 8.00], [-29.98, -40.91, 8.00], + [-32.04, -37.49, 8.00], [-34.10, -32.00, 8.00], [-36.16, -21.03, 8.00], [-36.16, 6.40, 8.00], + [-35.47, 10.51, 8.00], [-32.73, 19.43, 8.00], [-29.30, 26.29, 8.00], [-24.50, 33.83, 8.00], + [-19.01, 41.37, 8.00], [-14.21, 46.17, 8.00], [-12.16, 47.54, 8.00], [-4.61, 49.60, 8.00], + [4.99, 49.60, 8.00], [12.53, 47.54, 8.00], [14.59, 46.17, 8.00], [19.39, 41.37, 8.00], + [24.87, 33.83, 8.00], [29.67, 26.29, 8.00], [33.10, 19.43, 8.00], [35.84, 10.51, 8.00], + [36.53, 6.40, 8.00], [36.53, -21.03, 8.00], [34.47, -32.00, 8.00], [32.42, -37.49, 8.00], + [30.36, -40.91, 8.00], [24.19, -46.40, 8.00], [18.02, -49.14, 8.00], [6.36, -51.20, 8.00], + [-5.98, -51.20, 8.00], +], dtype=np.float32) + +# UI constants +BTN_SIZE = 192 +IMG_SIZE = 144 +ARC_LENGTH = 133 +ARC_THICKNESS_DEFAULT = 6.7 +ARC_THICKNESS_EXTEND = 12.0 + +SCALES_POS = np.array([0.9, 0.4, 0.4], dtype=np.float32) +SCALES_NEG = np.array([0.7, 0.4, 0.4], dtype=np.float32) + +ARC_POINT_COUNT = 37 # Number of points in the arc +ARC_ANGLES = np.linspace(0.0, np.pi, ARC_POINT_COUNT, dtype=np.float32) + + +@dataclass +class ArcData: + """Data structure for arc rendering parameters.""" + x: float + y: float + width: float + height: float + thickness: float + + +class DriverStateRenderer(Widget): + def __init__(self): + super().__init__() + # Initial state with NumPy arrays + self.face_kpts_draw = DEFAULT_FACE_KPTS_3D.copy() + self.is_active = False + self.is_rhd = False + self.dm_fade_state = 0.0 + self.driver_pose_vals = np.zeros(3, dtype=np.float32) + self.driver_pose_diff = np.zeros(3, dtype=np.float32) + self.driver_pose_sins = np.zeros(3, dtype=np.float32) + self.driver_pose_coss = np.zeros(3, dtype=np.float32) + self.face_keypoints_transformed = np.zeros((DEFAULT_FACE_KPTS_3D.shape[0], 2), dtype=np.float32) + self.position_x: float = 0.0 + self.position_y: float = 0.0 + self.h_arc_data = None + self.v_arc_data = None + + # Pre-allocate drawing arrays + self.face_lines = [rl.Vector2(0, 0) for _ in range(len(DEFAULT_FACE_KPTS_3D))] + self.h_arc_lines = [rl.Vector2(0, 0) for _ in range(ARC_POINT_COUNT)] + self.v_arc_lines = [rl.Vector2(0, 0) for _ in range(ARC_POINT_COUNT)] + + # Load the driver face icon + self.dm_img = gui_app.texture("icons/driver_face.png", IMG_SIZE, IMG_SIZE) + + # Colors + self.white_color = rl.Color(255, 255, 255, 255) + self.arc_color = rl.Color(26, 242, 66, 255) + self.engaged_color = rl.Color(26, 242, 66, 255) + self.disengaged_color = rl.Color(139, 139, 139, 255) + + self.set_visible(lambda: (ui_state.sm["selfdriveState"].alertSize == AlertSize.none and + ui_state.sm.recv_frame["driverStateV2"] > ui_state.started_frame)) + + def _render(self, rect): + # Set opacity based on active state + opacity = 0.65 if self.is_active else 0.2 + + # Draw background circle + rl.draw_circle(int(self.position_x), int(self.position_y), BTN_SIZE // 2, rl.Color(0, 0, 0, 70)) + + # Draw face icon + icon_pos = rl.Vector2(self.position_x - self.dm_img.width // 2, self.position_y - self.dm_img.height // 2) + rl.draw_texture_v(self.dm_img, icon_pos, rl.Color(255, 255, 255, int(255 * opacity))) + + # Draw face outline + self.white_color.a = int(255 * opacity) + rl.draw_spline_linear(self.face_lines, len(self.face_lines), 5.2, self.white_color) + + # Set arc color based on engaged state + self.arc_color = self.engaged_color if ui_state.engaged else self.disengaged_color + self.arc_color.a = int(0.4 * 255 * (1.0 - self.dm_fade_state)) # Fade out when inactive + + # Draw arcs + if self.h_arc_data: + rl.draw_spline_linear(self.h_arc_lines, len(self.h_arc_lines), self.h_arc_data.thickness, self.arc_color) + if self.v_arc_data: + rl.draw_spline_linear(self.v_arc_lines, len(self.v_arc_lines), self.v_arc_data.thickness, self.arc_color) + + def _update_state(self): + """Update the driver monitoring state based on model data""" + sm = ui_state.sm + if not self.is_visible: + return + + # Get monitoring state + dm_state = sm["driverMonitoringState"] + self.is_active = dm_state.activePolicy == log.DriverMonitoringState.MonitoringPolicy.vision + self.is_rhd = dm_state.isRHD + + # Update fade state (smoother transition between active/inactive) + fade_target = 0.0 if self.is_active else 0.5 + self.dm_fade_state = np.clip(self.dm_fade_state + 0.2 * (fade_target - self.dm_fade_state), 0.0, 1.0) + + # Get driver orientation data from appropriate camera + driverstate = sm["driverStateV2"] + driver_data = driverstate.rightDriverData if self.is_rhd else driverstate.leftDriverData + driver_orient = driver_data.faceOrientation + + # Update pose values with scaling and smoothing + driver_orient = np.array(driver_orient) + scales = np.where(driver_orient < 0, SCALES_NEG, SCALES_POS) + v_this = driver_orient * scales + self.driver_pose_diff = np.abs(self.driver_pose_vals - v_this) + self.driver_pose_vals = 0.8 * v_this + 0.2 * self.driver_pose_vals # Smooth changes + + # Apply fade to rotation and compute sin/cos + rotation_amount = self.driver_pose_vals * (1.0 - self.dm_fade_state) + self.driver_pose_sins = np.sin(rotation_amount) + self.driver_pose_coss = np.cos(rotation_amount) + + # Create rotation matrix for 3D face model + sin_y, sin_x, sin_z = self.driver_pose_sins + cos_y, cos_x, cos_z = self.driver_pose_coss + r_xyz = np.array( + [ + [cos_x * cos_z, cos_x * sin_z, -sin_x], + [-sin_y * sin_x * cos_z - cos_y * sin_z, -sin_y * sin_x * sin_z + cos_y * cos_z, -sin_y * cos_x], + [cos_y * sin_x * cos_z - sin_y * sin_z, cos_y * sin_x * sin_z + sin_y * cos_z, cos_y * cos_x], + ] + ) + + # Transform face keypoints using vectorized matrix multiplication + self.face_kpts_draw = DEFAULT_FACE_KPTS_3D @ r_xyz.T + self.face_kpts_draw[:, 2] = self.face_kpts_draw[:, 2] * (1.0 - self.dm_fade_state) + 8 * self.dm_fade_state + + # Pre-calculate the transformed keypoints + kp_depth = (self.face_kpts_draw[:, 2] - 8) / 120.0 + 1.0 + self.face_keypoints_transformed = self.face_kpts_draw[:, :2] * kp_depth[:, None] + + # Pre-calculate all drawing elements + self._pre_calculate_drawing_elements() + + def _pre_calculate_drawing_elements(self): + """Pre-calculate all drawing elements based on the current rectangle""" + # Calculate icon position (bottom-left or bottom-right) + width, height = self._rect.width, self._rect.height + offset = UI_BORDER_SIZE + BTN_SIZE // 2 + self.position_x = self._rect.x + (width - offset if self.is_rhd else offset) + self.position_y = self._rect.y + height - offset + + # Pre-calculate the face lines positions + positioned_keypoints = self.face_keypoints_transformed + np.array([self.position_x, self.position_y]) + for i in range(len(positioned_keypoints)): + self.face_lines[i].x = positioned_keypoints[i][0] + self.face_lines[i].y = positioned_keypoints[i][1] + + # Calculate arc dimensions based on head rotation + delta_x = -self.driver_pose_sins[1] * ARC_LENGTH / 2.0 # Horizontal movement + delta_y = -self.driver_pose_sins[0] * ARC_LENGTH / 2.0 # Vertical movement + + # Horizontal arc + h_width = abs(delta_x) + self.h_arc_data = self._calculate_arc_data( + delta_x, h_width, self.position_x, self.position_y - ARC_LENGTH / 2, + self.driver_pose_sins[1], self.driver_pose_diff[1], is_horizontal=True + ) + + # Vertical arc + v_height = abs(delta_y) + self.v_arc_data = self._calculate_arc_data( + delta_y, v_height, self.position_x - ARC_LENGTH / 2, self.position_y, + self.driver_pose_sins[0], self.driver_pose_diff[0], is_horizontal=False + ) + + def _calculate_arc_data( + self, delta: float, size: float, x: float, y: float, sin_val: float, diff_val: float, is_horizontal: bool + ): + """Calculate arc data and pre-compute arc points.""" + if size <= 0: + return None + + thickness = ARC_THICKNESS_DEFAULT + ARC_THICKNESS_EXTEND * min(1.0, diff_val * 5.0) + start_angle = (90 if sin_val > 0 else -90) if is_horizontal else (0 if sin_val > 0 else 180) + x = min(x + delta, x) if is_horizontal else x + y = y if is_horizontal else min(y + delta, y) + + arc_data = ArcData( + x=x, + y=y, + width=size if is_horizontal else ARC_LENGTH, + height=ARC_LENGTH if is_horizontal else size, + thickness=thickness, + ) + + # Pre-calculate arc points + angles = ARC_ANGLES + np.deg2rad(start_angle) + + center_x = x + arc_data.width / 2 + center_y = y + arc_data.height / 2 + radius_x = arc_data.width / 2 + radius_y = arc_data.height / 2 + + x_coords = center_x + np.cos(angles) * radius_x + y_coords = center_y - np.sin(angles) * radius_y + + arc_lines = self.h_arc_lines if is_horizontal else self.v_arc_lines + for i, (x_coord, y_coord) in enumerate(zip(x_coords, y_coords, strict=True)): + arc_lines[i].x = x_coord + arc_lines[i].y = y_coord + + return arc_data diff --git a/selfdrive/ui/onroad/exp_button.py b/selfdrive/ui/onroad/exp_button.py new file mode 100644 index 00000000000000..9a92ebc3c358a1 --- /dev/null +++ b/selfdrive/ui/onroad/exp_button.py @@ -0,0 +1,70 @@ +import time +import pyray as rl +from openpilot.common.params import Params +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget + + +class ExpButton(Widget): + def __init__(self, button_size: int, icon_size: int): + super().__init__() + self._params = Params() + self._experimental_mode: bool = False + self._engageable: bool = False + + # State hold mechanism + self._hold_duration = 2.0 # seconds + self._held_mode: bool | None = None + self._hold_end_time: float | None = None + + self._white_color: rl.Color = rl.Color(255, 255, 255, 255) + self._black_bg: rl.Color = rl.Color(0, 0, 0, 166) + self._txt_wheel: rl.Texture = gui_app.texture('icons/chffr_wheel.png', icon_size, icon_size) + self._txt_exp: rl.Texture = gui_app.texture('icons/experimental.png', icon_size, icon_size) + self._rect = rl.Rectangle(0, 0, button_size, button_size) + + def set_rect(self, rect: rl.Rectangle) -> None: + self._rect.x, self._rect.y = rect.x, rect.y + + def _update_state(self) -> None: + selfdrive_state = ui_state.sm["selfdriveState"] + self._experimental_mode = selfdrive_state.experimentalMode + self._engageable = selfdrive_state.engageable or selfdrive_state.enabled + + def _handle_mouse_release(self, _): + super()._handle_mouse_release(_) + if self._is_toggle_allowed(): + new_mode = not self._experimental_mode + self._params.put_bool("ExperimentalMode", new_mode) + + # Hold new state temporarily + self._held_mode = new_mode + self._hold_end_time = time.monotonic() + self._hold_duration + + def _render(self, rect: rl.Rectangle) -> None: + center_x = int(self._rect.x + self._rect.width // 2) + center_y = int(self._rect.y + self._rect.height // 2) + + self._white_color.a = 180 if self.is_pressed or not self._engageable else 255 + + texture = self._txt_exp if self._held_or_actual_mode() else self._txt_wheel + rl.draw_circle(center_x, center_y, self._rect.width / 2, self._black_bg) + rl.draw_texture_ex(texture, rl.Vector2(center_x - texture.width / 2, center_y - texture.height / 2), 0.0, 1.0, self._white_color) + + def _held_or_actual_mode(self): + now = time.monotonic() + if self._hold_end_time and now < self._hold_end_time: + return self._held_mode + + if self._hold_end_time and now >= self._hold_end_time: + self._hold_end_time = self._held_mode = None + + return self._experimental_mode + + def _is_toggle_allowed(self): + if not self._params.get_bool("ExperimentalModeConfirmed"): + return False + + # Mirror exp mode toggle using persistent car params + return ui_state.has_longitudinal_control diff --git a/selfdrive/ui/onroad/force_offroad_confirm.py b/selfdrive/ui/onroad/force_offroad_confirm.py new file mode 100644 index 00000000000000..0cbf4fa1e85c55 --- /dev/null +++ b/selfdrive/ui/onroad/force_offroad_confirm.py @@ -0,0 +1,129 @@ +"""On-road Yes/No before Force Offroad stock-CC handoff. + +Justin: big, hard to miss while driving. Same ConfirmDialog stack as +other 3X NAP modals (gui_app.push_widget), larger type + buttons. +Not a Settings row. +""" +from collections.abc import Callable + +import pyray as rl + +from openpilot.common.params import Params +from openpilot.system.hardware.nap_force_offroad import ( + CONFIRM_NO, + CONFIRM_PROMPT, + CONFIRM_YES, + CONFIRMED_PARAM, + HANDOFF_READY_PARAM, + PARAM, + apply_force_offroad_toggle, + cancel_force_offroad, + confirm_force_offroad, + needs_driver_confirm, +) +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.label import Label + +# Larger than stock ConfirmDialog (70 / 160) so it reads at speed. +_PROMPT_SIZE = 90 +_BUTTON_HEIGHT = 200 +_BUTTON_FONT = 80 +_OUTER = 80 +_MARGIN = 40 +_DIM = rl.Color(0, 0, 0, 180) +_CARD = rl.Color(27, 27, 27, 255) + + +class ForceOffroadConfirmDialog(ConfirmDialog): + """Full-screen dim + large Yes / No. Copy is Justin's prompt.""" + + def __init__(self, callback: Callable[[DialogResult], None] | None = None): + super().__init__(CONFIRM_PROMPT, CONFIRM_YES, cancel_text=CONFIRM_NO, callback=callback) + self._label = Label( + CONFIRM_PROMPT, _PROMPT_SIZE, FontWeight.BOLD, + text_color=rl.Color(201, 201, 201, 255), + ) + self._cancel_button = Button( + CONFIRM_NO, self._cancel_button_callback, font_size=_BUTTON_FONT, + ) + self._confirm_button = Button( + CONFIRM_YES, self._confirm_button_callback, font_size=_BUTTON_FONT, + button_style=ButtonStyle.PRIMARY, + ) + + def _render(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, _DIM) + dialog_x = _OUTER + dialog_y = _OUTER + dialog_width = gui_app.width - 2 * dialog_x + dialog_height = gui_app.height - 2 * dialog_y + dialog_rect = rl.Rectangle(dialog_x, dialog_y, dialog_width, dialog_height) + + bottom = dialog_rect.y + dialog_rect.height + button_width = (dialog_rect.width - 3 * _MARGIN) // 2 + cancel_button_x = dialog_rect.x + _MARGIN + confirm_button_x = dialog_rect.x + dialog_rect.width - button_width - _MARGIN + button_y = bottom - _BUTTON_HEIGHT - _MARGIN + cancel_button = rl.Rectangle(cancel_button_x, button_y, button_width, _BUTTON_HEIGHT) + confirm_button = rl.Rectangle(confirm_button_x, button_y, button_width, _BUTTON_HEIGHT) + + rl.draw_rectangle_rec(dialog_rect, _CARD) + + text_rect = rl.Rectangle( + dialog_rect.x + _MARGIN, dialog_rect.y + 24, + dialog_rect.width - 2 * _MARGIN, + dialog_rect.height - _BUTTON_HEIGHT - _MARGIN - 48, + ) + self._label.render(text_rect) + + if rl.is_key_pressed(rl.KeyboardKey.KEY_ENTER): + self._confirm_button_callback() + elif rl.is_key_pressed(rl.KeyboardKey.KEY_ESCAPE): + self._cancel_button_callback() + + self._confirm_button.render(confirm_button) + self._cancel_button.render(cancel_button) + + +_dialog_open = False + + +def _on_result(result: DialogResult): + global _dialog_open + _dialog_open = False + params = Params() + if result == DialogResult.CONFIRM: + confirm_force_offroad(params) + else: + cancel_force_offroad(params) + + +def show_force_offroad_confirm() -> bool: + """Push the dialog once. Returns True if it was shown this call.""" + global _dialog_open + if _dialog_open: + return False + _dialog_open = True + gui_app.push_widget(ForceOffroadConfirmDialog(callback=_on_result)) + return True + + +def maybe_show_force_offroad_confirm(params=None, started: bool | None = None) -> bool: + """MainLayout tick: show when onroad Force Offroad is waiting for Yes.""" + if params is None: + params = Params() + if started is None: + from openpilot.selfdrive.ui.ui_state import ui_state + started = bool(ui_state.started) + force = bool(params.get_bool(PARAM)) + confirmed = bool(params.get_bool(CONFIRMED_PARAM)) + if not force: + if confirmed or params.get_bool(HANDOFF_READY_PARAM): + apply_force_offroad_toggle(params, False, started=False) + return False + if not needs_driver_confirm(force, confirmed, started): + return False + return show_force_offroad_confirm() diff --git a/selfdrive/ui/onroad/hud_renderer.py b/selfdrive/ui/onroad/hud_renderer.py new file mode 100644 index 00000000000000..ae5641c03d9f68 --- /dev/null +++ b/selfdrive/ui/onroad/hud_renderer.py @@ -0,0 +1,246 @@ +import pyray as rl +from dataclasses import dataclass +from openpilot.common.constants import CV +from openpilot.selfdrive.controls.lib.gap_lock import gap_lock_hud_chip +from openpilot.selfdrive.ui.onroad.exp_button import ExpButton +from openpilot.selfdrive.ui.onroad.speed_sign_hud import SpeedSignHud +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + +# Constants +SET_SPEED_NA = 255 +KM_TO_MILE = 0.621371 +CRUISE_DISABLED_CHAR = '–' + + +@dataclass(frozen=True) +class UIConfig: + header_height: int = 300 + border_size: int = 30 + button_size: int = 192 + set_speed_width_metric: int = 200 + set_speed_width_imperial: int = 172 + set_speed_height: int = 204 + wheel_icon_size: int = 144 + + +@dataclass(frozen=True) +class FontSizes: + current_speed: int = 176 + speed_unit: int = 66 + max_speed: int = 40 + set_speed: int = 90 + + +@dataclass(frozen=True) +class Colors: + WHITE = rl.WHITE + DISENGAGED = rl.Color(145, 155, 149, 255) + OVERRIDE = rl.Color(145, 155, 149, 255) # Added + ENGAGED = rl.Color(128, 216, 166, 255) + DISENGAGED_BG = rl.Color(0, 0, 0, 153) + OVERRIDE_BG = rl.Color(145, 155, 149, 204) + ENGAGED_BG = rl.Color(128, 216, 166, 204) + GREY = rl.Color(166, 166, 166, 255) + DARK_GREY = rl.Color(114, 114, 114, 255) + BLACK_TRANSLUCENT = rl.Color(0, 0, 0, 166) + WHITE_TRANSLUCENT = rl.Color(255, 255, 255, 200) + BORDER_TRANSLUCENT = rl.Color(255, 255, 255, 75) + HEADER_GRADIENT_START = rl.Color(0, 0, 0, 114) + HEADER_GRADIENT_END = rl.BLANK + + +UI_CONFIG = UIConfig() +FONT_SIZES = FontSizes() +COLORS = Colors() + + +class HudRenderer(Widget): + def __init__(self): + super().__init__() + """Initialize the HUD renderer.""" + self.is_cruise_set: bool = False + self.is_cruise_available: bool = True + self.set_speed: float = SET_SPEED_NA + self.speed: float = 0.0 + self.map_speed_valid: bool = False + self.map_speed_limit: float = 0.0 + self.gap_lock_chip: str | None = None + + self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) + self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM) + + self._exp_button: ExpButton = ExpButton(UI_CONFIG.button_size, UI_CONFIG.wheel_icon_size) + self._speed_sign_hud = SpeedSignHud(tici=True) + + def _update_state(self) -> None: + """Update HUD state based on car state and controls state.""" + sm = ui_state.sm + if sm.recv_frame["carState"] < ui_state.started_frame: + self.is_cruise_set = False + self.set_speed = SET_SPEED_NA + self.speed = 0.0 + self.gap_lock_chip = None + return + + controls_state = sm['controlsState'] + car_state = sm['carState'] + + v_cruise_cluster = car_state.vCruiseCluster + self.set_speed = ( + controls_state.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster + ) + self.is_cruise_set = 0 < self.set_speed < SET_SPEED_NA + self.is_cruise_available = self.set_speed != -1 + + if self.is_cruise_set and not ui_state.is_metric: + self.set_speed *= KM_TO_MILE + + # Top-middle live speed is wheel/ESP vEgo only. vEgoCluster is Tesla + # DI_digitalSpeed, which pre-AP also uses as cruiseState.speed. Map-speed + # writes MAX into vCruise / pedal_speed / cruiseState.speed (90 kph = 56 mph). + # That set-speed path must not appear here. + speed_conversion = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + self.speed = max(0.0, float(car_state.vEgo) * speed_conversion) + + self.map_speed_valid = False + self.map_speed_limit = 0.0 + self.gap_lock_chip = None + if sm.valid.get("longitudinalPlan", False): + self.gap_lock_chip = gap_lock_hud_chip(getattr(sm["longitudinalPlan"], "gapLockM", 0.0)) + if "liveMapDataNAP" in sm.valid and sm.valid["liveMapDataNAP"]: + md = sm["liveMapDataNAP"] + if md.speedLimitValid and md.speedLimit > 0: + self.map_speed_valid = True + self.map_speed_limit = md.speedLimit * speed_conversion + + def _render(self, rect: rl.Rectangle) -> None: + """Render HUD elements to the screen.""" + # Draw the header background + rl.draw_rectangle_gradient_v( + int(rect.x), + int(rect.y), + int(rect.width), + UI_CONFIG.header_height, + COLORS.HEADER_GRADIENT_START, + COLORS.HEADER_GRADIENT_END, + ) + + if self.is_cruise_available: + self._draw_set_speed(rect) + self._draw_map_speed_limit(rect) + self._draw_gap_lock(rect) + + self._draw_current_speed(rect) + self._speed_sign_hud.render(rect) + + button_x = rect.x + rect.width - UI_CONFIG.border_size - UI_CONFIG.button_size + button_y = rect.y + UI_CONFIG.border_size + self._exp_button.render(rl.Rectangle(button_x, button_y, UI_CONFIG.button_size, UI_CONFIG.button_size)) + + def touch_on_hud_button(self, x: float, y: float) -> bool: + return self._speed_sign_hud.owns_touch(x, y) + + def user_interacting(self) -> bool: + return self._exp_button.is_pressed or self._speed_sign_hud.is_pressed + + def _draw_set_speed(self, rect: rl.Rectangle) -> None: + """Draw the MAX speed indicator box.""" + set_speed_width = UI_CONFIG.set_speed_width_metric if ui_state.is_metric else UI_CONFIG.set_speed_width_imperial + x = rect.x + 60 + (UI_CONFIG.set_speed_width_imperial - set_speed_width) // 2 + y = rect.y + 45 + + set_speed_rect = rl.Rectangle(x, y, set_speed_width, UI_CONFIG.set_speed_height) + rl.draw_rectangle_rounded(set_speed_rect, 0.35, 10, COLORS.BLACK_TRANSLUCENT) + rl.draw_rectangle_rounded_lines_ex(set_speed_rect, 0.35, 10, 6, COLORS.BORDER_TRANSLUCENT) + + max_color = COLORS.GREY + set_speed_color = COLORS.DARK_GREY + if self.is_cruise_set: + set_speed_color = COLORS.WHITE + if ui_state.status == UIStatus.ENGAGED: + max_color = COLORS.ENGAGED + elif ui_state.status == UIStatus.DISENGAGED: + max_color = COLORS.DISENGAGED + elif ui_state.status == UIStatus.OVERRIDE: + max_color = COLORS.OVERRIDE + + max_text = tr("MAX") + max_text_width = measure_text_cached(self._font_semi_bold, max_text, FONT_SIZES.max_speed).x + rl.draw_text_ex( + self._font_semi_bold, + max_text, + rl.Vector2(x + (set_speed_width - max_text_width) / 2, y + 27), + FONT_SIZES.max_speed, + 0, + max_color, + ) + + set_speed_text = CRUISE_DISABLED_CHAR if not self.is_cruise_set else str(round(self.set_speed)) + speed_text_width = measure_text_cached(self._font_bold, set_speed_text, FONT_SIZES.set_speed).x + rl.draw_text_ex( + self._font_bold, + set_speed_text, + rl.Vector2(x + (set_speed_width - speed_text_width) / 2, y + 77), + FONT_SIZES.set_speed, + 0, + set_speed_color, + ) + + def _draw_gap_lock(self, rect: rl.Rectangle) -> None: + """Chip under MAX while a gap lock is latched. Gone when the lock clears.""" + text = self.gap_lock_chip + if not text: + return + set_speed_width = UI_CONFIG.set_speed_width_metric if ui_state.is_metric else UI_CONFIG.set_speed_width_imperial + x = rect.x + 60 + (UI_CONFIG.set_speed_width_imperial - set_speed_width) // 2 + y = rect.y + 45 + UI_CONFIG.set_speed_height + 14 + font_size = 36 + text_size = measure_text_cached(self._font_bold, text, font_size) + w = max(float(set_speed_width), text_size.x + 28) + h = 58 + chip = rl.Rectangle(x, y, w, h) + rl.draw_rectangle_rounded(chip, 0.35, 8, COLORS.BLACK_TRANSLUCENT) + rl.draw_rectangle_rounded_lines_ex(chip, 0.35, 8, 4, COLORS.ENGAGED) + rl.draw_text_ex( + self._font_bold, + text, + rl.Vector2(x + (w - text_size.x) / 2, y + (h - text_size.y) / 2), + font_size, + 0, + COLORS.ENGAGED, + ) + + def _draw_map_speed_limit(self, rect: rl.Rectangle) -> None: + """MUTCD-style OSM speed-limit sign to the right of MAX.""" + if not self.map_speed_valid: + return + set_speed_width = UI_CONFIG.set_speed_width_metric if ui_state.is_metric else UI_CONFIG.set_speed_width_imperial + x = rect.x + 60 + (UI_CONFIG.set_speed_width_imperial - set_speed_width) // 2 + set_speed_width + 18 + y = rect.y + 45 + w, h = 132, 168 + sign = rl.Rectangle(x, y, w, h) + rl.draw_rectangle_rounded(sign, 0.12, 8, rl.WHITE) + rl.draw_rectangle_rounded_lines_ex(sign, 0.12, 8, 4, rl.Color(180, 40, 40, 255)) + label = tr("LIMIT") + label_w = measure_text_cached(self._font_semi_bold, label, 28).x + rl.draw_text_ex(self._font_semi_bold, label, rl.Vector2(x + (w - label_w) / 2, y + 14), 28, 0, rl.Color(40, 40, 40, 255)) + num = str(round(self.map_speed_limit)) + num_w = measure_text_cached(self._font_bold, num, 64).x + rl.draw_text_ex(self._font_bold, num, rl.Vector2(x + (w - num_w) / 2, y + 52), 64, 0, rl.BLACK) + + def _draw_current_speed(self, rect: rl.Rectangle) -> None: + """Draw the current vehicle speed and unit.""" + speed_text = str(round(self.speed)) + speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) + speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) + rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.WHITE) + + unit_text = tr("km/h") if ui_state.is_metric else tr("mph") + unit_text_size = measure_text_cached(self._font_medium, unit_text, FONT_SIZES.speed_unit) + unit_pos = rl.Vector2(rect.x + rect.width / 2 - unit_text_size.x / 2, 290 - unit_text_size.y / 2) + rl.draw_text_ex(self._font_medium, unit_text, unit_pos, FONT_SIZES.speed_unit, 0, COLORS.WHITE_TRANSLUCENT) diff --git a/selfdrive/ui/onroad/model_renderer.py b/selfdrive/ui/onroad/model_renderer.py new file mode 100644 index 00000000000000..ed3af876dfacf0 --- /dev/null +++ b/selfdrive/ui/onroad/model_renderer.py @@ -0,0 +1,438 @@ +import colorsys +import numpy as np +import pyray as rl +from cereal import messaging, car +from dataclasses import dataclass, field +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.params import Params +from openpilot.selfdrive.locationd.calibrationd import HEIGHT_INIT +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient +from openpilot.system.ui.widgets import Widget + +CLIP_MARGIN = 500 +MIN_DRAW_DISTANCE = 10.0 +MAX_DRAW_DISTANCE = 100.0 + +THROTTLE_COLORS = [ + rl.Color(13, 248, 122, 102), # HSLF(148/360, 0.94, 0.51, 0.4) + rl.Color(114, 255, 92, 89), # HSLF(112/360, 1.0, 0.68, 0.35) + rl.Color(114, 255, 92, 0), # HSLF(112/360, 1.0, 0.68, 0.0) +] + +NO_THROTTLE_COLORS = [ + rl.Color(242, 242, 242, 102), # HSLF(148/360, 0.0, 0.95, 0.4) + rl.Color(242, 242, 242, 89), # HSLF(112/360, 0.0, 0.95, 0.35) + rl.Color(242, 242, 242, 0), # HSLF(112/360, 0.0, 0.95, 0.0) +] + + +@dataclass +class ModelPoints: + raw_points: np.ndarray = field(default_factory=lambda: np.empty((0, 3), dtype=np.float32)) + projected_points: np.ndarray = field(default_factory=lambda: np.empty((0, 2), dtype=np.float32)) + + +@dataclass +class LeadVehicle: + glow: list[float] = field(default_factory=list) + chevron: list[float] = field(default_factory=list) + fill_alpha: int = 0 + + +class ModelRenderer(Widget): + def __init__(self): + super().__init__() + self._longitudinal_control = False + self._experimental_mode = False + self._blend_filter = FirstOrderFilter(1.0, 0.25, 1 / gui_app.target_fps) + self._prev_allow_throttle = True + self._lane_line_probs = np.zeros(4, dtype=np.float32) + self._road_edge_stds = np.zeros(2, dtype=np.float32) + self._lead_vehicles = [LeadVehicle(), LeadVehicle()] + self._path_offset_z = HEIGHT_INIT[0] + + # Initialize ModelPoints objects + self._path = ModelPoints() + self._lane_lines = [ModelPoints() for _ in range(4)] + self._road_edges = [ModelPoints() for _ in range(2)] + self._acceleration_x = np.empty((0,), dtype=np.float32) + + # Transform matrix (3x3 for car space to screen space) + self._car_space_transform = np.zeros((3, 3), dtype=np.float32) + self._transform_dirty = True + self._clip_region = None + + self._exp_gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=[], + stops=[], + ) + + # Get longitudinal control setting from car parameters + if car_params := Params().get("CarParams"): + cp = messaging.log_from_bytes(car_params, car.CarParams) + self._longitudinal_control = cp.openpilotLongitudinalControl + + def set_transform(self, transform: np.ndarray): + self._car_space_transform = transform.astype(np.float32) + self._transform_dirty = True + + def _render(self, rect: rl.Rectangle): + sm = ui_state.sm + + # Check if data is up-to-date + if (sm.recv_frame["liveCalibration"] < ui_state.started_frame or + sm.recv_frame["modelV2"] < ui_state.started_frame): + return + + # Set up clipping region + self._clip_region = rl.Rectangle( + rect.x - CLIP_MARGIN, rect.y - CLIP_MARGIN, rect.width + 2 * CLIP_MARGIN, rect.height + 2 * CLIP_MARGIN + ) + + # Update state + self._experimental_mode = sm['selfdriveState'].experimentalMode + + live_calib = sm['liveCalibration'] + self._path_offset_z = live_calib.height[0] if live_calib.height else HEIGHT_INIT[0] + + if sm.updated['carParams']: + self._longitudinal_control = sm['carParams'].openpilotLongitudinalControl + + model = sm['modelV2'] + radar_state = sm['radarState'] if sm.valid['radarState'] else None + lead_one = radar_state.leadOne if radar_state else None + render_lead_indicator = self._longitudinal_control and radar_state is not None + + # Update model data when needed + model_updated = sm.updated['modelV2'] + if model_updated or sm.updated['radarState'] or self._transform_dirty: + if model_updated: + self._update_raw_points(model) + + path_x_array = self._path.raw_points[:, 0] + if path_x_array.size == 0: + return + + self._update_model(lead_one, path_x_array) + if render_lead_indicator: + self._update_leads(radar_state, path_x_array, has_lead=bool(sm['longitudinalPlan'].hasLead)) + self._transform_dirty = False + + # Draw elements + self._draw_lane_lines() + self._draw_path(sm) + + if render_lead_indicator and radar_state: + self._draw_lead_indicator() + + def _update_raw_points(self, model): + """Update raw 3D points from model data""" + self._path.raw_points = np.array([model.position.x, model.position.y, model.position.z], dtype=np.float32).T + + for i, lane_line in enumerate(model.laneLines): + self._lane_lines[i].raw_points = np.array([lane_line.x, lane_line.y, lane_line.z], dtype=np.float32).T + + for i, road_edge in enumerate(model.roadEdges): + self._road_edges[i].raw_points = np.array([road_edge.x, road_edge.y, road_edge.z], dtype=np.float32).T + + self._lane_line_probs = np.array(model.laneLineProbs, dtype=np.float32) + self._road_edge_stds = np.array(model.roadEdgeStds, dtype=np.float32) + self._acceleration_x = np.array(model.acceleration.x, dtype=np.float32) + + def _update_leads(self, radar_state, path_x_array, has_lead=False): + """Update positions of lead vehicles""" + self._lead_vehicles = [LeadVehicle(), LeadVehicle()] + leads = [radar_state.leadOne, radar_state.leadTwo] + + for i, lead_data in enumerate(leads): + # Show the chevron when radard has a track, or when the planner still + # treats a held leadOne as the lead (status flicker). + control_lead = bool(has_lead) and i == 0 and lead_data is not None and float(lead_data.dRel) > 0.0 + if lead_data and (lead_data.status or control_lead): + d_rel, y_rel, v_rel = lead_data.dRel, lead_data.yRel, lead_data.vRel + idx = self._get_path_length_idx(path_x_array, d_rel) + + # Get z-coordinate from path at the lead vehicle position + z = self._path.raw_points[idx, 2] if idx < len(self._path.raw_points) else 0.0 + point = self._map_to_screen(d_rel, -y_rel, z + self._path_offset_z) + if point: + self._lead_vehicles[i] = self._update_lead_vehicle(d_rel, v_rel, point, self._rect) + + def _update_model(self, lead, path_x_array): + """Update model visualization data based on model message""" + max_distance = np.clip(path_x_array[-1], MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE) + max_idx = self._get_path_length_idx(self._lane_lines[0].raw_points[:, 0], max_distance) + + # Update lane lines using raw points + for i, lane_line in enumerate(self._lane_lines): + lane_line.projected_points = self._map_line_to_polygon( + lane_line.raw_points, 0.025 * self._lane_line_probs[i], 0.0, max_idx, max_distance + ) + + # Update road edges using raw points + for road_edge in self._road_edges: + road_edge.projected_points = self._map_line_to_polygon(road_edge.raw_points, 0.025, 0.0, max_idx, max_distance) + + # Update path using raw points + if lead and lead.status: + lead_d = lead.dRel * 2.0 + max_distance = np.clip(lead_d - min(lead_d * 0.35, 10.0), 0.0, max_distance) + + max_idx = self._get_path_length_idx(path_x_array, max_distance) + self._path.projected_points = self._map_line_to_polygon( + self._path.raw_points, 0.9, self._path_offset_z, max_idx, max_distance, allow_invert=False + ) + + self._update_experimental_gradient() + + def _update_experimental_gradient(self): + """Pre-calculate experimental mode gradient colors""" + if not self._experimental_mode: + return + + max_len = min(len(self._path.projected_points) // 2, len(self._acceleration_x)) + + segment_colors = [] + gradient_stops = [] + + i = 0 + while i < max_len: + # Some points (screen space) are out of frame (rect space) + track_y = self._path.projected_points[i][1] + if track_y < self._rect.y or track_y > (self._rect.y + self._rect.height): + i += 1 + continue + + # Calculate color based on acceleration (0 is bottom, 1 is top) + lin_grad_point = 1 - (track_y - self._rect.y) / self._rect.height + + # speed up: 120, slow down: 0 + path_hue = np.clip(60 + self._acceleration_x[i] * 35, 0, 120) + + saturation = min(abs(self._acceleration_x[i] * 1.5), 1) + lightness = np.interp(saturation, [0.0, 1.0], [0.95, 0.62]) + alpha = np.interp(lin_grad_point, [0.75 / 2.0, 0.75], [0.4, 0.0]) + + # Use HSL to RGB conversion + color = self._hsla_to_color(path_hue / 360.0, saturation, lightness, alpha) + + gradient_stops.append(lin_grad_point) + segment_colors.append(color) + + # Skip a point, unless next is last + i += 1 + (1 if (i + 2) < max_len else 0) + + # Store the gradient in the path object + self._exp_gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=segment_colors, + stops=gradient_stops, + ) + + def _update_lead_vehicle(self, d_rel, v_rel, point, rect): + speed_buff, lead_buff = 10.0, 40.0 + + # Calculate fill alpha + fill_alpha = 0 + if d_rel < lead_buff: + fill_alpha = 255 * (1.0 - (d_rel / lead_buff)) + if v_rel < 0: + fill_alpha += 255 * (-1 * (v_rel / speed_buff)) + fill_alpha = min(fill_alpha, 255) + + # Calculate size and position + sz = np.clip((25 * 30) / (d_rel / 3 + 30), 15.0, 30.0) * 2.35 + x = np.clip(point[0], 0.0, rect.width - sz / 2) + y = min(point[1], rect.height - sz * 0.6) + + g_xo = sz / 5 + g_yo = sz / 10 + + glow = [(x + (sz * 1.35) + g_xo, y + sz + g_yo), (x, y - g_yo), (x - (sz * 1.35) - g_xo, y + sz + g_yo)] + chevron = [(x + (sz * 1.25), y + sz), (x, y), (x - (sz * 1.25), y + sz)] + + return LeadVehicle(glow=glow, chevron=chevron, fill_alpha=int(fill_alpha)) + + def _draw_lane_lines(self): + """Draw lane lines and road edges""" + for i, lane_line in enumerate(self._lane_lines): + if lane_line.projected_points.size == 0: + continue + + alpha = np.clip(self._lane_line_probs[i], 0.0, 0.7) + color = rl.Color(255, 255, 255, int(alpha * 255)) + draw_polygon(self._rect, lane_line.projected_points, color) + + for i, road_edge in enumerate(self._road_edges): + if road_edge.projected_points.size == 0: + continue + + alpha = np.clip(1.0 - self._road_edge_stds[i], 0.0, 1.0) + color = rl.Color(255, 0, 0, int(alpha * 255)) + draw_polygon(self._rect, road_edge.projected_points, color) + + def _draw_path(self, sm): + """Draw path with dynamic coloring based on mode and throttle state.""" + if not self._path.projected_points.size: + return + + allow_throttle = sm['longitudinalPlan'].allowThrottle or not self._longitudinal_control + self._blend_filter.update(int(allow_throttle)) + + if self._experimental_mode: + # Draw with acceleration coloring + if len(self._exp_gradient.colors) > 1: + draw_polygon(self._rect, self._path.projected_points, gradient=self._exp_gradient) + else: + draw_polygon(self._rect, self._path.projected_points, rl.Color(255, 255, 255, 30)) + else: + # Blend throttle/no throttle colors based on transition + blend_factor = round(self._blend_filter.x * 100) / 100 + blended_colors = self._blend_colors(NO_THROTTLE_COLORS, THROTTLE_COLORS, blend_factor) + gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=blended_colors, + stops=[0.0, 0.5, 1.0], + ) + draw_polygon(self._rect, self._path.projected_points, gradient=gradient) + + def _draw_lead_indicator(self): + # Draw lead vehicles if available + for lead in self._lead_vehicles: + if not lead.glow or not lead.chevron: + continue + + rl.draw_triangle_fan(lead.glow, len(lead.glow), rl.Color(218, 202, 37, 255)) + rl.draw_triangle_fan(lead.chevron, len(lead.chevron), rl.Color(201, 34, 49, lead.fill_alpha)) + + @staticmethod + def _get_path_length_idx(pos_x_array: np.ndarray, path_distance: float) -> int: + """Get the index corresponding to the given path distance""" + if len(pos_x_array) == 0: + return 0 + indices = np.where(pos_x_array <= path_distance)[0] + return indices[-1] if indices.size > 0 else 0 + + def _map_to_screen(self, in_x, in_y, in_z): + """Project a point in car space to screen space""" + input_pt = np.array([in_x, in_y, in_z]) + pt = self._car_space_transform @ input_pt + + if abs(pt[2]) < 1e-6: + return None + + x, y = pt[0] / pt[2], pt[1] / pt[2] + + clip = self._clip_region + if not (clip.x <= x <= clip.x + clip.width and clip.y <= y <= clip.y + clip.height): + return None + + return (x, y) + + def _map_line_to_polygon(self, line: np.ndarray, y_off: float, z_off: float, max_idx: int, max_distance: float, allow_invert: bool = True) -> np.ndarray: + """Convert 3D line to 2D polygon for rendering.""" + if line.shape[0] == 0: + return np.empty((0, 2), dtype=np.float32) + + # Slice points and filter non-negative x-coordinates + points = line[:max_idx + 1] + + # Interpolate around max_idx so path end is smooth (max_distance is always >= p0.x) + if 0 < max_idx < line.shape[0] - 1: + p0 = line[max_idx] + p1 = line[max_idx + 1] + x0, x1 = p0[0], p1[0] + interp_y = np.interp(max_distance, [x0, x1], [p0[1], p1[1]]) + interp_z = np.interp(max_distance, [x0, x1], [p0[2], p1[2]]) + interp_point = np.array([max_distance, interp_y, interp_z], dtype=points.dtype) + points = np.concatenate((points, interp_point[None, :]), axis=0) + + points = points[points[:, 0] >= 0] + if points.shape[0] == 0: + return np.empty((0, 2), dtype=np.float32) + + N = points.shape[0] + # Generate left and right 3D points in one array using broadcasting + offsets = np.array([[0, -y_off, z_off], [0, y_off, z_off]], dtype=np.float32) + points_3d = points[None, :, :] + offsets[:, None, :] # Shape: 2xNx3 + points_3d = points_3d.reshape(2 * N, 3) # Shape: (2*N)x3 + + # Transform all points to projected space in one operation + proj = self._car_space_transform @ points_3d.T # Shape: 3x(2*N) + proj = proj.reshape(3, 2, N) + left_proj = proj[:, 0, :] + right_proj = proj[:, 1, :] + + # Filter points where z is sufficiently large + valid_proj = (np.abs(left_proj[2]) >= 1e-6) & (np.abs(right_proj[2]) >= 1e-6) + if not np.any(valid_proj): + return np.empty((0, 2), dtype=np.float32) + + # Compute screen coordinates + left_screen = left_proj[:2, valid_proj] / left_proj[2, valid_proj][None, :] + right_screen = right_proj[:2, valid_proj] / right_proj[2, valid_proj][None, :] + + # Define clip region bounds + clip = self._clip_region + x_min, x_max = clip.x, clip.x + clip.width + y_min, y_max = clip.y, clip.y + clip.height + + # Filter points within clip region + left_in_clip = ( + (left_screen[0] >= x_min) & (left_screen[0] <= x_max) & + (left_screen[1] >= y_min) & (left_screen[1] <= y_max) + ) + right_in_clip = ( + (right_screen[0] >= x_min) & (right_screen[0] <= x_max) & + (right_screen[1] >= y_min) & (right_screen[1] <= y_max) + ) + both_in_clip = left_in_clip & right_in_clip + + if not np.any(both_in_clip): + return np.empty((0, 2), dtype=np.float32) + + # Select valid and clipped points + left_screen = left_screen[:, both_in_clip] + right_screen = right_screen[:, both_in_clip] + + # Handle Y-coordinate inversion on hills + if not allow_invert and left_screen.shape[1] > 1: + y = left_screen[1, :] # y-coordinates + keep = y == np.minimum.accumulate(y) + if not np.any(keep): + return np.empty((0, 2), dtype=np.float32) + left_screen = left_screen[:, keep] + right_screen = right_screen[:, keep] + + return np.vstack((left_screen.T, right_screen[:, ::-1].T)).astype(np.float32) + + @staticmethod + def _hsla_to_color(h, s, l, a): + rgb = colorsys.hls_to_rgb(h, l, s) + return rl.Color( + int(rgb[0] * 255), + int(rgb[1] * 255), + int(rgb[2] * 255), + int(a * 255) + ) + + @staticmethod + def _blend_colors(begin_colors, end_colors, t): + if t >= 1.0: + return end_colors + if t <= 0.0: + return begin_colors + + inv_t = 1.0 - t + return [rl.Color( + int(inv_t * start.r + t * end.r), + int(inv_t * start.g + t * end.g), + int(inv_t * start.b + t * end.b), + int(inv_t * start.a + t * end.a) + ) for start, end in zip(begin_colors, end_colors, strict=True)] diff --git a/selfdrive/ui/onroad/speed_sign_hud.py b/selfdrive/ui/onroad/speed_sign_hud.py new file mode 100644 index 00000000000000..22b55b0cb67b0b --- /dev/null +++ b/selfdrive/ui/onroad/speed_sign_hud.py @@ -0,0 +1,360 @@ +"""On-road camera speed-sign HUD (Yes saves a local map limit; No is log-only). + +Large opaque MUTCD-style plate on the driver / left side of the onroad UI. +TICI: below MAX. Mici: top-left. + +When the logger is On and ONNX weights failed to load, the plate shows +NO WT instead of staying blank (and never a fake mph). When the weights +are present but the CPU runtime is not installed, the plate shows NO RT +(Install weights also installs that runtime). When openpilot is +actively controlling, YOLO is skipped and the plate shows WAIT. If WAIT +appears while the UI looks disengaged, that is a bug — report swaglog +lines matching speedsignd. Manual driving (moving OK) still runs detect. + +Yes/No ("is this accurate?") appears only with a live mph — not for NO WT +or NO RT. +Taps are logged to speedsign_feedback/ (JSONL + crop JPEG). Yes also becomes a local +map override (mapd/speed_overrides.py) shown on the regular speed-limit sign; +No is log-only. Either tap hides this popup at once (AnswerGate). +""" +from __future__ import annotations + +import pyray as rl +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.speedsignd.hud import ( + AnswerGate, + point_in_confirm_buttons, + HUD_CONFIRM_NO, + HUD_CONFIRM_PROMPT, + HUD_CONFIRM_YES, + HUD_LABEL, + LiveSignView, + MICI_CONFIRM_BTN_W, + MICI_CONFIRM_GAP, + MICI_SIGN_H, + MICI_SIGN_W, + TICI_CONFIRM_BTN_H, + TICI_CONFIRM_GAP, + TICI_CONFIRM_PROMPT_H, + TICI_SIGN_H, + TICI_SIGN_W, + accuracy_button_rects, + apply_runtime_plate, + hit_accuracy_button, + hud_confirm_visible, + live_sign_from_event, + mici_sign_origin, + plate_digit_size, + tici_sign_origin, +) +from openpilot.selfdrive.speedsignd.install import runtime_missing +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + +# TICI digits bigger than OSM LIMIT (64pt), smaller than live speed (176pt). +TICI_W, TICI_H = TICI_SIGN_W, TICI_SIGN_H +TICI_DIGIT = 120 +TICI_LABEL = 36 +TICI_CONFIRM_FONT = 48 +TICI_PROMPT_FONT = 28 +# Mici 536x240 — still a solid plate, not a toast. +MICI_W, MICI_H = MICI_SIGN_W, MICI_SIGN_H +MICI_DIGIT = 72 +MICI_LABEL = 18 +MICI_CONFIRM_FONT = 22 + +_SIGN_BG = rl.WHITE +_SIGN_BORDER = rl.Color(180, 40, 40, 255) +_SIGN_INK = rl.BLACK +_SIGN_LABEL = rl.Color(40, 40, 40, 255) +_SIGN_MISSING_INK = rl.Color(160, 40, 40, 255) +_SIGN_PAUSED_INK = rl.Color(90, 90, 90, 255) +_YES_BG = rl.Color(36, 130, 72, 235) +_YES_BG_PRESSED = rl.Color(48, 160, 88, 255) +_NO_BG = rl.Color(170, 40, 40, 235) +_NO_BG_PRESSED = rl.Color(200, 52, 52, 255) +_BTN_INK = rl.WHITE +_PROMPT_INK = rl.Color(230, 230, 230, 255) + + +def live_sign_from_sm(sm, enabled: bool) -> LiveSignView: + if not enabled: + return LiveSignView() + try: + d = sm["liveSpeedSignNAP"] + except Exception: + return LiveSignView() + msg_valid = False + try: + msg_valid = bool(sm.valid["liveSpeedSignNAP"]) + except Exception: + msg_valid = False + view = live_sign_from_event(True, d, msg_valid) + # Disk, not a new cereal field. NO WT from the message still wins. + return apply_runtime_plate(view, runtime_missing=runtime_missing()) + + +def logger_enabled() -> bool: + return bool(getattr(ui_state, "speed_sign_log", False)) + + +def tici_sign_rect(rect: rl.Rectangle) -> rl.Rectangle: + """Driver-left, below the MAX box. Same anchor for SIGN mph and NO WT.""" + x, y = tici_sign_origin(rect.x, rect.y) + return rl.Rectangle(x, y, TICI_W, TICI_H) + + +def mici_sign_rect(rect: rl.Rectangle) -> rl.Rectangle: + """Left / driver side, analogous to TICI.""" + x, y = mici_sign_origin(rect.x, rect.y) + return rl.Rectangle(x, y, MICI_W, MICI_H) + + +def tici_confirm_rects(sign: rl.Rectangle) -> tuple[tuple[float, float, float, float], tuple[float, float, float, float]]: + return accuracy_button_rects( + sign.x, sign.y, sign.width, sign.height, + beside=False, btn_h=TICI_CONFIRM_BTN_H, gap=TICI_CONFIRM_GAP, prompt_h=TICI_CONFIRM_PROMPT_H, + ) + + +def mici_confirm_rects(sign: rl.Rectangle) -> tuple[tuple[float, float, float, float], tuple[float, float, float, float]]: + return accuracy_button_rects( + sign.x, sign.y, sign.width, sign.height, + beside=True, btn_w=MICI_CONFIRM_BTN_W, gap=MICI_CONFIRM_GAP, + ) + + +def on_confirm_accuracy(mph: int, yes: bool) -> None: + """Yes/No feedback: append to /data/media/0/nap/speedsign_feedback/feedback.jsonl. + + Keeps the peak-size crop JPEG speedsignd saved for the plate (pending.jpg) + and, on Yes, also appends confirmed.jsonl (future OSM confirmed readings; + nothing is uploaded to osm.org). The row and crop are mirrored into the + current realdata segment for athena harvest. + + Yes only: also sets NAPSpeedSignConfirmed; mapd stores it as a local + override for the matched OSM way + heading, so the regular speed-limit sign + and Map Speed Limit (MAX = limit + offset) use it now and on future drives + (selfdrive/mapd/speed_overrides.py). No is log-only. + """ + import time + from openpilot.selfdrive.speedsignd.two_stage import record_answer + rec = record_answer(int(mph), bool(yes)) + applied = False + if yes: + from openpilot.selfdrive.mapd.speed_overrides import request_override + applied = request_override(int(mph), rec, time.monotonic()) + cloudlog.info("speed_sign_hud feedback mph=%s yes=%s saved=%s jpg=%s lat=%s lon=%s realdata=%s applied=%s", + int(mph), bool(yes), rec is not None, (rec or {}).get("jpg"), + (rec or {}).get("lat"), (rec or {}).get("lon"), (rec or {}).get("realdata"), applied) + + +def draw_speed_sign_plate( + sign: rl.Rectangle, + text: str, + font_bold, + font_label, + digit_size: int, + label_size: int, + *, + ink=None, +) -> None: + rl.draw_rectangle_rounded(sign, 0.10, 8, _SIGN_BG) + rl.draw_rectangle_rounded_lines_ex(sign, 0.10, 8, 6, _SIGN_BORDER) + label_w = measure_text_cached(font_label, HUD_LABEL, label_size).x + rl.draw_text_ex( + font_label, HUD_LABEL, + rl.Vector2(sign.x + (sign.width - label_w) / 2, sign.y + max(6, sign.height * 0.06)), + label_size, 0, _SIGN_LABEL, + ) + num = str(text) + size = plate_digit_size(num, digit_size) + num_w = measure_text_cached(font_bold, num, size).x + num_h = measure_text_cached(font_bold, num, size).y + color = _SIGN_INK if ink is None else ink + rl.draw_text_ex( + font_bold, num, + rl.Vector2(sign.x + (sign.width - num_w) / 2, sign.y + sign.height * 0.38 - num_h / 4), + size, 0, color, + ) + + +def _rect_from_tuple(r: tuple[float, float, float, float]) -> rl.Rectangle: + return rl.Rectangle(r[0], r[1], r[2], r[3]) + + +def _draw_confirm_button(r: tuple[float, float, float, float], label: str, font, font_size: int, + bg, pressed: bool, pressed_bg) -> None: + box = _rect_from_tuple(r) + rl.draw_rectangle_rounded(box, 0.18, 8, pressed_bg if pressed else bg) + text_w = measure_text_cached(font, label, font_size).x + text_h = measure_text_cached(font, label, font_size).y + rl.draw_text_ex( + font, label, + rl.Vector2(box.x + (box.width - text_w) / 2, box.y + (box.height - text_h) / 2), + font_size, 0, _BTN_INK, + ) + + +def draw_accuracy_overlay( + sign: rl.Rectangle, + yes: tuple[float, float, float, float], + no: tuple[float, float, float, float], + font, + *, + tici: bool, + pressed_yes: bool = False, + pressed_no: bool = False, +) -> None: + font_size = TICI_CONFIRM_FONT if tici else MICI_CONFIRM_FONT + if tici: + prompt_w = measure_text_cached(font, HUD_CONFIRM_PROMPT, TICI_PROMPT_FONT).x + rl.draw_text_ex( + font, HUD_CONFIRM_PROMPT, + rl.Vector2(sign.x + (sign.width - prompt_w) / 2, sign.y + sign.height + 6), + TICI_PROMPT_FONT, 0, _PROMPT_INK, + ) + _draw_confirm_button(yes, HUD_CONFIRM_YES, font, font_size, _YES_BG, pressed_yes, _YES_BG_PRESSED) + _draw_confirm_button(no, HUD_CONFIRM_NO, font, font_size, _NO_BG, pressed_no, _NO_BG_PRESSED) + + +_GATE = AnswerGate() + + +def _now() -> float: + import time + return time.monotonic() + + +def _draw_live_sign(rect_fn, rect: rl.Rectangle, font_bold, font_label, digit_size: int, label_size: int) -> LiveSignView: + view = _GATE.filter(live_sign_from_sm(ui_state.sm, logger_enabled()), _now()) + if not view.show: + return view + if view.show_missing_weights or view.show_runtime_missing: + ink = _SIGN_MISSING_INK + elif view.show_detect_paused: + ink = _SIGN_PAUSED_INK + else: + ink = _SIGN_INK + draw_speed_sign_plate( + rect_fn(rect), view.plate_text, font_bold, font_label, digit_size, label_size, ink=ink, + ) + return view + + +def draw_tici_speed_sign(rect: rl.Rectangle, font_bold, font_label) -> LiveSignView: + return _draw_live_sign(tici_sign_rect, rect, font_bold, font_label, TICI_DIGIT, TICI_LABEL) + + +def draw_mici_speed_sign(rect: rl.Rectangle, font_bold, font_label) -> LiveSignView: + return _draw_live_sign(mici_sign_rect, rect, font_bold, font_label, MICI_DIGIT, MICI_LABEL) + + +def _safe_confirm(mph: int, yes: bool) -> None: + try: + on_confirm_accuracy(mph, yes) + except Exception: + cloudlog.exception("speed_sign_hud: feedback failed") + + +class SpeedSignHud(Widget): + """SIGN / NO WT plate plus stub Yes/No accuracy overlay.""" + + def __init__(self, *, tici: bool): + super().__init__() + self._tici = tici + self._view = LiveSignView() + self._yes = (0.0, 0.0, 0.0, 0.0) + self._no = (0.0, 0.0, 0.0, 0.0) + self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + self._font_label: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) + + def render(self, rect: rl.Rectangle | None = None): + # A HUD error must never break the onroad frame or its touch handling. + try: + return super().render(rect) + except Exception: + if not getattr(self, "_logged_err", False): + cloudlog.exception("speed_sign_hud: render failed; HUD hidden this frame") + self._logged_err = True + self._view = LiveSignView() + return None + + def owns_touch(self, x: float, y: float) -> bool: + """Press is on a visible Yes/No button (onroad then skips the sidebar toggle).""" + try: + return point_in_confirm_buttons(x, y, self._view, self._yes, self._no) + except Exception: + return False + + def _update_state(self) -> None: + self._view = _GATE.filter(live_sign_from_sm(ui_state.sm, logger_enabled()), _now()) + + def _layout(self) -> None: + sign = tici_sign_rect(self._rect) if self._tici else mici_sign_rect(self._rect) + if self._tici: + self._yes, self._no = tici_confirm_rects(sign) + else: + self._yes, self._no = mici_confirm_rects(sign) + + @property + def _hit_rect(self) -> rl.Rectangle: + # Only Yes/No consume touches — the plate itself does not block onroad UI. + if not hud_confirm_visible(self._view): + return rl.Rectangle(0, 0, 0, 0) + yx, yy, yw, yh = self._yes + nx, ny, nw, nh = self._no + x = min(yx, nx) + y = min(yy, ny) + return rl.Rectangle(x, y, max(yx + yw, nx + nw) - x, max(yy + yh, ny + nh) - y) + + def _handle_mouse_press(self, mouse_pos: MousePos) -> None: + # Answer on press, not release: the press is inside a drawn button right + # now, so a later layout shift (sidebar, plate expiring) can't drop it, + # and is_pressed is already set when onroad checks user_interacting(). + self._answer_at(mouse_pos) + + def _handle_mouse_release(self, mouse_pos: MousePos) -> None: + pass + + def _answer_at(self, mouse_pos: MousePos) -> None: + if not hud_confirm_visible(self._view): + return + hit = hit_accuracy_button(mouse_pos.x, mouse_pos.y, self._yes, self._no) + if hit is None: + return + # One answer per plate: ignore repeat taps on the same mph for 3 s. + import time as _time + now = _time.monotonic() + last = getattr(self, "_last_answer", (None, 0.0)) + if last[0] == int(self._view.mph) and now - last[1] < 3.0: + return + self._last_answer = (int(self._view.mph), now) + mph = int(self._view.mph) + # Hide the popup (question + prompt) this frame for Yes and No. + _GATE.answer(mph, hit, now) + self._view = _GATE.filter(self._view, now) + # Disk / params work off the UI thread so a slow write can never stall frames. + import threading + threading.Thread(target=_safe_confirm, args=(mph, hit), daemon=True, name="speedsign-tap").start() + + def _render(self, rect: rl.Rectangle) -> None: + if not self._view.show: + return + if self._tici: + sign = tici_sign_rect(rect) + view = draw_tici_speed_sign(rect, self._font_bold, self._font_label) + else: + sign = mici_sign_rect(rect) + view = draw_mici_speed_sign(rect, self._font_bold, self._font_label) + if not hud_confirm_visible(view): + return + mouse = rl.get_mouse_position() + pressed = self.is_pressed + draw_accuracy_overlay( + sign, self._yes, self._no, self._font_label, tici=self._tici, + pressed_yes=pressed and hit_accuracy_button(mouse.x, mouse.y, self._yes, self._no) is True, + pressed_no=pressed and hit_accuracy_button(mouse.x, mouse.y, self._yes, self._no) is False, + ) diff --git a/selfdrive/ui/qt/api.cc b/selfdrive/ui/qt/api.cc deleted file mode 100644 index 6889b40e51518b..00000000000000 --- a/selfdrive/ui/qt/api.cc +++ /dev/null @@ -1,142 +0,0 @@ -#include "selfdrive/ui/qt/api.h" - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" - -namespace CommaApi { - -RSA *get_rsa_private_key() { - static std::unique_ptr rsa_private(nullptr, RSA_free); - if (!rsa_private) { - FILE *fp = fopen(Path::rsa_file().c_str(), "rb"); - if (!fp) { - qDebug() << "No RSA private key found, please run manager.py or registration.py"; - return nullptr; - } - rsa_private.reset(PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)); - fclose(fp); - } - return rsa_private.get(); -} - -QByteArray rsa_sign(const QByteArray &data) { - RSA *rsa_private = get_rsa_private_key(); - if (!rsa_private) return {}; - - QByteArray sig(RSA_size(rsa_private), Qt::Uninitialized); - unsigned int sig_len; - int ret = RSA_sign(NID_sha256, (unsigned char*)data.data(), data.size(), (unsigned char*)sig.data(), &sig_len, rsa_private); - assert(ret == 1); - assert(sig.size() == sig_len); - return sig; -} - -QString create_jwt(const QJsonObject &payloads, int expiry) { - QJsonObject header = {{"alg", "RS256"}}; - - auto t = QDateTime::currentSecsSinceEpoch(); - QJsonObject payload = {{"identity", getDongleId().value_or("")}, {"nbf", t}, {"iat", t}, {"exp", t + expiry}}; - for (auto it = payloads.begin(); it != payloads.end(); ++it) { - payload.insert(it.key(), it.value()); - } - - auto b64_opts = QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals; - QString jwt = QJsonDocument(header).toJson(QJsonDocument::Compact).toBase64(b64_opts) + '.' + - QJsonDocument(payload).toJson(QJsonDocument::Compact).toBase64(b64_opts); - - auto hash = QCryptographicHash::hash(jwt.toUtf8(), QCryptographicHash::Sha256); - return jwt + "." + rsa_sign(hash).toBase64(b64_opts); -} - -} // namespace CommaApi - -HttpRequest::HttpRequest(QObject *parent, bool create_jwt, int timeout) : create_jwt(create_jwt), QObject(parent) { - networkTimer = new QTimer(this); - networkTimer->setSingleShot(true); - networkTimer->setInterval(timeout); - connect(networkTimer, &QTimer::timeout, this, &HttpRequest::requestTimeout); -} - -bool HttpRequest::active() const { - return reply != nullptr; -} - -bool HttpRequest::timeout() const { - return reply && reply->error() == QNetworkReply::OperationCanceledError; -} - -void HttpRequest::sendRequest(const QString &requestURL, const HttpRequest::Method method) { - if (active()) { - qDebug() << "HttpRequest is active"; - return; - } - QString token; - if (create_jwt) { - token = CommaApi::create_jwt(); - } else { - QString token_json = QString::fromStdString(util::read_file(util::getenv("HOME") + "/.comma/auth.json")); - QJsonDocument json_d = QJsonDocument::fromJson(token_json.toUtf8()); - token = json_d["access_token"].toString(); - } - - QNetworkRequest request; - request.setUrl(QUrl(requestURL)); - request.setRawHeader("User-Agent", getUserAgent().toUtf8()); - - if (!token.isEmpty()) { - request.setRawHeader(QByteArray("Authorization"), ("JWT " + token).toUtf8()); - } - - if (method == HttpRequest::Method::GET) { - reply = nam()->get(request); - } else if (method == HttpRequest::Method::DELETE) { - reply = nam()->deleteResource(request); - } - - networkTimer->start(); - connect(reply, &QNetworkReply::finished, this, &HttpRequest::requestFinished); -} - -void HttpRequest::requestTimeout() { - reply->abort(); -} - -void HttpRequest::requestFinished() { - networkTimer->stop(); - - if (reply->error() == QNetworkReply::NoError) { - emit requestDone(reply->readAll(), true, reply->error()); - } else { - QString error; - if (reply->error() == QNetworkReply::OperationCanceledError) { - nam()->clearAccessCache(); - nam()->clearConnectionCache(); - error = "Request timed out"; - } else { - error = reply->errorString(); - } - emit requestDone(error, false, reply->error()); - } - - reply->deleteLater(); - reply = nullptr; -} - -QNetworkAccessManager *HttpRequest::nam() { - static QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(qApp); - return networkAccessManager; -} diff --git a/selfdrive/ui/qt/api.h b/selfdrive/ui/qt/api.h deleted file mode 100644 index ad64d7e7228320..00000000000000 --- a/selfdrive/ui/qt/api.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "common/util.h" - -namespace CommaApi { - -const QString BASE_URL = util::getenv("API_HOST", "https://api.commadotai.com").c_str(); -QByteArray rsa_sign(const QByteArray &data); -QString create_jwt(const QJsonObject &payloads = {}, int expiry = 3600); - -} // namespace CommaApi - -/** - * Makes a request to the request endpoint. - */ - -class HttpRequest : public QObject { - Q_OBJECT - -public: - enum class Method {GET, DELETE}; - - explicit HttpRequest(QObject* parent, bool create_jwt = true, int timeout = 20000); - void sendRequest(const QString &requestURL, const Method method = Method::GET); - bool active() const; - bool timeout() const; - -signals: - void requestDone(const QString &response, bool success, QNetworkReply::NetworkError error); - -protected: - QNetworkReply *reply = nullptr; - -private: - static QNetworkAccessManager *nam(); - QTimer *networkTimer = nullptr; - bool create_jwt; - -private slots: - void requestTimeout(); - void requestFinished(); -}; diff --git a/selfdrive/ui/qt/body.cc b/selfdrive/ui/qt/body.cc deleted file mode 100644 index e01adbe0637811..00000000000000 --- a/selfdrive/ui/qt/body.cc +++ /dev/null @@ -1,161 +0,0 @@ -#include "selfdrive/ui/qt/body.h" - -#include -#include - -#include -#include - -#include "common/params.h" -#include "common/timing.h" - -RecordButton::RecordButton(QWidget *parent) : QPushButton(parent) { - setCheckable(true); - setChecked(false); - setFixedSize(148, 148); - - QObject::connect(this, &QPushButton::toggled, [=]() { - setEnabled(false); - }); -} - -void RecordButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - QPoint center(width() / 2, height() / 2); - - QColor bg(isChecked() ? "#FFFFFF" : "#737373"); - QColor accent(isChecked() ? "#FF0000" : "#FFFFFF"); - if (!isEnabled()) { - bg = QColor("#404040"); - accent = QColor("#FFFFFF"); - } - - if (isDown()) { - accent.setAlphaF(0.7); - } - - p.setPen(Qt::NoPen); - p.setBrush(bg); - p.drawEllipse(center, 74, 74); - - p.setPen(QPen(accent, 6)); - p.setBrush(Qt::NoBrush); - p.drawEllipse(center, 42, 42); - - p.setPen(Qt::NoPen); - p.setBrush(accent); - p.drawEllipse(center, 22, 22); -} - - -BodyWindow::BodyWindow(QWidget *parent) : fuel_filter(1.0, 5., 1. / UI_FREQ), QWidget(parent) { - QStackedLayout *layout = new QStackedLayout(this); - layout->setStackingMode(QStackedLayout::StackAll); - - QWidget *w = new QWidget; - QVBoxLayout *vlayout = new QVBoxLayout(w); - vlayout->setMargin(45); - layout->addWidget(w); - - // face - face = new QLabel(); - face->setAlignment(Qt::AlignCenter); - layout->addWidget(face); - awake = new QMovie("../assets/body/awake.gif", {}, this); - awake->setCacheMode(QMovie::CacheAll); - sleep = new QMovie("../assets/body/sleep.gif", {}, this); - sleep->setCacheMode(QMovie::CacheAll); - - // record button - btn = new RecordButton(this); - vlayout->addWidget(btn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(btn, &QPushButton::clicked, [=](bool checked) { - btn->setEnabled(false); - Params().putBool("DisableLogging", !checked); - last_button = nanos_since_boot(); - }); - w->raise(); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &BodyWindow::updateState); -} - -void BodyWindow::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - p.fillRect(rect(), QColor(0, 0, 0)); - - // battery outline + detail - p.translate(width() - 136, 16); - const QColor gray = QColor("#737373"); - p.setBrush(Qt::NoBrush); - p.setPen(QPen(gray, 4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - p.drawRoundedRect(2, 2, 78, 36, 8, 8); - - p.setPen(Qt::NoPen); - p.setBrush(gray); - p.drawRoundedRect(84, 12, 6, 16, 4, 4); - p.drawRect(84, 12, 3, 16); - - // battery level - double fuel = std::clamp(fuel_filter.x(), 0.2f, 1.0f); - const int m = 5; // manual margin since we can't do an inner border - p.setPen(Qt::NoPen); - p.setBrush(fuel > 0.25 ? QColor("#32D74B") : QColor("#FF453A")); - p.drawRoundedRect(2 + m, 2 + m, (78 - 2*m)*fuel, 36 - 2*m, 4, 4); - - // charging status - if (charging) { - p.setPen(Qt::NoPen); - p.setBrush(Qt::white); - const QPolygonF charger({ - QPointF(12.31, 0), - QPointF(12.31, 16.92), - QPointF(18.46, 16.92), - QPointF(6.15, 40), - QPointF(6.15, 23.08), - QPointF(0, 23.08), - }); - p.drawPolygon(charger.translated(98, 0)); - } -} - -void BodyWindow::offroadTransition(bool offroad) { - btn->setChecked(true); - btn->setEnabled(true); - fuel_filter.reset(1.0); -} - -void BodyWindow::updateState(const UIState &s) { - if (!isVisible()) { - return; - } - - const SubMaster &sm = *(s.sm); - auto cs = sm["carState"].getCarState(); - - charging = cs.getCharging(); - fuel_filter.update(cs.getFuelGauge()); - - // TODO: use carState.standstill when that's fixed - const bool standstill = std::abs(cs.getVEgo()) < 0.01; - QMovie *m = standstill ? sleep : awake; - if (m != face->movie()) { - face->setMovie(m); - face->movie()->start(); - } - - // update record button state - if (sm.updated("managerState") && (sm.rcv_time("managerState") - last_button)*1e-9 > 0.5) { - for (auto proc : sm["managerState"].getManagerState().getProcesses()) { - if (proc.getName() == "loggerd") { - btn->setEnabled(true); - btn->setChecked(proc.getRunning()); - } - } - } - - update(); -} diff --git a/selfdrive/ui/qt/body.h b/selfdrive/ui/qt/body.h deleted file mode 100644 index 567a54d49befd5..00000000000000 --- a/selfdrive/ui/qt/body.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "common/util.h" -#include "selfdrive/ui/ui.h" - -class RecordButton : public QPushButton { - Q_OBJECT - -public: - RecordButton(QWidget* parent = 0); - -private: - void paintEvent(QPaintEvent*) override; -}; - -class BodyWindow : public QWidget { - Q_OBJECT - -public: - BodyWindow(QWidget* parent = 0); - -private: - bool charging = false; - uint64_t last_button = 0; - FirstOrderFilter fuel_filter; - QLabel *face; - QMovie *awake, *sleep; - RecordButton *btn; - void paintEvent(QPaintEvent*) override; - -private slots: - void updateState(const UIState &s); - void offroadTransition(bool onroad); -}; diff --git a/selfdrive/ui/qt/home.cc b/selfdrive/ui/qt/home.cc deleted file mode 100644 index af946c79872871..00000000000000 --- a/selfdrive/ui/qt/home.cc +++ /dev/null @@ -1,243 +0,0 @@ -#include "selfdrive/ui/qt/home.h" - -#include -#include -#include -#include - -#include "selfdrive/ui/qt/offroad/experimental_mode.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/prime.h" - -// HomeWindow: the container for the offroad and onroad UIs - -HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) { - QHBoxLayout *main_layout = new QHBoxLayout(this); - main_layout->setMargin(0); - main_layout->setSpacing(0); - - sidebar = new Sidebar(this); - main_layout->addWidget(sidebar); - QObject::connect(sidebar, &Sidebar::openSettings, this, &HomeWindow::openSettings); - - slayout = new QStackedLayout(); - main_layout->addLayout(slayout); - - home = new OffroadHome(this); - QObject::connect(home, &OffroadHome::openSettings, this, &HomeWindow::openSettings); - slayout->addWidget(home); - - onroad = new OnroadWindow(this); - slayout->addWidget(onroad); - - body = new BodyWindow(this); - slayout->addWidget(body); - - driver_view = new DriverViewWindow(this); - connect(driver_view, &DriverViewWindow::done, [=] { - showDriverView(false); - }); - slayout->addWidget(driver_view); - setAttribute(Qt::WA_NoSystemBackground); - QObject::connect(uiState(), &UIState::uiUpdate, this, &HomeWindow::updateState); - QObject::connect(uiState(), &UIState::offroadTransition, this, &HomeWindow::offroadTransition); - QObject::connect(uiState(), &UIState::offroadTransition, sidebar, &Sidebar::offroadTransition); -} - -void HomeWindow::showSidebar(bool show) { - sidebar->setVisible(show); -} - -void HomeWindow::updateState(const UIState &s) { - const SubMaster &sm = *(s.sm); - - // switch to the generic robot UI - if (onroad->isVisible() && !body->isEnabled() && sm["carParams"].getCarParams().getNotCar()) { - body->setEnabled(true); - slayout->setCurrentWidget(body); - } -} - -void HomeWindow::offroadTransition(bool offroad) { - body->setEnabled(false); - sidebar->setVisible(offroad); - if (offroad) { - slayout->setCurrentWidget(home); - } else { - slayout->setCurrentWidget(onroad); - } -} - -void HomeWindow::showDriverView(bool show) { - if (show) { - emit closeSettings(); - slayout->setCurrentWidget(driver_view); - } else { - slayout->setCurrentWidget(home); - } - sidebar->setVisible(show == false); -} - -void HomeWindow::mousePressEvent(QMouseEvent* e) { - // Handle sidebar collapsing - if ((onroad->isVisible() || body->isVisible()) && (!sidebar->isVisible() || e->x() > sidebar->width())) { - sidebar->setVisible(!sidebar->isVisible()); - } -} - -void HomeWindow::mouseDoubleClickEvent(QMouseEvent* e) { - HomeWindow::mousePressEvent(e); - const SubMaster &sm = *(uiState()->sm); - if (sm["carParams"].getCarParams().getNotCar()) { - if (onroad->isVisible()) { - slayout->setCurrentWidget(body); - } else if (body->isVisible()) { - slayout->setCurrentWidget(onroad); - } - showSidebar(false); - } -} - -// OffroadHome: the offroad home page - -OffroadHome::OffroadHome(QWidget* parent) : QFrame(parent) { - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(40, 40, 40, 40); - - // top header - QHBoxLayout* header_layout = new QHBoxLayout(); - header_layout->setContentsMargins(0, 0, 0, 0); - header_layout->setSpacing(16); - - update_notif = new QPushButton(tr("UPDATE")); - update_notif->setVisible(false); - update_notif->setStyleSheet("background-color: #364DEF;"); - QObject::connect(update_notif, &QPushButton::clicked, [=]() { center_layout->setCurrentIndex(1); }); - header_layout->addWidget(update_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); - - alert_notif = new QPushButton(); - alert_notif->setVisible(false); - alert_notif->setStyleSheet("background-color: #E22C2C;"); - QObject::connect(alert_notif, &QPushButton::clicked, [=] { center_layout->setCurrentIndex(2); }); - header_layout->addWidget(alert_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); - - version = new ElidedLabel(); - header_layout->addWidget(version, 0, Qt::AlignHCenter | Qt::AlignRight); - - main_layout->addLayout(header_layout); - - // main content - main_layout->addSpacing(25); - center_layout = new QStackedLayout(); - - QWidget *home_widget = new QWidget(this); - { - QHBoxLayout *home_layout = new QHBoxLayout(home_widget); - home_layout->setContentsMargins(0, 0, 0, 0); - home_layout->setSpacing(30); - - // left: PrimeAdWidget - QStackedWidget *left_widget = new QStackedWidget(this); - QVBoxLayout *left_prime_layout = new QVBoxLayout(); - QWidget *prime_user = new PrimeUserWidget(); - prime_user->setStyleSheet(R"( - border-radius: 10px; - background-color: #333333; - )"); - left_prime_layout->addWidget(prime_user); - left_prime_layout->addStretch(); - left_widget->addWidget(new LayoutWidget(left_prime_layout)); - left_widget->addWidget(new PrimeAdWidget); - left_widget->setStyleSheet("border-radius: 10px;"); - - left_widget->setCurrentIndex(uiState()->hasPrime() ? 0 : 1); - connect(uiState(), &UIState::primeChanged, [=](bool prime) { - left_widget->setCurrentIndex(prime ? 0 : 1); - }); - - home_layout->addWidget(left_widget, 1); - - // right: ExperimentalModeButton, SetupWidget - QWidget* right_widget = new QWidget(this); - QVBoxLayout* right_column = new QVBoxLayout(right_widget); - right_column->setContentsMargins(0, 0, 0, 0); - right_widget->setFixedWidth(750); - right_column->setSpacing(30); - - ExperimentalModeButton *experimental_mode = new ExperimentalModeButton(this); - QObject::connect(experimental_mode, &ExperimentalModeButton::openSettings, this, &OffroadHome::openSettings); - right_column->addWidget(experimental_mode, 1); - - SetupWidget *setup_widget = new SetupWidget; - QObject::connect(setup_widget, &SetupWidget::openSettings, this, &OffroadHome::openSettings); - right_column->addWidget(setup_widget, 1); - - home_layout->addWidget(right_widget, 1); - } - center_layout->addWidget(home_widget); - - // add update & alerts widgets - update_widget = new UpdateAlert(); - QObject::connect(update_widget, &UpdateAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); }); - center_layout->addWidget(update_widget); - alerts_widget = new OffroadAlert(); - QObject::connect(alerts_widget, &OffroadAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); }); - center_layout->addWidget(alerts_widget); - - main_layout->addLayout(center_layout, 1); - - // set up refresh timer - timer = new QTimer(this); - timer->callOnTimeout(this, &OffroadHome::refresh); - - setStyleSheet(R"( - * { - color: white; - } - OffroadHome { - background-color: black; - } - OffroadHome > QPushButton { - padding: 15px 30px; - border-radius: 5px; - font-size: 40px; - font-weight: 500; - } - OffroadHome > QLabel { - font-size: 55px; - } - )"); -} - -void OffroadHome::showEvent(QShowEvent *event) { - refresh(); - timer->start(10 * 1000); -} - -void OffroadHome::hideEvent(QHideEvent *event) { - timer->stop(); -} - -void OffroadHome::refresh() { - version->setText(getBrand() + " " + QString::fromStdString(params.get("UpdaterCurrentDescription"))); - - bool updateAvailable = update_widget->refresh(); - int alerts = alerts_widget->refresh(); - - // pop-up new notification - int idx = center_layout->currentIndex(); - if (!updateAvailable && !alerts) { - idx = 0; - } else if (updateAvailable && (!update_notif->isVisible() || (!alerts && idx == 2))) { - idx = 1; - } else if (alerts && (!alert_notif->isVisible() || (!updateAvailable && idx == 1))) { - idx = 2; - } - center_layout->setCurrentIndex(idx); - - update_notif->setVisible(updateAvailable); - alert_notif->setVisible(alerts); - if (alerts) { - alert_notif->setText(QString::number(alerts) + (alerts > 1 ? tr(" ALERTS") : tr(" ALERT"))); - } -} diff --git a/selfdrive/ui/qt/home.h b/selfdrive/ui/qt/home.h deleted file mode 100644 index a19b70ac3f3ef5..00000000000000 --- a/selfdrive/ui/qt/home.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/offroad/driverview.h" -#include "selfdrive/ui/qt/body.h" -#include "selfdrive/ui/qt/onroad/onroad_home.h" -#include "selfdrive/ui/qt/sidebar.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/offroad_alerts.h" -#include "selfdrive/ui/ui.h" - -class OffroadHome : public QFrame { - Q_OBJECT - -public: - explicit OffroadHome(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - -private: - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - void refresh(); - - Params params; - - QTimer* timer; - ElidedLabel* version; - QStackedLayout* center_layout; - UpdateAlert *update_widget; - OffroadAlert* alerts_widget; - QPushButton* alert_notif; - QPushButton* update_notif; -}; - -class HomeWindow : public QWidget { - Q_OBJECT - -public: - explicit HomeWindow(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - void closeSettings(); - -public slots: - void offroadTransition(bool offroad); - void showDriverView(bool show); - void showSidebar(bool show); - -protected: - void mousePressEvent(QMouseEvent* e) override; - void mouseDoubleClickEvent(QMouseEvent* e) override; - -private: - Sidebar *sidebar; - OffroadHome *home; - OnroadWindow *onroad; - BodyWindow *body; - DriverViewWindow *driver_view; - QStackedLayout *slayout; - -private slots: - void updateState(const UIState &s); -}; diff --git a/selfdrive/ui/qt/network/networking.cc b/selfdrive/ui/qt/network/networking.cc deleted file mode 100644 index 250fa0fbf8e3ca..00000000000000 --- a/selfdrive/ui/qt/network/networking.cc +++ /dev/null @@ -1,378 +0,0 @@ -#include "selfdrive/ui/qt/network/networking.h" - -#include - -#include -#include -#include - -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -static const int ICON_WIDTH = 49; - -// Networking functions - -Networking::Networking(QWidget* parent, bool show_advanced) : QFrame(parent) { - main_layout = new QStackedLayout(this); - - wifi = new WifiManager(this); - connect(wifi, &WifiManager::refreshSignal, this, &Networking::refresh); - connect(wifi, &WifiManager::wrongPassword, this, &Networking::wrongPassword); - - wifiScreen = new QWidget(this); - QVBoxLayout* vlayout = new QVBoxLayout(wifiScreen); - vlayout->setContentsMargins(20, 20, 20, 20); - if (show_advanced) { - QPushButton* advancedSettings = new QPushButton(tr("Advanced")); - advancedSettings->setObjectName("advanced_btn"); - advancedSettings->setStyleSheet("margin-right: 30px;"); - advancedSettings->setFixedSize(400, 100); - connect(advancedSettings, &QPushButton::clicked, [=]() { main_layout->setCurrentWidget(an); }); - vlayout->addSpacing(10); - vlayout->addWidget(advancedSettings, 0, Qt::AlignRight); - vlayout->addSpacing(10); - } - - wifiWidget = new WifiUI(this, wifi); - wifiWidget->setObjectName("wifiWidget"); - connect(wifiWidget, &WifiUI::connectToNetwork, this, &Networking::connectToNetwork); - - ScrollView *wifiScroller = new ScrollView(wifiWidget, this); - wifiScroller->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - vlayout->addWidget(wifiScroller, 1); - main_layout->addWidget(wifiScreen); - - an = new AdvancedNetworking(this, wifi); - connect(an, &AdvancedNetworking::backPress, [=]() { main_layout->setCurrentWidget(wifiScreen); }); - connect(an, &AdvancedNetworking::requestWifiScreen, [=]() { main_layout->setCurrentWidget(wifiScreen); }); - main_layout->addWidget(an); - - QPalette pal = palette(); - pal.setColor(QPalette::Window, QColor(0x29, 0x29, 0x29)); - setAutoFillBackground(true); - setPalette(pal); - - setStyleSheet(R"( - #wifiWidget > QPushButton, #back_btn, #advanced_btn { - font-size: 50px; - margin: 0px; - padding: 15px; - border-width: 0; - border-radius: 30px; - color: #dddddd; - background-color: #393939; - } - #back_btn:pressed, #advanced_btn:pressed { - background-color: #4a4a4a; - } - )"); - main_layout->setCurrentWidget(wifiScreen); -} - -void Networking::refresh() { - wifiWidget->refresh(); - an->refresh(); -} - -void Networking::connectToNetwork(const Network n) { - if (wifi->isKnownConnection(n.ssid)) { - wifi->activateWifiConnection(n.ssid); - } else if (n.security_type == SecurityType::OPEN) { - wifi->connect(n, false); - } else if (n.security_type == SecurityType::WPA) { - QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); - if (!pass.isEmpty()) { - wifi->connect(n, false, pass); - } - } -} - -void Networking::wrongPassword(const QString &ssid) { - if (wifi->seenNetworks.contains(ssid)) { - const Network &n = wifi->seenNetworks.value(ssid); - QString pass = InputDialog::getText(tr("Wrong password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); - if (!pass.isEmpty()) { - wifi->connect(n, false, pass); - } - } -} - -void Networking::showEvent(QShowEvent *event) { - wifi->start(); -} - -void Networking::hideEvent(QHideEvent *event) { - main_layout->setCurrentWidget(wifiScreen); - wifi->stop(); -} - -// AdvancedNetworking functions - -AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWidget(parent), wifi(wifi) { - - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setMargin(40); - main_layout->setSpacing(20); - - // Back button - QPushButton* back = new QPushButton(tr("Back")); - back->setObjectName("back_btn"); - back->setFixedSize(400, 100); - connect(back, &QPushButton::clicked, [=]() { emit backPress(); }); - main_layout->addWidget(back, 0, Qt::AlignLeft); - - ListWidget *list = new ListWidget(this); - // Enable tethering layout - tetheringToggle = new ToggleControl(tr("Enable Tethering"), "", "", wifi->isTetheringEnabled()); - list->addItem(tetheringToggle); - QObject::connect(tetheringToggle, &ToggleControl::toggleFlipped, this, &AdvancedNetworking::toggleTethering); - - // Change tethering password - ButtonControl *editPasswordButton = new ButtonControl(tr("Tethering Password"), tr("EDIT")); - connect(editPasswordButton, &ButtonControl::clicked, [=]() { - QString pass = InputDialog::getText(tr("Enter new tethering password"), this, "", true, 8, wifi->getTetheringPassword()); - if (!pass.isEmpty()) { - wifi->changeTetheringPassword(pass); - } - }); - list->addItem(editPasswordButton); - - // IP address - ipLabel = new LabelControl(tr("IP Address"), wifi->ipv4_address); - list->addItem(ipLabel); - - // SSH keys - list->addItem(new SshToggle()); - list->addItem(new SshControl()); - - // Roaming toggle - const bool roamingEnabled = params.getBool("GsmRoaming"); - roamingToggle = new ToggleControl(tr("Enable Roaming"), "", "", roamingEnabled); - QObject::connect(roamingToggle, &ToggleControl::toggleFlipped, [=](bool state) { - params.putBool("GsmRoaming", state); - wifi->updateGsmSettings(state, QString::fromStdString(params.get("GsmApn")), params.getBool("GsmMetered")); - }); - list->addItem(roamingToggle); - - // APN settings - editApnButton = new ButtonControl(tr("APN Setting"), tr("EDIT")); - connect(editApnButton, &ButtonControl::clicked, [=]() { - const QString cur_apn = QString::fromStdString(params.get("GsmApn")); - QString apn = InputDialog::getText(tr("Enter APN"), this, tr("leave blank for automatic configuration"), false, -1, cur_apn).trimmed(); - - if (apn.isEmpty()) { - params.remove("GsmApn"); - } else { - params.put("GsmApn", apn.toStdString()); - } - wifi->updateGsmSettings(params.getBool("GsmRoaming"), apn, params.getBool("GsmMetered")); - }); - list->addItem(editApnButton); - - // Metered toggle - const bool metered = params.getBool("GsmMetered"); - meteredToggle = new ToggleControl(tr("Cellular Metered"), tr("Prevent large data uploads when on a metered connection"), "", metered); - QObject::connect(meteredToggle, &SshToggle::toggleFlipped, [=](bool state) { - params.putBool("GsmMetered", state); - wifi->updateGsmSettings(params.getBool("GsmRoaming"), QString::fromStdString(params.get("GsmApn")), state); - }); - list->addItem(meteredToggle); - - // Hidden Network - hiddenNetworkButton = new ButtonControl(tr("Hidden Network"), tr("CONNECT")); - connect(hiddenNetworkButton, &ButtonControl::clicked, [=]() { - QString ssid = InputDialog::getText(tr("Enter SSID"), this, "", false, 1); - if (!ssid.isEmpty()) { - QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(ssid), true, -1); - Network hidden_network; - hidden_network.ssid = ssid.toUtf8(); - if (!pass.isEmpty()) { - hidden_network.security_type = SecurityType::WPA; - wifi->connect(hidden_network, true, pass); - } else { - wifi->connect(hidden_network, true); - } - emit requestWifiScreen(); - } - }); - list->addItem(hiddenNetworkButton); - - // Set initial config - wifi->updateGsmSettings(roamingEnabled, QString::fromStdString(params.get("GsmApn")), metered); - - connect(uiState(), &UIState::primeTypeChanged, this, [=](PrimeType prime_type) { - bool gsmVisible = prime_type == PrimeType::PRIME_TYPE_NONE || prime_type == PrimeType::PRIME_TYPE_LITE; - roamingToggle->setVisible(gsmVisible); - editApnButton->setVisible(gsmVisible); - meteredToggle->setVisible(gsmVisible); - }); - - main_layout->addWidget(new ScrollView(list, this)); - main_layout->addStretch(1); -} - -void AdvancedNetworking::refresh() { - ipLabel->setText(wifi->ipv4_address); - tetheringToggle->setEnabled(true); - update(); -} - -void AdvancedNetworking::toggleTethering(bool enabled) { - wifi->setTetheringEnabled(enabled); - tetheringToggle->setEnabled(false); -} - -// WifiUI functions - -WifiUI::WifiUI(QWidget *parent, WifiManager* wifi) : QWidget(parent), wifi(wifi) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(0, 0, 0, 0); - main_layout->setSpacing(0); - - // load imgs - for (const auto &s : {"low", "medium", "high", "full"}) { - QPixmap pix(ASSET_PATH + "/offroad/icon_wifi_strength_" + s + ".svg"); - strengths.push_back(pix.scaledToHeight(68, Qt::SmoothTransformation)); - } - lock = QPixmap(ASSET_PATH + "offroad/icon_lock_closed.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - checkmark = QPixmap(ASSET_PATH + "offroad/icon_checkmark.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - circled_slash = QPixmap(ASSET_PATH + "img_circled_slash.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - - scanningLabel = new QLabel(tr("Scanning for networks...")); - scanningLabel->setStyleSheet("font-size: 65px;"); - main_layout->addWidget(scanningLabel, 0, Qt::AlignCenter); - - wifi_list_widget = new ListWidget(this); - wifi_list_widget->setVisible(false); - main_layout->addWidget(wifi_list_widget); - - setStyleSheet(R"( - QScrollBar::handle:vertical { - min-height: 0px; - border-radius: 4px; - background-color: #8A8A8A; - } - #forgetBtn { - font-size: 32px; - font-weight: 600; - color: #292929; - background-color: #BDBDBD; - border-width: 1px solid #828282; - border-radius: 5px; - padding: 40px; - padding-bottom: 16px; - padding-top: 16px; - } - #forgetBtn:pressed { - background-color: #828282; - } - #connecting { - font-size: 32px; - font-weight: 600; - color: white; - border-radius: 0; - padding: 27px; - padding-left: 43px; - padding-right: 43px; - background-color: black; - } - #ssidLabel { - text-align: left; - border: none; - padding-top: 50px; - padding-bottom: 50px; - } - #ssidLabel:disabled { - color: #696969; - } - )"); -} - -void WifiUI::refresh() { - bool is_empty = wifi->seenNetworks.isEmpty(); - scanningLabel->setVisible(is_empty); - wifi_list_widget->setVisible(!is_empty); - if (is_empty) return; - - setUpdatesEnabled(false); - - const bool is_tethering_enabled = wifi->isTetheringEnabled(); - QList sortedNetworks = wifi->seenNetworks.values(); - std::sort(sortedNetworks.begin(), sortedNetworks.end(), compare_by_strength); - - int n = 0; - for (Network &network : sortedNetworks) { - QPixmap status_icon; - if (network.connected == ConnectedType::CONNECTED) { - status_icon = checkmark; - } else if (network.security_type == SecurityType::UNSUPPORTED) { - status_icon = circled_slash; - } else if (network.security_type == SecurityType::WPA) { - status_icon = lock; - } - bool show_forget_btn = wifi->isKnownConnection(network.ssid) && !is_tethering_enabled; - QPixmap strength = strengths[strengthLevel(network.strength)]; - - auto item = getItem(n++); - item->setItem(network, status_icon, show_forget_btn, strength); - item->setVisible(true); - } - for (; n < wifi_items.size(); ++n) wifi_items[n]->setVisible(false); - - setUpdatesEnabled(true); -} - -WifiItem *WifiUI::getItem(int n) { - auto item = n < wifi_items.size() ? wifi_items[n] : wifi_items.emplace_back(new WifiItem(tr("CONNECTING..."), tr("FORGET"))); - if (!item->parentWidget()) { - QObject::connect(item, &WifiItem::connectToNetwork, this, &WifiUI::connectToNetwork); - QObject::connect(item, &WifiItem::forgotNetwork, [this](const Network n) { - if (ConfirmationDialog::confirm(tr("Forget Wi-Fi Network \"%1\"?").arg(QString::fromUtf8(n.ssid)), tr("Forget"), this)) - wifi->forgetConnection(n.ssid); - }); - wifi_list_widget->addItem(item); - } - return item; -} - -// WifiItem - -WifiItem::WifiItem(const QString &connecting_text, const QString &forget_text, QWidget *parent) : QWidget(parent) { - QHBoxLayout *hlayout = new QHBoxLayout(this); - hlayout->setContentsMargins(44, 0, 73, 0); - hlayout->setSpacing(50); - - hlayout->addWidget(ssidLabel = new ElidedLabel()); - ssidLabel->setObjectName("ssidLabel"); - ssidLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - hlayout->addWidget(connecting = new QPushButton(connecting_text), 0, Qt::AlignRight); - connecting->setObjectName("connecting"); - hlayout->addWidget(forgetBtn = new QPushButton(forget_text), 0, Qt::AlignRight); - forgetBtn->setObjectName("forgetBtn"); - hlayout->addWidget(iconLabel = new QLabel(), 0, Qt::AlignRight); - hlayout->addWidget(strengthLabel = new QLabel(), 0, Qt::AlignRight); - - iconLabel->setFixedWidth(ICON_WIDTH); - QObject::connect(forgetBtn, &QPushButton::clicked, [this]() { emit forgotNetwork(network); }); - QObject::connect(ssidLabel, &ElidedLabel::clicked, [this]() { - if (network.connected == ConnectedType::DISCONNECTED) emit connectToNetwork(network); - }); -} - -void WifiItem::setItem(const Network &n, const QPixmap &status_icon, bool show_forget_btn, const QPixmap &strength_icon) { - network = n; - - ssidLabel->setText(n.ssid); - ssidLabel->setEnabled(n.security_type != SecurityType::UNSUPPORTED); - ssidLabel->setFont(InterFont(55, network.connected == ConnectedType::DISCONNECTED ? QFont::Normal : QFont::Bold)); - - connecting->setVisible(n.connected == ConnectedType::CONNECTING); - forgetBtn->setVisible(show_forget_btn); - - iconLabel->setPixmap(status_icon); - strengthLabel->setPixmap(strength_icon); -} diff --git a/selfdrive/ui/qt/network/networking.h b/selfdrive/ui/qt/network/networking.h deleted file mode 100644 index 9b6af005ea640c..00000000000000 --- a/selfdrive/ui/qt/network/networking.h +++ /dev/null @@ -1,101 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/qt/network/wifi_manager.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/ssh_keys.h" -#include "selfdrive/ui/qt/widgets/toggle.h" - -class WifiItem : public QWidget { - Q_OBJECT -public: - explicit WifiItem(const QString &connecting_text, const QString &forget_text, QWidget* parent = nullptr); - void setItem(const Network& n, const QPixmap &icon, bool show_forget_btn, const QPixmap &strength); - -signals: - // Cannot pass Network by reference. it may change after the signal is sent. - void connectToNetwork(const Network n); - void forgotNetwork(const Network n); - -protected: - ElidedLabel* ssidLabel; - QPushButton* connecting; - QPushButton* forgetBtn; - QLabel* iconLabel; - QLabel* strengthLabel; - Network network; -}; - -class WifiUI : public QWidget { - Q_OBJECT - -public: - explicit WifiUI(QWidget *parent = 0, WifiManager* wifi = 0); - -private: - WifiItem *getItem(int n); - - WifiManager *wifi = nullptr; - QLabel *scanningLabel = nullptr; - QPixmap lock; - QPixmap checkmark; - QPixmap circled_slash; - QVector strengths; - ListWidget *wifi_list_widget = nullptr; - std::vector wifi_items; - -signals: - void connectToNetwork(const Network n); - -public slots: - void refresh(); -}; - -class AdvancedNetworking : public QWidget { - Q_OBJECT -public: - explicit AdvancedNetworking(QWidget* parent = 0, WifiManager* wifi = 0); - -private: - LabelControl* ipLabel; - ToggleControl* tetheringToggle; - ToggleControl* roamingToggle; - ButtonControl* editApnButton; - ButtonControl* hiddenNetworkButton; - ToggleControl* meteredToggle; - WifiManager* wifi = nullptr; - Params params; - -signals: - void backPress(); - void requestWifiScreen(); - -public slots: - void toggleTethering(bool enabled); - void refresh(); -}; - -class Networking : public QFrame { - Q_OBJECT - -public: - explicit Networking(QWidget* parent = 0, bool show_advanced = true); - WifiManager* wifi = nullptr; - -private: - QStackedLayout* main_layout = nullptr; - QWidget* wifiScreen = nullptr; - AdvancedNetworking* an = nullptr; - WifiUI* wifiWidget; - - void showEvent(QShowEvent* event) override; - void hideEvent(QHideEvent* event) override; - -public slots: - void refresh(); - -private slots: - void connectToNetwork(const Network n); - void wrongPassword(const QString &ssid); -}; diff --git a/selfdrive/ui/qt/network/networkmanager.h b/selfdrive/ui/qt/network/networkmanager.h deleted file mode 100644 index 8bdeaf3bbd068c..00000000000000 --- a/selfdrive/ui/qt/network/networkmanager.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -/** - * We are using a NetworkManager DBUS API : https://developer.gnome.org/NetworkManager/1.26/spec.html - * */ - -// https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApFlags -const int NM_802_11_AP_FLAGS_NONE = 0x00000000; -const int NM_802_11_AP_FLAGS_PRIVACY = 0x00000001; -const int NM_802_11_AP_FLAGS_WPS = 0x00000002; - -// https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApSecurityFlags -const int NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001; -const int NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002; -const int NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010; -const int NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020; -const int NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100; -const int NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200; - -const QString NM_DBUS_PATH = "/org/freedesktop/NetworkManager"; -const QString NM_DBUS_PATH_SETTINGS = "/org/freedesktop/NetworkManager/Settings"; - -const QString NM_DBUS_INTERFACE = "org.freedesktop.NetworkManager"; -const QString NM_DBUS_INTERFACE_PROPERTIES = "org.freedesktop.DBus.Properties"; -const QString NM_DBUS_INTERFACE_SETTINGS = "org.freedesktop.NetworkManager.Settings"; -const QString NM_DBUS_INTERFACE_SETTINGS_CONNECTION = "org.freedesktop.NetworkManager.Settings.Connection"; -const QString NM_DBUS_INTERFACE_DEVICE = "org.freedesktop.NetworkManager.Device"; -const QString NM_DBUS_INTERFACE_DEVICE_WIRELESS = "org.freedesktop.NetworkManager.Device.Wireless"; -const QString NM_DBUS_INTERFACE_ACCESS_POINT = "org.freedesktop.NetworkManager.AccessPoint"; -const QString NM_DBUS_INTERFACE_ACTIVE_CONNECTION = "org.freedesktop.NetworkManager.Connection.Active"; -const QString NM_DBUS_INTERFACE_IP4_CONFIG = "org.freedesktop.NetworkManager.IP4Config"; - -const QString NM_DBUS_SERVICE = "org.freedesktop.NetworkManager"; - -const int NM_DEVICE_STATE_UNKNOWN = 0; -const int NM_DEVICE_STATE_ACTIVATED = 100; -const int NM_DEVICE_STATE_NEED_AUTH = 60; -const int NM_DEVICE_TYPE_WIFI = 2; -const int NM_DEVICE_TYPE_MODEM = 8; -const int NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT = 8; -const int DBUS_TIMEOUT = 100; - -// https://developer-old.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMMetered -const int NM_METERED_UNKNOWN = 0; -const int NM_METERED_YES = 1; -const int NM_METERED_NO = 2; -const int NM_METERED_GUESS_YES = 3; -const int NM_METERED_GUESS_NO = 4; diff --git a/selfdrive/ui/qt/network/wifi_manager.cc b/selfdrive/ui/qt/network/wifi_manager.cc deleted file mode 100644 index b0c95352730118..00000000000000 --- a/selfdrive/ui/qt/network/wifi_manager.cc +++ /dev/null @@ -1,507 +0,0 @@ -#include "selfdrive/ui/qt/network/wifi_manager.h" - -#include - -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/widgets/prime.h" - -#include "common/params.h" -#include "common/swaglog.h" -#include "selfdrive/ui/qt/util.h" - -bool compare_by_strength(const Network &a, const Network &b) { - return std::tuple(a.connected, strengthLevel(a.strength), b.ssid) > - std::tuple(b.connected, strengthLevel(b.strength), a.ssid); -} - -template -T call(const QString &path, const QString &interface, const QString &method, Args &&...args) { - QDBusInterface nm(NM_DBUS_SERVICE, path, interface, QDBusConnection::systemBus()); - nm.setTimeout(DBUS_TIMEOUT); - - QDBusMessage response = nm.call(method, std::forward(args)...); - if (response.type() == QDBusMessage::ErrorMessage) { - qCritical() << "DBus call error:" << response.errorMessage(); - return T(); - } - - if constexpr (std::is_same_v) { - return response; - } else if (response.arguments().count() >= 1) { - QVariant vFirst = response.arguments().at(0).value().variant(); - if (vFirst.canConvert()) { - return vFirst.value(); - } - QDebug critical = qCritical(); - critical << "Variant unpacking failure :" << method << ','; - (critical << ... << args); - } - return T(); -} - -template -QDBusPendingCall asyncCall(const QString &path, const QString &interface, const QString &method, Args &&...args) { - QDBusInterface nm = QDBusInterface(NM_DBUS_SERVICE, path, interface, QDBusConnection::systemBus()); - return nm.asyncCall(method, args...); -} - -bool emptyPath(const QString &path) { - return path == "" || path == "/"; -} - -WifiManager::WifiManager(QObject *parent) : QObject(parent) { - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); - - // Set tethering ssid as "weedle" + first 4 characters of a dongle id - tethering_ssid = "weedle"; - if (auto dongle_id = getDongleId()) { - tethering_ssid += "-" + dongle_id->left(4); - } - - adapter = getAdapter(); - if (!adapter.isEmpty()) { - setup(); - } else { - QDBusConnection::systemBus().connect(NM_DBUS_SERVICE, NM_DBUS_PATH, NM_DBUS_INTERFACE, "DeviceAdded", this, SLOT(deviceAdded(QDBusObjectPath))); - } - - timer.callOnTimeout(this, &WifiManager::requestScan); - - initConnections(); -} - -void WifiManager::setup() { - auto bus = QDBusConnection::systemBus(); - bus.connect(NM_DBUS_SERVICE, adapter, NM_DBUS_INTERFACE_DEVICE, "StateChanged", this, SLOT(stateChange(unsigned int, unsigned int, unsigned int))); - bus.connect(NM_DBUS_SERVICE, adapter, NM_DBUS_INTERFACE_PROPERTIES, "PropertiesChanged", this, SLOT(propertyChange(QString, QVariantMap, QStringList))); - - bus.connect(NM_DBUS_SERVICE, NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "ConnectionRemoved", this, SLOT(connectionRemoved(QDBusObjectPath))); - bus.connect(NM_DBUS_SERVICE, NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "NewConnection", this, SLOT(newConnection(QDBusObjectPath))); - - raw_adapter_state = call(adapter, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE, "State"); - activeAp = call(adapter, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE_WIRELESS, "ActiveAccessPoint").path(); - - requestScan(); -} - -void WifiManager::start() { - timer.start(5000); - refreshNetworks(); -} - -void WifiManager::stop() { - timer.stop(); -} - -void WifiManager::refreshNetworks() { - if (adapter.isEmpty() || !timer.isActive()) return; - - QDBusPendingCall pending_call = asyncCall(adapter, NM_DBUS_INTERFACE_DEVICE_WIRELESS, "GetAllAccessPoints"); - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &WifiManager::refreshFinished); -} - -void WifiManager::refreshFinished(QDBusPendingCallWatcher *watcher) { - ipv4_address = getIp4Address(); - seenNetworks.clear(); - - const QDBusReply> watcher_reply = *watcher; - if (!watcher_reply.isValid()) { - qCritical() << "Failed to refresh"; - watcher->deleteLater(); - return; - } - - for (const QDBusObjectPath &path : watcher_reply.value()) { - QDBusReply reply = call(path.path(), NM_DBUS_INTERFACE_PROPERTIES, "GetAll", NM_DBUS_INTERFACE_ACCESS_POINT); - if (!reply.isValid()) { - qCritical() << "Failed to retrieve properties for path:" << path.path(); - continue; - } - - auto properties = reply.value(); - const QByteArray ssid = properties["Ssid"].toByteArray(); - if (ssid.isEmpty()) continue; - - // May be multiple access points for each SSID. - // Use first for ssid and security type, then update connected status and strength using all - if (!seenNetworks.contains(ssid)) { - seenNetworks[ssid] = {ssid, 0U, ConnectedType::DISCONNECTED, getSecurityType(properties)}; - } - - if (path.path() == activeAp) { - seenNetworks[ssid].connected = (ssid == connecting_to_network) ? ConnectedType::CONNECTING : ConnectedType::CONNECTED; - } - - uint32_t strength = properties["Strength"].toUInt(); - if (seenNetworks[ssid].strength < strength) { - seenNetworks[ssid].strength = strength; - } - } - - emit refreshSignal(); - watcher->deleteLater(); -} - -QString WifiManager::getIp4Address() { - if (raw_adapter_state != NM_DEVICE_STATE_ACTIVATED) return ""; - - for (const auto &p : getActiveConnections()) { - QString type = call(p.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "802-11-wireless") { - auto ip4config = call(p.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Ip4Config"); - const auto &arr = call(ip4config.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_IP4_CONFIG, "AddressData"); - QVariantMap path; - arr.beginArray(); - while (!arr.atEnd()) { - arr >> path; - arr.endArray(); - return path.value("address").value(); - } - arr.endArray(); - } - } - return ""; -} - -SecurityType WifiManager::getSecurityType(const QVariantMap &properties) { - int sflag = properties["Flags"].toUInt(); - int wpaflag = properties["WpaFlags"].toUInt(); - int rsnflag = properties["RsnFlags"].toUInt(); - int wpa_props = wpaflag | rsnflag; - - // obtained by looking at flags of networks in the office as reported by an Android phone - const int supports_wpa = NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104 | NM_802_11_AP_SEC_GROUP_WEP40 | NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_KEY_MGMT_PSK; - - if ((sflag == NM_802_11_AP_FLAGS_NONE) || ((sflag & NM_802_11_AP_FLAGS_WPS) && !(wpa_props & supports_wpa))) { - return SecurityType::OPEN; - } else if ((sflag & NM_802_11_AP_FLAGS_PRIVACY) && (wpa_props & supports_wpa) && !(wpa_props & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { - return SecurityType::WPA; - } else { - LOGW("Unsupported network! sflag: %d, wpaflag: %d, rsnflag: %d", sflag, wpaflag, rsnflag); - return SecurityType::UNSUPPORTED; - } -} - -void WifiManager::connect(const Network &n, const bool is_hidden, const QString &password, const QString &username) { - setCurrentConnecting(n.ssid); - forgetConnection(n.ssid); // Clear all connections that may already exist to the network we are connecting - Connection connection; - connection["connection"]["type"] = "802-11-wireless"; - connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); - connection["connection"]["id"] = "openpilot connection " + QString::fromStdString(n.ssid.toStdString()); - connection["connection"]["autoconnect-retries"] = 0; - - connection["802-11-wireless"]["ssid"] = n.ssid; - connection["802-11-wireless"]["hidden"] = is_hidden; - connection["802-11-wireless"]["mode"] = "infrastructure"; - - if (n.security_type == SecurityType::WPA) { - connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; - connection["802-11-wireless-security"]["auth-alg"] = "open"; - connection["802-11-wireless-security"]["psk"] = password; - } - - connection["ipv4"]["method"] = "auto"; - connection["ipv4"]["dns-priority"] = 600; - connection["ipv6"]["method"] = "ignore"; - - call(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "AddConnection", QVariant::fromValue(connection)); -} - -void WifiManager::deactivateConnectionBySsid(const QString &ssid) { - for (QDBusObjectPath active_connection : getActiveConnections()) { - auto pth = call(active_connection.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "SpecificObject"); - if (!emptyPath(pth.path())) { - QString Ssid = get_property(pth.path(), "Ssid"); - if (Ssid == ssid) { - deactivateConnection(active_connection); - return; - } - } - } -} - -void WifiManager::deactivateConnection(const QDBusObjectPath &path) { - asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "DeactivateConnection", QVariant::fromValue(path)); -} - -QVector WifiManager::getActiveConnections() { - auto result = call(NM_DBUS_PATH, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE, "ActiveConnections"); - return qdbus_cast>(result); -} - -bool WifiManager::isKnownConnection(const QString &ssid) { - return !getConnectionPath(ssid).path().isEmpty(); -} - -void WifiManager::forgetConnection(const QString &ssid) { - const QDBusObjectPath &path = getConnectionPath(ssid); - if (!path.path().isEmpty()) { - call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Delete"); - } -} - -void WifiManager::setCurrentConnecting(const QString &ssid) { - connecting_to_network = ssid; - for (auto &network : seenNetworks) { - network.connected = (network.ssid == ssid) ? ConnectedType::CONNECTING : ConnectedType::DISCONNECTED; - } - emit refreshSignal(); -} - -uint WifiManager::getAdapterType(const QDBusObjectPath &path) { - return call(path.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE, "DeviceType"); -} - -void WifiManager::requestScan() { - if (!adapter.isEmpty()) { - asyncCall(adapter, NM_DBUS_INTERFACE_DEVICE_WIRELESS, "RequestScan", QVariantMap()); - } -} - -QByteArray WifiManager::get_property(const QString &network_path , const QString &property) { - return call(network_path, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACCESS_POINT, property); -} - -QString WifiManager::getAdapter(const uint adapter_type) { - QDBusReply> response = call(NM_DBUS_PATH, NM_DBUS_INTERFACE, "GetDevices"); - for (const QDBusObjectPath &path : response.value()) { - if (getAdapterType(path) == adapter_type) { - return path.path(); - } - } - return ""; -} - -void WifiManager::stateChange(unsigned int new_state, unsigned int previous_state, unsigned int change_reason) { - raw_adapter_state = new_state; - if (new_state == NM_DEVICE_STATE_NEED_AUTH && change_reason == NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT && !connecting_to_network.isEmpty()) { - forgetConnection(connecting_to_network); - emit wrongPassword(connecting_to_network); - } else if (new_state == NM_DEVICE_STATE_ACTIVATED) { - connecting_to_network = ""; - refreshNetworks(); - } -} - -// https://developer.gnome.org/NetworkManager/stable/gdbus-org.freedesktop.NetworkManager.Device.Wireless.html -void WifiManager::propertyChange(const QString &interface, const QVariantMap &props, const QStringList &invalidated_props) { - if (interface == NM_DBUS_INTERFACE_DEVICE_WIRELESS && props.contains("LastScan")) { - refreshNetworks(); - } else if (interface == NM_DBUS_INTERFACE_DEVICE_WIRELESS && props.contains("ActiveAccessPoint")) { - activeAp = props.value("ActiveAccessPoint").value().path(); - } -} - -void WifiManager::deviceAdded(const QDBusObjectPath &path) { - if (getAdapterType(path) == NM_DEVICE_TYPE_WIFI && emptyPath(adapter)) { - adapter = path.path(); - setup(); - } -} - -void WifiManager::connectionRemoved(const QDBusObjectPath &path) { - knownConnections.remove(path); -} - -void WifiManager::newConnection(const QDBusObjectPath &path) { - Connection settings = getConnectionSettings(path); - if (settings.value("connection").value("type") == "802-11-wireless") { - knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); - if (knownConnections[path] != tethering_ssid) { - activateWifiConnection(knownConnections[path]); - } - } -} - -QDBusObjectPath WifiManager::getConnectionPath(const QString &ssid) { - return knownConnections.key(ssid); -} - -Connection WifiManager::getConnectionSettings(const QDBusObjectPath &path) { - return QDBusReply(call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "GetSettings")).value(); -} - -void WifiManager::initConnections() { - const QDBusReply> response = call(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "ListConnections"); - for (const QDBusObjectPath &path : response.value()) { - const Connection settings = getConnectionSettings(path); - if (settings.value("connection").value("type") == "802-11-wireless") { - knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); - } else if (settings.value("connection").value("id") == "lte") { - lteConnectionPath = path; - } - } -} - -std::optional WifiManager::activateWifiConnection(const QString &ssid) { - const QDBusObjectPath &path = getConnectionPath(ssid); - if (!path.path().isEmpty()) { - setCurrentConnecting(ssid); - return asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(adapter)), QVariant::fromValue(QDBusObjectPath("/"))); - } - return std::nullopt; -} - -void WifiManager::activateModemConnection(const QDBusObjectPath &path) { - QString modem = getAdapter(NM_DEVICE_TYPE_MODEM); - if (!path.path().isEmpty() && !modem.isEmpty()) { - asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(modem)), QVariant::fromValue(QDBusObjectPath("/"))); - } -} - -// function matches tici/hardware.py -NetworkType WifiManager::currentNetworkType() { - auto primary_conn = call(NM_DBUS_PATH, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE, "PrimaryConnection"); - auto primary_type = call(primary_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - - if (primary_type == "802-3-ethernet") { - return NetworkType::ETHERNET; - } else if (primary_type == "802-11-wireless" && !isTetheringEnabled()) { - return NetworkType::WIFI; - } else { - for (const QDBusObjectPath &conn : getActiveConnections()) { - auto type = call(conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "gsm") { - return NetworkType::CELL; - } - } - } - return NetworkType::NONE; -} - -void WifiManager::updateGsmSettings(bool roaming, QString apn, bool metered) { - if (!lteConnectionPath.path().isEmpty()) { - bool changes = false; - bool auto_config = apn.isEmpty(); - Connection settings = getConnectionSettings(lteConnectionPath); - if (settings.value("gsm").value("auto-config").toBool() != auto_config) { - qWarning() << "Changing gsm.auto-config to" << auto_config; - settings["gsm"]["auto-config"] = auto_config; - changes = true; - } - - if (settings.value("gsm").value("apn").toString() != apn) { - qWarning() << "Changing gsm.apn to" << apn; - settings["gsm"]["apn"] = apn; - changes = true; - } - - if (settings.value("gsm").value("home-only").toBool() == roaming) { - qWarning() << "Changing gsm.home-only to" << !roaming; - settings["gsm"]["home-only"] = !roaming; - changes = true; - } - - int meteredInt = metered ? NM_METERED_UNKNOWN : NM_METERED_NO; - if (settings.value("connection").value("metered").toInt() != meteredInt) { - qWarning() << "Changing connection.metered to" << meteredInt; - settings["connection"]["metered"] = meteredInt; - changes = true; - } - - if (changes) { - call(lteConnectionPath.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "UpdateUnsaved", QVariant::fromValue(settings)); // update is temporary - deactivateConnection(lteConnectionPath); - activateModemConnection(lteConnectionPath); - } - } -} - -// Functions for tethering -void WifiManager::addTetheringConnection() { - Connection connection; - connection["connection"]["id"] = "Hotspot"; - connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); - connection["connection"]["type"] = "802-11-wireless"; - connection["connection"]["interface-name"] = "wlan0"; - connection["connection"]["autoconnect"] = false; - - connection["802-11-wireless"]["band"] = "bg"; - connection["802-11-wireless"]["mode"] = "ap"; - connection["802-11-wireless"]["ssid"] = tethering_ssid.toUtf8(); - - connection["802-11-wireless-security"]["group"] = QStringList("ccmp"); - connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; - connection["802-11-wireless-security"]["pairwise"] = QStringList("ccmp"); - connection["802-11-wireless-security"]["proto"] = QStringList("rsn"); - connection["802-11-wireless-security"]["psk"] = defaultTetheringPassword; - - connection["ipv4"]["method"] = "shared"; - QVariantMap address; - address["address"] = "192.168.43.1"; - address["prefix"] = 24u; - connection["ipv4"]["address-data"] = QVariant::fromValue(IpConfig() << address); - connection["ipv4"]["gateway"] = "192.168.43.1"; - connection["ipv4"]["route-metric"] = 1100; - connection["ipv6"]["method"] = "ignore"; - - auto path = call(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "AddConnection", QVariant::fromValue(connection)); - if (!path.path().isEmpty()) { - knownConnections[path] = tethering_ssid; - } -} - -void WifiManager::tetheringActivated(QDBusPendingCallWatcher *call) { - int prime_type = uiState()->primeType(); - int ipv4_forward = (prime_type == PrimeType::PRIME_TYPE_NONE || prime_type == PrimeType::PRIME_TYPE_LITE); - - if (!ipv4_forward) { - QTimer::singleShot(5000, this, [=] { - qWarning() << "net.ipv4.ip_forward = 0"; - std::system("sudo sysctl net.ipv4.ip_forward=0"); - }); - } - call->deleteLater(); -} - -void WifiManager::setTetheringEnabled(bool enabled) { - if (enabled) { - if (!isKnownConnection(tethering_ssid)) { - addTetheringConnection(); - } - - auto pending_call = activateWifiConnection(tethering_ssid); - - if (pending_call) { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(*pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &WifiManager::tetheringActivated); - } - - } else { - deactivateConnectionBySsid(tethering_ssid); - } -} - -bool WifiManager::isTetheringEnabled() { - if (!emptyPath(activeAp)) { - return get_property(activeAp, "Ssid") == tethering_ssid; - } - return false; -} - -QString WifiManager::getTetheringPassword() { - if (!isKnownConnection(tethering_ssid)) { - addTetheringConnection(); - } - const QDBusObjectPath &path = getConnectionPath(tethering_ssid); - if (!path.path().isEmpty()) { - QDBusReply> response = call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "GetSecrets", "802-11-wireless-security"); - return response.value().value("802-11-wireless-security").value("psk").toString(); - } - return ""; -} - -void WifiManager::changeTetheringPassword(const QString &newPassword) { - const QDBusObjectPath &path = getConnectionPath(tethering_ssid); - if (!path.path().isEmpty()) { - Connection settings = getConnectionSettings(path); - settings["802-11-wireless-security"]["psk"] = newPassword; - call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Update", QVariant::fromValue(settings)); - if (isTetheringEnabled()) { - activateWifiConnection(tethering_ssid); - } - } -} diff --git a/selfdrive/ui/qt/network/wifi_manager.h b/selfdrive/ui/qt/network/wifi_manager.h deleted file mode 100644 index 2f6a1829d785cd..00000000000000 --- a/selfdrive/ui/qt/network/wifi_manager.h +++ /dev/null @@ -1,102 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "selfdrive/ui/qt/network/networkmanager.h" - -enum class SecurityType { - OPEN, - WPA, - UNSUPPORTED -}; -enum class ConnectedType { - DISCONNECTED, - CONNECTING, - CONNECTED -}; -enum class NetworkType { - NONE, - WIFI, - CELL, - ETHERNET -}; - -typedef QMap Connection; -typedef QVector IpConfig; - -struct Network { - QByteArray ssid; - unsigned int strength; - ConnectedType connected; - SecurityType security_type; -}; -bool compare_by_strength(const Network &a, const Network &b); -inline int strengthLevel(unsigned int strength) { return std::clamp((int)round(strength / 33.), 0, 3); } - -class WifiManager : public QObject { - Q_OBJECT - -public: - QMap seenNetworks; - QMap knownConnections; - QString ipv4_address; - - explicit WifiManager(QObject* parent); - void start(); - void stop(); - void requestScan(); - void forgetConnection(const QString &ssid); - bool isKnownConnection(const QString &ssid); - std::optional activateWifiConnection(const QString &ssid); - NetworkType currentNetworkType(); - void updateGsmSettings(bool roaming, QString apn, bool metered); - void connect(const Network &ssid, const bool is_hidden = false, const QString &password = {}, const QString &username = {}); - - // Tethering functions - void setTetheringEnabled(bool enabled); - bool isTetheringEnabled(); - void changeTetheringPassword(const QString &newPassword); - QString getTetheringPassword(); - -private: - QString adapter; // Path to network manager wifi-device - QTimer timer; - unsigned int raw_adapter_state = NM_DEVICE_STATE_UNKNOWN; // Connection status https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMDeviceState - QString connecting_to_network; - QString tethering_ssid; - const QString defaultTetheringPassword = "swagswagcomma"; - QString activeAp; - QDBusObjectPath lteConnectionPath; - - QString getAdapter(const uint = NM_DEVICE_TYPE_WIFI); - uint getAdapterType(const QDBusObjectPath &path); - QString getIp4Address(); - void deactivateConnectionBySsid(const QString &ssid); - void deactivateConnection(const QDBusObjectPath &path); - QVector getActiveConnections(); - QByteArray get_property(const QString &network_path, const QString &property); - SecurityType getSecurityType(const QVariantMap &properties); - QDBusObjectPath getConnectionPath(const QString &ssid); - Connection getConnectionSettings(const QDBusObjectPath &path); - void initConnections(); - void setup(); - void refreshNetworks(); - void activateModemConnection(const QDBusObjectPath &path); - void addTetheringConnection(); - void setCurrentConnecting(const QString &ssid); - -signals: - void wrongPassword(const QString &ssid); - void refreshSignal(); - -private slots: - void stateChange(unsigned int new_state, unsigned int previous_state, unsigned int change_reason); - void propertyChange(const QString &interface, const QVariantMap &props, const QStringList &invalidated_props); - void deviceAdded(const QDBusObjectPath &path); - void connectionRemoved(const QDBusObjectPath &path); - void newConnection(const QDBusObjectPath &path); - void refreshFinished(QDBusPendingCallWatcher *call); - void tetheringActivated(QDBusPendingCallWatcher *call); -}; diff --git a/selfdrive/ui/qt/offroad/driverview.cc b/selfdrive/ui/qt/offroad/driverview.cc deleted file mode 100644 index df9bb246510cfb..00000000000000 --- a/selfdrive/ui/qt/offroad/driverview.cc +++ /dev/null @@ -1,77 +0,0 @@ -#include "selfdrive/ui/qt/offroad/driverview.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -const int FACE_IMG_SIZE = 130; - -DriverViewWindow::DriverViewWindow(QWidget* parent) : CameraWidget("camerad", VISION_STREAM_DRIVER, true, parent) { - face_img = loadPixmap("../assets/img_driver_face_static.png", {FACE_IMG_SIZE, FACE_IMG_SIZE}); - QObject::connect(this, &CameraWidget::clicked, this, &DriverViewWindow::done); - QObject::connect(device(), &Device::interactiveTimeout, this, [this]() { - if (isVisible()) { - emit done(); - } - }); -} - -void DriverViewWindow::showEvent(QShowEvent* event) { - params.putBool("IsDriverViewEnabled", true); - device()->resetInteractiveTimeout(60); - CameraWidget::showEvent(event); -} - -void DriverViewWindow::hideEvent(QHideEvent* event) { - params.putBool("IsDriverViewEnabled", false); - stopVipcThread(); - CameraWidget::hideEvent(event); -} - -void DriverViewWindow::paintGL() { - CameraWidget::paintGL(); - - std::lock_guard lk(frame_lock); - QPainter p(this); - // startup msg - if (frames.empty()) { - p.setPen(Qt::white); - p.setRenderHint(QPainter::TextAntialiasing); - p.setFont(InterFont(100, QFont::Bold)); - p.drawText(geometry(), Qt::AlignCenter, tr("camera starting")); - return; - } - - const auto &sm = *(uiState()->sm); - cereal::DriverStateV2::Reader driver_state = sm["driverStateV2"].getDriverStateV2(); - bool is_rhd = driver_state.getWheelOnRightProb() > 0.5; - auto driver_data = is_rhd ? driver_state.getRightDriverData() : driver_state.getLeftDriverData(); - - bool face_detected = driver_data.getFaceProb() > 0.7; - if (face_detected) { - auto fxy_list = driver_data.getFacePosition(); - auto std_list = driver_data.getFaceOrientationStd(); - float face_x = fxy_list[0]; - float face_y = fxy_list[1]; - float face_std = std::max(std_list[0], std_list[1]); - - float alpha = 0.7; - if (face_std > 0.15) { - alpha = std::max(0.7 - (face_std-0.15)*3.5, 0.0); - } - const int box_size = 220; - // use approx instead of distort_points - int fbox_x = 1080.0 - 1714.0 * face_x; - int fbox_y = -135.0 + (504.0 + std::abs(face_x)*112.0) + (1205.0 - std::abs(face_x)*724.0) * face_y; - p.setPen(QPen(QColor(255, 255, 255, alpha * 255), 10)); - p.drawRoundedRect(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size, 35.0, 35.0); - } - - // icon - const int img_offset = 60; - const int img_x = is_rhd ? rect().right() - FACE_IMG_SIZE - img_offset : rect().left() + img_offset; - const int img_y = rect().bottom() - FACE_IMG_SIZE - img_offset; - p.setOpacity(face_detected ? 1.0 : 0.2); - p.drawPixmap(img_x, img_y, face_img); -} diff --git a/selfdrive/ui/qt/offroad/driverview.h b/selfdrive/ui/qt/offroad/driverview.h deleted file mode 100644 index 155e4ede32073d..00000000000000 --- a/selfdrive/ui/qt/offroad/driverview.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/widgets/cameraview.h" - -class DriverViewWindow : public CameraWidget { - Q_OBJECT - -public: - explicit DriverViewWindow(QWidget *parent); - -signals: - void done(); - -protected: - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - void paintGL() override; - - Params params; - QPixmap face_img; -}; diff --git a/selfdrive/ui/qt/offroad/experimental_mode.cc b/selfdrive/ui/qt/offroad/experimental_mode.cc deleted file mode 100644 index b99220c1d18369..00000000000000 --- a/selfdrive/ui/qt/offroad/experimental_mode.cc +++ /dev/null @@ -1,76 +0,0 @@ -#include "selfdrive/ui/qt/offroad/experimental_mode.h" - -#include -#include -#include -#include -#include - -#include "selfdrive/ui/ui.h" - -ExperimentalModeButton::ExperimentalModeButton(QWidget *parent) : QPushButton(parent) { - chill_pixmap = QPixmap("../assets/img_couch.svg").scaledToWidth(img_width, Qt::SmoothTransformation); - experimental_pixmap = QPixmap("../assets/img_experimental_grey.svg").scaledToWidth(img_width, Qt::SmoothTransformation); - - // go to toggles and expand experimental mode description - connect(this, &QPushButton::clicked, [=]() { emit openSettings(2, "ExperimentalMode"); }); - - setFixedHeight(125); - QHBoxLayout *main_layout = new QHBoxLayout; - main_layout->setContentsMargins(horizontal_padding, 0, horizontal_padding, 0); - - mode_label = new QLabel; - mode_icon = new QLabel; - mode_icon->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - - main_layout->addWidget(mode_label, 1, Qt::AlignLeft); - main_layout->addWidget(mode_icon, 0, Qt::AlignRight); - - setLayout(main_layout); - - setStyleSheet(R"( - QPushButton { - border: none; - } - - QLabel { - font-size: 45px; - font-weight: 300; - text-align: left; - font-family: JetBrainsMono; - color: #000000; - } - )"); -} - -void ExperimentalModeButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing); - - QPainterPath path; - path.addRoundedRect(rect(), 10, 10); - - // gradient - bool pressed = isDown(); - QLinearGradient gradient(rect().left(), 0, rect().right(), 0); - if (experimental_mode) { - gradient.setColorAt(0, QColor(255, 155, 63, pressed ? 0xcc : 0xff)); - gradient.setColorAt(1, QColor(219, 56, 34, pressed ? 0xcc : 0xff)); - } else { - gradient.setColorAt(0, QColor(20, 255, 171, pressed ? 0xcc : 0xff)); - gradient.setColorAt(1, QColor(35, 149, 255, pressed ? 0xcc : 0xff)); - } - p.fillPath(path, gradient); - - // vertical line - p.setPen(QPen(QColor(0, 0, 0, 0x4d), 3, Qt::SolidLine)); - int line_x = rect().right() - img_width - (2 * horizontal_padding); - p.drawLine(line_x, rect().bottom(), line_x, rect().top()); -} - -void ExperimentalModeButton::showEvent(QShowEvent *event) { - experimental_mode = params.getBool("ExperimentalMode"); - mode_icon->setPixmap(experimental_mode ? experimental_pixmap : chill_pixmap); - mode_label->setText(experimental_mode ? tr("EXPERIMENTAL MODE ON") : tr("CHILL MODE ON")); -} diff --git a/selfdrive/ui/qt/offroad/experimental_mode.h b/selfdrive/ui/qt/offroad/experimental_mode.h deleted file mode 100644 index bfb7638bbec4b3..00000000000000 --- a/selfdrive/ui/qt/offroad/experimental_mode.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include - -#include "common/params.h" - -class ExperimentalModeButton : public QPushButton { - Q_OBJECT - -public: - explicit ExperimentalModeButton(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString &toggle = ""); - -private: - void showEvent(QShowEvent *event) override; - - Params params; - bool experimental_mode; - int img_width = 100; - int horizontal_padding = 30; - QPixmap experimental_pixmap; - QPixmap chill_pixmap; - QLabel *mode_label; - QLabel *mode_icon; - -protected: - void paintEvent(QPaintEvent *event) override; -}; diff --git a/selfdrive/ui/qt/offroad/onboarding.cc b/selfdrive/ui/qt/offroad/onboarding.cc deleted file mode 100644 index bae7e3bdf31ef9..00000000000000 --- a/selfdrive/ui/qt/offroad/onboarding.cc +++ /dev/null @@ -1,232 +0,0 @@ -#include "selfdrive/ui/qt/offroad/onboarding.h" - -#include - -#include -#include -#include -#include -#include - -#include "common/util.h" -#include "common/params.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -TrainingGuide::TrainingGuide(QWidget *parent) : QFrame(parent) { - setAttribute(Qt::WA_OpaquePaintEvent); -} - -void TrainingGuide::mouseReleaseEvent(QMouseEvent *e) { - if (click_timer.elapsed() < 250) { - return; - } - click_timer.restart(); - - auto contains = [this](QRect r, const QPoint &pt) { - if (image.size() != image_raw_size) { - QTransform transform; - transform.translate((width()- image.width()) / 2.0, (height()- image.height()) / 2.0); - transform.scale(image.width() / (float)image_raw_size.width(), image.height() / (float)image_raw_size.height()); - r= transform.mapRect(r); - } - return r.contains(pt); - }; - - if (contains(boundingRect[currentIndex], e->pos())) { - if (currentIndex == 9) { - const QRect yes = QRect(707, 804, 531, 164); - Params().putBool("RecordFront", contains(yes, e->pos())); - } - currentIndex += 1; - } else if (currentIndex == (boundingRect.size() - 2) && contains(boundingRect.last(), e->pos())) { - currentIndex = 0; - } - - if (currentIndex >= (boundingRect.size() - 1)) { - emit completedTraining(); - } else { - update(); - } -} - -void TrainingGuide::showEvent(QShowEvent *event) { - currentIndex = 0; - click_timer.start(); -} - -QImage TrainingGuide::loadImage(int id) { - QImage img(img_path + QString("step%1.png").arg(id)); - image_raw_size = img.size(); - if (image_raw_size != rect().size()) { - img = img.scaled(width(), height(), Qt::KeepAspectRatio, Qt::SmoothTransformation); - } - return img; -} - -void TrainingGuide::paintEvent(QPaintEvent *event) { - QPainter painter(this); - - QRect bg(0, 0, painter.device()->width(), painter.device()->height()); - painter.fillRect(bg, QColor("#000000")); - - image = loadImage(currentIndex); - QRect rect(image.rect()); - rect.moveCenter(bg.center()); - painter.drawImage(rect.topLeft(), image); - - // progress bar - if (currentIndex > 0 && currentIndex < (boundingRect.size() - 2)) { - const int h = 20; - const int w = (currentIndex / (float)(boundingRect.size() - 2)) * width(); - painter.fillRect(QRect(0, height() - h, w, h), QColor("#465BEA")); - } -} - -void TermsPage::showEvent(QShowEvent *event) { - // late init, building QML widget takes 200ms - if (layout()) { - return; - } - - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(45, 35, 45, 45); - main_layout->setSpacing(0); - - QLabel *title = new QLabel(tr("Terms & Conditions")); - title->setStyleSheet("font-size: 90px; font-weight: 600;"); - main_layout->addWidget(title); - - QLabel *text = new QLabel(this); - text->setTextFormat(Qt::RichText); - text->setWordWrap(true); - text->setText(QString::fromStdString(util::read_file("../assets/offroad/tc.html"))); - text->setStyleSheet("font-size:50px; font-weight: 200; color: #C9C9C9; background-color:#1B1B1B; padding:50px 50px;"); - ScrollView *scroll = new ScrollView(text, this); - - main_layout->addSpacing(30); - main_layout->addWidget(scroll); - main_layout->addSpacing(50); - - QHBoxLayout* buttons = new QHBoxLayout; - buttons->setMargin(0); - buttons->setSpacing(45); - main_layout->addLayout(buttons); - - QPushButton *decline_btn = new QPushButton(tr("Decline")); - buttons->addWidget(decline_btn); - QObject::connect(decline_btn, &QPushButton::clicked, this, &TermsPage::declinedTerms); - - accept_btn = new QPushButton(tr("Scroll to accept")); - accept_btn->setEnabled(false); - accept_btn->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #3049F4; - } - QPushButton:disabled { - background-color: #4F4F4F; - } - )"); - buttons->addWidget(accept_btn); - QObject::connect(accept_btn, &QPushButton::clicked, this, &TermsPage::acceptedTerms); - QScrollBar *scroll_bar = scroll->verticalScrollBar(); - connect(scroll_bar, &QScrollBar::valueChanged, this, [this, scroll_bar](int value) { - if (value == scroll_bar->maximum()) { - enableAccept(); - } - }); -} - -void TermsPage::enableAccept() { - accept_btn->setText(tr("Agree")); - accept_btn->setEnabled(true); -} - -void DeclinePage::showEvent(QShowEvent *event) { - if (layout()) { - return; - } - - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(45); - main_layout->setSpacing(40); - - QLabel *text = new QLabel(this); - text->setText(tr("You must accept the Terms and Conditions in order to use openpilot.")); - text->setStyleSheet(R"(font-size: 80px; font-weight: 300; margin: 200px;)"); - text->setWordWrap(true); - main_layout->addWidget(text, 0, Qt::AlignCenter); - - QHBoxLayout* buttons = new QHBoxLayout; - buttons->setSpacing(45); - main_layout->addLayout(buttons); - - QPushButton *back_btn = new QPushButton(tr("Back")); - buttons->addWidget(back_btn); - - QObject::connect(back_btn, &QPushButton::clicked, this, &DeclinePage::getBack); - - QPushButton *uninstall_btn = new QPushButton(tr("Decline, uninstall %1").arg(getBrand())); - uninstall_btn->setStyleSheet("background-color: #B73D3D"); - buttons->addWidget(uninstall_btn); - QObject::connect(uninstall_btn, &QPushButton::clicked, [=]() { - Params().putBool("DoUninstall", true); - }); -} - -void OnboardingWindow::updateActiveScreen() { - if (!accepted_terms) { - setCurrentIndex(0); - } else if (!training_done) { - setCurrentIndex(1); - } else { - emit onboardingDone(); - } -} - -OnboardingWindow::OnboardingWindow(QWidget *parent) : QStackedWidget(parent) { - std::string current_terms_version = params.get("TermsVersion"); - std::string current_training_version = params.get("TrainingVersion"); - accepted_terms = params.get("HasAcceptedTerms") == current_terms_version; - training_done = params.get("CompletedTrainingVersion") == current_training_version; - - TermsPage* terms = new TermsPage(this); - addWidget(terms); - connect(terms, &TermsPage::acceptedTerms, [=]() { - params.put("HasAcceptedTerms", current_terms_version); - accepted_terms = true; - updateActiveScreen(); - }); - connect(terms, &TermsPage::declinedTerms, [=]() { setCurrentIndex(2); }); - - TrainingGuide* tr = new TrainingGuide(this); - addWidget(tr); - connect(tr, &TrainingGuide::completedTraining, [=]() { - training_done = true; - params.put("CompletedTrainingVersion", current_training_version); - updateActiveScreen(); - }); - - DeclinePage* declinePage = new DeclinePage(this); - addWidget(declinePage); - connect(declinePage, &DeclinePage::getBack, [=]() { updateActiveScreen(); }); - - setStyleSheet(R"( - * { - color: white; - background-color: black; - } - QPushButton { - height: 160px; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #4F4F4F; - } - )"); - updateActiveScreen(); -} diff --git a/selfdrive/ui/qt/offroad/onboarding.h b/selfdrive/ui/qt/offroad/onboarding.h deleted file mode 100644 index a1b6895ba087d0..00000000000000 --- a/selfdrive/ui/qt/offroad/onboarding.h +++ /dev/null @@ -1,110 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/qt_window.h" - -class TrainingGuide : public QFrame { - Q_OBJECT - -public: - explicit TrainingGuide(QWidget *parent = 0); - -private: - void showEvent(QShowEvent *event) override; - void paintEvent(QPaintEvent *event) override; - void mouseReleaseEvent(QMouseEvent* e) override; - QImage loadImage(int id); - - QImage image; - QSize image_raw_size; - int currentIndex = 0; - - // Bounding boxes for each training guide step - const QRect continueBtn = {1840, 0, 320, 1080}; - QVector boundingRect { - QRect(112, 804, 618, 164), - continueBtn, - continueBtn, - QRect(1641, 558, 210, 313), - QRect(1662, 528, 184, 108), - continueBtn, - QRect(1814, 621, 211, 170), - QRect(1350, 0, 497, 755), - QRect(1540, 386, 468, 238), - QRect(112, 804, 1126, 164), - QRect(1598, 199, 316, 333), - continueBtn, - QRect(1364, 90, 796, 990), - continueBtn, - QRect(1593, 114, 318, 853), - QRect(1379, 511, 391, 243), - continueBtn, - continueBtn, - QRect(630, 804, 626, 164), - QRect(108, 804, 426, 164), - }; - - const QString img_path = "../assets/training/"; - QElapsedTimer click_timer; - -signals: - void completedTraining(); -}; - - -class TermsPage : public QFrame { - Q_OBJECT - -public: - explicit TermsPage(QWidget *parent = 0) : QFrame(parent) {} - -public slots: - void enableAccept(); - -private: - void showEvent(QShowEvent *event) override; - - QPushButton *accept_btn; - -signals: - void acceptedTerms(); - void declinedTerms(); -}; - -class DeclinePage : public QFrame { - Q_OBJECT - -public: - explicit DeclinePage(QWidget *parent = 0) : QFrame(parent) {} - -private: - void showEvent(QShowEvent *event) override; - -signals: - void getBack(); -}; - -class OnboardingWindow : public QStackedWidget { - Q_OBJECT - -public: - explicit OnboardingWindow(QWidget *parent = 0); - inline void showTrainingGuide() { setCurrentIndex(1); } - inline bool completed() const { return accepted_terms && training_done; } - -private: - void updateActiveScreen(); - - Params params; - bool accepted_terms = false, training_done = false; - -signals: - void onboardingDone(); -}; diff --git a/selfdrive/ui/qt/offroad/settings.cc b/selfdrive/ui/qt/offroad/settings.cc deleted file mode 100644 index fc92a471d6c2bf..00000000000000 --- a/selfdrive/ui/qt/offroad/settings.cc +++ /dev/null @@ -1,453 +0,0 @@ -#include -#include -#include -#include -#include - -#include - -#include "common/watchdog.h" -#include "common/util.h" -#include "selfdrive/ui/qt/network/networking.h" -#include "selfdrive/ui/qt/offroad/settings.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/prime.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" -#include "selfdrive/ui/qt/widgets/ssh_keys.h" - -TogglesPanel::TogglesPanel(SettingsWindow *parent) : ListWidget(parent) { - // param, title, desc, icon - std::vector> toggle_defs{ - { - "OpenpilotEnabledToggle", - tr("Enable openpilot"), - tr("Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off."), - "../assets/offroad/icon_openpilot.png", - }, - { - "ExperimentalLongitudinalEnabled", - tr("openpilot Longitudinal Control (Alpha)"), - QString("%1

%2") - .arg(tr("WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB).")) - .arg(tr("On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. " - "Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha.")), - "../assets/offroad/icon_speed_limit.png", - }, - { - "ExperimentalMode", - tr("Experimental Mode"), - "", - "../assets/img_experimental_white.svg", - }, - { - "DisengageOnAccelerator", - tr("Disengage on Accelerator Pedal"), - tr("When enabled, pressing the accelerator pedal will disengage openpilot."), - "../assets/offroad/icon_disengage_on_accelerator.svg", - }, - { - "IsLdwEnabled", - tr("Enable Lane Departure Warnings"), - tr("Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h)."), - "../assets/offroad/icon_warning.png", - }, - { - "AlwaysOnDM", - tr("Always-On Driver Monitoring"), - tr("Enable driver monitoring even when openpilot is not engaged."), - "../assets/offroad/icon_monitoring.png", - }, - { - "RecordFront", - tr("Record and Upload Driver Camera"), - tr("Upload data from the driver facing camera and help improve the driver monitoring algorithm."), - "../assets/offroad/icon_monitoring.png", - }, - { - "IsMetric", - tr("Use Metric System"), - tr("Display speed in km/h instead of mph."), - "../assets/offroad/icon_metric.png", - }, - }; - - - std::vector longi_button_texts{tr("Aggressive"), tr("Standard"), tr("Relaxed")}; - long_personality_setting = new ButtonParamControl("LongitudinalPersonality", tr("Driving Personality"), - tr("Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. " - "In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " - "your steering wheel distance button."), - "../assets/offroad/icon_speed_limit.png", - longi_button_texts); - - // set up uiState update for personality setting - QObject::connect(uiState(), &UIState::uiUpdate, this, &TogglesPanel::updateState); - - for (auto &[param, title, desc, icon] : toggle_defs) { - auto toggle = new ParamControl(param, title, desc, icon, this); - - bool locked = params.getBool((param + "Lock").toStdString()); - toggle->setEnabled(!locked); - - addItem(toggle); - toggles[param.toStdString()] = toggle; - - // insert longitudinal personality after NDOG toggle - if (param == "DisengageOnAccelerator") { - addItem(long_personality_setting); - } - } - - // Toggles with confirmation dialogs - toggles["ExperimentalMode"]->setActiveIcon("../assets/img_experimental.svg"); - toggles["ExperimentalMode"]->setConfirmation(true, true); - toggles["ExperimentalLongitudinalEnabled"]->setConfirmation(true, false); - - connect(toggles["ExperimentalLongitudinalEnabled"], &ToggleControl::toggleFlipped, [=]() { - updateToggles(); - }); -} - -void TogglesPanel::updateState(const UIState &s) { - const SubMaster &sm = *(s.sm); - - if (sm.updated("selfdriveState")) { - auto personality = sm["selfdriveState"].getSelfdriveState().getPersonality(); - if (personality != s.scene.personality && s.scene.started && isVisible()) { - long_personality_setting->setCheckedButton(static_cast(personality)); - } - uiState()->scene.personality = personality; - } -} - -void TogglesPanel::expandToggleDescription(const QString ¶m) { - toggles[param.toStdString()]->showDescription(); -} - -void TogglesPanel::showEvent(QShowEvent *event) { - updateToggles(); -} - -void TogglesPanel::updateToggles() { - auto experimental_mode_toggle = toggles["ExperimentalMode"]; - auto op_long_toggle = toggles["ExperimentalLongitudinalEnabled"]; - const QString e2e_description = QString("%1
" - "

%2


" - "%3
" - "

%4


" - "%5
") - .arg(tr("openpilot defaults to driving in chill mode. Experimental mode enables alpha-level features that aren't ready for chill mode. Experimental features are listed below:")) - .arg(tr("End-to-End Longitudinal Control")) - .arg(tr("Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. " - "Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; " - "mistakes should be expected.")) - .arg(tr("New Driving Visualization")) - .arg(tr("The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner.")); - - const bool is_release = params.getBool("IsReleaseBranch"); - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - if (!CP.getExperimentalLongitudinalAvailable() || is_release) { - params.remove("ExperimentalLongitudinalEnabled"); - } - op_long_toggle->setVisible(CP.getExperimentalLongitudinalAvailable() && !is_release); - if (hasLongitudinalControl(CP)) { - // normal description and toggle - experimental_mode_toggle->setEnabled(true); - experimental_mode_toggle->setDescription(e2e_description); - long_personality_setting->setEnabled(true); - } else { - // no long for now - experimental_mode_toggle->setEnabled(false); - long_personality_setting->setEnabled(false); - params.remove("ExperimentalMode"); - - const QString unavailable = tr("Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control."); - - QString long_desc = unavailable + " " + \ - tr("openpilot longitudinal control may come in a future update."); - if (CP.getExperimentalLongitudinalAvailable()) { - if (is_release) { - long_desc = unavailable + " " + tr("An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches."); - } else { - long_desc = tr("Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode."); - } - } - experimental_mode_toggle->setDescription("" + long_desc + "

" + e2e_description); - } - - experimental_mode_toggle->refresh(); - } else { - experimental_mode_toggle->setDescription(e2e_description); - op_long_toggle->setVisible(false); - } -} - -DevicePanel::DevicePanel(SettingsWindow *parent) : ListWidget(parent) { - setSpacing(50); - addItem(new LabelControl(tr("Dongle ID"), getDongleId().value_or(tr("N/A")))); - addItem(new LabelControl(tr("Serial"), params.get("HardwareSerial").c_str())); - - pair_device = new ButtonControl(tr("Pair Device"), tr("PAIR"), - tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.")); - connect(pair_device, &ButtonControl::clicked, [=]() { - PairingPopup popup(this); - popup.exec(); - }); - addItem(pair_device); - - // offroad-only buttons - - auto dcamBtn = new ButtonControl(tr("Driver Camera"), tr("PREVIEW"), - tr("Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)")); - connect(dcamBtn, &ButtonControl::clicked, [=]() { emit showDriverView(); }); - addItem(dcamBtn); - - auto resetCalibBtn = new ButtonControl(tr("Reset Calibration"), tr("RESET"), ""); - connect(resetCalibBtn, &ButtonControl::showDescriptionEvent, this, &DevicePanel::updateCalibDescription); - connect(resetCalibBtn, &ButtonControl::clicked, [&]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset calibration?"), tr("Reset"), this)) { - params.remove("CalibrationParams"); - params.remove("LiveTorqueParameters"); - } - }); - addItem(resetCalibBtn); - - auto retrainingBtn = new ButtonControl(tr("Review Training Guide"), tr("REVIEW"), tr("Review the rules, features, and limitations of openpilot")); - connect(retrainingBtn, &ButtonControl::clicked, [=]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to review the training guide?"), tr("Review"), this)) { - emit reviewTrainingGuide(); - } - }); - addItem(retrainingBtn); - - if (Hardware::TICI()) { - auto regulatoryBtn = new ButtonControl(tr("Regulatory"), tr("VIEW"), ""); - connect(regulatoryBtn, &ButtonControl::clicked, [=]() { - const std::string txt = util::read_file("../assets/offroad/fcc.html"); - ConfirmationDialog::rich(QString::fromStdString(txt), this); - }); - addItem(regulatoryBtn); - } - - auto translateBtn = new ButtonControl(tr("Change Language"), tr("CHANGE"), ""); - connect(translateBtn, &ButtonControl::clicked, [=]() { - QMap langs = getSupportedLanguages(); - QString selection = MultiOptionDialog::getSelection(tr("Select a language"), langs.keys(), langs.key(uiState()->language), this); - if (!selection.isEmpty()) { - // put language setting, exit Qt UI, and trigger fast restart - params.put("LanguageSetting", langs[selection].toStdString()); - qApp->exit(18); - watchdog_kick(0); - } - }); - addItem(translateBtn); - - QObject::connect(uiState(), &UIState::primeTypeChanged, [this] (PrimeType type) { - pair_device->setVisible(type == PrimeType::PRIME_TYPE_UNPAIRED); - }); - QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - for (auto btn : findChildren()) { - if (btn != pair_device) { - btn->setEnabled(offroad); - } - } - }); - - // power buttons - QHBoxLayout *power_layout = new QHBoxLayout(); - power_layout->setSpacing(30); - - QPushButton *reboot_btn = new QPushButton(tr("Reboot")); - reboot_btn->setObjectName("reboot_btn"); - power_layout->addWidget(reboot_btn); - QObject::connect(reboot_btn, &QPushButton::clicked, this, &DevicePanel::reboot); - - QPushButton *poweroff_btn = new QPushButton(tr("Power Off")); - poweroff_btn->setObjectName("poweroff_btn"); - power_layout->addWidget(poweroff_btn); - QObject::connect(poweroff_btn, &QPushButton::clicked, this, &DevicePanel::poweroff); - - if (!Hardware::PC()) { - connect(uiState(), &UIState::offroadTransition, poweroff_btn, &QPushButton::setVisible); - } - - setStyleSheet(R"( - #reboot_btn { height: 120px; border-radius: 15px; background-color: #393939; } - #reboot_btn:pressed { background-color: #4a4a4a; } - #poweroff_btn { height: 120px; border-radius: 15px; background-color: #E22C2C; } - #poweroff_btn:pressed { background-color: #FF2424; } - )"); - addItem(power_layout); -} - -void DevicePanel::updateCalibDescription() { - QString desc = - tr("openpilot requires the device to be mounted within 4° left or right and " - "within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required."); - std::string calib_bytes = params.get("CalibrationParams"); - if (!calib_bytes.empty()) { - try { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(calib_bytes.data(), calib_bytes.size())); - auto calib = cmsg.getRoot().getLiveCalibration(); - if (calib.getCalStatus() != cereal::LiveCalibrationData::Status::UNCALIBRATED) { - double pitch = calib.getRpyCalib()[1] * (180 / M_PI); - double yaw = calib.getRpyCalib()[2] * (180 / M_PI); - desc += tr(" Your device is pointed %1° %2 and %3° %4.") - .arg(QString::number(std::abs(pitch), 'g', 1), pitch > 0 ? tr("down") : tr("up"), - QString::number(std::abs(yaw), 'g', 1), yaw > 0 ? tr("left") : tr("right")); - } - } catch (kj::Exception) { - qInfo() << "invalid CalibrationParams"; - } - } - qobject_cast(sender())->setDescription(desc); -} - -void DevicePanel::reboot() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reboot?"), tr("Reboot"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.putBool("DoReboot", true); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Reboot"), this); - } -} - -void DevicePanel::poweroff() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to power off?"), tr("Power Off"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.putBool("DoShutdown", true); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Power Off"), this); - } -} - -void DevicePanel::showEvent(QShowEvent *event) { - pair_device->setVisible(uiState()->primeType() == PrimeType::PRIME_TYPE_UNPAIRED); - ListWidget::showEvent(event); -} - -void SettingsWindow::showEvent(QShowEvent *event) { - setCurrentPanel(0); -} - -void SettingsWindow::setCurrentPanel(int index, const QString ¶m) { - panel_widget->setCurrentIndex(index); - nav_btns->buttons()[index]->setChecked(true); - if (!param.isEmpty()) { - emit expandToggleDescription(param); - } -} - -SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { - - // setup two main layouts - sidebar_widget = new QWidget; - QVBoxLayout *sidebar_layout = new QVBoxLayout(sidebar_widget); - panel_widget = new QStackedWidget(); - - // close button - QPushButton *close_btn = new QPushButton(tr("×")); - close_btn->setStyleSheet(R"( - QPushButton { - font-size: 140px; - padding-bottom: 20px; - border-radius: 100px; - background-color: #292929; - font-weight: 400; - } - QPushButton:pressed { - background-color: #3B3B3B; - } - )"); - close_btn->setFixedSize(200, 200); - sidebar_layout->addSpacing(45); - sidebar_layout->addWidget(close_btn, 0, Qt::AlignCenter); - QObject::connect(close_btn, &QPushButton::clicked, this, &SettingsWindow::closeSettings); - - // setup panels - DevicePanel *device = new DevicePanel(this); - QObject::connect(device, &DevicePanel::reviewTrainingGuide, this, &SettingsWindow::reviewTrainingGuide); - QObject::connect(device, &DevicePanel::showDriverView, this, &SettingsWindow::showDriverView); - - TogglesPanel *toggles = new TogglesPanel(this); - QObject::connect(this, &SettingsWindow::expandToggleDescription, toggles, &TogglesPanel::expandToggleDescription); - - QList> panels = { - {tr("Device"), device}, - {tr("Network"), new Networking(this)}, - {tr("Toggles"), toggles}, - {tr("Software"), new SoftwarePanel(this)}, - }; - - nav_btns = new QButtonGroup(this); - for (auto &[name, panel] : panels) { - QPushButton *btn = new QPushButton(name); - btn->setCheckable(true); - btn->setChecked(nav_btns->buttons().size() == 0); - btn->setStyleSheet(R"( - QPushButton { - color: grey; - border: none; - background: none; - font-size: 65px; - font-weight: 500; - } - QPushButton:checked { - color: white; - } - QPushButton:pressed { - color: #ADADAD; - } - )"); - btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); - nav_btns->addButton(btn); - sidebar_layout->addWidget(btn, 0, Qt::AlignRight); - - const int lr_margin = name != tr("Network") ? 50 : 0; // Network panel handles its own margins - panel->setContentsMargins(lr_margin, 25, lr_margin, 25); - - ScrollView *panel_frame = new ScrollView(panel, this); - panel_widget->addWidget(panel_frame); - - QObject::connect(btn, &QPushButton::clicked, [=, w = panel_frame]() { - btn->setChecked(true); - panel_widget->setCurrentWidget(w); - }); - } - sidebar_layout->setContentsMargins(50, 50, 100, 50); - - // main settings layout, sidebar + main panel - QHBoxLayout *main_layout = new QHBoxLayout(this); - - sidebar_widget->setFixedWidth(500); - main_layout->addWidget(sidebar_widget); - main_layout->addWidget(panel_widget); - - setStyleSheet(R"( - * { - color: white; - font-size: 50px; - } - SettingsWindow { - background-color: black; - } - QStackedWidget, ScrollView { - background-color: #292929; - border-radius: 30px; - } - )"); -} diff --git a/selfdrive/ui/qt/offroad/settings.h b/selfdrive/ui/qt/offroad/settings.h deleted file mode 100644 index 35a044bdd20f1e..00000000000000 --- a/selfdrive/ui/qt/offroad/settings.h +++ /dev/null @@ -1,101 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/controls.h" - -// ********** settings window + top-level panels ********** -class SettingsWindow : public QFrame { - Q_OBJECT - -public: - explicit SettingsWindow(QWidget *parent = 0); - void setCurrentPanel(int index, const QString ¶m = ""); - -protected: - void showEvent(QShowEvent *event) override; - -signals: - void closeSettings(); - void reviewTrainingGuide(); - void showDriverView(); - void expandToggleDescription(const QString ¶m); - -private: - QPushButton *sidebar_alert_widget; - QWidget *sidebar_widget; - QButtonGroup *nav_btns; - QStackedWidget *panel_widget; -}; - -class DevicePanel : public ListWidget { - Q_OBJECT -public: - explicit DevicePanel(SettingsWindow *parent); - void showEvent(QShowEvent *event) override; - -signals: - void reviewTrainingGuide(); - void showDriverView(); - -private slots: - void poweroff(); - void reboot(); - void updateCalibDescription(); - -private: - Params params; - ButtonControl *pair_device; -}; - -class TogglesPanel : public ListWidget { - Q_OBJECT -public: - explicit TogglesPanel(SettingsWindow *parent); - void showEvent(QShowEvent *event) override; - -public slots: - void expandToggleDescription(const QString ¶m); - -private slots: - void updateState(const UIState &s); - -private: - Params params; - std::map toggles; - ButtonParamControl *long_personality_setting; - - void updateToggles(); -}; - -class SoftwarePanel : public ListWidget { - Q_OBJECT -public: - explicit SoftwarePanel(QWidget* parent = nullptr); - -private: - void showEvent(QShowEvent *event) override; - void updateLabels(); - void checkForUpdates(); - - bool is_onroad = false; - - QLabel *onroadLbl; - LabelControl *versionLbl; - ButtonControl *installBtn; - ButtonControl *downloadBtn; - ButtonControl *targetBranchBtn; - - Params params; - ParamWatcher *fs_watch; -}; diff --git a/selfdrive/ui/qt/offroad/software_settings.cc b/selfdrive/ui/qt/offroad/software_settings.cc deleted file mode 100644 index c8245205ce8b5d..00000000000000 --- a/selfdrive/ui/qt/offroad/software_settings.cc +++ /dev/null @@ -1,156 +0,0 @@ -#include "selfdrive/ui/qt/offroad/settings.h" - -#include -#include -#include - -#include -#include - -#include "common/params.h" -#include "common/util.h" -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "system/hardware/hw.h" - - -void SoftwarePanel::checkForUpdates() { - std::system("pkill -SIGUSR1 -f system.updated.updated"); -} - -SoftwarePanel::SoftwarePanel(QWidget* parent) : ListWidget(parent) { - onroadLbl = new QLabel(tr("Updates are only downloaded while the car is off.")); - onroadLbl->setStyleSheet("font-size: 50px; font-weight: 400; text-align: left; padding-top: 30px; padding-bottom: 30px;"); - addItem(onroadLbl); - - // current version - versionLbl = new LabelControl(tr("Current Version"), ""); - addItem(versionLbl); - - // download update btn - downloadBtn = new ButtonControl(tr("Download"), tr("CHECK")); - connect(downloadBtn, &ButtonControl::clicked, [=]() { - downloadBtn->setEnabled(false); - if (downloadBtn->text() == tr("CHECK")) { - checkForUpdates(); - } else { - std::system("pkill -SIGHUP -f system.updated.updated"); - } - }); - addItem(downloadBtn); - - // install update btn - installBtn = new ButtonControl(tr("Install Update"), tr("INSTALL")); - connect(installBtn, &ButtonControl::clicked, [=]() { - installBtn->setEnabled(false); - params.putBool("DoReboot", true); - }); - addItem(installBtn); - - // branch selecting - targetBranchBtn = new ButtonControl(tr("Target Branch"), tr("SELECT")); - connect(targetBranchBtn, &ButtonControl::clicked, [=]() { - auto current = params.get("GitBranch"); - QStringList branches = QString::fromStdString(params.get("UpdaterAvailableBranches")).split(","); - for (QString b : {current.c_str(), "devel-staging", "devel", "nightly", "master-ci", "master"}) { - auto i = branches.indexOf(b); - if (i >= 0) { - branches.removeAt(i); - branches.insert(0, b); - } - } - - QString cur = QString::fromStdString(params.get("UpdaterTargetBranch")); - QString selection = MultiOptionDialog::getSelection(tr("Select a branch"), branches, cur, this); - if (!selection.isEmpty()) { - params.put("UpdaterTargetBranch", selection.toStdString()); - targetBranchBtn->setValue(QString::fromStdString(params.get("UpdaterTargetBranch"))); - checkForUpdates(); - } - }); - if (!params.getBool("IsTestedBranch")) { - addItem(targetBranchBtn); - } - - // uninstall button - auto uninstallBtn = new ButtonControl(tr("Uninstall %1").arg(getBrand()), tr("UNINSTALL")); - connect(uninstallBtn, &ButtonControl::clicked, [&]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to uninstall?"), tr("Uninstall"), this)) { - params.putBool("DoUninstall", true); - } - }); - addItem(uninstallBtn); - - fs_watch = new ParamWatcher(this); - QObject::connect(fs_watch, &ParamWatcher::paramChanged, [=](const QString ¶m_name, const QString ¶m_value) { - updateLabels(); - }); - - connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - is_onroad = !offroad; - updateLabels(); - }); - - updateLabels(); -} - -void SoftwarePanel::showEvent(QShowEvent *event) { - // nice for testing on PC - installBtn->setEnabled(true); - - updateLabels(); -} - -void SoftwarePanel::updateLabels() { - // add these back in case the files got removed - fs_watch->addParam("LastUpdateTime"); - fs_watch->addParam("UpdateFailedCount"); - fs_watch->addParam("UpdaterState"); - fs_watch->addParam("UpdateAvailable"); - - if (!isVisible()) { - return; - } - - // updater only runs offroad - onroadLbl->setVisible(is_onroad); - downloadBtn->setVisible(!is_onroad); - - // download update - QString updater_state = QString::fromStdString(params.get("UpdaterState")); - bool failed = std::atoi(params.get("UpdateFailedCount").c_str()) > 0; - if (updater_state != "idle") { - downloadBtn->setEnabled(false); - downloadBtn->setValue(updater_state); - } else { - if (failed) { - downloadBtn->setText(tr("CHECK")); - downloadBtn->setValue(tr("failed to check for update")); - } else if (params.getBool("UpdaterFetchAvailable")) { - downloadBtn->setText(tr("DOWNLOAD")); - downloadBtn->setValue(tr("update available")); - } else { - QString lastUpdate = tr("never"); - auto tm = params.get("LastUpdateTime"); - if (!tm.empty()) { - lastUpdate = timeAgo(QDateTime::fromString(QString::fromStdString(tm + "Z"), Qt::ISODate)); - } - downloadBtn->setText(tr("CHECK")); - downloadBtn->setValue(tr("up to date, last checked %1").arg(lastUpdate)); - } - downloadBtn->setEnabled(true); - } - targetBranchBtn->setValue(QString::fromStdString(params.get("UpdaterTargetBranch"))); - - // current + new versions - versionLbl->setText(QString::fromStdString(params.get("UpdaterCurrentDescription"))); - versionLbl->setDescription(QString::fromStdString(params.get("UpdaterCurrentReleaseNotes"))); - - installBtn->setVisible(!is_onroad && params.getBool("UpdateAvailable")); - installBtn->setValue(QString::fromStdString(params.get("UpdaterNewDescription"))); - installBtn->setDescription(QString::fromStdString(params.get("UpdaterNewReleaseNotes"))); - - update(); -} diff --git a/selfdrive/ui/qt/onroad/alerts.cc b/selfdrive/ui/qt/onroad/alerts.cc deleted file mode 100644 index d5d2e6c0de0be9..00000000000000 --- a/selfdrive/ui/qt/onroad/alerts.cc +++ /dev/null @@ -1,112 +0,0 @@ -#include "selfdrive/ui/qt/onroad/alerts.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -void OnroadAlerts::updateState(const UIState &s) { - Alert a = getAlert(*(s.sm), s.scene.started_frame); - if (!alert.equal(a)) { - alert = a; - update(); - } -} - -void OnroadAlerts::clear() { - alert = {}; - update(); -} - -OnroadAlerts::Alert OnroadAlerts::getAlert(const SubMaster &sm, uint64_t started_frame) { - const cereal::SelfdriveState::Reader &cs = sm["selfdriveState"].getSelfdriveState(); - const uint64_t controls_frame = sm.rcv_frame("selfdriveState"); - - Alert a = {}; - if (controls_frame >= started_frame) { // Don't get old alert. - a = {cs.getAlertText1().cStr(), cs.getAlertText2().cStr(), - cs.getAlertType().cStr(), cs.getAlertSize(), cs.getAlertStatus()}; - } - - if (!sm.updated("selfdriveState") && (sm.frame - started_frame) > 5 * UI_FREQ) { - const int CONTROLS_TIMEOUT = 5; - const int controls_missing = (nanos_since_boot() - sm.rcv_time("selfdriveState")) / 1e9; - - // Handle controls timeout - if (controls_frame < started_frame) { - // car is started, but selfdriveState hasn't been seen at all - a = {tr("openpilot Unavailable"), tr("Waiting for controls to start"), - "controlsWaiting", cereal::SelfdriveState::AlertSize::MID, - cereal::SelfdriveState::AlertStatus::NORMAL}; - } else if (controls_missing > CONTROLS_TIMEOUT && !Hardware::PC()) { - // car is started, but controls is lagging or died - if (cs.getEnabled() && (controls_missing - CONTROLS_TIMEOUT) < 10) { - a = {tr("TAKE CONTROL IMMEDIATELY"), tr("Controls Unresponsive"), - "controlsUnresponsive", cereal::SelfdriveState::AlertSize::FULL, - cereal::SelfdriveState::AlertStatus::CRITICAL}; - } else { - a = {tr("Controls Unresponsive"), tr("Reboot Device"), - "controlsUnresponsivePermanent", cereal::SelfdriveState::AlertSize::MID, - cereal::SelfdriveState::AlertStatus::NORMAL}; - } - } - } - return a; -} - -void OnroadAlerts::paintEvent(QPaintEvent *event) { - if (alert.size == cereal::SelfdriveState::AlertSize::NONE) { - return; - } - static std::map alert_heights = { - {cereal::SelfdriveState::AlertSize::SMALL, 271}, - {cereal::SelfdriveState::AlertSize::MID, 420}, - {cereal::SelfdriveState::AlertSize::FULL, height()}, - }; - int h = alert_heights[alert.size]; - - int margin = 40; - int radius = 30; - if (alert.size == cereal::SelfdriveState::AlertSize::FULL) { - margin = 0; - radius = 0; - } - QRect r = QRect(0 + margin, height() - h + margin, width() - margin*2, h - margin*2); - - QPainter p(this); - - // draw background + gradient - p.setPen(Qt::NoPen); - p.setCompositionMode(QPainter::CompositionMode_SourceOver); - p.setBrush(QBrush(alert_colors[alert.status])); - p.drawRoundedRect(r, radius, radius); - - QLinearGradient g(0, r.y(), 0, r.bottom()); - g.setColorAt(0, QColor::fromRgbF(0, 0, 0, 0.05)); - g.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0.35)); - - p.setCompositionMode(QPainter::CompositionMode_DestinationOver); - p.setBrush(QBrush(g)); - p.drawRoundedRect(r, radius, radius); - p.setCompositionMode(QPainter::CompositionMode_SourceOver); - - // text - const QPoint c = r.center(); - p.setPen(QColor(0xff, 0xff, 0xff)); - p.setRenderHint(QPainter::TextAntialiasing); - if (alert.size == cereal::SelfdriveState::AlertSize::SMALL) { - p.setFont(InterFont(74, QFont::DemiBold)); - p.drawText(r, Qt::AlignCenter, alert.text1); - } else if (alert.size == cereal::SelfdriveState::AlertSize::MID) { - p.setFont(InterFont(88, QFont::Bold)); - p.drawText(QRect(0, c.y() - 125, width(), 150), Qt::AlignHCenter | Qt::AlignTop, alert.text1); - p.setFont(InterFont(66)); - p.drawText(QRect(0, c.y() + 21, width(), 90), Qt::AlignHCenter, alert.text2); - } else if (alert.size == cereal::SelfdriveState::AlertSize::FULL) { - bool l = alert.text1.length() > 15; - p.setFont(InterFont(l ? 132 : 177, QFont::Bold)); - p.drawText(QRect(0, r.y() + (l ? 240 : 270), width(), 600), Qt::AlignHCenter | Qt::TextWordWrap, alert.text1); - p.setFont(InterFont(88)); - p.drawText(QRect(0, r.height() - (l ? 361 : 420), width(), 300), Qt::AlignHCenter | Qt::TextWordWrap, alert.text2); - } -} diff --git a/selfdrive/ui/qt/onroad/alerts.h b/selfdrive/ui/qt/onroad/alerts.h deleted file mode 100644 index de38d8ffc36d36..00000000000000 --- a/selfdrive/ui/qt/onroad/alerts.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/ui.h" - -class OnroadAlerts : public QWidget { - Q_OBJECT - -public: - OnroadAlerts(QWidget *parent = 0) : QWidget(parent) {} - void updateState(const UIState &s); - void clear(); - -protected: - struct Alert { - QString text1; - QString text2; - QString type; - cereal::SelfdriveState::AlertSize size; - cereal::SelfdriveState::AlertStatus status; - - bool equal(const Alert &other) const { - return text1 == other.text1 && text2 == other.text2 && type == other.type; - } - }; - - const QMap alert_colors = { - {cereal::SelfdriveState::AlertStatus::NORMAL, QColor(0x15, 0x15, 0x15, 0xf1)}, - {cereal::SelfdriveState::AlertStatus::USER_PROMPT, QColor(0xDA, 0x6F, 0x25, 0xf1)}, - {cereal::SelfdriveState::AlertStatus::CRITICAL, QColor(0xC9, 0x22, 0x31, 0xf1)}, - }; - - void paintEvent(QPaintEvent*) override; - OnroadAlerts::Alert getAlert(const SubMaster &sm, uint64_t started_frame); - - QColor bg; - Alert alert = {}; -}; diff --git a/selfdrive/ui/qt/onroad/annotated_camera.cc b/selfdrive/ui/qt/onroad/annotated_camera.cc deleted file mode 100644 index cc9940f2754838..00000000000000 --- a/selfdrive/ui/qt/onroad/annotated_camera.cc +++ /dev/null @@ -1,336 +0,0 @@ - -#include "selfdrive/ui/qt/onroad/annotated_camera.h" - -#include -#include -#include - -#include "common/swaglog.h" -#include "selfdrive/ui/qt/onroad/buttons.h" -#include "selfdrive/ui/qt/util.h" - -// Window that shows camera view and variety of info drawn on top -AnnotatedCameraWidget::AnnotatedCameraWidget(VisionStreamType type, QWidget* parent) : fps_filter(UI_FREQ, 3, 1. / UI_FREQ), CameraWidget("camerad", type, true, parent) { - pm = std::make_unique(std::vector{"uiDebug"}); - - main_layout = new QVBoxLayout(this); - main_layout->setMargin(UI_BORDER_SIZE); - main_layout->setSpacing(0); - - experimental_btn = new ExperimentalButton(this); - main_layout->addWidget(experimental_btn, 0, Qt::AlignTop | Qt::AlignRight); -} - -void AnnotatedCameraWidget::updateState(const UIState &s) { - const int SET_SPEED_NA = 255; - const SubMaster &sm = *(s.sm); - - const bool cs_alive = sm.alive("controlsState"); - const auto cs = sm["controlsState"].getControlsState(); - const auto car_state = sm["carState"].getCarState(); - - is_metric = s.scene.is_metric; - - // Handle older routes where vCruiseCluster is not set - float v_cruise = car_state.getVCruiseCluster() == 0.0 ? cs.getVCruiseDEPRECATED() : car_state.getVCruiseCluster(); - setSpeed = cs_alive ? v_cruise : SET_SPEED_NA; - is_cruise_set = setSpeed > 0 && (int)setSpeed != SET_SPEED_NA; - if (is_cruise_set && !is_metric) { - setSpeed *= KM_TO_MILE; - } - - // Handle older routes where vEgoCluster is not set - v_ego_cluster_seen = v_ego_cluster_seen || car_state.getVEgoCluster() != 0.0; - float v_ego = v_ego_cluster_seen ? car_state.getVEgoCluster() : car_state.getVEgo(); - speed = cs_alive ? std::max(0.0, v_ego) : 0.0; - speed *= is_metric ? MS_TO_KPH : MS_TO_MPH; - - speedUnit = is_metric ? tr("km/h") : tr("mph"); - status = s.status; - - // update engageability/experimental mode button - experimental_btn->updateState(s); - - // update DM icon - dmon.updateState(s); -} - -void AnnotatedCameraWidget::drawHud(QPainter &p) { - p.save(); - - // Header gradient - QLinearGradient bg(0, UI_HEADER_HEIGHT - (UI_HEADER_HEIGHT / 2.5), 0, UI_HEADER_HEIGHT); - bg.setColorAt(0, QColor::fromRgbF(0, 0, 0, 0.45)); - bg.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0)); - p.fillRect(0, 0, width(), UI_HEADER_HEIGHT, bg); - - QString speedStr = QString::number(std::nearbyint(speed)); - QString setSpeedStr = is_cruise_set ? QString::number(std::nearbyint(setSpeed)) : "–"; - - // Draw outer box + border to contain set speed - const QSize default_size = {172, 204}; - QSize set_speed_size = default_size; - if (is_metric) set_speed_size.rwidth() = 200; - - QRect set_speed_rect(QPoint(60 + (default_size.width() - set_speed_size.width()) / 2, 45), set_speed_size); - p.setPen(QPen(whiteColor(75), 6)); - p.setBrush(blackColor(166)); - p.drawRoundedRect(set_speed_rect, 32, 32); - - // Draw MAX - QColor max_color = QColor(0x80, 0xd8, 0xa6, 0xff); - QColor set_speed_color = whiteColor(); - if (is_cruise_set) { - if (status == STATUS_DISENGAGED) { - max_color = whiteColor(); - } else if (status == STATUS_OVERRIDE) { - max_color = QColor(0x91, 0x9b, 0x95, 0xff); - } - } else { - max_color = QColor(0xa6, 0xa6, 0xa6, 0xff); - set_speed_color = QColor(0x72, 0x72, 0x72, 0xff); - } - p.setFont(InterFont(40, QFont::DemiBold)); - p.setPen(max_color); - p.drawText(set_speed_rect.adjusted(0, 27, 0, 0), Qt::AlignTop | Qt::AlignHCenter, tr("MAX")); - p.setFont(InterFont(90, QFont::Bold)); - p.setPen(set_speed_color); - p.drawText(set_speed_rect.adjusted(0, 77, 0, 0), Qt::AlignTop | Qt::AlignHCenter, setSpeedStr); - - // current speed - p.setFont(InterFont(176, QFont::Bold)); - drawText(p, rect().center().x(), 210, speedStr); - p.setFont(InterFont(66)); - drawText(p, rect().center().x(), 290, speedUnit, 200); - - p.restore(); -} - -void AnnotatedCameraWidget::drawText(QPainter &p, int x, int y, const QString &text, int alpha) { - QRect real_rect = p.fontMetrics().boundingRect(text); - real_rect.moveCenter({x, y - real_rect.height() / 2}); - - p.setPen(QColor(0xff, 0xff, 0xff, alpha)); - p.drawText(real_rect.x(), real_rect.bottom(), text); -} - -void AnnotatedCameraWidget::initializeGL() { - CameraWidget::initializeGL(); - qInfo() << "OpenGL version:" << QString((const char*)glGetString(GL_VERSION)); - qInfo() << "OpenGL vendor:" << QString((const char*)glGetString(GL_VENDOR)); - qInfo() << "OpenGL renderer:" << QString((const char*)glGetString(GL_RENDERER)); - qInfo() << "OpenGL language version:" << QString((const char*)glGetString(GL_SHADING_LANGUAGE_VERSION)); - - prev_draw_t = millis_since_boot(); - setBackgroundColor(bg_colors[STATUS_DISENGAGED]); -} - -void AnnotatedCameraWidget::updateFrameMat() { - CameraWidget::updateFrameMat(); - UIState *s = uiState(); - int w = width(), h = height(); - - s->fb_w = w; - s->fb_h = h; - - // Apply transformation such that video pixel coordinates match video - // 1) Put (0, 0) in the middle of the video - // 2) Apply same scaling as video - // 3) Put (0, 0) in top left corner of video - s->car_space_transform.reset(); - s->car_space_transform.translate(w / 2 - x_offset, h / 2 - y_offset) - .scale(zoom, zoom) - .translate(-intrinsic_matrix.v[2], -intrinsic_matrix.v[5]); -} - -void AnnotatedCameraWidget::drawLaneLines(QPainter &painter, const UIState *s) { - painter.save(); - - const UIScene &scene = s->scene; - SubMaster &sm = *(s->sm); - - // lanelines - for (int i = 0; i < std::size(scene.lane_line_vertices); ++i) { - painter.setBrush(QColor::fromRgbF(1.0, 1.0, 1.0, std::clamp(scene.lane_line_probs[i], 0.0, 0.7))); - painter.drawPolygon(scene.lane_line_vertices[i]); - } - - // road edges - for (int i = 0; i < std::size(scene.road_edge_vertices); ++i) { - painter.setBrush(QColor::fromRgbF(1.0, 0, 0, std::clamp(1.0 - scene.road_edge_stds[i], 0.0, 1.0))); - painter.drawPolygon(scene.road_edge_vertices[i]); - } - - // paint path - QLinearGradient bg(0, height(), 0, 0); - if (sm["selfdriveState"].getSelfdriveState().getExperimentalMode()) { - // The first half of track_vertices are the points for the right side of the path - const auto &acceleration = sm["modelV2"].getModelV2().getAcceleration().getX(); - const int max_len = std::min(scene.track_vertices.length() / 2, acceleration.size()); - - for (int i = 0; i < max_len; ++i) { - // Some points are out of frame - int track_idx = max_len - i - 1; // flip idx to start from bottom right - if (scene.track_vertices[track_idx].y() < 0 || scene.track_vertices[track_idx].y() > height()) continue; - - // Flip so 0 is bottom of frame - float lin_grad_point = (height() - scene.track_vertices[track_idx].y()) / height(); - - // speed up: 120, slow down: 0 - float path_hue = fmax(fmin(60 + acceleration[i] * 35, 120), 0); - // FIXME: painter.drawPolygon can be slow if hue is not rounded - path_hue = int(path_hue * 100 + 0.5) / 100; - - float saturation = fmin(fabs(acceleration[i] * 1.5), 1); - float lightness = util::map_val(saturation, 0.0f, 1.0f, 0.95f, 0.62f); // lighter when grey - float alpha = util::map_val(lin_grad_point, 0.75f / 2.f, 0.75f, 0.4f, 0.0f); // matches previous alpha fade - bg.setColorAt(lin_grad_point, QColor::fromHslF(path_hue / 360., saturation, lightness, alpha)); - - // Skip a point, unless next is last - i += (i + 2) < max_len ? 1 : 0; - } - - } else { - bg.setColorAt(0.0, QColor::fromHslF(148 / 360., 0.94, 0.51, 0.4)); - bg.setColorAt(0.5, QColor::fromHslF(112 / 360., 1.0, 0.68, 0.35)); - bg.setColorAt(1.0, QColor::fromHslF(112 / 360., 1.0, 0.68, 0.0)); - } - - painter.setBrush(bg); - painter.drawPolygon(scene.track_vertices); - - painter.restore(); -} - -void AnnotatedCameraWidget::drawLead(QPainter &painter, const cereal::RadarState::LeadData::Reader &lead_data, const QPointF &vd) { - painter.save(); - - const float speedBuff = 10.; - const float leadBuff = 40.; - const float d_rel = lead_data.getDRel(); - const float v_rel = lead_data.getVRel(); - - float fillAlpha = 0; - if (d_rel < leadBuff) { - fillAlpha = 255 * (1.0 - (d_rel / leadBuff)); - if (v_rel < 0) { - fillAlpha += 255 * (-1 * (v_rel / speedBuff)); - } - fillAlpha = (int)(fmin(fillAlpha, 255)); - } - - float sz = std::clamp((25 * 30) / (d_rel / 3 + 30), 15.0f, 30.0f) * 2.35; - float x = std::clamp((float)vd.x(), 0.f, width() - sz / 2); - float y = std::fmin(height() - sz * .6, (float)vd.y()); - - float g_xo = sz / 5; - float g_yo = sz / 10; - - QPointF glow[] = {{x + (sz * 1.35) + g_xo, y + sz + g_yo}, {x, y - g_yo}, {x - (sz * 1.35) - g_xo, y + sz + g_yo}}; - painter.setBrush(QColor(218, 202, 37, 255)); - painter.drawPolygon(glow, std::size(glow)); - - // chevron - QPointF chevron[] = {{x + (sz * 1.25), y + sz}, {x, y}, {x - (sz * 1.25), y + sz}}; - painter.setBrush(redColor(fillAlpha)); - painter.drawPolygon(chevron, std::size(chevron)); - - painter.restore(); -} - -void AnnotatedCameraWidget::paintGL() { - UIState *s = uiState(); - SubMaster &sm = *(s->sm); - const double start_draw_t = millis_since_boot(); - const cereal::ModelDataV2::Reader &model = sm["modelV2"].getModelV2(); - - // draw camera frame - { - std::lock_guard lk(frame_lock); - - if (frames.empty()) { - if (skip_frame_count > 0) { - skip_frame_count--; - qDebug() << "skipping frame, not ready"; - return; - } - } else { - // skip drawing up to this many frames if we're - // missing camera frames. this smooths out the - // transitions from the narrow and wide cameras - skip_frame_count = 5; - } - - // Wide or narrow cam dependent on speed - bool has_wide_cam = available_streams.count(VISION_STREAM_WIDE_ROAD); - if (has_wide_cam) { - float v_ego = sm["carState"].getCarState().getVEgo(); - if ((v_ego < 10) || available_streams.size() == 1) { - wide_cam_requested = true; - } else if (v_ego > 15) { - wide_cam_requested = false; - } - wide_cam_requested = wide_cam_requested && sm["selfdriveState"].getSelfdriveState().getExperimentalMode(); - // for replay of old routes, never go to widecam - wide_cam_requested = wide_cam_requested && s->scene.calibration_wide_valid; - } - CameraWidget::setStreamType(wide_cam_requested ? VISION_STREAM_WIDE_ROAD : VISION_STREAM_ROAD); - - s->scene.wide_cam = CameraWidget::getStreamType() == VISION_STREAM_WIDE_ROAD; - if (s->scene.calibration_valid) { - auto calib = s->scene.wide_cam ? s->scene.view_from_wide_calib : s->scene.view_from_calib; - CameraWidget::updateCalibration(calib); - } else { - CameraWidget::updateCalibration(DEFAULT_CALIBRATION); - } - CameraWidget::setFrameId(model.getFrameId()); - CameraWidget::paintGL(); - } - - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.setPen(Qt::NoPen); - - if (s->scene.world_objects_visible) { - update_model(s, model); - drawLaneLines(painter, s); - - if (s->scene.longitudinal_control && sm.rcv_frame("radarState") > s->scene.started_frame) { - auto radar_state = sm["radarState"].getRadarState(); - update_leads(s, radar_state, model.getPosition()); - auto lead_one = radar_state.getLeadOne(); - auto lead_two = radar_state.getLeadTwo(); - if (lead_one.getStatus()) { - drawLead(painter, lead_one, s->scene.lead_vertices[0]); - } - if (lead_two.getStatus() && (std::abs(lead_one.getDRel() - lead_two.getDRel()) > 3.0)) { - drawLead(painter, lead_two, s->scene.lead_vertices[1]); - } - } - } - - dmon.draw(painter, rect()); - - drawHud(painter); - - double cur_draw_t = millis_since_boot(); - double dt = cur_draw_t - prev_draw_t; - double fps = fps_filter.update(1. / dt * 1000); - if (fps < 15) { - LOGW("slow frame rate: %.2f fps", fps); - } - prev_draw_t = cur_draw_t; - - // publish debug msg - MessageBuilder msg; - auto m = msg.initEvent().initUiDebug(); - m.setDrawTimeMillis(cur_draw_t - start_draw_t); - pm->send("uiDebug", msg); -} - -void AnnotatedCameraWidget::showEvent(QShowEvent *event) { - CameraWidget::showEvent(event); - - ui_update_params(uiState()); - prev_draw_t = millis_since_boot(); -} diff --git a/selfdrive/ui/qt/onroad/annotated_camera.h b/selfdrive/ui/qt/onroad/annotated_camera.h deleted file mode 100644 index 4a4196b22ce028..00000000000000 --- a/selfdrive/ui/qt/onroad/annotated_camera.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include - -#include "selfdrive/ui/qt/onroad/buttons.h" -#include "selfdrive/ui/qt/onroad/driver_monitoring.h" -#include "selfdrive/ui/qt/widgets/cameraview.h" - -class AnnotatedCameraWidget : public CameraWidget { - Q_OBJECT - -public: - explicit AnnotatedCameraWidget(VisionStreamType type, QWidget* parent = 0); - void updateState(const UIState &s); - -private: - void drawText(QPainter &p, int x, int y, const QString &text, int alpha = 255); - - QVBoxLayout *main_layout; - ExperimentalButton *experimental_btn; - DriverMonitorRenderer dmon; - float speed; - QString speedUnit; - float setSpeed; - bool is_cruise_set = false; - bool is_metric = false; - bool v_ego_cluster_seen = false; - int status = STATUS_DISENGAGED; - std::unique_ptr pm; - - int skip_frame_count = 0; - bool wide_cam_requested = false; - -protected: - void paintGL() override; - void initializeGL() override; - void showEvent(QShowEvent *event) override; - void updateFrameMat() override; - void drawLaneLines(QPainter &painter, const UIState *s); - void drawLead(QPainter &painter, const cereal::RadarState::LeadData::Reader &lead_data, const QPointF &vd); - void drawHud(QPainter &p); - inline QColor redColor(int alpha = 255) { return QColor(201, 34, 49, alpha); } - inline QColor whiteColor(int alpha = 255) { return QColor(255, 255, 255, alpha); } - inline QColor blackColor(int alpha = 255) { return QColor(0, 0, 0, alpha); } - - double prev_draw_t = 0; - FirstOrderFilter fps_filter; -}; diff --git a/selfdrive/ui/qt/onroad/buttons.cc b/selfdrive/ui/qt/onroad/buttons.cc deleted file mode 100644 index 2c2cc672b9aeba..00000000000000 --- a/selfdrive/ui/qt/onroad/buttons.cc +++ /dev/null @@ -1,49 +0,0 @@ -#include "selfdrive/ui/qt/onroad/buttons.h" - -#include - -#include "selfdrive/ui/qt/util.h" - -void drawIcon(QPainter &p, const QPoint ¢er, const QPixmap &img, const QBrush &bg, float opacity) { - p.setRenderHint(QPainter::Antialiasing); - p.setOpacity(1.0); // bg dictates opacity of ellipse - p.setPen(Qt::NoPen); - p.setBrush(bg); - p.drawEllipse(center, btn_size / 2, btn_size / 2); - p.setOpacity(opacity); - p.drawPixmap(center - QPoint(img.width() / 2, img.height() / 2), img); - p.setOpacity(1.0); -} - -// ExperimentalButton -ExperimentalButton::ExperimentalButton(QWidget *parent) : experimental_mode(false), engageable(false), QPushButton(parent) { - setFixedSize(btn_size, btn_size); - - engage_img = loadPixmap("../assets/img_chffr_wheel.png", {img_size, img_size}); - experimental_img = loadPixmap("../assets/img_experimental.svg", {img_size, img_size}); - QObject::connect(this, &QPushButton::clicked, this, &ExperimentalButton::changeMode); -} - -void ExperimentalButton::changeMode() { - const auto cp = (*uiState()->sm)["carParams"].getCarParams(); - bool can_change = hasLongitudinalControl(cp) && params.getBool("ExperimentalModeConfirmed"); - if (can_change) { - params.putBool("ExperimentalMode", !experimental_mode); - } -} - -void ExperimentalButton::updateState(const UIState &s) { - const auto cs = (*s.sm)["selfdriveState"].getSelfdriveState(); - bool eng = cs.getEngageable() || cs.getEnabled(); - if ((cs.getExperimentalMode() != experimental_mode) || (eng != engageable)) { - engageable = eng; - experimental_mode = cs.getExperimentalMode(); - update(); - } -} - -void ExperimentalButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - QPixmap img = experimental_mode ? experimental_img : engage_img; - drawIcon(p, QPoint(btn_size / 2, btn_size / 2), img, QColor(0, 0, 0, 166), (isDown() || !engageable) ? 0.6 : 1.0); -} diff --git a/selfdrive/ui/qt/onroad/buttons.h b/selfdrive/ui/qt/onroad/buttons.h deleted file mode 100644 index 9c91bc3c7b649f..00000000000000 --- a/selfdrive/ui/qt/onroad/buttons.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/ui.h" - -const int btn_size = 192; -const int img_size = (btn_size / 4) * 3; - -class ExperimentalButton : public QPushButton { - Q_OBJECT - -public: - explicit ExperimentalButton(QWidget *parent = 0); - void updateState(const UIState &s); - -private: - void paintEvent(QPaintEvent *event) override; - void changeMode(); - - Params params; - QPixmap engage_img; - QPixmap experimental_img; - bool experimental_mode; - bool engageable; -}; - -void drawIcon(QPainter &p, const QPoint ¢er, const QPixmap &img, const QBrush &bg, float opacity); diff --git a/selfdrive/ui/qt/onroad/driver_monitoring.cc b/selfdrive/ui/qt/onroad/driver_monitoring.cc deleted file mode 100644 index afd003cf8f412a..00000000000000 --- a/selfdrive/ui/qt/onroad/driver_monitoring.cc +++ /dev/null @@ -1,107 +0,0 @@ -#include "selfdrive/ui/qt/onroad/driver_monitoring.h" -#include -#include - -#include "selfdrive/ui/qt/onroad/buttons.h" -#include "selfdrive/ui/qt/util.h" - -// Default 3D coordinates for face keypoints -static constexpr vec3 DEFAULT_FACE_KPTS_3D[] = { - {-5.98, -51.20, 8.00}, {-17.64, -49.14, 8.00}, {-23.81, -46.40, 8.00}, {-29.98, -40.91, 8.00}, {-32.04, -37.49, 8.00}, - {-34.10, -32.00, 8.00}, {-36.16, -21.03, 8.00}, {-36.16, 6.40, 8.00}, {-35.47, 10.51, 8.00}, {-32.73, 19.43, 8.00}, - {-29.30, 26.29, 8.00}, {-24.50, 33.83, 8.00}, {-19.01, 41.37, 8.00}, {-14.21, 46.17, 8.00}, {-12.16, 47.54, 8.00}, - {-4.61, 49.60, 8.00}, {4.99, 49.60, 8.00}, {12.53, 47.54, 8.00}, {14.59, 46.17, 8.00}, {19.39, 41.37, 8.00}, - {24.87, 33.83, 8.00}, {29.67, 26.29, 8.00}, {33.10, 19.43, 8.00}, {35.84, 10.51, 8.00}, {36.53, 6.40, 8.00}, - {36.53, -21.03, 8.00}, {34.47, -32.00, 8.00}, {32.42, -37.49, 8.00}, {30.36, -40.91, 8.00}, {24.19, -46.40, 8.00}, - {18.02, -49.14, 8.00}, {6.36, -51.20, 8.00}, {-5.98, -51.20, 8.00}, -}; - -// Colors used for drawing based on monitoring state -static const QColor DMON_ENGAGED_COLOR = QColor::fromRgbF(0.1, 0.945, 0.26); -static const QColor DMON_DISENGAGED_COLOR = QColor::fromRgbF(0.545, 0.545, 0.545); - -DriverMonitorRenderer::DriverMonitorRenderer() : face_kpts_draw(std::size(DEFAULT_FACE_KPTS_3D)) { - dm_img = loadPixmap("../assets/img_driver_face.png", {img_size + 5, img_size + 5}); -} - -void DriverMonitorRenderer::updateState(const UIState &s) { - auto &sm = *(s.sm); - is_visible = sm["selfdriveState"].getSelfdriveState().getAlertSize() == cereal::SelfdriveState::AlertSize::NONE && - sm.rcv_frame("driverStateV2") > s.scene.started_frame; - if (!is_visible) return; - - auto dm_state = sm["driverMonitoringState"].getDriverMonitoringState(); - is_active = dm_state.getIsActiveMode(); - is_rhd = dm_state.getIsRHD(); - dm_fade_state = std::clamp(dm_fade_state + 0.2f * (0.5f - is_active), 0.0f, 1.0f); - - const auto &driverstate = sm["driverStateV2"].getDriverStateV2(); - const auto driver_orient = is_rhd ? driverstate.getRightDriverData().getFaceOrientation() : driverstate.getLeftDriverData().getFaceOrientation(); - - for (int i = 0; i < 3; ++i) { - float v_this = (i == 0 ? (driver_orient[i] < 0 ? 0.7 : 0.9) : 0.4) * driver_orient[i]; - driver_pose_diff[i] = std::abs(driver_pose_vals[i] - v_this); - driver_pose_vals[i] = 0.8f * v_this + (1 - 0.8) * driver_pose_vals[i]; - driver_pose_sins[i] = std::sin(driver_pose_vals[i] * (1.0f - dm_fade_state)); - driver_pose_coss[i] = std::cos(driver_pose_vals[i] * (1.0f - dm_fade_state)); - } - - auto [sin_y, sin_x, sin_z] = driver_pose_sins; - auto [cos_y, cos_x, cos_z] = driver_pose_coss; - - // Rotation matrix for transforming face keypoints based on driver's head orientation - const mat3 r_xyz = {{ - cos_x * cos_z, cos_x * sin_z, -sin_x, - -sin_y * sin_x * cos_z - cos_y * sin_z, -sin_y * sin_x * sin_z + cos_y * cos_z, -sin_y * cos_x, - cos_y * sin_x * cos_z - sin_y * sin_z, cos_y * sin_x * sin_z + sin_y * cos_z, cos_y * cos_x, - }}; - - // Transform vertices - for (int i = 0; i < face_kpts_draw.size(); ++i) { - vec3 kpt = matvecmul3(r_xyz, DEFAULT_FACE_KPTS_3D[i]); - face_kpts_draw[i] = {{kpt.v[0], kpt.v[1], kpt.v[2] * (1.0f - dm_fade_state) + 8 * dm_fade_state}}; - } -} - -void DriverMonitorRenderer::draw(QPainter &painter, const QRect &surface_rect) { - if (!is_visible) return; - - painter.save(); - - int offset = UI_BORDER_SIZE + btn_size / 2; - float x = is_rhd ? surface_rect.width() - offset : offset; - float y = surface_rect.height() - offset; - float opacity = is_active ? 0.65f : 0.2f; - - drawIcon(painter, QPoint(x, y), dm_img, QColor(0, 0, 0, 70), opacity); - - QPointF keypoints[std::size(DEFAULT_FACE_KPTS_3D)]; - for (int i = 0; i < std::size(keypoints); ++i) { - const auto &v = face_kpts_draw[i].v; - float kp = (v[2] - 8) / 120.0f + 1.0f; - keypoints[i] = QPointF(v[0] * kp + x, v[1] * kp + y); - } - - painter.setPen(QPen(QColor::fromRgbF(1.0, 1.0, 1.0, opacity), 5.2, Qt::SolidLine, Qt::RoundCap)); - painter.drawPolyline(keypoints, std::size(keypoints)); - - // tracking arcs - const int arc_l = 133; - const float arc_t_default = 6.7f; - const float arc_t_extend = 12.0f; - QColor arc_color = uiState()->engaged() ? DMON_ENGAGED_COLOR : DMON_DISENGAGED_COLOR; - arc_color.setAlphaF(0.4 * (1.0f - dm_fade_state)); - - float delta_x = -driver_pose_sins[1] * arc_l / 2.0f; - float delta_y = -driver_pose_sins[0] * arc_l / 2.0f; - - // Draw horizontal tracking arc - painter.setPen(QPen(arc_color, arc_t_default + arc_t_extend * std::min(1.0, driver_pose_diff[1] * 5.0), Qt::SolidLine, Qt::RoundCap)); - painter.drawArc(QRectF(std::min(x + delta_x, x), y - arc_l / 2, std::abs(delta_x), arc_l), (driver_pose_sins[1] > 0 ? 90 : -90) * 16, 180 * 16); - - // Draw vertical tracking arc - painter.setPen(QPen(arc_color, arc_t_default + arc_t_extend * std::min(1.0, driver_pose_diff[0] * 5.0), Qt::SolidLine, Qt::RoundCap)); - painter.drawArc(QRectF(x - arc_l / 2, std::min(y + delta_y, y), arc_l, std::abs(delta_y)), (driver_pose_sins[0] > 0 ? 0 : 180) * 16, 180 * 16); - - painter.restore(); -} diff --git a/selfdrive/ui/qt/onroad/driver_monitoring.h b/selfdrive/ui/qt/onroad/driver_monitoring.h deleted file mode 100644 index 47db151c81b136..00000000000000 --- a/selfdrive/ui/qt/onroad/driver_monitoring.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -#include -#include "selfdrive/ui/ui.h" - -class DriverMonitorRenderer { -public: - DriverMonitorRenderer(); - void updateState(const UIState &s); - void draw(QPainter &painter, const QRect &surface_rect); - -private: - float driver_pose_vals[3] = {}; - float driver_pose_diff[3] = {}; - float driver_pose_sins[3] = {}; - float driver_pose_coss[3] = {}; - bool is_visible = false; - bool is_active = false; - bool is_rhd = false; - float dm_fade_state = 1.0; - QPixmap dm_img; - std::vector face_kpts_draw; -}; diff --git a/selfdrive/ui/qt/onroad/onroad_home.cc b/selfdrive/ui/qt/onroad/onroad_home.cc deleted file mode 100644 index 823e14bf3c58a4..00000000000000 --- a/selfdrive/ui/qt/onroad/onroad_home.cc +++ /dev/null @@ -1,65 +0,0 @@ -#include "selfdrive/ui/qt/onroad/onroad_home.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -OnroadWindow::OnroadWindow(QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(UI_BORDER_SIZE); - QStackedLayout *stacked_layout = new QStackedLayout; - stacked_layout->setStackingMode(QStackedLayout::StackAll); - main_layout->addLayout(stacked_layout); - - nvg = new AnnotatedCameraWidget(VISION_STREAM_ROAD, this); - - QWidget * split_wrapper = new QWidget; - split = new QHBoxLayout(split_wrapper); - split->setContentsMargins(0, 0, 0, 0); - split->setSpacing(0); - split->addWidget(nvg); - - if (getenv("DUAL_CAMERA_VIEW")) { - CameraWidget *arCam = new CameraWidget("camerad", VISION_STREAM_ROAD, true, this); - split->insertWidget(0, arCam); - } - - stacked_layout->addWidget(split_wrapper); - - alerts = new OnroadAlerts(this); - alerts->setAttribute(Qt::WA_TransparentForMouseEvents, true); - stacked_layout->addWidget(alerts); - - // setup stacking order - alerts->raise(); - - setAttribute(Qt::WA_OpaquePaintEvent); - QObject::connect(uiState(), &UIState::uiUpdate, this, &OnroadWindow::updateState); - QObject::connect(uiState(), &UIState::offroadTransition, this, &OnroadWindow::offroadTransition); -} - -void OnroadWindow::updateState(const UIState &s) { - if (!s.scene.started) { - return; - } - - alerts->updateState(s); - nvg->updateState(s); - - QColor bgColor = bg_colors[s.status]; - if (bg != bgColor) { - // repaint border - bg = bgColor; - update(); - } -} - -void OnroadWindow::offroadTransition(bool offroad) { - alerts->clear(); -} - -void OnroadWindow::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.fillRect(rect(), QColor(bg.red(), bg.green(), bg.blue(), 255)); -} diff --git a/selfdrive/ui/qt/onroad/onroad_home.h b/selfdrive/ui/qt/onroad/onroad_home.h deleted file mode 100644 index c321d2d44f479c..00000000000000 --- a/selfdrive/ui/qt/onroad/onroad_home.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/onroad/alerts.h" -#include "selfdrive/ui/qt/onroad/annotated_camera.h" - -class OnroadWindow : public QWidget { - Q_OBJECT - -public: - OnroadWindow(QWidget* parent = 0); - -private: - void paintEvent(QPaintEvent *event); - OnroadAlerts *alerts; - AnnotatedCameraWidget *nvg; - QColor bg = bg_colors[STATUS_DISENGAGED]; - QHBoxLayout* split; - -private slots: - void offroadTransition(bool offroad); - void updateState(const UIState &s); -}; diff --git a/selfdrive/ui/qt/python_helpers.py b/selfdrive/ui/qt/python_helpers.py deleted file mode 100644 index 88c36290d92b71..00000000000000 --- a/selfdrive/ui/qt/python_helpers.py +++ /dev/null @@ -1,20 +0,0 @@ -import os -from cffi import FFI - -import sip - -from openpilot.common.ffi_wrapper import suffix -from openpilot.common.basedir import BASEDIR - - -def get_ffi(): - lib = os.path.join(BASEDIR, "selfdrive", "ui", "qt", "libpython_helpers" + suffix()) - - ffi = FFI() - ffi.cdef("void set_main_window(void *w);") - return ffi, ffi.dlopen(lib) - - -def set_main_window(widget): - ffi, lib = get_ffi() - lib.set_main_window(ffi.cast('void*', sip.unwrapinstance(widget))) diff --git a/selfdrive/ui/qt/qt_window.cc b/selfdrive/ui/qt/qt_window.cc deleted file mode 100644 index 8d3d7cf72e400f..00000000000000 --- a/selfdrive/ui/qt/qt_window.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include "selfdrive/ui/qt/qt_window.h" - -void setMainWindow(QWidget *w) { - const float scale = util::getenv("SCALE", 1.0f); - const QSize sz = QGuiApplication::primaryScreen()->size(); - - if (Hardware::PC() && scale == 1.0 && !(sz - DEVICE_SCREEN_SIZE).isValid()) { - w->setMinimumSize(QSize(640, 480)); // allow resize smaller than fullscreen - w->setMaximumSize(DEVICE_SCREEN_SIZE); - w->resize(sz); - } else { - w->setFixedSize(DEVICE_SCREEN_SIZE * scale); - } - w->show(); - -#ifdef QCOM2 - QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface(); - wl_surface *s = reinterpret_cast(native->nativeResourceForWindow("surface", w->windowHandle())); - wl_surface_set_buffer_transform(s, WL_OUTPUT_TRANSFORM_270); - wl_surface_commit(s); - - w->setWindowState(Qt::WindowFullScreen); - w->setVisible(true); - - // ensure we have a valid eglDisplay, otherwise the ui will silently fail - void *egl = native->nativeResourceForWindow("egldisplay", w->windowHandle()); - assert(egl != nullptr); -#endif -} - - -extern "C" { - void set_main_window(void *w) { - setMainWindow((QWidget*)w); - } -} diff --git a/selfdrive/ui/qt/qt_window.h b/selfdrive/ui/qt/qt_window.h deleted file mode 100644 index 6f16e00957485c..00000000000000 --- a/selfdrive/ui/qt/qt_window.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -#ifdef QCOM2 -#include -#include -#include -#endif - -#include "system/hardware/hw.h" - -const QString ASSET_PATH = ":/"; -const QSize DEVICE_SCREEN_SIZE = {2160, 1080}; - -void setMainWindow(QWidget *w); diff --git a/selfdrive/ui/qt/request_repeater.cc b/selfdrive/ui/qt/request_repeater.cc deleted file mode 100644 index 7aa731898c978f..00000000000000 --- a/selfdrive/ui/qt/request_repeater.cc +++ /dev/null @@ -1,27 +0,0 @@ -#include "selfdrive/ui/qt/request_repeater.h" - -RequestRepeater::RequestRepeater(QObject *parent, const QString &requestURL, const QString &cacheKey, - int period, bool while_onroad) : HttpRequest(parent) { - timer = new QTimer(this); - timer->setTimerType(Qt::VeryCoarseTimer); - QObject::connect(timer, &QTimer::timeout, [=]() { - if ((!uiState()->scene.started || while_onroad) && device()->isAwake() && !active()) { - sendRequest(requestURL); - } - }); - - timer->start(period * 1000); - - if (!cacheKey.isEmpty()) { - prevResp = QString::fromStdString(params.get(cacheKey.toStdString())); - if (!prevResp.isEmpty()) { - QTimer::singleShot(500, [=]() { emit requestDone(prevResp, true, QNetworkReply::NoError); }); - } - QObject::connect(this, &HttpRequest::requestDone, [=](const QString &resp, bool success) { - if (success && resp != prevResp) { - params.put(cacheKey.toStdString(), resp.toStdString()); - prevResp = resp; - } - }); - } -} diff --git a/selfdrive/ui/qt/request_repeater.h b/selfdrive/ui/qt/request_repeater.h deleted file mode 100644 index c0e27582736138..00000000000000 --- a/selfdrive/ui/qt/request_repeater.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include "common/util.h" -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/ui.h" - -class RequestRepeater : public HttpRequest { -public: - RequestRepeater(QObject *parent, const QString &requestURL, const QString &cacheKey = "", int period = 0, bool while_onroad=false); - -private: - Params params; - QTimer *timer; - QString prevResp; -}; diff --git a/selfdrive/ui/qt/setup/reset.cc b/selfdrive/ui/qt/setup/reset.cc deleted file mode 100644 index c9e0525784aa7a..00000000000000 --- a/selfdrive/ui/qt/setup/reset.cc +++ /dev/null @@ -1,134 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/setup/reset.h" - -#define NVME "/dev/nvme0n1" -#define USERDATA "/dev/disk/by-partlabel/userdata" - -void Reset::doErase() { - // best effort to wipe nvme - std::system("sudo umount " NVME); - std::system("yes | sudo mkfs.ext4 " NVME); - - int rm = std::system("sudo rm -rf /data/*"); - std::system("sudo umount " USERDATA); - int fmt = std::system("yes | sudo mkfs.ext4 " USERDATA); - - if (rm == 0 || fmt == 0) { - std::system("sudo reboot"); - } - body->setText(tr("Reset failed. Reboot to try again.")); - rebootBtn->show(); -} - -void Reset::startReset() { - body->setText(tr("Resetting device...\nThis may take up to a minute.")); - rejectBtn->hide(); - rebootBtn->hide(); - confirmBtn->hide(); -#ifdef __aarch64__ - QTimer::singleShot(100, this, &Reset::doErase); -#endif -} - -void Reset::confirm() { - const QString confirm_txt = tr("Are you sure you want to reset your device?"); - if (body->text() != confirm_txt) { - body->setText(confirm_txt); - } else { - startReset(); - } -} - -Reset::Reset(ResetMode mode, QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(45, 220, 45, 45); - main_layout->setSpacing(0); - - QLabel *title = new QLabel(tr("System Reset")); - title->setStyleSheet("font-size: 90px; font-weight: 600;"); - main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - main_layout->addSpacing(60); - - body = new QLabel(tr("System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot.")); - body->setWordWrap(true); - body->setStyleSheet("font-size: 80px; font-weight: light;"); - main_layout->addWidget(body, 1, Qt::AlignTop | Qt::AlignLeft); - - QHBoxLayout *blayout = new QHBoxLayout(); - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - rejectBtn = new QPushButton(tr("Cancel")); - blayout->addWidget(rejectBtn); - QObject::connect(rejectBtn, &QPushButton::clicked, QCoreApplication::instance(), &QCoreApplication::quit); - - rebootBtn = new QPushButton(tr("Reboot")); - blayout->addWidget(rebootBtn); -#ifdef __aarch64__ - QObject::connect(rebootBtn, &QPushButton::clicked, [=]{ - std::system("sudo reboot"); - }); -#endif - - confirmBtn = new QPushButton(tr("Confirm")); - confirmBtn->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - blayout->addWidget(confirmBtn); - QObject::connect(confirmBtn, &QPushButton::clicked, this, &Reset::confirm); - - bool recover = mode == ResetMode::RECOVER; - rejectBtn->setVisible(!recover); - rebootBtn->setVisible(recover); - if (recover) { - body->setText(tr("Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device.")); - } - - setStyleSheet(R"( - * { - font-family: Inter; - color: white; - background-color: black; - } - QLabel { - margin-left: 140; - } - QPushButton { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #333333; - } - QPushButton:pressed { - background-color: #444444; - } - )"); -} - -int main(int argc, char *argv[]) { - ResetMode mode = ResetMode::USER_RESET; - if (argc > 1) { - if (strcmp(argv[1], "--recover") == 0) { - mode = ResetMode::RECOVER; - } - } - - QApplication a(argc, argv); - Reset reset(mode); - setMainWindow(&reset); - return a.exec(); -} diff --git a/selfdrive/ui/qt/setup/reset.h b/selfdrive/ui/qt/setup/reset.h deleted file mode 100644 index 8bf368e3e8af4d..00000000000000 --- a/selfdrive/ui/qt/setup/reset.h +++ /dev/null @@ -1,26 +0,0 @@ -#include -#include -#include - -enum ResetMode { - USER_RESET, // user initiated a factory reset from openpilot - RECOVER, // userdata is corrupt for some reason, give a chance to recover -}; - -class Reset : public QWidget { - Q_OBJECT - -public: - explicit Reset(ResetMode mode, QWidget *parent = 0); - -private: - QLabel *body; - QPushButton *rejectBtn; - QPushButton *rebootBtn; - QPushButton *confirmBtn; - void doErase(); - void startReset(); - -private slots: - void confirm(); -}; diff --git a/selfdrive/ui/qt/setup/setup.cc b/selfdrive/ui/qt/setup/setup.cc deleted file mode 100644 index aff9b015b3a40d..00000000000000 --- a/selfdrive/ui/qt/setup/setup.cc +++ /dev/null @@ -1,488 +0,0 @@ -#include "selfdrive/ui/qt/setup/setup.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/network/networking.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/input.h" - -const std::string USER_AGENT = "AGNOSSetup-"; -const QString OPENPILOT_URL = "https://openpilot.comma.ai"; - -bool is_elf(char *fname) { - FILE *fp = fopen(fname, "rb"); - if (fp == NULL) { - return false; - } - char buf[4]; - size_t n = fread(buf, 1, 4, fp); - fclose(fp); - return n == 4 && buf[0] == 0x7f && buf[1] == 'E' && buf[2] == 'L' && buf[3] == 'F'; -} - -void Setup::download(QString url) { - // autocomplete incomplete urls - if (QRegularExpression("^([^/.]+)/([^/]+)$").match(url).hasMatch()) { - url.prepend("https://installer.comma.ai/"); - } - - CURL *curl = curl_easy_init(); - if (!curl) { - emit finished(url, tr("Something went wrong. Reboot the device.")); - return; - } - - auto version = util::read_file("/VERSION"); - - struct curl_slist *list = NULL; - list = curl_slist_append(list, ("X-openpilot-serial: " + Hardware::get_serial()).c_str()); - - char tmpfile[] = "/tmp/installer_XXXXXX"; - FILE *fp = fdopen(mkstemp(tmpfile), "wb"); - - curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str()); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); - curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); - curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); - curl_easy_setopt(curl, CURLOPT_USERAGENT, (USER_AGENT + version).c_str()); - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); - curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L); - - int ret = curl_easy_perform(curl); - long res_status = 0; - curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &res_status); - - if (ret != CURLE_OK || res_status != 200) { - emit finished(url, tr("Ensure the entered URL is valid, and the device’s internet connection is good.")); - } else if (!is_elf(tmpfile)) { - emit finished(url, tr("No custom software found at this URL.")); - } else { - rename(tmpfile, "/tmp/installer"); - - FILE *fp_url = fopen("/tmp/installer_url", "w"); - fprintf(fp_url, "%s", url.toStdString().c_str()); - fclose(fp_url); - - emit finished(url); - } - - curl_slist_free_all(list); - curl_easy_cleanup(curl); - fclose(fp); -} - -QWidget * Setup::low_voltage() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 0, 55, 55); - main_layout->setSpacing(0); - - // inner text layout: warning icon, title, and body - QVBoxLayout *inner_layout = new QVBoxLayout(); - inner_layout->setContentsMargins(110, 144, 365, 0); - main_layout->addLayout(inner_layout); - - QLabel *triangle = new QLabel(); - triangle->setPixmap(QPixmap(ASSET_PATH + "offroad/icon_warning.png")); - inner_layout->addWidget(triangle, 0, Qt::AlignTop | Qt::AlignLeft); - inner_layout->addSpacing(80); - - QLabel *title = new QLabel(tr("WARNING: Low Voltage")); - title->setStyleSheet("font-size: 90px; font-weight: 500; color: #FF594F;"); - inner_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - inner_layout->addSpacing(25); - - QLabel *body = new QLabel(tr("Power your device in a car with a harness or proceed at your own risk.")); - body->setWordWrap(true); - body->setAlignment(Qt::AlignTop | Qt::AlignLeft); - body->setStyleSheet("font-size: 80px; font-weight: 300;"); - inner_layout->addWidget(body); - - inner_layout->addStretch(); - - // power off + continue buttons - QHBoxLayout *blayout = new QHBoxLayout(); - blayout->setSpacing(50); - main_layout->addLayout(blayout, 0); - - QPushButton *poweroff = new QPushButton(tr("Power off")); - poweroff->setObjectName("navBtn"); - blayout->addWidget(poweroff); - QObject::connect(poweroff, &QPushButton::clicked, this, [=]() { - Hardware::poweroff(); - }); - - QPushButton *cont = new QPushButton(tr("Continue")); - cont->setObjectName("navBtn"); - blayout->addWidget(cont); - QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage); - - return widget; -} - -QWidget * Setup::getting_started() { - QWidget *widget = new QWidget(); - - QHBoxLayout *main_layout = new QHBoxLayout(widget); - main_layout->setMargin(0); - - QVBoxLayout *vlayout = new QVBoxLayout(); - vlayout->setContentsMargins(165, 280, 100, 0); - main_layout->addLayout(vlayout); - - QLabel *title = new QLabel(tr("Getting Started")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - vlayout->addSpacing(90); - QLabel *desc = new QLabel(tr("Before we get on the road, let’s finish installation and cover some details.")); - desc->setWordWrap(true); - desc->setStyleSheet("font-size: 80px; font-weight: 300;"); - vlayout->addWidget(desc, 0, Qt::AlignTop | Qt::AlignLeft); - - vlayout->addStretch(); - - QPushButton *btn = new QPushButton(); - btn->setIcon(QIcon(":/img_continue_triangle.svg")); - btn->setIconSize(QSize(54, 106)); - btn->setFixedSize(310, 1080); - btn->setProperty("primary", true); - btn->setStyleSheet("border: none;"); - main_layout->addWidget(btn, 0, Qt::AlignRight); - QObject::connect(btn, &QPushButton::clicked, this, &Setup::nextPage); - - return widget; -} - -QWidget * Setup::network_setup() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 50, 55, 50); - - // title - QLabel *title = new QLabel(tr("Connect to Wi-Fi")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); - - main_layout->addSpacing(25); - - // wifi widget - Networking *networking = new Networking(this, false); - networking->setStyleSheet("Networking {background-color: #292929; border-radius: 13px;}"); - main_layout->addWidget(networking, 1); - - main_layout->addSpacing(35); - - // back + continue buttons - QHBoxLayout *blayout = new QHBoxLayout; - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - QPushButton *back = new QPushButton(tr("Back")); - back->setObjectName("navBtn"); - QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage); - blayout->addWidget(back); - - QPushButton *cont = new QPushButton(); - cont->setObjectName("navBtn"); - cont->setProperty("primary", true); - cont->setEnabled(false); - QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage); - blayout->addWidget(cont); - - // setup timer for testing internet connection - HttpRequest *request = new HttpRequest(this, false, 2500); - QObject::connect(request, &HttpRequest::requestDone, [=](const QString &, bool success) { - cont->setEnabled(success); - if (success) { - const bool wifi = networking->wifi->currentNetworkType() == NetworkType::WIFI; - cont->setText(wifi ? tr("Continue") : tr("Continue without Wi-Fi")); - } else { - cont->setText(tr("Waiting for internet")); - } - repaint(); - }); - request->sendRequest(OPENPILOT_URL); - QTimer *timer = new QTimer(this); - QObject::connect(timer, &QTimer::timeout, [=]() { - if (!request->active() && cont->isVisible()) { - request->sendRequest(OPENPILOT_URL); - } - }); - timer->start(1000); - - return widget; -} - -QWidget * radio_button(QString title, QButtonGroup *group) { - QPushButton *btn = new QPushButton(title); - btn->setCheckable(true); - group->addButton(btn); - btn->setStyleSheet(R"( - QPushButton { - height: 230; - padding-left: 100px; - padding-right: 100px; - text-align: left; - font-size: 80px; - font-weight: 400; - border-radius: 10px; - background-color: #4F4F4F; - } - QPushButton:checked { - background-color: #465BEA; - } - )"); - - // checkmark icon - QPixmap pix(":/img_circled_check.svg"); - btn->setIcon(pix); - btn->setIconSize(QSize(0, 0)); - btn->setLayoutDirection(Qt::RightToLeft); - QObject::connect(btn, &QPushButton::toggled, [=](bool checked) { - btn->setIconSize(checked ? QSize(104, 104) : QSize(0, 0)); - }); - return btn; -} - -QWidget * Setup::software_selection() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 50, 55, 50); - main_layout->setSpacing(0); - - // title - QLabel *title = new QLabel(tr("Choose Software to Install")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); - - main_layout->addSpacing(50); - - // openpilot + custom radio buttons - QButtonGroup *group = new QButtonGroup(widget); - group->setExclusive(true); - - QWidget *openpilot = radio_button(tr("openpilot"), group); - main_layout->addWidget(openpilot); - - main_layout->addSpacing(30); - - QWidget *custom = radio_button(tr("Custom Software"), group); - main_layout->addWidget(custom); - - main_layout->addStretch(); - - // back + continue buttons - QHBoxLayout *blayout = new QHBoxLayout; - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - QPushButton *back = new QPushButton(tr("Back")); - back->setObjectName("navBtn"); - QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage); - blayout->addWidget(back); - - QPushButton *cont = new QPushButton(tr("Continue")); - cont->setObjectName("navBtn"); - cont->setEnabled(false); - cont->setProperty("primary", true); - blayout->addWidget(cont); - - QObject::connect(cont, &QPushButton::clicked, [=]() { - auto w = currentWidget(); - QTimer::singleShot(0, [=]() { - setCurrentWidget(downloading_widget); - }); - QString url = OPENPILOT_URL; - if (group->checkedButton() != openpilot) { - url = InputDialog::getText(tr("Enter URL"), this, tr("for Custom Software")); - } - if (!url.isEmpty()) { - QTimer::singleShot(1000, this, [=]() { - download(url); - }); - } else { - setCurrentWidget(w); - } - }); - - connect(group, QOverload::of(&QButtonGroup::buttonClicked), [=](QAbstractButton *btn) { - btn->setChecked(true); - cont->setEnabled(true); - }); - - return widget; -} - -QWidget * Setup::downloading() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - QLabel *txt = new QLabel(tr("Downloading...")); - txt->setStyleSheet("font-size: 90px; font-weight: 500;"); - main_layout->addWidget(txt, 0, Qt::AlignCenter); - return widget; -} - -QWidget * Setup::download_failed(QLabel *url, QLabel *body) { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 185, 55, 55); - main_layout->setSpacing(0); - - QLabel *title = new QLabel(tr("Download Failed")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - main_layout->addSpacing(67); - - url->setWordWrap(true); - url->setAlignment(Qt::AlignTop | Qt::AlignLeft); - url->setStyleSheet("font-family: \"JetBrains Mono\"; font-size: 64px; font-weight: 400; margin-right: 100px;"); - main_layout->addWidget(url); - - main_layout->addSpacing(48); - - body->setWordWrap(true); - body->setAlignment(Qt::AlignTop | Qt::AlignLeft); - body->setStyleSheet("font-size: 80px; font-weight: 300; margin-right: 100px;"); - main_layout->addWidget(body); - - main_layout->addStretch(); - - // reboot + start over buttons - QHBoxLayout *blayout = new QHBoxLayout(); - blayout->setSpacing(50); - main_layout->addLayout(blayout, 0); - - QPushButton *reboot = new QPushButton(tr("Reboot device")); - reboot->setObjectName("navBtn"); - blayout->addWidget(reboot); - QObject::connect(reboot, &QPushButton::clicked, this, [=]() { - Hardware::reboot(); - }); - - QPushButton *restart = new QPushButton(tr("Start over")); - restart->setObjectName("navBtn"); - restart->setProperty("primary", true); - blayout->addWidget(restart); - QObject::connect(restart, &QPushButton::clicked, this, [=]() { - setCurrentIndex(1); - }); - - widget->setStyleSheet(R"( - QLabel { - margin-left: 117; - } - )"); - return widget; -} - -void Setup::prevPage() { - setCurrentIndex(currentIndex() - 1); -} - -void Setup::nextPage() { - setCurrentIndex(currentIndex() + 1); -} - -Setup::Setup(QWidget *parent) : QStackedWidget(parent) { - if (std::getenv("MULTILANG")) { - selectLanguage(); - } - - std::stringstream buffer; - buffer << std::ifstream("/sys/class/hwmon/hwmon1/in1_input").rdbuf(); - float voltage = (float)std::atoi(buffer.str().c_str()) / 1000.; - if (voltage < 7) { - addWidget(low_voltage()); - } - - addWidget(getting_started()); - addWidget(network_setup()); - addWidget(software_selection()); - - downloading_widget = downloading(); - addWidget(downloading_widget); - - QLabel *url_label = new QLabel(); - QLabel *body_label = new QLabel(); - failed_widget = download_failed(url_label, body_label); - addWidget(failed_widget); - - QObject::connect(this, &Setup::finished, [=](const QString &url, const QString &error) { - qDebug() << "finished" << url << error; - if (error.isEmpty()) { - // hide setup on success - QTimer::singleShot(3000, this, &QWidget::hide); - } else { - url_label->setText(url); - body_label->setText(error); - setCurrentWidget(failed_widget); - } - }); - - // TODO: revisit pressed bg color - setStyleSheet(R"( - * { - color: white; - font-family: Inter; - } - Setup { - background-color: black; - } - QPushButton#navBtn { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #333333; - } - QPushButton#navBtn:disabled, QPushButton[primary='true']:disabled { - color: #808080; - background-color: #333333; - } - QPushButton#navBtn:pressed { - background-color: #444444; - } - QPushButton[primary='true'], #navBtn[primary='true'] { - background-color: #465BEA; - } - QPushButton[primary='true']:pressed, #navBtn:pressed[primary='true'] { - background-color: #3049F4; - } - )"); -} - -void Setup::selectLanguage() { - QMap langs = getSupportedLanguages(); - QString selection = MultiOptionDialog::getSelection(tr("Select a language"), langs.keys(), "", this); - if (!selection.isEmpty()) { - QString selectedLang = langs[selection]; - Params().put("LanguageSetting", selectedLang.toStdString()); - if (translator.load(":/" + selectedLang)) { - qApp->installTranslator(&translator); - } - } -} - -int main(int argc, char *argv[]) { - QApplication a(argc, argv); - Setup setup; - setMainWindow(&setup); - return a.exec(); -} diff --git a/selfdrive/ui/qt/setup/setup.h b/selfdrive/ui/qt/setup/setup.h deleted file mode 100644 index ee5cc854831cf8..00000000000000 --- a/selfdrive/ui/qt/setup/setup.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -class Setup : public QStackedWidget { - Q_OBJECT - -public: - explicit Setup(QWidget *parent = 0); - -private: - void selectLanguage(); - QWidget *low_voltage(); - QWidget *getting_started(); - QWidget *network_setup(); - QWidget *software_selection(); - QWidget *downloading(); - QWidget *download_failed(QLabel *url, QLabel *body); - - QWidget *failed_widget; - QWidget *downloading_widget; - QTranslator translator; - -signals: - void finished(const QString &url, const QString &error = ""); - -public slots: - void nextPage(); - void prevPage(); - void download(QString url); -}; diff --git a/selfdrive/ui/qt/setup/updater.cc b/selfdrive/ui/qt/setup/updater.cc deleted file mode 100644 index ed47590aa32501..00000000000000 --- a/selfdrive/ui/qt/setup/updater.cc +++ /dev/null @@ -1,186 +0,0 @@ -#include -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/setup/updater.h" -#include "selfdrive/ui/qt/network/networking.h" - -Updater::Updater(const QString &updater_path, const QString &manifest_path, QWidget *parent) - : updater(updater_path), manifest(manifest_path), QStackedWidget(parent) { - - assert(updater.size()); - assert(manifest.size()); - - // initial prompt screen - prompt = new QWidget; - { - QVBoxLayout *layout = new QVBoxLayout(prompt); - layout->setContentsMargins(100, 250, 100, 100); - - QLabel *title = new QLabel(tr("Update Required")); - title->setStyleSheet("font-size: 80px; font-weight: bold;"); - layout->addWidget(title); - - layout->addSpacing(75); - - QLabel *desc = new QLabel(tr("An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB.")); - desc->setWordWrap(true); - desc->setStyleSheet("font-size: 65px;"); - layout->addWidget(desc); - - layout->addStretch(); - - QHBoxLayout *hlayout = new QHBoxLayout; - hlayout->setSpacing(30); - layout->addLayout(hlayout); - - QPushButton *connect = new QPushButton(tr("Connect to Wi-Fi")); - connect->setObjectName("navBtn"); - QObject::connect(connect, &QPushButton::clicked, [=]() { - setCurrentWidget(wifi); - }); - hlayout->addWidget(connect); - - QPushButton *install = new QPushButton(tr("Install")); - install->setObjectName("navBtn"); - install->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - QObject::connect(install, &QPushButton::clicked, this, &Updater::installUpdate); - hlayout->addWidget(install); - } - - // wifi connection screen - wifi = new QWidget; - { - QVBoxLayout *layout = new QVBoxLayout(wifi); - layout->setContentsMargins(100, 100, 100, 100); - - Networking *networking = new Networking(this, false); - networking->setStyleSheet("Networking { background-color: #292929; border-radius: 13px; }"); - layout->addWidget(networking, 1); - - QPushButton *back = new QPushButton(tr("Back")); - back->setObjectName("navBtn"); - back->setStyleSheet("padding-left: 60px; padding-right: 60px;"); - QObject::connect(back, &QPushButton::clicked, [=]() { - setCurrentWidget(prompt); - }); - layout->addWidget(back, 0, Qt::AlignLeft); - } - - // progress screen - progress = new QWidget; - { - QVBoxLayout *layout = new QVBoxLayout(progress); - layout->setContentsMargins(150, 330, 150, 150); - layout->setSpacing(0); - - text = new QLabel(tr("Loading...")); - text->setStyleSheet("font-size: 90px; font-weight: 600;"); - layout->addWidget(text, 0, Qt::AlignTop); - - layout->addSpacing(100); - - bar = new QProgressBar(); - bar->setRange(0, 100); - bar->setTextVisible(false); - bar->setFixedHeight(72); - layout->addWidget(bar, 0, Qt::AlignTop); - - layout->addStretch(); - - reboot = new QPushButton(tr("Reboot")); - reboot->setObjectName("navBtn"); - reboot->setStyleSheet("padding-left: 60px; padding-right: 60px;"); - QObject::connect(reboot, &QPushButton::clicked, [=]() { - Hardware::reboot(); - }); - layout->addWidget(reboot, 0, Qt::AlignLeft); - reboot->hide(); - - layout->addStretch(); - } - - addWidget(prompt); - addWidget(wifi); - addWidget(progress); - - setStyleSheet(R"( - * { - color: white; - outline: none; - font-family: Inter; - } - Updater { - color: white; - background-color: black; - } - QPushButton#navBtn { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #333333; - } - QPushButton#navBtn:pressed { - background-color: #444444; - } - QProgressBar { - border: none; - background-color: #292929; - } - QProgressBar::chunk { - background-color: #364DEF; - } - )"); -} - -void Updater::installUpdate() { - setCurrentWidget(progress); - QObject::connect(&proc, &QProcess::readyReadStandardOutput, this, &Updater::readProgress); - QObject::connect(&proc, QOverload::of(&QProcess::finished), this, &Updater::updateFinished); - proc.setProcessChannelMode(QProcess::ForwardedErrorChannel); - proc.start(updater, {"--swap", manifest}); -} - -void Updater::readProgress() { - auto lines = QString(proc.readAllStandardOutput()); - for (const QString &line : lines.trimmed().split("\n")) { - auto parts = line.split(":"); - if (parts.size() == 2) { - text->setText(parts[0]); - bar->setValue((int)parts[1].toDouble()); - } else { - qDebug() << line; - } - } - update(); -} - -void Updater::updateFinished(int exitCode, QProcess::ExitStatus exitStatus) { - qDebug() << "finished with " << exitCode; - if (exitCode == 0) { - Hardware::reboot(); - } else { - text->setText(tr("Update failed")); - reboot->show(); - } -} - -int main(int argc, char *argv[]) { - initApp(argc, argv); - QApplication a(argc, argv); - Updater updater(argv[1], argv[2]); - setMainWindow(&updater); - a.installEventFilter(&updater); - return a.exec(); -} diff --git a/selfdrive/ui/qt/setup/updater.h b/selfdrive/ui/qt/setup/updater.h deleted file mode 100644 index ce46c0aabd089a..00000000000000 --- a/selfdrive/ui/qt/setup/updater.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -class Updater : public QStackedWidget { - Q_OBJECT - -public: - explicit Updater(const QString &updater_path, const QString &manifest_path, QWidget *parent = 0); - -private slots: - void installUpdate(); - void readProgress(); - void updateFinished(int exitCode, QProcess::ExitStatus exitStatus); - -private: - QProcess proc; - QString updater, manifest; - - QLabel *text; - QProgressBar *bar; - QPushButton *reboot; - QWidget *prompt, *wifi, *progress; -}; diff --git a/selfdrive/ui/qt/sidebar.cc b/selfdrive/ui/qt/sidebar.cc deleted file mode 100644 index 7a93534da9b289..00000000000000 --- a/selfdrive/ui/qt/sidebar.cc +++ /dev/null @@ -1,141 +0,0 @@ -#include "selfdrive/ui/qt/sidebar.h" - -#include - -#include "selfdrive/ui/qt/util.h" - -void Sidebar::drawMetric(QPainter &p, const QPair &label, QColor c, int y) { - const QRect rect = {30, y, 240, 126}; - - p.setPen(Qt::NoPen); - p.setBrush(QBrush(c)); - p.setClipRect(rect.x() + 4, rect.y(), 18, rect.height(), Qt::ClipOperation::ReplaceClip); - p.drawRoundedRect(QRect(rect.x() + 4, rect.y() + 4, 100, 118), 18, 18); - p.setClipping(false); - - QPen pen = QPen(QColor(0xff, 0xff, 0xff, 0x55)); - pen.setWidth(2); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - p.drawRoundedRect(rect, 20, 20); - - p.setPen(QColor(0xff, 0xff, 0xff)); - p.setFont(InterFont(35, QFont::DemiBold)); - p.drawText(rect.adjusted(22, 0, 0, 0), Qt::AlignCenter, label.first + "\n" + label.second); -} - -Sidebar::Sidebar(QWidget *parent) : QFrame(parent), onroad(false), flag_pressed(false), settings_pressed(false) { - home_img = loadPixmap("../assets/images/button_home.png", home_btn.size()); - flag_img = loadPixmap("../assets/images/button_flag.png", home_btn.size()); - settings_img = loadPixmap("../assets/images/button_settings.png", settings_btn.size(), Qt::IgnoreAspectRatio); - - connect(this, &Sidebar::valueChanged, [=] { update(); }); - - setAttribute(Qt::WA_OpaquePaintEvent); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); - setFixedWidth(300); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &Sidebar::updateState); - - pm = std::make_unique(std::vector{"userFlag"}); -} - -void Sidebar::mousePressEvent(QMouseEvent *event) { - if (onroad && home_btn.contains(event->pos())) { - flag_pressed = true; - update(); - } else if (settings_btn.contains(event->pos())) { - settings_pressed = true; - update(); - } -} - -void Sidebar::mouseReleaseEvent(QMouseEvent *event) { - if (flag_pressed || settings_pressed) { - flag_pressed = settings_pressed = false; - update(); - } - if (onroad && home_btn.contains(event->pos())) { - MessageBuilder msg; - msg.initEvent().initUserFlag(); - pm->send("userFlag", msg); - } else if (settings_btn.contains(event->pos())) { - emit openSettings(); - } -} - -void Sidebar::offroadTransition(bool offroad) { - onroad = !offroad; - update(); -} - -void Sidebar::updateState(const UIState &s) { - if (!isVisible()) return; - - auto &sm = *(s.sm); - - auto deviceState = sm["deviceState"].getDeviceState(); - setProperty("netType", network_type[deviceState.getNetworkType()]); - int strength = (int)deviceState.getNetworkStrength(); - setProperty("netStrength", strength > 0 ? strength + 1 : 0); - - ItemStatus connectStatus; - auto last_ping = deviceState.getLastAthenaPingTime(); - if (last_ping == 0) { - connectStatus = ItemStatus{{tr("CONNECT"), tr("OFFLINE")}, warning_color}; - } else { - connectStatus = nanos_since_boot() - last_ping < 80e9 - ? ItemStatus{{tr("CONNECT"), tr("ONLINE")}, good_color} - : ItemStatus{{tr("CONNECT"), tr("ERROR")}, danger_color}; - } - setProperty("connectStatus", QVariant::fromValue(connectStatus)); - - ItemStatus tempStatus = {{tr("TEMP"), tr("HIGH")}, danger_color}; - auto ts = deviceState.getThermalStatus(); - if (ts == cereal::DeviceState::ThermalStatus::GREEN) { - tempStatus = {{tr("TEMP"), tr("GOOD")}, good_color}; - } else if (ts == cereal::DeviceState::ThermalStatus::YELLOW) { - tempStatus = {{tr("TEMP"), tr("OK")}, warning_color}; - } - setProperty("tempStatus", QVariant::fromValue(tempStatus)); - - ItemStatus pandaStatus = {{tr("VEHICLE"), tr("ONLINE")}, good_color}; - if (s.scene.pandaType == cereal::PandaState::PandaType::UNKNOWN) { - pandaStatus = {{tr("NO"), tr("PANDA")}, danger_color}; - } - setProperty("pandaStatus", QVariant::fromValue(pandaStatus)); -} - -void Sidebar::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing); - - p.fillRect(rect(), QColor(57, 57, 57)); - - // buttons - p.setOpacity(settings_pressed ? 0.65 : 1.0); - p.drawPixmap(settings_btn.x(), settings_btn.y(), settings_img); - p.setOpacity(onroad && flag_pressed ? 0.65 : 1.0); - p.drawPixmap(home_btn.x(), home_btn.y(), onroad ? flag_img : home_img); - p.setOpacity(1.0); - - // network - int x = 58; - const QColor gray(0x54, 0x54, 0x54); - for (int i = 0; i < 5; ++i) { - p.setBrush(i < net_strength ? Qt::white : gray); - p.drawEllipse(x, 196, 27, 27); - x += 37; - } - - p.setFont(InterFont(35)); - p.setPen(QColor(0xff, 0xff, 0xff)); - const QRect r = QRect(50, 247, 100, 50); - p.drawText(r, Qt::AlignCenter, net_type); - - // metrics - drawMetric(p, temp_status.first, temp_status.second, 338); - drawMetric(p, panda_status.first, panda_status.second, 496); - drawMetric(p, connect_status.first, connect_status.second, 654); -} diff --git a/selfdrive/ui/qt/sidebar.h b/selfdrive/ui/qt/sidebar.h deleted file mode 100644 index f627aac810ec3d..00000000000000 --- a/selfdrive/ui/qt/sidebar.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -#include - -#include -#include - -#include "selfdrive/ui/ui.h" - -typedef QPair, QColor> ItemStatus; -Q_DECLARE_METATYPE(ItemStatus); - -class Sidebar : public QFrame { - Q_OBJECT - Q_PROPERTY(ItemStatus connectStatus MEMBER connect_status NOTIFY valueChanged); - Q_PROPERTY(ItemStatus pandaStatus MEMBER panda_status NOTIFY valueChanged); - Q_PROPERTY(ItemStatus tempStatus MEMBER temp_status NOTIFY valueChanged); - Q_PROPERTY(QString netType MEMBER net_type NOTIFY valueChanged); - Q_PROPERTY(int netStrength MEMBER net_strength NOTIFY valueChanged); - -public: - explicit Sidebar(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - void valueChanged(); - -public slots: - void offroadTransition(bool offroad); - void updateState(const UIState &s); - -protected: - void paintEvent(QPaintEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void drawMetric(QPainter &p, const QPair &label, QColor c, int y); - - QPixmap home_img, flag_img, settings_img; - bool onroad, flag_pressed, settings_pressed; - const QMap network_type = { - {cereal::DeviceState::NetworkType::NONE, tr("--")}, - {cereal::DeviceState::NetworkType::WIFI, tr("Wi-Fi")}, - {cereal::DeviceState::NetworkType::ETHERNET, tr("ETH")}, - {cereal::DeviceState::NetworkType::CELL2_G, tr("2G")}, - {cereal::DeviceState::NetworkType::CELL3_G, tr("3G")}, - {cereal::DeviceState::NetworkType::CELL4_G, tr("LTE")}, - {cereal::DeviceState::NetworkType::CELL5_G, tr("5G")} - }; - - const QRect home_btn = QRect(60, 860, 180, 180); - const QRect settings_btn = QRect(50, 35, 200, 117); - const QColor good_color = QColor(255, 255, 255); - const QColor warning_color = QColor(218, 202, 37); - const QColor danger_color = QColor(201, 34, 49); - - ItemStatus connect_status, panda_status, temp_status; - QString net_type; - int net_strength = 0; - -private: - std::unique_ptr pm; -}; diff --git a/selfdrive/ui/qt/spinner.cc b/selfdrive/ui/qt/spinner.cc deleted file mode 100644 index 2404efa668408b..00000000000000 --- a/selfdrive/ui/qt/spinner.cc +++ /dev/null @@ -1,120 +0,0 @@ -#include "selfdrive/ui/qt/spinner.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/util.h" - -TrackWidget::TrackWidget(QWidget *parent) : QWidget(parent) { - setAttribute(Qt::WA_OpaquePaintEvent); - setFixedSize(spinner_size); - - // pre-compute all the track imgs. make this a gif instead? - QPixmap comma_img = loadPixmap("../assets/img_spinner_comma.png", spinner_size); - QPixmap track_img = loadPixmap("../assets/img_spinner_track.png", spinner_size); - - QTransform transform(1, 0, 0, 1, width() / 2, height() / 2); - QPixmap pm(spinner_size); - QPainter p(&pm); - p.setRenderHint(QPainter::SmoothPixmapTransform); - for (int i = 0; i < track_imgs.size(); ++i) { - p.resetTransform(); - p.fillRect(0, 0, spinner_size.width(), spinner_size.height(), Qt::black); - p.drawPixmap(0, 0, comma_img); - p.setTransform(transform.rotate(360 / spinner_fps)); - p.drawPixmap(-width() / 2, -height() / 2, track_img); - track_imgs[i] = pm.copy(); - } - - m_anim.setDuration(1000); - m_anim.setStartValue(0); - m_anim.setEndValue(int(track_imgs.size() -1)); - m_anim.setLoopCount(-1); - m_anim.start(); - connect(&m_anim, SIGNAL(valueChanged(QVariant)), SLOT(update())); -} - -void TrackWidget::paintEvent(QPaintEvent *event) { - QPainter painter(this); - painter.drawPixmap(0, 0, track_imgs[m_anim.currentValue().toInt()]); -} - -// Spinner - -Spinner::Spinner(QWidget *parent) : QWidget(parent) { - QGridLayout *main_layout = new QGridLayout(this); - main_layout->setSpacing(0); - main_layout->setMargin(200); - - main_layout->addWidget(new TrackWidget(this), 0, 0, Qt::AlignHCenter | Qt::AlignVCenter); - - text = new QLabel(); - text->setWordWrap(true); - text->setVisible(false); - text->setAlignment(Qt::AlignCenter); - main_layout->addWidget(text, 1, 0, Qt::AlignHCenter); - - progress_bar = new QProgressBar(); - progress_bar->setRange(5, 100); - progress_bar->setTextVisible(false); - progress_bar->setVisible(false); - progress_bar->setFixedHeight(20); - main_layout->addWidget(progress_bar, 1, 0, Qt::AlignHCenter); - - setStyleSheet(R"( - Spinner { - background-color: black; - } - QLabel { - color: white; - font-size: 80px; - background-color: transparent; - } - QProgressBar { - background-color: #373737; - width: 1000px; - border solid white; - border-radius: 10px; - } - QProgressBar::chunk { - border-radius: 10px; - background-color: white; - } - )"); - - notifier = new QSocketNotifier(fileno(stdin), QSocketNotifier::Read); - QObject::connect(notifier, &QSocketNotifier::activated, this, &Spinner::update); -} - -void Spinner::update(int n) { - std::string line; - std::getline(std::cin, line); - - if (line.length()) { - bool number = std::all_of(line.begin(), line.end(), ::isdigit); - text->setVisible(!number); - progress_bar->setVisible(number); - text->setText(QString::fromStdString(line)); - if (number) { - progress_bar->setValue(std::stoi(line)); - } - } -} - -int main(int argc, char *argv[]) { - initApp(argc, argv); - QApplication a(argc, argv); - Spinner spinner; - setMainWindow(&spinner); - return a.exec(); -} diff --git a/selfdrive/ui/qt/spinner.h b/selfdrive/ui/qt/spinner.h deleted file mode 100644 index 43d90a75b01036..00000000000000 --- a/selfdrive/ui/qt/spinner.h +++ /dev/null @@ -1,37 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include - -constexpr int spinner_fps = 30; -constexpr QSize spinner_size = QSize(360, 360); - -class TrackWidget : public QWidget { - Q_OBJECT -public: - TrackWidget(QWidget *parent = nullptr); - -private: - void paintEvent(QPaintEvent *event) override; - std::array track_imgs; - QVariantAnimation m_anim; -}; - -class Spinner : public QWidget { - Q_OBJECT - -public: - explicit Spinner(QWidget *parent = 0); - -private: - QLabel *text; - QProgressBar *progress_bar; - QSocketNotifier *notifier; - -public slots: - void update(int n); -}; diff --git a/selfdrive/ui/qt/spinner_larch64 b/selfdrive/ui/qt/spinner_larch64 deleted file mode 100755 index 74081a6925eaf8..00000000000000 --- a/selfdrive/ui/qt/spinner_larch64 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:81d7073d16e8ddc40d4d81fc88f8fc11c434df241593b455e2787935371383e4 -size 3821728 diff --git a/selfdrive/ui/qt/text.cc b/selfdrive/ui/qt/text.cc deleted file mode 100644 index 21ec5eedcf6be4..00000000000000 --- a/selfdrive/ui/qt/text.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -int main(int argc, char *argv[]) { - initApp(argc, argv); - QApplication a(argc, argv); - QWidget window; - setMainWindow(&window); - - QGridLayout *main_layout = new QGridLayout(&window); - main_layout->setMargin(50); - - QLabel *label = new QLabel(argv[1]); - label->setWordWrap(true); - label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); - ScrollView *scroll = new ScrollView(label); - scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - main_layout->addWidget(scroll, 0, 0, Qt::AlignTop); - - // Scroll to the bottom - QObject::connect(scroll->verticalScrollBar(), &QAbstractSlider::rangeChanged, [=]() { - scroll->verticalScrollBar()->setValue(scroll->verticalScrollBar()->maximum()); - }); - - QPushButton *btn = new QPushButton(); -#ifdef __aarch64__ - btn->setText(QObject::tr("Reboot")); - QObject::connect(btn, &QPushButton::clicked, [=]() { - Hardware::reboot(); - }); -#else - btn->setText(QObject::tr("Exit")); - QObject::connect(btn, &QPushButton::clicked, &a, &QApplication::quit); -#endif - main_layout->addWidget(btn, 0, 0, Qt::AlignRight | Qt::AlignBottom); - - window.setStyleSheet(R"( - * { - outline: none; - color: white; - background-color: black; - font-size: 60px; - } - QPushButton { - padding: 50px; - padding-right: 100px; - padding-left: 100px; - border: 2px solid white; - border-radius: 20px; - margin-right: 40px; - } - )"); - - return a.exec(); -} diff --git a/selfdrive/ui/qt/text_larch64 b/selfdrive/ui/qt/text_larch64 deleted file mode 100755 index 7d74f4d31c7be1..00000000000000 --- a/selfdrive/ui/qt/text_larch64 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:61f539845ebfc9568c8d28867f1e5642e882f52ead8862c9b2224b7139f4a552 -size 3787480 diff --git a/selfdrive/ui/qt/util.cc b/selfdrive/ui/qt/util.cc deleted file mode 100644 index 399a1a98d7b374..00000000000000 --- a/selfdrive/ui/qt/util.cc +++ /dev/null @@ -1,223 +0,0 @@ -#include "selfdrive/ui/qt/util.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "common/swaglog.h" -#include "system/hardware/hw.h" - -QString getVersion() { - static QString version = QString::fromStdString(Params().get("Version")); - return version; -} - -QString getBrand() { - return QObject::tr("openpilot"); -} - -QString getUserAgent() { - return "openpilot-" + getVersion(); -} - -std::optional getDongleId() { - std::string id = Params().get("DongleId"); - - if (!id.empty() && (id != "UnregisteredDevice")) { - return QString::fromStdString(id); - } else { - return {}; - } -} - -QMap getSupportedLanguages() { - QFile f(":/languages.json"); - f.open(QIODevice::ReadOnly | QIODevice::Text); - QString val = f.readAll(); - - QJsonObject obj = QJsonDocument::fromJson(val.toUtf8()).object(); - QMap map; - for (auto key : obj.keys()) { - map[key] = obj[key].toString(); - } - return map; -} - -QString timeAgo(const QDateTime &date) { - int diff = date.secsTo(QDateTime::currentDateTimeUtc()); - - QString s; - if (diff < 60) { - s = QObject::tr("now"); - } else if (diff < 60 * 60) { - int minutes = diff / 60; - s = QObject::tr("%n minute(s) ago", "", minutes); - } else if (diff < 60 * 60 * 24) { - int hours = diff / (60 * 60); - s = QObject::tr("%n hour(s) ago", "", hours); - } else if (diff < 3600 * 24 * 7) { - int days = diff / (60 * 60 * 24); - s = QObject::tr("%n day(s) ago", "", days); - } else { - s = date.date().toString(); - } - - return s; -} - -void setQtSurfaceFormat() { - QSurfaceFormat fmt; -#ifdef __APPLE__ - fmt.setVersion(3, 2); - fmt.setProfile(QSurfaceFormat::OpenGLContextProfile::CoreProfile); - fmt.setRenderableType(QSurfaceFormat::OpenGL); -#else - fmt.setRenderableType(QSurfaceFormat::OpenGLES); -#endif - fmt.setSamples(16); - fmt.setStencilBufferSize(1); - QSurfaceFormat::setDefaultFormat(fmt); -} - -void sigTermHandler(int s) { - std::signal(s, SIG_DFL); - qApp->quit(); -} - -void initApp(int argc, char *argv[], bool disable_hidpi) { - Hardware::set_display_power(true); - Hardware::set_brightness(65); - - // setup signal handlers to exit gracefully - std::signal(SIGINT, sigTermHandler); - std::signal(SIGTERM, sigTermHandler); - - QString app_dir; -#ifdef __APPLE__ - // Get the devicePixelRatio, and scale accordingly to maintain 1:1 rendering - QApplication tmp(argc, argv); - app_dir = QCoreApplication::applicationDirPath(); - if (disable_hidpi) { - qputenv("QT_SCALE_FACTOR", QString::number(1.0 / tmp.devicePixelRatio()).toLocal8Bit()); - } -#else - app_dir = QFileInfo(util::readlink("/proc/self/exe").c_str()).path(); -#endif - - qputenv("QT_DBL_CLICK_DIST", QByteArray::number(150)); - // ensure the current dir matches the exectuable's directory - QDir::setCurrent(app_dir); - - setQtSurfaceFormat(); -} - -void swagLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { - static std::map levels = { - {QtMsgType::QtDebugMsg, CLOUDLOG_DEBUG}, - {QtMsgType::QtInfoMsg, CLOUDLOG_INFO}, - {QtMsgType::QtWarningMsg, CLOUDLOG_WARNING}, - {QtMsgType::QtCriticalMsg, CLOUDLOG_ERROR}, - {QtMsgType::QtSystemMsg, CLOUDLOG_ERROR}, - {QtMsgType::QtFatalMsg, CLOUDLOG_CRITICAL}, - }; - - std::string file, function; - if (context.file != nullptr) file = context.file; - if (context.function != nullptr) function = context.function; - - auto bts = msg.toUtf8(); - cloudlog_e(levels[type], file.c_str(), context.line, function.c_str(), "%s", bts.constData()); -} - - -QWidget* topWidget(QWidget* widget) { - while (widget->parentWidget() != nullptr) widget=widget->parentWidget(); - return widget; -} - -QPixmap loadPixmap(const QString &fileName, const QSize &size, Qt::AspectRatioMode aspectRatioMode) { - if (size.isEmpty()) { - return QPixmap(fileName); - } else { - return QPixmap(fileName).scaled(size, aspectRatioMode, Qt::SmoothTransformation); - } -} - -static QHash load_bootstrap_icons() { - QHash icons; - - QFile f(":/bootstrap-icons.svg"); - if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { - QDomDocument xml; - xml.setContent(&f); - QDomNode n = xml.documentElement().firstChild(); - while (!n.isNull()) { - QDomElement e = n.toElement(); - if (!e.isNull() && e.hasAttribute("id")) { - QString svg_str; - QTextStream stream(&svg_str); - n.save(stream, 0); - svg_str.replace("", ""); - icons[e.attribute("id")] = svg_str.toUtf8(); - } - n = n.nextSibling(); - } - } - return icons; -} - -QPixmap bootstrapPixmap(const QString &id) { - static QHash icons = load_bootstrap_icons(); - - QPixmap pixmap; - if (auto it = icons.find(id); it != icons.end()) { - pixmap.loadFromData(it.value(), "svg"); - } - return pixmap; -} - -bool hasLongitudinalControl(const cereal::CarParams::Reader &car_params) { - // Using the experimental longitudinal toggle, returns whether longitudinal control - // will be active without needing a restart of openpilot - return car_params.getExperimentalLongitudinalAvailable() - ? Params().getBool("ExperimentalLongitudinalEnabled") - : car_params.getOpenpilotLongitudinalControl(); -} - -// ParamWatcher - -ParamWatcher::ParamWatcher(QObject *parent) : QObject(parent) { - watcher = new QFileSystemWatcher(this); - QObject::connect(watcher, &QFileSystemWatcher::fileChanged, this, &ParamWatcher::fileChanged); -} - -void ParamWatcher::fileChanged(const QString &path) { - auto param_name = QFileInfo(path).fileName(); - auto param_value = QString::fromStdString(params.get(param_name.toStdString())); - - auto it = params_hash.find(param_name); - bool content_changed = (it == params_hash.end()) || (it.value() != param_value); - params_hash[param_name] = param_value; - // emit signal when the content changes. - if (content_changed) { - emit paramChanged(param_name, param_value); - } -} - -void ParamWatcher::addParam(const QString ¶m_name) { - watcher->addPath(QString::fromStdString(params.getParamPath(param_name.toStdString()))); -} diff --git a/selfdrive/ui/qt/util.h b/selfdrive/ui/qt/util.h deleted file mode 100644 index 2bf1a70a62a437..00000000000000 --- a/selfdrive/ui/qt/util.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "cereal/gen/cpp/car.capnp.h" -#include "common/params.h" - -QString getVersion(); -QString getBrand(); -QString getUserAgent(); -std::optional getDongleId(); -QMap getSupportedLanguages(); -void setQtSurfaceFormat(); -void sigTermHandler(int s); -QString timeAgo(const QDateTime &date); -void swagLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg); -void initApp(int argc, char *argv[], bool disable_hidpi = true); -QWidget* topWidget(QWidget* widget); -QPixmap loadPixmap(const QString &fileName, const QSize &size = {}, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio); -QPixmap bootstrapPixmap(const QString &id); -bool hasLongitudinalControl(const cereal::CarParams::Reader &car_params); - -struct InterFont : public QFont { - InterFont(int pixel_size, QFont::Weight weight = QFont::Normal) : QFont("Inter") { - setPixelSize(pixel_size); - setWeight(weight); - } -}; - -class ParamWatcher : public QObject { - Q_OBJECT - -public: - ParamWatcher(QObject *parent); - void addParam(const QString ¶m_name); - -signals: - void paramChanged(const QString ¶m_name, const QString ¶m_value); - -private: - void fileChanged(const QString &path); - - QFileSystemWatcher *watcher; - QHash params_hash; - Params params; -}; diff --git a/selfdrive/ui/qt/widgets/cameraview.cc b/selfdrive/ui/qt/widgets/cameraview.cc deleted file mode 100644 index 914b04b6544445..00000000000000 --- a/selfdrive/ui/qt/widgets/cameraview.cc +++ /dev/null @@ -1,439 +0,0 @@ -#include "selfdrive/ui/qt/widgets/cameraview.h" - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include -#include -#include -#include - -#include -#include -#include - -namespace { - -const char frame_vertex_shader[] = -#ifdef __APPLE__ - "#version 330 core\n" -#else - "#version 300 es\n" -#endif - "layout(location = 0) in vec4 aPosition;\n" - "layout(location = 1) in vec2 aTexCoord;\n" - "uniform mat4 uTransform;\n" - "out vec2 vTexCoord;\n" - "void main() {\n" - " gl_Position = uTransform * aPosition;\n" - " vTexCoord = aTexCoord;\n" - "}\n"; - -const char frame_fragment_shader[] = -#ifdef QCOM2 - "#version 300 es\n" - "#extension GL_OES_EGL_image_external_essl3 : enable\n" - "precision mediump float;\n" - "uniform samplerExternalOES uTexture;\n" - "in vec2 vTexCoord;\n" - "out vec4 colorOut;\n" - "void main() {\n" - " colorOut = texture(uTexture, vTexCoord);\n" - // gamma to improve worst case visibility when dark - " colorOut.rgb = pow(colorOut.rgb, vec3(1.0/1.28));\n" - "}\n"; -#else -#ifdef __APPLE__ - "#version 330 core\n" -#else - "#version 300 es\n" - "precision mediump float;\n" -#endif - "uniform sampler2D uTextureY;\n" - "uniform sampler2D uTextureUV;\n" - "in vec2 vTexCoord;\n" - "out vec4 colorOut;\n" - "void main() {\n" - " float y = texture(uTextureY, vTexCoord).r;\n" - " vec2 uv = texture(uTextureUV, vTexCoord).rg - 0.5;\n" - " float r = y + 1.402 * uv.y;\n" - " float g = y - 0.344 * uv.x - 0.714 * uv.y;\n" - " float b = y + 1.772 * uv.x;\n" - " colorOut = vec4(r, g, b, 1.0);\n" - "}\n"; -#endif - -mat4 get_driver_view_transform(int screen_width, int screen_height, int stream_width, int stream_height) { - const float driver_view_ratio = 2.0; - const float yscale = stream_height * driver_view_ratio / stream_width; - const float xscale = yscale*screen_height/screen_width*stream_width/stream_height; - mat4 transform = (mat4){{ - xscale, 0.0, 0.0, 0.0, - 0.0, yscale, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; - return transform; -} - -mat4 get_fit_view_transform(float widget_aspect_ratio, float frame_aspect_ratio) { - float zx = 1, zy = 1; - if (frame_aspect_ratio > widget_aspect_ratio) { - zy = widget_aspect_ratio / frame_aspect_ratio; - } else { - zx = frame_aspect_ratio / widget_aspect_ratio; - } - - const mat4 frame_transform = {{ - zx, 0.0, 0.0, 0.0, - 0.0, zy, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; - return frame_transform; -} - -} // namespace - -CameraWidget::CameraWidget(std::string stream_name, VisionStreamType type, bool zoom, QWidget* parent) : - stream_name(stream_name), active_stream_type(type), requested_stream_type(type), zoomed_view(zoom), QOpenGLWidget(parent) { - setAttribute(Qt::WA_OpaquePaintEvent); - qRegisterMetaType>("availableStreams"); - QObject::connect(this, &CameraWidget::vipcThreadConnected, this, &CameraWidget::vipcConnected, Qt::BlockingQueuedConnection); - QObject::connect(this, &CameraWidget::vipcThreadFrameReceived, this, &CameraWidget::vipcFrameReceived, Qt::QueuedConnection); - QObject::connect(this, &CameraWidget::vipcAvailableStreamsUpdated, this, &CameraWidget::availableStreamsUpdated, Qt::QueuedConnection); - QObject::connect(QApplication::instance(), &QCoreApplication::aboutToQuit, this, &CameraWidget::stopVipcThread); -} - -CameraWidget::~CameraWidget() { - makeCurrent(); - stopVipcThread(); - if (isValid()) { - glDeleteVertexArrays(1, &frame_vao); - glDeleteBuffers(1, &frame_vbo); - glDeleteBuffers(1, &frame_ibo); - glDeleteBuffers(2, textures); - } - doneCurrent(); -} - -// Qt uses device-independent pixels, depending on platform this may be -// different to what OpenGL uses -int CameraWidget::glWidth() { - return width() * devicePixelRatio(); -} - -int CameraWidget::glHeight() { - return height() * devicePixelRatio(); -} - -void CameraWidget::initializeGL() { - initializeOpenGLFunctions(); - - program = std::make_unique(context()); - bool ret = program->addShaderFromSourceCode(QOpenGLShader::Vertex, frame_vertex_shader); - assert(ret); - ret = program->addShaderFromSourceCode(QOpenGLShader::Fragment, frame_fragment_shader); - assert(ret); - - program->link(); - GLint frame_pos_loc = program->attributeLocation("aPosition"); - GLint frame_texcoord_loc = program->attributeLocation("aTexCoord"); - - auto [x1, x2, y1, y2] = requested_stream_type == VISION_STREAM_DRIVER ? std::tuple(0.f, 1.f, 1.f, 0.f) : std::tuple(1.f, 0.f, 1.f, 0.f); - const uint8_t frame_indicies[] = {0, 1, 2, 0, 2, 3}; - const float frame_coords[4][4] = { - {-1.0, -1.0, x2, y1}, // bl - {-1.0, 1.0, x2, y2}, // tl - { 1.0, 1.0, x1, y2}, // tr - { 1.0, -1.0, x1, y1}, // br - }; - - glGenVertexArrays(1, &frame_vao); - glBindVertexArray(frame_vao); - glGenBuffers(1, &frame_vbo); - glBindBuffer(GL_ARRAY_BUFFER, frame_vbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(frame_coords), frame_coords, GL_STATIC_DRAW); - glEnableVertexAttribArray(frame_pos_loc); - glVertexAttribPointer(frame_pos_loc, 2, GL_FLOAT, GL_FALSE, - sizeof(frame_coords[0]), (const void *)0); - glEnableVertexAttribArray(frame_texcoord_loc); - glVertexAttribPointer(frame_texcoord_loc, 2, GL_FLOAT, GL_FALSE, - sizeof(frame_coords[0]), (const void *)(sizeof(float) * 2)); - glGenBuffers(1, &frame_ibo); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, frame_ibo); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(frame_indicies), frame_indicies, GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - - glUseProgram(program->programId()); - -#ifdef QCOM2 - glUniform1i(program->uniformLocation("uTexture"), 0); -#else - glGenTextures(2, textures); - glUniform1i(program->uniformLocation("uTextureY"), 0); - glUniform1i(program->uniformLocation("uTextureUV"), 1); -#endif -} - -void CameraWidget::showEvent(QShowEvent *event) { - if (!vipc_thread) { - clearFrames(); - vipc_thread = new QThread(); - connect(vipc_thread, &QThread::started, [=]() { vipcThread(); }); - connect(vipc_thread, &QThread::finished, vipc_thread, &QObject::deleteLater); - vipc_thread->start(); - } -} - -void CameraWidget::stopVipcThread() { - makeCurrent(); - if (vipc_thread) { - vipc_thread->requestInterruption(); - vipc_thread->quit(); - vipc_thread->wait(); - vipc_thread = nullptr; - } - -#ifdef QCOM2 - EGLDisplay egl_display = eglGetCurrentDisplay(); - assert(egl_display != EGL_NO_DISPLAY); - for (auto &pair : egl_images) { - eglDestroyImageKHR(egl_display, pair.second); - assert(eglGetError() == EGL_SUCCESS); - } - egl_images.clear(); -#endif -} - -void CameraWidget::availableStreamsUpdated(std::set streams) { - available_streams = streams; -} - -void CameraWidget::updateFrameMat() { - int w = glWidth(), h = glHeight(); - - if (zoomed_view) { - if (active_stream_type == VISION_STREAM_DRIVER) { - if (stream_width > 0 && stream_height > 0) { - frame_mat = get_driver_view_transform(w, h, stream_width, stream_height); - } - } else { - // Project point at "infinity" to compute x and y offsets - // to ensure this ends up in the middle of the screen - // for narrow come and a little lower for wide cam. - // TODO: use proper perspective transform? - if (active_stream_type == VISION_STREAM_WIDE_ROAD) { - intrinsic_matrix = ECAM_INTRINSIC_MATRIX; - zoom = 2.0; - } else { - intrinsic_matrix = FCAM_INTRINSIC_MATRIX; - zoom = 1.1; - } - const vec3 inf = {{1000., 0., 0.}}; - const vec3 Ep = matvecmul3(calibration, inf); - const vec3 Kep = matvecmul3(intrinsic_matrix, Ep); - - float x_offset_ = (Kep.v[0] / Kep.v[2] - intrinsic_matrix.v[2]) * zoom; - float y_offset_ = (Kep.v[1] / Kep.v[2] - intrinsic_matrix.v[5]) * zoom; - - float max_x_offset = intrinsic_matrix.v[2] * zoom - w / 2 - 5; - float max_y_offset = intrinsic_matrix.v[5] * zoom - h / 2 - 5; - - x_offset = std::clamp(x_offset_, -max_x_offset, max_x_offset); - y_offset = std::clamp(y_offset_, -max_y_offset, max_y_offset); - - float zx = zoom * 2 * intrinsic_matrix.v[2] / w; - float zy = zoom * 2 * intrinsic_matrix.v[5] / h; - const mat4 frame_transform = {{ - zx, 0.0, 0.0, -x_offset / w * 2, - 0.0, zy, 0.0, y_offset / h * 2, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; - frame_mat = frame_transform; - } - } else if (stream_width > 0 && stream_height > 0) { - // fit frame to widget size - float widget_aspect_ratio = (float)w / h; - float frame_aspect_ratio = (float)stream_width / stream_height; - frame_mat = get_fit_view_transform(widget_aspect_ratio, frame_aspect_ratio); - } -} - -void CameraWidget::updateCalibration(const mat3 &calib) { - calibration = calib; -} - -void CameraWidget::paintGL() { - glClearColor(bg.redF(), bg.greenF(), bg.blueF(), bg.alphaF()); - glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT); - - std::lock_guard lk(frame_lock); - if (frames.empty()) return; - - int frame_idx = frames.size() - 1; - - // Always draw latest frame until sync logic is more stable - // for (frame_idx = 0; frame_idx < frames.size() - 1; frame_idx++) { - // if (frames[frame_idx].first == draw_frame_id) break; - // } - - // Log duplicate/dropped frames - if (frames[frame_idx].first == prev_frame_id) { - qDebug() << "Drawing same frame twice" << frames[frame_idx].first; - } else if (frames[frame_idx].first != prev_frame_id + 1) { - qDebug() << "Skipped frame" << frames[frame_idx].first; - } - prev_frame_id = frames[frame_idx].first; - VisionBuf *frame = frames[frame_idx].second; - assert(frame != nullptr); - - updateFrameMat(); - - glViewport(0, 0, glWidth(), glHeight()); - glBindVertexArray(frame_vao); - glUseProgram(program->programId()); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - -#ifdef QCOM2 - // no frame copy - glActiveTexture(GL_TEXTURE0); - glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, egl_images[frame->idx]); - assert(glGetError() == GL_NO_ERROR); -#else - // fallback to copy - glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, textures[0]); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width, stream_height, GL_RED, GL_UNSIGNED_BYTE, frame->y); - assert(glGetError() == GL_NO_ERROR); - - glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride/2); - glActiveTexture(GL_TEXTURE0 + 1); - glBindTexture(GL_TEXTURE_2D, textures[1]); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width/2, stream_height/2, GL_RG, GL_UNSIGNED_BYTE, frame->uv); - assert(glGetError() == GL_NO_ERROR); -#endif - - glUniformMatrix4fv(program->uniformLocation("uTransform"), 1, GL_TRUE, frame_mat.v); - glEnableVertexAttribArray(0); - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, (const void *)0); - glDisableVertexAttribArray(0); - glBindVertexArray(0); - glBindTexture(GL_TEXTURE_2D, 0); - glActiveTexture(GL_TEXTURE0); - glPixelStorei(GL_UNPACK_ALIGNMENT, 4); - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); -} - -void CameraWidget::vipcConnected(VisionIpcClient *vipc_client) { - makeCurrent(); - stream_width = vipc_client->buffers[0].width; - stream_height = vipc_client->buffers[0].height; - stream_stride = vipc_client->buffers[0].stride; - -#ifdef QCOM2 - EGLDisplay egl_display = eglGetCurrentDisplay(); - assert(egl_display != EGL_NO_DISPLAY); - for (auto &pair : egl_images) { - eglDestroyImageKHR(egl_display, pair.second); - } - egl_images.clear(); - - for (int i = 0; i < vipc_client->num_buffers; i++) { // import buffers into OpenGL - int fd = dup(vipc_client->buffers[i].fd); // eglDestroyImageKHR will close, so duplicate - EGLint img_attrs[] = { - EGL_WIDTH, (int)vipc_client->buffers[i].width, - EGL_HEIGHT, (int)vipc_client->buffers[i].height, - EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_NV12, - EGL_DMA_BUF_PLANE0_FD_EXT, fd, - EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, - EGL_DMA_BUF_PLANE0_PITCH_EXT, (int)vipc_client->buffers[i].stride, - EGL_DMA_BUF_PLANE1_FD_EXT, fd, - EGL_DMA_BUF_PLANE1_OFFSET_EXT, (int)vipc_client->buffers[i].uv_offset, - EGL_DMA_BUF_PLANE1_PITCH_EXT, (int)vipc_client->buffers[i].stride, - EGL_NONE - }; - egl_images[i] = eglCreateImageKHR(egl_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, 0, img_attrs); - assert(eglGetError() == EGL_SUCCESS); - } -#else - glBindTexture(GL_TEXTURE_2D, textures[0]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, stream_width, stream_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr); - assert(glGetError() == GL_NO_ERROR); - - glBindTexture(GL_TEXTURE_2D, textures[1]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, stream_width/2, stream_height/2, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr); - assert(glGetError() == GL_NO_ERROR); -#endif -} - -void CameraWidget::vipcFrameReceived() { - update(); -} - -void CameraWidget::vipcThread() { - VisionStreamType cur_stream = requested_stream_type; - std::unique_ptr vipc_client; - VisionIpcBufExtra meta_main = {0}; - - while (!QThread::currentThread()->isInterruptionRequested()) { - if (!vipc_client || cur_stream != requested_stream_type) { - clearFrames(); - qDebug().nospace() << "connecting to stream " << requested_stream_type << ", was connected to " << cur_stream; - cur_stream = requested_stream_type; - vipc_client.reset(new VisionIpcClient(stream_name, cur_stream, false)); - } - active_stream_type = cur_stream; - - if (!vipc_client->connected) { - clearFrames(); - auto streams = VisionIpcClient::getAvailableStreams(stream_name, false); - if (streams.empty()) { - QThread::msleep(100); - continue; - } - emit vipcAvailableStreamsUpdated(streams); - - if (!vipc_client->connect(false)) { - QThread::msleep(100); - continue; - } - emit vipcThreadConnected(vipc_client.get()); - } - - if (VisionBuf *buf = vipc_client->recv(&meta_main, 1000)) { - { - std::lock_guard lk(frame_lock); - frames.push_back(std::make_pair(meta_main.frame_id, buf)); - while (frames.size() > FRAME_BUFFER_SIZE) { - frames.pop_front(); - } - } - emit vipcThreadFrameReceived(); - } else { - if (!isVisible()) { - vipc_client->connected = false; - } - } - } -} - -void CameraWidget::clearFrames() { - std::lock_guard lk(frame_lock); - frames.clear(); - available_streams.clear(); -} diff --git a/selfdrive/ui/qt/widgets/cameraview.h b/selfdrive/ui/qt/widgets/cameraview.h deleted file mode 100644 index 85ec49873579dc..00000000000000 --- a/selfdrive/ui/qt/widgets/cameraview.h +++ /dev/null @@ -1,103 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#ifdef QCOM2 -#define EGL_EGLEXT_PROTOTYPES -#define EGL_NO_X11 -#define GL_TEXTURE_EXTERNAL_OES 0x8D65 -#include -#include -#include -#endif - -#include "msgq/visionipc/visionipc_client.h" -#include "system/camerad/cameras/camera_common.h" -#include "selfdrive/ui/ui.h" - -const int FRAME_BUFFER_SIZE = 5; -static_assert(FRAME_BUFFER_SIZE <= YUV_BUFFER_COUNT); - -class CameraWidget : public QOpenGLWidget, protected QOpenGLFunctions { - Q_OBJECT - -public: - using QOpenGLWidget::QOpenGLWidget; - explicit CameraWidget(std::string stream_name, VisionStreamType stream_type, bool zoom, QWidget* parent = nullptr); - ~CameraWidget(); - void setBackgroundColor(const QColor &color) { bg = color; } - void setFrameId(int frame_id) { draw_frame_id = frame_id; } - void setStreamType(VisionStreamType type) { requested_stream_type = type; } - VisionStreamType getStreamType() { return active_stream_type; } - void stopVipcThread(); - -signals: - void clicked(); - void vipcThreadConnected(VisionIpcClient *); - void vipcThreadFrameReceived(); - void vipcAvailableStreamsUpdated(std::set); - -protected: - void paintGL() override; - void initializeGL() override; - void resizeGL(int w, int h) override { updateFrameMat(); } - void showEvent(QShowEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override { emit clicked(); } - virtual void updateFrameMat(); - void updateCalibration(const mat3 &calib); - void vipcThread(); - void clearFrames(); - - int glWidth(); - int glHeight(); - - bool zoomed_view; - GLuint frame_vao, frame_vbo, frame_ibo; - GLuint textures[2]; - mat4 frame_mat = {}; - std::unique_ptr program; - QColor bg = QColor("#000000"); - -#ifdef QCOM2 - std::map egl_images; -#endif - - std::string stream_name; - int stream_width = 0; - int stream_height = 0; - int stream_stride = 0; - std::atomic active_stream_type; - std::atomic requested_stream_type; - std::set available_streams; - QThread *vipc_thread = nullptr; - - // Calibration - float x_offset = 0; - float y_offset = 0; - float zoom = 1.0; - mat3 calibration = DEFAULT_CALIBRATION; - mat3 intrinsic_matrix = FCAM_INTRINSIC_MATRIX; - - std::recursive_mutex frame_lock; - std::deque> frames; - uint32_t draw_frame_id = 0; - uint32_t prev_frame_id = 0; - -protected slots: - void vipcConnected(VisionIpcClient *vipc_client); - void vipcFrameReceived(); - void availableStreamsUpdated(std::set streams); -}; - -Q_DECLARE_METATYPE(std::set); diff --git a/selfdrive/ui/qt/widgets/controls.cc b/selfdrive/ui/qt/widgets/controls.cc deleted file mode 100644 index 40dda971f51e6f..00000000000000 --- a/selfdrive/ui/qt/widgets/controls.cc +++ /dev/null @@ -1,141 +0,0 @@ -#include "selfdrive/ui/qt/widgets/controls.h" - -#include -#include - -AbstractControl::AbstractControl(const QString &title, const QString &desc, const QString &icon, QWidget *parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(0); - - hlayout = new QHBoxLayout; - hlayout->setMargin(0); - hlayout->setSpacing(20); - - // left icon - icon_label = new QLabel(this); - hlayout->addWidget(icon_label); - if (!icon.isEmpty()) { - icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); - icon_label->setPixmap(icon_pixmap); - icon_label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - } - icon_label->setVisible(!icon.isEmpty()); - - // title - title_label = new QPushButton(title); - title_label->setFixedHeight(120); - title_label->setStyleSheet("font-size: 50px; font-weight: 400; text-align: left; border: none;"); - hlayout->addWidget(title_label, 1); - - // value next to control button - value = new ElidedLabel(); - value->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - value->setStyleSheet("color: #aaaaaa"); - hlayout->addWidget(value); - - main_layout->addLayout(hlayout); - - // description - description = new QLabel(desc); - description->setContentsMargins(40, 20, 40, 20); - description->setStyleSheet("font-size: 40px; color: grey"); - description->setWordWrap(true); - description->setVisible(false); - main_layout->addWidget(description); - - connect(title_label, &QPushButton::clicked, [=]() { - if (!description->isVisible()) { - emit showDescriptionEvent(); - } - - if (!description->text().isEmpty()) { - description->setVisible(!description->isVisible()); - } - }); - - main_layout->addStretch(); -} - -void AbstractControl::hideEvent(QHideEvent *e) { - if (description != nullptr) { - description->hide(); - } -} - -// controls - -ButtonControl::ButtonControl(const QString &title, const QString &text, const QString &desc, QWidget *parent) : AbstractControl(title, desc, "", parent) { - btn.setText(text); - btn.setStyleSheet(R"( - QPushButton { - padding: 0; - border-radius: 50px; - font-size: 35px; - font-weight: 500; - color: #E4E4E4; - background-color: #393939; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:disabled { - color: #33E4E4E4; - } - )"); - btn.setFixedSize(250, 100); - QObject::connect(&btn, &QPushButton::clicked, this, &ButtonControl::clicked); - hlayout->addWidget(&btn); -} - -// ElidedLabel - -ElidedLabel::ElidedLabel(QWidget *parent) : ElidedLabel({}, parent) {} - -ElidedLabel::ElidedLabel(const QString &text, QWidget *parent) : QLabel(text.trimmed(), parent) { - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - setMinimumWidth(1); -} - -void ElidedLabel::resizeEvent(QResizeEvent* event) { - QLabel::resizeEvent(event); - lastText_ = elidedText_ = ""; -} - -void ElidedLabel::paintEvent(QPaintEvent *event) { - const QString curText = text(); - if (curText != lastText_) { - elidedText_ = fontMetrics().elidedText(curText, Qt::ElideRight, contentsRect().width()); - lastText_ = curText; - } - - QPainter painter(this); - drawFrame(&painter); - QStyleOption opt; - opt.initFrom(this); - style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elidedText_, foregroundRole()); -} - -// ParamControl - -ParamControl::ParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent) - : ToggleControl(title, desc, icon, false, parent) { - key = param.toStdString(); - QObject::connect(this, &ParamControl::toggleFlipped, this, &ParamControl::toggleClicked); -} - -void ParamControl::toggleClicked(bool state) { - auto do_confirm = [this]() { - QString content("

" + title_label->text() + "


" - "

" + getDescription() + "

"); - return ConfirmationDialog(content, tr("Enable"), tr("Cancel"), true, this).exec(); - }; - - bool confirmed = store_confirm && params.getBool(key + "Confirmed"); - if (!confirm || confirmed || !state || do_confirm()) { - if (store_confirm && state) params.putBool(key + "Confirmed", true); - params.putBool(key, state); - setIcon(state); - } else { - toggle.togglePosition(); - } -} diff --git a/selfdrive/ui/qt/widgets/controls.h b/selfdrive/ui/qt/widgets/controls.h deleted file mode 100644 index aa304e0df68fee..00000000000000 --- a/selfdrive/ui/qt/widgets/controls.h +++ /dev/null @@ -1,296 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/toggle.h" - -class ElidedLabel : public QLabel { - Q_OBJECT - -public: - explicit ElidedLabel(QWidget *parent = 0); - explicit ElidedLabel(const QString &text, QWidget *parent = 0); - -signals: - void clicked(); - -protected: - void paintEvent(QPaintEvent *event) override; - void resizeEvent(QResizeEvent* event) override; - void mouseReleaseEvent(QMouseEvent *event) override { - if (rect().contains(event->pos())) { - emit clicked(); - } - } - QString lastText_, elidedText_; -}; - - -class AbstractControl : public QFrame { - Q_OBJECT - -public: - void setDescription(const QString &desc) { - if (description) description->setText(desc); - } - - void setTitle(const QString &title) { - title_label->setText(title); - } - - void setValue(const QString &val) { - value->setText(val); - } - - const QString getDescription() { - return description->text(); - } - - QLabel *icon_label; - QPixmap icon_pixmap; - -public slots: - void showDescription() { - description->setVisible(true); - } - -signals: - void showDescriptionEvent(); - -protected: - AbstractControl(const QString &title, const QString &desc = "", const QString &icon = "", QWidget *parent = nullptr); - void hideEvent(QHideEvent *e) override; - - QHBoxLayout *hlayout; - QPushButton *title_label; - -private: - ElidedLabel *value; - QLabel *description = nullptr; -}; - -// widget to display a value -class LabelControl : public AbstractControl { - Q_OBJECT - -public: - LabelControl(const QString &title, const QString &text = "", const QString &desc = "", QWidget *parent = nullptr) : AbstractControl(title, desc, "", parent) { - label.setText(text); - label.setAlignment(Qt::AlignRight | Qt::AlignVCenter); - hlayout->addWidget(&label); - } - void setText(const QString &text) { label.setText(text); } - -private: - ElidedLabel label; -}; - -// widget for a button with a label -class ButtonControl : public AbstractControl { - Q_OBJECT - -public: - ButtonControl(const QString &title, const QString &text, const QString &desc = "", QWidget *parent = nullptr); - inline void setText(const QString &text) { btn.setText(text); } - inline QString text() const { return btn.text(); } - -signals: - void clicked(); - -public slots: - void setEnabled(bool enabled) { btn.setEnabled(enabled); } - -private: - QPushButton btn; -}; - -class ToggleControl : public AbstractControl { - Q_OBJECT - -public: - ToggleControl(const QString &title, const QString &desc = "", const QString &icon = "", const bool state = false, QWidget *parent = nullptr) : AbstractControl(title, desc, icon, parent) { - toggle.setFixedSize(150, 100); - if (state) { - toggle.togglePosition(); - } - hlayout->addWidget(&toggle); - QObject::connect(&toggle, &Toggle::stateChanged, this, &ToggleControl::toggleFlipped); - } - - void setEnabled(bool enabled) { - toggle.setEnabled(enabled); - toggle.update(); - } - -signals: - void toggleFlipped(bool state); - -protected: - Toggle toggle; -}; - -// widget to toggle params -class ParamControl : public ToggleControl { - Q_OBJECT - -public: - ParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent = nullptr); - void setConfirmation(bool _confirm, bool _store_confirm) { - confirm = _confirm; - store_confirm = _store_confirm; - } - - void setActiveIcon(const QString &icon) { - active_icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); - } - - void refresh() { - bool state = params.getBool(key); - if (state != toggle.on) { - toggle.togglePosition(); - setIcon(state); - } - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - -private: - void toggleClicked(bool state); - void setIcon(bool state) { - if (state && !active_icon_pixmap.isNull()) { - icon_label->setPixmap(active_icon_pixmap); - } else if (!icon_pixmap.isNull()) { - icon_label->setPixmap(icon_pixmap); - } - } - - std::string key; - Params params; - QPixmap active_icon_pixmap; - bool confirm = false; - bool store_confirm = false; -}; - -class ButtonParamControl : public AbstractControl { - Q_OBJECT -public: - ButtonParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, const int minimum_button_width = 225) : AbstractControl(title, desc, icon) { - const QString style = R"( - QPushButton { - border-radius: 50px; - font-size: 40px; - font-weight: 500; - height:100px; - padding: 0 25 0 25; - color: #E4E4E4; - background-color: #393939; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:checked:enabled { - background-color: #33Ab4C; - } - QPushButton:disabled { - color: #33E4E4E4; - } - )"; - key = param.toStdString(); - int value = atoi(params.get(key).c_str()); - - button_group = new QButtonGroup(this); - button_group->setExclusive(true); - for (int i = 0; i < button_texts.size(); i++) { - QPushButton *button = new QPushButton(button_texts[i], this); - button->setCheckable(true); - button->setChecked(i == value); - button->setStyleSheet(style); - button->setMinimumWidth(minimum_button_width); - hlayout->addWidget(button); - button_group->addButton(button, i); - } - - QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonClicked), [=](int id) { - params.put(key, std::to_string(id)); - }); - } - - void setEnabled(bool enable) { - for (auto btn : button_group->buttons()) { - btn->setEnabled(enable); - } - } - - void setCheckedButton(int id) { - button_group->button(id)->setChecked(true); - } - - void refresh() { - int value = atoi(params.get(key).c_str()); - button_group->button(value)->setChecked(true); - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - -private: - std::string key; - Params params; - QButtonGroup *button_group; -}; - -class ListWidget : public QWidget { - Q_OBJECT - public: - explicit ListWidget(QWidget *parent = 0) : QWidget(parent), outer_layout(this) { - outer_layout.setMargin(0); - outer_layout.setSpacing(0); - outer_layout.addLayout(&inner_layout); - inner_layout.setMargin(0); - inner_layout.setSpacing(25); // default spacing is 25 - outer_layout.addStretch(); - } - inline void addItem(QWidget *w) { inner_layout.addWidget(w); } - inline void addItem(QLayout *layout) { inner_layout.addLayout(layout); } - inline void setSpacing(int spacing) { inner_layout.setSpacing(spacing); } - -private: - void paintEvent(QPaintEvent *) override { - QPainter p(this); - p.setPen(Qt::gray); - for (int i = 0; i < inner_layout.count() - 1; ++i) { - QWidget *widget = inner_layout.itemAt(i)->widget(); - if (widget == nullptr || widget->isVisible()) { - QRect r = inner_layout.itemAt(i)->geometry(); - int bottom = r.bottom() + inner_layout.spacing() / 2; - p.drawLine(r.left() + 40, bottom, r.right() - 40, bottom); - } - } - } - QVBoxLayout outer_layout; - QVBoxLayout inner_layout; -}; - -// convenience class for wrapping layouts -class LayoutWidget : public QWidget { - Q_OBJECT - -public: - LayoutWidget(QLayout *l, QWidget *parent = nullptr) : QWidget(parent) { - setLayout(l); - } -}; diff --git a/selfdrive/ui/qt/widgets/input.cc b/selfdrive/ui/qt/widgets/input.cc deleted file mode 100644 index b0b6b4c23bedec..00000000000000 --- a/selfdrive/ui/qt/widgets/input.cc +++ /dev/null @@ -1,336 +0,0 @@ -#include "selfdrive/ui/qt/widgets/input.h" - -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - - -DialogBase::DialogBase(QWidget *parent) : QDialog(parent) { - Q_ASSERT(parent != nullptr); - parent->installEventFilter(this); - - setStyleSheet(R"( - * { - outline: none; - color: white; - font-family: Inter; - } - DialogBase { - background-color: black; - } - QPushButton { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - color: white; - background-color: #333333; - } - QPushButton:pressed { - background-color: #444444; - } - )"); -} - -bool DialogBase::eventFilter(QObject *o, QEvent *e) { - if (o == parent() && e->type() == QEvent::Hide) { - reject(); - } - return QDialog::eventFilter(o, e); -} - -int DialogBase::exec() { - setMainWindow(this); - return QDialog::exec(); -} - -InputDialog::InputDialog(const QString &title, QWidget *parent, const QString &subtitle, bool secret) : DialogBase(parent) { - main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 55, 50, 50); - main_layout->setSpacing(0); - - // build header - QHBoxLayout *header_layout = new QHBoxLayout(); - - QVBoxLayout *vlayout = new QVBoxLayout; - header_layout->addLayout(vlayout); - label = new QLabel(title, this); - label->setStyleSheet("font-size: 90px; font-weight: bold;"); - vlayout->addWidget(label, 1, Qt::AlignTop | Qt::AlignLeft); - - if (!subtitle.isEmpty()) { - sublabel = new QLabel(subtitle, this); - sublabel->setStyleSheet("font-size: 55px; font-weight: light; color: #BDBDBD;"); - vlayout->addWidget(sublabel, 1, Qt::AlignTop | Qt::AlignLeft); - } - - QPushButton* cancel_btn = new QPushButton(tr("Cancel")); - cancel_btn->setFixedSize(386, 125); - cancel_btn->setStyleSheet(R"( - QPushButton { - font-size: 48px; - border-radius: 10px; - color: #E4E4E4; - background-color: #333333; - } - QPushButton:pressed { - background-color: #444444; - } - )"); - header_layout->addWidget(cancel_btn, 0, Qt::AlignRight); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &InputDialog::reject); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &InputDialog::cancel); - - main_layout->addLayout(header_layout); - - // text box - main_layout->addStretch(2); - - QWidget *textbox_widget = new QWidget; - textbox_widget->setObjectName("textbox"); - QHBoxLayout *textbox_layout = new QHBoxLayout(textbox_widget); - textbox_layout->setContentsMargins(50, 0, 50, 0); - - textbox_widget->setStyleSheet(R"( - #textbox { - margin-left: 50px; - margin-right: 50px; - border-radius: 0; - border-bottom: 3px solid #BDBDBD; - } - * { - border: none; - font-size: 80px; - font-weight: light; - background-color: transparent; - } - )"); - - line = new QLineEdit(); - line->setStyleSheet("lineedit-password-character: 8226; lineedit-password-mask-delay: 1500;"); - textbox_layout->addWidget(line, 1); - - if (secret) { - eye_btn = new QPushButton(); - eye_btn->setCheckable(true); - eye_btn->setFixedSize(150, 120); - QObject::connect(eye_btn, &QPushButton::toggled, [=](bool checked) { - if (checked) { - eye_btn->setIcon(QIcon(ASSET_PATH + "img_eye_closed.svg")); - eye_btn->setIconSize(QSize(81, 54)); - line->setEchoMode(QLineEdit::Password); - } else { - eye_btn->setIcon(QIcon(ASSET_PATH + "img_eye_open.svg")); - eye_btn->setIconSize(QSize(81, 44)); - line->setEchoMode(QLineEdit::Normal); - } - }); - eye_btn->toggle(); - eye_btn->setChecked(false); - textbox_layout->addWidget(eye_btn); - } - - main_layout->addWidget(textbox_widget, 0, Qt::AlignBottom); - main_layout->addSpacing(25); - - k = new Keyboard(this); - QObject::connect(k, &Keyboard::emitEnter, this, &InputDialog::handleEnter); - QObject::connect(k, &Keyboard::emitBackspace, this, [=]() { - line->backspace(); - }); - QObject::connect(k, &Keyboard::emitKey, this, [=](const QString &key) { - line->insert(key.left(1)); - }); - - main_layout->addWidget(k, 2, Qt::AlignBottom); -} - -QString InputDialog::getText(const QString &prompt, QWidget *parent, const QString &subtitle, - bool secret, int minLength, const QString &defaultText) { - InputDialog d(prompt, parent, subtitle, secret); - d.line->setText(defaultText); - d.setMinLength(minLength); - const int ret = d.exec(); - return ret ? d.text() : QString(); -} - -QString InputDialog::text() { - return line->text(); -} - -void InputDialog::show() { - setMainWindow(this); -} - -void InputDialog::handleEnter() { - if (line->text().length() >= minLength) { - done(QDialog::Accepted); - emitText(line->text()); - } else { - setMessage(tr("Need at least %n character(s)!", "", minLength), false); - } -} - -void InputDialog::setMessage(const QString &message, bool clearInputField) { - label->setText(message); - if (clearInputField) { - line->setText(""); - } -} - -void InputDialog::setMinLength(int length) { - minLength = length; -} - -// ConfirmationDialog - -ConfirmationDialog::ConfirmationDialog(const QString &prompt_text, const QString &confirm_text, const QString &cancel_text, - const bool rich, QWidget *parent) : DialogBase(parent) { - QFrame *container = new QFrame(this); - container->setStyleSheet(R"( - QFrame { background-color: #1B1B1B; color: #C9C9C9; } - #confirm_btn { background-color: #465BEA; } - #confirm_btn:pressed { background-color: #3049F4; } - )"); - QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(32, rich ? 32 : 120, 32, 32); - - QLabel *prompt = new QLabel(prompt_text, this); - prompt->setWordWrap(true); - prompt->setAlignment(rich ? Qt::AlignLeft : Qt::AlignHCenter); - prompt->setStyleSheet((rich ? "font-size: 42px; font-weight: light;" : "font-size: 70px; font-weight: bold;") + QString(" margin: 45px;")); - main_layout->addWidget(rich ? (QWidget*)new ScrollView(prompt, this) : (QWidget*)prompt, 1, Qt::AlignTop); - - // cancel + confirm buttons - QHBoxLayout *btn_layout = new QHBoxLayout(); - btn_layout->setSpacing(30); - main_layout->addLayout(btn_layout); - - if (cancel_text.length()) { - QPushButton* cancel_btn = new QPushButton(cancel_text); - btn_layout->addWidget(cancel_btn); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &ConfirmationDialog::reject); - } - - if (confirm_text.length()) { - QPushButton* confirm_btn = new QPushButton(confirm_text); - confirm_btn->setObjectName("confirm_btn"); - btn_layout->addWidget(confirm_btn); - QObject::connect(confirm_btn, &QPushButton::clicked, this, &ConfirmationDialog::accept); - } - - QVBoxLayout *outer_layout = new QVBoxLayout(this); - int margin = rich ? 100 : 200; - outer_layout->setContentsMargins(margin, margin, margin, margin); - outer_layout->addWidget(container); -} - -bool ConfirmationDialog::alert(const QString &prompt_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, tr("Ok"), "", false, parent); - return d.exec(); -} - -bool ConfirmationDialog::confirm(const QString &prompt_text, const QString &confirm_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, confirm_text, tr("Cancel"), false, parent); - return d.exec(); -} - -bool ConfirmationDialog::rich(const QString &prompt_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, tr("Ok"), "", true, parent); - return d.exec(); -} - -// MultiOptionDialog - -MultiOptionDialog::MultiOptionDialog(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent) : DialogBase(parent) { - QFrame *container = new QFrame(this); - container->setStyleSheet(R"( - QFrame { background-color: #1B1B1B; } - #confirm_btn[enabled="false"] { background-color: #2B2B2B; } - #confirm_btn:enabled { background-color: #465BEA; } - #confirm_btn:enabled:pressed { background-color: #3049F4; } - )"); - - QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(55, 50, 55, 50); - - QLabel *title = new QLabel(prompt_text, this); - title->setStyleSheet("font-size: 70px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); - main_layout->addSpacing(25); - - QWidget *listWidget = new QWidget(this); - QVBoxLayout *listLayout = new QVBoxLayout(listWidget); - listLayout->setSpacing(20); - listWidget->setStyleSheet(R"( - QPushButton { - height: 135; - padding: 0px 50px; - text-align: left; - font-size: 55px; - font-weight: 300; - border-radius: 10px; - background-color: #4F4F4F; - } - QPushButton:checked { background-color: #465BEA; } - )"); - - QButtonGroup *group = new QButtonGroup(listWidget); - group->setExclusive(true); - - QPushButton *confirm_btn = new QPushButton(tr("Select")); - confirm_btn->setObjectName("confirm_btn"); - confirm_btn->setEnabled(false); - - for (const QString &s : l) { - QPushButton *selectionLabel = new QPushButton(s); - selectionLabel->setCheckable(true); - selectionLabel->setChecked(s == current); - QObject::connect(selectionLabel, &QPushButton::toggled, [=](bool checked) { - if (checked) selection = s; - if (selection != current) { - confirm_btn->setEnabled(true); - } else { - confirm_btn->setEnabled(false); - } - }); - - group->addButton(selectionLabel); - listLayout->addWidget(selectionLabel); - } - // add stretch to keep buttons spaced correctly - listLayout->addStretch(1); - - ScrollView *scroll_view = new ScrollView(listWidget, this); - scroll_view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - - main_layout->addWidget(scroll_view); - main_layout->addSpacing(35); - - // cancel + confirm buttons - QHBoxLayout *blayout = new QHBoxLayout; - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - QPushButton *cancel_btn = new QPushButton(tr("Cancel")); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &ConfirmationDialog::reject); - QObject::connect(confirm_btn, &QPushButton::clicked, this, &ConfirmationDialog::accept); - blayout->addWidget(cancel_btn); - blayout->addWidget(confirm_btn); - - QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(50, 50, 50, 50); - outer_layout->addWidget(container); -} - -QString MultiOptionDialog::getSelection(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent) { - MultiOptionDialog d(prompt_text, l, current, parent); - if (d.exec()) { - return d.selection; - } - return ""; -} diff --git a/selfdrive/ui/qt/widgets/input.h b/selfdrive/ui/qt/widgets/input.h deleted file mode 100644 index 089e54e4a0018d..00000000000000 --- a/selfdrive/ui/qt/widgets/input.h +++ /dev/null @@ -1,71 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/widgets/keyboard.h" - - -class DialogBase : public QDialog { - Q_OBJECT - -protected: - DialogBase(QWidget *parent); - bool eventFilter(QObject *o, QEvent *e) override; - -public slots: - int exec() override; -}; - -class InputDialog : public DialogBase { - Q_OBJECT - -public: - explicit InputDialog(const QString &title, QWidget *parent, const QString &subtitle = "", bool secret = false); - static QString getText(const QString &title, QWidget *parent, const QString &subtitle = "", - bool secret = false, int minLength = -1, const QString &defaultText = ""); - QString text(); - void setMessage(const QString &message, bool clearInputField = true); - void setMinLength(int length); - void show(); - -private: - int minLength; - QLineEdit *line; - Keyboard *k; - QLabel *label; - QLabel *sublabel; - QVBoxLayout *main_layout; - QPushButton *eye_btn; - -private slots: - void handleEnter(); - -signals: - void cancel(); - void emitText(const QString &text); -}; - -class ConfirmationDialog : public DialogBase { - Q_OBJECT - -public: - explicit ConfirmationDialog(const QString &prompt_text, const QString &confirm_text, - const QString &cancel_text, const bool rich, QWidget* parent); - static bool alert(const QString &prompt_text, QWidget *parent); - static bool confirm(const QString &prompt_text, const QString &confirm_text, QWidget *parent); - static bool rich(const QString &prompt_text, QWidget *parent); -}; - -class MultiOptionDialog : public DialogBase { - Q_OBJECT - -public: - explicit MultiOptionDialog(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent); - static QString getSelection(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent); - QString selection; -}; diff --git a/selfdrive/ui/qt/widgets/keyboard.cc b/selfdrive/ui/qt/widgets/keyboard.cc deleted file mode 100644 index 370e9a53ccb62f..00000000000000 --- a/selfdrive/ui/qt/widgets/keyboard.cc +++ /dev/null @@ -1,167 +0,0 @@ -#include "selfdrive/ui/qt/widgets/keyboard.h" - -#include - -#include -#include -#include -#include -#include - -const QString BACKSPACE_KEY = "⌫"; -const QString ENTER_KEY = "→"; - -const QMap KEY_STRETCH = {{" ", 5}, {ENTER_KEY, 2}}; - -const QStringList CONTROL_BUTTONS = {"↑", "↓", "ABC", "#+=", "123", BACKSPACE_KEY, ENTER_KEY}; - -const float key_spacing_vertical = 20; -const float key_spacing_horizontal = 15; - -KeyButton::KeyButton(const QString &text, QWidget *parent) : QPushButton(text, parent) { - setAttribute(Qt::WA_AcceptTouchEvents); - setFocusPolicy(Qt::NoFocus); -} - -bool KeyButton::event(QEvent *event) { - if (event->type() == QEvent::TouchBegin || event->type() == QEvent::TouchEnd) { - QTouchEvent *touchEvent = static_cast(event); - if (!touchEvent->touchPoints().empty()) { - const QEvent::Type mouseType = event->type() == QEvent::TouchBegin ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease; - QMouseEvent mouseEvent(mouseType, touchEvent->touchPoints().front().pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); - QPushButton::event(&mouseEvent); - event->accept(); - parentWidget()->update(); - return true; - } - } - return QPushButton::event(event); -} - -KeyboardLayout::KeyboardLayout(QWidget* parent, const std::vector>& layout) : QWidget(parent) { - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setMargin(0); - main_layout->setSpacing(0); - - QButtonGroup* btn_group = new QButtonGroup(this); - QObject::connect(btn_group, SIGNAL(buttonClicked(QAbstractButton*)), parent, SLOT(handleButton(QAbstractButton*))); - - for (const auto &s : layout) { - QHBoxLayout *hlayout = new QHBoxLayout; - hlayout->setSpacing(0); - - if (main_layout->count() == 1) { - hlayout->addSpacing(90); - } - - for (const QString &p : s) { - KeyButton* btn = new KeyButton(p); - if (p == BACKSPACE_KEY) { - btn->setAutoRepeat(true); - } else if (p == ENTER_KEY) { - btn->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #444444; - } - )"); - } - btn->setFixedHeight(135 + key_spacing_vertical); - btn_group->addButton(btn); - hlayout->addWidget(btn, KEY_STRETCH.value(p, 1)); - } - - if (main_layout->count() == 1) { - hlayout->addSpacing(90); - } - - main_layout->addLayout(hlayout); - } - - setStyleSheet(QString(R"( - QPushButton { - font-size: 75px; - margin-left: %1px; - margin-right: %1px; - margin-top: %2px; - margin-bottom: %2px; - padding: 0px; - border-radius: 10px; - color: #dddddd; - background-color: #444444; - } - QPushButton:pressed { - background-color: #333333; - } - )").arg(key_spacing_vertical / 2).arg(key_spacing_horizontal / 2)); -} - -Keyboard::Keyboard(QWidget *parent) : QFrame(parent) { - main_layout = new QStackedLayout(this); - main_layout->setMargin(0); - - // lowercase - std::vector> lowercase = { - {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"}, - {"a", "s", "d", "f", "g", "h", "j", "k", "l"}, - {"↑", "z", "x", "c", "v", "b", "n", "m", BACKSPACE_KEY}, - {"123", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, lowercase)); - - // uppercase - std::vector> uppercase = { - {"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"}, - {"A", "S", "D", "F", "G", "H", "J", "K", "L"}, - {"↓", "Z", "X", "C", "V", "B", "N", "M", BACKSPACE_KEY}, - {"123", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, uppercase)); - - // numbers + specials - std::vector> numbers = { - {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}, - {"-", "/", ":", ";", "(", ")", "$", "&&", "@", "\""}, - {"#+=", ".", ",", "?", "!", "`", BACKSPACE_KEY}, - {"ABC", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, numbers)); - - // extra specials - std::vector> specials = { - {"[", "]", "{", "}", "#", "%", "^", "*", "+", "="}, - {"_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"}, - {"123", ".", ",", "?", "!", "'", BACKSPACE_KEY}, - {"ABC", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, specials)); - - main_layout->setCurrentIndex(0); -} - -void Keyboard::handleButton(QAbstractButton* btn) { - const QString &key = btn->text(); - if (CONTROL_BUTTONS.contains(key)) { - if (key == "↓" || key == "ABC") { - main_layout->setCurrentIndex(0); - } else if (key == "↑") { - main_layout->setCurrentIndex(1); - } else if (key == "123") { - main_layout->setCurrentIndex(2); - } else if (key == "#+=") { - main_layout->setCurrentIndex(3); - } else if (key == ENTER_KEY) { - main_layout->setCurrentIndex(0); - emit emitEnter(); - } else if (key == BACKSPACE_KEY) { - emit emitBackspace(); - } - } else { - if ("A" <= key && key <= "Z") { - main_layout->setCurrentIndex(0); - } - emit emitKey(key); - } -} diff --git a/selfdrive/ui/qt/widgets/keyboard.h b/selfdrive/ui/qt/widgets/keyboard.h deleted file mode 100644 index efc02d075d99ab..00000000000000 --- a/selfdrive/ui/qt/widgets/keyboard.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -class KeyButton : public QPushButton { - Q_OBJECT - -public: - KeyButton(const QString &text, QWidget *parent = 0); - bool event(QEvent *event) override; -}; - -class KeyboardLayout : public QWidget { - Q_OBJECT - -public: - explicit KeyboardLayout(QWidget* parent, const std::vector>& layout); -}; - -class Keyboard : public QFrame { - Q_OBJECT - -public: - explicit Keyboard(QWidget *parent = 0); - -private: - QStackedLayout* main_layout; - -private slots: - void handleButton(QAbstractButton* m_button); - -signals: - void emitKey(const QString &s); - void emitBackspace(); - void emitEnter(); -}; diff --git a/selfdrive/ui/qt/widgets/offroad_alerts.cc b/selfdrive/ui/qt/widgets/offroad_alerts.cc deleted file mode 100644 index 74ece36d15bb5d..00000000000000 --- a/selfdrive/ui/qt/widgets/offroad_alerts.cc +++ /dev/null @@ -1,127 +0,0 @@ -#include "selfdrive/ui/qt/widgets/offroad_alerts.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -AbstractAlert::AbstractAlert(bool hasRebootBtn, QWidget *parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(50); - main_layout->setSpacing(30); - - QWidget *widget = new QWidget; - scrollable_layout = new QVBoxLayout(widget); - widget->setStyleSheet("background-color: transparent;"); - main_layout->addWidget(new ScrollView(widget)); - - // bottom footer, dismiss + reboot buttons - QHBoxLayout *footer_layout = new QHBoxLayout(); - main_layout->addLayout(footer_layout); - - QPushButton *dismiss_btn = new QPushButton(tr("Close")); - dismiss_btn->setFixedSize(400, 125); - footer_layout->addWidget(dismiss_btn, 0, Qt::AlignBottom | Qt::AlignLeft); - QObject::connect(dismiss_btn, &QPushButton::clicked, this, &AbstractAlert::dismiss); - - snooze_btn = new QPushButton(tr("Snooze Update")); - snooze_btn->setVisible(false); - snooze_btn->setFixedSize(550, 125); - footer_layout->addWidget(snooze_btn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(snooze_btn, &QPushButton::clicked, [=]() { - params.putBool("SnoozeUpdate", true); - }); - QObject::connect(snooze_btn, &QPushButton::clicked, this, &AbstractAlert::dismiss); - snooze_btn->setStyleSheet(R"(color: white; background-color: #4F4F4F;)"); - - if (hasRebootBtn) { - QPushButton *rebootBtn = new QPushButton(tr("Reboot and Update")); - rebootBtn->setFixedSize(600, 125); - footer_layout->addWidget(rebootBtn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(rebootBtn, &QPushButton::clicked, [=]() { Hardware::reboot(); }); - } - - setStyleSheet(R"( - * { - font-size: 48px; - color: white; - } - QFrame { - border-radius: 30px; - background-color: #393939; - } - QPushButton { - color: black; - font-weight: 500; - border-radius: 30px; - background-color: white; - } - )"); -} - -int OffroadAlert::refresh() { - // build widgets for each offroad alert on first refresh - if (alerts.empty()) { - QString json = util::read_file("../controls/lib/alerts_offroad.json").c_str(); - QJsonObject obj = QJsonDocument::fromJson(json.toUtf8()).object(); - - // descending sort labels by severity - std::vector> sorted; - for (auto it = obj.constBegin(); it != obj.constEnd(); ++it) { - sorted.push_back({it.key().toStdString(), it.value()["severity"].toInt()}); - } - std::sort(sorted.begin(), sorted.end(), [=](auto &l, auto &r) { return l.second > r.second; }); - - for (auto &[key, severity] : sorted) { - QLabel *l = new QLabel(this); - alerts[key] = l; - l->setMargin(60); - l->setWordWrap(true); - l->setStyleSheet(QString("background-color: %1").arg(severity ? "#E22C2C" : "#292929")); - scrollable_layout->addWidget(l); - } - scrollable_layout->addStretch(1); - } - - int alertCount = 0; - for (const auto &[key, label] : alerts) { - QString text; - std::string bytes = params.get(key); - if (bytes.size()) { - auto doc_par = QJsonDocument::fromJson(bytes.c_str()); - text = tr(doc_par["text"].toString().toUtf8().data()); - auto extra = doc_par["extra"].toString(); - if (!extra.isEmpty()) { - text = text.arg(extra); - } - } - label->setText(text); - label->setVisible(!text.isEmpty()); - alertCount += !text.isEmpty(); - } - snooze_btn->setVisible(!alerts["Offroad_ConnectivityNeeded"]->text().isEmpty()); - return alertCount; -} - -UpdateAlert::UpdateAlert(QWidget *parent) : AbstractAlert(true, parent) { - releaseNotes = new QLabel(this); - releaseNotes->setWordWrap(true); - releaseNotes->setAlignment(Qt::AlignTop); - scrollable_layout->addWidget(releaseNotes); -} - -bool UpdateAlert::refresh() { - bool updateAvailable = params.getBool("UpdateAvailable"); - if (updateAvailable) { - releaseNotes->setText(params.get("UpdaterNewReleaseNotes").c_str()); - } - return updateAvailable; -} diff --git a/selfdrive/ui/qt/widgets/offroad_alerts.h b/selfdrive/ui/qt/widgets/offroad_alerts.h deleted file mode 100644 index ace2e754561483..00000000000000 --- a/selfdrive/ui/qt/widgets/offroad_alerts.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include - -#include "common/params.h" - -class AbstractAlert : public QFrame { - Q_OBJECT - -protected: - AbstractAlert(bool hasRebootBtn, QWidget *parent = nullptr); - - QPushButton *snooze_btn; - QVBoxLayout *scrollable_layout; - Params params; - -signals: - void dismiss(); -}; - -class UpdateAlert : public AbstractAlert { - Q_OBJECT - -public: - UpdateAlert(QWidget *parent = 0); - bool refresh(); - -private: - QLabel *releaseNotes = nullptr; -}; - -class OffroadAlert : public AbstractAlert { - Q_OBJECT - -public: - explicit OffroadAlert(QWidget *parent = 0) : AbstractAlert(false, parent) {} - int refresh(); - -private: - std::map alerts; -}; diff --git a/selfdrive/ui/qt/widgets/prime.cc b/selfdrive/ui/qt/widgets/prime.cc deleted file mode 100644 index f86258ea4ff957..00000000000000 --- a/selfdrive/ui/qt/widgets/prime.cc +++ /dev/null @@ -1,278 +0,0 @@ -#include "selfdrive/ui/qt/widgets/prime.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "selfdrive/ui/qt/request_repeater.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/wifi.h" - -using qrcodegen::QrCode; - -PairingQRWidget::PairingQRWidget(QWidget* parent) : QWidget(parent) { - timer = new QTimer(this); - connect(timer, &QTimer::timeout, this, &PairingQRWidget::refresh); -} - -void PairingQRWidget::showEvent(QShowEvent *event) { - refresh(); - timer->start(5 * 60 * 1000); - device()->setOffroadBrightness(100); -} - -void PairingQRWidget::hideEvent(QHideEvent *event) { - timer->stop(); - device()->setOffroadBrightness(BACKLIGHT_OFFROAD); -} - -void PairingQRWidget::refresh() { - QString pairToken = CommaApi::create_jwt({{"pair", true}}); - QString qrString = "https://connect.comma.ai/?pair=" + pairToken; - this->updateQrCode(qrString); - update(); -} - -void PairingQRWidget::updateQrCode(const QString &text) { - QrCode qr = QrCode::encodeText(text.toUtf8().data(), QrCode::Ecc::LOW); - qint32 sz = qr.getSize(); - QImage im(sz, sz, QImage::Format_RGB32); - - QRgb black = qRgb(0, 0, 0); - QRgb white = qRgb(255, 255, 255); - for (int y = 0; y < sz; y++) { - for (int x = 0; x < sz; x++) { - im.setPixel(x, y, qr.getModule(x, y) ? black : white); - } - } - - // Integer division to prevent anti-aliasing - int final_sz = ((width() / sz) - 1) * sz; - img = QPixmap::fromImage(im.scaled(final_sz, final_sz, Qt::KeepAspectRatio), Qt::MonoOnly); -} - -void PairingQRWidget::paintEvent(QPaintEvent *e) { - QPainter p(this); - p.fillRect(rect(), Qt::white); - - QSize s = (size() - img.size()) / 2; - p.drawPixmap(s.width(), s.height(), img); -} - - -PairingPopup::PairingPopup(QWidget *parent) : DialogBase(parent) { - QHBoxLayout *hlayout = new QHBoxLayout(this); - hlayout->setContentsMargins(0, 0, 0, 0); - hlayout->setSpacing(0); - - setStyleSheet("PairingPopup { background-color: #E0E0E0; }"); - - // text - QVBoxLayout *vlayout = new QVBoxLayout(); - vlayout->setContentsMargins(85, 70, 50, 70); - vlayout->setSpacing(50); - hlayout->addLayout(vlayout, 1); - { - QPushButton *close = new QPushButton(QIcon(":/icons/close.svg"), "", this); - close->setIconSize(QSize(80, 80)); - close->setStyleSheet("border: none;"); - vlayout->addWidget(close, 0, Qt::AlignLeft); - QObject::connect(close, &QPushButton::clicked, this, &QDialog::reject); - - vlayout->addSpacing(30); - - QLabel *title = new QLabel(tr("Pair your device to your comma account"), this); - title->setStyleSheet("font-size: 75px; color: black;"); - title->setWordWrap(true); - vlayout->addWidget(title); - - QLabel *instructions = new QLabel(QString(R"( -
    -
  1. %1
  2. -
  3. %2
  4. -
  5. %3
  6. -
- )").arg(tr("Go to https://connect.comma.ai on your phone")) - .arg(tr("Click \"add new device\" and scan the QR code on the right")) - .arg(tr("Bookmark connect.comma.ai to your home screen to use it like an app")), this); - - instructions->setStyleSheet("font-size: 47px; font-weight: bold; color: black;"); - instructions->setWordWrap(true); - vlayout->addWidget(instructions); - - vlayout->addStretch(); - } - - // QR code - PairingQRWidget *qr = new PairingQRWidget(this); - hlayout->addWidget(qr, 1); -} - - -PrimeUserWidget::PrimeUserWidget(QWidget *parent) : QFrame(parent) { - setObjectName("primeWidget"); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setContentsMargins(56, 40, 56, 40); - mainLayout->setSpacing(20); - - QLabel *subscribed = new QLabel(tr("✓ SUBSCRIBED")); - subscribed->setStyleSheet("font-size: 41px; font-weight: bold; color: #86FF4E;"); - mainLayout->addWidget(subscribed); - - QLabel *commaPrime = new QLabel(tr("comma prime")); - commaPrime->setStyleSheet("font-size: 75px; font-weight: bold;"); - mainLayout->addWidget(commaPrime); -} - - -PrimeAdWidget::PrimeAdWidget(QWidget* parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(80, 90, 80, 60); - main_layout->setSpacing(0); - - QLabel *upgrade = new QLabel(tr("Upgrade Now")); - upgrade->setStyleSheet("font-size: 75px; font-weight: bold;"); - main_layout->addWidget(upgrade, 0, Qt::AlignTop); - main_layout->addSpacing(50); - - QLabel *description = new QLabel(tr("Become a comma prime member at connect.comma.ai")); - description->setStyleSheet("font-size: 56px; font-weight: light; color: white;"); - description->setWordWrap(true); - main_layout->addWidget(description, 0, Qt::AlignTop); - - main_layout->addStretch(); - - QLabel *features = new QLabel(tr("PRIME FEATURES:")); - features->setStyleSheet("font-size: 41px; font-weight: bold; color: #E5E5E5;"); - main_layout->addWidget(features, 0, Qt::AlignBottom); - main_layout->addSpacing(30); - - QVector bullets = {tr("Remote access"), tr("24/7 LTE connectivity"), tr("1 year of drive storage"), tr("Remote snapshots")}; - for (auto &b : bullets) { - const QString check = "✓ "; - QLabel *l = new QLabel(check + b); - l->setAlignment(Qt::AlignLeft); - l->setStyleSheet("font-size: 50px; margin-bottom: 15px;"); - main_layout->addWidget(l, 0, Qt::AlignBottom); - } - - setStyleSheet(R"( - PrimeAdWidget { - border-radius: 10px; - background-color: #333333; - } - )"); -} - - -SetupWidget::SetupWidget(QWidget* parent) : QFrame(parent) { - mainLayout = new QStackedWidget; - - // Unpaired, registration prompt layout - - QFrame* finishRegistration = new QFrame; - finishRegistration->setObjectName("primeWidget"); - QVBoxLayout* finishRegistationLayout = new QVBoxLayout(finishRegistration); - finishRegistationLayout->setSpacing(38); - finishRegistationLayout->setContentsMargins(64, 48, 64, 48); - - QLabel* registrationTitle = new QLabel(tr("Finish Setup")); - registrationTitle->setStyleSheet("font-size: 75px; font-weight: bold;"); - finishRegistationLayout->addWidget(registrationTitle); - - QLabel* registrationDescription = new QLabel(tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.")); - registrationDescription->setWordWrap(true); - registrationDescription->setStyleSheet("font-size: 50px; font-weight: light;"); - finishRegistationLayout->addWidget(registrationDescription); - - finishRegistationLayout->addStretch(); - - QPushButton* pair = new QPushButton(tr("Pair device")); - pair->setStyleSheet(R"( - QPushButton { - font-size: 55px; - font-weight: 500; - border-radius: 10px; - background-color: #465BEA; - padding: 64px; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - finishRegistationLayout->addWidget(pair); - - popup = new PairingPopup(this); - QObject::connect(pair, &QPushButton::clicked, popup, &PairingPopup::exec); - - mainLayout->addWidget(finishRegistration); - - // build stacked layout - QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(0, 0, 0, 0); - outer_layout->addWidget(mainLayout); - - QWidget *content = new QWidget; - QVBoxLayout *content_layout = new QVBoxLayout(content); - content_layout->setContentsMargins(0, 0, 0, 0); - content_layout->setSpacing(30); - - WiFiPromptWidget *wifi_prompt = new WiFiPromptWidget; - QObject::connect(wifi_prompt, &WiFiPromptWidget::openSettings, this, &SetupWidget::openSettings); - content_layout->addWidget(wifi_prompt); - content_layout->addStretch(); - - mainLayout->addWidget(content); - - mainLayout->setCurrentIndex(1); - - setStyleSheet(R"( - #primeWidget { - border-radius: 10px; - background-color: #333333; - } - )"); - - // Retain size while hidden - QSizePolicy sp_retain = sizePolicy(); - sp_retain.setRetainSizeWhenHidden(true); - setSizePolicy(sp_retain); - - // set up API requests - if (auto dongleId = getDongleId()) { - QString url = CommaApi::BASE_URL + "/v1.1/devices/" + *dongleId + "/"; - RequestRepeater* repeater = new RequestRepeater(this, url, "ApiCache_Device", 5); - - QObject::connect(repeater, &RequestRepeater::requestDone, this, &SetupWidget::replyFinished); - } -} - -void SetupWidget::replyFinished(const QString &response, bool success) { - if (!success) return; - - QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); - if (doc.isNull()) { - qDebug() << "JSON Parse failed on getting pairing and prime status"; - return; - } - - QJsonObject json = doc.object(); - bool is_paired = json["is_paired"].toBool(); - PrimeType prime_type = static_cast(json["prime_type"].toInt()); - uiState()->setPrimeType(is_paired ? prime_type : PrimeType::PRIME_TYPE_UNPAIRED); - - if (!is_paired) { - mainLayout->setCurrentIndex(0); - } else { - popup->reject(); - mainLayout->setCurrentIndex(1); - } -} diff --git a/selfdrive/ui/qt/widgets/prime.h b/selfdrive/ui/qt/widgets/prime.h deleted file mode 100644 index eac71bcddb12b7..00000000000000 --- a/selfdrive/ui/qt/widgets/prime.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "selfdrive/ui/qt/widgets/input.h" - -// pairing QR code -class PairingQRWidget : public QWidget { - Q_OBJECT - -public: - explicit PairingQRWidget(QWidget* parent = 0); - void paintEvent(QPaintEvent*) override; - -private: - QPixmap img; - QTimer *timer; - void updateQrCode(const QString &text); - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - -private slots: - void refresh(); -}; - - -// pairing popup widget -class PairingPopup : public DialogBase { - Q_OBJECT - -public: - explicit PairingPopup(QWidget* parent); -}; - - -// widget for paired users with prime -class PrimeUserWidget : public QFrame { - Q_OBJECT - -public: - explicit PrimeUserWidget(QWidget* parent = 0); -}; - - -// widget for paired users without prime -class PrimeAdWidget : public QFrame { - Q_OBJECT -public: - explicit PrimeAdWidget(QWidget* parent = 0); -}; - - -// container widget -class SetupWidget : public QFrame { - Q_OBJECT - -public: - explicit SetupWidget(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - -private: - PairingPopup *popup; - QStackedWidget *mainLayout; - -private slots: - void replyFinished(const QString &response, bool success); -}; diff --git a/selfdrive/ui/qt/widgets/scrollview.cc b/selfdrive/ui/qt/widgets/scrollview.cc deleted file mode 100644 index 978bf83a63b170..00000000000000 --- a/selfdrive/ui/qt/widgets/scrollview.cc +++ /dev/null @@ -1,49 +0,0 @@ -#include "selfdrive/ui/qt/widgets/scrollview.h" - -#include -#include - -// TODO: disable horizontal scrolling and resize - -ScrollView::ScrollView(QWidget *w, QWidget *parent) : QScrollArea(parent) { - setWidget(w); - setWidgetResizable(true); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setStyleSheet("background-color: transparent; border:none"); - - QString style = R"( - QScrollBar:vertical { - border: none; - background: transparent; - width: 10px; - margin: 0; - } - QScrollBar::handle:vertical { - min-height: 0px; - border-radius: 5px; - background-color: white; - } - QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { - height: 0px; - } - QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { - background: none; - } - )"; - verticalScrollBar()->setStyleSheet(style); - horizontalScrollBar()->setStyleSheet(style); - - QScroller *scroller = QScroller::scroller(this->viewport()); - QScrollerProperties sp = scroller->scrollerProperties(); - - sp.setScrollMetric(QScrollerProperties::VerticalOvershootPolicy, QVariant::fromValue(QScrollerProperties::OvershootAlwaysOff)); - sp.setScrollMetric(QScrollerProperties::HorizontalOvershootPolicy, QVariant::fromValue(QScrollerProperties::OvershootAlwaysOff)); - sp.setScrollMetric(QScrollerProperties::MousePressEventDelay, 0.01); - scroller->grabGesture(this->viewport(), QScroller::LeftMouseButtonGesture); - scroller->setScrollerProperties(sp); -} - -void ScrollView::hideEvent(QHideEvent *e) { - verticalScrollBar()->setValue(0); -} diff --git a/selfdrive/ui/qt/widgets/scrollview.h b/selfdrive/ui/qt/widgets/scrollview.h deleted file mode 100644 index 024331aa39dd2e..00000000000000 --- a/selfdrive/ui/qt/widgets/scrollview.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class ScrollView : public QScrollArea { - Q_OBJECT - -public: - explicit ScrollView(QWidget *w = nullptr, QWidget *parent = nullptr); -protected: - void hideEvent(QHideEvent *e) override; -}; diff --git a/selfdrive/ui/qt/widgets/ssh_keys.cc b/selfdrive/ui/qt/widgets/ssh_keys.cc deleted file mode 100644 index 26743952de3854..00000000000000 --- a/selfdrive/ui/qt/widgets/ssh_keys.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include "selfdrive/ui/qt/widgets/ssh_keys.h" - -#include "common/params.h" -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/qt/widgets/input.h" - -SshControl::SshControl() : - ButtonControl(tr("SSH Keys"), "", tr("Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username " - "other than your own. A comma employee will NEVER ask you to add their GitHub username.")) { - - QObject::connect(this, &ButtonControl::clicked, [=]() { - if (text() == tr("ADD")) { - QString username = InputDialog::getText(tr("Enter your GitHub username"), this); - if (username.length() > 0) { - setText(tr("LOADING")); - setEnabled(false); - getUserKeys(username); - } - } else { - params.remove("GithubUsername"); - params.remove("GithubSshKeys"); - refresh(); - } - }); - - refresh(); -} - -void SshControl::refresh() { - QString param = QString::fromStdString(params.get("GithubSshKeys")); - if (param.length()) { - setValue(QString::fromStdString(params.get("GithubUsername"))); - setText(tr("REMOVE")); - } else { - setValue(""); - setText(tr("ADD")); - } - setEnabled(true); -} - -void SshControl::getUserKeys(const QString &username) { - HttpRequest *request = new HttpRequest(this, false); - QObject::connect(request, &HttpRequest::requestDone, [=](const QString &resp, bool success) { - if (success) { - if (!resp.isEmpty()) { - params.put("GithubUsername", username.toStdString()); - params.put("GithubSshKeys", resp.toStdString()); - } else { - ConfirmationDialog::alert(tr("Username '%1' has no keys on GitHub").arg(username), this); - } - } else { - if (request->timeout()) { - ConfirmationDialog::alert(tr("Request timed out"), this); - } else { - ConfirmationDialog::alert(tr("Username '%1' doesn't exist on GitHub").arg(username), this); - } - } - - refresh(); - request->deleteLater(); - }); - - request->sendRequest("https://github.com/" + username + ".keys"); -} diff --git a/selfdrive/ui/qt/widgets/ssh_keys.h b/selfdrive/ui/qt/widgets/ssh_keys.h deleted file mode 100644 index 920bd651e2dcd0..00000000000000 --- a/selfdrive/ui/qt/widgets/ssh_keys.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/widgets/controls.h" - -// SSH enable toggle -class SshToggle : public ToggleControl { - Q_OBJECT - -public: - SshToggle() : ToggleControl(tr("Enable SSH"), "", "", Hardware::get_ssh_enabled()) { - QObject::connect(this, &SshToggle::toggleFlipped, [=](bool state) { - Hardware::set_ssh_enabled(state); - }); - } -}; - -// SSH key management widget -class SshControl : public ButtonControl { - Q_OBJECT - -public: - SshControl(); - -private: - Params params; - - void refresh(); - void getUserKeys(const QString &username); -}; diff --git a/selfdrive/ui/qt/widgets/toggle.cc b/selfdrive/ui/qt/widgets/toggle.cc deleted file mode 100644 index 82302ad5bc78f3..00000000000000 --- a/selfdrive/ui/qt/widgets/toggle.cc +++ /dev/null @@ -1,83 +0,0 @@ -#include "selfdrive/ui/qt/widgets/toggle.h" - -#include - -Toggle::Toggle(QWidget *parent) : QAbstractButton(parent), -_height(80), -_height_rect(60), -on(false), -_anim(new QPropertyAnimation(this, "offset_circle", this)) -{ - _radius = _height / 2; - _x_circle = _radius; - _y_circle = _radius; - _y_rect = (_height - _height_rect)/2; - circleColor = QColor(0xffffff); // placeholder - green = QColor(0xffffff); // placeholder - setEnabled(true); -} - -void Toggle::paintEvent(QPaintEvent *e) { - this->setFixedHeight(_height); - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing, true); - - // Draw toggle background left - p.setBrush(green); - p.drawRoundedRect(QRect(0, _y_rect, _x_circle + _radius, _height_rect), _height_rect/2, _height_rect/2); - - // Draw toggle background right - p.setBrush(QColor(0x393939)); - p.drawRoundedRect(QRect(_x_circle - _radius, _y_rect, width() - (_x_circle - _radius), _height_rect), _height_rect/2, _height_rect/2); - - // Draw toggle circle - p.setBrush(circleColor); - p.drawEllipse(QRectF(_x_circle - _radius, _y_circle - _radius, 2 * _radius, 2 * _radius)); -} - -void Toggle::mouseReleaseEvent(QMouseEvent *e) { - if (!enabled) { - return; - } - const int left = _radius; - const int right = width() - _radius; - if ((_x_circle != left && _x_circle != right) || !this->rect().contains(e->localPos().toPoint())) { - // If mouse release isn't in rect or animation is running, don't parse touch events - return; - } - if (e->button() & Qt::LeftButton) { - togglePosition(); - emit stateChanged(on); - } -} - -void Toggle::togglePosition() { - on = !on; - const int left = _radius; - const int right = width() - _radius; - _anim->setStartValue(on ? left + immediateOffset : right - immediateOffset); - _anim->setEndValue(on ? right : left); - _anim->setDuration(animation_duration); - _anim->start(); - repaint(); -} - -void Toggle::enterEvent(QEvent *e) { - QAbstractButton::enterEvent(e); -} - -bool Toggle::getEnabled() { - return enabled; -} - -void Toggle::setEnabled(bool value) { - enabled = value; - if (value) { - circleColor.setRgb(0xfafafa); - green.setRgb(0x33ab4c); - } else { - circleColor.setRgb(0x888888); - green.setRgb(0x227722); - } -} diff --git a/selfdrive/ui/qt/widgets/toggle.h b/selfdrive/ui/qt/widgets/toggle.h deleted file mode 100644 index e7263a008fa183..00000000000000 --- a/selfdrive/ui/qt/widgets/toggle.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include -#include - -class Toggle : public QAbstractButton { - Q_OBJECT - Q_PROPERTY(int offset_circle READ offset_circle WRITE set_offset_circle CONSTANT) - -public: - Toggle(QWidget* parent = nullptr); - void togglePosition(); - bool on; - int animation_duration = 150; - int immediateOffset = 0; - int offset_circle() const { - return _x_circle; - } - - void set_offset_circle(int o) { - _x_circle = o; - update(); - } - bool getEnabled(); - void setEnabled(bool value); - -protected: - void paintEvent(QPaintEvent*) override; - void mouseReleaseEvent(QMouseEvent*) override; - void enterEvent(QEvent*) override; - -private: - QColor circleColor; - QColor green; - bool enabled = true; - int _x_circle, _y_circle; - int _height, _radius; - int _height_rect, _y_rect; - QPropertyAnimation *_anim = nullptr; - -signals: - void stateChanged(bool new_state); -}; diff --git a/selfdrive/ui/qt/widgets/wifi.cc b/selfdrive/ui/qt/widgets/wifi.cc deleted file mode 100644 index 9c5289a22d8c29..00000000000000 --- a/selfdrive/ui/qt/widgets/wifi.cc +++ /dev/null @@ -1,103 +0,0 @@ -#include "selfdrive/ui/qt/widgets/wifi.h" - -#include -#include -#include -#include - -WiFiPromptWidget::WiFiPromptWidget(QWidget *parent) : QFrame(parent) { - stack = new QStackedLayout(this); - - // Setup Wi-Fi - QFrame *setup = new QFrame; - QVBoxLayout *setup_layout = new QVBoxLayout(setup); - setup_layout->setContentsMargins(56, 40, 56, 40); - setup_layout->setSpacing(20); - { - QHBoxLayout *title_layout = new QHBoxLayout; - title_layout->setSpacing(32); - { - QLabel *icon = new QLabel; - QPixmap pixmap("../assets/offroad/icon_wifi_strength_full.svg"); - icon->setPixmap(pixmap.scaledToWidth(80, Qt::SmoothTransformation)); - title_layout->addWidget(icon); - - QLabel *title = new QLabel(tr("Setup Wi-Fi")); - title->setStyleSheet("font-size: 64px; font-weight: 600;"); - title_layout->addWidget(title); - title_layout->addStretch(); - } - setup_layout->addLayout(title_layout); - - QLabel *desc = new QLabel(tr("Connect to Wi-Fi to upload driving data and help improve openpilot")); - desc->setStyleSheet("font-size: 40px; font-weight: 400;"); - desc->setWordWrap(true); - setup_layout->addWidget(desc); - - QPushButton *settings_btn = new QPushButton(tr("Open Settings")); - connect(settings_btn, &QPushButton::clicked, [=]() { emit openSettings(1); }); - settings_btn->setStyleSheet(R"( - QPushButton { - font-size: 48px; - font-weight: 500; - border-radius: 10px; - background-color: #465BEA; - padding: 32px; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - setup_layout->addWidget(settings_btn); - } - stack->addWidget(setup); - - // Uploading data - QWidget *uploading = new QWidget; - QVBoxLayout *uploading_layout = new QVBoxLayout(uploading); - uploading_layout->setContentsMargins(64, 56, 64, 56); - uploading_layout->setSpacing(36); - { - QHBoxLayout *title_layout = new QHBoxLayout; - { - QLabel *title = new QLabel(tr("Ready to upload")); - title->setStyleSheet("font-size: 64px; font-weight: 600;"); - title->setWordWrap(true); - title->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); - title_layout->addWidget(title); - title_layout->addStretch(); - - QLabel *icon = new QLabel; - QPixmap pixmap("../assets/offroad/icon_wifi_uploading.svg"); - icon->setPixmap(pixmap.scaledToWidth(120, Qt::SmoothTransformation)); - title_layout->addWidget(icon); - } - uploading_layout->addLayout(title_layout); - - QLabel *desc = new QLabel(tr("Training data will be pulled periodically while your device is on Wi-Fi")); - desc->setStyleSheet("font-size: 48px; font-weight: 400;"); - desc->setWordWrap(true); - uploading_layout->addWidget(desc); - } - stack->addWidget(uploading); - - setStyleSheet(R"( - WiFiPromptWidget { - background-color: #333333; - border-radius: 10px; - } - )"); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &WiFiPromptWidget::updateState); -} - -void WiFiPromptWidget::updateState(const UIState &s) { - if (!isVisible()) return; - - auto &sm = *(s.sm); - - auto network_type = sm["deviceState"].getDeviceState().getNetworkType(); - auto uploading = network_type == cereal::DeviceState::NetworkType::WIFI || - network_type == cereal::DeviceState::NetworkType::ETHERNET; - stack->setCurrentIndex(uploading ? 1 : 0); -} diff --git a/selfdrive/ui/qt/widgets/wifi.h b/selfdrive/ui/qt/widgets/wifi.h deleted file mode 100644 index 60c865f2b89a9c..00000000000000 --- a/selfdrive/ui/qt/widgets/wifi.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "selfdrive/ui/ui.h" - -class WiFiPromptWidget : public QFrame { - Q_OBJECT - -public: - explicit WiFiPromptWidget(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - -public slots: - void updateState(const UIState &s); - -protected: - QStackedLayout *stack; -}; diff --git a/selfdrive/ui/qt/window.cc b/selfdrive/ui/qt/window.cc deleted file mode 100644 index 6b579fcc5dc80c..00000000000000 --- a/selfdrive/ui/qt/window.cc +++ /dev/null @@ -1,98 +0,0 @@ -#include "selfdrive/ui/qt/window.h" - -#include - -#include "system/hardware/hw.h" - -MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { - main_layout = new QStackedLayout(this); - main_layout->setMargin(0); - - homeWindow = new HomeWindow(this); - main_layout->addWidget(homeWindow); - QObject::connect(homeWindow, &HomeWindow::openSettings, this, &MainWindow::openSettings); - QObject::connect(homeWindow, &HomeWindow::closeSettings, this, &MainWindow::closeSettings); - - settingsWindow = new SettingsWindow(this); - main_layout->addWidget(settingsWindow); - QObject::connect(settingsWindow, &SettingsWindow::closeSettings, this, &MainWindow::closeSettings); - QObject::connect(settingsWindow, &SettingsWindow::reviewTrainingGuide, [=]() { - onboardingWindow->showTrainingGuide(); - main_layout->setCurrentWidget(onboardingWindow); - }); - QObject::connect(settingsWindow, &SettingsWindow::showDriverView, [=] { - homeWindow->showDriverView(true); - }); - - onboardingWindow = new OnboardingWindow(this); - main_layout->addWidget(onboardingWindow); - QObject::connect(onboardingWindow, &OnboardingWindow::onboardingDone, [=]() { - main_layout->setCurrentWidget(homeWindow); - }); - if (!onboardingWindow->completed()) { - main_layout->setCurrentWidget(onboardingWindow); - } - - QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - if (!offroad) { - closeSettings(); - } - }); - QObject::connect(device(), &Device::interactiveTimeout, [=]() { - if (main_layout->currentWidget() == settingsWindow) { - closeSettings(); - } - }); - - // load fonts - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Black.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Bold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-ExtraBold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-ExtraLight.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Medium.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Regular.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-SemiBold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Thin.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/JetBrainsMono-Medium.ttf"); - - // no outline to prevent the focus rectangle - setStyleSheet(R"( - * { - font-family: Inter; - outline: none; - } - )"); - setAttribute(Qt::WA_NoSystemBackground); -} - -void MainWindow::openSettings(int index, const QString ¶m) { - main_layout->setCurrentWidget(settingsWindow); - settingsWindow->setCurrentPanel(index, param); -} - -void MainWindow::closeSettings() { - main_layout->setCurrentWidget(homeWindow); - - if (uiState()->scene.started) { - homeWindow->showSidebar(false); - } -} - -bool MainWindow::eventFilter(QObject *obj, QEvent *event) { - bool ignore = false; - switch (event->type()) { - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - case QEvent::TouchEnd: - case QEvent::MouseButtonPress: - case QEvent::MouseMove: { - // ignore events when device is awakened by resetInteractiveTimeout - ignore = !device()->isAwake(); - device()->resetInteractiveTimeout(); - break; - } - default: - break; - } - return ignore; -} diff --git a/selfdrive/ui/qt/window.h b/selfdrive/ui/qt/window.h deleted file mode 100644 index 05b61e1f762bff..00000000000000 --- a/selfdrive/ui/qt/window.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include -#include - -#include "selfdrive/ui/qt/home.h" -#include "selfdrive/ui/qt/offroad/onboarding.h" -#include "selfdrive/ui/qt/offroad/settings.h" - -class MainWindow : public QWidget { - Q_OBJECT - -public: - explicit MainWindow(QWidget *parent = 0); - -private: - bool eventFilter(QObject *obj, QEvent *event) override; - void openSettings(int index = 0, const QString ¶m = ""); - void closeSettings(); - - QStackedLayout *main_layout; - HomeWindow *homeWindow; - SettingsWindow *settingsWindow; - OnboardingWindow *onboardingWindow; -}; diff --git a/selfdrive/ui/radar/__init__.py b/selfdrive/ui/radar/__init__.py new file mode 100644 index 00000000000000..c4306147ae75c0 --- /dev/null +++ b/selfdrive/ui/radar/__init__.py @@ -0,0 +1,3 @@ +from openpilot.selfdrive.ui.radar.bosch_status import BoschRadarMonitor, BoschRadarStatus, RadarTrack + +__all__ = ["BoschRadarMonitor", "BoschRadarStatus", "RadarTrack"] diff --git a/selfdrive/ui/radar/bosch_status.py b/selfdrive/ui/radar/bosch_status.py new file mode 100644 index 00000000000000..4bdf7f3ebf73bd --- /dev/null +++ b/selfdrive/ui/radar/bosch_status.py @@ -0,0 +1,258 @@ +"""Live Bosch radar health from cereal CAN + liveTracks. + +The radar interface already owns track lifecycle. This module only +decodes what a driver needs to see: ECU lamps, the 0x501 alert matrix, +the GTW identity bytes we are sending, and whether the published table +has stopped changing. +""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass + +RADAR_BUS = 1 +ADDR_SGU = 0x301 +ADDR_POINT0 = 0x310 +ADDR_ALERT = 0x501 +ADDR_CAR_CONFIG = 0x2A9 +ADDR_VIN_FEED = 0x2B9 +ADDR_VIN_HOST = 0x560 + +# DBC TeslaRadarSguInfo / TeslaRadarAlertMatrix, little-endian @1+. +SGU_HW_FAIL_BIT = 45 +SGU_FAIL_BIT = 46 +SGU_DIRTY_BIT = 44 + +ALERT_BITS: tuple[tuple[int, str], ...] = ( + (3, "adjustmentNotDone"), + (4, "adjustmentReq"), + (5, "adjustmentNotOk"), + (6, "sensorBlinded"), + (8, "configMismatch"), + (11, "espMIA"), + (12, "gtwMIA"), + (13, "sccmMIA"), + (36, "vinValidity"), + (41, "xwdValidity"), + (60, "radPositionMismatch"), + (61, "strRackMismatch"), +) + +FREEZE_HOLD_S = 5.0 +FREEZE_MIN_TRACKS = 4 +ALIGN_D_MIN = 2.5 +ALIGN_D_MAX = 14.5 +ALIGN_Y_MAX = 1.0 + + +def radar_bus(src: int) -> bool: + return (int(src) & 0x7F) == RADAR_BUS + + +def _bit(dat: bytes, index: int) -> bool: + byte_i, bit_i = divmod(index, 8) + if byte_i >= len(dat): + return False + return bool((dat[byte_i] >> bit_i) & 1) + + +def decode_car_config(dat: bytes) -> tuple[bool, int, int]: + lo = int.from_bytes(dat[:4], "little") + hi = int.from_bytes(dat[4:8], "little") if len(dat) >= 8 else 0 + return bool(lo & 0x08), (hi >> 4) & 0x03, (hi >> 12) & 0x07 + + +def vin_mux_chars(dat: bytes) -> tuple[int, tuple[str, ...]] | None: + if not dat: + return None + rec = dat[0] + if rec == 0x10 and len(dat) >= 8: + return 0, tuple(chr(b) if 32 <= b < 127 else "?" for b in dat[5:8]) + if rec == 0x11 and len(dat) >= 8: + return 3, tuple(chr(b) if 32 <= b < 127 else "?" for b in dat[1:8]) + if rec == 0x12 and len(dat) >= 8: + return 10, tuple(chr(b) if 32 <= b < 127 else "?" for b in dat[1:8]) + return None + + +@dataclass(frozen=True) +class RadarTrack: + track_id: int + d_rel: float + y_rel: float + v_rel: float + measured: bool + + +@dataclass(frozen=True) +class BoschRadarStatus: + tracks: tuple[RadarTrack, ...] = () + hw_fail: bool = False + sgu_fail: bool = False + dirty: bool = False + alerts: tuple[str, ...] = () + table_frozen: bool = False + can_error: bool = False + radar_fault: bool = False + radar_unavailable: bool = False + awd: bool | None = None + position: int | None = None + epas_type: int | None = None + vin: str = "" + unique_raw: int = 0 + vin_stream_complete: bool = False + gtw_live: bool = False + last_sgu_age_s: float | None = None + last_tracks_age_s: float | None = None + last_raw_age_s: float | None = None + vin_f190: str = "" + vin_chassis: str = "" + + @property + def health_label(self) -> str: + if not self.gtw_live and not self.tracks: + return "WAIT GTW" if self.vin_stream_complete else "WAIT VIN" + if self.radar_fault or self.hw_fail: + return "FAULT" + if self.table_frozen: + return "FROZEN" + if self.can_error: + return "CAN" + if "vinValidity" in self.alerts or "xwdValidity" in self.alerts or "radPositionMismatch" in self.alerts: + return "REJECT" + if self.sgu_fail: + return "SGU" + if self.radar_unavailable: + return "UNAVAIL" + if not self.tracks: + return "NO TRACKS" + return "LIVE" + + @property + def health_ok(self) -> bool: + return self.health_label == "LIVE" + + +class BoschRadarMonitor: + def __init__(self): + self._vin = ["."] * 17 + self._status = BoschRadarStatus() + self._fingerprints: deque[tuple[float, tuple]] = deque() + self._raw_seen: deque[tuple[float, bytes]] = deque() + self._last_sgu_t: float | None = None + self._last_tracks_t: float | None = None + self._vin_bits = 0 + self._gtw_live = False + + @property + def status(self) -> BoschRadarStatus: + return self._status + + def update(self, now: float, can_messages, live_tracks=None) -> BoschRadarStatus: + hw_fail = self._status.hw_fail + sgu_fail = self._status.sgu_fail + dirty = self._status.dirty + alerts = self._status.alerts + awd = self._status.awd + position = self._status.position + epas_type = self._status.epas_type + can_error = self._status.can_error + radar_fault = self._status.radar_fault + radar_unavailable = self._status.radar_unavailable + tracks = self._status.tracks + + for addr, dat, src in can_messages: + dat = bytes(dat) + if addr == ADDR_VIN_HOST and dat: + rec = dat[0] + if rec == 0: + self._vin_bits |= 1 + elif rec == 1: + self._vin_bits |= 2 + elif rec == 2: + self._vin_bits |= 4 + continue + if not radar_bus(src): + continue + if addr == ADDR_SGU: + hw_fail = _bit(dat, SGU_HW_FAIL_BIT) + sgu_fail = _bit(dat, SGU_FAIL_BIT) + dirty = _bit(dat, SGU_DIRTY_BIT) + self._last_sgu_t = now + elif addr == ADDR_ALERT: + alerts = tuple(name for bit_i, name in ALERT_BITS if _bit(dat, bit_i)) + elif addr == ADDR_CAR_CONFIG and len(dat) >= 8: + awd, position, epas_type = decode_car_config(dat) + self._gtw_live = True + elif addr == ADDR_VIN_FEED: + parsed = vin_mux_chars(dat) + if parsed is not None: + start, chars = parsed + for i, ch in enumerate(chars): + if start + i < 17: + self._vin[start + i] = ch + elif addr == ADDR_POINT0: + self._raw_seen.append((now, dat[:6])) + + while self._raw_seen and now - self._raw_seen[0][0] > FREEZE_HOLD_S: + self._raw_seen.popleft() + + if live_tracks is not None: + errors = getattr(live_tracks, "errors", None) + if errors is not None: + can_error = bool(getattr(errors, "canError", False)) + radar_fault = bool(getattr(errors, "radarFault", False)) + radar_unavailable = bool(getattr(errors, "radarUnavailableTemporary", False)) + points = getattr(live_tracks, "points", ()) + tracks = tuple( + RadarTrack( + track_id=int(p.trackId), + d_rel=float(p.dRel), + y_rel=float(p.yRel), + v_rel=float(p.vRel), + measured=bool(p.measured), + ) + for p in points + ) + self._last_tracks_t = now + fingerprint = tuple((t.track_id, round(t.d_rel, 1), round(t.v_rel, 1)) for t in tracks) + self._fingerprints.append((now, fingerprint)) + + while self._fingerprints and now - self._fingerprints[0][0] > FREEZE_HOLD_S: + self._fingerprints.popleft() + + table_frozen = False + if self._fingerprints and len(tracks) >= FREEZE_MIN_TRACKS: + span = now - self._fingerprints[0][0] + same = all(fp == self._fingerprints[-1][1] for _, fp in self._fingerprints) + table_frozen = span >= FREEZE_HOLD_S - 1e-3 and same and bool(self._fingerprints[-1][1]) + + unique_raw = len({payload for _, payload in self._raw_seen}) + last_raw_age_s = None if not self._raw_seen else now - self._raw_seen[-1][0] + vin = "".join(self._vin) + if vin == "." * 17: + vin = "" + + self._status = BoschRadarStatus( + tracks=tracks, + hw_fail=hw_fail, + sgu_fail=sgu_fail, + dirty=dirty, + alerts=alerts, + table_frozen=table_frozen, + can_error=can_error, + radar_fault=radar_fault, + radar_unavailable=radar_unavailable, + awd=awd, + position=position, + epas_type=epas_type, + vin=vin, + unique_raw=unique_raw, + vin_stream_complete=self._vin_bits == 7, + gtw_live=self._gtw_live, + last_sgu_age_s=None if self._last_sgu_t is None else now - self._last_sgu_t, + last_tracks_age_s=None if self._last_tracks_t is None else now - self._last_tracks_t, + last_raw_age_s=last_raw_age_s, + ) + return self._status diff --git a/selfdrive/ui/radar/preview_radar_ui.py b/selfdrive/ui/radar/preview_radar_ui.py new file mode 100755 index 00000000000000..6399d628f838ed --- /dev/null +++ b/selfdrive/ui/radar/preview_radar_ui.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Render the radar HUD and monitor dialog to PNGs for visual check.""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +os.environ.setdefault("OFFSCREEN", "1") +os.environ.setdefault("BIG", "1") +os.environ.setdefault("SCALE", "1") + +from dataclasses import replace + +from openpilot.selfdrive.ui.radar.bosch_status import BoschRadarStatus, RadarTrack +from openpilot.selfdrive.ui.radar.radar_view import RadarHudOverlay, RadarMonitorDialog, radar_hud_rect +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +import pyray as rl + + +def _status(label_tracks=True) -> BoschRadarStatus: + tracks = ( + RadarTrack(12, 18.4, -0.31, -1.2, True), + RadarTrack(15, 32.0, 1.10, -0.4, True), + RadarTrack(19, 47.5, -2.80, 0.1, False), + RadarTrack(22, 61.0, 0.20, -3.4, True), + ) if label_tracks else () + return BoschRadarStatus( + tracks=tracks, + hw_fail=False, + sgu_fail=True, + dirty=False, + alerts=("vinValidity", "xwdValidity", "radPositionMismatch"), + table_frozen=True, + awd=True, + position=0, + epas_type=2, + vin="5YJSA1E45FF108485", + unique_raw=2, + gtw_live=True, + vin_stream_complete=True, + last_raw_age_s=0.08, + vin_f190="5YJSA1E45FF108485", + vin_chassis="5YJSA1H15EFP37440", + ) + + +def main() -> None: + out = Path(sys.argv[1] if len(sys.argv) > 1 else "/tmp/radar-ui") + out.mkdir(parents=True, exist_ok=True) + + gui_app.init_window("radar preview") + ui_state.radar_hud = True + ui_state.radar_status = _status() + + overlay = RadarHudOverlay() + dialog = RadarMonitorDialog() + hud = radar_hud_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + rl.begin_drawing() + rl.clear_background(rl.Color(30, 40, 50, 255)) + rl.draw_rectangle(0, 0, gui_app.width, 120, rl.Color(20, 20, 20, 255)) + overlay.render(hud) + rl.end_drawing() + overlay_path = str(out / "radar_hud.png") + rl.take_screenshot(overlay_path) + + rl.begin_drawing() + dialog.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + rl.end_drawing() + dialog_path = str(out / "radar_monitor.png") + rl.take_screenshot(dialog_path) + + ui_state.radar_status = replace( + _status(), + sgu_fail=False, + alerts=(), + table_frozen=False, + awd=False, + position=1, + epas_type=0, + vin="5YJSA1S11EFP54129", + unique_raw=14, + last_raw_age_s=0.04, + vin_f190="5YJSA1E25FF106153", + vin_chassis="5YJSA1H13EFP20460", + ) + rl.begin_drawing() + rl.clear_background(rl.Color(30, 40, 50, 255)) + overlay.render(hud) + rl.end_drawing() + live_path = str(out / "radar_hud_live.png") + rl.take_screenshot(live_path) + + gui_app.close() + print(overlay_path) + print(dialog_path) + print(live_path) + + +if __name__ == "__main__": + main() diff --git a/selfdrive/ui/radar/radar_view.py b/selfdrive/ui/radar/radar_view.py new file mode 100644 index 00000000000000..322ce62412d1a9 --- /dev/null +++ b/selfdrive/ui/radar/radar_view.py @@ -0,0 +1,600 @@ +"""Bird's-eye Bosch radar plot, driving HUD, and in-session monitor dialog. + +Tinkla C2's calibrate/test tools subscribed to cereal `can` and left +pandad running. NAP's script runner killed the comma session instead. +This dialog is a push_widget overlay: open while driving, close without +reboot, no NAPScriptRunning. + +Hidpi 2160x1080 is the product: full key-on chips, range rings, tracks table +top-right. C4 536x240 is cut-down: state plus one or two reject/table bits, +the ID/dRel/yRel/vRel table, optional small plot, and Close. +""" + +from __future__ import annotations + +from dataclasses import replace +import math + +import pyray as rl + +from openpilot.selfdrive.ui.radar.bosch_status import ( + ALIGN_D_MAX, + ALIGN_D_MIN, + ALIGN_Y_MAX, + BoschRadarStatus, + RadarTrack, +) +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle + +RANGE_M = 120.0 +LATERAL_M = 8.0 + +# Concentric dRel rings. Distinct colors so 20/40/60/80 m read at a glance. +RANGE_RINGS = ( + (20.0, rl.Color(72, 210, 160, 230)), # sea + (40.0, rl.Color(230, 190, 70, 230)), # gold + (60.0, rl.Color(235, 115, 95, 230)), # coral + (80.0, rl.Color(180, 120, 230, 230)), # orchid +) + +# C4 on-road strip. Must fit inside 536x240 (content ~476x180 after 30px border). +C4_HUD_W = 460.0 +C4_HUD_H = 44.0 +# Hidpi on-road panel: plot + chips + tracks table. Slightly bigger than 900x340. +HIDPI_HUD_W = 980.0 +HIDPI_HUD_H = 380.0 + +TABLE_HEADER = " ID dRel yRel vRel" + +# 0x501 bits Jack uses to decide "wrong radar / wrong car" — product names, not DBC ids. +ALERT_CHIP = ( + ("vinValidity", "VIN"), + ("xwdValidity", "XWD"), + ("radPositionMismatch", "POS"), + ("strRackMismatch", "RACK"), +) +KEY_REJECT = tuple(k for k, _ in ALERT_CHIP) + +HEALTH_COLOR = { + "LIVE": rl.Color(70, 200, 120, 255), + "NO TRACKS": rl.Color(180, 180, 180, 255), + "WAIT VIN": rl.Color(230, 170, 50, 255), + "WAIT GTW": rl.Color(230, 170, 50, 255), + "SGU": rl.Color(230, 170, 50, 255), + "REJECT": rl.Color(230, 120, 40, 255), + "UNAVAIL": rl.Color(230, 170, 50, 255), + "CAN": rl.Color(226, 44, 44, 255), + "FROZEN": rl.Color(226, 44, 44, 255), + "FAULT": rl.Color(226, 44, 44, 255), +} + +PANEL_BG = rl.Color(12, 14, 18, 230) +PANEL_BORDER = rl.Color(255, 255, 255, 70) +ALIGN_FILL = rl.Color(70, 91, 234, 40) +ALIGN_LINE = rl.Color(70, 91, 234, 160) +TRACK_FILL = rl.Color(90, 200, 255, 230) +TRACK_COAST = rl.Color(180, 180, 180, 200) +LEAD_FILL = rl.Color(128, 216, 166, 255) +TEXT = rl.Color(236, 236, 236, 255) +MUTED = rl.Color(170, 170, 170, 255) +CHIP_MUTED = rl.Color(128, 128, 128, 255) +CHIP_FILL = rl.Color(57, 57, 57, 255) +CHIP_ON_FILL = rl.Color(70, 40, 20, 230) +OK_FILL = rl.Color(20, 50, 32, 230) + + +def health_color(label: str) -> rl.Color: + return HEALTH_COLOR.get(label, MUTED) + + +def _draw_text(font, text: str, x: float, y: float, size: int, color: rl.Color) -> None: + rl.draw_text_ex(font, text, rl.Vector2(x, y), size, 0, color) + + +def _line_h(font, text: str, size: int, gap: int = 4) -> float: + return measure_text_cached(font, text or "Ag", size).y + gap + + +def is_c4_screen(rect: rl.Rectangle) -> bool: + return rect.width < 800 and rect.height < 500 + + +def radar_hud_rect(content: rl.Rectangle) -> rl.Rectangle: + """On-road HUD that always fits inside `content`. + + C4 536x240 / content ~476x180: 460x44 status strip. + Hidpi 2160x1080 / content ~2100x1020: 1200x400 chip + table panel. + """ + if is_c4_screen(content): + margin = 8.0 + w = min(C4_HUD_W, max(0.0, content.width - margin * 2)) + h = min(C4_HUD_H, max(0.0, content.height - margin)) + return rl.Rectangle(content.x + margin, content.y + content.height - h - margin, w, h) + margin_x, margin_y = 24.0, 20.0 + w = min(HIDPI_HUD_W, max(0.0, content.width - margin_x * 2)) + h = min(HIDPI_HUD_H, max(0.0, content.height - 24.0)) + return rl.Rectangle(content.x + margin_x, content.y + content.height - h - margin_y, w, h) + + +def _clamp_to_window(rect: rl.Rectangle) -> rl.Rectangle: + w_max = float(max(1, gui_app.width)) + h_max = float(max(1, gui_app.height)) + x = min(max(0.0, rect.x), w_max) + y = min(max(0.0, rect.y), h_max) + w = min(max(0.0, rect.width), w_max - x) + h = min(max(0.0, rect.height), h_max - y) + return rl.Rectangle(x, y, w, h) + + +def _chip_pad(font_size: int) -> tuple[int, int]: + if font_size < 16: + return 6, 2 + if font_size < 22: + return 8, 3 + return 12, 5 + + +def chip_size(text: str, font_size: int) -> tuple[float, float]: + font = gui_app.font(FontWeight.BOLD) + sz = measure_text_cached(font, text, font_size) + pad_x, pad_y = _chip_pad(font_size) + return sz.x + pad_x * 2, sz.y + pad_y * 2 + + +def draw_chip(x: float, y: float, text: str, color: rl.Color, font_size: int, + fill: rl.Color | None = None) -> tuple[float, float]: + font = gui_app.font(FontWeight.BOLD) + sz = measure_text_cached(font, text, font_size) + pad_x, pad_y = _chip_pad(font_size) + w = sz.x + pad_x * 2 + h = sz.y + pad_y * 2 + rec = rl.Rectangle(x, y, w, h) + bg = fill if fill is not None else rl.Color(color.r, color.g, color.b, 48) + rl.draw_rectangle_rounded(rec, 0.5, 8, bg) + rl.draw_rectangle_rounded_lines_ex(rec, 0.5, 8, 1.5 if font_size < 20 else 2, color) + _draw_text(font, text, x + pad_x, y + pad_y, font_size, color) + return w, h + + +def draw_chip_row(x: float, y: float, max_w: float, chips: list[tuple[str, rl.Color, rl.Color | None]], + font_size: int, gap: float = 6) -> tuple[float, float]: + cx, cy = x, y + row_h = 0.0 + used_w = 0.0 + bottom = y + for text, color, fill in chips: + tw, th = chip_size(text, font_size) + if cx + tw > x + max_w and cx > x: + cx = x + cy += row_h + 4 + row_h = 0.0 + if tw > max_w: + continue + draw_chip(cx, cy, text, color, font_size, fill=fill) + cx += tw + gap + row_h = max(row_h, th) + used_w = max(used_w, cx - x) + bottom = cy + row_h + return used_w, max(0.0, bottom - y) + + +def table_bit(status: BoschRadarStatus) -> str | None: + if status.table_frozen or status.unique_raw == 1: + return "frozen" + if status.unique_raw >= 2: + return "moving" + return None + + +def link_label(status: BoschRadarStatus) -> str: + # silent-until-VIN-complete: host 0x560 mux must finish before panda talks + return "talking" if status.vin_stream_complete else "waiting" + + +def c4_extra_chips(status: BoschRadarStatus) -> list[tuple[str, rl.Color]]: + """One or two bits that matter on C4. No VIN trio, no 0x2A9 desk.""" + extras: list[tuple[str, rl.Color]] = [] + reason = None + for key, short in ALERT_CHIP: + if key in status.alerts: + reason = short + break + if reason is None and status.hw_fail: + reason = "HWFail" + elif reason is None and status.sgu_fail: + reason = "SGUFail" + elif reason is None and status.health_label in ("WAIT VIN", "WAIT GTW"): + reason = "waiting" + if reason: + extras.append((reason, health_color("REJECT" if reason in ("VIN", "XWD", "POS", "RACK") else status.health_label))) + bit = table_bit(status) + if bit: + extras.append((bit, health_color("FROZEN" if bit == "frozen" else "LIVE"))) + return extras[:2] + + +def _extract_vin(raw) -> str: + if raw is None: + return "" + if isinstance(raw, (bytes, bytearray)): + raw = raw.decode("ascii", "ignore") + token = "".join(ch for ch in str(raw).upper() if ch.isalnum()) + return token if len(token) == 17 else "" + + +def vin_refs(status: BoschRadarStatus) -> tuple[str, str, str]: + """0x2B9 feed vs F190 (radar EEPROM / donor param) vs chassis CarVin.""" + feed = status.vin if len(status.vin) == 17 else (status.vin or "") + f190 = _extract_vin(getattr(status, "vin_f190", "") or "") + chassis = _extract_vin(getattr(status, "vin_chassis", "") or "") + if not f190 or not chassis: + try: + if not f190: + raw = ui_state.params.get("NAPRadarDonorVin", return_default=True) or "" + f190 = _extract_vin(raw) + if not chassis and getattr(ui_state, "CP", None) is not None: + chassis = _extract_vin(getattr(ui_state.CP, "carVin", "") or "") + if not chassis: + chassis = _extract_vin(ui_state.params.get("CarVin")) + except Exception: + pass + return feed, f190, chassis + + +def _light(color: rl.Color) -> rl.Color: + return rl.Color(min(255, color.r + 36), min(255, color.g + 36), min(255, color.b + 36), 210) + + +def _draw_range_rings(rect: rl.Rectangle, to_px, compact: bool) -> None: + """Concentric range arcs centered on the car. Labels are hidpi-only.""" + if rect.height < 48: + return + car_x, car_y = to_px(0.0, 0.0) + n = 40 if compact else 80 + thick = 1.5 if compact else 2.5 + font = gui_app.font(FontWeight.NORMAL) + label_size = 14 + for r_m, color in RANGE_RINGS: + radius = (r_m / RANGE_M) * rect.height + if radius < 6: + continue + prev = None + for i in range(n + 1): + theta = math.pi * i / n + x = car_x + radius * math.cos(theta) + y = car_y - radius * math.sin(theta) + if prev is not None: + rl.draw_line_ex(rl.Vector2(prev[0], prev[1]), rl.Vector2(x, y), thick, color) + prev = (x, y) + if not compact: + lx, ly = to_px(r_m, 0.0) + _draw_text(font, f"{int(r_m)}m", lx + 8, ly - 12, label_size, _light(color)) + + +def draw_radar_plot(rect: rl.Rectangle, status: BoschRadarStatus, align_box: bool = True, + compact: bool = False) -> None: + rl.draw_rectangle_rec(rect, rl.Color(8, 10, 14, 255)) + rl.draw_rectangle_lines_ex(rect, 1 if compact else 2, PANEL_BORDER) + if rect.width < 8 or rect.height < 8: + return + + def to_px(d_rel: float, y_rel: float) -> tuple[float, float]: + x = rect.x + rect.width * (0.5 - y_rel / (2 * LATERAL_M)) + y = rect.y + rect.height * (1.0 - d_rel / RANGE_M) + return x, y + + rl.begin_scissor_mode(int(rect.x) + 1, int(rect.y) + 1, max(1, int(rect.width) - 2), max(1, int(rect.height) - 2)) + + if align_box: + left, bottom = to_px(ALIGN_D_MIN, ALIGN_Y_MAX) + right, top = to_px(ALIGN_D_MAX, -ALIGN_Y_MAX) + box = rl.Rectangle(min(left, right), min(top, bottom), abs(right - left), abs(bottom - top)) + rl.draw_rectangle_rec(box, ALIGN_FILL) + rl.draw_rectangle_lines_ex(box, 1 if compact else 2, ALIGN_LINE) + + _draw_range_rings(rect, to_px, compact) + + car_x, car_y = to_px(0.0, 0.0) + cw, ch = (5, 8) if compact else (12, 16) + rl.draw_rectangle(int(car_x - cw / 2), int(car_y - ch + 2), cw, ch, rl.Color(220, 220, 220, 255)) + + closest = None + for track in status.tracks: + if closest is None or track.d_rel < closest.d_rel: + closest = track + for track in status.tracks: + x, y = to_px(max(0.0, min(RANGE_M, track.d_rel)), track.y_rel) + color = LEAD_FILL if track is closest else (TRACK_FILL if track.measured else TRACK_COAST) + radius = (4 if track is closest else 3) if compact else (7 if track is closest else 5) + rl.draw_circle(int(x), int(y), radius, color) + + rl.end_scissor_mode() + + font = gui_app.font(FontWeight.NORMAL) + tick = 11 if compact else 18 + _draw_text(font, "0m", rect.x + 4, rect.y + rect.height - (14 if compact else 28), tick, MUTED) + _draw_text(font, f"{int(RANGE_M)}m", rect.x + 4, rect.y + 3, tick, MUTED) + + +def _track_row(track: RadarTrack) -> str: + flag = "m" if track.measured else "c" + return f"{track.track_id:>4} {track.d_rel:6.1f} {track.y_rel:+6.2f} {track.v_rel:+6.2f} {flag}" + + +def draw_tracks_table(x: float, y: float, bottom: float, status: BoschRadarStatus, + font_size: int, max_rows: int, empty: str) -> float: + """ID / dRel / yRel / vRel. The table C4 must not lose.""" + if bottom - y < font_size + 2: + return y + font = gui_app.font(FontWeight.MEDIUM) + _draw_text(font, TABLE_HEADER, x, y, font_size, MUTED) + y += _line_h(font, "dRel", font_size, 3 if font_size < 16 else 6) + rows = sorted(status.tracks, key=lambda t: t.d_rel)[:max_rows] + gap = 2 if font_size < 16 else 4 + for track in rows: + if y + font_size > bottom: + break + _draw_text(font, _track_row(track), x, y, font_size, TEXT) + y += _line_h(font, _track_row(track), font_size, gap) + if not rows and y + font_size <= bottom: + _draw_text(font, empty, x, y, font_size, MUTED) + y += _line_h(font, empty, font_size, gap) + return y + + +def _c4_chip_list(status: BoschRadarStatus) -> list[tuple[str, rl.Color, rl.Color | None]]: + chips: list[tuple[str, rl.Color, rl.Color | None]] = [ + (status.health_label, health_color(status.health_label), None), + ] + for text, color in c4_extra_chips(status): + fill = CHIP_FILL if text in ("moving", "frozen", "waiting") else CHIP_ON_FILL + chips.append((text, color, fill)) + return chips + + +def draw_c4_strip(panel: rl.Rectangle, status: BoschRadarStatus) -> None: + """Cut-down C4 HUD: state + at most two reject/table bits.""" + rl.draw_rectangle_rounded(panel, 0.18, 6, PANEL_BG) + rl.draw_rectangle_rounded_lines_ex(panel, 0.18, 6, 2, health_color(status.health_label)) + font_size = 13 + chips = _c4_chip_list(status) + max_h = 0.0 + for text, _, _ in chips: + _w, th = chip_size(text, font_size) + max_h = max(max_h, th) + pad = 6.0 + y = panel.y + max(pad, (panel.height - max_h) / 2) + draw_chip_row(panel.x + pad, y, panel.width - pad * 2, chips, font_size, gap=6) + + +def draw_hidpi_chips(rect: rl.Rectangle, status: BoschRadarStatus, font_size: int) -> float: + """Full key-on chips. Product names, not a wall of CAN ids.""" + if rect.width < 8 or rect.height < 8: + return rect.y + font = gui_app.font(FontWeight.MEDIUM) + label_size = max(14, font_size - 4) + x, y = rect.x, rect.y + max_w = rect.width + bottom = rect.y + rect.height + gap = 8 + + def row(label: str, chips: list[tuple[str, rl.Color, rl.Color | None]]) -> None: + nonlocal y + if y + 20 > bottom: + return + lw = 0.0 + if label: + _draw_text(font, label, x, y + 4, label_size, MUTED) + lw = measure_text_cached(font, label, label_size).x + 10 + _, h = draw_chip_row(x + lw, y, max_w - lw, chips, font_size, gap=6) + y += max(h, _line_h(font, label or "Ag", label_size, 0)) + gap + + label = status.health_label + talking = link_label(status) + row("", [ + (label, health_color(label), None), + ("SGUFail", health_color("SGU") if status.sgu_fail else CHIP_MUTED, + CHIP_ON_FILL if status.sgu_fail else CHIP_FILL), + ("HWFail", health_color("FAULT") if status.hw_fail else CHIP_MUTED, + CHIP_ON_FILL if status.hw_fail else CHIP_FILL), + (talking, health_color("LIVE") if talking == "talking" else health_color("WAIT VIN"), + OK_FILL if talking == "talking" else CHIP_FILL), + ]) + + alert_chips = [] + for key, short in ALERT_CHIP: + on = key in status.alerts + alert_chips.append((short, health_color("REJECT") if on else CHIP_MUTED, CHIP_ON_FILL if on else CHIP_FILL)) + row("reject", alert_chips) + + awd = "4WD" if status.awd else ("2WD" if status.awd is False else "drive —") + pos = "—" if status.position is None else str(status.position) + epas = "—" if status.epas_type is None else str(status.epas_type) + row("drive", [ + (awd, TEXT, CHIP_FILL), + (f"pos {pos}", TEXT, CHIP_FILL), + (f"EPAS {epas}", TEXT, CHIP_FILL), + ]) + + feed, f190, chassis = vin_refs(status) + present = [v for v in (feed, f190, chassis) if v] + mismatch = len(set(present)) > 1 + + def vin_chip(tag: str, value: str) -> tuple[str, rl.Color, rl.Color | None]: + shown = value or "—" + bad = bool(value) and mismatch and any(v != value for v in present) + return (f"{tag} {shown}", health_color("REJECT") if bad else TEXT, CHIP_ON_FILL if bad else CHIP_FILL) + + row("VIN", [ + vin_chip("2B9", feed), + vin_chip("F190", f190), + vin_chip("CHS", chassis), + ]) + + age = "age —" if status.last_raw_age_s is None else ( + f"age {status.last_raw_age_s:.1f}s" if status.last_raw_age_s < 10 else f"age {status.last_raw_age_s:.0f}s" + ) + bit = table_bit(status) + raw_chips: list[tuple[str, rl.Color, rl.Color | None]] = [ + (f"raw {status.unique_raw}", TEXT, CHIP_FILL), + (age, TEXT, CHIP_FILL), + (f"{len(status.tracks)} trk", TEXT, CHIP_FILL), + ] + if bit: + raw_chips.append((bit, health_color("FROZEN" if bit == "frozen" else "LIVE"), + CHIP_ON_FILL if bit == "frozen" else OK_FILL)) + row("table", raw_chips) + return y + + +class RadarHudOverlay(Widget): + """On-road readout. Hidden unless NAPRadarHud is set.""" + + def _render(self, rect: rl.Rectangle): + if not ui_state.radar_hud: + return + status = ui_state.radar_status + panel = _clamp_to_window(rect) + if panel.width < 8 or panel.height < 8: + return + if panel.height < 80: + draw_c4_strip(panel, status) + return + + rl.draw_rectangle_rounded(panel, 0.06, 8, PANEL_BG) + rl.draw_rectangle_rounded_lines_ex(panel, 0.06, 8, 2, health_color(status.health_label)) + pad = 14 + plot_w = min(230.0, panel.width * 0.22) + plot = rl.Rectangle(panel.x + pad, panel.y + pad, plot_w, panel.height - pad * 2) + draw_radar_plot(plot, status, align_box=False, compact=False) + + table_w = 390.0 if panel.width >= 980 else 0.0 + gap = 14.0 + chips_x = plot.x + plot.width + gap + chips_w = panel.width - plot.width - pad * 2 - gap + if table_w: + chips_w = panel.width - plot.width - table_w - pad * 2 - gap * 2 + chips = rl.Rectangle(chips_x, panel.y + pad, max(8.0, chips_w), panel.height - pad * 2) + draw_hidpi_chips(chips, status, font_size=18) + if table_w: + table_x = panel.x + panel.width - pad - table_w + draw_tracks_table(table_x, panel.y + pad, panel.y + panel.height - pad, + status, 16, 8, "no published tracks") + + +class RadarMonitorDialog(Widget): + """Full-screen live radar. Does not stop pandad or set NAPScriptRunning.""" + + def __init__(self): + super().__init__() + self._close = Button("Close", click_callback=self._on_close, font_size=35, + text_padding=16, button_style=ButtonStyle.TRANSPARENT_WHITE_BORDER) + self._align_only = False + self._align_btn = Button("Align", click_callback=self._toggle_align, font_size=35, + text_padding=16, button_style=ButtonStyle.ACTION) + + def _on_close(self): + gui_app.pop_widget() + + def _toggle_align(self): + self._align_only = not self._align_only + + def _tune_buttons(self, compact: bool) -> None: + font = 16 if compact else 35 + pad = 4 if compact else 16 + radius = 8 if compact else 10 + for btn in (self._close, self._align_btn): + btn._label.set_font_size(font) + btn._label._text_padding = pad + btn._border_radius = radius + self._align_btn.set_button_style(ButtonStyle.PRIMARY if self._align_only else ButtonStyle.ACTION) + + def _render(self, rect: rl.Rectangle): + status = ui_state.radar_status + compact = is_c4_screen(rect) + if self._align_only and not compact: + tracks = tuple( + t for t in status.tracks + if ALIGN_D_MIN <= t.d_rel <= ALIGN_D_MAX and abs(t.y_rel) <= ALIGN_Y_MAX + ) + status = replace(status, tracks=tracks) + + self._tune_buttons(compact) + rl.draw_rectangle_rec(rect, rl.Color(0, 0, 0, 255)) + if compact: + self._render_c4(rect, status) + else: + self._render_hidpi(rect, status) + + def _render_c4(self, rect: rl.Rectangle, status: BoschRadarStatus) -> None: + """536x240: chips + tracks TABLE + small plot + Close. No Align, no VIN dump.""" + pad = 6 + title_size = 16 + btn_w, btn_h = 96, 30 + footer_h = btn_h + 8 + title_font = gui_app.font(FontWeight.BOLD) + _draw_text(title_font, "Live radar", rect.x + pad, rect.y + 3, title_size, TEXT) + chip_y = rect.y + 22 + draw_chip_row(rect.x + pad, chip_y, rect.width - pad * 2, _c4_chip_list(status), 12, gap=5) + body_y = rect.y + 46 + body_h = rect.height - 46 - footer_h + # Table is required. Plot stays only if the table still has room. + table_font = 11 + min_table_w = 220.0 + plot_w = 120.0 + if rect.width - pad * 3 - plot_w < min_table_w: + plot_w = 0.0 + if plot_w and body_h > 40: + plot = rl.Rectangle(rect.x + pad, body_y, plot_w, body_h) + draw_radar_plot(plot, status, align_box=False, compact=True) + table_x = plot.x + plot.width + 8 + else: + table_x = rect.x + pad + empty = "no published tracks" + draw_tracks_table(table_x, body_y, body_y + body_h - 2, status, table_font, 8, empty) + btn_y = rect.y + rect.height - footer_h + 4 + self._close.render(rl.Rectangle(rect.x + pad, btn_y, btn_w, btn_h)) + + def _render_hidpi(self, rect: rl.Rectangle, status: BoschRadarStatus) -> None: + pad = 28 + title_size = 42 + body = 22 + btn_h, btn_w, align_w = 80, 240, 200 + header_h = 92 + footer_h = btn_h + 24 + title_font = gui_app.font(FontWeight.BOLD) + body_font = gui_app.font(FontWeight.MEDIUM) + + _draw_text(title_font, "Live radar", rect.x + pad, rect.y + 16, title_size, TEXT) + chip_x = rect.x + pad + measure_text_cached(title_font, "Live radar", title_size).x + 16 + draw_chip(chip_x, rect.y + 20, status.health_label, health_color(status.health_label), 22) + _draw_text(body_font, "openpilot stays running", rect.x + pad, rect.y + 64, 20, MUTED) + + mode = "2.5–14.5 m" if self._align_only else "All tracks" + mode_color = health_color("LIVE") if self._align_only else MUTED + mw, mh = chip_size(mode, body) + mode_x = rect.x + rect.width - pad - mw + mode_y = rect.y + 20 + draw_chip(mode_x, mode_y, mode, mode_color, body, + fill=ALIGN_FILL if self._align_only else CHIP_FILL) + + table_w = 460.0 + plot_w = min(rect.width * 0.34, 720) + footer_y = rect.y + rect.height - footer_h + plot = rl.Rectangle(rect.x + pad, rect.y + header_h, plot_w, footer_y - (rect.y + header_h)) + draw_radar_plot(plot, status, align_box=True, compact=False) + + table_x = rect.x + rect.width - pad - table_w + chips_x = plot.x + plot.width + 24 + chips_w = table_x - chips_x - 20 + draw_hidpi_chips(rl.Rectangle(chips_x, plot.y, max(8.0, chips_w), plot.height), status, font_size=20) + empty = "no tracks in 2.5–14.5 m" if self._align_only else "no published tracks" + draw_tracks_table(table_x, plot.y, footer_y - 8, status, body, 12, empty) + + btn_y = footer_y + 12 + self._close.render(rl.Rectangle(rect.x + pad, btn_y, btn_w, btn_h)) + self._align_btn.render(rl.Rectangle(rect.x + pad + btn_w + 14, btn_y, align_w, btn_h)) diff --git a/selfdrive/ui/soundd.py b/selfdrive/ui/soundd.py index 4055fcfd35a9a7..1e8400cbfdd9ad 100644 --- a/selfdrive/ui/soundd.py +++ b/selfdrive/ui/soundd.py @@ -8,21 +8,34 @@ from openpilot.common.basedir import BASEDIR from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.realtime import Ratekeeper -from openpilot.common.retry import retry +from openpilot.common.utils import retry from openpilot.common.swaglog import cloudlog from openpilot.system import micd +from openpilot.system.hardware import HARDWARE +from openpilot.selfdrive.ui.obstacle_chime import ( + OBSTACLE_CHIME_FILE, + OBSTACLE_CHIME_ID, + alert_sound_id, + floor_volume, +) SAMPLE_RATE = 48000 SAMPLE_BUFFER = 4096 # (approx 100ms) MAX_VOLUME = 1.0 MIN_VOLUME = 0.1 -CONTROLS_TIMEOUT = 5 # 5 seconds +ALERT_RAMP_TIME = 4 # seconds to ramp to max volume for warningImmediate +SELFDRIVE_STATE_TIMEOUT = 5 # 5 seconds FILTER_DT = 1. / (micd.SAMPLE_RATE / micd.FFT_SAMPLES) -AMBIENT_DB = 30 # DB where MIN_VOLUME is applied +AMBIENT_DB = 24 # DB where MIN_VOLUME is applied DB_SCALE = 30 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied +VOLUME_BASE = 20 +if HARDWARE.get_device_type() == "tizi": + AMBIENT_DB = 30 + VOLUME_BASE = 10 + AudibleAlert = car.CarControl.HUDControl.AudibleAlert @@ -39,12 +52,19 @@ AudibleAlert.warningSoft: ("warning_soft.wav", None, MAX_VOLUME), AudibleAlert.warningImmediate: ("warning_immediate.wav", None, MAX_VOLUME), } - -def check_controls_timeout_alert(sm): - controls_missing = time.monotonic() - sm.recv_time['selfdriveState'] - - if controls_missing > CONTROLS_TIMEOUT: - if sm['selfdriveState'].enabled and (controls_missing - CONTROLS_TIMEOUT) < 10: +if HARDWARE.get_device_type() == "tizi": + sound_list.update({ + AudibleAlert.engage: ("engage_tizi.wav", 1, MAX_VOLUME), + AudibleAlert.disengage: ("disengage_tizi.wav", 1, MAX_VOLUME), + }) +# Negative id: not an AudibleAlert ordinal. Played from alertType obstacleChime/*. +sound_list[OBSTACLE_CHIME_ID] = (OBSTACLE_CHIME_FILE, 1, MAX_VOLUME) + +def check_selfdrive_timeout_alert(sm): + ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] + + if ss_missing > SELFDRIVE_STATE_TIMEOUT: + if sm['selfdriveState'].enabled and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < 10: return True return False @@ -58,7 +78,10 @@ def __init__(self): self.current_volume = MIN_VOLUME self.current_sound_frame = 0 - self.controls_timeout_alert = False + self.ramp_start_volume = MIN_VOLUME + self.ramp_start_time = 0. + + self.selfdrive_timeout_alert = False self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False) @@ -69,20 +92,27 @@ def load_sounds(self): for sound in sound_list: filename, play_count, volume = sound_list[sound] - wavefile = wave.open(BASEDIR + "/selfdrive/assets/sounds/" + filename, 'r') + try: + with wave.open(BASEDIR + "/selfdrive/assets/sounds/" + filename, 'r') as wavefile: + assert wavefile.getnchannels() == 1 + assert wavefile.getsampwidth() == 2 + assert wavefile.getframerate() == SAMPLE_RATE - assert wavefile.getnchannels() == 1 - assert wavefile.getsampwidth() == 2 - assert wavefile.getframerate() == SAMPLE_RATE - - length = wavefile.getnframes() - self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2) + length = wavefile.getnframes() + self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2) + except Exception: + if sound == OBSTACLE_CHIME_ID: + cloudlog.exception("obstacle chime wav failed to load") + continue + raise def get_sound_data(self, frames): # get "frames" worth of data from the current alert sound, looping when required ret = np.zeros(frames, dtype=np.float32) - if self.current_alert != AudibleAlert.none: + if (self.current_alert != AudibleAlert.none + and self.current_alert in sound_list + and self.current_alert in self.loaded_sounds): num_loops = sound_list[self.current_alert][1] sound_data = self.loaded_sounds[self.current_alert] written_frames = 0 @@ -105,27 +135,36 @@ def callback(self, data_out: np.ndarray, frames: int, time, status) -> None: data_out[:frames, 0] = self.get_sound_data(frames) def update_alert(self, new_alert): - current_alert_played_once = self.current_alert == AudibleAlert.none or self.current_sound_frame > len(self.loaded_sounds[self.current_alert]) + loaded = self.current_alert in self.loaded_sounds + current_alert_played_once = ( + self.current_alert == AudibleAlert.none + or not loaded + or self.current_sound_frame > len(self.loaded_sounds[self.current_alert]) + ) if self.current_alert != new_alert and (new_alert != AudibleAlert.none or current_alert_played_once): + if new_alert == AudibleAlert.warningImmediate: + self.ramp_start_volume = self.current_volume + self.ramp_start_time = time.monotonic() self.current_alert = new_alert self.current_sound_frame = 0 def get_audible_alert(self, sm): if sm.updated['selfdriveState']: - new_alert = sm['selfdriveState'].alertSound.raw + ss = sm['selfdriveState'] + new_alert = alert_sound_id(ss.alertSound.raw, getattr(ss, "alertType", "")) self.update_alert(new_alert) - elif check_controls_timeout_alert(sm): + elif check_selfdrive_timeout_alert(sm): self.update_alert(AudibleAlert.warningImmediate) - self.controls_timeout_alert = True - elif self.controls_timeout_alert: + self.selfdrive_timeout_alert = True + elif self.selfdrive_timeout_alert: self.update_alert(AudibleAlert.none) - self.controls_timeout_alert = False + self.selfdrive_timeout_alert = False def calculate_volume(self, weighted_db): volume = ((weighted_db - AMBIENT_DB) / DB_SCALE) * (MAX_VOLUME - MIN_VOLUME) + MIN_VOLUME - return math.pow(10, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1)) + return math.pow(VOLUME_BASE, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1)) - @retry(attempts=7, delay=3) + @retry(attempts=10, delay=3) def get_stream(self, sd): # reload sounddevice to reinitialize portaudio sd._terminate() @@ -136,7 +175,7 @@ def soundd_thread(self): # sounddevice must be imported after forking processes import sounddevice as sd - sm = messaging.SubMaster(['selfdriveState', 'microphone']) + sm = messaging.SubMaster(['selfdriveState', 'soundPressure']) with self.get_stream(sd) as stream: rk = Ratekeeper(20) @@ -145,12 +184,22 @@ def soundd_thread(self): while True: sm.update(0) - if sm.updated['microphone'] and self.current_alert == AudibleAlert.none: # only update volume filter when not playing alert - self.spl_filter_weighted.update(sm["microphone"].soundPressureWeightedDb) + # Always update volume, even when alert is playing + if sm.updated['soundPressure']: + self.spl_filter_weighted.update(sm["soundPressure"].soundPressureWeightedDb) self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x)) self.get_audible_alert(sm) + # Ramp up immediate warning sound over 4s + if self.current_alert == AudibleAlert.warningImmediate: + elapsed = time.monotonic() - self.ramp_start_time + ramp_vol = float(np.interp(elapsed, [0, ALERT_RAMP_TIME], [self.ramp_start_volume, MAX_VOLUME])) + self.current_volume = max(self.current_volume, ramp_vol) + + # Quiet cabin cannot drop the obstacle chime below 0.7. Other sounds stay scaled. + self.current_volume = floor_volume(self.current_alert, self.current_volume) + rk.keep_time() assert stream.active diff --git a/selfdrive/ui/spinner b/selfdrive/ui/spinner deleted file mode 100755 index 965c8f581ab64a..00000000000000 --- a/selfdrive/ui/spinner +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -if [ -f /TICI ] && [ ! -f _spinner ]; then - cp qt/spinner_larch64 _spinner -fi - -exec ./_spinner "$1" diff --git a/selfdrive/ui/tests/.gitignore b/selfdrive/ui/tests/.gitignore deleted file mode 100644 index 91898ac59a1e11..00000000000000 --- a/selfdrive/ui/tests/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -test -test_translations -test_ui/report_1 \ No newline at end of file diff --git a/selfdrive/ui/tests/body.py b/selfdrive/ui/tests/body.py index 7e24c2beb77f9e..07a2ef5128ae10 100755 --- a/selfdrive/ui/tests/body.py +++ b/selfdrive/ui/tests/body.py @@ -8,7 +8,7 @@ batt = 1. while True: msg = messaging.new_message('carParams') - msg.carParams.carName = "BODY" + msg.carParams.brand = "body" msg.carParams.notCar = True pm.send('carParams', msg) diff --git a/selfdrive/ui/tests/create_test_translations.sh b/selfdrive/ui/tests/create_test_translations.sh deleted file mode 100755 index ed0890d94651d4..00000000000000 --- a/selfdrive/ui/tests/create_test_translations.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash - -set -e - -UI_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"/.. -TEST_TEXT="(WRAPPED_SOURCE_TEXT)" -TEST_TS_FILE=$UI_DIR/translations/main_test_en.ts -TEST_QM_FILE=$UI_DIR/translations/main_test_en.qm - -# translation strings -UNFINISHED="<\/translation>" -TRANSLATED="$TEST_TEXT<\/translation>" - -mkdir -p $UI_DIR/translations -rm -f $TEST_TS_FILE $TEST_QM_FILE -lupdate -recursive "$UI_DIR" -ts $TEST_TS_FILE -sed -i "s/$UNFINISHED/$TRANSLATED/" $TEST_TS_FILE -lrelease $TEST_TS_FILE diff --git a/selfdrive/ui/tests/cycle_offroad_alerts.py b/selfdrive/ui/tests/cycle_offroad_alerts.py index 75b19ceb9025fa..fcb4a72c77e8a3 100755 --- a/selfdrive/ui/tests/cycle_offroad_alerts.py +++ b/selfdrive/ui/tests/cycle_offroad_alerts.py @@ -6,24 +6,23 @@ from openpilot.common.basedir import BASEDIR from openpilot.common.params import Params -from openpilot.selfdrive.controls.lib.alertmanager import set_offroad_alert +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert +from openpilot.system.updated.updated import parse_release_notes if __name__ == "__main__": params = Params() - with open(os.path.join(BASEDIR, "selfdrive/controls/lib/alerts_offroad.json")) as f: + with open(os.path.join(BASEDIR, "selfdrive/selfdrived/alerts_offroad.json")) as f: offroad_alerts = json.load(f) t = 10 if len(sys.argv) < 2 else int(sys.argv[1]) while True: print("setting alert update") - params.put_bool("UpdateAvailable", True) - r = open(os.path.join(BASEDIR, "RELEASES.md")).read() - r = r[:r.find('\n\n')] # Slice latest release notes - params.put("UpdaterNewReleaseNotes", r + "\n") + params.put_bool("UpdateAvailable", True, block=True) + params.put("UpdaterNewReleaseNotes", parse_release_notes(BASEDIR), block=True) time.sleep(t) - params.put_bool("UpdateAvailable", False) + params.put_bool("UpdateAvailable", False, block=True) # cycle through normal alerts for a in offroad_alerts: diff --git a/selfdrive/ui/tests/diff/diff.py b/selfdrive/ui/tests/diff/diff.py new file mode 100755 index 00000000000000..974edb42a367ee --- /dev/null +++ b/selfdrive/ui/tests/diff/diff.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +import os +import sys +import subprocess +import webbrowser +import argparse +from pathlib import Path +from openpilot.common.basedir import BASEDIR + +DIFF_OUT_DIR = Path(BASEDIR) / "selfdrive" / "ui" / "tests" / "diff" / "report" +HTML_TEMPLATE_PATH = Path(__file__).with_name("diff_template.html") + + +def extract_framehashes(video_path): + cmd = ['ffmpeg', '-i', video_path, '-map', '0:v:0', '-vsync', '0', '-f', 'framehash', '-hash', 'md5', '-'] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + hashes = [] + for line in result.stdout.splitlines(): + if not line or line.startswith('#'): + continue + parts = line.split(',') + if len(parts) < 4: + continue + hashes.append(parts[-1].strip()) + return hashes + + +def create_diff_video(video1, video2, output_path): + """Create a diff video using ffmpeg blend filter with difference mode.""" + print("Creating diff video...") + cmd = ['ffmpeg', '-i', video1, '-i', video2, '-filter_complex', '[0:v]blend=all_mode=difference', '-vsync', '0', '-y', output_path] + subprocess.run(cmd, capture_output=True, check=True) + + +def find_differences(video1, video2) -> tuple[list[int], tuple[int, int]]: + print(f"Hashing frames from {video1}...") + hashes1 = extract_framehashes(video1) + + print(f"Hashing frames from {video2}...") + hashes2 = extract_framehashes(video2) + + print(f"Comparing {len(hashes1)} frames...") + different_frames = [] + + for i, (h1, h2) in enumerate(zip(hashes1, hashes2, strict=False)): + if h1 != h2: + different_frames.append(i) + + return different_frames, (len(hashes1), len(hashes2)) + + +def generate_html_report(videos: tuple[str, str], basedir: str, different_frames: list[int], frame_counts: tuple[int, int], diff_video_name): + chunks = [] + if different_frames: + current_chunk = [different_frames[0]] + for i in range(1, len(different_frames)): + if different_frames[i] == different_frames[i - 1] + 1: + current_chunk.append(different_frames[i]) + else: + chunks.append(current_chunk) + current_chunk = [different_frames[i]] + chunks.append(current_chunk) + + total_frames = max(frame_counts) + frame_delta = frame_counts[1] - frame_counts[0] + different_total = len(different_frames) + abs(frame_delta) + + result_text = ( + f"✅ Videos are identical! ({total_frames} frames)" + if different_total == 0 + else f"❌ Found {different_total} different frames out of {total_frames} total ({different_total / total_frames * 100:.1f}%)." + + (f" Video {'2' if frame_delta > 0 else '1'} is longer by {abs(frame_delta)} frames." if frame_delta != 0 else "") + ) + + # Load HTML template and replace placeholders + html = HTML_TEMPLATE_PATH.read_text() + placeholders = { + "VIDEO1_SRC": os.path.join(basedir, os.path.basename(videos[0])), + "VIDEO2_SRC": os.path.join(basedir, os.path.basename(videos[1])), + "DIFF_SRC": os.path.join(basedir, diff_video_name), + "RESULT_TEXT": result_text, + } + for key, value in placeholders.items(): + html = html.replace(f"${key}", value) + + return html + + +def main(): + parser = argparse.ArgumentParser(description='Compare two videos and generate HTML diff report') + parser.add_argument('video1', help='First video file') + parser.add_argument('video2', help='Second video file') + parser.add_argument('output', nargs='?', default='diff.html', help='Output HTML file (default: diff.html)') + parser.add_argument("--basedir", type=str, help="Base directory for output", default="") + parser.add_argument('--no-open', action='store_true', help='Do not open HTML report in browser') + + args = parser.parse_args() + + if not args.output.lower().endswith('.html'): + args.output += '.html' + + os.makedirs(DIFF_OUT_DIR, exist_ok=True) + + print("=" * 60) + print("VIDEO DIFF - HTML REPORT") + print("=" * 60) + print(f"Video 1: {args.video1}") + print(f"Video 2: {args.video2}") + print(f"Output: {args.output}") + print() + + # Create diff video with name derived from output HTML + diff_video_name = Path(args.output).stem + '.mp4' + diff_video_path = str(DIFF_OUT_DIR / diff_video_name) + create_diff_video(args.video1, args.video2, diff_video_path) + + different_frames, frame_counts = find_differences(args.video1, args.video2) + + if different_frames is None: + sys.exit(1) + + print() + print("Generating HTML report...") + html = generate_html_report((args.video1, args.video2), args.basedir, different_frames, frame_counts, diff_video_name) + + with open(DIFF_OUT_DIR / args.output, 'w') as f: + f.write(html) + + # Open in browser by default + if not args.no_open: + print(f"Opening {args.output} in browser...") + webbrowser.open(f'file://{os.path.abspath(DIFF_OUT_DIR / args.output)}') + + extra_frames = abs(frame_counts[0] - frame_counts[1]) + return 0 if (len(different_frames) + extra_frames) == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/selfdrive/ui/tests/diff/diff_template.html b/selfdrive/ui/tests/diff/diff_template.html new file mode 100644 index 00000000000000..3f1de1051205fe --- /dev/null +++ b/selfdrive/ui/tests/diff/diff_template.html @@ -0,0 +1,80 @@ + + + + + + UI Diff Report + + + +

UI Diff

+
+
+

Results: $RESULT_TEXT

+ + + diff --git a/selfdrive/ui/tests/diff/replay.py b/selfdrive/ui/tests/diff/replay.py new file mode 100755 index 00000000000000..25920b67fb0603 --- /dev/null +++ b/selfdrive/ui/tests/diff/replay.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +import os +import argparse +import coverage +import pyray as rl + +from tqdm import tqdm +from typing import Literal +from collections.abc import Callable +from cereal.messaging import PubMaster +from openpilot.common.api import Api +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.prefix import OpenpilotPrefix +from openpilot.selfdrive.ui.tests.diff.diff import DIFF_OUT_DIR +from openpilot.system.updated.updated import parse_release_notes +from openpilot.system.version import terms_version, training_version + +LayoutVariant = Literal["mici", "tizi"] + +FPS = 60 +HEADLESS = os.getenv("WINDOWED", "0") != "1" + + +def setup_state(): + params = Params() + params.put("HasAcceptedTerms", terms_version, block=True) + params.put("CompletedTrainingVersion", training_version, block=True) + params.put("DongleId", "test123456789", block=True) + # Combined description for layouts that still use it (BIG home, settings/software) + params.put("UpdaterCurrentDescription", "0.10.1 / test-branch / abc1234 / Nov 30", block=True) + params.put("UpdaterCurrentReleaseNotes", parse_release_notes(BASEDIR), block=True) + # Params for mici home + params.put("Version", "0.10.1", block=True) + params.put("GitBranch", "test-branch", block=True) + params.put("GitCommit", "abc12340ff9131237ba23a1d0fbd8edf9c80e87", block=True) + params.put("GitCommitDate", "'1732924800 2024-11-30 00:00:00 +0000'", block=True) + + # Patch Api.get_token to return a static token so the pairing QR code is deterministic across runs + Api.get_token = lambda self, payload_extra=None, expiry_hours=0: "test_token" + + +def run_replay(variant: LayoutVariant) -> None: + if HEADLESS: + rl.set_config_flags(rl.ConfigFlags.FLAG_WINDOW_HIDDEN) + os.environ["OFFSCREEN"] = "1" # Run UI without FPS limit (set before importing gui_app) + + setup_state() + os.makedirs(DIFF_OUT_DIR, exist_ok=True) + + from openpilot.selfdrive.ui.ui_state import ui_state, device # Import within OpenpilotPrefix context so param values are setup correctly + from openpilot.system.ui.lib.application import gui_app # Import here for accurate coverage + from openpilot.selfdrive.ui.tests.diff.replay_script import build_script + + gui_app.init_window("ui diff test", fps=FPS) + + # Dynamically import main layout based on variant + if variant == "mici": + from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout as MainLayout + else: + from openpilot.selfdrive.ui.layouts.main import MainLayout + main_layout = MainLayout() + + # Disable interactive timeout — replay clicks use left_down=False so they never reset the timer, + # and after 30s of real wall-clock time the settings panel would close automatically. + device.set_override_interactive_timeout(99999) + + pm = PubMaster(["deviceState", "pandaStates", "driverStateV2", "selfdriveState"]) + script = build_script(pm, main_layout, variant) + script_index = 0 + + send_fn: Callable | None = None + frame = 0 + # Override raylib timing functions to return deterministic values based on frame count instead of real time + rl.get_frame_time = lambda: 1.0 / FPS + rl.get_time = lambda: frame / FPS + + # Main loop to replay events and render frames + with tqdm(total=script[-1][0] + 1, desc="Replaying", unit="frame", disable=bool(os.getenv("CI"))) as pbar: + for _ in gui_app.render(): + # Handle all events for the current frame + while script_index < len(script) and script[script_index][0] == frame: + _, event = script[script_index] + # Call setup function, if any + if event.setup: + event.setup() + # Send mouse events to the application + if event.mouse_events: + with gui_app._mouse._lock: + gui_app._mouse._events.extend(event.mouse_events) + # Update persistent send function + if event.send_fn is not None: + send_fn = event.send_fn + # Move to next script event + script_index += 1 + + # Keep sending cereal messages for persistent states (onroad, alerts) + if send_fn: + send_fn() + + ui_state.update() + + frame += 1 + pbar.update(1) + + if script_index >= len(script): + break + + gui_app.close() + + print(f"Total frames: {frame}") + print(f"Video saved to: {os.environ['RECORD_OUTPUT']}") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--big', action='store_true', help='Use big UI layout (tizi/tici) instead of mici layout') + args = parser.parse_args() + + variant: LayoutVariant = 'tizi' if args.big else 'mici' + + if args.big: + os.environ["BIG"] = "1" + os.environ["RECORD"] = "1" + os.environ["RECORD_QUALITY"] = "0" # Use CRF 0 ("lossless" encode) for deterministic output across different machines + os.environ["RECORD_OUTPUT"] = os.path.join(DIFF_OUT_DIR, os.environ.get("RECORD_OUTPUT", f"{variant}_ui_replay.mp4")) + + print(f"Running {variant} UI replay...") + with OpenpilotPrefix(): + sources = ["openpilot.system.ui"] + if variant == "mici": + sources.append("openpilot.selfdrive.ui.mici") + omit = ["**/*tizi*", "**/*tici*"] # exclude files containing "tizi" or "tici" + else: + sources.extend(["openpilot.selfdrive.ui.layouts", "openpilot.selfdrive.ui.onroad", "openpilot.selfdrive.ui.widgets"]) + omit = ["**/*mici*"] # exclude files containing "mici" + cov = coverage.Coverage(source=sources, omit=omit) + with cov.collect(): + run_replay(variant) + cov.save() + cov.report() + directory = os.path.join(DIFF_OUT_DIR, f"htmlcov-{variant}") + cov.html_report(directory=directory) + print(f"HTML report: {directory}/index.html") + + +if __name__ == "__main__": + main() diff --git a/selfdrive/ui/tests/diff/replay_script.py b/selfdrive/ui/tests/diff/replay_script.py new file mode 100644 index 00000000000000..ad7e8952d6d152 --- /dev/null +++ b/selfdrive/ui/tests/diff/replay_script.py @@ -0,0 +1,526 @@ +from __future__ import annotations +from typing import TYPE_CHECKING +from collections.abc import Callable +from dataclasses import dataclass + +import math + +from cereal import car, log, messaging +from cereal.messaging import PubMaster +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert +from openpilot.selfdrive.ui.lib.prime_state import PrimeType +from openpilot.selfdrive.ui.tests.diff.replay import FPS, LayoutVariant +from openpilot.system.updated.updated import parse_release_notes + +# Default frames to wait after events +WAIT_LONG = FPS +WAIT_SHORT = FPS // 2 +FAST_CLICK = FPS // 6 + +# Direction vectors for drag gestures +DIR_LEFT = (-1, 0) +DIR_RIGHT = (1, 0) +DIR_UP = (0, -1) +DIR_DOWN = (0, 1) + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus + +BRANCH_NAME = "this-is-a-really-super-mega-ultra-max-extreme-ultimate-long-branch-name" + + +@dataclass +class ScriptEvent: + if TYPE_CHECKING: + # Only import for type checking to avoid excluding the application code from coverage + from openpilot.system.ui.lib.application import MouseEvent + + setup: Callable | None = None # Setup function to run prior to adding mouse events + mouse_events: list[MouseEvent] | None = None # Mouse events to send to the application on this event's frame + send_fn: Callable | None = None # When set, the main loop uses this as the new persistent sender + + +ScriptEntry = tuple[int, ScriptEvent] # (frame, event) + + +class Script: + def __init__(self, fps: int) -> None: + self.fps = fps + self.frame = 0 + self.entries: list[ScriptEntry] = [] + + def get_frame_time(self) -> float: + return self.frame / self.fps + + def add(self, event: ScriptEvent, before: int = 0, after: int = 0) -> None: + """Add event to the script, optionally with the given number of frames to wait before or after the event.""" + self.frame += before + self.entries.append((self.frame, event)) + self.frame += after + + def end(self) -> None: + """Add a final empty event to mark the end of the script.""" + self.add(ScriptEvent()) # Without this, it will just end on the last event without waiting for any specified delay after it + + def wait(self, frames: int) -> None: + """Add a delay for the given number of frames followed by an empty event.""" + self.add(ScriptEvent(), before=frames) + + def setup(self, fn: Callable, wait_after: int = WAIT_SHORT) -> None: + """Add a setup function to be called immediately followed by a delay of the given number of frames.""" + self.add(ScriptEvent(setup=fn), after=wait_after) + + def set_send(self, fn: Callable, wait_after: int = WAIT_SHORT) -> None: + """Set a new persistent send function to be called every frame.""" + self.add(ScriptEvent(send_fn=fn), after=wait_after) + + def click(self, x: int, y: int, wait_after: int = WAIT_SHORT, wait_between: int = 2) -> None: + """Add a click event to the script for the given position and specify frames to wait between mouse events or after the click.""" + # NOTE: By default we wait a couple frames between mouse events so pressed states will be rendered + from openpilot.system.ui.lib.application import MouseEvent, MousePos + + mouse_down = MouseEvent(pos=MousePos(x, y), slot=0, left_pressed=True, left_released=False, left_down=False, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_down]), after=wait_between) + mouse_up = MouseEvent(pos=MousePos(x, y), slot=0, left_pressed=False, left_released=True, left_down=False, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_up]), after=wait_after) + + def drag(self, start_x: int, start_y: int, direction: tuple[int, int], distance: int, duration_frames: int, wait_after: int = WAIT_LONG) -> None: + """Add a drag gesture to the script from start position in the specified direction by the given distance over the given number of frames.""" + from openpilot.system.ui.lib.application import MouseEvent, MousePos + + # Calculate delta and end position based on direction and distance + delta_x, delta_y = direction[0] * distance, direction[1] * distance + end_x, end_y = start_x + delta_x, start_y + delta_y + + # Mouse down at start + mouse_down = MouseEvent(pos=MousePos(start_x, start_y), slot=0, left_pressed=True, left_released=False, left_down=True, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_down]), after=1) + + # Interpolate positions over duration_frames + for i in range(1, duration_frames): + t = i / duration_frames + x, y = int(start_x + delta_x * t), int(start_y + delta_y * t) + mouse_move = MouseEvent(pos=MousePos(x, y), slot=0, left_pressed=False, left_released=False, left_down=True, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_move]), after=1) + + # Mouse up at end + mouse_up = MouseEvent(pos=MousePos(end_x, end_y), slot=0, left_pressed=False, left_released=True, left_down=False, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_up]), after=wait_after) + + +# --- Setup functions --- + + +def set_prime_state(prime_type: PrimeType) -> None: + from openpilot.selfdrive.ui.ui_state import ui_state + ui_state.prime_state.set_type(prime_type) + + +def setup_offroad_alerts() -> None: + set_offroad_alert("Offroad_TemperatureTooHigh", True, extra_text='99C') + set_offroad_alert("Offroad_ExcessiveActuation", True, extra_text='longitudinal') + set_offroad_alert("Offroad_IsTakingSnapshot", True) + + +def setup_update_available(available: bool = True) -> None: + params = Params() + params.put_bool("UpdateAvailable", available, block=True) + params.put("UpdaterAvailableBranches", ",".join(["test-branch", "test-branch-2", BRANCH_NAME]), block=True) + if available: + params.put("UpdaterNewDescription", f"0.10.2 / {BRANCH_NAME} / 0a1b2c3 / Jan 01", block=True) + params.put("UpdaterNewReleaseNotes", parse_release_notes(BASEDIR), block=True) + params.put("UpdaterTargetBranch", BRANCH_NAME, block=True) + else: + params.remove("UpdaterNewDescription") + params.remove("UpdaterNewReleaseNotes") + params.remove("UpdaterTargetBranch") + + +def setup_calibration_params() -> None: + params = Params() + # live calibration + calib = messaging.new_message('liveCalibration') + calib.liveCalibration.calStatus = log.LiveCalibrationData.Status.calibrated + calib.liveCalibration.rpyCalib = [0.0, math.radians(2.5), math.radians(-1.2)] + params.put("CalibrationParams", calib.to_bytes(), block=True) + # live delay + delay = messaging.new_message('liveDelay') + delay.liveDelay.calPerc = 75 + params.put("LiveDelay", delay.to_bytes(), block=True) + # live torque parameters + torque = messaging.new_message('liveTorqueParameters') + torque.liveTorqueParameters.useParams = True + torque.liveTorqueParameters.calPerc = 60 + params.put("LiveTorqueParameters", torque.to_bytes(), block=True) + + +def setup_developer_params() -> None: + CP = car.CarParams() + CP.alphaLongitudinalAvailable = True + Params().put("CarParamsPersistent", CP.to_bytes(), block=True) + + +# --- Send functions --- + +def send_onroad(pm: PubMaster) -> None: + ds = messaging.new_message('deviceState') + ds.deviceState.started = True + ds.deviceState.networkType = log.DeviceState.NetworkType.wifi + + ps = messaging.new_message('pandaStates', 1) + ps.pandaStates[0].pandaType = log.PandaState.PandaType.dos + ps.pandaStates[0].ignitionLine = True + + pm.send('deviceState', ds) + pm.send('pandaStates', ps) + + +def make_network_state_setup(pm: PubMaster, network_type) -> Callable: + def _send() -> None: + ds = messaging.new_message('deviceState') + ds.deviceState.networkType = network_type + pm.send('deviceState', ds) + return _send + + +def make_alert_setup(pm: PubMaster, size, text1, text2, status) -> Callable: + def _send() -> None: + alert = messaging.new_message('selfdriveState') + ss = alert.selfdriveState + ss.alertSize = size + ss.alertText1 = text1 + ss.alertText2 = text2 + ss.alertStatus = status + pm.send('selfdriveState', alert) + return _send + + +def test_onroad_alerts(script: Script, pm: PubMaster) -> None: + """Go through various alert types and sizes and add them to the script to test alert rendering. + Each alert is sent as a separate event with a delay in between.""" + # Small alert (normal) + script.set_send(make_alert_setup(pm, AlertSize.small, "Small Alert", "This is a small alert", AlertStatus.normal)) + # Medium alert (userPrompt) + script.set_send(make_alert_setup(pm, AlertSize.mid, "Medium Alert", "This is a medium alert", AlertStatus.userPrompt)) + # Full alert (critical) + script.set_send(make_alert_setup(pm, AlertSize.full, "DISENGAGE IMMEDIATELY", "Driver Distracted", AlertStatus.critical)) + # Full alert multiline + script.set_send(make_alert_setup(pm, AlertSize.full, "Reverse\nGear", "", AlertStatus.normal)) + # Full alert long text + script.set_send(make_alert_setup(pm, AlertSize.full, "TAKE CONTROL IMMEDIATELY", "Calibration Invalid: Remount Device & Recalibrate", AlertStatus.userPrompt)) + + +# --- Script builders --- + +def build_mici_script(pm: PubMaster, main_layout, script: Script) -> None: + """Build the replay script for the mici layout.""" + from openpilot.system.ui.lib.application import gui_app + + width, height = gui_app.width, gui_app.height + center = (width // 2, height // 2) + right = (width * 4 // 5, height // 2) + left = (width // 5, height // 2) + top = (width // 2, height // 10) + bottom = (width // 2, height * 9 // 10) + + DURATION = 5 + SWIPE_WAIT = FPS * 3 // 4 + + def click(times: int = 1, wait_after: int = WAIT_SHORT) -> None: + """Click at the center of the screen the given number of times with optional delay after.""" + for _ in range(times): + script.click(*center, wait_after=wait_after) + + def press(x: int, y: int, duration_frames: int = DURATION, wait_after: int = WAIT_SHORT) -> None: + """Perform a drag with no movement to simulate a left_down mouse event at the given position for the specified duration and delay after.""" + script.drag(x, y, (0, 0), 0, duration_frames, wait_after=wait_after) + + def swipe_left(distance: int = right[0] - left[0], duration_frames: int = DURATION, wait_after: int = SWIPE_WAIT) -> None: + """Drag from right edge to left (scroll right / slide confirmation).""" + script.drag(*right, DIR_LEFT, distance, duration_frames, wait_after) + + def swipe_right(distance: int = right[0] - left[0], duration_frames: int = DURATION, wait_after: int = SWIPE_WAIT) -> None: + """Drag from left edge to right (scroll left).""" + script.drag(*left, DIR_RIGHT, distance, duration_frames, wait_after) + + def swipe_down(distance: int = bottom[1] - top[1], duration_frames: int = DURATION, wait_after: int = SWIPE_WAIT) -> None: + """Drag from top edge to bottom (scroll up / go back).""" + script.drag(*top, DIR_DOWN, distance, duration_frames, wait_after) + + def swipe_up(distance: int = bottom[1] - top[1], duration_frames: int = DURATION, wait_after: int = SWIPE_WAIT) -> None: + """Drag from bottom edge to top (scroll down).""" + script.drag(*bottom, DIR_UP, distance, duration_frames, wait_after) + + ActionFn = Callable[[], None] | None + Cases = list[ActionFn] + + def run_actions(*actions: ActionFn, after_each: ActionFn = None) -> None: + """Helper function to run a sequence of actions in order for interaction tests, calling after_each callback after each action if provided.""" + for action in actions: + if action is not None: + action() + if after_each is not None: + after_each() + + def explore_setting(*actions: ActionFn) -> None: + """Helper function to open a settings item, run the given actions, and go back.""" + run_actions(click, *actions, swipe_down) # open, interact, go back + + def scroll_through_cases(cases: Cases) -> None: + """Helper function to explore a panel by calling the interaction callbacks for each item/page before swiping to the next one.""" + run_actions(*cases, after_each=lambda: swipe_left(210, 10)) # swipe to roughly the center of the next toggle after each case + + def interact_keyboard() -> None: + """Interact with the keyboard in various ways to test different actions and states. + Assumes it's a password keyboard with 8 characters required. Closes by pressing confirm at the end.""" + KEY = (250, 160) # key in the middle of the keyboard ('G') + SHIFT = (50, 210) + NUMBERS = (480, 210) + SPACE = (500, 160) + BACKSPACE = (490, 30) + CONFIRM = (50, 30) + # Begin interactions + press(*CONFIRM, wait_after=FAST_CLICK) # confirm while disabled should do nothing + swipe_left(duration_frames=FPS // 2) # swipe to type + swipe_up(duration_frames=FPS // 2) # swipe out of keyboard (nothing typed) + # press various keys to test different states: + for key in [ + SHIFT, KEY, KEY, SHIFT, SHIFT, KEY, KEY, # test casing (upper, lower, caps lock) + SPACE, SPACE, BACKSPACE, BACKSPACE, # test multiple space and backspace + NUMBERS, KEY, center, SHIFT, KEY # test numbers and symbols + ]: + press(*key, wait_after=FAST_CLICK) + # press confirm to close + script.wait(WAIT_SHORT) # wait for confirm to enable + press(*CONFIRM) + + toggle_cases: Cases = [ + lambda: click(times=3, wait_after=FAST_CLICK), # first toggle is personality, which has 3 states + None, None, None, None, None, None, # skip other toggles to save time + lambda: click(times=2, wait_after=FAST_CLICK), # test final toggle (enable openpilot) + ] + + network_cases: Cases = [ + explore_setting, # select wifi (just open and close) + None, None, + lambda: run_actions(click, interact_keyboard), # tether password keyboard + ] + + device_cases: Cases = [ + None, + click, # update + explore_setting, # pairing (just open and close) + lambda: explore_setting( + # training guide + lambda: swipe_left(width * 2), click, # first page, click next + lambda: swipe_left(width * 2), swipe_down # second page, go back (TODO: make driver cam preview work) + ), + None, # TODO: preview driver camera; enabling this causes MultiplePublishersError later in onroad alert tests + lambda: explore_setting(swipe_left), # terms & conditions (swipe to view QR code) + lambda: explore_setting(lambda: swipe_up(height * 3), lambda: swipe_down(height * 3)), # regulatory info + lambda: run_actions(click, lambda: swipe_left(width)), # reset calibration confirm (goes back automatically) + lambda: explore_setting(lambda: swipe_left(width)), # uninstall + lambda: run_actions( + lambda: explore_setting(lambda: swipe_left(width)), # reboot + lambda: script.click(430, 120), lambda: swipe_left(width), swipe_down, # shutdown + ), + ] + + developer_cases: Cases = [ + lambda: click(times=2, wait_after=FAST_CLICK), # toggle ssh mode + explore_setting, # SSH keys keyboard (just open and close) + None, # joystick mode + lambda: click(wait_after=FAST_CLICK), # longitudinal maneuver mode (disabled; should do nothing) + lambda: click(times=2, wait_after=FAST_CLICK), # toggle UI debug mode + ] + + settings_cases: Cases = [ + lambda: scroll_through_cases(toggle_cases), + lambda: scroll_through_cases(network_cases), + lambda: scroll_through_cases(device_cases), + lambda: script.wait(WAIT_SHORT), # pairing + lambda: run_actions(lambda: swipe_up(height * 3), lambda: swipe_down(height * 3)), # firehose (scroll down and back up) + lambda: scroll_through_cases(developer_cases), + ] + + # === Homescreen === # + script.wait(WAIT_SHORT) + swipe_left(width, wait_after=WAIT_SHORT) # onroad screen + swipe_right(width, wait_after=WAIT_SHORT) # back to home + + # === Offroad Alerts === + def setup_offroad_alerts_and_refresh() -> None: + """Setup function to trigger offroad alerts and force a refresh on the alerts layout.""" + setup_offroad_alerts() + params = Params() + main_layout._alerts_layout._pending_params = ({"UpdaterNewDescription": params.get("UpdaterNewDescription")} | + {alert_data.key: params.get(alert_data.key) for alert_data in main_layout._alerts_layout.sorted_alerts}) + main_layout._alerts_layout._refresh() + + swipe_right(width, wait_after=WAIT_SHORT) # open alerts + script.setup(setup_offroad_alerts_and_refresh) # show alerts + swipe_up(height) # scroll alerts + swipe_left(width, wait_after=WAIT_SHORT) # close alerts + + # === Settings === # + click() # open settings + scroll_through_cases([lambda case=case: explore_setting(case) for case in settings_cases]) # explore settings + swipe_down() # back to home + + # === Onroad === + script.set_send(lambda: send_onroad(pm)) + swipe_left(width, wait_after=WAIT_SHORT) # onroad screen + test_onroad_alerts(script, pm) + swipe_right(width) # back to home + + script.end() + + +def build_tizi_script(pm: PubMaster, main_layout, script: Script) -> None: + """Build the replay script for the tizi layout.""" + + def make_home_refresh_setup(fn: Callable) -> Callable: + """Return setup function that calls the given function to modify state and forces an immediate refresh on the home layout.""" + from openpilot.selfdrive.ui.layouts.main import MainState + + def setup(): + fn() + main_layout._layouts[MainState.HOME].last_refresh = 0 + + return setup + + def add_prime_state_setup(prime_type: PrimeType) -> None: + script.set_send(lambda: set_prime_state(prime_type)) + + def do_onboarding() -> None: + """Click through the training guide and close.""" + from openpilot.selfdrive.ui.layouts.onboarding import STEP_RECTS + step = 0 + for step_rect in STEP_RECTS: + if step < len(STEP_RECTS) - 1: + script.click(int(step_rect.x), int(step_rect.y), wait_after=FAST_CLICK) + else: + script.click(950, 900) # On the last step, click Finish instead of restart + step += 1 + + def type_keyboard() -> None: + """Types 8 characters using the big keyboard to test different layouts and interactions.""" + KEY = (150, 430) # e.g. 'Q' key + SHIFT = (150, 750) # also symbols key in number mode + NUMBERS = (150, 950) + SPACE = (1060, 950) + BACKSPACE = (2000, 780) + for key in [ + SHIFT, KEY, KEY, SHIFT, SHIFT, KEY, KEY, # test casing (upper, lower, caps lock) + SPACE, SPACE, BACKSPACE, BACKSPACE, # test multiple space and backspace + NUMBERS, KEY, KEY, SHIFT, KEY, KEY # test numbers and symbols + ]: + script.click(*key, wait_after=FAST_CLICK) + + # TODO: Better way of organizing the events + + # === Homescreen === + script.set_send(make_network_state_setup(pm, log.DeviceState.NetworkType.wifi)) + # Go through different prime state layouts + add_prime_state_setup(PrimeType.LITE) + add_prime_state_setup(PrimeType.NONE) + add_prime_state_setup(PrimeType.UNPAIRED) + + # === Update Available (auto-transitions via HomeLayout refresh) === + script.setup(make_home_refresh_setup(setup_update_available)) + + # === Offroad Alerts (auto-transitions via HomeLayout refresh, overrides update) === + script.setup(make_home_refresh_setup(setup_offroad_alerts)) + script.click(620, 950) # close alerts + + # === Settings (click sidebar settings button) === + script.click(150, 90) + + # === Settings - Device === + # pair device + script.click(2000, 450) # pair device + script.click(110, 110) # close pairing dialog + add_prime_state_setup(PrimeType.NONE) # changed from unpaired to hide pair device button + # calibration + script.setup(setup_calibration_params, wait_after=0) + script.click(1000, 620) # expand calibration description + script.click(2000, 620) # reset calibration confirmation + script.click(1500, 750) # confirm reset + script.click(1000, 620) # collapse calibration description + # training guide + script.click(2000, 800) # open training guide + do_onboarding() + # regulatory info + script.click(2000, 970) # regulatory button + script.click(2000, 970) # OK + + # === Settings - Network === + script.click(278, 450) + # TODO: mock networks + script.click(1880, 100) # advanced network settings + + # Keyboard (tethering password) + script.click(2000, 420, wait_after=FAST_CLICK) # open tether password keyboard + script.click(2000, 950, wait_after=FAST_CLICK) # click confirm (disabled, should not close) + script.click(2000, 115) # cancel (close without typing) + script.click(2000, 420, wait_after=FAST_CLICK) # open keyboard again + type_keyboard() # test various keyboard layouts and interactions + script.click(2050, 250, wait_after=FAST_CLICK) # toggle show/hide password + script.click(2000, 950) # confirm (close keyboard) + + script.click(630, 80) # back from advanced network + + # === Settings - Toggles === + script.click(278, 600) + script.click(1200, 280) # expand experimental mode description + + # === Settings - Software === + script.setup(lambda: setup_update_available(False), wait_after=0) # start with no update available + script.click(278, 720) # software + for _ in range(2): + script.click(720, 120) # toggle current release notes + script.setup(setup_update_available) # set update available + for _ in range(2): + script.click(720, 450) # toggle new release notes + script.click(2000, 630) # open select branch dialog + script.click(1000, 300) # select 1st option + script.click(1600, 900) # confirm selection + script.click(2000, 800) # uninstall + script.click(650, 750) # cancel uninstall + + # === Settings - Firehose === + script.click(278, 845) + + # === Settings - Developer (set CarParamsPersistent first) === + script.setup(setup_developer_params, wait_after=0) + script.click(278, 950) + script.click(1930, 470) # SSH keys (keyboard) + script.click(1930, 115) # click cancel on keyboard + script.click(2000, 960) # toggle alpha long + script.click(1500, 875) # confirm + + # === Close settings === + script.click(250, 160) + + # === Onroad === + script.set_send(lambda: send_onroad(pm)) + script.click(1000, 500) # click onroad to toggle sidebar + test_onroad_alerts(script, pm) + + # End + script.end() + + +def build_script(pm: PubMaster, main_layout, variant: LayoutVariant) -> list[ScriptEntry]: + """Build the replay script for the appropriate layout variant and return list of script entries.""" + print(f"Building {variant} replay script...") + + script = Script(FPS) + builder = build_tizi_script if variant == 'tizi' else build_mici_script + builder(pm, main_layout, script) + + print(f"Built replay script with {len(script.entries)} events and {script.frame} frames ({script.get_frame_time():.2f} seconds)") + + return script.entries diff --git a/selfdrive/ui/tests/profile_onroad.py b/selfdrive/ui/tests/profile_onroad.py new file mode 100755 index 00000000000000..18194d73630199 --- /dev/null +++ b/selfdrive/ui/tests/profile_onroad.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +import os +import time +import cProfile +import pyray as rl +import numpy as np + +from msgq.visionipc import VisionIpcServer, VisionStreamType +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout +from openpilot.system.ui.lib.application import gui_app +from openpilot.tools.lib.logreader import LogReader + +FPS = 60 + + +def chunk_messages_by_time(messages): + dt_ns = 1e9 / FPS + chunks = [] + current_services = {} + next_time = messages[0].logMonoTime + dt_ns if messages else 0 + + for msg in messages: + if msg.logMonoTime >= next_time: + chunks.append(current_services) + current_services = {} + next_time += dt_ns * ((msg.logMonoTime - next_time) // dt_ns + 1) + current_services[msg.which()] = msg + + if current_services: + chunks.append(current_services) + return chunks + + +def patch_submaster(message_chunks): + def mock_update(timeout=None): + sm = ui_state.sm + sm.updated = dict.fromkeys(sm.services, False) + current_time = time.monotonic() + for service, msg in message_chunks[sm.frame].items(): + if service in sm.data: + sm.seen[service] = True + sm.updated[service] = True + + msg_builder = msg.as_builder() + sm.data[service] = getattr(msg_builder, service) + sm.logMonoTime[service] = msg.logMonoTime + sm.recv_time[service] = current_time + sm.recv_frame[service] = sm.frame + sm.valid[service] = True + sm.frame += 1 + ui_state.sm.update = mock_update + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser(description='Profile openpilot UI rendering and state updates') + parser.add_argument('route', type=str, nargs='?', default="302bab07c1511180/00000006--0b9a7005f1/3", + help='Route to use for profiling') + parser.add_argument('--loop', type=int, default=1, + help='Number of times to loop the log (default: 1)') + parser.add_argument('--output', type=str, default='cachegrind.out.ui', + help='Output file prefix (default: cachegrind.out.ui)') + parser.add_argument('--max-seconds', type=float, default=None, + help='Maximum seconds of messages to process (default: all)') + parser.add_argument('--headless', action='store_true', + help='Run in headless mode without GPU (for CI/testing)') + args = parser.parse_args() + + print(f"Loading log from {args.route}...") + lr = LogReader(args.route, sort_by_time=True) + messages = list(lr) * args.loop + + print("Chunking messages...") + message_chunks = chunk_messages_by_time(messages) + if args.max_seconds: + message_chunks = message_chunks[:int(args.max_seconds * FPS)] + + print("Initializing UI with GPU rendering...") + + if args.headless: + os.environ['SDL_VIDEODRIVER'] = 'dummy' + + gui_app.init_window("UI Profiling", fps=600) + main_layout = MiciMainLayout() + + print("Running...") + patch_submaster(message_chunks) + + W, H = 2048, 1216 + vipc = VisionIpcServer("camerad") + vipc.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 5, W, H) + vipc.start_listener() + yuv_buffer_size = W * H + (W // 2) * (H // 2) * 2 + yuv_data = np.random.randint(0, 256, yuv_buffer_size, dtype=np.uint8).tobytes() + with cProfile.Profile() as pr: + for _ in gui_app.render(): + if ui_state.sm.frame >= len(message_chunks): + break + if ui_state.sm.frame % 3 == 0: + eof = int((ui_state.sm.frame % 3) * 0.05 * 1e9) + vipc.send(VisionStreamType.VISION_STREAM_ROAD, yuv_data, ui_state.sm.frame % 3, eof, eof) + ui_state.update() + pr.dump_stats(f'{args.output}_deterministic.stats') + + rl.close_window() + print("\nProfiling complete!") + print(f" run: python -m pstats {args.output}_deterministic.stats") diff --git a/selfdrive/ui/tests/test_bookmark_voice_note.py b/selfdrive/ui/tests/test_bookmark_voice_note.py new file mode 100644 index 00000000000000..8abaabea29e149 --- /dev/null +++ b/selfdrive/ui/tests/test_bookmark_voice_note.py @@ -0,0 +1,47 @@ +import os +import wave + +from openpilot.selfdrive.ui.feedback.feedbackd import VoiceNote, active_segment_dir, VOICE_NOTE_MAX_DURATION +from openpilot.system.micd import SAMPLE_RATE, SAMPLE_BUFFER + + +def _mkseg(root, name, lock): + d = root / name + d.mkdir() + (d / "rlog.zst").write_bytes(b"") + if lock: + (d / "rlog.lock").write_bytes(b"") + return d + + +def test_active_segment_dir_picks_locked(tmp_path): + _mkseg(tmp_path, "00000001--abc--0", lock=False) + live = _mkseg(tmp_path, "00000001--abc--1", lock=True) + assert active_segment_dir(str(tmp_path)) == str(live) + + +def test_active_segment_dir_none(tmp_path): + _mkseg(tmp_path, "00000001--abc--0", lock=False) + assert active_segment_dir(str(tmp_path)) is None + assert active_segment_dir(str(tmp_path / "missing")) is None + + +def test_voice_note_writes_wav(tmp_path): + note = VoiceNote(str(tmp_path), "20261014-070000") + blocks = int(VOICE_NOTE_MAX_DURATION * SAMPLE_RATE / SAMPLE_BUFFER) + for _ in range(blocks): + note.add(bytes(SAMPLE_BUFFER * 2)) + assert note.duration() >= VOICE_NOTE_MAX_DURATION + note.close() + path = tmp_path / "bookmark_20261014-070000.wav" + assert path.exists() and not os.path.exists(str(path) + ".tmp") + with wave.open(str(path)) as w: + assert w.getframerate() == SAMPLE_RATE + assert w.getnframes() == blocks * SAMPLE_BUFFER + + +def test_voice_note_without_segment(tmp_path): + note = VoiceNote(None, "x") + note.add(bytes(10)) + note.close() + assert note.path is None diff --git a/selfdrive/ui/tests/test_feedbackd.py b/selfdrive/ui/tests/test_feedbackd.py new file mode 100644 index 00000000000000..0f7148de04ea4f --- /dev/null +++ b/selfdrive/ui/tests/test_feedbackd.py @@ -0,0 +1,53 @@ +import pytest +import cereal.messaging as messaging +from cereal import car +from openpilot.common.params import Params +from openpilot.system.manager.process_config import managed_processes + + +@pytest.mark.skip("tmp disabled") +class TestFeedbackd: + def setup_method(self): + self.pm = messaging.PubMaster(['carState', 'rawAudioData']) + self.sm = messaging.SubMaster(['audioFeedback']) + + def _send_lkas_button(self, pressed: bool): + msg = messaging.new_message('carState') + msg.carState.canValid = True + msg.carState.buttonEvents = [{'type': car.CarState.ButtonEvent.Type.lkas, 'pressed': pressed}] + self.pm.send('carState', msg) + + def _send_audio_data(self, count: int = 5): + for _ in range(count): + audio_msg = messaging.new_message('rawAudioData') + audio_msg.rawAudioData.data = bytes(1600) # 800 samples of int16 + audio_msg.rawAudioData.sampleRate = 16000 + self.pm.send('rawAudioData', audio_msg) + self.sm.update(timeout=100) + + @pytest.mark.parametrize("record_feedback", [False, True]) + def test_audio_feedback(self, record_feedback): + Params().put_bool("RecordAudioFeedback", record_feedback, block=True) + + managed_processes["feedbackd"].start() + assert self.pm.wait_for_readers_to_update('carState', timeout=5) + assert self.pm.wait_for_readers_to_update('rawAudioData', timeout=5) + + self._send_lkas_button(pressed=True) + self._send_audio_data() + self._send_lkas_button(pressed=False) + self._send_audio_data() + + if record_feedback: + assert self.sm.updated['audioFeedback'], "audioFeedback should be published when enabled" + else: + assert not self.sm.updated['audioFeedback'], "audioFeedback should not be published when disabled" + + self._send_lkas_button(pressed=True) + self._send_audio_data() + self._send_lkas_button(pressed=False) + self._send_audio_data() + + assert not self.sm.updated['audioFeedback'], "audioFeedback should not be published after second press" + + managed_processes["feedbackd"].stop() diff --git a/selfdrive/ui/tests/test_radar_monitor.py b/selfdrive/ui/tests/test_radar_monitor.py new file mode 100644 index 00000000000000..5aa1adb4ba812e --- /dev/null +++ b/selfdrive/ui/tests/test_radar_monitor.py @@ -0,0 +1,132 @@ +from types import SimpleNamespace + +from openpilot.selfdrive.ui.radar.bosch_status import ( + ADDR_ALERT, + ADDR_CAR_CONFIG, + ADDR_SGU, + ADDR_VIN_FEED, + ADDR_VIN_HOST, + BoschRadarMonitor, + decode_car_config, + vin_mux_chars, +) + + +def _sgu(*, hw=0, sgu=0, dirty=0) -> bytes: + dat = bytearray(6) + if dirty: + dat[5] |= 1 << 4 + if hw: + dat[5] |= 1 << 5 + if sgu: + dat[5] |= 1 << 6 + return bytes(dat) + + +def _alert(*bits: int) -> bytes: + dat = bytearray(8) + for bit in bits: + dat[bit // 8] |= 1 << (bit % 8) + return bytes(dat) + + +def _tracks(*points): + pts = [ + SimpleNamespace(trackId=i, dRel=d, yRel=y, vRel=v, measured=True) + for i, (d, y, v) in enumerate(points) + ] + errors = SimpleNamespace(canError=False, radarFault=False, radarUnavailableTemporary=False) + return SimpleNamespace(points=pts, errors=errors) + + +def test_sgu_and_alert_bits(): + mon = BoschRadarMonitor() + status = mon.update(0.0, [ + (ADDR_CAR_CONFIG, bytes.fromhex("4a85555300200010"), 129), + (ADDR_SGU, _sgu(sgu=1), 1), + (ADDR_ALERT, _alert(36, 41, 60), 1), + ]) + assert status.sgu_fail is True + assert status.hw_fail is False + assert status.alerts == ("vinValidity", "xwdValidity", "radPositionMismatch") + assert status.health_label == "REJECT" + + +def test_chassis_bus_is_ignored(): + mon = BoschRadarMonitor() + status = mon.update(0.0, [ + (ADDR_SGU, _sgu(hw=1, sgu=1), 0), + (ADDR_ALERT, _alert(36), 0), + ]) + assert status.hw_fail is False + assert status.alerts == () + + +def test_returned_tx_still_counts(): + dat = bytes.fromhex("4a85555300200010") + assert decode_car_config(dat) == (True, 0, 2) + mon = BoschRadarMonitor() + status = mon.update(0.0, [(ADDR_CAR_CONFIG, dat, 129)]) + assert status.awd is True + assert status.position == 0 + assert status.epas_type == 2 + + +def test_vin_mux(): + assert vin_mux_chars(bytes([0x10, 0, 0, 0, 0, 0x35, 0x59, 0x4A])) == (0, ("5", "Y", "J")) + mon = BoschRadarMonitor() + mon.update(0.0, [ + (ADDR_VIN_FEED, bytes([0x10, 0, 0, 0, 0, 0x35, 0x59, 0x4A]), 129), + (ADDR_VIN_FEED, bytes([0x11, 0x53, 0x41, 0x31, 0x45, 0x34, 0x35, 0x46]), 129), + (ADDR_VIN_FEED, bytes([0x12, 0x46, 0x31, 0x30, 0x38, 0x34, 0x38, 0x35]), 129), + ]) + assert mon.status.vin == "5YJSA1E45FF108485" + + +def test_frozen_table(): + mon = BoschRadarMonitor() + frozen = _tracks((20.0, 0.1, -2.0), (30.0, -0.4, -1.5), (40.0, 0.2, 0.0), (50.0, 1.0, -0.5)) + status = None + for i in range(12): + status = mon.update(i * 0.5, [], frozen) + assert status is not None + assert status.table_frozen is True + assert status.health_label == "FROZEN" + + +def test_moving_table_is_live(): + mon = BoschRadarMonitor() + status = None + for i in range(12): + tracks = _tracks((20.0 + i, 0.1, -2.0), (30.0, -0.4, -1.5), (40.0, 0.2, 0.0), (50.0, 1.0, -0.5)) + status = mon.update(i * 0.5, [(ADDR_SGU, _sgu(), 1)], tracks) + assert status is not None + assert status.table_frozen is False + assert status.health_label == "LIVE" + + +def test_hw_fail_is_fault(): + mon = BoschRadarMonitor() + status = mon.update(0.0, [ + (ADDR_CAR_CONFIG, bytes.fromhex("4295555310001710"), 129), + (ADDR_SGU, _sgu(hw=1), 1), + ], None) + assert status.health_label == "FAULT" + + +def test_wait_vin_until_host_stream_and_gtw(): + mon = BoschRadarMonitor() + status = mon.update(0.0, [], None) + assert status.health_label == "WAIT VIN" + + status = mon.update(0.1, [ + (ADDR_VIN_HOST, bytes([0, 1, 1, 0, 0, 0x20, 0x20, 0x20]), 192), + (ADDR_VIN_HOST, bytes([1, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20]), 192), + (ADDR_VIN_HOST, bytes([2, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20]), 192), + ], None) + assert status.vin_stream_complete is True + assert status.health_label == "WAIT GTW" + + status = mon.update(0.2, [(ADDR_CAR_CONFIG, bytes.fromhex("4295555310001710"), 129)], None) + assert status.gtw_live is True + assert status.health_label == "NO TRACKS" diff --git a/selfdrive/ui/tests/test_raylib_ui.py b/selfdrive/ui/tests/test_raylib_ui.py new file mode 100644 index 00000000000000..69ba946dcd9ae3 --- /dev/null +++ b/selfdrive/ui/tests/test_raylib_ui.py @@ -0,0 +1,8 @@ +import time +from openpilot.selfdrive.test.helpers import with_processes + + +@with_processes(["ui"]) +def test_raylib_ui(): + """Test initialization of the UI widgets is successful.""" + time.sleep(1) diff --git a/selfdrive/ui/tests/test_runner.cc b/selfdrive/ui/tests/test_runner.cc deleted file mode 100644 index ac63139d178a89..00000000000000 --- a/selfdrive/ui/tests/test_runner.cc +++ /dev/null @@ -1,25 +0,0 @@ -#define CATCH_CONFIG_RUNNER -#include "catch2/catch.hpp" - -#include -#include -#include -#include - -int main(int argc, char **argv) { - // unit tests for Qt - QApplication app(argc, argv); - - QString language_file = "main_test_en"; - qDebug() << "Loading language:" << language_file; - - QTranslator translator; - QString translationsPath = QDir::cleanPath(qApp->applicationDirPath() + "/../translations"); - if (!translator.load(language_file, translationsPath)) { - qDebug() << "Failed to load translation file!"; - } - app.installTranslator(&translator); - - const int res = Catch::Session().run(argc, argv); - return (res < 0xff ? res : 0xff); -} diff --git a/selfdrive/ui/tests/test_soundd.py b/selfdrive/ui/tests/test_soundd.py index f40af8696a1baf..a9da8455ebdd24 100644 --- a/selfdrive/ui/tests/test_soundd.py +++ b/selfdrive/ui/tests/test_soundd.py @@ -1,7 +1,7 @@ from cereal import car from cereal import messaging from cereal.messaging import SubMaster, PubMaster -from openpilot.selfdrive.ui.soundd import CONTROLS_TIMEOUT, check_controls_timeout_alert +from openpilot.selfdrive.ui.soundd import SELFDRIVE_STATE_TIMEOUT, check_selfdrive_timeout_alert import time @@ -9,7 +9,7 @@ class TestSoundd: - def test_check_controls_timeout_alert(self): + def test_check_selfdrive_timeout_alert(self): sm = SubMaster(['selfdriveState']) pm = PubMaster(['selfdriveState']) @@ -23,13 +23,13 @@ def test_check_controls_timeout_alert(self): sm.update(0) - assert not check_controls_timeout_alert(sm) + assert not check_selfdrive_timeout_alert(sm) - for _ in range(CONTROLS_TIMEOUT * 110): + for _ in range(SELFDRIVE_STATE_TIMEOUT * 110): sm.update(0) time.sleep(0.01) - assert check_controls_timeout_alert(sm) + assert check_selfdrive_timeout_alert(sm) # TODO: add test with micd for checking that soundd actually outputs sounds diff --git a/selfdrive/ui/tests/test_translations.cc b/selfdrive/ui/tests/test_translations.cc deleted file mode 100644 index fcefc5784fee7a..00000000000000 --- a/selfdrive/ui/tests/test_translations.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include "catch2/catch.hpp" - -#include "common/params.h" -#include "selfdrive/ui/qt/window.h" - -const QString TEST_TEXT = "(WRAPPED_SOURCE_TEXT)"; // what each string should be translated to -QRegExp RE_NUM("\\d*"); - -QStringList getParentWidgets(QWidget* widget){ - QStringList parentWidgets; - while (widget->parentWidget() != Q_NULLPTR) { - widget = widget->parentWidget(); - parentWidgets.append(widget->metaObject()->className()); - } - return parentWidgets; -} - -template -void checkWidgetTrWrap(MainWindow &w) { - for (auto widget : w.findChildren()) { - const QString text = widget->text(); - bool isNumber = RE_NUM.exactMatch(text); - bool wrapped = text.contains(TEST_TEXT); - QString parentWidgets = getParentWidgets(widget).join("->"); - - if (!text.isEmpty() && !isNumber && !wrapped) { - FAIL(("\"" + text + "\" must be wrapped. Parent widgets: " + parentWidgets).toStdString()); - } - - // warn if source string wrapped, but UI adds text - // TODO: add way to ignore this - if (wrapped && text != TEST_TEXT) { - WARN(("\"" + text + "\" is dynamic and needs a custom retranslate function. Parent widgets: " + parentWidgets).toStdString()); - } - } -} - -// Tests all strings in the UI are wrapped with tr() -TEST_CASE("UI: test all strings wrapped") { - Params().remove("LanguageSetting"); - Params().remove("HardwareSerial"); - Params().remove("DongleId"); - qputenv("TICI", "1"); - - MainWindow w; - checkWidgetTrWrap(w); - checkWidgetTrWrap(w); -} diff --git a/selfdrive/ui/tests/test_translations.py b/selfdrive/ui/tests/test_translations.py index 0967152fa4bb95..fba595acadb3f4 100644 --- a/selfdrive/ui/tests/test_translations.py +++ b/selfdrive/ui/tests/test_translations.py @@ -1,129 +1,106 @@ -import pytest import json -import os import re -import shutil -import tempfile -import xml.etree.ElementTree as ET import string -import requests -from parameterized import parameterized_class - -from openpilot.selfdrive.ui.update_translations import TRANSLATIONS_DIR, LANGUAGES_FILE, update_translations - -with open(LANGUAGES_FILE) as f: - translation_files = json.load(f) - -UNFINISHED_TRANSLATION_TAG = "" not in cur_translations, \ - f"{self.file} ({self.name}) translation file has obsolete translations. Run selfdrive/ui/update_translations.py --vanish to remove them" - - def test_finished_translations(self): - """ - Tests ran on each translation marked "finished" - Plural: - - that any numerus (plural) translations have all plural forms non-empty - - that the correct format specifier is used (%n) - Non-plural: - - that translation is not empty - - that translation format arguments are consistent - """ - tr_xml = ET.parse(os.path.join(TRANSLATIONS_DIR, f"{self.file}.ts")) - - for context in tr_xml.getroot(): - for message in context.iterfind("message"): - translation = message.find("translation") - source_text = message.find("source").text - - # Do not test unfinished translations - if translation.get("type") == "unfinished": - continue +from pathlib import Path - if message.get("numerus") == "yes": - numerusform = [t.text for t in translation.findall("numerusform")] +import pytest - for nf in numerusform: - assert nf is not None, f"Ensure all plural translation forms are completed: {source_text}" - assert "%n" in nf, "Ensure numerus argument (%n) exists in translation." - assert FORMAT_ARG.search(nf) is None, f"Plural translations must use %n, not %1, %2, etc.: {numerusform}" +from openpilot.selfdrive.ui.translations.potools import parse_po +from openpilot.system.ui.lib.multilang import LANGUAGES_FILE, TRANSLATIONS_DIR - else: - assert translation.text is not None, f"Ensure translation is completed: {source_text}" +PERCENT_PLACEHOLDER_RE = re.compile(r"%(?:n|\d+)") +BAD_ENTITY_RE = re.compile(r'@(\w+);') +LINE_NUMBER_REF_RE = re.compile(r'^#:\s+.+:\d+(?:\s|$)') +FORMATTER = string.Formatter() +PO_DIR = Path(str(TRANSLATIONS_DIR)) - source_args = FORMAT_ARG.findall(source_text) - translation_args = FORMAT_ARG.findall(translation.text) - assert sorted(source_args) == sorted(translation_args), \ - f"Ensure format arguments are consistent: `{source_text}` vs. `{translation.text}`" +with LANGUAGES_FILE.open(encoding='utf-8') as f: + TRANSLATION_LANGUAGES = json.load(f) - def test_no_locations(self): - for line in self._read_translation_file(TRANSLATIONS_DIR, self.file).splitlines(): - assert not line.strip().startswith(LOCATION_TAG), \ - f"Line contains location tag: {line.strip()}, remove all line numbers." - def test_entities_error(self): - cur_translations = self._read_translation_file(TRANSLATIONS_DIR, self.file) - matches = re.findall(r'@(\w+);', cur_translations) - assert len(matches) == 0, f"The string(s) {matches} were found with '@' instead of '&'" +def extract_placeholders(text: str) -> list[str]: + placeholders = PERCENT_PLACEHOLDER_RE.findall(text) - def test_bad_language(self): - IGNORED_WORDS = {'pédale'} + try: + parsed = list(FORMATTER.parse(text)) + except ValueError as e: + raise AssertionError(f"invalid brace formatting in {text!r}: {e}") from e - match = re.search(r'_([a-zA-Z]{2,3})', self.file) - assert match, f"{self.name} - could not parse language" + for _, field_name, format_spec, conversion in parsed: + if field_name is None: + continue - response = requests.get(f"https://raw.githubusercontent.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/master/{match.group(1)}") - response.raise_for_status() + token = "{" + token += field_name + if conversion: + token += f"!{conversion}" + if format_spec: + token += f":{format_spec}" + token += "}" + placeholders.append(token) - banned_words = {line.strip() for line in response.text.splitlines()} + return sorted(placeholders) - for context in ET.parse(os.path.join(TRANSLATIONS_DIR, f"{self.file}.ts")).getroot(): - for message in context.iterfind("message"): - translation = message.find("translation") - if translation.get("type") == "unfinished": - continue - translation_text = " ".join([t.text for t in translation.findall("numerusform")]) if message.get("numerus") == "yes" else translation.text +def load_po_text(po_path: Path) -> str: + return po_path.read_text(encoding='utf-8') + + +@pytest.mark.parametrize("language_code", sorted(TRANSLATION_LANGUAGES.values())) +def test_translation_file_exists(language_code: str): + po_path = PO_DIR / f"app_{language_code}.po" + assert po_path.exists(), f"missing translation file: {po_path}" + + +@pytest.mark.parametrize("po_path", sorted(PO_DIR.glob("app_*.po")), ids=lambda p: p.name) +def test_translation_placeholders_are_preserved(po_path: Path): + _, entries = parse_po(po_path) + language = po_path.stem.removeprefix("app_") + + for entry in entries: + source_placeholders = extract_placeholders(entry.msgid) + + if entry.is_plural: + plural_placeholders = extract_placeholders(entry.msgid_plural) + message = ( + f"{language}: source plural placeholders do not match singular for " + + f"{entry.msgid!r}: {source_placeholders} vs {plural_placeholders}" + ) + assert plural_placeholders == source_placeholders, message - if not translation_text: + for idx, msgstr in sorted(entry.msgstr_plural.items()): + if not msgstr: continue - words = set(translation_text.translate(str.maketrans('', '', string.punctuation + '%n')).lower().split()) - bad_words_found = words & (banned_words - IGNORED_WORDS) - assert not bad_words_found, f"Bad language found in {self.name}: '{translation_text}'. Bad word(s): {', '.join(bad_words_found)}" + translated_placeholders = extract_placeholders(msgstr) + message = ( + f"{language}: plural form {idx} changes placeholders for {entry.msgid!r}: " + + f"expected {source_placeholders}, got {translated_placeholders}" + ) + assert translated_placeholders == source_placeholders, message + else: + if not entry.msgstr: + continue + + translated_placeholders = extract_placeholders(entry.msgstr) + message = ( + f"{language}: translation changes placeholders for {entry.msgid!r}: " + + f"expected {source_placeholders}, got {translated_placeholders}" + ) + assert translated_placeholders == source_placeholders, message + + +@pytest.mark.parametrize("po_path", sorted(PO_DIR.glob("app_*.po")), ids=lambda p: p.name) +def test_translation_refs_do_not_include_line_numbers(po_path: Path): + for line in load_po_text(po_path).splitlines(): + assert not LINE_NUMBER_REF_RE.match(line), ( + f"{po_path.name}: line-number source reference found: {line}" + ) + + +@pytest.mark.parametrize("po_path", sorted(PO_DIR.glob("app_*.po")), ids=lambda p: p.name) +def test_translation_entities_are_valid(po_path: Path): + matches = BAD_ENTITY_RE.findall(load_po_text(po_path)) + assert not matches, ( + f"{po_path.name}: found '@...;' entity typo(s): {', '.join(sorted(set(matches)))}" + ) diff --git a/selfdrive/ui/tests/test_triple_tap.py b/selfdrive/ui/tests/test_triple_tap.py new file mode 100644 index 00000000000000..3c58224e231d59 --- /dev/null +++ b/selfdrive/ui/tests/test_triple_tap.py @@ -0,0 +1,171 @@ +"""Triple-tap detector + hidden-NAP-toggle placement (no GUI).""" +from pathlib import Path + +from openpilot.selfdrive.ui.layouts.settings.triple_tap import ( + MICI_NAP_OPEN_DELAY_S, + TAP_COUNT, + TripleTapDetector, + WINDOW_S, +) + +ROOT = Path(__file__).resolve().parents[3] + + +def _code_without_comments(src: str) -> str: + """Drop '# ...' tails so source-string checks ignore comments.""" + return "\n".join(line.split("#", 1)[0] for line in src.splitlines()) + + +def test_window_and_count_constants(): + assert WINDOW_S == 1.0 + assert TAP_COUNT == 3 + assert MICI_NAP_OPEN_DELAY_S == 0.40 + assert MICI_NAP_OPEN_DELAY_S < WINDOW_S + + +def test_three_taps_inside_window_fire(): + d = TripleTapDetector() + assert d.tap(0.00) is False + assert d.pending_count == 1 + assert d.tap(0.40) is False + assert d.tap(0.90) is True + assert d.pending_count == 0 + + +def test_three_taps_exactly_at_window_edge_fire(): + d = TripleTapDetector() + assert d.tap(1.00) is False + assert d.tap(1.50) is False + assert d.tap(2.00) is True + + +def test_slow_taps_do_not_fire(): + d = TripleTapDetector() + assert d.tap(0.00) is False + assert d.tap(0.60) is False + assert d.tap(1.61) is False + assert d.pending_count == 1 # only the last tap remains + + +def test_sliding_window_keeps_recent_pair(): + d = TripleTapDetector() + assert d.tap(0.00) is False + assert d.tap(0.70) is False + # 0.00 drops out; [0.70, 1.50] is only two taps + assert d.tap(1.50) is False + assert d.pending_count == 2 + assert d.tap(1.60) is True + + +def test_reset_clears_burst(): + d = TripleTapDetector() + d.tap(0.00) + d.tap(0.20) + d.reset() + assert d.pending_count == 0 + assert d.tap(0.30) is False + + +def test_hidden_toggles_removed_from_normal_lists(): + tici_dm = (ROOT / "selfdrive/ui/layouts/settings/driving_mannerisms.py").read_text() + mici_dm = (ROOT / "selfdrive/ui/mici/layouts/settings/driving_mannerisms.py").read_text() + nap = (ROOT / "selfdrive/ui/layouts/settings/nap.py").read_text() + nap_mici = (ROOT / "selfdrive/ui/mici/layouts/settings/nap.py").read_text() + popup = (ROOT / "selfdrive/ui/layouts/settings/hidden_toggles.py").read_text() + overlay = (ROOT / "selfdrive/ui/mici/layouts/settings/hidden_toggles.py").read_text() + settings = (ROOT / "selfdrive/ui/layouts/settings/settings.py").read_text() + settings_mici = (ROOT / "selfdrive/ui/mici/layouts/settings/settings.py").read_text() + + assert "Simulate Look" not in tici_dm + assert "False Alert Ignore" not in tici_dm + assert "NAP_DM_SIMULATE_LOOKING" not in tici_dm + assert "NAP_DM_FALSE_ALERT_IGNORE" not in tici_dm + assert "simulate look" not in mici_dm + assert "false alert ignore" not in mici_dm + assert "NAP_DM_SIMULATE_LOOKING" not in mici_dm + assert "NAP_DM_FALSE_ALERT_IGNORE" not in mici_dm + + assert 'self._add_toggle(\n NAP_FORCE_OFFROAD' not in nap + assert "Go Offline" not in nap + assert "simulate look" not in nap + assert "false alert ignore" not in nap + assert 'put_bool(NAP_FORCE_OFFROAD, False)' in nap + assert "NAPForceOffroadConfirmed" in nap + assert 'put_bool(NAP_DM_SIMULATE_LOOKING, True)' in nap + assert 'put_bool(NAP_DM_FALSE_ALERT_IGNORE, False)' in nap + + assert 'BigParamControl("force offroad"' not in nap_mici + assert "NAP_FORCE_OFFROAD" not in nap_mici + + assert "Simulate Look" in popup + assert "False Alert Ignore" in popup + assert "Force Offroad" in popup + assert "[self._offroad_item, self._dm_item, self._fai_item, self._cone_log_item]" in popup + assert "NAP_DM_SIMULATE_LOOKING" in popup + assert "NAP_DM_FALSE_ALERT_IGNORE" in popup + assert "NAP_FORCE_OFFROAD" in popup + assert "apply_force_offroad_toggle" in popup + assert "apply_dm_simulate_looking" in popup + assert "apply_dm_false_alert_ignore" in popup + assert "read_exclusive_dm_toggles" in popup + # Live switch: paint sibling from apply() return, not a stale get_bool. + on_sim = _code_without_comments( + popup[popup.index("def _on_dm_sim_looking"):popup.index("def _on_false_alert_ignore")] + ) + on_fai = _code_without_comments( + popup[popup.index("def _on_false_alert_ignore"):popup.index("def _on_force_offroad")] + ) + assert "apply_dm_simulate_looking(self._params, bool(state))" in on_sim + assert "set_state(fai)" in on_sim + assert "get_bool(" not in on_sim + assert "apply_dm_false_alert_ignore(self._params, bool(state))" in on_fai + assert "set_state(sim)" in on_fai + assert "get_bool(" not in on_fai + assert "set_enabled(ui_state.is_offroad)" not in popup + assert popup.index('"Force Offroad"') < popup.index('"Simulate Look"') + assert popup.index('"Simulate Look"') < popup.index('"False Alert Ignore"') + + assert "simulate look" in overlay + assert "false alert ignore" in overlay + assert "force offroad" in overlay + assert overlay.index('BigParamControl("force offroad"') < overlay.index('BigParamControl("simulate look"') + assert overlay.index('BigParamControl("simulate look"') < overlay.index('BigParamControl("false alert ignore"') + assert "NAP_DM_SIMULATE_LOOKING" in overlay + assert "NAP_DM_FALSE_ALERT_IGNORE" in overlay + assert "NAP_FORCE_OFFROAD" in overlay + assert "apply_dm_simulate_looking" in overlay + assert "apply_dm_false_alert_ignore" in overlay + assert "read_exclusive_dm_toggles" in overlay + on_sim_m = _code_without_comments( + overlay[overlay.index("def _on_simulate_look"):overlay.index("def _on_false_alert_ignore")] + ) + on_fai_m = _code_without_comments( + overlay[overlay.index("def _on_false_alert_ignore"):overlay.index("def show_event")] + ) + assert "apply_dm_simulate_looking(self._params, bool(state))" in on_sim_m + assert "set_checked(fai)" in on_sim_m + assert "refresh()" not in on_sim_m + assert "get_bool(" not in on_sim_m + assert "apply_dm_false_alert_ignore(self._params, bool(state))" in on_fai_m + assert "set_checked(sim)" in on_fai_m + assert "refresh()" not in on_fai_m + assert "get_bool(" not in on_fai_m + assert "set_enabled(ui_state.is_offroad)" not in overlay + + assert "TripleTapDetector" in settings + assert "_on_nap_sidebar_tap" in settings + assert "_handle_mouse_release" in settings + assert "TripleTapDetector" in settings_mici + assert "_on_nap_clicked" in settings_mici + assert "HiddenTogglesOverlayMici" in settings_mici + + # Soft-lat / One-Pedal Long / Hypermile / Hill Climb / Acceleration stay on the normal mannerisms list. + assert "Soft Lateral Handoff" in tici_dm + assert "One-Pedal Long" in tici_dm + assert "Hill Climb" in tici_dm + assert "Hypermile" in tici_dm + assert "Acceleration" in tici_dm + assert "NAPMapSpeedAccel" in tici_dm + assert "hill climb" in mici_dm + assert '"acceleration"' in mici_dm + assert "NAPMapSpeedAccel" in mici_dm diff --git a/selfdrive/ui/tests/test_ui/run.py b/selfdrive/ui/tests/test_ui/run.py deleted file mode 100644 index 1a075b3c44f2a1..00000000000000 --- a/selfdrive/ui/tests/test_ui/run.py +++ /dev/null @@ -1,255 +0,0 @@ -from collections import namedtuple -import capnp -import pathlib -import shutil -import sys -import jinja2 -import matplotlib.pyplot as plt -import numpy as np -import os -import pywinctl -import time - -from cereal import messaging, log -from msgq.visionipc import VisionIpcServer, VisionStreamType -from cereal.messaging import SubMaster, PubMaster -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.common.prefix import OpenpilotPrefix -from openpilot.common.transformations.camera import CameraConfig, DEVICE_CAMERAS -from openpilot.selfdrive.controls.lib.alertmanager import set_offroad_alert -from openpilot.selfdrive.test.helpers import with_processes -from openpilot.selfdrive.test.process_replay.migration import migrate_controlsState -from openpilot.tools.lib.logreader import LogReader -from openpilot.tools.lib.framereader import FrameReader -from openpilot.tools.lib.route import Route - -UI_DELAY = 0.5 # may be slower on CI? -TEST_ROUTE = "a2a0ccea32023010|2023-07-27--13-01-19" - -STREAMS: list[tuple[VisionStreamType, CameraConfig, bytes]] = [] -OFFROAD_ALERTS = ['Offroad_StorageMissing', 'Offroad_IsTakingSnapshot'] -DATA: dict[str, capnp.lib.capnp._DynamicStructBuilder] = dict.fromkeys( - ["carParams", "deviceState", "pandaStates", "controlsState", "selfdriveState", - "liveCalibration", "modelV2", "radarState", "driverMonitoringState", "carState", - "driverStateV2", "roadCameraState", "wideRoadCameraState", "driverCameraState"], None) - -def setup_common(click, pm: PubMaster): - Params().put("DongleId", "123456789012345") - pm.send('deviceState', DATA['deviceState']) - -def setup_homescreen(click, pm: PubMaster): - setup_common(click, pm) - -def setup_settings_device(click, pm: PubMaster): - setup_common(click, pm) - - click(100, 100) - -def setup_onroad(click, pm: PubMaster): - setup_common(click, pm) - - vipc_server = VisionIpcServer("camerad") - for stream_type, cam, _ in STREAMS: - vipc_server.create_buffers(stream_type, 5, False, cam.width, cam.height) - vipc_server.start_listener() - - packet_id = 0 - for _ in range(20): - for service, data in DATA.items(): - if data: - data.clear_write_flag() - pm.send(service, data) - - packet_id = packet_id + 1 - for stream_type, _, image in STREAMS: - vipc_server.send(stream_type, image, packet_id, packet_id, packet_id) - - time.sleep(0.05) - -def setup_onroad_wide(click, pm: PubMaster): - DATA['selfdriveState'].selfdriveState.experimentalMode = True - DATA["carState"].carState.vEgo = 1 - setup_onroad(click, pm) - -def setup_onroad_sidebar(click, pm: PubMaster): - setup_onroad(click, pm) - click(500, 500) - -def setup_onroad_wide_sidebar(click, pm: PubMaster): - setup_onroad_wide(click, pm) - click(500, 500) - -def setup_body(click, pm: PubMaster): - DATA['carParams'].carParams.carName = "BODY" - DATA['carParams'].carParams.notCar = True - DATA['carState'].carState.charging = True - DATA['carState'].carState.fuelGauge = 50.0 - setup_onroad(click, pm) - -def setup_driver_camera(click, pm: PubMaster): - setup_settings_device(click, pm) - click(1950, 435) - DATA['deviceState'].deviceState.started = False - setup_onroad(click, pm) - DATA['deviceState'].deviceState.started = True - -def setup_onroad_alert(click, pm: PubMaster, text1, text2, size, status=log.SelfdriveState.AlertStatus.normal): - print(f'setup onroad alert, size: {size}') - setup_onroad(click, pm) - dat = messaging.new_message('selfdriveState') - cs = dat.selfdriveState - cs.alertText1 = text1 - cs.alertText2 = text2 - cs.alertSize = size - cs.alertStatus = status - cs.alertType = "test_onroad_alert" - pm.send('selfdriveState', dat) - -def setup_onroad_alert_small(click, pm: PubMaster): - setup_onroad_alert(click, pm, 'This is a small alert message', '', log.SelfdriveState.AlertSize.small) - -def setup_onroad_alert_mid(click, pm: PubMaster): - setup_onroad_alert(click, pm, 'Medium Alert', 'This is a medium alert message', log.SelfdriveState.AlertSize.mid) - -def setup_onroad_alert_full(click, pm: PubMaster): - setup_onroad_alert(click, pm, 'Full Alert', 'This is a full alert message', log.SelfdriveState.AlertSize.full) - -def setup_offroad_alert(click, pm: PubMaster): - setup_common(click, pm) - for alert in OFFROAD_ALERTS: - set_offroad_alert(alert, True) - - # Toggle between settings and home to refresh the offroad alert widget - setup_settings_device(click, pm) - click(240, 216) - -def setup_update_available(click, pm: PubMaster): - setup_common(click, pm) - Params().put_bool("UpdateAvailable", True) - release_notes_path = os.path.join(BASEDIR, "RELEASES.md") - with open(release_notes_path) as file: - release_notes = file.read().split('\n\n', 1)[0] - Params().put("UpdaterNewReleaseNotes", release_notes + "\n") - - setup_settings_device(click, pm) - click(240, 216) - - -CASES = { - "homescreen": setup_homescreen, - "settings_device": setup_settings_device, - "onroad": setup_onroad, - "onroad_sidebar": setup_onroad_sidebar, - "onroad_alert_small": setup_onroad_alert_small, - "onroad_alert_mid": setup_onroad_alert_mid, - "onroad_alert_full": setup_onroad_alert_full, - "onroad_wide": setup_onroad_wide, - "onroad_wide_sidebar": setup_onroad_wide_sidebar, - "driver_camera": setup_driver_camera, - "body": setup_body, - "offroad_alert": setup_offroad_alert, - "update_available": setup_update_available -} - -TEST_DIR = pathlib.Path(__file__).parent - -TEST_OUTPUT_DIR = TEST_DIR / "report_1" -SCREENSHOTS_DIR = TEST_OUTPUT_DIR / "screenshots" - - -class TestUI: - def __init__(self): - os.environ["SCALE"] = "1" - sys.modules["mouseinfo"] = False - - def setup(self): - self.sm = SubMaster(["uiDebug"]) - self.pm = PubMaster(list(DATA.keys())) - while not self.sm.valid["uiDebug"]: - self.sm.update(1) - time.sleep(UI_DELAY) # wait a bit more for the UI to start rendering - try: - self.ui = pywinctl.getWindowsWithTitle("ui")[0] - except Exception as e: - print(f"failed to find ui window, assuming that it's in the top left (for Xvfb) {e}") - self.ui = namedtuple("bb", ["left", "top", "width", "height"])(0,0,2160,1080) - - def screenshot(self): - import pyautogui - im = pyautogui.screenshot(region=(self.ui.left, self.ui.top, self.ui.width, self.ui.height)) - assert im.width == 2160 - assert im.height == 1080 - img = np.array(im) - im.close() - return img - - def click(self, x, y, *args, **kwargs): - import pyautogui - pyautogui.click(self.ui.left + x, self.ui.top + y, *args, **kwargs) - time.sleep(UI_DELAY) # give enough time for the UI to react - - @with_processes(["ui"]) - def test_ui(self, name, setup_case): - self.setup() - - setup_case(self.click, self.pm) - - time.sleep(UI_DELAY) # wait a bit more for the UI to finish rendering - - im = self.screenshot() - plt.imsave(SCREENSHOTS_DIR / f"{name}.png", im) - - -def create_html_report(): - OUTPUT_FILE = TEST_OUTPUT_DIR / "index.html" - - with open(TEST_DIR / "template.html") as f: - template = jinja2.Template(f.read()) - - cases = {f.stem: (str(f.relative_to(TEST_OUTPUT_DIR)), "reference.png") for f in SCREENSHOTS_DIR.glob("*.png")} - cases = dict(sorted(cases.items())) - - with open(OUTPUT_FILE, "w") as f: - f.write(template.render(cases=cases)) - -def create_screenshots(): - if TEST_OUTPUT_DIR.exists(): - shutil.rmtree(TEST_OUTPUT_DIR) - - SCREENSHOTS_DIR.mkdir(parents=True) - - route = Route(TEST_ROUTE) - - segnum = 2 - lr = LogReader(route.qlog_paths()[segnum]) - DATA['carParams'] = next((event.as_builder() for event in lr if event.which() == 'carParams'), None) - for event in migrate_controlsState(lr): - if event.which() in DATA: - DATA[event.which()] = event.as_builder() - - if all(DATA.values()): - break - - cam = DEVICE_CAMERAS[("tici", "ar0231")] - road_img = FrameReader(route.camera_paths()[segnum]).get(0, pix_fmt="nv12")[0] - STREAMS.append((VisionStreamType.VISION_STREAM_ROAD, cam.fcam, road_img.flatten().tobytes())) - - wide_road_img = FrameReader(route.ecamera_paths()[segnum]).get(0, pix_fmt="nv12")[0] - STREAMS.append((VisionStreamType.VISION_STREAM_WIDE_ROAD, cam.ecam, wide_road_img.flatten().tobytes())) - - driver_img = FrameReader(route.dcamera_paths()[segnum]).get(0, pix_fmt="nv12")[0] - STREAMS.append((VisionStreamType.VISION_STREAM_DRIVER, cam.dcam, driver_img.flatten().tobytes())) - - t = TestUI() - - with OpenpilotPrefix(): - for name, setup in CASES.items(): - t.test_ui(name, setup) - -if __name__ == "__main__": - print("creating test screenshots") - create_screenshots() - - print("creating html report") - create_html_report() diff --git a/selfdrive/ui/tests/test_ui/template.html b/selfdrive/ui/tests/test_ui/template.html deleted file mode 100644 index 68df5879e6692c..00000000000000 --- a/selfdrive/ui/tests/test_ui/template.html +++ /dev/null @@ -1,34 +0,0 @@ - - - - -{% for name, (image, ref_image) in cases.items() %} - -

{{name}}

-
-
- -
-
- -
- -{% endfor %} - \ No newline at end of file diff --git a/selfdrive/ui/text b/selfdrive/ui/text deleted file mode 100755 index b12235f4e6a00e..00000000000000 --- a/selfdrive/ui/text +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -if [ -f /TICI ] && [ ! -f _text ]; then - cp qt/text_larch64 _text -fi - -exec ./_text "$1" diff --git a/selfdrive/ui/translations/README.md b/selfdrive/ui/translations/README.md deleted file mode 100644 index 4f11fe3388bccc..00000000000000 --- a/selfdrive/ui/translations/README.md +++ /dev/null @@ -1,71 +0,0 @@ -# Multilanguage - -[![languages](https://raw.githubusercontent.com/commaai/openpilot/badges/translation_badge.svg)](#) - -## Contributing - -Before getting started, make sure you have set up the openpilot Ubuntu development environment by reading the [tools README.md](/tools/README.md). - -### Policy - -Most of the languages supported by openpilot come from and are maintained by the community via pull requests. A pull request likely to be merged is one that [fixes a translation or adds missing translations.](https://github.com/commaai/openpilot/blob/master/selfdrive/ui/translations/README.md#improving-an-existing-language) - -We also generally merge pull requests adding support for a new language if there are community members willing to maintain it. Maintaining a language is ensuring quality and completion of translations before each openpilot release. - -comma may remove or hide language support from releases depending on translation quality and completeness. - -### Adding a New Language - -openpilot provides a few tools to help contributors manage their translations and to ensure quality. To get started: - -1. Add your new language to [languages.json](/selfdrive/ui/translations/languages.json) with the appropriate [language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) and the localized language name (Traditional Chinese is `中文(繁體)`). -2. Generate the XML translation file (`*.ts`): - ```shell - selfdrive/ui/update_translations.py - ``` -3. Edit the translation file, marking each translation as completed: - ```shell - linguist selfdrive/ui/translations/your_language_file.ts - ``` -4. View your finished translations by compiling and starting the UI, then find it in the language selector: - ```shell - scons -j$(nproc) selfdrive/ui && selfdrive/ui/ui - ``` -5. Read [Checking the UI](#checking-the-ui) to double-check your translations fit in the UI. - -### Improving an Existing Language - -Follow step 3. above, you can review existing translations and add missing ones. Once you're done, just open a pull request to openpilot. - -### Checking the UI -Different languages use varying space to convey the same message, so it's a good idea to double-check that your translations do not overlap and fit into each widget. Start the UI (step 4. above) and view each page, making adjustments to translations as needed. - -#### To view offroad alerts: - -With the UI started, you can view the offroad alerts with: -```shell -selfdrive/ui/tests/cycle_offroad_alerts.py -``` - -### Updating the UI - -Any time you edit source code in the UI, you need to update the translations to ensure the line numbers and contexts are up to date (first step above). - -### Testing - -openpilot has a few unit tests to make sure all translations are up-to-date and that all strings are wrapped in a translation marker. They are run in CI, but you can also run them locally. - -Tests translation files up to date: - -```shell -selfdrive/ui/tests/test_translations.py -``` - -Tests all static source strings are wrapped: - -```shell -selfdrive/ui/tests/create_test_translations.sh && selfdrive/ui/tests/test_translations -``` - ---- -![multilanguage_onroad](https://user-images.githubusercontent.com/25857203/178912800-2c798af8-78e3-498e-9e19-35906e0bafff.png) diff --git a/selfdrive/ui/translations/app.pot b/selfdrive/ui/translations/app.pot new file mode 100644 index 00000000000000..0872ed538e3021 --- /dev/null +++ b/selfdrive/ui/translations/app.pot @@ -0,0 +1,823 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "" + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "" + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "" + diff --git a/selfdrive/ui/translations/app_de.po b/selfdrive/ui/translations/app_de.po new file mode 100644 index 00000000000000..287ecde1a01ed2 --- /dev/null +++ b/selfdrive/ui/translations/app_de.po @@ -0,0 +1,825 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: de\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Die Lenkmoment-Reaktionskalibrierung ist abgeschlossen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " Die Lenkmoment-Reaktionskalibrierung ist zu {}% abgeschlossen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Ihr Gerät ist um {:.1f}° {} und {:.1f}° {} ausgerichtet." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 Jahr Fahrtdatenspeicherung" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "24/7 LTE‑Verbindung" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

Kalibrierung der Lenkverzögerung abgeschlossen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Kalibrierung der Lenkverzögerung zu {}% abgeschlossen." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "HINZUFÜGEN" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN‑Einstellung" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Übermäßige Betätigung bestätigen" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Erweitert" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Aggressiv" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Zustimmen" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Immer aktive Fahrerüberwachung" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Sind Sie sicher, dass Sie ausschalten möchten?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Sind Sie sicher, dass Sie neu starten möchten?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Sind Sie sicher, dass Sie die Kalibrierung zurücksetzen möchten?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Sind Sie sicher, dass Sie deinstallieren möchten?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Zurück" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Werden Sie comma prime Mitglied auf connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Fügen Sie connect.comma.ai Ihrem Startbildschirm hinzu, um es wie eine App zu verwenden" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "ÄNDERN" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "PRÜFEN" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "CHILL‑MODUS AKTIV" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "VERBINDUNG" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "VERBINDUNG" + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Abbrechen" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Getaktete Mobilfunkverbindung" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Sprache ändern" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr " Durch Ändern dieser Einstellung wird openpilot neu gestartet, wenn das Auto eingeschaltet ist." + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Klicken Sie auf \"add new device\" und scannen Sie den QR‑Code rechts" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Schließen" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Aktuelle Version" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "HERUNTERLADEN" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Ablehnen" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "Ablehnen, openpilot deinstallieren" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Entwickler" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Gerät" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Beim Gaspedal deaktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Zum Ausschalten deaktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Zum Neustart deaktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Zum Zurücksetzen der Kalibrierung deaktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Geschwindigkeit in km/h statt mph anzeigen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "Dongle-ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Herunterladen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Fahrerkamera" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Fahrstil" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "BEARBEITEN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "FEHLER" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "EXPERIMENTALMODUS AKTIV" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "ADB aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Spurverlassenswarnungen aktivieren" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Roaming aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "SSH aktivieren" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Tethering aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "Fahrerüberwachung auch aktivieren, wenn openpilot nicht aktiv ist." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "openpilot aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "Den Schalter für die openpilot-Längsregelung (Alpha) aktivieren, um den Experimentalmodus zu erlauben." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "APN eingeben" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "SSID eingeben" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Neues Tethering‑Passwort eingeben" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Passwort eingeben" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Geben Sie Ihren GitHub‑Benutzernamen ein" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Fehler" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Experimentalmodus" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Der Experimentalmodus ist derzeit auf diesem Fahrzeug nicht verfügbar, da der serienmäßige ACC für die Längsregelung verwendet wird." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "WIRD VERGESSEN..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Einrichtung abschließen" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Datenstrom" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose‑Modus" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Vergessen" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "WLAN‑Netz „{}“ vergessen?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "GUT" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Gehen Sie auf Ihrem Telefon zu https://connect.comma.ai" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "HOCH" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Verstecktes Netzwerk" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALLIEREN" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP‑Adresse" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Update installieren" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Joystick‑Debugmodus" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "LADEN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Längsmanövermodus" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MAX." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximieren Sie Ihre Trainingsdaten‑Uploads, um die Fahrmodelle von openpilot zu verbessern." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "k. A." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "KEIN" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Netzwerk" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "Keine SSH‑Schlüssel für Benutzer '{}' gefunden" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Keine Versionshinweise verfügbar." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "GETRENNT" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "VERBUNDEN" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Öffnen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "KOPPELN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "VORSCHAU" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME‑FUNKTIONEN:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Gerät koppeln" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Gerät koppeln" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Koppeln Sie Ihr Gerät mit Ihrem comma‑Konto" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Koppeln Sie Ihr Gerät mit comma connect (connect.comma.ai) und lösen Sie Ihr comma‑prime‑Angebot ein." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Bitte mit WLAN verbinden, um das erste Koppeln abzuschließen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Ausschalten" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Verhindern Sie das Hochladen großer Datenmengen bei einer getakteten WLAN-Verbindung" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Verhindern Sie das Hochladen großer Datenmengen bei einer getakteten Mobilfunkverbindung" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Vorschau der Fahrer‑Kamera, um sicherzustellen, dass die Fahrerüberwachung gute Sicht hat. (Fahrzeug muss ausgeschaltet sein)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR‑Code‑Fehler" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "ENTFERNEN" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "ZURÜCKSETZEN" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "ANSEHEN" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Neustart" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Gerät neu starten" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Neustarten und aktualisieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Fahrerkamera aufzeichnen und hochladen" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Mikrofonton aufzeichnen und hochladen" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Mikrofonton während der Fahrt aufzeichnen und speichern. Die Audiospur wird im Dashcam‑Video in comma connect enthalten sein." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Vorschriften" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Entspannt" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Fernzugriff" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Remote‑Schnappschüsse" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Zeitüberschreitung bei der Anfrage" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Zurücksetzen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Kalibrierung zurücksetzen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Trainingsanleitung ansehen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "Überprüfen Sie die Regeln, Funktionen und Einschränkungen von openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "WÄHLEN" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH‑Schlüssel" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "WLAN‑Netzwerke werden gesucht..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Auswählen" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Zweig auswählen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Sprache auswählen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Seriennummer" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Update verschieben" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Softwarebereich" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Standardmodus" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "System reagiert nicht" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "SOFORT DIE KONTROLLE ÜBERNEHMEN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Zielzweig" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Tethering‑Passwort" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Schalter" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "UI-Debug-Modus" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "DEINSTALLIEREN" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "AKTUALISIEREN" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Deinstallieren" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Unbekannt" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Updates werden nur heruntergeladen, wenn das Auto aus ist." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Jetzt abonnieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Daten von der Fahrer‑Kamera hochladen und den Fahrerüberwachungs‑Algorithmus verbessern." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Metersystem verwenden" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "FAHRZEUG" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "ANSEHEN" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Warten auf Start" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "Willkommen bei openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "Wenn aktiviert, deaktiviert das Drücken des Gaspedals openpilot." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "WLAN" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Getaktetes WLAN‑Netzwerk" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Falsches Passwort" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "Sie müssen die Nutzungsbedingungen akzeptieren, um openpilot zu verwenden." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "Sie müssen die Nutzungsbedingungen akzeptieren, um openpilot zu verwenden. Lesen Sie die aktuellen Bedingungen unter https://comma.ai/terms, bevor Sie fortfahren." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "Kamera startet" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "Überprüfung..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "Standard" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "unten" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "Herunterladen..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "Überprüfung auf Updates fehlgeschlagen" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "Update wird finalisiert..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "für „{}“" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "für automatische Konfiguration leer lassen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "links" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "getaktet" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "nie" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "jetzt" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "openpilot Längsregelung (Alpha)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot nicht verfügbar" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "Die openpilot‑Längsregelung könnte in einem zukünftigen Update kommen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot erfordert, dass das Gerät innerhalb von 4° nach links oder rechts und innerhalb von 5° nach oben oder 9° nach unten montiert ist." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "rechts" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "unbegrenzt" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "oben" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "Aktuell, zuletzt geprüft: nie" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "Aktuell, zuletzt geprüft: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "Update verfügbar" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} WARNUNG" +msgstr[1] "{} WARNUNGEN" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "vor {} Tag" +msgstr[1] "vor {} Tagen" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "vor {} Stunde" +msgstr[1] "vor {} Stunden" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "vor {} Minute" +msgstr[1] "vor {} Minuten" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} Segment Ihrer Fahrten ist bisher im Trainingsdatensatz." +msgstr[1] "{} Segmente Ihrer Fahrten sind bisher im Trainingsdatensatz." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ABONNIERT" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose‑Modus 🔥" + diff --git a/selfdrive/ui/translations/app_en.po b/selfdrive/ui/translations/app_en.po new file mode 100644 index 00000000000000..9f99c42b1116a9 --- /dev/null +++ b/selfdrive/ui/translations/app_en.po @@ -0,0 +1,825 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: en\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Steering torque response calibration is complete." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " Steering torque response calibration is {}% complete." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Your device is pointed {:.1f}° {} and {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 year of drive storage" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "24/7 LTE connectivity" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

Steering lag calibration is complete." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Steering lag calibration is {}% complete." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "ADD" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN Setting" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Acknowledge Excessive Actuation" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Advanced" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Aggressive" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Agree" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Always-On Driver Monitoring" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Are you sure you want to power off?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Are you sure you want to reboot?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Are you sure you want to reset calibration?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Are you sure you want to uninstall?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Back" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Become a comma prime member at connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Bookmark connect.comma.ai to your home screen to use it like an app" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "CHANGE" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "CHECK" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "CHILL MODE ON" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "CONNECT" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "CONNECTING..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Cancel" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Cellular Metered" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Change Language" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "Changing this setting will restart openpilot if the car is powered on." + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Click \"add new device\" and scan the QR code on the right" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Close" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Current Version" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "DOWNLOAD" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Decline" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "Decline, uninstall openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Developer" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Device" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Disengage on Accelerator Pedal" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Disengage to Power Off" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Disengage to Reboot" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Disengage to Reset Calibration" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Display speed in km/h instead of mph." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "Dongle ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Download" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Driver Camera" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Driving Personality" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "EDIT" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ERROR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "EXPERIMENTAL MODE ON" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Enable" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Enable ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Enable Lane Departure Warnings" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Enable Roaming" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Enable SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Enable Tethering" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "Enable driver monitoring even when openpilot is not engaged." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "Enable openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Enter APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Enter SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Enter new tethering password" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Enter password" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Enter your GitHub username" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Error" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Experimental Mode" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "FORGETTING..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Finish Setup" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Firehose" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose Mode" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Forget" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Forget Wi-Fi Network \"{}\"?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "GOOD" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Go to https://connect.comma.ai on your phone" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "HIGH" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Hidden Network" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALL" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP Address" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Install Update" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Joystick Debug Mode" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "LOADING" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Longitudinal Maneuver Mode" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MAX" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximize your training data uploads to improve openpilot's driving models." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "N/A" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "NO" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Network" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "No SSH keys found for user '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "No release notes available." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "OFFLINE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ONLINE" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Open" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "PAIR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "PREVIEW" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME FEATURES:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Pair Device" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Pair device" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Pair your device to your comma account" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Please connect to Wi-Fi to complete initial pairing" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Power Off" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Prevent large data uploads when on a metered Wi-Fi connection" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Prevent large data uploads when on a metered cellular connection" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR Code Error" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "REMOVE" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "RESET" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "REVIEW" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Reboot" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Reboot Device" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Reboot and Update" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Record and Upload Driver Camera" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Record and Upload Microphone Audio" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Regulatory" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Relaxed" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Remote access" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Remote snapshots" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Request timed out" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Reset" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Reset Calibration" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Review Training Guide" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "Review the rules, features, and limitations of openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SELECT" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH Keys" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Scanning Wi-Fi networks..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Select" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Select a branch" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Select a language" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Serial" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Snooze Update" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Software" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Standard" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "System Unresponsive" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "TAKE CONTROL IMMEDIATELY" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Target Branch" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Tethering Password" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Toggles" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "UI Debug Mode" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "UNINSTALL" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "UPDATE" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Uninstall" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Unknown" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Updates are only downloaded while the car is off." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Upgrade Now" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Upload data from the driver facing camera and help improve the driver monitoring algorithm." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Use Metric System" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "VEHICLE" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "VIEW" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Waiting to start" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "Welcome to openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "When enabled, pressing the accelerator pedal will disengage openpilot." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi-Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi-Fi Network Metered" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Wrong password" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "You must accept the Terms and Conditions in order to use openpilot." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "camera starting" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "checking..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "default" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "down" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "downloading..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "failed to check for update" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "finalizing update..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "for \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "leave blank for automatic configuration" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "left" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "metered" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "never" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "now" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "openpilot Longitudinal Control (Alpha)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot Unavailable" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "openpilot longitudinal control may come in a future update." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "right" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "unmetered" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "up" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "up to date, last checked never" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "up to date, last checked {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "update available" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} ALERT" +msgstr[1] "{} ALERTS" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} day ago" +msgstr[1] "{} days ago" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} hour ago" +msgstr[1] "{} hours ago" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} minute ago" +msgstr[1] "{} minutes ago" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segment of your driving is in the training dataset so far." +msgstr[1] "{} segments of your driving is in the training dataset so far." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ SUBSCRIBED" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose Mode 🔥" + diff --git a/selfdrive/ui/translations/app_es.po b/selfdrive/ui/translations/app_es.po new file mode 100644 index 00000000000000..707816bc009c90 --- /dev/null +++ b/selfdrive/ui/translations/app_es.po @@ -0,0 +1,825 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: es\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " La calibración de respuesta de par de dirección está completa." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " La calibración de respuesta de par de dirección está {}% completa." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Tu dispositivo está orientado {:.1f}° {} y {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 año de almacenamiento de conducción" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "Conectividad LTE 24/7" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

La calibración del retraso de dirección está completa." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

La calibración del retraso de dirección está completa en un {}%." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "AÑADIR" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "Configuración de APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Reconocer actuación excesiva" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Avanzado" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Agresivo" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Aceptar" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Supervisión del conductor siempre activa" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "¿Seguro que quieres apagar?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "¿Seguro que quieres reiniciar?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "¿Seguro que quieres restablecer la calibración?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "¿Seguro que quieres desinstalar?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Atrás" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Hazte miembro de comma prime en connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Añade connect.comma.ai a tu pantalla de inicio para usarlo como una app" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "CAMBIAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "COMPROBAR" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "MODO CHILL ACTIVADO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "CONECTAR" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "CONECTAR" + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Cancelar" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Medición celular" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Cambiar idioma" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr " Cambiar esta configuración reiniciará openpilot si el coche está encendido." + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Haz clic en \"añadir nuevo dispositivo\" y escanea el código QR de la derecha" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Cerrar" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Versión actual" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "DESCARGAR" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Rechazar" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "Rechazar, desinstalar openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Desarrollador" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Dispositivo" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Desactivar con el pedal del acelerador" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Desactivar para apagar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Desactivar para reiniciar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Desactivar para restablecer la calibración" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Mostrar la velocidad en km/h en lugar de mph." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ID del dongle" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Descargar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Cámara del conductor" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Estilo de conducción" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "EDITAR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "FALLO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "MODO EXPERIMENTAL ACTIVADO" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Activar" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Activar ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Activar advertencias de salida de carril" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Activar roaming" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Activar SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Activar anclaje" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "Activar la supervisión del conductor incluso cuando openpilot no esté activado." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "Activar openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "Activa el interruptor de control longitudinal de openpilot (alpha) para permitir el modo Experimental." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Introduce APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Introduzca SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Ingrese una nueva contraseña de anclaje a red" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Introduce la contraseña" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Introduce tu nombre de usuario de GitHub" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Fallo" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Modo experimental" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "El modo experimental no está disponible actualmente en este coche, ya que se usa el ACC de fábrica para el control longitudinal." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "OLVIDAR..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Finalizar configuración" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Flujo masivo" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Modo Firehose" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Olvidar" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "¿Olvidaste la red Wi-Fi \"{}\"?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "BUENO" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Ve a https://connect.comma.ai en tu teléfono" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "ALTO" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Red oculta" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALAR" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "Dirección IP" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Instalar actualización" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Modo de depuración de joystick" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "CARGANDO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Modo de maniobra longitudinal" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MÁX" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximiza tus cargas de datos de entrenamiento para mejorar los modelos de conducción de openpilot." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "N / A" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "SIN" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Red" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "No se encontraron claves SSH para el usuario '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "No hay notas de versión disponibles." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "SIN CONEXIÓN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "EN LÍNEA" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Abrir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "EMPAREJAR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "VISTA PREVIA" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "FUNCIONES PRIME:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Emparejar dispositivo" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Emparejar dispositivo" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Empareja tu dispositivo con tu cuenta de comma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Empareja tu dispositivo con comma connect (connect.comma.ai) y reclama tu oferta de comma prime." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Conéctate a Wi‑Fi para completar el emparejamiento inicial" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Apagar" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Evite grandes cargas de datos cuando esté en una conexión Wi-Fi medida" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Evite grandes cargas de datos cuando esté en una conexión celular medida" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Previsualiza la cámara hacia el conductor para asegurarte de que la supervisión del conductor tenga buena visibilidad. (el vehículo debe estar apagado)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "Error de código QR" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "ELIMINAR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "RESTABLECER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "REVISAR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Reiniciar" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Reiniciar dispositivo" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Reiniciar y actualizar" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Grabar y subir cámara del conductor" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Grabar y subir audio del micrófono" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Grabar y almacenar audio del micrófono mientras conduces. El audio se incluirá en el video de la dashcam en comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Reglamentario" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Relajado" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Acceso remoto" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Capturas remotas" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Se agotó el tiempo de espera de la solicitud" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Restablecer" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Restablecer calibración" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Revisar guía de entrenamiento" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "Revisa las reglas, funciones y limitaciones de openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SELECCIONAR" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "Claves SSH" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Escaneando redes Wi-Fi..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Seleccionar" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Selecciona una rama" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Selecciona un idioma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Número de serie" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Posponer actualización" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Sistema" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Estándar" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Sistema sin respuesta" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "TOME EL CONTROL INMEDIATAMENTE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Rama objetivo" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Contraseña de anclaje" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Interruptores" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Modo de depuración de la interfaz de usuario" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "DESINSTALAR" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "ACTUALIZAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Desinstalar" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Desconocido" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Las actualizaciones solo se descargan cuando el coche está apagado." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Mejorar ahora" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Sube datos de la cámara orientada al conductor y ayuda a mejorar el algoritmo de supervisión del conductor." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Usar sistema métrico" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "VEHÍCULO" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "VER" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Esperando para iniciar" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "Bienvenido a openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "Cuando está activado, al presionar el pedal del acelerador se desactivará openpilot." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Red Wi-Fi medida" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Contraseña incorrecta" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "Debes aceptar los Términos y Condiciones para poder usar openpilot." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "Debes aceptar los Términos y Condiciones para usar openpilot. Lee los términos más recientes en https://comma.ai/terms antes de continuar." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "iniciando cámara" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "de cheques..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "por defecto" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "abajo" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "descargando..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "Error al buscar actualizaciones" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "finalizando actualización..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "para \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "dejar en blanco para configuración automática" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "izquierda" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "medido" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "nunca" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "ahora" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "Control longitudinal de openpilot (Alpha)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot no disponible" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "El control longitudinal de openpilot podría llegar en una actualización futura." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot requiere que el dispositivo esté montado dentro de 4° a izquierda o derecha y dentro de 5° hacia arriba o 9° hacia abajo." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "derecha" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "sin medir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "arriba" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "actualizado, última comprobación: nunca" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "actualizado, última comprobación: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "actualización disponible" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} ALERTA" +msgstr[1] "{} ALERTAS" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "hace {} día" +msgstr[1] "hace {} días" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "hace {} hora" +msgstr[1] "hace {} horas" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "hace {} minuto" +msgstr[1] "hace {} minutos" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segmento de tu conducción está en el conjunto de entrenamiento hasta ahora." +msgstr[1] "{} segmentos de tu conducción están en el conjunto de entrenamiento hasta ahora." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ SUSCRITO" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Modo Firehose 🔥" + diff --git a/selfdrive/ui/translations/app_fr.po b/selfdrive/ui/translations/app_fr.po new file mode 100644 index 00000000000000..7c0aecc9ec3846 --- /dev/null +++ b/selfdrive/ui/translations/app_fr.po @@ -0,0 +1,825 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: fr\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " L'étalonnage de la réponse du couple de direction est terminé." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " L'étalonnage de la réponse du couple de direction est terminé à {}%." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Votre appareil est orienté {:.1f}° {} et {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 an de stockage de trajets" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "Connexion LTE 24/7" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

L'étalonnage du délai de réponse de la direction est terminé." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

L'étalonnage du délai de réponse de la direction est terminé à {}%." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "AJOUTER" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "Paramètres APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Accuser réception d'actionnement excessif" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Avancé" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Agressif" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Accepter" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Surveillance continue du conducteur" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Êtes-vous sûr de vouloir éteindre ?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Êtes-vous sûr de vouloir redémarrer ?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Êtes-vous sûr de vouloir réinitialiser la calibration ?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Êtes-vous sûr de vouloir désinstaller ?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Retour" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Devenez membre comma prime sur connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Ajoutez connect.comma.ai à votre écran d'accueil pour l'utiliser comme une application" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "CHANGER" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "VÉRIFIER" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "MODE CHILL ACTIVÉ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "CONNECTER" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "CONNECTER..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Annuler" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Données cellulaire limitées" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Changer la langue" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "La modification de ce réglage redémarrera openpilot si la voiture est sous tension." + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Cliquez sur \"add new device\" et scannez le code QR à droite" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Fermer" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Version actuelle" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "TÉLÉCHARGER" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Refuser" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "Refuser, désinstaller openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Développeur" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Appareil" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Désengager à l'appui sur l'accélérateur" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Désengager pour éteindre" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Désengager pour redémarrer" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Désengager pour réinitialiser la calibration" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Afficher la vitesse en km/h au lieu de mph." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ID du dongle" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Télécharger" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Caméra conducteur" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Personnalité de conduite" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "EDITER" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ERREUR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "MODE EXPÉRIMENTAL ACTIVÉ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Activer" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Activer ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Activer les alertes de sortie de voie" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Activer openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Activer SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Activer les alertes de sortie de voie" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "Activer la surveillance du conducteur même lorsque openpilot n'est pas engagé." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "Activer openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "Activez l'option de contrôle longitudinal openpilot (alpha) pour autoriser le mode expérimental." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Saisir l'APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Entrer le SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Saisir le mot de passe du partage de connexion" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Saisir le mot de passe" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Entrez votre nom d'utilisateur GitHub" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Erreur" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Mode expérimental" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Le mode expérimental est actuellement indisponible sur cette voiture car l'ACC d'origine est utilisé pour le contrôle longitudinal." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "OUBLIER..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Terminer la configuration" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Flux continu" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Mode Firehose" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Oublier" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Oublier le réseau Wi-Fi \"{}\" ?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "BON" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Allez sur https://connect.comma.ai sur votre téléphone" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "ÉLEVÉ" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Réseau" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALLER" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "Adresse IP" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Installer la mise à jour" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Mode débogage joystick" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "CHARGEMENT" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Mode de manœuvre longitudinale" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MAX." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximisez vos envois de données d'entraînement pour améliorer les modèles de conduite d'openpilot." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "NC" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "NON" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Réseau" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "Aucune clé SSH trouvée pour l'utilisateur '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Aucune note de version disponible." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "HORS LIGNE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "EN LIGNE" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Ouvrir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "ASSOCIER" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "APERÇU" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "FONCTIONNALITÉS PRIME :" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Associer l'appareil" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Associer l'appareil" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Associez votre appareil à votre compte comma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Associez votre appareil à comma connect (connect.comma.ai) et réclamez votre offre comma prime." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Veuillez vous connecter au Wi‑Fi pour terminer l'association initiale" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Éteindre" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Eviter les transferts de données volumineux lorsque vous êtes connecté à un réseau Wi-Fi limité" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Eviter les transferts de données volumineux lors d'une connexion à un réseau cellulaire limité" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Prévisualisez la caméra orientée conducteur pour vous assurer que la surveillance du conducteur a une bonne visibilité. (le véhicule doit être éteint)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "Erreur de code QR" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "SUPPRIMER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "RÉINITIALISER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "CONSULTER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Redémarrer" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Redémarrer l'appareil" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Redémarrer et mettre à jour" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Enregistrer et téléverser la caméra conducteur" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Enregistrer et téléverser l'audio du microphone" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Enregistrer et stocker l'audio du microphone pendant la conduite. L'audio sera inclus dans la vidéo dashcam dans comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Réglementaire" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Détendu" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Accès à distance" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Captures à distance" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Délai de la requête dépassé" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Réinitialiser" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Réinitialiser la calibration" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Consulter le guide d'entraînement" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "Consultez les règles, fonctionnalités et limitations d'openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SELECTIONNER" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "Clefs SSH" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Analyse des réseaux Wi-Fi..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Sélectionner" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Sélectionner une branche" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Sélectionner un langage" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Numéro de série" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Reporter la mise à jour" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Logiciel" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Normal" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Système non réactif" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "REPRENEZ IMMÉDIATEMENT LE CONTRÔLE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMPÉRATURE" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Branche cible" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Mot de passe du partage de connexion" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Options" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Mode de débogage de l'interface utilisateur" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "DÉSINSTALLER" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "METTRE À JOUR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Désinstaller" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Inconnu" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Les mises à jour ne sont téléchargées que lorsque la voiture est éteinte." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Mettre à niveau maintenant" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Téléverser les données de la caméra orientée conducteur et aider à améliorer l'algorithme de surveillance du conducteur." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Utiliser le système métrique" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "VÉHICULE" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "VOIR" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "En attente de démarrage" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "Bienvenue sur openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "Lorsque activé, appuyer sur la pédale d'accélérateur désengagera openpilot." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Réseau Wi-Fi limité" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Mauvais mot de passe" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "Vous devez accepter les conditions générales pour utiliser openpilot." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "Vous devez accepter les conditions générales pour utiliser openpilot. Lisez les dernières conditions sur https://comma.ai/terms avant de continuer." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "démarrage de la caméra" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "vérification..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "défaut" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "bas" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "téléchargement..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "échec de la vérification de mise à jour" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "finalisation de la mise à jour..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "pour \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "ne pas remplir pour une configuration automatique" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "gauche" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "limité" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "jamais" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "maintenant" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "Contrôle longitudinal openpilot (Alpha)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot indisponible" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "Le contrôle longitudinal openpilot pourra arriver dans une future mise à jour." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot exige que l'appareil soit monté à moins de 4° à gauche ou à droite et à moins de 5° vers le haut ou 9° vers le bas." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "droite" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "non limité" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "haut" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "à jour, dernière vérification jamais" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "à jour, dernière vérification {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "mise à jour disponible" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} ALERTE" +msgstr[1] "{} ALERTES" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "il y a {} jour" +msgstr[1] "il y a {} jours" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "il y a {} heure" +msgstr[1] "il y a {} heures" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "il y a {} minute" +msgstr[1] "il y a {} minutes" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segment de votre conduite est dans l'ensemble d'entraînement jusqu'à présent." +msgstr[1] "{} segments de votre conduite sont dans l'ensemble d'entraînement jusqu'à présent." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ABONNÉ" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Mode Firehose 🔥" + diff --git a/selfdrive/ui/translations/app_ja.po b/selfdrive/ui/translations/app_ja.po new file mode 100644 index 00000000000000..78d3cf17c678eb --- /dev/null +++ b/selfdrive/ui/translations/app_ja.po @@ -0,0 +1,820 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: ja\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " ステアリングトルク応答のキャリブレーションが完了しました。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " ステアリングトルク応答のキャリブレーションは{}%完了しました。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " デバイスは{:.1f}°{}、{:.1f}°{}の向きです。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "走行データを1年間保存" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "24時間365日のLTE接続" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

ステアリング遅延のキャリブレーションが完了しました。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

ステアリング遅延のキャリブレーションは{}%完了しました。" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "追加" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN設定" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "過度な作動を承認" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "詳細設定" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "アグレッシブ" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "同意する" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "常時ドライバーモニタリング" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "本当に電源をオフにしますか?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "本当に再起動しますか?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "本当にキャリブレーションをリセットしますか?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "本当にアンインストールしますか?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "戻る" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "connect.comma.aiで comma prime に加入" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "connect.comma.aiをホーム画面に追加してアプリのように使いましょう" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "変更" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "確認" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "チルモードON" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "接続" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "接続中..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "キャンセル" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "従量課金の携帯回線" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "言語を変更" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "車が起動中の場合、この設定を変更するとopenpilotが再起動します。" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "\"add new device\"を押して右側のQRコードをスキャン" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "閉じる" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "現在のバージョン" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "ダウンロード" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "拒否する" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "拒否してopenpilotをアンインストール" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "開発者" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "デバイス" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "アクセルで解除" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "解除して電源オフ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "解除して再起動" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "解除してキャリブレーションをリセット" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "速度をmphではなくkm/hで表示します。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ドングルID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "ダウンロード" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "ドライバーカメラ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "走行性格" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "編集" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "エラー" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "実験モードON" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "有効化" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "ADBを有効化" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "車線逸脱警報を有効化" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "ローミングを有効化" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "SSHを有効化" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "テザリングを有効化" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "openpilotが未作動でもドライバーモニタリングを有効にします。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "openpilotを有効化" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "openpilot縦制御(アルファ)のトグルを有効にすると実験モードが使用できます。" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "APNを入力" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "SSIDを入力" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "新しいテザリングのパスワードを入力" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "パスワードを入力" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "GitHubユーザー名を入力" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "エラー" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "実験モード" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "この車では縦制御に純正ACCを使用するため、現在実験モードは利用できません。" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "削除中..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "セットアップを完了" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "大量配信" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehoseモード" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "削除" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Wi‑Fiネットワーク「{}」を削除しますか?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "良好" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "スマートフォンで https://connect.comma.ai にアクセス" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "高温" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "非公開ネットワーク" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "インストール" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IPアドレス" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "アップデートをインストール" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "ジョイスティックデバッグモード" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "読み込み中" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "縦制御マヌーバーモード" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "最大" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "学習データのアップロードを最大化してopenpilotの運転モデルを改善しましょう。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "該当なし" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "いいえ" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "ネットワーク" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "ユーザー'{}'のSSH鍵が見つかりません" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "リリースノートはありません。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "オフライン" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "オンライン" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "開く" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "ペアリング" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "プレビュー" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "prime の特典:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "デバイスをペアリング" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "デバイスをペアリング" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "デバイスをあなたの comma アカウントにペアリング" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "デバイスを comma connect(connect.comma.ai)とペアリングして、comma prime 特典を受け取りましょう。" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "初回ペアリングを完了するにはWi‑Fiに接続してください" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "電源オフ" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "従量課金のWi‑Fi接続時は大きなデータのアップロードを抑制" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "従量課金の携帯回線接続時は大きなデータのアップロードを抑制" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "ドライバー向きカメラのプレビューでモニタリングの視界を確認します。(車両は停止状態である必要があります)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QRコードエラー" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "削除" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "リセット" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "確認" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "再起動" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "デバイスを再起動" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "再起動して更新" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "ドライバーカメラを記録してアップロード" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "マイク音声を記録してアップロード" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "走行中にマイク音声を記録・保存します。音声は comma connect のドライブレコーダー動画に含まれます。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "規制情報" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "リラックス" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "リモートアクセス" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "リモートスナップショット" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "リクエストがタイムアウトしました" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "リセット" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "キャリブレーションをリセット" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "トレーニングガイドを確認" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "openpilotのルール、機能、制限を確認" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "選択" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH鍵" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Wi‑Fiネットワークを検索中..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "選択" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "ブランチを選択" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "言語を選択" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "シリアル" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "更新を後で通知" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "ソフトウェア" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "スタンダード" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "システムが応答しません" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "すぐに手動介入してください" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "温度" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "対象ブランチ" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "テザリングのパスワード" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "トグル" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "UIデバッグモード" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "アンインストール" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "更新" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "アンインストール" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "不明" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "アップデートは車両の電源が切れている間のみダウンロードされます。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "今すぐアップグレード" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "ドライバー向きカメラのデータをアップロードしてモニタリングアルゴリズムの改善に協力してください。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "メートル法を使用" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "車両" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "表示" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "開始待機中" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "openpilotへようこそ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "有効にすると、アクセルを踏むとopenpilotが解除されます。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi‑Fiネットワーク(従量課金)" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "パスワードが違います" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "openpilotを使用するには、利用規約に同意する必要があります。" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "openpilotを使用するには利用規約に同意する必要があります。続行する前に https://comma.ai/terms の最新の規約をお読みください。" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "カメラを起動中" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "チェック中..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "既定" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "下" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "ダウンロード中..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "アップデートの確認に失敗しました" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "アップデートを終了しています..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "「{}」向け" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "自動設定の場合は空欄のままにしてください" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "左" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "従量" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "なし" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "今" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "openpilot 縦制御(アルファ)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilotは利用できません" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "openpilotの縦制御は将来のアップデートで提供される可能性があります。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilotでは、デバイスの取り付け角度が左右±4°、上方向5°以内、下方向9°以内である必要があります。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "右" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "非従量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "上" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "最新です。最終確認: なし" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "最新です。最終確認: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "更新があります" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{}件のアラート" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{}日前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{}時間前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{}分前" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "これまでにあなたの走行の{}セグメントが学習データセットに含まれています。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ 登録済み" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehoseモード 🔥" + diff --git a/selfdrive/ui/translations/app_ko.po b/selfdrive/ui/translations/app_ko.po new file mode 100644 index 00000000000000..24306ae02a7684 --- /dev/null +++ b/selfdrive/ui/translations/app_ko.po @@ -0,0 +1,820 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: ko\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " 스티어링 토크 응답 보정이 완료되었습니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " 스티어링 토크 응답 보정이 {}% 완료되었습니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " 장치는 {:.1f}° {} 및 {:.1f}° {} 방향을 가리키고 있습니다." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "주행 데이터 1년 보관" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "연중무휴 LTE 연결" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

스티어링 지연 보정이 완료되었습니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

스티어링 지연 보정이 {}% 완료되었습니다." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "추가" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN 설정" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "과도한 작동을 확인" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "고급" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "공격적" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "동의" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "운전자 모니터링 항상 켜짐" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "정말 전원을 끄시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "정말 재시작하시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "정말 보정을 재설정하시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "정말 제거하시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "뒤로" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "connect.comma.ai에서 comma prime 회원이 되세요" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "connect.comma.ai를 홈 화면에 추가하여 앱처럼 사용하세요" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "변경" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "확인" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "안정적 모드 켜짐" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "연결" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "연결 중..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "취소" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "종량제 셀룰러" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "언어 변경" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "차량 전원이 켜져 있으면 이 설정을 변경할 때 openpilot이 재시작됩니다." + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "\"add new device\"를 눌러 오른쪽의 QR 코드를 스캔하세요" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "닫기" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "현재 버전" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "다운로드" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "거부" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "거부하고 openpilot 제거" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "개발자" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "장치" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "가속 페달로 해제" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "해제 후 전원 끄기" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "해제 후 재시작" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "해제 후 캘리브레이션 재설정" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "속도를 mph 대신 km/h로 표시합니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "동글 ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "다운로드" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "운전자 카메라" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "주행 성향" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "편집" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "오류" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "실험 모드 켜짐" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "사용" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "ADB 사용" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "차선 이탈 경고 사용" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "로밍 사용" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "SSH 사용" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "테더링 사용" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "openpilot이 작동 중이 아닐 때도 운전자 모니터링을 사용합니다." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "openpilot 사용" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "실험 모드를 사용하려면 openpilot 롱컨 제어(알파) 토글을 켜세요." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "APN 입력" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "SSID 입력" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "새 테더링 비밀번호 입력" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "비밀번호 입력" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "GitHub 사용자 이름 입력" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "오류" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "실험 모드" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "이 차량은 롱컨 제어에 순정 ACC를 사용하므로 현재 실험 모드를 사용할 수 없습니다." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "삭제 중..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "설정 완료" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "파이어호스" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "파이어호스 모드" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "삭제" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Wi‑Fi 네트워크 \"{}\"를 삭제하시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "양호" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "휴대폰에서 https://connect.comma.ai 에 접속하세요" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "높음" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "숨겨진 네트워크" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "설치" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP 주소" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "업데이트 설치" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "조이스틱 디버그 모드" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "로딩 중" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "롱컨 기동 모드" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "최대" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "학습 데이터 업로드를 최대화하여 openpilot의 주행 모델을 개선하세요." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "해당 없음" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "아니오" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "네트워크" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "사용자 '{}'의 SSH 키를 찾을 수 없습니다" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "릴리스 노트가 없습니다." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "오프라인" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "확인" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "온라인" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "열기" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "페어링" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "미리보기" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "프라임 기능:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "장치 페어링" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "장치 페어링" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "장치를 귀하의 comma 계정에 페어링하세요" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "장치를 comma connect(connect.comma.ai)와 페어링하고 comma 프라임 혜택을 받으세요." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "초기 페어링을 완료하려면 Wi‑Fi에 연결하세요" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "전원 끄기" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "종량제 Wi‑Fi 연결 시 대용량 업로드 방지" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "종량제 셀룰러 연결 시 대용량 업로드 방지" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "운전자 모니터링의 가시성을 확인하기 위해 운전자 카메라를 미리 봅니다. (차량은 꺼져 있어야 합니다)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR 코드 오류" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "제거" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "재설정" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "검토" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "재시작" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "장치 재시작" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "재시작 및 업데이트" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "운전자 카메라 기록 및 업로드" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "마이크 오디오 기록 및 업로드" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "주행 중 마이크 오디오를 기록하고 저장합니다. 오디오는 comma connect의 대시캠 영상에 포함됩니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "규제 정보" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "편안한" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "원격 액세스" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "원격 스냅샷" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "요청 시간이 초과되었습니다" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "재설정" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "캘리브레이션 재설정" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "학습 가이드 검토" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "openpilot의 규칙, 기능 및 제한을 검토" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "선택" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH 키" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Wi‑Fi 네트워크 검색 중..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "선택" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "브랜치 선택" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "언어 선택" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "시리얼" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "업데이트 나중에 알림" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "소프트웨어" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "표준" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "시스템 응답 없음" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "즉시 수동 조작하세요" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "온도" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "대상 브랜치" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "테더링 비밀번호" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "토글" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "UI 디버그 모드" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "제거" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "업데이트" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "제거" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "알수없음" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "업데이트는 차량 전원이 꺼져 있을 때만 다운로드됩니다." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "지금 업그레이드" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "운전자 방향 카메라 데이터를 업로드하여 운전자 모니터링 알고리즘 개선에 도움을 주세요." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "미터법 사용" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "차량" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "보기" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "시작 대기 중" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "openpilot에 오신 것을 환영합니다" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "이 옵션을 켜면 가속 페달을 밟을 때 openpilot이 해제됩니다." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi‑Fi 네트워크 종량제" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "비밀번호가 올바르지 않습니다" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "openpilot을 사용하려면 약관에 동의해야 합니다." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "openpilot을 사용하려면 약관에 동의해야 합니다. 계속하기 전에 https://comma.ai/terms 에서 최신 약관을 읽어주세요." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "카메라 시작 중" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "확인 중..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma 프라임" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "기본값" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "아래" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "다운로드 중..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "업데이트 확인 실패" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "업데이트 마무리 중..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "\"{}\"용" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "자동 구성을 사용하려면 비워 두세요" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "왼쪽" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "종량제" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "없음" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "지금" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "openpilot 롱컨 제어(알파)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot 사용 불가" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "openpilot 롱컨 제어는 향후 업데이트에서 제공될 수 있습니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot은 장치를 좌우 4°, 위쪽 5°, 아래쪽 9° 이내로 장착해야 합니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "오른쪽" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "비종량제" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "위" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "최신입니다. 마지막 확인: 없음" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "최신입니다. 마지막 확인: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "업데이트 가능" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{}건의 알림" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{}일 전" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{}시간 전" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{}분 전" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "현재까지 귀하의 주행 {}구간이 학습 데이터셋에 포함되었습니다." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ 구독됨" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 파이어호스 모드 🔥" + diff --git a/selfdrive/ui/translations/app_pt-BR.po b/selfdrive/ui/translations/app_pt-BR.po new file mode 100644 index 00000000000000..58f20944794242 --- /dev/null +++ b/selfdrive/ui/translations/app_pt-BR.po @@ -0,0 +1,825 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: pt-BR\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " A calibração da resposta de torque da direção foi concluída." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " A calibração da resposta de torque da direção está {}% concluída." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Seu dispositivo está apontado {:.1f}° {} e {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 ano de armazenamento de condução" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "Conectividade LTE 24/7" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

A calibração da latência da direção está concluída." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

A calibração da latência da direção está {}% concluída." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "ADICIONAR" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "Configuração de APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Reconhecer Atuação Excessiva" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Avançado" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Agressivo" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Concordo" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Monitoramento de Motorista Sempre Ativo" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Tem certeza de que deseja desligar?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Tem certeza de que deseja reiniciar?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Tem certeza de que deseja redefinir a calibração?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Tem certeza de que deseja desinstalar?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Voltar" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Torne-se membro comma prime em connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Adicione connect.comma.ai à tela inicial para usá-lo como um app" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "ALTERAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "VERIFICAR" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "MODO CHILL ATIVO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "CONECTAR" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "CONECTANDO..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Cancelar" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Dados móveis limitados" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Alterar Idioma" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "Alterar esta configuração reiniciará o openpilot se o carro estiver ligado." + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Toque em \"adicionar novo dispositivo\" e escaneie o QR code à direita" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Fechar" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Versão Atual" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "BAIXAR" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Recusar" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "Recusar, desinstalar o openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Desenvolv" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Dispositivo" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Desativar ao pressionar o acelerador" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Desativar para Desligar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Desativar para Reiniciar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Desativar para Redefinir Calibração" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Exibir velocidade em km/h em vez de mph." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ID do Dongle" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Baixar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Câmera do Motorista" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Personalidade" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "EDITAR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ERRO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "MODO EXPERIMENTAL ATIVO" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Ativar" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Ativar ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Ativar alertas de saída de faixa" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Ativar roaming" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Ativar SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Ativar compartilhamento" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "Ativar monitoramento do motorista mesmo quando o openpilot não está engajado." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "Ativar openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "Ative a opção de controle longitudinal do openpilot (alpha) para permitir o Modo Experimental." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Digite APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Digite SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Digite nova senha tethering" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Digite a senha" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Digite seu nome de usuário do GitHub" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Erro" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Modo Experimental" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "O Modo Experimental está indisponível neste carro pois o ACC original do carro é usado para controle longitudinal." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "ESQUECENDO..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Configure" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Fluxo contínuo" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Modo Firehose" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Esquecer" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Esquecer rede Wi-Fi \"{}\"?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "BOM" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Acesse https://connect.comma.ai no seu telefone" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "ALTO" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Rede oculta" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALAR" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "Endereço IP" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Instalar Atualização" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Modo de Depuração do Joystick" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "CARREGANDO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Modo de Manobra Longitudinal" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MÁX" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximize seus envios de dados de treinamento para melhorar os modelos de condução do openpilot." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "Indisp." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "NÃO" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Rede" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "Nenhuma chave SSH encontrada para o usuário '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Sem notas de versão disponíveis." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "OFF-LINE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ON-LINE" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Abrir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "EMPARELHAR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "PRÉVIA" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "RECURSOS PRIME:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Emparelhar Dispositivo" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Emparelhar dispositivo" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Emparelhe seu dispositivo à sua conta comma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Emparelhe seu dispositivo com o comma connect (connect.comma.ai) e resgate sua oferta comma prime." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Conecte-se ao Wi‑Fi para concluir o emparelhamento inicial" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Desligar" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Evitar uploads grandes de dados em conexões Wi-Fi limitadas" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Evitar uploads grandes de dados em conexões móveis limitadas" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Pré-visualize a câmera voltada para o motorista para garantir que o monitoramento do motorista tenha boa visibilidade. (veículo deve estar desligado)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "Erro no QR Code" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "REMOVER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "REDEFINIR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "REVISAR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Reiniciar" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Reiniciar Dispositivo" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Reiniciar e Atualizar" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Gravar e Enviar Câmera do Motorista" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Gravar e Enviar Áudio do Microfone" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Grave e armazene o áudio do microfone enquanto dirige. O áudio será incluído no vídeo da dashcam no comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Regulatório" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Relaxado" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Acesso remoto" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Capturas remotas" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Tempo da solicitação esgotado" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Redefinir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Redefinir Calibração" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Revisar Guia de Treinamento" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "Revise as regras, recursos e limitações do openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SELECIONAR" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "Chaves SSH" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Procurando redes Wi-Fi..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Selecione" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Selecione uma ramificação" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Selecione um idioma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Número de série" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Adiar Atualização" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Sistema" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Padrão" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Sistema sem resposta" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "ASSUMA O CONTROLE IMEDIATAMENTE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Branch Alvo" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Senha Tethering" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Alternativas" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Modo de depuração da interface do usuário" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "DESINSTALAR" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "ATUALIZAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Desinstalar" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Desconhecido" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Atualizações são baixadas apenas com o carro desligado." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Atualizar Agora" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Envie dados da câmera voltada para o motorista e ajude a melhorar o algoritmo de monitoramento do motorista." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Usar Sistema Métrico" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "VEÍCULO" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "VER" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Aguardando para iniciar" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "Bem-vindo ao openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "Quando ativado, pressionar o pedal do acelerador desengajará o openpilot." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Rede Wi-Fi limitada" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Senha errada" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "Você deve aceitar os Termos e Condições para usar o openpilot." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "Você deve aceitar os Termos e Condições para usar o openpilot. Leia os termos mais recentes em https://comma.ai/terms antes de continuar." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "câmera iniciando" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "verificando..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "padrão" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "para baixo" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "baixando..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "falha ao verificar atualização" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "finalizando atualização..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "para \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "deixe em branco para configuração automática" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "à esquerda" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "limitados" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "nunca" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "agora" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "Controle Longitudinal do openpilot (Alpha)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot Indisponível" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "o controle longitudinal do openpilot pode vir em uma atualização futura." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "o openpilot requer que o dispositivo seja montado dentro de 4° para a esquerda ou direita e dentro de 5° para cima ou 9° para baixo." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "à direita" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "ilimitados" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "para cima" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "atualizado, última verificação: nunca" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "atualizado, última verificação: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "atualização disponível" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} ALERTA" +msgstr[1] "{} ALERTAS" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} dia atrás" +msgstr[1] "{} dias atrás" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} hora atrás" +msgstr[1] "{} horas atrás" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} minuto atrás" +msgstr[1] "{} minutos atrás" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segmento da sua condução está no conjunto de treinamento até agora." +msgstr[1] "{} segmentos da sua condução estão no conjunto de treinamento até agora." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ASSINADO" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Modo Firehose 🔥" + diff --git a/selfdrive/ui/translations/app_th.po b/selfdrive/ui/translations/app_th.po new file mode 100644 index 00000000000000..4e45cae14b3960 --- /dev/null +++ b/selfdrive/ui/translations/app_th.po @@ -0,0 +1,820 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: th\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr "การสอบเทียบการตอบสนองแรงบิดของพวงมาลัยเสร็จสมบูรณ์" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr "การสอบเทียบการตอบสนองแรงบิดของพวงมาลัยเสร็จสมบูรณ์ {}%" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr "อุปกรณ์ของคุณชี้ไปที่ {:.1f}° {} และ {:.1f}° {}" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "พื้นที่เก็บข้อมูลไดรฟ์ 1 ปี" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "การเชื่อมต่อ LTE ตลอด 24 ชั่วโมงทุกวัน" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2จี" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3จี" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5จี" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

การปรับเทียบความล่าช้าของพวงมาลัยเสร็จสมบูรณ์" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

การปรับเทียบความล่าช้าของพวงมาลัย {}% เสร็จสมบูรณ์" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "เพิ่ม" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "การตั้งค่า APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "รับทราบการดำเนินการที่มากเกินไป" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "ขั้นสูง" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "ก้าวร้าว" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "เห็นด้วย" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "การตรวจสอบไดรเวอร์ตลอดเวลา" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "คุณแน่ใจหรือไม่ว่าต้องการปิดเครื่อง?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "คุณแน่ใจหรือไม่ว่าต้องการรีบูต?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "คุณแน่ใจหรือไม่ว่าต้องการรีเซ็ตการปรับเทียบ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "คุณแน่ใจหรือไม่ว่าต้องการถอนการติดตั้ง?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "กลับ" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "เป็นสมาชิกจุลภาคไพรม์ที่ Connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "คั่นหน้า Connect.comma.ai ไปที่หน้าจอหลักของคุณเพื่อใช้เหมือนแอป" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "เปลี่ยน" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "ตรวจสอบ" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "เปิดโหมด Chill" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "เชื่อมต่อ" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "กำลังเชื่อมต่อ..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "ยกเลิก" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "เซลล์วัดแสง" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "เปลี่ยนภาษา" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "การเปลี่ยนการตั้งค่านี้จะรีสตาร์ท Openpilot หากรถเปิดอยู่" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "คลิก \"เพิ่มอุปกรณ์ใหม่\" และสแกนโค้ด QR ทางด้านขวา" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "ปิด" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "เวอร์ชันปัจจุบัน" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "ดาวน์โหลด" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "ปฏิเสธ" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "ปฏิเสธ ถอนการติดตั้ง openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "นักพัฒนา" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "อุปกรณ์" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "ปลดเมื่อเหยียบคันเร่ง" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "ปลดเพื่อปิดเครื่อง" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "ยกเลิกการเชื่อมต่อเพื่อรีบูต" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "ปลดเพื่อรีเซ็ตการปรับเทียบ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "แสดงความเร็วเป็น km/h แทน mph" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "รหัสดองเกิล" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "ดาวน์โหลด" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "กล้องไดร์เวอร์" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "บุคลิกภาพในการขับขี่" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "แก้ไข" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ข้อผิดพลาด" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ผลประโยชน์ทับซ้อน" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "โหมดทดลองเปิดอยู่" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "เปิดใช้งาน" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "เปิดใช้งาน ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "เปิดใช้งานคำเตือนการออกนอกเลน" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "เปิดใช้งานโรมมิ่ง" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "เปิดใช้งาน SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "เปิดใช้งานการปล่อยสัญญาณ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "เปิดใช้งานการตรวจสอบไดรเวอร์แม้ว่าจะไม่ได้ใช้งาน openpilot ก็ตาม" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "เปิดใช้งานโอเพ่นไพลอต" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "เปิดใช้งานการสลับการควบคุมตามยาวของ openpilot (อัลฟา) เพื่ออนุญาตโหมดการทดลอง" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "ป้อน APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "ป้อน SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "ป้อนรหัสผ่านการปล่อยสัญญาณใหม่" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "ใส่รหัสผ่าน" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "ป้อนชื่อผู้ใช้ GitHub ของคุณ" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "ข้อผิดพลาด" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "โหมดทดลอง" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "ขณะนี้โหมดทดลองไม่สามารถใช้งานได้บนรถคันนี้ เนื่องจาก ACC ในสต็อกของรถใช้สำหรับการควบคุมตามยาว" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "กำลังลืม..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "เสร็จสิ้นการตั้งค่า" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "สายดับเพลิง" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "โหมดสายดับเพลิง" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "ลืม" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "ลืมเครือข่าย Wi-Fi \"{}\" หรือไม่" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "ดี" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "ไปที่ https://connect.comma.ai บนโทรศัพท์ของคุณ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "สูง" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "เครือข่ายที่ซ่อนอยู่" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "ติดตั้ง" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "ที่อยู่ IP" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "ติดตั้งอัปเดต" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "โหมดดีบักจอยสติ๊ก" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "กำลังโหลด" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "แอลทีที" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "โหมดการซ้อมรบตามยาว" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "สูงสุด" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "เพิ่มการอัปโหลดข้อมูลการฝึกของคุณให้สูงสุดเพื่อปรับปรุงโมเดลการขับขี่ของ Openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "ไม่มี" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "เลขที่" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "เครือข่าย" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "ไม่พบคีย์ SSH สำหรับผู้ใช้ '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "ไม่มีบันทึกประจำรุ่น" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "ออฟไลน์" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "ตกลง" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ออนไลน์" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "เปิด" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "คู่" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "แพนด้า" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "ดูตัวอย่าง" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "คุณสมบัติเด่น:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "จับคู่อุปกรณ์" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "จับคู่อุปกรณ์" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "จับคู่อุปกรณ์ของคุณกับบัญชีลูกน้ำของคุณ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "จับคู่อุปกรณ์ของคุณกับการเชื่อมต่อด้วยเครื่องหมายจุลภาค (connect.comma.ai) และรับข้อเสนอจุลภาคเฉพาะของคุณ" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "โปรดเชื่อมต่อ Wi-Fi เพื่อทำการจับคู่ครั้งแรกให้เสร็จสิ้น" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "ปิดเครื่อง" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "ป้องกันการอัปโหลดข้อมูลขนาดใหญ่เมื่อใช้การเชื่อมต่อ Wi-Fi แบบมิเตอร์" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "ป้องกันการอัพโหลดข้อมูลขนาดใหญ่เมื่อใช้การเชื่อมต่อมือถือแบบคิดค่าบริการตามปริมาณข้อมูล" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "ดูตัวอย่างกล้องที่หันหน้าไปทางคนขับเพื่อให้แน่ใจว่าการตรวจสอบผู้ขับขี่มีทัศนวิสัยที่ดี (รถจะต้องถูกปิด)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "ข้อผิดพลาดรหัส QR" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "ลบ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "รีเซ็ต" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "ทบทวน" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "รีบูต" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "รีบูตอุปกรณ์" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "รีบูตและอัปเดต" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "บันทึกและอัพโหลดกล้องไดร์เวอร์" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "บันทึกและอัปโหลดเสียงไมโครโฟน" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "บันทึกและจัดเก็บเสียงไมโครโฟนขณะขับรถ เสียงจะรวมอยู่ในวิดีโอ dashcam ด้วยการเชื่อมต่อด้วยเครื่องหมายจุลภาค" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "กฎระเบียบ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "ผ่อนคลาย" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "การเข้าถึงระยะไกล" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "สแนปชอตระยะไกล" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "คำขอหมดเวลา" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "รีเซ็ต" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "รีเซ็ตการปรับเทียบ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "ทบทวนคู่มือการฝึกอบรม" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "ตรวจสอบกฎ คุณสมบัติ และข้อจำกัดของ openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "เลือก" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "คีย์ SSH" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "กำลังสแกนเครือข่าย Wi-Fi..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "เลือก" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "เลือกสาขา" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "เลือกภาษา" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "อนุกรม" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "เลื่อนการอัปเดต" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "ซอฟต์แวร์" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "มาตรฐาน" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "ระบบไม่ตอบสนอง" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "เข้าควบคุมทันที" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "อุณหภูมิ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "สาขาเป้าหมาย" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "รหัสผ่านการแชร์อินเทอร์เน็ต" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "สลับ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "โหมดดีบัก UI" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "ถอนการติดตั้ง" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "อัปเดต" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "ถอนการติดตั้ง" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "ไม่ทราบ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "การอัพเดตจะถูกดาวน์โหลดในขณะที่รถดับอยู่เท่านั้น" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "อัพเกรดทันที" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "อัปโหลดข้อมูลจากกล้องที่หันเข้าหาคนขับและช่วยปรับปรุงอัลกอริธึมการตรวจสอบผู้ขับขี่" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "ใช้ระบบเมตริก" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "ยานพาหนะ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "ดู" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "กำลังรอที่จะเริ่ม" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "ยินดีต้อนรับสู่ openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "เมื่อเปิดใช้งาน การกดแป้นคันเร่งจะเป็นการปลดโอเพ่นไพลอต" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "อินเตอร์เน็ตไร้สาย" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "เครือข่าย Wi-Fi มีการตรวจวัด" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "รหัสผ่านผิด" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "คุณต้องยอมรับข้อกำหนดและเงื่อนไขเพื่อใช้งาน openpilot" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "คุณต้องยอมรับข้อกำหนดและเงื่อนไขเพื่อใช้ openpilot อ่านข้อกำหนดล่าสุดได้ที่ https://comma.ai/terms ก่อนดำเนินการต่อ" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "กำลังเริ่มกล้อง" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "กำลังตรวจสอบ..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "เครื่องหมายลูกน้ำเฉพาะ" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "ค่าเริ่มต้น" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "ลง" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "กำลังดาวน์โหลด..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "ไม่สามารถตรวจสอบการอัปเดตได้" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "กำลังสรุปการอัปเดต..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "สำหรับ \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "กม./ชม" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "เว้นว่างไว้เพื่อกำหนดค่าอัตโนมัติ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "ซ้าย" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "คิดค่าบริการตามปริมาณ" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "ไมล์/ชม." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "ไม่เคย" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "ตอนนี้" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "การควบคุมตามยาวของ openpilot (อัลฟา)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot ไม่พร้อมใช้งาน" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "ระบบควบคุมตามยาวของ openpilot อาจมาในการอัปเดตครั้งถัดไป" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot ต้องติดตั้งอุปกรณ์ให้อยู่ในช่วงเอียงซ้ายหรือขวาไม่เกิน 4° และเอียงขึ้นไม่เกิน 5° หรือเอียงลงไม่เกิน 9°" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "ขวา" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "ไม่จำกัดปริมาณ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "ขึ้น" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "เป็นเวอร์ชันล่าสุด ตรวจสอบครั้งล่าสุด: ไม่เคย" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "เป็นเวอร์ชันล่าสุด ตรวจสอบครั้งล่าสุดเมื่อ {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "มีอัปเดตใหม่" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "การแจ้งเตือน {} รายการ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} วันที่แล้ว" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} ชั่วโมงที่แล้ว" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} นาทีที่แล้ว" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "ขณะนี้มีช่วงการขับขี่ของคุณ {} ช่วงอยู่ในชุดข้อมูลฝึกสอนแล้ว" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ สมัครแล้ว" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 โหมด Firehose 🔥" + diff --git a/selfdrive/ui/translations/app_tr.po b/selfdrive/ui/translations/app_tr.po new file mode 100644 index 00000000000000..dbb5b325a61624 --- /dev/null +++ b/selfdrive/ui/translations/app_tr.po @@ -0,0 +1,825 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: tr\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Direksiyon tork tepkisi kalibrasyonu tamamlandı." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " Direksiyon tork tepkisi kalibrasyonu {}% tamamlandı." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Cihazınız {:.1f}° {} ve {:.1f}° {} yönünde konumlandırılmış." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 yıl sürüş depolaması" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "7/24 LTE bağlantısı" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

Direksiyon gecikmesi kalibrasyonu tamamlandı." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Direksiyon gecikmesi kalibrasyonu %{} tamamlandı." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "EKLE" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN Ayarı" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Aşırı Müdahaleyi Onayla" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Gelişmiş" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Agresif" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Kabul et" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Sürekli Sürücü İzleme" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Kapatmak istediğinizden emin misiniz?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Yeniden başlatmak istediğinizden emin misiniz?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Kalibrasyonu sıfırlamak istediğinizden emin misiniz?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Kaldırmak istediğinizden emin misiniz?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Geri" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "connect.comma.ai adresinde comma prime üyesi olun" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "connect.comma.ai'yi ana ekranınıza ekleyerek bir uygulama gibi kullanın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "DEĞİŞTİR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "KONTROL ET" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "CHILL MODU AÇIK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "BAĞLAN" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "BAĞLAN" + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "İptal" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Ölçülü Hücresel" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Dili Değiştir" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr " Bu ayarı değiştirmek, araç çalışıyorsa openpilot'u yeniden başlatacaktır." + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "\"yeni cihaz ekle\"ye tıklayın ve sağdaki QR kodunu tarayın" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Kapat" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Geçerli Sürüm" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "İNDİR" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Reddet" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "Reddet, openpilot'u kaldır" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Geliştirici" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Cihaz" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Gaz Pedalında Devreden Çık" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Kapatmak için Devreden Çıkın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Yeniden Başlatmak için Devreden Çıkın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Kalibrasyonu Sıfırlamak için Devreden Çıkın" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Hızı mph yerine km/h olarak göster." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "Dongle kimliği" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "İndir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Sürücü Kamerası" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Sürüş Kişiliği" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "DÜZENLE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "HATA" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "DENEYSEL MOD AÇIK" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "ADB'yi Etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Şerit Terk Uyarılarını Etkinleştir" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Dolaşımı Etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "SSH'yi Etkinleştir" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "İnternet Paylaşımını Etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "openpilot devrede değilken bile sürücü izlemesini etkinleştir." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "openpilot'u etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "Deneysel modu etkinleştirmek için openpilot boylamsal kontrolünü (alfa) açın." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "APN girin" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "SSID girin" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Yeni internet paylaşımı şifresini girin" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Şifre girin" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "GitHub kullanıcı adınızı girin" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Hata" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Deneysel Mod" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Bu araçta boylamsal kontrol için stok ACC kullanıldığından şu anda Deneysel mod kullanılamıyor." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "UNUTULUYOR..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Kurulumu Bitir" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Yoğun veri akışı" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose Modu" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Unut" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "\"{}\" Wi‑Fi ağı unutulsun mu?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "İYİ" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Telefonunuzda https://connect.comma.ai adresine gidin" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "YÜKSEK" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Gizli Ağ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "YÜKLE" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP Adresi" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Güncellemeyi Yükle" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Joystick Hata Ayıklama Modu" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "YÜKLENİYOR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Boylamsal Manevra Modu" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MAKS" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "openpilot'un sürüş modellerini iyileştirmek için eğitim veri yüklemelerinizi en üst düzeye çıkarın." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "Yok" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "HAYIR" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Ağ" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "'{}' kullanıcısı için SSH anahtarı bulunamadı" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Sürüm notu mevcut değil." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "ÇEVRİMDIŞI" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ÇEVRİMİÇİ" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Aç" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "EŞLE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "ÖNİZLEME" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME ÖZELLİKLERİ:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Cihazı Eşle" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Cihazı eşle" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Cihazınızı comma hesabınızla eşleştirin" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Cihazınızı comma connect (connect.comma.ai) ile eşleştirin ve comma prime teklifinizi alın." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "İlk eşleştirmeyi tamamlamak için lütfen Wi‑Fi'a bağlanın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Kapat" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Ölçülü bir Wi‑Fi bağlantısındayken büyük veri yüklemelerini engelle" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Ölçülü bir hücresel bağlantıdayken büyük veri yüklemelerini engelle" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Sürücü izleme görünürlüğünün iyi olduğundan emin olmak için sürücüye bakan kamerayı önizleyin. (araç kapalı olmalıdır)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR Kod Hatası" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "KALDIR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "SIFIRLA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "GÖZDEN GEÇİR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Yeniden Başlat" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Cihazı Yeniden Başlat" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Yeniden Başlat ve Güncelle" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Sürücü Kamerasını Kaydet ve Yükle" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Mikrofon Sesini Kaydet ve Yükle" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Sürüş sırasında mikrofon sesini kaydedip saklayın. Ses, comma connect'teki ön kamera videosuna dahil edilecektir." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Mevzuat" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Rahat" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Uzaktan erişim" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Uzaktan anlık görüntüler" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "İstek zaman aşımına uğradı" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Sıfırla" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Kalibrasyonu Sıfırla" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Eğitim Kılavuzunu İncele" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "openpilot'un kurallarını, özelliklerini ve sınırlamalarını gözden geçirin" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SEÇ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH Anahtarları" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Wi‑Fi ağları taranıyor..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Seç" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Bir dal seçin" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Bir dil seçin" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Seri" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Güncellemeyi Ertele" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Yazılım" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Standart" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Sistem Yanıt Vermiyor" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "HEMEN KONTROLÜ DEVRALIN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "SIC." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Hedef Dal" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "İnternet Paylaşımı Şifresi" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Seçenekler" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Arayüz Hata Ayıklama Modu" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "KALDIR" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "GÜNCELLE" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Kaldır" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Bilinmiyor" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Güncellemeler yalnızca araç kapalıyken indirilir." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Şimdi Yükselt" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Sürücüye bakan kameradan veri yükleyin ve sürücü izleme algoritmasını geliştirmeye yardımcı olun." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Metrik Sistemi Kullan" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "ARAÇ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "GÖRÜNTÜLE" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Başlatma bekleniyor" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "openpilot'a hoş geldiniz" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "Etkinleştirildiğinde, gaz pedalına basmak openpilot'u devreden çıkarır." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Ölçülü Wi‑Fi Ağı" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Yanlış şifre" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "openpilot'u kullanmak için Şartlar ve Koşulları kabul etmelisiniz." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "openpilot'u kullanmak için Şartlar ve Koşulları kabul etmelisiniz. Devam etmeden önce en güncel şartları https://comma.ai/terms adresinde okuyun." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "kamera başlatılıyor" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "kontrol ediliyor..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "varsayılan" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "aşağı" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "indiriliyor..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "güncelleme kontrolü başarısız" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "güncelleme tamamlanıyor..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "\"{}\" için" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "otomatik yapılandırma için boş bırakın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "sol" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "ölçülü" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "asla" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "şimdi" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "openpilot Boylamsal Kontrol (Alfa)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot Kullanılamıyor" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "openpilot boylamsal kontrolü gelecekteki bir güncellemede gelebilir." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot, cihazın sağa/sola 4° ve yukarı 5° veya aşağı 9° içinde monte edilmesini gerektirir." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "sağ" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "ölçüsüz" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "yukarı" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "güncel, son kontrol asla" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "güncel, son kontrol {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "güncelleme mevcut" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} UYARI" +msgstr[1] "{} UYARILAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} gün önce" +msgstr[1] "{} gün önce" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} saat önce" +msgstr[1] "{} saat önce" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} dakika önce" +msgstr[1] "{} dakika önce" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segment sürüşünüz eğitim veri setinde." +msgstr[1] "{} segment sürüşünüz eğitim veri setinde." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ABONE" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose Modu 🔥" + diff --git a/selfdrive/ui/translations/app_uk.po b/selfdrive/ui/translations/app_uk.po new file mode 100644 index 00000000000000..3f3d1866579338 --- /dev/null +++ b/selfdrive/ui/translations/app_uk.po @@ -0,0 +1,830 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: uk\n" +"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Калібрування реакції крутного моменту керма завершено." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr "Калібрування реакції крутного моменту керма завершено на {}%." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Ваш пристрій нахилено на {:.1f}° {} та {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 рік зберігання поїздок" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "Підключення LTE 24/7" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

Калібрування затримки кермування завершено." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Калібрування затримки кермування завершено на {}%." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "ДОДАТИ" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "Налаштування APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Визнайте надмірне спрацьовування" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Розширені" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Агресивн." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Погодитися" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Постійний моніторинг водія" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Ви впевнені, що хочете вимкнути?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Ви впевнені, що хочете перезавантажити?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Ви впевнені, що хочете скинути калібрування?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Ви впевнені, що хочете видалити?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Назад" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Станьте членом comma prime на connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Додайте connect.comma.ai до головного екрану, щоб використовувати його як додаток." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "ЗМІНИТИ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "ПЕРЕВІРИТИ" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "СПОКІЙНИЙ РЕЖИМ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "ПІДКЛЮЧИТИ" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "ПІДКЛЮЧА..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Скасувати" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Лімітне стільникове з'єднання" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Змінити мову" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "Зміна цього параметра призведе до перезапуску openpilot, якщо автомобіль увімкнено." + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Натисніть «додати новий пристрій» і відскануйте QR-код праворуч." + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Закрити" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Поточна версія" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "ВАНТАЖ" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Відхилити" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "Відхилити, видалити openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Розробник" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Пристрій" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Вимкнення при натисканні на педаль газу" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Вимкніть openpilot, щоб вимкнути пристрій" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Вимкніть openpilot, щоб перезавантажити" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Деактивуйте для скидання калібрування" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Відображати швидкість у км/год замість миль/год." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ID ключа" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Завантажити" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Камера водія" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Стиль водіння" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "РЕДАГ." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ПОМИЛКА" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "ЕКСПЕРИМЕНТ. РЕЖИМ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Увімкнути" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Увімкнути ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Увімкнути попередження про виїзд зі смуги" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Увімкнути роумінг" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Увімкнути SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Увімкнути точку доступу" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "Увімкнути моніторинг водія, навіть коли openpilot не ввімкнено." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "Увімкнути openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "Увімкніть перемикач поздовжнього керування openpilot (альфа), щоб увімкнути експериментальний режим." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Введіть APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Введіть SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Введіть новий пароль для модему" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Введіть пароль" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Введіть ваш логін GitHub" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Помилка" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Експериментальний режим" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Експериментальний режим наразі недоступний для цього автомобіля, оскільки для поздовжнього керування використовується штатний адаптивний круїз-контроль (ACC)." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "ЗАБУВАЮ..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Завершити налаштування" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Злива" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Режим зливи" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Забути" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Забути мережу Wi-Fi \"{}\"?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "ДОБРА" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Перейдіть на сайт https://connect.comma.ai на своєму телефоні." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "ВИСОКА" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Прихована мережа" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "ВСТАНОВ." + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP-адреса" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Встановити оновлення" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Режим зневадження джойстика" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "ЗАВАНТАЖЕННЯ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Режим поздовжнього маневрування" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "МАКС" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Максимізуйте завантаження навчальних даних, щоб поліпшити моделі openpilot." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "Н/Д" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "НЕМАЄ" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Мережа" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "Користувач '{}' не має ключів на GitHub" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Інформація про випуск відсутня." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "ОФЛАЙН" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ОНЛАЙН" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "ВІДКРИТИ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "ПІДКЛЮЧИТИ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "ПОКАЖИ" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "XАРАКТЕРИСТИКИ PRIME:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Підключити пристрій" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Підключити пристрій" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Підключіть свій пристрій до обліковки comma connect" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Підключіть свій пристрій до comma connect (connect.comma.ai) і отримайте свою пропозицію comma prime." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Будь ласка, підключіться до Wi-Fi, щоб завершити початкове сполучення." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Вимкнути" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Запобігайте завантаженню великих обсягів даних під час використання Wi-Fi-з'єднання з обмеженим трафіком" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Запобігати великим завантаженням даних під час лімітного стільникового з'єднання" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Попередньо перегляньте камеру, спрямовану на водія, щоб переконатися, що система моніторингу водія має добру видимість. (автомобіль повинен бути вимкнений)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "Помилка QR-коду" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "ВИДАЛИТИ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "Скинути" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "ДИВИТИСЬ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Перезавантажити" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Перезавантажте пристрій" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Перезавантажити та оновити" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Писати та вантажити відео з камери водія" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Запис та завантаження аудіо з мікрофона" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Записуйте та зберігайте аудіо з мікрофона під час руху. Аудіо буде включено до відео з відеореєстратора в comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Нормативні документи" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Спокійний" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Віддалений доступ" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Віддалені знімки" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Час запиту вичерпано" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Скинути" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Скинути калібрування" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Переглянути посібник з навчання" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "Перегляньте правила, функції та обмеження openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "ВИБРАТИ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH ключі" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Пошук мереж..." + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Вибрати" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Виберіть гілку" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Виберіть мову" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Серійний номер" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Відкласти оновлення" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Програма" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Стандарт" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Система не реагує" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "КЕРМУЙТЕ НЕГАЙНО" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "ТЕМП" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Цільова гілка" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Пароль для точки доступу" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Перемикачі" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Режим налагодження інтерфейсу" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "ВИДАЛИТИ" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "ОНОВИТИ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Видалити" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Невідомо" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Оновлення завантажуються лише тоді, коли автомобіль вимкнено." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Оновити зараз" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Завантажуйте дані з камери, спрямованої на водія, та допоможіть покращити алгоритм моніторингу водія." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Використовувати метричну систему" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "АВТО" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "ДИВИСЬ" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Очікування початку" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "Ласкаво просимо до openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "Якщо увімкнено, натискання на педаль акселератора вимкне openpilot." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi-Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Трафік Wi-Fi" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Невірний пароль" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "Ви повинні прийняти Умови та положення, щоб користуватися openpilot." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "Ви повинні прийняти Умови використання, щоб користуватися openpilot. Перед тим, як продовжити, ознайомтеся з останніми умовами на сайті https://comma.ai/terms." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "запуск камери" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "перевіряю..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "замовч." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "вниз" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "завантажую..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "не вдалося перевірити оновлення" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "завершую..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "для \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "км/год" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "залиште порожнім для автоматичного налаштування" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "вліво" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "обмеж." + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "миль/год" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "ніколи" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "зараз" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "Поздовжнє керування openpilot (Альфа)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot Недоступний" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "Поздовжнє керування openpilot може з'явитися в майбутньому оновленні." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "Для роботи openpilot потрібно, щоб пристрій був встановлений з нахилом не більше 4° вліво або вправо та не більше 5° вгору або 9° вниз. openpilot постійно калібрується, тому скидання калібрування потрібне рідко." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "вправо" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "необмеж." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "вгору" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "оновлено, ніколи не перевірялось" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "оновлено, перевірив {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "доступне оновлення" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} СПОВІЩЕННЯ" +msgstr[1] "{} СПОВІЩЕННЯ" +msgstr[2] "{} СПОВІЩЕНЬ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} день тому" +msgstr[1] "{} дні тому" +msgstr[2] "{} днів тому" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} година тому" +msgstr[1] "{} години тому" +msgstr[2] "{} годин тому" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} хвилина тому" +msgstr[1] "{} хвилини тому" +msgstr[2] "{} хвилин тому" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} сегмент вашого водіння на даний момент містяться в тренувальному наборі даних." +msgstr[1] "{} сегменти вашого водіння на даний момент містяться в тренувальному наборі даних." +msgstr[2] "{} сегментів вашого водіння на даний момент містяться в тренувальному наборі даних." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ПІДПИСАНО" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🌧️ Режим зливи 🌧️" + diff --git a/selfdrive/ui/translations/app_zh-CHS.po b/selfdrive/ui/translations/app_zh-CHS.po new file mode 100644 index 00000000000000..55a7c329f632a8 --- /dev/null +++ b/selfdrive/ui/translations/app_zh-CHS.po @@ -0,0 +1,825 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: zh-CHS\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " 转向扭矩响应校准完成。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " 转向扭矩响应校准已完成 {}%。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " 您的设备朝向 {:.1f}° {} 与 {:.1f}° {}。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 年行驶数据存储" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "全天候 LTE 连接" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

转向延迟校准完成。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

转向延迟校准已完成 {}%。" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "添加" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN 设置" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "确认过度作动" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "高级" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "激进" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "同意" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "始终启用驾驶员监控" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "确定要关机吗?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "确定要重启吗?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "确定要重置校准吗?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "确定要卸载吗?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "返回" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "前往 connect.comma.ai 成为 comma prime 会员" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "将 connect.comma.ai 添加到主屏幕,像应用一样使用" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "更改" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "检查" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "安稳模式已开启" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "连接" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "连接中..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "取消" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "蜂窝计量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "更改语言" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "若车辆通电,更改此设置将重启 openpilot。" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "点击“添加新设备”,扫描右侧二维码" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "关闭" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "当前版本" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "下载" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "拒绝" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "拒绝并卸载 openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "开发者" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "设备" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "踩下加速踏板时脱离" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "脱离以关机" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "脱离以重启" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "脱离以重置校准" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "以 km/h 显示速度(非 mph)。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "设备 ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "下载" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "车内摄像头" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "驾驶风格" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "编辑" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "错误" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "实验模式已开启" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "启用" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "启用 ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "启用车道偏离警示" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "启用漫游" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "启用 SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "启用网络共享" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "即使未启用 openpilot 也启用驾驶员监控。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "启用 openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "启用 openpilot 纵向控制(alpha)开关,以使用实验模式。" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "输入 APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "输入 SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "输入新的网络共享密码" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "输入密码" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "输入您的 GitHub 用户名" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "错误" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "实验模式" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "此车型当前无法使用实验模式,因为纵向控制使用的是原厂 ACC。" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "正在遗忘..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "完成设置" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "数据洪流" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose 模式" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "忘记" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "要忘记 Wi‑Fi 网络“{}”吗?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "良好" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "在手机上前往 https://connect.comma.ai" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "高" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "隐藏网络" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "安装" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP 地址" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "安装更新" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "摇杆调试模式" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "加载中" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "纵向操作模式" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "最大" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "最大化上传训练数据,以改进 openpilot 的驾驶模型。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "无" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "否" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "网络" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "未找到用户“{}”的 SSH 密钥" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "暂无发行说明。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "离线" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "确定" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "在线" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "打开" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "配对" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "预览" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME 功能:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "配对设备" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "配对设备" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "将设备配对到您的 comma 账号" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "将设备与 comma connect(connect.comma.ai)配对,领取您的 comma prime 优惠。" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "请连接 Wi‑Fi 以完成初始配对" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "关机" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "在计量制 Wi‑Fi 连接时避免大量上传" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "在计量制蜂窝网络时避免大量上传" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "预览车内摄像头以确保驾驶员监控视野良好。(车辆必须熄火)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "二维码错误" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "移除" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "重置" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "查看" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "重启" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "重启设备" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "重启并更新" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "录制并上传车内摄像头" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "录制并上传麦克风音频" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "行驶时录制并保存麦克风音频。音频将包含在 comma connect 的行车记录视频中。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "法规" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "从容" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "远程访问" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "远程快照" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "请求超时" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "重置" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "重置校准" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "查看训练指南" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "查看 openpilot 的规则、功能与限制" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "选择" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH 密钥" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "正在扫描 Wi‑Fi 网络…" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "选择" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "选择分支" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "选择语言" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "序列号" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "延后更新" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "软件" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "标准" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "系统无响应" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "请立即接管控制" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "温度" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "目标分支" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "网络共享密码" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "切换" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "界面调试模式" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "卸载" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "更新" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "卸载" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "未知" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "仅在车辆熄火时下载更新。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "立即升级" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "上传车内摄像头数据,帮助改进驾驶员监控算法。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "使用公制" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "车辆" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "查看" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "等待开始" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "欢迎使用 openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "启用后,踩下加速踏板将会脱离 openpilot。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi‑Fi 计量网络" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "密码错误" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "您必须接受条款与条件才能使用 openpilot。" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "您必须接受条款与条件才能使用 openpilot。继续前请阅读 https://comma.ai/terms 上的最新条款。" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "相机启动中" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "检查中..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "默认" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "下" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "下载中..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "检查更新失败" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "正在完成更新..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "用于“{}”" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "留空以自动配置" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "左" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "计量" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "从不" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "现在" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "openpilot 纵向控制(Alpha)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot 无法使用" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "openpilot 纵向控制可能会在未来更新中提供。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot 要求设备安装在左右 4°、上 5° 或下 9° 以内。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "右" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "不限流量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "上" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "已是最新,最后检查:从未" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "已是最新,最后检查:{}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "有可用更新" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} 条警报" +msgstr[1] "{} 条警报" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} 天前" +msgstr[1] "{} 天前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} 小时前" +msgstr[1] "{} 小时前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} 分钟前" +msgstr[1] "{} 分钟前" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "目前已有 {} 个您的驾驶片段被纳入训练数据集。" +msgstr[1] "目前已有 {} 个您的驾驶片段被纳入训练数据集。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ 已订阅" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose 模式 🔥" + diff --git a/selfdrive/ui/translations/app_zh-CHT.po b/selfdrive/ui/translations/app_zh-CHT.po new file mode 100644 index 00000000000000..93f9b9ed8e1039 --- /dev/null +++ b/selfdrive/ui/translations/app_zh-CHT.po @@ -0,0 +1,825 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: zh-CHT\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " 轉向扭矩回應校正完成。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " 轉向扭矩回應校正已完成 {}%。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " 您的裝置朝向 {:.1f}° {} 與 {:.1f}° {}。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 年行駛資料儲存" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "全年無休 LTE 連線" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

轉向延遲校正完成。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

轉向延遲校正已完成 {}%。" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "新增" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN 設定" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "確認過度作動" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "進階" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "積極" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "同意" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "持續啟用駕駛監控" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "確定要關機嗎?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "確定要重新啟動嗎?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "確定要重設校正嗎?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "確定要解除安裝嗎?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "返回" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "前往 connect.comma.ai 成為 comma prime 會員" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "將 connect.comma.ai 加到主畫面,像 App 一樣使用" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "變更" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "檢查" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "安穩模式已開啟" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "連線" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "連線中..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "取消" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "行動網路計量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "變更語言" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart openpilot if the car is powered on." +msgstr "若車輛通電,變更此設定將重新啟動 openpilot。" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "點選「新增裝置」,掃描右側 QR 碼" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "關閉" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "目前版本" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "下載" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "拒絕" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall openpilot" +msgstr "拒絕並解除安裝 openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "開發人員" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "裝置" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "踩下加速踏板時脫離" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "脫離以關機" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "脫離以重新啟動" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "脫離以重設校正" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "以 km/h 顯示速度(非 mph)。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "裝置 ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "下載" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "車內鏡頭" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "駕駛風格" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "編輯" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "錯誤" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "實驗模式已開啟" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "啟用" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "啟用 ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "啟用偏離車道警示" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "啟用漫遊" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "啟用 SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "啟用網路共享" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when openpilot is not engaged." +msgstr "即使未啟動 openpilot 亦啟用駕駛監控。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable openpilot" +msgstr "啟用 openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "啟用 openpilot 縱向控制(alpha)切換,以使用實驗模式。" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "輸入 APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "輸入 SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "輸入新的網路共享密碼" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "輸入密碼" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "輸入您的 GitHub 使用者名稱" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "錯誤" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "實驗模式" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "此車款目前無法使用實驗模式,因為縱向控制使用的是原廠 ACC。" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "正在遺忘..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "完成設定" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "資料洪流" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose 模式" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "忘記" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "要忘記 Wi‑Fi 網路「{}」嗎?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "良好" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "在手機上前往 https://connect.comma.ai" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "高" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "隱藏網路" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "安裝" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP 位址" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "安裝更新" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "搖桿除錯模式" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "載入中" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "縱向操作模式" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "最大" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "最大化上傳訓練資料,以改進 openpilot 的駕駛模型。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "無" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "否" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "網路" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "找不到使用者 '{}' 的 SSH 金鑰" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "無可用發行說明。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "離線" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "確定" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "線上" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "開啟" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "配對" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "預覽" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME 功能:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "配對裝置" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "配對裝置" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "將裝置配對至您的 comma 帳號" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "將裝置與 comma connect(connect.comma.ai)配對,領取您的 comma prime 優惠。" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "請連線至 Wi‑Fi 以完成初始化配對" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "關機" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "在計量制 Wi‑Fi 連線時避免大量上傳" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "在計量制行動網路時避免大量上傳" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "預覽車內鏡頭以確保駕駛監控視野良好。(車輛須熄火)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR 碼錯誤" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "移除" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "重設" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "檢視" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "重新啟動" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "重新啟動裝置" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "重新啟動並更新" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "錄製並上傳車內鏡頭" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "錄製並上傳麥克風音訊" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "行車時錄製並儲存麥克風音訊。音訊將包含在 comma connect 的行車紀錄影片中。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "法規" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "從容" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "遠端存取" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "遠端擷圖" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "要求逾時" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "重設" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "重設校正" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "檢視訓練指南" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of openpilot" +msgstr "檢視 openpilot 的規則、功能與限制" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "選取" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH 金鑰" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "正在掃描 Wi‑Fi 網路…" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "選取" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "選取分支" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "選取語言" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "序號" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "延後更新" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "軟體" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "標準" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "系統無回應" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "請立刻接手控制" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "溫度" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "目標分支" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "網路共享密碼" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "切換" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "介面除錯模式" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "解除安裝" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "更新" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "解除安裝" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "未知" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "僅在車輛熄火時下載更新。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "立即升級" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "上傳車內鏡頭資料,協助改善駕駛監控演算法。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "使用公制" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "車輛" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "檢視" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "等待開始" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to openpilot" +msgstr "歡迎使用 openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage openpilot." +msgstr "啟用後,踩下加速踏板將會脫離 openpilot。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi‑Fi 計量網路" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "密碼錯誤" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions in order to use openpilot." +msgstr "您必須接受條款與細則才能使用 openpilot。" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing." +msgstr "您必須接受條款與細則才能使用 openpilot。繼續前請閱讀 https://comma.ai/terms 上的最新條款。" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "相機啟動中" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "檢查中..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "預設" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "下" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "下載中..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "檢查更新失敗" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "正在完成更新..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "適用於「{}」" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "留空以自動設定" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "左" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "計量" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "從不" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "現在" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "openpilot Longitudinal Control (Alpha)" +msgstr "openpilot 縱向控制(Alpha)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "openpilot Unavailable" +msgstr "openpilot 無法使用" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "openpilot longitudinal control may come in a future update." +msgstr "openpilot 縱向控制可能於未來更新提供。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "openpilot 要求裝置安裝在左右 4°、上 5° 或下 9° 以內。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "右" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "不限流量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "上" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "已為最新,最後檢查:從未" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "已為最新,最後檢查:{}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "有可用更新" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} 則警示" +msgstr[1] "{} 則警示" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} 天前" +msgstr[1] "{} 天前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} 小時前" +msgstr[1] "{} 小時前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} 分鐘前" +msgstr[1] "{} 分鐘前" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "目前已有 {} 個您的駕駛片段納入訓練資料集。" +msgstr[1] "目前已有 {} 個您的駕駛片段納入訓練資料集。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ 已訂閱" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose 模式 🔥" + diff --git a/selfdrive/ui/translations/auto_translate.py b/selfdrive/ui/translations/auto_translate.py deleted file mode 100755 index c2e4bbc5527b6a..00000000000000 --- a/selfdrive/ui/translations/auto_translate.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import json -import os -import pathlib -import xml.etree.ElementTree as ET -from typing import cast - -import requests - -TRANSLATIONS_DIR = pathlib.Path(__file__).resolve().parent -TRANSLATIONS_LANGUAGES = TRANSLATIONS_DIR / "languages.json" - -OPENAI_MODEL = "gpt-4" -OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") -OPENAI_PROMPT = "You are a professional translator from English to {language} (ISO 639 language code). " + \ - "The following sentence or word is in the GUI of a software called openpilot, translate it accordingly." - - -def get_language_files(languages: list[str] = None) -> dict[str, pathlib.Path]: - files = {} - - with open(TRANSLATIONS_LANGUAGES) as fp: - language_dict = json.load(fp) - - for filename in language_dict.values(): - path = TRANSLATIONS_DIR / f"{filename}.ts" - language = path.stem.split("main_")[1] - - if languages is None or language in languages: - files[language] = path - - return files - - -def translate_phrase(text: str, language: str) -> str: - response = requests.post( - "https://api.openai.com/v1/chat/completions", - json={ - "model": OPENAI_MODEL, - "messages": [ - { - "role": "system", - "content": OPENAI_PROMPT.format(language=language), - }, - { - "role": "user", - "content": text, - }, - ], - "temperature": 0.8, - "max_tokens": 1024, - "top_p": 1, - }, - headers={ - "Authorization": f"Bearer {OPENAI_API_KEY}", - "Content-Type": "application/json", - }, - ) - - if 400 <= response.status_code < 600: - raise requests.HTTPError(f'Error {response.status_code}: {response.json()}', response=response) - - data = response.json() - - return cast(str, data["choices"][0]["message"]["content"]) - - -def translate_file(path: pathlib.Path, language: str, all_: bool) -> None: - tree = ET.parse(path) - - root = tree.getroot() - - for context in root.findall("./context"): - name = context.find("name") - if name is None: - raise ValueError("name not found") - - print(f"Context: {name.text}") - - for message in context.findall("./message"): - source = message.find("source") - translation = message.find("translation") - - if source is None or translation is None: - raise ValueError("source or translation not found") - - if not all_ and translation.attrib.get("type") != "unfinished": - continue - - llm_translation = translate_phrase(cast(str, source.text), language) - - print(f"Source: {source.text}\n" + - f"Current translation: {translation.text}\n" + - f"LLM translation: {llm_translation}") - - translation.text = llm_translation - - with path.open("w", encoding="utf-8") as fp: - fp.write('\n' + - '\n' + - ET.tostring(root, encoding="utf-8").decode()) - - -def main(): - arg_parser = argparse.ArgumentParser("Auto translate") - - group = arg_parser.add_mutually_exclusive_group(required=True) - group.add_argument("-a", "--all-files", action="store_true", help="Translate all files") - group.add_argument("-f", "--file", nargs="+", help="Translate the selected files. (Example: -f fr de)") - - arg_parser.add_argument("-t", "--all-translations", action="store_true", default=False, help="Translate all sections. (Default: only unfinished)") - - args = arg_parser.parse_args() - - if OPENAI_API_KEY is None: - print("OpenAI API key is missing. (Hint: use `export OPENAI_API_KEY=YOUR-KEY` before you run the script).\n" + - "If you don't have one go to: https://beta.openai.com/account/api-keys.") - exit(1) - - files = get_language_files(None if args.all_files else args.file) - - if args.file: - missing_files = set(args.file) - set(files) - if len(missing_files): - print(f"No language files found: {missing_files}") - exit(1) - - print(f"Translation mode: {'all' if args.all_translations else 'only unfinished'}. Files: {list(files)}") - - for lang, path in files.items(): - print(f"Translate {lang} ({path})") - translate_file(path, lang, args.all_translations) - - -if __name__ == "__main__": - main() diff --git a/selfdrive/ui/translations/auto_translate.sh b/selfdrive/ui/translations/auto_translate.sh new file mode 100755 index 00000000000000..03a207ca3c4b0a --- /dev/null +++ b/selfdrive/ui/translations/auto_translate.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail + +DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd)" +ROOT="$DIR/../../../" + +cd $DIR +./update_translations.py + +command -v codex >/dev/null || { + echo "Install codex CLI to continue:" + echo "-> https://developers.openai.com/codex/cli" + echo + exit 1 +} + +codex exec --cd "$ROOT" -c 'model_reasoning_effort="low"' --dangerously-bypass-approvals-and-sandbox "$(cat < 90 else "red" - - # Download badge - badge_label = f"LANGUAGE {name}" - badge_message = f"{percent_finished}% complete" - if unfinished_translations != 0: - badge_message += f" ({unfinished_translations} unfinished)" - - r = requests.get(f"{SHIELDS_URL}/{badge_label}-{badge_message}-{color}", timeout=10) - assert r.status_code == 200, "Error downloading badge" - content_svg = r.content.decode("utf-8") - - xml = ET.fromstring(content_svg) - assert "width" in xml.attrib - max_badge_width = max(max_badge_width, int(xml.attrib["width"])) - - # Make tag ids in each badge unique to combine them into one svg - for tag in ("r", "s"): - content_svg = content_svg.replace(f'id="{tag}"', f'id="{tag}{idx}"') - content_svg = content_svg.replace(f'"url(#{tag})"', f'"url(#{tag}{idx})"') - - badge_svg.extend([f'', content_svg, ""]) - - badge_svg.insert(0, '') - badge_svg.append("") - - with open(os.path.join(BASEDIR, "translation_badge.svg"), "w") as badge_f: - badge_f.write("\n".join(badge_svg)) diff --git a/selfdrive/ui/translations/languages.json b/selfdrive/ui/translations/languages.json index 132b5088d7e199..99d3aafe3a2f92 100644 --- a/selfdrive/ui/translations/languages.json +++ b/selfdrive/ui/translations/languages.json @@ -1,14 +1,14 @@ { - "English": "main_en", - "Deutsch": "main_de", - "Français": "main_fr", - "Português": "main_pt-BR", - "Español": "main_es", - "Türkçe": "main_tr", - "العربية": "main_ar", - "ไทย": "main_th", - "中文(繁體)": "main_zh-CHT", - "中文(简体)": "main_zh-CHS", - "한국어": "main_ko", - "日本語": "main_ja" + "English": "en", + "Deutsch": "de", + "Français": "fr", + "Português": "pt-BR", + "Español": "es", + "Türkçe": "tr", + "Українська": "uk", + "ไทย": "th", + "中文(繁體)": "zh-CHT", + "中文(简体)": "zh-CHS", + "한국어": "ko", + "日本語": "ja" } diff --git a/selfdrive/ui/translations/main_ar.ts b/selfdrive/ui/translations/main_ar.ts deleted file mode 100644 index 0116f3c15299ea..00000000000000 --- a/selfdrive/ui/translations/main_ar.ts +++ /dev/null @@ -1,1155 +0,0 @@ - - - - - AbstractAlert - - Close - إغلاق - - - Snooze Update - تأخير التحديث - - - Reboot and Update - إعادة التشغيل والتحديث - - - - AdvancedNetworking - - Back - السابق - - - Enable Tethering - تمكين الربط - - - Tethering Password - كلمة مرور الربط - - - EDIT - تعديل - - - Enter new tethering password - أدخل كلمة مرور الربط الجديدة - - - IP Address - عنوان IP - - - Enable Roaming - تمكين التجوال - - - APN Setting - إعدادات APN - - - Enter APN - إدخال APN - - - leave blank for automatic configuration - اتركه فارغاً من أجل التكوين التلقائي - - - Cellular Metered - محدود بالاتصال الخلوي - - - Prevent large data uploads when on a metered connection - منع تحميل البيانات الكبيرة عندما يكون الاتصال محدوداً - - - Hidden Network - شبكة مخفية - - - CONNECT - الاتصال - - - Enter SSID - أدخل SSID - - - Enter password - أدخل كلمة المرور - - - for "%1" - من أجل "%1" - - - - AnnotatedCameraWidget - - km/h - كم/س - - - mph - ميل/س - - - MAX - MAX - - - - ConfirmationDialog - - Ok - موافق - - - Cancel - إلغاء - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - يجب عليك قبول الشروط والأحكام من أجل استخدام openpilot. - - - Back - السابق - - - Decline, uninstall %1 - رفض، إلغاء التثبيت %1 - - - - DevicePanel - - Dongle ID - معرف دونجل - - - N/A - غير متاح - - - Serial - الرقم التسلسلي - - - Driver Camera - كاميرة السائق - - - PREVIEW - معاينة - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - قم بمعاينة الكاميرا المواجهة للسائق للتأكد من أن نظام مراقبة السائق يتمتع برؤية جيدة. (يجب أن تكون السيارة متوقفة) - - - Reset Calibration - إعادة ضبط المعايرة - - - RESET - إعادة الضبط - - - Are you sure you want to reset calibration? - هل أنت متأكد أنك تريد إعادة ضبط المعايرة؟ - - - Review Training Guide - مراجعة دليل التدريب - - - REVIEW - مراجعة - - - Review the rules, features, and limitations of openpilot - مراجعة الأدوار والميزات والقيود في openpilot - - - Are you sure you want to review the training guide? - هل أنت متأكد أنك تريد مراجعة دليل التدريب؟ - - - Regulatory - التنظيمية - - - VIEW - عرض - - - Change Language - تغيير اللغة - - - CHANGE - تغيير - - - Select a language - اختر لغة - - - Reboot - إعادة التشغيل - - - Power Off - إيقاف التشغيل - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - يحتاج openpilot أن يتم ضبط الجهاز ضمن حدود 4 درجات يميناً أو يساراً و5 درجات نحو الأعلى أو 9 نحو الأسفل. يقوم openpilot بالمعايرة باستمرار، ونادراً ما يحتاج إلى عملية إعادة الضبط. - - - Your device is pointed %1° %2 and %3° %4. - يشير جهازك إلى %1 درجة %2، و%3 درجة %4. - - - down - نحو الأسفل - - - up - نحو الأعلى - - - left - نحو اليسار - - - right - نحو اليمين - - - Are you sure you want to reboot? - هل أنت متأكد أنك تريد إعادة التشغيل؟ - - - Disengage to Reboot - فك الارتباط من أجل إعادة التشغيل - - - Are you sure you want to power off? - هل أنت متأكد أنك تريد إيقاف التشغيل؟ - - - Disengage to Power Off - فك الارتباط من أجل إيقاف التشغيل - - - Reset - إعادة الضبط - - - Review - مراجعة - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - اقرن جهازك بجهاز (connect.comma.ai) واحصل على عرضك من comma prime. - - - Pair Device - إقران الجهاز - - - PAIR - إقران - - - - DriverViewWindow - - camera starting - بدء تشغيل الكاميرا - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - تشغيل الوضع التجريبي - - - CHILL MODE ON - تشغيل وضع الراحة - - - - InputDialog - - Cancel - إلغاء - - - Need at least %n character(s)! - - تحتاج إلى حرف %n على الأقل! - تحتاج إلى حرف %n على الأقل! - تحتاج إلى حرفين %n على الأقل! - تحتاج إلى %n أحرف على الأقل! - تحتاج إلى %n أحرف على الأقل! - تحتاج إلى %n حرف على الأقل! - - - - - Installer - - Installing... - جارٍ التثبيت... - - - - MultiOptionDialog - - Select - اختيار - - - Cancel - إلغاء - - - - Networking - - Advanced - متقدم - - - Enter password - أدخل كلمة المرور - - - for "%1" - من أجل "%1" - - - Wrong password - كلمة مرور خاطئة - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - درجة حرارة الجهاز مرتفعة جداً. يقوم النظام بالتبريد قبل البدء. درجة الحرارة الحالية للمكونات الداخلية: %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - اتصل فوراً بالإنترنت للتحقق من وجود تحديثات. إذا لم تكم متصلاً بالإنترنت فإن openpilot لن يساهم في %1 - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - اتصل بالإنترنت للتحقق من وجود تحديثات. لا يعمل openpilot تلقائياً إلا إذا اتصل بالإنترنت من أجل التحقق من التحديثات. - - - Unable to download updates -%1 - غير قادر على تحميل التحديثات -%1 - - - Taking camera snapshots. System won't start until finished. - التقاط لقطات كاميرا. لن يبدأ النظام حتى تنتهي هذه العملية. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - يتم تنزيل تحديث لنظام تشغيل جهازك في الخلفية. سيطلَب منك التحديث عندما يصبح جاهزاً للتثبيت. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - فشل تسجيل الجهاز. لن يقوم بالاتصال أو تحميل خوادم comma.ai، ولا تلقي الدعم من comma.ai. إذا كان هذا الجهاز نظامياً فيرجى زيارة الموقع https://comma.ai/support. - - - NVMe drive not mounted. - محرك NVMe غير مثبَّت. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - تم اكتشاف محرك NVMe غير مدعوم. قد يستهلك الجهاز قدراً أكبر بكثير من الطاقة، وزيادة في ارتفاع درجة الحرارة بسبب وجود NVMe غير مدعوم. - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - لم يكن openpilot قادراً على تحديد سيارتك. إما أن تكون سيارتك غير مدعومة أو أنه لم يتم التعرف على وحدة التحكم الإلكتروني (ECUs) فيها. يرجى تقديم طلب سحب من أجل إضافة نسخ برمجيات ثابتة إلى السيارة المناسبة. هل تحتاج إلى أي مساعدة؟ لا تتردد في التواصل مع doscord.comma.ai. - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - لم يتمكن openpilot من تحديد سيارتك. تحقق من سلامة الكابلات وتأكد من تأمين جميع الوصلات، لا سيما أنه قد تم إدخال طاقة الفاصلة بالكامل في منفذ OBD-II في السيارة. هل تريد أي مساعدة؟ لا تتردد في الانضمام إلى discord.comma.ai. - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - لقد اكتشف openpilot تغييراً في موقع تركيب الجهاز. تأكد من تثبيت الجهاز بشكل كامل في موقعه وتثبيته بإحكام على الزجاج الأمامي. - - - - OffroadHome - - UPDATE - تحديث - - - ALERTS - التنبهات - - - ALERT - تنبيه - - - - OnroadAlerts - - openpilot Unavailable - openpilot غير متوفر - - - Waiting for controls to start - في انتظار بدء عناصر التحكم - - - TAKE CONTROL IMMEDIATELY - تحكم على الفور - - - Controls Unresponsive - الضوابط غير مستجيبة - - - Reboot Device - إعادة التشغيل - - - - PairingPopup - - Pair your device to your comma account - اقرن جهازك مع حسابك على comma - - - Go to https://connect.comma.ai on your phone - انتقل إلى https://connect.comma.ai على جوالك - - - Click "add new device" and scan the QR code on the right - انقر "،إضافة جهاز جديد"، وامسح رمز الاستجابة السريعة (QR) على اليمين - - - Bookmark connect.comma.ai to your home screen to use it like an app - اجعل لـconnect.comma.ai إشارة مرجعية على شاشتك الرئيسية من أجل استخدامه مثل أي تطبيق - - - - ParamControl - - Enable - تمكين - - - Cancel - إلغاء - - - - PrimeAdWidget - - Upgrade Now - الترقية الآن - - - Become a comma prime member at connect.comma.ai - كن عضوًا في comma prime على connect.comma.ai - - - PRIME FEATURES: - الميزات الأساسية: - - - Remote access - التحكم عن بعد - - - 24/7 LTE connectivity - اتصال LTE على مدار الساعة 24/7 - - - 1 year of drive storage - سنة واحدة من تخزين القرص - - - Remote snapshots - لقطات عن بُعد - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ مشترك - - - comma prime - comma prime - - - - QObject - - Reboot - إعادة التشغيل - - - Exit - إغلاق - - - openpilot - openpilot - - - %n minute(s) ago - - منذ %n دقيقة - منذ %n دقيقة - منذ دقيقتين %n - منذ %n دقائق - منذ %n دقائق - منذ %n دقيقة - - - - %n hour(s) ago - - منذ %n ساعة - منذ %n ساعة - منذ ساعتين %n - منذ %n ساعات - منذ %n ساعات - منذ %n ساعة - - - - %n day(s) ago - - منذ %n يوم - منذ %n يوم - منذ يومين %n - منذ %n أيام - منذ %n أيام - منذ %n يوم - - - - now - الآن - - - - Reset - - Reset failed. Reboot to try again. - فشل إعاة الضبط. أعد التشغيل للمحاولة من جديد. - - - Are you sure you want to reset your device? - هل أنت متأكد أنك تريد إعادة ضبط جهازك؟ - - - System Reset - إعادة ضبط النظام - - - Cancel - إلغاء - - - Reboot - إعادة التشغيل - - - Confirm - تأكيد - - - Resetting device... -This may take up to a minute. - يتم إعادة ضبط الجهاز... -قد يستغرق الأمر حوالي الدقيقة. - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - غير قادر على تحميل جزء البيانات. قد يكون الجزء تالفاً. اضغط على تأكيد لمسح جهازك وإعادة ضبطه. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - تم تفعيل إعادة ضبط النظام. اضغط على تأكيد لمسح جميع المحتويات والإعدادات. اضغط على إلغاء لاستئناف التمهيد. - - - - SettingsWindow - - × - × - - - Device - الجهاز - - - Network - الشبكة - - - Toggles - المثبتتات - - - Software - البرنامج - - - - Setup - - WARNING: Low Voltage - تحذير: الجهد منخفض - - - Power your device in a car with a harness or proceed at your own risk. - شغل جهازك في السيارة عن طريق شرطان التوصيل، أو تابع على مسؤوليتك. - - - Power off - إيقاف التشغيل - - - Continue - متابعة - - - Getting Started - البدء - - - Before we get on the road, let’s finish installation and cover some details. - قبل أن ننطلق في الطريق، دعنا ننتهي من التثبيت ونغطي بعض التفاصيل. - - - Connect to Wi-Fi - الاتصال بشبكة الواي فاي - - - Back - السابق - - - Continue without Wi-Fi - المتابعة بدون شبكة الواي فاي - - - Waiting for internet - بانتظار الاتصال بالإنترنت - - - Enter URL - أدخل رابط URL - - - for Custom Software - للبرامج المخصصة - - - Downloading... - يتم الآن التنزيل... - - - Download Failed - فشل التنزيل - - - Ensure the entered URL is valid, and the device’s internet connection is good. - تأكد من أن رابط URL الذي أدخلته صالح، وأن اتصال الجهاز بالإنترنت جيد. - - - Reboot device - إعادة التشغيل - - - Start over - البدء من جديد - - - Something went wrong. Reboot the device. - حدث خطأ ما. أعد التشغيل الجهاز. - - - No custom software found at this URL. - لم يتم العثور على برنامج خاص لعنوان URL ها. - - - Select a language - اختر لغة - - - Choose Software to Install - اختر البرنامج للتثبيت - - - openpilot - openpilot - - - Custom Software - البرمجيات المخصصة - - - - SetupWidget - - Finish Setup - إنهاء الإعداد - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - اقرن جهازك بجهاز (connect.comma.ai) واحصل على عرضك من comma prime. - - - Pair device - اقتران الجهاز - - - - Sidebar - - CONNECT - الاتصال - - - OFFLINE - غير متصل - - - ONLINE - متصل - - - ERROR - خطأ - - - TEMP - درجة الحرارة - - - HIGH - مرتفع - - - GOOD - جيد - - - OK - موافق - - - VEHICLE - المركبة - - - NO - لا - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - UNINSTALL - إلغاء التثبيت - - - Uninstall %1 - إلغاء التثبيت %1 - - - Are you sure you want to uninstall? - هل أنت متأكد أنك تريد إلغاء التثبيت؟ - - - CHECK - التحقق - - - Updates are only downloaded while the car is off. - يتم تحميل التحديثات فقط عندما تكون السيارة متوقفة. - - - Current Version - النسخة الحالية - - - Download - تنزيل - - - Install Update - تثبيت التحديث - - - INSTALL - تثبيت - - - Target Branch - فرع الهدف - - - SELECT - اختيار - - - Select a branch - اختر فرعاً - - - Uninstall - إلغاء التثبيت - - - failed to check for update - فشل التحقق من التحديث - - - DOWNLOAD - تنزيل - - - update available - يتوفر تحديث - - - never - إطلاقاً - - - up to date, last checked %1 - أحدث نسخة، آخر تحقق %1 - - - - SshControl - - SSH Keys - مفاتيح SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - تنبيه: هذا يمنح SSH إمكانية الوصول إلى جميع المفاتيح العامة في إعدادات GitHub. لا تقم بإدخال اسم مستخدم GitHub بدلاً من اسمك. لن تطلب منك comma employee إطلاقاً أن تضيف اسم مستخدم GitHub الخاص بهم. - - - ADD - إضافة - - - Enter your GitHub username - ادخل اسم المستخدم GitHub الخاص بك - - - LOADING - يتم التحميل - - - REMOVE - إزالة - - - Username '%1' has no keys on GitHub - لا يحتوي اسم المستخدم '%1' أي مفاتيح على GitHub - - - Request timed out - انتهى وقت الطلب - - - Username '%1' doesn't exist on GitHub - اسم المستخدم '%1' غير موجود على GitHub - - - - SshToggle - - Enable SSH - تمكين SSH - - - - TermsPage - - Terms & Conditions - الشروط والأحكام - - - Decline - رفض - - - Scroll to accept - قم بالتمرير للقبول - - - Agree - أوافق - - - - TogglesPanel - - Enable openpilot - تمكين openpilot - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - استخدم نظام openpilot من أجل الضبط التكيفي للسرعة والحفاظ على مساعدة السائق للبقاء في المسار. انتباهك مطلوب في جميع الأوقات مع استخدام هذه الميزة. يعمل هذا التغيير في الإعدادات عند إيقاف تشغيل السيارة. - - - Enable Lane Departure Warnings - قم بتمكين تحذيرات مغادرة المسار - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - تلقي التنبيهات من أجل الالتفاف للعودة إلى المسار عندما تنحرف سيارتك فوق الخط المحدد للمسار دون تشغيل إشارة الانعطاف عند القيادة لمسافة تزيد عن 31 ميل/سا (50 كم/سا). - - - Use Metric System - استخدام النظام المتري - - - Display speed in km/h instead of mph. - عرض السرعة بواحدات كم/سا بدلاً من ميل/سا. - - - Record and Upload Driver Camera - تسجيل وتحميل كاميرا السائق - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - تحميل البيانات من الكاميرا المواجهة للسائق، والمساعدة في تحسين خوارزمية مراقبة السائق. - - - Disengage on Accelerator Pedal - فك الارتباط عن دواسة الوقود - - - When enabled, pressing the accelerator pedal will disengage openpilot. - عند تمكين هذه الميزة، فإن الضغط على دواسة الوقود سيؤدي إلى فك ارتباط openpilot. - - - openpilot Longitudinal Control (Alpha) - التحكم الطولي openpilot (ألفا) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - تحذير: التحكم الطولي في openpilot في المرحلة ألفا لهذه السيارة، وسيقوم بتعطيل مكابح الطوارئ الآلية (AEB). - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - في هذه السيارة يعمل openpilot افتراضياً بالشكل المدمج في التحكم التكيفي في السرعة بدلاً من التحكم الطولي. قم بتمكين هذا الخيار من أجل الانتقال إلى التحكم الطولي. يوصى بتمكين الوضع التجريبي عند استخدام وضع التحكم الطولي ألفا من openpilot. - - - Experimental Mode - الوضع التجريبي - - - Aggressive - الهجومي - - - Standard - القياسي - - - Relaxed - الراحة - - - Driving Personality - شخصية القيادة - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - يتم وضع openpilot بشكل قياسي في <b>وضعية الراحة</b>. يمكن الوضع التجريبي <b>ميزات المستوى ألفا</b> التي لا تكون جاهزة في وضع الراحة: - - - End-to-End Longitudinal Control - التحكم الطولي من طرف إلى طرف - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - دع نظام القيادة يتحكم بالوقود والمكابح. سيقوم openpilot بالقيادة كما لو أنه كائن بشري، بما في ذلك التوقف عند الإشارة الحمراء، وإشارات التوقف. وبما أن نمط القيادة يحدد سرعة القيادة، فإن السرعة المضبوطة تشكل الحد الأقصى فقط. هذه خاصية الجودة ألفا، فيجب توقع حدوث الأخطاء. - - - New Driving Visualization - تصور القيادة الديد - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - الوضع التجريبي غير متوفر حالياً في هذه السيارة نظراً لاستخدام رصيد التحكم التكيفي بالسرعة من أجل التحكم الطولي. - - - openpilot longitudinal control may come in a future update. - قد يتم الحصول على التحكم الطولي في openpilot في عمليات التحديث المستقبلية. - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - يمكن اختبار نسخة ألفا من التحكم الطولي من openpilot، مع الوضع التجريبي، لكن على الفروع غير المطلقة. - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - تمكين التحكم الطولي من openpilot (ألفا) للسماح بالوضع التجريبي. - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - يوصى بالمعيار. في الوضع العدواني، سيتبع الطيار المفتوح السيارات الرائدة بشكل أقرب ويكون أكثر عدوانية مع البنزين والفرامل. في الوضع المريح، سيبقى openpilot بعيدًا عن السيارات الرائدة. في السيارات المدعومة، يمكنك التنقل بين هذه الشخصيات باستخدام زر مسافة عجلة القيادة. - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - ستتحول واجهة القيادة إلى الكاميرا الواسعة المواجهة للطريق عند السرعات المنخفضة لعرض بعض المنعطفات بشكل أفضل. كما سيتم عرض شعار وضع التجريبي في الزاوية العلوية اليمنى. - - - Always-On Driver Monitoring - مراقبة السائق المستمرة - - - Enable driver monitoring even when openpilot is not engaged. - تمكين مراقبة السائق حتى عندما لا يكون نظام OpenPilot مُفعّلاً. - - - - Updater - - Update Required - التحديث مطلوب - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - تحديث نظام التشغيل مطلوب. قم بوصل جهازك بشبكة واي فاي من أجل تحديث أسرع. حجم التحميل حوالي 1 غيغا بايت تقريباً. - - - Connect to Wi-Fi - الاتصال بشبكة الواي فاي - - - Install - تثبيت - - - Back - السابق - - - Loading... - يتم التحميل... - - - Reboot - إعادة التشغيل - - - Update failed - فشل التحديث - - - - WiFiPromptWidget - - Setup Wi-Fi - إعداد شبكة الواي فاي - - - Connect to Wi-Fi to upload driving data and help improve openpilot - الاتصال بشبكة الواي فاي لتحميل بيانات القيادة والمساهمة في تحسين openpilot - - - Open Settings - فتح الإعدادات - - - Ready to upload - جاهز للتحميل - - - Training data will be pulled periodically while your device is on Wi-Fi - سيتم سحب بيانات التدريب دورياً عندما يكون جهازك متصل بشبكة واي فاي - - - - WifiUI - - Scanning for networks... - يتم البحث عن شبكات... - - - CONNECTING... - يتم الاتصال... - - - FORGET - نسيان هذه الشبكة - - - Forget Wi-Fi Network "%1"? - هل تريد نسيان شبكة الواي فاي "%1"؟ - - - Forget - نسيان - - - diff --git a/selfdrive/ui/translations/main_de.ts b/selfdrive/ui/translations/main_de.ts deleted file mode 100644 index 48180eef929944..00000000000000 --- a/selfdrive/ui/translations/main_de.ts +++ /dev/null @@ -1,1139 +0,0 @@ - - - - - AbstractAlert - - Close - Schließen - - - Snooze Update - Update pausieren - - - Reboot and Update - Aktualisieren und neu starten - - - - AdvancedNetworking - - Back - Zurück - - - Enable Tethering - Tethering aktivieren - - - Tethering Password - Tethering Passwort - - - EDIT - ÄNDERN - - - Enter new tethering password - Neues tethering Passwort eingeben - - - IP Address - IP Adresse - - - Enable Roaming - Roaming aktivieren - - - APN Setting - APN Einstellungen - - - Enter APN - APN eingeben - - - leave blank for automatic configuration - für automatische Konfiguration leer lassen - - - Cellular Metered - Getaktete Verbindung - - - Prevent large data uploads when on a metered connection - Hochladen großer Dateien über getaktete Verbindungen unterbinden - - - Hidden Network - - - - CONNECT - CONNECT - - - Enter SSID - SSID eingeben - - - Enter password - Passwort eingeben - - - for "%1" - für "%1" - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - - ConfirmationDialog - - Ok - Ok - - - Cancel - Abbrechen - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - Du musst die Nutzungsbedingungen akzeptieren, um Openpilot zu benutzen. - - - Back - Zurück - - - Decline, uninstall %1 - Ablehnen, deinstallieren %1 - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - Nicht verfügbar - - - Serial - Seriennummer - - - Driver Camera - Fahrerkamera - - - PREVIEW - VORSCHAU - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Vorschau der auf den Fahrer gerichteten Kamera, um sicherzustellen, dass die Fahrerüberwachung eine gute Sicht hat. (Fahrzeug muss aus sein) - - - Reset Calibration - Neu kalibrieren - - - RESET - RESET - - - Are you sure you want to reset calibration? - Bist du sicher, dass du die Kalibrierung zurücksetzen möchtest? - - - Review Training Guide - Trainingsanleitung wiederholen - - - REVIEW - TRAINING - - - Review the rules, features, and limitations of openpilot - Wiederhole die Regeln, Fähigkeiten und Limitierungen von Openpilot - - - Are you sure you want to review the training guide? - Bist du sicher, dass du die Trainingsanleitung wiederholen möchtest? - - - Regulatory - Rechtliche Hinweise - - - VIEW - ANSEHEN - - - Change Language - Sprache ändern - - - CHANGE - ÄNDERN - - - Select a language - Sprache wählen - - - Reboot - Neustart - - - Power Off - Ausschalten - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - Damit Openpilot funktioniert, darf die Installationsposition nicht mehr als 4° nach rechts/links, 5° nach oben und 9° nach unten abweichen. Openpilot kalibriert sich durchgehend, ein Zurücksetzen ist selten notwendig. - - - Your device is pointed %1° %2 and %3° %4. - Deine Geräteausrichtung ist %1° %2 und %3° %4. - - - down - unten - - - up - oben - - - left - links - - - right - rechts - - - Are you sure you want to reboot? - Bist du sicher, dass du das Gerät neu starten möchtest? - - - Disengage to Reboot - Für Neustart deaktivieren - - - Are you sure you want to power off? - Bist du sicher, dass du das Gerät ausschalten möchtest? - - - Disengage to Power Off - Zum Ausschalten deaktivieren - - - Reset - Zurücksetzen - - - Review - Überprüfen - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Koppele dein Gerät mit Comma Connect (connect.comma.ai) und sichere dir dein Comma Prime Angebot. - - - Pair Device - - - - PAIR - - - - - DriverViewWindow - - camera starting - Kamera startet - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - EXPERIMENTELLER MODUS AN - - - CHILL MODE ON - ENTSPANNTER MODUS AN - - - - InputDialog - - Cancel - Abbrechen - - - Need at least %n character(s)! - - Mindestens %n Buchstabe benötigt! - Mindestens %n Buchstaben benötigt! - - - - - Installer - - Installing... - Installiere... - - - - MultiOptionDialog - - Select - Auswählen - - - Cancel - Abbrechen - - - - Networking - - Advanced - Erweitert - - - Enter password - Passwort eingeben - - - for "%1" - für "%1" - - - Wrong password - Falsches Passwort - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - - - - Unable to download updates -%1 - - - - Taking camera snapshots. System won't start until finished. - - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - - - - NVMe drive not mounted. - - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - - - - - OffroadHome - - UPDATE - Aktualisieren - - - ALERTS - HINWEISE - - - ALERT - HINWEIS - - - - OnroadAlerts - - openpilot Unavailable - - - - Waiting for controls to start - - - - TAKE CONTROL IMMEDIATELY - - - - Controls Unresponsive - - - - Reboot Device - - - - - PairingPopup - - Pair your device to your comma account - Verbinde dein Gerät mit deinem comma Konto - - - Go to https://connect.comma.ai on your phone - Gehe zu https://connect.comma.ai auf deinem Handy - - - Click "add new device" and scan the QR code on the right - Klicke auf "neues Gerät hinzufügen" und scanne den QR code rechts - - - Bookmark connect.comma.ai to your home screen to use it like an app - Füge connect.comma.ai als Lesezeichen auf deinem Homescreen hinzu um es wie eine App zu verwenden - - - - ParamControl - - Cancel - Abbrechen - - - Enable - Aktivieren - - - - PrimeAdWidget - - Upgrade Now - Jetzt abonieren - - - Become a comma prime member at connect.comma.ai - Werde Comma Prime Mitglied auf connect.comma.ai - - - PRIME FEATURES: - PRIME FUNKTIONEN: - - - Remote access - Fernzugriff - - - 24/7 LTE connectivity - - - - 1 year of drive storage - - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ ABBONIERT - - - comma prime - comma prime - - - - QObject - - Reboot - Neustart - - - Exit - Verlassen - - - openpilot - openpilot - - - %n minute(s) ago - - vor %n Minute - vor %n Minuten - - - - %n hour(s) ago - - vor %n Stunde - vor %n Stunden - - - - %n day(s) ago - - vor %n Tag - vor %n Tagen - - - - now - - - - - Reset - - Reset failed. Reboot to try again. - Zurücksetzen fehlgeschlagen. Starte das Gerät neu und versuche es wieder. - - - Are you sure you want to reset your device? - Bist du sicher, dass du das Gerät auf Werkseinstellungen zurücksetzen möchtest? - - - System Reset - System auf Werkseinstellungen zurücksetzen - - - Cancel - Abbrechen - - - Reboot - Neustart - - - Confirm - Bestätigen - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - - - - Resetting device... -This may take up to a minute. - - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - - - - - SettingsWindow - - × - x - - - Device - Gerät - - - Network - Netzwerk - - - Toggles - Schalter - - - Software - Software - - - - Setup - - WARNING: Low Voltage - Warnung: Batteriespannung niedrig - - - Power your device in a car with a harness or proceed at your own risk. - Versorge dein Gerät über einen Kabelbaum im Auto mit Strom, oder fahre auf eigene Gefahr fort. - - - Power off - Ausschalten - - - Continue - Fortsetzen - - - Getting Started - Loslegen - - - Before we get on the road, let’s finish installation and cover some details. - Bevor wir uns auf die Straße begeben, lass uns die Installation fertigstellen und einige Details prüfen. - - - Connect to Wi-Fi - Mit WLAN verbinden - - - Back - Zurück - - - Continue without Wi-Fi - Ohne WLAN fortsetzen - - - Waiting for internet - Auf Internet warten - - - Enter URL - URL eingeben - - - for Custom Software - für spezifische Software - - - Downloading... - Herunterladen... - - - Download Failed - Herunterladen fehlgeschlagen - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Stelle sicher, dass die eingegebene URL korrekt ist und dein Gerät eine stabile Internetverbindung hat. - - - Reboot device - Gerät neustarten - - - Start over - Von neuem beginnen - - - No custom software found at this URL. - - - - Something went wrong. Reboot the device. - - - - Select a language - Sprache wählen - - - Choose Software to Install - - - - openpilot - openpilot - - - Custom Software - - - - - SetupWidget - - Finish Setup - Einrichtung beenden - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Koppele dein Gerät mit Comma Connect (connect.comma.ai) und sichere dir dein Comma Prime Angebot. - - - Pair device - Gerät koppeln - - - - Sidebar - - CONNECT - This is a brand/service name for comma connect, don't translate - CONNECT - - - OFFLINE - OFFLINE - - - ONLINE - ONLINE - - - ERROR - FEHLER - - - TEMP - TEMP - - - HIGH - HOCH - - - GOOD - GUT - - - OK - OK - - - VEHICLE - FAHRZEUG - - - NO - KEIN - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - WLAN - - - ETH - LAN - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - UNINSTALL - Too long for UI - DEINSTALL - - - Uninstall %1 - Deinstalliere %1 - - - Are you sure you want to uninstall? - Bist du sicher, dass du Openpilot entfernen möchtest? - - - CHECK - ÜBERPRÜFEN - - - Updates are only downloaded while the car is off. - Updates werden nur heruntergeladen, wenn das Auto aus ist. - - - Current Version - Aktuelle Version - - - Download - Download - - - Install Update - Update installieren - - - INSTALL - INSTALLIEREN - - - Target Branch - Ziel Branch - - - SELECT - AUSWÄHLEN - - - Select a branch - Wähle einen Branch - - - Uninstall - Deinstallieren - - - failed to check for update - - - - up to date, last checked %1 - - - - DOWNLOAD - - - - update available - - - - never - - - - - SshControl - - SSH Keys - SSH Schlüssel - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Warnung: Dies ermöglicht SSH zugriff für alle öffentlichen Schlüssel in deinen Github Einstellungen. Gib niemals einen anderen Benutzernamen, als deinen Eigenen an. Comma Angestellte fragen dich niemals danach ihren Github Benutzernamen hinzuzufügen. - - - ADD - HINZUFÜGEN - - - Enter your GitHub username - Gib deinen GitHub Benutzernamen ein - - - LOADING - LADEN - - - REMOVE - LÖSCHEN - - - Username '%1' has no keys on GitHub - Benutzername '%1' hat keine Schlüssel auf GitHub - - - Request timed out - Zeitüberschreitung der Anforderung - - - Username '%1' doesn't exist on GitHub - Benutzername '%1' existiert nicht auf GitHub - - - - SshToggle - - Enable SSH - SSH aktivieren - - - - TermsPage - - Terms & Conditions - Benutzungsbedingungen - - - Decline - Ablehnen - - - Scroll to accept - Scrolle herunter um zu akzeptieren - - - Agree - Zustimmen - - - - TogglesPanel - - Enable openpilot - Openpilot aktivieren - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Benutze das Openpilot System als adaptiven Tempomaten und Spurhalteassistenten. Deine Aufmerksamkeit ist jederzeit erforderlich, um diese Funktion zu nutzen. Diese Einstellung wird übernommen, wenn das Auto aus ist. - - - Enable Lane Departure Warnings - Spurverlassenswarnungen aktivieren - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Erhalte Warnungen, zurück in die Spur zu lenken, wenn dein Auto über eine erkannte Fahrstreifenmarkierung ohne aktivierten Blinker mit mehr als 50 km/h fährt. - - - Use Metric System - Benutze das metrische System - - - Display speed in km/h instead of mph. - Zeige die Geschwindigkeit in km/h anstatt von mph. - - - Record and Upload Driver Camera - Fahrerkamera aufnehmen und hochladen - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Lade Daten der Fahreraufmerksamkeitsüberwachungskamera hoch, um die Fahreraufmerksamkeitsüberwachungsalgorithmen zu verbessern. - - - When enabled, pressing the accelerator pedal will disengage openpilot. - Wenn aktiviert, deaktiviert sich Openpilot sobald das Gaspedal betätigt wird. - - - Experimental Mode - Experimenteller Modus - - - Disengage on Accelerator Pedal - Bei Gasbetätigung ausschalten - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - Openpilot fährt standardmäßig im <b>entspannten Modus</b>. Der Experimentelle Modus aktiviert<b>Alpha-level Funktionen</b>, die noch nicht für den entspannten Modus bereit sind. Die experimentellen Funktionen sind die Folgenden: - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - Lass das Fahrmodell Gas und Bremse kontrollieren. Openpilot wird so fahren, wie es dies von einem Menschen erwarten würde; inklusive des Anhaltens für Ampeln und Stoppschildern. Da das Fahrmodell entscheidet wie schnell es fährt stellt die gesetzte Geschwindigkeit lediglich das obere Limit dar. Dies ist ein Alpha-level Funktion. Fehler sind zu erwarten. - - - New Driving Visualization - Neue Fahrvisualisierung - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - Der experimentelle Modus ist momentan für dieses Auto nicht verfügbar da es den eingebauten adaptiven Tempomaten des Autos benutzt. - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - Aggressive - - - - Standard - - - - Relaxed - - - - Driving Personality - - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - End-to-End Longitudinal Control - - - - openpilot longitudinal control may come in a future update. - - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - - - - Always-On Driver Monitoring - - - - Enable driver monitoring even when openpilot is not engaged. - - - - - Updater - - Update Required - Aktualisierung notwendig - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Eine Aktualisierung des Betriebssystems ist notwendig. Verbinde dein Gerät mit WLAN für ein schnelleres Update. Die Download Größe ist ungefähr 1GB. - - - Connect to Wi-Fi - Mit WLAN verbinden - - - Install - Installieren - - - Back - Zurück - - - Loading... - Laden... - - - Reboot - Neustart - - - Update failed - Aktualisierung fehlgeschlagen - - - - WiFiPromptWidget - - Setup Wi-Fi - - - - Connect to Wi-Fi to upload driving data and help improve openpilot - - - - Open Settings - - - - Ready to upload - - - - Training data will be pulled periodically while your device is on Wi-Fi - - - - - WifiUI - - Scanning for networks... - Suche nach Netzwerken... - - - CONNECTING... - VERBINDEN... - - - FORGET - VERGESSEN - - - Forget Wi-Fi Network "%1"? - WLAN Netzwerk "%1" vergessen? - - - Forget - Vergessen - - - diff --git a/selfdrive/ui/translations/main_en.ts b/selfdrive/ui/translations/main_en.ts deleted file mode 100644 index 3f9692e5fa4850..00000000000000 --- a/selfdrive/ui/translations/main_en.ts +++ /dev/null @@ -1,38 +0,0 @@ - - - - - InputDialog - - Need at least %n character(s)! - - Need at least %n character! - Need at least %n characters! - - - - - QObject - - %n minute(s) ago - - %n minute ago - %n minutes ago - - - - %n hour(s) ago - - %n hour ago - %n hours ago - - - - %n day(s) ago - - %n day ago - %n days ago - - - - diff --git a/selfdrive/ui/translations/main_es.ts b/selfdrive/ui/translations/main_es.ts deleted file mode 100644 index 150c00d117a773..00000000000000 --- a/selfdrive/ui/translations/main_es.ts +++ /dev/null @@ -1,1139 +0,0 @@ - - - - - AbstractAlert - - Close - Cerrar - - - Snooze Update - Posponer Actualización - - - Reboot and Update - Reiniciar y Actualizar - - - - AdvancedNetworking - - Back - Volver - - - Enable Tethering - Activar Tether - - - Tethering Password - Contraseña de Tethering - - - EDIT - EDITAR - - - Enter new tethering password - Nueva contraseña de tethering - - - IP Address - Dirección IP - - - Enable Roaming - Activar Roaming - - - APN Setting - Configuración de APN - - - Enter APN - Insertar APN - - - leave blank for automatic configuration - dejar en blanco para configuración automática - - - Cellular Metered - Plano de datos limitado - - - Prevent large data uploads when on a metered connection - Evitar grandes descargas de datos cuando tenga una conexión limitada - - - Hidden Network - Red Oculta - - - CONNECT - CONECTAR - - - Enter SSID - Ingrese SSID - - - Enter password - Ingrese contraseña - - - for "%1" - para "%1" - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - - ConfirmationDialog - - Ok - OK - - - Cancel - Cancelar - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - Debe aceptar los términos y condiciones para poder utilizar openpilot. - - - Back - Atrás - - - Decline, uninstall %1 - Rechazar, desinstalar %1 - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - N/A - - - Serial - Serial - - - Pair Device - Emparejar Dispositivo - - - PAIR - EMPAREJAR - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Empareja tu dispositivo con comma connect (connect.comma.ai) y reclama tu oferta de comma prime. - - - Driver Camera - Cámara del conductor - - - PREVIEW - VISUALIZAR - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Previsualizar la cámara del conductor para garantizar que la monitorización del sistema tenga buena visibilidad (el vehículo tiene que estar apagado) - - - Reset Calibration - Formatear Calibración - - - RESET - REINICIAR - - - Are you sure you want to reset calibration? - ¿Seguro que quiere formatear la calibración? - - - Reset - Formatear - - - Review Training Guide - Revisar la Guía de Entrenamiento - - - REVIEW - REVISAR - - - Review the rules, features, and limitations of openpilot - Revisar las reglas, características y limitaciones de openpilot - - - Are you sure you want to review the training guide? - ¿Seguro que quiere revisar la guía de entrenamiento? - - - Review - Revisar - - - Regulatory - Regulador - - - VIEW - VER - - - Change Language - Cambiar Idioma - - - CHANGE - CAMBIAR - - - Select a language - Seleccione el idioma - - - Reboot - Reiniciar - - - Power Off - Apagar - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot requiere que el dispositivo sea montado entre 4° grados a la izquierda o derecha y entre 5° grados hacia arriba o 9° grados hacia abajo. openpilot está constantemente en calibración, formatear rara vez es necesario. - - - Your device is pointed %1° %2 and %3° %4. - Su dispositivo está apuntando %1° %2 y %3° %4. - - - down - abajo - - - up - arriba - - - left - izquierda - - - right - derecha - - - Are you sure you want to reboot? - ¿Seguro qué quiere reiniciar? - - - Disengage to Reboot - Desactivar para Reiniciar - - - Are you sure you want to power off? - ¿Seguro qué quiere apagar? - - - Disengage to Power Off - Desactivar para apagar - - - - DriverViewWindow - - camera starting - iniciando cámara - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - MODO EXPERIMENTAL - - - CHILL MODE ON - MODO CHILL - - - - InputDialog - - Cancel - Cancelar - - - Need at least %n character(s)! - - ¡Necesita mínimo %n caracter! - ¡Necesita mínimo %n caracteres! - - - - - Installer - - Installing... - Instalando... - - - - MultiOptionDialog - - Select - Seleccionar - - - Cancel - Cancelar - - - - Networking - - Advanced - Avanzado - - - Enter password - Ingresar contraseña - - - for "%1" - para "%1" - - - Wrong password - Contraseña incorrecta - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - La temperatura del dispositivo es muy alta. El sistema se está enfriando antes de iniciar. Temperatura actual del componente interno: %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - Conéctese inmediatamente al internet para buscar actualizaciones. Si no se conecta al internet, openpilot no iniciará en %1 - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - Conectese al internet para buscar actualizaciones. openpilot no iniciará automáticamente hasta conectarse al internet para buscar actualizaciones. - - - Unable to download updates -%1 - Incapaz de descargar actualizaciones. -%1 - - - Taking camera snapshots. System won't start until finished. - Tomando capturas de las cámaras. El sistema no se iniciará hasta que finalice. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - Se está descargando una actualización del sistema operativo de su dispositivo en segundo plano. Se le pedirá que actualice cuando esté listo para instalarse. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - El dispositivo no pudo registrarse. No se conectará ni subirá datos a los servidores de comma.ai y no recibe soporte de comma.ai. Si este es un dispositivo oficial, visite https://comma.ai/support. - - - NVMe drive not mounted. - Unidad NVMe no montada. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - Se detectó una unidad NVMe incompatible. El dispositivo puede consumir mucha más energía y sobrecalentarse debido a esto. - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - openpilot no pudo identificar su automóvil. Su automóvil no es compatible o no se reconocen sus ECU. Por favor haga un pull request para agregar las versiones de firmware del vehículo adecuado. ¿Necesita ayuda? Únase a discord.comma.ai. - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - openpilot no pudo identificar su automóvil. Verifique la integridad de los cables y asegúrese de que todas las conexiones estén seguras, en particular que el comma power esté completamente insertado en el puerto OBD-II del vehículo. ¿Necesita ayuda? Únase discord.comma.ai. - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - openpilot detectó un cambio en la posición de montaje del dispositivo. Asegúrese de que el dispositivo esté completamente asentado en el soporte y que el soporte esté firmemente asegurado al parabrisas. - - - - OffroadHome - - UPDATE - ACTUALIZAR - - - ALERTS - ALERTAS - - - ALERT - ALERTA - - - - OnroadAlerts - - openpilot Unavailable - openpilot no disponible - - - Waiting for controls to start - Esperando que los controles inicien - - - TAKE CONTROL IMMEDIATELY - TOME CONTROL INMEDIATAMENTE - - - Controls Unresponsive - Controles no responden - - - Reboot Device - Reiniciar Dispositivo - - - - PairingPopup - - Pair your device to your comma account - Empareje su dispositivo con su cuenta de comma - - - Go to https://connect.comma.ai on your phone - Vaya a https://connect.comma.ai en su teléfono - - - Click "add new device" and scan the QR code on the right - Seleccione "agregar nuevo dispositivo" y escanee el código QR a la derecha - - - Bookmark connect.comma.ai to your home screen to use it like an app - Añada connect.comma.ai a su pantalla de inicio para usarlo como una aplicación - - - - ParamControl - - Enable - Activar - - - Cancel - Cancelar - - - - PrimeAdWidget - - Upgrade Now - Actualizar Ahora - - - Become a comma prime member at connect.comma.ai - Hazte miembro de comma prime en connect.comma.ai - - - PRIME FEATURES: - BENEFICIOS PRIME: - - - Remote access - Acceso remoto - - - 24/7 LTE connectivity - Conectividad LTE 24/7 - - - 1 year of drive storage - 1 año de almacenamiento - - - Remote snapshots - Capturas remotas - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ SUSCRITO - - - comma prime - comma prime - - - - QObject - - Reboot - Reiniciar - - - Exit - Salir - - - openpilot - openpilot - - - now - ahora - - - %n minute(s) ago - - hace %n min - hace %n mins - - - - %n hour(s) ago - - hace %n hora - hace %n horas - - - - %n day(s) ago - - hace %n día - hace %n días - - - - - Reset - - Reset failed. Reboot to try again. - Formateo fallido. Reinicie para reintentar. - - - Resetting device... -This may take up to a minute. - formateando dispositivo... -Esto puede tardar un minuto. - - - Are you sure you want to reset your device? - ¿Seguro que quiere formatear su dispositivo? - - - System Reset - Formatear Sistema - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Formateo del sistema activado. Presione confirmar para borrar todo el contenido y la configuración. Presione cancelar para reanudar el inicio. - - - Cancel - Cancelar - - - Reboot - Reiniciar - - - Confirm - Confirmar - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - No es posible montar una partición de datos. La partición podría estar corrompida. Confirme para borrar y formatear su dispositivo. - - - - SettingsWindow - - × - × - - - Device - Dispositivo - - - Network - Red - - - Toggles - Ajustes - - - Software - Software - - - - Setup - - Something went wrong. Reboot the device. - Algo ha ido mal. Reinicie el dispositivo. - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Asegúrese de que la URL insertada es válida y que el dispositivo tiene buena conexión. - - - No custom software found at this URL. - No encontramos software personalizado en esta URL. - - - WARNING: Low Voltage - ALERTA: Voltaje bajo - - - Power your device in a car with a harness or proceed at your own risk. - Encienda su dispositivo en un auto con el arnés o proceda bajo su propio riesgo. - - - Power off - Apagar - - - Continue - Continuar - - - Getting Started - Comenzando - - - Before we get on the road, let’s finish installation and cover some details. - Antes de ponernos en marcha, terminemos la instalación y cubramos algunos detalles. - - - Connect to Wi-Fi - Conectarse al Wi-Fi - - - Back - Volver - - - Continue without Wi-Fi - Continuar sin Wi-Fi - - - Waiting for internet - Esperando conexión a internet - - - Choose Software to Install - Elija el software a instalar - - - openpilot - openpilot - - - Custom Software - Software personalizado - - - Enter URL - Insertar URL - - - for Custom Software - para Software personalizado - - - Downloading... - Descargando... - - - Download Failed - Descarga fallida - - - Reboot device - Reiniciar Dispositivo - - - Start over - Comenzar de nuevo - - - Select a language - Seleccione un idioma - - - - SetupWidget - - Finish Setup - Terminar configuración - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Empareje su dispositivo con comma connect (connect.comma.ai) y reclame su oferta de comma prime. - - - Pair device - Emparejar dispositivo - - - - Sidebar - - CONNECT - CONNECT - - - OFFLINE - OFFLINE - - - ONLINE - EN LÍNEA - - - ERROR - ERROR - - - TEMP - TEMP - - - HIGH - ALTA - - - GOOD - BUENA - - - OK - OK - - - VEHICLE - VEHÍCULO - - - NO - SIN - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - Actualizaciones solo se descargan con el auto apagado. - - - Current Version - Versión Actual - - - Download - Descargar - - - CHECK - VERIFICAR - - - Install Update - Actualizar - - - INSTALL - INSTALAR - - - Target Branch - Rama objetivo - - - SELECT - SELECCIONAR - - - Select a branch - Selecione una rama - - - Uninstall %1 - Desinstalar %1 - - - UNINSTALL - DESINSTALAR - - - Are you sure you want to uninstall? - ¿Seguro qué desea desinstalar? - - - Uninstall - Desinstalar - - - failed to check for update - no se pudo buscar actualizaciones - - - DOWNLOAD - DESCARGAR - - - update available - actualización disponible - - - never - nunca - - - up to date, last checked %1 - actualizado, último chequeo %1 - - - - SshControl - - SSH Keys - Clave SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Aviso: Esto otorga acceso SSH a todas las claves públicas en su Github. Nunca ingrese un nombre de usuario de Github que no sea suyo. Un empleado de comma NUNCA le pedirá que añada un usuario de Github que no sea el suyo. - - - ADD - AÑADIR - - - Enter your GitHub username - Ingrese su usuario de GitHub - - - LOADING - CARGANDO - - - REMOVE - ELIMINAR - - - Username '%1' has no keys on GitHub - El usuario "%1” no tiene claves en GitHub - - - Request timed out - Solicitud expirada - - - Username '%1' doesn't exist on GitHub - El usuario '%1' no existe en Github - - - - SshToggle - - Enable SSH - Habilitar SSH - - - - TermsPage - - Terms & Conditions - Términos & Condiciones - - - Decline - Rechazar - - - Scroll to accept - Desliza para aceptar - - - Agree - Aceptar - - - - TogglesPanel - - Enable openpilot - Activar openpilot - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Utilice el sistema openpilot para acceder a un autocrucero adaptativo y asistencia al conductor para mantenerse en el carril. Se requiere su atención en todo momento para utilizar esta función. Cambiar esta configuración solo tendrá efecto con el auto apagado. - - - openpilot Longitudinal Control (Alpha) - Control longitudinal de openpilot (fase experimental) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - AVISO: el control longitudinal de openpilot está en fase experimental para este automóvil y desactivará el Frenado Automático de Emergencia (AEB). - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - En este automóvil, openpilot se configura de manera predeterminada con el Autocrucero Adaptativo (ACC) incorporado en el automóvil en lugar del control longitudinal de openpilot. Habilita esta opción para cambiar al control longitudinal de openpilot. Se recomienda activar el modo experimental al habilitar el control longitudinal de openpilot (aún en fase experimental). - - - Experimental Mode - Modo Experimental - - - Disengage on Accelerator Pedal - Desactivar con el Acelerador - - - When enabled, pressing the accelerator pedal will disengage openpilot. - Cuando esté activado, presionar el acelerador deshabilitará openpilot. - - - Enable Lane Departure Warnings - Activar Avisos de Salida de Carril - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Recibir alertas para volver al carril cuando su vehículo se salga fuera del carril sin que esté activada la señal de giro y esté conduciendo por encima de 50 km/h (31 mph). - - - Always-On Driver Monitoring - Monitoreo Permanente del Conductor - - - Enable driver monitoring even when openpilot is not engaged. - Habilitar el monitoreo del conductor incluso cuando Openpilot no esté activado. - - - Record and Upload Driver Camera - Grabar y Subir Cámara del Conductor - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Subir datos de la cámara del conductor para ayudar a mejorar el algoritmo de monitoreo del conductor. - - - Use Metric System - Usar Sistema Métrico - - - Display speed in km/h instead of mph. - Mostrar velocidad en km/h en vez de mph. - - - Aggressive - Agresivo - - - Standard - Estándar - - - Relaxed - Relajado - - - Driving Personality - Personalidad de conducción - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - Se recomienda el modo estándar. En el modo agresivo, openpilot seguirá más cerca a los autos delante suyo y será más agresivo con el acelerador y el freno. En modo relajado, openpilot se mantendrá más alejado de los autos delante suyo. En automóviles compatibles, puede recorrer estas personalidades con el botón de distancia del volante. - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - openpilot por defecto conduce en <b>modo chill</b>. El modo Experimental activa <b>funcionalidades en fase experimental</b>, que no están listas para el modo chill. Las funcionalidades del modo expeimental están listados abajo: - - - End-to-End Longitudinal Control - Control Longitudinal de Punta a Punta - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - Dajar que el modelo de conducción controle la aceleración y el frenado. openpilot conducirá como piensa que lo haría una persona, incluiyendo parar en los semáforos en rojo y las señales de alto. Dado que el modelo decide la velocidad de conducción, la velocidad de crucero establecida solo actuará como el límite superior. Este recurso aún está en fase experimental; deberían esperarse errores. - - - New Driving Visualization - Nueva Visualización de la conducción - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - La visualización de la conducción cambiará a la cámara que enfoca la carretera a velocidades bajas para mostrar mejor los giros. El logo del modo experimental también se mostrará en la esquina superior derecha. - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - El modo Experimental no está disponible actualmente para este auto, ya que el ACC default del auto está siendo usado para el control longitudinal. - - - openpilot longitudinal control may come in a future update. - El control longitudinal de openpilot podrá llegar en futuras actualizaciones. - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - Se puede probar una versión experimental del control longitudinal openpilot, junto con el modo Experimental, en ramas no liberadas. - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - Activar el control longitudinal (fase experimental) para permitir el modo Experimental. - - - - Updater - - Update Required - Actualización Requerida - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Es necesario la actualización del sistema operativo. Conecte su dispositivo al Wi-Fi para una actualización rápida. El tamaño de descarga es de aproximadamente 1GB. - - - Connect to Wi-Fi - Conectarse a la Wi-Fi - - - Install - Instalar - - - Back - Volver - - - Loading... - Cargando... - - - Reboot - Reiniciar - - - Update failed - Actualización fallida - - - - WiFiPromptWidget - - Setup Wi-Fi - Configurar Wi-Fi - - - Connect to Wi-Fi to upload driving data and help improve openpilot - Conectarse al Wi-Fi para subir los datos de conducción y mejorar openpilot - - - Open Settings - Abrir Configuraciones - - - Ready to upload - Listo para subir - - - Training data will be pulled periodically while your device is on Wi-Fi - Los datos de entrenamiento se extraerán periódicamente mientras tu dispositivo esté conectado a Wi-Fi - - - - WifiUI - - Scanning for networks... - Buscando redes... - - - CONNECTING... - CONECTANDO... - - - FORGET - OLVIDAR - - - Forget Wi-Fi Network "%1"? - ¿Olvidar la Red de Wi-Fi "%1"? - - - Forget - Olvidar - - - diff --git a/selfdrive/ui/translations/main_fr.ts b/selfdrive/ui/translations/main_fr.ts deleted file mode 100644 index a678742f74b975..00000000000000 --- a/selfdrive/ui/translations/main_fr.ts +++ /dev/null @@ -1,1139 +0,0 @@ - - - - - AbstractAlert - - Close - Fermer - - - Snooze Update - Reporter la mise à jour - - - Reboot and Update - Redémarrer et mettre à jour - - - - AdvancedNetworking - - Back - Retour - - - Enable Tethering - Activer le partage de connexion - - - Tethering Password - Mot de passe du partage de connexion - - - EDIT - MODIFIER - - - Enter new tethering password - Entrez le nouveau mot de passe du partage de connexion - - - IP Address - Adresse IP - - - Enable Roaming - Activer l'itinérance - - - APN Setting - Paramètre APN - - - Enter APN - Entrer le nom du point d'accès - - - leave blank for automatic configuration - laisser vide pour une configuration automatique - - - Cellular Metered - Connexion cellulaire limitée - - - Prevent large data uploads when on a metered connection - Éviter les transferts de données importants sur une connexion limitée - - - Hidden Network - Réseau Caché - - - CONNECT - CONNECTER - - - Enter SSID - Entrer le SSID - - - Enter password - Entrer le mot de passe - - - for "%1" - pour "%1" - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mi/h - - - MAX - MAX - - - - ConfirmationDialog - - Ok - Ok - - - Cancel - Annuler - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - Vous devez accepter les conditions générales pour utiliser openpilot. - - - Back - Retour - - - Decline, uninstall %1 - Refuser, désinstaller %1 - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - N/A - - - Serial - N° de série - - - Driver Camera - Caméra conducteur - - - PREVIEW - APERÇU - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Aperçu de la caméra orientée vers le conducteur pour assurer une bonne visibilité de la surveillance du conducteur. (véhicule doit être éteint) - - - Reset Calibration - Réinitialiser la calibration - - - RESET - RÉINITIALISER - - - Are you sure you want to reset calibration? - Êtes-vous sûr de vouloir réinitialiser la calibration ? - - - Reset - Réinitialiser - - - Review Training Guide - Revoir le guide de formation - - - REVIEW - REVOIR - - - Review the rules, features, and limitations of openpilot - Revoir les règles, fonctionnalités et limitations d'openpilot - - - Are you sure you want to review the training guide? - Êtes-vous sûr de vouloir revoir le guide de formation ? - - - Review - Revoir - - - Regulatory - Réglementaire - - - VIEW - VOIR - - - Change Language - Changer de langue - - - CHANGE - CHANGER - - - Select a language - Choisir une langue - - - Reboot - Redémarrer - - - Power Off - Éteindre - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot nécessite que l'appareil soit monté à 4° à gauche ou à droite et à 5° vers le haut ou 9° vers le bas. openpilot se calibre en continu, la réinitialisation est rarement nécessaire. - - - Your device is pointed %1° %2 and %3° %4. - Votre appareil est orienté %1° %2 et %3° %4. - - - down - bas - - - up - haut - - - left - gauche - - - right - droite - - - Are you sure you want to reboot? - Êtes-vous sûr de vouloir redémarrer ? - - - Disengage to Reboot - Désengager pour redémarrer - - - Are you sure you want to power off? - Êtes-vous sûr de vouloir éteindre ? - - - Disengage to Power Off - Désengager pour éteindre - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Associez votre appareil avec comma connect (connect.comma.ai) et profitez de l'offre comma prime. - - - Pair Device - - - - PAIR - - - - - DriverViewWindow - - camera starting - démarrage de la caméra - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - MODE EXPÉRIMENTAL ACTIVÉ - - - CHILL MODE ON - MODE DÉTENTE ACTIVÉ - - - - InputDialog - - Cancel - Annuler - - - Need at least %n character(s)! - - Besoin d'au moins %n caractère ! - Besoin d'au moins %n caractères ! - - - - - Installer - - Installing... - Installation... - - - - MultiOptionDialog - - Select - Sélectionner - - - Cancel - Annuler - - - - Networking - - Advanced - Avancé - - - Enter password - Entrer le mot de passe - - - for "%1" - pour "%1" - - - Wrong password - Mot de passe incorrect - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - Température de l'appareil trop élevée. Le système doit refroidir avant de démarrer. Température actuelle de l'appareil : %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - Connectez-vous immédiatement à internet pour vérifier les mises à jour. Si vous ne vous connectez pas à internet, openpilot ne s'engagera pas dans %1 - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - Connectez l'appareil à internet pour vérifier les mises à jour. openpilot ne démarrera pas automatiquement tant qu'il ne se connecte pas à internet pour vérifier les mises à jour. - - - Unable to download updates -%1 - Impossible de télécharger les mises à jour -%1 - - - Taking camera snapshots. System won't start until finished. - Capture de clichés photo. Le système ne démarrera pas tant qu'il n'est pas terminé. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - Une mise à jour du système d'exploitation de votre appareil est en cours de téléchargement en arrière-plan. Vous serez invité à effectuer la mise à jour lorsqu'elle sera prête à être installée. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - L'appareil n'a pas réussi à s'enregistrer. Il ne se connectera pas aux serveurs de comma.ai, n'enverra rien et ne recevra aucune assistance de comma.ai. S'il s'agit d'un appareil officiel, visitez https://comma.ai/support. - - - NVMe drive not mounted. - Le disque NVMe n'est pas monté. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - Disque NVMe non supporté détecté. L'appareil peut consommer beaucoup plus d'énergie et surchauffer en raison du NVMe non supporté. - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - openpilot n'a pas pu identifier votre voiture. Votre voiture n'est pas supportée ou ses ECUs ne sont pas reconnues. Veuillez soumettre un pull request pour ajouter les versions de firmware au véhicule approprié. Besoin d'aide ? Rejoignez discord.comma.ai. - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - openpilot n'a pas pu identifier votre voiture. Vérifiez l'intégrité des câbles et assurez-vous que toutes les connexions sont correctes, en particulier l'alimentation du comma est totalement insérée dans le port OBD-II du véhicule. Besoin d'aide ? Rejoignez discord.comma.ai. - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - openpilot a détecté un changement dans la position de montage de l'appareil. Assurez-vous que l'appareil est totalement inséré dans le support et que le support est fermement fixé au pare-brise. - - - - OffroadHome - - UPDATE - MISE À JOUR - - - ALERTS - ALERTES - - - ALERT - ALERTE - - - - OnroadAlerts - - openpilot Unavailable - - - - Waiting for controls to start - - - - TAKE CONTROL IMMEDIATELY - - - - Controls Unresponsive - - - - Reboot Device - - - - - PairingPopup - - Pair your device to your comma account - Associez votre appareil à votre compte comma - - - Go to https://connect.comma.ai on your phone - Allez sur https://connect.comma.ai sur votre téléphone - - - Click "add new device" and scan the QR code on the right - Cliquez sur "ajouter un nouvel appareil" et scannez le code QR à droite - - - Bookmark connect.comma.ai to your home screen to use it like an app - Ajoutez connect.comma.ai à votre écran d'accueil pour l'utiliser comme une application - - - - ParamControl - - Enable - Activer - - - Cancel - Annuler - - - - PrimeAdWidget - - Upgrade Now - Mettre à niveau - - - Become a comma prime member at connect.comma.ai - Devenez membre comma prime sur connect.comma.ai - - - PRIME FEATURES: - FONCTIONNALITÉS PRIME : - - - Remote access - Accès à distance - - - 24/7 LTE connectivity - Connexion LTE 24/7 - - - 1 year of drive storage - 1 an de stockage de trajets - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ ABONNÉ - - - comma prime - comma prime - - - - QObject - - Reboot - Redémarrer - - - Exit - Quitter - - - openpilot - openpilot - - - %n minute(s) ago - - il y a %n minute - il y a %n minutes - - - - %n hour(s) ago - - il y a %n heure - il y a %n heures - - - - %n day(s) ago - - il y a %n jour - il y a %n jours - - - - now - - - - - Reset - - Reset failed. Reboot to try again. - Réinitialisation échouée. Redémarrez pour réessayer. - - - Resetting device... -This may take up to a minute. - Réinitialisation de l'appareil... -Cela peut prendre jusqu'à une minute. - - - Are you sure you want to reset your device? - Êtes-vous sûr de vouloir réinitialiser votre appareil ? - - - System Reset - Réinitialisation du système - - - Cancel - Annuler - - - Reboot - Redémarrer - - - Confirm - Confirmer - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - Impossible de monter la partition data. La partition peut être corrompue. Appuyez sur confirmer pour effacer et réinitialiser votre appareil. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - - - - - SettingsWindow - - × - × - - - Device - Appareil - - - Network - Réseau - - - Toggles - Options - - - Software - Logiciel - - - - Setup - - Something went wrong. Reboot the device. - Un problème est survenu. Redémarrez l'appareil. - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Assurez-vous que l'URL saisie est valide et que la connexion internet de l'appareil est bonne. - - - No custom software found at this URL. - Aucun logiciel personnalisé trouvé à cette URL. - - - WARNING: Low Voltage - ATTENTION : Tension faible - - - Power your device in a car with a harness or proceed at your own risk. - Alimentez votre appareil dans une voiture avec un harness ou continuez à vos risques et périls. - - - Power off - Éteindre - - - Continue - Continuer - - - Getting Started - Commencer - - - Before we get on the road, let’s finish installation and cover some details. - Avant de prendre la route, terminons l'installation et passons en revue quelques détails. - - - Connect to Wi-Fi - Se connecter au Wi-Fi - - - Back - Retour - - - Enter URL - Entrer l'URL - - - for Custom Software - pour logiciel personnalisé - - - Continue without Wi-Fi - Continuer sans Wi-Fi - - - Waiting for internet - En attente d'internet - - - Downloading... - Téléchargement... - - - Download Failed - Échec du téléchargement - - - Reboot device - Redémarrer l'appareil - - - Start over - Recommencer - - - Select a language - Choisir une langue - - - Choose Software to Install - - - - openpilot - openpilot - - - Custom Software - - - - - SetupWidget - - Finish Setup - Terminer l'installation - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Associez votre appareil avec comma connect (connect.comma.ai) et profitez de l'offre comma prime. - - - Pair device - Associer l'appareil - - - - Sidebar - - CONNECT - CONNECTER - - - OFFLINE - HORS LIGNE - - - ONLINE - EN LIGNE - - - ERROR - ERREUR - - - TEMP - TEMP - - - HIGH - HAUT - - - GOOD - BON - - - OK - OK - - - VEHICLE - VÉHICULE - - - NO - NON - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - Les MàJ sont téléchargées uniquement si la voiture est éteinte. - - - Current Version - Version actuelle - - - Download - Télécharger - - - CHECK - VÉRIFIER - - - Install Update - Installer la mise à jour - - - INSTALL - INSTALLER - - - Target Branch - Branche cible - - - SELECT - SÉLECTIONNER - - - Select a branch - Sélectionner une branche - - - Uninstall %1 - Désinstaller %1 - - - UNINSTALL - DÉSINSTALLER - - - Are you sure you want to uninstall? - Êtes-vous sûr de vouloir désinstaller ? - - - Uninstall - Désinstaller - - - failed to check for update - échec de la vérification de la mise à jour - - - DOWNLOAD - TÉLÉCHARGER - - - update available - mise à jour disponible - - - never - jamais - - - up to date, last checked %1 - à jour, dernière vérification %1 - - - - SshControl - - SSH Keys - Clés SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Attention : Ceci accorde l'accès SSH à toutes les clés publiques de vos paramètres GitHub. N'entrez jamais un nom d'utilisateur GitHub autre que le vôtre. Un employé de comma ne vous demandera JAMAIS d'ajouter son nom d'utilisateur GitHub. - - - ADD - AJOUTER - - - Enter your GitHub username - Entrez votre nom d'utilisateur GitHub - - - LOADING - CHARGEMENT - - - REMOVE - SUPPRIMER - - - Username '%1' has no keys on GitHub - L'utilisateur '%1' n'a pas de clés sur GitHub - - - Request timed out - Délai de la demande dépassé - - - Username '%1' doesn't exist on GitHub - L'utilisateur '%1' n'existe pas sur GitHub - - - - SshToggle - - Enable SSH - Activer SSH - - - - TermsPage - - Terms & Conditions - Termes & Conditions - - - Decline - Refuser - - - Scroll to accept - Faire défiler pour accepter - - - Agree - Accepter - - - - TogglesPanel - - Enable openpilot - Activer openpilot - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Utilisez le système openpilot pour le régulateur de vitesse adaptatif et l'assistance au maintien de voie. Votre attention est requise en permanence pour utiliser cette fonctionnalité. La modification de ce paramètre prend effet lorsque la voiture est éteinte. - - - openpilot Longitudinal Control (Alpha) - Contrôle longitudinal openpilot (Alpha) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - ATTENTION : le contrôle longitudinal openpilot est en alpha pour cette voiture et désactivera le freinage d'urgence automatique (AEB). - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - Sur cette voiture, openpilot utilise par défaut le régulateur de vitesse adaptatif intégré à la voiture plutôt que le contrôle longitudinal d'openpilot. Activez ceci pour passer au contrôle longitudinal openpilot. Il est recommandé d'activer le mode expérimental lors de l'activation du contrôle longitudinal openpilot alpha. - - - Experimental Mode - Mode expérimental - - - Disengage on Accelerator Pedal - Désengager avec la pédale d'accélérateur - - - When enabled, pressing the accelerator pedal will disengage openpilot. - Lorsqu'il est activé, appuyer sur la pédale d'accélérateur désengagera openpilot. - - - Enable Lane Departure Warnings - Activer les avertissements de sortie de voie - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Recevez des alertes pour revenir dans la voie lorsque votre véhicule dérive au-delà d'une ligne de voie détectée sans clignotant activé en roulant à plus de 31 mph (50 km/h). - - - Record and Upload Driver Camera - Enregistrer et télécharger la caméra conducteur - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Publiez les données de la caméra orientée vers le conducteur et aidez à améliorer l'algorithme de surveillance du conducteur. - - - Use Metric System - Utiliser le système métrique - - - Display speed in km/h instead of mph. - Afficher la vitesse en km/h au lieu de mph. - - - Aggressive - Aggressif - - - Standard - Standard - - - Relaxed - Détendu - - - Driving Personality - Personnalité de conduite - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - Par défaut, openpilot conduit en <b>mode détente</b>. Le mode expérimental permet d'activer des <b>fonctionnalités alpha</b> qui ne sont pas prêtes pour le mode détente. Les fonctionnalités expérimentales sont listées ci-dessous : - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - Laissez le modèle de conduite contrôler l'accélérateur et les freins. openpilot conduira comme il pense qu'un humain le ferait, y compris s'arrêter aux feux rouges et aux panneaux stop. Comme le modèle de conduite décide de la vitesse à adopter, la vitesse définie ne servira que de limite supérieure. Cette fonctionnalité est de qualité alpha ; des erreurs sont à prévoir. - - - New Driving Visualization - Nouvelle visualisation de la conduite - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - Le mode expérimental est actuellement indisponible pour cette voiture car le régulateur de vitesse adaptatif d'origine est utilisé pour le contrôle longitudinal. - - - openpilot longitudinal control may come in a future update. - Le contrôle longitudinal openpilot pourrait être disponible dans une future mise à jour. - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - Une version alpha du contrôle longitudinal openpilot peut être testée, avec le mode expérimental, sur des branches non publiées. - - - End-to-End Longitudinal Control - Contrôle longitudinal de bout en bout - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - Activer le contrôle longitudinal d'openpilot (en alpha) pour autoriser le mode expérimental. - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - La visualisation de la conduite passera sur la caméra grand angle dirigée vers la route à faible vitesse afin de mieux montrer certains virages. Le logo du mode expérimental s'affichera également dans le coin supérieur droit. - - - Always-On Driver Monitoring - - - - Enable driver monitoring even when openpilot is not engaged. - - - - - Updater - - Update Required - Mise à jour requise - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Une mise à jour du système d'exploitation est requise. Connectez votre appareil au Wi-Fi pour une mise à jour plus rapide. La taille du téléchargement est d'environ 1 Go. - - - Connect to Wi-Fi - Se connecter au Wi-Fi - - - Install - Installer - - - Back - Retour - - - Loading... - Chargement... - - - Reboot - Redémarrer - - - Update failed - Échec de la mise à jour - - - - WiFiPromptWidget - - Setup Wi-Fi - Configurer Wi-Fi - - - Connect to Wi-Fi to upload driving data and help improve openpilot - Connectez-vous au Wi-Fi pour publier les données de conduite et aider à améliorer openpilot - - - Open Settings - Ouvrir les paramètres - - - Ready to upload - Prêt à uploader - - - Training data will be pulled periodically while your device is on Wi-Fi - Les données d'entraînement seront envoyées périodiquement lorsque votre appareil est connecté au réseau Wi-Fi - - - - WifiUI - - Scanning for networks... - Recherche de réseaux... - - - CONNECTING... - CONNEXION... - - - FORGET - OUBLIER - - - Forget Wi-Fi Network "%1"? - Oublier le réseau Wi-Fi "%1" ? - - - Forget - Oublier - - - diff --git a/selfdrive/ui/translations/main_ja.ts b/selfdrive/ui/translations/main_ja.ts deleted file mode 100644 index 096fa9509176ac..00000000000000 --- a/selfdrive/ui/translations/main_ja.ts +++ /dev/null @@ -1,1133 +0,0 @@ - - - - - AbstractAlert - - Close - 閉じる - - - Snooze Update - 更新の一時停止 - - - Reboot and Update - 再起動してアップデート - - - - AdvancedNetworking - - Back - 戻る - - - Enable Tethering - テザリングを有効化 - - - Tethering Password - テザリングパスワード - - - EDIT - 編集 - - - Enter new tethering password - 新しいテザリングパスワードを入力 - - - IP Address - IP アドレス - - - Enable Roaming - ローミングを有効化 - - - APN Setting - APN 設定 - - - Enter APN - APN を入力 - - - leave blank for automatic configuration - 自動で設定するには、空白のままにしてください。 - - - Cellular Metered - 従量制通信設定 - - - Prevent large data uploads when on a metered connection - 大量のデータのアップロードを防止します。 - - - Hidden Network - - - - CONNECT - 接続 - - - Enter SSID - SSID を入力 - - - Enter password - パスワードを入力 - - - for "%1" - ネットワーク名:%1 - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - 最高速度 - - - - ConfirmationDialog - - Ok - OK - - - Cancel - キャンセル - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - openpilot をご利用される前に、利用規約に同意する必要があります。 - - - Back - 戻る - - - Decline, uninstall %1 - 拒否して %1 をアンインストール - - - - DevicePanel - - Dongle ID - ドングル番号 (Dongle ID) - - - N/A - N/A - - - Serial - シリアル番号 - - - Driver Camera - 車内カメラ - - - PREVIEW - プレビュー - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - 車内カメラをプレビューして、ドライバー監視システムの視界を確認ができます。(車両の電源を切る必要があります) - - - Reset Calibration - キャリブレーションをリセット - - - RESET - リセット - - - Are you sure you want to reset calibration? - キャリブレーションをリセットしてもよろしいですか? - - - Review Training Guide - 使い方の確認 - - - REVIEW - 見る - - - Review the rules, features, and limitations of openpilot - openpilot の特徴を見る - - - Are you sure you want to review the training guide? - 使い方の確認をしますか? - - - Regulatory - 認証情報 - - - VIEW - 見る - - - Change Language - 言語を変更 - - - CHANGE - 変更 - - - Select a language - 言語を選択 - - - Reboot - 再起動 - - - Power Off - 電源を切る - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - openpilotの本体は、左右4°以内、上5°、下9°以内の角度で取付ける必要があります。継続してキャリブレーションを続けているので、手動でリセットを行う必要はほぼありません。 - - - Your device is pointed %1° %2 and %3° %4. - このデバイスは%2 %1°、%4 %3°の向きに設置されています。 - - - down - 下 - - - up - 上 - - - left - 左 - - - right - 右 - - - Are you sure you want to reboot? - 再起動してもよろしいですか? - - - Disengage to Reboot - openpilot をキャンセルして再起動ができます - - - Are you sure you want to power off? - シャットダウンしてもよろしいですか? - - - Disengage to Power Off - openpilot をキャンセルしてシャットダウンができます - - - Reset - リセット - - - Review - 確認 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - デバイスを comma connect (connect.comma.ai)でペアリングし、comma primeの特典を申請してください。 - - - Pair Device - - - - PAIR - - - - - DriverViewWindow - - camera starting - カメラを起動しています - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - 実験モード - - - CHILL MODE ON - チルモード - - - - InputDialog - - Cancel - キャンセル - - - Need at least %n character(s)! - - %n文字以上でお願いします! - - - - - Installer - - Installing... - インストールしています... - - - - MultiOptionDialog - - Select - 選択 - - - Cancel - キャンセル - - - - Networking - - Advanced - 詳細 - - - Enter password - パスワードを入力 - - - for "%1" - ネットワーク名:%1 - - - Wrong password - パスワードが間違っています - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - - - - Unable to download updates -%1 - - - - Taking camera snapshots. System won't start until finished. - - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - - - - NVMe drive not mounted. - - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - - - - - OffroadHome - - UPDATE - 更新 - - - ALERTS - 警告 - - - ALERT - 警告 - - - - OnroadAlerts - - openpilot Unavailable - - - - Waiting for controls to start - - - - TAKE CONTROL IMMEDIATELY - - - - Controls Unresponsive - - - - Reboot Device - - - - - PairingPopup - - Pair your device to your comma account - デバイスと comma アカウントを連携する - - - Go to https://connect.comma.ai on your phone - スマートフォンで「https://connect.comma.ai」にアクセスしてください。 - - - Click "add new device" and scan the QR code on the right - 「新しいデバイスを追加」を押し、右側のQRコードをスキャンしてください。 - - - Bookmark connect.comma.ai to your home screen to use it like an app - 「connect.comma.ai」をホーム画面に追加して、アプリのように使うことができます。 - - - - ParamControl - - Cancel - キャンセル - - - Enable - を有効化 - - - - PrimeAdWidget - - Upgrade Now - 今すぐアップグレート - - - Become a comma prime member at connect.comma.ai - connect.comma.ai でプライム会員に登録できます - - - PRIME FEATURES: - 特典: - - - Remote access - リモートアクセス - - - 24/7 LTE connectivity - - - - 1 year of drive storage - - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ 入会しました - - - comma prime - comma prime - - - - QObject - - Reboot - 再起動 - - - Exit - 閉じる - - - openpilot - openpilot - - - %n minute(s) ago - - %n 分前 - - - - %n hour(s) ago - - %n 時間前 - - - - %n day(s) ago - - %n 日前 - - - - now - - - - - Reset - - Reset failed. Reboot to try again. - 初期化に失敗しました。再起動後に再試行してください。 - - - Are you sure you want to reset your device? - 初期化してもよろしいですか? - - - System Reset - システムを初期化 - - - Cancel - キャンセル - - - Reboot - 再起動 - - - Confirm - 確認 - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - - - - Resetting device... -This may take up to a minute. - - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - - - - - SettingsWindow - - × - × - - - Device - デバイス - - - Network - ネットワーク - - - Toggles - 機能設定 - - - Software - ソフトウェア - - - - Setup - - WARNING: Low Voltage - 警告:低電圧 - - - Power your device in a car with a harness or proceed at your own risk. - 自己責任で実行を継続するか、ハーネスから電源を供給してください。 - - - Power off - 電源を切る - - - Continue - 続ける - - - Getting Started - はじめに - - - Before we get on the road, let’s finish installation and cover some details. - 道路に向かう前に、インストールを完了して使い方を確認しましょう。 - - - Connect to Wi-Fi - Wi-Fi に接続 - - - Back - 戻る - - - Continue without Wi-Fi - Wi-Fi に接続せずに続行 - - - Waiting for internet - インターネット接続を待機中 - - - Enter URL - URL を入力 - - - for Custom Software - カスタムソフトウェア - - - Downloading... - ダウンロード中... - - - Download Failed - ダウンロード失敗 - - - Ensure the entered URL is valid, and the device’s internet connection is good. - 入力された URL を確認し、デバイスがインターネットに接続されていることを確認してください。 - - - Reboot device - デバイスを再起動 - - - Start over - 最初からやり直す - - - No custom software found at this URL. - - - - Something went wrong. Reboot the device. - - - - Select a language - 言語を選択 - - - Choose Software to Install - - - - openpilot - openpilot - - - Custom Software - - - - - SetupWidget - - Finish Setup - セットアップ完了 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - デバイスを comma connect (connect.comma.ai)でペアリングし、comma primeの特典を申請してください。 - - - Pair device - デバイスをペアリング - - - - Sidebar - - CONNECT - 接続 - - - OFFLINE - オフライン - - - ONLINE - オンライン - - - ERROR - エラー - - - TEMP - 温度 - - - HIGH - 高温 - - - GOOD - 最適 - - - OK - OK - - - VEHICLE - 車両 - - - NO - NO - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - 車の電源がオフの間のみ、アップデートのダウンロードが行われます。 - - - Current Version - 現在のバージョン - - - Download - ダウンロード - - - Install Update - アップデート - - - INSTALL - インストール - - - Target Branch - 対象のブランチ - - - SELECT - 選択 - - - Select a branch - ブランチを選択 - - - UNINSTALL - 実行 - - - Uninstall %1 - %1をアンインストール - - - Are you sure you want to uninstall? - アンインストールしてもよろしいですか? - - - CHECK - 確認 - - - Uninstall - アンインストール - - - failed to check for update - - - - up to date, last checked %1 - - - - DOWNLOAD - - - - update available - - - - never - - - - - SshControl - - SSH Keys - SSH 鍵 - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - 警告: これは、GitHub の設定にあるすべての公開鍵への SSH アクセスを許可するものです。自分以外の GitHub のユーザー名を入力しないでください。commaのスタッフが GitHub のユーザー名を追加するようお願いすることはありません。 - - - ADD - 追加 - - - Enter your GitHub username - GitHub のユーザー名を入力してください - - - LOADING - 読み込み中 - - - REMOVE - 削除 - - - Username '%1' has no keys on GitHub - ユーザー名 “%1” は GitHub に鍵がありません - - - Request timed out - リクエストタイムアウト - - - Username '%1' doesn't exist on GitHub - ユーザー名 '%1' は GitHub に存在しません - - - - SshToggle - - Enable SSH - SSH を有効化 - - - - TermsPage - - Terms & Conditions - 利用規約 - - - Decline - 拒否 - - - Scroll to accept - スクロールして同意 - - - Agree - 同意 - - - - TogglesPanel - - Enable openpilot - openpilot を有効化 - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - openpilotによるアダプティブクルーズコントロールとレーンキーピングドライバーアシストを利用します。この機能を利用する際は、常に前方への注意が必要です。この設定を変更すると、車の電源が切れた時に反映されます。 - - - Enable Lane Departure Warnings - 車線逸脱警報機能を有効化 - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 時速31マイル(50km)を超えるスピードで走行中、ウインカーを作動させずに検出された車線ライン上に車両が触れた場合、手動で車線内に戻るように警告を行います。 - - - Use Metric System - メートル法を使用 - - - Display speed in km/h instead of mph. - 速度は mph ではなく km/h で表示されます。 - - - Record and Upload Driver Camera - 車内カメラの録画とアップロード - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - 車内カメラの映像をアップロードし、ドライバー監視システムのアルゴリズムの向上に役立てます。 - - - Disengage on Accelerator Pedal - アクセルを踏むと openpilot を中断 - - - When enabled, pressing the accelerator pedal will disengage openpilot. - この機能を有効化すると、openpilotを利用中にアクセルを踏むとopenpilotによる運転サポートを中断します。 - - - Experimental Mode - 実験モード - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - openpilotは標準ではゆっくりとくつろげる運転を提供します。この実験モードを有効にすると、以下のくつろげる段階ではない開発中の機能を利用する事ができます。 - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - openpilotにアクセルとブレーキを任せます。openpilotは赤信号や一時停止サインでの停止を含み、人間と同じように考えて運転を行います。openpilotが運転速度を決定するため、あなたが設定する速度は上限速度になります。この機能は実験段階のため、openpilotの運転ミスに常に備えて注意してください。 - - - New Driving Visualization - 新しい運転画面 - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - この車のACCがアクセル制御を行うため実験モードを利用することができません。 - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - Aggressive - - - - Standard - - - - Relaxed - - - - Driving Personality - - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - End-to-End Longitudinal Control - - - - openpilot longitudinal control may come in a future update. - - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - - - - Always-On Driver Monitoring - - - - Enable driver monitoring even when openpilot is not engaged. - - - - - Updater - - Update Required - アップデートが必要です - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - オペレーティングシステムのアップデートが必要です。Wi-Fi に接続してアップデートする事をお勧めします。ダウンロードサイズは約 1GB です。 - - - Connect to Wi-Fi - Wi-Fi に接続 - - - Install - インストール - - - Back - 戻る - - - Loading... - 読み込み中... - - - Reboot - 再起動 - - - Update failed - 更新失敗 - - - - WiFiPromptWidget - - Setup Wi-Fi - - - - Connect to Wi-Fi to upload driving data and help improve openpilot - - - - Open Settings - - - - Ready to upload - - - - Training data will be pulled periodically while your device is on Wi-Fi - - - - - WifiUI - - Scanning for networks... - ネットワークをスキャン中... - - - CONNECTING... - 接続中... - - - FORGET - 削除 - - - Forget Wi-Fi Network "%1"? - Wi-Fiネットワーク%1を削除してもよろしいですか? - - - Forget - 削除 - - - diff --git a/selfdrive/ui/translations/main_ko.ts b/selfdrive/ui/translations/main_ko.ts deleted file mode 100644 index df012d3e8586ba..00000000000000 --- a/selfdrive/ui/translations/main_ko.ts +++ /dev/null @@ -1,1135 +0,0 @@ - - - - - AbstractAlert - - Close - 닫기 - - - Snooze Update - 업데이트 일시 중지 - - - Reboot and Update - 업데이트 및 재부팅 - - - - AdvancedNetworking - - Back - 뒤로 - - - Enable Tethering - 테더링 사용 - - - Tethering Password - 테더링 비밀번호 - - - EDIT - 편집 - - - Enter new tethering password - 새 테더링 비밀번호를 입력하세요 - - - IP Address - IP 주소 - - - Enable Roaming - 로밍 사용 - - - APN Setting - APN 설정 - - - Enter APN - APN 입력 - - - leave blank for automatic configuration - 자동 설정하려면 빈 칸으로 두세요 - - - Cellular Metered - 데이터 요금제 - - - Prevent large data uploads when on a metered connection - 데이터 요금제 연결 시 대용량 데이터 업로드를 방지합니다 - - - Hidden Network - 숨겨진 네트워크 - - - CONNECT - 연결됨 - - - Enter SSID - SSID 입력 - - - Enter password - 비밀번호를 입력하세요 - - - for "%1" - "%1"에 접속하려면 비밀번호가 필요합니다 - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - - ConfirmationDialog - - Ok - 확인 - - - Cancel - 취소 - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - openpilot을 사용하려면 이용약관에 동의해야 합니다. - - - Back - 뒤로 - - - Decline, uninstall %1 - 거절, %1 제거 - - - - DevicePanel - - Dongle ID - 동글 ID - - - N/A - N/A - - - Serial - 시리얼 - - - Driver Camera - 운전자 카메라 - - - PREVIEW - 미리보기 - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - 운전자 모니터링이 잘 되는지 확인하기 위해 후면 카메라를 미리 봅니다. (차량 시동이 꺼져 있어야 합니다) - - - Reset Calibration - 캘리브레이션 초기화 - - - RESET - 초기화 - - - Are you sure you want to reset calibration? - 캘리브레이션을 초기화하시겠습니까? - - - Review Training Guide - 트레이닝 가이드 다시보기 - - - REVIEW - 다시보기 - - - Review the rules, features, and limitations of openpilot - openpilot의 규칙, 기능 및 제한 다시 확인 - - - Are you sure you want to review the training guide? - 트레이닝 가이드를 다시 확인하시겠습니까? - - - Regulatory - 규제 - - - VIEW - 보기 - - - Change Language - 언어 변경 - - - CHANGE - 변경 - - - Select a language - 언어를 선택하세요 - - - Reboot - 재부팅 - - - Power Off - 전원 끄기 - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot 장치는 좌우 4°, 위로 5°, 아래로 9° 이내 각도로 장착되어야 합니다. openpilot은 지속적으로 자동 보정되며 재설정은 거의 필요하지 않습니다. - - - Your device is pointed %1° %2 and %3° %4. - 사용자의 장치는 %2 %1° 및 %4 %3° 의 방향으로 장착되어 있습니다. - - - down - 아래로 - - - up - 위로 - - - left - 좌측으로 - - - right - 우측으로 - - - Are you sure you want to reboot? - 재부팅하시겠습니까? - - - Disengage to Reboot - 재부팅하려면 연결을 해제하세요 - - - Are you sure you want to power off? - 전원을 끄시겠습니까? - - - Disengage to Power Off - 전원을 끄려면 연결을 해제하세요 - - - Reset - 초기화 - - - Review - 다시보기 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 장치를 comma connect (connect.comma.ai)에서 페어링하고 comma prime 무료 이용권을 사용하세요. - - - Pair Device - 장치 동기화 - - - PAIR - 동기화 - - - - DriverViewWindow - - camera starting - 카메라 시작 중 - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - 실험 모드 사용 - - - CHILL MODE ON - 안정 모드 사용 - - - - InputDialog - - Cancel - 취소 - - - Need at least %n character(s)! - - 최소 %n자 이상이어야 합니다! - - - - - Installer - - Installing... - 설치 중... - - - - MultiOptionDialog - - Select - 선택 - - - Cancel - 취소 - - - - Networking - - Advanced - 고급 설정 - - - Enter password - 비밀번호를 입력하세요 - - - for "%1" - "%1"에 접속하려면 비밀번호가 필요합니다 - - - Wrong password - 비밀번호가 틀렸습니다 - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - 즉시 인터넷에 연결하여 업데이트를 확인하세요. 인터넷에 연결되어 있지 않으면 %1 이후에는 openpilot이 활성화되지 않습니다. - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - 업데이트를 확인하려면 인터넷에 연결하세요. openpilot은 업데이트를 확인하기 위해 인터넷에 연결할 때까지 자동으로 시작되지 않습니다. - - - Unable to download updates -%1 - 업데이트를 다운로드할 수 없습니다 -%1 - - - Taking camera snapshots. System won't start until finished. - 카메라 스냅샷 찍기가 완료될 때까지 시스템이 시작되지 않습니다. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - 백그라운드에서 운영 체제에 대한 업데이트가 다운로드되고 있습니다. 설치가 준비되면 업데이트 메시지가 표시됩니다. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - 장치를 등록하지 못했습니다. comma.ai 서버에 연결하거나 데이터를 업로드하지 않으며 comma.ai에서 지원을 받지 않습니다. 공식 장치인 경우 https://comma.ai/support 에 방문하여 문의하세요. - - - NVMe drive not mounted. - NVMe 드라이브가 마운트되지 않았습니다. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - 지원되지 않는 NVMe 드라이브가 감지되었습니다. 지원되지 않는 NVMe 드라이브는 많은 전력을 소비하고 장치를 과열시킬 수 있습니다. - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - openpilot이 차량을 식별할 수 없었습니다. 지원되지 않는 차량이거나 ECU가 인식되지 않습니다. 해당 차량에 맞는 펌웨어 버전을 추가하려면 PR을 제출하세요. 도움이 필요하시면 discord.comma.ai에 가입하세요. - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - openpilot이 차량을 식별할 수 없었습니다. 케이블의 무결성을 점검하고 모든 연결부, 특히 comma power가 차량의 OBD-II 포트에 제대로 삽입되었는지 확인하세요. 도움이 필요하시면 discord.comma.ai에 가입하세요. - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - openpilot 장치의 장착 위치가 변경되었습니다. 장치가 마운트에 완전히 장착되고 마운트가 앞유리에 단단히 고정되었는지 확인하세요. - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - 장치 온도가 너무 높습니다. 시작하기 전에 온도를 낮춰주세요. 현재 내부 부품 온도: %1 - - - - OffroadHome - - UPDATE - 업데이트 - - - ALERTS - 알림 - - - ALERT - 알림 - - - - OnroadAlerts - - openpilot Unavailable - 오픈파일럿을 사용할수없습니다 - - - Waiting for controls to start - 프로세스가 준비중입니다 - - - TAKE CONTROL IMMEDIATELY - 핸들을 잡아주세요 - - - Controls Unresponsive - 프로세스가 응답하지않습니다 - - - Reboot Device - 장치를 재부팅하세요 - - - - PairingPopup - - Pair your device to your comma account - 장치를 comma 계정에 동기화합니다 - - - Go to https://connect.comma.ai on your phone - https://connect.comma.ai에 접속하세요 - - - Click "add new device" and scan the QR code on the right - "새 장치 추가"를 클릭하고 오른쪽 QR 코드를 스캔하세요 - - - Bookmark connect.comma.ai to your home screen to use it like an app - connect.comma.ai를 앱처럼 사용하려면 홈 화면에 바로가기를 만드세요 - - - - ParamControl - - Cancel - 취소 - - - Enable - 활성화 - - - - PrimeAdWidget - - Upgrade Now - 지금 업그레이드하세요 - - - Become a comma prime member at connect.comma.ai - connect.comma.ai에 접속하여 comma prime 회원으로 등록하세요 - - - PRIME FEATURES: - PRIME 기능: - - - Remote access - 원격 접속 - - - 24/7 LTE connectivity - 항상 LTE 연결 - - - 1 year of drive storage - 1년간 드라이브 로그 저장 - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ 구독함 - - - comma prime - comma prime - - - - QObject - - Reboot - 재부팅 - - - Exit - 종료 - - - openpilot - openpilot - - - %n minute(s) ago - - %n 분 전 - - - - %n hour(s) ago - - %n 시간 전 - - - - %n day(s) ago - - %n 일 전 - - - - now - now - - - - Reset - - Reset failed. Reboot to try again. - 초기화 실패. 재부팅 후 다시 시도하세요. - - - Are you sure you want to reset your device? - 장치를 초기화하시겠습니까? - - - System Reset - 장치 초기화 - - - Cancel - 취소 - - - Reboot - 재부팅 - - - Confirm - 확인 - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - 데이터 파티션을 마운트할 수 없습니다. 파티션이 손상되었을 수 있습니다. 모든 설정을 삭제하고 장치를 초기화하려면 확인을 누르세요. - - - Resetting device... -This may take up to a minute. - 장치를 초기화하는 중... -최대 1분이 소요될 수 있습니다. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - 시스템 재설정이 시작되었습니다. 모든 콘텐츠와 설정을 지우려면 확인을 누르시고 부팅을 재개하려면 취소를 누르세요. - - - - SettingsWindow - - × - × - - - Device - 장치 - - - Network - 네트워크 - - - Toggles - 토글 - - - Software - 소프트웨어 - - - - Setup - - WARNING: Low Voltage - 경고: 전압이 낮습니다 - - - Power your device in a car with a harness or proceed at your own risk. - 장치를 하네스를 통해 차량 전원에 연결하세요. USB 전원에서는 예상치 못한 문제가 생길 수 있습니다. - - - Power off - 전원 끄기 - - - Continue - 계속 - - - Getting Started - 시작하기 - - - Before we get on the road, let’s finish installation and cover some details. - 출발 전 설정을 완료하고 세부 사항을 살펴봅니다. - - - Connect to Wi-Fi - Wi-Fi 연결 - - - Back - 뒤로 - - - Continue without Wi-Fi - Wi-Fi 연결 없이 진행 - - - Waiting for internet - 인터넷 연결 대기 중 - - - Enter URL - URL 입력 - - - for Custom Software - 커스텀 소프트웨어 - - - Downloading... - 다운로드 중... - - - Download Failed - 다운로드 실패 - - - Ensure the entered URL is valid, and the device’s internet connection is good. - 입력된 URL이 유효하고 인터넷 연결이 원활한지 확인하세요. - - - Reboot device - 장치 재부팅 - - - Start over - 다시 시작 - - - Something went wrong. Reboot the device. - 문제가 발생했습니다. 장치를 재부팅하세요. - - - No custom software found at this URL. - 이 URL에서 커스텀 소프트웨어를 찾을 수 없습니다. - - - Select a language - 언어를 선택하세요 - - - Choose Software to Install - 설치할 소프트웨어 선택 - - - openpilot - openpilot - - - Custom Software - 커스텀 소프트웨어 - - - - SetupWidget - - Finish Setup - 설정 완료 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 장치를 comma connect (connect.comma.ai)에서 페어링하고 comma prime 무료 이용권을 사용하세요. - - - Pair device - 장치 페어링 - - - - Sidebar - - CONNECT - 커넥트 - - - OFFLINE - 연결 안됨 - - - ONLINE - 온라인 - - - ERROR - 오류 - - - TEMP - 온도 - - - HIGH - 높음 - - - GOOD - 좋음 - - - OK - OK - - - VEHICLE - 차량 - - - NO - NO - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - LAN - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - 업데이트는 차량 시동이 꺼졌을 때 다운로드됩니다. - - - Current Version - 현재 버전 - - - Download - 다운로드 - - - Install Update - 업데이트 설치 - - - INSTALL - 설치 - - - Target Branch - 대상 브랜치 - - - SELECT - 선택 - - - Select a branch - 브랜치 선택 - - - UNINSTALL - 제거 - - - Uninstall %1 - %1 제거 - - - Are you sure you want to uninstall? - 제거하시겠습니까? - - - CHECK - 확인 - - - Uninstall - 제거 - - - failed to check for update - 업데이트를 확인하지 못했습니다 - - - up to date, last checked %1 - 최신 버전입니다. 마지막 확인: %1 - - - DOWNLOAD - 다운로드 - - - update available - 업데이트 가능 - - - never - 업데이트 안함 - - - - SshControl - - SSH Keys - SSH 키 - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - 경고: 이 설정은 GitHub에 등록된 모든 공용 키에 대해 SSH 액세스 권한을 부여합니다. 본인의 GitHub 사용자 아이디 이외에는 입력하지 마십시오. comma에서는 GitHub 아이디를 추가하라는 요청을 하지 않습니다. - - - ADD - 추가 - - - Enter your GitHub username - GitHub 사용자 ID - - - LOADING - 로딩 중 - - - REMOVE - 삭제 - - - Username '%1' has no keys on GitHub - 사용자 '%1'의 GitHub에 키가 등록되어 있지 않습니다 - - - Request timed out - 요청 시간 초과 - - - Username '%1' doesn't exist on GitHub - GitHub 사용자 '%1'를 찾지 못했습니다 - - - - SshToggle - - Enable SSH - SSH 사용 - - - - TermsPage - - Terms & Conditions - 이용약관 - - - Decline - 거절 - - - Scroll to accept - 동의하려면 아래로 스크롤하세요 - - - Agree - 동의 - - - - TogglesPanel - - Enable openpilot - openpilot 사용 - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - 어댑티브 크루즈 컨트롤 및 차로 유지 보조를 위해 openpilot 시스템을 사용할 수 있습니다. 이 기능을 사용할 때에는 언제나 주의를 기울여야 합니다. 설정을 변경하면 차량 시동이 꺼졌을 때 적용됩니다. - - - Enable Lane Departure Warnings - 차선 이탈 경고 활성화 - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 차량이 50km/h(31mph) 이상의 속도로 주행할 때 방향지시등이 켜지지 않은 상태에서 차선을 벗어나면 경고합니다. - - - Use Metric System - 미터법 사용 - - - Display speed in km/h instead of mph. - mph 대신 km/h로 속도를 표시합니다. - - - Record and Upload Driver Camera - 운전자 카메라 녹화 및 업로드 - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - 운전자 카메라의 영상 데이터를 업로드하여 운전자 모니터링 알고리즘을 개선합니다. - - - Disengage on Accelerator Pedal - 가속페달 조작 시 해제 - - - When enabled, pressing the accelerator pedal will disengage openpilot. - 활성화된 경우 가속 페달을 밟으면 openpilot이 해제됩니다. - - - Experimental Mode - 실험 모드 - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - openpilot은 기본적으로 <b>안정 모드</b>로 주행합니다. 실험 모드는 안정화되지 않은 <b>알파 수준의 기능</b>을 활성화합니다. 실험 모드의 기능은 아래와 같습니다: - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - openpilot의 주행모델이 가감속을 제어합니다. openpilot은 신호등과 정지 표지판을 보고 멈추는 것을 포함하여 인간이 운전하는 것처럼 생각하고 주행합니다. 주행 모델이 주행할 속도를 결정하므로 설정된 속도는 최대 주행 속도로만 기능합니다. 이 기능은 알파 수준이므로 사용에 각별히 주의해야 합니다. - - - New Driving Visualization - 새로운 주행 시각화 - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - 차량에 장착된 ACC로 가감속을 제어하기 때문에 현재 이 차량에서는 실험 모드를 사용할 수 없습니다. - - - openpilot longitudinal control may come in a future update. - openpilot 가감속 제어는 향후 업데이트에서 지원될 수 있습니다. - - - openpilot Longitudinal Control (Alpha) - openpilot 가감속 제어 (알파) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - 경고: openpilot 가감속 제어 알파 기능으로 차량의 자동긴급제동(AEB)을 비활성화합니다. - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - 이 차량은 openpilot 가감속 제어 대신 기본적으로 차량의 ACC로 가감속을 제어합니다. openpilot의 가감속 제어로 전환하려면 이 기능을 활성화하세요. openpilot 가감속 제어 알파를 활성화하는 경우 실험 모드 활성화를 권장합니다. - - - Aggressive - 공격적 - - - Standard - 표준 - - - Relaxed - 편안한 - - - Driving Personality - 주행 모드 - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - openpilot 가감속 제어 알파 버전은 비 릴리즈 브랜치에서 실험 모드와 함께 테스트할 수 있습니다. - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - 실험 모드를 사용하려면 openpilot E2E 가감속 제어 (알파) 토글을 활성화하세요. - - - End-to-End Longitudinal Control - E2E 가감속 제어 - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - 표준 모드를 권장합니다. 공격적 모드의 openpilot은 선두 차량을 더 가까이 따라가고 가감속제어를 사용하여 더욱 공격적으로 움직입니다. 편안한 모드의 openpilot은 선두 차량으로부터 더 멀리 떨어져 있습니다. 지원되는 차량에서는 스티어링 휠 거리 버튼을 사용하여 이러한 특성을 순환할 수 있습니다. - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - - - - Always-On Driver Monitoring - - - - Enable driver monitoring even when openpilot is not engaged. - - - - - Updater - - Update Required - 업데이트 필요 - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - OS 업데이트가 필요합니다. 장치를 Wi-Fi에 연결하면 가장 빠르게 업데이트할 수 있습니다. 다운로드 크기는 약 1GB입니다. - - - Connect to Wi-Fi - Wi-Fi 연결 - - - Install - 설치 - - - Back - 뒤로 - - - Loading... - 로딩 중... - - - Reboot - 재부팅 - - - Update failed - 업데이트 실패 - - - - WiFiPromptWidget - - Setup Wi-Fi - Wi-Fi 설정 - - - Connect to Wi-Fi to upload driving data and help improve openpilot - Wi-Fi에 연결하여 주행 데이터를 업로드하고 openpilot 개선에 기여하세요 - - - Open Settings - 설정 열기 - - - Ready to upload - 업로드 준비 완료 - - - Training data will be pulled periodically while your device is on Wi-Fi - 기기가 Wi-Fi에 연결되어 있는 동안 트레이닝 데이터를 주기적으로 전송합니다 - - - - WifiUI - - Scanning for networks... - 네트워크 검색 중... - - - CONNECTING... - 연결 중... - - - FORGET - 삭제 - - - Forget Wi-Fi Network "%1"? - Wi-Fi "%1"에 자동으로 연결하지 않겠습니까? - - - Forget - 삭제 - - - diff --git a/selfdrive/ui/translations/main_nl.ts b/selfdrive/ui/translations/main_nl.ts deleted file mode 100644 index 10651a416011ff..00000000000000 --- a/selfdrive/ui/translations/main_nl.ts +++ /dev/null @@ -1,1120 +0,0 @@ - - - - - AbstractAlert - - Close - Sluit - - - Snooze Update - Update uitstellen - - - Reboot and Update - Opnieuw Opstarten en Updaten - - - - AdvancedNetworking - - Back - Terug - - - Enable Tethering - Tethering Inschakelen - - - Tethering Password - Tethering Wachtwoord - - - EDIT - AANPASSEN - - - Enter new tethering password - Voer nieuw tethering wachtwoord in - - - IP Address - IP Adres - - - Enable Roaming - Roaming Inschakelen - - - APN Setting - APN Instelling - - - Enter APN - Voer APN in - - - leave blank for automatic configuration - laat leeg voor automatische configuratie - - - Cellular Metered - - - - Prevent large data uploads when on a metered connection - - - - - AnnotatedCameraWidget - - km/h - km/u - - - mph - mph - - - MAX - MAX - - - SPEED - SPEED - - - LIMIT - LIMIT - - - - ConfirmationDialog - - Ok - Ok - - - Cancel - Annuleren - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - U moet de Algemene Voorwaarden accepteren om openpilot te gebruiken. - - - Back - Terug - - - Decline, uninstall %1 - Afwijzen, verwijder %1 - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - Nvt - - - Serial - Serienummer - - - Driver Camera - Bestuurders Camera - - - PREVIEW - BEKIJKEN - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Bekijk de naar de bestuurder gerichte camera om ervoor te zorgen dat het monitoren van de bestuurder goed zicht heeft. (Voertuig moet uitgschakeld zijn) - - - Reset Calibration - Kalibratie Resetten - - - RESET - RESET - - - Are you sure you want to reset calibration? - Weet u zeker dat u de kalibratie wilt resetten? - - - Review Training Guide - Doorloop de Training Opnieuw - - - REVIEW - BEKIJKEN - - - Review the rules, features, and limitations of openpilot - Bekijk de regels, functies en beperkingen van openpilot - - - Are you sure you want to review the training guide? - Weet u zeker dat u de training opnieuw wilt doorlopen? - - - Regulatory - Regelgeving - - - VIEW - BEKIJKEN - - - Change Language - Taal Wijzigen - - - CHANGE - WIJZIGEN - - - Select a language - Selecteer een taal - - - Reboot - Opnieuw Opstarten - - - Power Off - Uitschakelen - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot vereist dat het apparaat binnen 4° links of rechts en binnen 5° omhoog of 8° omlaag wordt gemonteerd. openpilot kalibreert continu, resetten is zelden nodig. - - - Your device is pointed %1° %2 and %3° %4. - Uw apparaat is gericht op %1° %2 en %3° %4. - - - down - omlaag - - - up - omhoog - - - left - links - - - right - rechts - - - Are you sure you want to reboot? - Weet u zeker dat u opnieuw wilt opstarten? - - - Disengage to Reboot - Deactiveer openpilot om opnieuw op te starten - - - Are you sure you want to power off? - Weet u zeker dat u wilt uitschakelen? - - - Disengage to Power Off - Deactiveer openpilot om uit te schakelen - - - - DriveStats - - Drives - Ritten - - - Hours - Uren - - - ALL TIME - TOTAAL - - - PAST WEEK - AFGELOPEN WEEK - - - KM - Km - - - Miles - Mijl - - - - DriverViewScene - - camera starting - Camera wordt gestart - - - - InputDialog - - Cancel - Annuleren - - - Need at least %n character(s)! - - Heeft minstens %n karakter nodig! - Heeft minstens %n karakters nodig! - - - - - Installer - - Installing... - Installeren... - - - Receiving objects: - Objecten ontvangen: - - - Resolving deltas: - Deltas verwerken: - - - Updating files: - Bestanden bijwerken: - - - - MapETA - - eta - eta - - - min - min - - - hr - uur - - - km - km - - - mi - mi - - - - MapInstructions - - km - km - - - m - m - - - mi - mi - - - ft - ft - - - - MapPanel - - Current Destination - Huidige Bestemming - - - CLEAR - LEEGMAKEN - - - Recent Destinations - Recente Bestemmingen - - - Try the Navigation Beta - Probeer de Navigatie Bèta - - - Get turn-by-turn directions displayed and more with a comma -prime subscription. Sign up now: https://connect.comma.ai - Krijg stapsgewijze routebeschrijving en meer met een comma -prime abonnement. Meld u nu aan: https://connect.comma.ai - - - No home -location set - Geen thuislocatie -ingesteld - - - No work -location set - Geen werklocatie -ingesteld - - - no recent destinations - geen recente bestemmingen - - - - MapWindow - - Map Loading - Kaart wordt geladen - - - Waiting for GPS - Wachten op GPS - - - - MultiOptionDialog - - Select - Selecteer - - - Cancel - Annuleren - - - - Networking - - Advanced - Geavanceerd - - - Enter password - Voer wachtwoord in - - - for "%1" - voor "%1" - - - Wrong password - Verkeerd wachtwoord - - - - OffroadHome - - UPDATE - UPDATE - - - ALERTS - WAARSCHUWINGEN - - - ALERT - WAARSCHUWING - - - - PairingPopup - - Pair your device to your comma account - Koppel uw apparaat aan uw comma-account - - - Go to https://connect.comma.ai on your phone - Ga naar https://connect.comma.ai op uw telefoon - - - Click "add new device" and scan the QR code on the right - Klik op "add new device" en scan de QR-code aan de rechterkant - - - Bookmark connect.comma.ai to your home screen to use it like an app - Voeg connect.comma.ai toe op uw startscherm om het als een app te gebruiken - - - - PrimeAdWidget - - Upgrade Now - Upgrade nu - - - Become a comma prime member at connect.comma.ai - Word een comma prime lid op connect.comma.ai - - - PRIME FEATURES: - PRIME BEVAT: - - - Remote access - Toegang op afstand - - - 1 year of storage - 1 jaar lang opslag - - - Developer perks - Voordelen voor ontwikkelaars - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ GEABONNEERD - - - comma prime - comma prime - - - CONNECT.COMMA.AI - CONNECT.COMMA.AI - - - COMMA POINTS - COMMA PUNTEN - - - - QObject - - Reboot - Opnieuw Opstarten - - - Exit - Afsluiten - - - dashcam - dashcam - - - openpilot - openpilot - - - %n minute(s) ago - - %n minuut geleden - %n minuten geleden - - - - %n hour(s) ago - - %n uur geleden - %n uur geleden - - - - %n day(s) ago - - %n dag geleden - %n dagen geleden - - - - - Reset - - Reset failed. Reboot to try again. - Opnieuw instellen mislukt. Start opnieuw op om opnieuw te proberen. - - - Are you sure you want to reset your device? - Weet u zeker dat u uw apparaat opnieuw wilt instellen? - - - Resetting device... - Apparaat opnieuw instellen... - - - System Reset - Systeemreset - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Systeemreset geactiveerd. Druk op bevestigen om alle inhoud en instellingen te wissen. Druk op Annuleren om het opstarten te hervatten. - - - Cancel - Annuleren - - - Reboot - Opnieuw Opstarten - - - Confirm - Bevestigen - - - Unable to mount data partition. Press confirm to reset your device. - Kan gegevenspartitie niet koppelen. Druk op bevestigen om uw apparaat te resetten. - - - - RichTextDialog - - Ok - Ok - - - - SettingsWindow - - × - × - - - Device - Apparaat - - - Network - Netwerk - - - Toggles - Opties - - - Software - Software - - - Navigation - Navigatie - - - - Setup - - WARNING: Low Voltage - WAARCHUWING: Lage Spanning - - - Power your device in a car with a harness or proceed at your own risk. - Voorzie uw apparaat van stroom in een auto met een harnas (car harness) of ga op eigen risico verder. - - - Power off - Uitschakelen - - - Continue - Doorgaan - - - Getting Started - Aan de slag - - - Before we get on the road, let’s finish installation and cover some details. - Laten we, voordat we op pad gaan, de installatie afronden en enkele details bespreken. - - - Connect to Wi-Fi - Maak verbinding met Wi-Fi - - - Back - Terug - - - Continue without Wi-Fi - Doorgaan zonder Wi-Fi - - - Waiting for internet - Wachten op internet - - - Choose Software to Install - Kies Software om te Installeren - - - Dashcam - Dashcam - - - Custom Software - Andere Software - - - Enter URL - Voer URL in - - - for Custom Software - voor Andere Software - - - Downloading... - Downloaden... - - - Download Failed - Downloaden Mislukt - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Zorg ervoor dat de ingevoerde URL geldig is en dat de internetverbinding van het apparaat goed is. - - - Reboot device - Apparaat opnieuw opstarten - - - Start over - Begin opnieuw - - - - SetupWidget - - Finish Setup - Installatie voltooien - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Koppel uw apparaat met comma connect (connect.comma.ai) en claim uw comma prime-aanbieding. - - - Pair device - Apparaat koppelen - - - - Sidebar - - CONNECT - VERBINDING - - - OFFLINE - OFFLINE - - - ONLINE - ONLINE - - - ERROR - FOUT - - - TEMP - TEMP - - - HIGH - HOOG - - - GOOD - GOED - - - OK - OK - - - VEHICLE - VOERTUIG - - - NO - GEEN - - - PANDA - PANDA - - - GPS - GPS - - - SEARCH - ZOEKEN - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - 4G - - - 5G - 5G - - - - SoftwarePanel - - Git Branch - Git Branch - - - Git Commit - Git Commit - - - OS Version - OS Versie - - - Version - Versie - - - Last Update Check - Laatste Updatecontrole - - - The last time openpilot successfully checked for an update. The updater only runs while the car is off. - De laatste keer dat openpilot met succes heeft gecontroleerd op een update. De updater werkt alleen als de auto is uitgeschakeld. - - - Check for Update - Controleer op Updates - - - CHECKING - CONTROLEER - - - Switch Branch - Branch Verwisselen - - - ENTER - INVOEREN - - - The new branch will be pulled the next time the updater runs. - Tijdens de volgende update wordt de nieuwe branch opgehaald. - - - Enter branch name - Voer branch naam in - - - Uninstall %1 - Verwijder %1 - - - UNINSTALL - VERWIJDER - - - Are you sure you want to uninstall? - Weet u zeker dat u de installatie ongedaan wilt maken? - - - failed to fetch update - ophalen van update mislukt - - - CHECK - CONTROLEER - - - Updates are only downloaded while the car is off. - - - - Current Version - - - - Download - - - - Install Update - - - - INSTALL - - - - Target Branch - - - - SELECT - - - - Select a branch - - - - - SshControl - - SSH Keys - SSH Sleutels - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Waarschuwing: dit geeft SSH toegang tot alle openbare sleutels in uw GitHub-instellingen. Voer nooit een andere GitHub-gebruikersnaam in dan die van uzelf. Een medewerker van comma zal u NOOIT vragen om zijn GitHub-gebruikersnaam toe te voegen. - - - ADD - TOEVOEGEN - - - Enter your GitHub username - Voer uw GitHub gebruikersnaam in - - - LOADING - LADEN - - - REMOVE - VERWIJDEREN - - - Username '%1' has no keys on GitHub - Gebruikersnaam '%1' heeft geen SSH sleutels op GitHub - - - Request timed out - Time-out van aanvraag - - - Username '%1' doesn't exist on GitHub - Gebruikersnaam '%1' bestaat niet op GitHub - - - - SshToggle - - Enable SSH - SSH Inschakelen - - - - TermsPage - - Terms & Conditions - Algemene Voorwaarden - - - Decline - Afwijzen - - - Scroll to accept - Scroll om te accepteren - - - Agree - Akkoord - - - - TogglesPanel - - Enable openpilot - openpilot Inschakelen - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Gebruik het openpilot-systeem voor adaptieve cruisecontrol en rijstrookassistentie. Uw aandacht is te allen tijde vereist om deze functie te gebruiken. Het wijzigen van deze instelling wordt van kracht wanneer de auto wordt uitgeschakeld. - - - Enable Lane Departure Warnings - Waarschuwingen bij Verlaten Rijstrook Inschakelen - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Ontvang waarschuwingen om terug naar de rijstrook te sturen wanneer uw voertuig over een gedetecteerde rijstrookstreep drijft zonder dat de richtingaanwijzer wordt geactiveerd terwijl u harder rijdt dan 50 km/u (31 mph). - - - Use Metric System - Gebruik Metrisch Systeem - - - Display speed in km/h instead of mph. - Geef snelheid weer in km/u in plaats van mph. - - - Record and Upload Driver Camera - Opnemen en Uploaden van de Bestuurders Camera - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Upload gegevens van de bestuurders camera en help het algoritme voor het monitoren van de bestuurder te verbeteren. - - - Disengage on Accelerator Pedal - Deactiveren Met Gaspedaal - - - When enabled, pressing the accelerator pedal will disengage openpilot. - Indien ingeschakeld, zal het indrukken van het gaspedaal openpilot deactiveren. - - - Show ETA in 24h Format - Toon verwachte aankomsttijd in 24-uurs formaat - - - Use 24h format instead of am/pm - Gebruik 24-uurs formaat in plaats van AM en PM - - - Show Map on Left Side of UI - Toon kaart aan linkerkant van het scherm - - - Show map on left side when in split screen view. - Toon kaart links in gesplitste schermweergave. - - - openpilot Longitudinal Control - openpilot Longitudinale Controle - - - openpilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB! - openpilot zal de radar van de auto uitschakelen en de controle over gas en remmen overnemen. Waarschuwing: hierdoor wordt AEB (automatische noodrem) uitgeschakeld! - - - 🌮 End-to-end longitudinal (extremely alpha) 🌮 - - - - Experimental openpilot Longitudinal Control - - - - <b>WARNING: openpilot longitudinal control is experimental for this car and will disable AEB.</b> - - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would. Super experimental. - - - - openpilot longitudinal control is not currently available for this car. - - - - Enable experimental longitudinal control to enable this. - - - - - Updater - - Update Required - Update Vereist - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Een update van het besturingssysteem is vereist. Verbind je apparaat met Wi-Fi voor de snelste update-ervaring. De downloadgrootte is ongeveer 1 GB. - - - Connect to Wi-Fi - Maak verbinding met Wi-Fi - - - Install - Installeer - - - Back - Terug - - - Loading... - Aan het laden... - - - Reboot - Opnieuw Opstarten - - - Update failed - Update mislukt - - - - WifiUI - - Scanning for networks... - Scannen naar netwerken... - - - CONNECTING... - VERBINDEN... - - - FORGET - VERGETEN - - - Forget Wi-Fi Network "%1"? - Vergeet Wi-Fi Netwerk "%1"? - - - diff --git a/selfdrive/ui/translations/main_pl.ts b/selfdrive/ui/translations/main_pl.ts deleted file mode 100644 index 4f8b03ef50d02b..00000000000000 --- a/selfdrive/ui/translations/main_pl.ts +++ /dev/null @@ -1,1124 +0,0 @@ - - - - - AbstractAlert - - Close - Zamknij - - - Snooze Update - Zaktualizuj później - - - Reboot and Update - Uruchom ponownie i zaktualizuj - - - - AdvancedNetworking - - Back - Wróć - - - Enable Tethering - Włącz hotspot osobisty - - - Tethering Password - Hasło do hotspotu - - - EDIT - EDYTUJ - - - Enter new tethering password - Wprowadź nowe hasło do hotspotu - - - IP Address - Adres IP - - - Enable Roaming - Włącz roaming danych - - - APN Setting - Ustawienia APN - - - Enter APN - Wprowadź APN - - - leave blank for automatic configuration - Pozostaw puste, aby użyć domyślnej konfiguracji - - - Cellular Metered - - - - Prevent large data uploads when on a metered connection - - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - SPEED - PRĘDKOŚĆ - - - LIMIT - OGRANICZENIE - - - - ConfirmationDialog - - Ok - Ok - - - Cancel - Anuluj - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - Aby korzystać z openpilota musisz zaakceptować regulamin. - - - Back - Wróć - - - Decline, uninstall %1 - Odrzuć, odinstaluj %1 - - - - DevicePanel - - Dongle ID - ID adaptera - - - N/A - N/A - - - Serial - Numer seryjny - - - Driver Camera - Kamera kierowcy - - - PREVIEW - PODGLĄD - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Wyświetl podgląd z kamery skierowanej na kierowcę, aby upewnić się, że monitoring kierowcy ma dobry zakres widzenia. (pojazd musi być wyłączony) - - - Reset Calibration - Zresetuj kalibrację - - - RESET - ZRESETUJ - - - Are you sure you want to reset calibration? - Czy na pewno chcesz zresetować kalibrację? - - - Review Training Guide - Zapoznaj się z samouczkiem - - - REVIEW - ZAPOZNAJ SIĘ - - - Review the rules, features, and limitations of openpilot - Zapoznaj się z zasadami, funkcjami i ograniczeniami openpilota - - - Are you sure you want to review the training guide? - Czy na pewno chcesz się zapoznać z samouczkiem? - - - Regulatory - Regulacja - - - VIEW - WIDOK - - - Change Language - Zmień język - - - CHANGE - ZMIEŃ - - - Select a language - Wybierz język - - - Reboot - Uruchom ponownie - - - Power Off - Wyłącz - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot wymaga, aby urządzenie było zamontowane z maksymalnym odchyłem 4° poziomo, 5° w górę oraz 8° w dół. openpilot jest ciągle kalibrowany, rzadko konieczne jest resetowania urządzenia. - - - Your device is pointed %1° %2 and %3° %4. - Twoje urządzenie jest skierowane %1° %2 oraz %3° %4. - - - down - w dół - - - up - w górę - - - left - w lewo - - - right - w prawo - - - Are you sure you want to reboot? - Czy na pewno chcesz uruchomić ponownie urządzenie? - - - Disengage to Reboot - Aby uruchomić ponownie, odłącz sterowanie - - - Are you sure you want to power off? - Czy na pewno chcesz wyłączyć urządzenie? - - - Disengage to Power Off - Aby wyłączyć urządzenie, odłącz sterowanie - - - - DriveStats - - Drives - Przejazdy - - - Hours - Godziny - - - ALL TIME - CAŁKOWICIE - - - PAST WEEK - OSTATNI TYDZIEŃ - - - KM - KM - - - Miles - Mile - - - - DriverViewScene - - camera starting - uruchamianie kamery - - - - InputDialog - - Cancel - Anuluj - - - Need at least %n character(s)! - - Wpisana wartość powinna składać się przynajmniej z %n znaku! - Wpisana wartość powinna skłądać się przynajmniej z %n znaków! - Wpisana wartość powinna skłądać się przynajmniej z %n znaków! - - - - - Installer - - Installing... - Instalowanie... - - - Receiving objects: - Odbieranie obiektów: - - - Resolving deltas: - Rozwiązywanie różnic: - - - Updating files: - Aktualizacja plików: - - - - MapETA - - eta - przewidywany czas - - - min - min - - - hr - godz - - - km - km - - - mi - mi - - - - MapInstructions - - km - km - - - m - m - - - mi - mi - - - ft - ft - - - - MapPanel - - Current Destination - Miejsce docelowe - - - CLEAR - WYCZYŚĆ - - - Recent Destinations - Ostatnie miejsca docelowe - - - Try the Navigation Beta - Wypróbuj nawigację w wersji beta - - - Get turn-by-turn directions displayed and more with a comma -prime subscription. Sign up now: https://connect.comma.ai - Odblokuj nawigację zakręt po zakęcie i wiele więcej subskrybując -comma prime. Zarejestruj się teraz: https://connect.comma.ai - - - No home -location set - Lokalizacja domu -nie została ustawiona - - - No work -location set - Miejsce pracy -nie zostało ustawione - - - no recent destinations - brak ostatnich miejsc docelowych - - - - MapWindow - - Map Loading - Ładowanie Mapy - - - Waiting for GPS - Oczekiwanie na sygnał GPS - - - - MultiOptionDialog - - Select - Wybierz - - - Cancel - Anuluj - - - - Networking - - Advanced - Zaawansowane - - - Enter password - Wprowadź hasło - - - for "%1" - do "%1" - - - Wrong password - Niepoprawne hasło - - - - OffroadHome - - UPDATE - UAKTUALNIJ - - - ALERTS - ALERTY - - - ALERT - ALERT - - - - PairingPopup - - Pair your device to your comma account - Sparuj swoje urzadzenie ze swoim kontem comma - - - Go to https://connect.comma.ai on your phone - Wejdź na stronę https://connect.comma.ai na swoim telefonie - - - Click "add new device" and scan the QR code on the right - Kliknij "add new device" i zeskanuj kod QR znajdujący się po prawej stronie - - - Bookmark connect.comma.ai to your home screen to use it like an app - Dodaj connect.comma.ai do zakładek na swoim ekranie początkowym, aby korzystać z niej jak z aplikacji - - - - PrimeAdWidget - - Upgrade Now - Uaktualnij teraz - - - Become a comma prime member at connect.comma.ai - Zostań członkiem comma prime na connect.comma.ai - - - PRIME FEATURES: - FUNKCJE PRIME: - - - Remote access - Zdalny dostęp - - - 1 year of storage - 1 rok przechowywania danych - - - Developer perks - Udogodnienia dla programistów - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ ZASUBSKRYBOWANO - - - comma prime - comma prime - - - CONNECT.COMMA.AI - CONNECT.COMMA.AI - - - COMMA POINTS - COMMA POINTS - - - - QObject - - Reboot - Uruchom Ponownie - - - Exit - Wyjdź - - - dashcam - wideorejestrator - - - openpilot - openpilot - - - %n minute(s) ago - - %n minutę temu - %n minuty temu - %n minut temu - - - - %n hour(s) ago - - % godzinę temu - %n godziny temu - %n godzin temu - - - - %n day(s) ago - - %n dzień temu - %n dni temu - %n dni temu - - - - - Reset - - Reset failed. Reboot to try again. - Wymazywanie zakończone niepowodzeniem. Aby spróbować ponownie, uruchom ponownie urządzenie. - - - Are you sure you want to reset your device? - Czy na pewno chcesz wymazać urządzenie? - - - Resetting device... - Wymazywanie urządzenia... - - - System Reset - Przywróć do ustawień fabrycznych - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Przywracanie do ustawień fabrycznych. Wciśnij potwierdź, aby usunąć wszystkie dane oraz ustawienia. Wciśnij anuluj, aby wznowić uruchamianie. - - - Cancel - Anuluj - - - Reboot - Uruchom ponownie - - - Confirm - Potwiedź - - - Unable to mount data partition. Press confirm to reset your device. - Partycja nie została zamontowana poprawnie. Wciśnij potwierdź, aby uruchomić ponownie urządzenie. - - - - RichTextDialog - - Ok - Ok - - - - SettingsWindow - - × - x - - - Device - Urządzenie - - - Network - Sieć - - - Toggles - Przełączniki - - - Software - Oprogramowanie - - - Navigation - Nawigacja - - - - Setup - - WARNING: Low Voltage - OSTRZEŻENIE: Niskie Napięcie - - - Power your device in a car with a harness or proceed at your own risk. - Podłącz swoje urządzenie do zasilania poprzez podłączenienie go do pojazdu lub kontynuuj na własną odpowiedzialność. - - - Power off - Wyłącz - - - Continue - Kontynuuj - - - Getting Started - Zacznij - - - Before we get on the road, let’s finish installation and cover some details. - Zanim ruszysz w drogę, dokończ instalację i podaj kilka szczegółów. - - - Connect to Wi-Fi - Połącz z Wi-Fi - - - Back - Wróć - - - Continue without Wi-Fi - Kontynuuj bez połączenia z Wif-Fi - - - Waiting for internet - Oczekiwanie na połączenie sieciowe - - - Choose Software to Install - Wybierz oprogramowanie do instalacji - - - Dashcam - Wideorejestrator - - - Custom Software - Własne oprogramowanie - - - Enter URL - Wprowadź adres URL - - - for Custom Software - do własnego oprogramowania - - - Downloading... - Pobieranie... - - - Download Failed - Pobieranie nie powiodło się - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Upewnij się, że wpisany adres URL jest poprawny, a połączenie internetowe działa poprawnie. - - - Reboot device - Uruchom ponownie - - - Start over - Zacznij od początku - - - - SetupWidget - - Finish Setup - Zakończ konfigurację - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Sparuj swoje urządzenie z comma connect (connect.comma.ai) i wybierz swoją ofertę comma prime. - - - Pair device - Sparuj urządzenie - - - - Sidebar - - CONNECT - POŁĄCZENIE - - - OFFLINE - OFFLINE - - - ONLINE - ONLINE - - - ERROR - BŁĄD - - - TEMP - TEMP - - - HIGH - WYSOKA - - - GOOD - DOBRA - - - OK - OK - - - VEHICLE - POJAZD - - - NO - BRAK - - - PANDA - PANDA - - - GPS - GPS - - - SEARCH - SZUKAJ - - - -- - -- - - - Wi-Fi - Wi-FI - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Git Branch - Gałąź Git - - - Git Commit - Git commit - - - OS Version - Wersja systemu - - - Version - Wersja - - - Last Update Check - Ostatnie sprawdzenie aktualizacji - - - The last time openpilot successfully checked for an update. The updater only runs while the car is off. - Ostatni raz kiedy openpilot znalazł aktualizację. Aktualizator może być uruchomiony wyłącznie wtedy, kiedy pojazd jest wyłączony. - - - Check for Update - Sprawdź uaktualnienia - - - CHECKING - SPRAWDZANIE - - - Switch Branch - Zmień gąłąź - - - ENTER - WPROWADŹ - - - The new branch will be pulled the next time the updater runs. - Nowa gałąź będzie pobrana przy następnym uruchomieniu aktualizatora. - - - Enter branch name - Wprowadź nazwę gałęzi - - - Uninstall %1 - Odinstaluj %1 - - - UNINSTALL - ODINSTALUJ - - - Are you sure you want to uninstall? - Czy na pewno chcesz odinstalować? - - - failed to fetch update - pobieranie aktualizacji zakończone niepowodzeniem - - - CHECK - SPRAWDŹ - - - Updates are only downloaded while the car is off. - - - - Current Version - - - - Download - - - - Install Update - - - - INSTALL - - - - Target Branch - - - - SELECT - - - - Select a branch - - - - - SshControl - - SSH Keys - Klucze SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Ostrzeżenie: To spowoduje przekazanie dostępu do wszystkich Twoich publicznych kuczy z ustawień GitHuba. Nigdy nie wprowadzaj nazwy użytkownika innej niż swoja. Pracownik comma NIGDY nie poprosi o dodanie swojej nazwy uzytkownika. - - - ADD - DODAJ - - - Enter your GitHub username - Wpisz swoją nazwę użytkownika GitHub - - - LOADING - ŁADOWANIE - - - REMOVE - USUŃ - - - Username '%1' has no keys on GitHub - Użytkownik '%1' nie posiada żadnych kluczy na GitHubie - - - Request timed out - Limit czasu rządania - - - Username '%1' doesn't exist on GitHub - Użytkownik '%1' nie istnieje na GitHubie - - - - SshToggle - - Enable SSH - Włącz SSH - - - - TermsPage - - Terms & Conditions - Regulamin - - - Decline - Odrzuć - - - Scroll to accept - Przewiń w dół, aby zaakceptować - - - Agree - Zaakceptuj - - - - TogglesPanel - - Enable openpilot - Włącz openpilota - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Użyj openpilota do zachowania bezpiecznego odstępu między pojazdami i do asystowania w utrzymywaniu pasa ruchu. Twoja pełna uwaga jest wymagana przez cały czas korzystania z tej funkcji. Ustawienie to może być wdrożone wyłącznie wtedy, gdy pojazd jest wyłączony. - - - Enable Lane Departure Warnings - Włącz ostrzeganie przed zmianą pasa ruchu - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Otrzymuj alerty o powrocie na właściwy pas, kiedy Twój pojazd przekroczy linię bez włączonego kierunkowskazu jadąc powyżej 50 km/h (31 mph). - - - Use Metric System - Korzystaj z systemu metrycznego - - - Display speed in km/h instead of mph. - Wyświetl prędkość w km/h zamiast mph. - - - Record and Upload Driver Camera - Nagraj i prześlij nagranie z kamery kierowcy - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Prześlij dane z kamery skierowanej na kierowcę i pomóż poprawiać algorytm monitorowania kierowcy. - - - Disengage on Accelerator Pedal - Odłącz poprzez naciśnięcie gazu - - - When enabled, pressing the accelerator pedal will disengage openpilot. - Po włączeniu, naciśnięcie na pedał gazu odłączy openpilota. - - - Show ETA in 24h Format - Pokaż oczekiwany czas dojazdu w formacie 24-godzinnym - - - Use 24h format instead of am/pm - Korzystaj z formatu 24-godzinnego zamiast 12-godzinnego - - - Show Map on Left Side of UI - Pokaż mapę po lewej stronie ekranu - - - Show map on left side when in split screen view. - Pokaż mapę po lewej stronie kiedy ekran jest podzielony. - - - openpilot Longitudinal Control - Kontrola wzdłużna openpilota - - - openpilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB! - openpilot wyłączy radar samochodu i przejmie kontrolę nad gazem i hamulcem. Ostrzeżenie: wyłączony zostanie system AEB! - - - 🌮 End-to-end longitudinal (extremely alpha) 🌮 - - - - Experimental openpilot Longitudinal Control - - - - <b>WARNING: openpilot longitudinal control is experimental for this car and will disable AEB.</b> - - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would. Super experimental. - - - - openpilot longitudinal control is not currently available for this car. - - - - Enable experimental longitudinal control to enable this. - - - - - Updater - - Update Required - Wymagana Aktualizacja - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Wymagana aktualizacja systemu operacyjnego. Aby przyspieszyć proces aktualizacji połącz swoje urzeądzenie do Wi-Fi. Rozmiar pobieranej paczki wynosi około 1GB. - - - Connect to Wi-Fi - Połącz się z Wi-Fi - - - Install - Zainstaluj - - - Back - Wróć - - - Loading... - Ładowanie... - - - Reboot - Uruchom ponownie - - - Update failed - Aktualizacja nie powiodła się - - - - WifiUI - - Scanning for networks... - Wyszukiwanie sieci... - - - CONNECTING... - ŁĄCZENIE... - - - FORGET - ZAPOMNIJ - - - Forget Wi-Fi Network "%1"? - Czy chcesz zapomnieć sieć "%1"? - - - diff --git a/selfdrive/ui/translations/main_pt-BR.ts b/selfdrive/ui/translations/main_pt-BR.ts deleted file mode 100644 index 1500f07e63709a..00000000000000 --- a/selfdrive/ui/translations/main_pt-BR.ts +++ /dev/null @@ -1,1139 +0,0 @@ - - - - - AbstractAlert - - Close - Fechar - - - Snooze Update - Adiar Atualização - - - Reboot and Update - Reiniciar e Atualizar - - - - AdvancedNetworking - - Back - Voltar - - - Enable Tethering - Ativar Tether - - - Tethering Password - Senha Tethering - - - EDIT - EDITAR - - - Enter new tethering password - Insira nova senha tethering - - - IP Address - Endereço IP - - - Enable Roaming - Ativar Roaming - - - APN Setting - APN Config - - - Enter APN - Insira APN - - - leave blank for automatic configuration - deixe em branco para configuração automática - - - Cellular Metered - Plano de Dados Limitado - - - Prevent large data uploads when on a metered connection - Evite grandes uploads de dados quando estiver em uma conexão limitada - - - Hidden Network - Rede Oculta - - - CONNECT - CONECTE - - - Enter SSID - Digite o SSID - - - Enter password - Insira a senha - - - for "%1" - para "%1" - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - LIMITE - - - - ConfirmationDialog - - Ok - OK - - - Cancel - Cancelar - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - Você precisa aceitar os Termos e Condições para utilizar openpilot. - - - Back - Voltar - - - Decline, uninstall %1 - Rejeitar, desintalar %1 - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - N/A - - - Serial - Serial - - - Driver Camera - Câmera do Motorista - - - PREVIEW - VER - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Pré-visualizar a câmera voltada para o motorista para garantir que o monitoramento do sistema tenha uma boa visibilidade (veículo precisa estar desligado) - - - Reset Calibration - Reinicializar Calibragem - - - RESET - RESET - - - Are you sure you want to reset calibration? - Tem certeza que quer resetar a calibragem? - - - Review Training Guide - Revisar Guia de Treinamento - - - REVIEW - REVISAR - - - Review the rules, features, and limitations of openpilot - Revisar regras, aprimoramentos e limitações do openpilot - - - Are you sure you want to review the training guide? - Tem certeza que quer rever o treinamento? - - - Regulatory - Regulatório - - - VIEW - VER - - - Change Language - Alterar Idioma - - - CHANGE - ALTERAR - - - Select a language - Selecione o Idioma - - - Reboot - Reiniciar - - - Power Off - Desligar - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - O openpilot requer que o dispositivo seja montado dentro de 4° esquerda ou direita e dentro de 5° para cima ou 9° para baixo. O openpilot está continuamente calibrando, resetar raramente é necessário. - - - Your device is pointed %1° %2 and %3° %4. - Seu dispositivo está montado %1° %2 e %3° %4. - - - down - baixo - - - up - cima - - - left - esquerda - - - right - direita - - - Are you sure you want to reboot? - Tem certeza que quer reiniciar? - - - Disengage to Reboot - Desacione para Reiniciar - - - Are you sure you want to power off? - Tem certeza que quer desligar? - - - Disengage to Power Off - Desacione para Desligar - - - Reset - Resetar - - - Review - Revisar - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Pareie seu dispositivo com comma connect (connect.comma.ai) e reivindique sua oferta de comma prime. - - - Pair Device - Parear Dispositivo - - - PAIR - PAREAR - - - - DriverViewWindow - - camera starting - câmera iniciando - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - MODO EXPERIMENTAL ON - - - CHILL MODE ON - MODO CHILL ON - - - - InputDialog - - Cancel - Cancelar - - - Need at least %n character(s)! - - Necessita no mínimo %n caractere! - Necessita no mínimo %n caracteres! - - - - - Installer - - Installing... - Instalando... - - - - MultiOptionDialog - - Select - Selecione - - - Cancel - Cancelar - - - - Networking - - Advanced - Avançado - - - Enter password - Insira a senha - - - for "%1" - para "%1" - - - Wrong password - Senha incorreta - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - Conecte-se imediatamente à internet para verificar se há atualizações. Se você não se conectar à internet em %1 não será possível acionar o openpilot. - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - Conecte-se à internet para verificar se há atualizações. O openpilot não será iniciado automaticamente até que ele se conecte à internet para verificar se há atualizações. - - - Unable to download updates -%1 - Não é possível baixar atualizações -%1 - - - Taking camera snapshots. System won't start until finished. - Tirando fotos da câmera. O sistema não será iniciado até terminar. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - Uma atualização para o sistema operacional do seu dispositivo está sendo baixada em segundo plano. Você será solicitado a atualizar quando estiver pronto para instalar. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - Falha ao registrar o dispositivo. Ele não se conectará ou fará upload para os servidores comma.ai e não receberá suporte da comma.ai. Se este for um dispositivo oficial, visite https://comma.ai/support. - - - NVMe drive not mounted. - Unidade NVMe não montada. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - Unidade NVMe não suportada detectada. O dispositivo pode consumir significativamente mais energia e superaquecimento devido ao NVMe não suportado. - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - O openpilot não conseguiu identificar o seu carro. Seu carro não é suportado ou seus ECUs não são reconhecidos. Envie um pull request para adicionar as versões de firmware ao veículo adequado. Precisa de ajuda? Junte-se discord.comma.ai. - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - O openpilot não conseguiu identificar o seu carro. Verifique a integridade dos cabos e certifique-se de que todas as conexões estejam seguras, especialmente se o comma power está totalmente inserido na porta OBD-II do veículo. Precisa de ajuda? Junte-se discord.comma.ai. - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - O openpilot detectou uma mudança na posição de montagem do dispositivo. Verifique se o dispositivo está totalmente encaixado no suporte e se o suporte está firmemente preso ao para-brisa. - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - Temperatura do dispositivo muito alta. O sistema está sendo resfriado antes de iniciar. A temperatura atual do componente interno é: %1 - - - - OffroadHome - - UPDATE - ATUALIZAÇÃO - - - ALERTS - ALERTAS - - - ALERT - ALERTA - - - - OnroadAlerts - - openpilot Unavailable - openpilot Indisponível - - - Waiting for controls to start - Aguardando controles para iniciar - - - TAKE CONTROL IMMEDIATELY - ASSUMA IMEDIATAMENTE - - - Controls Unresponsive - Controles Não Respondem - - - Reboot Device - Reinicie o Dispositivo - - - - PairingPopup - - Pair your device to your comma account - Pareie seu dispositivo à sua conta comma - - - Go to https://connect.comma.ai on your phone - navegue até https://connect.comma.ai no seu telefone - - - Click "add new device" and scan the QR code on the right - Clique "add new device" e escaneie o QR code a seguir - - - Bookmark connect.comma.ai to your home screen to use it like an app - Salve connect.comma.ai como sua página inicial para utilizar como um app - - - - ParamControl - - Cancel - Cancelar - - - Enable - Ativar - - - - PrimeAdWidget - - Upgrade Now - Atualizar Agora - - - Become a comma prime member at connect.comma.ai - Seja um membro comma prime em connect.comma.ai - - - PRIME FEATURES: - BENEFÍCIOS PRIME: - - - Remote access - Acesso remoto (proxy comma) - - - 24/7 LTE connectivity - Conectividade LTE (só nos EUA) - - - 1 year of drive storage - 1 ano de dados em nuvem - - - Remote snapshots - Captura remota - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ INSCRITO - - - comma prime - comma prime - - - - QObject - - Reboot - Reiniciar - - - Exit - Sair - - - openpilot - openpilot - - - %n minute(s) ago - - há %n minuto - há %n minutos - - - - %n hour(s) ago - - há %n hora - há %n horas - - - - %n day(s) ago - - há %n dia - há %n dias - - - - now - agora - - - - Reset - - Reset failed. Reboot to try again. - Reset falhou. Reinicie para tentar novamente. - - - Are you sure you want to reset your device? - Tem certeza que quer resetar seu dispositivo? - - - System Reset - Resetar Sistema - - - Cancel - Cancelar - - - Reboot - Reiniciar - - - Confirm - Confirmar - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - Não é possível montar a partição de dados. Partição corrompida. Confirme para apagar e redefinir o dispositivo. - - - Resetting device... -This may take up to a minute. - Redefinindo o dispositivo -Isso pode levar até um minuto. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Reinicialização do sistema acionada. Pressione confirmar para apagar todo o conteúdo e configurações. Pressione cancel para retomar a inicialização. - - - - SettingsWindow - - × - × - - - Device - Dispositivo - - - Network - Rede - - - Toggles - Ajustes - - - Software - Software - - - - Setup - - WARNING: Low Voltage - ALERTA: Baixa Voltagem - - - Power your device in a car with a harness or proceed at your own risk. - Ligue seu dispositivo em um carro com um chicote ou prossiga por sua conta e risco. - - - Power off - Desligar - - - Continue - Continuar - - - Getting Started - Começando - - - Before we get on the road, let’s finish installation and cover some details. - Antes de pegarmos a estrada, vamos terminar a instalação e cobrir alguns detalhes. - - - Connect to Wi-Fi - Conectar ao Wi-Fi - - - Back - Voltar - - - Continue without Wi-Fi - Continuar sem Wi-Fi - - - Waiting for internet - Esperando pela internet - - - Enter URL - Preencher URL - - - for Custom Software - para o Software Customizado - - - Downloading... - Baixando... - - - Download Failed - Download Falhou - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Garanta que a URL inserida é valida, e uma boa conexão à internet. - - - Reboot device - Reiniciar Dispositivo - - - Start over - Inicializar - - - No custom software found at this URL. - Não há software personalizado nesta URL. - - - Something went wrong. Reboot the device. - Algo deu errado. Reinicie o dispositivo. - - - Select a language - Selecione o Idioma - - - Choose Software to Install - Escolha o Software a ser Instalado - - - openpilot - openpilot - - - Custom Software - Software Customizado - - - - SetupWidget - - Finish Setup - Concluir - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Pareie seu dispositivo com comma connect (connect.comma.ai) e reivindique sua oferta de comma prime. - - - Pair device - Parear dispositivo - - - - Sidebar - - CONNECT - CONEXÃO - - - OFFLINE - OFFLINE - - - ONLINE - ONLINE - - - ERROR - ERRO - - - TEMP - TEMP - - - HIGH - ALTA - - - GOOD - BOA - - - OK - OK - - - VEHICLE - VEÍCULO - - - NO - SEM - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - Atualizações baixadas durante o motor desligado. - - - Current Version - Versão Atual - - - Download - Download - - - Install Update - Instalar Atualização - - - INSTALL - INSTALAR - - - Target Branch - Alterar Branch - - - SELECT - SELECIONE - - - Select a branch - Selecione uma branch - - - UNINSTALL - REMOVER - - - Uninstall %1 - Desinstalar o %1 - - - Are you sure you want to uninstall? - Tem certeza que quer desinstalar? - - - CHECK - VERIFICAR - - - Uninstall - Desinstalar - - - failed to check for update - falha ao verificar por atualizações - - - up to date, last checked %1 - atualizado, última verificação %1 - - - DOWNLOAD - BAIXAR - - - update available - atualização disponível - - - never - nunca - - - - SshControl - - SSH Keys - Chave SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Aviso: isso concede acesso SSH a todas as chaves públicas nas configurações do GitHub. Nunca insira um nome de usuário do GitHub que não seja o seu. Um funcionário da comma NUNCA pedirá que você adicione seu nome de usuário do GitHub. - - - ADD - ADICIONAR - - - Enter your GitHub username - Insira seu nome de usuário do GitHub - - - LOADING - CARREGANDO - - - REMOVE - REMOVER - - - Username '%1' has no keys on GitHub - Usuário "%1” não possui chaves no GitHub - - - Request timed out - A solicitação expirou - - - Username '%1' doesn't exist on GitHub - Usuário '%1' não existe no GitHub - - - - SshToggle - - Enable SSH - Habilitar SSH - - - - TermsPage - - Terms & Conditions - Termos & Condições - - - Decline - Declinar - - - Scroll to accept - Role a tela para aceitar - - - Agree - Concordo - - - - TogglesPanel - - Enable openpilot - Ativar openpilot - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Use o sistema openpilot para controle de cruzeiro adaptativo e assistência ao motorista de manutenção de faixa. Sua atenção é necessária o tempo todo para usar esse recurso. A alteração desta configuração tem efeito quando o carro é desligado. - - - Enable Lane Departure Warnings - Ativar Avisos de Saída de Faixa - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Receba alertas para voltar para a pista se o seu veículo sair da faixa e a seta não tiver sido acionada previamente quando em velocidades superiores a 50 km/h. - - - Use Metric System - Usar Sistema Métrico - - - Display speed in km/h instead of mph. - Exibir velocidade em km/h invés de mph. - - - Record and Upload Driver Camera - Gravar e Upload Câmera Motorista - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Upload dados da câmera voltada para o motorista e ajude a melhorar o algoritmo de monitoramentor. - - - Disengage on Accelerator Pedal - Desacionar com Pedal do Acelerador - - - When enabled, pressing the accelerator pedal will disengage openpilot. - Quando ativado, pressionar o pedal do acelerador desacionará o openpilot. - - - Experimental Mode - Modo Experimental - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - openpilot por padrão funciona em <b>modo chill</b>. modo Experimental ativa <b>recursos de nível-embrionário</b> que não estão prontos para o modo chill. Recursos experimentais estão listados abaixo: - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - Deixe o modelo de IA controlar o acelerador e os freios. O openpilot irá dirigir como pensa que um humano faria, incluindo parar em sinais vermelhos e sinais de parada. Uma vez que o modelo de condução decide a velocidade a conduzir, a velocidade definida apenas funcionará como um limite superior. Este é um recurso de qualidade embrionária; erros devem ser esperados. - - - New Driving Visualization - Nova Visualização de Condução - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - O modo Experimental está atualmente indisponível para este carro já que o ACC original do carro é usado para controle longitudinal. - - - openpilot longitudinal control may come in a future update. - O controle longitudinal openpilot poderá vir em uma atualização futura. - - - openpilot Longitudinal Control (Alpha) - Controle Longitudinal openpilot (Embrionário) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - AVISO: o controle longitudinal openpilot está em estado embrionário para este carro e desativará a Frenagem Automática de Emergência (AEB). - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - Neste carro, o openpilot tem como padrão o ACC embutido do carro em vez do controle longitudinal do openpilot. Habilite isso para alternar para o controle longitudinal openpilot. Recomenda-se ativar o modo Experimental ao ativar o embrionário controle longitudinal openpilot. - - - Aggressive - Disputa - - - Standard - Neutro - - - Relaxed - Calmo - - - Driving Personality - Temperamento de Direção - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - Uma versão embrionária do controle longitudinal openpilot pode ser testada em conjunto com o modo Experimental, em branches que não sejam de produção. - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - Habilite o controle longitudinal (embrionário) openpilot para permitir o modo Experimental. - - - End-to-End Longitudinal Control - Controle Longitudinal de Ponta a Ponta - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - Neutro é o recomendado. No modo disputa o openpilot seguirá o carro da frente mais de perto e será mais agressivo com a aceleração e frenagem. No modo calmo o openpilot se manterá mais longe do carro da frente. Em carros compatíveis, você pode alternar esses temperamentos com o botão de distância do volante. - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - A visualização de condução fará a transição para a câmera grande angular voltada para a estrada em baixas velocidades para mostrar melhor algumas curvas. O logotipo do modo Experimental também será mostrado no canto superior direito. - - - Always-On Driver Monitoring - Monitoramento do Motorista Sempre Ativo - - - Enable driver monitoring even when openpilot is not engaged. - Habilite o monitoramento do motorista mesmo quando o openpilot não estiver acionado. - - - - Updater - - Update Required - Atualização Necessária - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Uma atualização do sistema operacional é necessária. Conecte seu dispositivo ao Wi-Fi para a experiência de atualização mais rápida. O tamanho do download é de aproximadamente 1GB. - - - Connect to Wi-Fi - Conecte-se ao Wi-Fi - - - Install - Instalar - - - Back - Voltar - - - Loading... - Carregando... - - - Reboot - Reiniciar - - - Update failed - Falha na atualização - - - - WiFiPromptWidget - - Setup Wi-Fi - Configurar Wi-Fi - - - Connect to Wi-Fi to upload driving data and help improve openpilot - Conecte se ao Wi-Fi para realizar upload de dados de condução e ajudar a melhorar o openpilot - - - Open Settings - Abrir Configurações - - - Ready to upload - Pronto para upload - - - Training data will be pulled periodically while your device is on Wi-Fi - Os dados de treinamento serão extraídos periodicamente enquanto o dispositivo estiver no Wi-Fi - - - - WifiUI - - Scanning for networks... - Procurando redes... - - - CONNECTING... - CONECTANDO... - - - FORGET - ESQUECER - - - Forget Wi-Fi Network "%1"? - Esquecer Rede Wi-Fi "%1"? - - - Forget - Esquecer - - - diff --git a/selfdrive/ui/translations/main_th.ts b/selfdrive/ui/translations/main_th.ts deleted file mode 100644 index bae326d5324efa..00000000000000 --- a/selfdrive/ui/translations/main_th.ts +++ /dev/null @@ -1,1135 +0,0 @@ - - - - - AbstractAlert - - Close - ปิด - - - Snooze Update - เลื่อนการอัปเดต - - - Reboot and Update - รีบูตและอัปเดต - - - - AdvancedNetworking - - Back - ย้อนกลับ - - - Enable Tethering - ปล่อยฮอตสปอต - - - Tethering Password - รหัสผ่านฮอตสปอต - - - EDIT - แก้ไข - - - Enter new tethering password - ป้อนรหัสผ่านฮอตสปอตใหม่ - - - IP Address - หมายเลขไอพี - - - Enable Roaming - เปิดใช้งานโรมมิ่ง - - - APN Setting - ตั้งค่า APN - - - Enter APN - ป้อนค่า APN - - - leave blank for automatic configuration - เว้นว่างเพื่อตั้งค่าอัตโนมัติ - - - Cellular Metered - ลดการส่งข้อมูลผ่านเซลลูล่าร์ - - - Prevent large data uploads when on a metered connection - ปิดการอัพโหลดข้อมูลขนาดใหญ่เมื่อเชื่อมต่อผ่านเซลลูล่าร์ - - - Hidden Network - เครือข่ายที่ซ่อนอยู่ - - - CONNECT - เชื่อมต่อ - - - Enter SSID - ป้อนค่า SSID - - - Enter password - ใส่รหัสผ่าน - - - for "%1" - สำหรับ "%1" - - - - AnnotatedCameraWidget - - km/h - กม./ชม. - - - mph - ไมล์/ชม. - - - MAX - สูงสุด - - - - ConfirmationDialog - - Ok - ตกลง - - - Cancel - ยกเลิก - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - คุณต้องยอมรับเงื่อนไขและข้อตกลง เพื่อใช้งาน openpilot - - - Back - ย้อนกลับ - - - Decline, uninstall %1 - ปฏิเสธ และถอนการติดตั้ง %1 - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - ไม่มี - - - Serial - ซีเรียล - - - Driver Camera - กล้องฝั่งคนขับ - - - PREVIEW - แสดงภาพ - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - ดูภาพตัวอย่างกล้องที่หันเข้าหาคนขับเพื่อให้แน่ใจว่าการตรวจสอบคนขับมีทัศนวิสัยที่ดี (รถต้องดับเครื่องยนต์) - - - Reset Calibration - รีเซ็ตการคาลิเบรท - - - RESET - รีเซ็ต - - - Are you sure you want to reset calibration? - คุณแน่ใจหรือไม่ว่าต้องการรีเซ็ตการคาลิเบรท? - - - Review Training Guide - ทบทวนคู่มือการใช้งาน - - - REVIEW - ทบทวน - - - Review the rules, features, and limitations of openpilot - ตรวจสอบกฎ คุณสมบัติ และข้อจำกัดของ openpilot - - - Are you sure you want to review the training guide? - คุณแน่ใจหรือไม่ว่าต้องการทบทวนคู่มือการใช้งาน? - - - Regulatory - ระเบียบข้อบังคับ - - - VIEW - ดู - - - Change Language - เปลี่ยนภาษา - - - CHANGE - เปลี่ยน - - - Select a language - เลือกภาษา - - - Reboot - รีบูต - - - Power Off - ปิดเครื่อง - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot กำหนดให้ติดตั้งอุปกรณ์ โดยสามารถเอียงด้านซ้ายหรือขวาไม่เกิน 4° และเอียงขึ้นด้านบนไม่เกิน 5° หรือเอียงลงด้านล่างไม่เกิน 9° openpilot ทำการคาลิเบรทอย่างต่อเนื่อง แทบจะไม่จำเป็นต้องทำการรีเซ็ตการคาลิเบรท - - - Your device is pointed %1° %2 and %3° %4. - อุปกรณ์ของคุณเอียงไปทาง %2 %1° และ %4 %3° - - - down - ด้านล่าง - - - up - ด้านบน - - - left - ด้านซ้าย - - - right - ด้านขวา - - - Are you sure you want to reboot? - คุณแน่ใจหรือไม่ว่าต้องการรีบูต? - - - Disengage to Reboot - ยกเลิกระบบช่วยขับเพื่อรีบูต - - - Are you sure you want to power off? - คุณแน่ใจหรือไม่ว่าต้องการปิดเครื่อง? - - - Disengage to Power Off - ยกเลิกระบบช่วยขับเพื่อปิดเครื่อง - - - Reset - รีเซ็ต - - - Review - ทบทวน - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - จับคู่อุปกรณ์ของคุณกับ comma connect (connect.comma.ai) และรับข้อเสนอ comma prime ของคุณ - - - Pair Device - จับคู่อุปกรณ์ - - - PAIR - จับคู่ - - - - DriverViewWindow - - camera starting - กำลังเปิดกล้อง - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - คุณกำลังใช้โหมดทดลอง - - - CHILL MODE ON - คุณกำลังใช้โหมดชิล - - - - InputDialog - - Cancel - ยกเลิก - - - Need at least %n character(s)! - - ต้องการอย่างน้อย %n ตัวอักษร! - - - - - Installer - - Installing... - กำลังติดตั้ง... - - - - MultiOptionDialog - - Select - เลือก - - - Cancel - ยกเลิก - - - - Networking - - Advanced - ขั้นสูง - - - Enter password - ใส่รหัสผ่าน - - - for "%1" - สำหรับ "%1" - - - Wrong password - รหัสผ่านผิด - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - อุณหภูมิของอุปกรณ์สูงเกินไป ระบบกำลังทำความเย็นก่อนเริ่ม อุณหภูมิของชิ้นส่วนภายในปัจจุบัน: %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - กรุณาเชื่อมต่ออินเตอร์เน็ตเพื่อตรวจสอบอัปเดทเดี๋ยวนี้ ถ้าคุณไม่เชื่อมต่ออินเตอร์เน็ต openpilot จะไม่ทำงานในอีก %1 - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - กรุณาเชื่อมต่ออินเตอร์เน็ตเพื่อตรวจสอบอัปเดท openpilot จะไม่เริ่มทำงานอัตโนมัติจนกว่าจะได้เชื่อมต่อกับอินเตอร์เน็ตเพื่อตรวจสอบอัปเดท - - - Unable to download updates -%1 - ไม่สามารถดาวน์โหลดอัพเดทได้ -%1 - - - Taking camera snapshots. System won't start until finished. - กล้องกำลังถ่ายภาพ ระบบจะไม่เริ่มทำงานจนกว่าจะเสร็จ - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - กำลังดาวน์โหลดอัปเดทสำหรับระบบปฏิบัติการอยู่เบื้องหลัง คุณจะได้รับการแจ้งเตือนเมื่อระบบพร้อมสำหรับการติดตั้ง - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - ไม่สามารถลงทะเบียนอุปกรณ์ได้ อุปกรณ์จะไม่สามารถเชื่อมต่อหรืออัปโหลดไปยังเซิร์ฟเวอร์ของ comma.ai ได้และจะไม่ได้รับการสนับสนุนจาก comma.ai ถ้านี่คืออุปกรณ์อย่างเป็นทางการ กรุณาติดต่อ https://comma.ai/support - - - NVMe drive not mounted. - ไม่ได้ติดตั้งไดร์ฟ NVMe - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - ตรวจพบไดร์ฟ NVMe ที่ไม่รองรับ อุปกรณ์อาจใช้พลังงานมากขึ้นและร้อนเกินไปเนื่องจากไดร์ฟ NVMe ที่ไม่รองรับ - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - openpilot ไม่สามารถระบุรถยนต์ของคุณได้ ระบบอาจไม่รองรับรถยนต์ของคุณหรือไม่รู้จัก ECU กรุณาส่ง pull request เพื่อเพิ่มรุ่นของเฟิร์มแวร์ให้กับรถยนต์ที่เหมาะสม หากต้องการความช่วยเหลือให้เข้าร่วม discord.comma.ai - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - openpilot ไม่สามารถระบุรถยนต์ของคุณได้ กรุณาตรวจสอบสายเคเบิ้ลและจุดเชื่อมต่อทั้งหมดว่าแน่นหนา โดยเฉพาะ comma power ว่าได้ดันเข้าไปยังพอร์ต OBD II ของรถยนต์จนสุด หากต้องการความช่วยเหลือให้เข้าร่วม discord.comma.ai - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - openpilot ตรวจพบการเปลี่ยนแปลงของตำแหน่งที่ติดตั้ง กรุณาตรวจสอบว่าได้เลื่อนอุปกรณ์เข้ากับจุดติดตั้งจนสุดแล้ว และจุดติดตั้งได้ยึดติดกับกระจกหน้าอย่างแน่นหนา - - - - OffroadHome - - UPDATE - อัปเดต - - - ALERTS - การแจ้งเตือน - - - ALERT - การแจ้งเตือน - - - - OnroadAlerts - - openpilot Unavailable - openpilot ไม่สามารถใช้งานได้ - - - Waiting for controls to start - กำลังรอให้ controls เริ่มทำงาน - - - TAKE CONTROL IMMEDIATELY - เข้าควบคุมรถเดี๋ยวนี้ - - - Controls Unresponsive - Controls ไม่ตอบสนอง - - - Reboot Device - รีบูตอุปกรณ์ - - - - PairingPopup - - Pair your device to your comma account - จับคู่อุปกรณ์ของคุณกับบัญชี comma ของคุณ - - - Go to https://connect.comma.ai on your phone - ไปที่ https://connect.comma.ai ด้วยโทรศัพท์ของคุณ - - - Click "add new device" and scan the QR code on the right - กดที่ "add new device" และสแกนคิวอาร์โค้ดทางด้านขวา - - - Bookmark connect.comma.ai to your home screen to use it like an app - จดจำ connect.comma.ai โดยการเพิ่มไปยังหน้าจอโฮม เพื่อใช้งานเหมือนเป็นแอปพลิเคชัน - - - - ParamControl - - Enable - เปิดใช้งาน - - - Cancel - ยกเลิก - - - - PrimeAdWidget - - Upgrade Now - อัพเกรดเดี๋ยวนี้ - - - Become a comma prime member at connect.comma.ai - สมัครสมาชิก comma prime ได้ที่ connect.comma.ai - - - PRIME FEATURES: - คุณสมบัติของ PRIME: - - - Remote access - การเข้าถึงระยะไกล - - - 24/7 LTE connectivity - การเชื่อมต่อ LTE แบบ 24/7 - - - 1 year of drive storage - จัดเก็บข้อมูลการขับขี่นาน 1 ปี - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ สมัครสำเร็จ - - - comma prime - comma prime - - - - QObject - - Reboot - รีบูต - - - Exit - ปิด - - - openpilot - openpilot - - - %n minute(s) ago - - %n นาทีที่แล้ว - - - - %n hour(s) ago - - %n ชั่วโมงที่แล้ว - - - - %n day(s) ago - - %n วันที่แล้ว - - - - now - ตอนนี้ - - - - Reset - - Reset failed. Reboot to try again. - การรีเซ็ตล้มเหลว รีบูตเพื่อลองอีกครั้ง - - - Are you sure you want to reset your device? - คุณแน่ใจหรือไม่ว่าต้องการรีเซ็ตอุปกรณ์? - - - System Reset - รีเซ็ตระบบ - - - Cancel - ยกเลิก - - - Reboot - รีบูต - - - Confirm - ยืนยัน - - - Resetting device... -This may take up to a minute. - กำลังรีเซ็ตอุปกรณ์... -อาจใช้เวลาถึงหนึ่งนาที - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - ไม่สามารถเมานต์พาร์ติชั่นข้อมูลได้ พาร์ติชั่นอาจเสียหาย กดยืนยันเพื่อลบและรีเซ็ตอุปกรณ์ของคุณ - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - ระบบถูกรีเซ็ต กดยืนยันเพื่อลบข้อมูลและการตั้งค่าทั้งหมด กดยกเลิกเพื่อบูตต่อ - - - - SettingsWindow - - × - × - - - Device - อุปกรณ์ - - - Network - เครือข่าย - - - Toggles - ตัวเลือก - - - Software - ซอฟต์แวร์ - - - - Setup - - WARNING: Low Voltage - คำเตือน: แรงดันแบตเตอรี่ต่ำ - - - Power your device in a car with a harness or proceed at your own risk. - โปรดต่ออุปกรณ์ของคุณเข้ากับสายควบคุมในรถยนต์ หรือดำเนินการด้วยความเสี่ยงของคุณเอง - - - Power off - ปิดเครื่อง - - - Continue - ดำเนินการต่อ - - - Getting Started - เริ่มกันเลย - - - Before we get on the road, let’s finish installation and cover some details. - ก่อนออกเดินทาง เรามาทำการติดตั้งซอฟต์แวร์ และตรวจสอบการตั้งค่า - - - Connect to Wi-Fi - เชื่อมต่อ Wi-Fi - - - Back - ย้อนกลับ - - - Continue without Wi-Fi - ดำเนินการต่อโดยไม่ใช้ Wi-Fi - - - Waiting for internet - กำลังรอสัญญาณอินเตอร์เน็ต - - - Enter URL - ป้อน URL - - - for Custom Software - สำหรับซอฟต์แวร์ที่กำหนดเอง - - - Downloading... - กำลังดาวน์โหลด... - - - Download Failed - ดาวน์โหลดล้มเหลว - - - Ensure the entered URL is valid, and the device’s internet connection is good. - ตรวจสอบให้แน่ใจว่า URL ที่ป้อนนั้นถูกต้อง และอุปกรณ์เชื่อมต่ออินเทอร์เน็ตอยู่ - - - Reboot device - รีบูตอุปกรณ์ - - - Start over - เริ่มต้นใหม่ - - - Something went wrong. Reboot the device. - มีบางอย่างผิดพลาด รีบูตอุปกรณ์ - - - No custom software found at this URL. - ไม่พบซอฟต์แวร์ที่กำหนดเองที่ URL นี้ - - - Select a language - เลือกภาษา - - - Choose Software to Install - เลือกซอฟต์แวร์ที่จะติดตั้ง - - - openpilot - openpilot - - - Custom Software - ซอฟต์แวร์ที่กำหนดเอง - - - - SetupWidget - - Finish Setup - ตั้งค่าเสร็จสิ้น - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - จับคู่อุปกรณ์ของคุณกับ comma connect (connect.comma.ai) และรับข้อเสนอ comma prime ของคุณ - - - Pair device - จับคู่อุปกรณ์ - - - - Sidebar - - CONNECT - เชื่อมต่อ - - - OFFLINE - ออฟไลน์ - - - ONLINE - ออนไลน์ - - - ERROR - เกิดข้อผิดพลาด - - - TEMP - อุณหภูมิ - - - HIGH - สูง - - - GOOD - ดี - - - OK - พอใช้ - - - VEHICLE - รถยนต์ - - - NO - ไม่พบ - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Uninstall %1 - ถอนการติดตั้ง %1 - - - UNINSTALL - ถอนการติดตั้ง - - - Are you sure you want to uninstall? - คุณแน่ใจหรือไม่ว่าต้องการถอนการติดตั้ง? - - - CHECK - ตรวจสอบ - - - Updates are only downloaded while the car is off. - ตัวอัปเดตจะดำเนินการดาวน์โหลดเมื่อรถดับเครื่องยนต์อยู่เท่านั้น - - - Current Version - เวอร์ชั่นปัจจุบัน - - - Download - ดาวน์โหลด - - - Install Update - ติดตั้งตัวอัปเดต - - - INSTALL - ติดตั้ง - - - Target Branch - Branch ที่เลือก - - - SELECT - เลือก - - - Select a branch - เลือก Branch - - - Uninstall - ถอนการติดตั้ง - - - failed to check for update - ไม่สามารถตรวจสอบอัปเดตได้ - - - DOWNLOAD - ดาวน์โหลด - - - update available - มีอัปเดตใหม่ - - - never - ไม่เคย - - - up to date, last checked %1 - ล่าสุดแล้ว ตรวจสอบครั้งสุดท้ายเมื่อ %1 - - - - SshControl - - SSH Keys - คีย์ SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - คำเตือน: สิ่งนี้ให้สิทธิ์ SSH เข้าถึงคีย์สาธารณะทั้งหมดใน GitHub ของคุณ อย่าป้อนชื่อผู้ใช้ GitHub อื่นนอกเหนือจากของคุณเอง พนักงาน comma จะไม่ขอให้คุณเพิ่มชื่อผู้ใช้ GitHub ของพวกเขา - - - ADD - เพิ่ม - - - Enter your GitHub username - ป้อนชื่อผู้ใช้ GitHub ของคุณ - - - LOADING - กำลังโหลด - - - REMOVE - ลบ - - - Username '%1' has no keys on GitHub - ชื่อผู้ใช้ '%1' ไม่มีคีย์บน GitHub - - - Request timed out - ตรวจสอบไม่สำเร็จ เนื่องจากใช้เวลามากเกินไป - - - Username '%1' doesn't exist on GitHub - ไม่พบชื่อผู้ใช้ '%1' บน GitHub - - - - SshToggle - - Enable SSH - เปิดใช้งาน SSH - - - - TermsPage - - Terms & Conditions - ข้อตกลงและเงื่อนไข - - - Decline - ปฏิเสธ - - - Scroll to accept - เลื่อนเพื่อตอบรับข้อตกลง - - - Agree - ยอมรับ - - - - TogglesPanel - - Enable openpilot - เปิดใช้งาน openpilot - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - ใช้ระบบ openpilot สำหรับระบบควบคุมความเร็วอัตโนมัติ และระบบช่วยควบคุมรถให้อยู่ในเลน คุณจำเป็นต้องให้ความสนใจตลอดเวลาที่ใช้คุณสมบัตินี้ การเปลี่ยนการตั้งค่านี้จะมีผลเมื่อคุณดับเครื่องยนต์ - - - Enable Lane Departure Warnings - เปิดใช้งานการเตือนการออกนอกเลน - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - รับการแจ้งเตือนให้เลี้ยวกลับเข้าเลนเมื่อรถของคุณตรวจพบการข้ามช่องจราจรโดยไม่เปิดสัญญาณไฟเลี้ยวในขณะขับขี่ที่ความเร็วเกิน 31 ไมล์ต่อชั่วโมง (50 กม./ชม) - - - Use Metric System - ใช้ระบบเมตริก - - - Display speed in km/h instead of mph. - แสดงความเร็วเป็น กม./ชม. แทน ไมล์/ชั่วโมง - - - Record and Upload Driver Camera - บันทึกและอัปโหลดภาพจากกล้องคนขับ - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - อัปโหลดข้อมูลจากกล้องที่หันหน้าไปทางคนขับ และช่วยปรับปรุงอัลกอริธึมการตรวจสอบผู้ขับขี่ - - - Disengage on Accelerator Pedal - ยกเลิกระบบช่วยขับเมื่อเหยียบคันเร่ง - - - When enabled, pressing the accelerator pedal will disengage openpilot. - เมื่อเปิดใช้งาน การกดแป้นคันเร่งจะเป็นการยกเลิกระบบช่วยขับโดย openpilot - - - Experimental Mode - โหมดทดลอง - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - โดยปกติ openpilot จะขับใน<b>โหมดชิล</b> เปิดโหมดทดลองเพื่อใช้<b>ความสามารถในขั้นพัฒนา</b> ซึ่งยังไม่พร้อมสำหรับโหมดชิล ความสามารถในขั้นพัฒนามีดังนี้: - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - ให้ openpilot ควบคุมการเร่ง/เบรค โดย openpilot จะขับอย่างที่มนุษย์คิด รวมถึงการหยุดที่ไฟแดง และป้ายหยุดรถ เนื่องจาก openpilot จะกำหนดความเร็วในการขับด้วยตัวเอง การตั้งความเร็วจะเป็นเพียงการกำหนดความเร็วสูงสูดเท่านั้น ความสามารถนี้ยังอยู่ในขั้นพัฒนา อาจเกิดข้อผิดพลาดขึ้นได้ - - - New Driving Visualization - การแสดงภาพการขับขี่แบบใหม่ - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - ขณะนี้โหมดทดลองไม่สามารถใช้งานได้ในรถคันนี้ เนื่องจากเปิดใช้ระบบควบคุมการเร่ง/เบรคของรถที่ติดตั้งจากโรงงานอยู่ - - - openpilot longitudinal control may come in a future update. - ระบบควบคุมการเร่ง/เบรคโดย openpilot อาจมาในการอัปเดตในอนาคต - - - openpilot Longitudinal Control (Alpha) - ระบบควบคุมการเร่ง/เบรคโดย openpilot (Alpha) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - คำเตือน: การควบคุมการเร่ง/เบรคโดย openpilot สำหรับรถคันนี้ยังอยู่ในสถานะ alpha และระบบเบรคฉุกเฉินอัตโนมัติ (AEB) จะถูกปิด - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - โดยปกติสำหรับรถคันนี้ openpilot จะควบคุมการเร่ง/เบรคด้วยระบบ ACC จากโรงงาน แทนการควยคุมโดย openpilot เปิดสวิตซ์นี้เพื่อให้ openpilot ควบคุมการเร่ง/เบรค แนะนำให้เปิดโหมดทดลองเมื่อต้องการให้ openpilot ควบคุมการเร่ง/เบรค ซึ่งอยู่ในสถานะ alpha - - - Aggressive - ดุดัน - - - Standard - มาตรฐาน - - - Relaxed - ผ่อนคลาย - - - Driving Personality - บุคลิกการขับขี่ - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - ระบบควบคุมการเร่ง/เบรคโดย openpilot เวอร์ชัน alpha สามารถทดสอบได้พร้อมกับโหมดการทดลอง บน branch ที่กำลังพัฒนา - - - End-to-End Longitudinal Control - ควบคุมเร่ง/เบรคแบบ End-to-End - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - เปิดระบบควบคุมการเร่ง/เบรคโดย openpilot (alpha) เพื่อเปิดใช้งานโหมดทดลอง - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - แนะนำให้ใช้แบบมาตรฐาน ในโหมดดุดัน openpilot จะตามรถคันหน้าใกล้ขึ้นและเร่งและเบรคแบบดุดันมากขึ้น ในโหมดผ่อนคลาย openpilot จะอยู่ห่างจากรถคันหน้ามากขึ้น ในรถรุ่นที่รองรับคุณสามารถเปลี่ยนบุคลิกไปแบบต่าง ๆ โดยใช้ปุ่มปรับระยะห่างบนพวงมาลัย - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - การแสดงภาพการขับขี่จะเปลี่ยนไปใช้กล้องมุมกว้างที่หันหน้าไปทางถนนเมื่ออยู่ในความเร็วต่ำ เพื่อแสดงภาพการเลี้ยวที่ดีขึ้น โลโก้โหมดการทดลองจะแสดงที่มุมบนขวาด้วย - - - Always-On Driver Monitoring - - - - Enable driver monitoring even when openpilot is not engaged. - - - - - Updater - - Update Required - จำเป็นต้องอัปเดต - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - จำเป็นต้องมีการอัปเดตระบบปฏิบัติการ เชื่อมต่ออุปกรณ์ของคุณกับ Wi-Fi เพื่อประสบการณ์การอัปเดตที่เร็วที่สุด ขนาดดาวน์โหลดประมาณ 1GB - - - Connect to Wi-Fi - เชื่อมต่อกับ Wi-Fi - - - Install - ติดตั้ง - - - Back - ย้อนกลับ - - - Loading... - กำลังโหลด... - - - Reboot - รีบูต - - - Update failed - การอัปเดตล้มเหลว - - - - WiFiPromptWidget - - Setup Wi-Fi - ตั้งค่า Wi-Fi - - - Connect to Wi-Fi to upload driving data and help improve openpilot - เชื่อมต่อกับ Wi-Fi เพื่ออัปโหลดข้อมูลการขับขี่และช่วยปรับปรุง openpilot - - - Open Settings - เปิดการตั้งค่า - - - Ready to upload - พร้อมจะอัปโหลด - - - Training data will be pulled periodically while your device is on Wi-Fi - ข้อมูลการฝึกฝนจะถูกดึงเป็นระยะระหว่างที่อุปกรณ์ของคุณเชื่อมต่อกับ Wi-Fi - - - - WifiUI - - Scanning for networks... - กำลังสแกนหาเครือข่าย... - - - CONNECTING... - กำลังเชื่อมต่อ... - - - FORGET - เลิกใช้ - - - Forget Wi-Fi Network "%1"? - เลิกใช้เครือข่าย Wi-Fi "%1"? - - - Forget - เลิกใช้ - - - diff --git a/selfdrive/ui/translations/main_tr.ts b/selfdrive/ui/translations/main_tr.ts deleted file mode 100644 index 72148807d430d8..00000000000000 --- a/selfdrive/ui/translations/main_tr.ts +++ /dev/null @@ -1,1133 +0,0 @@ - - - - - AbstractAlert - - Close - Kapat - - - Snooze Update - Güncellemeyi sessize al - - - Reboot and Update - Güncelle ve Yeniden başlat - - - - AdvancedNetworking - - Back - Geri dön - - - Enable Tethering - Kişisel erişim noktasını aç - - - Tethering Password - Kişisel erişim noktasının parolası - - - EDIT - DÜZENLE - - - Enter new tethering password - Erişim noktasına yeni bir sonraki başlatılışında çekilir. parola belirleyin. - - - IP Address - IP Adresi - - - Enable Roaming - Hücresel veri aç - - - APN Setting - APN Ayarları - - - Enter APN - APN Gir - - - leave blank for automatic configuration - otomatik yapılandırma için boş bırakın - - - Cellular Metered - - - - Prevent large data uploads when on a metered connection - - - - Hidden Network - - - - CONNECT - BAĞLANTI - - - Enter SSID - APN Gir - - - Enter password - Parolayı girin - - - for "%1" - için "%1" - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - - ConfirmationDialog - - Ok - Tamam - - - Cancel - Vazgeç - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - Openpilotu kullanmak için Kullanıcı Koşullarını kabul etmelisiniz. - - - Back - Geri - - - Decline, uninstall %1 - Reddet, Kurulumu kaldır. %1 - - - - DevicePanel - - Dongle ID - Adaptör ID - - - N/A - N/A - - - Serial - Seri Numara - - - Driver Camera - Sürücü Kamerası - - - PREVIEW - ÖN İZLEME - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Sürücü kamerasının görüş açısını test etmek için kamerayı önizleyin (Araç kapalı olmalıdır.) - - - Reset Calibration - Kalibrasyonu sıfırla - - - RESET - SIFIRLA - - - Are you sure you want to reset calibration? - Kalibrasyon ayarını sıfırlamak istediğinizden emin misiniz? - - - Review Training Guide - Eğitim kılavuzunu inceleyin - - - REVIEW - GÖZDEN GEÇİR - - - Review the rules, features, and limitations of openpilot - openpilot sisteminin kurallarını ve sınırlamalarını gözden geçirin. - - - Are you sure you want to review the training guide? - Eğitim kılavuzunu incelemek istediğinizden emin misiniz? - - - Regulatory - Mevzuat - - - VIEW - BAK - - - Change Language - Dili değiştir - - - CHANGE - DEĞİŞTİR - - - Select a language - Dil seçin - - - Reboot - Yeniden başlat - - - Power Off - Sistemi kapat - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot, cihazın 4° sola veya 5° yukarı yada 9° aşağı bakıcak şekilde monte edilmesi gerekmektedir. openpilot sürekli kendisini kalibre edilmektedir ve nadiren sıfırlama gerebilir. - - - Your device is pointed %1° %2 and %3° %4. - Cihazınız %1° %2 ve %3° %4 yönünde ayarlı - - - down - aşağı - - - up - yukarı - - - left - sol - - - right - sağ - - - Are you sure you want to reboot? - Cihazı Tekrar başlatmak istediğinizden eminmisiniz? - - - Disengage to Reboot - Bağlantıyı kes ve Cihazı Yeniden başlat - - - Are you sure you want to power off? - Cihazı kapatmak istediğizden eminmisiniz? - - - Disengage to Power Off - Bağlantıyı kes ve Cihazı kapat - - - Reset - - - - Review - - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Cihazınızı comma connect (connect.comma.ai) ile eşleştirin ve comma prime aboneliğine göz atın. - - - Pair Device - - - - PAIR - - - - - DriverViewWindow - - camera starting - kamera başlatılıyor - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - - - - CHILL MODE ON - - - - - InputDialog - - Cancel - Kapat - - - Need at least %n character(s)! - - En az %n karakter gerekli! - - - - - Installer - - Installing... - Yükleniyor... - - - - MultiOptionDialog - - Select - Seç - - - Cancel - İptal et - - - - Networking - - Advanced - Gelişmiş Seçenekler - - - Enter password - Parolayı girin - - - for "%1" - için "%1" - - - Wrong password - Yalnış parola - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - - - - Unable to download updates -%1 - - - - Taking camera snapshots. System won't start until finished. - - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - - - - NVMe drive not mounted. - - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - - - - - OffroadHome - - UPDATE - GÜNCELLE - - - ALERTS - UYARILAR - - - ALERT - UYARI - - - - OnroadAlerts - - openpilot Unavailable - - - - Waiting for controls to start - - - - TAKE CONTROL IMMEDIATELY - - - - Controls Unresponsive - - - - Reboot Device - - - - - PairingPopup - - Pair your device to your comma account - comma.ai hesabınız ile cihazı eşleştirin - - - Go to https://connect.comma.ai on your phone - Telefonuzdan https://connect.comma.ai sitesine gidin - - - Click "add new device" and scan the QR code on the right - Yeni cihaz eklemek için sağdaki QR kodunu okutun - - - Bookmark connect.comma.ai to your home screen to use it like an app - Uygulama gibi kullanmak için connect.comma.ai sitesini yer işaretlerine ekleyin. - - - - ParamControl - - Enable - - - - Cancel - - - - - PrimeAdWidget - - Upgrade Now - Hemen yükselt - - - Become a comma prime member at connect.comma.ai - connect.comma.ai üzerinden comma prime üyesi olun - - - PRIME FEATURES: - PRIME ABONELİĞİNİN ÖZELLİKLERİ: - - - Remote access - Uzaktan erişim - - - 24/7 LTE connectivity - - - - 1 year of drive storage - - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ ABONE - - - comma prime - comma prime - - - - QObject - - Reboot - Yeniden başlat - - - Exit - Çık - - - openpilot - openpilot - - - %n minute(s) ago - - %n dakika önce - - - - %n hour(s) ago - - %n saat önce - - - - %n day(s) ago - - %n gün önce - - - - now - - - - - Reset - - Reset failed. Reboot to try again. - Sıfırlama başarız oldu. Cihazı yeniden başlatın ve tekrar deneyin. - - - Are you sure you want to reset your device? - Cihazı sıfırlamak istediğinizden eminmisiniz ? - - - System Reset - Sistemi sıfırla - - - Cancel - İptal - - - Reboot - Yeniden başlat - - - Confirm - Onayla - - - Resetting device... -This may take up to a minute. - - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - - - - - SettingsWindow - - × - x - - - Device - Cihaz - - - Network - Ağ - - - Toggles - Değiştirme - - - Software - Yazılım - - - - Setup - - WARNING: Low Voltage - UYARI: Düşük voltaj - - - Power your device in a car with a harness or proceed at your own risk. - Cihazınızı emniyet kemeri olan bir arabada çalıştırın veya riski kabul ederek devam edin. - - - Power off - Sistemi kapat - - - Continue - Devam et - - - Getting Started - Başlarken - - - Before we get on the road, let’s finish installation and cover some details. - Yola çıkmadan önce kurulumu bitirin ve bazı detayları gözden geçirin.. - - - Connect to Wi-Fi - Wi-Fi ile bağlan - - - Back - Geri - - - Continue without Wi-Fi - Wi-Fi bağlantısı olmadan devam edin - - - Waiting for internet - İnternet bağlantısı bekleniyor. - - - Enter URL - URL girin - - - for Custom Software - özel yazılım için - - - Downloading... - İndiriliyor... - - - Download Failed - İndirme başarısız. - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Girilen URL nin geçerli olduğundan ve cihazın internet bağlantısının olduğunu kontrol edin - - - Reboot device - Cihazı yeniden başlat - - - Start over - Zacznij od początku - - - Something went wrong. Reboot the device. - - - - No custom software found at this URL. - - - - Select a language - Dil seçin - - - Choose Software to Install - - - - openpilot - openpilot - - - Custom Software - - - - - SetupWidget - - Finish Setup - Kurulumu bitir - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Cihazınızı comma connect (connect.comma.ai) ile eşleştirin ve comma prime aboneliğine göz atın. - - - Pair device - Cihazı eşleştirme - - - - Sidebar - - CONNECT - BAĞLANTI - - - OFFLINE - ÇEVRİMDIŞI - - - ONLINE - ÇEVRİMİÇİ - - - ERROR - HATA - - - TEMP - SICAKLIK - - - HIGH - YÜKSEK - - - GOOD - İYİ - - - OK - TAMAM - - - VEHICLE - ARAÇ - - - NO - HAYIR - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-FI - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Uninstall %1 - Kaldır %1 - - - UNINSTALL - KALDIR - - - Are you sure you want to uninstall? - Kaldırmak istediğinden eminmisin? - - - CHECK - KONTROL ET - - - Updates are only downloaded while the car is off. - - - - Current Version - - - - Download - - - - Install Update - - - - INSTALL - - - - Target Branch - - - - SELECT - - - - Select a branch - - - - Uninstall - - - - failed to check for update - - - - DOWNLOAD - - - - update available - - - - never - - - - up to date, last checked %1 - - - - - SshControl - - SSH Keys - SSH Anahtarları - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - UYARI: Bu, GitHub ayarlarınızdaki tüm ortak anahtarlara SSH erişimi sağlar. Asla kendi kullanıcı adınız dışında bir sonraki başlatılışında çekilir. GitHub kullanıcı adı girmeyin. - - - ADD - EKLE - - - Enter your GitHub username - Github kullanıcı adınızı giriniz - - - LOADING - YÜKLENİYOR - - - REMOVE - KALDIR - - - Username '%1' has no keys on GitHub - Kullanısının '%1' Github erişim anahtarı yok - - - Request timed out - İstek zaman aşımına uğradı - - - Username '%1' doesn't exist on GitHub - Github kullanıcısı %1 bulunamadı - - - - SshToggle - - Enable SSH - SSH aç - - - - TermsPage - - Terms & Conditions - Şartlar ve Koşullar - - - Decline - Reddet - - - Scroll to accept - Kabul etmek için kaydırın - - - Agree - Kabul et - - - - TogglesPanel - - Enable openpilot - openpilot'u aktifleştir - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Ayarlanabilir hız sabitleyici ve şeritte kalma yardımı için openpilot sistemini kullanın. Bu özelliği kullanırken her zaman dikkatli olmanız gerekiyor. Bu ayarın değiştirilmesi için araç kapatılıp açılması gerekiyor. - - - Enable Lane Departure Warnings - Şerit ihlali uyarı alın - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 50 km/s (31 mph) hızın üzerinde sürüş sırasında aracınız dönüş sinyali vermeden algılanan bir sonraki başlatılışında çekilir. şerit çizgisi ihlalinde şeride geri dönmek için uyarılar alın. - - - Use Metric System - Metrik sistemi kullan - - - Display speed in km/h instead of mph. - Hızı mph yerine km/h şeklinde görüntüleyin. - - - Record and Upload Driver Camera - Sürücü kamerasını kayıt et. - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Sürücüye bakan kamera verisini yükleyin ve Cihazın algoritmasını geliştirmemize yardımcı olun. - - - When enabled, pressing the accelerator pedal will disengage openpilot. - Aktifleştirilirse eğer gaz pedalına basınca openpilot devre dışı kalır. - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - Experimental Mode - - - - Disengage on Accelerator Pedal - - - - Aggressive - - - - Standard - - - - Relaxed - - - - Driving Personality - - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - - - - End-to-End Longitudinal Control - - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - - - - New Driving Visualization - - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - - - - openpilot longitudinal control may come in a future update. - - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - - - - Always-On Driver Monitoring - - - - Enable driver monitoring even when openpilot is not engaged. - - - - - Updater - - Update Required - Güncelleme yapılması gerekli - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - İşletim sistemi güncellemesi gerekmektedir. Lütfen Cihazı daha hızlı günceleyebilmesi için bir sonraki başlatılışında çekilir. Wi-Fi ağına bağlayın. Dosyanın boyutu yaklaşık 1GB dır. - - - Connect to Wi-Fi - Wi-Fi ağına bağlan - - - Install - Yükle - - - Back - Geri - - - Loading... - Yükleniyor... - - - Reboot - Yeniden başlat - - - Update failed - Güncelleme başarız oldu - - - - WiFiPromptWidget - - Setup Wi-Fi - - - - Connect to Wi-Fi to upload driving data and help improve openpilot - - - - Open Settings - - - - Ready to upload - - - - Training data will be pulled periodically while your device is on Wi-Fi - - - - - WifiUI - - Scanning for networks... - Ağ aranıyor... - - - CONNECTING... - BAĞLANILIYOR... - - - FORGET - UNUT - - - Forget Wi-Fi Network "%1"? - Wi-Fi ağını unut "%1"? - - - Forget - - - - diff --git a/selfdrive/ui/translations/main_zh-CHS.ts b/selfdrive/ui/translations/main_zh-CHS.ts deleted file mode 100644 index 976b58b31d6cd7..00000000000000 --- a/selfdrive/ui/translations/main_zh-CHS.ts +++ /dev/null @@ -1,1135 +0,0 @@ - - - - - AbstractAlert - - Close - 关闭 - - - Snooze Update - 暂停更新 - - - Reboot and Update - 重启并更新 - - - - AdvancedNetworking - - Back - 返回 - - - Enable Tethering - 启用WiFi热点 - - - Tethering Password - WiFi热点密码 - - - EDIT - 编辑 - - - Enter new tethering password - 输入新的WiFi热点密码 - - - IP Address - IP地址 - - - Enable Roaming - 启用数据漫游 - - - APN Setting - APN设置 - - - Enter APN - 输入APN - - - leave blank for automatic configuration - 留空以自动配置 - - - Cellular Metered - 按流量计费的手机移动网络 - - - Prevent large data uploads when on a metered connection - 当使用按流量计费的连接时,避免上传大流量数据 - - - Hidden Network - 隐藏的网络 - - - CONNECT - 连线 - - - Enter SSID - 输入 SSID - - - Enter password - 输入密码 - - - for "%1" - 网络名称:"%1" - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - 最高定速 - - - - ConfirmationDialog - - Ok - 好的 - - - Cancel - 取消 - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - 您必须接受条款和条件以使用openpilot。 - - - Back - 返回 - - - Decline, uninstall %1 - 拒绝并卸载%1 - - - - DevicePanel - - Dongle ID - 设备ID(Dongle ID) - - - N/A - N/A - - - Serial - 序列号 - - - Driver Camera - 驾驶员摄像头 - - - PREVIEW - 预览 - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - 打开并预览驾驶员摄像头,以确保驾驶员监控具有良好视野。(仅熄火时可用) - - - Reset Calibration - 重置设备校准 - - - RESET - 重置 - - - Are you sure you want to reset calibration? - 您确定要重置设备校准吗? - - - Review Training Guide - 新手指南 - - - REVIEW - 查看 - - - Review the rules, features, and limitations of openpilot - 查看 openpilot 的使用规则,以及其功能和限制 - - - Are you sure you want to review the training guide? - 您确定要查看新手指南吗? - - - Regulatory - 监管信息 - - - VIEW - 查看 - - - Change Language - 切换语言 - - - CHANGE - 切换 - - - Select a language - 选择语言 - - - Reboot - 重启 - - - Power Off - 关机 - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot要求设备安装的偏航角在左4°和右4°之间,俯仰角在上5°和下9°之间。一般来说,openpilot会持续更新校准,很少需要重置。 - - - Your device is pointed %1° %2 and %3° %4. - 您的设备校准为%1° %2、%3° %4。 - - - down - 朝下 - - - up - 朝上 - - - left - 朝左 - - - right - 朝右 - - - Are you sure you want to reboot? - 您确定要重新启动吗? - - - Disengage to Reboot - 取消openpilot以重新启动 - - - Are you sure you want to power off? - 您确定要关机吗? - - - Disengage to Power Off - 取消openpilot以关机 - - - Reset - 重置 - - - Review - 预览 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 将您的设备与comma connect (connect.comma.ai)配对并领取您的comma prime优惠。 - - - Pair Device - 配对设备 - - - PAIR - 配对 - - - - DriverViewWindow - - camera starting - 正在启动相机 - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - 试验模式运行 - - - CHILL MODE ON - 轻松模式运行 - - - - InputDialog - - Cancel - 取消 - - - Need at least %n character(s)! - - 至少需要 %n 个字符! - - - - - Installer - - Installing... - 正在安装…… - - - - MultiOptionDialog - - Select - 选择 - - - Cancel - 取消 - - - - Networking - - Advanced - 高级 - - - Enter password - 输入密码 - - - for "%1" - 网络名称:"%1" - - - Wrong password - 密码错误 - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - 请立即连接网络检查更新。如果不连接网络,openpilot 将在 %1 后便无法使用 - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - 请连接至互联网以检查更新。在连接至互联网并完成更新检查之前,openpilot 将不会自动启动。 - - - Unable to download updates -%1 - 无法下载更新 -%1 - - - Taking camera snapshots. System won't start until finished. - 正在使用相机拍摄中。在完成之前,系统将无法启动。 - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - 一个针对您设备的操作系统更新正在后台下载中。当更新准备好安装时,您将收到提示进行更新。 - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - 设备注册失败。它将无法连接或上传至 comma.ai 服务器,并且无法获得 comma.ai 的支持。如果这是一个官方设备,请访问 https://comma.ai/support。 - - - NVMe drive not mounted. - NVMe固态硬盘未被挂载。 - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - 检测到不支持的 NVMe 固态硬盘。您的设备因为使用了不支持的 NVMe 固态硬盘可能会消耗更多电力并更易过热。 - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - openpilot 无法识别您的车辆。您的车辆可能未被支持,或是其电控单元 (ECU) 未被识别。请提交一个 Pull Request 为您的车辆添加正确的固件版本。需要帮助吗?请加入 discord.comma.ai。 - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - openpilot 无法识别您的车辆。请检查线路是否正确安装并确保所有的连接都牢固,特别是确保 comma power 完全插入车辆的 OBD-II 接口。需要帮助吗?请加入 discord.comma.ai。 - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - openpilot 检测到设备的安装位置发生变化。请确保设备完全安装在支架上,并确保支架牢固地固定在挡风玻璃上。 - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - 设备温度过高。系统正在冷却中,等冷却完毕后才会启动。目前内部组件温度:%1 - - - - OffroadHome - - UPDATE - 更新 - - - ALERTS - 警报 - - - ALERT - 警报 - - - - OnroadAlerts - - openpilot Unavailable - 无法使用 openpilot - - - Waiting for controls to start - 等待控制服务啟動 - - - TAKE CONTROL IMMEDIATELY - 立即接管 - - - Controls Unresponsive - 控制服务无响应 - - - Reboot Device - 重启设备 - - - - PairingPopup - - Pair your device to your comma account - 将您的设备与comma账号配对 - - - Go to https://connect.comma.ai on your phone - 在手机上访问 https://connect.comma.ai - - - Click "add new device" and scan the QR code on the right - 点击“添加新设备”,扫描右侧二维码 - - - Bookmark connect.comma.ai to your home screen to use it like an app - 将 connect.comma.ai 收藏到您的主屏幕,以便像应用程序一样使用它 - - - - ParamControl - - Cancel - 取消 - - - Enable - 启用 - - - - PrimeAdWidget - - Upgrade Now - 现在升级 - - - Become a comma prime member at connect.comma.ai - 打开connect.comma.ai以注册comma prime会员 - - - PRIME FEATURES: - comma prime特权: - - - Remote access - 远程访问 - - - 24/7 LTE connectivity - 全天候 LTE 連線 - - - 1 year of drive storage - 一年的行驶记录储存空间 - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ 已订阅 - - - comma prime - comma prime - - - - QObject - - Reboot - 重启 - - - Exit - 退出 - - - openpilot - openpilot - - - %n minute(s) ago - - %n 分钟前 - - - - %n hour(s) ago - - %n 小时前 - - - - %n day(s) ago - - %n 天前 - - - - now - 现在 - - - - Reset - - Reset failed. Reboot to try again. - 重置失败。 重新启动以重试。 - - - Are you sure you want to reset your device? - 您确定要重置您的设备吗? - - - System Reset - 恢复出厂设置 - - - Cancel - 取消 - - - Reboot - 重启 - - - Confirm - 确认 - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - 无法挂载数据分区。分区可能已经损坏。请确认是否要删除并重新设置。 - - - Resetting device... -This may take up to a minute. - 设备重置中… -这可能需要一分钟的时间。 - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - 系统重置已触发。按下“确认”以清除所有内容和设置,按下“取消”以继续启动。 - - - - SettingsWindow - - × - × - - - Device - 设备 - - - Network - 网络 - - - Toggles - 设定 - - - Software - 软件 - - - - Setup - - WARNING: Low Voltage - 警告:低电压 - - - Power your device in a car with a harness or proceed at your own risk. - 请使用car harness线束为您的设备供电,或自行承担风险。 - - - Power off - 关机 - - - Continue - 继续 - - - Getting Started - 开始设置 - - - Before we get on the road, let’s finish installation and cover some details. - 开始旅程之前,让我们完成安装并介绍一些细节。 - - - Connect to Wi-Fi - 连接到WiFi - - - Back - 返回 - - - Continue without Wi-Fi - 不连接WiFi并继续 - - - Waiting for internet - 等待网络连接 - - - Enter URL - 输入网址 - - - for Custom Software - 以下载自定义软件 - - - Downloading... - 正在下载…… - - - Download Failed - 下载失败 - - - Ensure the entered URL is valid, and the device’s internet connection is good. - 请确保互联网连接良好且输入的URL有效。 - - - Reboot device - 重启设备 - - - Start over - 重来 - - - No custom software found at this URL. - 在此网址找不到自定义软件。 - - - Something went wrong. Reboot the device. - 发生了一些错误。请重新启动您的设备。 - - - Select a language - 选择语言 - - - Choose Software to Install - 选择要安装的软件 - - - openpilot - openpilot - - - Custom Software - 定制软件 - - - - SetupWidget - - Finish Setup - 完成设置 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 将您的设备与comma connect (connect.comma.ai)配对并领取您的comma prime优惠。 - - - Pair device - 配对设备 - - - - Sidebar - - CONNECT - CONNECT - - - OFFLINE - 离线 - - - ONLINE - 在线 - - - ERROR - 连接出错 - - - TEMP - 设备温度 - - - HIGH - 过热 - - - GOOD - 良好 - - - OK - 一般 - - - VEHICLE - 车辆连接 - - - NO - 无 - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - 以太网 - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - 车辆熄火时才能下载升级文件。 - - - Current Version - 当前版本 - - - Download - 下载 - - - Install Update - 安装更新 - - - INSTALL - 安装 - - - Target Branch - 目标分支 - - - SELECT - 选择 - - - Select a branch - 选择分支 - - - UNINSTALL - 卸载 - - - Uninstall %1 - 卸载 %1 - - - Are you sure you want to uninstall? - 您确定要卸载吗? - - - CHECK - 查看 - - - Uninstall - 卸载 - - - failed to check for update - 检查更新失败 - - - up to date, last checked %1 - 已经是最新版本,上次检查时间为 %1 - - - DOWNLOAD - 下载 - - - update available - 有可用的更新 - - - never - 从未更新 - - - - SshControl - - SSH Keys - SSH密钥 - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - 警告:这将授予SSH访问权限给您GitHub设置中的所有公钥。切勿输入您自己以外的GitHub用户名。comma员工永远不会要求您添加他们的GitHub用户名。 - - - ADD - 添加 - - - Enter your GitHub username - 输入您的GitHub用户名 - - - LOADING - 正在加载 - - - REMOVE - 删除 - - - Username '%1' has no keys on GitHub - 用户名“%1”在GitHub上没有密钥 - - - Request timed out - 请求超时 - - - Username '%1' doesn't exist on GitHub - GitHub上不存在用户名“%1” - - - - SshToggle - - Enable SSH - 启用SSH - - - - TermsPage - - Terms & Conditions - 条款和条件 - - - Decline - 拒绝 - - - Scroll to accept - 滑动以接受 - - - Agree - 同意 - - - - TogglesPanel - - Enable openpilot - 启用openpilot - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - 使用openpilot进行自适应巡航和车道保持辅助。使用此功能时您必须时刻保持注意力。该设置的更改在熄火时生效。 - - - Enable Lane Departure Warnings - 启用车道偏离警告 - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 车速超过31mph(50km/h)时,若检测到车辆越过车道线且未打转向灯,系统将发出警告以提醒您返回车道。 - - - Use Metric System - 使用公制单位 - - - Display speed in km/h instead of mph. - 显示车速时,以km/h代替mph。 - - - Record and Upload Driver Camera - 录制并上传驾驶员摄像头 - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - 上传驾驶员摄像头的数据,帮助改进驾驶员监控算法。 - - - Disengage on Accelerator Pedal - 踩油门时取消控制 - - - When enabled, pressing the accelerator pedal will disengage openpilot. - 启用后,踩下油门踏板将取消openpilot。 - - - Experimental Mode - 测试模式 - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - openpilot 默认 <b>轻松模式</b>驾驶车辆。试验模式启用一些轻松模式之外的 <b>试验性功能</b>。试验性功能包括: - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - 允许驾驶模型控制加速和制动,openpilot将模仿人类驾驶车辆,包括在红灯和停车让行标识前停车。鉴于驾驶模型确定行驶车速,所设定的车速仅作为上限。此功能尚处于早期测试状态,有可能会出现操作错误。 - - - New Driving Visualization - 新驾驶视角 - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - 由于此车辆使用自带的ACC纵向控制,当前无法使用试验模式。 - - - openpilot longitudinal control may come in a future update. - openpilot纵向控制可能会在未来的更新中提供。 - - - openpilot Longitudinal Control (Alpha) - openpilot纵向控制(Alpha 版) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - 警告:此车辆的 openpilot 纵向控制功能目前处于Alpha版本,使用此功能将会停用自动紧急制动(AEB)功能。 - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - 在这辆车上,openpilot 默认使用车辆内建的主动巡航控制(ACC),而非 openpilot 的纵向控制。启用此项功能可切换至 openpilot 的纵向控制。当启用 openpilot 纵向控制 Alpha 版本时,建议同时启用实验性模式(Experimental mode)。 - - - Aggressive - 积极 - - - Standard - 标准 - - - Relaxed - 舒适 - - - Driving Personality - 驾驶风格 - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - 在正式(release)版本以外的分支上,可以测试 openpilot 纵向控制的 Alpha 版本以及实验模式。 - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - 启用 openpilot 纵向控制(alpha)开关以允许实验模式。 - - - End-to-End Longitudinal Control - 端到端纵向控制 - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - 推荐使用标准模式。在积极模式下,openpilot 会更靠近前方车辆,并在油门和刹车方面更加激进。在放松模式下,openpilot 会与前方车辆保持更远距离。在支持的车型上,你可以使用方向盘上的距离按钮来循环切换这些驾驶风格。 - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - 在低速时,驾驶可视化将转换为道路朝向的广角摄像头,以更好地展示某些转弯。测试模式标志也将显示在右上角。 - - - Always-On Driver Monitoring - 驾驶员监控常开 - - - Enable driver monitoring even when openpilot is not engaged. - 即使在openpilot未激活时也启用驾驶员监控。 - - - - Updater - - Update Required - 需要更新 - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - 操作系统需要更新。请将您的设备连接到WiFi以获取更快的更新体验。下载大小约为1GB。 - - - Connect to Wi-Fi - 连接到WiFi - - - Install - 安装 - - - Back - 返回 - - - Loading... - 正在加载…… - - - Reboot - 重启 - - - Update failed - 更新失败 - - - - WiFiPromptWidget - - Setup Wi-Fi - 设置 Wi-Fi 连接 - - - Connect to Wi-Fi to upload driving data and help improve openpilot - 请连接至 Wi-Fi 上传驾驶数据以协助改进openpilot - - - Open Settings - 打开设置 - - - Ready to upload - 准备好上传 - - - Training data will be pulled periodically while your device is on Wi-Fi - 训练数据将定期通过 Wi-Fi 上载 - - - - WifiUI - - Scanning for networks... - 正在扫描网络…… - - - CONNECTING... - 正在连接…… - - - FORGET - 忽略 - - - Forget Wi-Fi Network "%1"? - 忽略WiFi网络 "%1"? - - - Forget - 忽略 - - - diff --git a/selfdrive/ui/translations/main_zh-CHT.ts b/selfdrive/ui/translations/main_zh-CHT.ts deleted file mode 100644 index de8d3ff7018d68..00000000000000 --- a/selfdrive/ui/translations/main_zh-CHT.ts +++ /dev/null @@ -1,1135 +0,0 @@ - - - - - AbstractAlert - - Close - 關閉 - - - Snooze Update - 暫停更新 - - - Reboot and Update - 重啟並更新 - - - - AdvancedNetworking - - Back - 回上頁 - - - Enable Tethering - 啟用網路分享 - - - Tethering Password - 網路分享密碼 - - - EDIT - 編輯 - - - Enter new tethering password - 輸入新的網路分享密碼 - - - IP Address - IP 地址 - - - Enable Roaming - 啟用漫遊 - - - APN Setting - APN 設置 - - - Enter APN - 輸入 APN - - - leave blank for automatic configuration - 留空白將自動配置 - - - Cellular Metered - 行動網路 - - - Prevent large data uploads when on a metered connection - 防止使用行動網路上傳大量的數據 - - - Hidden Network - 隱藏的網路 - - - CONNECT - 連線 - - - Enter SSID - 輸入 SSID - - - Enter password - 輸入密碼 - - - for "%1" - 給 "%1" - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - 最高 - - - - ConfirmationDialog - - Ok - 確定 - - - Cancel - 取消 - - - - DeclinePage - - You must accept the Terms and Conditions in order to use openpilot. - 您必須先接受條款和條件才能使用 openpilot。 - - - Back - 回上頁 - - - Decline, uninstall %1 - 拒絕並解除安裝 %1 - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - 無法使用 - - - Serial - 序號 - - - Driver Camera - 駕駛員監控鏡頭 - - - PREVIEW - 預覽 - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - 預覽駕駛員監控鏡頭畫面,以確保其具有良好視野。(僅在熄火時可用) - - - Reset Calibration - 重設校準 - - - RESET - 重設 - - - Are you sure you want to reset calibration? - 您確定要重設校準嗎? - - - Review Training Guide - 觀看使用教學 - - - REVIEW - 觀看 - - - Review the rules, features, and limitations of openpilot - 觀看 openpilot 的使用規則、功能和限制 - - - Are you sure you want to review the training guide? - 您確定要觀看使用教學嗎? - - - Regulatory - 法規/監管 - - - VIEW - 觀看 - - - Change Language - 更改語言 - - - CHANGE - 更改 - - - Select a language - 選擇語言 - - - Reboot - 重新啟動 - - - Power Off - 關機 - - - openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required. - openpilot 需要將裝置固定在左右偏差 4° 以內,朝上偏差 5° 以內或朝下偏差 9° 以內。鏡頭在後台會持續自動校準,很少有需要重置的情況。 - - - Your device is pointed %1° %2 and %3° %4. - 你的裝置目前朝%2 %1° 以及朝%4 %3° 。 - - - down - 下 - - - up - 上 - - - left - 左 - - - right - 右 - - - Are you sure you want to reboot? - 您確定要重新啟動嗎? - - - Disengage to Reboot - 請先取消控車才能重新啟動 - - - Are you sure you want to power off? - 您確定您要關機嗎? - - - Disengage to Power Off - 請先取消控車才能關機 - - - Reset - 重設 - - - Review - 回顧 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 將您的裝置與 comma connect (connect.comma.ai) 配對並領取您的 comma 高級會員優惠。 - - - Pair Device - 配對裝置 - - - PAIR - 配對 - - - - DriverViewWindow - - camera starting - 開啟相機中 - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - 實驗模式 ON - - - CHILL MODE ON - 輕鬆模式 ON - - - - InputDialog - - Cancel - 取消 - - - Need at least %n character(s)! - - 需要至少 %n 個字元! - - - - - Installer - - Installing... - 安裝中… - - - - MultiOptionDialog - - Select - 選擇 - - - Cancel - 取消 - - - - Networking - - Advanced - 進階 - - - Enter password - 輸入密碼 - - - for "%1" - 給 "%1" - - - Wrong password - 密碼錯誤 - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, openpilot won't engage in %1 - 請立即連接網路檢查更新。如果不連接網路,openpilot 將在 %1 後便無法使用 - - - Connect to internet to check for updates. openpilot won't automatically start until it connects to internet to check for updates. - 請連接至網際網路以檢查更新。在連接至網際網路並完成更新檢查之前,openpilot 將不會自動啟動。 - - - Unable to download updates -%1 - 無法下載更新 -%1 - - - Taking camera snapshots. System won't start until finished. - 正在使用相機拍攝中。在完成之前,系統將無法啟動。 - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - 一個有關操作系統的更新正在後台下載中。當更新準備好安裝時,您將收到提示進行更新。 - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - 裝置註冊失敗。它將無法連接或上傳至 comma.ai 伺服器,並且無法獲得 comma.ai 的支援。如果這是一個官方裝置,請訪問 https://comma.ai/support 。 - - - NVMe drive not mounted. - NVMe 固態硬碟未被掛載。 - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - 檢測到不支援的 NVMe 固態硬碟。您的裝置因為使用了不支援的 NVMe 固態硬碟可能會消耗更多電力並更易過熱。 - - - openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - openpilot 無法識別您的車輛。您的車輛可能未被支援,或是其電控單元 (ECU) 未被識別。請提交一個 Pull Request 為您的車輛添加正確的韌體版本。需要幫助嗎?請加入 discord.comma.ai 。 - - - openpilot was unable to identify your car. Check integrity of cables and ensure all connections are secure, particularly that the comma power is fully inserted in the OBD-II port of the vehicle. Need help? Join discord.comma.ai. - openpilot 無法識別您的車輛。請檢查線路是否正確的安裝並確保所有的連接都牢固,特別是確保 comma power 完全插入車輛的 OBD-II 介面。需要幫助嗎?請加入 discord.comma.ai 。 - - - openpilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - openpilot 偵測到裝置的安裝位置發生變化。請確保裝置完全安裝在支架上,並確保支架牢固地固定在擋風玻璃上。 - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - 裝置溫度過高。系統正在冷卻中,等冷卻完畢後才會啟動。目前內部組件溫度:%1 - - - - OffroadHome - - UPDATE - 更新 - - - ALERTS - 提醒 - - - ALERT - 提醒 - - - - OnroadAlerts - - openpilot Unavailable - 無法使用 openpilot - - - Waiting for controls to start - 等待操控服務開始 - - - TAKE CONTROL IMMEDIATELY - 立即接管 - - - Controls Unresponsive - 操控服務沒有反應 - - - Reboot Device - 請重新啟裝置 - - - - PairingPopup - - Pair your device to your comma account - 將裝置與您的 comma 帳號配對 - - - Go to https://connect.comma.ai on your phone - 用手機連至 https://connect.comma.ai - - - Click "add new device" and scan the QR code on the right - 點選 "add new device" 後掃描右邊的二維碼 - - - Bookmark connect.comma.ai to your home screen to use it like an app - 將 connect.comma.ai 加入您的主螢幕,以便像手機 App 一樣使用它 - - - - ParamControl - - Cancel - 取消 - - - Enable - 啟用 - - - - PrimeAdWidget - - Upgrade Now - 馬上升級 - - - Become a comma prime member at connect.comma.ai - 成為 connect.comma.ai 的高級會員 - - - PRIME FEATURES: - 高級會員特點: - - - Remote access - 遠端存取 - - - 24/7 LTE connectivity - 24/7 LTE 連線 - - - 1 year of drive storage - 一年的行駛記錄儲存空間 - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ 已訂閱 - - - comma prime - comma 高級會員 - - - - QObject - - Reboot - 重新啟動 - - - Exit - 離開 - - - openpilot - openpilot - - - %n minute(s) ago - - %n 分鐘前 - - - - %n hour(s) ago - - %n 小時前 - - - - %n day(s) ago - - %n 天前 - - - - now - 現在 - - - - Reset - - Reset failed. Reboot to try again. - 重設失敗。請重新啟動後再試。 - - - Are you sure you want to reset your device? - 您確定要重設你的裝置嗎? - - - System Reset - 系統重設 - - - Cancel - 取消 - - - Reboot - 重新啟動 - - - Confirm - 確認 - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - 無法掛載資料分割區。分割區可能已經毀損。請確認是否要刪除並重置。 - - - Resetting device... -This may take up to a minute. - 重置中… -這可能需要一分鐘的時間。 - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - 系統重設已啟動。按下「確認」以清除所有內容和設定,或按下「取消」以繼續開機。 - - - - SettingsWindow - - × - × - - - Device - 裝置 - - - Network - 網路 - - - Toggles - 設定 - - - Software - 軟體 - - - - Setup - - WARNING: Low Voltage - 警告:電壓過低 - - - Power your device in a car with a harness or proceed at your own risk. - 請使用車上 harness 提供的電源,若繼續的話您需要自擔風險。 - - - Power off - 關機 - - - Continue - 繼續 - - - Getting Started - 入門 - - - Before we get on the road, let’s finish installation and cover some details. - 在我們上路之前,讓我們完成安裝並介紹一些細節。 - - - Connect to Wi-Fi - 連接到無線網路 - - - Back - 回上頁 - - - Continue without Wi-Fi - 在沒有 Wi-Fi 的情況下繼續 - - - Waiting for internet - 連接至網路中 - - - Enter URL - 輸入網址 - - - for Custom Software - 訂製的軟體 - - - Downloading... - 下載中… - - - Download Failed - 下載失敗 - - - Ensure the entered URL is valid, and the device’s internet connection is good. - 請確定您輸入的是有效的安裝網址,並且確定裝置的網路連線狀態良好。 - - - Reboot device - 重新啟動 - - - Start over - 重新開始 - - - No custom software found at this URL. - 在此網址找不到自訂軟體。 - - - Something went wrong. Reboot the device. - 發生了一些錯誤。請重新啟動您的裝置。 - - - Select a language - 選擇語言 - - - Choose Software to Install - 選擇要安裝的軟體 - - - openpilot - openpilot - - - Custom Software - 自訂軟體 - - - - SetupWidget - - Finish Setup - 完成設置 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 將您的裝置與 comma connect (connect.comma.ai) 配對並領取您的 comma 高級會員優惠。 - - - Pair device - 配對裝置 - - - - Sidebar - - CONNECT - 雲端服務 - - - OFFLINE - 已離線 - - - ONLINE - 已連線 - - - ERROR - 錯誤 - - - TEMP - 溫度 - - - HIGH - 偏高 - - - GOOD - 正常 - - - OK - 一般 - - - VEHICLE - 車輛通訊 - - - NO - 未連線 - - - PANDA - 車輛通訊 - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - 系統更新只會在熄火時下載。 - - - Current Version - 當前版本 - - - Download - 下載 - - - Install Update - 安裝更新 - - - INSTALL - 安裝 - - - Target Branch - 目標分支 - - - SELECT - 選取 - - - Select a branch - 選取一個分支 - - - UNINSTALL - 解除安裝 - - - Uninstall %1 - 解除安裝 %1 - - - Are you sure you want to uninstall? - 您確定您要解除安裝嗎? - - - CHECK - 檢查 - - - Uninstall - 解除安裝 - - - failed to check for update - 檢查更新失敗 - - - up to date, last checked %1 - 已經是最新版本,上次檢查時間為 %1 - - - DOWNLOAD - 下載 - - - update available - 有可用的更新 - - - never - 從未更新 - - - - SshControl - - SSH Keys - SSH 金鑰 - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - 警告:這將授權給 GitHub 帳號中所有公鑰 SSH 訪問權限。切勿輸入非您自己的 GitHub 使用者名稱。comma 員工「永遠不會」要求您添加他們的 GitHub 使用者名稱。 - - - ADD - 新增 - - - Enter your GitHub username - 請輸入您 GitHub 的使用者名稱 - - - LOADING - 載入中 - - - REMOVE - 移除 - - - Username '%1' has no keys on GitHub - GitHub 用戶 '%1' 沒有設定任何金鑰 - - - Request timed out - 請求超時 - - - Username '%1' doesn't exist on GitHub - GitHub 用戶 '%1' 不存在 - - - - SshToggle - - Enable SSH - 啟用 SSH 服務 - - - - TermsPage - - Terms & Conditions - 條款和條件 - - - Decline - 拒絕 - - - Scroll to accept - 滑動至頁尾接受條款 - - - Agree - 接受 - - - - TogglesPanel - - Enable openpilot - 啟用 openpilot - - - Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - 使用 openpilot 的主動式巡航和車道保持功能,開啟後您需要持續集中注意力,設定變更在重新啟動車輛後生效。 - - - Enable Lane Departure Warnings - 啟用車道偏離警告 - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 車速在時速 50 公里 (31 英里) 以上且未打方向燈的情況下,如果偵測到車輛駛出目前車道線時,發出車道偏離警告。 - - - Use Metric System - 使用公制單位 - - - Display speed in km/h instead of mph. - 啟用後,速度單位顯示將從 mp/h 改為 km/h。 - - - Record and Upload Driver Camera - 記錄並上傳駕駛監控影像 - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - 上傳駕駛監控的錄影來協助我們提升駕駛監控的準確率。 - - - Disengage on Accelerator Pedal - 油門取消控車 - - - When enabled, pressing the accelerator pedal will disengage openpilot. - 啟用後,踩踏油門將會取消 openpilot 控制。 - - - Experimental Mode - 實驗模式 - - - openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - openpilot 預設以 <b>輕鬆模式</b> 駕駛。 實驗模式啟用了尚未準備好進入輕鬆模式的 <b>alpha 級功能</b>。實驗功能如下: - - - Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - 讓駕駛模型來控制油門及煞車。openpilot將會模擬人類的駕駛行為,包含在看見紅燈及停止標示時停車。由於車速將由駕駛模型決定,因此您設定的時速將成為速度上限。本功能仍在早期實驗階段,請預期模型有犯錯的可能性。 - - - New Driving Visualization - 新的駕駛視覺介面 - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - 因車輛使用內建ACC系統,無法在本車輛上啟動實驗模式。 - - - openpilot longitudinal control may come in a future update. - openpilot 縱向控制可能會在未來的更新中提供。 - - - openpilot Longitudinal Control (Alpha) - openpilot 縱向控制 (Alpha 版) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - 警告:此車輛的 openpilot 縱向控制功能目前處於 Alpha 版本,使用此功能將會停用自動緊急煞車(AEB)功能。 - - - On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - 在這輛車上,openpilot 預設使用車輛內建的主動巡航控制(ACC),而非 openpilot 的縱向控制。啟用此項功能可切換至 openpilot 的縱向控制。當啟用 openpilot 縱向控制 Alpha 版本時,建議同時啟用實驗性模式(Experimental mode)。 - - - Aggressive - 積極 - - - Standard - 標準 - - - Relaxed - 舒適 - - - Driving Personality - 駕駛風格 - - - An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - 在正式 (release) 版以外的分支上可以測試 openpilot 縱向控制的 Alpha 版本以及實驗模式。 - - - Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode. - 啟用 openpilot 縱向控制(alpha)切換以允許實驗模式。 - - - End-to-End Longitudinal Control - 端到端縱向控制 - - - Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - 建議使用標準模式。在積極模式下,openpilot 會更接近前車並更積極地使用油門和剎車。在輕鬆模式下,openpilot 會與前車保持較遠距離。對於支援的汽車,您可以使用方向盤上的距離按鈕來切換這些駕駛風格。 - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - 在低速時,駕駛可視化將切換至道路朝向的廣角攝影機,以更好地顯示某些彎道。在右上角還會顯示「實驗模式」的標誌。 - - - Always-On Driver Monitoring - 駕駛監控常開 - - - Enable driver monitoring even when openpilot is not engaged. - 即使在openpilot未激活時也啟用駕駛監控。 - - - - Updater - - Update Required - 系統更新 - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - 需要進行作業系統更新。建議將您的裝置連接上 Wi-Fi 獲得更快的更新下載。下載大小約為 1GB。 - - - Connect to Wi-Fi - 連接到無線網路 - - - Install - 安裝 - - - Back - 回上頁 - - - Loading... - 載入中… - - - Reboot - 重新啟動 - - - Update failed - 更新失敗 - - - - WiFiPromptWidget - - Setup Wi-Fi - 設置 Wi-Fi 連接 - - - Connect to Wi-Fi to upload driving data and help improve openpilot - 請連接至 Wi-Fi 傳駕駛數據以協助改進 openpilot - - - Open Settings - 開啟設置 - - - Ready to upload - 準備好上傳 - - - Training data will be pulled periodically while your device is on Wi-Fi - 訓練數據將定期經過 Wi-Fi 上傳 - - - - WifiUI - - Scanning for networks... - 掃描無線網路中... - - - CONNECTING... - 連線中... - - - FORGET - 清除 - - - Forget Wi-Fi Network "%1"? - 清除 Wi-Fi 網路 "%1"? - - - Forget - 清除 - - - diff --git a/selfdrive/ui/translations/potools.py b/selfdrive/ui/translations/potools.py new file mode 100644 index 00000000000000..ac4dafb9888a4f --- /dev/null +++ b/selfdrive/ui/translations/potools.py @@ -0,0 +1,333 @@ +"""Pure Python tools for managing .po translation files. + +Replaces GNU gettext CLI tools (xgettext, msginit, msgmerge) with Python +implementations for extracting, creating, and updating .po files. +""" + +import ast +import os +import re +from dataclasses import dataclass, field +from pathlib import Path + + +@dataclass +class POEntry: + msgid: str = "" + msgstr: str = "" + msgid_plural: str = "" + msgstr_plural: dict[int, str] = field(default_factory=dict) + comments: list[str] = field(default_factory=list) + source_refs: list[str] = field(default_factory=list) + flags: list[str] = field(default_factory=list) + + @property + def is_plural(self) -> bool: + return bool(self.msgid_plural) + + +# ──── PO file parsing ──── + +def _parse_quoted(s: str) -> str: + """Parse a PO-format quoted string, handling escape sequences.""" + s = s.strip() + if not (s.startswith('"') and s.endswith('"')): + raise ValueError(f"Expected quoted string: {s!r}") + s = s[1:-1] + result = [] + i = 0 + while i < len(s): + if s[i] == '\\' and i + 1 < len(s): + c = s[i + 1] + if c == 'n': + result.append('\n') + elif c == 't': + result.append('\t') + elif c == '"': + result.append('"') + elif c == '\\': + result.append('\\') + else: + result.append(s[i:i + 2]) + i += 2 + else: + result.append(s[i]) + i += 1 + return ''.join(result) + + +def parse_po(path: str | Path) -> tuple[POEntry | None, list[POEntry]]: + """Parse a .po/.pot file. Returns (header_entry, entries).""" + with open(path, encoding='utf-8') as f: + lines = f.readlines() + + entries: list[POEntry] = [] + header: POEntry | None = None + cur: POEntry | None = None + cur_field: str | None = None + plural_idx = 0 + + def finish(): + nonlocal cur, header + if cur is None: + return + if cur.msgid == "" and cur.msgstr: + header = cur + elif cur.msgid != "" or cur.is_plural: + entries.append(cur) + cur = None + + for raw in lines: + line = raw.rstrip('\n') + stripped = line.strip() + + if not stripped: + finish() + cur_field = None + continue + + # Skip obsolete entries + if stripped.startswith('#~'): + continue + + if stripped.startswith('#'): + if cur is None: + cur = POEntry() + if stripped.startswith('#:'): + cur.source_refs.append(stripped[2:].strip()) + elif stripped.startswith('#,'): + cur.flags.extend(f.strip() for f in stripped[2:].split(',') if f.strip()) + else: + cur.comments.append(line) + continue + + if stripped.startswith('msgid_plural '): + if cur is None: + cur = POEntry() + cur.msgid_plural = _parse_quoted(stripped[len('msgid_plural '):]) + cur_field = 'msgid_plural' + continue + + if stripped.startswith('msgid '): + if cur is None: + cur = POEntry() + cur.msgid = _parse_quoted(stripped[len('msgid '):]) + cur_field = 'msgid' + continue + + m = re.match(r'msgstr\[(\d+)]\s+(.*)', stripped) + if m: + plural_idx = int(m.group(1)) + cur.msgstr_plural[plural_idx] = _parse_quoted(m.group(2)) + cur_field = 'msgstr_plural' + continue + + if stripped.startswith('msgstr '): + cur.msgstr = _parse_quoted(stripped[len('msgstr '):]) + cur_field = 'msgstr' + continue + + if stripped.startswith('"'): + val = _parse_quoted(stripped) + if cur_field == 'msgid': + cur.msgid += val + elif cur_field == 'msgid_plural': + cur.msgid_plural += val + elif cur_field == 'msgstr': + cur.msgstr += val + elif cur_field == 'msgstr_plural': + cur.msgstr_plural[plural_idx] += val + + finish() + return header, entries + + +# ──── PO file writing ──── + +def _quote(s: str) -> str: + """Quote a string for .po file output.""" + s = s.replace('\\', '\\\\').replace('"', '\\"').replace('\t', '\\t') + if '\n' in s and s != '\n': + parts = s.split('\n') + lines = ['""'] + for i, part in enumerate(parts): + text = part + ('\\n' if i < len(parts) - 1 else '') + if text: + lines.append(f'"{text}"') + return '\n'.join(lines) + return f'"{s}"'.replace('\n', '\\n') + + +def write_po(path: str | Path, header: POEntry | None, entries: list[POEntry]) -> None: + """Write a .po/.pot file.""" + with open(path, 'w', encoding='utf-8') as f: + if header: + for c in header.comments: + f.write(c + '\n') + f.write(f'msgid {_quote("")}\n') + f.write(f'msgstr {_quote(header.msgstr)}\n\n') + + for entry in entries: + for c in entry.comments: + f.write(c + '\n') + # Keep file-level context for translators, but drop line numbers to + # avoid churning PO diffs on unrelated code edits. + source_files = sorted({ref.rsplit(':', 1)[0] for ref in entry.source_refs}) + for ref in source_files: + f.write(f'#: {ref}\n') + # Runtime loading ignores gettext flags; omit them to reduce noise. + f.write(f'msgid {_quote(entry.msgid)}\n') + if entry.is_plural: + f.write(f'msgid_plural {_quote(entry.msgid_plural)}\n') + for idx in sorted(entry.msgstr_plural): + f.write(f'msgstr[{idx}] {_quote(entry.msgstr_plural[idx])}\n') + else: + f.write(f'msgstr {_quote(entry.msgstr)}\n') + f.write('\n') + + +# ──── String extraction (replaces xgettext) ──── + +def extract_strings(files: list[str], basedir: str) -> list[POEntry]: + """Extract tr/trn/tr_noop calls from Python source files.""" + seen: dict[str, POEntry] = {} + + for filepath in files: + full = os.path.join(basedir, filepath) + with open(full, encoding='utf-8') as f: + source = f.read() + try: + tree = ast.parse(source, filename=filepath) + except SyntaxError: + continue + + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + + func = node.func + if isinstance(func, ast.Name): + name = func.id + elif isinstance(func, ast.Attribute): + name = func.attr + else: + continue + + if name not in ('tr', 'trn', 'tr_noop'): + continue + + ref = f'{filepath}:{node.lineno}' + is_flagged = name in ('tr', 'trn') + + if name in ('tr', 'tr_noop'): + if not node.args or not isinstance(node.args[0], ast.Constant) or not isinstance(node.args[0].value, str): + continue + msgid = node.args[0].value + if msgid in seen: + if ref not in seen[msgid].source_refs: + seen[msgid].source_refs.append(ref) + else: + flags = ['python-format'] if is_flagged else [] + seen[msgid] = POEntry(msgid=msgid, source_refs=[ref], flags=flags) + + elif name == 'trn': + if len(node.args) < 2: + continue + a1, a2 = node.args[0], node.args[1] + if not (isinstance(a1, ast.Constant) and isinstance(a1.value, str)): + continue + if not (isinstance(a2, ast.Constant) and isinstance(a2.value, str)): + continue + msgid, msgid_plural = a1.value, a2.value + if msgid in seen: + if ref not in seen[msgid].source_refs: + seen[msgid].source_refs.append(ref) + else: + flags = ['python-format'] if is_flagged else [] + seen[msgid] = POEntry( + msgid=msgid, msgid_plural=msgid_plural, + source_refs=[ref], flags=flags, + msgstr_plural={0: '', 1: ''}, + ) + + return list(seen.values()) + + +# ──── POT generation ──── + +def _build_pot_header() -> POEntry: + return POEntry( + msgstr='Content-Type: text/plain; charset=UTF-8\n', + ) + + +def _build_po_header(language: str) -> POEntry: + plural_forms = PLURAL_FORMS.get(language, 'nplurals=2; plural=(n != 1);') + return POEntry( + msgstr='Content-Type: text/plain; charset=UTF-8\n' + + f'Language: {language}\n' + + f'Plural-Forms: {plural_forms}\n', + ) + + +def generate_pot(entries: list[POEntry], pot_path: str | Path) -> None: + """Generate a .pot template file from extracted entries.""" + write_po(pot_path, _build_pot_header(), entries) + + +# ──── PO init (replaces msginit) ──── + +PLURAL_FORMS: dict[str, str] = { + 'en': 'nplurals=2; plural=(n != 1);', + 'de': 'nplurals=2; plural=(n != 1);', + 'fr': 'nplurals=2; plural=(n > 1);', + 'es': 'nplurals=2; plural=(n != 1);', + 'pt-BR': 'nplurals=2; plural=(n > 1);', + 'tr': 'nplurals=2; plural=(n != 1);', + 'uk': 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);', + 'th': 'nplurals=1; plural=0;', + 'zh-CHT': 'nplurals=1; plural=0;', + 'zh-CHS': 'nplurals=1; plural=0;', + 'ko': 'nplurals=1; plural=0;', + 'ja': 'nplurals=1; plural=0;', +} + + +def init_po(pot_path: str | Path, po_path: str | Path, language: str) -> None: + """Create a new .po file from a .pot template (replaces msginit).""" + _, entries = parse_po(pot_path) + plural_forms = PLURAL_FORMS.get(language, 'nplurals=2; plural=(n != 1);') + + nplurals = int(re.search(r'nplurals=(\d+)', plural_forms).group(1)) + for e in entries: + if e.is_plural: + e.msgstr_plural = dict.fromkeys(range(nplurals), '') + + write_po(po_path, _build_po_header(language), entries) + + +# ──── PO merge (replaces msgmerge) ──── + +def merge_po(po_path: str | Path, pot_path: str | Path) -> None: + """Update a .po file with entries from a .pot template (replaces msgmerge --update).""" + _, po_entries = parse_po(po_path) + _, pot_entries = parse_po(pot_path) + language = Path(po_path).stem.removeprefix("app_") + + existing = {e.msgid: e for e in po_entries} + merged = [] + + for pot_e in pot_entries: + if pot_e.msgid in existing: + old = existing[pot_e.msgid] + old.source_refs = pot_e.source_refs + old.flags = pot_e.flags + old.comments = pot_e.comments + if pot_e.is_plural: + old.msgid_plural = pot_e.msgid_plural + merged.append(old) + else: + merged.append(pot_e) + + merged.sort(key=lambda e: e.msgid) + write_po(po_path, _build_po_header(language), merged) diff --git a/selfdrive/ui/translations/update_translations.py b/selfdrive/ui/translations/update_translations.py new file mode 100755 index 00000000000000..6ff3667d8a9812 --- /dev/null +++ b/selfdrive/ui/translations/update_translations.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +from itertools import chain +import os +from openpilot.common.basedir import BASEDIR +from openpilot.system.ui.lib.multilang import SYSTEM_UI_DIR, UI_DIR, TRANSLATIONS_DIR, multilang +from openpilot.selfdrive.ui.translations.potools import extract_strings, generate_pot, merge_po, init_po + +LANGUAGES_FILE = os.path.join(str(TRANSLATIONS_DIR), "languages.json") +POT_FILE = os.path.join(str(TRANSLATIONS_DIR), "app.pot") + + +def update_translations(): + files = [] + for root, _, filenames in chain(os.walk(SYSTEM_UI_DIR), + os.walk(os.path.join(UI_DIR, "widgets")), + os.walk(os.path.join(UI_DIR, "layouts")), + os.walk(os.path.join(UI_DIR, "onroad"))): + for filename in filenames: + if filename.endswith(".py"): + files.append(os.path.relpath(os.path.join(root, filename), BASEDIR)) + + # Extract translatable strings and generate .pot template + entries = extract_strings(files, BASEDIR) + generate_pot(entries, POT_FILE) + + # Generate/update translation files for each language + for name in multilang.languages.values(): + po_file = os.path.join(TRANSLATIONS_DIR, f"app_{name}.po") + if os.path.exists(po_file): + merge_po(po_file, POT_FILE) + else: + init_po(POT_FILE, po_file, name) + + +if __name__ == "__main__": + update_translations() diff --git a/selfdrive/ui/ui.cc b/selfdrive/ui/ui.cc deleted file mode 100644 index 1a3198c936a0f5..00000000000000 --- a/selfdrive/ui/ui.cc +++ /dev/null @@ -1,335 +0,0 @@ -#include "selfdrive/ui/ui.h" - -#include -#include -#include - -#include - -#include "common/transformations/orientation.hpp" -#include "common/params.h" -#include "common/swaglog.h" -#include "common/util.h" -#include "common/watchdog.h" -#include "system/hardware/hw.h" - -#define BACKLIGHT_DT 0.05 -#define BACKLIGHT_TS 10.00 - -// Projects a point in car to space to the corresponding point in full frame -// image space. -static bool calib_frame_to_full_frame(const UIState *s, float in_x, float in_y, float in_z, QPointF *out) { - const float margin = 500.0f; - const QRectF clip_region{-margin, -margin, s->fb_w + 2 * margin, s->fb_h + 2 * margin}; - - const vec3 pt = (vec3){{in_x, in_y, in_z}}; - const vec3 Ep = matvecmul3(s->scene.wide_cam ? s->scene.view_from_wide_calib : s->scene.view_from_calib, pt); - const vec3 KEp = matvecmul3(s->scene.wide_cam ? ECAM_INTRINSIC_MATRIX : FCAM_INTRINSIC_MATRIX, Ep); - - // Project. - QPointF point = s->car_space_transform.map(QPointF{KEp.v[0] / KEp.v[2], KEp.v[1] / KEp.v[2]}); - if (clip_region.contains(point)) { - *out = point; - return true; - } - return false; -} - -int get_path_length_idx(const cereal::XYZTData::Reader &line, const float path_height) { - const auto line_x = line.getX(); - int max_idx = 0; - for (int i = 1; i < line_x.size() && line_x[i] <= path_height; ++i) { - max_idx = i; - } - return max_idx; -} - -void update_leads(UIState *s, const cereal::RadarState::Reader &radar_state, const cereal::XYZTData::Reader &line) { - for (int i = 0; i < 2; ++i) { - auto lead_data = (i == 0) ? radar_state.getLeadOne() : radar_state.getLeadTwo(); - if (lead_data.getStatus()) { - float z = line.getZ()[get_path_length_idx(line, lead_data.getDRel())]; - calib_frame_to_full_frame(s, lead_data.getDRel(), -lead_data.getYRel(), z + 1.22, &s->scene.lead_vertices[i]); - } - } -} - -void update_line_data(const UIState *s, const cereal::XYZTData::Reader &line, - float y_off, float z_off, QPolygonF *pvd, int max_idx, bool allow_invert=true) { - const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ(); - QPointF left, right; - pvd->clear(); - for (int i = 0; i <= max_idx; i++) { - // highly negative x positions are drawn above the frame and cause flickering, clip to zy plane of camera - if (line_x[i] < 0) continue; - - bool l = calib_frame_to_full_frame(s, line_x[i], line_y[i] - y_off, line_z[i] + z_off, &left); - bool r = calib_frame_to_full_frame(s, line_x[i], line_y[i] + y_off, line_z[i] + z_off, &right); - if (l && r) { - // For wider lines the drawn polygon will "invert" when going over a hill and cause artifacts - if (!allow_invert && pvd->size() && left.y() > pvd->back().y()) { - continue; - } - pvd->push_back(left); - pvd->push_front(right); - } - } -} - -void update_model(UIState *s, - const cereal::ModelDataV2::Reader &model) { - UIScene &scene = s->scene; - auto model_position = model.getPosition(); - float max_distance = std::clamp(*(model_position.getX().end() - 1), - MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE); - - // update lane lines - const auto lane_lines = model.getLaneLines(); - const auto lane_line_probs = model.getLaneLineProbs(); - int max_idx = get_path_length_idx(lane_lines[0], max_distance); - for (int i = 0; i < std::size(scene.lane_line_vertices); i++) { - scene.lane_line_probs[i] = lane_line_probs[i]; - update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 0, &scene.lane_line_vertices[i], max_idx); - } - - // update road edges - const auto road_edges = model.getRoadEdges(); - const auto road_edge_stds = model.getRoadEdgeStds(); - for (int i = 0; i < std::size(scene.road_edge_vertices); i++) { - scene.road_edge_stds[i] = road_edge_stds[i]; - update_line_data(s, road_edges[i], 0.025, 0, &scene.road_edge_vertices[i], max_idx); - } - - // update path - auto lead_one = (*s->sm)["radarState"].getRadarState().getLeadOne(); - if (lead_one.getStatus()) { - const float lead_d = lead_one.getDRel() * 2.; - max_distance = std::clamp((float)(lead_d - fmin(lead_d * 0.35, 10.)), 0.0f, max_distance); - } - max_idx = get_path_length_idx(model_position, max_distance); - update_line_data(s, model_position, 0.9, 1.22, &scene.track_vertices, max_idx, false); -} - -static void update_sockets(UIState *s) { - s->sm->update(0); -} - -static void update_state(UIState *s) { - SubMaster &sm = *(s->sm); - UIScene &scene = s->scene; - - if (sm.updated("liveCalibration")) { - auto live_calib = sm["liveCalibration"].getLiveCalibration(); - auto rpy_list = live_calib.getRpyCalib(); - auto wfde_list = live_calib.getWideFromDeviceEuler(); - Eigen::Vector3d rpy; - Eigen::Vector3d wfde; - if (rpy_list.size() == 3) rpy << rpy_list[0], rpy_list[1], rpy_list[2]; - if (wfde_list.size() == 3) wfde << wfde_list[0], wfde_list[1], wfde_list[2]; - Eigen::Matrix3d device_from_calib = euler2rot(rpy); - Eigen::Matrix3d wide_from_device = euler2rot(wfde); - Eigen::Matrix3d view_from_device; - view_from_device << 0, 1, 0, - 0, 0, 1, - 1, 0, 0; - Eigen::Matrix3d view_from_calib = view_from_device * device_from_calib; - Eigen::Matrix3d view_from_wide_calib = view_from_device * wide_from_device * device_from_calib; - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - scene.view_from_calib.v[i*3 + j] = view_from_calib(i, j); - scene.view_from_wide_calib.v[i*3 + j] = view_from_wide_calib(i, j); - } - } - scene.calibration_valid = live_calib.getCalStatus() == cereal::LiveCalibrationData::Status::CALIBRATED; - scene.calibration_wide_valid = wfde_list.size() == 3; - } - if (sm.updated("pandaStates")) { - auto pandaStates = sm["pandaStates"].getPandaStates(); - if (pandaStates.size() > 0) { - scene.pandaType = pandaStates[0].getPandaType(); - - if (scene.pandaType != cereal::PandaState::PandaType::UNKNOWN) { - scene.ignition = false; - for (const auto& pandaState : pandaStates) { - scene.ignition |= pandaState.getIgnitionLine() || pandaState.getIgnitionCan(); - } - } - } - } else if ((s->sm->frame - s->sm->rcv_frame("pandaStates")) > 5*UI_FREQ) { - scene.pandaType = cereal::PandaState::PandaType::UNKNOWN; - } - if (sm.updated("carParams")) { - scene.longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); - } - if (sm.updated("wideRoadCameraState")) { - auto cam_state = sm["wideRoadCameraState"].getWideRoadCameraState(); - float scale = (cam_state.getSensor() == cereal::FrameData::ImageSensor::AR0231) ? 6.0f : 1.0f; - scene.light_sensor = std::max(100.0f - scale * cam_state.getExposureValPercent(), 0.0f); - } else if (!sm.allAliveAndValid({"wideRoadCameraState"})) { - scene.light_sensor = -1; - } - scene.started = sm["deviceState"].getDeviceState().getStarted() && scene.ignition; - - scene.world_objects_visible = scene.world_objects_visible || - (scene.started && - sm.rcv_frame("liveCalibration") > scene.started_frame && - sm.rcv_frame("modelV2") > scene.started_frame); -} - -void ui_update_params(UIState *s) { - auto params = Params(); - s->scene.is_metric = params.getBool("IsMetric"); -} - -void UIState::updateStatus() { - if (scene.started && sm->updated("selfdriveState")) { - auto ss = (*sm)["selfdriveState"].getSelfdriveState(); - auto state = ss .getState(); - if (state == cereal::SelfdriveState::OpenpilotState::PRE_ENABLED || state == cereal::SelfdriveState::OpenpilotState::OVERRIDING) { - status = STATUS_OVERRIDE; - } else { - status = ss.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; - } - } - - // Handle onroad/offroad transition - if (scene.started != started_prev || sm->frame == 1) { - if (scene.started) { - status = STATUS_DISENGAGED; - scene.started_frame = sm->frame; - } - started_prev = scene.started; - scene.world_objects_visible = false; - emit offroadTransition(!scene.started); - } -} - -UIState::UIState(QObject *parent) : QObject(parent) { - sm = std::make_unique(std::vector{ - "modelV2", "controlsState", "liveCalibration", "radarState", "deviceState", - "pandaStates", "carParams", "driverMonitoringState", "carState", "driverStateV2", - "wideRoadCameraState", "managerState", "selfdriveState", - }); - - Params params; - language = QString::fromStdString(params.get("LanguageSetting")); - auto prime_value = params.get("PrimeType"); - if (!prime_value.empty()) { - prime_type = static_cast(std::atoi(prime_value.c_str())); - } - - // update timer - timer = new QTimer(this); - QObject::connect(timer, &QTimer::timeout, this, &UIState::update); - timer->start(1000 / UI_FREQ); -} - -void UIState::update() { - update_sockets(this); - update_state(this); - updateStatus(); - - if (std::getenv("PRIME_TYPE")) { - setPrimeType((PrimeType)atoi(std::getenv("PRIME_TYPE"))); - } - - if (sm->frame % UI_FREQ == 0) { - watchdog_kick(nanos_since_boot()); - } - emit uiUpdate(*this); -} - -void UIState::setPrimeType(PrimeType type) { - if (type != prime_type) { - bool prev_prime = hasPrime(); - - prime_type = type; - Params().put("PrimeType", std::to_string(prime_type)); - emit primeTypeChanged(prime_type); - - bool prime = hasPrime(); - if (prev_prime != prime) { - emit primeChanged(prime); - } - } -} - -Device::Device(QObject *parent) : brightness_filter(BACKLIGHT_OFFROAD, BACKLIGHT_TS, BACKLIGHT_DT), QObject(parent) { - setAwake(true); - resetInteractiveTimeout(); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &Device::update); -} - -void Device::update(const UIState &s) { - updateBrightness(s); - updateWakefulness(s); -} - -void Device::setAwake(bool on) { - if (on != awake) { - awake = on; - Hardware::set_display_power(awake); - LOGD("setting display power %d", awake); - emit displayPowerChanged(awake); - } -} - -void Device::resetInteractiveTimeout(int timeout) { - if (timeout == -1) { - timeout = (ignition_on ? 10 : 30); - } - interactive_timeout = timeout * UI_FREQ; -} - -void Device::updateBrightness(const UIState &s) { - float clipped_brightness = offroad_brightness; - if (s.scene.started && s.scene.light_sensor > 0) { - clipped_brightness = s.scene.light_sensor; - - // CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm - if (clipped_brightness <= 8) { - clipped_brightness = (clipped_brightness / 903.3); - } else { - clipped_brightness = std::pow((clipped_brightness + 16.0) / 116.0, 3.0); - } - - // Scale back to 10% to 100% - clipped_brightness = std::clamp(100.0f * clipped_brightness, 10.0f, 100.0f); - } - - int brightness = brightness_filter.update(clipped_brightness); - if (!awake) { - brightness = 0; - } - - if (brightness != last_brightness) { - if (!brightness_future.isRunning()) { - brightness_future = QtConcurrent::run(Hardware::set_brightness, brightness); - last_brightness = brightness; - } - } -} - -void Device::updateWakefulness(const UIState &s) { - bool ignition_just_turned_off = !s.scene.ignition && ignition_on; - ignition_on = s.scene.ignition; - - if (ignition_just_turned_off) { - resetInteractiveTimeout(); - } else if (interactive_timeout > 0 && --interactive_timeout == 0) { - emit interactiveTimeout(); - } - - setAwake(s.scene.ignition || interactive_timeout > 0); -} - -UIState *uiState() { - static UIState ui_state; - return &ui_state; -} - -Device *device() { - static Device _device; - return &_device; -} diff --git a/selfdrive/ui/ui.h b/selfdrive/ui/ui.h deleted file mode 100644 index 73b8c5ddeb6012..00000000000000 --- a/selfdrive/ui/ui.h +++ /dev/null @@ -1,172 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "common/mat.h" -#include "common/params.h" -#include "common/timing.h" -#include "system/hardware/hw.h" - -const int UI_BORDER_SIZE = 30; -const int UI_HEADER_HEIGHT = 420; - -const int UI_FREQ = 20; // Hz -const int BACKLIGHT_OFFROAD = 50; - -const float MIN_DRAW_DISTANCE = 10.0; -const float MAX_DRAW_DISTANCE = 100.0; -constexpr mat3 DEFAULT_CALIBRATION = {{ 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0 }}; -constexpr mat3 FCAM_INTRINSIC_MATRIX = (mat3){{2648.0, 0.0, 1928.0 / 2, - 0.0, 2648.0, 1208.0 / 2, - 0.0, 0.0, 1.0}}; -// tici ecam focal probably wrong? magnification is not consistent across frame -// Need to retrain model before this can be changed -constexpr mat3 ECAM_INTRINSIC_MATRIX = (mat3){{567.0, 0.0, 1928.0 / 2, - 0.0, 567.0, 1208.0 / 2, - 0.0, 0.0, 1.0}}; - -typedef enum UIStatus { - STATUS_DISENGAGED, - STATUS_OVERRIDE, - STATUS_ENGAGED, -} UIStatus; - -enum PrimeType { - PRIME_TYPE_UNKNOWN = -2, - PRIME_TYPE_UNPAIRED = -1, - PRIME_TYPE_NONE = 0, - PRIME_TYPE_MAGENTA = 1, - PRIME_TYPE_LITE = 2, - PRIME_TYPE_BLUE = 3, - PRIME_TYPE_MAGENTA_NEW = 4, - PRIME_TYPE_PURPLE = 5, -}; - -const QColor bg_colors [] = { - [STATUS_DISENGAGED] = QColor(0x17, 0x33, 0x49, 0xc8), - [STATUS_OVERRIDE] = QColor(0x91, 0x9b, 0x95, 0xf1), - [STATUS_ENGAGED] = QColor(0x17, 0x86, 0x44, 0xf1), -}; - - -typedef struct UIScene { - bool calibration_valid = false; - bool calibration_wide_valid = false; - bool wide_cam = true; - mat3 view_from_calib = DEFAULT_CALIBRATION; - mat3 view_from_wide_calib = DEFAULT_CALIBRATION; - cereal::PandaState::PandaType pandaType; - - // modelV2 - float lane_line_probs[4]; - float road_edge_stds[2]; - QPolygonF track_vertices; - QPolygonF lane_line_vertices[4]; - QPolygonF road_edge_vertices[2]; - - // lead - QPointF lead_vertices[2]; - - cereal::LongitudinalPersonality personality; - - float light_sensor = -1; - bool started, ignition, is_metric, longitudinal_control; - bool world_objects_visible = false; - uint64_t started_frame; -} UIScene; - -class UIState : public QObject { - Q_OBJECT - -public: - UIState(QObject* parent = 0); - void updateStatus(); - inline bool engaged() const { - return scene.started && (*sm)["selfdriveState"].getSelfdriveState().getEnabled(); - } - - void setPrimeType(PrimeType type); - inline PrimeType primeType() const { return prime_type; } - inline bool hasPrime() const { return prime_type > PrimeType::PRIME_TYPE_NONE; } - - int fb_w = 0, fb_h = 0; - - std::unique_ptr sm; - - UIStatus status; - UIScene scene = {}; - - QString language; - - QTransform car_space_transform; - -signals: - void uiUpdate(const UIState &s); - void offroadTransition(bool offroad); - void primeChanged(bool prime); - void primeTypeChanged(PrimeType prime_type); - -private slots: - void update(); - -private: - QTimer *timer; - bool started_prev = false; - PrimeType prime_type = PrimeType::PRIME_TYPE_UNKNOWN; -}; - -UIState *uiState(); - -// device management class -class Device : public QObject { - Q_OBJECT - -public: - Device(QObject *parent = 0); - bool isAwake() { return awake; } - void setOffroadBrightness(int brightness) { - offroad_brightness = std::clamp(brightness, 0, 100); - } - -private: - bool awake = false; - int interactive_timeout = 0; - bool ignition_on = false; - - int offroad_brightness = BACKLIGHT_OFFROAD; - int last_brightness = 0; - FirstOrderFilter brightness_filter; - QFuture brightness_future; - - void updateBrightness(const UIState &s); - void updateWakefulness(const UIState &s); - void setAwake(bool on); - -signals: - void displayPowerChanged(bool on); - void interactiveTimeout(); - -public slots: - void resetInteractiveTimeout(int timeout = -1); - void update(const UIState &s); -}; - -Device *device(); - -void ui_update_params(UIState *s); -int get_path_length_idx(const cereal::XYZTData::Reader &line, const float path_height); -void update_model(UIState *s, - const cereal::ModelDataV2::Reader &model); -void update_dmonitoring(UIState *s, const cereal::DriverStateV2::Reader &driverstate, float dm_fade_state, bool is_rhd); -void update_leads(UIState *s, const cereal::RadarState::Reader &radar_state, const cereal::XYZTData::Reader &line); -void update_line_data(const UIState *s, const cereal::XYZTData::Reader &line, - float y_off, float z_off, QPolygonF *pvd, int max_idx, bool allow_invert); diff --git a/selfdrive/ui/ui.py b/selfdrive/ui/ui.py new file mode 100755 index 00000000000000..e01ddb25132713 --- /dev/null +++ b/selfdrive/ui/ui.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +import os +import time + +from cereal import messaging +from openpilot.system.hardware import TICI +from openpilot.common.realtime import Priority, config_realtime_process, set_core_affinity +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.layouts.main import MainLayout +from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout +from openpilot.selfdrive.ui.ui_state import ui_state + +BIG_UI = gui_app.big_ui() + + +def main(): + cores = {5, } + # above plannerd and radard + config_realtime_process(0, Priority.CTRL_HIGH) + + gui_app.init_window("UI") + if BIG_UI: + MainLayout() + else: + MiciMainLayout() + + pm = messaging.PubMaster(['uiDebug']) + for should_render, frame_time, cpu_time in gui_app.render(): + extra_start = time.monotonic() + ui_state.update() + + if should_render: + # reaffine after power save offlines our core + if TICI and os.sched_getaffinity(0) != cores: + try: + set_core_affinity(list(cores)) + except OSError: + pass + + extra_cpu = time.monotonic() - extra_start + msg = messaging.new_message('uiDebug') + msg.uiDebug.cpuTimeMillis = (cpu_time + extra_cpu) * 1000 + msg.uiDebug.frameTimeMillis = frame_time * 1000 + pm.send('uiDebug', msg) + + +if __name__ == "__main__": + main() diff --git a/selfdrive/ui/ui_state.py b/selfdrive/ui/ui_state.py new file mode 100644 index 00000000000000..e0b77f9ffca7d4 --- /dev/null +++ b/selfdrive/ui/ui_state.py @@ -0,0 +1,363 @@ +import pyray as rl +import numpy as np +import time +import threading +from collections.abc import Callable +from enum import Enum +from cereal import messaging, car, log +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.params import Params +from openpilot.common.realtime import drop_realtime +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.lib.prime_state import PrimeState +from openpilot.selfdrive.ui.radar.bosch_status import BoschRadarMonitor, BoschRadarStatus +from openpilot.selfdrive.controls.lib.driver_lateral_handoff import hud_engaged_status +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.hardware import HARDWARE, PC + +BACKLIGHT_OFFROAD = 65 if HARDWARE.get_device_type() == "mici" else 50 +PARAM_UPDATE_TIME = 1 / 5.0 + + +class UIStatus(Enum): + DISENGAGED = "disengaged" + ENGAGED = "engaged" + OVERRIDE = "override" + + +class UIState: + _instance: 'UIState | None' = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super().__new__(cls) + cls._instance._initialize() + return cls._instance + + def _initialize(self): + self.params = Params() + self.sm = messaging.SubMaster( + [ + "modelV2", + "controlsState", + "onroadEvents", + "liveCalibration", + "radarState", + "deviceState", + "pandaStates", + "carParams", + "driverMonitoringState", + "carState", + "driverStateV2", + "roadCameraState", + "wideRoadCameraState", + "managerState", + "selfdriveState", + "longitudinalPlan", + "gpsLocationExternal", + "carOutput", + "carControl", + "liveParameters", + "liveMapDataNAP", + "liveSpeedSignNAP", + "testJoystick", + "rawAudioData", + "liveTracks", + "can", + ] + ) + + self.prime_state = PrimeState() + + # UI Status tracking + self.status: UIStatus = UIStatus.DISENGAGED + self.started_frame: int = 0 + self.started_time: float = 0.0 + self._engaged_prev: bool = False + self._started_prev: bool = False + + # Core state variables + self.is_metric: bool = self.params.get_bool("IsMetric") + self.is_release = self.params.get_bool("IsReleaseBranch") + self.always_on_dm: bool = self.params.get_bool("AlwaysOnDM") + self.experimental_mode: bool = self.params.get_bool("ExperimentalMode") + self.usbgpu: bool = self.params.get_bool("UsbGpuPresent") + self.usbgpu_compiled: bool = self.params.get_bool("UsbGpuCompiled") + self.started: bool = False + self.ignition: bool = False + self.recording_audio: bool = False + self.panda_type: log.PandaState.PandaType = log.PandaState.PandaType.unknown + self.personality: log.LongitudinalPersonality = log.LongitudinalPersonality.standard + self.has_longitudinal_control: bool = False + self.is_body: bool | None = None + self.CP: car.CarParams | None = None + self.light_sensor: float = -1.0 + self.radar_monitor = BoschRadarMonitor() + self.radar_status = BoschRadarStatus() + self.radar_hud: bool = False + self.speed_sign_log: bool = False + + self._params_thread: threading.Thread | None = None + + # Callbacks + self._offroad_transition_callbacks: list[Callable[[], None]] = [] + self._engaged_transition_callbacks: list[Callable[[], None]] = [] + self._on_body_changed_callbacks: list[Callable[[], None]] = [] + + def add_offroad_transition_callback(self, callback: Callable[[], None]): + self._offroad_transition_callbacks.append(callback) + + def add_engaged_transition_callback(self, callback: Callable[[], None]): + self._engaged_transition_callbacks.append(callback) + + def add_on_body_changed_callbacks(self, callback: Callable[[], None]): + self._on_body_changed_callbacks.append(callback) + + @property + def engaged(self) -> bool: + return self.started and self.sm["selfdriveState"].enabled + + def is_onroad(self) -> bool: + return self.started + + def is_offroad(self) -> bool: + return not self.started + + def update(self) -> None: + self.prime_state.start() # start thread after manager forks ui + if self._params_thread is None: + self._params_thread = threading.Thread(target=self._params_refresh_worker, daemon=True) + self._params_thread.start() + + self.sm.update(0) + self._update_state() + self._update_status() + device.update() + + def _params_refresh_worker(self): + drop_realtime() + while True: + self.update_params() + time.sleep(PARAM_UPDATE_TIME) + + def _update_state(self) -> None: + # Handle panda states updates + if self.sm.updated["pandaStates"]: + panda_states = self.sm["pandaStates"] + + if len(panda_states) > 0: + # Get panda type from first panda + self.panda_type = panda_states[0].pandaType + # Check ignition status across all pandas + if self.panda_type != log.PandaState.PandaType.unknown: + self.ignition = any(state.ignitionLine or state.ignitionCan for state in panda_states) + elif self.sm.frame - self.sm.recv_frame["pandaStates"] > 5 * rl.get_fps(): + self.panda_type = log.PandaState.PandaType.unknown + + # Handle wide road camera state updates + if self.sm.updated["wideRoadCameraState"]: + cam_state = self.sm["wideRoadCameraState"] + self.light_sensor = max(100.0 - cam_state.exposureValPercent, 0.0) + elif not self.sm.alive["wideRoadCameraState"] or not self.sm.valid["wideRoadCameraState"]: + self.light_sensor = -1 + + # started comes from hardwared (deviceState.started). NAP Force Offroad + # clears that flag so manager stops the onroad stack. Do not OR a + # UI-only override here — buttons would unlock while OP still engages. + self.started = self.sm["deviceState"].started and self.ignition + + # Update body state + if self.CP is not None and self.is_body != self.CP.notCar: + self.is_body = self.CP.notCar + for callback in self._on_body_changed_callbacks: + callback() + + self._update_radar_monitor() + + def _update_status(self) -> None: + if self.started and (self.sm.updated["selfdriveState"] or self.sm.updated["controlsState"]): + ss = self.sm["selfdriveState"] + lat_active = False + if self.sm.updated.get("carControl") or self.sm.recv_frame.get("carControl", 0) > 0: + lat_active = bool(self.sm["carControl"].latActive) + lat_handoff_paused = False + if self.sm.recv_frame.get("controlsState", 0) > 0: + lat_handoff_paused = bool(self.sm["controlsState"].latHandoffPaused) + + status_name = hud_engaged_status( + enabled=bool(ss.enabled), + op_state=ss.state, + lat_active=lat_active, + lat_handoff_paused=lat_handoff_paused, + ) + self.status = UIStatus(status_name) + + # Check for engagement state changes + if self.engaged != self._engaged_prev: + for callback in self._engaged_transition_callbacks: + callback() + self._engaged_prev = self.engaged + + # Handle onroad/offroad transition + if self.started != self._started_prev or self.sm.frame == 1: + if self.started: + self.status = UIStatus.DISENGAGED + self.started_frame = self.sm.frame + self.started_time = time.monotonic() + + for callback in self._offroad_transition_callbacks: + callback() + + self._started_prev = self.started + + def update_params(self) -> None: + # For slower operations + # Update longitudinal control state + CP_bytes = self.params.get("CarParamsPersistent") + if CP_bytes is not None: + self.CP = messaging.log_from_bytes(CP_bytes, car.CarParams) + if self.CP.alphaLongitudinalAvailable: + self.has_longitudinal_control = self.params.get_bool("AlphaLongitudinalEnabled") + else: + self.has_longitudinal_control = self.CP.openpilotLongitudinalControl + + self.recording_audio = self.params.get_bool("RecordAudio") and self.started + self.is_metric = self.params.get_bool("IsMetric") + self.always_on_dm = self.params.get_bool("AlwaysOnDM") + self.experimental_mode = self.params.get_bool("ExperimentalMode") + self.usbgpu = self.params.get_bool("UsbGpuPresent") + self.usbgpu_compiled = self.params.get_bool("UsbGpuCompiled") + try: + self.radar_hud = self.params.get_bool("NAPRadarHud") + except Exception: + self.radar_hud = False + try: + self.speed_sign_log = self.params.get_bool("NAPSpeedSignLog") + except Exception: + self.speed_sign_log = False + + def _update_radar_monitor(self) -> None: + can_messages = [] + if self.sm.updated.get("can", False): + can_messages = [(int(c.address), bytes(c.dat), int(c.src)) for c in self.sm["can"]] + live_tracks = self.sm["liveTracks"] if self.sm.updated.get("liveTracks", False) else None + if can_messages or live_tracks is not None: + self.radar_status = self.radar_monitor.update(time.monotonic(), can_messages, live_tracks) + + +class Device: + def __init__(self): + self._ignition = False + self._interaction_time: float = -1 + self._override_interactive_timeout: int | None = None + self._interactive_timeout_callbacks: list[Callable] = [] + self._prev_timed_out = False + self._awake: bool = True + + self._offroad_brightness: int = BACKLIGHT_OFFROAD + self._last_brightness: int = 0 + self._brightness_filter = FirstOrderFilter(BACKLIGHT_OFFROAD, 10.00, 1 / gui_app.target_fps) + self._brightness_thread: threading.Thread | None = None + self._brightness_event = threading.Event() + self._brightness_target: int = 0 + + @property + def awake(self) -> bool: + return self._awake + + def set_override_interactive_timeout(self, timeout: int | None) -> None: + # Override the interactive timeout duration temporarily + self._override_interactive_timeout = timeout + self._reset_interactive_timeout() + + @property + def interactive_timeout(self) -> int: + if self._override_interactive_timeout is not None: + return self._override_interactive_timeout + + ignition_timeout = 10 if gui_app.big_ui() else 5 + return ignition_timeout if ui_state.ignition else 30 + + def _reset_interactive_timeout(self) -> None: + self._interaction_time = time.monotonic() + self.interactive_timeout + + def add_interactive_timeout_callback(self, callback: Callable): + self._interactive_timeout_callbacks.append(callback) + + def update(self): + self._start_brightness_thread() # start thread after manager forks ui + + # do initial reset + if self._interaction_time <= 0: + self._reset_interactive_timeout() + + self._update_brightness() + self._update_wakefulness() + + def _start_brightness_thread(self): + if self._brightness_thread is None or not self._brightness_thread.is_alive(): + self._brightness_thread = threading.Thread(target=self._brightness_worker, daemon=True) + self._brightness_thread.start() + + def _brightness_worker(self): + drop_realtime() + while True: + self._brightness_event.wait() + self._brightness_event.clear() + HARDWARE.set_screen_brightness(self._brightness_target) + + def set_offroad_brightness(self, brightness: int | None): + if brightness is None: + brightness = BACKLIGHT_OFFROAD + self._offroad_brightness = min(max(brightness, 0), 100) + + def _update_brightness(self): + clipped_brightness = self._offroad_brightness + + if ui_state.started and ui_state.light_sensor >= 0: + clipped_brightness = ui_state.light_sensor + + # CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm + if clipped_brightness <= 8: + clipped_brightness = clipped_brightness / 903.3 + else: + clipped_brightness = ((clipped_brightness + 16.0) / 116.0) ** 3.0 + + clipped_brightness = float(np.interp(clipped_brightness, [0, 1], [30, 100])) + + brightness = round(self._brightness_filter.update(clipped_brightness)) + if not self._awake: + brightness = 0 + + if brightness != self._last_brightness: + self._brightness_target = brightness + self._brightness_event.set() + self._last_brightness = brightness + + def _update_wakefulness(self): + # Handle interactive timeout + ignition_just_turned_off = not ui_state.ignition and self._ignition + self._ignition = ui_state.ignition + + if ignition_just_turned_off or any(ev.left_down for ev in gui_app.mouse_events): + self._reset_interactive_timeout() + + interaction_timeout = time.monotonic() > self._interaction_time + if interaction_timeout and not self._prev_timed_out: + for callback in self._interactive_timeout_callbacks: + callback() + self._prev_timed_out = interaction_timeout + + self._set_awake(ui_state.ignition or not interaction_timeout or PC) + + def _set_awake(self, on: bool): + if on != self._awake: + self._awake = on + cloudlog.debug(f"setting display power {int(on)}") + HARDWARE.set_display_power(on) + gui_app.set_should_render(on) + + +# Global instance +ui_state = UIState() +device = Device() diff --git a/selfdrive/ui/update_translations.py b/selfdrive/ui/update_translations.py deleted file mode 100755 index f13c65fdaed867..00000000000000 --- a/selfdrive/ui/update_translations.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import json -import os - -from openpilot.common.basedir import BASEDIR - -UI_DIR = os.path.join(BASEDIR, "selfdrive", "ui") -TRANSLATIONS_DIR = os.path.join(UI_DIR, "translations") -LANGUAGES_FILE = os.path.join(TRANSLATIONS_DIR, "languages.json") -TRANSLATIONS_INCLUDE_FILE = os.path.join(TRANSLATIONS_DIR, "alerts_generated.h") -PLURAL_ONLY = ["main_en"] # base language, only create entries for strings with plural forms - - -def generate_translations_include(): - # offroad alerts - # TODO translate events from openpilot.selfdrive/controls/lib/events.py - content = "// THIS IS AN AUTOGENERATED FILE, PLEASE EDIT alerts_offroad.json\n" - with open(os.path.join(BASEDIR, "selfdrive/controls/lib/alerts_offroad.json")) as f: - for alert in json.load(f).values(): - content += f'QT_TRANSLATE_NOOP("OffroadAlert", R"({alert["text"]})");\n' - - with open(TRANSLATIONS_INCLUDE_FILE, "w") as f: - f.write(content) - - -def update_translations(vanish: bool = False, translation_files: None | list[str] = None, translations_dir: str = TRANSLATIONS_DIR): - if translation_files is None: - with open(LANGUAGES_FILE) as f: - translation_files = json.load(f).values() - - for file in translation_files: - tr_file = os.path.join(translations_dir, f"{file}.ts") - args = f"lupdate -locations none -recursive {UI_DIR} -ts {tr_file} -I {BASEDIR}" - if vanish: - args += " -no-obsolete" - if file in PLURAL_ONLY: - args += " -pluralonly" - ret = os.system(args) - assert ret == 0 - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Update translation files for UI", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("--vanish", action="store_true", help="Remove translations with source text no longer found") - args = parser.parse_args() - - generate_translations_include() - update_translations(args.vanish) diff --git a/selfdrive/ui/watch3.cc b/selfdrive/ui/watch3.cc deleted file mode 100644 index c14e03aa6ea70f..00000000000000 --- a/selfdrive/ui/watch3.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include - -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/cameraview.h" - -int main(int argc, char *argv[]) { - initApp(argc, argv); - - QApplication a(argc, argv); - QWidget w; - setMainWindow(&w); - - QVBoxLayout *layout = new QVBoxLayout(&w); - layout->setMargin(0); - layout->setSpacing(0); - - { - QHBoxLayout *hlayout = new QHBoxLayout(); - layout->addLayout(hlayout); - hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_ROAD, false)); - } - - { - QHBoxLayout *hlayout = new QHBoxLayout(); - layout->addLayout(hlayout); - hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_DRIVER, false)); - hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_WIDE_ROAD, false)); - } - - return a.exec(); -} diff --git a/selfdrive/ui/watch3.py b/selfdrive/ui/watch3.py new file mode 100755 index 00000000000000..bb64cdc4d543fa --- /dev/null +++ b/selfdrive/ui/watch3.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import pyray as rl + +from msgq.visionipc import VisionStreamType +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.onroad.cameraview import CameraView + + +if __name__ == "__main__": + gui_app.init_window("watch3") + road = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) + driver = CameraView("camerad", VisionStreamType.VISION_STREAM_DRIVER) + wide = CameraView("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD) + for _ in gui_app.render(): + road.render(rl.Rectangle(gui_app.width // 4, 0, gui_app.width // 2, gui_app.height // 2)) + driver.render(rl.Rectangle(0, gui_app.height // 2, gui_app.width // 2, gui_app.height // 2)) + wide.render(rl.Rectangle(gui_app.width // 2, gui_app.height // 2, gui_app.width // 2, gui_app.height // 2)) diff --git a/selfdrive/ui/widgets/__init__.py b/selfdrive/ui/widgets/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/selfdrive/ui/widgets/exp_mode_button.py b/selfdrive/ui/widgets/exp_mode_button.py new file mode 100644 index 00000000000000..0b5bff7da46298 --- /dev/null +++ b/selfdrive/ui/widgets/exp_mode_button.py @@ -0,0 +1,65 @@ +import pyray as rl +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget + + +class ExperimentalModeButton(Widget): + def __init__(self): + super().__init__() + + self.img_width = 80 + self.horizontal_padding = 25 + self.button_height = 125 + + self.params = Params() + self.experimental_mode = self.params.get_bool("ExperimentalMode") + + self.chill_pixmap = gui_app.texture("icons/couch.png", self.img_width, self.img_width) + self.experimental_pixmap = gui_app.texture("icons/experimental_grey.png", self.img_width, self.img_width) + + def show_event(self): + super().show_event() + self.experimental_mode = self.params.get_bool("ExperimentalMode") + + def _get_gradient_colors(self): + alpha = 0xCC if self.is_pressed else 0xFF + + if self.experimental_mode: + return rl.Color(255, 155, 63, alpha), rl.Color(219, 56, 34, alpha) + else: + return rl.Color(20, 255, 171, alpha), rl.Color(35, 149, 255, alpha) + + def _draw_gradient_background(self, rect): + start_color, end_color = self._get_gradient_colors() + rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), int(rect.width), int(rect.height), + start_color, end_color) + + def _render(self, rect): + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + self._draw_gradient_background(rect) + rl.draw_rectangle_rounded_lines_ex(self._rect, 0.19, 10, 5, rl.BLACK) + rl.end_scissor_mode() + + # Draw vertical separator line + line_x = rect.x + rect.width - self.img_width - (2 * self.horizontal_padding) + separator_color = rl.Color(0, 0, 0, 77) # 0x4d = 77 + rl.draw_line_ex(rl.Vector2(line_x, rect.y), rl.Vector2(line_x, rect.y + rect.height), 3, separator_color) + + # Draw text label (left aligned) + text = tr("EXPERIMENTAL MODE ON") if self.experimental_mode else tr("CHILL MODE ON") + text_x = rect.x + self.horizontal_padding + text_y = rect.y + rect.height / 2 - 45 * FONT_SCALE // 2 # Center vertically + + rl.draw_text_ex(gui_app.font(FontWeight.NORMAL), text, rl.Vector2(int(text_x), int(text_y)), 45, 0, rl.BLACK) + + # Draw icon (right aligned) + icon_x = rect.x + rect.width - self.horizontal_padding - self.img_width + icon_y = rect.y + (rect.height - self.img_width) / 2 + icon_rect = rl.Rectangle(icon_x, icon_y, self.img_width, self.img_width) + + # Draw current mode icon + current_icon = self.experimental_pixmap if self.experimental_mode else self.chill_pixmap + source_rect = rl.Rectangle(0, 0, current_icon.width, current_icon.height) + rl.draw_texture_pro(current_icon, source_rect, icon_rect, rl.Vector2(0, 0), 0, rl.WHITE) diff --git a/selfdrive/ui/widgets/offroad_alerts.py b/selfdrive/ui/widgets/offroad_alerts.py new file mode 100644 index 00000000000000..110ca714a9d82e --- /dev/null +++ b/selfdrive/ui/widgets/offroad_alerts.py @@ -0,0 +1,345 @@ +import pyray as rl +from enum import IntEnum +from abc import ABC, abstractmethod +from collections.abc import Callable +from dataclasses import dataclass +from openpilot.common.params import Params +from openpilot.system.hardware import HARDWARE +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.html_render import HtmlRenderer +from openpilot.selfdrive.selfdrived.alertmanager import OFFROAD_ALERTS + + +class AlertColors: + HIGH_SEVERITY = rl.Color(226, 44, 44, 255) + LOW_SEVERITY = rl.Color(41, 41, 41, 255) + BACKGROUND = rl.Color(57, 57, 57, 255) + BUTTON = rl.WHITE + BUTTON_PRESSED = rl.Color(200, 200, 200, 255) + BUTTON_TEXT = rl.BLACK + SNOOZE_BG = rl.Color(79, 79, 79, 255) + SNOOZE_BG_PRESSED = rl.Color(100, 100, 100, 255) + TEXT = rl.WHITE + + +class AlertConstants: + MIN_BUTTON_WIDTH = 400 + BUTTON_HEIGHT = 125 + MARGIN = 50 + SPACING = 30 + FONT_SIZE = 48 + BORDER_RADIUS = 30 * 2 # matches Qt's 30px + ALERT_HEIGHT = 120 + ALERT_SPACING = 10 + ALERT_INSET = 60 + + +@dataclass +class AlertData: + key: str + text: str + severity: int + visible: bool = False + + +class ButtonStyle(IntEnum): + LIGHT = 0 + DARK = 1 + + +class ActionButton(Widget): + def __init__(self, text: str | Callable[[], str], style: ButtonStyle = ButtonStyle.LIGHT, + min_width: int = AlertConstants.MIN_BUTTON_WIDTH): + super().__init__() + self._text = text + self._style = style + self._min_width = min_width + self._font = gui_app.font(FontWeight.MEDIUM) + + @property + def text(self) -> str: + return self._text if isinstance(self._text, str) else self._text() + + def _render(self, _): + text_size = measure_text_cached(gui_app.font(FontWeight.MEDIUM), self.text, AlertConstants.FONT_SIZE) + self._rect.width = max(text_size.x + 60 * 2, self._min_width) + self._rect.height = AlertConstants.BUTTON_HEIGHT + + roundness = AlertConstants.BORDER_RADIUS / self._rect.height + bg_color = AlertColors.BUTTON if self._style == ButtonStyle.LIGHT else AlertColors.SNOOZE_BG + if self.is_pressed: + bg_color = AlertColors.BUTTON_PRESSED if self._style == ButtonStyle.LIGHT else AlertColors.SNOOZE_BG_PRESSED + + rl.draw_rectangle_rounded(self._rect, roundness, 10, bg_color) + + # center text + color = rl.WHITE if self._style == ButtonStyle.DARK else rl.BLACK + text_x = int(self._rect.x + (self._rect.width - text_size.x) // 2) + text_y = int(self._rect.y + (self._rect.height - text_size.y) // 2) + rl.draw_text_ex(self._font, self.text, rl.Vector2(text_x, text_y), AlertConstants.FONT_SIZE, 0, color) + + +class AbstractAlert(Widget, ABC): + def __init__(self, has_reboot_btn: bool = False): + super().__init__() + self.params = Params() + self.has_reboot_btn = has_reboot_btn + self.dismiss_callback: Callable | None = None + + def snooze_callback(): + self.params.put_bool("SnoozeUpdate", True) + if self.dismiss_callback: + self.dismiss_callback() + + def excessive_actuation_callback(): + self.params.remove("Offroad_ExcessiveActuation") + if self.dismiss_callback: + self.dismiss_callback() + + self.dismiss_btn = ActionButton(lambda: tr("Close")) + + self.snooze_btn = ActionButton(lambda: tr("Snooze Update"), style=ButtonStyle.DARK) + self.snooze_btn.set_click_callback(snooze_callback) + + self.excessive_actuation_btn = ActionButton(lambda: tr("Acknowledge Excessive Actuation"), style=ButtonStyle.DARK, min_width=800) + self.excessive_actuation_btn.set_click_callback(excessive_actuation_callback) + + self.reboot_btn = ActionButton(lambda: tr("Reboot and Update"), min_width=600) + self.reboot_btn.set_click_callback(lambda: HARDWARE.reboot()) + + # TODO: just use a Scroller? + self.content_rect = rl.Rectangle(0, 0, 0, 0) + self.scroll_panel_rect = rl.Rectangle(0, 0, 0, 0) + self.scroll_panel = GuiScrollPanel() + + def show_event(self): + super().show_event() + self.scroll_panel.set_offset(0) + + def set_dismiss_callback(self, callback: Callable): + self.dismiss_callback = callback + self.dismiss_btn.set_click_callback(self.dismiss_callback) + + @abstractmethod + def refresh(self) -> bool: + pass + + @abstractmethod + def get_content_height(self) -> float: + pass + + def _render(self, rect: rl.Rectangle): + rl.draw_rectangle_rounded(rect, AlertConstants.BORDER_RADIUS / rect.height, 10, AlertColors.BACKGROUND) + + footer_height = AlertConstants.BUTTON_HEIGHT + AlertConstants.SPACING + content_height = rect.height - 2 * AlertConstants.MARGIN - footer_height + + self.content_rect = rl.Rectangle( + rect.x + AlertConstants.MARGIN, + rect.y + AlertConstants.MARGIN, + rect.width - 2 * AlertConstants.MARGIN, + content_height, + ) + self.scroll_panel_rect = rl.Rectangle( + self.content_rect.x, self.content_rect.y, self.content_rect.width, self.content_rect.height + ) + + self._render_scrollable_content() + self._render_footer(rect) + + def _render_scrollable_content(self): + content_total_height = self.get_content_height() + content_bounds = rl.Rectangle(0, 0, self.scroll_panel_rect.width, content_total_height) + scroll_offset = self.scroll_panel.update(self.scroll_panel_rect, content_bounds) + + rl.begin_scissor_mode( + int(self.scroll_panel_rect.x), + int(self.scroll_panel_rect.y), + int(self.scroll_panel_rect.width), + int(self.scroll_panel_rect.height), + ) + + content_rect_with_scroll = rl.Rectangle( + self.scroll_panel_rect.x, + self.scroll_panel_rect.y + scroll_offset, + self.scroll_panel_rect.width, + content_total_height, + ) + + self._render_content(content_rect_with_scroll) + rl.end_scissor_mode() + + @abstractmethod + def _render_content(self, content_rect: rl.Rectangle): + pass + + def _render_footer(self, rect: rl.Rectangle): + footer_y = rect.y + rect.height - AlertConstants.MARGIN - AlertConstants.BUTTON_HEIGHT + + dismiss_x = rect.x + AlertConstants.MARGIN + self.dismiss_btn.set_position(dismiss_x, footer_y) + self.dismiss_btn.render() + + if self.has_reboot_btn: + reboot_x = rect.x + rect.width - AlertConstants.MARGIN - self.reboot_btn.rect.width + self.reboot_btn.set_position(reboot_x, footer_y) + self.reboot_btn.render() + + elif self.excessive_actuation_btn.is_visible: + actuation_x = rect.x + rect.width - AlertConstants.MARGIN - self.excessive_actuation_btn.rect.width + self.excessive_actuation_btn.set_position(actuation_x, footer_y) + self.excessive_actuation_btn.render() + + elif self.snooze_btn.is_visible: + snooze_x = rect.x + rect.width - AlertConstants.MARGIN - self.snooze_btn.rect.width + self.snooze_btn.set_position(snooze_x, footer_y) + self.snooze_btn.render() + + +class OffroadAlert(AbstractAlert): + def __init__(self): + super().__init__(has_reboot_btn=False) + self.sorted_alerts: list[AlertData] = [] + + def refresh(self): + if not self.sorted_alerts: + self._build_alerts() + + active_count = 0 + connectivity_needed = False + excessive_actuation = False + + for alert_data in self.sorted_alerts: + text = "" + alert_json = self.params.get(alert_data.key) + + if alert_json: + text = alert_json.get("text", "").replace("%1", alert_json.get("extra", "")) + + alert_data.text = text + alert_data.visible = bool(text) + + if alert_data.visible: + active_count += 1 + + if alert_data.key == "Offroad_ConnectivityNeeded" and alert_data.visible: + connectivity_needed = True + + if alert_data.key == "Offroad_ExcessiveActuation" and alert_data.visible: + excessive_actuation = True + + self.excessive_actuation_btn.set_visible(excessive_actuation) + self.snooze_btn.set_visible(connectivity_needed and not excessive_actuation) + return active_count + + def get_content_height(self) -> float: + if not self.sorted_alerts: + return 0 + + total_height = 20 + font = gui_app.font(FontWeight.NORMAL) + + for alert_data in self.sorted_alerts: + if not alert_data.visible: + continue + + text_width = int(self.content_rect.width - (AlertConstants.ALERT_INSET * 2)) + wrapped_lines = wrap_text(font, alert_data.text, AlertConstants.FONT_SIZE, text_width) + line_count = len(wrapped_lines) + text_height = line_count * (AlertConstants.FONT_SIZE * FONT_SCALE) + alert_item_height = max(text_height + (AlertConstants.ALERT_INSET * 2), AlertConstants.ALERT_HEIGHT) + total_height += round(alert_item_height + AlertConstants.ALERT_SPACING) + + if total_height > 20: + total_height = total_height - AlertConstants.ALERT_SPACING + 20 + + return total_height + + def _build_alerts(self): + self.sorted_alerts = [] + for key, config in sorted(OFFROAD_ALERTS.items(), key=lambda x: x[1].get("severity", 0), reverse=True): + severity = config.get("severity", 0) + alert_data = AlertData(key=key, text="", severity=severity) + self.sorted_alerts.append(alert_data) + + def _render_content(self, content_rect: rl.Rectangle): + y_offset = AlertConstants.ALERT_SPACING + font = gui_app.font(FontWeight.NORMAL) + + for alert_data in self.sorted_alerts: + if not alert_data.visible: + continue + + bg_color = AlertColors.HIGH_SEVERITY if alert_data.severity > 0 else AlertColors.LOW_SEVERITY + text_width = int(content_rect.width - (AlertConstants.ALERT_INSET * 2)) + wrapped_lines = wrap_text(font, alert_data.text, AlertConstants.FONT_SIZE, text_width) + line_count = len(wrapped_lines) + text_height = line_count * (AlertConstants.FONT_SIZE * FONT_SCALE) + alert_item_height = max(text_height + (AlertConstants.ALERT_INSET * 2), AlertConstants.ALERT_HEIGHT) + + alert_rect = rl.Rectangle( + content_rect.x + 10, + content_rect.y + y_offset, + content_rect.width - 30, + alert_item_height, + ) + + roundness = AlertConstants.BORDER_RADIUS / min(alert_rect.height, alert_rect.width) + rl.draw_rectangle_rounded(alert_rect, roundness, 10, bg_color) + + text_x = alert_rect.x + AlertConstants.ALERT_INSET + text_y = alert_rect.y + AlertConstants.ALERT_INSET + + for i, line in enumerate(wrapped_lines): + rl.draw_text_ex( + font, + line, + rl.Vector2(text_x, text_y + i * AlertConstants.FONT_SIZE * FONT_SCALE), + AlertConstants.FONT_SIZE, + 0, + AlertColors.TEXT, + ) + + y_offset += round(alert_item_height + AlertConstants.ALERT_SPACING) + + +class UpdateAlert(AbstractAlert): + def __init__(self): + super().__init__(has_reboot_btn=True) + self.release_notes = "" + self._wrapped_release_notes = "" + self._cached_content_height: float = 0.0 + self._html_renderer = HtmlRenderer(text="") + + def refresh(self) -> bool: + update_available: bool = self.params.get_bool("UpdateAvailable") + no_release_notes = "

" + tr("No release notes available.") + "

" + + if update_available: + self.release_notes = (self.params.get("UpdaterNewReleaseNotes") or b"").decode("utf8").strip() + self._html_renderer.parse_html_content(self.release_notes or no_release_notes) + self._cached_content_height = 0 + else: + self._html_renderer.parse_html_content(no_release_notes) + + return update_available + + def get_content_height(self) -> float: + if not self.release_notes: + return 100 + + if self._cached_content_height == 0: + self._wrapped_release_notes = self.release_notes + size = measure_text_cached(gui_app.font(FontWeight.NORMAL), self._wrapped_release_notes, AlertConstants.FONT_SIZE) + self._cached_content_height = max(size.y + 60, 100) + + return self._cached_content_height + + def _render_content(self, content_rect: rl.Rectangle): + notes_rect = rl.Rectangle(content_rect.x + 30, content_rect.y + 30, content_rect.width - 60, content_rect.height - 60) + self._html_renderer.render(notes_rect) diff --git a/selfdrive/ui/widgets/pairing_dialog.py b/selfdrive/ui/widgets/pairing_dialog.py new file mode 100644 index 00000000000000..1ff550e4b6d524 --- /dev/null +++ b/selfdrive/ui/widgets/pairing_dialog.py @@ -0,0 +1,170 @@ +import pyray as rl +import qrcode +import numpy as np +import time + +from openpilot.common.api import Api +from openpilot.common.swaglog import cloudlog +from openpilot.common.params import Params +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets.button import IconButton +from openpilot.selfdrive.ui.ui_state import ui_state + + +class PairingDialog(Widget): + """Dialog for device pairing with QR code.""" + + QR_REFRESH_INTERVAL = 300 # 5 minutes in seconds + + def __init__(self): + super().__init__() + self.params = Params() + self.qr_texture: rl.Texture | None = None + self.last_qr_generation = float('-inf') + self._close_btn = IconButton(gui_app.texture("icons/close.png", 80, 80)) + self._close_btn.set_click_callback(gui_app.pop_widget) + + def _get_pairing_url(self) -> str: + try: + dongle_id = self.params.get("DongleId") or "" + token = Api(dongle_id).get_token({'pair': True}) + except Exception: + cloudlog.exception("Failed to get pairing token") + token = "" + return f"https://connect.comma.ai/?pair={token}" + + def _generate_qr_code(self) -> None: + try: + qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4) + qr.add_data(self._get_pairing_url()) + qr.make(fit=True) + + pil_img = qr.make_image(fill_color="black", back_color="white").convert('RGBA') + img_array = np.array(pil_img, dtype=np.uint8) + + if self.qr_texture and self.qr_texture.id != 0: + rl.unload_texture(self.qr_texture) + + rl_image = rl.Image() + rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) + rl_image.width = pil_img.width + rl_image.height = pil_img.height + rl_image.mipmaps = 1 + rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 + + self.qr_texture = rl.load_texture_from_image(rl_image) + except Exception: + cloudlog.exception("QR code generation failed") + self.qr_texture = None + + def _check_qr_refresh(self) -> None: + current_time = time.monotonic() + if current_time - self.last_qr_generation >= self.QR_REFRESH_INTERVAL: + self._generate_qr_code() + self.last_qr_generation = current_time + + def _update_state(self): + if ui_state.prime_state.is_paired(): + gui_app.pop_widget() + + def _render(self, rect: rl.Rectangle) -> int: + rl.clear_background(rl.Color(224, 224, 224, 255)) + + self._check_qr_refresh() + + margin = 70 + content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - 2 * margin, rect.height - 2 * margin) + y = content_rect.y + + # Close button + close_size = 80 + pad = 20 + close_rect = rl.Rectangle(content_rect.x - pad, y - pad, close_size + pad * 2, close_size + pad * 2) + self._close_btn.render(close_rect) + + y += close_size + 40 + + # Title + title = tr("Pair your device to your comma account") + title_font = gui_app.font(FontWeight.NORMAL) + left_width = int(content_rect.width * 0.5 - 15) + + title_wrapped = wrap_text(title_font, title, 75, left_width) + rl.draw_text_ex(title_font, "\n".join(title_wrapped), rl.Vector2(content_rect.x, y), 75, 0.0, rl.BLACK) + y += len(title_wrapped) * 75 + 60 + + # Two columns: instructions and QR code + remaining_height = content_rect.height - (y - content_rect.y) + right_width = content_rect.width // 2 - 20 + + # Instructions + self._render_instructions(rl.Rectangle(content_rect.x, y, left_width, remaining_height)) + + # QR code + qr_size = min(right_width, content_rect.height) - 40 + qr_x = content_rect.x + left_width + 40 + (right_width - qr_size) // 2 + qr_y = content_rect.y + self._render_qr_code(rl.Rectangle(qr_x, qr_y, qr_size, qr_size)) + + return -1 + + def _render_instructions(self, rect: rl.Rectangle) -> None: + instructions = [ + tr("Go to https://connect.comma.ai on your phone"), + tr("Click \"add new device\" and scan the QR code on the right"), + tr("Bookmark connect.comma.ai to your home screen to use it like an app"), + ] + + font = gui_app.font(FontWeight.BOLD) + y = rect.y + + for i, text in enumerate(instructions): + circle_radius = 25 + circle_x = rect.x + circle_radius + 15 + text_x = rect.x + circle_radius * 2 + 40 + text_width = rect.width - (circle_radius * 2 + 40) + + wrapped = wrap_text(font, text, 47, int(text_width)) + text_height = len(wrapped) * 47 + circle_y = y + text_height // 2 + + # Circle and number + rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255)) + number = str(i + 1) + number_size = measure_text_cached(font, number, 30) + rl.draw_text_ex(font, number, (int(circle_x - number_size.x // 2), int(circle_y - number_size.y // 2)), 30, 0, rl.WHITE) + + # Text + rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK) + y += text_height + 50 + + def _render_qr_code(self, rect: rl.Rectangle) -> None: + if not self.qr_texture: + rl.draw_rectangle_rounded(rect, 0.1, 20, rl.Color(240, 240, 240, 255)) + error_font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex( + error_font, tr("QR Code Error"), rl.Vector2(rect.x + 20, rect.y + rect.height // 2 - 15), 30, 0.0, rl.RED + ) + return + + source = rl.Rectangle(0, 0, self.qr_texture.width, self.qr_texture.height) + rl.draw_texture_pro(self.qr_texture, source, rect, rl.Vector2(0, 0), 0, rl.WHITE) + + def __del__(self): + if self.qr_texture and self.qr_texture.id != 0: + rl.unload_texture(self.qr_texture) + + +if __name__ == "__main__": + gui_app.init_window("pairing device") + pairing = PairingDialog() + gui_app.push_widget(pairing) + try: + for _ in gui_app.render(): + pass + finally: + del pairing diff --git a/selfdrive/ui/widgets/prime.py b/selfdrive/ui/widgets/prime.py new file mode 100644 index 00000000000000..e98e4c1e1ccde5 --- /dev/null +++ b/selfdrive/ui/widgets/prime.py @@ -0,0 +1,63 @@ +import pyray as rl + +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import gui_label + + +class PrimeWidget(Widget): + """Widget for displaying comma prime subscription status""" + + PRIME_BG_COLOR = rl.Color(51, 51, 51, 255) + + def _render(self, rect): + if ui_state.prime_state.is_prime(): + self._render_for_prime_user(rect) + else: + self._render_for_non_prime_users(rect) + + def _render_for_non_prime_users(self, rect: rl.Rectangle): + """Renders the advertisement for non-Prime users.""" + + rl.draw_rectangle_rounded(rect, 0.025, 10, self.PRIME_BG_COLOR) + + # Layout + x, y = rect.x + 80, rect.y + 90 + w = rect.width - 160 + + # Title + gui_label(rl.Rectangle(x, y, w, 90), tr("Upgrade Now"), 75, font_weight=FontWeight.BOLD) + + # Description with wrapping + desc_y = y + 140 + font = gui_app.font(FontWeight.NORMAL) + wrapped_text = "\n".join(wrap_text(font, tr("Become a comma prime member at connect.comma.ai"), 56, int(w))) + text_size = measure_text_cached(font, wrapped_text, 56) + rl.draw_text_ex(font, wrapped_text, rl.Vector2(x, desc_y), 56, 0, rl.WHITE) + + # Features section + features_y = desc_y + text_size.y + 50 + gui_label(rl.Rectangle(x, features_y, w, 50), tr("PRIME FEATURES:"), 41, font_weight=FontWeight.BOLD) + + # Feature list + features = [tr("Remote access"), tr("24/7 LTE connectivity"), tr("1 year of drive storage"), tr("Remote snapshots")] + for i, feature in enumerate(features): + item_y = features_y + 80 + i * 65 + gui_label(rl.Rectangle(x, item_y, 100, 60), "✓", 50, color=rl.Color(70, 91, 234, 255)) + gui_label(rl.Rectangle(x + 60, item_y, w - 60, 60), feature, 50) + + def _render_for_prime_user(self, rect: rl.Rectangle): + """Renders the prime user widget with subscription status.""" + + rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, 230), 0.1, 10, self.PRIME_BG_COLOR) + + x = rect.x + 56 + y = rect.y + 40 + + font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex(font, tr("✓ SUBSCRIBED"), rl.Vector2(x, y), 41, 0, rl.Color(134, 255, 78, 255)) + rl.draw_text_ex(font, tr("comma prime"), rl.Vector2(x, y + 61), 75, 0, rl.WHITE) diff --git a/selfdrive/ui/widgets/setup.py b/selfdrive/ui/widgets/setup.py new file mode 100644 index 00000000000000..c9452fc53502eb --- /dev/null +++ b/selfdrive/ui/widgets/setup.py @@ -0,0 +1,95 @@ +import pyray as rl +from openpilot.common.time_helpers import system_time_valid +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.confirm_dialog import alert_dialog +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import Label + + +class SetupWidget(Widget): + def __init__(self): + super().__init__() + self._open_settings_callback = None + self._pair_device_btn = Button(lambda: tr("Pair device"), self._show_pairing, button_style=ButtonStyle.PRIMARY) + self._open_settings_btn = Button(lambda: tr("Open"), lambda: self._open_settings_callback() if self._open_settings_callback else None, + button_style=ButtonStyle.PRIMARY) + self._firehose_label = Label(lambda: tr("🔥 Firehose Mode 🔥"), font_weight=FontWeight.MEDIUM, font_size=64) + + def set_open_settings_callback(self, callback): + self._open_settings_callback = callback + + def _render(self, rect: rl.Rectangle): + if not ui_state.prime_state.is_paired(): + self._render_registration(rect) + else: + self._render_firehose_prompt(rect) + + def _render_registration(self, rect: rl.Rectangle): + """Render registration prompt.""" + + rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, rect.height), 0.03, 20, rl.Color(51, 51, 51, 255)) + + x = rect.x + 64 + y = rect.y + 48 + w = rect.width - 128 + + # Title + font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex(font, tr("Finish Setup"), rl.Vector2(x, y), 75, 0, rl.WHITE) + y += 113 # 75 + 38 spacing + + # Description + desc = tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.") + light_font = gui_app.font(FontWeight.NORMAL) + wrapped = wrap_text(light_font, desc, 50, int(w)) + for line in wrapped: + rl.draw_text_ex(light_font, line, rl.Vector2(x, y), 50, 0, rl.WHITE) + y += 50 * FONT_SCALE + + button_rect = rl.Rectangle(x, y + 30, w, 200) + self._pair_device_btn.render(button_rect) + + def _render_firehose_prompt(self, rect: rl.Rectangle): + """Render firehose prompt widget.""" + + rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, 500), 0.04, 20, rl.Color(51, 51, 51, 255)) + + # Content margins (56, 40, 56, 40) + x = rect.x + 56 + y = rect.y + 40 + w = rect.width - 112 + spacing = 42 + + # Title with fire emojis + self._firehose_label.render(rl.Rectangle(rect.x, y, rect.width, 64)) + y += 64 + spacing + + # Description + desc_font = gui_app.font(FontWeight.NORMAL) + desc_text = tr("Maximize your training data uploads to improve openpilot's driving models.") + wrapped_desc = wrap_text(desc_font, desc_text, 40, int(w)) + + for line in wrapped_desc: + rl.draw_text_ex(desc_font, line, rl.Vector2(x, y), 40, 0, rl.WHITE) + y += 40 * FONT_SCALE + + y += spacing + + # Open button + button_height = 48 + 64 # font size + padding + button_rect = rl.Rectangle(x, y, w, button_height) + self._open_settings_btn.render(button_rect) + + @staticmethod + def _show_pairing(): + if not system_time_valid(): + dlg = alert_dialog(tr("Please connect to Wi-Fi to complete initial pairing")) + gui_app.push_widget(dlg) + return + + gui_app.push_widget(PairingDialog()) diff --git a/selfdrive/ui/widgets/ssh_key.py b/selfdrive/ui/widgets/ssh_key.py new file mode 100644 index 00000000000000..aa7cb91b1f0107 --- /dev/null +++ b/selfdrive/ui/widgets/ssh_key.py @@ -0,0 +1,158 @@ +import pyray as rl +import requests +import threading +from collections.abc import Callable +from enum import Enum + +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.confirm_dialog import alert_dialog +from openpilot.system.ui.widgets.keyboard import Keyboard +from openpilot.system.ui.widgets.list_view import ( + ItemAction, + ListItem, + BUTTON_HEIGHT, + BUTTON_BORDER_RADIUS, + BUTTON_FONT_SIZE, + BUTTON_WIDTH, +) + +VALUE_FONT_SIZE = 48 + + +class SshKeyFetcher: + HTTP_TIMEOUT = 15 # seconds + + def __init__(self, params: Params): + self._params = params + self._on_response: Callable[[str | None], None] | None = None + self._done: bool = False + self._error: str | None = None + + def fetch(self, username: str, on_response: Callable[[str | None], None]): + self._error = None + self._on_response = on_response + threading.Thread(target=self._fetch_thread, args=(username,), daemon=True).start() + + def update(self): + if not self._done: + return + self._done = False + if self._error is not None: + self.clear() + if self._on_response: + self._on_response(self._error) + + def clear(self): + self._params.remove("GithubUsername") + self._params.remove("GithubSshKeys") + + def _fetch_thread(self, username: str): + try: + response = requests.get(f"https://github.com/{username}.keys", timeout=self.HTTP_TIMEOUT) + response.raise_for_status() + keys = response.text.strip() + if not keys: + raise requests.exceptions.HTTPError("No SSH keys found") + + self._params.put("GithubUsername", username, block=True) + self._params.put("GithubSshKeys", keys, block=True) + except requests.exceptions.Timeout: + self._error = tr("Request timed out") + except Exception: + self._error = tr("No SSH keys found for user '{}'").format(username) + finally: + self._done = True + + +class SshKeyActionState(Enum): + LOADING = tr_noop("LOADING") + ADD = tr_noop("ADD") + REMOVE = tr_noop("REMOVE") + + +class SshKeyAction(ItemAction): + MAX_WIDTH = 500 + + def __init__(self): + super().__init__(self.MAX_WIDTH, True) + + self._keyboard = Keyboard(min_text_size=1) + self._params = Params() + self._fetcher = SshKeyFetcher(self._params) + self._text_font = gui_app.font(FontWeight.NORMAL) + self._button = Button("", click_callback=self._handle_button_click, button_style=ButtonStyle.LIST_ACTION, + border_radius=BUTTON_BORDER_RADIUS, font_size=BUTTON_FONT_SIZE) + + self._refresh_state() + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self._button.set_touch_valid_callback(touch_callback) + + def _refresh_state(self): + self._username = self._params.get("GithubUsername") + self._state = SshKeyActionState.REMOVE if self._params.get("GithubSshKeys") else SshKeyActionState.ADD + + def _update_state(self): + super()._update_state() + self._fetcher.update() + + def _render(self, rect: rl.Rectangle) -> bool: + # Draw username if exists + if self._username: + text_size = measure_text_cached(self._text_font, self._username, VALUE_FONT_SIZE) + rl.draw_text_ex( + self._text_font, + self._username, + (rect.x + rect.width - BUTTON_WIDTH - text_size.x - 30, rect.y + (rect.height - text_size.y) / 2), + VALUE_FONT_SIZE, + 1.0, + rl.Color(170, 170, 170, 255), + ) + + # Draw button + button_rect = rl.Rectangle(rect.x + rect.width - BUTTON_WIDTH, rect.y + (rect.height - BUTTON_HEIGHT) / 2, BUTTON_WIDTH, BUTTON_HEIGHT) + self._button.set_rect(button_rect) + self._button.set_text(tr(self._state.value)) + self._button.set_enabled(self._state != SshKeyActionState.LOADING) + self._button.render(button_rect) + return False + + def _handle_button_click(self): + if self._state == SshKeyActionState.ADD: + self._keyboard.reset() + self._keyboard.set_title(tr("Enter your GitHub username")) + self._keyboard.set_callback(self._on_username_submit) + gui_app.push_widget(self._keyboard) + elif self._state == SshKeyActionState.REMOVE: + self._fetcher.clear() + self._refresh_state() + + def _on_username_submit(self, result: DialogResult): + if result != DialogResult.CONFIRM: + return + + username = self._keyboard.text.strip() + if not username: + return + + self._state = SshKeyActionState.LOADING + self._fetcher.fetch(username, self._on_fetch_response) + + def _on_fetch_response(self, error: str | None): + if error is None: + self._state = SshKeyActionState.REMOVE + self._username = self._params.get("GithubUsername") + else: + self._state = SshKeyActionState.ADD + self._username = "" + gui_app.push_widget(alert_dialog(error)) + + +def ssh_key_item(title: str | Callable[[], str], description: str | Callable[[], str]) -> ListItem: + return ListItem(title=title, description=description, action_item=SshKeyAction()) diff --git a/system/athena/athenad.py b/system/athena/athenad.py index 52e3a29ac8653f..6bccaae63eb424 100755 --- a/system/athena/athenad.py +++ b/system/athena/athenad.py @@ -14,28 +14,27 @@ import tempfile import threading import time -import zstandard as zstd from dataclasses import asdict, dataclass, replace from datetime import datetime -from functools import partial +from functools import partial, total_ordering from queue import Queue from typing import cast from collections.abc import Callable import requests +from requests.adapters import HTTPAdapter, DEFAULT_POOLBLOCK from jsonrpc import JSONRPCResponseManager, dispatcher from websocket import (ABNF, WebSocket, WebSocketException, WebSocketTimeoutException, create_connection) import cereal.messaging as messaging -from cereal import log +from cereal import car, log from cereal.services import SERVICE_LIST -from openpilot.common.api import Api -from openpilot.common.file_helpers import CallbackReader +from openpilot.common.api import Api, get_key_pair +from openpilot.common.utils import CallbackReader, get_upload_stream from openpilot.common.params import Params from openpilot.common.realtime import set_core_affinity from openpilot.system.hardware import HARDWARE, PC -from openpilot.system.loggerd.uploader import LOG_COMPRESSION_LEVEL from openpilot.system.loggerd.xattr_cache import getxattr, setxattr from openpilot.common.swaglog import cloudlog from openpilot.system.version import get_build_metadata @@ -44,7 +43,8 @@ ATHENA_HOST = os.getenv('ATHENA_HOST', 'wss://athena.comma.ai') HANDLER_THREADS = int(os.getenv('HANDLER_THREADS', "4")) -LOCAL_PORT_WHITELIST = {8022} +LOCAL_PORT_WHITELIST = {22, } # SSH +WEBRTCD_PORT = 5001 LOG_ATTR_NAME = 'user.upload' LOG_ATTR_VALUE_MAX_UNIX_TIME = int.to_bytes(2147483647, 4, sys.byteorder) @@ -54,6 +54,13 @@ MAX_RETRY_COUNT = 30 # Try for at most 5 minutes if upload fails immediately MAX_AGE = 31 * 24 * 3600 # seconds WS_FRAME_SIZE = 4096 +DEVICE_STATE_UPDATE_INTERVAL = 1.0 # in seconds +DEFAULT_UPLOAD_PRIORITY = 99 # higher number = lower priority + +# https://bytesolutions.com/dscp-tos-cos-precedence-conversion-chart, +# https://en.wikipedia.org/wiki/Differentiated_services +UPLOAD_TOS = 0x20 # CS1, low priority background traffic +SSH_TOS = 0x90 # AF42, DSCP of 36/HDD_LINUX_AC_VI with the minimum delay flag NetworkType = log.DeviceState.NetworkType @@ -63,19 +70,32 @@ UploadFilesToUrlResponse = dict[str, int | list[UploadItemDict] | list[str]] +class UploadTOSAdapter(HTTPAdapter): + def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): + pool_kwargs["socket_options"] = [(socket.IPPROTO_IP, socket.IP_TOS, UPLOAD_TOS)] + super().init_poolmanager(connections, maxsize, block, **pool_kwargs) + + +UPLOAD_SESS = requests.Session() +UPLOAD_SESS.mount("http://", UploadTOSAdapter()) +UPLOAD_SESS.mount("https://", UploadTOSAdapter()) + + @dataclass class UploadFile: fn: str url: str headers: dict[str, str] allow_cellular: bool + priority: int = DEFAULT_UPLOAD_PRIORITY @classmethod def from_dict(cls, d: dict) -> UploadFile: - return cls(d.get("fn", ""), d.get("url", ""), d.get("headers", {}), d.get("allow_cellular", False)) + return cls(d.get("fn", ""), d.get("url", ""), d.get("headers", {}), d.get("allow_cellular", False), d.get("priority", DEFAULT_UPLOAD_PRIORITY)) @dataclass +@total_ordering class UploadItem: path: str url: str @@ -86,17 +106,28 @@ class UploadItem: current: bool = False progress: float = 0 allow_cellular: bool = False + priority: int = DEFAULT_UPLOAD_PRIORITY @classmethod def from_dict(cls, d: dict) -> UploadItem: return cls(d["path"], d["url"], d["headers"], d["created_at"], d["id"], d["retry_count"], d["current"], - d["progress"], d["allow_cellular"]) + d["progress"], d["allow_cellular"], d["priority"]) + + def __lt__(self, other): + if not isinstance(other, UploadItem): + return NotImplemented + return self.priority < other.priority + + def __eq__(self, other): + if not isinstance(other, UploadItem): + return NotImplemented + return self.priority == other.priority dispatcher["echo"] = lambda s: s recv_queue: Queue[str] = queue.Queue() send_queue: Queue[str] = queue.Queue() -upload_queue: Queue[UploadItem] = queue.Queue() +upload_queue: Queue[UploadItem] = queue.PriorityQueue() low_priority_send_queue: Queue[str] = queue.Queue() log_recv_queue: Queue[str] = queue.Queue() cancelled_uploads: set[str] = set() @@ -121,7 +152,7 @@ def initialize(upload_queue: Queue[UploadItem]) -> None: try: upload_queue_json = Params().get("AthenadUploadQueue") if upload_queue_json is not None: - for item in json.loads(upload_queue_json): + for item in upload_queue_json: upload_queue.put(UploadItem.from_dict(item)) except Exception: cloudlog.exception("athena.UploadQueueCache.initialize.exception") @@ -131,7 +162,7 @@ def cache(upload_queue: Queue[UploadItem]) -> None: try: queue: list[UploadItem | None] = list(upload_queue.queue) items = [asdict(i) for i in queue if i is not None and (i.id not in cancelled_uploads)] - Params().put("AthenadUploadQueue", json.dumps(items)) + Params().put("AthenadUploadQueue", items, block=True) except Exception: cloudlog.exception("athena.UploadQueueCache.cache.exception") @@ -144,6 +175,9 @@ def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None: threading.Thread(target=ws_recv, args=(ws, end_event), name='ws_recv'), threading.Thread(target=ws_send, args=(ws, end_event), name='ws_send'), threading.Thread(target=upload_handler, args=(end_event,), name='upload_handler'), + threading.Thread(target=upload_handler, args=(end_event,), name='upload_handler2'), + threading.Thread(target=upload_handler, args=(end_event,), name='upload_handler3'), + threading.Thread(target=upload_handler, args=(end_event,), name='upload_handler4'), threading.Thread(target=log_handler, args=(end_event,), name='log_handler'), threading.Thread(target=stat_handler, args=(end_event,), name='stat_handler'), ] + [ @@ -211,10 +245,11 @@ def retry_upload(tid: int, end_event: threading.Event, increase_count: bool = Tr def cb(sm, item, tid, end_event: threading.Event, sz: int, cur: int) -> None: # Abort transfer if connection changed to metered after starting upload # or if athenad is shutting down to re-connect the websocket - sm.update(0) - metered = sm['deviceState'].networkMetered - if metered and (not item.allow_cellular): - raise AbortTransferException + if not item.allow_cellular: + if (time.monotonic() - sm.recv_time['deviceState']) > DEVICE_STATE_UPDATE_INTERVAL: + sm.update(0) + if sm['deviceState'].networkMetered: + raise AbortTransferException if end_event.is_set(): raise AbortTransferException @@ -258,13 +293,13 @@ def upload_handler(end_event: threading.Event) -> None: sz = -1 cloudlog.event("athena.upload_handler.upload_start", fn=fn, sz=sz, network_type=network_type, metered=metered, retry_count=item.retry_count) - response = _do_upload(item, partial(cb, sm, item, tid, end_event)) - if response.status_code not in (200, 201, 401, 403, 412): - cloudlog.event("athena.upload_handler.retry", status_code=response.status_code, fn=fn, sz=sz, network_type=network_type, metered=metered) - retry_upload(tid, end_event) - else: - cloudlog.event("athena.upload_handler.success", fn=fn, sz=sz, network_type=network_type, metered=metered) + with _do_upload(item, partial(cb, sm, item, tid, end_event)) as response: + if response.status_code not in (200, 201, 401, 403, 412): + cloudlog.event("athena.upload_handler.retry", status_code=response.status_code, fn=fn, sz=sz, network_type=network_type, metered=metered) + retry_upload(tid, end_event) + else: + cloudlog.event("athena.upload_handler.success", fn=fn, sz=sz, network_type=network_type, metered=metered) UploadQueueCache.cache(upload_queue) except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.SSLError): @@ -280,7 +315,7 @@ def upload_handler(end_event: threading.Event) -> None: cloudlog.exception("athena.upload_handler.exception") -def _do_upload(upload_item: UploadItem, callback: Callable = None) -> requests.Response: +def _do_upload(upload_item: UploadItem, callback: Callable | None = None) -> requests.Response: path = upload_item.path compress = False @@ -289,17 +324,17 @@ def _do_upload(upload_item: UploadItem, callback: Callable = None) -> requests.R path = strip_zst_extension(path) compress = True - with open(path, "rb") as f: - content = f.read() - if compress: - cloudlog.event("athena.upload_handler.compress", fn=path, fn_orig=upload_item.path) - content = zstd.compress(content, LOG_COMPRESSION_LEVEL) - - with io.BytesIO(content) as data: - return requests.put(upload_item.url, - data=CallbackReader(data, callback, len(content)) if callback else data, - headers={**upload_item.headers, 'Content-Length': str(len(content))}, - timeout=30) + stream = None + try: + stream, content_length = get_upload_stream(path, compress) + response = UPLOAD_SESS.put(upload_item.url, + data=CallbackReader(stream, callback, content_length) if callback else stream, + headers={**upload_item.headers, 'Content-Length': str(content_length)}, + timeout=30) + return response + finally: + if stream: + stream.close() # security: user should be able to request any message from their car @@ -309,13 +344,16 @@ def getMessage(service: str, timeout: int = 1000) -> dict: raise Exception("invalid service") socket = messaging.sub_sock(service, timeout=timeout) - ret = messaging.recv_one(socket) + try: + ret = messaging.recv_one(socket) - if ret is None: - raise TimeoutError + if ret is None: + raise TimeoutError - # this is because capnp._DynamicStructReader doesn't have typing information - return cast(dict, ret.to_dict()) + # this is because capnp._DynamicStructReader doesn't have typing information + return cast(dict, ret.to_dict()) + finally: + del socket @dispatcher.add_method @@ -389,9 +427,10 @@ def uploadFilesToUrls(files_data: list[UploadFileDict]) -> UploadFilesToUrlRespo path=path, url=file.url, headers=file.headers, - created_at=int(time.time() * 1000), + created_at=int(time.time() * 1000), # noqa: TID251 id=None, allow_cellular=file.allow_cellular, + priority=file.priority, ) upload_id = hashlib.sha1(str(item).encode()).hexdigest() item = replace(item, id=upload_id) @@ -432,33 +471,36 @@ def setRouteViewed(route: str) -> dict[str, int | str]: # maintain a list of the last 10 routes viewed in connect params = Params() - r = params.get("AthenadRecentlyViewedRoutes", encoding="utf8") + r = params.get("AthenadRecentlyViewedRoutes") routes = [] if r is None else r.split(",") routes.append(route) # remove duplicates routes = list(dict.fromkeys(routes)) - params.put("AthenadRecentlyViewedRoutes", ",".join(routes[-10:])) + params.put("AthenadRecentlyViewedRoutes", ",".join(routes[-10:]), block=True) return {"success": 1} def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local_port: int) -> dict[str, int]: try: + # migration, can be removed once 0.9.8 is out for a while + if local_port == 8022: + local_port = 22 + if local_port not in LOCAL_PORT_WHITELIST: raise Exception("Requested local port not whitelisted") cloudlog.debug("athena.startLocalProxy.starting") - dongle_id = Params().get("DongleId").decode('utf8') + dongle_id = Params().get("DongleId") identity_token = Api(dongle_id).get_token() ws = create_connection(remote_ws_uri, cookie="jwt=" + identity_token, enable_multithread=True) # Set TOS to keep connection responsive while under load. - # DSCP of 36/HDD_LINUX_AC_VI with the minimum delay flag - ws.sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, 0x90) + ws.sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, SSH_TOS) ssock, csock = socket.socketpair() local_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -482,21 +524,27 @@ def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local @dispatcher.add_method def getPublicKey() -> str | None: - if not os.path.isfile(Paths.persist_root() + '/comma/id_rsa.pub'): - return None - - with open(Paths.persist_root() + '/comma/id_rsa.pub') as f: - return f.read() + _, _, public_key = get_key_pair() + return public_key @dispatcher.add_method def getSshAuthorizedKeys() -> str: - return Params().get("GithubSshKeys", encoding='utf8') or '' + return cast(str, Params().get("GithubSshKeys") or "") @dispatcher.add_method def getGithubUsername() -> str: - return Params().get("GithubUsername", encoding='utf8') or '' + return cast(str, Params().get("GithubUsername") or "") + + +@dispatcher.add_method +def getNotCar() -> bool: + cp_bytes = Params().get("CarParamsPersistent") + if cp_bytes is not None: + with car.CarParams.from_bytes(cp_bytes) as CP: + return CP.notCar + return False @dispatcher.add_method @@ -520,9 +568,38 @@ def getNetworks(): return HARDWARE.get_networks() +@dispatcher.add_method +def startStream(sdp: str) -> dict: + from openpilot.system.webrtc.webrtcd import StreamRequestBody + bridge_services_in = [] + + # get live car params to avoid stale notCar edge case + cp_bytes = Params().get("CarParams") + if cp_bytes is not None: + with car.CarParams.from_bytes(cp_bytes) as CP: + if CP.notCar: + bridge_services_in.append("testJoystick") + + body = StreamRequestBody(sdp, "wideRoad", bridge_services_in, ["carState"]) + try: + resp = requests.post(f"http://localhost:{WEBRTCD_PORT}/stream", + json=asdict(body), timeout=10) + if not resp.ok: + try: + error_body = resp.json() + raise Exception(error_body.get("message", f"webrtcd returned {resp.status_code}")) + except ValueError: + resp.raise_for_status() + return resp.json() + except requests.ConnectTimeout as e: + raise Exception("webrtc took too long to respond. is it on?") from e + except requests.ConnectionError as e: + raise Exception("webrtc is not running. turn on comma body ignition.") from e + + @dispatcher.add_method def takeSnapshot() -> str | dict[str, str] | None: - from openpilot.system.camerad.snapshot.snapshot import jpeg_write, snapshot + from openpilot.system.camerad.snapshot import jpeg_write, snapshot ret = snapshot() if ret is not None: def b64jpeg(x): @@ -540,7 +617,7 @@ def b64jpeg(x): def get_logs_to_send_sorted() -> list[str]: # TODO: scan once then use inotify to detect file creation/deletion - curr_time = int(time.time()) + curr_time = int(time.time()) # noqa: TID251 logs = [] for log_entry in os.listdir(Paths.swaglog_root()): log_path = os.path.join(Paths.swaglog_root(), log_entry) @@ -577,7 +654,7 @@ def log_handler(end_event: threading.Event) -> None: log_entry = log_files.pop() # newest log file cloudlog.debug(f"athena.log_handler.forward_request {log_entry}") try: - curr_time = int(time.time()) + curr_time = int(time.time()) # noqa: TID251 log_path = os.path.join(Paths.swaglog_root(), log_entry) setxattr(log_path, LOG_ATTR_NAME, int.to_bytes(curr_time, 4, sys.byteorder)) with open(log_path) as f: @@ -622,8 +699,9 @@ def log_handler(end_event: threading.Event) -> None: def stat_handler(end_event: threading.Event) -> None: STATS_DIR = Paths.stats_root() + last_scan = 0.0 + while not end_event.is_set(): - last_scan = 0. curr_scan = time.monotonic() try: if curr_scan - last_scan > 10: @@ -707,7 +785,7 @@ def ws_recv(ws: WebSocket, end_event: threading.Event) -> None: recv_queue.put_nowait(data) elif opcode == ABNF.OPCODE_PING: last_ping = int(time.monotonic() * 1e9) - Params().put("LastAthenaPingTime", str(last_ping)) + Params().put("LastAthenaPingTime", last_ping, block=True) except WebSocketTimeoutException: ns_since_last_ping = int(time.monotonic() * 1e9) - last_ping if ns_since_last_ping > RECONNECT_TIMEOUT_S * 1e9: @@ -751,8 +829,11 @@ def ws_manage(ws: WebSocket, end_event: threading.Event) -> None: # While not sending data, onroad, we can expect to time out in 7 + (7 * 2) = 21s # offroad, we can expect to time out in 30 + (10 * 3) = 60s # FIXME: TCP_USER_TIMEOUT is effectively 2x for some reason (32s), so it's mostly unused - sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 16000 if onroad else 0) - sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 7 if onroad else 30) + if sys.platform == 'linux': + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 16000 if onroad else 0) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 7 if onroad else 30) + elif sys.platform == 'darwin': + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, 7 if onroad else 30) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 7 if onroad else 10) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 2 if onroad else 3) @@ -764,14 +845,14 @@ def backoff(retries: int) -> int: return random.randrange(0, min(128, int(2 ** retries))) -def main(exit_event: threading.Event = None): +def main(exit_event: threading.Event | None = None): try: set_core_affinity([0, 1, 2, 3]) except Exception: cloudlog.exception("failed to set core affinity") params = Params() - dongle_id = params.get("DongleId", encoding='utf-8') + dongle_id = params.get("DongleId") UploadQueueCache.initialize(upload_queue) ws_uri = ATHENA_HOST + "/ws/v2/" + dongle_id @@ -797,6 +878,8 @@ def main(exit_event: threading.Event = None): cur_upload_items.clear() handle_long_poll(ws, exit_event) + + ws.close() except (KeyboardInterrupt, SystemExit): break except (ConnectionError, TimeoutError, WebSocketException): diff --git a/system/athena/manage_athenad.py b/system/athena/manage_athenad.py index f5ab817206a64b..ee63606b666c1a 100755 --- a/system/athena/manage_athenad.py +++ b/system/athena/manage_athenad.py @@ -14,7 +14,7 @@ def main(): params = Params() - dongle_id = params.get("DongleId").decode('utf-8') + dongle_id = params.get("DongleId") build_metadata = get_build_metadata() cloudlog.bind_global(dongle_id=dongle_id, diff --git a/system/athena/registration.py b/system/athena/registration.py index 06ecd0b9d44298..ecc102edf9202f 100755 --- a/system/athena/registration.py +++ b/system/athena/registration.py @@ -2,13 +2,14 @@ import time import json import jwt +from typing import cast from pathlib import Path from datetime import datetime, timedelta, UTC -from openpilot.common.api import api_get +from openpilot.common.api import api_get, get_key_pair from openpilot.common.params import Params from openpilot.common.spinner import Spinner -from openpilot.selfdrive.controls.lib.alertmanager import set_offroad_alert +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert from openpilot.system.hardware import HARDWARE, PC from openpilot.system.hardware.hw import Paths from openpilot.common.swaglog import cloudlog @@ -17,7 +18,7 @@ UNREGISTERED_DONGLE_ID = "UnregisteredDevice" def is_registered_device() -> bool: - dongle = Params().get("DongleId", encoding='utf-8') + dongle = Params().get("DongleId") return dongle not in (None, UNREGISTERED_DONGLE_ID) @@ -33,29 +34,23 @@ def register(show_spinner=False) -> str | None: """ params = Params() - IMEI = params.get("IMEI", encoding='utf8') - HardwareSerial = params.get("HardwareSerial", encoding='utf8') - dongle_id: str | None = params.get("DongleId", encoding='utf8') + dongle_id: str | None = params.get("DongleId") if dongle_id is None and Path(Paths.persist_root()+"/comma/dongle_id").is_file(): # not all devices will have this; added early in comma 3X production (2/28/24) with open(Paths.persist_root()+"/comma/dongle_id") as f: dongle_id = f.read().strip() - needs_registration = None in (IMEI, HardwareSerial, dongle_id) - pubkey = Path(Paths.persist_root()+"/comma/id_rsa.pub") - if not pubkey.is_file(): + # Create registration token, in the future, this key will make JWTs directly + jwt_algo, private_key, public_key = get_key_pair() + + if not public_key: dongle_id = UNREGISTERED_DONGLE_ID - cloudlog.warning(f"missing public key: {pubkey}") - elif needs_registration: + cloudlog.warning("missing public key") + elif dongle_id is None: if show_spinner: spinner = Spinner() spinner.update("registering device") - # Create registration token, in the future, this key will make JWTs directly - with open(Paths.persist_root()+"/comma/id_rsa.pub") as f1, open(Paths.persist_root()+"/comma/id_rsa") as f2: - public_key = f1.read() - private_key = f2.read() - # Block until we get the imei serial = HARDWARE.get_serial() start_time = time.monotonic() @@ -71,14 +66,12 @@ def register(show_spinner=False) -> str | None: if time.monotonic() - start_time > 60 and show_spinner: spinner.update(f"registering device - serial: {serial}, IMEI: ({imei1}, {imei2})") - params.put("IMEI", imei1) - params.put("HardwareSerial", serial) - backoff = 0 start_time = time.monotonic() while True: try: - register_token = jwt.encode({'register': True, 'exp': datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1)}, private_key, algorithm='RS256') + register_token = jwt.encode({'register': True, 'exp': datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1)}, + cast(str, private_key), algorithm=jwt_algo) cloudlog.info("getting pilotauth") resp = api_get("v2/pilotauth/", method='POST', timeout=15, imei=imei1, imei2=imei2, serial=serial, public_key=public_key, register_token=register_token) @@ -102,8 +95,8 @@ def register(show_spinner=False) -> str | None: spinner.close() if dongle_id: - params.put("DongleId", dongle_id) - set_offroad_alert("Offroad_UnofficialHardware", (dongle_id == UNREGISTERED_DONGLE_ID) and not PC) + params.put("DongleId", dongle_id, block=True) + set_offroad_alert("Offroad_UnregisteredHardware", (dongle_id == UNREGISTERED_DONGLE_ID) and not PC) return dongle_id diff --git a/system/athena/tests/test_athenad.py b/system/athena/tests/test_athenad.py index a4dcbef67a7bd5..b0c20a26a92e66 100644 --- a/system/athena/tests/test_athenad.py +++ b/system/athena/tests/test_athenad.py @@ -19,7 +19,7 @@ from openpilot.common.params import Params from openpilot.common.timeout import Timeout from openpilot.system.athena import athenad -from openpilot.system.athena.athenad import MAX_RETRY_COUNT, dispatcher +from openpilot.system.athena.athenad import MAX_RETRY_COUNT, UPLOAD_SESS, dispatcher from openpilot.system.athena.tests.helpers import HTTPRequestHandler, MockWebsocket, MockApi, EchoSocket from openpilot.selfdrive.test.helpers import http_server_context from openpilot.system.hardware.hw import Paths @@ -29,7 +29,7 @@ def seed_athena_server(host, port): with Timeout(2, 'HTTP Server seeding failed'): while True: try: - requests.put(f'http://{host}:{port}/qlog.zst', data='', timeout=10) + UPLOAD_SESS.put(f'http://{host}:{port}/qlog.zst', data='', timeout=10) break except requests.exceptions.ConnectionError: time.sleep(0.1) @@ -66,17 +66,17 @@ def setup_class(cls): def setup_method(self): self.default_params = { "DongleId": "0000000000000000", - "GithubSshKeys": b"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC307aE+nuHzTAgaJhzSf5v7ZZQW9gaperjhCmyPyl4PzY7T1mDGenTlVTN7yoVFZ9UfO9oMQqo0n1OwDIiqbIFxqnhrHU0cYfj88rI85m5BEKlNu5RdaVTj1tcbaPpQc5kZEolaI1nDDjzV0lwS7jo5VYDHseiJHlik3HH1SgtdtsuamGR2T80q1SyW+5rHoMOJG73IH2553NnWuikKiuikGHUYBd00K1ilVAK2xSiMWJp55tQfZ0ecr9QjEsJ+J/efL4HqGNXhffxvypCXvbUYAFSddOwXUPo5BTKevpxMtH+2YrkpSjocWA04VnTYFiPG6U4ItKmbLOTFZtPzoez private", # noqa: E501 - "GithubUsername": b"commaci", - "AthenadUploadQueue": '[]', + "GithubSshKeys": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC307aE+nuHzTAgaJhzSf5v7ZZQW9gaperjhCmyPyl4PzY7T1mDGenTlVTN7yoVFZ9UfO9oMQqo0n1OwDIiqbIFxqnhrHU0cYfj88rI85m5BEKlNu5RdaVTj1tcbaPpQc5kZEolaI1nDDjzV0lwS7jo5VYDHseiJHlik3HH1SgtdtsuamGR2T80q1SyW+5rHoMOJG73IH2553NnWuikKiuikGHUYBd00K1ilVAK2xSiMWJp55tQfZ0ecr9QjEsJ+J/efL4HqGNXhffxvypCXvbUYAFSddOwXUPo5BTKevpxMtH+2YrkpSjocWA04VnTYFiPG6U4ItKmbLOTFZtPzoez private", # noqa: E501 + "GithubUsername": "commaci", + "AthenadUploadQueue": [], } self.params = Params() for k, v in self.default_params.items(): - self.params.put(k, v) - self.params.put_bool("GsmMetered", True) + self.params.put(k, v, block=True) + self.params.put_bool("GsmMetered", True, block=True) - athenad.upload_queue = queue.Queue() + athenad.upload_queue = queue.PriorityQueue() athenad.cur_upload_items.clear() athenad.cancelled_uploads.clear() @@ -91,13 +91,13 @@ def setup_method(self): @staticmethod def _wait_for_upload(): - now = time.time() - while time.time() - now < 5: + now = time.monotonic() + while time.monotonic() - now < 5: if athenad.upload_queue.qsize() == 0: break @staticmethod - def _create_file(file: str, parent: str = None, data: bytes = b'') -> str: + def _create_file(file: str, parent: str | None = None, data: bytes = b'') -> str: fn = os.path.join(Paths.log_root() if parent is None else parent, file) os.makedirs(os.path.dirname(fn), exist_ok=True) with open(fn, 'wb') as f: @@ -138,7 +138,7 @@ def test_list_data_directory(self): route = '2021-03-29--13-32-47' segments = [0, 1, 2, 3, 11] - filenames = ['qlog', 'qcamera.ts', 'rlog', 'fcamera.hevc', 'ecamera.hevc', 'dcamera.hevc'] + filenames = ['qlog.zst', 'qcamera.ts', 'rlog.zst', 'fcamera.hevc', 'ecamera.hevc', 'dcamera.hevc'] files = [f'{route}--{s}/{f}' for s in segments for f in filenames] for file in files: self._create_file(file) @@ -190,11 +190,11 @@ def test_do_upload(self, host, compress): fn = self._create_file('qlog', data=os.urandom(10000 * 1024)) upload_fn = fn + ('.zst' if compress else '') - item = athenad.UploadItem(path=upload_fn, url="http://localhost:1238", headers={}, created_at=int(time.time()*1000), id='') + item = athenad.UploadItem(path=upload_fn, url="http://localhost:1238", headers={}, created_at=int(time.time()*1000), id='') # noqa: TID251 with pytest.raises(requests.exceptions.ConnectionError): athenad._do_upload(item) - item = athenad.UploadItem(path=upload_fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='') + item = athenad.UploadItem(path=upload_fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='') # noqa: TID251 resp = athenad._do_upload(item) assert resp.status_code == 201 @@ -226,7 +226,7 @@ def test_upload_file_to_url_does_not_exist(self, host): @with_upload_handler def test_upload_handler(self, host): fn = self._create_file('qlog.zst') - item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) + item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) self._wait_for_upload() @@ -239,10 +239,10 @@ def test_upload_handler(self, host): @pytest.mark.parametrize("status,retry", [(500,True), (412,False)]) @with_upload_handler def test_upload_handler_retry(self, mocker, host, status, retry): - mock_put = mocker.patch('requests.put') - mock_put.return_value.status_code = status + mock_put = mocker.patch('openpilot.system.athena.athenad.UPLOAD_SESS.put') + mock_put.return_value.__enter__.return_value.status_code = status fn = self._create_file('qlog.zst') - item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) + item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) self._wait_for_upload() @@ -257,7 +257,7 @@ def test_upload_handler_retry(self, mocker, host, status, retry): def test_upload_handler_timeout(self): """When an upload times out or fails to connect it should be placed back in the queue""" fn = self._create_file('qlog.zst') - item = athenad.UploadItem(path=fn, url="http://localhost:44444/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) + item = athenad.UploadItem(path=fn, url="http://localhost:44444/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251 item_no_retry = replace(item, retry_count=MAX_RETRY_COUNT) athenad.upload_queue.put_nowait(item_no_retry) @@ -278,7 +278,7 @@ def test_upload_handler_timeout(self): @with_upload_handler def test_cancel_upload(self): item = athenad.UploadItem(path="qlog.zst", url="http://localhost:44444/qlog.zst", headers={}, - created_at=int(time.time()*1000), id='id', allow_cellular=True) + created_at=int(time.time()*1000), id='id', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) dispatcher["cancelUpload"](item.id) @@ -312,7 +312,7 @@ def test_list_upload_queue_empty(self): @with_upload_handler def test_list_upload_queue_current(self, host: str): fn = self._create_file('qlog.zst') - item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) + item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) self._wait_for_upload() @@ -321,9 +321,29 @@ def test_list_upload_queue_current(self, host: str): assert len(items) == 1 assert items[0]['current'] + def test_list_upload_queue_priority(self): + priorities = (25, 50, 99, 75, 0) + + for i in priorities: + fn = f'qlog_{i}.zst' + fp = self._create_file(fn) + item = athenad.UploadItem( + path=fp, + url=f"http://localhost:44444/{fn}", + headers={}, + created_at=int(time.time()*1000), # noqa: TID251 + id='', + allow_cellular=True, + priority=i + ) + athenad.upload_queue.put_nowait(item) + + for i in sorted(priorities): + assert athenad.upload_queue.get_nowait().priority == i + def test_list_upload_queue(self): item = athenad.UploadItem(path="qlog.zst", url="http://localhost:44444/qlog.zst", headers={}, - created_at=int(time.time()*1000), id='id', allow_cellular=True) + created_at=int(time.time()*1000), id='id', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) items = dispatcher["listUploadQueue"]() @@ -336,8 +356,8 @@ def test_list_upload_queue(self): assert len(items) == 0 def test_upload_queue_persistence(self): - item1 = athenad.UploadItem(path="_", url="_", headers={}, created_at=int(time.time()), id='id1') - item2 = athenad.UploadItem(path="_", url="_", headers={}, created_at=int(time.time()), id='id2') + item1 = athenad.UploadItem(path="_", url="_", headers={}, created_at=int(time.time()), id='id1') # noqa: TID251 + item2 = athenad.UploadItem(path="_", url="_", headers={}, created_at=int(time.time()), id='id2') # noqa: TID251 athenad.upload_queue.put_nowait(item1) athenad.upload_queue.put_nowait(item2) @@ -380,11 +400,11 @@ def test_start_local_proxy(self, mock_create_connection): def test_get_ssh_authorized_keys(self): keys = dispatcher["getSshAuthorizedKeys"]() - assert keys == self.default_params["GithubSshKeys"].decode('utf-8') + assert keys == self.default_params["GithubSshKeys"] def test_get_github_username(self): keys = dispatcher["getGithubUsername"]() - assert keys == self.default_params["GithubUsername"].decode('utf-8') + assert keys == self.default_params["GithubUsername"] def test_get_version(self): resp = dispatcher["getVersion"]() diff --git a/system/athena/tests/test_athenad_ping.py b/system/athena/tests/test_athenad_ping.py index 025df7d61445d8..8ff1e37a5de7c9 100644 --- a/system/athena/tests/test_athenad_ping.py +++ b/system/athena/tests/test_athenad_ping.py @@ -28,7 +28,7 @@ class TestAthenadPing: exit_event: threading.Event def _get_ping_time(self) -> str | None: - return cast(str | None, self.params.get("LastAthenaPingTime", encoding="utf-8")) + return cast(str | None, self.params.get("LastAthenaPingTime")) def _clear_ping_time(self) -> None: self.params.remove("LastAthenaPingTime") @@ -42,7 +42,7 @@ def teardown_class(cls) -> None: def setup_method(self) -> None: self.params = Params() - self.dongle_id = self.params.get("DongleId", encoding="utf-8") + self.dongle_id = self.params.get("DongleId") wifi_radio(True) self._clear_ping_time() diff --git a/system/athena/tests/test_registration.py b/system/athena/tests/test_registration.py index 17ebaa472d4f13..f5d900d4db6e4d 100644 --- a/system/athena/tests/test_registration.py +++ b/system/athena/tests/test_registration.py @@ -32,14 +32,12 @@ def _generate_keys(self): def test_valid_cache(self, mocker): # if all params are written, return the cached dongle id. # should work with a dongle ID on either /persist/ or normal params - self.params.put("IMEI", "imei") - self.params.put("HardwareSerial", "serial") self._generate_keys() dongle = "DONGLE_ID_123" m = mocker.patch("openpilot.system.athena.registration.api_get", autospec=True) for persist, params in [(True, True), (True, False), (False, True)]: - self.params.put("DongleId", dongle if params else "") + self.params.put("DongleId", dongle if params else "", block=True) with open(self.dongle_id, "w") as f: f.write(dongle if persist else "") assert register() == dongle @@ -51,7 +49,7 @@ def test_no_keys(self, mocker): dongle = register() assert m.call_count == 0 assert dongle == UNREGISTERED_DONGLE_ID - assert self.params.get("DongleId", encoding='utf-8') == dongle + assert self.params.get("DongleId") == dongle def test_missing_cache(self, mocker): # keys exist but no dongle id @@ -65,7 +63,7 @@ def test_missing_cache(self, mocker): # call again, shouldn't hit the API this time assert register() == dongle assert m.call_count == 1 - assert self.params.get("DongleId", encoding='utf-8') == dongle + assert self.params.get("DongleId") == dongle def test_unregistered(self, mocker): # keys exist, but unregistered @@ -75,4 +73,4 @@ def test_unregistered(self, mocker): dongle = register() assert m.call_count == 1 assert dongle == UNREGISTERED_DONGLE_ID - assert self.params.get("DongleId", encoding='utf-8') == dongle + assert self.params.get("DongleId") == dongle diff --git a/system/camerad/SConscript b/system/camerad/SConscript index 511664c275c3f9..c28330b32c4316 100644 --- a/system/camerad/SConscript +++ b/system/camerad/SConscript @@ -1,10 +1,11 @@ -Import('env', 'arch', 'messaging', 'common', 'gpucommon', 'visionipc') +Import('env', 'arch', 'messaging', 'common', 'visionipc') -libs = ['m', 'pthread', common, 'jpeg', 'OpenCL', 'yuv', messaging, visionipc, gpucommon, 'atomic'] +libs = [common, messaging, visionipc] -camera_obj = env.Object(['cameras/camera_qcom2.cc', 'cameras/camera_common.cc', 'cameras/camera_util.cc', - 'sensors/ar0231.cc', 'sensors/ox03c10.cc', 'sensors/os04c10.cc']) -env.Program('camerad', ['main.cc', camera_obj], LIBS=libs) +if arch != "Darwin": + camera_obj = env.Object(['cameras/camera_qcom2.cc', 'cameras/camera_common.cc', 'cameras/spectra.cc', + 'cameras/cdm.cc', 'sensors/ox03c10.cc', 'sensors/os04c10.cc']) + env.Program('camerad', ['main.cc', camera_obj], LIBS=libs) if GetOption("extras") and arch == "x86_64": env.Program('test/test_ae_gray', ['test/test_ae_gray.cc', camera_obj], LIBS=libs) diff --git a/system/camerad/cameras/bps_blobs.h b/system/camerad/cameras/bps_blobs.h new file mode 100644 index 00000000000000..ee31698e7f0a89 --- /dev/null +++ b/system/camerad/cameras/bps_blobs.h @@ -0,0 +1,30 @@ +#include +#include + + +/* ********************************************************** + THIS FILE IS AUTO-GENERATED, DO NOT EDIT DIRECTLY! + ********************************************************** */ + + +unsigned char bps_cfg[4][768] = { +{ /* placeholder */ }, +{ /* placeholder */ }, + {0x3, 0x0, 0x0, 0x0, 0x88, 0x7, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0xB, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x88, 0x7, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x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0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, +}; + diff --git a/system/camerad/cameras/camera_common.cc b/system/camerad/cameras/camera_common.cc index 6c745e1cde9404..329192b63ae9c8 100644 --- a/system/camerad/cameras/camera_common.cc +++ b/system/camerad/cameras/camera_common.cc @@ -3,123 +3,48 @@ #include #include -#include "third_party/libyuv/include/libyuv.h" -#include - -#include "common/clutil.h" #include "common/swaglog.h" -#include "third_party/linux/include/msm_media_info.h" - -#include "system/camerad/cameras/camera_qcom2.h" -#ifdef QCOM2 -#include "CL/cl_ext_qcom.h" -#endif - -class ImgProc { -public: - ImgProc(cl_device_id device_id, cl_context context, const CameraBuf *b, const CameraState *s, int buf_width, int uv_offset) { - char args[4096]; - const SensorInfo *ci = s->ci.get(); - snprintf(args, sizeof(args), - "-cl-fast-relaxed-math -cl-denorms-are-zero -Isensors " - "-DFRAME_WIDTH=%d -DFRAME_HEIGHT=%d -DFRAME_STRIDE=%d -DFRAME_OFFSET=%d " - "-DRGB_WIDTH=%d -DRGB_HEIGHT=%d -DYUV_STRIDE=%d -DUV_OFFSET=%d " - "-DSENSOR_ID=%hu -DHDR_OFFSET=%d -DVIGNETTING=%d ", - ci->frame_width, ci->frame_height, ci->hdr_offset > 0 ? ci->frame_stride * 2 : ci->frame_stride, ci->frame_offset, - b->rgb_width, b->rgb_height, buf_width, uv_offset, - static_cast(ci->image_sensor), ci->hdr_offset, s->camera_num == 1); - const char *cl_file = "cameras/process_raw.cl"; - cl_program prg_imgproc = cl_program_from_file(context, device_id, cl_file, args); - krnl_ = CL_CHECK_ERR(clCreateKernel(prg_imgproc, "process_raw", &err)); - CL_CHECK(clReleaseProgram(prg_imgproc)); - - const cl_queue_properties props[] = {0}; //CL_QUEUE_PRIORITY_KHR, CL_QUEUE_PRIORITY_HIGH_KHR, 0}; - queue = CL_CHECK_ERR(clCreateCommandQueueWithProperties(context, device_id, props, &err)); - } - - void runKernel(cl_mem cam_buf_cl, cl_mem buf_cl, int width, int height, int expo_time) { - CL_CHECK(clSetKernelArg(krnl_, 0, sizeof(cl_mem), &cam_buf_cl)); - CL_CHECK(clSetKernelArg(krnl_, 1, sizeof(cl_mem), &buf_cl)); - CL_CHECK(clSetKernelArg(krnl_, 2, sizeof(cl_int), &expo_time)); - - const size_t globalWorkSize[] = {size_t(width / 2), size_t(height / 2)}; - const int imgproc_local_worksize = 16; - const size_t localWorkSize[] = {imgproc_local_worksize, imgproc_local_worksize}; +#include "system/camerad/cameras/spectra.h" - cl_event event; - CL_CHECK(clEnqueueNDRangeKernel(queue, krnl_, 2, NULL, globalWorkSize, localWorkSize, 0, 0, &event)); - clWaitForEvents(1, &event); - CL_CHECK(clReleaseEvent(event)); - } - - ~ImgProc() { - CL_CHECK(clReleaseKernel(krnl_)); - CL_CHECK(clReleaseCommandQueue(queue)); - } - -private: - cl_kernel krnl_; - cl_command_queue queue; -}; -void CameraBuf::init(cl_device_id device_id, cl_context context, CameraState *s, VisionIpcServer * v, int frame_cnt, VisionStreamType type) { +void CameraBuf::init(SpectraCamera *cam, VisionIpcServer * v, int frame_cnt, VisionStreamType type) { vipc_server = v; stream_type = type; frame_buf_count = frame_cnt; - const SensorInfo *ci = s->ci.get(); - // RAW frame - const int frame_size = (ci->frame_height + ci->extra_height) * ci->frame_stride; - camera_bufs = std::make_unique(frame_buf_count); - camera_bufs_metadata = std::make_unique(frame_buf_count); - - for (int i = 0; i < frame_buf_count; i++) { - camera_bufs[i].allocate(frame_size); - camera_bufs[i].init_cl(device_id, context); - } - LOGD("allocated %d CL buffers", frame_buf_count); - - rgb_width = ci->frame_width; - rgb_height = ci->hdr_offset > 0 ? (ci->frame_height - ci->hdr_offset) / 2 : ci->frame_height; + const SensorInfo *sensor = cam->sensor.get(); - int nv12_width = VENUS_Y_STRIDE(COLOR_FMT_NV12, rgb_width); - int nv12_height = VENUS_Y_SCANLINES(COLOR_FMT_NV12, rgb_height); - assert(nv12_width == VENUS_UV_STRIDE(COLOR_FMT_NV12, rgb_width)); - assert(nv12_height/2 == VENUS_UV_SCANLINES(COLOR_FMT_NV12, rgb_height)); - size_t nv12_uv_offset = nv12_width * nv12_height; + // RAW frames from ISP + if (cam->cc.output_type != ISP_IFE_PROCESSED) { + camera_bufs_raw = std::make_unique(frame_buf_count); - // the encoder HW tells us the size it wants after setting it up. - // TODO: VENUS_BUFFER_SIZE should give the size, but it's too small. dependent on encoder settings? - size_t nv12_size = (rgb_width <= 1344 ? 2900 : 2346)*nv12_width; - - vipc_server->create_buffers_with_sizes(stream_type, YUV_BUFFER_COUNT, false, rgb_width, rgb_height, nv12_size, nv12_width, nv12_uv_offset); - LOGD("created %d YUV vipc buffers with size %dx%d", YUV_BUFFER_COUNT, nv12_width, nv12_height); + const int raw_frame_size = (sensor->frame_height + sensor->extra_height) * sensor->frame_stride; + for (int i = 0; i < frame_buf_count; i++) { + camera_bufs_raw[i].allocate(raw_frame_size); + } + LOGD("allocated %d buffers", frame_buf_count); + } - imgproc = new ImgProc(device_id, context, this, s, nv12_width, nv12_uv_offset); + vipc_server->create_buffers_with_sizes(stream_type, VIPC_BUFFER_COUNT, out_img_width, out_img_height, cam->yuv_size, cam->stride, cam->uv_offset); + LOGD("created %d YUV vipc buffers with size %dx%d", VIPC_BUFFER_COUNT, cam->stride, cam->y_height); } CameraBuf::~CameraBuf() { - for (int i = 0; i < frame_buf_count; i++) { - camera_bufs[i].free(); + if (camera_bufs_raw != nullptr) { + for (int i = 0; i < frame_buf_count; i++) { + camera_bufs_raw[i].free(); + } } - if (imgproc) delete imgproc; } -bool CameraBuf::acquire() { - if (!safe_queue.try_pop(cur_buf_idx, 50)) return false; +void CameraBuf::sendFrameToVipc() { + assert(cur_buf_idx >=0 && cur_buf_idx < frame_buf_count); - if (camera_bufs_metadata[cur_buf_idx].frame_id == -1) { - LOGE("no frame data? wtf"); - return false; + if (camera_bufs_raw) { + cur_camera_buf = &camera_bufs_raw[cur_buf_idx]; } - cur_frame_data = camera_bufs_metadata[cur_buf_idx]; - cur_yuv_buf = vipc_server->get_buffer(stream_type); - cur_camera_buf = &camera_bufs[cur_buf_idx]; - - double start_time = millis_since_boot(); - imgproc->runKernel(camera_bufs[cur_buf_idx].buf_cl, cur_yuv_buf->buf_cl, rgb_width, rgb_height, cur_frame_data.integ_lines); - cur_frame_data.processing_time = (millis_since_boot() - start_time) / 1000.0; + cur_yuv_buf = vipc_server->get_buffer(stream_type, cur_buf_idx); VisionIpcBufExtra extra = { cur_frame_data.frame_id, @@ -128,34 +53,10 @@ bool CameraBuf::acquire() { }; cur_yuv_buf->set_frame_id(cur_frame_data.frame_id); vipc_server->send(cur_yuv_buf, &extra); - - return true; -} - -void CameraBuf::queue(size_t buf_idx) { - safe_queue.push(buf_idx); } // common functions -void fill_frame_data(cereal::FrameData::Builder &framed, const FrameMetadata &frame_data, CameraState *c) { - framed.setFrameId(frame_data.frame_id); - framed.setRequestId(frame_data.request_id); - framed.setTimestampEof(frame_data.timestamp_eof); - framed.setTimestampSof(frame_data.timestamp_sof); - framed.setIntegLines(frame_data.integ_lines); - framed.setGain(frame_data.gain); - framed.setHighConversionGain(frame_data.high_conversion_gain); - framed.setMeasuredGreyFraction(frame_data.measured_grey_fraction); - framed.setTargetGreyFraction(frame_data.target_grey_fraction); - framed.setProcessingTime(frame_data.processing_time); - - const float ev = c->cur_ev[frame_data.frame_id % 3]; - const float perc = util::map_val(ev, c->ci->min_ev, c->ci->max_ev, 0.0f, 100.0f); - framed.setExposureValPercent(perc); - framed.setSensor(c->ci->image_sensor); -} - kj::Array get_raw_frame_image(const CameraBuf *b) { const uint8_t *dat = (const uint8_t *)b->cur_camera_buf->addr; @@ -167,96 +68,7 @@ kj::Array get_raw_frame_image(const CameraBuf *b) { return kj::mv(frame_image); } -static kj::Array yuv420_to_jpeg(const CameraBuf *b, int thumbnail_width, int thumbnail_height) { - int downscale = b->cur_yuv_buf->width / thumbnail_width; - assert(downscale * thumbnail_height == b->cur_yuv_buf->height); - int in_stride = b->cur_yuv_buf->stride; - - // make the buffer big enough. jpeg_write_raw_data requires 16-pixels aligned height to be used. - std::unique_ptr buf(new uint8_t[(thumbnail_width * ((thumbnail_height + 15) & ~15) * 3) / 2]); - uint8_t *y_plane = buf.get(); - uint8_t *u_plane = y_plane + thumbnail_width * thumbnail_height; - uint8_t *v_plane = u_plane + (thumbnail_width * thumbnail_height) / 4; - { - // subsampled conversion from nv12 to yuv - for (int hy = 0; hy < thumbnail_height/2; hy++) { - for (int hx = 0; hx < thumbnail_width/2; hx++) { - int ix = hx * downscale + (downscale-1)/2; - int iy = hy * downscale + (downscale-1)/2; - y_plane[(hy*2 + 0)*thumbnail_width + (hx*2 + 0)] = b->cur_yuv_buf->y[(iy*2 + 0) * in_stride + ix*2 + 0]; - y_plane[(hy*2 + 0)*thumbnail_width + (hx*2 + 1)] = b->cur_yuv_buf->y[(iy*2 + 0) * in_stride + ix*2 + 1]; - y_plane[(hy*2 + 1)*thumbnail_width + (hx*2 + 0)] = b->cur_yuv_buf->y[(iy*2 + 1) * in_stride + ix*2 + 0]; - y_plane[(hy*2 + 1)*thumbnail_width + (hx*2 + 1)] = b->cur_yuv_buf->y[(iy*2 + 1) * in_stride + ix*2 + 1]; - u_plane[hy*thumbnail_width/2 + hx] = b->cur_yuv_buf->uv[iy*in_stride + ix*2 + 0]; - v_plane[hy*thumbnail_width/2 + hx] = b->cur_yuv_buf->uv[iy*in_stride + ix*2 + 1]; - } - } - } - - struct jpeg_compress_struct cinfo; - struct jpeg_error_mgr jerr; - cinfo.err = jpeg_std_error(&jerr); - jpeg_create_compress(&cinfo); - - uint8_t *thumbnail_buffer = nullptr; - size_t thumbnail_len = 0; - jpeg_mem_dest(&cinfo, &thumbnail_buffer, &thumbnail_len); - - cinfo.image_width = thumbnail_width; - cinfo.image_height = thumbnail_height; - cinfo.input_components = 3; - - jpeg_set_defaults(&cinfo); - jpeg_set_colorspace(&cinfo, JCS_YCbCr); - // configure sampling factors for yuv420. - cinfo.comp_info[0].h_samp_factor = 2; // Y - cinfo.comp_info[0].v_samp_factor = 2; - cinfo.comp_info[1].h_samp_factor = 1; // U - cinfo.comp_info[1].v_samp_factor = 1; - cinfo.comp_info[2].h_samp_factor = 1; // V - cinfo.comp_info[2].v_samp_factor = 1; - cinfo.raw_data_in = TRUE; - - jpeg_set_quality(&cinfo, 50, TRUE); - jpeg_start_compress(&cinfo, TRUE); - - JSAMPROW y[16], u[8], v[8]; - JSAMPARRAY planes[3]{y, u, v}; - - for (int line = 0; line < cinfo.image_height; line += 16) { - for (int i = 0; i < 16; ++i) { - y[i] = y_plane + (line + i) * cinfo.image_width; - if (i % 2 == 0) { - int offset = (cinfo.image_width / 2) * ((i + line) / 2); - u[i / 2] = u_plane + offset; - v[i / 2] = v_plane + offset; - } - } - jpeg_write_raw_data(&cinfo, planes, 16); - } - - jpeg_finish_compress(&cinfo); - jpeg_destroy_compress(&cinfo); - - kj::Array dat = kj::heapArray(thumbnail_buffer, thumbnail_len); - free(thumbnail_buffer); - return dat; -} - -void publish_thumbnail(PubMaster *pm, const CameraBuf *b) { - auto thumbnail = yuv420_to_jpeg(b, b->rgb_width / 4, b->rgb_height / 4); - if (thumbnail.size() == 0) return; - - MessageBuilder msg; - auto thumbnaild = msg.initEvent().initThumbnail(); - thumbnaild.setFrameId(b->cur_frame_data.frame_id); - thumbnaild.setTimestampEof(b->cur_frame_data.timestamp_eof); - thumbnaild.setThumbnail(thumbnail); - - pm->send("thumbnail", msg); -} - -float set_exposure_target(const CameraBuf *b, Rect ae_xywh, int x_skip, int y_skip) { +float calculate_exposure_value(const CameraBuf *b, Rect ae_xywh, int x_skip, int y_skip) { int lum_med; uint32_t lum_binning[256] = {0}; const uint8_t *pix_ptr = b->cur_yuv_buf->y; @@ -264,7 +76,7 @@ float set_exposure_target(const CameraBuf *b, Rect ae_xywh, int x_skip, int y_sk unsigned int lum_total = 0; for (int y = ae_xywh.y; y < ae_xywh.y + ae_xywh.h; y += y_skip) { for (int x = ae_xywh.x; x < ae_xywh.x + ae_xywh.w; x += x_skip) { - uint8_t lum = pix_ptr[(y * b->rgb_width) + x]; + uint8_t lum = pix_ptr[(y * b->out_img_width) + x]; lum_binning[lum]++; lum_total += 1; } @@ -283,30 +95,6 @@ float set_exposure_target(const CameraBuf *b, Rect ae_xywh, int x_skip, int y_sk return lum_med / 256.0; } -void camerad_thread() { - cl_device_id device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); -#ifdef QCOM2 - const cl_context_properties props[] = {CL_CONTEXT_PRIORITY_HINT_QCOM, CL_PRIORITY_HINT_HIGH_QCOM, 0}; - cl_context context = CL_CHECK_ERR(clCreateContext(props, 1, &device_id, NULL, NULL, &err)); -#else - cl_context context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); -#endif - - { - MultiCameraState cameras; - VisionIpcServer vipc_server("camerad", device_id, context); - - cameras_open(&cameras); - cameras_init(&vipc_server, &cameras, device_id, context); - - vipc_server.start_listener(); - - cameras_run(&cameras); - } - - CL_CHECK(clReleaseContext(context)); -} - int open_v4l_by_name_and_index(const char name[], int index, int flags) { for (int v4l_index = 0; /**/; ++v4l_index) { std::string v4l_name = util::read_file(util::string_format("/sys/class/video4linux/v4l-subdev%d/name", v4l_index)); diff --git a/system/camerad/cameras/camera_common.h b/system/camerad/cameras/camera_common.h index 7c2fbaeec8656e..7f35e06a8353a8 100644 --- a/system/camerad/cameras/camera_common.h +++ b/system/camerad/cameras/camera_common.h @@ -1,80 +1,46 @@ #pragma once -#include #include #include "cereal/messaging/messaging.h" #include "msgq/visionipc/visionipc_server.h" -#include "common/queue.h" #include "common/util.h" -const int YUV_BUFFER_COUNT = 20; -enum CameraType { - RoadCam = 0, - DriverCam, - WideRoadCam -}; - -// for debugging -const bool env_debug_frames = getenv("DEBUG_FRAMES") != NULL; -const bool env_log_raw_frames = getenv("LOG_RAW_FRAMES") != NULL; -const bool env_ctrl_exp_from_params = getenv("CTRL_EXP_FROM_PARAMS") != NULL; +const int VIPC_BUFFER_COUNT = 18; typedef struct FrameMetadata { uint32_t frame_id; uint32_t request_id; - - // Timestamps uint64_t timestamp_sof; uint64_t timestamp_eof; - - // Exposure - unsigned int integ_lines; - bool high_conversion_gain; - float gain; - float measured_grey_fraction; - float target_grey_fraction; - float processing_time; } FrameMetadata; -struct MultiCameraState; -class CameraState; -class ImgProc; +class SpectraCamera; class CameraBuf { private: - VisionIpcServer *vipc_server; - ImgProc *imgproc = nullptr; - VisionStreamType stream_type; - int cur_buf_idx; - SafeQueue safe_queue; int frame_buf_count; public: + VisionIpcServer *vipc_server; + VisionStreamType stream_type; + + int cur_buf_idx; FrameMetadata cur_frame_data; VisionBuf *cur_yuv_buf; VisionBuf *cur_camera_buf; - std::unique_ptr camera_bufs; - std::unique_ptr camera_bufs_metadata; - int rgb_width, rgb_height; + std::unique_ptr camera_bufs_raw; + uint32_t out_img_width, out_img_height; CameraBuf() = default; ~CameraBuf(); - void init(cl_device_id device_id, cl_context context, CameraState *s, VisionIpcServer * v, int frame_cnt, VisionStreamType type); - bool acquire(); - void queue(size_t buf_idx); + void init(SpectraCamera *cam, VisionIpcServer * v, int frame_cnt, VisionStreamType type); + void sendFrameToVipc(); }; -void fill_frame_data(cereal::FrameData::Builder &framed, const FrameMetadata &frame_data, CameraState *c); -kj::Array get_raw_frame_image(const CameraBuf *b); -float set_exposure_target(const CameraBuf *b, Rect ae_xywh, int x_skip, int y_skip); -void publish_thumbnail(PubMaster *pm, const CameraBuf *b); -void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx); -void cameras_open(MultiCameraState *s); -void cameras_run(MultiCameraState *s); -void cameras_close(MultiCameraState *s); void camerad_thread(); - +kj::Array get_raw_frame_image(const CameraBuf *b); +float calculate_exposure_value(const CameraBuf *b, Rect ae_xywh, int x_skip, int y_skip); int open_v4l_by_name_and_index(const char name[], int index = 0, int flags = O_RDWR | O_NONBLOCK); diff --git a/system/camerad/cameras/camera_qcom2.cc b/system/camerad/cameras/camera_qcom2.cc index 0648ddf4dede34..63640920db9b23 100644 --- a/system/camerad/cameras/camera_qcom2.cc +++ b/system/camerad/cameras/camera_qcom2.cc @@ -1,4 +1,5 @@ -#include "system/camerad/cameras/camera_qcom2.h" +#include "system/camerad/cameras/camera_common.h" +#include "system/camerad/cameras/spectra.h" #include #include @@ -11,829 +12,100 @@ #include #include -#include "media/cam_defs.h" -#include "media/cam_isp.h" -#include "media/cam_isp_ife.h" -#include "media/cam_req_mgr.h" -#include "media/cam_sensor_cmn_header.h" -#include "media/cam_sync.h" +#include "common/params.h" #include "common/swaglog.h" -const int MIPI_SETTLE_CNT = 33; // Calculated by camera_freqs.py - -// For debugging: -// echo "4294967295" > /sys/module/cam_debug_util/parameters/debug_mdl ExitHandler do_exit; -CameraState::CameraState(MultiCameraState *multi_camera_state, const CameraConfig &config) - : multi_cam_state(multi_camera_state), - camera_num(config.camera_num), - stream_type(config.stream_type), - focal_len(config.focal_len), - publish_name(config.publish_name), - init_camera_state(config.init_camera_state), - enabled(config.enabled) { -} - -int CameraState::clear_req_queue() { - struct cam_req_mgr_flush_info req_mgr_flush_request = {0}; - req_mgr_flush_request.session_hdl = session_handle; - req_mgr_flush_request.link_hdl = link_handle; - req_mgr_flush_request.flush_type = CAM_REQ_MGR_FLUSH_TYPE_ALL; - int ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_FLUSH_REQ, &req_mgr_flush_request, sizeof(req_mgr_flush_request)); - // LOGD("flushed all req: %d", ret); - return ret; -} - -// ************** high level camera helpers **************** - -void CameraState::sensors_start() { - if (!enabled) return; - LOGD("starting sensor %d", camera_num); - sensors_i2c(ci->start_reg_array.data(), ci->start_reg_array.size(), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, ci->data_word); -} - -void CameraState::sensors_poke(int request_id) { - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet); - auto pkt = mm.alloc(size, &cam_packet_handle); - pkt->num_cmd_buf = 0; - pkt->kmd_cmd_buf_index = -1; - pkt->header.size = size; - pkt->header.op_code = CAM_SENSOR_PACKET_OPCODE_SENSOR_NOP; - pkt->header.request_id = request_id; - - int ret = device_config(sensor_fd, session_handle, sensor_dev_handle, cam_packet_handle); - if (ret != 0) { - LOGE("** sensor %d FAILED poke, disabling", camera_num); - enabled = false; - return; - } -} - -void CameraState::sensors_i2c(const struct i2c_random_wr_payload* dat, int len, int op_code, bool data_word) { - // LOGD("sensors_i2c: %d", len); - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*1; - auto pkt = mm.alloc(size, &cam_packet_handle); - pkt->num_cmd_buf = 1; - pkt->kmd_cmd_buf_index = -1; - pkt->header.size = size; - pkt->header.op_code = op_code; - struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; - - buf_desc[0].size = buf_desc[0].length = sizeof(struct i2c_rdwr_header) + len*sizeof(struct i2c_random_wr_payload); - buf_desc[0].type = CAM_CMD_BUF_I2C; - - auto i2c_random_wr = mm.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); - i2c_random_wr->header.count = len; - i2c_random_wr->header.op_code = 1; - i2c_random_wr->header.cmd_type = CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_WR; - i2c_random_wr->header.data_type = data_word ? CAMERA_SENSOR_I2C_TYPE_WORD : CAMERA_SENSOR_I2C_TYPE_BYTE; - i2c_random_wr->header.addr_type = CAMERA_SENSOR_I2C_TYPE_WORD; - memcpy(i2c_random_wr->random_wr_payload, dat, len*sizeof(struct i2c_random_wr_payload)); - - int ret = device_config(sensor_fd, session_handle, sensor_dev_handle, cam_packet_handle); - if (ret != 0) { - LOGE("** sensor %d FAILED i2c, disabling", camera_num); - enabled = false; - return; - } -} - -static cam_cmd_power *power_set_wait(cam_cmd_power *power, int16_t delay_ms) { - cam_cmd_unconditional_wait *unconditional_wait = (cam_cmd_unconditional_wait *)((char *)power + (sizeof(struct cam_cmd_power) + (power->count - 1) * sizeof(struct cam_power_settings))); - unconditional_wait->cmd_type = CAMERA_SENSOR_CMD_TYPE_WAIT; - unconditional_wait->delay = delay_ms; - unconditional_wait->op_code = CAMERA_SENSOR_WAIT_OP_SW_UCND; - return (struct cam_cmd_power *)(unconditional_wait + 1); -} - -int CameraState::sensors_init() { - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*2; - auto pkt = mm.alloc(size, &cam_packet_handle); - pkt->num_cmd_buf = 2; - pkt->kmd_cmd_buf_index = -1; - pkt->header.op_code = 0x1000000 | CAM_SENSOR_PACKET_OPCODE_SENSOR_PROBE; - pkt->header.size = size; - struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; - - buf_desc[0].size = buf_desc[0].length = sizeof(struct cam_cmd_i2c_info) + sizeof(struct cam_cmd_probe); - buf_desc[0].type = CAM_CMD_BUF_LEGACY; - auto i2c_info = mm.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); - auto probe = (struct cam_cmd_probe *)(i2c_info.get() + 1); - - probe->camera_id = camera_num; - i2c_info->slave_addr = ci->getSlaveAddress(camera_num); - // 0(I2C_STANDARD_MODE) = 100khz, 1(I2C_FAST_MODE) = 400khz - //i2c_info->i2c_freq_mode = I2C_STANDARD_MODE; - i2c_info->i2c_freq_mode = I2C_FAST_MODE; - i2c_info->cmd_type = CAMERA_SENSOR_CMD_TYPE_I2C_INFO; - - probe->data_type = CAMERA_SENSOR_I2C_TYPE_WORD; - probe->addr_type = CAMERA_SENSOR_I2C_TYPE_WORD; - probe->op_code = 3; // don't care? - probe->cmd_type = CAMERA_SENSOR_CMD_TYPE_PROBE; - probe->reg_addr = ci->probe_reg_addr; - probe->expected_data = ci->probe_expected_data; - probe->data_mask = 0; - - //buf_desc[1].size = buf_desc[1].length = 148; - buf_desc[1].size = buf_desc[1].length = 196; - buf_desc[1].type = CAM_CMD_BUF_I2C; - auto power_settings = mm.alloc(buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle); - - // power on - struct cam_cmd_power *power = power_settings.get(); - power->count = 4; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; - power->power_settings[0].power_seq_type = 3; // clock?? - power->power_settings[1].power_seq_type = 1; // analog - power->power_settings[2].power_seq_type = 2; // digital - power->power_settings[3].power_seq_type = 8; // reset low - power = power_set_wait(power, 1); - - // set clock - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; - power->power_settings[0].power_seq_type = 0; - power->power_settings[0].config_val_low = ci->mclk_frequency; - power = power_set_wait(power, 1); - - // reset high - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; - power->power_settings[0].power_seq_type = 8; - power->power_settings[0].config_val_low = 1; - // wait 650000 cycles @ 19.2 mhz = 33.8 ms - power = power_set_wait(power, 34); - - // probe happens here - - // disable clock - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 0; - power->power_settings[0].config_val_low = 0; - power = power_set_wait(power, 1); - - // reset high - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 8; - power->power_settings[0].config_val_low = 1; - power = power_set_wait(power, 1); - - // reset low - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 8; - power->power_settings[0].config_val_low = 0; - power = power_set_wait(power, 1); - - // power off - power->count = 3; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 2; - power->power_settings[1].power_seq_type = 1; - power->power_settings[2].power_seq_type = 3; - - int ret = do_cam_control(sensor_fd, CAM_SENSOR_PROBE_CMD, (void *)(uintptr_t)cam_packet_handle, 0); - LOGD("probing the sensor: %d", ret); - return ret; -} - -void CameraState::config_isp(int io_mem_handle, int fence, int request_id, int buf0_mem_handle, int buf0_offset) { - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*2; - if (io_mem_handle != 0) { - size += sizeof(struct cam_buf_io_cfg); - } - auto pkt = mm.alloc(size, &cam_packet_handle); - pkt->num_cmd_buf = 2; - pkt->kmd_cmd_buf_index = 0; - // YUV has kmd_cmd_buf_offset = 1780 - // I guess this is the ISP command - // YUV also has patch_offset = 0x1030 and num_patches = 10 - - if (io_mem_handle != 0) { - pkt->io_configs_offset = sizeof(struct cam_cmd_buf_desc)*pkt->num_cmd_buf; - pkt->num_io_configs = 1; - } - - if (io_mem_handle != 0) { - pkt->header.op_code = 0xf000001; - pkt->header.request_id = request_id; - } else { - pkt->header.op_code = 0xf000000; - } - pkt->header.size = size; - struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; - struct cam_buf_io_cfg *io_cfg = (struct cam_buf_io_cfg *)((char*)&pkt->payload + pkt->io_configs_offset); - - // TODO: support MMU - buf_desc[0].size = 65624; - buf_desc[0].length = 0; - buf_desc[0].type = CAM_CMD_BUF_DIRECT; - buf_desc[0].meta_data = 3; - buf_desc[0].mem_handle = buf0_mem_handle; - buf_desc[0].offset = buf0_offset; - - // parsed by cam_isp_packet_generic_blob_handler - struct isp_packet { - uint32_t type_0; - cam_isp_resource_hfr_config resource_hfr; - - uint32_t type_1; - cam_isp_clock_config clock; - uint64_t extra_rdi_hz[3]; - - uint32_t type_2; - cam_isp_bw_config bw; - struct cam_isp_bw_vote extra_rdi_vote[6]; - } __attribute__((packed)) tmp; - memset(&tmp, 0, sizeof(tmp)); - - tmp.type_0 = CAM_ISP_GENERIC_BLOB_TYPE_HFR_CONFIG; - tmp.type_0 |= sizeof(cam_isp_resource_hfr_config) << 8; - static_assert(sizeof(cam_isp_resource_hfr_config) == 0x20); - tmp.resource_hfr = { - .num_ports = 1, // 10 for YUV (but I don't think we need them) - .port_hfr_config[0] = { - .resource_type = CAM_ISP_IFE_OUT_RES_RDI_0, // CAM_ISP_IFE_OUT_RES_FULL for YUV - .subsample_pattern = 1, - .subsample_period = 0, - .framedrop_pattern = 1, - .framedrop_period = 0, - }}; - - tmp.type_1 = CAM_ISP_GENERIC_BLOB_TYPE_CLOCK_CONFIG; - tmp.type_1 |= (sizeof(cam_isp_clock_config) + sizeof(tmp.extra_rdi_hz)) << 8; - static_assert((sizeof(cam_isp_clock_config) + sizeof(tmp.extra_rdi_hz)) == 0x38); - tmp.clock = { - .usage_type = 1, // dual mode - .num_rdi = 4, - .left_pix_hz = 404000000, - .right_pix_hz = 404000000, - .rdi_hz[0] = 404000000, - }; - - - tmp.type_2 = CAM_ISP_GENERIC_BLOB_TYPE_BW_CONFIG; - tmp.type_2 |= (sizeof(cam_isp_bw_config) + sizeof(tmp.extra_rdi_vote)) << 8; - static_assert((sizeof(cam_isp_bw_config) + sizeof(tmp.extra_rdi_vote)) == 0xe0); - tmp.bw = { - .usage_type = 1, // dual mode - .num_rdi = 4, - .left_pix_vote = { - .resource_id = 0, - .cam_bw_bps = 450000000, - .ext_bw_bps = 450000000, - }, - .rdi_vote[0] = { - .resource_id = 0, - .cam_bw_bps = 8706200000, - .ext_bw_bps = 8706200000, - }, - }; - - static_assert(offsetof(struct isp_packet, type_2) == 0x60); - - buf_desc[1].size = sizeof(tmp); - buf_desc[1].offset = io_mem_handle != 0 ? 0x60 : 0; - buf_desc[1].length = buf_desc[1].size - buf_desc[1].offset; - buf_desc[1].type = CAM_CMD_BUF_GENERIC; - buf_desc[1].meta_data = CAM_ISP_PACKET_META_GENERIC_BLOB_COMMON; - auto buf2 = mm.alloc(buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle); - memcpy(buf2.get(), &tmp, sizeof(tmp)); - - if (io_mem_handle != 0) { - io_cfg[0].mem_handle[0] = io_mem_handle; - io_cfg[0].planes[0] = (struct cam_plane_cfg){ - .width = ci->frame_width, - .height = ci->frame_height + ci->extra_height, - .plane_stride = ci->frame_stride, - .slice_height = ci->frame_height + ci->extra_height, - .meta_stride = 0x0, // YUV has meta(stride=0x400, size=0x5000) - .meta_size = 0x0, - .meta_offset = 0x0, - .packer_config = 0x0, // 0xb for YUV - .mode_config = 0x0, // 0x9ef for YUV - .tile_config = 0x0, - .h_init = 0x0, - .v_init = 0x0, - }; - io_cfg[0].format = ci->mipi_format; // CAM_FORMAT_UBWC_TP10 for YUV - io_cfg[0].color_space = CAM_COLOR_SPACE_BASE; // CAM_COLOR_SPACE_BT601_FULL for YUV - io_cfg[0].color_pattern = 0x5; // 0x0 for YUV - io_cfg[0].bpp = (ci->mipi_format == CAM_FORMAT_MIPI_RAW_10 ? 0xa : 0xc); // bits per pixel - io_cfg[0].resource_type = CAM_ISP_IFE_OUT_RES_RDI_0; // CAM_ISP_IFE_OUT_RES_FULL for YUV - io_cfg[0].fence = fence; - io_cfg[0].direction = CAM_BUF_OUTPUT; - io_cfg[0].subsample_pattern = 0x1; - io_cfg[0].framedrop_pattern = 0x1; +// for debugging +const bool env_debug_frames = getenv("DEBUG_FRAMES") != nullptr; +const bool env_log_raw_frames = getenv("LOG_RAW_FRAMES") != nullptr; +const bool env_ctrl_exp_from_params = getenv("CTRL_EXP_FROM_PARAMS") != nullptr; + + +class CameraState { +public: + SpectraCamera camera; + int exposure_time = 5; + bool dc_gain_enabled = false; + int dc_gain_weight = 0; + int gain_idx = 0; + float analog_gain_frac = 0; + + float cur_ev[3] = {}; + float best_ev_score = 0; + int new_exp_g = 0; + int new_exp_t = 0; + + Rect ae_xywh = {}; + float measured_grey_fraction = 0; + float target_grey_fraction = 0.125; + + float fl_pix = 0; + std::unique_ptr pm; + + CameraState(SpectraMaster *master, const CameraConfig &config) : camera(master, config) {}; + ~CameraState(); + void init(VisionIpcServer *v); + void update_exposure_score(float desired_ev, int exp_t, int exp_g_idx, float exp_gain); + void set_camera_exposure(float grey_frac); + void set_exposure_rect(); + void sendState(); + + float get_gain_factor() const { + return (1 + dc_gain_weight * (camera.sensor->dc_gain_factor-1) / camera.sensor->dc_gain_max_weight); } +}; - int ret = device_config(multi_cam_state->isp_fd, session_handle, isp_dev_handle, cam_packet_handle); - assert(ret == 0); - if (ret != 0) { - LOGE("isp config failed"); - } -} +void CameraState::init(VisionIpcServer *v) { + camera.camera_open(v); -void CameraState::enqueue_buffer(int i, bool dp) { - int ret; - uint64_t request_id = request_ids[i]; + if (!camera.enabled) return; - if (buf_handle[i] && sync_objs[i]) { - // wait - struct cam_sync_wait sync_wait = {0}; - sync_wait.sync_obj = sync_objs[i]; - sync_wait.timeout_ms = 50; // max dt tolerance, typical should be 23 - ret = do_cam_control(multi_cam_state->cam_sync_fd, CAM_SYNC_WAIT, &sync_wait, sizeof(sync_wait)); - if (ret != 0) { - LOGE("failed to wait for sync: %d %d", ret, sync_wait.sync_obj); - // TODO: handle frame drop cleanly - } - - buf.camera_bufs_metadata[i].timestamp_eof = (uint64_t)nanos_since_boot(); // set true eof - if (dp) buf.queue(i); - - // destroy old output fence - struct cam_sync_info sync_destroy = {0}; - sync_destroy.sync_obj = sync_objs[i]; - ret = do_cam_control(multi_cam_state->cam_sync_fd, CAM_SYNC_DESTROY, &sync_destroy, sizeof(sync_destroy)); - if (ret != 0) { - LOGE("failed to destroy sync object: %d %d", ret, sync_destroy.sync_obj); - } - } - - // create output fence - struct cam_sync_info sync_create = {0}; - strcpy(sync_create.name, "NodeOutputPortFence"); - ret = do_cam_control(multi_cam_state->cam_sync_fd, CAM_SYNC_CREATE, &sync_create, sizeof(sync_create)); - if (ret != 0) { - LOGE("failed to create fence: %d %d", ret, sync_create.sync_obj); - } - sync_objs[i] = sync_create.sync_obj; - - // schedule request with camera request manager - struct cam_req_mgr_sched_request req_mgr_sched_request = {0}; - req_mgr_sched_request.session_hdl = session_handle; - req_mgr_sched_request.link_hdl = link_handle; - req_mgr_sched_request.req_id = request_id; - ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_SCHED_REQ, &req_mgr_sched_request, sizeof(req_mgr_sched_request)); - if (ret != 0) { - LOGE("failed to schedule cam mgr request: %d %lu", ret, request_id); - } + fl_pix = camera.cc.focal_len / camera.sensor->pixel_size_mm / camera.sensor->out_scale; + set_exposure_rect(); - // poke sensor, must happen after schedule - sensors_poke(request_id); + dc_gain_weight = camera.sensor->dc_gain_min_weight; + gain_idx = camera.sensor->analog_gain_rec_idx; + cur_ev[0] = cur_ev[1] = cur_ev[2] = get_gain_factor() * camera.sensor->sensor_analog_gains[gain_idx] * exposure_time; - // submit request to the ife - config_isp(buf_handle[i], sync_objs[i], request_id, buf0_handle, 65632*(i+1)); + pm = std::make_unique(std::vector{camera.cc.publish_name}); } -void CameraState::enqueue_req_multi(uint64_t start, int n, bool dp) { - for (uint64_t i = start; i < start + n; ++i) { - request_ids[(i - 1) % FRAME_BUF_COUNT] = i; - enqueue_buffer((i - 1) % FRAME_BUF_COUNT, dp); - } -} - -// ******************* camera ******************* +CameraState::~CameraState() {} void CameraState::set_exposure_rect() { // set areas for each camera, shouldn't be changed std::vector> ae_targets = { // (Rect, F) - std::make_pair((Rect){96, 250, 1734, 524}, 567.0), // wide + std::make_pair((Rect){96, 400, 1734, 524}, 567.0), // wide std::make_pair((Rect){96, 160, 1734, 986}, 2648.0), // road - std::make_pair((Rect){96, 242, 1736, 906}, 567.0) // driver + std::make_pair((Rect){96, 242, 1736, 906}, 567.0) // driver }; int h_ref = 1208; /* - exposure target intrinics is + exposure target intrinsics is [ [F, 0, 0.5*ae_xywh[2]] [0, F, 0.5*H-ae_xywh[1]] [0, 0, 1] ] */ - auto ae_target = ae_targets[camera_num]; + auto ae_target = ae_targets[camera.cc.camera_num]; Rect xywh_ref = ae_target.first; float fl_ref = ae_target.second; ae_xywh = (Rect){ - std::max(0, buf.rgb_width / 2 - (int)(fl_pix / fl_ref * xywh_ref.w / 2)), - std::max(0, buf.rgb_height / 2 - (int)(fl_pix / fl_ref * (h_ref / 2 - xywh_ref.y))), - std::min((int)(fl_pix / fl_ref * xywh_ref.w), buf.rgb_width / 2 + (int)(fl_pix / fl_ref * xywh_ref.w / 2)), - std::min((int)(fl_pix / fl_ref * xywh_ref.h), buf.rgb_height / 2 + (int)(fl_pix / fl_ref * (h_ref / 2 - xywh_ref.y))) - }; -} - -void CameraState::sensor_set_parameters() { - dc_gain_weight = ci->dc_gain_min_weight; - gain_idx = ci->analog_gain_rec_idx; - cur_ev[0] = cur_ev[1] = cur_ev[2] = (1 + dc_gain_weight * (ci->dc_gain_factor-1) / ci->dc_gain_max_weight) * ci->sensor_analog_gains[gain_idx] * exposure_time; -} - -void CameraState::camera_map_bufs() { - for (int i = 0; i < FRAME_BUF_COUNT; i++) { - // configure ISP to put the image in place - struct cam_mem_mgr_map_cmd mem_mgr_map_cmd = {0}; - mem_mgr_map_cmd.mmu_hdls[0] = multi_cam_state->device_iommu; - mem_mgr_map_cmd.num_hdl = 1; - mem_mgr_map_cmd.flags = CAM_MEM_FLAG_HW_READ_WRITE; - mem_mgr_map_cmd.fd = buf.camera_bufs[i].fd; - int ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_MAP_BUF, &mem_mgr_map_cmd, sizeof(mem_mgr_map_cmd)); - LOGD("map buf req: (fd: %d) 0x%x %d", buf.camera_bufs[i].fd, mem_mgr_map_cmd.out.buf_handle, ret); - buf_handle[i] = mem_mgr_map_cmd.out.buf_handle; - } - enqueue_req_multi(1, FRAME_BUF_COUNT, 0); -} - -void CameraState::camera_init(VisionIpcServer * v, cl_device_id device_id, cl_context ctx) { - if (!enabled) return; - - LOGD("camera init %d", camera_num); - buf.init(device_id, ctx, this, v, FRAME_BUF_COUNT, stream_type); - camera_map_bufs(); - - fl_pix = focal_len / ci->pixel_size_mm; - set_exposure_rect(); -} - -void CameraState::camera_open() { - if (!enabled) return; - - if (!openSensor()) { - return; - } - - configISP(); - configCSIPHY(); - linkDevices(); -} - -bool CameraState::openSensor() { - sensor_fd = open_v4l_by_name_and_index("cam-sensor-driver", camera_num); - assert(sensor_fd >= 0); - LOGD("opened sensor for %d", camera_num); - - // init memorymanager for this camera - mm.init(multi_cam_state->video0_fd); - - LOGD("-- Probing sensor %d", camera_num); - - auto init_sensor_lambda = [this](SensorInfo *sensor) { - ci.reset(sensor); - int ret = sensors_init(); - if (ret == 0) { - sensor_set_parameters(); - } - return ret == 0; + std::max(0, (int)camera.buf.out_img_width / 2 - (int)(fl_pix / fl_ref * xywh_ref.w / 2)), + std::max(0, (int)camera.buf.out_img_height / 2 - (int)(fl_pix / fl_ref * (h_ref / 2 - xywh_ref.y))), + std::min((int)(fl_pix / fl_ref * xywh_ref.w), (int)camera.buf.out_img_width / 2 + (int)(fl_pix / fl_ref * xywh_ref.w / 2)), + std::min((int)(fl_pix / fl_ref * xywh_ref.h), (int)camera.buf.out_img_height / 2 + (int)(fl_pix / fl_ref * (h_ref / 2 - xywh_ref.y))) }; - - // Try different sensors one by one until it success. - if (!init_sensor_lambda(new AR0231) && - !init_sensor_lambda(new OX03C10) && - !init_sensor_lambda(new OS04C10)) { - LOGE("** sensor %d FAILED bringup, disabling", camera_num); - enabled = false; - return false; - } - LOGD("-- Probing sensor %d success", camera_num); - - // create session - struct cam_req_mgr_session_info session_info = {}; - int ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_CREATE_SESSION, &session_info, sizeof(session_info)); - LOGD("get session: %d 0x%X", ret, session_info.session_hdl); - session_handle = session_info.session_hdl; - - // access the sensor - LOGD("-- Accessing sensor"); - auto sensor_dev_handle_ = device_acquire(sensor_fd, session_handle, nullptr); - assert(sensor_dev_handle_); - sensor_dev_handle = *sensor_dev_handle_; - LOGD("acquire sensor dev"); - - LOG("-- Configuring sensor"); - sensors_i2c(ci->init_reg_array.data(), ci->init_reg_array.size(), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, ci->data_word); - return true; -} - -void CameraState::configISP() { - // NOTE: to be able to disable road and wide road, we still have to configure the sensor over i2c - // If you don't do this, the strobe GPIO is an output (even in reset it seems!) - if (!enabled) return; - - struct cam_isp_in_port_info in_port_info = { - .res_type = (uint32_t[]){CAM_ISP_IFE_IN_RES_PHY_0, CAM_ISP_IFE_IN_RES_PHY_1, CAM_ISP_IFE_IN_RES_PHY_2}[camera_num], - - .lane_type = CAM_ISP_LANE_TYPE_DPHY, - .lane_num = 4, - .lane_cfg = 0x3210, - - .vc = 0x0, - .dt = ci->frame_data_type, - .format = ci->mipi_format, - - .test_pattern = 0x2, // 0x3? - .usage_type = 0x0, - - .left_start = 0, - .left_stop = ci->frame_width - 1, - .left_width = ci->frame_width, - - .right_start = 0, - .right_stop = ci->frame_width - 1, - .right_width = ci->frame_width, - - .line_start = 0, - .line_stop = ci->frame_height + ci->extra_height - 1, - .height = ci->frame_height + ci->extra_height, - - .pixel_clk = 0x0, - .batch_size = 0x0, - .dsp_mode = CAM_ISP_DSP_MODE_NONE, - .hbi_cnt = 0x0, - .custom_csid = 0x0, - - .num_out_res = 0x1, - .data[0] = (struct cam_isp_out_port_info){ - .res_type = CAM_ISP_IFE_OUT_RES_RDI_0, - .format = ci->mipi_format, - .width = ci->frame_width, - .height = ci->frame_height + ci->extra_height, - .comp_grp_id = 0x0, .split_point = 0x0, .secure_mode = 0x0, - }, - }; - struct cam_isp_resource isp_resource = { - .resource_id = CAM_ISP_RES_ID_PORT, - .handle_type = CAM_HANDLE_USER_POINTER, - .res_hdl = (uint64_t)&in_port_info, - .length = sizeof(in_port_info), - }; - - auto isp_dev_handle_ = device_acquire(multi_cam_state->isp_fd, session_handle, &isp_resource); - assert(isp_dev_handle_); - isp_dev_handle = *isp_dev_handle_; - LOGD("acquire isp dev"); - - // config ISP - alloc_w_mmu_hdl(multi_cam_state->video0_fd, 984480, (uint32_t*)&buf0_handle, 0x20, CAM_MEM_FLAG_HW_READ_WRITE | CAM_MEM_FLAG_KMD_ACCESS | - CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_CMD_BUF_TYPE, multi_cam_state->device_iommu, multi_cam_state->cdm_iommu); - config_isp(0, 0, 1, buf0_handle, 0); -} - -void CameraState::configCSIPHY() { - csiphy_fd = open_v4l_by_name_and_index("cam-csiphy-driver", camera_num); - assert(csiphy_fd >= 0); - LOGD("opened csiphy for %d", camera_num); - - struct cam_csiphy_acquire_dev_info csiphy_acquire_dev_info = {.combo_mode = 0}; - auto csiphy_dev_handle_ = device_acquire(csiphy_fd, session_handle, &csiphy_acquire_dev_info); - assert(csiphy_dev_handle_); - csiphy_dev_handle = *csiphy_dev_handle_; - LOGD("acquire csiphy dev"); - - // config csiphy - LOG("-- Config CSI PHY"); - { - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*1; - auto pkt = mm.alloc(size, &cam_packet_handle); - pkt->num_cmd_buf = 1; - pkt->kmd_cmd_buf_index = -1; - pkt->header.size = size; - struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; - - buf_desc[0].size = buf_desc[0].length = sizeof(struct cam_csiphy_info); - buf_desc[0].type = CAM_CMD_BUF_GENERIC; - - auto csiphy_info = mm.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); - csiphy_info->lane_mask = 0x1f; - csiphy_info->lane_assign = 0x3210;// skip clk. How is this 16 bit for 5 channels?? - csiphy_info->csiphy_3phase = 0x0; // no 3 phase, only 2 conductors per lane - csiphy_info->combo_mode = 0x0; - csiphy_info->lane_cnt = 0x4; - csiphy_info->secure_mode = 0x0; - csiphy_info->settle_time = MIPI_SETTLE_CNT * 200000000ULL; - csiphy_info->data_rate = 48000000; // Calculated by camera_freqs.py - - int ret_ = device_config(csiphy_fd, session_handle, csiphy_dev_handle, cam_packet_handle); - assert(ret_ == 0); - } -} - -void CameraState::linkDevices() { - LOG("-- Link devices"); - struct cam_req_mgr_link_info req_mgr_link_info = {0}; - req_mgr_link_info.session_hdl = session_handle; - req_mgr_link_info.num_devices = 2; - req_mgr_link_info.dev_hdls[0] = isp_dev_handle; - req_mgr_link_info.dev_hdls[1] = sensor_dev_handle; - int ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_LINK, &req_mgr_link_info, sizeof(req_mgr_link_info)); - link_handle = req_mgr_link_info.link_hdl; - LOGD("link: %d session: 0x%X isp: 0x%X sensors: 0x%X link: 0x%X", ret, session_handle, isp_dev_handle, sensor_dev_handle, link_handle); - - struct cam_req_mgr_link_control req_mgr_link_control = {0}; - req_mgr_link_control.ops = CAM_REQ_MGR_LINK_ACTIVATE; - req_mgr_link_control.session_hdl = session_handle; - req_mgr_link_control.num_links = 1; - req_mgr_link_control.link_hdls[0] = link_handle; - ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_LINK_CONTROL, &req_mgr_link_control, sizeof(req_mgr_link_control)); - LOGD("link control: %d", ret); - - ret = device_control(csiphy_fd, CAM_START_DEV, session_handle, csiphy_dev_handle); - LOGD("start csiphy: %d", ret); - ret = device_control(multi_cam_state->isp_fd, CAM_START_DEV, session_handle, isp_dev_handle); - LOGD("start isp: %d", ret); - assert(ret == 0); - - // TODO: this is unneeded, should we be doing the start i2c in a different way? - //ret = device_control(sensor_fd, CAM_START_DEV, session_handle, sensor_dev_handle); - //LOGD("start sensor: %d", ret); -} - -void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) { - s->driver_cam.camera_init(v, device_id, ctx); - s->road_cam.camera_init(v, device_id, ctx); - s->wide_road_cam.camera_init(v, device_id, ctx); - - s->pm = new PubMaster({"roadCameraState", "driverCameraState", "wideRoadCameraState", "thumbnail"}); -} - -void cameras_open(MultiCameraState *s) { - LOG("-- Opening devices"); - // video0 is req_mgr, the target of many ioctls - s->video0_fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-soc:qcom_cam-req-mgr-video-index0", O_RDWR | O_NONBLOCK)); - assert(s->video0_fd >= 0); - LOGD("opened video0"); - - // video1 is cam_sync, the target of some ioctls - s->cam_sync_fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-cam_sync-video-index0", O_RDWR | O_NONBLOCK)); - assert(s->cam_sync_fd >= 0); - LOGD("opened video1 (cam_sync)"); - - // looks like there's only one of these - s->isp_fd = open_v4l_by_name_and_index("cam-isp"); - assert(s->isp_fd >= 0); - LOGD("opened isp"); - - // query icp for MMU handles - LOG("-- Query ICP for MMU handles"); - struct cam_isp_query_cap_cmd isp_query_cap_cmd = {0}; - struct cam_query_cap_cmd query_cap_cmd = {0}; - query_cap_cmd.handle_type = 1; - query_cap_cmd.caps_handle = (uint64_t)&isp_query_cap_cmd; - query_cap_cmd.size = sizeof(isp_query_cap_cmd); - int ret = do_cam_control(s->isp_fd, CAM_QUERY_CAP, &query_cap_cmd, sizeof(query_cap_cmd)); - assert(ret == 0); - LOGD("using MMU handle: %x", isp_query_cap_cmd.device_iommu.non_secure); - LOGD("using MMU handle: %x", isp_query_cap_cmd.cdm_iommu.non_secure); - s->device_iommu = isp_query_cap_cmd.device_iommu.non_secure; - s->cdm_iommu = isp_query_cap_cmd.cdm_iommu.non_secure; - - // subscribe - LOG("-- Subscribing"); - struct v4l2_event_subscription sub = {0}; - sub.type = V4L_EVENT_CAM_REQ_MGR_EVENT; - sub.id = V4L_EVENT_CAM_REQ_MGR_SOF_BOOT_TS; - ret = HANDLE_EINTR(ioctl(s->video0_fd, VIDIOC_SUBSCRIBE_EVENT, &sub)); - LOGD("req mgr subscribe: %d", ret); - - s->driver_cam.camera_open(); - LOGD("driver camera opened"); - s->road_cam.camera_open(); - LOGD("road camera opened"); - s->wide_road_cam.camera_open(); - LOGD("wide road camera opened"); -} - -void CameraState::camera_close() { - // stop devices - LOG("-- Stop devices %d", camera_num); - - if (enabled) { - // ret = device_control(sensor_fd, CAM_STOP_DEV, session_handle, sensor_dev_handle); - // LOGD("stop sensor: %d", ret); - int ret = device_control(multi_cam_state->isp_fd, CAM_STOP_DEV, session_handle, isp_dev_handle); - LOGD("stop isp: %d", ret); - ret = device_control(csiphy_fd, CAM_STOP_DEV, session_handle, csiphy_dev_handle); - LOGD("stop csiphy: %d", ret); - // link control stop - LOG("-- Stop link control"); - struct cam_req_mgr_link_control req_mgr_link_control = {0}; - req_mgr_link_control.ops = CAM_REQ_MGR_LINK_DEACTIVATE; - req_mgr_link_control.session_hdl = session_handle; - req_mgr_link_control.num_links = 1; - req_mgr_link_control.link_hdls[0] = link_handle; - ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_LINK_CONTROL, &req_mgr_link_control, sizeof(req_mgr_link_control)); - LOGD("link control stop: %d", ret); - - // unlink - LOG("-- Unlink"); - struct cam_req_mgr_unlink_info req_mgr_unlink_info = {0}; - req_mgr_unlink_info.session_hdl = session_handle; - req_mgr_unlink_info.link_hdl = link_handle; - ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_UNLINK, &req_mgr_unlink_info, sizeof(req_mgr_unlink_info)); - LOGD("unlink: %d", ret); - - // release devices - LOGD("-- Release devices"); - ret = device_control(multi_cam_state->isp_fd, CAM_RELEASE_DEV, session_handle, isp_dev_handle); - LOGD("release isp: %d", ret); - ret = device_control(csiphy_fd, CAM_RELEASE_DEV, session_handle, csiphy_dev_handle); - LOGD("release csiphy: %d", ret); - - for (int i = 0; i < FRAME_BUF_COUNT; i++) { - release(multi_cam_state->video0_fd, buf_handle[i]); - } - LOGD("released buffers"); - } - - int ret = device_control(sensor_fd, CAM_RELEASE_DEV, session_handle, sensor_dev_handle); - LOGD("release sensor: %d", ret); - - // destroyed session - struct cam_req_mgr_session_info session_info = {.session_hdl = session_handle}; - ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_DESTROY_SESSION, &session_info, sizeof(session_info)); - LOGD("destroyed session %d: %d", camera_num, ret); -} - -void cameras_close(MultiCameraState *s) { - s->driver_cam.camera_close(); - s->road_cam.camera_close(); - s->wide_road_cam.camera_close(); - - delete s->pm; -} - -void CameraState::handle_camera_event(void *evdat) { - if (!enabled) return; - struct cam_req_mgr_message *event_data = (struct cam_req_mgr_message *)evdat; - assert(event_data->session_hdl == session_handle); - assert(event_data->u.frame_msg.link_hdl == link_handle); - - uint64_t timestamp = event_data->u.frame_msg.timestamp; - uint64_t main_id = event_data->u.frame_msg.frame_id; - uint64_t real_id = event_data->u.frame_msg.request_id; - - if (real_id != 0) { // next ready - if (real_id == 1) {idx_offset = main_id;} - int buf_idx = (real_id - 1) % FRAME_BUF_COUNT; - - // check for skipped frames - if (main_id > frame_id_last + 1 && !skipped) { - LOGE("camera %d realign", camera_num); - clear_req_queue(); - enqueue_req_multi(real_id + 1, FRAME_BUF_COUNT - 1, 0); - skipped = true; - } else if (main_id == frame_id_last + 1) { - skipped = false; - } - - // check for dropped requests - if (real_id > request_id_last + 1) { - LOGE("camera %d dropped requests %ld %ld", camera_num, real_id, request_id_last); - enqueue_req_multi(request_id_last + 1 + FRAME_BUF_COUNT, real_id - (request_id_last + 1), 0); - } - - // metas - frame_id_last = main_id; - request_id_last = real_id; - - auto &meta_data = buf.camera_bufs_metadata[buf_idx]; - meta_data.frame_id = main_id - idx_offset; - meta_data.request_id = real_id; - meta_data.timestamp_sof = timestamp; - exp_lock.lock(); - meta_data.gain = analog_gain_frac * (1 + dc_gain_weight * (ci->dc_gain_factor-1) / ci->dc_gain_max_weight); - meta_data.high_conversion_gain = dc_gain_enabled; - meta_data.integ_lines = exposure_time; - meta_data.measured_grey_fraction = measured_grey_fraction; - meta_data.target_grey_fraction = target_grey_fraction; - exp_lock.unlock(); - - // dispatch - enqueue_req_multi(real_id + FRAME_BUF_COUNT, 1, 1); - } else { // not ready - if (main_id > frame_id_last + 10) { - LOGE("camera %d reset after half second of no response", camera_num); - clear_req_queue(); - enqueue_req_multi(request_id_last + 1, FRAME_BUF_COUNT, 0); - frame_id_last = main_id; - skipped = true; - } - } } void CameraState::update_exposure_score(float desired_ev, int exp_t, int exp_g_idx, float exp_gain) { - float score = ci->getExposureScore(desired_ev, exp_t, exp_g_idx, exp_gain, gain_idx); + float score = camera.sensor->getExposureScore(desired_ev, exp_t, exp_g_idx, exp_gain, gain_idx); if (score < best_ev_score) { new_exp_t = exp_t; new_exp_g = exp_g_idx; @@ -842,7 +114,9 @@ void CameraState::update_exposure_score(float desired_ev, int exp_t, int exp_g_i } void CameraState::set_camera_exposure(float grey_frac) { - if (!enabled) return; + if (!camera.enabled) return; + std::vector target_grey_minimums = {0.1, 0.1, 0.125}; // wide, road, driver + const float dt = 0.05; const float ts_grey = 10.0; @@ -856,13 +130,15 @@ void CameraState::set_camera_exposure(float grey_frac) { // Therefore we use the target EV from 3 frames ago, the grey fraction that was just measured was the result of that control action. // TODO: Lower latency to 2 frames, by using the histogram outputted by the sensor we can do AE before the debayering is complete - const float cur_ev_ = cur_ev[buf.cur_frame_data.frame_id % 3]; + const auto &sensor = camera.sensor; + // Offset idx by one to not get stuck in self loop + const float cur_ev_ = cur_ev[(camera.buf.cur_frame_data.frame_id - 1) % 3] * sensor->ev_scale; - // Scale target grey between 0.1 and 0.4 depending on lighting conditions - float new_target_grey = std::clamp(0.4 - 0.3 * log2(1.0 + ci->target_grey_factor*cur_ev_) / log2(6000.0), 0.1, 0.4); + // Scale target grey between min and 0.4 depending on lighting conditions + float new_target_grey = std::clamp(0.4 - 0.3 * log2(1.0 + sensor->target_grey_factor*cur_ev_) / log2(6000.0), target_grey_minimums[camera.cc.camera_num], 0.4); float target_grey = (1.0 - k_grey) * target_grey_fraction + k_grey * new_target_grey; - float desired_ev = std::clamp(cur_ev_ * target_grey / grey_frac, ci->min_ev, ci->max_ev); + float desired_ev = std::clamp(cur_ev_ / sensor->ev_scale * target_grey / grey_frac, sensor->min_ev, sensor->max_ev); float k = (1.0 - k_ev) / 3.0; desired_ev = (k * cur_ev[0]) + (k * cur_ev[1]) + (k * cur_ev[2]) + (k_ev * desired_ev); @@ -873,19 +149,20 @@ void CameraState::set_camera_exposure(float grey_frac) { // Hysteresis around high conversion gain // We usually want this on since it results in lower noise, but turn off in very bright day scenes bool enable_dc_gain = dc_gain_enabled; - if (!enable_dc_gain && target_grey < ci->dc_gain_on_grey) { + if (!enable_dc_gain && target_grey < sensor->dc_gain_on_grey) { enable_dc_gain = true; - dc_gain_weight = ci->dc_gain_min_weight; - } else if (enable_dc_gain && target_grey > ci->dc_gain_off_grey) { + dc_gain_weight = sensor->dc_gain_min_weight; + } else if (enable_dc_gain && target_grey > sensor->dc_gain_off_grey) { enable_dc_gain = false; - dc_gain_weight = ci->dc_gain_max_weight; + dc_gain_weight = sensor->dc_gain_max_weight; } - if (enable_dc_gain && dc_gain_weight < ci->dc_gain_max_weight) {dc_gain_weight += 1;} - if (!enable_dc_gain && dc_gain_weight > ci->dc_gain_min_weight) {dc_gain_weight -= 1;} + if (enable_dc_gain && dc_gain_weight < sensor->dc_gain_max_weight) {dc_gain_weight += 1;} + if (!enable_dc_gain && dc_gain_weight > sensor->dc_gain_min_weight) {dc_gain_weight -= 1;} std::string gain_bytes, time_bytes; if (env_ctrl_exp_from_params) { + static Params params; gain_bytes = params.get("CameraDebugExpGain"); time_bytes = params.get("CameraDebugExpTime"); } @@ -899,16 +176,17 @@ void CameraState::set_camera_exposure(float grey_frac) { new_exp_t = exposure_time; enable_dc_gain = false; } else { - // Simple brute force optimizer to choose sensor parameters - // to reach desired EV - for (int g = std::max((int)ci->analog_gain_min_idx, gain_idx - 1); g <= std::min((int)ci->analog_gain_max_idx, gain_idx + 1); g++) { - float gain = ci->sensor_analog_gains[g] * (1 + dc_gain_weight * (ci->dc_gain_factor-1) / ci->dc_gain_max_weight); + // Simple brute force optimizer to choose sensor parameters to reach desired EV + int min_g = std::max(gain_idx - 1, sensor->analog_gain_min_idx); + int max_g = std::min(gain_idx + 1, sensor->analog_gain_max_idx); + for (int g = min_g; g <= max_g; g++) { + float gain = sensor->sensor_analog_gains[g] * get_gain_factor(); // Compute optimal time for given gain - int t = std::clamp(int(std::round(desired_ev / gain)), ci->exposure_time_min, ci->exposure_time_max); + int t = std::clamp(int(std::round(desired_ev / gain)), sensor->exposure_time_min, sensor->exposure_time_max); // Only go below recommended gain when absolutely necessary to not overexpose - if (g < ci->analog_gain_rec_idx && t > 20 && g < gain_idx) { + if (g < sensor->analog_gain_rec_idx && t > 20 && g < gain_idx) { continue; } @@ -916,92 +194,83 @@ void CameraState::set_camera_exposure(float grey_frac) { } } - exp_lock.lock(); - measured_grey_fraction = grey_frac; target_grey_fraction = target_grey; - analog_gain_frac = ci->sensor_analog_gains[new_exp_g]; + analog_gain_frac = sensor->sensor_analog_gains[new_exp_g]; gain_idx = new_exp_g; exposure_time = new_exp_t; dc_gain_enabled = enable_dc_gain; - float gain = analog_gain_frac * (1 + dc_gain_weight * (ci->dc_gain_factor-1) / ci->dc_gain_max_weight); - cur_ev[buf.cur_frame_data.frame_id % 3] = exposure_time * gain; + float gain = analog_gain_frac * get_gain_factor(); + cur_ev[camera.buf.cur_frame_data.frame_id % 3] = exposure_time * gain; - exp_lock.unlock(); + // LOGE("ae - camera %d, cur_t %.5f, sof %.5f, dt %.5f", camera.cc.camera_num, 1e-9 * nanos_since_boot(), 1e-9 * camera.buf.cur_frame_data.timestamp_sof, 1e-9 * (nanos_since_boot() - camera.buf.cur_frame_data.timestamp_sof)); - // Processing a frame takes right about 50ms, so we need to wait a few ms - // so we don't send i2c commands around the frame start. - int ms = (nanos_since_boot() - buf.cur_frame_data.timestamp_sof) / 1000000; - if (ms < 60) { - util::sleep_for(60 - ms); - } - // LOGE("ae - camera %d, cur_t %.5f, sof %.5f, dt %.5f", camera_num, 1e-9 * nanos_since_boot(), 1e-9 * buf.cur_frame_data.timestamp_sof, 1e-9 * (nanos_since_boot() - buf.cur_frame_data.timestamp_sof)); - - auto exp_reg_array = ci->getExposureRegisters(exposure_time, new_exp_g, dc_gain_enabled); - sensors_i2c(exp_reg_array.data(), exp_reg_array.size(), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, ci->data_word); + auto exp_reg_array = sensor->getExposureRegisters(exposure_time, new_exp_g, dc_gain_enabled); + camera.sensors_i2c(exp_reg_array.data(), exp_reg_array.size(), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, camera.sensor->data_word); } -void CameraState::run() { - util::set_thread_name(publish_name); +void CameraState::sendState() { + camera.buf.sendFrameToVipc(); + + MessageBuilder msg; + auto framed = (msg.initEvent().*camera.cc.init_camera_state)(); + const FrameMetadata &meta = camera.buf.cur_frame_data; + framed.setFrameId(meta.frame_id); + framed.setRequestId(meta.request_id); + framed.setTimestampEof(meta.timestamp_eof); + framed.setTimestampSof(meta.timestamp_sof); + framed.setIntegLines(exposure_time); + framed.setGain(analog_gain_frac * get_gain_factor()); + framed.setHighConversionGain(dc_gain_enabled); + framed.setMeasuredGreyFraction(measured_grey_fraction); + framed.setTargetGreyFraction(target_grey_fraction); + framed.setProcessingTime(meta.processing_time); + + const float ev = cur_ev[meta.frame_id % 3]; + const float perc = util::map_val(ev, camera.sensor->min_ev, camera.sensor->max_ev, 0.0f, 100.0f); + framed.setExposureValPercent(perc); + framed.setSensor(camera.sensor->image_sensor); + + // Log raw frames for road camera + if (env_log_raw_frames && camera.cc.stream_type == VISION_STREAM_ROAD && meta.frame_id % 100 == 5) { // no overlap with qlog decimation + framed.setImage(get_raw_frame_image(&camera.buf)); + } - for (uint32_t cnt = 0; !do_exit; ++cnt) { - // Acquire the buffer; continue if acquisition fails - if (!buf.acquire()) continue; + set_camera_exposure(calculate_exposure_value(&camera.buf, ae_xywh, 2, camera.cc.stream_type != VISION_STREAM_DRIVER ? 2 : 4)); - MessageBuilder msg; - auto framed = (msg.initEvent().*init_camera_state)(); - fill_frame_data(framed, buf.cur_frame_data, this); + // Send the message + pm->send(camera.cc.publish_name, msg); +} - // Log raw frames for road camera - if (env_log_raw_frames && stream_type == VISION_STREAM_ROAD && cnt % 100 == 5) { // no overlap with qlog decimation - framed.setImage(get_raw_frame_image(&buf)); - } - // Log frame id for road and wide road cameras - if (stream_type != VISION_STREAM_DRIVER) { - LOGT(buf.cur_frame_data.frame_id, "%s: Image set", publish_name); - } +void camerad_thread() { + // TODO: centralize enabled handling - // Process camera registers and set camera exposure - ci->processRegisters(this, framed); - set_camera_exposure(set_exposure_target(&buf, ae_xywh, 2, stream_type != VISION_STREAM_DRIVER ? 2 : 4)); + VisionIpcServer v("camerad"); - // Send the message - multi_cam_state->pm->send(publish_name, msg); - if (stream_type == VISION_STREAM_ROAD && cnt % 100 == 3) { - publish_thumbnail(multi_cam_state->pm, &buf); // this takes 10ms??? - } - } -} + // *** initial ISP init *** + SpectraMaster m; + m.init(); -MultiCameraState::MultiCameraState() - : driver_cam(this, DRIVER_CAMERA_CONFIG), - road_cam(this, ROAD_CAMERA_CONFIG), - wide_road_cam(this, WIDE_ROAD_CAMERA_CONFIG) { -} + // *** per-cam init *** + std::vector> cams; + for (const auto &config : ALL_CAMERA_CONFIGS) { + auto cam = std::make_unique(&m, config); + cam->init(&v); + cams.emplace_back(std::move(cam)); + } -void cameras_run(MultiCameraState *s) { - LOG("-- Starting threads"); - std::vector threads; - if (s->driver_cam.enabled) threads.emplace_back(&CameraState::run, &s->driver_cam); - if (s->road_cam.enabled) threads.emplace_back(&CameraState::run, &s->road_cam); - if (s->wide_road_cam.enabled) threads.emplace_back(&CameraState::run, &s->wide_road_cam); + v.start_listener(); // start devices LOG("-- Starting devices"); - s->driver_cam.sensors_start(); - s->road_cam.sensors_start(); - s->wide_road_cam.sensors_start(); + for (auto &cam : cams) cam->camera.sensors_start(); // poll events LOG("-- Dequeueing Video events"); while (!do_exit) { - struct pollfd fds[1] = {{0}}; - - fds[0].fd = s->video0_fd; - fds[0].events = POLLPRI; - + struct pollfd fds[1] = {{.fd = m.video0_fd, .events = POLLPRI}}; int ret = poll(fds, std::size(fds), 1000); if (ret < 0) { if (errno == EINTR || errno == EAGAIN) continue; @@ -1009,7 +278,7 @@ void cameras_run(MultiCameraState *s) { break; } - if (!fds[0].revents) continue; + if (!(fds[0].revents & POLLPRI)) continue; struct v4l2_event ev = {0}; ret = HANDLE_EINTR(ioctl(fds[0].fd, VIDIOC_DQEVENT, &ev)); @@ -1019,20 +288,16 @@ void cameras_run(MultiCameraState *s) { if (env_debug_frames) { printf("sess_hdl 0x%6X, link_hdl 0x%6X, frame_id %lu, req_id %lu, timestamp %.2f ms, sof_status %d\n", event_data->session_hdl, event_data->u.frame_msg.link_hdl, event_data->u.frame_msg.frame_id, event_data->u.frame_msg.request_id, event_data->u.frame_msg.timestamp/1e6, event_data->u.frame_msg.sof_status); + do_exit = do_exit || event_data->u.frame_msg.frame_id > (1*20); } - // for debugging - //do_exit = do_exit || event_data->u.frame_msg.frame_id > (30*20); - - if (event_data->session_hdl == s->road_cam.session_handle) { - s->road_cam.handle_camera_event(event_data); - } else if (event_data->session_hdl == s->wide_road_cam.session_handle) { - s->wide_road_cam.handle_camera_event(event_data); - } else if (event_data->session_hdl == s->driver_cam.session_handle) { - s->driver_cam.handle_camera_event(event_data); - } else { - LOGE("Unknown vidioc event source"); - assert(false); + for (auto &cam : cams) { + if (event_data->session_hdl == cam->camera.session_handle) { + if (cam->camera.handle_camera_event(event_data)) { + cam->sendState(); + } + break; + } } } else { LOGE("unhandled event %d\n", ev.type); @@ -1041,10 +306,4 @@ void cameras_run(MultiCameraState *s) { LOGE("VIDIOC_DQEVENT failed, errno=%d", errno); } } - - LOG(" ************** STOPPING **************"); - - for (auto &t : threads) t.join(); - - cameras_close(s); } diff --git a/system/camerad/cameras/camera_qcom2.h b/system/camerad/cameras/camera_qcom2.h deleted file mode 100644 index 02ebeb71f31296..00000000000000 --- a/system/camerad/cameras/camera_qcom2.h +++ /dev/null @@ -1,151 +0,0 @@ -#pragma once - -#include -#include - -#include "system/camerad/cameras/camera_common.h" -#include "system/camerad/cameras/camera_util.h" -#include "system/camerad/sensors/sensor.h" -#include "common/params.h" -#include "common/util.h" - -#define FRAME_BUF_COUNT 4 - -struct CameraConfig { - int camera_num; - VisionStreamType stream_type; - float focal_len; // millimeters - const char *publish_name; - cereal::FrameData::Builder (cereal::Event::Builder::*init_camera_state)(); - bool enabled; -}; - -const CameraConfig WIDE_ROAD_CAMERA_CONFIG = { - .camera_num = 0, - .stream_type = VISION_STREAM_WIDE_ROAD, - .focal_len = 1.71, - .publish_name = "wideRoadCameraState", - .init_camera_state = &cereal::Event::Builder::initWideRoadCameraState, - .enabled = !getenv("DISABLE_WIDE_ROAD"), -}; - -const CameraConfig ROAD_CAMERA_CONFIG = { - .camera_num = 1, - .stream_type = VISION_STREAM_ROAD, - .focal_len = 8.0, - .publish_name = "roadCameraState", - .init_camera_state = &cereal::Event::Builder::initRoadCameraState, - .enabled = !getenv("DISABLE_ROAD"), -}; - -const CameraConfig DRIVER_CAMERA_CONFIG = { - .camera_num = 2, - .stream_type = VISION_STREAM_DRIVER, - .focal_len = 1.71, - .publish_name = "driverCameraState", - .init_camera_state = &cereal::Event::Builder::initDriverCameraState, - .enabled = !getenv("DISABLE_DRIVER"), -}; - -class CameraState { -public: - MultiCameraState *multi_cam_state = nullptr; - std::unique_ptr ci; - bool enabled = true; - VisionStreamType stream_type; - const char *publish_name = nullptr; - cereal::FrameData::Builder (cereal::Event::Builder::*init_camera_state)() = nullptr; - float focal_len = 0; - - std::mutex exp_lock; - - int exposure_time = 5; - bool dc_gain_enabled = false; - int dc_gain_weight = 0; - int gain_idx = 0; - float analog_gain_frac = 0; - - float cur_ev[3] = {}; - float best_ev_score = 0; - int new_exp_g = 0; - int new_exp_t = 0; - - Rect ae_xywh = {}; - float measured_grey_fraction = 0; - float target_grey_fraction = 0.3; - - unique_fd sensor_fd; - unique_fd csiphy_fd; - - int camera_num = 0; - float fl_pix = 0; - - CameraState(MultiCameraState *multi_camera_state, const CameraConfig &config); - void handle_camera_event(void *evdat); - void update_exposure_score(float desired_ev, int exp_t, int exp_g_idx, float exp_gain); - void set_camera_exposure(float grey_frac); - - void sensors_start(); - - void camera_open(); - void set_exposure_rect(); - void sensor_set_parameters(); - void camera_map_bufs(); - void camera_init(VisionIpcServer *v, cl_device_id device_id, cl_context ctx); - void camera_close(); - void run(); - - int32_t session_handle = -1; - int32_t sensor_dev_handle = -1; - int32_t isp_dev_handle = -1; - int32_t csiphy_dev_handle = -1; - - int32_t link_handle = -1; - - int buf0_handle = 0; - int buf_handle[FRAME_BUF_COUNT] = {}; - int sync_objs[FRAME_BUF_COUNT] = {}; - uint64_t request_ids[FRAME_BUF_COUNT] = {}; - uint64_t request_id_last = 0; - uint64_t frame_id_last = 0; - uint64_t idx_offset = 0; - bool skipped = true; - - CameraBuf buf; - MemoryManager mm; - - void config_isp(int io_mem_handle, int fence, int request_id, int buf0_mem_handle, int buf0_offset); - void enqueue_req_multi(uint64_t start, int n, bool dp); - void enqueue_buffer(int i, bool dp); - int clear_req_queue(); - - int sensors_init(); - void sensors_poke(int request_id); - void sensors_i2c(const struct i2c_random_wr_payload* dat, int len, int op_code, bool data_word); - -private: - bool openSensor(); - void configISP(); - void configCSIPHY(); - void linkDevices(); - - // for debugging - Params params; -}; - -class MultiCameraState { -public: - MultiCameraState(); - - unique_fd video0_fd; - unique_fd cam_sync_fd; - unique_fd isp_fd; - int device_iommu = -1; - int cdm_iommu = -1; - - CameraState road_cam; - CameraState wide_road_cam; - CameraState driver_cam; - - PubMaster *pm; -}; diff --git a/system/camerad/cameras/camera_util.cc b/system/camerad/cameras/camera_util.cc deleted file mode 100644 index 7bd23fd9fe7e40..00000000000000 --- a/system/camerad/cameras/camera_util.cc +++ /dev/null @@ -1,137 +0,0 @@ -#include "system/camerad/cameras/camera_util.h" - -#include - -#include - -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" - -// ************** low level camera helpers **************** -int do_cam_control(int fd, int op_code, void *handle, int size) { - struct cam_control camcontrol = {0}; - camcontrol.op_code = op_code; - camcontrol.handle = (uint64_t)handle; - if (size == 0) { - camcontrol.size = 8; - camcontrol.handle_type = CAM_HANDLE_MEM_HANDLE; - } else { - camcontrol.size = size; - camcontrol.handle_type = CAM_HANDLE_USER_POINTER; - } - - int ret = HANDLE_EINTR(ioctl(fd, VIDIOC_CAM_CONTROL, &camcontrol)); - if (ret == -1) { - LOGE("VIDIOC_CAM_CONTROL error: op_code %d - errno %d", op_code, errno); - } - return ret; -} - -std::optional device_acquire(int fd, int32_t session_handle, void *data, uint32_t num_resources) { - struct cam_acquire_dev_cmd cmd = { - .session_handle = session_handle, - .handle_type = CAM_HANDLE_USER_POINTER, - .num_resources = (uint32_t)(data ? num_resources : 0), - .resource_hdl = (uint64_t)data, - }; - int err = do_cam_control(fd, CAM_ACQUIRE_DEV, &cmd, sizeof(cmd)); - return err == 0 ? std::make_optional(cmd.dev_handle) : std::nullopt; -} - -int device_config(int fd, int32_t session_handle, int32_t dev_handle, uint64_t packet_handle) { - struct cam_config_dev_cmd cmd = { - .session_handle = session_handle, - .dev_handle = dev_handle, - .packet_handle = packet_handle, - }; - return do_cam_control(fd, CAM_CONFIG_DEV, &cmd, sizeof(cmd)); -} - -int device_control(int fd, int op_code, int session_handle, int dev_handle) { - // start stop and release are all the same - struct cam_start_stop_dev_cmd cmd { .session_handle = session_handle, .dev_handle = dev_handle }; - return do_cam_control(fd, op_code, &cmd, sizeof(cmd)); -} - -void *alloc_w_mmu_hdl(int video0_fd, int len, uint32_t *handle, int align, int flags, int mmu_hdl, int mmu_hdl2) { - struct cam_mem_mgr_alloc_cmd mem_mgr_alloc_cmd = {0}; - mem_mgr_alloc_cmd.len = len; - mem_mgr_alloc_cmd.align = align; - mem_mgr_alloc_cmd.flags = flags; - mem_mgr_alloc_cmd.num_hdl = 0; - if (mmu_hdl != 0) { - mem_mgr_alloc_cmd.mmu_hdls[0] = mmu_hdl; - mem_mgr_alloc_cmd.num_hdl++; - } - if (mmu_hdl2 != 0) { - mem_mgr_alloc_cmd.mmu_hdls[1] = mmu_hdl2; - mem_mgr_alloc_cmd.num_hdl++; - } - - do_cam_control(video0_fd, CAM_REQ_MGR_ALLOC_BUF, &mem_mgr_alloc_cmd, sizeof(mem_mgr_alloc_cmd)); - *handle = mem_mgr_alloc_cmd.out.buf_handle; - - void *ptr = NULL; - if (mem_mgr_alloc_cmd.out.fd > 0) { - ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, mem_mgr_alloc_cmd.out.fd, 0); - assert(ptr != MAP_FAILED); - } - - // LOGD("allocated: %x %d %llx mapped %p", mem_mgr_alloc_cmd.out.buf_handle, mem_mgr_alloc_cmd.out.fd, mem_mgr_alloc_cmd.out.vaddr, ptr); - - return ptr; -} - -void release(int video0_fd, uint32_t handle) { - struct cam_mem_mgr_release_cmd mem_mgr_release_cmd = {0}; - mem_mgr_release_cmd.buf_handle = handle; - - int ret = do_cam_control(video0_fd, CAM_REQ_MGR_RELEASE_BUF, &mem_mgr_release_cmd, sizeof(mem_mgr_release_cmd)); - assert(ret == 0); -} - -void release_fd(int video0_fd, uint32_t handle) { - // handle to fd - close(handle>>16); - release(video0_fd, handle); -} - -void *MemoryManager::alloc_buf(int size, uint32_t *handle) { - lock.lock(); - void *ptr; - if (!cached_allocations[size].empty()) { - ptr = cached_allocations[size].front(); - cached_allocations[size].pop(); - *handle = handle_lookup[ptr]; - } else { - ptr = alloc_w_mmu_hdl(video0_fd, size, handle); - handle_lookup[ptr] = *handle; - size_lookup[ptr] = size; - } - lock.unlock(); - memset(ptr, 0, size); - return ptr; -} - -void MemoryManager::free(void *ptr) { - lock.lock(); - cached_allocations[size_lookup[ptr]].push(ptr); - lock.unlock(); -} - -MemoryManager::~MemoryManager() { - for (auto& x : cached_allocations) { - while (!x.second.empty()) { - void *ptr = x.second.front(); - x.second.pop(); - LOGD("freeing cached allocation %p with size %d", ptr, size_lookup[ptr]); - munmap(ptr, size_lookup[ptr]); - release_fd(video0_fd, handle_lookup[ptr]); - handle_lookup.erase(ptr); - size_lookup.erase(ptr); - } - } -} diff --git a/system/camerad/cameras/camera_util.h b/system/camerad/cameras/camera_util.h deleted file mode 100644 index 891ce3e793a5b8..00000000000000 --- a/system/camerad/cameras/camera_util.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include - -std::optional device_acquire(int fd, int32_t session_handle, void *data, uint32_t num_resources=1); -int device_config(int fd, int32_t session_handle, int32_t dev_handle, uint64_t packet_handle); -int device_control(int fd, int op_code, int session_handle, int dev_handle); -int do_cam_control(int fd, int op_code, void *handle, int size); -void *alloc_w_mmu_hdl(int video0_fd, int len, uint32_t *handle, int align = 8, int flags = CAM_MEM_FLAG_KMD_ACCESS | CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_CMD_BUF_TYPE, - int mmu_hdl = 0, int mmu_hdl2 = 0); -void release(int video0_fd, uint32_t handle); - -class MemoryManager { - public: - void init(int _video0_fd) { video0_fd = _video0_fd; } - ~MemoryManager(); - - template - auto alloc(int len, uint32_t *handle) { - return std::unique_ptr>((T*)alloc_buf(len, handle), [this](void *ptr) { this->free(ptr); }); - } - - private: - void *alloc_buf(int len, uint32_t *handle); - void free(void *ptr); - - std::mutex lock; - std::map handle_lookup; - std::map size_lookup; - std::map > cached_allocations; - int video0_fd; -}; diff --git a/system/camerad/cameras/cdm.cc b/system/camerad/cameras/cdm.cc new file mode 100644 index 00000000000000..8a070fa3aad82c --- /dev/null +++ b/system/camerad/cameras/cdm.cc @@ -0,0 +1,47 @@ +#include "cdm.h" +#include "stddef.h" + +int write_dmi(uint8_t *dst, uint64_t *addr, uint32_t length, uint32_t dmi_addr, uint8_t sel, uint8_t opcode) { + struct cdm_dmi_cmd *cmd = (struct cdm_dmi_cmd*)dst; + cmd->cmd = opcode; + cmd->length = length - 1; + cmd->reserved = 0; + cmd->addr = 0; // gets patched in + cmd->DMIAddr = dmi_addr; + cmd->DMISel = sel; + + *addr = (uint64_t)(dst + offsetof(struct cdm_dmi_cmd, addr)); + return sizeof(struct cdm_dmi_cmd); +} + +int write_cont(uint8_t *dst, uint32_t reg, const std::vector &vals) { + struct cdm_regcontinuous_cmd *cmd = (struct cdm_regcontinuous_cmd*)dst; + cmd->cmd = CAM_CDM_CMD_REG_CONT; + cmd->count = vals.size(); + cmd->offset = reg; + cmd->reserved0 = 0; + cmd->reserved1 = 0; + + uint32_t *vd = (uint32_t*)(dst + sizeof(struct cdm_regcontinuous_cmd)); + for (int i = 0; i < vals.size(); i++) { + *vd = vals[i]; + vd++; + } + + return sizeof(struct cdm_regcontinuous_cmd) + vals.size()*sizeof(uint32_t); +} + +int write_random(uint8_t *dst, const std::vector &vals) { + struct cdm_regrandom_cmd *cmd = (struct cdm_regrandom_cmd*)dst; + cmd->cmd = CAM_CDM_CMD_REG_RANDOM; + cmd->count = vals.size() / 2; + cmd->reserved = 0; + + uint32_t *vd = (uint32_t*)(dst + sizeof(struct cdm_regrandom_cmd)); + for (int i = 0; i < vals.size(); i++) { + *vd = vals[i]; + vd++; + } + + return sizeof(struct cdm_regrandom_cmd) + vals.size()*sizeof(uint32_t); +} diff --git a/system/camerad/cameras/cdm.h b/system/camerad/cameras/cdm.h new file mode 100644 index 00000000000000..d9640cee3e5327 --- /dev/null +++ b/system/camerad/cameras/cdm.h @@ -0,0 +1,79 @@ +#pragma once + +#include +#include +#include +#include +#include + +// from drivers/media/platform/msm/camera/cam_cdm/cam_cdm_util.{c,h} + +enum cam_cdm_command { + CAM_CDM_CMD_UNUSED = 0x0, + CAM_CDM_CMD_DMI = 0x1, + CAM_CDM_CMD_NOT_DEFINED = 0x2, + CAM_CDM_CMD_REG_CONT = 0x3, + CAM_CDM_CMD_REG_RANDOM = 0x4, + CAM_CDM_CMD_BUFF_INDIRECT = 0x5, + CAM_CDM_CMD_GEN_IRQ = 0x6, + CAM_CDM_CMD_WAIT_EVENT = 0x7, + CAM_CDM_CMD_CHANGE_BASE = 0x8, + CAM_CDM_CMD_PERF_CTRL = 0x9, + CAM_CDM_CMD_DMI_32 = 0xa, + CAM_CDM_CMD_DMI_64 = 0xb, + CAM_CDM_CMD_PRIVATE_BASE = 0xc, + CAM_CDM_CMD_SWD_DMI_32 = (CAM_CDM_CMD_PRIVATE_BASE + 0x64), + CAM_CDM_CMD_SWD_DMI_64 = (CAM_CDM_CMD_PRIVATE_BASE + 0x65), + CAM_CDM_CMD_PRIVATE_BASE_MAX = 0x7F +}; + +// our helpers +int write_random(uint8_t *dst, const std::vector &vals); +int write_cont(uint8_t *dst, uint32_t reg, const std::vector &vals); +int write_dmi(uint8_t *dst, uint64_t *addr, uint32_t length, uint32_t dmi_addr, uint8_t sel, uint8_t opcode = CAM_CDM_CMD_DMI_32); + +/** + * struct cdm_regrandom_cmd - Definition for CDM random register command. + * @count: Number of register writes + * @reserved: reserved bits + * @cmd: Command ID (CDMCmd) + */ +struct cdm_regrandom_cmd { + unsigned int count : 16; + unsigned int reserved : 8; + unsigned int cmd : 8; +} __attribute__((__packed__)); + +/** + * struct cdm_regcontinuous_cmd - Definition for a CDM register range command. + * @count: Number of register writes + * @reserved0: reserved bits + * @cmd: Command ID (CDMCmd) + * @offset: Start address of the range of registers + * @reserved1: reserved bits + */ +struct cdm_regcontinuous_cmd { + unsigned int count : 16; + unsigned int reserved0 : 8; + unsigned int cmd : 8; + unsigned int offset : 24; + unsigned int reserved1 : 8; +} __attribute__((__packed__)); + +/** + * struct cdm_dmi_cmd - Definition for a CDM DMI command. + * @length: Number of bytes in LUT - 1 + * @reserved: reserved bits + * @cmd: Command ID (CDMCmd) + * @addr: Address of the LUT in memory + * @DMIAddr: Address of the target DMI config register + * @DMISel: DMI identifier + */ +struct cdm_dmi_cmd { + unsigned int length : 16; + unsigned int reserved : 8; + unsigned int cmd : 8; + unsigned int addr; + unsigned int DMIAddr : 24; + unsigned int DMISel : 8; +} __attribute__((__packed__)); diff --git a/system/camerad/cameras/hw.h b/system/camerad/cameras/hw.h new file mode 100644 index 00000000000000..defe878e89ad19 --- /dev/null +++ b/system/camerad/cameras/hw.h @@ -0,0 +1,72 @@ +#pragma once + +#include "common/util.h" +#include "cereal/gen/cpp/log.capnp.h" +#include "msgq/visionipc/visionipc_server.h" + +#include "media/cam_isp_ife.h" + + +typedef enum { + ISP_RAW_OUTPUT, // raw frame from sensor + ISP_IFE_PROCESSED, // fully processed image through the IFE + ISP_BPS_PROCESSED, // fully processed image through the BPS +} SpectraOutputType; + +// For the comma 3X three camera platform + +struct CameraConfig { + int camera_num; + VisionStreamType stream_type; + float focal_len; // millimeters + const char *publish_name; + cereal::FrameData::Builder (cereal::Event::Builder::*init_camera_state)(); + bool enabled; + uint32_t phy; + bool vignetting_correction; + SpectraOutputType output_type; + bool staggered_sof; // SOF is staggered (half-period offset) from other cameras +}; + +// NOTE: to be able to disable road and wide road, we still have to configure the sensor over i2c +// If you don't do this, the strobe GPIO is an output (even in reset it seems!) +const CameraConfig WIDE_ROAD_CAMERA_CONFIG = { + .camera_num = 0, + .stream_type = VISION_STREAM_WIDE_ROAD, + .focal_len = 1.71, + .publish_name = "wideRoadCameraState", + .init_camera_state = &cereal::Event::Builder::initWideRoadCameraState, + .enabled = !getenv("DISABLE_WIDE_ROAD"), + .phy = CAM_ISP_IFE_IN_RES_PHY_0, + .vignetting_correction = false, + .output_type = ISP_IFE_PROCESSED, + .staggered_sof = false, +}; + +const CameraConfig ROAD_CAMERA_CONFIG = { + .camera_num = 1, + .stream_type = VISION_STREAM_ROAD, + .focal_len = 8.0, + .publish_name = "roadCameraState", + .init_camera_state = &cereal::Event::Builder::initRoadCameraState, + .enabled = !getenv("DISABLE_ROAD"), + .phy = CAM_ISP_IFE_IN_RES_PHY_1, + .vignetting_correction = true, + .output_type = ISP_IFE_PROCESSED, + .staggered_sof = false, +}; + +const CameraConfig DRIVER_CAMERA_CONFIG = { + .camera_num = 2, + .stream_type = VISION_STREAM_DRIVER, + .focal_len = 1.71, + .publish_name = "driverCameraState", + .init_camera_state = &cereal::Event::Builder::initDriverCameraState, + .enabled = !getenv("DISABLE_DRIVER"), + .phy = CAM_ISP_IFE_IN_RES_PHY_2, + .vignetting_correction = false, + .output_type = ISP_BPS_PROCESSED, + .staggered_sof = true, +}; + +const CameraConfig ALL_CAMERA_CONFIGS[] = {WIDE_ROAD_CAMERA_CONFIG, ROAD_CAMERA_CONFIG, DRIVER_CAMERA_CONFIG}; diff --git a/system/camerad/cameras/ife.h b/system/camerad/cameras/ife.h new file mode 100644 index 00000000000000..fd87d2baa4a742 --- /dev/null +++ b/system/camerad/cameras/ife.h @@ -0,0 +1,236 @@ +#pragma once + +#include "cdm.h" + +#include "system/camerad/cameras/hw.h" +#include "system/camerad/sensors/sensor.h" + +int build_common_ife_bps(uint8_t *dst, const CameraConfig cam, const SensorInfo *s, std::vector &patches, bool ife) { + uint8_t *start = dst; + + /* + Common between IFE and BPS. + */ + + // IFE -> BPS addresses + /* + std::map addrs = { + {0xf30, 0x3468}, + }; + */ + + // YUV + dst += write_cont(dst, ife ? 0xf30 : 0x3468, { + 0x00680208, + 0x00000108, + 0x00400000, + 0x03ff0000, + 0x01c01ed8, + 0x00001f68, + 0x02000000, + 0x03ff0000, + 0x1fb81e88, + 0x000001c0, + 0x02000000, + 0x03ff0000, + }); + + return dst - start; +} + +int build_update(uint8_t *dst, const CameraConfig cam, const SensorInfo *s, std::vector &patches) { + uint8_t *start = dst; + + // init sequence + dst += write_random(dst, { + 0x2c, 0xffffffff, + 0x30, 0xffffffff, + 0x34, 0xffffffff, + 0x38, 0xffffffff, + 0x3c, 0xffffffff, + }); + + // demux cfg + dst += write_cont(dst, 0x560, { + 0x00000001, + 0x04440444, + 0x04450445, + 0x04440444, + 0x04450445, + 0x000000ca, + 0x0000009c, + }); + + // white balance + dst += write_cont(dst, 0x6fc, { + 0x00800080, + 0x00000080, + 0x00000000, + 0x00000000, + }); + + // module config/enables (e.g. enable debayer, white balance, etc.) + dst += write_cont(dst, 0x40, { + 0x00000c06 | ((uint32_t)(cam.vignetting_correction) << 8), + }); + dst += write_cont(dst, 0x44, { + 0x00000000, + }); + dst += write_cont(dst, 0x48, { + (1 << 3) | (1 << 1), + }); + dst += write_cont(dst, 0x4c, { + 0x00000019, + }); + dst += write_cont(dst, 0xf00, { + 0x00000000, + }); + + // cropping + dst += write_cont(dst, 0xe0c, { + 0x00000e00, + }); + dst += write_cont(dst, 0xe2c, { + 0x00000e00, + }); + + // black level scale + offset + dst += write_cont(dst, 0x6b0, { + ((uint32_t)(1 << 11) << 0xf) | (s->black_level << (14 - s->bits_per_pixel)), + 0x0, + 0x0, + }); + + return dst - start; +} + + +int build_initial_config(uint8_t *dst, const CameraConfig cam, const SensorInfo *s, std::vector &patches, uint32_t out_width, uint32_t out_height) { + uint8_t *start = dst; + + // start with the every frame config + dst += build_update(dst, cam, s, patches); + + uint64_t addr; + + // setup + dst += write_cont(dst, 0x478, { + 0x00000004, + 0x004000c0, + }); + dst += write_cont(dst, 0x488, { + 0x00000000, + 0x00000000, + 0x00000f0f, + }); + dst += write_cont(dst, 0x49c, { + 0x00000001, + }); + dst += write_cont(dst, 0xce4, { + 0x00000000, + 0x00000000, + }); + + // linearization + dst += write_cont(dst, 0x4dc, { + 0x00000000, + }); + dst += write_cont(dst, 0x4e0, s->linearization_pts); + dst += write_cont(dst, 0x4f0, s->linearization_pts); + dst += write_cont(dst, 0x500, s->linearization_pts); + dst += write_cont(dst, 0x510, s->linearization_pts); + // TODO: this is DMI64 in the dump, does that matter? + dst += write_dmi(dst, &addr, s->linearization_lut.size()*sizeof(uint32_t), 0xc24, 9); + patches.push_back(addr - (uint64_t)start); + + // vignetting correction + dst += write_cont(dst, 0x6bc, { + 0x0b3c0000, + 0x00670067, + 0xd3b1300c, + 0x13b1300c, + }); + dst += write_cont(dst, 0x6d8, { + 0xec4e4000, + 0x0100c003, + }); + dst += write_dmi(dst, &addr, s->vignetting_lut.size()*sizeof(uint32_t), 0xc24, 14); // GRR + patches.push_back(addr - (uint64_t)start); + dst += write_dmi(dst, &addr, s->vignetting_lut.size()*sizeof(uint32_t), 0xc24, 15); // GBB + patches.push_back(addr - (uint64_t)start); + + // debayer + dst += write_cont(dst, 0x6f8, { + 0x00000100, + }); + dst += write_cont(dst, 0x71c, { + 0x00008000, + 0x08000066, + }); + + // color correction + dst += write_cont(dst, 0x760, s->color_correct_matrix); + + // gamma + dst += write_cont(dst, 0x798, { + 0x00000000, + }); + dst += write_dmi(dst, &addr, s->gamma_lut_rgb.size()*sizeof(uint32_t), 0xc24, 26); // G + patches.push_back(addr - (uint64_t)start); + dst += write_dmi(dst, &addr, s->gamma_lut_rgb.size()*sizeof(uint32_t), 0xc24, 28); // B + patches.push_back(addr - (uint64_t)start); + dst += write_dmi(dst, &addr, s->gamma_lut_rgb.size()*sizeof(uint32_t), 0xc24, 30); // R + patches.push_back(addr - (uint64_t)start); + + // output size/scaling + dst += write_cont(dst, 0xa3c, { + 0x00000003, + ((out_width - 1) << 16) | (s->frame_width - 1), + 0x30036666, + 0x00000000, + 0x00000000, + s->frame_width - 1, + ((out_height - 1) << 16) | (s->frame_height - 1), + 0x30036666, + 0x00000000, + 0x00000000, + s->frame_height - 1, + }); + dst += write_cont(dst, 0xa68, { + 0x00000003, + ((out_width / 2 - 1) << 16) | (s->frame_width - 1), + 0x3006cccc, + 0x00000000, + 0x00000000, + s->frame_width - 1, + ((out_height / 2 - 1) << 16) | (s->frame_height - 1), + 0x3006cccc, + 0x00000000, + 0x00000000, + s->frame_height - 1, + }); + + // cropping + dst += write_cont(dst, 0xe10, { + out_height - 1, + out_width - 1, + }); + dst += write_cont(dst, 0xe30, { + out_height / 2 - 1, + out_width - 1, + }); + dst += write_cont(dst, 0xe18, { + 0x0ff00000, + 0x00000016, + }); + dst += write_cont(dst, 0xe38, { + 0x0ff00000, + 0x00000017, + }); + + dst += build_common_ife_bps(dst, cam, s, patches, true); + + return dst - start; +} + + diff --git a/system/camerad/cameras/nv12_info.h b/system/camerad/cameras/nv12_info.h new file mode 100644 index 00000000000000..c0460caee33d25 --- /dev/null +++ b/system/camerad/cameras/nv12_info.h @@ -0,0 +1,130 @@ +#pragma once + +#include +#include +#include + +// NV12 subset copied from media/msm_media_info.h. +#ifndef MSM_MEDIA_ALIGN +#define MSM_MEDIA_ALIGN(__sz, __align) (((__align) & ((__align) - 1)) ? \ + ((((__sz) + (__align) - 1) / (__align)) * (__align)) : \ + (((__sz) + (__align) - 1) & (~((__align) - 1)))) +#endif + +#ifndef MSM_MEDIA_MAX +#define MSM_MEDIA_MAX(__a, __b) ((__a) > (__b) ? (__a) : (__b)) +#endif + +enum color_fmts { + COLOR_FMT_NV12, +}; + +static inline unsigned int VENUS_EXTRADATA_SIZE(int width, int height) { + (void)height; + (void)width; + return 16 * 1024; +} + +static inline unsigned int VENUS_Y_STRIDE(int color_fmt, int width) { + unsigned int stride = 0; + if (!width) goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12: + stride = MSM_MEDIA_ALIGN(width, 128); + break; + default: + break; + } +invalid_input: + return stride; +} + +static inline unsigned int VENUS_UV_STRIDE(int color_fmt, int width) { + unsigned int stride = 0; + if (!width) goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12: + stride = MSM_MEDIA_ALIGN(width, 128); + break; + default: + break; + } +invalid_input: + return stride; +} + +static inline unsigned int VENUS_Y_SCANLINES(int color_fmt, int height) { + unsigned int sclines = 0; + if (!height) goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12: + sclines = MSM_MEDIA_ALIGN(height, 32); + break; + default: + break; + } +invalid_input: + return sclines; +} + +static inline unsigned int VENUS_UV_SCANLINES(int color_fmt, int height) { + unsigned int sclines = 0; + if (!height) goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12: + sclines = MSM_MEDIA_ALIGN((height + 1) >> 1, 16); + break; + default: + break; + } +invalid_input: + return sclines; +} + +static inline unsigned int VENUS_BUFFER_SIZE(int color_fmt, int width, int height) { + const unsigned int extra_size = VENUS_EXTRADATA_SIZE(width, height); + unsigned int size = 0; + unsigned int y_stride = 0, uv_stride = 0, y_sclines = 0, uv_sclines = 0; + + if (!width || !height) goto invalid_input; + + y_stride = VENUS_Y_STRIDE(color_fmt, width); + uv_stride = VENUS_UV_STRIDE(color_fmt, width); + y_sclines = VENUS_Y_SCANLINES(color_fmt, height); + uv_sclines = VENUS_UV_SCANLINES(color_fmt, height); + + switch (color_fmt) { + case COLOR_FMT_NV12: { + const unsigned int y_plane = y_stride * y_sclines; + const unsigned int uv_plane = uv_stride * uv_sclines + 4096; + size = y_plane + uv_plane + MSM_MEDIA_MAX(extra_size, 8 * y_stride); + size = MSM_MEDIA_ALIGN(size, 4096); + size += MSM_MEDIA_ALIGN(width, 512) * 512; + size = MSM_MEDIA_ALIGN(size, 4096); + break; + } + default: + break; + } +invalid_input: + return size; +} + +// Returns NV12 aligned (stride, y_height, uv_height, buffer_size) for the given frame dimensions. +inline std::tuple get_nv12_info(int width, int height) { + const uint32_t stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, width); + const uint32_t y_height = VENUS_Y_SCANLINES(COLOR_FMT_NV12, height); + const uint32_t uv_height = VENUS_UV_SCANLINES(COLOR_FMT_NV12, height); + const uint32_t size = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, width, height); + + // Sanity checks for NV12 format assumptions + assert(stride == VENUS_UV_STRIDE(COLOR_FMT_NV12, width)); + assert(y_height / 2 == uv_height); + assert((stride * y_height) % 0x1000 == 0); // uv_offset must be page-aligned + + return {stride, y_height, uv_height, size}; +} diff --git a/system/camerad/cameras/nv12_info.py b/system/camerad/cameras/nv12_info.py new file mode 100644 index 00000000000000..2cadc2936406db --- /dev/null +++ b/system/camerad/cameras/nv12_info.py @@ -0,0 +1,21 @@ +# Python version of system/camerad/cameras/nv12_info.h +# Calculations from media/msm_media_info.h (VENUS_BUFFER_SIZE) + +def align(val: int, alignment: int) -> int: + return ((val + alignment - 1) // alignment) * alignment + +def get_nv12_info(width: int, height: int) -> tuple[int, int, int, int]: + """Returns (stride, y_height, uv_height, buffer_size) for NV12 frame dimensions.""" + stride = align(width, 128) + y_height = align(height, 32) + uv_height = align(height // 2, 16) + + # VENUS_BUFFER_SIZE for NV12 + y_plane = stride * y_height + uv_plane = stride * uv_height + 4096 + size = y_plane + uv_plane + max(16 * 1024, 8 * stride) + size = align(size, 4096) + size += align(width, 512) * 512 # kernel padding for non-aligned frames + size = align(size, 4096) + + return stride, y_height, uv_height, size diff --git a/system/camerad/cameras/process_raw.cl b/system/camerad/cameras/process_raw.cl deleted file mode 100644 index 6f6612fab0328a..00000000000000 --- a/system/camerad/cameras/process_raw.cl +++ /dev/null @@ -1,238 +0,0 @@ -#include "ar0231_cl.h" -#include "ox03c10_cl.h" -#include "os04c10_cl.h" - -#define UV_WIDTH RGB_WIDTH / 2 -#define UV_HEIGHT RGB_HEIGHT / 2 - -#define RGB_TO_Y(r, g, b) ((((mul24(b, 13) + mul24(g, 65) + mul24(r, 33)) + 64) >> 7) + 16) -#define RGB_TO_U(r, g, b) ((mul24(b, 56) - mul24(g, 37) - mul24(r, 19) + 0x8080) >> 8) -#define RGB_TO_V(r, g, b) ((mul24(r, 56) - mul24(g, 47) - mul24(b, 9) + 0x8080) >> 8) -#define AVERAGE(x, y, z, w) ((convert_ushort(x) + convert_ushort(y) + convert_ushort(z) + convert_ushort(w) + 1) >> 1) - -#if defined(BGGR) - #define ROW_READ_ORDER (int[]){3, 2, 1, 0} - #define RGB_WRITE_ORDER (int[]){2, 3, 0, 1} -#else - #define ROW_READ_ORDER (int[]){0, 1, 2, 3} - #define RGB_WRITE_ORDER (int[]){0, 1, 2, 3} -#endif - -float get_vignetting_s(float r) { - if (r < 62500) { - return (1.0f + 0.0000008f*r); - } else if (r < 490000) { - return (0.9625f + 0.0000014f*r); - } else if (r < 1102500) { - return (1.26434f + 0.0000000000016f*r*r); - } else { - return (0.53503625f + 0.0000000000022f*r*r); - } -} - -int4 parse_12bit(uchar8 pvs) { - // lower bits scambled? - return (int4)(((int)pvs.s0<<4) + (pvs.s1>>4), - ((int)pvs.s2<<4) + (pvs.s4&0xF), - ((int)pvs.s3<<4) + (pvs.s4>>4), - ((int)pvs.s5<<4) + (pvs.s7&0xF)); -} - -int4 parse_10bit(uchar8 pvs, uchar ext, bool aligned) { - if (aligned) { - return (int4)(((int)pvs.s0 << 2) + (pvs.s1 & 0b00000011), - ((int)pvs.s2 << 2) + ((pvs.s6 & 0b11000000) / 64), - ((int)pvs.s3 << 2) + ((pvs.s6 & 0b00110000) / 16), - ((int)pvs.s4 << 2) + ((pvs.s6 & 0b00001100) / 4)); - } else { - return (int4)(((int)pvs.s0 << 2) + ((pvs.s3 & 0b00110000) / 16), - ((int)pvs.s1 << 2) + ((pvs.s3 & 0b00001100) / 4), - ((int)pvs.s2 << 2) + ((pvs.s3 & 0b00000011)), - ((int)pvs.s4 << 2) + ((ext & 0b11000000) / 64)); - } -} - -float get_k(float a, float b, float c, float d) { - return 2.0 - (fabs(a - b) + fabs(c - d)); -} - -__kernel void process_raw(const __global uchar * in, __global uchar * out, int expo_time) -{ - const int gid_x = get_global_id(0); - const int gid_y = get_global_id(1); - - // estimate vignetting - #if VIGNETTING - int gx = (gid_x*2 - RGB_WIDTH/2); - int gy = (gid_y*2 - RGB_HEIGHT/2); - const float vignette_factor = get_vignetting_s((gx*gx + gy*gy) / VIGNETTE_RSZ); - #else - const float vignette_factor = 1.0; - #endif - - const int row_before_offset = (gid_y == 0) ? 2 : 0; - const int row_after_offset = (gid_y == (RGB_HEIGHT/2 - 1)) ? 1 : 3; - - float3 rgb_tmp; - uchar3 rgb_out[4]; // output is 2x2 window - - // read offset - int start_idx; - #if BIT_DEPTH == 10 - bool aligned10; - if (gid_x % 2 == 0) { - aligned10 = true; - start_idx = (2 * gid_y - 1) * FRAME_STRIDE + (5 * gid_x / 2 - 2) + (FRAME_STRIDE * FRAME_OFFSET); - } else { - aligned10 = false; - start_idx = (2 * gid_y - 1) * FRAME_STRIDE + (5 * (gid_x - 1) / 2 + 1) + (FRAME_STRIDE * FRAME_OFFSET); - } - #else - start_idx = (2 * gid_y - 1) * FRAME_STRIDE + (3 * gid_x - 2) + (FRAME_STRIDE * FRAME_OFFSET); - #endif - - // read in 4 rows, 8 uchars each - uchar8 dat[4]; - // row_before - dat[0] = vload8(0, in + start_idx + FRAME_STRIDE*row_before_offset); - // row_0 - if (gid_x == 0 && gid_y == 0) { - // this wasn't a problem due to extra rows - dat[1] = vload8(0, in + start_idx + FRAME_STRIDE*1 + 2); - dat[1] = (uchar8)(0, 0, dat[1].s0, dat[1].s1, dat[1].s2, dat[1].s3, dat[1].s4, dat[1].s5); - } else { - dat[1] = vload8(0, in + start_idx + FRAME_STRIDE*1); - } - // row_1 - dat[2] = vload8(0, in + start_idx + FRAME_STRIDE*2); - // row_after - dat[3] = vload8(0, in + start_idx + FRAME_STRIDE*row_after_offset); - // need extra bit for 10-bit, 4 rows, 1 uchar each - #if BIT_DEPTH == 10 - uchar extra_dat[4]; - if (!aligned10) { - extra_dat[0] = in[start_idx + FRAME_STRIDE*row_before_offset + 8]; - extra_dat[1] = in[start_idx + FRAME_STRIDE*1 + 8]; - extra_dat[2] = in[start_idx + FRAME_STRIDE*2 + 8]; - extra_dat[3] = in[start_idx + FRAME_STRIDE*row_after_offset + 8]; - } - #endif - - // read odd rows for staggered second exposure - #if HDR_OFFSET > 0 - uchar8 short_dat[4]; - short_dat[0] = vload8(0, in + start_idx + FRAME_STRIDE*(row_before_offset+HDR_OFFSET/2) + FRAME_STRIDE/2); - short_dat[1] = vload8(0, in + start_idx + FRAME_STRIDE*(1+HDR_OFFSET/2) + FRAME_STRIDE/2); - short_dat[2] = vload8(0, in + start_idx + FRAME_STRIDE*(2+HDR_OFFSET/2) + FRAME_STRIDE/2); - short_dat[3] = vload8(0, in + start_idx + FRAME_STRIDE*(row_after_offset+HDR_OFFSET/2) + FRAME_STRIDE/2); - #if BIT_DEPTH == 10 - uchar short_extra_dat[4]; - if (!aligned10) { - short_extra_dat[0] = in[start_idx + FRAME_STRIDE*(row_before_offset+HDR_OFFSET/2) + FRAME_STRIDE/2 + 8]; - short_extra_dat[1] = in[start_idx + FRAME_STRIDE*(1+HDR_OFFSET/2) + FRAME_STRIDE/2 + 8]; - short_extra_dat[2] = in[start_idx + FRAME_STRIDE*(2+HDR_OFFSET/2) + FRAME_STRIDE/2 + 8]; - short_extra_dat[3] = in[start_idx + FRAME_STRIDE*(row_after_offset+HDR_OFFSET/2) + FRAME_STRIDE/2 + 8]; - } - #endif - #endif - - // parse into floats 0.0-1.0 - float4 v_rows[4]; - #if BIT_DEPTH == 10 - // for now it's always HDR - int4 parsed = parse_10bit(dat[0], extra_dat[0], aligned10); - int4 short_parsed = parse_10bit(short_dat[0], short_extra_dat[0], aligned10); - v_rows[ROW_READ_ORDER[0]] = normalize_pv_hdr(parsed, short_parsed, vignette_factor, expo_time); - parsed = parse_10bit(dat[1], extra_dat[1], aligned10); - short_parsed = parse_10bit(short_dat[1], short_extra_dat[1], aligned10); - v_rows[ROW_READ_ORDER[1]] = normalize_pv_hdr(parsed, short_parsed, vignette_factor, expo_time); - parsed = parse_10bit(dat[2], extra_dat[2], aligned10); - short_parsed = parse_10bit(short_dat[2], short_extra_dat[2], aligned10); - v_rows[ROW_READ_ORDER[2]] = normalize_pv_hdr(parsed, short_parsed, vignette_factor, expo_time); - parsed = parse_10bit(dat[3], extra_dat[3], aligned10); - short_parsed = parse_10bit(short_dat[3], short_extra_dat[3], aligned10); - v_rows[ROW_READ_ORDER[3]] = normalize_pv_hdr(parsed, short_parsed, vignette_factor, expo_time); - #else - // no HDR here - int4 parsed = parse_12bit(dat[0]); - v_rows[ROW_READ_ORDER[0]] = normalize_pv(parsed, vignette_factor); - parsed = parse_12bit(dat[1]); - v_rows[ROW_READ_ORDER[1]] = normalize_pv(parsed, vignette_factor); - parsed = parse_12bit(dat[2]); - v_rows[ROW_READ_ORDER[2]] = normalize_pv(parsed, vignette_factor); - parsed = parse_12bit(dat[3]); - v_rows[ROW_READ_ORDER[3]] = normalize_pv(parsed, vignette_factor); - #endif - - // mirror padding - if (gid_x == 0) { - v_rows[0].s0 = v_rows[0].s2; - v_rows[1].s0 = v_rows[1].s2; - v_rows[2].s0 = v_rows[2].s2; - v_rows[3].s0 = v_rows[3].s2; - } else if (gid_x == RGB_WIDTH/2 - 1) { - v_rows[0].s3 = v_rows[0].s1; - v_rows[1].s3 = v_rows[1].s1; - v_rows[2].s3 = v_rows[2].s1; - v_rows[3].s3 = v_rows[3].s1; - } - - // debayering - // a simplified version of https://opensignalprocessingjournal.com/contents/volumes/V6/TOSIGPJ-6-1/TOSIGPJ-6-1.pdf - const float k01 = get_k(v_rows[0].s0, v_rows[1].s1, v_rows[0].s2, v_rows[1].s1); - const float k02 = get_k(v_rows[0].s2, v_rows[1].s1, v_rows[2].s2, v_rows[1].s1); - const float k03 = get_k(v_rows[2].s0, v_rows[1].s1, v_rows[2].s2, v_rows[1].s1); - const float k04 = get_k(v_rows[0].s0, v_rows[1].s1, v_rows[2].s0, v_rows[1].s1); - rgb_tmp.x = (k02*v_rows[1].s2+k04*v_rows[1].s0)/(k02+k04); // R_G1 - rgb_tmp.y = v_rows[1].s1; // G1(R) - rgb_tmp.z = (k01*v_rows[0].s1+k03*v_rows[2].s1)/(k01+k03); // B_G1 - rgb_out[RGB_WRITE_ORDER[0]] = convert_uchar3_sat(apply_gamma(color_correct(clamp(rgb_tmp, 0.0, 1.0)), expo_time) * 255.0); - - const float k11 = get_k(v_rows[0].s1, v_rows[2].s1, v_rows[0].s3, v_rows[2].s3); - const float k12 = get_k(v_rows[0].s2, v_rows[1].s1, v_rows[1].s3, v_rows[2].s2); - const float k13 = get_k(v_rows[0].s1, v_rows[0].s3, v_rows[2].s1, v_rows[2].s3); - const float k14 = get_k(v_rows[0].s2, v_rows[1].s3, v_rows[2].s2, v_rows[1].s1); - rgb_tmp.x = v_rows[1].s2; // R - rgb_tmp.y = (k11*(v_rows[0].s2+v_rows[2].s2)*0.5+k13*(v_rows[1].s3+v_rows[1].s1)*0.5)/(k11+k13); // G_R - rgb_tmp.z = (k12*(v_rows[0].s3+v_rows[2].s1)*0.5+k14*(v_rows[0].s1+v_rows[2].s3)*0.5)/(k12+k14); // B_R - rgb_out[RGB_WRITE_ORDER[1]] = convert_uchar3_sat(apply_gamma(color_correct(clamp(rgb_tmp, 0.0, 1.0)), expo_time) * 255.0); - - const float k21 = get_k(v_rows[1].s0, v_rows[3].s0, v_rows[1].s2, v_rows[3].s2); - const float k22 = get_k(v_rows[1].s1, v_rows[2].s0, v_rows[2].s2, v_rows[3].s1); - const float k23 = get_k(v_rows[1].s0, v_rows[1].s2, v_rows[3].s0, v_rows[3].s2); - const float k24 = get_k(v_rows[1].s1, v_rows[2].s2, v_rows[3].s1, v_rows[2].s0); - rgb_tmp.x = (k22*(v_rows[1].s2+v_rows[3].s0)*0.5+k24*(v_rows[1].s0+v_rows[3].s2)*0.5)/(k22+k24); // R_B - rgb_tmp.y = (k21*(v_rows[1].s1+v_rows[3].s1)*0.5+k23*(v_rows[2].s2+v_rows[2].s0)*0.5)/(k21+k23); // G_B - rgb_tmp.z = v_rows[2].s1; // B - rgb_out[RGB_WRITE_ORDER[2]] = convert_uchar3_sat(apply_gamma(color_correct(clamp(rgb_tmp, 0.0, 1.0)), expo_time) * 255.0); - - const float k31 = get_k(v_rows[1].s1, v_rows[2].s2, v_rows[1].s3, v_rows[2].s2); - const float k32 = get_k(v_rows[1].s3, v_rows[2].s2, v_rows[3].s3, v_rows[2].s2); - const float k33 = get_k(v_rows[3].s1, v_rows[2].s2, v_rows[3].s3, v_rows[2].s2); - const float k34 = get_k(v_rows[1].s1, v_rows[2].s2, v_rows[3].s1, v_rows[2].s2); - rgb_tmp.x = (k31*v_rows[1].s2+k33*v_rows[3].s2)/(k31+k33); // R_G2 - rgb_tmp.y = v_rows[2].s2; // G2(B) - rgb_tmp.z = (k32*v_rows[2].s3+k34*v_rows[2].s1)/(k32+k34); // B_G2 - rgb_out[RGB_WRITE_ORDER[3]] = convert_uchar3_sat(apply_gamma(color_correct(clamp(rgb_tmp, 0.0, 1.0)), expo_time) * 255.0); - - // rgb2yuv(nv12) - uchar2 yy = (uchar2)( - RGB_TO_Y(rgb_out[0].s0, rgb_out[0].s1, rgb_out[0].s2), - RGB_TO_Y(rgb_out[1].s0, rgb_out[1].s1, rgb_out[1].s2) - ); - vstore2(yy, 0, out + mad24(gid_y * 2, YUV_STRIDE, gid_x * 2)); - yy = (uchar2)( - RGB_TO_Y(rgb_out[2].s0, rgb_out[2].s1, rgb_out[2].s2), - RGB_TO_Y(rgb_out[3].s0, rgb_out[3].s1, rgb_out[3].s2) - ); - vstore2(yy, 0, out + mad24(gid_y * 2 + 1, YUV_STRIDE, gid_x * 2)); - - const short ar = AVERAGE(rgb_out[0].s0, rgb_out[1].s0, rgb_out[2].s0, rgb_out[3].s0); - const short ag = AVERAGE(rgb_out[0].s1, rgb_out[1].s1, rgb_out[2].s1, rgb_out[3].s1); - const short ab = AVERAGE(rgb_out[0].s2, rgb_out[1].s2, rgb_out[2].s2, rgb_out[3].s2); - uchar2 uv = (uchar2)( - RGB_TO_U(ar, ag, ab), - RGB_TO_V(ar, ag, ab) - ); - vstore2(uv, 0, out + UV_OFFSET + mad24(gid_y, YUV_STRIDE, gid_x * 2)); -} diff --git a/system/camerad/cameras/spectra.cc b/system/camerad/cameras/spectra.cc new file mode 100644 index 00000000000000..0b5f5327f58a55 --- /dev/null +++ b/system/camerad/cameras/spectra.cc @@ -0,0 +1,1578 @@ +#include "cdm.h" + +#include +#include +#include +#include +#include + +#include "media/cam_defs.h" +#include "media/cam_isp.h" +#include "media/cam_icp.h" +#include "media/cam_isp_ife.h" +#include "media/cam_sync.h" + +#include "common/util.h" +#include "common/swaglog.h" +#include "system/camerad/cameras/ife.h" +#include "system/camerad/cameras/nv12_info.h" +#include "system/camerad/cameras/spectra.h" +#include "system/camerad/cameras/bps_blobs.h" + + +// ************** low level camera helpers **************** + +int do_cam_control(int fd, int op_code, void *handle, int size) { + struct cam_control camcontrol = {0}; + camcontrol.op_code = op_code; + camcontrol.handle = (uint64_t)handle; + if (size == 0) { + camcontrol.size = 8; + camcontrol.handle_type = CAM_HANDLE_MEM_HANDLE; + } else { + camcontrol.size = size; + camcontrol.handle_type = CAM_HANDLE_USER_POINTER; + } + + int ret = HANDLE_EINTR(ioctl(fd, VIDIOC_CAM_CONTROL, &camcontrol)); + if (ret == -1) { + LOGE("VIDIOC_CAM_CONTROL error: op_code %d - errno %d", op_code, errno); + } + return ret; +} + +int do_sync_control(int fd, uint32_t id, void *handle, uint32_t size) { + struct cam_private_ioctl_arg arg = { + .id = id, + .size = size, + .ioctl_ptr = (uint64_t)handle, + }; + int ret = HANDLE_EINTR(ioctl(fd, CAM_PRIVATE_IOCTL_CMD, &arg)); + + int32_t ioctl_result = static_cast(arg.result); + if (ret < 0) { + LOGE("CAM_SYNC error: id %u - errno %d - ret %d - ioctl_result %d", id, errno, ret, ioctl_result); + return ret; + } + if (ioctl_result != 0) { + LOGE("CAM_SYNC error: id %u - errno %d - ret %d - ioctl_result %d", id, errno, ret, ioctl_result); + return ioctl_result; + } + return ret; +} + +std::optional device_acquire(int fd, int32_t session_handle, void *data, uint32_t num_resources) { + struct cam_acquire_dev_cmd cmd = { + .session_handle = session_handle, + .handle_type = CAM_HANDLE_USER_POINTER, + .num_resources = (uint32_t)(data ? num_resources : 0), + .resource_hdl = (uint64_t)data, + }; + int err = do_cam_control(fd, CAM_ACQUIRE_DEV, &cmd, sizeof(cmd)); + return err == 0 ? std::make_optional(cmd.dev_handle) : std::nullopt; +} + +int device_config(int fd, int32_t session_handle, int32_t dev_handle, uint64_t packet_handle) { + struct cam_config_dev_cmd cmd = { + .session_handle = session_handle, + .dev_handle = dev_handle, + .packet_handle = packet_handle, + }; + return do_cam_control(fd, CAM_CONFIG_DEV, &cmd, sizeof(cmd)); +} + +int device_control(int fd, int op_code, int session_handle, int dev_handle) { + // start stop and release are all the same + struct cam_start_stop_dev_cmd cmd { .session_handle = session_handle, .dev_handle = dev_handle }; + return do_cam_control(fd, op_code, &cmd, sizeof(cmd)); +} + +void *alloc_w_mmu_hdl(int video0_fd, int len, uint32_t *handle, int align, int flags, int mmu_hdl, int mmu_hdl2) { + struct cam_mem_mgr_alloc_cmd mem_mgr_alloc_cmd = {0}; + mem_mgr_alloc_cmd.len = len; + mem_mgr_alloc_cmd.align = align; + mem_mgr_alloc_cmd.flags = flags; + mem_mgr_alloc_cmd.num_hdl = 0; + if (mmu_hdl != 0) { + mem_mgr_alloc_cmd.mmu_hdls[0] = mmu_hdl; + mem_mgr_alloc_cmd.num_hdl++; + } + if (mmu_hdl2 != 0) { + mem_mgr_alloc_cmd.mmu_hdls[1] = mmu_hdl2; + mem_mgr_alloc_cmd.num_hdl++; + } + + do_cam_control(video0_fd, CAM_REQ_MGR_ALLOC_BUF, &mem_mgr_alloc_cmd, sizeof(mem_mgr_alloc_cmd)); + *handle = mem_mgr_alloc_cmd.out.buf_handle; + + void *ptr = NULL; + if (mem_mgr_alloc_cmd.out.fd > 0) { + ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, mem_mgr_alloc_cmd.out.fd, 0); + assert(ptr != MAP_FAILED); + } + + // LOGD("allocated: %x %d %llx mapped %p", mem_mgr_alloc_cmd.out.buf_handle, mem_mgr_alloc_cmd.out.fd, mem_mgr_alloc_cmd.out.vaddr, ptr); + + return ptr; +} + +void release(int video0_fd, uint32_t handle) { + struct cam_mem_mgr_release_cmd mem_mgr_release_cmd = {0}; + mem_mgr_release_cmd.buf_handle = handle; + + int ret = do_cam_control(video0_fd, CAM_REQ_MGR_RELEASE_BUF, &mem_mgr_release_cmd, sizeof(mem_mgr_release_cmd)); + assert(ret == 0); +} + +static cam_cmd_power *power_set_wait(cam_cmd_power *power, int16_t delay_ms) { + cam_cmd_unconditional_wait *unconditional_wait = (cam_cmd_unconditional_wait *)((char *)power + (sizeof(struct cam_cmd_power) + (power->count - 1) * sizeof(struct cam_power_settings))); + unconditional_wait->cmd_type = CAMERA_SENSOR_CMD_TYPE_WAIT; + unconditional_wait->delay = delay_ms; + unconditional_wait->op_code = CAMERA_SENSOR_WAIT_OP_SW_UCND; + return (struct cam_cmd_power *)(unconditional_wait + 1); +} + +// *** MemoryManager *** + +void *MemoryManager::alloc_buf(int size, uint32_t *handle) { + void *ptr; + auto &cache = cached_allocations[size]; + if (!cache.empty()) { + ptr = cache.front(); + cache.pop(); + *handle = handle_lookup[ptr]; + } else { + ptr = alloc_w_mmu_hdl(video0_fd, size, handle); + handle_lookup[ptr] = *handle; + size_lookup[ptr] = size; + } + memset(ptr, 0, size); + return ptr; +} + +void MemoryManager::free(void *ptr) { + cached_allocations[size_lookup[ptr]].push(ptr); +} + +MemoryManager::~MemoryManager() { + for (auto& x : cached_allocations) { + while (!x.second.empty()) { + void *ptr = x.second.front(); + x.second.pop(); + LOGD("freeing cached allocation %p with size %d", ptr, size_lookup[ptr]); + munmap(ptr, size_lookup[ptr]); + + // release fd + close(handle_lookup[ptr] >> 16); + release(video0_fd, handle_lookup[ptr]); + + handle_lookup.erase(ptr); + size_lookup.erase(ptr); + } + } +} + +// *** SpectraMaster *** + +void SpectraMaster::init() { + LOG("-- Opening devices"); + // video0 is req_mgr, the target of many ioctls + video0_fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-soc:qcom_cam-req-mgr-video-index0", O_RDWR | O_NONBLOCK)); + assert(video0_fd >= 0); + LOGD("opened video0"); + + // video1 is cam_sync, the target of some ioctls + cam_sync_fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-cam_sync-video-index0", O_RDWR | O_NONBLOCK)); + assert(cam_sync_fd >= 0); + LOGD("opened video1 (cam_sync)"); + + // looks like there's only one of these + isp_fd = open_v4l_by_name_and_index("cam-isp"); + assert(isp_fd >= 0); + LOGD("opened isp %d", (int)isp_fd); + + icp_fd = open_v4l_by_name_and_index("cam-icp"); + assert(icp_fd >= 0); + LOGD("opened icp %d", (int)icp_fd); + + // query ISP for MMU handles + LOG("-- Query for MMU handles"); + struct cam_isp_query_cap_cmd isp_query_cap_cmd = {0}; + struct cam_query_cap_cmd query_cap_cmd = {0}; + query_cap_cmd.handle_type = 1; + query_cap_cmd.caps_handle = (uint64_t)&isp_query_cap_cmd; + query_cap_cmd.size = sizeof(isp_query_cap_cmd); + int ret = do_cam_control(isp_fd, CAM_QUERY_CAP, &query_cap_cmd, sizeof(query_cap_cmd)); + assert(ret == 0); + LOGD("using MMU handle: %x", isp_query_cap_cmd.device_iommu.non_secure); + LOGD("using MMU handle: %x", isp_query_cap_cmd.cdm_iommu.non_secure); + device_iommu = isp_query_cap_cmd.device_iommu.non_secure; + cdm_iommu = isp_query_cap_cmd.cdm_iommu.non_secure; + + // query ICP for MMU handles + struct cam_icp_query_cap_cmd icp_query_cap_cmd = {0}; + query_cap_cmd.caps_handle = (uint64_t)&icp_query_cap_cmd; + query_cap_cmd.size = sizeof(icp_query_cap_cmd); + ret = do_cam_control(icp_fd, CAM_QUERY_CAP, &query_cap_cmd, sizeof(query_cap_cmd)); + assert(ret == 0); + LOGD("using ICP MMU handle: %x", icp_query_cap_cmd.dev_iommu_handle.non_secure); + icp_device_iommu = icp_query_cap_cmd.dev_iommu_handle.non_secure; + + // subscribe + LOG("-- Subscribing"); + struct v4l2_event_subscription sub = {0}; + sub.type = V4L_EVENT_CAM_REQ_MGR_EVENT; + sub.id = V4L_EVENT_CAM_REQ_MGR_SOF_BOOT_TS; + ret = HANDLE_EINTR(ioctl(video0_fd, VIDIOC_SUBSCRIBE_EVENT, &sub)); + LOGD("req mgr subscribe: %d", ret); + + mem_mgr.init(video0_fd); +} + +// *** SpectraCamera *** + +SpectraCamera::SpectraCamera(SpectraMaster *master, const CameraConfig &config) + : m(master), + enabled(config.enabled), + cc(config) { + ife_buf_depth = VIPC_BUFFER_COUNT; + assert(ife_buf_depth < MAX_IFE_BUFS); +} + +SpectraCamera::~SpectraCamera() { + if (open) { + camera_close(); + } +} + +int SpectraCamera::clear_req_queue() { + // for "non-realtime" BPS + if (icp_dev_handle > 0) { + struct cam_flush_dev_cmd cmd = { + .session_handle = session_handle, + .dev_handle = icp_dev_handle, + .flush_type = CAM_FLUSH_TYPE_ALL, + }; + int err = do_cam_control(m->icp_fd, CAM_FLUSH_REQ, &cmd, sizeof(cmd)); + assert(err == 0); + LOGD("flushed bps: %d", err); + } + + // for "realtime" devices + struct cam_req_mgr_flush_info req_mgr_flush_request = {0}; + req_mgr_flush_request.session_hdl = session_handle; + req_mgr_flush_request.link_hdl = link_handle; + req_mgr_flush_request.flush_type = CAM_REQ_MGR_FLUSH_TYPE_ALL; + int ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_FLUSH_REQ, &req_mgr_flush_request, sizeof(req_mgr_flush_request)); + LOGD("flushed all req: %d", ret); // returns a "time until timeout" on clearing the workq + + for (int i = 0; i < MAX_IFE_BUFS; ++i) { + destroySyncObjectAt(i); + } + + return ret; +} + +void SpectraCamera::camera_open(VisionIpcServer *v) { + if (!openSensor()) { + return; + } + + if (!enabled) return; + + buf.out_img_width = sensor->frame_width / sensor->out_scale; + buf.out_img_height = (sensor->hdr_offset > 0 ? (sensor->frame_height - sensor->hdr_offset) / 2 : sensor->frame_height) / sensor->out_scale; + + // size is driven by all the HW that handles frames, + // the video encoder has certain alignment requirements in this case + std::tie(stride, y_height, uv_height, yuv_size) = get_nv12_info(buf.out_img_width, buf.out_img_height); + uv_offset = stride * y_height; + + open = true; + configISP(); + if (cc.output_type == ISP_BPS_PROCESSED) configICP(); + configCSIPHY(); + linkDevices(); + + LOGD("camera init %d", cc.camera_num); + buf.init(this, v, ife_buf_depth, cc.stream_type); + camera_map_bufs(); + clearAndRequeue(1); +} + +void SpectraCamera::sensors_start() { + if (!enabled) return; + LOGD("starting sensor %d", cc.camera_num); + sensors_i2c(sensor->start_reg_array.data(), sensor->start_reg_array.size(), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, sensor->data_word); +} + +void SpectraCamera::sensors_poke(int request_id) { + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet); + auto pkt = m->mem_mgr.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 0; + pkt->kmd_cmd_buf_index = -1; + pkt->header.size = size; + pkt->header.op_code = CAM_SENSOR_PACKET_OPCODE_SENSOR_NOP; + pkt->header.request_id = request_id; + + int ret = device_config(sensor_fd, session_handle, sensor_dev_handle, cam_packet_handle); + if (ret != 0) { + LOGE("** sensor %d FAILED poke, disabling", cc.camera_num); + enabled = false; + return; + } +} + +void SpectraCamera::sensors_i2c(const struct i2c_random_wr_payload* dat, int len, int op_code, bool data_word) { + // LOGD("sensors_i2c: %d", len); + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*1; + auto pkt = m->mem_mgr.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 1; + pkt->kmd_cmd_buf_index = -1; + pkt->header.size = size; + pkt->header.op_code = op_code; + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + + buf_desc[0].size = buf_desc[0].length = sizeof(struct i2c_rdwr_header) + len*sizeof(struct i2c_random_wr_payload); + buf_desc[0].type = CAM_CMD_BUF_I2C; + + auto i2c_random_wr = m->mem_mgr.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); + i2c_random_wr->header.count = len; + i2c_random_wr->header.op_code = 1; + i2c_random_wr->header.cmd_type = CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_WR; + i2c_random_wr->header.data_type = data_word ? CAMERA_SENSOR_I2C_TYPE_WORD : CAMERA_SENSOR_I2C_TYPE_BYTE; + i2c_random_wr->header.addr_type = CAMERA_SENSOR_I2C_TYPE_WORD; + memcpy(i2c_random_wr->random_wr_payload, dat, len*sizeof(struct i2c_random_wr_payload)); + + int ret = device_config(sensor_fd, session_handle, sensor_dev_handle, cam_packet_handle); + if (ret != 0) { + LOGE("** sensor %d FAILED i2c, disabling", cc.camera_num); + enabled = false; + return; + } +} + +int SpectraCamera::sensors_init() { + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*2; + auto pkt = m->mem_mgr.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 2; + pkt->kmd_cmd_buf_index = -1; + pkt->header.op_code = CSLDeviceTypeImageSensor | CAM_SENSOR_PACKET_OPCODE_SENSOR_PROBE; + pkt->header.size = size; + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + + buf_desc[0].size = buf_desc[0].length = sizeof(struct cam_cmd_i2c_info) + sizeof(struct cam_cmd_probe); + buf_desc[0].type = CAM_CMD_BUF_LEGACY; + auto i2c_info = m->mem_mgr.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); + auto probe = (struct cam_cmd_probe *)(i2c_info.get() + 1); + + probe->camera_id = cc.camera_num; + i2c_info->slave_addr = sensor->getSlaveAddress(cc.camera_num); + // 0(I2C_STANDARD_MODE) = 100khz, 1(I2C_FAST_MODE) = 400khz + //i2c_info->i2c_freq_mode = I2C_STANDARD_MODE; + i2c_info->i2c_freq_mode = I2C_FAST_MODE; + i2c_info->cmd_type = CAMERA_SENSOR_CMD_TYPE_I2C_INFO; + + probe->data_type = CAMERA_SENSOR_I2C_TYPE_WORD; + probe->addr_type = CAMERA_SENSOR_I2C_TYPE_WORD; + probe->op_code = 3; // don't care? + probe->cmd_type = CAMERA_SENSOR_CMD_TYPE_PROBE; + probe->reg_addr = sensor->probe_reg_addr; + probe->expected_data = sensor->probe_expected_data; + probe->data_mask = 0; + + //buf_desc[1].size = buf_desc[1].length = 148; + buf_desc[1].size = buf_desc[1].length = 196; + buf_desc[1].type = CAM_CMD_BUF_I2C; + auto power_settings = m->mem_mgr.alloc(buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle); + + // power on + struct cam_cmd_power *power = power_settings.get(); + power->count = 4; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; + power->power_settings[0].power_seq_type = 3; // clock?? + power->power_settings[1].power_seq_type = 1; // analog + power->power_settings[2].power_seq_type = 2; // digital + power->power_settings[3].power_seq_type = 8; // reset low + power = power_set_wait(power, 1); + + // set clock + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; + power->power_settings[0].power_seq_type = 0; + power->power_settings[0].config_val_low = sensor->mclk_frequency; + power = power_set_wait(power, 1); + + // reset high + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; + power->power_settings[0].power_seq_type = 8; + power->power_settings[0].config_val_low = 1; + // wait 650000 cycles @ 19.2 mhz = 33.8 ms + power = power_set_wait(power, 34); + + // probe happens here + + // disable clock + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; + power->power_settings[0].power_seq_type = 0; + power->power_settings[0].config_val_low = 0; + power = power_set_wait(power, 1); + + // reset high + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; + power->power_settings[0].power_seq_type = 8; + power->power_settings[0].config_val_low = 1; + power = power_set_wait(power, 1); + + // reset low + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; + power->power_settings[0].power_seq_type = 8; + power->power_settings[0].config_val_low = 0; + power = power_set_wait(power, 1); + + // power off + power->count = 3; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; + power->power_settings[0].power_seq_type = 2; + power->power_settings[1].power_seq_type = 1; + power->power_settings[2].power_seq_type = 3; + + int ret = do_cam_control(sensor_fd, CAM_SENSOR_PROBE_CMD, (void *)(uintptr_t)cam_packet_handle, 0); + LOGD("probing the sensor: %d", ret); + return ret; +} + +void add_patch(struct cam_packet *pkt, int32_t dst_hdl, uint32_t dst_offset, int32_t src_hdl, uint32_t src_offset) { + void *ptr = (char*)&pkt->payload + pkt->patch_offset; + struct cam_patch_desc *p = (struct cam_patch_desc *)((unsigned char*)ptr + sizeof(struct cam_patch_desc)*pkt->num_patches); + p->dst_buf_hdl = dst_hdl; + p->src_buf_hdl = src_hdl; + p->dst_offset = dst_offset; + p->src_offset = src_offset; + pkt->num_patches++; +}; + +void SpectraCamera::config_bps(int idx, int request_id) { + /* + Handles per-frame BPS config. + * BPS = Bayer Processing Segment + */ + + bool needs_downscale = sensor->out_scale > 1; + int num_io_cfgs = needs_downscale ? 3 : 2; + int num_patches = needs_downscale ? 14 : 12; + int size = sizeof(struct cam_packet) + sizeof(struct cam_cmd_buf_desc)*2 + sizeof(struct cam_buf_io_cfg)*num_io_cfgs; + size += sizeof(struct cam_patch_desc)*num_patches; + + uint32_t cam_packet_handle = 0; + auto pkt = m->mem_mgr.alloc(size, &cam_packet_handle); + + pkt->header.op_code = CSLDeviceTypeBPS | CAM_ICP_OPCODE_BPS_UPDATE; + pkt->header.request_id = request_id; + pkt->header.size = size; + + typedef struct { + struct { + uint32_t ptr[2]; + uint32_t unknown[2]; + } frames[9]; + + uint32_t unknown1; + uint32_t unknown2; + uint32_t unknown3; + uint32_t unknown4; + + uint32_t cdm_addr; + uint32_t cdm_size; + uint32_t settings_addr; + uint32_t striping_addr; + uint32_t cdm_addr2; + + uint32_t req_id; + uint64_t handle; + } bps_tmp; + + typedef struct { + uint32_t a; + uint32_t n; + unsigned base : 32; + unsigned unused : 12; + unsigned length : 20; + uint32_t p; + uint32_t u; + uint32_t h; + uint32_t b; + } cdm_tmp; + + // *** cmd buf *** + std::vector patches; + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + { + pkt->num_cmd_buf = 2; + pkt->kmd_cmd_buf_index = -1; + pkt->kmd_cmd_buf_offset = 0; + + buf_desc[0].meta_data = 0; + buf_desc[0].mem_handle = bps_cmd.handle; + buf_desc[0].type = CAM_CMD_BUF_FW; + buf_desc[0].offset = bps_cmd.aligned_size()*idx; + + buf_desc[0].length = sizeof(bps_tmp) + sizeof(cdm_tmp); + buf_desc[0].size = buf_desc[0].length; + + // rest gets patched in + bps_tmp *fp = (bps_tmp *)((unsigned char *)bps_cmd.ptr + buf_desc[0].offset); + memset(fp, 0, buf_desc[0].length); + fp->handle = (uint64_t)icp_dev_handle; + fp->cdm_size = bps_cdm_striping_bl.size; // this comes from the striping lib create call + fp->req_id = 0; // why always 0? + + cdm_tmp *pa = (cdm_tmp *)((unsigned char *)fp + sizeof(bps_tmp)); + pa->a = 0; + pa->n = 1; + pa->p = 20; // GENERIC + pa->u = 0; + pa->h = 0; + pa->b = 0; + pa->unused = 0; + pa->base = 0; // this gets patched + + int cdm_len = 0; + + if (bps_lin_reg.size() == 0) { + // set first knee pt to do BLC + uint32_t new_knee[8]; + new_knee[0] = sensor->black_level << (14 - sensor->bits_per_pixel); + for (int i = 0; i < 7; i++) { + uint32_t pts = sensor->linearization_pts[i / 2]; + new_knee[i + 1] = (i % 2 == 0) ? (pts >> 16) : (pts & 0xffff); + } + for (int i = 0; i < 4; i++) { + bps_lin_reg.push_back((new_knee[2*i + 1] << 16) | new_knee[2*i]); + } + } + + if (bps_ccm_reg.size() == 0) { + for (int i = 0; i < 3; i++) { + bps_ccm_reg.push_back(sensor->color_correct_matrix[i] | (sensor->color_correct_matrix[i+3] << 0x10)); + bps_ccm_reg.push_back(sensor->color_correct_matrix[i+6]); + } + } + + // white balance + cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x2868, { + 0x04000400, + 0x00000400, + 0x00000000, + 0x00000000, + }); + // debayer + cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x2878, { + 0x00000080, + 0x00800066, + }); + // linearization + cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x1868, bps_lin_reg); + cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x1878, bps_lin_reg); + cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x1888, bps_lin_reg); + cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x1898, bps_lin_reg); + uint64_t addr; + cdm_len += write_dmi((unsigned char *)bps_cdm_program_array.ptr + cdm_len, &addr, sensor->linearization_lut.size()*sizeof(uint32_t), 0x1808, 1, CAM_CDM_CMD_DMI); + patches.push_back(addr - (uint64_t)bps_cdm_program_array.ptr); + + // color correction + cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x2e68, bps_ccm_reg); + + // gamma + for (uint8_t ch = 1; ch <= 3; ch++) { + cdm_len += write_dmi((unsigned char *)bps_cdm_program_array.ptr + cdm_len, &addr, sensor->gamma_lut_rgb.size()*sizeof(uint32_t), 0x3208, ch, CAM_CDM_CMD_DMI); + patches.push_back(addr - (uint64_t)bps_cdm_program_array.ptr); + } + + cdm_len += build_common_ife_bps((unsigned char *)bps_cdm_program_array.ptr + cdm_len, cc, sensor.get(), patches, false); + + pa->length = cdm_len - 1; + + // *** second command *** + // parsed by cam_icp_packet_generic_blob_handler + struct isp_packet { + uint32_t header; + struct cam_icp_clk_bw_request clk; + } __attribute__((packed)) tmp; + tmp.header = CAM_ICP_CMD_GENERIC_BLOB_CLK; + tmp.header |= (sizeof(cam_icp_clk_bw_request)) << 8; + tmp.clk.budget_ns = 0x1fca058; + tmp.clk.frame_cycles = sensor->frame_width * sensor->frame_height; // matches striping lib pixelCount + tmp.clk.rt_flag = 0x0; + tmp.clk.uncompressed_bw = 0x38512180; + tmp.clk.compressed_bw = 0x38512180; + + buf_desc[1].size = sizeof(tmp); + buf_desc[1].offset = 0; + buf_desc[1].length = buf_desc[1].size - buf_desc[1].offset; + buf_desc[1].type = CAM_CMD_BUF_GENERIC; + buf_desc[1].meta_data = CAM_ICP_CMD_META_GENERIC_BLOB; + auto buf2 = m->mem_mgr.alloc(buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle); + memcpy(buf2.get(), &tmp, sizeof(tmp)); + } + + // *** io config *** + pkt->num_io_configs = num_io_cfgs; + pkt->io_configs_offset = sizeof(struct cam_cmd_buf_desc)*pkt->num_cmd_buf; + struct cam_buf_io_cfg *io_cfg = (struct cam_buf_io_cfg *)((char*)&pkt->payload + pkt->io_configs_offset); + { + // input frame + io_cfg[0].offsets[0] = 0; + io_cfg[0].mem_handle[0] = buf_handle_raw[idx]; + + io_cfg[0].planes[0] = (struct cam_plane_cfg){ + .width = sensor->frame_width, + .height = sensor->frame_height + sensor->extra_height, + .plane_stride = sensor->frame_stride, + .slice_height = sensor->frame_height + sensor->extra_height, + }; + io_cfg[0].format = sensor->mipi_format; + io_cfg[0].color_space = CAM_COLOR_SPACE_BASE; + io_cfg[0].color_pattern = 0x5; + io_cfg[0].bpp = (sensor->mipi_format == CAM_FORMAT_MIPI_RAW_10 ? 0xa : 0xc); + io_cfg[0].resource_type = CAM_ICP_BPS_INPUT_IMAGE; + io_cfg[0].fence = sync_objs_ife[idx]; + io_cfg[0].direction = CAM_BUF_INPUT; + io_cfg[0].subsample_pattern = 0x1; + io_cfg[0].framedrop_pattern = 0x1; + + // output frame + io_cfg[1].mem_handle[0] = buf_handle_yuv[idx]; + io_cfg[1].mem_handle[1] = buf_handle_yuv[idx]; + io_cfg[1].planes[0] = (struct cam_plane_cfg){ + .width = buf.out_img_width, + .height = buf.out_img_height, + .plane_stride = stride, + .slice_height = y_height, + }; + io_cfg[1].planes[1] = (struct cam_plane_cfg){ + .width = buf.out_img_width, + .height = buf.out_img_height / 2, + .plane_stride = stride, + .slice_height = uv_height, + }; + io_cfg[1].offsets[1] = ALIGNED_SIZE(io_cfg[1].planes[0].plane_stride*io_cfg[1].planes[0].slice_height, 0x1000); + assert(io_cfg[1].offsets[1] == uv_offset); + + io_cfg[1].format = CAM_FORMAT_NV12; // TODO: why is this 21 in the dump? should be 12 + io_cfg[1].color_space = CAM_COLOR_SPACE_BT601_FULL; + io_cfg[1].resource_type = needs_downscale ? CAM_ICP_BPS_OUTPUT_IMAGE_REG1 : CAM_ICP_BPS_OUTPUT_IMAGE_FULL; + io_cfg[1].fence = sync_objs_bps[idx]; + io_cfg[1].direction = CAM_BUF_OUTPUT; + io_cfg[1].subsample_pattern = 0x1; + io_cfg[1].framedrop_pattern = 0x1; + + if (needs_downscale) { + // downscaling needs a full res placeholder + uint32_t full_stride, full_y_h, full_uv_h, full_yuv_size; + std::tie(full_stride, full_y_h, full_uv_h, full_yuv_size) = get_nv12_info(sensor->frame_width, sensor->frame_height); + io_cfg[2].mem_handle[0] = bps_fullres_dummy.handle; + io_cfg[2].mem_handle[1] = bps_fullres_dummy.handle; + io_cfg[2].planes[0] = (struct cam_plane_cfg){ + .width = sensor->frame_width, + .height = sensor->frame_height, + .plane_stride = full_stride, + .slice_height = full_y_h, + }; + io_cfg[2].planes[1] = (struct cam_plane_cfg){ + .width = sensor->frame_width, + .height = sensor->frame_height / 2, + .plane_stride = full_stride, + .slice_height = full_uv_h, + }; + io_cfg[2].offsets[1] = ALIGNED_SIZE(full_stride * full_y_h, 0x1000); + io_cfg[2].format = CAM_FORMAT_NV12; + io_cfg[2].color_space = CAM_COLOR_SPACE_BT601_FULL; + io_cfg[2].resource_type = CAM_ICP_BPS_OUTPUT_IMAGE_FULL; + io_cfg[2].fence = sync_objs_bps[idx]; + io_cfg[2].direction = CAM_BUF_OUTPUT; + io_cfg[2].subsample_pattern = 0x1; + io_cfg[2].framedrop_pattern = 0x1; + } + } + + // *** patches *** + { + assert(patches.size() == 0 || patches.size() == 4); + pkt->patch_offset = sizeof(struct cam_cmd_buf_desc)*pkt->num_cmd_buf + sizeof(struct cam_buf_io_cfg)*pkt->num_io_configs; + + if (patches.size() > 0) { + // linearization LUT + add_patch(pkt.get(), bps_cdm_program_array.handle, patches[0], bps_linearization_lut.handle, 0); + // gamma LUTs + for (int i = 0; i < 3; i++) { + add_patch(pkt.get(), bps_cdm_program_array.handle, patches[i+1], bps_gamma_lut.handle, 0); + } + } + + // input frame + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[0].ptr[0]), buf_handle_raw[idx], 0); + + if (needs_downscale) { + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[0]), bps_fullres_dummy.handle, 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[1]), bps_fullres_dummy.handle, io_cfg[2].offsets[1]); + // output frame at REG1 + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[7].ptr[0]), buf_handle_yuv[idx], 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[7].ptr[1]), buf_handle_yuv[idx], io_cfg[1].offsets[1]); + } else { + // output frame at FULL + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[0]), buf_handle_yuv[idx], 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[1]), buf_handle_yuv[idx], io_cfg[1].offsets[1]); + } + + // rest of buffers + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, settings_addr), bps_iq.handle, 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, cdm_addr2), bps_cmd.handle, sizeof(bps_tmp)); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + 0xc8, bps_cdm_program_array.handle, 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, striping_addr), bps_striping.handle, 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, cdm_addr), bps_cdm_striping_bl.handle, 0); + } + + int ret = device_config(m->icp_fd, session_handle, icp_dev_handle, cam_packet_handle); + assert(ret == 0); +} + +void SpectraCamera::config_ife(int idx, int request_id, bool init) { + /* + Handles initial + per-frame IFE config. + * IFE = Image Front End + */ + int size = sizeof(struct cam_packet) + sizeof(struct cam_cmd_buf_desc)*2; + size += sizeof(struct cam_patch_desc)*10; + if (!init) { + size += sizeof(struct cam_buf_io_cfg); + } + + uint32_t cam_packet_handle = 0; + auto pkt = m->mem_mgr.alloc(size, &cam_packet_handle); + + if (!init) { + pkt->header.op_code = CSLDeviceTypeIFE | OpcodesIFEUpdate; // 0xf000001 + pkt->header.request_id = request_id; + } else { + pkt->header.op_code = CSLDeviceTypeIFE | OpcodesIFEInitialConfig; // 0xf000000 + pkt->header.request_id = 1; + } + pkt->header.size = size; + + // *** cmd buf *** + std::vector patches; + { + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + pkt->num_cmd_buf = 2; + + // *** first command *** + buf_desc[0].size = ife_cmd.size; + buf_desc[0].length = 0; + buf_desc[0].type = CAM_CMD_BUF_DIRECT; + buf_desc[0].meta_data = CAM_ISP_PACKET_META_COMMON; + buf_desc[0].mem_handle = ife_cmd.handle; + buf_desc[0].offset = ife_cmd.aligned_size()*idx; + + // stream of IFE register writes + bool is_raw = cc.output_type != ISP_IFE_PROCESSED; + if (!is_raw) { + if (init) { + buf_desc[0].length = build_initial_config((unsigned char*)ife_cmd.ptr + buf_desc[0].offset, cc, sensor.get(), patches, buf.out_img_width, buf.out_img_height); + } else { + buf_desc[0].length = build_update((unsigned char*)ife_cmd.ptr + buf_desc[0].offset, cc, sensor.get(), patches); + } + } + + pkt->kmd_cmd_buf_offset = buf_desc[0].length; + pkt->kmd_cmd_buf_index = 0; + + // *** second command *** + // parsed by cam_isp_packet_generic_blob_handler + struct isp_packet { + uint32_t type_0; + cam_isp_resource_hfr_config resource_hfr; + + uint32_t type_1; + cam_isp_clock_config clock; + uint64_t extra_rdi_hz[3]; + + uint32_t type_2; + cam_isp_bw_config bw; + struct cam_isp_bw_vote extra_rdi_vote[6]; + } __attribute__((packed)) tmp; + memset(&tmp, 0, sizeof(tmp)); + + tmp.type_0 = CAM_ISP_GENERIC_BLOB_TYPE_HFR_CONFIG; + tmp.type_0 |= sizeof(cam_isp_resource_hfr_config) << 8; + static_assert(sizeof(cam_isp_resource_hfr_config) == 0x20); + tmp.resource_hfr = { + .num_ports = 1, + .port_hfr_config[0] = { + .resource_type = static_cast(is_raw ? CAM_ISP_IFE_OUT_RES_RDI_0 : CAM_ISP_IFE_OUT_RES_FULL), + .subsample_pattern = 1, + .subsample_period = 0, + .framedrop_pattern = 1, + .framedrop_period = 0, + } + }; + + tmp.type_1 = CAM_ISP_GENERIC_BLOB_TYPE_CLOCK_CONFIG; + tmp.type_1 |= (sizeof(cam_isp_clock_config) + sizeof(tmp.extra_rdi_hz)) << 8; + static_assert((sizeof(cam_isp_clock_config) + sizeof(tmp.extra_rdi_hz)) == 0x38); + tmp.clock = { + .usage_type = 1, // dual mode + .num_rdi = 4, + .left_pix_hz = 404000000, + .right_pix_hz = 404000000, + .rdi_hz[0] = 404000000, + }; + + tmp.type_2 = CAM_ISP_GENERIC_BLOB_TYPE_BW_CONFIG; + tmp.type_2 |= (sizeof(cam_isp_bw_config) + sizeof(tmp.extra_rdi_vote)) << 8; + static_assert((sizeof(cam_isp_bw_config) + sizeof(tmp.extra_rdi_vote)) == 0xe0); + tmp.bw = { + .usage_type = 1, // dual mode + .num_rdi = 4, + .left_pix_vote = { + .resource_id = 0, + .cam_bw_bps = 450000000, + .ext_bw_bps = 450000000, + }, + .rdi_vote[0] = { + .resource_id = 0, + .cam_bw_bps = 8706200000, + .ext_bw_bps = 8706200000, + }, + }; + + static_assert(offsetof(struct isp_packet, type_2) == 0x60); + + buf_desc[1].size = sizeof(tmp); + buf_desc[1].offset = !init ? 0x60 : 0; + buf_desc[1].length = buf_desc[1].size - buf_desc[1].offset; + buf_desc[1].type = CAM_CMD_BUF_GENERIC; + buf_desc[1].meta_data = CAM_ISP_PACKET_META_GENERIC_BLOB_COMMON; + auto buf2 = m->mem_mgr.alloc(buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle); + memcpy(buf2.get(), &tmp, sizeof(tmp)); + } + + // *** io config *** + if (!init) { + // configure output frame + pkt->num_io_configs = 1; + pkt->io_configs_offset = sizeof(struct cam_cmd_buf_desc)*pkt->num_cmd_buf; + + struct cam_buf_io_cfg *io_cfg = (struct cam_buf_io_cfg *)((char*)&pkt->payload + pkt->io_configs_offset); + if (cc.output_type != ISP_IFE_PROCESSED) { + io_cfg[0].mem_handle[0] = buf_handle_raw[idx]; + io_cfg[0].planes[0] = (struct cam_plane_cfg){ + .width = sensor->frame_width, + .height = sensor->frame_height, + .plane_stride = sensor->frame_stride, + .slice_height = sensor->frame_height + sensor->extra_height, + }; + io_cfg[0].format = sensor->mipi_format; + io_cfg[0].color_space = CAM_COLOR_SPACE_BASE; + io_cfg[0].color_pattern = 0x5; + io_cfg[0].bpp = (sensor->mipi_format == CAM_FORMAT_MIPI_RAW_10 ? 0xa : 0xc); + io_cfg[0].resource_type = CAM_ISP_IFE_OUT_RES_RDI_0; + io_cfg[0].fence = sync_objs_ife[idx]; + io_cfg[0].direction = CAM_BUF_OUTPUT; + io_cfg[0].subsample_pattern = 0x1; + io_cfg[0].framedrop_pattern = 0x1; + } else { + io_cfg[0].mem_handle[0] = buf_handle_yuv[idx]; + io_cfg[0].mem_handle[1] = buf_handle_yuv[idx]; + io_cfg[0].planes[0] = (struct cam_plane_cfg){ + .width = buf.out_img_width, + .height = buf.out_img_height, + .plane_stride = stride, + .slice_height = y_height, + }; + io_cfg[0].planes[1] = (struct cam_plane_cfg){ + .width = buf.out_img_width, + .height = buf.out_img_height / 2, + .plane_stride = stride, + .slice_height = uv_height, + }; + io_cfg[0].offsets[1] = uv_offset; + io_cfg[0].format = CAM_FORMAT_NV12; + io_cfg[0].color_space = 0; + io_cfg[0].color_pattern = 0x0; + io_cfg[0].bpp = 0; + io_cfg[0].resource_type = CAM_ISP_IFE_OUT_RES_FULL; + io_cfg[0].fence = sync_objs_ife[idx]; + io_cfg[0].direction = CAM_BUF_OUTPUT; + io_cfg[0].subsample_pattern = 0x1; + io_cfg[0].framedrop_pattern = 0x1; + } + } + + // *** patches *** + // sets up the kernel driver to do address translation for the IFE + { + // order here corresponds to the one in build_initial_config + assert(patches.size() == 6 || patches.size() == 0); + + pkt->patch_offset = sizeof(struct cam_cmd_buf_desc)*pkt->num_cmd_buf + sizeof(struct cam_buf_io_cfg)*pkt->num_io_configs; + if (patches.size() > 0) { + // linearization LUT + add_patch(pkt.get(), ife_cmd.handle, patches[0], ife_linearization_lut.handle, 0); + + // vignetting correction LUTs + add_patch(pkt.get(), ife_cmd.handle, patches[1], ife_vignetting_lut.handle, 0); + add_patch(pkt.get(), ife_cmd.handle, patches[2], ife_vignetting_lut.handle, ife_vignetting_lut.size); + + // gamma LUTs + for (int i = 0; i < 3; i++) { + add_patch(pkt.get(), ife_cmd.handle, patches[i+3], ife_gamma_lut.handle, ife_gamma_lut.size*i); + } + } + } + + int ret = device_config(m->isp_fd, session_handle, isp_dev_handle, cam_packet_handle); + assert(ret == 0); +} + +void SpectraCamera::enqueue_frame(uint64_t request_id) { + int i = request_id % ife_buf_depth; + assert(sync_objs_ife[i] == 0); + + // create output fences + struct cam_sync_info sync_create = {0}; + strcpy(sync_create.name, "NodeOutputPortFence"); + int ret = do_sync_control(m->cam_sync_fd, CAM_SYNC_CREATE, &sync_create, sizeof(sync_create)); + if (ret != 0) { + LOGE("failed to create fence: %d %d", ret, sync_create.sync_obj); + } else { + sync_objs_ife[i] = sync_create.sync_obj; + } + + if (icp_dev_handle > 0) { + ret = do_cam_control(m->cam_sync_fd, CAM_SYNC_CREATE, &sync_create, sizeof(sync_create)); + if (ret != 0) { + LOGE("failed to create fence: %d %d", ret, sync_create.sync_obj); + } else { + sync_objs_bps[i] = sync_create.sync_obj; + } + } + + // schedule request with camera request manager + struct cam_req_mgr_sched_request req_mgr_sched_request = {0}; + req_mgr_sched_request.session_hdl = session_handle; + req_mgr_sched_request.link_hdl = link_handle; + req_mgr_sched_request.req_id = request_id; + ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_SCHED_REQ, &req_mgr_sched_request, sizeof(req_mgr_sched_request)); + if (ret != 0) { + LOGE("failed to schedule cam mgr request: %d %lu", ret, request_id); + } + + // poke sensor, must happen after schedule + sensors_poke(request_id); + + // submit request to IFE and BPS + config_ife(i, request_id); + if (cc.output_type == ISP_BPS_PROCESSED) config_bps(i, request_id); +} + +void SpectraCamera::destroySyncObjectAt(int index) { + auto destroy_sync_obj = [](int cam_sync_fd, int32_t &sync_obj) { + if (sync_obj == 0) return; + + struct cam_sync_info sync_destroy = {.sync_obj = sync_obj}; + int ret = do_sync_control(cam_sync_fd, CAM_SYNC_DESTROY, &sync_destroy, sizeof(sync_destroy)); + if (ret != 0) { + LOGE("Failed to destroy sync object: %d, sync_obj: %d", ret, sync_destroy.sync_obj); + } + + sync_obj = 0; // Reset the sync object to 0 + }; + + destroy_sync_obj(m->cam_sync_fd, sync_objs_ife[index]); + destroy_sync_obj(m->cam_sync_fd, sync_objs_bps[index]); +} + +void SpectraCamera::camera_map_bufs() { + int ret; + for (int i = 0; i < ife_buf_depth; i++) { + // map our VisionIPC bufs into ISP memory + struct cam_mem_mgr_map_cmd mem_mgr_map_cmd = {0}; + mem_mgr_map_cmd.flags = CAM_MEM_FLAG_HW_READ_WRITE; + mem_mgr_map_cmd.mmu_hdls[0] = m->device_iommu; + mem_mgr_map_cmd.num_hdl = 1; + if (icp_dev_handle > 0) { + mem_mgr_map_cmd.num_hdl = 2; + mem_mgr_map_cmd.mmu_hdls[1] = m->icp_device_iommu; + } + + if (cc.output_type != ISP_IFE_PROCESSED) { + // RAW bayer images + mem_mgr_map_cmd.fd = buf.camera_bufs_raw[i].fd; + ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_MAP_BUF, &mem_mgr_map_cmd, sizeof(mem_mgr_map_cmd)); + assert(ret == 0); + LOGD("map buf req: (fd: %d) 0x%x %d", buf.camera_bufs_raw[i].fd, mem_mgr_map_cmd.out.buf_handle, ret); + buf_handle_raw[i] = mem_mgr_map_cmd.out.buf_handle; + } + + if (cc.output_type != ISP_RAW_OUTPUT) { + // final processed images + VisionBuf *vb = buf.vipc_server->get_buffer(buf.stream_type, i); + mem_mgr_map_cmd.fd = vb->fd; + ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_MAP_BUF, &mem_mgr_map_cmd, sizeof(mem_mgr_map_cmd)); + LOGD("map buf req: (fd: %d) 0x%x %d", vb->fd, mem_mgr_map_cmd.out.buf_handle, ret); + buf_handle_yuv[i] = mem_mgr_map_cmd.out.buf_handle; + } + } +} + +bool SpectraCamera::openSensor() { + sensor_fd = open_v4l_by_name_and_index("cam-sensor-driver", cc.camera_num); + assert(sensor_fd >= 0); + LOGD("opened sensor for %d", cc.camera_num); + + LOGD("-- Probing sensor %d", cc.camera_num); + + auto init_sensor_lambda = [this](SensorInfo *s) { + sensor.reset(s); + return (sensors_init() == 0); + }; + + // Figure out which sensor we have + if (!init_sensor_lambda(new OS04C10) && + !init_sensor_lambda(new OX03C10)) { + LOGE("** sensor %d FAILED bringup, disabling", cc.camera_num); + enabled = false; + return false; + } + LOGD("-- Probing sensor %d success", cc.camera_num); + + // create session + struct cam_req_mgr_session_info session_info = {}; + int ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_CREATE_SESSION, &session_info, sizeof(session_info)); + LOGD("get session: %d 0x%X", ret, session_info.session_hdl); + session_handle = session_info.session_hdl; + + // access the sensor + LOGD("-- Accessing sensor"); + auto sensor_dev_handle_ = device_acquire(sensor_fd, session_handle, nullptr); + assert(sensor_dev_handle_); + sensor_dev_handle = *sensor_dev_handle_; + LOGD("acquire sensor dev"); + + LOG("-- Configuring sensor"); + sensors_i2c(sensor->init_reg_array.data(), sensor->init_reg_array.size(), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, sensor->data_word); + return true; +} + +void SpectraCamera::configISP() { + if (!enabled) return; + + struct cam_isp_in_port_info in_port_info = { + // ISP input to the CSID + .res_type = cc.phy, + .lane_type = CAM_ISP_LANE_TYPE_DPHY, + .lane_num = 4, + .lane_cfg = 0x3210, + + .vc = 0x0, + .dt = sensor->frame_data_type, + .format = sensor->mipi_format, + + .test_pattern = sensor->bayer_pattern, + .usage_type = 0x0, + + .left_start = 0, + .left_stop = sensor->frame_width - 1, + .left_width = sensor->frame_width, + + .right_start = 0, + .right_stop = sensor->frame_width - 1, + .right_width = sensor->frame_width, + + .line_start = sensor->frame_offset, + .line_stop = sensor->frame_height + sensor->frame_offset - 1, + .height = sensor->frame_height + sensor->frame_offset, + + .pixel_clk = 0x0, + .batch_size = 0x0, + .dsp_mode = CAM_ISP_DSP_MODE_NONE, + .hbi_cnt = 0x0, + .custom_csid = 0x0, + + // ISP outputs + .num_out_res = 0x1, + .data[0] = (struct cam_isp_out_port_info){ + .res_type = CAM_ISP_IFE_OUT_RES_FULL, + .format = CAM_FORMAT_NV12, + .width = buf.out_img_width, + .height = buf.out_img_height + sensor->extra_height, + .comp_grp_id = 0x0, .split_point = 0x0, .secure_mode = 0x0, + }, + }; + + if (cc.output_type != ISP_IFE_PROCESSED) { + in_port_info.line_start = 0; + in_port_info.line_stop = sensor->frame_height + sensor->extra_height - 1; + in_port_info.height = sensor->frame_height + sensor->extra_height; + + in_port_info.data[0].res_type = CAM_ISP_IFE_OUT_RES_RDI_0; + in_port_info.data[0].format = sensor->mipi_format; + } + + struct cam_isp_resource isp_resource = { + .resource_id = CAM_ISP_RES_ID_PORT, + .handle_type = CAM_HANDLE_USER_POINTER, + .res_hdl = (uint64_t)&in_port_info, + .length = sizeof(in_port_info), + }; + + auto isp_dev_handle_ = device_acquire(m->isp_fd, session_handle, &isp_resource); + assert(isp_dev_handle_); + isp_dev_handle = *isp_dev_handle_; + LOGD("acquire isp dev"); + + // allocate IFE memory, then configure it + ife_cmd.init(m, 67984, 0x20, false, m->device_iommu, m->cdm_iommu, ife_buf_depth); + if (cc.output_type == ISP_IFE_PROCESSED) { + assert(sensor->gamma_lut_rgb.size() == 64); + ife_gamma_lut.init(m, sensor->gamma_lut_rgb.size()*sizeof(uint32_t), 0x20, false, m->device_iommu, m->cdm_iommu, 3); // 3 for RGB + for (int i = 0; i < 3; i++) { + memcpy(ife_gamma_lut.ptr + ife_gamma_lut.size*i, sensor->gamma_lut_rgb.data(), ife_gamma_lut.size); + } + assert(sensor->linearization_lut.size() == 36); + ife_linearization_lut.init(m, sensor->linearization_lut.size()*sizeof(uint32_t), 0x20, false, m->device_iommu, m->cdm_iommu); + memcpy(ife_linearization_lut.ptr, sensor->linearization_lut.data(), ife_linearization_lut.size); + assert(sensor->vignetting_lut.size() == 221); + ife_vignetting_lut.init(m, sensor->vignetting_lut.size()*sizeof(uint32_t), 0x20, false, m->device_iommu, m->cdm_iommu, 2); + for (int i = 0; i < 2; i++) { + memcpy(ife_vignetting_lut.ptr + ife_vignetting_lut.size*i, sensor->vignetting_lut.data(), ife_vignetting_lut.size); + } + } + + config_ife(0, 1, true); +} + +void SpectraCamera::configICP() { + /* + Configures both the ICP and BPS. + */ + + int cfg_handle; + + uint32_t cfg_size = sizeof(bps_cfg[0]) / sizeof(bps_cfg[0][0]); + void *cfg = alloc_w_mmu_hdl(m->video0_fd, cfg_size, (uint32_t*)&cfg_handle, 0x1, + CAM_MEM_FLAG_HW_READ_WRITE | CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_HW_SHARED_ACCESS, + m->icp_device_iommu); + memcpy(cfg, bps_cfg[sensor->num()], cfg_size); + + struct cam_icp_acquire_dev_info icp_info = { + .scratch_mem_size = 0x0, + .dev_type = CAM_ICP_RES_TYPE_BPS, + .io_config_cmd_size = cfg_size, + .io_config_cmd_handle = cfg_handle, + .secure_mode = 0, + .num_out_res = 1, + .in_res = (struct cam_icp_res_info){ + .format = 0x9, // RAW MIPI + .width = sensor->frame_width, + .height = sensor->frame_height, + .fps = 20, + }, + .out_res[0] = (struct cam_icp_res_info){ + .format = 0x3, // YUV420NV12 + .width = buf.out_img_width, + .height = buf.out_img_height, + .fps = 20, + }, + }; + auto h = device_acquire(m->icp_fd, session_handle, &icp_info); + assert(h); + icp_dev_handle = *h; + LOGD("acquire icp dev"); + + release(m->video0_fd, cfg_handle); + + // BPS has a lot of buffers to init + bps_cmd.init(m, 464, 0x20, true, m->icp_device_iommu, 0, ife_buf_depth); + + // BPSIQSettings struct + uint32_t settings_size = sizeof(bps_settings[0]) / sizeof(bps_settings[0][0]); + bps_iq.init(m, settings_size, 0x20, true, m->icp_device_iommu); + memcpy(bps_iq.ptr, bps_settings[sensor->num()], settings_size); + + // for cdm register writes, just make it bigger than you need + bps_cdm_program_array.init(m, 0x1000, 0x20, true, m->icp_device_iommu); + + // striping lib output + uint32_t striping_size = sizeof(bps_striping_output[0]) / sizeof(bps_striping_output[0][0]); + bps_striping.init(m, striping_size, 0x20, true, m->icp_device_iommu); + memcpy(bps_striping.ptr, bps_striping_output[sensor->num()], striping_size); + + // used internally by the BPS, we just allocate it. + // size comes from the BPSStripingLib + bps_cdm_striping_bl.init(m, 0xcfe0, 0x20, true, m->icp_device_iommu); + + if (sensor->out_scale > 1) { + uint32_t full_stride, full_y_h, full_uv_h, full_yuv_size; + std::tie(full_stride, full_y_h, full_uv_h, full_yuv_size) = get_nv12_info(sensor->frame_width, sensor->frame_height); + bps_fullres_dummy.init(m, full_yuv_size, 0x1000, true, m->icp_device_iommu); + } + + // LUTs + assert(sensor->linearization_lut.size() == 36); + bps_linearization_lut.init(m, sensor->linearization_lut.size()*sizeof(uint32_t), 0x20, true, m->icp_device_iommu); + + // bit shift linearization_lut to bps specs, also compensate for black level here + uint32_t bl = sensor->black_level << (14 - sensor->bits_per_pixel); + uint32_t* bps_lut = (uint32_t*)bps_linearization_lut.ptr; + for (size_t i = 0; i < sensor->linearization_lut.size(); i++) { + size_t seg = i / 4; + size_t ch = i % 4; + if (seg == 0) { + bps_lut[i] = 0; + continue; + } + uint32_t e = sensor->linearization_lut[(seg - 1) * 4 + ch]; + uint32_t base = e & 0x3fff; + uint32_t slope_q11 = (e >> 14) & 0x3fff; + uint32_t slope_q12 = std::min(slope_q11 << 1, 0x3fff); + base = (base > bl) ? (base - bl) : 0; + bps_lut[i] = base | (slope_q12 << 14); + } + + assert(sensor->gamma_lut_rgb.size() == 64); + bps_gamma_lut.init(m, sensor->gamma_lut_rgb.size()*sizeof(uint32_t), 0x20, true, m->icp_device_iommu); + memcpy(bps_gamma_lut.ptr, sensor->gamma_lut_rgb.data(), bps_gamma_lut.size); +} + +void SpectraCamera::configCSIPHY() { + csiphy_fd = open_v4l_by_name_and_index("cam-csiphy-driver", cc.camera_num); + assert(csiphy_fd >= 0); + LOGD("opened csiphy for %d", cc.camera_num); + + struct cam_csiphy_acquire_dev_info csiphy_acquire_dev_info = {.combo_mode = 0}; + auto csiphy_dev_handle_ = device_acquire(csiphy_fd, session_handle, &csiphy_acquire_dev_info); + assert(csiphy_dev_handle_); + csiphy_dev_handle = *csiphy_dev_handle_; + LOGD("acquire csiphy dev"); + + // config csiphy + LOG("-- Config CSI PHY"); + { + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*1; + auto pkt = m->mem_mgr.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 1; + pkt->kmd_cmd_buf_index = -1; + pkt->header.size = size; + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + + buf_desc[0].size = buf_desc[0].length = sizeof(struct cam_csiphy_info); + buf_desc[0].type = CAM_CMD_BUF_GENERIC; + + auto csiphy_info = m->mem_mgr.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); + csiphy_info->lane_mask = 0x1f; + csiphy_info->lane_assign = 0x3210;// skip clk. How is this 16 bit for 5 channels?? + csiphy_info->csiphy_3phase = 0x0; // no 3 phase, only 2 conductors per lane + csiphy_info->combo_mode = 0x0; + csiphy_info->lane_cnt = 0x4; + csiphy_info->secure_mode = 0x0; + csiphy_info->settle_time = MIPI_SETTLE_CNT * 200000000ULL; + csiphy_info->data_rate = 48000000; // Calculated by camera_freqs.py + + int ret_ = device_config(csiphy_fd, session_handle, csiphy_dev_handle, cam_packet_handle); + assert(ret_ == 0); + } +} + +void SpectraCamera::linkDevices() { + LOG("-- Link devices"); + struct cam_req_mgr_link_info req_mgr_link_info = {0}; + req_mgr_link_info.session_hdl = session_handle; + req_mgr_link_info.num_devices = 2; + req_mgr_link_info.dev_hdls[0] = isp_dev_handle; + req_mgr_link_info.dev_hdls[1] = sensor_dev_handle; + int ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_LINK, &req_mgr_link_info, sizeof(req_mgr_link_info)); + assert(ret == 0); + link_handle = req_mgr_link_info.link_hdl; + LOGD("link: %d session: 0x%X isp: 0x%X sensors: 0x%X link: 0x%X", ret, session_handle, isp_dev_handle, sensor_dev_handle, link_handle); + + struct cam_req_mgr_link_control req_mgr_link_control = {0}; + req_mgr_link_control.ops = CAM_REQ_MGR_LINK_ACTIVATE; + req_mgr_link_control.session_hdl = session_handle; + req_mgr_link_control.num_links = 1; + req_mgr_link_control.link_hdls[0] = link_handle; + ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_LINK_CONTROL, &req_mgr_link_control, sizeof(req_mgr_link_control)); + LOGD("link control: %d", ret); + + ret = device_control(csiphy_fd, CAM_START_DEV, session_handle, csiphy_dev_handle); + LOGD("start csiphy: %d", ret); + assert(ret == 0); + ret = device_control(m->isp_fd, CAM_START_DEV, session_handle, isp_dev_handle); + LOGD("start isp: %d", ret); + assert(ret == 0); + if (cc.output_type == ISP_BPS_PROCESSED) { + ret = device_control(m->icp_fd, CAM_START_DEV, session_handle, icp_dev_handle); + LOGD("start icp: %d", ret); + assert(ret == 0); + } +} + +void SpectraCamera::camera_close() { + LOG("-- Stop devices %d", cc.camera_num); + + if (enabled) { + clear_req_queue(); + + // ret = device_control(sensor_fd, CAM_STOP_DEV, session_handle, sensor_dev_handle); + // LOGD("stop sensor: %d", ret); + int ret = device_control(m->isp_fd, CAM_STOP_DEV, session_handle, isp_dev_handle); + LOGD("stop isp: %d", ret); + if (cc.output_type == ISP_BPS_PROCESSED) { + ret = device_control(m->icp_fd, CAM_STOP_DEV, session_handle, icp_dev_handle); + LOGD("stop icp: %d", ret); + } + ret = device_control(csiphy_fd, CAM_STOP_DEV, session_handle, csiphy_dev_handle); + LOGD("stop csiphy: %d", ret); + + // link control stop + LOG("-- Stop link control"); + struct cam_req_mgr_link_control req_mgr_link_control = {0}; + req_mgr_link_control.ops = CAM_REQ_MGR_LINK_DEACTIVATE; + req_mgr_link_control.session_hdl = session_handle; + req_mgr_link_control.num_links = 1; + req_mgr_link_control.link_hdls[0] = link_handle; + ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_LINK_CONTROL, &req_mgr_link_control, sizeof(req_mgr_link_control)); + LOGD("link control stop: %d", ret); + + // unlink + LOG("-- Unlink"); + struct cam_req_mgr_unlink_info req_mgr_unlink_info = {0}; + req_mgr_unlink_info.session_hdl = session_handle; + req_mgr_unlink_info.link_hdl = link_handle; + ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_UNLINK, &req_mgr_unlink_info, sizeof(req_mgr_unlink_info)); + LOGD("unlink: %d", ret); + + // release devices + LOGD("-- Release devices"); + ret = device_control(m->isp_fd, CAM_RELEASE_DEV, session_handle, isp_dev_handle); + LOGD("release isp: %d", ret); + if (cc.output_type == ISP_BPS_PROCESSED) { + ret = device_control(m->icp_fd, CAM_RELEASE_DEV, session_handle, icp_dev_handle); + LOGD("release icp: %d", ret); + } + ret = device_control(csiphy_fd, CAM_RELEASE_DEV, session_handle, csiphy_dev_handle); + LOGD("release csiphy: %d", ret); + + for (int i = 0; i < ife_buf_depth; i++) { + if (buf_handle_raw[i]) { + release(m->video0_fd, buf_handle_raw[i]); + } + if (buf_handle_yuv[i]) { + release(m->video0_fd, buf_handle_yuv[i]); + } + } + LOGD("released buffers"); + } + + int ret = device_control(sensor_fd, CAM_RELEASE_DEV, session_handle, sensor_dev_handle); + LOGD("release sensor: %d", ret); + + // destroyed session + struct cam_req_mgr_session_info session_info = {.session_hdl = session_handle}; + ret = do_cam_control(m->video0_fd, CAM_REQ_MGR_DESTROY_SESSION, &session_info, sizeof(session_info)); + LOGD("destroyed session %d: %d", cc.camera_num, ret); +} + +bool SpectraCamera::handle_camera_event(const cam_req_mgr_message *event_data) { + /* + Handles camera SOF event. Returns true if the frame is valid for publishing. + */ + + uint64_t request_id = event_data->u.frame_msg.request_id; // ID from the camera request manager + uint64_t frame_id_raw = event_data->u.frame_msg.frame_id; // raw as opposed to our re-indexed frame ID + uint64_t timestamp = event_data->u.frame_msg.timestamp; // timestamped in the kernel's SOF IRQ callback + //LOGD("handle cam %d ts %lu req id %lu frame id %lu", cc.camera_num, timestamp, request_id, frame_id_raw); + + // if there's a lag, some more frames could have already come in before + // we cleared the queue, so we'll still get them with valid (> 0) request IDs. + if (timestamp < last_requeue_ts) { + LOGD("skipping frame: ts before requeue / cam %d ts %lu req id %lu frame id %lu", cc.camera_num, timestamp, request_id, frame_id_raw); + return false; + } + + if (stress_test("skipping SOF event")) { + return false; + } + + if (!validateEvent(request_id, frame_id_raw)) { + return false; + } + + // Update tracking variables + if (request_id == request_id_last + 1) { + skip_expected = false; + } + frame_id_raw_last = frame_id_raw; + request_id_last = request_id; + + // Wait until frame's fully read out and processed + if (!waitForFrameReady(request_id)) { + // Reset queue on sync failure to prevent frame tearing + LOGE("camera %d sync failure %ld %ld ", cc.camera_num, request_id, frame_id_raw); + clearAndRequeue(request_id + 1); + return false; + } + + int buf_idx = request_id % ife_buf_depth; + bool ret = processFrame(buf_idx, request_id, frame_id_raw, timestamp); + destroySyncObjectAt(buf_idx); + enqueue_frame(request_id + ife_buf_depth); // request next frame for this slot + return ret; +} + +bool SpectraCamera::validateEvent(uint64_t request_id, uint64_t frame_id_raw) { + // check if the request ID is even valid. this happens after queued + // requests are cleared. unclear if it happens any other time. + if (request_id == 0) { + if (invalid_request_count++ > ife_buf_depth+2) { + LOGE("camera %d reset after half second of invalid requests", cc.camera_num); + clearAndRequeue(request_id_last + 1); + invalid_request_count = 0; + } + return false; + } + invalid_request_count = 0; + + // check for skips in frame_id or request_id + if (!skip_expected) { + if (frame_id_raw != frame_id_raw_last + 1) { + LOGE("camera %d frame ID skipped, %lu -> %lu", cc.camera_num, frame_id_raw_last, frame_id_raw); + clearAndRequeue(request_id + 1); + return false; + } + + if (request_id != request_id_last + 1) { + LOGE("camera %d requests skipped %ld -> %ld", cc.camera_num, request_id_last, request_id); + clearAndRequeue(request_id + 1); + return false; + } + } + return true; +} + +void SpectraCamera::clearAndRequeue(uint64_t from_request_id) { + // clear everything, then queue up a fresh set of frames + LOGW("clearing and requeuing camera %d from %lu", cc.camera_num, from_request_id); + clear_req_queue(); + last_requeue_ts = nanos_since_boot(); + for (uint64_t id = from_request_id; id < from_request_id + ife_buf_depth; ++id) { + enqueue_frame(id); + } + skip_expected = true; +} + +bool SpectraCamera::waitForFrameReady(uint64_t request_id) { + int buf_idx = request_id % ife_buf_depth; + assert(sync_objs_ife[buf_idx]); + + if (stress_test("sync sleep time")) { + util::sleep_for(350); + return false; + } + + auto waitForSync = [&](uint32_t sync_obj, int timeout_ms, const char *sync_type) { + double st = millis_since_boot(); + struct cam_sync_wait sync_wait = {}; + sync_wait.sync_obj = sync_obj; + sync_wait.timeout_ms = stress_test(sync_type) ? 1 : timeout_ms; + bool ret = do_sync_control(m->cam_sync_fd, CAM_SYNC_WAIT, &sync_wait, sizeof(sync_wait)) == 0; + double et = millis_since_boot(); + if (!ret) LOGE("camera %d %s failed after %.2fms", cc.camera_num, sync_type, et-st); + return ret; + }; + + // wait for frame from IFE + // - in RAW_OUTPUT mode, this time is just the frame readout from the sensor + // - in IFE_PROCESSED mode, this time also includes image processing (~1ms) + bool success = waitForSync(sync_objs_ife[buf_idx], 100, "IFE sync"); + if (success && sync_objs_bps[buf_idx]) { + // BPS is typically 7ms + success = waitForSync(sync_objs_bps[buf_idx], 50, "BPS sync"); + } + + return success; +} + +bool SpectraCamera::processFrame(int buf_idx, uint64_t request_id, uint64_t frame_id_raw, uint64_t timestamp) { + if (!syncFirstFrame(cc.camera_num, request_id, frame_id_raw, timestamp, cc.staggered_sof)) { + return false; + } + + // in IFE_PROCESSED mode, we can't know the true EOF, so recover it with sensor readout time + uint64_t timestamp_eof = timestamp + sensor->readout_time_ns; + + // Update buffer and frame data + buf.cur_buf_idx = buf_idx; + buf.cur_frame_data = { + .frame_id = (uint32_t)(frame_id_raw - camera_sync_data[cc.camera_num].frame_id_offset), + .request_id = (uint32_t)request_id, + .timestamp_sof = timestamp, + .timestamp_eof = timestamp_eof, + .processing_time = float((nanos_since_boot() - timestamp_eof) * 1e-9) + }; + return true; +} + +bool SpectraCamera::syncFirstFrame(int camera_id, uint64_t request_id, uint64_t raw_id, uint64_t timestamp, bool staggered) { + if (first_frame_synced) return true; + + // Store the frame data for this camera + camera_sync_data[camera_id] = SyncData{timestamp, raw_id + 1, staggered}; + + // Ensure all cameras are up + int enabled_camera_count = std::count_if(std::begin(ALL_CAMERA_CONFIGS), std::end(ALL_CAMERA_CONFIGS), + [](const auto &config) { return config.enabled; }); + bool all_cams_up = camera_sync_data.size() == enabled_camera_count; + + // Check that camera timestamps are properly aligned: + // - non-staggered cameras should be within 0.2ms of each other + // - staggered cameras should be within 0.2ms of a 25ms offset from non-staggered cameras + const uint64_t half_period_ns = 25 * 1000000ULL; // 25ms + const uint64_t tolerance_ns = 200000ULL; // 0.2ms + bool all_cams_synced = true; + for (const auto &[cam, sync_data] : camera_sync_data) { + if (cam == camera_id) continue; + uint64_t diff = std::max(timestamp, sync_data.timestamp) - + std::min(timestamp, sync_data.timestamp); + bool pair_staggered = staggered != sync_data.staggered; + uint64_t expected_offset = pair_staggered ? half_period_ns : 0; + uint64_t error = (diff > expected_offset) ? diff - expected_offset : expected_offset - diff; + if (error > tolerance_ns) { + all_cams_synced = false; + } + } + + if (all_cams_up && all_cams_synced) { + first_frame_synced = true; + for (const auto&[cam, sync_data] : camera_sync_data) { + LOGW("camera %d synced on frame_id_offset %ld timestamp %lu", cam, sync_data.frame_id_offset, sync_data.timestamp); + } + } + + // Timeout in case the timestamps never line up + if (raw_id > 40) { + LOGE("camera first frame sync timed out"); + first_frame_synced = true; + } + + return false; +} diff --git a/system/camerad/cameras/spectra.h b/system/camerad/cameras/spectra.h new file mode 100644 index 00000000000000..eb6d95af1ce273 --- /dev/null +++ b/system/camerad/cameras/spectra.h @@ -0,0 +1,245 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "media/cam_req_mgr.h" + +#include "common/util.h" +#include "common/swaglog.h" +#include "system/camerad/cameras/hw.h" +#include "system/camerad/cameras/camera_common.h" +#include "system/camerad/sensors/sensor.h" + +#define MAX_IFE_BUFS 20 + +const int MIPI_SETTLE_CNT = 33; // Calculated by camera_freqs.py + +// For use with the Titan 170 ISP in the SDM845 +// https://github.com/commaai/agnos-kernel-sdm845 + +// CSLDeviceType/CSLPacketOpcodesIFE from camx +// cam_packet_header.op_code = (device << 24) | (opcode); +#define CSLDeviceTypeImageSensor (0x01 << 24) +#define CSLDeviceTypeIFE (0x0F << 24) +#define CSLDeviceTypeBPS (0x10 << 24) +#define OpcodesIFEInitialConfig 0x0 +#define OpcodesIFEUpdate 0x1 + +// Sensor command values from the SDM845 kernel's private camera header: +// drivers/media/platform/msm/camera/cam_sensor_module/cam_sensor_utils/cam_sensor_cmn_header.h +// These are userspace-visible ioctl payload values, but Qualcomm did not export them through UAPI. +enum { + CAMERA_SENSOR_CMD_TYPE_PROBE = 1, + CAMERA_SENSOR_CMD_TYPE_PWR_UP = 2, + CAMERA_SENSOR_CMD_TYPE_PWR_DOWN = 3, + CAMERA_SENSOR_CMD_TYPE_I2C_INFO = 4, + CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_WR = 5, + CAMERA_SENSOR_CMD_TYPE_WAIT = 9, + + CAMERA_SENSOR_WAIT_OP_SW_UCND = 3, + + CAMERA_SENSOR_I2C_TYPE_BYTE = 1, + CAMERA_SENSOR_I2C_TYPE_WORD = 2, + + I2C_FAST_MODE = 1, + + CAM_SENSOR_PACKET_OPCODE_SENSOR_PROBE = 3, + CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG = 4, + CAM_SENSOR_PACKET_OPCODE_SENSOR_NOP = 127, +}; + +std::optional device_acquire(int fd, int32_t session_handle, void *data, uint32_t num_resources=1); +int device_config(int fd, int32_t session_handle, int32_t dev_handle, uint64_t packet_handle); +int device_control(int fd, int op_code, int session_handle, int dev_handle); +int do_cam_control(int fd, int op_code, void *handle, int size); +void *alloc_w_mmu_hdl(int video0_fd, int len, uint32_t *handle, int align = 8, int flags = CAM_MEM_FLAG_KMD_ACCESS | CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_CMD_BUF_TYPE, + int mmu_hdl = 0, int mmu_hdl2 = 0); +void release(int video0_fd, uint32_t handle); + +class MemoryManager { +public: + void init(int _video0_fd) { video0_fd = _video0_fd; } + ~MemoryManager(); + + template + auto alloc(int len, uint32_t *handle) { + return std::unique_ptr>((T*)alloc_buf(len, handle), [this](void *ptr) { this->free(ptr); }); + } + +private: + void *alloc_buf(int len, uint32_t *handle); + void free(void *ptr); + + std::map handle_lookup; + std::map size_lookup; + std::map > cached_allocations; + int video0_fd; +}; + +class SpectraMaster { +public: + void init(); + + unique_fd video0_fd; + unique_fd cam_sync_fd; + unique_fd isp_fd; + unique_fd icp_fd; + int device_iommu = -1; + int cdm_iommu = -1; + int icp_device_iommu = -1; + MemoryManager mem_mgr; +}; + +class SpectraBuf { +public: + SpectraBuf() = default; + + ~SpectraBuf() { + if (video_fd >= 0 && ptr) { + munmap(ptr, mmap_size); + release(video_fd, handle); + } + } + + void init(SpectraMaster *m, int s, int a, bool shared_access, int mmu_hdl = 0, int mmu_hdl2 = 0, int count = 1) { + video_fd = m->video0_fd; + size = s; + alignment = a; + mmap_size = aligned_size() * count; + + uint32_t flags = CAM_MEM_FLAG_HW_READ_WRITE | CAM_MEM_FLAG_KMD_ACCESS | CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_CMD_BUF_TYPE; + if (shared_access) { + flags |= CAM_MEM_FLAG_HW_SHARED_ACCESS; + } + + void *p = alloc_w_mmu_hdl(video_fd, mmap_size, (uint32_t*)&handle, alignment, flags, mmu_hdl, mmu_hdl2); + ptr = (unsigned char*)p; + assert(ptr != NULL); + }; + + uint32_t aligned_size() { + return ALIGNED_SIZE(size, alignment); + }; + + int video_fd = -1; + unsigned char *ptr = nullptr; + int size = 0, alignment = 0, handle = 0, mmap_size = 0; +}; + +class SpectraCamera { +public: + SpectraCamera(SpectraMaster *master, const CameraConfig &config); + ~SpectraCamera(); + + void camera_open(VisionIpcServer *v); + bool handle_camera_event(const cam_req_mgr_message *event_data); + void camera_close(); + void camera_map_bufs(); + void config_bps(int idx, int request_id); + void config_ife(int idx, int request_id, bool init=false); + + int clear_req_queue(); + void enqueue_frame(uint64_t request_id); + + int sensors_init(); + void sensors_start(); + void sensors_poke(int request_id); + void sensors_i2c(const struct i2c_random_wr_payload* dat, int len, int op_code, bool data_word); + + bool openSensor(); + void configISP(); + void configICP(); + void configCSIPHY(); + void linkDevices(); + void destroySyncObjectAt(int index); + + // *** state *** + + int ife_buf_depth = -1; + bool open = false; + bool enabled = true; + CameraConfig cc; + std::unique_ptr sensor; + + // YUV image size + uint32_t stride; + uint32_t y_height; + uint32_t uv_height; + uint32_t uv_offset; + uint32_t yuv_size; + + unique_fd sensor_fd; + unique_fd csiphy_fd; + + int32_t session_handle = -1; + int32_t sensor_dev_handle = -1; + int32_t isp_dev_handle = -1; + int32_t icp_dev_handle = -1; + int32_t csiphy_dev_handle = -1; + + int32_t link_handle = -1; + + SpectraBuf ife_cmd; + SpectraBuf ife_gamma_lut; + SpectraBuf ife_linearization_lut; + SpectraBuf ife_vignetting_lut; + + SpectraBuf bps_cmd; + SpectraBuf bps_cdm_buffer; + SpectraBuf bps_cdm_program_array; + SpectraBuf bps_cdm_striping_bl; + SpectraBuf bps_iq; + SpectraBuf bps_striping; + SpectraBuf bps_linearization_lut; + SpectraBuf bps_gamma_lut; + SpectraBuf bps_fullres_dummy; + std::vector bps_lin_reg; + std::vector bps_ccm_reg; + + int buf_handle_yuv[MAX_IFE_BUFS] = {}; + int buf_handle_raw[MAX_IFE_BUFS] = {}; + int sync_objs_ife[MAX_IFE_BUFS] = {}; + int sync_objs_bps[MAX_IFE_BUFS] = {}; + uint64_t request_id_last = 0; + uint64_t last_requeue_ts = 0; + uint64_t frame_id_raw_last = 0; + int invalid_request_count = 0; + bool skip_expected = true; + + CameraBuf buf; + SpectraMaster *m; + +private: + void clearAndRequeue(uint64_t from_request_id); + bool validateEvent(uint64_t request_id, uint64_t frame_id_raw); + bool waitForFrameReady(uint64_t request_id); + bool processFrame(int buf_idx, uint64_t request_id, uint64_t frame_id_raw, uint64_t timestamp); + static bool syncFirstFrame(int camera_id, uint64_t request_id, uint64_t raw_id, uint64_t timestamp, bool staggered); + struct SyncData { + uint64_t timestamp; + uint64_t frame_id_offset = 0; + bool staggered = false; + }; + inline static std::map camera_sync_data; + inline static bool first_frame_synced = false; + + // a mode for stressing edge cases: realignment, sync failures, etc. + inline bool stress_test(std::string log) { + static double last_trigger = 0; + static double prob = std::stod(util::getenv("SPECTRA_ERROR_PROB", "-1")); + static double dt = std::stod(util::getenv("SPECTRA_ERROR_DT", "1")); + bool triggered = (prob > 0) && \ + ((static_cast(rand()) / RAND_MAX) < prob) && \ + (millis_since_boot() - last_trigger) > dt; + if (triggered) { + last_trigger = millis_since_boot(); + LOGE("stress test (cam %d): %s", cc.camera_num, log.c_str()); + } + return triggered; + } +}; diff --git a/system/camerad/main.cc b/system/camerad/main.cc index b86b4f57ff737e..05fdef1a65c16a 100644 --- a/system/camerad/main.cc +++ b/system/camerad/main.cc @@ -4,17 +4,10 @@ #include "common/params.h" #include "common/util.h" -#include "system/hardware/hw.h" int main(int argc, char *argv[]) { - if (Hardware::PC()) { - printf("exiting, camerad is not meant to run on PC\n"); - return 0; - } - - int ret = util::set_realtime_priority(53); - assert(ret == 0); - ret = util::set_core_affinity({6}); + // doesn't need RT priority since we're using isolcpus + int ret = util::set_core_affinity({6}); assert(ret == 0 || Params().getBool("IsOffroad")); // failure ok while offroad due to offlining cores camerad_thread(); diff --git a/system/camerad/sensors/ar0231.cc b/system/camerad/sensors/ar0231.cc deleted file mode 100644 index 9b688389c4460b..00000000000000 --- a/system/camerad/sensors/ar0231.cc +++ /dev/null @@ -1,172 +0,0 @@ -#include - -#include "common/swaglog.h" -#include "system/camerad/cameras/camera_common.h" -#include "system/camerad/cameras/camera_qcom2.h" -#include "system/camerad/sensors/sensor.h" - -namespace { - -const size_t AR0231_REGISTERS_HEIGHT = 2; -// TODO: this extra height is universal and doesn't apply per camera -const size_t AR0231_STATS_HEIGHT = 2 + 8; - -const float sensor_analog_gains_AR0231[] = { - 1.0 / 8.0, 2.0 / 8.0, 2.0 / 7.0, 3.0 / 7.0, // 0, 1, 2, 3 - 3.0 / 6.0, 4.0 / 6.0, 4.0 / 5.0, 5.0 / 5.0, // 4, 5, 6, 7 - 5.0 / 4.0, 6.0 / 4.0, 6.0 / 3.0, 7.0 / 3.0, // 8, 9, 10, 11 - 7.0 / 2.0, 8.0 / 2.0, 8.0 / 1.0}; // 12, 13, 14, 15 = bypass - -std::map> ar0231_build_register_lut(CameraState *c, uint8_t *data) { - // This function builds a lookup table from register address, to a pair of indices in the - // buffer where to read this address. The buffer contains padding bytes, - // as well as markers to indicate the type of the next byte. - // - // 0xAA is used to indicate the MSB of the address, 0xA5 for the LSB of the address. - // Every byte of data (MSB and LSB) is preceded by 0x5A. Specifying an address is optional - // for contiguous ranges. See page 27-29 of the AR0231 Developer guide for more information. - - int max_i[] = {1828 / 2 * 3, 1500 / 2 * 3}; - auto get_next_idx = [](int cur_idx) { - return (cur_idx % 3 == 1) ? cur_idx + 2 : cur_idx + 1; // Every third byte is padding - }; - - std::map> registers; - for (int register_row = 0; register_row < 2; register_row++) { - uint8_t *registers_raw = data + c->ci->frame_stride * register_row; - assert(registers_raw[0] == 0x0a); // Start of line - - int value_tag_count = 0; - int first_val_idx = 0; - uint16_t cur_addr = 0; - - for (int i = 1; i <= max_i[register_row]; i = get_next_idx(get_next_idx(i))) { - int val_idx = get_next_idx(i); - - uint8_t tag = registers_raw[i]; - uint16_t val = registers_raw[val_idx]; - - if (tag == 0xAA) { // Register MSB tag - cur_addr = val << 8; - } else if (tag == 0xA5) { // Register LSB tag - cur_addr |= val; - cur_addr -= 2; // Next value tag will increment address again - } else if (tag == 0x5A) { // Value tag - - // First tag - if (value_tag_count % 2 == 0) { - cur_addr += 2; - first_val_idx = val_idx; - } else { - registers[cur_addr] = std::make_pair(first_val_idx + c->ci->frame_stride * register_row, val_idx + c->ci->frame_stride * register_row); - } - - value_tag_count++; - } - } - } - return registers; -} - -float ar0231_parse_temp_sensor(uint16_t calib1, uint16_t calib2, uint16_t data_reg) { - // See AR0231 Developer Guide - page 36 - float slope = (125.0 - 55.0) / ((float)calib1 - (float)calib2); - float t0 = 55.0 - slope * (float)calib2; - return t0 + slope * (float)data_reg; -} - -} // namespace - -AR0231::AR0231() { - image_sensor = cereal::FrameData::ImageSensor::AR0231; - pixel_size_mm = 0.003; - data_word = true; - frame_width = 1928; - frame_height = 1208; - frame_stride = (frame_width * 12 / 8) + 4; - extra_height = AR0231_REGISTERS_HEIGHT + AR0231_STATS_HEIGHT; - - registers_offset = 0; - frame_offset = AR0231_REGISTERS_HEIGHT; - stats_offset = AR0231_REGISTERS_HEIGHT + frame_height; - - start_reg_array.assign(std::begin(start_reg_array_ar0231), std::end(start_reg_array_ar0231)); - init_reg_array.assign(std::begin(init_array_ar0231), std::end(init_array_ar0231)); - probe_reg_addr = 0x3000; - probe_expected_data = 0x354; - mipi_format = CAM_FORMAT_MIPI_RAW_12; - frame_data_type = 0x12; // Changing stats to 0x2C doesn't work, so change pixels to 0x12 instead - mclk_frequency = 19200000; //Hz - - dc_gain_factor = 2.5; - dc_gain_min_weight = 0; - dc_gain_max_weight = 1; - dc_gain_on_grey = 0.2; - dc_gain_off_grey = 0.3; - exposure_time_min = 2; // with HDR, fastest ss - exposure_time_max = 0x0855; // with HDR, slowest ss, 40ms - analog_gain_min_idx = 0x1; // 0.25x - analog_gain_rec_idx = 0x6; // 0.8x - analog_gain_max_idx = 0xD; // 4.0x - analog_gain_cost_delta = 0; - analog_gain_cost_low = 0.1; - analog_gain_cost_high = 5.0; - for (int i = 0; i <= analog_gain_max_idx; i++) { - sensor_analog_gains[i] = sensor_analog_gains_AR0231[i]; - } - min_ev = exposure_time_min * sensor_analog_gains[analog_gain_min_idx]; - max_ev = exposure_time_max * dc_gain_factor * sensor_analog_gains[analog_gain_max_idx]; - target_grey_factor = 1.0; -} - -void AR0231::processRegisters(CameraState *c, cereal::FrameData::Builder &framed) const { - const uint8_t expected_preamble[] = {0x0a, 0xaa, 0x55, 0x20, 0xa5, 0x55}; - uint8_t *data = (uint8_t *)c->buf.cur_camera_buf->addr + c->ci->registers_offset; - - if (memcmp(data, expected_preamble, std::size(expected_preamble)) != 0) { - LOGE("unexpected register data found"); - return; - } - - if (ar0231_register_lut.empty()) { - ar0231_register_lut = ar0231_build_register_lut(c, data); - } - std::map registers; - for (uint16_t addr : {0x2000, 0x2002, 0x20b0, 0x20b2, 0x30c6, 0x30c8, 0x30ca, 0x30cc}) { - auto offset = ar0231_register_lut[addr]; - registers[addr] = ((uint16_t)data[offset.first] << 8) | data[offset.second]; - } - - uint32_t frame_id = ((uint32_t)registers[0x2000] << 16) | registers[0x2002]; - framed.setFrameIdSensor(frame_id); - - float temp_0 = ar0231_parse_temp_sensor(registers[0x30c6], registers[0x30c8], registers[0x20b0]); - float temp_1 = ar0231_parse_temp_sensor(registers[0x30ca], registers[0x30cc], registers[0x20b2]); - framed.setTemperaturesC({temp_0, temp_1}); -} - - -std::vector AR0231::getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const { - uint16_t analog_gain_reg = 0xFF00 | (new_exp_g << 4) | new_exp_g; - return { - {0x3366, analog_gain_reg}, - {0x3362, (uint16_t)(dc_gain_enabled ? 0x1 : 0x0)}, - {0x3012, (uint16_t)exposure_time}, - }; -} - -int AR0231::getSlaveAddress(int port) const { - assert(port >= 0 && port <= 2); - return (int[]){0x20, 0x30, 0x20}[port]; -} - -float AR0231::getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const { - // Cost of ev diff - float score = std::abs(desired_ev - (exp_t * exp_gain)) * 10; - // Cost of absolute gain - float m = exp_g_idx > analog_gain_rec_idx ? analog_gain_cost_high : analog_gain_cost_low; - score += std::abs(exp_g_idx - (int)analog_gain_rec_idx) * m; - // Cost of changing gain - score += std::abs(exp_g_idx - gain_idx) * (score + 1.0) / 10.0; - return score; -} diff --git a/system/camerad/sensors/ar0231_cl.h b/system/camerad/sensors/ar0231_cl.h deleted file mode 100644 index 8e96bbce5b6aad..00000000000000 --- a/system/camerad/sensors/ar0231_cl.h +++ /dev/null @@ -1,33 +0,0 @@ -#if SENSOR_ID == 1 - -#define BIT_DEPTH 12 -#define PV_MAX 4096 -#define BLACK_LVL 168 -#define VIGNETTE_RSZ 1.0f - -float4 normalize_pv(int4 parsed, float vignette_factor) { - float4 pv = (convert_float4(parsed) - BLACK_LVL) / (PV_MAX - BLACK_LVL); - return clamp(pv*vignette_factor, 0.0, 1.0); -} - -float3 color_correct(float3 rgb) { - float3 corrected = rgb.x * (float3)(1.82717181, -0.31231438, 0.07307673); - corrected += rgb.y * (float3)(-0.5743977, 1.36858544, -0.53183455); - corrected += rgb.z * (float3)(-0.25277411, -0.05627105, 1.45875782); - return corrected; -} - -float3 apply_gamma(float3 rgb, int expo_time) { - // tone mapping params - const float gamma_k = 0.75; - const float gamma_b = 0.125; - const float mp = 0.01; // ideally midpoint should be adaptive - const float rk = 9 - 100*mp; - - // poly approximation for s curve - return (rgb > mp) ? - ((rk * (rgb-mp) * (1-(gamma_k*mp+gamma_b)) * (1+1/(rk*(1-mp))) / (1+rk*(rgb-mp))) + gamma_k*mp + gamma_b) : - ((rk * (rgb-mp) * (gamma_k*mp+gamma_b) * (1+1/(rk*mp)) / (1-rk*(rgb-mp))) + gamma_k*mp + gamma_b); -} - -#endif \ No newline at end of file diff --git a/system/camerad/sensors/ar0231_registers.h b/system/camerad/sensors/ar0231_registers.h deleted file mode 100644 index 6c4c251e8ea11a..00000000000000 --- a/system/camerad/sensors/ar0231_registers.h +++ /dev/null @@ -1,119 +0,0 @@ -#pragma once - -const struct i2c_random_wr_payload start_reg_array_ar0231[] = {{0x301A, 0x91C}}; -const struct i2c_random_wr_payload stop_reg_array_ar0231[] = {{0x301A, 0x918}}; - -const struct i2c_random_wr_payload init_array_ar0231[] = { - {0x301A, 0x0018}, // RESET_REGISTER - - // CLOCK Settings - // input clock is 19.2 / 2 * 0x37 = 528 MHz - // pixclk is 528 / 6 = 88 MHz - // full roll time is 1000/(PIXCLK/(LINE_LENGTH_PCK*FRAME_LENGTH_LINES)) = 39.99 ms - // img roll time is 1000/(PIXCLK/(LINE_LENGTH_PCK*Y_OUTPUT_CONTROL)) = 22.85 ms - {0x302A, 0x0006}, // VT_PIX_CLK_DIV - {0x302C, 0x0001}, // VT_SYS_CLK_DIV - {0x302E, 0x0002}, // PRE_PLL_CLK_DIV - {0x3030, 0x0037}, // PLL_MULTIPLIER - {0x3036, 0x000C}, // OP_PIX_CLK_DIV - {0x3038, 0x0001}, // OP_SYS_CLK_DIV - - // FORMAT - {0x3040, 0xC000}, // READ_MODE - {0x3004, 0x0000}, // X_ADDR_START_ - {0x3008, 0x0787}, // X_ADDR_END_ - {0x3002, 0x0000}, // Y_ADDR_START_ - {0x3006, 0x04B7}, // Y_ADDR_END_ - {0x3032, 0x0000}, // SCALING_MODE - {0x30A2, 0x0001}, // X_ODD_INC_ - {0x30A6, 0x0001}, // Y_ODD_INC_ - {0x3402, 0x0788}, // X_OUTPUT_CONTROL - {0x3404, 0x04B8}, // Y_OUTPUT_CONTROL - {0x3064, 0x1982}, // SMIA_TEST - {0x30BA, 0x11F2}, // DIGITAL_CTRL - - // Enable external trigger and disable GPIO outputs - {0x30CE, 0x0120}, // SLAVE_SH_SYNC_MODE | FRAME_START_MODE - {0x340A, 0xE0}, // GPIO3_INPUT_DISABLE | GPIO2_INPUT_DISABLE | GPIO1_INPUT_DISABLE - {0x340C, 0x802}, // GPIO_HIDRV_EN | GPIO0_ISEL=2 - - // Readout timing - {0x300C, 0x0672}, // LINE_LENGTH_PCK (valid for 3-exposure HDR) - {0x300A, 0x0855}, // FRAME_LENGTH_LINES - {0x3042, 0x0000}, // EXTRA_DELAY - - // Readout Settings - {0x31AE, 0x0204}, // SERIAL_FORMAT, 4-lane MIPI - {0x31AC, 0x0C0C}, // DATA_FORMAT_BITS, 12 -> 12 - {0x3342, 0x1212}, // MIPI_F1_PDT_EDT - {0x3346, 0x1212}, // MIPI_F2_PDT_EDT - {0x334A, 0x1212}, // MIPI_F3_PDT_EDT - {0x334E, 0x1212}, // MIPI_F4_PDT_EDT - {0x3344, 0x0011}, // MIPI_F1_VDT_VC - {0x3348, 0x0111}, // MIPI_F2_VDT_VC - {0x334C, 0x0211}, // MIPI_F3_VDT_VC - {0x3350, 0x0311}, // MIPI_F4_VDT_VC - {0x31B0, 0x0053}, // FRAME_PREAMBLE - {0x31B2, 0x003B}, // LINE_PREAMBLE - {0x301A, 0x001C}, // RESET_REGISTER - - // Noise Corrections - {0x3092, 0x0C24}, // ROW_NOISE_CONTROL - {0x337A, 0x0C80}, // DBLC_SCALE0 - {0x3370, 0x03B1}, // DBLC - {0x3044, 0x0400}, // DARK_CONTROL - - // Enable temperature sensor - {0x30B4, 0x0007}, // TEMPSENS0_CTRL_REG - {0x30B8, 0x0007}, // TEMPSENS1_CTRL_REG - - // Enable dead pixel correction using - // the 1D line correction scheme - {0x31E0, 0x0003}, - - // HDR Settings - {0x3082, 0x0004}, // OPERATION_MODE_CTRL - {0x3238, 0x0444}, // EXPOSURE_RATIO - - {0x1008, 0x0361}, // FINE_INTEGRATION_TIME_MIN - {0x100C, 0x0589}, // FINE_INTEGRATION_TIME2_MIN - {0x100E, 0x07B1}, // FINE_INTEGRATION_TIME3_MIN - {0x1010, 0x0139}, // FINE_INTEGRATION_TIME4_MIN - - // TODO: do these have to be lower than LINE_LENGTH_PCK? - {0x3014, 0x08CB}, // FINE_INTEGRATION_TIME_ - {0x321E, 0x0894}, // FINE_INTEGRATION_TIME2 - - {0x31D0, 0x0000}, // COMPANDING, no good in 10 bit? - {0x33DA, 0x0000}, // COMPANDING - {0x318E, 0x0200}, // PRE_HDR_GAIN_EN - - // DLO Settings - {0x3100, 0x4000}, // DLO_CONTROL0 - {0x3280, 0x0CCC}, // T1 G1 - {0x3282, 0x0CCC}, // T1 R - {0x3284, 0x0CCC}, // T1 B - {0x3286, 0x0CCC}, // T1 G2 - {0x3288, 0x0FA0}, // T2 G1 - {0x328A, 0x0FA0}, // T2 R - {0x328C, 0x0FA0}, // T2 B - {0x328E, 0x0FA0}, // T2 G2 - - // Initial Gains - {0x3022, 0x0001}, // GROUPED_PARAMETER_HOLD_ - {0x3366, 0xFF77}, // ANALOG_GAIN (1x) - - {0x3060, 0x3333}, // ANALOG_COLOR_GAIN - - {0x3362, 0x0000}, // DC GAIN - - {0x305A, 0x00F8}, // red gain - {0x3058, 0x0122}, // blue gain - {0x3056, 0x009A}, // g1 gain - {0x305C, 0x009A}, // g2 gain - - {0x3022, 0x0000}, // GROUPED_PARAMETER_HOLD_ - - // Initial Integration Time - {0x3012, 0x0005}, -}; diff --git a/system/camerad/sensors/os04c10.cc b/system/camerad/sensors/os04c10.cc index e651d6ff7ac762..d14c288b919c9b 100644 --- a/system/camerad/sensors/os04c10.cc +++ b/system/camerad/sensors/os04c10.cc @@ -1,4 +1,7 @@ +#include + #include "system/camerad/sensors/sensor.h" +#include namespace { @@ -20,13 +23,14 @@ const uint32_t os04c10_analog_gains_reg[] = { OS04C10::OS04C10() { image_sensor = cereal::FrameData::ImageSensor::OS04C10; - pixel_size_mm = 0.004; + bayer_pattern = CAM_ISP_PATTERN_BAYER_BGBGBG; + pixel_size_mm = 0.002; data_word = false; - hdr_offset = 64 * 2 + 8; // stagger - frame_width = 1344; - frame_height = 760 * 2 + hdr_offset; - frame_stride = (frame_width * 10 / 8); // no alignment + out_scale = 2; + frame_width = 2688; + frame_height = 1520; + frame_stride = frame_width * 12 / 8; extra_height = 0; frame_offset = 0; @@ -35,29 +39,73 @@ OS04C10::OS04C10() { init_reg_array.assign(std::begin(init_array_os04c10), std::end(init_array_os04c10)); probe_reg_addr = 0x300a; probe_expected_data = 0x5304; - mipi_format = CAM_FORMAT_MIPI_RAW_10; - frame_data_type = 0x2b; + bits_per_pixel = 12; + mipi_format = CAM_FORMAT_MIPI_RAW_12; + frame_data_type = CSI_RAW12; mclk_frequency = 24000000; // Hz + // TODO: this was set from logs. actually calculate it out + readout_time_ns = 11000000; + + ev_scale = 150.0; dc_gain_factor = 1; dc_gain_min_weight = 1; // always on is fine dc_gain_max_weight = 1; dc_gain_on_grey = 0.9; dc_gain_off_grey = 1.0; exposure_time_min = 2; - exposure_time_max = 2400; + exposure_time_max = 2352; analog_gain_min_idx = 0x0; analog_gain_rec_idx = 0x0; // 1x - analog_gain_max_idx = 0x36; + analog_gain_max_idx = 0x28; analog_gain_cost_delta = -1; analog_gain_cost_low = 0.4; analog_gain_cost_high = 6.4; for (int i = 0; i <= analog_gain_max_idx; i++) { sensor_analog_gains[i] = sensor_analog_gains_OS04C10[i]; } - min_ev = (exposure_time_min) * sensor_analog_gains[analog_gain_min_idx]; + min_ev = exposure_time_min * sensor_analog_gains[analog_gain_min_idx]; max_ev = exposure_time_max * dc_gain_factor * sensor_analog_gains[analog_gain_max_idx]; target_grey_factor = 0.01; + + black_level = 48; + color_correct_matrix = { + 0x000000c2, 0x00000fe0, 0x00000fde, + 0x00000fa7, 0x000000d9, 0x00001000, + 0x00000fca, 0x00000fef, 0x000000c7, + }; + for (int i = 0; i < 65; i++) { + float fx = i / 64.0; + gamma_lut_rgb.push_back((uint32_t)((10*fx)/(1+9*fx)*1023.0 + 0.5)); + } + prepare_gamma_lut(); + linearization_lut = { + 0x02000000, 0x02000000, 0x02000000, 0x02000000, + 0x020007ff, 0x020007ff, 0x020007ff, 0x020007ff, + 0x02000bff, 0x02000bff, 0x02000bff, 0x02000bff, + 0x020017ff, 0x020017ff, 0x020017ff, 0x020017ff, + 0x02001bff, 0x02001bff, 0x02001bff, 0x02001bff, + 0x020023ff, 0x020023ff, 0x020023ff, 0x020023ff, + 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, + 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, + 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, + }; + linearization_pts = {0x07ff0bff, 0x17ff1bff, 0x23ff3fff, 0x3fff3fff}; + vignetting_lut = { + 0x01064832, 0x00da26d1, 0x00bb25d9, 0x00aac556, 0x00a06503, 0x009a64d3, 0x009744ba, 0x009744ba, 0x009a24d1, 0x00a00500, 0x00aa2551, 0x00ba45d2, 0x00d826c1, 0x01040820, 0x013729b9, 0x0171ab8d, 0x01b36d9b, + 0x00eee777, 0x00c2c616, 0x00ae2571, 0x009fe4ff, 0x0096e4b7, 0x0090e487, 0x008d446a, 0x008d2469, 0x0090a485, 0x009684b4, 0x009f64fb, 0x00ad456a, 0x00c1a60d, 0x00eca765, 0x011fc8fe, 0x015a4ad2, 0x019c0ce0, + 0x00dee6f7, 0x00b9c5ce, 0x00a5652b, 0x009964cb, 0x00904482, 0x00892449, 0x0085842c, 0x0085642b, 0x0088e447, 0x008fe47f, 0x0098e4c7, 0x00a4c526, 0x00b8a5c5, 0x00dc86e4, 0x010fc87e, 0x014a2a51, 0x018c0c60, + 0x00d626b1, 0x00b4e5a7, 0x00a1e50f, 0x0095e4af, 0x008c2461, 0x00850428, 0x0081640b, 0x0081440a, 0x0084a425, 0x008ba45d, 0x009564ab, 0x00a1450a, 0x00b3c59e, 0x00d3e69f, 0x01070838, 0x01418a0c, 0x01834c1a, + 0x00d4c6a6, 0x00b425a1, 0x00a1450a, 0x009544aa, 0x008b645b, 0x00844422, 0x0080a405, 0x0080a405, 0x00840420, 0x008b0458, 0x0094c4a6, 0x00a0a505, 0x00b30598, 0x00d26693, 0x0105a82d, 0x01402a01, 0x0181ec0f, + 0x00daa6d5, 0x00b765bb, 0x00a3c51e, 0x0097a4bd, 0x008e4472, 0x00872439, 0x0083841c, 0x0083641b, 0x0086e437, 0x008de46f, 0x009724b9, 0x00a30518, 0x00b665b3, 0x00d866c3, 0x010b885c, 0x01460a30, 0x0187ec3f, + 0x00e80740, 0x00bec5f6, 0x00aa6553, 0x009d24e9, 0x009404a0, 0x008d846c, 0x0089e44f, 0x0089e44f, 0x008d446a, 0x0093c49e, 0x009ca4e5, 0x00a9854c, 0x00bdc5ee, 0x00e5a72d, 0x0118c8c6, 0x01534a9a, 0x01952ca9, + 0x00fca7e5, 0x00d06683, 0x00b5c5ae, 0x00a5852c, 0x009c84e4, 0x009664b3, 0x0093649b, 0x0093449a, 0x009624b1, 0x009c24e1, 0x00a50528, 0x00b4e5a7, 0x00ce8674, 0x00fa47d2, 0x012d696b, 0x0167eb3f, 0x01a9cd4e, + 0x011888c4, 0x00ec6763, 0x00c7863c, 0x00b4e5a7, 0x00a8a545, 0x00a1c50e, 0x009ec4f6, 0x009ea4f5, 0x00a1a50d, 0x00a82541, 0x00b445a2, 0x00c5e62f, 0x00ea6753, 0x011648b2, 0x01496a4b, 0x0183ec1f, 0x01c5ae2d, + 0x013bc9de, 0x010fa87d, 0x00eac756, 0x00cd466a, 0x00bc25e1, 0x00b405a0, 0x00afc57e, 0x00afa57d, 0x00b3a59d, 0x00bbc5de, 0x00cc0660, 0x00e92749, 0x010da86d, 0x013989cc, 0x016cab65, 0x01a72d39, 0x01e8ef47, + 0x01666b33, 0x013a49d2, 0x011568ab, 0x00f7e7bf, 0x00e1c70e, 0x00d2e697, 0x00cb665b, 0x00cb2659, 0x00d26693, 0x00e0c706, 0x00f6a7b5, 0x0113c89e, 0x013849c2, 0x01642b21, 0x01974cba, 0x01d1ce8e, 0x0213909c, + 0x01986cc3, 0x016c2b61, 0x01476a3b, 0x0129e94f, 0x0113a89d, 0x0104c826, 0x00fd47ea, 0x00fd27e9, 0x01044822, 0x0112c896, 0x0128a945, 0x0145ca2e, 0x016a4b52, 0x01960cb0, 0x01c92e49, 0x0203b01d, 0x0245922c, + 0x01d1ae8d, 0x01a58d2c, 0x0180ac05, 0x01632b19, 0x014cea67, 0x013e29f1, 0x013689b4, 0x013669b3, 0x013d89ec, 0x014c0a60, 0x0161eb0f, 0x017f0bf8, 0x01a38d1c, 0x01cf4e7a, 0x02029014, 0x023d11e8, 0x027ed3f6, + }; } std::vector OS04C10::getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const { diff --git a/system/camerad/sensors/os04c10_cl.h b/system/camerad/sensors/os04c10_cl.h deleted file mode 100644 index 61775dcdc8c893..00000000000000 --- a/system/camerad/sensors/os04c10_cl.h +++ /dev/null @@ -1,55 +0,0 @@ -#if SENSOR_ID == 3 - -#define BGGR - -#define BIT_DEPTH 10 -#define PV_MAX10 1023 -#define PV_MAX16 65536 // gamma curve is calibrated to 16bit -#define BLACK_LVL 64 -#define VIGNETTE_RSZ 2.2545f - -float combine_dual_pvs(float lv, float sv, int expo_time) { - float svc = fmax(sv * expo_time, (float)(64 * (PV_MAX10 - BLACK_LVL))); - float svd = sv * fmin(expo_time, 8.0) / 8; - - if (expo_time > 64) { - if (lv < PV_MAX10 - BLACK_LVL) { - return lv / (PV_MAX16 - BLACK_LVL); - } else { - return (svc / 64) / (PV_MAX16 - BLACK_LVL); - } - } else { - if (lv > 32) { - return (lv * 64 / fmax(expo_time, 8.0)) / (PV_MAX16 - BLACK_LVL); - } else { - return svd / (PV_MAX16 - BLACK_LVL); - } - } -} - -float4 normalize_pv_hdr(int4 parsed, int4 short_parsed, float vignette_factor, int expo_time) { - float4 pl = convert_float4(parsed - BLACK_LVL); - float4 ps = convert_float4(short_parsed - BLACK_LVL); - float4 pv; - pv.s0 = combine_dual_pvs(pl.s0, ps.s0, expo_time); - pv.s1 = combine_dual_pvs(pl.s1, ps.s1, expo_time); - pv.s2 = combine_dual_pvs(pl.s2, ps.s2, expo_time); - pv.s3 = combine_dual_pvs(pl.s3, ps.s3, expo_time); - return clamp(pv*vignette_factor, 0.0, 1.0); -} - -float3 color_correct(float3 rgb) { - float3 corrected = rgb.x * (float3)(1.55361989, -0.268894615, -0.000593219); - corrected += rgb.y * (float3)(-0.421217301, 1.51883144, -0.69760146); - corrected += rgb.z * (float3)(-0.132402589, -0.249936825, 1.69819468); - return corrected; -} - -float3 apply_gamma(float3 rgb, int expo_time) { - float s = log2((float)expo_time); - if (s < 6) {s = fmin(12.0 - s, 9.0);} - // log function adaptive to number of bits - return clamp(log(1 + rgb*(PV_MAX16 - BLACK_LVL)) * (0.48*s*s - 12.92*s + 115.0) - (1.08*s*s - 29.2*s + 260.0), 0.0, 255.0) / 255.0; -} - -#endif diff --git a/system/camerad/sensors/os04c10_registers.h b/system/camerad/sensors/os04c10_registers.h index d698b1311f5682..45512851bcf921 100644 --- a/system/camerad/sensors/os04c10_registers.h +++ b/system/camerad/sensors/os04c10_registers.h @@ -4,18 +4,18 @@ const struct i2c_random_wr_payload start_reg_array_os04c10[] = {{0x100, 1}}; const struct i2c_random_wr_payload stop_reg_array_os04c10[] = {{0x100, 0}}; const struct i2c_random_wr_payload init_array_os04c10[] = { - // DP_2688X1520_NEWSTG_MIPI0776Mbps_30FPS_10BIT_FOURLANE - {0x0103, 0x01}, + // OS04C10_AA_00_02_17_wAO_2688x1524_MIPI728Mbps_Linear12bit_20FPS_4Lane_MCLK24MHz + {0x0103, 0x01}, // software reset - // PLL - {0x0301, 0x84}, + // PLL + clocks + {0x0301, 0xe4}, {0x0303, 0x01}, - {0x0305, 0x61}, + {0x0305, 0xb6}, {0x0306, 0x01}, {0x0307, 0x17}, {0x0323, 0x04}, {0x0324, 0x01}, - {0x0325, 0x7a}, + {0x0325, 0x62}, {0x3012, 0x06}, {0x3013, 0x02}, @@ -24,18 +24,18 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x3106, 0x21}, {0x3107, 0xa1}, - // ? + // Analog/timing fine-tuning block {0x3624, 0x00}, {0x3625, 0x4c}, {0x3660, 0x04}, {0x3666, 0xa5}, {0x3667, 0xa5}, - {0x366a, 0x54}, + {0x366a, 0x50}, {0x3673, 0x0d}, {0x3672, 0x0d}, {0x3671, 0x0d}, {0x3670, 0x0d}, - {0x3685, 0x0a}, + {0x3685, 0x00}, {0x3694, 0x0d}, {0x3693, 0x0d}, {0x3692, 0x0d}, @@ -53,17 +53,17 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x36a0, 0x12}, {0x36a1, 0xdd}, {0x36a2, 0x66}, - {0x370a, 0x00}, + {0x370a, 0x02}, {0x370e, 0x00}, {0x3710, 0x00}, {0x3713, 0x04}, {0x3725, 0x02}, {0x372a, 0x03}, {0x3738, 0xce}, - {0x3748, 0x00}, - {0x374a, 0x00}, - {0x374c, 0x00}, - {0x374e, 0x00}, + {0x3748, 0x02}, + {0x374a, 0x02}, + {0x374c, 0x02}, + {0x374e, 0x02}, {0x3756, 0x00}, {0x3757, 0x00}, {0x3767, 0x00}, @@ -88,14 +88,12 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x37c7, 0xa8}, {0x37da, 0x11}, {0x381f, 0x08}, - // {0x3829, 0x03}, - // {0x3832, 0x00}, {0x3881, 0x00}, {0x3888, 0x04}, {0x388b, 0x00}, {0x3c80, 0x10}, {0x3c86, 0x00}, - {0x3c8c, 0x20}, + {0x3c8c, 0x40}, {0x3c9f, 0x01}, {0x3d85, 0x1b}, {0x3d8c, 0x71}, @@ -103,7 +101,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x3f00, 0x0b}, {0x3f06, 0x04}, - // BLC + // BLC - black level correction {0x400a, 0x01}, {0x400b, 0x50}, {0x400e, 0x08}, @@ -111,7 +109,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x4045, 0x7e}, {0x4047, 0x7e}, {0x4049, 0x7e}, - {0x4090, 0x14}, + {0x4090, 0x04}, {0x40b0, 0x00}, {0x40b1, 0x00}, {0x40b2, 0x00}, @@ -129,7 +127,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x4503, 0x00}, {0x4504, 0x06}, {0x4506, 0x00}, - {0x4507, 0x57}, + {0x4507, 0x47}, {0x4803, 0x00}, {0x480c, 0x32}, {0x480e, 0x04}, @@ -139,7 +137,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x4823, 0x3f}, {0x4825, 0x30}, {0x4833, 0x10}, - {0x484b, 0x07}, + {0x484b, 0x27}, {0x488b, 0x00}, {0x4d00, 0x04}, {0x4d01, 0xad}, @@ -152,14 +150,14 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x4e0d, 0x00}, // ISP - {0x5001, 0x00}, + {0x5001, 0x09}, {0x5004, 0x00}, {0x5080, 0x04}, {0x5036, 0x80}, {0x5180, 0x70}, {0x5181, 0x10}, - // DPC + // DPC - defective pixel correction {0x520a, 0x03}, {0x520b, 0x06}, {0x520c, 0x0c}, @@ -173,14 +171,14 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x301c, 0xf8}, {0x301e, 0xb4}, {0x301f, 0xf0}, - {0x3022, 0x01}, + {0x3022, 0x61}, {0x3109, 0xe7}, {0x3600, 0x00}, - {0x3610, 0x75}, + {0x3610, 0x65}, {0x3611, 0x85}, {0x3613, 0x3a}, {0x3615, 0x60}, - {0x3621, 0x90}, + {0x3621, 0xb0}, {0x3620, 0x0c}, {0x3629, 0x00}, {0x3661, 0x04}, @@ -194,31 +192,31 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x3701, 0x12}, {0x3703, 0x28}, {0x3704, 0x0e}, - {0x3706, 0x4a}, + {0x3706, 0x9d}, {0x3709, 0x4a}, - {0x370b, 0xa2}, + {0x370b, 0x48}, {0x370c, 0x01}, {0x370f, 0x00}, - {0x3714, 0x28}, + {0x3714, 0x24}, {0x3716, 0x04}, {0x3719, 0x11}, {0x371a, 0x1e}, {0x3720, 0x00}, {0x3724, 0x13}, {0x373f, 0xb0}, - {0x3741, 0x4a}, - {0x3743, 0x4a}, - {0x3745, 0x4a}, - {0x3747, 0x4a}, - {0x3749, 0xa2}, - {0x374b, 0xa2}, - {0x374d, 0xa2}, - {0x374f, 0xa2}, + {0x3741, 0x9d}, + {0x3743, 0x9d}, + {0x3745, 0x9d}, + {0x3747, 0x9d}, + {0x3749, 0x48}, + {0x374b, 0x48}, + {0x374d, 0x48}, + {0x374f, 0x48}, {0x3755, 0x10}, {0x376c, 0x00}, - {0x378d, 0x30}, - {0x3790, 0x4a}, - {0x3791, 0xa2}, + {0x378d, 0x3c}, + {0x3790, 0x01}, + {0x3791, 0x01}, {0x3798, 0x40}, {0x379e, 0x00}, {0x379f, 0x04}, @@ -231,7 +229,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x37bd, 0x01}, {0x37bf, 0x26}, {0x37c0, 0x11}, - {0x37c2, 0x14}, + {0x37c2, 0x04}, {0x37cd, 0x19}, {0x37e0, 0x08}, {0x37e6, 0x04}, @@ -241,16 +239,16 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x37d8, 0x02}, {0x37e2, 0x10}, {0x3739, 0x10}, - {0x3662, 0x08}, + {0x3662, 0x10}, {0x37e4, 0x20}, {0x37e3, 0x08}, - {0x37d9, 0x04}, + {0x37d9, 0x08}, {0x4040, 0x00}, - {0x4041, 0x03}, - {0x4008, 0x01}, - {0x4009, 0x06}, + {0x4041, 0x07}, + {0x4008, 0x02}, + {0x4009, 0x0d}, - // FSIN + // FSIN - frame sync {0x3002, 0x22}, {0x3663, 0x22}, {0x368a, 0x04}, @@ -269,36 +267,36 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0a}, {0x3805, 0x8f}, {0x3806, 0x05}, {0x3807, 0xff}, - {0x3808, 0x05}, {0x3809, 0x40}, - {0x380a, 0x02}, {0x380b, 0xf8}, + {0x3808, 0x0a}, {0x3809, 0x80}, + {0x380a, 0x05}, {0x380b, 0xf0}, {0x3811, 0x08}, {0x3813, 0x08}, - {0x3814, 0x03}, + {0x3814, 0x01}, {0x3815, 0x01}, - {0x3816, 0x03}, + {0x3816, 0x01}, {0x3817, 0x01}, - {0x380c, 0x04}, {0x380d, 0x2e}, // HTS - {0x380e, 0x09}, {0x380f, 0xdb}, // VTS + {0x380c, 0x08}, {0x380d, 0x5c}, // HTS (line length) + {0x380e, 0x09}, {0x380f, 0x38}, // VTS (frame length) - {0x3820, 0xb3}, - {0x3821, 0x05}, + {0x3820, 0xb0}, + {0x3821, 0x00}, {0x3880, 0x00}, {0x3882, 0x20}, {0x3c91, 0x0b}, {0x3c94, 0x45}, - // {0x3cad, 0x00}, - // {0x3cae, 0x00}, + {0x3cad, 0x00}, + {0x3cae, 0x00}, {0x4000, 0xf3}, {0x4001, 0x60}, {0x4003, 0x40}, {0x4300, 0xff}, {0x4302, 0x0f}, - {0x4305, 0x93}, + {0x4305, 0x83}, {0x4505, 0x84}, {0x4809, 0x0e}, {0x480a, 0x04}, - {0x4837, 0x14}, + {0x4837, 0x15}, {0x4c00, 0x08}, {0x4c01, 0x08}, {0x4c04, 0x00}, @@ -307,22 +305,21 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { // {0x0100, 0x01}, // {0x320d, 0x00}, // {0x3208, 0xa0}, - // {0x3822, 0x14}, // initialize exposure {0x3503, 0x88}, - // long + // long exposure {0x3500, 0x00}, {0x3501, 0x00}, {0x3502, 0x10}, {0x3508, 0x00}, {0x3509, 0x80}, {0x350a, 0x04}, {0x350b, 0x00}, - // short + // short exposure {0x3510, 0x00}, {0x3511, 0x00}, {0x3512, 0x40}, {0x350c, 0x00}, {0x350d, 0x80}, {0x350e, 0x04}, {0x350f, 0x00}, - // wb + // white balance // b {0x5100, 0x06}, {0x5101, 0x7e}, {0x5140, 0x06}, {0x5141, 0x7e}, diff --git a/system/camerad/sensors/ox03c10.cc b/system/camerad/sensors/ox03c10.cc index 94efa0ea24bb07..e0e0dec2ffe948 100644 --- a/system/camerad/sensors/ox03c10.cc +++ b/system/camerad/sensors/ox03c10.cc @@ -1,4 +1,7 @@ +#include + #include "system/camerad/sensors/sensor.h" +#include namespace { @@ -23,6 +26,7 @@ const uint32_t VS_TIME_MAX_OX03C10 = 34; // vs < 35 OX03C10::OX03C10() { image_sensor = cereal::FrameData::ImageSensor::OX03C10; + bayer_pattern = CAM_ISP_PATTERN_BAYER_GRGRGR; pixel_size_mm = 0.003; data_word = false; frame_width = 1928; @@ -35,9 +39,12 @@ OX03C10::OX03C10() { init_reg_array.assign(std::begin(init_array_ox03c10), std::end(init_array_ox03c10)); probe_reg_addr = 0x300a; probe_expected_data = 0x5803; + bits_per_pixel = 12; mipi_format = CAM_FORMAT_MIPI_RAW_12; - frame_data_type = 0x2c; // one is 0x2a, two are 0x2b - mclk_frequency = 24000000; //Hz + frame_data_type = CSI_RAW12; + mclk_frequency = 24000000; // Hz + + readout_time_ns = 14697000; dc_gain_factor = 7.32; dc_gain_min_weight = 1; // always on is fine @@ -58,6 +65,46 @@ OX03C10::OX03C10() { min_ev = (exposure_time_min + VS_TIME_MIN_OX03C10) * sensor_analog_gains[analog_gain_min_idx]; max_ev = exposure_time_max * dc_gain_factor * sensor_analog_gains[analog_gain_max_idx]; target_grey_factor = 0.01; + + black_level = 0; + color_correct_matrix = { + 0x000000b6, 0x00000ff1, 0x00000fda, + 0x00000fcc, 0x000000b9, 0x00000ffb, + 0x00000fc2, 0x00000ff6, 0x000000c9, + }; + for (int i = 0; i < 65; i++) { + float fx = i / 64.0; + fx = -0.507089*exp(-12.54124638*fx) + 0.9655*pow(fx, 0.5) - 0.472597*fx + 0.507089; + gamma_lut_rgb.push_back((uint32_t)(fx*1023.0 + 0.5)); + } + prepare_gamma_lut(); + linearization_lut = { + 0x00200000, 0x00200000, 0x00200000, 0x00200000, + 0x00404080, 0x00404080, 0x00404080, 0x00404080, + 0x00804100, 0x00804100, 0x00804100, 0x00804100, + 0x02014402, 0x02014402, 0x02014402, 0x02014402, + 0x0402c804, 0x0402c804, 0x0402c804, 0x0402c804, + 0x0805d00a, 0x0805d00a, 0x0805d00a, 0x0805d00a, + 0x100ba015, 0x100ba015, 0x100ba015, 0x100ba015, + 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, + 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, + }; + linearization_pts = {0x07ff0bff, 0x17ff1bff, 0x1fff23ff, 0x27ff3fff}; + vignetting_lut = { + 0x00eaa755, 0x00cf2679, 0x00bc05e0, 0x00acc566, 0x00a1450a, 0x009984cc, 0x0095a4ad, 0x009584ac, 0x009944ca, 0x00a0c506, 0x00ac0560, 0x00bb25d9, 0x00ce2671, 0x00e90748, 0x01112889, 0x014a2a51, 0x01984cc2, + 0x00db06d8, 0x00c30618, 0x00afe57f, 0x00a0a505, 0x009524a9, 0x008d646b, 0x0089844c, 0x0089644b, 0x008d2469, 0x0094a4a5, 0x009fe4ff, 0x00af0578, 0x00c20610, 0x00d986cc, 0x00fda7ed, 0x01320990, 0x017aebd7, + 0x00d1868c, 0x00baa5d5, 0x00a7853c, 0x009844c2, 0x008cc466, 0x0085a42d, 0x0083641b, 0x0083641b, 0x0085842c, 0x008c4462, 0x0097a4bd, 0x00a6c536, 0x00b9a5cd, 0x00d06683, 0x00f1678b, 0x01226913, 0x0167ab3d, + 0x00cd0668, 0x00b625b1, 0x00a30518, 0x0093c49e, 0x00884442, 0x00830418, 0x0080e407, 0x0080c406, 0x0082e417, 0x0087c43e, 0x00932499, 0x00a22511, 0x00b525a9, 0x00cbe65f, 0x00eb0758, 0x011a68d3, 0x015daaed, + 0x00cc4662, 0x00b565ab, 0x00a24512, 0x00930498, 0x0087843c, 0x0082a415, 0x00806403, 0x00806403, 0x00828414, 0x00870438, 0x00926493, 0x00a1850c, 0x00b465a3, 0x00cb2659, 0x00ea2751, 0x011928c9, 0x015c2ae1, + 0x00cf667b, 0x00b885c4, 0x00a5652b, 0x009624b1, 0x008aa455, 0x00846423, 0x00822411, 0x00822411, 0x00844422, 0x008a2451, 0x009564ab, 0x00a48524, 0x00b785bc, 0x00ce4672, 0x00ee6773, 0x011e88f4, 0x0162eb17, + 0x00d6c6b6, 0x00bf65fb, 0x00ac4562, 0x009d04e8, 0x0091848c, 0x0089c44e, 0x00862431, 0x00860430, 0x0089844c, 0x00910488, 0x009c64e3, 0x00ab655b, 0x00be65f3, 0x00d566ab, 0x00f847c2, 0x012b2959, 0x01726b93, + 0x00e3e71f, 0x00ca0650, 0x00b705b8, 0x00a7a53d, 0x009c24e1, 0x009484a4, 0x00908484, 0x00908484, 0x009424a1, 0x009bc4de, 0x00a70538, 0x00b625b1, 0x00c90648, 0x00e26713, 0x0108e847, 0x013fe9ff, 0x018bcc5e, + 0x00f807c0, 0x00d966cb, 0x00c5862c, 0x00b625b1, 0x00aaa555, 0x00a30518, 0x009f04f8, 0x009f04f8, 0x00a2a515, 0x00aa2551, 0x00b585ac, 0x00c4a625, 0x00d846c2, 0x00f647b2, 0x0121a90d, 0x015e4af2, 0x01b8cdc6, + 0x011548aa, 0x00f1678b, 0x00d886c4, 0x00c86643, 0x00bce5e7, 0x00b545aa, 0x00b1658b, 0x00b1458a, 0x00b505a8, 0x00bc85e4, 0x00c7c63e, 0x00d786bc, 0x00efe77f, 0x0113489a, 0x0144ea27, 0x01888c44, 0x01fdcfee, + 0x013e49f2, 0x0113e89f, 0x00f5a7ad, 0x00e0c706, 0x00d30698, 0x00cb665b, 0x00c7663b, 0x00c7663b, 0x00cb0658, 0x00d2a695, 0x00dfe6ff, 0x00f467a3, 0x01122891, 0x013be9df, 0x01750ba8, 0x01cfae7d, 0x025912c8, + 0x01766bb3, 0x01446a23, 0x011fc8fe, 0x0105e82f, 0x00f467a3, 0x00e9874c, 0x00e46723, 0x00e44722, 0x00e92749, 0x00f3a79d, 0x0104c826, 0x011e48f2, 0x01424a12, 0x01738b9c, 0x01bf6dfb, 0x023611b0, 0x02ced676, + 0x01cf8e7c, 0x01866c33, 0x015aaad5, 0x013ae9d7, 0x01250928, 0x011768bb, 0x0110a885, 0x01108884, 0x0116e8b7, 0x01242921, 0x0139a9cd, 0x0158eac7, 0x01840c20, 0x01cb0e58, 0x0233719b, 0x02b9d5ce, 0x03645b22, + }; } std::vector OX03C10::getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const { diff --git a/system/camerad/sensors/ox03c10_cl.h b/system/camerad/sensors/ox03c10_cl.h deleted file mode 100644 index 21441902fc2cd0..00000000000000 --- a/system/camerad/sensors/ox03c10_cl.h +++ /dev/null @@ -1,43 +0,0 @@ -#if SENSOR_ID == 2 - -#define BIT_DEPTH 12 -#define BLACK_LVL 64 -#define VIGNETTE_RSZ 1.0f - -constant float ox03c10_lut[] = { - 0.0000e+00, 5.9488e-08, 1.1898e-07, 1.7846e-07, 2.3795e-07, 2.9744e-07, 3.5693e-07, 4.1642e-07, 4.7591e-07, 5.3539e-07, 5.9488e-07, 6.5437e-07, 7.1386e-07, 7.7335e-07, 8.3284e-07, 8.9232e-07, 9.5181e-07, 1.0113e-06, 1.0708e-06, 1.1303e-06, 1.1898e-06, 1.2493e-06, 1.3087e-06, 1.3682e-06, 1.4277e-06, 1.4872e-06, 1.5467e-06, 1.6062e-06, 1.6657e-06, 1.7252e-06, 1.7846e-06, 1.8441e-06, 1.9036e-06, 1.9631e-06, 2.0226e-06, 2.0821e-06, 2.1416e-06, 2.2011e-06, 2.2606e-06, 2.3200e-06, 2.3795e-06, 2.4390e-06, 2.4985e-06, 2.5580e-06, 2.6175e-06, 2.6770e-06, 2.7365e-06, 2.7959e-06, 2.8554e-06, 2.9149e-06, 2.9744e-06, 3.0339e-06, 3.0934e-06, 3.1529e-06, 3.2124e-06, 3.2719e-06, 3.3313e-06, 3.3908e-06, 3.4503e-06, 3.5098e-06, 3.5693e-06, 3.6288e-06, 3.6883e-06, 3.7478e-06, 3.8072e-06, 3.8667e-06, 3.9262e-06, 3.9857e-06, 4.0452e-06, 4.1047e-06, 4.1642e-06, 4.2237e-06, 4.2832e-06, 4.3426e-06, 4.4021e-06, 4.4616e-06, 4.5211e-06, 4.5806e-06, 4.6401e-06, 4.6996e-06, 4.7591e-06, 4.8185e-06, 4.8780e-06, 4.9375e-06, 4.9970e-06, 5.0565e-06, 5.1160e-06, 5.1755e-06, 5.2350e-06, 5.2945e-06, 5.3539e-06, 5.4134e-06, 5.4729e-06, 5.5324e-06, 5.5919e-06, 5.6514e-06, 5.7109e-06, 5.7704e-06, 5.8298e-06, 5.8893e-06, 5.9488e-06, 6.0083e-06, 6.0678e-06, 6.1273e-06, 6.1868e-06, 6.2463e-06, 6.3058e-06, 6.3652e-06, 6.4247e-06, 6.4842e-06, 6.5437e-06, 6.6032e-06, 6.6627e-06, 6.7222e-06, 6.7817e-06, 6.8411e-06, 6.9006e-06, 6.9601e-06, 7.0196e-06, 7.0791e-06, 7.1386e-06, 7.1981e-06, 7.2576e-06, 7.3171e-06, 7.3765e-06, 7.4360e-06, 7.4955e-06, 7.5550e-06, 7.6145e-06, 7.6740e-06, 7.7335e-06, 7.7930e-06, 7.8524e-06, 7.9119e-06, 7.9714e-06, 8.0309e-06, 8.0904e-06, 8.1499e-06, 8.2094e-06, 8.2689e-06, 8.3284e-06, 8.3878e-06, 8.4473e-06, 8.5068e-06, 8.5663e-06, 8.6258e-06, 8.6853e-06, 8.7448e-06, 8.8043e-06, 8.8637e-06, 8.9232e-06, 8.9827e-06, 9.0422e-06, 9.1017e-06, 9.1612e-06, 9.2207e-06, 9.2802e-06, 9.3397e-06, 9.3991e-06, 9.4586e-06, 9.5181e-06, 9.5776e-06, 9.6371e-06, 9.6966e-06, 9.7561e-06, 9.8156e-06, 9.8750e-06, 9.9345e-06, 9.9940e-06, 1.0054e-05, 1.0113e-05, 1.0172e-05, 1.0232e-05, 1.0291e-05, 1.0351e-05, 1.0410e-05, 1.0470e-05, 1.0529e-05, 1.0589e-05, 1.0648e-05, 1.0708e-05, 1.0767e-05, 1.0827e-05, 1.0886e-05, 1.0946e-05, 1.1005e-05, 1.1065e-05, 1.1124e-05, 1.1184e-05, 1.1243e-05, 1.1303e-05, 1.1362e-05, 1.1422e-05, 1.1481e-05, 1.1541e-05, 1.1600e-05, 1.1660e-05, 1.1719e-05, 1.1779e-05, 1.1838e-05, 1.1898e-05, 1.1957e-05, 1.2017e-05, 1.2076e-05, 1.2136e-05, 1.2195e-05, 1.2255e-05, 1.2314e-05, 1.2374e-05, 1.2433e-05, 1.2493e-05, 1.2552e-05, 1.2612e-05, 1.2671e-05, 1.2730e-05, 1.2790e-05, 1.2849e-05, 1.2909e-05, 1.2968e-05, 1.3028e-05, 1.3087e-05, 1.3147e-05, 1.3206e-05, 1.3266e-05, 1.3325e-05, 1.3385e-05, 1.3444e-05, 1.3504e-05, 1.3563e-05, 1.3623e-05, 1.3682e-05, 1.3742e-05, 1.3801e-05, 1.3861e-05, 1.3920e-05, 1.3980e-05, 1.4039e-05, 1.4099e-05, 1.4158e-05, 1.4218e-05, 1.4277e-05, 1.4337e-05, 1.4396e-05, 1.4456e-05, 1.4515e-05, 1.4575e-05, 1.4634e-05, 1.4694e-05, 1.4753e-05, 1.4813e-05, 1.4872e-05, 1.4932e-05, 1.4991e-05, 1.5051e-05, 1.5110e-05, 1.5169e-05, // NOLINT - 1.5229e-05, 1.5288e-05, 1.5348e-05, 1.5407e-05, 1.5467e-05, 1.5526e-05, 1.5586e-05, 1.5645e-05, 1.5705e-05, 1.5764e-05, 1.5824e-05, 1.5883e-05, 1.5943e-05, 1.6002e-05, 1.6062e-05, 1.6121e-05, 1.6181e-05, 1.6240e-05, 1.6300e-05, 1.6359e-05, 1.6419e-05, 1.6478e-05, 1.6538e-05, 1.6597e-05, 1.6657e-05, 1.6716e-05, 1.6776e-05, 1.6835e-05, 1.6895e-05, 1.6954e-05, 1.7014e-05, 1.7073e-05, 1.7133e-05, 1.7192e-05, 1.7252e-05, 1.7311e-05, 1.7371e-05, 1.7430e-05, 1.7490e-05, 1.7549e-05, 1.7609e-05, 1.7668e-05, 1.7727e-05, 1.7787e-05, 1.7846e-05, 1.7906e-05, 1.7965e-05, 1.8025e-05, 1.8084e-05, 1.8144e-05, 1.8203e-05, 1.8263e-05, 1.8322e-05, 1.8382e-05, 1.8441e-05, 1.8501e-05, 1.8560e-05, 1.8620e-05, 1.8679e-05, 1.8739e-05, 1.8798e-05, 1.8858e-05, 1.8917e-05, 1.8977e-05, 1.9036e-05, 1.9096e-05, 1.9155e-05, 1.9215e-05, 1.9274e-05, 1.9334e-05, 1.9393e-05, 1.9453e-05, 1.9512e-05, 1.9572e-05, 1.9631e-05, 1.9691e-05, 1.9750e-05, 1.9810e-05, 1.9869e-05, 1.9929e-05, 1.9988e-05, 2.0048e-05, 2.0107e-05, 2.0167e-05, 2.0226e-05, 2.0285e-05, 2.0345e-05, 2.0404e-05, 2.0464e-05, 2.0523e-05, 2.0583e-05, 2.0642e-05, 2.0702e-05, 2.0761e-05, 2.0821e-05, 2.0880e-05, 2.0940e-05, 2.0999e-05, 2.1059e-05, 2.1118e-05, 2.1178e-05, 2.1237e-05, 2.1297e-05, 2.1356e-05, 2.1416e-05, 2.1475e-05, 2.1535e-05, 2.1594e-05, 2.1654e-05, 2.1713e-05, 2.1773e-05, 2.1832e-05, 2.1892e-05, 2.1951e-05, 2.2011e-05, 2.2070e-05, 2.2130e-05, 2.2189e-05, 2.2249e-05, 2.2308e-05, 2.2368e-05, 2.2427e-05, 2.2487e-05, 2.2546e-05, 2.2606e-05, 2.2665e-05, 2.2725e-05, 2.2784e-05, 2.2843e-05, 2.2903e-05, 2.2962e-05, 2.3022e-05, 2.3081e-05, 2.3141e-05, 2.3200e-05, 2.3260e-05, 2.3319e-05, 2.3379e-05, 2.3438e-05, 2.3498e-05, 2.3557e-05, 2.3617e-05, 2.3676e-05, 2.3736e-05, 2.3795e-05, 2.3855e-05, 2.3914e-05, 2.3974e-05, 2.4033e-05, 2.4093e-05, 2.4152e-05, 2.4212e-05, 2.4271e-05, 2.4331e-05, 2.4390e-05, 2.4450e-05, 2.4509e-05, 2.4569e-05, 2.4628e-05, 2.4688e-05, 2.4747e-05, 2.4807e-05, 2.4866e-05, 2.4926e-05, 2.4985e-05, 2.5045e-05, 2.5104e-05, 2.5164e-05, 2.5223e-05, 2.5282e-05, 2.5342e-05, 2.5401e-05, 2.5461e-05, 2.5520e-05, 2.5580e-05, 2.5639e-05, 2.5699e-05, 2.5758e-05, 2.5818e-05, 2.5877e-05, 2.5937e-05, 2.5996e-05, 2.6056e-05, 2.6115e-05, 2.6175e-05, 2.6234e-05, 2.6294e-05, 2.6353e-05, 2.6413e-05, 2.6472e-05, 2.6532e-05, 2.6591e-05, 2.6651e-05, 2.6710e-05, 2.6770e-05, 2.6829e-05, 2.6889e-05, 2.6948e-05, 2.7008e-05, 2.7067e-05, 2.7127e-05, 2.7186e-05, 2.7246e-05, 2.7305e-05, 2.7365e-05, 2.7424e-05, 2.7484e-05, 2.7543e-05, 2.7603e-05, 2.7662e-05, 2.7722e-05, 2.7781e-05, 2.7840e-05, 2.7900e-05, 2.7959e-05, 2.8019e-05, 2.8078e-05, 2.8138e-05, 2.8197e-05, 2.8257e-05, 2.8316e-05, 2.8376e-05, 2.8435e-05, 2.8495e-05, 2.8554e-05, 2.8614e-05, 2.8673e-05, 2.8733e-05, 2.8792e-05, 2.8852e-05, 2.8911e-05, 2.8971e-05, 2.9030e-05, 2.9090e-05, 2.9149e-05, 2.9209e-05, 2.9268e-05, 2.9328e-05, 2.9387e-05, 2.9447e-05, 2.9506e-05, 2.9566e-05, 2.9625e-05, 2.9685e-05, 2.9744e-05, 2.9804e-05, 2.9863e-05, 2.9923e-05, 2.9982e-05, 3.0042e-05, 3.0101e-05, 3.0161e-05, 3.0220e-05, 3.0280e-05, 3.0339e-05, 3.0398e-05, // NOLINT - 3.0458e-05, 3.0577e-05, 3.0697e-05, 3.0816e-05, 3.0936e-05, 3.1055e-05, 3.1175e-05, 3.1294e-05, 3.1414e-05, 3.1533e-05, 3.1652e-05, 3.1772e-05, 3.1891e-05, 3.2011e-05, 3.2130e-05, 3.2250e-05, 3.2369e-05, 3.2489e-05, 3.2608e-05, 3.2727e-05, 3.2847e-05, 3.2966e-05, 3.3086e-05, 3.3205e-05, 3.3325e-05, 3.3444e-05, 3.3563e-05, 3.3683e-05, 3.3802e-05, 3.3922e-05, 3.4041e-05, 3.4161e-05, 3.4280e-05, 3.4400e-05, 3.4519e-05, 3.4638e-05, 3.4758e-05, 3.4877e-05, 3.4997e-05, 3.5116e-05, 3.5236e-05, 3.5355e-05, 3.5475e-05, 3.5594e-05, 3.5713e-05, 3.5833e-05, 3.5952e-05, 3.6072e-05, 3.6191e-05, 3.6311e-05, 3.6430e-05, 3.6550e-05, 3.6669e-05, 3.6788e-05, 3.6908e-05, 3.7027e-05, 3.7147e-05, 3.7266e-05, 3.7386e-05, 3.7505e-05, 3.7625e-05, 3.7744e-05, 3.7863e-05, 3.7983e-05, 3.8102e-05, 3.8222e-05, 3.8341e-05, 3.8461e-05, 3.8580e-05, 3.8700e-05, 3.8819e-05, 3.8938e-05, 3.9058e-05, 3.9177e-05, 3.9297e-05, 3.9416e-05, 3.9536e-05, 3.9655e-05, 3.9775e-05, 3.9894e-05, 4.0013e-05, 4.0133e-05, 4.0252e-05, 4.0372e-05, 4.0491e-05, 4.0611e-05, 4.0730e-05, 4.0850e-05, 4.0969e-05, 4.1088e-05, 4.1208e-05, 4.1327e-05, 4.1447e-05, 4.1566e-05, 4.1686e-05, 4.1805e-05, 4.1925e-05, 4.2044e-05, 4.2163e-05, 4.2283e-05, 4.2402e-05, 4.2522e-05, 4.2641e-05, 4.2761e-05, 4.2880e-05, 4.2999e-05, 4.3119e-05, 4.3238e-05, 4.3358e-05, 4.3477e-05, 4.3597e-05, 4.3716e-05, 4.3836e-05, 4.3955e-05, 4.4074e-05, 4.4194e-05, 4.4313e-05, 4.4433e-05, 4.4552e-05, 4.4672e-05, 4.4791e-05, 4.4911e-05, 4.5030e-05, 4.5149e-05, 4.5269e-05, 4.5388e-05, 4.5508e-05, 4.5627e-05, 4.5747e-05, 4.5866e-05, 4.5986e-05, 4.6105e-05, 4.6224e-05, 4.6344e-05, 4.6463e-05, 4.6583e-05, 4.6702e-05, 4.6822e-05, 4.6941e-05, 4.7061e-05, 4.7180e-05, 4.7299e-05, 4.7419e-05, 4.7538e-05, 4.7658e-05, 4.7777e-05, 4.7897e-05, 4.8016e-05, 4.8136e-05, 4.8255e-05, 4.8374e-05, 4.8494e-05, 4.8613e-05, 4.8733e-05, 4.8852e-05, 4.8972e-05, 4.9091e-05, 4.9211e-05, 4.9330e-05, 4.9449e-05, 4.9569e-05, 4.9688e-05, 4.9808e-05, 4.9927e-05, 5.0047e-05, 5.0166e-05, 5.0286e-05, 5.0405e-05, 5.0524e-05, 5.0644e-05, 5.0763e-05, 5.0883e-05, 5.1002e-05, 5.1122e-05, 5.1241e-05, 5.1361e-05, 5.1480e-05, 5.1599e-05, 5.1719e-05, 5.1838e-05, 5.1958e-05, 5.2077e-05, 5.2197e-05, 5.2316e-05, 5.2435e-05, 5.2555e-05, 5.2674e-05, 5.2794e-05, 5.2913e-05, 5.3033e-05, 5.3152e-05, 5.3272e-05, 5.3391e-05, 5.3510e-05, 5.3630e-05, 5.3749e-05, 5.3869e-05, 5.3988e-05, 5.4108e-05, 5.4227e-05, 5.4347e-05, 5.4466e-05, 5.4585e-05, 5.4705e-05, 5.4824e-05, 5.4944e-05, 5.5063e-05, 5.5183e-05, 5.5302e-05, 5.5422e-05, 5.5541e-05, 5.5660e-05, 5.5780e-05, 5.5899e-05, 5.6019e-05, 5.6138e-05, 5.6258e-05, 5.6377e-05, 5.6497e-05, 5.6616e-05, 5.6735e-05, 5.6855e-05, 5.6974e-05, 5.7094e-05, 5.7213e-05, 5.7333e-05, 5.7452e-05, 5.7572e-05, 5.7691e-05, 5.7810e-05, 5.7930e-05, 5.8049e-05, 5.8169e-05, 5.8288e-05, 5.8408e-05, 5.8527e-05, 5.8647e-05, 5.8766e-05, 5.8885e-05, 5.9005e-05, 5.9124e-05, 5.9244e-05, 5.9363e-05, 5.9483e-05, 5.9602e-05, 5.9722e-05, 5.9841e-05, 5.9960e-05, 6.0080e-05, 6.0199e-05, 6.0319e-05, 6.0438e-05, 6.0558e-05, 6.0677e-05, 6.0797e-05, 6.0916e-05, // NOLINT - 6.1154e-05, 6.1392e-05, 6.1631e-05, 6.1869e-05, 6.2107e-05, 6.2345e-05, 6.2583e-05, 6.2821e-05, 6.3060e-05, 6.3298e-05, 6.3536e-05, 6.3774e-05, 6.4012e-05, 6.4251e-05, 6.4489e-05, 6.4727e-05, 6.4965e-05, 6.5203e-05, 6.5441e-05, 6.5680e-05, 6.5918e-05, 6.6156e-05, 6.6394e-05, 6.6632e-05, 6.6871e-05, 6.7109e-05, 6.7347e-05, 6.7585e-05, 6.7823e-05, 6.8062e-05, 6.8300e-05, 6.8538e-05, 6.8776e-05, 6.9014e-05, 6.9252e-05, 6.9491e-05, 6.9729e-05, 6.9967e-05, 7.0205e-05, 7.0443e-05, 7.0682e-05, 7.0920e-05, 7.1158e-05, 7.1396e-05, 7.1634e-05, 7.1872e-05, 7.2111e-05, 7.2349e-05, 7.2587e-05, 7.2825e-05, 7.3063e-05, 7.3302e-05, 7.3540e-05, 7.3778e-05, 7.4016e-05, 7.4254e-05, 7.4493e-05, 7.4731e-05, 7.4969e-05, 7.5207e-05, 7.5445e-05, 7.5683e-05, 7.5922e-05, 7.6160e-05, 7.6398e-05, 7.6636e-05, 7.6874e-05, 7.7113e-05, 7.7351e-05, 7.7589e-05, 7.7827e-05, 7.8065e-05, 7.8304e-05, 7.8542e-05, 7.8780e-05, 7.9018e-05, 7.9256e-05, 7.9494e-05, 7.9733e-05, 7.9971e-05, 8.0209e-05, 8.0447e-05, 8.0685e-05, 8.0924e-05, 8.1162e-05, 8.1400e-05, 8.1638e-05, 8.1876e-05, 8.2114e-05, 8.2353e-05, 8.2591e-05, 8.2829e-05, 8.3067e-05, 8.3305e-05, 8.3544e-05, 8.3782e-05, 8.4020e-05, 8.4258e-05, 8.4496e-05, 8.4735e-05, 8.4973e-05, 8.5211e-05, 8.5449e-05, 8.5687e-05, 8.5925e-05, 8.6164e-05, 8.6402e-05, 8.6640e-05, 8.6878e-05, 8.7116e-05, 8.7355e-05, 8.7593e-05, 8.7831e-05, 8.8069e-05, 8.8307e-05, 8.8545e-05, 8.8784e-05, 8.9022e-05, 8.9260e-05, 8.9498e-05, 8.9736e-05, 8.9975e-05, 9.0213e-05, 9.0451e-05, 9.0689e-05, 9.0927e-05, 9.1166e-05, 9.1404e-05, 9.1642e-05, 9.1880e-05, 9.2118e-05, 9.2356e-05, 9.2595e-05, 9.2833e-05, 9.3071e-05, 9.3309e-05, 9.3547e-05, 9.3786e-05, 9.4024e-05, 9.4262e-05, 9.4500e-05, 9.4738e-05, 9.4977e-05, 9.5215e-05, 9.5453e-05, 9.5691e-05, 9.5929e-05, 9.6167e-05, 9.6406e-05, 9.6644e-05, 9.6882e-05, 9.7120e-05, 9.7358e-05, 9.7597e-05, 9.7835e-05, 9.8073e-05, 9.8311e-05, 9.8549e-05, 9.8787e-05, 9.9026e-05, 9.9264e-05, 9.9502e-05, 9.9740e-05, 9.9978e-05, 1.0022e-04, 1.0045e-04, 1.0069e-04, 1.0093e-04, 1.0117e-04, 1.0141e-04, 1.0165e-04, 1.0188e-04, 1.0212e-04, 1.0236e-04, 1.0260e-04, 1.0284e-04, 1.0307e-04, 1.0331e-04, 1.0355e-04, 1.0379e-04, 1.0403e-04, 1.0427e-04, 1.0450e-04, 1.0474e-04, 1.0498e-04, 1.0522e-04, 1.0546e-04, 1.0569e-04, 1.0593e-04, 1.0617e-04, 1.0641e-04, 1.0665e-04, 1.0689e-04, 1.0712e-04, 1.0736e-04, 1.0760e-04, 1.0784e-04, 1.0808e-04, 1.0831e-04, 1.0855e-04, 1.0879e-04, 1.0903e-04, 1.0927e-04, 1.0951e-04, 1.0974e-04, 1.0998e-04, 1.1022e-04, 1.1046e-04, 1.1070e-04, 1.1093e-04, 1.1117e-04, 1.1141e-04, 1.1165e-04, 1.1189e-04, 1.1213e-04, 1.1236e-04, 1.1260e-04, 1.1284e-04, 1.1308e-04, 1.1332e-04, 1.1355e-04, 1.1379e-04, 1.1403e-04, 1.1427e-04, 1.1451e-04, 1.1475e-04, 1.1498e-04, 1.1522e-04, 1.1546e-04, 1.1570e-04, 1.1594e-04, 1.1618e-04, 1.1641e-04, 1.1665e-04, 1.1689e-04, 1.1713e-04, 1.1737e-04, 1.1760e-04, 1.1784e-04, 1.1808e-04, 1.1832e-04, 1.1856e-04, 1.1880e-04, 1.1903e-04, 1.1927e-04, 1.1951e-04, 1.1975e-04, 1.1999e-04, 1.2022e-04, 1.2046e-04, 1.2070e-04, 1.2094e-04, 1.2118e-04, 1.2142e-04, 1.2165e-04, 1.2189e-04, // NOLINT - 1.2213e-04, 1.2237e-04, 1.2261e-04, 1.2284e-04, 1.2308e-04, 1.2332e-04, 1.2356e-04, 1.2380e-04, 1.2404e-04, 1.2427e-04, 1.2451e-04, 1.2475e-04, 1.2499e-04, 1.2523e-04, 1.2546e-04, 1.2570e-04, 1.2594e-04, 1.2618e-04, 1.2642e-04, 1.2666e-04, 1.2689e-04, 1.2713e-04, 1.2737e-04, 1.2761e-04, 1.2785e-04, 1.2808e-04, 1.2832e-04, 1.2856e-04, 1.2880e-04, 1.2904e-04, 1.2928e-04, 1.2951e-04, 1.2975e-04, 1.2999e-04, 1.3023e-04, 1.3047e-04, 1.3070e-04, 1.3094e-04, 1.3118e-04, 1.3142e-04, 1.3166e-04, 1.3190e-04, 1.3213e-04, 1.3237e-04, 1.3261e-04, 1.3285e-04, 1.3309e-04, 1.3332e-04, 1.3356e-04, 1.3380e-04, 1.3404e-04, 1.3428e-04, 1.3452e-04, 1.3475e-04, 1.3499e-04, 1.3523e-04, 1.3547e-04, 1.3571e-04, 1.3594e-04, 1.3618e-04, 1.3642e-04, 1.3666e-04, 1.3690e-04, 1.3714e-04, 1.3737e-04, 1.3761e-04, 1.3785e-04, 1.3809e-04, 1.3833e-04, 1.3856e-04, 1.3880e-04, 1.3904e-04, 1.3928e-04, 1.3952e-04, 1.3976e-04, 1.3999e-04, 1.4023e-04, 1.4047e-04, 1.4071e-04, 1.4095e-04, 1.4118e-04, 1.4142e-04, 1.4166e-04, 1.4190e-04, 1.4214e-04, 1.4238e-04, 1.4261e-04, 1.4285e-04, 1.4309e-04, 1.4333e-04, 1.4357e-04, 1.4380e-04, 1.4404e-04, 1.4428e-04, 1.4452e-04, 1.4476e-04, 1.4500e-04, 1.4523e-04, 1.4547e-04, 1.4571e-04, 1.4595e-04, 1.4619e-04, 1.4642e-04, 1.4666e-04, 1.4690e-04, 1.4714e-04, 1.4738e-04, 1.4762e-04, 1.4785e-04, 1.4809e-04, 1.4833e-04, 1.4857e-04, 1.4881e-04, 1.4904e-04, 1.4928e-04, 1.4952e-04, 1.4976e-04, 1.5000e-04, 1.5024e-04, 1.5047e-04, 1.5071e-04, 1.5095e-04, 1.5119e-04, 1.5143e-04, 1.5166e-04, 1.5190e-04, 1.5214e-04, 1.5238e-04, 1.5262e-04, 1.5286e-04, 1.5309e-04, 1.5333e-04, 1.5357e-04, 1.5381e-04, 1.5405e-04, 1.5428e-04, 1.5452e-04, 1.5476e-04, 1.5500e-04, 1.5524e-04, 1.5548e-04, 1.5571e-04, 1.5595e-04, 1.5619e-04, 1.5643e-04, 1.5667e-04, 1.5690e-04, 1.5714e-04, 1.5738e-04, 1.5762e-04, 1.5786e-04, 1.5810e-04, 1.5833e-04, 1.5857e-04, 1.5881e-04, 1.5905e-04, 1.5929e-04, 1.5952e-04, 1.5976e-04, 1.6000e-04, 1.6024e-04, 1.6048e-04, 1.6072e-04, 1.6095e-04, 1.6119e-04, 1.6143e-04, 1.6167e-04, 1.6191e-04, 1.6214e-04, 1.6238e-04, 1.6262e-04, 1.6286e-04, 1.6310e-04, 1.6334e-04, 1.6357e-04, 1.6381e-04, 1.6405e-04, 1.6429e-04, 1.6453e-04, 1.6476e-04, 1.6500e-04, 1.6524e-04, 1.6548e-04, 1.6572e-04, 1.6596e-04, 1.6619e-04, 1.6643e-04, 1.6667e-04, 1.6691e-04, 1.6715e-04, 1.6738e-04, 1.6762e-04, 1.6786e-04, 1.6810e-04, 1.6834e-04, 1.6858e-04, 1.6881e-04, 1.6905e-04, 1.6929e-04, 1.6953e-04, 1.6977e-04, 1.7001e-04, 1.7024e-04, 1.7048e-04, 1.7072e-04, 1.7096e-04, 1.7120e-04, 1.7143e-04, 1.7167e-04, 1.7191e-04, 1.7215e-04, 1.7239e-04, 1.7263e-04, 1.7286e-04, 1.7310e-04, 1.7334e-04, 1.7358e-04, 1.7382e-04, 1.7405e-04, 1.7429e-04, 1.7453e-04, 1.7477e-04, 1.7501e-04, 1.7525e-04, 1.7548e-04, 1.7572e-04, 1.7596e-04, 1.7620e-04, 1.7644e-04, 1.7667e-04, 1.7691e-04, 1.7715e-04, 1.7739e-04, 1.7763e-04, 1.7787e-04, 1.7810e-04, 1.7834e-04, 1.7858e-04, 1.7882e-04, 1.7906e-04, 1.7929e-04, 1.7953e-04, 1.7977e-04, 1.8001e-04, 1.8025e-04, 1.8049e-04, 1.8072e-04, 1.8096e-04, 1.8120e-04, 1.8144e-04, 1.8168e-04, 1.8191e-04, 1.8215e-04, 1.8239e-04, 1.8263e-04, 1.8287e-04, // NOLINT - 1.8311e-04, 1.8334e-04, 1.8358e-04, 1.8382e-04, 1.8406e-04, 1.8430e-04, 1.8453e-04, 1.8477e-04, 1.8501e-04, 1.8525e-04, 1.8549e-04, 1.8573e-04, 1.8596e-04, 1.8620e-04, 1.8644e-04, 1.8668e-04, 1.8692e-04, 1.8715e-04, 1.8739e-04, 1.8763e-04, 1.8787e-04, 1.8811e-04, 1.8835e-04, 1.8858e-04, 1.8882e-04, 1.8906e-04, 1.8930e-04, 1.8954e-04, 1.8977e-04, 1.9001e-04, 1.9025e-04, 1.9049e-04, 1.9073e-04, 1.9097e-04, 1.9120e-04, 1.9144e-04, 1.9168e-04, 1.9192e-04, 1.9216e-04, 1.9239e-04, 1.9263e-04, 1.9287e-04, 1.9311e-04, 1.9335e-04, 1.9359e-04, 1.9382e-04, 1.9406e-04, 1.9430e-04, 1.9454e-04, 1.9478e-04, 1.9501e-04, 1.9525e-04, 1.9549e-04, 1.9573e-04, 1.9597e-04, 1.9621e-04, 1.9644e-04, 1.9668e-04, 1.9692e-04, 1.9716e-04, 1.9740e-04, 1.9763e-04, 1.9787e-04, 1.9811e-04, 1.9835e-04, 1.9859e-04, 1.9883e-04, 1.9906e-04, 1.9930e-04, 1.9954e-04, 1.9978e-04, 2.0002e-04, 2.0025e-04, 2.0049e-04, 2.0073e-04, 2.0097e-04, 2.0121e-04, 2.0145e-04, 2.0168e-04, 2.0192e-04, 2.0216e-04, 2.0240e-04, 2.0264e-04, 2.0287e-04, 2.0311e-04, 2.0335e-04, 2.0359e-04, 2.0383e-04, 2.0407e-04, 2.0430e-04, 2.0454e-04, 2.0478e-04, 2.0502e-04, 2.0526e-04, 2.0549e-04, 2.0573e-04, 2.0597e-04, 2.0621e-04, 2.0645e-04, 2.0669e-04, 2.0692e-04, 2.0716e-04, 2.0740e-04, 2.0764e-04, 2.0788e-04, 2.0811e-04, 2.0835e-04, 2.0859e-04, 2.0883e-04, 2.0907e-04, 2.0931e-04, 2.0954e-04, 2.0978e-04, 2.1002e-04, 2.1026e-04, 2.1050e-04, 2.1073e-04, 2.1097e-04, 2.1121e-04, 2.1145e-04, 2.1169e-04, 2.1193e-04, 2.1216e-04, 2.1240e-04, 2.1264e-04, 2.1288e-04, 2.1312e-04, 2.1335e-04, 2.1359e-04, 2.1383e-04, 2.1407e-04, 2.1431e-04, 2.1455e-04, 2.1478e-04, 2.1502e-04, 2.1526e-04, 2.1550e-04, 2.1574e-04, 2.1597e-04, 2.1621e-04, 2.1645e-04, 2.1669e-04, 2.1693e-04, 2.1717e-04, 2.1740e-04, 2.1764e-04, 2.1788e-04, 2.1812e-04, 2.1836e-04, 2.1859e-04, 2.1883e-04, 2.1907e-04, 2.1931e-04, 2.1955e-04, 2.1979e-04, 2.2002e-04, 2.2026e-04, 2.2050e-04, 2.2074e-04, 2.2098e-04, 2.2121e-04, 2.2145e-04, 2.2169e-04, 2.2193e-04, 2.2217e-04, 2.2241e-04, 2.2264e-04, 2.2288e-04, 2.2312e-04, 2.2336e-04, 2.2360e-04, 2.2383e-04, 2.2407e-04, 2.2431e-04, 2.2455e-04, 2.2479e-04, 2.2503e-04, 2.2526e-04, 2.2550e-04, 2.2574e-04, 2.2598e-04, 2.2622e-04, 2.2646e-04, 2.2669e-04, 2.2693e-04, 2.2717e-04, 2.2741e-04, 2.2765e-04, 2.2788e-04, 2.2812e-04, 2.2836e-04, 2.2860e-04, 2.2884e-04, 2.2908e-04, 2.2931e-04, 2.2955e-04, 2.2979e-04, 2.3003e-04, 2.3027e-04, 2.3050e-04, 2.3074e-04, 2.3098e-04, 2.3122e-04, 2.3146e-04, 2.3170e-04, 2.3193e-04, 2.3217e-04, 2.3241e-04, 2.3265e-04, 2.3289e-04, 2.3312e-04, 2.3336e-04, 2.3360e-04, 2.3384e-04, 2.3408e-04, 2.3432e-04, 2.3455e-04, 2.3479e-04, 2.3503e-04, 2.3527e-04, 2.3551e-04, 2.3574e-04, 2.3598e-04, 2.3622e-04, 2.3646e-04, 2.3670e-04, 2.3694e-04, 2.3717e-04, 2.3741e-04, 2.3765e-04, 2.3789e-04, 2.3813e-04, 2.3836e-04, 2.3860e-04, 2.3884e-04, 2.3908e-04, 2.3932e-04, 2.3956e-04, 2.3979e-04, 2.4003e-04, 2.4027e-04, 2.4051e-04, 2.4075e-04, 2.4098e-04, 2.4122e-04, 2.4146e-04, 2.4170e-04, 2.4194e-04, 2.4218e-04, 2.4241e-04, 2.4265e-04, 2.4289e-04, 2.4313e-04, 2.4337e-04, 2.4360e-04, 2.4384e-04, // NOLINT - 2.4480e-04, 2.4575e-04, 2.4670e-04, 2.4766e-04, 2.4861e-04, 2.4956e-04, 2.5052e-04, 2.5147e-04, 2.5242e-04, 2.5337e-04, 2.5433e-04, 2.5528e-04, 2.5623e-04, 2.5719e-04, 2.5814e-04, 2.5909e-04, 2.6005e-04, 2.6100e-04, 2.6195e-04, 2.6291e-04, 2.6386e-04, 2.6481e-04, 2.6577e-04, 2.6672e-04, 2.6767e-04, 2.6863e-04, 2.6958e-04, 2.7053e-04, 2.7149e-04, 2.7244e-04, 2.7339e-04, 2.7435e-04, 2.7530e-04, 2.7625e-04, 2.7720e-04, 2.7816e-04, 2.7911e-04, 2.8006e-04, 2.8102e-04, 2.8197e-04, 2.8292e-04, 2.8388e-04, 2.8483e-04, 2.8578e-04, 2.8674e-04, 2.8769e-04, 2.8864e-04, 2.8960e-04, 2.9055e-04, 2.9150e-04, 2.9246e-04, 2.9341e-04, 2.9436e-04, 2.9532e-04, 2.9627e-04, 2.9722e-04, 2.9818e-04, 2.9913e-04, 3.0008e-04, 3.0104e-04, 3.0199e-04, 3.0294e-04, 3.0389e-04, 3.0485e-04, 3.0580e-04, 3.0675e-04, 3.0771e-04, 3.0866e-04, 3.0961e-04, 3.1057e-04, 3.1152e-04, 3.1247e-04, 3.1343e-04, 3.1438e-04, 3.1533e-04, 3.1629e-04, 3.1724e-04, 3.1819e-04, 3.1915e-04, 3.2010e-04, 3.2105e-04, 3.2201e-04, 3.2296e-04, 3.2391e-04, 3.2487e-04, 3.2582e-04, 3.2677e-04, 3.2772e-04, 3.2868e-04, 3.2963e-04, 3.3058e-04, 3.3154e-04, 3.3249e-04, 3.3344e-04, 3.3440e-04, 3.3535e-04, 3.3630e-04, 3.3726e-04, 3.3821e-04, 3.3916e-04, 3.4012e-04, 3.4107e-04, 3.4202e-04, 3.4298e-04, 3.4393e-04, 3.4488e-04, 3.4584e-04, 3.4679e-04, 3.4774e-04, 3.4870e-04, 3.4965e-04, 3.5060e-04, 3.5156e-04, 3.5251e-04, 3.5346e-04, 3.5441e-04, 3.5537e-04, 3.5632e-04, 3.5727e-04, 3.5823e-04, 3.5918e-04, 3.6013e-04, 3.6109e-04, 3.6204e-04, 3.6299e-04, 3.6395e-04, 3.6490e-04, 3.6585e-04, 3.6681e-04, 3.6776e-04, 3.6871e-04, 3.6967e-04, 3.7062e-04, 3.7157e-04, 3.7253e-04, 3.7348e-04, 3.7443e-04, 3.7539e-04, 3.7634e-04, 3.7729e-04, 3.7825e-04, 3.7920e-04, 3.8015e-04, 3.8110e-04, 3.8206e-04, 3.8301e-04, 3.8396e-04, 3.8492e-04, 3.8587e-04, 3.8682e-04, 3.8778e-04, 3.8873e-04, 3.8968e-04, 3.9064e-04, 3.9159e-04, 3.9254e-04, 3.9350e-04, 3.9445e-04, 3.9540e-04, 3.9636e-04, 3.9731e-04, 3.9826e-04, 3.9922e-04, 4.0017e-04, 4.0112e-04, 4.0208e-04, 4.0303e-04, 4.0398e-04, 4.0493e-04, 4.0589e-04, 4.0684e-04, 4.0779e-04, 4.0875e-04, 4.0970e-04, 4.1065e-04, 4.1161e-04, 4.1256e-04, 4.1351e-04, 4.1447e-04, 4.1542e-04, 4.1637e-04, 4.1733e-04, 4.1828e-04, 4.1923e-04, 4.2019e-04, 4.2114e-04, 4.2209e-04, 4.2305e-04, 4.2400e-04, 4.2495e-04, 4.2591e-04, 4.2686e-04, 4.2781e-04, 4.2877e-04, 4.2972e-04, 4.3067e-04, 4.3162e-04, 4.3258e-04, 4.3353e-04, 4.3448e-04, 4.3544e-04, 4.3639e-04, 4.3734e-04, 4.3830e-04, 4.3925e-04, 4.4020e-04, 4.4116e-04, 4.4211e-04, 4.4306e-04, 4.4402e-04, 4.4497e-04, 4.4592e-04, 4.4688e-04, 4.4783e-04, 4.4878e-04, 4.4974e-04, 4.5069e-04, 4.5164e-04, 4.5260e-04, 4.5355e-04, 4.5450e-04, 4.5545e-04, 4.5641e-04, 4.5736e-04, 4.5831e-04, 4.5927e-04, 4.6022e-04, 4.6117e-04, 4.6213e-04, 4.6308e-04, 4.6403e-04, 4.6499e-04, 4.6594e-04, 4.6689e-04, 4.6785e-04, 4.6880e-04, 4.6975e-04, 4.7071e-04, 4.7166e-04, 4.7261e-04, 4.7357e-04, 4.7452e-04, 4.7547e-04, 4.7643e-04, 4.7738e-04, 4.7833e-04, 4.7929e-04, 4.8024e-04, 4.8119e-04, 4.8214e-04, 4.8310e-04, 4.8405e-04, 4.8500e-04, 4.8596e-04, 4.8691e-04, 4.8786e-04, // NOLINT - 4.8977e-04, 4.9168e-04, 4.9358e-04, 4.9549e-04, 4.9740e-04, 4.9931e-04, 5.0121e-04, 5.0312e-04, 5.0503e-04, 5.0693e-04, 5.0884e-04, 5.1075e-04, 5.1265e-04, 5.1456e-04, 5.1647e-04, 5.1837e-04, 5.2028e-04, 5.2219e-04, 5.2409e-04, 5.2600e-04, 5.2791e-04, 5.2982e-04, 5.3172e-04, 5.3363e-04, 5.3554e-04, 5.3744e-04, 5.3935e-04, 5.4126e-04, 5.4316e-04, 5.4507e-04, 5.4698e-04, 5.4888e-04, 5.5079e-04, 5.5270e-04, 5.5460e-04, 5.5651e-04, 5.5842e-04, 5.6033e-04, 5.6223e-04, 5.6414e-04, 5.6605e-04, 5.6795e-04, 5.6986e-04, 5.7177e-04, 5.7367e-04, 5.7558e-04, 5.7749e-04, 5.7939e-04, 5.8130e-04, 5.8321e-04, 5.8512e-04, 5.8702e-04, 5.8893e-04, 5.9084e-04, 5.9274e-04, 5.9465e-04, 5.9656e-04, 5.9846e-04, 6.0037e-04, 6.0228e-04, 6.0418e-04, 6.0609e-04, 6.0800e-04, 6.0990e-04, 6.1181e-04, 6.1372e-04, 6.1563e-04, 6.1753e-04, 6.1944e-04, 6.2135e-04, 6.2325e-04, 6.2516e-04, 6.2707e-04, 6.2897e-04, 6.3088e-04, 6.3279e-04, 6.3469e-04, 6.3660e-04, 6.3851e-04, 6.4041e-04, 6.4232e-04, 6.4423e-04, 6.4614e-04, 6.4804e-04, 6.4995e-04, 6.5186e-04, 6.5376e-04, 6.5567e-04, 6.5758e-04, 6.5948e-04, 6.6139e-04, 6.6330e-04, 6.6520e-04, 6.6711e-04, 6.6902e-04, 6.7092e-04, 6.7283e-04, 6.7474e-04, 6.7665e-04, 6.7855e-04, 6.8046e-04, 6.8237e-04, 6.8427e-04, 6.8618e-04, 6.8809e-04, 6.8999e-04, 6.9190e-04, 6.9381e-04, 6.9571e-04, 6.9762e-04, 6.9953e-04, 7.0143e-04, 7.0334e-04, 7.0525e-04, 7.0716e-04, 7.0906e-04, 7.1097e-04, 7.1288e-04, 7.1478e-04, 7.1669e-04, 7.1860e-04, 7.2050e-04, 7.2241e-04, 7.2432e-04, 7.2622e-04, 7.2813e-04, 7.3004e-04, 7.3195e-04, 7.3385e-04, 7.3576e-04, 7.3767e-04, 7.3957e-04, 7.4148e-04, 7.4339e-04, 7.4529e-04, 7.4720e-04, 7.4911e-04, 7.5101e-04, 7.5292e-04, 7.5483e-04, 7.5673e-04, 7.5864e-04, 7.6055e-04, 7.6246e-04, 7.6436e-04, 7.6627e-04, 7.6818e-04, 7.7008e-04, 7.7199e-04, 7.7390e-04, 7.7580e-04, 7.7771e-04, 7.7962e-04, 7.8152e-04, 7.8343e-04, 7.8534e-04, 7.8724e-04, 7.8915e-04, 7.9106e-04, 7.9297e-04, 7.9487e-04, 7.9678e-04, 7.9869e-04, 8.0059e-04, 8.0250e-04, 8.0441e-04, 8.0631e-04, 8.0822e-04, 8.1013e-04, 8.1203e-04, 8.1394e-04, 8.1585e-04, 8.1775e-04, 8.1966e-04, 8.2157e-04, 8.2348e-04, 8.2538e-04, 8.2729e-04, 8.2920e-04, 8.3110e-04, 8.3301e-04, 8.3492e-04, 8.3682e-04, 8.3873e-04, 8.4064e-04, 8.4254e-04, 8.4445e-04, 8.4636e-04, 8.4826e-04, 8.5017e-04, 8.5208e-04, 8.5399e-04, 8.5589e-04, 8.5780e-04, 8.5971e-04, 8.6161e-04, 8.6352e-04, 8.6543e-04, 8.6733e-04, 8.6924e-04, 8.7115e-04, 8.7305e-04, 8.7496e-04, 8.7687e-04, 8.7878e-04, 8.8068e-04, 8.8259e-04, 8.8450e-04, 8.8640e-04, 8.8831e-04, 8.9022e-04, 8.9212e-04, 8.9403e-04, 8.9594e-04, 8.9784e-04, 8.9975e-04, 9.0166e-04, 9.0356e-04, 9.0547e-04, 9.0738e-04, 9.0929e-04, 9.1119e-04, 9.1310e-04, 9.1501e-04, 9.1691e-04, 9.1882e-04, 9.2073e-04, 9.2263e-04, 9.2454e-04, 9.2645e-04, 9.2835e-04, 9.3026e-04, 9.3217e-04, 9.3407e-04, 9.3598e-04, 9.3789e-04, 9.3980e-04, 9.4170e-04, 9.4361e-04, 9.4552e-04, 9.4742e-04, 9.4933e-04, 9.5124e-04, 9.5314e-04, 9.5505e-04, 9.5696e-04, 9.5886e-04, 9.6077e-04, 9.6268e-04, 9.6458e-04, 9.6649e-04, 9.6840e-04, 9.7031e-04, 9.7221e-04, 9.7412e-04, 9.7603e-04, // NOLINT - 9.7984e-04, 9.8365e-04, 9.8747e-04, 9.9128e-04, 9.9510e-04, 9.9891e-04, 1.0027e-03, 1.0065e-03, 1.0104e-03, 1.0142e-03, 1.0180e-03, 1.0218e-03, 1.0256e-03, 1.0294e-03, 1.0332e-03, 1.0371e-03, 1.0409e-03, 1.0447e-03, 1.0485e-03, 1.0523e-03, 1.0561e-03, 1.0599e-03, 1.0638e-03, 1.0676e-03, 1.0714e-03, 1.0752e-03, 1.0790e-03, 1.0828e-03, 1.0866e-03, 1.0905e-03, 1.0943e-03, 1.0981e-03, 1.1019e-03, 1.1057e-03, 1.1095e-03, 1.1133e-03, 1.1172e-03, 1.1210e-03, 1.1248e-03, 1.1286e-03, 1.1324e-03, 1.1362e-03, 1.1400e-03, 1.1439e-03, 1.1477e-03, 1.1515e-03, 1.1553e-03, 1.1591e-03, 1.1629e-03, 1.1667e-03, 1.1706e-03, 1.1744e-03, 1.1782e-03, 1.1820e-03, 1.1858e-03, 1.1896e-03, 1.1934e-03, 1.1973e-03, 1.2011e-03, 1.2049e-03, 1.2087e-03, 1.2125e-03, 1.2163e-03, 1.2201e-03, 1.2240e-03, 1.2278e-03, 1.2316e-03, 1.2354e-03, 1.2392e-03, 1.2430e-03, 1.2468e-03, 1.2507e-03, 1.2545e-03, 1.2583e-03, 1.2621e-03, 1.2659e-03, 1.2697e-03, 1.2735e-03, 1.2774e-03, 1.2812e-03, 1.2850e-03, 1.2888e-03, 1.2926e-03, 1.2964e-03, 1.3002e-03, 1.3040e-03, 1.3079e-03, 1.3117e-03, 1.3155e-03, 1.3193e-03, 1.3231e-03, 1.3269e-03, 1.3307e-03, 1.3346e-03, 1.3384e-03, 1.3422e-03, 1.3460e-03, 1.3498e-03, 1.3536e-03, 1.3574e-03, 1.3613e-03, 1.3651e-03, 1.3689e-03, 1.3727e-03, 1.3765e-03, 1.3803e-03, 1.3841e-03, 1.3880e-03, 1.3918e-03, 1.3956e-03, 1.3994e-03, 1.4032e-03, 1.4070e-03, 1.4108e-03, 1.4147e-03, 1.4185e-03, 1.4223e-03, 1.4261e-03, 1.4299e-03, 1.4337e-03, 1.4375e-03, 1.4414e-03, 1.4452e-03, 1.4490e-03, 1.4528e-03, 1.4566e-03, 1.4604e-03, 1.4642e-03, 1.4681e-03, 1.4719e-03, 1.4757e-03, 1.4795e-03, 1.4833e-03, 1.4871e-03, 1.4909e-03, 1.4948e-03, 1.4986e-03, 1.5024e-03, 1.5062e-03, 1.5100e-03, 1.5138e-03, 1.5176e-03, 1.5215e-03, 1.5253e-03, 1.5291e-03, 1.5329e-03, 1.5367e-03, 1.5405e-03, 1.5443e-03, 1.5482e-03, 1.5520e-03, 1.5558e-03, 1.5596e-03, 1.5634e-03, 1.5672e-03, 1.5710e-03, 1.5749e-03, 1.5787e-03, 1.5825e-03, 1.5863e-03, 1.5901e-03, 1.5939e-03, 1.5977e-03, 1.6016e-03, 1.6054e-03, 1.6092e-03, 1.6130e-03, 1.6168e-03, 1.6206e-03, 1.6244e-03, 1.6283e-03, 1.6321e-03, 1.6359e-03, 1.6397e-03, 1.6435e-03, 1.6473e-03, 1.6511e-03, 1.6550e-03, 1.6588e-03, 1.6626e-03, 1.6664e-03, 1.6702e-03, 1.6740e-03, 1.6778e-03, 1.6817e-03, 1.6855e-03, 1.6893e-03, 1.6931e-03, 1.6969e-03, 1.7007e-03, 1.7045e-03, 1.7084e-03, 1.7122e-03, 1.7160e-03, 1.7198e-03, 1.7236e-03, 1.7274e-03, 1.7312e-03, 1.7351e-03, 1.7389e-03, 1.7427e-03, 1.7465e-03, 1.7503e-03, 1.7541e-03, 1.7579e-03, 1.7618e-03, 1.7656e-03, 1.7694e-03, 1.7732e-03, 1.7770e-03, 1.7808e-03, 1.7846e-03, 1.7885e-03, 1.7923e-03, 1.7961e-03, 1.7999e-03, 1.8037e-03, 1.8075e-03, 1.8113e-03, 1.8152e-03, 1.8190e-03, 1.8228e-03, 1.8266e-03, 1.8304e-03, 1.8342e-03, 1.8380e-03, 1.8419e-03, 1.8457e-03, 1.8495e-03, 1.8533e-03, 1.8571e-03, 1.8609e-03, 1.8647e-03, 1.8686e-03, 1.8724e-03, 1.8762e-03, 1.8800e-03, 1.8838e-03, 1.8876e-03, 1.8914e-03, 1.8953e-03, 1.8991e-03, 1.9029e-03, 1.9067e-03, 1.9105e-03, 1.9143e-03, 1.9181e-03, 1.9220e-03, 1.9258e-03, 1.9296e-03, 1.9334e-03, 1.9372e-03, 1.9410e-03, 1.9448e-03, 1.9487e-03, 1.9525e-03, // NOLINT - 1.9601e-03, 1.9677e-03, 1.9754e-03, 1.9830e-03, 1.9906e-03, 1.9982e-03, 2.0059e-03, 2.0135e-03, 2.0211e-03, 2.0288e-03, 2.0364e-03, 2.0440e-03, 2.0516e-03, 2.0593e-03, 2.0669e-03, 2.0745e-03, 2.0822e-03, 2.0898e-03, 2.0974e-03, 2.1050e-03, 2.1127e-03, 2.1203e-03, 2.1279e-03, 2.1356e-03, 2.1432e-03, 2.1508e-03, 2.1585e-03, 2.1661e-03, 2.1737e-03, 2.1813e-03, 2.1890e-03, 2.1966e-03, 2.2042e-03, 2.2119e-03, 2.2195e-03, 2.2271e-03, 2.2347e-03, 2.2424e-03, 2.2500e-03, 2.2576e-03, 2.2653e-03, 2.2729e-03, 2.2805e-03, 2.2881e-03, 2.2958e-03, 2.3034e-03, 2.3110e-03, 2.3187e-03, 2.3263e-03, 2.3339e-03, 2.3415e-03, 2.3492e-03, 2.3568e-03, 2.3644e-03, 2.3721e-03, 2.3797e-03, 2.3873e-03, 2.3949e-03, 2.4026e-03, 2.4102e-03, 2.4178e-03, 2.4255e-03, 2.4331e-03, 2.4407e-03, 2.4483e-03, 2.4560e-03, 2.4636e-03, 2.4712e-03, 2.4789e-03, 2.4865e-03, 2.4941e-03, 2.5018e-03, 2.5094e-03, 2.5170e-03, 2.5246e-03, 2.5323e-03, 2.5399e-03, 2.5475e-03, 2.5552e-03, 2.5628e-03, 2.5704e-03, 2.5780e-03, 2.5857e-03, 2.5933e-03, 2.6009e-03, 2.6086e-03, 2.6162e-03, 2.6238e-03, 2.6314e-03, 2.6391e-03, 2.6467e-03, 2.6543e-03, 2.6620e-03, 2.6696e-03, 2.6772e-03, 2.6848e-03, 2.6925e-03, 2.7001e-03, 2.7077e-03, 2.7154e-03, 2.7230e-03, 2.7306e-03, 2.7382e-03, 2.7459e-03, 2.7535e-03, 2.7611e-03, 2.7688e-03, 2.7764e-03, 2.7840e-03, 2.7917e-03, 2.7993e-03, 2.8069e-03, 2.8145e-03, 2.8222e-03, 2.8298e-03, 2.8374e-03, 2.8451e-03, 2.8527e-03, 2.8603e-03, 2.8679e-03, 2.8756e-03, 2.8832e-03, 2.8908e-03, 2.8985e-03, 2.9061e-03, 2.9137e-03, 2.9213e-03, 2.9290e-03, 2.9366e-03, 2.9442e-03, 2.9519e-03, 2.9595e-03, 2.9671e-03, 2.9747e-03, 2.9824e-03, 2.9900e-03, 2.9976e-03, 3.0053e-03, 3.0129e-03, 3.0205e-03, 3.0281e-03, 3.0358e-03, 3.0434e-03, 3.0510e-03, 3.0587e-03, 3.0663e-03, 3.0739e-03, 3.0816e-03, 3.0892e-03, 3.0968e-03, 3.1044e-03, 3.1121e-03, 3.1197e-03, 3.1273e-03, 3.1350e-03, 3.1426e-03, 3.1502e-03, 3.1578e-03, 3.1655e-03, 3.1731e-03, 3.1807e-03, 3.1884e-03, 3.1960e-03, 3.2036e-03, 3.2112e-03, 3.2189e-03, 3.2265e-03, 3.2341e-03, 3.2418e-03, 3.2494e-03, 3.2570e-03, 3.2646e-03, 3.2723e-03, 3.2799e-03, 3.2875e-03, 3.2952e-03, 3.3028e-03, 3.3104e-03, 3.3180e-03, 3.3257e-03, 3.3333e-03, 3.3409e-03, 3.3486e-03, 3.3562e-03, 3.3638e-03, 3.3715e-03, 3.3791e-03, 3.3867e-03, 3.3943e-03, 3.4020e-03, 3.4096e-03, 3.4172e-03, 3.4249e-03, 3.4325e-03, 3.4401e-03, 3.4477e-03, 3.4554e-03, 3.4630e-03, 3.4706e-03, 3.4783e-03, 3.4859e-03, 3.4935e-03, 3.5011e-03, 3.5088e-03, 3.5164e-03, 3.5240e-03, 3.5317e-03, 3.5393e-03, 3.5469e-03, 3.5545e-03, 3.5622e-03, 3.5698e-03, 3.5774e-03, 3.5851e-03, 3.5927e-03, 3.6003e-03, 3.6079e-03, 3.6156e-03, 3.6232e-03, 3.6308e-03, 3.6385e-03, 3.6461e-03, 3.6537e-03, 3.6613e-03, 3.6690e-03, 3.6766e-03, 3.6842e-03, 3.6919e-03, 3.6995e-03, 3.7071e-03, 3.7148e-03, 3.7224e-03, 3.7300e-03, 3.7376e-03, 3.7453e-03, 3.7529e-03, 3.7605e-03, 3.7682e-03, 3.7758e-03, 3.7834e-03, 3.7910e-03, 3.7987e-03, 3.8063e-03, 3.8139e-03, 3.8216e-03, 3.8292e-03, 3.8368e-03, 3.8444e-03, 3.8521e-03, 3.8597e-03, 3.8673e-03, 3.8750e-03, 3.8826e-03, 3.8902e-03, 3.8978e-03, 3.9055e-03, // NOLINT - 3.9207e-03, 3.9360e-03, 3.9513e-03, 3.9665e-03, 3.9818e-03, 3.9970e-03, 4.0123e-03, 4.0275e-03, 4.0428e-03, 4.0581e-03, 4.0733e-03, 4.0886e-03, 4.1038e-03, 4.1191e-03, 4.1343e-03, 4.1496e-03, 4.1649e-03, 4.1801e-03, 4.1954e-03, 4.2106e-03, 4.2259e-03, 4.2412e-03, 4.2564e-03, 4.2717e-03, 4.2869e-03, 4.3022e-03, 4.3174e-03, 4.3327e-03, 4.3480e-03, 4.3632e-03, 4.3785e-03, 4.3937e-03, 4.4090e-03, 4.4243e-03, 4.4395e-03, 4.4548e-03, 4.4700e-03, 4.4853e-03, 4.5005e-03, 4.5158e-03, 4.5311e-03, 4.5463e-03, 4.5616e-03, 4.5768e-03, 4.5921e-03, 4.6074e-03, 4.6226e-03, 4.6379e-03, 4.6531e-03, 4.6684e-03, 4.6836e-03, 4.6989e-03, 4.7142e-03, 4.7294e-03, 4.7447e-03, 4.7599e-03, 4.7752e-03, 4.7905e-03, 4.8057e-03, 4.8210e-03, 4.8362e-03, 4.8515e-03, 4.8667e-03, 4.8820e-03, 4.8973e-03, 4.9125e-03, 4.9278e-03, 4.9430e-03, 4.9583e-03, 4.9736e-03, 4.9888e-03, 5.0041e-03, 5.0193e-03, 5.0346e-03, 5.0498e-03, 5.0651e-03, 5.0804e-03, 5.0956e-03, 5.1109e-03, 5.1261e-03, 5.1414e-03, 5.1567e-03, 5.1719e-03, 5.1872e-03, 5.2024e-03, 5.2177e-03, 5.2329e-03, 5.2482e-03, 5.2635e-03, 5.2787e-03, 5.2940e-03, 5.3092e-03, 5.3245e-03, 5.3398e-03, 5.3550e-03, 5.3703e-03, 5.3855e-03, 5.4008e-03, 5.4160e-03, 5.4313e-03, 5.4466e-03, 5.4618e-03, 5.4771e-03, 5.4923e-03, 5.5076e-03, 5.5229e-03, 5.5381e-03, 5.5534e-03, 5.5686e-03, 5.5839e-03, 5.5991e-03, 5.6144e-03, 5.6297e-03, 5.6449e-03, 5.6602e-03, 5.6754e-03, 5.6907e-03, 5.7060e-03, 5.7212e-03, 5.7365e-03, 5.7517e-03, 5.7670e-03, 5.7822e-03, 5.7975e-03, 5.8128e-03, 5.8280e-03, 5.8433e-03, 5.8585e-03, 5.8738e-03, 5.8891e-03, 5.9043e-03, 5.9196e-03, 5.9348e-03, 5.9501e-03, 5.9653e-03, 5.9806e-03, 5.9959e-03, 6.0111e-03, 6.0264e-03, 6.0416e-03, 6.0569e-03, 6.0722e-03, 6.0874e-03, 6.1027e-03, 6.1179e-03, 6.1332e-03, 6.1484e-03, 6.1637e-03, 6.1790e-03, 6.1942e-03, 6.2095e-03, 6.2247e-03, 6.2400e-03, 6.2553e-03, 6.2705e-03, 6.2858e-03, 6.3010e-03, 6.3163e-03, 6.3315e-03, 6.3468e-03, 6.3621e-03, 6.3773e-03, 6.3926e-03, 6.4078e-03, 6.4231e-03, 6.4384e-03, 6.4536e-03, 6.4689e-03, 6.4841e-03, 6.4994e-03, 6.5146e-03, 6.5299e-03, 6.5452e-03, 6.5604e-03, 6.5757e-03, 6.5909e-03, 6.6062e-03, 6.6215e-03, 6.6367e-03, 6.6520e-03, 6.6672e-03, 6.6825e-03, 6.6977e-03, 6.7130e-03, 6.7283e-03, 6.7435e-03, 6.7588e-03, 6.7740e-03, 6.7893e-03, 6.8046e-03, 6.8198e-03, 6.8351e-03, 6.8503e-03, 6.8656e-03, 6.8808e-03, 6.8961e-03, 6.9114e-03, 6.9266e-03, 6.9419e-03, 6.9571e-03, 6.9724e-03, 6.9877e-03, 7.0029e-03, 7.0182e-03, 7.0334e-03, 7.0487e-03, 7.0639e-03, 7.0792e-03, 7.0945e-03, 7.1097e-03, 7.1250e-03, 7.1402e-03, 7.1555e-03, 7.1708e-03, 7.1860e-03, 7.2013e-03, 7.2165e-03, 7.2318e-03, 7.2470e-03, 7.2623e-03, 7.2776e-03, 7.2928e-03, 7.3081e-03, 7.3233e-03, 7.3386e-03, 7.3539e-03, 7.3691e-03, 7.3844e-03, 7.3996e-03, 7.4149e-03, 7.4301e-03, 7.4454e-03, 7.4607e-03, 7.4759e-03, 7.4912e-03, 7.5064e-03, 7.5217e-03, 7.5370e-03, 7.5522e-03, 7.5675e-03, 7.5827e-03, 7.5980e-03, 7.6132e-03, 7.6285e-03, 7.6438e-03, 7.6590e-03, 7.6743e-03, 7.6895e-03, 7.7048e-03, 7.7201e-03, 7.7353e-03, 7.7506e-03, 7.7658e-03, 7.7811e-03, 7.7963e-03, 7.8116e-03, // NOLINT - 7.8421e-03, 7.8726e-03, 7.9032e-03, 7.9337e-03, 7.9642e-03, 7.9947e-03, 8.0252e-03, 8.0557e-03, 8.0863e-03, 8.1168e-03, 8.1473e-03, 8.1778e-03, 8.2083e-03, 8.2388e-03, 8.2694e-03, 8.2999e-03, 8.3304e-03, 8.3609e-03, 8.3914e-03, 8.4219e-03, 8.4525e-03, 8.4830e-03, 8.5135e-03, 8.5440e-03, 8.5745e-03, 8.6051e-03, 8.6356e-03, 8.6661e-03, 8.6966e-03, 8.7271e-03, 8.7576e-03, 8.7882e-03, 8.8187e-03, 8.8492e-03, 8.8797e-03, 8.9102e-03, 8.9407e-03, 8.9713e-03, 9.0018e-03, 9.0323e-03, 9.0628e-03, 9.0933e-03, 9.1238e-03, 9.1544e-03, 9.1849e-03, 9.2154e-03, 9.2459e-03, 9.2764e-03, 9.3069e-03, 9.3375e-03, 9.3680e-03, 9.3985e-03, 9.4290e-03, 9.4595e-03, 9.4900e-03, 9.5206e-03, 9.5511e-03, 9.5816e-03, 9.6121e-03, 9.6426e-03, 9.6731e-03, 9.7037e-03, 9.7342e-03, 9.7647e-03, 9.7952e-03, 9.8257e-03, 9.8563e-03, 9.8868e-03, 9.9173e-03, 9.9478e-03, 9.9783e-03, 1.0009e-02, 1.0039e-02, 1.0070e-02, 1.0100e-02, 1.0131e-02, 1.0161e-02, 1.0192e-02, 1.0222e-02, 1.0253e-02, 1.0283e-02, 1.0314e-02, 1.0345e-02, 1.0375e-02, 1.0406e-02, 1.0436e-02, 1.0467e-02, 1.0497e-02, 1.0528e-02, 1.0558e-02, 1.0589e-02, 1.0619e-02, 1.0650e-02, 1.0680e-02, 1.0711e-02, 1.0741e-02, 1.0772e-02, 1.0802e-02, 1.0833e-02, 1.0863e-02, 1.0894e-02, 1.0924e-02, 1.0955e-02, 1.0985e-02, 1.1016e-02, 1.1046e-02, 1.1077e-02, 1.1107e-02, 1.1138e-02, 1.1168e-02, 1.1199e-02, 1.1230e-02, 1.1260e-02, 1.1291e-02, 1.1321e-02, 1.1352e-02, 1.1382e-02, 1.1413e-02, 1.1443e-02, 1.1474e-02, 1.1504e-02, 1.1535e-02, 1.1565e-02, 1.1596e-02, 1.1626e-02, 1.1657e-02, 1.1687e-02, 1.1718e-02, 1.1748e-02, 1.1779e-02, 1.1809e-02, 1.1840e-02, 1.1870e-02, 1.1901e-02, 1.1931e-02, 1.1962e-02, 1.1992e-02, 1.2023e-02, 1.2053e-02, 1.2084e-02, 1.2115e-02, 1.2145e-02, 1.2176e-02, 1.2206e-02, 1.2237e-02, 1.2267e-02, 1.2298e-02, 1.2328e-02, 1.2359e-02, 1.2389e-02, 1.2420e-02, 1.2450e-02, 1.2481e-02, 1.2511e-02, 1.2542e-02, 1.2572e-02, 1.2603e-02, 1.2633e-02, 1.2664e-02, 1.2694e-02, 1.2725e-02, 1.2755e-02, 1.2786e-02, 1.2816e-02, 1.2847e-02, 1.2877e-02, 1.2908e-02, 1.2938e-02, 1.2969e-02, 1.3000e-02, 1.3030e-02, 1.3061e-02, 1.3091e-02, 1.3122e-02, 1.3152e-02, 1.3183e-02, 1.3213e-02, 1.3244e-02, 1.3274e-02, 1.3305e-02, 1.3335e-02, 1.3366e-02, 1.3396e-02, 1.3427e-02, 1.3457e-02, 1.3488e-02, 1.3518e-02, 1.3549e-02, 1.3579e-02, 1.3610e-02, 1.3640e-02, 1.3671e-02, 1.3701e-02, 1.3732e-02, 1.3762e-02, 1.3793e-02, 1.3823e-02, 1.3854e-02, 1.3885e-02, 1.3915e-02, 1.3946e-02, 1.3976e-02, 1.4007e-02, 1.4037e-02, 1.4068e-02, 1.4098e-02, 1.4129e-02, 1.4159e-02, 1.4190e-02, 1.4220e-02, 1.4251e-02, 1.4281e-02, 1.4312e-02, 1.4342e-02, 1.4373e-02, 1.4403e-02, 1.4434e-02, 1.4464e-02, 1.4495e-02, 1.4525e-02, 1.4556e-02, 1.4586e-02, 1.4617e-02, 1.4647e-02, 1.4678e-02, 1.4708e-02, 1.4739e-02, 1.4770e-02, 1.4800e-02, 1.4831e-02, 1.4861e-02, 1.4892e-02, 1.4922e-02, 1.4953e-02, 1.4983e-02, 1.5014e-02, 1.5044e-02, 1.5075e-02, 1.5105e-02, 1.5136e-02, 1.5166e-02, 1.5197e-02, 1.5227e-02, 1.5258e-02, 1.5288e-02, 1.5319e-02, 1.5349e-02, 1.5380e-02, 1.5410e-02, 1.5441e-02, 1.5471e-02, 1.5502e-02, 1.5532e-02, 1.5563e-02, 1.5593e-02, 1.5624e-02, // NOLINT - 1.5746e-02, 1.5868e-02, 1.5990e-02, 1.6112e-02, 1.6234e-02, 1.6356e-02, 1.6478e-02, 1.6601e-02, 1.6723e-02, 1.6845e-02, 1.6967e-02, 1.7089e-02, 1.7211e-02, 1.7333e-02, 1.7455e-02, 1.7577e-02, 1.7699e-02, 1.7821e-02, 1.7943e-02, 1.8065e-02, 1.8187e-02, 1.8310e-02, 1.8432e-02, 1.8554e-02, 1.8676e-02, 1.8798e-02, 1.8920e-02, 1.9042e-02, 1.9164e-02, 1.9286e-02, 1.9408e-02, 1.9530e-02, 1.9652e-02, 1.9774e-02, 1.9896e-02, 2.0018e-02, 2.0141e-02, 2.0263e-02, 2.0385e-02, 2.0507e-02, 2.0629e-02, 2.0751e-02, 2.0873e-02, 2.0995e-02, 2.1117e-02, 2.1239e-02, 2.1361e-02, 2.1483e-02, 2.1605e-02, 2.1727e-02, 2.1850e-02, 2.1972e-02, 2.2094e-02, 2.2216e-02, 2.2338e-02, 2.2460e-02, 2.2582e-02, 2.2704e-02, 2.2826e-02, 2.2948e-02, 2.3070e-02, 2.3192e-02, 2.3314e-02, 2.3436e-02, 2.3558e-02, 2.3681e-02, 2.3803e-02, 2.3925e-02, 2.4047e-02, 2.4169e-02, 2.4291e-02, 2.4413e-02, 2.4535e-02, 2.4657e-02, 2.4779e-02, 2.4901e-02, 2.5023e-02, 2.5145e-02, 2.5267e-02, 2.5390e-02, 2.5512e-02, 2.5634e-02, 2.5756e-02, 2.5878e-02, 2.6000e-02, 2.6122e-02, 2.6244e-02, 2.6366e-02, 2.6488e-02, 2.6610e-02, 2.6732e-02, 2.6854e-02, 2.6976e-02, 2.7099e-02, 2.7221e-02, 2.7343e-02, 2.7465e-02, 2.7587e-02, 2.7709e-02, 2.7831e-02, 2.7953e-02, 2.8075e-02, 2.8197e-02, 2.8319e-02, 2.8441e-02, 2.8563e-02, 2.8685e-02, 2.8807e-02, 2.8930e-02, 2.9052e-02, 2.9174e-02, 2.9296e-02, 2.9418e-02, 2.9540e-02, 2.9662e-02, 2.9784e-02, 2.9906e-02, 3.0028e-02, 3.0150e-02, 3.0272e-02, 3.0394e-02, 3.0516e-02, 3.0639e-02, 3.0761e-02, 3.0883e-02, 3.1005e-02, 3.1127e-02, 3.1249e-02, 3.1493e-02, 3.1737e-02, 3.1981e-02, 3.2225e-02, 3.2470e-02, 3.2714e-02, 3.2958e-02, 3.3202e-02, 3.3446e-02, 3.3690e-02, 3.3934e-02, 3.4179e-02, 3.4423e-02, 3.4667e-02, 3.4911e-02, 3.5155e-02, 3.5399e-02, 3.5643e-02, 3.5888e-02, 3.6132e-02, 3.6376e-02, 3.6620e-02, 3.6864e-02, 3.7108e-02, 3.7352e-02, 3.7596e-02, 3.7841e-02, 3.8085e-02, 3.8329e-02, 3.8573e-02, 3.8817e-02, 3.9061e-02, 3.9305e-02, 3.9550e-02, 3.9794e-02, 4.0038e-02, 4.0282e-02, 4.0526e-02, 4.0770e-02, 4.1014e-02, 4.1259e-02, 4.1503e-02, 4.1747e-02, 4.1991e-02, 4.2235e-02, 4.2479e-02, 4.2723e-02, 4.2968e-02, 4.3212e-02, 4.3456e-02, 4.3700e-02, 4.3944e-02, 4.4188e-02, 4.4432e-02, 4.4677e-02, 4.4921e-02, 4.5165e-02, 4.5409e-02, 4.5653e-02, 4.5897e-02, 4.6141e-02, 4.6386e-02, 4.6630e-02, 4.6874e-02, 4.7118e-02, 4.7362e-02, 4.7606e-02, 4.7850e-02, 4.8095e-02, 4.8339e-02, 4.8583e-02, 4.8827e-02, 4.9071e-02, 4.9315e-02, 4.9559e-02, 4.9803e-02, 5.0048e-02, 5.0292e-02, 5.0536e-02, 5.0780e-02, 5.1024e-02, 5.1268e-02, 5.1512e-02, 5.1757e-02, 5.2001e-02, 5.2245e-02, 5.2489e-02, 5.2733e-02, 5.2977e-02, 5.3221e-02, 5.3466e-02, 5.3710e-02, 5.3954e-02, 5.4198e-02, 5.4442e-02, 5.4686e-02, 5.4930e-02, 5.5175e-02, 5.5419e-02, 5.5663e-02, 5.5907e-02, 5.6151e-02, 5.6395e-02, 5.6639e-02, 5.6884e-02, 5.7128e-02, 5.7372e-02, 5.7616e-02, 5.7860e-02, 5.8104e-02, 5.8348e-02, 5.8593e-02, 5.8837e-02, 5.9081e-02, 5.9325e-02, 5.9569e-02, 5.9813e-02, 6.0057e-02, 6.0301e-02, 6.0546e-02, 6.0790e-02, 6.1034e-02, 6.1278e-02, 6.1522e-02, 6.1766e-02, 6.2010e-02, 6.2255e-02, 6.2499e-02, // NOLINT - 6.2743e-02, 6.2987e-02, 6.3231e-02, 6.3475e-02, 6.3719e-02, 6.3964e-02, 6.4208e-02, 6.4452e-02, 6.4696e-02, 6.4940e-02, 6.5184e-02, 6.5428e-02, 6.5673e-02, 6.5917e-02, 6.6161e-02, 6.6405e-02, 6.6649e-02, 6.6893e-02, 6.7137e-02, 6.7382e-02, 6.7626e-02, 6.7870e-02, 6.8114e-02, 6.8358e-02, 6.8602e-02, 6.8846e-02, 6.9091e-02, 6.9335e-02, 6.9579e-02, 6.9823e-02, 7.0067e-02, 7.0311e-02, 7.0555e-02, 7.0799e-02, 7.1044e-02, 7.1288e-02, 7.1532e-02, 7.1776e-02, 7.2020e-02, 7.2264e-02, 7.2508e-02, 7.2753e-02, 7.2997e-02, 7.3241e-02, 7.3485e-02, 7.3729e-02, 7.3973e-02, 7.4217e-02, 7.4462e-02, 7.4706e-02, 7.4950e-02, 7.5194e-02, 7.5438e-02, 7.5682e-02, 7.5926e-02, 7.6171e-02, 7.6415e-02, 7.6659e-02, 7.6903e-02, 7.7147e-02, 7.7391e-02, 7.7635e-02, 7.7880e-02, 7.8124e-02, 7.8368e-02, 7.8612e-02, 7.8856e-02, 7.9100e-02, 7.9344e-02, 7.9589e-02, 7.9833e-02, 8.0077e-02, 8.0321e-02, 8.0565e-02, 8.0809e-02, 8.1053e-02, 8.1298e-02, 8.1542e-02, 8.1786e-02, 8.2030e-02, 8.2274e-02, 8.2518e-02, 8.2762e-02, 8.3006e-02, 8.3251e-02, 8.3495e-02, 8.3739e-02, 8.3983e-02, 8.4227e-02, 8.4471e-02, 8.4715e-02, 8.4960e-02, 8.5204e-02, 8.5448e-02, 8.5692e-02, 8.5936e-02, 8.6180e-02, 8.6424e-02, 8.6669e-02, 8.6913e-02, 8.7157e-02, 8.7401e-02, 8.7645e-02, 8.7889e-02, 8.8133e-02, 8.8378e-02, 8.8622e-02, 8.8866e-02, 8.9110e-02, 8.9354e-02, 8.9598e-02, 8.9842e-02, 9.0087e-02, 9.0331e-02, 9.0575e-02, 9.0819e-02, 9.1063e-02, 9.1307e-02, 9.1551e-02, 9.1796e-02, 9.2040e-02, 9.2284e-02, 9.2528e-02, 9.2772e-02, 9.3016e-02, 9.3260e-02, 9.3504e-02, 9.3749e-02, 9.4237e-02, 9.4725e-02, 9.5213e-02, 9.5702e-02, 9.6190e-02, 9.6678e-02, 9.7167e-02, 9.7655e-02, 9.8143e-02, 9.8631e-02, 9.9120e-02, 9.9608e-02, 1.0010e-01, 1.0058e-01, 1.0107e-01, 1.0156e-01, 1.0205e-01, 1.0254e-01, 1.0303e-01, 1.0351e-01, 1.0400e-01, 1.0449e-01, 1.0498e-01, 1.0547e-01, 1.0596e-01, 1.0644e-01, 1.0693e-01, 1.0742e-01, 1.0791e-01, 1.0840e-01, 1.0889e-01, 1.0937e-01, 1.0986e-01, 1.1035e-01, 1.1084e-01, 1.1133e-01, 1.1182e-01, 1.1230e-01, 1.1279e-01, 1.1328e-01, 1.1377e-01, 1.1426e-01, 1.1474e-01, 1.1523e-01, 1.1572e-01, 1.1621e-01, 1.1670e-01, 1.1719e-01, 1.1767e-01, 1.1816e-01, 1.1865e-01, 1.1914e-01, 1.1963e-01, 1.2012e-01, 1.2060e-01, 1.2109e-01, 1.2158e-01, 1.2207e-01, 1.2256e-01, 1.2305e-01, 1.2353e-01, 1.2402e-01, 1.2451e-01, 1.2500e-01, 1.2549e-01, 1.2598e-01, 1.2646e-01, 1.2695e-01, 1.2744e-01, 1.2793e-01, 1.2842e-01, 1.2890e-01, 1.2939e-01, 1.2988e-01, 1.3037e-01, 1.3086e-01, 1.3135e-01, 1.3183e-01, 1.3232e-01, 1.3281e-01, 1.3330e-01, 1.3379e-01, 1.3428e-01, 1.3476e-01, 1.3525e-01, 1.3574e-01, 1.3623e-01, 1.3672e-01, 1.3721e-01, 1.3769e-01, 1.3818e-01, 1.3867e-01, 1.3916e-01, 1.3965e-01, 1.4014e-01, 1.4062e-01, 1.4111e-01, 1.4160e-01, 1.4209e-01, 1.4258e-01, 1.4306e-01, 1.4355e-01, 1.4404e-01, 1.4453e-01, 1.4502e-01, 1.4551e-01, 1.4599e-01, 1.4648e-01, 1.4697e-01, 1.4746e-01, 1.4795e-01, 1.4844e-01, 1.4892e-01, 1.4941e-01, 1.4990e-01, 1.5039e-01, 1.5088e-01, 1.5137e-01, 1.5185e-01, 1.5234e-01, 1.5283e-01, 1.5332e-01, 1.5381e-01, 1.5430e-01, 1.5478e-01, 1.5527e-01, 1.5576e-01, 1.5625e-01, // NOLINT - 1.5674e-01, 1.5723e-01, 1.5771e-01, 1.5820e-01, 1.5869e-01, 1.5918e-01, 1.5967e-01, 1.6015e-01, 1.6064e-01, 1.6113e-01, 1.6162e-01, 1.6211e-01, 1.6260e-01, 1.6308e-01, 1.6357e-01, 1.6406e-01, 1.6455e-01, 1.6504e-01, 1.6553e-01, 1.6601e-01, 1.6650e-01, 1.6699e-01, 1.6748e-01, 1.6797e-01, 1.6846e-01, 1.6894e-01, 1.6943e-01, 1.6992e-01, 1.7041e-01, 1.7090e-01, 1.7139e-01, 1.7187e-01, 1.7236e-01, 1.7285e-01, 1.7334e-01, 1.7383e-01, 1.7431e-01, 1.7480e-01, 1.7529e-01, 1.7578e-01, 1.7627e-01, 1.7676e-01, 1.7724e-01, 1.7773e-01, 1.7822e-01, 1.7871e-01, 1.7920e-01, 1.7969e-01, 1.8017e-01, 1.8066e-01, 1.8115e-01, 1.8164e-01, 1.8213e-01, 1.8262e-01, 1.8310e-01, 1.8359e-01, 1.8408e-01, 1.8457e-01, 1.8506e-01, 1.8555e-01, 1.8603e-01, 1.8652e-01, 1.8701e-01, 1.8750e-01, 1.8848e-01, 1.8945e-01, 1.9043e-01, 1.9140e-01, 1.9238e-01, 1.9336e-01, 1.9433e-01, 1.9531e-01, 1.9629e-01, 1.9726e-01, 1.9824e-01, 1.9922e-01, 2.0019e-01, 2.0117e-01, 2.0215e-01, 2.0312e-01, 2.0410e-01, 2.0508e-01, 2.0605e-01, 2.0703e-01, 2.0801e-01, 2.0898e-01, 2.0996e-01, 2.1094e-01, 2.1191e-01, 2.1289e-01, 2.1387e-01, 2.1484e-01, 2.1582e-01, 2.1680e-01, 2.1777e-01, 2.1875e-01, 2.1972e-01, 2.2070e-01, 2.2168e-01, 2.2265e-01, 2.2363e-01, 2.2461e-01, 2.2558e-01, 2.2656e-01, 2.2754e-01, 2.2851e-01, 2.2949e-01, 2.3047e-01, 2.3144e-01, 2.3242e-01, 2.3340e-01, 2.3437e-01, 2.3535e-01, 2.3633e-01, 2.3730e-01, 2.3828e-01, 2.3926e-01, 2.4023e-01, 2.4121e-01, 2.4219e-01, 2.4316e-01, 2.4414e-01, 2.4512e-01, 2.4609e-01, 2.4707e-01, 2.4805e-01, 2.4902e-01, 2.5000e-01, 2.5097e-01, 2.5195e-01, 2.5293e-01, 2.5390e-01, 2.5488e-01, 2.5586e-01, 2.5683e-01, 2.5781e-01, 2.5879e-01, 2.5976e-01, 2.6074e-01, 2.6172e-01, 2.6269e-01, 2.6367e-01, 2.6465e-01, 2.6562e-01, 2.6660e-01, 2.6758e-01, 2.6855e-01, 2.6953e-01, 2.7051e-01, 2.7148e-01, 2.7246e-01, 2.7344e-01, 2.7441e-01, 2.7539e-01, 2.7637e-01, 2.7734e-01, 2.7832e-01, 2.7930e-01, 2.8027e-01, 2.8125e-01, 2.8222e-01, 2.8320e-01, 2.8418e-01, 2.8515e-01, 2.8613e-01, 2.8711e-01, 2.8808e-01, 2.8906e-01, 2.9004e-01, 2.9101e-01, 2.9199e-01, 2.9297e-01, 2.9394e-01, 2.9492e-01, 2.9590e-01, 2.9687e-01, 2.9785e-01, 2.9883e-01, 2.9980e-01, 3.0078e-01, 3.0176e-01, 3.0273e-01, 3.0371e-01, 3.0469e-01, 3.0566e-01, 3.0664e-01, 3.0762e-01, 3.0859e-01, 3.0957e-01, 3.1055e-01, 3.1152e-01, 3.1250e-01, 3.1347e-01, 3.1445e-01, 3.1543e-01, 3.1640e-01, 3.1738e-01, 3.1836e-01, 3.1933e-01, 3.2031e-01, 3.2129e-01, 3.2226e-01, 3.2324e-01, 3.2422e-01, 3.2519e-01, 3.2617e-01, 3.2715e-01, 3.2812e-01, 3.2910e-01, 3.3008e-01, 3.3105e-01, 3.3203e-01, 3.3301e-01, 3.3398e-01, 3.3496e-01, 3.3594e-01, 3.3691e-01, 3.3789e-01, 3.3887e-01, 3.3984e-01, 3.4082e-01, 3.4180e-01, 3.4277e-01, 3.4375e-01, 3.4472e-01, 3.4570e-01, 3.4668e-01, 3.4765e-01, 3.4863e-01, 3.4961e-01, 3.5058e-01, 3.5156e-01, 3.5254e-01, 3.5351e-01, 3.5449e-01, 3.5547e-01, 3.5644e-01, 3.5742e-01, 3.5840e-01, 3.5937e-01, 3.6035e-01, 3.6133e-01, 3.6230e-01, 3.6328e-01, 3.6426e-01, 3.6523e-01, 3.6621e-01, 3.6719e-01, 3.6816e-01, 3.6914e-01, 3.7012e-01, 3.7109e-01, 3.7207e-01, 3.7305e-01, 3.7402e-01, 3.7500e-01, // NOLINT - 3.7695e-01, 3.7890e-01, 3.8086e-01, 3.8281e-01, 3.8476e-01, 3.8672e-01, 3.8867e-01, 3.9062e-01, 3.9258e-01, 3.9453e-01, 3.9648e-01, 3.9844e-01, 4.0039e-01, 4.0234e-01, 4.0430e-01, 4.0625e-01, 4.0820e-01, 4.1015e-01, 4.1211e-01, 4.1406e-01, 4.1601e-01, 4.1797e-01, 4.1992e-01, 4.2187e-01, 4.2383e-01, 4.2578e-01, 4.2773e-01, 4.2969e-01, 4.3164e-01, 4.3359e-01, 4.3555e-01, 4.3750e-01, 4.3945e-01, 4.4140e-01, 4.4336e-01, 4.4531e-01, 4.4726e-01, 4.4922e-01, 4.5117e-01, 4.5312e-01, 4.5508e-01, 4.5703e-01, 4.5898e-01, 4.6094e-01, 4.6289e-01, 4.6484e-01, 4.6680e-01, 4.6875e-01, 4.7070e-01, 4.7265e-01, 4.7461e-01, 4.7656e-01, 4.7851e-01, 4.8047e-01, 4.8242e-01, 4.8437e-01, 4.8633e-01, 4.8828e-01, 4.9023e-01, 4.9219e-01, 4.9414e-01, 4.9609e-01, 4.9805e-01, 5.0000e-01, 5.0195e-01, 5.0390e-01, 5.0586e-01, 5.0781e-01, 5.0976e-01, 5.1172e-01, 5.1367e-01, 5.1562e-01, 5.1758e-01, 5.1953e-01, 5.2148e-01, 5.2344e-01, 5.2539e-01, 5.2734e-01, 5.2930e-01, 5.3125e-01, 5.3320e-01, 5.3515e-01, 5.3711e-01, 5.3906e-01, 5.4101e-01, 5.4297e-01, 5.4492e-01, 5.4687e-01, 5.4883e-01, 5.5078e-01, 5.5273e-01, 5.5469e-01, 5.5664e-01, 5.5859e-01, 5.6055e-01, 5.6250e-01, 5.6445e-01, 5.6640e-01, 5.6836e-01, 5.7031e-01, 5.7226e-01, 5.7422e-01, 5.7617e-01, 5.7812e-01, 5.8008e-01, 5.8203e-01, 5.8398e-01, 5.8594e-01, 5.8789e-01, 5.8984e-01, 5.9180e-01, 5.9375e-01, 5.9570e-01, 5.9765e-01, 5.9961e-01, 6.0156e-01, 6.0351e-01, 6.0547e-01, 6.0742e-01, 6.0937e-01, 6.1133e-01, 6.1328e-01, 6.1523e-01, 6.1719e-01, 6.1914e-01, 6.2109e-01, 6.2305e-01, 6.2500e-01, 6.2695e-01, 6.2890e-01, 6.3086e-01, 6.3281e-01, 6.3476e-01, 6.3672e-01, 6.3867e-01, 6.4062e-01, 6.4258e-01, 6.4453e-01, 6.4648e-01, 6.4844e-01, 6.5039e-01, 6.5234e-01, 6.5430e-01, 6.5625e-01, 6.5820e-01, 6.6015e-01, 6.6211e-01, 6.6406e-01, 6.6601e-01, 6.6797e-01, 6.6992e-01, 6.7187e-01, 6.7383e-01, 6.7578e-01, 6.7773e-01, 6.7969e-01, 6.8164e-01, 6.8359e-01, 6.8554e-01, 6.8750e-01, 6.8945e-01, 6.9140e-01, 6.9336e-01, 6.9531e-01, 6.9726e-01, 6.9922e-01, 7.0117e-01, 7.0312e-01, 7.0508e-01, 7.0703e-01, 7.0898e-01, 7.1094e-01, 7.1289e-01, 7.1484e-01, 7.1679e-01, 7.1875e-01, 7.2070e-01, 7.2265e-01, 7.2461e-01, 7.2656e-01, 7.2851e-01, 7.3047e-01, 7.3242e-01, 7.3437e-01, 7.3633e-01, 7.3828e-01, 7.4023e-01, 7.4219e-01, 7.4414e-01, 7.4609e-01, 7.4804e-01, 7.5000e-01, 7.5390e-01, 7.5781e-01, 7.6172e-01, 7.6562e-01, 7.6953e-01, 7.7344e-01, 7.7734e-01, 7.8125e-01, 7.8515e-01, 7.8906e-01, 7.9297e-01, 7.9687e-01, 8.0078e-01, 8.0469e-01, 8.0859e-01, 8.1250e-01, 8.1640e-01, 8.2031e-01, 8.2422e-01, 8.2812e-01, 8.3203e-01, 8.3594e-01, 8.3984e-01, 8.4375e-01, 8.4765e-01, 8.5156e-01, 8.5547e-01, 8.5937e-01, 8.6328e-01, 8.6719e-01, 8.7109e-01, 8.7500e-01, 8.7890e-01, 8.8281e-01, 8.8672e-01, 8.9062e-01, 8.9453e-01, 8.9844e-01, 9.0234e-01, 9.0625e-01, 9.1015e-01, 9.1406e-01, 9.1797e-01, 9.2187e-01, 9.2578e-01, 9.2969e-01, 9.3359e-01, 9.3750e-01, 9.4140e-01, 9.4531e-01, 9.4922e-01, 9.5312e-01, 9.5703e-01, 9.6094e-01, 9.6484e-01, 9.6875e-01, 9.7265e-01, 9.7656e-01, 9.8047e-01, 9.8437e-01, 9.8828e-01, 9.9219e-01, 9.9609e-01, 1.0000e+00 // NOLINT -}; - -float4 normalize_pv(int4 parsed, float vignette_factor) { - // PWL - float4 pv = {ox03c10_lut[parsed.s0], ox03c10_lut[parsed.s1], ox03c10_lut[parsed.s2], ox03c10_lut[parsed.s3]}; - return clamp(pv*vignette_factor*256.0, 0.0, 1.0); -} - -float3 color_correct(float3 rgb) { - float3 corrected = rgb.x * (float3)(1.5664815, -0.29808738, -0.03973474); - corrected += rgb.y * (float3)(-0.48672447, 1.41914433, -0.40295248); - corrected += rgb.z * (float3)(-0.07975703, -0.12105695, 1.44268722); - return corrected; -} - -float3 apply_gamma(float3 rgb, int expo_time) { - return -0.507089*exp(-12.54124638*rgb) + 0.9655*powr(rgb, 0.5) - 0.472597*rgb + 0.507089; -} - -#endif \ No newline at end of file diff --git a/system/camerad/sensors/ox03c10_registers.h b/system/camerad/sensors/ox03c10_registers.h index 575a2cb93472be..bb7a1c5dd63f6e 100644 --- a/system/camerad/sensors/ox03c10_registers.h +++ b/system/camerad/sensors/ox03c10_registers.h @@ -31,6 +31,7 @@ const struct i2c_random_wr_payload init_array_ox03c10[] = { // delay launch group 2 {0x3208, 0xa2},*/ + // **NOTE**: if this is changed, readout_time_ns must be updated in the Sensor config // PLL setup {0x0301, 0xc8}, // pll1_divs, pll1_predivp, pll1_divpix {0x0303, 0x01}, // pll1_prediv @@ -63,21 +64,7 @@ const struct i2c_random_wr_payload init_array_ox03c10[] = { {0x3007, 0x01}, // io_pad_sel {0x3008, 0x80}, // io_pad_sel - // FSIN first frame - /* - {0x3009, 0x2}, - {0x3015, 0x2}, - {0x3822, 0x20}, - {0x3823, 0x58}, - - {0x3826, 0x0}, {0x3827, 0x8}, - {0x3881, 0x4}, - - {0x3882, 0x8}, {0x3883, 0x0D}, - {0x3836, 0x1F}, {0x3837, 0x40}, - */ - - // FSIN with external pulses + // FSIN (frame sync) with external pulses {0x3009, 0x2}, {0x3015, 0x2}, {0x383E, 0x80}, @@ -85,8 +72,11 @@ const struct i2c_random_wr_payload init_array_ox03c10[] = { {0x3882, 0x8}, {0x3883, 0x0D}, {0x3836, 0x1F}, {0x3837, 0x40}, + // causes issues on some devices + //{0x3822, 0x33}, // wait for pulse before first frame + {0x3892, 0x44}, - {0x3823, 0x48}, + {0x3823, 0x41}, {0x3012, 0x41}, // SC_PHY_CTRL = 4 lane MIPI {0x3020, 0x05}, // SC_CTRL_20 diff --git a/system/camerad/sensors/sensor.h b/system/camerad/sensors/sensor.h index add514b117bac4..1a647d1528af10 100644 --- a/system/camerad/sensors/sensor.h +++ b/system/camerad/sensors/sensor.h @@ -5,9 +5,11 @@ #include #include #include + +#include "media/cam_isp.h" #include "media/cam_sensor.h" -#include "system/camerad/cameras/camera_common.h" -#include "system/camerad/sensors/ar0231_registers.h" + +#include "cereal/gen/cpp/log.capnp.h" #include "system/camerad/sensors/ox03c10_registers.h" #include "system/camerad/sensors/os04c10_registers.h" @@ -19,7 +21,6 @@ class SensorInfo { virtual std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const { return {}; } virtual float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const {return 0; } virtual int getSlaveAddress(int port) const { assert(0); } - virtual void processRegisters(CameraState *c, cereal::FrameData::Builder &framed) const {} cereal::FrameData::ImageSensor image_sensor = cereal::FrameData::ImageSensor::UNKNOWN; float pixel_size_mm; @@ -27,6 +28,7 @@ class SensorInfo { uint32_t frame_stride; uint32_t frame_offset = 0; uint32_t extra_height = 0; + int out_scale = 1; int registers_offset = -1; int stats_offset = -1; int hdr_offset = -1; @@ -40,6 +42,7 @@ class SensorInfo { float dc_gain_on_grey; float dc_gain_off_grey; + float ev_scale = 1.0; float sensor_analog_gains[ANALOG_GAIN_MAX_CNT]; int analog_gain_min_idx; int analog_gain_max_idx; @@ -57,21 +60,31 @@ class SensorInfo { std::vector start_reg_array; std::vector init_reg_array; + uint32_t bits_per_pixel; + uint32_t bayer_pattern; uint32_t mipi_format; uint32_t mclk_frequency; uint32_t frame_data_type; -}; -class AR0231 : public SensorInfo { -public: - AR0231(); - std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const override; - float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const override; - int getSlaveAddress(int port) const override; - void processRegisters(CameraState *c, cereal::FrameData::Builder &framed) const override; + uint32_t readout_time_ns; // used to recover EOF from SOF + + // ISP image processing params + uint32_t black_level; + std::vector color_correct_matrix; // 3x3 + std::vector gamma_lut_rgb; // gamma LUTs are length 64 * sizeof(uint32_t); same for r/g/b here + void prepare_gamma_lut() { + for (int i = 0; i < 64; i++) { + gamma_lut_rgb[i] |= ((uint32_t)(gamma_lut_rgb[i+1] - gamma_lut_rgb[i]) << 10); + } + gamma_lut_rgb.pop_back(); + } + std::vector linearization_lut; // length 36 + std::vector linearization_pts; // length 4 + std::vector vignetting_lut; // length 221 -private: - mutable std::map> ar0231_register_lut; + const int num() const { + return static_cast(image_sensor); + }; }; class OX03C10 : public SensorInfo { diff --git a/system/camerad/snapshot/snapshot.py b/system/camerad/snapshot.py similarity index 81% rename from system/camerad/snapshot/snapshot.py rename to system/camerad/snapshot.py index 4ba38c1df4b19f..ec6cbc8ad3fd5c 100755 --- a/system/camerad/snapshot/snapshot.py +++ b/system/camerad/snapshot.py @@ -10,7 +10,7 @@ from openpilot.common.params import Params from openpilot.common.realtime import DT_MDL from openpilot.system.hardware import PC -from openpilot.selfdrive.controls.lib.alertmanager import set_offroad_alert +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert from openpilot.system.manager.process_config import managed_processes @@ -43,9 +43,15 @@ def yuv_to_rgb(y, u, v): def extract_image(buf): + # NV12 format: Y plane followed by interleaved UV plane + # UV plane size is stride * uv_height, where uv_height = align(height/2, 16) + uv_height = ((buf.height // 2) + 15) // 16 * 16 + uv_plane_size = buf.stride * uv_height + y = np.array(buf.data[:buf.uv_offset], dtype=np.uint8).reshape((-1, buf.stride))[:buf.height, :buf.width] - u = np.array(buf.data[buf.uv_offset::2], dtype=np.uint8).reshape((-1, buf.stride//2))[:buf.height//2, :buf.width//2] - v = np.array(buf.data[buf.uv_offset+1::2], dtype=np.uint8).reshape((-1, buf.stride//2))[:buf.height//2, :buf.width//2] + uv_data = buf.data[buf.uv_offset:buf.uv_offset + uv_plane_size] + u = np.array(uv_data[::2], dtype=np.uint8).reshape((-1, buf.stride//2))[:buf.height//2, :buf.width//2] + v = np.array(uv_data[1::2], dtype=np.uint8).reshape((-1, buf.stride//2))[:buf.height//2, :buf.width//2] return yuv_to_rgb(y, u, v) @@ -81,7 +87,7 @@ def snapshot(): return None, None front_camera_allowed = params.get_bool("RecordFront") - params.put_bool("IsTakingSnapshot", True) + params.put_bool("IsTakingSnapshot", True, block=True) set_offroad_alert("Offroad_IsTakingSnapshot", True) time.sleep(2.0) # Give hardwared time to read the param, or if just started give camerad time to start @@ -89,7 +95,7 @@ def snapshot(): try: subprocess.check_call(["pgrep", "camerad"]) print("Camerad already running") - params.put_bool("IsTakingSnapshot", False) + params.put_bool("IsTakingSnapshot", False, block=True) params.remove("Offroad_IsTakingSnapshot") return None, None except subprocess.CalledProcessError: @@ -105,7 +111,7 @@ def snapshot(): rear, front = get_snapshots(frame, front_frame) finally: managed_processes['camerad'].stop() - params.put_bool("IsTakingSnapshot", False) + params.put_bool("IsTakingSnapshot", False, block=True) set_offroad_alert("Offroad_IsTakingSnapshot", False) if not front_camera_allowed: diff --git a/system/camerad/test/check_skips.py b/system/camerad/test/check_skips.py deleted file mode 100755 index 0814ce44ff80ee..00000000000000 --- a/system/camerad/test/check_skips.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python3 -# type: ignore -import cereal.messaging as messaging - -all_sockets = ['roadCameraState', 'driverCameraState', 'wideRoadCameraState'] -prev_id = [None,None,None] -this_id = [None,None,None] -dt = [None,None,None] -num_skipped = [0,0,0] - -if __name__ == "__main__": - sm = messaging.SubMaster(all_sockets) - while True: - sm.update() - - for i in range(len(all_sockets)): - if not sm.updated[all_sockets[i]]: - continue - this_id[i] = sm[all_sockets[i]].frameId - if prev_id[i] is None: - prev_id[i] = this_id[i] - continue - dt[i] = this_id[i] - prev_id[i] - if dt[i] != 1: - num_skipped[i] += dt[i] - 1 - print(all_sockets[i] ,dt[i] - 1, num_skipped[i]) - prev_id[i] = this_id[i] diff --git a/system/camerad/test/debug.sh b/system/camerad/test/debug.sh new file mode 100755 index 00000000000000..eba167ce6a1934 --- /dev/null +++ b/system/camerad/test/debug.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -e + +#echo 4294967295 | sudo tee /sys/module/cam_debug_util/parameters/debug_mdl + +# no CCI and UTIL, very spammy +echo 0xfffdbfff | sudo tee /sys/module/cam_debug_util/parameters/debug_mdl +#echo 0 | sudo tee /sys/module/cam_debug_util/parameters/debug_mdl + +sudo dmesg -C +scons -u --minimal . +export DEBUG_FRAMES=1 +export DISABLE_ROAD=1 DISABLE_WIDE_ROAD=1 +#export DISABLE_DRIVER=1 +export LOGPRINT=debug +./camerad diff --git a/system/camerad/test/get_thumbnails_for_segment.py b/system/camerad/test/get_thumbnails_for_segment.py deleted file mode 100755 index 21409f398d03d1..00000000000000 --- a/system/camerad/test/get_thumbnails_for_segment.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import os -from tqdm import tqdm - -from openpilot.tools.lib.logreader import LogReader - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("route", help="The route name") - args = parser.parse_args() - - out_path = os.path.join("jpegs", f"{args.route.replace('|', '_').replace('/', '_')}") - os.makedirs(out_path, exist_ok=True) - - lr = LogReader(args.route) - - for msg in tqdm(lr): - if msg.which() == 'thumbnail': - with open(os.path.join(out_path, f"{msg.thumbnail.frameId}.jpg"), 'wb') as f: - f.write(msg.thumbnail.thumbnail) - elif msg.which() == 'navThumbnail': - with open(os.path.join(out_path, f"nav_{msg.navThumbnail.frameId}.jpg"), 'wb') as f: - f.write(msg.navThumbnail.thumbnail) diff --git a/system/camerad/test/icp_debug.sh b/system/camerad/test/icp_debug.sh new file mode 100755 index 00000000000000..ebeef9bf8f2d7c --- /dev/null +++ b/system/camerad/test/icp_debug.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -e + +cd /sys/kernel/debug/tracing +echo "" > trace +echo 1 > tracing_on +#echo Y > /sys/kernel/debug/camera_icp/a5_debug_q +echo 0x1 > /sys/kernel/debug/camera_icp/a5_debug_type +echo 1 > /sys/kernel/debug/tracing/events/camera/enable +echo 0xffffffff > /sys/kernel/debug/camera_icp/a5_debug_lvl +echo 1 > /sys/kernel/debug/tracing/events/camera/cam_icp_fw_dbg/enable + +cat /sys/kernel/debug/tracing/trace_pipe diff --git a/system/camerad/test/intercept.sh b/system/camerad/test/intercept.sh new file mode 100755 index 00000000000000..e269929afc5feb --- /dev/null +++ b/system/camerad/test/intercept.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +DISABLE_ROAD=1 DISABLE_WIDE_ROAD=1 DEBUG_FRAMES=1 LOGPRINT=debug LD_PRELOAD=/data/tici_test_scripts/isp/interceptor/tmpioctl.so ./camerad diff --git a/system/camerad/test/test_ae_gray.cc b/system/camerad/test/test_ae_gray.cc index be9a0cc59f20f8..39c3d9c4e55785 100644 --- a/system/camerad/test/test_ae_gray.cc +++ b/system/camerad/test/test_ae_gray.cc @@ -27,18 +27,18 @@ float gts[TONE_SPLITS * TONE_SPLITS * TONE_SPLITS * TONE_SPLITS] = { 0.000000}; -TEST_CASE("camera.test_set_exposure_target") { +TEST_CASE("camera.test_calculate_exposure_value") { // set up fake camerabuf CameraBuf cb = {}; VisionBuf vb = {}; uint8_t * fb_y = new uint8_t[W*H]; vb.y = fb_y; cb.cur_yuv_buf = &vb; - cb.rgb_width = W; - cb.rgb_height = H; + cb.out_img_width = W; + cb.out_img_height = H; Rect rect = {0, 0, W-1, H-1}; - printf("AE test patterns %dx%d\n", cb.rgb_width, cb.rgb_height); + printf("AE test patterns %dx%d\n", cb.out_img_width, cb.out_img_height); // mix of 5 tones uint8_t l[5] = {0, 24, 48, 96, 235}; // 235 is yuv max @@ -61,7 +61,7 @@ TEST_CASE("camera.test_set_exposure_target") { memset(&fb_y[h_0*W+h_1*W], l[2], h_2*W); memset(&fb_y[h_0*W+h_1*W+h_2*W], l[3], h_3*W); memset(&fb_y[h_0*W+h_1*W+h_2*W+h_3*W], l[4], h_4*W); - float ev = set_exposure_target((const CameraBuf*) &cb, rect, 1, 1); + float ev = calculate_exposure_value((const CameraBuf*) &cb, rect, 1, 1); // printf("%d/%d/%d/%d/%d ev is %f\n", h_0, h_1, h_2, h_3, h_4, ev); // printf("%f\n", ev); diff --git a/system/camerad/test/test_camerad.py b/system/camerad/test/test_camerad.py index ada9594895e425..3abe4db6548c1a 100644 --- a/system/camerad/test/test_camerad.py +++ b/system/camerad/test/test_camerad.py @@ -1,82 +1,162 @@ -import pytest +import os import time +import pytest import numpy as np -from flaky import flaky -from collections import defaultdict -import cereal.messaging as messaging -from cereal import log from cereal.services import SERVICE_LIST -from openpilot.system.manager.process_config import managed_processes - -TEST_TIMESPAN = 30 -LAG_FRAME_TOLERANCE = {log.FrameData.ImageSensor.ar0231: 0.5, # ARs use synced pulses for frame starts - log.FrameData.ImageSensor.ox03c10: 1.1} # OXs react to out-of-sync at next frame -FRAME_DELTA_TOLERANCE = {log.FrameData.ImageSensor.ar0231: 1.0, - log.FrameData.ImageSensor.ox03c10: 1.0} +from openpilot.tools.lib.log_time_series import msgs_to_time_series +from openpilot.system.camerad.snapshot import get_snapshots +from openpilot.selfdrive.test.helpers import collect_logs, log_collector, processes_context +TEST_TIMESPAN = 10 CAMERAS = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') +EXPOSURE_STABLE_COUNT = 3 +EXPOSURE_RANGE = (0.15, 0.35) +MAX_TEST_TIME = 25 + + +def _numpy_rgb2gray(im): + return np.clip(im[:,:,2] * 0.114 + im[:,:,1] * 0.587 + im[:,:,0] * 0.299, 0, 255).astype(np.uint8) + +def _exposure_stats(im): + h, w = im.shape[:2] + gray = _numpy_rgb2gray(im[h//10:9*h//10, w//10:9*w//10]) + return float(np.median(gray) / 255.), float(np.mean(gray) / 255.) + +def _in_range(median, mean): + lo, hi = EXPOSURE_RANGE + return lo < median < hi and lo < mean < hi + +def _exposure_stable(results): + return all( + len(v) >= EXPOSURE_STABLE_COUNT and all(_in_range(*s) for s in v[-EXPOSURE_STABLE_COUNT:]) + for v in results.values() + ) + + +def run_and_log(procs, services, duration): + with processes_context(procs): + return collect_logs(services, duration) + +@pytest.fixture(scope="module") +def _camera_session(): + """Single camerad session that collects logs and exposure data. + Runs until exposure stabilizes (min TEST_TIMESPAN seconds for enough log data).""" + with processes_context(["camerad"]), log_collector(CAMERAS) as (raw_logs, lock): + exposure = {cam: [] for cam in CAMERAS} + start = time.monotonic() + while time.monotonic() - start < MAX_TEST_TIME: + rpic, dpic = get_snapshots(frame="roadCameraState", front_frame="driverCameraState") + wpic, _ = get_snapshots(frame="wideRoadCameraState") + for cam, img in zip(CAMERAS, [rpic, dpic, wpic], strict=True): + exposure[cam].append(_exposure_stats(img)) + + if time.monotonic() - start >= TEST_TIMESPAN and _exposure_stable(exposure): + break + + elapsed = time.monotonic() - start + + with lock: + ts = msgs_to_time_series(raw_logs) + + for cam in CAMERAS: + expected_frames = SERVICE_LIST[cam].frequency * elapsed + cnt = len(ts[cam]['t']) + assert expected_frames*0.8 < cnt < expected_frames*1.2, f"unexpected frame count {cam}: {expected_frames=}, got {cnt}" + + dts = np.abs(np.diff([ts[cam]['timestampSof']/1e6]) - 1000/SERVICE_LIST[cam].frequency) + assert (dts < 1.0).all(), f"{cam} dts(ms) out of spec: max diff {dts.max()}, 99 percentile {np.percentile(dts, 99)}" + + return ts, exposure + +@pytest.fixture(scope="module") +def logs(_camera_session): + return _camera_session[0] + +@pytest.fixture(scope="module") +def exposure_data(_camera_session): + return _camera_session[1] -# TODO: this shouldn't be needed -@flaky(max_runs=3) @pytest.mark.tici class TestCamerad: - def setup_method(self): - # run camerad and record logs - managed_processes['camerad'].start() - time.sleep(3) - socks = {c: messaging.sub_sock(c, conflate=False, timeout=100) for c in CAMERAS} - - self.logs = defaultdict(list) - start_time = time.monotonic() - while time.monotonic()- start_time < TEST_TIMESPAN: - for cam, s in socks.items(): - self.logs[cam] += messaging.drain_sock(s) - time.sleep(0.2) - managed_processes['camerad'].stop() - - self.log_by_frame_id = defaultdict(list) - self.sensor_type = None - for cam, msgs in self.logs.items(): - if self.sensor_type is None: - self.sensor_type = getattr(msgs[0], msgs[0].which()).sensor.raw - expected_frames = SERVICE_LIST[cam].frequency * TEST_TIMESPAN - assert expected_frames*0.95 < len(msgs) < expected_frames*1.05, f"unexpected frame count {cam}: {expected_frames=}, got {len(msgs)}" - - dts = np.abs(np.diff([getattr(m, m.which()).timestampSof/1e6 for m in msgs]) - 1000/SERVICE_LIST[cam].frequency) - assert (dts < FRAME_DELTA_TOLERANCE[self.sensor_type]).all(), f"{cam} dts(ms) out of spec: max diff {dts.max()}, 99 percentile {np.percentile(dts, 99)}" - - for m in msgs: - self.log_by_frame_id[getattr(m, m.which()).frameId].append(m) - - # strip beginning and end - for _ in range(3): - mn, mx = min(self.log_by_frame_id.keys()), max(self.log_by_frame_id.keys()) - del self.log_by_frame_id[mn] - del self.log_by_frame_id[mx] - - def test_frame_skips(self): - skips = {} - frame_ids = self.log_by_frame_id.keys() - for frame_id in range(min(frame_ids), max(frame_ids)): - seen_cams = [msg.which() for msg in self.log_by_frame_id[frame_id]] - skip_cams = set(CAMERAS) - set(seen_cams) - if len(skip_cams): - skips[frame_id] = skip_cams - assert len(skips) == 0, f"Found frame skips, missing cameras for the following frames: {skips}" - - def test_frame_sync(self): - frame_times = {frame_id: [getattr(m, m.which()).timestampSof for m in msgs] for frame_id, msgs in self.log_by_frame_id.items()} - diffs = {frame_id: (max(ts) - min(ts))/1e6 for frame_id, ts in frame_times.items()} - - def get_desc(fid, diff): - cam_times = [(m.which(), getattr(m, m.which()).timestampSof/1e6) for m in self.log_by_frame_id[fid]] - return (diff, cam_times) - laggy_frames = {k: get_desc(k, v) for k, v in diffs.items() if v > LAG_FRAME_TOLERANCE[self.sensor_type]} - - def in_tol(diff): - return 50 - LAG_FRAME_TOLERANCE[self.sensor_type] < diff and diff < 50 + LAG_FRAME_TOLERANCE[self.sensor_type] - if len(laggy_frames) != 0 and all( in_tol(laggy_frames[lf][0]) for lf in laggy_frames): - print("TODO: handle camera out of sync") - else: - assert len(laggy_frames) == 0, f"Frames not synced properly: {laggy_frames=}" + @pytest.mark.parametrize("cam", CAMERAS) + def test_camera_exposure(self, exposure_data, cam): + lo, hi = EXPOSURE_RANGE + checks = exposure_data[cam] + assert len(checks) >= EXPOSURE_STABLE_COUNT, f"{cam}: only got {len(checks)} samples" + + # check that exposure converges into the valid range + passed = sum(_in_range(med, mean) for med, mean in checks) + assert passed >= EXPOSURE_STABLE_COUNT, \ + f"{cam}: only {passed}/{len(checks)} checks in range. " + \ + " | ".join(f"#{i+1}: med={m:.4f} mean={u:.4f}" for i, (m, u) in enumerate(checks)) + + # check that exposure is stable once converged (no regressions) + in_range = False + for i, (median, mean) in enumerate(checks): + ok = _in_range(median, mean) + if in_range and not ok: + pytest.fail(f"{cam}: exposure regressed on sample {i+1} " + + f"(median={median:.4f}, mean={mean:.4f}, expected: ({lo}, {hi}))") + in_range = ok + + def test_frame_skips(self, logs): + for c in CAMERAS: + assert set(np.diff(logs[c]['frameId'])) == {1, }, f"{c} has frame skips" + + def test_frame_sync(self, logs): + SYNCED_CAMS = ('roadCameraState', 'wideRoadCameraState') + n = range(len(logs['roadCameraState']['t'][:-10])) + + frame_ids = {i: [logs[cam]['frameId'][i] for cam in CAMERAS] for i in n} + assert all(len(set(v)) == 1 for v in frame_ids.values()), "frame IDs not aligned" + + # road and wide cameras should be synced within 1.1ms + synced_times = {i: [logs[cam]['timestampSof'][i] for cam in SYNCED_CAMS] for i in n} + diffs = {i: (max(ts) - min(ts))/1e6 for i, ts in synced_times.items()} + laggy_frames = {k: v for k, v in diffs.items() if v > 1.1} + assert len(laggy_frames) == 0, f"Frames not synced properly: {laggy_frames=}" + + # driver camera should be staggered ~25ms from road camera + for i in n: + offset_ms = abs(logs['driverCameraState']['timestampSof'][i] - logs['roadCameraState']['timestampSof'][i]) / 1e6 + assert 20 < offset_ms < 30, f"driver camera stagger out of range at frame {i}: {offset_ms:.1f}ms (expected ~25ms)" + + def test_sanity_checks(self, logs): + self._sanity_checks(logs) + + def _sanity_checks(self, ts): + for c in CAMERAS: + assert c in ts + assert len(ts[c]['t']) > 20 + + # not a valid request id + assert 0 not in ts[c]['requestId'] + + # should monotonically increase + assert np.all(np.diff(ts[c]['frameId']) >= 1) + assert np.all(np.diff(ts[c]['requestId']) >= 1) + + # EOF > SOF + assert np.all((ts[c]['timestampEof'] - ts[c]['timestampSof']) > 0) + + # logMonoTime > SOF + assert np.all((ts[c]['t'] - ts[c]['timestampSof']/1e9) > 1e-7) + + # logMonoTime > EOF, needs some tolerance since EOF is (SOF + readout time) but there is noise in the SOF timestamping (done via IRQ) + assert np.mean((ts[c]['t'] - ts[c]['timestampEof']/1e9) > 1e-7) > 0.7 # should be mostly logMonoTime > EOF + assert np.all((ts[c]['t'] - ts[c]['timestampEof']/1e9) > -0.10) # when EOF > logMonoTime, it should never be more than two frames + + def test_stress_test(self): + os.environ['SPECTRA_ERROR_PROB'] = '0.008' + try: + logs = run_and_log(["camerad", ], CAMERAS, 10) + finally: + del os.environ['SPECTRA_ERROR_PROB'] + ts = msgs_to_time_series(logs) + + # we should see some jumps from introduced errors + assert np.max([ np.max(np.diff(ts[c]['frameId'])) for c in CAMERAS ]) > 1 + assert np.max([ np.max(np.diff(ts[c]['requestId'])) for c in CAMERAS ]) > 1 + + self._sanity_checks(ts) diff --git a/system/camerad/test/test_exposure.py b/system/camerad/test/test_exposure.py deleted file mode 100644 index dbe6f3d880c20b..00000000000000 --- a/system/camerad/test/test_exposure.py +++ /dev/null @@ -1,50 +0,0 @@ -import time -import numpy as np - -from openpilot.selfdrive.test.helpers import with_processes, phone_only -from openpilot.system.camerad.snapshot.snapshot import get_snapshots - -TEST_TIME = 45 -REPEAT = 5 - -class TestCamerad: - @classmethod - def setup_class(cls): - pass - - def _numpy_rgb2gray(self, im): - ret = np.clip(im[:,:,2] * 0.114 + im[:,:,1] * 0.587 + im[:,:,0] * 0.299, 0, 255).astype(np.uint8) - return ret - - def _is_exposure_okay(self, i, med_mean=None): - if med_mean is None: - med_mean = np.array([[0.2,0.4],[0.2,0.6]]) - h, w = i.shape[:2] - i = i[h//10:9*h//10,w//10:9*w//10] - med_ex, mean_ex = med_mean - i = self._numpy_rgb2gray(i) - i_median = np.median(i) / 255. - i_mean = np.mean(i) / 255. - print([i_median, i_mean]) - return med_ex[0] < i_median < med_ex[1] and mean_ex[0] < i_mean < mean_ex[1] - - @phone_only - @with_processes(['camerad']) - def test_camera_operation(self): - passed = 0 - start = time.time() - while time.time() - start < TEST_TIME and passed < REPEAT: - rpic, dpic = get_snapshots(frame="roadCameraState", front_frame="driverCameraState") - wpic, _ = get_snapshots(frame="wideRoadCameraState") - - res = self._is_exposure_okay(rpic) - res = res and self._is_exposure_okay(dpic) - res = res and self._is_exposure_okay(wpic) - - if passed > 0 and not res: - passed = -passed # fails test if any failure after first sus - break - - passed += int(res) - time.sleep(2) - assert passed >= REPEAT diff --git a/system/hardware/.gitignore b/system/hardware/.gitignore deleted file mode 100644 index 980f09abfa7d56..00000000000000 --- a/system/hardware/.gitignore +++ /dev/null @@ -1 +0,0 @@ -eon/rat diff --git a/system/hardware/base.h b/system/hardware/base.h index ca24633a182a91..3eded659acc38c 100644 --- a/system/hardware/base.h +++ b/system/hardware/base.h @@ -10,10 +10,6 @@ // no-op base hw class class HardwareNone { public: - static constexpr float MAX_VOLUME = 0.7; - static constexpr float MIN_VOLUME = 0.2; - - static std::string get_os_version() { return ""; } static std::string get_name() { return ""; } static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::UNKNOWN; } static int get_voltage() { return 0; } @@ -25,15 +21,7 @@ class HardwareNone { return {}; } - static void reboot() {} - static void poweroff() {} - static void set_brightness(int percent) {} - static void set_display_power(bool on) {} - - static bool get_ssh_enabled() { return false; } - static void set_ssh_enabled(bool enabled) {} - - static void config_cpu_rendering(bool offscreen); + static void set_ir_power(int percentage) {} static bool PC() { return false; } static bool TICI() { return false; } diff --git a/system/hardware/base.py b/system/hardware/base.py index 6cdb4a4d64e676..5bcf886ae83789 100644 --- a/system/hardware/base.py +++ b/system/hardware/base.py @@ -1,11 +1,106 @@ +import os from abc import abstractmethod, ABC -from collections import namedtuple +from dataclasses import dataclass, fields from cereal import log -ThermalConfig = namedtuple('ThermalConfig', ['cpu', 'gpu', 'mem', 'bat', 'pmic']) NetworkType = log.DeviceState.NetworkType +NetworkStrength = log.DeviceState.NetworkStrength + +class LPAError(RuntimeError): + pass + +class LPAProfileNotFoundError(LPAError): + pass + +@dataclass +class Profile: + iccid: str + nickname: str + enabled: bool + provider: str + + @property + def is_comma(self) -> bool: + return self.provider == 'Webbing' and self.iccid.startswith('8985235') + +@dataclass +class ThermalZone: + # a zone from /sys/class/thermal/thermal_zone* + name: str # a.k.a type + scale: float = 1000. # scale to get degrees in C + zone_number = -1 + + def read(self) -> float: + if self.zone_number < 0: + for n in os.listdir("/sys/devices/virtual/thermal"): + if not n.startswith("thermal_zone"): + continue + with open(os.path.join("/sys/devices/virtual/thermal", n, "type")) as f: + if f.read().strip() == self.name: + self.zone_number = int(n.removeprefix("thermal_zone")) + break + try: + with open(f"/sys/devices/virtual/thermal/thermal_zone{self.zone_number}/temp") as f: + return int(f.read()) / self.scale + except FileNotFoundError: + return 0 + +@dataclass +class ThermalConfig: + cpu: list[ThermalZone] | None = None + gpu: list[ThermalZone] | None = None + dsp: ThermalZone | None = None + pmic: list[ThermalZone] | None = None + memory: ThermalZone | None = None + intake: ThermalZone | None = None + exhaust: ThermalZone | None = None + gnss: ThermalZone | None = None + bottomSoc: ThermalZone | None = None + + def get_msg(self): + ret = {} + for f in fields(ThermalConfig): + v = getattr(self, f.name) + if v is not None: + if isinstance(v, list): + ret[f.name + "TempC"] = [x.read() for x in v] + else: + ret[f.name + "TempC"] = v.read() + return ret + +class LPABase(ABC): + @abstractmethod + def list_profiles(self) -> list[Profile]: + pass + + @abstractmethod + def get_active_profile(self) -> Profile | None: + pass + + @abstractmethod + def delete_profile(self, iccid: str) -> None: + pass + + @abstractmethod + def download_profile(self, qr: str, nickname: str | None = None) -> None: + pass + + @abstractmethod + def nickname_profile(self, iccid: str, nickname: str) -> None: + pass + + @abstractmethod + def switch_profile(self, iccid: str) -> None: + pass + + def process_notifications(self) -> None: + pass + + @abstractmethod + def is_euicc(self) -> bool: + pass class HardwareBase(ABC): @staticmethod @@ -25,113 +120,87 @@ def read_param_file(path, parser, default=0): def booted(self) -> bool: return True - @abstractmethod def reboot(self, reason=None): - pass + print("REBOOT!") - @abstractmethod def uninstall(self): - pass + print("uninstall") - @abstractmethod def get_os_version(self): - pass + return None @abstractmethod def get_device_type(self): pass - @abstractmethod - def get_sound_card_online(self): - pass - - @abstractmethod def get_imei(self, slot) -> str: - pass + return "" - @abstractmethod def get_serial(self): - pass + return "" - @abstractmethod def get_network_info(self): - pass + return None - @abstractmethod def get_network_type(self): - pass + return NetworkType.none - @abstractmethod def get_sim_info(self): - pass + return { + 'sim_id': '', + 'mcc_mnc': None, + 'network_type': ["Unknown"], + 'sim_state': ["ABSENT"], + 'data_connected': False + } + + def get_sim_lpa(self) -> LPABase: + raise NotImplementedError("SIM LPA not available") - @abstractmethod def get_network_strength(self, network_type): - pass + return NetworkStrength.unknown def get_network_metered(self, network_type) -> bool: return network_type not in (NetworkType.none, NetworkType.wifi, NetworkType.ethernet) - @staticmethod - def set_bandwidth_limit(upload_speed_kbps: int, download_speed_kbps: int) -> None: - pass - - @abstractmethod def get_current_power_draw(self): - pass + return 0 - @abstractmethod def get_som_power_draw(self): - pass + return 0 - @abstractmethod def shutdown(self): - pass + print("SHUTDOWN!") - @abstractmethod def get_thermal_config(self): + return ThermalConfig() + + def set_display_power(self, on: bool): pass - @abstractmethod def set_screen_brightness(self, percentage): pass - @abstractmethod def get_screen_brightness(self): - pass + return 0 - @abstractmethod def set_power_save(self, powersave_enabled): pass - @abstractmethod def get_gpu_usage_percent(self): - pass + return 0 def get_modem_version(self): return None - def get_modem_nv(self): - return None - - @abstractmethod def get_modem_temperatures(self): - pass - - @abstractmethod - def get_nvme_temperatures(self): - pass + return [] - @abstractmethod def initialize_hardware(self): pass - def configure_modem(self): - pass - - @abstractmethod def get_networks(self): - pass + return None def has_internal_panda(self) -> bool: return False @@ -144,3 +213,12 @@ def recover_internal_panda(self): def get_modem_data_usage(self): return -1, -1 + + def get_voltage(self) -> float: + return 0. + + def get_current(self) -> float: + return 0. + + def set_ir_power(self, percent: int): + pass diff --git a/system/hardware/esim.py b/system/hardware/esim.py new file mode 100755 index 00000000000000..18d84de9835f65 --- /dev/null +++ b/system/hardware/esim.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 + +import argparse +from openpilot.system.hardware import HARDWARE +from openpilot.system.hardware.base import LPABase, Profile + + +def sorted_profiles(lpa: LPABase) -> list[Profile]: + return sorted(lpa.list_profiles(), key=lambda p: p.iccid) + + +def resolve_iccid(lpa: LPABase, ref: str) -> str: + # ref is either a 1-based index into the sorted list, or a literal iccid + if ref.isdigit(): + profiles = sorted_profiles(lpa) + idx = int(ref) - 1 + if not 0 <= idx < len(profiles): + raise SystemExit(f'no profile at index {ref} (have {len(profiles)})') + return profiles[idx].iccid + return ref + + +def print_profiles(lpa: LPABase) -> None: + profiles = sorted_profiles(lpa) + print(f'\n{len(profiles)} profile{"s" if len(profiles) != 1 else ""}:') + for i, p in enumerate(profiles, start=1): + print(f'{i}. {p.iccid} (nickname: {p.nickname or ""}) (provider: {p.provider}) - {"enabled" if p.enabled else "disabled"}') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(prog='esim.py', description='manage eSIM profiles on your comma device', epilog='comma.ai') + sub = parser.add_subparsers(dest='cmd') + + sub.add_parser('list', help='list profiles') + + p_switch = sub.add_parser('switch', help='switch to profile') + p_switch.add_argument('profile', help='iccid or 1-based index from `list`') + + p_delete = sub.add_parser('delete', help='delete profile (warning: this cannot be undone)') + p_delete.add_argument('profile', help='iccid or 1-based index from `list`') + + p_download = sub.add_parser('download', help='download a profile using QR code (format: LPA:1$rsp.truphone.com$QRF-SPEEDTEST)') + p_download.add_argument('qr') + p_download.add_argument('name') + + p_nickname = sub.add_parser('nickname', help='update the nickname for a profile') + p_nickname.add_argument('profile', help='iccid or 1-based index from `list`') + p_nickname.add_argument('name') + + args = parser.parse_args() + + lpa = HARDWARE.get_sim_lpa() + if args.cmd == 'switch': + lpa.switch_profile(resolve_iccid(lpa, args.profile)) + elif args.cmd == 'delete': + iccid = resolve_iccid(lpa, args.profile) + confirm = input(f'are you sure you want to delete profile {iccid}? (y/N) ') + if confirm == 'y': + lpa.delete_profile(iccid) + else: + print('cancelled') + exit(0) + elif args.cmd == 'download': + lpa.download_profile(args.qr, args.name) + elif args.cmd == 'nickname': + lpa.nickname_profile(resolve_iccid(lpa, args.profile), args.name) + else: + if args.cmd is None: + parser.print_help() + print_profiles(lpa) diff --git a/system/hardware/fan_controller.py b/system/hardware/fan_controller.py index f72e183cde9479..eafde599ade5e2 100755 --- a/system/hardware/fan_controller.py +++ b/system/hardware/fan_controller.py @@ -1,38 +1,28 @@ #!/usr/bin/env python3 -from abc import ABC, abstractmethod +import numpy as np -from openpilot.common.realtime import DT_HW -from openpilot.common.numpy_fast import interp -from openpilot.common.swaglog import cloudlog from openpilot.common.pid import PIDController +from openpilot.system.hardware import HARDWARE -class BaseFanController(ABC): - @abstractmethod - def update(self, cur_temp: float, ignition: bool) -> int: - pass - +# raise fan setpoint on tici/tizi to reduce noise +# after raising LMH threshold in AGNOS 18.1 to prevent CPU throttling +OFFSET = 0 if HARDWARE.get_device_type() == "mici" else 5 -class TiciFanController(BaseFanController): - def __init__(self) -> None: - super().__init__() - cloudlog.info("Setting up TICI fan handler") +class FanController: + def __init__(self, rate: int) -> None: self.last_ignition = False - self.controller = PIDController(k_p=0, k_i=4e-3, k_f=1, rate=(1 / DT_HW)) + self.controller = PIDController(k_p=0, k_i=4e-3, rate=rate) def update(self, cur_temp: float, ignition: bool) -> int: - self.controller.neg_limit = -(100 if ignition else 30) - self.controller.pos_limit = -(30 if ignition else 0) + self.controller.pos_limit = 100 if ignition else 30 + self.controller.neg_limit = 30 if ignition else 0 if ignition != self.last_ignition: self.controller.reset() - - error = 70 - cur_temp - fan_pwr_out = -int(self.controller.update( - error=error, - feedforward=interp(cur_temp, [60.0, 100.0], [0, -100]) - )) - self.last_ignition = ignition - return fan_pwr_out + return int(self.controller.update( + error=(cur_temp - (75 + OFFSET)), # temperature setpoint in C + feedforward=np.interp(cur_temp, [60.0 + OFFSET, 100.0 + OFFSET], [0, 100]) + )) diff --git a/system/hardware/hardwared.py b/system/hardware/hardwared.py index 34e58315d0ed2f..ebc68361912a96 100755 --- a/system/hardware/hardwared.py +++ b/system/hardware/hardwared.py @@ -1,28 +1,39 @@ #!/usr/bin/env python3 +import fcntl import os -import json import queue +import struct import threading import time from collections import OrderedDict, namedtuple -from pathlib import Path import psutil import cereal.messaging as messaging from cereal import log from cereal.services import SERVICE_LIST -from openpilot.common.dict_helpers import strip_deprecated_keys +from openpilot.common.utils import strip_deprecated_keys from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.params import Params from openpilot.common.realtime import DT_HW -from openpilot.selfdrive.controls.lib.alertmanager import set_offroad_alert +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert from openpilot.system.hardware import HARDWARE, TICI, AGNOS from openpilot.system.loggerd.config import get_available_percent from openpilot.system.statsd import statlog from openpilot.common.swaglog import cloudlog from openpilot.system.hardware.power_monitoring import PowerMonitoring -from openpilot.system.hardware.fan_controller import TiciFanController +from openpilot.system.hardware.fan_controller import FanController +from openpilot.system.hardware.loop_timing import HardwareLoopTimer, slow_loop_fields +from openpilot.system.hardware.sysfs_reader import SysReadCache, sysfs_reader_thread +from openpilot.system.hardware.thermal_reader import ThermalCache, stale_thermal_status, thermal_reader_thread +from openpilot.system.hardware.nap_force_offroad import ( + PARAM as NAP_FORCE_OFFROAD_PARAM, + HANDOFF_READY_PARAM as NAP_FORCE_OFFROAD_HANDOFF_READY_PARAM, + CONFIRMED_PARAM as NAP_FORCE_OFFROAD_CONFIRMED_PARAM, + allows_onroad as nap_force_offroad_allows_onroad, + handoff_wait_timed_out as nap_force_offroad_handoff_timed_out, + should_start_now, +) from openpilot.system.version import terms_version, training_version ThermalStatus = log.DeviceState.ThermalStatus @@ -32,58 +43,32 @@ TEMP_TAU = 5. # 5s time constant DISCONNECT_TIMEOUT = 5. # wait 5 seconds before going offroad after disconnect so you get an alert PANDA_STATES_TIMEOUT = round(1000 / SERVICE_LIST['pandaStates'].frequency * 1.5) # 1.5x the expected pandaState frequency +ONROAD_CYCLE_TIME = 1 # seconds to wait offroad after requesting an onroad cycle ThermalBand = namedtuple("ThermalBand", ['min_temp', 'max_temp']) HardwareState = namedtuple("HardwareState", ['network_type', 'network_info', 'network_strength', 'network_stats', - 'network_metered', 'nvme_temps', 'modem_temps']) + 'network_metered', 'modem_temps']) # List of thermal bands. We will stay within this region as long as we are within the bounds. # When exiting the bounds, we'll jump to the lower or higher band. Bands are ordered in the dict. -THERMAL_BANDS = OrderedDict({ - ThermalStatus.green: ThermalBand(None, 80.0), - ThermalStatus.yellow: ThermalBand(75.0, 96.0), - ThermalStatus.red: ThermalBand(88.0, 107.), - ThermalStatus.danger: ThermalBand(94.0, None), -}) +if HARDWARE.get_device_type() == "mici": + THERMAL_BANDS = OrderedDict({ + ThermalStatus.ok: ThermalBand(None, 100.0), + ThermalStatus.overheated: ThermalBand(92.0, 107.), + ThermalStatus.critical: ThermalBand(98.0, None), + }) +else: + THERMAL_BANDS = OrderedDict({ + ThermalStatus.ok: ThermalBand(None, 96.0), + ThermalStatus.overheated: ThermalBand(88.0, 107.), + ThermalStatus.critical: ThermalBand(94.0, None), + }) # Override to highest thermal band when offroad and above this temp -OFFROAD_DANGER_TEMP = 75 +OFFROAD_DANGER_TEMP = 85 if HARDWARE.get_device_type() == "mici" else 75 prev_offroad_states: dict[str, tuple[bool, str | None]] = {} -tz_by_type: dict[str, int] | None = None -def populate_tz_by_type(): - global tz_by_type - tz_by_type = {} - for n in os.listdir("/sys/devices/virtual/thermal"): - if not n.startswith("thermal_zone"): - continue - with open(os.path.join("/sys/devices/virtual/thermal", n, "type")) as f: - tz_by_type[f.read().strip()] = int(n.removeprefix("thermal_zone")) - -def read_tz(x): - if x is None: - return 0 - - if isinstance(x, str): - if tz_by_type is None: - populate_tz_by_type() - x = tz_by_type[x] - - try: - with open(f"/sys/devices/virtual/thermal/thermal_zone{x}/temp") as f: - return int(f.read()) - except FileNotFoundError: - return 0 - - -def read_thermal(thermal_config): - dat = messaging.new_message('deviceState', valid=True) - dat.deviceState.cpuTempC = [read_tz(z) / thermal_config.cpu[1] for z in thermal_config.cpu[0]] - dat.deviceState.gpuTempC = [read_tz(z) / thermal_config.gpu[1] for z in thermal_config.gpu[0]] - dat.deviceState.memoryTempC = read_tz(thermal_config.mem[0]) / thermal_config.mem[1] - dat.deviceState.pmicTempC = [read_tz(z) / thermal_config.pmic[1] for z in thermal_config.pmic[0]] - return dat def set_offroad_alert_if_changed(offroad_alert: str, show_alert: bool, extra_text: str | None=None): @@ -92,6 +77,40 @@ def set_offroad_alert_if_changed(offroad_alert: str, show_alert: bool, extra_tex prev_offroad_states[offroad_alert] = (show_alert, extra_text) set_offroad_alert(offroad_alert, show_alert, extra_text) +def touch_thread(end_event): + count = 0 + + pm = messaging.PubMaster(["touch"]) + + event_format = "llHHi" + event_size = struct.calcsize(event_format) + event_frame = [] + + with open("/dev/input/by-path/platform-894000.i2c-event", "rb") as event_file: + fcntl.fcntl(event_file, fcntl.F_SETFL, os.O_NONBLOCK) + while not end_event.is_set(): + if (count % int(1. / DT_HW)) == 0: + event = event_file.read(event_size) + if event: + (sec, usec, etype, code, value) = struct.unpack(event_format, event) + if etype != 0 or code != 0 or value != 0: + touch = log.Touch.new_message() + touch.sec = sec + touch.usec = usec + touch.type = etype + touch.code = code + touch.value = value + event_frame.append(touch) + else: # end of frame, push new log + msg = messaging.new_message('touch', len(event_frame), valid=True) + msg.touch = event_frame + pm.send('touch', msg) + event_frame = [] + continue + + count += 1 + time.sleep(DT_HW) + def hw_state_thread(end_event, hw_queue): """Handles non critical hardware state, and sends over queue""" @@ -99,10 +118,6 @@ def hw_state_thread(end_event, hw_queue): prev_hw_state = None modem_version = None - modem_nv = None - modem_configured = False - modem_restarted = False - modem_missing_count = 0 while not end_event.is_set(): # these are expensive calls. update every 10s @@ -114,22 +129,11 @@ def hw_state_thread(end_event, hw_queue): modem_temps = prev_hw_state.modem_temps # Log modem version once - if AGNOS and ((modem_version is None) or (modem_nv is None)): + if AGNOS and (modem_version is None): modem_version = HARDWARE.get_modem_version() - modem_nv = HARDWARE.get_modem_nv() - - if (modem_version is not None) and (modem_nv is not None): - cloudlog.event("modem version", version=modem_version, nv=modem_nv) - else: - if not modem_restarted: - # TODO: we may be able to remove this with a MM update - # ModemManager's probing on startup can fail - # rarely, restart the service to probe again. - modem_missing_count += 1 - if modem_missing_count > 3: - modem_restarted = True - cloudlog.event("restarting ModemManager") - os.system("sudo systemctl restart --no-block ModemManager") + + if modem_version is not None: + cloudlog.event("modem version", version=modem_version) tx, rx = HARDWARE.get_modem_data_usage() @@ -139,7 +143,6 @@ def hw_state_thread(end_event, hw_queue): network_strength=HARDWARE.get_network_strength(network_type), network_stats={'wwanTx': tx, 'wwanRx': rx}, network_metered=HARDWARE.get_network_metered(network_type), - nvme_temps=HARDWARE.get_nvme_temperatures(), modem_temps=modem_temps, ) @@ -148,12 +151,6 @@ def hw_state_thread(end_event, hw_queue): except queue.Full: pass - # TODO: remove this once the config is in AGNOS - if not modem_configured and len(HARDWARE.get_sim_info().get('sim_id', '')) > 0: - cloudlog.warning("configuring modem") - HARDWARE.configure_modem() - modem_configured = True - prev_hw_state = hw_state except Exception: cloudlog.exception("Error getting hardware state") @@ -162,7 +159,22 @@ def hw_state_thread(end_event, hw_queue): time.sleep(DT_HW) -def hardware_thread(end_event, hw_queue) -> None: +def _report_slow_hardware_loop(timer: HardwareLoopTimer) -> None: + """Name the blocking step when one hardware_thread pass takes more than 1 s. + + logmessaged only copies ERROR and above into errorLogMessage, which is the + channel qlog keeps. cloudlog.warning stays on logMessage (rlog only), so the + same step durations are also emitted as an error event. Nothing published + on deviceState changes. + """ + fields = slow_loop_fields(timer) + if fields is None: + return + cloudlog.warning({"event": "hardwared slow loop", **fields}) + cloudlog.event("hardwared slow loop", error=True, **fields) + + +def hardware_thread(end_event, hw_queue, thermal_queue=None, sys_cache=None) -> None: pm = messaging.PubMaster(['deviceState']) sm = messaging.SubMaster(["peripheralState", "gpsLocationExternal", "selfdriveState", "pandaStates"], poll="pandaStates") @@ -170,6 +182,9 @@ def hardware_thread(end_event, hw_queue) -> None: onroad_conditions: dict[str, bool] = { "ignition": False, + "not_onroad_cycle": True, + "device_temp_good": True, + "not_force_offroad": True, } startup_conditions: dict[str, bool] = {} startup_conditions_prev: dict[str, bool] = {} @@ -178,7 +193,7 @@ def hardware_thread(end_event, hw_queue) -> None: started_ts: float | None = None started_seen = False startup_blocked_ts: float | None = None - thermal_status = ThermalStatus.yellow + thermal_status = ThermalStatus.ok last_hw_state = HardwareState( network_type=NetworkType.none, @@ -186,7 +201,6 @@ def hardware_thread(end_event, hw_queue) -> None: network_metered=False, network_strength=NetworkStrength.unknown, network_stats={'wwanTx': -1, 'wwanRx': -1}, - nvme_temps=[], modem_temps=[], ) @@ -195,21 +209,95 @@ def hardware_thread(end_event, hw_queue) -> None: should_start_prev = False in_car = False engaged_prev = False + pwrsave = False + offroad_cycle_count = 0 params = Params() power_monitor = PowerMonitoring() + uptime_offroad: float = params.get("UptimeOffroad", return_default=True) + uptime_onroad: float = params.get("UptimeOnroad", return_default=True) + last_uptime_ts: float = time.monotonic() + force_offroad_handoff_wait_ts: float | None = None + HARDWARE.initialize_hardware() thermal_config = HARDWARE.get_thermal_config() + # Thermal zones are read off the publish loop; see thermal_reader.py. + thermal_reader = None + if thermal_queue is None: + thermal_queue = queue.Queue(maxsize=1) + thermal_reader = threading.Thread(target=thermal_reader_thread, args=(end_event, thermal_config, thermal_queue), daemon=True) + thermal_reader.start() + thermal_cache = ThermalCache(thermal_queue) + + # All other system-file reads are off the publish loop too; see sysfs_reader.py. + if sys_cache is None: + sys_cache = SysReadCache({ + "free_space": 100.0, "memory": 0, "gpu": 0, "cpu": [], "screen_brightness": 0, + "booted": False, "power_draw": 0.0, "som_power_draw": 0.0, + }) + sys_readers = { + "free_space": lambda: get_available_percent(default=100.0), + "memory": lambda: int(round(psutil.virtual_memory().percent)), + "gpu": lambda: int(round(HARDWARE.get_gpu_usage_percent())), + "cpu": lambda: [int(round(n)) for n in psutil.cpu_percent(percpu=True)], + "screen_brightness": HARDWARE.get_screen_brightness, + "booted": HARDWARE.booted, + "power_draw": HARDWARE.get_current_power_draw, + "som_power_draw": HARDWARE.get_som_power_draw, + } + threading.Thread(target=sysfs_reader_thread, args=(end_event, sys_readers, sys_cache), daemon=True).start() + if thermal_reader is not None: + # Startup only: wait briefly for the first real reading so the first + # deviceState isn't published with empty temperatures. + try: + thermal_cache.snapshot = thermal_queue.get(timeout=2.0) + except queue.Empty: + pass - fan_controller = None + fan_controller = FanController(int(1./DT_HW)) while not end_event.is_set(): + timer = HardwareLoopTimer() sm.update(PANDA_STATES_TIMEOUT) + timer.mark("sm_update") pandaStates = sm['pandaStates'] peripheralState = sm['peripheralState'] - peripheral_panda_present = peripheralState.pandaType != log.PandaState.PandaType.unknown + + # handle requests to cycle system started state + if params.get_bool("OnroadCycleRequested"): + params.put_bool("OnroadCycleRequested", False, block=True) + offroad_cycle_count = sm.frame + timer.mark("onroad_cycle_param") + onroad_conditions["not_onroad_cycle"] = (sm.frame - offroad_cycle_count) >= ONROAD_CYCLE_TIME * SERVICE_LIST['pandaStates'].frequency + # Read every loop so toggling Force Offroad trips ign_edge immediately + # (same pattern as OnroadCycleRequested). Do not use CLEAR_ON_OFFROAD + # on this param — going offroad is what the toggle does. + # While already onroad, hold started until card finishes the Pre-AP + # stock-CC handoff (or HANDOFF_TIMEOUT_S) so pedal long does not drop + # into hard regen. Cancel/SET live in the onroad carcontroller. + force_offroad = params.get_bool(NAP_FORCE_OFFROAD_PARAM) + handoff_ready = params.get_bool(NAP_FORCE_OFFROAD_HANDOFF_READY_PARAM) + force_offroad_confirmed = params.get_bool(NAP_FORCE_OFFROAD_CONFIRMED_PARAM) + timer.mark("force_offroad_params") + already_started = started_ts is not None + # Do not start the handoff timeout until the driver taps Yes. + if force_offroad and already_started and force_offroad_confirmed and not handoff_ready: + if force_offroad_handoff_wait_ts is None: + force_offroad_handoff_wait_ts = time.monotonic() + handoff_timed_out = nap_force_offroad_handoff_timed_out( + force_offroad_handoff_wait_ts, time.monotonic()) + else: + force_offroad_handoff_wait_ts = None + handoff_timed_out = False + onroad_conditions["not_force_offroad"] = nap_force_offroad_allows_onroad( + force_offroad, + handoff_ready=handoff_ready, + already_started=already_started, + timed_out=handoff_timed_out, + confirmed=force_offroad_confirmed, + ) if sm.updated['pandaStates'] and len(pandaStates) > 0: @@ -220,35 +308,40 @@ def hardware_thread(end_event, hw_queue) -> None: in_car = pandaState.harnessStatus != log.PandaState.HarnessStatus.notConnected - # Setup fan handler on first connect to panda - if fan_controller is None and peripheral_panda_present: - if TICI: - fan_controller = TiciFanController() - elif (time.monotonic() - sm.recv_time['pandaStates']) > DISCONNECT_TIMEOUT: if onroad_conditions["ignition"]: onroad_conditions["ignition"] = False cloudlog.error("panda timed out onroad") + timer.mark("panda_state") # Run at 2Hz, plus either edge of ignition - ign_edge = (started_ts is not None) != onroad_conditions["ignition"] + ign_edge = (started_ts is not None) != all(onroad_conditions.values()) if (sm.frame % round(SERVICE_LIST['pandaStates'].frequency * DT_HW) != 0) and not ign_edge: + _report_slow_hardware_loop(timer) continue - msg = read_thermal(thermal_config) + msg = messaging.new_message('deviceState', valid=True) + thermal_cache.poll() + msg.deviceState = thermal_cache.temps msg.deviceState.deviceType = HARDWARE.get_device_type() + timer.mark("thermal_config") try: last_hw_state = hw_queue.get_nowait() except queue.Empty: pass - - msg.deviceState.freeSpacePercent = get_available_percent(default=100.0) - msg.deviceState.memoryUsagePercent = int(round(psutil.virtual_memory().percent)) - msg.deviceState.gpuUsagePercent = int(round(HARDWARE.get_gpu_usage_percent())) - online_cpu_usage = [int(round(n)) for n in psutil.cpu_percent(percpu=True)] - offline_cpu_usage = [0., ] * (len(msg.deviceState.cpuTempC) - len(online_cpu_usage)) + timer.mark("hw_queue") + + msg.deviceState.freeSpacePercent = sys_cache.get("free_space", 100.0) + timer.mark("statvfs") + msg.deviceState.memoryUsagePercent = sys_cache.get("memory", 0) + timer.mark("memory") + msg.deviceState.gpuUsagePercent = sys_cache.get("gpu", 0) + timer.mark("gpu") + online_cpu_usage = list(sys_cache.get("cpu", [])) + offline_cpu_usage = [0, ] * (len(msg.deviceState.cpuTempC) - len(online_cpu_usage)) msg.deviceState.cpuUsagePercent = online_cpu_usage + offline_cpu_usage + timer.mark("cpu") msg.deviceState.networkType = last_hw_state.network_type msg.deviceState.networkMetered = last_hw_state.network_metered @@ -257,32 +350,35 @@ def hardware_thread(end_event, hw_queue) -> None: if last_hw_state.network_info is not None: msg.deviceState.networkInfo = last_hw_state.network_info - msg.deviceState.nvmeTempC = last_hw_state.nvme_temps msg.deviceState.modemTempC = last_hw_state.modem_temps + timer.mark("network") - msg.deviceState.screenBrightnessPercent = HARDWARE.get_screen_brightness() + msg.deviceState.screenBrightnessPercent = sys_cache.get("screen_brightness", 0) + timer.mark("screen_brightness") # this subset is only used for offroad temp_sources = [ msg.deviceState.memoryTempC, - max(msg.deviceState.cpuTempC), - max(msg.deviceState.gpuTempC), + max(msg.deviceState.cpuTempC, default=0.), + max(msg.deviceState.gpuTempC, default=0.), ] offroad_comp_temp = offroad_temp_filter.update(max(temp_sources)) # this drives the thermal status while onroad - temp_sources.append(max(msg.deviceState.pmicTempC)) + temp_sources.append(max(msg.deviceState.pmicTempC, default=0.)) all_comp_temp = all_temp_filter.update(max(temp_sources)) msg.deviceState.maxTempC = all_comp_temp - if fan_controller is not None: - msg.deviceState.fanSpeedPercentDesired = fan_controller.update(all_comp_temp, onroad_conditions["ignition"]) + msg.deviceState.fanSpeedPercentDesired = fan_controller.update(all_comp_temp, onroad_conditions["ignition"]) + if thermal_cache.stale: + msg.deviceState.fanSpeedPercentDesired = 100 + timer.mark("thermal_fan") is_offroad_for_5_min = (started_ts is None) and ((not started_seen) or (off_ts is None) or (time.monotonic() - off_ts > 60 * 5)) if is_offroad_for_5_min and offroad_comp_temp > OFFROAD_DANGER_TEMP: # if device is offroad and already hot without the extra onroad load, # we want to cool down first before increasing load - thermal_status = ThermalStatus.danger + thermal_status = ThermalStatus.critical else: current_band = THERMAL_BANDS[thermal_status] band_idx = list(THERMAL_BANDS.keys()).index(thermal_status) @@ -290,10 +386,16 @@ def hardware_thread(end_event, hw_queue) -> None: thermal_status = list(THERMAL_BANDS.keys())[band_idx - 1] elif current_band.max_temp is not None and all_comp_temp > current_band.max_temp: thermal_status = list(THERMAL_BANDS.keys())[band_idx + 1] + # Stale temps: hold last status; fail hot if it was already yellow or + # stale > 60 s. While stale all_comp_temp is computed from held temps. + thermal_status = stale_thermal_status( + thermal_status, thermal_cache.stale, thermal_cache.stale_s, all_comp_temp, + THERMAL_BANDS[ThermalStatus.overheated].min_temp, ThermalStatus.ok, ThermalStatus.overheated) # **** starting logic **** startup_conditions["up_to_date"] = params.get("Offroad_ConnectivityNeeded") is None or params.get_bool("DisableUpdates") or params.get_bool("SnoozeUpdate") + startup_conditions["no_excessive_actuation"] = params.get("Offroad_ExcessiveActuation") is None startup_conditions["not_uninstalling"] = not params.get_bool("DoUninstall") startup_conditions["accepted_terms"] = params.get("HasAcceptedTerms") == terms_version @@ -304,47 +406,40 @@ def hardware_thread(end_event, hw_queue) -> None: startup_conditions["not_taking_snapshot"] = not params.get_bool("IsTakingSnapshot") # must be at an engageable thermal band to go onroad - startup_conditions["device_temp_engageable"] = thermal_status < ThermalStatus.red + startup_conditions["device_temp_engageable"] = thermal_status < ThermalStatus.overheated # ensure device is fully booted - startup_conditions["device_booted"] = startup_conditions.get("device_booted", False) or HARDWARE.booted() + startup_conditions["device_booted"] = startup_conditions.get("device_booted", False) or bool(sys_cache.get("booted", False)) + timer.mark("startup_params") # if the temperature enters the danger zone, go offroad to cool down - onroad_conditions["device_temp_good"] = thermal_status < ThermalStatus.danger + onroad_conditions["device_temp_good"] = thermal_status < ThermalStatus.critical extra_text = f"{offroad_comp_temp:.1f}C" show_alert = (not onroad_conditions["device_temp_good"] or not startup_conditions["device_temp_engageable"]) and onroad_conditions["ignition"] set_offroad_alert_if_changed("Offroad_TemperatureTooHigh", show_alert, extra_text=extra_text) + timer.mark("thermal_alert") - # TODO: this should move to TICI.initialize_hardware, but we currently can't import params there - if TICI: - if not os.path.isfile("/persist/comma/living-in-the-moment"): - if not Path("/data/media").is_mount(): - set_offroad_alert_if_changed("Offroad_StorageMissing", True) - else: - # check for bad NVMe - try: - with open("/sys/block/nvme0n1/device/model") as f: - model = f.read().strip() - if not model.startswith("Samsung SSD 980") and params.get("Offroad_BadNvme") is None: - set_offroad_alert_if_changed("Offroad_BadNvme", True) - cloudlog.event("Unsupported NVMe", model=model, error=True) - except Exception: - pass + if show_alert: + msg.deviceState.fanSpeedPercentDesired = 100 + + # *** registration check *** + # No dongle-id gate: pre-AP Teslas run on non-comma hardware that doesn't + # register with comma's backend, so onroad must not depend on registration. + # comma's stock code enforces this here; forks are invited to differ. # Handle offroad/onroad transition - should_start = all(onroad_conditions.values()) - if started_ts is None: - should_start = should_start and all(startup_conditions.values()) + should_start = should_start_now(onroad_conditions, startup_conditions, started_ts is not None) + timer.mark("should_start") if should_start != should_start_prev or (count == 0): - params.put_bool("IsEngaged", False) + params.put_bool("IsEngaged", False, block=True) engaged_prev = False - HARDWARE.set_power_save(not should_start) + timer.mark("engaged_param") if sm.updated['selfdriveState']: engaged = sm['selfdriveState'].enabled if engaged != engaged_prev: - params.put_bool("IsEngaged", engaged) + params.put_bool("IsEngaged", engaged, block=True) engaged_prev = engaged try: @@ -352,6 +447,13 @@ def hardware_thread(end_event, hw_queue) -> None: kmsg.write(f"<3>[hardware] engaged: {engaged}\n") except Exception: pass + timer.mark("selfdrive_engaged") + + should_pwrsave = not onroad_conditions["ignition"] and msg.deviceState.screenBrightnessPercent < 1e-3 + if should_pwrsave != pwrsave or (count == 0): + HARDWARE.set_power_save(should_pwrsave) + pwrsave = should_pwrsave + timer.mark("power_save") if should_start: off_ts = None @@ -372,34 +474,41 @@ def hardware_thread(end_event, hw_queue) -> None: started_ts = None if off_ts is None: off_ts = time.monotonic() + timer.mark("onroad_transition") # Offroad power monitoring voltage = None if peripheralState.pandaType == log.PandaState.PandaType.unknown else peripheralState.voltage power_monitor.calculate(voltage, onroad_conditions["ignition"]) msg.deviceState.offroadPowerUsageUwh = power_monitor.get_power_used() msg.deviceState.carBatteryCapacityUwh = max(0, power_monitor.get_car_battery_capacity()) - current_power_draw = HARDWARE.get_current_power_draw() + timer.mark("power_monitor") + current_power_draw = sys_cache.get("power_draw", 0.0) statlog.sample("power_draw", current_power_draw) msg.deviceState.powerDrawW = current_power_draw + timer.mark("power_draw") - som_power_draw = HARDWARE.get_som_power_draw() + som_power_draw = sys_cache.get("som_power_draw", 0.0) statlog.sample("som_power_draw", som_power_draw) msg.deviceState.somPowerDrawW = som_power_draw + timer.mark("som_power_draw") # Check if we need to shut down if power_monitor.should_shutdown(onroad_conditions["ignition"], in_car, off_ts, started_seen): cloudlog.warning(f"shutting device down, offroad since {off_ts}") - params.put_bool("DoShutdown", True) + params.put_bool("DoShutdown", True, block=True) + timer.mark("shutdown_check") msg.deviceState.started = started_ts is not None msg.deviceState.startedMonoTime = int(1e9*(started_ts or 0)) last_ping = params.get("LastAthenaPingTime") if last_ping is not None: - msg.deviceState.lastAthenaPingTime = int(last_ping) + msg.deviceState.lastAthenaPingTime = last_ping + timer.mark("athena_ping") msg.deviceState.thermalStatus = thermal_status pm.send("deviceState", msg) + timer.mark("publish") # Log to statsd statlog.gauge("free_space_percent", msg.deviceState.freeSpacePercent) @@ -414,16 +523,16 @@ def hardware_thread(end_event, hw_queue) -> None: statlog.gauge("memory_temperature", msg.deviceState.memoryTempC) for i, temp in enumerate(msg.deviceState.pmicTempC): statlog.gauge(f"pmic{i}_temperature", temp) - for i, temp in enumerate(last_hw_state.nvme_temps): - statlog.gauge(f"nvme_temperature{i}", temp) for i, temp in enumerate(last_hw_state.modem_temps): statlog.gauge(f"modem_temperature{i}", temp) statlog.gauge("fan_speed_percent_desired", msg.deviceState.fanSpeedPercentDesired) statlog.gauge("screen_brightness_percent", msg.deviceState.screenBrightnessPercent) + timer.mark("statlog") - # report to server once every 10 minutes + # report to server once every 10 minutes, or every 1s when thermally blocked rising_edge_started = should_start and not should_start_prev - if rising_edge_started or (count % int(600. / DT_HW)) == 0: + status_packet_interval = 1. if show_alert else 600. + if rising_edge_started or (count % int(status_packet_interval / DT_HW)) == 0: dat = { 'count': count, 'pandaStates': [strip_deprecated_keys(p.to_dict()) for p in pandaStates], @@ -436,14 +545,29 @@ def hardware_thread(end_event, hw_queue) -> None: # save last one before going onroad if rising_edge_started: try: - params.put("LastOffroadStatusPacket", json.dumps(dat)) + params.put("LastOffroadStatusPacket", dat, block=True) except Exception: cloudlog.exception("failed to save offroad status") + timer.mark("status_packet") - params.put_bool_nonblocking("NetworkMetered", msg.deviceState.networkMetered) + params.put_bool("NetworkMetered", msg.deviceState.networkMetered) + timer.mark("network_metered_param") + + now_ts = time.monotonic() + if off_ts: + uptime_offroad += now_ts - max(last_uptime_ts, off_ts) + elif started_ts: + uptime_onroad += now_ts - max(last_uptime_ts, started_ts) + last_uptime_ts = now_ts + + if (count % int(60. / DT_HW)) == 0: + params.put("UptimeOffroad", uptime_offroad, block=True) + params.put("UptimeOnroad", uptime_onroad, block=True) + timer.mark("uptime_params") count += 1 should_start_prev = should_start + _report_slow_hardware_loop(timer) def main(): @@ -455,6 +579,9 @@ def main(): threading.Thread(target=hardware_thread, args=(end_event, hw_queue)), ] + if TICI: + threads.append(threading.Thread(target=touch_thread, args=(end_event,))) + for t in threads: t.start() diff --git a/system/hardware/hw.h b/system/hardware/hw.h index 394807ccb574be..a9058401ceb9cd 100644 --- a/system/hardware/hw.h +++ b/system/hardware/hw.h @@ -5,7 +5,7 @@ #include "system/hardware/base.h" #include "common/util.h" -#if QCOM2 +#if __TICI__ #include "system/hardware/tici/hardware.h" #define Hardware HardwareTici #else @@ -47,4 +47,12 @@ namespace Path { } return "/tmp/comma_download_cache" + Path::openpilot_prefix() + "/"; } + + inline std::string shm_path() { + #ifdef __APPLE__ + return"/tmp"; + #else + return "/dev/shm"; + #endif + } } // namespace Path diff --git a/system/hardware/hw.py b/system/hardware/hw.py index 694299d72e4a15..dc36dc047498a7 100644 --- a/system/hardware/hw.py +++ b/system/hardware/hw.py @@ -1,4 +1,5 @@ import os +import platform from pathlib import Path from openpilot.system.hardware import PC @@ -56,3 +57,9 @@ def config_root() -> str: return Paths.comma_home() else: return "/tmp/.comma" + + @staticmethod + def shm_path() -> str: + if PC and platform.system() == "Darwin": + return "/tmp" # This is not really shared memory on macOS, but it's the closest we can get + return "/dev/shm" diff --git a/system/hardware/loop_timing.py b/system/hardware/loop_timing.py new file mode 100644 index 00000000000000..c9a138c8056f3a --- /dev/null +++ b/system/hardware/loop_timing.py @@ -0,0 +1,37 @@ +"""Per-step monotonic timing for hardwared's publish loop.""" + +import time + +# One iteration past this is logged with each step's duration so a stall +# names the blocking call. Publishing and the loop rate are unchanged. +SLOW_HW_LOOP_S = 1.0 + + +class HardwareLoopTimer: + def __init__(self, clock=None): + self._clock = time.monotonic if clock is None else clock + self._t0 = self._clock() + self._prev = self._t0 + self.steps: dict[str, float] = {} + + def mark(self, name: str) -> None: + now = self._clock() + self.steps[name] = now - self._prev + self._prev = now + + @property + def total_s(self) -> float: + return self._clock() - self._t0 + + +def slow_loop_fields(timer: HardwareLoopTimer) -> dict[str, float] | None: + """Step durations in milliseconds when the iteration exceeded 1 s. + + None when the loop was fast enough that nothing should be logged. + """ + total = timer.total_s + if total <= SLOW_HW_LOOP_S: + return None + fields = {f"{name}_ms": round(dt * 1000.0, 1) for name, dt in timer.steps.items()} + fields["total_ms"] = round(total * 1000.0, 1) + return fields diff --git a/system/hardware/nap_force_offroad.py b/system/hardware/nap_force_offroad.py new file mode 100644 index 00000000000000..2311802c639bc3 --- /dev/null +++ b/system/hardware/nap_force_offroad.py @@ -0,0 +1,85 @@ +"""NAP Force Offroad / Go Offline — started=false while the car can still move. + +Settings → NAP toggle. hardwared applies this as +onroad_conditions['not_force_offroad'] so deviceState.started stays false. + +When Pre-AP software long is active, card holds this off until stock CC is +ENABLED (or a short timeout) so pedal long does not drop into hard regen. +See selfdrive/car/tesla/preap_force_offroad_handoff.py. +""" + +PARAM = "NAPForceOffroad" +HANDOFF_READY_PARAM = "NAPForceOffroadHandoffReady" +CONFIRMED_PARAM = "NAPForceOffroadConfirmed" + +# On-road Yes/No copy. Keep Justin's wording. +CONFIRM_PROMPT = "Ready to resume steering control?" +CONFIRM_YES = "Yes" +CONFIRM_NO = "No" + +# hardwared fallback if card never writes HandoffReady (non-Pre-AP card +# miss, card already dying). Card's own budget is 2.5 s; keep this a bit +# longer so the onroad SET can finish first. +HANDOFF_TIMEOUT_S = 3.0 + + +def needs_driver_confirm(force_offroad: bool, confirmed: bool, already_started: bool) -> bool: + """On-road Force Offroad waits for the Yes/No popup before any handoff.""" + return bool(force_offroad) and bool(already_started) and not confirmed + + +def apply_force_offroad_toggle(params, on: bool, *, started: bool) -> None: + """Write the toggle and confirm/handoff flags. Parked skips the popup.""" + params.put_bool(PARAM, bool(on)) + if not on: + params.put_bool(CONFIRMED_PARAM, False) + params.put_bool(HANDOFF_READY_PARAM, False) + return + params.put_bool(CONFIRMED_PARAM, not started) + if not started: + return + params.put_bool(HANDOFF_READY_PARAM, False) + + +def confirm_force_offroad(params) -> None: + params.put_bool(CONFIRMED_PARAM, True) + + +def cancel_force_offroad(params) -> None: + """No: drop all Force Offroad intent. Leave NAP/OP as it was.""" + apply_force_offroad_toggle(params, False, started=False) + + +def allows_onroad(force_offroad: bool, *, handoff_ready: bool = True, + already_started: bool = False, timed_out: bool = False, + confirmed: bool = True) -> bool: + """True unless Force Offroad may flip started=false. + + Default kwargs keep the old one-arg call: toggle ON + not already + started → block start (parked / already offroad). While onroad, hold + started until the driver taps Yes *and* card reports stock-CC ENABLED + (or timeout). Do not start the timeout until Yes. + """ + if not force_offroad: + return True + if not already_started: + return False + if not confirmed: + return True + return not (handoff_ready or timed_out) + + +def handoff_wait_timed_out(wait_started_mono: float | None, now_mono: float, + timeout_s: float = HANDOFF_TIMEOUT_S) -> bool: + if wait_started_mono is None: + return False + return (now_mono - wait_started_mono) >= timeout_s + + +def should_start_now(onroad_conditions: dict[str, bool], startup_conditions: dict[str, bool], + already_started: bool) -> bool: + """deviceState.started decision. already_started skips startup_conditions.""" + should_start = all(onroad_conditions.values()) + if not already_started: + should_start = should_start and all(startup_conditions.values()) + return should_start diff --git a/system/hardware/pc/hardware.h b/system/hardware/pc/hardware.h index 5dea184ca6db91..71f58b188bed01 100644 --- a/system/hardware/pc/hardware.h +++ b/system/hardware/pc/hardware.h @@ -6,18 +6,9 @@ class HardwarePC : public HardwareNone { public: - static std::string get_os_version() { return "openpilot for PC"; } static std::string get_name() { return "pc"; } static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::PC; } static bool PC() { return true; } static bool TICI() { return util::getenv("TICI", 0) == 1; } static bool AGNOS() { return util::getenv("TICI", 0) == 1; } - - static void config_cpu_rendering(bool offscreen) { - if (offscreen) { - setenv("QT_QPA_PLATFORM", "offscreen", 1); - } - setenv("__GLX_VENDOR_LIBRARY_NAME", "mesa", 1); - setenv("LP_NUM_THREADS", "0", 1); // disable threading so we stay on our assigned CPU - } }; diff --git a/system/hardware/pc/hardware.py b/system/hardware/pc/hardware.py index 719e272aea1639..f3d527429ce4a6 100644 --- a/system/hardware/pc/hardware.py +++ b/system/hardware/pc/hardware.py @@ -1,84 +1,12 @@ -import random - from cereal import log -from openpilot.system.hardware.base import HardwareBase, ThermalConfig +from openpilot.system.hardware.base import HardwareBase NetworkType = log.DeviceState.NetworkType -NetworkStrength = log.DeviceState.NetworkStrength class Pc(HardwareBase): - def get_os_version(self): - return None - def get_device_type(self): return "pc" - def get_sound_card_online(self): - return True - - def reboot(self, reason=None): - print("REBOOT!") - - def uninstall(self): - print("uninstall") - - def get_imei(self, slot): - return "%015d" % random.randint(0, 1 << 32) - - def get_serial(self): - return "cccccccc" - - def get_network_info(self): - return None - def get_network_type(self): return NetworkType.wifi - - def get_sim_info(self): - return { - 'sim_id': '', - 'mcc_mnc': None, - 'network_type': ["Unknown"], - 'sim_state': ["ABSENT"], - 'data_connected': False - } - - def get_network_strength(self, network_type): - return NetworkStrength.unknown - - def get_current_power_draw(self): - return 0 - - def get_som_power_draw(self): - return 0 - - def shutdown(self): - print("SHUTDOWN!") - - def get_thermal_config(self): - return ThermalConfig(cpu=((None,), 1), gpu=((None,), 1), mem=(None, 1), bat=(None, 1), pmic=((None,), 1)) - - def set_screen_brightness(self, percentage): - pass - - def get_screen_brightness(self): - return 0 - - def set_power_save(self, powersave_enabled): - pass - - def get_gpu_usage_percent(self): - return 0 - - def get_modem_temperatures(self): - return [] - - def get_nvme_temperatures(self): - return [] - - def initialize_hardware(self): - pass - - def get_networks(self): - return None diff --git a/system/hardware/power_monitoring.py b/system/hardware/power_monitoring.py index 5a94625b486b1e..161b5d23eff40d 100644 --- a/system/hardware/power_monitoring.py +++ b/system/hardware/power_monitoring.py @@ -29,12 +29,10 @@ def __init__(self): self.car_voltage_instant_mV = 12e3 # Last value of peripheralState voltage self.integration_lock = threading.Lock() - car_battery_capacity_uWh = self.params.get("CarBatteryCapacity") - if car_battery_capacity_uWh is None: - car_battery_capacity_uWh = 0 + car_battery_capacity_uWh = self.params.get("CarBatteryCapacity") or 0 # Reset capacity if it's low - self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), int(car_battery_capacity_uWh)) + self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), car_battery_capacity_uWh) # Calculation tick def calculate(self, voltage: int | None, ignition: bool): @@ -58,7 +56,7 @@ def calculate(self, voltage: int | None, ignition: bool): self.car_battery_capacity_uWh = max(self.car_battery_capacity_uWh, 0) self.car_battery_capacity_uWh = min(self.car_battery_capacity_uWh, CAR_BATTERY_CAPACITY_uWh) if now - self.last_save_time >= 10: - self.params.put_nonblocking("CarBatteryCapacity", str(int(self.car_battery_capacity_uWh))) + self.params.put("CarBatteryCapacity", int(self.car_battery_capacity_uWh)) self.last_save_time = now # First measurement, set integration time diff --git a/system/hardware/sysfs_reader.py b/system/hardware/sysfs_reader.py new file mode 100644 index 00000000000000..0e406af1329168 --- /dev/null +++ b/system/hardware/sysfs_reader.py @@ -0,0 +1,73 @@ +"""Off-loop system-file reads for hardwared. + +Oct 13 2026 11:25 CT (route 0000018e seg 23): the 2 Hz deviceState loop +blocked 12.6 s inside HARDWARE.get_som_power_draw() (bms sysfs read), +deviceState went silent and selfdrived raised commIssue. Same class as the +Oct 7/11 thermal hangs (moved to thermal_reader.py). + +Every remaining sysfs / procfs / statvfs / sudo read the publish loop used +to make inline now runs here, in a background thread, with per-read timing. +The publish loop only reads the last cached value from SysReadCache.get(), +which never blocks on I/O. A hung read delays only fresh values; deviceState +keeps publishing with the previous ones. +""" + +import threading +import time +from collections.abc import Callable + +from openpilot.common.realtime import DT_HW +from openpilot.common.swaglog import cloudlog + +SLOW_READ_S = 0.25 + + +class SysReadCache: + """Latest value per named read, shared between the reader thread and the publish loop.""" + + def __init__(self, defaults: dict, clock=time.monotonic): + self._lock = threading.Lock() + self._values = dict(defaults) + self._updated: dict[str, float] = {} + self._clock = clock + + def set(self, name: str, value) -> None: + with self._lock: + self._values[name] = value + self._updated[name] = self._clock() + + def get(self, name: str, default=None): + with self._lock: + return self._values.get(name, default) + + def age_s(self, name: str) -> float | None: + with self._lock: + t = self._updated.get(name) + return None if t is None else self._clock() - t + + +def read_once(readers: dict[str, Callable], cache: SysReadCache, clock=time.monotonic, slow_read_s=SLOW_READ_S) -> dict: + """Run each reader once, store results; returns {name: seconds} for slow reads.""" + t0 = clock() + slow: dict[str, float] = {} + for name, fn in readers.items(): + s = clock() + try: + cache.set(name, fn()) + except Exception: + cloudlog.exception(f"hardwared sysfs read failed: {name}") + dt = clock() - s + if dt > slow_read_s: + slow[name] = dt + if slow: + cloudlog.event("hardwared slow sysfs read", error=True, + reads_ms={k: round(v * 1000.0, 1) for k, v in slow.items()}, + total_ms=round((clock() - t0) * 1000.0, 1)) + return slow + + +def sysfs_reader_thread(end_event, readers: dict[str, Callable], cache: SysReadCache, period_s=DT_HW, clock=time.monotonic): + while not end_event.is_set(): + start = clock() + read_once(readers, cache, clock=clock) + end_event.wait(max(0.0, period_s - (clock() - start))) diff --git a/system/hardware/tests/test_fan_controller.py b/system/hardware/tests/test_fan_controller.py index 002c1edfda50ba..ee39a24f8748b4 100644 --- a/system/hardware/tests/test_fan_controller.py +++ b/system/hardware/tests/test_fan_controller.py @@ -1,12 +1,12 @@ import pytest -from openpilot.system.hardware.fan_controller import TiciFanController +from openpilot.system.hardware.fan_controller import FanController -ALL_CONTROLLERS = [TiciFanController] +ALL_CONTROLLERS = [FanController] def patched_controller(mocker, controller_class): mocker.patch("os.system", new=mocker.Mock()) - return controller_class() + return controller_class(2) class TestFanController: def wind_up(self, controller, ignition=True): diff --git a/system/hardware/tests/test_power_monitoring.py b/system/hardware/tests/test_power_monitoring.py index 1dff6c6c5f728e..5e1b751a0f2a05 100644 --- a/system/hardware/tests/test_power_monitoring.py +++ b/system/hardware/tests/test_power_monitoring.py @@ -139,7 +139,7 @@ def test_car_voltage(self, mocker): def test_disable_power_down(self, mocker): POWER_DRAW = 0 # To stop shutting down for other reasons TEST_TIME = 100 - self.params.put_bool("DisablePowerDown", True) + self.params.put_bool("DisablePowerDown", True, block=True) pm_patch(mocker, "HARDWARE.get_current_power_draw", POWER_DRAW) pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh diff --git a/system/hardware/tests/test_sysfs_reader.py b/system/hardware/tests/test_sysfs_reader.py new file mode 100644 index 00000000000000..8d4fcce04ef22e --- /dev/null +++ b/system/hardware/tests/test_sysfs_reader.py @@ -0,0 +1,118 @@ +import ast +import inspect +import textwrap +import threading +import time + +from openpilot.system.hardware import sysfs_reader as sr +from openpilot.system.hardware.sysfs_reader import SysReadCache, read_once, sysfs_reader_thread + + +class FakeClock: + def __init__(self): + self.t = 100.0 + + def __call__(self): + return self.t + + +def test_read_once_caches_and_names_slow_read(monkeypatch): + clk = FakeClock() + events = [] + monkeypatch.setattr(sr.cloudlog, "event", lambda name, **kw: events.append((name, kw))) + def slow_som(): + clk.t += 13.0 + return 4.2 + cache = SysReadCache({"power_draw": 0.0, "som_power_draw": 0.0}, clock=clk) + slow = read_once({"power_draw": lambda: 1.5, "som_power_draw": slow_som}, cache, clock=clk) + assert cache.get("power_draw") == 1.5 + assert cache.get("som_power_draw") == 4.2 + assert list(slow) == ["som_power_draw"] + assert events and events[0][0] == "hardwared slow sysfs read" + assert events[0][1]["reads_ms"] == {"som_power_draw": 13000.0} + + +def test_failed_read_keeps_last_value(monkeypatch): + monkeypatch.setattr(sr.cloudlog, "exception", lambda *a, **k: None) + cache = SysReadCache({"gpu": 7}) + def boom(): + raise OSError("EIO") + read_once({"gpu": boom}, cache) + assert cache.get("gpu") == 7 + + +def test_13s_hung_power_draw_read_does_not_stop_2hz_device_state(): + """Real threads: the power-draw read hangs ~13 s (Oct 13 11:25 route 0000018e + seg 23). The 2 Hz publish loop keeps sending deviceState with the last + cached power values and never blocks; fresh values resume after the hang.""" + release = threading.Event() + armed = {"on": False} + hang_done = threading.Event() + def som_power_draw(): + if armed["on"]: + armed["on"] = False + release.wait(13.0) + hang_done.set() + return 9.9 + return 9.9 if hang_done.is_set() else 3.3 + cache = SysReadCache({"power_draw": 0.0, "som_power_draw": 0.0, "memory": 0}) + readers = {"power_draw": lambda: 1.1, "som_power_draw": som_power_draw, "memory": lambda: 42} + end = threading.Event() + threading.Thread(target=sysfs_reader_thread, args=(end, readers, cache), daemon=True).start() + time.sleep(0.6) + assert cache.get("som_power_draw") == 3.3 + armed["on"] = True + + published = [] # (t, powerDrawW, somPowerDrawW) + t0 = time.monotonic() + # run through the hang plus ~1 s after it ends (bounded for slow CI) + done_at = None + while time.monotonic() - t0 < 20.0: + if hang_done.is_set() and done_at is None: + done_at = time.monotonic() + if done_at is not None and time.monotonic() - done_at > 1.0: + break + start = time.monotonic() + msg = {"powerDrawW": cache.get("power_draw", 0.0), "somPowerDrawW": cache.get("som_power_draw", 0.0), + "memoryUsagePercent": cache.get("memory", 0)} + published.append((start - t0, msg)) + assert time.monotonic() - start < 0.05 # never blocks on the hung read + time.sleep(max(0.0, 0.5 - (time.monotonic() - start))) + end.set() + release.set() + + times = [t for t, _ in published] + gaps = [b - a for a, b in zip(times, times[1:], strict=False)] + assert max(gaps) < 0.7 + assert done_at is not None and done_at - t0 > 12.0 # it really hung ~13 s + assert len(published) >= 26 + # during the hang deviceState kept the last good value (not zero) + assert all(m["somPowerDrawW"] in (3.3, 9.9) for _, m in published) + assert all(m["memoryUsagePercent"] == 42 for _, m in published) + assert any(m["somPowerDrawW"] == 3.3 for t, m in published if 5.0 < t < 12.0) + # read finished at ~13 s, value updated + assert published[-1][1]["somPowerDrawW"] == 9.9 + + +BLOCKING_CALLS = { + "get_current_power_draw", "get_som_power_draw", "get_gpu_usage_percent", "get_screen_brightness", + "booted", "get_available_percent", "virtual_memory", "cpu_percent", "get_msg", +} + + +def test_publish_loop_makes_no_blocking_system_file_reads(): + """Guard: inside hardware_thread's `while` loop, none of these reads may be + called directly (they belong in sysfs_reader / thermal_reader threads).""" + from openpilot.system.hardware import hardwared + tree = ast.parse(textwrap.dedent(inspect.getsource(hardwared.hardware_thread))) + loops = [n for n in ast.walk(tree) if isinstance(n, ast.While)] + assert loops + bad = set() + for loop in loops: + for n in ast.walk(loop): + if isinstance(n, ast.Call): + f = n.func + name = f.attr if isinstance(f, ast.Attribute) else getattr(f, "id", None) + if name in BLOCKING_CALLS: + bad.add(name) + assert not bad, f"blocking reads on the publish loop: {sorted(bad)}" diff --git a/system/hardware/tests/test_thermal_reader.py b/system/hardware/tests/test_thermal_reader.py new file mode 100644 index 00000000000000..c6c0f91eddf7ab --- /dev/null +++ b/system/hardware/tests/test_thermal_reader.py @@ -0,0 +1,150 @@ +import queue +import threading +import time +from dataclasses import dataclass + +from cereal import log +from openpilot.system.hardware.thermal_reader import ( + STALE_AFTER_S, STALE_ESCALATE_S, ThermalCache, stale_thermal_status, read_thermal_snapshot, thermal_reader_thread, +) + +ThermalStatus = log.DeviceState.ThermalStatus + + +class FakeZone: + def __init__(self, name, temp, block=None): + self.name, self.temp, self.block = name, temp, block + + def read(self): + if self.block is not None: + self.block() + return self.temp + + +@dataclass +class FakeConfig: + cpu: list | None = None + pmic: list | None = None + memory: FakeZone | None = None + + +class FakeClock: + def __init__(self): + self.t = 100.0 + + def __call__(self): + return self.t + + +def test_snapshot_matches_get_msg_shape_and_names_slow_zone(): + clk = FakeClock() + def slow(): + clk.t += 13.0 + cfg = FakeConfig(cpu=[FakeZone("cpu0", 50.), FakeZone("cpu1", 51.)], + pmic=[FakeZone("pm8998_tz", 45., block=slow)], memory=FakeZone("ddr", 40.)) + snap = read_thermal_snapshot(cfg, clock=clk) + assert snap.temps == {"cpuTempC": [50., 51.], "pmicTempC": [45.], "memoryTempC": 40.} + assert list(snap.slow_zones) == ["pm8998_tz"] + assert abs(snap.slow_zones["pm8998_tz"] - 13.0) < 1e-6 + + +def test_stale_flag_and_holds_last_temps(): + clk = FakeClock() + q = queue.Queue(maxsize=1) + cache = ThermalCache(q, clock=clk) + q.put_nowait(read_thermal_snapshot(FakeConfig(memory=FakeZone("ddr", 70.)), clock=clk)) + assert cache.poll() is False + clk.t += STALE_AFTER_S - 0.5 + assert cache.poll() is False + clk.t += 1.0 + assert cache.poll() is True + assert cache.temps == {"memoryTempC": 70.} # held, not zeroed + q.put_nowait(read_thermal_snapshot(FakeConfig(memory=FakeZone("ddr", 71.)), clock=clk)) + assert cache.poll() is False + assert cache.temps["memoryTempC"] == 71. + + +OK, OV, CRIT = ThermalStatus.ok, ThermalStatus.overheated, ThermalStatus.critical +YELLOW_T = 92.0 + + +def status(st, stale, stale_s, temp): + return stale_thermal_status(st, stale, stale_s, temp, YELLOW_T, OK, OV) + + +def test_stale_green_holds_up_to_60s_then_escalates(): + assert status(OK, False, 0.0, 76.) == OK + assert status(OK, True, 3.0, 76.) == OK # 13 s stall = 3 s stale + assert status(OK, True, STALE_ESCALATE_S, 76.) == OK + assert status(OK, True, STALE_ESCALATE_S + 0.5, 76.) == OV + + +def test_stale_from_yellow_escalates_immediately(): + assert status(OK, True, 0.0, 93.) == OV # last reading in yellow zone + assert status(OV, True, 0.0, 90.) == OV + assert status(CRIT, True, 0.0, 99.) == CRIT # never cooler + + +def test_stale_start_end_logged(monkeypatch): + import openpilot.system.hardware.thermal_reader as tr + events = [] + monkeypatch.setattr(tr.cloudlog, "event", lambda name, **kw: events.append((name, kw))) + clk = FakeClock() + q = queue.Queue(maxsize=1) + cache = ThermalCache(q, clock=clk) + q.put_nowait(read_thermal_snapshot(FakeConfig(memory=FakeZone("ddr", 70.)), clock=clk)) + cache.poll() + clk.t += STALE_AFTER_S + 1 + cache.poll() + clk.t += 70 + assert cache.stale_s > STALE_ESCALATE_S + q.put_nowait(read_thermal_snapshot(FakeConfig(memory=FakeZone("ddr", 70.)), clock=clk)) + cache.poll() + names = [n for n, _ in events] + assert names == ["hardwared thermal stale start", "hardwared thermal stale end"] + assert events[1][1]["stale_s"] == 70.0 + assert cache.stale_s == 0.0 + + +def test_13s_thermal_read_does_not_stop_2hz_publish(): + """Real threads: one zone sleeps 13 s. The 2 Hz publish loop keeps going, + goes stale after 10 s at green (76 C) without any alert, then recovers.""" + release = threading.Event() + stall_once = {"armed": False} + def stall(): + if stall_once["armed"]: + stall_once["armed"] = False + release.wait(13.0) + cfg = FakeConfig(cpu=[FakeZone("cpu0", 60.)], pmic=[FakeZone("pm8998_tz", 50., block=stall)]) + q = queue.Queue(maxsize=1) + end = threading.Event() + th = threading.Thread(target=thermal_reader_thread, args=(end, cfg, q), daemon=True) + th.start() + cache = ThermalCache(q) + time.sleep(0.6) + cache.poll() + assert cache.snapshot is not None + stall_once["armed"] = True + + publishes, stale_seen, statuses = [], [], [] + t0 = time.monotonic() + while time.monotonic() - t0 < 15.0: + start = time.monotonic() + stale = cache.poll() + publishes.append(start) + stale_seen.append((start - t0, stale)) + statuses.append(status(OK, stale, cache.stale_s, 76.)) + assert time.monotonic() - start < 0.05 # never blocks on the sensor + time.sleep(max(0.0, 0.5 - (time.monotonic() - start))) + end.set() + release.set() + + gaps = [b - a for a, b in zip(publishes, publishes[1:], strict=False)] + assert max(gaps) < 0.7 + assert len(publishes) >= 28 + assert any(s for _, s in stale_seen) + assert not any(s for t, s in stale_seen if t < 9.0) + assert all(st == OK for st in statuses) # no overheat alert at green + # read finished at ~13 s, then fresh again + assert stale_seen[-1][1] is False + assert statuses[-1] == ThermalStatus.ok diff --git a/system/hardware/thermal_reader.py b/system/hardware/thermal_reader.py new file mode 100644 index 00000000000000..f46bc5fc9a80df --- /dev/null +++ b/system/hardware/thermal_reader.py @@ -0,0 +1,141 @@ +"""Off-loop thermal-zone reads for hardwared. + +The 2 Hz deviceState loop used to call thermal_config.get_msg() inline. A +sysfs thermal read that sleeps (Oct 11 2026: 12.7 s in one pass) then stops +deviceState and selfdrived raises commIssue. The reads now run in their own +thread; the publish loop only takes the latest snapshot from a queue and +never blocks on a sensor. + +If no fresh snapshot arrives for STALE_AFTER_S, the cache reports stale. +hardwared then keeps the last temperatures and thermalStatus (never zeros +or cools them) and runs the fan at full. It escalates to at least +`overheated` (fail hot) only if the last good reading was already "yellow" +(max temp at or above the overheated band's entry temperature, or status +already above ok), or once stale time passes STALE_ESCALATE_S. +""" + +import queue +import time +from dataclasses import dataclass, field, fields + +from openpilot.common.realtime import DT_HW +from openpilot.common.swaglog import cloudlog + +STALE_AFTER_S = 10.0 +STALE_ESCALATE_S = 60.0 # stale time (after STALE_AFTER_S) before failing hot +SLOW_ZONE_S = 0.25 + + +@dataclass +class ThermalSnapshot: + temps: dict # deviceState field name -> float or list[float] + t: float # monotonic time the read finished + read_s: float = 0.0 + slow_zones: dict = field(default_factory=dict) # zone name -> seconds + + +def _zones(thermal_config): + for f in fields(thermal_config): + v = getattr(thermal_config, f.name) + if v is not None: + yield f.name + "TempC", v + + +def read_thermal_snapshot(thermal_config, clock=time.monotonic, slow_zone_s=SLOW_ZONE_S) -> ThermalSnapshot: + """Same values as ThermalConfig.get_msg(), with per-zone timing.""" + t0 = clock() + temps: dict = {} + slow: dict = {} + + def timed(zone): + s = clock() + val = zone.read() + dt = clock() - s + if dt > slow_zone_s: + slow[getattr(zone, "name", "?")] = dt + return val + + for key, v in _zones(thermal_config): + temps[key] = [timed(z) for z in v] if isinstance(v, list) else timed(v) + t1 = clock() + if slow: + ms = {k: round(v * 1000.0, 1) for k, v in slow.items()} + cloudlog.event("hardwared slow thermal zone", error=True, zones_ms=ms, total_ms=round((t1 - t0) * 1000.0, 1)) + return ThermalSnapshot(temps=temps, t=t1, read_s=t1 - t0, slow_zones=slow) + + +def thermal_reader_thread(end_event, thermal_config, thermal_queue, period_s=DT_HW, clock=time.monotonic): + while not end_event.is_set(): + start = clock() + try: + snap = read_thermal_snapshot(thermal_config, clock=clock) + # keep only the newest snapshot + try: + thermal_queue.get_nowait() + except queue.Empty: + pass + try: + thermal_queue.put_nowait(snap) + except queue.Full: + pass + except Exception: + cloudlog.exception("Error reading thermal zones") + end_event.wait(max(0.0, period_s - (clock() - start))) + + +class ThermalCache: + """Latest thermal snapshot as seen by the publish loop. Never blocks.""" + + def __init__(self, thermal_queue, clock=time.monotonic, stale_after_s=STALE_AFTER_S): + self._q = thermal_queue + self._clock = clock + self._stale_after_s = stale_after_s + self._start = clock() + self.snapshot: ThermalSnapshot | None = None + self.stale = False + self.stale_since: float | None = None + + def poll(self) -> bool: + try: + while True: + self.snapshot = self._q.get_nowait() + except queue.Empty: + pass + ref = self.snapshot.t if self.snapshot is not None else self._start + stale = (self._clock() - ref) > self._stale_after_s + now = self._clock() + if stale != self.stale: + if stale: + self.stale_since = now + cloudlog.event("hardwared thermal stale start", error=True, age_s=round(now - ref, 1)) + else: + cloudlog.event("hardwared thermal stale end", error=True, + stale_s=round(now - (self.stale_since or now), 1)) + self.stale_since = None + self.stale = stale + return stale + + @property + def stale_s(self) -> float: + """Seconds since the cache went stale (0 when fresh).""" + return 0.0 if self.stale_since is None else self._clock() - self.stale_since + + @property + def temps(self) -> dict: + return {} if self.snapshot is None else self.snapshot.temps + + +def stale_thermal_status(status, stale: bool, stale_s: float, last_temp: float, yellow_temp: float, + ok, overheated, escalate_s: float = STALE_ESCALATE_S): + """thermalStatus to publish given cache staleness. + + Fresh: unchanged. Stale: keep the last status (never cooler), but fail hot + (at least `overheated`) if the last good reading was already yellow or + worse, or once stale for longer than escalate_s. + """ + if not stale: + return status + was_yellow = status > ok or last_temp >= yellow_temp + if was_yellow or stale_s > escalate_s: + return max(status, overheated) + return status diff --git a/system/hardware/tici/agnos.json b/system/hardware/tici/agnos.json index b1862bdef9351f..07e2079ec9f7d1 100644 --- a/system/hardware/tici/agnos.json +++ b/system/hardware/tici/agnos.json @@ -1,77 +1,84 @@ [ { - "name": "boot", - "url": "https://commadist.azureedge.net/agnosupdate/boot-5674ea6767e7198cf1e7def3de66a57061f001ed76d43dc4b4f84de545c53c6f.img.xz", - "hash": "5674ea6767e7198cf1e7def3de66a57061f001ed76d43dc4b4f84de545c53c6f", - "hash_raw": "5674ea6767e7198cf1e7def3de66a57061f001ed76d43dc4b4f84de545c53c6f", - "size": 16029696, + "name": "xbl", + "url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz", + "hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb", + "hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb", + "size": 3282256, "sparse": false, "full_check": true, - "has_ab": true + "has_ab": true, + "ondevice_hash": "bea7f1a24428c3ededf672fa4fc78baf180cfbd8aafb77c974655b38517283e3" }, { - "name": "abl", - "url": "https://commadist.azureedge.net/agnosupdate/abl-eeb89a74c968a5a2ffce96f23158b72e03e2814adf72ef59d1200ba8ea5d2f39.img.xz", - "hash": "eeb89a74c968a5a2ffce96f23158b72e03e2814adf72ef59d1200ba8ea5d2f39", - "hash_raw": "eeb89a74c968a5a2ffce96f23158b72e03e2814adf72ef59d1200ba8ea5d2f39", - "size": 274432, + "name": "xbl_config", + "url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz", + "hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85", + "hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85", + "size": 98124, "sparse": false, "full_check": true, - "has_ab": true + "has_ab": true, + "ondevice_hash": "fb18cde08a98a168961ecd357e92474823046752b94e112f59fe51a6acd7197d" }, { - "name": "xbl", - "url": "https://commadist.azureedge.net/agnosupdate/xbl-bcef195b00a1ab685da601f4072722569773ab161e91c8753ad99ca4217a28f5.img.xz", - "hash": "bcef195b00a1ab685da601f4072722569773ab161e91c8753ad99ca4217a28f5", - "hash_raw": "bcef195b00a1ab685da601f4072722569773ab161e91c8753ad99ca4217a28f5", - "size": 3282672, + "name": "abl", + "url": "https://commadist.azureedge.net/agnosupdate/abl-b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c.img.xz", + "hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c", + "hash_raw": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c", + "size": 274432, "sparse": false, "full_check": true, - "has_ab": true + "has_ab": true, + "ondevice_hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c" }, { - "name": "xbl_config", - "url": "https://commadist.azureedge.net/agnosupdate/xbl_config-19791056558c16f8dae787531b5e30b3b3db2ded9d666688df45ce1b91a72bac.img.xz", - "hash": "19791056558c16f8dae787531b5e30b3b3db2ded9d666688df45ce1b91a72bac", - "hash_raw": "19791056558c16f8dae787531b5e30b3b3db2ded9d666688df45ce1b91a72bac", - "size": 98124, + "name": "aop", + "url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz", + "hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1", + "hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1", + "size": 184364, "sparse": false, "full_check": true, - "has_ab": true + "has_ab": true, + "ondevice_hash": "6c9135446bd3fc075fcee59b887a12e49029ab1f98ed8d6d1e32c73569d47de3" }, { "name": "devcfg", - "url": "https://commadist.azureedge.net/agnosupdate/devcfg-be44b73dda5be840b09d5347d536459e31098da3fea97596956c0bdad19bdf27.img.xz", - "hash": "be44b73dda5be840b09d5347d536459e31098da3fea97596956c0bdad19bdf27", - "hash_raw": "be44b73dda5be840b09d5347d536459e31098da3fea97596956c0bdad19bdf27", + "url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz", + "hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc", + "hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc", "size": 40336, "sparse": false, "full_check": true, - "has_ab": true + "has_ab": true, + "ondevice_hash": "2a67971602012c1b43544964709da13c322786b456a8e78568b117e8b1540ce3" }, { - "name": "aop", - "url": "https://commadist.azureedge.net/agnosupdate/aop-5d764611a683d6a738cf06a1dcf8a926d0f47b5117ad40d3054167de6dd8bd0f.img.xz", - "hash": "5d764611a683d6a738cf06a1dcf8a926d0f47b5117ad40d3054167de6dd8bd0f", - "hash_raw": "5d764611a683d6a738cf06a1dcf8a926d0f47b5117ad40d3054167de6dd8bd0f", - "size": 184364, + "name": "boot", + "url": "https://commadist.azureedge.net/agnosupdate/boot-8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8.img.xz", + "hash": "8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8", + "hash_raw": "8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8", + "size": 17487872, "sparse": false, "full_check": true, - "has_ab": true + "has_ab": true, + "ondevice_hash": "edca8bee1531e66953d107eeceeed2dc7b3ca46417e49d55508f94e58bf95db8" }, { "name": "system", - "url": "https://commadist.azureedge.net/agnosupdate/system-1badfe72851628d6cf9200a53a6151bb4e797b49c717141409fc57138eae388a.img.xz", - "hash": "328e90c62068222dfd98f71dd3f6251fcb962f082b49c6be66ab2699f5db6f4f", - "hash_raw": "1badfe72851628d6cf9200a53a6151bb4e797b49c717141409fc57138eae388a", - "size": 10737418240, + "url": "https://commadist.azureedge.net/agnosupdate/system-ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f.img.xz", + "hash": "78acfe16a7b62a3a91fc7a81f40a693e4468cec1c69df7d0b1e550aacc646113", + "hash_raw": "ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f", + "size": 4718592000, "sparse": true, "full_check": false, "has_ab": true, + "ondevice_hash": "743142c5a898f27b2a1029cca42c8a5d5d1fc0096414422b850fe84c8d0b8342", "alt": { - "hash": "bc11d2148f29862ee1326aca2af1cf6bbf5fed831e3f8f6b8f7a0f110dfe8d26", - "url": "https://commadist.azureedge.net/agnosupdate/system-skip-chunks-1badfe72851628d6cf9200a53a6151bb4e797b49c717141409fc57138eae388a.img.xz", - "size": 4548070000 + "hash": "ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f", + "url": "https://commadist.azureedge.net/agnosupdate/system-ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f.img", + "size": 4718592000 } } ] \ No newline at end of file diff --git a/system/hardware/tici/all-partitions.json b/system/hardware/tici/all-partitions.json new file mode 100644 index 00000000000000..80a0f7702ebcd5 --- /dev/null +++ b/system/hardware/tici/all-partitions.json @@ -0,0 +1,389 @@ +[ + { + "name": "gpt_main_0", + "url": "https://commadist.azureedge.net/agnosupdate/gpt_main_0-8928a31fd9ee20f8703649f89833eba9b55e84b6415e67799c777b163c95a0bd.img.xz", + "hash": "8928a31fd9ee20f8703649f89833eba9b55e84b6415e67799c777b163c95a0bd", + "hash_raw": "8928a31fd9ee20f8703649f89833eba9b55e84b6415e67799c777b163c95a0bd", + "size": 24576, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "8928a31fd9ee20f8703649f89833eba9b55e84b6415e67799c777b163c95a0bd", + "gpt": { + "lun": 0, + "start_sector": 0, + "num_sectors": 6 + } + }, + { + "name": "gpt_main_1", + "url": "https://commadist.azureedge.net/agnosupdate/gpt_main_1-fe8ef7653db588d7420a625920ca06927dfcb0ed8aff3e3a1c74a52a24398ba6.img.xz", + "hash": "fe8ef7653db588d7420a625920ca06927dfcb0ed8aff3e3a1c74a52a24398ba6", + "hash_raw": "fe8ef7653db588d7420a625920ca06927dfcb0ed8aff3e3a1c74a52a24398ba6", + "size": 24576, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "fe8ef7653db588d7420a625920ca06927dfcb0ed8aff3e3a1c74a52a24398ba6", + "gpt": { + "lun": 1, + "start_sector": 0, + "num_sectors": 6 + } + }, + { + "name": "gpt_main_2", + "url": "https://commadist.azureedge.net/agnosupdate/gpt_main_2-5ccfc7240c8cbfa2f1a018a2e376cf274a6baf858c9bfe71951d8e28cab53c21.img.xz", + "hash": "5ccfc7240c8cbfa2f1a018a2e376cf274a6baf858c9bfe71951d8e28cab53c21", + "hash_raw": "5ccfc7240c8cbfa2f1a018a2e376cf274a6baf858c9bfe71951d8e28cab53c21", + "size": 24576, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "5ccfc7240c8cbfa2f1a018a2e376cf274a6baf858c9bfe71951d8e28cab53c21", + "gpt": { + "lun": 2, + "start_sector": 0, + "num_sectors": 6 + } + }, + { + "name": "gpt_main_3", + "url": "https://commadist.azureedge.net/agnosupdate/gpt_main_3-c707979fa21e89519328f4f30c2b21c9c453401ca8303f914c1873d410a95159.img.xz", + "hash": "c707979fa21e89519328f4f30c2b21c9c453401ca8303f914c1873d410a95159", + "hash_raw": "c707979fa21e89519328f4f30c2b21c9c453401ca8303f914c1873d410a95159", + "size": 24576, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "c707979fa21e89519328f4f30c2b21c9c453401ca8303f914c1873d410a95159", + "gpt": { + "lun": 3, + "start_sector": 0, + "num_sectors": 6 + } + }, + { + "name": "gpt_main_4", + "url": "https://commadist.azureedge.net/agnosupdate/gpt_main_4-e9405dcd785dbe79412184e1894a9c51ab7deb33bb612166c4c42a3d2bf42a0e.img.xz", + "hash": "e9405dcd785dbe79412184e1894a9c51ab7deb33bb612166c4c42a3d2bf42a0e", + "hash_raw": "e9405dcd785dbe79412184e1894a9c51ab7deb33bb612166c4c42a3d2bf42a0e", + "size": 24576, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "e9405dcd785dbe79412184e1894a9c51ab7deb33bb612166c4c42a3d2bf42a0e", + "gpt": { + "lun": 4, + "start_sector": 0, + "num_sectors": 6 + } + }, + { + "name": "gpt_main_5", + "url": "https://commadist.azureedge.net/agnosupdate/gpt_main_5-21ae965f05b2fa8d02e04f1eb74718f9779864f6eacdeb859757d6435e8ccce3.img.xz", + "hash": "21ae965f05b2fa8d02e04f1eb74718f9779864f6eacdeb859757d6435e8ccce3", + "hash_raw": "21ae965f05b2fa8d02e04f1eb74718f9779864f6eacdeb859757d6435e8ccce3", + "size": 24576, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "21ae965f05b2fa8d02e04f1eb74718f9779864f6eacdeb859757d6435e8ccce3", + "gpt": { + "lun": 5, + "start_sector": 0, + "num_sectors": 6 + } + }, + { + "name": "persist", + "url": "https://commadist.azureedge.net/agnosupdate/persist-d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786.img.xz", + "hash": "d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786", + "hash_raw": "d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786", + "size": 4096, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786" + }, + { + "name": "systemrw", + "url": "https://commadist.azureedge.net/agnosupdate/systemrw-8ce150ca38ef64a0885fc2fe816e5b63bae8adb4df5d809c5b318e6996366c7e.img.xz", + "hash": "8ce150ca38ef64a0885fc2fe816e5b63bae8adb4df5d809c5b318e6996366c7e", + "hash_raw": "8ce150ca38ef64a0885fc2fe816e5b63bae8adb4df5d809c5b318e6996366c7e", + "size": 16777216, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "8ce150ca38ef64a0885fc2fe816e5b63bae8adb4df5d809c5b318e6996366c7e" + }, + { + "name": "cache", + "url": "https://commadist.azureedge.net/agnosupdate/cache-ebfbaaa2f96dc4e5fea4f126364e5bf5b3b44c12cbc753b62fdd8baab82f70b4.img.xz", + "hash": "ebfbaaa2f96dc4e5fea4f126364e5bf5b3b44c12cbc753b62fdd8baab82f70b4", + "hash_raw": "ebfbaaa2f96dc4e5fea4f126364e5bf5b3b44c12cbc753b62fdd8baab82f70b4", + "size": 134217728, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "ebfbaaa2f96dc4e5fea4f126364e5bf5b3b44c12cbc753b62fdd8baab82f70b4" + }, + { + "name": "xbl", + "url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz", + "hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb", + "hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb", + "size": 3282256, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "bea7f1a24428c3ededf672fa4fc78baf180cfbd8aafb77c974655b38517283e3" + }, + { + "name": "xbl_config", + "url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz", + "hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85", + "hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85", + "size": 98124, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "fb18cde08a98a168961ecd357e92474823046752b94e112f59fe51a6acd7197d" + }, + { + "name": "abl", + "url": "https://commadist.azureedge.net/agnosupdate/abl-b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c.img.xz", + "hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c", + "hash_raw": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c", + "size": 274432, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c" + }, + { + "name": "aop", + "url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz", + "hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1", + "hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1", + "size": 184364, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "6c9135446bd3fc075fcee59b887a12e49029ab1f98ed8d6d1e32c73569d47de3" + }, + { + "name": "bluetooth", + "url": "https://commadist.azureedge.net/agnosupdate/bluetooth-9bb766d2d2ce0cc4491664b3010fe1ef62f8ffc1e362d55f78e48c4141f75533.img.xz", + "hash": "9bb766d2d2ce0cc4491664b3010fe1ef62f8ffc1e362d55f78e48c4141f75533", + "hash_raw": "9bb766d2d2ce0cc4491664b3010fe1ef62f8ffc1e362d55f78e48c4141f75533", + "size": 1048576, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "9bb766d2d2ce0cc4491664b3010fe1ef62f8ffc1e362d55f78e48c4141f75533" + }, + { + "name": "cmnlib64", + "url": "https://commadist.azureedge.net/agnosupdate/cmnlib64-1a876bd151bb9635f18719c4a17f953079de6e11d3eaec800968fc75669e0dc3.img.xz", + "hash": "1a876bd151bb9635f18719c4a17f953079de6e11d3eaec800968fc75669e0dc3", + "hash_raw": "1a876bd151bb9635f18719c4a17f953079de6e11d3eaec800968fc75669e0dc3", + "size": 524288, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "1a876bd151bb9635f18719c4a17f953079de6e11d3eaec800968fc75669e0dc3" + }, + { + "name": "cmnlib", + "url": "https://commadist.azureedge.net/agnosupdate/cmnlib-63df823e8a5fae01d66cb2b8c20f0d2ddb5c5f2425e5d0992a64676273ba1c82.img.xz", + "hash": "63df823e8a5fae01d66cb2b8c20f0d2ddb5c5f2425e5d0992a64676273ba1c82", + "hash_raw": "63df823e8a5fae01d66cb2b8c20f0d2ddb5c5f2425e5d0992a64676273ba1c82", + "size": 524288, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "63df823e8a5fae01d66cb2b8c20f0d2ddb5c5f2425e5d0992a64676273ba1c82" + }, + { + "name": "devcfg", + "url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz", + "hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc", + "hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc", + "size": 40336, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "2a67971602012c1b43544964709da13c322786b456a8e78568b117e8b1540ce3" + }, + { + "name": "devinfo", + "url": "https://commadist.azureedge.net/agnosupdate/devinfo-143869c499a7e878fbeab756e9c53074195770cc41d6d0d10e45c043141389a3.img.xz", + "hash": "143869c499a7e878fbeab756e9c53074195770cc41d6d0d10e45c043141389a3", + "hash_raw": "143869c499a7e878fbeab756e9c53074195770cc41d6d0d10e45c043141389a3", + "size": 4096, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "143869c499a7e878fbeab756e9c53074195770cc41d6d0d10e45c043141389a3" + }, + { + "name": "dsp", + "url": "https://commadist.azureedge.net/agnosupdate/dsp-4b15fbd2f45581f1553f33f01649e450b24aa19d5deff2ac7dcb16a534d9c248.img.xz", + "hash": "4b15fbd2f45581f1553f33f01649e450b24aa19d5deff2ac7dcb16a534d9c248", + "hash_raw": "4b15fbd2f45581f1553f33f01649e450b24aa19d5deff2ac7dcb16a534d9c248", + "size": 33554432, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "4b15fbd2f45581f1553f33f01649e450b24aa19d5deff2ac7dcb16a534d9c248" + }, + { + "name": "hyp", + "url": "https://commadist.azureedge.net/agnosupdate/hyp-ff5ece6a4e3d2b4d898c77ffe193fc8bbc8acebe78263996ecf52373d8088927.img.xz", + "hash": "ff5ece6a4e3d2b4d898c77ffe193fc8bbc8acebe78263996ecf52373d8088927", + "hash_raw": "ff5ece6a4e3d2b4d898c77ffe193fc8bbc8acebe78263996ecf52373d8088927", + "size": 524288, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "ff5ece6a4e3d2b4d898c77ffe193fc8bbc8acebe78263996ecf52373d8088927" + }, + { + "name": "keymaster", + "url": "https://commadist.azureedge.net/agnosupdate/keymaster-5c968c76f29b9a4d66fbe57e639bac6b7a2c83b1758e25abbaf5d276b8a6af04.img.xz", + "hash": "5c968c76f29b9a4d66fbe57e639bac6b7a2c83b1758e25abbaf5d276b8a6af04", + "hash_raw": "5c968c76f29b9a4d66fbe57e639bac6b7a2c83b1758e25abbaf5d276b8a6af04", + "size": 524288, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "5c968c76f29b9a4d66fbe57e639bac6b7a2c83b1758e25abbaf5d276b8a6af04" + }, + { + "name": "limits", + "url": "https://commadist.azureedge.net/agnosupdate/limits-94951a0f7aa55fb6cb975535ce4ebbfe6d695f04cb5424677b01c10dfa2e94e1.img.xz", + "hash": "94951a0f7aa55fb6cb975535ce4ebbfe6d695f04cb5424677b01c10dfa2e94e1", + "hash_raw": "94951a0f7aa55fb6cb975535ce4ebbfe6d695f04cb5424677b01c10dfa2e94e1", + "size": 4096, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "94951a0f7aa55fb6cb975535ce4ebbfe6d695f04cb5424677b01c10dfa2e94e1" + }, + { + "name": "logfs", + "url": "https://commadist.azureedge.net/agnosupdate/logfs-b8b5ac87f3d954404fc7ecbdd9ee3b5b0cf5691e5006e6ec55db4c899ff61220.img.xz", + "hash": "b8b5ac87f3d954404fc7ecbdd9ee3b5b0cf5691e5006e6ec55db4c899ff61220", + "hash_raw": "b8b5ac87f3d954404fc7ecbdd9ee3b5b0cf5691e5006e6ec55db4c899ff61220", + "size": 8388608, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "b8b5ac87f3d954404fc7ecbdd9ee3b5b0cf5691e5006e6ec55db4c899ff61220" + }, + { + "name": "modem", + "url": "https://commadist.azureedge.net/agnosupdate/modem-a3d014f0896d77a2df7e5a80a70f43a51a047b9d03cfc675b6f0e31a6ecc4994.img.xz", + "hash": "a3d014f0896d77a2df7e5a80a70f43a51a047b9d03cfc675b6f0e31a6ecc4994", + "hash_raw": "a3d014f0896d77a2df7e5a80a70f43a51a047b9d03cfc675b6f0e31a6ecc4994", + "size": 125829120, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "a3d014f0896d77a2df7e5a80a70f43a51a047b9d03cfc675b6f0e31a6ecc4994" + }, + { + "name": "qupfw", + "url": "https://commadist.azureedge.net/agnosupdate/qupfw-64cc7c29d5d69b04267452b8b4ddba9f4809e68f476fc162ca283f58537afe4a.img.xz", + "hash": "64cc7c29d5d69b04267452b8b4ddba9f4809e68f476fc162ca283f58537afe4a", + "hash_raw": "64cc7c29d5d69b04267452b8b4ddba9f4809e68f476fc162ca283f58537afe4a", + "size": 65536, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "64cc7c29d5d69b04267452b8b4ddba9f4809e68f476fc162ca283f58537afe4a" + }, + { + "name": "splash", + "url": "https://commadist.azureedge.net/agnosupdate/splash-5c61260048f22ede6e6343fabb27f6ff73f9271f4751a01aaf7abf097afc1f08.img.xz", + "hash": "5c61260048f22ede6e6343fabb27f6ff73f9271f4751a01aaf7abf097afc1f08", + "hash_raw": "5c61260048f22ede6e6343fabb27f6ff73f9271f4751a01aaf7abf097afc1f08", + "size": 34226176, + "sparse": false, + "full_check": true, + "has_ab": false, + "ondevice_hash": "5c61260048f22ede6e6343fabb27f6ff73f9271f4751a01aaf7abf097afc1f08" + }, + { + "name": "storsec", + "url": "https://commadist.azureedge.net/agnosupdate/storsec-4494d86f68b125fbf2c004c824b1c6dbe71e61a65d2a1cc7db13c553edcb3fce.img.xz", + "hash": "4494d86f68b125fbf2c004c824b1c6dbe71e61a65d2a1cc7db13c553edcb3fce", + "hash_raw": "4494d86f68b125fbf2c004c824b1c6dbe71e61a65d2a1cc7db13c553edcb3fce", + "size": 131072, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "4494d86f68b125fbf2c004c824b1c6dbe71e61a65d2a1cc7db13c553edcb3fce" + }, + { + "name": "tz", + "url": "https://commadist.azureedge.net/agnosupdate/tz-e9443bf187641661bfa6c96702b9ab0156e72fb7482500f8799ba9ee2503cb16.img.xz", + "hash": "e9443bf187641661bfa6c96702b9ab0156e72fb7482500f8799ba9ee2503cb16", + "hash_raw": "e9443bf187641661bfa6c96702b9ab0156e72fb7482500f8799ba9ee2503cb16", + "size": 2097152, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "e9443bf187641661bfa6c96702b9ab0156e72fb7482500f8799ba9ee2503cb16" + }, + { + "name": "boot", + "url": "https://commadist.azureedge.net/agnosupdate/boot-8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8.img.xz", + "hash": "8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8", + "hash_raw": "8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8", + "size": 17487872, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "edca8bee1531e66953d107eeceeed2dc7b3ca46417e49d55508f94e58bf95db8" + }, + { + "name": "system", + "url": "https://commadist.azureedge.net/agnosupdate/system-ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f.img.xz", + "hash": "78acfe16a7b62a3a91fc7a81f40a693e4468cec1c69df7d0b1e550aacc646113", + "hash_raw": "ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f", + "size": 4718592000, + "sparse": true, + "full_check": false, + "has_ab": true, + "ondevice_hash": "743142c5a898f27b2a1029cca42c8a5d5d1fc0096414422b850fe84c8d0b8342", + "alt": { + "hash": "ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f", + "url": "https://commadist.azureedge.net/agnosupdate/system-ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f.img", + "size": 4718592000 + } + }, + { + "name": "userdata_90", + "url": "https://commadist.azureedge.net/agnosupdate/userdata_90-14a3fc6e9bd148b9deebf6ae9df2f1b3b759e629b337e41b6895864cdd51f630.img.xz", + "hash": "52160dd01b30b3dc572226e8d549a034b03bc328e80f1f4cd6a857b6dd447687", + "hash_raw": "14a3fc6e9bd148b9deebf6ae9df2f1b3b759e629b337e41b6895864cdd51f630", + "size": 96636764160, + "sparse": true, + "full_check": true, + "has_ab": false, + "ondevice_hash": "3bbc052c7793087946b0cd668c1778f930084f6b00896aeebd193dfce53fa518" + }, + { + "name": "userdata_89", + "url": "https://commadist.azureedge.net/agnosupdate/userdata_89-425c69d021f4ee2f767963bf7b991d1a492485fa465c5f5d001e1cf7de3d62a0.img.xz", + "hash": "02a8c5512754d7781d930d242be3fad01fbce652297c69dfe8722dc92b18dc09", + "hash_raw": "425c69d021f4ee2f767963bf7b991d1a492485fa465c5f5d001e1cf7de3d62a0", + "size": 95563022336, + "sparse": true, + "full_check": true, + "has_ab": false, + "ondevice_hash": "3667d500f91b08a4671d7c09623eb6ae8fc905d9273893b50689e214005c7fa6" + } +] \ No newline at end of file diff --git a/system/hardware/tici/amplifier.py b/system/hardware/tici/amplifier.py index af82067467eaf1..09436e6ff4625a 100755 --- a/system/hardware/tici/amplifier.py +++ b/system/hardware/tici/amplifier.py @@ -1,28 +1,14 @@ #!/usr/bin/env python3 import time -from smbus2 import SMBus from collections import namedtuple +from openpilot.common.i2c import SMBus + # https://datasheets.maximintegrated.com/en/ds/MAX98089.pdf AmpConfig = namedtuple('AmpConfig', ['name', 'value', 'register', 'offset', 'mask']) -EQParams = namedtuple('EQParams', ['K', 'k1', 'k2', 'c1', 'c2']) - -def configs_from_eq_params(base, eq_params): - return [ - AmpConfig("K (high)", (eq_params.K >> 8), base, 0, 0xFF), - AmpConfig("K (low)", (eq_params.K & 0xFF), base + 1, 0, 0xFF), - AmpConfig("k1 (high)", (eq_params.k1 >> 8), base + 2, 0, 0xFF), - AmpConfig("k1 (low)", (eq_params.k1 & 0xFF), base + 3, 0, 0xFF), - AmpConfig("k2 (high)", (eq_params.k2 >> 8), base + 4, 0, 0xFF), - AmpConfig("k2 (low)", (eq_params.k2 & 0xFF), base + 5, 0, 0xFF), - AmpConfig("c1 (high)", (eq_params.c1 >> 8), base + 6, 0, 0xFF), - AmpConfig("c1 (low)", (eq_params.c1 & 0xFF), base + 7, 0, 0xFF), - AmpConfig("c2 (high)", (eq_params.c2 >> 8), base + 8, 0, 0xFF), - AmpConfig("c2 (low)", (eq_params.c2 & 0xFF), base + 9, 0, 0xFF), - ] - -BASE_CONFIG = [ + +CONFIG = [ AmpConfig("MCLK prescaler", 0b01, 0x10, 4, 0b00110000), AmpConfig("PM: enable speakers", 0b11, 0x4D, 4, 0b00110000), AmpConfig("PM: enable DACs", 0b11, 0x4D, 0, 0b00000011), @@ -58,46 +44,30 @@ def configs_from_eq_params(base, eq_params): AmpConfig("Enhanced volume smoothing disabled", 0b0, 0x49, 7, 0b10000000), AmpConfig("Volume adjustment smoothing disabled", 0b0, 0x49, 6, 0b01000000), AmpConfig("Zero-crossing detection disabled", 0b0, 0x49, 5, 0b00100000), -] -CONFIGS = { - "tici": [ - AmpConfig("Right speaker output from right DAC", 0b1, 0x2C, 0, 0b11111111), - AmpConfig("Right Speaker Mixer Gain", 0b00, 0x2D, 2, 0b00001100), - AmpConfig("Right speaker output volume", 0x1c, 0x3E, 0, 0b00011111), - AmpConfig("DAI2 EQ enable", 0b1, 0x49, 1, 0b00000010), - - *configs_from_eq_params(0x84, EQParams(0x274F, 0xC0FF, 0x3BF9, 0x0B3C, 0x1656)), - *configs_from_eq_params(0x8E, EQParams(0x1009, 0xC6BF, 0x2952, 0x1C97, 0x30DF)), - *configs_from_eq_params(0x98, EQParams(0x0F75, 0xCBE5, 0x0ED2, 0x2528, 0x3E42)), - *configs_from_eq_params(0xA2, EQParams(0x091F, 0x3D4C, 0xCE11, 0x1266, 0x2807)), - *configs_from_eq_params(0xAC, EQParams(0x0A9E, 0x3F20, 0xE573, 0x0A8B, 0x3A3B)), - ], - "tizi": [ - AmpConfig("Left speaker output from left DAC", 0b1, 0x2B, 0, 0b11111111), - AmpConfig("Right speaker output from right DAC", 0b1, 0x2C, 0, 0b11111111), - AmpConfig("Left Speaker Mixer Gain", 0b00, 0x2D, 0, 0b00000011), - AmpConfig("Right Speaker Mixer Gain", 0b00, 0x2D, 2, 0b00001100), - AmpConfig("Left speaker output volume", 0x17, 0x3D, 0, 0b00011111), - AmpConfig("Right speaker output volume", 0x17, 0x3E, 0, 0b00011111), - - AmpConfig("DAI2 EQ enable", 0b0, 0x49, 1, 0b00000010), - AmpConfig("DAI2: DC blocking", 0b0, 0x20, 0, 0b00000001), - AmpConfig("ALC enable", 0b0, 0x43, 7, 0b10000000), - AmpConfig("DAI2 EQ attenuation", 0x2, 0x32, 0, 0b00001111), - AmpConfig("Excursion limiter upper corner freq", 0b001, 0x41, 4, 0b01110000), - AmpConfig("Excursion limiter threshold", 0b100, 0x42, 0, 0b00001111), - AmpConfig("Distortion limit (THDCLP)", 0x0, 0x46, 4, 0b11110000), - AmpConfig("Distortion limiter release time constant", 0b1, 0x46, 0, 0b00000001), - AmpConfig("Left DAC input mixer: DAI1 left", 0b0, 0x22, 7, 0b10000000), - AmpConfig("Left DAC input mixer: DAI1 right", 0b0, 0x22, 6, 0b01000000), - AmpConfig("Left DAC input mixer: DAI2 left", 0b1, 0x22, 5, 0b00100000), - AmpConfig("Left DAC input mixer: DAI2 right", 0b0, 0x22, 4, 0b00010000), - AmpConfig("Right DAC input mixer: DAI2 left", 0b0, 0x22, 1, 0b00000010), - AmpConfig("Right DAC input mixer: DAI2 right", 0b1, 0x22, 0, 0b00000001), - AmpConfig("Volume adjustment smoothing disabled", 0b1, 0x49, 6, 0b01000000), - ], -} + AmpConfig("Left speaker output from left DAC", 0b1, 0x2B, 0, 0b11111111), + AmpConfig("Right speaker output from right DAC", 0b1, 0x2C, 0, 0b11111111), + AmpConfig("Left Speaker Mixer Gain", 0b00, 0x2D, 0, 0b00000011), + AmpConfig("Right Speaker Mixer Gain", 0b00, 0x2D, 2, 0b00001100), + AmpConfig("Left speaker output volume", 0x17, 0x3D, 0, 0b00011111), + AmpConfig("Right speaker output volume", 0x17, 0x3E, 0, 0b00011111), + + AmpConfig("DAI2 EQ enable", 0b0, 0x49, 1, 0b00000010), + AmpConfig("DAI2: DC blocking", 0b0, 0x20, 0, 0b00000001), + AmpConfig("ALC enable", 0b0, 0x43, 7, 0b10000000), + AmpConfig("DAI2 EQ attenuation", 0x2, 0x32, 0, 0b00001111), + AmpConfig("Excursion limiter upper corner freq", 0b001, 0x41, 4, 0b01110000), + AmpConfig("Excursion limiter threshold", 0b100, 0x42, 0, 0b00001111), + AmpConfig("Distortion limit (THDCLP)", 0x0, 0x46, 4, 0b11110000), + AmpConfig("Distortion limiter release time constant", 0b1, 0x46, 0, 0b00000001), + AmpConfig("Left DAC input mixer: DAI1 left", 0b0, 0x22, 7, 0b10000000), + AmpConfig("Left DAC input mixer: DAI1 right", 0b0, 0x22, 6, 0b01000000), + AmpConfig("Left DAC input mixer: DAI2 left", 0b1, 0x22, 5, 0b00100000), + AmpConfig("Left DAC input mixer: DAI2 right", 0b0, 0x22, 4, 0b00010000), + AmpConfig("Right DAC input mixer: DAI2 left", 0b0, 0x22, 1, 0b00000010), + AmpConfig("Right DAC input mixer: DAI2 right", 0b1, 0x22, 0, 0b00000001), + AmpConfig("Volume adjustment smoothing disabled", 0b1, 0x49, 6, 0b01000000), +] class Amplifier: AMP_I2C_BUS = 0 @@ -125,32 +95,29 @@ def _set_configs(self, configs: list[AmpConfig]) -> None: def set_configs(self, configs: list[AmpConfig]) -> bool: # retry in case panda is using the amp tries = 15 - for i in range(15): + backoff = 0. + for i in range(tries): try: self._set_configs(configs) return True except OSError: + backoff += 0.1 + time.sleep(backoff) print(f"Failed to set amp config, {tries - i - 1} retries left") - time.sleep(0.02) return False def set_global_shutdown(self, amp_disabled: bool) -> bool: return self.set_configs([self._get_shutdown_config(amp_disabled), ]) - def initialize_configuration(self, model: str) -> bool: + def initialize_configuration(self) -> bool: cfgs = [ self._get_shutdown_config(True), - *BASE_CONFIG, - *CONFIGS[model], + *CONFIG, self._get_shutdown_config(False), ] return self.set_configs(cfgs) if __name__ == "__main__": - with open("/sys/firmware/devicetree/base/model") as f: - model = f.read().strip('\x00') - model = model.split('comma ')[-1] - amp = Amplifier() - amp.initialize_configuration(model) + amp.initialize_configuration() diff --git a/system/hardware/tici/esim.nmconnection b/system/hardware/tici/esim.nmconnection deleted file mode 100644 index 74f6f8e82c74dd..00000000000000 --- a/system/hardware/tici/esim.nmconnection +++ /dev/null @@ -1,30 +0,0 @@ -[connection] -id=esim -uuid=fff6553c-3284-4707-a6b1-acc021caaafb -type=gsm -permissions= -autoconnect=true -autoconnect-retries=100 -autoconnect-priority=2 -metered=1 - -[gsm] -apn= -home-only=false -auto-config=true -sim-id= - -[ipv4] -route-metric=1000 -dns-priority=1000 -dns-search= -method=auto - -[ipv6] -ddr-gen-mode=stable-privacy -dns-search= -route-metric=1000 -dns-priority=1000 -method=auto - -[proxy] diff --git a/system/hardware/tici/esim.py b/system/hardware/tici/esim.py deleted file mode 100755 index df76c1a5fdccfb..00000000000000 --- a/system/hardware/tici/esim.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python3 -import os -import math -import time -import binascii -import requests -import serial -import subprocess - - -def post(url, payload): - print() - print("POST to", url) - r = requests.post( - url, - data=payload, - verify=False, - headers={ - "Content-Type": "application/json", - "X-Admin-Protocol": "gsma/rsp/v2.2.0", - "charset": "utf-8", - "User-Agent": "gsma-rsp-lpad", - }, - ) - print("resp", r) - print("resp text", repr(r.text)) - print() - r.raise_for_status() - - ret = f"HTTP/1.1 {r.status_code}" - ret += ''.join(f"{k}: {v}" for k, v in r.headers.items() if k != 'Connection') - return ret.encode() + r.content - - -class LPA: - def __init__(self): - self.dev = serial.Serial('/dev/ttyUSB2', baudrate=57600, timeout=1, bytesize=8) - self.dev.reset_input_buffer() - self.dev.reset_output_buffer() - assert "OK" in self.at("AT") - - def at(self, cmd): - print(f"==> {cmd}") - self.dev.write(cmd.encode() + b'\r\n') - - r = b"" - cnt = 0 - while b"OK" not in r and b"ERROR" not in r and cnt < 20: - r += self.dev.read(8192).strip() - cnt += 1 - r = r.decode() - print(f"<== {repr(r)}") - return r - - def download_ota(self, qr): - return self.at(f'AT+QESIM="ota","{qr}"') - - def download(self, qr): - smdp = qr.split('$')[1] - out = self.at(f'AT+QESIM="download","{qr}"') - for _ in range(5): - line = out.split("+QESIM: ")[1].split("\r\n\r\nOK")[0] - - parts = [x.strip().strip('"') for x in line.split(',', maxsplit=4)] - print(repr(parts)) - trans, ret, url, payloadlen, payload = parts - assert trans == "trans" and ret == "0" - assert len(payload) == int(payloadlen) - - r = post(f"https://{smdp}/{url}", payload) - to_send = binascii.hexlify(r).decode() - - chunk_len = 1400 - for i in range(math.ceil(len(to_send) / chunk_len)): - state = 1 if (i+1)*chunk_len < len(to_send) else 0 - data = to_send[i * chunk_len : (i+1)*chunk_len] - out = self.at(f'AT+QESIM="trans",{len(to_send)},{state},{i},{len(data)},"{data}"') - assert "OK" in out - - if '+QESIM:"download",1' in out: - raise Exception("profile install failed") - elif '+QESIM:"download",0' in out: - print("done, successfully loaded") - break - - def enable(self, iccid): - self.at(f'AT+QESIM="enable","{iccid}"') - - def disable(self, iccid): - self.at(f'AT+QESIM="disable","{iccid}"') - - def delete(self, iccid): - self.at(f'AT+QESIM="delete","{iccid}"') - - def list_profiles(self): - out = self.at('AT+QESIM="list"') - return out.strip().splitlines()[1:] - - -if __name__ == "__main__": - import sys - - if "RESTART" in os.environ: - subprocess.check_call("sudo systemctl stop ModemManager", shell=True) - subprocess.check_call("/usr/comma/lte/lte.sh stop_blocking", shell=True) - subprocess.check_call("/usr/comma/lte/lte.sh start", shell=True) - while not os.path.exists('/dev/ttyUSB2'): - time.sleep(1) - time.sleep(3) - - lpa = LPA() - print(lpa.list_profiles()) - if len(sys.argv) > 1: - lpa.download(sys.argv[1]) - print(lpa.list_profiles()) diff --git a/system/hardware/tici/gsma_ci_bundle.pem b/system/hardware/tici/gsma_ci_bundle.pem new file mode 100644 index 00000000000000..3ee7fd12521b12 --- /dev/null +++ b/system/hardware/tici/gsma_ci_bundle.pem @@ -0,0 +1,133 @@ +# GSMA Certificate Issuer (CI) bundle for eSIM RSP +# Source: https://euicc-manual.osmocom.org/docs/pki/ci/bundle.pem + +issuer= + countryName = CH + organizationName = OISTE Foundation + commonName = OISTE GSMA CI G1 +notBefore=2024-01-16 23:17:39Z +notAfter=2059-01-07 23:17:38Z +-----BEGIN CERTIFICATE----- +MIIB9zCCAZ2gAwIBAgIUSpBSCCDYPOEG/IFHUCKpZ2pIAQMwCgYIKoZIzj0EAwIw +QzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5kYXRpb24xGTAXBgNV +BAMMEE9JU1RFIEdTTUEgQ0kgRzEwIBcNMjQwMTE2MjMxNzM5WhgPMjA1OTAxMDcy +MzE3MzhaMEMxCzAJBgNVBAYTAkNIMRkwFwYDVQQKDBBPSVNURSBGb3VuZGF0aW9u +MRkwFwYDVQQDDBBPSVNURSBHU01BIENJIEcxMFkwEwYHKoZIzj0CAQYIKoZIzj0D +AQcDQgAEvZ3s3PFC4NgrCcCMmHJ6DJ66uzAHuLcvjJnOn+TtBNThS7YHLDyHCa2v +7D+zTP+XTtgqgcLoB56Gha9EQQQ4xKNtMGswDwYDVR0TAQH/BAUwAwEB/zAQBgNV +HREECTAHiAVghXQFDjAXBgNVHSABAf8EDTALMAkGB2eBEgECAQAwHQYDVR0OBBYE +FEwnlnrSDBSzkelgHkHmBK1XwCIvMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQD +AgNIADBFAiBVcywTj017jKpAQ+gwy4MqK2hQvzve6lkvQkgSP6ykHwIhAI0KFwCD +jnPbmcJsG41hUrWNlf+IcrMvFuYii0DasBNi +-----END CERTIFICATE----- +issuer= + organizationName = GSM Association + commonName = GSM Association - RSP2 Root CI1 +notBefore=2017-02-22 00:00:00Z +notAfter=2052-02-21 23:59:59Z +-----BEGIN CERTIFICATE----- +MIICSTCCAe+gAwIBAgIQbmhWeneg7nyF7hg5Y9+qejAKBggqhkjOPQQDAjBEMRgw +FgYDVQQKEw9HU00gQXNzb2NpYXRpb24xKDAmBgNVBAMTH0dTTSBBc3NvY2lhdGlv +biAtIFJTUDIgUm9vdCBDSTEwIBcNMTcwMjIyMDAwMDAwWhgPMjA1MjAyMjEyMzU5 +NTlaMEQxGDAWBgNVBAoTD0dTTSBBc3NvY2lhdGlvbjEoMCYGA1UEAxMfR1NNIEFz +c29jaWF0aW9uIC0gUlNQMiBSb290IENJMTBZMBMGByqGSM49AgEGCCqGSM49AwEH +A0IABJ1qutL0HCMX52GJ6/jeibsAqZfULWj/X10p/Min6seZN+hf5llovbCNuB2n +unLz+O8UD0SUCBUVo8e6n9X1TuajgcAwgb0wDgYDVR0PAQH/BAQDAgEGMA8GA1Ud +EwEB/wQFMAMBAf8wEwYDVR0RBAwwCogIKwYBBAGC6WAwFwYDVR0gAQH/BA0wCzAJ +BgdngRIBAgEAME0GA1UdHwRGMEQwQqBAoD6GPGh0dHA6Ly9nc21hLWNybC5zeW1h +dXRoLmNvbS9vZmZsaW5lY2EvZ3NtYS1yc3AyLXJvb3QtY2kxLmNybDAdBgNVHQ4E +FgQUgTcPUSXQsdQI1MOyMubSXnlb6/swCgYIKoZIzj0EAwIDSAAwRQIgIJdYsOMF +WziPK7l8nh5mu0qiRiVf25oa9ullG/OIASwCIQDqCmDrYf+GziHXBOiwJwnBaeBO +aFsiLzIEOaUuZwdNUw== +-----END CERTIFICATE----- +issuer= + countryName = US + organizationName = Entrust, Inc. + organizationalUnitName = See www.entrust.net/legal-terms + organizationalUnitName = (c) 2016 Entrust, Inc. - for authorized use only + commonName = Entrust eSIM Certification Authority +notBefore=2016-11-16 16:04:02Z +notAfter=2051-10-16 16:34:02Z +-----BEGIN CERTIFICATE----- +MIIC6DCCAo2gAwIBAgIR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ES + organizationalUnitName = TELECOM + commonName = MC4 OT ROOT CI v1 +notBefore=2016-11-15 00:00:01Z +notAfter=2046-11-08 23:59:59Z +-----BEGIN CERTIFICATE----- +MIICOjCCAeGgAwIBAgIBATAKBggqhkjOPQQDAjBbMQswCQYDVQQGEwJGUjEeMBwG +A1UEChMVT0JFUlRIVVIgVEVDSE5PTE9HSUVTMRAwDgYDVQQLEwdURUxFQ09NMRow +GAYDVQQDExFNQzQgT1QgUk9PVCBDSSB2MTAeFw0xNjExMTUwMDAwMDFaFw00NjEx +MDgyMzU5NTlaMFsxCzAJBgNVBAYTAkZSMR4wHAYDVQQKExVPQkVSVEhVUiBURUNI +Tk9MT0dJRVMxEDAOBgNVBAsTB1RFTEVDT00xGjAYBgNVBAMTEU1DNCBPVCBST09U +IENJIHYxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHb/Gajt3OZxuaDSklBQE +D4lOd6PGPLSvtfkM952ubdyy45tJwAeA0eEii0CLrFT6tcfXkW+H/5mQyMRXaAUk +T6OBlTCBkjAfBgNVHSMEGDAWgBTNbmC3LXoGPLyEYluR6A/jBAbhPjAdBgNVHQ4E +FgQUzW5gty16Bjy8hGJbkegP4wQG4T4wDgYDVR0PAQH/BAQDAgAGMBcGA1UdIAEB +/wQNMAswCQYHZ4ESAQIBADAWBgNVHREEDzANiAsrBgEEAYHvb7OITTAPBgNVHRMB +Af8EBTADAQH/MAoGCCqGSM49BAMCA0cAMEQCIEw4Nc7f2fDtoH+6ON/bknfDQxmT +ikThXjhpLtSrSKN2AiAxHxgC87L0FDnH8dJNlkdGX9c0JIx6oLheIplfS6k+jg== +-----END CERTIFICATE----- +issuer= + commonName = SubMan V4.2 CI Google Pixel + organizationName = Giesecke and Devrient GmbH + organizationalUnitName = Mobile Security + countryName = DE +notBefore=2017-05-10 00:00:00Z +notAfter=2027-05-10 00:00:00Z +-----BEGIN CERTIFICATE----- +MIICaTCCAg6gAwIBAgICASwwCgYIKoZIzj0EAwIwczElMCMGA1UEAxMcIFN1Yk1h +biBWNC4yIENJIEdvb2dsZSBQaXhlbDEjMCEGA1UEChMaR2llc2Vja2UgYW5kIERl +dnJpZW50IEdtYkgxGDAWBgNVBAsTD01vYmlsZSBTZWN1cml0eTELMAkGA1UEBhMC +REUwHhcNMTcwNTEwMDAwMDAwWhcNMjcwNTEwMDAwMDAwWjBzMSUwIwYDVQQDExwg +U3ViTWFuIFY0LjIgQ0kgR29vZ2xlIFBpeGVsMSMwIQYDVQQKExpHaWVzZWNrZSBh +bmQgRGV2cmllbnQgR21iSDEYMBYGA1UECxMPTW9iaWxlIFNlY3VyaXR5MQswCQYD +VQQGEwJERTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHNorfaJsGzqWNawyAhl +IAv9QL2/+b9RsUoso06t/dKX1MRr5CUJ51acvv5TAFhQKIml+dwLbFnV5aO+8W6Z +wxajgZEwgY4wHwYDVR0jBBgwFoAUtg8LiX/WMLiM/tYWH46oCMU4KsMwHQYDVR0O +BBYEFLYPC4l/1jC4jP7WFh+OqAjFOCrDMA4GA1UdDwEB/wQEAwIBBjAXBgNVHSAB +Af8EDTALMAkGB2eBEgECAQAwDwYDVR0TAQH/BAUwAwEB/zASBgNVHREECzAJiAcr +BgEEAdwPMAoGCCqGSM49BAMCA0kAMEYCIQDpoZcuAQrjATW8U+AWqMUJ0dY6nWW1 +R1QmFzVZ1yMXSwIhALCvRqkCtgiavdeFeSgsSNbY5Fhd+QoCltuSh1U4TE7A +-----END CERTIFICATE----- +issuer= + countryName = DE + commonName = SubMan V4.2 CI + organizationName = Giesecke and Devrient + organizationalUnitName = Mobile Security +notBefore=2016-08-12 13:51:48Z +notAfter=2026-08-12 13:51:48Z +-----BEGIN CERTIFICATE----- +MIICUjCCAfigAwIBAgIDQgAAMAoGCCqGSM49BAMCMGAxCzAJBgNVBAYTAkRFMRcw +FQYDVQQDEw5TdWJNYW4gVjQuMiBDSTEeMBwGA1UEChMVR2llc2Vja2UgYW5kIERl +dnJpZW50MRgwFgYDVQQLEw9Nb2JpbGUgU2VjdXJpdHkwHhcNMTYwODEyMTM1MTQ4 +WhcNMjYwODEyMTM1MTQ4WjBgMQswCQYDVQQGEwJERTEXMBUGA1UEAxMOU3ViTWFu +IFY0LjIgQ0kxHjAcBgNVBAoTFUdpZXNlY2tlIGFuZCBEZXZyaWVudDEYMBYGA1UE +CxMPTW9iaWxlIFNlY3VyaXR5MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYIgl +VQr9wbXOlwPp8qMg5Df08Cli9Mc+lpr3Lwa9PlVA3QWlLeX4GfD4H3phLBqVIa17 +yHttmtheTxi0KoEqhKOBoDCBnTAdBgNVHQ4EFgQU6lOt7zMpuVCa/XVf1Ei4LcG8 +7P8wDgYDVR0PAQH/BAQDAgEGMBcGA1UdIAEB/wQNMAswCQYHZ4ESAQIBADAPBgNV +HRMBAf8EBTADAQH/MBIGA1UdEQQLMAmIBysGAQQB3A8wLgYDVR0fBCcwJTAjoCGg +H4YdaHR0cDovL2dpLWRlLmNvbS90ZXN0LmNybC5wZW0wCgYIKoZIzj0EAwIDSAAw +RQIhAMMx2L/VHDiOW+Fl/OuFmhCdizYM17Yn9zAVieKO2T0iAiANWtCMmY+DzkqK +yHxBFX0U2tBd682zP4DpgRt8j3Ylew== +-----END CERTIFICATE----- diff --git a/system/hardware/tici/hardware.h b/system/hardware/tici/hardware.h index f1d1f1e717ed88..a06ce43b35626d 100644 --- a/system/hardware/tici/hardware.h +++ b/system/hardware/tici/hardware.h @@ -1,31 +1,34 @@ #pragma once #include +#include #include #include #include +#include // for std::clamp -#include "common/params.h" #include "common/util.h" #include "system/hardware/base.h" class HardwareTici : public HardwareNone { public: - static constexpr float MAX_VOLUME = 0.9; - static constexpr float MIN_VOLUME = 0.1; - static bool TICI() { return true; } - static bool AGNOS() { return true; } - static std::string get_os_version() { - return "AGNOS " + util::read_file("/VERSION"); - } - static std::string get_name() { - std::string model = util::read_file("/sys/firmware/devicetree/base/model"); - return model.substr(std::string("comma ").size()); + static const std::string name = []() { + std::string model = util::read_file("/sys/firmware/devicetree/base/model"); + return util::strip(model.substr(std::string("comma ").size())); + }(); + return name; } static cereal::InitData::DeviceType get_device_type() { - return (get_name() == "tizi") ? cereal::InitData::DeviceType::TIZI : (get_name() == "mici" ? cereal::InitData::DeviceType::MICI : cereal::InitData::DeviceType::TICI); + static const std::map device_map = { + {"tici", cereal::InitData::DeviceType::TICI}, + {"tizi", cereal::InitData::DeviceType::TIZI}, + {"mici", cereal::InitData::DeviceType::MICI} + }; + static const auto it = device_map.find(get_name()); + assert(it != device_map.end()); + return it->second; } static int get_voltage() { return std::atoi(util::read_file("/sys/class/hwmon/hwmon1/in1_input").c_str()); } @@ -49,23 +52,17 @@ class HardwareTici : public HardwareNone { return serial; } - static void reboot() { std::system("sudo reboot"); } - static void poweroff() { std::system("sudo poweroff"); } - static void set_brightness(int percent) { - std::string max = util::read_file("/sys/class/backlight/panel0-backlight/max_brightness"); - - std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness"); - if (brightness_control.is_open()) { - brightness_control << (int)(percent * (std::stof(max)/100.)) << "\n"; - brightness_control.close(); - } - } - static void set_display_power(bool on) { - std::ofstream bl_power_control("/sys/class/backlight/panel0-backlight/bl_power"); - if (bl_power_control.is_open()) { - bl_power_control << (on ? "0" : "4") << "\n"; - bl_power_control.close(); + static void set_ir_power(int percent) { + auto device = get_device_type(); + if (device == cereal::InitData::DeviceType::TICI || + device == cereal::InitData::DeviceType::TIZI) { + return; } + + int value = util::map_val(std::clamp(percent, 0, 100), 0, 100, 0, 300); + std::ofstream("/sys/class/leds/led:switch_2/brightness") << 0 << "\n"; + std::ofstream("/sys/class/leds/led:torch_2/brightness") << value << "\n"; + std::ofstream("/sys/class/leds/led:switch_2/brightness") << value << "\n"; } static std::map get_init_logs() { @@ -93,14 +90,4 @@ class HardwareTici : public HardwareNone { return ret; } - - static bool get_ssh_enabled() { return Params().getBool("SshEnabled"); } - static void set_ssh_enabled(bool enabled) { Params().putBool("SshEnabled", enabled); } - - static void config_cpu_rendering(bool offscreen) { - if (offscreen) { - setenv("QT_QPA_PLATFORM", "eglfs", 1); // offscreen doesn't work with EGL/GLES - } - setenv("LP_NUM_THREADS", "0", 1); // disable threading so we stay on our assigned CPU - } }; diff --git a/system/hardware/tici/hardware.py b/system/hardware/tici/hardware.py index eb524dbafaa5e8..e4c8cf0b5cc034 100644 --- a/system/hardware/tici/hardware.py +++ b/system/hardware/tici/hardware.py @@ -1,17 +1,17 @@ import json -import math import os import subprocess import time -import tempfile from enum import IntEnum from functools import cached_property, lru_cache from pathlib import Path from cereal import log +from openpilot.common.utils import sudo_read, sudo_write from openpilot.common.gpio import gpio_set, gpio_init, get_irqs_for_action -from openpilot.system.hardware.base import HardwareBase, ThermalConfig +from openpilot.system.hardware.base import HardwareBase, LPABase, ThermalConfig, ThermalZone from openpilot.system.hardware.tici import iwlist +from openpilot.system.hardware.tici.lpa import TiciLPA from openpilot.system.hardware.tici.pins import GPIO from openpilot.system.hardware.tici.amplifier import Amplifier @@ -19,30 +19,9 @@ NM_CON_ACT = NM + '.Connection.Active' NM_DEV = NM + '.Device' NM_DEV_WL = NM + '.Device.Wireless' -NM_DEV_STATS = NM + '.Device.Statistics' NM_AP = NM + '.AccessPoint' DBUS_PROPS = 'org.freedesktop.DBus.Properties' -MM = 'org.freedesktop.ModemManager1' -MM_MODEM = MM + ".Modem" -MM_MODEM_SIMPLE = MM + ".Modem.Simple" -MM_SIM = MM + ".Sim" - -class MM_MODEM_STATE(IntEnum): - FAILED = -1 - UNKNOWN = 0 - INITIALIZING = 1 - LOCKED = 2 - DISABLED = 3 - DISABLING = 4 - ENABLING = 5 - ENABLED = 6 - SEARCHING = 7 - REGISTERED = 8 - DISCONNECTING = 9 - CONNECTING = 10 - CONNECTED = 11 - class NMMetered(IntEnum): NM_METERED_UNKNOWN = 0 NM_METERED_YES = 1 @@ -50,35 +29,12 @@ class NMMetered(IntEnum): NM_METERED_GUESS_YES = 3 NM_METERED_GUESS_NO = 4 +MODEM_STATE_PATH = "/dev/shm/modem" TIMEOUT = 0.1 -REFRESH_RATE_MS = 1000 NetworkType = log.DeviceState.NetworkType NetworkStrength = log.DeviceState.NetworkStrength -# https://developer.gnome.org/ModemManager/unstable/ModemManager-Flags-and-Enumerations.html#MMModemAccessTechnology -MM_MODEM_ACCESS_TECHNOLOGY_UMTS = 1 << 5 -MM_MODEM_ACCESS_TECHNOLOGY_LTE = 1 << 14 - - -def sudo_write(val, path): - try: - with open(path, 'w') as f: - f.write(str(val)) - except PermissionError: - os.system(f"sudo chmod a+w {path}") - try: - with open(path, 'w') as f: - f.write(str(val)) - except PermissionError: - # fallback for debugfs files - os.system(f"sudo su -c 'echo {val} > {path}'") - -def sudo_read(path: str) -> str: - try: - return subprocess.check_output(f"sudo cat {path}", shell=True, encoding='utf8') - except Exception: - return "" def affine_irq(val, action): irqs = get_irqs_for_action(action) @@ -106,16 +62,19 @@ def bus(self): def nm(self): return self.bus.get_object(NM, '/org/freedesktop/NetworkManager') - @property # this should not be cached, in case the modemmanager restarts - def mm(self): - return self.bus.get_object(MM, '/org/freedesktop/ModemManager1') - @cached_property def amplifier(self): if self.get_device_type() == "mici": return None return Amplifier() + def get_modem_state(self) -> dict: + try: + with open(MODEM_STATE_PATH) as f: + return json.load(f) + except (FileNotFoundError, json.JSONDecodeError): + return {} + def get_os_version(self): with open("/VERSION") as f: return f.read().strip() @@ -123,12 +82,6 @@ def get_os_version(self): def get_device_type(self): return get_device_type() - def get_sound_card_online(self): - if os.path.isfile('/proc/asound/card0/state'): - with open('/proc/asound/card0/state') as f: - return f.read().strip() == 'ONLINE' - return False - def reboot(self, reason=None): subprocess.check_output(["sudo", "reboot"]) @@ -140,105 +93,87 @@ def uninstall(self): def get_serial(self): return self.get_cmdline()['androidboot.serialno'] + def get_voltage(self): + with open("/sys/class/hwmon/hwmon1/in1_input") as f: + return int(f.read()) + + def get_current(self): + with open("/sys/class/hwmon/hwmon1/curr1_input") as f: + return int(f.read()) + + def set_ir_power(self, percent: int): + if self.get_device_type() == "tizi": + return + + value = int((percent / 100) * 300) + with open("/sys/class/leds/led:switch_2/brightness", "w") as f: + f.write("0\n") + with open("/sys/class/leds/led:torch_2/brightness", "w") as f: + f.write(f"{value}\n") + with open("/sys/class/leds/led:switch_2/brightness", "w") as f: + f.write(f"{value}\n") + def get_network_type(self): try: primary_connection = self.nm.Get(NM, 'PrimaryConnection', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) primary_connection = self.bus.get_object(NM, primary_connection) primary_type = primary_connection.Get(NM_CON_ACT, 'Type', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - if primary_type == '802-3-ethernet': return NetworkType.ethernet elif primary_type == '802-11-wireless': return NetworkType.wifi - else: - active_connections = self.nm.Get(NM, 'ActiveConnections', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - for conn in active_connections: - c = self.bus.get_object(NM, conn) - tp = c.Get(NM_CON_ACT, 'Type', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - if tp == 'gsm': - modem = self.get_modem() - access_t = modem.Get(MM_MODEM, 'AccessTechnologies', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - if access_t >= MM_MODEM_ACCESS_TECHNOLOGY_LTE: - return NetworkType.cell4G - elif access_t >= MM_MODEM_ACCESS_TECHNOLOGY_UMTS: - return NetworkType.cell3G - else: - return NetworkType.cell2G except Exception: pass + ms = self.get_modem_state() + if ms.get('connected'): + nt = ms.get('network_type', '') + if nt == 'nr': + return NetworkType.cell5G + elif nt == 'lte': + return NetworkType.cell4G + elif nt in ('utran', 'umts'): + return NetworkType.cell3G + elif nt == 'gsm': + return NetworkType.cell2G return NetworkType.none - def get_modem(self): - objects = self.mm.GetManagedObjects(dbus_interface="org.freedesktop.DBus.ObjectManager", timeout=TIMEOUT) - modem_path = list(objects.keys())[0] - return self.bus.get_object(MM, modem_path) - def get_wlan(self): wlan_path = self.nm.GetDeviceByIpIface('wlan0', dbus_interface=NM, timeout=TIMEOUT) return self.bus.get_object(NM, wlan_path) - def get_wwan(self): - wwan_path = self.nm.GetDeviceByIpIface('wwan0', dbus_interface=NM, timeout=TIMEOUT) - return self.bus.get_object(NM, wwan_path) - def get_sim_info(self): - modem = self.get_modem() - sim_path = modem.Get(MM_MODEM, 'Sim', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - - if sim_path == "/": - return { - 'sim_id': '', - 'mcc_mnc': None, - 'network_type': ["Unknown"], - 'sim_state': ["ABSENT"], - 'data_connected': False - } - else: - sim = self.bus.get_object(MM, sim_path) - return { - 'sim_id': str(sim.Get(MM_SIM, 'SimIdentifier', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)), - 'mcc_mnc': str(sim.Get(MM_SIM, 'OperatorIdentifier', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)), - 'network_type': ["Unknown"], - 'sim_state': ["READY"], - 'data_connected': modem.Get(MM_MODEM, 'State', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) == MM_MODEM_STATE.CONNECTED, - } + ms = self.get_modem_state() + sim_id = ms.get('iccid', '') + return { + 'sim_id': sim_id, + 'mcc_mnc': ms.get('mcc_mnc') or None, + 'network_type': ["Unknown"], + 'sim_state': ["ABSENT"] if not sim_id else ["READY"], + 'data_connected': ms.get('connected', False), + } + + def get_sim_lpa(self) -> LPABase: + return TiciLPA() def get_imei(self, slot): if slot != 0: return "" - - return str(self.get_modem().Get(MM_MODEM, 'EquipmentIdentifier', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)) + return self.get_modem_state().get('imei', '') def get_network_info(self): - try: - modem = self.get_modem() - info = modem.Command("AT+QNWINFO", math.ceil(TIMEOUT), dbus_interface=MM_MODEM, timeout=TIMEOUT) - extra = modem.Command('AT+QENG="servingcell"', math.ceil(TIMEOUT), dbus_interface=MM_MODEM, timeout=TIMEOUT) - state = modem.Get(MM_MODEM, 'State', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - except Exception: + if self.get_device_type() == "mici": return None - if info and info.startswith('+QNWINFO: '): - info = info.replace('+QNWINFO: ', '').replace('"', '').split(',') - extra = "" if extra is None else extra.replace('+QENG: "servingcell",', '').replace('"', '') - state = "" if state is None else MM_MODEM_STATE(state).name - - if len(info) != 4: - return None - - technology, operator, band, channel = info - - return({ - 'technology': technology, - 'operator': operator, - 'band': band, - 'channel': int(channel), - 'extra': extra, - 'state': state, - }) - else: - return None + ms = self.get_modem_state() + return { + 'technology': ms.get('network_type', '').upper() if ms.get('network_type') else '', + 'operator': ms.get('operator', ''), + 'band': ms.get('band', ''), + 'channel': ms.get('channel', 0), + 'extra': ms.get('extra', ''), + 'state': ms.get('state', 'UNKNOWN'), + } def parse_strength(self, percentage): if percentage < 25: @@ -264,15 +199,16 @@ def get_network_strength(self, network_type): strength = int(active_ap.Get(NM_AP, 'Strength', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)) network_strength = self.parse_strength(strength) else: # Cellular - modem = self.get_modem() - strength = int(modem.Get(MM_MODEM, 'SignalQuality', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)[0]) - network_strength = self.parse_strength(strength) + network_strength = self.parse_strength(self.get_modem_state().get('signal_quality', 0)) except Exception: pass return network_strength def get_network_metered(self, network_type) -> bool: + if network_type in (NetworkType.cell2G, NetworkType.cell3G, NetworkType.cell4G, NetworkType.cell5G): + from openpilot.common.params import Params + return Params().get_bool("GsmMetered") try: primary_connection = self.nm.Get(NM, 'PrimaryConnection', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) primary_connection = self.bus.get_object(NM, primary_connection) @@ -285,52 +221,16 @@ def get_network_metered(self, network_type) -> bool: if network_type == NetworkType.wifi: if metered_prop in [NMMetered.NM_METERED_YES, NMMetered.NM_METERED_GUESS_YES]: return True - elif network_type in [NetworkType.cell2G, NetworkType.cell3G, NetworkType.cell4G, NetworkType.cell5G]: - if metered_prop == NMMetered.NM_METERED_NO: - return False except Exception: pass return super().get_network_metered(network_type) def get_modem_version(self): - try: - modem = self.get_modem() - return modem.Get(MM_MODEM, 'Revision', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - except Exception: - return None - - def get_modem_nv(self): - timeout = 0.2 # Default timeout is too short - files = ( - '/nv/item_files/modem/mmode/ue_usage_setting', - '/nv/item_files/ims/IMS_enable', - '/nv/item_files/modem/mmode/sms_only', - ) - try: - modem = self.get_modem() - return { fn: str(modem.Command(f'AT+QNVFR="{fn}"', math.ceil(timeout), dbus_interface=MM_MODEM, timeout=timeout)) for fn in files} - except Exception: - return None + return self.get_modem_state().get('modem_version') or None def get_modem_temperatures(self): - timeout = 0.2 # Default timeout is too short - try: - modem = self.get_modem() - temps = modem.Command("AT+QTEMP", math.ceil(timeout), dbus_interface=MM_MODEM, timeout=timeout) - return list(map(int, temps.split(' ')[1].split(','))) - except Exception: - return [] - - def get_nvme_temperatures(self): - ret = [] - try: - out = subprocess.check_output("sudo smartctl -aj /dev/nvme0", shell=True) - dat = json.loads(out) - ret = list(map(int, dat["nvme_smart_health_information_log"]["temperature_sensors"])) - except Exception: - pass - return ret + return self.get_modem_state().get('temperatures', []) def get_current_power_draw(self): return (self.read_param_file("/sys/class/hwmon/hwmon1/power1_input", int) / 1e6) @@ -342,12 +242,29 @@ def shutdown(self): os.system("sudo poweroff") def get_thermal_config(self): - return ThermalConfig(cpu=(["cpu%d-silver-usr" % i for i in range(4)] + - ["cpu%d-gold-usr" % i for i in range(4)], 1000), - gpu=(("gpu0-usr", "gpu1-usr"), 1000), - mem=("ddr-usr", 1000), - bat=(None, 1), - pmic=(("pm8998_tz", "pm8005_tz"), 1000)) + intake, exhaust, gnss, bottomSoc = None, None, None, None + if self.get_device_type() == "mici": + gnss = ThermalZone("gnss") + intake = ThermalZone("intake") + exhaust = ThermalZone("exhaust") + bottomSoc = ThermalZone("bottom_soc") + return ThermalConfig(cpu=[ThermalZone(f"cpu{i}-silver-usr") for i in range(4)] + + [ThermalZone(f"cpu{i}-gold-usr") for i in range(4)], + gpu=[ThermalZone("gpu0-usr"), ThermalZone("gpu1-usr")], + dsp=ThermalZone("compute-hvx-usr"), + memory=ThermalZone("ddr-usr"), + pmic=[ThermalZone("pm8998_tz"), ThermalZone("pm8005_tz")], + intake=intake, + exhaust=exhaust, + gnss=gnss, + bottomSoc=bottomSoc) + + def set_display_power(self, on): + try: + with open("/sys/class/backlight/panel0-backlight/bl_power", "w") as f: + f.write("0" if on else "4") + except Exception: + pass def set_screen_brightness(self, percentage): try: @@ -375,11 +292,11 @@ def set_power_save(self, powersave_enabled): if self.amplifier is not None: self.amplifier.set_global_shutdown(amp_disabled=powersave_enabled) if not powersave_enabled: - self.amplifier.initialize_configuration(self.get_device_type()) + self.amplifier.initialize_configuration() # *** CPU config *** - # offline big cluster, leave core 4 online for pandad + # offline big cluster for i in range(4, 8): val = '0' if powersave_enabled else '1' sudo_write(val, f'/sys/devices/system/cpu/cpu{i}/online') @@ -392,13 +309,13 @@ def set_power_save(self, powersave_enabled): # *** IRQ config *** - # GPU - affine_irq(5, "kgsl-3d0") + # GPU, modeld core + affine_irq(7, "kgsl-3d0") # camerad core - camera_irqs = ("cci", "cpas_camnoc", "cpas-cdm", "csid", "ife", "csid-lite", "ife-lite") + camera_irqs = ("a5", "cci", "cpas_camnoc", "cpas-cdm", "csid", "ife", "csid-lite", "ife-lite") for n in camera_irqs: - affine_irq(5, n) + affine_irq(6, n) def get_gpu_usage_percent(self): try: @@ -410,7 +327,7 @@ def get_gpu_usage_percent(self): def initialize_hardware(self): if self.amplifier is not None: - self.amplifier.initialize_configuration(self.get_device_type()) + self.amplifier.initialize_configuration() # Allow hardwared to write engagement status to kmsg os.system("sudo chmod a+w /dev/kmsg") @@ -425,12 +342,13 @@ def initialize_hardware(self): sudo_write("f", "/proc/irq/default_smp_affinity") # move these off the default core - affine_irq(1, "msm_drm") # display affine_irq(1, "msm_vidc") # encoders affine_irq(1, "i2c_geni") # sensors # *** GPU config *** # https://github.com/commaai/agnos-kernel-sdm845/blob/master/arch/arm64/boot/dts/qcom/sdm845-gpu.dtsi#L216 + affine_irq(5, "fts_ts") # touch + affine_irq(5, "msm_drm") # display sudo_write("1", "/sys/class/kgsl/kgsl-3d0/min_pwrlevel") sudo_write("1", "/sys/class/kgsl/kgsl-3d0/max_pwrlevel") sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_bus_on") @@ -451,9 +369,6 @@ def initialize_hardware(self): # pandad core affine_irq(3, "spi_geni") # SPI - if "tici" in self.get_device_type(): - affine_irq(3, "xhci-hcd:usb3") # aux panda USB (or potentially anything else on USB) - affine_irq(3, "xhci-hcd:usb1") # internal panda USB (also modem) try: pid = subprocess.check_output(["pgrep", "-f", "spi0"], encoding='utf8').strip() subprocess.call(["sudo", "chrt", "-f", "-p", "1", pid]) @@ -461,60 +376,6 @@ def initialize_hardware(self): except subprocess.CalledProcessException as e: print(str(e)) - def configure_modem(self): - sim_id = self.get_sim_info().get('sim_id', '') - - modem = self.get_modem() - try: - manufacturer = str(modem.Get(MM_MODEM, 'Manufacturer', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)) - except Exception: - manufacturer = None - - cmds = [] - if manufacturer == 'Cavli Inc.': - cmds += [ - # use sim slot - 'AT^SIMSWAP=1', - - # ethernet config - 'AT$QCPCFG=usbNet,0', - 'AT$QCNETDEVCTL=3,1', - ] - else: - cmds += [ - # configure modem as data-centric - 'AT+QNVW=5280,0,"0102000000000000"', - 'AT+QNVFW="/nv/item_files/ims/IMS_enable",00', - 'AT+QNVFW="/nv/item_files/modem/mmode/ue_usage_setting",01', - ] - if self.get_device_type() == "tizi": - cmds += [ - # SIM hot swap - 'AT+QSIMDET=1,0', - 'AT+QSIMSTAT=1', - ] - - # clear out old blue prime initial APN - os.system('mmcli -m any --3gpp-set-initial-eps-bearer-settings="apn="') - for cmd in cmds: - try: - modem.Command(cmd, math.ceil(TIMEOUT), dbus_interface=MM_MODEM, timeout=TIMEOUT) - except Exception: - pass - - # eSIM prime - if sim_id.startswith('8985235'): - dest = "/etc/NetworkManager/system-connections/esim.nmconnection" - with open(Path(__file__).parent/'esim.nmconnection') as f, tempfile.NamedTemporaryFile(mode='w') as tf: - dat = f.read() - dat = dat.replace("sim-id=", f"sim-id={sim_id}") - tf.write(dat) - tf.flush() - - # needs to be root - os.system(f"sudo cp {tf.name} {dest}") - os.system(f"sudo nmcli con load {dest}") - def get_networks(self): r = {} @@ -543,20 +404,8 @@ def get_networks(self): return r def get_modem_data_usage(self): - try: - wwan = self.get_wwan() - - # Ensure refresh rate is set so values don't go stale - refresh_rate = wwan.Get(NM_DEV_STATS, 'RefreshRateMs', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - if refresh_rate != REFRESH_RATE_MS: - u = type(refresh_rate) - wwan.Set(NM_DEV_STATS, 'RefreshRateMs', u(REFRESH_RATE_MS), dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - - tx = wwan.Get(NM_DEV_STATS, 'TxBytes', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - rx = wwan.Get(NM_DEV_STATS, 'RxBytes', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - return int(tx), int(rx) - except Exception: - return -1, -1 + ms = self.get_modem_state() + return ms.get('tx_bytes', -1), ms.get('rx_bytes', -1) def has_internal_panda(self): return True @@ -567,7 +416,7 @@ def reset_internal_panda(self): gpio_set(GPIO.STM_RST_N, 1) gpio_set(GPIO.STM_BOOT0, 0) - time.sleep(1) + time.sleep(0.01) gpio_set(GPIO.STM_RST_N, 0) def recover_internal_panda(self): @@ -576,9 +425,9 @@ def recover_internal_panda(self): gpio_set(GPIO.STM_RST_N, 1) gpio_set(GPIO.STM_BOOT0, 1) - time.sleep(0.5) + time.sleep(0.01) gpio_set(GPIO.STM_RST_N, 0) - time.sleep(0.5) + time.sleep(0.01) gpio_set(GPIO.STM_BOOT0, 0) def booted(self): @@ -590,6 +439,6 @@ def booted(self): if __name__ == "__main__": t = Tici() - t.configure_modem() t.initialize_hardware() t.set_power_save(False) + print(t.get_sim_info()) diff --git a/system/hardware/tici/lpa.py b/system/hardware/tici/lpa.py new file mode 100644 index 00000000000000..618d11e5d15e0f --- /dev/null +++ b/system/hardware/tici/lpa.py @@ -0,0 +1,791 @@ +# SGP.22 v2.3: https://www.gsma.com/solutions-and-impact/technologies/esim/wp-content/uploads/2021/07/SGP.22-v2.3.pdf + +import atexit +import base64 +import fcntl +import hashlib +import os +import requests +import serial +import subprocess +import sys +import termios +import time + +from collections.abc import Callable, Generator +from contextlib import contextmanager +from typing import Any + +from pathlib import Path + +from openpilot.common.time_helpers import system_time_valid +from openpilot.system.hardware.base import LPABase, LPAError, LPAProfileNotFoundError, Profile + +GSMA_CI_BUNDLE = str(Path(__file__).parent / "gsma_ci_bundle.pem") + +DEFAULT_DEVICE = "/dev/modem_at0" +DEFAULT_BAUD = 9600 +DEFAULT_TIMEOUT = 5.0 +# https://euicc-manual.osmocom.org/docs/lpa/applet-id/ +ISDR_AID = "A0000005591010FFFFFFFF8900000100" +ES10X_MSS = 120 +HTTP_TIMEOUT = 30 +OPEN_ISDR_RETRIES = 10 +OPEN_ISDR_RETRY_DELAY_S = 0.25 +OPEN_ISDR_RESET_ATTEMPT = 5 +SEND_APDU_RETRIES = 3 +LOCK_FILE = '/dev/shm/modem.lock' +DEBUG = os.environ.get("DEBUG") == "1" + + +# TLV Tags +TAG_ICCID = 0x5A +TAG_STATUS = 0x80 +TAG_EUICC_INFO = 0xBF20 +TAG_PREPARE_DOWNLOAD = 0xBF21 +TAG_BPP_COMMAND = 0xBF23 +TAG_PROFILE_METADATA = 0xBF25 +TAG_INSTALL_RESULT_DATA = 0xBF27 +TAG_LIST_NOTIFICATION = 0xBF28 +TAG_SET_NICKNAME = 0xBF29 +TAG_RETRIEVE_NOTIFICATION = 0xBF2B +TAG_PROFILE_INFO_LIST = 0xBF2D +TAG_EUICC_CHALLENGE = 0xBF2E +TAG_NOTIFICATION_METADATA = 0xBF2F +TAG_NOTIFICATION_SENT = 0xBF30 +TAG_ENABLE_PROFILE = 0xBF31 +TAG_DELETE_PROFILE = 0xBF33 +TAG_BPP = 0xBF36 +TAG_PROFILE_INSTALL_RESULT = 0xBF37 +TAG_AUTH_SERVER = 0xBF38 +TAG_CANCEL_SESSION = 0xBF41 +TAG_OK = 0xA0 + +PROFILE_OK = 0x00 +PROFILE_NOT_IN_DISABLED_STATE = 0x02 +PROFILE_CAT_BUSY = 0x05 + +PROFILE_ERROR_CODES = { + 0x01: "iccidOrAidNotFound", PROFILE_NOT_IN_DISABLED_STATE: "profileNotInDisabledState", + 0x03: "disallowedByPolicy", 0x04: "wrongProfileReenabling", + PROFILE_CAT_BUSY: "catBusy", 0x06: "undefinedError", +} +AUTH_SERVER_ERROR_CODES = { + 0x01: "eUICCVerificationFailed", 0x02: "eUICCCertificateExpired", + 0x03: "eUICCCertificateRevoked", 0x05: "invalidServerSignature", + 0x06: "euiccCiPKUnknown", 0x0A: "matchingIdRefused", + 0x10: "insufficientMemory", +} +BPP_COMMAND_NAMES = { + 0: "initialiseSecureChannel", 1: "configureISDP", 2: "storeMetadata", + 3: "storeMetadata2", 4: "replaceSessionKeys", 5: "loadProfileElements", +} +BPP_ERROR_REASONS = { + 1: "incorrectInputValues", 2: "invalidSignature", 3: "invalidTransactionId", + 4: "unsupportedCrtValues", 5: "unsupportedRemoteOperationType", + 6: "unsupportedProfileClass", 7: "scp03tStructureError", 8: "scp03tSecurityError", + 9: "iccidAlreadyExistsOnEuicc", 10: "insufficientMemoryForProfile", + 11: "installInterrupted", 12: "peProcessingError", 13: "dataMismatch", + 14: "invalidNAA", +} +BPP_ERROR_MESSAGES = { + 9: "This eSIM profile is already installed on this device.", + 10: "Not enough memory on the eUICC to install this profile.", + 12: "Profile installation failed. The QR code may have already been used.", +} + +# SGP.22 §5.2.6 SM-DP+ reason/subject codes mapped to user-friendly messages +ES9P_ERROR_MESSAGES: dict[tuple[str, str], str] = { + ('3.8', '8.2.6'): "This eSIM profile is already installed on another device. Please use a new QR code.", + ('3.8', '8.2.1'): "This eSIM profile has expired. Please request a new QR code.", + ('3.8', '8.1'): "The SM-DP+ server refused this request.", + ('3.1', '8.2.6'): "This eSIM profile has been revoked by the carrier.", + ('3.9', '8.2.6'): "This eSIM profile download has already been completed.", + ('2.1', '8.8'): "The device is not compatible with this eSIM profile.", + ('1.2', '8.1'): "The SM-DP+ server is temporarily unavailable. Try again later.", +} + +NOTIFICATION_OPERATIONS = {0x80: "install", 0x40: "enable", 0x20: "disable", 0x10: "delete"} + +STATE_LABELS = {0: "disabled", 1: "enabled", 255: "unknown"} +ICON_LABELS = {0: "jpeg", 1: "png", 255: "unknown"} +CLASS_LABELS = {0: "test", 1: "provisioning", 2: "operational", 255: "unknown"} + +# TLV tag -> (field_name, decoder) +FieldMap = dict[int, tuple[str, Callable[[bytes], Any]]] + + +def b64e(data: bytes) -> str: + return base64.b64encode(data).decode("ascii") + + +def base64_trim(s: str) -> str: + return "".join(c for c in s if c not in "\n\r \t") + + +def b64d(s: str) -> bytes: + return base64.b64decode(base64_trim(s)) + + +class AtClient: + def __init__(self, device: str, baud: int, timeout: float) -> None: + self.channel: str | None = None + self._device = device + self._baud = baud + self._timeout = timeout + self._serial: serial.Serial | None = None + + def send_raw(self, data: bytes) -> None: + self._ensure_serial() + self._serial.reset_input_buffer() + self._serial.write(data) + self._serial.flush() + + def close(self) -> None: + try: + if self.channel: + try: + self.query(f"AT+CCHC={self.channel}") + except (RuntimeError, TimeoutError): + pass + self.channel = None + finally: + if self._serial: + self._serial.close() + + def _send(self, cmd: str) -> None: + if DEBUG: + print(f"SER >> {cmd}", file=sys.stderr) + self._serial.write((cmd + "\r").encode("ascii")) + + def _expect(self) -> list[str]: + lines: list[str] = [] + while True: + raw = self._serial.readline() + if not raw: + raise TimeoutError("AT command timed out") + line = raw.decode(errors="ignore").strip() + if not line: + continue + if DEBUG: + print(f"SER << {line}", file=sys.stderr) + if line == "OK": + return lines + if line == "ERROR" or line.startswith("+CME ERROR"): + raise RuntimeError(f"AT command failed: {line}") + lines.append(line) + + def _ensure_serial(self, reconnect: bool = False) -> None: + if reconnect: + self.channel = None + try: + if self._serial: + self._serial.close() + except Exception: + pass + self._serial = None + if self._serial is None: + self._serial = serial.Serial(self._device, baudrate=self._baud, timeout=self._timeout) + + def query(self, cmd: str) -> list[str]: + self._ensure_serial() + try: + self._send(cmd) + return self._expect() + except serial.SerialException: + self._ensure_serial(reconnect=True) + self._send(cmd) + return self._expect() + + def _open_isdr_once(self) -> None: + if self.channel: + try: + self.query(f"AT+CCHC={self.channel}") + except RuntimeError: + pass + self.channel = None + # drain any unsolicited responses before opening + if self._serial: + try: + self._serial.reset_input_buffer() + except (OSError, serial.SerialException, termios.error): + self._ensure_serial(reconnect=True) + for line in self.query(f'AT+CCHO="{ISDR_AID}"'): + if line.startswith("+CCHO:") and (ch := line.split(":", 1)[1].strip()): + self.channel = ch + return + raise RuntimeError("Failed to open ISD-R application") + + def _reset_modem(self) -> None: + if self._serial: + try: + self._serial.close() + except Exception: + pass + self._serial = None + subprocess.run(['/usr/comma/lte/lte.sh', 'start'], capture_output=True) + + def open_isdr(self) -> None: + for attempt in range(OPEN_ISDR_RETRIES): + try: + self._open_isdr_once() + return + except (RuntimeError, TimeoutError, termios.error, serial.SerialException): + time.sleep(OPEN_ISDR_RETRY_DELAY_S) + if attempt == OPEN_ISDR_RESET_ATTEMPT: + self._reset_modem() + raise RuntimeError("Failed to open ISD-R after retries") + + def send_apdu(self, apdu: bytes) -> tuple[bytes, int, int]: + for attempt in range(SEND_APDU_RETRIES): + try: + if not self.channel: + self.open_isdr() + hex_payload = apdu.hex().upper() + for line in self.query(f'AT+CGLA={self.channel},{len(hex_payload)},"{hex_payload}"'): + if line.startswith("+CGLA:"): + parts = line.split(":", 1)[1].split(",", 1) + if len(parts) == 2: + data = bytes.fromhex(parts[1].strip().strip('"')) + if len(data) >= 2: + return data[:-2], data[-2], data[-1] + raise RuntimeError("Missing +CGLA response") + except (RuntimeError, ValueError): + self.channel = None + if attempt == SEND_APDU_RETRIES - 1: + raise + raise RuntimeError("send_apdu failed") + + +# --- TLV utilities --- + +def iter_tlv(data: bytes, with_positions: bool = False) -> Generator: + idx, length = 0, len(data) + while idx < length: + start_pos = idx + tag = data[idx] + idx += 1 + if tag & 0x1F == 0x1F: # Multi-byte tag + tag_value = tag + while idx < length: + next_byte = data[idx] + idx += 1 + tag_value = (tag_value << 8) | next_byte + if not (next_byte & 0x80): + break + else: + tag_value = tag + if idx >= length: + break + size = data[idx] + idx += 1 + if size & 0x80: # Multi-byte length + num_bytes = size & 0x7F + if idx + num_bytes > length: + break + size = int.from_bytes(data[idx : idx + num_bytes], "big") + idx += num_bytes + if idx + size > length: + break + value = data[idx : idx + size] + idx += size + yield (tag_value, value, start_pos, idx) if with_positions else (tag_value, value) + + +def find_tag(data: bytes, target: int) -> bytes | None: + return next((v for t, v in iter_tlv(data) if t == target), None) + + +def require_tag(data: bytes, target: int, label: str = "") -> bytes: + v = find_tag(data, target) + if v is None: + raise RuntimeError(f"Missing {label or f'tag 0x{target:X}'}") + return v + + +def tbcd_to_string(raw: bytes) -> str: + return "".join(str(n) for b in raw for n in (b & 0x0F, b >> 4) if n <= 9) + + +def string_to_tbcd(s: str) -> bytes: + digits = [int(c) for c in s if c.isdigit()] + return bytes(digits[i] | ((digits[i + 1] if i + 1 < len(digits) else 0xF) << 4) for i in range(0, len(digits), 2)) + + +def encode_tlv(tag: int, value: bytes) -> bytes: + tag_bytes = bytes([(tag >> 8) & 0xFF, tag & 0xFF]) if tag > 255 else bytes([tag]) + vlen = len(value) + if vlen <= 127: + return tag_bytes + bytes([vlen]) + value + length_bytes = vlen.to_bytes((vlen.bit_length() + 7) // 8, "big") + return tag_bytes + bytes([0x80 | len(length_bytes)]) + length_bytes + value + + +def int_bytes(n: int) -> bytes: + """Encode a positive integer as minimal big-endian bytes (at least 1 byte).""" + return n.to_bytes((n.bit_length() + 7) // 8 or 1, "big") + + +PROFILE: FieldMap = { + TAG_ICCID: ("iccid", tbcd_to_string), + 0x4F: ("isdpAid", lambda v: v.hex().upper()), + 0x9F70: ("profileState", lambda v: STATE_LABELS.get(v[0], "unknown")), + 0x90: ("profileNickname", lambda v: v.decode("utf-8", errors="ignore") or None), + 0x91: ("serviceProviderName", lambda v: v.decode("utf-8", errors="ignore") or None), + 0x92: ("profileName", lambda v: v.decode("utf-8", errors="ignore") or None), + 0x93: ("iconType", lambda v: ICON_LABELS.get(v[0], "unknown")), + 0x94: ("icon", b64e), + 0x95: ("profileClass", lambda v: CLASS_LABELS.get(v[0], "unknown")), +} + + +def decode_struct(data: bytes, field_map: FieldMap) -> dict[str, Any]: + """Parse TLV data using a {tag: (field_name, decoder)} map into a dict.""" + result: dict[str, Any] = {name: None for name, _ in field_map.values()} + for tag, value in iter_tlv(data): + if (field := field_map.get(tag)): + result[field[0]] = field[1](value) + return result + + +# --- ES10x command transport --- + +def es10x_command(client: AtClient, data: bytes) -> bytes: + response = bytearray() + sequence = 0 + offset = 0 + while offset < len(data): + chunk = data[offset : offset + ES10X_MSS] + offset += len(chunk) + is_last = offset == len(data) + apdu = bytes([0x80, 0xE2, 0x91 if is_last else 0x11, sequence & 0xFF, len(chunk)]) + chunk + segment, sw1, sw2 = client.send_apdu(apdu) + response.extend(segment) + while True: + if sw1 == 0x61: # More data available + segment, sw1, sw2 = client.send_apdu(bytes([0x80, 0xC0, 0x00, 0x00, sw2 or 0])) + response.extend(segment) + continue + if (sw1 & 0xF0) == 0x90: + break + raise RuntimeError(f"APDU failed with SW={sw1:02X}{sw2:02X}") + sequence += 1 + return bytes(response) + + +# --- Profile operations --- + +NOTIFICATION: FieldMap = { + TAG_STATUS: ("seqNumber", lambda v: int.from_bytes(v, "big")), + 0x81: ("profileManagementOperation", + lambda v: NOTIFICATION_OPERATIONS.get(next((m for m in NOTIFICATION_OPERATIONS if len(v) >= 2 and v[1] & m), 0), "unknown")), + 0x0C: ("notificationAddress", lambda v: v.decode("utf-8", errors="ignore")), + TAG_ICCID: ("iccid", tbcd_to_string), +} + + +def decode_profiles(blob: bytes) -> list[dict]: + root = require_tag(blob, TAG_PROFILE_INFO_LIST, "ProfileInfoList") + list_ok = find_tag(root, TAG_OK) + if list_ok is None: + return [] + return [decode_struct(value, PROFILE) for tag, value in iter_tlv(list_ok) if tag == 0xE3] + + +def list_profiles(client: AtClient) -> list[dict]: + return decode_profiles(es10x_command(client, TAG_PROFILE_INFO_LIST.to_bytes(2, "big") + b"\x00")) + + +def set_profile_nickname(client: AtClient, iccid: str, nickname: str) -> None: + nickname_bytes = nickname.encode("utf-8") + if len(nickname_bytes) > 64: + raise ValueError("Profile nickname must be 64 bytes or less") + content = encode_tlv(TAG_ICCID, string_to_tbcd(iccid)) + encode_tlv(0x90, nickname_bytes) + response = es10x_command(client, encode_tlv(TAG_SET_NICKNAME, content)) + code = require_tag(require_tag(response, TAG_SET_NICKNAME, "SetNicknameResponse"), TAG_STATUS, "SetNickname status")[0] + if code == 0x01: + raise LPAError(f"profile {iccid} not found") + if code != 0x00: + raise RuntimeError(f"SetNickname failed with status 0x{code:02X}") + + +# --- ES9P HTTP --- + +def es9p_request(smdp_address: str, endpoint: str, payload: dict, error_prefix: str = "Request", session: requests.Session | None = None) -> dict: + url = f"https://{smdp_address}/gsma/rsp2/es9plus/{endpoint}" + headers = {"User-Agent": "gsma-rsp-lpad", "X-Admin-Protocol": "gsma/rsp/v2.3.0", "Content-Type": "application/json"} + http = session or requests + resp = http.post(url, json=payload, headers=headers, timeout=HTTP_TIMEOUT, verify=GSMA_CI_BUNDLE) + resp.raise_for_status() + if not resp.content: + return {} + data = resp.json() + if "header" in data and "functionExecutionStatus" in data["header"]: + status = data["header"]["functionExecutionStatus"] + if status.get("status") == "Failed": + sd = status.get("statusCodeData", {}) + reason = sd.get("reasonCode", "unknown") + subject = sd.get("subjectCode", "unknown") + msg = ES9P_ERROR_MESSAGES.get((reason, subject), + f"{error_prefix} failed: {reason}/{subject} - {sd.get('message', 'unknown')}") + raise RuntimeError(msg) + return data + + +# --- Notifications --- + +def list_notifications(client: AtClient) -> list[dict]: + response = es10x_command(client, encode_tlv(TAG_LIST_NOTIFICATION, b"")) + root = require_tag(response, TAG_LIST_NOTIFICATION, "ListNotificationResponse") + metadata_list = find_tag(root, TAG_OK) + if metadata_list is None: + return [] + return [decode_struct(value, NOTIFICATION) for tag, value in iter_tlv(metadata_list) if tag == TAG_NOTIFICATION_METADATA] + + +def process_notifications(client: AtClient) -> None: + for notification in list_notifications(client): + seq_number, smdp_address = notification["seqNumber"], notification["notificationAddress"] + try: + request = encode_tlv(TAG_RETRIEVE_NOTIFICATION, encode_tlv(TAG_OK, encode_tlv(TAG_STATUS, int_bytes(seq_number)))) + response = es10x_command(client, request) + content = require_tag(require_tag(response, TAG_RETRIEVE_NOTIFICATION, "RetrieveNotificationsListResponse"), + TAG_OK, "RetrieveNotificationsListResponse") + pending_notif = next((v for t, v in iter_tlv(content) if t in (TAG_PROFILE_INSTALL_RESULT, 0x30)), None) + if pending_notif is None: + raise RuntimeError("Missing PendingNotification") + + es9p_request(smdp_address, "handleNotification", {"pendingNotification": b64e(pending_notif)}, "HandleNotification") + + response = es10x_command(client, encode_tlv(TAG_NOTIFICATION_SENT, encode_tlv(TAG_STATUS, int_bytes(seq_number)))) + root = require_tag(response, TAG_NOTIFICATION_SENT, "NotificationSentResponse") + if int.from_bytes(require_tag(root, TAG_STATUS, "RemoveNotificationFromList status"), "big") != 0: + raise RuntimeError("RemoveNotificationFromList failed") + except Exception as e: + print(f"notification {seq_number} failed: {e}", file=sys.stderr) + + +# --- Authentication & Download --- + +def get_challenge_and_info(client: AtClient) -> tuple[bytes, bytes]: + challenge_resp = es10x_command(client, encode_tlv(TAG_EUICC_CHALLENGE, b"")) + challenge = require_tag(require_tag(challenge_resp, TAG_EUICC_CHALLENGE, "GetEuiccDataResponse"), + TAG_STATUS, "challenge in response") + info_resp = es10x_command(client, encode_tlv(TAG_EUICC_INFO, b"")) + require_tag(info_resp, TAG_EUICC_INFO, "GetEuiccInfo1Response") + return challenge, info_resp + + +def authenticate_server(client: AtClient, b64_signed1: str, b64_sig1: str, b64_pk_id: str, b64_cert: str, matching_id: str) -> str: + tac = bytes([0x35, 0x29, 0x06, 0x11]) + device_info = encode_tlv(TAG_STATUS, tac) + encode_tlv(0xA1, b"") + ctx_inner = encode_tlv(TAG_STATUS, matching_id.encode("utf-8")) + encode_tlv(0xA1, device_info) + content = b64d(b64_signed1) + b64d(b64_sig1) + b64d(b64_pk_id) + b64d(b64_cert) + encode_tlv(0xA0, ctx_inner) + response = es10x_command(client, encode_tlv(TAG_AUTH_SERVER, content)) + root = require_tag(response, TAG_AUTH_SERVER, "AuthenticateServerResponse") + error_tag = find_tag(root, 0xA1) + if error_tag is not None: + code = int.from_bytes(error_tag, "big") if error_tag else 0 + raise RuntimeError(f"AuthenticateServer rejected by eUICC: {AUTH_SERVER_ERROR_CODES.get(code, 'unknown')} (0x{code:02X})") + return b64e(response) + + +def prepare_download(client: AtClient, b64_signed2: str, b64_sig2: str, b64_cert: str, cc: str | None = None) -> str: + smdp_signed2 = b64d(b64_signed2) + smdp_signature2 = b64d(b64_sig2) + smdp_certificate = b64d(b64_cert) + smdp_signed2_root = find_tag(smdp_signed2, 0x30) + if smdp_signed2_root is None: + raise RuntimeError("Invalid smdpSigned2") + transaction_id = find_tag(smdp_signed2_root, TAG_STATUS) + cc_required_flag = find_tag(smdp_signed2_root, 0x01) + if transaction_id is None or cc_required_flag is None: + raise RuntimeError("Invalid smdpSigned2") + content = smdp_signed2 + smdp_signature2 + if int.from_bytes(cc_required_flag, "big") != 0: + if not cc: + raise RuntimeError("Confirmation code required but not provided") + content += encode_tlv(0x04, hashlib.sha256(hashlib.sha256(cc.encode("utf-8")).digest() + transaction_id).digest()) + content += smdp_certificate + response = es10x_command(client, encode_tlv(TAG_PREPARE_DOWNLOAD, content)) + require_tag(response, TAG_PREPARE_DOWNLOAD, "PrepareDownloadResponse") + return b64e(response) + + +def _parse_tlv_header_len(data: bytes) -> int: + tag_len = 2 if data[0] & 0x1F == 0x1F else 1 + length_byte = data[tag_len] + return tag_len + (1 + (length_byte & 0x7F) if length_byte & 0x80 else 1) + + +def _split_bpp(bpp: bytes) -> list[bytes]: + """Split a BoundProfilePackage into APDU chunks per SGP.22 §5.7.6.""" + root_value = None + for tag, value, start, end in iter_tlv(bpp, with_positions=True): + if tag == TAG_BPP: + root_value = value + val_start = start + _parse_tlv_header_len(bpp[start:end]) + break + if root_value is None: + raise RuntimeError("Invalid BoundProfilePackage") + + chunks: list[bytes] = [] + for tag, value, start, end in iter_tlv(root_value, with_positions=True): + if tag == TAG_BPP_COMMAND: + chunks.append(bpp[0 : val_start + end]) + elif tag in (0xA0, 0xA2): + chunks.append(bpp[val_start + start : val_start + end]) + elif tag in (0xA1, 0xA3): + hdr_len = _parse_tlv_header_len(root_value[start:end]) + chunks.append(bpp[val_start + start : val_start + start + hdr_len]) + for _, _, cs, ce in iter_tlv(value, with_positions=True): + chunks.append(value[cs:ce]) + return chunks + + +def _parse_install_result(response: bytes) -> dict[str, Any] | None: + """Parse a ProfileInstallResult from an APDU response, or None if not present.""" + root = find_tag(response, TAG_PROFILE_INSTALL_RESULT) + if not root: + return None + result_data = find_tag(root, TAG_INSTALL_RESULT_DATA) + if not result_data: + return None + result: dict[str, Any] = {"seqNumber": 0, "success": False, "bppCommandId": None, "errorReason": None} + notif_meta = find_tag(result_data, TAG_NOTIFICATION_METADATA) + if notif_meta: + seq_num = find_tag(notif_meta, TAG_STATUS) + if seq_num: + result["seqNumber"] = int.from_bytes(seq_num, "big") + final_result = find_tag(result_data, 0xA2) + if final_result: + for tag, value in iter_tlv(final_result): + if tag == 0xA0: + result["success"] = True + elif tag == 0xA1: + bpp_cmd = find_tag(value, TAG_STATUS) + if bpp_cmd: + result["bppCommandId"] = int.from_bytes(bpp_cmd, "big") + err = find_tag(value, 0x81) + if err: + result["errorReason"] = int.from_bytes(err, "big") + return result + + +def load_bpp(client: AtClient, b64_bpp: str) -> dict: + bpp = b64d(b64_bpp) + result = None + for chunk in _split_bpp(bpp): + response = es10x_command(client, chunk) + if response and (parsed := _parse_install_result(response)): + result = parsed + break + + if result is None: + raise RuntimeError("Profile installation failed: no result from eUICC") + if not result["success"] and result["errorReason"] is not None: + msg = BPP_ERROR_MESSAGES.get(result["errorReason"]) + if not msg: + cmd_name = BPP_COMMAND_NAMES.get(result["bppCommandId"], f"unknown({result['bppCommandId']})") + err_name = BPP_ERROR_REASONS.get(result["errorReason"], f"unknown({result['errorReason']})") + msg = f"Profile installation failed at {cmd_name}: {err_name}" + raise RuntimeError(msg) + if not result["success"]: + raise RuntimeError("Profile installation failed: no result from eUICC") + return result + + +def parse_metadata(b64_metadata: str) -> dict: + root = find_tag(b64d(b64_metadata), TAG_PROFILE_METADATA) + if root is None: + raise RuntimeError("Invalid profileMetadata") + return decode_struct(root, PROFILE) + + +def cancel_session(client: AtClient, transaction_id: bytes, reason: int = 127) -> str: + content = encode_tlv(0x80, transaction_id) + encode_tlv(0x81, bytes([reason])) + response = es10x_command(client, encode_tlv(TAG_CANCEL_SESSION, content)) + return b64e(response) + + +def parse_lpa_activation_code(activation_code: str) -> tuple[str, str]: + """Parse 'LPA:1$smdp.example.com$MATCHING-ID' into (smdp_address, matching_id).""" + if not activation_code.startswith("LPA:"): + raise ValueError("Invalid activation code format") + parts = activation_code[4:].split("$") + if len(parts) != 3: + raise ValueError("Invalid activation code format") + return parts[1], parts[2] + + +def _b64_field(data: dict, key: str) -> str: + return base64_trim(data[key]) + + +def _cancel_session_safe(client: AtClient, smdp: str, tx_id: str, session: requests.Session) -> None: + b64_cancel = "" + try: + b64_cancel = cancel_session(client, b64d(tx_id)) + except Exception: + pass + try: + es9p_request(smdp, "cancelSession", {"transactionId": tx_id, "cancelSessionResponse": b64_cancel}, "CancelSession", session=session) + except Exception: + pass + + +def download_profile(client: AtClient, activation_code: str) -> str: + """Download and install an eSIM profile. Returns the ICCID of the installed profile.""" + if not system_time_valid(): + raise RuntimeError("System time is not set; TLS certificate validation requires a valid clock") + smdp, matching_id = parse_lpa_activation_code(activation_code) + challenge, euicc_info = get_challenge_and_info(client) + session = requests.Session() + tx_id = None + + try: + # step 1: initiate authentication + auth = es9p_request(smdp, "initiateAuthentication", { + "smdpAddress": smdp, "euiccChallenge": b64e(challenge), + "euiccInfo1": b64e(euicc_info), "matchingId": matching_id, + }, "Authentication", session=session) + tx_id = _b64_field(auth, "transactionId") + + # step 2: authenticate server + b64_auth = authenticate_server(client, + _b64_field(auth, "serverSigned1"), _b64_field(auth, "serverSignature1"), + _b64_field(auth, "euiccCiPKIdToBeUsed"), _b64_field(auth, "serverCertificate"), + matching_id) + + # step 3: authenticate client + get metadata + cli = es9p_request(smdp, "authenticateClient", { + "transactionId": tx_id, "authenticateServerResponse": b64_auth, + }, "Authentication", session=session) + iccid = parse_metadata(_b64_field(cli, "profileMetadata"))["iccid"] + + # step 4: prepare download + b64_prep = prepare_download(client, + _b64_field(cli, "smdpSigned2"), _b64_field(cli, "smdpSignature2"), + _b64_field(cli, "smdpCertificate")) + + # step 5: get and install bound profile package + bpp = es9p_request(smdp, "getBoundProfilePackage", { + "transactionId": tx_id, "prepareDownloadResponse": b64_prep, + }, "GetBoundProfilePackage", session=session) + load_bpp(client, _b64_field(bpp, "boundProfilePackage")) + return iccid + except Exception: + if tx_id: + _cancel_session_safe(client, smdp, tx_id, session) + raise + finally: + session.close() + + +class TiciLPA(LPABase): + def __init__(self): + if hasattr(self, '_client'): + return + self._client = AtClient(DEFAULT_DEVICE, DEFAULT_BAUD, DEFAULT_TIMEOUT) + atexit.register(self._client.close) + + @contextmanager + def _acquire_lock(self): + fd = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + fcntl.flock(fd, fcntl.LOCK_UN) + os.close(fd) + + @contextmanager + def _acquire_channel(self): + with self._acquire_lock(): + try: + self._client.open_isdr() + yield + finally: + if self._client.channel: + try: + self._client.query(f"AT+CCHC={self._client.channel}") + except (RuntimeError, TimeoutError): + pass + self._client.channel = None + + def list_profiles(self) -> list[Profile]: + with self._acquire_channel(): + return [ + Profile( + iccid=p.get("iccid", ""), + nickname=p.get("profileNickname") or "", + enabled=p.get("profileState") == "enabled", + provider=p.get("serviceProviderName") or "", + ) + for p in list_profiles(self._client) + ] + + def get_active_profile(self) -> Profile | None: + return None + + def process_notifications(self) -> None: + if not system_time_valid(): + raise RuntimeError("System time is not set; TLS certificate validation requires a valid clock") + with self._acquire_channel(): + process_notifications(self._client) + + def delete_profile(self, iccid: str) -> None: + profile = next((p for p in self.list_profiles() if p.iccid == iccid), None) + if profile is None: + raise LPAProfileNotFoundError(f"profile not found: {iccid}") + if profile.is_comma: + raise LPAError("refusing to delete a comma profile") + with self._acquire_channel(): + request = encode_tlv(TAG_DELETE_PROFILE, encode_tlv(TAG_ICCID, string_to_tbcd(iccid))) + response = es10x_command(self._client, request) + code = require_tag(require_tag(response, TAG_DELETE_PROFILE, "DeleteProfileResponse"), TAG_STATUS, "DeleteProfile status")[0] + if code != PROFILE_OK: + raise LPAError(f"DeleteProfile failed: {PROFILE_ERROR_CODES.get(code, 'unknown')} (0x{code:02X})") + + def download_profile(self, qr: str, nickname: str | None = None) -> None: + with self._acquire_channel(): + iccid = download_profile(self._client, qr) + if nickname and iccid: + set_profile_nickname(self._client, iccid, nickname) + + def nickname_profile(self, iccid: str, nickname: str) -> None: + with self._acquire_channel(): + set_profile_nickname(self._client, iccid, nickname) + + def _enable_profile(self, iccid: str) -> int: + inner = encode_tlv(TAG_OK, encode_tlv(TAG_ICCID, string_to_tbcd(iccid))) + inner += b'\x01\x01\x01' # refreshFlag=1 + response = es10x_command(self._client, encode_tlv(TAG_ENABLE_PROFILE, inner)) + return require_tag(require_tag(response, TAG_ENABLE_PROFILE, "EnableProfileResponse"), TAG_STATUS, "EnableProfile status")[0] + + def switch_profile(self, iccid: str) -> None: + with self._acquire_channel(): + code = self._enable_profile(iccid) + if code == PROFILE_CAT_BUSY: # stale eUICC transaction, reset and retry + self._client._reset_modem() + self._client.open_isdr() + code = self._enable_profile(iccid) + if code not in (PROFILE_OK, PROFILE_NOT_IN_DISABLED_STATE): + raise LPAError(f"EnableProfile failed: {PROFILE_ERROR_CODES.get(code, 'unknown')} (0x{code:02X})") + + def is_euicc(self) -> bool: + # +CCHO: -> ISD-R applet present, eUICC. Any error -> non-eUICC. + with self._acquire_lock(): + try: + lines = self._client.query(f'AT+CCHO="{ISDR_AID}"') + except RuntimeError: + return False + for line in lines: + if line.startswith("+CCHO:") and (ch := line.split(":", 1)[1].strip()): + try: + self._client.query(f"AT+CCHC={ch}") + except (RuntimeError, TimeoutError): + pass + self._client.channel = None + return True + return False diff --git a/system/hardware/tici/modem.py b/system/hardware/tici/modem.py new file mode 100755 index 00000000000000..39266be1225a61 --- /dev/null +++ b/system/hardware/tici/modem.py @@ -0,0 +1,587 @@ +#!/usr/bin/env python3 +import fcntl +import json +import logging +import os +import serial +import signal +import subprocess +import tempfile +import time + +from ipaddress import IPv4Address, AddressValueError + +from enum import Enum + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s.%(msecs)03d %(levelname)-7s modem: %(message)s", + datefmt="%H:%M:%S", +) + +AT_PORT = "/dev/modem_at0" +PPP_PORT = "/dev/modem_at1" +STATE_PATH = "/dev/shm/modem" +AT_LOCK = "/dev/shm/modem.lock" # shared with LPA +AT_INIT = [ + "ATE0", # disable command echo + "ATV1", # verbose result codes (CONNECT/BUSY/NO CARRIER, not numeric) + "AT+CMEE=1", # numeric +CME ERROR codes on failures (per 3GPP 27.007) + "ATX4", # extended result codes: busy + dial tone detection, line speed in CONNECT + "AT&C1", # DCD pin follows carrier state (V.250 default) + "AT+CREG=2", # registration URCs include location info + "AT+CGREG=2", # GPRS registration URCs include location info +] +CREG = {0: "not_registered", 1: "home", 2: "searching", 3: "denied", 4: "unknown", 5: "roaming"} +# 3GPP TS 27.007 +COPS -> network type +NETWORK_TYPE = {0: "gsm", 1: "gsm", 3: "gsm", 8: "gsm", + 2: "utran", 4: "utran", 5: "utran", 6: "utran", + 7: "lte", 9: "lte", 10: "lte", + 11: "nr", 12: "nr", 13: "nr"} + +DIAL_CID = 1 +WEBBING_ICCID_PREFIX = "8985235" + +PPPD_CMD = [ + "sudo", "pppd", PPP_PORT, "460800", "noauth", "nodetach", "noipdefault", "usepeerdns", + "nodefaultroute", "connect", + "/usr/sbin/chat -v ABORT 'NO CARRIER' ABORT 'NO DIALTONE' ABORT 'BUSY' " + + f"ABORT 'NO ANSWER' ABORT 'ERROR' TIMEOUT 5 '' AT OK ATD*99***{DIAL_CID}# CONNECT ''", + "lcp-echo-interval", "30", "lcp-echo-failure", "4", "mtu", "1500", "mru", "1500", + "novj", "novjccomp", "ipcp-accept-local", "ipcp-accept-remote", "nomagic", + "user", '""', "password", '""', +] +INITIAL_STATE = { + "seconds_since_boot": 0, + "state": "INITIALIZING", + "connected": False, "ip_address": "", + "iccid": "", "mcc_mnc": "", "imei": "", "modem_version": "", + "signal_strength": 0, "signal_quality": 0, + "network_type": "unknown", "operator": "", "band": "", "channel": 0, + "registration": "unknown", "temperatures": [], "extra": "", + "tx_bytes": 0, "rx_bytes": 0, +} + + +class State(Enum): + INITIALIZING = "INITIALIZING" + SEARCHING = "SEARCHING" + CONNECTING = "CONNECTING" + CONNECTED = "CONNECTED" + DISCONNECTING = "DISCONNECTING" + + +STATE_WAIT = 1.0 # seconds to wait after each state handler returns + + +class PPPSession: + """Owns pppd lifecycle, fail tracking, and PPP routing.""" + MAX_FAILS = 3 + + def __init__(self): + self._proc: subprocess.Popen | None = None + self._fails = 0 + self._peer = "" + + def start(self): + self._proc = subprocess.Popen(PPPD_CMD, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self._peer = "" + logging.info(f"PPP dialing CID {DIAL_CID}") + + def kill(self): + subprocess.run(["sudo", "killall", "-9", "pppd"], capture_output=True) + self._peer = "" + + @staticmethod + def reset_data_port(): + """Drop DTR on PPP_PORT so the modem terminates any stuck PPP session.""" + try: + with serial.Serial(PPP_PORT, 460800, timeout=1) as s: + s.dtr = False + time.sleep(0.2) + s.dtr = True + except Exception as e: + logging.warning(f"data port reset failed: {e}") + + def has_exited(self) -> bool: + return self._proc is not None and self._proc.poll() is not None + + def reset_fail_counter(self): + self._fails = 0 + + def record_fail(self) -> bool: + """Bump fail counter; return True if at the give-up limit.""" + self._fails += 1 + return self._fails >= self.MAX_FAILS + + @property + def fails(self) -> int: + return self._fails + + def maybe_install_routes(self, ip: str, peer: str) -> bool: + """Install routes if peer changed; kill the session on failure so the state machine reconnects.""" + if not peer or peer == self._peer: + return False + try: + IPv4Address(ip) + IPv4Address(peer) + except AddressValueError: + logging.warning(f"refusing route install with non-IPv4 ip={ip!r} peer={peer!r}") + self.kill() + return False + self.cleanup_routes() + cmds = [ + ["sudo", "ip", "route", "add", "default", "via", peer, "dev", "ppp0", "metric", "1000"], + ["sudo", "ip", "route", "add", "default", "via", peer, "dev", "ppp0", "table", "1000"], + ["sudo", "ip", "rule", "add", "from", ip, "table", "1000"], + ] + for cmd in cmds: + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + logging.warning(f"route install failed ({' '.join(cmd[1:])}): {r.stderr.strip()}") + self.cleanup_routes() + self.kill() + return False + logging.info(f"route set up for {ip} via {peer}") + self._peer = peer + return True + + def maybe_install_dns(self, dns_servers: list[str]) -> bool: + """Register DNS servers with systemd-resolved; kill the session on failure to force a retry.""" + if not dns_servers: + return False + for cmd in (["sudo", "resolvectl", "dns", "ppp0", *dns_servers], + ["sudo", "resolvectl", "default-route", "ppp0", "yes"]): + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + logging.warning(f"resolvectl failed ({' '.join(cmd[1:])}): {r.stderr.strip()}") + self.kill() + return False + logging.info(f"resolvectl: ppp0 DNS = {dns_servers}") + return True + + @staticmethod + def cleanup_routes(): + subprocess.run(["sudo", "ip", "route", "del", "default", "dev", "ppp0"], capture_output=True) + subprocess.run(["sudo", "ip", "route", "flush", "table", "1000"], capture_output=True) + # rules don't have a flush; delete until none remain + while subprocess.run(["sudo", "ip", "rule", "del", "table", "1000"], capture_output=True).returncode == 0: + pass + subprocess.run(["sudo", "resolvectl", "revert", "ppp0"], capture_output=True) + + +class Modem: + def __init__(self): + self._ppp = PPPSession() + self._sim_change = False + self._apn = "" # blank = network-provided via PCO + self._roaming_allowed = True + self.running = True + self.S = INITIAL_STATE.copy() + + @staticmethod + def _read_param(key): + try: + with open(f"/data/params/d/{key}") as f: + return f.read().strip() + except FileNotFoundError: + return "" + + @staticmethod + def _parse_reg(v: str) -> str: + try: + return CREG.get(int(v.split(",")[1].strip('"')), "unknown") + except (ValueError, IndexError): + return "unknown" + + @staticmethod + def _has_modem_manager() -> bool: + return os.path.isfile("/lib/systemd/system/ModemManager.service") + + def _is_roaming_allowed(self) -> bool: + if self.S["iccid"].startswith(WEBBING_ICCID_PREFIX): + return True + return self._read_param("GsmRoaming") == "1" + + def _publish_state(self, **kwargs): + self.S.update(kwargs) + self.S["seconds_since_boot"] = time.monotonic() + with tempfile.NamedTemporaryFile(mode="w", dir="/dev/shm", delete=False) as f: + json.dump(self.S, f, indent=2) + os.chmod(f.name, 0o644) + os.replace(f.name, STATE_PATH) + + def _at(self, cmd): + """Send AT command, return response lines. [] on error or if LPA holds port.""" + fd = os.open(AT_LOCK, os.O_CREAT | os.O_RDWR, 0o666) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + os.close(fd) + return [] + try: + with serial.Serial(AT_PORT, 9600, timeout=5) as ser: + ser.reset_input_buffer() + ser.write((cmd + "\r").encode()) + lines = [] + while True: + raw = ser.readline() + if not raw: + raise TimeoutError("AT timeout") + line = raw.decode(errors="ignore").strip() + if not line: + continue + if line == "OK": + break + if line == "ERROR" or line.startswith("+CME ERROR"): + raise RuntimeError(line) + lines.append(line) + return lines + except (RuntimeError, TimeoutError, OSError) as e: + logging.info(f"AT {cmd} failed: {e}") + return [] + finally: + fcntl.flock(fd, fcntl.LOCK_UN) + os.close(fd) + + def _atv(self, cmd, pfx): + for line in self._at(cmd): + if pfx in line and ":" in line: + return line.split(":", 1)[1].strip() + return None + + def _init_at_channel(self) -> bool: + """Run AT_INIT and confirm ATE0 took effect. Returns False if echo is still on.""" + for c in AT_INIT: + self._at(c) + r = self._at("AT+CGMI") + return bool(r) and not r[0].startswith("AT") + + def _configure_modem(self, modem_version: str): + if not modem_version.startswith("EG25"): + return + cmds = [ + # clear initial EPS bearer APN (some carriers reject the default) + 'AT+CGDCONT=0,"IP",""', + + # SIM hot swap + 'AT+QSIMDET=1,0', + 'AT+QSIMSTAT=1', + + # configure modem as data-centric + 'AT+QNVW=5280,0,"0102000000000000"', + 'AT+QNVFW="/nv/item_files/ims/IMS_enable",00', + 'AT+QNVFW="/nv/item_files/modem/mmode/ue_usage_setting",01', + ] + for c in cmds: + self._at(c) + + def _do_initializing(self): + if not os.path.exists(AT_PORT): + return State.INITIALIZING + logging.info("port found, initializing") + self._ppp.kill() + self._ppp.cleanup_routes() + + if not self._init_at_channel(): + logging.warning("AT echo still on, retrying") + return State.INITIALIZING + + identity = self._read_identity() + if not identity["iccid"] or not identity["imei"]: + logging.warning(f"identity read incomplete: {identity}, retrying") + return State.INITIALIZING + + self._configure_modem(identity["modem_version"]) + + self.S.update(identity) + self._apn = self._read_param("GsmApn") + self._roaming_allowed = self._is_roaming_allowed() + # blank APN lets the carrier supply one via PCO + self._at(f'AT+CGDCONT={DIAL_CID},"IP","{self._apn}"') + logging.info(f"APN '{self._apn or '(network-provided)'}' written to CID {DIAL_CID}, roaming={'on' if self._roaming_allowed else 'off'}") + + self._sim_change = False # clear since we just re-read identity with the new SIM + self._publish_state(**identity) + return State.SEARCHING + + def _read_identity(self): + def first_line(cmd): + r = self._at(cmd) + return r[0].strip() if r else "" + + imei = first_line("AT+CGSN") + if not (imei.isdigit() and 14 <= len(imei) <= 17): # 3GPP TS 23.003 + imei = "" + + iccid = (self._atv("AT+QCCID", "+QCCID:") or "").rstrip("F") + if not iccid.isdigit(): + iccid = "" + + imsi = first_line("AT+CIMI") + mcc_mnc = imsi[:6] if imsi.isdigit() and len(imsi) >= 6 else "" + + modem_version = first_line("AT+GMR") + + logging.info(f"imei={imei} iccid={iccid} mcc_mnc={mcc_mnc} ver={modem_version}") + return {"imei": imei, "iccid": iccid, "mcc_mnc": mcc_mnc, "modem_version": modem_version} + + def _do_searching(self): + new_roaming = self._is_roaming_allowed() + if new_roaming != self._roaming_allowed: + logging.info(f"roaming changed: {self._roaming_allowed} -> {new_roaming}") + self._roaming_allowed = new_roaming + + v = self._atv("AT+CREG?", "+CREG:") + if not v: + return self._searching_idle() + + reg = self._parse_reg(v) + greg = self._parse_reg(self._atv("AT+CGREG?", "+CGREG:") or "") + logging.debug(f"creg={reg} cgreg={greg} roaming_allowed={self._roaming_allowed}") + + if reg == "roaming" and not self._roaming_allowed: + self._publish_state(registration=reg) + return State.SEARCHING + + if reg in ("home", "roaming") and greg in ("home", "roaming"): + self._publish_state(registration=reg) + return State.CONNECTING + + if reg != self.S.get("registration"): + self._publish_state(registration=reg) + return self._searching_idle() + + def _searching_idle(self): + if self._sim_change or not os.path.exists(AT_PORT): + logging.info(f"-> reconnecting (sim_change={self._sim_change} port={os.path.exists(AT_PORT)})") + return State.DISCONNECTING + return State.SEARCHING + + def _do_connecting(self): + logging.info("starting pppd") + self._ppp.reset_fail_counter() + self._sim_change = False + self._ppp.start() + return State.CONNECTED + + def _handle_pppd_exit(self): + if self._sim_change or not os.path.exists(AT_PORT): + return State.DISCONNECTING + give_up = self._ppp.record_fail() + if give_up: + logging.warning(f"PPP fail {self._ppp.fails}/{self._ppp.MAX_FAILS}, reconnecting") + return State.DISCONNECTING + logging.warning(f"PPP fail {self._ppp.fails}/{self._ppp.MAX_FAILS}, retrying") + self._ppp.reset_data_port() + if not os.path.exists(AT_PORT): + return State.DISCONNECTING + self._ppp.start() + return State.CONNECTED + + def _params_changed(self) -> bool: + new_apn = self._read_param("GsmApn") + if new_apn != self._apn: + logging.info(f"GsmApn changed: '{self._apn}' -> '{new_apn}'") + return True + new_roaming = self._is_roaming_allowed() + if new_roaming != self._roaming_allowed: + logging.info(f"roaming changed: {self._roaming_allowed} -> {new_roaming}") + return True + return False + + def _check_iccid(self, state): + if state in (State.INITIALIZING, State.DISCONNECTING) or not self.S["iccid"]: + return + iccid = (self._atv("AT+QCCID", "+QCCID:") or "").rstrip("F") + if iccid and iccid != self.S["iccid"]: + logging.warning(f"iccid changed: {self.S['iccid']} -> {iccid}") + self._sim_change = True + + def _do_connected(self): + if self._ppp.has_exited(): + return self._handle_pppd_exit() + + if self._sim_change or not os.path.exists(AT_PORT) or self._params_changed(): + return State.DISCONNECTING + + self._poll() + return State.CONNECTED + + def _do_disconnecting(self): + logging.warning("reconnecting") + self._publish_state(**INITIAL_STATE) + self._ppp.kill() + self._ppp.cleanup_routes() + self._ppp.reset_data_port() + self._sim_change = False + return State.INITIALIZING + + def _poll_signal(self) -> dict: + v = self._atv("AT+CSQ", "+CSQ:") + if not v: + return {} + try: + rssi = int(v.split(",")[0]) + if rssi == 99: + return {} + return {"signal_strength": rssi, "signal_quality": min(100, int(rssi / 31 * 100))} + except (ValueError, IndexError): + return {} + + def _poll_operator(self) -> dict: + v = self._atv("AT+COPS?", "+COPS:") + if not v: + return {} + p = v.split(",") + out: dict = {} + try: + if len(p) >= 3: + out["operator"] = p[2].strip('"') + if len(p) >= 4: + out["network_type"] = NETWORK_TYPE.get(int(p[3]), "unknown") + except (ValueError, IndexError): + pass + return out + + def _poll_band(self) -> dict: + v = self._atv("AT+QNWINFO", "+QNWINFO:") + if not v: + return {} + info = v.replace('"', '').split(",") + try: + if len(info) >= 4: + return {"band": info[2], "channel": int(info[3])} + except ValueError: + pass + return {} + + def _poll_extra(self) -> dict: + v = self._atv('AT+QENG="servingcell"', "+QENG:") + return {"extra": v.replace('"', '')} if v else {} + + def _poll_temps(self) -> dict: + v = self._atv("AT+QTEMP", "+QTEMP:") + if not v: + return {} + try: + return {"temperatures": [t for t in (int(x) for x in v.split(",") if x.strip()) if t != 255]} + except (ValueError, IndexError): + return {} + + def _poll_iface(self) -> dict: + try: + r = subprocess.run(["ip", "-4", "addr", "show", "ppp0"], capture_output=True, text=True, timeout=2) + ip, peer = "", "" + for line in r.stdout.splitlines(): + # `inet 10.x.x.x peer 10.64.64.64/32 ...` + parts = line.strip().split() + if "inet" in parts: + i = parts.index("inet") + ip = parts[i + 1].split("/")[0] + if "peer" in parts: + peer = parts[parts.index("peer") + 1].split("/")[0] + break + if ip: + if self._ppp.maybe_install_routes(ip, peer): + self._ppp.maybe_install_dns(self._read_cellular_dns()) + return {"ip_address": ip, "connected": True} + if self.S["connected"]: + return {"connected": False, "ip_address": ""} + except Exception: + pass + return {} + + def _read_cellular_dns(self) -> list[str]: + v = self._atv(f"AT+CGCONTRDP={DIAL_CID}", "+CGCONTRDP:") + if not v: + return [] + # +CGCONTRDP: ,,,,,,,... + fields = [f.strip().strip('"') for f in v.split(",")] + dns_servers = [] + for d in fields[5:7]: + try: + dns_servers.append(str(IPv4Address(d))) + except (AddressValueError, ValueError): + pass + if not dns_servers: + logging.warning(f"no cellular DNS servers reported by modem: {v!r}") + return dns_servers + + def _poll_byte_counters(self) -> dict: + try: + with open("/sys/class/net/ppp0/statistics/tx_bytes") as f: + tx = int(f.read().strip()) + with open("/sys/class/net/ppp0/statistics/rx_bytes") as f: + rx = int(f.read().strip()) + except Exception: + return {} + return {"tx_bytes": tx, "rx_bytes": rx} + + def _poll(self): + s: dict = {} + for fn in (self._poll_signal, self._poll_operator, self._poll_band, + self._poll_extra, self._poll_temps, self._poll_iface, + self._poll_byte_counters): + s.update(fn()) + if s: + self._publish_state(**s) + + def run(self): + logging.info("starting") + self._publish_state(state=State.INITIALIZING.value) + if self._has_modem_manager(): + subprocess.run(["sudo", "systemctl", "mask", "--runtime", "ModemManager"], capture_output=True) + subprocess.run(["sudo", "systemctl", "stop", "ModemManager"], capture_output=True) + self._ppp.kill() + + state = State.INITIALIZING + + handlers = { + State.INITIALIZING: self._do_initializing, + State.SEARCHING: self._do_searching, + State.CONNECTING: self._do_connecting, + State.CONNECTED: self._do_connected, + State.DISCONNECTING: self._do_disconnecting, + } + + while self.running: + try: + self._check_iccid(state) + prev = state + state = handlers[state]() + if state != prev: + self._publish_state(state=state.value) + logging.info(f"{prev.value} -> {state.value}") + except Exception: + logging.exception(f"error in {state.value}") + state = State.DISCONNECTING + time.sleep(STATE_WAIT) + + def stop(self): + self.running = False + self._ppp.kill() + self._ppp.cleanup_routes() + try: + os.remove(STATE_PATH) + except FileNotFoundError: + pass + if self._has_modem_manager(): + subprocess.run(["sudo", "systemctl", "unmask", "--runtime", "ModemManager"], capture_output=True) + subprocess.run(["sudo", "systemctl", "start", "ModemManager"], capture_output=True) + + +def main(): + m = Modem() + + def _sig(*_): + m.running = False + + signal.signal(signal.SIGINT, _sig) + signal.signal(signal.SIGTERM, _sig) + m.run() + m.stop() + + +if __name__ == "__main__": + main() diff --git a/system/hardware/tici/pins.py b/system/hardware/tici/pins.py index 4388351e1f9f7f..bdbea591fbf840 100644 --- a/system/hardware/tici/pins.py +++ b/system/hardware/tici/pins.py @@ -1,5 +1,3 @@ -# TODO: these are also defined in a header - # GPIO pin definitions class GPIO: # both GPIO_STM_RST_N and GPIO_LTE_RST_N are misnamed, they are high to reset @@ -7,8 +5,10 @@ class GPIO: UBLOX_RST_N = 32 UBLOX_SAFEBOOT_N = 33 GNSS_PWR_EN = 34 # SCHEMATIC LABEL: GPIO_UBLOX_PWR_EN + STM_RST_N = 124 STM_BOOT0 = 134 + STM_PWR_EN_N = 41 # because STM32H7 RST doesn't generate a full power-on-reset SIREN = 42 SOM_ST_IO = 49 @@ -24,7 +24,4 @@ class GPIO: CAM2_RSTN = 12 # Sensor interrupts - BMX055_ACCEL_INT = 21 - BMX055_GYRO_INT = 23 - BMX055_MAGN_INT = 87 LSM_INT = 84 diff --git a/system/hardware/tici/restart_modem.sh b/system/hardware/tici/restart_modem.sh deleted file mode 100755 index 741dc72050fe32..00000000000000 --- a/system/hardware/tici/restart_modem.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash - -#nmcli connection modify --temporary lte gsm.home-only yes -#nmcli connection modify --temporary lte gsm.auto-config yes -#nmcli connection modify --temporary lte connection.autoconnect-retries 20 -sudo nmcli connection reload - -sudo systemctl stop ModemManager -nmcli con down lte -nmcli con down blue-prime - -# power cycle modem -/usr/comma/lte/lte.sh stop_blocking -/usr/comma/lte/lte.sh start - -sudo systemctl restart NetworkManager -#sudo systemctl restart ModemManager -sudo ModemManager --debug diff --git a/system/hardware/tici/tests/test_amplifier.py b/system/hardware/tici/tests/test_amplifier.py index 3f75436db1874f..9ce00c3ff26c26 100644 --- a/system/hardware/tici/tests/test_amplifier.py +++ b/system/hardware/tici/tests/test_amplifier.py @@ -5,7 +5,6 @@ from panda import Panda from openpilot.system.hardware import TICI, HARDWARE -from openpilot.system.hardware.tici.hardware import Tici from openpilot.system.hardware.tici.amplifier import Amplifier @@ -39,7 +38,7 @@ def _check_for_i2c_errors(self, expected): def test_init(self): amp = Amplifier(debug=True) - r = amp.initialize_configuration(Tici().get_device_type()) + r = amp.initialize_configuration() assert r assert self._check_for_i2c_errors(False) @@ -61,7 +60,7 @@ def test_init_while_siren_play(self): time.sleep(random.randint(0, 5)) amp = Amplifier(debug=True) - r = amp.initialize_configuration(Tici().get_device_type()) + r = amp.initialize_configuration() assert r if self._check_for_i2c_errors(True): diff --git a/system/hardware/tici/tests/test_hardware.py b/system/hardware/tici/tests/test_hardware.py deleted file mode 100644 index 75f53e7cdb8efc..00000000000000 --- a/system/hardware/tici/tests/test_hardware.py +++ /dev/null @@ -1,26 +0,0 @@ -import pytest -import time -import numpy as np - -from openpilot.system.hardware.tici.hardware import Tici - -HARDWARE = Tici() - - -@pytest.mark.tici -class TestHardware: - - def test_power_save_time(self): - ts = {True: [], False: []} - for _ in range(5): - for on in (True, False): - st = time.monotonic() - HARDWARE.set_power_save(on) - ts[on].append(time.monotonic() - st) - - # disabling power save is the main time-critical one - assert 0.1 < np.mean(ts[False]) < 0.15 - assert max(ts[False]) < 0.2 - - assert 0.1 < np.mean(ts[True]) < 0.35 - assert max(ts[True]) < 0.4 diff --git a/system/hardware/tici/tests/test_power_draw.py b/system/hardware/tici/tests/test_power_draw.py index eb3a515b76eeaa..6656addf73bb53 100644 --- a/system/hardware/tici/tests/test_power_draw.py +++ b/system/hardware/tici/tests/test_power_draw.py @@ -3,14 +3,13 @@ import time import numpy as np from dataclasses import dataclass -from tabulate import tabulate +from openpilot.common.utils import tabulate import cereal.messaging as messaging from cereal.services import SERVICE_LIST from opendbc.car.car_helpers import get_demo_car_params from openpilot.common.mock import mock_messages from openpilot.common.params import Params -from openpilot.selfdrive.car.card import convert_to_capnp from openpilot.system.hardware.tici.power_monitor import get_power from openpilot.system.manager.process_config import managed_processes from openpilot.system.manager.manager import manager_cleanup @@ -32,9 +31,9 @@ def name(self): PROCS = [ - Proc(['camerad'], 2.1, msgs=['roadCameraState', 'wideRoadCameraState', 'driverCameraState']), - Proc(['modeld'], 1.12, atol=0.2, msgs=['modelV2']), - Proc(['dmonitoringmodeld'], 0.4, msgs=['driverStateV2']), + Proc(['camerad'], 1.65, atol=0.4, msgs=['roadCameraState', 'wideRoadCameraState', 'driverCameraState']), + Proc(['modeld'], 1.5, atol=0.2, msgs=['modelV2']), + Proc(['dmonitoringmodeld'], 0.65, atol=0.35, msgs=['driverStateV2']), Proc(['encoderd'], 0.23, msgs=[]), ] @@ -43,7 +42,7 @@ def name(self): class TestPowerDraw: def setup_method(self): - Params().put("CarParams", convert_to_capnp(get_demo_car_params()).to_bytes()) + Params().put("CarParams", get_demo_car_params().to_bytes(), block=True) # wait a bit for power save to disable time.sleep(5) @@ -57,10 +56,10 @@ def get_expected_messages(self, proc): def valid_msg_count(self, proc, msg_counts): msgs_received = sum(msg_counts[msg] for msg in proc.msgs) msgs_expected = self.get_expected_messages(proc) - return np.core.numeric.isclose(msgs_expected, msgs_received, rtol=.02, atol=2) + return np.isclose(msgs_expected, msgs_received, rtol=.02, atol=2) def valid_power_draw(self, proc, used): - return np.core.numeric.isclose(used, proc.power, rtol=proc.rtol, atol=proc.atol) + return np.isclose(used, proc.power, rtol=proc.rtol, atol=proc.atol) def tabulate_msg_counts(self, msgs_and_power): msg_counts = defaultdict(int) diff --git a/system/hardware/tici/updater b/system/hardware/tici/updater index 11ce7809d09774..69ce323a1064e9 100755 --- a/system/hardware/tici/updater +++ b/system/hardware/tici/updater @@ -1,3 +1,17 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8db3f973663e59921fcc9e5d5600a346c1e229a2e8481a874ef996d97303dc4e -size 16631712 +#!/usr/bin/env bash + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" + +AGNOS_PY=$1 +MANIFEST=$2 + +if [[ ! -f "$AGNOS_PY" || ! -f "$MANIFEST" ]]; then + echo "invalid args" + exit 1 +fi + +if systemctl is-active --quiet weston-ready; then + $DIR/updater_weston $AGNOS_PY $MANIFEST +else + $DIR/updater_magic $AGNOS_PY $MANIFEST +fi diff --git a/system/hardware/tici/updater_magic b/system/hardware/tici/updater_magic new file mode 100755 index 00000000000000..44b82d0c547173 --- /dev/null +++ b/system/hardware/tici/updater_magic @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a94ab8395f20d20a9d5a2a2bacca0694f072df8421cf13adca6250d28065bdc +size 24709205 diff --git a/system/hardware/tici/updater_weston b/system/hardware/tici/updater_weston new file mode 100755 index 00000000000000..23cdc140f452a1 --- /dev/null +++ b/system/hardware/tici/updater_weston @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eba5f44e6a763e1f74d1c718993218adcc72cba4caafe99b595fa701151a4c54 +size 10448792 diff --git a/system/journald.py b/system/journald.py new file mode 100755 index 00000000000000..37158b9251dd5b --- /dev/null +++ b/system/journald.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +import json +import subprocess + +import cereal.messaging as messaging +from openpilot.common.swaglog import cloudlog + + +def main(): + pm = messaging.PubMaster(['androidLog']) + cmd = ['journalctl', '-f', '-o', 'json'] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) + assert proc.stdout is not None + try: + for line in proc.stdout: + line = line.strip() + if not line: + continue + try: + kv = json.loads(line) + except json.JSONDecodeError: + cloudlog.exception("failed to parse journalctl output") + continue + + msg = messaging.new_message('androidLog') + entry = msg.androidLog + entry.ts = int(kv.get('__REALTIME_TIMESTAMP', 0)) + entry.message = json.dumps(kv) + if '_PID' in kv: + entry.pid = int(kv['_PID']) + if 'PRIORITY' in kv: + entry.priority = int(kv['PRIORITY']) + if 'SYSLOG_IDENTIFIER' in kv: + entry.tag = kv['SYSLOG_IDENTIFIER'] + + pm.send('androidLog', msg) + finally: + proc.terminate() + proc.wait() + + +if __name__ == '__main__': + main() diff --git a/system/logcatd/.gitignore b/system/logcatd/.gitignore deleted file mode 100644 index c66f7622d96b86..00000000000000 --- a/system/logcatd/.gitignore +++ /dev/null @@ -1 +0,0 @@ -logcatd diff --git a/system/logcatd/SConscript b/system/logcatd/SConscript deleted file mode 100644 index 39c45d10931fae..00000000000000 --- a/system/logcatd/SConscript +++ /dev/null @@ -1,3 +0,0 @@ -Import('env', 'messaging', 'common') - -env.Program('logcatd', 'logcatd_systemd.cc', LIBS=[messaging, common, 'systemd']) diff --git a/system/logcatd/logcatd_systemd.cc b/system/logcatd/logcatd_systemd.cc deleted file mode 100644 index 54b37821328203..00000000000000 --- a/system/logcatd/logcatd_systemd.cc +++ /dev/null @@ -1,75 +0,0 @@ -#include - -#include -#include -#include -#include - -#include "third_party/json11/json11.hpp" - -#include "cereal/messaging/messaging.h" -#include "common/timing.h" -#include "common/util.h" - -ExitHandler do_exit; -int main(int argc, char *argv[]) { - - PubMaster pm({"androidLog"}); - - sd_journal *journal; - int err = sd_journal_open(&journal, 0); - assert(err >= 0); - err = sd_journal_get_fd(journal); // needed so sd_journal_wait() works properly if files rotate - assert(err >= 0); - err = sd_journal_seek_tail(journal); - assert(err >= 0); - - // workaround for bug https://github.com/systemd/systemd/issues/9934 - // call sd_journal_previous_skip after sd_journal_seek_tail (like journalctl -f does) to makes things work. - sd_journal_previous_skip(journal, 1); - - while (!do_exit) { - err = sd_journal_next(journal); - assert(err >= 0); - - // Wait for new message if we didn't receive anything - if (err == 0) { - err = sd_journal_wait(journal, 1000 * 1000); - assert(err >= 0); - continue; // Try again - } - - uint64_t timestamp = 0; - err = sd_journal_get_realtime_usec(journal, ×tamp); - assert(err >= 0); - - const void *data; - size_t length; - std::map kv; - - SD_JOURNAL_FOREACH_DATA(journal, data, length) { - std::string str((char*)data, length); - - // Split "KEY=VALUE"" on "=" and put in map - std::size_t found = str.find("="); - if (found != std::string::npos) { - kv[str.substr(0, found)] = str.substr(found + 1, std::string::npos); - } - } - - MessageBuilder msg; - - // Build message - auto androidEntry = msg.initEvent().initAndroidLog(); - androidEntry.setTs(timestamp); - androidEntry.setMessage(json11::Json(kv).dump()); - if (kv.count("_PID")) androidEntry.setPid(std::atoi(kv["_PID"].c_str())); - if (kv.count("PRIORITY")) androidEntry.setPriority(std::atoi(kv["PRIORITY"].c_str())); - if (kv.count("SYSLOG_IDENTIFIER")) androidEntry.setTag(kv["SYSLOG_IDENTIFIER"]); - - pm.send("androidLog", msg); - } - - sd_journal_close(journal); - return 0; -} diff --git a/system/loggerd/SConscript b/system/loggerd/SConscript index 196d18476a3157..a638704dcad992 100644 --- a/system/loggerd/SConscript +++ b/system/loggerd/SConscript @@ -1,26 +1,28 @@ Import('env', 'arch', 'messaging', 'common', 'visionipc') libs = [common, messaging, visionipc, - 'z', 'avformat', 'avcodec', 'swscale', - 'avutil', 'yuv', 'OpenCL', 'pthread'] + 'avformat', 'avcodec', 'swresample', 'avutil', 'x264', + 'pthread', 'z', 'm', 'zstd'] +frameworks = [] -src = ['logger.cc', 'video_writer.cc', 'encoder/encoder.cc', 'encoder/v4l_encoder.cc'] -if arch != "larch64": +src = ['logger.cc', 'zstd_writer.cc', 'video_writer.cc', 'encoder/encoder.cc', 'encoder/jpeg_encoder.cc'] +if arch == "larch64": + src += ['encoder/v4l_encoder.cc'] +else: src += ['encoder/ffmpeg_encoder.cc'] + libs += ['yuv'] + if arch == "Darwin": + frameworks += ['VideoToolbox', 'CoreMedia', 'CoreFoundation', 'CoreVideo'] -if arch == "Darwin": - # fix OpenCL - del libs[libs.index('OpenCL')] - env['FRAMEWORKS'] = ['OpenCL'] - # exclude v4l - del src[src.index('encoder/v4l_encoder.cc')] +if arch != "Darwin": + libs += ['va', 'va-drm', 'drm'] logger_lib = env.Library('logger', src) libs.insert(0, logger_lib) -env.Program('loggerd', ['loggerd.cc'], LIBS=libs) -env.Program('encoderd', ['encoderd.cc'], LIBS=libs) -env.Program('bootlog.cc', LIBS=libs) +env.Program('loggerd', ['loggerd.cc'], LIBS=libs, FRAMEWORKS=frameworks) +env.Program('encoderd', ['encoderd.cc'], LIBS=libs + ["jpeg"], FRAMEWORKS=frameworks) +env.Program('bootlog.cc', LIBS=libs, FRAMEWORKS=frameworks) if GetOption('extras'): - env.Program('tests/test_logger', ['tests/test_runner.cc', 'tests/test_logger.cc'], LIBS=libs + ['curl', 'crypto']) + env.Program('tests/test_logger', ['tests/test_runner.cc', 'tests/test_logger.cc', 'tests/test_zstd_writer.cc'], LIBS=libs) diff --git a/system/loggerd/bootlog.cc b/system/loggerd/bootlog.cc index b8257b6d696d4c..1b87ce394f9a0f 100644 --- a/system/loggerd/bootlog.cc +++ b/system/loggerd/bootlog.cc @@ -5,6 +5,7 @@ #include "common/params.h" #include "common/swaglog.h" #include "system/loggerd/logger.h" +#include "system/loggerd/zstd_writer.h" static kj::Array build_boot_log() { @@ -27,12 +28,9 @@ static kj::Array build_boot_log() { // Gather output of commands std::vector bootlog_commands = { - "[ -x \"$(command -v journalctl)\" ] && journalctl", + "[ -x \"$(command -v journalctl)\" ] && journalctl -o short-monotonic", }; - if (Hardware::TICI()) { - bootlog_commands.push_back("[ -e /dev/nvme0 ] && sudo nvme smart-log --output-format=json /dev/nvme0"); - } auto commands = boot.initCommands().initEntries(bootlog_commands.size()); for (int j = 0; j < bootlog_commands.size(); j++) { @@ -50,14 +48,14 @@ static kj::Array build_boot_log() { int main(int argc, char** argv) { const std::string id = logger_get_identifier("BootCount"); - const std::string path = Path::log_root() + "/boot/" + id; + const std::string path = Path::log_root() + "/boot/" + id + ".zst"; LOGW("bootlog to %s", path.c_str()); // Open bootlog bool r = util::create_directories(Path::log_root() + "/boot/", 0775); assert(r); - RawFile file(path.c_str()); + ZstdFileWriter file(path, LOG_COMPRESSION_LEVEL); // Write initdata file.write(logger_build_init_data().asBytes()); // Write bootlog diff --git a/system/loggerd/config.py b/system/loggerd/config.py index 5c2c89b73fcf20..e1c47c768df93f 100644 --- a/system/loggerd/config.py +++ b/system/loggerd/config.py @@ -9,7 +9,7 @@ STATS_SOCKET = "ipc:///tmp/stats" STATS_FLUSH_TIME_S = 60 -def get_available_percent(default=None): +def get_available_percent(default: float) -> float: try: statvfs = os.statvfs(Paths.log_root()) available_percent = 100.0 * statvfs.f_bavail / statvfs.f_blocks @@ -19,7 +19,7 @@ def get_available_percent(default=None): return available_percent -def get_available_bytes(default=None): +def get_available_bytes(default: int) -> int: try: statvfs = os.statvfs(Paths.log_root()) available_bytes = statvfs.f_bavail * statvfs.f_frsize diff --git a/system/loggerd/deleter.py b/system/loggerd/deleter.py index 7d83b490b0ff7f..eb8fd35f21813c 100755 --- a/system/loggerd/deleter.py +++ b/system/loggerd/deleter.py @@ -22,8 +22,9 @@ def has_preserve_xattr(d: str) -> bool: return getxattr(os.path.join(Paths.log_root(), d), PRESERVE_ATTR_NAME) == PRESERVE_ATTR_VALUE -def get_preserved_segments(dirs_by_creation: list[str]) -> list[str]: - preserved = [] +def get_preserved_segments(dirs_by_creation: list[str]) -> set[str]: + # skip deleting most recent N preserved segments (and their prior segment) + preserved = set() for n, d in enumerate(filter(has_preserve_xattr, reversed(dirs_by_creation))): if n == PRESERVE_COUNT: break @@ -39,20 +40,18 @@ def get_preserved_segments(dirs_by_creation: list[str]) -> list[str]: # preserve segment and two prior for _seg_num in range(max(0, seg_num - 2), seg_num + 1): - preserved.append(f"{date_str}--{_seg_num}") + preserved.add(f"{date_str}--{_seg_num}") return preserved -def deleter_thread(exit_event): +def deleter_thread(exit_event: threading.Event): while not exit_event.is_set(): out_of_bytes = get_available_bytes(default=MIN_BYTES + 1) < MIN_BYTES out_of_percent = get_available_percent(default=MIN_PERCENT + 1) < MIN_PERCENT if out_of_percent or out_of_bytes: dirs = listdir_by_creation(Paths.log_root()) - - # skip deleting most recent N preserved segments (and their prior segment) preserved_dirs = get_preserved_segments(dirs) # remove the earliest directory we can @@ -64,10 +63,7 @@ def deleter_thread(exit_event): try: cloudlog.info(f"deleting {delete_path}") - if os.path.isfile(delete_path): - os.remove(delete_path) - else: - shutil.rmtree(delete_path) + shutil.rmtree(delete_path) break except OSError: cloudlog.exception(f"issue deleting {delete_path}") diff --git a/system/loggerd/encoder/encoder.cc b/system/loggerd/encoder/encoder.cc index 313a0f57a142c4..06922b0cd07a12 100644 --- a/system/loggerd/encoder/encoder.cc +++ b/system/loggerd/encoder/encoder.cc @@ -6,20 +6,14 @@ VideoEncoder::VideoEncoder(const EncoderInfo &encoder_info, int in_width, int in out_width = encoder_info.frame_width > 0 ? encoder_info.frame_width : in_width; out_height = encoder_info.frame_height > 0 ? encoder_info.frame_height : in_height; - - std::vector pubs = {encoder_info.publish_name}; - if (encoder_info.thumbnail_name != NULL) { - pubs.push_back(encoder_info.thumbnail_name); - } - pm.reset(new PubMaster(pubs)); + pm.reset(new PubMaster(std::vector{encoder_info.publish_name})); } -void VideoEncoder::publisher_publish(VideoEncoder *e, int segment_num, uint32_t idx, VisionIpcBufExtra &extra, +void VideoEncoder::publisher_publish(int segment_num, uint32_t idx, VisionIpcBufExtra &extra, unsigned int flags, kj::ArrayPtr header, kj::ArrayPtr dat) { - // broadcast packet MessageBuilder msg; auto event = msg.initEvent(true); - auto edat = (event.*(e->encoder_info.init_encode_data_func))(); + auto edat = (event.*(encoder_info.init_encode_data_func))(); auto edata = edat.initIdx(); struct timespec ts; timespec_get(&ts, TIME_UTC); @@ -27,33 +21,22 @@ void VideoEncoder::publisher_publish(VideoEncoder *e, int segment_num, uint32_t edata.setFrameId(extra.frame_id); edata.setTimestampSof(extra.timestamp_sof); edata.setTimestampEof(extra.timestamp_eof); - edata.setType(e->encoder_info.encode_type); - edata.setEncodeId(e->cnt++); + edata.setType(encoder_info.get_settings(in_width).encode_type); + edata.setEncodeId(cnt++); edata.setSegmentNum(segment_num); edata.setSegmentId(idx); edata.setFlags(flags); edata.setLen(dat.size()); - edat.setData(dat); + edat.adoptData(msg.getOrphanage().referenceExternalData(dat)); edat.setWidth(out_width); edat.setHeight(out_height); if (flags & V4L2_BUF_FLAG_KEYFRAME) edat.setHeader(header); uint32_t bytes_size = capnp::computeSerializedSizeInWords(msg) * sizeof(capnp::word); - if (e->msg_cache.size() < bytes_size) { - e->msg_cache.resize(bytes_size); + if (msg_cache.size() < bytes_size) { + msg_cache.resize(bytes_size); } - kj::ArrayOutputStream output_stream(kj::ArrayPtr(e->msg_cache.data(), bytes_size)); + kj::ArrayOutputStream output_stream(kj::ArrayPtr(msg_cache.data(), bytes_size)); capnp::writeMessage(output_stream, msg); - e->pm->send(e->encoder_info.publish_name, e->msg_cache.data(), bytes_size); - - // Publish keyframe thumbnail - if ((flags & V4L2_BUF_FLAG_KEYFRAME) && e->encoder_info.thumbnail_name != NULL) { - MessageBuilder tm; - auto thumbnail = tm.initEvent().initThumbnail(); - thumbnail.setFrameId(extra.frame_id); - thumbnail.setTimestampEof(extra.timestamp_eof); - thumbnail.setThumbnail(dat); - thumbnail.setEncoding(cereal::Thumbnail::Encoding::KEYFRAME); - pm->send(e->encoder_info.thumbnail_name, tm); - } -} \ No newline at end of file + pm->send(encoder_info.publish_name, msg_cache.data(), bytes_size); +} diff --git a/system/loggerd/encoder/encoder.h b/system/loggerd/encoder/encoder.h index 72848609efbf4b..97cd10acc92eaa 100644 --- a/system/loggerd/encoder/encoder.h +++ b/system/loggerd/encoder/encoder.h @@ -1,5 +1,13 @@ #pragma once +// has to be in this order +#ifdef __linux__ +#include +#include +#else +#define V4L2_BUF_FLAG_KEYFRAME 8 +#endif + #include #include #include @@ -9,24 +17,19 @@ #include "cereal/messaging/messaging.h" #include "msgq/visionipc/visionipc.h" #include "common/queue.h" -#include "system/camerad/cameras/camera_common.h" #include "system/loggerd/loggerd.h" -#define V4L2_BUF_FLAG_KEYFRAME 8 - class VideoEncoder { public: VideoEncoder(const EncoderInfo &encoder_info, int in_width, int in_height); virtual ~VideoEncoder() {} virtual int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) = 0; - virtual void encoder_open(const char* path) = 0; + virtual void encoder_open() = 0; virtual void encoder_close() = 0; - void publisher_publish(VideoEncoder *e, int segment_num, uint32_t idx, VisionIpcBufExtra &extra, unsigned int flags, kj::ArrayPtr header, kj::ArrayPtr dat); + void publisher_publish(int segment_num, uint32_t idx, VisionIpcBufExtra &extra, unsigned int flags, kj::ArrayPtr header, kj::ArrayPtr dat); protected: - void publish_thumbnail(uint32_t frame_id, uint64_t timestamp_eof, kj::ArrayPtr dat); - int in_width, in_height; int out_width, out_height; const EncoderInfo encoder_info; diff --git a/system/loggerd/encoder/ffmpeg_encoder.cc b/system/loggerd/encoder/ffmpeg_encoder.cc index 9d992f088ddcd7..275a2e481e51df 100644 --- a/system/loggerd/encoder/ffmpeg_encoder.cc +++ b/system/loggerd/encoder/ffmpeg_encoder.cc @@ -1,5 +1,3 @@ -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - #include "system/loggerd/encoder/ffmpeg_encoder.h" #include @@ -11,7 +9,7 @@ #define __STDC_CONSTANT_MACROS -#include "third_party/libyuv/include/libyuv.h" +#include "libyuv.h" extern "C" { #include @@ -47,8 +45,11 @@ FfmpegEncoder::~FfmpegEncoder() { av_frame_free(&frame); } -void FfmpegEncoder::encoder_open(const char* path) { - const AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_FFVHUFF); +void FfmpegEncoder::encoder_open() { + auto codec_id = encoder_info.get_settings(in_width).encode_type == cereal::EncodeIndex::Type::QCAMERA_H264 + ? AV_CODEC_ID_H264 + : AV_CODEC_ID_FFVHUFF; + const AVCodec *codec = avcodec_find_encoder(codec_id); this->codec_ctx = avcodec_alloc_context3(codec); assert(this->codec_ctx); @@ -116,8 +117,7 @@ int FfmpegEncoder::encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) { ret = -1; } - AVPacket pkt; - av_init_packet(&pkt); + AVPacket pkt = {}; pkt.data = NULL; pkt.size = 0; while (ret >= 0) { @@ -138,7 +138,7 @@ int FfmpegEncoder::encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) { printf("%20s got %8d bytes flags %8x idx %4d id %8d\n", encoder_info.publish_name, pkt.size, pkt.flags, counter, extra->frame_id); } - publisher_publish(this, segment_num, counter, *extra, + publisher_publish(segment_num, counter, *extra, (pkt.flags & AV_PKT_FLAG_KEY) ? V4L2_BUF_FLAG_KEYFRAME : 0, kj::arrayPtr(pkt.data, (size_t)0), // TODO: get the header kj::arrayPtr(pkt.data, pkt.size)); diff --git a/system/loggerd/encoder/ffmpeg_encoder.h b/system/loggerd/encoder/ffmpeg_encoder.h index 9e45a3d82db5ea..cd5ac1e13a69eb 100644 --- a/system/loggerd/encoder/ffmpeg_encoder.h +++ b/system/loggerd/encoder/ffmpeg_encoder.h @@ -19,7 +19,7 @@ class FfmpegEncoder : public VideoEncoder { FfmpegEncoder(const EncoderInfo &encoder_info, int in_width, int in_height); ~FfmpegEncoder(); int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra); - void encoder_open(const char* path); + void encoder_open(); void encoder_close(); private: diff --git a/system/loggerd/encoder/jpeg_encoder.cc b/system/loggerd/encoder/jpeg_encoder.cc new file mode 100644 index 00000000000000..6bb946157c2279 --- /dev/null +++ b/system/loggerd/encoder/jpeg_encoder.cc @@ -0,0 +1,105 @@ +#include "system/loggerd/encoder/jpeg_encoder.h" + +#include +#include + +JpegEncoder::JpegEncoder(const std::string &pusblish_name, int width, int height) + : publish_name(pusblish_name), thumbnail_width(width), thumbnail_height(height) { + yuv_buffer.resize((thumbnail_width * ((thumbnail_height + 15) & ~15) * 3) / 2); + pm = std::make_unique(std::vector{pusblish_name.c_str()}); +} + +JpegEncoder::~JpegEncoder() { + if (out_buffer) { + free(out_buffer); + } +} + +void JpegEncoder::pushThumbnail(VisionBuf *buf, const VisionIpcBufExtra &extra) { + generateThumbnail(buf->y, buf->uv, buf->width, buf->height, buf->stride); + + MessageBuilder msg; + auto thumbnaild = msg.initEvent().initThumbnail(); + thumbnaild.setFrameId(extra.frame_id); + thumbnaild.setTimestampEof(extra.timestamp_eof); + thumbnaild.setThumbnail({out_buffer, out_size}); + + pm->send(publish_name.c_str(), msg); +} + +void JpegEncoder::generateThumbnail(const uint8_t *y_addr, const uint8_t *uv_addr, int width, int height, int stride) { + int downscale = width / thumbnail_width; + assert(downscale * thumbnail_height == height); + + // make the buffer big enough. jpeg_write_raw_data requires 16-pixels aligned height to be used. + uint8_t *y_plane = yuv_buffer.data(); + uint8_t *u_plane = y_plane + thumbnail_width * thumbnail_height; + uint8_t *v_plane = u_plane + (thumbnail_width * thumbnail_height) / 4; + { + // subsampled conversion from nv12 to yuv + for (int hy = 0; hy < thumbnail_height / 2; hy++) { + for (int hx = 0; hx < thumbnail_width / 2; hx++) { + int ix = hx * downscale + (downscale - 1) / 2; + int iy = hy * downscale + (downscale - 1) / 2; + y_plane[(hy * 2 + 0) * thumbnail_width + (hx * 2 + 0)] = y_addr[(iy * 2 + 0) * stride + ix * 2 + 0]; + y_plane[(hy * 2 + 0) * thumbnail_width + (hx * 2 + 1)] = y_addr[(iy * 2 + 0) * stride + ix * 2 + 1]; + y_plane[(hy * 2 + 1) * thumbnail_width + (hx * 2 + 0)] = y_addr[(iy * 2 + 1) * stride + ix * 2 + 0]; + y_plane[(hy * 2 + 1) * thumbnail_width + (hx * 2 + 1)] = y_addr[(iy * 2 + 1) * stride + ix * 2 + 1]; + u_plane[hy * thumbnail_width / 2 + hx] = uv_addr[iy * stride + ix * 2 + 0]; + v_plane[hy * thumbnail_width / 2 + hx] = uv_addr[iy * stride + ix * 2 + 1]; + } + } + } + + compressToJpeg(y_plane, u_plane, v_plane); +} + +void JpegEncoder::compressToJpeg(uint8_t *y_plane, uint8_t *u_plane, uint8_t *v_plane) { + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_compress(&cinfo); + + if (out_buffer) { + free(out_buffer); + out_buffer = nullptr; + out_size = 0; + } + jpeg_mem_dest(&cinfo, &out_buffer, &out_size); + + cinfo.image_width = thumbnail_width; + cinfo.image_height = thumbnail_height; + cinfo.input_components = 3; + + jpeg_set_defaults(&cinfo); + jpeg_set_colorspace(&cinfo, JCS_YCbCr); + // configure sampling factors for yuv420. + cinfo.comp_info[0].h_samp_factor = 2; // Y + cinfo.comp_info[0].v_samp_factor = 2; + cinfo.comp_info[1].h_samp_factor = 1; // U + cinfo.comp_info[1].v_samp_factor = 1; + cinfo.comp_info[2].h_samp_factor = 1; // V + cinfo.comp_info[2].v_samp_factor = 1; + cinfo.raw_data_in = TRUE; + + jpeg_set_quality(&cinfo, 50, TRUE); + jpeg_start_compress(&cinfo, TRUE); + + JSAMPROW y[16], u[8], v[8]; + JSAMPARRAY planes[3]{y, u, v}; + + for (int line = 0; line < cinfo.image_height; line += 16) { + for (int i = 0; i < 16; ++i) { + y[i] = y_plane + (line + i) * cinfo.image_width; + if (i % 2 == 0) { + int offset = (cinfo.image_width / 2) * ((i + line) / 2); + u[i / 2] = u_plane + offset; + v[i / 2] = v_plane + offset; + } + } + jpeg_write_raw_data(&cinfo, planes, 16); + } + + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); +} diff --git a/system/loggerd/encoder/jpeg_encoder.h b/system/loggerd/encoder/jpeg_encoder.h new file mode 100644 index 00000000000000..af1427c19a3d2d --- /dev/null +++ b/system/loggerd/encoder/jpeg_encoder.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "cereal/messaging/messaging.h" +#include "msgq/visionipc/visionbuf.h" + +class JpegEncoder { +public: + JpegEncoder(const std::string &pusblish_name, int width, int height); + ~JpegEncoder(); + void pushThumbnail(VisionBuf *buf, const VisionIpcBufExtra &extra); + +private: + void generateThumbnail(const uint8_t *y, const uint8_t *uv, int width, int height, int stride); + void compressToJpeg(uint8_t *y_plane, uint8_t *u_plane, uint8_t *v_plane); + + int thumbnail_width; + int thumbnail_height; + std::string publish_name; + std::vector yuv_buffer; + std::unique_ptr pm; + + // JPEG output buffer + unsigned char* out_buffer = nullptr; + unsigned long out_size = 0; +}; diff --git a/system/loggerd/encoder/v4l_encoder.cc b/system/loggerd/encoder/v4l_encoder.cc index 853a17abbecf4e..c54469f69d3869 100644 --- a/system/loggerd/encoder/v4l_encoder.cc +++ b/system/loggerd/encoder/v4l_encoder.cc @@ -7,11 +7,10 @@ #include "common/util.h" #include "common/timing.h" -#include "third_party/libyuv/include/libyuv.h" -#include "third_party/linux/include/msm_media_info.h" +#include // has to be in this order -#include "third_party/linux/include/v4l2-controls.h" +#include #include #define V4L2_QCOM_BUF_FLAG_CODECCONFIG 0x00020000 #define V4L2_QCOM_BUF_FLAG_EOS 0x02000000 @@ -24,14 +23,6 @@ */ const int env_debug_encoder = (getenv("DEBUG_ENCODER") != NULL) ? atoi(getenv("DEBUG_ENCODER")) : 0; -static void checked_ioctl(int fd, unsigned long request, void *argp) { - int ret = util::safe_ioctl(fd, request, argp); - if (ret != 0) { - LOGE("checked_ioctl failed with error %d (%d %lx %p)", errno, fd, request, argp); - assert(0); - } -} - static void dequeue_buffer(int fd, v4l2_buf_type buf_type, unsigned int *index=NULL, unsigned int *bytesused=NULL, unsigned int *flags=NULL, struct timeval *timestamp=NULL) { v4l2_plane plane = {0}; v4l2_buffer v4l_buf = { @@ -40,7 +31,7 @@ static void dequeue_buffer(int fd, v4l2_buf_type buf_type, unsigned int *index=N .m = { .planes = &plane, }, .length = 1, }; - checked_ioctl(fd, VIDIOC_DQBUF, &v4l_buf); + util::safe_ioctl(fd, VIDIOC_DQBUF, &v4l_buf, "VIDIOC_DQBUF failed"); if (index) *index = v4l_buf.index; if (bytesused) *bytesused = v4l_buf.m.planes[0].bytesused; @@ -51,32 +42,31 @@ static void dequeue_buffer(int fd, v4l2_buf_type buf_type, unsigned int *index=N static void queue_buffer(int fd, v4l2_buf_type buf_type, unsigned int index, VisionBuf *buf, struct timeval timestamp={}) { v4l2_plane plane = { + .bytesused = (uint32_t)buf->len, .length = (unsigned int)buf->len, .m = { .userptr = (unsigned long)buf->addr, }, - .bytesused = (uint32_t)buf->len, .reserved = {(unsigned int)buf->fd} }; v4l2_buffer v4l_buf = { - .type = buf_type, .index = index, + .type = buf_type, + .flags = V4L2_BUF_FLAG_TIMESTAMP_COPY, + .timestamp = timestamp, .memory = V4L2_MEMORY_USERPTR, .m = { .planes = &plane, }, .length = 1, - .flags = V4L2_BUF_FLAG_TIMESTAMP_COPY, - .timestamp = timestamp }; - - checked_ioctl(fd, VIDIOC_QBUF, &v4l_buf); + util::safe_ioctl(fd, VIDIOC_QBUF, &v4l_buf, "VIDIOC_QBUF failed"); } static void request_buffers(int fd, v4l2_buf_type buf_type, unsigned int count) { struct v4l2_requestbuffers reqbuf = { + .count = count, .type = buf_type, .memory = V4L2_MEMORY_USERPTR, - .count = count }; - checked_ioctl(fd, VIDIOC_REQBUFS, &reqbuf); + util::safe_ioctl(fd, VIDIOC_REQBUFS, &reqbuf, "VIDIOC_REQBUFS failed"); } void V4LEncoder::dequeue_handler(V4LEncoder *e) { @@ -133,7 +123,7 @@ void V4LEncoder::dequeue_handler(V4LEncoder *e) { assert(extra.timestamp_eof/1000 == ts); // stay in sync frame_id = extra.frame_id; ++idx; - e->publisher_publish(e, e->segment_num, idx, extra, flags, header, kj::arrayPtr(buf, bytesused)); + e->publisher_publish(e->segment_num, idx, extra, flags, header, kj::arrayPtr(buf, bytesused)); } if (env_debug_encoder) { @@ -155,15 +145,18 @@ void V4LEncoder::dequeue_handler(V4LEncoder *e) { V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_height) : VideoEncoder(encoder_info, in_width, in_height) { - fd = open("/dev/v4l/by-path/platform-aa00000.qcom_vidc-video-index1", O_RDWR|O_NONBLOCK); + fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-aa00000.qcom_vidc-video-index1", O_RDWR|O_NONBLOCK)); assert(fd >= 0); struct v4l2_capability cap; - checked_ioctl(fd, VIDIOC_QUERYCAP, &cap); + util::safe_ioctl(fd, VIDIOC_QUERYCAP, &cap, "VIDIOC_QUERYCAP failed"); LOGD("opened encoder device %s %s = %d", cap.driver, cap.card, fd); assert(strcmp((const char *)cap.driver, "msm_vidc_driver") == 0); assert(strcmp((const char *)cap.card, "msm_vidc_venc") == 0); + EncoderSettings encoder_settings = encoder_info.get_settings(in_width); + bool is_h265 = encoder_settings.encode_type == cereal::EncodeIndex::Type::FULL_H_E_V_C; + struct v4l2_format fmt_out = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .fmt = { @@ -171,13 +164,13 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei // downscales are free with v4l .width = (unsigned int)(out_width), .height = (unsigned int)(out_height), - .pixelformat = (encoder_info.encode_type == cereal::EncodeIndex::Type::FULL_H_E_V_C) ? V4L2_PIX_FMT_HEVC : V4L2_PIX_FMT_H264, + .pixelformat = is_h265 ? V4L2_PIX_FMT_HEVC : V4L2_PIX_FMT_H264, .field = V4L2_FIELD_ANY, .colorspace = V4L2_COLORSPACE_DEFAULT, } } }; - checked_ioctl(fd, VIDIOC_S_FMT, &fmt_out); + util::safe_ioctl(fd, VIDIOC_S_FMT, &fmt_out, "VIDIOC_S_FMT failed"); v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, @@ -186,12 +179,12 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei // TODO: more stuff here? we don't know .timeperframe = { .numerator = 1, - .denominator = 20 + .denominator = (unsigned int)encoder_info.fps } } } }; - checked_ioctl(fd, VIDIOC_S_PARM, &streamparm); + util::safe_ioctl(fd, VIDIOC_S_PARM, &streamparm, "VIDIOC_S_PARM failed"); struct v4l2_format fmt_in = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, @@ -205,7 +198,7 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei } } }; - checked_ioctl(fd, VIDIOC_S_FMT, &fmt_in); + util::safe_ioctl(fd, VIDIOC_S_FMT, &fmt_in, "VIDIOC_S_FMT failed"); LOGD("in buffer size %d, out buffer size %d", fmt_in.fmt.pix_mp.plane_fmt[0].sizeimage, @@ -214,34 +207,32 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei // shared ctrls { struct v4l2_control ctrls[] = { + { .id = V4L2_CID_MPEG_VIDEO_BITRATE, .value = encoder_settings.bitrate}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES, .value = encoder_settings.gop_size - encoder_settings.b_frames - 1}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES, .value = encoder_settings.b_frames}, { .id = V4L2_CID_MPEG_VIDEO_HEADER_MODE, .value = V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE}, - { .id = V4L2_CID_MPEG_VIDEO_BITRATE, .value = encoder_info.bitrate}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL, .value = V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_CFR}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY, .value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_IDR_PERIOD, .value = 1}, }; for (auto ctrl : ctrls) { - checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + util::safe_ioctl(fd, VIDIOC_S_CTRL, &ctrl, "VIDIOC_S_CTRL failed"); } } - if (encoder_info.encode_type == cereal::EncodeIndex::Type::FULL_H_E_V_C) { + if (is_h265) { struct v4l2_control ctrls[] = { { .id = V4L2_CID_MPEG_VIDC_VIDEO_HEVC_PROFILE, .value = V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_HEVC_TIER_LEVEL, .value = V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_VUI_TIMING_INFO, .value = V4L2_MPEG_VIDC_VIDEO_VUI_TIMING_INFO_ENABLED}, - { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES, .value = 29}, - { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES, .value = 0}, }; for (auto ctrl : ctrls) { - checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + util::safe_ioctl(fd, VIDIOC_S_CTRL, &ctrl, "VIDIOC_S_CTRL failed"); } } else { struct v4l2_control ctrls[] = { { .id = V4L2_CID_MPEG_VIDEO_H264_PROFILE, .value = V4L2_MPEG_VIDEO_H264_PROFILE_HIGH}, { .id = V4L2_CID_MPEG_VIDEO_H264_LEVEL, .value = V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN}, - { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES, .value = 14}, - { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES, .value = 0}, { .id = V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE, .value = V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL, .value = V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_0}, { .id = V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE, .value = 0}, @@ -250,7 +241,7 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei { .id = V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE, .value = 0}, }; for (auto ctrl : ctrls) { - checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + util::safe_ioctl(fd, VIDIOC_S_CTRL, &ctrl, "VIDIOC_S_CTRL failed"); } } @@ -260,9 +251,9 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei // start encoder v4l2_buf_type buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; - checked_ioctl(fd, VIDIOC_STREAMON, &buf_type); + util::safe_ioctl(fd, VIDIOC_STREAMON, &buf_type, "VIDIOC_STREAMON failed"); buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; - checked_ioctl(fd, VIDIOC_STREAMON, &buf_type); + util::safe_ioctl(fd, VIDIOC_STREAMON, &buf_type, "VIDIOC_STREAMON failed"); // queue up output buffers for (unsigned int i = 0; i < BUF_OUT_COUNT; i++) { @@ -275,7 +266,7 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei } } -void V4LEncoder::encoder_open(const char* path) { +void V4LEncoder::encoder_open() { dequeue_handler_thread = std::thread(V4LEncoder::dequeue_handler, this); this->is_open = true; this->counter = 0; @@ -305,7 +296,7 @@ void V4LEncoder::encoder_close() { for (int i = 0; i < BUF_IN_COUNT; i++) free_buf_in.push(i); // no frames, stop the encoder struct v4l2_encoder_cmd encoder_cmd = { .cmd = V4L2_ENC_CMD_STOP }; - checked_ioctl(fd, VIDIOC_ENCODER_CMD, &encoder_cmd); + util::safe_ioctl(fd, VIDIOC_ENCODER_CMD, &encoder_cmd, "VIDIOC_ENCODER_CMD failed"); // join waits for V4L2_QCOM_BUF_FLAG_EOS dequeue_handler_thread.join(); assert(extras.empty()); @@ -316,10 +307,10 @@ void V4LEncoder::encoder_close() { V4LEncoder::~V4LEncoder() { encoder_close(); v4l2_buf_type buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; - checked_ioctl(fd, VIDIOC_STREAMOFF, &buf_type); + util::safe_ioctl(fd, VIDIOC_STREAMOFF, &buf_type, "VIDIOC_STREAMOFF failed"); request_buffers(fd, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, 0); buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; - checked_ioctl(fd, VIDIOC_STREAMOFF, &buf_type); + util::safe_ioctl(fd, VIDIOC_STREAMOFF, &buf_type, "VIDIOC_STREAMOFF failed"); request_buffers(fd, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, 0); close(fd); diff --git a/system/loggerd/encoder/v4l_encoder.h b/system/loggerd/encoder/v4l_encoder.h index 9336bf3d8b81bc..58011d60e1a881 100644 --- a/system/loggerd/encoder/v4l_encoder.h +++ b/system/loggerd/encoder/v4l_encoder.h @@ -11,8 +11,9 @@ class V4LEncoder : public VideoEncoder { V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_height); ~V4LEncoder(); int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra); - void encoder_open(const char* path); + void encoder_open(); void encoder_close(); + private: int fd; diff --git a/system/loggerd/encoderd.cc b/system/loggerd/encoderd.cc index 1b45df68278fb2..9d4b81a3f90230 100644 --- a/system/loggerd/encoderd.cc +++ b/system/loggerd/encoderd.cc @@ -1,8 +1,9 @@ #include #include "system/loggerd/loggerd.h" +#include "system/loggerd/encoder/jpeg_encoder.h" -#ifdef QCOM2 +#ifdef __TICI__ #include "system/loggerd/encoder/v4l_encoder.h" #define Encoder V4LEncoder #else @@ -18,12 +19,12 @@ struct EncoderdState { // Sync logic for startup std::atomic encoders_ready = 0; std::atomic start_frame_id = 0; - bool camera_ready[WideRoadCam + 1] = {}; - bool camera_synced[WideRoadCam + 1] = {}; + bool camera_ready[VISION_STREAM_WIDE_ROAD + 1] = {}; + bool camera_synced[VISION_STREAM_WIDE_ROAD + 1] = {}; }; // Handle initial encoder syncing by waiting for all encoders to reach the same frame id -bool sync_encoders(EncoderdState *s, CameraType cam_type, uint32_t frame_id) { +bool sync_encoders(EncoderdState *s, VisionStreamType cam_type, uint32_t frame_id) { if (s->camera_synced[cam_type]) return true; if (s->max_waiting > 1 && s->encoders_ready != s->max_waiting) { @@ -50,6 +51,8 @@ void encoder_thread(EncoderdState *s, const LogCameraInfo &cam_info) { std::vector> encoders; VisionIpcClient vipc_client = VisionIpcClient("camerad", cam_info.stream_type, false); + std::unique_ptr jpeg_encoder; + int cur_seg = 0; while (!do_exit) { if (!vipc_client.connect(false)) { @@ -59,13 +62,18 @@ void encoder_thread(EncoderdState *s, const LogCameraInfo &cam_info) { // init encoders if (encoders.empty()) { - VisionBuf buf_info = vipc_client.buffers[0]; + const VisionBuf &buf_info = vipc_client.buffers[0]; LOGW("encoder %s init %zux%zu", cam_info.thread_name, buf_info.width, buf_info.height); assert(buf_info.width > 0 && buf_info.height > 0); for (const auto &encoder_info : cam_info.encoder_infos) { auto &e = encoders.emplace_back(new Encoder(encoder_info, buf_info.width, buf_info.height)); - e->encoder_open(nullptr); + e->encoder_open(); + } + + // Only one thumbnail can be generated per camera stream + if (auto thumbnail_name = cam_info.encoder_infos[0].thumbnail_name) { + jpeg_encoder = std::make_unique(thumbnail_name, buf_info.width / 4, buf_info.height / 4); } } @@ -85,7 +93,7 @@ void encoder_thread(EncoderdState *s, const LogCameraInfo &cam_info) { } lagging = false; - if (!sync_encoders(s, cam_info.type, extra.frame_id)) { + if (!sync_encoders(s, cam_info.stream_type, extra.frame_id)) { continue; } if (do_exit) break; @@ -95,7 +103,7 @@ void encoder_thread(EncoderdState *s, const LogCameraInfo &cam_info) { if (cur_seg >= 0 && extra.frame_id >= ((cur_seg + 1) * frames_per_seg) + s->start_frame_id) { for (auto &e : encoders) { e->encoder_close(); - e->encoder_open(NULL); + e->encoder_open(); } ++cur_seg; } @@ -108,6 +116,10 @@ void encoder_thread(EncoderdState *s, const LogCameraInfo &cam_info) { LOGE("Failed to encode frame. frame_id: %d", extra.frame_id); } } + + if (jpeg_encoder && (extra.frame_id % 1200 == 100)) { + jpeg_encoder->pushThumbnail(buf, extra); + } } } } diff --git a/system/loggerd/logger.cc b/system/loggerd/logger.cc index 8234cd84ade9d4..0ebe323939ab53 100644 --- a/system/loggerd/logger.cc +++ b/system/loggerd/logger.cc @@ -40,7 +40,7 @@ kj::Array logger_build_init_data() { init.setOsVersion(util::read_file("/VERSION")); // log params - auto params = Params(util::getenv("PARAMS_COPY_PATH", "")); + Params params(util::getenv("PARAMS_COPY_PATH", "")); std::map params_map = params.readAll(); init.setGitCommit(params_map["GitCommit"]); @@ -50,12 +50,16 @@ kj::Array logger_build_init_data() { init.setPassive(false); init.setDongleId(params_map["DongleId"]); + // for prebuilt branches + init.setGitSrcCommit(util::read_file("../../git_src_commit")); + init.setGitSrcCommitDate(util::read_file("../../git_src_commit_date")); + auto lparams = init.initParams().initEntries(params_map.size()); int j = 0; for (auto& [key, value] : params_map) { auto lentry = lparams[j]; lentry.setKey(key); - if ( !(params.getKeyType(key) & DONT_LOG) ) { + if ( !(params.getKeyFlag(key) & DONT_LOG) ) { lentry.setValue(capnp::Data::Reader((const kj::byte*)value.data(), value.size())); } j++; @@ -113,6 +117,42 @@ std::string logger_get_identifier(std::string key) { return util::string_format("%08x--%s", cnt, ss.str().c_str()); } +std::string zstd_decompress(const std::string &in) { + ZSTD_DCtx *dctx = ZSTD_createDCtx(); + assert(dctx != nullptr); + + // Initialize input and output buffers + ZSTD_inBuffer input = {in.data(), in.size(), 0}; + + // Estimate and reserve memory for decompressed data + size_t estimatedDecompressedSize = ZSTD_getFrameContentSize(in.data(), in.size()); + if (estimatedDecompressedSize == ZSTD_CONTENTSIZE_ERROR || estimatedDecompressedSize == ZSTD_CONTENTSIZE_UNKNOWN) { + estimatedDecompressedSize = in.size() * 2; // Use a fallback size + } + + std::string decompressedData; + decompressedData.reserve(estimatedDecompressedSize); + + const size_t bufferSize = ZSTD_DStreamOutSize(); // Recommended output buffer size + std::string outputBuffer(bufferSize, '\0'); + + while (input.pos < input.size) { + ZSTD_outBuffer output = {outputBuffer.data(), bufferSize, 0}; + + size_t result = ZSTD_decompressStream(dctx, &output, &input); + if (ZSTD_isError(result)) { + break; + } + + decompressedData.append(outputBuffer.data(), output.pos); + } + + ZSTD_freeDCtx(dctx); + decompressedData.shrink_to_fit(); + return decompressedData; +} + + static void log_sentinel(LoggerState *log, SentinelType type, int exit_signal = 0) { MessageBuilder msg; auto sen = msg.initEvent().initSentinel(); @@ -144,12 +184,11 @@ bool LoggerState::next() { bool ret = util::create_directories(segment_path, 0775); assert(ret == true); - const std::string rlog_path = segment_path + "/rlog"; - lock_file = rlog_path + ".lock"; + lock_file = segment_path + "/rlog.lock"; std::ofstream{lock_file}; - rlog.reset(new RawFile(rlog_path)); - qlog.reset(new RawFile(segment_path + "/qlog")); + rlog.reset(new ZstdFileWriter(segment_path + "/rlog.zst", LOG_COMPRESSION_LEVEL)); + qlog.reset(new ZstdFileWriter(segment_path + "/qlog.zst", LOG_COMPRESSION_LEVEL)); // log init data & sentinel type. write(init_data.asBytes(), true); diff --git a/system/loggerd/logger.h b/system/loggerd/logger.h index 7a8490d57a1300..18d07b5f383237 100644 --- a/system/loggerd/logger.h +++ b/system/loggerd/logger.h @@ -7,31 +7,12 @@ #include "cereal/messaging/messaging.h" #include "common/util.h" #include "system/hardware/hw.h" +#include "system/loggerd/zstd_writer.h" -class RawFile { - public: - RawFile(const std::string &path) { - file = util::safe_fopen(path.c_str(), "wb"); - assert(file != nullptr); - } - ~RawFile() { - util::safe_fflush(file); - int err = fclose(file); - assert(err == 0); - } - inline void write(void* data, size_t size) { - int written = util::safe_fwrite(data, 1, size, file); - assert(written == size); - } - inline void write(kj::ArrayPtr array) { write(array.begin(), array.size()); } - - private: - FILE* file = nullptr; -}; +constexpr int LOG_COMPRESSION_LEVEL = 10; typedef cereal::Sentinel::SentinelType SentinelType; - class LoggerState { public: LoggerState(const std::string& log_root = Path::log_root()); @@ -48,8 +29,9 @@ class LoggerState { int part = -1, exit_signal = 0; std::string route_path, route_name, segment_path, lock_file; kj::Array init_data; - std::unique_ptr rlog, qlog; + std::unique_ptr rlog, qlog; }; kj::Array logger_build_init_data(); std::string logger_get_identifier(std::string key); +std::string zstd_decompress(const std::string &in); diff --git a/system/loggerd/loggerd.cc b/system/loggerd/loggerd.cc index c9632c0dd60c7c..37559296192b51 100644 --- a/system/loggerd/loggerd.cc +++ b/system/loggerd/loggerd.cc @@ -62,8 +62,56 @@ struct RemoteEncoder { bool recording = false; bool marked_ready_to_rotate = false; bool seen_first_packet = false; + bool audio_initialized = false; }; +size_t write_encode_data(LoggerdState *s, cereal::Event::Reader event, RemoteEncoder &re, const EncoderInfo &encoder_info) { + auto edata = (event.*(encoder_info.get_encode_data_func))(); + auto idx = edata.getIdx(); + auto flags = idx.getFlags(); + + // if we aren't recording yet, try to start, since we are in the correct segment + if (!re.recording) { + if (flags & V4L2_BUF_FLAG_KEYFRAME) { + // only create on iframe + if (re.dropped_frames) { + // this should only happen for the first segment, maybe + LOGW("%s: dropped %d non iframe packets before init", encoder_info.publish_name, re.dropped_frames); + re.dropped_frames = 0; + } + if (encoder_info.record) { + // write the header + auto header = edata.getHeader(); + re.writer->write((uint8_t *)header.begin(), header.size(), idx.getTimestampEof() / 1000, true, false); + } + re.recording = true; + } else { + // this is a sad case when we aren't recording, but don't have an iframe + // nothing we can do but drop the frame + ++re.dropped_frames; + return 0; + } + } + + // we have to be recording if we are here + assert(re.recording); + + // if we are actually writing the video file, do so + if (re.writer) { + auto data = edata.getData(); + re.writer->write((uint8_t *)data.begin(), data.size(), idx.getTimestampEof() / 1000, false, flags & V4L2_BUF_FLAG_KEYFRAME); + } + + // put it in log stream as the idx packet + MessageBuilder bmsg; + auto evt = bmsg.initEvent(event.getValid()); + evt.setLogMonoTime(event.getLogMonoTime()); + (evt.*(encoder_info.set_encode_idx_func))(idx); + auto new_msg = bmsg.toBytes(); + s->logger.write((uint8_t *)new_msg.begin(), new_msg.size(), true); // always in qlog? + return new_msg.size(); +} + int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct RemoteEncoder &re, const EncoderInfo &encoder_info) { int bytes_count = 0; @@ -72,7 +120,6 @@ int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct auto event = cmsg.getRoot(); auto edata = (event.*(encoder_info.get_encode_data_func))(); auto idx = edata.getIdx(); - auto flags = idx.getFlags(); // encoderd can have started long before loggerd if (!re.seen_first_packet) { @@ -87,70 +134,36 @@ int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct // if this is a new segment, we close any possible old segments, move to the new, and process any queued packets if (re.current_segment != s->logger.segment()) { - if (re.recording) { - re.writer.reset(); + // if we aren't actually recording, don't create the writer + if (encoder_info.record) { + assert(encoder_info.filename != NULL); + re.writer.reset(new VideoWriter(s->logger.segmentPath().c_str(), + encoder_info.filename, idx.getType() != cereal::EncodeIndex::Type::FULL_H_E_V_C, + edata.getWidth(), edata.getHeight(), encoder_info.fps, idx.getType())); re.recording = false; + re.audio_initialized = false; } re.current_segment = s->logger.segment(); re.marked_ready_to_rotate = false; + } + if (re.audio_initialized || !encoder_info.include_audio) { // we are in this segment now, process any queued messages before this one if (!re.q.empty()) { - for (auto &qmsg : re.q) { - bytes_count += handle_encoder_msg(s, qmsg, name, re, encoder_info); + for (auto qmsg : re.q) { + capnp::FlatArrayMessageReader reader({(capnp::word *)qmsg->getData(), qmsg->getSize() / sizeof(capnp::word)}); + bytes_count += write_encode_data(s, reader.getRoot(), re, encoder_info); + delete qmsg; } re.q.clear(); } + bytes_count += write_encode_data(s, event, re, encoder_info); + delete msg; + } else if (re.q.size() > MAIN_FPS*10) { + LOGE_100("%s: dropping frame waiting for audio initialization, queue is too large", name.c_str()); + delete msg; + } else { + re.q.push_back(msg); // queue up all the new segment messages, they go in after audio is initialized } - - // if we aren't recording yet, try to start, since we are in the correct segment - if (!re.recording) { - if (flags & V4L2_BUF_FLAG_KEYFRAME) { - // only create on iframe - if (re.dropped_frames) { - // this should only happen for the first segment, maybe - LOGW("%s: dropped %d non iframe packets before init", name.c_str(), re.dropped_frames); - re.dropped_frames = 0; - } - // if we aren't actually recording, don't create the writer - if (encoder_info.record) { - assert(encoder_info.filename != NULL); - re.writer.reset(new VideoWriter(s->logger.segmentPath().c_str(), - encoder_info.filename, idx.getType() != cereal::EncodeIndex::Type::FULL_H_E_V_C, - edata.getWidth(), edata.getHeight(), encoder_info.fps, idx.getType())); - // write the header - auto header = edata.getHeader(); - re.writer->write((uint8_t *)header.begin(), header.size(), idx.getTimestampEof()/1000, true, false); - } - re.recording = true; - } else { - // this is a sad case when we aren't recording, but don't have an iframe - // nothing we can do but drop the frame - delete msg; - ++re.dropped_frames; - return bytes_count; - } - } - - // we have to be recording if we are here - assert(re.recording); - - // if we are actually writing the video file, do so - if (re.writer) { - auto data = edata.getData(); - re.writer->write((uint8_t *)data.begin(), data.size(), idx.getTimestampEof()/1000, false, flags & V4L2_BUF_FLAG_KEYFRAME); - } - - // put it in log stream as the idx packet - MessageBuilder bmsg; - auto evt = bmsg.initEvent(event.getValid()); - evt.setLogMonoTime(event.getLogMonoTime()); - (evt.*(encoder_info.set_encode_idx_func))(idx); - auto new_msg = bmsg.toBytes(); - s->logger.write((uint8_t *)new_msg.begin(), new_msg.size(), true); // always in qlog? - bytes_count += new_msg.size(); - - // free the message, we used it - delete msg; } else if (offset_segment_num > s->logger.segment()) { // encoderd packet has a newer segment, this means encoderd has rolled over if (!re.marked_ready_to_rotate) { @@ -160,8 +173,15 @@ int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct s->logger.segment(), offset_segment_num, s->ready_to_rotate.load(), s->max_waiting, name.c_str()); } - // queue up all the new segment messages, they go in after the rotate - re.q.push_back(msg); + + // TODO: define this behavior, but for now don't leak + if (re.q.size() > MAIN_FPS*10) { + LOGE_100("%s: dropping frame, queue is too large", name.c_str()); + delete msg; + } else { + // queue up all the new segment messages, they go in after the rotate + re.q.push_back(msg); + } } else { LOGE("%s: encoderd packet has a older segment!!! idx.getSegmentNum():%d s->logger.segment():%d re.encoderd_segment_offset:%d", name.c_str(), idx.getSegmentNum(), s->logger.segment(), re.encoderd_segment_offset); @@ -174,7 +194,7 @@ int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct return bytes_count; } -void handle_user_flag(LoggerdState *s) { +void handle_preserve_segment(LoggerdState *s) { static int prev_segment = -1; if (s->logger.segment() == prev_segment) return; @@ -191,7 +211,7 @@ void handle_user_flag(LoggerdState *s) { // mark route for uploading Params params; - std::string routes = Params().get("AthenadRecentlyViewedRoutes"); + std::string routes = params.get("AthenadRecentlyViewedRoutes"); params.put("AthenadRecentlyViewedRoutes", routes + "," + s->logger.routeName()); prev_segment = s->logger.segment(); @@ -199,11 +219,11 @@ void handle_user_flag(LoggerdState *s) { void loggerd_thread() { // setup messaging - typedef struct ServiceState { + struct ServiceState { std::string name; int counter, freq; - bool encoder, user_flag; - } ServiceState; + bool encoder, preserve_segment, record_audio; + }; std::unordered_map service_state; std::unordered_map remote_encoders; @@ -214,19 +234,22 @@ void loggerd_thread() { for (const auto& [_, it] : services) { const bool encoder = util::ends_with(it.name, "EncodeData"); const bool livestream_encoder = util::starts_with(it.name, "livestream"); - if (!it.should_log && (!encoder || livestream_encoder)) continue; - LOGD("logging %s", it.name.c_str()); - - SubSocket * sock = SubSocket::create(ctx.get(), it.name); - assert(sock != NULL); - poller->registerSocket(sock); - service_state[sock] = { - .name = it.name, - .counter = 0, - .freq = it.decimation, - .encoder = encoder, - .user_flag = it.name == "userFlag", - }; + const bool record_audio = (it.name == "rawAudioData") && Params().getBool("RecordAudio"); + if (it.should_log || (encoder && !livestream_encoder) || record_audio) { + LOGD("logging %s", it.name.c_str()); + + SubSocket * sock = SubSocket::create(ctx.get(), it.name, "127.0.0.1", false, true, it.queue_size); + assert(sock != NULL); + poller->registerSocket(sock); + service_state[sock] = { + .name = it.name, + .counter = 0, + .freq = it.decimation, + .encoder = encoder, + .preserve_segment = (it.name == "userBookmark") || (it.name == "audioFeedback"), + .record_audio = record_audio, + }; + } } LoggerdState s; @@ -235,6 +258,7 @@ void loggerd_thread() { Params().put("CurrentRoute", s.logger.routeName()); std::map encoder_infos_dict; + std::vector encoders_with_audio; for (const auto &cam : cameras_logged) { for (const auto &encoder_info : cam.encoder_infos) { encoder_infos_dict[encoder_info.publish_name] = encoder_info; @@ -242,6 +266,13 @@ void loggerd_thread() { } } + for (auto &[sock, service] : service_state) { + auto it = encoder_infos_dict.find(service.name); + if (it != encoder_infos_dict.end() && it->second.include_audio) { + encoders_with_audio.push_back(&remote_encoders[sock]); + } + } + uint64_t msg_count = 0, bytes_count = 0; double start_ts = millis_since_boot(); while (!do_exit) { @@ -250,8 +281,8 @@ void loggerd_thread() { if (do_exit) break; ServiceState &service = service_state[sock]; - if (service.user_flag) { - handle_user_flag(&s); + if (service.preserve_segment) { + handle_preserve_segment(&s); } // drain socket @@ -259,6 +290,20 @@ void loggerd_thread() { Message *msg = nullptr; while (!do_exit && (msg = sock->receive(true))) { const bool in_qlog = service.freq != -1 && (service.counter++ % service.freq == 0); + + if (service.record_audio) { + capnp::FlatArrayMessageReader cmsg(kj::ArrayPtr((capnp::word *)msg->getData(), msg->getSize() / sizeof(capnp::word))); + auto event = cmsg.getRoot(); + auto audio_data = event.getRawAudioData().getData(); + auto sample_rate = event.getRawAudioData().getSampleRate(); + for (auto* encoder : encoders_with_audio) { + if (encoder && encoder->writer) { + encoder->writer->write_audio((uint8_t*)audio_data.begin(), audio_data.size(), event.getLogMonoTime() / 1000, sample_rate); + encoder->audio_initialized = true; + } + } + } + if (service.encoder) { s.last_camera_seen_tms = millis_since_boot(); bytes_count += handle_encoder_msg(&s, msg, service.name, remote_encoders[sock], encoder_infos_dict[service.name]); @@ -270,7 +315,7 @@ void loggerd_thread() { rotate_if_needed(&s); - if ((++msg_count % 1000) == 0) { + if ((++msg_count % 10000) == 0) { double seconds = (millis_since_boot() - start_ts) / 1000.0; LOGD("%" PRIu64 " messages, %.2f msg/sec, %.2f KB/sec", msg_count, msg_count / seconds, bytes_count * 0.001 / seconds); } diff --git a/system/loggerd/loggerd.h b/system/loggerd/loggerd.h index 7c80ba51a214cd..01bce2c9ea7e7b 100644 --- a/system/loggerd/loggerd.h +++ b/system/loggerd/loggerd.h @@ -1,11 +1,11 @@ #pragma once +#include #include #include "cereal/messaging/messaging.h" #include "cereal/services.h" #include "msgq/visionipc/visionipc_client.h" -#include "system/camerad/cameras/camera_common.h" #include "system/hardware/hw.h" #include "common/params.h" #include "common/swaglog.h" @@ -14,10 +14,7 @@ #include "system/loggerd/logger.h" constexpr int MAIN_FPS = 20; -const int MAIN_BITRATE = 1e7; -const int LIVESTREAM_BITRATE = 1e6; -const int QCAM_BITRATE = 256000; - +const auto MAIN_ENCODE_TYPE = Hardware::PC() ? cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS : cereal::EncodeIndex::Type::FULL_H_E_V_C; #define NO_CAMERA_PATIENCE 500 // fall back to time-based rotation if all cameras are dead #define INIT_ENCODE_FUNCTIONS(encode_type) \ @@ -30,18 +27,43 @@ const int SEGMENT_LENGTH = LOGGERD_TEST ? atoi(getenv("LOGGERD_SEGMENT_LENGTH")) constexpr char PRESERVE_ATTR_NAME[] = "user.preserve"; constexpr char PRESERVE_ATTR_VALUE = '1'; + +struct EncoderSettings { + cereal::EncodeIndex::Type encode_type; + int bitrate; + int gop_size; + int b_frames = 0; // we don't use b frames + + static EncoderSettings MainEncoderSettings(int in_width) { + if (in_width <= 1344) { + return EncoderSettings{.encode_type = MAIN_ENCODE_TYPE, .bitrate = 5'000'000, .gop_size = 20}; + } else { + return EncoderSettings{.encode_type = MAIN_ENCODE_TYPE, .bitrate = 10'000'000, .gop_size = 30}; + } + } + + static EncoderSettings QcamEncoderSettings() { + return EncoderSettings{.encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, .bitrate = 256'000, .gop_size = 15}; + } + + static EncoderSettings StreamEncoderSettings() { + int _stream_bitrate = getenv("STREAM_BITRATE") ? atoi(getenv("STREAM_BITRATE")) : 4'000'000; + return EncoderSettings{.encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, .bitrate = _stream_bitrate , .gop_size = 5}; + } +}; + class EncoderInfo { public: const char *publish_name; const char *thumbnail_name = NULL; const char *filename = NULL; bool record = true; + bool include_audio = false; int frame_width = -1; int frame_height = -1; int fps = MAIN_FPS; - int bitrate = MAIN_BITRATE; - cereal::EncodeIndex::Type encode_type = Hardware::PC() ? cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS - : cereal::EncodeIndex::Type::FULL_H_E_V_C; + std::function get_settings; + ::cereal::EncodeData::Reader (cereal::Event::Reader::*get_encode_data_func)() const; void (cereal::Event::Builder::*set_encode_idx_func)(::cereal::EncodeIndex::Reader); cereal::EncodeData::Builder (cereal::Event::Builder::*init_encode_data_func)(); @@ -51,20 +73,22 @@ class LogCameraInfo { public: const char *thread_name; int fps = MAIN_FPS; - CameraType type; VisionStreamType stream_type; std::vector encoder_infos; }; const EncoderInfo main_road_encoder_info = { .publish_name = "roadEncodeData", + .thumbnail_name = "thumbnail", .filename = "fcamera.hevc", + .get_settings = [](int in_width){return EncoderSettings::MainEncoderSettings(in_width);}, INIT_ENCODE_FUNCTIONS(RoadEncode), }; const EncoderInfo main_wide_road_encoder_info = { .publish_name = "wideRoadEncodeData", .filename = "ecamera.hevc", + .get_settings = [](int in_width){return EncoderSettings::MainEncoderSettings(in_width);}, INIT_ENCODE_FUNCTIONS(WideRoadEncode), }; @@ -72,82 +96,74 @@ const EncoderInfo main_driver_encoder_info = { .publish_name = "driverEncodeData", .filename = "dcamera.hevc", .record = Params().getBool("RecordFront"), + .get_settings = [](int in_width){return EncoderSettings::MainEncoderSettings(in_width);}, INIT_ENCODE_FUNCTIONS(DriverEncode), }; const EncoderInfo stream_road_encoder_info = { .publish_name = "livestreamRoadEncodeData", //.thumbnail_name = "thumbnail", - .encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, .record = false, - .bitrate = LIVESTREAM_BITRATE, + .get_settings = [](int){return EncoderSettings::StreamEncoderSettings();}, INIT_ENCODE_FUNCTIONS(LivestreamRoadEncode), }; const EncoderInfo stream_wide_road_encoder_info = { .publish_name = "livestreamWideRoadEncodeData", - .encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, .record = false, - .bitrate = LIVESTREAM_BITRATE, + .get_settings = [](int){return EncoderSettings::StreamEncoderSettings();}, INIT_ENCODE_FUNCTIONS(LivestreamWideRoadEncode), }; const EncoderInfo stream_driver_encoder_info = { .publish_name = "livestreamDriverEncodeData", - .encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, .record = false, - .bitrate = LIVESTREAM_BITRATE, + .get_settings = [](int){return EncoderSettings::StreamEncoderSettings();}, INIT_ENCODE_FUNCTIONS(LivestreamDriverEncode), }; const EncoderInfo qcam_encoder_info = { .publish_name = "qRoadEncodeData", .filename = "qcamera.ts", - .bitrate = QCAM_BITRATE, - .encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, + .include_audio = Params().getBool("RecordAudio"), .frame_width = 526, .frame_height = 330, + .get_settings = [](int){return EncoderSettings::QcamEncoderSettings();}, INIT_ENCODE_FUNCTIONS(QRoadEncode), }; const LogCameraInfo road_camera_info{ .thread_name = "road_cam_encoder", - .type = RoadCam, .stream_type = VISION_STREAM_ROAD, .encoder_infos = {main_road_encoder_info, qcam_encoder_info} }; const LogCameraInfo wide_road_camera_info{ .thread_name = "wide_road_cam_encoder", - .type = WideRoadCam, .stream_type = VISION_STREAM_WIDE_ROAD, .encoder_infos = {main_wide_road_encoder_info} }; const LogCameraInfo driver_camera_info{ .thread_name = "driver_cam_encoder", - .type = DriverCam, .stream_type = VISION_STREAM_DRIVER, .encoder_infos = {main_driver_encoder_info} }; const LogCameraInfo stream_road_camera_info{ .thread_name = "road_cam_encoder", - .type = RoadCam, .stream_type = VISION_STREAM_ROAD, .encoder_infos = {stream_road_encoder_info} }; const LogCameraInfo stream_wide_road_camera_info{ .thread_name = "wide_road_cam_encoder", - .type = WideRoadCam, .stream_type = VISION_STREAM_WIDE_ROAD, .encoder_infos = {stream_wide_road_encoder_info} }; const LogCameraInfo stream_driver_camera_info{ .thread_name = "driver_cam_encoder", - .type = DriverCam, .stream_type = VISION_STREAM_DRIVER, .encoder_infos = {stream_driver_encoder_info} }; diff --git a/system/loggerd/tests/loggerd_tests_common.py b/system/loggerd/tests/loggerd_tests_common.py index 15fd997eb84f3a..fd071486dffc63 100644 --- a/system/loggerd/tests/loggerd_tests_common.py +++ b/system/loggerd/tests/loggerd_tests_common.py @@ -10,7 +10,7 @@ from openpilot.system.loggerd.xattr_cache import setxattr -def create_random_file(file_path: Path, size_mb: float, lock: bool = False, upload_xattr: bytes = None) -> None: +def create_random_file(file_path: Path, size_mb: float, lock: bool = False, upload_xattr: bytes | None = None) -> None: file_path.parent.mkdir(parents=True, exist_ok=True) if lock: @@ -76,11 +76,11 @@ def setup_method(self): self.seg_dir = self.seg_format.format(self.seg_num) self.params = Params() - self.params.put("IsOffroad", "1") - self.params.put("DongleId", "0000000000000000") + self.params.put("IsOffroad", True, block=True) + self.params.put("DongleId", "0000000000000000", block=True) def make_file_with_data(self, f_dir: str, fn: str, size_mb: float = .1, lock: bool = False, - upload_xattr: bytes = None, preserve_xattr: bytes = None) -> Path: + upload_xattr: bytes | None = None, preserve_xattr: bytes | None = None) -> Path: file_path = Path(Paths.log_root()) / f_dir / fn create_random_file(file_path, size_mb, lock, upload_xattr) diff --git a/system/loggerd/tests/test_encoder.py b/system/loggerd/tests/test_encoder.py index 75862a9d457969..2b74fe2276bdc0 100644 --- a/system/loggerd/tests/test_encoder.py +++ b/system/loggerd/tests/test_encoder.py @@ -7,7 +7,7 @@ import time from pathlib import Path -from parameterized import parameterized +from openpilot.common.parameterized import parameterized from tqdm import trange from openpilot.common.params import Params @@ -19,11 +19,12 @@ SEGMENT_LENGTH = 2 FULL_SIZE = 2507572 +def hevc_size(w): return FULL_SIZE // 2 if w <= 1344 else FULL_SIZE CAMERAS = [ - ("fcamera.hevc", 20, FULL_SIZE, "roadEncodeIdx"), - ("dcamera.hevc", 20, FULL_SIZE, "driverEncodeIdx"), - ("ecamera.hevc", 20, FULL_SIZE, "wideRoadEncodeIdx"), - ("qcamera.ts", 20, 130000, None), + ("fcamera.hevc", 20, hevc_size, "roadEncodeIdx"), + ("dcamera.hevc", 20, hevc_size, "driverEncodeIdx"), + ("ecamera.hevc", 20, hevc_size, "wideRoadEncodeIdx"), + ("qcamera.ts", 20, lambda x: 130000, None), ] # we check frame count, so we don't have to be too strict on size @@ -52,7 +53,7 @@ def _get_latest_segment_path(self): # TODO: this should run faster than real time @parameterized.expand([(True, ), (False, )]) def test_log_rotation(self, record_front): - Params().put_bool("RecordFront", record_front) + Params().put_bool("RecordFront", record_front, block=True) managed_processes['sensord'].start() managed_processes['loggerd'].start() @@ -61,7 +62,7 @@ def test_log_rotation(self, record_front): time.sleep(1.0) managed_processes['camerad'].start() - num_segments = int(os.getenv("SEGMENTS", random.randint(10, 15))) + num_segments = int(os.getenv("SEGMENTS", random.randint(2, 8))) # wait for loggerd to make the dir for first segment route_prefix_path = None @@ -76,7 +77,7 @@ def check_seg(i): # check each camera file size counts = [] first_frames = [] - for camera, fps, size, encode_idx_name in CAMERAS: + for camera, fps, size_lambda, encode_idx_name in CAMERAS: if not record_front and "dcamera" in camera: continue @@ -86,14 +87,14 @@ def check_seg(i): assert os.path.exists(file_path), f"segment #{i}: '{file_path}' missing" # TODO: this ffprobe call is really slow - # check frame count - cmd = f"ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=nb_read_packets -of csv=p=0 {file_path}" + # get width and check frame count + cmd = f"ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=nb_read_packets,width -of csv=p=0 {file_path}" if TICI: cmd = "LD_LIBRARY_PATH=/usr/local/lib " + cmd expected_frames = fps * SEGMENT_LENGTH - probe = subprocess.check_output(cmd, shell=True, encoding='utf8') - frame_count = int(probe.split('\n')[0].strip()) + probe = subprocess.check_output(cmd, shell=True, encoding='utf8').split('\n')[0].strip().split(',') + frame_width, frame_count = int(probe[0]), int(probe[1]) counts.append(frame_count) assert frame_count == expected_frames, \ @@ -101,12 +102,13 @@ def check_seg(i): # sanity check file size file_size = os.path.getsize(file_path) - assert math.isclose(file_size, size, rel_tol=FILE_SIZE_TOLERANCE), \ - f"{file_path} size {file_size} isn't close to target size {size}" + target_size = size_lambda(frame_width) + assert math.isclose(file_size, target_size, rel_tol=FILE_SIZE_TOLERANCE), \ + f"{file_path} size {file_size} isn't close to target size {target_size}" # Check encodeIdx if encode_idx_name is not None: - rlog_path = f"{route_prefix_path}--{i}/rlog" + rlog_path = f"{route_prefix_path}--{i}/rlog.zst" msgs = [m for m in LogReader(rlog_path) if m.which() == encode_idx_name] encode_msgs = [getattr(m, encode_idx_name) for m in msgs] diff --git a/system/loggerd/tests/test_logger.cc b/system/loggerd/tests/test_logger.cc index 2dae136e13c0bc..61509c256c9f64 100644 --- a/system/loggerd/tests/test_logger.cc +++ b/system/loggerd/tests/test_logger.cc @@ -9,12 +9,13 @@ void verify_segment(const std::string &route_path, int segment, int max_segment, SentinelType end_sentinel = segment == max_segment - 1 ? SentinelType::END_OF_ROUTE : SentinelType::END_OF_SEGMENT; REQUIRE(!util::file_exists(segment_path + "/rlog.lock")); - for (const char *fn : {"/rlog", "/qlog"}) { + for (const char *fn : {"/rlog.zst", "/qlog.zst"}) { const std::string log_file = segment_path + fn; std::string log = util::read_file(log_file); REQUIRE(!log.empty()); + std::string decompressed_log = zstd_decompress(log); int event_cnt = 0, i = 0; - kj::ArrayPtr words((capnp::word *)log.data(), log.size() / sizeof(capnp::word)); + kj::ArrayPtr words((capnp::word *)decompressed_log.data(), decompressed_log.size() / sizeof(capnp::word)); while (words.size() > 0) { try { capnp::FlatArrayMessageReader reader(words); @@ -55,7 +56,7 @@ void write_msg(LoggerState *logger) { TEST_CASE("logger") { const int segment_cnt = 100; const std::string log_root = "/tmp/test_logger"; - system(("rm " + log_root + " -rf").c_str()); + REQUIRE(system(("rm " + log_root + " -rf").c_str()) == 0); std::string route_name; { LoggerState logger(log_root); diff --git a/system/loggerd/tests/test_loggerd.py b/system/loggerd/tests/test_loggerd.py index cfd12477029b81..9fd1b2d4343f74 100644 --- a/system/loggerd/tests/test_loggerd.py +++ b/system/loggerd/tests/test_loggerd.py @@ -16,6 +16,7 @@ from openpilot.common.params import Params from openpilot.common.timeout import Timeout from openpilot.system.hardware.hw import Paths +from openpilot.system.hardware import TICI from openpilot.system.loggerd.xattr_cache import getxattr from openpilot.system.loggerd.deleter import PRESERVE_ATTR_NAME, PRESERVE_ATTR_VALUE from openpilot.system.manager.process_config import managed_processes @@ -23,7 +24,6 @@ from openpilot.tools.lib.helpers import RE from openpilot.tools.lib.logreader import LogReader from msgq.visionipc import VisionIpcServer, VisionStreamType -from openpilot.common.transformations.camera import DEVICE_CAMERAS SentinelType = log.Sentinel.SentinelType @@ -82,7 +82,7 @@ def _publish_random_messages(self, services: list[str]) -> dict[str, list]: assert pm.wait_for_readers_to_update(s, timeout=5) sent_msgs = defaultdict(list) - for _ in range(random.randint(2, 10) * 100): + for i in range(random.randint(2, 10) * 100): for s in services: try: m = messaging.new_message(s) @@ -91,12 +91,68 @@ def _publish_random_messages(self, services: list[str]) -> dict[str, list]: pm.send(s, m) sent_msgs[s].append(m) + # Keep msgq's finite per-service queues from wrapping; this test asserts + # that loggerd logged every message we sent. + if (i + 1) % 100 == 0: + for s in services: + assert pm.wait_for_readers_to_update(s, timeout=5) + for s in services: assert pm.wait_for_readers_to_update(s, timeout=5) managed_processes["loggerd"].stop() return sent_msgs + def _publish_camera_and_audio_messages(self, num_segs=1, segment_length=5): + # Use small frame sizes for testing (width, height, size, stride, uv_offset) + # NV12 format: size = stride * height * 1.5, uv_offset = stride * height + w, h = 320, 240 + frame_spec = (w, h, w * h * 3 // 2, w, w * h) + streams = [ + (VisionStreamType.VISION_STREAM_ROAD, frame_spec, "roadCameraState"), + (VisionStreamType.VISION_STREAM_DRIVER, frame_spec, "driverCameraState"), + (VisionStreamType.VISION_STREAM_WIDE_ROAD, frame_spec, "wideRoadCameraState"), + ] + + sm = messaging.SubMaster(["roadEncodeData"]) + pm = messaging.PubMaster([s for _, _, s in streams] + ["rawAudioData"]) + vipc_server = VisionIpcServer("camerad") + for stream_type, frame_spec, _ in streams: + vipc_server.create_buffers_with_sizes(stream_type, 40, *(frame_spec)) + vipc_server.start_listener() + + os.environ["LOGGERD_TEST"] = "1" + os.environ["LOGGERD_SEGMENT_LENGTH"] = str(segment_length) + managed_processes["loggerd"].start() + managed_processes["encoderd"].start() + assert pm.wait_for_readers_to_update("roadCameraState", timeout=5) + + fps = 20 + for n in range(1, int(num_segs * segment_length * fps) + 1): + # send video + for stream_type, frame_spec, state in streams: + dat = np.empty(frame_spec[2], dtype=np.uint8) + vipc_server.send(stream_type, dat[:].flatten().tobytes(), n, n / fps, n / fps) + + camera_state = messaging.new_message(state) + frame = getattr(camera_state, state) + frame.frameId = n + pm.send(state, camera_state) + + # send audio + msg = messaging.new_message('rawAudioData') + msg.rawAudioData.data = bytes(800 * 2) # 800 samples of int16 + msg.rawAudioData.sampleRate = 16000 + pm.send('rawAudioData', msg) + + for _, _, state in streams: + assert pm.wait_for_readers_to_update(state, timeout=5, dt=0.001) + + sm.update(100) # wait for encode data publish + + managed_processes["loggerd"].stop() + managed_processes["encoderd"].stop() + def test_init_data_values(self): os.environ["CLEAN"] = random.choice(["0", "1"]) @@ -111,8 +167,8 @@ def test_init_data_values(self): ] params = Params() for k, _, v in fake_params: - params.put(k, v) - params.put("AccessToken", "abc") + params.put(k, v, block=True) + params.put("AccessToken", "abc", block=True) lr = list(LogReader(str(self._gen_bootlog()))) initData = lr[0].initData @@ -136,53 +192,23 @@ def test_init_data_values(self): assert getattr(initData, initData_key) == v assert logged_params[param_key].decode() == v - @pytest.mark.skip("FIXME: encoderd sometimes crashes in CI when running with pytest-xdist") + @pytest.mark.xdist_group("camera_encoder_tests") # setting xdist group ensures tests are run in same worker, prevents encoderd from crashing def test_rotation(self): - os.environ["LOGGERD_TEST"] = "1" - Params().put("RecordFront", "1") + Params().put("RecordFront", True, block=True) - d = DEVICE_CAMERAS[("tici", "ar0231")] - expected_files = {"rlog", "qlog", "qcamera.ts", "fcamera.hevc", "dcamera.hevc", "ecamera.hevc"} - streams = [(VisionStreamType.VISION_STREAM_ROAD, (d.fcam.width, d.fcam.height, 2048*2346, 2048, 2048*1216), "roadCameraState"), - (VisionStreamType.VISION_STREAM_DRIVER, (d.dcam.width, d.dcam.height, 2048*2346, 2048, 2048*1216), "driverCameraState"), - (VisionStreamType.VISION_STREAM_WIDE_ROAD, (d.ecam.width, d.ecam.height, 2048*2346, 2048, 2048*1216), "wideRoadCameraState")] + expected_files = {"rlog.zst", "qlog.zst", "qcamera.ts", "fcamera.hevc", "dcamera.hevc", "ecamera.hevc"} - pm = messaging.PubMaster(["roadCameraState", "driverCameraState", "wideRoadCameraState"]) - vipc_server = VisionIpcServer("camerad") - for stream_type, frame_spec, _ in streams: - vipc_server.create_buffers_with_sizes(stream_type, 40, False, *(frame_spec)) - vipc_server.start_listener() + num_segs = random.randint(2, 3) + length = random.randint(4, 5) # H264 encoder uses 40 lookahead frames and does B-frame reordering, so minimum 3 seconds before qcam output - num_segs = random.randint(2, 5) - length = random.randint(1, 3) - os.environ["LOGGERD_SEGMENT_LENGTH"] = str(length) - managed_processes["loggerd"].start() - managed_processes["encoderd"].start() - assert pm.wait_for_readers_to_update("roadCameraState", timeout=5) - - fps = 20.0 - for n in range(1, int(num_segs*length*fps)+1): - for stream_type, frame_spec, state in streams: - dat = np.empty(frame_spec[2], dtype=np.uint8) - vipc_server.send(stream_type, dat[:].flatten().tobytes(), n, n/fps, n/fps) - - camera_state = messaging.new_message(state) - frame = getattr(camera_state, state) - frame.frameId = n - pm.send(state, camera_state) - - for _, _, state in streams: - assert pm.wait_for_readers_to_update(state, timeout=5, dt=0.001) - - managed_processes["loggerd"].stop() - managed_processes["encoderd"].stop() + self._publish_camera_and_audio_messages(num_segs=num_segs, segment_length=length) route_path = str(self._get_latest_log_dir()).rsplit("--", 1)[0] for n in range(num_segs): p = Path(f"{route_path}--{n}") logged = {f.name for f in p.iterdir() if f.is_file()} diff = logged ^ expected_files - assert len(diff) == 0, f"didn't get all expected files. run={_} seg={n} {route_path=}, {diff=}\n{logged=} {expected_files=}" + assert len(diff) == 0, f"didn't get all expected files. seg={n} {route_path=}, {diff=}\n{logged=} {expected_files=}" def test_bootlog(self): # generate bootlog with fake launch log @@ -207,13 +233,16 @@ def test_bootlog(self): assert abs(boot.wallTimeNanos - time.time_ns()) < 5*1e9 # within 5s assert boot.launchLog == launch_log - for fn in ["console-ramoops", "pmsg-ramoops-0"]: - path = Path(os.path.join("/sys/fs/pstore/", fn)) - if path.is_file(): - with open(path, "rb") as f: - expected_val = f.read() - bootlog_val = [e.value for e in boot.pstore.entries if e.key == fn][0] - assert expected_val == bootlog_val + if TICI: + for fn in ["console-ramoops", "pmsg-ramoops-0"]: + path = Path(os.path.join("/sys/fs/pstore/", fn)) + if path.is_file(): + with open(path, "rb") as f: + expected_val = f.read() + bootlog_val = [e.value for e in boot.pstore.entries if e.key == fn][0] + assert expected_val == bootlog_val + else: + assert len(boot.pstore.entries) == 0 # next one should increment by one bl1 = re.match(RE.LOG_ID_V2, bootlog_path.name) @@ -229,7 +258,7 @@ def test_qlog(self): random.sample(no_qlog_services, random.randint(2, min(10, len(no_qlog_services)))) sent_msgs = self._publish_random_messages(services) - qlog_path = os.path.join(self._get_latest_log_dir(), "qlog") + qlog_path = os.path.join(self._get_latest_log_dir(), "qlog.zst") lr = list(LogReader(qlog_path)) # check initData and sentinel @@ -255,7 +284,7 @@ def test_rlog(self): services = random.sample(CEREAL_SERVICES, random.randint(5, 10)) sent_msgs = self._publish_random_messages(services) - lr = list(LogReader(os.path.join(self._get_latest_log_dir(), "rlog"))) + lr = list(LogReader(os.path.join(self._get_latest_log_dir(), "rlog.zst"))) # check initData and sentinel self._check_init_data(lr) @@ -268,17 +297,43 @@ def test_rlog(self): sent.clear_write_flag() assert sent.to_bytes() == m.as_builder().to_bytes() - def test_preserving_flagged_segments(self): - services = set(random.sample(CEREAL_SERVICES, random.randint(5, 10))) | {"userFlag"} + def test_preserving_bookmarked_segments(self): + services = set(random.sample(CEREAL_SERVICES, random.randint(5, 10))) | {"userBookmark"} self._publish_random_messages(services) segment_dir = self._get_latest_log_dir() assert getxattr(segment_dir, PRESERVE_ATTR_NAME) == PRESERVE_ATTR_VALUE - def test_not_preserving_unflagged_segments(self): - services = set(random.sample(CEREAL_SERVICES, random.randint(5, 10))) - {"userFlag"} + def test_not_preserving_nonbookmarked_segments(self): + services = set(random.sample(CEREAL_SERVICES, random.randint(5, 10))) - {"userBookmark", "audioFeedback"} self._publish_random_messages(services) segment_dir = self._get_latest_log_dir() assert getxattr(segment_dir, PRESERVE_ATTR_NAME) is None + @pytest.mark.xdist_group("camera_encoder_tests") # setting xdist group ensures tests are run in same worker, prevents encoderd from crashing + @pytest.mark.parametrize("record_front", [True, False]) + def test_record_front(self, record_front): + params = Params() + params.put_bool("RecordFront", record_front, block=True) + + self._publish_camera_and_audio_messages() + + dcamera_hevc_exists = os.path.exists(os.path.join(self._get_latest_log_dir(), 'dcamera.hevc')) + assert dcamera_hevc_exists == record_front + + @pytest.mark.xdist_group("camera_encoder_tests") # setting xdist group ensures tests are run in same worker, prevents encoderd from crashing + @pytest.mark.parametrize("record_audio", [True, False]) + def test_record_audio(self, record_audio): + params = Params() + params.put_bool("RecordAudio", record_audio, block=True) + + self._publish_camera_and_audio_messages() + + qcamera_ts_path = os.path.join(self._get_latest_log_dir(), 'qcamera.ts') + ffprobe_cmd = f"ffprobe -i {qcamera_ts_path} -show_streams -select_streams a -loglevel error" + has_audio_stream = subprocess.run(ffprobe_cmd, shell=True, capture_output=True).stdout.strip() != b'' + assert has_audio_stream == record_audio + + raw_audio_in_rlog = any(m.which() == 'rawAudioData' for m in LogReader(os.path.join(self._get_latest_log_dir(), 'rlog.zst'))) + assert raw_audio_in_rlog == record_audio diff --git a/system/loggerd/tests/test_uploader.py b/system/loggerd/tests/test_uploader.py index fa716002635a08..562bc068eb80e8 100644 --- a/system/loggerd/tests/test_uploader.py +++ b/system/loggerd/tests/test_uploader.py @@ -50,7 +50,7 @@ def join_thread(self): self.end_event.set() self.up_thread.join() - def gen_files(self, lock=False, xattr: bytes = None, boot=True) -> list[Path]: + def gen_files(self, lock=False, xattr: bytes | None = None, boot=True) -> list[Path]: f_paths = [] for t in ["qlog", "rlog", "dcamera.hevc", "fcamera.hevc"]: f_paths.append(self.make_file_with_data(self.seg_dir, t, 1, lock=lock, upload_xattr=xattr)) @@ -73,7 +73,7 @@ def test_upload(self): self.start_thread() # allow enough time that files could upload twice if there is a bug in the logic - time.sleep(5) + time.sleep(1) self.join_thread() exp_order = self.gen_order([self.seg_num], []) @@ -91,7 +91,7 @@ def test_upload_with_wrong_xattr(self): self.start_thread() # allow enough time that files could upload twice if there is a bug in the logic - time.sleep(5) + time.sleep(1) self.join_thread() exp_order = self.gen_order([self.seg_num], []) @@ -110,7 +110,7 @@ def test_upload_ignored(self): self.start_thread() # allow enough time that files could upload twice if there is a bug in the logic - time.sleep(5) + time.sleep(1) self.join_thread() exp_order = self.gen_order([self.seg_num], []) @@ -137,7 +137,7 @@ def test_upload_files_in_create_order(self): self.start_thread() # allow enough time that files could upload twice if there is a bug in the logic - time.sleep(5) + time.sleep(1) self.join_thread() assert len(log_handler.upload_ignored) == 0, "Some files were ignored" @@ -155,7 +155,7 @@ def test_no_upload_with_lock_file(self): f_paths = self.gen_files(lock=True, boot=False) # allow enough time that files should have been uploaded if they would be uploaded - time.sleep(5) + time.sleep(1) self.join_thread() for f_path in f_paths: @@ -168,7 +168,7 @@ def test_no_upload_with_xattr(self): self.start_thread() # allow enough time that files could upload twice if there is a bug in the logic - time.sleep(5) + time.sleep(1) self.join_thread() assert len(log_handler.upload_order) == 0, "File uploaded again" @@ -176,7 +176,7 @@ def test_no_upload_with_xattr(self): def test_clear_locks_on_startup(self): f_paths = self.gen_files(lock=True, boot=False) self.start_thread() - time.sleep(1) + time.sleep(0.25) self.join_thread() for f_path in f_paths: diff --git a/system/loggerd/tests/test_zstd_writer.cc b/system/loggerd/tests/test_zstd_writer.cc new file mode 100644 index 00000000000000..479e866a14ac99 --- /dev/null +++ b/system/loggerd/tests/test_zstd_writer.cc @@ -0,0 +1,44 @@ +#include + +#include +#include +#include + +#include "common/util.h" +#include "system/loggerd/logger.h" +#include "system/loggerd/zstd_writer.h" + +TEST_CASE("ZstdFileWriter writes and compresses data correctly in loops", "[ZstdFileWriter]") { + const std::string filename = "test_zstd_file.zst"; + const int iterations = 100; + const size_t dataSize = 1024; + + std::string totalTestData; + + // Step 1: Write compressed data to file in a loop + { + ZstdFileWriter writer(filename, LOG_COMPRESSION_LEVEL); + // Write various data sizes including edge cases + std::vector testSizes = {dataSize, 1, 0, dataSize * 2}; // Normal, minimal, empty, large + for (int i = 0; i < iterations; ++i) { + size_t currentSize = testSizes[i % testSizes.size()]; + std::string testData = util::random_string(currentSize); + totalTestData.append(testData); + + writer.write((void *)testData.c_str(), testData.size()); + } + } + + // Step 2: Decompress the file and verify the data + auto compressedContent = util::read_file(filename); + REQUIRE(compressedContent.size() > 0); + REQUIRE(compressedContent.size() < totalTestData.size()); + std::string decompressedData = zstd_decompress(compressedContent); + + // Step 3: Verify that the decompressed data matches the original accumulated data + REQUIRE(decompressedData.size() == totalTestData.size()); + REQUIRE(std::memcmp(decompressedData.data(), totalTestData.c_str(), totalTestData.size()) == 0); + + // Clean up the test file + std::remove(filename.c_str()); +} diff --git a/system/loggerd/tests/vidc_debug.sh b/system/loggerd/tests/vidc_debug.sh new file mode 100755 index 00000000000000..7471f2ab082cbe --- /dev/null +++ b/system/loggerd/tests/vidc_debug.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -e + +cd /sys/kernel/debug/tracing +echo "" > trace +echo 1 > tracing_on +echo 1 > /sys/kernel/debug/tracing/events/msm_vidc/enable + +echo 0xff > /sys/module/videobuf2_core/parameters/debug +echo 0x7fffffff > /sys/kernel/debug/msm_vidc/debug_level +echo 0xff > /sys/devices/platform/soc/aa00000.qcom,vidc/video4linux/video33/dev_debug + +cat /sys/kernel/debug/tracing/trace_pipe diff --git a/system/loggerd/uploader.py b/system/loggerd/uploader.py index 965d74bef8653d..8ac38b6df6a76d 100755 --- a/system/loggerd/uploader.py +++ b/system/loggerd/uploader.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -import io import json import os import random @@ -8,12 +7,12 @@ import time import traceback import datetime -import zstandard as zstd from collections.abc import Iterator from cereal import log import cereal.messaging as messaging from openpilot.common.api import Api +from openpilot.common.utils import get_upload_stream from openpilot.common.params import Params from openpilot.common.realtime import set_core_affinity from openpilot.system.hardware.hw import Paths @@ -24,10 +23,13 @@ UPLOAD_ATTR_NAME = 'user.upload' UPLOAD_ATTR_VALUE = b'1' -UPLOAD_QLOG_QCAM_MAX_SIZE = 5 * 1e6 # MB -LOG_COMPRESSION_LEVEL = 10 # little benefit up to level 15. level ~17 is a small step change +MAX_UPLOAD_SIZES = { + "qlog": 25*1e6, # can't be too restrictive here since we use qlogs to find + # bugs, including ones that can cause massive log sizes + "qcam": 5*1e6, +} -allow_sleep = bool(os.getenv("UPLOADER_SLEEP", "1")) +allow_sleep = bool(int(os.getenv("UPLOADER_SLEEP", "1"))) force_wifi = os.getenv("FORCEWIFI") is not None fake_upload = os.getenv("FAKEUPLOAD") is not None @@ -86,8 +88,8 @@ def __init__(self, dongle_id: str, root: str): self.immediate_priority = {"qlog": 0, "qlog.zst": 0, "qcamera.ts": 1} def list_upload_files(self, metered: bool) -> Iterator[tuple[str, str, str]]: - r = self.params.get("AthenadRecentlyViewedRoutes", encoding="utf8") - requested_routes = [] if r is None else r.split(",") + r = self.params.get("AthenadRecentlyViewedRoutes") + requested_routes = [] if r is None else [route for route in r.split(",") if route] for logdir in listdir_by_creation(self.root): path = os.path.join(self.root, logdir) @@ -150,13 +152,15 @@ def do_upload(self, key: str, fn: str): if fake_upload: return FakeResponse() - with open(fn, "rb") as f: - content = f.read() - if key.endswith('.zst') and not fn.endswith('.zst'): - content = zstd.compress(content, LOG_COMPRESSION_LEVEL) - - with io.BytesIO(content) as data: - return requests.put(url, data=data, headers=headers, timeout=10) + stream = None + try: + compress = key.endswith('.zst') and not fn.endswith('.zst') + stream, _ = get_upload_stream(fn, compress) + response = requests.put(url, data=stream, headers=headers, timeout=10) + return response + finally: + if stream: + stream.close() def upload(self, name: str, key: str, fn: str, network_type: int, metered: bool) -> bool: try: @@ -170,7 +174,7 @@ def upload(self, name: str, key: str, fn: str, network_type: int, metered: bool) if sz == 0: # tag files of 0 size as uploaded success = True - elif name in self.immediate_priority and sz > UPLOAD_QLOG_QCAM_MAX_SIZE: + elif name in MAX_UPLOAD_SIZES and sz > MAX_UPLOAD_SIZES[name]: cloudlog.event("uploader_too_large", key=key, fn=fn, sz=sz) success = True else: @@ -222,7 +226,7 @@ def step(self, network_type: int, metered: bool) -> bool | None: return self.upload(name, key, fn, network_type, metered) -def main(exit_event: threading.Event = None) -> None: +def main(exit_event: threading.Event | None = None) -> None: if exit_event is None: exit_event = threading.Event() @@ -234,7 +238,7 @@ def main(exit_event: threading.Event = None) -> None: clear_locks(Paths.log_root()) params = Params() - dongle_id = params.get("DongleId", encoding='utf8') + dongle_id = params.get("DongleId") if dongle_id is None: cloudlog.info("uploader missing dongle_id") diff --git a/system/loggerd/video_writer.cc b/system/loggerd/video_writer.cc index 90b5f1af3d1b94..1b47a8fceba613 100644 --- a/system/loggerd/video_writer.cc +++ b/system/loggerd/video_writer.cc @@ -1,4 +1,3 @@ -#pragma clang diagnostic ignored "-Wdeprecated-declarations" #include #include "system/loggerd/video_writer.h" @@ -50,6 +49,45 @@ VideoWriter::VideoWriter(const char *path, const char *filename, bool remuxing, } } +void VideoWriter::initialize_audio(int sample_rate) { + assert(this->ofmt_ctx->oformat->audio_codec != AV_CODEC_ID_NONE); // check output format supports audio streams + const AVCodec *audio_avcodec = avcodec_find_encoder(AV_CODEC_ID_AAC); + assert(audio_avcodec); + this->audio_codec_ctx = avcodec_alloc_context3(audio_avcodec); + assert(this->audio_codec_ctx); + this->audio_codec_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP; + this->audio_codec_ctx->sample_rate = sample_rate; + #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1+ + av_channel_layout_default(&this->audio_codec_ctx->ch_layout, 1); + #else + this->audio_codec_ctx->channel_layout = AV_CH_LAYOUT_MONO; + #endif + this->audio_codec_ctx->bit_rate = 32000; + this->audio_codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + this->audio_codec_ctx->time_base = (AVRational){1, audio_codec_ctx->sample_rate}; + int err = avcodec_open2(this->audio_codec_ctx, audio_avcodec, NULL); + assert(err >= 0); + av_log_set_level(AV_LOG_WARNING); // hide "QAvg" info msgs at the end of every segment + + this->audio_stream = avformat_new_stream(this->ofmt_ctx, NULL); + assert(this->audio_stream); + err = avcodec_parameters_from_context(this->audio_stream->codecpar, this->audio_codec_ctx); + assert(err >= 0); + + this->audio_frame = av_frame_alloc(); + assert(this->audio_frame); + this->audio_frame->format = this->audio_codec_ctx->sample_fmt; + #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1+ + av_channel_layout_copy(&this->audio_frame->ch_layout, &this->audio_codec_ctx->ch_layout); + #else + this->audio_frame->channel_layout = this->audio_codec_ctx->channel_layout; + #endif + this->audio_frame->sample_rate = this->audio_codec_ctx->sample_rate; + this->audio_frame->nb_samples = this->audio_codec_ctx->frame_size; + err = av_frame_get_buffer(this->audio_frame, 0); + assert(err >= 0); +} + void VideoWriter::write(uint8_t *data, int len, long long timestamp, bool codecconfig, bool keyframe) { if (of && data) { size_t written = util::safe_fwrite(data, 1, len, of); @@ -67,16 +105,18 @@ void VideoWriter::write(uint8_t *data, int len, long long timestamp, bool codecc } int err = avcodec_parameters_from_context(out_stream->codecpar, codec_ctx); assert(err >= 0); + // if there is an audio stream, it must be initialized before this point err = avformat_write_header(ofmt_ctx, NULL); assert(err >= 0); + header_written = true; } else { // input timestamps are in microseconds AVRational in_timebase = {1, 1000000}; - AVPacket pkt; - av_init_packet(&pkt); + AVPacket pkt = {}; pkt.data = data; pkt.size = len; + pkt.stream_index = this->out_stream->index; enum AVRounding rnd = static_cast(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); pkt.pts = pkt.dts = av_rescale_q_rnd(timestamp, in_timebase, ofmt_ctx->streams[0]->time_base, rnd); @@ -95,11 +135,93 @@ void VideoWriter::write(uint8_t *data, int len, long long timestamp, bool codecc } } +void VideoWriter::write_audio(uint8_t *data, int len, long long timestamp, int sample_rate) { + if (!remuxing) return; + if (!audio_initialized) { + initialize_audio(sample_rate); + audio_initialized = true; + } + if (!audio_codec_ctx) return; + // sync logMonoTime of first audio packet with the timestampEof of first video packet + if (audio_pts == 0) { + audio_pts = (timestamp * audio_codec_ctx->sample_rate) / 1000000ULL; + } + + // convert s16le samples to fltp and add to buffer + const int16_t *raw_samples = reinterpret_cast(data); + int sample_count = len / sizeof(int16_t); + constexpr float normalizer = 1.0f / 32768.0f; + + const size_t max_buffer_size = sample_rate * 10; // 10 seconds + if (audio_buffer.size() + sample_count > max_buffer_size) { + size_t samples_to_drop = (audio_buffer.size() + sample_count) - max_buffer_size; + LOGE("Audio buffer overflow, dropping %zu oldest samples", samples_to_drop); + audio_buffer.erase(audio_buffer.begin(), audio_buffer.begin() + samples_to_drop); + audio_pts += samples_to_drop; + } + + // Add new samples to the buffer + const size_t original_size = audio_buffer.size(); + audio_buffer.resize(original_size + sample_count); + std::transform(raw_samples, raw_samples + sample_count, audio_buffer.begin() + original_size, + [](int16_t sample) { return sample * normalizer; }); + + if (!header_written) return; // header not written yet, process audio frame after header is written + while (audio_buffer.size() >= audio_codec_ctx->frame_size) { + audio_frame->pts = audio_pts; + float *f_samples = reinterpret_cast(audio_frame->data[0]); + std::copy(audio_buffer.begin(), audio_buffer.begin() + audio_codec_ctx->frame_size, f_samples); + audio_buffer.erase(audio_buffer.begin(), audio_buffer.begin() + audio_codec_ctx->frame_size); + encode_and_write_audio_frame(audio_frame); + } +} + +void VideoWriter::encode_and_write_audio_frame(AVFrame* frame) { + if (!remuxing || !audio_codec_ctx) return; + int send_result = avcodec_send_frame(audio_codec_ctx, frame); // encode frame + if (send_result >= 0) { + AVPacket *pkt = av_packet_alloc(); + while (avcodec_receive_packet(audio_codec_ctx, pkt) == 0) { + av_packet_rescale_ts(pkt, audio_codec_ctx->time_base, audio_stream->time_base); + pkt->stream_index = audio_stream->index; + + int err = av_interleaved_write_frame(ofmt_ctx, pkt); // write encoded frame + if (err < 0) { + LOGW("AUDIO: Write frame failed - error: %d", err); + } + av_packet_unref(pkt); + } + av_packet_free(&pkt); + } else { + LOGW("AUDIO: Failed to send audio frame to encoder: %d", send_result); + } + audio_pts += audio_codec_ctx->frame_size; +} + +void VideoWriter::process_remaining_audio() { + // Process remaining audio samples by padding with silence + if (audio_buffer.size() > 0 && audio_buffer.size() < audio_codec_ctx->frame_size) { + audio_buffer.resize(audio_codec_ctx->frame_size, 0.0f); + + // Encode final frame + audio_frame->pts = audio_pts; + float *f_samples = reinterpret_cast(audio_frame->data[0]); + std::copy(audio_buffer.begin(), audio_buffer.end(), f_samples); + encode_and_write_audio_frame(audio_frame); + } +} + VideoWriter::~VideoWriter() { if (this->remuxing) { + if (this->audio_codec_ctx) { + process_remaining_audio(); + encode_and_write_audio_frame(NULL); // flush encoder + avcodec_free_context(&this->audio_codec_ctx); + } int err = av_write_trailer(this->ofmt_ctx); if (err != 0) LOGE("av_write_trailer failed %d", err); avcodec_free_context(&this->codec_ctx); + if (this->audio_frame) av_frame_free(&this->audio_frame); err = avio_closep(&this->ofmt_ctx->pb); if (err != 0) LOGE("avio_closep failed %d", err); avformat_free_context(this->ofmt_ctx); diff --git a/system/loggerd/video_writer.h b/system/loggerd/video_writer.h index 1aa758b42b78b0..e973c5d8114d58 100644 --- a/system/loggerd/video_writer.h +++ b/system/loggerd/video_writer.h @@ -1,6 +1,7 @@ #pragma once #include +#include extern "C" { #include @@ -13,13 +14,29 @@ class VideoWriter { public: VideoWriter(const char *path, const char *filename, bool remuxing, int width, int height, int fps, cereal::EncodeIndex::Type codec); void write(uint8_t *data, int len, long long timestamp, bool codecconfig, bool keyframe); + void write_audio(uint8_t *data, int len, long long timestamp, int sample_rate); + ~VideoWriter(); + private: + void initialize_audio(int sample_rate); + void encode_and_write_audio_frame(AVFrame* frame); + void process_remaining_audio(); + std::string vid_path, lock_path; FILE *of = nullptr; AVCodecContext *codec_ctx; AVFormatContext *ofmt_ctx; AVStream *out_stream; + + bool audio_initialized = false; + bool header_written = false; + AVStream *audio_stream = nullptr; + AVCodecContext *audio_codec_ctx = nullptr; + AVFrame *audio_frame = nullptr; + uint64_t audio_pts = 0; + std::deque audio_buffer; + bool remuxing; }; diff --git a/system/loggerd/xattr_cache.py b/system/loggerd/xattr_cache.py index d3220118ac6bca..39bb1720598cc4 100644 --- a/system/loggerd/xattr_cache.py +++ b/system/loggerd/xattr_cache.py @@ -1,16 +1,17 @@ -import os import errno +import xattr + _cached_attributes: dict[tuple, bytes | None] = {} def getxattr(path: str, attr_name: str) -> bytes | None: key = (path, attr_name) if key not in _cached_attributes: try: - response = os.getxattr(path, attr_name) + response = xattr.getxattr(path, attr_name) except OSError as e: - # ENODATA means attribute hasn't been set - if e.errno == errno.ENODATA: + # ENODATA (Linux) or ENOATTR (macOS) means attribute hasn't been set + if e.errno == errno.ENODATA or (hasattr(errno, 'ENOATTR') and e.errno == errno.ENOATTR): response = None else: raise @@ -19,4 +20,4 @@ def getxattr(path: str, attr_name: str) -> bytes | None: def setxattr(path: str, attr_name: str, attr_value: bytes) -> None: _cached_attributes.pop((path, attr_name), None) - return os.setxattr(path, attr_name, attr_value) + xattr.setxattr(path, attr_name, attr_value) diff --git a/system/loggerd/zstd_writer.cc b/system/loggerd/zstd_writer.cc new file mode 100644 index 00000000000000..69ca64479edf05 --- /dev/null +++ b/system/loggerd/zstd_writer.cc @@ -0,0 +1,65 @@ + +#include "system/loggerd/zstd_writer.h" + +#include + +#include "common/util.h" + +// Constructor: Initializes compression stream and opens file +ZstdFileWriter::ZstdFileWriter(const std::string& filename, int compression_level) { + // Create the compression stream + cstream_ = ZSTD_createCStream(); + assert(cstream_); + + size_t initResult = ZSTD_initCStream(cstream_, compression_level); + assert(!ZSTD_isError(initResult)); + + input_cache_capacity_ = ZSTD_CStreamInSize(); + input_cache_.reserve(input_cache_capacity_); + output_buffer_.resize(ZSTD_CStreamOutSize()); + + file_ = util::safe_fopen(filename.c_str(), "wb"); + assert(file_ != nullptr); +} + +// Destructor: Finalizes compression and closes file +ZstdFileWriter::~ZstdFileWriter() { + flushCache(true); + util::safe_fflush(file_); + + int err = fclose(file_); + assert(err == 0); + + ZSTD_freeCStream(cstream_); +} + +// Compresses and writes data to file +void ZstdFileWriter::write(void* data, size_t size) { + // Add data to the input cache + input_cache_.insert(input_cache_.end(), (uint8_t*)data, (uint8_t*)data + size); + + // If the cache is full, compress and write to the file + if (input_cache_.size() >= input_cache_capacity_) { + flushCache(false); + } +} + +// Compress and flush the input cache to the file +void ZstdFileWriter::flushCache(bool last_chunk) { + ZSTD_inBuffer input = {input_cache_.data(), input_cache_.size(), 0}; + ZSTD_EndDirective mode = !last_chunk ? ZSTD_e_continue : ZSTD_e_end; + int finished = 0; + + do { + ZSTD_outBuffer output = {output_buffer_.data(), output_buffer_.size(), 0}; + size_t remaining = ZSTD_compressStream2(cstream_, &output, &input, mode); + assert(!ZSTD_isError(remaining)); + + size_t written = util::safe_fwrite(output_buffer_.data(), 1, output.pos, file_); + assert(written == output.pos); + + finished = last_chunk ? (remaining == 0) : (input.pos == input.size); + } while (!finished); + + input_cache_.clear(); // Clear cache after compression +} diff --git a/system/loggerd/zstd_writer.h b/system/loggerd/zstd_writer.h new file mode 100644 index 00000000000000..b11deaab2055b5 --- /dev/null +++ b/system/loggerd/zstd_writer.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include +#include +#include + +class ZstdFileWriter { +public: + ZstdFileWriter(const std::string &filename, int compression_level); + ~ZstdFileWriter(); + void write(void* data, size_t size); + inline void write(kj::ArrayPtr array) { write(array.begin(), array.size()); } + +private: + void flushCache(bool last_chunk); + + size_t input_cache_capacity_ = 0; + std::vector input_cache_; + std::vector output_buffer_; + ZSTD_CStream *cstream_; + FILE* file_ = nullptr; +}; diff --git a/system/manager/build.py b/system/manager/build.py index 956336a604fdff..470cfccdaa706e 100755 --- a/system/manager/build.py +++ b/system/manager/build.py @@ -1,69 +1,58 @@ #!/usr/bin/env python3 import os import subprocess -from pathlib import Path # NOTE: Do NOT import anything here that needs be built (e.g. params) from openpilot.common.basedir import BASEDIR from openpilot.common.spinner import Spinner from openpilot.common.text_window import TextWindow -from openpilot.system.hardware import AGNOS -from openpilot.common.swaglog import cloudlog, add_file_handler -from openpilot.system.version import get_build_metadata +from openpilot.system.hardware import HARDWARE, AGNOS -MAX_CACHE_SIZE = 4e9 if "CI" in os.environ else 2e9 -CACHE_DIR = Path("/data/scons_cache" if AGNOS else "/tmp/scons_cache") - -TOTAL_SCONS_NODES = 2820 -MAX_BUILD_PROGRESS = 100 - -def build(spinner: Spinner, dirty: bool = False, minimal: bool = False) -> None: - env = os.environ.copy() - env['SCONS_PROGRESS'] = "1" - nproc = os.cpu_count() - if nproc is None: - nproc = 2 +def build() -> None: + spinner = Spinner() + spinner.update_progress(0, 100) - extra_args = ["--minimal"] if minimal else [] + HARDWARE.set_power_save(False) + if AGNOS: + os.sched_setaffinity(0, range(8)) # ensure we can use the isolcpus cores - # building with all cores can result in using too - # much memory, so retry with less parallelism + # building with all cores can result in using too much memory, so retry serially compile_output: list[bytes] = [] - for n in (nproc, nproc/2, 1): + for parallelism in ([], ["-j4"], ["-j1"]): compile_output.clear() - scons: subprocess.Popen = subprocess.Popen(["scons", f"-j{int(n)}", "--cache-populate", *extra_args], cwd=BASEDIR, env=env, stderr=subprocess.PIPE) - assert scons.stderr is not None + with subprocess.Popen(["scons", *parallelism], cwd=BASEDIR, env={**os.environ, "PWD": BASEDIR}, stderr=subprocess.PIPE) as scons: + assert scons.stderr is not None - # Read progress from stderr and update spinner - while scons.poll() is None: - try: - line = scons.stderr.readline() - if line is None: - continue - line = line.rstrip() + # Read progress from stderr and update spinner + while scons.poll() is None: + try: + line = scons.stderr.readline() + if line is None: + continue + line = line.rstrip() + + prefix = b'progress: ' + if line.startswith(prefix): + progress = float(line[len(prefix):]) + spinner.update_progress(100 * min(1., progress / 100.), 100.) + elif len(line): + compile_output.append(line) + print(line.decode('utf8', 'replace')) + except Exception: + pass - prefix = b'progress: ' - if line.startswith(prefix): - i = int(line[len(prefix):]) - spinner.update_progress(MAX_BUILD_PROGRESS * min(1., i / TOTAL_SCONS_NODES), 100.) - elif len(line): + # Drain and close the pipe before retrying or returning. + for line in scons.stderr.read().split(b'\n'): + line = line.rstrip() + if len(line): compile_output.append(line) - print(line.decode('utf8', 'replace')) - except Exception: - pass if scons.returncode == 0: break if scons.returncode != 0: - # Read remaining output - if scons.stderr is not None: - compile_output += scons.stderr.read().split(b'\n') - # Build failed log errors error_s = b"\n".join(compile_output).decode('utf8', 'replace') - add_file_handler(cloudlog) - cloudlog.error("scons build failed\n" + error_s) # Show TextWindow spinner.close() @@ -72,19 +61,5 @@ def build(spinner: Spinner, dirty: bool = False, minimal: bool = False) -> None: t.wait_for_exit() exit(1) - # enforce max cache size - cache_files = [f for f in CACHE_DIR.rglob('*') if f.is_file()] - cache_files.sort(key=lambda f: f.stat().st_mtime) - cache_size = sum(f.stat().st_size for f in cache_files) - for f in cache_files: - if cache_size < MAX_CACHE_SIZE: - break - cache_size -= f.stat().st_size - f.unlink() - - if __name__ == "__main__": - spinner = Spinner() - spinner.update_progress(0, 100) - build_metadata = get_build_metadata() - build(spinner, build_metadata.openpilot.is_dirty, minimal = AGNOS) + build() diff --git a/system/manager/helpers.py b/system/manager/helpers.py index 047d0ac2d6f881..6af4a799e428d9 100644 --- a/system/manager/helpers.py +++ b/system/manager/helpers.py @@ -46,8 +46,8 @@ def unblock_stdout() -> None: def write_onroad_params(started, params): - params.put_bool("IsOnroad", started) - params.put_bool("IsOffroad", not started) + params.put_bool("IsOnroad", started, block=True) + params.put_bool("IsOffroad", not started, block=True) def save_bootlog(): diff --git a/system/manager/manager.py b/system/manager/manager.py index 9ebbdf422def83..73d990e7e79df6 100755 --- a/system/manager/manager.py +++ b/system/manager/manager.py @@ -3,12 +3,14 @@ import os import signal import sys +import time import traceback from cereal import log import cereal.messaging as messaging import openpilot.system.sentry as sentry -from openpilot.common.params import Params, ParamKeyType +from openpilot.common.utils import atomic_write +from openpilot.common.params import Params, ParamKeyFlag from openpilot.common.text_window import TextWindow from openpilot.system.hardware import HARDWARE from openpilot.system.manager.helpers import unblock_stdout, write_onroad_params, save_bootlog @@ -17,7 +19,7 @@ from openpilot.system.athena.registration import register, UNREGISTERED_DONGLE_ID from openpilot.common.swaglog import cloudlog, add_file_handler from openpilot.system.version import get_build_metadata, terms_version, training_version - +from openpilot.system.hardware.hw import Paths def manager_init() -> None: @@ -26,55 +28,52 @@ def manager_init() -> None: build_metadata = get_build_metadata() params = Params() - params.clear_all(ParamKeyType.CLEAR_ON_MANAGER_START) - params.clear_all(ParamKeyType.CLEAR_ON_ONROAD_TRANSITION) - params.clear_all(ParamKeyType.CLEAR_ON_OFFROAD_TRANSITION) + params.clear_all(ParamKeyFlag.CLEAR_ON_MANAGER_START) + params.clear_all(ParamKeyFlag.CLEAR_ON_ONROAD_TRANSITION) + params.clear_all(ParamKeyFlag.CLEAR_ON_OFFROAD_TRANSITION) + params.clear_all(ParamKeyFlag.CLEAR_ON_IGNITION_ON) if build_metadata.release_channel: - params.clear_all(ParamKeyType.DEVELOPMENT_ONLY) - - default_params: list[tuple[str, str | bytes]] = [ - ("CompletedTrainingVersion", "0"), - ("DisengageOnAccelerator", "0"), - ("GsmMetered", "1"), - ("HasAcceptedTerms", "0"), - ("LanguageSetting", "main_en"), - ("OpenpilotEnabledToggle", "1"), - ("LongitudinalPersonality", str(log.LongitudinalPersonality.standard)), - ] + params.clear_all(ParamKeyFlag.DEVELOPMENT_ONLY) if params.get_bool("RecordFrontLock"): - params.put_bool("RecordFront", True) + params.put_bool("RecordFront", True, block=True) - # set unset params - for k, v in default_params: - if params.get(k) is None: - params.put(k, v) + # set unset params to their default value + for k in params.all_keys(): + default_value = params.get_default_value(k) + if default_value is not None and params.get(k) is None: + params.put(k, default_value, block=True) # Create folders needed for msgq try: - os.mkdir("/dev/shm") + os.mkdir(Paths.shm_path()) except FileExistsError: pass except PermissionError: - print("WARNING: failed to make /dev/shm") - - # set version params - params.put("Version", build_metadata.openpilot.version) - params.put("TermsVersion", terms_version) - params.put("TrainingVersion", training_version) - params.put("GitCommit", build_metadata.openpilot.git_commit) - params.put("GitCommitDate", build_metadata.openpilot.git_commit_date) - params.put("GitBranch", build_metadata.channel) - params.put("GitRemote", build_metadata.openpilot.git_origin) - params.put_bool("IsTestedBranch", build_metadata.tested_channel) - params.put_bool("IsReleaseBranch", build_metadata.release_channel) + print(f"WARNING: failed to make {Paths.shm_path()}") + + # set params + serial = HARDWARE.get_serial() + params.put("Version", build_metadata.openpilot.version, block=True) + params.put("TermsVersion", terms_version, block=True) + params.put("TrainingVersion", training_version, block=True) + params.put("GitCommit", build_metadata.openpilot.git_commit, block=True) + params.put("GitCommitDate", build_metadata.openpilot.git_commit_date, block=True) + params.put("GitBranch", build_metadata.channel, block=True) + params.put("GitRemote", build_metadata.openpilot.git_origin, block=True) + params.put_bool("IsTestedBranch", build_metadata.tested_channel, block=True) + params.put_bool("IsReleaseBranch", build_metadata.release_channel, block=True) + params.put("HardwareSerial", serial, block=True) + + # NAP: ensure Pre-AP fingerprint is forced on first boot + if params.get("NAPForcePreAP") is None: + params.put_bool("NAPForcePreAP", True) # set dongle id reg_res = register(show_spinner=True) if reg_res: dongle_id = reg_res else: - serial = params.get("HardwareSerial") raise Exception(f"Registration failed for device {serial}") os.environ['DONGLE_ID'] = dongle_id # Needed for swaglog os.environ['GIT_ORIGIN'] = build_metadata.openpilot.git_normalized_origin # Needed for swaglog @@ -119,19 +118,20 @@ def manager_thread() -> None: params = Params() ignore: list[str] = [] - if params.get("DongleId", encoding='utf8') in (None, UNREGISTERED_DONGLE_ID): + if params.get("DongleId") in (None, UNREGISTERED_DONGLE_ID): ignore += ["manage_athenad", "uploader"] if os.getenv("NOBOARD") is not None: ignore.append("pandad") ignore += [x for x in os.getenv("BLOCK", "").split(",") if len(x) > 0] - sm = messaging.SubMaster(['deviceState', 'carParams'], poll='deviceState') + sm = messaging.SubMaster(['deviceState', 'carParams', 'pandaStates'], poll='deviceState') pm = messaging.PubMaster(['managerState']) write_onroad_params(False, params) ensure_running(managed_processes.values(), False, params=params, CP=sm['carParams'], not_run=ignore) started_prev = False + ignition_prev = False while True: sm.update(1000) @@ -139,17 +139,29 @@ def manager_thread() -> None: started = sm['deviceState'].started if started and not started_prev: - params.clear_all(ParamKeyType.CLEAR_ON_ONROAD_TRANSITION) + params.clear_all(ParamKeyFlag.CLEAR_ON_ONROAD_TRANSITION) elif not started and started_prev: - params.clear_all(ParamKeyType.CLEAR_ON_OFFROAD_TRANSITION) + params.clear_all(ParamKeyFlag.CLEAR_ON_OFFROAD_TRANSITION) + + ignition = any(ps.ignitionLine or ps.ignitionCan for ps in sm['pandaStates'] if ps.pandaType != log.PandaState.PandaType.unknown) + if ignition and not ignition_prev: + params.clear_all(ParamKeyFlag.CLEAR_ON_IGNITION_ON) # update onroad params, which drives pandad's safety setter thread if started != started_prev: write_onroad_params(started, params) started_prev = started + ignition_prev = ignition - ensure_running(managed_processes.values(), started, params=params, CP=sm['carParams'], not_run=ignore) + # When a NAP script is running (e.g. pedal calibration), stop conflicting processes + # so the script can access hardware directly without conflicts. + nap_ignore = [] + if params.get_bool("NAPScriptRunning"): + nap_ignore = ["pandad", "card", "controlsd", "selfdrived", "plannerd", "radard", + "calibrationd", "torqued", "locationd", "modeld", "dmonitoringmodeld"] + + ensure_running(managed_processes.values(), started, params=params, CP=sm['carParams'], not_run=ignore + nap_ignore) running = ' '.join("{}{}\u001b[0m".format("\u001b[32m" if p.proc.is_alive() else "\u001b[31m", p.name) for p in managed_processes.values() if p.proc) @@ -161,12 +173,20 @@ def manager_thread() -> None: msg.managerState.processes = [p.get_process_state_msg() for p in managed_processes.values()] pm.send('managerState', msg) + # kick AGNOS power monitoring watchdog + try: + if sm.all_checks(['deviceState']): + with atomic_write("/var/tmp/power_watchdog", "w", overwrite=True) as f: + f.write(str(time.monotonic())) + except Exception: + pass + # Exit main loop when uninstall/shutdown/reboot is needed shutdown = False for param in ("DoUninstall", "DoShutdown", "DoReboot"): if params.get_bool(param): shutdown = True - params.put("LastManagerExitReason", f"{param} {datetime.datetime.now()}") + params.put("LastManagerExitReason", f"{param} {datetime.datetime.now()}", block=True) cloudlog.warning(f"Shutting down manager - {param} set") if shutdown: diff --git a/system/manager/optional_procs.py b/system/manager/optional_procs.py new file mode 100644 index 00000000000000..4394204ee9b286 --- /dev/null +++ b/system/manager/optional_procs.py @@ -0,0 +1,28 @@ +"""Optional manager processes that must not block engage. + +Companion Dash is not a driving process. If it crashes, fails to bind +port 80 (or 7070), or fails to preimport, selfdrived must not raise +processNotRunning (NO_ENTRY + SOFT_DISABLE). +""" +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +OPTIONAL_PROCESS_NAMES = frozenset({"nap_dash", "pathobstacled"}) + + +def missing_required_processes(processes: Iterable[Any], optional_names: set[str] | frozenset[str] | None = None) -> list[str]: + """Names that should trigger EventName.processNotRunning.""" + skip = OPTIONAL_PROCESS_NAMES if optional_names is None else optional_names + return [p.name for p in processes if not p.running and p.shouldBeRunning and p.name not in skip] + + +def nap_dash_enabled(started: bool, params: Any, CP: Any) -> bool: + """Companion Dash. Default on. Missing/corrupt param must not disable or block engage.""" + try: + if params is None or params.get("NAPDashEnabled") is None: + return True + return bool(params.get_bool("NAPDashEnabled")) + except Exception: + return True diff --git a/system/manager/process.py b/system/manager/process.py index 10c8f74f9dd8eb..af29f5765ad748 100644 --- a/system/manager/process.py +++ b/system/manager/process.py @@ -1,7 +1,6 @@ import importlib import os import signal -import struct import time import subprocess from collections.abc import Callable, ValuesView @@ -17,9 +16,6 @@ from openpilot.common.params import Params from openpilot.common.swaglog import cloudlog -WATCHDOG_FN = "/dev/shm/wd_" -ENABLE_WATCHDOG = os.getenv("NO_WATCHDOG") is None - def launcher(proc: str, name: str) -> None: try: @@ -70,11 +66,9 @@ class ManagerProcess(ABC): proc: Process | None = None enabled = True name = "" - - last_watchdog_time = 0 - watchdog_max_dt: int | None = None - watchdog_seen = False shutting_down = False + restart_if_crash = False + optional = False @abstractmethod def prepare(self) -> None: @@ -88,28 +82,7 @@ def restart(self) -> None: self.stop(sig=signal.SIGKILL) self.start() - def check_watchdog(self, started: bool) -> None: - if self.watchdog_max_dt is None or self.proc is None: - return - - try: - fn = WATCHDOG_FN + str(self.proc.pid) - with open(fn, "rb") as f: - # TODO: why can't pylint find struct.unpack? - self.last_watchdog_time = struct.unpack('Q', f.read())[0] - except Exception: - pass - - dt = time.monotonic() - self.last_watchdog_time / 1e9 - - if dt > self.watchdog_max_dt: - if self.watchdog_seen and ENABLE_WATCHDOG: - cloudlog.error(f"Watchdog timeout for {self.name} (exitcode {self.proc.exitcode}) restarting ({started=})") - self.restart() - else: - self.watchdog_seen = True - - def stop(self, retry: bool = True, block: bool = True, sig: signal.Signals = None) -> int | None: + def stop(self, retry: bool = True, block: bool = True, sig: signal.Signals | None = None) -> int | None: if self.proc is None: return None @@ -161,21 +134,24 @@ def get_process_state_msg(self): state.name = self.name if self.proc: state.running = self.proc.is_alive() - state.shouldBeRunning = self.proc is not None and not self.shutting_down + # Optional companions stay out of processNotRunning if they die. + if self.optional and not state.running: + state.shouldBeRunning = False + else: + state.shouldBeRunning = self.proc is not None and not self.shutting_down state.pid = self.proc.pid or 0 state.exitCode = self.proc.exitcode or 0 return state class NativeProcess(ManagerProcess): - def __init__(self, name, cwd, cmdline, should_run, enabled=True, sigkill=False, watchdog_max_dt=None): + def __init__(self, name, cwd, cmdline, should_run, enabled=True, sigkill=False): self.name = name self.cwd = cwd self.cmdline = cmdline self.should_run = should_run self.enabled = enabled self.sigkill = sigkill - self.watchdog_max_dt = watchdog_max_dt self.launcher = nativelauncher def prepare(self) -> None: @@ -193,24 +169,30 @@ def start(self) -> None: cloudlog.info(f"starting process {self.name}") self.proc = Process(name=self.name, target=self.launcher, args=(self.cmdline, cwd, self.name)) self.proc.start() - self.watchdog_seen = False self.shutting_down = False class PythonProcess(ManagerProcess): - def __init__(self, name, module, should_run, enabled=True, sigkill=False, watchdog_max_dt=None): + def __init__(self, name, module, should_run, enabled=True, sigkill=False, restart_if_crash=False, optional=False): self.name = name self.module = module self.should_run = should_run self.enabled = enabled self.sigkill = sigkill - self.watchdog_max_dt = watchdog_max_dt self.launcher = launcher + self.restart_if_crash = restart_if_crash + self.optional = optional def prepare(self) -> None: if self.enabled: cloudlog.info(f"preimporting {self.module}") - importlib.import_module(self.module) + try: + importlib.import_module(self.module) + except Exception: + if self.optional: + cloudlog.exception(f"optional process {self.name} failed to preimport") + return + raise def start(self) -> None: # In case we only tried a non blocking stop we need to stop it before restarting @@ -220,10 +202,13 @@ def start(self) -> None: if self.proc is not None: return + # TODO: this is just a workaround for this tinygrad check: + # https://github.com/tinygrad/tinygrad/blob/ac9c96dae1656dc220ee4acc39cef4dd449aa850/tinygrad/device.py#L26 + name = self.name if "modeld" not in self.name else "MainProcess" + cloudlog.info(f"starting python {self.module}") - self.proc = Process(name=self.name, target=self.launcher, args=(self.module, self.name)) + self.proc = Process(name=name, target=self.launcher, args=(self.module, self.name)) self.proc.start() - self.watchdog_seen = False self.shutting_down = False @@ -248,7 +233,7 @@ def start(self) -> None: if self.params is None: self.params = Params() - pid = self.params.get(self.param_name, encoding='utf-8') + pid = self.params.get(self.param_name) if pid is not None: try: os.kill(int(pid), 0) @@ -267,7 +252,7 @@ def start(self) -> None: stderr=open('/dev/null', 'w'), preexec_fn=os.setpgrp) - self.params.put(self.param_name, str(proc.pid)) + self.params.put(self.param_name, proc.pid, block=True) def stop(self, retry=True, block=True, sig=None) -> None: pass @@ -281,12 +266,13 @@ def ensure_running(procs: ValuesView[ManagerProcess], started: bool, params=None running = [] for p in procs: if p.enabled and p.name not in not_run and p.should_run(started, params, CP): + if p.restart_if_crash and p.proc is not None and not p.proc.is_alive(): + cloudlog.error(f'Restarting {p.name} (exitcode {p.proc.exitcode})') + p.restart() running.append(p) else: p.stop(block=False) - p.check_watchdog(started) - for p in running: p.start() diff --git a/system/manager/process_config.py b/system/manager/process_config.py index 791d26a8f4a4fb..89498e5e5d426a 100644 --- a/system/manager/process_config.py +++ b/system/manager/process_config.py @@ -1,9 +1,12 @@ import os +import operator +import platform from cereal import car from openpilot.common.params import Params from openpilot.system.hardware import PC, TICI from openpilot.system.manager.process import PythonProcess, NativeProcess, DaemonProcess +from openpilot.system.manager.optional_procs import nap_dash_enabled WEBCAM = os.getenv("USE_WEBCAM") is not None @@ -16,75 +19,114 @@ def notcar(started: bool, params: Params, CP: car.CarParams) -> bool: def iscar(started: bool, params: Params, CP: car.CarParams) -> bool: return started and not CP.notCar -def logging(started, params, CP: car.CarParams) -> bool: +def logging(started: bool, params: Params, CP: car.CarParams) -> bool: run = (not CP.notCar) or not params.get_bool("DisableLogging") return started and run def ublox_available() -> bool: return os.path.exists('/dev/ttyHS0') and not os.path.exists('/persist/comma/use-quectel-gps') -def ublox(started, params, CP: car.CarParams) -> bool: +def ublox(started: bool, params: Params, CP: car.CarParams) -> bool: use_ublox = ublox_available() if use_ublox != params.get_bool("UbloxAvailable"): - params.put_bool("UbloxAvailable", use_ublox) + params.put_bool("UbloxAvailable", use_ublox, block=True) return started and use_ublox -def qcomgps(started, params, CP: car.CarParams) -> bool: +def joystick(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and params.get_bool("JoystickDebugMode") + +def not_joystick(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and not params.get_bool("JoystickDebugMode") + +def long_maneuver(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and params.get_bool("LongitudinalManeuverMode") + +def lat_maneuver(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and params.get_bool("LateralManeuverMode") + +def not_long_maneuver(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and not params.get_bool("LongitudinalManeuverMode") + +def qcomgps(started: bool, params: Params, CP: car.CarParams) -> bool: return started and not ublox_available() -def always_run(started, params, CP: car.CarParams) -> bool: +def always_run(started: bool, params: Params, CP: car.CarParams) -> bool: return True -def only_onroad(started: bool, params, CP: car.CarParams) -> bool: +def only_onroad(started: bool, params: Params, CP: car.CarParams) -> bool: return started -def only_offroad(started, params, CP: car.CarParams) -> bool: +def only_offroad(started: bool, params: Params, CP: car.CarParams) -> bool: return not started +def speed_sign_log(started: bool, params: Params, CP: car.CarParams) -> bool: + # Default-off MUTCD JSONL logger. Does not start unless NAPSpeedSignLog is on. + return started and params.get_bool("NAPSpeedSignLog") + +def or_(*fns): + return lambda *args: operator.or_(*(fn(*args) for fn in fns)) + +def and_(*fns): + return lambda *args: operator.and_(*(fn(*args) for fn in fns)) + procs = [ DaemonProcess("manage_athenad", "system.athena.manage_athenad", "AthenadPid"), - NativeProcess("camerad", "system/camerad", ["./camerad"], driverview), - NativeProcess("logcatd", "system/logcatd", ["./logcatd"], only_onroad), - NativeProcess("proclogd", "system/proclogd", ["./proclogd"], only_onroad), + NativeProcess("loggerd", "system/loggerd", ["./loggerd"], logging), + NativeProcess("encoderd", "system/loggerd", ["./encoderd"], only_onroad), + NativeProcess("stream_encoderd", "system/loggerd", ["./encoderd", "--stream"], notcar), PythonProcess("logmessaged", "system.logmessaged", always_run), + + NativeProcess("camerad", "system/camerad", ["./camerad"], driverview, enabled=not WEBCAM), + PythonProcess("webcamerad", "tools.webcam.camerad", driverview, enabled=WEBCAM), + PythonProcess("proclogd", "system.proclogd", only_onroad, enabled=platform.system() != "Darwin"), + PythonProcess("journald", "system.journald", only_onroad, platform.system() != "Darwin"), PythonProcess("micd", "system.micd", iscar), PythonProcess("timed", "system.timed", always_run, enabled=not PC), - PythonProcess("dmonitoringmodeld", "selfdrive.modeld.dmonitoringmodeld", driverview, enabled=(not PC or WEBCAM)), - NativeProcess("encoderd", "system/loggerd", ["./encoderd"], only_onroad), - NativeProcess("stream_encoderd", "system/loggerd", ["./encoderd", "--stream"], notcar), - NativeProcess("loggerd", "system/loggerd", ["./loggerd"], logging), - NativeProcess("modeld", "selfdrive/modeld", ["./modeld"], only_onroad), - NativeProcess("sensord", "system/sensord", ["./sensord"], only_onroad, enabled=not PC), - NativeProcess("ui", "selfdrive/ui", ["./ui"], always_run, watchdog_max_dt=(5 if not PC else None)), + PythonProcess("modeld", "selfdrive.modeld.modeld", only_onroad), + PythonProcess("dmonitoringmodeld", "selfdrive.modeld.dmonitoringmodeld", driverview, enabled=(WEBCAM or not PC)), + + PythonProcess("sensord", "system.sensord.sensord", only_onroad, enabled=not PC), + PythonProcess("ui", "selfdrive.ui.ui", always_run, restart_if_crash=True), + PythonProcess("nap_dash", "selfdrive.nap_dash.server", nap_dash_enabled, restart_if_crash=True, optional=True), PythonProcess("soundd", "selfdrive.ui.soundd", only_onroad), - NativeProcess("locationd", "selfdrive/locationd", ["./locationd"], only_onroad), - NativeProcess("pandad", "selfdrive/pandad", ["./pandad"], always_run, enabled=False), + PythonProcess("locationd", "selfdrive.locationd.locationd", only_onroad), + NativeProcess("_pandad", "selfdrive/pandad", ["./pandad"], always_run, enabled=False), PythonProcess("calibrationd", "selfdrive.locationd.calibrationd", only_onroad), PythonProcess("torqued", "selfdrive.locationd.torqued", only_onroad), - PythonProcess("controlsd", "selfdrive.controls.controlsd", only_onroad), + PythonProcess("controlsd", "selfdrive.controls.controlsd", and_(not_joystick, iscar)), + PythonProcess("joystickd", "tools.joystick.joystickd", or_(joystick, notcar)), + PythonProcess("selfdrived", "selfdrive.selfdrived.selfdrived", only_onroad), PythonProcess("card", "selfdrive.car.card", only_onroad), PythonProcess("deleter", "system.loggerd.deleter", always_run), - PythonProcess("dmonitoringd", "selfdrive.monitoring.dmonitoringd", driverview, enabled=(not PC or WEBCAM)), + PythonProcess("dmonitoringd", "selfdrive.monitoring.dmonitoringd", driverview, enabled=(WEBCAM or not PC)), PythonProcess("qcomgpsd", "system.qcomgpsd.qcomgpsd", qcomgps, enabled=TICI), - #PythonProcess("ugpsd", "system.ugpsd", only_onroad, enabled=TICI), PythonProcess("pandad", "selfdrive.pandad.pandad", always_run), PythonProcess("paramsd", "selfdrive.locationd.paramsd", only_onroad), - NativeProcess("ubloxd", "system/ubloxd", ["./ubloxd"], ublox, enabled=TICI), + PythonProcess("lagd", "selfdrive.locationd.lagd", only_onroad), + PythonProcess("ubloxd", "system.ubloxd.ubloxd", ublox, enabled=TICI), PythonProcess("pigeond", "system.ubloxd.pigeond", ublox, enabled=TICI), - PythonProcess("plannerd", "selfdrive.controls.plannerd", only_onroad), + PythonProcess("plannerd", "selfdrive.controls.plannerd", not_long_maneuver), + PythonProcess("mapd", "selfdrive.mapd.mapd", only_onroad), + PythonProcess("speedsignd", "selfdrive.speedsignd.speedsignd", speed_sign_log), + PythonProcess("maneuversd", "tools.longitudinal_maneuvers.maneuversd", long_maneuver), + PythonProcess("lateral_maneuversd", "tools.lateral_maneuvers.lateral_maneuversd", lat_maneuver), PythonProcess("radard", "selfdrive.controls.radard", only_onroad), + PythonProcess("pathobstacled", "selfdrive.pathobstacled.pathobstacled", and_(only_onroad, lambda s, p, cp: p.get_bool("NAPObstacleLog")), optional=True), PythonProcess("hardwared", "system.hardware.hardwared", always_run), + PythonProcess("modem", "system.hardware.tici.modem", always_run, enabled=TICI), PythonProcess("tombstoned", "system.tombstoned", always_run, enabled=not PC), PythonProcess("updated", "system.updated.updated", only_offroad, enabled=not PC), PythonProcess("uploader", "system.loggerd.uploader", always_run), PythonProcess("statsd", "system.statsd", always_run), + PythonProcess("feedbackd", "selfdrive.ui.feedback.feedbackd", only_onroad), # debug procs NativeProcess("bridge", "cereal/messaging", ["./bridge"], notcar), PythonProcess("webrtcd", "system.webrtc.webrtcd", notcar), PythonProcess("webjoystick", "tools.bodyteleop.web", notcar), + PythonProcess("joystick", "tools.joystick.joystick_control", and_(joystick, iscar)), ] managed_processes = {p.name: p for p in procs} diff --git a/system/manager/test/test_manager.py b/system/manager/test/test_manager.py index e5960d1113632c..34d07c6724cf7b 100644 --- a/system/manager/test/test_manager.py +++ b/system/manager/test/test_manager.py @@ -3,13 +3,11 @@ import signal import time -from parameterized import parameterized - from cereal import car from openpilot.common.params import Params import openpilot.system.manager.manager as manager from openpilot.system.manager.process import ensure_running -from openpilot.system.manager.process_config import managed_processes +from openpilot.system.manager.process_config import managed_processes, procs from openpilot.system.hardware import HARDWARE os.environ['FAKEUPLOAD'] = "1" @@ -18,7 +16,6 @@ BLACKLIST_PROCS = ['manage_athenad', 'pandad', 'pigeond'] -@pytest.mark.tici class TestManager: def setup_method(self): HARDWARE.set_power_save(False) @@ -34,17 +31,25 @@ def test_manager_prepare(self): os.environ['PREPAREONLY'] = '1' manager.main() + def test_duplicate_procs(self): + assert len(procs) == len(managed_processes), "Duplicate process names" + def test_blacklisted_procs(self): # TODO: ensure there are blacklisted procs until we have a dedicated test assert len(BLACKLIST_PROCS), "No blacklisted procs to test not_run" - @parameterized.expand([(i,) for i in range(10)]) - def test_startup_time(self, index): - start = time.monotonic() + def test_set_params_with_default_value(self): + params = Params() + params.clear_all() + os.environ['PREPAREONLY'] = '1' manager.main() - t = time.monotonic() - start - assert t < MAX_STARTUP_TIME, f"startup took {t}s, expected <{MAX_STARTUP_TIME}s" + for k in params.all_keys(): + default_value = params.get_default_value(k) + if default_value is not None: + assert params.get(k) == default_value + assert params.get("OpenpilotEnabledToggle") + assert params.get("RouteCount") == 0 @pytest.mark.skip("this test is flaky the way it's currently written, should be moved to test_onroad") def test_clean_exit(self, subtests): diff --git a/system/micd.py b/system/micd.py index af1aa3136063a7..9b3ccc8d29a290 100755 --- a/system/micd.py +++ b/system/micd.py @@ -1,17 +1,18 @@ #!/usr/bin/env python3 import numpy as np from functools import cache +import threading from cereal import messaging from openpilot.common.realtime import Ratekeeper -from openpilot.common.retry import retry +from openpilot.common.utils import retry from openpilot.common.swaglog import cloudlog RATE = 10 -FFT_SAMPLES = 4096 +FFT_SAMPLES = 1600 # 100ms REFERENCE_SPL = 2e-5 # newtons/m^2 -SAMPLE_RATE = 44100 -SAMPLE_BUFFER = 4096 # approx 100ms +SAMPLE_RATE = 16000 +SAMPLE_BUFFER = 800 # 50ms @cache @@ -44,7 +45,7 @@ def apply_a_weighting(measurements: np.ndarray) -> np.ndarray: class Mic: def __init__(self): self.rk = Ratekeeper(RATE) - self.pm = messaging.PubMaster(['microphone']) + self.pm = messaging.PubMaster(['soundPressure', 'rawAudioData']) self.measurements = np.empty(0) @@ -52,14 +53,20 @@ def __init__(self): self.sound_pressure_weighted = 0 self.sound_pressure_level_weighted = 0 + self.lock = threading.Lock() + def update(self): - msg = messaging.new_message('microphone', valid=True) - msg.microphone.soundPressure = float(self.sound_pressure) - msg.microphone.soundPressureWeighted = float(self.sound_pressure_weighted) + with self.lock: + sound_pressure = self.sound_pressure + sound_pressure_weighted = self.sound_pressure_weighted + sound_pressure_level_weighted = self.sound_pressure_level_weighted - msg.microphone.soundPressureWeightedDb = float(self.sound_pressure_level_weighted) + msg = messaging.new_message('soundPressure', valid=True) + msg.soundPressure.soundPressure = float(sound_pressure) + msg.soundPressure.soundPressureWeighted = float(sound_pressure_weighted) + msg.soundPressure.soundPressureWeightedDb = float(sound_pressure_level_weighted) - self.pm.send('microphone', msg) + self.pm.send('soundPressure', msg) self.rk.keep_time() def callback(self, indata, frames, time, status): @@ -69,19 +76,25 @@ def callback(self, indata, frames, time, status): Logged A-weighted equivalents are rough approximations of the human-perceived loudness. """ + msg = messaging.new_message('rawAudioData', valid=True) + audio_data_int_16 = (indata[:, 0] * 32767).astype(np.int16) + msg.rawAudioData.data = audio_data_int_16.tobytes() + msg.rawAudioData.sampleRate = SAMPLE_RATE + self.pm.send('rawAudioData', msg) - self.measurements = np.concatenate((self.measurements, indata[:, 0])) + with self.lock: + self.measurements = np.concatenate((self.measurements, indata[:, 0])) - while self.measurements.size >= FFT_SAMPLES: - measurements = self.measurements[:FFT_SAMPLES] + while self.measurements.size >= FFT_SAMPLES: + measurements = self.measurements[:FFT_SAMPLES] - self.sound_pressure, _ = calculate_spl(measurements) - measurements_weighted = apply_a_weighting(measurements) - self.sound_pressure_weighted, self.sound_pressure_level_weighted = calculate_spl(measurements_weighted) + self.sound_pressure, _ = calculate_spl(measurements) + measurements_weighted = apply_a_weighting(measurements) + self.sound_pressure_weighted, self.sound_pressure_level_weighted = calculate_spl(measurements_weighted) - self.measurements = self.measurements[FFT_SAMPLES:] + self.measurements = self.measurements[FFT_SAMPLES:] - @retry(attempts=7, delay=3) + @retry(attempts=10, delay=3) def get_stream(self, sd): # reload sounddevice to reinitialize portaudio sd._terminate() diff --git a/system/proclogd.py b/system/proclogd.py new file mode 100755 index 00000000000000..b008f8ed9bcd5b --- /dev/null +++ b/system/proclogd.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +import os +from typing import NoReturn, TypedDict + +from cereal import messaging +from openpilot.common.realtime import Ratekeeper +from openpilot.common.swaglog import cloudlog + +JIFFY = os.sysconf(os.sysconf_names['SC_CLK_TCK']) +PAGE_SIZE = os.sysconf(os.sysconf_names['SC_PAGE_SIZE']) + + +def _cpu_times() -> list[dict[str, float]]: + cpu_times: list[dict[str, float]] = [] + try: + with open('/proc/stat') as f: + lines = f.readlines()[1:] + for line in lines: + if not line.startswith('cpu') or len(line) < 4 or not line[3].isdigit(): + break + parts = line.split() + cpu_times.append({ + 'cpuNum': int(parts[0][3:]), + 'user': float(parts[1]) / JIFFY, + 'nice': float(parts[2]) / JIFFY, + 'system': float(parts[3]) / JIFFY, + 'idle': float(parts[4]) / JIFFY, + 'iowait': float(parts[5]) / JIFFY, + 'irq': float(parts[6]) / JIFFY, + 'softirq': float(parts[7]) / JIFFY, + }) + except Exception: + cloudlog.exception("failed to read /proc/stat") + return cpu_times + + +def _mem_info() -> dict[str, int]: + keys = ["MemTotal:", "MemFree:", "MemAvailable:", "Buffers:", "Cached:", "Active:", "Inactive:", "Shmem:"] + info: dict[str, int] = dict.fromkeys(keys, 0) + try: + with open('/proc/meminfo') as f: + for line in f: + parts = line.split() + if parts and parts[0] in info: + info[parts[0]] = int(parts[1]) * 1024 + except Exception: + cloudlog.exception("failed to read /proc/meminfo") + return info + + +_STAT_POS = { + 'pid': 1, + 'state': 3, + 'ppid': 4, + 'utime': 14, + 'stime': 15, + 'cutime': 16, + 'cstime': 17, + 'priority': 18, + 'nice': 19, + 'num_threads': 20, + 'starttime': 22, + 'vsize': 23, + 'rss': 24, + 'processor': 39, +} + +class ProcStat(TypedDict): + name: str + pid: int + state: str + ppid: int + utime: int + stime: int + cutime: int + cstime: int + priority: int + nice: int + num_threads: int + starttime: int + vms: int + rss: int + processor: int + + +def _parse_proc_stat(stat: str) -> ProcStat | None: + open_paren = stat.find('(') + close_paren = stat.rfind(')') + if open_paren == -1 or close_paren == -1 or open_paren > close_paren: + return None + name = stat[open_paren + 1:close_paren] + stat = stat[:open_paren] + stat[open_paren:close_paren].replace(' ', '_') + stat[close_paren:] + parts = stat.split() + if len(parts) < 52: + return None + try: + return { + 'name': name, + 'pid': int(parts[_STAT_POS['pid'] - 1]), + 'state': parts[_STAT_POS['state'] - 1][0], + 'ppid': int(parts[_STAT_POS['ppid'] - 1]), + 'utime': int(parts[_STAT_POS['utime'] - 1]), + 'stime': int(parts[_STAT_POS['stime'] - 1]), + 'cutime': int(parts[_STAT_POS['cutime'] - 1]), + 'cstime': int(parts[_STAT_POS['cstime'] - 1]), + 'priority': int(parts[_STAT_POS['priority'] - 1]), + 'nice': int(parts[_STAT_POS['nice'] - 1]), + 'num_threads': int(parts[_STAT_POS['num_threads'] - 1]), + 'starttime': int(parts[_STAT_POS['starttime'] - 1]), + 'vms': int(parts[_STAT_POS['vsize'] - 1]), + 'rss': int(parts[_STAT_POS['rss'] - 1]), + 'processor': int(parts[_STAT_POS['processor'] - 1]), + } + except Exception: + cloudlog.exception("failed to parse /proc//stat") + return None + +class SmapsData(TypedDict): + pss: int # bytes + pss_anon: int # bytes + pss_shmem: int # bytes + + +_SMAPS_KEYS = {b'Pss:', b'Pss_Anon:', b'Pss_Shmem:'} + +# smaps_rollup (kernel 4.14+) is ideal but missing on some BSP kernels; +# fall back to per-VMA smaps (any kernel). Pss_Anon/Pss_Shmem only in 5.x+. +_smaps_path: str | None = None # auto-detected on first call + +# per-VMA smaps is expensive (kernel walks page tables for every VMA). +# cache results and only refresh every N cycles to keep CPU low. +_smaps_cache: dict[int, SmapsData] = {} +_smaps_cycle = 0 +_SMAPS_EVERY = 20 # refresh every 20th cycle (40s at 0.5Hz) + + +def _read_smaps(pid: int) -> SmapsData: + global _smaps_path + try: + if _smaps_path is None: + _smaps_path = 'smaps_rollup' if os.path.exists(f'/proc/{pid}/smaps_rollup') else 'smaps' + + result: SmapsData = {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0} + with open(f'/proc/{pid}/{_smaps_path}', 'rb') as f: + for line in f: + parts = line.split() + if len(parts) >= 2 and parts[0] in _SMAPS_KEYS: + val = int(parts[1]) * 1024 # kB -> bytes + if parts[0] == b'Pss:': + result['pss'] += val + elif parts[0] == b'Pss_Anon:': + result['pss_anon'] += val + elif parts[0] == b'Pss_Shmem:': + result['pss_shmem'] += val + return result + except (FileNotFoundError, PermissionError, ProcessLookupError, OSError): + return {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0} + + +def _get_smaps_cached(pid: int) -> SmapsData: + """Return cached smaps data, refreshing every _SMAPS_EVERY cycles.""" + if _smaps_cycle == 0 or pid not in _smaps_cache: + _smaps_cache[pid] = _read_smaps(pid) + return _smaps_cache.get(pid, {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0}) + + +class ProcExtra(TypedDict): + pid: int + name: str + exe: str + cmdline: list[str] + + +_proc_cache: dict[int, ProcExtra] = {} + + +def _get_proc_extra(pid: int, name: str) -> ProcExtra: + cache: ProcExtra | None = _proc_cache.get(pid) + if cache is None or cache.get('name') != name: + exe = '' + cmdline: list[str] = [] + try: + exe = os.readlink(f'/proc/{pid}/exe') + except OSError: + pass + try: + with open(f'/proc/{pid}/cmdline', 'rb') as f: + cmdline = [c.decode('utf-8', errors='replace') for c in f.read().split(b'\0') if c] + except OSError: + pass + cache = {'pid': pid, 'name': name, 'exe': exe, 'cmdline': cmdline} + _proc_cache[pid] = cache + return cache + + +def _procs() -> list[ProcStat]: + stats: list[ProcStat] = [] + for pid_str in os.listdir('/proc'): + if not pid_str.isdigit(): + continue + try: + with open(f'/proc/{pid_str}/stat') as f: + stat = f.read() + parsed = _parse_proc_stat(stat) + if parsed is not None: + stats.append(parsed) + except OSError: + continue + return stats + + +def build_proc_log_message(msg) -> None: + pl = msg.procLog + + procs = _procs() + l = pl.init('procs', len(procs)) + for i, r in enumerate(procs): + proc = l[i] + proc.pid = r['pid'] + proc.state = ord(r['state'][0]) + proc.ppid = r['ppid'] + proc.cpuUser = r['utime'] / JIFFY + proc.cpuSystem = r['stime'] / JIFFY + proc.cpuChildrenUser = r['cutime'] / JIFFY + proc.cpuChildrenSystem = r['cstime'] / JIFFY + proc.priority = r['priority'] + proc.nice = r['nice'] + proc.numThreads = r['num_threads'] + proc.startTime = r['starttime'] / JIFFY + proc.memVms = r['vms'] + proc.memRss = r['rss'] * PAGE_SIZE + proc.processor = r['processor'] + proc.name = r['name'] + + extra = _get_proc_extra(r['pid'], r['name']) + proc.exe = extra['exe'] + cmdline = proc.init('cmdline', len(extra['cmdline'])) + for j, arg in enumerate(extra['cmdline']): + cmdline[j] = arg + + # smaps is expensive (kernel walks page tables); skip small processes, use cache + if r['rss'] * PAGE_SIZE > 5 * 1024 * 1024: + smaps = _get_smaps_cached(r['pid']) + proc.memPss = smaps['pss'] + proc.memPssAnon = smaps['pss_anon'] + proc.memPssShmem = smaps['pss_shmem'] + + cpu_times = _cpu_times() + cpu_list = pl.init('cpuTimes', len(cpu_times)) + for i, ct in enumerate(cpu_times): + cpu = cpu_list[i] + cpu.cpuNum = ct['cpuNum'] + cpu.user = ct['user'] + cpu.nice = ct['nice'] + cpu.system = ct['system'] + cpu.idle = ct['idle'] + cpu.iowait = ct['iowait'] + cpu.irq = ct['irq'] + cpu.softirq = ct['softirq'] + + mem_info = _mem_info() + pl.mem.total = mem_info["MemTotal:"] + pl.mem.free = mem_info["MemFree:"] + pl.mem.available = mem_info["MemAvailable:"] + pl.mem.buffers = mem_info["Buffers:"] + pl.mem.cached = mem_info["Cached:"] + pl.mem.active = mem_info["Active:"] + pl.mem.inactive = mem_info["Inactive:"] + pl.mem.shared = mem_info["Shmem:"] + + global _smaps_cycle + _smaps_cycle = (_smaps_cycle + 1) % _SMAPS_EVERY + + +def main() -> NoReturn: + pm = messaging.PubMaster(['procLog']) + rk = Ratekeeper(0.5) + while True: + msg = messaging.new_message('procLog', valid=True) + build_proc_log_message(msg) + pm.send('procLog', msg) + rk.keep_time() + + +if __name__ == '__main__': + main() diff --git a/system/proclogd/SConscript b/system/proclogd/SConscript deleted file mode 100644 index 08814d5ccb0a0c..00000000000000 --- a/system/proclogd/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('env', 'messaging', 'common') -libs = [messaging, 'pthread', common] -env.Program('proclogd', ['main.cc', 'proclog.cc'], LIBS=libs) - -if GetOption('extras'): - env.Program('tests/test_proclog', ['tests/test_proclog.cc', 'proclog.cc'], LIBS=libs) diff --git a/system/proclogd/main.cc b/system/proclogd/main.cc deleted file mode 100644 index 3f8a889eea9aec..00000000000000 --- a/system/proclogd/main.cc +++ /dev/null @@ -1,25 +0,0 @@ - -#include - -#include "common/ratekeeper.h" -#include "common/util.h" -#include "system/proclogd/proclog.h" - -ExitHandler do_exit; - -int main(int argc, char **argv) { - setpriority(PRIO_PROCESS, 0, -15); - - RateKeeper rk("proclogd", 0.5); - PubMaster publisher({"procLog"}); - - while (!do_exit) { - MessageBuilder msg; - buildProcLogMessage(msg); - publisher.send("procLog", msg); - - rk.keepTime(); - } - - return 0; -} diff --git a/system/proclogd/proclog.cc b/system/proclogd/proclog.cc deleted file mode 100644 index 09ab4f559e5c63..00000000000000 --- a/system/proclogd/proclog.cc +++ /dev/null @@ -1,239 +0,0 @@ -#include "system/proclogd/proclog.h" - -#include - -#include -#include -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" - -namespace Parser { - -// parse /proc/stat -std::vector cpuTimes(std::istream &stream) { - std::vector cpu_times; - std::string line; - // skip the first line for cpu total - std::getline(stream, line); - while (std::getline(stream, line)) { - if (line.compare(0, 3, "cpu") != 0) break; - - CPUTime t = {}; - std::istringstream iss(line); - if (iss.ignore(3) >> t.id >> t.utime >> t.ntime >> t.stime >> t.itime >> t.iowtime >> t.irqtime >> t.sirqtime) - cpu_times.push_back(t); - } - return cpu_times; -} - -// parse /proc/meminfo -std::unordered_map memInfo(std::istream &stream) { - std::unordered_map mem_info; - std::string line, key; - while (std::getline(stream, line)) { - uint64_t val = 0; - std::istringstream iss(line); - if (iss >> key >> val) { - mem_info[key] = val * 1024; - } - } - return mem_info; -} - -// field position (https://man7.org/linux/man-pages/man5/proc.5.html) -enum StatPos { - pid = 1, - state = 3, - ppid = 4, - utime = 14, - stime = 15, - cutime = 16, - cstime = 17, - priority = 18, - nice = 19, - num_threads = 20, - starttime = 22, - vsize = 23, - rss = 24, - processor = 39, - MAX_FIELD = 52, -}; - -// parse /proc/pid/stat -std::optional procStat(std::string stat) { - // To avoid being fooled by names containing a closing paren, scan backwards. - auto open_paren = stat.find('('); - auto close_paren = stat.rfind(')'); - if (open_paren == std::string::npos || close_paren == std::string::npos || open_paren > close_paren) { - return std::nullopt; - } - - std::string name = stat.substr(open_paren + 1, close_paren - open_paren - 1); - // replace space in name with _ - std::replace(&stat[open_paren], &stat[close_paren], ' ', '_'); - std::istringstream iss(stat); - std::vector v{std::istream_iterator(iss), - std::istream_iterator()}; - try { - if (v.size() != StatPos::MAX_FIELD) { - throw std::invalid_argument("stat"); - } - ProcStat p = { - .name = name, - .pid = stoi(v[StatPos::pid - 1]), - .state = v[StatPos::state - 1][0], - .ppid = stoi(v[StatPos::ppid - 1]), - .utime = stoul(v[StatPos::utime - 1]), - .stime = stoul(v[StatPos::stime - 1]), - .cutime = stol(v[StatPos::cutime - 1]), - .cstime = stol(v[StatPos::cstime - 1]), - .priority = stol(v[StatPos::priority - 1]), - .nice = stol(v[StatPos::nice - 1]), - .num_threads = stol(v[StatPos::num_threads - 1]), - .starttime = stoull(v[StatPos::starttime - 1]), - .vms = stoul(v[StatPos::vsize - 1]), - .rss = stol(v[StatPos::rss - 1]), - .processor = stoi(v[StatPos::processor - 1]), - }; - return p; - } catch (const std::invalid_argument &e) { - LOGE("failed to parse procStat (%s) :%s", e.what(), stat.c_str()); - } catch (const std::out_of_range &e) { - LOGE("failed to parse procStat (%s) :%s", e.what(), stat.c_str()); - } - return std::nullopt; -} - -// return list of PIDs from /proc -std::vector pids() { - std::vector ids; - DIR *d = opendir("/proc"); - assert(d); - char *p_end; - struct dirent *de = NULL; - while ((de = readdir(d))) { - if (de->d_type == DT_DIR) { - int pid = strtol(de->d_name, &p_end, 10); - if (p_end == (de->d_name + strlen(de->d_name))) { - ids.push_back(pid); - } - } - } - closedir(d); - return ids; -} - -// null-delimited cmdline arguments to vector -std::vector cmdline(std::istream &stream) { - std::vector ret; - std::string line; - while (std::getline(stream, line, '\0')) { - if (!line.empty()) { - ret.push_back(line); - } - } - return ret; -} - -const ProcCache &getProcExtraInfo(int pid, const std::string &name) { - static std::unordered_map proc_cache; - ProcCache &cache = proc_cache[pid]; - if (cache.pid != pid || cache.name != name) { - cache.pid = pid; - cache.name = name; - std::string proc_path = "/proc/" + std::to_string(pid); - cache.exe = util::readlink(proc_path + "/exe"); - std::ifstream stream(proc_path + "/cmdline"); - cache.cmdline = cmdline(stream); - } - return cache; -} - -} // namespace Parser - -const double jiffy = sysconf(_SC_CLK_TCK); -const size_t page_size = sysconf(_SC_PAGE_SIZE); - -void buildCPUTimes(cereal::ProcLog::Builder &builder) { - std::ifstream stream("/proc/stat"); - std::vector stats = Parser::cpuTimes(stream); - - auto log_cpu_times = builder.initCpuTimes(stats.size()); - for (int i = 0; i < stats.size(); ++i) { - auto l = log_cpu_times[i]; - const CPUTime &r = stats[i]; - l.setCpuNum(r.id); - l.setUser(r.utime / jiffy); - l.setNice(r.ntime / jiffy); - l.setSystem(r.stime / jiffy); - l.setIdle(r.itime / jiffy); - l.setIowait(r.iowtime / jiffy); - l.setIrq(r.irqtime / jiffy); - l.setSoftirq(r.sirqtime / jiffy); - } -} - -void buildMemInfo(cereal::ProcLog::Builder &builder) { - std::ifstream stream("/proc/meminfo"); - auto mem_info = Parser::memInfo(stream); - - auto mem = builder.initMem(); - mem.setTotal(mem_info["MemTotal:"]); - mem.setFree(mem_info["MemFree:"]); - mem.setAvailable(mem_info["MemAvailable:"]); - mem.setBuffers(mem_info["Buffers:"]); - mem.setCached(mem_info["Cached:"]); - mem.setActive(mem_info["Active:"]); - mem.setInactive(mem_info["Inactive:"]); - mem.setShared(mem_info["Shmem:"]); -} - -void buildProcs(cereal::ProcLog::Builder &builder) { - auto pids = Parser::pids(); - std::vector proc_stats; - proc_stats.reserve(pids.size()); - for (int pid : pids) { - std::string path = "/proc/" + std::to_string(pid) + "/stat"; - if (auto stat = Parser::procStat(util::read_file(path))) { - proc_stats.push_back(*stat); - } - } - - auto procs = builder.initProcs(proc_stats.size()); - for (size_t i = 0; i < proc_stats.size(); i++) { - auto l = procs[i]; - const ProcStat &r = proc_stats[i]; - l.setPid(r.pid); - l.setState(r.state); - l.setPpid(r.ppid); - l.setCpuUser(r.utime / jiffy); - l.setCpuSystem(r.stime / jiffy); - l.setCpuChildrenUser(r.cutime / jiffy); - l.setCpuChildrenSystem(r.cstime / jiffy); - l.setPriority(r.priority); - l.setNice(r.nice); - l.setNumThreads(r.num_threads); - l.setStartTime(r.starttime / jiffy); - l.setMemVms(r.vms); - l.setMemRss((uint64_t)r.rss * page_size); - l.setProcessor(r.processor); - l.setName(r.name); - - const ProcCache &extra_info = Parser::getProcExtraInfo(r.pid, r.name); - l.setExe(extra_info.exe); - auto lcmdline = l.initCmdline(extra_info.cmdline.size()); - for (size_t j = 0; j < lcmdline.size(); j++) { - lcmdline.set(j, extra_info.cmdline[j]); - } - } -} - -void buildProcLogMessage(MessageBuilder &msg) { - auto procLog = msg.initEvent().initProcLog(); - buildProcs(procLog); - buildCPUTimes(procLog); - buildMemInfo(procLog); -} diff --git a/system/proclogd/proclog.h b/system/proclogd/proclog.h deleted file mode 100644 index 49f97cdd36bed7..00000000000000 --- a/system/proclogd/proclog.h +++ /dev/null @@ -1,40 +0,0 @@ -#include -#include -#include -#include - -#include "cereal/messaging/messaging.h" - -struct CPUTime { - int id; - unsigned long utime, ntime, stime, itime; - unsigned long iowtime, irqtime, sirqtime; -}; - -struct ProcCache { - int pid; - std::string name, exe; - std::vector cmdline; -}; - -struct ProcStat { - int pid, ppid, processor; - char state; - long cutime, cstime, priority, nice, num_threads, rss; - unsigned long utime, stime, vms; - unsigned long long starttime; - std::string name; -}; - -namespace Parser { - -std::vector pids(); -std::optional procStat(std::string stat); -std::vector cmdline(std::istream &stream); -std::vector cpuTimes(std::istream &stream); -std::unordered_map memInfo(std::istream &stream); -const ProcCache &getProcExtraInfo(int pid, const std::string &name); - -}; // namespace Parser - -void buildProcLogMessage(MessageBuilder &msg); diff --git a/system/proclogd/tests/.gitignore b/system/proclogd/tests/.gitignore deleted file mode 100644 index 5230b1598dfbd2..00000000000000 --- a/system/proclogd/tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -test_proclog diff --git a/system/proclogd/tests/test_proclog.cc b/system/proclogd/tests/test_proclog.cc deleted file mode 100644 index b86229a4996cd1..00000000000000 --- a/system/proclogd/tests/test_proclog.cc +++ /dev/null @@ -1,142 +0,0 @@ -#define CATCH_CONFIG_MAIN -#include "catch2/catch.hpp" -#include "common/util.h" -#include "system/proclogd/proclog.h" - -const std::string allowed_states = "RSDTZtWXxKWPI"; - -TEST_CASE("Parser::procStat") { - SECTION("from string") { - const std::string stat_str = - "33012 (code )) S 32978 6620 6620 0 -1 4194368 2042377 0 144 0 24510 11627 0 " - "0 20 0 39 0 53077 830029824 62214 18446744073709551615 94257242783744 94257366235808 " - "140735738643248 0 0 0 0 4098 1073808632 0 0 0 17 2 0 0 2 0 0 94257370858656 94257371248232 " - "94257404952576 140735738648768 140735738648823 140735738648823 140735738650595 0"; - auto stat = Parser::procStat(stat_str); - REQUIRE(stat); - REQUIRE(stat->pid == 33012); - REQUIRE(stat->name == "code )"); - REQUIRE(stat->state == 'S'); - REQUIRE(stat->ppid == 32978); - REQUIRE(stat->utime == 24510); - REQUIRE(stat->stime == 11627); - REQUIRE(stat->cutime == 0); - REQUIRE(stat->cstime == 0); - REQUIRE(stat->priority == 20); - REQUIRE(stat->nice == 0); - REQUIRE(stat->num_threads == 39); - REQUIRE(stat->starttime == 53077); - REQUIRE(stat->vms == 830029824); - REQUIRE(stat->rss == 62214); - REQUIRE(stat->processor == 2); - } - SECTION("all processes") { - std::vector pids = Parser::pids(); - REQUIRE(pids.size() > 1); - for (int pid : pids) { - std::string stat_path = "/proc/" + std::to_string(pid) + "/stat"; - INFO(stat_path); - if (auto stat = Parser::procStat(util::read_file(stat_path))) { - REQUIRE(stat->pid == pid); - REQUIRE(allowed_states.find(stat->state) != std::string::npos); - } else { - REQUIRE(util::file_exists(stat_path) == false); - } - } - } -} - -TEST_CASE("Parser::cpuTimes") { - SECTION("from string") { - std::string stat = - "cpu 0 0 0 0 0 0 0 0 0 0\n" - "cpu0 1 2 3 4 5 6 7 8 9 10\n" - "cpu1 1 2 3 4 5 6 7 8 9 10\n"; - std::istringstream stream(stat); - auto stats = Parser::cpuTimes(stream); - REQUIRE(stats.size() == 2); - for (int i = 0; i < stats.size(); ++i) { - REQUIRE(stats[i].id == i); - REQUIRE(stats[i].utime == 1); - REQUIRE(stats[i].ntime ==2); - REQUIRE(stats[i].stime == 3); - REQUIRE(stats[i].itime == 4); - REQUIRE(stats[i].iowtime == 5); - REQUIRE(stats[i].irqtime == 6); - REQUIRE(stats[i].sirqtime == 7); - } - } - SECTION("all cpus") { - std::istringstream stream(util::read_file("/proc/stat")); - auto stats = Parser::cpuTimes(stream); - REQUIRE(stats.size() == sysconf(_SC_NPROCESSORS_ONLN)); - for (int i = 0; i < stats.size(); ++i) { - REQUIRE(stats[i].id == i); - } - } -} - -TEST_CASE("Parser::memInfo") { - SECTION("from string") { - std::istringstream stream("MemTotal: 1024 kb\nMemFree: 2048 kb\n"); - auto meminfo = Parser::memInfo(stream); - REQUIRE(meminfo["MemTotal:"] == 1024 * 1024); - REQUIRE(meminfo["MemFree:"] == 2048 * 1024); - } - SECTION("from /proc/meminfo") { - std::string require_keys[] = {"MemTotal:", "MemFree:", "MemAvailable:", "Buffers:", "Cached:", "Active:", "Inactive:", "Shmem:"}; - std::istringstream stream(util::read_file("/proc/meminfo")); - auto meminfo = Parser::memInfo(stream); - for (auto &key : require_keys) { - REQUIRE(meminfo.find(key) != meminfo.end()); - REQUIRE(meminfo[key] > 0); - } - } -} - -void test_cmdline(std::string cmdline, const std::vector requires) { - std::stringstream ss; - ss.write(&cmdline[0], cmdline.size()); - auto cmds = Parser::cmdline(ss); - REQUIRE(cmds.size() == requires.size()); - for (int i = 0; i < requires.size(); ++i) { - REQUIRE(cmds[i] == requires[i]); - } -} -TEST_CASE("Parser::cmdline") { - test_cmdline(std::string("a\0b\0c\0", 7), {"a", "b", "c"}); - test_cmdline(std::string("a\0\0c\0", 6), {"a", "c"}); - test_cmdline(std::string("a\0b\0c\0\0\0", 9), {"a", "b", "c"}); -} - -TEST_CASE("buildProcLoggerMessage") { - MessageBuilder msg; - buildProcLogMessage(msg); - - kj::Array buf = capnp::messageToFlatArray(msg); - capnp::FlatArrayMessageReader reader(buf); - auto log = reader.getRoot().getProcLog(); - REQUIRE(log.totalSize().wordCount > 0); - - // test cereal::ProcLog::CPUTimes - auto cpu_times = log.getCpuTimes(); - REQUIRE(cpu_times.size() == sysconf(_SC_NPROCESSORS_ONLN)); - REQUIRE(cpu_times[cpu_times.size() - 1].getCpuNum() == cpu_times.size() - 1); - - // test cereal::ProcLog::Mem - auto mem = log.getMem(); - REQUIRE(mem.getTotal() > 0); - REQUIRE(mem.getShared() > 0); - - // test cereal::ProcLog::Process - auto procs = log.getProcs(); - for (auto p : procs) { - REQUIRE(allowed_states.find(p.getState()) != std::string::npos); - if (p.getPid() == ::getpid()) { - REQUIRE(p.getName() == "test_proclog"); - REQUIRE(p.getState() == 'R'); - REQUIRE_THAT(p.getExe().cStr(), Catch::Matchers::Contains("test_proclog")); - REQUIRE_THAT(p.getCmdline()[0], Catch::Matchers::Contains("test_proclog")); - } - } -} diff --git a/system/qcomgpsd/nmeaport.py b/system/qcomgpsd/nmeaport.py index 8b9ab510864e98..10b8516ed09d7e 100644 --- a/system/qcomgpsd/nmeaport.py +++ b/system/qcomgpsd/nmeaport.py @@ -107,11 +107,11 @@ def process_nmea_port_messages(device:str="/dev/ttyUSB1") -> NoReturn: match fields[0]: case "$GNCLK": # fields at end are reserved (not used) - gnss_clock = GnssClockNmeaPort(*fields[1:10]) # type: ignore[arg-type] + gnss_clock = GnssClockNmeaPort(*fields[1:10]) print(gnss_clock) case "$GNMEAS": # fields at end are reserved (not used) - gnss_meas = GnssMeasNmeaPort(*fields[1:14]) # type: ignore[arg-type] + gnss_meas = GnssMeasNmeaPort(*fields[1:14]) print(gnss_meas) except Exception as e: print(e) diff --git a/system/qcomgpsd/qcomgpsd.py b/system/qcomgpsd/qcomgpsd.py index 43ddb8993994ca..7e0d30487206bb 100755 --- a/system/qcomgpsd/qcomgpsd.py +++ b/system/qcomgpsd/qcomgpsd.py @@ -1,23 +1,21 @@ #!/usr/bin/env python3 +import fcntl import os import sys import signal import itertools import math import time -import requests -import shutil -import subprocess +from serial import Serial import datetime -from multiprocessing import Process, Event from typing import NoReturn from struct import unpack_from, calcsize, pack from cereal import log import cereal.messaging as messaging from openpilot.common.gpio import gpio_init, gpio_set -from openpilot.common.retry import retry -from openpilot.common.time import system_time_valid +from openpilot.common.utils import retry +from openpilot.common.time_helpers import system_time_valid from openpilot.system.hardware.tici.pins import GPIO from openpilot.common.swaglog import cloudlog from openpilot.system.qcomgpsd.modemdiag import ModemDiag, DIAG_LOG_F, setup_logs, send_recv @@ -30,9 +28,6 @@ LOG_GNSS_OEMDRE_SVPOLY_REPORT) DEBUG = int(os.getenv("DEBUG", "0"))==1 -ASSIST_DATA_FILE = '/tmp/xtra3grc.bin' -ASSIST_DATA_FILE_DOWNLOAD = ASSIST_DATA_FILE + '.download' -ASSISTANCE_URL = 'http://xtrapath3.izatcloud.net/xtra3grc.bin' LOG_TYPES = [ LOG_GNSS_GPS_MEASUREMENT_REPORT, @@ -90,55 +85,33 @@ def try_setup_logs(diag, logs): return setup_logs(diag, logs) -@retry(attempts=3, delay=1.0) -def at_cmd(cmd: str) -> str | None: - return subprocess.check_output(f"mmcli -m any --timeout 30 --command='{cmd}'", shell=True, encoding='utf8') +AT_PORT = "/dev/modem_at0" +AT_LOCK = "/dev/shm/modem.lock" # shared with modem.py and LPA + +@retry(attempts=5, delay=1.0) +def at_cmd(cmd: str) -> str: + with os.fdopen(os.open(AT_LOCK, os.O_CREAT | os.O_RDWR, 0o666), "r+") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + with Serial(AT_PORT, baudrate=115200, timeout=5) as ser: + ser.reset_input_buffer() + ser.write(f"{cmd}\r".encode()) + lines = [] + while True: + line = ser.readline() + if not line: + raise RuntimeError(f"AT command timeout: {cmd}") + line = line.decode('utf-8', errors='replace').strip() + if line in ("OK", "ERROR") or line.startswith("+CME ERROR"): + break + if line and line != cmd: + lines.append(line) + return '\n'.join(lines) def gps_enabled() -> bool: return "QGPS: 1" in at_cmd("AT+QGPS?") -def download_assistance(): - try: - response = requests.get(ASSISTANCE_URL, timeout=5, stream=True) - - with open(ASSIST_DATA_FILE_DOWNLOAD, 'wb') as fp: - for chunk in response.iter_content(chunk_size=8192): - fp.write(chunk) - if fp.tell() > 1e5: - cloudlog.error("Qcom assistance data larger than expected") - return - - os.rename(ASSIST_DATA_FILE_DOWNLOAD, ASSIST_DATA_FILE) - - except requests.exceptions.RequestException: - cloudlog.exception("Failed to download assistance file") - return - -def downloader_loop(event): - if os.path.exists(ASSIST_DATA_FILE): - os.remove(ASSIST_DATA_FILE) - - alt_path = os.getenv("QCOM_ALT_ASSISTANCE_PATH", None) - if alt_path is not None and os.path.exists(alt_path): - shutil.copyfile(alt_path, ASSIST_DATA_FILE) - - try: - while not os.path.exists(ASSIST_DATA_FILE) and not event.is_set(): - download_assistance() - event.wait(timeout=10) - except KeyboardInterrupt: - pass - -@retry(attempts=5, delay=0.2, ignore_failure=True) -def inject_assistance(): - cmd = f"mmcli -m any --timeout 30 --location-inject-assistance-data={ASSIST_DATA_FILE}" - subprocess.check_output(cmd, stderr=subprocess.PIPE, shell=True) - cloudlog.info("successfully loaded assistance data") - @retry(attempts=5, delay=1.0) -def setup_quectel(diag: ModemDiag) -> bool: - ret = False - +def setup_quectel(diag: ModemDiag): # enable OEMDRE in the NV # TODO: it has to reboot for this to take effect DIAG_NV_READ_F = 38 @@ -152,26 +125,11 @@ def setup_quectel(diag: ModemDiag) -> bool: if gps_enabled(): at_cmd("AT+QGPSEND") - if "GPS_COLD_START" in os.environ: - # deletes all assistance - at_cmd("AT+QGPSDEL=0") - else: - # allow module to perform hot start - at_cmd("AT+QGPSDEL=1") - # disable DPO power savings for more accuracy at_cmd("AT+QGPSCFG=\"dpoenable\",0") # don't automatically turn on GNSS on powerup at_cmd("AT+QGPSCFG=\"autogps\",0") - # Do internet assistance - at_cmd("AT+QGPSXTRA=1") - at_cmd("AT+QGPSSUPLURL=\"NULL\"") - if os.path.exists(ASSIST_DATA_FILE): - ret = True - inject_assistance() - os.remove(ASSIST_DATA_FILE) - #at_cmd("AT+QGPSXTRADATA?") if system_time_valid(): time_str = datetime.datetime.now(datetime.UTC).replace(tzinfo=None).strftime("%Y/%m/%d,%H:%M:%S") at_cmd(f"AT+QGPSXTRATIME=0,\"{time_str}\",1,1,1000") @@ -198,7 +156,6 @@ def setup_quectel(diag: ModemDiag) -> bool: 0,0 )) - return ret def teardown_quectel(diag): at_cmd("AT+QGPSCFG=\"outport\",\"none\"") @@ -207,13 +164,19 @@ def teardown_quectel(diag): try_setup_logs(diag, []) -def wait_for_modem(cmd="AT+QGPS?"): +def wait_for_modem(): cloudlog.warning("waiting for modem to come up") + while not os.path.exists(AT_PORT): + time.sleep(0.5) + # wait until the modem GNSS subsystem responds while True: - ret = subprocess.call(f"mmcli -m any --timeout 10 --command=\"{cmd}\"", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True) - if ret == 0: - return - time.sleep(0.1) + try: + resp = at_cmd("AT+QGPS?") + if "+QGPS:" in resp: + return + except Exception: + pass + time.sleep(0.5) def main() -> NoReturn: @@ -233,19 +196,15 @@ def main() -> NoReturn: wait_for_modem() - stop_download_event = Event() - assist_fetch_proc = Process(target=downloader_loop, args=(stop_download_event,)) - assist_fetch_proc.start() def cleanup(sig, frame): cloudlog.warning("caught sig disabling quectel gps") gpio_set(GPIO.GNSS_PWR_EN, False) - teardown_quectel(diag) - cloudlog.warning("quectel cleanup done") - - stop_download_event.set() - assist_fetch_proc.kill() - assist_fetch_proc.join() + try: + teardown_quectel(diag) + cloudlog.warning("quectel cleanup done") + except NameError: + cloudlog.warning('quectel not yet setup') sys.exit(0) signal.signal(signal.SIGINT, cleanup) @@ -253,8 +212,7 @@ def cleanup(sig, frame): # connect to modem diag = ModemDiag() - r = setup_quectel(diag) - want_assistance = not r + setup_quectel(diag) cloudlog.warning("quectel setup done") gpio_init(GPIO.GNSS_PWR_EN, True) gpio_set(GPIO.GNSS_PWR_EN, True) @@ -262,10 +220,6 @@ def cleanup(sig, frame): pm = messaging.PubMaster(['qcomGnss', 'gpsLocation']) while 1: - if os.path.exists(ASSIST_DATA_FILE) and want_assistance: - setup_quectel(diag) - want_assistance = False - opcode, payload = diag.recv() if opcode != DIAG_LOG_F: cloudlog.error(f"Unhandled opcode: {opcode}") @@ -273,7 +227,7 @@ def cleanup(sig, frame): (pending_msgs, log_outer_length), inner_log_packet = unpack_from(' 0: - cloudlog.debug("have %d pending messages" % pending_msgs) + cloudlog.debug(f"have {pending_msgs} pending messages") assert log_outer_length == len(inner_log_packet) (log_inner_length, log_type, log_time), log_payload = unpack_from('= 0xFFFF: + continue vNED = [report["q_FltVelEnuMps[1]"], report["q_FltVelEnuMps[0]"], -report["q_FltVelEnuMps[2]"]] vNEDsigma = [report["q_FltVelSigmaMps[1]"], report["q_FltVelSigmaMps[0]"], -report["q_FltVelSigmaMps[2]"]] @@ -355,9 +312,6 @@ def cleanup(sig, frame): gps.speedAccuracy = math.sqrt(sum([x**2 for x in vNEDsigma])) # quectel gps verticalAccuracy is clipped to 500, set invalid if so gps.hasFix = gps.verticalAccuracy != 500 - if gps.hasFix: - want_assistance = False - stop_download_event.set() pm.send('gpsLocation', msg) elif log_type == LOG_GNSS_OEMDRE_SVPOLY_REPORT: diff --git a/system/qcomgpsd/structs.py b/system/qcomgpsd/structs.py index f97704bbee6791..497493a0bf2077 100644 --- a/system/qcomgpsd/structs.py +++ b/system/qcomgpsd/structs.py @@ -322,7 +322,7 @@ def parse_struct(ss): cnt = int(nam.split("[")[1].split("]")[0]) st += st[-1]*(cnt-1) for i in range(cnt): - nams.append("%s[%d]" % (nam.split("[")[0], i)) + nams.append(f'{nam.split("[")[0]}[{i}]') else: nams.append(nam) return st, nams diff --git a/system/qcomgpsd/tests/test_qcomgpsd.py b/system/qcomgpsd/tests/test_qcomgpsd.py deleted file mode 100644 index 716bc33ed21b6a..00000000000000 --- a/system/qcomgpsd/tests/test_qcomgpsd.py +++ /dev/null @@ -1,119 +0,0 @@ -import os -import pytest -import json -import time -import datetime -import subprocess - -import cereal.messaging as messaging -from openpilot.system.qcomgpsd.qcomgpsd import at_cmd, wait_for_modem -from openpilot.system.manager.process_config import managed_processes - -GOOD_SIGNAL = bool(int(os.getenv("GOOD_SIGNAL", '0'))) - - -@pytest.mark.tici -class TestRawgpsd: - @classmethod - def setup_class(cls): - os.system("sudo systemctl start systemd-resolved") - os.system("sudo systemctl restart ModemManager lte") - wait_for_modem() - - @classmethod - def teardown_class(cls): - managed_processes['qcomgpsd'].stop() - os.system("sudo systemctl restart systemd-resolved") - os.system("sudo systemctl restart ModemManager lte") - - def setup_method(self): - at_cmd("AT+QGPSDEL=0") - self.sm = messaging.SubMaster(['qcomGnss', 'gpsLocation', 'gnssMeasurements']) - - def teardown_method(self): - managed_processes['qcomgpsd'].stop() - os.system("sudo systemctl restart systemd-resolved") - - def _wait_for_output(self, t): - dt = 0.1 - for _ in range(t*int(1/dt)): - self.sm.update(0) - if self.sm.updated['qcomGnss']: - break - time.sleep(dt) - return self.sm.updated['qcomGnss'] - - def test_no_crash_double_command(self): - at_cmd("AT+QGPSDEL=0") - at_cmd("AT+QGPSDEL=0") - - def test_wait_for_modem(self): - os.system("sudo systemctl stop ModemManager") - managed_processes['qcomgpsd'].start() - assert not self._wait_for_output(5) - - os.system("sudo systemctl restart ModemManager") - assert self._wait_for_output(30) - - def test_startup_time(self, subtests): - for internet in (True, False): - if not internet: - os.system("sudo systemctl stop systemd-resolved") - with subtests.test(internet=internet): - managed_processes['qcomgpsd'].start() - assert self._wait_for_output(7) - managed_processes['qcomgpsd'].stop() - - def test_turns_off_gnss(self, subtests): - for s in (0.1, 1, 5): - with subtests.test(runtime=s): - managed_processes['qcomgpsd'].start() - time.sleep(s) - managed_processes['qcomgpsd'].stop() - - ls = subprocess.check_output("mmcli -m any --location-status --output-json", shell=True, encoding='utf-8') - loc_status = json.loads(ls) - assert set(loc_status['modem']['location']['enabled']) <= {'3gpp-lac-ci'} - - - def check_assistance(self, should_be_loaded): - # after QGPSDEL: '+QGPSXTRADATA: 0,"1980/01/05,19:00:00"' - # after loading: '+QGPSXTRADATA: 10080,"2023/06/24,19:00:00"' - out = at_cmd("AT+QGPSXTRADATA?") - out = out.split("+QGPSXTRADATA:")[1].split("'")[0].strip() - valid_duration, injected_time_str = out.split(",", 1) - if should_be_loaded: - assert valid_duration == "10080" # should be max time - injected_time = datetime.datetime.strptime(injected_time_str.replace("\"", ""), "%Y/%m/%d,%H:%M:%S") - assert abs((datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - injected_time).total_seconds()) < 60*60*12 - else: - valid_duration, injected_time_str = out.split(",", 1) - injected_time_str = injected_time_str.replace('\"', '').replace('\'', '') - assert injected_time_str[:] == '1980/01/05,19:00:00'[:] - assert valid_duration == '0' - - def test_assistance_loading(self): - managed_processes['qcomgpsd'].start() - assert self._wait_for_output(10) - managed_processes['qcomgpsd'].stop() - self.check_assistance(True) - - def test_no_assistance_loading(self): - os.system("sudo systemctl stop systemd-resolved") - - managed_processes['qcomgpsd'].start() - assert self._wait_for_output(10) - managed_processes['qcomgpsd'].stop() - self.check_assistance(False) - - def test_late_assistance_loading(self): - os.system("sudo systemctl stop systemd-resolved") - - managed_processes['qcomgpsd'].start() - self._wait_for_output(17) - assert self.sm.updated['qcomGnss'] - - os.system("sudo systemctl restart systemd-resolved") - time.sleep(15) - managed_processes['qcomgpsd'].stop() - self.check_assistance(True) diff --git a/system/sensord/.gitignore b/system/sensord/.gitignore deleted file mode 100644 index e17675e254285f..00000000000000 --- a/system/sensord/.gitignore +++ /dev/null @@ -1 +0,0 @@ -sensord diff --git a/system/sensord/SConscript b/system/sensord/SConscript deleted file mode 100644 index e2dfb522c61897..00000000000000 --- a/system/sensord/SConscript +++ /dev/null @@ -1,17 +0,0 @@ -Import('env', 'arch', 'common', 'messaging') - -sensors = [ - 'sensors/i2c_sensor.cc', - 'sensors/bmx055_accel.cc', - 'sensors/bmx055_gyro.cc', - 'sensors/bmx055_magn.cc', - 'sensors/bmx055_temp.cc', - 'sensors/lsm6ds3_accel.cc', - 'sensors/lsm6ds3_gyro.cc', - 'sensors/lsm6ds3_temp.cc', - 'sensors/mmc5603nj_magn.cc', -] -libs = [common, messaging, 'pthread'] -if arch == "larch64": - libs.append('i2c') -env.Program('sensord', ['sensors_qcom2.cc'] + sensors, LIBS=libs) diff --git a/system/sensord/sensord.py b/system/sensord/sensord.py new file mode 100755 index 00000000000000..ce6fb9ccb24340 --- /dev/null +++ b/system/sensord/sensord.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +import os +import time +import ctypes +import select +import threading + +import cereal.messaging as messaging +from cereal.services import SERVICE_LIST +from openpilot.common.utils import sudo_write +from openpilot.common.realtime import config_realtime_process, Ratekeeper +from openpilot.common.swaglog import cloudlog +from openpilot.common.gpio import gpiochip_get_ro_value_fd, gpioevent_data + +from openpilot.system.sensord.sensors.i2c_sensor import Sensor +from openpilot.system.sensord.sensors.lsm6ds3_accel import LSM6DS3_Accel +from openpilot.system.sensord.sensors.lsm6ds3_gyro import LSM6DS3_Gyro +from openpilot.system.sensord.sensors.lsm6ds3_temp import LSM6DS3_Temp + +I2C_BUS_IMU = 1 + +def interrupt_loop(sensors: list[tuple[Sensor, str, bool]], event) -> None: + pm = messaging.PubMaster([service for sensor, service, interrupt in sensors if interrupt]) + + # NOTE: the gyro and accelerometer share an IRQ due to the comma three + # routing only one GPIO from the LSM to the SOC, but comma 3X and four + # have two. if we want better timestamps in the future, we can use both. + + # Requesting both edges as the data ready pulse from the lsm6ds sensor is + # very short (75us) and is mostly detected as falling edge instead of rising. + # So if it is detected as rising the following falling edge is skipped. + fd = gpiochip_get_ro_value_fd("sensord", 0, 84) + + # Configure IRQ affinity + irq_path = "/proc/irq/336/smp_affinity_list" + if not os.path.exists(irq_path): + irq_path = "/proc/irq/335/smp_affinity_list" + if os.path.exists(irq_path): + sudo_write('1\n', irq_path) + + offset = time.time_ns() - time.monotonic_ns() + + poller = select.poll() + poller.register(fd, select.POLLIN | select.POLLPRI) + while not event.is_set(): + events = poller.poll(100) + if not events: + cloudlog.error("poll timed out") + continue + if not (events[0][1] & (select.POLLIN | select.POLLPRI)): + cloudlog.error("no poll events set") + continue + + dat = os.read(fd, ctypes.sizeof(gpioevent_data)*16) + evd = gpioevent_data.from_buffer_copy(dat) + + cur_offset = time.time_ns() - time.monotonic_ns() + if abs(cur_offset - offset) > 10 * 1e6: # ms + cloudlog.warning(f"time jumped: {cur_offset} {offset}") + offset = cur_offset + continue + + ts = evd.timestamp - cur_offset + for sensor, service, interrupt in sensors: + if interrupt: + try: + evt = sensor.get_event(ts) + if not sensor.is_data_valid(): + continue + msg = messaging.new_message(service, valid=True) + setattr(msg, service, evt) + pm.send(service, msg) + except Sensor.DataNotReady: + pass + except Exception: + cloudlog.exception(f"Error processing {service}") + + +def polling_loop(sensor: Sensor, service: str, event: threading.Event) -> None: + pm = messaging.PubMaster([service]) + rk = Ratekeeper(SERVICE_LIST[service].frequency, print_delay_threshold=None) + while not event.is_set(): + try: + evt = sensor.get_event() + if not sensor.is_data_valid(): + continue + msg = messaging.new_message(service, valid=True) + setattr(msg, service, evt) + pm.send(service, msg) + except Exception: + cloudlog.exception(f"Error in {service} polling loop") + rk.keep_time() + +def main() -> None: + config_realtime_process([1, ], 1) + + sensors_cfg = [ + (LSM6DS3_Accel(I2C_BUS_IMU), "accelerometer", True), + (LSM6DS3_Gyro(I2C_BUS_IMU), "gyroscope", True), + (LSM6DS3_Temp(I2C_BUS_IMU), "temperatureSensor", False), + ] + + # Reset sensors + for sensor, _, _ in sensors_cfg: + try: + sensor.reset() + except Exception: + cloudlog.exception(f"Error initializing {sensor} sensor") + + # Initialize sensors + exit_event = threading.Event() + threads = [ + threading.Thread(target=interrupt_loop, args=(sensors_cfg, exit_event), daemon=True) + ] + for sensor, service, interrupt in sensors_cfg: + try: + sensor.init() + if not interrupt: + # Start polling thread for sensors without interrupts + threads.append(threading.Thread( + target=polling_loop, + args=(sensor, service, exit_event), + daemon=True + )) + except Exception: + cloudlog.exception(f"Error initializing {service} sensor") + + try: + for t in threads: + t.start() + while any(t.is_alive() for t in threads): + time.sleep(1) + except KeyboardInterrupt: + pass + finally: + exit_event.set() + for t in threads: + if t.is_alive(): + t.join() + + for sensor, _, _ in sensors_cfg: + try: + sensor.shutdown() + except Exception: + cloudlog.exception("Error shutting down sensor") + +if __name__ == "__main__": + main() diff --git a/system/sensord/sensors/__init__.py b/system/sensord/sensors/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/system/sensord/sensors/bmx055_accel.cc b/system/sensord/sensors/bmx055_accel.cc deleted file mode 100644 index bdb0113de3e14c..00000000000000 --- a/system/sensord/sensors/bmx055_accel.cc +++ /dev/null @@ -1,78 +0,0 @@ -#include "system/sensord/sensors/bmx055_accel.h" - -#include - -#include "common/swaglog.h" -#include "common/timing.h" -#include "common/util.h" - -BMX055_Accel::BMX055_Accel(I2CBus *bus) : I2CSensor(bus) {} - -int BMX055_Accel::init() { - int ret = verify_chip_id(BMX055_ACCEL_I2C_REG_ID, {BMX055_ACCEL_CHIP_ID}); - if (ret == -1) return -1; - - ret = set_register(BMX055_ACCEL_I2C_REG_PMU, BMX055_ACCEL_NORMAL_MODE); - if (ret < 0) { - goto fail; - } - // bmx055 accel has a 1.3ms wakeup time from deep suspend mode - util::sleep_for(10); - - // High bandwidth - // ret = set_register(BMX055_ACCEL_I2C_REG_HBW, BMX055_ACCEL_HBW_ENABLE); - // if (ret < 0) { - // goto fail; - // } - - // Low bandwidth - ret = set_register(BMX055_ACCEL_I2C_REG_HBW, BMX055_ACCEL_HBW_DISABLE); - if (ret < 0) { - goto fail; - } - - ret = set_register(BMX055_ACCEL_I2C_REG_BW, BMX055_ACCEL_BW_125HZ); - if (ret < 0) { - goto fail; - } - -fail: - return ret; -} - -int BMX055_Accel::shutdown() { - // enter deep suspend mode (lowest power mode) - int ret = set_register(BMX055_ACCEL_I2C_REG_PMU, BMX055_ACCEL_DEEP_SUSPEND); - if (ret < 0) { - LOGE("Could not move BMX055 ACCEL in deep suspend mode!"); - } - - return ret; -} - -bool BMX055_Accel::get_event(MessageBuilder &msg, uint64_t ts) { - uint64_t start_time = nanos_since_boot(); - uint8_t buffer[6]; - int len = read_register(BMX055_ACCEL_I2C_REG_X_LSB, buffer, sizeof(buffer)); - assert(len == 6); - - // 12 bit = +-2g - float scale = 9.81 * 2.0f / (1 << 11); - float x = -read_12_bit(buffer[0], buffer[1]) * scale; - float y = -read_12_bit(buffer[2], buffer[3]) * scale; - float z = read_12_bit(buffer[4], buffer[5]) * scale; - - auto event = msg.initEvent().initAccelerometer2(); - event.setSource(cereal::SensorEventData::SensorSource::BMX055); - event.setVersion(1); - event.setSensor(SENSOR_ACCELEROMETER); - event.setType(SENSOR_TYPE_ACCELEROMETER); - event.setTimestamp(start_time); - - float xyz[] = {x, y, z}; - auto svec = event.initAcceleration(); - svec.setV(xyz); - svec.setStatus(true); - - return true; -} diff --git a/system/sensord/sensors/bmx055_accel.h b/system/sensord/sensors/bmx055_accel.h deleted file mode 100644 index 2cc316e992521b..00000000000000 --- a/system/sensord/sensors/bmx055_accel.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include "system/sensord/sensors/i2c_sensor.h" - -// Address of the chip on the bus -#define BMX055_ACCEL_I2C_ADDR 0x18 - -// Registers of the chip -#define BMX055_ACCEL_I2C_REG_ID 0x00 -#define BMX055_ACCEL_I2C_REG_X_LSB 0x02 -#define BMX055_ACCEL_I2C_REG_TEMP 0x08 -#define BMX055_ACCEL_I2C_REG_BW 0x10 -#define BMX055_ACCEL_I2C_REG_PMU 0x11 -#define BMX055_ACCEL_I2C_REG_HBW 0x13 -#define BMX055_ACCEL_I2C_REG_FIFO 0x3F - -// Constants -#define BMX055_ACCEL_CHIP_ID 0xFA - -#define BMX055_ACCEL_HBW_ENABLE 0b10000000 -#define BMX055_ACCEL_HBW_DISABLE 0b00000000 -#define BMX055_ACCEL_DEEP_SUSPEND 0b00100000 -#define BMX055_ACCEL_NORMAL_MODE 0b00000000 - -#define BMX055_ACCEL_BW_7_81HZ 0b01000 -#define BMX055_ACCEL_BW_15_63HZ 0b01001 -#define BMX055_ACCEL_BW_31_25HZ 0b01010 -#define BMX055_ACCEL_BW_62_5HZ 0b01011 -#define BMX055_ACCEL_BW_125HZ 0b01100 -#define BMX055_ACCEL_BW_250HZ 0b01101 -#define BMX055_ACCEL_BW_500HZ 0b01110 -#define BMX055_ACCEL_BW_1000HZ 0b01111 - -class BMX055_Accel : public I2CSensor { - uint8_t get_device_address() {return BMX055_ACCEL_I2C_ADDR;} -public: - BMX055_Accel(I2CBus *bus); - int init(); - bool get_event(MessageBuilder &msg, uint64_t ts = 0); - int shutdown(); -}; diff --git a/system/sensord/sensors/bmx055_gyro.cc b/system/sensord/sensors/bmx055_gyro.cc deleted file mode 100644 index 411b2f445e25d5..00000000000000 --- a/system/sensord/sensors/bmx055_gyro.cc +++ /dev/null @@ -1,88 +0,0 @@ -#include "system/sensord/sensors/bmx055_gyro.h" - -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" - -#define DEG2RAD(x) ((x) * M_PI / 180.0) - - -BMX055_Gyro::BMX055_Gyro(I2CBus *bus) : I2CSensor(bus) {} - -int BMX055_Gyro::init() { - int ret = verify_chip_id(BMX055_GYRO_I2C_REG_ID, {BMX055_GYRO_CHIP_ID}); - if (ret == -1) return -1; - - ret = set_register(BMX055_GYRO_I2C_REG_LPM1, BMX055_GYRO_NORMAL_MODE); - if (ret < 0) { - goto fail; - } - // bmx055 gyro has a 30ms wakeup time from deep suspend mode - util::sleep_for(50); - - // High bandwidth - // ret = set_register(BMX055_GYRO_I2C_REG_HBW, BMX055_GYRO_HBW_ENABLE); - // if (ret < 0) { - // goto fail; - // } - - // Low bandwidth - ret = set_register(BMX055_GYRO_I2C_REG_HBW, BMX055_GYRO_HBW_DISABLE); - if (ret < 0) { - goto fail; - } - - // 116 Hz filter - ret = set_register(BMX055_GYRO_I2C_REG_BW, BMX055_GYRO_BW_116HZ); - if (ret < 0) { - goto fail; - } - - // +- 125 deg/s range - ret = set_register(BMX055_GYRO_I2C_REG_RANGE, BMX055_GYRO_RANGE_125); - if (ret < 0) { - goto fail; - } - -fail: - return ret; -} - -int BMX055_Gyro::shutdown() { - // enter deep suspend mode (lowest power mode) - int ret = set_register(BMX055_GYRO_I2C_REG_LPM1, BMX055_GYRO_DEEP_SUSPEND); - if (ret < 0) { - LOGE("Could not move BMX055 GYRO in deep suspend mode!"); - } - - return ret; -} - -bool BMX055_Gyro::get_event(MessageBuilder &msg, uint64_t ts) { - uint64_t start_time = nanos_since_boot(); - uint8_t buffer[6]; - int len = read_register(BMX055_GYRO_I2C_REG_RATE_X_LSB, buffer, sizeof(buffer)); - assert(len == 6); - - // 16 bit = +- 125 deg/s - float scale = 125.0f / (1 << 15); - float x = -DEG2RAD(read_16_bit(buffer[0], buffer[1]) * scale); - float y = -DEG2RAD(read_16_bit(buffer[2], buffer[3]) * scale); - float z = DEG2RAD(read_16_bit(buffer[4], buffer[5]) * scale); - - auto event = msg.initEvent().initGyroscope2(); - event.setSource(cereal::SensorEventData::SensorSource::BMX055); - event.setVersion(1); - event.setSensor(SENSOR_GYRO_UNCALIBRATED); - event.setType(SENSOR_TYPE_GYROSCOPE_UNCALIBRATED); - event.setTimestamp(start_time); - - float xyz[] = {x, y, z}; - auto svec = event.initGyroUncalibrated(); - svec.setV(xyz); - svec.setStatus(true); - - return true; -} diff --git a/system/sensord/sensors/bmx055_gyro.h b/system/sensord/sensors/bmx055_gyro.h deleted file mode 100644 index 7be3e56563c6be..00000000000000 --- a/system/sensord/sensors/bmx055_gyro.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include "system/sensord/sensors/i2c_sensor.h" - -// Address of the chip on the bus -#define BMX055_GYRO_I2C_ADDR 0x68 - -// Registers of the chip -#define BMX055_GYRO_I2C_REG_ID 0x00 -#define BMX055_GYRO_I2C_REG_RATE_X_LSB 0x02 -#define BMX055_GYRO_I2C_REG_RANGE 0x0F -#define BMX055_GYRO_I2C_REG_BW 0x10 -#define BMX055_GYRO_I2C_REG_LPM1 0x11 -#define BMX055_GYRO_I2C_REG_HBW 0x13 -#define BMX055_GYRO_I2C_REG_FIFO 0x3F - -// Constants -#define BMX055_GYRO_CHIP_ID 0x0F - -#define BMX055_GYRO_HBW_ENABLE 0b10000000 -#define BMX055_GYRO_HBW_DISABLE 0b00000000 -#define BMX055_GYRO_DEEP_SUSPEND 0b00100000 -#define BMX055_GYRO_NORMAL_MODE 0b00000000 - -#define BMX055_GYRO_RANGE_2000 0b000 -#define BMX055_GYRO_RANGE_1000 0b001 -#define BMX055_GYRO_RANGE_500 0b010 -#define BMX055_GYRO_RANGE_250 0b011 -#define BMX055_GYRO_RANGE_125 0b100 - -#define BMX055_GYRO_BW_116HZ 0b0010 - - -class BMX055_Gyro : public I2CSensor { - uint8_t get_device_address() {return BMX055_GYRO_I2C_ADDR;} -public: - BMX055_Gyro(I2CBus *bus); - int init(); - bool get_event(MessageBuilder &msg, uint64_t ts = 0); - int shutdown(); -}; diff --git a/system/sensord/sensors/bmx055_magn.cc b/system/sensord/sensors/bmx055_magn.cc deleted file mode 100644 index 223f0337e8e698..00000000000000 --- a/system/sensord/sensors/bmx055_magn.cc +++ /dev/null @@ -1,256 +0,0 @@ -#include "system/sensord/sensors/bmx055_magn.h" - -#include - -#include -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" - -static int16_t compensate_x(trim_data_t trim_data, int16_t mag_data_x, uint16_t data_rhall) { - uint16_t process_comp_x0 = data_rhall; - int32_t process_comp_x1 = ((int32_t)trim_data.dig_xyz1) * 16384; - uint16_t process_comp_x2 = ((uint16_t)(process_comp_x1 / process_comp_x0)) - ((uint16_t)0x4000); - int16_t retval = ((int16_t)process_comp_x2); - int32_t process_comp_x3 = (((int32_t)retval) * ((int32_t)retval)); - int32_t process_comp_x4 = (((int32_t)trim_data.dig_xy2) * (process_comp_x3 / 128)); - int32_t process_comp_x5 = (int32_t)(((int16_t)trim_data.dig_xy1) * 128); - int32_t process_comp_x6 = ((int32_t)retval) * process_comp_x5; - int32_t process_comp_x7 = (((process_comp_x4 + process_comp_x6) / 512) + ((int32_t)0x100000)); - int32_t process_comp_x8 = ((int32_t)(((int16_t)trim_data.dig_x2) + ((int16_t)0xA0))); - int32_t process_comp_x9 = ((process_comp_x7 * process_comp_x8) / 4096); - int32_t process_comp_x10 = ((int32_t)mag_data_x) * process_comp_x9; - retval = ((int16_t)(process_comp_x10 / 8192)); - retval = (retval + (((int16_t)trim_data.dig_x1) * 8)) / 16; - - return retval; -} - -static int16_t compensate_y(trim_data_t trim_data, int16_t mag_data_y, uint16_t data_rhall) { - uint16_t process_comp_y0 = trim_data.dig_xyz1; - int32_t process_comp_y1 = (((int32_t)trim_data.dig_xyz1) * 16384) / process_comp_y0; - uint16_t process_comp_y2 = ((uint16_t)process_comp_y1) - ((uint16_t)0x4000); - int16_t retval = ((int16_t)process_comp_y2); - int32_t process_comp_y3 = ((int32_t) retval) * ((int32_t)retval); - int32_t process_comp_y4 = ((int32_t)trim_data.dig_xy2) * (process_comp_y3 / 128); - int32_t process_comp_y5 = ((int32_t)(((int16_t)trim_data.dig_xy1) * 128)); - int32_t process_comp_y6 = ((process_comp_y4 + (((int32_t)retval) * process_comp_y5)) / 512); - int32_t process_comp_y7 = ((int32_t)(((int16_t)trim_data.dig_y2) + ((int16_t)0xA0))); - int32_t process_comp_y8 = (((process_comp_y6 + ((int32_t)0x100000)) * process_comp_y7) / 4096); - int32_t process_comp_y9 = (((int32_t)mag_data_y) * process_comp_y8); - retval = (int16_t)(process_comp_y9 / 8192); - retval = (retval + (((int16_t)trim_data.dig_y1) * 8)) / 16; - - return retval; -} - -static int16_t compensate_z(trim_data_t trim_data, int16_t mag_data_z, uint16_t data_rhall) { - int16_t process_comp_z0 = ((int16_t)data_rhall) - ((int16_t) trim_data.dig_xyz1); - int32_t process_comp_z1 = (((int32_t)trim_data.dig_z3) * ((int32_t)(process_comp_z0))) / 4; - int32_t process_comp_z2 = (((int32_t)(mag_data_z - trim_data.dig_z4)) * 32768); - int32_t process_comp_z3 = ((int32_t)trim_data.dig_z1) * (((int16_t)data_rhall) * 2); - int16_t process_comp_z4 = (int16_t)((process_comp_z3 + (32768)) / 65536); - int32_t retval = ((process_comp_z2 - process_comp_z1) / (trim_data.dig_z2 + process_comp_z4)); - - /* saturate result to +/- 2 micro-tesla */ - retval = std::clamp(retval, -32767, 32767); - - /* Conversion of LSB to micro-tesla*/ - retval = retval / 16; - - return (int16_t)retval; -} - -BMX055_Magn::BMX055_Magn(I2CBus *bus) : I2CSensor(bus) {} - -int BMX055_Magn::init() { - uint8_t trim_x1y1[2] = {0}; - uint8_t trim_x2y2[2] = {0}; - uint8_t trim_xy1xy2[2] = {0}; - uint8_t trim_z1[2] = {0}; - uint8_t trim_z2[2] = {0}; - uint8_t trim_z3[2] = {0}; - uint8_t trim_z4[2] = {0}; - uint8_t trim_xyz1[2] = {0}; - - // suspend -> sleep - int ret = set_register(BMX055_MAGN_I2C_REG_PWR_0, 0x01); - if (ret < 0) { - LOGW("Enabling power failed: %d", ret); - goto fail; - } - util::sleep_for(5); // wait until the chip is powered on - - ret = verify_chip_id(BMX055_MAGN_I2C_REG_ID, {BMX055_MAGN_CHIP_ID}); - if (ret == -1) { - goto fail; - } - - // Load magnetometer trim - ret = read_register(BMX055_MAGN_I2C_REG_DIG_X1, trim_x1y1, 2); - if (ret < 0) goto fail; - ret = read_register(BMX055_MAGN_I2C_REG_DIG_X2, trim_x2y2, 2); - if (ret < 0) goto fail; - ret = read_register(BMX055_MAGN_I2C_REG_DIG_XY2, trim_xy1xy2, 2); - if (ret < 0) goto fail; - ret = read_register(BMX055_MAGN_I2C_REG_DIG_Z1_LSB, trim_z1, 2); - if (ret < 0) goto fail; - ret = read_register(BMX055_MAGN_I2C_REG_DIG_Z2_LSB, trim_z2, 2); - if (ret < 0) goto fail; - ret = read_register(BMX055_MAGN_I2C_REG_DIG_Z3_LSB, trim_z3, 2); - if (ret < 0) goto fail; - ret = read_register(BMX055_MAGN_I2C_REG_DIG_Z4_LSB, trim_z4, 2); - if (ret < 0) goto fail; - ret = read_register(BMX055_MAGN_I2C_REG_DIG_XYZ1_LSB, trim_xyz1, 2); - if (ret < 0) goto fail; - - // Read trim data - trim_data.dig_x1 = trim_x1y1[0]; - trim_data.dig_y1 = trim_x1y1[1]; - - trim_data.dig_x2 = trim_x2y2[0]; - trim_data.dig_y2 = trim_x2y2[1]; - - trim_data.dig_xy1 = trim_xy1xy2[1]; // NB: MSB/LSB swapped - trim_data.dig_xy2 = trim_xy1xy2[0]; - - trim_data.dig_z1 = read_16_bit(trim_z1[0], trim_z1[1]); - trim_data.dig_z2 = read_16_bit(trim_z2[0], trim_z2[1]); - trim_data.dig_z3 = read_16_bit(trim_z3[0], trim_z3[1]); - trim_data.dig_z4 = read_16_bit(trim_z4[0], trim_z4[1]); - - trim_data.dig_xyz1 = read_16_bit(trim_xyz1[0], trim_xyz1[1] & 0x7f); - assert(trim_data.dig_xyz1 != 0); - - perform_self_test(); - - // f_max = 1 / (145us * nXY + 500us * NZ + 980us) - // Chose NXY = 7, NZ = 12, which gives 125 Hz, - // and has the same ratio as the high accuracy preset - ret = set_register(BMX055_MAGN_I2C_REG_REPXY, (7 - 1) / 2); - if (ret < 0) { - goto fail; - } - - ret = set_register(BMX055_MAGN_I2C_REG_REPZ, 12 - 1); - if (ret < 0) { - goto fail; - } - - - return 0; - - fail: - return ret; -} - -int BMX055_Magn::shutdown() { - // move to suspend mode - int ret = set_register(BMX055_MAGN_I2C_REG_PWR_0, 0); - if (ret < 0) { - LOGE("Could not move BMX055 MAGN in suspend mode!"); - } - - return ret; -} - -bool BMX055_Magn::perform_self_test() { - uint8_t buffer[8]; - int16_t x, y; - int16_t neg_z, pos_z; - - // Increase z reps for less false positives (~30 Hz ODR) - set_register(BMX055_MAGN_I2C_REG_REPXY, 1); - set_register(BMX055_MAGN_I2C_REG_REPZ, 64 - 1); - - // Clean existing measurement - read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); - - uint8_t forced = BMX055_MAGN_FORCED; - - // Negative current - set_register(BMX055_MAGN_I2C_REG_MAG, forced | (uint8_t(0b10) << 6)); - util::sleep_for(100); - - read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); - parse_xyz(buffer, &x, &y, &neg_z); - - // Positive current - set_register(BMX055_MAGN_I2C_REG_MAG, forced | (uint8_t(0b11) << 6)); - util::sleep_for(100); - - read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); - parse_xyz(buffer, &x, &y, &pos_z); - - // Put back in normal mode - set_register(BMX055_MAGN_I2C_REG_MAG, 0); - - int16_t diff = pos_z - neg_z; - bool passed = (diff > 180) && (diff < 240); - - if (!passed) { - LOGE("self test failed: neg %d pos %d diff %d", neg_z, pos_z, diff); - } - - return passed; -} - -bool BMX055_Magn::parse_xyz(uint8_t buffer[8], int16_t *x, int16_t *y, int16_t *z) { - bool ready = buffer[6] & 0x1; - if (ready) { - int16_t mdata_x = (int16_t) (((int16_t)buffer[1] << 8) | buffer[0]) >> 3; - int16_t mdata_y = (int16_t) (((int16_t)buffer[3] << 8) | buffer[2]) >> 3; - int16_t mdata_z = (int16_t) (((int16_t)buffer[5] << 8) | buffer[4]) >> 1; - uint16_t data_r = (uint16_t) (((uint16_t)buffer[7] << 8) | buffer[6]) >> 2; - assert(data_r != 0); - - *x = compensate_x(trim_data, mdata_x, data_r); - *y = compensate_y(trim_data, mdata_y, data_r); - *z = compensate_z(trim_data, mdata_z, data_r); - } - return ready; -} - - -bool BMX055_Magn::get_event(MessageBuilder &msg, uint64_t ts) { - uint64_t start_time = nanos_since_boot(); - uint8_t buffer[8]; - int16_t _x, _y, x, y, z; - - int len = read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); - assert(len == sizeof(buffer)); - - bool parsed = parse_xyz(buffer, &_x, &_y, &z); - if (parsed) { - - auto event = msg.initEvent().initMagnetometer(); - event.setSource(cereal::SensorEventData::SensorSource::BMX055); - event.setVersion(2); - event.setSensor(SENSOR_MAGNETOMETER_UNCALIBRATED); - event.setType(SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED); - event.setTimestamp(start_time); - - // Move magnetometer into same reference frame as accel/gryo - x = -_y; - y = _x; - - // Axis convention - x = -x; - y = -y; - - float xyz[] = {(float)x, (float)y, (float)z}; - auto svec = event.initMagneticUncalibrated(); - svec.setV(xyz); - svec.setStatus(true); - } - - // The BMX055 Magnetometer has no FIFO mode. Self running mode only goes - // up to 30 Hz. Therefore we put in forced mode, and request measurements - // at a 100 Hz. When reading the registers we have to check the ready bit - // To verify the measurement was completed this cycle. - set_register(BMX055_MAGN_I2C_REG_MAG, BMX055_MAGN_FORCED); - - return parsed; -} diff --git a/system/sensord/sensors/bmx055_magn.h b/system/sensord/sensors/bmx055_magn.h deleted file mode 100644 index 15c4e734b9c691..00000000000000 --- a/system/sensord/sensors/bmx055_magn.h +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once -#include - -#include "system/sensord/sensors/i2c_sensor.h" - -// Address of the chip on the bus -#define BMX055_MAGN_I2C_ADDR 0x10 - -// Registers of the chip -#define BMX055_MAGN_I2C_REG_ID 0x40 -#define BMX055_MAGN_I2C_REG_PWR_0 0x4B -#define BMX055_MAGN_I2C_REG_MAG 0x4C -#define BMX055_MAGN_I2C_REG_DATAX_LSB 0x42 -#define BMX055_MAGN_I2C_REG_RHALL_LSB 0x48 -#define BMX055_MAGN_I2C_REG_REPXY 0x51 -#define BMX055_MAGN_I2C_REG_REPZ 0x52 - -#define BMX055_MAGN_I2C_REG_DIG_X1 0x5D -#define BMX055_MAGN_I2C_REG_DIG_Y1 0x5E -#define BMX055_MAGN_I2C_REG_DIG_Z4_LSB 0x62 -#define BMX055_MAGN_I2C_REG_DIG_Z4_MSB 0x63 -#define BMX055_MAGN_I2C_REG_DIG_X2 0x64 -#define BMX055_MAGN_I2C_REG_DIG_Y2 0x65 -#define BMX055_MAGN_I2C_REG_DIG_Z2_LSB 0x68 -#define BMX055_MAGN_I2C_REG_DIG_Z2_MSB 0x69 -#define BMX055_MAGN_I2C_REG_DIG_Z1_LSB 0x6A -#define BMX055_MAGN_I2C_REG_DIG_Z1_MSB 0x6B -#define BMX055_MAGN_I2C_REG_DIG_XYZ1_LSB 0x6C -#define BMX055_MAGN_I2C_REG_DIG_XYZ1_MSB 0x6D -#define BMX055_MAGN_I2C_REG_DIG_Z3_LSB 0x6E -#define BMX055_MAGN_I2C_REG_DIG_Z3_MSB 0x6F -#define BMX055_MAGN_I2C_REG_DIG_XY2 0x70 -#define BMX055_MAGN_I2C_REG_DIG_XY1 0x71 - -// Constants -#define BMX055_MAGN_CHIP_ID 0x32 -#define BMX055_MAGN_FORCED (0b01 << 1) - -struct trim_data_t { - int8_t dig_x1; - int8_t dig_y1; - int8_t dig_x2; - int8_t dig_y2; - uint16_t dig_z1; - int16_t dig_z2; - int16_t dig_z3; - int16_t dig_z4; - uint8_t dig_xy1; - int8_t dig_xy2; - uint16_t dig_xyz1; -}; - - -class BMX055_Magn : public I2CSensor{ - uint8_t get_device_address() {return BMX055_MAGN_I2C_ADDR;} - trim_data_t trim_data = {0}; - bool perform_self_test(); - bool parse_xyz(uint8_t buffer[8], int16_t *x, int16_t *y, int16_t *z); -public: - BMX055_Magn(I2CBus *bus); - int init(); - bool get_event(MessageBuilder &msg, uint64_t ts = 0); - int shutdown(); -}; diff --git a/system/sensord/sensors/bmx055_temp.cc b/system/sensord/sensors/bmx055_temp.cc deleted file mode 100644 index da7b86476cfa7c..00000000000000 --- a/system/sensord/sensors/bmx055_temp.cc +++ /dev/null @@ -1,31 +0,0 @@ -#include "system/sensord/sensors/bmx055_temp.h" - -#include - -#include "system/sensord/sensors/bmx055_accel.h" -#include "common/swaglog.h" -#include "common/timing.h" - -BMX055_Temp::BMX055_Temp(I2CBus *bus) : I2CSensor(bus) {} - -int BMX055_Temp::init() { - return verify_chip_id(BMX055_ACCEL_I2C_REG_ID, {BMX055_ACCEL_CHIP_ID}) == -1 ? -1 : 0; -} - -bool BMX055_Temp::get_event(MessageBuilder &msg, uint64_t ts) { - uint64_t start_time = nanos_since_boot(); - uint8_t buffer[1]; - int len = read_register(BMX055_ACCEL_I2C_REG_TEMP, buffer, sizeof(buffer)); - assert(len == sizeof(buffer)); - - float temp = 23.0f + int8_t(buffer[0]) / 2.0f; - - auto event = msg.initEvent().initTemperatureSensor(); - event.setSource(cereal::SensorEventData::SensorSource::BMX055); - event.setVersion(1); - event.setType(SENSOR_TYPE_AMBIENT_TEMPERATURE); - event.setTimestamp(start_time); - event.setTemperature(temp); - - return true; -} diff --git a/system/sensord/sensors/bmx055_temp.h b/system/sensord/sensors/bmx055_temp.h deleted file mode 100644 index a2eabae395c4b1..00000000000000 --- a/system/sensord/sensors/bmx055_temp.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include "system/sensord/sensors/bmx055_accel.h" -#include "system/sensord/sensors/i2c_sensor.h" - -class BMX055_Temp : public I2CSensor { - uint8_t get_device_address() {return BMX055_ACCEL_I2C_ADDR;} -public: - BMX055_Temp(I2CBus *bus); - int init(); - bool get_event(MessageBuilder &msg, uint64_t ts = 0); - int shutdown() { return 0; } -}; diff --git a/system/sensord/sensors/constants.h b/system/sensord/sensors/constants.h deleted file mode 100644 index c216f838a5ab0e..00000000000000 --- a/system/sensord/sensors/constants.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - - -#define SENSOR_ACCELEROMETER 1 -#define SENSOR_MAGNETOMETER 2 -#define SENSOR_MAGNETOMETER_UNCALIBRATED 3 -#define SENSOR_GYRO 4 -#define SENSOR_GYRO_UNCALIBRATED 5 -#define SENSOR_LIGHT 7 - -#define SENSOR_TYPE_ACCELEROMETER 1 -#define SENSOR_TYPE_GEOMAGNETIC_FIELD 2 -#define SENSOR_TYPE_GYROSCOPE 4 -#define SENSOR_TYPE_LIGHT 5 -#define SENSOR_TYPE_AMBIENT_TEMPERATURE 13 -#define SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED 14 -#define SENSOR_TYPE_MAGNETIC_FIELD SENSOR_TYPE_GEOMAGNETIC_FIELD -#define SENSOR_TYPE_GYROSCOPE_UNCALIBRATED 16 diff --git a/system/sensord/sensors/i2c_sensor.cc b/system/sensord/sensors/i2c_sensor.cc deleted file mode 100644 index 90220f551dcb7b..00000000000000 --- a/system/sensord/sensors/i2c_sensor.cc +++ /dev/null @@ -1,50 +0,0 @@ -#include "system/sensord/sensors/i2c_sensor.h" - -int16_t read_12_bit(uint8_t lsb, uint8_t msb) { - uint16_t combined = (uint16_t(msb) << 8) | uint16_t(lsb & 0xF0); - return int16_t(combined) / (1 << 4); -} - -int16_t read_16_bit(uint8_t lsb, uint8_t msb) { - uint16_t combined = (uint16_t(msb) << 8) | uint16_t(lsb); - return int16_t(combined); -} - -int32_t read_20_bit(uint8_t b2, uint8_t b1, uint8_t b0) { - uint32_t combined = (uint32_t(b0) << 16) | (uint32_t(b1) << 8) | uint32_t(b2); - return int32_t(combined) / (1 << 4); -} - -I2CSensor::I2CSensor(I2CBus *bus, int gpio_nr, bool shared_gpio) : - bus(bus), gpio_nr(gpio_nr), shared_gpio(shared_gpio) {} - -I2CSensor::~I2CSensor() { - if (gpio_fd != -1) { - close(gpio_fd); - } -} - -int I2CSensor::read_register(uint register_address, uint8_t *buffer, uint8_t len) { - return bus->read_register(get_device_address(), register_address, buffer, len); -} - -int I2CSensor::set_register(uint register_address, uint8_t data) { - return bus->set_register(get_device_address(), register_address, data); -} - -int I2CSensor::init_gpio() { - if (shared_gpio || gpio_nr == 0) { - return 0; - } - - gpio_fd = gpiochip_get_ro_value_fd("sensord", GPIOCHIP_INT, gpio_nr); - if (gpio_fd < 0) { - return -1; - } - - return 0; -} - -bool I2CSensor::has_interrupt_enabled() { - return gpio_nr != 0; -} diff --git a/system/sensord/sensors/i2c_sensor.h b/system/sensord/sensors/i2c_sensor.h deleted file mode 100644 index 6082510083ad3a..00000000000000 --- a/system/sensord/sensors/i2c_sensor.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include -#include -#include -#include "cereal/gen/cpp/log.capnp.h" - -#include "common/i2c.h" -#include "common/gpio.h" - -#include "common/swaglog.h" -#include "system/sensord/sensors/constants.h" -#include "system/sensord/sensors/sensor.h" - -int16_t read_12_bit(uint8_t lsb, uint8_t msb); -int16_t read_16_bit(uint8_t lsb, uint8_t msb); -int32_t read_20_bit(uint8_t b2, uint8_t b1, uint8_t b0); - - -class I2CSensor : public Sensor { -private: - I2CBus *bus; - int gpio_nr; - bool shared_gpio; - virtual uint8_t get_device_address() = 0; - -public: - I2CSensor(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); - ~I2CSensor(); - int read_register(uint register_address, uint8_t *buffer, uint8_t len); - int set_register(uint register_address, uint8_t data); - int init_gpio(); - bool has_interrupt_enabled(); - virtual int init() = 0; - virtual bool get_event(MessageBuilder &msg, uint64_t ts = 0) = 0; - virtual int shutdown() = 0; - - int verify_chip_id(uint8_t address, const std::vector &expected_ids) { - uint8_t chip_id = 0; - int ret = read_register(address, &chip_id, 1); - if (ret < 0) { - LOGW("Reading chip ID failed: %d", ret); - return -1; - } - for (int i = 0; i < expected_ids.size(); ++i) { - if (chip_id == expected_ids[i]) return chip_id; - } - LOGE("Chip ID wrong. Got: %d, Expected %d", chip_id, expected_ids[0]); - return -1; - } -}; diff --git a/system/sensord/sensors/i2c_sensor.py b/system/sensord/sensors/i2c_sensor.py new file mode 100644 index 00000000000000..57edcc52d9056f --- /dev/null +++ b/system/sensord/sensors/i2c_sensor.py @@ -0,0 +1,78 @@ +import time +import ctypes +from collections.abc import Iterable + +from cereal import log +from openpilot.common.i2c import SMBus + + +class Sensor: + class SensorException(Exception): + pass + + class DataNotReady(SensorException): + pass + + def __init__(self, bus: int) -> None: + self.bus = SMBus(bus) + self.source = log.SensorEventData.SensorSource.velodyne # unknown + self.start_ts = 0. + + def __del__(self): + self.bus.close() + + def read(self, addr: int, length: int) -> bytes: + return bytes(self.bus.read_i2c_block_data(self.device_address, addr, length)) + + def write(self, addr: int, data: int) -> None: + self.bus.write_byte_data(self.device_address, addr, data) + + def writes(self, writes: Iterable[tuple[int, int]]) -> None: + for addr, data in writes: + self.write(addr, data) + + def verify_chip_id(self, address: int, expected_ids: list[int]) -> int: + chip_id = self.read(address, 1)[0] + assert chip_id in expected_ids + return chip_id + + # Abstract methods that must be implemented by subclasses + @property + def device_address(self) -> int: + raise NotImplementedError + + def reset(self) -> None: + # optional. + # not part of init due to shared registers + pass + + def init(self) -> None: + raise NotImplementedError + + def get_event(self, ts: int | None = None) -> log.SensorEventData: + raise NotImplementedError + + def shutdown(self) -> None: + raise NotImplementedError + + def is_data_valid(self) -> bool: + if self.start_ts == 0: + self.start_ts = time.monotonic() + + # unclear whether we need this... + return (time.monotonic() - self.start_ts) > 0.5 + + # *** helpers *** + @staticmethod + def wait(): + # a standard small sleep + time.sleep(0.005) + + @staticmethod + def parse_16bit(lsb: int, msb: int) -> int: + return ctypes.c_int16((msb << 8) | lsb).value + + @staticmethod + def parse_20bit(b2: int, b1: int, b0: int) -> int: + combined = ctypes.c_uint32((b0 << 16) | (b1 << 8) | b2).value + return ctypes.c_int32(combined).value // (1 << 4) diff --git a/system/sensord/sensors/lsm6ds3_accel.cc b/system/sensord/sensors/lsm6ds3_accel.cc deleted file mode 100644 index 03533e0657c6bc..00000000000000 --- a/system/sensord/sensors/lsm6ds3_accel.cc +++ /dev/null @@ -1,250 +0,0 @@ -#include "system/sensord/sensors/lsm6ds3_accel.h" - -#include -#include -#include - -#include "common/swaglog.h" -#include "common/timing.h" -#include "common/util.h" - -LSM6DS3_Accel::LSM6DS3_Accel(I2CBus *bus, int gpio_nr, bool shared_gpio) : - I2CSensor(bus, gpio_nr, shared_gpio) {} - -void LSM6DS3_Accel::wait_for_data_ready() { - uint8_t drdy = 0; - uint8_t buffer[6]; - - do { - read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); - drdy &= LSM6DS3_ACCEL_DRDY_XLDA; - } while (drdy == 0); - - read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); -} - -void LSM6DS3_Accel::read_and_avg_data(float* out_buf) { - uint8_t drdy = 0; - uint8_t buffer[6]; - - float scaling = 0.061f; - if (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) { - scaling = 0.122f; - } - - for (int i = 0; i < 5; i++) { - do { - read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); - drdy &= LSM6DS3_ACCEL_DRDY_XLDA; - } while (drdy == 0); - - int len = read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); - assert(len == sizeof(buffer)); - - for (int j = 0; j < 3; j++) { - out_buf[j] += (float)read_16_bit(buffer[j*2], buffer[j*2+1]) * scaling; - } - } - - for (int i = 0; i < 3; i++) { - out_buf[i] /= 5.0f; - } -} - -int LSM6DS3_Accel::self_test(int test_type) { - float val_st_off[3] = {0}; - float val_st_on[3] = {0}; - float test_val[3] = {0}; - uint8_t ODR_FS_MO = LSM6DS3_ACCEL_ODR_52HZ; // full scale: +-2g, ODR: 52Hz - - // prepare sensor for self-test - - // enable block data update and automatic increment - int ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL3_C, LSM6DS3_ACCEL_IF_INC_BDU); - if (ret < 0) { - return ret; - } - - if (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) { - ODR_FS_MO = LSM6DS3_ACCEL_FS_4G | LSM6DS3_ACCEL_ODR_52HZ; - } - ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, ODR_FS_MO); - if (ret < 0) { - return ret; - } - - // wait for stable output, and discard first values - util::sleep_for(100); - wait_for_data_ready(); - read_and_avg_data(val_st_off); - - // enable Self Test positive (or negative) - ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL5_C, test_type); - if (ret < 0) { - return ret; - } - - // wait for stable output, and discard first values - util::sleep_for(100); - wait_for_data_ready(); - read_and_avg_data(val_st_on); - - // disable sensor - ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, 0); - if (ret < 0) { - return ret; - } - - // disable self test - ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL5_C, 0); - if (ret < 0) { - return ret; - } - - // calculate the mg values for self test - for (int i = 0; i < 3; i++) { - test_val[i] = fabs(val_st_on[i] - val_st_off[i]); - } - - // verify test result - for (int i = 0; i < 3; i++) { - if ((LSM6DS3_ACCEL_MIN_ST_LIMIT_mg > test_val[i]) || - (test_val[i] > LSM6DS3_ACCEL_MAX_ST_LIMIT_mg)) { - return -1; - } - } - - return ret; -} - -int LSM6DS3_Accel::init() { - uint8_t value = 0; - bool do_self_test = false; - - const char* env_lsm_selftest = std::getenv("LSM_SELF_TEST"); - if (env_lsm_selftest != nullptr && strncmp(env_lsm_selftest, "1", 1) == 0) { - do_self_test = true; - } - - int ret = verify_chip_id(LSM6DS3_ACCEL_I2C_REG_ID, {LSM6DS3_ACCEL_CHIP_ID, LSM6DS3TRC_ACCEL_CHIP_ID}); - if (ret == -1) return -1; - - if (ret == LSM6DS3TRC_ACCEL_CHIP_ID) { - source = cereal::SensorEventData::SensorSource::LSM6DS3TRC; - } - - ret = self_test(LSM6DS3_ACCEL_POSITIVE_TEST); - if (ret < 0) { - LOGE("LSM6DS3 accel positive self-test failed!"); - if (do_self_test) goto fail; - } - - ret = self_test(LSM6DS3_ACCEL_NEGATIVE_TEST); - if (ret < 0) { - LOGE("LSM6DS3 accel negative self-test failed!"); - if (do_self_test) goto fail; - } - - ret = init_gpio(); - if (ret < 0) { - goto fail; - } - - // enable continuous update, and automatic increase - ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL3_C, LSM6DS3_ACCEL_IF_INC); - if (ret < 0) { - goto fail; - } - - // TODO: set scale and bandwidth. Default is +- 2G, 50 Hz - ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, LSM6DS3_ACCEL_ODR_104HZ); - if (ret < 0) { - goto fail; - } - - ret = set_register(LSM6DS3_ACCEL_I2C_REG_DRDY_CFG, LSM6DS3_ACCEL_DRDY_PULSE_MODE); - if (ret < 0) { - goto fail; - } - - // enable data ready interrupt for accel on INT1 - // (without resetting existing interrupts) - ret = read_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, &value, 1); - if (ret < 0) { - goto fail; - } - - value |= LSM6DS3_ACCEL_INT1_DRDY_XL; - ret = set_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, value); - -fail: - return ret; -} - -int LSM6DS3_Accel::shutdown() { - int ret = 0; - - // disable data ready interrupt for accel on INT1 - uint8_t value = 0; - ret = read_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, &value, 1); - if (ret < 0) { - goto fail; - } - - value &= ~(LSM6DS3_ACCEL_INT1_DRDY_XL); - ret = set_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, value); - if (ret < 0) { - LOGE("Could not disable lsm6ds3 acceleration interrupt!"); - goto fail; - } - - // enable power-down mode - value = 0; - ret = read_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, &value, 1); - if (ret < 0) { - goto fail; - } - - value &= 0x0F; - ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, value); - if (ret < 0) { - LOGE("Could not power-down lsm6ds3 accelerometer!"); - goto fail; - } - -fail: - return ret; -} - -bool LSM6DS3_Accel::get_event(MessageBuilder &msg, uint64_t ts) { - - // INT1 shared with gyro, check STATUS_REG who triggered - uint8_t status_reg = 0; - read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &status_reg, sizeof(status_reg)); - if ((status_reg & LSM6DS3_ACCEL_DRDY_XLDA) == 0) { - return false; - } - - uint8_t buffer[6]; - int len = read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); - assert(len == sizeof(buffer)); - - float scale = 9.81 * 2.0f / (1 << 15); - float x = read_16_bit(buffer[0], buffer[1]) * scale; - float y = read_16_bit(buffer[2], buffer[3]) * scale; - float z = read_16_bit(buffer[4], buffer[5]) * scale; - - auto event = msg.initEvent().initAccelerometer(); - event.setSource(source); - event.setVersion(1); - event.setSensor(SENSOR_ACCELEROMETER); - event.setType(SENSOR_TYPE_ACCELEROMETER); - event.setTimestamp(ts); - - float xyz[] = {y, -x, z}; - auto svec = event.initAcceleration(); - svec.setV(xyz); - svec.setStatus(true); - - return true; -} diff --git a/system/sensord/sensors/lsm6ds3_accel.h b/system/sensord/sensors/lsm6ds3_accel.h deleted file mode 100644 index 69667cb759ec2a..00000000000000 --- a/system/sensord/sensors/lsm6ds3_accel.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include "system/sensord/sensors/i2c_sensor.h" - -// Address of the chip on the bus -#define LSM6DS3_ACCEL_I2C_ADDR 0x6A - -// Registers of the chip -#define LSM6DS3_ACCEL_I2C_REG_DRDY_CFG 0x0B -#define LSM6DS3_ACCEL_I2C_REG_ID 0x0F -#define LSM6DS3_ACCEL_I2C_REG_INT1_CTRL 0x0D -#define LSM6DS3_ACCEL_I2C_REG_CTRL1_XL 0x10 -#define LSM6DS3_ACCEL_I2C_REG_CTRL3_C 0x12 -#define LSM6DS3_ACCEL_I2C_REG_CTRL5_C 0x14 -#define LSM6DS3_ACCEL_I2C_REG_CTR9_XL 0x18 -#define LSM6DS3_ACCEL_I2C_REG_STAT_REG 0x1E -#define LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL 0x28 - -// Constants -#define LSM6DS3_ACCEL_CHIP_ID 0x69 -#define LSM6DS3TRC_ACCEL_CHIP_ID 0x6A -#define LSM6DS3_ACCEL_FS_4G (0b10 << 2) -#define LSM6DS3_ACCEL_ODR_52HZ (0b0011 << 4) -#define LSM6DS3_ACCEL_ODR_104HZ (0b0100 << 4) -#define LSM6DS3_ACCEL_INT1_DRDY_XL 0b1 -#define LSM6DS3_ACCEL_DRDY_XLDA 0b1 -#define LSM6DS3_ACCEL_DRDY_PULSE_MODE (1 << 7) -#define LSM6DS3_ACCEL_IF_INC 0b00000100 -#define LSM6DS3_ACCEL_IF_INC_BDU 0b01000100 -#define LSM6DS3_ACCEL_XYZ_DEN 0b11100000 -#define LSM6DS3_ACCEL_POSITIVE_TEST 0b01 -#define LSM6DS3_ACCEL_NEGATIVE_TEST 0b10 -#define LSM6DS3_ACCEL_MIN_ST_LIMIT_mg 90.0f -#define LSM6DS3_ACCEL_MAX_ST_LIMIT_mg 1700.0f - -class LSM6DS3_Accel : public I2CSensor { - uint8_t get_device_address() {return LSM6DS3_ACCEL_I2C_ADDR;} - cereal::SensorEventData::SensorSource source = cereal::SensorEventData::SensorSource::LSM6DS3; - - // self test functions - int self_test(int test_type); - void wait_for_data_ready(); - void read_and_avg_data(float* val_st_off); -public: - LSM6DS3_Accel(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); - int init(); - bool get_event(MessageBuilder &msg, uint64_t ts = 0); - int shutdown(); -}; diff --git a/system/sensord/sensors/lsm6ds3_accel.py b/system/sensord/sensors/lsm6ds3_accel.py new file mode 100644 index 00000000000000..761ae828bbdee3 --- /dev/null +++ b/system/sensord/sensors/lsm6ds3_accel.py @@ -0,0 +1,157 @@ +import os +import time + +from cereal import log +from openpilot.system.sensord.sensors.i2c_sensor import Sensor + +class LSM6DS3_Accel(Sensor): + LSM6DS3_ACCEL_I2C_REG_DRDY_CFG = 0x0B + LSM6DS3_ACCEL_I2C_REG_INT1_CTRL = 0x0D + LSM6DS3_ACCEL_I2C_REG_CTRL1_XL = 0x10 + LSM6DS3_ACCEL_I2C_REG_CTRL3_C = 0x12 + LSM6DS3_ACCEL_I2C_REG_CTRL5_C = 0x14 + LSM6DS3_ACCEL_I2C_REG_STAT_REG = 0x1E + LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL = 0x28 + + LSM6DS3_ACCEL_ODR_104HZ = (0b0100 << 4) + LSM6DS3_ACCEL_INT1_DRDY_XL = 0b1 + LSM6DS3_ACCEL_DRDY_XLDA = 0b1 + LSM6DS3_ACCEL_DRDY_PULSE_MODE = (1 << 7) + LSM6DS3_ACCEL_IF_INC = 0b00000100 + + LSM6DS3_ACCEL_ODR_52HZ = (0b0011 << 4) + LSM6DS3_ACCEL_FS_4G = (0b10 << 2) + LSM6DS3_ACCEL_IF_INC_BDU = 0b01000100 + LSM6DS3_ACCEL_POSITIVE_TEST = 0b01 + LSM6DS3_ACCEL_NEGATIVE_TEST = 0b10 + LSM6DS3_ACCEL_MIN_ST_LIMIT_mg = 90.0 + LSM6DS3_ACCEL_MAX_ST_LIMIT_mg = 1700.0 + + @property + def device_address(self) -> int: + return 0x6A + + def reset(self): + self.write(0x12, 0x1) + time.sleep(0.1) + + def init(self): + chip_id = self.verify_chip_id(0x0F, [0x69, 0x6A]) + if chip_id == 0x6A: + self.source = log.SensorEventData.SensorSource.lsm6ds3trc + else: + self.source = log.SensorEventData.SensorSource.lsm6ds3 + + # self-test + if os.getenv("LSM_SELF_TEST") == "1": + self.self_test(self.LSM6DS3_ACCEL_POSITIVE_TEST) + self.self_test(self.LSM6DS3_ACCEL_NEGATIVE_TEST) + + # actual init + int1 = self.read(self.LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, 1)[0] + int1 |= self.LSM6DS3_ACCEL_INT1_DRDY_XL + self.writes(( + # Enable continuous update and automatic address increment + (self.LSM6DS3_ACCEL_I2C_REG_CTRL3_C, self.LSM6DS3_ACCEL_IF_INC), + # Set ODR to 104 Hz, FS to ±2g (default) + (self.LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, self.LSM6DS3_ACCEL_ODR_104HZ), + # Configure data ready signal to pulse mode + (self.LSM6DS3_ACCEL_I2C_REG_DRDY_CFG, self.LSM6DS3_ACCEL_DRDY_PULSE_MODE), + # Enable data ready interrupt on INT1 without resetting existing interrupts + (self.LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, int1), + )) + + def get_event(self, ts: int | None = None) -> log.SensorEventData: + assert ts is not None # must come from the IRQ event + + # Check if data is ready since IRQ is shared with gyro + status_reg = self.read(self.LSM6DS3_ACCEL_I2C_REG_STAT_REG, 1)[0] + if (status_reg & self.LSM6DS3_ACCEL_DRDY_XLDA) == 0: + raise self.DataNotReady + + scale = 9.81 * 2.0 / (1 << 15) + b = self.read(self.LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, 6) + x = self.parse_16bit(b[0], b[1]) * scale + y = self.parse_16bit(b[2], b[3]) * scale + z = self.parse_16bit(b[4], b[5]) * scale + + event = log.SensorEventData.new_message() + event.timestamp = ts + event.source = self.source + a = event.init('acceleration') + a.v = [y, -x, z] + return event + + def shutdown(self) -> None: + # Disable data ready interrupt on INT1 + value = self.read(self.LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, 1)[0] + value &= ~self.LSM6DS3_ACCEL_INT1_DRDY_XL + self.write(self.LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, value) + + # Power down by clearing ODR bits + value = self.read(self.LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, 1)[0] + value &= 0x0F + self.write(self.LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, value) + + # *** self-test stuff *** + def _wait_for_data_ready(self): + while True: + drdy = self.read(self.LSM6DS3_ACCEL_I2C_REG_STAT_REG, 1)[0] + if drdy & self.LSM6DS3_ACCEL_DRDY_XLDA: + break + + def _read_and_avg_data(self, scaling: float) -> list[float]: + out_buf = [0.0, 0.0, 0.0] + for _ in range(5): + self._wait_for_data_ready() + b = self.read(self.LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, 6) + for j in range(3): + val = self.parse_16bit(b[j*2], b[j*2+1]) * scaling + out_buf[j] += val + return [x / 5.0 for x in out_buf] + + def self_test(self, test_type: int) -> None: + # Prepare sensor for self-test + self.write(self.LSM6DS3_ACCEL_I2C_REG_CTRL3_C, self.LSM6DS3_ACCEL_IF_INC_BDU) + + # Configure ODR and full scale based on sensor type + if self.source == log.SensorEventData.SensorSource.lsm6ds3trc: + odr_fs = self.LSM6DS3_ACCEL_FS_4G | self.LSM6DS3_ACCEL_ODR_52HZ + scaling = 0.122 # mg/LSB for ±4g + else: + odr_fs = self.LSM6DS3_ACCEL_ODR_52HZ + scaling = 0.061 # mg/LSB for ±2g + self.write(self.LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, odr_fs) + + # Wait for stable output + time.sleep(0.1) + self._wait_for_data_ready() + val_st_off = self._read_and_avg_data(scaling) + + # Enable self-test + self.write(self.LSM6DS3_ACCEL_I2C_REG_CTRL5_C, test_type) + + # Wait for stable output + time.sleep(0.1) + self._wait_for_data_ready() + val_st_on = self._read_and_avg_data(scaling) + + # Disable sensor and self-test + self.write(self.LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, 0) + self.write(self.LSM6DS3_ACCEL_I2C_REG_CTRL5_C, 0) + + # Calculate differences and check limits + test_val = [abs(on - off) for on, off in zip(val_st_on, val_st_off, strict=False)] + for val in test_val: + if val < self.LSM6DS3_ACCEL_MIN_ST_LIMIT_mg or val > self.LSM6DS3_ACCEL_MAX_ST_LIMIT_mg: + raise self.SensorException(f"Accelerometer self-test failed for test type {test_type}") + +if __name__ == "__main__": + import numpy as np + s = LSM6DS3_Accel(1) + s.init() + time.sleep(0.2) + e = s.get_event(0) + print(e) + print(np.linalg.norm(e.acceleration.v)) + s.shutdown() diff --git a/system/sensord/sensors/lsm6ds3_gyro.cc b/system/sensord/sensors/lsm6ds3_gyro.cc deleted file mode 100644 index 0459b6ad64779c..00000000000000 --- a/system/sensord/sensors/lsm6ds3_gyro.cc +++ /dev/null @@ -1,233 +0,0 @@ -#include "system/sensord/sensors/lsm6ds3_gyro.h" - -#include -#include -#include - -#include "common/swaglog.h" -#include "common/timing.h" -#include "common/util.h" - -#define DEG2RAD(x) ((x) * M_PI / 180.0) - -LSM6DS3_Gyro::LSM6DS3_Gyro(I2CBus *bus, int gpio_nr, bool shared_gpio) : - I2CSensor(bus, gpio_nr, shared_gpio) {} - -void LSM6DS3_Gyro::wait_for_data_ready() { - uint8_t drdy = 0; - uint8_t buffer[6]; - - do { - read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); - drdy &= LSM6DS3_GYRO_DRDY_GDA; - } while (drdy == 0); - - read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); -} - -void LSM6DS3_Gyro::read_and_avg_data(float* out_buf) { - uint8_t drdy = 0; - uint8_t buffer[6]; - - for (int i = 0; i < 5; i++) { - do { - read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); - drdy &= LSM6DS3_GYRO_DRDY_GDA; - } while (drdy == 0); - - int len = read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); - assert(len == sizeof(buffer)); - - for (int j = 0; j < 3; j++) { - out_buf[j] += (float)read_16_bit(buffer[j*2], buffer[j*2+1]) * 70.0f; - } - } - - // calculate the mg average values - for (int i = 0; i < 3; i++) { - out_buf[i] /= 5.0f; - } -} - -int LSM6DS3_Gyro::self_test(int test_type) { - float val_st_off[3] = {0}; - float val_st_on[3] = {0}; - float test_val[3] = {0}; - - // prepare sensor for self-test - - // full scale: 2000dps, ODR: 208Hz - int ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, LSM6DS3_GYRO_ODR_208HZ | LSM6DS3_GYRO_FS_2000dps); - if (ret < 0) { - return ret; - } - - // wait for stable output, and discard first values - util::sleep_for(150); - wait_for_data_ready(); - read_and_avg_data(val_st_off); - - // enable Self Test positive (or negative) - ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL5_C, test_type); - if (ret < 0) { - return ret; - } - - // wait for stable output, and discard first values - util::sleep_for(50); - wait_for_data_ready(); - read_and_avg_data(val_st_on); - - // disable sensor - ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, 0); - if (ret < 0) { - return ret; - } - - // disable self test - ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL5_C, 0); - if (ret < 0) { - return ret; - } - - // calculate the mg values for self test - for (int i = 0; i < 3; i++) { - test_val[i] = fabs(val_st_on[i] - val_st_off[i]); - } - - // verify test result - for (int i = 0; i < 3; i++) { - if ((LSM6DS3_GYRO_MIN_ST_LIMIT_mdps > test_val[i]) || - (test_val[i] > LSM6DS3_GYRO_MAX_ST_LIMIT_mdps)) { - return -1; - } - } - - return ret; -} - -int LSM6DS3_Gyro::init() { - uint8_t value = 0; - bool do_self_test = false; - - const char* env_lsm_selftest =env_lsm_selftest = std::getenv("LSM_SELF_TEST"); - if (env_lsm_selftest != nullptr && strncmp(env_lsm_selftest, "1", 1) == 0) { - do_self_test = true; - } - - int ret = verify_chip_id(LSM6DS3_GYRO_I2C_REG_ID, {LSM6DS3_GYRO_CHIP_ID, LSM6DS3TRC_GYRO_CHIP_ID}); - if (ret == -1) return -1; - - if (ret == LSM6DS3TRC_GYRO_CHIP_ID) { - source = cereal::SensorEventData::SensorSource::LSM6DS3TRC; - } - - ret = init_gpio(); - if (ret < 0) { - goto fail; - } - - ret = self_test(LSM6DS3_GYRO_POSITIVE_TEST); - if (ret < 0) { - LOGE("LSM6DS3 gyro positive self-test failed!"); - if (do_self_test) goto fail; - } - - ret = self_test(LSM6DS3_GYRO_NEGATIVE_TEST); - if (ret < 0) { - LOGE("LSM6DS3 gyro negative self-test failed!"); - if (do_self_test) goto fail; - } - - // TODO: set scale. Default is +- 250 deg/s - ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, LSM6DS3_GYRO_ODR_104HZ); - if (ret < 0) { - goto fail; - } - - ret = set_register(LSM6DS3_GYRO_I2C_REG_DRDY_CFG, LSM6DS3_GYRO_DRDY_PULSE_MODE); - if (ret < 0) { - goto fail; - } - - // enable data ready interrupt for gyro on INT1 - // (without resetting existing interrupts) - ret = read_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, &value, 1); - if (ret < 0) { - goto fail; - } - - value |= LSM6DS3_GYRO_INT1_DRDY_G; - ret = set_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, value); - -fail: - return ret; -} - -int LSM6DS3_Gyro::shutdown() { - int ret = 0; - - // disable data ready interrupt for gyro on INT1 - uint8_t value = 0; - ret = read_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, &value, 1); - if (ret < 0) { - goto fail; - } - - value &= ~(LSM6DS3_GYRO_INT1_DRDY_G); - ret = set_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, value); - if (ret < 0) { - LOGE("Could not disable lsm6ds3 gyroscope interrupt!"); - goto fail; - } - - // enable power-down mode - value = 0; - ret = read_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, &value, 1); - if (ret < 0) { - goto fail; - } - - value &= 0x0F; - ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, value); - if (ret < 0) { - LOGE("Could not power-down lsm6ds3 gyroscope!"); - goto fail; - } - -fail: - return ret; -} - -bool LSM6DS3_Gyro::get_event(MessageBuilder &msg, uint64_t ts) { - - // INT1 shared with accel, check STATUS_REG who triggered - uint8_t status_reg = 0; - read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &status_reg, sizeof(status_reg)); - if ((status_reg & LSM6DS3_GYRO_DRDY_GDA) == 0) { - return false; - } - - uint8_t buffer[6]; - int len = read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); - assert(len == sizeof(buffer)); - - float scale = 8.75 / 1000.0; - float x = DEG2RAD(read_16_bit(buffer[0], buffer[1]) * scale); - float y = DEG2RAD(read_16_bit(buffer[2], buffer[3]) * scale); - float z = DEG2RAD(read_16_bit(buffer[4], buffer[5]) * scale); - - auto event = msg.initEvent().initGyroscope(); - event.setSource(source); - event.setVersion(2); - event.setSensor(SENSOR_GYRO_UNCALIBRATED); - event.setType(SENSOR_TYPE_GYROSCOPE_UNCALIBRATED); - event.setTimestamp(ts); - - float xyz[] = {y, -x, z}; - auto svec = event.initGyroUncalibrated(); - svec.setV(xyz); - svec.setStatus(true); - - return true; -} diff --git a/system/sensord/sensors/lsm6ds3_gyro.h b/system/sensord/sensors/lsm6ds3_gyro.h deleted file mode 100644 index adaae62dd28dcd..00000000000000 --- a/system/sensord/sensors/lsm6ds3_gyro.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include "system/sensord/sensors/i2c_sensor.h" - -// Address of the chip on the bus -#define LSM6DS3_GYRO_I2C_ADDR 0x6A - -// Registers of the chip -#define LSM6DS3_GYRO_I2C_REG_DRDY_CFG 0x0B -#define LSM6DS3_GYRO_I2C_REG_ID 0x0F -#define LSM6DS3_GYRO_I2C_REG_INT1_CTRL 0x0D -#define LSM6DS3_GYRO_I2C_REG_CTRL2_G 0x11 -#define LSM6DS3_GYRO_I2C_REG_CTRL5_C 0x14 -#define LSM6DS3_GYRO_I2C_REG_STAT_REG 0x1E -#define LSM6DS3_GYRO_I2C_REG_OUTX_L_G 0x22 -#define LSM6DS3_GYRO_POSITIVE_TEST (0b01 << 2) -#define LSM6DS3_GYRO_NEGATIVE_TEST (0b11 << 2) - -// Constants -#define LSM6DS3_GYRO_CHIP_ID 0x69 -#define LSM6DS3TRC_GYRO_CHIP_ID 0x6A -#define LSM6DS3_GYRO_FS_2000dps (0b11 << 2) -#define LSM6DS3_GYRO_ODR_104HZ (0b0100 << 4) -#define LSM6DS3_GYRO_ODR_208HZ (0b0101 << 4) -#define LSM6DS3_GYRO_INT1_DRDY_G 0b10 -#define LSM6DS3_GYRO_DRDY_GDA 0b10 -#define LSM6DS3_GYRO_DRDY_PULSE_MODE (1 << 7) -#define LSM6DS3_GYRO_MIN_ST_LIMIT_mdps 150000.0f -#define LSM6DS3_GYRO_MAX_ST_LIMIT_mdps 700000.0f - - -class LSM6DS3_Gyro : public I2CSensor { - uint8_t get_device_address() {return LSM6DS3_GYRO_I2C_ADDR;} - cereal::SensorEventData::SensorSource source = cereal::SensorEventData::SensorSource::LSM6DS3; - - // self test functions - int self_test(int test_type); - void wait_for_data_ready(); - void read_and_avg_data(float* val_st_off); -public: - LSM6DS3_Gyro(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); - int init(); - bool get_event(MessageBuilder &msg, uint64_t ts = 0); - int shutdown(); -}; diff --git a/system/sensord/sensors/lsm6ds3_gyro.py b/system/sensord/sensors/lsm6ds3_gyro.py new file mode 100644 index 00000000000000..654cff9da8d0e1 --- /dev/null +++ b/system/sensord/sensors/lsm6ds3_gyro.py @@ -0,0 +1,141 @@ +import os +import math +import time + +from cereal import log +from openpilot.system.sensord.sensors.i2c_sensor import Sensor + +class LSM6DS3_Gyro(Sensor): + LSM6DS3_GYRO_I2C_REG_DRDY_CFG = 0x0B + LSM6DS3_GYRO_I2C_REG_INT1_CTRL = 0x0D + LSM6DS3_GYRO_I2C_REG_CTRL2_G = 0x11 + LSM6DS3_GYRO_I2C_REG_CTRL5_C = 0x14 + LSM6DS3_GYRO_I2C_REG_STAT_REG = 0x1E + LSM6DS3_GYRO_I2C_REG_OUTX_L_G = 0x22 + + LSM6DS3_GYRO_ODR_104HZ = (0b0100 << 4) + LSM6DS3_GYRO_INT1_DRDY_G = 0b10 + LSM6DS3_GYRO_DRDY_GDA = 0b10 + LSM6DS3_GYRO_DRDY_PULSE_MODE = (1 << 7) + + LSM6DS3_GYRO_ODR_208HZ = (0b0101 << 4) + LSM6DS3_GYRO_FS_2000dps = (0b11 << 2) + LSM6DS3_GYRO_POSITIVE_TEST = (0b01 << 2) + LSM6DS3_GYRO_NEGATIVE_TEST = (0b11 << 2) + LSM6DS3_GYRO_MIN_ST_LIMIT_mdps = 150000.0 + LSM6DS3_GYRO_MAX_ST_LIMIT_mdps = 700000.0 + + @property + def device_address(self) -> int: + return 0x6A + + def reset(self): + self.write(0x12, 0x1) + time.sleep(0.1) + + def init(self): + chip_id = self.verify_chip_id(0x0F, [0x69, 0x6A]) + if chip_id == 0x6A: + self.source = log.SensorEventData.SensorSource.lsm6ds3trc + else: + self.source = log.SensorEventData.SensorSource.lsm6ds3 + + # self-test + if "LSM_SELF_TEST" in os.environ: + self.self_test(self.LSM6DS3_GYRO_POSITIVE_TEST) + self.self_test(self.LSM6DS3_GYRO_NEGATIVE_TEST) + + # actual init + self.writes(( + # TODO: set scale. Default is +- 250 deg/s + (self.LSM6DS3_GYRO_I2C_REG_CTRL2_G, self.LSM6DS3_GYRO_ODR_104HZ), + # Configure data ready signal to pulse mode + (self.LSM6DS3_GYRO_I2C_REG_DRDY_CFG, self.LSM6DS3_GYRO_DRDY_PULSE_MODE), + )) + value = self.read(self.LSM6DS3_GYRO_I2C_REG_INT1_CTRL, 1)[0] + value |= self.LSM6DS3_GYRO_INT1_DRDY_G + self.write(self.LSM6DS3_GYRO_I2C_REG_INT1_CTRL, value) + + def get_event(self, ts: int | None = None) -> log.SensorEventData: + assert ts is not None # must come from the IRQ event + + # Check if gyroscope data is ready, since it's shared with accelerometer + status_reg = self.read(self.LSM6DS3_GYRO_I2C_REG_STAT_REG, 1)[0] + if not (status_reg & self.LSM6DS3_GYRO_DRDY_GDA): + raise self.DataNotReady + + b = self.read(self.LSM6DS3_GYRO_I2C_REG_OUTX_L_G, 6) + x = self.parse_16bit(b[0], b[1]) + y = self.parse_16bit(b[2], b[3]) + z = self.parse_16bit(b[4], b[5]) + scale = (8.75 / 1000.0) * (math.pi / 180.0) + xyz = [y * scale, -x * scale, z * scale] + + event = log.SensorEventData.new_message() + event.timestamp = ts + event.source = self.source + g = event.init('gyroUncalibrated') + g.v = xyz + return event + + def shutdown(self) -> None: + # Disable data ready interrupt on INT1 + value = self.read(self.LSM6DS3_GYRO_I2C_REG_INT1_CTRL, 1)[0] + value &= ~self.LSM6DS3_GYRO_INT1_DRDY_G + self.write(self.LSM6DS3_GYRO_I2C_REG_INT1_CTRL, value) + + # Power down by clearing ODR bits + value = self.read(self.LSM6DS3_GYRO_I2C_REG_CTRL2_G, 1)[0] + value &= 0x0F + self.write(self.LSM6DS3_GYRO_I2C_REG_CTRL2_G, value) + + # *** self-test stuff *** + def _wait_for_data_ready(self): + while True: + drdy = self.read(self.LSM6DS3_GYRO_I2C_REG_STAT_REG, 1)[0] + if drdy & self.LSM6DS3_GYRO_DRDY_GDA: + break + + def _read_and_avg_data(self) -> list[float]: + out_buf = [0.0, 0.0, 0.0] + for _ in range(5): + self._wait_for_data_ready() + b = self.read(self.LSM6DS3_GYRO_I2C_REG_OUTX_L_G, 6) + for j in range(3): + val = self.parse_16bit(b[j*2], b[j*2+1]) * 70.0 # mdps/LSB for 2000 dps + out_buf[j] += val + return [x / 5.0 for x in out_buf] + + def self_test(self, test_type: int): + # Set ODR to 208Hz, FS to 2000dps + self.write(self.LSM6DS3_GYRO_I2C_REG_CTRL2_G, self.LSM6DS3_GYRO_ODR_208HZ | self.LSM6DS3_GYRO_FS_2000dps) + + # Wait for stable output + time.sleep(0.15) + self._wait_for_data_ready() + val_st_off = self._read_and_avg_data() + + # Enable self-test + self.write(self.LSM6DS3_GYRO_I2C_REG_CTRL5_C, test_type) + + # Wait for stable output + time.sleep(0.05) + self._wait_for_data_ready() + val_st_on = self._read_and_avg_data() + + # Disable sensor and self-test + self.write(self.LSM6DS3_GYRO_I2C_REG_CTRL2_G, 0) + self.write(self.LSM6DS3_GYRO_I2C_REG_CTRL5_C, 0) + + # Calculate differences and check limits + test_val = [abs(on - off) for on, off in zip(val_st_on, val_st_off, strict=False)] + for val in test_val: + if val < self.LSM6DS3_GYRO_MIN_ST_LIMIT_mdps or val > self.LSM6DS3_GYRO_MAX_ST_LIMIT_mdps: + raise Exception(f"Gyroscope self-test failed for test type {test_type}") + +if __name__ == "__main__": + s = LSM6DS3_Gyro(1) + s.init() + time.sleep(0.1) + print(s.get_event(0)) + s.shutdown() diff --git a/system/sensord/sensors/lsm6ds3_temp.cc b/system/sensord/sensors/lsm6ds3_temp.cc deleted file mode 100644 index f481614154ba01..00000000000000 --- a/system/sensord/sensors/lsm6ds3_temp.cc +++ /dev/null @@ -1,37 +0,0 @@ -#include "system/sensord/sensors/lsm6ds3_temp.h" - -#include - -#include "common/swaglog.h" -#include "common/timing.h" - -LSM6DS3_Temp::LSM6DS3_Temp(I2CBus *bus) : I2CSensor(bus) {} - -int LSM6DS3_Temp::init() { - int ret = verify_chip_id(LSM6DS3_TEMP_I2C_REG_ID, {LSM6DS3_TEMP_CHIP_ID, LSM6DS3TRC_TEMP_CHIP_ID}); - if (ret == -1) return -1; - - if (ret == LSM6DS3TRC_TEMP_CHIP_ID) { - source = cereal::SensorEventData::SensorSource::LSM6DS3TRC; - } - return 0; -} - -bool LSM6DS3_Temp::get_event(MessageBuilder &msg, uint64_t ts) { - uint64_t start_time = nanos_since_boot(); - uint8_t buffer[2]; - int len = read_register(LSM6DS3_TEMP_I2C_REG_OUT_TEMP_L, buffer, sizeof(buffer)); - assert(len == sizeof(buffer)); - - float scale = (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) ? 256.0f : 16.0f; - float temp = 25.0f + read_16_bit(buffer[0], buffer[1]) / scale; - - auto event = msg.initEvent().initTemperatureSensor(); - event.setSource(source); - event.setVersion(1); - event.setType(SENSOR_TYPE_AMBIENT_TEMPERATURE); - event.setTimestamp(start_time); - event.setTemperature(temp); - - return true; -} diff --git a/system/sensord/sensors/lsm6ds3_temp.h b/system/sensord/sensors/lsm6ds3_temp.h deleted file mode 100644 index 1b5b6218143fab..00000000000000 --- a/system/sensord/sensors/lsm6ds3_temp.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include "system/sensord/sensors/i2c_sensor.h" - -// Address of the chip on the bus -#define LSM6DS3_TEMP_I2C_ADDR 0x6A - -// Registers of the chip -#define LSM6DS3_TEMP_I2C_REG_ID 0x0F -#define LSM6DS3_TEMP_I2C_REG_OUT_TEMP_L 0x20 - -// Constants -#define LSM6DS3_TEMP_CHIP_ID 0x69 -#define LSM6DS3TRC_TEMP_CHIP_ID 0x6A - - -class LSM6DS3_Temp : public I2CSensor { - uint8_t get_device_address() {return LSM6DS3_TEMP_I2C_ADDR;} - cereal::SensorEventData::SensorSource source = cereal::SensorEventData::SensorSource::LSM6DS3; - -public: - LSM6DS3_Temp(I2CBus *bus); - int init(); - bool get_event(MessageBuilder &msg, uint64_t ts = 0); - int shutdown() { return 0; } -}; diff --git a/system/sensord/sensors/lsm6ds3_temp.py b/system/sensord/sensors/lsm6ds3_temp.py new file mode 100644 index 00000000000000..ffe970c22cbbbf --- /dev/null +++ b/system/sensord/sensors/lsm6ds3_temp.py @@ -0,0 +1,32 @@ +import time + +from cereal import log +from openpilot.system.sensord.sensors.i2c_sensor import Sensor + +# https://content.arduino.cc/assets/st_imu_lsm6ds3_datasheet.pdf +class LSM6DS3_Temp(Sensor): + @property + def device_address(self) -> int: + return 0x6A + + def _read_temperature(self) -> float: + scale = 16.0 if self.source == log.SensorEventData.SensorSource.lsm6ds3 else 256.0 + data = self.read(0x20, 2) + return 25 + (self.parse_16bit(data[0], data[1]) / scale) + + def init(self): + chip_id = self.verify_chip_id(0x0F, [0x69, 0x6A]) + if chip_id == 0x6A: + self.source = log.SensorEventData.SensorSource.lsm6ds3trc + else: + self.source = log.SensorEventData.SensorSource.lsm6ds3 + + def get_event(self, ts: int | None = None) -> log.SensorEventData: + event = log.SensorEventData.new_message() + event.timestamp = int(time.monotonic() * 1e9) + event.source = self.source + event.temperature = self._read_temperature() + return event + + def shutdown(self) -> None: + pass diff --git a/system/sensord/sensors/mmc5603nj_magn.cc b/system/sensord/sensors/mmc5603nj_magn.cc deleted file mode 100644 index 0e8ba967e3c264..00000000000000 --- a/system/sensord/sensors/mmc5603nj_magn.cc +++ /dev/null @@ -1,108 +0,0 @@ -#include "system/sensord/sensors/mmc5603nj_magn.h" - -#include -#include -#include - -#include "common/swaglog.h" -#include "common/timing.h" -#include "common/util.h" - -MMC5603NJ_Magn::MMC5603NJ_Magn(I2CBus *bus) : I2CSensor(bus) {} - -int MMC5603NJ_Magn::init() { - int ret = verify_chip_id(MMC5603NJ_I2C_REG_ID, {MMC5603NJ_CHIP_ID}); - if (ret == -1) return -1; - - // Set ODR to 0 - ret = set_register(MMC5603NJ_I2C_REG_ODR, 0); - if (ret < 0) { - goto fail; - } - - // Set BW to 0b01 for 1-150 Hz operation - ret = set_register(MMC5603NJ_I2C_REG_INTERNAL_1, 0b01); - if (ret < 0) { - goto fail; - } - -fail: - return ret; -} - -int MMC5603NJ_Magn::shutdown() { - int ret = 0; - - // disable auto reset of measurements - uint8_t value = 0; - ret = read_register(MMC5603NJ_I2C_REG_INTERNAL_0, &value, 1); - if (ret < 0) { - goto fail; - } - - value &= ~(MMC5603NJ_CMM_FREQ_EN | MMC5603NJ_AUTO_SR_EN); - ret = set_register(MMC5603NJ_I2C_REG_INTERNAL_0, value); - if (ret < 0) { - goto fail; - } - - // set ODR to 0 to leave continuous mode - ret = set_register(MMC5603NJ_I2C_REG_ODR, 0); - if (ret < 0) { - goto fail; - } - return ret; - -fail: - LOGE("Could not disable mmc5603nj auto set reset"); - return ret; -} - -void MMC5603NJ_Magn::start_measurement() { - set_register(MMC5603NJ_I2C_REG_INTERNAL_0, 0b01); - util::sleep_for(5); -} - -std::vector MMC5603NJ_Magn::read_measurement() { - int len; - uint8_t buffer[9]; - len = read_register(MMC5603NJ_I2C_REG_XOUT0, buffer, sizeof(buffer)); - assert(len == sizeof(buffer)); - float scale = 1.0 / 16384.0; - float x = (read_20_bit(buffer[6], buffer[1], buffer[0]) * scale) - 32.0; - float y = (read_20_bit(buffer[7], buffer[3], buffer[2]) * scale) - 32.0; - float z = (read_20_bit(buffer[8], buffer[5], buffer[4]) * scale) - 32.0; - std::vector xyz = {x, y, z}; - return xyz; -} - -bool MMC5603NJ_Magn::get_event(MessageBuilder &msg, uint64_t ts) { - uint64_t start_time = nanos_since_boot(); - // SET - RESET cycle - set_register(MMC5603NJ_I2C_REG_INTERNAL_0, MMC5603NJ_SET); - util::sleep_for(5); - MMC5603NJ_Magn::start_measurement(); - std::vector xyz = MMC5603NJ_Magn::read_measurement(); - - set_register(MMC5603NJ_I2C_REG_INTERNAL_0, MMC5603NJ_RESET); - util::sleep_for(5); - MMC5603NJ_Magn::start_measurement(); - std::vector reset_xyz = MMC5603NJ_Magn::read_measurement(); - - auto event = msg.initEvent().initMagnetometer(); - event.setSource(cereal::SensorEventData::SensorSource::MMC5603NJ); - event.setVersion(1); - event.setSensor(SENSOR_MAGNETOMETER_UNCALIBRATED); - event.setType(SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED); - event.setTimestamp(start_time); - - float vals[] = {xyz[0], xyz[1], xyz[2], reset_xyz[0], reset_xyz[1], reset_xyz[2]}; - bool valid = true; - if (std::any_of(std::begin(vals), std::end(vals), [](float val) { return val == -32.0; })) { - valid = false; - } - auto svec = event.initMagneticUncalibrated(); - svec.setV(vals); - svec.setStatus(valid); - return true; -} diff --git a/system/sensord/sensors/mmc5603nj_magn.h b/system/sensord/sensors/mmc5603nj_magn.h deleted file mode 100644 index 9c0fbd252129f0..00000000000000 --- a/system/sensord/sensors/mmc5603nj_magn.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include - -#include "system/sensord/sensors/i2c_sensor.h" - -// Address of the chip on the bus -#define MMC5603NJ_I2C_ADDR 0x30 - -// Registers of the chip -#define MMC5603NJ_I2C_REG_XOUT0 0x00 -#define MMC5603NJ_I2C_REG_ODR 0x1A -#define MMC5603NJ_I2C_REG_INTERNAL_0 0x1B -#define MMC5603NJ_I2C_REG_INTERNAL_1 0x1C -#define MMC5603NJ_I2C_REG_INTERNAL_2 0x1D -#define MMC5603NJ_I2C_REG_ID 0x39 - -// Constants -#define MMC5603NJ_CHIP_ID 0x10 -#define MMC5603NJ_CMM_FREQ_EN (1 << 7) -#define MMC5603NJ_AUTO_SR_EN (1 << 5) -#define MMC5603NJ_CMM_EN (1 << 4) -#define MMC5603NJ_EN_PRD_SET (1 << 3) -#define MMC5603NJ_SET (1 << 3) -#define MMC5603NJ_RESET (1 << 4) - -class MMC5603NJ_Magn : public I2CSensor { -private: - uint8_t get_device_address() {return MMC5603NJ_I2C_ADDR;} - void start_measurement(); - std::vector read_measurement(); -public: - MMC5603NJ_Magn(I2CBus *bus); - int init(); - bool get_event(MessageBuilder &msg, uint64_t ts = 0); - int shutdown(); -}; diff --git a/system/sensord/sensors/sensor.h b/system/sensord/sensors/sensor.h deleted file mode 100644 index 1b0e3be0dc6065..00000000000000 --- a/system/sensord/sensors/sensor.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "cereal/messaging/messaging.h" - -class Sensor { -public: - int gpio_fd = -1; - uint64_t start_ts = 0; - uint64_t init_delay = 500e6; // default dealy 500ms - virtual ~Sensor() {} - virtual int init() = 0; - virtual bool get_event(MessageBuilder &msg, uint64_t ts = 0) = 0; - virtual bool has_interrupt_enabled() = 0; - virtual int shutdown() = 0; - - virtual bool is_data_valid(uint64_t current_ts) { - if (start_ts == 0) { - start_ts = current_ts; - } - return (current_ts - start_ts) > init_delay; - } -}; diff --git a/system/sensord/sensors_qcom2.cc b/system/sensord/sensors_qcom2.cc deleted file mode 100644 index 9cbc24864d35f9..00000000000000 --- a/system/sensord/sensors_qcom2.cc +++ /dev/null @@ -1,168 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include - -#include "cereal/services.h" -#include "cereal/messaging/messaging.h" -#include "common/i2c.h" -#include "common/ratekeeper.h" -#include "common/swaglog.h" -#include "common/timing.h" -#include "common/util.h" -#include "system/sensord/sensors/bmx055_accel.h" -#include "system/sensord/sensors/bmx055_gyro.h" -#include "system/sensord/sensors/bmx055_magn.h" -#include "system/sensord/sensors/bmx055_temp.h" -#include "system/sensord/sensors/constants.h" -#include "system/sensord/sensors/lsm6ds3_accel.h" -#include "system/sensord/sensors/lsm6ds3_gyro.h" -#include "system/sensord/sensors/lsm6ds3_temp.h" -#include "system/sensord/sensors/mmc5603nj_magn.h" - -#define I2C_BUS_IMU 1 - -ExitHandler do_exit; - -void interrupt_loop(std::vector> sensors) { - PubMaster pm({"gyroscope", "accelerometer"}); - - int fd = -1; - for (auto &[sensor, msg_name] : sensors) { - if (sensor->has_interrupt_enabled()) { - fd = sensor->gpio_fd; - break; - } - } - - struct pollfd fd_list[1] = {0}; - fd_list[0].fd = fd; - fd_list[0].events = POLLIN | POLLPRI; - - while (!do_exit) { - int err = poll(fd_list, 1, 100); - if (err == -1) { - if (errno == EINTR) { - continue; - } - return; - } else if (err == 0) { - LOGE("poll timed out"); - continue; - } - - if ((fd_list[0].revents & (POLLIN | POLLPRI)) == 0) { - LOGE("no poll events set"); - continue; - } - - // Read all events - struct gpioevent_data evdata[16]; - err = read(fd, evdata, sizeof(evdata)); - if (err < 0 || err % sizeof(*evdata) != 0) { - LOGE("error reading event data %d", err); - continue; - } - - int num_events = err / sizeof(*evdata); - uint64_t offset = nanos_since_epoch() - nanos_since_boot(); - uint64_t ts = evdata[num_events - 1].timestamp - offset; - - for (auto &[sensor, msg_name] : sensors) { - if (!sensor->has_interrupt_enabled()) { - continue; - } - - MessageBuilder msg; - if (!sensor->get_event(msg, ts)) { - continue; - } - - if (!sensor->is_data_valid(ts)) { - continue; - } - - pm.send(msg_name.c_str(), msg); - } - } -} - -void polling_loop(Sensor *sensor, std::string msg_name) { - PubMaster pm({msg_name.c_str()}); - RateKeeper rk(msg_name, services.at(msg_name).frequency); - while (!do_exit) { - MessageBuilder msg; - if (sensor->get_event(msg) && sensor->is_data_valid(nanos_since_boot())) { - pm.send(msg_name.c_str(), msg); - } - rk.keepTime(); - } -} - -int sensor_loop(I2CBus *i2c_bus_imu) { - // Sensor init - std::vector> sensors_init = { - {new BMX055_Accel(i2c_bus_imu), "accelerometer2"}, - {new BMX055_Gyro(i2c_bus_imu), "gyroscope2"}, - {new BMX055_Magn(i2c_bus_imu), "magnetometer"}, - {new BMX055_Temp(i2c_bus_imu), "temperatureSensor2"}, - - {new LSM6DS3_Accel(i2c_bus_imu, GPIO_LSM_INT), "accelerometer"}, - {new LSM6DS3_Gyro(i2c_bus_imu, GPIO_LSM_INT, true), "gyroscope"}, - {new LSM6DS3_Temp(i2c_bus_imu), "temperatureSensor"}, - - {new MMC5603NJ_Magn(i2c_bus_imu), "magnetometer"}, - }; - - // Initialize sensors - std::vector threads; - for (auto &[sensor, msg_name] : sensors_init) { - int err = sensor->init(); - if (err < 0) { - continue; - } - - if (!sensor->has_interrupt_enabled()) { - threads.emplace_back(polling_loop, sensor, msg_name); - } - } - - // increase interrupt quality by pinning interrupt and process to core 1 - setpriority(PRIO_PROCESS, 0, -18); - util::set_core_affinity({1}); - - // TODO: get the IRQ number from gpiochip - std::string irq_path = "/proc/irq/336/smp_affinity_list"; - if (!util::file_exists(irq_path)) { - irq_path = "/proc/irq/335/smp_affinity_list"; - } - std::system(util::string_format("sudo su -c 'echo 1 > %s'", irq_path.c_str()).c_str()); - - // thread for reading events via interrupts - threads.emplace_back(&interrupt_loop, std::ref(sensors_init)); - - // wait for all threads to finish - for (auto &t : threads) { - t.join(); - } - - for (auto &[sensor, msg_name] : sensors_init) { - sensor->shutdown(); - delete sensor; - } - return 0; -} - -int main(int argc, char *argv[]) { - try { - auto i2c_bus_imu = std::make_unique(I2C_BUS_IMU); - return sensor_loop(i2c_bus_imu.get()); - } catch (std::exception &e) { - LOGE("I2CBus init failed"); - return -1; - } -} diff --git a/system/sensord/tests/test_sensord.py b/system/sensord/tests/test_sensord.py index 1871012dd6fd70..3d7d26f9faf4bc 100644 --- a/system/sensord/tests/test_sensord.py +++ b/system/sensord/tests/test_sensord.py @@ -5,64 +5,19 @@ from collections import namedtuple, defaultdict import cereal.messaging as messaging -from cereal import log from cereal.services import SERVICE_LIST from openpilot.common.gpio import get_irqs_for_action from openpilot.common.timeout import Timeout from openpilot.system.manager.process_config import managed_processes -BMX = { - ('bmx055', 'acceleration'), - ('bmx055', 'gyroUncalibrated'), - ('bmx055', 'magneticUncalibrated'), - ('bmx055', 'temperature'), -} - -LSM = { - ('lsm6ds3', 'acceleration'), - ('lsm6ds3', 'gyroUncalibrated'), - ('lsm6ds3', 'temperature'), -} -LSM_C = {(x[0]+'trc', x[1]) for x in LSM} - -MMC = { - ('mmc5603nj', 'magneticUncalibrated'), -} - -SENSOR_CONFIGURATIONS = ( - (BMX | LSM), - (MMC | LSM), - (BMX | LSM_C), - (MMC| LSM_C), -) - -Sensor = log.SensorEventData.SensorSource -SensorConfig = namedtuple('SensorConfig', ['type', 'sanity_min', 'sanity_max']) -ALL_SENSORS = { - Sensor.lsm6ds3: { - SensorConfig("acceleration", 5, 15), - SensorConfig("gyroUncalibrated", 0, .2), - SensorConfig("temperature", 0, 60), - }, - - Sensor.lsm6ds3trc: { - SensorConfig("acceleration", 5, 15), - SensorConfig("gyroUncalibrated", 0, .2), - SensorConfig("temperature", 0, 60), - }, - - Sensor.bmx055: { - SensorConfig("acceleration", 5, 15), - SensorConfig("gyroUncalibrated", 0, .2), - SensorConfig("magneticUncalibrated", 0, 300), - SensorConfig("temperature", 0, 60), - }, - - Sensor.mmc5603nj: { - SensorConfig("magneticUncalibrated", 0, 300), - } -} +SensorConfig = namedtuple('SensorConfig', ['service', 'measurement', 'sanity_min', 'sanity_max', 'std_max']) +SENSOR_CONFIGS = ( + SensorConfig("accelerometer", "acceleration", 5, 15, 5), + SensorConfig("gyroscope", "gyroUncalibrated", 0, .15, 0.5), + SensorConfig("temperatureSensor", "temperature", 10, 40, 0.5), # set for max range of our office +) +SENSOR_CONFIGS_BY_MEASUREMENT = {config.measurement: config for config in SENSOR_CONFIGS} def get_irq_count(irq: int): with open(f"/sys/kernel/irq/{irq}/per_cpu_count") as f: @@ -70,13 +25,11 @@ def get_irq_count(irq: int): return sum(per_cpu) def read_sensor_events(duration_sec): - sensor_types = ['accelerometer', 'gyroscope', 'magnetometer', 'accelerometer2', - 'gyroscope2', 'temperatureSensor', 'temperatureSensor2'] socks = {} poller = messaging.Poller() events = defaultdict(list) - for stype in sensor_types: - socks[stype] = messaging.sub_sock(stype, poller=poller, timeout=100) + for config in SENSOR_CONFIGS: + socks[config.service] = messaging.sub_sock(config.service, poller=poller, timeout=100) # wait for sensors to come up with Timeout(int(os.environ.get("SENSOR_WAIT", "5")), "sensors didn't come up"): @@ -91,11 +44,15 @@ def read_sensor_events(duration_sec): for s in socks: events[s] += messaging.drain_sock(socks[s]) time.sleep(0.1) - assert sum(map(len, events.values())) != 0, "No sensor events collected!" return {k: v for k, v in events.items() if len(v) > 0} +def iter_measurements(events): + for msgs in events.values(): + for measurement in msgs: + yield measurement, getattr(measurement, measurement.which()) + @pytest.mark.tici class TestSensord: @classmethod @@ -123,31 +80,19 @@ def teardown_class(cls): def teardown_method(self): managed_processes["sensord"].stop() - def test_sensors_present(self): - # verify correct sensors configuration - seen = set() - for etype in self.events: - for measurement in self.events[etype]: - m = getattr(measurement, measurement.which()) - seen.add((str(m.source), m.which())) - - assert seen in SENSOR_CONFIGURATIONS + def test_all_sensors_present(self): + missing = [config.service for config in SENSOR_CONFIGS if config.service not in self.events] + assert len(missing) == 0, f"missing sensors: {missing}" def test_lsm6ds3_timing(self, subtests): # verify measurements are sampled and published at 104Hz - sensor_t = { - 1: [], # accel - 5: [], # gyro - } - - for measurement in self.events['accelerometer']: - m = getattr(measurement, measurement.which()) - sensor_t[m.sensor].append(m.timestamp) + sensor_t = {service: [] for service in ('accelerometer', 'gyroscope')} - for measurement in self.events['gyroscope']: - m = getattr(measurement, measurement.which()) - sensor_t[m.sensor].append(m.timestamp) + for service in sensor_t: + for measurement in self.events.get(service, []): + m = getattr(measurement, measurement.which()) + sensor_t[service].append(m.timestamp) for s, vals in sensor_t.items(): with subtests.test(sensor=s): @@ -174,19 +119,16 @@ def test_sensor_frequency(self, subtests): def test_logmonottime_timestamp_diff(self): # ensure diff between the message logMonotime and sample timestamp is small - tdiffs = list() - for etype in self.events: - for measurement in self.events[etype]: - m = getattr(measurement, measurement.which()) - - # check if gyro and accel timestamps are before logMonoTime - if str(m.source).startswith("lsm6ds3") and m.which() != 'temperature': - err_msg = f"Timestamp after logMonoTime: {m.timestamp} > {measurement.logMonoTime}" - assert m.timestamp < measurement.logMonoTime, err_msg + tdiffs = [] + for measurement, m in iter_measurements(self.events): + # check if gyro and accel timestamps are before logMonoTime + if str(m.source).startswith("lsm6ds3") and m.which() != 'temperature': + err_msg = f"Timestamp after logMonoTime: {m.timestamp} > {measurement.logMonoTime}" + assert m.timestamp < measurement.logMonoTime, err_msg - # negative values might occur, as non interrupt packages created - # before the sensor is read - tdiffs.append(abs(measurement.logMonoTime - m.timestamp) / 1e6) + # negative values might occur, as non interrupt packages created + # before the sensor is read + tdiffs.append(abs(measurement.logMonoTime - m.timestamp) / 1e6) # some sensors have a read procedure that will introduce an expected diff on the order of 20ms high_delay_diffs = set(filter(lambda d: d >= 25., tdiffs)) @@ -196,32 +138,29 @@ def test_logmonottime_timestamp_diff(self): assert avg_diff < 4, f"Avg packet diff: {avg_diff:.1f}ms" def test_sensor_values(self): - sensor_values = dict() - for etype in self.events: - for measurement in self.events[etype]: - m = getattr(measurement, measurement.which()) - key = (m.source.raw, m.which()) - values = getattr(m, m.which()) + sensor_values = defaultdict(list) + for _, m in iter_measurements(self.events): + key = (m.source.raw, m.which()) + values = getattr(m, m.which()) - if hasattr(values, 'v'): - values = values.v - values = np.atleast_1d(values) - - if key in sensor_values: - sensor_values[key].append(values) - else: - sensor_values[key] = [values] + if hasattr(values, 'v'): + values = values.v + sensor_values[key].append(np.atleast_1d(values)) # Sanity check sensor values - for sensor, stype in sensor_values: - for s in ALL_SENSORS[sensor]: - if s.type != stype: - continue + for (sensor, stype), values in sensor_values.items(): + config = SENSOR_CONFIGS_BY_MEASUREMENT[stype] + + if config.measurement == 'temperature': + measurement_stat = np.mean(values) + else: + measurement_stat = np.mean(np.linalg.norm(values, axis=1)) + err_msg = f"Sensor '{sensor} {config.measurement}' failed sanity checks {measurement_stat} is not between {config.sanity_min} and {config.sanity_max}" + assert config.sanity_min <= measurement_stat <= config.sanity_max, err_msg - key = (sensor, s.type) - mean_norm = np.mean(np.linalg.norm(sensor_values[key], axis=1)) - err_msg = f"Sensor '{sensor} {s.type}' failed sanity checks {mean_norm} is not between {s.sanity_min} and {s.sanity_max}" - assert s.sanity_min <= mean_norm <= s.sanity_max, err_msg + std_dev = np.std(values, axis=0) + err_msg = f"Sensor '{sensor} {config.measurement}' failed std dev test {std_dev} is not under {config.std_max}" + assert np.all(std_dev <= config.std_max), err_msg def test_sensor_verify_no_interrupts_after_stop(self): managed_processes["sensord"].start() @@ -243,4 +182,3 @@ def test_sensor_verify_no_interrupts_after_stop(self): time.sleep(1) state_two = get_irq_count(self.sensord_irq) assert state_one == state_two, "Interrupts received after sensord stop!" - diff --git a/system/sensord/tests/ttff_test.py b/system/sensord/tests/ttff_test.py deleted file mode 100755 index a9cc16d7079de7..00000000000000 --- a/system/sensord/tests/ttff_test.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env python3 - -import time -import atexit - -from cereal import messaging -from openpilot.system.manager.process_config import managed_processes - -TIMEOUT = 10*60 - -def kill(): - for proc in ['ubloxd', 'pigeond']: - managed_processes[proc].stop(retry=True, block=True) - -if __name__ == "__main__": - # start ubloxd - managed_processes['ubloxd'].start() - atexit.register(kill) - - sm = messaging.SubMaster(['ubloxGnss']) - - times = [] - for i in range(20): - # start pigeond - st = time.monotonic() - managed_processes['pigeond'].start() - - # wait for a >4 satellite fix - while True: - sm.update(0) - msg = sm['ubloxGnss'] - if msg.which() == 'measurementReport' and sm.updated["ubloxGnss"]: - report = msg.measurementReport - if report.numMeas > 4: - times.append(time.monotonic() - st) - print(f"\033[94m{i}: Got a fix in {round(times[-1], 2)} seconds\033[0m") - break - - if time.monotonic() - st > TIMEOUT: - raise TimeoutError("\033[91mFailed to get a fix in {TIMEOUT} seconds!\033[0m") - - time.sleep(0.1) - - # stop pigeond - managed_processes['pigeond'].stop(retry=True, block=True) - time.sleep(20) - - print(f"\033[92mAverage TTFF: {round(sum(times) / len(times), 2)}s\033[0m") diff --git a/system/sentry.py b/system/sentry.py index 5f4772fa711a0d..47d64ba0fde75a 100644 --- a/system/sentry.py +++ b/system/sentry.py @@ -49,7 +49,7 @@ def init(project: SentryProject) -> bool: return False env = "release" if build_metadata.tested_channel else "master" - dongle_id = Params().get("DongleId", encoding='utf-8') + dongle_id = Params().get("DongleId") integrations = [] if project == SentryProject.SELFDRIVE: @@ -63,8 +63,6 @@ def init(project: SentryProject) -> bool: max_value_length=8192, environment=env) - build_metadata = get_build_metadata() - sentry_sdk.set_user({"id": dongle_id}) sentry_sdk.set_tag("dirty", build_metadata.openpilot.is_dirty) sentry_sdk.set_tag("origin", build_metadata.openpilot.git_origin) @@ -72,7 +70,4 @@ def init(project: SentryProject) -> bool: sentry_sdk.set_tag("commit", build_metadata.openpilot.git_commit) sentry_sdk.set_tag("device", HARDWARE.get_device_type()) - if project == SentryProject.SELFDRIVE: - sentry_sdk.Hub.current.start_session() - return True diff --git a/system/statsd.py b/system/statsd.py index 5e76b73ae99976..33e9e9912d4a1c 100755 --- a/system/statsd.py +++ b/system/statsd.py @@ -2,6 +2,7 @@ import os import zmq import time +import uuid from pathlib import Path from collections import defaultdict from datetime import datetime, UTC @@ -12,7 +13,7 @@ from openpilot.system.hardware.hw import Paths from openpilot.common.swaglog import cloudlog from openpilot.system.hardware import HARDWARE -from openpilot.common.file_helpers import atomic_write_in_dir +from openpilot.common.utils import atomic_write from openpilot.system.version import get_build_metadata from openpilot.system.loggerd.config import STATS_DIR_FILE_LIMIT, STATS_SOCKET, STATS_FLUSH_TIME_S @@ -60,7 +61,7 @@ def sample(self, name: str, value: float): def main() -> NoReturn: - dongle_id = Params().get("DongleId", encoding='utf-8') + dongle_id = Params().get("DongleId") def get_influxdb_line(measurement: str, value: float | dict[str, float], timestamp: datetime, tags: dict) -> str: res = f"{measurement}" for k, v in tags.items(): @@ -102,6 +103,7 @@ def get_influxdb_line(measurement: str, value: float | dict[str, float], timest sm = SubMaster(['deviceState']) idx = 0 + boot_uid = str(uuid.uuid4())[:8] last_flush_time = time.monotonic() gauges = {} samples: dict[str, list[float]] = defaultdict(list) @@ -164,8 +166,8 @@ def get_influxdb_line(measurement: str, value: float | dict[str, float], timest # check that we aren't filling up the drive if len(os.listdir(STATS_DIR)) < STATS_DIR_FILE_LIMIT: if len(result) > 0: - stats_path = os.path.join(STATS_DIR, f"{current_time.timestamp():.0f}_{idx}") - with atomic_write_in_dir(stats_path) as f: + stats_path = os.path.join(STATS_DIR, f"{boot_uid}_{idx}") + with atomic_write(stats_path) as f: f.write(result) idx += 1 else: diff --git a/system/tests/test_logmessaged.py b/system/tests/test_logmessaged.py index 3baf5300c0c13e..9ccc8ef53bc25c 100644 --- a/system/tests/test_logmessaged.py +++ b/system/tests/test_logmessaged.py @@ -19,7 +19,7 @@ def setup_method(self): self.error_sock = messaging.sub_sock("logMessage", timeout=1000, conflate=False) # ensure sockets are connected - time.sleep(1) + time.sleep(0.5) messaging.drain_sock(self.sock) messaging.drain_sock(self.error_sock) @@ -35,7 +35,7 @@ def test_simple_log(self): msgs = [f"abc {i}" for i in range(10)] for m in msgs: cloudlog.error(m) - time.sleep(3) + time.sleep(0.5) m = messaging.drain_sock(self.sock) assert len(m) == len(msgs) assert len(self._get_log_files()) >= 1 @@ -45,7 +45,7 @@ def test_big_log(self): msg = "a"*3*1024*1024 for _ in range(n): cloudlog.info(msg) - time.sleep(3) + time.sleep(0.5) msgs = messaging.drain_sock(self.sock) assert len(msgs) == 0 diff --git a/system/timed.py b/system/timed.py index 31d0d065886879..c74ba51da59923 100755 --- a/system/timed.py +++ b/system/timed.py @@ -5,7 +5,7 @@ from typing import NoReturn import cereal.messaging as messaging -from openpilot.common.time import system_time_valid +from openpilot.common.time_helpers import min_date, MAX_DATE, system_time_valid from openpilot.common.swaglog import cloudlog from openpilot.common.params import Params from openpilot.common.gps import get_gps_location_service @@ -13,7 +13,7 @@ def set_time(new_time): diff = datetime.datetime.now() - new_time - if diff < datetime.timedelta(seconds=10): + if abs(diff) < datetime.timedelta(seconds=10): cloudlog.debug(f"Time diff too small: {diff}") return @@ -26,10 +26,10 @@ def set_time(new_time): def main() -> NoReturn: """ - timed has one responsibility: - - getting the current time + timed has two responsibilities: + - getting the current time from GPS + - publishing the time in the logs - GPS directly gives time. AGNOS will also use NTP to update the time. """ @@ -47,14 +47,15 @@ def main() -> NoReturn: pm.send('clocks', msg) gps = sm[gps_location_service] + gps_time = datetime.datetime.fromtimestamp(gps.unixTimestampMillis / 1000.) if not sm.updated[gps_location_service] or (time.monotonic() - sm.logMonoTime[gps_location_service] / 1e9) > 2.0: continue + if not gps.hasFix: + continue + if gps_time < min_date() or gps_time > MAX_DATE: + continue - # set time - # TODO: account for unixTimesatmpMillis being a (usually short) time in the past - gps_time = datetime.datetime.fromtimestamp(gps.unixTimestampMillis / 1000.) set_time(gps_time) - time.sleep(10) if __name__ == "__main__": diff --git a/system/ubloxd/.gitignore b/system/ubloxd/.gitignore deleted file mode 100644 index 05263ff67caf37..00000000000000 --- a/system/ubloxd/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -ubloxd -tests/test_glonass_runner diff --git a/system/ubloxd/SConscript b/system/ubloxd/SConscript deleted file mode 100644 index ce09e235e622e4..00000000000000 --- a/system/ubloxd/SConscript +++ /dev/null @@ -1,20 +0,0 @@ -Import('env', 'common', 'messaging') - -loc_libs = [messaging, common, 'kaitai', 'pthread'] - -if GetOption('kaitai'): - generated = Dir('generated').srcnode().abspath - cmd = f"kaitai-struct-compiler --target cpp_stl --outdir {generated} $SOURCES" - env.Command(['generated/ubx.cpp', 'generated/ubx.h'], 'ubx.ksy', cmd) - env.Command(['generated/gps.cpp', 'generated/gps.h'], 'gps.ksy', cmd) - glonass = env.Command(['generated/glonass.cpp', 'generated/glonass.h'], 'glonass.ksy', cmd) - - # kaitai issue: https://github.com/kaitai-io/kaitai_struct/issues/910 - patch = env.Command(None, 'glonass_fix.patch', 'git apply $SOURCES') - env.Depends(patch, glonass) - -glonass_obj = env.Object('generated/glonass.cpp') -env.Program("ubloxd", ["ubloxd.cc", "ublox_msg.cc", "generated/ubx.cpp", "generated/gps.cpp", glonass_obj], LIBS=loc_libs) - -if GetOption('extras'): - env.Program("tests/test_glonass_runner", ['tests/test_glonass_runner.cc', 'tests/test_glonass_kaitai.cc', glonass_obj], LIBS=[loc_libs]) \ No newline at end of file diff --git a/system/ubloxd/binary_struct.py b/system/ubloxd/binary_struct.py new file mode 100644 index 00000000000000..c144bd56962b6f --- /dev/null +++ b/system/ubloxd/binary_struct.py @@ -0,0 +1,280 @@ +""" +Binary struct parsing DSL. + +Defines a declarative schema for binary messages using dataclasses +and type annotations. +""" + +import struct +from enum import Enum +from dataclasses import dataclass, is_dataclass +from typing import Annotated, Any, TypeVar, get_args, get_origin + + +class FieldType: + """Base class for field type descriptors.""" + + +@dataclass(frozen=True) +class IntType(FieldType): + bits: int + signed: bool + big_endian: bool = False + +@dataclass(frozen=True) +class FloatType(FieldType): + bits: int + +@dataclass(frozen=True) +class BitsType(FieldType): + bits: int + +@dataclass(frozen=True) +class BytesType(FieldType): + size: int + +@dataclass(frozen=True) +class ArrayType(FieldType): + element_type: Any + count_field: str + +@dataclass(frozen=True) +class SwitchType(FieldType): + selector: str + cases: dict[Any, Any] + default: Any = None + +@dataclass(frozen=True) +class EnumType(FieldType): + base_type: FieldType + enum_cls: type[Enum] + +@dataclass(frozen=True) +class ConstType(FieldType): + base_type: FieldType + expected: Any + +@dataclass(frozen=True) +class SubstreamType(FieldType): + length_field: str + element_type: Any + +# Common types - little endian +u8 = IntType(8, False) +u16 = IntType(16, False) +u32 = IntType(32, False) +s8 = IntType(8, True) +s16 = IntType(16, True) +s32 = IntType(32, True) +f32 = FloatType(32) +f64 = FloatType(64) +# Big endian variants +u16be = IntType(16, False, big_endian=True) +u32be = IntType(32, False, big_endian=True) +s16be = IntType(16, True, big_endian=True) +s32be = IntType(32, True, big_endian=True) + + +def bits(n: int) -> BitsType: + """Create a bit-level field type.""" + return BitsType(n) + +def bytes_field(size: int) -> BytesType: + """Create a fixed-size bytes field.""" + return BytesType(size) + +def array(element_type: Any, count_field: str) -> ArrayType: + """Create an array/repeated field.""" + return ArrayType(element_type, count_field) + +def switch(selector: str, cases: dict[Any, Any], default: Any = None) -> SwitchType: + """Create a switch-on field.""" + return SwitchType(selector, cases, default) + +def enum(base_type: Any, enum_cls: type[Enum]) -> EnumType: + """Create an enum-wrapped field.""" + field_type = _field_type_from_spec(base_type) + if field_type is None: + raise TypeError(f"Unsupported field type: {base_type!r}") + return EnumType(field_type, enum_cls) + +def const(base_type: Any, expected: Any) -> ConstType: + """Create a constant-value field.""" + field_type = _field_type_from_spec(base_type) + if field_type is None: + raise TypeError(f"Unsupported field type: {base_type!r}") + return ConstType(field_type, expected) + +def substream(length_field: str, element_type: Any) -> SubstreamType: + """Parse a fixed-length substream using an inner schema.""" + return SubstreamType(length_field, element_type) + + +class BinaryReader: + def __init__(self, data: bytes): + self.data = data + self.pos = 0 + self.bit_pos = 0 # 0-7, position within current byte + + def _require(self, n: int) -> None: + if self.pos + n > len(self.data): + raise EOFError("Unexpected end of data") + + def _read_struct(self, fmt: str): + self._align_to_byte() + size = struct.calcsize(fmt) + self._require(size) + value = struct.unpack_from(fmt, self.data, self.pos)[0] + self.pos += size + return value + + def read_bytes(self, n: int) -> bytes: + self._align_to_byte() + self._require(n) + result = self.data[self.pos : self.pos + n] + self.pos += n + return result + + def read_bits_int_be(self, n: int) -> int: + result = 0 + bits_remaining = n + while bits_remaining > 0: + if self.pos >= len(self.data): + raise EOFError("Unexpected end of data while reading bits") + bits_in_byte = 8 - self.bit_pos + bits_to_read = min(bits_remaining, bits_in_byte) + byte_val = self.data[self.pos] + shift = bits_in_byte - bits_to_read + mask = (1 << bits_to_read) - 1 + extracted = (byte_val >> shift) & mask + result = (result << bits_to_read) | extracted + self.bit_pos += bits_to_read + bits_remaining -= bits_to_read + if self.bit_pos >= 8: + self.bit_pos = 0 + self.pos += 1 + return result + + def _align_to_byte(self) -> None: + if self.bit_pos > 0: + self.bit_pos = 0 + self.pos += 1 + + +T = TypeVar('T', bound='BinaryStruct') + + +class BinaryStruct: + """Base class for binary struct definitions.""" + + def __init_subclass__(cls, **kwargs) -> None: + super().__init_subclass__(**kwargs) + if cls is BinaryStruct: + return + if not is_dataclass(cls): + dataclass(init=False)(cls) + fields = list(getattr(cls, '__annotations__', {}).items()) + cls.__binary_fields__ = fields + + @classmethod + def _read(inner_cls, reader: BinaryReader): + obj = inner_cls.__new__(inner_cls) + for name, spec in inner_cls.__binary_fields__: + value = _parse_field(spec, reader, obj) + setattr(obj, name, value) + return obj + + cls._read = _read + + @classmethod + def from_bytes(cls: type[T], data: bytes) -> T: + """Parse struct from bytes.""" + reader = BinaryReader(data) + return cls._read(reader) + + @classmethod + def _read(cls: type[T], reader: BinaryReader) -> T: + """Override in subclasses to implement parsing.""" + raise NotImplementedError + + +def _resolve_path(obj: Any, path: str) -> Any: + cur = obj + for part in path.split('.'): + cur = getattr(cur, part) + return cur + +def _unwrap_annotated(spec: Any) -> tuple[Any, ...]: + if get_origin(spec) is Annotated: + return get_args(spec)[1:] + return () + +def _field_type_from_spec(spec: Any) -> FieldType | None: + if isinstance(spec, FieldType): + return spec + for item in _unwrap_annotated(spec): + if isinstance(item, FieldType): + return item + return None + + +def _int_format(field_type: IntType) -> str: + if field_type.bits == 8: + return 'b' if field_type.signed else 'B' + endian = '>' if field_type.big_endian else '<' + if field_type.bits == 16: + code = 'h' if field_type.signed else 'H' + elif field_type.bits == 32: + code = 'i' if field_type.signed else 'I' + else: + raise ValueError(f"Unsupported integer size: {field_type.bits}") + return f"{endian}{code}" + +def _float_format(field_type: FloatType) -> str: + if field_type.bits == 32: + return ' Any: + field_type = _field_type_from_spec(spec) + if field_type is not None: + spec = field_type + if isinstance(spec, ConstType): + value = _parse_field(spec.base_type, reader, obj) + if value != spec.expected: + raise ValueError(f"Invalid constant: expected {spec.expected!r}, got {value!r}") + return value + if isinstance(spec, EnumType): + raw = _parse_field(spec.base_type, reader, obj) + try: + return spec.enum_cls(raw) + except ValueError: + return raw + if isinstance(spec, SwitchType): + key = _resolve_path(obj, spec.selector) + target = spec.cases.get(key, spec.default) + if target is None: + return None + return _parse_field(target, reader, obj) + if isinstance(spec, ArrayType): + count = _resolve_path(obj, spec.count_field) + return [_parse_field(spec.element_type, reader, obj) for _ in range(int(count))] + if isinstance(spec, SubstreamType): + length = _resolve_path(obj, spec.length_field) + data = reader.read_bytes(int(length)) + sub_reader = BinaryReader(data) + return _parse_field(spec.element_type, sub_reader, obj) + if isinstance(spec, IntType): + return reader._read_struct(_int_format(spec)) + if isinstance(spec, FloatType): + return reader._read_struct(_float_format(spec)) + if isinstance(spec, BitsType): + value = reader.read_bits_int_be(spec.bits) + return bool(value) if spec.bits == 1 else value + if isinstance(spec, BytesType): + return reader.read_bytes(spec.size) + if isinstance(spec, type) and issubclass(spec, BinaryStruct): + return spec._read(reader) + raise TypeError(f"Unsupported field spec: {spec!r}") diff --git a/system/ubloxd/generated/glonass.cpp b/system/ubloxd/generated/glonass.cpp deleted file mode 100644 index cd0f96ab68da91..00000000000000 --- a/system/ubloxd/generated/glonass.cpp +++ /dev/null @@ -1,353 +0,0 @@ -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "glonass.h" - -glonass_t::glonass_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = this; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::_read() { - m_idle_chip = m__io->read_bits_int_be(1); - m_string_number = m__io->read_bits_int_be(4); - //m__io->align_to_byte(); - switch (string_number()) { - case 4: { - m_data = new string_4_t(m__io, this, m__root); - break; - } - case 1: { - m_data = new string_1_t(m__io, this, m__root); - break; - } - case 3: { - m_data = new string_3_t(m__io, this, m__root); - break; - } - case 5: { - m_data = new string_5_t(m__io, this, m__root); - break; - } - case 2: { - m_data = new string_2_t(m__io, this, m__root); - break; - } - default: { - m_data = new string_non_immediate_t(m__io, this, m__root); - break; - } - } - m_hamming_code = m__io->read_bits_int_be(8); - m_pad_1 = m__io->read_bits_int_be(11); - m_superframe_number = m__io->read_bits_int_be(16); - m_pad_2 = m__io->read_bits_int_be(8); - m_frame_number = m__io->read_bits_int_be(8); -} - -glonass_t::~glonass_t() { - _clean_up(); -} - -void glonass_t::_clean_up() { - if (m_data) { - delete m_data; m_data = 0; - } -} - -glonass_t::string_4_t::string_4_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_tau_n = false; - f_delta_tau_n = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_4_t::_read() { - m_tau_n_sign = m__io->read_bits_int_be(1); - m_tau_n_value = m__io->read_bits_int_be(21); - m_delta_tau_n_sign = m__io->read_bits_int_be(1); - m_delta_tau_n_value = m__io->read_bits_int_be(4); - m_e_n = m__io->read_bits_int_be(5); - m_not_used_1 = m__io->read_bits_int_be(14); - m_p4 = m__io->read_bits_int_be(1); - m_f_t = m__io->read_bits_int_be(4); - m_not_used_2 = m__io->read_bits_int_be(3); - m_n_t = m__io->read_bits_int_be(11); - m_n = m__io->read_bits_int_be(5); - m_m = m__io->read_bits_int_be(2); -} - -glonass_t::string_4_t::~string_4_t() { - _clean_up(); -} - -void glonass_t::string_4_t::_clean_up() { -} - -int32_t glonass_t::string_4_t::tau_n() { - if (f_tau_n) - return m_tau_n; - m_tau_n = ((tau_n_sign()) ? ((tau_n_value() * -1)) : (tau_n_value())); - f_tau_n = true; - return m_tau_n; -} - -int32_t glonass_t::string_4_t::delta_tau_n() { - if (f_delta_tau_n) - return m_delta_tau_n; - m_delta_tau_n = ((delta_tau_n_sign()) ? ((delta_tau_n_value() * -1)) : (delta_tau_n_value())); - f_delta_tau_n = true; - return m_delta_tau_n; -} - -glonass_t::string_non_immediate_t::string_non_immediate_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_non_immediate_t::_read() { - m_data_1 = m__io->read_bits_int_be(64); - m_data_2 = m__io->read_bits_int_be(8); -} - -glonass_t::string_non_immediate_t::~string_non_immediate_t() { - _clean_up(); -} - -void glonass_t::string_non_immediate_t::_clean_up() { -} - -glonass_t::string_5_t::string_5_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_5_t::_read() { - m_n_a = m__io->read_bits_int_be(11); - m_tau_c = m__io->read_bits_int_be(32); - m_not_used = m__io->read_bits_int_be(1); - m_n_4 = m__io->read_bits_int_be(5); - m_tau_gps = m__io->read_bits_int_be(22); - m_l_n = m__io->read_bits_int_be(1); -} - -glonass_t::string_5_t::~string_5_t() { - _clean_up(); -} - -void glonass_t::string_5_t::_clean_up() { -} - -glonass_t::string_1_t::string_1_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_x_vel = false; - f_x_accel = false; - f_x = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_1_t::_read() { - m_not_used = m__io->read_bits_int_be(2); - m_p1 = m__io->read_bits_int_be(2); - m_t_k = m__io->read_bits_int_be(12); - m_x_vel_sign = m__io->read_bits_int_be(1); - m_x_vel_value = m__io->read_bits_int_be(23); - m_x_accel_sign = m__io->read_bits_int_be(1); - m_x_accel_value = m__io->read_bits_int_be(4); - m_x_sign = m__io->read_bits_int_be(1); - m_x_value = m__io->read_bits_int_be(26); -} - -glonass_t::string_1_t::~string_1_t() { - _clean_up(); -} - -void glonass_t::string_1_t::_clean_up() { -} - -int32_t glonass_t::string_1_t::x_vel() { - if (f_x_vel) - return m_x_vel; - m_x_vel = ((x_vel_sign()) ? ((x_vel_value() * -1)) : (x_vel_value())); - f_x_vel = true; - return m_x_vel; -} - -int32_t glonass_t::string_1_t::x_accel() { - if (f_x_accel) - return m_x_accel; - m_x_accel = ((x_accel_sign()) ? ((x_accel_value() * -1)) : (x_accel_value())); - f_x_accel = true; - return m_x_accel; -} - -int32_t glonass_t::string_1_t::x() { - if (f_x) - return m_x; - m_x = ((x_sign()) ? ((x_value() * -1)) : (x_value())); - f_x = true; - return m_x; -} - -glonass_t::string_2_t::string_2_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_y_vel = false; - f_y_accel = false; - f_y = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_2_t::_read() { - m_b_n = m__io->read_bits_int_be(3); - m_p2 = m__io->read_bits_int_be(1); - m_t_b = m__io->read_bits_int_be(7); - m_not_used = m__io->read_bits_int_be(5); - m_y_vel_sign = m__io->read_bits_int_be(1); - m_y_vel_value = m__io->read_bits_int_be(23); - m_y_accel_sign = m__io->read_bits_int_be(1); - m_y_accel_value = m__io->read_bits_int_be(4); - m_y_sign = m__io->read_bits_int_be(1); - m_y_value = m__io->read_bits_int_be(26); -} - -glonass_t::string_2_t::~string_2_t() { - _clean_up(); -} - -void glonass_t::string_2_t::_clean_up() { -} - -int32_t glonass_t::string_2_t::y_vel() { - if (f_y_vel) - return m_y_vel; - m_y_vel = ((y_vel_sign()) ? ((y_vel_value() * -1)) : (y_vel_value())); - f_y_vel = true; - return m_y_vel; -} - -int32_t glonass_t::string_2_t::y_accel() { - if (f_y_accel) - return m_y_accel; - m_y_accel = ((y_accel_sign()) ? ((y_accel_value() * -1)) : (y_accel_value())); - f_y_accel = true; - return m_y_accel; -} - -int32_t glonass_t::string_2_t::y() { - if (f_y) - return m_y; - m_y = ((y_sign()) ? ((y_value() * -1)) : (y_value())); - f_y = true; - return m_y; -} - -glonass_t::string_3_t::string_3_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_gamma_n = false; - f_z_vel = false; - f_z_accel = false; - f_z = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_3_t::_read() { - m_p3 = m__io->read_bits_int_be(1); - m_gamma_n_sign = m__io->read_bits_int_be(1); - m_gamma_n_value = m__io->read_bits_int_be(10); - m_not_used = m__io->read_bits_int_be(1); - m_p = m__io->read_bits_int_be(2); - m_l_n = m__io->read_bits_int_be(1); - m_z_vel_sign = m__io->read_bits_int_be(1); - m_z_vel_value = m__io->read_bits_int_be(23); - m_z_accel_sign = m__io->read_bits_int_be(1); - m_z_accel_value = m__io->read_bits_int_be(4); - m_z_sign = m__io->read_bits_int_be(1); - m_z_value = m__io->read_bits_int_be(26); -} - -glonass_t::string_3_t::~string_3_t() { - _clean_up(); -} - -void glonass_t::string_3_t::_clean_up() { -} - -int32_t glonass_t::string_3_t::gamma_n() { - if (f_gamma_n) - return m_gamma_n; - m_gamma_n = ((gamma_n_sign()) ? ((gamma_n_value() * -1)) : (gamma_n_value())); - f_gamma_n = true; - return m_gamma_n; -} - -int32_t glonass_t::string_3_t::z_vel() { - if (f_z_vel) - return m_z_vel; - m_z_vel = ((z_vel_sign()) ? ((z_vel_value() * -1)) : (z_vel_value())); - f_z_vel = true; - return m_z_vel; -} - -int32_t glonass_t::string_3_t::z_accel() { - if (f_z_accel) - return m_z_accel; - m_z_accel = ((z_accel_sign()) ? ((z_accel_value() * -1)) : (z_accel_value())); - f_z_accel = true; - return m_z_accel; -} - -int32_t glonass_t::string_3_t::z() { - if (f_z) - return m_z; - m_z = ((z_sign()) ? ((z_value() * -1)) : (z_value())); - f_z = true; - return m_z; -} diff --git a/system/ubloxd/generated/glonass.h b/system/ubloxd/generated/glonass.h deleted file mode 100644 index 19867ba22b220e..00000000000000 --- a/system/ubloxd/generated/glonass.h +++ /dev/null @@ -1,375 +0,0 @@ -#ifndef GLONASS_H_ -#define GLONASS_H_ - -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "kaitai/kaitaistruct.h" -#include - -#if KAITAI_STRUCT_VERSION < 9000L -#error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" -#endif - -class glonass_t : public kaitai::kstruct { - -public: - class string_4_t; - class string_non_immediate_t; - class string_5_t; - class string_1_t; - class string_2_t; - class string_3_t; - - glonass_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = 0, glonass_t* p__root = 0); - -private: - void _read(); - void _clean_up(); - -public: - ~glonass_t(); - - class string_4_t : public kaitai::kstruct { - - public: - - string_4_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_4_t(); - - private: - bool f_tau_n; - int32_t m_tau_n; - - public: - int32_t tau_n(); - - private: - bool f_delta_tau_n; - int32_t m_delta_tau_n; - - public: - int32_t delta_tau_n(); - - private: - bool m_tau_n_sign; - uint64_t m_tau_n_value; - bool m_delta_tau_n_sign; - uint64_t m_delta_tau_n_value; - uint64_t m_e_n; - uint64_t m_not_used_1; - bool m_p4; - uint64_t m_f_t; - uint64_t m_not_used_2; - uint64_t m_n_t; - uint64_t m_n; - uint64_t m_m; - glonass_t* m__root; - glonass_t* m__parent; - - public: - bool tau_n_sign() const { return m_tau_n_sign; } - uint64_t tau_n_value() const { return m_tau_n_value; } - bool delta_tau_n_sign() const { return m_delta_tau_n_sign; } - uint64_t delta_tau_n_value() const { return m_delta_tau_n_value; } - uint64_t e_n() const { return m_e_n; } - uint64_t not_used_1() const { return m_not_used_1; } - bool p4() const { return m_p4; } - uint64_t f_t() const { return m_f_t; } - uint64_t not_used_2() const { return m_not_used_2; } - uint64_t n_t() const { return m_n_t; } - uint64_t n() const { return m_n; } - uint64_t m() const { return m_m; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_non_immediate_t : public kaitai::kstruct { - - public: - - string_non_immediate_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_non_immediate_t(); - - private: - uint64_t m_data_1; - uint64_t m_data_2; - glonass_t* m__root; - glonass_t* m__parent; - - public: - uint64_t data_1() const { return m_data_1; } - uint64_t data_2() const { return m_data_2; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_5_t : public kaitai::kstruct { - - public: - - string_5_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_5_t(); - - private: - uint64_t m_n_a; - uint64_t m_tau_c; - bool m_not_used; - uint64_t m_n_4; - uint64_t m_tau_gps; - bool m_l_n; - glonass_t* m__root; - glonass_t* m__parent; - - public: - uint64_t n_a() const { return m_n_a; } - uint64_t tau_c() const { return m_tau_c; } - bool not_used() const { return m_not_used; } - uint64_t n_4() const { return m_n_4; } - uint64_t tau_gps() const { return m_tau_gps; } - bool l_n() const { return m_l_n; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_1_t : public kaitai::kstruct { - - public: - - string_1_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_1_t(); - - private: - bool f_x_vel; - int32_t m_x_vel; - - public: - int32_t x_vel(); - - private: - bool f_x_accel; - int32_t m_x_accel; - - public: - int32_t x_accel(); - - private: - bool f_x; - int32_t m_x; - - public: - int32_t x(); - - private: - uint64_t m_not_used; - uint64_t m_p1; - uint64_t m_t_k; - bool m_x_vel_sign; - uint64_t m_x_vel_value; - bool m_x_accel_sign; - uint64_t m_x_accel_value; - bool m_x_sign; - uint64_t m_x_value; - glonass_t* m__root; - glonass_t* m__parent; - - public: - uint64_t not_used() const { return m_not_used; } - uint64_t p1() const { return m_p1; } - uint64_t t_k() const { return m_t_k; } - bool x_vel_sign() const { return m_x_vel_sign; } - uint64_t x_vel_value() const { return m_x_vel_value; } - bool x_accel_sign() const { return m_x_accel_sign; } - uint64_t x_accel_value() const { return m_x_accel_value; } - bool x_sign() const { return m_x_sign; } - uint64_t x_value() const { return m_x_value; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_2_t : public kaitai::kstruct { - - public: - - string_2_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_2_t(); - - private: - bool f_y_vel; - int32_t m_y_vel; - - public: - int32_t y_vel(); - - private: - bool f_y_accel; - int32_t m_y_accel; - - public: - int32_t y_accel(); - - private: - bool f_y; - int32_t m_y; - - public: - int32_t y(); - - private: - uint64_t m_b_n; - bool m_p2; - uint64_t m_t_b; - uint64_t m_not_used; - bool m_y_vel_sign; - uint64_t m_y_vel_value; - bool m_y_accel_sign; - uint64_t m_y_accel_value; - bool m_y_sign; - uint64_t m_y_value; - glonass_t* m__root; - glonass_t* m__parent; - - public: - uint64_t b_n() const { return m_b_n; } - bool p2() const { return m_p2; } - uint64_t t_b() const { return m_t_b; } - uint64_t not_used() const { return m_not_used; } - bool y_vel_sign() const { return m_y_vel_sign; } - uint64_t y_vel_value() const { return m_y_vel_value; } - bool y_accel_sign() const { return m_y_accel_sign; } - uint64_t y_accel_value() const { return m_y_accel_value; } - bool y_sign() const { return m_y_sign; } - uint64_t y_value() const { return m_y_value; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_3_t : public kaitai::kstruct { - - public: - - string_3_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_3_t(); - - private: - bool f_gamma_n; - int32_t m_gamma_n; - - public: - int32_t gamma_n(); - - private: - bool f_z_vel; - int32_t m_z_vel; - - public: - int32_t z_vel(); - - private: - bool f_z_accel; - int32_t m_z_accel; - - public: - int32_t z_accel(); - - private: - bool f_z; - int32_t m_z; - - public: - int32_t z(); - - private: - bool m_p3; - bool m_gamma_n_sign; - uint64_t m_gamma_n_value; - bool m_not_used; - uint64_t m_p; - bool m_l_n; - bool m_z_vel_sign; - uint64_t m_z_vel_value; - bool m_z_accel_sign; - uint64_t m_z_accel_value; - bool m_z_sign; - uint64_t m_z_value; - glonass_t* m__root; - glonass_t* m__parent; - - public: - bool p3() const { return m_p3; } - bool gamma_n_sign() const { return m_gamma_n_sign; } - uint64_t gamma_n_value() const { return m_gamma_n_value; } - bool not_used() const { return m_not_used; } - uint64_t p() const { return m_p; } - bool l_n() const { return m_l_n; } - bool z_vel_sign() const { return m_z_vel_sign; } - uint64_t z_vel_value() const { return m_z_vel_value; } - bool z_accel_sign() const { return m_z_accel_sign; } - uint64_t z_accel_value() const { return m_z_accel_value; } - bool z_sign() const { return m_z_sign; } - uint64_t z_value() const { return m_z_value; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - -private: - bool m_idle_chip; - uint64_t m_string_number; - kaitai::kstruct* m_data; - uint64_t m_hamming_code; - uint64_t m_pad_1; - uint64_t m_superframe_number; - uint64_t m_pad_2; - uint64_t m_frame_number; - glonass_t* m__root; - kaitai::kstruct* m__parent; - -public: - bool idle_chip() const { return m_idle_chip; } - uint64_t string_number() const { return m_string_number; } - kaitai::kstruct* data() const { return m_data; } - uint64_t hamming_code() const { return m_hamming_code; } - uint64_t pad_1() const { return m_pad_1; } - uint64_t superframe_number() const { return m_superframe_number; } - uint64_t pad_2() const { return m_pad_2; } - uint64_t frame_number() const { return m_frame_number; } - glonass_t* _root() const { return m__root; } - kaitai::kstruct* _parent() const { return m__parent; } -}; - -#endif // GLONASS_H_ diff --git a/system/ubloxd/generated/gps.cpp b/system/ubloxd/generated/gps.cpp deleted file mode 100644 index 8e1cb85b956085..00000000000000 --- a/system/ubloxd/generated/gps.cpp +++ /dev/null @@ -1,325 +0,0 @@ -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "gps.h" -#include "kaitai/exceptions.h" - -gps_t::gps_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = this; - m_tlm = 0; - m_how = 0; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::_read() { - m_tlm = new tlm_t(m__io, this, m__root); - m_how = new how_t(m__io, this, m__root); - n_body = true; - switch (how()->subframe_id()) { - case 1: { - n_body = false; - m_body = new subframe_1_t(m__io, this, m__root); - break; - } - case 2: { - n_body = false; - m_body = new subframe_2_t(m__io, this, m__root); - break; - } - case 3: { - n_body = false; - m_body = new subframe_3_t(m__io, this, m__root); - break; - } - case 4: { - n_body = false; - m_body = new subframe_4_t(m__io, this, m__root); - break; - } - } -} - -gps_t::~gps_t() { - _clean_up(); -} - -void gps_t::_clean_up() { - if (m_tlm) { - delete m_tlm; m_tlm = 0; - } - if (m_how) { - delete m_how; m_how = 0; - } - if (!n_body) { - if (m_body) { - delete m_body; m_body = 0; - } - } -} - -gps_t::subframe_1_t::subframe_1_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_af_0 = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_1_t::_read() { - m_week_no = m__io->read_bits_int_be(10); - m_code = m__io->read_bits_int_be(2); - m_sv_accuracy = m__io->read_bits_int_be(4); - m_sv_health = m__io->read_bits_int_be(6); - m_iodc_msb = m__io->read_bits_int_be(2); - m_l2_p_data_flag = m__io->read_bits_int_be(1); - m_reserved1 = m__io->read_bits_int_be(23); - m_reserved2 = m__io->read_bits_int_be(24); - m_reserved3 = m__io->read_bits_int_be(24); - m_reserved4 = m__io->read_bits_int_be(16); - m__io->align_to_byte(); - m_t_gd = m__io->read_s1(); - m_iodc_lsb = m__io->read_u1(); - m_t_oc = m__io->read_u2be(); - m_af_2 = m__io->read_s1(); - m_af_1 = m__io->read_s2be(); - m_af_0_sign = m__io->read_bits_int_be(1); - m_af_0_value = m__io->read_bits_int_be(21); - m_reserved5 = m__io->read_bits_int_be(2); -} - -gps_t::subframe_1_t::~subframe_1_t() { - _clean_up(); -} - -void gps_t::subframe_1_t::_clean_up() { -} - -int32_t gps_t::subframe_1_t::af_0() { - if (f_af_0) - return m_af_0; - m_af_0 = ((af_0_sign()) ? ((af_0_value() - (1 << 21))) : (af_0_value())); - f_af_0 = true; - return m_af_0; -} - -gps_t::subframe_3_t::subframe_3_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_omega_dot = false; - f_idot = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_3_t::_read() { - m_c_ic = m__io->read_s2be(); - m_omega_0 = m__io->read_s4be(); - m_c_is = m__io->read_s2be(); - m_i_0 = m__io->read_s4be(); - m_c_rc = m__io->read_s2be(); - m_omega = m__io->read_s4be(); - m_omega_dot_sign = m__io->read_bits_int_be(1); - m_omega_dot_value = m__io->read_bits_int_be(23); - m__io->align_to_byte(); - m_iode = m__io->read_u1(); - m_idot_sign = m__io->read_bits_int_be(1); - m_idot_value = m__io->read_bits_int_be(13); - m_reserved = m__io->read_bits_int_be(2); -} - -gps_t::subframe_3_t::~subframe_3_t() { - _clean_up(); -} - -void gps_t::subframe_3_t::_clean_up() { -} - -int32_t gps_t::subframe_3_t::omega_dot() { - if (f_omega_dot) - return m_omega_dot; - m_omega_dot = ((omega_dot_sign()) ? ((omega_dot_value() - (1 << 23))) : (omega_dot_value())); - f_omega_dot = true; - return m_omega_dot; -} - -int32_t gps_t::subframe_3_t::idot() { - if (f_idot) - return m_idot; - m_idot = ((idot_sign()) ? ((idot_value() - (1 << 13))) : (idot_value())); - f_idot = true; - return m_idot; -} - -gps_t::subframe_4_t::subframe_4_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_4_t::_read() { - m_data_id = m__io->read_bits_int_be(2); - m_page_id = m__io->read_bits_int_be(6); - m__io->align_to_byte(); - n_body = true; - switch (page_id()) { - case 56: { - n_body = false; - m_body = new ionosphere_data_t(m__io, this, m__root); - break; - } - } -} - -gps_t::subframe_4_t::~subframe_4_t() { - _clean_up(); -} - -void gps_t::subframe_4_t::_clean_up() { - if (!n_body) { - if (m_body) { - delete m_body; m_body = 0; - } - } -} - -gps_t::subframe_4_t::ionosphere_data_t::ionosphere_data_t(kaitai::kstream* p__io, gps_t::subframe_4_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_4_t::ionosphere_data_t::_read() { - m_a0 = m__io->read_s1(); - m_a1 = m__io->read_s1(); - m_a2 = m__io->read_s1(); - m_a3 = m__io->read_s1(); - m_b0 = m__io->read_s1(); - m_b1 = m__io->read_s1(); - m_b2 = m__io->read_s1(); - m_b3 = m__io->read_s1(); -} - -gps_t::subframe_4_t::ionosphere_data_t::~ionosphere_data_t() { - _clean_up(); -} - -void gps_t::subframe_4_t::ionosphere_data_t::_clean_up() { -} - -gps_t::how_t::how_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::how_t::_read() { - m_tow_count = m__io->read_bits_int_be(17); - m_alert = m__io->read_bits_int_be(1); - m_anti_spoof = m__io->read_bits_int_be(1); - m_subframe_id = m__io->read_bits_int_be(3); - m_reserved = m__io->read_bits_int_be(2); -} - -gps_t::how_t::~how_t() { - _clean_up(); -} - -void gps_t::how_t::_clean_up() { -} - -gps_t::tlm_t::tlm_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::tlm_t::_read() { - m_preamble = m__io->read_bytes(1); - if (!(preamble() == std::string("\x8B", 1))) { - throw kaitai::validation_not_equal_error(std::string("\x8B", 1), preamble(), _io(), std::string("/types/tlm/seq/0")); - } - m_tlm = m__io->read_bits_int_be(14); - m_integrity_status = m__io->read_bits_int_be(1); - m_reserved = m__io->read_bits_int_be(1); -} - -gps_t::tlm_t::~tlm_t() { - _clean_up(); -} - -void gps_t::tlm_t::_clean_up() { -} - -gps_t::subframe_2_t::subframe_2_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_2_t::_read() { - m_iode = m__io->read_u1(); - m_c_rs = m__io->read_s2be(); - m_delta_n = m__io->read_s2be(); - m_m_0 = m__io->read_s4be(); - m_c_uc = m__io->read_s2be(); - m_e = m__io->read_s4be(); - m_c_us = m__io->read_s2be(); - m_sqrt_a = m__io->read_u4be(); - m_t_oe = m__io->read_u2be(); - m_fit_interval_flag = m__io->read_bits_int_be(1); - m_aoda = m__io->read_bits_int_be(5); - m_reserved = m__io->read_bits_int_be(2); -} - -gps_t::subframe_2_t::~subframe_2_t() { - _clean_up(); -} - -void gps_t::subframe_2_t::_clean_up() { -} diff --git a/system/ubloxd/generated/gps.h b/system/ubloxd/generated/gps.h deleted file mode 100644 index 9dfc5031f505c9..00000000000000 --- a/system/ubloxd/generated/gps.h +++ /dev/null @@ -1,359 +0,0 @@ -#ifndef GPS_H_ -#define GPS_H_ - -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "kaitai/kaitaistruct.h" -#include - -#if KAITAI_STRUCT_VERSION < 9000L -#error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" -#endif - -class gps_t : public kaitai::kstruct { - -public: - class subframe_1_t; - class subframe_3_t; - class subframe_4_t; - class how_t; - class tlm_t; - class subframe_2_t; - - gps_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = 0, gps_t* p__root = 0); - -private: - void _read(); - void _clean_up(); - -public: - ~gps_t(); - - class subframe_1_t : public kaitai::kstruct { - - public: - - subframe_1_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~subframe_1_t(); - - private: - bool f_af_0; - int32_t m_af_0; - - public: - int32_t af_0(); - - private: - uint64_t m_week_no; - uint64_t m_code; - uint64_t m_sv_accuracy; - uint64_t m_sv_health; - uint64_t m_iodc_msb; - bool m_l2_p_data_flag; - uint64_t m_reserved1; - uint64_t m_reserved2; - uint64_t m_reserved3; - uint64_t m_reserved4; - int8_t m_t_gd; - uint8_t m_iodc_lsb; - uint16_t m_t_oc; - int8_t m_af_2; - int16_t m_af_1; - bool m_af_0_sign; - uint64_t m_af_0_value; - uint64_t m_reserved5; - gps_t* m__root; - gps_t* m__parent; - - public: - uint64_t week_no() const { return m_week_no; } - uint64_t code() const { return m_code; } - uint64_t sv_accuracy() const { return m_sv_accuracy; } - uint64_t sv_health() const { return m_sv_health; } - uint64_t iodc_msb() const { return m_iodc_msb; } - bool l2_p_data_flag() const { return m_l2_p_data_flag; } - uint64_t reserved1() const { return m_reserved1; } - uint64_t reserved2() const { return m_reserved2; } - uint64_t reserved3() const { return m_reserved3; } - uint64_t reserved4() const { return m_reserved4; } - int8_t t_gd() const { return m_t_gd; } - uint8_t iodc_lsb() const { return m_iodc_lsb; } - uint16_t t_oc() const { return m_t_oc; } - int8_t af_2() const { return m_af_2; } - int16_t af_1() const { return m_af_1; } - bool af_0_sign() const { return m_af_0_sign; } - uint64_t af_0_value() const { return m_af_0_value; } - uint64_t reserved5() const { return m_reserved5; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class subframe_3_t : public kaitai::kstruct { - - public: - - subframe_3_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~subframe_3_t(); - - private: - bool f_omega_dot; - int32_t m_omega_dot; - - public: - int32_t omega_dot(); - - private: - bool f_idot; - int32_t m_idot; - - public: - int32_t idot(); - - private: - int16_t m_c_ic; - int32_t m_omega_0; - int16_t m_c_is; - int32_t m_i_0; - int16_t m_c_rc; - int32_t m_omega; - bool m_omega_dot_sign; - uint64_t m_omega_dot_value; - uint8_t m_iode; - bool m_idot_sign; - uint64_t m_idot_value; - uint64_t m_reserved; - gps_t* m__root; - gps_t* m__parent; - - public: - int16_t c_ic() const { return m_c_ic; } - int32_t omega_0() const { return m_omega_0; } - int16_t c_is() const { return m_c_is; } - int32_t i_0() const { return m_i_0; } - int16_t c_rc() const { return m_c_rc; } - int32_t omega() const { return m_omega; } - bool omega_dot_sign() const { return m_omega_dot_sign; } - uint64_t omega_dot_value() const { return m_omega_dot_value; } - uint8_t iode() const { return m_iode; } - bool idot_sign() const { return m_idot_sign; } - uint64_t idot_value() const { return m_idot_value; } - uint64_t reserved() const { return m_reserved; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class subframe_4_t : public kaitai::kstruct { - - public: - class ionosphere_data_t; - - subframe_4_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~subframe_4_t(); - - class ionosphere_data_t : public kaitai::kstruct { - - public: - - ionosphere_data_t(kaitai::kstream* p__io, gps_t::subframe_4_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~ionosphere_data_t(); - - private: - int8_t m_a0; - int8_t m_a1; - int8_t m_a2; - int8_t m_a3; - int8_t m_b0; - int8_t m_b1; - int8_t m_b2; - int8_t m_b3; - gps_t* m__root; - gps_t::subframe_4_t* m__parent; - - public: - int8_t a0() const { return m_a0; } - int8_t a1() const { return m_a1; } - int8_t a2() const { return m_a2; } - int8_t a3() const { return m_a3; } - int8_t b0() const { return m_b0; } - int8_t b1() const { return m_b1; } - int8_t b2() const { return m_b2; } - int8_t b3() const { return m_b3; } - gps_t* _root() const { return m__root; } - gps_t::subframe_4_t* _parent() const { return m__parent; } - }; - - private: - uint64_t m_data_id; - uint64_t m_page_id; - ionosphere_data_t* m_body; - bool n_body; - - public: - bool _is_null_body() { body(); return n_body; }; - - private: - gps_t* m__root; - gps_t* m__parent; - - public: - uint64_t data_id() const { return m_data_id; } - uint64_t page_id() const { return m_page_id; } - ionosphere_data_t* body() const { return m_body; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class how_t : public kaitai::kstruct { - - public: - - how_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~how_t(); - - private: - uint64_t m_tow_count; - bool m_alert; - bool m_anti_spoof; - uint64_t m_subframe_id; - uint64_t m_reserved; - gps_t* m__root; - gps_t* m__parent; - - public: - uint64_t tow_count() const { return m_tow_count; } - bool alert() const { return m_alert; } - bool anti_spoof() const { return m_anti_spoof; } - uint64_t subframe_id() const { return m_subframe_id; } - uint64_t reserved() const { return m_reserved; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class tlm_t : public kaitai::kstruct { - - public: - - tlm_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~tlm_t(); - - private: - std::string m_preamble; - uint64_t m_tlm; - bool m_integrity_status; - bool m_reserved; - gps_t* m__root; - gps_t* m__parent; - - public: - std::string preamble() const { return m_preamble; } - uint64_t tlm() const { return m_tlm; } - bool integrity_status() const { return m_integrity_status; } - bool reserved() const { return m_reserved; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class subframe_2_t : public kaitai::kstruct { - - public: - - subframe_2_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~subframe_2_t(); - - private: - uint8_t m_iode; - int16_t m_c_rs; - int16_t m_delta_n; - int32_t m_m_0; - int16_t m_c_uc; - int32_t m_e; - int16_t m_c_us; - uint32_t m_sqrt_a; - uint16_t m_t_oe; - bool m_fit_interval_flag; - uint64_t m_aoda; - uint64_t m_reserved; - gps_t* m__root; - gps_t* m__parent; - - public: - uint8_t iode() const { return m_iode; } - int16_t c_rs() const { return m_c_rs; } - int16_t delta_n() const { return m_delta_n; } - int32_t m_0() const { return m_m_0; } - int16_t c_uc() const { return m_c_uc; } - int32_t e() const { return m_e; } - int16_t c_us() const { return m_c_us; } - uint32_t sqrt_a() const { return m_sqrt_a; } - uint16_t t_oe() const { return m_t_oe; } - bool fit_interval_flag() const { return m_fit_interval_flag; } - uint64_t aoda() const { return m_aoda; } - uint64_t reserved() const { return m_reserved; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - -private: - tlm_t* m_tlm; - how_t* m_how; - kaitai::kstruct* m_body; - bool n_body; - -public: - bool _is_null_body() { body(); return n_body; }; - -private: - gps_t* m__root; - kaitai::kstruct* m__parent; - -public: - tlm_t* tlm() const { return m_tlm; } - how_t* how() const { return m_how; } - kaitai::kstruct* body() const { return m_body; } - gps_t* _root() const { return m__root; } - kaitai::kstruct* _parent() const { return m__parent; } -}; - -#endif // GPS_H_ diff --git a/system/ubloxd/generated/ubx.cpp b/system/ubloxd/generated/ubx.cpp deleted file mode 100644 index 81b82ccafca6a0..00000000000000 --- a/system/ubloxd/generated/ubx.cpp +++ /dev/null @@ -1,424 +0,0 @@ -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "ubx.h" -#include "kaitai/exceptions.h" - -ubx_t::ubx_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = this; - f_checksum = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::_read() { - m_magic = m__io->read_bytes(2); - if (!(magic() == std::string("\xB5\x62", 2))) { - throw kaitai::validation_not_equal_error(std::string("\xB5\x62", 2), magic(), _io(), std::string("/seq/0")); - } - m_msg_type = m__io->read_u2be(); - m_length = m__io->read_u2le(); - n_body = true; - switch (msg_type()) { - case 2569: { - n_body = false; - m_body = new mon_hw_t(m__io, this, m__root); - break; - } - case 533: { - n_body = false; - m_body = new rxm_rawx_t(m__io, this, m__root); - break; - } - case 531: { - n_body = false; - m_body = new rxm_sfrbx_t(m__io, this, m__root); - break; - } - case 309: { - n_body = false; - m_body = new nav_sat_t(m__io, this, m__root); - break; - } - case 2571: { - n_body = false; - m_body = new mon_hw2_t(m__io, this, m__root); - break; - } - case 263: { - n_body = false; - m_body = new nav_pvt_t(m__io, this, m__root); - break; - } - } -} - -ubx_t::~ubx_t() { - _clean_up(); -} - -void ubx_t::_clean_up() { - if (!n_body) { - if (m_body) { - delete m_body; m_body = 0; - } - } - if (f_checksum) { - } -} - -ubx_t::rxm_rawx_t::rxm_rawx_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - m_meas = 0; - m__raw_meas = 0; - m__io__raw_meas = 0; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::rxm_rawx_t::_read() { - m_rcv_tow = m__io->read_f8le(); - m_week = m__io->read_u2le(); - m_leap_s = m__io->read_s1(); - m_num_meas = m__io->read_u1(); - m_rec_stat = m__io->read_u1(); - m_reserved1 = m__io->read_bytes(3); - m__raw_meas = new std::vector(); - m__io__raw_meas = new std::vector(); - m_meas = new std::vector(); - const int l_meas = num_meas(); - for (int i = 0; i < l_meas; i++) { - m__raw_meas->push_back(m__io->read_bytes(32)); - kaitai::kstream* io__raw_meas = new kaitai::kstream(m__raw_meas->at(m__raw_meas->size() - 1)); - m__io__raw_meas->push_back(io__raw_meas); - m_meas->push_back(new measurement_t(io__raw_meas, this, m__root)); - } -} - -ubx_t::rxm_rawx_t::~rxm_rawx_t() { - _clean_up(); -} - -void ubx_t::rxm_rawx_t::_clean_up() { - if (m__raw_meas) { - delete m__raw_meas; m__raw_meas = 0; - } - if (m__io__raw_meas) { - for (std::vector::iterator it = m__io__raw_meas->begin(); it != m__io__raw_meas->end(); ++it) { - delete *it; - } - delete m__io__raw_meas; m__io__raw_meas = 0; - } - if (m_meas) { - for (std::vector::iterator it = m_meas->begin(); it != m_meas->end(); ++it) { - delete *it; - } - delete m_meas; m_meas = 0; - } -} - -ubx_t::rxm_rawx_t::measurement_t::measurement_t(kaitai::kstream* p__io, ubx_t::rxm_rawx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::rxm_rawx_t::measurement_t::_read() { - m_pr_mes = m__io->read_f8le(); - m_cp_mes = m__io->read_f8le(); - m_do_mes = m__io->read_f4le(); - m_gnss_id = static_cast(m__io->read_u1()); - m_sv_id = m__io->read_u1(); - m_reserved2 = m__io->read_bytes(1); - m_freq_id = m__io->read_u1(); - m_lock_time = m__io->read_u2le(); - m_cno = m__io->read_u1(); - m_pr_stdev = m__io->read_u1(); - m_cp_stdev = m__io->read_u1(); - m_do_stdev = m__io->read_u1(); - m_trk_stat = m__io->read_u1(); - m_reserved3 = m__io->read_bytes(1); -} - -ubx_t::rxm_rawx_t::measurement_t::~measurement_t() { - _clean_up(); -} - -void ubx_t::rxm_rawx_t::measurement_t::_clean_up() { -} - -ubx_t::rxm_sfrbx_t::rxm_sfrbx_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - m_body = 0; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::rxm_sfrbx_t::_read() { - m_gnss_id = static_cast(m__io->read_u1()); - m_sv_id = m__io->read_u1(); - m_reserved1 = m__io->read_bytes(1); - m_freq_id = m__io->read_u1(); - m_num_words = m__io->read_u1(); - m_reserved2 = m__io->read_bytes(1); - m_version = m__io->read_u1(); - m_reserved3 = m__io->read_bytes(1); - m_body = new std::vector(); - const int l_body = num_words(); - for (int i = 0; i < l_body; i++) { - m_body->push_back(m__io->read_u4le()); - } -} - -ubx_t::rxm_sfrbx_t::~rxm_sfrbx_t() { - _clean_up(); -} - -void ubx_t::rxm_sfrbx_t::_clean_up() { - if (m_body) { - delete m_body; m_body = 0; - } -} - -ubx_t::nav_sat_t::nav_sat_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - m_svs = 0; - m__raw_svs = 0; - m__io__raw_svs = 0; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::nav_sat_t::_read() { - m_itow = m__io->read_u4le(); - m_version = m__io->read_u1(); - m_num_svs = m__io->read_u1(); - m_reserved = m__io->read_bytes(2); - m__raw_svs = new std::vector(); - m__io__raw_svs = new std::vector(); - m_svs = new std::vector(); - const int l_svs = num_svs(); - for (int i = 0; i < l_svs; i++) { - m__raw_svs->push_back(m__io->read_bytes(12)); - kaitai::kstream* io__raw_svs = new kaitai::kstream(m__raw_svs->at(m__raw_svs->size() - 1)); - m__io__raw_svs->push_back(io__raw_svs); - m_svs->push_back(new nav_t(io__raw_svs, this, m__root)); - } -} - -ubx_t::nav_sat_t::~nav_sat_t() { - _clean_up(); -} - -void ubx_t::nav_sat_t::_clean_up() { - if (m__raw_svs) { - delete m__raw_svs; m__raw_svs = 0; - } - if (m__io__raw_svs) { - for (std::vector::iterator it = m__io__raw_svs->begin(); it != m__io__raw_svs->end(); ++it) { - delete *it; - } - delete m__io__raw_svs; m__io__raw_svs = 0; - } - if (m_svs) { - for (std::vector::iterator it = m_svs->begin(); it != m_svs->end(); ++it) { - delete *it; - } - delete m_svs; m_svs = 0; - } -} - -ubx_t::nav_sat_t::nav_t::nav_t(kaitai::kstream* p__io, ubx_t::nav_sat_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::nav_sat_t::nav_t::_read() { - m_gnss_id = static_cast(m__io->read_u1()); - m_sv_id = m__io->read_u1(); - m_cno = m__io->read_u1(); - m_elev = m__io->read_s1(); - m_azim = m__io->read_s2le(); - m_pr_res = m__io->read_s2le(); - m_flags = m__io->read_u4le(); -} - -ubx_t::nav_sat_t::nav_t::~nav_t() { - _clean_up(); -} - -void ubx_t::nav_sat_t::nav_t::_clean_up() { -} - -ubx_t::nav_pvt_t::nav_pvt_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::nav_pvt_t::_read() { - m_i_tow = m__io->read_u4le(); - m_year = m__io->read_u2le(); - m_month = m__io->read_u1(); - m_day = m__io->read_u1(); - m_hour = m__io->read_u1(); - m_min = m__io->read_u1(); - m_sec = m__io->read_u1(); - m_valid = m__io->read_u1(); - m_t_acc = m__io->read_u4le(); - m_nano = m__io->read_s4le(); - m_fix_type = m__io->read_u1(); - m_flags = m__io->read_u1(); - m_flags2 = m__io->read_u1(); - m_num_sv = m__io->read_u1(); - m_lon = m__io->read_s4le(); - m_lat = m__io->read_s4le(); - m_height = m__io->read_s4le(); - m_h_msl = m__io->read_s4le(); - m_h_acc = m__io->read_u4le(); - m_v_acc = m__io->read_u4le(); - m_vel_n = m__io->read_s4le(); - m_vel_e = m__io->read_s4le(); - m_vel_d = m__io->read_s4le(); - m_g_speed = m__io->read_s4le(); - m_head_mot = m__io->read_s4le(); - m_s_acc = m__io->read_s4le(); - m_head_acc = m__io->read_u4le(); - m_p_dop = m__io->read_u2le(); - m_flags3 = m__io->read_u1(); - m_reserved1 = m__io->read_bytes(5); - m_head_veh = m__io->read_s4le(); - m_mag_dec = m__io->read_s2le(); - m_mag_acc = m__io->read_u2le(); -} - -ubx_t::nav_pvt_t::~nav_pvt_t() { - _clean_up(); -} - -void ubx_t::nav_pvt_t::_clean_up() { -} - -ubx_t::mon_hw2_t::mon_hw2_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::mon_hw2_t::_read() { - m_ofs_i = m__io->read_s1(); - m_mag_i = m__io->read_u1(); - m_ofs_q = m__io->read_s1(); - m_mag_q = m__io->read_u1(); - m_cfg_source = static_cast(m__io->read_u1()); - m_reserved1 = m__io->read_bytes(3); - m_low_lev_cfg = m__io->read_u4le(); - m_reserved2 = m__io->read_bytes(8); - m_post_status = m__io->read_u4le(); - m_reserved3 = m__io->read_bytes(4); -} - -ubx_t::mon_hw2_t::~mon_hw2_t() { - _clean_up(); -} - -void ubx_t::mon_hw2_t::_clean_up() { -} - -ubx_t::mon_hw_t::mon_hw_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::mon_hw_t::_read() { - m_pin_sel = m__io->read_u4le(); - m_pin_bank = m__io->read_u4le(); - m_pin_dir = m__io->read_u4le(); - m_pin_val = m__io->read_u4le(); - m_noise_per_ms = m__io->read_u2le(); - m_agc_cnt = m__io->read_u2le(); - m_a_status = static_cast(m__io->read_u1()); - m_a_power = static_cast(m__io->read_u1()); - m_flags = m__io->read_u1(); - m_reserved1 = m__io->read_bytes(1); - m_used_mask = m__io->read_u4le(); - m_vp = m__io->read_bytes(17); - m_jam_ind = m__io->read_u1(); - m_reserved2 = m__io->read_bytes(2); - m_pin_irq = m__io->read_u4le(); - m_pull_h = m__io->read_u4le(); - m_pull_l = m__io->read_u4le(); -} - -ubx_t::mon_hw_t::~mon_hw_t() { - _clean_up(); -} - -void ubx_t::mon_hw_t::_clean_up() { -} - -uint16_t ubx_t::checksum() { - if (f_checksum) - return m_checksum; - std::streampos _pos = m__io->pos(); - m__io->seek((length() + 6)); - m_checksum = m__io->read_u2le(); - m__io->seek(_pos); - f_checksum = true; - return m_checksum; -} diff --git a/system/ubloxd/generated/ubx.h b/system/ubloxd/generated/ubx.h deleted file mode 100644 index 022108489ff27a..00000000000000 --- a/system/ubloxd/generated/ubx.h +++ /dev/null @@ -1,484 +0,0 @@ -#ifndef UBX_H_ -#define UBX_H_ - -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "kaitai/kaitaistruct.h" -#include -#include - -#if KAITAI_STRUCT_VERSION < 9000L -#error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" -#endif - -class ubx_t : public kaitai::kstruct { - -public: - class rxm_rawx_t; - class rxm_sfrbx_t; - class nav_sat_t; - class nav_pvt_t; - class mon_hw2_t; - class mon_hw_t; - - enum gnss_type_t { - GNSS_TYPE_GPS = 0, - GNSS_TYPE_SBAS = 1, - GNSS_TYPE_GALILEO = 2, - GNSS_TYPE_BEIDOU = 3, - GNSS_TYPE_IMES = 4, - GNSS_TYPE_QZSS = 5, - GNSS_TYPE_GLONASS = 6 - }; - - ubx_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = 0, ubx_t* p__root = 0); - -private: - void _read(); - void _clean_up(); - -public: - ~ubx_t(); - - class rxm_rawx_t : public kaitai::kstruct { - - public: - class measurement_t; - - rxm_rawx_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~rxm_rawx_t(); - - class measurement_t : public kaitai::kstruct { - - public: - - measurement_t(kaitai::kstream* p__io, ubx_t::rxm_rawx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~measurement_t(); - - private: - double m_pr_mes; - double m_cp_mes; - float m_do_mes; - gnss_type_t m_gnss_id; - uint8_t m_sv_id; - std::string m_reserved2; - uint8_t m_freq_id; - uint16_t m_lock_time; - uint8_t m_cno; - uint8_t m_pr_stdev; - uint8_t m_cp_stdev; - uint8_t m_do_stdev; - uint8_t m_trk_stat; - std::string m_reserved3; - ubx_t* m__root; - ubx_t::rxm_rawx_t* m__parent; - - public: - double pr_mes() const { return m_pr_mes; } - double cp_mes() const { return m_cp_mes; } - float do_mes() const { return m_do_mes; } - gnss_type_t gnss_id() const { return m_gnss_id; } - uint8_t sv_id() const { return m_sv_id; } - std::string reserved2() const { return m_reserved2; } - uint8_t freq_id() const { return m_freq_id; } - uint16_t lock_time() const { return m_lock_time; } - uint8_t cno() const { return m_cno; } - uint8_t pr_stdev() const { return m_pr_stdev; } - uint8_t cp_stdev() const { return m_cp_stdev; } - uint8_t do_stdev() const { return m_do_stdev; } - uint8_t trk_stat() const { return m_trk_stat; } - std::string reserved3() const { return m_reserved3; } - ubx_t* _root() const { return m__root; } - ubx_t::rxm_rawx_t* _parent() const { return m__parent; } - }; - - private: - double m_rcv_tow; - uint16_t m_week; - int8_t m_leap_s; - uint8_t m_num_meas; - uint8_t m_rec_stat; - std::string m_reserved1; - std::vector* m_meas; - ubx_t* m__root; - ubx_t* m__parent; - std::vector* m__raw_meas; - std::vector* m__io__raw_meas; - - public: - double rcv_tow() const { return m_rcv_tow; } - uint16_t week() const { return m_week; } - int8_t leap_s() const { return m_leap_s; } - uint8_t num_meas() const { return m_num_meas; } - uint8_t rec_stat() const { return m_rec_stat; } - std::string reserved1() const { return m_reserved1; } - std::vector* meas() const { return m_meas; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - std::vector* _raw_meas() const { return m__raw_meas; } - std::vector* _io__raw_meas() const { return m__io__raw_meas; } - }; - - class rxm_sfrbx_t : public kaitai::kstruct { - - public: - - rxm_sfrbx_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~rxm_sfrbx_t(); - - private: - gnss_type_t m_gnss_id; - uint8_t m_sv_id; - std::string m_reserved1; - uint8_t m_freq_id; - uint8_t m_num_words; - std::string m_reserved2; - uint8_t m_version; - std::string m_reserved3; - std::vector* m_body; - ubx_t* m__root; - ubx_t* m__parent; - - public: - gnss_type_t gnss_id() const { return m_gnss_id; } - uint8_t sv_id() const { return m_sv_id; } - std::string reserved1() const { return m_reserved1; } - uint8_t freq_id() const { return m_freq_id; } - uint8_t num_words() const { return m_num_words; } - std::string reserved2() const { return m_reserved2; } - uint8_t version() const { return m_version; } - std::string reserved3() const { return m_reserved3; } - std::vector* body() const { return m_body; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - }; - - class nav_sat_t : public kaitai::kstruct { - - public: - class nav_t; - - nav_sat_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~nav_sat_t(); - - class nav_t : public kaitai::kstruct { - - public: - - nav_t(kaitai::kstream* p__io, ubx_t::nav_sat_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~nav_t(); - - private: - gnss_type_t m_gnss_id; - uint8_t m_sv_id; - uint8_t m_cno; - int8_t m_elev; - int16_t m_azim; - int16_t m_pr_res; - uint32_t m_flags; - ubx_t* m__root; - ubx_t::nav_sat_t* m__parent; - - public: - gnss_type_t gnss_id() const { return m_gnss_id; } - uint8_t sv_id() const { return m_sv_id; } - uint8_t cno() const { return m_cno; } - int8_t elev() const { return m_elev; } - int16_t azim() const { return m_azim; } - int16_t pr_res() const { return m_pr_res; } - uint32_t flags() const { return m_flags; } - ubx_t* _root() const { return m__root; } - ubx_t::nav_sat_t* _parent() const { return m__parent; } - }; - - private: - uint32_t m_itow; - uint8_t m_version; - uint8_t m_num_svs; - std::string m_reserved; - std::vector* m_svs; - ubx_t* m__root; - ubx_t* m__parent; - std::vector* m__raw_svs; - std::vector* m__io__raw_svs; - - public: - uint32_t itow() const { return m_itow; } - uint8_t version() const { return m_version; } - uint8_t num_svs() const { return m_num_svs; } - std::string reserved() const { return m_reserved; } - std::vector* svs() const { return m_svs; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - std::vector* _raw_svs() const { return m__raw_svs; } - std::vector* _io__raw_svs() const { return m__io__raw_svs; } - }; - - class nav_pvt_t : public kaitai::kstruct { - - public: - - nav_pvt_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~nav_pvt_t(); - - private: - uint32_t m_i_tow; - uint16_t m_year; - uint8_t m_month; - uint8_t m_day; - uint8_t m_hour; - uint8_t m_min; - uint8_t m_sec; - uint8_t m_valid; - uint32_t m_t_acc; - int32_t m_nano; - uint8_t m_fix_type; - uint8_t m_flags; - uint8_t m_flags2; - uint8_t m_num_sv; - int32_t m_lon; - int32_t m_lat; - int32_t m_height; - int32_t m_h_msl; - uint32_t m_h_acc; - uint32_t m_v_acc; - int32_t m_vel_n; - int32_t m_vel_e; - int32_t m_vel_d; - int32_t m_g_speed; - int32_t m_head_mot; - int32_t m_s_acc; - uint32_t m_head_acc; - uint16_t m_p_dop; - uint8_t m_flags3; - std::string m_reserved1; - int32_t m_head_veh; - int16_t m_mag_dec; - uint16_t m_mag_acc; - ubx_t* m__root; - ubx_t* m__parent; - - public: - uint32_t i_tow() const { return m_i_tow; } - uint16_t year() const { return m_year; } - uint8_t month() const { return m_month; } - uint8_t day() const { return m_day; } - uint8_t hour() const { return m_hour; } - uint8_t min() const { return m_min; } - uint8_t sec() const { return m_sec; } - uint8_t valid() const { return m_valid; } - uint32_t t_acc() const { return m_t_acc; } - int32_t nano() const { return m_nano; } - uint8_t fix_type() const { return m_fix_type; } - uint8_t flags() const { return m_flags; } - uint8_t flags2() const { return m_flags2; } - uint8_t num_sv() const { return m_num_sv; } - int32_t lon() const { return m_lon; } - int32_t lat() const { return m_lat; } - int32_t height() const { return m_height; } - int32_t h_msl() const { return m_h_msl; } - uint32_t h_acc() const { return m_h_acc; } - uint32_t v_acc() const { return m_v_acc; } - int32_t vel_n() const { return m_vel_n; } - int32_t vel_e() const { return m_vel_e; } - int32_t vel_d() const { return m_vel_d; } - int32_t g_speed() const { return m_g_speed; } - int32_t head_mot() const { return m_head_mot; } - int32_t s_acc() const { return m_s_acc; } - uint32_t head_acc() const { return m_head_acc; } - uint16_t p_dop() const { return m_p_dop; } - uint8_t flags3() const { return m_flags3; } - std::string reserved1() const { return m_reserved1; } - int32_t head_veh() const { return m_head_veh; } - int16_t mag_dec() const { return m_mag_dec; } - uint16_t mag_acc() const { return m_mag_acc; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - }; - - class mon_hw2_t : public kaitai::kstruct { - - public: - - enum config_source_t { - CONFIG_SOURCE_FLASH = 102, - CONFIG_SOURCE_OTP = 111, - CONFIG_SOURCE_CONFIG_PINS = 112, - CONFIG_SOURCE_ROM = 113 - }; - - mon_hw2_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~mon_hw2_t(); - - private: - int8_t m_ofs_i; - uint8_t m_mag_i; - int8_t m_ofs_q; - uint8_t m_mag_q; - config_source_t m_cfg_source; - std::string m_reserved1; - uint32_t m_low_lev_cfg; - std::string m_reserved2; - uint32_t m_post_status; - std::string m_reserved3; - ubx_t* m__root; - ubx_t* m__parent; - - public: - int8_t ofs_i() const { return m_ofs_i; } - uint8_t mag_i() const { return m_mag_i; } - int8_t ofs_q() const { return m_ofs_q; } - uint8_t mag_q() const { return m_mag_q; } - config_source_t cfg_source() const { return m_cfg_source; } - std::string reserved1() const { return m_reserved1; } - uint32_t low_lev_cfg() const { return m_low_lev_cfg; } - std::string reserved2() const { return m_reserved2; } - uint32_t post_status() const { return m_post_status; } - std::string reserved3() const { return m_reserved3; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - }; - - class mon_hw_t : public kaitai::kstruct { - - public: - - enum antenna_status_t { - ANTENNA_STATUS_INIT = 0, - ANTENNA_STATUS_DONTKNOW = 1, - ANTENNA_STATUS_OK = 2, - ANTENNA_STATUS_SHORT = 3, - ANTENNA_STATUS_OPEN = 4 - }; - - enum antenna_power_t { - ANTENNA_POWER_FALSE = 0, - ANTENNA_POWER_TRUE = 1, - ANTENNA_POWER_DONTKNOW = 2 - }; - - mon_hw_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~mon_hw_t(); - - private: - uint32_t m_pin_sel; - uint32_t m_pin_bank; - uint32_t m_pin_dir; - uint32_t m_pin_val; - uint16_t m_noise_per_ms; - uint16_t m_agc_cnt; - antenna_status_t m_a_status; - antenna_power_t m_a_power; - uint8_t m_flags; - std::string m_reserved1; - uint32_t m_used_mask; - std::string m_vp; - uint8_t m_jam_ind; - std::string m_reserved2; - uint32_t m_pin_irq; - uint32_t m_pull_h; - uint32_t m_pull_l; - ubx_t* m__root; - ubx_t* m__parent; - - public: - uint32_t pin_sel() const { return m_pin_sel; } - uint32_t pin_bank() const { return m_pin_bank; } - uint32_t pin_dir() const { return m_pin_dir; } - uint32_t pin_val() const { return m_pin_val; } - uint16_t noise_per_ms() const { return m_noise_per_ms; } - uint16_t agc_cnt() const { return m_agc_cnt; } - antenna_status_t a_status() const { return m_a_status; } - antenna_power_t a_power() const { return m_a_power; } - uint8_t flags() const { return m_flags; } - std::string reserved1() const { return m_reserved1; } - uint32_t used_mask() const { return m_used_mask; } - std::string vp() const { return m_vp; } - uint8_t jam_ind() const { return m_jam_ind; } - std::string reserved2() const { return m_reserved2; } - uint32_t pin_irq() const { return m_pin_irq; } - uint32_t pull_h() const { return m_pull_h; } - uint32_t pull_l() const { return m_pull_l; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - }; - -private: - bool f_checksum; - uint16_t m_checksum; - -public: - uint16_t checksum(); - -private: - std::string m_magic; - uint16_t m_msg_type; - uint16_t m_length; - kaitai::kstruct* m_body; - bool n_body; - -public: - bool _is_null_body() { body(); return n_body; }; - -private: - ubx_t* m__root; - kaitai::kstruct* m__parent; - -public: - std::string magic() const { return m_magic; } - uint16_t msg_type() const { return m_msg_type; } - uint16_t length() const { return m_length; } - kaitai::kstruct* body() const { return m_body; } - ubx_t* _root() const { return m__root; } - kaitai::kstruct* _parent() const { return m__parent; } -}; - -#endif // UBX_H_ diff --git a/system/ubloxd/glonass.ksy b/system/ubloxd/glonass.ksy deleted file mode 100644 index be99f6e497ab37..00000000000000 --- a/system/ubloxd/glonass.ksy +++ /dev/null @@ -1,176 +0,0 @@ -# http://gauss.gge.unb.ca/GLONASS.ICD.pdf -# some variables are misprinted but good in the old doc -# https://www.unavco.org/help/glossary/docs/ICD_GLONASS_4.0_(1998)_en.pdf -meta: - id: glonass - endian: be - bit-endian: be -seq: - - id: idle_chip - type: b1 - - id: string_number - type: b4 - - id: data - type: - switch-on: string_number - cases: - 1: string_1 - 2: string_2 - 3: string_3 - 4: string_4 - 5: string_5 - _: string_non_immediate - - id: hamming_code - type: b8 - - id: pad_1 - type: b11 - - id: superframe_number - type: b16 - - id: pad_2 - type: b8 - - id: frame_number - type: b8 - -types: - string_1: - seq: - - id: not_used - type: b2 - - id: p1 - type: b2 - - id: t_k - type: b12 - - id: x_vel_sign - type: b1 - - id: x_vel_value - type: b23 - - id: x_accel_sign - type: b1 - - id: x_accel_value - type: b4 - - id: x_sign - type: b1 - - id: x_value - type: b26 - instances: - x_vel: - value: 'x_vel_sign ? (x_vel_value * (-1)) : x_vel_value' - x_accel: - value: 'x_accel_sign ? (x_accel_value * (-1)) : x_accel_value' - x: - value: 'x_sign ? (x_value * (-1)) : x_value' - string_2: - seq: - - id: b_n - type: b3 - - id: p2 - type: b1 - - id: t_b - type: b7 - - id: not_used - type: b5 - - id: y_vel_sign - type: b1 - - id: y_vel_value - type: b23 - - id: y_accel_sign - type: b1 - - id: y_accel_value - type: b4 - - id: y_sign - type: b1 - - id: y_value - type: b26 - instances: - y_vel: - value: 'y_vel_sign ? (y_vel_value * (-1)) : y_vel_value' - y_accel: - value: 'y_accel_sign ? (y_accel_value * (-1)) : y_accel_value' - y: - value: 'y_sign ? (y_value * (-1)) : y_value' - string_3: - seq: - - id: p3 - type: b1 - - id: gamma_n_sign - type: b1 - - id: gamma_n_value - type: b10 - - id: not_used - type: b1 - - id: p - type: b2 - - id: l_n - type: b1 - - id: z_vel_sign - type: b1 - - id: z_vel_value - type: b23 - - id: z_accel_sign - type: b1 - - id: z_accel_value - type: b4 - - id: z_sign - type: b1 - - id: z_value - type: b26 - instances: - gamma_n: - value: 'gamma_n_sign ? (gamma_n_value * (-1)) : gamma_n_value' - z_vel: - value: 'z_vel_sign ? (z_vel_value * (-1)) : z_vel_value' - z_accel: - value: 'z_accel_sign ? (z_accel_value * (-1)) : z_accel_value' - z: - value: 'z_sign ? (z_value * (-1)) : z_value' - string_4: - seq: - - id: tau_n_sign - type: b1 - - id: tau_n_value - type: b21 - - id: delta_tau_n_sign - type: b1 - - id: delta_tau_n_value - type: b4 - - id: e_n - type: b5 - - id: not_used_1 - type: b14 - - id: p4 - type: b1 - - id: f_t - type: b4 - - id: not_used_2 - type: b3 - - id: n_t - type: b11 - - id: n - type: b5 - - id: m - type: b2 - instances: - tau_n: - value: 'tau_n_sign ? (tau_n_value * (-1)) : tau_n_value' - delta_tau_n: - value: 'delta_tau_n_sign ? (delta_tau_n_value * (-1)) : delta_tau_n_value' - string_5: - seq: - - id: n_a - type: b11 - - id: tau_c - type: b32 - - id: not_used - type: b1 - - id: n_4 - type: b5 - - id: tau_gps - type: b22 - - id: l_n - type: b1 - string_non_immediate: - seq: - - id: data_1 - type: b64 - - id: data_2 - type: b8 diff --git a/system/ubloxd/glonass.py b/system/ubloxd/glonass.py new file mode 100644 index 00000000000000..144ccdde6e244b --- /dev/null +++ b/system/ubloxd/glonass.py @@ -0,0 +1,156 @@ +""" +Parses GLONASS navigation strings per GLONASS ICD specification. +http://gauss.gge.unb.ca/GLONASS.ICD.pdf +https://www.unavco.org/help/glossary/docs/ICD_GLONASS_4.0_(1998)_en.pdf +""" + +from typing import Annotated + +from openpilot.system.ubloxd import binary_struct as bs + + +class Glonass(bs.BinaryStruct): + class String1(bs.BinaryStruct): + not_used: Annotated[int, bs.bits(2)] + p1: Annotated[int, bs.bits(2)] + t_k: Annotated[int, bs.bits(12)] + x_vel_sign: Annotated[bool, bs.bits(1)] + x_vel_value: Annotated[int, bs.bits(23)] + x_accel_sign: Annotated[bool, bs.bits(1)] + x_accel_value: Annotated[int, bs.bits(4)] + x_sign: Annotated[bool, bs.bits(1)] + x_value: Annotated[int, bs.bits(26)] + + @property + def x_vel(self) -> int: + """Computed x_vel from sign-magnitude representation.""" + return (self.x_vel_value * -1) if self.x_vel_sign else self.x_vel_value + + @property + def x_accel(self) -> int: + """Computed x_accel from sign-magnitude representation.""" + return (self.x_accel_value * -1) if self.x_accel_sign else self.x_accel_value + + @property + def x(self) -> int: + """Computed x from sign-magnitude representation.""" + return (self.x_value * -1) if self.x_sign else self.x_value + + class String2(bs.BinaryStruct): + b_n: Annotated[int, bs.bits(3)] + p2: Annotated[bool, bs.bits(1)] + t_b: Annotated[int, bs.bits(7)] + not_used: Annotated[int, bs.bits(5)] + y_vel_sign: Annotated[bool, bs.bits(1)] + y_vel_value: Annotated[int, bs.bits(23)] + y_accel_sign: Annotated[bool, bs.bits(1)] + y_accel_value: Annotated[int, bs.bits(4)] + y_sign: Annotated[bool, bs.bits(1)] + y_value: Annotated[int, bs.bits(26)] + + @property + def y_vel(self) -> int: + """Computed y_vel from sign-magnitude representation.""" + return (self.y_vel_value * -1) if self.y_vel_sign else self.y_vel_value + + @property + def y_accel(self) -> int: + """Computed y_accel from sign-magnitude representation.""" + return (self.y_accel_value * -1) if self.y_accel_sign else self.y_accel_value + + @property + def y(self) -> int: + """Computed y from sign-magnitude representation.""" + return (self.y_value * -1) if self.y_sign else self.y_value + + class String3(bs.BinaryStruct): + p3: Annotated[bool, bs.bits(1)] + gamma_n_sign: Annotated[bool, bs.bits(1)] + gamma_n_value: Annotated[int, bs.bits(10)] + not_used: Annotated[bool, bs.bits(1)] + p: Annotated[int, bs.bits(2)] + l_n: Annotated[bool, bs.bits(1)] + z_vel_sign: Annotated[bool, bs.bits(1)] + z_vel_value: Annotated[int, bs.bits(23)] + z_accel_sign: Annotated[bool, bs.bits(1)] + z_accel_value: Annotated[int, bs.bits(4)] + z_sign: Annotated[bool, bs.bits(1)] + z_value: Annotated[int, bs.bits(26)] + + @property + def gamma_n(self) -> int: + """Computed gamma_n from sign-magnitude representation.""" + return (self.gamma_n_value * -1) if self.gamma_n_sign else self.gamma_n_value + + @property + def z_vel(self) -> int: + """Computed z_vel from sign-magnitude representation.""" + return (self.z_vel_value * -1) if self.z_vel_sign else self.z_vel_value + + @property + def z_accel(self) -> int: + """Computed z_accel from sign-magnitude representation.""" + return (self.z_accel_value * -1) if self.z_accel_sign else self.z_accel_value + + @property + def z(self) -> int: + """Computed z from sign-magnitude representation.""" + return (self.z_value * -1) if self.z_sign else self.z_value + + class String4(bs.BinaryStruct): + tau_n_sign: Annotated[bool, bs.bits(1)] + tau_n_value: Annotated[int, bs.bits(21)] + delta_tau_n_sign: Annotated[bool, bs.bits(1)] + delta_tau_n_value: Annotated[int, bs.bits(4)] + e_n: Annotated[int, bs.bits(5)] + not_used_1: Annotated[int, bs.bits(14)] + p4: Annotated[bool, bs.bits(1)] + f_t: Annotated[int, bs.bits(4)] + not_used_2: Annotated[int, bs.bits(3)] + n_t: Annotated[int, bs.bits(11)] + n: Annotated[int, bs.bits(5)] + m: Annotated[int, bs.bits(2)] + + @property + def tau_n(self) -> int: + """Computed tau_n from sign-magnitude representation.""" + return (self.tau_n_value * -1) if self.tau_n_sign else self.tau_n_value + + @property + def delta_tau_n(self) -> int: + """Computed delta_tau_n from sign-magnitude representation.""" + return (self.delta_tau_n_value * -1) if self.delta_tau_n_sign else self.delta_tau_n_value + + class String5(bs.BinaryStruct): + n_a: Annotated[int, bs.bits(11)] + tau_c: Annotated[int, bs.bits(32)] + not_used: Annotated[bool, bs.bits(1)] + n_4: Annotated[int, bs.bits(5)] + tau_gps: Annotated[int, bs.bits(22)] + l_n: Annotated[bool, bs.bits(1)] + + class StringNonImmediate(bs.BinaryStruct): + data_1: Annotated[int, bs.bits(64)] + data_2: Annotated[int, bs.bits(8)] + + idle_chip: Annotated[bool, bs.bits(1)] + string_number: Annotated[int, bs.bits(4)] + data: Annotated[ + object, + bs.switch( + 'string_number', + { + 1: String1, + 2: String2, + 3: String3, + 4: String4, + 5: String5, + }, + default=StringNonImmediate, + ), + ] + hamming_code: Annotated[int, bs.bits(8)] + pad_1: Annotated[int, bs.bits(11)] + superframe_number: Annotated[int, bs.bits(16)] + pad_2: Annotated[int, bs.bits(8)] + frame_number: Annotated[int, bs.bits(8)] diff --git a/system/ubloxd/glonass_fix.patch b/system/ubloxd/glonass_fix.patch deleted file mode 100644 index 7eb973a3480f5c..00000000000000 --- a/system/ubloxd/glonass_fix.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/system/ubloxd/generated/glonass.cpp b/system/ubloxd/generated/glonass.cpp -index 5b17bc327..b5c6aa610 100644 ---- a/system/ubloxd/generated/glonass.cpp -+++ b/system/ubloxd/generated/glonass.cpp -@@ -17,7 +17,7 @@ glonass_t::glonass_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, glonass - void glonass_t::_read() { - m_idle_chip = m__io->read_bits_int_be(1); - m_string_number = m__io->read_bits_int_be(4); -- m__io->align_to_byte(); -+ //m__io->align_to_byte(); - switch (string_number()) { - case 4: { - m_data = new string_4_t(m__io, this, m__root); diff --git a/system/ubloxd/gps.ksy b/system/ubloxd/gps.ksy deleted file mode 100644 index 893ad1b25bee5e..00000000000000 --- a/system/ubloxd/gps.ksy +++ /dev/null @@ -1,189 +0,0 @@ -# https://www.gps.gov/technical/icwg/IS-GPS-200E.pdf -meta: - id: gps - endian: be - bit-endian: be -seq: - - id: tlm - type: tlm - - id: how - type: how - - id: body - type: - switch-on: how.subframe_id - cases: - 1: subframe_1 - 2: subframe_2 - 3: subframe_3 - 4: subframe_4 -types: - tlm: - seq: - - id: preamble - contents: [0x8b] - - id: tlm - type: b14 - - id: integrity_status - type: b1 - - id: reserved - type: b1 - how: - seq: - - id: tow_count - type: b17 - - id: alert - type: b1 - - id: anti_spoof - type: b1 - - id: subframe_id - type: b3 - - id: reserved - type: b2 - subframe_1: - seq: - # Word 3 - - id: week_no - type: b10 - - id: code - type: b2 - - id: sv_accuracy - type: b4 - - id: sv_health - type: b6 - - id: iodc_msb - type: b2 - # Word 4 - - id: l2_p_data_flag - type: b1 - - id: reserved1 - type: b23 - # Word 5 - - id: reserved2 - type: b24 - # Word 6 - - id: reserved3 - type: b24 - # Word 7 - - id: reserved4 - type: b16 - - id: t_gd - type: s1 - # Word 8 - - id: iodc_lsb - type: u1 - - id: t_oc - type: u2 - # Word 9 - - id: af_2 - type: s1 - - id: af_1 - type: s2 - # Word 10 - - id: af_0_sign - type: b1 - - id: af_0_value - type: b21 - - id: reserved5 - type: b2 - instances: - af_0: - value: 'af_0_sign ? (af_0_value - (1 << 21)) : af_0_value' - subframe_2: - seq: - # Word 3 - - id: iode - type: u1 - - id: c_rs - type: s2 - # Word 4 & 5 - - id: delta_n - type: s2 - - id: m_0 - type: s4 - # Word 6 & 7 - - id: c_uc - type: s2 - - id: e - type: s4 - # Word 8 & 9 - - id: c_us - type: s2 - - id: sqrt_a - type: u4 - # Word 10 - - id: t_oe - type: u2 - - id: fit_interval_flag - type: b1 - - id: aoda - type: b5 - - id: reserved - type: b2 - subframe_3: - seq: - # Word 3 & 4 - - id: c_ic - type: s2 - - id: omega_0 - type: s4 - # Word 5 & 6 - - id: c_is - type: s2 - - id: i_0 - type: s4 - # Word 7 & 8 - - id: c_rc - type: s2 - - id: omega - type: s4 - # Word 9 - - id: omega_dot_sign - type: b1 - - id: omega_dot_value - type: b23 - # Word 10 - - id: iode - type: u1 - - id: idot_sign - type: b1 - - id: idot_value - type: b13 - - id: reserved - type: b2 - instances: - omega_dot: - value: 'omega_dot_sign ? (omega_dot_value - (1 << 23)) : omega_dot_value' - idot: - value: 'idot_sign ? (idot_value - (1 << 13)) : idot_value' - subframe_4: - seq: - # Word 3 - - id: data_id - type: b2 - - id: page_id - type: b6 - - id: body - type: - switch-on: page_id - cases: - 56: ionosphere_data - types: - ionosphere_data: - seq: - - id: a0 - type: s1 - - id: a1 - type: s1 - - id: a2 - type: s1 - - id: a3 - type: s1 - - id: b0 - type: s1 - - id: b1 - type: s1 - - id: b2 - type: s1 - - id: b3 - type: s1 - diff --git a/system/ubloxd/gps.py b/system/ubloxd/gps.py new file mode 100644 index 00000000000000..1c0833bd92d990 --- /dev/null +++ b/system/ubloxd/gps.py @@ -0,0 +1,116 @@ +""" +Parses GPS navigation subframes per IS-GPS-200E specification. +https://www.gps.gov/technical/icwg/IS-GPS-200E.pdf +""" + +from typing import Annotated + +from openpilot.system.ubloxd import binary_struct as bs + + +class Gps(bs.BinaryStruct): + class Tlm(bs.BinaryStruct): + preamble: Annotated[bytes, bs.const(bs.bytes_field(1), b"\x8b")] + tlm: Annotated[int, bs.bits(14)] + integrity_status: Annotated[bool, bs.bits(1)] + reserved: Annotated[bool, bs.bits(1)] + + class How(bs.BinaryStruct): + tow_count: Annotated[int, bs.bits(17)] + alert: Annotated[bool, bs.bits(1)] + anti_spoof: Annotated[bool, bs.bits(1)] + subframe_id: Annotated[int, bs.bits(3)] + reserved: Annotated[int, bs.bits(2)] + + class Subframe1(bs.BinaryStruct): + week_no: Annotated[int, bs.bits(10)] + code: Annotated[int, bs.bits(2)] + sv_accuracy: Annotated[int, bs.bits(4)] + sv_health: Annotated[int, bs.bits(6)] + iodc_msb: Annotated[int, bs.bits(2)] + l2_p_data_flag: Annotated[bool, bs.bits(1)] + reserved1: Annotated[int, bs.bits(23)] + reserved2: Annotated[int, bs.bits(24)] + reserved3: Annotated[int, bs.bits(24)] + reserved4: Annotated[int, bs.bits(16)] + t_gd: Annotated[int, bs.s8] + iodc_lsb: Annotated[int, bs.u8] + t_oc: Annotated[int, bs.u16be] + af_2: Annotated[int, bs.s8] + af_1: Annotated[int, bs.s16be] + af_0_sign: Annotated[bool, bs.bits(1)] + af_0_value: Annotated[int, bs.bits(21)] + reserved5: Annotated[int, bs.bits(2)] + + @property + def af_0(self) -> int: + """Computed af_0 from sign-magnitude representation.""" + return (self.af_0_value - (1 << 21)) if self.af_0_sign else self.af_0_value + + class Subframe2(bs.BinaryStruct): + iode: Annotated[int, bs.u8] + c_rs: Annotated[int, bs.s16be] + delta_n: Annotated[int, bs.s16be] + m_0: Annotated[int, bs.s32be] + c_uc: Annotated[int, bs.s16be] + e: Annotated[int, bs.s32be] + c_us: Annotated[int, bs.s16be] + sqrt_a: Annotated[int, bs.u32be] + t_oe: Annotated[int, bs.u16be] + fit_interval_flag: Annotated[bool, bs.bits(1)] + aoda: Annotated[int, bs.bits(5)] + reserved: Annotated[int, bs.bits(2)] + + class Subframe3(bs.BinaryStruct): + c_ic: Annotated[int, bs.s16be] + omega_0: Annotated[int, bs.s32be] + c_is: Annotated[int, bs.s16be] + i_0: Annotated[int, bs.s32be] + c_rc: Annotated[int, bs.s16be] + omega: Annotated[int, bs.s32be] + omega_dot_sign: Annotated[bool, bs.bits(1)] + omega_dot_value: Annotated[int, bs.bits(23)] + iode: Annotated[int, bs.u8] + idot_sign: Annotated[bool, bs.bits(1)] + idot_value: Annotated[int, bs.bits(13)] + reserved: Annotated[int, bs.bits(2)] + + @property + def omega_dot(self) -> int: + """Computed omega_dot from sign-magnitude representation.""" + return (self.omega_dot_value - (1 << 23)) if self.omega_dot_sign else self.omega_dot_value + + @property + def idot(self) -> int: + """Computed idot from sign-magnitude representation.""" + return (self.idot_value - (1 << 13)) if self.idot_sign else self.idot_value + + class Subframe4(bs.BinaryStruct): + class IonosphereData(bs.BinaryStruct): + a0: Annotated[int, bs.s8] + a1: Annotated[int, bs.s8] + a2: Annotated[int, bs.s8] + a3: Annotated[int, bs.s8] + b0: Annotated[int, bs.s8] + b1: Annotated[int, bs.s8] + b2: Annotated[int, bs.s8] + b3: Annotated[int, bs.s8] + + data_id: Annotated[int, bs.bits(2)] + page_id: Annotated[int, bs.bits(6)] + body: Annotated[object, bs.switch('page_id', {56: IonosphereData})] + + tlm: Tlm + how: How + body: Annotated[ + object, + bs.switch( + 'how.subframe_id', + { + 1: Subframe1, + 2: Subframe2, + 3: Subframe3, + 4: Subframe4, + }, + ), + ] diff --git a/system/ubloxd/pigeond.py b/system/ubloxd/pigeond.py index 8809689dcddf3c..e458a9d65f2373 100755 --- a/system/ubloxd/pigeond.py +++ b/system/ubloxd/pigeond.py @@ -9,6 +9,7 @@ from datetime import datetime, UTC from cereal import messaging +from openpilot.common.time_helpers import system_time_valid from openpilot.common.params import Params from openpilot.common.swaglog import cloudlog from openpilot.system.hardware import TICI @@ -40,7 +41,7 @@ def add_ubx_checksum(msg: bytes) -> bytes: B = (B + A) % 256 return msg + bytes([A, B]) -def get_assistnow_messages(token: bytes) -> list[bytes]: +def get_assistnow_messages(token: str) -> list[bytes]: # make request # TODO: implement adding the last known location r = requests.get("https://online-live2.services.u-blox.com/GetOnlineData.ashx", params=urllib.parse.urlencode({ @@ -135,6 +136,17 @@ def reset_device(self) -> bool: return True return False +def save_almanac(pigeon: TTYPigeon) -> None: + # store almanac in flash + pigeon.send(b"\xB5\x62\x09\x14\x04\x00\x00\x00\x00\x00\x21\xEC") + try: + if pigeon.wait_for_ack(ack=UBLOX_SOS_ACK, nack=UBLOX_SOS_NACK): + cloudlog.info("Done storing almanac") + else: + cloudlog.error("Error storing almanac") + except TimeoutError: + pass + def init_baudrate(pigeon: TTYPigeon): # ublox default setting on startup is 9600 baudrate pigeon.set_baud(9600) @@ -145,7 +157,7 @@ def init_baudrate(pigeon: TTYPigeon): pigeon.set_baud(460800) -def initialize_pigeon(pigeon: TTYPigeon) -> bool: +def init_pigeon(pigeon: TTYPigeon) -> bool: # try initializing a few times for _ in range(10): try: @@ -196,8 +208,8 @@ def initialize_pigeon(pigeon: TTYPigeon) -> bool: cloudlog.error(f"failed to restore almanac backup, status: {restore_status}") # sending time to ublox - t_now = datetime.now(UTC).replace(tzinfo=None) - if t_now >= datetime(2021, 6, 1): + if system_time_valid(): + t_now = datetime.now(UTC).replace(tzinfo=None) cloudlog.warning("Sending current time to ublox") # UBX-MGA-INI-TIME_UTC @@ -238,32 +250,17 @@ def initialize_pigeon(pigeon: TTYPigeon) -> bool: return True def deinitialize_and_exit(pigeon: TTYPigeon | None): - cloudlog.warning("Storing almanac in ublox flash") - if pigeon is not None: # controlled GNSS stop pigeon.send(b"\xB5\x62\x06\x04\x04\x00\x00\x00\x08\x00\x16\x74") - # store almanac in flash - pigeon.send(b"\xB5\x62\x09\x14\x04\x00\x00\x00\x00\x00\x21\xEC") - try: - if pigeon.wait_for_ack(ack=UBLOX_SOS_ACK, nack=UBLOX_SOS_NACK): - cloudlog.warning("Done storing almanac") - else: - cloudlog.error("Error storing almanac") - except TimeoutError: - pass - # turn off power and exit cleanly set_power(False) sys.exit(0) -def create_pigeon() -> tuple[TTYPigeon, messaging.PubMaster]: - pigeon = None - +def init(pigeon: TTYPigeon) -> None: # register exit handler signal.signal(signal.SIGINT, lambda sig, frame: deinitialize_and_exit(pigeon)) - pm = messaging.PubMaster(['ubloxRaw']) # power cycle ublox set_power(False) @@ -271,28 +268,34 @@ def create_pigeon() -> tuple[TTYPigeon, messaging.PubMaster]: set_power(True) time.sleep(0.5) - pigeon = TTYPigeon() - return pigeon, pm + init_baudrate(pigeon) + init_pigeon(pigeon) -def run_receiving(pigeon: TTYPigeon, pm: messaging.PubMaster, duration: int = 0): +def run_receiving(duration: int = 0): + pm = messaging.PubMaster(['ubloxRaw']) - start_time = time.monotonic() - def end_condition(): - return True if duration == 0 else time.monotonic() - start_time < duration + pigeon = TTYPigeon() + init(pigeon) - while end_condition(): + start_time = time.monotonic() + last_almanac_save = time.monotonic() + while (duration == 0) or (time.monotonic() - start_time < duration): dat = pigeon.receive() if len(dat) > 0: if dat[0] == 0x00: cloudlog.warning("received invalid data from ublox, re-initing!") - init_baudrate(pigeon) - initialize_pigeon(pigeon) + init(pigeon) continue # send out to socket msg = messaging.new_message('ubloxRaw', len(dat), valid=True) msg.ubloxRaw = dat[:] pm.send('ubloxRaw', msg) + + # save almanac every 5 minutes + if (time.monotonic() - last_almanac_save) > 60*5: + save_almanac(pigeon) + last_almanac_save = time.monotonic() else: # prevent locking up a CPU core if ublox disconnects time.sleep(0.001) @@ -300,13 +303,7 @@ def end_condition(): def main(): assert TICI, "unsupported hardware for pigeond" - - pigeon, pm = create_pigeon() - init_baudrate(pigeon) - initialize_pigeon(pigeon) - - # start receiving data - run_receiving(pigeon, pm) + run_receiving() if __name__ == "__main__": main() diff --git a/system/ubloxd/tests/print_gps_stats.py b/system/ubloxd/tests/print_gps_stats.py deleted file mode 100755 index edf94c060a938d..00000000000000 --- a/system/ubloxd/tests/print_gps_stats.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env python3 -import time -import cereal.messaging as messaging - -if __name__ == "__main__": - sm = messaging.SubMaster(['ubloxGnss', 'gpsLocationExternal']) - - while 1: - ug = sm['ubloxGnss'] - gle = sm['gpsLocationExternal'] - - try: - cnos = [] - for m in ug.measurementReport.measurements: - cnos.append(m.cno) - print("Sats: %d Accuracy: %.2f m cnos" % (ug.measurementReport.numMeas, gle.horizontalAccuracy), sorted(cnos)) - except Exception: - pass - sm.update() - time.sleep(0.1) diff --git a/system/ubloxd/tests/test_glonass_kaitai.cc b/system/ubloxd/tests/test_glonass_kaitai.cc deleted file mode 100644 index 96f43742b4c0c9..00000000000000 --- a/system/ubloxd/tests/test_glonass_kaitai.cc +++ /dev/null @@ -1,360 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "catch2/catch.hpp" -#include "system/ubloxd/generated/glonass.h" - -typedef std::vector> string_data; - -#define IDLE_CHIP_IDX 0 -#define STRING_NUMBER_IDX 1 -// string data 1-5 -#define HC_IDX 0 -#define PAD1_IDX 1 -#define SUPERFRAME_IDX 2 -#define PAD2_IDX 3 -#define FRAME_IDX 4 - -// Indexes for string number 1 -#define ST1_NU_IDX 2 -#define ST1_P1_IDX 3 -#define ST1_T_K_IDX 4 -#define ST1_X_VEL_S_IDX 5 -#define ST1_X_VEL_V_IDX 6 -#define ST1_X_ACCEL_S_IDX 7 -#define ST1_X_ACCEL_V_IDX 8 -#define ST1_X_S_IDX 9 -#define ST1_X_V_IDX 10 -#define ST1_HC_OFF 11 - -// Indexes for string number 2 -#define ST2_BN_IDX 2 -#define ST2_P2_IDX 3 -#define ST2_TB_IDX 4 -#define ST2_NU_IDX 5 -#define ST2_Y_VEL_S_IDX 6 -#define ST2_Y_VEL_V_IDX 7 -#define ST2_Y_ACCEL_S_IDX 8 -#define ST2_Y_ACCEL_V_IDX 9 -#define ST2_Y_S_IDX 10 -#define ST2_Y_V_IDX 11 -#define ST2_HC_OFF 12 - -// Indexes for string number 3 -#define ST3_P3_IDX 2 -#define ST3_GAMMA_N_S_IDX 3 -#define ST3_GAMMA_N_V_IDX 4 -#define ST3_NU_1_IDX 5 -#define ST3_P_IDX 6 -#define ST3_L_N_IDX 7 -#define ST3_Z_VEL_S_IDX 8 -#define ST3_Z_VEL_V_IDX 9 -#define ST3_Z_ACCEL_S_IDX 10 -#define ST3_Z_ACCEL_V_IDX 11 -#define ST3_Z_S_IDX 12 -#define ST3_Z_V_IDX 13 -#define ST3_HC_OFF 14 - -// Indexes for string number 4 -#define ST4_TAU_N_S_IDX 2 -#define ST4_TAU_N_V_IDX 3 -#define ST4_DELTA_TAU_N_S_IDX 4 -#define ST4_DELTA_TAU_N_V_IDX 5 -#define ST4_E_N_IDX 6 -#define ST4_NU_1_IDX 7 -#define ST4_P4_IDX 8 -#define ST4_F_T_IDX 9 -#define ST4_NU_2_IDX 10 -#define ST4_N_T_IDX 11 -#define ST4_N_IDX 12 -#define ST4_M_IDX 13 -#define ST4_HC_OFF 14 - -// Indexes for string number 5 -#define ST5_N_A_IDX 2 -#define ST5_TAU_C_IDX 3 -#define ST5_NU_IDX 4 -#define ST5_N_4_IDX 5 -#define ST5_TAU_GPS_IDX 6 -#define ST5_L_N_IDX 7 -#define ST5_HC_OFF 8 - -// Indexes for non immediate -#define ST6_DATA_1_IDX 2 -#define ST6_DATA_2_IDX 3 -#define ST6_HC_OFF 4 - - -std::string generate_inp_data(string_data& data) { - std::string inp_data = ""; - for (auto& [b, v] : data) { - std::string tmp = std::bitset<64>(v).to_string(); - inp_data += tmp.substr(64-b, b); - } - assert(inp_data.size() == 128); - - std::string string_data; - string_data.reserve(16); - for (int i = 0; i < 128; i+=8) { - std::string substr = inp_data.substr(i, 8); - string_data.push_back((uint8_t)std::stoi(substr.c_str(), 0, 2)); - } - - return string_data; -} - -string_data generate_string_data(uint8_t string_number) { - - srand((unsigned)time(0)); - string_data data; // - data.push_back({1, 0}); // idle chip - data.push_back({4, string_number}); // string number - - if (string_number == 1) { - data.push_back({2, 3}); // not_used - data.push_back({2, 1}); // p1 - data.push_back({12, 113}); // t_k - data.push_back({1, rand() & 1}); // x_vel_sign - data.push_back({23, 7122}); // x_vel_value - data.push_back({1, rand() & 1}); // x_accel_sign - data.push_back({4, 3}); // x_accel_value - data.push_back({1, rand() & 1}); // x_sign - data.push_back({26, 33554431}); // x_value - } else if (string_number == 2) { - data.push_back({3, 3}); // b_n - data.push_back({1, 1}); // p2 - data.push_back({7, 123}); // t_b - data.push_back({5, 31}); // not_used - data.push_back({1, rand() & 1}); // y_vel_sign - data.push_back({23, 7422}); // y_vel_value - data.push_back({1, rand() & 1}); // y_accel_sign - data.push_back({4, 3}); // y_accel_value - data.push_back({1, rand() & 1}); // y_sign - data.push_back({26, 67108863}); // y_value - } else if (string_number == 3) { - data.push_back({1, 0}); // p3 - data.push_back({1, 1}); // gamma_n_sign - data.push_back({10, 123}); // gamma_n_value - data.push_back({1, 0}); // not_used - data.push_back({2, 2}); // p - data.push_back({1, 1}); // l_n - data.push_back({1, rand() & 1}); // z_vel_sign - data.push_back({23, 1337}); // z_vel_value - data.push_back({1, rand() & 1}); // z_accel_sign - data.push_back({4, 9}); // z_accel_value - data.push_back({1, rand() & 1}); // z_sign - data.push_back({26, 100023}); // z_value - } else if (string_number == 4) { - data.push_back({1, rand() & 1}); // tau_n_sign - data.push_back({21, 197152}); // tau_n_value - data.push_back({1, rand() & 1}); // delta_tau_n_sign - data.push_back({4, 4}); // delta_tau_n_value - data.push_back({5, 0}); // e_n - data.push_back({14, 2}); // not_used_1 - data.push_back({1, 1}); // p4 - data.push_back({4, 9}); // f_t - data.push_back({3, 3}); // not_used_2 - data.push_back({11, 2047}); // n_t - data.push_back({5, 2}); // n - data.push_back({2, 1}); // m - } else if (string_number == 5) { - data.push_back({11, 2047}); // n_a - data.push_back({32, 4294767295}); // tau_c - data.push_back({1, 0}); // not_used_1 - data.push_back({5, 2}); // n_4 - data.push_back({22, 4114304}); // tau_gps - data.push_back({1, 0}); // l_n - } else { // non-immediate data is not parsed - data.push_back({64, rand()}); // data_1 - data.push_back({8, 6}); // data_2 - } - - data.push_back({8, rand() & 0xFF}); // hamming code - data.push_back({11, rand() & 0x7FF}); // pad - data.push_back({16, rand() & 0xFFFF}); // superframe - data.push_back({8, rand() & 0xFF}); // pad - data.push_back({8, rand() & 0xFF}); // frame - return data; -} - -TEST_CASE("parse_string_number_1"){ - string_data data = generate_string_data(1); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST1_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST1_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST1_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST1_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST1_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str1(inp_data); - glonass_t str1_data(&str1); - glonass_t::string_1_t* s1 = static_cast(str1_data.data()); - - REQUIRE(s1->not_used() == data[ST1_NU_IDX].second); - REQUIRE(s1->p1() == data[ST1_P1_IDX].second); - REQUIRE(s1->t_k() == data[ST1_T_K_IDX].second); - - int mul = s1->x_vel_sign() ? (-1) : 1; - REQUIRE(s1->x_vel() == (data[ST1_X_VEL_V_IDX].second * mul)); - mul = s1->x_accel_sign() ? (-1) : 1; - REQUIRE(s1->x_accel() == (data[ST1_X_ACCEL_V_IDX].second * mul)); - mul = s1->x_sign() ? (-1) : 1; - REQUIRE(s1->x() == (data[ST1_X_V_IDX].second * mul)); -} - -TEST_CASE("parse_string_number_2"){ - string_data data = generate_string_data(2); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST2_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST2_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST2_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST2_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST2_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str2(inp_data); - glonass_t str2_data(&str2); - glonass_t::string_2_t* s2 = static_cast(str2_data.data()); - - REQUIRE(s2->b_n() == data[ST2_BN_IDX].second); - REQUIRE(s2->not_used() == data[ST2_NU_IDX].second); - REQUIRE(s2->p2() == data[ST2_P2_IDX].second); - REQUIRE(s2->t_b() == data[ST2_TB_IDX].second); - int mul = s2->y_vel_sign() ? (-1) : 1; - REQUIRE(s2->y_vel() == (data[ST2_Y_VEL_V_IDX].second * mul)); - mul = s2->y_accel_sign() ? (-1) : 1; - REQUIRE(s2->y_accel() == (data[ST2_Y_ACCEL_V_IDX].second * mul)); - mul = s2->y_sign() ? (-1) : 1; - REQUIRE(s2->y() == (data[ST2_Y_V_IDX].second * mul)); -} - -TEST_CASE("parse_string_number_3"){ - string_data data = generate_string_data(3); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST3_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST3_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST3_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST3_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST3_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str3(inp_data); - glonass_t str3_data(&str3); - glonass_t::string_3_t* s3 = static_cast(str3_data.data()); - - REQUIRE(s3->p3() == data[ST3_P3_IDX].second); - int mul = s3->gamma_n_sign() ? (-1) : 1; - REQUIRE(s3->gamma_n() == (data[ST3_GAMMA_N_V_IDX].second * mul)); - REQUIRE(s3->not_used() == data[ST3_NU_1_IDX].second); - REQUIRE(s3->p() == data[ST3_P_IDX].second); - REQUIRE(s3->l_n() == data[ST3_L_N_IDX].second); - mul = s3->z_vel_sign() ? (-1) : 1; - REQUIRE(s3->z_vel() == (data[ST3_Z_VEL_V_IDX].second * mul)); - mul = s3->z_accel_sign() ? (-1) : 1; - REQUIRE(s3->z_accel() == (data[ST3_Z_ACCEL_V_IDX].second * mul)); - mul = s3->z_sign() ? (-1) : 1; - REQUIRE(s3->z() == (data[ST3_Z_V_IDX].second * mul)); -} - -TEST_CASE("parse_string_number_4"){ - string_data data = generate_string_data(4); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST4_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST4_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST4_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST4_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST4_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str4(inp_data); - glonass_t str4_data(&str4); - glonass_t::string_4_t* s4 = static_cast(str4_data.data()); - - int mul = s4->tau_n_sign() ? (-1) : 1; - REQUIRE(s4->tau_n() == (data[ST4_TAU_N_V_IDX].second * mul)); - mul = s4->delta_tau_n_sign() ? (-1) : 1; - REQUIRE(s4->delta_tau_n() == (data[ST4_DELTA_TAU_N_V_IDX].second * mul)); - REQUIRE(s4->e_n() == data[ST4_E_N_IDX].second); - REQUIRE(s4->not_used_1() == data[ST4_NU_1_IDX].second); - REQUIRE(s4->p4() == data[ST4_P4_IDX].second); - REQUIRE(s4->f_t() == data[ST4_F_T_IDX].second); - REQUIRE(s4->not_used_2() == data[ST4_NU_2_IDX].second); - REQUIRE(s4->n_t() == data[ST4_N_T_IDX].second); - REQUIRE(s4->n() == data[ST4_N_IDX].second); - REQUIRE(s4->m() == data[ST4_M_IDX].second); -} - -TEST_CASE("parse_string_number_5"){ - string_data data = generate_string_data(5); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST5_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST5_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST5_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST5_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST5_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str5(inp_data); - glonass_t str5_data(&str5); - glonass_t::string_5_t* s5 = static_cast(str5_data.data()); - - REQUIRE(s5->n_a() == data[ST5_N_A_IDX].second); - REQUIRE(s5->tau_c() == data[ST5_TAU_C_IDX].second); - REQUIRE(s5->not_used() == data[ST5_NU_IDX].second); - REQUIRE(s5->n_4() == data[ST5_N_4_IDX].second); - REQUIRE(s5->tau_gps() == data[ST5_TAU_GPS_IDX].second); - REQUIRE(s5->l_n() == data[ST5_L_N_IDX].second); -} - -TEST_CASE("parse_string_number_NI"){ - string_data data = generate_string_data((rand() % 10) + 6); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST6_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST6_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST6_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST6_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST6_HC_OFF + FRAME_IDX].second); - - kaitai::kstream strni(inp_data); - glonass_t strni_data(&strni); - glonass_t::string_non_immediate_t* sni = static_cast(strni_data.data()); - - REQUIRE(sni->data_1() == data[ST6_DATA_1_IDX].second); - REQUIRE(sni->data_2() == data[ST6_DATA_2_IDX].second); -} diff --git a/system/ubloxd/tests/test_glonass_runner.cc b/system/ubloxd/tests/test_glonass_runner.cc deleted file mode 100644 index 62bf7476a18996..00000000000000 --- a/system/ubloxd/tests/test_glonass_runner.cc +++ /dev/null @@ -1,2 +0,0 @@ -#define CATCH_CONFIG_MAIN -#include "catch2/catch.hpp" diff --git a/system/ubloxd/tests/ubloxd.py b/system/ubloxd/tests/ubloxd.py deleted file mode 100755 index c17387114fd32e..00000000000000 --- a/system/ubloxd/tests/ubloxd.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python3 -# type: ignore - -from openpilot.selfdrive.locationd.test import ublox -import struct - -baudrate = 460800 -rate = 100 # send new data every 100ms - - -def configure_ublox(dev): - # configure ports and solution parameters and rate - dev.configure_port(port=ublox.PORT_USB, inMask=1, outMask=1) # enable only UBX on USB - dev.configure_port(port=0, inMask=0, outMask=0) # disable DDC - - payload = struct.pack(' - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "common/swaglog.h" - -const double gpsPi = 3.1415926535898; -#define UBLOX_MSG_SIZE(hdr) (*(uint16_t *)&hdr[4]) - -inline static bool bit_to_bool(uint8_t val, int shifts) { - return (bool)(val & (1 << shifts)); -} - -inline int UbloxMsgParser::needed_bytes() { - // Msg header incomplete? - if (bytes_in_parse_buf < ublox::UBLOX_HEADER_SIZE) - return ublox::UBLOX_HEADER_SIZE + ublox::UBLOX_CHECKSUM_SIZE - bytes_in_parse_buf; - uint16_t needed = UBLOX_MSG_SIZE(msg_parse_buf) + ublox::UBLOX_HEADER_SIZE + ublox::UBLOX_CHECKSUM_SIZE; - // too much data - if (needed < (uint16_t)bytes_in_parse_buf) - return -1; - return needed - (uint16_t)bytes_in_parse_buf; -} - -inline bool UbloxMsgParser::valid_cheksum() { - uint8_t ck_a = 0, ck_b = 0; - for (int i = 2; i < bytes_in_parse_buf - ublox::UBLOX_CHECKSUM_SIZE; i++) { - ck_a = (ck_a + msg_parse_buf[i]) & 0xFF; - ck_b = (ck_b + ck_a) & 0xFF; - } - if (ck_a != msg_parse_buf[bytes_in_parse_buf - 2]) { - LOGD("Checksum a mismatch: %02X, %02X", ck_a, msg_parse_buf[6]); - return false; - } - if (ck_b != msg_parse_buf[bytes_in_parse_buf - 1]) { - LOGD("Checksum b mismatch: %02X, %02X", ck_b, msg_parse_buf[7]); - return false; - } - return true; -} - -inline bool UbloxMsgParser::valid() { - return bytes_in_parse_buf >= ublox::UBLOX_HEADER_SIZE + ublox::UBLOX_CHECKSUM_SIZE && - needed_bytes() == 0 && valid_cheksum(); -} - -inline bool UbloxMsgParser::valid_so_far() { - if (bytes_in_parse_buf > 0 && msg_parse_buf[0] != ublox::PREAMBLE1) { - return false; - } - if (bytes_in_parse_buf > 1 && msg_parse_buf[1] != ublox::PREAMBLE2) { - return false; - } - if (needed_bytes() == 0 && !valid()) { - return false; - } - return true; -} - -bool UbloxMsgParser::add_data(float log_time, const uint8_t *incoming_data, uint32_t incoming_data_len, size_t &bytes_consumed) { - last_log_time = log_time; - int needed = needed_bytes(); - if (needed > 0) { - bytes_consumed = std::min((uint32_t)needed, incoming_data_len); - // Add data to buffer - memcpy(msg_parse_buf + bytes_in_parse_buf, incoming_data, bytes_consumed); - bytes_in_parse_buf += bytes_consumed; - } else { - bytes_consumed = incoming_data_len; - } - - // Validate msg format, detect invalid header and invalid checksum. - while (!valid_so_far() && bytes_in_parse_buf != 0) { - // Corrupted msg, drop a byte. - bytes_in_parse_buf -= 1; - if (bytes_in_parse_buf > 0) - memmove(&msg_parse_buf[0], &msg_parse_buf[1], bytes_in_parse_buf); - } - - // There is redundant data at the end of buffer, reset the buffer. - if (needed_bytes() == -1) { - bytes_in_parse_buf = 0; - } - return valid(); -} - - -std::pair> UbloxMsgParser::gen_msg() { - std::string dat = data(); - kaitai::kstream stream(dat); - - ubx_t ubx_message(&stream); - auto body = ubx_message.body(); - - switch (ubx_message.msg_type()) { - case 0x0107: - return {"gpsLocationExternal", gen_nav_pvt(static_cast(body))}; - case 0x0213: // UBX-RXM-SFRB (Broadcast Navigation Data Subframe) - return {"ubloxGnss", gen_rxm_sfrbx(static_cast(body))}; - case 0x0215: // UBX-RXM-RAW (Multi-GNSS Raw Measurement Data) - return {"ubloxGnss", gen_rxm_rawx(static_cast(body))}; - case 0x0a09: - return {"ubloxGnss", gen_mon_hw(static_cast(body))}; - case 0x0a0b: - return {"ubloxGnss", gen_mon_hw2(static_cast(body))}; - case 0x0135: - return {"ubloxGnss", gen_nav_sat(static_cast(body))}; - default: - LOGE("Unknown message type %x", ubx_message.msg_type()); - return {"ubloxGnss", kj::Array()}; - } -} - - -kj::Array UbloxMsgParser::gen_nav_pvt(ubx_t::nav_pvt_t *msg) { - MessageBuilder msg_builder; - auto gpsLoc = msg_builder.initEvent().initGpsLocationExternal(); - gpsLoc.setSource(cereal::GpsLocationData::SensorSource::UBLOX); - gpsLoc.setFlags(msg->flags()); - gpsLoc.setHasFix((msg->flags() % 2) == 1); - gpsLoc.setLatitude(msg->lat() * 1e-07); - gpsLoc.setLongitude(msg->lon() * 1e-07); - gpsLoc.setAltitude(msg->height() * 1e-03); - gpsLoc.setSpeed(msg->g_speed() * 1e-03); - gpsLoc.setBearingDeg(msg->head_mot() * 1e-5); - gpsLoc.setHorizontalAccuracy(msg->h_acc() * 1e-03); - std::tm timeinfo = std::tm(); - timeinfo.tm_year = msg->year() - 1900; - timeinfo.tm_mon = msg->month() - 1; - timeinfo.tm_mday = msg->day(); - timeinfo.tm_hour = msg->hour(); - timeinfo.tm_min = msg->min(); - timeinfo.tm_sec = msg->sec(); - - std::time_t utc_tt = timegm(&timeinfo); - gpsLoc.setUnixTimestampMillis(utc_tt * 1e+03 + msg->nano() * 1e-06); - float f[] = { msg->vel_n() * 1e-03f, msg->vel_e() * 1e-03f, msg->vel_d() * 1e-03f }; - gpsLoc.setVNED(f); - gpsLoc.setVerticalAccuracy(msg->v_acc() * 1e-03); - gpsLoc.setSpeedAccuracy(msg->s_acc() * 1e-03); - gpsLoc.setBearingAccuracyDeg(msg->head_acc() * 1e-05); - return capnp::messageToFlatArray(msg_builder); -} - -kj::Array UbloxMsgParser::parse_gps_ephemeris(ubx_t::rxm_sfrbx_t *msg) { - // GPS subframes are packed into 10x 4 bytes, each containing 3 actual bytes - // We will first need to separate the data from the padding and parity - auto body = *msg->body(); - assert(body.size() == 10); - - std::string subframe_data; - subframe_data.reserve(30); - for (uint32_t word : body) { - word = word >> 6; // TODO: Verify parity - subframe_data.push_back(word >> 16); - subframe_data.push_back(word >> 8); - subframe_data.push_back(word >> 0); - } - - // Collect subframes in map and parse when we have all the parts - { - kaitai::kstream stream(subframe_data); - gps_t subframe(&stream); - - int subframe_id = subframe.how()->subframe_id(); - if (subframe_id > 3 || subframe_id < 1) { - // don't parse almanac subframes - return kj::Array(); - } - gps_subframes[msg->sv_id()][subframe_id] = subframe_data; - } - - // publish if subframes 1-3 have been collected - if (gps_subframes[msg->sv_id()].size() == 3) { - MessageBuilder msg_builder; - auto eph = msg_builder.initEvent().initUbloxGnss().initEphemeris(); - eph.setSvId(msg->sv_id()); - - int iode_s2 = 0; - int iode_s3 = 0; - int iodc_lsb = 0; - int week; - - // Subframe 1 - { - kaitai::kstream stream(gps_subframes[msg->sv_id()][1]); - gps_t subframe(&stream); - gps_t::subframe_1_t* subframe_1 = static_cast(subframe.body()); - - // Each message is incremented to be greater or equal than week 1877 (2015-12-27). - // To skip this use the current_time argument - week = subframe_1->week_no(); - week += 1024; - if (week < 1877) { - week += 1024; - } - //eph.setGpsWeek(subframe_1->week_no()); - eph.setTgd(subframe_1->t_gd() * pow(2, -31)); - eph.setToc(subframe_1->t_oc() * pow(2, 4)); - eph.setAf2(subframe_1->af_2() * pow(2, -55)); - eph.setAf1(subframe_1->af_1() * pow(2, -43)); - eph.setAf0(subframe_1->af_0() * pow(2, -31)); - eph.setSvHealth(subframe_1->sv_health()); - eph.setTowCount(subframe.how()->tow_count()); - iodc_lsb = subframe_1->iodc_lsb(); - } - - // Subframe 2 - { - kaitai::kstream stream(gps_subframes[msg->sv_id()][2]); - gps_t subframe(&stream); - gps_t::subframe_2_t* subframe_2 = static_cast(subframe.body()); - - // GPS week refers to current week, the ephemeris can be valid for the next - // if toe equals 0, this can be verified by the TOW count if it is within the - // last 2 hours of the week (gps ephemeris valid for 4hours) - if (subframe_2->t_oe() == 0 and subframe.how()->tow_count()*6 >= (SECS_IN_WEEK - 2*SECS_IN_HR)){ - week += 1; - } - eph.setCrs(subframe_2->c_rs() * pow(2, -5)); - eph.setDeltaN(subframe_2->delta_n() * pow(2, -43) * gpsPi); - eph.setM0(subframe_2->m_0() * pow(2, -31) * gpsPi); - eph.setCuc(subframe_2->c_uc() * pow(2, -29)); - eph.setEcc(subframe_2->e() * pow(2, -33)); - eph.setCus(subframe_2->c_us() * pow(2, -29)); - eph.setA(pow(subframe_2->sqrt_a() * pow(2, -19), 2.0)); - eph.setToe(subframe_2->t_oe() * pow(2, 4)); - iode_s2 = subframe_2->iode(); - } - - // Subframe 3 - { - kaitai::kstream stream(gps_subframes[msg->sv_id()][3]); - gps_t subframe(&stream); - gps_t::subframe_3_t* subframe_3 = static_cast(subframe.body()); - - eph.setCic(subframe_3->c_ic() * pow(2, -29)); - eph.setOmega0(subframe_3->omega_0() * pow(2, -31) * gpsPi); - eph.setCis(subframe_3->c_is() * pow(2, -29)); - eph.setI0(subframe_3->i_0() * pow(2, -31) * gpsPi); - eph.setCrc(subframe_3->c_rc() * pow(2, -5)); - eph.setOmega(subframe_3->omega() * pow(2, -31) * gpsPi); - eph.setOmegaDot(subframe_3->omega_dot() * pow(2, -43) * gpsPi); - eph.setIode(subframe_3->iode()); - eph.setIDot(subframe_3->idot() * pow(2, -43) * gpsPi); - iode_s3 = subframe_3->iode(); - } - - eph.setToeWeek(week); - eph.setTocWeek(week); - - gps_subframes[msg->sv_id()].clear(); - if (iodc_lsb != iode_s2 || iodc_lsb != iode_s3) { - // data set cutover, reject ephemeris - return kj::Array(); - } - return capnp::messageToFlatArray(msg_builder); - } - return kj::Array(); -} - -kj::Array UbloxMsgParser::parse_glonass_ephemeris(ubx_t::rxm_sfrbx_t *msg) { - // This parser assumes that no 2 satellites of the same frequency - // can be in view at the same time - auto body = *msg->body(); - assert(body.size() == 4); - { - std::string string_data; - string_data.reserve(16); - for (uint32_t word : body) { - for (int i = 3; i >= 0; i--) - string_data.push_back(word >> 8*i); - } - - kaitai::kstream stream(string_data); - glonass_t gl_string(&stream); - int string_number = gl_string.string_number(); - if (string_number < 1 || string_number > 5 || gl_string.idle_chip()) { - // don't parse non immediate data, idle_chip == 0 - return kj::Array(); - } - - // Check if new string either has same superframe_id or log transmission times make sense - bool superframe_unknown = false; - bool needs_clear = false; - for (int i = 1; i <= 5; i++) { - if (glonass_strings[msg->freq_id()].find(i) == glonass_strings[msg->freq_id()].end()) - continue; - if (glonass_string_superframes[msg->freq_id()][i] == 0 || gl_string.superframe_number() == 0) { - superframe_unknown = true; - } else if (glonass_string_superframes[msg->freq_id()][i] != gl_string.superframe_number()) { - needs_clear = true; - } - // Check if string times add up to being from the same frame - // If superframe is known this is redundant - // Strings are sent 2s apart and frames are 30s apart - if (superframe_unknown && - std::abs((glonass_string_times[msg->freq_id()][i] - 2.0 * i) - (last_log_time - 2.0 * string_number)) > 10) - needs_clear = true; - } - if (needs_clear) { - glonass_strings[msg->freq_id()].clear(); - glonass_string_superframes[msg->freq_id()].clear(); - glonass_string_times[msg->freq_id()].clear(); - } - glonass_strings[msg->freq_id()][string_number] = string_data; - glonass_string_superframes[msg->freq_id()][string_number] = gl_string.superframe_number(); - glonass_string_times[msg->freq_id()][string_number] = last_log_time; - } - if (msg->sv_id() == 255) { - // data can be decoded before identifying the SV number, in this case 255 - // is returned, which means "unknown" (ublox p32) - return kj::Array(); - } - - // publish if strings 1-5 have been collected - if (glonass_strings[msg->freq_id()].size() != 5) { - return kj::Array(); - } - - MessageBuilder msg_builder; - auto eph = msg_builder.initEvent().initUbloxGnss().initGlonassEphemeris(); - eph.setSvId(msg->sv_id()); - eph.setFreqNum(msg->freq_id() - 7); - - uint16_t current_day = 0; - uint16_t tk = 0; - - // string number 1 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][1]); - glonass_t gl_stream(&stream); - glonass_t::string_1_t* data = static_cast(gl_stream.data()); - - eph.setP1(data->p1()); - tk = data->t_k(); - eph.setTkDEPRECATED(tk); - eph.setXVel(data->x_vel() * pow(2, -20)); - eph.setXAccel(data->x_accel() * pow(2, -30)); - eph.setX(data->x() * pow(2, -11)); - } - - // string number 2 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][2]); - glonass_t gl_stream(&stream); - glonass_t::string_2_t* data = static_cast(gl_stream.data()); - - eph.setSvHealth(data->b_n()>>2); // MSB indicates health - eph.setP2(data->p2()); - eph.setTb(data->t_b()); - eph.setYVel(data->y_vel() * pow(2, -20)); - eph.setYAccel(data->y_accel() * pow(2, -30)); - eph.setY(data->y() * pow(2, -11)); - } - - // string number 3 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][3]); - glonass_t gl_stream(&stream); - glonass_t::string_3_t* data = static_cast(gl_stream.data()); - - eph.setP3(data->p3()); - eph.setGammaN(data->gamma_n() * pow(2, -40)); - eph.setSvHealth(eph.getSvHealth() | data->l_n()); - eph.setZVel(data->z_vel() * pow(2, -20)); - eph.setZAccel(data->z_accel() * pow(2, -30)); - eph.setZ(data->z() * pow(2, -11)); - } - - // string number 4 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][4]); - glonass_t gl_stream(&stream); - glonass_t::string_4_t* data = static_cast(gl_stream.data()); - - current_day = data->n_t(); - eph.setNt(current_day); - eph.setTauN(data->tau_n() * pow(2, -30)); - eph.setDeltaTauN(data->delta_tau_n() * pow(2, -30)); - eph.setAge(data->e_n()); - eph.setP4(data->p4()); - eph.setSvURA(glonass_URA_lookup.at(data->f_t())); - if (msg->sv_id() != data->n()) { - LOGE("SV_ID != SLOT_NUMBER: %d %" PRIu64, msg->sv_id(), data->n()); - } - eph.setSvType(data->m()); - } - - // string number 5 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][5]); - glonass_t gl_stream(&stream); - glonass_t::string_5_t* data = static_cast(gl_stream.data()); - - // string5 parsing is only needed to get the year, this can be removed and - // the year can be fetched later in laika (note rollovers and leap year) - eph.setN4(data->n_4()); - int tk_seconds = SECS_IN_HR * ((tk>>7) & 0x1F) + SECS_IN_MIN * ((tk>>1) & 0x3F) + (tk & 0x1) * 30; - eph.setTkSeconds(tk_seconds); - } - - glonass_strings[msg->freq_id()].clear(); - return capnp::messageToFlatArray(msg_builder); -} - - -kj::Array UbloxMsgParser::gen_rxm_sfrbx(ubx_t::rxm_sfrbx_t *msg) { - switch (msg->gnss_id()) { - case ubx_t::gnss_type_t::GNSS_TYPE_GPS: - return parse_gps_ephemeris(msg); - case ubx_t::gnss_type_t::GNSS_TYPE_GLONASS: - return parse_glonass_ephemeris(msg); - default: - return kj::Array(); - } -} - -kj::Array UbloxMsgParser::gen_rxm_rawx(ubx_t::rxm_rawx_t *msg) { - MessageBuilder msg_builder; - auto mr = msg_builder.initEvent().initUbloxGnss().initMeasurementReport(); - mr.setRcvTow(msg->rcv_tow()); - mr.setGpsWeek(msg->week()); - mr.setLeapSeconds(msg->leap_s()); - mr.setGpsWeek(msg->week()); - - auto mb = mr.initMeasurements(msg->num_meas()); - auto measurements = *msg->meas(); - for (int8_t i = 0; i < msg->num_meas(); i++) { - mb[i].setSvId(measurements[i]->sv_id()); - mb[i].setPseudorange(measurements[i]->pr_mes()); - mb[i].setCarrierCycles(measurements[i]->cp_mes()); - mb[i].setDoppler(measurements[i]->do_mes()); - mb[i].setGnssId(measurements[i]->gnss_id()); - mb[i].setGlonassFrequencyIndex(measurements[i]->freq_id()); - mb[i].setLocktime(measurements[i]->lock_time()); - mb[i].setCno(measurements[i]->cno()); - mb[i].setPseudorangeStdev(0.01 * (pow(2, (measurements[i]->pr_stdev() & 15)))); // weird scaling, might be wrong - mb[i].setCarrierPhaseStdev(0.004 * (measurements[i]->cp_stdev() & 15)); - mb[i].setDopplerStdev(0.002 * (pow(2, (measurements[i]->do_stdev() & 15)))); // weird scaling, might be wrong - - auto ts = mb[i].initTrackingStatus(); - auto trk_stat = measurements[i]->trk_stat(); - ts.setPseudorangeValid(bit_to_bool(trk_stat, 0)); - ts.setCarrierPhaseValid(bit_to_bool(trk_stat, 1)); - ts.setHalfCycleValid(bit_to_bool(trk_stat, 2)); - ts.setHalfCycleSubtracted(bit_to_bool(trk_stat, 3)); - } - - mr.setNumMeas(msg->num_meas()); - auto rs = mr.initReceiverStatus(); - rs.setLeapSecValid(bit_to_bool(msg->rec_stat(), 0)); - rs.setClkReset(bit_to_bool(msg->rec_stat(), 2)); - return capnp::messageToFlatArray(msg_builder); -} - -kj::Array UbloxMsgParser::gen_nav_sat(ubx_t::nav_sat_t *msg) { - MessageBuilder msg_builder; - auto sr = msg_builder.initEvent().initUbloxGnss().initSatReport(); - sr.setITow(msg->itow()); - - auto svs = sr.initSvs(msg->num_svs()); - auto svs_data = *msg->svs(); - for (int8_t i = 0; i < msg->num_svs(); i++) { - svs[i].setSvId(svs_data[i]->sv_id()); - svs[i].setGnssId(svs_data[i]->gnss_id()); - svs[i].setFlagsBitfield(svs_data[i]->flags()); - } - - return capnp::messageToFlatArray(msg_builder); -} - -kj::Array UbloxMsgParser::gen_mon_hw(ubx_t::mon_hw_t *msg) { - MessageBuilder msg_builder; - auto hwStatus = msg_builder.initEvent().initUbloxGnss().initHwStatus(); - hwStatus.setNoisePerMS(msg->noise_per_ms()); - hwStatus.setFlags(msg->flags()); - hwStatus.setAgcCnt(msg->agc_cnt()); - hwStatus.setAStatus((cereal::UbloxGnss::HwStatus::AntennaSupervisorState) msg->a_status()); - hwStatus.setAPower((cereal::UbloxGnss::HwStatus::AntennaPowerStatus) msg->a_power()); - hwStatus.setJamInd(msg->jam_ind()); - return capnp::messageToFlatArray(msg_builder); -} - -kj::Array UbloxMsgParser::gen_mon_hw2(ubx_t::mon_hw2_t *msg) { - MessageBuilder msg_builder; - auto hwStatus = msg_builder.initEvent().initUbloxGnss().initHwStatus2(); - hwStatus.setOfsI(msg->ofs_i()); - hwStatus.setMagI(msg->mag_i()); - hwStatus.setOfsQ(msg->ofs_q()); - hwStatus.setMagQ(msg->mag_q()); - - switch (msg->cfg_source()) { - case ubx_t::mon_hw2_t::config_source_t::CONFIG_SOURCE_ROM: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::ROM); - break; - case ubx_t::mon_hw2_t::config_source_t::CONFIG_SOURCE_OTP: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::OTP); - break; - case ubx_t::mon_hw2_t::config_source_t::CONFIG_SOURCE_CONFIG_PINS: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::CONFIGPINS); - break; - case ubx_t::mon_hw2_t::config_source_t::CONFIG_SOURCE_FLASH: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::FLASH); - break; - default: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::UNDEFINED); - break; - } - - hwStatus.setLowLevCfg(msg->low_lev_cfg()); - hwStatus.setPostStatus(msg->post_status()); - - return capnp::messageToFlatArray(msg_builder); -} diff --git a/system/ubloxd/ublox_msg.h b/system/ubloxd/ublox_msg.h deleted file mode 100644 index d21760edc28498..00000000000000 --- a/system/ubloxd/ublox_msg.h +++ /dev/null @@ -1,131 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "common/util.h" -#include "system/ubloxd/generated/gps.h" -#include "system/ubloxd/generated/glonass.h" -#include "system/ubloxd/generated/ubx.h" - -using namespace std::string_literals; - -const int SECS_IN_MIN = 60; -const int SECS_IN_HR = 60 * SECS_IN_MIN; -const int SECS_IN_DAY = 24 * SECS_IN_HR; -const int SECS_IN_WEEK = 7 * SECS_IN_DAY; - -// protocol constants -namespace ublox { - const uint8_t PREAMBLE1 = 0xb5; - const uint8_t PREAMBLE2 = 0x62; - - const int UBLOX_HEADER_SIZE = 6; - const int UBLOX_CHECKSUM_SIZE = 2; - const int UBLOX_MAX_MSG_SIZE = 65536; - - struct ubx_mga_ini_time_utc_t { - uint8_t type; - uint8_t version; - uint8_t ref; - int8_t leapSecs; - uint16_t year; - uint8_t month; - uint8_t day; - uint8_t hour; - uint8_t minute; - uint8_t second; - uint8_t reserved1; - uint32_t ns; - uint16_t tAccS; - uint16_t reserved2; - uint32_t tAccNs; - } __attribute__((packed)); - - inline std::string ubx_add_checksum(const std::string &msg) { - assert(msg.size() > 2); - - uint8_t ck_a = 0, ck_b = 0; - for (int i = 2; i < msg.size(); i++) { - ck_a = (ck_a + msg[i]) & 0xFF; - ck_b = (ck_b + ck_a) & 0xFF; - } - - std::string r = msg; - r.push_back(ck_a); - r.push_back(ck_b); - return r; - } - - inline std::string build_ubx_mga_ini_time_utc(struct tm time) { - ublox::ubx_mga_ini_time_utc_t payload = { - .type = 0x10, - .version = 0x0, - .ref = 0x0, - .leapSecs = -128, // Unknown - .year = (uint16_t)(1900 + time.tm_year), - .month = (uint8_t)(1 + time.tm_mon), - .day = (uint8_t)time.tm_mday, - .hour = (uint8_t)time.tm_hour, - .minute = (uint8_t)time.tm_min, - .second = (uint8_t)time.tm_sec, - .reserved1 = 0x0, - .ns = 0, - .tAccS = 30, - .reserved2 = 0x0, - .tAccNs = 0, - }; - assert(sizeof(payload) == 24); - - std::string msg = "\xb5\x62\x13\x40\x18\x00"s; - msg += std::string((char*)&payload, sizeof(payload)); - - return ubx_add_checksum(msg); - } -} - -class UbloxMsgParser { - public: - bool add_data(float log_time, const uint8_t *incoming_data, uint32_t incoming_data_len, size_t &bytes_consumed); - inline void reset() {bytes_in_parse_buf = 0;} - inline int needed_bytes(); - inline std::string data() {return std::string((const char*)msg_parse_buf, bytes_in_parse_buf);} - - std::pair> gen_msg(); - kj::Array gen_nav_pvt(ubx_t::nav_pvt_t *msg); - kj::Array gen_rxm_sfrbx(ubx_t::rxm_sfrbx_t *msg); - kj::Array gen_rxm_rawx(ubx_t::rxm_rawx_t *msg); - kj::Array gen_mon_hw(ubx_t::mon_hw_t *msg); - kj::Array gen_mon_hw2(ubx_t::mon_hw2_t *msg); - kj::Array gen_nav_sat(ubx_t::nav_sat_t *msg); - - private: - inline bool valid_cheksum(); - inline bool valid(); - inline bool valid_so_far(); - - kj::Array parse_gps_ephemeris(ubx_t::rxm_sfrbx_t *msg); - kj::Array parse_glonass_ephemeris(ubx_t::rxm_sfrbx_t *msg); - - std::unordered_map> gps_subframes; - - float last_log_time = 0.0; - size_t bytes_in_parse_buf = 0; - uint8_t msg_parse_buf[ublox::UBLOX_HEADER_SIZE + ublox::UBLOX_MAX_MSG_SIZE]; - - // user range accuracy in meters - const std::unordered_map glonass_URA_lookup = - {{ 0, 1}, { 1, 2}, { 2, 2.5}, { 3, 4}, { 4, 5}, {5, 7}, - { 6, 10}, { 7, 12}, { 8, 14}, { 9, 16}, {10, 32}, - {11, 64}, {12, 128}, {13, 256}, {14, 512}, {15, 1024}}; - - std::unordered_map> glonass_strings; - std::unordered_map> glonass_string_times; - std::unordered_map> glonass_string_superframes; -}; diff --git a/system/ubloxd/ubloxd.cc b/system/ubloxd/ubloxd.cc deleted file mode 100644 index 668c1a7ec07a47..00000000000000 --- a/system/ubloxd/ubloxd.cc +++ /dev/null @@ -1,65 +0,0 @@ -#include - -#include - -#include "cereal/messaging/messaging.h" -#include "common/swaglog.h" -#include "common/util.h" -#include "system/ubloxd/ublox_msg.h" - -ExitHandler do_exit; -using namespace ublox; - -int main() { - LOGW("starting ubloxd"); - AlignedBuffer aligned_buf; - UbloxMsgParser parser; - - PubMaster pm({"ubloxGnss", "gpsLocationExternal"}); - - std::unique_ptr context(Context::create()); - std::unique_ptr subscriber(SubSocket::create(context.get(), "ubloxRaw")); - assert(subscriber != NULL); - subscriber->setTimeout(100); - - - while (!do_exit) { - std::unique_ptr msg(subscriber->receive()); - if (!msg) { - if (errno == EINTR) { - do_exit = true; - } - continue; - } - - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(msg.get())); - cereal::Event::Reader event = cmsg.getRoot(); - auto ubloxRaw = event.getUbloxRaw(); - float log_time = 1e-9 * event.getLogMonoTime(); - - const uint8_t *data = ubloxRaw.begin(); - size_t len = ubloxRaw.size(); - size_t bytes_consumed = 0; - - while (bytes_consumed < len && !do_exit) { - size_t bytes_consumed_this_time = 0U; - if (parser.add_data(log_time, data + bytes_consumed, (uint32_t)(len - bytes_consumed), bytes_consumed_this_time)) { - - try { - auto ublox_msg = parser.gen_msg(); - if (ublox_msg.second.size() > 0) { - auto bytes = ublox_msg.second.asBytes(); - pm.send(ublox_msg.first.c_str(), bytes.begin(), bytes.size()); - } - } catch (const std::exception& e) { - LOGE("Error parsing ublox message %s", e.what()); - } - - parser.reset(); - } - bytes_consumed += bytes_consumed_this_time; - } - } - - return 0; -} diff --git a/system/ubloxd/ubloxd.py b/system/ubloxd/ubloxd.py new file mode 100755 index 00000000000000..78429a847b7c0e --- /dev/null +++ b/system/ubloxd/ubloxd.py @@ -0,0 +1,534 @@ +#!/usr/bin/env python3 +import math +import capnp +import calendar +import numpy as np +from collections import defaultdict +from dataclasses import dataclass + +from cereal import log +from cereal import messaging +from openpilot.system.ubloxd.ubx import Ubx +from openpilot.system.ubloxd.gps import Gps +from openpilot.system.ubloxd.glonass import Glonass + + +SECS_IN_MIN = 60 +SECS_IN_HR = 60 * SECS_IN_MIN +SECS_IN_DAY = 24 * SECS_IN_HR +SECS_IN_WEEK = 7 * SECS_IN_DAY + + +class UbxFramer: + PREAMBLE1 = 0xB5 + PREAMBLE2 = 0x62 + HEADER_SIZE = 6 + CHECKSUM_SIZE = 2 + + def __init__(self) -> None: + self.buf = bytearray() + self.last_log_time = 0.0 + + def reset(self) -> None: + self.buf.clear() + + @staticmethod + def _checksum_ok(frame: bytes) -> bool: + ck_a = 0 + ck_b = 0 + for b in frame[2:-2]: + ck_a = (ck_a + b) & 0xFF + ck_b = (ck_b + ck_a) & 0xFF + return ck_a == frame[-2] and ck_b == frame[-1] + + def add_data(self, log_time: float, incoming: bytes) -> list[bytes]: + self.last_log_time = log_time + out: list[bytes] = [] + if not incoming: + return out + self.buf += incoming + + while True: + # find preamble + if len(self.buf) < 2: + break + start = self.buf.find(b"\xb5\x62") + if start < 0: + # no preamble in buffer + self.buf.clear() + break + if start > 0: + # drop garbage before preamble + self.buf = self.buf[start:] + + if len(self.buf) < self.HEADER_SIZE: + break + + length_le = int.from_bytes(self.buf[4:6], 'little', signed=False) + total_len = self.HEADER_SIZE + length_le + self.CHECKSUM_SIZE + if len(self.buf) < total_len: + break + + candidate = bytes(self.buf[:total_len]) + if self._checksum_ok(candidate): + out.append(candidate) + # consume this frame + self.buf = self.buf[total_len:] + else: + # drop first byte and retry + self.buf = self.buf[1:] + + return out + + +def _bit(b: int, shift: int) -> bool: + return (b & (1 << shift)) != 0 + + +@dataclass +class EphemerisCaches: + gps_subframes: defaultdict[int, dict[int, bytes]] + glonass_strings: defaultdict[int, dict[int, bytes]] + glonass_string_times: defaultdict[int, dict[int, float]] + glonass_string_superframes: defaultdict[int, dict[int, int]] + + +class UbloxMsgParser: + gpsPi = 3.1415926535898 + + # user range accuracy in meters + glonass_URA_lookup: dict[int, float] = { + 0: 1, + 1: 2, + 2: 2.5, + 3: 4, + 4: 5, + 5: 7, + 6: 10, + 7: 12, + 8: 14, + 9: 16, + 10: 32, + 11: 64, + 12: 128, + 13: 256, + 14: 512, + 15: 1024, + } + + def __init__(self) -> None: + self.framer = UbxFramer() + self.caches = EphemerisCaches( + gps_subframes=defaultdict(dict), + glonass_strings=defaultdict(dict), + glonass_string_times=defaultdict(dict), + glonass_string_superframes=defaultdict(dict), + ) + + # Message generation entry point + def parse_frame(self, frame: bytes) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: + # Quick header parse + msg_type = int.from_bytes(frame[2:4], 'big') + payload = frame[6:-2] + if msg_type == 0x0107: + body = Ubx.NavPvt.from_bytes(payload) + return self._gen_nav_pvt(body) + if msg_type == 0x0213: + # Manually parse RXM-SFRBX to avoid EOF on some frames + if len(payload) < 8: + return None + gnss_id = payload[0] + sv_id = payload[1] + freq_id = payload[3] + num_words = payload[4] + exp = 8 + 4 * num_words + if exp != len(payload): + return None + words: list[int] = [] + off = 8 + for _ in range(num_words): + words.append(int.from_bytes(payload[off : off + 4], 'little')) + off += 4 + + class _SfrbxView: + def __init__(self, gid: int, sid: int, fid: int, body: list[int]): + self.gnss_id = Ubx.GnssType(gid) + self.sv_id = sid + self.freq_id = fid + self.body = body + + view = _SfrbxView(gnss_id, sv_id, freq_id, words) + return self._gen_rxm_sfrbx(view) + if msg_type == 0x0215: + body = Ubx.RxmRawx.from_bytes(payload) + return self._gen_rxm_rawx(body) + if msg_type == 0x0A09: + body = Ubx.MonHw.from_bytes(payload) + return self._gen_mon_hw(body) + if msg_type == 0x0A0B: + body = Ubx.MonHw2.from_bytes(payload) + return self._gen_mon_hw2(body) + if msg_type == 0x0135: + body = Ubx.NavSat.from_bytes(payload) + return self._gen_nav_sat(body) + return None + + # NAV-PVT -> gpsLocationExternal + def _gen_nav_pvt(self, msg: Ubx.NavPvt) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('gpsLocationExternal', valid=True) + gps = dat.gpsLocationExternal + gps.source = log.GpsLocationData.SensorSource.ublox + gps.flags = msg.flags + gps.hasFix = (msg.flags % 2) == 1 + gps.latitude = msg.lat * 1e-07 + gps.longitude = msg.lon * 1e-07 + gps.altitude = msg.height * 1e-03 + gps.speed = msg.g_speed * 1e-03 + gps.bearingDeg = msg.head_mot * 1e-5 + gps.horizontalAccuracy = msg.h_acc * 1e-03 + gps.satelliteCount = msg.num_sv + + # build UTC timestamp millis (NAV-PVT is in UTC) + # tolerate invalid or unset date values like C++ timegm + try: + utc_tt = calendar.timegm((msg.year, msg.month, msg.day, msg.hour, msg.min, msg.sec, 0, 0, 0)) + except Exception: + utc_tt = 0 + gps.unixTimestampMillis = int(utc_tt * 1e3 + (msg.nano * 1e-6)) + + # match C++ float32 rounding semantics exactly + gps.vNED = [ + float(np.float32(msg.vel_n) * np.float32(1e-03)), + float(np.float32(msg.vel_e) * np.float32(1e-03)), + float(np.float32(msg.vel_d) * np.float32(1e-03)), + ] + gps.verticalAccuracy = msg.v_acc * 1e-03 + gps.speedAccuracy = msg.s_acc * 1e-03 + gps.bearingAccuracyDeg = msg.head_acc * 1e-05 + return ('gpsLocationExternal', dat) + + # RXM-SFRBX dispatch to GPS or GLONASS ephemeris + def _gen_rxm_sfrbx(self, msg) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: + if msg.gnss_id == Ubx.GnssType.gps: + return self._parse_gps_ephemeris(msg) + if msg.gnss_id == Ubx.GnssType.glonass: + return self._parse_glonass_ephemeris(msg) + return None + + def _parse_gps_ephemeris(self, msg: Ubx.RxmSfrbx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: + # body is list of 10 words; convert to 30-byte subframe (strip parity/padding) + body = msg.body + if len(body) != 10: + return None + subframe_data = bytearray() + for word in body: + word >>= 6 + subframe_data.append((word >> 16) & 0xFF) + subframe_data.append((word >> 8) & 0xFF) + subframe_data.append(word & 0xFF) + + sf = Gps.from_bytes(bytes(subframe_data)) + subframe_id = sf.how.subframe_id + if subframe_id < 1 or subframe_id > 3: + return None + self.caches.gps_subframes[msg.sv_id][subframe_id] = bytes(subframe_data) + + if len(self.caches.gps_subframes[msg.sv_id]) != 3: + return None + + dat = messaging.new_message('ubloxGnss', valid=True) + eph = dat.ubloxGnss.init('ephemeris') + eph.svId = msg.sv_id + + iode_s2 = 0 + iode_s3 = 0 + iodc_lsb = 0 + week = 0 + + # Subframe 1 + sf1 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][1]) + s1 = sf1.body + assert isinstance(s1, Gps.Subframe1) + week = s1.week_no + week += 1024 + if week < 1877: + week += 1024 + eph.tgd = s1.t_gd * math.pow(2, -31) + eph.toc = s1.t_oc * math.pow(2, 4) + eph.af2 = s1.af_2 * math.pow(2, -55) + eph.af1 = s1.af_1 * math.pow(2, -43) + eph.af0 = s1.af_0 * math.pow(2, -31) + eph.svHealth = s1.sv_health + eph.towCount = sf1.how.tow_count + iodc_lsb = s1.iodc_lsb + + # Subframe 2 + sf2 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][2]) + s2 = sf2.body + assert isinstance(s2, Gps.Subframe2) + if s2.t_oe == 0 and sf2.how.tow_count * 6 >= (SECS_IN_WEEK - 2 * SECS_IN_HR): + week += 1 + eph.crs = s2.c_rs * math.pow(2, -5) + eph.deltaN = s2.delta_n * math.pow(2, -43) * self.gpsPi + eph.m0 = s2.m_0 * math.pow(2, -31) * self.gpsPi + eph.cuc = s2.c_uc * math.pow(2, -29) + eph.ecc = s2.e * math.pow(2, -33) + eph.cus = s2.c_us * math.pow(2, -29) + eph.a = math.pow(s2.sqrt_a * math.pow(2, -19), 2.0) + eph.toe = s2.t_oe * math.pow(2, 4) + iode_s2 = s2.iode + + # Subframe 3 + sf3 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][3]) + s3 = sf3.body + assert isinstance(s3, Gps.Subframe3) + eph.cic = s3.c_ic * math.pow(2, -29) + eph.omega0 = s3.omega_0 * math.pow(2, -31) * self.gpsPi + eph.cis = s3.c_is * math.pow(2, -29) + eph.i0 = s3.i_0 * math.pow(2, -31) * self.gpsPi + eph.crc = s3.c_rc * math.pow(2, -5) + eph.omega = s3.omega * math.pow(2, -31) * self.gpsPi + eph.omegaDot = s3.omega_dot * math.pow(2, -43) * self.gpsPi + eph.iode = s3.iode + eph.iDot = s3.idot * math.pow(2, -43) * self.gpsPi + iode_s3 = s3.iode + + eph.toeWeek = week + eph.tocWeek = week + + # clear cache for this SV + self.caches.gps_subframes[msg.sv_id].clear() + if not (iodc_lsb == iode_s2 == iode_s3): + return None + return ('ubloxGnss', dat) + + def _parse_glonass_ephemeris(self, msg: Ubx.RxmSfrbx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: + # words are 4 bytes each; Glonass parser expects 16 bytes (string) + body = msg.body + if len(body) != 4: + return None + string_bytes = bytearray() + for word in body: + for i in (3, 2, 1, 0): + string_bytes.append((word >> (8 * i)) & 0xFF) + + gl = Glonass.from_bytes(bytes(string_bytes)) + string_number = gl.string_number + if string_number < 1 or string_number > 5 or gl.idle_chip: + return None + + # correlate by superframe and timing, similar to C++ logic + freq_id = msg.freq_id + superframe_unknown = False + needs_clear = False + for i in range(1, 6): + if i not in self.caches.glonass_strings[freq_id]: + continue + sf_prev = self.caches.glonass_string_superframes[freq_id].get(i, 0) + if sf_prev == 0 or gl.superframe_number == 0: + superframe_unknown = True + elif sf_prev != gl.superframe_number: + needs_clear = True + if superframe_unknown: + prev_time = self.caches.glonass_string_times[freq_id].get(i, 0.0) + if abs((prev_time - 2.0 * i) - (self.framer.last_log_time - 2.0 * string_number)) > 10: + needs_clear = True + + if needs_clear: + self.caches.glonass_strings[freq_id].clear() + self.caches.glonass_string_superframes[freq_id].clear() + self.caches.glonass_string_times[freq_id].clear() + + self.caches.glonass_strings[freq_id][string_number] = bytes(string_bytes) + self.caches.glonass_string_superframes[freq_id][string_number] = gl.superframe_number + self.caches.glonass_string_times[freq_id][string_number] = self.framer.last_log_time + + if msg.sv_id == 255: + # unknown SV id + return None + if len(self.caches.glonass_strings[freq_id]) != 5: + return None + + dat = messaging.new_message('ubloxGnss', valid=True) + eph = dat.ubloxGnss.init('glonassEphemeris') + eph.svId = msg.sv_id + eph.freqNum = msg.freq_id - 7 + + current_day = 0 + tk = 0 + + # string 1 + try: + s1 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][1]).data + except Exception: + return None + assert isinstance(s1, Glonass.String1) + eph.p1 = int(s1.p1) + tk = int(s1.t_k) + eph.deprecated.tk = tk + eph.xVel = float(s1.x_vel) * math.pow(2, -20) + eph.xAccel = float(s1.x_accel) * math.pow(2, -30) + eph.x = float(s1.x) * math.pow(2, -11) + + # string 2 + try: + s2 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][2]).data + except Exception: + return None + assert isinstance(s2, Glonass.String2) + eph.svHealth = int(s2.b_n >> 2) + eph.p2 = int(s2.p2) + eph.tb = int(s2.t_b) + eph.yVel = float(s2.y_vel) * math.pow(2, -20) + eph.yAccel = float(s2.y_accel) * math.pow(2, -30) + eph.y = float(s2.y) * math.pow(2, -11) + + # string 3 + try: + s3 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][3]).data + except Exception: + return None + assert isinstance(s3, Glonass.String3) + eph.p3 = int(s3.p3) + eph.gammaN = float(s3.gamma_n) * math.pow(2, -40) + eph.svHealth = int(eph.svHealth | (1 if s3.l_n else 0)) + eph.zVel = float(s3.z_vel) * math.pow(2, -20) + eph.zAccel = float(s3.z_accel) * math.pow(2, -30) + eph.z = float(s3.z) * math.pow(2, -11) + + # string 4 + try: + s4 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][4]).data + except Exception: + return None + assert isinstance(s4, Glonass.String4) + current_day = int(s4.n_t) + eph.nt = current_day + eph.tauN = float(s4.tau_n) * math.pow(2, -30) + eph.deltaTauN = float(s4.delta_tau_n) * math.pow(2, -30) + eph.age = int(s4.e_n) + eph.p4 = int(s4.p4) + eph.svURA = float(self.glonass_URA_lookup.get(int(s4.f_t), 0.0)) + # consistency check: SV slot number + # if it doesn't match, keep going but note mismatch (no logging here) + eph.svType = int(s4.m) + + # string 5 + try: + s5 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][5]).data + except Exception: + return None + assert isinstance(s5, Glonass.String5) + eph.n4 = int(s5.n_4) + tk_seconds = int(SECS_IN_HR * ((tk >> 7) & 0x1F) + SECS_IN_MIN * ((tk >> 1) & 0x3F) + (tk & 0x1) * 30) + eph.tkSeconds = tk_seconds + + self.caches.glonass_strings[freq_id].clear() + return ('ubloxGnss', dat) + + def _gen_rxm_rawx(self, msg: Ubx.RxmRawx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('ubloxGnss', valid=True) + mr = dat.ubloxGnss.init('measurementReport') + mr.rcvTow = msg.rcv_tow + mr.gpsWeek = msg.week + mr.leapSeconds = msg.leap_s + + mb = mr.init('measurements', msg.num_meas) + for i, m in enumerate(msg.meas): + mb[i].svId = m.sv_id + mb[i].pseudorange = m.pr_mes + mb[i].carrierCycles = m.cp_mes + mb[i].doppler = m.do_mes + mb[i].gnssId = int(m.gnss_id.value) + mb[i].glonassFrequencyIndex = m.freq_id + mb[i].locktime = m.lock_time + mb[i].cno = m.cno + mb[i].pseudorangeStdev = 0.01 * (math.pow(2, (m.pr_stdev & 15))) + mb[i].carrierPhaseStdev = 0.004 * (m.cp_stdev & 15) + mb[i].dopplerStdev = 0.002 * (math.pow(2, (m.do_stdev & 15))) + + ts = mb[i].init('trackingStatus') + trk = m.trk_stat + ts.pseudorangeValid = _bit(trk, 0) + ts.carrierPhaseValid = _bit(trk, 1) + ts.halfCycleValid = _bit(trk, 2) + ts.halfCycleSubtracted = _bit(trk, 3) + + mr.numMeas = msg.num_meas + rs = mr.init('receiverStatus') + rs.leapSecValid = _bit(msg.rec_stat, 0) + rs.clkReset = _bit(msg.rec_stat, 2) + return ('ubloxGnss', dat) + + def _gen_nav_sat(self, msg: Ubx.NavSat) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('ubloxGnss', valid=True) + sr = dat.ubloxGnss.init('satReport') + sr.iTow = msg.itow + svs = sr.init('svs', msg.num_svs) + for i, s in enumerate(msg.svs): + svs[i].svId = s.sv_id + svs[i].gnssId = int(s.gnss_id.value) + svs[i].flagsBitfield = s.flags + svs[i].cno = s.cno + svs[i].elevationDeg = s.elev + svs[i].azimuthDeg = s.azim + svs[i].pseudorangeResidual = s.pr_res * 0.1 + return ('ubloxGnss', dat) + + def _gen_mon_hw(self, msg: Ubx.MonHw) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('ubloxGnss', valid=True) + hw = dat.ubloxGnss.init('hwStatus') + hw.noisePerMS = msg.noise_per_ms + hw.flags = msg.flags + hw.agcCnt = msg.agc_cnt + hw.aStatus = int(msg.a_status.value) + hw.aPower = int(msg.a_power.value) + hw.jamInd = msg.jam_ind + return ('ubloxGnss', dat) + + def _gen_mon_hw2(self, msg: Ubx.MonHw2) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('ubloxGnss', valid=True) + hw = dat.ubloxGnss.init('hwStatus2') + hw.ofsI = msg.ofs_i + hw.magI = msg.mag_i + hw.ofsQ = msg.ofs_q + hw.magQ = msg.mag_q + # Map Ubx enum to cereal enum {undefined=0, rom=1, otp=2, configpins=3, flash=4} + cfg_map = { + Ubx.MonHw2.ConfigSource.rom: 1, + Ubx.MonHw2.ConfigSource.otp: 2, + Ubx.MonHw2.ConfigSource.config_pins: 3, + Ubx.MonHw2.ConfigSource.flash: 4, + } + hw.cfgSource = cfg_map.get(msg.cfg_source, 0) + hw.lowLevCfg = msg.low_lev_cfg + hw.postStatus = msg.post_status + return ('ubloxGnss', dat) + + +def main(): + parser = UbloxMsgParser() + pm = messaging.PubMaster(['ubloxGnss', 'gpsLocationExternal']) + sock = messaging.sub_sock('ubloxRaw', timeout=100, conflate=False) + + while True: + msg = messaging.recv_one(sock) + if msg is None: + continue + + data = bytes(msg.ubloxRaw) + log_time = msg.logMonoTime * 1e-9 + frames = parser.framer.add_data(log_time, data) + for frame in frames: + try: + res = parser.parse_frame(frame) + except Exception: + continue + if not res: + continue + service, dat = res + pm.send(service, dat) + + +if __name__ == '__main__': + main() diff --git a/system/ubloxd/ubx.ksy b/system/ubloxd/ubx.ksy deleted file mode 100644 index 02c757fe71797f..00000000000000 --- a/system/ubloxd/ubx.ksy +++ /dev/null @@ -1,293 +0,0 @@ -meta: - id: ubx - endian: le -seq: - - id: magic - contents: [0xb5, 0x62] - - id: msg_type - type: u2be - - id: length - type: u2 - - id: body - type: - switch-on: msg_type - cases: - 0x0107: nav_pvt - 0x0213: rxm_sfrbx - 0x0215: rxm_rawx - 0x0a09: mon_hw - 0x0a0b: mon_hw2 - 0x0135: nav_sat -instances: - checksum: - pos: length + 6 - type: u2 - -types: - mon_hw: - seq: - - id: pin_sel - type: u4 - - id: pin_bank - type: u4 - - id: pin_dir - type: u4 - - id: pin_val - type: u4 - - id: noise_per_ms - type: u2 - - id: agc_cnt - type: u2 - - id: a_status - type: u1 - enum: antenna_status - - id: a_power - type: u1 - enum: antenna_power - - id: flags - type: u1 - - id: reserved1 - size: 1 - - id: used_mask - type: u4 - - id: vp - size: 17 - - id: jam_ind - type: u1 - - id: reserved2 - size: 2 - - id: pin_irq - type: u4 - - id: pull_h - type: u4 - - id: pull_l - type: u4 - enums: - antenna_status: - 0: init - 1: dontknow - 2: ok - 3: short - 4: open - antenna_power: - 0: off - 1: on - 2: dontknow - - mon_hw2: - seq: - - id: ofs_i - type: s1 - - id: mag_i - type: u1 - - id: ofs_q - type: s1 - - id: mag_q - type: u1 - - id: cfg_source - type: u1 - enum: config_source - - id: reserved1 - size: 3 - - id: low_lev_cfg - type: u4 - - id: reserved2 - size: 8 - - id: post_status - type: u4 - - id: reserved3 - size: 4 - - enums: - config_source: - 113: rom - 111: otp - 112: config_pins - 102: flash - - rxm_sfrbx: - seq: - - id: gnss_id - type: u1 - enum: gnss_type - - id: sv_id - type: u1 - - id: reserved1 - size: 1 - - id: freq_id - type: u1 - - id: num_words - type: u1 - - id: reserved2 - size: 1 - - id: version - type: u1 - - id: reserved3 - size: 1 - - id: body - type: u4 - repeat: expr - repeat-expr: num_words - - rxm_rawx: - seq: - - id: rcv_tow - type: f8 - - id: week - type: u2 - - id: leap_s - type: s1 - - id: num_meas - type: u1 - - id: rec_stat - type: u1 - - id: reserved1 - size: 3 - - id: meas - type: measurement - size: 32 - repeat: expr - repeat-expr: num_meas - types: - measurement: - seq: - - id: pr_mes - type: f8 - - id: cp_mes - type: f8 - - id: do_mes - type: f4 - - id: gnss_id - type: u1 - enum: gnss_type - - id: sv_id - type: u1 - - id: reserved2 - size: 1 - - id: freq_id - type: u1 - - id: lock_time - type: u2 - - id: cno - type: u1 - - id: pr_stdev - type: u1 - - id: cp_stdev - type: u1 - - id: do_stdev - type: u1 - - id: trk_stat - type: u1 - - id: reserved3 - size: 1 - nav_sat: - seq: - - id: itow - type: u4 - - id: version - type: u1 - - id: num_svs - type: u1 - - id: reserved - size: 2 - - id: svs - type: nav - size: 12 - repeat: expr - repeat-expr: num_svs - types: - nav: - seq: - - id: gnss_id - type: u1 - enum: gnss_type - - id: sv_id - type: u1 - - id: cno - type: u1 - - id: elev - type: s1 - - id: azim - type: s2 - - id: pr_res - type: s2 - - id: flags - type: u4 - - nav_pvt: - seq: - - id: i_tow - type: u4 - - id: year - type: u2 - - id: month - type: u1 - - id: day - type: u1 - - id: hour - type: u1 - - id: min - type: u1 - - id: sec - type: u1 - - id: valid - type: u1 - - id: t_acc - type: u4 - - id: nano - type: s4 - - id: fix_type - type: u1 - - id: flags - type: u1 - - id: flags2 - type: u1 - - id: num_sv - type: u1 - - id: lon - type: s4 - - id: lat - type: s4 - - id: height - type: s4 - - id: h_msl - type: s4 - - id: h_acc - type: u4 - - id: v_acc - type: u4 - - id: vel_n - type: s4 - - id: vel_e - type: s4 - - id: vel_d - type: s4 - - id: g_speed - type: s4 - - id: head_mot - type: s4 - - id: s_acc - type: s4 - - id: head_acc - type: u4 - - id: p_dop - type: u2 - - id: flags3 - type: u1 - - id: reserved1 - size: 5 - - id: head_veh - type: s4 - - id: mag_dec - type: s2 - - id: mag_acc - type: u2 -enums: - gnss_type: - 0: gps - 1: sbas - 2: galileo - 3: beidou - 4: imes - 5: qzss - 6: glonass diff --git a/system/ubloxd/ubx.py b/system/ubloxd/ubx.py new file mode 100644 index 00000000000000..857498ebf1351e --- /dev/null +++ b/system/ubloxd/ubx.py @@ -0,0 +1,180 @@ +""" +UBX protocol parser +""" + +from enum import IntEnum +from typing import Annotated + +from openpilot.system.ubloxd import binary_struct as bs + + +class GnssType(IntEnum): + gps = 0 + sbas = 1 + galileo = 2 + beidou = 3 + imes = 4 + qzss = 5 + glonass = 6 + + +class Ubx(bs.BinaryStruct): + GnssType = GnssType + + class RxmRawx(bs.BinaryStruct): + class Measurement(bs.BinaryStruct): + pr_mes: Annotated[float, bs.f64] + cp_mes: Annotated[float, bs.f64] + do_mes: Annotated[float, bs.f32] + gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] + sv_id: Annotated[int, bs.u8] + reserved2: Annotated[bytes, bs.bytes_field(1)] + freq_id: Annotated[int, bs.u8] + lock_time: Annotated[int, bs.u16] + cno: Annotated[int, bs.u8] + pr_stdev: Annotated[int, bs.u8] + cp_stdev: Annotated[int, bs.u8] + do_stdev: Annotated[int, bs.u8] + trk_stat: Annotated[int, bs.u8] + reserved3: Annotated[bytes, bs.bytes_field(1)] + + rcv_tow: Annotated[float, bs.f64] + week: Annotated[int, bs.u16] + leap_s: Annotated[int, bs.s8] + num_meas: Annotated[int, bs.u8] + rec_stat: Annotated[int, bs.u8] + reserved1: Annotated[bytes, bs.bytes_field(3)] + meas: Annotated[list[Measurement], bs.array(Measurement, count_field='num_meas')] + + class RxmSfrbx(bs.BinaryStruct): + gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] + sv_id: Annotated[int, bs.u8] + reserved1: Annotated[bytes, bs.bytes_field(1)] + freq_id: Annotated[int, bs.u8] + num_words: Annotated[int, bs.u8] + reserved2: Annotated[bytes, bs.bytes_field(1)] + version: Annotated[int, bs.u8] + reserved3: Annotated[bytes, bs.bytes_field(1)] + body: Annotated[list[int], bs.array(bs.u32, count_field='num_words')] + + class NavSat(bs.BinaryStruct): + class Nav(bs.BinaryStruct): + gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] + sv_id: Annotated[int, bs.u8] + cno: Annotated[int, bs.u8] + elev: Annotated[int, bs.s8] + azim: Annotated[int, bs.s16] + pr_res: Annotated[int, bs.s16] + flags: Annotated[int, bs.u32] + + itow: Annotated[int, bs.u32] + version: Annotated[int, bs.u8] + num_svs: Annotated[int, bs.u8] + reserved: Annotated[bytes, bs.bytes_field(2)] + svs: Annotated[list[Nav], bs.array(Nav, count_field='num_svs')] + + class NavPvt(bs.BinaryStruct): + i_tow: Annotated[int, bs.u32] + year: Annotated[int, bs.u16] + month: Annotated[int, bs.u8] + day: Annotated[int, bs.u8] + hour: Annotated[int, bs.u8] + min: Annotated[int, bs.u8] + sec: Annotated[int, bs.u8] + valid: Annotated[int, bs.u8] + t_acc: Annotated[int, bs.u32] + nano: Annotated[int, bs.s32] + fix_type: Annotated[int, bs.u8] + flags: Annotated[int, bs.u8] + flags2: Annotated[int, bs.u8] + num_sv: Annotated[int, bs.u8] + lon: Annotated[int, bs.s32] + lat: Annotated[int, bs.s32] + height: Annotated[int, bs.s32] + h_msl: Annotated[int, bs.s32] + h_acc: Annotated[int, bs.u32] + v_acc: Annotated[int, bs.u32] + vel_n: Annotated[int, bs.s32] + vel_e: Annotated[int, bs.s32] + vel_d: Annotated[int, bs.s32] + g_speed: Annotated[int, bs.s32] + head_mot: Annotated[int, bs.s32] + s_acc: Annotated[int, bs.s32] + head_acc: Annotated[int, bs.u32] + p_dop: Annotated[int, bs.u16] + flags3: Annotated[int, bs.u8] + reserved1: Annotated[bytes, bs.bytes_field(5)] + head_veh: Annotated[int, bs.s32] + mag_dec: Annotated[int, bs.s16] + mag_acc: Annotated[int, bs.u16] + + class MonHw2(bs.BinaryStruct): + class ConfigSource(IntEnum): + flash = 102 + otp = 111 + config_pins = 112 + rom = 113 + + ofs_i: Annotated[int, bs.s8] + mag_i: Annotated[int, bs.u8] + ofs_q: Annotated[int, bs.s8] + mag_q: Annotated[int, bs.u8] + cfg_source: Annotated[ConfigSource | int, bs.enum(bs.u8, ConfigSource)] + reserved1: Annotated[bytes, bs.bytes_field(3)] + low_lev_cfg: Annotated[int, bs.u32] + reserved2: Annotated[bytes, bs.bytes_field(8)] + post_status: Annotated[int, bs.u32] + reserved3: Annotated[bytes, bs.bytes_field(4)] + + class MonHw(bs.BinaryStruct): + class AntennaStatus(IntEnum): + init = 0 + dontknow = 1 + ok = 2 + short = 3 + open = 4 + + class AntennaPower(IntEnum): + false = 0 + true = 1 + dontknow = 2 + + pin_sel: Annotated[int, bs.u32] + pin_bank: Annotated[int, bs.u32] + pin_dir: Annotated[int, bs.u32] + pin_val: Annotated[int, bs.u32] + noise_per_ms: Annotated[int, bs.u16] + agc_cnt: Annotated[int, bs.u16] + a_status: Annotated[AntennaStatus | int, bs.enum(bs.u8, AntennaStatus)] + a_power: Annotated[AntennaPower | int, bs.enum(bs.u8, AntennaPower)] + flags: Annotated[int, bs.u8] + reserved1: Annotated[bytes, bs.bytes_field(1)] + used_mask: Annotated[int, bs.u32] + vp: Annotated[bytes, bs.bytes_field(17)] + jam_ind: Annotated[int, bs.u8] + reserved2: Annotated[bytes, bs.bytes_field(2)] + pin_irq: Annotated[int, bs.u32] + pull_h: Annotated[int, bs.u32] + pull_l: Annotated[int, bs.u32] + + magic: Annotated[bytes, bs.const(bs.bytes_field(2), b"\xb5\x62")] + msg_type: Annotated[int, bs.u16be] + length: Annotated[int, bs.u16] + body: Annotated[ + object, + bs.substream( + 'length', + bs.switch( + 'msg_type', + { + 0x0107: NavPvt, + 0x0213: RxmSfrbx, + 0x0215: RxmRawx, + 0x0A09: MonHw, + 0x0A0B: MonHw2, + 0x0135: NavSat, + }, + ), + ), + ] + checksum: Annotated[int, bs.u16] diff --git a/system/ugpsd.py b/system/ugpsd.py deleted file mode 100755 index 34b20b01c80188..00000000000000 --- a/system/ugpsd.py +++ /dev/null @@ -1,165 +0,0 @@ -#!/usr/bin/env python3 -import os -import time -import traceback -import serial -import datetime -import numpy as np -from collections import defaultdict - -from cereal import log -import cereal.messaging as messaging -from openpilot.common.retry import retry -from openpilot.common.swaglog import cloudlog -from openpilot.system.qcomgpsd.qcomgpsd import at_cmd, wait_for_modem - - -def sfloat(n: str): - return float(n) if len(n) > 0 else 0 - -def checksum(s: str): - ret = 0 - for c in s[1:-3]: - ret ^= ord(c) - return format(ret, '02X') - -class Unicore: - def __init__(self): - self.s = serial.Serial('/dev/ttyHS0', 115200) - self.s.timeout = 1 - self.s.writeTimeout = 1 - self.s.newline = b'\r\n' - - self.s.flush() - self.s.reset_input_buffer() - self.s.reset_output_buffer() - self.s.read(2048) - - def send(self, cmd): - self.s.write(cmd.encode('utf8') + b'\r') - resp = self.s.read(2048) - print(len(resp), cmd, "\n", resp) - assert b"OK" in resp - - def recv(self): - return self.s.readline() - -def build_msg(state): - """ - NMEA sentences: - https://campar.in.tum.de/twiki/pub/Chair/NaviGpsDemon/nmea.html#RMC - NAV messages: - https://www.unicorecomm.com/assets/upload/file/UFirebird_Standard_Positioning_Products_Protocol_Specification_CH.pdf - """ - - msg = messaging.new_message('gpsLocation', valid=True) - gps = msg.gpsLocation - - gnrmc = state['$GNRMC'] - gps.hasFix = gnrmc[1] == 'A' - gps.source = log.GpsLocationData.SensorSource.unicore - gps.latitude = (sfloat(gnrmc[3][:2]) + (sfloat(gnrmc[3][2:]) / 60)) * (1 if gnrmc[4] == "N" else -1) - gps.longitude = (sfloat(gnrmc[5][:3]) + (sfloat(gnrmc[5][3:]) / 60)) * (1 if gnrmc[6] == "E" else -1) - - try: - date = gnrmc[9][:6] - dt = datetime.datetime.strptime(f"{date} {gnrmc[1]}", '%d%m%y %H%M%S.%f') - gps.unixTimestampMillis = dt.timestamp()*1e3 - except Exception: - pass - - gps.bearingDeg = sfloat(gnrmc[8]) - - if len(state['$GNGGA']): - gngga = state['$GNGGA'] - if gngga[10] == 'M': - gps.altitude = sfloat(gngga[9]) - - if len(state['$GNGSA']): - gngsa = state['$GNGSA'] - gps.horizontalAccuracy = sfloat(gngsa[4]) - gps.verticalAccuracy = sfloat(gngsa[5]) - - #if len(state['$NAVACC']): - # # $NAVVEL,264415000,5,3,0.375,0.141,-0.735,-65.450*2A - # navacc = state['$NAVACC'] - # gps.horizontalAccuracy = sfloat(navacc[3]) - # gps.speedAccuracy = sfloat(navacc[4]) - # gps.bearingAccuracyDeg = sfloat(navacc[5]) - - if len(state['$NAVVEL']): - # $NAVVEL,264415000,5,3,0.375,0.141,-0.735,-65.450*2A - navvel = state['$NAVVEL'] - vECEF = [ - sfloat(navvel[4]), - sfloat(navvel[5]), - sfloat(navvel[6]), - ] - - lat = np.radians(gps.latitude) - lon = np.radians(gps.longitude) - R = np.array([ - [-np.sin(lat) * np.cos(lon), -np.sin(lon), -np.cos(lat) * np.cos(lon)], - [-np.sin(lat) * np.sin(lon), np.cos(lon), -np.cos(lat) * np.sin(lon)], - [np.cos(lat), 0, -np.sin(lat)] - ]) - - vNED = [float(x) for x in R.dot(vECEF)] - gps.vNED = vNED - gps.speed = np.linalg.norm(vNED) - - # TODO: set these from the module - gps.bearingAccuracyDeg = 5. - gps.speedAccuracy = 3. - - return msg - - -@retry(attempts=10, delay=0.1) -def setup(u): - at_cmd('AT+CGPS=0') - at_cmd('AT+CGPS=1') - time.sleep(1.0) - - # setup NAVXXX outputs - for i in range(4): - u.send(f"$CFGMSG,1,{i},1") - for i in (1, 3): - u.send(f"$CFGMSG,3,{i},1") - - # 10Hz NAV outputs - u.send("$CFGNAV,100,100,1000") - - -def main(): - wait_for_modem("AT+CGPS?") - - u = Unicore() - setup(u) - - state = defaultdict(list) - pm = messaging.PubMaster(['gpsLocation']) - while True: - try: - msg = u.recv().decode('utf8').strip() - if "DEBUG" in os.environ: - print(repr(msg)) - - if len(msg) > 0: - if checksum(msg) != msg.split('*')[1]: - cloudlog.error(f"invalid checksum: {repr(msg)}") - continue - - k = msg.split(',')[0] - state[k] = msg.split(',') - if '$GNRMC' not in msg: - continue - - pm.send('gpsLocation', build_msg(state)) - except Exception: - traceback.print_exc() - cloudlog.exception("gps.issue") - - -if __name__ == "__main__": - main() diff --git a/system/ui/README.md b/system/ui/README.md new file mode 100644 index 00000000000000..79a4dd32ea9240 --- /dev/null +++ b/system/ui/README.md @@ -0,0 +1,20 @@ +# ui + +The user interfaces here are built with [raylib](https://www.raylib.com/). + +Quick start: +* set `BIG=1` to run the comma 3X UI (comma four UI runs by default) +* set `SHOW_FPS=1` to show the FPS +* set `STRICT_MODE=1` to kill the app if it drops too much below 60fps +* set `SCALE=1.5` to scale the entire UI by 1.5x +* set `BURN_IN=1` to get a burn-in heatmap version of the UI +* set `GRID=50` to show a 50-pixel alignment grid overlay +* set `MAGIC_DEBUG=1` to show every dropped frames (only on device) +* set `RECORD=1` to record the screen, output defaults to `output.mp4` but can be set with `RECORD_OUTPUT` +* https://www.raylib.com/cheatsheet/cheatsheet.html +* https://electronstudio.github.io/raylib-python-cffi/README.html#quickstart + +Style guide: +* All graphical elements should subclass [`Widget`](/system/ui/widgets/__init__.py). + * Prefer a stateful widget over a function for easy migration from QT +* All internal class variables and functions should be prefixed with `_` diff --git a/system/ui/lib/__init__.py b/system/ui/lib/__init__.py new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/system/ui/lib/application.py b/system/ui/lib/application.py new file mode 100644 index 00000000000000..2513086edddf79 --- /dev/null +++ b/system/ui/lib/application.py @@ -0,0 +1,865 @@ +import atexit +import cffi +import math +import os +import queue +import time +import signal +import sys +import pyray as rl +import threading +import platform +import subprocess +from contextlib import contextmanager +from collections.abc import Callable +from collections import deque +from enum import StrEnum +from pathlib import Path +from typing import NamedTuple +from importlib.resources import as_file, files +from openpilot.common.swaglog import cloudlog +from openpilot.system.hardware import HARDWARE, PC +from openpilot.system.ui.lib.multilang import multilang +from openpilot.common.realtime import Ratekeeper + +_DEFAULT_FPS = int(os.getenv("FPS", {'tizi': 20}.get(HARDWARE.get_device_type(), 60))) +FPS_LOG_INTERVAL = 5 # Seconds between logging FPS drops +FPS_DROP_THRESHOLD = 0.9 # FPS drop threshold for triggering a warning +FPS_CRITICAL_THRESHOLD = 0.5 # Critical threshold for triggering strict actions +MOUSE_THREAD_RATE = 140 # touch controller runs at 140Hz +MAX_TOUCH_SLOTS = 2 +TOUCH_HISTORY_TIMEOUT = 3.0 # Seconds before touch points fade out + +BIG_UI = os.getenv("BIG", "0") == "1" +ENABLE_VSYNC = os.getenv("ENABLE_VSYNC", "0") == "1" +SHOW_FPS = os.getenv("SHOW_FPS") == "1" +SHOW_TOUCHES = os.getenv("SHOW_TOUCHES") == "1" +STRICT_MODE = os.getenv("STRICT_MODE") == "1" +SCALE = float(os.getenv("SCALE", "1.0")) +GRID_SIZE = int(os.getenv("GRID", "0")) +PROFILE_RENDER = int(os.getenv("PROFILE_RENDER", "0")) +PROFILE_STATS = int(os.getenv("PROFILE_STATS", "100")) # Number of functions to show in profile output +RECORD = os.getenv("RECORD") == "1" +RECORD_OUTPUT = str(Path(os.getenv("RECORD_OUTPUT", "output")).with_suffix(".mp4")) +RECORD_QUALITY = int(os.getenv("RECORD_QUALITY", "23")) # Dynamic bitrate quality level (CRF); 0 is lossless (bigger size), max is 51, default is 23 for x264 +RECORD_BITRATE = os.getenv("RECORD_BITRATE", "") # Target bitrate e.g. "2000k" (overrides RECORD_QUALITY when set) +RECORD_SPEED = int(os.getenv("RECORD_SPEED", "1")) # Speed multiplier +OFFSCREEN = os.getenv("OFFSCREEN") == "1" # Disable FPS limiting for fast offline rendering + +GL_VERSION = """ +#version 300 es +precision highp float; +""" +if platform.system() == "Darwin": + GL_VERSION = """ + #version 330 core + """ + +BURN_IN_MODE = "BURN_IN" in os.environ +BURN_IN_VERTEX_SHADER = GL_VERSION + """ +in vec3 vertexPosition; +in vec2 vertexTexCoord; +uniform mat4 mvp; +out vec2 fragTexCoord; +void main() { + fragTexCoord = vertexTexCoord; + gl_Position = mvp * vec4(vertexPosition, 1.0); +} +""" +BURN_IN_FRAGMENT_SHADER = GL_VERSION + """ +in vec2 fragTexCoord; +uniform sampler2D texture0; +out vec4 fragColor; +void main() { + vec4 sampled = texture(texture0, fragTexCoord); + float intensity = sampled.b; + // Map blue intensity to green -> yellow -> red to highlight burn-in risk. + vec3 start = vec3(0.0, 1.0, 0.0); + vec3 middle = vec3(1.0, 1.0, 0.0); + vec3 end = vec3(1.0, 0.0, 0.0); + vec3 gradient = mix(start, middle, clamp(intensity * 2.0, 0.0, 1.0)); + gradient = mix(gradient, end, clamp((intensity - 0.5) * 2.0, 0.0, 1.0)); + fragColor = vec4(gradient, sampled.a); +} +""" + +DEFAULT_TEXT_SIZE = 60 +DEFAULT_TEXT_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) + +# Qt draws fonts accounting for ascent/descent differently, so compensate to match old styles +# The real scales for the fonts below range from 1.212 to 1.266 +FONT_SCALE = 1.242 if BIG_UI else 1.16 + +ASSETS_DIR = files("openpilot.selfdrive").joinpath("assets") +FONT_DIR = ASSETS_DIR.joinpath("fonts") + + +class FontWeight(StrEnum): + NORMAL = "Inter-Regular.fnt" if BIG_UI else "Inter-Medium.fnt" + MEDIUM = "Inter-Medium.fnt" + BOLD = "Inter-Bold.fnt" + SEMI_BOLD = "Inter-SemiBold.fnt" + UNIFONT = "unifont.fnt" + + # Small UI fonts + DISPLAY_REGULAR = "Inter-Regular.fnt" + ROMAN = "Inter-Regular.fnt" + DISPLAY = "Inter-Bold.fnt" + + +def font_fallback(font: rl.Font) -> rl.Font: + """Fall back to unifont for languages that require it.""" + if multilang.requires_unifont(): + return gui_app.font(FontWeight.UNIFONT) + return font + + +class MousePos(NamedTuple): + x: float + y: float + + +class MousePosWithTime(NamedTuple): + x: float + y: float + t: float + + +class MouseEvent(NamedTuple): + pos: MousePos + slot: int + left_pressed: bool + left_released: bool + left_down: bool + t: float + + +class MouseState: + def __init__(self, scale: float = 1.0): + self._scale = scale + self._events: deque[MouseEvent] = deque(maxlen=MOUSE_THREAD_RATE) # bound event list + self._prev_mouse_event: list[MouseEvent | None] = [None] * MAX_TOUCH_SLOTS + + self._rk = Ratekeeper(MOUSE_THREAD_RATE, print_delay_threshold=None) + self._lock = threading.Lock() + self._exit_event = threading.Event() + self._thread = None + + def get_events(self) -> list[MouseEvent]: + with self._lock: + events = list(self._events) + self._events.clear() + return events + + def start(self): + self._exit_event.clear() + if self._thread is None or not self._thread.is_alive(): + self._thread = threading.Thread(target=self._run_thread, daemon=True) + self._thread.start() + + def stop(self): + self._exit_event.set() + if self._thread is not None and self._thread.is_alive(): + self._thread.join() + + def _run_thread(self): + while not self._exit_event.is_set(): + rl.poll_input_events() + self._handle_mouse_event() + self._rk.keep_time() + + def _handle_mouse_event(self): + # TODO: read touch events from evdev directly to get real kernel timestamps. + # Polling at 140Hz with time.monotonic() causes timing jitter that makes scroll + # velocity oscillate (alternating high/low). Real timestamps would also let us + # detect swipe-stop-lift via event gaps instead of the fragile decel heuristic. + for slot in range(MAX_TOUCH_SLOTS): + mouse_pos = rl.get_touch_position(slot) + x = mouse_pos.x / self._scale if self._scale != 1.0 else mouse_pos.x + y = mouse_pos.y / self._scale if self._scale != 1.0 else mouse_pos.y + ev = MouseEvent( + MousePos(x, y), + slot, + rl.is_mouse_button_pressed(slot), # noqa: TID251 + rl.is_mouse_button_released(slot), # noqa: TID251 + rl.is_mouse_button_down(slot), + time.monotonic(), + ) + # Only add changes + prev = self._prev_mouse_event[slot] + if prev is None or ev[:-1] != prev[:-1]: + with self._lock: + self._events.append(ev) + self._prev_mouse_event[slot] = ev + + +class GuiApplication: + def __init__(self, width: int | None = None, height: int | None = None): + self._set_log_callback() + + self._fonts: dict[FontWeight, rl.Font] = {} + self._width = width if width is not None else GuiApplication._default_width() + self._height = height if height is not None else GuiApplication._default_height() + + if PC and os.getenv("SCALE") is None: + self._scale = self._calculate_auto_scale() + else: + self._scale = SCALE + + # Scale, then ensure dimensions are even + self._scaled_width = int(self._width * self._scale) + self._scaled_height = int(self._height * self._scale) + self._scaled_width += self._scaled_width % 2 + self._scaled_height += self._scaled_height % 2 + + self._render_texture: rl.RenderTexture | None = None + self._burn_in_shader: rl.Shader | None = None + self._ffmpeg_proc: subprocess.Popen | None = None + self._ffmpeg_queue: queue.Queue | None = None + self._ffmpeg_thread: threading.Thread | None = None + self._ffmpeg_stop_event: threading.Event | None = None + self._textures: dict[str, rl.Texture] = {} + self._target_fps: int = _DEFAULT_FPS + self._last_fps_log_time: float = time.monotonic() + self._frame = 0 + self._window_close_requested = False + self._nav_stack: list[object] = [] + self._nav_stack_ticks: list[Callable[[], None]] = [] + self._nav_stack_widgets_to_render = 1 if self.big_ui() else 2 + + self._mouse = MouseState(self._scale) + self._mouse_events: list[MouseEvent] = [] + self._last_mouse_event: MouseEvent = MouseEvent(MousePos(0, 0), 0, False, False, False, 0.0) + + self._should_render = True + + # Debug variables + self._mouse_history: deque[MousePosWithTime] = deque(maxlen=MOUSE_THREAD_RATE) + self._show_touches = SHOW_TOUCHES + self._show_fps = SHOW_FPS + self._grid_size = GRID_SIZE + self._profile_render_frames = PROFILE_RENDER + self._render_profiler = None + self._render_profile_start_time = None + + @property + def frame(self): + return self._frame + + def set_show_touches(self, show: bool): + self._show_touches = show + + def set_show_fps(self, show: bool): + self._show_fps = show + + @property + def show_touches(self) -> bool: + return self._show_touches + + @property + def target_fps(self): + return self._target_fps + + def request_close(self): + self._window_close_requested = True + + def init_window(self, title: str, fps: int = _DEFAULT_FPS): + with self._startup_profile_context(): + def _close(sig, frame): + self.close() + sys.exit(0) + signal.signal(signal.SIGINT, _close) + atexit.register(self.close) + + flags = rl.ConfigFlags.FLAG_MSAA_4X_HINT + if ENABLE_VSYNC: + flags |= rl.ConfigFlags.FLAG_VSYNC_HINT + rl.set_config_flags(flags) + + rl.init_window(self._scaled_width, self._scaled_height, title) + + needs_render_texture = self._scale != 1.0 or BURN_IN_MODE or RECORD + if self._scale != 1.0: + rl.set_mouse_scale(1 / self._scale, 1 / self._scale) + if needs_render_texture: + self._render_texture = rl.load_render_texture(self._scaled_width, self._scaled_height) + rl.set_texture_filter(self._render_texture.texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR) + + if RECORD: + output_fps = fps * RECORD_SPEED + ffmpeg_args = [ + 'ffmpeg', + '-v', 'warning', # Reduce ffmpeg log spam + '-nostats', # Suppress encoding progress + '-f', 'rawvideo', # Input format + '-pix_fmt', 'rgba', # Input pixel format + '-s', f'{self._scaled_width}x{self._scaled_height}', # Input resolution + '-r', str(fps), # Input frame rate + '-i', 'pipe:0', # Input from stdin + '-vf', 'vflip,format=yuv420p', # Flip vertically and convert to yuv420p + '-r', str(output_fps), # Output frame rate (for speed multiplier) + '-c:v', 'libx264', + '-preset', 'veryfast', + '-crf', str(RECORD_QUALITY) + ] + if RECORD_BITRATE: + # NOTE: custom bitrate overrides crf setting + ffmpeg_args += ['-b:v', RECORD_BITRATE, '-maxrate', RECORD_BITRATE, '-bufsize', RECORD_BITRATE] + ffmpeg_args += [ + '-y', # Overwrite existing file + '-f', 'mp4', # Output format + RECORD_OUTPUT, # Output file path + ] + self._ffmpeg_proc = subprocess.Popen(ffmpeg_args, stdin=subprocess.PIPE) + self._ffmpeg_queue = queue.Queue(maxsize=60) # Buffer up to 60 frames + self._ffmpeg_stop_event = threading.Event() + self._ffmpeg_thread = threading.Thread(target=self._ffmpeg_writer_thread, daemon=True) + self._ffmpeg_thread.start() + + # four display runs slightly faster than 60 FPS, let it dictate rate so we don't drift and drop frames + vblank_control = HARDWARE.get_device_type() == 'mici' + rl.set_target_fps(0 if OFFSCREEN or vblank_control else fps) + + self._target_fps = fps + self._set_styles() + self._load_fonts() + self._patch_text_functions() + self._patch_scissor_mode() + if BURN_IN_MODE and self._burn_in_shader is None: + self._burn_in_shader = rl.load_shader_from_memory(BURN_IN_VERTEX_SHADER, BURN_IN_FRAGMENT_SHADER) + + if not PC: + self._mouse.start() + + @contextmanager + def _startup_profile_context(self): + if "PROFILE_STARTUP" not in os.environ: + yield + return + + import cProfile + import io + import pstats + + profiler = cProfile.Profile() + start_time = time.monotonic() + profiler.enable() + + # do the init + yield + + profiler.disable() + elapsed_ms = (time.monotonic() - start_time) * 1e3 + + stats_stream = io.StringIO() + pstats.Stats(profiler, stream=stats_stream).sort_stats("cumtime").print_stats(25) + print("\n=== Startup profile ===") + print(stats_stream.getvalue().rstrip()) + + green = "\033[92m" + reset = "\033[0m" + print(f"{green}UI window ready in {elapsed_ms:.1f} ms{reset}") + sys.exit(0) + + def _ffmpeg_writer_thread(self): + """Background thread that writes frames to ffmpeg.""" + while True: + try: + data = self._ffmpeg_queue.get(timeout=1.0) + if data is None: # Sentinel to stop + break + self._ffmpeg_proc.stdin.write(data) + except queue.Empty: + if self._ffmpeg_stop_event.is_set(): + break + continue + except Exception: + break + + def push_widget(self, widget: object): + if widget in self._nav_stack: + cloudlog.warning("Widget already in stack, cannot push again!") + return + + # disable previous widget to prevent input processing + if len(self._nav_stack) > 0: + prev_widget = self._nav_stack[-1] + # TODO: change these to touch_valid + prev_widget.set_enabled(False) + + self._nav_stack.append(widget) + widget.show_event() + widget.set_enabled(True) + + def pop_widget(self, idx: int | None = None): + # Pops widget instantly without animation + if len(self._nav_stack) < 2: + cloudlog.warning("At least one widget should remain on the stack, ignoring pop!") + return + + idx_to_pop = len(self._nav_stack) - 1 if idx is None else idx + if idx_to_pop <= 0 or idx_to_pop >= len(self._nav_stack): + cloudlog.warning(f"Invalid index {idx_to_pop} to pop, ignoring!") + return + + # only re-enable previous widget if popping top widget + if idx_to_pop == len(self._nav_stack) - 1: + prev_widget = self._nav_stack[idx_to_pop - 1] + prev_widget.set_enabled(True) + + widget = self._nav_stack.pop(idx_to_pop) + widget.hide_event() + + def pop_widgets_to(self, widget: object, callback: Callable[[], None] | None = None, instant: bool = False): + # Pops middle widgets instantly without animation then dismisses top, animated out if NavWidget + if widget not in self._nav_stack: + cloudlog.warning("Widget not in stack, cannot pop to it!") + return + + # Nothing to pop, ensure we still run callback + top_widget = self._nav_stack[-1] + if top_widget == widget: + if callback: + callback() + return + + # instantly pop widgets in between, then dismiss top widget for animation + while len(self._nav_stack) > 1 and self._nav_stack[-2] != widget: + self.pop_widget(len(self._nav_stack) - 2) + + if not instant: + top_widget.dismiss(callback) + else: + self.pop_widget() + + def get_active_widget(self): + if len(self._nav_stack) > 0: + return self._nav_stack[-1] + return None + + def widget_in_stack(self, widget: object) -> bool: + return widget in self._nav_stack + + def add_nav_stack_tick(self, tick_function: Callable[[], None]): + if tick_function not in self._nav_stack_ticks: + self._nav_stack_ticks.append(tick_function) + + def remove_nav_stack_tick(self, tick_function: Callable[[], None]): + if tick_function in self._nav_stack_ticks: + self._nav_stack_ticks.remove(tick_function) + + def set_should_render(self, should_render: bool): + self._should_render = should_render + + def texture(self, asset_path: str, width: int | None = None, height: int | None = None, + alpha_premultiply=False, keep_aspect_ratio=True, flip_x: bool = False) -> rl.Texture: + if width is not None: + width = round(width) + if height is not None: + height = round(height) + + cache_key = f"{asset_path}_{width}_{height}_{alpha_premultiply}_{keep_aspect_ratio}_{flip_x}" + if cache_key in self._textures: + return self._textures[cache_key] + + with as_file(ASSETS_DIR.joinpath(asset_path)) as fspath: + image_obj = self._load_image_from_path(fspath.as_posix(), width, height, alpha_premultiply, keep_aspect_ratio, flip_x) + texture_obj = self._load_texture_from_image(image_obj) + + # Set logical size so widget layout math stays at 1x coordinates + if self._scale != 1.0 and width is not None and height is not None: + texture_obj.width = width + texture_obj.height = height + + self._textures[cache_key] = texture_obj + return texture_obj + + def _load_image_from_path(self, image_path: str, width: int | None = None, height: int | None = None, + alpha_premultiply: bool = False, keep_aspect_ratio: bool = True, flip_x: bool = False) -> rl.Image: + """Load and resize an image, storing it for later automatic unloading.""" + image = rl.load_image(image_path) + + if alpha_premultiply: + rl.image_alpha_premultiply(image) + + # Scale up load size for sharper rendering, capped at source resolution + if self._scale != 1.0 and width is not None and height is not None: + width = min(int(width * self._scale), image.width) + height = min(int(height * self._scale), image.height) + + if width is not None and height is not None: + same_dimensions = image.width == width and image.height == height + + # Resize with aspect ratio preservation if requested + if not same_dimensions: + if keep_aspect_ratio: + orig_width = image.width + orig_height = image.height + + scale_width = width / orig_width + scale_height = height / orig_height + + # Calculate new dimensions + scale = min(scale_width, scale_height) + new_width = int(orig_width * scale) + new_height = int(orig_height * scale) + + rl.image_resize(image, new_width, new_height) + else: + rl.image_resize(image, width, height) + else: + assert keep_aspect_ratio, "Cannot resize without specifying width and height" + + if flip_x: + rl.image_flip_horizontal(image) + + return image + + def _load_texture_from_image(self, image: rl.Image) -> rl.Texture: + """Send image to GPU and unload original image.""" + texture = rl.load_texture_from_image(image) + # Set texture filtering to smooth the result + rl.set_texture_filter(texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR) + # prevent artifacts from wrapping coordinates + rl.set_texture_wrap(texture, rl.TextureWrap.TEXTURE_WRAP_CLAMP) + + rl.unload_image(image) + return texture + + def close_ffmpeg(self): + if self._ffmpeg_thread is not None: + # Signal thread to stop, send sentinel, then wait for it to drain + self._ffmpeg_stop_event.set() + self._ffmpeg_queue.put(None) + self._ffmpeg_thread.join(timeout=30) + + if self._ffmpeg_proc is not None: + self._ffmpeg_proc.stdin.flush() + self._ffmpeg_proc.stdin.close() + try: + self._ffmpeg_proc.wait(timeout=30) + except subprocess.TimeoutExpired: + self._ffmpeg_proc.terminate() + self._ffmpeg_proc.wait() + + def close(self): + if not rl.is_window_ready(): + return + + for texture in self._textures.values(): + rl.unload_texture(texture) + self._textures = {} + + for font in self._fonts.values(): + rl.unload_font(font) + self._fonts = {} + + if self._render_texture is not None: + rl.unload_render_texture(self._render_texture) + self._render_texture = None + + if self._burn_in_shader: + rl.unload_shader(self._burn_in_shader) + self._burn_in_shader = None + + if not PC: + self._mouse.stop() + + self.close_ffmpeg() + + rl.close_window() + + @property + def mouse_events(self) -> list[MouseEvent]: + return self._mouse_events + + @property + def last_mouse_event(self) -> MouseEvent: + return self._last_mouse_event + + def render(self): + try: + if self._profile_render_frames > 0: + import cProfile + self._render_profiler = cProfile.Profile() + self._render_profile_start_time = time.monotonic() + self._render_profiler.enable() + + while not (self._window_close_requested or rl.window_should_close()): + frame_start = time.monotonic() + + if PC: + # Thread is not used on PC, need to manually add mouse events + self._mouse._handle_mouse_event() + + # Store all mouse events for the current frame + self._mouse_events = self._mouse.get_events() + if len(self._mouse_events) > 0: + self._last_mouse_event = self._mouse_events[-1] + + # Skip rendering when screen is off + if not self._should_render: + if PC: + rl.poll_input_events() + time.sleep(1 / self._target_fps) + yield False, 0.0, 0.0 + continue + + if self._render_texture: + rl.begin_texture_mode(self._render_texture) + rl.clear_background(rl.BLACK) + else: + rl.begin_drawing() + rl.clear_background(rl.BLACK) + + if self._scale != 1.0: + rl.rl_push_matrix() + rl.rl_scalef(self._scale, self._scale, 1.0) + + # Allow a Widget to still run a function regardless of the stack depth + for tick in self._nav_stack_ticks: + tick() + + # Only render top widgets + for widget in self._nav_stack[-self._nav_stack_widgets_to_render:]: + widget.render(rl.Rectangle(0, 0, self.width, self.height)) + + frame_time = rl.get_frame_time() + cpu_time = time.monotonic() - frame_start + yield True, frame_time, cpu_time + + if self._scale != 1.0: + rl.rl_pop_matrix() + + if self._render_texture: + rl.end_texture_mode() + rl.begin_drawing() + rl.clear_background(rl.BLACK) + src_rect = rl.Rectangle(0, 0, float(self._scaled_width), -float(self._scaled_height)) + dst_rect = rl.Rectangle(0, 0, float(self._scaled_width), float(self._scaled_height)) + texture = self._render_texture.texture + if texture: + if BURN_IN_MODE and self._burn_in_shader: + rl.begin_shader_mode(self._burn_in_shader) + rl.draw_texture_pro(texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + else: + rl.draw_texture_pro(texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + + if self._show_fps: + rl.draw_fps(10, 10) + + if self._show_touches: + self._draw_touch_points() + + if self._grid_size > 0: + self._draw_grid() + + rl.end_drawing() + + if RECORD: + image = rl.load_image_from_texture(self._render_texture.texture) + data_size = image.width * image.height * 4 + data = bytes(rl.ffi.buffer(image.data, data_size)) + self._ffmpeg_queue.put(data) # Async write via background thread + rl.unload_image(image) + + self._monitor_fps() + self._frame += 1 + + if self._profile_render_frames > 0 and self._frame >= self._profile_render_frames: + self._output_render_profile() + except KeyboardInterrupt: + pass + + def font(self, font_weight: FontWeight = FontWeight.NORMAL) -> rl.Font: + return self._fonts[font_weight] + + @property + def width(self): + return self._width + + @property + def height(self): + return self._height + + def _load_fonts(self): + for font_weight_file in FontWeight: + with as_file(FONT_DIR) as fspath: + fnt_path = fspath / font_weight_file + font = rl.load_font(fnt_path.as_posix()) + if font_weight_file != FontWeight.UNIFONT: + rl.gen_texture_mipmaps(font.texture) + rl.set_texture_filter(font.texture, rl.TextureFilter.TEXTURE_FILTER_TRILINEAR) + self._fonts[font_weight_file] = font + rl.gui_set_font(self._fonts[FontWeight.NORMAL]) + + def _set_styles(self): + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.BORDER_WIDTH, 0) + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_SIZE, DEFAULT_TEXT_SIZE) + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.BACKGROUND_COLOR, rl.color_to_int(rl.BLACK)) + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_COLOR_NORMAL, rl.color_to_int(DEFAULT_TEXT_COLOR)) + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.BASE_COLOR_NORMAL, rl.color_to_int(rl.Color(50, 50, 50, 255))) + + def _patch_text_functions(self): + # Wrap pyray text APIs to apply a global text size scale so our px sizes match Qt + if not hasattr(rl, "_orig_draw_text_ex"): + rl._orig_draw_text_ex = rl.draw_text_ex + + def _draw_text_ex_scaled(font, text, position, font_size, spacing, tint): + font = font_fallback(font) + return rl._orig_draw_text_ex(font, text, position, font_size * FONT_SCALE, spacing, tint) + + rl.draw_text_ex = _draw_text_ex_scaled + + def _patch_scissor_mode(self): + if self._scale == 1.0: + return + + if not hasattr(rl, "_orig_begin_scissor_mode"): + rl._orig_begin_scissor_mode = rl.begin_scissor_mode + + def _begin_scissor_mode_scaled(x, y, width, height): + return rl._orig_begin_scissor_mode( + int(x * self._scale), int(y * self._scale), + int(math.ceil(width * self._scale)), int(math.ceil(height * self._scale))) + + rl.begin_scissor_mode = _begin_scissor_mode_scaled + + def _set_log_callback(self): + ffi_libc = cffi.FFI() + ffi_libc.cdef(""" + int vasprintf(char **strp, const char *fmt, void *ap); + void free(void *ptr); + """) + libc = ffi_libc.dlopen(None) + + @rl.ffi.callback("void(int, char *, void *)") + def trace_log_callback(log_level, text, args): + try: + text_addr = int(rl.ffi.cast("uintptr_t", text)) + args_addr = int(rl.ffi.cast("uintptr_t", args)) + text_libc = ffi_libc.cast("char *", text_addr) + args_libc = ffi_libc.cast("void *", args_addr) + + out = ffi_libc.new("char **") + if libc.vasprintf(out, text_libc, args_libc) >= 0 and out[0] != ffi_libc.NULL: + text_str = ffi_libc.string(out[0]).decode("utf-8", "replace") + libc.free(out[0]) + else: + text_str = rl.ffi.string(text).decode("utf-8", "replace") + except Exception as e: + text_str = f"[Log decode error: {e}]" + + if log_level == rl.TraceLogLevel.LOG_ERROR: + cloudlog.error(f"raylib: {text_str}") + elif log_level == rl.TraceLogLevel.LOG_WARNING: + cloudlog.warning(f"raylib: {text_str}") + elif log_level == rl.TraceLogLevel.LOG_INFO: + cloudlog.info(f"raylib: {text_str}") + elif log_level == rl.TraceLogLevel.LOG_DEBUG: + cloudlog.debug(f"raylib: {text_str}") + else: + cloudlog.error(f"raylib: Unknown level {log_level}: {text_str}") + + # ensure we get all the logs forwarded to us + rl.set_trace_log_level(rl.TraceLogLevel.LOG_DEBUG) + + # Store callback reference + self._trace_log_callback = trace_log_callback + rl.set_trace_log_callback(self._trace_log_callback) + + def _monitor_fps(self): + fps = rl.get_fps() + + # Log FPS drop below threshold at regular intervals + if fps < self._target_fps * FPS_DROP_THRESHOLD: + current_time = time.monotonic() + if current_time - self._last_fps_log_time >= FPS_LOG_INTERVAL: + cloudlog.warning(f"FPS dropped below {self._target_fps}: {fps}") + self._last_fps_log_time = current_time + + # Strict mode: terminate UI if FPS drops too much + if STRICT_MODE and fps < self._target_fps * FPS_CRITICAL_THRESHOLD: + cloudlog.error(f"FPS dropped critically below {fps}. Shutting down UI.") + self.close_ffmpeg() + os._exit(1) + + def _draw_touch_points(self): + current_time = time.monotonic() + + for mouse_event in self._mouse_events: + if mouse_event.left_pressed: + self._mouse_history.clear() + self._mouse_history.append(MousePosWithTime(mouse_event.pos.x * self._scale, mouse_event.pos.y * self._scale, current_time)) + + # Remove old touch points that exceed the timeout + while self._mouse_history and (current_time - self._mouse_history[0].t) > TOUCH_HISTORY_TIMEOUT: + self._mouse_history.popleft() + + if self._mouse_history: + mouse_pos = self._mouse_history[-1] + rl.draw_circle(int(mouse_pos.x), int(mouse_pos.y), 15, rl.RED) + for idx, mouse_pos in enumerate(self._mouse_history): + perc = idx / len(self._mouse_history) + color = rl.Color(min(int(255 * (1.5 - perc)), 255), int(min(255 * (perc + 0.5), 255)), 50, 255) + rl.draw_circle(int(mouse_pos.x), int(mouse_pos.y), 5, color) + + def _draw_grid(self): + grid_color = rl.Color(60, 60, 60, 255) + # Draw vertical lines + x = 0 + while x <= self._scaled_width: + rl.draw_line(x, 0, x, self._scaled_height, grid_color) + x += self._grid_size + # Draw horizontal lines + y = 0 + while y <= self._scaled_height: + rl.draw_line(0, y, self._scaled_width, y, grid_color) + y += self._grid_size + + def _output_render_profile(self): + import io + import pstats + + self._render_profiler.disable() + elapsed_ms = (time.monotonic() - self._render_profile_start_time) * 1e3 + avg_frame_time = elapsed_ms / self._frame if self._frame > 0 else 0 + + stats_stream = io.StringIO() + pstats.Stats(self._render_profiler, stream=stats_stream).sort_stats("cumtime").print_stats(PROFILE_STATS) + print("\n=== Render loop profile ===") + print(stats_stream.getvalue().rstrip()) + + green = "\033[92m" + reset = "\033[0m" + print(f"\n{green}Rendered {self._frame} frames in {elapsed_ms:.1f} ms{reset}") + print(f"{green}Average frame time: {avg_frame_time:.2f} ms ({1000/avg_frame_time:.1f} FPS){reset}") + sys.exit(0) + + def _calculate_auto_scale(self) -> float: + # Create temporary window to query monitor info + rl.init_window(1, 1, "") + w, h = rl.get_monitor_width(0), rl.get_monitor_height(0) + rl.close_window() + + if w == 0 or h == 0 or (w >= self._width and h >= self._height): + return 1.0 + + # Apply 0.95 factor for window decorations/taskbar margin + return max(0.3, min(w / self._width, h / self._height) * 0.95) + + @staticmethod + def _default_width() -> int: + return 2160 if GuiApplication.big_ui() else 536 + + @staticmethod + def _default_height() -> int: + return 1080 if GuiApplication.big_ui() else 240 + + @staticmethod + def big_ui() -> bool: + return HARDWARE.get_device_type() in ('tici', 'tizi') or BIG_UI + + +gui_app = GuiApplication() diff --git a/system/ui/lib/egl.py b/system/ui/lib/egl.py new file mode 100644 index 00000000000000..69236482b0e85b --- /dev/null +++ b/system/ui/lib/egl.py @@ -0,0 +1,181 @@ +import os +import cffi +from dataclasses import dataclass +from typing import Any +from openpilot.common.swaglog import cloudlog + +# EGL constants +EGL_LINUX_DMA_BUF_EXT = 0x3270 +EGL_WIDTH = 0x3057 +EGL_HEIGHT = 0x3056 +EGL_LINUX_DRM_FOURCC_EXT = 0x3271 +EGL_DMA_BUF_PLANE0_FD_EXT = 0x3272 +EGL_DMA_BUF_PLANE0_OFFSET_EXT = 0x3273 +EGL_DMA_BUF_PLANE0_PITCH_EXT = 0x3274 +EGL_DMA_BUF_PLANE1_FD_EXT = 0x3275 +EGL_DMA_BUF_PLANE1_OFFSET_EXT = 0x3276 +EGL_DMA_BUF_PLANE1_PITCH_EXT = 0x3277 +EGL_NONE = 0x3038 +GL_TEXTURE0 = 0x84C0 +GL_TEXTURE_EXTERNAL_OES = 0x8D65 + +# DRM Format for NV12 +DRM_FORMAT_NV12 = 842094158 + + +@dataclass +class EGLImage: + """Container for EGL image and associated resources""" + + egl_image: Any + fd: int + + +@dataclass +class EGLState: + """Container for all EGL-related state""" + + initialized: bool = False + ffi: Any = None + egl_lib: Any = None + gles_lib: Any = None + + # EGL display connection - shared across all users + display: Any = None + + # Constants + NO_CONTEXT: Any = None + NO_DISPLAY: Any = None + NO_IMAGE_KHR: Any = None + + # Function pointers + get_current_display: Any = None + create_image_khr: Any = None + destroy_image_khr: Any = None + image_target_texture: Any = None + get_error: Any = None + bind_texture: Any = None + active_texture: Any = None + + +# Create a single instance of the state +_egl = EGLState() + + +def init_egl() -> bool: + """Initialize EGL and load necessary functions""" + global _egl + + # Don't re-initialize if already done + if _egl.initialized: + return True + + try: + _egl.ffi = cffi.FFI() + _egl.ffi.cdef(""" + typedef int EGLint; + typedef unsigned int EGLBoolean; + typedef unsigned int EGLenum; + typedef unsigned int GLenum; + typedef void *EGLContext; + typedef void *EGLDisplay; + typedef void *EGLClientBuffer; + typedef void *EGLImageKHR; + typedef void *GLeglImageOES; + + EGLDisplay eglGetCurrentDisplay(void); + EGLint eglGetError(void); + EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, + EGLenum target, EGLClientBuffer buffer, + const EGLint *attrib_list); + EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR image); + void glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image); + void glBindTexture(GLenum target, unsigned int texture); + void glActiveTexture(GLenum texture); + """) + + # Load libraries + _egl.egl_lib = _egl.ffi.dlopen("libEGL.so") + _egl.gles_lib = _egl.ffi.dlopen("libGLESv2.so") + + # Cast NULL pointers + _egl.NO_CONTEXT = _egl.ffi.cast("void *", 0) + _egl.NO_DISPLAY = _egl.ffi.cast("void *", 0) + _egl.NO_IMAGE_KHR = _egl.ffi.cast("void *", 0) + + # Bind functions + _egl.get_current_display = _egl.egl_lib.eglGetCurrentDisplay + _egl.create_image_khr = _egl.egl_lib.eglCreateImageKHR + _egl.destroy_image_khr = _egl.egl_lib.eglDestroyImageKHR + _egl.image_target_texture = _egl.gles_lib.glEGLImageTargetTexture2DOES + _egl.get_error = _egl.egl_lib.eglGetError + _egl.bind_texture = _egl.gles_lib.glBindTexture + _egl.active_texture = _egl.gles_lib.glActiveTexture + + # Initialize EGL display once here + _egl.display = _egl.get_current_display() + if _egl.display == _egl.NO_DISPLAY: + raise RuntimeError("Failed to get EGL display") + + _egl.initialized = True + return True + except Exception as e: + cloudlog.exception(f"EGL initialization failed: {e}") + _egl.initialized = False + return False + + +def create_egl_image(width: int, height: int, stride: int, fd: int, uv_offset: int) -> EGLImage | None: + assert _egl.initialized, "EGL not initialized" + + try: + # Duplicate fd since EGL needs it + dup_fd = os.dup(fd) + except OSError as e: + cloudlog.exception(f"Failed to duplicate frame fd when creating EGL image: {e}") + return None + + # Create image attributes for EGL + img_attrs = [ + EGL_WIDTH, width, + EGL_HEIGHT, height, + EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_NV12, + EGL_DMA_BUF_PLANE0_FD_EXT, dup_fd, + EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, + EGL_DMA_BUF_PLANE0_PITCH_EXT, stride, + EGL_DMA_BUF_PLANE1_FD_EXT, dup_fd, + EGL_DMA_BUF_PLANE1_OFFSET_EXT, uv_offset, + EGL_DMA_BUF_PLANE1_PITCH_EXT, stride, + EGL_NONE + ] + + attr_array = _egl.ffi.new("int[]", img_attrs) + egl_image = _egl.create_image_khr(_egl.display, _egl.NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, _egl.ffi.NULL, attr_array) + + if egl_image == _egl.NO_IMAGE_KHR: + cloudlog.error(f"Failed to create EGL image: {_egl.get_error()}") + os.close(dup_fd) + return None + + return EGLImage(egl_image=egl_image, fd=dup_fd) + + +def destroy_egl_image(egl_image: EGLImage) -> None: + assert _egl.initialized, "EGL not initialized" + + _egl.destroy_image_khr(_egl.display, egl_image.egl_image) + + # Close the duplicated fd we created in create_egl_image() + # We need to handle OSError since the fd might already be closed + try: + os.close(egl_image.fd) + except OSError: + pass + + +def bind_egl_image_to_texture(texture_id: int, egl_image: EGLImage) -> None: + assert _egl.initialized, "EGL not initialized" + + _egl.active_texture(GL_TEXTURE0) + _egl.bind_texture(GL_TEXTURE_EXTERNAL_OES, texture_id) + _egl.image_target_texture(GL_TEXTURE_EXTERNAL_OES, egl_image.egl_image) diff --git a/system/ui/lib/emoji.py b/system/ui/lib/emoji.py new file mode 100644 index 00000000000000..ad4c272c8de7fb --- /dev/null +++ b/system/ui/lib/emoji.py @@ -0,0 +1,55 @@ +import io +import re +import functools +from importlib.resources import as_file + +from PIL import Image, ImageDraw, ImageFont +import pyray as rl + +from openpilot.system.ui.lib.application import FONT_DIR + +_cache: dict[str, rl.Texture] = {} + +EMOJI_REGEX = re.compile( +"""[\U0001F600-\U0001F64F +\U0001F300-\U0001F5FF +\U0001F680-\U0001F6FF +\U0001F1E0-\U0001F1FF +\U00002700-\U000027BF +\U0001F900-\U0001F9FF +\U00002600-\U000026FF +\U00002300-\U000023FF +\U00002B00-\U00002BFF +\U0001FA70-\U0001FAFF +\U0001F700-\U0001F77F +\u2640-\u2642 +\u2600-\u2B55 +\u200d +\u23cf +\u23e9 +\u231a +\ufe0f +\u3030 +]+""".replace("\n", ""), + flags=re.UNICODE +) + +@functools.cache +def _load_emoji_font() -> ImageFont.FreeTypeFont: + with as_file(FONT_DIR.joinpath("NotoColorEmoji.ttf")) as font_path: + return ImageFont.truetype(io.BytesIO(font_path.read_bytes()), 109) + +def find_emoji(text): + return [(m.start(), m.end(), m.group()) for m in EMOJI_REGEX.finditer(text)] + +def emoji_tex(emoji): + if emoji not in _cache: + img = Image.new("RGBA", (128, 128), (0, 0, 0, 0)) + draw = ImageDraw.Draw(img) + draw.text((0, 0), emoji, font=_load_emoji_font(), embedded_color=True) + with io.BytesIO() as buffer: + img.save(buffer, format="PNG") + l = buffer.tell() + buffer.seek(0) + _cache[emoji] = rl.load_texture_from_image(rl.load_image_from_memory(".png", buffer.getvalue(), l)) + return _cache[emoji] diff --git a/system/ui/lib/multilang.py b/system/ui/lib/multilang.py new file mode 100644 index 00000000000000..06c54f6e9f67f9 --- /dev/null +++ b/system/ui/lib/multilang.py @@ -0,0 +1,213 @@ +from importlib.resources import files +import json +import os +import re +from openpilot.common.basedir import BASEDIR +from openpilot.common.swaglog import cloudlog + +try: + from openpilot.common.params import Params +except ImportError: + Params = None + +SYSTEM_UI_DIR = os.path.join(BASEDIR, "system", "ui") +UI_DIR = files("openpilot.selfdrive.ui") +TRANSLATIONS_DIR = UI_DIR.joinpath("translations") +LANGUAGES_FILE = TRANSLATIONS_DIR.joinpath("languages.json") + +UNIFONT_LANGUAGES = [ + "th", + "zh-CHT", + "zh-CHS", + "ko", + "ja", +] + +# Plural form selectors for supported languages +PLURAL_SELECTORS = { + 'en': lambda n: 0 if n == 1 else 1, + 'de': lambda n: 0 if n == 1 else 1, + 'fr': lambda n: 0 if n <= 1 else 1, + 'pt-BR': lambda n: 0 if n <= 1 else 1, + 'es': lambda n: 0 if n == 1 else 1, + 'tr': lambda n: 0 if n == 1 else 1, + 'uk': lambda n: 0 if n % 10 == 1 and n % 100 != 11 else (1 if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14 else 2), + 'th': lambda n: 0, + 'zh-CHT': lambda n: 0, + 'zh-CHS': lambda n: 0, + 'ko': lambda n: 0, + 'ja': lambda n: 0, +} + + +def _parse_quoted(s: str) -> str: + """Parse a PO-format quoted string.""" + s = s.strip() + if not (s.startswith('"') and s.endswith('"')): + raise ValueError(f"Expected quoted string: {s!r}") + s = s[1:-1] + result: list[str] = [] + i = 0 + while i < len(s): + if s[i] == '\\' and i + 1 < len(s): + c = s[i + 1] + if c == 'n': + result.append('\n') + elif c == 't': + result.append('\t') + elif c == '"': + result.append('"') + elif c == '\\': + result.append('\\') + else: + result.append(s[i:i + 2]) + i += 2 + else: + result.append(s[i]) + i += 1 + return ''.join(result) + + +def load_translations(path) -> tuple[dict[str, str], dict[str, list[str]]]: + """Parse a .po file and return (translations, plurals) dicts. + + translations: msgid -> msgstr + plurals: msgid -> [msgstr[0], msgstr[1], ...] + """ + with path.open(encoding='utf-8') as f: + lines = f.readlines() + + translations: dict[str, str] = {} + plurals: dict[str, list[str]] = {} + + # Parser state + msgid = msgid_plural = msgstr = "" + msgstr_plurals: dict[int, str] = {} + field: str | None = None + plural_idx = 0 + + def finish(): + nonlocal msgid, msgid_plural, msgstr, msgstr_plurals, field + if msgid: # skip header (empty msgid) + if msgid_plural: + max_idx = max(msgstr_plurals.keys()) if msgstr_plurals else 0 + plurals[msgid] = [msgstr_plurals.get(i, '') for i in range(max_idx + 1)] + else: + translations[msgid] = msgstr + msgid = msgid_plural = msgstr = "" + msgstr_plurals = {} + field = None + + for raw in lines: + line = raw.strip() + + if not line: + finish() + continue + + if line.startswith('#'): + continue + + if line.startswith('msgid_plural '): + msgid_plural = _parse_quoted(line[len('msgid_plural '):]) + field = 'msgid_plural' + continue + + if line.startswith('msgid '): + msgid = _parse_quoted(line[len('msgid '):]) + field = 'msgid' + continue + + m = re.match(r'msgstr\[(\d+)]\s+(.*)', line) + if m: + plural_idx = int(m.group(1)) + msgstr_plurals[plural_idx] = _parse_quoted(m.group(2)) + field = 'msgstr_plural' + continue + + if line.startswith('msgstr '): + msgstr = _parse_quoted(line[len('msgstr '):]) + field = 'msgstr' + continue + + if line.startswith('"'): + val = _parse_quoted(line) + if field == 'msgid': + msgid += val + elif field == 'msgid_plural': + msgid_plural += val + elif field == 'msgstr': + msgstr += val + elif field == 'msgstr_plural': + msgstr_plurals[plural_idx] += val + + finish() + return translations, plurals + + +class Multilang: + def __init__(self): + self._params = Params() if Params is not None else None + self._language: str = "en" + self.languages: dict[str, str] = {} + self.codes: dict[str, str] = {} + self._translations: dict[str, str] = {} + self._plurals: dict[str, list[str]] = {} + self._plural_selector = PLURAL_SELECTORS.get('en', lambda n: 0) + self._load_languages() + + @property + def language(self) -> str: + return self._language + + def requires_unifont(self) -> bool: + """Certain languages require unifont to render their glyphs.""" + return self._language in UNIFONT_LANGUAGES + + def setup(self): + try: + po_path = TRANSLATIONS_DIR.joinpath(f'app_{self._language}.po') + self._translations, self._plurals = load_translations(po_path) + self._plural_selector = PLURAL_SELECTORS.get(self._language, lambda n: 0) + cloudlog.debug(f"Loaded translations for language: {self._language}") + except FileNotFoundError: + cloudlog.error(f"No translation file found for language: {self._language}, using default.") + self._translations = {} + self._plurals = {} + + def change_language(self, language_code: str) -> None: + self._params.put("LanguageSetting", language_code, block=True) + self._language = language_code + self.setup() + + def tr(self, text: str) -> str: + return self._translations.get(text, text) or text + + def trn(self, singular: str, plural: str, n: int) -> str: + if singular in self._plurals: + idx = self._plural_selector(n) + forms = self._plurals[singular] + if idx < len(forms) and forms[idx]: + return forms[idx] + return singular if n == 1 else plural + + def _load_languages(self): + with LANGUAGES_FILE.open(encoding='utf-8') as f: + self.languages = json.load(f) + self.codes = {v: k for k, v in self.languages.items()} + + if self._params is not None: + lang = str(self._params.get("LanguageSetting")).removeprefix("main_") + if lang in self.codes: + self._language = lang + + +multilang = Multilang() +multilang.setup() + +tr, trn = multilang.tr, multilang.trn + + +# no-op marker for static strings translated later +def tr_noop(s: str) -> str: + return s diff --git a/system/ui/lib/networkmanager.py b/system/ui/lib/networkmanager.py new file mode 100644 index 00000000000000..d2d6b30b1071da --- /dev/null +++ b/system/ui/lib/networkmanager.py @@ -0,0 +1,64 @@ +from enum import IntEnum + + +# NetworkManager device states +class NMDeviceState(IntEnum): + # https://networkmanager.dev/docs/api/1.46/nm-dbus-types.html#NMDeviceState + UNKNOWN = 0 + UNMANAGED = 10 + UNAVAILABLE = 20 + DISCONNECTED = 30 + PREPARE = 40 + CONFIG = 50 + NEED_AUTH = 60 + IP_CONFIG = 70 + IP_CHECK = 80 + SECONDARIES = 90 + ACTIVATED = 100 + DEACTIVATING = 110 + FAILED = 120 + + +class NMDeviceStateReason(IntEnum): + # https://networkmanager.dev/docs/api/1.46/nm-dbus-types.html#NMDeviceStateReason + NONE = 0 + UNKNOWN = 1 + IP_CONFIG_UNAVAILABLE = 5 + NO_SECRETS = 7 + SUPPLICANT_DISCONNECT = 8 + SUPPLICANT_TIMEOUT = 11 + CONNECTION_REMOVED = 38 + USER_REQUESTED = 39 + SSID_NOT_FOUND = 53 + NEW_ACTIVATION = 60 + + +# NetworkManager constants +NM = "org.freedesktop.NetworkManager" +NM_PATH = '/org/freedesktop/NetworkManager' +NM_IFACE = 'org.freedesktop.NetworkManager' +NM_ACCESS_POINT_IFACE = 'org.freedesktop.NetworkManager.AccessPoint' +NM_SETTINGS_PATH = '/org/freedesktop/NetworkManager/Settings' +NM_SETTINGS_IFACE = 'org.freedesktop.NetworkManager.Settings' +NM_CONNECTION_IFACE = 'org.freedesktop.NetworkManager.Settings.Connection' +NM_ACTIVE_CONNECTION_IFACE = 'org.freedesktop.NetworkManager.Connection.Active' +NM_WIRELESS_IFACE = 'org.freedesktop.NetworkManager.Device.Wireless' +NM_PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' +NM_DEVICE_IFACE = 'org.freedesktop.NetworkManager.Device' +NM_IP4_CONFIG_IFACE = 'org.freedesktop.NetworkManager.IP4Config' + +NM_DEVICE_TYPE_WIFI = 2 +NM_DEVICE_TYPE_MODEM = 8 + +# https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApFlags +NM_802_11_AP_FLAGS_NONE = 0x0 +NM_802_11_AP_FLAGS_PRIVACY = 0x1 +NM_802_11_AP_FLAGS_WPS = 0x2 + +# https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApSecurityFlags +NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001 +NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002 +NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010 +NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020 +NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100 +NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200 diff --git a/system/ui/lib/scroll_panel.py b/system/ui/lib/scroll_panel.py new file mode 100644 index 00000000000000..a5b9fc70d33555 --- /dev/null +++ b/system/ui/lib/scroll_panel.py @@ -0,0 +1,134 @@ +import math +import pyray as rl +from enum import IntEnum +from openpilot.system.ui.lib.application import gui_app, MouseEvent +from openpilot.common.filter_simple import FirstOrderFilter + +# Scroll constants for smooth scrolling behavior +MOUSE_WHEEL_SCROLL_SPEED = 50 +BOUNCE_RETURN_RATE = 5 # ~0.92 at 60fps +MIN_VELOCITY = 2 # px/s, changes from auto scroll to steady state +MIN_VELOCITY_FOR_CLICKING = 2 * 60 # px/s, accepts clicks while auto scrolling below this velocity +DRAG_THRESHOLD = 12 # pixels of movement to consider it a drag, not a click + +DEBUG = False + + +class ScrollState(IntEnum): + IDLE = 0 # Not dragging, content may be bouncing or scrolling with inertia + DRAGGING_CONTENT = 1 # User is actively dragging the content + + +class GuiScrollPanel: + def __init__(self): + self._scroll_state: ScrollState = ScrollState.IDLE + self._last_mouse_y: float = 0.0 + self._start_mouse_y: float = 0.0 # Track the initial mouse position for drag detection + self._offset_filter_y = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + self._velocity_filter_y = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps) + self._last_drag_time: float = 0.0 + + def update(self, bounds: rl.Rectangle, content: rl.Rectangle) -> float: + for mouse_event in gui_app.mouse_events: + if mouse_event.slot == 0: + self._handle_mouse_event(mouse_event, bounds, content) + + self._update_state(bounds, content) + + return float(self._offset_filter_y.x) + + def _update_state(self, bounds: rl.Rectangle, content: rl.Rectangle): + if DEBUG: + rl.draw_rectangle_lines(0, 0, abs(int(self._velocity_filter_y.x)), 10, rl.RED) + + # Handle mouse wheel + self._offset_filter_y.x += rl.get_mouse_wheel_move() * MOUSE_WHEEL_SCROLL_SPEED + + max_scroll_distance = max(0, content.height - bounds.height) + if self._scroll_state == ScrollState.IDLE: + above_bounds, below_bounds = self._check_bounds(bounds, content) + + # Decay velocity when idle + if abs(self._velocity_filter_y.x) > MIN_VELOCITY: + # Faster decay if bouncing back from out of bounds + friction = math.exp(-BOUNCE_RETURN_RATE * 1 / gui_app.target_fps) + self._velocity_filter_y.x *= friction ** 2 if (above_bounds or below_bounds) else friction + else: + self._velocity_filter_y.x = 0.0 + + if above_bounds or below_bounds: + if above_bounds: + self._offset_filter_y.update(0) + else: + self._offset_filter_y.update(-max_scroll_distance) + + self._offset_filter_y.x += self._velocity_filter_y.x / gui_app.target_fps + + elif self._scroll_state == ScrollState.DRAGGING_CONTENT: + # Mouse not moving, decay velocity + if not len(gui_app.mouse_events): + self._velocity_filter_y.update(0.0) + + # Settle to exact bounds + if abs(self._offset_filter_y.x) < 1e-2: + self._offset_filter_y.x = 0.0 + elif abs(self._offset_filter_y.x + max_scroll_distance) < 1e-2: + self._offset_filter_y.x = -max_scroll_distance + + def _handle_mouse_event(self, mouse_event: MouseEvent, bounds: rl.Rectangle, content: rl.Rectangle): + if self._scroll_state == ScrollState.IDLE: + if rl.check_collision_point_rec(mouse_event.pos, bounds): + if mouse_event.left_pressed: + self._start_mouse_y = mouse_event.pos.y + # Interrupt scrolling with new drag + # TODO: stop scrolling with any tap, need to fix is_touch_valid + if abs(self._velocity_filter_y.x) > MIN_VELOCITY_FOR_CLICKING: + self._scroll_state = ScrollState.DRAGGING_CONTENT + # Start velocity at initial measurement for more immediate response + self._velocity_filter_y.initialized = False + + if mouse_event.left_down: + if abs(mouse_event.pos.y - self._start_mouse_y) > DRAG_THRESHOLD: + self._scroll_state = ScrollState.DRAGGING_CONTENT + # Start velocity at initial measurement for more immediate response + self._velocity_filter_y.initialized = False + + elif self._scroll_state == ScrollState.DRAGGING_CONTENT: + if mouse_event.left_released: + self._scroll_state = ScrollState.IDLE + else: + delta_y = mouse_event.pos.y - self._last_mouse_y + above_bounds, below_bounds = self._check_bounds(bounds, content) + # Rubber banding effect when out of bands + if above_bounds or below_bounds: + delta_y /= 3 + + self._offset_filter_y.x += delta_y + + # Track velocity for inertia + dt = mouse_event.t - self._last_drag_time + if dt > 0: + drag_velocity = delta_y / dt + self._velocity_filter_y.update(drag_velocity) + + # TODO: just store last mouse event! + self._last_drag_time = mouse_event.t + self._last_mouse_y = mouse_event.pos.y + + def _check_bounds(self, bounds: rl.Rectangle, content: rl.Rectangle) -> tuple[bool, bool]: + max_scroll_distance = max(0, content.height - bounds.height) + above_bounds = self._offset_filter_y.x > 0 + below_bounds = self._offset_filter_y.x < -max_scroll_distance + return above_bounds, below_bounds + + def is_touch_valid(self): + return self._scroll_state == ScrollState.IDLE and abs(self._velocity_filter_y.x) < MIN_VELOCITY_FOR_CLICKING + + def set_offset(self, position: float) -> None: + self._offset_filter_y.x = position + self._velocity_filter_y.x = 0.0 + self._scroll_state = ScrollState.IDLE + + @property + def offset(self) -> float: + return float(self._offset_filter_y.x) diff --git a/system/ui/lib/scroll_panel2.py b/system/ui/lib/scroll_panel2.py new file mode 100644 index 00000000000000..7fae60119c0d11 --- /dev/null +++ b/system/ui/lib/scroll_panel2.py @@ -0,0 +1,268 @@ +import os +import math +import pyray as rl +from collections.abc import Callable +from enum import Enum +from typing import cast +from openpilot.system.ui.lib.application import gui_app, MouseEvent +from openpilot.system.hardware import TICI +from collections import deque + +MIN_VELOCITY = 10 # px/s, changes from auto scroll to steady state +MIN_VELOCITY_FOR_CLICKING = 2 * 60 # px/s, accepts clicks while auto scrolling below this velocity +MIN_DRAG_PIXELS = 12 +AUTO_SCROLL_TC_SNAP = 0.025 +AUTO_SCROLL_TC = 0.18 +BOUNCE_RETURN_RATE = 10.0 +SNAP_RATE = 6.3 # matches previous Scroller snapping. exp rate of approach to snap target, 1/s +REJECT_DECELERATION_FACTOR = 3 +MAX_SPEED = 10000.0 # px/s + +DEBUG = os.getenv("DEBUG_SCROLL", "0") == "1" + + +# Weights older (steadier) velocity samples more heavily on release. +# Finger-lift samples are noisy; trusting earlier samples gives consistent fling velocity. +# Reverse-engineered from iOS UIScrollView (tuned at 120Hz touch) by Flutter team: +# https://github.com/flutter/flutter/pull/60501 +# 3 samples ≈ 25ms at 120Hz (iOS) / ~21ms at 140Hz (comma). Scale if touch rate changes. +def weighted_velocity(buffer: deque) -> float: + if len(buffer) >= 3: + return buffer[-3] * 0.6 + buffer[-2] * 0.35 + buffer[-1] * 0.05 + elif len(buffer) == 2: + return buffer[-2] * 0.7 + buffer[-1] * 0.3 + elif len(buffer) == 1: + return buffer[-1] + return 0.0 + + +# from https://ariya.io/2011/10/flick-list-with-its-momentum-scrolling-and-deceleration +class ScrollState(Enum): + STEADY = 0 + PRESSED = 1 + MANUAL_SCROLL = 2 + AUTO_SCROLL = 3 + + +class GuiScrollPanel2: + def __init__(self, horizontal: bool = True) -> None: + self._horizontal = horizontal + self._state = ScrollState.STEADY + self._offset: rl.Vector2 = rl.Vector2(0, 0) + self._initial_click_event: MouseEvent | None = None + self._previous_mouse_event: MouseEvent | None = None + self._velocity = 0.0 # pixels per second + self._velocity_buffer: deque[float] = deque(maxlen=12 if TICI else 6) + self._enabled: bool | Callable[[], bool] = True + + def set_enabled(self, enabled: bool | Callable[[], bool]) -> None: + self._enabled = enabled + + @property + def enabled(self) -> bool: + return self._enabled() if callable(self._enabled) else self._enabled + + def update(self, bounds: rl.Rectangle, content_size: float, snap_target: float | None = None) -> float: + if DEBUG: + print('Old state:', self._state) + + bounds_size = bounds.width if self._horizontal else bounds.height + + for mouse_event in gui_app.mouse_events: + self._handle_mouse_event(mouse_event, bounds, bounds_size, content_size) + self._previous_mouse_event = mouse_event + + self._update_state(bounds_size, content_size, snap_target) + + if DEBUG: + print('Velocity:', self._velocity) + print('Offset X:', self._offset.x, 'Y:', self._offset.y) + print('New state:', self._state) + print() + return self.get_offset() + + def _get_offset_bounds(self, bounds_size: float, content_size: float) -> tuple[float, float]: + """Returns (max_offset, min_offset) for the given bounds and content size.""" + return 0.0, min(0.0, bounds_size - content_size) + + def _update_state(self, bounds_size: float, content_size: float, snap_target: float | None) -> None: + """Runs per render frame, independent of mouse events. Updates auto-scrolling state and velocity.""" + max_offset, min_offset = self._get_offset_bounds(bounds_size, content_size) + + if self._state == ScrollState.STEADY: + # if we find ourselves out of bounds, scroll back in (from external layout dimension changes, etc.) + if self.get_offset() > max_offset or self.get_offset() < min_offset: + self._state = ScrollState.AUTO_SCROLL + + elif self._state == ScrollState.AUTO_SCROLL: + # simple exponential return if out of bounds + # out of bounds is handled by snapping, so skip if set + out_of_bounds = self.get_offset() > max_offset or self.get_offset() < min_offset + if out_of_bounds and snap_target is None: + target = max_offset if self.get_offset() > max_offset else min_offset + + dt = rl.get_frame_time() or 1e-6 + factor = 1.0 - math.exp(-BOUNCE_RETURN_RATE * dt) + + dist = target - self.get_offset() + self.set_offset(self.get_offset() + dist * factor) # ease toward the edge + self._velocity *= (1.0 - factor) # damp any leftover fling + + # Steady once we are close enough to the target + if abs(dist) < 1 and abs(self._velocity) < MIN_VELOCITY: + self.set_offset(target) + self._velocity = 0.0 + self._state = ScrollState.STEADY + + elif abs(self._velocity) < MIN_VELOCITY: + self._velocity = 0.0 + self._state = ScrollState.STEADY + + # Update the offset based on the current velocity + dt = rl.get_frame_time() + self.set_offset(self.get_offset() + self._velocity * dt) # Adjust the offset based on velocity + # fast decay in snap mode so velocity yields to the snap pull instead of fighting it + auto_scroll_tc = AUTO_SCROLL_TC_SNAP if snap_target is not None else AUTO_SCROLL_TC + alpha = 1 - (dt / (auto_scroll_tc + dt)) + self._velocity *= alpha + + # Ease toward snap target when not in user control. Composes with velocity coast above: + # high velocity dominates initially, snap dominates as velocity decays. + if snap_target is not None and self._state not in (ScrollState.PRESSED, ScrollState.MANUAL_SCROLL): + snap_target = max(min_offset, min(max_offset, snap_target)) + dist = snap_target - self.get_offset() + if abs(dist) < 1: # finished snap + self.set_offset(snap_target) + else: + dt = rl.get_frame_time() or 1e-6 + factor = 1.0 - math.exp(-SNAP_RATE * dt) + self.set_offset(self.get_offset() + dist * factor) + + def _handle_mouse_event(self, mouse_event: MouseEvent, bounds: rl.Rectangle, bounds_size: float, + content_size: float) -> None: + max_offset, min_offset = self._get_offset_bounds(bounds_size, content_size) + # simple exponential return if out of bounds + out_of_bounds = self.get_offset() > max_offset or self.get_offset() < min_offset + if DEBUG: + print('Mouse event:', mouse_event) + + mouse_pos = self._get_mouse_pos(mouse_event) + + if not self.enabled: + # Reset state if not enabled + self._state = ScrollState.STEADY + self._velocity = 0.0 + self._velocity_buffer.clear() + + elif self._state == ScrollState.STEADY: + if rl.check_collision_point_rec(mouse_event.pos, bounds): + if mouse_event.left_pressed: + self._state = ScrollState.PRESSED + self._initial_click_event = mouse_event + + elif self._state == ScrollState.PRESSED: + initial_click_pos = self._get_mouse_pos(cast(MouseEvent, self._initial_click_event)) + diff = abs(mouse_pos - initial_click_pos) + if mouse_event.left_released: + # Special handling for down and up clicks across two frames + # TODO: not sure what that means or if it's accurate anymore + if out_of_bounds: + self._state = ScrollState.AUTO_SCROLL + elif diff <= MIN_DRAG_PIXELS: + self._state = ScrollState.STEADY + else: + self._state = ScrollState.MANUAL_SCROLL + elif diff > MIN_DRAG_PIXELS: + self._state = ScrollState.MANUAL_SCROLL + + elif self._state == ScrollState.MANUAL_SCROLL: + if mouse_event.left_released: + # Touch rejection: when releasing finger after swiping and stopping, panel + # reports a few erroneous touch events with high velocity, try to ignore. + + # If velocity decelerates very quickly, assume user doesn't intend to auto scroll. + # Catches two cases: 1) swipe, stop finger, then lift (stale high velocity in buffer) + # 2) dirty finger lift where finger rotates/slides producing spurious velocity spike. + # TODO: this heuristic false-positives on fast swipes because 140Hz touch polling + # jitter causes velocity to oscillate (not real deceleration). Better approaches: + # - Use evdev kernel timestamps to eliminate velocity oscillation at the source + # - Replace with a time-since-last-event check (40ms timeout) for swipe-stop-lift + high_decel = False + if len(self._velocity_buffer) > 2: + # We limit max to first half since final few velocities can surpass first few + abs_velocity_buffer = [(abs(v), i) for i, v in enumerate(self._velocity_buffer)] + max_idx = max(abs_velocity_buffer[:len(abs_velocity_buffer) // 2])[1] + min_idx = min(abs_velocity_buffer)[1] + if DEBUG: + print('min_idx:', min_idx, 'max_idx:', max_idx, 'velocity buffer:', self._velocity_buffer) + if (abs(self._velocity_buffer[min_idx]) * REJECT_DECELERATION_FACTOR < abs(self._velocity_buffer[max_idx]) and + max_idx < min_idx): + if DEBUG: + print('deceleration too high, going to STEADY') + high_decel = True + + self._velocity = weighted_velocity(self._velocity_buffer) + + # If final velocity is below some threshold, switch to steady state too + low_speed = abs(self._velocity) <= MIN_VELOCITY_FOR_CLICKING * 1.5 # plus some margin + + if out_of_bounds or not (high_decel or low_speed): + self._state = ScrollState.AUTO_SCROLL + else: + # TODO: we should just set velocity and let autoscroll go back to steady. delays one frame but who cares + self._velocity = 0.0 + self._state = ScrollState.STEADY + self._velocity_buffer.clear() + else: + # Update velocity for when we release the mouse button. + # Do not update velocity on the same frame the mouse was released + previous_mouse_pos = self._get_mouse_pos(cast(MouseEvent, self._previous_mouse_event)) + delta_x = mouse_pos - previous_mouse_pos + delta_t = max((mouse_event.t - cast(MouseEvent, self._previous_mouse_event).t), 1e-6) + self._velocity = delta_x / delta_t + self._velocity = max(-MAX_SPEED, min(MAX_SPEED, self._velocity)) + self._velocity_buffer.append(self._velocity) + + # rubber-banding: reduce dragging when out of bounds + # TODO: this drifts when dragging quickly + if out_of_bounds: + delta_x *= 0.25 + + # Update the offset based on the mouse movement + # Use internal _offset directly to preserve precision (don't round via get_offset()) + # TODO: make get_offset return float + current_offset = self._offset.x if self._horizontal else self._offset.y + self.set_offset(current_offset + delta_x) + + elif self._state == ScrollState.AUTO_SCROLL: + if mouse_event.left_pressed: + # Decide whether to click or scroll (block click if moving too fast) + if abs(self._velocity) <= MIN_VELOCITY_FOR_CLICKING: + # Traveling slow enough, click + self._state = ScrollState.PRESSED + self._initial_click_event = mouse_event + else: + # Go straight into manual scrolling to block erroneous input + self._state = ScrollState.MANUAL_SCROLL + # Reset velocity for touch down and up events that happen in back-to-back frames + self._velocity = 0.0 + + def _get_mouse_pos(self, mouse_event: MouseEvent) -> float: + return mouse_event.pos.x if self._horizontal else mouse_event.pos.y + + def get_offset(self) -> float: + return self._offset.x if self._horizontal else self._offset.y + + def set_offset(self, value: float) -> None: + if self._horizontal: + self._offset.x = value + else: + self._offset.y = value + + @property + def state(self) -> ScrollState: + return self._state + + def is_touch_valid(self) -> bool: + # MIN_VELOCITY_FOR_CLICKING is checked in auto-scroll state + return bool(self._state != ScrollState.MANUAL_SCROLL) diff --git a/system/ui/lib/shader_polygon.py b/system/ui/lib/shader_polygon.py new file mode 100644 index 00000000000000..94af35e157fc48 --- /dev/null +++ b/system/ui/lib/shader_polygon.py @@ -0,0 +1,238 @@ +import pyray as rl +import numpy as np +from dataclasses import dataclass +from typing import Any, Optional, cast +from openpilot.system.ui.lib.application import gui_app, GL_VERSION + +MAX_GRADIENT_COLORS = 20 # includes stops as well + + +@dataclass +class Gradient: + start: tuple[float, float] + end: tuple[float, float] + colors: list[rl.Color] + stops: list[float] + + def __post_init__(self): + if len(self.colors) > MAX_GRADIENT_COLORS: + self.colors = self.colors[:MAX_GRADIENT_COLORS] + print(f"Warning: Gradient colors truncated to {MAX_GRADIENT_COLORS} entries") + + if len(self.stops) > MAX_GRADIENT_COLORS: + self.stops = self.stops[:MAX_GRADIENT_COLORS] + print(f"Warning: Gradient stops truncated to {MAX_GRADIENT_COLORS} entries") + + if not len(self.stops): + color_count = min(len(self.colors), MAX_GRADIENT_COLORS) + self.stops = [i / max(1, color_count - 1) for i in range(color_count)] + + +FRAGMENT_SHADER = GL_VERSION + """ +in vec2 fragTexCoord; +out vec4 finalColor; + +uniform vec4 fillColor; + +// Gradient line defined in *screen pixels* +uniform int useGradient; +uniform vec2 gradientStart; // e.g. vec2(0, 0) +uniform vec2 gradientEnd; // e.g. vec2(0, screenHeight) +uniform vec4 gradientColors[20]; +uniform float gradientStops[20]; +uniform int gradientColorCount; + +vec4 getGradientColor(vec2 p) { + // Compute t from screen-space position + vec2 d = gradientStart - gradientEnd; + float len2 = max(dot(d, d), 1e-6); + float t = clamp(dot(p - gradientEnd, d) / len2, 0.0, 1.0); + + // Clamp to range + float t0 = gradientStops[0]; + float tn = gradientStops[gradientColorCount-1]; + if (t <= t0) return gradientColors[0]; + if (t >= tn) return gradientColors[gradientColorCount-1]; + + for (int i = 0; i < gradientColorCount - 1; i++) { + float a = gradientStops[i]; + float b = gradientStops[i+1]; + if (t >= a && t <= b) { + float k = (t - a) / max(b - a, 1e-6); + return mix(gradientColors[i], gradientColors[i+1], k); + } + } + + return gradientColors[gradientColorCount-1]; +} + +void main() { + // TODO: do proper antialiasing + finalColor = useGradient == 1 ? getGradientColor(gl_FragCoord.xy) : fillColor; +} +""" + +# Default vertex shader +VERTEX_SHADER = GL_VERSION + """ +in vec3 vertexPosition; +in vec2 vertexTexCoord; +out vec2 fragTexCoord; +uniform mat4 mvp; + +void main() { + fragTexCoord = vertexTexCoord; + gl_Position = mvp * vec4(vertexPosition, 1.0); +} +""" + +UNIFORM_INT = rl.ShaderUniformDataType.SHADER_UNIFORM_INT +UNIFORM_FLOAT = rl.ShaderUniformDataType.SHADER_UNIFORM_FLOAT +UNIFORM_VEC2 = rl.ShaderUniformDataType.SHADER_UNIFORM_VEC2 +UNIFORM_VEC4 = rl.ShaderUniformDataType.SHADER_UNIFORM_VEC4 + + +class ShaderState: + _instance: Any = None + + @classmethod + def get_instance(cls): + if cls._instance is None: + cls._instance = cls() + return cls._instance + + def __init__(self): + if ShaderState._instance is not None: + raise Exception("This class is a singleton. Use get_instance() instead.") + + self.initialized = False + self.shader = None + + # Shader uniform locations + self.locations = { + 'fillColor': None, + 'useGradient': None, + 'gradientStart': None, + 'gradientEnd': None, + 'gradientColors': None, + 'gradientStops': None, + 'gradientColorCount': None, + 'mvp': None, + } + + # Pre-allocated FFI objects + self.fill_color_ptr = rl.ffi.new("float[]", [0.0, 0.0, 0.0, 0.0]) + self.use_gradient_ptr = rl.ffi.new("int[]", [0]) + self.color_count_ptr = rl.ffi.new("int[]", [0]) + self.gradient_colors_ptr = rl.ffi.new("float[]", MAX_GRADIENT_COLORS * 4) + self.gradient_stops_ptr = rl.ffi.new("float[]", MAX_GRADIENT_COLORS) + + def initialize(self): + if self.initialized: + return + + self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAGMENT_SHADER) + + # Cache all uniform locations + for uniform in self.locations.keys(): + self.locations[uniform] = rl.get_shader_location(self.shader, uniform) + + # Orthographic MVP (origin top-left) + proj = rl.matrix_ortho(0, gui_app.width, gui_app.height, 0, -1, 1) + rl.set_shader_value_matrix(self.shader, self.locations['mvp'], proj) + + self.initialized = True + + def cleanup(self): + if not self.initialized: + return + if self.shader: + rl.unload_shader(self.shader) + self.shader = None + + self.initialized = False + + +def _configure_shader_color(state: ShaderState, color: Optional[rl.Color], + gradient: Gradient | None, origin_rect: rl.Rectangle): + assert (color is not None) != (gradient is not None), "Either color or gradient must be provided" + + use_gradient = 1 if (gradient is not None and len(gradient.colors) >= 1) else 0 + state.use_gradient_ptr[0] = use_gradient + rl.set_shader_value(state.shader, state.locations['useGradient'], state.use_gradient_ptr, UNIFORM_INT) + + if use_gradient: + gradient = cast(Gradient, gradient) + state.color_count_ptr[0] = len(gradient.colors) + for i in range(len(gradient.colors)): + c = gradient.colors[i] + base = i * 4 + state.gradient_colors_ptr[base:base + 4] = [c.r / 255.0, c.g / 255.0, c.b / 255.0, c.a / 255.0] + rl.set_shader_value_v(state.shader, state.locations['gradientColors'], state.gradient_colors_ptr, UNIFORM_VEC4, len(gradient.colors)) + + for i in range(len(gradient.stops)): + s = float(gradient.stops[i]) + state.gradient_stops_ptr[i] = 0.0 if s < 0.0 else 1.0 if s > 1.0 else s + rl.set_shader_value_v(state.shader, state.locations['gradientStops'], state.gradient_stops_ptr, UNIFORM_FLOAT, len(gradient.stops)) + rl.set_shader_value(state.shader, state.locations['gradientColorCount'], state.color_count_ptr, UNIFORM_INT) + + # Map normalized start/end to screen pixels + start_vec = rl.Vector2(origin_rect.x + gradient.start[0] * origin_rect.width, origin_rect.y + gradient.start[1] * origin_rect.height) + end_vec = rl.Vector2(origin_rect.x + gradient.end[0] * origin_rect.width, origin_rect.y + gradient.end[1] * origin_rect.height) + rl.set_shader_value(state.shader, state.locations['gradientStart'], start_vec, UNIFORM_VEC2) + rl.set_shader_value(state.shader, state.locations['gradientEnd'], end_vec, UNIFORM_VEC2) + else: + color = color or rl.WHITE + state.fill_color_ptr[0:4] = [color.r / 255.0, color.g / 255.0, color.b / 255.0, color.a / 255.0] + rl.set_shader_value(state.shader, state.locations['fillColor'], state.fill_color_ptr, UNIFORM_VEC4) + + +def triangulate(pts: np.ndarray) -> list[tuple[float, float]]: + """Only supports simple polygons with two chains (ribbon).""" + + # TODO: consider deduping close screenspace points + # interleave points to produce a triangle strip + # assert len(pts) % 2 == 0, "Interleaving expects even number of points" + if len(pts) % 2 != 0: + pts = pts[:-1] + + tri_strip = [] + for i in range(len(pts) // 2): + tri_strip.append(pts[i]) + tri_strip.append(pts[-i - 1]) + + return cast(list, np.array(tri_strip).tolist()) + + +def draw_polygon(origin_rect: rl.Rectangle, points: np.ndarray, + color: Optional[rl.Color] = None, gradient: Gradient | None = None): + + """ + Draw a ribbon polygon (two chains) with a triangle strip and gradient. + - Input must be [L0..Lk-1, Rk-1..R0], even count, no crossings/holes. + """ + if len(points) < 3: + return + + # Initialize shader on-demand + state = ShaderState.get_instance() + state.initialize() + + # Ensure (N,2) float32 contiguous array + pts = np.ascontiguousarray(points, dtype=np.float32) + assert pts.ndim == 2 and pts.shape[1] == 2, "points must be (N,2)" + + # Configure gradient shader + _configure_shader_color(state, color, gradient, origin_rect) + + # Triangulate via interleaving + tri_strip = triangulate(pts) + + # Draw strip, color here doesn't matter + rl.begin_shader_mode(state.shader) + rl.draw_triangle_strip(tri_strip, len(tri_strip), rl.WHITE) + rl.end_shader_mode() + + +def cleanup_shader_resources(): + state = ShaderState.get_instance() + state.cleanup() diff --git a/system/ui/lib/tests/test_handle_state_change.py b/system/ui/lib/tests/test_handle_state_change.py new file mode 100644 index 00000000000000..69aae6fdf31e5f --- /dev/null +++ b/system/ui/lib/tests/test_handle_state_change.py @@ -0,0 +1,906 @@ +"""Tests for WifiManager._handle_state_change. + +Tests the state machine in isolation by constructing a WifiManager with mocked +DBus, then calling _handle_state_change directly with NM state transitions. +""" +import pytest +from jeepney.low_level import MessageType +from pytest_mock import MockerFixture + +from openpilot.system.ui.lib.networkmanager import NMDeviceState, NMDeviceStateReason +from openpilot.system.ui.lib.wifi_manager import WifiManager, WifiState, ConnectStatus + + +def _make_wm(mocker: MockerFixture, connections=None): + """Create a WifiManager with only the fields _handle_state_change touches.""" + mocker.patch.object(WifiManager, '_initialize') + wm = WifiManager.__new__(WifiManager) + wm._exit = True # prevent stop() from doing anything in __del__ + wm._conn_monitor = mocker.MagicMock() + wm._connections = dict(connections or {}) + wm._wifi_state = WifiState() + wm._user_epoch = 0 + wm._callback_queue = [] + wm._need_auth = [] + wm._activated = [] + wm._update_networks = mocker.MagicMock() + wm._update_active_connection_info = mocker.MagicMock() + wm._get_active_wifi_connection = mocker.MagicMock(return_value=(None, None)) + return wm + + +def fire(wm: WifiManager, new_state: int, prev_state: int = NMDeviceState.UNKNOWN, + reason: int = NMDeviceStateReason.NONE) -> None: + """Feed a state change into the handler.""" + wm._handle_state_change(new_state, prev_state, reason) + + +def fire_wpa_connect(wm: WifiManager) -> None: + """WPA handshake then IP negotiation through ACTIVATED, as seen on device.""" + fire(wm, NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.IP_CONFIG) + fire(wm, NMDeviceState.IP_CHECK) + fire(wm, NMDeviceState.SECONDARIES) + fire(wm, NMDeviceState.ACTIVATED) + + +# --------------------------------------------------------------------------- +# Basic transitions +# --------------------------------------------------------------------------- + +class TestDisconnected: + def test_generic_disconnect_clears_state(self, mocker): + wm = _make_wm(mocker) + wm._wifi_state = WifiState(ssid="Net", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.UNKNOWN) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + wm._update_networks.assert_not_called() + + def test_new_activation_is_noop(self, mocker): + """NEW_ACTIVATION means NM is about to connect to another network — don't clear.""" + wm = _make_wm(mocker) + wm._wifi_state = WifiState(ssid="OldNet", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.NEW_ACTIVATION) + + assert wm._wifi_state.ssid == "OldNet" + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + def test_connection_removed_keeps_other_connecting(self, mocker): + """Forget A while connecting to B: CONNECTION_REMOVED for A must not clear B.""" + wm = _make_wm(mocker, connections={"B": "/path/B"}) + wm._set_connecting("B") + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.CONNECTION_REMOVED) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_connection_removed_clears_when_forgotten(self, mocker): + """Forget A: A is no longer in _connections, so state should clear.""" + wm = _make_wm(mocker, connections={}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.CONNECTION_REMOVED) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + +class TestDeactivating: + def test_deactivating_noop_for_non_connection_removed(self, mocker): + """DEACTIVATING with non-CONNECTION_REMOVED reason is a no-op.""" + wm = _make_wm(mocker) + wm._wifi_state = WifiState(ssid="Net", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.USER_REQUESTED) + + assert wm._wifi_state.ssid == "Net" + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + @pytest.mark.parametrize("status, expected_clears", [ + (ConnectStatus.CONNECTED, True), + (ConnectStatus.CONNECTING, False), + ]) + def test_deactivating_connection_removed(self, mocker, status, expected_clears): + """DEACTIVATING(CONNECTION_REMOVED) clears CONNECTED but preserves CONNECTING. + + CONNECTED: forgetting the current network. The forgotten callback fires between + DEACTIVATING and DISCONNECTED — must clear here so the UI doesn't flash "connected" + after the eager _network_forgetting flag resets. + + CONNECTING: forget A while connecting to B. DEACTIVATING fires for A's removal, + but B's CONNECTING state must be preserved. + """ + wm = _make_wm(mocker, connections={"B": "/path/B"}) + wm._wifi_state = WifiState(ssid="B" if status == ConnectStatus.CONNECTING else "A", status=status) + + fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.CONNECTION_REMOVED) + + if expected_clears: + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + else: + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + +class TestPrepareConfig: + def test_user_initiated_skips_dbus_lookup(self, mocker): + """User called _set_connecting('B') — PREPARE must not overwrite via DBus. + + Reproduced on device: rapidly tap A then B. PREPARE's DBus lookup returns A's + stale conn_path, overwriting ssid to A for 1-2 frames. UI shows the "connecting" + indicator briefly jump to the wrong network row then back. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._set_connecting("B") + wm._get_active_wifi_connection.return_value = ("/path/A", {}) + + fire(wm, NMDeviceState.PREPARE) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + wm._get_active_wifi_connection.assert_not_called() + + @pytest.mark.parametrize("state", [NMDeviceState.PREPARE, NMDeviceState.CONFIG]) + def test_auto_connect_looks_up_ssid(self, mocker, state): + """Auto-connection (ssid=None): PREPARE and CONFIG must look up ssid from NM.""" + wm = _make_wm(mocker, connections={"AutoNet": "/path/auto"}) + wm._get_active_wifi_connection.return_value = ("/path/auto", {}) + + fire(wm, state) + + assert wm._wifi_state.ssid == "AutoNet" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_auto_connect_dbus_fails(self, mocker): + """Auto-connection but DBus returns None: ssid stays None, status CONNECTING.""" + wm = _make_wm(mocker) + + fire(wm, NMDeviceState.PREPARE) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_auto_connect_conn_path_not_in_connections(self, mocker): + """DBus returns a conn_path that doesn't match any known connection.""" + wm = _make_wm(mocker, connections={"Other": "/path/other"}) + wm._get_active_wifi_connection.return_value = ("/path/unknown", {}) + + fire(wm, NMDeviceState.PREPARE) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + +class TestNeedAuth: + def test_wrong_password_fires_callback(self, mocker): + """NEED_AUTH+SUPPLICANT_DISCONNECT from CONFIG = real wrong password.""" + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._set_connecting("SecNet") + + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert len(wm._callback_queue) == 1 + wm.process_callbacks() + cb.assert_called_once_with("SecNet") + + def test_failed_no_secrets_fires_callback(self, mocker): + """FAILED+NO_SECRETS = wrong password (weak/gone network). + + Confirmed on device: also fires when a hotspot turns off during connection. + NM can't complete the WPA handshake (AP vanished) and reports NO_SECRETS + rather than SSID_NOT_FOUND. The need_auth callback fires, so the UI shows + "wrong password" — a false positive, but same signal path. + + Real device sequence (new connection, hotspot turned off immediately): + PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → NEED_AUTH(CONFIG, NONE) → FAILED(NEED_AUTH, NO_SECRETS) → DISCONNECTED(FAILED, NONE) + """ + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._set_connecting("WeakNet") + + fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NO_SECRETS) + + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert len(wm._callback_queue) == 1 + wm.process_callbacks() + cb.assert_called_once_with("WeakNet") + + def test_need_auth_then_failed_no_double_fire(self, mocker): + """Real device sends NEED_AUTH(SUPPLICANT_DISCONNECT) then FAILED(NO_SECRETS) back-to-back. + + The first clears ssid, so the second must not fire a duplicate callback. + Real device sequence: NEED_AUTH(CONFIG, SUPPLICANT_DISCONNECT) → FAILED(NEED_AUTH, NO_SECRETS) + """ + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._set_connecting("BadPass") + + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + assert len(wm._callback_queue) == 1 + + fire(wm, NMDeviceState.FAILED, prev_state=NMDeviceState.NEED_AUTH, + reason=NMDeviceStateReason.NO_SECRETS) + assert len(wm._callback_queue) == 1 # no duplicate + + wm.process_callbacks() + cb.assert_called_once_with("BadPass") + + def test_no_ssid_no_callback(self, mocker): + """If ssid is None when NEED_AUTH fires, no callback enqueued.""" + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + + fire(wm, NMDeviceState.NEED_AUTH, reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + + assert len(wm._callback_queue) == 0 + + def test_interrupted_auth_ignored(self, mocker): + """Switching A->B: NEED_AUTH from A (prev=DISCONNECTED) must not fire callback. + + Reproduced on device: rapidly switching between two saved networks can trigger a + rare false "wrong password" dialog for the previous network, even though both have + correct passwords. The stale NEED_AUTH has prev_state=DISCONNECTED (not CONFIG). + """ + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._set_connecting("A") + wm._set_connecting("B") + + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.DISCONNECTED, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + assert len(wm._callback_queue) == 0 + + +class TestPassthroughStates: + """NEED_AUTH (generic), IP_CONFIG, IP_CHECK, SECONDARIES, FAILED (generic) are no-ops.""" + + @pytest.mark.parametrize("state", [ + NMDeviceState.NEED_AUTH, + NMDeviceState.IP_CONFIG, + NMDeviceState.IP_CHECK, + NMDeviceState.SECONDARIES, + NMDeviceState.FAILED, + ]) + def test_passthrough_is_noop(self, mocker, state): + wm = _make_wm(mocker) + wm._set_connecting("Net") + + fire(wm, state, reason=NMDeviceStateReason.NONE) + + assert wm._wifi_state.ssid == "Net" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + assert len(wm._callback_queue) == 0 + + +class TestActivated: + def test_sets_connected(self, mocker): + """ACTIVATED sets status to CONNECTED and fires callback.""" + wm = _make_wm(mocker, connections={"MyNet": "/path/mynet"}) + cb = mocker.MagicMock() + wm.add_callbacks(activated=cb) + wm._set_connecting("MyNet") + wm._get_active_wifi_connection.return_value = ("/path/mynet", {}) + + fire(wm, NMDeviceState.ACTIVATED) + + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "MyNet" + assert len(wm._callback_queue) == 1 + wm.process_callbacks() + cb.assert_called_once() + + def test_conn_path_none_still_connected(self, mocker): + """ACTIVATED but DBus returns None: status CONNECTED, ssid unchanged.""" + wm = _make_wm(mocker) + wm._set_connecting("MyNet") + + fire(wm, NMDeviceState.ACTIVATED) + + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "MyNet" + + def test_activated_side_effects(self, mocker): + """ACTIVATED persists the volatile connection to disk and updates active connection info.""" + wm = _make_wm(mocker, connections={"Net": "/path/net"}) + wm._set_connecting("Net") + wm._get_active_wifi_connection.return_value = ("/path/net", {}) + + fire(wm, NMDeviceState.ACTIVATED) + + wm._conn_monitor.send_and_get_reply.assert_called_once() + wm._update_active_connection_info.assert_called_once() + wm._update_networks.assert_not_called() + + +# --------------------------------------------------------------------------- +# Thread races: _set_connecting on main thread vs _handle_state_change on monitor thread. +# Uses side_effect on the DBus mock to simulate _set_connecting running mid-handler. +# The epoch counter detects that a user action occurred during the slow DBus call +# and discards the stale update. +# --------------------------------------------------------------------------- +# The deterministic fixes (skip DBus lookup when ssid already set, prev_state guard +# on NEED_AUTH, DEACTIVATING clears CONNECTED on CONNECTION_REMOVED, CONNECTION_REMOVED +# guard) shrink these race windows significantly. The epoch counter closes the +# remaining gaps. + +class TestThreadRaces: + def test_prepare_race_user_tap_during_dbus(self, mocker): + """User taps B while PREPARE's DBus call is in flight for auto-connect. + + Monitor thread reads wifi_state (ssid=None), starts DBus call. + Main thread: _set_connecting("B"). Monitor thread writes back stale ssid from DBus. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + + def user_taps_b_during_dbus(*args, **kwargs): + wm._set_connecting("B") + return ("/path/A", {}) + + wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus + + fire(wm, NMDeviceState.PREPARE) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_activated_race_user_tap_during_dbus(self, mocker): + """User taps B right as A finishes connecting (ACTIVATED handler running). + + Monitor thread reads wifi_state (A, CONNECTING), starts DBus call. + Main thread: _set_connecting("B"). Monitor thread writes (A, CONNECTED), losing B. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._set_connecting("A") + + def user_taps_b_during_dbus(*args, **kwargs): + wm._set_connecting("B") + return ("/path/A", {}) + + wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus + + fire(wm, NMDeviceState.ACTIVATED) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_init_wifi_state_race_user_tap_during_dbus(self, mocker): + """User taps B while _init_wifi_state's DBus calls are in flight. + + _init_wifi_state runs from set_active(True) or worker error paths. It does + 2 DBus calls (device State property + _get_active_wifi_connection) then + unconditionally writes _wifi_state. If the user taps a network during those + calls, _set_connecting("B") is overwritten with stale NM ground truth. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._wifi_device = "/dev/wifi0" + wm._router_main = mocker.MagicMock() + + state_reply = mocker.MagicMock() + state_reply.body = [('u', NMDeviceState.ACTIVATED)] + wm._router_main.send_and_get_reply.return_value = state_reply + + def user_taps_b_during_dbus(*args, **kwargs): + wm._set_connecting("B") + return ("/path/A", {}) + + wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus + + wm._init_wifi_state() + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + +# --------------------------------------------------------------------------- +# Full sequences (NM signal order from real devices) +# --------------------------------------------------------------------------- + +class TestFullSequences: + def test_normal_connect(self, mocker): + """User connects to saved network: full happy path. + + Real device sequence (switching from another connected network): + DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) + PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG + → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED + """ + wm = _make_wm(mocker, connections={"Home": "/path/home"}) + wm._get_active_wifi_connection.return_value = ("/path/home", {}) + + wm._set_connecting("Home") + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) + fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.CONFIG) + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.IP_CONFIG) + fire(wm, NMDeviceState.IP_CHECK) + fire(wm, NMDeviceState.SECONDARIES) + fire(wm, NMDeviceState.ACTIVATED) + + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "Home" + + def test_wrong_password_then_retry(self, mocker): + """Wrong password → NEED_AUTH → FAILED → NM auto-reconnects to saved network. + + Confirmed on device: wrong password for Shane's iPhone, NM auto-connected to unifi. + + Real device sequence (switching from a connected network): + DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) ← WPA handshake + → PREPARE(NEED_AUTH, NONE) → CONFIG + → NEED_AUTH(CONFIG, SUPPLICANT_DISCONNECT) ← wrong password + → FAILED(NEED_AUTH, NO_SECRETS) ← NM gives up + → DISCONNECTED(FAILED, NONE) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED ← auto-reconnect to other saved network + """ + wm = _make_wm(mocker, connections={"Sec": "/path/sec"}) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + + wm._set_connecting("Sec") + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) + fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.CONFIG) + + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert len(wm._callback_queue) == 1 + + # FAILED(NO_SECRETS) follows but ssid is already cleared — no double-fire + fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NO_SECRETS) + assert len(wm._callback_queue) == 1 + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.FAILED) + + # Retry + wm._callback_queue.clear() + wm._set_connecting("Sec") + wm._get_active_wifi_connection.return_value = ("/path/sec", {}) + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + def test_switch_saved_networks(self, mocker): + """Switch from A to B (both saved): NM signal sequence from real device. + + Real device sequence: + DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG + → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + wm._get_active_wifi_connection.return_value = ("/path/B", {}) + + wm._set_connecting("B") + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.NEW_ACTIVATION) + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.NEW_ACTIVATION) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "B" + + def test_rapid_switch_no_false_wrong_password(self, mocker): + """Switch A→B quickly: A's interrupted NEED_AUTH must NOT show wrong password. + + NOTE: The late NEED_AUTH(DISCONNECTED, SUPPLICANT_DISCONNECT) is common when rapidly + switching between networks with wrong/new passwords. Less common when switching between + saved networks with correct passwords. Not guaranteed — some switches skip it and go + straight from DISCONNECTED to PREPARE. The prev_state is consistently DISCONNECTED + for stale signals, so the prev_state guard reliably distinguishes them. + + Worst-case signal sequence this protects against: + DEACTIVATING(NEW_ACTIVATION) → DISCONNECTED(NEW_ACTIVATION) + → NEED_AUTH(DISCONNECTED, SUPPLICANT_DISCONNECT) ← A's stale auth failure + → PREPARE → CONFIG → ... → ACTIVATED ← B connects + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + wm._get_active_wifi_connection.return_value = ("/path/B", {}) + + wm._set_connecting("B") + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.NEW_ACTIVATION) + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.NEW_ACTIVATION) + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.DISCONNECTED, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + assert len(wm._callback_queue) == 0 + + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + def test_forget_while_connecting(self, mocker): + """Forget the network we're currently connecting to (not yet ACTIVATED). + + Confirmed on device: connected to unifi, tapped Shane's iPhone, then forgot + Shane's iPhone while at CONFIG. NM auto-connected to unifi afterward. + + Real device sequence (switching then forgetting mid-connection): + DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → DEACTIVATING(CONFIG, CONNECTION_REMOVED) ← forget at CONFIG + → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) + → PREPARE → CONFIG → ... → ACTIVATED ← NM auto-connects to other saved network + + Note: DEACTIVATING fires from CONFIG (not ACTIVATED). wifi_state.status is + CONNECTING, so the DEACTIVATING handler is a no-op. DISCONNECTED clears state + (ssid removed from _connections by ConnectionRemoved), then PREPARE recovers + via DBus lookup for the auto-connect. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "Other": "/path/other"}) + wm._get_active_wifi_connection.return_value = ("/path/other", {}) + + wm._set_connecting("A") + + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + assert wm._wifi_state.ssid == "A" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + # User forgets A: ConnectionRemoved processed first, then state changes + del wm._connections["A"] + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.CONFIG, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid == "A" + assert wm._wifi_state.status == ConnectStatus.CONNECTING # DEACTIVATING preserves CONNECTING + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + # NM auto-connects to another saved network + fire(wm, NMDeviceState.PREPARE) + assert wm._wifi_state.ssid == "Other" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "Other" + + def test_forget_connected_network(self, mocker): + """Forget the currently connected network (not switching to another). + + Real device sequence: + DEACTIVATING(ACTIVATED, CONNECTION_REMOVED) → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) + + ConnectionRemoved signal may or may not have been processed before state changes. + Either way, state must clear — we're forgetting what we're connected to, not switching. + """ + wm = _make_wm(mocker, connections={"A": "/path/A"}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + # DISCONNECTED follows — harmless since state is already cleared + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + def test_forget_A_connect_B(self, mocker): + """Forget A while connecting to B: full signal sequence. + + Real device sequence: + DEACTIVATING(ACTIVATED, CONNECTION_REMOVED) → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG + → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED + + Signal order: + 1. User: _set_connecting("B"), forget("A") removes A from _connections + 2. NewConnection for B arrives → _connections["B"] = ... + 3. DEACTIVATING(CONNECTION_REMOVED) — no-op + 4. DISCONNECTED(CONNECTION_REMOVED) — B is in _connections, must not clear + 5. PREPARE → CONFIG → NEED_AUTH → PREPARE → CONFIG → ... → ACTIVATED + """ + wm = _make_wm(mocker, connections={"A": "/path/A"}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + + wm._set_connecting("B") + del wm._connections["A"] + wm._connections["B"] = "/path/B" + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + wm._get_active_wifi_connection.return_value = ("/path/B", {}) + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "B" + + def test_forget_A_connect_B_late_new_connection(self, mocker): + """Forget A, connect B: NewConnection for B arrives AFTER DISCONNECTED. + + This is the worst-case race: B isn't in _connections when DISCONNECTED fires, + so the guard can't protect it and state clears. PREPARE must recover by doing + the DBus lookup (ssid is None at that point). + + Signal order: + 1. User: _set_connecting("B"), forget("A") removes A from _connections + 2. DEACTIVATING(CONNECTION_REMOVED) — B NOT in _connections, should be no-op + 3. DISCONNECTED(CONNECTION_REMOVED) — B STILL NOT in _connections, clears state + 4. NewConnection for B arrives late → _connections["B"] = ... + 5. PREPARE (ssid=None, so DBus lookup recovers) → CONFIG → ACTIVATED + """ + wm = _make_wm(mocker, connections={"A": "/path/A"}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + + wm._set_connecting("B") + del wm._connections["A"] + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + # B not in _connections yet, so state clears — this is the known edge case + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + # NewConnection arrives late + wm._connections["B"] = "/path/B" + wm._get_active_wifi_connection.return_value = ("/path/B", {}) + + # PREPARE recovers: ssid is None so it looks up from DBus + fire(wm, NMDeviceState.PREPARE) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "B" + + def test_auto_connect(self, mocker): + """NM auto-connects (no user action, ssid starts None).""" + wm = _make_wm(mocker, connections={"AutoNet": "/path/auto"}) + wm._get_active_wifi_connection.return_value = ("/path/auto", {}) + + fire(wm, NMDeviceState.PREPARE) + assert wm._wifi_state.ssid == "AutoNet" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "AutoNet" + + def test_network_lost_during_connection(self, mocker): + """Hotspot turned off while connecting (before ACTIVATED). + + Confirmed on device: started new connection to Shane's iPhone, immediately + turned off the hotspot. NM can't complete WPA handshake and reports + FAILED(NO_SECRETS) — same signal as wrong password (false positive). + + Real device sequence: + PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → NEED_AUTH(CONFIG, NONE) → FAILED(NEED_AUTH, NO_SECRETS) → DISCONNECTED(FAILED, NONE) + + Note: no DEACTIVATING, no SUPPLICANT_DISCONNECT. The NEED_AUTH(CONFIG, NONE) is the + normal WPA handshake (not an error). NM gives up with NO_SECRETS because the AP + vanished mid-handshake. + """ + wm = _make_wm(mocker, connections={"Hotspot": "/path/hs"}) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + + wm._set_connecting("Hotspot") + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) + fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.CONFIG) + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + # Second NEED_AUTH(CONFIG, NONE) — NM retries handshake, AP vanishing + fire(wm, NMDeviceState.NEED_AUTH) + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + # NM gives up — reports NO_SECRETS (same as wrong password) + fire(wm, NMDeviceState.FAILED, prev_state=NMDeviceState.NEED_AUTH, + reason=NMDeviceStateReason.NO_SECRETS) + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert len(wm._callback_queue) == 1 + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.FAILED) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + wm.process_callbacks() + cb.assert_called_once_with("Hotspot") + + @pytest.mark.xfail(reason="TODO: FAILED(SSID_NOT_FOUND) should emit error for UI") + def test_ssid_not_found(self, mocker): + """Network drops off while connected — hotspot turned off. + + NM docs: SSID_NOT_FOUND (53) = "The WiFi network could not be found" + + Confirmed on device: connected to Shane's iPhone, then turned off the hotspot. + No DEACTIVATING fires — NM goes straight from ACTIVATED to FAILED(SSID_NOT_FOUND). + NM retries connecting (PREPARE → CONFIG → ... → FAILED(CONFIG, SSID_NOT_FOUND)) + before finally giving up with DISCONNECTED. + + NOTE: turning off a hotspot during initial connection (before ACTIVATED) typically + produces FAILED(NO_SECRETS) instead of SSID_NOT_FOUND (see test_failed_no_secrets). + + Real device sequence (hotspot turned off while connected): + FAILED(ACTIVATED, SSID_NOT_FOUND) → DISCONNECTED(FAILED, NONE) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → FAILED(CONFIG, SSID_NOT_FOUND) → DISCONNECTED(FAILED, NONE) + + The UI error callback mechanism is intentionally deferred — for now just clear state. + """ + wm = _make_wm(mocker, connections={"GoneNet": "/path/gone"}) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + + wm._set_connecting("GoneNet") + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.SSID_NOT_FOUND) + + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert wm._wifi_state.ssid is None + + def test_failed_then_disconnected_clears_state(self, mocker): + """After FAILED, NM always transitions to DISCONNECTED to clean up. + + NM docs: FAILED (120) = "failed to connect, cleaning up the connection request" + Full sequence: ... → FAILED(reason) → DISCONNECTED(NONE) + """ + wm = _make_wm(mocker) + wm._set_connecting("Net") + + fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NONE) + assert wm._wifi_state.status == ConnectStatus.CONNECTING # FAILED(NONE) is a no-op + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.NONE) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + def test_user_requested_disconnect(self, mocker): + """User explicitly disconnects from the network. + + NM docs: USER_REQUESTED (39) = "Device disconnected by user or client" + Expected sequence: DEACTIVATING(USER_REQUESTED) → DISCONNECTED(USER_REQUESTED) + """ + wm = _make_wm(mocker) + wm._wifi_state = WifiState(ssid="MyNet", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.USER_REQUESTED) + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.USER_REQUESTED) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + +# --------------------------------------------------------------------------- +# Worker error recovery: DBus errors in activate/connect re-sync with NM +# --------------------------------------------------------------------------- +# Verified on device: when ActivateConnection returns UnknownConnection error, +# NM emits no state signals. The worker error path is the only recovery point. + +class TestWorkerErrorRecovery: + """Worker threads re-sync with NM via _init_wifi_state on DBus errors, + preserving actual NM state instead of blindly clearing to DISCONNECTED.""" + + def _mock_init_restores(self, wm, mocker, ssid, status): + """Replace _init_wifi_state with a mock that simulates NM reporting the given state.""" + mock = mocker.MagicMock( + side_effect=lambda: setattr(wm, '_wifi_state', WifiState(ssid=ssid, status=status)) + ) + wm._init_wifi_state = mock + return mock + + def test_activate_dbus_error_resyncs(self, mocker): + """ActivateConnection returns DBus error while A is connected. + NM rejects the request — no state signals emitted. Worker must re-read NM + state to discover A is still connected, not clear to DISCONNECTED. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._wifi_device = "/dev/wifi0" + wm._nm = mocker.MagicMock() + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + wm._router_main = mocker.MagicMock() + + error_reply = mocker.MagicMock() + error_reply.header.message_type = MessageType.error + wm._router_main.send_and_get_reply.return_value = error_reply + + mock_init = self._mock_init_restores(wm, mocker, "A", ConnectStatus.CONNECTED) + + wm.activate_connection("B", block=True) + + mock_init.assert_called_once() + assert wm._wifi_state.ssid == "A" + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + def test_connect_to_network_dbus_error_resyncs(self, mocker): + """AddAndActivateConnection2 returns DBus error while A is connected.""" + wm = _make_wm(mocker, connections={"A": "/path/A"}) + wm._wifi_device = "/dev/wifi0" + wm._nm = mocker.MagicMock() + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + wm._router_main = mocker.MagicMock() + wm._forgotten = [] + + error_reply = mocker.MagicMock() + error_reply.header.message_type = MessageType.error + wm._router_main.send_and_get_reply.return_value = error_reply + + mock_init = self._mock_init_restores(wm, mocker, "A", ConnectStatus.CONNECTED) + + # Run worker thread synchronously + workers = [] + mocker.patch('openpilot.system.ui.lib.wifi_manager.threading.Thread', + side_effect=lambda target, **kw: type('T', (), {'start': lambda self: workers.append(target)})()) + + wm.connect_to_network("B", "password123") + workers[-1]() + + mock_init.assert_called_once() + assert wm._wifi_state.ssid == "A" + assert wm._wifi_state.status == ConnectStatus.CONNECTED diff --git a/system/ui/lib/tests/test_tethering_subnet.py b/system/ui/lib/tests/test_tethering_subnet.py new file mode 100644 index 00000000000000..f7fe69a64a0fe7 --- /dev/null +++ b/system/ui/lib/tests/test_tethering_subnet.py @@ -0,0 +1,94 @@ +"""Comma hotspot subnet for the Pre-AP Tesla browser. + +The helpers live in wifi_manager.py. Importing that module also imports +NetworkManager and cereal. When those are not built (a host without capnp), +execute just the subnet functions from the same source so the assertions +still cover the real hotspot block. +""" +import ast +from pathlib import Path +from typing import Any + + +def _load(): + try: + from openpilot.system.ui.lib.wifi_manager import ( + TETHERING_IP_ADDRESS, + TETHERING_PREFIX, + ipv4_shared_address, + tethering_ipv4_setting, + ) + return TETHERING_IP_ADDRESS, TETHERING_PREFIX, ipv4_shared_address, tethering_ipv4_setting + except Exception: + src_path = Path(__file__).resolve().parents[1] / "wifi_manager.py" + tree = ast.parse(src_path.read_text(encoding="utf-8")) + keep = { + "TETHERING_IP_ADDRESS", + "TETHERING_PREFIX", + "_DBUS_SIG_CHARS", + "_dbus_variant", + "tethering_ipv4_setting", + "ipv4_shared_address", + } + + def _name(node): + if isinstance(node, ast.FunctionDef): + return node.name + if isinstance(node, ast.Assign): + target = node.targets[0] + return target.id if isinstance(target, ast.Name) else None + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + return node.target.id + return None + + body = [node for node in tree.body if _name(node) in keep] + module = ast.Module(body=body, type_ignores=[]) + ast.fix_missing_locations(module) + ns = {"Any": Any} + exec(compile(module, str(src_path), "exec"), ns) + return ( + ns["TETHERING_IP_ADDRESS"], + ns["TETHERING_PREFIX"], + ns["ipv4_shared_address"], + ns["tethering_ipv4_setting"], + ) + + +TETHERING_IP_ADDRESS, TETHERING_PREFIX, ipv4_shared_address, tethering_ipv4_setting = _load() + + +def test_hotspot_is_tesla_browser_subnet(): + assert TETHERING_IP_ADDRESS == "100.99.9.1" + assert TETHERING_PREFIX == 24 + block = tethering_ipv4_setting() + assert block["method"] == ("s", "shared") + assert block["gateway"] == ("s", "100.99.9.1") + assert block["never-default"] == ("b", True) + assert ipv4_shared_address(block) == "100.99.9.1" + + +def test_old_hotspot_address_is_detected(): + legacy = { + "method": ("s", "shared"), + "address-data": ("aa{sv}", [[ + ("address", ("s", "192.168.43.1")), + ("prefix", ("u", 24)), + ]]), + "gateway": ("s", "192.168.43.1"), + } + assert ipv4_shared_address(legacy) == "192.168.43.1" + assert ipv4_shared_address(legacy) != TETHERING_IP_ADDRESS + + nm_default = {"method": ("s", "shared"), "gateway": ("s", "10.42.0.1")} + assert ipv4_shared_address(nm_default) == "10.42.0.1" + + # Unpacked dict form, no signature tuples. + plain = {"address-data": [{"address": "100.99.9.1", "prefix": 24}]} + assert ipv4_shared_address(plain) == "100.99.9.1" + + +def test_client_profile_shape_is_not_the_hotspot_block(): + """Infrastructure Wi-Fi stays method=auto. Only the shared block is rewritten.""" + hotspot = tethering_ipv4_setting() + assert hotspot["method"][1] == "shared" + assert "dns-priority" not in hotspot diff --git a/system/ui/lib/text_measure.py b/system/ui/lib/text_measure.py new file mode 100644 index 00000000000000..dee4b419ffc1b5 --- /dev/null +++ b/system/ui/lib/text_measure.py @@ -0,0 +1,36 @@ +import pyray as rl +from openpilot.system.ui.lib.application import FONT_SCALE, font_fallback +from openpilot.system.ui.lib.emoji import find_emoji + +_cache: dict[int, rl.Vector2] = {} + + +def measure_text_cached(font: rl.Font, text: str, font_size: int, spacing: float = 0) -> rl.Vector2: + """Caches text measurements to avoid redundant calculations.""" + font = font_fallback(font) + spacing = round(spacing, 4) + key = hash((font.texture.id, text, font_size, spacing)) + if key in _cache: + return _cache[key] + + # Measure normal characters without emojis, then add standard width for each found emoji + emoji = find_emoji(text) + if emoji: + non_emoji_text = "" + last_index = 0 + for start, end, _ in emoji: + non_emoji_text += text[last_index:start] + last_index = end + non_emoji_text += text[last_index:] + else: + non_emoji_text = text + + result = rl.measure_text_ex(font, non_emoji_text, font_size * FONT_SCALE, spacing) # noqa: TID251 + if emoji: + result.x += len(emoji) * font_size * FONT_SCALE + # If just emoji assume a single line height + if result.y == 0: + result.y = font_size * FONT_SCALE + + _cache[key] = result + return result diff --git a/system/ui/lib/utils.py b/system/ui/lib/utils.py new file mode 100644 index 00000000000000..77035d0da08145 --- /dev/null +++ b/system/ui/lib/utils.py @@ -0,0 +1,18 @@ +import pyray as rl + + +class GuiStyleContext: + def __init__(self, styles: list[tuple[int, int, int]]): + """styles is a list of tuples (control, prop, new_value)""" + self.styles = styles + self.prev_styles: list[tuple[int, int, int]] = [] + + def __enter__(self): + for control, prop, new_value in self.styles: + prev_value = rl.gui_get_style(control, prop) + self.prev_styles.append((control, prop, prev_value)) + rl.gui_set_style(control, prop, new_value) + + def __exit__(self, exc_type, exc_value, traceback): + for control, prop, prev_value in self.prev_styles: + rl.gui_set_style(control, prop, prev_value) diff --git a/system/ui/lib/wifi_manager.py b/system/ui/lib/wifi_manager.py new file mode 100644 index 00000000000000..0cb722fff10637 --- /dev/null +++ b/system/ui/lib/wifi_manager.py @@ -0,0 +1,1029 @@ +import atexit +import threading +import time +import uuid +import subprocess +from collections.abc import Callable +from dataclasses import dataclass, replace +from enum import IntEnum +from typing import Any + +from jeepney import DBusAddress, new_method_call +from jeepney.bus_messages import MatchRule, message_bus +from jeepney.io.blocking import DBusConnection, open_dbus_connection as open_dbus_connection_blocking +from jeepney.io.threading import DBusRouter, open_dbus_connection as open_dbus_connection_threading +from jeepney.low_level import MessageType +from jeepney.wrappers import Properties + +from openpilot.common.swaglog import cloudlog +from openpilot.system.ui.lib.networkmanager import (NM, NM_WIRELESS_IFACE, NM_802_11_AP_SEC_PAIR_WEP40, + NM_802_11_AP_SEC_PAIR_WEP104, NM_802_11_AP_SEC_GROUP_WEP40, + NM_802_11_AP_SEC_GROUP_WEP104, NM_802_11_AP_SEC_KEY_MGMT_PSK, + NM_802_11_AP_SEC_KEY_MGMT_802_1X, NM_802_11_AP_FLAGS_NONE, + NM_802_11_AP_FLAGS_PRIVACY, NM_802_11_AP_FLAGS_WPS, + NM_PATH, NM_IFACE, NM_ACCESS_POINT_IFACE, NM_SETTINGS_PATH, + NM_SETTINGS_IFACE, NM_CONNECTION_IFACE, NM_DEVICE_IFACE, + NM_DEVICE_TYPE_WIFI, NM_ACTIVE_CONNECTION_IFACE, + NM_IP4_CONFIG_IFACE, NM_PROPERTIES_IFACE, NMDeviceState, NMDeviceStateReason) + +try: + from openpilot.common.params import Params +except Exception: + Params = None + +# Pre-AP Tesla MCU browsers load local pages on 100.99.9.x and not on +# the usual 192.168.43.0/24 or 10.42.0.0/24 hotspot ranges. NetworkManager +# persists this profile under system-connections, and UI startup rewrites +# a stale profile so the subnet survives reboot. +TETHERING_IP_ADDRESS = "100.99.9.1" +TETHERING_PREFIX = 24 +DEFAULT_TETHERING_PASSWORD = "swagswagcomma" +_DBUS_SIG_CHARS = set("ybnqiuxtdhsogva{}()") +SIGNAL_QUEUE_SIZE = 10 +SCAN_PERIOD_SECONDS = 5 + +DEBUG = False +_dbus_call_idx = 0 + + +def _dbus_variant(value: Any) -> Any: + """Unwrap a jeepney (signature, value) pair. Leave real tuples alone.""" + if isinstance(value, tuple) and len(value) == 2 and isinstance(value[0], str) and value[0] \ + and all(ch in _DBUS_SIG_CHARS for ch in value[0]): + return value[1] + return value + + +def tethering_ipv4_setting(address: str = TETHERING_IP_ADDRESS, prefix: int = TETHERING_PREFIX) -> dict: + """IPv4 block for the comma hotspot. + + method=shared NATs clients out through whatever default route the comma + already has (LTE or a Wi-Fi uplink). never-default keeps the AP from + replacing that route, so normal Wi-Fi client mode and the modem are unchanged. + """ + return { + 'method': ('s', 'shared'), + 'address-data': ('aa{sv}', [[ + ('address', ('s', address)), + ('prefix', ('u', prefix)), + ]]), + 'gateway': ('s', address), + 'never-default': ('b', True), + } + + +def ipv4_shared_address(ipv4: dict | None) -> str: + """Read the shared hotspot address out of a NetworkManager ipv4 setting.""" + if not isinstance(ipv4, dict): + return "" + data = _dbus_variant(ipv4.get("address-data")) + if isinstance(data, (list, tuple)): + for entry in data: + if isinstance(entry, dict): + addr = _dbus_variant(entry.get("address")) + if isinstance(addr, str) and addr: + return addr + if isinstance(entry, (list, tuple)): + for item in entry: + if isinstance(item, (list, tuple)) and len(item) >= 2 and item[0] == "address": + addr = _dbus_variant(item[1]) + if isinstance(addr, str) and addr: + return addr + gateway = _dbus_variant(ipv4.get("gateway")) + if isinstance(gateway, str): + return gateway + return "" + + +def normalize_ssid(ssid: str) -> str: + return ssid.replace("’", "'") # for iPhone hotspots + + +def _wrap_router(router): + def _wrap(orig): + def wrapper(msg, **kw): + global _dbus_call_idx + _dbus_call_idx += 1 + if DEBUG: + h = msg.header.fields + print(f"[DBUS #{_dbus_call_idx}] {h.get(6, '?')} {h.get(3, '?')} {msg.body}") + return orig(msg, **kw) + return wrapper + router.send_and_get_reply = _wrap(router.send_and_get_reply) + router.send = _wrap(router.send) + + +class SecurityType(IntEnum): + OPEN = 0 + WPA = 1 + WPA2 = 2 + WPA3 = 3 + UNSUPPORTED = 4 + + +class MeteredType(IntEnum): + UNKNOWN = 0 + YES = 1 + NO = 2 + + +def get_security_type(flags: int, wpa_flags: int, rsn_flags: int) -> SecurityType: + wpa_props = wpa_flags | rsn_flags + + # obtained by looking at flags of networks in the office as reported by an Android phone + supports_wpa = (NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104 | NM_802_11_AP_SEC_GROUP_WEP40 | + NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_KEY_MGMT_PSK) + + if (flags == NM_802_11_AP_FLAGS_NONE) or ((flags & NM_802_11_AP_FLAGS_WPS) and not (wpa_props & supports_wpa)): + return SecurityType.OPEN + elif (flags & NM_802_11_AP_FLAGS_PRIVACY) and (wpa_props & supports_wpa) and not (wpa_props & NM_802_11_AP_SEC_KEY_MGMT_802_1X): + return SecurityType.WPA + else: + cloudlog.warning(f"Unsupported network! flags: {flags}, wpa_flags: {wpa_flags}, rsn_flags: {rsn_flags}") + return SecurityType.UNSUPPORTED + + +@dataclass(frozen=True) +class Network: + ssid: str + strength: int + security_type: SecurityType + is_tethering: bool + + @classmethod + def from_dbus(cls, ssid: str, aps: list["AccessPoint"], is_tethering: bool) -> "Network": + # we only want to show the strongest AP for each Network/SSID + strongest_ap = max(aps, key=lambda ap: ap.strength) + security_type = get_security_type(strongest_ap.flags, strongest_ap.wpa_flags, strongest_ap.rsn_flags) + + return cls( + ssid=ssid, + strength=100 if is_tethering else strongest_ap.strength, + security_type=security_type, + is_tethering=is_tethering, + ) + + +@dataclass(frozen=True) +class AccessPoint: + ssid: str + bssid: str + strength: int + flags: int + wpa_flags: int + rsn_flags: int + ap_path: str + + @classmethod + def from_dbus(cls, ap_props: dict[str, tuple[str, Any]], ap_path: str) -> "AccessPoint": + ssid = bytes(ap_props['Ssid'][1]).decode("utf-8", "replace") + bssid = str(ap_props['HwAddress'][1]) + strength = int(ap_props['Strength'][1]) + flags = int(ap_props['Flags'][1]) + wpa_flags = int(ap_props['WpaFlags'][1]) + rsn_flags = int(ap_props['RsnFlags'][1]) + + return cls( + ssid=ssid, + bssid=bssid, + strength=strength, + flags=flags, + wpa_flags=wpa_flags, + rsn_flags=rsn_flags, + ap_path=ap_path, + ) + + +class ConnectStatus(IntEnum): + DISCONNECTED = 0 + CONNECTING = 1 + CONNECTED = 2 + + +@dataclass(frozen=True) +class WifiState: + ssid: str | None = None + status: ConnectStatus = ConnectStatus.DISCONNECTED + + +class WifiManager: + def __init__(self): + self._networks: list[Network] = [] # an unsorted list of available Networks. a Network can be comprised of multiple APs + self._active = True # used to not run when not in settings + self._exit = False + + # DBus connections + try: + self._router_main = DBusRouter(open_dbus_connection_threading(bus="SYSTEM")) # used by scanner / general method calls + _wrap_router(self._router_main) + self._conn_monitor = open_dbus_connection_blocking(bus="SYSTEM") # used by state monitor thread + self._nm = DBusAddress(NM_PATH, bus_name=NM, interface=NM_IFACE) + except FileNotFoundError: + cloudlog.exception("Failed to connect to system D-Bus") + self._router_main = None + self._conn_monitor = None + self._exit = True + + # Store wifi device path + self._wifi_device: str | None = None + + # State + self._connections: dict[str, str] = {} # ssid -> connection path, updated via NM signals + self._wifi_state: WifiState = WifiState() + self._user_epoch: int = 0 + self._ipv4_address: str = "" + self._current_network_metered: MeteredType = MeteredType.UNKNOWN + self._tethering_password: str = "" + self._ipv4_forward = False + + self._last_network_scan: float = 0.0 + self._callback_queue: list[Callable] = [] + + self._tethering_ssid = "weedle" + if Params is not None: + dongle_id = Params().get("DongleId") + if dongle_id: + self._tethering_ssid += "-" + dongle_id[:4] + + # Callbacks + self._need_auth: list[Callable[[str], None]] = [] + self._activated: list[Callable[[], None]] = [] + self._forgotten: list[Callable[[str | None], None]] = [] + self._networks_updated: list[Callable[[list[Network]], None]] = [] + self._disconnected: list[Callable[[], None]] = [] + + self._scan_lock = threading.Lock() + self._scan_thread = threading.Thread(target=self._network_scanner, daemon=True) + self._state_thread = threading.Thread(target=self._monitor_state, daemon=True) + self._initialize() + atexit.register(self.stop) + + def _initialize(self): + def worker(): + self._wait_for_wifi_device() + + # TODO: wait for state thread to start before adding tethering connection, tiny race currently + self._scan_thread.start() + self._state_thread.start() + + self._init_connections() + if Params is not None and self._tethering_ssid not in self._connections: + self._add_tethering_connection() + self._init_connections() + # Correct an already-saved hotspot (old 192.168.43.1 / 10.42.0.1) + # without touching infrastructure or modem profiles. + self._ensure_tethering_subnet() + + self._init_wifi_state() + + self._tethering_password = self._get_tethering_password() + cloudlog.debug("WifiManager initialized") + + threading.Thread(target=worker, daemon=True).start() + + def _init_wifi_state(self, block: bool = True): + def worker(): + if self._wifi_device is None: + cloudlog.warning("No WiFi device found") + return + + epoch = self._user_epoch + + dev_addr = DBusAddress(self._wifi_device, bus_name=NM, interface=NM_DEVICE_IFACE) + dev_state = self._router_main.send_and_get_reply(Properties(dev_addr).get('State')).body[0][1] + + ssid: str | None = None + status = ConnectStatus.DISCONNECTED + if NMDeviceState.PREPARE <= dev_state <= NMDeviceState.SECONDARIES and dev_state != NMDeviceState.NEED_AUTH: + status = ConnectStatus.CONNECTING + elif dev_state == NMDeviceState.ACTIVATED: + status = ConnectStatus.CONNECTED + + conn_path, _ = self._get_active_wifi_connection() + if conn_path: + ssid = next((s for s, p in self._connections.items() if p == conn_path), None) + + # Discard if user acted during DBus calls + if self._user_epoch != epoch: + return + + self._wifi_state = WifiState(ssid=ssid, status=status) + + if block: + worker() + else: + threading.Thread(target=worker, daemon=True).start() + + def add_callbacks(self, need_auth: Callable[[str], None] | None = None, + activated: Callable[[], None] | None = None, + forgotten: Callable[[str], None] | None = None, + networks_updated: Callable[[list[Network]], None] | None = None, + disconnected: Callable[[], None] | None = None): + if need_auth is not None: + self._need_auth.append(need_auth) + if activated is not None: + self._activated.append(activated) + if forgotten is not None: + self._forgotten.append(forgotten) + if networks_updated is not None: + self._networks_updated.append(networks_updated) + if disconnected is not None: + self._disconnected.append(disconnected) + + @property + def networks(self) -> list[Network]: + # Sort by connected/connecting, then known, then strength, then alphabetically. This is a pure UI ordering and should not affect underlying state. + return sorted(self._networks, key=lambda n: (n.ssid != self._wifi_state.ssid, not self.is_connection_saved(n.ssid), -n.strength, n.ssid.lower())) + + @property + def wifi_state(self) -> WifiState: + return self._wifi_state + + @property + def ipv4_address(self) -> str: + return self._ipv4_address + + @property + def current_network_metered(self) -> MeteredType: + return self._current_network_metered + + @property + def connecting_to_ssid(self) -> str | None: + wifi_state = self._wifi_state + return wifi_state.ssid if wifi_state.status == ConnectStatus.CONNECTING else None + + @property + def connected_ssid(self) -> str | None: + wifi_state = self._wifi_state + return wifi_state.ssid if wifi_state.status == ConnectStatus.CONNECTED else None + + @property + def tethering_password(self) -> str: + return self._tethering_password + + def _set_connecting(self, ssid: str | None): + # Called by user action, or sequentially from state change handler + self._user_epoch += 1 + self._wifi_state = WifiState(ssid=ssid, status=ConnectStatus.DISCONNECTED if ssid is None else ConnectStatus.CONNECTING) + + def _enqueue_callbacks(self, cbs: list[Callable], *args): + for cb in cbs: + self._callback_queue.append(lambda _cb=cb: _cb(*args)) + + def process_callbacks(self): + # Call from UI thread to run any pending callbacks + to_run, self._callback_queue = self._callback_queue, [] + for cb in to_run: + cb() + + def set_active(self, active: bool): + self._active = active + + # Update networks and WiFi state (to self-heal) immediately when activating for UI + if active: + self._init_wifi_state(block=False) + self._update_networks(block=False) + + def _monitor_state(self): + # Filter for signals + rules = ( + MatchRule( + type="signal", + interface=NM_DEVICE_IFACE, + member="StateChanged", + path=self._wifi_device, + ), + MatchRule( + type="signal", + interface=NM_SETTINGS_IFACE, + member="NewConnection", + path=NM_SETTINGS_PATH, + ), + MatchRule( + type="signal", + interface=NM_SETTINGS_IFACE, + member="ConnectionRemoved", + path=NM_SETTINGS_PATH, + ), + MatchRule( + type="signal", + interface=NM_PROPERTIES_IFACE, + member="PropertiesChanged", + path=self._wifi_device, + ), + ) + + for rule in rules: + self._conn_monitor.send_and_get_reply(message_bus.AddMatch(rule)) + + with (self._conn_monitor.filter(rules[0], bufsize=SIGNAL_QUEUE_SIZE) as state_q, + self._conn_monitor.filter(rules[1], bufsize=SIGNAL_QUEUE_SIZE) as new_conn_q, + self._conn_monitor.filter(rules[2], bufsize=SIGNAL_QUEUE_SIZE) as removed_conn_q, + self._conn_monitor.filter(rules[3], bufsize=SIGNAL_QUEUE_SIZE) as props_q): + while not self._exit: + try: + self._conn_monitor.recv_messages(timeout=1) + except TimeoutError: + continue + + # Connection added/removed + while len(removed_conn_q): + conn_path = removed_conn_q.popleft().body[0] + self._connection_removed(conn_path) + while len(new_conn_q): + conn_path = new_conn_q.popleft().body[0] + self._new_connection(conn_path) + + # PropertiesChanged on wifi device (LastScan = scan complete) + while len(props_q): + iface, changed, _ = props_q.popleft().body + if iface == NM_WIRELESS_IFACE and 'LastScan' in changed: + self._update_networks() + + # Device state changes + while len(state_q): + new_state, previous_state, change_reason = state_q.popleft().body + + self._handle_state_change(new_state, previous_state, change_reason) + + def _handle_state_change(self, new_state: int, prev_state: int, change_reason: int): + # Thread safety: _wifi_state is read/written by both the monitor thread (this handler) + # and the main thread (_set_connecting via connect/activate). PREPARE/CONFIG and ACTIVATED + # have a read-then-write pattern with a slow DBus call in between — if _set_connecting + # runs mid-call, the handler would overwrite the user's newer state with stale data. + # + # The _user_epoch counter solves this without locks. _set_connecting increments the epoch + # on every user action. Handlers snapshot the epoch before their DBus call and compare + # after: if it changed, a user action occurred during the call and the stale result is + # discarded. Combined with deterministic fixes (skip DBus lookup when ssid already set, + # DEACTIVATING clears CONNECTED on CONNECTION_REMOVED, CONNECTION_REMOVED guard), + # all known race windows are closed. + + # TODO: Handle (FAILED, SSID_NOT_FOUND) and emit for UI to show error + # Happens when network drops off after starting connection + + if new_state == NMDeviceState.DISCONNECTED: + if change_reason == NMDeviceStateReason.NEW_ACTIVATION: + return + + # Guard: forget A while connecting to B fires CONNECTION_REMOVED. Don't clear B's state + # if B is still a known connection. If B hasn't arrived in _connections yet (late + # NewConnection), state clears here but PREPARE recovers via DBus lookup. + if (change_reason == NMDeviceStateReason.CONNECTION_REMOVED and self._wifi_state.ssid and + self._wifi_state.ssid in self._connections): + return + + self._set_connecting(None) + + elif new_state in (NMDeviceState.PREPARE, NMDeviceState.CONFIG): + epoch = self._user_epoch + + if self._wifi_state.ssid is not None: + self._wifi_state = replace(self._wifi_state, status=ConnectStatus.CONNECTING) + return + + # Auto-connection when NetworkManager connects to known networks on its own (ssid=None): look up ssid from NM + wifi_state = replace(self._wifi_state, status=ConnectStatus.CONNECTING) + + conn_path, _ = self._get_active_wifi_connection(self._conn_monitor) + + # Discard if user acted during DBus call + if self._user_epoch != epoch: + return + + if conn_path is None: + cloudlog.warning("Failed to get active wifi connection during PREPARE/CONFIG state") + else: + wifi_state = replace(wifi_state, ssid=next((s for s, p in self._connections.items() if p == conn_path), None)) + + self._wifi_state = wifi_state + + # BAD PASSWORD + # - strong network rejects with NEED_AUTH+SUPPLICANT_DISCONNECT + # - weak/gone network fails with FAILED+NO_SECRETS + # TODO: sometimes on PC it's observed no future signals are fired if mouse is held down blocking wrong password dialog + elif ((new_state == NMDeviceState.NEED_AUTH and change_reason == NMDeviceStateReason.SUPPLICANT_DISCONNECT + and prev_state == NMDeviceState.CONFIG) or + (new_state == NMDeviceState.FAILED and change_reason == NMDeviceStateReason.NO_SECRETS)): + + # prev_state guard: real auth failures come from CONFIG (supplicant handshake). + # Stale NEED_AUTH from a prior connection during network switching arrives with + # prev_state=DISCONNECTED and must be ignored to avoid a false wrong-password callback. + if self._wifi_state.ssid: + self._enqueue_callbacks(self._need_auth, self._wifi_state.ssid) + self._set_connecting(None) + + elif new_state in (NMDeviceState.NEED_AUTH, NMDeviceState.IP_CONFIG, NMDeviceState.IP_CHECK, + NMDeviceState.SECONDARIES, NMDeviceState.FAILED): + pass + + elif new_state == NMDeviceState.ACTIVATED: + # Note that IP address from Ip4Config may not be propagated immediately and could take until the next scan results + epoch = self._user_epoch + wifi_state = replace(self._wifi_state, status=ConnectStatus.CONNECTED) + + conn_path, _ = self._get_active_wifi_connection(self._conn_monitor) + + # Discard if user acted during DBus call + if self._user_epoch != epoch: + return + + if conn_path is None: + cloudlog.warning("Failed to get active wifi connection during ACTIVATED state") + else: + wifi_state = replace(wifi_state, ssid=next((s for s, p in self._connections.items() if p == conn_path), None)) + + self._wifi_state = wifi_state + self._enqueue_callbacks(self._activated) + self._update_active_connection_info() + + # Persist volatile connections (created by AddAndActivateConnection2) to disk + if conn_path is not None: + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + save_reply = self._conn_monitor.send_and_get_reply(new_method_call(conn_addr, 'Save')) + if save_reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to persist connection to disk: {save_reply}") + + elif new_state == NMDeviceState.DEACTIVATING: + # Must clear state when forgetting the currently connected network so the UI + # doesn't flash "connected" after the eager "forgetting..." state resets + # (the forgotten callback fires between DEACTIVATING and DISCONNECTED). + # Only clear CONNECTED — CONNECTING must be preserved for forget-A-connect-B. + if change_reason == NMDeviceStateReason.CONNECTION_REMOVED and self._wifi_state.status == ConnectStatus.CONNECTED: + self._set_connecting(None) + + def _network_scanner(self): + while not self._exit: + if self._active: + if time.monotonic() - self._last_network_scan > SCAN_PERIOD_SECONDS: + self._request_scan() + self._last_network_scan = time.monotonic() + time.sleep(1 / 2.) + + def _wait_for_wifi_device(self): + while not self._exit: + device_path = self._get_adapter(NM_DEVICE_TYPE_WIFI) + if device_path is not None: + self._wifi_device = device_path + break + time.sleep(1) + + def _get_adapter(self, adapter_type: int) -> str | None: + # Return the first NetworkManager device path matching adapter_type + try: + device_paths = self._router_main.send_and_get_reply(new_method_call(self._nm, 'GetDevices')).body[0] + for device_path in device_paths: + dev_addr = DBusAddress(device_path, bus_name=NM, interface=NM_DEVICE_IFACE) + dev_type = self._router_main.send_and_get_reply(Properties(dev_addr).get('DeviceType')).body[0][1] + if dev_type == adapter_type: + return str(device_path) + except Exception as e: + cloudlog.exception(f"Error getting adapter type {adapter_type}: {e}") + return None + + def _init_connections(self) -> None: + settings_addr = DBusAddress(NM_SETTINGS_PATH, bus_name=NM, interface=NM_SETTINGS_IFACE) + known_connections = self._router_main.send_and_get_reply(new_method_call(settings_addr, 'ListConnections')).body[0] + + conns: dict[str, str] = {} + for conn_path in known_connections: + settings = self._get_connection_settings(conn_path) + + if len(settings) == 0: + cloudlog.warning(f'Failed to get connection settings for {conn_path}') + continue + + if "802-11-wireless" in settings: + ssid = settings['802-11-wireless']['ssid'][1].decode("utf-8", "replace") + if ssid != "": + conns[ssid] = conn_path + self._connections = conns + + def _new_connection(self, conn_path: str): + settings = self._get_connection_settings(conn_path) + + if "802-11-wireless" in settings: + ssid = settings['802-11-wireless']['ssid'][1].decode("utf-8", "replace") + if ssid != "": + self._connections[ssid] = conn_path + + def _connection_removed(self, conn_path: str): + self._connections = {ssid: path for ssid, path in self._connections.items() if path != conn_path} + + def _get_active_connections(self, router: DBusConnection | DBusRouter | None = None): + # Returns list of ActiveConnection + if router is None: + router = self._router_main + + return router.send_and_get_reply(Properties(self._nm).get('ActiveConnections')).body[0][1] + + def _get_active_wifi_connection(self, router: DBusConnection | DBusRouter | None = None) -> tuple[str | None, dict | None]: + # Returns first Connection settings path and ActiveConnection props from ActiveConnections with Type 802-11-wireless + if router is None: + router = self._router_main + + for active_conn in self._get_active_connections(router): + conn_addr = DBusAddress(active_conn, bus_name=NM, interface=NM_ACTIVE_CONNECTION_IFACE) + reply = router.send_and_get_reply(Properties(conn_addr).get_all()) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to get active connection properties for {active_conn}: {reply}") + continue + + props = reply.body[0] + + conn_path = props.get('Connection', ('o', '/'))[1] + if props.get('Type', ('s', ''))[1] == '802-11-wireless' and conn_path != '/': + return conn_path, props + + return None, None + + def _get_connection_settings(self, conn_path: str) -> dict: + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(conn_addr, 'GetSettings')) + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to get connection settings: {reply}') + return {} + return dict(reply.body[0]) + + def _add_tethering_connection(self): + connection = { + 'connection': { + 'type': ('s', '802-11-wireless'), + 'uuid': ('s', str(uuid.uuid4())), + 'id': ('s', 'Hotspot'), + 'autoconnect-retries': ('i', 0), + 'interface-name': ('s', 'wlan0'), + 'autoconnect': ('b', False), + }, + '802-11-wireless': { + 'band': ('s', 'bg'), + 'mode': ('s', 'ap'), + 'ssid': ('ay', self._tethering_ssid.encode("utf-8")), + }, + '802-11-wireless-security': { + 'group': ('as', ['ccmp']), + 'key-mgmt': ('s', 'wpa-psk'), + 'pairwise': ('as', ['ccmp']), + 'proto': ('as', ['rsn']), + 'psk': ('s', DEFAULT_TETHERING_PASSWORD), + }, + 'ipv4': tethering_ipv4_setting(), + 'ipv6': {'method': ('s', 'ignore')}, + } + + settings_addr = DBusAddress(NM_SETTINGS_PATH, bus_name=NM, interface=NM_SETTINGS_IFACE) + self._router_main.send_and_get_reply(new_method_call(settings_addr, 'AddConnection', 'a{sa{sv}}', (connection,))) + + def _ensure_tethering_subnet(self): + """Point a saved hotspot profile at TETHERING_IP_ADDRESS. + + AddConnection only runs when the profile is missing, so a comma that + already has the old subnet keeps it until this update. NetworkManager + writes the profile to disk. Client-mode and LTE connections are not + opened here. If the hotspot is up, reactivate so DHCP follows. + """ + if self._router_main is None: + return + conn_path = self._connections.get(self._tethering_ssid) + if conn_path is None: + return + try: + settings = self._get_connection_settings(conn_path) + if len(settings) == 0: + return + current = ipv4_shared_address(settings.get('ipv4') or {}) + if current == TETHERING_IP_ADDRESS: + return + settings['ipv4'] = tethering_ipv4_setting() + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(conn_addr, 'Update', 'a{sa{sv}}', (settings,))) + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to update hotspot subnet: {reply}') + return + cloudlog.warning(f'hotspot subnet set to {TETHERING_IP_ADDRESS}/{TETHERING_PREFIX}') + if self.is_tethering_active(): + self.activate_connection(self._tethering_ssid, block=True) + except Exception: + cloudlog.exception('hotspot subnet update failed') + + def connect_to_network(self, ssid: str, password: str, hidden: bool = False): + self._set_connecting(ssid) + + def worker(): + # Clear all connections that may already exist to the network we are connecting to + self.forget_connection(ssid, block=True) + + connection = { + 'connection': { + 'type': ('s', '802-11-wireless'), + 'uuid': ('s', str(uuid.uuid4())), + 'id': ('s', f'openpilot connection {ssid}'), + 'autoconnect-retries': ('i', 0), + }, + '802-11-wireless': { + 'ssid': ('ay', ssid.encode("utf-8")), + 'hidden': ('b', hidden), + 'mode': ('s', 'infrastructure'), + }, + 'ipv4': { + 'method': ('s', 'auto'), + 'dns-priority': ('i', 600), + }, + 'ipv6': {'method': ('s', 'ignore')}, + } + + if password: + connection['802-11-wireless-security'] = { + 'key-mgmt': ('s', 'wpa-psk'), + 'auth-alg': ('s', 'open'), + 'psk': ('s', password), + } + + # Volatile connection auto-deletes on disconnect (wrong password, user switches networks) + # Persisted to disk on ACTIVATED via Save() + if self._wifi_device is None: + cloudlog.warning("No WiFi device found") + # TODO: expose a failed connection state in the UI + self._init_wifi_state() + return + + reply = self._router_main.send_and_get_reply(new_method_call(self._nm, 'AddAndActivateConnection2', 'a{sa{sv}}ooa{sv}', + (connection, self._wifi_device, "/", {'persist': ('s', 'volatile')}))) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to add and activate connection for {ssid}: {reply}") + # TODO: expose a failed connection state in the UI + self._init_wifi_state() + + threading.Thread(target=worker, daemon=True).start() + + def forget_connection(self, ssid: str, block: bool = False): + def worker(): + conn_path = self._connections.get(ssid, None) + if conn_path is None: + cloudlog.warning(f"Trying to forget unknown connection: {ssid}") + else: + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + self._router_main.send_and_get_reply(new_method_call(conn_addr, 'Delete')) + + self._enqueue_callbacks(self._forgotten, ssid) + + if block: + worker() + else: + threading.Thread(target=worker, daemon=True).start() + + def activate_connection(self, ssid: str, block: bool = False): + self._set_connecting(ssid) + + def worker(): + conn_path = self._connections.get(ssid, None) + if conn_path is None or self._wifi_device is None: + cloudlog.warning(f"Failed to activate connection for {ssid}: conn_path={conn_path}, wifi_device={self._wifi_device}") + # TODO: expose a failed connection state in the UI + self._init_wifi_state() + return + + reply = self._router_main.send_and_get_reply(new_method_call(self._nm, 'ActivateConnection', 'ooo', + (conn_path, self._wifi_device, "/"))) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to activate connection for {ssid}: {reply}") + # TODO: expose a failed connection state in the UI + self._init_wifi_state() + + if block: + worker() + else: + threading.Thread(target=worker, daemon=True).start() + + def _deactivate_connection(self, ssid: str): + for active_conn in self._get_active_connections(): + conn_addr = DBusAddress(active_conn, bus_name=NM, interface=NM_ACTIVE_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(Properties(conn_addr).get('SpecificObject')) + if reply.header.message_type == MessageType.error: + continue # object gone (e.g. rapid connect/disconnect) + + specific_obj_path = reply.body[0][1] + + if specific_obj_path != "/": + ap_addr = DBusAddress(specific_obj_path, bus_name=NM, interface=NM_ACCESS_POINT_IFACE) + ap_reply = self._router_main.send_and_get_reply(Properties(ap_addr).get('Ssid')) + if ap_reply.header.message_type == MessageType.error: + continue # AP gone (e.g. mode switch) + + ap_ssid = bytes(ap_reply.body[0][1]).decode("utf-8", "replace") + + if ap_ssid == ssid: + self._router_main.send_and_get_reply(new_method_call(self._nm, 'DeactivateConnection', 'o', (active_conn,))) + return + + def is_tethering_active(self) -> bool: + # Check ssid, not connected_ssid, to also catch connecting state + return self._wifi_state.ssid == self._tethering_ssid + + def is_connection_saved(self, ssid: str) -> bool: + return ssid in self._connections + + def set_tethering_password(self, password: str): + def worker(): + conn_path = self._connections.get(self._tethering_ssid, None) + if conn_path is None: + cloudlog.warning('No tethering connection found') + return + + settings = self._get_connection_settings(conn_path) + if len(settings) == 0: + cloudlog.warning(f'Failed to get tethering settings for {conn_path}') + return + + settings['802-11-wireless-security']['psk'] = ('s', password) + + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(conn_addr, 'Update', 'a{sa{sv}}', (settings,))) + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to update tethering settings: {reply}') + return + + self._tethering_password = password + if self.is_tethering_active(): + self.activate_connection(self._tethering_ssid, block=True) + + threading.Thread(target=worker, daemon=True).start() + + def _get_tethering_password(self) -> str: + conn_path = self._connections.get(self._tethering_ssid, None) + if conn_path is None: + cloudlog.warning('No tethering connection found') + return '' + + reply = self._router_main.send_and_get_reply(new_method_call( + DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE), + 'GetSecrets', 's', ('802-11-wireless-security',) + )) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to get tethering password: {reply}') + return '' + + secrets = reply.body[0] + if '802-11-wireless-security' not in secrets: + return '' + + return str(secrets['802-11-wireless-security'].get('psk', ('s', ''))[1]) + + def set_ipv4_forward(self, enabled: bool): + self._ipv4_forward = enabled + + def set_tethering_active(self, active: bool): + def worker(): + if active: + self.activate_connection(self._tethering_ssid, block=True) + + if not self._ipv4_forward: + time.sleep(5) + cloudlog.warning("net.ipv4.ip_forward = 0") + subprocess.run(["sudo", "sysctl", "net.ipv4.ip_forward=0"], check=False) + else: + self._deactivate_connection(self._tethering_ssid) + + threading.Thread(target=worker, daemon=True).start() + + def set_current_network_metered(self, metered: MeteredType): + def worker(): + if self.is_tethering_active(): + return + + conn_path, _ = self._get_active_wifi_connection() + if conn_path is None: + cloudlog.warning('No active WiFi connection found') + return + + settings = self._get_connection_settings(conn_path) + + if len(settings) == 0: + cloudlog.warning(f'Failed to get connection settings for {conn_path}') + return + + settings['connection']['metered'] = ('i', int(metered)) + + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(conn_addr, 'Update', 'a{sa{sv}}', (settings,))) + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to update metered settings: {reply}') + + threading.Thread(target=worker, daemon=True).start() + + def _request_scan(self): + if self._wifi_device is None: + cloudlog.warning("No WiFi device found") + return + + wifi_addr = DBusAddress(self._wifi_device, bus_name=NM, interface=NM_WIRELESS_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(wifi_addr, 'RequestScan', 'a{sv}', ({},))) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to request scan: {reply}") + + def _update_networks(self, block: bool = True): + if not self._active: + return + + def worker(): + with self._scan_lock: + if self._wifi_device is None: + cloudlog.warning("No WiFi device found") + return + + # NOTE: AccessPoints property may exclude hidden APs (use GetAllAccessPoints method if needed) + wifi_addr = DBusAddress(self._wifi_device, NM, interface=NM_WIRELESS_IFACE) + wifi_props_reply = self._router_main.send_and_get_reply(Properties(wifi_addr).get_all()) + if wifi_props_reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to get WiFi properties: {wifi_props_reply}") + return + + ap_paths = wifi_props_reply.body[0].get('AccessPoints', ('ao', []))[1] + + aps: dict[str, list[AccessPoint]] = {} + + for ap_path in ap_paths: + ap_addr = DBusAddress(ap_path, NM, interface=NM_ACCESS_POINT_IFACE) + ap_props = self._router_main.send_and_get_reply(Properties(ap_addr).get_all()) + + # some APs have been seen dropping off during iteration + if ap_props.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to get AP properties for {ap_path}") + continue + + try: + ap = AccessPoint.from_dbus(ap_props.body[0], ap_path) + if ap.ssid == "": + continue + + if ap.ssid not in aps: + aps[ap.ssid] = [] + + aps[ap.ssid].append(ap) + except Exception: + # catch all for parsing errors + cloudlog.exception(f"Failed to parse AP properties for {ap_path}") + + self._networks = [Network.from_dbus(ssid, ap_list, ssid == self._tethering_ssid) for ssid, ap_list in aps.items()] + self._update_active_connection_info() + self._enqueue_callbacks(self._networks_updated, self.networks) # sorted + + if block: + worker() + else: + threading.Thread(target=worker, daemon=True).start() + + def _update_active_connection_info(self): + ipv4_address = "" + metered = MeteredType.UNKNOWN + + conn_path, props = self._get_active_wifi_connection() + + if conn_path is not None and props is not None: + # IPv4 address + ip4config_path = props.get('Ip4Config', ('o', '/'))[1] + + if ip4config_path != "/": + ip4config_addr = DBusAddress(ip4config_path, bus_name=NM, interface=NM_IP4_CONFIG_IFACE) + address_data = self._router_main.send_and_get_reply(Properties(ip4config_addr).get('AddressData')).body[0][1] + + for entry in address_data: + if 'address' in entry: + ipv4_address = entry['address'][1] + break + + # Metered status + settings = self._get_connection_settings(conn_path) + + if len(settings) > 0: + metered_prop = settings['connection'].get('metered', ('i', 0))[1] + + if metered_prop == MeteredType.YES: + metered = MeteredType.YES + elif metered_prop == MeteredType.NO: + metered = MeteredType.NO + + self._ipv4_address = ipv4_address + self._current_network_metered = metered + + def __del__(self): + self.stop() + + def stop(self): + if not self._exit: + self._exit = True + if self._scan_thread.is_alive(): + self._scan_thread.join() + if self._state_thread.is_alive(): + self._state_thread.join() + + if self._router_main is not None: + self._router_main.close() + self._router_main.conn.close() + if self._conn_monitor is not None: + self._conn_monitor.close() diff --git a/system/ui/lib/wrap_text.py b/system/ui/lib/wrap_text.py new file mode 100644 index 00000000000000..3fabfbb66bd385 --- /dev/null +++ b/system/ui/lib/wrap_text.py @@ -0,0 +1,107 @@ +import pyray as rl +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.application import font_fallback + + +def _break_long_word(font: rl.Font, word: str, font_size: int, max_width: int, spacing: float = 0) -> list[str]: + if not word: + return [] + + parts = [] + remaining = word + + while remaining: + if measure_text_cached(font, remaining, font_size, spacing).x <= max_width: + parts.append(remaining) + break + + # Binary search for the longest substring that fits + left, right = 1, len(remaining) + best_fit = 1 + + while left <= right: + mid = (left + right) // 2 + substring = remaining[:mid] + width = measure_text_cached(font, substring, font_size, spacing).x + + if width <= max_width: + best_fit = mid + left = mid + 1 + else: + right = mid - 1 + + # Add the part that fits + parts.append(remaining[:best_fit]) + remaining = remaining[best_fit:] + + return parts + + +_cache: dict[int, list[str]] = {} + + +def wrap_text(font: rl.Font, text: str, font_size: int, max_width: int, spacing: float = 0) -> list[str]: + font = font_fallback(font) + spacing = round(spacing, 4) + key = hash((font.texture.id, text, font_size, max_width, spacing)) + if key in _cache: + return _cache[key] + + if not text or max_width <= 0: + return [] + + # Split text by newlines first to preserve explicit line breaks + paragraphs = text.split('\n') + all_lines: list[str] = [] + + for paragraph in paragraphs: + # Handle empty paragraphs (preserve empty lines) + if not paragraph.strip(): + all_lines.append("") + continue + + # Process each paragraph separately + words = paragraph.split() + if not words: + all_lines.append("") + continue + + lines: list[str] = [] + current_line: list[str] = [] + + for word in words: + word_width = measure_text_cached(font, word, font_size, spacing).x + + # Check if word alone exceeds max width (need to break the word) + if word_width > max_width: + # Finish current line if it has content + if current_line: + lines.append(" ".join(current_line)) + current_line = [] + + # Break the long word into parts + lines.extend(_break_long_word(font, word, font_size, max_width, spacing)) + continue + + # Measure the actual joined string to get accurate width (accounts for kerning, etc.) + test_line = " ".join(current_line + [word]) if current_line else word + test_width = measure_text_cached(font, test_line, font_size, spacing).x + + # Check if word fits on current line + if test_width <= max_width: + current_line.append(word) + else: + # Start new line with this word + if current_line: + lines.append(" ".join(current_line)) + current_line = [word] + + # Add remaining words + if current_line: + lines.append(" ".join(current_line)) + + # Add all lines from this paragraph + all_lines.extend(lines) + + _cache[key] = all_lines + return all_lines diff --git a/system/ui/mici/widgets/script_runner_app.py b/system/ui/mici/widgets/script_runner_app.py new file mode 100644 index 00000000000000..19b526d9829d2f --- /dev/null +++ b/system/ui/mici/widgets/script_runner_app.py @@ -0,0 +1,283 @@ +"""Mici full-screen script runner. + +Standalone app by default: ``run()`` owns a ``gui_app`` window. It can also +be embedded via ``prepare()`` / ``render_overlay()`` on an already-open window +(Settings overlay) so the main UI is not drawn underneath. + +The UI is plain raylib at mici-scaled sizes — title and status at the top, +a clipped scrollable text region in the body for instructions (before +start) or live output (after), and a compact action button at the bottom. +No card chrome, no NavScroller. This is a tool, not an onboarding flow. + +States: + READY — instructions visible, primary Start action + RUNNING — output streaming, Exit action (may be disabled by consumer) + COMPLETED — output frozen, Exit action + ERROR — output frozen with red status, Exit action + +Threading: ``append_output`` and ``set_state`` are safe to call from any +thread. Both push onto queues. The render loop drains and mutates UI +objects from one thread only. + +Generic primitive: no NAP, subprocess, or hardware knowledge. The consumer +wires ``on_start`` and ``on_exit`` callbacks and decides what those mean. +Use ``run()`` as a standalone window, or ``prepare()`` + ``render_overlay()`` +as a pushed widget on an already-open ``gui_app``. +""" +import enum +import queue +from collections.abc import Callable + +import pyray as rl + +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets.button import Button, ButtonStyle + + +class ScriptState(enum.IntEnum): + READY = 0 + RUNNING = 1 + COMPLETED = 2 + ERROR = 3 + + +# Mici-scaled constants. The logical canvas is 536x240 on a comma 4 device; +# anything larger than this stops feeling like a tool. +MARGIN_X = 16 +MARGIN_TOP = 10 +MARGIN_BOTTOM = 10 + +TITLE_FONT_SIZE = 24 +STATUS_FONT_SIZE = 16 +BODY_FONT_SIZE = 18 +LINE_HEIGHT = 22 + +BUTTON_W = 120 +BUTTON_H = 36 + +TITLE_BAR_H = TITLE_FONT_SIZE + 8 +BUTTON_BAR_H = BUTTON_H + MARGIN_BOTTOM + +# Lines older than this fall off the back of the output buffer. Practical +# scripts rarely emit more than a few hundred lines; the cap protects the +# render loop in pathological cases. +MAX_OUTPUT_LINES = 500 + + +class MiciScriptRunnerApp: + def __init__( + self, + title: str, + instructions: str, + on_start: Callable[[], None], + on_exit: Callable[[], None], + ): + self._title = title + self._instructions = instructions + self._on_start = on_start + self._on_exit = on_exit + + # State owned by the render thread. + self._state = ScriptState.READY + self._output_lines: list[str] = [] + self._instruction_lines: list[str] = [] # wrapped once after _init_ui + + # Producer threads enqueue here; render thread drains. + self._output_queue: queue.Queue[str] = queue.Queue() + self._state_queue: queue.Queue[ScriptState] = queue.Queue() + + # Initialized in _init_ui after gui_app.init_window. + self._font = None + self._title_font = None + self._scroll_panel: GuiScrollPanel | None = None + self._action_button: Button | None = None + + # ── public api ────────────────────────────────────────────────────────── + + def run(self, window_title: str = "Script Runner") -> None: + gui_app.init_window(window_title) + self.prepare() + for _ in gui_app.render(): + self.render_overlay() + + def prepare(self) -> None: + """Bind fonts/buttons to an already-open gui_app window.""" + self._init_ui() + + def render_overlay(self) -> None: + """Draw one opaque frame. Call from the UI thread only.""" + self._drain_queues() + self._render_frame() + + def append_output(self, line: str) -> None: + """Push a line into the output area. Safe from any thread.""" + self._output_queue.put(line) + + def set_state(self, state: ScriptState) -> None: + """Transition state. Safe from any thread; applied on next frame.""" + self._state_queue.put(state) + + @property + def state(self) -> ScriptState: + return self._state + + # ── internals ─────────────────────────────────────────────────────────── + + def _init_ui(self) -> None: + self._font = gui_app.font(FontWeight.NORMAL) + self._title_font = gui_app.font(FontWeight.BOLD) + self._scroll_panel = GuiScrollPanel() + self._action_button = Button( + "start", + click_callback=self._handle_action, + button_style=ButtonStyle.PRIMARY, + font_size=BODY_FONT_SIZE, + ) + + content_width = gui_app.width - MARGIN_X * 2 + self._instruction_lines = wrap_text( + self._font, self._instructions, BODY_FONT_SIZE, content_width + ) + + def _drain_queues(self) -> None: + assert self._action_button is not None + + new_state = self._state + drained_state = False + while True: + try: + new_state = self._state_queue.get_nowait() + drained_state = True + except queue.Empty: + break + if drained_state and new_state != self._state: + self._state = new_state + self._action_button.set_text("start" if new_state == ScriptState.READY else "exit") + + content_width = gui_app.width - MARGIN_X * 2 + while True: + try: + line = self._output_queue.get_nowait() + except queue.Empty: + break + # Subprocess stdout lines are often longer than the 536px canvas + # (especially Python tracebacks with long file paths). Use the + # framework wrap_text — it breaks single long unspaceable words + # (paths, urls) at the character level, which our paragraph-level + # split-on-spaces wouldn't catch. + wrapped = wrap_text(self._font, line, BODY_FONT_SIZE, content_width) + if wrapped: + self._output_lines.extend(wrapped) + else: + self._output_lines.append("") + if len(self._output_lines) > MAX_OUTPUT_LINES: + self._output_lines = self._output_lines[-MAX_OUTPUT_LINES:] + + # Universal: action button disabled while RUNNING. Matches the tici + # runner's behavior — scripts can't be canceled mid-execution. + self._action_button.set_enabled(self._state != ScriptState.RUNNING) + + def _render_frame(self) -> None: + rect = rl.Rectangle(0, 0, gui_app.width, gui_app.height) + rl.draw_rectangle_rec(rect, rl.Color(20, 20, 20, 255)) + + title_y = MARGIN_TOP + rl.draw_text_ex(self._title_font, self._title, + rl.Vector2(MARGIN_X, title_y), + TITLE_FONT_SIZE, 0, rl.WHITE) + + status = _status_text(self._state) + if status: + status_w = measure_text_cached(self._font, status, STATUS_FONT_SIZE).x + status_y = title_y + (TITLE_FONT_SIZE - STATUS_FONT_SIZE) // 2 + rl.draw_text_ex(self._font, status, + rl.Vector2(rect.width - MARGIN_X - status_w, status_y), + STATUS_FONT_SIZE, 0, _status_color(self._state)) + + sep_y = title_y + TITLE_FONT_SIZE + 4 + rl.draw_line_ex( + rl.Vector2(MARGIN_X, sep_y), + rl.Vector2(rect.width - MARGIN_X, sep_y), + 1, rl.Color(80, 80, 80, 255), + ) + + body_top = sep_y + 6 + body_bottom = rect.height - BUTTON_BAR_H - 4 + body_rect = rl.Rectangle(MARGIN_X, body_top, + rect.width - 2 * MARGIN_X, + body_bottom - body_top) + + lines = self._instruction_lines if self._state == ScriptState.READY else self._output_lines + self._render_text_block(body_rect, lines) + + button_y = rect.height - MARGIN_BOTTOM - BUTTON_H + button_x = rect.width - MARGIN_X - BUTTON_W + assert self._action_button is not None + self._action_button.render(rl.Rectangle(button_x, button_y, BUTTON_W, BUTTON_H)) + + def _render_text_block(self, body_rect: rl.Rectangle, lines: list[str]) -> None: + assert self._scroll_panel is not None + + content_h = len(lines) * LINE_HEIGHT + content_rect = rl.Rectangle(0, 0, body_rect.width, content_h) + + # Output streams in; auto-pin to bottom when it would otherwise be + # offscreen. Instructions don't grow after init, so this pin is mostly + # relevant in RUNNING/COMPLETED/ERROR states. + if content_h > body_rect.height and self._state != ScriptState.READY: + self._scroll_panel._offset_filter_y.x = -(content_h - body_rect.height) + + scroll = self._scroll_panel.update(body_rect, content_rect) + + rl.begin_scissor_mode( + int(body_rect.x), int(body_rect.y), + int(body_rect.width), int(body_rect.height), + ) + for i, line in enumerate(lines): + y = body_rect.y + scroll + i * LINE_HEIGHT + if y + LINE_HEIGHT < body_rect.y or y > body_rect.y + body_rect.height: + continue + color = _line_color(line) + rl.draw_text_ex(self._font, line, + rl.Vector2(body_rect.x, y), + BODY_FONT_SIZE, 0, color) + rl.end_scissor_mode() + + def _handle_action(self) -> None: + if self._state == ScriptState.READY: + self._on_start() + else: + self._on_exit() + + +def _status_text(state: ScriptState) -> str: + return { + ScriptState.READY: "", + ScriptState.RUNNING: "running", + ScriptState.COMPLETED: "completed", + ScriptState.ERROR: "error", + }[state] + + +def _status_color(state: ScriptState) -> rl.Color: + return { + ScriptState.RUNNING: rl.Color(255, 200, 100, 255), + ScriptState.COMPLETED: rl.Color(100, 255, 100, 255), + ScriptState.ERROR: rl.Color(255, 100, 100, 255), + }.get(state, rl.WHITE) + + +def _line_color(line: str) -> rl.Color: + if "[Error" in line or "Error:" in line or line.startswith("[ERROR]"): + return rl.Color(255, 100, 100, 255) + if "[Script completed" in line: + return rl.Color(100, 255, 100, 255) + if line.startswith("***"): + return rl.Color(100, 200, 255, 255) + return rl.WHITE + + +__all__ = ["MiciScriptRunnerApp", "ScriptState"] diff --git a/system/ui/mici_reset.py b/system/ui/mici_reset.py new file mode 100755 index 00000000000000..9cc6e7f3f8ee27 --- /dev/null +++ b/system/ui/mici_reset.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +import os +import sys +import time +import threading +from enum import IntEnum + +import pyray as rl + +from openpilot.system.hardware import HARDWARE, PC +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets.scroller import Scroller +from openpilot.system.ui.mici_setup import GreyBigButton, FailedPage +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationCircleButton + +USERDATA = "/dev/disk/by-partlabel/userdata" +TIMEOUT = 3*60 + + +class ResetMode(IntEnum): + USER_RESET = 0 # user initiated a factory reset from openpilot + RECOVER = 1 # userdata is corrupt for some reason, give a chance to recover + TAP_RESET = 2 # user initiated a factory reset by tapping the screen during boot + + +class ResetFailedPage(FailedPage): + def __init__(self): + super().__init__(None, "reset failed", "reboot to try again", icon="icons_mici/setup/reset_failed.png") + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 # not dismissable + + def _back_enabled(self) -> bool: + return False + + +class ResettingPage(BigDialog): + DOT_STEP = 0.6 + + def __init__(self): + super().__init__("resetting device", "this may take up to\na minute...", + gui_app.texture("icons_mici/setup/factory_reset.png", 64, 64)) + self._show_time = 0.0 + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 # not dismissable + self._show_time = rl.get_time() + + def _back_enabled(self) -> bool: + return False + + def _render(self, _): + t = (rl.get_time() - self._show_time) % (self.DOT_STEP * 2) + dots = "." * min(int(t / (self.DOT_STEP / 4)), 3) + self._card.set_value(f"this may take up to\na minute{dots}") + super()._render(_) + + +class Reset(Scroller): + def __init__(self, mode): + super().__init__() + self._mode = mode + self._previous_active_widget = None + self._reset_failed = False + self._timeout_st = time.monotonic() + + self._resetting_page = ResettingPage() + self._reset_failed_page = ResetFailedPage() + + self._reset_button = BigConfirmationCircleButton("reset &\nerase", gui_app.texture("icons_mici/settings/device/uninstall.png", 70, 70), + self._start_reset, exit_on_confirm=False, red=True) + self._cancel_button = BigConfirmationCircleButton("cancel", gui_app.texture("icons_mici/setup/cancel.png", 64, 64), + gui_app.request_close, exit_on_confirm=False) + self._reboot_button = BigConfirmationCircleButton("reboot\ndevice", gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70), + HARDWARE.reboot, exit_on_confirm=False) + + # show reboot button if in recover mode + self._cancel_button.set_visible(mode != ResetMode.RECOVER) + self._reboot_button.set_visible(mode == ResetMode.RECOVER) + + main_card = GreyBigButton("factory reset", "resetting erases\nall user content & data", + gui_app.texture("icons_mici/setup/factory_reset.png", 64, 64)) + self._scroller.add_widget(main_card) + + if mode != ResetMode.USER_RESET: + self._scroller.add_widget(GreyBigButton("", "Resetting erases all user content & data.")) + if mode == ResetMode.RECOVER: + main_card.set_value("user data partition\ncould not be mounted") + elif mode == ResetMode.TAP_RESET: + main_card.set_value("reset triggered by\ntapping the screen") + + self._scroller.add_widgets([ + GreyBigButton("", "For a deeper reset, go to\nhttps://flash.comma.ai"), + self._cancel_button, + self._reboot_button, + self._reset_button, + ]) + + gui_app.add_nav_stack_tick(self._nav_stack_tick) + + def _do_erase(self): + if PC: + return + + # Removing data and formatting + rm = os.system("sudo rm -rf /data/*") + os.system(f"sudo umount {USERDATA}") + fmt = os.system(f"yes | sudo mkfs.ext4 {USERDATA}") + + if rm == 0 or fmt == 0: + os.system("sudo reboot") + else: + self._reset_failed = True + + def _start_reset(self): + def do_erase_thread(): + threading.Thread(target=self._do_erase, daemon=True).start() + + self._resetting_page.set_shown_callback(do_erase_thread) + gui_app.push_widget(self._resetting_page) + + def _nav_stack_tick(self): + if self._reset_failed: + self._reset_failed = False + gui_app.pop_widgets_to(self, lambda: gui_app.push_widget(self._reset_failed_page)) + + active_widget = gui_app.get_active_widget() + if active_widget != self._previous_active_widget: + self._previous_active_widget = active_widget + self._timeout_st = time.monotonic() + elif self._mode != ResetMode.RECOVER and active_widget != self._resetting_page and (time.monotonic() - self._timeout_st) > TIMEOUT: + exit(0) + + +def main(): + mode = ResetMode.USER_RESET + if len(sys.argv) > 1: + if sys.argv[1] == '--recover': + mode = ResetMode.RECOVER + elif sys.argv[1] == '--tap-reset': + mode = ResetMode.TAP_RESET + + gui_app.init_window("System Reset") + reset = Reset(mode) + gui_app.push_widget(reset) + + for _ in gui_app.render(): + pass + + +if __name__ == "__main__": + main() diff --git a/system/ui/mici_setup.py b/system/ui/mici_setup.py new file mode 100755 index 00000000000000..2a23e4c4fd6a0b --- /dev/null +++ b/system/ui/mici_setup.py @@ -0,0 +1,593 @@ +#!/usr/bin/env python3 +import os +import re +import ssl +import threading +import time +import urllib.request +import urllib.error +from urllib.parse import urlparse +from collections.abc import Callable + +import pyray as rl + +from cereal import log +from openpilot.common.filter_simple import BounceFilter +from openpilot.system.hardware import HARDWARE, TICI +from openpilot.common.realtime import config_realtime_process, set_core_affinity +from openpilot.common.swaglog import cloudlog +from openpilot.common.time_helpers import system_time_valid +from openpilot.common.utils import run_cmd +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.wifi_manager import WifiManager, ConnectStatus +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import Scroller, NavScroller, ITEM_SPACING +from openpilot.system.ui.widgets.slider import LargerSlider +from openpilot.selfdrive.ui.mici.layouts.settings.network import WifiNetworkButton +from openpilot.selfdrive.ui.mici.layouts.settings.network.wifi_ui import WifiUIMici +from openpilot.selfdrive.ui.mici.widgets.dialog import BigInputDialog, BigConfirmationCircleButton +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, GreyBigButton + +NetworkType = log.DeviceState.NetworkType + +OPENPILOT_URL = "https://openpilot.comma.ai" +USER_AGENT = f"AGNOSSetup-{HARDWARE.get_os_version()}" + +INSTALLER_DESTINATION_PATH = "/tmp/installer" +INSTALLER_URL_PATH = "/tmp/installer_url" + + +class NetworkConnectivityMonitor: + def __init__(self, should_check: Callable[[], bool] | None = None): + self.network_connected = threading.Event() + self.wifi_connected = threading.Event() + self.recheck_event = threading.Event() + self._should_check = should_check or (lambda: True) + self._stop_event = threading.Event() + self._last_timesyncd_restart = 0.0 + self._thread: threading.Thread | None = None + + def start(self): + self._stop_event.clear() + if self._thread is None or not self._thread.is_alive(): + self._thread = threading.Thread(target=self._run, daemon=True) + self._thread.start() + + def stop(self): + if self._thread is not None: + self._stop_event.set() + self._thread.join() + self._thread = None + + def reset(self): + self.network_connected.clear() + self.wifi_connected.clear() + + def invalidate(self): + self.recheck_event.set() + self.reset() + + def _run(self): + while not self._stop_event.is_set(): + if self._should_check(): + try: + request = urllib.request.Request(OPENPILOT_URL, method="HEAD") + urllib.request.urlopen(request, timeout=2.0) + + # Discard stale result if invalidated during request + if self.recheck_event.is_set(): + self.recheck_event.clear() + continue + + self.network_connected.set() + if HARDWARE.get_network_type() == NetworkType.wifi: + self.wifi_connected.set() + except urllib.error.URLError as e: + if (isinstance(e.reason, ssl.SSLCertVerificationError) and + not system_time_valid() and + time.monotonic() - self._last_timesyncd_restart > 5): + self._last_timesyncd_restart = time.monotonic() + run_cmd(["sudo", "systemctl", "restart", "systemd-timesyncd"]) + self.reset() + except Exception: + self.reset() + else: + self.reset() + + if self._stop_event.wait(timeout=1.0): + break + + +class StartPage(Widget): + def __init__(self): + super().__init__() + + self._title = UnifiedLabel("start", 64, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), + font_weight=FontWeight.DISPLAY, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + self._start_bg_txt = gui_app.texture("icons_mici/setup/start_button.png", 500, 224, keep_aspect_ratio=False) + self._start_bg_pressed_txt = gui_app.texture("icons_mici/setup/start_button_pressed.png", 500, 224, keep_aspect_ratio=False) + self._scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._click_delay = 0.075 + + def _render(self, rect: rl.Rectangle): + scale = self._scale_filter.update(1.07 if self.is_pressed else 1.0) + base_draw_x = rect.x + (rect.width - self._start_bg_txt.width) / 2 + base_draw_y = rect.y + (rect.height - self._start_bg_txt.height) / 2 + draw_x = base_draw_x + (self._start_bg_txt.width * (1 - scale)) / 2 + draw_y = base_draw_y + (self._start_bg_txt.height * (1 - scale)) / 2 + texture = self._start_bg_pressed_txt if self.is_pressed else self._start_bg_txt + rl.draw_texture_ex(texture, (draw_x, draw_y), 0, scale, rl.WHITE) + + self._title.render(rl.Rectangle(rect.x, rect.y + (draw_y - base_draw_y), rect.width, rect.height)) + + +class SoftwareSelectionPage(NavWidget): + def __init__(self, use_openpilot_callback: Callable, + use_custom_software_callback: Callable): + super().__init__() + + self._openpilot_slider = self._child(LargerSlider("slide to install\nopenpilot", use_openpilot_callback)) + self._openpilot_slider.set_enabled(lambda: self.enabled and not self.is_dismissing) + self._custom_software_slider = self._child(LargerSlider("slide to install\ncustom software", use_custom_software_callback, green=False, shimmer_offset=0.4)) + self._custom_software_slider.set_enabled(lambda: self.enabled and not self.is_dismissing) + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 + + def _update_state(self): + super()._update_state() + if self.is_dismissing: + self.reset() + + def reset(self): + self._openpilot_slider.reset() + self._custom_software_slider.reset() + + def _render(self, rect: rl.Rectangle): + self._openpilot_slider.set_opacity(1.0 - self._custom_software_slider.slider_percentage) + self._custom_software_slider.set_opacity(1.0 - self._openpilot_slider.slider_percentage) + + openpilot_rect = rl.Rectangle( + rect.x + (rect.width - self._openpilot_slider.rect.width) / 2, + rect.y, + self._openpilot_slider.rect.width, + rect.height / 2, + ) + self._openpilot_slider.render(openpilot_rect) + + custom_software_rect = rl.Rectangle( + rect.x + (rect.width - self._custom_software_slider.rect.width) / 2, + rect.y + rect.height / 2, + self._custom_software_slider.rect.width, + rect.height / 2, + ) + self._custom_software_slider.render(custom_software_rect) + + +class CustomSoftwareWarningPage(NavScroller): + def __init__(self, continue_callback: Callable, back_callback: Callable): + super().__init__() + self.set_back_callback(back_callback) + + self._continue_button = BigPillButton("next") + self._continue_button.set_click_callback(continue_callback) + + self._scroller.add_widgets([ + GreyBigButton("caution: installing\n3rd party software", "swipe down to go back", + gui_app.texture("icons_mici/setup/warning.png", 64, 58)), + GreyBigButton("", "• It has not been tested by comma."), + GreyBigButton("", "• It may not comply with safety standards."), + GreyBigButton("", "• It may damage your device and/or vehicle."), + GreyBigButton("how to restore to a\nfactory state later", "https://flash.comma.ai", + gui_app.texture("icons_mici/setup/restore.png", 64, 64)), + self._continue_button, + ]) + + +# TODO: unifi with updater's progress page +class DownloadingPage(NavWidget): + def __init__(self): + super().__init__() + + self._title_label = UnifiedLabel("downloading...", 64, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), + font_weight=FontWeight.DISPLAY) + self._progress_label = UnifiedLabel("", 132, text_color=rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)), + font_weight=FontWeight.ROMAN, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + self._progress = 0 + + def _back_enabled(self) -> bool: + return False + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 # not dismissable + self.set_progress(0) + + def set_progress(self, progress: int): + self._progress = progress + self._progress_label.set_text(f"{progress}%") + + def _render(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, rl.BLACK) + self._title_label.render(rl.Rectangle( + rect.x + 12, + rect.y + 2, + rect.width, + 64, + )) + + self._progress_label.render(rl.Rectangle( + rect.x + 12, + rect.y + 18, + rect.width, + rect.height, + )) + + +class FailedPage(NavScroller): + def __init__(self, retry_callback: Callable | None, title: str = "download failed", + description: str | None = None, icon: str = "icons_mici/setup/warning.png"): + super().__init__() + self.set_back_callback(retry_callback) + + self._reason_card = GreyBigButton("", "") + self._reason_card.set_visible(False) + + self._scroller.add_widgets([ + GreyBigButton(title, description or "swipe down to go\nback and try again", + gui_app.texture(icon, 64, 58)), + self._reason_card, + BigConfirmationCircleButton("reboot\ndevice", gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70), + HARDWARE.reboot, exit_on_confirm=False), + ]) + + def set_reason(self, reason: str): + if reason: + self._reason_card.set_value(reason) + self._reason_card.set_visible(True) + else: + self._reason_card.set_visible(False) + + +class BigPillButton(BigButton): + def __init__(self, *args, green: bool = False, disabled_background: bool = False, **kwargs): + self._green = green + self._disabled_background = disabled_background + super().__init__(*args, **kwargs) + + self._label.set_font_size(48) + self._label.set_alignment(rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + self._label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + def _load_images(self): + if self._green: + self._txt_default_bg = gui_app.texture("icons_mici/setup/start_button.png", 402, 180) + self._txt_pressed_bg = gui_app.texture("icons_mici/setup/start_button_pressed.png", 402, 180) + else: + self._txt_default_bg = gui_app.texture("icons_mici/setup/continue.png", 402, 180) + self._txt_pressed_bg = gui_app.texture("icons_mici/setup/continue_pressed.png", 402, 180) + self._txt_disabled_bg = gui_app.texture("icons_mici/setup/continue_disabled.png", 402, 180) + + def set_green(self, green: bool): + if self._green != green: + self._green = green + self._load_images() + + def _update_label_layout(self): + # Don't change label text size + pass + + def _handle_background(self) -> tuple[rl.Texture, float, float, float]: + txt_bg, btn_x, btn_y, scale = super()._handle_background() + + if self._disabled_background: + txt_bg = self._txt_disabled_bg + return txt_bg, btn_x, btn_y, scale + + +class NetworkSetupPageBase(Scroller): + def __init__(self, network_monitor: NetworkConnectivityMonitor, continue_callback: Callable[[bool], None], + disable_connect_hint: bool = False): + super().__init__() + + self._wifi_manager = WifiManager() + self._wifi_manager.set_active(True) + self._network_monitor = network_monitor + self._custom_software = False + self._wifi_ui = WifiUIMici(self._wifi_manager) + + self._connect_button = GreyBigButton("connect to\ninternet", "swipe down to go back", + gui_app.texture("icons_mici/setup/small_slider/slider_arrow.png", 64, 56, flip_x=True)) + self._connect_button.set_visible(not disable_connect_hint) + + self._wifi_button = WifiNetworkButton(self._wifi_manager) + self._wifi_button.set_click_callback(lambda: gui_app.push_widget(self._wifi_ui)) + + self._prev_has_internet = False + self._prev_wifi_connected = False + self._pending_has_internet_scroll: float | None = None # stores time to use as delay + self._pending_continue_grow_animation = False + self._pending_wifi_grow_animation = False + + def on_waiting_click(): + offset = (self._wifi_button.rect.x + self._wifi_button.rect.width / 2) - (self._rect.x + self._rect.width / 2) + self._scroller.scroll_to(offset, smooth=True, block_interrupt=True, block_widget_interaction=True) + # trigger grow when wifi button in view + self._pending_wifi_grow_animation = True + + self._waiting_button = BigPillButton("connect to\ncontinue", disabled_background=True) + self._waiting_button.set_click_callback(on_waiting_click) + self._continue_button = BigPillButton("install openpilot", green=True) + self._continue_button.set_click_callback(lambda: continue_callback(self._custom_software)) + + self._scroller.add_widgets([ + self._connect_button, + self._wifi_button, + self._continue_button, + self._waiting_button, + ]) + + gui_app.add_nav_stack_tick(self._nav_stack_tick) + + def show_event(self): + super().show_event() + # make sure we populate strength and ip immediately if already have wifi + self._wifi_manager.set_active(True) + self._prev_has_internet = self._has_internet + self._prev_wifi_connected = self._wifi_manager.wifi_state.status == ConnectStatus.CONNECTED + self._pending_has_internet_scroll = None + self._pending_continue_grow_animation = False + self._pending_wifi_grow_animation = False + + if self._prev_has_internet or self._prev_wifi_connected: + self.set_shown_callback(lambda: self._scroll_to_end_and_grow()) + + @property + def _has_internet(self) -> bool: + network_changing = self._wifi_ui.any_network_forgetting or self._wifi_manager.wifi_state.status == ConnectStatus.CONNECTING + if network_changing: + self._network_monitor.invalidate() + + has_internet = (self._network_monitor.network_connected.is_set() and + not network_changing and + not self._network_monitor.recheck_event.is_set()) + return has_internet + + def _nav_stack_tick(self): + # Only run tick when this page or its WiFi UI is on the stack + if gui_app.get_active_widget() is not self and not gui_app.widget_in_stack(self._wifi_ui): + self._wifi_manager.process_callbacks() + return + + # Check network state before processing callbacks so forgetting flag + # is still set on the frame the forgotten callback fires + has_internet = self._has_internet + wifi_connected = self._wifi_manager.wifi_state.status == ConnectStatus.CONNECTED + + self._continue_button.set_visible(has_internet) + self._waiting_button.set_visible(not has_internet) + + # TODO: fire show/hide events on visibility changes + if not has_internet: + self._pending_continue_grow_animation = False + self._waiting_button.set_text("waiting for\ninternet..." if wifi_connected else "connect to\ncontinue") + + self._wifi_manager.process_callbacks() + + # Dismiss WiFi UI and scroll on WiFi connect or internet gain + if (has_internet and not self._prev_has_internet) or (wifi_connected and not self._prev_wifi_connected): + # TODO: cancel if connect is transient + self._pending_has_internet_scroll = rl.get_time() + + self._prev_has_internet = has_internet + self._prev_wifi_connected = wifi_connected + + if self._pending_has_internet_scroll is not None: + # Scrolls over to continue button, then grows once in view + elapsed = rl.get_time() - self._pending_has_internet_scroll + if elapsed > 0.7 or gui_app.get_active_widget() is self: # instant scroll + grow if not popping + # Animate WifiUi down first before scroll + self._pending_has_internet_scroll = None + gui_app.pop_widgets_to(self, self._scroll_to_end_and_grow) + + def _scroll_to_end_and_grow(self): + self._scroller._layout() + end_offset = -(self._scroller.content_size - self._rect.width) + remaining = self._scroller.scroll_panel.get_offset() - end_offset + self._scroller.scroll_to(remaining, smooth=True, block_interrupt=True, block_widget_interaction=True) + self._pending_continue_grow_animation = True + + def set_custom_software(self, custom_software: bool): + self._custom_software = custom_software + self._continue_button.set_text("install openpilot" if not custom_software else "choose software") + self._continue_button.set_green(not custom_software) + + def _update_state(self): + super()._update_state() + + if self._pending_continue_grow_animation: + btn_right = self._continue_button.rect.x + self._continue_button.rect.width + visible_right = self._rect.x + self._rect.width + if btn_right < visible_right + 50: + self._pending_continue_grow_animation = False + self._continue_button.trigger_grow_animation() + + if self._pending_wifi_grow_animation and abs(self._wifi_button.rect.x - ITEM_SPACING) < 50: + self._pending_wifi_grow_animation = False + self._wifi_button.trigger_grow_animation() + + +class NetworkSetupPage(NetworkSetupPageBase, NavScroller): + def __init__(self, network_monitor: NetworkConnectivityMonitor, continue_callback: Callable[[bool], None], + back_callback: Callable[[], None] | None): + super().__init__(network_monitor, continue_callback) + self.set_back_callback(back_callback) + + +class Setup(Widget): + def __init__(self): + super().__init__() + self.download_url = "" + self.download_progress = 0 + self.download_thread = None + self._download_failed_reason: str | None = None + + self._network_monitor = NetworkConnectivityMonitor() + self._network_monitor.start() + + def getting_started_button_callback(): + gui_app.push_widget(self._software_selection_page) + + self._start_page = StartPage() + self._start_page.set_click_callback(getting_started_button_callback) + self._start_page.set_enabled(lambda: self.enabled) # for nav stack + + self._network_setup_page = NetworkSetupPage(self._network_monitor, self._network_setup_continue_callback, self._pop_to_software_selection) + + self._software_selection_page = SoftwareSelectionPage(self._push_network_setup, lambda: gui_app.push_widget(self._custom_software_warning_page)) + + self._download_failed_page = FailedPage(self._pop_to_software_selection, icon="icons_mici/setup/red_warning.png") + + self._custom_software_warning_page = CustomSoftwareWarningPage(lambda: self._push_network_setup(True), self._pop_to_software_selection) + + self._downloading_page = DownloadingPage() + + gui_app.add_nav_stack_tick(self._nav_stack_tick) + + def _nav_stack_tick(self): + self._downloading_page.set_progress(self.download_progress) + + if self._download_failed_reason is not None: + reason = self._download_failed_reason + self._download_failed_reason = None + self._download_failed_page.set_reason(reason) + gui_app.pop_widgets_to(self._software_selection_page, lambda: gui_app.push_widget(self._download_failed_page)) + + def _render(self, rect: rl.Rectangle): + self._start_page.render(rect) + + def close(self): + self._network_monitor.stop() + + def _pop_to_software_selection(self): + # reset sliders after dismiss completes + gui_app.pop_widgets_to(self._software_selection_page, self._software_selection_page.reset) + + def _push_network_setup(self, custom_software: bool = False): + # to fire the correct continue callback later + self._network_setup_page.set_custom_software(custom_software) + gui_app.push_widget(self._network_setup_page) + + def _network_setup_continue_callback(self, custom_software: bool): + if not custom_software: + self._download(OPENPILOT_URL) + else: + def handle_keyboard_result(text): + url = text.strip() + if url: + self._download(url) + + keyboard = BigInputDialog("custom software URL...", confirm_callback=handle_keyboard_result, auto_return_to_letters="./") + gui_app.push_widget(keyboard) + + def _download(self, url: str): + # autocomplete incomplete URLs + if re.match("^([^/.]+)/([^/]+)$", url): + url = f"https://installer.comma.ai/{url}" + + parsed = urlparse(url, scheme='https') + self.download_url = (urlparse(f"https://{url}") if not parsed.netloc else parsed).geturl() + self.download_progress = 0 + + def start_download(): + self.download_thread = threading.Thread(target=self._download_thread, daemon=True) + self.download_thread.start() + + self._downloading_page.set_shown_callback(start_download) + gui_app.push_widget(self._downloading_page) + + def _download_thread(self): + try: + import tempfile + + fd, tmpfile = tempfile.mkstemp(prefix="installer_") + + headers = {"User-Agent": USER_AGENT, + "X-openpilot-serial": HARDWARE.get_serial(), + "X-openpilot-device-type": HARDWARE.get_device_type()} + req = urllib.request.Request(self.download_url, headers=headers) + + with open(tmpfile, 'wb') as f, urllib.request.urlopen(req, timeout=30) as response: + total_size = int(response.headers.get('content-length', 0)) + downloaded = 0 + block_size = 8192 + + while True: + buffer = response.read(block_size) + if not buffer: + break + + downloaded += len(buffer) + f.write(buffer) + + if total_size: + self.download_progress = int(downloaded * 100 / total_size) + + is_elf = False + with open(tmpfile, 'rb') as f: + header = f.read(4) + is_elf = header == b'\x7fELF' + + if not is_elf: + self._download_failed_reason = "No custom software found at this URL: " + self.download_url.replace("https://", "", 1) + return + + # NOTE: currently unused, for future logging + with open(INSTALLER_URL_PATH, "w") as f: + f.write(self.download_url) + + # AGNOS might try to execute the installer before this process exits. + # Therefore, important to close the fd before renaming the installer. + os.close(fd) + os.rename(tmpfile, INSTALLER_DESTINATION_PATH) + + # give time for installer UI to take over + time.sleep(0.1) + gui_app.request_close() + + except urllib.error.HTTPError as e: + if e.code == 409: + self._download_failed_reason = "Incompatible openpilot version." + except Exception: + self._download_failed_reason = "Invalid URL: " + self.download_url.replace("https://", "", 1) + + +def main(): + config_realtime_process(0, 51) + # attempt to affine. AGNOS will start setup with all cores, should only fail when manually launching with screen off + if TICI: + try: + set_core_affinity([5]) + except OSError: + cloudlog.exception("Failed to set core affinity for setup process") + + try: + gui_app.init_window("Setup") + setup = Setup() + gui_app.push_widget(setup) + for _ in gui_app.render(): + pass + setup.close() + except Exception as e: + print(f"Setup error: {e}") + finally: + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/system/ui/mici_updater.py b/system/ui/mici_updater.py new file mode 100755 index 00000000000000..8437e6fa60c5dd --- /dev/null +++ b/system/ui/mici_updater.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +import sys +import subprocess +import threading +import pyray as rl + +from openpilot.common.realtime import config_realtime_process, set_core_affinity +from openpilot.system.hardware import HARDWARE, TICI +from openpilot.common.swaglog import cloudlog +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.scroller import Scroller +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.mici_setup import (NetworkSetupPage, FailedPage, NetworkConnectivityMonitor, + GreyBigButton, BigPillButton) + + +class UpdaterNetworkSetupPage(NetworkSetupPage): + def __init__(self, network_monitor, continue_callback): + super().__init__(network_monitor, continue_callback, back_callback=None) + self._continue_button.set_text("download\n& install") + self._continue_button.set_green(False) + + +class ProgressPage(NavWidget): + def __init__(self): + super().__init__() + + self._progress_title_label = UnifiedLabel("", 64, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), + font_weight=FontWeight.DISPLAY, line_height=0.8) + self._progress_percent_label = UnifiedLabel("", 132, text_color=rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)), + font_weight=FontWeight.ROMAN, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + + def _back_enabled(self) -> bool: + return False + + def set_progress(self, text: str, value: int): + self._progress_title_label.set_text(text.replace("_", "_\n") + "...") + self._progress_percent_label.set_text(f"{value}%") + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 # not dismissable + self.set_progress("downloading", 0) + + def _render(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, rl.BLACK) + self._progress_title_label.render(rl.Rectangle( + rect.x + 12, + rect.y + 2, + rect.width, + self._progress_title_label.get_content_height(int(rect.width - 20)), + )) + + self._progress_percent_label.render(rl.Rectangle( + rect.x + 12, + rect.y + 18, + rect.width, + rect.height, + )) + + +class Updater(Scroller): + def __init__(self, updater_path, manifest_path): + super().__init__() + self.updater = updater_path + self.manifest = manifest_path + + self.progress_value = 0 + self.progress_text = "loading" + self.process = None + self.update_thread = None + self._update_failed = False + + self._network_monitor = NetworkConnectivityMonitor() + self._network_monitor.start() + + self._network_setup_page = UpdaterNetworkSetupPage(self._network_monitor, self._network_setup_continue_callback) + + self._progress_page = ProgressPage() + + self._failed_page = FailedPage(self._retry, title="update failed") + + self._continue_button = BigPillButton("next") + self._continue_button.set_click_callback(lambda: gui_app.push_widget(self._network_setup_page)) + + self._scroller.add_widgets([ + GreyBigButton("update required", "the download size\nis approximately 1 GB", + gui_app.texture("icons_mici/offroad_alerts/green_wheel.png", 64, 64)), + self._continue_button, + ]) + + gui_app.add_nav_stack_tick(self._nav_stack_tick) + + def _network_setup_continue_callback(self, _): + self.install_update() + + def _retry(self): + gui_app.pop_widgets_to(self) + + def _nav_stack_tick(self): + self._progress_page.set_progress(self.progress_text, self.progress_value) + + if self._update_failed: + self._update_failed = False + self.show_event() + gui_app.pop_widgets_to(self, lambda: gui_app.push_widget(self._failed_page)) + + def install_update(self): + self.progress_value = 0 + self.progress_text = "downloading" + + def start_update(): + self.update_thread = threading.Thread(target=self._run_update_process, daemon=True) + self.update_thread.start() + + # Start the update process in a separate thread *after* show animation completes + self._progress_page.set_shown_callback(start_update) + gui_app.push_widget(self._progress_page) + + def _run_update_process(self): + # TODO: just import it and run in a thread without a subprocess + try: + cmd = [self.updater, "--swap", self.manifest] + self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, + text=True, bufsize=1, universal_newlines=True) + except Exception: + self._update_failed = True + return + + if self.process.stdout is not None: + for line in self.process.stdout: + parts = line.strip().split(":") + if len(parts) == 2: + self.progress_text = parts[0].lower() + try: + self.progress_value = int(float(parts[1])) + except ValueError: + pass + + exit_code = self.process.wait() + if exit_code == 0: + HARDWARE.reboot() + else: + self._update_failed = True + + def close(self): + self._network_monitor.stop() + + +def main(): + config_realtime_process(0, 51) + # attempt to affine. AGNOS will start setup with all cores, should only fail when manually launching with screen off + if TICI: + try: + set_core_affinity([5]) + except OSError: + cloudlog.exception("Failed to set core affinity for updater process") + + if len(sys.argv) < 3: + print("Usage: updater.py ") + sys.exit(1) + + updater_path = sys.argv[1] + manifest_path = sys.argv[2] + + try: + gui_app.init_window("System Update") + updater = Updater(updater_path, manifest_path) + gui_app.push_widget(updater) + for _ in gui_app.render(): + pass + updater.close() + except Exception as e: + print(f"Updater error: {e}") + finally: + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/system/ui/reset.py b/system/ui/reset.py new file mode 100755 index 00000000000000..c32504a5b8451b --- /dev/null +++ b/system/ui/reset.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +from openpilot.system.ui.lib.application import gui_app +import openpilot.system.ui.tici_reset as tici_reset +import openpilot.system.ui.mici_reset as mici_reset + + +def main(): + if gui_app.big_ui(): + tici_reset.main() + else: + mici_reset.main() + + +if __name__ == "__main__": + main() diff --git a/system/ui/setup.py b/system/ui/setup.py new file mode 100755 index 00000000000000..23ffc26aa2b765 --- /dev/null +++ b/system/ui/setup.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +from openpilot.system.ui.lib.application import gui_app +import openpilot.system.ui.tici_setup as tici_setup +import openpilot.system.ui.mici_setup as mici_setup + + +def main(): + if gui_app.big_ui(): + tici_setup.main() + else: + mici_setup.main() + + +if __name__ == "__main__": + main() diff --git a/system/ui/spinner.py b/system/ui/spinner.py new file mode 100755 index 00000000000000..2a48b3889b90c5 --- /dev/null +++ b/system/ui/spinner.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +import pyray as rl +import select +import sys + +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.text import wrap_text +from openpilot.system.ui.widgets import Widget + +# Constants +if gui_app.big_ui(): + PROGRESS_BAR_WIDTH = 1000 + PROGRESS_BAR_HEIGHT = 20 + TEXTURE_SIZE = 360 + WRAPPED_SPACING = 50 + CENTERED_SPACING = 150 +else: + PROGRESS_BAR_WIDTH = 268 + PROGRESS_BAR_HEIGHT = 10 + TEXTURE_SIZE = 140 + WRAPPED_SPACING = 10 + CENTERED_SPACING = 20 +DEGREES_PER_SECOND = 360.0 # one full rotation per second +MARGIN_H = 100 +FONT_SIZE = 96 +LINE_HEIGHT = 104 +DARKGRAY = (55, 55, 55, 255) + + +def clamp(value, min_value, max_value): + return max(min(value, max_value), min_value) + + +class Spinner(Widget): + def __init__(self): + super().__init__() + self._comma_texture = gui_app.texture("images/spinner_comma.png", TEXTURE_SIZE, TEXTURE_SIZE) + self._spinner_texture = gui_app.texture("images/spinner_track.png", TEXTURE_SIZE, TEXTURE_SIZE, alpha_premultiply=True) + self._rotation = 0.0 + self._progress: int | None = None + self._wrapped_lines: list[str] = [] + + def set_text(self, text: str) -> None: + if text.isdigit(): + self._progress = clamp(int(text), 0, 100) + self._wrapped_lines = [] + else: + self._progress = None + self._wrapped_lines = wrap_text(text, FONT_SIZE, gui_app.width - MARGIN_H) + + def _render(self, rect: rl.Rectangle): + if self._wrapped_lines: + # Calculate total height required for spinner and text + spacing = WRAPPED_SPACING + total_height = TEXTURE_SIZE + spacing + len(self._wrapped_lines) * LINE_HEIGHT + center_y = (rect.height - total_height) / 2.0 + TEXTURE_SIZE / 2.0 + else: + # Center spinner vertically + spacing = CENTERED_SPACING + center_y = rect.height / 2.0 + y_pos = center_y + TEXTURE_SIZE / 2.0 + spacing + + center = rl.Vector2(rect.width / 2.0, center_y) + spinner_origin = rl.Vector2(TEXTURE_SIZE / 2.0, TEXTURE_SIZE / 2.0) + comma_position = rl.Vector2(center.x - TEXTURE_SIZE / 2.0, center.y - TEXTURE_SIZE / 2.0) + + delta_time = rl.get_frame_time() + self._rotation = (self._rotation + DEGREES_PER_SECOND * delta_time) % 360.0 + + # Draw rotating spinner and static comma logo + rl.draw_texture_pro(self._spinner_texture, rl.Rectangle(0, 0, TEXTURE_SIZE, TEXTURE_SIZE), + rl.Rectangle(center.x, center.y, TEXTURE_SIZE, TEXTURE_SIZE), + spinner_origin, self._rotation, rl.WHITE) + rl.draw_texture_v(self._comma_texture, comma_position, rl.WHITE) + + # Display the progress bar or text based on user input + if self._progress is not None: + bar = rl.Rectangle(center.x - PROGRESS_BAR_WIDTH / 2.0, y_pos, PROGRESS_BAR_WIDTH, PROGRESS_BAR_HEIGHT) + rl.draw_rectangle_rounded(bar, 1, 10, DARKGRAY) + + bar.width *= self._progress / 100.0 + rl.draw_rectangle_rounded(bar, 1, 10, rl.WHITE) + elif self._wrapped_lines: + for i, line in enumerate(self._wrapped_lines): + text_size = measure_text_cached(gui_app.font(), line, FONT_SIZE) + rl.draw_text_ex(gui_app.font(), line, rl.Vector2(center.x - text_size.x / 2, y_pos + i * LINE_HEIGHT), + FONT_SIZE, 0.0, rl.WHITE) + + +def _read_stdin(): + """Non-blocking read of available lines from stdin.""" + lines = [] + while True: + rlist, _, _ = select.select([sys.stdin], [], [], 0.0) + if not rlist: + break + line = sys.stdin.readline().strip() + if line == "": + break + lines.append(line) + return lines + + +def main(): + gui_app.init_window("Spinner") + spinner = Spinner() + for _ in gui_app.render(): + text_list = _read_stdin() + if text_list: + spinner.set_text(text_list[-1]) + + spinner.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + +if __name__ == "__main__": + main() diff --git a/system/ui/text.py b/system/ui/text.py new file mode 100755 index 00000000000000..17e8a507cb0b2a --- /dev/null +++ b/system/ui/text.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +import re +import sys +import pyray as rl +from openpilot.system.hardware import HARDWARE, PC +from openpilot.system.ui.lib.application import BIG_UI, gui_app +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle + +if BIG_UI: + MARGIN = 50 + SPACING = 40 + FONT_SIZE = 72 + LINE_HEIGHT = 80 + BUTTON_SIZE = rl.Vector2(310, 160) +else: + MARGIN = 20 + SPACING = 30 + FONT_SIZE = 25 + LINE_HEIGHT = 25 + BUTTON_SIZE = rl.Vector2(150, 80) + +DEMO_TEXT = """This is a sample text that will be wrapped and scrolled if necessary. + The text is long enough to demonstrate scrolling and word wrapping.""" * 30 + + +def wrap_text(text, font_size, max_width): + lines = [] + font = gui_app.font() + + for paragraph in text.split("\n"): + if not paragraph.strip(): + # Don't add empty lines first, ensuring wrap_text("") returns [] + if lines: + lines.append("") + continue + indent = re.match(r"^\s*", paragraph).group() + current_line = indent + words = re.split(r"(\s+|-)", paragraph[len(indent):]) + while len(words): + word = words.pop(0) + test_line = current_line + word + (words.pop(0) if words else "") + if measure_text_cached(font, test_line, font_size).x <= max_width: + current_line = test_line + else: + lines.append(current_line) + current_line = word + " " + current_line = current_line.rstrip() + if current_line: + lines.append(current_line) + + return lines + + +class TextWindow(Widget): + def __init__(self, text: str): + super().__init__() + self._textarea_rect = rl.Rectangle(MARGIN, MARGIN, gui_app.width - MARGIN * 2, gui_app.height - MARGIN * 2) + self._wrapped_lines = wrap_text(text, FONT_SIZE, self._textarea_rect.width - 20) + self._content_rect = rl.Rectangle(0, 0, self._textarea_rect.width - 20, len(self._wrapped_lines) * LINE_HEIGHT) + self._scroll_panel = GuiScrollPanel() + self._scroll_panel._offset_filter_y.x = -max(self._content_rect.height - self._textarea_rect.height, 0) + + button_text = "Exit" if PC else "Reboot" + self._button = Button(button_text, click_callback=self._on_button_clicked, button_style=ButtonStyle.TRANSPARENT_WHITE_BORDER, font_size=FONT_SIZE) + + @staticmethod + def _on_button_clicked(): + gui_app.request_close() + if not PC: + HARDWARE.reboot() + + def _render(self, rect: rl.Rectangle): + scroll = self._scroll_panel.update(self._textarea_rect, self._content_rect) + rl.begin_scissor_mode(int(self._textarea_rect.x), int(self._textarea_rect.y), int(self._textarea_rect.width), int(self._textarea_rect.height)) + for i, line in enumerate(self._wrapped_lines): + position = rl.Vector2(self._textarea_rect.x, self._textarea_rect.y + scroll + i * LINE_HEIGHT) + if position.y + LINE_HEIGHT < self._textarea_rect.y or position.y > self._textarea_rect.y + self._textarea_rect.height: + continue + rl.draw_text_ex(gui_app.font(), line, position, FONT_SIZE, 0, rl.WHITE) + rl.end_scissor_mode() + + button_bounds = rl.Rectangle(rect.width - MARGIN - BUTTON_SIZE.x - SPACING, rect.height - MARGIN - BUTTON_SIZE.y, BUTTON_SIZE.x, BUTTON_SIZE.y) + self._button.render(button_bounds) + + +if __name__ == "__main__": + text = sys.argv[1] if len(sys.argv) > 1 else DEMO_TEXT + gui_app.init_window("Text Viewer") + text_window = TextWindow(text) + for _ in gui_app.render(): + text_window.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) diff --git a/system/ui/tici_reset.py b/system/ui/tici_reset.py new file mode 100755 index 00000000000000..a6603d547e6b42 --- /dev/null +++ b/system/ui/tici_reset.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +import os +import sys +import threading +import time +from enum import IntEnum + +import pyray as rl + +from openpilot.system.hardware import PC +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import gui_label, gui_text_box + +USERDATA = "/dev/disk/by-partlabel/userdata" +TIMEOUT = 3*60 + + +class ResetMode(IntEnum): + USER_RESET = 0 # user initiated a factory reset from openpilot + RECOVER = 1 # userdata is corrupt for some reason, give a chance to recover + + +class ResetState(IntEnum): + NONE = 0 + CONFIRM = 1 + RESETTING = 2 + FAILED = 3 + + +class Reset(Widget): + def __init__(self, mode): + super().__init__() + self._mode = mode + self._previous_reset_state = None + self._reset_state = ResetState.NONE + self._cancel_button = Button("Cancel", gui_app.request_close) + self._confirm_button = Button("Confirm", self._confirm, button_style=ButtonStyle.PRIMARY) + self._reboot_button = Button("Reboot", lambda: os.system("sudo reboot")) + + def _do_erase(self): + if PC: + return + + # Removing data and formatting + rm = os.system("sudo rm -rf /data/*") + os.system(f"sudo umount {USERDATA}") + fmt = os.system(f"yes | sudo mkfs.ext4 {USERDATA}") + + if rm == 0 or fmt == 0: + os.system("sudo reboot") + else: + self._reset_state = ResetState.FAILED + + def _start_reset(self): + self._reset_state = ResetState.RESETTING + threading.Timer(0.1, self._do_erase).start() + + def _update_state(self): + if self._reset_state != self._previous_reset_state: + self._previous_reset_state = self._reset_state + self._timeout_st = time.monotonic() + elif self._reset_state != ResetState.RESETTING and (time.monotonic() - self._timeout_st) > TIMEOUT: + exit(0) + + def _render(self, _): + content_rect = rl.Rectangle(45, 200, self._rect.width - 90, self._rect.height - 245) + + label_rect = rl.Rectangle(content_rect.x + 140, content_rect.y, content_rect.width - 280, 100 * FONT_SCALE) + gui_label(label_rect, "System Reset", 100, font_weight=FontWeight.BOLD) + + text_rect = rl.Rectangle(content_rect.x + 140, content_rect.y + 140, content_rect.width - 280, content_rect.height - 90 - 100 * FONT_SCALE) + gui_text_box(text_rect, self._get_body_text(), 90) + + button_height = 160 + button_spacing = 50 + button_top = content_rect.y + content_rect.height - button_height + button_width = (content_rect.width - button_spacing) / 2.0 + + if self._reset_state != ResetState.RESETTING: + if self._mode == ResetMode.RECOVER: + self._reboot_button.render(rl.Rectangle(content_rect.x, button_top, button_width, button_height)) + elif self._mode == ResetMode.USER_RESET: + self._cancel_button.render(rl.Rectangle(content_rect.x, button_top, button_width, button_height)) + + if self._reset_state != ResetState.FAILED: + self._confirm_button.render(rl.Rectangle(content_rect.x + button_width + 50, button_top, button_width, button_height)) + else: + self._reboot_button.render(rl.Rectangle(content_rect.x, button_top, content_rect.width, button_height)) + + def _confirm(self): + if self._reset_state == ResetState.CONFIRM: + self._start_reset() + else: + self._reset_state = ResetState.CONFIRM + + def _get_body_text(self): + if self._reset_state == ResetState.CONFIRM: + return "Are you sure you want to reset your device?" + if self._reset_state == ResetState.RESETTING: + return "Resetting device...\nThis may take up to a minute." + if self._reset_state == ResetState.FAILED: + return "Reset failed. Reboot to try again." + if self._mode == ResetMode.RECOVER: + return "Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device." + return "System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot." + + +def main(): + mode = ResetMode.USER_RESET + if len(sys.argv) > 1: + if sys.argv[1] == '--recover': + mode = ResetMode.RECOVER + + gui_app.init_window("System Reset", 20) + reset = Reset(mode) + + gui_app.push_widget(reset) + + for _ in gui_app.render(): + pass + + +if __name__ == "__main__": + main() diff --git a/system/ui/tici_setup.py b/system/ui/tici_setup.py new file mode 100755 index 00000000000000..9eefb6af537613 --- /dev/null +++ b/system/ui/tici_setup.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python3 +import os +import re +import threading +import time +import urllib.request +import urllib.error +from urllib.parse import urlparse +from enum import IntEnum + +import pyray as rl + +from cereal import log +from openpilot.system.hardware import HARDWARE +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle, ButtonRadio +from openpilot.system.ui.widgets.keyboard import Keyboard +from openpilot.system.ui.widgets.label import Label +from openpilot.system.ui.widgets.network import WifiManagerUI, WifiManager + +NetworkType = log.DeviceState.NetworkType + +MARGIN = 50 +TITLE_FONT_SIZE = 90 +TITLE_FONT_WEIGHT = FontWeight.MEDIUM +NEXT_BUTTON_WIDTH = 310 +BODY_FONT_SIZE = 80 +BUTTON_HEIGHT = 160 +BUTTON_SPACING = 50 + +OPENPILOT_URL = "https://openpilot.comma.ai" +USER_AGENT = f"AGNOSSetup-{HARDWARE.get_os_version()}" + +INSTALLER_DESTINATION_PATH = "/tmp/installer" +INSTALLER_URL_PATH = "/tmp/installer_url" + + +class SetupState(IntEnum): + LOW_VOLTAGE = 0 + GETTING_STARTED = 1 + NETWORK_SETUP = 2 + SOFTWARE_SELECTION = 3 + CUSTOM_SOFTWARE = 4 + DOWNLOADING = 5 + DOWNLOAD_FAILED = 6 + CUSTOM_SOFTWARE_WARNING = 7 + + +class Setup(Widget): + def __init__(self): + super().__init__() + self.state = SetupState.GETTING_STARTED + self.network_check_thread = None + self.network_connected = threading.Event() + self.wifi_connected = threading.Event() + self.stop_network_check_thread = threading.Event() + self.failed_url = "" + self.failed_reason = "" + self.download_url = "" + self.download_progress = 0 + self.download_thread = None + self.wifi_ui = WifiManagerUI(WifiManager()) + self.keyboard = Keyboard() + self.selected_radio = None + self.warning = gui_app.texture("icons/warning.png", 150, 150) + self.checkmark = gui_app.texture("icons/circled_check.png", 100, 100) + + self._low_voltage_title_label = Label("WARNING: Low Voltage", TITLE_FONT_SIZE, FontWeight.MEDIUM, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + text_color=rl.Color(255, 89, 79, 255), text_padding=20) + self._low_voltage_body_label = Label("Power your device in a car with a harness or proceed at your own risk.", BODY_FONT_SIZE, + text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._low_voltage_continue_button = Button("Continue", self._low_voltage_continue_button_callback) + self._low_voltage_poweroff_button = Button("Power Off", HARDWARE.shutdown) + + self._getting_started_button = Button("", self._getting_started_button_callback, button_style=ButtonStyle.PRIMARY, border_radius=0) + self._getting_started_title_label = Label("Getting Started", TITLE_FONT_SIZE, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._getting_started_body_label = Label("Before we get on the road, let's finish installation and cover some details.", + BODY_FONT_SIZE, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + + self._software_selection_openpilot_button = ButtonRadio("openpilot", self.checkmark, font_size=BODY_FONT_SIZE, text_padding=80) + self._software_selection_custom_software_button = ButtonRadio("Custom Software", self.checkmark, font_size=BODY_FONT_SIZE, text_padding=80) + self._software_selection_continue_button = Button("Continue", self._software_selection_continue_button_callback, + button_style=ButtonStyle.PRIMARY) + self._software_selection_continue_button.set_enabled(False) + self._software_selection_back_button = Button("Back", self._software_selection_back_button_callback) + self._software_selection_title_label = Label("Choose Software to Use", TITLE_FONT_SIZE, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + text_padding=20) + + self._download_failed_reboot_button = Button("Reboot device", HARDWARE.reboot) + self._download_failed_startover_button = Button("Start over", self._download_failed_startover_button_callback, button_style=ButtonStyle.PRIMARY) + self._download_failed_title_label = Label("Download Failed", TITLE_FONT_SIZE, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._download_failed_url_label = Label("", 52, FontWeight.NORMAL, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._download_failed_body_label = Label("", BODY_FONT_SIZE, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + + self._network_setup_back_button = Button("Back", self._network_setup_back_button_callback) + self._network_setup_continue_button = Button("Waiting for internet", self._network_setup_continue_button_callback, + button_style=ButtonStyle.PRIMARY) + self._network_setup_continue_button.set_enabled(False) + self._network_setup_title_label = Label("Connect to Wi-Fi", TITLE_FONT_SIZE, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + + self._custom_software_warning_continue_button = Button("Scroll to continue", self._custom_software_warning_continue_button_callback, + button_style=ButtonStyle.PRIMARY) + self._custom_software_warning_continue_button.set_enabled(False) + self._custom_software_warning_back_button = Button("Back", self._custom_software_warning_back_button_callback) + self._custom_software_warning_title_label = Label("WARNING: Custom Software", 81, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + text_color=rl.Color(255, 89, 79, 255), + text_padding=60) + self._custom_software_warning_body_label = Label("Use caution when installing third-party software.\n\n" + + "⚠️ It has not been tested by comma.\n\n" + + "⚠️ It may not comply with relevant safety standards.\n\n" + + "⚠️ It may cause damage to your device and/or vehicle.\n\n" + + "If you'd like to proceed, use https://flash.comma.ai " + + "to restore your device to a factory state later.", + 68, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=60) + self._custom_software_warning_body_scroll_panel = GuiScrollPanel() + + self._downloading_body_label = Label("Downloading...", TITLE_FONT_SIZE, FontWeight.MEDIUM, text_padding=20) + + try: + with open("/sys/class/hwmon/hwmon1/in1_input") as f: + voltage = float(f.read().strip()) / 1000.0 + if voltage < 7: + self.state = SetupState.LOW_VOLTAGE + except (FileNotFoundError, ValueError): + self.state = SetupState.LOW_VOLTAGE + + def _render(self, rect: rl.Rectangle): + if self.state == SetupState.LOW_VOLTAGE: + self.render_low_voltage(rect) + elif self.state == SetupState.GETTING_STARTED: + self.render_getting_started(rect) + elif self.state == SetupState.NETWORK_SETUP: + self.render_network_setup(rect) + elif self.state == SetupState.SOFTWARE_SELECTION: + self.render_software_selection(rect) + elif self.state == SetupState.CUSTOM_SOFTWARE_WARNING: + self.render_custom_software_warning(rect) + elif self.state == SetupState.CUSTOM_SOFTWARE: + self.render_custom_software() + elif self.state == SetupState.DOWNLOADING: + self.render_downloading(rect) + elif self.state == SetupState.DOWNLOAD_FAILED: + self.render_download_failed(rect) + + def _low_voltage_continue_button_callback(self): + self.state = SetupState.GETTING_STARTED + + def _custom_software_warning_back_button_callback(self): + self.state = SetupState.SOFTWARE_SELECTION + + def _custom_software_warning_continue_button_callback(self): + self.state = SetupState.NETWORK_SETUP + self.stop_network_check_thread.clear() + self.start_network_check() + + def _getting_started_button_callback(self): + self.state = SetupState.SOFTWARE_SELECTION + + def _software_selection_back_button_callback(self): + self.state = SetupState.GETTING_STARTED + + def _software_selection_continue_button_callback(self): + if self._software_selection_openpilot_button.selected: + self.state = SetupState.NETWORK_SETUP + self.stop_network_check_thread.clear() + self.start_network_check() + else: + self.state = SetupState.CUSTOM_SOFTWARE_WARNING + + def _download_failed_startover_button_callback(self): + self.state = SetupState.GETTING_STARTED + + def _network_setup_back_button_callback(self): + self.state = SetupState.SOFTWARE_SELECTION + + def _network_setup_continue_button_callback(self): + self.stop_network_check_thread.set() + if self._software_selection_openpilot_button.selected: + self.download(OPENPILOT_URL) + else: + self.state = SetupState.CUSTOM_SOFTWARE + + def render_low_voltage(self, rect: rl.Rectangle): + rl.draw_texture_ex(self.warning, rl.Vector2(rect.x + 150, rect.y + 110), 0.0, 1.0, rl.WHITE) + + self._low_voltage_title_label.render(rl.Rectangle(rect.x + 150, rect.y + 110 + 150 + 100, rect.width - 500 - 150, TITLE_FONT_SIZE * FONT_SCALE)) + self._low_voltage_body_label.render(rl.Rectangle(rect.x + 150, rect.y + 110 + 150 + 150, rect.width - 500, BODY_FONT_SIZE * FONT_SCALE * 3)) + + button_width = (rect.width - MARGIN * 3) / 2 + button_y = rect.height - MARGIN - BUTTON_HEIGHT + self._low_voltage_poweroff_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + self._low_voltage_continue_button.render(rl.Rectangle(rect.x + MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT)) + + def render_getting_started(self, rect: rl.Rectangle): + self._getting_started_title_label.render(rl.Rectangle(rect.x + 165, rect.y + 280, rect.width - 265, TITLE_FONT_SIZE * FONT_SCALE)) + self._getting_started_body_label.render(rl.Rectangle(rect.x + 165, rect.y + 280 + TITLE_FONT_SIZE * FONT_SCALE, rect.width - 500, + BODY_FONT_SIZE * FONT_SCALE * 3)) + + btn_rect = rl.Rectangle(rect.width - NEXT_BUTTON_WIDTH, 0, NEXT_BUTTON_WIDTH, rect.height) + self._getting_started_button.render(btn_rect) + triangle = gui_app.texture("images/button_continue_triangle.png", 54, int(btn_rect.height)) + rl.draw_texture_v(triangle, rl.Vector2(btn_rect.x + btn_rect.width / 2 - triangle.width / 2, btn_rect.height / 2 - triangle.height / 2), rl.WHITE) + + def check_network_connectivity(self): + while not self.stop_network_check_thread.is_set(): + if self.state == SetupState.NETWORK_SETUP: + try: + urllib.request.urlopen(OPENPILOT_URL, timeout=2.0) + self.network_connected.set() + if HARDWARE.get_network_type() == NetworkType.wifi: + self.wifi_connected.set() + else: + self.wifi_connected.clear() + except Exception: + self.network_connected.clear() + time.sleep(1.0) + + def start_network_check(self): + if self.network_check_thread is None or not self.network_check_thread.is_alive(): + self.network_check_thread = threading.Thread(target=self.check_network_connectivity, daemon=True) + self.network_check_thread.start() + + def close(self): + if self.network_check_thread is not None: + self.stop_network_check_thread.set() + self.network_check_thread.join() + + def render_network_setup(self, rect: rl.Rectangle): + self._network_setup_title_label.render(rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, TITLE_FONT_SIZE * FONT_SCALE)) + + wifi_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE * FONT_SCALE + MARGIN + 25, rect.width - MARGIN * 2, + rect.height - TITLE_FONT_SIZE * FONT_SCALE - 25 - BUTTON_HEIGHT - MARGIN * 3) + rl.draw_rectangle_rounded(wifi_rect, 0.05, 10, rl.Color(51, 51, 51, 255)) + wifi_content_rect = rl.Rectangle(wifi_rect.x + MARGIN, wifi_rect.y, wifi_rect.width - MARGIN * 2, wifi_rect.height) + self.wifi_ui.render(wifi_content_rect) + + button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 + button_y = rect.height - BUTTON_HEIGHT - MARGIN + + self._network_setup_back_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + + # Check network connectivity status + continue_enabled = self.network_connected.is_set() + self._network_setup_continue_button.set_enabled(continue_enabled) + continue_text = ("Continue" if self.wifi_connected.is_set() else "Continue without Wi-Fi") if continue_enabled else "Waiting for internet" + self._network_setup_continue_button.set_text(continue_text) + self._network_setup_continue_button.render(rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT)) + + def render_software_selection(self, rect: rl.Rectangle): + self._software_selection_title_label.render(rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, TITLE_FONT_SIZE * FONT_SCALE)) + + radio_height = 230 + radio_spacing = 30 + + self._software_selection_continue_button.set_enabled(False) + + openpilot_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE * FONT_SCALE + MARGIN * 2, rect.width - MARGIN * 2, radio_height) + self._software_selection_openpilot_button.render(openpilot_rect) + + if self._software_selection_openpilot_button.selected: + self._software_selection_continue_button.set_enabled(True) + self._software_selection_custom_software_button.selected = False + + custom_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE * FONT_SCALE + MARGIN * 2 + radio_height + radio_spacing, rect.width - MARGIN * 2, + radio_height) + self._software_selection_custom_software_button.render(custom_rect) + + if self._software_selection_custom_software_button.selected: + self._software_selection_continue_button.set_enabled(True) + self._software_selection_openpilot_button.selected = False + + button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 + button_y = rect.height - BUTTON_HEIGHT - MARGIN + + self._software_selection_back_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + self._software_selection_continue_button.render(rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT)) + + def render_downloading(self, rect: rl.Rectangle): + self._downloading_body_label.render(rl.Rectangle(rect.x, rect.y + rect.height / 2 - TITLE_FONT_SIZE * FONT_SCALE / 2, rect.width, + TITLE_FONT_SIZE * FONT_SCALE)) + + def render_download_failed(self, rect: rl.Rectangle): + self._download_failed_title_label.render(rl.Rectangle(rect.x + 117, rect.y + 185, rect.width - 117, TITLE_FONT_SIZE * FONT_SCALE)) + self._download_failed_url_label.set_text(self.failed_url) + self._download_failed_url_label.render(rl.Rectangle(rect.x + 117, rect.y + 185 + TITLE_FONT_SIZE * FONT_SCALE + 67, rect.width - 117 - 100, 64)) + + self._download_failed_body_label.set_text(self.failed_reason) + self._download_failed_body_label.render(rl.Rectangle(rect.x + 117, rect.y, rect.width - 117 - 100, rect.height)) + + button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 + button_y = rect.height - BUTTON_HEIGHT - MARGIN + self._download_failed_reboot_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + self._download_failed_startover_button.render(rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT)) + + def render_custom_software_warning(self, rect: rl.Rectangle): + warn_rect = rl.Rectangle(rect.x, rect.y, rect.width, 1500) + offset = self._custom_software_warning_body_scroll_panel.update(rect, warn_rect) + + button_width = (rect.width - MARGIN * 3) / 2 + button_y = rect.height - MARGIN - BUTTON_HEIGHT + + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(button_y - BODY_FONT_SIZE * FONT_SCALE)) + y_offset = rect.y + offset + self._custom_software_warning_title_label.render(rl.Rectangle(rect.x + 50, y_offset + 150, rect.width - 265, TITLE_FONT_SIZE * FONT_SCALE)) + self._custom_software_warning_body_label.render(rl.Rectangle(rect.x + 50, y_offset + 400, rect.width - 50, BODY_FONT_SIZE * FONT_SCALE * 3)) + rl.end_scissor_mode() + + self._custom_software_warning_back_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + self._custom_software_warning_continue_button.render(rl.Rectangle(rect.x + MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT)) + if offset < (rect.height - warn_rect.height): + self._custom_software_warning_continue_button.set_enabled(True) + self._custom_software_warning_continue_button.set_text("Continue") + + def render_custom_software(self): + def handle_keyboard_result(result): + # Enter pressed + if result == DialogResult.CONFIRM: + url = self.keyboard.text + self.keyboard.clear() + if url: + self.download(url) + + # Cancel pressed + elif result == DialogResult.CANCEL: + self.state = SetupState.SOFTWARE_SELECTION + + self.keyboard.reset(min_text_size=1) + self.keyboard.set_title("Enter URL", "for Custom Software") + self.keyboard.set_callback(handle_keyboard_result) + gui_app.push_widget(self.keyboard) + + def download(self, url: str): + # autocomplete incomplete URLs + if re.match("^([^/.]+)/([^/]+)$", url): + url = f"https://installer.comma.ai/{url}" + + parsed = urlparse(url, scheme='https') + self.download_url = (urlparse(f"https://{url}") if not parsed.netloc else parsed).geturl() + + self.state = SetupState.DOWNLOADING + + self.download_thread = threading.Thread(target=self._download_thread, daemon=True) + self.download_thread.start() + + def _download_thread(self): + try: + import tempfile + + fd, tmpfile = tempfile.mkstemp(prefix="installer_") + + headers = {"User-Agent": USER_AGENT, + "X-openpilot-serial": HARDWARE.get_serial(), + "X-openpilot-device-type": HARDWARE.get_device_type()} + req = urllib.request.Request(self.download_url, headers=headers) + + with open(tmpfile, 'wb') as f, urllib.request.urlopen(req, timeout=30) as response: + total_size = int(response.headers.get('content-length', 0)) + downloaded = 0 + block_size = 8192 + + while True: + buffer = response.read(block_size) + if not buffer: + break + + downloaded += len(buffer) + f.write(buffer) + + if total_size: + self.download_progress = int(downloaded * 100 / total_size) + + is_elf = False + with open(tmpfile, 'rb') as f: + header = f.read(4) + is_elf = header == b'\x7fELF' + + if not is_elf: + self.download_failed(self.download_url, "No custom software found at this URL.") + return + + # AGNOS might try to execute the installer before this process exits. + # Therefore, important to close the fd before renaming the installer. + os.close(fd) + os.rename(tmpfile, INSTALLER_DESTINATION_PATH) + + with open(INSTALLER_URL_PATH, "w") as f: + f.write(self.download_url) + + # give time for installer UI to take over + time.sleep(0.1) + gui_app.request_close() + + except urllib.error.HTTPError as e: + if e.code == 409: + error_msg = e.read().decode("utf-8") + self.download_failed(self.download_url, error_msg) + except Exception: + error_msg = "Ensure the entered URL is valid, and the device's internet connection is good." + self.download_failed(self.download_url, error_msg) + + def download_failed(self, url: str, reason: str): + self.failed_url = url + self.failed_reason = reason + self.state = SetupState.DOWNLOAD_FAILED + + +def main(): + try: + gui_app.init_window("Setup", 20) + setup = Setup() + gui_app.push_widget(setup) + for _ in gui_app.render(): + pass + setup.close() + except Exception as e: + print(f"Setup error: {e}") + finally: + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/system/ui/tici_updater.py b/system/ui/tici_updater.py new file mode 100755 index 00000000000000..3a3b0987d0e174 --- /dev/null +++ b/system/ui/tici_updater.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +import sys +import subprocess +import threading +import pyray as rl +from enum import IntEnum + +from openpilot.system.hardware import HARDWARE +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.wifi_manager import WifiManager +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import gui_text_box, gui_label +from openpilot.system.ui.widgets.network import WifiManagerUI + +# Constants +MARGIN = 50 +BUTTON_HEIGHT = 160 +BUTTON_WIDTH = 400 +PROGRESS_BAR_HEIGHT = 72 +TITLE_FONT_SIZE = 80 +BODY_FONT_SIZE = 65 +BACKGROUND_COLOR = rl.BLACK +PROGRESS_BG_COLOR = rl.Color(41, 41, 41, 255) +PROGRESS_COLOR = rl.Color(54, 77, 239, 255) + + +class Screen(IntEnum): + PROMPT = 0 + WIFI = 1 + PROGRESS = 2 + + +class Updater(Widget): + def __init__(self, updater_path, manifest_path): + super().__init__() + self.updater = updater_path + self.manifest = manifest_path + self.current_screen = Screen.PROMPT + + self.progress_value = 0 + self.progress_text = "Loading..." + self.show_reboot_button = False + self.process = None + self.update_thread = None + self.wifi_manager_ui = WifiManagerUI(WifiManager()) + + # Buttons + self._wifi_button = Button("Connect to Wi-Fi", click_callback=lambda: self.set_current_screen(Screen.WIFI)) + self._install_button = Button("Install", click_callback=self.install_update, button_style=ButtonStyle.PRIMARY) + self._back_button = Button("Back", click_callback=lambda: self.set_current_screen(Screen.PROMPT)) + self._reboot_button = Button("Reboot", click_callback=lambda: HARDWARE.reboot()) + + def set_current_screen(self, screen: Screen): + self.current_screen = screen + + def install_update(self): + self.set_current_screen(Screen.PROGRESS) + self.progress_value = 0 + self.progress_text = "Downloading..." + self.show_reboot_button = False + + # Start the update process in a separate thread + self.update_thread = threading.Thread(target=self._run_update_process) + self.update_thread.daemon = True + self.update_thread.start() + + def _run_update_process(self): + # TODO: just import it and run in a thread without a subprocess + try: + cmd = [self.updater, "--swap", self.manifest] + self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, + text=True, bufsize=1, universal_newlines=True) + except Exception: + self.progress_text = "Update failed" + self.show_reboot_button = True + return + + if self.process.stdout is not None: + for line in self.process.stdout: + parts = line.strip().split(":") + if len(parts) == 2: + self.progress_text = parts[0] + try: + self.progress_value = int(float(parts[1])) + except ValueError: + pass + + exit_code = self.process.wait() + if exit_code == 0: + HARDWARE.reboot() + else: + self.progress_text = "Update failed" + self.show_reboot_button = True + + def render_prompt_screen(self, rect: rl.Rectangle): + # Title + title_rect = rl.Rectangle(MARGIN + 50, 250, rect.width - MARGIN * 2 - 100, TITLE_FONT_SIZE * FONT_SCALE) + gui_label(title_rect, "Update Required", TITLE_FONT_SIZE, font_weight=FontWeight.BOLD) + + # Description + desc_text = ("An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. " + + "The download size is approximately 1GB.") + + desc_rect = rl.Rectangle(MARGIN + 50, 250 + TITLE_FONT_SIZE * FONT_SCALE + 75, rect.width - MARGIN * 2 - 100, BODY_FONT_SIZE * FONT_SCALE * 4) + gui_text_box(desc_rect, desc_text, BODY_FONT_SIZE) + + # Buttons at the bottom + button_y = rect.height - MARGIN - BUTTON_HEIGHT + button_width = (rect.width - MARGIN * 3) // 2 + + # WiFi button + wifi_button_rect = rl.Rectangle(MARGIN, button_y, button_width, BUTTON_HEIGHT) + self._wifi_button.render(wifi_button_rect) + + # Install button + install_button_rect = rl.Rectangle(MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT) + self._install_button.render(install_button_rect) + + def render_wifi_screen(self, rect: rl.Rectangle): + # Draw the Wi-Fi manager UI + wifi_rect = rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, + rect.height - BUTTON_HEIGHT - MARGIN * 3) + rl.draw_rectangle_rounded(wifi_rect, 0.035, 10, rl.Color(51, 51, 51, 255)) + wifi_content_rect = rl.Rectangle(wifi_rect.x + 50, wifi_rect.y, wifi_rect.width - 100, wifi_rect.height) + self.wifi_manager_ui.render(wifi_content_rect) + + back_button_rect = rl.Rectangle(MARGIN, rect.height - MARGIN - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT) + self._back_button.render(back_button_rect) + + def render_progress_screen(self, rect: rl.Rectangle): + title_rect = rl.Rectangle(MARGIN + 100, 330, rect.width - MARGIN * 2 - 200, 100) + gui_label(title_rect, self.progress_text, 90, font_weight=FontWeight.SEMI_BOLD) + + # Progress bar + bar_rect = rl.Rectangle(MARGIN + 100, 330 + 100 + 100, rect.width - MARGIN * 2 - 200, PROGRESS_BAR_HEIGHT) + rl.draw_rectangle_rounded(bar_rect, 0.5, 10, PROGRESS_BG_COLOR) + + # Calculate the width of the progress chunk + progress_width = (bar_rect.width * self.progress_value) / 100 + if progress_width > 0: + progress_rect = rl.Rectangle(bar_rect.x, bar_rect.y, progress_width, bar_rect.height) + rl.draw_rectangle_rounded(progress_rect, 0.5, 10, PROGRESS_COLOR) + + # Show reboot button if needed + if self.show_reboot_button: + reboot_rect = rl.Rectangle(MARGIN + 100, rect.height - MARGIN - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT) + self._reboot_button.render(reboot_rect) + + def _render(self, rect: rl.Rectangle): + if self.current_screen == Screen.PROMPT: + self.render_prompt_screen(rect) + elif self.current_screen == Screen.WIFI: + self.render_wifi_screen(rect) + elif self.current_screen == Screen.PROGRESS: + self.render_progress_screen(rect) + + +def main(): + if len(sys.argv) < 3: + print("Usage: updater.py ") + sys.exit(1) + + updater_path = sys.argv[1] + manifest_path = sys.argv[2] + + try: + gui_app.init_window("System Update") + gui_app.push_widget(Updater(updater_path, manifest_path)) + for _ in gui_app.render(): + pass + finally: + # Make sure we clean up even if there's an error + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/system/ui/updater.py b/system/ui/updater.py new file mode 100755 index 00000000000000..42d12d90901813 --- /dev/null +++ b/system/ui/updater.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +from openpilot.system.ui.lib.application import gui_app +import openpilot.system.ui.tici_updater as tici_updater +import openpilot.system.ui.mici_updater as mici_updater + + +def main(): + if gui_app.big_ui(): + tici_updater.main() + else: + mici_updater.main() + + +if __name__ == "__main__": + main() diff --git a/system/ui/widgets/__init__.py b/system/ui/widgets/__init__.py new file mode 100644 index 00000000000000..4ce1c1b694df89 --- /dev/null +++ b/system/ui/widgets/__init__.py @@ -0,0 +1,244 @@ +from __future__ import annotations + +import abc +import pyray as rl +from enum import IntEnum +from typing import TypeVar +from collections.abc import Callable +from openpilot.system.ui.lib.application import gui_app, MousePos, MAX_TOUCH_SLOTS, MouseEvent + +try: + from openpilot.selfdrive.ui.ui_state import device +except ImportError: + class Device: + awake = True + device = Device() + +W = TypeVar('W', bound='Widget') + +DEBUG = False + + +class DialogResult(IntEnum): + CANCEL = 0 + CONFIRM = 1 + NO_ACTION = -1 + + +class Widget(abc.ABC): + def __init__(self): + self._rect: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) + self._parent_rect: rl.Rectangle | None = None + self._children: list[Widget] = [] + + self._enabled: bool | Callable[[], bool] = True + self._is_visible: bool | Callable[[], bool] = True + + self.__is_pressed = [False] * MAX_TOUCH_SLOTS + # if current mouse/touch down started within the widget's rectangle + self.__tracking_is_pressed = [False] * MAX_TOUCH_SLOTS + self._touch_valid_callback: Callable[[], bool] | None = None + self._click_delay: float | None = None # seconds to hold is_pressed after release + self._click_release_time: float | None = None + self._click_callback: Callable[[], None] | None = None + self._multi_touch = False + self.__was_awake = True + + @property + def rect(self) -> rl.Rectangle: + return self._rect + + def set_rect(self, rect: rl.Rectangle) -> None: + changed = (self._rect.x != rect.x or self._rect.y != rect.y or + self._rect.width != rect.width or self._rect.height != rect.height) + self._rect = rect + if changed: + self._update_layout_rects() + + def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: + """Can be used like size hint in QT""" + self._parent_rect = parent_rect + + @property + def is_pressed(self) -> bool: + # if actually pressed or holding after release + return any(self.__is_pressed) or self._click_release_time is not None + + @property + def enabled(self) -> bool: + return self._enabled() if callable(self._enabled) else self._enabled + + def set_enabled(self, enabled: bool | Callable[[], bool]) -> None: + self._enabled = enabled + + @property + def is_visible(self) -> bool: + return self._is_visible() if callable(self._is_visible) else self._is_visible + + def set_visible(self, visible: bool | Callable[[], bool]) -> None: + self._is_visible = visible + + def set_click_callback(self, click_callback: Callable[[], None] | None) -> None: + """Set a callback to be called when the widget is clicked.""" + self._click_callback = click_callback + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + """Set a callback to determine if the widget can be clicked.""" + self._touch_valid_callback = touch_callback + + def _touch_valid(self) -> bool: + """Check if the widget can be touched.""" + return self._touch_valid_callback() if self._touch_valid_callback else True + + def set_position(self, x: float, y: float) -> None: + changed = (self._rect.x != x or self._rect.y != y) + self._rect = rl.Rectangle(x, y, self._rect.width, self._rect.height) + if changed: + self._update_layout_rects() + + @property + def _hit_rect(self) -> rl.Rectangle: + # restrict touches to within parent rect if set, useful inside Scroller + if self._parent_rect is None: + return self._rect + return rl.get_collision_rec(self._rect, self._parent_rect) + + def render(self, rect: rl.Rectangle | None = None) -> bool | int | None: + if rect is not None: + self.set_rect(rect) + + self._update_state() + + if self._click_release_time is not None and rl.get_time() >= self._click_release_time: + self._click_release_time = None + + if not self.is_visible: + return None + + self._layout() + ret = self._render(self._rect) + + if gui_app.show_touches: + self._draw_debug_rect() + + # Keep track of whether mouse down started within the widget's rectangle + if self.enabled and self.__was_awake: + self._process_mouse_events() + else: + # TODO: ideally we emit release events when going disabled + self.__is_pressed = [False] * MAX_TOUCH_SLOTS + self.__tracking_is_pressed = [False] * MAX_TOUCH_SLOTS + + self.__was_awake = device.awake + + return ret + + def _draw_debug_rect(self) -> None: + rl.draw_rectangle_lines(int(self._rect.x), int(self._rect.y), + max(int(self._rect.width), 1), max(int(self._rect.height), 1), rl.RED) + + def _process_mouse_events(self) -> None: + hit_rect = self._hit_rect + touch_valid = self._touch_valid() + + for mouse_event in gui_app.mouse_events: + if not self._multi_touch and mouse_event.slot != 0: + continue + + mouse_in_rect = rl.check_collision_point_rec(mouse_event.pos, hit_rect) + # Ignores touches/presses that start outside our rect + # Allows touch to leave the rect and come back in focus if mouse did not release + if mouse_event.left_pressed and touch_valid: + if mouse_in_rect: + self._handle_mouse_press(mouse_event.pos) + self.__is_pressed[mouse_event.slot] = True + self.__tracking_is_pressed[mouse_event.slot] = True + self._handle_mouse_event(mouse_event) + + # Callback such as scroll panel signifies user is scrolling + elif not touch_valid: + self.__is_pressed[mouse_event.slot] = False + self.__tracking_is_pressed[mouse_event.slot] = False + + elif mouse_event.left_released: + self._handle_mouse_event(mouse_event) + if self.__is_pressed[mouse_event.slot] and mouse_in_rect: + self._handle_mouse_release(mouse_event.pos) + self.__is_pressed[mouse_event.slot] = False + self.__tracking_is_pressed[mouse_event.slot] = False + + # Mouse/touch is still within our rect + elif mouse_in_rect: + if self.__tracking_is_pressed[mouse_event.slot]: + self.__is_pressed[mouse_event.slot] = True + self._handle_mouse_event(mouse_event) + + # Mouse/touch left our rect but may come back into focus later + elif not mouse_in_rect: + self.__is_pressed[mouse_event.slot] = False + self._handle_mouse_event(mouse_event) + + def _layout(self) -> None: + """Optionally lay out child widgets separately. This is called before rendering.""" + + def _update_state(self): + """Optionally update the widget's non-layout state. This is called before rendering.""" + + @abc.abstractmethod + def _render(self, rect: rl.Rectangle) -> bool | int | None: + """Render the widget within the given rectangle.""" + + def _update_layout_rects(self) -> None: + """Optionally update any layout rects on Widget rect change.""" + + def _handle_mouse_press(self, mouse_pos: MousePos) -> None: + """Optionally handle mouse press events.""" + + def _handle_mouse_release(self, mouse_pos: MousePos) -> None: + """Optionally handle mouse release events.""" + if self._click_delay is not None: + self._click_release_time = rl.get_time() + self._click_delay + if self._click_callback: + self._click_callback() + + def _handle_mouse_event(self, mouse_event: MouseEvent) -> None: + """Optionally handle mouse events. This is called before rendering.""" + # Default implementation does nothing, can be overridden by subclasses + + def _child(self, widget: W) -> W: + """ + Register a widget as a child. Lifecycle events (show/hide) propagate to registered children. + - If the widget is pushed onto the nav stack, do NOT register it (gui_app manages its lifecycle). + - If the widget is rendered inline in _render(), register it. + """ + assert widget not in self._children, f"{type(widget).__name__} already a child of {type(self).__name__}" + self._children.append(widget) + return widget + + _show_hide_depth = 0 + + def show_event(self): + """Called when widget becomes visible. Propagates to registered children.""" + if DEBUG: + print(f"{' ' * Widget._show_hide_depth}show_event: {type(self).__name__}") + Widget._show_hide_depth += 1 + for child in self._children: + child.show_event() + if DEBUG: + Widget._show_hide_depth -= 1 + + def hide_event(self): + """Called when widget is hidden. Propagates to registered children.""" + if DEBUG: + print(f"{' ' * Widget._show_hide_depth}hide_event: {type(self).__name__}") + Widget._show_hide_depth += 1 + for child in self._children: + child.hide_event() + if DEBUG: + Widget._show_hide_depth -= 1 + + def dismiss(self, callback: Callable[[], None] | None = None): + """Immediately dismiss the widget, firing the callback after.""" + gui_app.pop_widget() + if callback: + callback() diff --git a/system/ui/widgets/button.py b/system/ui/widgets/button.py new file mode 100644 index 00000000000000..36ef3bedab6473 --- /dev/null +++ b/system/ui/widgets/button.py @@ -0,0 +1,225 @@ +from collections.abc import Callable +from enum import IntEnum + +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import Label +from openpilot.common.filter_simple import FirstOrderFilter + + +class ButtonStyle(IntEnum): + NORMAL = 0 # Most common, neutral buttons + PRIMARY = 1 # For main actions + DANGER = 2 # For critical actions, like reboot or delete + TRANSPARENT = 3 # For buttons with transparent background and border + TRANSPARENT_WHITE_TEXT = 9 # For buttons with transparent background and border and white text + TRANSPARENT_WHITE_BORDER = 10 # For buttons with transparent background and white border and text + ACTION = 4 + LIST_ACTION = 5 # For list items with action buttons + NO_EFFECT = 6 + KEYBOARD = 7 + FORGET_WIFI = 8 + + +ICON_PADDING = 15 +DEFAULT_BUTTON_FONT_SIZE = 60 +ACTION_BUTTON_FONT_SIZE = 48 + +BUTTON_TEXT_COLOR = { + ButtonStyle.NORMAL: rl.Color(228, 228, 228, 255), + ButtonStyle.PRIMARY: rl.Color(228, 228, 228, 255), + ButtonStyle.DANGER: rl.Color(228, 228, 228, 255), + ButtonStyle.TRANSPARENT: rl.BLACK, + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.WHITE, + ButtonStyle.TRANSPARENT_WHITE_BORDER: rl.Color(228, 228, 228, 255), + ButtonStyle.ACTION: rl.BLACK, + ButtonStyle.LIST_ACTION: rl.Color(228, 228, 228, 255), + ButtonStyle.NO_EFFECT: rl.Color(228, 228, 228, 255), + ButtonStyle.KEYBOARD: rl.Color(221, 221, 221, 255), + ButtonStyle.FORGET_WIFI: rl.Color(51, 51, 51, 255), +} + +BUTTON_DISABLED_TEXT_COLORS = { + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.WHITE, +} + +BUTTON_BACKGROUND_COLORS = { + ButtonStyle.NORMAL: rl.Color(51, 51, 51, 255), + ButtonStyle.PRIMARY: rl.Color(70, 91, 234, 255), + ButtonStyle.DANGER: rl.Color(226, 44, 44, 255), + ButtonStyle.TRANSPARENT: rl.BLACK, + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.BLANK, + ButtonStyle.TRANSPARENT_WHITE_BORDER: rl.BLACK, + ButtonStyle.ACTION: rl.Color(189, 189, 189, 255), + ButtonStyle.LIST_ACTION: rl.Color(57, 57, 57, 255), + ButtonStyle.NO_EFFECT: rl.Color(51, 51, 51, 255), + ButtonStyle.KEYBOARD: rl.Color(68, 68, 68, 255), + ButtonStyle.FORGET_WIFI: rl.Color(189, 189, 189, 255), +} + +BUTTON_PRESSED_BACKGROUND_COLORS = { + ButtonStyle.NORMAL: rl.Color(74, 74, 74, 255), + ButtonStyle.PRIMARY: rl.Color(48, 73, 244, 255), + ButtonStyle.DANGER: rl.Color(255, 36, 36, 255), + ButtonStyle.TRANSPARENT: rl.BLACK, + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.BLANK, + ButtonStyle.TRANSPARENT_WHITE_BORDER: rl.BLANK, + ButtonStyle.ACTION: rl.Color(130, 130, 130, 255), + ButtonStyle.LIST_ACTION: rl.Color(74, 74, 74, 74), + ButtonStyle.NO_EFFECT: rl.Color(51, 51, 51, 255), + ButtonStyle.KEYBOARD: rl.Color(51, 51, 51, 255), + ButtonStyle.FORGET_WIFI: rl.Color(130, 130, 130, 255), +} + +BUTTON_DISABLED_BACKGROUND_COLORS = { + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.BLANK, +} + + +class Button(Widget): + def __init__(self, + text: str | Callable[[], str], + click_callback: Callable[[], None] | None = None, + font_size: int = DEFAULT_BUTTON_FONT_SIZE, + font_weight: FontWeight = FontWeight.MEDIUM, + button_style: ButtonStyle = ButtonStyle.NORMAL, + border_radius: int = 10, + text_alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + text_padding: int = 20, + icon=None, + elide_right: bool = False, + multi_touch: bool = False, + ): + + super().__init__() + self._button_style = button_style + self._border_radius = border_radius + self._background_color = BUTTON_BACKGROUND_COLORS[self._button_style] + + self._label = Label(text, font_size, font_weight, text_alignment, text_padding=text_padding, + text_color=BUTTON_TEXT_COLOR[self._button_style], icon=icon, elide_right=elide_right) + + self._click_callback = click_callback + self._multi_touch = multi_touch + + def set_text(self, text): + self._label.set_text(text) + + def set_button_style(self, button_style: ButtonStyle): + self._button_style = button_style + self._background_color = BUTTON_BACKGROUND_COLORS[self._button_style] + self._label.set_text_color(BUTTON_TEXT_COLOR[self._button_style]) + + def _update_state(self): + if self.enabled: + self._label.set_text_color(BUTTON_TEXT_COLOR[self._button_style]) + if self.is_pressed: + self._background_color = BUTTON_PRESSED_BACKGROUND_COLORS[self._button_style] + else: + self._background_color = BUTTON_BACKGROUND_COLORS[self._button_style] + elif self._button_style != ButtonStyle.NO_EFFECT: + self._background_color = BUTTON_DISABLED_BACKGROUND_COLORS.get(self._button_style, rl.Color(51, 51, 51, 255)) + self._label.set_text_color(BUTTON_DISABLED_TEXT_COLORS.get(self._button_style, rl.Color(228, 228, 228, 51))) + + def _render(self, _): + roundness = self._border_radius / (min(self._rect.width, self._rect.height) / 2) + if self._button_style == ButtonStyle.TRANSPARENT_WHITE_BORDER: + rl.draw_rectangle_rounded(self._rect, roundness, 10, rl.BLACK) + rl.draw_rectangle_rounded_lines_ex(self._rect, roundness, 10, 2, rl.WHITE) + else: + rl.draw_rectangle_rounded(self._rect, roundness, 10, self._background_color) + self._label.render(self._rect) + + +class ButtonRadio(Button): + def __init__(self, + text: str, + icon, + click_callback: Callable[[], None] | None = None, + font_size: int = DEFAULT_BUTTON_FONT_SIZE, + text_alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + border_radius: int = 10, + text_padding: int = 20, + ): + + super().__init__(text, click_callback=click_callback, font_size=font_size, + border_radius=border_radius, text_padding=text_padding, + text_alignment=text_alignment) + self._text_padding = text_padding + self._icon = icon + self.selected = False + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + self.selected = not self.selected + + def _update_state(self): + if self.selected: + self._background_color = BUTTON_BACKGROUND_COLORS[ButtonStyle.PRIMARY] + else: + self._background_color = BUTTON_BACKGROUND_COLORS[ButtonStyle.NORMAL] + + def _render(self, _): + roundness = self._border_radius / (min(self._rect.width, self._rect.height) / 2) + rl.draw_rectangle_rounded(self._rect, roundness, 10, self._background_color) + self._label.render(self._rect) + + if self._icon and self.selected: + icon_y = self._rect.y + (self._rect.height - self._icon.height) / 2 + icon_x = self._rect.x + self._rect.width - self._icon.width - self._text_padding - ICON_PADDING + rl.draw_texture_v(self._icon, rl.Vector2(icon_x, icon_y), rl.WHITE if self.enabled else rl.Color(255, 255, 255, 100)) + + +class IconButton(Widget): + def __init__(self, texture: rl.Texture): + super().__init__() + self._texture = texture + self._opacity_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) + self.set_rect(rl.Rectangle(0, 0, self._texture.width, self._texture.height)) + + def set_opacity(self, opacity: float, smooth: bool = False): + if smooth: + self._opacity_filter.update(opacity) + else: + self._opacity_filter.x = opacity + + def _render(self, rect: rl.Rectangle): + color = rl.Color(180, 180, 180, int(150 * self._opacity_filter.x)) if self.is_pressed else rl.WHITE + if not self.enabled: + color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.35 * self._opacity_filter.x)) + draw_x = rect.x + (rect.width - self._texture.width) / 2 + draw_y = rect.y + (rect.height - self._texture.height) / 2 + rl.draw_texture_ex(self._texture, rl.Vector2(draw_x, draw_y), 0.0, 1.0, color) + + +class SmallCircleIconButton(Widget): + def __init__(self, icon_txt: rl.Texture): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 100, 100)) + self._opacity_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._icon_bg_txt = gui_app.texture("icons_mici/setup/small_button.png", 100, 100) + self._icon_bg_pressed_txt = gui_app.texture("icons_mici/setup/small_button_pressed.png", 100, 100) + self._icon_bg_disabled_txt = gui_app.texture("icons_mici/setup/small_button_disabled.png", 100, 100) + self._icon_txt = icon_txt + + def set_opacity(self, opacity: float, smooth: bool = False): + if smooth: + self._opacity_filter.update(opacity) + else: + self._opacity_filter.x = opacity + + def _render(self, _): + white = rl.Color(255, 255, 255, int(255 * self._opacity_filter.x)) + if not self.enabled: + bg_txt = self._icon_bg_disabled_txt + icon_white = rl.Color(255, 255, 255, int(white.a * 0.35)) + else: + bg_txt = self._icon_bg_pressed_txt if self.is_pressed else self._icon_bg_txt + icon_white = white + + rl.draw_texture_ex(bg_txt, rl.Vector2(self.rect.x, self.rect.y), 0.0, 1.0, white) + icon_x = self.rect.x + (self.rect.width - self._icon_txt.width) / 2 + icon_y = self.rect.y + (self.rect.height - self._icon_txt.height) / 2 + rl.draw_texture_ex(self._icon_txt, rl.Vector2(icon_x, icon_y), 0.0, 1.0, icon_white) diff --git a/system/ui/widgets/confirm_dialog.py b/system/ui/widgets/confirm_dialog.py new file mode 100644 index 00000000000000..3544836761ce4e --- /dev/null +++ b/system/ui/widgets/confirm_dialog.py @@ -0,0 +1,94 @@ +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.button import ButtonStyle, Button +from openpilot.system.ui.widgets.label import Label +from openpilot.system.ui.widgets.html_render import HtmlRenderer, ElementType +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller_tici import Scroller + +OUTER_MARGIN = 200 +RICH_OUTER_MARGIN = 100 +BUTTON_HEIGHT = 160 +MARGIN = 50 +TEXT_PADDING = 10 +BACKGROUND_COLOR = rl.Color(27, 27, 27, 255) + + +class ConfirmDialog(Widget): + def __init__(self, text: str, confirm_text: str, cancel_text: str | None = None, rich: bool = False, callback: Callable[[DialogResult], None] | None = None): + super().__init__() + if cancel_text is None: + cancel_text = tr("Cancel") + self._label = Label(text, 70, FontWeight.BOLD, text_color=rl.Color(201, 201, 201, 255)) + self._html_renderer = HtmlRenderer(text=text, text_size={ElementType.P: 50}, center_text=True) + self._cancel_button = Button(cancel_text, self._cancel_button_callback) + self._confirm_button = Button(confirm_text, self._confirm_button_callback, button_style=ButtonStyle.PRIMARY) + self._rich = rich + self._callback = callback + self._cancel_text = cancel_text + self._scroller = Scroller([self._html_renderer], line_separator=False, spacing=0) + + def set_text(self, text): + if not self._rich: + self._label.set_text(text) + else: + self._html_renderer.parse_html_content(text) + + def _cancel_button_callback(self): + gui_app.pop_widget() + if self._callback: + self._callback(DialogResult.CANCEL) + + def _confirm_button_callback(self): + gui_app.pop_widget() + if self._callback: + self._callback(DialogResult.CONFIRM) + + def _render(self, rect: rl.Rectangle): + dialog_x = OUTER_MARGIN if not self._rich else RICH_OUTER_MARGIN + dialog_y = OUTER_MARGIN if not self._rich else RICH_OUTER_MARGIN + dialog_width = gui_app.width - 2 * dialog_x + dialog_height = gui_app.height - 2 * dialog_y + dialog_rect = rl.Rectangle(dialog_x, dialog_y, dialog_width, dialog_height) + + bottom = dialog_rect.y + dialog_rect.height + button_width = (dialog_rect.width - 3 * MARGIN) // 2 + cancel_button_x = dialog_rect.x + MARGIN + confirm_button_x = dialog_rect.x + dialog_rect.width - button_width - MARGIN + button_y = bottom - BUTTON_HEIGHT - MARGIN + cancel_button = rl.Rectangle(cancel_button_x, button_y, button_width, BUTTON_HEIGHT) + confirm_button = rl.Rectangle(confirm_button_x, button_y, button_width, BUTTON_HEIGHT) + + rl.draw_rectangle_rec(dialog_rect, BACKGROUND_COLOR) + + text_rect = rl.Rectangle(dialog_rect.x + MARGIN, dialog_rect.y + TEXT_PADDING, + dialog_rect.width - 2 * MARGIN, dialog_rect.height - BUTTON_HEIGHT - MARGIN - TEXT_PADDING * 2) + if not self._rich: + self._label.render(text_rect) + else: + html_rect = rl.Rectangle(text_rect.x, text_rect.y, text_rect.width, + self._html_renderer.get_total_height(int(text_rect.width))) + self._html_renderer.set_rect(html_rect) + self._scroller.render(text_rect) + + if rl.is_key_pressed(rl.KeyboardKey.KEY_ENTER): + self._confirm_button_callback() + elif rl.is_key_pressed(rl.KeyboardKey.KEY_ESCAPE): + self._cancel_button_callback() + + if self._cancel_text: + self._confirm_button.render(confirm_button) + self._cancel_button.render(cancel_button) + else: + full_button_width = dialog_rect.width - 2 * MARGIN + full_confirm_button = rl.Rectangle(dialog_rect.x + MARGIN, button_y, full_button_width, BUTTON_HEIGHT) + self._confirm_button.render(full_confirm_button) + + +def alert_dialog(message: str, button_text: str | None = None): + if button_text is None: + button_text = tr("OK") + return ConfirmDialog(message, button_text, cancel_text="") diff --git a/system/ui/widgets/html_render.py b/system/ui/widgets/html_render.py new file mode 100644 index 00000000000000..77fca9fe348a40 --- /dev/null +++ b/system/ui/widgets/html_render.py @@ -0,0 +1,290 @@ +import re +import pyray as rl +from dataclasses import dataclass +from enum import Enum +from typing import Any +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.lib.text_measure import measure_text_cached + +LIST_INDENT_PX = 40 + + +class ElementType(Enum): + H1 = "h1" + H2 = "h2" + H3 = "h3" + H4 = "h4" + H5 = "h5" + H6 = "h6" + P = "p" + B = "b" + UL = "ul" + LI = "li" + BR = "br" + + +TAG_NAMES = '|'.join([t.value for t in ElementType]) +START_TAG_RE = re.compile(f'<({TAG_NAMES})>') +END_TAG_RE = re.compile(f'') +COMMENT_RE = re.compile(r'', flags=re.DOTALL) +DOCTYPE_RE = re.compile(r']*>') +HTML_BODY_TAGS_RE = re.compile(r']*>') +TOKEN_RE = re.compile(r']+>|<[^>]+>|[^<\s]+') + + +def is_tag(token: str) -> tuple[bool, bool, ElementType | None]: + supported_tag = bool(START_TAG_RE.fullmatch(token)) + supported_end_tag = bool(END_TAG_RE.fullmatch(token)) + tag = ElementType(token[1:-1].strip('/')) if supported_tag or supported_end_tag else None + return supported_tag, supported_end_tag, tag + + +@dataclass +class HtmlElement: + type: ElementType + content: str + font_size: int + font_weight: FontWeight + margin_top: int + margin_bottom: int + line_height: float = 0.9 # matches Qt visually, unsure why not default 1.2 + indent_level: int = 0 + + +class HtmlRenderer(Widget): + def __init__(self, file_path: str | None = None, text: str | None = None, + text_size: dict | None = None, text_color: rl.Color = rl.WHITE, center_text: bool = False): + super().__init__() + self._text_color = text_color + self._center_text = center_text + self._normal_font = gui_app.font(FontWeight.NORMAL) + self._bold_font = gui_app.font(FontWeight.BOLD) + self._indent_level = 0 + + if text_size is None: + text_size = {} + + self._cached_height: float | None = None + self._cached_width: int = -1 + + # Base paragraph size (Qt stylesheet default is 48px in offroad alerts) + base_p_size = int(text_size.get(ElementType.P, 48)) + + # Untagged text defaults to

+ self.styles: dict[ElementType, dict[str, Any]] = { + ElementType.H1: {"size": round(base_p_size * 2), "weight": FontWeight.BOLD, "margin_top": 20, "margin_bottom": 16}, + ElementType.H2: {"size": round(base_p_size * 1.50), "weight": FontWeight.BOLD, "margin_top": 24, "margin_bottom": 12}, + ElementType.H3: {"size": round(base_p_size * 1.17), "weight": FontWeight.BOLD, "margin_top": 20, "margin_bottom": 10}, + ElementType.H4: {"size": round(base_p_size * 1.00), "weight": FontWeight.BOLD, "margin_top": 16, "margin_bottom": 8}, + ElementType.H5: {"size": round(base_p_size * 0.83), "weight": FontWeight.BOLD, "margin_top": 12, "margin_bottom": 6}, + ElementType.H6: {"size": round(base_p_size * 0.67), "weight": FontWeight.BOLD, "margin_top": 10, "margin_bottom": 4}, + ElementType.P: {"size": base_p_size, "weight": FontWeight.NORMAL, "margin_top": 8, "margin_bottom": 12}, + ElementType.B: {"size": base_p_size, "weight": FontWeight.BOLD, "margin_top": 8, "margin_bottom": 12}, + ElementType.LI: {"size": base_p_size, "weight": FontWeight.NORMAL, "color": rl.Color(40, 40, 40, 255), "margin_top": 6, "margin_bottom": 6}, + ElementType.BR: {"size": 0, "weight": FontWeight.NORMAL, "margin_top": 0, "margin_bottom": 12}, + } + + self.elements: list[HtmlElement] = [] + if file_path is not None: + self.parse_html_file(file_path) + elif text is not None: + self.parse_html_content(text) + else: + raise ValueError("Either file_path or text must be provided") + + def parse_html_file(self, file_path: str) -> None: + with open(file_path, encoding='utf-8') as file: + content = file.read() + self.parse_html_content(content) + + def parse_html_content(self, html_content: str) -> None: + self.elements.clear() + self._cached_height = None + self._cached_width = -1 + + # Remove HTML comments + html_content = COMMENT_RE.sub('', html_content) + + # Remove DOCTYPE, html, head, body tags but keep their content + html_content = DOCTYPE_RE.sub('', html_content) + html_content = HTML_BODY_TAGS_RE.sub('', html_content) + + # Parse HTML + tokens = TOKEN_RE.findall(html_content) + + def close_tag(): + nonlocal current_content + nonlocal current_tag + + # If no tag is set, default to paragraph so we don't lose text + if current_tag is None: + current_tag = ElementType.P + + text = ' '.join(current_content).strip() + current_content = [] + if text: + if current_tag == ElementType.LI: + text = '• ' + text + self._add_element(current_tag, text) + + current_content: list[str] = [] + current_tag: ElementType | None = None + for token in tokens: + is_start_tag, is_end_tag, tag = is_tag(token) + if tag is not None: + if tag == ElementType.BR: + # Close current tag and add a line break + close_tag() + self._add_element(ElementType.BR, "") + + elif is_start_tag or is_end_tag: + # Always add content regardless of opening or closing tag + close_tag() + + if is_start_tag: + current_tag = tag + else: + current_tag = None + + # increment after we add the content for the current tag + if tag == ElementType.UL: + self._indent_level = self._indent_level + 1 if is_start_tag else max(0, self._indent_level - 1) + + else: + current_content.append(token) + + if current_content: + close_tag() + + def _add_element(self, element_type: ElementType, content: str) -> None: + style = self.styles[element_type] + + element = HtmlElement( + type=element_type, + content=content, + font_size=style["size"], + font_weight=style["weight"], + margin_top=style["margin_top"], + margin_bottom=style["margin_bottom"], + indent_level=self._indent_level, + ) + + self.elements.append(element) + + def _render(self, rect: rl.Rectangle): + # TODO: speed up by removing duplicate calculations across renders + current_y = rect.y + padding = 20 + content_width = rect.width - (padding * 2) + + for element in self.elements: + if element.type == ElementType.BR: + current_y += element.margin_bottom + continue + + current_y += element.margin_top + if current_y > rect.y + rect.height: + break + + if element.content: + font = self._get_font(element.font_weight) + wrapped_lines = wrap_text(font, element.content, element.font_size, int(content_width)) + + for line in wrapped_lines: + # Use FONT_SCALE from wrapped raylib text functions to match what is drawn + if current_y < rect.y - element.font_size * FONT_SCALE: + current_y += element.font_size * FONT_SCALE * element.line_height + continue + + if current_y > rect.y + rect.height: + break + + if self._center_text: + text_width = measure_text_cached(font, line, element.font_size).x + text_x = rect.x + (rect.width - text_width) / 2 + else: # left align + text_x = rect.x + (max(element.indent_level - 1, 0) * LIST_INDENT_PX) + + rl.draw_text_ex(font, line, rl.Vector2(text_x + padding, current_y), element.font_size, 0, self._text_color) + + current_y += element.font_size * FONT_SCALE * element.line_height + + # Apply bottom margin + current_y += element.margin_bottom + + return current_y - rect.y + + def get_total_height(self, content_width: int) -> float: + if self._cached_height is not None and self._cached_width == content_width: + return self._cached_height + + total_height = 0.0 + padding = 20 + usable_width = content_width - (padding * 2) + + for element in self.elements: + if element.type == ElementType.BR: + total_height += element.margin_bottom + continue + + total_height += element.margin_top + + if element.content: + font = self._get_font(element.font_weight) + wrapped_lines = wrap_text(font, element.content, element.font_size, int(usable_width)) + + for _ in wrapped_lines: + total_height += element.font_size * FONT_SCALE * element.line_height + + total_height += element.margin_bottom + + # Store result in cache + self._cached_height = total_height + self._cached_width = content_width + + return total_height + + def _get_font(self, weight: FontWeight): + if weight == FontWeight.BOLD: + return self._bold_font + return self._normal_font + + +class HtmlModal(Widget): + def __init__(self, file_path: str | None = None, text: str | None = None): + super().__init__() + self._content = HtmlRenderer(file_path=file_path, text=text) + self._scroll_panel = GuiScrollPanel() + self._ok_button = Button(tr("OK"), click_callback=gui_app.pop_widget, button_style=ButtonStyle.PRIMARY) + + def _render(self, rect: rl.Rectangle): + margin = 50 + content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - (margin * 2), rect.height - (margin * 2)) + + button_height = 160 + button_spacing = 20 + scrollable_height = content_rect.height - button_height - button_spacing + + scrollable_rect = rl.Rectangle(content_rect.x, content_rect.y, content_rect.width, scrollable_height) + + total_height = self._content.get_total_height(int(scrollable_rect.width)) + scroll_content_rect = rl.Rectangle(scrollable_rect.x, scrollable_rect.y, scrollable_rect.width, total_height) + scroll_offset = self._scroll_panel.update(scrollable_rect, scroll_content_rect) + scroll_content_rect.y += scroll_offset + + rl.begin_scissor_mode(int(scrollable_rect.x), int(scrollable_rect.y), int(scrollable_rect.width), int(scrollable_rect.height)) + self._content.render(scroll_content_rect) + rl.end_scissor_mode() + + button_width = (rect.width - 3 * 50) // 3 + button_x = content_rect.x + content_rect.width - button_width + button_y = content_rect.y + content_rect.height - button_height + button_rect = rl.Rectangle(button_x, button_y, button_width, button_height) + self._ok_button.render(button_rect) + + return -1 diff --git a/system/ui/widgets/icon_widget.py b/system/ui/widgets/icon_widget.py new file mode 100644 index 00000000000000..bf7790b937b1a6 --- /dev/null +++ b/system/ui/widgets/icon_widget.py @@ -0,0 +1,16 @@ +import pyray as rl +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget + + +class IconWidget(Widget): + def __init__(self, image_path: str, size: tuple[int, int], opacity: float = 1.0): + super().__init__() + self._texture = gui_app.texture(image_path, size[0], size[1]) + self._opacity = opacity + self.set_rect(rl.Rectangle(0, 0, float(size[0]), float(size[1]))) + self.set_enabled(False) + + def _render(self, _) -> None: + color = rl.Color(255, 255, 255, int(self._opacity * 255)) + rl.draw_texture_ex(self._texture, rl.Vector2(self._rect.x, self._rect.y), 0.0, 1.0, color) diff --git a/system/ui/widgets/inputbox.py b/system/ui/widgets/inputbox.py new file mode 100644 index 00000000000000..f53e3f0ebb188b --- /dev/null +++ b/system/ui/widgets/inputbox.py @@ -0,0 +1,228 @@ +import pyray as rl +import time +from openpilot.system.ui.lib.application import gui_app, MousePos, FONT_SCALE +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + +PASSWORD_MASK_CHAR = "•" +PASSWORD_MASK_DELAY = 1.5 # Seconds to show character before masking + + +class InputBox(Widget): + def __init__(self, max_text_size=255, password_mode=False): + super().__init__() + self._max_text_size = max_text_size + self._input_text = "" + self._cursor_position = 0 + self._password_mode = password_mode + self._blink_counter = 0 + self._show_cursor = False + self._last_key_pressed = 0 + self._key_press_time = 0 + self._repeat_delay = 30 + self._repeat_rate = 4 + self._text_offset = 0 + self._visible_width = 0 + self._last_char_time = 0 # Track when last character was added + self._masked_length = 0 # How many characters are currently masked + + @property + def text(self): + return self._input_text + + @text.setter + def text(self, value): + self._input_text = value[: self._max_text_size] + self._cursor_position = len(self._input_text) + self._update_text_offset() + + def set_password_mode(self, password_mode): + self._password_mode = password_mode + + def clear(self): + self._input_text = '' + self._cursor_position = 0 + self._text_offset = 0 + + def set_cursor_position(self, position): + """Set the cursor position and reset the blink counter.""" + if 0 <= position <= len(self._input_text): + self._cursor_position = position + self._blink_counter = 0 + self._show_cursor = True + self._update_text_offset() + + def _update_text_offset(self): + """Ensure the cursor is visible by adjusting text offset.""" + if self._visible_width == 0: + return + + font = gui_app.font() + display_text = self._get_display_text() + padding = 10 + + if self._cursor_position > 0: + cursor_x = measure_text_cached(font, display_text[: self._cursor_position], self._font_size).x + else: + cursor_x = 0 + + visible_width = self._visible_width - (padding * 2) + + # Adjust offset if cursor would be outside visible area + if cursor_x < self._text_offset: + self._text_offset = max(0, cursor_x - padding) + elif cursor_x > self._text_offset + visible_width: + self._text_offset = cursor_x - visible_width + padding + + def add_char_at_cursor(self, char): + """Add a character at the current cursor position.""" + if len(self._input_text) < self._max_text_size: + self._input_text = self._input_text[: self._cursor_position] + char + self._input_text[self._cursor_position:] + self.set_cursor_position(self._cursor_position + 1) + + if self._password_mode: + self._last_char_time = time.monotonic() + + return True + return False + + def delete_char_before_cursor(self): + """Delete the character before the cursor position (backspace).""" + if self._cursor_position > 0: + self._input_text = self._input_text[: self._cursor_position - 1] + self._input_text[self._cursor_position:] + self.set_cursor_position(self._cursor_position - 1) + return True + return False + + def delete_char_at_cursor(self): + """Delete the character at the cursor position (delete).""" + if self._cursor_position < len(self._input_text): + self._input_text = self._input_text[: self._cursor_position] + self._input_text[self._cursor_position + 1:] + self.set_cursor_position(self._cursor_position) + return True + return False + + def _render(self, rect, color=rl.BLACK, border_color=rl.DARKGRAY, text_color=rl.WHITE, font_size=80): + # Store dimensions for text offset calculations + self._visible_width = rect.width + self._font_size = font_size + + # Draw input box + rl.draw_rectangle_rec(rect, color) + + # Process keyboard input + self._handle_keyboard_input() + + # Update cursor blink + self._blink_counter += 1 + if self._blink_counter >= 30: + self._show_cursor = not self._show_cursor + self._blink_counter = 0 + + # Display text + font = gui_app.font() + display_text = self._get_display_text() + padding = 10 + + # Clip text within input box bounds + buffer = 2 + rl.begin_scissor_mode(int(rect.x + padding - buffer), int(rect.y), int(rect.width - padding * 2 + buffer * 2), int(rect.height)) + rl.draw_text_ex( + font, + display_text, + rl.Vector2(int(rect.x + padding - self._text_offset), int(rect.y + rect.height / 2 - font_size * FONT_SCALE / 2)), + font_size, + 0, + text_color, + ) + + # Draw cursor + if self._show_cursor: + cursor_x = rect.x + padding + if len(display_text) > 0 and self._cursor_position > 0: + cursor_x += measure_text_cached(font, display_text[: self._cursor_position], font_size).x + + # Apply text offset to cursor position + cursor_x -= self._text_offset + + cursor_height = font_size * FONT_SCALE + 4 + cursor_y = rect.y + rect.height / 2 - cursor_height / 2 + rl.draw_line(int(cursor_x), int(cursor_y), int(cursor_x), int(cursor_y + cursor_height), rl.WHITE) + + rl.end_scissor_mode() + + def _get_display_text(self): + """Get text to display, applying password masking with delay if needed.""" + if not self._password_mode: + return self._input_text + + # Show character at last edited position if within delay window + masked_text = PASSWORD_MASK_CHAR * len(self._input_text) + recent_edit = time.monotonic() - self._last_char_time < PASSWORD_MASK_DELAY + if recent_edit and self._input_text: + last_pos = max(0, self._cursor_position - 1) + if last_pos < len(self._input_text): + return masked_text[:last_pos] + self._input_text[last_pos] + masked_text[last_pos + 1:] + + return masked_text + + def _handle_mouse_release(self, mouse_pos: MousePos): + # Calculate cursor position from click + if len(self._input_text) > 0: + font = gui_app.font() + display_text = self._get_display_text() + + # Find the closest character position to the click + relative_x = mouse_pos.x - (self._rect.x + 10) + self._text_offset + best_pos = 0 + min_distance = float('inf') + + for i in range(len(self._input_text) + 1): + char_width = measure_text_cached(font, display_text[:i], self._font_size).x + distance = abs(relative_x - char_width) + if distance < min_distance: + min_distance = distance + best_pos = i + + self.set_cursor_position(best_pos) + else: + self.set_cursor_position(0) + + def _handle_keyboard_input(self): + # Handle navigation keys + key = rl.get_key_pressed() + if key != 0: + self._process_key(key) + if key in (rl.KEY_LEFT, rl.KEY_RIGHT, rl.KEY_BACKSPACE, rl.KEY_DELETE): + self._last_key_pressed = key + self._key_press_time = 0 + + # Handle repeats for held keys + elif self._last_key_pressed != 0: + if rl.is_key_down(self._last_key_pressed): + self._key_press_time += 1 + if self._key_press_time > self._repeat_delay and self._key_press_time % self._repeat_rate == 0: + self._process_key(self._last_key_pressed) + else: + self._last_key_pressed = 0 + + # Handle text input + char = rl.get_char_pressed() + if char != 0 and char >= 32: # Filter out control characters + self.add_char_at_cursor(chr(char)) + + def _process_key(self, key): + if key == rl.KEY_LEFT: + if self._cursor_position > 0: + self.set_cursor_position(self._cursor_position - 1) + elif key == rl.KEY_RIGHT: + if self._cursor_position < len(self._input_text): + self.set_cursor_position(self._cursor_position + 1) + elif key == rl.KEY_BACKSPACE: + self.delete_char_before_cursor() + elif key == rl.KEY_DELETE: + self.delete_char_at_cursor() + elif key == rl.KEY_HOME: + self.set_cursor_position(0) + elif key == rl.KEY_END: + self.set_cursor_position(len(self._input_text)) diff --git a/system/ui/widgets/keyboard.py b/system/ui/widgets/keyboard.py new file mode 100644 index 00000000000000..49c59a431f12e5 --- /dev/null +++ b/system/ui/widgets/keyboard.py @@ -0,0 +1,282 @@ +from functools import partial +import time +from typing import Literal +from collections.abc import Callable + +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.button import ButtonStyle, Button +from openpilot.system.ui.widgets.inputbox import InputBox +from openpilot.system.ui.widgets.label import Label + +KEY_FONT_SIZE = 96 +DOUBLE_CLICK_THRESHOLD = 0.5 # seconds +DELETE_REPEAT_DELAY = 0.5 +DELETE_REPEAT_INTERVAL = 0.07 + +# Constants for special keys +CONTENT_MARGIN = 50 +BACKSPACE_KEY = "<-" +ENTER_KEY = "->" +SPACE_KEY = " " +SHIFT_INACTIVE_KEY = "SHIFT_OFF" +SHIFT_ACTIVE_KEY = "SHIFT_ON" +CAPS_LOCK_KEY = "CAPS" +NUMERIC_KEY = "123" +SYMBOL_KEY = "#+=" +ABC_KEY = "ABC" + +# Define keyboard layouts as a dictionary for easier access +KEYBOARD_LAYOUTS = { + "lowercase": [ + ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"], + ["a", "s", "d", "f", "g", "h", "j", "k", "l"], + [SHIFT_INACTIVE_KEY, "z", "x", "c", "v", "b", "n", "m", BACKSPACE_KEY], + [NUMERIC_KEY, "/", "-", SPACE_KEY, ".", ENTER_KEY], + ], + "uppercase": [ + ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"], + ["A", "S", "D", "F", "G", "H", "J", "K", "L"], + [SHIFT_ACTIVE_KEY, "Z", "X", "C", "V", "B", "N", "M", BACKSPACE_KEY], + [NUMERIC_KEY, "/", "-", SPACE_KEY, ".", ENTER_KEY], + ], + "numbers": [ + ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"], + ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""], + [SYMBOL_KEY, "_", ",", "?", "!", "`", BACKSPACE_KEY], + [ABC_KEY, SPACE_KEY, ".", ENTER_KEY], + ], + "specials": [ + ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="], + ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"], + [NUMERIC_KEY, "-", ",", "?", "!", "'", BACKSPACE_KEY], + [ABC_KEY, SPACE_KEY, ".", ENTER_KEY], + ], +} + + +class Keyboard(Widget): + def __init__(self, max_text_size: int = 255, min_text_size: int = 0, password_mode: bool = False, show_password_toggle: bool = False, + callback: Callable[[DialogResult], None] | None = None): + super().__init__() + self._layout_name: Literal["lowercase", "uppercase", "numbers", "specials"] = "lowercase" + self._caps_lock = False + self._last_shift_press_time = 0 + self._title = Label("", 90, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._sub_title = Label("", 55, FontWeight.NORMAL, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + + self._max_text_size = max_text_size + self._min_text_size = min_text_size + self._input_box = InputBox(max_text_size) + self._password_mode = password_mode + self._show_password_toggle = show_password_toggle + self._callback = callback + + # Backspace key repeat tracking + self._backspace_pressed: bool = False + self._backspace_press_time: float = 0.0 + self._backspace_last_repeat: float = 0.0 + + self._cancel_button = Button(lambda: tr("Cancel"), self._cancel_button_callback) + + self._eye_button = Button("", self._eye_button_callback, button_style=ButtonStyle.TRANSPARENT) + + self._eye_open_texture = gui_app.texture("icons/eye_open.png", 81, 54) + self._eye_closed_texture = gui_app.texture("icons/eye_closed.png", 81, 54) + self._key_icons = { + BACKSPACE_KEY: gui_app.texture("icons/backspace.png", 80, 80), + SHIFT_INACTIVE_KEY: gui_app.texture("icons/shift.png", 80, 80), + SHIFT_ACTIVE_KEY: gui_app.texture("icons/shift-fill.png", 80, 80), + CAPS_LOCK_KEY: gui_app.texture("icons/capslock-fill.png", 80, 80), + ENTER_KEY: gui_app.texture("icons/arrow-right.png", 80, 80), + } + + self._all_keys = {} + for l in KEYBOARD_LAYOUTS: + for _, keys in enumerate(KEYBOARD_LAYOUTS[l]): + for _, key in enumerate(keys): + if key in self._key_icons: + texture = self._key_icons[key] + self._all_keys[key] = Button("", partial(self._key_callback, key), icon=texture, + button_style=ButtonStyle.PRIMARY if key == ENTER_KEY else ButtonStyle.KEYBOARD, multi_touch=True) + else: + self._all_keys[key] = Button(key, partial(self._key_callback, key), button_style=ButtonStyle.KEYBOARD, font_size=85, multi_touch=True) + self._all_keys[CAPS_LOCK_KEY] = Button("", partial(self._key_callback, CAPS_LOCK_KEY), icon=self._key_icons[CAPS_LOCK_KEY], + button_style=ButtonStyle.KEYBOARD, multi_touch=True) + + def set_text(self, text: str): + self._input_box.text = text + + @property + def text(self): + return self._input_box.text + + def clear(self): + self._layout_name = "lowercase" + self._caps_lock = False + self._input_box.clear() + self._backspace_pressed = False + + def set_title(self, title: str, sub_title: str = ""): + self._title.set_text(title) + self._sub_title.set_text(sub_title) + + def set_callback(self, callback: Callable[[DialogResult], None] | None): + self._callback = callback + + def _eye_button_callback(self): + self._password_mode = not self._password_mode + + def _cancel_button_callback(self): + self.clear() + gui_app.pop_widget() + if self._callback: + self._callback(DialogResult.CANCEL) + + def _key_callback(self, k): + if k == ENTER_KEY: + gui_app.pop_widget() + if self._callback: + self._callback(DialogResult.CONFIRM) + else: + self.handle_key_press(k) + + def _render(self, rect: rl.Rectangle): + rect = rl.Rectangle(rect.x + CONTENT_MARGIN, rect.y + CONTENT_MARGIN, rect.width - 2 * CONTENT_MARGIN, rect.height - 2 * CONTENT_MARGIN) + self._title.render(rl.Rectangle(rect.x, rect.y, rect.width, 95)) + self._sub_title.render(rl.Rectangle(rect.x, rect.y + 95, rect.width, 60)) + self._cancel_button.render(rl.Rectangle(rect.x + rect.width - 386, rect.y, 386, 125)) + + # Draw input box and password toggle + input_margin = 25 + input_box_rect = rl.Rectangle(rect.x + input_margin, rect.y + 160, rect.width - input_margin, 100) + self._render_input_area(input_box_rect) + + # Process backspace key repeat if it's held down + if not self._all_keys[BACKSPACE_KEY].is_pressed: + self._backspace_pressed = False + + if self._backspace_pressed: + current_time = time.monotonic() + time_since_press = current_time - self._backspace_press_time + + # After initial delay, start repeating with shorter intervals + if time_since_press > DELETE_REPEAT_DELAY: + time_since_last_repeat = current_time - self._backspace_last_repeat + if time_since_last_repeat > DELETE_REPEAT_INTERVAL: + self._input_box.delete_char_before_cursor() + self._backspace_last_repeat = current_time + + layout = KEYBOARD_LAYOUTS[self._layout_name] + + h_space, v_space = 15, 15 + row_y_start = rect.y + 300 # Starting Y position for the first row + key_height = (rect.height - 300 - 3 * v_space) / 4 + key_max_width = (rect.width - (len(layout[2]) - 1) * h_space) / len(layout[2]) + + # Iterate over the rows of keys in the current layout + for row, keys in enumerate(layout): + key_width = min((rect.width - (180 if row == 1 else 0) - h_space * (len(keys) - 1)) / len(keys), key_max_width) + start_x = rect.x + (90 if row == 1 else 0) + + for i, key in enumerate(keys): + if i > 0: + start_x += h_space + + new_width = (key_width * 3 + h_space * 2) if key == SPACE_KEY else (key_width * 2 + h_space if key == ENTER_KEY else key_width) + key_rect = rl.Rectangle(start_x, row_y_start + row * (key_height + v_space), new_width, key_height) + start_x += new_width + + is_enabled = key != ENTER_KEY or len(self._input_box.text) >= self._min_text_size + + if key == BACKSPACE_KEY and self._all_keys[BACKSPACE_KEY].is_pressed and not self._backspace_pressed: + self._backspace_pressed = True + self._backspace_press_time = time.monotonic() + self._backspace_last_repeat = time.monotonic() + + if key in self._key_icons: + if key == SHIFT_ACTIVE_KEY and self._caps_lock: + key = CAPS_LOCK_KEY + self._all_keys[key].set_enabled(is_enabled) + self._all_keys[key].render(key_rect) + else: + self._all_keys[key].set_enabled(is_enabled) + self._all_keys[key].render(key_rect) + + def _render_input_area(self, input_rect: rl.Rectangle): + if self._show_password_toggle: + self._input_box.set_password_mode(self._password_mode) + self._input_box.render(rl.Rectangle(input_rect.x, input_rect.y, input_rect.width - 100, input_rect.height)) + + # render eye icon + eye_texture = self._eye_closed_texture if self._password_mode else self._eye_open_texture + + eye_rect = rl.Rectangle(input_rect.x + input_rect.width - 90, input_rect.y, 80, input_rect.height) + self._eye_button.render(eye_rect) + + eye_x = eye_rect.x + (eye_rect.width - eye_texture.width) / 2 + eye_y = eye_rect.y + (eye_rect.height - eye_texture.height) / 2 + + rl.draw_texture_v(eye_texture, rl.Vector2(eye_x, eye_y), rl.WHITE) + else: + self._input_box.render(input_rect) + + rl.draw_line_ex( + rl.Vector2(input_rect.x, input_rect.y + input_rect.height - 2), + rl.Vector2(input_rect.x + input_rect.width, input_rect.y + input_rect.height - 2), + 3.0, # 3 pixel thickness + rl.Color(189, 189, 189, 255), + ) + + def handle_key_press(self, key): + if key in (CAPS_LOCK_KEY, ABC_KEY): + self._caps_lock = False + self._layout_name = "lowercase" + elif key == SHIFT_INACTIVE_KEY: + self._last_shift_press_time = time.monotonic() + self._layout_name = "uppercase" + elif key == SHIFT_ACTIVE_KEY: + if time.monotonic() - self._last_shift_press_time < DOUBLE_CLICK_THRESHOLD: + self._caps_lock = True + else: + self._layout_name = "lowercase" + elif key == NUMERIC_KEY: + self._layout_name = "numbers" + elif key == SYMBOL_KEY: + self._layout_name = "specials" + elif key == BACKSPACE_KEY: + self._input_box.delete_char_before_cursor() + else: + self._input_box.add_char_at_cursor(key) + if not self._caps_lock and self._layout_name == "uppercase": + self._layout_name = "lowercase" + + def reset(self, min_text_size: int | None = None): + if min_text_size is not None: + self._min_text_size = min_text_size + self._last_shift_press_time = 0 + self._backspace_pressed = False + self._backspace_press_time = 0.0 + self._backspace_last_repeat = 0.0 + self.clear() + + +if __name__ == "__main__": + def callback(result: DialogResult): + if result == DialogResult.CONFIRM: + print(f"You typed: {keyboard.text}") + elif result == DialogResult.CANCEL: + print("Canceled") + gui_app.request_close() + + gui_app.init_window("Keyboard") + keyboard = Keyboard(min_text_size=8, show_password_toggle=True, callback=callback) + keyboard.set_title("Keyboard Input", "Type your text below") + + gui_app.push_widget(keyboard) + for _ in gui_app.render(): + pass + gui_app.close() diff --git a/system/ui/widgets/label.py b/system/ui/widgets/label.py new file mode 100644 index 00000000000000..7fe25ab51d1076 --- /dev/null +++ b/system/ui/widgets/label.py @@ -0,0 +1,722 @@ +import math +from enum import IntEnum +from collections.abc import Callable +from itertools import zip_longest +from typing import Union +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight, DEFAULT_TEXT_SIZE, DEFAULT_TEXT_COLOR, FONT_SCALE +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.utils import GuiStyleContext +from openpilot.system.ui.lib.emoji import find_emoji, emoji_tex +from openpilot.system.ui.lib.wrap_text import wrap_text + +ICON_PADDING = 15 + + +# TODO: make this common +def _resolve_value(value, default=""): + if callable(value): + return value() + return value if value is not None else default + + +class ScrollState(IntEnum): + STARTING = 0 + SCROLLING = 1 + + +# TODO: This should be a Widget class +def gui_label( + rect: rl.Rectangle, + text: str, + font_size: int = DEFAULT_TEXT_SIZE, + color: rl.Color = DEFAULT_TEXT_COLOR, + font_weight: FontWeight = FontWeight.NORMAL, + alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, + elide_right: bool = True +): + font = gui_app.font(font_weight) + text_size = measure_text_cached(font, text, font_size) + display_text = text + + # Elide text to fit within the rectangle + if elide_right and text_size.x > rect.width: + _ellipsis = "..." + left, right = 0, len(text) + while left < right: + mid = (left + right) // 2 + candidate = text[:mid] + _ellipsis + candidate_size = measure_text_cached(font, candidate, font_size) + if candidate_size.x <= rect.width: + left = mid + 1 + else: + right = mid + display_text = text[: left - 1] + _ellipsis if left > 0 else _ellipsis + text_size = measure_text_cached(font, display_text, font_size) + + # Calculate horizontal position based on alignment + text_x = rect.x + { + rl.GuiTextAlignment.TEXT_ALIGN_LEFT: 0, + rl.GuiTextAlignment.TEXT_ALIGN_CENTER: (rect.width - text_size.x) / 2, + rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: rect.width - text_size.x, + }.get(alignment, 0) + + # Calculate vertical position based on alignment + text_y = rect.y + { + rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP: 0, + rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE: (rect.height - text_size.y) / 2, + rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM: rect.height - text_size.y, + }.get(alignment_vertical, 0) + + # Draw the text in the specified rectangle + # TODO: add wrapping and proper centering for multiline text + rl.draw_text_ex(font, display_text, rl.Vector2(text_x, text_y), font_size, 0, color) + + +def gui_text_box( + rect: rl.Rectangle, + text: str, + font_size: int = DEFAULT_TEXT_SIZE, + color: rl.Color = DEFAULT_TEXT_COLOR, + alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + font_weight: FontWeight = FontWeight.NORMAL, + line_scale: float = 1.0, +): + styles = [ + (rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_COLOR_NORMAL, rl.color_to_int(color)), + (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_SIZE, round(font_size * FONT_SCALE)), + (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_LINE_SPACING, round(font_size * FONT_SCALE * line_scale)), + (rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_ALIGNMENT, alignment), + (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_ALIGNMENT_VERTICAL, alignment_vertical), + (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_WRAP_MODE, rl.GuiTextWrapMode.TEXT_WRAP_WORD) + ] + if font_weight != FontWeight.NORMAL: + rl.gui_set_font(gui_app.font(font_weight)) + + with GuiStyleContext(styles): + rl.gui_label(rect, text) + + if font_weight != FontWeight.NORMAL: + rl.gui_set_font(gui_app.font(FontWeight.NORMAL)) + + +# Non-interactive text area. Can render emojis and an optional specified icon. +class Label(Widget): + def __init__(self, + text: str | Callable[[], str], + font_size: int = DEFAULT_TEXT_SIZE, + font_weight: FontWeight = FontWeight.NORMAL, + text_alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + text_alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, + text_padding: int = 0, + text_color: rl.Color = DEFAULT_TEXT_COLOR, + icon: Union[rl.Texture, None] = None, + elide_right: bool = False, + line_scale=1.0, + ): + + super().__init__() + self._font_weight = font_weight + self._font = gui_app.font(self._font_weight) + self._font_size = font_size + self._text_alignment = text_alignment + self._text_alignment_vertical = text_alignment_vertical + self._text_padding = text_padding + self._text_color = text_color + self._icon = icon + self._elide_right = elide_right + self._line_scale = line_scale + + self._text = text + self.set_text(text) + + def set_text(self, text): + self._text = text + self._update_text(self._text) + + def set_text_color(self, color): + self._text_color = color + + def set_font_size(self, size): + self._font_size = size + self._update_text(self._text) + + def _update_text(self, text): + self._emojis = [] + self._text_size = [] + text = _resolve_value(text) + + if self._elide_right: + display_text = text + + # Elide text to fit within the rectangle + text_size = measure_text_cached(self._font, text, self._font_size) + content_width = self._rect.width - self._text_padding * 2 + if self._icon: + content_width -= self._icon.width + ICON_PADDING + if text_size.x > content_width: + _ellipsis = "..." + left, right = 0, len(text) + while left < right: + mid = (left + right) // 2 + candidate = text[:mid] + _ellipsis + candidate_size = measure_text_cached(self._font, candidate, self._font_size) + if candidate_size.x <= content_width: + left = mid + 1 + else: + right = mid + display_text = text[: left - 1] + _ellipsis if left > 0 else _ellipsis + + self._text_wrapped = [display_text] + else: + self._text_wrapped = wrap_text(self._font, text, self._font_size, round(self._rect.width - (self._text_padding * 2))) + + for t in self._text_wrapped: + self._emojis.append(find_emoji(t)) + self._text_size.append(measure_text_cached(self._font, t, self._font_size)) + + def _render(self, _): + # Text can be a callable + # TODO: cache until text changed + self._update_text(self._text) + + text_size = self._text_size[0] if self._text_size else rl.Vector2(0.0, 0.0) + if self._text_alignment_vertical == rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE: + total_text_height = sum(ts.y for ts in self._text_size) or self._font_size * FONT_SCALE + text_pos = rl.Vector2(self._rect.x, (self._rect.y + (self._rect.height - total_text_height) // 2)) + else: + text_pos = rl.Vector2(self._rect.x, self._rect.y) + + if self._icon: + icon_y = self._rect.y + (self._rect.height - self._icon.height) / 2 + if len(self._text_wrapped) > 0: + if self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_LEFT: + icon_x = self._rect.x + self._text_padding + text_pos.x = self._icon.width + ICON_PADDING + elif self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_CENTER: + total_width = self._icon.width + ICON_PADDING + text_size.x + icon_x = self._rect.x + (self._rect.width - total_width) / 2 + text_pos.x = self._icon.width + ICON_PADDING + else: + icon_x = (self._rect.x + self._rect.width - text_size.x - self._text_padding) - ICON_PADDING - self._icon.width + else: + icon_x = self._rect.x + (self._rect.width - self._icon.width) / 2 + rl.draw_texture_v(self._icon, rl.Vector2(icon_x, icon_y), rl.WHITE) + + for text, text_size, emojis in zip_longest(self._text_wrapped, self._text_size, self._emojis, fillvalue=[]): + line_pos = rl.Vector2(text_pos.x, text_pos.y) + if self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_LEFT: + line_pos.x += self._text_padding + elif self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_CENTER: + line_pos.x += (self._rect.width - text_size.x) // 2 + elif self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: + line_pos.x += self._rect.width - text_size.x - self._text_padding + + prev_index = 0 + for start, end, emoji in emojis: + text_before = text[prev_index:start] + width_before = measure_text_cached(self._font, text_before, self._font_size) + rl.draw_text_ex(self._font, text_before, line_pos, self._font_size, 0, self._text_color) + line_pos.x += width_before.x + + tex = emoji_tex(emoji) + rl.draw_texture_ex(tex, line_pos, 0.0, self._font_size / tex.height * FONT_SCALE, self._text_color) + line_pos.x += self._font_size * FONT_SCALE + prev_index = end + rl.draw_text_ex(self._font, text[prev_index:], line_pos, self._font_size, 0, self._text_color) + text_pos.y += (text_size.y or self._font_size * FONT_SCALE) * self._line_scale + + +class UnifiedLabel(Widget): + """ + Unified label widget that combines functionality from gui_label, gui_text_box, and Label. + + Supports: + - Emoji rendering + - Text wrapping + - Automatic eliding (single-line or multiline) + - Proper multiline vertical alignment + - Height calculation for layout purposes + """ + # Shimmer constants + SHIMMER_BAND_WIDTH = 0.3 # shimmer width as fraction of text width + SHIMMER_BLUR_RADIUS = 0.12 # gaussian blur as fraction of text width + SHIMMER_CYCLE_PERIOD = 2.5 # seconds per full shimmer cycle + SHIMMER_SWEEP_FRACTION = 0.9 # fraction of cycle spent sweeping (rest is pause) + SHIMMER_LOW_OPACITY = 0.65 # text opacity at rest, shimmer brings to 1.0 + + def __init__(self, + text: str | Callable[[], str], + font_size: int = DEFAULT_TEXT_SIZE, + font_weight: FontWeight = FontWeight.NORMAL, + text_color: rl.Color = DEFAULT_TEXT_COLOR, + alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + text_padding: int = 0, + max_width: int | None = None, + elide: bool = True, + wrap_text: bool = True, + scroll: bool = False, + line_height: float = 1.0, + letter_spacing: float = 0.0, + shimmer: bool = False): + super().__init__() + self._text = text + self._font_size = font_size + self._font_weight = font_weight + self._font = gui_app.font(self._font_weight) + self._text_color = text_color + self._alignment = alignment + self._alignment_vertical = alignment_vertical + self._text_padding = text_padding + self._max_width = max_width + self._elide = elide + self._wrap_text = wrap_text + self._scroll = scroll + self._line_height = line_height * 0.9 + self._letter_spacing = letter_spacing # 0.1 = 10% + self._spacing_pixels = font_size * letter_spacing + + # Shimmer state + self._shimmer = shimmer + self._shimmer_start_time = 0.0 + + # Scroll state + self._scroll = scroll + self._needs_scroll = False + self._scroll_offset = 0 + self._scroll_pause_t: float | None = None + self._scroll_state: ScrollState = ScrollState.STARTING + + # Scroll mode does not support eliding or multiline wrapping + if self._scroll: + self._elide = False + self._wrap_text = False + + # Cached data + self._cached_text: str | None = None + self._cached_wrapped_lines: list[str] = [] + self._cached_line_sizes: list[rl.Vector2] = [] + self._cached_line_emojis: list[list[tuple[int, int, str]]] = [] + self._cached_total_height: float | None = None + self._cached_width: int = -1 + + # If max_width is set, initialize rect size for Scroller support + if max_width is not None: + self._rect.width = max_width + self._rect.height = self.get_content_height(max_width) + + def set_text(self, text: str | Callable[[], str]): + """Update the text content.""" + self._text = text + # No need to update cache here, will be done on next render if needed + + @property + def text(self) -> str: + """Get the current text content.""" + return str(_resolve_value(self._text)) + + @property + def font_size(self) -> int: + return self._font_size + + @property + def text_width(self) -> float: + return max((s.x for s in self._cached_line_sizes), default=0.0) + + def set_text_color(self, color: rl.Color): + """Update the text color.""" + self._text_color = color + + def set_color(self, color: rl.Color): + """Update the text color (alias for set_text_color).""" + self.set_text_color(color) + + def set_font_size(self, size: int): + """Update the font size.""" + if self._font_size != size: + self._font_size = size + self._spacing_pixels = size * self._letter_spacing # Recalculate spacing + self._cached_text = None # Invalidate cache + + def set_letter_spacing(self, letter_spacing: float): + """Update letter spacing (as percentage, e.g., 0.1 = 10%).""" + if self._letter_spacing != letter_spacing: + self._letter_spacing = letter_spacing + self._spacing_pixels = self._font_size * letter_spacing + self._cached_text = None # Invalidate cache + + def set_line_height(self, line_height: float): + """Update line height (multiplier, e.g., 1.0 = default).""" + new_line_height = line_height * 0.9 + if self._line_height != new_line_height: + self._line_height = new_line_height + self._cached_text = None # Invalidate cache (affects total height) + + def set_font_weight(self, font_weight: FontWeight): + """Update the font weight.""" + if self._font_weight != font_weight: + self._font_weight = font_weight + self._font = gui_app.font(self._font_weight) + self._cached_text = None # Invalidate cache + + def set_alignment(self, alignment: int): + """Update the horizontal text alignment.""" + self._alignment = alignment + + def set_alignment_vertical(self, alignment_vertical: int): + """Update the vertical text alignment.""" + self._alignment_vertical = alignment_vertical + + def reset_scroll(self): + """Reset scroll state to initial position.""" + self._scroll_offset = 0 + self._scroll_pause_t = None + self._scroll_state = ScrollState.STARTING + + def show_event(self): + super().show_event() + if self._shimmer: + self.reset_shimmer() + + def reset_shimmer(self, offset: float = 0.0): + """Reset shimmer animation timing.""" + self._shimmer_start_time = rl.get_time() + offset + + def set_max_width(self, max_width: int | None): + """Set the maximum width constraint for wrapping/eliding.""" + if self._max_width != max_width: + self._max_width = max_width + self._cached_text = None # Invalidate cache + # Update rect size for Scroller support + if max_width is not None: + self._rect.width = max_width + self._rect.height = self.get_content_height(max_width) + + def _update_text_cache(self, available_width: int): + """Update cached text processing data.""" + text = self.text + + # Check if cache is still valid + if (self._cached_text == text and + self._cached_width == available_width and + self._cached_wrapped_lines): + return + + self._cached_text = text + self._cached_width = available_width + + # Determine wrapping width + content_width = available_width - (self._text_padding * 2) + if content_width <= 0: + content_width = 1 + + # Wrap text if enabled + if self._wrap_text: + self._cached_wrapped_lines = wrap_text(self._font, text, self._font_size, content_width, self._spacing_pixels) + else: + # Split by newlines but don't wrap + self._cached_wrapped_lines = text.split('\n') if text else [""] + + # Elide lines if needed (for width constraint) + self._cached_wrapped_lines = [self._elide_line(line, content_width) for line in self._cached_wrapped_lines] + + if self._scroll: + self._cached_wrapped_lines = self._cached_wrapped_lines[:1] # Only first line for scrolling + + # Process each line: measure and find emojis + self._cached_line_sizes = [] + self._cached_line_emojis = [] + + for line in self._cached_wrapped_lines: + emojis = find_emoji(line) + self._cached_line_emojis.append(emojis) + # Empty lines should still have height (use font size as line height) + if not line: + size = rl.Vector2(0, self._font_size * FONT_SCALE) + else: + size = measure_text_cached(self._font, line, self._font_size, self._spacing_pixels) + + # This is the only line + if self._scroll: + self._needs_scroll = size.x > content_width + + self._cached_line_sizes.append(size) + + # Calculate total height + # Each line contributes its measured height * line_height (matching Label's behavior) + # This includes spacing to the next line + if self._cached_line_sizes: + # Match the rendering logic: first line doesn't get line_height scaling + total_height = 0.0 + for idx, size in enumerate(self._cached_line_sizes): + if idx == 0: + total_height += size.y + else: + total_height += size.y * self._line_height + self._cached_total_height = total_height + else: + self._cached_total_height = 0.0 + + def _elide_line(self, line: str, max_width: int, force: bool = False) -> str: + """Elide a single line if it exceeds max_width. If force is True, always elide even if it fits.""" + if not self._elide and not force: + return line + + text_size = measure_text_cached(self._font, line, self._font_size, self._spacing_pixels) + if text_size.x <= max_width and not force: + return line + + ellipsis = "..." + # If force=True and line fits, just append ellipsis without truncating + if force and text_size.x <= max_width: + ellipsis_size = measure_text_cached(self._font, ellipsis, self._font_size, self._spacing_pixels) + if text_size.x + ellipsis_size.x <= max_width: + return line + ellipsis + # If line + ellipsis doesn't fit, need to truncate + # Fall through to binary search below + + left, right = 0, len(line) + while left < right: + mid = (left + right) // 2 + candidate = line[:mid] + ellipsis + candidate_size = measure_text_cached(self._font, candidate, self._font_size, self._spacing_pixels) + if candidate_size.x <= max_width: + left = mid + 1 + else: + right = mid + return line[:left - 1] + ellipsis if left > 0 else ellipsis + + def get_content_height(self, max_width: int) -> float: + """ + Returns the height needed for text at given max_width. + Similar to HtmlRenderer.get_total_height(). + """ + # Use max_width if provided, otherwise use self._max_width or a default + width = max_width if max_width > 0 else (self._max_width if self._max_width else 1000) + self._update_text_cache(width) + + if self._cached_total_height is not None: + return self._cached_total_height + return 0.0 + + def _render(self, _): + """Render the label.""" + if self._rect.width <= 0 or self._rect.height <= 0: + return + + # Determine available width + available_width = self._rect.width + if self._max_width is not None: + available_width = min(available_width, self._max_width) + + # Update text cache + self._update_text_cache(int(available_width)) + + if not self._cached_wrapped_lines: + return + + # Calculate which lines fit in the available height + visible_lines: list[str] = [] + visible_sizes: list[rl.Vector2] = [] + visible_emojis: list[list[tuple[int, int, str]]] = [] + + current_height = 0.0 + broke_early = False + for line, size, emojis in zip( + self._cached_wrapped_lines, + self._cached_line_sizes, + self._cached_line_emojis, + strict=True): + + # Calculate height needed for this line + # Each line contributes its height * line_height (matching Label's behavior) + line_height_needed = size.y * self._line_height + + # Check if this line fits + if current_height + line_height_needed > self._rect.height: + # This line doesn't fit + if len(visible_lines) == 0: + # First line doesn't fit by height - still show it (will be clipped by scissor if needed) + # Continue to add this line below + pass + else: + # We have visible lines and this one doesn't fit - mark that we broke early + broke_early = True + break + + visible_lines.append(line) + visible_sizes.append(size) + visible_emojis.append(emojis) + + current_height += line_height_needed + + # If we broke early (there are more lines that don't fit) and elide is enabled, elide the last visible line + if broke_early and len(visible_lines) > 0 and self._elide: + content_width = int(available_width - (self._text_padding * 2)) + if content_width <= 0: + content_width = 1 + + last_line_idx = len(visible_lines) - 1 + last_line = visible_lines[last_line_idx] + # Force elide the last line to show "..." even if it fits in width (to indicate more content) + elided = self._elide_line(last_line, content_width, force=True) + visible_lines[last_line_idx] = elided + visible_sizes[last_line_idx] = measure_text_cached(self._font, elided, self._font_size, self._spacing_pixels) + + if not visible_lines: + return + + # Calculate total visible text block height + # First line is not changed by line_height scaling + total_visible_height = 0.0 + for idx, size in enumerate(visible_sizes): + if idx == 0: + total_visible_height += size.y + else: + total_visible_height += size.y * self._line_height + + # Calculate vertical alignment offset + if self._alignment_vertical == rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP: + start_y = self._rect.y + elif self._alignment_vertical == rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM: + start_y = self._rect.y + self._rect.height - total_visible_height + else: # TEXT_ALIGN_MIDDLE + start_y = self._rect.y + (self._rect.height - total_visible_height) / 2 + + # Only scissor when we know there is a single scrolling line + # Pad a little since descenders like g or j may overflow below rect from font_scale + if self._needs_scroll: + rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y - self._font_size / 2), int(self._rect.width), int(self._rect.height + self._font_size)) + + # Render each line + current_y = start_y + for idx, (line, size, emojis) in enumerate(zip(visible_lines, visible_sizes, visible_emojis, strict=True)): + if self._needs_scroll: + if self._scroll_state == ScrollState.STARTING: + if self._scroll_pause_t is None: + self._scroll_pause_t = rl.get_time() + 2.0 + if rl.get_time() >= self._scroll_pause_t: + self._scroll_state = ScrollState.SCROLLING + self._scroll_pause_t = None + + elif self._scroll_state == ScrollState.SCROLLING: + self._scroll_offset -= 0.8 / 60. * gui_app.target_fps + # don't fully hide + if self._scroll_offset <= -size.x - self._rect.width / 3: + self._scroll_offset = 0 + self._scroll_state = ScrollState.STARTING + self._scroll_pause_t = None + else: + self.reset_scroll() + + self._render_line(line, size, emojis, current_y) + + # Draw 2nd instance for scrolling + if self._needs_scroll and self._scroll_state != ScrollState.STARTING: + text2_scroll_offset = size.x + self._rect.width / 3 + self._render_line(line, size, emojis, current_y, text2_scroll_offset) + + # Move to next line (if not last line) + if idx < len(visible_lines) - 1: + # Use current line's height * line_height for spacing to next line + current_y += size.y * self._line_height + + if self._needs_scroll: + # draw black fade on left and right + fade_width = 20 + rl.draw_rectangle_gradient_h(int(self._rect.x + self._rect.width - fade_width), int(self._rect.y), fade_width, int(self._rect.height), rl.BLANK, rl.BLACK) + + # stop drawing left fade once text scrolls past + text_width = visible_sizes[0].x if visible_sizes else 0 + first_copy_in_view = self._scroll_offset + text_width > 0 + draw_left_fade = self._scroll_state != ScrollState.STARTING and first_copy_in_view + if draw_left_fade: + rl.draw_rectangle_gradient_h(int(self._rect.x), int(self._rect.y), fade_width, int(self._rect.height), rl.BLACK, rl.BLANK) + + rl.end_scissor_mode() + + def _shimmer_alpha(self, char_x: float, shimmer_left: float, shimmer_width: float) -> float: + """Compute shimmer opacity multiplier for a character at the given x position.""" + sigma = shimmer_width * self.SHIMMER_BLUR_RADIUS + if sigma <= 0: + return self.SHIMMER_LOW_OPACITY + + elapsed = rl.get_time() - self._shimmer_start_time + t_raw = (elapsed % self.SHIMMER_CYCLE_PERIOD) / self.SHIMMER_CYCLE_PERIOD + t_clamped = max(0.0, min(t_raw / self.SHIMMER_SWEEP_FRACTION, 1.0)) + t = t_clamped * t_clamped * (3.0 - 2.0 * t_clamped) # smoothstep + + margin = shimmer_width * self.SHIMMER_BAND_WIDTH + center = shimmer_left + shimmer_width + margin - t * (shimmer_width + 2.0 * margin) + + d = char_x - center + shimmer = math.exp(-0.5 * d * d / (sigma * sigma)) + return self.SHIMMER_LOW_OPACITY + (1.0 - self.SHIMMER_LOW_OPACITY) * shimmer + + def _render_line(self, line, size, emojis, current_y, x_offset=0.0): + # Calculate horizontal position + if self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_LEFT: + line_x = self._rect.x + self._text_padding + elif self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_CENTER: + line_x = self._rect.x + (self._rect.width - size.x) / 2 + elif self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: + line_x = self._rect.x + self._rect.width - size.x - self._text_padding + else: + line_x = self._rect.x + self._text_padding + line_x += self._scroll_offset + x_offset + + if self._shimmer: + self._render_line_shimmer(line, line_x, current_y) + else: + # Render line with emojis + self._render_line_normal(line, emojis, line_x, current_y) + + def _render_line_normal(self, line, emojis, line_x, current_y): + line_pos = rl.Vector2(line_x, current_y) + prev_index = 0 + + for start, end, emoji in emojis: + # Draw text before emoji + text_before = line[prev_index:start] + if text_before: + rl.draw_text_ex(self._font, text_before, line_pos, self._font_size, self._spacing_pixels, self._text_color) + width_before = measure_text_cached(self._font, text_before, self._font_size, self._spacing_pixels) + line_pos.x += width_before.x + + # Draw emoji + tex = emoji_tex(emoji) + emoji_scale = self._font_size / tex.height * FONT_SCALE + rl.draw_texture_ex(tex, line_pos, 0.0, emoji_scale, self._text_color) + # Emoji width is font_size * FONT_SCALE (as per measure_text_cached) + line_pos.x += self._font_size * FONT_SCALE + prev_index = end + + # Draw remaining text after last emoji + text_after = line[prev_index:] + if text_after: + rl.draw_text_ex(self._font, text_after, line_pos, self._font_size, self._spacing_pixels, self._text_color) + + def _render_line_shimmer(self, line, line_x, current_y): + # Shimmer range based on widest line so sweep is even across all lines + max_width = self.text_width + if self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: + shimmer_left = self._rect.x + self._rect.width - self._text_padding - max_width + elif self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_CENTER: + shimmer_left = self._rect.x + (self._rect.width - max_width) / 2 + else: + shimmer_left = self._rect.x + self._text_padding + + base_a = self._text_color.a / 255.0 + cursor_x = line_x + for ch in line: + char_width = measure_text_cached(self._font, ch, self._font_size, self._spacing_pixels).x + char_center_x = cursor_x + char_width / 2.0 + alpha = int(255 * self._shimmer_alpha(char_center_x, shimmer_left, max_width) * base_a) + color = rl.Color(self._text_color.r, self._text_color.g, self._text_color.b, alpha) + rl.draw_text_ex(self._font, ch, rl.Vector2(cursor_x, current_y), self._font_size, 0, color) + cursor_x += char_width + self._spacing_pixels diff --git a/system/ui/widgets/layouts.py b/system/ui/widgets/layouts.py new file mode 100644 index 00000000000000..6bbc49e9275604 --- /dev/null +++ b/system/ui/widgets/layouts.py @@ -0,0 +1,59 @@ +from enum import IntFlag +from openpilot.system.ui.widgets import Widget + + +class Alignment(IntFlag): + LEFT = 0 + # TODO: implement + # H_CENTER = 2 + # RIGHT = 4 + + TOP = 8 + V_CENTER = 16 + BOTTOM = 32 + + +class HBoxLayout(Widget): + """ + A Widget that lays out child Widgets horizontally. + """ + + def __init__(self, widgets: list[Widget] | None = None, spacing: int = 0, + alignment: Alignment = Alignment.LEFT | Alignment.V_CENTER): + super().__init__() + self._spacing = spacing + self._alignment = alignment + + if widgets is not None: + for widget in widgets: + self.add_widget(widget) + + @property + def widgets(self) -> list[Widget]: + return self._children + + def add_widget(self, widget: Widget) -> None: + self._child(widget) + + def _render(self, _): + visible_widgets = [w for w in self._children if w.is_visible] + + cur_offset_x = 0 + + for idx, widget in enumerate(visible_widgets): + spacing = self._spacing if (idx > 0) else 0 + + x = self._rect.x + cur_offset_x + spacing + cur_offset_x += widget.rect.width + spacing + + if self._alignment & Alignment.TOP: + y = self._rect.y + elif self._alignment & Alignment.BOTTOM: + y = self._rect.y + self._rect.height - widget.rect.height + else: # center + y = self._rect.y + (self._rect.height - widget.rect.height) / 2 + + # Update widget position and render + widget.set_position(x, y) + widget.set_parent_rect(self._rect) + widget.render() diff --git a/system/ui/widgets/list_view.py b/system/ui/widgets/list_view.py new file mode 100644 index 00000000000000..82613c37c8efac --- /dev/null +++ b/system/ui/widgets/list_view.py @@ -0,0 +1,468 @@ +import os +import pyray as rl +from collections.abc import Callable +from abc import ABC +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.toggle import Toggle, WIDTH as TOGGLE_WIDTH, HEIGHT as TOGGLE_HEIGHT +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets.html_render import HtmlRenderer, ElementType + +ITEM_BASE_WIDTH = 600 +ITEM_BASE_HEIGHT = 170 +ITEM_PADDING = 20 +ITEM_TEXT_FONT_SIZE = 50 +ITEM_TEXT_COLOR = rl.WHITE +ITEM_TEXT_VALUE_COLOR = rl.Color(170, 170, 170, 255) +ITEM_DESC_TEXT_COLOR = rl.Color(128, 128, 128, 255) +ITEM_DESC_FONT_SIZE = 40 +ITEM_DESC_V_OFFSET = 140 +RIGHT_ITEM_PADDING = 20 +ICON_SIZE = 80 +BUTTON_WIDTH = 250 +BUTTON_HEIGHT = 100 +BUTTON_BORDER_RADIUS = 50 +BUTTON_FONT_SIZE = 35 +BUTTON_FONT_WEIGHT = FontWeight.MEDIUM + +TEXT_PADDING = 20 + + +def _resolve_value(value, default=""): + if callable(value): + return value() + return value if value is not None else default + + +# Abstract base class for right-side items +class ItemAction(Widget, ABC): + def __init__(self, width: int = BUTTON_HEIGHT, enabled: bool | Callable[[], bool] = True): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, width, 0)) + self._enabled_source = enabled + + def get_width_hint(self) -> float: + # Return's action ideal width, 0 means use full width + return self._rect.width + + def set_enabled(self, enabled: bool | Callable[[], bool]): + self._enabled_source = enabled + + @property + def enabled(self): + return _resolve_value(self._enabled_source, False) + + +class ToggleAction(ItemAction): + def __init__(self, initial_state: bool = False, width: int = TOGGLE_WIDTH, enabled: bool | Callable[[], bool] = True, + callback: Callable[[bool], None] | None = None): + super().__init__(width, enabled) + self.toggle = Toggle(initial_state=initial_state, callback=callback) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self.toggle.set_touch_valid_callback(touch_callback) + + def _render(self, rect: rl.Rectangle) -> bool: + self.toggle.set_enabled(self.enabled) + clicked = self.toggle.render(rl.Rectangle(rect.x, rect.y + (rect.height - TOGGLE_HEIGHT) / 2, self._rect.width, TOGGLE_HEIGHT)) + return bool(clicked) + + def set_state(self, state: bool): + self.toggle.set_state(state) + + def get_state(self) -> bool: + return self.toggle.get_state() + + +class ButtonAction(ItemAction): + def __init__(self, text: str | Callable[[], str], width: int = BUTTON_WIDTH, enabled: bool | Callable[[], bool] = True): + super().__init__(width, enabled) + self._text_source = text + self._value_source: str | Callable[[], str] | None = None + self._pressed = False + self._font = gui_app.font(FontWeight.NORMAL) + + def pressed(): + self._pressed = True + + self._button = Button( + self.text, + font_size=BUTTON_FONT_SIZE, + font_weight=BUTTON_FONT_WEIGHT, + button_style=ButtonStyle.LIST_ACTION, + border_radius=BUTTON_BORDER_RADIUS, + click_callback=pressed, + text_padding=0, + ) + self.set_enabled(enabled) + + def get_width_hint(self) -> float: + value_text = self.value + if value_text: + text_width = measure_text_cached(self._font, value_text, ITEM_TEXT_FONT_SIZE).x + return text_width + BUTTON_WIDTH + TEXT_PADDING + else: + return BUTTON_WIDTH + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self._button.set_touch_valid_callback(touch_callback) + + def set_text(self, text: str | Callable[[], str]): + self._text_source = text + + def set_value(self, value: str | Callable[[], str]): + self._value_source = value + + @property + def text(self): + return _resolve_value(self._text_source, tr("Error")) + + @property + def value(self): + return _resolve_value(self._value_source, "") + + def _render(self, rect: rl.Rectangle) -> bool: + self._button.set_text(self.text) + self._button.set_enabled(_resolve_value(self.enabled)) + button_rect = rl.Rectangle(rect.x + rect.width - BUTTON_WIDTH, rect.y + (rect.height - BUTTON_HEIGHT) / 2, BUTTON_WIDTH, BUTTON_HEIGHT) + self._button.render(button_rect) + + value_text = self.value + if value_text: + value_rect = rl.Rectangle(rect.x, rect.y, rect.width - BUTTON_WIDTH - TEXT_PADDING, rect.height) + gui_label(value_rect, value_text, font_size=ITEM_TEXT_FONT_SIZE, color=ITEM_TEXT_VALUE_COLOR, + font_weight=FontWeight.NORMAL, alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + # TODO: just use the generic Widget click callbacks everywhere, no returning from render + pressed = self._pressed + self._pressed = False + return pressed + + +class TextAction(ItemAction): + def __init__(self, text: str | Callable[[], str], color: rl.Color = ITEM_TEXT_COLOR, enabled: bool | Callable[[], bool] = True): + self._text_source = text + self.color = color + + self._font = gui_app.font(FontWeight.NORMAL) + initial_text = _resolve_value(text, "") + text_width = measure_text_cached(self._font, initial_text, ITEM_TEXT_FONT_SIZE).x + super().__init__(int(text_width + TEXT_PADDING), enabled) + + @property + def text(self): + return _resolve_value(self._text_source, tr("Error")) + + def get_width_hint(self) -> float: + text_width = measure_text_cached(self._font, self.text, ITEM_TEXT_FONT_SIZE).x + return text_width + TEXT_PADDING + + def _render(self, rect: rl.Rectangle) -> bool: + gui_label(self._rect, self.text, font_size=ITEM_TEXT_FONT_SIZE, color=self.color, + font_weight=FontWeight.NORMAL, alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + return False + + def set_text(self, text: str | Callable[[], str]): + self._text_source = text + + +class DualButtonAction(ItemAction): + def __init__(self, left_text: str | Callable[[], str], right_text: str | Callable[[], str], left_callback: Callable | None = None, + right_callback: Callable | None = None, enabled: bool | Callable[[], bool] = True): + super().__init__(width=0, enabled=enabled) # Width 0 means use full width + self.left_button = Button(left_text, click_callback=left_callback, button_style=ButtonStyle.NORMAL, text_padding=0) + self.right_button = Button(right_text, click_callback=right_callback, button_style=ButtonStyle.DANGER, text_padding=0) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self.left_button.set_touch_valid_callback(touch_callback) + self.right_button.set_touch_valid_callback(touch_callback) + + def _render(self, rect: rl.Rectangle): + button_spacing = 30 + button_height = 120 + button_width = (rect.width - button_spacing) / 2 + button_y = rect.y + (rect.height - button_height) / 2 + + left_rect = rl.Rectangle(rect.x, button_y, button_width, button_height) + right_rect = rl.Rectangle(rect.x + button_width + button_spacing, button_y, button_width, button_height) + + # expand one to full width if other is not visible + if not self.left_button.is_visible: + right_rect.x = rect.x + right_rect.width = rect.width + elif not self.right_button.is_visible: + left_rect.width = rect.width + + # Render buttons + self.left_button.render(left_rect) + self.right_button.render(right_rect) + + +class MultipleButtonAction(ItemAction): + def __init__(self, buttons: list[str | Callable[[], str]], button_width: int, selected_index: int = 0, callback: Callable | None = None): + super().__init__(width=len(buttons) * button_width + (len(buttons) - 1) * RIGHT_ITEM_PADDING, enabled=True) + self.buttons = buttons + self.button_width = button_width + self.selected_button = selected_index + self.callback = callback + self._font = gui_app.font(FontWeight.MEDIUM) + + def set_selected_button(self, index: int): + if 0 <= index < len(self.buttons): + self.selected_button = index + + def get_selected_button(self) -> int: + return self.selected_button + + def _render(self, rect: rl.Rectangle): + spacing = RIGHT_ITEM_PADDING + button_y = rect.y + (rect.height - BUTTON_HEIGHT) / 2 + + for i, _text in enumerate(self.buttons): + button_x = rect.x + i * (self.button_width + spacing) + button_rect = rl.Rectangle(button_x, button_y, self.button_width, BUTTON_HEIGHT) + + # Check button state + mouse_pos = rl.get_mouse_position() + is_pressed = rl.check_collision_point_rec(mouse_pos, button_rect) and self.enabled and self.is_pressed + is_selected = i == self.selected_button + + # Button colors + if is_selected: + bg_color = rl.Color(51, 171, 76, 255) # Green + elif is_pressed: + bg_color = rl.Color(74, 74, 74, 255) # Dark gray + else: + bg_color = rl.Color(57, 57, 57, 255) # Gray + + if not self.enabled: + bg_color = rl.Color(bg_color.r, bg_color.g, bg_color.b, 150) # Dim + + # Draw button + rl.draw_rectangle_rounded(button_rect, 1.0, 20, bg_color) + + # Draw text + text = _resolve_value(_text, "") + text_size = measure_text_cached(self._font, text, 40) + text_x = button_x + (self.button_width - text_size.x) / 2 + text_y = button_y + (BUTTON_HEIGHT - text_size.y) / 2 + text_color = rl.Color(228, 228, 228, 255) if self.enabled else rl.Color(150, 150, 150, 255) + rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), 40, 0, text_color) + + def _handle_mouse_release(self, mouse_pos: MousePos): + spacing = RIGHT_ITEM_PADDING + button_y = self._rect.y + (self._rect.height - BUTTON_HEIGHT) / 2 + for i, _ in enumerate(self.buttons): + button_x = self._rect.x + i * (self.button_width + spacing) + button_rect = rl.Rectangle(button_x, button_y, self.button_width, BUTTON_HEIGHT) + if rl.check_collision_point_rec(mouse_pos, button_rect): + self.selected_button = i + if self.callback: + self.callback(i) + + +class ListItem(Widget): + def __init__(self, title: str | Callable[[], str] = "", icon: str | None = None, description: str | Callable[[], str] | None = None, + description_visible: bool = False, callback: Callable | None = None, + action_item: ItemAction | None = None): + super().__init__() + self._title = title + self.set_icon(icon) + self._description = description + self.description_visible = description_visible + self.callback = callback + self.description_opened_callback: Callable | None = None + self.action_item = action_item + + self.set_rect(rl.Rectangle(0, 0, ITEM_BASE_WIDTH, ITEM_BASE_HEIGHT)) + self._font = gui_app.font(FontWeight.NORMAL) + + self._html_renderer = HtmlRenderer(text="", text_size={ElementType.P: ITEM_DESC_FONT_SIZE}, + text_color=ITEM_DESC_TEXT_COLOR) + self._parse_description(self.description) + + # Cached properties for performance + self._prev_description: str | None = self.description + + def show_event(self): + super().show_event() + self._set_description_visible(False) + + def set_description_opened_callback(self, callback: Callable) -> None: + self.description_opened_callback = callback + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + if self.action_item: + self.action_item.set_touch_valid_callback(touch_callback) + + def set_parent_rect(self, parent_rect: rl.Rectangle): + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + + def _handle_mouse_release(self, mouse_pos: MousePos): + if not self.is_visible: + return + + # Check not in action rect + if self.action_item: + action_rect = self.get_right_item_rect(self._rect) + if rl.check_collision_point_rec(mouse_pos, action_rect): + # Click was on right item, don't toggle description + return + + self._set_description_visible(not self.description_visible) + + def _set_description_visible(self, visible: bool): + if self.description and self.description_visible != visible: + self.description_visible = visible + # do callback first in case receiver changes description + if self.description_visible and self.description_opened_callback is not None: + self.description_opened_callback() + # Call _update_state to catch any description changes + self._update_state() + + content_width = int(self._rect.width - ITEM_PADDING * 2) + self._rect.height = self.get_item_height(self._font, content_width) + + def _update_state(self): + # Detect changes if description is callback + new_description = self.description + if new_description != self._prev_description: + self._parse_description(new_description) + + def _render(self, _): + if not self.is_visible: + return + + # Don't draw items that are not in parent's viewport + if ((self._rect.y + self.rect.height) <= self._parent_rect.y or + self._rect.y >= (self._parent_rect.y + self._parent_rect.height)): + return + + content_x = self._rect.x + ITEM_PADDING + text_x = content_x + + # Only draw title and icon for items that have them + if self.title: + # Draw icon if present + if self.icon: + rl.draw_texture_ex(self._icon_texture, rl.Vector2(content_x, self._rect.y + (ITEM_BASE_HEIGHT - self._icon_texture.height) / 2), 0.0, 1.0, rl.WHITE) + text_x += ICON_SIZE + ITEM_PADDING + + # Draw main text + text_size = measure_text_cached(self._font, self.title, ITEM_TEXT_FONT_SIZE) + item_y = self._rect.y + (ITEM_BASE_HEIGHT - text_size.y) // 2 + rl.draw_text_ex(self._font, self.title, rl.Vector2(text_x, item_y), ITEM_TEXT_FONT_SIZE, 0, ITEM_TEXT_COLOR) + + # Draw description if visible + if self.description_visible: + content_width = int(self._rect.width - ITEM_PADDING * 2) + description_height = self._html_renderer.get_total_height(content_width) + description_rect = rl.Rectangle( + self._rect.x + ITEM_PADDING, + self._rect.y + ITEM_DESC_V_OFFSET, + content_width, + description_height + ) + self._html_renderer.render(description_rect) + + # Draw right item if present + if self.action_item: + right_rect = self.get_right_item_rect(self._rect) + right_rect.y = self._rect.y + if self.action_item.render(right_rect) and self.action_item.enabled: + # Right item was clicked/activated + if self.callback: + self.callback() + + def set_icon(self, icon: str | None): + self.icon = icon + self._icon_texture = gui_app.texture(os.path.join("icons", self.icon), ICON_SIZE, ICON_SIZE) if self.icon else None + + def set_description(self, description: str | Callable[[], str] | None): + self._description = description + + def _parse_description(self, new_desc): + self._html_renderer.parse_html_content(new_desc) + self._prev_description = new_desc + + @property + def title(self): + return _resolve_value(self._title, "") + + @property + def description(self): + return _resolve_value(self._description, "") + + def get_item_height(self, font: rl.Font, max_width: int) -> float: + if not self.is_visible: + return 0 + + height = float(ITEM_BASE_HEIGHT) + if self.description_visible: + description_height = self._html_renderer.get_total_height(max_width) + height += description_height - (ITEM_BASE_HEIGHT - ITEM_DESC_V_OFFSET) + ITEM_PADDING + return height + + def get_right_item_rect(self, item_rect: rl.Rectangle) -> rl.Rectangle: + if not self.action_item: + return rl.Rectangle(0, 0, 0, 0) + + right_width = self.action_item.get_width_hint() + if right_width == 0: # Full width action (like DualButtonAction) + return rl.Rectangle(item_rect.x + ITEM_PADDING, item_rect.y, + item_rect.width - (ITEM_PADDING * 2), ITEM_BASE_HEIGHT) + + # Clip width to available space, never overlapping this Item's title + content_width = item_rect.width - (ITEM_PADDING * 2) + title_width = measure_text_cached(self._font, self.title, ITEM_TEXT_FONT_SIZE).x + right_width = min(content_width - title_width, right_width) + + right_x = item_rect.x + item_rect.width - right_width + right_y = item_rect.y + return rl.Rectangle(right_x, right_y, right_width, ITEM_BASE_HEIGHT) + + +# Factory functions +def simple_item(title: str | Callable[[], str], callback: Callable | None = None) -> ListItem: + return ListItem(title=title, callback=callback) + + +def toggle_item(title: str | Callable[[], str], description: str | Callable[[], str] | None = None, initial_state: bool = False, + callback: Callable | None = None, icon: str = "", enabled: bool | Callable[[], bool] = True) -> ListItem: + action = ToggleAction(initial_state=initial_state, enabled=enabled, callback=callback) + return ListItem(title=title, description=description, action_item=action, icon=icon) + + +def button_item(title: str | Callable[[], str], button_text: str | Callable[[], str], description: str | Callable[[], str] | None = None, + callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + action = ButtonAction(text=button_text, enabled=enabled) + return ListItem(title=title, description=description, action_item=action, callback=callback) + + +def text_item(title: str | Callable[[], str], value: str | Callable[[], str], description: str | Callable[[], str] | None = None, + callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + action = TextAction(text=value, color=ITEM_TEXT_VALUE_COLOR, enabled=enabled) + return ListItem(title=title, description=description, action_item=action, callback=callback) + + +def dual_button_item(left_text: str | Callable[[], str], right_text: str | Callable[[], str], + left_callback: Callable | None = None, right_callback: Callable | None = None, + description: str | Callable[[], str] | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + action = DualButtonAction(left_text, right_text, left_callback, right_callback, enabled) + return ListItem(title="", description=description, action_item=action) + + +def multiple_button_item(title: str | Callable[[], str], description: str | Callable[[], str], buttons: list[str | Callable[[], str]], selected_index: int, + button_width: int = BUTTON_WIDTH, callback: Callable | None = None, icon: str = ""): + action = MultipleButtonAction(buttons, button_width, selected_index, callback=callback) + return ListItem(title=title, description=description, icon=icon, action_item=action) diff --git a/system/ui/widgets/mici_keyboard.py b/system/ui/widgets/mici_keyboard.py new file mode 100644 index 00000000000000..bc3041aa3c67df --- /dev/null +++ b/system/ui/widgets/mici_keyboard.py @@ -0,0 +1,405 @@ +from enum import IntEnum +import pyray as rl +import numpy as np +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos, MouseEvent +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter + +CHAR_FONT_SIZE = 42 +CHAR_NEAR_FONT_SIZE = CHAR_FONT_SIZE * 2 +SELECTED_CHAR_FONT_SIZE = 128 +CHAR_CAPS_FONT_SIZE = 38 # TODO: implement this +NUMBER_LAYER_SWITCH_FONT_SIZE = 24 +KEYBOARD_COLUMN_PADDING = 33 +KEYBOARD_ROW_PADDING = {0: 44, 1: 33, 2: 44} # TODO: 2 should be 116 with extra control keys added in + +KEY_TOUCH_AREA_OFFSET = 10 # px +KEY_DRAG_HYSTERESIS = 5 # px +KEY_MIN_ANIMATION_TIME = 0.075 # s + +DEBUG = False +ANIMATION_SCALE = 0.65 + + +def zip_repeat(a, b): + la, lb = len(a), len(b) + for i in range(max(la, lb)): + yield (a[i] if i < la else a[-1], + b[i] if i < lb else b[-1]) + + +def fast_euclidean_distance(dx, dy): + # https://en.wikibooks.org/wiki/Algorithms/Distance_approximations + max_d, min_d = abs(dx), abs(dy) + if max_d < min_d: + max_d, min_d = min_d, max_d + return 0.941246 * max_d + 0.41 * min_d + + +class Key(Widget): + def __init__(self, char: str, font_weight: FontWeight = FontWeight.SEMI_BOLD): + super().__init__() + self.char = char + self._font = gui_app.font(font_weight) + self._x_filter = BounceFilter(0.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) + self._y_filter = BounceFilter(0.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) + self._size_filter = BounceFilter(CHAR_FONT_SIZE, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) + self._alpha_filter = BounceFilter(1.0, 0.075 * ANIMATION_SCALE, 1 / gui_app.target_fps) + + self._color = rl.Color(255, 255, 255, 255) + + self._position_initialized = False + self.original_position = rl.Vector2(0, 0) + + def set_position(self, x: float, y: float, smooth: bool = True): + # Smooth keys within parent rect + base_y = self._parent_rect.y if self._parent_rect else 0.0 + local_y = y - base_y + + if not self._position_initialized: + self._x_filter.x = x + self._y_filter.x = local_y + # keep track of original position so dragging around feels consistent. also move touch area down a bit + self.original_position = rl.Vector2(x, local_y + KEY_TOUCH_AREA_OFFSET) + self._position_initialized = True + + if not smooth: + self._x_filter.x = x + self._y_filter.x = local_y + + self._rect.x = self._x_filter.update(x) + self._rect.y = base_y + self._y_filter.update(local_y) + + def set_alpha(self, alpha: float): + self._alpha_filter.update(alpha) + + def get_position(self) -> tuple[float, float]: + return self._rect.x, self._rect.y + + def _update_state(self): + self._color.a = min(int(255 * self._alpha_filter.x), 255) + + def _render(self, _): + # center char at rect position + text_size = measure_text_cached(self._font, self.char, self._get_font_size()) + x = self._rect.x + self._rect.width / 2 - text_size.x / 2 + y = self._rect.y + self._rect.height / 2 - text_size.y / 2 + rl.draw_text_ex(self._font, self.char, (x, y), self._get_font_size(), 0, self._color) + + if DEBUG: + rl.draw_circle(int(self._rect.x), int(self._rect.y), 5, rl.RED) # Debug: draw circle around key + rl.draw_rectangle_lines_ex(self._rect, 2, rl.RED) + + def set_font_size(self, size: float): + self._size_filter.update(size) + + def _get_font_size(self) -> int: + return round(self._size_filter.x) + + +class SmallKey(Key): + def __init__(self, chars: str): + super().__init__(chars, FontWeight.BOLD) + self._size_filter.x = NUMBER_LAYER_SWITCH_FONT_SIZE + + def set_font_size(self, size: float): + self._size_filter.update(size * (NUMBER_LAYER_SWITCH_FONT_SIZE / CHAR_FONT_SIZE)) + + +class IconKey(Key): + def __init__(self, icon: str, vertical_align: str = "center", char: str = "", icon_size: tuple[int, int] = (38, 38)): + super().__init__(char) + self._icon_size = icon_size + self._icon = gui_app.texture(icon, *icon_size) + self._vertical_align = vertical_align + + def set_icon(self, icon: str, icon_size: tuple[int, int] | None = None): + size = icon_size if icon_size is not None else self._icon_size + self._icon = gui_app.texture(icon, *size) + + def _render(self, _): + scale = np.interp(self._size_filter.x, [CHAR_FONT_SIZE, CHAR_NEAR_FONT_SIZE], [1, 1.5]) + + if self._vertical_align == "center": + dest_rec = rl.Rectangle(self._rect.x + (self._rect.width - self._icon.width * scale) / 2, + self._rect.y + (self._rect.height - self._icon.height * scale) / 2, + self._icon.width * scale, self._icon.height * scale) + src_rec = rl.Rectangle(0, 0, self._icon.width, self._icon.height) + rl.draw_texture_pro(self._icon, src_rec, dest_rec, rl.Vector2(0, 0), 0, self._color) + + elif self._vertical_align == "bottom": + dest_rec = rl.Rectangle(self._rect.x + (self._rect.width - self._icon.width * scale) / 2, self._rect.y, + self._icon.width * scale, self._icon.height * scale) + src_rec = rl.Rectangle(0, 0, self._icon.width, self._icon.height) + rl.draw_texture_pro(self._icon, src_rec, dest_rec, rl.Vector2(0, 0), 0, self._color) + + if DEBUG: + rl.draw_circle(int(self._rect.x), int(self._rect.y), 5, rl.RED) # Debug: draw circle around key + rl.draw_rectangle_lines_ex(self._rect, 2, rl.RED) + + +class CapsState(IntEnum): + LOWER = 0 + UPPER = 1 + LOCK = 2 + + +class MiciKeyboard(Widget): + def __init__(self, auto_return_to_letters: str = ""): + super().__init__() + self._auto_return_to_letters = auto_return_to_letters + + lower_chars = [ + "qwertyuiop", + "asdfghjkl", + "zxcvbnm", + ] + upper_chars = ["".join([char.upper() for char in row]) for row in lower_chars] + special_chars = [ + "1234567890", + "-/:;()$&@\"", + "~.,?!'#%", + ] + super_special_chars = [ + "1234567890", + "`[]{}^*+=_", + "\\|<>¥€£•", + ] + + self._lower_keys = [[Key(char) for char in row] for row in lower_chars] + self._upper_keys = [[Key(char) for char in row] for row in upper_chars] + self._special_keys = [[Key(char) for char in row] for row in special_chars] + self._super_special_keys = [[Key(char) for char in row] for row in super_special_chars] + + # control keys + self._space_key = IconKey("icons_mici/settings/keyboard/space.png", char=" ", vertical_align="bottom", icon_size=(43, 14)) + self._caps_key = IconKey("icons_mici/settings/keyboard/caps_lower.png", icon_size=(38, 33)) + # these two are in different places on some layouts + self._123_key, self._123_key2 = SmallKey("123"), SmallKey("123") + self._abc_key = SmallKey("abc") + self._super_special_key = SmallKey("#+=") + + # insert control keys + for keys in (self._lower_keys, self._upper_keys): + keys[2].insert(0, self._caps_key) + keys[2].append(self._123_key) + + for keys in (self._lower_keys, self._upper_keys, self._special_keys, self._super_special_keys): + keys[1].append(self._space_key) + + for keys in (self._special_keys, self._super_special_keys): + keys[2].append(self._abc_key) + + self._special_keys[2].insert(0, self._super_special_key) + self._super_special_keys[2].insert(0, self._123_key2) + + # set initial keys + self._current_keys: list[list[Key]] = [] + self._set_keys(self._lower_keys) + self._caps_state = CapsState.LOWER + self._initialized = False + + self._load_images() + + self._closest_key: tuple[Key | None, float] = None, float('inf') + self._selected_key_t: float | None = None # time key was initially selected + self._unselect_key_t: float | None = None # time to unselect key after release + self._dragging_on_keyboard = False + + self._text: str = "" + + self._bg_scale_filter = BounceFilter(1.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) + self._selected_key_filter = FirstOrderFilter(0.0, 0.075 * ANIMATION_SCALE, 1 / gui_app.target_fps) + + def get_candidate_character(self) -> str: + # return str of character about to be added to text + key = self._closest_key[0] + return key.char if key is not None and key.__class__ is Key and self._dragging_on_keyboard else "" + + def get_keyboard_height(self) -> int: + return int(self._txt_bg.height) + + def _load_images(self): + self._txt_bg = gui_app.texture("icons_mici/settings/keyboard/keyboard_background.png", 520, 170, keep_aspect_ratio=False) + + def _set_keys(self, keys: list[list[Key]]): + # inherit previous keys' positions to fix switching animation + for current_row, row in zip(self._current_keys, keys, strict=False): + # not all layouts have the same number of keys + for current_key, key in zip_repeat(current_row, row): + # reset parent rect for new keys + key.set_parent_rect(self._rect) + current_pos = current_key.get_position() + key.set_position(current_pos[0], current_pos[1], smooth=False) + + self._current_keys = keys + + def set_text(self, text: str): + self._text = text + + def text(self) -> str: + return self._text + + def _handle_mouse_event(self, mouse_event: MouseEvent) -> None: + keyboard_pos_y = self._rect.y + self._rect.height - self._txt_bg.height + if mouse_event.left_pressed: + if mouse_event.pos.y > keyboard_pos_y: + self._dragging_on_keyboard = True + elif mouse_event.left_released: + self._dragging_on_keyboard = False + + if mouse_event.left_down and self._dragging_on_keyboard: + self._closest_key = self._get_closest_key() + if self._selected_key_t is None: + self._selected_key_t = rl.get_time() + + # unselect key temporarily if mouse goes above keyboard + if mouse_event.pos.y <= keyboard_pos_y: + self._closest_key = (None, float('inf')) + + if DEBUG: + print('HANDLE MOUSE EVENT', mouse_event, self._closest_key[0].char if self._closest_key[0] else 'None') + + def _get_closest_key(self) -> tuple[Key | None, float]: + closest_key: tuple[Key | None, float] = (None, float('inf')) + for row in self._current_keys: + for key in row: + mouse_pos = gui_app.last_mouse_event.pos + # approximate distance for comparison is accurate enough + # use local y coords so parent widget offset (e.g. during NavWidget animate-in) doesn't affect hit testing + dist = abs(key.original_position.x - mouse_pos.x) + abs(key.original_position.y - (mouse_pos.y - self._rect.y)) + if dist < closest_key[1]: + if self._closest_key[0] is None or key is self._closest_key[0] or dist < self._closest_key[1] - KEY_DRAG_HYSTERESIS: + closest_key = (key, dist) + return closest_key + + def _set_uppercase(self, cycle: bool): + self._set_keys(self._upper_keys if cycle else self._lower_keys) + if not cycle: + self._caps_state = CapsState.LOWER + self._caps_key.set_icon("icons_mici/settings/keyboard/caps_lower.png", icon_size=(38, 33)) + else: + if self._caps_state == CapsState.LOWER: + self._caps_state = CapsState.UPPER + self._caps_key.set_icon("icons_mici/settings/keyboard/caps_upper.png", icon_size=(38, 33)) + elif self._caps_state == CapsState.UPPER: + self._caps_state = CapsState.LOCK + self._caps_key.set_icon("icons_mici/settings/keyboard/caps_lock.png", icon_size=(39, 38)) + else: + self._set_uppercase(False) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if self._closest_key[0] is not None: + if self._closest_key[0] == self._caps_key: + self._set_uppercase(True) + elif self._closest_key[0] in (self._123_key, self._123_key2): + self._set_keys(self._special_keys) + elif self._closest_key[0] == self._abc_key: + self._set_uppercase(False) + elif self._closest_key[0] == self._super_special_key: + self._set_keys(self._super_special_keys) + else: + self._text += self._closest_key[0].char + + # Reset caps state + if self._caps_state == CapsState.UPPER: + self._set_uppercase(False) + + # Switch back to letters after common URL delimiters + if self._closest_key[0].char in self._auto_return_to_letters and self._current_keys in (self._special_keys, self._super_special_keys): + self._set_uppercase(False) + + # ensure minimum selected animation time + key_selected_dt = rl.get_time() - (self._selected_key_t or 0) + cur_t = rl.get_time() + self._unselect_key_t = cur_t + KEY_MIN_ANIMATION_TIME if (key_selected_dt < KEY_MIN_ANIMATION_TIME) else cur_t + + def backspace(self): + if self._text: + self._text = self._text[:-1] + + def space(self): + self._text += ' ' + + def _update_state(self): + # update selected key filter + self._selected_key_filter.update(self._closest_key[0] is not None) + + # unselect key after animation plays + if (self._unselect_key_t is not None and rl.get_time() > self._unselect_key_t) or not self.enabled: + self._closest_key = (None, float('inf')) + self._unselect_key_t = None + self._selected_key_t = None + + def _lay_out_keys(self, bg_x, bg_y, keys: list[list[Key]]): + key_rect = rl.Rectangle(bg_x, bg_y, self._txt_bg.width, self._txt_bg.height) + for row_idx, row in enumerate(keys): + padding = KEYBOARD_ROW_PADDING[row_idx] + step_y = (key_rect.height - 2 * KEYBOARD_COLUMN_PADDING) / (len(keys) - 1) + for key_idx, key in enumerate(row): + key_x = key_rect.x + padding + key_idx * ((key_rect.width - 2 * padding) / (len(row) - 1)) + key_y = key_rect.y + KEYBOARD_COLUMN_PADDING + row_idx * step_y + + if self._closest_key[0] is None: + key.set_alpha(1.0) + key.set_font_size(CHAR_FONT_SIZE) + elif key == self._closest_key[0]: + # push key up with a max and inward so user can see key easier + key_y = max(key_y - 120, 40) + key_x += np.interp(key_x, [self._rect.x, self._rect.x + self._rect.width], [100, -100]) + key.set_alpha(1.0) + key.set_font_size(SELECTED_CHAR_FONT_SIZE) + + # draw black circle behind selected key + circle_alpha = int(self._selected_key_filter.x * 225) + rl.draw_circle_gradient(rl.Vector2(key_x + key.rect.width / 2, key_y + key.rect.height / 2), + SELECTED_CHAR_FONT_SIZE, rl.Color(0, 0, 0, circle_alpha), rl.BLANK) + else: + # move other keys away from selected key a bit + dx = key.original_position.x - self._closest_key[0].original_position.x + dy = key.original_position.y - self._closest_key[0].original_position.y + distance_from_selected_key = fast_euclidean_distance(dx, dy) + + inv = 1 / (distance_from_selected_key or 1.0) + ux = dx * inv + uy = dy * inv + + # NOTE: hardcode to 20 to get entire keyboard to move + push_pixels = np.interp(distance_from_selected_key, [0, 250], [20, 0]) + key_x += ux * push_pixels + key_y += uy * push_pixels + + # TODO: slow enough to use an approximation or nah? also caching might work + font_size = np.interp(distance_from_selected_key, [0, 150], [CHAR_NEAR_FONT_SIZE, CHAR_FONT_SIZE]) + + key_alpha = np.interp(distance_from_selected_key, [0, 100], [1.0, 0.35]) + key.set_alpha(key_alpha) + key.set_font_size(font_size) + + # TODO: I like the push amount, so we should clip the pos inside the keyboard rect + key.set_parent_rect(self._rect) + key.set_position(key_x, key_y) + + def _render(self, _): + # draw bg + bg_x = self._rect.x + (self._rect.width - self._txt_bg.width) / 2 + bg_y = self._rect.y + self._rect.height - self._txt_bg.height + + scale = self._bg_scale_filter.update(1.0307692307692307 if self._closest_key[0] is not None else 1.0) + src_rec = rl.Rectangle(0, 0, self._txt_bg.width, self._txt_bg.height) + dest_rec = rl.Rectangle(self._rect.x + self._rect.width / 2 - self._txt_bg.width * scale / 2, bg_y, + self._txt_bg.width * scale, self._txt_bg.height) + + rl.draw_texture_pro(self._txt_bg, src_rec, dest_rec, rl.Vector2(0, 0), 0.0, rl.WHITE) + + # draw keys + if not self._initialized: + for keys in (self._lower_keys, self._upper_keys, self._special_keys, self._super_special_keys): + self._lay_out_keys(bg_x, bg_y, keys) + self._initialized = True + + self._lay_out_keys(bg_x, bg_y, self._current_keys) + for row in self._current_keys: + for key in row: + key.render() diff --git a/system/ui/widgets/nav_widget.py b/system/ui/widgets/nav_widget.py new file mode 100644 index 00000000000000..11770bbe5def5b --- /dev/null +++ b/system/ui/widgets/nav_widget.py @@ -0,0 +1,229 @@ +from __future__ import annotations + +import abc +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter +from openpilot.system.ui.lib.application import gui_app, MousePos, MouseEvent + +SWIPE_AWAY_THRESHOLD = 80 # px to dismiss after releasing +START_DISMISSING_THRESHOLD = 40 # px to start dismissing while dragging +BLOCK_SWIPE_AWAY_THRESHOLD = 60 # px horizontal movement to block swipe away + +NAV_BAR_MARGIN = 6 +NAV_BAR_WIDTH = 205 +NAV_BAR_HEIGHT = 8 + +DISMISS_PUSH_OFFSET = NAV_BAR_MARGIN + NAV_BAR_HEIGHT + 50 # px extra to push down when dismissing +DISMISS_ANIMATION_RC = 0.2 # slightly slower for non-user triggered dismiss animation + + +class NavBar(Widget): + FADE_AFTER_SECONDS = 2.0 + + def __init__(self): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, NAV_BAR_WIDTH, NAV_BAR_HEIGHT)) + self._alpha = 1.0 + self._alpha_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._fade_time = 0.0 + + def set_alpha(self, alpha: float) -> None: + self._alpha = alpha + self._fade_time = rl.get_time() + + def show_event(self): + super().show_event() + self._alpha = 1.0 + self._alpha_filter.x = 1.0 + self._fade_time = rl.get_time() + + def _render(self, _): + if rl.get_time() - self._fade_time > self.FADE_AFTER_SECONDS: + self._alpha = 0.0 + alpha = self._alpha_filter.update(self._alpha) + + # white bar with black border + rl.draw_rectangle_rounded(self._rect, 1.0, 6, rl.Color(255, 255, 255, int(255 * 0.9 * alpha))) + rl.draw_rectangle_rounded_lines_ex(self._rect, 1.0, 6, 2, rl.Color(0, 0, 0, int(255 * 0.3 * alpha))) + + +class NavWidget(Widget, abc.ABC): + """ + A full screen widget that supports back navigation by swiping down from the top. + """ + BACK_TOUCH_AREA_PERCENTAGE = 0.65 + + def __init__(self): + super().__init__() + # State + self._drag_start_pos: MousePos | None = None # cleared after certain amount of horizontal movement + self._dragging_down = False # swiped down enough to trigger dismissing on release + self._playing_dismiss_animation = False # released and animating away + self._y_pos_filter = BounceFilter(0.0, 0.1, 1 / gui_app.target_fps, bounce=1) + + self._back_callback: Callable[[], None] | None = None # persistent callback for user-initiated back navigation + self._dismiss_callback: Callable[[], None] | None = None # transient callback for programmatic dismiss + # TODO: add this functionality to push_widget + self._shown_callback: Callable[[], None] | None = None # transient callback fired after show animation completes + + # TODO: move this state into NavBar + self._nav_bar = self._child(NavBar()) + self._nav_bar_show_time = 0.0 + self._nav_bar_y_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + def _back_enabled(self) -> bool: + # Children can override this to block swipe away, like when not at + # the top of a vertical scroll panel to prevent erroneous swipes + return True + + def set_back_callback(self, callback: Callable[[], None]) -> None: + self._back_callback = callback + + def set_shown_callback(self, callback: Callable[[], None] | None) -> None: + self._shown_callback = callback + + def _handle_mouse_event(self, mouse_event: MouseEvent) -> None: + super()._handle_mouse_event(mouse_event) + + # Don't let touch events change filter state during dismiss animation + if self._playing_dismiss_animation: + return + + if mouse_event.left_pressed: + # user is able to swipe away if starting near top of screen + self._y_pos_filter.update_alpha(0.04) + in_dismiss_area = mouse_event.pos.y < self._rect.height * self.BACK_TOUCH_AREA_PERCENTAGE + + if in_dismiss_area and self._back_enabled(): + self._drag_start_pos = mouse_event.pos + + elif mouse_event.left_down: + if self._drag_start_pos is not None: + # block swiping away if too much horizontal or upward movement + # block (lock-in) threshold is higher than start dismissing + horizontal_movement = abs(mouse_event.pos.x - self._drag_start_pos.x) > BLOCK_SWIPE_AWAY_THRESHOLD + upward_movement = mouse_event.pos.y - self._drag_start_pos.y < -BLOCK_SWIPE_AWAY_THRESHOLD + + if not (horizontal_movement or upward_movement): + # no blocking movement, check if we should start dismissing + if mouse_event.pos.y - self._drag_start_pos.y > START_DISMISSING_THRESHOLD: + self._dragging_down = True + else: + if not self._dragging_down: + self._drag_start_pos = None + + elif mouse_event.left_released: + # reset rc for either slide up or down animation + self._y_pos_filter.update_alpha(0.1) + + # if far enough, trigger back navigation callback + if self._drag_start_pos is not None: + if mouse_event.pos.y - self._drag_start_pos.y > SWIPE_AWAY_THRESHOLD: + self._playing_dismiss_animation = True + + self._drag_start_pos = None + self._dragging_down = False + + def _update_state(self): + super()._update_state() + + new_y = 0.0 + + if self._dragging_down: + self._nav_bar.set_alpha(1.0) + + # FIXME: disabling this widget on new push_widget still causes this widget to track mouse events without mouse down + if not self.enabled: + self._drag_start_pos = None + + if self._drag_start_pos is not None: + last_mouse_event = gui_app.last_mouse_event + # push entire widget as user drags it away + new_y = max(last_mouse_event.pos.y - self._drag_start_pos.y, 0) + if new_y < SWIPE_AWAY_THRESHOLD: + new_y /= 2 # resistance until mouse release would dismiss widget + + if self._playing_dismiss_animation: + new_y = self._rect.height + DISMISS_PUSH_OFFSET + + new_y = self._y_pos_filter.update(new_y) + if abs(new_y) < 1 and abs(self._y_pos_filter.velocity.x) < 0.5: + new_y = self._y_pos_filter.x = 0.0 + self._y_pos_filter.velocity.x = 0.0 + + if self._shown_callback is not None: + self._shown_callback() + self._shown_callback = None + + if new_y > self._rect.height + DISMISS_PUSH_OFFSET - 10: + gui_app.pop_widget() + + # Only one callback should ever be fired + if self._dismiss_callback is not None: + self._dismiss_callback() + self._dismiss_callback = None + elif self._back_callback is not None: + self._back_callback() + + self._playing_dismiss_animation = False + self._drag_start_pos = None + self._dragging_down = False + + self.set_position(self._rect.x, new_y) + + def _layout(self): + # Dim whatever is behind this widget, fading with position (runs after _update_state so position is correct) + overlay_alpha = int(200 * max(0.0, min(1.0, 1.0 - self._rect.y / self._rect.height))) if self._rect.height > 0 else 0 + rl.draw_rectangle_rec(rl.Rectangle(0, 0, self._rect.width, self._rect.height), rl.Color(0, 0, 0, overlay_alpha)) + + bounce_height = 20 + rl.draw_rectangle_rec(rl.Rectangle(self._rect.x, self._rect.y, self._rect.width, self._rect.height + bounce_height), rl.BLACK) + + def render(self, rect: rl.Rectangle | None = None) -> bool | int | None: + ret = super().render(rect) + + bar_x = self._rect.x + (self._rect.width - self._nav_bar.rect.width) / 2 + nav_bar_delayed = rl.get_time() - self._nav_bar_show_time < 0.4 + # User dragging or dismissing, nav bar follows NavWidget + if self._drag_start_pos is not None or self._playing_dismiss_animation: + self._nav_bar_y_filter.x = NAV_BAR_MARGIN + self._y_pos_filter.x + # Waiting to show + elif nav_bar_delayed: + self._nav_bar_y_filter.x = -NAV_BAR_MARGIN - NAV_BAR_HEIGHT + # Animate back to top + else: + self._nav_bar_y_filter.update(NAV_BAR_MARGIN) + + self._nav_bar.set_position(bar_x, self._nav_bar_y_filter.x) + self._nav_bar.render() + + return ret + + @property + def is_dismissing(self) -> bool: + return self._dragging_down or self._playing_dismiss_animation + + def dismiss(self, callback: Callable[[], None] | None = None): + """Programmatically trigger the dismiss animation. Calls pop_widget when done, then callback.""" + if not self._playing_dismiss_animation: + self._playing_dismiss_animation = True + self._y_pos_filter.update_alpha(DISMISS_ANIMATION_RC) + self._dismiss_callback = callback + + def show_event(self): + super().show_event() + + # Reset state + self._drag_start_pos = None + self._dragging_down = False + self._playing_dismiss_animation = False + self._dismiss_callback = None + # Start NavWidget off-screen, no matter how tall it is + self._y_pos_filter.update_alpha(0.1) + self._y_pos_filter.x = gui_app.height + self._y_pos_filter.velocity.x = 0.0 + + self._nav_bar_y_filter.x = -NAV_BAR_MARGIN - NAV_BAR_HEIGHT + self._nav_bar_show_time = rl.get_time() diff --git a/system/ui/widgets/network.py b/system/ui/widgets/network.py new file mode 100644 index 00000000000000..f104ba6add1d06 --- /dev/null +++ b/system/ui/widgets/network.py @@ -0,0 +1,483 @@ +from enum import IntEnum +from functools import partial +from typing import cast + +import pyray as rl +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.wifi_manager import WifiManager, SecurityType, Network, MeteredType, normalize_ssid +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.button import ButtonStyle, Button +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.keyboard import Keyboard +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.list_view import ButtonAction, ListItem, MultipleButtonAction, ToggleAction, button_item, text_item + +# These are only used for AdvancedNetworkSettings, standalone apps just need WifiManagerUI +try: + from openpilot.common.params import Params + from openpilot.selfdrive.ui.ui_state import ui_state + from openpilot.selfdrive.ui.lib.prime_state import PrimeType +except Exception: + Params = None + ui_state = None + PrimeType = None + +NM_DEVICE_STATE_NEED_AUTH = 60 +MIN_PASSWORD_LENGTH = 8 +MAX_PASSWORD_LENGTH = 64 +ITEM_HEIGHT = 160 +ICON_SIZE = 50 + +STRENGTH_ICONS = [ + "icons/wifi_strength_low.png", + "icons/wifi_strength_medium.png", + "icons/wifi_strength_high.png", + "icons/wifi_strength_full.png", +] + + +class PanelType(IntEnum): + WIFI = 0 + ADVANCED = 1 + + +class UIState(IntEnum): + IDLE = 0 + CONNECTING = 1 + NEEDS_AUTH = 2 + SHOW_FORGET_CONFIRM = 3 + FORGETTING = 4 + + +class NavButton(Widget): + def __init__(self, text: str): + super().__init__() + self.text = text + self.set_rect(rl.Rectangle(0, 0, 400, 100)) + + def _render(self, _): + color = rl.Color(74, 74, 74, 255) if self.is_pressed else rl.Color(57, 57, 57, 255) + rl.draw_rectangle_rounded(self._rect, 0.6, 10, color) + gui_label(self.rect, self.text, font_size=60, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + + +class NetworkUI(Widget): + def __init__(self, wifi_manager: WifiManager): + super().__init__() + self._wifi_manager = wifi_manager + self._current_panel: PanelType = PanelType.WIFI + self._wifi_panel = self._child(WifiManagerUI(wifi_manager)) + self._advanced_panel = self._child(AdvancedNetworkSettings(wifi_manager)) + self._nav_button = self._child(NavButton(tr("Advanced"))) + self._nav_button.set_click_callback(self._cycle_panel) + + def show_event(self): + super().show_event() + self._set_current_panel(PanelType.WIFI) + + def _cycle_panel(self): + if self._current_panel == PanelType.WIFI: + self._set_current_panel(PanelType.ADVANCED) + else: + self._set_current_panel(PanelType.WIFI) + + def _render(self, _): + # subtract button + content_rect = rl.Rectangle(self._rect.x, self._rect.y + self._nav_button.rect.height + 40, + self._rect.width, self._rect.height - self._nav_button.rect.height - 40) + if self._current_panel == PanelType.WIFI: + self._nav_button.text = tr("Advanced") + self._nav_button.set_position(self._rect.x + self._rect.width - self._nav_button.rect.width, self._rect.y + 20) + self._wifi_panel.render(content_rect) + else: + self._nav_button.text = tr("Back") + self._nav_button.set_position(self._rect.x, self._rect.y + 20) + self._advanced_panel.render(content_rect) + + self._nav_button.render() + + def _set_current_panel(self, panel: PanelType): + self._current_panel = panel + + +class AdvancedNetworkSettings(Widget): + def __init__(self, wifi_manager: WifiManager): + super().__init__() + self._wifi_manager = wifi_manager + self._wifi_manager.add_callbacks(networks_updated=self._on_network_updated) + self._params = Params() + + self._keyboard = Keyboard(max_text_size=MAX_PASSWORD_LENGTH, min_text_size=MIN_PASSWORD_LENGTH, show_password_toggle=True) + + # Tethering + self._tethering_action = ToggleAction(initial_state=False) + tethering_btn = ListItem(lambda: tr("Enable Tethering"), action_item=self._tethering_action, callback=self._toggle_tethering) + + # Edit tethering password + self._tethering_password_action = ButtonAction(lambda: tr("EDIT")) + tethering_password_btn = ListItem(lambda: tr("Tethering Password"), action_item=self._tethering_password_action, callback=self._edit_tethering_password) + + # Roaming toggle + roaming_enabled = self._params.get_bool("GsmRoaming") + self._roaming_action = ToggleAction(initial_state=roaming_enabled) + self._roaming_btn = ListItem(lambda: tr("Enable Roaming"), action_item=self._roaming_action, callback=self._toggle_roaming) + + # Cellular metered toggle + cellular_metered = self._params.get_bool("GsmMetered") + self._cellular_metered_action = ToggleAction(initial_state=cellular_metered) + self._cellular_metered_btn = ListItem(lambda: tr("Cellular Metered"), + description=lambda: tr("Prevent large data uploads when on a metered cellular connection"), + action_item=self._cellular_metered_action, callback=self._toggle_cellular_metered) + + # APN setting + self._apn_btn = button_item(lambda: tr("APN Setting"), lambda: tr("EDIT"), callback=self._edit_apn) + + # Wi-Fi metered toggle + self._wifi_metered_action = MultipleButtonAction([lambda: tr("default"), lambda: tr("metered"), lambda: tr("unmetered")], 255, 0, + callback=self._toggle_wifi_metered) + wifi_metered_btn = ListItem(lambda: tr("Wi-Fi Network Metered"), description=lambda: tr("Prevent large data uploads when on a metered Wi-Fi connection"), + action_item=self._wifi_metered_action) + + items: list[Widget] = [ + tethering_btn, + tethering_password_btn, + text_item(lambda: tr("IP Address"), lambda: self._wifi_manager.ipv4_address), + self._roaming_btn, + self._apn_btn, + self._cellular_metered_btn, + wifi_metered_btn, + button_item(lambda: tr("Hidden Network"), lambda: tr("CONNECT"), callback=self._connect_to_hidden_network), + ] + + self._scroller = Scroller(items, line_separator=True, spacing=0) + + def _on_network_updated(self, networks: list[Network]): + self._tethering_action.set_enabled(True) + self._tethering_action.set_state(self._wifi_manager.is_tethering_active()) + self._tethering_password_action.set_enabled(True) + + if self._wifi_manager.is_tethering_active() or self._wifi_manager.ipv4_address == "": + self._wifi_metered_action.set_enabled(False) + self._wifi_metered_action.selected_button = 0 + elif self._wifi_manager.ipv4_address != "": + metered = self._wifi_manager.current_network_metered + self._wifi_metered_action.set_enabled(True) + self._wifi_metered_action.selected_button = int(metered) if metered in (MeteredType.UNKNOWN, MeteredType.YES, MeteredType.NO) else 0 + + def _toggle_tethering(self): + checked = self._tethering_action.get_state() + self._tethering_action.set_enabled(False) + if checked: + self._wifi_metered_action.set_enabled(False) + self._wifi_manager.set_tethering_active(checked) + + def _toggle_roaming(self): + self._params.put_bool("GsmRoaming", self._roaming_action.get_state(), block=True) + + def _edit_apn(self): + def update_apn(result: DialogResult): + if result != DialogResult.CONFIRM: + return + + apn = self._keyboard.text.strip() + if apn == "": + self._params.remove("GsmApn") + else: + self._params.put("GsmApn", apn, block=True) + + current_apn = self._params.get("GsmApn") or "" + self._keyboard.reset(min_text_size=0) + self._keyboard.set_title(tr("Enter APN"), tr("leave blank for automatic configuration")) + self._keyboard.set_text(current_apn) + self._keyboard.set_callback(update_apn) + gui_app.push_widget(self._keyboard) + + def _toggle_cellular_metered(self): + self._params.put_bool("GsmMetered", self._cellular_metered_action.get_state(), block=True) + + def _toggle_wifi_metered(self, metered): + metered_type = {0: MeteredType.UNKNOWN, 1: MeteredType.YES, 2: MeteredType.NO}.get(metered, MeteredType.UNKNOWN) + self._wifi_metered_action.set_enabled(False) + self._wifi_manager.set_current_network_metered(metered_type) + + def _connect_to_hidden_network(self): + def connect_hidden(result: DialogResult): + if result != DialogResult.CONFIRM: + return + + ssid = self._keyboard.text + if not ssid: + return + + def enter_password(result: DialogResult): + if result != DialogResult.CONFIRM: + return + + password = self._keyboard.text + if password == "": + # connect without password + self._wifi_manager.connect_to_network(ssid, "", hidden=True) + return + + self._wifi_manager.connect_to_network(ssid, password, hidden=True) + + self._keyboard.reset(min_text_size=0) + self._keyboard.set_title(tr("Enter password"), tr("for \"{}\"").format(ssid)) + self._keyboard.set_callback(enter_password) + gui_app.push_widget(self._keyboard) + + self._keyboard.reset(min_text_size=1) + self._keyboard.set_title(tr("Enter SSID"), "") + self._keyboard.set_callback(connect_hidden) + gui_app.push_widget(self._keyboard) + + def _edit_tethering_password(self): + def update_password(result: DialogResult): + if result != DialogResult.CONFIRM: + return + + password = self._keyboard.text + self._wifi_manager.set_tethering_password(password) + self._tethering_password_action.set_enabled(False) + + self._keyboard.reset(min_text_size=MIN_PASSWORD_LENGTH) + self._keyboard.set_title(tr("Enter new tethering password"), "") + self._keyboard.set_text(self._wifi_manager.tethering_password) + self._keyboard.set_callback(update_password) + gui_app.push_widget(self._keyboard) + + def _update_state(self): + self._wifi_manager.process_callbacks() + + # If not using prime SIM, show GSM settings and enable IPv4 forwarding + show_cell_settings = ui_state.prime_state.get_type() in (PrimeType.NONE, PrimeType.LITE) + self._wifi_manager.set_ipv4_forward(show_cell_settings) + self._roaming_btn.set_visible(show_cell_settings) + self._apn_btn.set_visible(show_cell_settings) + self._cellular_metered_btn.set_visible(show_cell_settings) + + def _render(self, _): + self._scroller.render(self._rect) + + +class WifiManagerUI(Widget): + def __init__(self, wifi_manager: WifiManager): + super().__init__() + self._wifi_manager = wifi_manager + self.state: UIState = UIState.IDLE + self._state_network: Network | None = None # for CONNECTING / NEEDS_AUTH / SHOW_FORGET_CONFIRM / FORGETTING + self._password_retry: bool = False # for NEEDS_AUTH + self.btn_width: int = 200 + self.scroll_panel = GuiScrollPanel() + self.keyboard = Keyboard(max_text_size=MAX_PASSWORD_LENGTH, min_text_size=MIN_PASSWORD_LENGTH, show_password_toggle=True) + self._load_icons() + + self._networks: list[Network] = [] + self._networks_buttons: dict[str, Button] = {} + self._forget_networks_buttons: dict[str, Button] = {} + + self._wifi_manager.add_callbacks(need_auth=self._on_need_auth, + activated=self._on_activated, + forgotten=self._on_forgotten, + networks_updated=self._on_network_updated, + disconnected=self._on_disconnected) + + def show_event(self): + super().show_event() + # start/stop scanning when widget is visible + self._wifi_manager.set_active(True) + + def hide_event(self): + super().hide_event() + self._wifi_manager.set_active(False) + + def _load_icons(self): + for icon in STRENGTH_ICONS + ["icons/checkmark.png", "icons/circled_slash.png", "icons/lock_closed.png"]: + gui_app.texture(icon, ICON_SIZE, ICON_SIZE) + + def _update_state(self): + self._wifi_manager.process_callbacks() + + def _render(self, rect: rl.Rectangle): + if not self._networks: + gui_label(rect, tr("Scanning Wi-Fi networks..."), 72, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + return + + if self.state == UIState.NEEDS_AUTH and self._state_network: + self.keyboard.set_title(tr("Wrong password") if self._password_retry else tr("Enter password"), + tr("for \"{}\"").format(normalize_ssid(self._state_network.ssid))) + self.keyboard.reset(min_text_size=MIN_PASSWORD_LENGTH) + self.keyboard.set_callback(lambda result: self._on_password_entered(cast(Network, self._state_network), result)) + gui_app.push_widget(self.keyboard) + elif self.state == UIState.SHOW_FORGET_CONFIRM and self._state_network: + confirm_dialog = ConfirmDialog("", tr("Forget"), tr("Cancel"), callback=lambda result: self.on_forgot_confirm_finished(self._state_network, result)) + confirm_dialog.set_text(tr("Forget Wi-Fi Network \"{}\"?").format(normalize_ssid(self._state_network.ssid))) + gui_app.push_widget(confirm_dialog) + else: + self._draw_network_list(rect) + + def _on_password_entered(self, network: Network, result: DialogResult): + if result == DialogResult.CONFIRM: + password = self.keyboard.text + self.keyboard.clear() + + if len(password) >= MIN_PASSWORD_LENGTH: + self.connect_to_network(network, password) + elif result == DialogResult.CANCEL: + self.state = UIState.IDLE + + def on_forgot_confirm_finished(self, network, result: DialogResult): + if result == DialogResult.CONFIRM: + self.forget_network(network) + elif result == DialogResult.CANCEL: + self.state = UIState.IDLE + + def _draw_network_list(self, rect: rl.Rectangle): + content_rect = rl.Rectangle(rect.x, rect.y, rect.width, len(self._networks) * ITEM_HEIGHT) + offset = self.scroll_panel.update(rect, content_rect) + + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + for i, network in enumerate(self._networks): + y_offset = rect.y + i * ITEM_HEIGHT + offset + item_rect = rl.Rectangle(rect.x, y_offset, rect.width, ITEM_HEIGHT) + if not rl.check_collision_recs(item_rect, rect): + continue + + self._draw_network_item(item_rect, network) + if i < len(self._networks) - 1: + line_y = int(item_rect.y + item_rect.height - 1) + rl.draw_line(int(item_rect.x), int(line_y), int(item_rect.x + item_rect.width), line_y, rl.LIGHTGRAY) + + rl.end_scissor_mode() + + def _draw_network_item(self, rect, network: Network): + spacing = 50 + ssid_rect = rl.Rectangle(rect.x, rect.y, rect.width - self.btn_width * 2, ITEM_HEIGHT) + signal_icon_rect = rl.Rectangle(rect.x + rect.width - ICON_SIZE, rect.y + (ITEM_HEIGHT - ICON_SIZE) / 2, ICON_SIZE, ICON_SIZE) + security_icon_rect = rl.Rectangle(signal_icon_rect.x - spacing - ICON_SIZE, rect.y + (ITEM_HEIGHT - ICON_SIZE) / 2, ICON_SIZE, ICON_SIZE) + + status_text = "" + if self.state == UIState.CONNECTING and self._state_network: + if self._state_network.ssid == network.ssid: + self._networks_buttons[network.ssid].set_enabled(False) + status_text = tr("CONNECTING...") + elif self.state == UIState.FORGETTING and self._state_network: + if self._state_network.ssid == network.ssid: + self._networks_buttons[network.ssid].set_enabled(False) + status_text = tr("FORGETTING...") + elif network.security_type == SecurityType.UNSUPPORTED: + self._networks_buttons[network.ssid].set_enabled(False) + else: + self._networks_buttons[network.ssid].set_enabled(True) + + self._networks_buttons[network.ssid].render(ssid_rect) + + if status_text: + status_text_rect = rl.Rectangle(security_icon_rect.x - 410, rect.y, 410, ITEM_HEIGHT) + gui_label(status_text_rect, status_text, font_size=48, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + else: + # If the network is saved, show the "Forget" button + if self._wifi_manager.is_connection_saved(network.ssid): + forget_btn_rect = rl.Rectangle( + security_icon_rect.x - self.btn_width - spacing, + rect.y + (ITEM_HEIGHT - 80) / 2, + self.btn_width, + 80, + ) + self._forget_networks_buttons[network.ssid].render(forget_btn_rect) + + self._draw_status_icon(security_icon_rect, network) + self._draw_signal_strength_icon(signal_icon_rect, network) + + def _networks_buttons_callback(self, network): + if not self._wifi_manager.is_connection_saved(network.ssid) and network.security_type != SecurityType.OPEN: + self.state = UIState.NEEDS_AUTH + self._state_network = network + self._password_retry = False + elif self._wifi_manager.wifi_state.ssid != network.ssid: + self.connect_to_network(network) + + def _forget_networks_buttons_callback(self, network): + self.state = UIState.SHOW_FORGET_CONFIRM + self._state_network = network + + def _draw_status_icon(self, rect, network: Network): + """Draw the status icon based on network's connection state""" + icon_file = None + if self._wifi_manager.connected_ssid == network.ssid and self.state != UIState.CONNECTING: + icon_file = "icons/checkmark.png" + elif network.security_type == SecurityType.UNSUPPORTED: + icon_file = "icons/circled_slash.png" + elif network.security_type != SecurityType.OPEN: + icon_file = "icons/lock_closed.png" + + if not icon_file: + return + + texture = gui_app.texture(icon_file, ICON_SIZE, ICON_SIZE) + icon_rect = rl.Vector2(rect.x, rect.y + (ICON_SIZE - texture.height) / 2) + rl.draw_texture_v(texture, icon_rect, rl.WHITE) + + def _draw_signal_strength_icon(self, rect: rl.Rectangle, network: Network): + """Draw the Wi-Fi signal strength icon based on network's signal strength""" + strength_level = max(0, min(3, round(network.strength / 33.0))) + rl.draw_texture_v(gui_app.texture(STRENGTH_ICONS[strength_level], ICON_SIZE, ICON_SIZE), rl.Vector2(rect.x, rect.y), rl.WHITE) + + def connect_to_network(self, network: Network, password=''): + self.state = UIState.CONNECTING + self._state_network = network + if self._wifi_manager.is_connection_saved(network.ssid) and not password: + self._wifi_manager.activate_connection(network.ssid) + else: + self._wifi_manager.connect_to_network(network.ssid, password) + + def forget_network(self, network: Network): + self.state = UIState.FORGETTING + self._state_network = network + self._wifi_manager.forget_connection(network.ssid) + + def _on_network_updated(self, networks: list[Network]): + self._networks = networks + for n in self._networks: + self._networks_buttons[n.ssid] = Button(normalize_ssid(n.ssid), partial(self._networks_buttons_callback, n), font_size=55, + text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, button_style=ButtonStyle.TRANSPARENT_WHITE_TEXT) + self._networks_buttons[n.ssid].set_touch_valid_callback(lambda: self.scroll_panel.is_touch_valid()) + self._forget_networks_buttons[n.ssid] = Button(tr("Forget"), partial(self._forget_networks_buttons_callback, n), button_style=ButtonStyle.FORGET_WIFI, + font_size=45) + self._forget_networks_buttons[n.ssid].set_touch_valid_callback(lambda: self.scroll_panel.is_touch_valid()) + + def _on_need_auth(self, ssid): + network = next((n for n in self._networks if n.ssid == ssid), None) + if network: + self.state = UIState.NEEDS_AUTH + self._state_network = network + self._password_retry = True + + def _on_activated(self): + if self.state == UIState.CONNECTING: + self.state = UIState.IDLE + + def _on_forgotten(self, _): + if self.state == UIState.FORGETTING: + self.state = UIState.IDLE + + def _on_disconnected(self): + if self.state == UIState.CONNECTING: + self.state = UIState.IDLE + + +def main(): + gui_app.init_window("Wi-Fi Manager") + gui_app.push_widget(WifiManagerUI(WifiManager())) + + for _ in gui_app.render(): + pass + + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/system/ui/widgets/option_dialog.py b/system/ui/widgets/option_dialog.py new file mode 100644 index 00000000000000..206400a74f1b5b --- /dev/null +++ b/system/ui/widgets/option_dialog.py @@ -0,0 +1,79 @@ +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets.scroller_tici import Scroller + +# Constants +MARGIN = 50 +TITLE_FONT_SIZE = 70 +ITEM_HEIGHT = 135 +BUTTON_SPACING = 50 +BUTTON_HEIGHT = 160 +ITEM_SPACING = 50 +LIST_ITEM_SPACING = 25 + + +class MultiOptionDialog(Widget): + def __init__(self, title, options, current="", option_font_weight=FontWeight.MEDIUM, callback: Callable[[DialogResult], None] | None = None): + super().__init__() + self.title = title + self.options = options + self.current = current + self.selection = current + self._callback = callback + + # Create scroller with option buttons + self.option_buttons = [Button(option, click_callback=lambda opt=option: self._on_option_clicked(opt), + font_weight=option_font_weight, + text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, button_style=ButtonStyle.NORMAL, + text_padding=50, elide_right=True) for option in options] + self.scroller = Scroller(self.option_buttons, spacing=LIST_ITEM_SPACING) + + self.cancel_button = Button(lambda: tr("Cancel"), click_callback=lambda: self._set_result(DialogResult.CANCEL)) + self.select_button = Button(lambda: tr("Select"), click_callback=lambda: self._set_result(DialogResult.CONFIRM), button_style=ButtonStyle.PRIMARY) + + def _set_result(self, result: DialogResult): + gui_app.pop_widget() + if self._callback: + self._callback(result) + + def _on_option_clicked(self, option): + self.selection = option + + def _render(self, rect): + dialog_rect = rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - 2 * MARGIN, rect.height - 2 * MARGIN) + rl.draw_rectangle_rounded(dialog_rect, 0.02, 20, rl.Color(30, 30, 30, 255)) + + content_rect = rl.Rectangle(dialog_rect.x + MARGIN, dialog_rect.y + MARGIN, + dialog_rect.width - 2 * MARGIN, dialog_rect.height - 2 * MARGIN) + + gui_label(rl.Rectangle(content_rect.x, content_rect.y, content_rect.width, TITLE_FONT_SIZE), self.title, 70, font_weight=FontWeight.BOLD) + + # Options area + options_y = content_rect.y + TITLE_FONT_SIZE + ITEM_SPACING + options_h = content_rect.height - TITLE_FONT_SIZE - BUTTON_HEIGHT - 2 * ITEM_SPACING + options_rect = rl.Rectangle(content_rect.x, options_y, content_rect.width, options_h) + + # Update button styles and set width based on selection + for i, option in enumerate(self.options): + selected = option == self.selection + button = self.option_buttons[i] + button.set_button_style(ButtonStyle.PRIMARY if selected else ButtonStyle.NORMAL) + button.set_rect(rl.Rectangle(0, 0, options_rect.width, ITEM_HEIGHT)) + + self.scroller.render(options_rect) + + # Buttons + button_y = content_rect.y + content_rect.height - BUTTON_HEIGHT + button_w = (content_rect.width - BUTTON_SPACING) / 2 + + cancel_rect = rl.Rectangle(content_rect.x, button_y, button_w, BUTTON_HEIGHT) + self.cancel_button.render(cancel_rect) + + select_rect = rl.Rectangle(content_rect.x + button_w + BUTTON_SPACING, button_y, button_w, BUTTON_HEIGHT) + self.select_button.set_enabled(self.selection != self.current) + self.select_button.render(select_rect) diff --git a/system/ui/widgets/script_runner.py b/system/ui/widgets/script_runner.py new file mode 100644 index 00000000000000..b5eeb611efe138 --- /dev/null +++ b/system/ui/widgets/script_runner.py @@ -0,0 +1,380 @@ +""" +Script Runner Widget + +Full-screen overlay for executing and displaying script output. +Provides instructions, start button, live output, and exit functionality. +""" + +import subprocess +import threading +import queue +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle + +MARGIN = 50 +TITLE_FONT_SIZE = 80 +TEXT_FONT_SIZE = 50 +OUTPUT_FONT_SIZE = 40 +LINE_HEIGHT = 50 +BUTTON_WIDTH = 400 +BUTTON_HEIGHT = 120 +BUTTON_SPACING = 30 + + +class ScriptState: + """Script execution states""" + READY = 0 # Showing instructions, waiting for Start + RUNNING = 1 # Script is executing + COMPLETED = 2 # Script finished successfully + ERROR = 3 # Script encountered an error + + +class ScriptRunner(Widget): + """ + Full-screen widget for running scripts with live output display. + + Usage: + runner = ScriptRunner( + title="Refresh maps", + instructions="Instructions for the user...", + script_module="scripts.nap.refresh_osm_maps", + on_close=lambda: gui_app.pop_widget(), + ) + gui_app.push_widget(runner) + """ + + def __init__( + self, + title: str, + instructions: str, + script_module: str, + on_close: Callable | None = None, + cwd: str = "/data/openpilot" + ): + super().__init__() + self._title = title + self._instructions = instructions + self._script_module = script_module + self._on_close = on_close + self._cwd = cwd + + self._state = ScriptState.READY + self._output_lines: list[str] = [] + self._output_queue: queue.Queue[str] = queue.Queue() + self._process: subprocess.Popen | None = None + self._reader_thread: threading.Thread | None = None + + # UI components + self._scroll_panel = GuiScrollPanel() + self._font = gui_app.font(FontWeight.NORMAL) + self._title_font = gui_app.font(FontWeight.BOLD) + + # Buttons + self._start_button = Button( + "Start", + click_callback=self._on_start_clicked, + button_style=ButtonStyle.PRIMARY, + font_size=TEXT_FONT_SIZE + ) + self._exit_button = Button( + "Exit", + click_callback=self._on_exit_clicked, + button_style=ButtonStyle.TRANSPARENT_WHITE_BORDER, + font_size=TEXT_FONT_SIZE + ) + + # Wrap instructions text + self._instruction_lines: list[str] = [] + + def _wrap_text(self, text: str, max_width: float, font_size: int) -> list[str]: + """Wrap text to fit within max_width""" + lines = [] + for paragraph in text.split("\n"): + if not paragraph.strip(): + lines.append("") + continue + + words = paragraph.split() + current_line = "" + + for word in words: + test_line = f"{current_line} {word}".strip() + text_width = measure_text_cached(self._font, test_line, font_size).x + + if text_width <= max_width: + current_line = test_line + else: + if current_line: + lines.append(current_line) + current_line = word + + if current_line: + lines.append(current_line) + + return lines + + def _on_start_clicked(self): + """Start script execution""" + if self._state != ScriptState.READY: + return + + self._state = ScriptState.RUNNING + self._output_lines = ["Starting script...", ""] + + # Start the script in a subprocess + try: + self._process = subprocess.Popen( + ["python", "-m", self._script_module], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=self._cwd, + text=True, + encoding="utf-8", + bufsize=1 # Line buffered + ) + + # Start reader thread + self._reader_thread = threading.Thread(target=self._read_output, daemon=True) + self._reader_thread.start() + + except Exception as e: + self._output_lines.append(f"Error starting script: {e}") + self._state = ScriptState.ERROR + + def _read_output(self): + """Read script output in background thread""" + try: + if self._process and self._process.stdout: + for line in iter(self._process.stdout.readline, ''): + if line: + self._output_queue.put(line.rstrip()) + if self._process.poll() is not None: + break + + # Wait for process to complete + if self._process: + return_code = self._process.wait() + if return_code == 0: + self._output_queue.put("\n[Script completed successfully]") + self._state = ScriptState.COMPLETED + else: + self._output_queue.put(f"\n[Script exited with code {return_code}]") + self._state = ScriptState.ERROR + + except Exception as e: + self._output_queue.put(f"\n[Error reading output: {e}]") + self._state = ScriptState.ERROR + + def _on_exit_clicked(self): + """Handle exit button click""" + # Kill process if still running + if self._process and self._process.poll() is None: + self._process.terminate() + try: + self._process.wait(timeout=2) + except subprocess.TimeoutExpired: + self._process.kill() + + if self._on_close: + self._on_close() + else: + gui_app.pop_widget() + + def _process_output_queue(self): + """Process any pending output from the queue""" + while True: + try: + line = self._output_queue.get_nowait() + self._output_lines.append(line) + except queue.Empty: + break + + def _render(self, rect: rl.Rectangle): + # Draw background + rl.draw_rectangle_rec(rect, rl.Color(20, 20, 20, 255)) + + # Process any pending output + self._process_output_queue() + + content_x = rect.x + MARGIN + content_width = rect.width - MARGIN * 2 + current_y = rect.y + MARGIN + + # Draw title + title_size = measure_text_cached(self._title_font, self._title, TITLE_FONT_SIZE) + rl.draw_text_ex( + self._title_font, + self._title, + rl.Vector2(content_x, current_y), + TITLE_FONT_SIZE, + 0, + rl.WHITE + ) + current_y += title_size.y + MARGIN + + # Draw separator line + rl.draw_line_ex( + rl.Vector2(content_x, current_y), + rl.Vector2(content_x + content_width, current_y), + 2, + rl.Color(80, 80, 80, 255) + ) + current_y += MARGIN + + if self._state == ScriptState.READY: + # Show instructions + self._render_instructions(rect, content_x, content_width, current_y) + else: + # Show output + self._render_output(rect, content_x, content_width, current_y) + + # Draw buttons at bottom + self._render_buttons(rect) + + return None + + def _render_instructions(self, rect: rl.Rectangle, content_x: float, content_width: float, start_y: float): + """Render instruction text""" + # Wrap instructions if not already done + if not self._instruction_lines: + self._instruction_lines = self._wrap_text(self._instructions, content_width, TEXT_FONT_SIZE) + + # Calculate text area + button_area_height = BUTTON_HEIGHT + MARGIN * 2 + text_area_height = rect.height - start_y - button_area_height - rect.y + + # Draw instructions + current_y = start_y + for line in self._instruction_lines: + if current_y + LINE_HEIGHT > start_y + text_area_height: + break + rl.draw_text_ex( + self._font, + line, + rl.Vector2(content_x, current_y), + TEXT_FONT_SIZE, + 0, + rl.Color(200, 200, 200, 255) + ) + current_y += LINE_HEIGHT + + def _render_output(self, rect: rl.Rectangle, content_x: float, content_width: float, start_y: float): + """Render script output with scrolling""" + button_area_height = BUTTON_HEIGHT + MARGIN * 2 + output_area_height = rect.height - start_y - button_area_height - rect.y + + # Create output area rect + output_rect = rl.Rectangle( + content_x, + start_y, + content_width, + output_area_height + ) + + # Calculate content height + content_height = len(self._output_lines) * LINE_HEIGHT + content_rect = rl.Rectangle(0, 0, content_width, content_height) + + # Auto-scroll to bottom when new content arrives + if content_height > output_area_height: + self._scroll_panel._offset_filter_y.x = -(content_height - output_area_height) + + # Get scroll offset + scroll = self._scroll_panel.update(output_rect, content_rect) + + # Draw output with scissor mode + rl.begin_scissor_mode( + int(output_rect.x), + int(output_rect.y), + int(output_rect.width), + int(output_rect.height) + ) + + for i, line in enumerate(self._output_lines): + line_y = output_rect.y + scroll + i * LINE_HEIGHT + + # Skip lines outside visible area + if line_y + LINE_HEIGHT < output_rect.y or line_y > output_rect.y + output_rect.height: + continue + + # Color code based on content + if "[Error" in line or "Error:" in line: + color = rl.Color(255, 100, 100, 255) # Red for errors + elif "[Script completed" in line: + color = rl.Color(100, 255, 100, 255) # Green for success + elif line.startswith("***"): + color = rl.Color(100, 200, 255, 255) # Blue for milestones + else: + color = rl.WHITE + + rl.draw_text_ex( + self._font, + line, + rl.Vector2(output_rect.x, line_y), + OUTPUT_FONT_SIZE, + 0, + color + ) + + rl.end_scissor_mode() + + # Draw status indicator + status_text = "" + status_color = rl.WHITE + if self._state == ScriptState.RUNNING: + status_text = "Running..." + status_color = rl.Color(255, 200, 100, 255) + elif self._state == ScriptState.COMPLETED: + status_text = "Completed" + status_color = rl.Color(100, 255, 100, 255) + elif self._state == ScriptState.ERROR: + status_text = "Error" + status_color = rl.Color(255, 100, 100, 255) + + if status_text: + status_size = measure_text_cached(self._font, status_text, TEXT_FONT_SIZE) + rl.draw_text_ex( + self._font, + status_text, + rl.Vector2(rect.x + rect.width - MARGIN - status_size.x, start_y - LINE_HEIGHT), + TEXT_FONT_SIZE, + 0, + status_color + ) + + def _render_buttons(self, rect: rl.Rectangle): + """Render action buttons at bottom""" + button_y = rect.y + rect.height - MARGIN - BUTTON_HEIGHT + + if self._state == ScriptState.READY: + # Show Start and Exit buttons + start_rect = rl.Rectangle( + rect.x + rect.width - MARGIN - BUTTON_WIDTH * 2 - BUTTON_SPACING, + button_y, + BUTTON_WIDTH, + BUTTON_HEIGHT + ) + exit_rect = rl.Rectangle( + rect.x + rect.width - MARGIN - BUTTON_WIDTH, + button_y, + BUTTON_WIDTH, + BUTTON_HEIGHT + ) + self._start_button.render(start_rect) + self._exit_button.render(exit_rect) + else: + # Show only Exit button (disabled while running) + exit_rect = rl.Rectangle( + rect.x + rect.width - MARGIN - BUTTON_WIDTH, + button_y, + BUTTON_WIDTH, + BUTTON_HEIGHT + ) + # Enable exit button only when not running + self._exit_button.set_enabled(self._state != ScriptState.RUNNING) + self._exit_button.render(exit_rect) diff --git a/system/ui/widgets/scroller.py b/system/ui/widgets/scroller.py new file mode 100644 index 00000000000000..b7b6bf59320b6c --- /dev/null +++ b/system/ui/widgets/scroller.py @@ -0,0 +1,432 @@ +import pyray as rl +import numpy as np +from collections.abc import Callable + +from openpilot.common.filter_simple import FirstOrderFilter, BounceFilter +from openpilot.common.swaglog import cloudlog +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.scroll_panel2 import GuiScrollPanel2, ScrollState +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.nav_widget import NavWidget + +ITEM_SPACING = 20 +LINE_COLOR = rl.GRAY +LINE_PADDING = 40 +ANIMATION_SCALE = 0.6 + +MOVE_LIFT = 20 +MOVE_OVERLAY_ALPHA = 0.65 +SCROLL_RC = 0.15 + +EDGE_SHADOW_WIDTH = 20 + +MIN_ZOOM_ANIMATION_TIME = 0.075 # seconds +DO_ZOOM = False +DO_JELLO = False + + +class ScrollIndicator(Widget): + HORIZONTAL_MARGIN = 4 + + def __init__(self): + super().__init__() + self._txt_scroll_indicator = gui_app.texture("icons_mici/settings/horizontal_scroll_indicator.png", 96, 48) + self._scroll_offset: float = 0.0 + self._content_size: float = 0.0 + self._viewport: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) + + def update(self, scroll_offset: float, content_size: float, viewport: rl.Rectangle) -> None: + self._scroll_offset = scroll_offset + self._content_size = content_size + self._viewport = viewport + + def _render(self, _): + # scale indicator width based on content size + indicator_w = float(np.interp(self._content_size, [1000, 3000], [300, 100])) + + # position based on scroll ratio + slide_range = self._viewport.width - indicator_w + max_scroll = self._content_size - self._viewport.width + scroll_ratio = (-self._scroll_offset / abs(max_scroll)) if abs(max_scroll) > 1e-3 else 0.0 + x = self._viewport.x + scroll_ratio * slide_range + # don't bounce up when NavWidget shows + y = max(self._viewport.y, 0) + self._viewport.height - self._txt_scroll_indicator.height / 2 + + # squeeze when overscrolling past edges + dest_left = max(x, self._viewport.x) + dest_right = min(x + indicator_w, self._viewport.x + self._viewport.width) + dest_w = max(indicator_w / 2, dest_right - dest_left) + + # keep within viewport after applying minimum width + dest_left = min(dest_left, self._viewport.x + self._viewport.width - dest_w) + dest_left = max(dest_left, self._viewport.x) + + src_rec = rl.Rectangle(0, 0, self._txt_scroll_indicator.width, self._txt_scroll_indicator.height) + dest_rec = rl.Rectangle(dest_left, y, dest_w, self._txt_scroll_indicator.height) + rl.draw_texture_pro(self._txt_scroll_indicator, src_rec, dest_rec, rl.Vector2(0, 0), 0.0, + rl.Color(255, 255, 255, int(255 * 0.45))) + + +class _Scroller(Widget): + """Should use wrapper below to reduce boilerplate""" + def __init__(self, items: list[Widget], horizontal: bool = True, snap_items: bool = False, spacing: int = ITEM_SPACING, + pad: int = ITEM_SPACING, scroll_indicator: bool = True, edge_shadows: bool = True): + super().__init__() + self._items: list[Widget] = [] + self._horizontal = horizontal + self._snap_items = snap_items + assert not self._snap_items or self._horizontal, "Snapping is only supported for horizontal scrolling" + self._spacing = spacing + self._pad = pad + + self._reset_scroll_at_show = True + + self._scrolling_to: tuple[float | None, bool, bool] = (None, False, False) # target offset, block_interrupt, block_widget_interaction + self._scrolling_to_filter = FirstOrderFilter(0.0, SCROLL_RC, 1 / gui_app.target_fps) + self._zoom_filter = FirstOrderFilter(1.0, 0.2, 1 / gui_app.target_fps) + self._zoom_out_t: float = 0.0 + + # layout state + self._visible_items: list[Widget] = [] + self._content_size: float = 0.0 + self._scroll_offset: float = 0.0 + + self._item_pos_filter = BounceFilter(0.0, 0.05, 1 / gui_app.target_fps) + + self.scroll_panel = GuiScrollPanel2(self._horizontal) + self._scroll_enabled: bool | Callable[[], bool] = True + + self._show_scroll_indicator = scroll_indicator and self._horizontal + self._scroll_indicator = ScrollIndicator() + self._edge_shadows = edge_shadows and self._horizontal + + # move animation state + # on move; lift src widget -> wait -> move all -> wait -> drop src widget + self._overlay_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps) + self._move_animations: dict[Widget, FirstOrderFilter] = {} + self._move_lift: dict[Widget, FirstOrderFilter] = {} + # these are used to wait before moving/dropping, also to move onto next part of the animation earlier for timing + self._pending_lift: set[Widget] = set() + self._pending_move: set[Widget] = set() + + self.add_widgets(items) + + def set_reset_scroll_at_show(self, scroll: bool): + self._reset_scroll_at_show = scroll + + def scroll_to(self, pos: float, smooth: bool = False, block_interrupt: bool = False, block_widget_interaction: bool = False): + assert smooth or (not block_interrupt and not block_widget_interaction), "Instant scroll cannot block interaction" + + # already there + if abs(pos) < 1: + return + + # FIXME: the padding correction doesn't seem correct + scroll_offset = self.scroll_panel.get_offset() - pos + if smooth: + self._scrolling_to_filter.x = self.scroll_panel.get_offset() + self._scrolling_to = scroll_offset, block_interrupt, block_widget_interaction + else: + self.scroll_panel.set_offset(scroll_offset) + + @property + def is_auto_scrolling(self) -> bool: + return self._scrolling_to[0] is not None + + @property + def items(self) -> list[Widget]: + return self._items + + @property + def content_size(self) -> float: + return self._content_size + + def add_widget(self, item: Widget) -> None: + self._items.append(item) + + # preserve original touch valid callback + original_touch_valid_callback = item._touch_valid_callback + item.set_touch_valid_callback(lambda: self.scroll_panel.is_touch_valid() and self.enabled and not self._scrolling_to[2] + and not self.moving_items and (original_touch_valid_callback() if + original_touch_valid_callback else True)) + + def add_widgets(self, items: list[Widget]) -> None: + for item in items: + self.add_widget(item) + + def set_scrolling_enabled(self, enabled: bool | Callable[[], bool]) -> None: + """Set whether scrolling is enabled (does not affect widget enabled state).""" + self._scroll_enabled = enabled + + def _update_state(self): + if DO_ZOOM: + if self._scrolling_to[0] is not None or self.scroll_panel.state != ScrollState.STEADY: + self._zoom_out_t = rl.get_time() + MIN_ZOOM_ANIMATION_TIME + self._zoom_filter.update(0.85) + else: + if self._zoom_out_t is not None: + if rl.get_time() > self._zoom_out_t: + self._zoom_filter.update(1.0) + else: + self._zoom_filter.update(0.85) + + # Cancel auto-scroll if user starts manually scrolling (unless block_interaction) + if (self.scroll_panel.state in (ScrollState.PRESSED, ScrollState.MANUAL_SCROLL) and + self._scrolling_to[0] is not None and not self._scrolling_to[1]): + self._scrolling_to = None, False, False + + if self._scrolling_to[0] is not None and len(self._pending_lift) == 0: + self._scrolling_to_filter.update(self._scrolling_to[0]) + self.scroll_panel.set_offset(self._scrolling_to_filter.x) + + if abs(self._scrolling_to_filter.x - self._scrolling_to[0]) < 1: # finished scroll + self.scroll_panel.set_offset(self._scrolling_to[0]) + self._scrolling_to = None, False, False + + def _get_scroll(self, visible_items: list[Widget], content_size: float) -> float: + scroll_enabled = self._scroll_enabled() if callable(self._scroll_enabled) else self._scroll_enabled + self.scroll_panel.set_enabled(scroll_enabled and self.enabled and not self._scrolling_to[1]) + + # Snap closest item to center. Skipped while scroll_to() is animating + snap_target: float | None = None + if self._snap_items and visible_items and self._scrolling_to[0] is None: + # TODO: this doesn't handle two small buttons at the edges well + center_pos = self._rect.x + self._rect.width / 2 + closest_delta_pos = min((((item.rect.x + item.rect.width / 2) - center_pos) for item in visible_items), key=abs) + snap_target = self.scroll_panel.get_offset() - closest_delta_pos + + return self.scroll_panel.update(self._rect, content_size, snap_target=snap_target) + + @property + def moving_items(self) -> bool: + return len(self._move_animations) > 0 or len(self._move_lift) > 0 + + def move_item(self, from_idx: int, to_idx: int): + assert self._horizontal + if from_idx == to_idx: + return + + if self.moving_items: + cloudlog.warning(f"Already moving items, cannot move from {from_idx} to {to_idx}") + return + + item = self._items.pop(from_idx) + self._items.insert(to_idx, item) + + # store original position in content space of all affected widgets to animate from + for idx in range(min(from_idx, to_idx), max(from_idx, to_idx) + 1): + affected_item = self._items[idx] + self._move_animations[affected_item] = FirstOrderFilter(affected_item.rect.x - self._scroll_offset, SCROLL_RC, 1 / gui_app.target_fps) + self._pending_move.add(affected_item) + + # lift only src widget to make it more clear which one is moving + self._move_lift[item] = FirstOrderFilter(0.0, SCROLL_RC, 1 / gui_app.target_fps) + self._pending_lift.add(item) + + def _do_move_animation(self, item: Widget, target_x: float, target_y: float) -> tuple[float, float]: + # wait a frame before moving so we match potential pending scroll animation + can_start_move = len(self._pending_lift) == 0 + + if item in self._move_lift: + lift_filter = self._move_lift[item] + + # Animate lift + if len(self._pending_move) > 0: + lift_filter.update(MOVE_LIFT) + # start moving when almost lifted + if abs(lift_filter.x - MOVE_LIFT) < 2: + self._pending_lift.discard(item) + else: + # if done moving, animate down + lift_filter.update(0) + if abs(lift_filter.x) < 1: + del self._move_lift[item] + target_y -= lift_filter.x + + # Animate move + if item in self._move_animations: + move_filter = self._move_animations[item] + + # compare/update in content space to match filter + content_x = target_x - self._scroll_offset + if can_start_move: + move_filter.update(content_x) + + # drop when close to target + if abs(move_filter.x - content_x) < 10: + self._pending_move.discard(item) + + # finished moving + if abs(move_filter.x - content_x) < 1: + del self._move_animations[item] + target_x = move_filter.x + self._scroll_offset + + return target_x, target_y + + def _layout(self): + self._visible_items = [item for item in self._items if item.is_visible] + + self._content_size = sum(item.rect.width if self._horizontal else item.rect.height for item in self._visible_items) + self._content_size += self._spacing * (len(self._visible_items) - 1) + self._content_size += self._pad * 2 + + self._scroll_offset = self._get_scroll(self._visible_items, self._content_size) + + self._item_pos_filter.update(self._scroll_offset) + + cur_pos = 0 + for idx, item in enumerate(self._visible_items): + spacing = self._spacing if (idx > 0) else self._pad + # Nicely lay out items horizontally/vertically + if self._horizontal: + x = self._rect.x + cur_pos + spacing + y = self._rect.y + (self._rect.height - item.rect.height) / 2 + cur_pos += item.rect.width + spacing + else: + x = self._rect.x + (self._rect.width - item.rect.width) / 2 + y = self._rect.y + cur_pos + spacing + cur_pos += item.rect.height + spacing + + # Consider scroll + if self._horizontal: + x += self._scroll_offset + else: + y += self._scroll_offset + + # Add some jello effect when scrolling + if DO_JELLO: + if self._horizontal: + cx = self._rect.x + self._rect.width / 2 + jello_offset = self._scroll_offset - np.interp(x + item.rect.width / 2, + [self._rect.x, cx, self._rect.x + self._rect.width], + [self._item_pos_filter.x, self._scroll_offset, self._item_pos_filter.x]) + x -= np.clip(jello_offset, -20, 20) + else: + cy = self._rect.y + self._rect.height / 2 + jello_offset = self._scroll_offset - np.interp(y + item.rect.height / 2, + [self._rect.y, cy, self._rect.y + self._rect.height], + [self._item_pos_filter.x, self._scroll_offset, self._item_pos_filter.x]) + y -= np.clip(jello_offset, -20, 20) + + # Animate moves if needed + x, y = self._do_move_animation(item, x, y) + + # Update item state + item.set_position(x, y) + item.set_parent_rect(self._rect) + + def _render_item(self, item: Widget): + # Skip rendering if not in viewport + if not rl.check_collision_recs(item.rect, self._rect): + return + + # Scale each element around its own origin when scrolling + scale = self._zoom_filter.x + if scale != 1.0: + rl.rl_push_matrix() + rl.rl_scalef(scale, scale, 1.0) + rl.rl_translatef((1 - scale) * (item.rect.x + item.rect.width / 2) / scale, + (1 - scale) * (item.rect.y + item.rect.height / 2) / scale, 0) + item.render() + rl.rl_pop_matrix() + else: + item.render() + + def _render(self, _): + rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y), + int(self._rect.width), int(self._rect.height)) + + for item in reversed(self._visible_items): + if item in self._move_lift: + continue + self._render_item(item) + + # Dim background if moving items, lifted items are above + self._overlay_filter.update(MOVE_OVERLAY_ALPHA if len(self._pending_move) else 0.0) + if self._overlay_filter.x > 0.01: + rl.draw_rectangle_rec(self._rect, rl.Color(0, 0, 0, int(255 * self._overlay_filter.x))) + + for item in self._move_lift: + self._render_item(item) + + rl.end_scissor_mode() + + # Draw edge shadows on top of scroller content + if self._edge_shadows: + rl.draw_rectangle_gradient_h(int(self._rect.x), int(self._rect.y), + EDGE_SHADOW_WIDTH, int(self._rect.height), + rl.Color(0, 0, 0, 204), rl.BLANK) + + right_x = int(self._rect.x + self._rect.width - EDGE_SHADOW_WIDTH) + rl.draw_rectangle_gradient_h(right_x, int(self._rect.y), + EDGE_SHADOW_WIDTH, int(self._rect.height), + rl.BLANK, rl.Color(0, 0, 0, 204)) + + # Draw scroll indicator on top of edge shadows + if self._show_scroll_indicator and len(self._visible_items) > 0: + self._scroll_indicator.update(self._scroll_offset, self._content_size, self._rect) + self._scroll_indicator.render() + + def show_event(self): + super().show_event() + for item in self._items: + item.show_event() + + if self._reset_scroll_at_show: + self.scroll_panel.set_offset(0.0) + + self._overlay_filter.x = 0.0 + self._move_animations.clear() + self._move_lift.clear() + self._pending_lift.clear() + self._pending_move.clear() + self._scrolling_to = None, False, False + self._scrolling_to_filter.x = 0.0 + + def hide_event(self): + super().hide_event() + for item in self._items: + item.hide_event() + + +class Scroller(Widget): + """Wrapper for _Scroller so that children do not need to call events or pass down enabled for nav stack.""" + def __init__(self, **kwargs): + super().__init__() + self._scroller = self._child(_Scroller([], **kwargs)) + # pass down enabled to child widget for nav stack + self._scroller.set_enabled(lambda: self.enabled) + + def _render(self, _): + self._scroller.render(self._rect) + + +class NavScroller(NavWidget, Scroller): + """Full screen Scroller that properly supports nav stack w/ animations""" + def __init__(self, **kwargs): + super().__init__(**kwargs) + # pass down enabled to child widget for nav stack + disable while swiping away NavWidget + self._scroller.set_enabled(lambda: self.enabled and not self.is_dismissing) + + def _back_enabled(self) -> bool: + # Vertical scrollers need to be at the top to swipe away to prevent erroneous swipes + # TODO: only used for offroad alerts, remove when horizontal + return self._scroller._horizontal or self._scroller.scroll_panel.get_offset() >= -20 # some tolerance + + +# TODO: only used for a few vertical scrollers, remove when horizontal +class NavRawScrollPanel(NavWidget): + # can swipe anywhere, only when at top + BACK_TOUCH_AREA_PERCENTAGE = 1.0 + + def __init__(self): + super().__init__() + self._scroll_panel = GuiScrollPanel2(horizontal=False) + self._scroll_panel.set_enabled(lambda: self.enabled and not self.is_dismissing) + + def show_event(self): + super().show_event() + self._scroll_panel.set_offset(0) + + def _back_enabled(self) -> bool: + return self._scroll_panel.get_offset() >= -20 diff --git a/system/ui/widgets/scroller_tici.py b/system/ui/widgets/scroller_tici.py new file mode 100644 index 00000000000000..a843010d56bac6 --- /dev/null +++ b/system/ui/widgets/scroller_tici.py @@ -0,0 +1,90 @@ +import pyray as rl +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.widgets import Widget + +ITEM_SPACING = 40 +LINE_COLOR = rl.GRAY +LINE_PADDING = 40 + + +class LineSeparator(Widget): + def __init__(self, height: int = 1): + super().__init__() + self._rect = rl.Rectangle(0, 0, 0, height) + + def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + + def _render(self, _): + rl.draw_line(int(self._rect.x) + LINE_PADDING, int(self._rect.y), + int(self._rect.x + self._rect.width) - LINE_PADDING, int(self._rect.y), + LINE_COLOR) + + +class Scroller(Widget): + def __init__(self, items: list[Widget], spacing: int = ITEM_SPACING, line_separator: bool = False, pad_end: bool = True): + super().__init__() + self._items: list[Widget] = [] + self._spacing = spacing + self._line_separator = LineSeparator() if line_separator else None + self._pad_end = pad_end + + self.scroll_panel = GuiScrollPanel() + + for item in items: + self.add_widget(item) + + def add_widget(self, item: Widget) -> None: + self._items.append(item) + item.set_touch_valid_callback(self.scroll_panel.is_touch_valid) + + def _render(self, _): + # TODO: don't draw items that are not in the viewport + visible_items = [item for item in self._items if item.is_visible] + + # Add line separator between items + if self._line_separator is not None: + l = len(visible_items) + for i in range(1, len(visible_items)): + visible_items.insert(l - i, self._line_separator) + + content_height = sum(item.rect.height for item in visible_items) + self._spacing * (len(visible_items)) + if not self._pad_end: + content_height -= self._spacing + scroll = self.scroll_panel.update(self._rect, rl.Rectangle(0, 0, self._rect.width, content_height)) + + rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y), + int(self._rect.width), int(self._rect.height)) + + cur_height = 0 + for idx, item in enumerate(visible_items): + if not item.is_visible: + continue + + # Nicely lay out items vertically + x = self._rect.x + y = self._rect.y + cur_height + self._spacing * (idx != 0) + cur_height += item.rect.height + self._spacing * (idx != 0) + + # Consider scroll + y += scroll + + # Update item state + item.set_position(x, y) + item.set_parent_rect(self._rect) + item.render() + + rl.end_scissor_mode() + + def show_event(self): + super().show_event() + # Reset to top + self.scroll_panel.set_offset(0) + for item in self._items: + item.show_event() + + def hide_event(self): + super().hide_event() + for item in self._items: + item.hide_event() diff --git a/system/ui/widgets/slider.py b/system/ui/widgets/slider.py new file mode 100644 index 00000000000000..bf965954f2e77d --- /dev/null +++ b/system/ui/widgets/slider.py @@ -0,0 +1,204 @@ +import abc +from collections.abc import Callable + +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.common.filter_simple import FirstOrderFilter, BounceFilter + + +class SliderBase(Widget, abc.ABC): + HORIZONTAL_PADDING = 8 + CONFIRM_DELAY = 0.2 + PRESSED_SCALE = 1.07 + + _bg_txt: rl.Texture + _circle_bg_txt: rl.Texture + _circle_bg_pressed_txt: rl.Texture + _circle_arrow_txt: rl.Texture + + def __init__(self, title: str, confirm_callback: Callable | None = None, shimmer_offset: float = 0.0): + super().__init__() + self._confirm_callback = confirm_callback + self._shimmer_offset = shimmer_offset + + self._load_assets() + + self._drag_threshold = -self._rect.width // 2 + + # State + self._opacity_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._confirmed_time = 0.0 + self._confirm_callback_called = False # we keep dialog open by default, only call once + self._start_x_circle = 0.0 + self._scroll_x_circle = 0.0 + self._scroll_x_circle_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + self._circle_scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._circle_press_time: float | None = None + + self._is_dragging_circle = False + + self._label = self._child(UnifiedLabel(title, font_size=36, font_weight=FontWeight.SEMI_BOLD, text_color=rl.WHITE, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, line_height=0.9, shimmer=True)) + + @abc.abstractmethod + def _load_assets(self): + ... + + @property + def confirmed(self) -> bool: + return self._confirmed_time > 0.0 + + def show_event(self): + super().show_event() + self.reset() + + def reset(self): + # reset all slider state + self._is_dragging_circle = False + self._circle_press_time = None + self._confirmed_time = 0.0 + self._confirm_callback_called = False + self._label.reset_shimmer(self._shimmer_offset) + + def set_opacity(self, opacity: float, smooth: bool = False): + if smooth: + self._opacity_filter.update(opacity) + else: + self._opacity_filter.x = opacity + + @property + def slider_percentage(self): + activated_pos = -self._bg_txt.width + self._circle_bg_txt.width + return min(max(-self._scroll_x_circle_filter.x / abs(activated_pos), 0.0), 1.0) + + def _on_confirm(self): + if self._confirm_callback: + self._confirm_callback() + + def _handle_mouse_event(self, mouse_event): + super()._handle_mouse_event(mouse_event) + + if mouse_event.left_pressed: + # touch rect goes to the padding + circle_button_rect = rl.Rectangle( + self._rect.x + (self._rect.width - self._circle_bg_txt.width) + self._scroll_x_circle_filter.x - self.HORIZONTAL_PADDING * 2, + self._rect.y, + self._circle_bg_txt.width + self.HORIZONTAL_PADDING * 2, + self._rect.height, + ) + if rl.check_collision_point_rec(mouse_event.pos, circle_button_rect): + self._start_x_circle = mouse_event.pos.x + self._is_dragging_circle = True + self._circle_press_time = rl.get_time() + + elif mouse_event.left_released: + # swiped to left + if self._scroll_x_circle_filter.x < self._drag_threshold: + self._confirmed_time = rl.get_time() + + self._is_dragging_circle = False + + if self._is_dragging_circle: + self._scroll_x_circle = mouse_event.pos.x - self._start_x_circle + + def _update_state(self): + super()._update_state() + # TODO: this math can probably be cleaned up to remove duplicate stuff + activated_pos = int(-self._bg_txt.width + self._circle_bg_txt.width) + self._scroll_x_circle = max(min(self._scroll_x_circle, 0), activated_pos) + + if self.confirmed: + # swiped left to confirm + self._scroll_x_circle_filter.update(activated_pos) + + # activate once animation completes, small threshold for small floats + if self._scroll_x_circle_filter.x < (activated_pos + 1): + if not self._confirm_callback_called and (rl.get_time() - self._confirmed_time) >= self.CONFIRM_DELAY: + self._confirm_callback_called = True + self._on_confirm() + + elif not self._is_dragging_circle: + # reset back to right + self._scroll_x_circle_filter.update(0) + else: + # not activated yet, keep movement 1:1 + self._scroll_x_circle_filter.x = self._scroll_x_circle + + def _render(self, _): + white = rl.Color(255, 255, 255, int(255 * self._opacity_filter.x)) + + bg_txt_x = self._rect.x + (self._rect.width - self._bg_txt.width) / 2 + bg_txt_y = self._rect.y + (self._rect.height - self._bg_txt.height) / 2 + rl.draw_texture_ex(self._bg_txt, rl.Vector2(bg_txt_x, bg_txt_y), 0.0, 1.0, white) + + btn_x = bg_txt_x + self._bg_txt.width - self._circle_bg_txt.width + self._scroll_x_circle_filter.x + btn_y = self._rect.y + (self._rect.height - self._circle_bg_txt.height) / 2 + + label_alpha = int(255 * (1.0 - self.slider_percentage) * self._opacity_filter.x) + if label_alpha > 0: + self._label.set_text_color(rl.Color(255, 255, 255, label_alpha)) + label_rect = rl.Rectangle( + self._rect.x + 20, + self._rect.y, + self._rect.width - self._circle_bg_txt.width - 20 * 2.5, + self._rect.height, + ) + self._label.render(label_rect) + + # circle and arrow with grow animation + circle_pressed = self._is_dragging_circle or self.confirmed or (self._circle_press_time is not None and rl.get_time() - self._circle_press_time < 0.075) + circle_bg_txt = self._circle_bg_pressed_txt if circle_pressed else self._circle_bg_txt + scale = self._circle_scale_filter.update(self.PRESSED_SCALE if circle_pressed else 1.0) + scaled_btn_x = btn_x + (self._circle_bg_txt.width * (1 - scale)) / 2 + scaled_btn_y = btn_y + (self._circle_bg_txt.height * (1 - scale)) / 2 + rl.draw_texture_ex(circle_bg_txt, rl.Vector2(scaled_btn_x, scaled_btn_y), 0.0, scale, white) + + arrow_x = btn_x + (self._circle_bg_txt.width - self._circle_arrow_txt.width) / 2 + arrow_y = scaled_btn_y + (self._circle_bg_txt.height - self._circle_arrow_txt.height) / 2 + rl.draw_texture_ex(self._circle_arrow_txt, rl.Vector2(arrow_x, arrow_y), 0.0, 1.0, white) + + +class LargerSlider(SliderBase): + def __init__(self, title: str, confirm_callback: Callable | None = None, green: bool = True, shimmer_offset: float = 0.0): + self._green = green + super().__init__(title, confirm_callback=confirm_callback, shimmer_offset=shimmer_offset) + + def _load_assets(self): + self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 115)) + + self._bg_txt = gui_app.texture("icons_mici/setup/small_slider/slider_bg_larger.png", 520, 115) + circle_fn = "slider_green_rounded_rectangle" if self._green else "slider_black_rounded_rectangle" + self._circle_bg_txt = gui_app.texture(f"icons_mici/setup/small_slider/{circle_fn}.png", 180, 115) + self._circle_bg_pressed_txt = gui_app.texture(f"icons_mici/setup/small_slider/{circle_fn}_pressed.png", 180, 115) + self._circle_arrow_txt = gui_app.texture("icons_mici/setup/small_slider/slider_arrow.png", 64, 55) + + +class BigSlider(SliderBase): + def __init__(self, title: str, icon: rl.Texture, confirm_callback: Callable | None = None): + self._icon = icon + super().__init__(title, confirm_callback=confirm_callback) + self._label.set_font_size(48) + self._label.set_font_weight(FontWeight.DISPLAY) + self._label.set_line_height(0.875) + + def _load_assets(self): + self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 180)) + + self._bg_txt = gui_app.texture("icons_mici/buttons/slider_bg.png", 520, 180) + self._circle_bg_txt = gui_app.texture("icons_mici/buttons/button_circle.png", 180, 180) + self._circle_bg_pressed_txt = gui_app.texture("icons_mici/buttons/button_circle_pressed.png", 180, 180) + self._circle_arrow_txt = self._icon + + +class RedBigSlider(BigSlider): + def _load_assets(self): + self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 180)) + + self._bg_txt = gui_app.texture("icons_mici/buttons/slider_bg.png", 520, 180) + self._circle_bg_txt = gui_app.texture("icons_mici/buttons/button_circle_red.png", 180, 180) + self._circle_bg_pressed_txt = gui_app.texture("icons_mici/buttons/button_circle_red_pressed.png", 180, 180) + self._circle_arrow_txt = self._icon diff --git a/system/ui/widgets/toggle.py b/system/ui/widgets/toggle.py new file mode 100644 index 00000000000000..0fbf3c844a10b9 --- /dev/null +++ b/system/ui/widgets/toggle.py @@ -0,0 +1,81 @@ +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.lib.application import MousePos +from openpilot.system.ui.widgets import Widget + +ON_COLOR = rl.Color(51, 171, 76, 255) +OFF_COLOR = rl.Color(0x39, 0x39, 0x39, 255) +KNOB_COLOR = rl.WHITE +DISABLED_ON_COLOR = rl.Color(0x22, 0x77, 0x22, 255) # Dark green when disabled + on +DISABLED_OFF_COLOR = rl.Color(0x39, 0x39, 0x39, 255) +DISABLED_KNOB_COLOR = rl.Color(0x88, 0x88, 0x88, 255) +WIDTH, HEIGHT = 160, 80 +BG_HEIGHT = 60 +ANIMATION_SPEED = 8.0 + + +class Toggle(Widget): + def __init__(self, initial_state: bool = False, callback: Callable[[bool], None] | None = None): + super().__init__() + self._state = initial_state + self._callback = callback + self._enabled = True + self._progress = 1.0 if initial_state else 0.0 + self._target = self._progress + self._clicked = False + + def set_rect(self, rect: rl.Rectangle): + self._rect = rl.Rectangle(rect.x, rect.y, WIDTH, HEIGHT) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if not self._enabled: + return + + self._clicked = True + self._state = not self._state + self._target = 1.0 if self._state else 0.0 + if self._callback: + self._callback(self._state) + + def get_state(self) -> bool: + return self._state + + def set_state(self, state: bool): + self._state = state + self._target = 1.0 if state else 0.0 + + def is_enabled(self): + return self._enabled + + def update(self): + if abs(self._progress - self._target) > 0.01: + delta = rl.get_frame_time() * ANIMATION_SPEED + self._progress += delta if self._progress < self._target else -delta + self._progress = max(0.0, min(1.0, self._progress)) + + def _render(self, rect: rl.Rectangle): + self.update() + + if self._enabled: + bg_color = self._blend_color(OFF_COLOR, ON_COLOR, self._progress) + knob_color = KNOB_COLOR + else: + bg_color = self._blend_color(DISABLED_OFF_COLOR, DISABLED_ON_COLOR, self._progress) + knob_color = DISABLED_KNOB_COLOR + + # Draw background + bg_rect = rl.Rectangle(self._rect.x + 5, self._rect.y + 10, WIDTH - 10, BG_HEIGHT) + rl.draw_rectangle_rounded(bg_rect, 1.0, 10, bg_color) + + # Draw knob + knob_x = self._rect.x + HEIGHT / 2 + (WIDTH - HEIGHT) * self._progress + knob_y = self._rect.y + HEIGHT / 2 + rl.draw_circle(int(knob_x), int(knob_y), HEIGHT / 2, knob_color) + + # TODO: use click callback + clicked = self._clicked + self._clicked = False + return clicked + + def _blend_color(self, c1, c2, t): + return rl.Color(int(c1.r + (c2.r - c1.r) * t), int(c1.g + (c2.g - c1.g) * t), int(c1.b + (c2.b - c1.b) * t), 255) diff --git a/system/updated/casync/casync.py b/system/updated/casync/casync.py index 7a3303a9e94e19..2bd46a1ffba45c 100755 --- a/system/updated/casync/casync.py +++ b/system/updated/casync/casync.py @@ -99,7 +99,7 @@ def __init__(self, path: str, cache_file: str) -> None: create_casync_tar_package(pathlib.Path(path), pathlib.Path(cache_file)) self.f = open(cache_file, "rb") - return super().__init__(self.f) + super().__init__(self.f) def __del__(self): self.f.close() @@ -168,7 +168,7 @@ def build_chunk_dict(chunks: list[Chunk]) -> ChunkDict: def extract(target: list[Chunk], sources: list[tuple[str, ChunkReader, ChunkDict]], out_path: str, - progress: Callable[[int], None] = None): + progress: Callable[[int], None] | None = None): stats: dict[str, int] = defaultdict(int) mode = 'rb+' if os.path.exists(out_path) else 'wb' @@ -208,7 +208,7 @@ def extract_directory(target: list[Chunk], sources: list[tuple[str, ChunkReader, ChunkDict]], out_path: str, tmp_file: str, - progress: Callable[[int], None] = None): + progress: Callable[[int], None] | None = None): """extract a directory stored as a casync tar archive""" stats = extract(target, sources, tmp_file, progress) diff --git a/system/updated/tests/test_base.py b/system/updated/tests/test_base.py index 52287c58f9b744..db38bfa840aef4 100644 --- a/system/updated/tests/test_base.py +++ b/system/updated/tests/test_base.py @@ -86,7 +86,7 @@ def mock_basedir(self, mocker): mocker.patch("openpilot.common.basedir.BASEDIR", self.basedir) def set_target_branch(self, branch): - self.params.put("UpdaterTargetBranch", branch) + self.params.put("UpdaterTargetBranch", branch, block=True) def setup_basedir_release(self, release): self.params = Params() @@ -132,8 +132,8 @@ def _test_finalized_update(self, branch, version, agnos_version, release_notes): class ParamsBaseUpdateTest(TestBaseUpdate): def _test_finalized_update(self, branch, version, agnos_version, release_notes): - assert self.params.get("UpdaterNewDescription", encoding="utf-8").startswith(f"{version} / {branch}") - assert self.params.get("UpdaterNewReleaseNotes", encoding="utf-8") == f"{release_notes}\n" + assert self.params.get("UpdaterNewDescription").startswith(f"{version} / {branch}") + assert self.params.get("UpdaterNewReleaseNotes") == f"{release_notes}\n".encode() super()._test_finalized_update(branch, version, agnos_version, release_notes) def send_check_for_updates_signal(self, updated: ManagerProcess): @@ -143,16 +143,16 @@ def send_download_signal(self, updated: ManagerProcess): updated.signal(signal.SIGHUP.value) def _test_params(self, branch, fetch_available, update_available): - assert self.params.get("UpdaterTargetBranch", encoding="utf-8") == branch + assert self.params.get("UpdaterTargetBranch") == branch assert self.params.get_bool("UpdaterFetchAvailable") == fetch_available assert self.params.get_bool("UpdateAvailable") == update_available def wait_for_idle(self): - self.wait_for_condition(lambda: self.params.get("UpdaterState", encoding="utf-8") == "idle") + self.wait_for_condition(lambda: self.params.get("UpdaterState") == "idle") def wait_for_failed(self): - self.wait_for_condition(lambda: self.params.get("UpdateFailedCount", encoding="utf-8") is not None and \ - int(self.params.get("UpdateFailedCount", encoding="utf-8")) > 0) + self.wait_for_condition(lambda: self.params.get("UpdateFailedCount") is not None and \ + self.params.get("UpdateFailedCount") > 0) def wait_for_fetch_available(self): self.wait_for_condition(lambda: self.params.get_bool("UpdaterFetchAvailable")) diff --git a/system/updated/tests/test_updated.py b/system/updated/tests/test_updated.py new file mode 100644 index 00000000000000..18ee0e706a4506 --- /dev/null +++ b/system/updated/tests/test_updated.py @@ -0,0 +1,38 @@ +import pytest + +from openpilot.common.params import Params +from openpilot.system.updated.updated import Updater + + +@pytest.mark.parametrize(("device_type", "branch", "expected"), [ + ("tizi", "release3", "release-tizi"), + ("tizi", "release3-staging", "release-tizi-staging"), + ("mici", "release3", "release-mici"), + ("mici", "release3-staging", "release-mici-staging"), +]) +def test_target_branch_migration_from_current_branch(mocker, device_type, branch, expected): + params = Params() + params.remove("UpdaterTargetBranch") + + mocker.patch("openpilot.system.updated.updated.HARDWARE.get_device_type", return_value=device_type) + mocker.patch.object(Updater, "get_branch", return_value=branch) + + assert Updater().target_branch == expected + + +@pytest.mark.parametrize(("device_type", "branch", "expected"), [ + ("tizi", "release3", "release-tizi"), + ("tizi", "release3-staging", "release-tizi-staging"), + ("mici", "release3", "release-mici"), + ("mici", "release3-staging", "release-mici-staging"), +]) +def test_target_branch_migration_from_param(mocker, device_type, branch, expected): + params = Params() + params.put("UpdaterTargetBranch", branch, block=True) + + mocker.patch("openpilot.system.updated.updated.HARDWARE.get_device_type", return_value=device_type) + + try: + assert Updater().target_branch == expected + finally: + params.remove("UpdaterTargetBranch") diff --git a/system/updated/updated.py b/system/updated/updated.py index 005c52bc8bb160..25821e3732e077 100755 --- a/system/updated/updated.py +++ b/system/updated/updated.py @@ -14,10 +14,10 @@ from openpilot.common.basedir import BASEDIR from openpilot.common.params import Params -from openpilot.common.time import system_time_valid +from openpilot.common.time_helpers import system_time_valid from openpilot.common.markdown import parse_markdown from openpilot.common.swaglog import cloudlog -from openpilot.selfdrive.controls.lib.alertmanager import set_offroad_alert +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert from openpilot.system.hardware import AGNOS, HARDWARE from openpilot.system.version import get_build_metadata @@ -31,8 +31,13 @@ OVERLAY_INIT = Path(os.path.join(BASEDIR, ".overlay_init")) -DAYS_NO_CONNECTIVITY_MAX = 14 # do not allow to engage after this many days -DAYS_NO_CONNECTIVITY_PROMPT = 10 # send an offroad prompt after this many days +# do not allow to engage after this many hours onroad and this many routes +HOURS_NO_CONNECTIVITY_MAX = 27 +ROUTES_NO_CONNECTIVITY_MAX = 84 +# send an offroad prompt after this many hours onroad and this many routes +HOURS_NO_CONNECTIVITY_PROMPT = 23 +ROUTES_NO_CONNECTIVITY_PROMPT = 80 + class UserRequest: NONE = 0 @@ -61,17 +66,9 @@ def sleep(self, t: float) -> None: def write_time_to_param(params, param) -> None: t = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - params.put(param, t.isoformat().encode('utf8')) + params.put(param, t, block=True) -def read_time_from_param(params, param) -> datetime.datetime | None: - t = params.get(param, encoding='utf8') - try: - return datetime.datetime.fromisoformat(t) - except (TypeError, ValueError): - pass - return None - -def run(cmd: list[str], cwd: str = None) -> str: +def run(cmd: list[str], cwd: str | None = None) -> str: return subprocess.check_output(cmd, cwd=cwd, stderr=subprocess.STDOUT, encoding='utf8') @@ -142,7 +139,7 @@ def init_overlay() -> None: cloudlog.info("preparing new safe staging area") params = Params() - params.put_bool("UpdateAvailable", False) + params.put_bool("UpdateAvailable", False, block=True) set_consistent_flag(False) dismount_overlay() run(["sudo", "rm", "-rf", STAGING_ROOT]) @@ -172,8 +169,8 @@ def init_overlay() -> None: run(["sudo"] + mount_cmd) run(["sudo", "chmod", "755", os.path.join(OVERLAY_METADATA, "work")]) - git_diff = run(["git", "diff"], OVERLAY_MERGED) - params.put("GitDiff", git_diff) + git_diff = run(["git", "diff", "--submodule=diff"], OVERLAY_MERGED) + params.put("GitDiff", git_diff, block=True) cloudlog.info(f"git diff output:\n{git_diff}") @@ -242,9 +239,15 @@ def has_internet(self) -> bool: @property def target_branch(self) -> str: - b: str | None = self.params.get("UpdaterTargetBranch", encoding='utf-8') + b: str | None = self.params.get("UpdaterTargetBranch") if b is None: b = self.get_branch(BASEDIR) + b = { + ("tizi", "release3"): "release-tizi", + ("tizi", "release3-staging"): "release-tizi-staging", + ("mici", "release3"): "release-mici", + ("mici", "release3-staging"): "release-mici-staging", + }.get((HARDWARE.get_device_type(), b), b) return b @property @@ -272,25 +275,27 @@ def get_commit_hash(self, path: str = OVERLAY_MERGED) -> str: return run(["git", "rev-parse", "HEAD"], path).rstrip() def set_params(self, update_success: bool, failed_count: int, exception: str | None) -> None: - self.params.put("UpdateFailedCount", str(failed_count)) - self.params.put("UpdaterTargetBranch", self.target_branch) + self.params.put("UpdateFailedCount", failed_count, block=True) + self.params.put("UpdaterTargetBranch", self.target_branch, block=True) - self.params.put_bool("UpdaterFetchAvailable", self.update_available) + self.params.put_bool("UpdaterFetchAvailable", self.update_available, block=True) if len(self.branches): - self.params.put("UpdaterAvailableBranches", ','.join(self.branches.keys())) + self.params.put("UpdaterAvailableBranches", ','.join(self.branches.keys()), block=True) - last_update = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) + last_uptime_onroad = self.params.get("UptimeOnroad", return_default=True) + last_route_count = self.params.get("RouteCount", return_default=True) if update_success: - write_time_to_param(self.params, "LastUpdateTime") + self.params.put("LastUpdateTime", datetime.datetime.now(datetime.UTC).replace(tzinfo=None), block=True) + self.params.put("LastUpdateUptimeOnroad", last_uptime_onroad, block=True) + self.params.put("LastUpdateRouteCount", last_route_count, block=True) else: - t = read_time_from_param(self.params, "LastUpdateTime") - if t is not None: - last_update = t + last_uptime_onroad = self.params.get("LastUpdateUptimeOnroad", return_default=True) + last_route_count = self.params.get("LastUpdateRouteCount", return_default=True) if exception is None: self.params.remove("LastUpdateException") else: - self.params.put("LastUpdateException", exception) + self.params.put("LastUpdateException", exception, block=True) # Write out current and new version info def get_description(basedir: str) -> str: @@ -313,18 +318,18 @@ def get_description(basedir: str) -> str: except Exception: cloudlog.exception("updater.get_description") return f"{version} / {branch} / {commit} / {commit_date}" - self.params.put("UpdaterCurrentDescription", get_description(BASEDIR)) - self.params.put("UpdaterCurrentReleaseNotes", parse_release_notes(BASEDIR)) - self.params.put("UpdaterNewDescription", get_description(FINALIZED)) - self.params.put("UpdaterNewReleaseNotes", parse_release_notes(FINALIZED)) - self.params.put_bool("UpdateAvailable", self.update_ready) + self.params.put("UpdaterCurrentDescription", get_description(BASEDIR), block=True) + self.params.put("UpdaterCurrentReleaseNotes", parse_release_notes(BASEDIR), block=True) + self.params.put("UpdaterNewDescription", get_description(FINALIZED), block=True) + self.params.put("UpdaterNewReleaseNotes", parse_release_notes(FINALIZED), block=True) + self.params.put_bool("UpdateAvailable", self.update_ready, block=True) # Handle user prompt for alert in ("Offroad_UpdateFailed", "Offroad_ConnectivityNeeded", "Offroad_ConnectivityNeededPrompt"): set_offroad_alert(alert, False) - now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - dt = now - last_update + dt_uptime_onroad = (self.params.get("UptimeOnroad", return_default=True) - last_uptime_onroad) / (60*60) + dt_route_count = self.params.get("RouteCount", return_default=True) - last_route_count build_metadata = get_build_metadata() if failed_count > 15 and exception is not None and self.has_internet: if build_metadata.tested_channel: @@ -333,11 +338,11 @@ def get_description(basedir: str) -> str: extra_text = exception set_offroad_alert("Offroad_UpdateFailed", True, extra_text=extra_text) elif failed_count > 0: - if dt.days > DAYS_NO_CONNECTIVITY_MAX: + if dt_uptime_onroad > HOURS_NO_CONNECTIVITY_MAX and dt_route_count > ROUTES_NO_CONNECTIVITY_MAX: set_offroad_alert("Offroad_ConnectivityNeeded", True) - elif dt.days > DAYS_NO_CONNECTIVITY_PROMPT: - remaining = max(DAYS_NO_CONNECTIVITY_MAX - dt.days, 1) - set_offroad_alert("Offroad_ConnectivityNeededPrompt", True, extra_text=f"{remaining} day{'' if remaining == 1 else 's'}.") + elif dt_uptime_onroad > HOURS_NO_CONNECTIVITY_PROMPT and dt_route_count > ROUTES_NO_CONNECTIVITY_PROMPT: + remaining = max(HOURS_NO_CONNECTIVITY_MAX - dt_uptime_onroad, 1) + set_offroad_alert("Offroad_ConnectivityNeededPrompt", True, extra_text=f"{remaining} hour{'' if remaining == 1 else 's'}.") def check_for_update(self) -> None: cloudlog.info("checking for updates") @@ -372,14 +377,16 @@ def check_for_update(self) -> None: def fetch_update(self) -> None: cloudlog.info("attempting git fetch inside staging overlay") - self.params.put("UpdaterState", "downloading...") + self.params.put("UpdaterState", "downloading...", block=True) # TODO: cleanly interrupt this and invalidate old update set_consistent_flag(False) - self.params.put_bool("UpdateAvailable", False) + self.params.put_bool("UpdateAvailable", False, block=True) setup_git_options(OVERLAY_MERGED) + run(["git", "config", "--replace-all", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"], OVERLAY_MERGED) + branch = self.target_branch git_fetch_output = run(["git", "fetch", "origin", branch], OVERLAY_MERGED) cloudlog.info("git fetch success: %s", git_fetch_output) @@ -387,6 +394,7 @@ def fetch_update(self) -> None: cloudlog.info("git reset in progress") cmds = [ ["git", "checkout", "--force", "--no-recurse-submodules", "-B", branch, "FETCH_HEAD"], + ["git", "branch", "--set-upstream-to", f"origin/{branch}"], ["git", "reset", "--hard"], ["git", "clean", "-xdff"], ["git", "submodule", "sync"], @@ -401,7 +409,7 @@ def fetch_update(self) -> None: handle_agnos_update() # Create the finalized, ready-to-swap update - self.params.put("UpdaterState", "finalizing update...") + self.params.put("UpdaterState", "finalizing update...", block=True) finalize_update() cloudlog.info("finalize success!") @@ -429,8 +437,8 @@ def main() -> None: cloudlog.event("update installed") if not params.get("InstallDate"): - t = datetime.datetime.now(datetime.UTC).replace(tzinfo=None).isoformat() - params.put("InstallDate", t.encode('utf8')) + t = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) + params.put("InstallDate", t, block=True) updater = Updater() update_failed_count = 0 # TODO: Load from param? @@ -440,7 +448,7 @@ def main() -> None: set_consistent_flag(False) # set initial state - params.put("UpdaterState", "idle") + params.put("UpdaterState", "idle", block=True) # Run the update loop first_run = True @@ -464,11 +472,11 @@ def main() -> None: update_failed_count += 1 # check for update - params.put("UpdaterState", "checking...") + params.put("UpdaterState", "checking...", block=True) updater.check_for_update() # download update - last_fetch = read_time_from_param(params, "UpdaterLastFetchTime") + last_fetch = params.get("UpdaterLastFetchTime") timed_out = last_fetch is None or (datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - last_fetch > datetime.timedelta(days=3)) user_requested_fetch = wait_helper.user_request == UserRequest.FETCH if params.get_bool("NetworkMetered") and not timed_out and not user_requested_fetch: @@ -494,7 +502,7 @@ def main() -> None: OVERLAY_INIT.unlink(missing_ok=True) try: - params.put("UpdaterState", "idle") + params.put("UpdaterState", "idle", block=True) update_successful = (update_failed_count == 0) updater.set_params(update_successful, update_failed_count, exception) except Exception: diff --git a/system/version.py b/system/version.py index 94964526b3f7a3..0cea616d236f7f 100755 --- a/system/version.py +++ b/system/version.py @@ -10,13 +10,13 @@ from openpilot.common.swaglog import cloudlog from openpilot.common.git import get_commit, get_origin, get_branch, get_short_branch, get_commit_date -RELEASE_BRANCHES = ['release3-staging', 'release3', 'nightly'] -TESTED_BRANCHES = RELEASE_BRANCHES + ['devel', 'devel-staging'] +RELEASE_BRANCHES = ['release-tizi-staging', 'release-mici-staging', 'release-tizi', 'release-mici', 'nightly'] +TESTED_BRANCHES = RELEASE_BRANCHES + ['devel-staging', 'nightly-dev'] BUILD_METADATA_FILENAME = "build.json" -training_version: bytes = b"0.2.0" -terms_version: bytes = b"2" +training_version: str = "0.2.0" +terms_version: str = "2" def get_version(path: str = BASEDIR) -> str: @@ -37,9 +37,7 @@ def is_prebuilt(path: str = BASEDIR) -> bool: @cache def is_dirty(cwd: str = BASEDIR) -> bool: - origin = get_origin() - branch = get_branch() - if not origin or not branch: + if not get_origin() or not get_short_branch(): return True dirty = False @@ -52,6 +50,9 @@ def is_dirty(cwd: str = BASEDIR) -> bool: except subprocess.CalledProcessError: pass + branch = get_branch() + if not branch: + return True dirty = (subprocess.call(["git", "diff-index", "--quiet", branch, "--"], cwd=cwd)) != 0 except subprocess.CalledProcessError: cloudlog.exception("git subprocess failed while checking dirty") @@ -156,10 +157,4 @@ def get_build_metadata(path: str = BASEDIR) -> BuildMetadata: if __name__ == "__main__": - from openpilot.common.params import Params - - params = Params() - params.put("TermsVersion", terms_version) - params.put("TrainingVersion", training_version) - print(get_build_metadata()) diff --git a/system/webrtc/device/audio.py b/system/webrtc/device/audio.py deleted file mode 100644 index 4b22033e03e639..00000000000000 --- a/system/webrtc/device/audio.py +++ /dev/null @@ -1,109 +0,0 @@ -import asyncio -import io - -import aiortc -import av -import numpy as np -import pyaudio - - -class AudioInputStreamTrack(aiortc.mediastreams.AudioStreamTrack): - PYAUDIO_TO_AV_FORMAT_MAP = { - pyaudio.paUInt8: 'u8', - pyaudio.paInt16: 's16', - pyaudio.paInt24: 's24', - pyaudio.paInt32: 's32', - pyaudio.paFloat32: 'flt', - } - - def __init__(self, audio_format: int = pyaudio.paInt16, rate: int = 16000, channels: int = 1, packet_time: float = 0.020, device_index: int = None): - super().__init__() - - self.p = pyaudio.PyAudio() - chunk_size = int(packet_time * rate) - self.stream = self.p.open(format=audio_format, - channels=channels, - rate=rate, - frames_per_buffer=chunk_size, - input=True, - input_device_index=device_index) - self.format = audio_format - self.rate = rate - self.channels = channels - self.packet_time = packet_time - self.chunk_size = chunk_size - self.pts = 0 - - async def recv(self): - mic_data = self.stream.read(self.chunk_size) - mic_array = np.frombuffer(mic_data, dtype=np.int16) - mic_array = np.expand_dims(mic_array, axis=0) - layout = 'stereo' if self.channels > 1 else 'mono' - frame = av.AudioFrame.from_ndarray(mic_array, format=self.PYAUDIO_TO_AV_FORMAT_MAP[self.format], layout=layout) - frame.rate = self.rate - frame.pts = self.pts - self.pts += frame.samples - - return frame - - -class AudioOutputSpeaker: - def __init__(self, audio_format: int = pyaudio.paInt16, rate: int = 48000, channels: int = 2, packet_time: float = 0.2, device_index: int = None): - - chunk_size = int(packet_time * rate) - self.p = pyaudio.PyAudio() - self.buffer = io.BytesIO() - self.channels = channels - self.stream = self.p.open(format=audio_format, - channels=channels, - rate=rate, - frames_per_buffer=chunk_size, - output=True, - output_device_index=device_index, - stream_callback=self.__pyaudio_callback) - self.tracks_and_tasks: list[tuple[aiortc.MediaStreamTrack, asyncio.Task | None]] = [] - - def __pyaudio_callback(self, in_data, frame_count, time_info, status): - if self.buffer.getbuffer().nbytes < frame_count * self.channels * 2: - buff = b'\x00\x00' * frame_count * self.channels - elif self.buffer.getbuffer().nbytes > 115200: # 3x the usual read size - self.buffer.seek(0) - buff = self.buffer.read(frame_count * self.channels * 4) - buff = buff[:frame_count * self.channels * 2] - self.buffer.seek(2) - else: - self.buffer.seek(0) - buff = self.buffer.read(frame_count * self.channels * 2) - self.buffer.seek(2) - return (buff, pyaudio.paContinue) - - async def __consume(self, track): - while True: - try: - frame = await track.recv() - except aiortc.MediaStreamError: - return - - self.buffer.write(bytes(frame.planes[0])) - - def hasTrack(self, track: aiortc.MediaStreamTrack) -> bool: - return any(t == track for t, _ in self.tracks_and_tasks) - - def addTrack(self, track: aiortc.MediaStreamTrack): - if not self.hasTrack(track): - self.tracks_and_tasks.append((track, None)) - - def start(self): - for index, (track, task) in enumerate(self.tracks_and_tasks): - if task is None: - self.tracks_and_tasks[index] = (track, asyncio.create_task(self.__consume(track))) - - def stop(self): - for _, task in self.tracks_and_tasks: - if task is not None: - task.cancel() - - self.tracks_and_tasks = [] - self.stream.stop_stream() - self.stream.close() - self.p.terminate() diff --git a/system/webrtc/device/video.py b/system/webrtc/device/video.py index 1bca909294504a..8a07c5b9be9c92 100644 --- a/system/webrtc/device/video.py +++ b/system/webrtc/device/video.py @@ -1,4 +1,6 @@ import asyncio +import struct +import time import av from teleoprtc.tracks import TiciVideoStreamTrack @@ -6,6 +8,13 @@ from cereal import messaging from openpilot.common.realtime import DT_MDL, DT_DMON +# arbitrary 16-byte UUID identifying openpilot frame-timing SEI messages +TIMING_SEI_UUID = bytes([ + 0xa5, 0xe0, 0xc4, 0xa4, 0x5b, 0x6e, 0x4e, 0x1e, + 0x9c, 0x7e, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, +]) +_SEI_PREFIX = b'\x00\x00\x00\x01\x06\x05\x30' + TIMING_SEI_UUID + class LiveStreamVideoStreamTrack(TiciVideoStreamTrack): camera_to_sock_mapping = { @@ -18,8 +27,30 @@ def __init__(self, camera_type: str): dt = DT_DMON if camera_type == "driver" else DT_MDL super().__init__(camera_type, dt) - self._sock = messaging.sub_sock(self.camera_to_sock_mapping[camera_type], conflate=True) + self._sock = self._make_sock(camera_type) self._pts = 0 + self._t0_ns = time.monotonic_ns() + self.timing_sei_enabled = False + + def _make_sock(self, camera_type: str) -> messaging.SubSocket: + return messaging.sub_sock(self.camera_to_sock_mapping[camera_type], conflate=True) + + def switch_camera(self, camera_type: str) -> None: + self._sock = self._make_sock(camera_type) + + def _build_frame_data(self, msg) -> bytes: + encode_data = getattr(msg, msg.which()) + if not self.timing_sei_enabled: + return encode_data.header + encode_data.data + + idx = encode_data.idx + sei_nal = _SEI_PREFIX + struct.pack('>4d', + (idx.timestampEof - idx.timestampSof) / 1e6, + (msg.logMonoTime - idx.timestampEof) / 1e6, + (time.monotonic_ns() - msg.logMonoTime) / 1e6, + time.time() * 1000, # noqa: TID251 + ) + b'\x80' + return encode_data.header + sei_nal + encode_data.data async def recv(self): while True: @@ -28,14 +59,12 @@ async def recv(self): break await asyncio.sleep(0.005) - evta = getattr(msg, msg.which()) - - packet = av.Packet(evta.header + evta.data) + packet = av.Packet(self._build_frame_data(msg)) packet.time_base = self._time_base - packet.pts = self._pts - self.log_debug("track sending frame %s", self._pts) - self._pts += self._dt * self._clock_rate + self._pts = ((time.monotonic_ns() - self._t0_ns) * self._clock_rate) // 1_000_000_000 + packet.pts = self._pts + self.log_debug("track sending frame %d", self._pts) return packet diff --git a/system/webrtc/schema.py b/system/webrtc/schema.py index d80986ebf2599e..4876198eb065ae 100644 --- a/system/webrtc/schema.py +++ b/system/webrtc/schema.py @@ -16,7 +16,7 @@ def generate_type(type_walker, schema_walker) -> str | list[Any] | dict[str, Any def generate_struct(schema: capnp.lib.capnp._StructSchema) -> dict[str, Any]: - return {field: generate_field(schema.fields[field]) for field in schema.fields if not field.endswith("DEPRECATED")} + return {field: generate_field(schema.fields[field]) for field in schema.fields if not field.endswith("DEPRECATED") and field != "deprecated"} def generate_field(field: capnp.lib.capnp._StructSchemaField) -> str | list[Any] | dict[str, Any]: diff --git a/system/webrtc/tests/test_stream_session.py b/system/webrtc/tests/test_stream_session.py index 113fa5e7e648ff..f44d217d58ced6 100644 --- a/system/webrtc/tests/test_stream_session.py +++ b/system/webrtc/tests/test_stream_session.py @@ -1,5 +1,6 @@ import asyncio import json +import time # for aiortc and its dependencies import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) @@ -8,13 +9,10 @@ from aiortc import RTCDataChannel from aiortc.mediastreams import VIDEO_CLOCK_RATE, VIDEO_TIME_BASE import capnp -import pyaudio from cereal import messaging, log from openpilot.system.webrtc.webrtcd import CerealOutgoingMessageProxy, CerealIncomingMessageProxy from openpilot.system.webrtc.device.video import LiveStreamVideoStreamTrack -from openpilot.system.webrtc.device.audio import AudioInputStreamTrack -from openpilot.common.realtime import DT_DMON class TestStreamSession: @@ -81,21 +79,9 @@ def test_livestream_track(self, mocker): for i in range(5): packet = self.loop.run_until_complete(track.recv()) assert packet.time_base == VIDEO_TIME_BASE - assert packet.pts == int(i * DT_DMON * VIDEO_CLOCK_RATE) + if i == 0: + start_ns = time.monotonic_ns() + start_pts = packet.pts + assert abs(i + packet.pts - (start_pts + (((time.monotonic_ns() - start_ns) * VIDEO_CLOCK_RATE) // 1_000_000_000))) < 450 #5ms assert packet.size == 0 - def test_input_audio_track(self, mocker): - packet_time, rate = 0.02, 16000 - sample_count = int(packet_time * rate) - mocked_stream = mocker.MagicMock(spec=pyaudio.Stream) - mocked_stream.read.return_value = b"\x00" * 2 * sample_count - - config = {"open.side_effect": lambda *args, **kwargs: mocked_stream} - mocker.patch("pyaudio.PyAudio", spec=True, **config) - track = AudioInputStreamTrack(audio_format=pyaudio.paInt16, packet_time=packet_time, rate=rate) - - for i in range(5): - frame = self.loop.run_until_complete(track.recv()) - assert frame.rate == rate - assert frame.samples == sample_count - assert frame.pts == i * sample_count diff --git a/system/webrtc/tests/test_webrtcd.py b/system/webrtc/tests/test_webrtcd.py deleted file mode 100644 index 4fa6d8953f7312..00000000000000 --- a/system/webrtc/tests/test_webrtcd.py +++ /dev/null @@ -1,65 +0,0 @@ -import pytest -import asyncio -import json -# for aiortc and its dependencies -import warnings -warnings.filterwarnings("ignore", category=DeprecationWarning) -warnings.filterwarnings("ignore", category=RuntimeWarning) # TODO: remove this when google-crc32c publish a python3.12 wheel - -from openpilot.system.webrtc.webrtcd import get_stream - -import aiortc -from teleoprtc import WebRTCOfferBuilder -from parameterized import parameterized_class - - -@parameterized_class(("in_services", "out_services"), [ - (["testJoystick"], ["carState"]), - ([], ["carState"]), - (["testJoystick"], []), - ([], []), -]) -@pytest.mark.asyncio -class TestWebrtcdProc: - async def assertCompletesWithTimeout(self, awaitable, timeout=1): - try: - async with asyncio.timeout(timeout): - await awaitable - except TimeoutError: - pytest.fail("Timeout while waiting for awaitable to complete") - - async def test_webrtcd(self, mocker): - mock_request = mocker.MagicMock() - async def connect(offer): - body = {'sdp': offer.sdp, 'cameras': offer.video, 'bridge_services_in': self.in_services, 'bridge_services_out': self.out_services} - mock_request.json.side_effect = mocker.AsyncMock(return_value=body) - response = await get_stream(mock_request) - response_json = json.loads(response.text) - return aiortc.RTCSessionDescription(**response_json) - - builder = WebRTCOfferBuilder(connect) - builder.offer_to_receive_video_stream("road") - builder.offer_to_receive_audio_stream() - if len(self.in_services) > 0 or len(self.out_services) > 0: - builder.add_messaging() - - stream = builder.stream() - - await self.assertCompletesWithTimeout(stream.start()) - await self.assertCompletesWithTimeout(stream.wait_for_connection()) - - assert stream.has_incoming_video_track("road") - assert stream.has_incoming_audio_track() - assert stream.has_messaging_channel() == (len(self.in_services) > 0 or len(self.out_services) > 0) - - video_track, audio_track = stream.get_incoming_video_track("road"), stream.get_incoming_audio_track() - await self.assertCompletesWithTimeout(video_track.recv()) - await self.assertCompletesWithTimeout(audio_track.recv()) - - await self.assertCompletesWithTimeout(stream.stop()) - - # cleanup, very implementation specific, test may break if it changes - assert mock_request.app["streams"].__setitem__.called, "Implementation changed, please update this test" - _, session = mock_request.app["streams"].__setitem__.call_args.args - await self.assertCompletesWithTimeout(session.post_run_cleanup()) - diff --git a/system/webrtc/webrtcd.py b/system/webrtc/webrtcd.py index 79c5b4888f31be..9ff937b67365db 100755 --- a/system/webrtc/webrtcd.py +++ b/system/webrtc/webrtcd.py @@ -1,7 +1,10 @@ #!/usr/bin/env python3 +from abc import abstractmethod +import time import argparse import asyncio +import contextlib import json import uuid import logging @@ -22,8 +25,35 @@ from cereal import messaging, log -class CerealOutgoingMessageProxy: +class AsyncTaskRunner: + def __init__(self): + self.is_running = False + self.task = None + self.logger = logging.getLogger("webrtcd") + + def start(self): + assert self.task is None + self.task = asyncio.create_task(self.run()) + + async def stop(self): + if self.task is None: + return + task = self.task + self.task = None + if task.done(): + return + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + @abstractmethod + async def run(self): + pass + + +class CerealOutgoingMessageProxy(AsyncTaskRunner): def __init__(self, sm: messaging.SubMaster): + super().__init__() self.sm = sm self.channels: list[RTCDataChannel] = [] @@ -55,6 +85,19 @@ def update(self): for channel in self.channels: channel.send(encoded_msg) + async def run(self): + from aiortc.exceptions import InvalidStateError + + while True: + try: + self.update() + except InvalidStateError: + self.logger.warning("Cereal outgoing proxy invalid state (connection closed)") + break + except Exception: + self.logger.exception("Cereal outgoing proxy failure") + await asyncio.sleep(0.01) + class CerealIncomingMessageProxy: def __init__(self, pm: messaging.PubMaster): @@ -72,37 +115,6 @@ def send(self, message: bytes): self.pm.send(msg_type, msg) -class CerealProxyRunner: - def __init__(self, proxy: CerealOutgoingMessageProxy): - self.proxy = proxy - self.is_running = False - self.task = None - self.logger = logging.getLogger("webrtcd") - - def start(self): - assert self.task is None - self.task = asyncio.create_task(self.run()) - - def stop(self): - if self.task is None or self.task.done(): - return - self.task.cancel() - self.task = None - - async def run(self): - from aiortc.exceptions import InvalidStateError - - while True: - try: - self.proxy.update() - except InvalidStateError: - self.logger.warning("Cereal outgoing proxy invalid state (connection closed)") - break - except Exception: - self.logger.exception("Cereal outgoing proxy failure") - await asyncio.sleep(0.01) - - class DynamicPubMaster(messaging.PubMaster): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -118,27 +130,15 @@ async def add_services_if_needed(self, services): class StreamSession: shared_pub_master = DynamicPubMaster([]) - def __init__(self, sdp: str, cameras: list[str], incoming_services: list[str], outgoing_services: list[str], debug_mode: bool = False): - from aiortc.mediastreams import VideoStreamTrack, AudioStreamTrack - from aiortc.contrib.media import MediaBlackhole + def __init__(self, sdp: str, init_camera: str, incoming_services: list[str], outgoing_services: list[str], debug_mode: bool = False): + from aiortc.mediastreams import VideoStreamTrack from openpilot.system.webrtc.device.video import LiveStreamVideoStreamTrack - from openpilot.system.webrtc.device.audio import AudioInputStreamTrack, AudioOutputSpeaker from teleoprtc import WebRTCAnswerBuilder - from teleoprtc.info import parse_info_from_offer - config = parse_info_from_offer(sdp) builder = WebRTCAnswerBuilder(sdp) - assert len(cameras) == config.n_expected_camera_tracks, "Incoming stream has misconfigured number of video tracks" - for cam in cameras: - track = LiveStreamVideoStreamTrack(cam) if not debug_mode else VideoStreamTrack() - builder.add_video_stream(cam, track) - if config.expected_audio_track: - track = AudioInputStreamTrack() if not debug_mode else AudioStreamTrack() - builder.add_audio_stream(track) - if config.incoming_audio_track: - self.audio_output_cls = AudioOutputSpeaker if not debug_mode else MediaBlackhole - builder.offer_to_receive_audio_stream() + self.video_track = LiveStreamVideoStreamTrack(init_camera) if not debug_mode else VideoStreamTrack() + builder.add_video_stream(init_camera, self.video_track) self.stream = builder.stream() self.identifier = str(uuid.uuid4()) @@ -146,35 +146,61 @@ def __init__(self, sdp: str, cameras: list[str], incoming_services: list[str], o self.incoming_bridge: CerealIncomingMessageProxy | None = None self.incoming_bridge_services = incoming_services self.outgoing_bridge: CerealOutgoingMessageProxy | None = None - self.outgoing_bridge_runner: CerealProxyRunner | None = None if len(incoming_services) > 0: self.incoming_bridge = CerealIncomingMessageProxy(self.shared_pub_master) if len(outgoing_services) > 0: self.outgoing_bridge = CerealOutgoingMessageProxy(messaging.SubMaster(outgoing_services)) - self.outgoing_bridge_runner = CerealProxyRunner(self.outgoing_bridge) - self.audio_output: AudioOutputSpeaker | MediaBlackhole | None = None self.run_task: asyncio.Task | None = None + self._cleanup_lock = asyncio.Lock() + self._cleanup_done = False self.logger = logging.getLogger("webrtcd") - self.logger.info("New stream session (%s), cameras %s, audio in %s out %s, incoming services %s, outgoing services %s", - self.identifier, cameras, config.incoming_audio_track, config.expected_audio_track, incoming_services, outgoing_services) + self.logger.info( + "New stream session (%s), init camera %s, incoming services %s, outgoing services %s", + self.identifier, init_camera, incoming_services, outgoing_services, + ) def start(self): self.run_task = asyncio.create_task(self.run()) - def stop(self): - if self.run_task.done(): - return - self.run_task.cancel() + async def stop(self): + if self.run_task is not None and not self.run_task.done() and self.run_task is not asyncio.current_task(): + self.run_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self.run_task self.run_task = None - asyncio.run(self.post_run_cleanup()) + await self.post_run_cleanup() async def get_answer(self): return await self.stream.start() - async def message_handler(self, message: bytes): + def message_handler(self, message: bytes): assert self.incoming_bridge is not None try: + payload = json.loads(message) if isinstance(message, (bytes, str)) else None + if isinstance(payload, dict): + msg_type = payload.get("type") + + if msg_type == "livestreamCameraSwitch": + self.video_track.switch_camera(payload["data"]["camera"]) + return + + if msg_type == "clockSync": + data = payload.get("data", {}) + pong = json.dumps({"type": "clockSync", "data": { + "action": "pong", "browserSendTime": data.get("browserSendTime"), "deviceTime": time.time() * 1000, # noqa: TID251 + }}) + self.stream.get_messaging_channel().send(pong) + return + + if msg_type == "enableTimingSei": + enabled = bool(payload.get("data", {}).get("enabled")) + if hasattr(self.video_track, 'timing_sei_enabled'): + self.video_track.timing_sei_enabled = enabled + return + + if payload.get("type") not in self.incoming_bridge_services: + return self.incoming_bridge.send(message) except Exception: self.logger.exception("Cereal incoming proxy failure") @@ -186,36 +212,34 @@ async def run(self): if self.incoming_bridge is not None: await self.shared_pub_master.add_services_if_needed(self.incoming_bridge_services) self.stream.set_message_handler(self.message_handler) - if self.outgoing_bridge_runner is not None: + if self.outgoing_bridge is not None: channel = self.stream.get_messaging_channel() - self.outgoing_bridge_runner.proxy.add_channel(channel) - self.outgoing_bridge_runner.start() - if self.stream.has_incoming_audio_track(): - track = self.stream.get_incoming_audio_track(buffered=False) - self.audio_output = self.audio_output_cls() - self.audio_output.addTrack(track) - self.audio_output.start() + self.outgoing_bridge.add_channel(channel) + self.outgoing_bridge.start() self.logger.info("Stream session (%s) connected", self.identifier) await self.stream.wait_for_disconnection() - await self.post_run_cleanup() self.logger.info("Stream session (%s) ended", self.identifier) except Exception: self.logger.exception("Stream session failure") + finally: + await self.post_run_cleanup() async def post_run_cleanup(self): - await self.stream.stop() - if self.outgoing_bridge is not None: - self.outgoing_bridge_runner.stop() - if self.audio_output: - self.audio_output.stop() + async with self._cleanup_lock: + if self._cleanup_done: + return + self._cleanup_done = True + if self.outgoing_bridge is not None: + await self.outgoing_bridge.stop() + await self.stream.stop() @dataclass class StreamRequestBody: sdp: str - cameras: list[str] + initCamera: str bridge_services_in: list[str] = field(default_factory=list) bridge_services_out: list[str] = field(default_factory=list) @@ -225,11 +249,33 @@ async def get_stream(request: 'web.Request'): raw_body = await request.json() body = StreamRequestBody(**raw_body) - session = StreamSession(body.sdp, body.cameras, body.bridge_services_in, body.bridge_services_out, debug_mode) - answer = await session.get_answer() - session.start() + async with request.app['stream_lock']: + # Fully disconnect any other active stream before starting the replacement. + for sid, s in list(stream_dict.items()): + if s.run_task and not s.run_task.done(): + try: + ch = s.stream.get_messaging_channel() + ch.send(json.dumps({"type": "connectionReplaced", "data": "Another device has connected, closing this session."})) + except Exception: + pass + await s.stop() + del stream_dict[sid] + + session = StreamSession(body.sdp, body.initCamera, body.bridge_services_in, body.bridge_services_out, debug_mode) + try: + answer = await session.get_answer() + except ValueError as e: + await session.stop() + raise web.HTTPBadRequest( + text=json.dumps({"error": "invalid_sdp", "message": str(e)}), + content_type="application/json", + ) from e + except Exception: + await session.stop() + raise + session.start() - stream_dict[session.identifier] = session + stream_dict[session.identifier] = session return web.json_response({"sdp": answer.sdp, "type": answer.type}) @@ -242,9 +288,25 @@ async def get_schema(request: 'web.Request'): return web.json_response(schema_dict) +async def post_notify(request: 'web.Request'): + try: + payload = await request.json() + except Exception as e: + raise web.HTTPBadRequest(text="Invalid JSON") from e + + for session in list(request.app.get('streams', {}).values()): + try: + ch = session.stream.get_messaging_channel() + ch.send(json.dumps(payload)) + except Exception: + continue + + return web.Response(status=200, text="OK") + + async def on_shutdown(app: 'web.Application'): for session in app['streams'].values(): - session.stop() + await session.stop() del app['streams'] @@ -257,9 +319,11 @@ def webrtcd_thread(host: str, port: int, debug: bool): app = web.Application() app['streams'] = dict() + app['stream_lock'] = asyncio.Lock() app['debug'] = debug app.on_shutdown.append(on_shutdown) app.router.add_post("/stream", get_stream) + app.router.add_post("/notify", post_notify) app.router.add_get("/schema", get_schema) web.run_app(app, host=host, port=port) diff --git a/teleoprtc_repo b/teleoprtc_repo index 389815b8ca5302..22df577821862e 160000 --- a/teleoprtc_repo +++ b/teleoprtc_repo @@ -1 +1 @@ -Subproject commit 389815b8ca5302ce7c1504b7841d4eb61a8cd51b +Subproject commit 22df577821862e32a011fb0cf42577599f3a79c4 diff --git a/third_party/.gitignore b/third_party/.gitignore deleted file mode 100644 index 0d20b6487c61e7..00000000000000 --- a/third_party/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.pyc diff --git a/third_party/SConscript b/third_party/SConscript deleted file mode 100644 index 507c17c4a5c715..00000000000000 --- a/third_party/SConscript +++ /dev/null @@ -1,4 +0,0 @@ -Import('env') - -env.Library('json11', ['json11/json11.cpp'], CCFLAGS=env['CCFLAGS'] + ['-Wno-unqualified-std-cast-call']) -env.Library('kaitai', ['kaitai/kaitaistream.cpp'], CPPDEFINES=['KS_STR_ENCODING_NONE']) diff --git a/third_party/acados/.gitignore b/third_party/acados/.gitignore deleted file mode 100644 index 68858c62e4321e..00000000000000 --- a/third_party/acados/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -acados_repo/ -lib -!x86_64/ -!larch64/ -!aarch64/ diff --git a/third_party/acados/Darwin/lib/libacados.dylib b/third_party/acados/Darwin/lib/libacados.dylib deleted file mode 100755 index 8cd5a41f14410b..00000000000000 --- a/third_party/acados/Darwin/lib/libacados.dylib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:620195ff61aaccf9adf00a66b8acf4e9915a0895d0a86f9f51ec952e44fad70a -size 853776 diff --git a/third_party/acados/Darwin/lib/libblasfeo.dylib b/third_party/acados/Darwin/lib/libblasfeo.dylib deleted file mode 100755 index 442a6c736d9ec0..00000000000000 --- a/third_party/acados/Darwin/lib/libblasfeo.dylib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1d9dbeb68b2ac13c884f606a1f6032f399640e0928cecad4c22b700a8d8ae970 -size 2010877 diff --git a/third_party/acados/Darwin/lib/libhpipm.dylib b/third_party/acados/Darwin/lib/libhpipm.dylib deleted file mode 100755 index 019ec8019ed70a..00000000000000 --- a/third_party/acados/Darwin/lib/libhpipm.dylib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:35783dba64c2d5bbe7e4c98ad01accac56b478b1bf874969ab5c31d7495499a2 -size 2290624 diff --git a/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib b/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib deleted file mode 100755 index caaa8ec7756d90..00000000000000 --- a/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f57eea51f4b91deff47fbf599eedc3eafedd395f23465b5fb24b2148fdaa2859 -size 496707 diff --git a/third_party/acados/Darwin/lib/libqpOASES_e.dylib b/third_party/acados/Darwin/lib/libqpOASES_e.dylib deleted file mode 120000 index e3d94c4bc2d648..00000000000000 --- a/third_party/acados/Darwin/lib/libqpOASES_e.dylib +++ /dev/null @@ -1 +0,0 @@ -libqpOASES_e.3.1.dylib \ No newline at end of file diff --git a/third_party/acados/Darwin/t_renderer b/third_party/acados/Darwin/t_renderer deleted file mode 100755 index 83a74ea5a30417..00000000000000 --- a/third_party/acados/Darwin/t_renderer +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c6c78791cfdd841da14266c62a6099d0af53cec348051118f1a70518729aa5ba -size 8483768 diff --git a/third_party/acados/aarch64 b/third_party/acados/aarch64 deleted file mode 120000 index 062c65e8d99c64..00000000000000 --- a/third_party/acados/aarch64 +++ /dev/null @@ -1 +0,0 @@ -larch64/ \ No newline at end of file diff --git a/third_party/acados/acados_template/.gitignore b/third_party/acados/acados_template/.gitignore deleted file mode 100644 index 63b741bb9dce90..00000000000000 --- a/third_party/acados/acados_template/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -__pycache__/ - -# Cython intermediates -*_pyx.c -*_pyx.o -*_pyx.so diff --git a/third_party/acados/acados_template/__init__.py b/third_party/acados/acados_template/__init__.py deleted file mode 100644 index bfbe907990b8be..00000000000000 --- a/third_party/acados/acados_template/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -from .acados_model import AcadosModel -from .acados_ocp import AcadosOcp, AcadosOcpConstraints, AcadosOcpCost, AcadosOcpDims, AcadosOcpOptions -from .acados_sim import AcadosSim, AcadosSimDims, AcadosSimOpts -from .acados_ocp_solver import AcadosOcpSolver, get_simulink_default_opts, ocp_get_default_cmake_builder -from .acados_sim_solver import AcadosSimSolver, sim_get_default_cmake_builder -from .utils import print_casadi_expression, get_acados_path, get_python_interface_path, \ - get_tera_exec_path, get_tera, check_casadi_version, acados_dae_model_json_dump, \ - casadi_length, make_object_json_dumpable, J_to_idx, get_default_simulink_opts - -from .zoro_description import ZoroDescription, process_zoro_description diff --git a/third_party/acados/acados_template/acados_layout.json b/third_party/acados/acados_template/acados_layout.json deleted file mode 100644 index a1cc5bbdf30fd3..00000000000000 --- a/third_party/acados/acados_template/acados_layout.json +++ /dev/null @@ -1,834 +0,0 @@ -{ - "code_export_directory": [ - "str" - ], - "acados_include_path": [ - "str" - ], - "cython_include_dirs": [ - "list" - ], - "json_file": [ - "str" - ], - "shared_lib_ext": [ - "str" - ], - "model": { - "name" : [ - "str" - ], - "dyn_ext_fun_type" : [ - "str" - ], - "dyn_generic_source" : [ - "str" - ], - "dyn_impl_dae_fun" : [ - "str" - ], - "dyn_impl_dae_fun_jac" : [ - "str" - ], - "dyn_impl_dae_jac" : [ - "str" - ], - "dyn_disc_fun_jac_hess" : [ - "str" - ], - "dyn_disc_fun_jac" : [ - "str" - ], - "dyn_disc_fun" : [ - "str" - ], - "gnsf" : { - "nontrivial_f_LO": [ - "int" - ], - "purely_linear": [ - "int" - ] - } - }, - "parameter_values": [ - "ndarray", - [ - "np" - ] - ], - "acados_lib_path": [ - "str" - ], - "problem_class": [ - "str" - ], - "constraints": { - "constr_type": [ - "str" - ], - "constr_type_e": [ - "str" - ], - "lbx": [ - "ndarray", - [ - "nbx" - ] - ], - "lbu": [ - "ndarray", - [ - "nbu" - ] - ], - "ubx": [ - "ndarray", - [ - "nbx" - ] - ], - "ubu": [ - "ndarray", - [ - "nbu" - ] - ], - "idxbx": [ - "ndarray", - [ - "nbx" - ] - ], - "idxbu": [ - "ndarray", - [ - "nbu" - ] - ], - "lbx_e": [ - "ndarray", - [ - "nbx_e" - ] - ], - "ubx_e": [ - "ndarray", - [ - "nbx_e" - ] - ], - "idxbx_e": [ - "ndarray", - [ - "nbx_e" - ] - ], - "lbx_0": [ - "ndarray", - [ - "nbx_0" - ] - ], - "ubx_0": [ - "ndarray", - [ - "nbx_0" - ] - ], - "idxbx_0": [ - "ndarray", - [ - "nbx_0" - ] - ], - "idxbxe_0": [ - "ndarray", - [ - "nbxe_0" - ] - ], - "lg": [ - "ndarray", - [ - "ng" - ] - ], - "ug": [ - "ndarray", - [ - "ng" - ] - ], - "D": [ - "ndarray", - [ - "ng", - "nu" - ] - ], - "C": [ - "ndarray", - [ - "ng", - "nx" - ] - ], - "C_e": [ - "ndarray", - [ - "ng_e", - "nx" - ] - ], - "lg_e": [ - "ndarray", - [ - "ng_e" - ] - ], - "ug_e": [ - "ndarray", - [ - "ng_e" - ] - ], - "lh": [ - "ndarray", - [ - "nh" - ] - ], - "uh": [ - "ndarray", - [ - "nh" - ] - ], - "lh_e": [ - "ndarray", - [ - "nh_e" - ] - ], - "uh_e": [ - "ndarray", - [ - "nh_e" - ] - ], - "lphi": [ - "ndarray", - [ - "nphi" - ] - ], - "uphi": [ - "ndarray", - [ - "nphi" - ] - ], - "lphi_e": [ - "ndarray", - [ - "nphi_e" - ] - ], - "uphi_e": [ - "ndarray", - [ - "nphi_e" - ] - ], - "lsbx": [ - "ndarray", - [ - "nsbx" - ] - ], - "usbx": [ - "ndarray", - [ - "nsbx" - ] - ], - "lsbu": [ - "ndarray", - [ - "nsbu" - ] - ], - "usbu": [ - "ndarray", - [ - "nsbu" - ] - ], - "idxsbx": [ - "ndarray", - [ - "nsbx" - ] - ], - "idxsbu": [ - "ndarray", - [ - "nsbu" - ] - ], - "lsbx_e": [ - "ndarray", - [ - "nsbx_e" - ] - ], - "usbx_e": [ - "ndarray", - [ - "nsbx_e" - ] - ], - "idxsbx_e": [ - "ndarray", - [ - "nsbx_e" - ] - ], - "lsg": [ - "ndarray", - [ - "nsg" - ] - ], - "usg": [ - "ndarray", - [ - "nsg" - ] - ], - "idxsg": [ - "ndarray", - [ - "nsg" - ] - ], - "lsg_e": [ - "ndarray", - [ - "nsg_e" - ] - ], - "usg_e": [ - "ndarray", - [ - "nsg_e" - ] - ], - "idxsg_e": [ - "ndarray", - [ - "nsg_e" - ] - ], - "lsh": [ - "ndarray", - [ - "nsh" - ] - ], - "ush": [ - "ndarray", - [ - "nsh" - ] - ], - "idxsh": [ - "ndarray", - [ - "nsh" - ] - ], - "lsh_e": [ - "ndarray", - [ - "nsh_e" - ] - ], - "ush_e": [ - "ndarray", - [ - "nsh_e" - ] - ], - "idxsh_e": [ - "ndarray", - [ - "nsh_e" - ] - ], - "lsphi": [ - "ndarray", - [ - "nsphi" - ] - ], - "usphi": [ - "ndarray", - [ - "nsphi" - ] - ], - "idxsphi": [ - "ndarray", - [ - "nsphi" - ] - ], - "lsphi_e": [ - "ndarray", - [ - "nsphi_e" - ] - ], - "usphi_e": [ - "ndarray", - [ - "nsphi_e" - ] - ], - "idxsphi_e": [ - "ndarray", - [ - "nsphi_e" - ] - ] - }, - "cost": { - "cost_type_0": [ - "str" - ], - "cost_type": [ - "str" - ], - "cost_type_e": [ - "str" - ], - "cost_ext_fun_type_0": [ - "str" - ], - "cost_ext_fun_type": [ - "str" - ], - "cost_ext_fun_type_e": [ - "str" - ], - "Vu_0": [ - "ndarray", - [ - "ny_0", - "nu" - ] - ], - "Vu": [ - "ndarray", - [ - "ny", - "nu" - ] - ], - "Vx_0": [ - "ndarray", - [ - "ny_0", - "nx" - ] - ], - "Vx": [ - "ndarray", - [ - "ny", - "nx" - ] - ], - "Vx_e": [ - "ndarray", - [ - "ny_e", - "nx" - ] - ], - "Vz_0": [ - "ndarray", - [ - "ny_0", - "nz" - ] - ], - "Vz": [ - "ndarray", - [ - "ny", - "nz" - ] - ], - "W_0": [ - "ndarray", - [ - "ny_0", - "ny_0" - ] - ], - "W": [ - "ndarray", - [ - "ny", - "ny" - ] - ], - "Zl": [ - "ndarray", - [ - "ns" - ] - ], - "Zu": [ - "ndarray", - [ - "ns" - ] - ], - "zl": [ - "ndarray", - [ - "ns" - ] - ], - "zu": [ - "ndarray", - [ - "ns" - ] - ], - "W_e": [ - "ndarray", - [ - "ny_e", - "ny_e" - ] - ], - "yref_0": [ - "ndarray", - [ - "ny_0" - ] - ], - "yref": [ - "ndarray", - [ - "ny" - ] - ], - "yref_e": [ - "ndarray", - [ - "ny_e" - ] - ], - "Zl_e": [ - "ndarray", - [ - "ns_e" - ] - ], - "Zu_e": [ - "ndarray", - [ - "ns_e" - ] - ], - "zl_e": [ - "ndarray", - [ - "ns_e" - ] - ], - "zu_e": [ - "ndarray", - [ - "ns_e" - ] - ] - }, - "dims": { - "N": [ - "int" - ], - "nbu": [ - "int" - ], - "nbx": [ - "int" - ], - "nsbu": [ - "int" - ], - "nsbx": [ - "int" - ], - "nsbx_e": [ - "int" - ], - "nbx_0": [ - "int" - ], - "nbx_e": [ - "int" - ], - "nbxe_0": [ - "int" - ], - "nsg": [ - "int" - ], - "nsg_e": [ - "int" - ], - "nsh": [ - "int" - ], - "nsh_e": [ - "int" - ], - "nsphi": [ - "int" - ], - "nsphi_e": [ - "int" - ], - "ns": [ - "int" - ], - "ns_e": [ - "int" - ], - "ng": [ - "int" - ], - "ng_e": [ - "int" - ], - "np": [ - "int" - ], - "nr": [ - "int" - ], - "nr_e": [ - "int" - ], - "nh": [ - "int" - ], - "nh_e": [ - "int" - ], - "nphi": [ - "int" - ], - "nphi_e": [ - "int" - ], - "nu": [ - "int" - ], - "nx": [ - "int" - ], - "ny": [ - "int" - ], - "ny_0": [ - "int" - ], - "ny_e": [ - "int" - ], - "nz": [ - "int" - ], - "gnsf_nx1": [ - "int" - ], - "gnsf_nz1": [ - "int" - ], - "gnsf_nuhat": [ - "int" - ], - "gnsf_ny": [ - "int" - ], - "gnsf_nout": [ - "int" - ] - }, - "solver_options": { - "time_steps": [ - "ndarray", - [ - "N" - ] - ], - "hessian_approx": [ - "str" - ], - "hpipm_mode": [ - "str" - ], - "regularize_method": [ - "str" - ], - "integrator_type": [ - "str" - ], - "nlp_solver_type": [ - "str" - ], - "collocation_type": [ - "str" - ], - "globalization": [ - "str" - ], - "nlp_solver_step_length": [ - "float" - ], - "levenberg_marquardt": [ - "float" - ], - "qp_solver": [ - "str" - ], - "tf": [ - "float" - ], - "Tsim": [ - "float" - ], - "alpha_min": [ - "float" - ], - "alpha_reduction": [ - "float" - ], - "line_search_use_sufficient_descent": [ - "int" - ], - "globalization_use_SOC": [ - "int" - ], - "full_step_dual": [ - "int" - ], - "eps_sufficient_descent": [ - "float" - ], - "sim_method_num_stages": [ - "ndarray", - [ - "N" - ] - ], - "sim_method_num_steps": [ - "ndarray", - [ - "N" - ] - ], - "sim_method_newton_iter": [ - "int" - ], - "sim_method_newton_tol": [ - "float" - ], - "sim_method_jac_reuse": [ - "ndarray", - [ - "N" - ] - ], - "qp_solver_cond_N": [ - "int" - ], - "qp_solver_warm_start": [ - "int" - ], - "qp_solver_tol_stat": [ - "float" - ], - "qp_solver_tol_eq": [ - "float" - ], - "qp_solver_tol_ineq": [ - "float" - ], - "qp_solver_tol_comp": [ - "float" - ], - "qp_solver_iter_max": [ - "int" - ], - "qp_solver_cond_ric_alg": [ - "int" - ], - "qp_solver_ric_alg": [ - "int" - ], - "nlp_solver_tol_stat": [ - "float" - ], - "nlp_solver_tol_eq": [ - "float" - ], - "nlp_solver_tol_ineq": [ - "float" - ], - "nlp_solver_tol_comp": [ - "float" - ], - "nlp_solver_max_iter": [ - "int" - ], - "nlp_solver_ext_qp_res": [ - "int" - ], - "print_level": [ - "int" - ], - "initialize_t_slacks": [ - "int" - ], - "exact_hess_cost": [ - "int" - ], - "exact_hess_constr": [ - "int" - ], - "exact_hess_dyn": [ - "int" - ], - "ext_cost_num_hess": [ - "int" - ], - "ext_fun_compile_flags": [ - "str" - ], - "model_external_shared_lib_dir": [ - "str" - ], - "model_external_shared_lib_name": [ - "str" - ] - } -} diff --git a/third_party/acados/acados_template/acados_model.py b/third_party/acados/acados_template/acados_model.py deleted file mode 100644 index b7c6945442c422..00000000000000 --- a/third_party/acados/acados_template/acados_model.py +++ /dev/null @@ -1,154 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - - -class AcadosModel(): - """ - Class containing all the information to code generate the external CasADi functions - that are needed when creating an acados ocp solver or acados integrator. - Thus, this class contains: - - a) the :py:attr:`name` of the model, - b) all CasADi variables/expressions needed in the CasADi function generation process. - """ - def __init__(self): - ## common for OCP and Integrator - self.name = None - """ - The model name is used for code generation. Type: string. Default: :code:`None` - """ - self.x = None #: CasADi variable describing the state of the system; Default: :code:`None` - self.xdot = None #: CasADi variable describing the derivative of the state wrt time; Default: :code:`None` - self.u = None #: CasADi variable describing the input of the system; Default: :code:`None` - self.z = [] #: CasADi variable describing the algebraic variables of the DAE; Default: :code:`empty` - self.p = [] #: CasADi variable describing parameters of the DAE; Default: :code:`empty` - # dynamics - self.f_impl_expr = None - """ - CasADi expression for the implicit dynamics :math:`f_\\text{impl}(\dot{x}, x, u, z, p) = 0`. - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.integrator_type` == 'IRK'. - Default: :code:`None` - """ - self.f_expl_expr = None - """ - CasADi expression for the explicit dynamics :math:`\dot{x} = f_\\text{expl}(x, u, p)`. - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.integrator_type` == 'ERK'. - Default: :code:`None` - """ - self.disc_dyn_expr = None - """ - CasADi expression for the discrete dynamics :math:`x_{+} = f_\\text{disc}(x, u, p)`. - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.integrator_type` == 'DISCRETE'. - Default: :code:`None` - """ - - self.dyn_ext_fun_type = 'casadi' #: type of external functions for dynamics module; 'casadi' or 'generic'; Default: 'casadi' - self.dyn_generic_source = None #: name of source file for discrete dyanamics; Default: :code:`None` - self.dyn_disc_fun_jac_hess = None #: name of function discrete dyanamics + jacobian and hessian; Default: :code:`None` - self.dyn_disc_fun_jac = None #: name of function discrete dyanamics + jacobian; Default: :code:`None` - self.dyn_disc_fun = None #: name of function discrete dyanamics; Default: :code:`None` - - # for GNSF models - self.gnsf = {'nontrivial_f_LO': 1, 'purely_linear': 0} - """ - dictionary containing information on GNSF structure needed when rendering templates. - Contains integers `nontrivial_f_LO`, `purely_linear`. - """ - - ## for OCP - # constraints - # BGH(default): lh <= h(x, u) <= uh - self.con_h_expr = None #: CasADi expression for the constraint :math:`h`; Default: :code:`None` - # BGP(convex over nonlinear): lphi <= phi(r(x, u)) <= uphi - self.con_phi_expr = None #: CasADi expression for the constraint phi; Default: :code:`None` - self.con_r_expr = None #: CasADi expression for the constraint phi(r); Default: :code:`None` - self.con_r_in_phi = None - # terminal - self.con_h_expr_e = None #: CasADi expression for the terminal constraint :math:`h^e`; Default: :code:`None` - self.con_r_expr_e = None #: CasADi expression for the terminal constraint; Default: :code:`None` - self.con_phi_expr_e = None #: CasADi expression for the terminal constraint; Default: :code:`None` - self.con_r_in_phi_e = None - # cost - self.cost_y_expr = None #: CasADi expression for nonlinear least squares; Default: :code:`None` - self.cost_y_expr_e = None #: CasADi expression for nonlinear least squares, terminal; Default: :code:`None` - self.cost_y_expr_0 = None #: CasADi expression for nonlinear least squares, initial; Default: :code:`None` - self.cost_expr_ext_cost = None #: CasADi expression for external cost; Default: :code:`None` - self.cost_expr_ext_cost_e = None #: CasADi expression for external cost, terminal; Default: :code:`None` - self.cost_expr_ext_cost_0 = None #: CasADi expression for external cost, initial; Default: :code:`None` - self.cost_expr_ext_cost_custom_hess = None #: CasADi expression for custom hessian (only for external cost); Default: :code:`None` - self.cost_expr_ext_cost_custom_hess_e = None #: CasADi expression for custom hessian (only for external cost), terminal; Default: :code:`None` - self.cost_expr_ext_cost_custom_hess_0 = None #: CasADi expression for custom hessian (only for external cost), initial; Default: :code:`None` - - ## CONVEX_OVER_NONLINEAR convex-over-nonlinear cost: psi(y(x, u, p) - y_ref; p) - self.cost_psi_expr_0 = None - """ - CasADi expression for the outer loss function :math:`\psi(r, p)`, initial; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_0` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_psi_expr = None - """ - CasADi expression for the outer loss function :math:`\psi(r, p)`; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_psi_expr_e = None - """ - CasADi expression for the outer loss function :math:`\psi(r, p)`, terminal; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_e` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_r_in_psi_expr_0 = None - """ - CasADi expression for the argument :math:`r`; to the outer loss function :math:`\psi(r, p)`, initial; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_0` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_r_in_psi_expr = None - """ - CasADi expression for the argument :math:`r`; to the outer loss function :math:`\psi(r, p)`; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_r_in_psi_expr_e = None - """ - CasADi expression for the argument :math:`r`; to the outer loss function :math:`\psi(r, p)`, terminal; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_e` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_conl_custom_outer_hess_0 = None - """ - CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost), initial; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_0` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_conl_custom_outer_hess = None - """ - CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost); Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_conl_custom_outer_hess_e = None - """ - CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost), terminal; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_e` == 'CONVEX_OVER_NONLINEAR'. - """ diff --git a/third_party/acados/acados_template/acados_ocp.py b/third_party/acados/acados_template/acados_ocp.py deleted file mode 100644 index ec02822ceb2754..00000000000000 --- a/third_party/acados/acados_template/acados_ocp.py +++ /dev/null @@ -1,3167 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -import numpy as np -import os -from .acados_model import AcadosModel -from .utils import get_acados_path, J_to_idx, J_to_idx_slack, get_lib_ext - -class AcadosOcpDims: - """ - Class containing the dimensions of the optimal control problem. - """ - def __init__(self): - self.__nx = None - self.__nu = None - self.__nz = 0 - self.__np = 0 - self.__ny = 0 - self.__ny_e = 0 - self.__ny_0 = 0 - self.__nr = 0 - self.__nr_e = 0 - self.__nh = 0 - self.__nh_e = 0 - self.__nphi = 0 - self.__nphi_e = 0 - self.__nbx = 0 - self.__nbx_0 = 0 - self.__nbx_e = 0 - self.__nbu = 0 - self.__nsbx = 0 - self.__nsbx_e = 0 - self.__nsbu = 0 - self.__nsh = 0 - self.__nsh_e = 0 - self.__nsphi = 0 - self.__nsphi_e = 0 - self.__ns = 0 - self.__ns_e = 0 - self.__ng = 0 - self.__ng_e = 0 - self.__nsg = 0 - self.__nsg_e = 0 - self.__nbxe_0 = None - self.__N = None - - - @property - def nx(self): - """:math:`n_x` - number of states. - Type: int; default: None""" - return self.__nx - - @property - def nz(self): - """:math:`n_z` - number of algebraic variables. - Type: int; default: 0""" - return self.__nz - - @property - def nu(self): - """:math:`n_u` - number of inputs. - Type: int; default: None""" - return self.__nu - - @property - def np(self): - """:math:`n_p` - number of parameters. - Type: int; default: 0""" - return self.__np - - @property - def ny(self): - """:math:`n_y` - number of residuals in Lagrange term. - Type: int; default: 0""" - return self.__ny - - @property - def ny_0(self): - """:math:`n_{y}^0` - number of residuals in Mayer term. - Type: int; default: 0""" - return self.__ny_0 - - @property - def ny_e(self): - """:math:`n_{y}^e` - number of residuals in Mayer term. - Type: int; default: 0""" - return self.__ny_e - - @property - def nr(self): - """:math:`n_{\pi}` - dimension of the image of the inner nonlinear function in positive definite constraints. - Type: int; default: 0""" - return self.__nr - - @property - def nr_e(self): - """:math:`n_{\pi}^e` - dimension of the image of the inner nonlinear function in positive definite constraints. - Type: int; default: 0""" - return self.__nr_e - - @property - def nh(self): - """:math:`n_h` - number of nonlinear constraints. - Type: int; default: 0""" - return self.__nh - - @property - def nh_e(self): - """:math:`n_{h}^e` - number of nonlinear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nh_e - - @property - def nphi(self): - """:math:`n_{\phi}` - number of convex-over-nonlinear constraints. - Type: int; default: 0""" - return self.__nphi - - @property - def nphi_e(self): - """:math:`n_{\phi}^e` - number of convex-over-nonlinear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nphi_e - - @property - def nbx(self): - """:math:`n_{b_x}` - number of state bounds. - Type: int; default: 0""" - return self.__nbx - - @property - def nbxe_0(self): - """:math:`n_{be_{x0}}` - number of state bounds at initial shooting node that are equalities. - Type: int; default: None""" - return self.__nbxe_0 - - @property - def nbx_0(self): - """:math:`n_{b_{x0}}` - number of state bounds for initial state. - Type: int; default: 0""" - return self.__nbx_0 - - @property - def nbx_e(self): - """:math:`n_{b_x}` - number of state bounds at terminal shooting node N. - Type: int; default: 0""" - return self.__nbx_e - - @property - def nbu(self): - """:math:`n_{b_u}` - number of input bounds. - Type: int; default: 0""" - return self.__nbu - - @property - def nsbx(self): - """:math:`n_{{sb}_x}` - number of soft state bounds. - Type: int; default: 0""" - return self.__nsbx - - @property - def nsbx_e(self): - """:math:`n_{{sb}^e_{x}}` - number of soft state bounds at terminal shooting node N. - Type: int; default: 0""" - return self.__nsbx_e - - @property - def nsbu(self): - """:math:`n_{{sb}_u}` - number of soft input bounds. - Type: int; default: 0""" - return self.__nsbu - - @property - def nsg(self): - """:math:`n_{{sg}}` - number of soft general linear constraints. - Type: int; default: 0""" - return self.__nsg - - @property - def nsg_e(self): - """:math:`n_{{sg}^e}` - number of soft general linear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nsg_e - - @property - def nsh(self): - """:math:`n_{{sh}}` - number of soft nonlinear constraints. - Type: int; default: 0""" - return self.__nsh - - @property - def nsh_e(self): - """:math:`n_{{sh}}^e` - number of soft nonlinear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nsh_e - - @property - def nsphi(self): - """:math:`n_{{s\phi}}` - number of soft convex-over-nonlinear constraints. - Type: int; default: 0""" - return self.__nsphi - - @property - def nsphi_e(self): - """:math:`n_{{s\phi}^e}` - number of soft convex-over-nonlinear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nsphi_e - - @property - def ns(self): - """:math:`n_{s}` - total number of slacks. - Type: int; default: 0""" - return self.__ns - - @property - def ns_e(self): - """:math:`n_{s}^e` - total number of slacks at terminal shooting node N. - Type: int; default: 0""" - return self.__ns_e - - @property - def ng(self): - """:math:`n_{g}` - number of general polytopic constraints. - Type: int; default: 0""" - return self.__ng - - @property - def ng_e(self): - """:math:`n_{g}^e` - number of general polytopic constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__ng_e - - @property - def N(self): - """:math:`N` - prediction horizon. - Type: int; default: None""" - return self.__N - - @nx.setter - def nx(self, nx): - if isinstance(nx, int) and nx > 0: - self.__nx = nx - else: - raise Exception('Invalid nx value, expected positive integer.') - - @nz.setter - def nz(self, nz): - if isinstance(nz, int) and nz > -1: - self.__nz = nz - else: - raise Exception('Invalid nz value, expected nonnegative integer.') - - @nu.setter - def nu(self, nu): - if isinstance(nu, int) and nu > -1: - self.__nu = nu - else: - raise Exception('Invalid nu value, expected nonnegative integer.') - - @np.setter - def np(self, np): - if isinstance(np, int) and np > -1: - self.__np = np - else: - raise Exception('Invalid np value, expected nonnegative integer.') - - @ny_0.setter - def ny_0(self, ny_0): - if isinstance(ny_0, int) and ny_0 > -1: - self.__ny_0 = ny_0 - else: - raise Exception('Invalid ny_0 value, expected nonnegative integer.') - - @ny.setter - def ny(self, ny): - if isinstance(ny, int) and ny > -1: - self.__ny = ny - else: - raise Exception('Invalid ny value, expected nonnegative integer.') - - @ny_e.setter - def ny_e(self, ny_e): - if isinstance(ny_e, int) and ny_e > -1: - self.__ny_e = ny_e - else: - raise Exception('Invalid ny_e value, expected nonnegative integer.') - - @nr.setter - def nr(self, nr): - if isinstance(nr, int) and nr > -1: - self.__nr = nr - else: - raise Exception('Invalid nr value, expected nonnegative integer.') - - @nr_e.setter - def nr_e(self, nr_e): - if isinstance(nr_e, int) and nr_e > -1: - self.__nr_e = nr_e - else: - raise Exception('Invalid nr_e value, expected nonnegative integer.') - - @nh.setter - def nh(self, nh): - if isinstance(nh, int) and nh > -1: - self.__nh = nh - else: - raise Exception('Invalid nh value, expected nonnegative integer.') - - @nh_e.setter - def nh_e(self, nh_e): - if isinstance(nh_e, int) and nh_e > -1: - self.__nh_e = nh_e - else: - raise Exception('Invalid nh_e value, expected nonnegative integer.') - - @nphi.setter - def nphi(self, nphi): - if isinstance(nphi, int) and nphi > -1: - self.__nphi = nphi - else: - raise Exception('Invalid nphi value, expected nonnegative integer.') - - @nphi_e.setter - def nphi_e(self, nphi_e): - if isinstance(nphi_e, int) and nphi_e > -1: - self.__nphi_e = nphi_e - else: - raise Exception('Invalid nphi_e value, expected nonnegative integer.') - - @nbx.setter - def nbx(self, nbx): - if isinstance(nbx, int) and nbx > -1: - self.__nbx = nbx - else: - raise Exception('Invalid nbx value, expected nonnegative integer.') - - @nbxe_0.setter - def nbxe_0(self, nbxe_0): - if isinstance(nbxe_0, int) and nbxe_0 > -1: - self.__nbxe_0 = nbxe_0 - else: - raise Exception('Invalid nbxe_0 value, expected nonnegative integer.') - - @nbx_0.setter - def nbx_0(self, nbx_0): - if isinstance(nbx_0, int) and nbx_0 > -1: - self.__nbx_0 = nbx_0 - else: - raise Exception('Invalid nbx_0 value, expected nonnegative integer.') - - @nbx_e.setter - def nbx_e(self, nbx_e): - if isinstance(nbx_e, int) and nbx_e > -1: - self.__nbx_e = nbx_e - else: - raise Exception('Invalid nbx_e value, expected nonnegative integer.') - - @nbu.setter - def nbu(self, nbu): - if isinstance(nbu, int) and nbu > -1: - self.__nbu = nbu - else: - raise Exception('Invalid nbu value, expected nonnegative integer.') - - @nsbx.setter - def nsbx(self, nsbx): - if isinstance(nsbx, int) and nsbx > -1: - self.__nsbx = nsbx - else: - raise Exception('Invalid nsbx value, expected nonnegative integer.') - - @nsbx_e.setter - def nsbx_e(self, nsbx_e): - if isinstance(nsbx_e, int) and nsbx_e > -1: - self.__nsbx_e = nsbx_e - else: - raise Exception('Invalid nsbx_e value, expected nonnegative integer.') - - @nsbu.setter - def nsbu(self, nsbu): - if isinstance(nsbu, int) and nsbu > -1: - self.__nsbu = nsbu - else: - raise Exception('Invalid nsbu value, expected nonnegative integer.') - - @nsg.setter - def nsg(self, nsg): - if isinstance(nsg, int) and nsg > -1: - self.__nsg = nsg - else: - raise Exception('Invalid nsg value, expected nonnegative integer.') - - @nsg_e.setter - def nsg_e(self, nsg_e): - if isinstance(nsg_e, int) and nsg_e > -1: - self.__nsg_e = nsg_e - else: - raise Exception('Invalid nsg_e value, expected nonnegative integer.') - - @nsh.setter - def nsh(self, nsh): - if isinstance(nsh, int) and nsh > -1: - self.__nsh = nsh - else: - raise Exception('Invalid nsh value, expected nonnegative integer.') - - @nsh_e.setter - def nsh_e(self, nsh_e): - if isinstance(nsh_e, int) and nsh_e > -1: - self.__nsh_e = nsh_e - else: - raise Exception('Invalid nsh_e value, expected nonnegative integer.') - - @nsphi.setter - def nsphi(self, nsphi): - if isinstance(nsphi, int) and nsphi > -1: - self.__nsphi = nsphi - else: - raise Exception('Invalid nsphi value, expected nonnegative integer.') - - @nsphi_e.setter - def nsphi_e(self, nsphi_e): - if isinstance(nsphi_e, int) and nsphi_e > -1: - self.__nsphi_e = nsphi_e - else: - raise Exception('Invalid nsphi_e value, expected nonnegative integer.') - - @ns.setter - def ns(self, ns): - if isinstance(ns, int) and ns > -1: - self.__ns = ns - else: - raise Exception('Invalid ns value, expected nonnegative integer.') - - @ns_e.setter - def ns_e(self, ns_e): - if isinstance(ns_e, int) and ns_e > -1: - self.__ns_e = ns_e - else: - raise Exception('Invalid ns_e value, expected nonnegative integer.') - - @ng.setter - def ng(self, ng): - if isinstance(ng, int) and ng > -1: - self.__ng = ng - else: - raise Exception('Invalid ng value, expected nonnegative integer.') - - @ng_e.setter - def ng_e(self, ng_e): - if isinstance(ng_e, int) and ng_e > -1: - self.__ng_e = ng_e - else: - raise Exception('Invalid ng_e value, expected nonnegative integer.') - - @N.setter - def N(self, N): - if isinstance(N, int) and N > 0: - self.__N = N - else: - raise Exception('Invalid N value, expected positive integer.') - - def set(self, attr, value): - setattr(self, attr, value) - - -class AcadosOcpCost: - """ - Class containing the numerical data of the cost: - - NOTE: all cost terms, except for the terminal one are weighted with the corresponding time step. - This means given the time steps are :math:`\Delta t_0,..., \Delta t_N`, the total cost is given by: - :math:`c_\\text{total} = \Delta t_0 \cdot c_0(x_0, u_0, p_0, z_0) + ... + \Delta t_{N-1} \cdot c_{N-1}(x_0, u_0, p_0, z_0) + c_N(x_N, p_N)`. - - This means the Lagrange cost term is given in continuous time, this makes up for a seeminglessly OCP discretization with a nonuniform time grid. - - In case of LINEAR_LS: - stage cost is - :math:`l(x,u,z) = || V_x \, x + V_u \, u + V_z \, z - y_\\text{ref}||^2_W`, - terminal cost is - :math:`m(x) = || V^e_x \, x - y_\\text{ref}^e||^2_{W^e}` - - In case of NONLINEAR_LS: - stage cost is - :math:`l(x,u,z,p) = || y(x,u,z,p) - y_\\text{ref}||^2_W`, - terminal cost is - :math:`m(x,p) = || y^e(x,p) - y_\\text{ref}^e||^2_{W^e}` - - In case of CONVEX_OVER_NONLINEAR: - stage cost is - :math:`l(x,u,p) = \psi(y(x,u,p) - y_\\text{ref}, p)`, - terminal cost is - :math:`m(x, p) = \psi^e (y^e(x,p) - y_\\text{ref}^e, p)` - """ - def __init__(self): - # initial stage - self.__cost_type_0 = None - self.__W_0 = None - self.__Vx_0 = None - self.__Vu_0 = None - self.__Vz_0 = None - self.__yref_0 = None - self.__cost_ext_fun_type_0 = 'casadi' - # Lagrange term - self.__cost_type = 'LINEAR_LS' # cost type - self.__W = np.zeros((0,0)) - self.__Vx = np.zeros((0,0)) - self.__Vu = np.zeros((0,0)) - self.__Vz = np.zeros((0,0)) - self.__yref = np.array([]) - self.__Zl = np.array([]) - self.__Zu = np.array([]) - self.__zl = np.array([]) - self.__zu = np.array([]) - self.__cost_ext_fun_type = 'casadi' - # Mayer term - self.__cost_type_e = 'LINEAR_LS' - self.__W_e = np.zeros((0,0)) - self.__Vx_e = np.zeros((0,0)) - self.__yref_e = np.array([]) - self.__Zl_e = np.array([]) - self.__Zu_e = np.array([]) - self.__zl_e = np.array([]) - self.__zu_e = np.array([]) - self.__cost_ext_fun_type_e = 'casadi' - - # initial stage - @property - def cost_type_0(self): - """Cost type at initial shooting node (0) - -- string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR} or :code:`None`. - Default: :code:`None`. - - .. note:: Cost at initial stage is the same as for intermediate shooting nodes if not set differently explicitly. - - .. note:: If :py:attr:`cost_type_0` is set to :code:`None` values in :py:attr:`W_0`, :py:attr:`Vx_0`, :py:attr:`Vu_0`, :py:attr:`Vz_0` and :py:attr:`yref_0` are ignored (set to :code:`None`). - """ - return self.__cost_type_0 - - @property - def W_0(self): - """:math:`W_0` - weight matrix at initial shooting node (0). - Default: :code:`None`. - """ - return self.__W_0 - - @property - def Vx_0(self): - """:math:`V_x^0` - x matrix coefficient at initial shooting node (0). - Default: :code:`None`. - """ - return self.__Vx_0 - - @property - def Vu_0(self): - """:math:`V_u^0` - u matrix coefficient at initial shooting node (0). - Default: :code:`None`. - """ - return self.__Vu_0 - - @property - def Vz_0(self): - """:math:`V_z^0` - z matrix coefficient at initial shooting node (0). - Default: :code:`None`. - """ - return self.__Vz_0 - - @property - def yref_0(self): - """:math:`y_\\text{ref}^0` - reference at initial shooting node (0). - Default: :code:`None`. - """ - return self.__yref_0 - - @property - def cost_ext_fun_type_0(self): - """Type of external function for cost at initial shooting node (0) - -- string in {casadi, generic} or :code:`None` - Default: :code:'casadi'. - - .. note:: Cost at initial stage is the same as for intermediate shooting nodes if not set differently explicitly. - """ - return self.__cost_ext_fun_type_0 - - @yref_0.setter - def yref_0(self, yref_0): - if isinstance(yref_0, np.ndarray) and len(yref_0.shape) == 1: - self.__yref_0 = yref_0 - else: - raise Exception('Invalid yref_0 value, expected 1-dimensional numpy array.') - - @W_0.setter - def W_0(self, W_0): - if isinstance(W_0, np.ndarray) and len(W_0.shape) == 2: - self.__W_0 = W_0 - else: - raise Exception('Invalid cost W_0 value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vx_0.setter - def Vx_0(self, Vx_0): - if isinstance(Vx_0, np.ndarray) and len(Vx_0.shape) == 2: - self.__Vx_0 = Vx_0 - else: - raise Exception('Invalid cost Vx_0 value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vu_0.setter - def Vu_0(self, Vu_0): - if isinstance(Vu_0, np.ndarray) and len(Vu_0.shape) == 2: - self.__Vu_0 = Vu_0 - else: - raise Exception('Invalid cost Vu_0 value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vz_0.setter - def Vz_0(self, Vz_0): - if isinstance(Vz_0, np.ndarray) and len(Vz_0.shape) == 2: - self.__Vz_0 = Vz_0 - else: - raise Exception('Invalid cost Vz_0 value. ' \ - + 'Should be 2 dimensional numpy array.') - - @cost_ext_fun_type_0.setter - def cost_ext_fun_type_0(self, cost_ext_fun_type_0): - if cost_ext_fun_type_0 in ['casadi', 'generic']: - self.__cost_ext_fun_type_0 = cost_ext_fun_type_0 - else: - raise Exception('Invalid cost_ext_fun_type_0 value, expected numpy array.') - - # Lagrange term - @property - def cost_type(self): - """ - Cost type at intermediate shooting nodes (1 to N-1) - -- string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR}. - Default: 'LINEAR_LS'. - """ - return self.__cost_type - - @property - def W(self): - """:math:`W` - weight matrix at intermediate shooting nodes (1 to N-1). - Default: :code:`np.zeros((0,0))`. - """ - return self.__W - - @property - def Vx(self): - """:math:`V_x` - x matrix coefficient at intermediate shooting nodes (1 to N-1). - Default: :code:`np.zeros((0,0))`. - """ - return self.__Vx - - @property - def Vu(self): - """:math:`V_u` - u matrix coefficient at intermediate shooting nodes (1 to N-1). - Default: :code:`np.zeros((0,0))`. - """ - return self.__Vu - - @property - def Vz(self): - """:math:`V_z` - z matrix coefficient at intermediate shooting nodes (1 to N-1). - Default: :code:`np.zeros((0,0))`. - """ - return self.__Vz - - @property - def yref(self): - """:math:`y_\\text{ref}` - reference at intermediate shooting nodes (1 to N-1). - Default: :code:`np.array([])`. - """ - return self.__yref - - @property - def Zl(self): - """:math:`Z_l` - diagonal of Hessian wrt lower slack at intermediate shooting nodes (0 to N-1). - Default: :code:`np.array([])`. - """ - return self.__Zl - - @property - def Zu(self): - """:math:`Z_u` - diagonal of Hessian wrt upper slack at intermediate shooting nodes (0 to N-1). - Default: :code:`np.array([])`. - """ - return self.__Zu - - @property - def zl(self): - """:math:`z_l` - gradient wrt lower slack at intermediate shooting nodes (0 to N-1). - Default: :code:`np.array([])`. - """ - return self.__zl - - @property - def zu(self): - """:math:`z_u` - gradient wrt upper slack at intermediate shooting nodes (0 to N-1). - Default: :code:`np.array([])`. - """ - return self.__zu - - @property - def cost_ext_fun_type(self): - """Type of external function for cost at intermediate shooting nodes (1 to N-1). - -- string in {casadi, generic} - Default: :code:'casadi'. - """ - return self.__cost_ext_fun_type - - @cost_type.setter - def cost_type(self, cost_type): - cost_types = ('LINEAR_LS', 'NONLINEAR_LS', 'EXTERNAL', 'CONVEX_OVER_NONLINEAR') - if cost_type in cost_types: - self.__cost_type = cost_type - else: - raise Exception('Invalid cost_type value.') - - @cost_type_0.setter - def cost_type_0(self, cost_type_0): - cost_types = ('LINEAR_LS', 'NONLINEAR_LS', 'EXTERNAL', 'CONVEX_OVER_NONLINEAR') - if cost_type_0 in cost_types: - self.__cost_type_0 = cost_type_0 - else: - raise Exception('Invalid cost_type_0 value.') - - @W.setter - def W(self, W): - if isinstance(W, np.ndarray) and len(W.shape) == 2: - self.__W = W - else: - raise Exception('Invalid cost W value. ' \ - + 'Should be 2 dimensional numpy array.') - - - @Vx.setter - def Vx(self, Vx): - if isinstance(Vx, np.ndarray) and len(Vx.shape) == 2: - self.__Vx = Vx - else: - raise Exception('Invalid cost Vx value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vu.setter - def Vu(self, Vu): - if isinstance(Vu, np.ndarray) and len(Vu.shape) == 2: - self.__Vu = Vu - else: - raise Exception('Invalid cost Vu value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vz.setter - def Vz(self, Vz): - if isinstance(Vz, np.ndarray) and len(Vz.shape) == 2: - self.__Vz = Vz - else: - raise Exception('Invalid cost Vz value. ' \ - + 'Should be 2 dimensional numpy array.') - - @yref.setter - def yref(self, yref): - if isinstance(yref, np.ndarray) and len(yref.shape) == 1: - self.__yref = yref - else: - raise Exception('Invalid yref value, expected 1-dimensional numpy array.') - - @Zl.setter - def Zl(self, Zl): - if isinstance(Zl, np.ndarray): - self.__Zl = Zl - else: - raise Exception('Invalid Zl value, expected numpy array.') - - @Zu.setter - def Zu(self, Zu): - if isinstance(Zu, np.ndarray): - self.__Zu = Zu - else: - raise Exception('Invalid Zu value, expected numpy array.') - - @zl.setter - def zl(self, zl): - if isinstance(zl, np.ndarray): - self.__zl = zl - else: - raise Exception('Invalid zl value, expected numpy array.') - - @zu.setter - def zu(self, zu): - if isinstance(zu, np.ndarray): - self.__zu = zu - else: - raise Exception('Invalid zu value, expected numpy array.') - - @cost_ext_fun_type.setter - def cost_ext_fun_type(self, cost_ext_fun_type): - if cost_ext_fun_type in ['casadi', 'generic']: - self.__cost_ext_fun_type = cost_ext_fun_type - else: - raise Exception("Invalid cost_ext_fun_type value, expected one in ['casadi', 'generic'].") - - # Mayer term - @property - def cost_type_e(self): - """ - Cost type at terminal shooting node (N) - -- string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR}. - Default: 'LINEAR_LS'. - """ - return self.__cost_type_e - - @property - def W_e(self): - """:math:`W_e` - weight matrix at terminal shooting node (N). - Default: :code:`np.zeros((0,0))`. - """ - return self.__W_e - - @property - def Vx_e(self): - """:math:`V_x^e` - x matrix coefficient for cost at terminal shooting node (N). - Default: :code:`np.zeros((0,0))`. - """ - return self.__Vx_e - - @property - def yref_e(self): - """:math:`y_\\text{ref}^e` - cost reference at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__yref_e - - @property - def Zl_e(self): - """:math:`Z_l^e` - diagonal of Hessian wrt lower slack at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__Zl_e - - @property - def Zu_e(self): - """:math:`Z_u^e` - diagonal of Hessian wrt upper slack at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__Zu_e - - @property - def zl_e(self): - """:math:`z_l^e` - gradient wrt lower slack at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__zl_e - - @property - def zu_e(self): - """:math:`z_u^e` - gradient wrt upper slack at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__zu_e - - @property - def cost_ext_fun_type_e(self): - """Type of external function for cost at terminal shooting node (N). - -- string in {casadi, generic} - Default: :code:'casadi'. - """ - return self.__cost_ext_fun_type_e - - @cost_type_e.setter - def cost_type_e(self, cost_type_e): - cost_types = ('LINEAR_LS', 'NONLINEAR_LS', 'EXTERNAL', 'CONVEX_OVER_NONLINEAR') - - if cost_type_e in cost_types: - self.__cost_type_e = cost_type_e - else: - raise Exception('Invalid cost_type_e value.') - - @W_e.setter - def W_e(self, W_e): - if isinstance(W_e, np.ndarray) and len(W_e.shape) == 2: - self.__W_e = W_e - else: - raise Exception('Invalid cost W_e value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vx_e.setter - def Vx_e(self, Vx_e): - if isinstance(Vx_e, np.ndarray) and len(Vx_e.shape) == 2: - self.__Vx_e = Vx_e - else: - raise Exception('Invalid cost Vx_e value. ' \ - + 'Should be 2 dimensional numpy array.') - - @yref_e.setter - def yref_e(self, yref_e): - if isinstance(yref_e, np.ndarray) and len(yref_e.shape) == 1: - self.__yref_e = yref_e - else: - raise Exception('Invalid yref_e value, expected 1-dimensional numpy array.') - - @Zl_e.setter - def Zl_e(self, Zl_e): - if isinstance(Zl_e, np.ndarray): - self.__Zl_e = Zl_e - else: - raise Exception('Invalid Zl_e value, expected numpy array.') - - @Zu_e.setter - def Zu_e(self, Zu_e): - if isinstance(Zu_e, np.ndarray): - self.__Zu_e = Zu_e - else: - raise Exception('Invalid Zu_e value, expected numpy array.') - - @zl_e.setter - def zl_e(self, zl_e): - if isinstance(zl_e, np.ndarray): - self.__zl_e = zl_e - else: - raise Exception('Invalid zl_e value, expected numpy array.') - - @zu_e.setter - def zu_e(self, zu_e): - if isinstance(zu_e, np.ndarray): - self.__zu_e = zu_e - else: - raise Exception('Invalid zu_e value, expected numpy array.') - - @cost_ext_fun_type_e.setter - def cost_ext_fun_type_e(self, cost_ext_fun_type_e): - if cost_ext_fun_type_e in ['casadi', 'generic']: - self.__cost_ext_fun_type_e = cost_ext_fun_type_e - else: - raise Exception("Invalid cost_ext_fun_type_e value, expected one in ['casadi', 'generic'].") - - def set(self, attr, value): - setattr(self, attr, value) - - -def print_J_to_idx_note(): - print("NOTE: J* matrix is converted to zero based vector idx* vector, which is returned here.") - - -class AcadosOcpConstraints: - """ - class containing the description of the constraints - """ - def __init__(self): - self.__constr_type = 'BGH' - self.__constr_type_e = 'BGH' - # initial x - self.__lbx_0 = np.array([]) - self.__ubx_0 = np.array([]) - self.__idxbx_0 = np.array([]) - self.__idxbxe_0 = np.array([]) - # state bounds - self.__lbx = np.array([]) - self.__ubx = np.array([]) - self.__idxbx = np.array([]) - # bounds on x at shooting node N - self.__lbx_e = np.array([]) - self.__ubx_e = np.array([]) - self.__idxbx_e = np.array([]) - # bounds on u - self.__lbu = np.array([]) - self.__ubu = np.array([]) - self.__idxbu = np.array([]) - # polytopic constraints - self.__lg = np.array([]) - self.__ug = np.array([]) - self.__D = np.zeros((0,0)) - self.__C = np.zeros((0,0)) - # polytopic constraints at shooting node N - self.__C_e = np.zeros((0,0)) - self.__lg_e = np.array([]) - self.__ug_e = np.array([]) - # nonlinear constraints - self.__lh = np.array([]) - self.__uh = np.array([]) - # nonlinear constraints at shooting node N - self.__uh_e = np.array([]) - self.__lh_e = np.array([]) - # convex-over-nonlinear constraints - self.__lphi = np.array([]) - self.__uphi = np.array([]) - # nonlinear constraints at shooting node N - self.__uphi_e = np.array([]) - self.__lphi_e = np.array([]) - # SLACK BOUNDS - # soft bounds on x - self.__lsbx = np.array([]) - self.__usbx = np.array([]) - self.__idxsbx = np.array([]) - # soft bounds on u - self.__lsbu = np.array([]) - self.__usbu = np.array([]) - self.__idxsbu = np.array([]) - # soft bounds on x at shooting node N - self.__lsbx_e = np.array([]) - self.__usbx_e = np.array([]) - self.__idxsbx_e= np.array([]) - # soft bounds on general linear constraints - self.__lsg = np.array([]) - self.__usg = np.array([]) - self.__idxsg = np.array([]) - # soft bounds on nonlinear constraints - self.__lsh = np.array([]) - self.__ush = np.array([]) - self.__idxsh = np.array([]) - # soft bounds on nonlinear constraints - self.__lsphi = np.array([]) - self.__usphi = np.array([]) - self.__idxsphi = np.array([]) - # soft bounds on general linear constraints at shooting node N - self.__lsg_e = np.array([]) - self.__usg_e = np.array([]) - self.__idxsg_e = np.array([]) - # soft bounds on nonlinear constraints at shooting node N - self.__lsh_e = np.array([]) - self.__ush_e = np.array([]) - self.__idxsh_e = np.array([]) - # soft bounds on nonlinear constraints at shooting node N - self.__lsphi_e = np.array([]) - self.__usphi_e = np.array([]) - self.__idxsphi_e = np.array([]) - - - # types - @property - def constr_type(self): - """Constraints type for shooting nodes (0 to N-1). string in {BGH, BGP}. - Default: BGH; BGP is for convex over nonlinear.""" - return self.__constr_type - - @property - def constr_type_e(self): - """Constraints type for terminal shooting node N. string in {BGH, BGP}. - Default: BGH; BGP is for convex over nonlinear.""" - return self.__constr_type_e - - # initial bounds on x - @property - def lbx_0(self): - """:math:`\\underline{x_0}` - lower bounds on x at initial stage 0. - Type: :code:`np.ndarray`; default: :code:`np.array([])`.""" - return self.__lbx_0 - - @property - def ubx_0(self): - """:math:`\\bar{x_0}` - upper bounds on x at initial stage 0. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__ubx_0 - - @property - def Jbx_0(self): - """:math:`J_{bx,0}` - matrix coefficient for bounds on x at initial stage 0. - Translated internally to :py:attr:`idxbx_0`""" - print_J_to_idx_note() - return self.__idxbx_0 - - @property - def idxbx_0(self): - """Indices of bounds on x at initial stage 0 - -- can be set automatically via x0. - Can be set by using :py:attr:`Jbx_0`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxbx_0 - - @property - def idxbxe_0(self): - """Indices of bounds on x0 that are equalities -- can be set automatically via :py:attr:`x0`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxbxe_0 - - # bounds on x - @property - def lbx(self): - """:math:`\\underline{x}` - lower bounds on x at intermediate shooting nodes (1 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__lbx - - @property - def ubx(self): - """:math:`\\bar{x}` - upper bounds on x at intermediate shooting nodes (1 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__ubx - - @property - def idxbx(self): - """indices of bounds on x (defines :math:`J_{bx}`) at intermediate shooting nodes (1 to N-1). - Can be set by using :py:attr:`Jbx`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxbx - - @property - def Jbx(self): - """:math:`J_{bx}` - matrix coefficient for bounds on x - at intermediate shooting nodes (1 to N-1). - Translated internally into :py:attr:`idxbx`.""" - print_J_to_idx_note() - return self.__idxbx - - # bounds on x at shooting node N - @property - def lbx_e(self): - """:math:`\\underline{x}^e` - lower bounds on x at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__lbx_e - - @property - def ubx_e(self): - """:math:`\\bar{x}^e` - upper bounds on x at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__ubx_e - - @property - def idxbx_e(self): - """Indices for bounds on x at terminal shooting node N (defines :math:`J_{bx}^e`). - Can be set by using :py:attr:`Jbx_e`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxbx_e - - @property - def Jbx_e(self): - """:math:`J_{bx}^e` matrix coefficient for bounds on x at terminal shooting node N. - Translated internally into :py:attr:`idxbx_e`.""" - print_J_to_idx_note() - return self.__idxbx_e - - # bounds on u - @property - def lbu(self): - """:math:`\\underline{u}` - lower bounds on u at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__lbu - - @property - def ubu(self): - """:math:`\\bar{u}` - upper bounds on u at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__ubu - - @property - def idxbu(self): - """Indices of bounds on u (defines :math:`J_{bu}`) at shooting nodes (0 to N-1). - Can be set by using :py:attr:`Jbu`. - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__idxbu - - @property - def Jbu(self): - """:math:`J_{bu}` - matrix coefficient for bounds on u at shooting nodes (0 to N-1). - Translated internally to :py:attr:`idxbu`. - """ - print_J_to_idx_note() - return self.__idxbu - - # polytopic constraints - @property - def C(self): - """:math:`C` - C matrix in :math:`\\underline{g} \\leq D \, u + C \, x \\leq \\bar{g}` - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array((0,0))`. - """ - return self.__C - - @property - def D(self): - """:math:`D` - D matrix in :math:`\\underline{g} \\leq D \, u + C \, x \\leq \\bar{g}` - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array((0,0))` - """ - return self.__D - - @property - def lg(self): - """:math:`\\underline{g}` - lower bound for general polytopic inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__lg - - @property - def ug(self): - """:math:`\\bar{g}` - upper bound for general polytopic inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__ug - - # polytopic constraints at shooting node N - @property - def C_e(self): - """:math:`C^e` - C matrix at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array((0,0))`. - """ - return self.__C_e - - @property - def lg_e(self): - """:math:`\\underline{g}^e` - lower bound on general polytopic inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lg_e - - @property - def ug_e(self): - """:math:`\\bar{g}^e` - upper bound on general polytopic inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__ug_e - - - # nonlinear constraints - @property - def lh(self): - """:math:`\\underline{h}` - lower bound for nonlinear inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lh - - @property - def uh(self): - """:math:`\\bar{h}` - upper bound for nonlinear inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__uh - - # nonlinear constraints at shooting node N - @property - def lh_e(self): - """:math:`\\underline{h}^e` - lower bound on nonlinear inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lh_e - - @property - def uh_e(self): - """:math:`\\bar{h}^e` - upper bound on nonlinear inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__uh_e - - # convex-over-nonlinear constraints - @property - def lphi(self): - """:math:`\\underline{\phi}` - lower bound for convex-over-nonlinear inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lphi - - @property - def uphi(self): - """:math:`\\bar{\phi}` - upper bound for convex-over-nonlinear inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__uphi - - # convex-over-nonlinear constraints at shooting node N - @property - def lphi_e(self): - """:math:`\\underline{\phi}^e` - lower bound on convex-over-nonlinear inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lphi_e - - @property - def uphi_e(self): - """:math:`\\bar{\phi}^e` - upper bound on convex-over-nonlinear inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__uphi_e - - - # SLACK bounds - # soft bounds on x - @property - def lsbx(self): - """Lower bounds on slacks corresponding to soft lower bounds on x - at stages (1 to N-1); - not required - zeros by default""" - return self.__lsbx - - @property - def usbx(self): - """Lower bounds on slacks corresponding to soft upper bounds on x - at stages (1 to N-1); - not required - zeros by default""" - return self.__usbx - - @property - def idxsbx(self): - """Indices of soft bounds on x within the indices of bounds on x - at stages (1 to N-1). - Can be set by using :py:attr:`Jsbx`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsbx - - @property - def Jsbx(self): - """:math:`J_{sbx}` - matrix coefficient for soft bounds on x - at stages (1 to N-1); - Translated internally into :py:attr:`idxsbx`.""" - print_J_to_idx_note() - return self.__idxsbx - - # soft bounds on u - @property - def lsbu(self): - """Lower bounds on slacks corresponding to soft lower bounds on u - at stages (0 to N-1). - Not required - zeros by default.""" - return self.__lsbu - - @property - def usbu(self): - """Lower bounds on slacks corresponding to soft upper bounds on u - at stages (0 to N-1); - not required - zeros by default""" - return self.__usbu - - @property - def idxsbu(self): - """Indices of soft bounds on u within the indices of bounds on u - at stages (0 to N-1). - Can be set by using :py:attr:`Jsbu`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsbu - - @property - def Jsbu(self): - """:math:`J_{sbu}` - matrix coefficient for soft bounds on u - at stages (0 to N-1); - internally translated into :py:attr:`idxsbu`""" - print_J_to_idx_note() - return self.__idxsbu - - # soft bounds on x at shooting node N - @property - def lsbx_e(self): - """Lower bounds on slacks corresponding to soft lower bounds on x at shooting node N. - Not required - zeros by default""" - return self.__lsbx_e - - @property - def usbx_e(self): - """Lower bounds on slacks corresponding to soft upper bounds on x at shooting node N. - Not required - zeros by default""" - return self.__usbx_e - - @property - def idxsbx_e(self): - """Indices of soft bounds on x at shooting node N, within the indices of bounds on x at terminal shooting node N. - Can be set by using :py:attr:`Jsbx_e`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsbx_e - - @property - def Jsbx_e(self): - """:math:`J_{sbx}^e` - matrix coefficient for soft bounds on x at terminal shooting node N. - Translated internally to :py:attr:`idxsbx_e`""" - print_J_to_idx_note() - return self.__idxsbx_e - - # soft general linear constraints - @property - def lsg(self): - """Lower bounds on slacks corresponding to soft lower bounds for general linear constraints - at stages (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__lsg - - @property - def usg(self): - """Lower bounds on slacks corresponding to soft upper bounds for general linear constraints. - Not required - zeros by default""" - return self.__usg - - @property - def idxsg(self): - """Indices of soft general linear constraints within the indices of general linear constraints. - Can be set by using :py:attr:`Jsg`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsg - - @property - def Jsg(self): - """:math:`J_{sg}` - matrix coefficient for soft bounds on general linear constraints. - Translated internally to :py:attr:`idxsg`""" - print_J_to_idx_note() - return self.__idxsg - - # soft nonlinear constraints - @property - def lsh(self): - """Lower bounds on slacks corresponding to soft lower bounds for nonlinear constraints. - Not required - zeros by default""" - return self.__lsh - - @property - def ush(self): - """Lower bounds on slacks corresponding to soft upper bounds for nonlinear constraints. - Not required - zeros by default""" - return self.__ush - - @property - def idxsh(self): - """Indices of soft nonlinear constraints within the indices of nonlinear constraints. - Can be set by using :py:attr:`Jbx`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsh - - @property - def Jsh(self): - """:math:`J_{sh}` - matrix coefficient for soft bounds on nonlinear constraints. - Translated internally to :py:attr:`idxsh`""" - print_J_to_idx_note() - return self.__idxsh - - # soft bounds on convex-over-nonlinear constraints - @property - def lsphi(self): - """Lower bounds on slacks corresponding to soft lower bounds for convex-over-nonlinear constraints. - Not required - zeros by default""" - return self.__lsphi - - @property - def usphi(self): - """Lower bounds on slacks corresponding to soft upper bounds for convex-over-nonlinear constraints. - Not required - zeros by default""" - return self.__usphi - - @property - def idxsphi(self): - """Indices of soft convex-over-nonlinear constraints within the indices of nonlinear constraints. - Can be set by using :py:attr:`Jsphi`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsphi - - @property - def Jsphi(self): - """:math:`J_{s, \phi}` - matrix coefficient for soft bounds on convex-over-nonlinear constraints. - Translated internally into :py:attr:`idxsphi`.""" - print_J_to_idx_note() - return self.__idxsphi - - - # soft bounds on general linear constraints at shooting node N - @property - def lsg_e(self): - """Lower bounds on slacks corresponding to soft lower bounds for general linear constraints at shooting node N. - Not required - zeros by default""" - return self.__lsg_e - - @property - def usg_e(self): - """Lower bounds on slacks corresponding to soft upper bounds for general linear constraints at shooting node N. - Not required - zeros by default""" - return self.__usg_e - - @property - def idxsg_e(self): - """Indices of soft general linear constraints at shooting node N within the indices of general linear constraints at shooting node N. - Can be set by using :py:attr:`Jsg_e`.""" - return self.__idxsg_e - - @property - def Jsg_e(self): - """:math:`J_{s,h}^e` - matrix coefficient for soft bounds on general linear constraints at terminal shooting node N. - Translated internally to :py:attr:`idxsg_e`""" - print_J_to_idx_note() - return self.__idxsg_e - - - # soft bounds on nonlinear constraints at shooting node N - @property - def lsh_e(self): - """Lower bounds on slacks corresponding to soft lower bounds for nonlinear constraints at terminal shooting node N. - Not required - zeros by default""" - return self.__lsh_e - - @property - def ush_e(self): - """Lower bounds on slacks corresponding to soft upper bounds for nonlinear constraints at terminal shooting node N. - Not required - zeros by default""" - return self.__ush_e - - @property - def idxsh_e(self): - """Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N. - Can be set by using :py:attr:`Jsh_e`.""" - return self.__idxsh_e - - @property - def Jsh_e(self): - """:math:`J_{s,h}^e` - matrix coefficient for soft bounds on nonlinear constraints at terminal shooting node N; fills :py:attr:`idxsh_e`""" - print_J_to_idx_note() - return self.__idxsh_e - - # soft bounds on convex-over-nonlinear constraints at shooting node N - @property - def lsphi_e(self): - """Lower bounds on slacks corresponding to soft lower bounds for convex-over-nonlinear constraints at terminal shooting node N. - Not required - zeros by default""" - return self.__lsphi_e - - @property - def usphi_e(self): - """Lower bounds on slacks corresponding to soft upper bounds for convex-over-nonlinear constraints at terminal shooting node N. - Not required - zeros by default""" - return self.__usphi_e - - @property - def idxsphi_e(self): - """Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N. - Can be set by using :py:attr:`Jsphi_e`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsphi_e - - @property - def Jsphi_e(self): - """:math:`J_{sh}^e` - matrix coefficient for soft bounds on convex-over-nonlinear constraints at shooting node N. - Translated internally to :py:attr:`idxsphi_e`""" - print_J_to_idx_note() - return self.__idxsphi_e - - @property - def x0(self): - """:math:`x_0 \\in \mathbb{R}^{n_x}` - initial state -- - Translated internally to :py:attr:`idxbx_0`, :py:attr:`lbx_0`, :py:attr:`ubx_0`, :py:attr:`idxbxe_0` """ - print("x0 is converted to lbx_0, ubx_0, idxbx_0") - print("idxbx_0: ", self.__idxbx_0) - print("lbx_0: ", self.__lbx_0) - print("ubx_0: ", self.__ubx_0) - print("idxbxe_0: ", self.__idxbxe_0) - return None - - # SETTERS - @constr_type.setter - def constr_type(self, constr_type): - constr_types = ('BGH', 'BGP') - if constr_type in constr_types: - self.__constr_type = constr_type - else: - raise Exception('Invalid constr_type value. Possible values are:\n\n' \ - + ',\n'.join(constr_types) + '.\n\nYou have: ' + constr_type + '.\n\n') - - @constr_type_e.setter - def constr_type_e(self, constr_type_e): - constr_types = ('BGH', 'BGP') - if constr_type_e in constr_types: - self.__constr_type_e = constr_type_e - else: - raise Exception('Invalid constr_type_e value. Possible values are:\n\n' \ - + ',\n'.join(constr_types) + '.\n\nYou have: ' + constr_type_e + '.\n\n') - - # initial x - @lbx_0.setter - def lbx_0(self, lbx_0): - if isinstance(lbx_0, np.ndarray): - self.__lbx_0 = lbx_0 - else: - raise Exception('Invalid lbx_0 value.') - - @ubx_0.setter - def ubx_0(self, ubx_0): - if isinstance(ubx_0, np.ndarray): - self.__ubx_0 = ubx_0 - else: - raise Exception('Invalid ubx_0 value.') - - @idxbx_0.setter - def idxbx_0(self, idxbx_0): - if isinstance(idxbx_0, np.ndarray): - self.__idxbx_0 = idxbx_0 - else: - raise Exception('Invalid idxbx_0 value.') - - @Jbx_0.setter - def Jbx_0(self, Jbx_0): - if isinstance(Jbx_0, np.ndarray): - self.__idxbx_0 = J_to_idx(Jbx_0) - else: - raise Exception('Invalid Jbx_0 value.') - - @idxbxe_0.setter - def idxbxe_0(self, idxbxe_0): - if isinstance(idxbxe_0, np.ndarray): - self.__idxbxe_0 = idxbxe_0 - else: - raise Exception('Invalid idxbxe_0 value.') - - - @x0.setter - def x0(self, x0): - if isinstance(x0, np.ndarray): - self.__lbx_0 = x0 - self.__ubx_0 = x0 - self.__idxbx_0 = np.arange(x0.size) - self.__idxbxe_0 = np.arange(x0.size) - else: - raise Exception('Invalid x0 value.') - - # bounds on x - @lbx.setter - def lbx(self, lbx): - if isinstance(lbx, np.ndarray): - self.__lbx = lbx - else: - raise Exception('Invalid lbx value.') - - @ubx.setter - def ubx(self, ubx): - if isinstance(ubx, np.ndarray): - self.__ubx = ubx - else: - raise Exception('Invalid ubx value.') - - @idxbx.setter - def idxbx(self, idxbx): - if isinstance(idxbx, np.ndarray): - self.__idxbx = idxbx - else: - raise Exception('Invalid idxbx value.') - - @Jbx.setter - def Jbx(self, Jbx): - if isinstance(Jbx, np.ndarray): - self.__idxbx = J_to_idx(Jbx) - else: - raise Exception('Invalid Jbx value.') - - # bounds on u - @lbu.setter - def lbu(self, lbu): - if isinstance(lbu, np.ndarray): - self.__lbu = lbu - else: - raise Exception('Invalid lbu value.') - - @ubu.setter - def ubu(self, ubu): - if isinstance(ubu, np.ndarray): - self.__ubu = ubu - else: - raise Exception('Invalid ubu value.') - - @idxbu.setter - def idxbu(self, idxbu): - if isinstance(idxbu, np.ndarray): - self.__idxbu = idxbu - else: - raise Exception('Invalid idxbu value.') - - @Jbu.setter - def Jbu(self, Jbu): - if isinstance(Jbu, np.ndarray): - self.__idxbu = J_to_idx(Jbu) - else: - raise Exception('Invalid Jbu value.') - - # bounds on x at shooting node N - @lbx_e.setter - def lbx_e(self, lbx_e): - if isinstance(lbx_e, np.ndarray): - self.__lbx_e = lbx_e - else: - raise Exception('Invalid lbx_e value.') - - @ubx_e.setter - def ubx_e(self, ubx_e): - if isinstance(ubx_e, np.ndarray): - self.__ubx_e = ubx_e - else: - raise Exception('Invalid ubx_e value.') - - @idxbx_e.setter - def idxbx_e(self, idxbx_e): - if isinstance(idxbx_e, np.ndarray): - self.__idxbx_e = idxbx_e - else: - raise Exception('Invalid idxbx_e value.') - - @Jbx_e.setter - def Jbx_e(self, Jbx_e): - if isinstance(Jbx_e, np.ndarray): - self.__idxbx_e = J_to_idx(Jbx_e) - else: - raise Exception('Invalid Jbx_e value.') - - # polytopic constraints - @D.setter - def D(self, D): - if isinstance(D, np.ndarray) and len(D.shape) == 2: - self.__D = D - else: - raise Exception('Invalid constraint D value.' \ - + 'Should be 2 dimensional numpy array.') - - @C.setter - def C(self, C): - if isinstance(C, np.ndarray) and len(C.shape) == 2: - self.__C = C - else: - raise Exception('Invalid constraint C value.' \ - + 'Should be 2 dimensional numpy array.') - - @lg.setter - def lg(self, lg): - if isinstance(lg, np.ndarray): - self.__lg = lg - else: - raise Exception('Invalid lg value.') - - @ug.setter - def ug(self, ug): - if isinstance(ug, np.ndarray): - self.__ug = ug - else: - raise Exception('Invalid ug value.') - - # polytopic constraints at shooting node N - @C_e.setter - def C_e(self, C_e): - if isinstance(C_e, np.ndarray) and len(C_e.shape) == 2: - self.__C_e = C_e - else: - raise Exception('Invalid constraint C_e value.' \ - + 'Should be 2 dimensional numpy array.') - - @lg_e.setter - def lg_e(self, lg_e): - if isinstance(lg_e, np.ndarray): - self.__lg_e = lg_e - else: - raise Exception('Invalid lg_e value.') - - @ug_e.setter - def ug_e(self, ug_e): - if isinstance(ug_e, np.ndarray): - self.__ug_e = ug_e - else: - raise Exception('Invalid ug_e value.') - - # nonlinear constraints - @lh.setter - def lh(self, lh): - if isinstance(lh, np.ndarray): - self.__lh = lh - else: - raise Exception('Invalid lh value.') - - @uh.setter - def uh(self, uh): - if isinstance(uh, np.ndarray): - self.__uh = uh - else: - raise Exception('Invalid uh value.') - - # convex-over-nonlinear constraints - @lphi.setter - def lphi(self, lphi): - if isinstance(lphi, np.ndarray): - self.__lphi = lphi - else: - raise Exception('Invalid lphi value.') - - @uphi.setter - def uphi(self, uphi): - if isinstance(uphi, np.ndarray): - self.__uphi = uphi - else: - raise Exception('Invalid uphi value.') - - # nonlinear constraints at shooting node N - @lh_e.setter - def lh_e(self, lh_e): - if isinstance(lh_e, np.ndarray): - self.__lh_e = lh_e - else: - raise Exception('Invalid lh_e value.') - - @uh_e.setter - def uh_e(self, uh_e): - if isinstance(uh_e, np.ndarray): - self.__uh_e = uh_e - else: - raise Exception('Invalid uh_e value.') - - # convex-over-nonlinear constraints at shooting node N - @lphi_e.setter - def lphi_e(self, lphi_e): - if isinstance(lphi_e, np.ndarray): - self.__lphi_e = lphi_e - else: - raise Exception('Invalid lphi_e value.') - - @uphi_e.setter - def uphi_e(self, uphi_e): - if isinstance(uphi_e, np.ndarray): - self.__uphi_e = uphi_e - else: - raise Exception('Invalid uphi_e value.') - - # SLACK bounds - # soft bounds on x - @lsbx.setter - def lsbx(self, lsbx): - if isinstance(lsbx, np.ndarray): - self.__lsbx = lsbx - else: - raise Exception('Invalid lsbx value.') - - @usbx.setter - def usbx(self, usbx): - if isinstance(usbx, np.ndarray): - self.__usbx = usbx - else: - raise Exception('Invalid usbx value.') - - @idxsbx.setter - def idxsbx(self, idxsbx): - if isinstance(idxsbx, np.ndarray): - self.__idxsbx = idxsbx - else: - raise Exception('Invalid idxsbx value.') - - @Jsbx.setter - def Jsbx(self, Jsbx): - if isinstance(Jsbx, np.ndarray): - self.__idxsbx = J_to_idx_slack(Jsbx) - else: - raise Exception('Invalid Jsbx value, expected numpy array.') - - # soft bounds on u - @lsbu.setter - def lsbu(self, lsbu): - if isinstance(lsbu, np.ndarray): - self.__lsbu = lsbu - else: - raise Exception('Invalid lsbu value.') - - @usbu.setter - def usbu(self, usbu): - if isinstance(usbu, np.ndarray): - self.__usbu = usbu - else: - raise Exception('Invalid usbu value.') - - @idxsbu.setter - def idxsbu(self, idxsbu): - if isinstance(idxsbu, np.ndarray): - self.__idxsbu = idxsbu - else: - raise Exception('Invalid idxsbu value.') - - @Jsbu.setter - def Jsbu(self, Jsbu): - if isinstance(Jsbu, np.ndarray): - self.__idxsbu = J_to_idx_slack(Jsbu) - else: - raise Exception('Invalid Jsbu value.') - - # soft bounds on x at shooting node N - @lsbx_e.setter - def lsbx_e(self, lsbx_e): - if isinstance(lsbx_e, np.ndarray): - self.__lsbx_e = lsbx_e - else: - raise Exception('Invalid lsbx_e value.') - - @usbx_e.setter - def usbx_e(self, usbx_e): - if isinstance(usbx_e, np.ndarray): - self.__usbx_e = usbx_e - else: - raise Exception('Invalid usbx_e value.') - - @idxsbx_e.setter - def idxsbx_e(self, idxsbx_e): - if isinstance(idxsbx_e, np.ndarray): - self.__idxsbx_e = idxsbx_e - else: - raise Exception('Invalid idxsbx_e value.') - - @Jsbx_e.setter - def Jsbx_e(self, Jsbx_e): - if isinstance(Jsbx_e, np.ndarray): - self.__idxsbx_e = J_to_idx_slack(Jsbx_e) - else: - raise Exception('Invalid Jsbx_e value.') - - - # soft bounds on general linear constraints - @lsg.setter - def lsg(self, lsg): - if isinstance(lsg, np.ndarray): - self.__lsg = lsg - else: - raise Exception('Invalid lsg value.') - - @usg.setter - def usg(self, usg): - if isinstance(usg, np.ndarray): - self.__usg = usg - else: - raise Exception('Invalid usg value.') - - @idxsg.setter - def idxsg(self, idxsg): - if isinstance(idxsg, np.ndarray): - self.__idxsg = idxsg - else: - raise Exception('Invalid idxsg value.') - - @Jsg.setter - def Jsg(self, Jsg): - if isinstance(Jsg, np.ndarray): - self.__idxsg = J_to_idx_slack(Jsg) - else: - raise Exception('Invalid Jsg value, expected numpy array.') - - - # soft bounds on nonlinear constraints - @lsh.setter - def lsh(self, lsh): - if isinstance(lsh, np.ndarray): - self.__lsh = lsh - else: - raise Exception('Invalid lsh value.') - - @ush.setter - def ush(self, ush): - if isinstance(ush, np.ndarray): - self.__ush = ush - else: - raise Exception('Invalid ush value.') - - @idxsh.setter - def idxsh(self, idxsh): - if isinstance(idxsh, np.ndarray): - self.__idxsh = idxsh - else: - raise Exception('Invalid idxsh value.') - - - @Jsh.setter - def Jsh(self, Jsh): - if isinstance(Jsh, np.ndarray): - self.__idxsh = J_to_idx_slack(Jsh) - else: - raise Exception('Invalid Jsh value, expected numpy array.') - - # soft bounds on convex-over-nonlinear constraints - @lsphi.setter - def lsphi(self, lsphi): - if isinstance(lsphi, np.ndarray): - self.__lsphi = lsphi - else: - raise Exception('Invalid lsphi value.') - - @usphi.setter - def usphi(self, usphi): - if isinstance(usphi, np.ndarray): - self.__usphi = usphi - else: - raise Exception('Invalid usphi value.') - - @idxsphi.setter - def idxsphi(self, idxsphi): - if isinstance(idxsphi, np.ndarray): - self.__idxsphi = idxsphi - else: - raise Exception('Invalid idxsphi value.') - - @Jsphi.setter - def Jsphi(self, Jsphi): - if isinstance(Jsphi, np.ndarray): - self.__idxsphi = J_to_idx_slack(Jsphi) - else: - raise Exception('Invalid Jsphi value, expected numpy array.') - - # soft bounds on general linear constraints at shooting node N - @lsg_e.setter - def lsg_e(self, lsg_e): - if isinstance(lsg_e, np.ndarray): - self.__lsg_e = lsg_e - else: - raise Exception('Invalid lsg_e value.') - - @usg_e.setter - def usg_e(self, usg_e): - if isinstance(usg_e, np.ndarray): - self.__usg_e = usg_e - else: - raise Exception('Invalid usg_e value.') - - @idxsg_e.setter - def idxsg_e(self, idxsg_e): - if isinstance(idxsg_e, np.ndarray): - self.__idxsg_e = idxsg_e - else: - raise Exception('Invalid idxsg_e value.') - - @Jsg_e.setter - def Jsg_e(self, Jsg_e): - if isinstance(Jsg_e, np.ndarray): - self.__idxsg_e = J_to_idx_slack(Jsg_e) - else: - raise Exception('Invalid Jsg_e value, expected numpy array.') - - # soft bounds on nonlinear constraints at shooting node N - @lsh_e.setter - def lsh_e(self, lsh_e): - if isinstance(lsh_e, np.ndarray): - self.__lsh_e = lsh_e - else: - raise Exception('Invalid lsh_e value.') - - @ush_e.setter - def ush_e(self, ush_e): - if isinstance(ush_e, np.ndarray): - self.__ush_e = ush_e - else: - raise Exception('Invalid ush_e value.') - - @idxsh_e.setter - def idxsh_e(self, idxsh_e): - if isinstance(idxsh_e, np.ndarray): - self.__idxsh_e = idxsh_e - else: - raise Exception('Invalid idxsh_e value.') - - @Jsh_e.setter - def Jsh_e(self, Jsh_e): - if isinstance(Jsh_e, np.ndarray): - self.__idxsh_e = J_to_idx_slack(Jsh_e) - else: - raise Exception('Invalid Jsh_e value, expected numpy array.') - - - # soft bounds on convex-over-nonlinear constraints at shooting node N - @lsphi_e.setter - def lsphi_e(self, lsphi_e): - if isinstance(lsphi_e, np.ndarray): - self.__lsphi_e = lsphi_e - else: - raise Exception('Invalid lsphi_e value.') - - @usphi_e.setter - def usphi_e(self, usphi_e): - if isinstance(usphi_e, np.ndarray): - self.__usphi_e = usphi_e - else: - raise Exception('Invalid usphi_e value.') - - @idxsphi_e.setter - def idxsphi_e(self, idxsphi_e): - if isinstance(idxsphi_e, np.ndarray): - self.__idxsphi_e = idxsphi_e - else: - raise Exception('Invalid idxsphi_e value.') - - @Jsphi_e.setter - def Jsphi_e(self, Jsphi_e): - if isinstance(Jsphi_e, np.ndarray): - self.__idxsphi_e = J_to_idx_slack(Jsphi_e) - else: - raise Exception('Invalid Jsphi_e value.') - - def set(self, attr, value): - setattr(self, attr, value) - - -class AcadosOcpOptions: - """ - class containing the description of the solver options - """ - def __init__(self): - self.__qp_solver = 'PARTIAL_CONDENSING_HPIPM' # qp solver to be used in the NLP solver - self.__hessian_approx = 'GAUSS_NEWTON' # hessian approximation - self.__integrator_type = 'ERK' # integrator type - self.__tf = None # prediction horizon - self.__nlp_solver_type = 'SQP_RTI' # NLP solver - self.__globalization = 'FIXED_STEP' - self.__nlp_solver_step_length = 1.0 # fixed Newton step length - self.__levenberg_marquardt = 0.0 - self.__collocation_type = 'GAUSS_LEGENDRE' - self.__sim_method_num_stages = 4 # number of stages in the integrator - self.__sim_method_num_steps = 1 # number of steps in the integrator - self.__sim_method_newton_iter = 3 # number of Newton iterations in simulation method - self.__sim_method_newton_tol = 0.0 - self.__sim_method_jac_reuse = 0 - self.__qp_solver_tol_stat = None # QP solver stationarity tolerance - self.__qp_solver_tol_eq = None # QP solver equality tolerance - self.__qp_solver_tol_ineq = None # QP solver inequality - self.__qp_solver_tol_comp = None # QP solver complementarity - self.__qp_solver_iter_max = 50 # QP solver max iter - self.__qp_solver_cond_N = None # QP solver: new horizon after partial condensing - self.__qp_solver_warm_start = 0 - self.__qp_solver_cond_ric_alg = 1 - self.__qp_solver_ric_alg = 1 - self.__nlp_solver_tol_stat = 1e-6 # NLP solver stationarity tolerance - self.__nlp_solver_tol_eq = 1e-6 # NLP solver equality tolerance - self.__nlp_solver_tol_ineq = 1e-6 # NLP solver inequality - self.__nlp_solver_tol_comp = 1e-6 # NLP solver complementarity - self.__nlp_solver_max_iter = 100 # NLP solver maximum number of iterations - self.__nlp_solver_ext_qp_res = 0 - self.__Tsim = None # automatically calculated as tf/N - self.__print_level = 0 # print level - self.__initialize_t_slacks = 0 # possible values: 0, 1 - self.__regularize_method = None - self.__time_steps = None - self.__shooting_nodes = None - self.__exact_hess_cost = 1 - self.__exact_hess_dyn = 1 - self.__exact_hess_constr = 1 - self.__ext_cost_num_hess = 0 - self.__alpha_min = 0.05 - self.__alpha_reduction = 0.7 - self.__line_search_use_sufficient_descent = 0 - self.__globalization_use_SOC = 0 - self.__full_step_dual = 0 - self.__eps_sufficient_descent = 1e-4 - self.__hpipm_mode = 'BALANCE' - # TODO: move those out? they are more about generation than about the acados OCP solver. - self.__ext_fun_compile_flags = '-O2' - self.__model_external_shared_lib_dir = None # path to the the .so lib - self.__model_external_shared_lib_name = None # name of the the .so lib - self.__custom_update_filename = '' - self.__custom_update_header_filename = '' - self.__custom_templates = [] - self.__custom_update_copy = True - - @property - def qp_solver(self): - """QP solver to be used in the NLP solver. - String in ('PARTIAL_CONDENSING_HPIPM', 'FULL_CONDENSING_QPOASES', 'FULL_CONDENSING_HPIPM', 'PARTIAL_CONDENSING_QPDUNES', 'PARTIAL_CONDENSING_OSQP', 'FULL_CONDENSING_DAQP'). - Default: 'PARTIAL_CONDENSING_HPIPM'. - """ - return self.__qp_solver - - @property - def ext_fun_compile_flags(self): - """ - String with compiler flags for external function compilation. - Default: '-O2'. - """ - return self.__ext_fun_compile_flags - - - @property - def custom_update_filename(self): - """ - Filename of the custom C function to update solver data and parameters in between solver calls - - This file has to implement the functions - int custom_update_init_function([model.name]_solver_capsule* capsule); - int custom_update_function([model.name]_solver_capsule* capsule); - int custom_update_terminate_function([model.name]_solver_capsule* capsule); - - - Default: ''. - """ - return self.__custom_update_filename - - - @property - def custom_templates(self): - """ - List of tuples of the form: - (input_filename, output_filename) - - Custom templates are render in OCP solver generation. - - Default: []. - """ - return self.__custom_templates - - - @property - def custom_update_header_filename(self): - """ - Header filename of the custom C function to update solver data and parameters in between solver calls - - This file has to declare the custom_update functions and look as follows: - - ``` - // Called at the end of solver creation. - // This is allowed to allocate memory and store the pointer to it into capsule->custom_update_memory. - int custom_update_init_function([model.name]_solver_capsule* capsule); - - // Custom update function that can be called between solver calls - int custom_update_function([model.name]_solver_capsule* capsule, double* data, int data_len); - - // Called just before destroying the solver. - // Responsible to free allocated memory, stored at capsule->custom_update_memory. - int custom_update_terminate_function([model.name]_solver_capsule* capsule); - - Default: ''. - """ - return self.__custom_update_header_filename - - @property - def custom_update_copy(self): - """ - Boolean; - If True, the custom update function files are copied into the `code_export_directory`. - """ - return self.__custom_update_copy - - - @property - def hpipm_mode(self): - """ - Mode of HPIPM to be used, - - String in ('BALANCE', 'SPEED_ABS', 'SPEED', 'ROBUST'). - - Default: 'BALANCE'. - - see https://cdn.syscop.de/publications/Frison2020a.pdf - and the HPIPM code: - https://github.com/giaf/hpipm/blob/master/ocp_qp/x_ocp_qp_ipm.c#L69 - """ - return self.__hpipm_mode - - @property - def hessian_approx(self): - """Hessian approximation. - String in ('GAUSS_NEWTON', 'EXACT'). - Default: 'GAUSS_NEWTON'. - """ - return self.__hessian_approx - - @property - def integrator_type(self): - """ - Integrator type. - String in ('ERK', 'IRK', 'GNSF', 'DISCRETE', 'LIFTED_IRK'). - Default: 'ERK'. - """ - return self.__integrator_type - - @property - def nlp_solver_type(self): - """NLP solver. - String in ('SQP', 'SQP_RTI'). - Default: 'SQP_RTI'. - """ - return self.__nlp_solver_type - - @property - def globalization(self): - """Globalization type. - String in ('FIXED_STEP', 'MERIT_BACKTRACKING'). - Default: 'FIXED_STEP'. - - .. note:: preliminary implementation. - """ - return self.__globalization - - @property - def collocation_type(self): - """Collocation type: relevant for implicit integrators - -- string in {GAUSS_RADAU_IIA, GAUSS_LEGENDRE}. - - Default: GAUSS_LEGENDRE - """ - return self.__collocation_type - - @property - def regularize_method(self): - """Regularization method for the Hessian. - String in ('NO_REGULARIZE', 'MIRROR', 'PROJECT', 'PROJECT_REDUC_HESS', 'CONVEXIFY') or :code:`None`. - - - MIRROR: performs eigenvalue decomposition H = V^T D V and sets D_ii = max(eps, abs(D_ii)) - - PROJECT: performs eigenvalue decomposition H = V^T D V and sets D_ii = max(eps, D_ii) - - CONVEXIFY: Algorithm 6 from Verschueren2017, https://cdn.syscop.de/publications/Verschueren2017.pdf - - PROJECT_REDUC_HESS: experimental - - Note: default eps = 1e-4 - - Default: :code:`None`. - """ - return self.__regularize_method - - @property - def nlp_solver_step_length(self): - """ - Fixed Newton step length. - Type: float > 0. - Default: 1.0. - """ - return self.__nlp_solver_step_length - - @property - def levenberg_marquardt(self): - """ - Factor for LM regularization. - Type: float >= 0 - Default: 0.0. - """ - return self.__levenberg_marquardt - - @property - def sim_method_num_stages(self): - """ - Number of stages in the integrator. - Type: int > 0 or ndarray of ints > 0 of shape (N,). - Default: 4 - """ - return self.__sim_method_num_stages - - @property - def sim_method_num_steps(self): - """ - Number of steps in the integrator. - Type: int > 0 or ndarray of ints > 0 of shape (N,). - Default: 1 - """ - return self.__sim_method_num_steps - - @property - def sim_method_newton_iter(self): - """ - Number of Newton iterations in simulation method. - Type: int > 0 - Default: 3 - """ - return self.__sim_method_newton_iter - - @property - def sim_method_newton_tol(self): - """ - Tolerance of Newton system in simulation method. - Type: float: 0.0 means not used - Default: 0.0 - """ - return self.__sim_method_newton_tol - - @property - def sim_method_jac_reuse(self): - """ - Integer determining if jacobians are reused within integrator or ndarray of ints > 0 of shape (N,). - 0: False (no reuse); 1: True (reuse) - Default: 0 - """ - return self.__sim_method_jac_reuse - - @property - def qp_solver_tol_stat(self): - """ - QP solver stationarity tolerance. - Default: :code:`None` - """ - return self.__qp_solver_tol_stat - - @property - def qp_solver_tol_eq(self): - """ - QP solver equality tolerance. - Default: :code:`None` - """ - return self.__qp_solver_tol_eq - - @property - def qp_solver_tol_ineq(self): - """ - QP solver inequality. - Default: :code:`None` - """ - return self.__qp_solver_tol_ineq - - @property - def qp_solver_tol_comp(self): - """ - QP solver complementarity. - Default: :code:`None` - """ - return self.__qp_solver_tol_comp - - @property - def qp_solver_cond_N(self): - """QP solver: New horizon after partial condensing. - Set to N by default -> no condensing.""" - return self.__qp_solver_cond_N - - @property - def qp_solver_warm_start(self): - """ - QP solver: Warm starting. - 0: no warm start; 1: warm start; 2: hot start. - Default: 0 - """ - return self.__qp_solver_warm_start - - @property - def qp_solver_cond_ric_alg(self): - """ - QP solver: Determines which algorithm is used in HPIPM condensing. - 0: dont factorize hessian in the condensing; 1: factorize. - Default: 1 - """ - return self.__qp_solver_cond_ric_alg - - @property - def qp_solver_ric_alg(self): - """ - QP solver: Determines which algorithm is used in HPIPM OCP QP solver. - 0 classical Riccati, 1 square-root Riccati. - - Note: taken from [HPIPM paper]: - - (a) the classical implementation requires the reduced Hessian with respect to the dynamics - equality constraints to be positive definite, but allows the full-space Hessian to be indefinite) - (b) the square-root implementation, which in order to reduce the flop count employs the Cholesky - factorization of the Riccati recursion matrix, and therefore requires the full-space Hessian to be positive definite - - [HPIPM paper]: HPIPM: a high-performance quadratic programming framework for model predictive control, Frison and Diehl, 2020 - https://cdn.syscop.de/publications/Frison2020a.pdf - - Default: 1 - """ - return self.__qp_solver_ric_alg - - @property - def qp_solver_iter_max(self): - """ - QP solver: maximum number of iterations. - Type: int > 0 - Default: 50 - """ - return self.__qp_solver_iter_max - - @property - def tol(self): - """ - NLP solver tolerance. Sets or gets the max of :py:attr:`nlp_solver_tol_eq`, - :py:attr:`nlp_solver_tol_ineq`, :py:attr:`nlp_solver_tol_comp` - and :py:attr:`nlp_solver_tol_stat`. - """ - return max([self.__nlp_solver_tol_eq, self.__nlp_solver_tol_ineq,\ - self.__nlp_solver_tol_comp, self.__nlp_solver_tol_stat]) - - @property - def qp_tol(self): - """ - QP solver tolerance. - Sets all of the following at once or gets the max of - :py:attr:`qp_solver_tol_eq`, :py:attr:`qp_solver_tol_ineq`, - :py:attr:`qp_solver_tol_comp` and - :py:attr:`qp_solver_tol_stat`. - """ - return max([self.__qp_solver_tol_eq, self.__qp_solver_tol_ineq,\ - self.__qp_solver_tol_comp, self.__qp_solver_tol_stat]) - - @property - def nlp_solver_tol_stat(self): - """ - NLP solver stationarity tolerance. - Type: float > 0 - Default: 1e-6 - """ - return self.__nlp_solver_tol_stat - - @property - def nlp_solver_tol_eq(self): - """NLP solver equality tolerance""" - return self.__nlp_solver_tol_eq - - @property - def alpha_min(self): - """Minimal step size for globalization MERIT_BACKTRACKING, default: 0.05.""" - return self.__alpha_min - - @property - def alpha_reduction(self): - """Step size reduction factor for globalization MERIT_BACKTRACKING, default: 0.7.""" - return self.__alpha_reduction - - @property - def line_search_use_sufficient_descent(self): - """ - Determines if sufficient descent (Armijo) condition is used in line search. - Type: int; 0 or 1; - default: 0. - """ - return self.__line_search_use_sufficient_descent - - @property - def eps_sufficient_descent(self): - """ - Factor for sufficient descent (Armijo) conditon, see line_search_use_sufficient_descent. - Type: float, - default: 1e-4. - """ - return self.__eps_sufficient_descent - - @property - def globalization_use_SOC(self): - """ - Determines if second order correction (SOC) is done when using MERIT_BACKTRACKING. - SOC is done if preliminary line search does not return full step. - Type: int; 0 or 1; - default: 0. - """ - return self.__globalization_use_SOC - - @property - def full_step_dual(self): - """ - Determines if dual variables are updated with full steps (alpha=1.0) when primal variables are updated with smaller step. - Type: int; 0 or 1; - default: 0. - """ - return self.__full_step_dual - - @property - def nlp_solver_tol_ineq(self): - """NLP solver inequality tolerance""" - return self.__nlp_solver_tol_ineq - - @property - def nlp_solver_ext_qp_res(self): - """Determines if residuals of QP are computed externally within NLP solver (for debugging) - - Type: int; 0 or 1; - Default: 0. - """ - return self.__nlp_solver_ext_qp_res - - @property - def nlp_solver_tol_comp(self): - """NLP solver complementarity tolerance""" - return self.__nlp_solver_tol_comp - - @property - def nlp_solver_max_iter(self): - """ - NLP solver maximum number of iterations. - Type: int > 0 - Default: 100 - """ - return self.__nlp_solver_max_iter - - @property - def time_steps(self): - """ - Vector with time steps between the shooting nodes. Set automatically to uniform discretization if :py:attr:`N` and :py:attr:`tf` are provided. - Default: :code:`None` - """ - return self.__time_steps - - @property - def shooting_nodes(self): - """ - Vector with the shooting nodes, time_steps will be computed from it automatically. - Default: :code:`None` - """ - return self.__shooting_nodes - - @property - def tf(self): - """ - Prediction horizon - Type: float > 0 - Default: :code:`None` - """ - return self.__tf - - @property - def Tsim(self): - """ - Time horizon for one integrator step. Automatically calculated as :py:attr:`tf`/:py:attr:`N`. - Default: :code:`None` - """ - return self.__Tsim - - @property - def print_level(self): - """ - Verbosity of printing. - Type: int >= 0 - Default: 0 - """ - return self.__print_level - - @property - def model_external_shared_lib_dir(self): - """Path to the .so lib""" - return self.__model_external_shared_lib_dir - - @property - def model_external_shared_lib_name(self): - """Name of the .so lib""" - return self.__model_external_shared_lib_name - - @property - def exact_hess_constr(self): - """ - Used in case of hessian_approx == 'EXACT'.\n - Can be used to turn off exact hessian contributions from the constraints module. - """ - return self.__exact_hess_constr - - @property - def exact_hess_cost(self): - """ - Used in case of hessian_approx == 'EXACT'.\n - Can be used to turn off exact hessian contributions from the cost module. - """ - return self.__exact_hess_cost - - @property - def exact_hess_dyn(self): - """ - Used in case of hessian_approx == 'EXACT'.\n - Can be used to turn off exact hessian contributions from the dynamics module. - """ - return self.__exact_hess_dyn - - @property - def ext_cost_num_hess(self): - """ - Determines if custom hessian approximation for cost contribution is used (> 0).\n - Or if hessian contribution is evaluated exactly using CasADi external function (=0 - default). - """ - return self.__ext_cost_num_hess - - @qp_solver.setter - def qp_solver(self, qp_solver): - qp_solvers = ('PARTIAL_CONDENSING_HPIPM', \ - 'FULL_CONDENSING_QPOASES', 'FULL_CONDENSING_HPIPM', \ - 'PARTIAL_CONDENSING_QPDUNES', 'PARTIAL_CONDENSING_OSQP', \ - 'FULL_CONDENSING_DAQP') - if qp_solver in qp_solvers: - self.__qp_solver = qp_solver - else: - raise Exception('Invalid qp_solver value. Possible values are:\n\n' \ - + ',\n'.join(qp_solvers) + '.\n\nYou have: ' + qp_solver + '.\n\n') - - @regularize_method.setter - def regularize_method(self, regularize_method): - regularize_methods = ('NO_REGULARIZE', 'MIRROR', 'PROJECT', \ - 'PROJECT_REDUC_HESS', 'CONVEXIFY') - if regularize_method in regularize_methods: - self.__regularize_method = regularize_method - else: - raise Exception('Invalid regularize_method value. Possible values are:\n\n' \ - + ',\n'.join(regularize_methods) + '.\n\nYou have: ' + regularize_method + '.\n\n') - - @collocation_type.setter - def collocation_type(self, collocation_type): - collocation_types = ('GAUSS_RADAU_IIA', 'GAUSS_LEGENDRE') - if collocation_type in collocation_types: - self.__collocation_type = collocation_type - else: - raise Exception('Invalid collocation_type value. Possible values are:\n\n' \ - + ',\n'.join(collocation_types) + '.\n\nYou have: ' + collocation_type + '.\n\n') - - @hpipm_mode.setter - def hpipm_mode(self, hpipm_mode): - hpipm_modes = ('BALANCE', 'SPEED_ABS', 'SPEED', 'ROBUST') - if hpipm_mode in hpipm_modes: - self.__hpipm_mode = hpipm_mode - else: - raise Exception('Invalid hpipm_mode value. Possible values are:\n\n' \ - + ',\n'.join(hpipm_modes) + '.\n\nYou have: ' + hpipm_mode + '.\n\n') - - @ext_fun_compile_flags.setter - def ext_fun_compile_flags(self, ext_fun_compile_flags): - if isinstance(ext_fun_compile_flags, str): - self.__ext_fun_compile_flags = ext_fun_compile_flags - else: - raise Exception('Invalid ext_fun_compile_flags, expected a string.\n') - - - @custom_update_filename.setter - def custom_update_filename(self, custom_update_filename): - if isinstance(custom_update_filename, str): - self.__custom_update_filename = custom_update_filename - else: - raise Exception('Invalid custom_update_filename, expected a string.\n') - - @custom_templates.setter - def custom_templates(self, custom_templates): - if not isinstance(custom_templates, list): - raise Exception('Invalid custom_templates, expected a list.\n') - for tup in custom_templates: - if not isinstance(tup, tuple): - raise Exception('Invalid custom_templates, shoubld be list of tuples.\n') - for s in tup: - if not isinstance(s, str): - raise Exception('Invalid custom_templates, shoubld be list of tuples of strings.\n') - self.__custom_templates = custom_templates - - @custom_update_header_filename.setter - def custom_update_header_filename(self, custom_update_header_filename): - if isinstance(custom_update_header_filename, str): - self.__custom_update_header_filename = custom_update_header_filename - else: - raise Exception('Invalid custom_update_header_filename, expected a string.\n') - - @custom_update_copy.setter - def custom_update_copy(self, custom_update_copy): - if isinstance(custom_update_copy, bool): - self.__custom_update_copy = custom_update_copy - else: - raise Exception('Invalid custom_update_copy, expected a bool.\n') - - @hessian_approx.setter - def hessian_approx(self, hessian_approx): - hessian_approxs = ('GAUSS_NEWTON', 'EXACT') - if hessian_approx in hessian_approxs: - self.__hessian_approx = hessian_approx - else: - raise Exception('Invalid hessian_approx value. Possible values are:\n\n' \ - + ',\n'.join(hessian_approxs) + '.\n\nYou have: ' + hessian_approx + '.\n\n') - - @integrator_type.setter - def integrator_type(self, integrator_type): - integrator_types = ('ERK', 'IRK', 'GNSF', 'DISCRETE', 'LIFTED_IRK') - if integrator_type in integrator_types: - self.__integrator_type = integrator_type - else: - raise Exception('Invalid integrator_type value. Possible values are:\n\n' \ - + ',\n'.join(integrator_types) + '.\n\nYou have: ' + integrator_type + '.\n\n') - - @tf.setter - def tf(self, tf): - self.__tf = tf - - @time_steps.setter - def time_steps(self, time_steps): - if isinstance(time_steps, np.ndarray): - if len(time_steps.shape) == 1: - self.__time_steps = time_steps - else: - raise Exception('Invalid time_steps, expected np.ndarray of shape (N,).') - else: - raise Exception('Invalid time_steps, expected np.ndarray.') - - @shooting_nodes.setter - def shooting_nodes(self, shooting_nodes): - if isinstance(shooting_nodes, np.ndarray): - if len(shooting_nodes.shape) == 1: - self.__shooting_nodes = shooting_nodes - else: - raise Exception('Invalid shooting_nodes, expected np.ndarray of shape (N+1,).') - else: - raise Exception('Invalid shooting_nodes, expected np.ndarray.') - - @Tsim.setter - def Tsim(self, Tsim): - self.__Tsim = Tsim - - @globalization.setter - def globalization(self, globalization): - globalization_types = ('MERIT_BACKTRACKING', 'FIXED_STEP') - if globalization in globalization_types: - self.__globalization = globalization - else: - raise Exception('Invalid globalization value. Possible values are:\n\n' \ - + ',\n'.join(globalization_types) + '.\n\nYou have: ' + globalization + '.\n\n') - - @alpha_min.setter - def alpha_min(self, alpha_min): - self.__alpha_min = alpha_min - - @alpha_reduction.setter - def alpha_reduction(self, alpha_reduction): - self.__alpha_reduction = alpha_reduction - - @line_search_use_sufficient_descent.setter - def line_search_use_sufficient_descent(self, line_search_use_sufficient_descent): - if line_search_use_sufficient_descent in [0, 1]: - self.__line_search_use_sufficient_descent = line_search_use_sufficient_descent - else: - raise Exception(f'Invalid value for line_search_use_sufficient_descent. Possible values are 0, 1, got {line_search_use_sufficient_descent}') - - @globalization_use_SOC.setter - def globalization_use_SOC(self, globalization_use_SOC): - if globalization_use_SOC in [0, 1]: - self.__globalization_use_SOC = globalization_use_SOC - else: - raise Exception(f'Invalid value for globalization_use_SOC. Possible values are 0, 1, got {globalization_use_SOC}') - - @full_step_dual.setter - def full_step_dual(self, full_step_dual): - if full_step_dual in [0, 1]: - self.__full_step_dual = full_step_dual - else: - raise Exception(f'Invalid value for full_step_dual. Possible values are 0, 1, got {full_step_dual}') - - @eps_sufficient_descent.setter - def eps_sufficient_descent(self, eps_sufficient_descent): - if isinstance(eps_sufficient_descent, float) and eps_sufficient_descent > 0: - self.__eps_sufficient_descent = eps_sufficient_descent - else: - raise Exception('Invalid eps_sufficient_descent value. eps_sufficient_descent must be a positive float.') - - @sim_method_num_stages.setter - def sim_method_num_stages(self, sim_method_num_stages): - - # if isinstance(sim_method_num_stages, int): - # self.__sim_method_num_stages = sim_method_num_stages - # else: - # raise Exception('Invalid sim_method_num_stages value. sim_method_num_stages must be an integer.') - - self.__sim_method_num_stages = sim_method_num_stages - - @sim_method_num_steps.setter - def sim_method_num_steps(self, sim_method_num_steps): - - # if isinstance(sim_method_num_steps, int): - # self.__sim_method_num_steps = sim_method_num_steps - # else: - # raise Exception('Invalid sim_method_num_steps value. sim_method_num_steps must be an integer.') - self.__sim_method_num_steps = sim_method_num_steps - - - @sim_method_newton_iter.setter - def sim_method_newton_iter(self, sim_method_newton_iter): - - if isinstance(sim_method_newton_iter, int): - self.__sim_method_newton_iter = sim_method_newton_iter - else: - raise Exception('Invalid sim_method_newton_iter value. sim_method_newton_iter must be an integer.') - - @sim_method_jac_reuse.setter - def sim_method_jac_reuse(self, sim_method_jac_reuse): - # if sim_method_jac_reuse in (True, False): - self.__sim_method_jac_reuse = sim_method_jac_reuse - # else: - # raise Exception('Invalid sim_method_jac_reuse value. sim_method_jac_reuse must be a Boolean.') - - @nlp_solver_type.setter - def nlp_solver_type(self, nlp_solver_type): - nlp_solver_types = ('SQP', 'SQP_RTI') - if nlp_solver_type in nlp_solver_types: - self.__nlp_solver_type = nlp_solver_type - else: - raise Exception('Invalid nlp_solver_type value. Possible values are:\n\n' \ - + ',\n'.join(nlp_solver_types) + '.\n\nYou have: ' + nlp_solver_type + '.\n\n') - - @nlp_solver_step_length.setter - def nlp_solver_step_length(self, nlp_solver_step_length): - if isinstance(nlp_solver_step_length, float) and nlp_solver_step_length > 0: - self.__nlp_solver_step_length = nlp_solver_step_length - else: - raise Exception('Invalid nlp_solver_step_length value. nlp_solver_step_length must be a positive float.') - - @levenberg_marquardt.setter - def levenberg_marquardt(self, levenberg_marquardt): - if isinstance(levenberg_marquardt, float) and levenberg_marquardt >= 0: - self.__levenberg_marquardt = levenberg_marquardt - else: - raise Exception('Invalid levenberg_marquardt value. levenberg_marquardt must be a positive float.') - - @qp_solver_iter_max.setter - def qp_solver_iter_max(self, qp_solver_iter_max): - if isinstance(qp_solver_iter_max, int) and qp_solver_iter_max > 0: - self.__qp_solver_iter_max = qp_solver_iter_max - else: - raise Exception('Invalid qp_solver_iter_max value. qp_solver_iter_max must be a positive int.') - - @qp_solver_ric_alg.setter - def qp_solver_ric_alg(self, qp_solver_ric_alg): - if qp_solver_ric_alg in [0, 1]: - self.__qp_solver_ric_alg = qp_solver_ric_alg - else: - raise Exception(f'Invalid qp_solver_ric_alg value. qp_solver_ric_alg must be in [0, 1], got {qp_solver_ric_alg}.') - - @qp_solver_cond_ric_alg.setter - def qp_solver_cond_ric_alg(self, qp_solver_cond_ric_alg): - if qp_solver_cond_ric_alg in [0, 1]: - self.__qp_solver_cond_ric_alg = qp_solver_cond_ric_alg - else: - raise Exception(f'Invalid qp_solver_cond_ric_alg value. qp_solver_cond_ric_alg must be in [0, 1], got {qp_solver_cond_ric_alg}.') - - - @qp_solver_cond_N.setter - def qp_solver_cond_N(self, qp_solver_cond_N): - if isinstance(qp_solver_cond_N, int) and qp_solver_cond_N >= 0: - self.__qp_solver_cond_N = qp_solver_cond_N - else: - raise Exception('Invalid qp_solver_cond_N value. qp_solver_cond_N must be a positive int.') - - @qp_solver_warm_start.setter - def qp_solver_warm_start(self, qp_solver_warm_start): - if qp_solver_warm_start in [0, 1, 2]: - self.__qp_solver_warm_start = qp_solver_warm_start - else: - raise Exception('Invalid qp_solver_warm_start value. qp_solver_warm_start must be 0 or 1 or 2.') - - @qp_tol.setter - def qp_tol(self, qp_tol): - if isinstance(qp_tol, float) and qp_tol > 0: - self.__qp_solver_tol_eq = qp_tol - self.__qp_solver_tol_ineq = qp_tol - self.__qp_solver_tol_stat = qp_tol - self.__qp_solver_tol_comp = qp_tol - else: - raise Exception('Invalid qp_tol value. qp_tol must be a positive float.') - - @qp_solver_tol_stat.setter - def qp_solver_tol_stat(self, qp_solver_tol_stat): - if isinstance(qp_solver_tol_stat, float) and qp_solver_tol_stat > 0: - self.__qp_solver_tol_stat = qp_solver_tol_stat - else: - raise Exception('Invalid qp_solver_tol_stat value. qp_solver_tol_stat must be a positive float.') - - @qp_solver_tol_eq.setter - def qp_solver_tol_eq(self, qp_solver_tol_eq): - if isinstance(qp_solver_tol_eq, float) and qp_solver_tol_eq > 0: - self.__qp_solver_tol_eq = qp_solver_tol_eq - else: - raise Exception('Invalid qp_solver_tol_eq value. qp_solver_tol_eq must be a positive float.') - - @qp_solver_tol_ineq.setter - def qp_solver_tol_ineq(self, qp_solver_tol_ineq): - if isinstance(qp_solver_tol_ineq, float) and qp_solver_tol_ineq > 0: - self.__qp_solver_tol_ineq = qp_solver_tol_ineq - else: - raise Exception('Invalid qp_solver_tol_ineq value. qp_solver_tol_ineq must be a positive float.') - - @qp_solver_tol_comp.setter - def qp_solver_tol_comp(self, qp_solver_tol_comp): - if isinstance(qp_solver_tol_comp, float) and qp_solver_tol_comp > 0: - self.__qp_solver_tol_comp = qp_solver_tol_comp - else: - raise Exception('Invalid qp_solver_tol_comp value. qp_solver_tol_comp must be a positive float.') - - @tol.setter - def tol(self, tol): - if isinstance(tol, float) and tol > 0: - self.__nlp_solver_tol_eq = tol - self.__nlp_solver_tol_ineq = tol - self.__nlp_solver_tol_stat = tol - self.__nlp_solver_tol_comp = tol - else: - raise Exception('Invalid tol value. tol must be a positive float.') - - @nlp_solver_tol_stat.setter - def nlp_solver_tol_stat(self, nlp_solver_tol_stat): - if isinstance(nlp_solver_tol_stat, float) and nlp_solver_tol_stat > 0: - self.__nlp_solver_tol_stat = nlp_solver_tol_stat - else: - raise Exception('Invalid nlp_solver_tol_stat value. nlp_solver_tol_stat must be a positive float.') - - @nlp_solver_tol_eq.setter - def nlp_solver_tol_eq(self, nlp_solver_tol_eq): - if isinstance(nlp_solver_tol_eq, float) and nlp_solver_tol_eq > 0: - self.__nlp_solver_tol_eq = nlp_solver_tol_eq - else: - raise Exception('Invalid nlp_solver_tol_eq value. nlp_solver_tol_eq must be a positive float.') - - @nlp_solver_tol_ineq.setter - def nlp_solver_tol_ineq(self, nlp_solver_tol_ineq): - if isinstance(nlp_solver_tol_ineq, float) and nlp_solver_tol_ineq > 0: - self.__nlp_solver_tol_ineq = nlp_solver_tol_ineq - else: - raise Exception('Invalid nlp_solver_tol_ineq value. nlp_solver_tol_ineq must be a positive float.') - - @nlp_solver_ext_qp_res.setter - def nlp_solver_ext_qp_res(self, nlp_solver_ext_qp_res): - if nlp_solver_ext_qp_res in [0, 1]: - self.__nlp_solver_ext_qp_res = nlp_solver_ext_qp_res - else: - raise Exception('Invalid nlp_solver_ext_qp_res value. nlp_solver_ext_qp_res must be in [0, 1].') - - @nlp_solver_tol_comp.setter - def nlp_solver_tol_comp(self, nlp_solver_tol_comp): - if isinstance(nlp_solver_tol_comp, float) and nlp_solver_tol_comp > 0: - self.__nlp_solver_tol_comp = nlp_solver_tol_comp - else: - raise Exception('Invalid nlp_solver_tol_comp value. nlp_solver_tol_comp must be a positive float.') - - @nlp_solver_max_iter.setter - def nlp_solver_max_iter(self, nlp_solver_max_iter): - - if isinstance(nlp_solver_max_iter, int) and nlp_solver_max_iter > 0: - self.__nlp_solver_max_iter = nlp_solver_max_iter - else: - raise Exception('Invalid nlp_solver_max_iter value. nlp_solver_max_iter must be a positive int.') - - @print_level.setter - def print_level(self, print_level): - if isinstance(print_level, int) and print_level >= 0: - self.__print_level = print_level - else: - raise Exception('Invalid print_level value. print_level takes one of the values >=0.') - - @model_external_shared_lib_dir.setter - def model_external_shared_lib_dir(self, model_external_shared_lib_dir): - if isinstance(model_external_shared_lib_dir, str) : - self.__model_external_shared_lib_dir = model_external_shared_lib_dir - else: - raise Exception('Invalid model_external_shared_lib_dir value. Str expected.' \ - + '.\n\nYou have: ' + type(model_external_shared_lib_dir) + '.\n\n') - - @model_external_shared_lib_name.setter - def model_external_shared_lib_name(self, model_external_shared_lib_name): - if isinstance(model_external_shared_lib_name, str) : - if model_external_shared_lib_name[-3:] == '.so' : - raise Exception('Invalid model_external_shared_lib_name value. Remove the .so extension.' \ - + '.\n\nYou have: ' + type(model_external_shared_lib_name) + '.\n\n') - else : - self.__model_external_shared_lib_name = model_external_shared_lib_name - else: - raise Exception('Invalid model_external_shared_lib_name value. Str expected.' \ - + '.\n\nYou have: ' + type(model_external_shared_lib_name) + '.\n\n') - - @exact_hess_constr.setter - def exact_hess_constr(self, exact_hess_constr): - if exact_hess_constr in [0, 1]: - self.__exact_hess_constr = exact_hess_constr - else: - raise Exception('Invalid exact_hess_constr value. exact_hess_constr takes one of the values 0, 1.') - - @exact_hess_cost.setter - def exact_hess_cost(self, exact_hess_cost): - if exact_hess_cost in [0, 1]: - self.__exact_hess_cost = exact_hess_cost - else: - raise Exception('Invalid exact_hess_cost value. exact_hess_cost takes one of the values 0, 1.') - - @exact_hess_dyn.setter - def exact_hess_dyn(self, exact_hess_dyn): - if exact_hess_dyn in [0, 1]: - self.__exact_hess_dyn = exact_hess_dyn - else: - raise Exception('Invalid exact_hess_dyn value. exact_hess_dyn takes one of the values 0, 1.') - - @ext_cost_num_hess.setter - def ext_cost_num_hess(self, ext_cost_num_hess): - if ext_cost_num_hess in [0, 1]: - self.__ext_cost_num_hess = ext_cost_num_hess - else: - raise Exception('Invalid ext_cost_num_hess value. ext_cost_num_hess takes one of the values 0, 1.') - - def set(self, attr, value): - setattr(self, attr, value) - - -class AcadosOcp: - """ - Class containing the full description of the optimal control problem. - This object can be used to create an :py:class:`acados_template.acados_ocp_solver.AcadosOcpSolver`. - - The class has the following properties that can be modified to formulate a specific OCP, see below: - - - :py:attr:`dims` of type :py:class:`acados_template.acados_ocp.AcadosOcpDims` - - :py:attr:`model` of type :py:class:`acados_template.acados_model.AcadosModel` - - :py:attr:`cost` of type :py:class:`acados_template.acados_ocp.AcadosOcpCost` - - :py:attr:`constraints` of type :py:class:`acados_template.acados_ocp.AcadosOcpConstraints` - - :py:attr:`solver_options` of type :py:class:`acados_template.acados_ocp.AcadosOcpOptions` - - - :py:attr:`acados_include_path` (set automatically) - - :py:attr:`shared_lib_ext` (set automatically) - - :py:attr:`acados_lib_path` (set automatically) - - :py:attr:`parameter_values` - used to initialize the parameters (can be changed) - """ - def __init__(self, acados_path=''): - """ - Keyword arguments: - acados_path -- path of your acados installation - """ - if acados_path == '': - acados_path = get_acados_path() - - self.dims = AcadosOcpDims() - """Dimension definitions, type :py:class:`acados_template.acados_ocp.AcadosOcpDims`""" - self.model = AcadosModel() - """Model definitions, type :py:class:`acados_template.acados_model.AcadosModel`""" - self.cost = AcadosOcpCost() - """Cost definitions, type :py:class:`acados_template.acados_ocp.AcadosOcpCost`""" - self.constraints = AcadosOcpConstraints() - """Constraints definitions, type :py:class:`acados_template.acados_ocp.AcadosOcpConstraints`""" - self.solver_options = AcadosOcpOptions() - """Solver Options, type :py:class:`acados_template.acados_ocp.AcadosOcpOptions`""" - - self.acados_include_path = os.path.join(acados_path, 'include').replace(os.sep, '/') # the replace part is important on Windows for CMake - """Path to acados include directory (set automatically), type: `string`""" - self.acados_lib_path = os.path.join(acados_path, 'lib').replace(os.sep, '/') # the replace part is important on Windows for CMake - """Path to where acados library is located, type: `string`""" - self.shared_lib_ext = get_lib_ext() - - # get cython paths - from sysconfig import get_paths - self.cython_include_dirs = [np.get_include(), get_paths()['include']] - - self.__parameter_values = np.array([]) - self.__problem_class = 'OCP' - - self.code_export_directory = 'c_generated_code' - """Path to where code will be exported. Default: `c_generated_code`.""" - - @property - def parameter_values(self): - """:math:`p` - initial values for parameter - can be updated stagewise""" - return self.__parameter_values - - @parameter_values.setter - def parameter_values(self, parameter_values): - if isinstance(parameter_values, np.ndarray): - self.__parameter_values = parameter_values - else: - raise Exception('Invalid parameter_values value. ' + - f'Expected numpy array, got {type(parameter_values)}.') - - def set(self, attr, value): - # tokenize string - tokens = attr.split('_', 1) - if len(tokens) > 1: - setter_to_call = getattr(getattr(self, tokens[0]), 'set') - else: - setter_to_call = getattr(self, 'set') - - setter_to_call(tokens[1], value) - - return diff --git a/third_party/acados/acados_template/acados_ocp_solver.py b/third_party/acados/acados_template/acados_ocp_solver.py deleted file mode 100644 index ffc9cf4b0e118c..00000000000000 --- a/third_party/acados/acados_template/acados_ocp_solver.py +++ /dev/null @@ -1,1991 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -import sys -import os -import json -import numpy as np -from datetime import datetime -import importlib -import shutil - -from subprocess import DEVNULL, call, STDOUT - -from ctypes import POINTER, cast, CDLL, c_void_p, c_char_p, c_double, c_int, c_int64, byref - -from copy import deepcopy -from pathlib import Path - -from .casadi_function_generation import generate_c_code_explicit_ode, \ - generate_c_code_implicit_ode, generate_c_code_gnsf, generate_c_code_discrete_dynamics, \ - generate_c_code_constraint, generate_c_code_nls_cost, generate_c_code_conl_cost, \ - generate_c_code_external_cost -from .gnsf.detect_gnsf_structure import detect_gnsf_structure -from .acados_ocp import AcadosOcp -from .acados_model import AcadosModel -from .utils import is_column, is_empty, casadi_length, render_template,\ - format_class_dict, make_object_json_dumpable, make_model_consistent,\ - set_up_imported_gnsf_model, get_ocp_nlp_layout, get_python_interface_path, get_lib_ext, check_casadi_version -from .builders import CMakeBuilder - - -def make_ocp_dims_consistent(acados_ocp: AcadosOcp): - dims = acados_ocp.dims - cost = acados_ocp.cost - constraints = acados_ocp.constraints - model = acados_ocp.model - opts = acados_ocp.solver_options - - # nx - if is_column(model.x): - dims.nx = casadi_length(model.x) - else: - raise Exception('model.x should be column vector!') - - # nu - if is_empty(model.u): - dims.nu = 0 - else: - dims.nu = casadi_length(model.u) - - # nz - if is_empty(model.z): - dims.nz = 0 - else: - dims.nz = casadi_length(model.z) - - # np - if is_empty(model.p): - dims.np = 0 - else: - dims.np = casadi_length(model.p) - if acados_ocp.parameter_values.shape[0] != dims.np: - raise Exception('inconsistent dimension np, regarding model.p and parameter_values.' + \ - f'\nGot np = {dims.np}, acados_ocp.parameter_values.shape = {acados_ocp.parameter_values.shape[0]}\n') - - ## cost - # initial stage - if not set, copy fields from path constraints - if cost.cost_type_0 is None: - cost.cost_type_0 = cost.cost_type - cost.W_0 = cost.W - cost.Vx_0 = cost.Vx - cost.Vu_0 = cost.Vu - cost.Vz_0 = cost.Vz - cost.yref_0 = cost.yref - cost.cost_ext_fun_type_0 = cost.cost_ext_fun_type - model.cost_y_expr_0 = model.cost_y_expr - model.cost_expr_ext_cost_0 = model.cost_expr_ext_cost - model.cost_expr_ext_cost_custom_hess_0 = model.cost_expr_ext_cost_custom_hess - - model.cost_psi_expr_0 = model.cost_psi_expr - model.cost_r_in_psi_expr_0 = model.cost_r_in_psi_expr - - if cost.cost_type_0 == 'LINEAR_LS': - ny_0 = cost.W_0.shape[0] - if cost.Vx_0.shape[0] != ny_0 or cost.Vu_0.shape[0] != ny_0: - raise Exception('inconsistent dimension ny_0, regarding W_0, Vx_0, Vu_0.' + \ - f'\nGot W_0[{cost.W_0.shape}], Vx_0[{cost.Vx_0.shape}], Vu_0[{cost.Vu_0.shape}]\n') - if dims.nz != 0 and cost.Vz_0.shape[0] != ny_0: - raise Exception('inconsistent dimension ny_0, regarding W_0, Vx_0, Vu_0, Vz_0.' + \ - f'\nGot W_0[{cost.W_0.shape}], Vx_0[{cost.Vx_0.shape}], Vu_0[{cost.Vu_0.shape}], Vz_0[{cost.Vz_0.shape}]\n') - if cost.Vx_0.shape[1] != dims.nx and ny_0 != 0: - raise Exception('inconsistent dimension: Vx_0 should have nx columns.') - if cost.Vu_0.shape[1] != dims.nu and ny_0 != 0: - raise Exception('inconsistent dimension: Vu_0 should have nu columns.') - if cost.yref_0.shape[0] != ny_0: - raise Exception('inconsistent dimension: regarding W_0, yref_0.' + \ - f'\nGot W_0[{cost.W_0.shape}], yref_0[{cost.yref_0.shape}]\n') - dims.ny_0 = ny_0 - - elif cost.cost_type_0 == 'NONLINEAR_LS': - ny_0 = cost.W_0.shape[0] - if is_empty(model.cost_y_expr_0) and ny_0 != 0: - raise Exception('inconsistent dimension ny_0: regarding W_0, cost_y_expr.') - elif casadi_length(model.cost_y_expr_0) != ny_0: - raise Exception('inconsistent dimension ny_0: regarding W_0, cost_y_expr.') - if cost.yref_0.shape[0] != ny_0: - raise Exception('inconsistent dimension: regarding W_0, yref_0.' + \ - f'\nGot W_0[{cost.W.shape}], yref_0[{cost.yref_0.shape}]\n') - dims.ny_0 = ny_0 - - elif cost.cost_type_0 == 'CONVEX_OVER_NONLINEAR': - if is_empty(model.cost_y_expr_0): - raise Exception('cost_y_expr_0 and/or cost_y_expr not provided.') - ny_0 = casadi_length(model.cost_y_expr_0) - if is_empty(model.cost_r_in_psi_expr_0) or casadi_length(model.cost_r_in_psi_expr_0) != ny_0: - raise Exception('inconsistent dimension ny_0: regarding cost_y_expr_0 and cost_r_in_psi_0.') - if is_empty(model.cost_psi_expr_0) or casadi_length(model.cost_psi_expr_0) != 1: - raise Exception('cost_psi_expr_0 not provided or not scalar-valued.') - if cost.yref_0.shape[0] != ny_0: - raise Exception('inconsistent dimension: regarding yref_0 and cost_y_expr_0, cost_r_in_psi_0.') - dims.ny_0 = ny_0 - - if not (opts.hessian_approx=='EXACT' and opts.exact_hess_cost==False) and opts.hessian_approx != 'GAUSS_NEWTON': - raise Exception("\nWith CONVEX_OVER_NONLINEAR cost type, possible Hessian approximations are:\n" - "GAUSS_NEWTON or EXACT with 'exact_hess_cost' == False.\n") - - elif cost.cost_type_0 == 'EXTERNAL': - if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess_0 is None: - print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" - "got cost_type_0: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" - "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" - "If you continue, acados will proceed computing the exact hessian for the cost term.\n" - "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" - "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") - - # path - if cost.cost_type == 'LINEAR_LS': - ny = cost.W.shape[0] - if cost.Vx.shape[0] != ny or cost.Vu.shape[0] != ny: - raise Exception('inconsistent dimension ny, regarding W, Vx, Vu.' + \ - f'\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\n') - if dims.nz != 0 and cost.Vz.shape[0] != ny: - raise Exception('inconsistent dimension ny, regarding W, Vx, Vu, Vz.' + \ - f'\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\n') - if cost.Vx.shape[1] != dims.nx and ny != 0: - raise Exception('inconsistent dimension: Vx should have nx columns.') - if cost.Vu.shape[1] != dims.nu and ny != 0: - raise Exception('inconsistent dimension: Vu should have nu columns.') - if cost.yref.shape[0] != ny: - raise Exception('inconsistent dimension: regarding W, yref.' + \ - f'\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\n') - dims.ny = ny - - elif cost.cost_type == 'NONLINEAR_LS': - ny = cost.W.shape[0] - if is_empty(model.cost_y_expr) and ny != 0: - raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') - elif casadi_length(model.cost_y_expr) != ny: - raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') - if cost.yref.shape[0] != ny: - raise Exception('inconsistent dimension: regarding W, yref.' + \ - f'\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\n') - dims.ny = ny - - elif cost.cost_type == 'CONVEX_OVER_NONLINEAR': - if is_empty(model.cost_y_expr): - raise Exception('cost_y_expr and/or cost_y_expr not provided.') - ny = casadi_length(model.cost_y_expr) - if is_empty(model.cost_r_in_psi_expr) or casadi_length(model.cost_r_in_psi_expr) != ny: - raise Exception('inconsistent dimension ny: regarding cost_y_expr and cost_r_in_psi.') - if is_empty(model.cost_psi_expr) or casadi_length(model.cost_psi_expr) != 1: - raise Exception('cost_psi_expr not provided or not scalar-valued.') - if cost.yref.shape[0] != ny: - raise Exception('inconsistent dimension: regarding yref and cost_y_expr, cost_r_in_psi.') - dims.ny = ny - - if not (opts.hessian_approx=='EXACT' and opts.exact_hess_cost==False) and opts.hessian_approx != 'GAUSS_NEWTON': - raise Exception("\nWith CONVEX_OVER_NONLINEAR cost type, possible Hessian approximations are:\n" - "GAUSS_NEWTON or EXACT with 'exact_hess_cost' == False.\n") - - - elif cost.cost_type == 'EXTERNAL': - if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess is None: - print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" - "got cost_type: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" - "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" - "If you continue, acados will proceed computing the exact hessian for the cost term.\n" - "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" - "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") - - # terminal - if cost.cost_type_e == 'LINEAR_LS': - ny_e = cost.W_e.shape[0] - if cost.Vx_e.shape[0] != ny_e: - raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.' + \ - f'\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') - if cost.Vx_e.shape[1] != dims.nx and ny_e != 0: - raise Exception('inconsistent dimension: Vx_e should have nx columns.') - if cost.yref_e.shape[0] != ny_e: - raise Exception('inconsistent dimension: regarding W_e, yref_e.') - dims.ny_e = ny_e - - elif cost.cost_type_e == 'NONLINEAR_LS': - ny_e = cost.W_e.shape[0] - if is_empty(model.cost_y_expr_e) and ny_e != 0: - raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') - elif casadi_length(model.cost_y_expr_e) != ny_e: - raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') - if cost.yref_e.shape[0] != ny_e: - raise Exception('inconsistent dimension: regarding W_e, yref_e.') - dims.ny_e = ny_e - - elif cost.cost_type_e == 'CONVEX_OVER_NONLINEAR': - if is_empty(model.cost_y_expr_e): - raise Exception('cost_y_expr_e not provided.') - ny_e = casadi_length(model.cost_y_expr_e) - if is_empty(model.cost_r_in_psi_expr_e) or casadi_length(model.cost_r_in_psi_expr_e) != ny_e: - raise Exception('inconsistent dimension ny_e: regarding cost_y_expr_e and cost_r_in_psi_e.') - if is_empty(model.cost_psi_expr_e) or casadi_length(model.cost_psi_expr_e) != 1: - raise Exception('cost_psi_expr_e not provided or not scalar-valued.') - if cost.yref_e.shape[0] != ny_e: - raise Exception('inconsistent dimension: regarding yref_e and cost_y_expr_e, cost_r_in_psi_e.') - dims.ny_e = ny_e - - if not (opts.hessian_approx=='EXACT' and opts.exact_hess_cost==False) and opts.hessian_approx != 'GAUSS_NEWTON': - raise Exception("\nWith CONVEX_OVER_NONLINEAR cost type, possible Hessian approximations are:\n" - "GAUSS_NEWTON or EXACT with 'exact_hess_cost' == False.\n") - - - - elif cost.cost_type_e == 'EXTERNAL': - if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess_e is None: - print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" - "got cost_type_e: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" - "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" - "If you continue, acados will proceed computing the exact hessian for the cost term.\n" - "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" - "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") - - ## constraints - # initial - this_shape = constraints.lbx_0.shape - other_shape = constraints.ubx_0.shape - if not this_shape == other_shape: - raise Exception('lbx_0, ubx_0 have different shapes!') - if not is_column(constraints.lbx_0): - raise Exception('lbx_0, ubx_0 must be column vectors!') - dims.nbx_0 = constraints.lbx_0.size - - if all(constraints.lbx_0 == constraints.ubx_0) and dims.nbx_0 == dims.nx \ - and dims.nbxe_0 is None \ - and (constraints.idxbxe_0.shape == constraints.idxbx_0.shape)\ - and all(constraints.idxbxe_0 == constraints.idxbx_0): - # case: x0 was set: nbx0 are all equlities. - dims.nbxe_0 = dims.nbx_0 - elif constraints.idxbxe_0 is not None: - dims.nbxe_0 = constraints.idxbxe_0.shape[0] - elif dims.nbxe_0 is None: - # case: x0 and idxbxe_0 were not set -> dont assume nbx0 to be equality constraints. - dims.nbxe_0 = 0 - - # path - nbx = constraints.idxbx.shape[0] - if constraints.ubx.shape[0] != nbx or constraints.lbx.shape[0] != nbx: - raise Exception('inconsistent dimension nbx, regarding idxbx, ubx, lbx.') - else: - dims.nbx = nbx - - nbu = constraints.idxbu.shape[0] - if constraints.ubu.shape[0] != nbu or constraints.lbu.shape[0] != nbu: - raise Exception('inconsistent dimension nbu, regarding idxbu, ubu, lbu.') - else: - dims.nbu = nbu - - ng = constraints.lg.shape[0] - if constraints.ug.shape[0] != ng or constraints.C.shape[0] != ng \ - or constraints.D.shape[0] != ng: - raise Exception('inconsistent dimension ng, regarding lg, ug, C, D.') - else: - dims.ng = ng - - if not is_empty(model.con_h_expr): - nh = casadi_length(model.con_h_expr) - else: - nh = 0 - - if constraints.uh.shape[0] != nh or constraints.lh.shape[0] != nh: - raise Exception('inconsistent dimension nh, regarding lh, uh, con_h_expr.') - else: - dims.nh = nh - - if is_empty(model.con_phi_expr): - dims.nphi = 0 - dims.nr = 0 - else: - dims.nphi = casadi_length(model.con_phi_expr) - if is_empty(model.con_r_expr): - raise Exception('convex over nonlinear constraints: con_r_expr but con_phi_expr is nonempty') - else: - dims.nr = casadi_length(model.con_r_expr) - - # terminal - nbx_e = constraints.idxbx_e.shape[0] - if constraints.ubx_e.shape[0] != nbx_e or constraints.lbx_e.shape[0] != nbx_e: - raise Exception('inconsistent dimension nbx_e, regarding idxbx_e, ubx_e, lbx_e.') - else: - dims.nbx_e = nbx_e - - ng_e = constraints.lg_e.shape[0] - if constraints.ug_e.shape[0] != ng_e or constraints.C_e.shape[0] != ng_e: - raise Exception('inconsistent dimension ng_e, regarding_e lg_e, ug_e, C_e.') - else: - dims.ng_e = ng_e - - if not is_empty(model.con_h_expr_e): - nh_e = casadi_length(model.con_h_expr_e) - else: - nh_e = 0 - - if constraints.uh_e.shape[0] != nh_e or constraints.lh_e.shape[0] != nh_e: - raise Exception('inconsistent dimension nh_e, regarding lh_e, uh_e, con_h_expr_e.') - else: - dims.nh_e = nh_e - - if is_empty(model.con_phi_expr_e): - dims.nphi_e = 0 - dims.nr_e = 0 - else: - dims.nphi_e = casadi_length(model.con_phi_expr_e) - if is_empty(model.con_r_expr_e): - raise Exception('convex over nonlinear constraints: con_r_expr_e but con_phi_expr_e is nonempty') - else: - dims.nr_e = casadi_length(model.con_r_expr_e) - - # Slack dimensions - nsbx = constraints.idxsbx.shape[0] - if nsbx > nbx: - raise Exception(f'inconsistent dimension nsbx = {nsbx}. Is greater than nbx = {nbx}.') - if is_empty(constraints.lsbx): - constraints.lsbx = np.zeros((nsbx,)) - elif constraints.lsbx.shape[0] != nsbx: - raise Exception('inconsistent dimension nsbx, regarding idxsbx, lsbx.') - if is_empty(constraints.usbx): - constraints.usbx = np.zeros((nsbx,)) - elif constraints.usbx.shape[0] != nsbx: - raise Exception('inconsistent dimension nsbx, regarding idxsbx, usbx.') - dims.nsbx = nsbx - - nsbu = constraints.idxsbu.shape[0] - if nsbu > nbu: - raise Exception(f'inconsistent dimension nsbu = {nsbu}. Is greater than nbu = {nbu}.') - if is_empty(constraints.lsbu): - constraints.lsbu = np.zeros((nsbu,)) - elif constraints.lsbu.shape[0] != nsbu: - raise Exception('inconsistent dimension nsbu, regarding idxsbu, lsbu.') - if is_empty(constraints.usbu): - constraints.usbu = np.zeros((nsbu,)) - elif constraints.usbu.shape[0] != nsbu: - raise Exception('inconsistent dimension nsbu, regarding idxsbu, usbu.') - dims.nsbu = nsbu - - nsh = constraints.idxsh.shape[0] - if nsh > nh: - raise Exception(f'inconsistent dimension nsh = {nsh}. Is greater than nh = {nh}.') - if is_empty(constraints.lsh): - constraints.lsh = np.zeros((nsh,)) - elif constraints.lsh.shape[0] != nsh: - raise Exception('inconsistent dimension nsh, regarding idxsh, lsh.') - if is_empty(constraints.ush): - constraints.ush = np.zeros((nsh,)) - elif constraints.ush.shape[0] != nsh: - raise Exception('inconsistent dimension nsh, regarding idxsh, ush.') - dims.nsh = nsh - - nsphi = constraints.idxsphi.shape[0] - if nsphi > dims.nphi: - raise Exception(f'inconsistent dimension nsphi = {nsphi}. Is greater than nphi = {dims.nphi}.') - if is_empty(constraints.lsphi): - constraints.lsphi = np.zeros((nsphi,)) - elif constraints.lsphi.shape[0] != nsphi: - raise Exception('inconsistent dimension nsphi, regarding idxsphi, lsphi.') - if is_empty(constraints.usphi): - constraints.usphi = np.zeros((nsphi,)) - elif constraints.usphi.shape[0] != nsphi: - raise Exception('inconsistent dimension nsphi, regarding idxsphi, usphi.') - dims.nsphi = nsphi - - nsg = constraints.idxsg.shape[0] - if nsg > ng: - raise Exception(f'inconsistent dimension nsg = {nsg}. Is greater than ng = {ng}.') - if is_empty(constraints.lsg): - constraints.lsg = np.zeros((nsg,)) - elif constraints.lsg.shape[0] != nsg: - raise Exception('inconsistent dimension nsg, regarding idxsg, lsg.') - if is_empty(constraints.usg): - constraints.usg = np.zeros((nsg,)) - elif constraints.usg.shape[0] != nsg: - raise Exception('inconsistent dimension nsg, regarding idxsg, usg.') - dims.nsg = nsg - - ns = nsbx + nsbu + nsh + nsg + nsphi - wrong_field = "" - if cost.Zl.shape[0] != ns: - wrong_field = "Zl" - dim = cost.Zl.shape[0] - elif cost.Zu.shape[0] != ns: - wrong_field = "Zu" - dim = cost.Zu.shape[0] - elif cost.zl.shape[0] != ns: - wrong_field = "zl" - dim = cost.zl.shape[0] - elif cost.zu.shape[0] != ns: - wrong_field = "zu" - dim = cost.zu.shape[0] - - if wrong_field != "": - raise Exception(f'Inconsistent size for field {wrong_field}, with dimension {dim}, \n\t'\ - + f'Detected ns = {ns} = nsbx + nsbu + nsg + nsh + nsphi.\n\t'\ - + f'With nsbx = {nsbx}, nsbu = {nsbu}, nsg = {nsg}, nsh = {nsh}, nsphi = {nsphi}') - - dims.ns = ns - - nsbx_e = constraints.idxsbx_e.shape[0] - if nsbx_e > nbx_e: - raise Exception(f'inconsistent dimension nsbx_e = {nsbx_e}. Is greater than nbx_e = {nbx_e}.') - if is_empty(constraints.lsbx_e): - constraints.lsbx_e = np.zeros((nsbx_e,)) - elif constraints.lsbx_e.shape[0] != nsbx_e: - raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, lsbx_e.') - if is_empty(constraints.usbx_e): - constraints.usbx_e = np.zeros((nsbx_e,)) - elif constraints.usbx_e.shape[0] != nsbx_e: - raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, usbx_e.') - dims.nsbx_e = nsbx_e - - nsh_e = constraints.idxsh_e.shape[0] - if nsh_e > nh_e: - raise Exception(f'inconsistent dimension nsh_e = {nsh_e}. Is greater than nh_e = {nh_e}.') - if is_empty(constraints.lsh_e): - constraints.lsh_e = np.zeros((nsh_e,)) - elif constraints.lsh_e.shape[0] != nsh_e: - raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, lsh_e.') - if is_empty(constraints.ush_e): - constraints.ush_e = np.zeros((nsh_e,)) - elif constraints.ush_e.shape[0] != nsh_e: - raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, ush_e.') - dims.nsh_e = nsh_e - - nsg_e = constraints.idxsg_e.shape[0] - if nsg_e > ng_e: - raise Exception(f'inconsistent dimension nsg_e = {nsg_e}. Is greater than ng_e = {ng_e}.') - if is_empty(constraints.lsg_e): - constraints.lsg_e = np.zeros((nsg_e,)) - elif constraints.lsg_e.shape[0] != nsg_e: - raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, lsg_e.') - if is_empty(constraints.usg_e): - constraints.usg_e = np.zeros((nsg_e,)) - elif constraints.usg_e.shape[0] != nsg_e: - raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, usg_e.') - dims.nsg_e = nsg_e - - nsphi_e = constraints.idxsphi_e.shape[0] - if nsphi_e > dims.nphi_e: - raise Exception(f'inconsistent dimension nsphi_e = {nsphi_e}. Is greater than nphi_e = {dims.nphi_e}.') - if is_empty(constraints.lsphi_e): - constraints.lsphi_e = np.zeros((nsphi_e,)) - elif constraints.lsphi_e.shape[0] != nsphi_e: - raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, lsphi_e.') - if is_empty(constraints.usphi_e): - constraints.usphi_e = np.zeros((nsphi_e,)) - elif constraints.usphi_e.shape[0] != nsphi_e: - raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, usphi_e.') - dims.nsphi_e = nsphi_e - - # terminal - ns_e = nsbx_e + nsh_e + nsg_e + nsphi_e - wrong_field = "" - if cost.Zl_e.shape[0] != ns_e: - wrong_field = "Zl_e" - dim = cost.Zl_e.shape[0] - elif cost.Zu_e.shape[0] != ns_e: - wrong_field = "Zu_e" - dim = cost.Zu_e.shape[0] - elif cost.zl_e.shape[0] != ns_e: - wrong_field = "zl_e" - dim = cost.zl_e.shape[0] - elif cost.zu_e.shape[0] != ns_e: - wrong_field = "zu_e" - dim = cost.zu_e.shape[0] - - if wrong_field != "": - raise Exception(f'Inconsistent size for field {wrong_field}, with dimension {dim}, \n\t'\ - + f'Detected ns_e = {ns_e} = nsbx_e + nsg_e + nsh_e + nsphi_e.\n\t'\ - + f'With nsbx_e = {nsbx_e}, nsg_e = {nsg_e}, nsh_e = {nsh_e}, nsphi_e = {nsphi_e}') - - dims.ns_e = ns_e - - # discretization - if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): - # uniform discretization - opts.time_steps = opts.tf / dims.N * np.ones((dims.N,)) - - elif not is_empty(opts.shooting_nodes): - if np.shape(opts.shooting_nodes)[0] != dims.N+1: - raise Exception('inconsistent dimension N, regarding shooting_nodes.') - - time_steps = opts.shooting_nodes[1:] - opts.shooting_nodes[0:-1] - # identify constant time_steps: due to numerical reasons the content of time_steps might vary a bit - avg_time_steps = np.average(time_steps) - # criterion for constant time step detection: the min/max difference in values normalized by the average - check_const_time_step = (np.max(time_steps)-np.min(time_steps)) / avg_time_steps - # if the criterion is small, we have a constant time_step - if check_const_time_step < 1e-9: - time_steps[:] = avg_time_steps # if we have a constant time_step: apply the average time_step - - opts.time_steps = time_steps - - elif (not is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)): - Exception('Please provide either time_steps or shooting_nodes for nonuniform discretization') - - tf = np.sum(opts.time_steps) - if (tf - opts.tf) / tf > 1e-15: - raise Exception(f'Inconsistent discretization: {opts.tf}'\ - f' = tf != sum(opts.time_steps) = {tf}.') - - # num_steps - if isinstance(opts.sim_method_num_steps, np.ndarray) and opts.sim_method_num_steps.size == 1: - opts.sim_method_num_steps = opts.sim_method_num_steps.item() - - if isinstance(opts.sim_method_num_steps, (int, float)) and opts.sim_method_num_steps % 1 == 0: - opts.sim_method_num_steps = opts.sim_method_num_steps * np.ones((dims.N,), dtype=np.int64) - elif isinstance(opts.sim_method_num_steps, np.ndarray) and opts.sim_method_num_steps.size == dims.N \ - and np.all(np.equal(np.mod(opts.sim_method_num_steps, 1), 0)): - opts.sim_method_num_steps = np.reshape(opts.sim_method_num_steps, (dims.N,)).astype(np.int64) - else: - raise Exception("Wrong value for sim_method_num_steps. Should be either int or array of ints of shape (N,).") - - # num_stages - if isinstance(opts.sim_method_num_stages, np.ndarray) and opts.sim_method_num_stages.size == 1: - opts.sim_method_num_stages = opts.sim_method_num_stages.item() - - if isinstance(opts.sim_method_num_stages, (int, float)) and opts.sim_method_num_stages % 1 == 0: - opts.sim_method_num_stages = opts.sim_method_num_stages * np.ones((dims.N,), dtype=np.int64) - elif isinstance(opts.sim_method_num_stages, np.ndarray) and opts.sim_method_num_stages.size == dims.N \ - and np.all(np.equal(np.mod(opts.sim_method_num_stages, 1), 0)): - opts.sim_method_num_stages = np.reshape(opts.sim_method_num_stages, (dims.N,)).astype(np.int64) - else: - raise Exception("Wrong value for sim_method_num_stages. Should be either int or array of ints of shape (N,).") - - # jac_reuse - if isinstance(opts.sim_method_jac_reuse, np.ndarray) and opts.sim_method_jac_reuse.size == 1: - opts.sim_method_jac_reuse = opts.sim_method_jac_reuse.item() - - if isinstance(opts.sim_method_jac_reuse, (int, float)) and opts.sim_method_jac_reuse % 1 == 0: - opts.sim_method_jac_reuse = opts.sim_method_jac_reuse * np.ones((dims.N,), dtype=np.int64) - elif isinstance(opts.sim_method_jac_reuse, np.ndarray) and opts.sim_method_jac_reuse.size == dims.N \ - and np.all(np.equal(np.mod(opts.sim_method_jac_reuse, 1), 0)): - opts.sim_method_jac_reuse = np.reshape(opts.sim_method_jac_reuse, (dims.N,)).astype(np.int64) - else: - raise Exception("Wrong value for sim_method_jac_reuse. Should be either int or array of ints of shape (N,).") - - -def get_simulink_default_opts(): - python_interface_path = get_python_interface_path() - abs_path = os.path.join(python_interface_path, 'simulink_default_opts.json') - with open(abs_path , 'r') as f: - simulink_default_opts = json.load(f) - return simulink_default_opts - - -def ocp_formulation_json_dump(acados_ocp, simulink_opts=None, json_file='acados_ocp_nlp.json'): - # Load acados_ocp_nlp structure description - ocp_layout = get_ocp_nlp_layout() - - # Copy input ocp object dictionary - ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) - # TODO: maybe make one function with formatting - - for acados_struct, v in ocp_layout.items(): - # skip non dict attributes - if not isinstance(v, dict): - continue - # setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) - # Copy ocp object attributes dictionaries - ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) - - ocp_nlp_dict = format_class_dict(ocp_nlp_dict) - - if simulink_opts is not None: - ocp_nlp_dict['simulink_opts'] = simulink_opts - - with open(json_file, 'w') as f: - json.dump(ocp_nlp_dict, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - - - -def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): - # Load acados_ocp_nlp structure description - ocp_layout = get_ocp_nlp_layout() - - with open(json_file, 'r') as f: - ocp_nlp_json = json.load(f) - - ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims']) - - # Instantiate AcadosOcp object - acados_ocp = AcadosOcp() - - # load class dict - acados_ocp.__dict__ = ocp_nlp_dict - - # load class attributes dict, dims, constraints, etc - for acados_struct, v in ocp_layout.items(): - # skip non dict attributes - if not isinstance(v, dict): - continue - acados_attribute = getattr(acados_ocp, acados_struct) - acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] - setattr(acados_ocp, acados_struct, acados_attribute) - - return acados_ocp - - -def ocp_generate_external_functions(acados_ocp: AcadosOcp, model: AcadosModel): - - model = make_model_consistent(model) - - if acados_ocp.solver_options.hessian_approx == 'EXACT': - opts = dict(generate_hess=1) - else: - opts = dict(generate_hess=0) - - # create code_export_dir, model_dir - code_export_dir = acados_ocp.code_export_directory - opts['code_export_directory'] = code_export_dir - model_dir = os.path.join(code_export_dir, model.name + '_model') - if not os.path.exists(model_dir): - os.makedirs(model_dir) - - check_casadi_version() - # TODO: remove dir gen from all the generate_c_* functions - if acados_ocp.model.dyn_ext_fun_type == 'casadi': - if acados_ocp.solver_options.integrator_type == 'ERK': - generate_c_code_explicit_ode(model, opts) - elif acados_ocp.solver_options.integrator_type == 'IRK': - generate_c_code_implicit_ode(model, opts) - elif acados_ocp.solver_options.integrator_type == 'LIFTED_IRK': - generate_c_code_implicit_ode(model, opts) - elif acados_ocp.solver_options.integrator_type == 'GNSF': - generate_c_code_gnsf(model, opts) - elif acados_ocp.solver_options.integrator_type == 'DISCRETE': - generate_c_code_discrete_dynamics(model, opts) - else: - raise Exception("ocp_generate_external_functions: unknown integrator type.") - else: - target_location = os.path.join(code_export_dir, model_dir, model.dyn_generic_source) - shutil.copyfile(model.dyn_generic_source, target_location) - - if acados_ocp.dims.nphi > 0 or acados_ocp.dims.nh > 0: - generate_c_code_constraint(model, model.name, False, opts) - - if acados_ocp.dims.nphi_e > 0 or acados_ocp.dims.nh_e > 0: - generate_c_code_constraint(model, model.name, True, opts) - - if acados_ocp.cost.cost_type_0 == 'NONLINEAR_LS': - generate_c_code_nls_cost(model, model.name, 'initial', opts) - elif acados_ocp.cost.cost_type_0 == 'CONVEX_OVER_NONLINEAR': - generate_c_code_conl_cost(model, model.name, 'initial', opts) - elif acados_ocp.cost.cost_type_0 == 'EXTERNAL': - generate_c_code_external_cost(model, 'initial', opts) - - if acados_ocp.cost.cost_type == 'NONLINEAR_LS': - generate_c_code_nls_cost(model, model.name, 'path', opts) - elif acados_ocp.cost.cost_type == 'CONVEX_OVER_NONLINEAR': - generate_c_code_conl_cost(model, model.name, 'path', opts) - elif acados_ocp.cost.cost_type == 'EXTERNAL': - generate_c_code_external_cost(model, 'path', opts) - - if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': - generate_c_code_nls_cost(model, model.name, 'terminal', opts) - elif acados_ocp.cost.cost_type_e == 'CONVEX_OVER_NONLINEAR': - generate_c_code_conl_cost(model, model.name, 'terminal', opts) - elif acados_ocp.cost.cost_type_e == 'EXTERNAL': - generate_c_code_external_cost(model, 'terminal', opts) - - -def ocp_get_default_cmake_builder() -> CMakeBuilder: - """ - If :py:class:`~acados_template.acados_ocp_solver.AcadosOcpSolver` is used with `CMake` this function returns a good first setting. - :return: default :py:class:`~acados_template.builders.CMakeBuilder` - """ - cmake_builder = CMakeBuilder() - cmake_builder.options_on = ['BUILD_ACADOS_OCP_SOLVER_LIB'] - return cmake_builder - - - -def ocp_render_templates(acados_ocp: AcadosOcp, json_file, cmake_builder=None, simulink_opts=None): - - # setting up loader and environment - json_path = os.path.abspath(json_file) - - if not os.path.exists(json_path): - raise Exception(f'Path "{json_path}" not found!') - - # Render templates - template_list = __ocp_get_template_list(acados_ocp, cmake_builder=cmake_builder, simulink_opts=simulink_opts) - for tup in template_list: - if len(tup) > 2: - output_dir = tup[2] - else: - output_dir = acados_ocp.code_export_directory - render_template(tup[0], tup[1], output_dir, json_path) - - # Custom templates - acados_template_path = os.path.dirname(os.path.abspath(__file__)) - custom_template_glob = os.path.join(acados_template_path, 'custom_update_templates', '*') - for tup in acados_ocp.solver_options.custom_templates: - render_template(tup[0], tup[1], acados_ocp.code_export_directory, json_path, template_glob=custom_template_glob) - - return - - - -def __ocp_get_template_list(acados_ocp: AcadosOcp, cmake_builder=None, simulink_opts=None) -> list: - """ - returns a list of tuples in the form: - (input_filename, output_filname) - or - (input_filename, output_filname, output_directory) - """ - name = acados_ocp.model.name - code_export_directory = acados_ocp.code_export_directory - template_list = [] - - template_list.append(('main.in.c', f'main_{name}.c')) - template_list.append(('acados_solver.in.c', f'acados_solver_{name}.c')) - template_list.append(('acados_solver.in.h', f'acados_solver_{name}.h')) - template_list.append(('acados_solver.in.pxd', f'acados_solver.pxd')) - if cmake_builder is not None: - template_list.append(('CMakeLists.in.txt', 'CMakeLists.txt')) - else: - template_list.append(('Makefile.in', 'Makefile')) - - - # sim - template_list.append(('acados_sim_solver.in.c', f'acados_sim_solver_{name}.c')) - template_list.append(('acados_sim_solver.in.h', f'acados_sim_solver_{name}.h')) - template_list.append(('main_sim.in.c', f'main_sim_{name}.c')) - - # model - model_dir = os.path.join(code_export_directory, f'{name}_model') - template_list.append(('model.in.h', f'{name}_model.h', model_dir)) - # constraints - constraints_dir = os.path.join(code_export_directory, f'{name}_constraints') - template_list.append(('constraints.in.h', f'{name}_constraints.h', constraints_dir)) - # cost - cost_dir = os.path.join(code_export_directory, f'{name}_cost') - template_list.append(('cost.in.h', f'{name}_cost.h', cost_dir)) - - # Simulink - if simulink_opts is not None: - template_file = os.path.join('matlab_templates', 'acados_solver_sfun.in.c') - template_list.append((template_file, f'acados_solver_sfunction_{name}.c')) - template_file = os.path.join('matlab_templates', 'acados_solver_sfun.in.c') - template_list.append((template_file, f'make_sfun_{name}.m')) - - return template_list - - -def remove_x0_elimination(acados_ocp): - acados_ocp.constraints.idxbxe_0 = np.zeros((0,)) - acados_ocp.dims.nbxe_0 = 0 - - -class AcadosOcpSolver: - """ - Class to interact with the acados ocp solver C object. - - :param acados_ocp: type :py:class:`~acados_template.acados_ocp.AcadosOcp` - description of the OCP for acados - :param json_file: name for the json file used to render the templated code - default: acados_ocp_nlp.json - :param simulink_opts: Options to configure Simulink S-function blocks, mainly to activate possible Inputs and Outputs - """ - if sys.platform=="win32": - from ctypes import wintypes - from ctypes import WinDLL - dlclose = WinDLL('kernel32', use_last_error=True).FreeLibrary - dlclose.argtypes = [wintypes.HMODULE] - else: - dlclose = CDLL(None).dlclose - dlclose.argtypes = [c_void_p] - - @classmethod - def generate(cls, acados_ocp: AcadosOcp, json_file='acados_ocp_nlp.json', simulink_opts=None, cmake_builder: CMakeBuilder = None): - """ - Generates the code for an acados OCP solver, given the description in acados_ocp. - :param acados_ocp: type AcadosOcp - description of the OCP for acados - :param json_file: name for the json file used to render the templated code - default: `acados_ocp_nlp.json` - :param simulink_opts: Options to configure Simulink S-function blocks, mainly to activate possible inputs and - outputs; default: `None` - :param cmake_builder: type :py:class:`~acados_template.builders.CMakeBuilder` generate a `CMakeLists.txt` and use - the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with - `MS Visual Studio`); default: `None` - """ - model = acados_ocp.model - acados_ocp.code_export_directory = os.path.abspath(acados_ocp.code_export_directory) - - # make dims consistent - make_ocp_dims_consistent(acados_ocp) - - # module dependent post processing - if acados_ocp.solver_options.integrator_type == 'GNSF': - if 'gnsf_model' in acados_ocp.__dict__: - set_up_imported_gnsf_model(acados_ocp) - else: - detect_gnsf_structure(acados_ocp) - - if acados_ocp.solver_options.qp_solver == 'PARTIAL_CONDENSING_QPDUNES': - remove_x0_elimination(acados_ocp) - - # set integrator time automatically - acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] - - # generate external functions - ocp_generate_external_functions(acados_ocp, model) - - # dump to json - acados_ocp.json_file = json_file - ocp_formulation_json_dump(acados_ocp, simulink_opts=simulink_opts, json_file=json_file) - - # render templates - ocp_render_templates(acados_ocp, json_file, cmake_builder=cmake_builder, simulink_opts=simulink_opts) - - # copy custom update function - if acados_ocp.solver_options.custom_update_filename != "" and acados_ocp.solver_options.custom_update_copy: - target_location = os.path.join(acados_ocp.code_export_directory, acados_ocp.solver_options.custom_update_filename) - shutil.copyfile(acados_ocp.solver_options.custom_update_filename, target_location) - if acados_ocp.solver_options.custom_update_header_filename != "" and acados_ocp.solver_options.custom_update_copy: - target_location = os.path.join(acados_ocp.code_export_directory, acados_ocp.solver_options.custom_update_header_filename) - shutil.copyfile(acados_ocp.solver_options.custom_update_header_filename, target_location) - - - @classmethod - def build(cls, code_export_dir, with_cython=False, cmake_builder: CMakeBuilder = None, verbose: bool = True): - """ - Builds the code for an acados OCP solver, that has been generated in code_export_dir - :param code_export_dir: directory in which acados OCP solver has been generated, see generate() - :param with_cython: option indicating if the cython interface is build, default: False. - :param cmake_builder: type :py:class:`~acados_template.builders.CMakeBuilder` generate a `CMakeLists.txt` and use - the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with - `MS Visual Studio`); default: `None` - :param verbose: indicating if build command is printed - """ - code_export_dir = os.path.abspath(code_export_dir) - cwd = os.getcwd() - os.chdir(code_export_dir) - if with_cython: - call( - ['make', 'clean_all'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - call( - ['make', 'ocp_cython'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - else: - if cmake_builder is not None: - cmake_builder.exec(code_export_dir) - else: - call( - ['make', 'clean_ocp_shared_lib'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - call( - ['make', 'ocp_shared_lib'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - os.chdir(cwd) - - - @classmethod - def create_cython_solver(cls, json_file): - """ - Returns an `AcadosOcpSolverCython` object. - - This is an alternative Cython based Python wrapper to the acados OCP solver in C. - This offers faster interaction with the solver, because getter and setter calls, which include shape checking are done in compiled C code. - - The default wrapper `AcadosOcpSolver` is based on ctypes. - """ - with open(json_file, 'r') as f: - acados_ocp_json = json.load(f) - code_export_directory = acados_ocp_json['code_export_directory'] - - importlib.invalidate_caches() - rel_code_export_directory = os.path.relpath(code_export_directory) - acados_ocp_solver_pyx = importlib.import_module(f'{rel_code_export_directory}.acados_ocp_solver_pyx') - - AcadosOcpSolverCython = getattr(acados_ocp_solver_pyx, 'AcadosOcpSolverCython') - return AcadosOcpSolverCython(acados_ocp_json['model']['name'], - acados_ocp_json['solver_options']['nlp_solver_type'], - acados_ocp_json['dims']['N']) - - - def __init__(self, acados_ocp: AcadosOcp, json_file='acados_ocp_nlp.json', simulink_opts=None, build=True, generate=True, cmake_builder: CMakeBuilder = None, verbose=True): - - self.solver_created = False - if generate: - self.generate(acados_ocp, json_file=json_file, simulink_opts=simulink_opts, cmake_builder=cmake_builder) - - # load json, store options in object - with open(json_file, 'r') as f: - acados_ocp_json = json.load(f) - self.N = acados_ocp_json['dims']['N'] - self.model_name = acados_ocp_json['model']['name'] - self.solver_options = acados_ocp_json['solver_options'] - - acados_lib_path = acados_ocp_json['acados_lib_path'] - code_export_directory = acados_ocp_json['code_export_directory'] - - if build: - self.build(code_export_directory, with_cython=False, cmake_builder=cmake_builder, verbose=verbose) - - # prepare library loading - lib_prefix = 'lib' - lib_ext = get_lib_ext() - if os.name == 'nt': - lib_prefix = '' - - # Load acados library to avoid unloading the library. - # This is necessary if acados was compiled with OpenMP, since the OpenMP threads can't be destroyed. - # Unloading a library which uses OpenMP results in a segfault (on any platform?). - # see [https://stackoverflow.com/questions/34439956/vc-crash-when-freeing-a-dll-built-with-openmp] - # or [https://python.hotexamples.com/examples/_ctypes/-/dlclose/python-dlclose-function-examples.html] - libacados_name = f'{lib_prefix}acados{lib_ext}' - libacados_filepath = os.path.join(acados_lib_path, libacados_name) - self.__acados_lib = CDLL(libacados_filepath) - # find out if acados was compiled with OpenMP - try: - self.__acados_lib_uses_omp = getattr(self.__acados_lib, 'omp_get_thread_num') is not None - except AttributeError as e: - self.__acados_lib_uses_omp = False - if self.__acados_lib_uses_omp: - print('acados was compiled with OpenMP.') - else: - print('acados was compiled without OpenMP.') - libacados_ocp_solver_name = f'{lib_prefix}acados_ocp_solver_{self.model_name}{lib_ext}' - self.shared_lib_name = os.path.join(code_export_directory, libacados_ocp_solver_name) - - # get shared_lib - self.shared_lib = CDLL(self.shared_lib_name) - - # create capsule - getattr(self.shared_lib, f"{self.model_name}_acados_create_capsule").restype = c_void_p - self.capsule = getattr(self.shared_lib, f"{self.model_name}_acados_create_capsule")() - - # create solver - getattr(self.shared_lib, f"{self.model_name}_acados_create").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_create").restype = c_int - assert getattr(self.shared_lib, f"{self.model_name}_acados_create")(self.capsule)==0 - self.solver_created = True - - self.acados_ocp = acados_ocp - - # get pointers solver - self.__get_pointers_solver() - - self.status = 0 - - # gettable fields - self.__qp_dynamics_fields = ['A', 'B', 'b'] - self.__qp_cost_fields = ['Q', 'R', 'S', 'q', 'r'] - self.__qp_constraint_fields = ['C', 'D', 'lg', 'ug', 'lbx', 'ubx', 'lbu', 'ubu'] - - - def __get_pointers_solver(self): - # """ - # Private function to get the pointers for solver - # """ - # get pointers solver - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_opts").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_opts").restype = c_void_p - self.nlp_opts = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_opts")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_dims").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_dims").restype = c_void_p - self.nlp_dims = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_dims")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_config").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_config").restype = c_void_p - self.nlp_config = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_config")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_out").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_out").restype = c_void_p - self.nlp_out = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_out")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out").restype = c_void_p - self.sens_out = getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in").restype = c_void_p - self.nlp_in = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_solver").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_solver").restype = c_void_p - self.nlp_solver = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_solver")(self.capsule) - - - - def solve_for_x0(self, x0_bar): - """ - Wrapper around `solve()` which sets initial state constraint, solves the OCP, and returns u0. - """ - self.set(0, "lbx", x0_bar) - self.set(0, "ubx", x0_bar) - - status = self.solve() - - if status == 2: - print("Warning: acados_ocp_solver reached maximum iterations.") - elif status != 0: - raise Exception(f'acados acados_ocp_solver returned status {status}') - - u0 = self.get(0, "u") - return u0 - - - def solve(self): - """ - Solve the ocp with current input. - """ - getattr(self.shared_lib, f"{self.model_name}_acados_solve").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_solve").restype = c_int - self.status = getattr(self.shared_lib, f"{self.model_name}_acados_solve")(self.capsule) - - return self.status - - - def custom_update(self, data_: np.ndarray): - """ - A custom function that can be implemented by a user to be called between solver calls. - By default this does nothing. - The idea is to have a convenient wrapper to do complex updates of parameters and numerical data efficiently in C, - in a function that is compiled into the solver library and can be conveniently used in the Python environment. - """ - data = np.ascontiguousarray(data_, dtype=np.float64) - c_data = cast(data.ctypes.data, POINTER(c_double)) - data_len = len(data) - - getattr(self.shared_lib, f"{self.model_name}_acados_custom_update").argtypes = [c_void_p, POINTER(c_double), c_int] - getattr(self.shared_lib, f"{self.model_name}_acados_custom_update").restype = c_int - status = getattr(self.shared_lib, f"{self.model_name}_acados_custom_update")(self.capsule, c_data, data_len) - - return status - - - def reset(self, reset_qp_solver_mem=1): - """ - Sets current iterate to all zeros. - """ - getattr(self.shared_lib, f"{self.model_name}_acados_reset").argtypes = [c_void_p, c_int] - getattr(self.shared_lib, f"{self.model_name}_acados_reset").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_reset")(self.capsule, reset_qp_solver_mem) - - return - - - def set_new_time_steps(self, new_time_steps): - """ - Set new time steps. - Recreates the solver if N changes. - - :param new_time_steps: 1 dimensional np array of new time steps for the solver - - .. note:: This allows for different use-cases: either set a new size of time_steps or a new distribution of - the shooting nodes without changing the number, e.g., to reach a different final time. Both cases - do not require a new code export and compilation. - """ - - # unlikely but still possible - if not self.solver_created: - raise Exception('Solver was not yet created!') - - # check if time steps really changed in value - if np.array_equal(self.solver_options['time_steps'], new_time_steps): - return - - N = new_time_steps.size - new_time_steps_data = cast(new_time_steps.ctypes.data, POINTER(c_double)) - - # check if recreation of acados is necessary (no need to recreate acados if sizes are identical) - if len(self.solver_options['time_steps']) == N: - getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps").argtypes = [c_void_p, c_int, c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps").restype = c_int - assert getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps")(self.capsule, N, new_time_steps_data) == 0 - else: # recreate the solver with the new time steps - self.solver_created = False - - # delete old memory (analog to __del__) - getattr(self.shared_lib, f"{self.model_name}_acados_free").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_free").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_free")(self.capsule) - - # create solver with new time steps - getattr(self.shared_lib, f"{self.model_name}_acados_create_with_discretization").argtypes = [c_void_p, c_int, c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_create_with_discretization").restype = c_int - assert getattr(self.shared_lib, f"{self.model_name}_acados_create_with_discretization")(self.capsule, N, new_time_steps_data) == 0 - - self.solver_created = True - - # get pointers solver - self.__get_pointers_solver() - - # store time_steps, N - self.solver_options['time_steps'] = new_time_steps - self.N = N - self.solver_options['Tsim'] = self.solver_options['time_steps'][0] - - - def update_qp_solver_cond_N(self, qp_solver_cond_N: int): - """ - Recreate solver with new value `qp_solver_cond_N` with a partial condensing QP solver. - This function is relevant for code reuse, i.e., if either `set_new_time_steps(...)` is used or - the influence of a different `qp_solver_cond_N` is studied without code export and compilation. - :param qp_solver_cond_N: new number of condensing stages for the solver - - .. note:: This function can only be used in combination with a partial condensing QP solver. - - .. note:: After `set_new_time_steps(...)` is used and depending on the new number of time steps it might be - necessary to change `qp_solver_cond_N` as well (using this function), i.e., typically - `qp_solver_cond_N < N`. - """ - # unlikely but still possible - if not self.solver_created: - raise Exception('Solver was not yet created!') - if self.N < qp_solver_cond_N: - raise Exception('Setting qp_solver_cond_N to be larger than N does not work!') - if self.solver_options['qp_solver_cond_N'] != qp_solver_cond_N: - self.solver_created = False - - # recreate the solver - fun_name = f'{self.model_name}_acados_update_qp_solver_cond_N' - getattr(self.shared_lib, fun_name).argtypes = [c_void_p, c_int] - getattr(self.shared_lib, fun_name).restype = c_int - assert getattr(self.shared_lib, fun_name)(self.capsule, qp_solver_cond_N) == 0 - - # store the new value - self.solver_options['qp_solver_cond_N'] = qp_solver_cond_N - self.solver_created = True - - # get pointers solver - self.__get_pointers_solver() - - - def eval_param_sens(self, index, stage=0, field="ex"): - """ - Calculate the sensitivity of the curent solution with respect to the initial state component of index - - :param index: integer corresponding to initial state index in range(nx) - """ - - field_ = field - field = field_.encode('utf-8') - - # checks - if not isinstance(index, int): - raise Exception('AcadosOcpSolver.eval_param_sens(): index must be Integer.') - - self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_void_p, c_int, c_char_p] - self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int - nx = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, 0, "x".encode('utf-8')) - - if index < 0 or index > nx: - raise Exception(f'AcadosOcpSolver.eval_param_sens(): index must be in [0, nx-1], got: {index}.') - - # actual eval_param - self.shared_lib.ocp_nlp_eval_param_sens.argtypes = [c_void_p, c_char_p, c_int, c_int, c_void_p] - self.shared_lib.ocp_nlp_eval_param_sens.restype = None - self.shared_lib.ocp_nlp_eval_param_sens(self.nlp_solver, field, stage, index, self.sens_out) - - return - - - def get(self, stage_, field_): - """ - Get the last solution of the solver: - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su',] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - - out_fields = ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su'] - # mem_fields = ['sl', 'su'] - sens_fields = ['sens_u', "sens_x"] - all_fields = out_fields + sens_fields - - field = field_ - - if (field_ not in all_fields): - raise Exception(f'AcadosOcpSolver.get(stage={stage_}, field={field_}): \'{field_}\' is an invalid argument.\ - \n Possible values are {all_fields}.') - - if not isinstance(stage_, int): - raise Exception(f'AcadosOcpSolver.get(stage={stage_}, field={field_}): stage index must be an integer, got type {type(stage_)}.') - - if stage_ < 0 or stage_ > self.N: - raise Exception(f'AcadosOcpSolver.get(stage={stage_}, field={field_}): stage index must be in [0, {self.N}], got: {stage_}.') - - if stage_ == self.N and field_ == 'pi': - raise Exception(f'AcadosOcpSolver.get(stage={stage_}, field={field_}): field \'{field_}\' does not exist at final stage {stage_}.') - - if field_ in sens_fields: - field = field_.replace('sens_', '') - - field = field.encode('utf-8') - - self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p] - self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int - - dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field) - - out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - if (field_ in out_fields): - self.shared_lib.ocp_nlp_out_get.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_get(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field, out_data) - # elif field_ in mem_fields: - # self.shared_lib.ocp_nlp_get_at_stage.argtypes = \ - # [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - # self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \ - # self.nlp_dims, self.nlp_solver, stage_, field, out_data) - elif field_ in sens_fields: - self.shared_lib.ocp_nlp_out_get.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_get(self.nlp_config, \ - self.nlp_dims, self.sens_out, stage_, field, out_data) - - return out - - - def print_statistics(self): - """ - prints statistics of previous solver run as a table: - - iter: iteration number - - res_stat: stationarity residual - - res_eq: residual wrt equality constraints (dynamics) - - res_ineq: residual wrt inequality constraints (constraints) - - res_comp: residual wrt complementarity conditions - - qp_stat: status of QP solver - - qp_iter: number of QP iterations - - alpha: SQP step size - - qp_res_stat: stationarity residual of the last QP solution - - qp_res_eq: residual wrt equality constraints (dynamics) of the last QP solution - - qp_res_ineq: residual wrt inequality constraints (constraints) of the last QP solution - - qp_res_comp: residual wrt complementarity conditions of the last QP solution - """ - stat = self.get_stats("statistics") - - if self.solver_options['nlp_solver_type'] == 'SQP': - print('\niter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha') - if stat.shape[0]>8: - print('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp') - for jj in range(stat.shape[1]): - print(f'{int(stat[0][jj]):d}\t{stat[1][jj]:e}\t{stat[2][jj]:e}\t{stat[3][jj]:e}\t' + - f'{stat[4][jj]:e}\t{int(stat[5][jj]):d}\t{int(stat[6][jj]):d}\t{stat[7][jj]:e}\t') - if stat.shape[0]>8: - print('\t{:e}\t{:e}\t{:e}\t{:e}'.format( \ - stat[8][jj], stat[9][jj], stat[10][jj], stat[11][jj])) - print('\n') - elif self.solver_options['nlp_solver_type'] == 'SQP_RTI': - print('\niter\tqp_stat\tqp_iter') - if stat.shape[0]>3: - print('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp') - for jj in range(stat.shape[1]): - print('{:d}\t{:d}\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) - if stat.shape[0]>3: - print('\t{:e}\t{:e}\t{:e}\t{:e}'.format( \ - stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj])) - print('\n') - - return - - - def store_iterate(self, filename: str = '', overwrite=False): - """ - Stores the current iterate of the ocp solver in a json file. - - :param filename: if not set, use f'{self.model_name}_iterate.json' - :param overwrite: if false and filename exists add timestamp to filename - """ - if filename == '': - filename = f'{self.model_name}_iterate.json' - - if not overwrite: - # append timestamp - if os.path.isfile(filename): - filename = filename[:-5] - filename += datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S.%f') + '.json' - - # get iterate: - solution = dict() - - lN = len(str(self.N+1)) - for i in range(self.N+1): - i_string = f'{i:0{lN}d}' - solution['x_'+i_string] = self.get(i,'x') - solution['u_'+i_string] = self.get(i,'u') - solution['z_'+i_string] = self.get(i,'z') - solution['lam_'+i_string] = self.get(i,'lam') - solution['t_'+i_string] = self.get(i, 't') - solution['sl_'+i_string] = self.get(i, 'sl') - solution['su_'+i_string] = self.get(i, 'su') - if i < self.N: - solution['pi_'+i_string] = self.get(i,'pi') - - for k in list(solution.keys()): - if len(solution[k]) == 0: - del solution[k] - - # save - with open(filename, 'w') as f: - json.dump(solution, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - print("stored current iterate in ", os.path.join(os.getcwd(), filename)) - - - - def dump_last_qp_to_json(self, filename: str = '', overwrite=False): - """ - Dumps the latest QP data into a json file - - :param filename: if not set, use model_name + timestamp + '.json' - :param overwrite: if false and filename exists add timestamp to filename - """ - if filename == '': - filename = f'{self.model_name}_QP.json' - - if not overwrite: - # append timestamp - if os.path.isfile(filename): - filename = filename[:-5] - filename += datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S.%f') + '.json' - - # get QP data: - qp_data = dict() - - lN = len(str(self.N+1)) - for field in self.__qp_dynamics_fields: - for i in range(self.N): - qp_data[f'{field}_{i:0{lN}d}'] = self.get_from_qp_in(i,field) - - for field in self.__qp_constraint_fields + self.__qp_cost_fields: - for i in range(self.N+1): - qp_data[f'{field}_{i:0{lN}d}'] = self.get_from_qp_in(i,field) - - # remove empty fields - for k in list(qp_data.keys()): - if len(qp_data[k]) == 0: - del qp_data[k] - - # save - with open(filename, 'w') as f: - json.dump(qp_data, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - print("stored qp from solver memory in ", os.path.join(os.getcwd(), filename)) - - - - def load_iterate(self, filename): - """ - Loads the iterate stored in json file with filename into the ocp solver. - """ - if not os.path.isfile(filename): - raise Exception('load_iterate: failed, file does not exist: ' + os.path.join(os.getcwd(), filename)) - - with open(filename, 'r') as f: - solution = json.load(f) - - print(f"loading iterate {filename}") - for key in solution.keys(): - (field, stage) = key.split('_') - self.set(int(stage), field, np.array(solution[key])) - - - def get_stats(self, field_): - """ - Get the information of the last solver call. - - :param field: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter', 'residuals', 'qp_iter', 'alpha'] - - Available fileds: - - time_tot: total CPU time previous call - - time_lin: CPU time for linearization - - time_sim: CPU time for integrator - - time_sim_ad: CPU time for integrator contribution of external function calls - - time_sim_la: CPU time for integrator contribution of linear algebra - - time_qp: CPU time qp solution - - time_qp_solver_call: CPU time inside qp solver (without converting the QP) - - time_qp_xcond: time_glob: CPU time globalization - - time_solution_sensitivities: CPU time for previous call to eval_param_sens - - time_reg: CPU time regularization - - sqp_iter: number of SQP iterations - - qp_iter: vector of QP iterations for last SQP call - - statistics: table with info about last iteration - - stat_m: number of rows in statistics matrix - - stat_n: number of columns in statistics matrix - - residuals: residuals of last iterate - - alpha: step sizes of SQP iterations - """ - - double_fields = ['time_tot', - 'time_lin', - 'time_sim', - 'time_sim_ad', - 'time_sim_la', - 'time_qp', - 'time_qp_solver_call', - 'time_qp_xcond', - 'time_glob', - 'time_solution_sensitivities', - 'time_reg' - ] - fields = double_fields + [ - 'sqp_iter', - 'qp_iter', - 'statistics', - 'stat_m', - 'stat_n', - 'residuals', - 'alpha', - ] - field = field_.encode('utf-8') - - - if field_ in ['sqp_iter', 'stat_m', 'stat_n']: - out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) - out_data = cast(out.ctypes.data, POINTER(c_int64)) - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - return out - - # TODO: just return double instead of np. - elif field_ in double_fields: - out = np.zeros((1,)) - out_data = cast(out.ctypes.data, POINTER(c_double)) - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - return out - - elif field_ == 'statistics': - sqp_iter = self.get_stats("sqp_iter") - stat_m = self.get_stats("stat_m") - stat_n = self.get_stats("stat_n") - min_size = min([stat_m, sqp_iter+1]) - out = np.ascontiguousarray( - np.zeros((stat_n[0]+1, min_size[0])), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - return out - - elif field_ == 'qp_iter': - full_stats = self.get_stats('statistics') - if self.solver_options['nlp_solver_type'] == 'SQP': - return full_stats[6, :] - elif self.solver_options['nlp_solver_type'] == 'SQP_RTI': - return full_stats[2, :] - - elif field_ == 'alpha': - full_stats = self.get_stats('statistics') - if self.solver_options['nlp_solver_type'] == 'SQP': - return full_stats[7, :] - else: # self.solver_options['nlp_solver_type'] == 'SQP_RTI': - raise Exception("alpha values are not available for SQP_RTI") - - elif field_ == 'residuals': - return self.get_residuals() - - else: - raise Exception(f'AcadosOcpSolver.get_stats(): \'{field}\' is not a valid argument.' - + f'\n Possible values are {fields}.') - - - def get_cost(self): - """ - Returns the cost value of the current solution. - """ - # compute cost internally - self.shared_lib.ocp_nlp_eval_cost.argtypes = [c_void_p, c_void_p, c_void_p] - self.shared_lib.ocp_nlp_eval_cost(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output array - out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - # call getter - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - - field = "cost_value".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - return out[0] - - - def get_residuals(self, recompute=False): - """ - Returns an array of the form [res_stat, res_eq, res_ineq, res_comp]. - This residual has to be computed for SQP_RTI solver, since it is not available by default. - - - res_stat: stationarity residual - - res_eq: residual wrt equality constraints (dynamics) - - res_ineq: residual wrt inequality constraints (constraints) - - res_comp: residual wrt complementarity conditions - """ - # compute residuals if RTI - if self.solver_options['nlp_solver_type'] == 'SQP_RTI' or recompute: - self.shared_lib.ocp_nlp_eval_residuals.argtypes = [c_void_p, c_void_p, c_void_p] - self.shared_lib.ocp_nlp_eval_residuals(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output array - out = np.ascontiguousarray(np.zeros((4, 1)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - # call getters - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - - field = "res_stat".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - out_data = cast(out[1].ctypes.data, POINTER(c_double)) - field = "res_eq".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - out_data = cast(out[2].ctypes.data, POINTER(c_double)) - field = "res_ineq".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - out_data = cast(out[3].ctypes.data, POINTER(c_double)) - field = "res_comp".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - return out.flatten() - - - # Note: this function should not be used anymore, better use cost_set, constraints_set - def set(self, stage_, field_, value_): - """ - Set numerical data inside the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'pi', 'lam', 't', 'p', 'xdot_guess', 'z_guess'] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - cost_fields = ['y_ref', 'yref'] - constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] - out_fields = ['x', 'u', 'pi', 'lam', 't', 'z', 'sl', 'su'] - mem_fields = ['xdot_guess', 'z_guess'] - - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = value_.astype(float) - - field = field_.encode('utf-8') - - stage = c_int(stage_) - - # treat parameters separately - if field_ == 'p': - getattr(self.shared_lib, f"{self.model_name}_acados_update_params").argtypes = [c_void_p, c_int, POINTER(c_double), c_int] - getattr(self.shared_lib, f"{self.model_name}_acados_update_params").restype = c_int - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - - assert getattr(self.shared_lib, f"{self.model_name}_acados_update_params")(self.capsule, stage, value_data, value_.shape[0])==0 - else: - if field_ not in constraints_fields + cost_fields + out_fields + mem_fields: - raise Exception(f"AcadosOcpSolver.set(): '{field}' is not a valid argument.\n" - f" Possible values are {constraints_fields + cost_fields + out_fields + mem_fields + ['p']}.") - - self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p] - self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int - - dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field) - - if value_.shape[0] != dims: - msg = f'AcadosOcpSolver.set(): mismatching dimension for field "{field_}" ' - msg += f'with dimension {dims} (you have {value_.shape[0]})' - raise Exception(msg) - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - if field_ in constraints_fields: - self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - elif field_ in cost_fields: - self.shared_lib.ocp_nlp_cost_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - elif field_ in out_fields: - self.shared_lib.ocp_nlp_out_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_set(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, value_data_p) - elif field_ in mem_fields: - self.shared_lib.ocp_nlp_set.argtypes = \ - [c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value_data_p) - # also set z_guess, when setting z. - if field_ == 'z': - field = 'z_guess'.encode('utf-8') - self.shared_lib.ocp_nlp_set.argtypes = \ - [c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value_data_p) - return - - - def cost_set(self, stage_, field_, value_, api='warn'): - """ - Set numerical data in the cost module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string, e.g. 'yref', 'W', 'ext_cost_num_hess', 'zl', 'zu', 'Zl', 'Zu' - :param value: of appropriate size - """ - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = value_.astype(float) - - field = field_ - field = field.encode('utf-8') - - stage = c_int(stage_) - self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int - - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field, dims_data) - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - - elif len(value_shape) == 2: - if api=='old': - pass - elif api=='warn': - if not np.all(np.ravel(value_, order='F')==np.ravel(value_, order='K')): - raise Exception("Ambiguity in API detected.\n" - "Are you making an acados model from scrach? Add api='new' to cost_set and carry on.\n" - "Are you seeing this error suddenly in previously running code? Read on.\n" - f" You are relying on a now-fixed bug in cost_set for field '{field_}'.\n" + - " acados_template now correctly passes on any matrices to acados in column major format.\n" + - " Two options to fix this error: \n" + - " * Add api='old' to cost_set to restore old incorrect behaviour\n" + - " * Add api='new' to cost_set and remove any unnatural manipulation of the value argument " + - "such as non-mathematical transposes, reshaping, casting to fortran order, etc... " + - "If there is no such manipulation, then you have probably been getting an incorrect solution before.") - # Get elements in column major order - value_ = np.ravel(value_, order='F') - elif api=='new': - # Get elements in column major order - value_ = np.ravel(value_, order='F') - else: - raise Exception("Unknown api: '{}'".format(api)) - - if value_shape != tuple(dims): - raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension' + - f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - self.shared_lib.ocp_nlp_cost_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - - return - - - def constraints_set(self, stage_, field_, value_, api='warn'): - """ - Set numerical data in the constraint module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['lbx', 'ubx', 'lbu', 'ubu', 'lg', 'ug', 'lh', 'uh', 'uphi', 'C', 'D'] - :param value: of appropriate size - """ - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = value_.astype(float) - - field = field_ - field = field.encode('utf-8') - - stage = c_int(stage_) - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int - - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field, dims_data) - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - elif len(value_shape) == 2: - if api=='old': - pass - elif api=='warn': - if not np.all(np.ravel(value_, order='F')==np.ravel(value_, order='K')): - raise Exception("Ambiguity in API detected.\n" - "Are you making an acados model from scrach? Add api='new' to constraints_set and carry on.\n" - "Are you seeing this error suddenly in previously running code? Read on.\n" - f" You are relying on a now-fixed bug in constraints_set for field '{field}'.\n" + - " acados_template now correctly passes on any matrices to acados in column major format.\n" + - " Two options to fix this error: \n" + - " * Add api='old' to constraints_set to restore old incorrect behaviour\n" + - " * Add api='new' to constraints_set and remove any unnatural manipulation of the value argument " + - "such as non-mathematical transposes, reshaping, casting to fortran order, etc... " + - "If there is no such manipulation, then you have probably been getting an incorrect solution before.") - # Get elements in column major order - value_ = np.ravel(value_, order='F') - elif api=='new': - # Get elements in column major order - value_ = np.ravel(value_, order='F') - else: - raise Exception(f"Unknown api: '{api}'") - - if value_shape != tuple(dims): - raise Exception(f'AcadosOcpSolver.constraints_set(): mismatching dimension' + - f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - - return - - - def get_from_qp_in(self, stage_: int, field_: str): - """ - Get numerical data from the current QP. - - :param stage: integer corresponding to shooting node - :param field: string in ['A', 'B', 'b', 'Q', 'R', 'S', 'q', 'r', 'C', 'D', 'lg', 'ug', 'lbx', 'ubx', 'lbu', 'ubu'] - """ - # idx* should be added too.. - if not isinstance(stage_, int): - raise TypeError("stage should be int") - if stage_ > self.N: - raise Exception("stage should be <= self.N") - if field_ in self.__qp_dynamics_fields and stage_ >= self.N: - raise ValueError(f"dynamics field {field_} not available at terminal stage") - if field_ not in self.__qp_dynamics_fields + self.__qp_cost_fields + self.__qp_constraint_fields: - raise Exception(f"field {field_} not supported.") - - field = field_.encode('utf-8') - stage = c_int(stage_) - - # get dims - self.shared_lib.ocp_nlp_qp_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_qp_dims_get_from_attr.restype = c_int - - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.ocp_nlp_qp_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field, dims_data) - - # create output data - out = np.ascontiguousarray(np.zeros((np.prod(dims),)), dtype=np.float64) - out = out.reshape(dims[0], dims[1], order='F') - - out_data = cast(out.ctypes.data, POINTER(c_double)) - out_data_p = cast((out_data), c_void_p) - - # call getter - self.shared_lib.ocp_nlp_get_at_stage.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \ - self.nlp_dims, self.nlp_solver, stage, field, out_data_p) - - return out - - - def options_set(self, field_, value_): - """ - Set options of the solver. - - :param field: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length', 'alpha_min', 'alpha_reduction', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0' - - :param value: of type int, float, string - - - qp_tol_stat: QP solver tolerance stationarity - - qp_tol_eq: QP solver tolerance equalities - - qp_tol_ineq: QP solver tolerance inequalities - - qp_tol_comp: QP solver tolerance complementarity - - qp_tau_min: for HPIPM QP solvers: minimum value of barrier parameter in HPIPM - - qp_mu0: for HPIPM QP solvers: initial value for complementarity slackness - - warm_start_first_qp: indicates if first QP in SQP is warm_started - """ - int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks', 'qp_warm_start', - 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'warm_start_first_qp'] - double_fields = ['step_length', 'tol_eq', 'tol_stat', 'tol_ineq', 'tol_comp', 'alpha_min', 'alpha_reduction', - 'eps_sufficient_descent', 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0'] - string_fields = ['globalization'] - - # check field availability and type - if field_ in int_fields: - if not isinstance(value_, int): - raise Exception(f'solver option \'{field_}\' must be of type int. You have {type(value_)}.') - else: - value_ctypes = c_int(value_) - - elif field_ in double_fields: - if not isinstance(value_, float): - raise Exception(f'solver option \'{field_}\' must be of type float. You have {type(value_)}.') - else: - value_ctypes = c_double(value_) - - elif field_ in string_fields: - if not isinstance(value_, str): - raise Exception(f'solver option \'{field_}\' must be of type str. You have {type(value_)}.') - else: - value_ctypes = value_.encode('utf-8') - else: - fields = ', '.join(int_fields + double_fields + string_fields) - raise Exception(f'AcadosOcpSolver.options_set() does not support field \'{field_}\'.\n'\ - f' Possible values are {fields}.') - - - if field_ == 'rti_phase': - if value_ < 0 or value_ > 2: - raise Exception('AcadosOcpSolver.options_set(): argument \'rti_phase\' can ' - 'take only values 0, 1, 2 for SQP-RTI-type solvers') - if self.solver_options['nlp_solver_type'] != 'SQP_RTI' and value_ > 0: - raise Exception('AcadosOcpSolver.options_set(): argument \'rti_phase\' can ' - 'take only value 0 for SQP-type solvers') - - # encode - field = field_ - field = field.encode('utf-8') - - # call C interface - if field_ in string_fields: - self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \ - [c_void_p, c_void_p, c_char_p, c_char_p] - self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \ - self.nlp_opts, field, value_ctypes) - else: - self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \ - [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \ - self.nlp_opts, field, byref(value_ctypes)) - return - - - def set_params_sparse(self, stage_, idx_values_, param_values_): - """ - set parameters of the solvers external function partially: - Pseudo: solver.param[idx_values_] = param_values_; - Parameters: - :param stage_: integer corresponding to shooting node - :param idx_values_: 0 based np array (or iterable) of integers: indices of parameter to be set - :param param_values_: new parameter values as numpy array - """ - - # if not isinstance(idx_values_, np.ndarray) or not issubclass(type(idx_values_[0]), np.integer): - # raise Exception('idx_values_ must be np.array of integers.') - - if not isinstance(param_values_, np.ndarray): - raise Exception('param_values_ must be np.array.') - elif np.float64 != param_values_.dtype: - raise TypeError('param_values_ must be np.array of float64.') - - if param_values_.shape[0] != len(idx_values_): - raise Exception(f'param_values_ and idx_values_ must be of the same size.' + - f' Got sizes idx {param_values_.shape[0]}, param_values {len(idx_values_)}.') - - if any(idx_values_ >= self.acados_ocp.dims.np): - raise Exception(f'idx_values_ contains value >= np = {self.acados_ocp.dims.np}') - - stage = c_int(stage_) - n_update = c_int(len(param_values_)) - - param_data = cast(param_values_.ctypes.data, POINTER(c_double)) - c_idx_values = np.ascontiguousarray(idx_values_, dtype=np.intc) - idx_data = cast(c_idx_values.ctypes.data, POINTER(c_int)) - - getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse").argtypes = \ - [c_void_p, c_int, POINTER(c_int), POINTER(c_double), c_int] - getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse") \ - (self.capsule, stage, idx_data, param_data, n_update) - - def __del__(self): - if self.solver_created: - getattr(self.shared_lib, f"{self.model_name}_acados_free").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_free").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_free")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_free_capsule").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_free_capsule").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_free_capsule")(self.capsule) - - try: - self.dlclose(self.shared_lib._handle) - except: - print(f"WARNING: acados Python interface could not close shared_lib handle of AcadosOcpSolver {self.model_name}.\n", - "Attempting to create a new one with the same name will likely result in the old one being used!") - pass diff --git a/third_party/acados/acados_template/acados_ocp_solver_pyx.pyx b/third_party/acados/acados_template/acados_ocp_solver_pyx.pyx deleted file mode 100644 index acd7f02d0a81ad..00000000000000 --- a/third_party/acados/acados_template/acados_ocp_solver_pyx.pyx +++ /dev/null @@ -1,795 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# -# cython: language_level=3 -# cython: profile=False -# distutils: language=c - -cimport cython -from libc cimport string - -cimport acados_solver_common -# TODO: make this import more clear? it is not a general solver, but problem specific. -cimport acados_solver - -cimport numpy as cnp - -import os -from datetime import datetime -import numpy as np - - -cdef class AcadosOcpSolverCython: - """ - Class to interact with the acados ocp solver C object. - """ - - cdef acados_solver.nlp_solver_capsule *capsule - cdef void *nlp_opts - cdef acados_solver_common.ocp_nlp_dims *nlp_dims - cdef acados_solver_common.ocp_nlp_config *nlp_config - cdef acados_solver_common.ocp_nlp_out *nlp_out - cdef acados_solver_common.ocp_nlp_out *sens_out - cdef acados_solver_common.ocp_nlp_in *nlp_in - cdef acados_solver_common.ocp_nlp_solver *nlp_solver - - cdef bint solver_created - - cdef str model_name - cdef int N - - cdef str nlp_solver_type - - def __cinit__(self, model_name, nlp_solver_type, N): - - self.solver_created = False - - self.N = N - self.model_name = model_name - self.nlp_solver_type = nlp_solver_type - - # create capsule - self.capsule = acados_solver.acados_create_capsule() - - # create solver - assert acados_solver.acados_create(self.capsule) == 0 - self.solver_created = True - - # get pointers solver - self.__get_pointers_solver() - - - def __get_pointers_solver(self): - """ - Private function to get the pointers for solver - """ - # get pointers solver - self.nlp_opts = acados_solver.acados_get_nlp_opts(self.capsule) - self.nlp_dims = acados_solver.acados_get_nlp_dims(self.capsule) - self.nlp_config = acados_solver.acados_get_nlp_config(self.capsule) - self.nlp_out = acados_solver.acados_get_nlp_out(self.capsule) - self.sens_out = acados_solver.acados_get_sens_out(self.capsule) - self.nlp_in = acados_solver.acados_get_nlp_in(self.capsule) - self.nlp_solver = acados_solver.acados_get_nlp_solver(self.capsule) - - - def solve_for_x0(self, x0_bar): - """ - Wrapper around `solve()` which sets initial state constraint, solves the OCP, and returns u0. - """ - self.set(0, "lbx", x0_bar) - self.set(0, "ubx", x0_bar) - - status = self.solve() - - if status == 2: - print("Warning: acados_ocp_solver reached maximum iterations.") - elif status != 0: - raise Exception(f'acados acados_ocp_solver returned status {status}') - - u0 = self.get(0, "u") - return u0 - - - def solve(self): - """ - Solve the ocp with current input. - """ - return acados_solver.acados_solve(self.capsule) - - - def reset(self, reset_qp_solver_mem=1): - """ - Sets current iterate to all zeros. - """ - return acados_solver.acados_reset(self.capsule, reset_qp_solver_mem) - - - def custom_update(self, data_): - """ - A custom function that can be implemented by a user to be called between solver calls. - By default this does nothing. - The idea is to have a convenient wrapper to do complex updates of parameters and numerical data efficiently in C, - in a function that is compiled into the solver library and can be conveniently used in the Python environment. - """ - data_len = len(data_) - cdef cnp.ndarray[cnp.float64_t, ndim=1] data = np.ascontiguousarray(data_, dtype=np.float64) - - return acados_solver.acados_custom_update(self.capsule, data.data, data_len) - - - def set_new_time_steps(self, new_time_steps): - """ - Set new time steps. - Recreates the solver if N changes. - - :param new_time_steps: 1 dimensional np array of new time steps for the solver - - .. note:: This allows for different use-cases: either set a new size of time-steps or a new distribution of - the shooting nodes without changing the number, e.g., to reach a different final time. Both cases - do not require a new code export and compilation. - """ - - raise NotImplementedError("AcadosOcpSolverCython: does not support set_new_time_steps() since it is only a prototyping feature") - # # unlikely but still possible - # if not self.solver_created: - # raise Exception('Solver was not yet created!') - - # ## check if time steps really changed in value - # # get time steps - # cdef cnp.ndarray[cnp.float64_t, ndim=1] old_time_steps = np.ascontiguousarray(np.zeros((self.N,)), dtype=np.float64) - # assert acados_solver.acados_get_time_steps(self.capsule, self.N, old_time_steps.data) - - # if np.array_equal(old_time_steps, new_time_steps): - # return - - # N = new_time_steps.size - # cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(new_time_steps, dtype=np.float64) - - # # check if recreation of acados is necessary (no need to recreate acados if sizes are identical) - # if len(old_time_steps) == N: - # assert acados_solver.acados_update_time_steps(self.capsule, N, value.data) == 0 - - # else: # recreate the solver with the new time steps - # self.solver_created = False - - # # delete old memory (analog to __del__) - # acados_solver.acados_free(self.capsule) - - # # create solver with new time steps - # assert acados_solver.acados_create_with_discretization(self.capsule, N, value.data) == 0 - - # self.solver_created = True - - # # get pointers solver - # self.__get_pointers_solver() - - # # store time_steps, N - # self.time_steps = new_time_steps - # self.N = N - - - def update_qp_solver_cond_N(self, qp_solver_cond_N: int): - """ - Recreate solver with new value `qp_solver_cond_N` with a partial condensing QP solver. - This function is relevant for code reuse, i.e., if either `set_new_time_steps(...)` is used or - the influence of a different `qp_solver_cond_N` is studied without code export and compilation. - :param qp_solver_cond_N: new number of condensing stages for the solver - - .. note:: This function can only be used in combination with a partial condensing QP solver. - - .. note:: After `set_new_time_steps(...)` is used and depending on the new number of time steps it might be - necessary to change `qp_solver_cond_N` as well (using this function), i.e., typically - `qp_solver_cond_N < N`. - """ - raise NotImplementedError("AcadosOcpSolverCython: does not support update_qp_solver_cond_N() since it is only a prototyping feature") - - # # unlikely but still possible - # if not self.solver_created: - # raise Exception('Solver was not yet created!') - # if self.N < qp_solver_cond_N: - # raise Exception('Setting qp_solver_cond_N to be larger than N does not work!') - # if self.qp_solver_cond_N != qp_solver_cond_N: - # self.solver_created = False - - # # recreate the solver - # acados_solver.acados_update_qp_solver_cond_N(self.capsule, qp_solver_cond_N) - - # # store the new value - # self.qp_solver_cond_N = qp_solver_cond_N - # self.solver_created = True - - # # get pointers solver - # self.__get_pointers_solver() - - - def eval_param_sens(self, index, stage=0, field="ex"): - """ - Calculate the sensitivity of the curent solution with respect to the initial state component of index - - :param index: integer corresponding to initial state index in range(nx) - """ - - field_ = field - field = field_.encode('utf-8') - - # checks - if not isinstance(index, int): - raise Exception('AcadosOcpSolverCython.eval_param_sens(): index must be Integer.') - - cdef int nx = acados_solver_common.ocp_nlp_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, 0, "x".encode('utf-8')) - - if index < 0 or index > nx: - raise Exception(f'AcadosOcpSolverCython.eval_param_sens(): index must be in [0, nx-1], got: {index}.') - - # actual eval_param - acados_solver_common.ocp_nlp_eval_param_sens(self.nlp_solver, field, stage, index, self.sens_out) - - return - - - def get(self, int stage, str field_): - """ - Get the last solution of the solver: - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su',] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - - out_fields = ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su'] - field = field_.encode('utf-8') - - if field_ not in out_fields: - raise Exception('AcadosOcpSolverCython.get(): {} is an invalid argument.\ - \n Possible values are {}.'.format(field_, out_fields)) - - if stage < 0 or stage > self.N: - raise Exception('AcadosOcpSolverCython.get(): stage index must be in [0, N], got: {}.'.format(self.N)) - - if stage == self.N and field_ == 'pi': - raise Exception('AcadosOcpSolverCython.get(): field {} does not exist at final stage {}.'\ - .format(field_, stage)) - - cdef int dims = acados_solver_common.ocp_nlp_dims_get_from_attr(self.nlp_config, - self.nlp_dims, self.nlp_out, stage, field) - - cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.zeros((dims,)) - acados_solver_common.ocp_nlp_out_get(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, out.data) - - return out - - - def print_statistics(self): - """ - prints statistics of previous solver run as a table: - - iter: iteration number - - res_stat: stationarity residual - - res_eq: residual wrt equality constraints (dynamics) - - res_ineq: residual wrt inequality constraints (constraints) - - res_comp: residual wrt complementarity conditions - - qp_stat: status of QP solver - - qp_iter: number of QP iterations - - qp_res_stat: stationarity residual of the last QP solution - - qp_res_eq: residual wrt equality constraints (dynamics) of the last QP solution - - qp_res_ineq: residual wrt inequality constraints (constraints) of the last QP solution - - qp_res_comp: residual wrt complementarity conditions of the last QP solution - """ - acados_solver.acados_print_stats(self.capsule) - - - def store_iterate(self, filename='', overwrite=False): - """ - Stores the current iterate of the ocp solver in a json file. - - :param filename: if not set, use model_name + timestamp + '.json' - :param overwrite: if false and filename exists add timestamp to filename - """ - import json - if filename == '': - filename += self.model_name + '_' + 'iterate' + '.json' - - if not overwrite: - # append timestamp - if os.path.isfile(filename): - filename = filename[:-5] - filename += datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S.%f') + '.json' - - # get iterate: - solution = dict() - - lN = len(str(self.N+1)) - for i in range(self.N+1): - i_string = f'{i:0{lN}d}' - solution['x_'+i_string] = self.get(i,'x') - solution['u_'+i_string] = self.get(i,'u') - solution['z_'+i_string] = self.get(i,'z') - solution['lam_'+i_string] = self.get(i,'lam') - solution['t_'+i_string] = self.get(i, 't') - solution['sl_'+i_string] = self.get(i, 'sl') - solution['su_'+i_string] = self.get(i, 'su') - if i < self.N: - solution['pi_'+i_string] = self.get(i,'pi') - - for k in list(solution.keys()): - if len(solution[k]) == 0: - del solution[k] - - # save - with open(filename, 'w') as f: - json.dump(solution, f, default=lambda x: x.tolist(), indent=4, sort_keys=True) - print("stored current iterate in ", os.path.join(os.getcwd(), filename)) - - - def load_iterate(self, filename): - """ - Loads the iterate stored in json file with filename into the ocp solver. - """ - import json - if not os.path.isfile(filename): - raise Exception('load_iterate: failed, file does not exist: ' + os.path.join(os.getcwd(), filename)) - - with open(filename, 'r') as f: - solution = json.load(f) - - for key in solution.keys(): - (field, stage) = key.split('_') - self.set(int(stage), field, np.array(solution[key])) - - - def get_stats(self, field_): - """ - Get the information of the last solver call. - - :param field: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] - Available fileds: - - time_tot: total CPU time previous call - - time_lin: CPU time for linearization - - time_sim: CPU time for integrator - - time_sim_ad: CPU time for integrator contribution of external function calls - - time_sim_la: CPU time for integrator contribution of linear algebra - - time_qp: CPU time qp solution - - time_qp_solver_call: CPU time inside qp solver (without converting the QP) - - time_qp_xcond: time_glob: CPU time globalization - - time_solution_sensitivities: CPU time for previous call to eval_param_sens - - time_reg: CPU time regularization - - sqp_iter: number of SQP iterations - - qp_iter: vector of QP iterations for last SQP call - - statistics: table with info about last iteration - - stat_m: number of rows in statistics matrix - - stat_n: number of columns in statistics matrix - - residuals: residuals of last iterate - - alpha: step sizes of SQP iterations - """ - - double_fields = ['time_tot', - 'time_lin', - 'time_sim', - 'time_sim_ad', - 'time_sim_la', - 'time_qp', - 'time_qp_solver_call', - 'time_qp_xcond', - 'time_glob', - 'time_solution_sensitivities', - 'time_reg' - ] - fields = double_fields + [ - 'sqp_iter', - 'qp_iter', - 'statistics', - 'stat_m', - 'stat_n', - 'residuals', - 'alpha', - ] - field = field_.encode('utf-8') - - if field_ in ['sqp_iter', 'stat_m', 'stat_n']: - return self.__get_stat_int(field) - - elif field_ in double_fields: - return self.__get_stat_double(field) - - elif field_ == 'statistics': - sqp_iter = self.get_stats("sqp_iter") - stat_m = self.get_stats("stat_m") - stat_n = self.get_stats("stat_n") - min_size = min([stat_m, sqp_iter+1]) - return self.__get_stat_matrix(field, stat_n+1, min_size) - - elif field_ == 'qp_iter': - full_stats = self.get_stats('statistics') - if self.nlp_solver_type == 'SQP': - return full_stats[6, :] - elif self.nlp_solver_type == 'SQP_RTI': - return full_stats[2, :] - - elif field_ == 'alpha': - full_stats = self.get_stats('statistics') - if self.nlp_solver_type == 'SQP': - return full_stats[7, :] - else: # self.nlp_solver_type == 'SQP_RTI': - raise Exception("alpha values are not available for SQP_RTI") - - elif field_ == 'residuals': - return self.get_residuals() - - else: - raise NotImplementedError("TODO!") - - - def __get_stat_int(self, field): - cdef int out - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &out) - return out - - def __get_stat_double(self, field): - cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.zeros((1,)) - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out.data) - return out - - def __get_stat_matrix(self, field, n, m): - cdef cnp.ndarray[cnp.float64_t, ndim=2] out_mat = np.ascontiguousarray(np.zeros((n, m)), dtype=np.float64) - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_mat.data) - return out_mat - - - def get_cost(self): - """ - Returns the cost value of the current solution. - """ - # compute cost internally - acados_solver_common.ocp_nlp_eval_cost(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output - cdef double out - - # call getter - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, "cost_value", &out) - - return out - - - def get_residuals(self, recompute=False): - """ - Returns an array of the form [res_stat, res_eq, res_ineq, res_comp]. - """ - # compute residuals if RTI - if self.nlp_solver_type == 'SQP_RTI' or recompute: - acados_solver_common.ocp_nlp_eval_residuals(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output array - cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.ascontiguousarray(np.zeros((4,), dtype=np.float64)) - cdef double double_value - - field = "res_stat".encode('utf-8') - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) - out[0] = double_value - - field = "res_eq".encode('utf-8') - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) - out[1] = double_value - - field = "res_ineq".encode('utf-8') - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) - out[2] = double_value - - field = "res_comp".encode('utf-8') - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) - out[3] = double_value - - return out - - - # Note: this function should not be used anymore, better use cost_set, constraints_set - def set(self, int stage, str field_, value_): - - """ - Set numerical data inside the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'pi', 'lam', 't', 'p'] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - if not isinstance(value_, np.ndarray): - raise Exception(f"set: value must be numpy array, got {type(value_)}.") - cost_fields = ['y_ref', 'yref'] - constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] - out_fields = ['x', 'u', 'pi', 'lam', 't', 'z', 'sl', 'su'] - mem_fields = ['xdot_guess', 'z_guess'] - - field = field_.encode('utf-8') - - cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(value_, dtype=np.float64) - - # treat parameters separately - if field_ == 'p': - assert acados_solver.acados_update_params(self.capsule, stage, value.data, value.shape[0]) == 0 - else: - if field_ not in constraints_fields + cost_fields + out_fields: - raise Exception("AcadosOcpSolverCython.set(): {} is not a valid argument.\ - \nPossible values are {}.".format(field, \ - constraints_fields + cost_fields + out_fields + ['p'])) - - dims = acados_solver_common.ocp_nlp_dims_get_from_attr(self.nlp_config, - self.nlp_dims, self.nlp_out, stage, field) - - if value_.shape[0] != dims: - msg = 'AcadosOcpSolverCython.set(): mismatching dimension for field "{}" '.format(field_) - msg += 'with dimension {} (you have {})'.format(dims, value_.shape[0]) - raise Exception(msg) - - if field_ in constraints_fields: - acados_solver_common.ocp_nlp_constraints_model_set(self.nlp_config, - self.nlp_dims, self.nlp_in, stage, field, value.data) - elif field_ in cost_fields: - acados_solver_common.ocp_nlp_cost_model_set(self.nlp_config, - self.nlp_dims, self.nlp_in, stage, field, value.data) - elif field_ in out_fields: - acados_solver_common.ocp_nlp_out_set(self.nlp_config, - self.nlp_dims, self.nlp_out, stage, field, value.data) - elif field_ in mem_fields: - acados_solver_common.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value.data) - - if field_ == 'z': - field = 'z_guess'.encode('utf-8') - acados_solver_common.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value.data) - return - - def cost_set(self, int stage, str field_, value_): - """ - Set numerical data in the cost module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string, e.g. 'yref', 'W', 'ext_cost_num_hess' - :param value: of appropriate size - """ - if not isinstance(value_, np.ndarray): - raise Exception(f"cost_set: value must be numpy array, got {type(value_)}.") - field = field_.encode('utf-8') - - cdef int dims[2] - acados_solver_common.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, &dims[0]) - - cdef double[::1,:] value - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - value = np.asfortranarray(value_[None,:]) - - elif len(value_shape) == 2: - # Get elements in column major order - value = np.asfortranarray(value_) - - if value_shape[0] != dims[0] or value_shape[1] != dims[1]: - raise Exception('AcadosOcpSolverCython.cost_set(): mismatching dimension' + - f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') - - acados_solver_common.ocp_nlp_cost_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, &value[0][0]) - - - def constraints_set(self, int stage, str field_, value_): - """ - Set numerical data in the constraint module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['lbx', 'ubx', 'lbu', 'ubu', 'lg', 'ug', 'lh', 'uh', 'uphi', 'C', 'D'] - :param value: of appropriate size - """ - if not isinstance(value_, np.ndarray): - raise Exception(f"constraints_set: value must be numpy array, got {type(value_)}.") - - field = field_.encode('utf-8') - - cdef int dims[2] - acados_solver_common.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, &dims[0]) - - cdef double[::1,:] value - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - value = np.asfortranarray(value_[None,:]) - - elif len(value_shape) == 2: - # Get elements in column major order - value = np.asfortranarray(value_) - - if value_shape != tuple(dims): - raise Exception(f'AcadosOcpSolverCython.constraints_set(): mismatching dimension' + - f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') - - acados_solver_common.ocp_nlp_constraints_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, &value[0][0]) - - return - - - def get_from_qp_in(self, int stage, str field_): - """ - Get numerical data from the dynamics module of the solver: - - :param stage: integer corresponding to shooting node - :param field: string, e.g. 'A' - """ - field = field_.encode('utf-8') - - # get dims - cdef int[2] dims - acados_solver_common.ocp_nlp_qp_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, stage, field, &dims[0]) - - # create output data - cdef cnp.ndarray[cnp.float64_t, ndim=2] out = np.zeros((dims[0], dims[1]), order='F') - - # call getter - acados_solver_common.ocp_nlp_get_at_stage(self.nlp_config, self.nlp_dims, self.nlp_solver, stage, field, out.data) - - return out - - - def options_set(self, str field_, value_): - """ - Set options of the solver. - - :param field: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length', 'alpha_min', 'alpha_reduction', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0' - - :param value: of type int, float, string - - - qp_tol_stat: QP solver tolerance stationarity - - qp_tol_eq: QP solver tolerance equalities - - qp_tol_ineq: QP solver tolerance inequalities - - qp_tol_comp: QP solver tolerance complementarity - - qp_tau_min: for HPIPM QP solvers: minimum value of barrier parameter in HPIPM - - qp_mu0: for HPIPM QP solvers: initial value for complementarity slackness - - warm_start_first_qp: indicates if first QP in SQP is warm_started - """ - int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'warm_start_first_qp'] - double_fields = ['step_length', 'tol_eq', 'tol_stat', 'tol_ineq', 'tol_comp', 'alpha_min', 'alpha_reduction', 'eps_sufficient_descent', - 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0'] - string_fields = ['globalization'] - - # encode - field = field_.encode('utf-8') - - cdef int int_value - cdef double double_value - cdef unsigned char[::1] string_value - - # check field availability and type - if field_ in int_fields: - if not isinstance(value_, int): - raise Exception('solver option {} must be of type int. You have {}.'.format(field_, type(value_))) - - if field_ == 'rti_phase': - if value_ < 0 or value_ > 2: - raise Exception('AcadosOcpSolverCython.solve(): argument \'rti_phase\' can ' - 'take only values 0, 1, 2 for SQP-RTI-type solvers') - if self.nlp_solver_type != 'SQP_RTI' and value_ > 0: - raise Exception('AcadosOcpSolverCython.solve(): argument \'rti_phase\' can ' - 'take only value 0 for SQP-type solvers') - - int_value = value_ - acados_solver_common.ocp_nlp_solver_opts_set(self.nlp_config, self.nlp_opts, field, &int_value) - - elif field_ in double_fields: - if not isinstance(value_, float): - raise Exception('solver option {} must be of type float. You have {}.'.format(field_, type(value_))) - - double_value = value_ - acados_solver_common.ocp_nlp_solver_opts_set(self.nlp_config, self.nlp_opts, field, &double_value) - - elif field_ in string_fields: - if not isinstance(value_, bytes): - raise Exception('solver option {} must be of type str. You have {}.'.format(field_, type(value_))) - - string_value = value_.encode('utf-8') - acados_solver_common.ocp_nlp_solver_opts_set(self.nlp_config, self.nlp_opts, field, &string_value[0]) - - else: - raise Exception('AcadosOcpSolverCython.options_set() does not support field {}.'\ - '\n Possible values are {}.'.format(field_, ', '.join(int_fields + double_fields + string_fields))) - - - def set_params_sparse(self, int stage, idx_values_, param_values_): - """ - set parameters of the solvers external function partially: - Pseudo: solver.param[idx_values_] = param_values_; - Parameters: - :param stage_: integer corresponding to shooting node - :param idx_values_: 0 based integer array corresponding to parameter indices to be set - :param param_values_: new parameter values as numpy array - """ - - if not isinstance(param_values_, np.ndarray): - raise Exception('param_values_ must be np.array.') - - if param_values_.shape[0] != len(idx_values_): - raise Exception(f'param_values_ and idx_values_ must be of the same size.' + - f' Got sizes idx {param_values_.shape[0]}, param_values {len(idx_values_)}.') - - # n_update = c_int(len(param_values_)) - - # param_data = cast(param_values_.ctypes.data, POINTER(c_double)) - # c_idx_values = np.ascontiguousarray(idx_values_, dtype=np.intc) - # idx_data = cast(c_idx_values.ctypes.data, POINTER(c_int)) - - # getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse").argtypes = \ - # [c_void_p, c_int, POINTER(c_int), POINTER(c_double), c_int] - # getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse").restype = c_int - # getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse") \ - # (self.capsule, stage, idx_data, param_data, n_update) - - cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(param_values_, dtype=np.float64) - # cdef cnp.ndarray[cnp.intc, ndim=1] idx = np.ascontiguousarray(idx_values_, dtype=np.intc) - - # NOTE: this does throw an error somehow: - # ValueError: Buffer dtype mismatch, expected 'int object' but got 'int' - # cdef cnp.ndarray[cnp.int, ndim=1] idx = np.ascontiguousarray(idx_values_, dtype=np.intc) - - cdef cnp.ndarray[cnp.int32_t, ndim=1] idx = np.ascontiguousarray(idx_values_, dtype=np.int32) - cdef int n_update = value.shape[0] - # print(f"in set_params_sparse Cython n_update {n_update}") - - assert acados_solver.acados_update_params_sparse(self.capsule, stage, idx.data, value.data, n_update) == 0 - return - - - def __del__(self): - if self.solver_created: - acados_solver.acados_free(self.capsule) - acados_solver.acados_free_capsule(self.capsule) diff --git a/third_party/acados/acados_template/acados_sim.py b/third_party/acados/acados_template/acados_sim.py deleted file mode 100644 index c0d6937a49a5a7..00000000000000 --- a/third_party/acados/acados_template/acados_sim.py +++ /dev/null @@ -1,367 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -import numpy as np -import os -from .acados_model import AcadosModel -from .utils import get_acados_path, get_lib_ext - -class AcadosSimDims: - """ - Class containing the dimensions of the model to be simulated. - """ - def __init__(self): - self.__nx = None - self.__nu = None - self.__nz = 0 - self.__np = 0 - - @property - def nx(self): - """:math:`n_x` - number of states. Type: int > 0""" - return self.__nx - - @property - def nz(self): - """:math:`n_z` - number of algebraic variables. Type: int >= 0""" - return self.__nz - - @property - def nu(self): - """:math:`n_u` - number of inputs. Type: int >= 0""" - return self.__nu - - @property - def np(self): - """:math:`n_p` - number of parameters. Type: int >= 0""" - return self.__np - - @nx.setter - def nx(self, nx): - if isinstance(nx, int) and nx > 0: - self.__nx = nx - else: - raise Exception('Invalid nx value, expected positive integer.') - - @nz.setter - def nz(self, nz): - if isinstance(nz, int) and nz > -1: - self.__nz = nz - else: - raise Exception('Invalid nz value, expected nonnegative integer.') - - @nu.setter - def nu(self, nu): - if isinstance(nu, int) and nu > -1: - self.__nu = nu - else: - raise Exception('Invalid nu value, expected nonnegative integer.') - - @np.setter - def np(self, np): - if isinstance(np, int) and np > -1: - self.__np = np - else: - raise Exception('Invalid np value, expected nonnegative integer.') - - def set(self, attr, value): - setattr(self, attr, value) - - -class AcadosSimOpts: - """ - class containing the solver options - """ - def __init__(self): - self.__integrator_type = 'ERK' - self.__collocation_type = 'GAUSS_LEGENDRE' - self.__Tsim = None - # ints - self.__sim_method_num_stages = 1 - self.__sim_method_num_steps = 1 - self.__sim_method_newton_iter = 3 - # doubles - self.__sim_method_newton_tol = 0.0 - # bools - self.__sens_forw = True - self.__sens_adj = False - self.__sens_algebraic = False - self.__sens_hess = False - self.__output_z = True - self.__sim_method_jac_reuse = 0 - self.__ext_fun_compile_flags = '-O2' - - @property - def integrator_type(self): - """Integrator type. Default: 'ERK'.""" - return self.__integrator_type - - @property - def num_stages(self): - """Number of stages in the integrator. Default: 1""" - return self.__sim_method_num_stages - - @property - def num_steps(self): - """Number of steps in the integrator. Default: 1""" - return self.__sim_method_num_steps - - @property - def newton_iter(self): - """Number of Newton iterations in simulation method. Default: 3""" - return self.__sim_method_newton_iter - - @property - def newton_tol(self): - """ - Tolerance for Newton system solved in implicit integrator (IRK, GNSF). - 0.0 means this is not used and exactly newton_iter iterations are carried out. - Default: 0.0 - """ - return self.__sim_method_newton_tol - - @property - def sens_forw(self): - """Boolean determining if forward sensitivities are computed. Default: True""" - return self.__sens_forw - - @property - def sens_adj(self): - """Boolean determining if adjoint sensitivities are computed. Default: False""" - return self.__sens_adj - - @property - def sens_algebraic(self): - """Boolean determining if sensitivities wrt algebraic variables are computed. Default: False""" - return self.__sens_algebraic - - @property - def sens_hess(self): - """Boolean determining if hessians are computed. Default: False""" - return self.__sens_hess - - @property - def output_z(self): - """Boolean determining if values for algebraic variables (corresponding to start of simulation interval) are computed. Default: True""" - return self.__output_z - - @property - def sim_method_jac_reuse(self): - """Integer determining if jacobians are reused (0 or 1). Default: 0""" - return self.__sim_method_jac_reuse - - @property - def T(self): - """Time horizon""" - return self.__Tsim - - @property - def collocation_type(self): - """Collocation type: relevant for implicit integrators - -- string in {GAUSS_RADAU_IIA, GAUSS_LEGENDRE} - - Default: GAUSS_LEGENDRE - """ - return self.__collocation_type - - @property - def ext_fun_compile_flags(self): - """ - String with compiler flags for external function compilation. - Default: '-O2'. - """ - return self.__ext_fun_compile_flags - - @ext_fun_compile_flags.setter - def ext_fun_compile_flags(self, ext_fun_compile_flags): - if isinstance(ext_fun_compile_flags, str): - self.__ext_fun_compile_flags = ext_fun_compile_flags - else: - raise Exception('Invalid ext_fun_compile_flags, expected a string.\n') - - @integrator_type.setter - def integrator_type(self, integrator_type): - integrator_types = ('ERK', 'IRK', 'GNSF') - if integrator_type in integrator_types: - self.__integrator_type = integrator_type - else: - raise Exception('Invalid integrator_type value. Possible values are:\n\n' \ - + ',\n'.join(integrator_types) + '.\n\nYou have: ' + integrator_type + '.\n\n') - - @collocation_type.setter - def collocation_type(self, collocation_type): - collocation_types = ('GAUSS_RADAU_IIA', 'GAUSS_LEGENDRE') - if collocation_type in collocation_types: - self.__collocation_type = collocation_type - else: - raise Exception('Invalid collocation_type value. Possible values are:\n\n' \ - + ',\n'.join(collocation_types) + '.\n\nYou have: ' + collocation_type + '.\n\n') - - @T.setter - def T(self, T): - self.__Tsim = T - - @num_stages.setter - def num_stages(self, num_stages): - if isinstance(num_stages, int): - self.__sim_method_num_stages = num_stages - else: - raise Exception('Invalid num_stages value. num_stages must be an integer.') - - @num_steps.setter - def num_steps(self, num_steps): - if isinstance(num_steps, int): - self.__sim_method_num_steps = num_steps - else: - raise Exception('Invalid num_steps value. num_steps must be an integer.') - - @newton_iter.setter - def newton_iter(self, newton_iter): - if isinstance(newton_iter, int): - self.__sim_method_newton_iter = newton_iter - else: - raise Exception('Invalid newton_iter value. newton_iter must be an integer.') - - @newton_tol.setter - def newton_tol(self, newton_tol): - if isinstance(newton_tol, float): - self.__sim_method_newton_tol = newton_tol - else: - raise Exception('Invalid newton_tol value. newton_tol must be an float.') - - @sens_forw.setter - def sens_forw(self, sens_forw): - if sens_forw in (True, False): - self.__sens_forw = sens_forw - else: - raise Exception('Invalid sens_forw value. sens_forw must be a Boolean.') - - @sens_adj.setter - def sens_adj(self, sens_adj): - if sens_adj in (True, False): - self.__sens_adj = sens_adj - else: - raise Exception('Invalid sens_adj value. sens_adj must be a Boolean.') - - @sens_hess.setter - def sens_hess(self, sens_hess): - if sens_hess in (True, False): - self.__sens_hess = sens_hess - else: - raise Exception('Invalid sens_hess value. sens_hess must be a Boolean.') - - @sens_algebraic.setter - def sens_algebraic(self, sens_algebraic): - if sens_algebraic in (True, False): - self.__sens_algebraic = sens_algebraic - else: - raise Exception('Invalid sens_algebraic value. sens_algebraic must be a Boolean.') - - @output_z.setter - def output_z(self, output_z): - if output_z in (True, False): - self.__output_z = output_z - else: - raise Exception('Invalid output_z value. output_z must be a Boolean.') - - @sim_method_jac_reuse.setter - def sim_method_jac_reuse(self, sim_method_jac_reuse): - if sim_method_jac_reuse in (0, 1): - self.__sim_method_jac_reuse = sim_method_jac_reuse - else: - raise Exception('Invalid sim_method_jac_reuse value. sim_method_jac_reuse must be 0 or 1.') - -class AcadosSim: - """ - The class has the following properties that can be modified to formulate a specific simulation problem, see below: - - :param acados_path: string with the path to acados. It is used to generate the include and lib paths. - - - :py:attr:`dims` of type :py:class:`acados_template.acados_ocp.AcadosSimDims` - are automatically detected from model - - :py:attr:`model` of type :py:class:`acados_template.acados_model.AcadosModel` - - :py:attr:`solver_options` of type :py:class:`acados_template.acados_sim.AcadosSimOpts` - - - :py:attr:`acados_include_path` (set automatically) - - :py:attr:`shared_lib_ext` (set automatically) - - :py:attr:`acados_lib_path` (set automatically) - - :py:attr:`parameter_values` - used to initialize the parameters (can be changed) - - """ - def __init__(self, acados_path=''): - if acados_path == '': - acados_path = get_acados_path() - self.dims = AcadosSimDims() - """Dimension definitions, automatically detected from :py:attr:`model`. Type :py:class:`acados_template.acados_sim.AcadosSimDims`""" - self.model = AcadosModel() - """Model definitions, type :py:class:`acados_template.acados_model.AcadosModel`""" - self.solver_options = AcadosSimOpts() - """Solver Options, type :py:class:`acados_template.acados_sim.AcadosSimOpts`""" - - self.acados_include_path = os.path.join(acados_path, 'include').replace(os.sep, '/') # the replace part is important on Windows for CMake - """Path to acados include directory (set automatically), type: `string`""" - self.acados_lib_path = os.path.join(acados_path, 'lib').replace(os.sep, '/') # the replace part is important on Windows for CMake - """Path to where acados library is located (set automatically), type: `string`""" - - self.code_export_directory = 'c_generated_code' - """Path to where code will be exported. Default: `c_generated_code`.""" - self.shared_lib_ext = get_lib_ext() - - # get cython paths - from sysconfig import get_paths - self.cython_include_dirs = [np.get_include(), get_paths()['include']] - - self.__parameter_values = np.array([]) - self.__problem_class = 'SIM' - - @property - def parameter_values(self): - """:math:`p` - initial values for parameter - can be updated""" - return self.__parameter_values - - @parameter_values.setter - def parameter_values(self, parameter_values): - if isinstance(parameter_values, np.ndarray): - self.__parameter_values = parameter_values - else: - raise Exception('Invalid parameter_values value. ' + - f'Expected numpy array, got {type(parameter_values)}.') - - def set(self, attr, value): - # tokenize string - tokens = attr.split('_', 1) - if len(tokens) > 1: - setter_to_call = getattr(getattr(self, tokens[0]), 'set') - else: - setter_to_call = getattr(self, 'set') - - setter_to_call(tokens[1], value) - - return diff --git a/third_party/acados/acados_template/acados_sim_layout.json b/third_party/acados/acados_template/acados_sim_layout.json deleted file mode 100644 index e3ca4b575b43d2..00000000000000 --- a/third_party/acados/acados_template/acados_sim_layout.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "acados_include_path": [ - "str" - ], - "model": { - "name" : [ - "str" - ] - }, - "acados_lib_path": [ - "str" - ], - "dims": { - "np": [ - "int" - ], - "nu": [ - "int" - ], - "nx": [ - "int" - ], - "nz": [ - "int" - ] - }, - "solver_options": { - "integrator_type": [ - "str" - ], - "collocation_type": [ - "str" - ], - "Tsim": [ - "float" - ], - "sim_method_num_stages": [ - "int" - ], - "sim_method_num_steps": [ - "int" - ], - "sim_method_newton_iter": [ - "int" - ], - "sim_method_newton_tol": [ - "float" - ], - "ext_fun_compile_flags": [ - "str" - ] - } -} diff --git a/third_party/acados/acados_template/acados_sim_solver.py b/third_party/acados/acados_template/acados_sim_solver.py deleted file mode 100644 index 612f439eaf7324..00000000000000 --- a/third_party/acados/acados_template/acados_sim_solver.py +++ /dev/null @@ -1,559 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -import sys -import os -import json -import importlib - -import numpy as np - -from subprocess import DEVNULL, call, STDOUT - -from ctypes import POINTER, cast, CDLL, c_void_p, c_char_p, c_double, c_int, c_bool, byref -from copy import deepcopy - -from .casadi_function_generation import generate_c_code_implicit_ode, generate_c_code_gnsf, generate_c_code_explicit_ode -from .acados_sim import AcadosSim -from .acados_ocp import AcadosOcp -from .utils import is_column, render_template, format_class_dict, make_object_json_dumpable,\ - make_model_consistent, set_up_imported_gnsf_model, get_python_interface_path, get_lib_ext,\ - casadi_length, is_empty, check_casadi_version -from .builders import CMakeBuilder -from .gnsf.detect_gnsf_structure import detect_gnsf_structure - - - -def make_sim_dims_consistent(acados_sim: AcadosSim): - dims = acados_sim.dims - model = acados_sim.model - # nx - if is_column(model.x): - dims.nx = casadi_length(model.x) - else: - raise Exception('model.x should be column vector!') - - # nu - if is_empty(model.u): - dims.nu = 0 - else: - dims.nu = casadi_length(model.u) - - # nz - if is_empty(model.z): - dims.nz = 0 - else: - dims.nz = casadi_length(model.z) - - # np - if is_empty(model.p): - dims.np = 0 - else: - dims.np = casadi_length(model.p) - if acados_sim.parameter_values.shape[0] != dims.np: - raise Exception('inconsistent dimension np, regarding model.p and parameter_values.' + \ - f'\nGot np = {dims.np}, acados_sim.parameter_values.shape = {acados_sim.parameter_values.shape[0]}\n') - - -def get_sim_layout(): - python_interface_path = get_python_interface_path() - abs_path = os.path.join(python_interface_path, 'acados_sim_layout.json') - with open(abs_path, 'r') as f: - sim_layout = json.load(f) - return sim_layout - - -def sim_formulation_json_dump(acados_sim: AcadosSim, json_file='acados_sim.json'): - # Load acados_sim structure description - sim_layout = get_sim_layout() - - # Copy input sim object dictionary - sim_dict = dict(deepcopy(acados_sim).__dict__) - - for key, v in sim_layout.items(): - # skip non dict attributes - if not isinstance(v, dict): continue - # Copy sim object attributes dictionaries - sim_dict[key]=dict(getattr(acados_sim, key).__dict__) - - sim_json = format_class_dict(sim_dict) - - with open(json_file, 'w') as f: - json.dump(sim_json, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - - -def sim_get_default_cmake_builder() -> CMakeBuilder: - """ - If :py:class:`~acados_template.acados_sim_solver.AcadosSimSolver` is used with `CMake` this function returns a good first setting. - :return: default :py:class:`~acados_template.builders.CMakeBuilder` - """ - cmake_builder = CMakeBuilder() - cmake_builder.options_on = ['BUILD_ACADOS_SIM_SOLVER_LIB'] - return cmake_builder - - -def sim_render_templates(json_file, model_name: str, code_export_dir, cmake_options: CMakeBuilder = None): - # setting up loader and environment - json_path = os.path.join(os.getcwd(), json_file) - - if not os.path.exists(json_path): - raise Exception(f"{json_path} not found!") - - # Render templates - in_file = 'acados_sim_solver.in.c' - out_file = f'acados_sim_solver_{model_name}.c' - render_template(in_file, out_file, code_export_dir, json_path) - - in_file = 'acados_sim_solver.in.h' - out_file = f'acados_sim_solver_{model_name}.h' - render_template(in_file, out_file, code_export_dir, json_path) - - in_file = 'acados_sim_solver.in.pxd' - out_file = f'acados_sim_solver.pxd' - render_template(in_file, out_file, code_export_dir, json_path) - - # Builder - if cmake_options is not None: - in_file = 'CMakeLists.in.txt' - out_file = 'CMakeLists.txt' - render_template(in_file, out_file, code_export_dir, json_path) - else: - in_file = 'Makefile.in' - out_file = 'Makefile' - render_template(in_file, out_file, code_export_dir, json_path) - - in_file = 'main_sim.in.c' - out_file = f'main_sim_{model_name}.c' - render_template(in_file, out_file, code_export_dir, json_path) - - # folder model - model_dir = os.path.join(code_export_dir, model_name + '_model') - - in_file = 'model.in.h' - out_file = f'{model_name}_model.h' - render_template(in_file, out_file, model_dir, json_path) - - -def sim_generate_external_functions(acados_sim: AcadosSim): - model = acados_sim.model - model = make_model_consistent(model) - - integrator_type = acados_sim.solver_options.integrator_type - - opts = dict(generate_hess = acados_sim.solver_options.sens_hess, - code_export_directory = acados_sim.code_export_directory) - - # create code_export_dir, model_dir - code_export_dir = acados_sim.code_export_directory - opts['code_export_directory'] = code_export_dir - model_dir = os.path.join(code_export_dir, model.name + '_model') - if not os.path.exists(model_dir): - os.makedirs(model_dir) - - # generate external functions - check_casadi_version() - if integrator_type == 'ERK': - generate_c_code_explicit_ode(model, opts) - elif integrator_type == 'IRK': - generate_c_code_implicit_ode(model, opts) - elif integrator_type == 'GNSF': - generate_c_code_gnsf(model, opts) - - -class AcadosSimSolver: - """ - Class to interact with the acados integrator C object. - - :param acados_sim: type :py:class:`~acados_template.acados_ocp.AcadosOcp` (takes values to generate an instance :py:class:`~acados_template.acados_sim.AcadosSim`) or :py:class:`~acados_template.acados_sim.AcadosSim` - :param json_file: Default: 'acados_sim.json' - :param build: Default: True - :param cmake_builder: type :py:class:`~acados_template.utils.CMakeBuilder` generate a `CMakeLists.txt` and use - the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with - `MS Visual Studio`); default: `None` - """ - if sys.platform=="win32": - from ctypes import wintypes - from ctypes import WinDLL - dlclose = WinDLL('kernel32', use_last_error=True).FreeLibrary - dlclose.argtypes = [wintypes.HMODULE] - else: - dlclose = CDLL(None).dlclose - dlclose.argtypes = [c_void_p] - - - @classmethod - def generate(cls, acados_sim: AcadosSim, json_file='acados_sim.json', cmake_builder: CMakeBuilder = None): - """ - Generates the code for an acados sim solver, given the description in acados_sim - """ - - acados_sim.code_export_directory = os.path.abspath(acados_sim.code_export_directory) - - # make dims consistent - make_sim_dims_consistent(acados_sim) - - # module dependent post processing - if acados_sim.solver_options.integrator_type == 'GNSF': - if acados_sim.solver_options.sens_hess == True: - raise Exception("AcadosSimSolver: GNSF does not support sens_hess = True.") - if 'gnsf_model' in acados_sim.__dict__: - set_up_imported_gnsf_model(acados_sim) - else: - detect_gnsf_structure(acados_sim) - - # generate external functions - sim_generate_external_functions(acados_sim) - - # dump to json - sim_formulation_json_dump(acados_sim, json_file) - - # render templates - sim_render_templates(json_file, acados_sim.model.name, acados_sim.code_export_directory, cmake_builder) - - - @classmethod - def build(cls, code_export_dir, with_cython=False, cmake_builder: CMakeBuilder = None, verbose: bool = True): - # Compile solver - cwd = os.getcwd() - os.chdir(code_export_dir) - if with_cython: - call( - ['make', 'clean_sim_cython'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - call( - ['make', 'sim_cython'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - else: - if cmake_builder is not None: - cmake_builder.exec(code_export_dir, verbose=verbose) - else: - call( - ['make', 'sim_shared_lib'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - os.chdir(cwd) - - - @classmethod - def create_cython_solver(cls, json_file): - """ - """ - with open(json_file, 'r') as f: - acados_sim_json = json.load(f) - code_export_directory = acados_sim_json['code_export_directory'] - - importlib.invalidate_caches() - rel_code_export_directory = os.path.relpath(code_export_directory) - acados_sim_solver_pyx = importlib.import_module(f'{rel_code_export_directory}.acados_sim_solver_pyx') - - AcadosSimSolverCython = getattr(acados_sim_solver_pyx, 'AcadosSimSolverCython') - return AcadosSimSolverCython(acados_sim_json['model']['name']) - - def __init__(self, acados_sim, json_file='acados_sim.json', generate=True, build=True, cmake_builder: CMakeBuilder = None, verbose: bool = True): - - self.solver_created = False - self.acados_sim = acados_sim - model_name = acados_sim.model.name - self.model_name = model_name - - code_export_dir = os.path.abspath(acados_sim.code_export_directory) - - # reuse existing json and casadi functions, when creating integrator from ocp - if generate and not isinstance(acados_sim, AcadosOcp): - self.generate(acados_sim, json_file=json_file, cmake_builder=cmake_builder) - - if build: - self.build(code_export_dir, cmake_builder=cmake_builder, verbose=True) - - # prepare library loading - lib_prefix = 'lib' - lib_ext = get_lib_ext() - if os.name == 'nt': - lib_prefix = '' - - # Load acados library to avoid unloading the library. - # This is necessary if acados was compiled with OpenMP, since the OpenMP threads can't be destroyed. - # Unloading a library which uses OpenMP results in a segfault (on any platform?). - # see [https://stackoverflow.com/questions/34439956/vc-crash-when-freeing-a-dll-built-with-openmp] - # or [https://python.hotexamples.com/examples/_ctypes/-/dlclose/python-dlclose-function-examples.html] - libacados_name = f'{lib_prefix}acados{lib_ext}' - libacados_filepath = os.path.join(acados_sim.acados_lib_path, libacados_name) - self.__acados_lib = CDLL(libacados_filepath) - # find out if acados was compiled with OpenMP - try: - self.__acados_lib_uses_omp = getattr(self.__acados_lib, 'omp_get_thread_num') is not None - except AttributeError as e: - self.__acados_lib_uses_omp = False - if self.__acados_lib_uses_omp: - print('acados was compiled with OpenMP.') - else: - print('acados was compiled without OpenMP.') - libacados_sim_solver_name = f'{lib_prefix}acados_sim_solver_{self.model_name}{lib_ext}' - self.shared_lib_name = os.path.join(code_export_dir, libacados_sim_solver_name) - - # get shared_lib - self.shared_lib = CDLL(self.shared_lib_name) - - # create capsule - getattr(self.shared_lib, f"{model_name}_acados_sim_solver_create_capsule").restype = c_void_p - self.capsule = getattr(self.shared_lib, f"{model_name}_acados_sim_solver_create_capsule")() - - # create solver - getattr(self.shared_lib, f"{model_name}_acados_sim_create").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_sim_create").restype = c_int - assert getattr(self.shared_lib, f"{model_name}_acados_sim_create")(self.capsule)==0 - self.solver_created = True - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_opts").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_opts").restype = c_void_p - self.sim_opts = getattr(self.shared_lib, f"{model_name}_acados_get_sim_opts")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_dims").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_dims").restype = c_void_p - self.sim_dims = getattr(self.shared_lib, f"{model_name}_acados_get_sim_dims")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_config").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_config").restype = c_void_p - self.sim_config = getattr(self.shared_lib, f"{model_name}_acados_get_sim_config")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_out").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_out").restype = c_void_p - self.sim_out = getattr(self.shared_lib, f"{model_name}_acados_get_sim_out")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_in").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_in").restype = c_void_p - self.sim_in = getattr(self.shared_lib, f"{model_name}_acados_get_sim_in")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_solver").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_solver").restype = c_void_p - self.sim_solver = getattr(self.shared_lib, f"{model_name}_acados_get_sim_solver")(self.capsule) - - self.gettable_vectors = ['x', 'u', 'z', 'S_adj'] - self.gettable_matrices = ['S_forw', 'Sx', 'Su', 'S_hess', 'S_algebraic'] - self.gettable_scalars = ['CPUtime', 'time_tot', 'ADtime', 'time_ad', 'LAtime', 'time_la'] - - - def simulate(self, x=None, u=None, z=None, p=None): - """ - Simulate the system forward for the given x, u, z, p and return x_next. - Wrapper around `solve()` taking care of setting/getting inputs/outputs. - """ - if x is not None: - self.set('x', x) - if u is not None: - self.set('u', u) - if z is not None: - self.set('z', z) - if p is not None: - self.set('p', p) - - status = self.solve() - - if status == 2: - print("Warning: acados_sim_solver reached maximum iterations.") - elif status != 0: - raise Exception(f'acados_sim_solver for model {self.model_name} returned status {status}.') - - x_next = self.get('x') - return x_next - - - def solve(self): - """ - Solve the simulation problem with current input. - """ - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solve").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solve").restype = c_int - - status = getattr(self.shared_lib, f"{self.model_name}_acados_sim_solve")(self.capsule) - return status - - - def get(self, field_): - """ - Get the last solution of the solver. - - :param str field: string in ['x', 'u', 'z', 'S_forw', 'Sx', 'Su', 'S_adj', 'S_hess', 'S_algebraic', 'CPUtime', 'time_tot', 'ADtime', 'time_ad', 'LAtime', 'time_la'] - """ - field = field_.encode('utf-8') - - if field_ in self.gettable_vectors: - # get dims - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.sim_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_int)] - self.shared_lib.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, dims_data) - - # allocate array - out = np.ascontiguousarray(np.zeros((dims[0],)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - self.shared_lib.sim_out_get.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out_data) - - elif field_ in self.gettable_matrices: - # get dims - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.sim_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_int)] - self.shared_lib.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, dims_data) - - out = np.zeros((dims[0], dims[1]), order='F') - out_data = cast(out.ctypes.data, POINTER(c_double)) - - self.shared_lib.sim_out_get.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out_data) - - elif field_ in self.gettable_scalars: - scalar = c_double() - scalar_data = byref(scalar) - self.shared_lib.sim_out_get.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, scalar_data) - - out = scalar.value - else: - raise Exception(f'AcadosSimSolver.get(): Unknown field {field_},' \ - f' available fields are {", ".join(self.gettable_vectors+self.gettable_matrices)}, {", ".join(self.gettable_scalars)}') - - return out - - - - def set(self, field_: str, value_): - """ - Set numerical data inside the solver. - - :param field: string in ['x', 'u', 'p', 'xdot', 'z', 'seed_adj', 'T'] - :param value: the value with appropriate size. - """ - settable = ['x', 'u', 'p', 'xdot', 'z', 'seed_adj', 'T'] # S_forw - - # TODO: check and throw error here. then remove checks in Cython for speed - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - - value_ = value_.astype(float) - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - field = field_.encode('utf-8') - - # treat parameters separately - if field_ == 'p': - model_name = self.acados_sim.model.name - getattr(self.shared_lib, f"{model_name}_acados_sim_update_params").argtypes = [c_void_p, POINTER(c_double), c_int] - value_data = cast(value_.ctypes.data, POINTER(c_double)) - getattr(self.shared_lib, f"{model_name}_acados_sim_update_params")(self.capsule, value_data, value_.shape[0]) - return - else: - # dimension check - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.sim_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_int)] - self.shared_lib.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, dims_data) - - value_ = np.ravel(value_, order='F') - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - - if value_shape != tuple(dims): - raise Exception(f'AcadosSimSolver.set(): mismatching dimension' \ - f' for field "{field_}" with dimension {tuple(dims)} (you have {value_shape}).') - - # set - if field_ in ['xdot', 'z']: - self.shared_lib.sim_solver_set.argtypes = [c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_solver_set(self.sim_solver, field, value_data_p) - elif field_ in settable: - self.shared_lib.sim_in_set.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_in_set(self.sim_config, self.sim_dims, self.sim_in, field, value_data_p) - else: - raise Exception(f'AcadosSimSolver.set(): Unknown field {field_},' \ - f' available fields are {", ".join(settable)}') - - return - - - def options_set(self, field_: str, value_: bool): - """ - Set solver options - - :param field: string in ['sens_forw', 'sens_adj', 'sens_hess'] - :param value: Boolean - """ - fields = ['sens_forw', 'sens_adj', 'sens_hess'] - if field_ not in fields: - raise Exception(f"field {field_} not supported. Supported values are {', '.join(fields)}.\n") - - field = field_.encode('utf-8') - value_ctypes = c_bool(value_) - - if not isinstance(value_, bool): - raise TypeError("options_set: expected boolean for value") - - # only allow setting - if getattr(self.acados_sim.solver_options, field_) or value_ == False: - self.shared_lib.sim_opts_set.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_bool)] - self.shared_lib.sim_opts_set(self.sim_config, self.sim_opts, field, value_ctypes) - else: - raise RuntimeError(f"Cannot set option {field_} to True, because it was False in original solver options.\n") - - return - - - def __del__(self): - - if self.solver_created: - getattr(self.shared_lib, f"{self.model_name}_acados_sim_free").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_sim_free").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_sim_free")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solver_free_capsule").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solver_free_capsule").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solver_free_capsule")(self.capsule) - - try: - self.dlclose(self.shared_lib._handle) - except: - print(f"WARNING: acados Python interface could not close shared_lib handle of AcadosSimSolver {self.model_name}.\n", - "Attempting to create a new one with the same name will likely result in the old one being used!") - pass diff --git a/third_party/acados/acados_template/acados_sim_solver_common.pxd b/third_party/acados/acados_template/acados_sim_solver_common.pxd deleted file mode 100644 index cc6a58efd77bb4..00000000000000 --- a/third_party/acados/acados_template/acados_sim_solver_common.pxd +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - - -cdef extern from "acados/sim/sim_common.h": - ctypedef struct sim_config: - pass - - ctypedef struct sim_opts: - pass - - ctypedef struct sim_in: - pass - - ctypedef struct sim_out: - pass - - -cdef extern from "acados_c/sim_interface.h": - - ctypedef struct sim_plan: - pass - - ctypedef struct sim_solver: - pass - - # out - void sim_out_get(sim_config *config, void *dims, sim_out *out, const char *field, void *value) - int sim_dims_get_from_attr(sim_config *config, void *dims, const char *field, void *dims_data) - - # opts - void sim_opts_set(sim_config *config, void *opts_, const char *field, void *value) - - # get/set - void sim_in_set(sim_config *config, void *dims, sim_in *sim_in, const char *field, void *value) - void sim_solver_set(sim_solver *solver, const char *field, void *value) \ No newline at end of file diff --git a/third_party/acados/acados_template/acados_sim_solver_pyx.pyx b/third_party/acados/acados_template/acados_sim_solver_pyx.pyx deleted file mode 100644 index be400addc7dd3a..00000000000000 --- a/third_party/acados/acados_template/acados_sim_solver_pyx.pyx +++ /dev/null @@ -1,256 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# -# cython: language_level=3 -# cython: profile=False -# distutils: language=c - -cimport cython -from libc cimport string -# from libc cimport bool as bool_t - -cimport acados_sim_solver_common -cimport acados_sim_solver - -cimport numpy as cnp - -import os -from datetime import datetime -import numpy as np - - -cdef class AcadosSimSolverCython: - """ - Class to interact with the acados sim solver C object. - """ - - cdef acados_sim_solver.sim_solver_capsule *capsule - cdef void *sim_dims - cdef acados_sim_solver_common.sim_opts *sim_opts - cdef acados_sim_solver_common.sim_config *sim_config - cdef acados_sim_solver_common.sim_out *sim_out - cdef acados_sim_solver_common.sim_in *sim_in - cdef acados_sim_solver_common.sim_solver *sim_solver - - cdef bint solver_created - - cdef str model_name - - cdef str sim_solver_type - - cdef list gettable_vectors - cdef list gettable_matrices - cdef list gettable_scalars - - def __cinit__(self, model_name): - - self.solver_created = False - - self.model_name = model_name - - # create capsule - self.capsule = acados_sim_solver.acados_sim_solver_create_capsule() - - # create solver - assert acados_sim_solver.acados_sim_create(self.capsule) == 0 - self.solver_created = True - - # get pointers solver - self.__get_pointers_solver() - - self.gettable_vectors = ['x', 'u', 'z', 'S_adj'] - self.gettable_matrices = ['S_forw', 'Sx', 'Su', 'S_hess', 'S_algebraic'] - self.gettable_scalars = ['CPUtime', 'time_tot', 'ADtime', 'time_ad', 'LAtime', 'time_la'] - - def __get_pointers_solver(self): - """ - Private function to get the pointers for solver - """ - # get pointers solver - self.sim_opts = acados_sim_solver.acados_get_sim_opts(self.capsule) - self.sim_dims = acados_sim_solver.acados_get_sim_dims(self.capsule) - self.sim_config = acados_sim_solver.acados_get_sim_config(self.capsule) - self.sim_out = acados_sim_solver.acados_get_sim_out(self.capsule) - self.sim_in = acados_sim_solver.acados_get_sim_in(self.capsule) - self.sim_solver = acados_sim_solver.acados_get_sim_solver(self.capsule) - - - def simulate(self, x=None, u=None, z=None, p=None): - """ - Simulate the system forward for the given x, u, z, p and return x_next. - Wrapper around `solve()` taking care of setting/getting inputs/outputs. - """ - if x is not None: - self.set('x', x) - if u is not None: - self.set('u', u) - if z is not None: - self.set('z', z) - if p is not None: - self.set('p', p) - - status = self.solve() - - if status == 2: - print("Warning: acados_sim_solver reached maximum iterations.") - elif status != 0: - raise Exception(f'acados_sim_solver for model {self.model_name} returned status {status}.') - - x_next = self.get('x') - return x_next - - - def solve(self): - """ - Solve the sim with current input. - """ - return acados_sim_solver.acados_sim_solve(self.capsule) - - - def get(self, field_): - """ - Get the last solution of the solver. - - :param str field: string in ['x', 'u', 'z', 'S_forw', 'Sx', 'Su', 'S_adj', 'S_hess', 'S_algebraic', 'CPUtime', 'time_tot', 'ADtime', 'time_ad', 'LAtime', 'time_la'] - """ - field = field_.encode('utf-8') - - if field_ in self.gettable_vectors: - return self.__get_vector(field) - elif field_ in self.gettable_matrices: - return self.__get_matrix(field) - elif field_ in self.gettable_scalars: - return self.__get_scalar(field) - else: - raise Exception(f'AcadosSimSolver.get(): Unknown field {field_},' \ - f' available fields are {", ".join(self.gettable.keys())}') - - - def __get_scalar(self, field): - cdef double scalar - acados_sim_solver_common.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, &scalar) - return scalar - - - def __get_vector(self, field): - cdef int[2] dims - acados_sim_solver_common.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, &dims[0]) - # cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.ascontiguousarray(np.zeros((dims[0],), dtype=np.float64)) - cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.zeros((dims[0]),) - acados_sim_solver_common.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out.data) - return out - - - def __get_matrix(self, field): - cdef int[2] dims - acados_sim_solver_common.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, &dims[0]) - cdef cnp.ndarray[cnp.float64_t, ndim=2] out = np.zeros((dims[0], dims[1]), order='F', dtype=np.float64) - acados_sim_solver_common.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out.data) - return out - - - def set(self, field_: str, value_): - """ - Set numerical data inside the solver. - - :param field: string in ['p', 'seed_adj', 'T', 'x', 'u', 'xdot', 'z'] - :param value: the value with appropriate size. - """ - settable = ['seed_adj', 'T', 'x', 'u', 'xdot', 'z', 'p'] # S_forw - - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - # if len(value_.shape) > 1: - # raise RuntimeError('AcadosSimSolverCython.set(): value_ should be 1 dimensional') - - cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(value_, dtype=np.float64).flatten() - - field = field_.encode('utf-8') - cdef int[2] dims - - # treat parameters separately - if field_ == 'p': - assert acados_sim_solver.acados_sim_update_params(self.capsule, value.data, value.shape[0]) == 0 - return - else: - acados_sim_solver_common.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, &dims[0]) - - value_ = np.ravel(value_, order='F') - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - - if value_shape != tuple(dims): - raise Exception(f'AcadosSimSolverCython.set(): mismatching dimension' \ - f' for field "{field_}" with dimension {tuple(dims)} (you have {value_shape}).') - - # set - if field_ in ['xdot', 'z']: - acados_sim_solver_common.sim_solver_set(self.sim_solver, field, value.data) - elif field_ in settable: - acados_sim_solver_common.sim_in_set(self.sim_config, self.sim_dims, self.sim_in, field, value.data) - else: - raise Exception(f'AcadosSimSolverCython.set(): Unknown field {field_},' \ - f' available fields are {", ".join(settable)}') - - - def options_set(self, field_: str, value_: bool): - """ - Set solver options - - :param field: string in ['sens_forw', 'sens_adj', 'sens_hess'] - :param value: Boolean - """ - fields = ['sens_forw', 'sens_adj', 'sens_hess'] - if field_ not in fields: - raise Exception(f"field {field_} not supported. Supported values are {', '.join(fields)}.\n") - - field = field_.encode('utf-8') - - if not isinstance(value_, bool): - raise TypeError("options_set: expected boolean for value") - - cdef bint bool_value = value_ - acados_sim_solver_common.sim_opts_set(self.sim_config, self.sim_opts, field, &bool_value) - # TODO: only allow setting - # if getattr(self.acados_sim.solver_options, field_) or value_ == False: - # acados_sim_solver_common.sim_opts_set(self.sim_config, self.sim_opts, field, &bool_value) - # else: - # raise RuntimeError(f"Cannot set option {field_} to True, because it was False in original solver options.\n") - - return - - - def __del__(self): - if self.solver_created: - acados_sim_solver.acados_sim_free(self.capsule) - acados_sim_solver.acados_sim_solver_free_capsule(self.capsule) diff --git a/third_party/acados/acados_template/acados_solver_common.pxd b/third_party/acados/acados_template/acados_solver_common.pxd deleted file mode 100644 index c6d59d40a501ef..00000000000000 --- a/third_party/acados/acados_template/acados_solver_common.pxd +++ /dev/null @@ -1,100 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - - -cdef extern from "acados/ocp_nlp/ocp_nlp_common.h": - ctypedef struct ocp_nlp_config: - pass - - ctypedef struct ocp_nlp_dims: - pass - - ctypedef struct ocp_nlp_in: - pass - - ctypedef struct ocp_nlp_out: - pass - - -cdef extern from "acados_c/ocp_nlp_interface.h": - ctypedef enum ocp_nlp_solver_t: - pass - - ctypedef enum ocp_nlp_cost_t: - pass - - ctypedef enum ocp_nlp_dynamics_t: - pass - - ctypedef enum ocp_nlp_constraints_t: - pass - - ctypedef enum ocp_nlp_reg_t: - pass - - ctypedef struct ocp_nlp_plan: - pass - - ctypedef struct ocp_nlp_solver: - pass - - int ocp_nlp_cost_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in_, - int start_stage, const char *field, void *value) - int ocp_nlp_constraints_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_in *in_, int stage, const char *field, void *value) - - # out - void ocp_nlp_out_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, void *value) - void ocp_nlp_out_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, void *value) - void ocp_nlp_get_at_stage(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_solver *solver, - int stage, const char *field, void *value) - int ocp_nlp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field) - void ocp_nlp_constraint_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out) - void ocp_nlp_cost_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out) - void ocp_nlp_qp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out) - - # opts - void ocp_nlp_solver_opts_set(ocp_nlp_config *config, void *opts_, const char *field, void* value) - - # solver - void ocp_nlp_eval_residuals(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out) - void ocp_nlp_eval_param_sens(ocp_nlp_solver *solver, char *field, int stage, int index, ocp_nlp_out *sens_nlp_out) - void ocp_nlp_eval_cost(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in_, ocp_nlp_out *nlp_out) - - # get/set - void ocp_nlp_get(ocp_nlp_config *config, ocp_nlp_solver *solver, const char *field, void *return_value_) - void ocp_nlp_set(ocp_nlp_config *config, ocp_nlp_solver *solver, int stage, const char *field, void *value) diff --git a/third_party/acados/acados_template/builders.py b/third_party/acados/acados_template/builders.py deleted file mode 100644 index 6f21bfe8cd2de2..00000000000000 --- a/third_party/acados/acados_template/builders.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, -# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, -# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, -# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -import os -import sys -from subprocess import DEVNULL, call, STDOUT - - -class CMakeBuilder: - """ - Class to work with the `CMake` build system. - """ - def __init__(self): - self._source_dir = None # private source directory, this is set to code_export_dir - self.build_dir = 'build' - self._build_dir = None # private build directory, usually rendered to abspath(build_dir) - self.generator = None - """Defines the generator, options can be found via `cmake --help` under 'Generator'. Type: string. Linux default 'Unix Makefiles', Windows 'Visual Studio 15 2017 Win64'; default value: `None`.""" - # set something for Windows - if os.name == 'nt': - self.generator = 'Visual Studio 15 2017 Win64' - self.build_targets = None - """A comma-separated list of the build targets, if `None` then all targets will be build; type: List of strings; default: `None`.""" - self.options_on = None - """List of strings as CMake options which are translated to '-D Opt[0]=ON -D Opt[1]=ON ...'; default: `None`.""" - - # Generate the command string for handling the cmake command. - def get_cmd1_cmake(self): - defines_str = '' - if self.options_on is not None: - defines_arr = [f' -D{opt}=ON' for opt in self.options_on] - defines_str = ' '.join(defines_arr) - generator_str = '' - if self.generator is not None: - generator_str = f' -G"{self.generator}"' - return f'cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="{self._source_dir}"{defines_str}{generator_str} -Wdev -S"{self._source_dir}" -B"{self._build_dir}"' - - # Generate the command string for handling the build. - def get_cmd2_build(self): - import multiprocessing - cmd = f'cmake --build "{self._build_dir}" --config Release -j{multiprocessing.cpu_count()}' - if self.build_targets is not None: - cmd += f' -t {self.build_targets}' - return cmd - - # Generate the command string for handling the install command. - def get_cmd3_install(self): - return f'cmake --install "{self._build_dir}"' - - def exec(self, code_export_directory, verbose=True): - """ - Execute the compilation using `CMake` with the given settings. - :param code_export_directory: must be the absolute path to the directory where the code was exported to - """ - if(os.path.isabs(code_export_directory) is False): - print(f'(W) the code export directory "{code_export_directory}" is not an absolute path!') - self._source_dir = code_export_directory - self._build_dir = os.path.abspath(self.build_dir) - try: - os.mkdir(self._build_dir) - except FileExistsError as e: - pass - - try: - os.chdir(self._build_dir) - cmd_str = self.get_cmd1_cmake() - print(f'call("{cmd_str})"') - retcode = call( - cmd_str, - shell=True, - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - if retcode != 0: - raise RuntimeError(f'CMake command "{cmd_str}" was terminated by signal {retcode}') - cmd_str = self.get_cmd2_build() - print(f'call("{cmd_str}")') - retcode = call( - cmd_str, - shell=True, - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - if retcode != 0: - raise RuntimeError(f'Build command "{cmd_str}" was terminated by signal {retcode}') - cmd_str = self.get_cmd3_install() - print(f'call("{cmd_str}")') - retcode = call( - cmd_str, - shell=True, - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - if retcode != 0: - raise RuntimeError(f'Install command "{cmd_str}" was terminated by signal {retcode}') - except OSError as e: - print("Execution failed:", e, file=sys.stderr) - except Exception as e: - print("Execution failed:", e, file=sys.stderr) - exit(1) diff --git a/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt b/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt deleted file mode 100644 index 99bc26f750c0b7..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt +++ /dev/null @@ -1,397 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -{%- if solver_options.qp_solver %} - {%- set qp_solver = solver_options.qp_solver %} -{%- else %} - {%- set qp_solver = "FULL_CONDENSING_HPIPM" %} -{%- endif %} - -{%- if solver_options.hessian_approx %} - {%- set hessian_approx = solver_options.hessian_approx %} -{%- elif solver_options.sens_hess %} - {%- set hessian_approx = "EXACT" %} -{%- else %} - {%- set hessian_approx = "GAUSS_NEWTON" %} -{%- endif %} - -{%- if constraints.constr_type %} - {%- set constr_type = constraints.constr_type %} -{%- else %} - {%- set constr_type = "NONE" %} -{%- endif %} - -{%- if constraints.constr_type_e %} - {%- set constr_type_e = constraints.constr_type_e %} -{%- else %} - {%- set constr_type_e = "NONE" %} -{%- endif %} - -{%- if cost.cost_type %} - {%- set cost_type = cost.cost_type %} -{%- else %} - {%- set cost_type = "NONE" %} -{%- endif %} - -{%- if cost.cost_type_e %} - {%- set cost_type_e = cost.cost_type_e %} -{%- else %} - {%- set cost_type_e = "NONE" %} -{%- endif %} - -{%- if cost.cost_type_0 %} - {%- set cost_type_0 = cost.cost_type_0 %} -{%- else %} - {%- set cost_type_0 = "NONE" %} -{%- endif %} - -{%- if dims.nh %} - {%- set dims_nh = dims.nh %} -{%- else %} - {%- set dims_nh = 0 %} -{%- endif %} - -{%- if dims.nphi %} - {%- set dims_nphi = dims.nphi %} -{%- else %} - {%- set dims_nphi = 0 %} -{%- endif %} - -{%- if dims.nh_e %} - {%- set dims_nh_e = dims.nh_e %} -{%- else %} - {%- set dims_nh_e = 0 %} -{%- endif %} - -{%- if dims.nphi_e %} - {%- set dims_nphi_e = dims.nphi_e %} -{%- else %} - {%- set dims_nphi_e = 0 %} -{%- endif %} - -{%- if solver_options.model_external_shared_lib_dir %} - {%- set model_external_shared_lib_dir = solver_options.model_external_shared_lib_dir %} -{%- endif %} - -{%- if solver_options.model_external_shared_lib_name %} - {%- set model_external_shared_lib_name = solver_options.model_external_shared_lib_name %} -{%- endif %} - -{#- control operator #} -{%- if os and os == "pc" %} - {%- set control = "&" %} -{%- else %} - {%- set control = ";" %} -{%- endif %} - -{%- if acados_link_libs and os and os == "pc" %}{# acados linking libraries and flags #} - {%- set link_libs = acados_link_libs.qpoases ~ " " ~ acados_link_libs.hpmpc ~ " " ~ acados_link_libs.osqp -%} - {%- set openmp_flag = acados_link_libs.openmp %} -{%- else %} - {%- set openmp_flag = " " %} - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - {%- set link_libs = "-lqpOASES_e" %} - {%- elif qp_solver == "FULL_CONDENSING_DAQP" %} - {%- set link_libs = "-ldaqp" %} - {%- else %} - {%- set link_libs = "" %} - {%- endif %} -{%- endif %} - -cmake_minimum_required(VERSION 3.13) - -project({{ model.name }}) - -# build options. -option(BUILD_ACADOS_SOLVER_LIB "Should the solver library acados_solver_{{ model.name }} be build?" OFF) -option(BUILD_ACADOS_OCP_SOLVER_LIB "Should the OCP solver library acados_ocp_solver_{{ model.name }} be build?" OFF) -option(BUILD_EXAMPLE "Should the example main_{{ model.name }} be build?" OFF) -{%- if solver_options.integrator_type != "DISCRETE" %} -option(BUILD_SIM_EXAMPLE "Should the simulation example main_sim_{{ model.name }} be build?" OFF) -option(BUILD_ACADOS_SIM_SOLVER_LIB "Should the simulation solver library acados_sim_solver_{{ model.name }} be build?" OFF) -{%- endif %} - - -if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND CMAKE_SYSTEM_NAME MATCHES "Windows") - # MinGW, change to .lib such that mex recognizes it - set(CMAKE_SHARED_LIBRARY_SUFFIX ".lib") - set(CMAKE_SHARED_LIBRARY_PREFIX "") -endif() - - -# object target names -set(MODEL_OBJ model_{{ model.name }}) -set(OCP_OBJ ocp_{{ model.name }}) -set(SIM_OBJ sim_{{ model.name }}) - -# model -set(MODEL_SRC - {%- if model.dyn_ext_fun_type == "casadi" %} -{%- if solver_options.integrator_type == "ERK" %} - {{ model.name }}_model/{{ model.name }}_expl_ode_fun.c - {{ model.name }}_model/{{ model.name }}_expl_vde_forw.c - {{ model.name }}_model/{{ model.name }}_expl_vde_adj.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_model/{{ model.name }}_expl_ode_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "IRK" %} - {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c - {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c - {{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "LIFTED_IRK" %} - {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c - {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_u.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c - {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c - {{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c - {% if model.gnsf.nontrivial_f_LO == 1 %} - {{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c - {%- endif %} - {%- endif %} - {{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c -{%- elif solver_options.integrator_type == "DISCRETE" %} - {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c - {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c - {%- endif %} -{%- endif -%} - {%- else %} - {{ model.name }}_model/{{ model.dyn_generic_source }} - {%- endif %} -) -add_library(${MODEL_OBJ} OBJECT ${MODEL_SRC} ) - -# optimal control problem - mostly CasADi exports -if(${BUILD_ACADOS_SOLVER_LIB} OR ${BUILD_ACADOS_OCP_SOLVER_LIB} OR ${BUILD_EXAMPLE}) - set(OCP_SRC -{%- if constr_type == "BGP" and dims_nphi > 0 %} - {{ model.name }}_constraints/{{ model.name }}_phi_constraint.c -{%- endif %} -{%- if constr_type_e == "BGP" and dims_nphi_e > 0 %} - {{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.c -{%- endif %} - -{%- if constr_type == "BGH" and dims_nh > 0 %} - {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.c - {{ model.name }}_constraints/{{ model.name }}_constr_h_fun.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c - {%- endif %} -{%- endif %} - -{%- if constr_type_e == "BGH" and dims_nh_e > 0 %} - {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.c - {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c - {%- endif %} -{%- endif %} - -{%- if cost_type_0 == "NONLINEAR_LS" %} - {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c - {{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c -{%- elif cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - {{ model.name }}_cost/{{ model.name }}_conl_cost_0_fun.c - {{ model.name }}_cost/{{ model.name }}_conl_cost_0_fun_jac_hess.c -{%- elif cost_type_0 == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_0 == "casadi" %} - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c - {%- else %} - {{ model.name }}_cost/{{ cost.cost_source_ext_cost_0 }} - {%- endif %} -{%- endif %} -{%- if cost_type == "NONLINEAR_LS" %} - {{ model.name }}_cost/{{ model.name }}_cost_y_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c - {{ model.name }}_cost/{{ model.name }}_cost_y_hess.c -{%- elif cost_type == "CONVEX_OVER_NONLINEAR" %} - {{ model.name }}_cost/{{ model.name }}_conl_cost_fun.c - {{ model.name }}_cost/{{ model.name }}_conl_cost_fun_jac_hess.c -{%- elif cost_type == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type == "casadi" %} - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c - {%- elif cost.cost_source_ext_cost != cost.cost_source_ext_cost_0 %} - {{ model.name }}_cost/{{ cost.cost_source_ext_cost }} - {%- endif %} -{%- endif %} -{%- if cost_type_e == "NONLINEAR_LS" %} - {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c - {{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c -{%- elif cost_type_e == "CONVEX_OVER_NONLINEAR" %} - {{ model.name }}_cost/{{ model.name }}_conl_cost_e_fun.c - {{ model.name }}_cost/{{ model.name }}_conl_cost_e_fun_jac_hess.c -{%- elif cost_type_e == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_e == "casadi" %} - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c - {%- elif cost.cost_source_ext_cost_e != cost.cost_source_ext_cost_0 %} - {{ model.name }}_cost/{{ cost.cost_source_ext_cost_e }} - {%- endif %} -{%- endif %} - acados_solver_{{ model.name }}.c) - add_library(${OCP_OBJ} OBJECT ${OCP_SRC}) -endif() - -{%- if solver_options.integrator_type != "DISCRETE" %} -# for sim solver -if(${BUILD_ACADOS_SOLVER_LIB} OR ${BUILD_EXAMPLE} - {%- if solver_options.integrator_type != "DISCRETE" %} - OR ${BUILD_SIM_EXAMPLE} OR ${BUILD_ACADOS_SIM_SOLVER_LIB} - {%- endif -%} - ) - set(SIM_SRC acados_sim_solver_{{ model.name }}.c) - add_library(${SIM_OBJ} OBJECT ${SIM_SRC}) -endif() -{%- endif %} - -# for target example -set(EX_SRC main_{{ model.name }}.c) -set(EX_EXE main_{{ model.name }}) - -{%- if model_external_shared_lib_dir and model_external_shared_lib_name %} -set(EXTERNAL_DIR {{ model_external_shared_lib_dir | replace(from="\", to="/") }}) -set(EXTERNAL_LIB {{ model_external_shared_lib_name }}) -{%- else %} -set(EXTERNAL_DIR) -set(EXTERNAL_LIB) -{%- endif %} - -# set some search paths for preprocessor and linker -set(ACADOS_INCLUDE_PATH {{ acados_include_path | replace(from="\", to="/") }} CACHE PATH "Define the path which contains the include directory for acados.") -set(ACADOS_LIB_PATH {{ acados_lib_path | replace(from="\", to="/") }} CACHE PATH "Define the path which contains the lib directory for acados.") - -# c-compiler flags for debugging -set(CMAKE_C_FLAGS_DEBUG "-O0 -ggdb") - -set(CMAKE_C_FLAGS "-fPIC -std=c99 {{ openmp_flag }} -{%- if qp_solver == "FULL_CONDENSING_QPOASES" -%} - -DACADOS_WITH_QPOASES -{%- endif -%} -{%- if qp_solver == "FULL_CONDENSING_DAQP" -%} - -DACADOS_WITH_DAQP -{%- endif -%} -{%- if qp_solver == "PARTIAL_CONDENSING_OSQP" -%} - -DACADOS_WITH_OSQP -{%- endif -%} -{%- if qp_solver == "PARTIAL_CONDENSING_QPDUNES" -%} - -DACADOS_WITH_QPDUNES -{%- endif -%} -") -#-fno-diagnostics-show-line-numbers -g - -include_directories( - ${ACADOS_INCLUDE_PATH} - ${ACADOS_INCLUDE_PATH}/acados - ${ACADOS_INCLUDE_PATH}/blasfeo/include - ${ACADOS_INCLUDE_PATH}/hpipm/include -{%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - ${ACADOS_INCLUDE_PATH}/qpOASES_e/ -{%- endif %} -{%- if qp_solver == "FULL_CONDENSING_DAQP" %} - ${ACADOS_INCLUDE_PATH}/daqp/include -{%- endif %} -) - -# linker flags -link_directories(${ACADOS_LIB_PATH}) - -# link to libraries -if(UNIX) - link_libraries(acados hpipm blasfeo m {{ link_libs }}) -else() - link_libraries(acados hpipm blasfeo {{ link_libs }}) -endif() - -# the targets - -# bundled_shared_lib -if(${BUILD_ACADOS_SOLVER_LIB}) - set(LIB_ACADOS_SOLVER acados_solver_{{ model.name }}) - add_library(${LIB_ACADOS_SOLVER} SHARED $ $ - {%- if solver_options.integrator_type != "DISCRETE" %} - $ - {%- endif -%} - ) - install(TARGETS ${LIB_ACADOS_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_ACADOS_SOLVER_LIB}) - -# ocp_shared_lib -if(${BUILD_ACADOS_OCP_SOLVER_LIB}) - set(LIB_ACADOS_OCP_SOLVER acados_ocp_solver_{{ model.name }}) - add_library(${LIB_ACADOS_OCP_SOLVER} SHARED $ $) - # Specify libraries or flags to use when linking a given target and/or its dependents. - target_link_libraries(${LIB_ACADOS_OCP_SOLVER} PRIVATE ${EXTERNAL_LIB}) - target_link_directories(${LIB_ACADOS_OCP_SOLVER} PRIVATE ${EXTERNAL_DIR}) - install(TARGETS ${LIB_ACADOS_OCP_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_ACADOS_OCP_SOLVER_LIB}) - -# example -if(${BUILD_EXAMPLE}) - add_executable(${EX_EXE} ${EX_SRC} $ $ - {%- if solver_options.integrator_type != "DISCRETE" %} - $ - {%- endif -%} - ) - install(TARGETS ${EX_EXE} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_EXAMPLE}) - -{% if solver_options.integrator_type != "DISCRETE" -%} -# example_sim -if(${BUILD_SIM_EXAMPLE}) - set(EX_SIM_SRC main_sim_{{ model.name }}.c) - set(EX_SIM_EXE main_sim_{{ model.name }}) - add_executable(${EX_SIM_EXE} ${EX_SIM_SRC} $ $) - install(TARGETS ${EX_SIM_EXE} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_SIM_EXAMPLE}) - -# sim_shared_lib -if(${BUILD_ACADOS_SIM_SOLVER_LIB}) - set(LIB_ACADOS_SIM_SOLVER acados_sim_solver_{{ model.name }}) - add_library(${LIB_ACADOS_SIM_SOLVER} SHARED $ $) - install(TARGETS ${LIB_ACADOS_SIM_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_ACADOS_SIM_SOLVER_LIB}) -{%- endif %} - diff --git a/third_party/acados/acados_template/c_templates_tera/Makefile.in b/third_party/acados/acados_template/c_templates_tera/Makefile.in deleted file mode 100644 index fbefc08e380d9c..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/Makefile.in +++ /dev/null @@ -1,468 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -{%- if solver_options.qp_solver %} - {%- set qp_solver = solver_options.qp_solver %} -{%- else %} - {%- set qp_solver = "FULL_CONDENSING_HPIPM" %} -{%- endif %} - -{%- if solver_options.hessian_approx %} - {%- set hessian_approx = solver_options.hessian_approx %} -{%- elif solver_options.sens_hess %} - {%- set hessian_approx = "EXACT" %} -{%- else %} - {%- set hessian_approx = "GAUSS_NEWTON" %} -{%- endif %} - -{%- if constraints.constr_type %} - {%- set constr_type = constraints.constr_type %} -{%- else %} - {%- set constr_type = "NONE" %} -{%- endif %} - -{%- if constraints.constr_type_e %} - {%- set constr_type_e = constraints.constr_type_e %} -{%- else %} - {%- set constr_type_e = "NONE" %} -{%- endif %} - -{%- if cost.cost_type %} - {%- set cost_type = cost.cost_type %} -{%- else %} - {%- set cost_type = "NONE" %} -{%- endif %} - -{%- if cost.cost_type_e %} - {%- set cost_type_e = cost.cost_type_e %} -{%- else %} - {%- set cost_type_e = "NONE" %} -{%- endif %} - -{%- if cost.cost_type_0 %} - {%- set cost_type_0 = cost.cost_type_0 %} -{%- else %} - {%- set cost_type_0 = "NONE" %} -{%- endif %} - -{%- if dims.nh %} - {%- set dims_nh = dims.nh %} -{%- else %} - {%- set dims_nh = 0 %} -{%- endif %} - -{%- if dims.nphi %} - {%- set dims_nphi = dims.nphi %} -{%- else %} - {%- set dims_nphi = 0 %} -{%- endif %} - -{%- if dims.nh_e %} - {%- set dims_nh_e = dims.nh_e %} -{%- else %} - {%- set dims_nh_e = 0 %} -{%- endif %} - -{%- if dims.nphi_e %} - {%- set dims_nphi_e = dims.nphi_e %} -{%- else %} - {%- set dims_nphi_e = 0 %} -{%- endif %} -{%- if solver_options.model_external_shared_lib_dir %} - {%- set model_external_shared_lib_dir = solver_options.model_external_shared_lib_dir %} -{%- endif %} -{%- if solver_options.model_external_shared_lib_name %} - {%- set model_external_shared_lib_name = solver_options.model_external_shared_lib_name %} -{%- endif %} - -{# control operator #} -{%- if os and os == "pc" %} - {%- set control = "&" %} -{%- else %} - {%- set control = ";" %} -{%- endif %} - -{# acados linking libraries and flags #} -{%- if acados_link_libs and os and os == "pc" %} - {%- set link_libs = acados_link_libs.qpoases ~ " " ~ acados_link_libs.hpmpc ~ " " ~ acados_link_libs.osqp -%} - {%- set openmp_flag = acados_link_libs.openmp %} -{%- else %} - {%- set openmp_flag = " " %} - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - {%- set link_libs = "-lqpOASES_e" %} - {%- elif qp_solver == "FULL_CONDENSING_DAQP" %} - {%- set link_libs = "-ldaqp" %} - {%- else %} - {%- set link_libs = "" %} - {%- endif %} -{%- endif %} - -# define sources and use make's implicit rules to generate object files (*.o) - -# model -MODEL_SRC= - {%- if model.dyn_ext_fun_type == "casadi" %} -{%- if solver_options.integrator_type == "ERK" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_ode_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_vde_forw.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_vde_adj.c - {%- if hessian_approx == "EXACT" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_ode_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "IRK" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c - {%- if hessian_approx == "EXACT" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "LIFTED_IRK" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_u.c - {%- if hessian_approx == "EXACT" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c - {% if model.gnsf.nontrivial_f_LO == 1 %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c - {%- endif %} - {%- endif %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c -{%- elif solver_options.integrator_type == "DISCRETE" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c - {%- if hessian_approx == "EXACT" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c - {%- endif %} -{%- endif %} - {%- else %} -MODEL_SRC+= {{ model.name }}_model/{{ model.dyn_generic_source }} - {%- endif %} -MODEL_OBJ := $(MODEL_SRC:.c=.o) - -# optimal control problem - mostly CasADi exports -OCP_SRC= -{%- if constr_type == "BGP" and dims_nphi > 0 %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_phi_constraint.c -{%- endif %} -{%- if constr_type_e == "BGP" and dims_nphi_e > 0 %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.c -{%- endif %} - -{%- if constr_type == "BGH" and dims_nh > 0 %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.c -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun.c - {%- if hessian_approx == "EXACT" %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c - {%- endif %} -{%- endif %} - -{%- if constr_type_e == "BGH" and dims_nh_e > 0 %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.c -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.c - {%- if hessian_approx == "EXACT" %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c - {%- endif %} -{%- endif %} - -{%- if cost_type_0 == "NONLINEAR_LS" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c -{%- elif cost_type_0 == "CONVEX_OVER_NONLINEAR" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_0_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_0_fun_jac_hess.c -{%- elif cost_type_0 == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_0 == "casadi" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c - {%- else %} -OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost_0 }} - {%- endif %} -{%- endif %} -{%- if cost_type == "NONLINEAR_LS" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_hess.c -{%- elif cost_type == "CONVEX_OVER_NONLINEAR" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_fun_jac_hess.c -{%- elif cost_type == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type == "casadi" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c - {%- elif cost.cost_source_ext_cost != cost.cost_source_ext_cost_0 %} -OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost }} - {%- endif %} -{%- endif %} -{%- if cost_type_e == "NONLINEAR_LS" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c -{%- elif cost_type_e == "CONVEX_OVER_NONLINEAR" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_e_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_e_fun_jac_hess.c -{%- elif cost_type_e == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_e == "casadi" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c - {%- elif cost.cost_source_ext_cost_e != cost.cost_source_ext_cost_0 %} -OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost_e }} - {%- endif %} -{%- endif %} -{%- if solver_options.custom_update_filename %} - {%- if solver_options.custom_update_filename != "" %} -OCP_SRC+= {{ solver_options.custom_update_filename }} - {%- endif %} -{%- endif %} - -OCP_SRC+= acados_solver_{{ model.name }}.c -OCP_OBJ := $(OCP_SRC:.c=.o) - -# for sim solver -SIM_SRC= acados_sim_solver_{{ model.name }}.c -SIM_OBJ := $(SIM_SRC:.c=.o) - -# for target example -EX_SRC= main_{{ model.name }}.c -EX_OBJ := $(EX_SRC:.c=.o) -EX_EXE := $(EX_SRC:.c=) - -# for target example_sim -EX_SIM_SRC= main_sim_{{ model.name }}.c -EX_SIM_OBJ := $(EX_SIM_SRC:.c=.o) -EX_SIM_EXE := $(EX_SIM_SRC:.c=) - -# combine model, sim and ocp object files -OBJ= -OBJ+= $(MODEL_OBJ) -{%- if solver_options.integrator_type != "DISCRETE" %} -OBJ+= $(SIM_OBJ) -{%- endif %} -OBJ+= $(OCP_OBJ) - -EXTERNAL_DIR= -EXTERNAL_LIB= - -{%- if model_external_shared_lib_dir and model_external_shared_lib_name %} -EXTERNAL_DIR+= {{ model_external_shared_lib_dir }} -EXTERNAL_LIB+= {{ model_external_shared_lib_name }} -{%- endif %} - -INCLUDE_PATH = {{ acados_include_path }} -LIB_PATH = {{ acados_lib_path }} - -# preprocessor flags for make's implicit rules -{%- if qp_solver == "FULL_CONDENSING_QPOASES" %} -CPPFLAGS += -DACADOS_WITH_QPOASES -{%- endif %} -{%- if qp_solver == "FULL_CONDENSING_DAQP" %} -CPPFLAGS += -DACADOS_WITH_DAQP -{%- endif %} -{%- if qp_solver == "PARTIAL_CONDENSING_OSQP" %} -CPPFLAGS += -DACADOS_WITH_OSQP -{%- endif %} -{%- if qp_solver == "PARTIAL_CONDENSING_QPDUNES" %} -CPPFLAGS += -DACADOS_WITH_QPDUNES -{%- endif %} -CPPFLAGS+= -I$(INCLUDE_PATH) -CPPFLAGS+= -I$(INCLUDE_PATH)/acados -CPPFLAGS+= -I$(INCLUDE_PATH)/blasfeo/include -CPPFLAGS+= -I$(INCLUDE_PATH)/hpipm/include - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} -CPPFLAGS+= -I $(INCLUDE_PATH)/qpOASES_e/ - {%- endif %} - {%- if qp_solver == "FULL_CONDENSING_DAQP" %} -CPPFLAGS+= -I $(INCLUDE_PATH)/daqp/include - {%- endif %} - -{# c-compiler flags #} -# define the c-compiler flags for make's implicit rules -CFLAGS = -fPIC -std=c99 {{ openmp_flag }} {{ solver_options.ext_fun_compile_flags }}#-fno-diagnostics-show-line-numbers -g -# # Debugging -# CFLAGS += -g3 - -# linker flags -LDFLAGS+= -L$(LIB_PATH) - -# link to libraries -LDLIBS+= -lacados -LDLIBS+= -lhpipm -LDLIBS+= -lblasfeo -LDLIBS+= -lm -LDLIBS+= {{ link_libs }} - -# libraries -LIBACADOS_SOLVER=libacados_solver_{{ model.name }}{{ shared_lib_ext }} -LIBACADOS_OCP_SOLVER=libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} -LIBACADOS_SIM_SOLVER=lib$(SIM_SRC:.c={{ shared_lib_ext }}) - -# virtual targets -.PHONY : all clean - -#all: clean example_sim example shared_lib -{% if solver_options.integrator_type == "DISCRETE" -%} -all: clean example -shared_lib: ocp_shared_lib -{%- else %} -all: clean example_sim example -shared_lib: bundled_shared_lib ocp_shared_lib sim_shared_lib -{%- endif %} - -# some linker targets -example: $(EX_OBJ) $(OBJ) - $(CC) $^ -o $(EX_EXE) $(LDFLAGS) $(LDLIBS) - -example_sim: $(EX_SIM_OBJ) $(MODEL_OBJ) $(SIM_OBJ) - $(CC) $^ -o $(EX_SIM_EXE) $(LDFLAGS) $(LDLIBS) - -{% if solver_options.integrator_type != "DISCRETE" -%} -bundled_shared_lib: $(OBJ) - $(CC) -shared $^ -o $(LIBACADOS_SOLVER) $(LDFLAGS) $(LDLIBS) -{%- endif %} - -ocp_shared_lib: $(OCP_OBJ) $(MODEL_OBJ) - $(CC) -shared $^ -o $(LIBACADOS_OCP_SOLVER) $(LDFLAGS) $(LDLIBS) \ - -L$(EXTERNAL_DIR) -l$(EXTERNAL_LIB) - -sim_shared_lib: $(SIM_OBJ) $(MODEL_OBJ) - $(CC) -shared $^ -o $(LIBACADOS_SIM_SOLVER) $(LDFLAGS) $(LDLIBS) - - -# Cython targets -ocp_cython_c: ocp_shared_lib - cython \ - -o acados_ocp_solver_pyx.c \ - -I $(INCLUDE_PATH)/../interfaces/acados_template/acados_template \ - $(INCLUDE_PATH)/../interfaces/acados_template/acados_template/acados_ocp_solver_pyx.pyx \ - -I {{ code_export_directory }} \ - -ocp_cython_o: ocp_cython_c - $(CC) $(ACADOS_FLAGS) -c -O2 \ - -fPIC \ - -o acados_ocp_solver_pyx.o \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) \ - {%- for path in cython_include_dirs %} - -I {{ path }} \ - {%- endfor %} - acados_ocp_solver_pyx.c \ - -ocp_cython: ocp_cython_o - $(CC) $(ACADOS_FLAGS) -shared \ - -o acados_ocp_solver_pyx{{ shared_lib_ext }} \ - -Wl,-rpath=$(LIB_PATH) \ - acados_ocp_solver_pyx.o \ - $(abspath .)/libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} \ - $(LDFLAGS) $(LDLIBS) - -# Sim Cython targets -sim_cython_c: sim_shared_lib - cython \ - -o acados_sim_solver_pyx.c \ - -I $(INCLUDE_PATH)/../interfaces/acados_template/acados_template \ - $(INCLUDE_PATH)/../interfaces/acados_template/acados_template/acados_sim_solver_pyx.pyx \ - -I {{ code_export_directory }} \ - -sim_cython_o: sim_cython_c - $(CC) $(ACADOS_FLAGS) -c -O2 \ - -fPIC \ - -o acados_sim_solver_pyx.o \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) \ - {%- for path in cython_include_dirs %} - -I {{ path }} \ - {%- endfor %} - acados_sim_solver_pyx.c \ - -sim_cython: sim_cython_o - $(CC) $(ACADOS_FLAGS) -shared \ - -o acados_sim_solver_pyx{{ shared_lib_ext }} \ - -Wl,-rpath=$(LIB_PATH) \ - acados_sim_solver_pyx.o \ - $(abspath .)/libacados_sim_solver_{{ model.name }}{{ shared_lib_ext }} \ - $(LDFLAGS) $(LDLIBS) - -{%- if os and os == "pc" %} - -clean: - del \Q *.o 2>nul - del \Q *{{ shared_lib_ext }} 2>nul - del \Q main_{{ model.name }} 2>nul - -clean_ocp_shared_lib: - del \Q libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} 2>nul - del \Q acados_solver_{{ model.name }}.o 2>nul - -clean_ocp_cython: - del \Q libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} 2>nul - del \Q acados_solver_{{ model.name }}.o 2>nul - del \Q acados_ocp_solver_pyx{{ shared_lib_ext }} 2>nul - del \Q acados_ocp_solver_pyx.o 2>nul - -clean_sim_cython: - del \Q libacados_sim_solver_{{ model.name }}{{ shared_lib_ext }} 2>nul - del \Q acados_sim_solver_{{ model.name }}.o 2>nul - del \Q acados_sim_solver_pyx{{ shared_lib_ext }} 2>nul - del \Q acados_sim_solver_pyx.o 2>nul - -{%- else %} - -clean: - $(RM) $(OBJ) $(EX_OBJ) $(EX_SIM_OBJ) - $(RM) $(LIBACADOS_SOLVER) $(LIBACADOS_OCP_SOLVER) $(LIBACADOS_SIM_SOLVER) - $(RM) $(EX_EXE) $(EX_SIM_EXE) - -clean_ocp_shared_lib: - $(RM) $(LIBACADOS_OCP_SOLVER) - $(RM) $(OCP_OBJ) - -clean_ocp_cython: - $(RM) libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} - $(RM) acados_solver_{{ model.name }}.o - $(RM) acados_ocp_solver_pyx{{ shared_lib_ext }} - $(RM) acados_ocp_solver_pyx.o - -clean_sim_cython: - $(RM) libacados_sim_solver_{{ model.name }}{{ shared_lib_ext }} - $(RM) acados_sim_solver_{{ model.name }}.o - $(RM) acados_sim_solver_pyx{{ shared_lib_ext }} - $(RM) acados_sim_solver_pyx.o - -{%- endif %} diff --git a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.c b/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.c deleted file mode 100644 index 0cd098273c6e65..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.c +++ /dev/null @@ -1,526 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -{%- if solver_options.hessian_approx %} - {%- set hessian_approx = solver_options.hessian_approx %} -{%- elif solver_options.sens_hess %} - {%- set hessian_approx = "EXACT" %} -{%- else %} - {%- set hessian_approx = "GAUSS_NEWTON" %} -{%- endif %} -// standard -#include -#include - -// acados -#include "acados_c/external_function_interface.h" -#include "acados_c/sim_interface.h" -#include "acados_c/external_function_interface.h" - -#include "acados/sim/sim_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/print.h" - - -// example specific -#include "{{ model.name }}_model/{{ model.name }}_model.h" -#include "acados_sim_solver_{{ model.name }}.h" - - -// ** solver data ** - -sim_solver_capsule * {{ model.name }}_acados_sim_solver_create_capsule() -{ - void* capsule_mem = malloc(sizeof(sim_solver_capsule)); - sim_solver_capsule *capsule = (sim_solver_capsule *) capsule_mem; - - return capsule; -} - - -int {{ model.name }}_acados_sim_solver_free_capsule(sim_solver_capsule * capsule) -{ - free(capsule); - return 0; -} - - -int {{ model.name }}_acados_sim_create(sim_solver_capsule * capsule) -{ - // initialize - const int nx = {{ model.name | upper }}_NX; - const int nu = {{ model.name | upper }}_NU; - const int nz = {{ model.name | upper }}_NZ; - const int np = {{ model.name | upper }}_NP; - bool tmp_bool; - - {#// double Tsim = {{ solver_options.tf / dims.N }};#} - double Tsim = {{ solver_options.Tsim }}; - - {% if solver_options.integrator_type == "IRK" %} - capsule->sim_impl_dae_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_impl_dae_fun_jac_x_xdot_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_impl_dae_jac_x_xdot_u_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - - {%- if model.dyn_ext_fun_type == "casadi" %} - // external functions (implicit model) - capsule->sim_impl_dae_fun->casadi_fun = &{{ model.name }}_impl_dae_fun; - capsule->sim_impl_dae_fun->casadi_work = &{{ model.name }}_impl_dae_fun_work; - capsule->sim_impl_dae_fun->casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_sparsity_in; - capsule->sim_impl_dae_fun->casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_sparsity_out; - capsule->sim_impl_dae_fun->casadi_n_in = &{{ model.name }}_impl_dae_fun_n_in; - capsule->sim_impl_dae_fun->casadi_n_out = &{{ model.name }}_impl_dae_fun_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_impl_dae_fun, np); - - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_fun = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_work = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_work; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_in; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_out; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_n_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_in; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_n_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_impl_dae_fun_jac_x_xdot_z, np); - - // external_function_param_{{ model.dyn_ext_fun_type }} impl_dae_jac_x_xdot_u_z; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_fun = &{{ model.name }}_impl_dae_jac_x_xdot_u_z; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_work = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_work; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_sparsity_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_in; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_sparsity_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_out; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_n_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_in; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_n_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_impl_dae_jac_x_xdot_u_z, np); - {%- else %} - capsule->sim_impl_dae_fun->fun = &{{ model.dyn_impl_dae_fun }}; - capsule->sim_impl_dae_fun_jac_x_xdot_z->fun = &{{ model.dyn_impl_dae_fun_jac }}; - capsule->sim_impl_dae_jac_x_xdot_u_z->fun = &{{ model.dyn_impl_dae_jac }}; - {%- endif %} - -{%- if hessian_approx == "EXACT" %} - capsule->sim_impl_dae_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - // external_function_param_{{ model.dyn_ext_fun_type }} impl_dae_jac_x_xdot_u_z; - capsule->sim_impl_dae_hess->casadi_fun = &{{ model.name }}_impl_dae_hess; - capsule->sim_impl_dae_hess->casadi_work = &{{ model.name }}_impl_dae_hess_work; - capsule->sim_impl_dae_hess->casadi_sparsity_in = &{{ model.name }}_impl_dae_hess_sparsity_in; - capsule->sim_impl_dae_hess->casadi_sparsity_out = &{{ model.name }}_impl_dae_hess_sparsity_out; - capsule->sim_impl_dae_hess->casadi_n_in = &{{ model.name }}_impl_dae_hess_n_in; - capsule->sim_impl_dae_hess->casadi_n_out = &{{ model.name }}_impl_dae_hess_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_impl_dae_hess, np); -{%- endif %} - - {% elif solver_options.integrator_type == "ERK" %} - // explicit ode - capsule->sim_forw_vde_casadi = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_vde_adj_casadi = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_expl_ode_fun_casadi = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - - capsule->sim_forw_vde_casadi->casadi_fun = &{{ model.name }}_expl_vde_forw; - capsule->sim_forw_vde_casadi->casadi_n_in = &{{ model.name }}_expl_vde_forw_n_in; - capsule->sim_forw_vde_casadi->casadi_n_out = &{{ model.name }}_expl_vde_forw_n_out; - capsule->sim_forw_vde_casadi->casadi_sparsity_in = &{{ model.name }}_expl_vde_forw_sparsity_in; - capsule->sim_forw_vde_casadi->casadi_sparsity_out = &{{ model.name }}_expl_vde_forw_sparsity_out; - capsule->sim_forw_vde_casadi->casadi_work = &{{ model.name }}_expl_vde_forw_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_forw_vde_casadi, np); - - capsule->sim_vde_adj_casadi->casadi_fun = &{{ model.name }}_expl_vde_adj; - capsule->sim_vde_adj_casadi->casadi_n_in = &{{ model.name }}_expl_vde_adj_n_in; - capsule->sim_vde_adj_casadi->casadi_n_out = &{{ model.name }}_expl_vde_adj_n_out; - capsule->sim_vde_adj_casadi->casadi_sparsity_in = &{{ model.name }}_expl_vde_adj_sparsity_in; - capsule->sim_vde_adj_casadi->casadi_sparsity_out = &{{ model.name }}_expl_vde_adj_sparsity_out; - capsule->sim_vde_adj_casadi->casadi_work = &{{ model.name }}_expl_vde_adj_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_vde_adj_casadi, np); - - capsule->sim_expl_ode_fun_casadi->casadi_fun = &{{ model.name }}_expl_ode_fun; - capsule->sim_expl_ode_fun_casadi->casadi_n_in = &{{ model.name }}_expl_ode_fun_n_in; - capsule->sim_expl_ode_fun_casadi->casadi_n_out = &{{ model.name }}_expl_ode_fun_n_out; - capsule->sim_expl_ode_fun_casadi->casadi_sparsity_in = &{{ model.name }}_expl_ode_fun_sparsity_in; - capsule->sim_expl_ode_fun_casadi->casadi_sparsity_out = &{{ model.name }}_expl_ode_fun_sparsity_out; - capsule->sim_expl_ode_fun_casadi->casadi_work = &{{ model.name }}_expl_ode_fun_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_expl_ode_fun_casadi, np); - -{%- if hessian_approx == "EXACT" %} - capsule->sim_expl_ode_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - // external_function_param_{{ model.dyn_ext_fun_type }} impl_dae_jac_x_xdot_u_z; - capsule->sim_expl_ode_hess->casadi_fun = &{{ model.name }}_expl_ode_hess; - capsule->sim_expl_ode_hess->casadi_work = &{{ model.name }}_expl_ode_hess_work; - capsule->sim_expl_ode_hess->casadi_sparsity_in = &{{ model.name }}_expl_ode_hess_sparsity_in; - capsule->sim_expl_ode_hess->casadi_sparsity_out = &{{ model.name }}_expl_ode_hess_sparsity_out; - capsule->sim_expl_ode_hess->casadi_n_in = &{{ model.name }}_expl_ode_hess_n_in; - capsule->sim_expl_ode_hess->casadi_n_out = &{{ model.name }}_expl_ode_hess_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_expl_ode_hess, np); -{%- endif %} - - {% elif solver_options.integrator_type == "GNSF" -%} - {% if model.gnsf.purely_linear != 1 %} - capsule->sim_gnsf_phi_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_gnsf_phi_fun_jac_y = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_gnsf_phi_jac_y_uhat = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - {%- endif %} - {%- endif %} - capsule->sim_gnsf_get_matrices_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - - {% if model.gnsf.purely_linear != 1 %} - capsule->sim_gnsf_phi_fun->casadi_fun = &{{ model.name }}_gnsf_phi_fun; - capsule->sim_gnsf_phi_fun->casadi_n_in = &{{ model.name }}_gnsf_phi_fun_n_in; - capsule->sim_gnsf_phi_fun->casadi_n_out = &{{ model.name }}_gnsf_phi_fun_n_out; - capsule->sim_gnsf_phi_fun->casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_sparsity_in; - capsule->sim_gnsf_phi_fun->casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_sparsity_out; - capsule->sim_gnsf_phi_fun->casadi_work = &{{ model.name }}_gnsf_phi_fun_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_phi_fun, np); - - capsule->sim_gnsf_phi_fun_jac_y->casadi_fun = &{{ model.name }}_gnsf_phi_fun_jac_y; - capsule->sim_gnsf_phi_fun_jac_y->casadi_n_in = &{{ model.name }}_gnsf_phi_fun_jac_y_n_in; - capsule->sim_gnsf_phi_fun_jac_y->casadi_n_out = &{{ model.name }}_gnsf_phi_fun_jac_y_n_out; - capsule->sim_gnsf_phi_fun_jac_y->casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_in; - capsule->sim_gnsf_phi_fun_jac_y->casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_out; - capsule->sim_gnsf_phi_fun_jac_y->casadi_work = &{{ model.name }}_gnsf_phi_fun_jac_y_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_phi_fun_jac_y, np); - - capsule->sim_gnsf_phi_jac_y_uhat->casadi_fun = &{{ model.name }}_gnsf_phi_jac_y_uhat; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_n_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_in; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_n_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_out; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_sparsity_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_in; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_sparsity_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_out; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_work = &{{ model.name }}_gnsf_phi_jac_y_uhat_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_phi_jac_y_uhat, np); - - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_fun = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_n_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_n_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_sparsity_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_in; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_sparsity_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_work = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z, np); - {%- endif %} - {%- endif %} - - capsule->sim_gnsf_get_matrices_fun->casadi_fun = &{{ model.name }}_gnsf_get_matrices_fun; - capsule->sim_gnsf_get_matrices_fun->casadi_n_in = &{{ model.name }}_gnsf_get_matrices_fun_n_in; - capsule->sim_gnsf_get_matrices_fun->casadi_n_out = &{{ model.name }}_gnsf_get_matrices_fun_n_out; - capsule->sim_gnsf_get_matrices_fun->casadi_sparsity_in = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_in; - capsule->sim_gnsf_get_matrices_fun->casadi_sparsity_out = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_out; - capsule->sim_gnsf_get_matrices_fun->casadi_work = &{{ model.name }}_gnsf_get_matrices_fun_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_get_matrices_fun, np); - {% endif %} - - // sim plan & config - sim_solver_plan_t plan; - plan.sim_solver = {{ solver_options.integrator_type }}; - - // create correct config based on plan - sim_config * {{ model.name }}_sim_config = sim_config_create(plan); - capsule->acados_sim_config = {{ model.name }}_sim_config; - - // sim dims - void *{{ model.name }}_sim_dims = sim_dims_create({{ model.name }}_sim_config); - capsule->acados_sim_dims = {{ model.name }}_sim_dims; - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nx", &nx); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nu", &nu); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nz", &nz); -{% if solver_options.integrator_type == "GNSF" %} - int gnsf_nx1 = {{ dims.gnsf_nx1 }}; - int gnsf_nz1 = {{ dims.gnsf_nz1 }}; - int gnsf_nout = {{ dims.gnsf_nout }}; - int gnsf_ny = {{ dims.gnsf_ny }}; - int gnsf_nuhat = {{ dims.gnsf_nuhat }}; - - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nx1", &gnsf_nx1); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nz1", &gnsf_nz1); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nout", &gnsf_nout); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "ny", &gnsf_ny); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nuhat", &gnsf_nuhat); -{% endif %} - - // sim opts - sim_opts *{{ model.name }}_sim_opts = sim_opts_create({{ model.name }}_sim_config, {{ model.name }}_sim_dims); - capsule->acados_sim_opts = {{ model.name }}_sim_opts; - int tmp_int = {{ solver_options.sim_method_newton_iter }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "newton_iter", &tmp_int); - double tmp_double = {{ solver_options.sim_method_newton_tol }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "newton_tol", &tmp_double); - sim_collocation_type collocation_type = {{ solver_options.collocation_type }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "collocation_type", &collocation_type); - -{% if problem_class == "SIM" %} - tmp_int = {{ solver_options.sim_method_num_stages }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "num_stages", &tmp_int); - tmp_int = {{ solver_options.sim_method_num_steps }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "num_steps", &tmp_int); - - // options that are not available to AcadosOcpSolver - // (in OCP they will be determined by other options, like exact_hessian) - tmp_bool = {{ solver_options.sens_forw }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "sens_forw", &tmp_bool); - tmp_bool = {{ solver_options.sens_adj }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "sens_adj", &tmp_bool); - tmp_bool = {{ solver_options.sens_algebraic }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "sens_algebraic", &tmp_bool); - tmp_bool = {{ solver_options.sens_hess }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "sens_hess", &tmp_bool); - tmp_bool = {{ solver_options.output_z }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "output_z", &tmp_bool); - -{% else %} {# num_stages and num_steps of first shooting interval are used #} - tmp_int = {{ solver_options.sim_method_num_stages[0] }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "num_stages", &tmp_int); - tmp_int = {{ solver_options.sim_method_num_steps[0] }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "num_steps", &tmp_int); - tmp_bool = {{ solver_options.sim_method_jac_reuse[0] }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "jac_reuse", &tmp_bool); -{% endif %} - - // sim in / out - sim_in *{{ model.name }}_sim_in = sim_in_create({{ model.name }}_sim_config, {{ model.name }}_sim_dims); - capsule->acados_sim_in = {{ model.name }}_sim_in; - sim_out *{{ model.name }}_sim_out = sim_out_create({{ model.name }}_sim_config, {{ model.name }}_sim_dims); - capsule->acados_sim_out = {{ model.name }}_sim_out; - - sim_in_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, - {{ model.name }}_sim_in, "T", &Tsim); - - // model functions -{%- if solver_options.integrator_type == "IRK" %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "impl_ode_fun", capsule->sim_impl_dae_fun); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "impl_ode_fun_jac_x_xdot", capsule->sim_impl_dae_fun_jac_x_xdot_z); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "impl_ode_jac_x_xdot_u", capsule->sim_impl_dae_jac_x_xdot_u_z); -{%- if hessian_approx == "EXACT" %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "impl_dae_hess", capsule->sim_impl_dae_hess); -{%- endif %} - -{%- elif solver_options.integrator_type == "ERK" %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "expl_vde_forw", capsule->sim_forw_vde_casadi); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "expl_vde_adj", capsule->sim_vde_adj_casadi); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "expl_ode_fun", capsule->sim_expl_ode_fun_casadi); -{%- if hessian_approx == "EXACT" %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "expl_ode_hess", capsule->sim_expl_ode_hess); -{%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "phi_fun", capsule->sim_gnsf_phi_fun); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "phi_fun_jac_y", capsule->sim_gnsf_phi_fun_jac_y); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "phi_jac_y_uhat", capsule->sim_gnsf_phi_jac_y_uhat); - {% if model.gnsf.nontrivial_f_LO == 1 %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "f_lo_jac_x1_x1dot_u_z", capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z); - {%- endif %} - {%- endif %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "gnsf_get_matrices_fun", capsule->sim_gnsf_get_matrices_fun); -{%- endif %} - - // sim solver - sim_solver *{{ model.name }}_sim_solver = sim_solver_create({{ model.name }}_sim_config, - {{ model.name }}_sim_dims, {{ model.name }}_sim_opts); - capsule->acados_sim_solver = {{ model.name }}_sim_solver; - -{% if dims.np > 0 %} - /* initialize parameter values */ - double* p = calloc(np, sizeof(double)); - {% for item in parameter_values %} - {%- if item != 0 %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endif %} - {%- endfor %} - - {{ model.name }}_acados_sim_update_params(capsule, p, np); - free(p); -{% endif %}{# if dims.np #} - - /* initialize input */ - // x - double x0[{{ dims.nx }}]; - for (int ii = 0; ii < {{ dims.nx }}; ii++) - x0[ii] = 0.0; - - sim_in_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, - {{ model.name }}_sim_in, "x", x0); - - - // u - double u0[{{ dims.nu }}]; - for (int ii = 0; ii < {{ dims.nu }}; ii++) - u0[ii] = 0.0; - - sim_in_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, - {{ model.name }}_sim_in, "u", u0); - - // S_forw - double S_forw[{{ dims.nx * (dims.nx + dims.nu) }}]; - for (int ii = 0; ii < {{ dims.nx * (dims.nx + dims.nu) }}; ii++) - S_forw[ii] = 0.0; - for (int ii = 0; ii < {{ dims.nx }}; ii++) - S_forw[ii + ii * {{ dims.nx }} ] = 1.0; - - - sim_in_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, - {{ model.name }}_sim_in, "S_forw", S_forw); - - int status = sim_precompute({{ model.name }}_sim_solver, {{ model.name }}_sim_in, {{ model.name }}_sim_out); - - return status; -} - - -int {{ model.name }}_acados_sim_solve(sim_solver_capsule *capsule) -{ - // integrate dynamics using acados sim_solver - int status = sim_solve(capsule->acados_sim_solver, - capsule->acados_sim_in, capsule->acados_sim_out); - if (status != 0) - printf("error in {{ model.name }}_acados_sim_solve()! Exiting.\n"); - - return status; -} - - -int {{ model.name }}_acados_sim_free(sim_solver_capsule *capsule) -{ - // free memory - sim_solver_destroy(capsule->acados_sim_solver); - sim_in_destroy(capsule->acados_sim_in); - sim_out_destroy(capsule->acados_sim_out); - sim_opts_destroy(capsule->acados_sim_opts); - sim_dims_destroy(capsule->acados_sim_dims); - sim_config_destroy(capsule->acados_sim_config); - - // free external function -{%- if solver_options.integrator_type == "IRK" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_impl_dae_fun); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_impl_dae_fun_jac_x_xdot_z); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_impl_dae_jac_x_xdot_u_z); -{%- if hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_impl_dae_hess); -{%- endif %} -{%- elif solver_options.integrator_type == "ERK" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_forw_vde_casadi); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_vde_adj_casadi); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_expl_ode_fun_casadi); -{%- if hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_expl_ode_hess); -{%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_phi_fun); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_phi_fun_jac_y); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_phi_jac_y_uhat); - {% if model.gnsf.nontrivial_f_LO == 1 %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z); - {%- endif %} - {%- endif %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_get_matrices_fun); -{% endif %} - - return 0; -} - - -int {{ model.name }}_acados_sim_update_params(sim_solver_capsule *capsule, double *p, int np) -{ - int status = 0; - int casadi_np = {{ model.name | upper }}_NP; - - if (casadi_np != np) { - printf("{{ model.name }}_acados_sim_update_params: trying to set %i parameters for external functions." - " External function has %i parameters. Exiting.\n", np, casadi_np); - exit(1); - } - -{%- if solver_options.integrator_type == "ERK" %} - capsule->sim_forw_vde_casadi[0].set_param(capsule->sim_forw_vde_casadi, p); - capsule->sim_vde_adj_casadi[0].set_param(capsule->sim_vde_adj_casadi, p); - capsule->sim_expl_ode_fun_casadi[0].set_param(capsule->sim_expl_ode_fun_casadi, p); -{%- if hessian_approx == "EXACT" %} - capsule->sim_expl_ode_hess[0].set_param(capsule->sim_expl_ode_hess, p); -{%- endif %} -{%- elif solver_options.integrator_type == "IRK" %} - capsule->sim_impl_dae_fun[0].set_param(capsule->sim_impl_dae_fun, p); - capsule->sim_impl_dae_fun_jac_x_xdot_z[0].set_param(capsule->sim_impl_dae_fun_jac_x_xdot_z, p); - capsule->sim_impl_dae_jac_x_xdot_u_z[0].set_param(capsule->sim_impl_dae_jac_x_xdot_u_z, p); -{%- if hessian_approx == "EXACT" %} - capsule->sim_impl_dae_hess[0].set_param(capsule->sim_impl_dae_hess, p); -{%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - capsule->sim_gnsf_phi_fun[0].set_param(capsule->sim_gnsf_phi_fun, p); - capsule->sim_gnsf_phi_fun_jac_y[0].set_param(capsule->sim_gnsf_phi_fun_jac_y, p); - capsule->sim_gnsf_phi_jac_y_uhat[0].set_param(capsule->sim_gnsf_phi_jac_y_uhat, p); - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z[0].set_param(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z, p); - {%- endif %} - {%- endif %} - capsule->sim_gnsf_get_matrices_fun[0].set_param(capsule->sim_gnsf_get_matrices_fun, p); -{% endif %} - - return status; -} - -/* getters pointers to C objects*/ -sim_config * {{ model.name }}_acados_get_sim_config(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_config; -}; - -sim_in * {{ model.name }}_acados_get_sim_in(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_in; -}; - -sim_out * {{ model.name }}_acados_get_sim_out(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_out; -}; - -void * {{ model.name }}_acados_get_sim_dims(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_dims; -}; - -sim_opts * {{ model.name }}_acados_get_sim_opts(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_opts; -}; - -sim_solver * {{ model.name }}_acados_get_sim_solver(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_solver; -}; - diff --git a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.h b/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.h deleted file mode 100644 index 59aee62f49fd3f..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -#ifndef ACADOS_SIM_{{ model.name }}_H_ -#define ACADOS_SIM_{{ model.name }}_H_ - -#include "acados_c/sim_interface.h" -#include "acados_c/external_function_interface.h" - -#define {{ model.name | upper }}_NX {{ dims.nx }} -#define {{ model.name | upper }}_NZ {{ dims.nz }} -#define {{ model.name | upper }}_NU {{ dims.nu }} -#define {{ model.name | upper }}_NP {{ dims.np }} - -#ifdef __cplusplus -extern "C" { -#endif - - -// ** capsule for solver data ** -typedef struct sim_solver_capsule -{ - // acados objects - sim_in *acados_sim_in; - sim_out *acados_sim_out; - sim_solver *acados_sim_solver; - sim_opts *acados_sim_opts; - sim_config *acados_sim_config; - void *acados_sim_dims; - - /* external functions */ - // ERK - external_function_param_{{ model.dyn_ext_fun_type }} * sim_forw_vde_casadi; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_vde_adj_casadi; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_expl_ode_fun_casadi; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_expl_ode_hess; - - // IRK - external_function_param_{{ model.dyn_ext_fun_type }} * sim_impl_dae_fun; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_impl_dae_fun_jac_x_xdot_z; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_impl_dae_jac_x_xdot_u_z; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_impl_dae_hess; - - // GNSF - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_phi_fun; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_phi_fun_jac_y; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_phi_jac_y_uhat; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_f_lo_jac_x1_x1dot_u_z; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_get_matrices_fun; - -} sim_solver_capsule; - - -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_create(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_solve(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_free(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_update_params(sim_solver_capsule *capsule, double *value, int np); - -ACADOS_SYMBOL_EXPORT sim_config * {{ model.name }}_acados_get_sim_config(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT sim_in * {{ model.name }}_acados_get_sim_in(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT sim_out * {{ model.name }}_acados_get_sim_out(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT void * {{ model.name }}_acados_get_sim_dims(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT sim_opts * {{ model.name }}_acados_get_sim_opts(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT sim_solver * {{ model.name }}_acados_get_sim_solver(sim_solver_capsule *capsule); - - -ACADOS_SYMBOL_EXPORT sim_solver_capsule * {{ model.name }}_acados_sim_solver_create_capsule(void); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_solver_free_capsule(sim_solver_capsule *capsule); - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_SIM_{{ model.name }}_H_ diff --git a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.pxd b/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.pxd deleted file mode 100644 index 153f98d13a62e1..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.pxd +++ /dev/null @@ -1,51 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -cimport acados_sim_solver_common - -cdef extern from "acados_sim_solver_{{ model.name }}.h": - ctypedef struct sim_solver_capsule "sim_solver_capsule": - pass - - sim_solver_capsule * acados_sim_solver_create_capsule "{{ model.name }}_acados_sim_solver_create_capsule"() - int acados_sim_solver_free_capsule "{{ model.name }}_acados_sim_solver_free_capsule"(sim_solver_capsule *capsule) - - int acados_sim_create "{{ model.name }}_acados_sim_create"(sim_solver_capsule * capsule) - int acados_sim_solve "{{ model.name }}_acados_sim_solve"(sim_solver_capsule * capsule) - int acados_sim_free "{{ model.name }}_acados_sim_free"(sim_solver_capsule * capsule) - int acados_sim_update_params "{{ model.name }}_acados_sim_update_params"(sim_solver_capsule * capsule, double *value, int np_) - # int acados_sim_update_params_sparse "{{ model.name }}_acados_sim_update_params_sparse"(sim_solver_capsule * capsule, int stage, int *idx, double *p, int n_update) - - acados_sim_solver_common.sim_in *acados_get_sim_in "{{ model.name }}_acados_get_sim_in"(sim_solver_capsule * capsule) - acados_sim_solver_common.sim_out *acados_get_sim_out "{{ model.name }}_acados_get_sim_out"(sim_solver_capsule * capsule) - acados_sim_solver_common.sim_solver *acados_get_sim_solver "{{ model.name }}_acados_get_sim_solver"(sim_solver_capsule * capsule) - acados_sim_solver_common.sim_config *acados_get_sim_config "{{ model.name }}_acados_get_sim_config"(sim_solver_capsule * capsule) - acados_sim_solver_common.sim_opts *acados_get_sim_opts "{{ model.name }}_acados_get_sim_opts"(sim_solver_capsule * capsule) - void *acados_get_sim_dims "{{ model.name }}_acados_get_sim_dims"(sim_solver_capsule * capsule) diff --git a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.c b/third_party/acados/acados_template/c_templates_tera/acados_solver.in.c deleted file mode 100644 index 5e36a53d1001d3..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.c +++ /dev/null @@ -1,2741 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -// standard -#include -#include -#include -// acados -// #include "acados/utils/print.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_c/external_function_interface.h" - -// example specific -#include "{{ model.name }}_model/{{ model.name }}_model.h" -#include "{{ model.name }}_constraints/{{ model.name }}_constraints.h" - -{%- if cost.cost_type != "LINEAR_LS" or cost.cost_type_e != "LINEAR_LS" or cost.cost_type_0 != "LINEAR_LS" %} -#include "{{ model.name }}_cost/{{ model.name }}_cost.h" -{%- endif %} - -{%- if not solver_options.custom_update_filename %} - {%- set custom_update_filename = "" %} -{% else %} - {%- set custom_update_filename = solver_options.custom_update_filename %} -{%- endif %} -{%- if not solver_options.custom_update_header_filename %} - {%- set custom_update_header_filename = "" %} -{% else %} - {%- set custom_update_header_filename = solver_options.custom_update_header_filename %} -{%- endif %} -{%- if custom_update_header_filename != "" %} -#include "{{ custom_update_header_filename }}" -{%- endif %} - - -#include "acados_solver_{{ model.name }}.h" - -#define NX {{ model.name | upper }}_NX -#define NZ {{ model.name | upper }}_NZ -#define NU {{ model.name | upper }}_NU -#define NP {{ model.name | upper }}_NP -#define NBX {{ model.name | upper }}_NBX -#define NBX0 {{ model.name | upper }}_NBX0 -#define NBU {{ model.name | upper }}_NBU -#define NSBX {{ model.name | upper }}_NSBX -#define NSBU {{ model.name | upper }}_NSBU -#define NSH {{ model.name | upper }}_NSH -#define NSG {{ model.name | upper }}_NSG -#define NSPHI {{ model.name | upper }}_NSPHI -#define NSHN {{ model.name | upper }}_NSHN -#define NSGN {{ model.name | upper }}_NSGN -#define NSPHIN {{ model.name | upper }}_NSPHIN -#define NSBXN {{ model.name | upper }}_NSBXN -#define NS {{ model.name | upper }}_NS -#define NSN {{ model.name | upper }}_NSN -#define NG {{ model.name | upper }}_NG -#define NBXN {{ model.name | upper }}_NBXN -#define NGN {{ model.name | upper }}_NGN -#define NY0 {{ model.name | upper }}_NY0 -#define NY {{ model.name | upper }}_NY -#define NYN {{ model.name | upper }}_NYN -// #define N {{ model.name | upper }}_N -#define NH {{ model.name | upper }}_NH -#define NPHI {{ model.name | upper }}_NPHI -#define NHN {{ model.name | upper }}_NHN -#define NPHIN {{ model.name | upper }}_NPHIN -#define NR {{ model.name | upper }}_NR - - -// ** solver data ** - -{{ model.name }}_solver_capsule * {{ model.name }}_acados_create_capsule(void) -{ - void* capsule_mem = malloc(sizeof({{ model.name }}_solver_capsule)); - {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) capsule_mem; - - return capsule; -} - - -int {{ model.name }}_acados_free_capsule({{ model.name }}_solver_capsule *capsule) -{ - free(capsule); - return 0; -} - - -int {{ model.name }}_acados_create({{ model.name }}_solver_capsule* capsule) -{ - int N_shooting_intervals = {{ model.name | upper }}_N; - double* new_time_steps = NULL; // NULL -> don't alter the code generated time-steps - return {{ model.name }}_acados_create_with_discretization(capsule, N_shooting_intervals, new_time_steps); -} - - -int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule* capsule, int N, double* new_time_steps) -{ - if (N != capsule->nlp_solver_plan->N) { - fprintf(stderr, "{{ model.name }}_acados_update_time_steps: given number of time steps (= %d) " \ - "differs from the currently allocated number of " \ - "time steps (= %d)!\n" \ - "Please recreate with new discretization and provide a new vector of time_stamps!\n", - N, capsule->nlp_solver_plan->N); - return 1; - } - - ocp_nlp_config * nlp_config = capsule->nlp_config; - ocp_nlp_dims * nlp_dims = capsule->nlp_dims; - ocp_nlp_in * nlp_in = capsule->nlp_in; - - for (int i = 0; i < N; i++) - { - ocp_nlp_in_set(nlp_config, nlp_dims, nlp_in, i, "Ts", &new_time_steps[i]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "scaling", &new_time_steps[i]); - } - return 0; -} - -/** - * Internal function for {{ model.name }}_acados_create: step 1 - */ -void {{ model.name }}_acados_create_1_set_plan(ocp_nlp_plan_t* nlp_solver_plan, const int N) -{ - assert(N == nlp_solver_plan->N); - - /************************************************ - * plan - ************************************************/ - - {%- if solver_options.nlp_solver_type == "SQP" %} - nlp_solver_plan->nlp_solver = SQP; - {%- else %} - nlp_solver_plan->nlp_solver = SQP_RTI; - {%- endif %} - - nlp_solver_plan->ocp_qp_solver_plan.qp_solver = {{ solver_options.qp_solver }}; - - nlp_solver_plan->nlp_cost[0] = {{ cost.cost_type_0 }}; - for (int i = 1; i < N; i++) - nlp_solver_plan->nlp_cost[i] = {{ cost.cost_type }}; - - nlp_solver_plan->nlp_cost[N] = {{ cost.cost_type_e }}; - - for (int i = 0; i < N; i++) - { - {%- if solver_options.integrator_type == "DISCRETE" %} - nlp_solver_plan->nlp_dynamics[i] = DISCRETE_MODEL; - // discrete dynamics does not need sim solver option, this field is ignored - nlp_solver_plan->sim_solver_plan[i].sim_solver = INVALID_SIM_SOLVER; - {%- else %} - nlp_solver_plan->nlp_dynamics[i] = CONTINUOUS_MODEL; - nlp_solver_plan->sim_solver_plan[i].sim_solver = {{ solver_options.integrator_type }}; - {%- endif %} - } - - for (int i = 0; i < N; i++) - { - {%- if constraints.constr_type == "BGP" %} - nlp_solver_plan->nlp_constraints[i] = BGP; - {%- else -%} - nlp_solver_plan->nlp_constraints[i] = BGH; - {%- endif %} - } - - {%- if constraints.constr_type_e == "BGP" %} - nlp_solver_plan->nlp_constraints[N] = BGP; - {%- else %} - nlp_solver_plan->nlp_constraints[N] = BGH; - {%- endif %} - - {%- if solver_options.regularize_method == "NO_REGULARIZE" %} - nlp_solver_plan->regularization = NO_REGULARIZE; - {%- elif solver_options.regularize_method == "MIRROR" %} - nlp_solver_plan->regularization = MIRROR; - {%- elif solver_options.regularize_method == "PROJECT" %} - nlp_solver_plan->regularization = PROJECT; - {%- elif solver_options.regularize_method == "PROJECT_REDUC_HESS" %} - nlp_solver_plan->regularization = PROJECT_REDUC_HESS; - {%- elif solver_options.regularize_method == "CONVEXIFY" %} - nlp_solver_plan->regularization = CONVEXIFY; - {%- endif %} -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 2 - */ -ocp_nlp_dims* {{ model.name }}_acados_create_2_create_and_set_dimensions({{ model.name }}_solver_capsule* capsule) -{ - ocp_nlp_plan_t* nlp_solver_plan = capsule->nlp_solver_plan; - const int N = nlp_solver_plan->N; - ocp_nlp_config* nlp_config = capsule->nlp_config; - - /************************************************ - * dimensions - ************************************************/ - #define NINTNP1MEMS 17 - int* intNp1mem = (int*)malloc( (N+1)*sizeof(int)*NINTNP1MEMS ); - - int* nx = intNp1mem + (N+1)*0; - int* nu = intNp1mem + (N+1)*1; - int* nbx = intNp1mem + (N+1)*2; - int* nbu = intNp1mem + (N+1)*3; - int* nsbx = intNp1mem + (N+1)*4; - int* nsbu = intNp1mem + (N+1)*5; - int* nsg = intNp1mem + (N+1)*6; - int* nsh = intNp1mem + (N+1)*7; - int* nsphi = intNp1mem + (N+1)*8; - int* ns = intNp1mem + (N+1)*9; - int* ng = intNp1mem + (N+1)*10; - int* nh = intNp1mem + (N+1)*11; - int* nphi = intNp1mem + (N+1)*12; - int* nz = intNp1mem + (N+1)*13; - int* ny = intNp1mem + (N+1)*14; - int* nr = intNp1mem + (N+1)*15; - int* nbxe = intNp1mem + (N+1)*16; - - for (int i = 0; i < N+1; i++) - { - // common - nx[i] = NX; - nu[i] = NU; - nz[i] = NZ; - ns[i] = NS; - // cost - ny[i] = NY; - // constraints - nbx[i] = NBX; - nbu[i] = NBU; - nsbx[i] = NSBX; - nsbu[i] = NSBU; - nsg[i] = NSG; - nsh[i] = NSH; - nsphi[i] = NSPHI; - ng[i] = NG; - nh[i] = NH; - nphi[i] = NPHI; - nr[i] = NR; - nbxe[i] = 0; - } - - // for initial state - nbx[0] = NBX0; - nsbx[0] = 0; - ns[0] = NS - NSBX; - nbxe[0] = {{ dims.nbxe_0 }}; - ny[0] = NY0; - - // terminal - common - nu[N] = 0; - nz[N] = 0; - ns[N] = NSN; - // cost - ny[N] = NYN; - // constraint - nbx[N] = NBXN; - nbu[N] = 0; - ng[N] = NGN; - nh[N] = NHN; - nphi[N] = NPHIN; - nr[N] = {{ dims.nr_e }}; - - nsbx[N] = NSBXN; - nsbu[N] = 0; - nsg[N] = NSGN; - nsh[N] = NSHN; - nsphi[N] = NSPHIN; - - /* create and set ocp_nlp_dims */ - ocp_nlp_dims * nlp_dims = ocp_nlp_dims_create(nlp_config); - - ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nx", nx); - ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nu", nu); - ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nz", nz); - ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "ns", ns); - - for (int i = 0; i <= N; i++) - { - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbx", &nbx[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbu", &nbu[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsbx", &nsbx[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsbu", &nsbu[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "ng", &ng[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsg", &nsg[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbxe", &nbxe[i]); - } - -{%- if cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" or cost.cost_type_0 == "CONVEX_OVER_NONLINEAR"%} - ocp_nlp_dims_set_cost(nlp_config, nlp_dims, 0, "ny", &ny[0]); -{%- endif %} - -{%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" or cost.cost_type == "CONVEX_OVER_NONLINEAR"%} - for (int i = 1; i < N; i++) - ocp_nlp_dims_set_cost(nlp_config, nlp_dims, i, "ny", &ny[i]); -{%- endif %} - - for (int i = 0; i < N; i++) - { - {%- if constraints.constr_type == "BGH" and dims.nh > 0 %} - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nh", &nh[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsh", &nsh[i]); - {%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %} - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nr", &nr[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nphi", &nphi[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsphi", &nsphi[i]); - {%- endif %} - } - -{%- if constraints.constr_type_e == "BGH" %} - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nh", &nh[N]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsh", &nsh[N]); -{%- elif constraints.constr_type_e == "BGP" %} - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nr", &nr[N]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nphi", &nphi[N]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsphi", &nsphi[N]); -{%- endif %} -{%- if cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" or cost.cost_type_e == "CONVEX_OVER_NONLINEAR"%} - ocp_nlp_dims_set_cost(nlp_config, nlp_dims, N, "ny", &ny[N]); -{%- endif %} - free(intNp1mem); - -{%- if solver_options.integrator_type == "GNSF" -%} - // GNSF specific dimensions - int gnsf_nx1 = {{ dims.gnsf_nx1 }}; - int gnsf_nz1 = {{ dims.gnsf_nz1 }}; - int gnsf_nout = {{ dims.gnsf_nout }}; - int gnsf_ny = {{ dims.gnsf_ny }}; - int gnsf_nuhat = {{ dims.gnsf_nuhat }}; - - for (int i = 0; i < N; i++) - { - if (nlp_solver_plan->sim_solver_plan[i].sim_solver == GNSF) - { - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nx1", &gnsf_nx1); - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nz1", &gnsf_nz1); - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nout", &gnsf_nout); - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_ny", &gnsf_ny); - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nuhat", &gnsf_nuhat); - } - } -{%- endif %} -return nlp_dims; -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 3 - */ -void {{ model.name }}_acados_create_3_create_and_set_functions({{ model.name }}_solver_capsule* capsule) -{ - const int N = capsule->nlp_solver_plan->N; - - /************************************************ - * external functions - ************************************************/ - -#define MAP_CASADI_FNC(__CAPSULE_FNC__, __MODEL_BASE_FNC__) do{ \ - capsule->__CAPSULE_FNC__.casadi_fun = & __MODEL_BASE_FNC__ ;\ - capsule->__CAPSULE_FNC__.casadi_n_in = & __MODEL_BASE_FNC__ ## _n_in; \ - capsule->__CAPSULE_FNC__.casadi_n_out = & __MODEL_BASE_FNC__ ## _n_out; \ - capsule->__CAPSULE_FNC__.casadi_sparsity_in = & __MODEL_BASE_FNC__ ## _sparsity_in; \ - capsule->__CAPSULE_FNC__.casadi_sparsity_out = & __MODEL_BASE_FNC__ ## _sparsity_out; \ - capsule->__CAPSULE_FNC__.casadi_work = & __MODEL_BASE_FNC__ ## _work; \ - external_function_param_casadi_create(&capsule->__CAPSULE_FNC__ , {{ dims.np }}); \ - }while(false) - -{% if constraints.constr_type == "BGP" %} - // constraints.constr_type == "BGP" - capsule->phi_constraint = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) - { - // nonlinear part of convex-composite constraint - MAP_CASADI_FNC(phi_constraint[i], {{ model.name }}_phi_constraint); - } -{%- endif %} - -{%- if constraints.constr_type_e == "BGP" %} - // constraints.constr_type_e == "BGP" - // nonlinear part of convex-composite constraint - MAP_CASADI_FNC(phi_e_constraint, {{ model.name }}_phi_e_constraint); -{%- endif %} - -{%- if constraints.constr_type == "BGH" and dims.nh > 0 %} - // constraints.constr_type == "BGH" and dims.nh > 0 - capsule->nl_constr_h_fun_jac = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(nl_constr_h_fun_jac[i], {{ model.name }}_constr_h_fun_jac_uxt_zt); - } - capsule->nl_constr_h_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(nl_constr_h_fun[i], {{ model.name }}_constr_h_fun); - } - {% if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_fun_jac_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(nl_constr_h_fun_jac_hess[i], {{ model.name }}_constr_h_fun_jac_uxt_zt_hess); - } - {% endif %} -{% endif %} - -{%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - MAP_CASADI_FNC(nl_constr_h_e_fun_jac, {{ model.name }}_constr_h_e_fun_jac_uxt_zt); - MAP_CASADI_FNC(nl_constr_h_e_fun, {{ model.name }}_constr_h_e_fun); - - {%- if solver_options.hessian_approx == "EXACT" %} - MAP_CASADI_FNC(nl_constr_h_e_fun_jac_hess, {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess); - {% endif %} -{%- endif %} - -{% if solver_options.integrator_type == "ERK" %} - // explicit ode - capsule->forw_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(forw_vde_casadi[i], {{ model.name }}_expl_vde_forw); - } - - capsule->expl_ode_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(expl_ode_fun[i], {{ model.name }}_expl_ode_fun); - } - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->hess_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(hess_vde_casadi[i], {{ model.name }}_expl_ode_hess); - } - {%- endif %} - -{% elif solver_options.integrator_type == "IRK" %} - // implicit dae - capsule->impl_dae_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(impl_dae_fun[i], {{ model.name }}_impl_dae_fun); - {%- else %} - capsule->impl_dae_fun[i].fun = &{{ model.dyn_impl_dae_fun }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->impl_dae_fun[i], {{ dims.np }}); - {%- endif %} - } - - capsule->impl_dae_fun_jac_x_xdot_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(impl_dae_fun_jac_x_xdot_z[i], {{ model.name }}_impl_dae_fun_jac_x_xdot_z); - {%- else %} - capsule->impl_dae_fun_jac_x_xdot_z[i].fun = &{{ model.dyn_impl_dae_fun_jac }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->impl_dae_fun_jac_x_xdot_z[i], {{ dims.np }}); - {%- endif %} - } - - capsule->impl_dae_jac_x_xdot_u_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(impl_dae_jac_x_xdot_u_z[i], {{ model.name }}_impl_dae_jac_x_xdot_u_z); - {%- else %} - capsule->impl_dae_jac_x_xdot_u_z[i].fun = &{{ model.dyn_impl_dae_jac }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->impl_dae_jac_x_xdot_u_z[i], {{ dims.np }}); - {%- endif %} - } - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->impl_dae_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(impl_dae_hess[i], {{ model.name }}_impl_dae_hess); - } - {%- endif %} -{% elif solver_options.integrator_type == "LIFTED_IRK" %} - // external functions (implicit model) - capsule->impl_dae_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(impl_dae_fun[i], {{ model.name }}_impl_dae_fun); - } - - capsule->impl_dae_fun_jac_x_xdot_u = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(impl_dae_fun_jac_x_xdot_u[i], {{ model.name }}_impl_dae_fun_jac_x_xdot_u); - } - -{% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - capsule->gnsf_phi_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_phi_fun[i], {{ model.name }}_gnsf_phi_fun); - } - - capsule->gnsf_phi_fun_jac_y = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_phi_fun_jac_y[i], {{ model.name }}_gnsf_phi_fun_jac_y); - } - - capsule->gnsf_phi_jac_y_uhat = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_phi_jac_y_uhat[i], {{ model.name }}_gnsf_phi_jac_y_uhat); - } - - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->gnsf_f_lo_jac_x1_x1dot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_f_lo_jac_x1_x1dot_u_z[i], {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz); - } - {%- endif %} - {%- endif %} - capsule->gnsf_get_matrices_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_get_matrices_fun[i], {{ model.name }}_gnsf_get_matrices_fun); - } -{% elif solver_options.integrator_type == "DISCRETE" %} - // discrete dynamics - capsule->discr_dyn_phi_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) - { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(discr_dyn_phi_fun[i], {{ model.name }}_dyn_disc_phi_fun); - {%- else %} - capsule->discr_dyn_phi_fun[i].fun = &{{ model.dyn_disc_fun }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun[i], {{ dims.np }}); - {%- endif %} - } - - capsule->discr_dyn_phi_fun_jac_ut_xt = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) - { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(discr_dyn_phi_fun_jac_ut_xt[i], {{ model.name }}_dyn_disc_phi_fun_jac); - {%- else %} - capsule->discr_dyn_phi_fun_jac_ut_xt[i].fun = &{{ model.dyn_disc_fun_jac }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun_jac_ut_xt[i], {{ dims.np }}); - {%- endif %} - } - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) - { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(discr_dyn_phi_fun_jac_ut_xt_hess[i], {{ model.name }}_dyn_disc_phi_fun_jac_hess); - {%- else %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].fun = &{{ model.dyn_disc_fun_jac_hess }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i], {{ dims.np }}); - {%- endif %} - } - {%- endif %} -{%- endif %} - - -{%- if cost.cost_type_0 == "NONLINEAR_LS" %} - // nonlinear least squares function - MAP_CASADI_FNC(cost_y_0_fun, {{ model.name }}_cost_y_0_fun); - MAP_CASADI_FNC(cost_y_0_fun_jac_ut_xt, {{ model.name }}_cost_y_0_fun_jac_ut_xt); - MAP_CASADI_FNC(cost_y_0_hess, {{ model.name }}_cost_y_0_hess); - -{%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - // convex-over-nonlinear cost - MAP_CASADI_FNC(conl_cost_0_fun, {{ model.name }}_conl_cost_0_fun); - MAP_CASADI_FNC(conl_cost_0_fun_jac_hess, {{ model.name }}_conl_cost_0_fun_jac_hess); - -{%- elif cost.cost_type_0 == "EXTERNAL" %} - // external cost - {%- if cost.cost_ext_fun_type_0 == "casadi" %} - MAP_CASADI_FNC(ext_cost_0_fun, {{ model.name }}_cost_ext_cost_0_fun); - {%- else %} - capsule->ext_cost_0_fun.fun = &{{ cost.cost_function_ext_cost_0 }}; - external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun, {{ dims.np }}); - {%- endif %} - - // external cost - {%- if cost.cost_ext_fun_type_0 == "casadi" %} - MAP_CASADI_FNC(ext_cost_0_fun_jac, {{ model.name }}_cost_ext_cost_0_fun_jac); - {%- else %} - capsule->ext_cost_0_fun_jac.fun = &{{ cost.cost_function_ext_cost_0 }}; - external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun_jac, {{ dims.np }}); - {%- endif %} - - // external cost - {%- if cost.cost_ext_fun_type_0 == "casadi" %} - MAP_CASADI_FNC(ext_cost_0_fun_jac_hess, {{ model.name }}_cost_ext_cost_0_fun_jac_hess); - {%- else %} - capsule->ext_cost_0_fun_jac_hess.fun = &{{ cost.cost_function_ext_cost_0 }}; - external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun_jac_hess, {{ dims.np }}); - {%- endif %} -{%- endif %} - -{%- if cost.cost_type == "NONLINEAR_LS" %} - // nonlinear least squares cost - capsule->cost_y_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(cost_y_fun[i], {{ model.name }}_cost_y_fun); - } - - capsule->cost_y_fun_jac_ut_xt = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(cost_y_fun_jac_ut_xt[i], {{ model.name }}_cost_y_fun_jac_ut_xt); - } - - capsule->cost_y_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(cost_y_hess[i], {{ model.name }}_cost_y_hess); - } - -{%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - // convex-over-nonlinear cost - capsule->conl_cost_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(conl_cost_fun[i], {{ model.name }}_conl_cost_fun); - } - capsule->conl_cost_fun_jac_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(conl_cost_fun_jac_hess[i], {{ model.name }}_conl_cost_fun_jac_hess); - } - -{%- elif cost.cost_type == "EXTERNAL" %} - // external cost - capsule->ext_cost_fun = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); - for (int i = 0; i < N-1; i++) - { - {%- if cost.cost_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(ext_cost_fun[i], {{ model.name }}_cost_ext_cost_fun); - {%- else %} - capsule->ext_cost_fun[i].fun = &{{ cost.cost_function_ext_cost }}; - external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun[i], {{ dims.np }}); - {%- endif %} - } - - capsule->ext_cost_fun_jac = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); - for (int i = 0; i < N-1; i++) - { - {%- if cost.cost_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(ext_cost_fun_jac[i], {{ model.name }}_cost_ext_cost_fun_jac); - {%- else %} - capsule->ext_cost_fun_jac[i].fun = &{{ cost.cost_function_ext_cost }}; - external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun_jac[i], {{ dims.np }}); - {%- endif %} - } - - capsule->ext_cost_fun_jac_hess = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); - for (int i = 0; i < N-1; i++) - { - {%- if cost.cost_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(ext_cost_fun_jac_hess[i], {{ model.name }}_cost_ext_cost_fun_jac_hess); - {%- else %} - capsule->ext_cost_fun_jac_hess[i].fun = &{{ cost.cost_function_ext_cost }}; - external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun_jac_hess[i], {{ dims.np }}); - {%- endif %} - } -{%- endif %} - -{%- if cost.cost_type_e == "NONLINEAR_LS" %} - // nonlinear least square function - MAP_CASADI_FNC(cost_y_e_fun, {{ model.name }}_cost_y_e_fun); - MAP_CASADI_FNC(cost_y_e_fun_jac_ut_xt, {{ model.name }}_cost_y_e_fun_jac_ut_xt); - MAP_CASADI_FNC(cost_y_e_hess, {{ model.name }}_cost_y_e_hess); - -{%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - // convex-over-nonlinear cost - MAP_CASADI_FNC(conl_cost_e_fun, {{ model.name }}_conl_cost_e_fun); - MAP_CASADI_FNC(conl_cost_e_fun_jac_hess, {{ model.name }}_conl_cost_e_fun_jac_hess); - -{%- elif cost.cost_type_e == "EXTERNAL" %} - // external cost - function - {%- if cost.cost_ext_fun_type_e == "casadi" %} - MAP_CASADI_FNC(ext_cost_e_fun, {{ model.name }}_cost_ext_cost_e_fun); - {% else %} - capsule->ext_cost_e_fun.fun = &{{ cost.cost_function_ext_cost_e }}; - external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun, {{ dims.np }}); - {%- endif %} - - // external cost - jacobian - {%- if cost.cost_ext_fun_type_e == "casadi" %} - MAP_CASADI_FNC(ext_cost_e_fun_jac, {{ model.name }}_cost_ext_cost_e_fun_jac); - {%- else %} - capsule->ext_cost_e_fun_jac.fun = &{{ cost.cost_function_ext_cost_e }}; - external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun_jac, {{ dims.np }}); - {%- endif %} - - // external cost - hessian - {%- if cost.cost_ext_fun_type_e == "casadi" %} - MAP_CASADI_FNC(ext_cost_e_fun_jac_hess, {{ model.name }}_cost_ext_cost_e_fun_jac_hess); - {%- else %} - capsule->ext_cost_e_fun_jac_hess.fun = &{{ cost.cost_function_ext_cost_e }}; - external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun_jac_hess, {{ dims.np }}); - {%- endif %} -{%- endif %} - -#undef MAP_CASADI_FNC -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 4 - */ -void {{ model.name }}_acados_create_4_set_default_parameters({{ model.name }}_solver_capsule* capsule) { -{%- if dims.np > 0 %} - const int N = capsule->nlp_solver_plan->N; - // initialize parameters to nominal value - double* p = calloc(NP, sizeof(double)); - {%- for item in parameter_values %} - {%- if item != 0 %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i <= N; i++) { - {{ model.name }}_acados_update_params(capsule, i, p, NP); - } - free(p); -{%- else %} - // no parameters defined -{%- endif %}{# if dims.np #} -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 5 - */ -void {{ model.name }}_acados_create_5_set_nlp_in({{ model.name }}_solver_capsule* capsule, const int N, double* new_time_steps) -{ - assert(N == capsule->nlp_solver_plan->N); - ocp_nlp_config* nlp_config = capsule->nlp_config; - ocp_nlp_dims* nlp_dims = capsule->nlp_dims; - - /************************************************ - * nlp_in - ************************************************/ -// ocp_nlp_in * nlp_in = ocp_nlp_in_create(nlp_config, nlp_dims); -// capsule->nlp_in = nlp_in; - ocp_nlp_in * nlp_in = capsule->nlp_in; - - // set up time_steps - {% set all_equal = true -%} - {%- set val = solver_options.time_steps[0] %} - {%- for j in range(start=1, end=dims.N) %} - {%- if val != solver_options.time_steps[j] %} - {%- set_global all_equal = false %} - {%- break %} - {%- endif %} - {%- endfor %} - - if (new_time_steps) { - {{ model.name }}_acados_update_time_steps(capsule, N, new_time_steps); - } else { - {%- if all_equal == true -%} - // all time_steps are identical - double time_step = {{ solver_options.time_steps[0] }}; - for (int i = 0; i < N; i++) - { - ocp_nlp_in_set(nlp_config, nlp_dims, nlp_in, i, "Ts", &time_step); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "scaling", &time_step); - } - {%- else -%} - // time_steps are different - double* time_steps = malloc(N*sizeof(double)); - {%- for j in range(end=dims.N) %} - time_steps[{{ j }}] = {{ solver_options.time_steps[j] }}; - {%- endfor %} - {{ model.name }}_acados_update_time_steps(capsule, N, time_steps); - free(time_steps); - {%- endif %} - } - - /**** Dynamics ****/ - for (int i = 0; i < N; i++) - { - {%- if solver_options.integrator_type == "ERK" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_vde_forw", &capsule->forw_vde_casadi[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_ode_fun", &capsule->expl_ode_fun[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_ode_hess", &capsule->hess_vde_casadi[i]); - {%- endif %} - {% elif solver_options.integrator_type == "IRK" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun", &capsule->impl_dae_fun[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, - "impl_dae_fun_jac_x_xdot_z", &capsule->impl_dae_fun_jac_x_xdot_z[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, - "impl_dae_jac_x_xdot_u", &capsule->impl_dae_jac_x_xdot_u_z[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_hess", &capsule->impl_dae_hess[i]); - {%- endif %} - {% elif solver_options.integrator_type == "LIFTED_IRK" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun", &capsule->impl_dae_fun[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, - "impl_dae_fun_jac_x_xdot_u", &capsule->impl_dae_fun_jac_x_xdot_u[i]); - {% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun", &capsule->gnsf_phi_fun[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun_jac_y", &capsule->gnsf_phi_fun_jac_y[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_jac_y_uhat", &capsule->gnsf_phi_jac_y_uhat[i]); - {% if model.gnsf.nontrivial_f_LO == 1 %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "f_lo_jac_x1_x1dot_u_z", - &capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i]); - {%- endif %} - {%- endif %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "gnsf_get_matrices_fun", - &capsule->gnsf_get_matrices_fun[i]); - {% elif solver_options.integrator_type == "DISCRETE" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun", &capsule->discr_dyn_phi_fun[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun_jac", - &capsule->discr_dyn_phi_fun_jac_ut_xt[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun_jac_hess", - &capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i]); - {%- endif %} - {%- endif %} - } - - /**** Cost ****/ - -{%- if dims.ny_0 == 0 %} -{%- elif cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" or cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - double* yref_0 = calloc(NY0, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_0) %} - {%- if cost.yref_0[j] != 0 %} - yref_0[{{ j }}] = {{ cost.yref_0[j] }}; - {%- endif %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "yref", yref_0); - free(yref_0); -{%- endif %} - - -{%- if dims.ny == 0 %} -{%- elif cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" or cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - double* yref = calloc(NY, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny) %} - {%- if cost.yref[j] != 0 %} - yref[{{ j }}] = {{ cost.yref[j] }}; - {%- endif %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "yref", yref); - } - free(yref); -{%- endif %} - - -{%- if dims.ny_e == 0 %} -{%- elif cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" or cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - double* yref_e = calloc(NYN, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_e) %} - {%- if cost.yref_e[j] != 0 %} - yref_e[{{ j }}] = {{ cost.yref_e[j] }}; - {%- endif %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "yref", yref_e); - free(yref_e); -{%- endif %} - -{%- if dims.ny_0 == 0 %} -{%- elif cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" %} - double* W_0 = calloc(NY0*NY0, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_0) %} - {%- for k in range(end=dims.ny_0) %} - {%- if cost.W_0[j][k] != 0 %} - W_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.W_0[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "W", W_0); - free(W_0); -{%- endif %} - -{%- if dims.ny == 0 %} -{%- elif cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %} - double* W = calloc(NY*NY, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny) %} - {%- for k in range(end=dims.ny) %} - {%- if cost.W[j][k] != 0 %} - W[{{ j }}+(NY) * {{ k }}] = {{ cost.W[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "W", W); - } - free(W); -{%- endif %} - -{%- if dims.ny_e == 0 %} -{%- elif cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" %} - double* W_e = calloc(NYN*NYN, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_e) %} - {%- for k in range(end=dims.ny_e) %} - {%- if cost.W_e[j][k] != 0 %} - W_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.W_e[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "W", W_e); - free(W_e); -{%- endif %} - -{%- if dims.ny_0 == 0 %} -{%- elif cost.cost_type_0 == "LINEAR_LS" %} - double* Vx_0 = calloc(NY0*NX, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_0) %} - {%- for k in range(end=dims.nx) %} - {%- if cost.Vx_0[j][k] != 0 %} - Vx_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vx_0[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vx", Vx_0); - free(Vx_0); - - {%- if dims.nu > 0 %} - double* Vu_0 = calloc(NY0*NU, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_0) %} - {%- for k in range(end=dims.nu) %} - {%- if cost.Vu_0[j][k] != 0 %} - Vu_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vu_0[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vu", Vu_0); - free(Vu_0); - {%- endif %} - - {%- if dims.nz > 0 %} - double* Vz_0 = calloc(NY0*NZ, sizeof(double)); - // change only the non-zero elements: - {% for j in range(end=dims.ny_0) %} - {%- for k in range(end=dims.nz) %} - {%- if cost.Vz_0[j][k] != 0 %} - Vz_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vz_0[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vz", Vz_0); - free(Vz_0); - {%- endif %} -{%- endif %} - -{%- if dims.ny == 0 %} -{%- elif cost.cost_type == "LINEAR_LS" %} - double* Vx = calloc(NY*NX, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny) %} - {%- for k in range(end=dims.nx) %} - {%- if cost.Vx[j][k] != 0 %} - Vx[{{ j }}+(NY) * {{ k }}] = {{ cost.Vx[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vx", Vx); - } - free(Vx); - - {% if dims.nu > 0 %} - double* Vu = calloc(NY*NU, sizeof(double)); - // change only the non-zero elements: - {% for j in range(end=dims.ny) %} - {%- for k in range(end=dims.nu) %} - {%- if cost.Vu[j][k] != 0 %} - Vu[{{ j }}+(NY) * {{ k }}] = {{ cost.Vu[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vu", Vu); - } - free(Vu); - {%- endif %} - - {%- if dims.nz > 0 %} - double* Vz = calloc(NY*NZ, sizeof(double)); - // change only the non-zero elements: - {% for j in range(end=dims.ny) %} - {%- for k in range(end=dims.nz) %} - {%- if cost.Vz[j][k] != 0 %} - Vz[{{ j }}+(NY) * {{ k }}] = {{ cost.Vz[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vz", Vz); - } - free(Vz); - {%- endif %} -{%- endif %}{# LINEAR LS #} - -{%- if dims.ny_e == 0 %} -{%- elif cost.cost_type_e == "LINEAR_LS" %} - double* Vx_e = calloc(NYN*NX, sizeof(double)); - // change only the non-zero elements: - {% for j in range(end=dims.ny_e) %} - {%- for k in range(end=dims.nx) %} - {%- if cost.Vx_e[j][k] != 0 %} - Vx_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.Vx_e[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Vx", Vx_e); - free(Vx_e); -{%- endif %} - -{%- if cost.cost_type_0 == "NONLINEAR_LS" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_fun", &capsule->cost_y_0_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_fun_jac", &capsule->cost_y_0_fun_jac_ut_xt); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_hess", &capsule->cost_y_0_hess); -{%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "conl_cost_fun", &capsule->conl_cost_0_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "conl_cost_fun_jac_hess", &capsule->conl_cost_0_fun_jac_hess); -{%- elif cost.cost_type_0 == "EXTERNAL" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun", &capsule->ext_cost_0_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun_jac", &capsule->ext_cost_0_fun_jac); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun_jac_hess", &capsule->ext_cost_0_fun_jac_hess); -{%- endif %} - -{%- if cost.cost_type == "NONLINEAR_LS" %} - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_fun", &capsule->cost_y_fun[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_fun_jac", &capsule->cost_y_fun_jac_ut_xt[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_hess", &capsule->cost_y_hess[i-1]); - } -{%- elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "conl_cost_fun", &capsule->conl_cost_fun[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "conl_cost_fun_jac_hess", &capsule->conl_cost_fun_jac_hess[i-1]); - } -{%- elif cost.cost_type == "EXTERNAL" %} - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun", &capsule->ext_cost_fun[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun_jac", &capsule->ext_cost_fun_jac[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun_jac_hess", &capsule->ext_cost_fun_jac_hess[i-1]); - } -{%- endif %} - -{%- if cost.cost_type_e == "NONLINEAR_LS" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun", &capsule->cost_y_e_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun_jac", &capsule->cost_y_e_fun_jac_ut_xt); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_hess", &capsule->cost_y_e_hess); - -{%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "conl_cost_fun", &capsule->conl_cost_e_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "conl_cost_fun_jac_hess", &capsule->conl_cost_e_fun_jac_hess); - -{%- elif cost.cost_type_e == "EXTERNAL" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun", &capsule->ext_cost_e_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun_jac", &capsule->ext_cost_e_fun_jac); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun_jac_hess", &capsule->ext_cost_e_fun_jac_hess); -{%- endif %} - - -{%- if dims.ns > 0 %} - // slacks - double* zlumem = calloc(4*NS, sizeof(double)); - double* Zl = zlumem+NS*0; - double* Zu = zlumem+NS*1; - double* zl = zlumem+NS*2; - double* zu = zlumem+NS*3; - // change only the non-zero elements: - {%- for j in range(end=dims.ns) %} - {%- if cost.Zl[j] != 0 %} - Zl[{{ j }}] = {{ cost.Zl[j] }}; - {%- endif %} - {%- endfor %} - - {%- for j in range(end=dims.ns) %} - {%- if cost.Zu[j] != 0 %} - Zu[{{ j }}] = {{ cost.Zu[j] }}; - {%- endif %} - {%- endfor %} - - {%- for j in range(end=dims.ns) %} - {%- if cost.zl[j] != 0 %} - zl[{{ j }}] = {{ cost.zl[j] }}; - {%- endif %} - {%- endfor %} - - {%- for j in range(end=dims.ns) %} - {%- if cost.zu[j] != 0 %} - zu[{{ j }}] = {{ cost.zu[j] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Zl", Zl); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Zu", Zu); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zl", zl); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zu", zu); - } - free(zlumem); -{%- endif %} - -{% if dims.ns_e > 0 %} - // slacks terminal - double* zluemem = calloc(4*NSN, sizeof(double)); - double* Zl_e = zluemem+NSN*0; - double* Zu_e = zluemem+NSN*1; - double* zl_e = zluemem+NSN*2; - double* zu_e = zluemem+NSN*3; - - // change only the non-zero elements: - {% for j in range(end=dims.ns_e) %} - {%- if cost.Zl_e[j] != 0 %} - Zl_e[{{ j }}] = {{ cost.Zl_e[j] }}; - {%- endif %} - {%- endfor %} - - {% for j in range(end=dims.ns_e) %} - {%- if cost.Zu_e[j] != 0 %} - Zu_e[{{ j }}] = {{ cost.Zu_e[j] }}; - {%- endif %} - {%- endfor %} - - {% for j in range(end=dims.ns_e) %} - {%- if cost.zl_e[j] != 0 %} - zl_e[{{ j }}] = {{ cost.zl_e[j] }}; - {%- endif %} - {%- endfor %} - - {% for j in range(end=dims.ns_e) %} - {%- if cost.zu_e[j] != 0 %} - zu_e[{{ j }}] = {{ cost.zu_e[j] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Zl", Zl_e); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Zu", Zu_e); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "zl", zl_e); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "zu", zu_e); - free(zluemem); -{%- endif %} - - /**** Constraints ****/ - - // bounds for initial stage -{%- if dims.nbx_0 > 0 %} - // x0 - int* idxbx0 = malloc(NBX0 * sizeof(int)); - {%- for i in range(end=dims.nbx_0) %} - idxbx0[{{ i }}] = {{ constraints.idxbx_0[i] }}; - {%- endfor %} - - double* lubx0 = calloc(2*NBX0, sizeof(double)); - double* lbx0 = lubx0; - double* ubx0 = lubx0 + NBX0; - // change only the non-zero elements: - {%- for i in range(end=dims.nbx_0) %} - {%- if constraints.lbx_0[i] != 0 %} - lbx0[{{ i }}] = {{ constraints.lbx_0[i] }}; - {%- endif %} - {%- if constraints.ubx_0[i] != 0 %} - ubx0[{{ i }}] = {{ constraints.ubx_0[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbx", idxbx0); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbx", lbx0); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", ubx0); - free(idxbx0); - free(lubx0); -{%- endif %} - -{%- if dims.nbxe_0 > 0 %} - // idxbxe_0 - int* idxbxe_0 = malloc({{ dims.nbxe_0 }} * sizeof(int)); - {% for i in range(end=dims.nbxe_0) %} - idxbxe_0[{{ i }}] = {{ constraints.idxbxe_0[i] }}; - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbxe", idxbxe_0); - free(idxbxe_0); -{%- endif %} - - /* constraints that are the same for initial and intermediate */ -{%- if dims.nsbx > 0 %} -{# TODO: introduce nsbx0 & move this block down!! #} - // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxsbx", idxsbx); - // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lsbx", lsbx); - // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "usbx", usbx); - - // soft bounds on x - int* idxsbx = malloc(NSBX * sizeof(int)); - {%- for i in range(end=dims.nsbx) %} - idxsbx[{{ i }}] = {{ constraints.idxsbx[i] }}; - {%- endfor %} - - double* lusbx = calloc(2*NSBX, sizeof(double)); - double* lsbx = lusbx; - double* usbx = lusbx + NSBX; - {%- for i in range(end=dims.nsbx) %} - {%- if constraints.lsbx[i] != 0 %} - lsbx[{{ i }}] = {{ constraints.lsbx[i] }}; - {%- endif %} - {%- if constraints.usbx[i] != 0 %} - usbx[{{ i }}] = {{ constraints.usbx[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsbx", idxsbx); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsbx", lsbx); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usbx", usbx); - } - free(idxsbx); - free(lusbx); -{%- endif %} - - -{%- if dims.nbu > 0 %} - // u - int* idxbu = malloc(NBU * sizeof(int)); - {% for i in range(end=dims.nbu) %} - idxbu[{{ i }}] = {{ constraints.idxbu[i] }}; - {%- endfor %} - double* lubu = calloc(2*NBU, sizeof(double)); - double* lbu = lubu; - double* ubu = lubu + NBU; - {% for i in range(end=dims.nbu) %} - {%- if constraints.lbu[i] != 0 %} - lbu[{{ i }}] = {{ constraints.lbu[i] }}; - {%- endif %} - {%- if constraints.ubu[i] != 0 %} - ubu[{{ i }}] = {{ constraints.ubu[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxbu", idxbu); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lbu", lbu); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ubu", ubu); - } - free(idxbu); - free(lubu); -{%- endif %} - -{%- if dims.nsbu > 0 %} - // set up soft bounds for u - int* idxsbu = malloc(NSBU * sizeof(int)); - {% for i in range(end=dims.nsbu) %} - idxsbu[{{ i }}] = {{ constraints.idxsbu[i] }}; - {%- endfor %} - double* lusbu = calloc(2*NSBU, sizeof(double)); - double* lsbu = lusbu; - double* usbu = lusbu + NSBU; - {% for i in range(end=dims.nsbu) %} - {%- if constraints.lsbu[i] != 0 %} - lsbu[{{ i }}] = {{ constraints.lsbu[i] }}; - {%- endif %} - {%- if constraints.usbu[i] != 0 %} - usbu[{{ i }}] = {{ constraints.usbu[i] }}; - {%- endif %} - {%- endfor %} - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsbu", idxsbu); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsbu", lsbu); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usbu", usbu); - } - free(idxsbu); - free(lusbu); -{%- endif %} - -{% if dims.nsg > 0 %} - // set up soft bounds for general linear constraints - int* idxsg = malloc(NSG * sizeof(int)); - {% for i in range(end=dims.nsg) %} - idxsg[{{ i }}] = {{ constraints.idxsg[i] }}; - {%- endfor %} - double* lusg = calloc(2*NSG, sizeof(double)); - double* lsg = lusg; - double* usg = lusg + NSG; - {% for i in range(end=dims.nsg) %} - {%- if constraints.lsg[i] != 0 %} - lsg[{{ i }}] = {{ constraints.lsg[i] }}; - {%- endif %} - {%- if constraints.usg[i] != 0 %} - usg[{{ i }}] = {{ constraints.usg[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsg", idxsg); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsg", lsg); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usg", usg); - } - free(idxsg); - free(lusg); -{%- endif %} - -{% if dims.nsh > 0 %} - // set up soft bounds for nonlinear constraints - int* idxsh = malloc(NSH * sizeof(int)); - {% for i in range(end=dims.nsh) %} - idxsh[{{ i }}] = {{ constraints.idxsh[i] }}; - {%- endfor %} - double* lush = calloc(2*NSH, sizeof(double)); - double* lsh = lush; - double* ush = lush + NSH; - {% for i in range(end=dims.nsh) %} - {%- if constraints.lsh[i] != 0 %} - lsh[{{ i }}] = {{ constraints.lsh[i] }}; - {%- endif %} - {%- if constraints.ush[i] != 0 %} - ush[{{ i }}] = {{ constraints.ush[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsh", idxsh); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsh", lsh); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ush", ush); - } - free(idxsh); - free(lush); -{%- endif %} - -{% if dims.nsphi > 0 %} - // set up soft bounds for convex-over-nonlinear constraints - int* idxsphi = malloc(NSPHI * sizeof(int)); - {% for i in range(end=dims.nsphi) %} - idxsphi[{{ i }}] = {{ constraints.idxsphi[i] }}; - {%- endfor %} - double* lusphi = calloc(2*NSPHI, sizeof(double)); - double* lsphi = lusphi; - double* usphi = lusphi + NSPHI; - {% for i in range(end=dims.nsphi) %} - {%- if constraints.lsphi[i] != 0 %} - lsphi[{{ i }}] = {{ constraints.lsphi[i] }}; - {%- endif %} - {%- if constraints.usphi[i] != 0 %} - usphi[{{ i }}] = {{ constraints.usphi[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsphi", idxsphi); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsphi", lsphi); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usphi", usphi); - } - free(idxsphi); - free(lusphi); -{%- endif %} - -{% if dims.nbx > 0 %} - // x - int* idxbx = malloc(NBX * sizeof(int)); - {% for i in range(end=dims.nbx) %} - idxbx[{{ i }}] = {{ constraints.idxbx[i] }}; - {%- endfor %} - double* lubx = calloc(2*NBX, sizeof(double)); - double* lbx = lubx; - double* ubx = lubx + NBX; - {% for i in range(end=dims.nbx) %} - {%- if constraints.lbx[i] != 0 %} - lbx[{{ i }}] = {{ constraints.lbx[i] }}; - {%- endif %} - {%- if constraints.ubx[i] != 0 %} - ubx[{{ i }}] = {{ constraints.ubx[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxbx", idxbx); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lbx", lbx); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ubx", ubx); - } - free(idxbx); - free(lubx); -{%- endif %} - -{% if dims.ng > 0 %} - // set up general constraints for stage 0 to N-1 - double* D = calloc(NG*NU, sizeof(double)); - double* C = calloc(NG*NX, sizeof(double)); - double* lug = calloc(2*NG, sizeof(double)); - double* lg = lug; - double* ug = lug + NG; - - {% for j in range(end=dims.ng) -%} - {% for k in range(end=dims.nu) %} - {%- if constraints.D[j][k] != 0 %} - D[{{ j }}+NG * {{ k }}] = {{ constraints.D[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - {% for j in range(end=dims.ng) -%} - {% for k in range(end=dims.nx) %} - {%- if constraints.C[j][k] != 0 %} - C[{{ j }}+NG * {{ k }}] = {{ constraints.C[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - {% for i in range(end=dims.ng) %} - {%- if constraints.lg[i] != 0 %} - lg[{{ i }}] = {{ constraints.lg[i] }}; - {%- endif %} - {%- endfor %} - - {% for i in range(end=dims.ng) %} - {%- if constraints.ug[i] != 0 %} - ug[{{ i }}] = {{ constraints.ug[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "D", D); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "C", C); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lg", lg); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ug", ug); - } - free(D); - free(C); - free(lug); -{%- endif %} - -{% if dims.nh > 0 %} - // set up nonlinear constraints for stage 0 to N-1 - double* luh = calloc(2*NH, sizeof(double)); - double* lh = luh; - double* uh = luh + NH; - - {% for i in range(end=dims.nh) %} - {%- if constraints.lh[i] != 0 %} - lh[{{ i }}] = {{ constraints.lh[i] }}; - {%- endif %} - {%- endfor %} - - {% for i in range(end=dims.nh) %} - {%- if constraints.uh[i] != 0 %} - uh[{{ i }}] = {{ constraints.uh[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - // nonlinear constraints for stages 0 to N-1 - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun_jac", - &capsule->nl_constr_h_fun_jac[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun", - &capsule->nl_constr_h_fun[i]); - {% if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, - "nl_constr_h_fun_jac_hess", &capsule->nl_constr_h_fun_jac_hess[i]); - {% endif %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lh", lh); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uh", uh); - } - free(luh); -{%- endif %} - -{% if dims.nphi > 0 and constraints.constr_type == "BGP" %} - // set up convex-over-nonlinear constraints for stage 0 to N-1 - double* luphi = calloc(2*NPHI, sizeof(double)); - double* lphi = luphi; - double* uphi = luphi + NPHI; - {% for i in range(end=dims.nphi) %} - {%- if constraints.lphi[i] != 0 %} - lphi[{{ i }}] = {{ constraints.lphi[i] }}; - {%- endif %} - {%- endfor %} - - {% for i in range(end=dims.nphi) %} - {%- if constraints.uphi[i] != 0 %} - uphi[{{ i }}] = {{ constraints.uphi[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, - "nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &capsule->phi_constraint[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lphi", lphi); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uphi", uphi); - } - free(luphi); -{%- endif %} - - /* terminal constraints */ -{% if dims.nbx_e > 0 %} - // set up bounds for last stage - // x - int* idxbx_e = malloc(NBXN * sizeof(int)); - {% for i in range(end=dims.nbx_e) %} - idxbx_e[{{ i }}] = {{ constraints.idxbx_e[i] }}; - {%- endfor %} - double* lubx_e = calloc(2*NBXN, sizeof(double)); - double* lbx_e = lubx_e; - double* ubx_e = lubx_e + NBXN; - {% for i in range(end=dims.nbx_e) %} - {%- if constraints.lbx_e[i] != 0 %} - lbx_e[{{ i }}] = {{ constraints.lbx_e[i] }}; - {%- endif %} - {%- if constraints.ubx_e[i] != 0 %} - ubx_e[{{ i }}] = {{ constraints.ubx_e[i] }}; - {%- endif %} - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxbx", idxbx_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lbx", lbx_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ubx", ubx_e); - free(idxbx_e); - free(lubx_e); -{%- endif %} - -{% if dims.nsg_e > 0 %} - // set up soft bounds for general linear constraints - int* idxsg_e = calloc(NSGN, sizeof(int)); - {% for i in range(end=dims.nsg_e) %} - idxsg_e[{{ i }}] = {{ constraints.idxsg_e[i] }}; - {%- endfor %} - double* lusg_e = calloc(2*NSGN, sizeof(double)); - double* lsg_e = lusg_e; - double* usg_e = lusg_e + NSGN; - {% for i in range(end=dims.nsg_e) %} - {%- if constraints.lsg_e[i] != 0 %} - lsg_e[{{ i }}] = {{ constraints.lsg_e[i] }}; - {%- endif %} - {%- if constraints.usg_e[i] != 0 %} - usg_e[{{ i }}] = {{ constraints.usg_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsg", idxsg_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsg", lsg_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usg", usg_e); - free(idxsg_e); - free(lusg_e); -{%- endif %} - -{% if dims.nsh_e > 0 %} - // set up soft bounds for nonlinear constraints - int* idxsh_e = malloc(NSHN * sizeof(int)); - {% for i in range(end=dims.nsh_e) %} - idxsh_e[{{ i }}] = {{ constraints.idxsh_e[i] }}; - {%- endfor %} - double* lush_e = calloc(2*NSHN, sizeof(double)); - double* lsh_e = lush_e; - double* ush_e = lush_e + NSHN; - {% for i in range(end=dims.nsh_e) %} - {%- if constraints.lsh_e[i] != 0 %} - lsh_e[{{ i }}] = {{ constraints.lsh_e[i] }}; - {%- endif %} - {%- if constraints.ush_e[i] != 0 %} - ush_e[{{ i }}] = {{ constraints.ush_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsh", idxsh_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsh", lsh_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ush", ush_e); - free(idxsh_e); - free(lush_e); -{%- endif %} - -{% if dims.nsphi_e > 0 %} - // set up soft bounds for convex-over-nonlinear constraints - int* idxsphi_e = malloc(NSPHIN * sizeof(int)); - {% for i in range(end=dims.nsphi_e) %} - idxsphi_e[{{ i }}] = {{ constraints.idxsphi_e[i] }}; - {%- endfor %} - double* lusphi_e = calloc(2*NSPHIN, sizeof(double)); - double* lsphi_e = lusphi_e; - double* usphi_e = lusphi_e + NSPHIN; - {% for i in range(end=dims.nsphi_e) %} - {%- if constraints.lsphi_e[i] != 0 %} - lsphi_e[{{ i }}] = {{ constraints.lsphi_e[i] }}; - {%- endif %} - {%- if constraints.usphi_e[i] != 0 %} - usphi_e[{{ i }}] = {{ constraints.usphi_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsphi", idxsphi_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsphi", lsphi_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usphi", usphi_e); - free(idxsphi_e); - free(lusphi_e); -{%- endif %} - -{% if dims.nsbx_e > 0 %} - // soft bounds on x - int* idxsbx_e = malloc(NSBXN * sizeof(int)); - {% for i in range(end=dims.nsbx_e) %} - idxsbx_e[{{ i }}] = {{ constraints.idxsbx_e[i] }}; - {%- endfor %} - double* lusbx_e = calloc(2*NSBXN, sizeof(double)); - double* lsbx_e = lusbx_e; - double* usbx_e = lusbx_e + NSBXN; - {% for i in range(end=dims.nsbx_e) %} - {%- if constraints.lsbx_e[i] != 0 %} - lsbx_e[{{ i }}] = {{ constraints.lsbx_e[i] }}; - {%- endif %} - {%- if constraints.usbx_e[i] != 0 %} - usbx_e[{{ i }}] = {{ constraints.usbx_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsbx", idxsbx_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsbx", lsbx_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usbx", usbx_e); - free(idxsbx_e); - free(lusbx_e); -{% endif %} - -{% if dims.ng_e > 0 %} - // set up general constraints for last stage - double* C_e = calloc(NGN*NX, sizeof(double)); - double* lug_e = calloc(2*NGN, sizeof(double)); - double* lg_e = lug_e; - double* ug_e = lug_e + NGN; - - {% for j in range(end=dims.ng_e) %} - {%- for k in range(end=dims.nx) %} - {%- if constraints.C_e[j][k] != 0 %} - C_e[{{ j }}+NGN * {{ k }}] = {{ constraints.C_e[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - {% for i in range(end=dims.ng_e) %} - {%- if constraints.lg_e[i] != 0 %} - lg_e[{{ i }}] = {{ constraints.lg_e[i] }}; - {%- endif %} - {%- if constraints.ug_e[i] != 0 %} - ug_e[{{ i }}] = {{ constraints.ug_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "C", C_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lg", lg_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ug", ug_e); - free(C_e); - free(lug_e); -{%- endif %} - -{% if dims.nh_e > 0 %} - // set up nonlinear constraints for last stage - double* luh_e = calloc(2*NHN, sizeof(double)); - double* lh_e = luh_e; - double* uh_e = luh_e + NHN; - {% for i in range(end=dims.nh_e) %} - {%- if constraints.lh_e[i] != 0 %} - lh_e[{{ i }}] = {{ constraints.lh_e[i] }}; - {%- endif %} - {%- endfor %} - - {% for i in range(end=dims.nh_e) %} - {%- if constraints.uh_e[i] != 0 %} - uh_e[{{ i }}] = {{ constraints.uh_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun_jac", &capsule->nl_constr_h_e_fun_jac); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun", &capsule->nl_constr_h_e_fun); - {% if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun_jac_hess", - &capsule->nl_constr_h_e_fun_jac_hess); - {% endif %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lh", lh_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uh", uh_e); - free(luh_e); -{%- endif %} - -{% if dims.nphi_e > 0 and constraints.constr_type_e == "BGP" %} - // set up convex-over-nonlinear constraints for last stage - double* luphi_e = calloc(2*NPHIN, sizeof(double)); - double* lphi_e = luphi_e; - double* uphi_e = luphi_e + NPHIN; - {% for i in range(end=dims.nphi_e) %} - {%- if constraints.lphi_e[i] != 0 %} - lphi_e[{{ i }}] = {{ constraints.lphi_e[i] }}; - {%- endif %} - {%- if constraints.uphi_e[i] != 0 %} - uphi_e[{{ i }}] = {{ constraints.uphi_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lphi", lphi_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uphi", uphi_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, - "nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &capsule->phi_e_constraint); - free(luphi_e); -{% endif %} -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 6 - */ -void {{ model.name }}_acados_create_6_set_opts({{ model.name }}_solver_capsule* capsule) -{ - const int N = capsule->nlp_solver_plan->N; - ocp_nlp_config* nlp_config = capsule->nlp_config; - void *nlp_opts = capsule->nlp_opts; - - /************************************************ - * opts - ************************************************/ - -{% if solver_options.hessian_approx == "EXACT" %} - int nlp_solver_exact_hessian = 1; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess", &nlp_solver_exact_hessian); - - int exact_hess_dyn = {{ solver_options.exact_hess_dyn }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_dyn", &exact_hess_dyn); - - int exact_hess_cost = {{ solver_options.exact_hess_cost }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_cost", &exact_hess_cost); - - int exact_hess_constr = {{ solver_options.exact_hess_constr }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_constr", &exact_hess_constr); -{%- endif -%} - -{%- if solver_options.globalization == "FIXED_STEP" %} - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "globalization", "fixed_step"); -{%- elif solver_options.globalization == "MERIT_BACKTRACKING" %} - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "globalization", "merit_backtracking"); - - double alpha_min = {{ solver_options.alpha_min }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "alpha_min", &alpha_min); - - double alpha_reduction = {{ solver_options.alpha_reduction }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "alpha_reduction", &alpha_reduction); - - int line_search_use_sufficient_descent = {{ solver_options.line_search_use_sufficient_descent }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "line_search_use_sufficient_descent", &line_search_use_sufficient_descent); - - int globalization_use_SOC = {{ solver_options.globalization_use_SOC }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "globalization_use_SOC", &globalization_use_SOC); - - double eps_sufficient_descent = {{ solver_options.eps_sufficient_descent }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "eps_sufficient_descent", &eps_sufficient_descent); -{%- endif -%} - int full_step_dual = {{ solver_options.full_step_dual }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "full_step_dual", &full_step_dual); - -{%- if dims.nz > 0 %} - // TODO: these options are lower level -> should be encapsulated! maybe through hessian approx option. - bool output_z_val = true; - bool sens_algebraic_val = true; - - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_output_z", &output_z_val); - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_sens_algebraic", &sens_algebraic_val); -{%- endif %} - -{%- if solver_options.integrator_type != "DISCRETE" %} - - // set collocation type (relevant for implicit integrators) - sim_collocation_type collocation_type = {{ solver_options.collocation_type }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_collocation_type", &collocation_type); - - // set up sim_method_num_steps - {%- set all_equal = true %} - {%- set val = solver_options.sim_method_num_steps[0] %} - {%- for j in range(start=1, end=dims.N) %} - {%- if val != solver_options.sim_method_num_steps[j] %} - {%- set_global all_equal = false %} - {%- break %} - {%- endif %} - {%- endfor %} - - {%- if all_equal == true %} - // all sim_method_num_steps are identical - int sim_method_num_steps = {{ solver_options.sim_method_num_steps[0] }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps); - {%- else %} - // sim_method_num_steps are different - int* sim_method_num_steps = malloc(N*sizeof(int)); - {%- for j in range(end=dims.N) %} - sim_method_num_steps[{{ j }}] = {{ solver_options.sim_method_num_steps[j] }}; - {%- endfor %} - - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps[i]); - free(sim_method_num_steps); - {%- endif %} - - // set up sim_method_num_stages - {%- set all_equal = true %} - {%- set val = solver_options.sim_method_num_stages[0] %} - {%- for j in range(start=1, end=dims.N) %} - {%- if val != solver_options.sim_method_num_stages[j] %} - {%- set_global all_equal = false %} - {%- break %} - {%- endif %} - {%- endfor %} - - {%- if all_equal == true %} - // all sim_method_num_stages are identical - int sim_method_num_stages = {{ solver_options.sim_method_num_stages[0] }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages); - {%- else %} - int* sim_method_num_stages = malloc(N*sizeof(int)); - {%- for j in range(end=dims.N) %} - sim_method_num_stages[{{ j }}] = {{ solver_options.sim_method_num_stages[j] }}; - {%- endfor %} - - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages[i]); - free(sim_method_num_stages); - {%- endif %} - - int newton_iter_val = {{ solver_options.sim_method_newton_iter }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_newton_iter", &newton_iter_val); - - - // set up sim_method_jac_reuse - {%- set all_equal = true %} - {%- set val = solver_options.sim_method_jac_reuse[0] %} - {%- for j in range(start=1, end=dims.N) %} - {%- if val != solver_options.sim_method_jac_reuse[j] %} - {%- set_global all_equal = false %} - {%- break %} - {%- endif %} - {%- endfor %} - {%- if all_equal == true %} - bool tmp_bool = (bool) {{ solver_options.sim_method_jac_reuse[0] }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_jac_reuse", &tmp_bool); - {%- else %} - bool* sim_method_jac_reuse = malloc(N*sizeof(bool)); - {%- for j in range(end=dims.N) %} - sim_method_jac_reuse[{{ j }}] = (bool){{ solver_options.sim_method_jac_reuse[j] }}; - {%- endfor %} - - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_jac_reuse", &sim_method_jac_reuse[i]); - free(sim_method_jac_reuse); - {%- endif %} - -{%- endif %} - - double nlp_solver_step_length = {{ solver_options.nlp_solver_step_length }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "step_length", &nlp_solver_step_length); - - {%- if solver_options.nlp_solver_warm_start_first_qp %} - int nlp_solver_warm_start_first_qp = {{ solver_options.nlp_solver_warm_start_first_qp }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "warm_start_first_qp", &nlp_solver_warm_start_first_qp); - {%- endif %} - - double levenberg_marquardt = {{ solver_options.levenberg_marquardt }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "levenberg_marquardt", &levenberg_marquardt); - - /* options QP solver */ -{%- if solver_options.qp_solver is starting_with("PARTIAL_CONDENSING") %} - int qp_solver_cond_N; - - {% if solver_options.qp_solver_cond_N -%} - const int qp_solver_cond_N_ori = {{ solver_options.qp_solver_cond_N }}; - qp_solver_cond_N = N < qp_solver_cond_N_ori ? N : qp_solver_cond_N_ori; // use the minimum value here - {%- else %} - // NOTE: there is no condensing happening here! - qp_solver_cond_N = N; - {%- endif %} - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_cond_N", &qp_solver_cond_N); -{%- endif %} - - int nlp_solver_ext_qp_res = {{ solver_options.nlp_solver_ext_qp_res }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "ext_qp_res", &nlp_solver_ext_qp_res); - -{%- if solver_options.qp_solver is containing("HPIPM") %} - // set HPIPM mode: should be done before setting other QP solver options - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_hpipm_mode", "{{ solver_options.hpipm_mode }}"); -{%- endif %} - -{% if solver_options.nlp_solver_type == "SQP" %} - // set SQP specific options - double nlp_solver_tol_stat = {{ solver_options.nlp_solver_tol_stat }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_stat", &nlp_solver_tol_stat); - - double nlp_solver_tol_eq = {{ solver_options.nlp_solver_tol_eq }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_eq", &nlp_solver_tol_eq); - - double nlp_solver_tol_ineq = {{ solver_options.nlp_solver_tol_ineq }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_ineq", &nlp_solver_tol_ineq); - - double nlp_solver_tol_comp = {{ solver_options.nlp_solver_tol_comp }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_comp", &nlp_solver_tol_comp); - - int nlp_solver_max_iter = {{ solver_options.nlp_solver_max_iter }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "max_iter", &nlp_solver_max_iter); - - int initialize_t_slacks = {{ solver_options.initialize_t_slacks }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "initialize_t_slacks", &initialize_t_slacks); -{%- endif %} - - int qp_solver_iter_max = {{ solver_options.qp_solver_iter_max }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_iter_max", &qp_solver_iter_max); - -{# NOTE: qp_solver tolerances must be set after NLP ones, since the setter for NLP tolerances sets the QP tolerances to the sam values. #} - {%- if solver_options.qp_solver_tol_stat %} - double qp_solver_tol_stat = {{ solver_options.qp_solver_tol_stat }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_stat", &qp_solver_tol_stat); - {%- endif -%} - - {%- if solver_options.qp_solver_tol_eq %} - double qp_solver_tol_eq = {{ solver_options.qp_solver_tol_eq }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_eq", &qp_solver_tol_eq); - {%- endif -%} - - {%- if solver_options.qp_solver_tol_ineq %} - double qp_solver_tol_ineq = {{ solver_options.qp_solver_tol_ineq }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_ineq", &qp_solver_tol_ineq); - {%- endif -%} - - {%- if solver_options.qp_solver_tol_comp %} - double qp_solver_tol_comp = {{ solver_options.qp_solver_tol_comp }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_comp", &qp_solver_tol_comp); - {%- endif -%} - - {%- if solver_options.qp_solver_warm_start %} - int qp_solver_warm_start = {{ solver_options.qp_solver_warm_start }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_warm_start", &qp_solver_warm_start); - {%- endif -%} - - int print_level = {{ solver_options.print_level }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "print_level", &print_level); - -{%- if solver_options.qp_solver is containing('PARTIAL_CONDENSING') %} - int qp_solver_cond_ric_alg = {{ solver_options.qp_solver_cond_ric_alg }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_cond_ric_alg", &qp_solver_cond_ric_alg); -{% endif %} - -{%- if solver_options.qp_solver == 'PARTIAL_CONDENSING_HPIPM' %} - int qp_solver_ric_alg = {{ solver_options.qp_solver_ric_alg }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_ric_alg", &qp_solver_ric_alg); -{% endif %} - - int ext_cost_num_hess = {{ solver_options.ext_cost_num_hess }}; -{%- if cost.cost_type == "EXTERNAL" %} - for (int i = 0; i < N; i++) - { - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "cost_numerical_hessian", &ext_cost_num_hess); - } -{%- endif %} -{%- if cost.cost_type_e == "EXTERNAL" %} - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, N, "cost_numerical_hessian", &ext_cost_num_hess); -{%- endif %} -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 7 - */ -void {{ model.name }}_acados_create_7_set_nlp_out({{ model.name }}_solver_capsule* capsule) -{ - const int N = capsule->nlp_solver_plan->N; - ocp_nlp_config* nlp_config = capsule->nlp_config; - ocp_nlp_dims* nlp_dims = capsule->nlp_dims; - ocp_nlp_out* nlp_out = capsule->nlp_out; - - // initialize primal solution - double* xu0 = calloc(NX+NU, sizeof(double)); - double* x0 = xu0; -{% if dims.nbx_0 == dims.nx %} - // initialize with x0 - {% for item in constraints.lbx_0 %} - {%- if item != 0 %} - x0[{{ loop.index0 }}] = {{ item }}; - {%- endif %} - {%- endfor %} -{% else %} - // initialize with zeros -{%- endif %} - - double* u0 = xu0 + NX; - - for (int i = 0; i < N; i++) - { - // x0 - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x0); - // u0 - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0); - } - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, N, "x", x0); - free(xu0); -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 8 - */ -//void {{ model.name }}_acados_create_8_create_solver({{ model.name }}_solver_capsule* capsule) -//{ -// capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); -//} - -/** - * Internal function for {{ model.name }}_acados_create: step 9 - */ -int {{ model.name }}_acados_create_9_precompute({{ model.name }}_solver_capsule* capsule) { - int status = ocp_nlp_precompute(capsule->nlp_solver, capsule->nlp_in, capsule->nlp_out); - - if (status != ACADOS_SUCCESS) { - printf("\nocp_nlp_precompute failed!\n\n"); - exit(1); - } - - return status; -} - - -int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule* capsule, int N, double* new_time_steps) -{ - // If N does not match the number of shooting intervals used for code generation, new_time_steps must be given. - if (N != {{ model.name | upper }}_N && !new_time_steps) { - fprintf(stderr, "{{ model.name }}_acados_create_with_discretization: new_time_steps is NULL " \ - "but the number of shooting intervals (= %d) differs from the number of " \ - "shooting intervals (= %d) during code generation! Please provide a new vector of time_stamps!\n", \ - N, {{ model.name | upper }}_N); - return 1; - } - - // number of expected runtime parameters - capsule->nlp_np = NP; - - // 1) create and set nlp_solver_plan; create nlp_config - capsule->nlp_solver_plan = ocp_nlp_plan_create(N); - {{ model.name }}_acados_create_1_set_plan(capsule->nlp_solver_plan, N); - capsule->nlp_config = ocp_nlp_config_create(*capsule->nlp_solver_plan); - - // 3) create and set dimensions - capsule->nlp_dims = {{ model.name }}_acados_create_2_create_and_set_dimensions(capsule); - {{ model.name }}_acados_create_3_create_and_set_functions(capsule); - - // 4) set default parameters in functions - {{ model.name }}_acados_create_4_set_default_parameters(capsule); - - // 5) create and set nlp_in - capsule->nlp_in = ocp_nlp_in_create(capsule->nlp_config, capsule->nlp_dims); - {{ model.name }}_acados_create_5_set_nlp_in(capsule, N, new_time_steps); - - // 6) create and set nlp_opts - capsule->nlp_opts = ocp_nlp_solver_opts_create(capsule->nlp_config, capsule->nlp_dims); - {{ model.name }}_acados_create_6_set_opts(capsule); - - // 7) create and set nlp_out - // 7.1) nlp_out - capsule->nlp_out = ocp_nlp_out_create(capsule->nlp_config, capsule->nlp_dims); - // 7.2) sens_out - capsule->sens_out = ocp_nlp_out_create(capsule->nlp_config, capsule->nlp_dims); - {{ model.name }}_acados_create_7_set_nlp_out(capsule); - - // 8) create solver - capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); - //{{ model.name }}_acados_create_8_create_solver(capsule); - - // 9) do precomputations - int status = {{ model.name }}_acados_create_9_precompute(capsule); - - {%- if custom_update_filename != "" %} - // Initialize custom update function - custom_update_init_function(capsule); - {%- endif %} - - return status; -} - -/** - * This function is for updating an already initialized solver with a different number of qp_cond_N. It is useful for code reuse after code export. - */ -int {{ model.name }}_acados_update_qp_solver_cond_N({{ model.name }}_solver_capsule* capsule, int qp_solver_cond_N) -{ -{%- if solver_options.qp_solver is starting_with("PARTIAL_CONDENSING") %} - // 1) destroy solver - ocp_nlp_solver_destroy(capsule->nlp_solver); - - // 2) set new value for "qp_cond_N" - const int N = capsule->nlp_solver_plan->N; - if(qp_solver_cond_N > N) - printf("Warning: qp_solver_cond_N = %d > N = %d\n", qp_solver_cond_N, N); - ocp_nlp_solver_opts_set(capsule->nlp_config, capsule->nlp_opts, "qp_cond_N", &qp_solver_cond_N); - - // 3) continue with the remaining steps from {{ model.name }}_acados_create_with_discretization(...): - // -> 8) create solver - capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); - - // -> 9) do precomputations - int status = {{ model.name }}_acados_create_9_precompute(capsule); - return status; -{%- else %} - printf("\nacados_update_qp_solver_cond_N() failed, since no partial condensing solver is used!\n\n"); - // Todo: what is an adequate behavior here? - exit(1); - return -1; -{%- endif %} -} - - -int {{ model.name }}_acados_reset({{ model.name }}_solver_capsule* capsule, int reset_qp_solver_mem) -{ - - // set initialization to all zeros -{# TODO: use guess values / initial state value from json instead?! #} - const int N = capsule->nlp_solver_plan->N; - ocp_nlp_config* nlp_config = capsule->nlp_config; - ocp_nlp_dims* nlp_dims = capsule->nlp_dims; - ocp_nlp_out* nlp_out = capsule->nlp_out; - ocp_nlp_in* nlp_in = capsule->nlp_in; - ocp_nlp_solver* nlp_solver = capsule->nlp_solver; - - double* buffer = calloc(NX+NU+NZ+2*NS+2*NSN+NBX+NBU+NG+NH+NPHI+NBX0+NBXN+NHN+NPHIN+NGN, sizeof(double)); - - for(int i=0; i reset memory - int qp_status; - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "qp_status", &qp_status); - if (reset_qp_solver_mem || (qp_status == 3)) - { - // printf("\nin reset qp_status %d -> resetting QP memory\n", qp_status); - ocp_nlp_solver_reset_qp_memory(nlp_solver, nlp_in, nlp_out); - } -{%- endif %} - - free(buffer); - return 0; -} - - - - -int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule* capsule, int stage, double *p, int np) -{ - int solver_status = 0; - - int casadi_np = {{ dims.np }}; - if (casadi_np != np) { - printf("acados_update_params: trying to set %i parameters for external functions." - " External function has %i parameters. Exiting.\n", np, casadi_np); - exit(1); - } - - const int N = capsule->nlp_solver_plan->N; - if (stage < N && stage >= 0) - { - {%- if solver_options.integrator_type == "IRK" %} - capsule->impl_dae_fun[stage].set_param(capsule->impl_dae_fun+stage, p); - capsule->impl_dae_fun_jac_x_xdot_z[stage].set_param(capsule->impl_dae_fun_jac_x_xdot_z+stage, p); - capsule->impl_dae_jac_x_xdot_u_z[stage].set_param(capsule->impl_dae_jac_x_xdot_u_z+stage, p); - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->impl_dae_hess[stage].set_param(capsule->impl_dae_hess+stage, p); - {%- endif %} - {% elif solver_options.integrator_type == "LIFTED_IRK" %} - capsule->impl_dae_fun[stage].set_param(capsule->impl_dae_fun+stage, p); - capsule->impl_dae_fun_jac_x_xdot_u[stage].set_param(capsule->impl_dae_fun_jac_x_xdot_u+stage, p); - {% elif solver_options.integrator_type == "ERK" %} - capsule->forw_vde_casadi[stage].set_param(capsule->forw_vde_casadi+stage, p); - capsule->expl_ode_fun[stage].set_param(capsule->expl_ode_fun+stage, p); - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->hess_vde_casadi[stage].set_param(capsule->hess_vde_casadi+stage, p); - {%- endif %} - {% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - capsule->gnsf_phi_fun[stage].set_param(capsule->gnsf_phi_fun+stage, p); - capsule->gnsf_phi_fun_jac_y[stage].set_param(capsule->gnsf_phi_fun_jac_y+stage, p); - capsule->gnsf_phi_jac_y_uhat[stage].set_param(capsule->gnsf_phi_jac_y_uhat+stage, p); - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[stage].set_param(capsule->gnsf_f_lo_jac_x1_x1dot_u_z+stage, p); - {%- endif %} - {%- endif %} - {% elif solver_options.integrator_type == "DISCRETE" %} - capsule->discr_dyn_phi_fun[stage].set_param(capsule->discr_dyn_phi_fun+stage, p); - capsule->discr_dyn_phi_fun_jac_ut_xt[stage].set_param(capsule->discr_dyn_phi_fun_jac_ut_xt+stage, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[stage].set_param(capsule->discr_dyn_phi_fun_jac_ut_xt_hess+stage, p); - {% endif %} - {%- endif %}{# integrator_type #} - - // constraints - {% if constraints.constr_type == "BGP" %} - capsule->phi_constraint[stage].set_param(capsule->phi_constraint+stage, p); - {% elif constraints.constr_type == "BGH" and dims.nh > 0 %} - capsule->nl_constr_h_fun_jac[stage].set_param(capsule->nl_constr_h_fun_jac+stage, p); - capsule->nl_constr_h_fun[stage].set_param(capsule->nl_constr_h_fun+stage, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_fun_jac_hess[stage].set_param(capsule->nl_constr_h_fun_jac_hess+stage, p); - {%- endif %} - {%- endif %} - - // cost - if (stage == 0) - { - {%- if cost.cost_type_0 == "NONLINEAR_LS" %} - capsule->cost_y_0_fun.set_param(&capsule->cost_y_0_fun, p); - capsule->cost_y_0_fun_jac_ut_xt.set_param(&capsule->cost_y_0_fun_jac_ut_xt, p); - capsule->cost_y_0_hess.set_param(&capsule->cost_y_0_hess, p); - {%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_0_fun.set_param(&capsule->conl_cost_0_fun, p); - capsule->conl_cost_0_fun_jac_hess.set_param(&capsule->conl_cost_0_fun_jac_hess, p); - {%- elif cost.cost_type_0 == "EXTERNAL" %} - capsule->ext_cost_0_fun.set_param(&capsule->ext_cost_0_fun, p); - capsule->ext_cost_0_fun_jac.set_param(&capsule->ext_cost_0_fun_jac, p); - capsule->ext_cost_0_fun_jac_hess.set_param(&capsule->ext_cost_0_fun_jac_hess, p); - {% endif %} - } - else // 0 < stage < N - { - {%- if cost.cost_type == "NONLINEAR_LS" %} - capsule->cost_y_fun[stage-1].set_param(capsule->cost_y_fun+stage-1, p); - capsule->cost_y_fun_jac_ut_xt[stage-1].set_param(capsule->cost_y_fun_jac_ut_xt+stage-1, p); - capsule->cost_y_hess[stage-1].set_param(capsule->cost_y_hess+stage-1, p); - {%- elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_fun[stage-1].set_param(capsule->conl_cost_fun+stage-1, p); - capsule->conl_cost_fun_jac_hess[stage-1].set_param(capsule->conl_cost_fun_jac_hess+stage-1, p); - {%- elif cost.cost_type == "EXTERNAL" %} - capsule->ext_cost_fun[stage-1].set_param(capsule->ext_cost_fun+stage-1, p); - capsule->ext_cost_fun_jac[stage-1].set_param(capsule->ext_cost_fun_jac+stage-1, p); - capsule->ext_cost_fun_jac_hess[stage-1].set_param(capsule->ext_cost_fun_jac_hess+stage-1, p); - {%- endif %} - } - } - - else // stage == N - { - // terminal shooting node has no dynamics - // cost - {%- if cost.cost_type_e == "NONLINEAR_LS" %} - capsule->cost_y_e_fun.set_param(&capsule->cost_y_e_fun, p); - capsule->cost_y_e_fun_jac_ut_xt.set_param(&capsule->cost_y_e_fun_jac_ut_xt, p); - capsule->cost_y_e_hess.set_param(&capsule->cost_y_e_hess, p); - {%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_e_fun.set_param(&capsule->conl_cost_e_fun, p); - capsule->conl_cost_e_fun_jac_hess.set_param(&capsule->conl_cost_e_fun_jac_hess, p); - {%- elif cost.cost_type_e == "EXTERNAL" %} - capsule->ext_cost_e_fun.set_param(&capsule->ext_cost_e_fun, p); - capsule->ext_cost_e_fun_jac.set_param(&capsule->ext_cost_e_fun_jac, p); - capsule->ext_cost_e_fun_jac_hess.set_param(&capsule->ext_cost_e_fun_jac_hess, p); - {% endif %} - // constraints - {% if constraints.constr_type_e == "BGP" %} - capsule->phi_e_constraint.set_param(&capsule->phi_e_constraint, p); - {% elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - capsule->nl_constr_h_e_fun_jac.set_param(&capsule->nl_constr_h_e_fun_jac, p); - capsule->nl_constr_h_e_fun.set_param(&capsule->nl_constr_h_e_fun, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_e_fun_jac_hess.set_param(&capsule->nl_constr_h_e_fun_jac_hess, p); - {%- endif %} - {% endif %} - } - - return solver_status; -} - - -int {{ model.name }}_acados_update_params_sparse({{ model.name }}_solver_capsule * capsule, int stage, int *idx, double *p, int n_update) -{ - int solver_status = 0; - - int casadi_np = {{ dims.np }}; - if (casadi_np < n_update) { - printf("{{ model.name }}_acados_update_params_sparse: trying to set %d parameters for external functions." - " External function has %d parameters. Exiting.\n", n_update, casadi_np); - exit(1); - } - // for (int i = 0; i < n_update; i++) - // { - // if (idx[i] > casadi_np) { - // printf("{{ model.name }}_acados_update_params_sparse: attempt to set parameters with index %d, while" - // " external functions only has %d parameters. Exiting.\n", idx[i], casadi_np); - // exit(1); - // } - // printf("param %d value %e\n", idx[i], p[i]); - // } - -{%- if dims.np > 0 %} - const int N = capsule->nlp_solver_plan->N; - if (stage < N && stage >= 0) - { - {%- if solver_options.integrator_type == "IRK" %} - capsule->impl_dae_fun[stage].set_param_sparse(capsule->impl_dae_fun+stage, n_update, idx, p); - capsule->impl_dae_fun_jac_x_xdot_z[stage].set_param_sparse(capsule->impl_dae_fun_jac_x_xdot_z+stage, n_update, idx, p); - capsule->impl_dae_jac_x_xdot_u_z[stage].set_param_sparse(capsule->impl_dae_jac_x_xdot_u_z+stage, n_update, idx, p); - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->impl_dae_hess[stage].set_param_sparse(capsule->impl_dae_hess+stage, n_update, idx, p); - {%- endif %} - {% elif solver_options.integrator_type == "LIFTED_IRK" %} - capsule->impl_dae_fun[stage].set_param_sparse(capsule->impl_dae_fun+stage, n_update, idx, p); - capsule->impl_dae_fun_jac_x_xdot_u[stage].set_param_sparse(capsule->impl_dae_fun_jac_x_xdot_u+stage, n_update, idx, p); - {% elif solver_options.integrator_type == "ERK" %} - capsule->forw_vde_casadi[stage].set_param_sparse(capsule->forw_vde_casadi+stage, n_update, idx, p); - capsule->expl_ode_fun[stage].set_param_sparse(capsule->expl_ode_fun+stage, n_update, idx, p); - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->hess_vde_casadi[stage].set_param_sparse(capsule->hess_vde_casadi+stage, n_update, idx, p); - {%- endif %} - {% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - capsule->gnsf_phi_fun[stage].set_param_sparse(capsule->gnsf_phi_fun+stage, n_update, idx, p); - capsule->gnsf_phi_fun_jac_y[stage].set_param_sparse(capsule->gnsf_phi_fun_jac_y+stage, n_update, idx, p); - capsule->gnsf_phi_jac_y_uhat[stage].set_param_sparse(capsule->gnsf_phi_jac_y_uhat+stage, n_update, idx, p); - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[stage].set_param_sparse(capsule->gnsf_f_lo_jac_x1_x1dot_u_z+stage, n_update, idx, p); - {%- endif %} - {%- endif %} - {% elif solver_options.integrator_type == "DISCRETE" %} - capsule->discr_dyn_phi_fun[stage].set_param_sparse(capsule->discr_dyn_phi_fun+stage, n_update, idx, p); - capsule->discr_dyn_phi_fun_jac_ut_xt[stage].set_param_sparse(capsule->discr_dyn_phi_fun_jac_ut_xt+stage, n_update, idx, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[stage].set_param_sparse(capsule->discr_dyn_phi_fun_jac_ut_xt_hess+stage, n_update, idx, p); - {% endif %} - {%- endif %}{# integrator_type #} - - // constraints - {% if constraints.constr_type == "BGP" %} - capsule->phi_constraint[stage].set_param_sparse(capsule->phi_constraint+stage, n_update, idx, p); - {% elif constraints.constr_type == "BGH" and dims.nh > 0 %} - capsule->nl_constr_h_fun_jac[stage].set_param_sparse(capsule->nl_constr_h_fun_jac+stage, n_update, idx, p); - capsule->nl_constr_h_fun[stage].set_param_sparse(capsule->nl_constr_h_fun+stage, n_update, idx, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_fun_jac_hess[stage].set_param_sparse(capsule->nl_constr_h_fun_jac_hess+stage, n_update, idx, p); - {%- endif %} - {%- endif %} - - // cost - if (stage == 0) - { - {%- if cost.cost_type_0 == "NONLINEAR_LS" %} - capsule->cost_y_0_fun.set_param_sparse(&capsule->cost_y_0_fun, n_update, idx, p); - capsule->cost_y_0_fun_jac_ut_xt.set_param_sparse(&capsule->cost_y_0_fun_jac_ut_xt, n_update, idx, p); - capsule->cost_y_0_hess.set_param_sparse(&capsule->cost_y_0_hess, n_update, idx, p); - {%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_0_fun.set_param_sparse(&capsule->conl_cost_0_fun, n_update, idx, p); - capsule->conl_cost_0_fun_jac_hess.set_param_sparse(&capsule->conl_cost_0_fun_jac_hess, n_update, idx, p); - {%- elif cost.cost_type_0 == "EXTERNAL" %} - capsule->ext_cost_0_fun.set_param_sparse(&capsule->ext_cost_0_fun, n_update, idx, p); - capsule->ext_cost_0_fun_jac.set_param_sparse(&capsule->ext_cost_0_fun_jac, n_update, idx, p); - capsule->ext_cost_0_fun_jac_hess.set_param_sparse(&capsule->ext_cost_0_fun_jac_hess, n_update, idx, p); - {% endif %} - } - else // 0 < stage < N - { - {%- if cost.cost_type == "NONLINEAR_LS" %} - capsule->cost_y_fun[stage-1].set_param_sparse(capsule->cost_y_fun+stage-1, n_update, idx, p); - capsule->cost_y_fun_jac_ut_xt[stage-1].set_param_sparse(capsule->cost_y_fun_jac_ut_xt+stage-1, n_update, idx, p); - capsule->cost_y_hess[stage-1].set_param_sparse(capsule->cost_y_hess+stage-1, n_update, idx, p); - {%- elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_fun[stage-1].set_param_sparse(capsule->conl_cost_fun+stage-1, n_update, idx, p); - capsule->conl_cost_fun_jac_hess[stage-1].set_param_sparse(capsule->conl_cost_fun_jac_hess+stage-1, n_update, idx, p); - {%- elif cost.cost_type == "EXTERNAL" %} - capsule->ext_cost_fun[stage-1].set_param_sparse(capsule->ext_cost_fun+stage-1, n_update, idx, p); - capsule->ext_cost_fun_jac[stage-1].set_param_sparse(capsule->ext_cost_fun_jac+stage-1, n_update, idx, p); - capsule->ext_cost_fun_jac_hess[stage-1].set_param_sparse(capsule->ext_cost_fun_jac_hess+stage-1, n_update, idx, p); - {%- endif %} - } - } - - else // stage == N - { - // terminal shooting node has no dynamics - // cost - {%- if cost.cost_type_e == "NONLINEAR_LS" %} - capsule->cost_y_e_fun.set_param_sparse(&capsule->cost_y_e_fun, n_update, idx, p); - capsule->cost_y_e_fun_jac_ut_xt.set_param_sparse(&capsule->cost_y_e_fun_jac_ut_xt, n_update, idx, p); - capsule->cost_y_e_hess.set_param_sparse(&capsule->cost_y_e_hess, n_update, idx, p); - {%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_e_fun.set_param_sparse(&capsule->conl_cost_e_fun, n_update, idx, p); - capsule->conl_cost_e_fun_jac_hess.set_param_sparse(&capsule->conl_cost_e_fun_jac_hess, n_update, idx, p); - {%- elif cost.cost_type_e == "EXTERNAL" %} - capsule->ext_cost_e_fun.set_param_sparse(&capsule->ext_cost_e_fun, n_update, idx, p); - capsule->ext_cost_e_fun_jac.set_param_sparse(&capsule->ext_cost_e_fun_jac, n_update, idx, p); - capsule->ext_cost_e_fun_jac_hess.set_param_sparse(&capsule->ext_cost_e_fun_jac_hess, n_update, idx, p); - {% endif %} - // constraints - {% if constraints.constr_type_e == "BGP" %} - capsule->phi_e_constraint.set_param_sparse(&capsule->phi_e_constraint, n_update, idx, p); - {% elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - capsule->nl_constr_h_e_fun_jac.set_param_sparse(&capsule->nl_constr_h_e_fun_jac, n_update, idx, p); - capsule->nl_constr_h_e_fun.set_param_sparse(&capsule->nl_constr_h_e_fun, n_update, idx, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_e_fun_jac_hess.set_param_sparse(&capsule->nl_constr_h_e_fun_jac_hess, n_update, idx, p); - {%- endif %} - {% endif %} - } -{% endif %}{# if dims.np #} - - return solver_status; -} - -int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule* capsule) -{ - // solve NLP - int solver_status = ocp_nlp_solve(capsule->nlp_solver, capsule->nlp_in, capsule->nlp_out); - - return solver_status; -} - - -int {{ model.name }}_acados_free({{ model.name }}_solver_capsule* capsule) -{ - // before destroying, keep some info - const int N = capsule->nlp_solver_plan->N; - {%- if custom_update_filename != "" %} - custom_update_terminate_function(capsule); - {%- endif %} - // free memory - ocp_nlp_solver_opts_destroy(capsule->nlp_opts); - ocp_nlp_in_destroy(capsule->nlp_in); - ocp_nlp_out_destroy(capsule->nlp_out); - ocp_nlp_out_destroy(capsule->sens_out); - ocp_nlp_solver_destroy(capsule->nlp_solver); - ocp_nlp_dims_destroy(capsule->nlp_dims); - ocp_nlp_config_destroy(capsule->nlp_config); - ocp_nlp_plan_destroy(capsule->nlp_solver_plan); - - /* free external function */ - // dynamics -{%- if solver_options.integrator_type == "IRK" %} - for (int i = 0; i < N; i++) - { - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_fun[i]); - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_fun_jac_x_xdot_z[i]); - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_jac_x_xdot_u_z[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_hess[i]); - {%- endif %} - } - free(capsule->impl_dae_fun); - free(capsule->impl_dae_fun_jac_x_xdot_z); - free(capsule->impl_dae_jac_x_xdot_u_z); - {%- if solver_options.hessian_approx == "EXACT" %} - free(capsule->impl_dae_hess); - {%- endif %} - -{%- elif solver_options.integrator_type == "LIFTED_IRK" %} - for (int i = 0; i < N; i++) - { - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_fun[i]); - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_fun_jac_x_xdot_u[i]); - } - free(capsule->impl_dae_fun); - free(capsule->impl_dae_fun_jac_x_xdot_u); - -{%- elif solver_options.integrator_type == "ERK" %} - for (int i = 0; i < N; i++) - { - external_function_param_casadi_free(&capsule->forw_vde_casadi[i]); - external_function_param_casadi_free(&capsule->expl_ode_fun[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi_free(&capsule->hess_vde_casadi[i]); - {%- endif %} - } - free(capsule->forw_vde_casadi); - free(capsule->expl_ode_fun); - {%- if solver_options.hessian_approx == "EXACT" %} - free(capsule->hess_vde_casadi); - {%- endif %} - -{%- elif solver_options.integrator_type == "GNSF" %} - for (int i = 0; i < N; i++) - { - {% if model.gnsf.purely_linear != 1 %} - external_function_param_casadi_free(&capsule->gnsf_phi_fun[i]); - external_function_param_casadi_free(&capsule->gnsf_phi_fun_jac_y[i]); - external_function_param_casadi_free(&capsule->gnsf_phi_jac_y_uhat[i]); - {% if model.gnsf.nontrivial_f_LO == 1 %} - external_function_param_casadi_free(&capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i]); - {%- endif %} - {%- endif %} - external_function_param_casadi_free(&capsule->gnsf_get_matrices_fun[i]); - } - {% if model.gnsf.purely_linear != 1 %} - free(capsule->gnsf_phi_fun); - free(capsule->gnsf_phi_fun_jac_y); - free(capsule->gnsf_phi_jac_y_uhat); - {% if model.gnsf.nontrivial_f_LO == 1 %} - free(capsule->gnsf_f_lo_jac_x1_x1dot_u_z); - {%- endif %} - {%- endif %} - free(capsule->gnsf_get_matrices_fun); -{%- elif solver_options.integrator_type == "DISCRETE" %} - for (int i = 0; i < N; i++) - { - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun[i]); - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun_jac_ut_xt[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i]); - {%- endif %} - } - free(capsule->discr_dyn_phi_fun); - free(capsule->discr_dyn_phi_fun_jac_ut_xt); - {%- if solver_options.hessian_approx == "EXACT" %} - free(capsule->discr_dyn_phi_fun_jac_ut_xt_hess); - {%- endif %} - -{%- endif %} - - // cost -{%- if cost.cost_type_0 == "NONLINEAR_LS" %} - external_function_param_casadi_free(&capsule->cost_y_0_fun); - external_function_param_casadi_free(&capsule->cost_y_0_fun_jac_ut_xt); - external_function_param_casadi_free(&capsule->cost_y_0_hess); -{%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi_free(&capsule->conl_cost_0_fun); - external_function_param_casadi_free(&capsule->conl_cost_0_fun_jac_hess); -{%- elif cost.cost_type_0 == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun); - external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun_jac); - external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun_jac_hess); -{%- endif %} -{%- if cost.cost_type == "NONLINEAR_LS" %} - for (int i = 0; i < N - 1; i++) - { - external_function_param_casadi_free(&capsule->cost_y_fun[i]); - external_function_param_casadi_free(&capsule->cost_y_fun_jac_ut_xt[i]); - external_function_param_casadi_free(&capsule->cost_y_hess[i]); - } - free(capsule->cost_y_fun); - free(capsule->cost_y_fun_jac_ut_xt); - free(capsule->cost_y_hess); -{%- elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - for (int i = 0; i < N - 1; i++) - { - external_function_param_casadi_free(&capsule->conl_cost_fun[i]); - external_function_param_casadi_free(&capsule->conl_cost_fun_jac_hess[i]); - } - free(capsule->conl_cost_fun); - free(capsule->conl_cost_fun_jac_hess); -{%- elif cost.cost_type == "EXTERNAL" %} - for (int i = 0; i < N - 1; i++) - { - external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun[i]); - external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun_jac[i]); - external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun_jac_hess[i]); - } - free(capsule->ext_cost_fun); - free(capsule->ext_cost_fun_jac); - free(capsule->ext_cost_fun_jac_hess); -{%- endif %} -{%- if cost.cost_type_e == "NONLINEAR_LS" %} - external_function_param_casadi_free(&capsule->cost_y_e_fun); - external_function_param_casadi_free(&capsule->cost_y_e_fun_jac_ut_xt); - external_function_param_casadi_free(&capsule->cost_y_e_hess); -{%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi_free(&capsule->conl_cost_e_fun); - external_function_param_casadi_free(&capsule->conl_cost_e_fun_jac_hess); -{%- elif cost.cost_type_e == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun); - external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun_jac); - external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun_jac_hess); -{%- endif %} - - // constraints -{%- if constraints.constr_type == "BGH" and dims.nh > 0 %} - for (int i = 0; i < N; i++) - { - external_function_param_casadi_free(&capsule->nl_constr_h_fun_jac[i]); - external_function_param_casadi_free(&capsule->nl_constr_h_fun[i]); - } - {%- if solver_options.hessian_approx == "EXACT" %} - for (int i = 0; i < N; i++) - { - external_function_param_casadi_free(&capsule->nl_constr_h_fun_jac_hess[i]); - } - {%- endif %} - free(capsule->nl_constr_h_fun_jac); - free(capsule->nl_constr_h_fun); - {%- if solver_options.hessian_approx == "EXACT" %} - free(capsule->nl_constr_h_fun_jac_hess); - {%- endif %} - -{%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %} - for (int i = 0; i < N; i++) - { - external_function_param_casadi_free(&capsule->phi_constraint[i]); - } - free(capsule->phi_constraint); -{%- endif %} - -{%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - external_function_param_casadi_free(&capsule->nl_constr_h_e_fun_jac); - external_function_param_casadi_free(&capsule->nl_constr_h_e_fun); -{%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi_free(&capsule->nl_constr_h_e_fun_jac_hess); -{%- endif %} -{%- elif constraints.constr_type_e == "BGP" and dims.nphi_e > 0 %} - external_function_param_casadi_free(&capsule->phi_e_constraint); -{%- endif %} - - return 0; -} - - -void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule* capsule) -{ - int sqp_iter, stat_m, stat_n, tmp_int; - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "sqp_iter", &sqp_iter); - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "stat_n", &stat_n); - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "stat_m", &stat_m); - - {% set stat_n_max = 12 %} - double stat[{{ solver_options.nlp_solver_max_iter * stat_n_max }}]; - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "statistics", stat); - - int nrow = sqp_iter+1 < stat_m ? sqp_iter+1 : stat_m; - - printf("iter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha"); - if (stat_n > 8) - printf("\t\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp"); - printf("\n"); - -{%- if solver_options.nlp_solver_type == "SQP" %} - - for (int i = 0; i < nrow; i++) - { - for (int j = 0; j < stat_n + 1; j++) - { - if (j == 0 || j == 5 || j == 6) - { - tmp_int = (int) stat[i + j * nrow]; - printf("%d\t", tmp_int); - } - else - { - printf("%e\t", stat[i + j * nrow]); - } - } - printf("\n"); - } -{% else %} - printf("iter\tqp_stat\tqp_iter\n"); - for (int i = 0; i < nrow; i++) - { - for (int j = 0; j < stat_n + 1; j++) - { - tmp_int = (int) stat[i + j * nrow]; - printf("%d\t", tmp_int); - } - printf("\n"); - } -{%- endif %} -} - -int {{ model.name }}_acados_custom_update({{ model.name }}_solver_capsule* capsule, double* data, int data_len) -{ -{%- if custom_update_filename == "" %} - (void)capsule; - (void)data; - (void)data_len; - printf("\ndummy function that can be called in between solver calls to update parameters or numerical data efficiently in C.\n"); - printf("nothing set yet..\n"); - return 1; -{% else %} - custom_update_function(capsule, data, data_len); -{%- endif %} -} - - - -ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_in; } -ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_out; } -ocp_nlp_out *{{ model.name }}_acados_get_sens_out({{ model.name }}_solver_capsule* capsule) { return capsule->sens_out; } -ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_solver; } -ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_config; } -void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_opts; } -ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_dims; } -ocp_nlp_plan_t *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_solver_plan; } diff --git a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.h b/third_party/acados/acados_template/c_templates_tera/acados_solver.in.h deleted file mode 100644 index 5cf38aa8c8ff3b..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.h +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -#ifndef ACADOS_SOLVER_{{ model.name }}_H_ -#define ACADOS_SOLVER_{{ model.name }}_H_ - -#include "acados/utils/types.h" - -#include "acados_c/ocp_nlp_interface.h" -#include "acados_c/external_function_interface.h" - -#define {{ model.name | upper }}_NX {{ dims.nx }} -#define {{ model.name | upper }}_NZ {{ dims.nz }} -#define {{ model.name | upper }}_NU {{ dims.nu }} -#define {{ model.name | upper }}_NP {{ dims.np }} -#define {{ model.name | upper }}_NBX {{ dims.nbx }} -#define {{ model.name | upper }}_NBX0 {{ dims.nbx_0 }} -#define {{ model.name | upper }}_NBU {{ dims.nbu }} -#define {{ model.name | upper }}_NSBX {{ dims.nsbx }} -#define {{ model.name | upper }}_NSBU {{ dims.nsbu }} -#define {{ model.name | upper }}_NSH {{ dims.nsh }} -#define {{ model.name | upper }}_NSG {{ dims.nsg }} -#define {{ model.name | upper }}_NSPHI {{ dims.nsphi }} -#define {{ model.name | upper }}_NSHN {{ dims.nsh_e }} -#define {{ model.name | upper }}_NSGN {{ dims.nsg_e }} -#define {{ model.name | upper }}_NSPHIN {{ dims.nsphi_e }} -#define {{ model.name | upper }}_NSBXN {{ dims.nsbx_e }} -#define {{ model.name | upper }}_NS {{ dims.ns }} -#define {{ model.name | upper }}_NSN {{ dims.ns_e }} -#define {{ model.name | upper }}_NG {{ dims.ng }} -#define {{ model.name | upper }}_NBXN {{ dims.nbx_e }} -#define {{ model.name | upper }}_NGN {{ dims.ng_e }} -#define {{ model.name | upper }}_NY0 {{ dims.ny_0 }} -#define {{ model.name | upper }}_NY {{ dims.ny }} -#define {{ model.name | upper }}_NYN {{ dims.ny_e }} -#define {{ model.name | upper }}_N {{ dims.N }} -#define {{ model.name | upper }}_NH {{ dims.nh }} -#define {{ model.name | upper }}_NPHI {{ dims.nphi }} -#define {{ model.name | upper }}_NHN {{ dims.nh_e }} -#define {{ model.name | upper }}_NPHIN {{ dims.nphi_e }} -#define {{ model.name | upper }}_NR {{ dims.nr }} - -#ifdef __cplusplus -extern "C" { -#endif - -{%- if not solver_options.custom_update_filename %} - {%- set custom_update_filename = "" %} -{% else %} - {%- set custom_update_filename = solver_options.custom_update_filename %} -{%- endif %} - -// ** capsule for solver data ** -typedef struct {{ model.name }}_solver_capsule -{ - // acados objects - ocp_nlp_in *nlp_in; - ocp_nlp_out *nlp_out; - ocp_nlp_out *sens_out; - ocp_nlp_solver *nlp_solver; - void *nlp_opts; - ocp_nlp_plan_t *nlp_solver_plan; - ocp_nlp_config *nlp_config; - ocp_nlp_dims *nlp_dims; - - // number of expected runtime parameters - unsigned int nlp_np; - - /* external functions */ - // dynamics -{% if solver_options.integrator_type == "ERK" %} - external_function_param_casadi *forw_vde_casadi; - external_function_param_casadi *expl_ode_fun; -{% if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi *hess_vde_casadi; -{%- endif %} -{% elif solver_options.integrator_type == "IRK" %} - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_fun; - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_fun_jac_x_xdot_z; - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_jac_x_xdot_u_z; -{% if solver_options.hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_hess; -{%- endif %} -{% elif solver_options.integrator_type == "LIFTED_IRK" %} - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_fun; - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_fun_jac_x_xdot_u; -{% elif solver_options.integrator_type == "GNSF" %} - external_function_param_casadi *gnsf_phi_fun; - external_function_param_casadi *gnsf_phi_fun_jac_y; - external_function_param_casadi *gnsf_phi_jac_y_uhat; - external_function_param_casadi *gnsf_f_lo_jac_x1_x1dot_u_z; - external_function_param_casadi *gnsf_get_matrices_fun; -{% elif solver_options.integrator_type == "DISCRETE" %} - external_function_param_{{ model.dyn_ext_fun_type }} *discr_dyn_phi_fun; - external_function_param_{{ model.dyn_ext_fun_type }} *discr_dyn_phi_fun_jac_ut_xt; -{%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }} *discr_dyn_phi_fun_jac_ut_xt_hess; -{%- endif %} -{%- endif %} - - - // cost -{% if cost.cost_type == "NONLINEAR_LS" %} - external_function_param_casadi *cost_y_fun; - external_function_param_casadi *cost_y_fun_jac_ut_xt; - external_function_param_casadi *cost_y_hess; -{% elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi *conl_cost_fun; - external_function_param_casadi *conl_cost_fun_jac_hess; -{%- elif cost.cost_type == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type }} *ext_cost_fun; - external_function_param_{{ cost.cost_ext_fun_type }} *ext_cost_fun_jac; - external_function_param_{{ cost.cost_ext_fun_type }} *ext_cost_fun_jac_hess; -{% endif %} - -{% if cost.cost_type_0 == "NONLINEAR_LS" %} - external_function_param_casadi cost_y_0_fun; - external_function_param_casadi cost_y_0_fun_jac_ut_xt; - external_function_param_casadi cost_y_0_hess; -{% elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi conl_cost_0_fun; - external_function_param_casadi conl_cost_0_fun_jac_hess; -{% elif cost.cost_type_0 == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type_0 }} ext_cost_0_fun; - external_function_param_{{ cost.cost_ext_fun_type_0 }} ext_cost_0_fun_jac; - external_function_param_{{ cost.cost_ext_fun_type_0 }} ext_cost_0_fun_jac_hess; -{%- endif %} - -{% if cost.cost_type_e == "NONLINEAR_LS" %} - external_function_param_casadi cost_y_e_fun; - external_function_param_casadi cost_y_e_fun_jac_ut_xt; - external_function_param_casadi cost_y_e_hess; -{% elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi conl_cost_e_fun; - external_function_param_casadi conl_cost_e_fun_jac_hess; -{% elif cost.cost_type_e == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type_e }} ext_cost_e_fun; - external_function_param_{{ cost.cost_ext_fun_type_e }} ext_cost_e_fun_jac; - external_function_param_{{ cost.cost_ext_fun_type_e }} ext_cost_e_fun_jac_hess; -{%- endif %} - - // constraints -{%- if constraints.constr_type == "BGP" %} - external_function_param_casadi *phi_constraint; -{% elif constraints.constr_type == "BGH" and dims.nh > 0 %} - external_function_param_casadi *nl_constr_h_fun_jac; - external_function_param_casadi *nl_constr_h_fun; -{%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi *nl_constr_h_fun_jac_hess; -{%- endif %} -{%- endif %} - - -{% if constraints.constr_type_e == "BGP" %} - external_function_param_casadi phi_e_constraint; -{% elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - external_function_param_casadi nl_constr_h_e_fun_jac; - external_function_param_casadi nl_constr_h_e_fun; -{%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi nl_constr_h_e_fun_jac_hess; -{%- endif %} -{%- endif %} - -{%- if custom_update_filename != "" %} - void * custom_update_memory; -{%- endif %} - -} {{ model.name }}_solver_capsule; - -ACADOS_SYMBOL_EXPORT {{ model.name }}_solver_capsule * {{ model.name }}_acados_create_capsule(void); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_free_capsule({{ model.name }}_solver_capsule *capsule); - -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_create({{ model.name }}_solver_capsule * capsule); - -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_reset({{ model.name }}_solver_capsule* capsule, int reset_qp_solver_mem); - -/** - * Generic version of {{ model.name }}_acados_create which allows to use a different number of shooting intervals than - * the number used for code generation. If new_time_steps=NULL and n_time_steps matches the number used for code - * generation, the time-steps from code generation is used. - */ -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule * capsule, int n_time_steps, double* new_time_steps); -/** - * Update the time step vector. Number N must be identical to the currently set number of shooting nodes in the - * nlp_solver_plan. Returns 0 if no error occurred and a otherwise a value other than 0. - */ -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule * capsule, int N, double* new_time_steps); -/** - * This function is used for updating an already initialized solver with a different number of qp_cond_N. - */ -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_qp_solver_cond_N({{ model.name }}_solver_capsule * capsule, int qp_solver_cond_N); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * capsule, int stage, double *value, int np); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_params_sparse({{ model.name }}_solver_capsule * capsule, int stage, int *idx, double *p, int n_update); - -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_custom_update({{ model.name }}_solver_capsule* capsule, double* data, int data_len); - - -ACADOS_SYMBOL_EXPORT ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_out *{{ model.name }}_acados_get_sens_out({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_plan_t *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule * capsule); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SOLVER_{{ model.name }}_H_ diff --git a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.pxd b/third_party/acados/acados_template/c_templates_tera/acados_solver.in.pxd deleted file mode 100644 index 233e3f79da5198..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.pxd +++ /dev/null @@ -1,62 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -cimport acados_solver_common - -cdef extern from "acados_solver_{{ model.name }}.h": - ctypedef struct nlp_solver_capsule "{{ model.name }}_solver_capsule": - pass - - nlp_solver_capsule * acados_create_capsule "{{ model.name }}_acados_create_capsule"() - int acados_free_capsule "{{ model.name }}_acados_free_capsule"(nlp_solver_capsule *capsule) - - int acados_create "{{ model.name }}_acados_create"(nlp_solver_capsule * capsule) - - int acados_create_with_discretization "{{ model.name }}_acados_create_with_discretization"(nlp_solver_capsule * capsule, int n_time_steps, double* new_time_steps) - int acados_update_time_steps "{{ model.name }}_acados_update_time_steps"(nlp_solver_capsule * capsule, int N, double* new_time_steps) - int acados_update_qp_solver_cond_N "{{ model.name }}_acados_update_qp_solver_cond_N"(nlp_solver_capsule * capsule, int qp_solver_cond_N) - - int acados_update_params "{{ model.name }}_acados_update_params"(nlp_solver_capsule * capsule, int stage, double *value, int np_) - int acados_update_params_sparse "{{ model.name }}_acados_update_params_sparse"(nlp_solver_capsule * capsule, int stage, int *idx, double *p, int n_update) - int acados_solve "{{ model.name }}_acados_solve"(nlp_solver_capsule * capsule) - int acados_reset "{{ model.name }}_acados_reset"(nlp_solver_capsule * capsule, int reset_qp_solver_mem) - int acados_free "{{ model.name }}_acados_free"(nlp_solver_capsule * capsule) - void acados_print_stats "{{ model.name }}_acados_print_stats"(nlp_solver_capsule * capsule) - - int acados_custom_update "{{ model.name }}_acados_custom_update"(nlp_solver_capsule* capsule, double * data, int data_len) - - acados_solver_common.ocp_nlp_in *acados_get_nlp_in "{{ model.name }}_acados_get_nlp_in"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_out *acados_get_nlp_out "{{ model.name }}_acados_get_nlp_out"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_out *acados_get_sens_out "{{ model.name }}_acados_get_sens_out"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_solver *acados_get_nlp_solver "{{ model.name }}_acados_get_nlp_solver"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_config *acados_get_nlp_config "{{ model.name }}_acados_get_nlp_config"(nlp_solver_capsule * capsule) - void *acados_get_nlp_opts "{{ model.name }}_acados_get_nlp_opts"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_dims *acados_get_nlp_dims "{{ model.name }}_acados_get_nlp_dims"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_plan *acados_get_nlp_plan "{{ model.name }}_acados_get_nlp_plan"(nlp_solver_capsule * capsule) diff --git a/third_party/acados/acados_template/c_templates_tera/constraints.in.h b/third_party/acados/acados_template/c_templates_tera/constraints.in.h deleted file mode 100644 index d71ce5cc221f1b..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/constraints.in.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -#ifndef {{ model.name }}_CONSTRAINTS -#define {{ model.name }}_CONSTRAINTS - -#ifdef __cplusplus -extern "C" { -#endif - -{% if dims.nphi > 0 %} -int {{ model.name }}_phi_constraint(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_phi_constraint_work(int *, int *, int *, int *); -const int *{{ model.name }}_phi_constraint_sparsity_in(int); -const int *{{ model.name }}_phi_constraint_sparsity_out(int); -int {{ model.name }}_phi_constraint_n_in(void); -int {{ model.name }}_phi_constraint_n_out(void); -{% endif %} - -{% if dims.nphi_e > 0 %} -int {{ model.name }}_phi_e_constraint(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_phi_e_constraint_work(int *, int *, int *, int *); -const int *{{ model.name }}_phi_e_constraint_sparsity_in(int); -const int *{{ model.name }}_phi_e_constraint_sparsity_out(int); -int {{ model.name }}_phi_e_constraint_n_in(void); -int {{ model.name }}_phi_e_constraint_n_out(void); -{% endif %} - -{% if dims.nh > 0 %} -int {{ model.name }}_constr_h_fun_jac_uxt_zt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_in(int); -const int *{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_out(int); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_n_in(void); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_n_out(void); - -int {{ model.name }}_constr_h_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_fun_sparsity_in(int); -const int *{{ model.name }}_constr_h_fun_sparsity_out(int); -int {{ model.name }}_constr_h_fun_n_in(void); -int {{ model.name }}_constr_h_fun_n_out(void); - -{% if solver_options.hessian_approx == "EXACT" -%} -int {{ model.name }}_constr_h_fun_jac_uxt_zt_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_sparsity_in(int); -const int *{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_sparsity_out(int); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_hess_n_in(void); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_hess_n_out(void); -{% endif %} -{% endif %} - -{% if dims.nh_e > 0 %} -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_in(int); -const int *{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_out(int); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_in(void); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_out(void); - -int {{ model.name }}_constr_h_e_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_e_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_e_fun_sparsity_in(int); -const int *{{ model.name }}_constr_h_e_fun_sparsity_out(int); -int {{ model.name }}_constr_h_e_fun_n_in(void); -int {{ model.name }}_constr_h_e_fun_n_out(void); - -{% if solver_options.hessian_approx == "EXACT" -%} -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_sparsity_in(int); -const int *{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_sparsity_out(int); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_n_in(void); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_n_out(void); -{% endif %} -{% endif %} - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // {{ model.name }}_CONSTRAINTS diff --git a/third_party/acados/acados_template/c_templates_tera/cost.in.h b/third_party/acados/acados_template/c_templates_tera/cost.in.h deleted file mode 100644 index 45eb09c12e2b3b..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/cost.in.h +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef {{ model.name }}_COST -#define {{ model.name }}_COST - -#ifdef __cplusplus -extern "C" { -#endif - - -// Cost at initial shooting node -{% if cost.cost_type_0 == "NONLINEAR_LS" %} -int {{ model.name }}_cost_y_0_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_0_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_0_fun_sparsity_in(int); -const int *{{ model.name }}_cost_y_0_fun_sparsity_out(int); -int {{ model.name }}_cost_y_0_fun_n_in(void); -int {{ model.name }}_cost_y_0_fun_n_out(void); - -int {{ model.name }}_cost_y_0_fun_jac_ut_xt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_0_fun_jac_ut_xt_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_0_fun_jac_ut_xt_sparsity_in(int); -const int *{{ model.name }}_cost_y_0_fun_jac_ut_xt_sparsity_out(int); -int {{ model.name }}_cost_y_0_fun_jac_ut_xt_n_in(void); -int {{ model.name }}_cost_y_0_fun_jac_ut_xt_n_out(void); - -int {{ model.name }}_cost_y_0_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_0_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_0_hess_sparsity_in(int); -const int *{{ model.name }}_cost_y_0_hess_sparsity_out(int); -int {{ model.name }}_cost_y_0_hess_n_in(void); -int {{ model.name }}_cost_y_0_hess_n_out(void); -{% elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - -int {{ model.name }}_conl_cost_0_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_0_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_0_fun_sparsity_in(int); -const int *{{ model.name }}_conl_cost_0_fun_sparsity_out(int); -int {{ model.name }}_conl_cost_0_fun_n_in(void); -int {{ model.name }}_conl_cost_0_fun_n_out(void); - -int {{ model.name }}_conl_cost_0_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_0_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_0_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_conl_cost_0_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_conl_cost_0_fun_jac_hess_n_in(void); -int {{ model.name }}_conl_cost_0_fun_jac_hess_n_out(void); - -{% elif cost.cost_type_0 == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_0 == "casadi" %} -int {{ model.name }}_cost_ext_cost_0_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_0_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_0_fun_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_0_fun_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_0_fun_n_in(void); -int {{ model.name }}_cost_ext_cost_0_fun_n_out(void); - -int {{ model.name }}_cost_ext_cost_0_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_0_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_0_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_0_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_0_fun_jac_hess_n_in(void); -int {{ model.name }}_cost_ext_cost_0_fun_jac_hess_n_out(void); - -int {{ model.name }}_cost_ext_cost_0_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_0_fun_jac_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_0_fun_jac_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_0_fun_jac_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_0_fun_jac_n_in(void); -int {{ model.name }}_cost_ext_cost_0_fun_jac_n_out(void); - {%- else %} -int {{ cost.cost_function_ext_cost_0 }}(void **, void **, void *); - {%- endif %} -{% endif %} - - -// Cost at path shooting node -{% if cost.cost_type == "NONLINEAR_LS" %} -int {{ model.name }}_cost_y_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_fun_sparsity_in(int); -const int *{{ model.name }}_cost_y_fun_sparsity_out(int); -int {{ model.name }}_cost_y_fun_n_in(void); -int {{ model.name }}_cost_y_fun_n_out(void); - -int {{ model.name }}_cost_y_fun_jac_ut_xt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_fun_jac_ut_xt_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_in(int); -const int *{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_out(int); -int {{ model.name }}_cost_y_fun_jac_ut_xt_n_in(void); -int {{ model.name }}_cost_y_fun_jac_ut_xt_n_out(void); - -int {{ model.name }}_cost_y_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_hess_sparsity_in(int); -const int *{{ model.name }}_cost_y_hess_sparsity_out(int); -int {{ model.name }}_cost_y_hess_n_in(void); -int {{ model.name }}_cost_y_hess_n_out(void); - -{% elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} -int {{ model.name }}_conl_cost_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_fun_sparsity_in(int); -const int *{{ model.name }}_conl_cost_fun_sparsity_out(int); -int {{ model.name }}_conl_cost_fun_n_in(void); -int {{ model.name }}_conl_cost_fun_n_out(void); - -int {{ model.name }}_conl_cost_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_conl_cost_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_conl_cost_fun_jac_hess_n_in(void); -int {{ model.name }}_conl_cost_fun_jac_hess_n_out(void); -{% elif cost.cost_type == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type == "casadi" %} -int {{ model.name }}_cost_ext_cost_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_fun_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_fun_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_fun_n_in(void); -int {{ model.name }}_cost_ext_cost_fun_n_out(void); - -int {{ model.name }}_cost_ext_cost_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_fun_jac_hess_n_in(void); -int {{ model.name }}_cost_ext_cost_fun_jac_hess_n_out(void); - -int {{ model.name }}_cost_ext_cost_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_fun_jac_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_fun_jac_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_fun_jac_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_fun_jac_n_in(void); -int {{ model.name }}_cost_ext_cost_fun_jac_n_out(void); - {%- else %} -int {{ cost.cost_function_ext_cost }}(void **, void **, void *); - {%- endif %} -{% endif %} - -// Cost at terminal shooting node -{% if cost.cost_type_e == "NONLINEAR_LS" %} -int {{ model.name }}_cost_y_e_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_e_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_e_fun_sparsity_in(int); -const int *{{ model.name }}_cost_y_e_fun_sparsity_out(int); -int {{ model.name }}_cost_y_e_fun_n_in(void); -int {{ model.name }}_cost_y_e_fun_n_out(void); - -int {{ model.name }}_cost_y_e_fun_jac_ut_xt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_e_fun_jac_ut_xt_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_in(int); -const int *{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_out(int); -int {{ model.name }}_cost_y_e_fun_jac_ut_xt_n_in(void); -int {{ model.name }}_cost_y_e_fun_jac_ut_xt_n_out(void); - -int {{ model.name }}_cost_y_e_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_e_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_e_hess_sparsity_in(int); -const int *{{ model.name }}_cost_y_e_hess_sparsity_out(int); -int {{ model.name }}_cost_y_e_hess_n_in(void); -int {{ model.name }}_cost_y_e_hess_n_out(void); -{% elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} -int {{ model.name }}_conl_cost_e_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_e_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_e_fun_sparsity_in(int); -const int *{{ model.name }}_conl_cost_e_fun_sparsity_out(int); -int {{ model.name }}_conl_cost_e_fun_n_in(void); -int {{ model.name }}_conl_cost_e_fun_n_out(void); - -int {{ model.name }}_conl_cost_e_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_e_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_e_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_conl_cost_e_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_conl_cost_e_fun_jac_hess_n_in(void); -int {{ model.name }}_conl_cost_e_fun_jac_hess_n_out(void); -{% elif cost.cost_type_e == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_e == "casadi" %} -int {{ model.name }}_cost_ext_cost_e_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_e_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_e_fun_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_e_fun_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_e_fun_n_in(void); -int {{ model.name }}_cost_ext_cost_e_fun_n_out(void); - -int {{ model.name }}_cost_ext_cost_e_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_e_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_in(void); -int {{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_out(void); - -int {{ model.name }}_cost_ext_cost_e_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_e_fun_jac_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_e_fun_jac_n_in(void); -int {{ model.name }}_cost_ext_cost_e_fun_jac_n_out(void); - {%- else %} -int {{ cost.cost_function_ext_cost_e }}(void **, void **, void *); - {%- endif %} -{% endif %} - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // {{ model.name }}_COST diff --git a/third_party/acados/acados_template/c_templates_tera/main.in.c b/third_party/acados/acados_template/c_templates_tera/main.in.c deleted file mode 100644 index 92a8b33eac2d61..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/main.in.c +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -{%- if not solver_options.custom_update_filename %} - {%- set custom_update_filename = "" %} -{% else %} - {%- set custom_update_filename = solver_options.custom_update_filename %} -{%- endif %} - -// standard -#include -#include -// acados -#include "acados/utils/print.h" -#include "acados/utils/math.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_c/external_function_interface.h" -#include "acados_solver_{{ model.name }}.h" - -// blasfeo -#include "blasfeo/include/blasfeo_d_aux_ext_dep.h" - -#define NX {{ model.name | upper }}_NX -#define NZ {{ model.name | upper }}_NZ -#define NU {{ model.name | upper }}_NU -#define NP {{ model.name | upper }}_NP -#define NBX {{ model.name | upper }}_NBX -#define NBX0 {{ model.name | upper }}_NBX0 -#define NBU {{ model.name | upper }}_NBU -#define NSBX {{ model.name | upper }}_NSBX -#define NSBU {{ model.name | upper }}_NSBU -#define NSH {{ model.name | upper }}_NSH -#define NSG {{ model.name | upper }}_NSG -#define NSPHI {{ model.name | upper }}_NSPHI -#define NSHN {{ model.name | upper }}_NSHN -#define NSGN {{ model.name | upper }}_NSGN -#define NSPHIN {{ model.name | upper }}_NSPHIN -#define NSBXN {{ model.name | upper }}_NSBXN -#define NS {{ model.name | upper }}_NS -#define NSN {{ model.name | upper }}_NSN -#define NG {{ model.name | upper }}_NG -#define NBXN {{ model.name | upper }}_NBXN -#define NGN {{ model.name | upper }}_NGN -#define NY0 {{ model.name | upper }}_NY0 -#define NY {{ model.name | upper }}_NY -#define NYN {{ model.name | upper }}_NYN -#define NH {{ model.name | upper }}_NH -#define NPHI {{ model.name | upper }}_NPHI -#define NHN {{ model.name | upper }}_NHN -#define NPHIN {{ model.name | upper }}_NPHIN -#define NR {{ model.name | upper }}_NR - - -int main() -{ - - {{ model.name }}_solver_capsule *acados_ocp_capsule = {{ model.name }}_acados_create_capsule(); - // there is an opportunity to change the number of shooting intervals in C without new code generation - int N = {{ model.name | upper }}_N; - // allocate the array and fill it accordingly - double* new_time_steps = NULL; - int status = {{ model.name }}_acados_create_with_discretization(acados_ocp_capsule, N, new_time_steps); - - if (status) - { - printf("{{ model.name }}_acados_create() returned status %d. Exiting.\n", status); - exit(1); - } - - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(acados_ocp_capsule); - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(acados_ocp_capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(acados_ocp_capsule); - ocp_nlp_out *nlp_out = {{ model.name }}_acados_get_nlp_out(acados_ocp_capsule); - ocp_nlp_solver *nlp_solver = {{ model.name }}_acados_get_nlp_solver(acados_ocp_capsule); - void *nlp_opts = {{ model.name }}_acados_get_nlp_opts(acados_ocp_capsule); - - // initial condition - int idxbx0[NBX0]; - {%- for i in range(end=dims.nbx_0) %} - idxbx0[{{ i }}] = {{ constraints.idxbx_0[i] }}; - {%- endfor %} - - double lbx0[NBX0]; - double ubx0[NBX0]; - {%- for i in range(end=dims.nbx_0) %} - lbx0[{{ i }}] = {{ constraints.lbx_0[i] }}; - ubx0[{{ i }}] = {{ constraints.ubx_0[i] }}; - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbx", idxbx0); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbx", lbx0); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", ubx0); - - // initialization for state values - double x_init[NX]; - {%- for i in range(end=dims.nx) %} - x_init[{{ i }}] = 0.0; - {%- endfor %} - - // initial value for control input - double u0[NU]; - {%- for i in range(end=dims.nu) %} - u0[{{ i }}] = 0.0; - {%- endfor %} - - - {%- if dims.np > 0 %} - // set parameters - double p[NP]; - {%- for item in parameter_values %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endfor %} - - for (int ii = 0; ii <= N; ii++) - { - {{ model.name }}_acados_update_params(acados_ocp_capsule, ii, p, NP); - } - {% endif %}{# if np > 0 #} - - // prepare evaluation - int NTIMINGS = 1; - double min_time = 1e12; - double kkt_norm_inf; - double elapsed_time; - int sqp_iter; - - double xtraj[NX * (N+1)]; - double utraj[NU * N]; - - - // solve ocp in loop - int rti_phase = 0; - - for (int ii = 0; ii < NTIMINGS; ii++) - { - // initialize solution - for (int i = 0; i < N; i++) - { - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x_init); - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0); - } - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, N, "x", x_init); - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "rti_phase", &rti_phase); - status = {{ model.name }}_acados_solve(acados_ocp_capsule); - ocp_nlp_get(nlp_config, nlp_solver, "time_tot", &elapsed_time); - min_time = MIN(elapsed_time, min_time); - } - - /* print solution and statistics */ - for (int ii = 0; ii <= nlp_dims->N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, "x", &xtraj[ii*NX]); - for (int ii = 0; ii < nlp_dims->N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, "u", &utraj[ii*NU]); - - printf("\n--- xtraj ---\n"); - d_print_exp_tran_mat( NX, N+1, xtraj, NX); - printf("\n--- utraj ---\n"); - d_print_exp_tran_mat( NU, N, utraj, NU ); - // ocp_nlp_out_print(nlp_solver->dims, nlp_out); - - printf("\nsolved ocp %d times, solution printed above\n\n", NTIMINGS); - - if (status == ACADOS_SUCCESS) - { - printf("{{ model.name }}_acados_solve(): SUCCESS!\n"); - } - else - { - printf("{{ model.name }}_acados_solve() failed with status %d.\n", status); - } - - -{%- if custom_update_filename != "" %} - {{ model.name }}_acados_custom_update(acados_ocp_capsule, xtraj, NX*(N+1)); -{%- endif %} - - // get solution - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 0, "kkt_norm_inf", &kkt_norm_inf); - ocp_nlp_get(nlp_config, nlp_solver, "sqp_iter", &sqp_iter); - - {{ model.name }}_acados_print_stats(acados_ocp_capsule); - - printf("\nSolver info:\n"); - printf(" SQP iterations %2d\n minimum time for %d solve %f [ms]\n KKT %e\n", - sqp_iter, NTIMINGS, min_time*1000, kkt_norm_inf); - - // free solver - status = {{ model.name }}_acados_free(acados_ocp_capsule); - if (status) { - printf("{{ model.name }}_acados_free() returned status %d. \n", status); - } - // free solver capsule - status = {{ model.name }}_acados_free_capsule(acados_ocp_capsule); - if (status) { - printf("{{ model.name }}_acados_free_capsule() returned status %d. \n", status); - } - - return status; -} diff --git a/third_party/acados/acados_template/c_templates_tera/main_sim.in.c b/third_party/acados/acados_template/c_templates_tera/main_sim.in.c deleted file mode 100644 index 8960aa00354bde..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/main_sim.in.c +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -// standard -#include -#include -// acados -#include "acados/utils/print.h" -#include "acados/utils/math.h" -#include "acados_c/sim_interface.h" -#include "acados_sim_solver_{{ model.name }}.h" - -#define NX {{ model.name | upper }}_NX -#define NZ {{ model.name | upper }}_NZ -#define NU {{ model.name | upper }}_NU -#define NP {{ model.name | upper }}_NP - - -int main() -{ - int status = 0; - sim_solver_capsule *capsule = {{ model.name }}_acados_sim_solver_create_capsule(); - status = {{ model.name }}_acados_sim_create(capsule); - - if (status) - { - printf("acados_create() returned status %d. Exiting.\n", status); - exit(1); - } - - sim_config *acados_sim_config = {{ model.name }}_acados_get_sim_config(capsule); - sim_in *acados_sim_in = {{ model.name }}_acados_get_sim_in(capsule); - sim_out *acados_sim_out = {{ model.name }}_acados_get_sim_out(capsule); - void *acados_sim_dims = {{ model.name }}_acados_get_sim_dims(capsule); - - // initial condition - double x_current[NX]; - {%- for i in range(end=dims.nx) %} - x_current[{{ i }}] = 0.0; - {%- endfor %} - - {% if constraints.lbx_0 %} - {%- for i in range(end=dims.nbx_0) %} - x_current[{{ constraints.idxbx_0[i] }}] = {{ constraints.lbx_0[i] }}; - {%- endfor %} - {% if dims.nbx_0 != dims.nx %} - printf("main_sim: NOTE: initial state not fully defined via lbx_0, using 0.0 for indices that are not in idxbx_0."); - {%- endif %} - {% else %} - printf("main_sim: initial state not defined, should be in lbx_0, using zero vector."); - {%- endif %} - - - // initial value for control input - double u0[NU]; - {%- for i in range(end=dims.nu) %} - u0[{{ i }}] = 0.0; - {%- endfor %} - - {%- if dims.np > 0 %} - // set parameters - double p[NP]; - {%- for item in parameter_values %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endfor %} - - {{ model.name }}_acados_sim_update_params(capsule, p, NP); - {% endif %}{# if np > 0 #} - - int n_sim_steps = 3; - // solve ocp in loop - for (int ii = 0; ii < n_sim_steps; ii++) - { - sim_in_set(acados_sim_config, acados_sim_dims, - acados_sim_in, "x", x_current); - status = {{ model.name }}_acados_sim_solve(capsule); - - if (status != ACADOS_SUCCESS) - { - printf("acados_solve() failed with status %d.\n", status); - } - - sim_out_get(acados_sim_config, acados_sim_dims, - acados_sim_out, "x", x_current); - - printf("\nx_current, %d\n", ii); - for (int jj = 0; jj < NX; jj++) - { - printf("%e\n", x_current[jj]); - } - } - - printf("\nPerformed %d simulation steps with acados integrator successfully.\n\n", n_sim_steps); - - // free solver - status = {{ model.name }}_acados_sim_free(capsule); - if (status) { - printf("{{ model.name }}_acados_sim_free() returned status %d. \n", status); - } - - {{ model.name }}_acados_sim_solver_free_capsule(capsule); - - return status; -} diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_create.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_create.in.c deleted file mode 100644 index 24ae94ac2cc96d..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_create.in.c +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -// standard -#include -#include -#include - -// acados -#include "acados/utils/print.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_solver_{{ model.name }}.h" - -// mex -#include "mex.h" - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) -{ - long long *l_ptr; - int status = 0; - - // create solver - {{ model.name }}_solver_capsule *acados_ocp_capsule = {{ model.name }}_acados_create_capsule(); - - status = {{ model.name }}_acados_create(acados_ocp_capsule); - - if (status) - { - mexPrintf("{{ model.name }}_acados_create() returned status %d.\n", status); - } - mexPrintf("{{ model.name }}_acados_create() -> success!\n"); - - // get pointers to nlp solver related objects - ocp_nlp_plan_t *nlp_plan = {{ model.name }}_acados_get_nlp_plan(acados_ocp_capsule); - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(acados_ocp_capsule); - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(acados_ocp_capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(acados_ocp_capsule); - ocp_nlp_out *nlp_out = {{ model.name }}_acados_get_nlp_out(acados_ocp_capsule); - ocp_nlp_solver *nlp_solver = {{ model.name }}_acados_get_nlp_solver(acados_ocp_capsule); - void *nlp_opts = {{ model.name }}_acados_get_nlp_opts(acados_ocp_capsule); - - // mexPrintf("acados: got pointer to objectes!\n"); - - // field names of output struct - #define FIELDS_OCP 9 - #define FIELDS_EXT_FUN 25 - #define MAX_FIELDS 25 - char *fieldnames[MAX_FIELDS]; - - for (int i = 0; i < MAX_FIELDS; i++) - { - fieldnames[i] = (char*) mxMalloc(50); - } - - memcpy(fieldnames[0],"config",sizeof("config")); - memcpy(fieldnames[1],"dims",sizeof("dims")); - memcpy(fieldnames[2],"opts",sizeof("opts")); - memcpy(fieldnames[3],"in",sizeof("in")); - memcpy(fieldnames[4],"out",sizeof("out")); - memcpy(fieldnames[5],"solver",sizeof("solver")); - memcpy(fieldnames[6],"sens_out",sizeof("sens_out")); - memcpy(fieldnames[7],"plan",sizeof("plan")); - memcpy(fieldnames[8],"capsule",sizeof("capsule")); - - // create output struct - C_ocp - plhs[0] = mxCreateStructMatrix(1, 1, 9, (const char **) fieldnames); - - // MEX: config, dims, opts, in, out, solver, sens_out, plan - // plan - mxArray *plan_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(plan_mat); - l_ptr[0] = (long long) nlp_plan; - mxSetField(plhs[0], 0, "plan", plan_mat); - - // config - mxArray *config_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(config_mat); - l_ptr[0] = (long long) nlp_config; - mxSetField(plhs[0], 0, "config", config_mat); - - // dims - mxArray *dims_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(dims_mat); - l_ptr[0] = (long long) nlp_dims; - mxSetField(plhs[0], 0, "dims", dims_mat); - - // opts - mxArray *opts_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(opts_mat); - l_ptr[0] = (long long) nlp_opts; - mxSetField(plhs[0], 0, "opts", opts_mat); - - // in - mxArray *in_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(in_mat); - l_ptr[0] = (long long) nlp_in; - mxSetField(plhs[0], 0, "in", in_mat); - - // out - mxArray *out_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(out_mat); - l_ptr[0] = (long long) nlp_out; - mxSetField(plhs[0], 0, "out", out_mat); - - // solver - mxArray *solver_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(solver_mat); - l_ptr[0] = (long long) nlp_solver; - mxSetField(plhs[0], 0, "solver", solver_mat); - - // TODO: sens_out not actually implemented in templates.. - // sens_out - mxArray *sens_out_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(sens_out_mat); - l_ptr[0] = (long long) 1; - mxSetField(plhs[0], 0, "sens_out", sens_out_mat); - - // capsule - mxArray *capsule_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(capsule_mat); - l_ptr[0] = (long long) acados_ocp_capsule; - mxSetField(plhs[0], 0, "capsule", capsule_mat); - - /* store external function pointers */ - // dyn - memcpy(fieldnames[0],"expl_ode_fun",sizeof("expl_ode_fun")); - memcpy(fieldnames[1],"forw_vde",sizeof("forw_vde")); - memcpy(fieldnames[2],"hess_vde",sizeof("hess_vde")); - memcpy(fieldnames[3],"impl_dae_fun",sizeof("impl_dae_fun")); - memcpy(fieldnames[4],"impl_dae_fun_jac_x_xdot_z",sizeof("impl_dae_fun_jac_x_xdot_z")); - memcpy(fieldnames[5],"impl_dae_jac_x_xdot_u_z",sizeof("impl_dae_jac_x_xdot_u_z")); - memcpy(fieldnames[6],"impl_dae_hess",sizeof("impl_dae_hess")); - - memcpy(fieldnames[7],"gnsf_phi_fun",sizeof("gnsf_phi_fun")); - memcpy(fieldnames[8],"gnsf_phi_fun_jac_y",sizeof("gnsf_phi_fun_jac_y")); - memcpy(fieldnames[9],"gnsf_phi_jac_y_uhat",sizeof("gnsf_phi_jac_y_uhat")); - memcpy(fieldnames[10],"gnsf_f_lo_jac_x1_x1dot_u_z",sizeof("gnsf_f_lo_jac_x1_x1dot_u_z")); - memcpy(fieldnames[11],"gnsf_get_matrices_fun",sizeof("gnsf_get_matrices_fun")); - - memcpy(fieldnames[12],"disc_phi_fun",sizeof("disc_phi_fun")); - memcpy(fieldnames[13],"disc_phi_fun_jac",sizeof("disc_phi_fun_jac")); - memcpy(fieldnames[14],"disc_phi_fun_jac_hess",sizeof("disc_phi_fun_jac_hess")); - - // cost - memcpy(fieldnames[15],"cost_y_fun",sizeof("cost_y_fun")); - memcpy(fieldnames[16],"cost_y_fun_jac_ut_xt",sizeof("cost_y_fun_jac_ut_xt")); - memcpy(fieldnames[17],"cost_y_hess",sizeof("cost_y_hess")); - memcpy(fieldnames[18],"ext_cost_fun",sizeof("ext_cost_fun")); - memcpy(fieldnames[19],"ext_cost_fun_jac",sizeof("ext_cost_fun_jac")); - memcpy(fieldnames[20],"ext_cost_fun_jac_hess",sizeof("ext_cost_fun_jac_hess")); - - // constraints - memcpy(fieldnames[21],"phi_constraint",sizeof("phi_constraint")); - memcpy(fieldnames[22],"nl_constr_h_fun_jac",sizeof("nl_constr_h_fun_jac")); - memcpy(fieldnames[23],"nl_constr_h_fun",sizeof("nl_constr_h_fun")); - memcpy(fieldnames[24],"nl_constr_h_fun_jac_hess",sizeof("nl_constr_h_fun_jac_hess")); - - - // create output struct - C_ocp_ext_fun - plhs[1] = mxCreateStructMatrix(1, 1, FIELDS_EXT_FUN, (const char **) fieldnames); - - - for (int i = 0; i < FIELDS_EXT_FUN; i++) - { - mxFree( fieldnames[i] ); - } - -/* dynamics */ - mxArray *expl_ode_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *forw_vde_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *hess_vde_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *impl_dae_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *impl_dae_fun_jac_x_xdot_z_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *impl_dae_jac_x_xdot_u_z_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *impl_dae_hess_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - - mxArray *gnsf_phi_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *gnsf_phi_fun_jac_y_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *gnsf_phi_jac_y_uhat_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *gnsf_f_lo_jac_x1_x1dot_u_z_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *gnsf_get_matrices_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - - mxArray *disc_phi_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *disc_phi_fun_jac_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *disc_phi_fun_jac_hess_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - -{% if solver_options.integrator_type == "ERK" %} - {# TODO: remove _casadi from these names.. #} - l_ptr = mxGetData(forw_vde_mat); - l_ptr[0] = (long long) acados_ocp_capsule->forw_vde_casadi; - l_ptr = mxGetData(expl_ode_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->expl_ode_fun; -{% if solver_options.hessian_approx == "EXACT" %} - l_ptr = mxGetData(hess_vde_mat); - l_ptr[0] = (long long) acados_ocp_capsule->hess_vde_casadi; -{%- endif %} -{% elif solver_options.integrator_type == "IRK" %} - l_ptr = mxGetData(impl_dae_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_fun; - l_ptr = mxGetData(impl_dae_fun_jac_x_xdot_z_mat); - l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_fun_jac_x_xdot_z; - l_ptr = mxGetData(impl_dae_jac_x_xdot_u_z_mat); - l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_jac_x_xdot_u_z; -{% if solver_options.hessian_approx == "EXACT" %} - l_ptr = mxGetData(impl_dae_hess_mat); - l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_hess; -{%- endif %} -{% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - l_ptr = mxGetData(gnsf_phi_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_fun; - l_ptr = mxGetData(gnsf_phi_fun_jac_y_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_fun_jac_y; - l_ptr = mxGetData(gnsf_phi_jac_y_uhat_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_jac_y_uhat; - {% if model.gnsf.nontrivial_f_LO == 1 %} - l_ptr = mxGetData(gnsf_f_lo_jac_x1_x1dot_u_z_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_f_lo_jac_x1_x1dot_u_z; - {%- endif %} - {%- endif %} - l_ptr = mxGetData(gnsf_get_matrices_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_get_matrices_fun; -{% elif solver_options.integrator_type == "DISCRETE" %} - l_ptr = mxGetData(disc_phi_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->discr_dyn_phi_fun; - l_ptr = mxGetData(disc_phi_fun_jac_mat); - l_ptr[0] = (long long) acados_ocp_capsule->discr_dyn_phi_fun_jac_ut_xt; -{% if solver_options.hessian_approx == "EXACT" %} - l_ptr = mxGetData(disc_phi_fun_jac_hess_mat); - l_ptr[0] = (long long) acados_ocp_capsule->discr_dyn_phi_fun_jac_ut_xt_hess; -{%- endif %} -{%- endif %} - mxSetField(plhs[1], 0, "expl_ode_fun", expl_ode_fun_mat); - mxSetField(plhs[1], 0, "forw_vde", forw_vde_mat); - mxSetField(plhs[1], 0, "hess_vde", hess_vde_mat); - - mxSetField(plhs[1], 0, "gnsf_phi_fun", gnsf_phi_fun_mat); - mxSetField(plhs[1], 0, "gnsf_phi_fun_jac_y", gnsf_phi_fun_jac_y_mat); - mxSetField(plhs[1], 0, "gnsf_phi_jac_y_uhat", gnsf_phi_jac_y_uhat_mat); - mxSetField(plhs[1], 0, "gnsf_f_lo_jac_x1_x1dot_u_z", gnsf_f_lo_jac_x1_x1dot_u_z_mat); - mxSetField(plhs[1], 0, "gnsf_get_matrices_fun", gnsf_get_matrices_fun_mat); - - mxSetField(plhs[1], 0, "impl_dae_fun", impl_dae_fun_mat); - mxSetField(plhs[1], 0, "impl_dae_fun_jac_x_xdot_z", impl_dae_fun_jac_x_xdot_z_mat); - mxSetField(plhs[1], 0, "impl_dae_jac_x_xdot_u_z", impl_dae_jac_x_xdot_u_z_mat); - mxSetField(plhs[1], 0, "impl_dae_hess", impl_dae_hess_mat); - - mxSetField(plhs[1], 0, "disc_phi_fun", disc_phi_fun_mat); - mxSetField(plhs[1], 0, "disc_phi_fun_jac", disc_phi_fun_jac_mat); - mxSetField(plhs[1], 0, "disc_phi_fun_jac_hess", disc_phi_fun_jac_hess_mat); -/* constaints */ - mxArray *phi_constraint_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(phi_constraint_mat); -{%- if constraints.constr_type == "BGP" %} - l_ptr[0] = (long long) acados_ocp_capsule->phi_constraint; -{% endif %} -{% if constraints.constr_type_e == "BGP" %} - l_ptr[1] = (long long) &acados_ocp_capsule->phi_e_constraint; -{% endif %} - mxSetField(plhs[1], 0, "phi_constraint", phi_constraint_mat); - - mxArray *nl_constr_h_fun_jac_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(nl_constr_h_fun_jac_mat); -{% if constraints.constr_type == "BGH" and dims.nh > 0 %} - l_ptr[0] = (long long) acados_ocp_capsule->nl_constr_h_fun_jac; -{% endif %} -{% if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - l_ptr[1] = (long long) &acados_ocp_capsule->nl_constr_h_e_fun_jac; -{%- endif %} - mxSetField(plhs[1], 0, "nl_constr_h_fun_jac", nl_constr_h_fun_jac_mat); - - mxArray *nl_constr_h_fun_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(nl_constr_h_fun_mat); -{% if constraints.constr_type == "BGH" and dims.nh > 0 %} - l_ptr[0] = (long long) acados_ocp_capsule->nl_constr_h_fun; -{% endif %} -{% if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - l_ptr[1] = (long long) &acados_ocp_capsule->nl_constr_h_e_fun; -{%- endif %} - mxSetField(plhs[1], 0, "nl_constr_h_fun", nl_constr_h_fun_mat); - - mxArray *nl_constr_h_fun_jac_hess_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(nl_constr_h_fun_jac_hess_mat); -{% if constraints.constr_type == "BGH" and dims.nh > 0 and solver_options.hessian_approx == "EXACT" %} - l_ptr[0] = (long long) acados_ocp_capsule->nl_constr_h_fun_jac_hess; -{% endif %} -{% if constraints.constr_type_e == "BGH" and dims.nh_e > 0 and solver_options.hessian_approx == "EXACT" %} - l_ptr[1] = (long long) &acados_ocp_capsule->nl_constr_h_e_fun_jac_hess; -{%- endif %} - mxSetField(plhs[1], 0, "nl_constr_h_fun_jac_hess", nl_constr_h_fun_jac_hess_mat); - -/* cost */ - mxArray *cost_y_fun_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(cost_y_fun_mat); -{% if cost.cost_type == "NONLINEAR_LS" %} - l_ptr[0] = (long long) acados_ocp_capsule->cost_y_fun; -{% endif %} -{% if cost.cost_type_e == "NONLINEAR_LS" %} - l_ptr[1] = (long long) &acados_ocp_capsule->cost_y_e_fun; -{%- endif %} - mxSetField(plhs[1], 0, "cost_y_fun", cost_y_fun_mat); - - mxArray *cost_y_fun_jac_ut_xt_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(cost_y_fun_jac_ut_xt_mat); -{% if cost.cost_type == "NONLINEAR_LS" %} - l_ptr[0] = (long long) acados_ocp_capsule->cost_y_fun_jac_ut_xt; -{% endif %} -{% if cost.cost_type_e == "NONLINEAR_LS" %} - l_ptr[1] = (long long) &acados_ocp_capsule->cost_y_e_fun_jac_ut_xt; -{%- endif %} - mxSetField(plhs[1], 0, "cost_y_fun_jac_ut_xt", cost_y_fun_jac_ut_xt_mat); - - mxArray *cost_y_hess_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(cost_y_hess_mat); -{% if cost.cost_type == "NONLINEAR_LS" %} - l_ptr[0] = (long long) acados_ocp_capsule->cost_y_hess; -{% endif %} -{% if cost.cost_type_e == "NONLINEAR_LS" %} - l_ptr[1] = (long long) &acados_ocp_capsule->cost_y_e_hess; -{%- endif %} - mxSetField(plhs[1], 0, "cost_y_hess", cost_y_hess_mat); - - mxArray *ext_cost_fun_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(ext_cost_fun_mat); -{% if cost.cost_type == "EXTERNAL" %} - l_ptr[0] = (long long) acados_ocp_capsule->ext_cost_fun; -{% endif -%} -{% if cost.cost_type_e == "EXTERNAL" %} - l_ptr[1] = (long long) &acados_ocp_capsule->ext_cost_e_fun; -{%- endif %} - mxSetField(plhs[1], 0, "ext_cost_fun", ext_cost_fun_mat); - - mxArray *ext_cost_fun_jac_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(ext_cost_fun_jac_mat); -{% if cost.cost_type == "EXTERNAL" %} - l_ptr[0] = (long long) acados_ocp_capsule->ext_cost_fun_jac; -{% endif -%} -{% if cost.cost_type_e == "EXTERNAL" %} - l_ptr[1] = (long long) &acados_ocp_capsule->ext_cost_e_fun_jac; -{%- endif %} - mxSetField(plhs[1], 0, "ext_cost_fun_jac", ext_cost_fun_jac_mat); - - mxArray *ext_cost_fun_jac_hess_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(ext_cost_fun_jac_hess_mat); -{% if cost.cost_type == "EXTERNAL" %} - l_ptr[0] = (long long) acados_ocp_capsule->ext_cost_fun_jac_hess; -{% endif -%} -{% if cost.cost_type_e == "EXTERNAL" %} - l_ptr[1] = (long long) &acados_ocp_capsule->ext_cost_e_fun_jac_hess; -{%- endif %} - mxSetField(plhs[1], 0, "ext_cost_fun_jac_hess", ext_cost_fun_jac_hess_mat); - - - return; -} diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_free.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_free.in.c deleted file mode 100644 index bd457969b27408..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_free.in.c +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -// system -#include -#include -#include -// acados -#include "acados_solver_{{ model.name }}.h" - -// mex -#include "mex.h" - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) -{ - int status = 0; - long long *ptr; - - // mexPrintf("\nin mex_acados_free\n"); - const mxArray *C_ocp = prhs[0]; - // capsule - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "capsule" ) ); - {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) ptr[0]; - - status = {{ model.name }}_acados_free(capsule); - if (status) - { - mexPrintf("{{ model.name }}_acados_free() returned status %d.\n", status); - } - - status = {{ model.name }}_acados_free_capsule(capsule); - if (status) - { - mexPrintf("{{ model.name }}_acados_free_capsule() returned status %d.\n", status); - } - - return; -} - diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_set.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_set.in.c deleted file mode 100644 index 78a308df495b36..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_set.in.c +++ /dev/null @@ -1,632 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -// standard -#include -#include -#include - -// acados -#include "acados/utils/print.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_solver_{{ model.name }}.h" - -// mex -#include "mex.h" -#include "mex_macros.h" - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) -{ - - long long *ptr; - int acados_size; - mxArray *mex_field; - char fun_name[20] = "ocp_set"; - char buffer [500]; // for error messages - - /* RHS */ - int min_nrhs = 6; - - // C ocp - const mxArray *C_ocp = prhs[2]; - // capsule - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "capsule" ) ); - {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) ptr[0]; - // plan - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "plan" ) ); - ocp_nlp_plan_t *plan = (ocp_nlp_plan_t *) ptr[0]; - // config - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "config" ) ); - ocp_nlp_config *config = (ocp_nlp_config *) ptr[0]; - // dims - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "dims" ) ); - ocp_nlp_dims *dims = (ocp_nlp_dims *) ptr[0]; - // opts - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "opts" ) ); - void *opts = (void *) ptr[0]; - // in - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "in" ) ); - ocp_nlp_in *in = (ocp_nlp_in *) ptr[0]; - // out - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "out" ) ); - ocp_nlp_out *out = (ocp_nlp_out *) ptr[0]; - // solver - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "solver" ) ); - ocp_nlp_solver *solver = (ocp_nlp_solver *) ptr[0]; - - const mxArray *C_ext_fun_pointers = prhs[3]; - // field - char *field = mxArrayToString( prhs[4] ); - // value - double *value = mxGetPr( prhs[5] ); - - // for checks - int matlab_size = (int) mxGetNumberOfElements( prhs[5] ); - int nrow = (int) mxGetM( prhs[5] ); - int ncol = (int) mxGetN( prhs[5] ); - - int N = dims->N; - int nu = dims->nu[0]; - int nx = dims->nx[0]; - - // stage - int s0, se; - if (nrhs==min_nrhs) - { - s0 = 0; - se = N; - } - else if (nrhs==min_nrhs+1) - { - s0 = mxGetScalar( prhs[6] ); - if (s0 > N) - { - sprintf(buffer, "ocp_set: N < specified stage = %d\n", s0); - mexErrMsgTxt(buffer); - } - se = s0 + 1; - } - else - { - sprintf(buffer, "ocp_set: wrong nrhs: %d\n", nrhs); - mexErrMsgTxt(buffer); - } - - /* Set value */ - // constraints - if (!strcmp(field, "constr_x0")) - { - acados_size = nx; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_constraints_model_set(config, dims, in, 0, "lbx", value); - ocp_nlp_constraints_model_set(config, dims, in, 0, "ubx", value); - } - else if (!strcmp(field, "constr_C")) - { - for (int ii=s0; iinlp_cost[ii] == LINEAR_LS) || (plan->nlp_cost[ii] == NONLINEAR_LS)) - { - acados_size = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "y_ref"); - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, ii, "y_ref", value); - } - else - { - MEX_FIELD_NOT_SUPPORTED_FOR_COST_STAGE(fun_name, field, plan->nlp_cost[ii], ii); - } - } - } - else if (!strcmp(field, "cost_y_ref_e")) - { - acados_size = ocp_nlp_dims_get_from_attr(config, dims, out, N, "y_ref"); - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, N, "y_ref", value); - } - else if (!strcmp(field, "cost_Vu")) - { - for (int ii=s0; iinlp_cost[ii] == LINEAR_LS) || (plan->nlp_cost[ii] == NONLINEAR_LS)) - { - int ny = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "y_ref"); - int nu = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "u"); - acados_size = ny * nu; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, ii, "Vu", value); - } - else - { - MEX_FIELD_NOT_SUPPORTED_FOR_COST_STAGE(fun_name, field, plan->nlp_cost[ii], ii); - } - } - } - else if (!strcmp(field, "cost_Vx")) - { - for (int ii=s0; iinlp_cost[ii] == LINEAR_LS) || (plan->nlp_cost[ii] == NONLINEAR_LS)) - { - int ny = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "y_ref"); - int nx = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "x"); - acados_size = ny * nx; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, ii, "Vx", value); - } - else - { - MEX_FIELD_NOT_SUPPORTED_FOR_COST_STAGE(fun_name, field, plan->nlp_cost[ii], ii); - } - } - } - else if (!strcmp(field, "cost_W")) - { - for (int ii=s0; iinlp_cost[ii] == LINEAR_LS) || (plan->nlp_cost[ii] == NONLINEAR_LS)) - { - int ny = ocp_nlp_dims_get_from_attr(config, dims, out, s0, "y_ref"); - acados_size = ny * ny; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, ii, "W", value); - } - else - { - MEX_FIELD_NOT_SUPPORTED_FOR_COST_STAGE(fun_name, field, plan->nlp_cost[ii], ii); - } - } - } - else if (!strcmp(field, "cost_Z")) - { - acados_size = ocp_nlp_dims_get_from_attr(config, dims, out, s0, "cost_Z"); - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - for (int ii=s0; iisim_solver_plan[0]; - sim_solver_t type = sim_plan.sim_solver; - if (type == IRK) - { - int nz = ocp_nlp_dims_get_from_attr(config, dims, out, 0, "z"); - if (nrhs==min_nrhs) - { - acados_size = N*nz; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - for (int ii=0; iisim_solver_plan[0]; - sim_solver_t type = sim_plan.sim_solver; - if (type == IRK) - { - int nx = ocp_nlp_dims_get_from_attr(config, dims, out, 0, "x"); - if (nrhs==min_nrhs) - { - acados_size = N*nx; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - for (int ii=0; iisim_solver_plan[0]; - sim_solver_t type = sim_plan.sim_solver; - if (type == GNSF) - { - int nout = ocp_nlp_dims_get_from_attr(config, dims, out, 0, "init_gnsf_phi"); - - if (nrhs==min_nrhs) - { - acados_size = N*nout; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - for (int ii=0; iinlp_solver == SQP && rti_phase != 0) - { - MEX_FIELD_ONLY_SUPPORTED_FOR_SOLVER(fun_name, field, "sqp_rti") - } - ocp_nlp_solver_opts_set(config, opts, "rti_phase", &rti_phase); - } - else if (!strcmp(field, "qp_warm_start")) - { - acados_size = 1; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - int qp_warm_start = (int) value[0]; - ocp_nlp_solver_opts_set(config, opts, "qp_warm_start", &qp_warm_start); - } - else if (!strcmp(field, "warm_start_first_qp")) - { - acados_size = 1; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - int warm_start_first_qp = (int) value[0]; - ocp_nlp_solver_opts_set(config, opts, "warm_start_first_qp", &warm_start_first_qp); - } - else if (!strcmp(field, "print_level")) - { - acados_size = 1; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - int print_level = (int) value[0]; - ocp_nlp_solver_opts_set(config, opts, "print_level", &print_level); - } - else - { - MEX_FIELD_NOT_SUPPORTED_SUGGEST(fun_name, field, "p, constr_x0,\ - constr_lbx, constr_ubx, constr_C, constr_D, constr_lg, constr_ug, constr_lh, constr_uh,\ - constr_lbu, constr_ubu, cost_y_ref[_e], sl, su, x, xdot, u, pi, lam, z, \ - cost_Vu, cost_Vx, cost_Vz, cost_W, cost_Z, cost_Zl, cost_Zu, cost_z,\ - cost_zl, cost_zu, init_x, init_u, init_z, init_xdot, init_gnsf_phi,\ - init_pi, nlp_solver_max_iter, qp_warm_start, warm_start_first_qp, print_level"); - } - - return; -} - diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_solve.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_solve.in.c deleted file mode 100644 index 300a440cc928ca..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_solve.in.c +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -// system -#include -#include -#include -// acados -#include "acados_solver_{{ model.name }}.h" - -// mex -#include "mex.h" - - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) -{ - // C_ocp - long long *ptr; - const mxArray *C_ocp = prhs[0]; - - // capsule - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "capsule" ) ); - {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) ptr[0]; - - // solve - {{ model.name }}_acados_solve(capsule); - -} diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_sim_solver_sfun.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_sim_solver_sfun.in.c deleted file mode 100644 index bd73ff69a45e99..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_sim_solver_sfun.in.c +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -#define S_FUNCTION_NAME acados_sim_solver_sfunction_{{ model.name }} -#define S_FUNCTION_LEVEL 2 - -#define MDL_START - -// acados -// #include "acados/utils/print.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_c/external_function_interface.h" - -// example specific -#include "{{ model.name }}_model/{{ model.name }}_model.h" -#include "acados_sim_solver_{{ model.name }}.h" - -#include "simstruc.h" - -#define SAMPLINGTIME {{ solver_options.Tsim }} - - -static void mdlInitializeSizes (SimStruct *S) -{ - // specify the number of continuous and discrete states - ssSetNumContStates(S, 0); - ssSetNumDiscStates(S, 0); - - {# compute number of input ports #} - {%- set n_inputs = 1 %} {# x0 #} - {%- if dims.nu > 0 %} {# u0 -#} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif %} - {%- if dims.np > 0 %} {# parameters #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif %} - - // specify the number of input ports - if ( !ssSetNumInputPorts(S, {{ n_inputs }}) ) - return; - - // specify the number of output ports - if ( !ssSetNumOutputPorts(S, 1) ) - return; - - // specify dimension information for the input ports - {%- set i_input = 0 %} - // x0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nx }}); - - {%- if dims.nu > 0 %} - {%- set i_input = i_input + 1 %} - // u0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nu }}); - {%- endif %} - - {%- if dims.np > 0 %} - {%- set i_input = i_input + 1 %} - // parameters - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.np }}); - {%- endif %} - - // specify dimension information for the output ports - ssSetOutputPortVectorDimension(S, 0, {{ dims.nx }} ); // xnext - - // specify the direct feedthrough status - // should be set to 1 for all inputs used in mdlOutputs - {%- for i in range(end=n_inputs) %} - ssSetInputPortDirectFeedThrough(S, {{ i }}, 1); - {%- endfor %} - - // one sample time - ssSetNumSampleTimes(S, 1); -} - - -#if defined(MATLAB_MEX_FILE) - -#define MDL_SET_INPUT_PORT_DIMENSION_INFO -#define MDL_SET_OUTPUT_PORT_DIMENSION_INFO - -static void mdlSetInputPortDimensionInfo(SimStruct *S, int_T port, const DimsInfo_T *dimsInfo) -{ - if ( !ssSetInputPortDimensionInfo(S, port, dimsInfo) ) - return; -} - -static void mdlSetOutputPortDimensionInfo(SimStruct *S, int_T port, const DimsInfo_T *dimsInfo) -{ - if ( !ssSetOutputPortDimensionInfo(S, port, dimsInfo) ) - return; -} - -#endif /* MATLAB_MEX_FILE */ - - -static void mdlInitializeSampleTimes(SimStruct *S) -{ - ssSetSampleTime(S, 0, SAMPLINGTIME); - ssSetOffsetTime(S, 0, 0.0); -} - - -static void mdlStart(SimStruct *S) -{ - sim_solver_capsule *capsule = {{ model.name }}_acados_sim_solver_create_capsule(); - {{ model.name }}_acados_sim_create(capsule); - - ssSetUserData(S, (void*)capsule); -} - -static void mdlOutputs(SimStruct *S, int_T tid) -{ - sim_solver_capsule *capsule = ssGetUserData(S); - - sim_config *acados_sim_config = {{ model.name }}_acados_get_sim_config(capsule); - sim_in *acados_sim_in = {{ model.name }}_acados_get_sim_in(capsule); - sim_out *acados_sim_out = {{ model.name }}_acados_get_sim_out(capsule); - void *acados_sim_dims = {{ model.name }}_acados_get_sim_dims(capsule); - // sim_opts * {{ model.name }}_acados_get_sim_opts(capsule); - // sim_solver * {{ model.name }}_acados_get_sim_solver(capsule); - - InputRealPtrsType in_sign; - {% set input_sizes = [dims.nx, dims.nu, dims.np] %} - - // local buffer - {%- set buffer_size = input_sizes | sort | last %} - real_t buffer[{{ buffer_size }}]; - - - /* go through inputs */ - {%- set i_input = 0 %} - // initial condition - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nx }}; i++) - buffer[i] = (double)(*in_sign[i]); - - sim_in_set(acados_sim_config, acados_sim_dims, - acados_sim_in, "x", buffer); - - - // ssPrintf("\nin acados sim:\n"); - // for (int i = 0; i < {{ dims.nx }}; i++) ssPrintf("x0[%d] = %f\n", i, buffer[i]); - // ssPrintf("\n"); - -{% if dims.nu > 0 %} - // control input - u - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.nu }}; i++) - buffer[i] = (double)(*in_sign[i]); - - sim_in_set(acados_sim_config, acados_sim_dims, - acados_sim_in, "u", buffer); -{%- endif %} - - -{% if dims.np > 0 %} - // parameters - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.np }}; i++) - buffer[i] = (double)(*in_sign[i]); - - // update value of parameters - {{ model.name }}_acados_sim_update_params(capsule, buffer, {{ dims.np }}); -{%- endif %} - - - /* call solver */ - int acados_status = {{ model.name }}_acados_sim_solve(capsule); - - - /* set outputs */ - real_t *out_x = ssGetOutputPortRealSignal(S, 0); - - // get simulated state - sim_out_get(acados_sim_config, acados_sim_dims, acados_sim_out, - "xn", (void *) out_x); - - // ssPrintf("\nacados sim solve: returned %d\n", acados_status); - // for (int i = 0; i < {{ dims.nx }}; i++) ssPrintf("x_sim[%d] = %f\n", i, out_x[i]); - // ssPrintf("\n"); - -} - - -static void mdlTerminate(SimStruct *S) -{ - sim_solver_capsule *capsule = ssGetUserData(S); - - {{ model.name }}_acados_sim_free(capsule); - {{ model.name }}_acados_sim_solver_free_capsule(capsule); -} - - -#ifdef MATLAB_MEX_FILE -#include "simulink.c" -#else -#include "cg_sfun.h" -#endif diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_solver_sfun.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_solver_sfun.in.c deleted file mode 100644 index 3dd248037aeedd..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_solver_sfun.in.c +++ /dev/null @@ -1,853 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -#define S_FUNCTION_NAME acados_solver_sfunction_{{ model.name }} -#define S_FUNCTION_LEVEL 2 - -#define MDL_START - -// acados -// #include "acados/utils/print.h" -#include "acados_c/sim_interface.h" -#include "acados_c/external_function_interface.h" - -// example specific -#include "{{ model.name }}_model/{{ model.name }}_model.h" -#include "acados_solver_{{ model.name }}.h" - -#include "simstruc.h" - -{% if simulink_opts.samplingtime == "t0" -%} -#define SAMPLINGTIME {{ solver_options.time_steps[0] }} -{%- elif simulink_opts.samplingtime == "-1" -%} -#define SAMPLINGTIME -1 -{%- else -%} - {{ throw(message = "simulink_opts.samplingtime must be '-1' or 't0', got val") }} -{%- endif %} - -static void mdlInitializeSizes (SimStruct *S) -{ - // specify the number of continuous and discrete states - ssSetNumContStates(S, 0); - ssSetNumDiscStates(S, 0); - - int N = {{ model.name | upper }}_N; - - {%- for key, val in simulink_opts.inputs -%} - {%- if val != 0 and val != 1 -%} - {{ throw(message = "simulink_opts.inputs must be 0 or 1, got val") }} - {%- endif -%} - {%- endfor -%} - - {#- compute number of input ports #} - {%- set n_inputs = 0 -%} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.lbx_0 -%} {#- lbx_0 #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.ubx_0 -%} {#- ubx_0 #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.np > 0 and simulink_opts.inputs.parameter_traj -%} {#- parameter_traj #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ny_0 > 0 and simulink_opts.inputs.y_ref_0 -%} {#- y_ref_0 -#} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref -%} {#- y_ref -#} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e -%} {#- y_ref_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.lbx -%} {#- lbx #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.ubx -%} {#- ubx #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.lbx_e -%} {#- lbx_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.ubx_e -%} {#- ubx_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.lbu -%} {#- lbu #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.ubu -%} {#- ubu #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ng > 0 and simulink_opts.inputs.lg -%} {#- lg #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ng > 0 and simulink_opts.inputs.ug -%} {#- ug #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nh > 0 and simulink_opts.inputs.lh -%} {#- lh #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nh > 0 and simulink_opts.inputs.uh -%} {#- uh #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nh_e > 0 and simulink_opts.inputs.lh_e -%} {#- lh_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nh_e > 0 and simulink_opts.inputs.uh_e -%} {#- uh_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - {%- for key, val in simulink_opts.inputs -%} - {%- if val != 0 and val != 1 -%} - {{ throw(message = "simulink_opts.inputs must be 0 or 1, got val") }} - {%- endif -%} - {%- endfor -%} - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} - {%- set n_inputs = n_inputs + 1 %} - {%- endif -%} - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} - {%- set n_inputs = n_inputs + 1 %} - {%- endif -%} - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - {%- if simulink_opts.inputs.reset_solver -%} {#- reset_solver #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - {%- if simulink_opts.inputs.x_init -%} {#- x_init #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - {%- if simulink_opts.inputs.u_init -%} {#- u_init #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - // specify the number of input ports - if ( !ssSetNumInputPorts(S, {{ n_inputs }}) ) - return; - - // specify the number of output ports - {%- set_global n_outputs = 0 %} - {%- for key, val in simulink_opts.outputs %} - {%- if val == 1 %} - {%- set_global n_outputs = n_outputs + val %} - {%- elif val != 0 %} - {{ throw(message = "simulink_opts.outputs must be 0 or 1, got val") }} - {%- endif %} - {%- endfor %} - if ( !ssSetNumOutputPorts(S, {{ n_outputs }}) ) - return; - - // specify dimension information for the input ports - {%- set i_input = -1 %}{# note here i_input is 0-based #} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.lbx_0 -%} {#- lbx_0 #} - {%- set i_input = i_input + 1 %} - // lbx_0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nbx_0 }}); - {%- endif %} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.ubx_0 -%} {#- ubx_0 #} - {%- set i_input = i_input + 1 %} - // ubx_0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nbx_0 }}); - {%- endif %} - - {%- if dims.np > 0 and simulink_opts.inputs.parameter_traj -%} {#- parameter_traj #} - {%- set i_input = i_input + 1 %} - // parameters - ssSetInputPortVectorDimension(S, {{ i_input }}, (N+1) * {{ dims.np }}); - {%- endif %} - - {%- if dims.ny > 0 and simulink_opts.inputs.y_ref_0 %} - {%- set i_input = i_input + 1 %} - // y_ref_0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_0 }}); - {%- endif %} - - {%- if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref %} - {%- set i_input = i_input + 1 %} - // y_ref - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ (dims.N-1) * dims.ny }}); - {%- endif %} - - {%- if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e %} - {%- set i_input = i_input + 1 %} - // y_ref_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_e }}); - {%- endif %} - - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.lbx -%} {#- lbx #} - {%- set i_input = i_input + 1 %} - // lbx - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ (dims.N-1) * dims.nbx }}); - {%- endif %} - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.ubx -%} {#- ubx #} - {%- set i_input = i_input + 1 %} - // ubx - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ (dims.N-1) * dims.nbx }}); - {%- endif %} - - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.lbx_e -%} {#- lbx_e #} - {%- set i_input = i_input + 1 %} - // lbx_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nbx_e }}); - {%- endif %} - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.ubx_e -%} {#- ubx_e #} - {%- set i_input = i_input + 1 %} - // ubx_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nbx_e }}); - {%- endif %} - - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.lbu -%} {#- lbu #} - {%- set i_input = i_input + 1 %} - // lbu - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.nbu }}); - {%- endif -%} - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.ubu -%} {#- ubu #} - {%- set i_input = i_input + 1 %} - // ubu - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.nbu }}); - {%- endif -%} - - - {%- if dims.ng > 0 and simulink_opts.inputs.lg -%} {#- lg #} - {%- set i_input = i_input + 1 %} - // lg - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.ng }}); - {%- endif -%} - {%- if dims.ng > 0 and simulink_opts.inputs.ug -%} {#- ug #} - {%- set i_input = i_input + 1 %} - // ug - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.ng }}); - {%- endif -%} - - {%- if dims.nh > 0 and simulink_opts.inputs.lh -%} {#- lh #} - {%- set i_input = i_input + 1 %} - // lh - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.nh }}); - {%- endif -%} - {%- if dims.nh > 0 and simulink_opts.inputs.uh -%} {#- uh #} - {%- set i_input = i_input + 1 %} - // uh - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.nh }}); - {%- endif -%} - - {%- if dims.nh_e > 0 and simulink_opts.inputs.lh_e -%} {#- lh_e #} - {%- set i_input = i_input + 1 %} - // lh_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nh_e }}); - {%- endif -%} - {%- if dims.nh_e > 0 and simulink_opts.inputs.uh_e -%} {#- uh_e #} - {%- set i_input = i_input + 1 %} - // uh_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nh_e }}); - {%- endif -%} - - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} - {%- set i_input = i_input + 1 %} - // cost_W_0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_0 * dims.ny_0 }}); - {%- endif %} - - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} - {%- set i_input = i_input + 1 %} - // cost_W - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny * dims.ny }}); - {%- endif %} - - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} - {%- set i_input = i_input + 1 %} - // cost_W_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_e * dims.ny_e }}); - {%- endif %} - - {%- if simulink_opts.inputs.reset_solver -%} {#- reset_solver #} - {%- set i_input = i_input + 1 %} - // reset_solver - ssSetInputPortVectorDimension(S, {{ i_input }}, 1); - {%- endif -%} - - {%- if simulink_opts.inputs.x_init -%} {#- x_init #} - {%- set i_input = i_input + 1 %} - // x_init - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nx * (dims.N+1) }}); - {%- endif -%} - - {%- if simulink_opts.inputs.u_init -%} {#- u_init #} - {%- set i_input = i_input + 1 %} - // u_init - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nu * (dims.N) }}); - {%- endif -%} - - /* specify dimension information for the OUTPUT ports */ - {%- set i_output = -1 %}{# note here i_output is 0-based #} - {%- if dims.nu > 0 and simulink_opts.outputs.u0 == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, {{ dims.nu }} ); - {%- endif %} - - {%- if simulink_opts.outputs.utraj == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, {{ dims.nu * dims.N }} ); - {%- endif %} - - {%- if simulink_opts.outputs.xtraj == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, {{ dims.nx * (dims.N+1) }} ); - {%- endif %} - - {%- if simulink_opts.outputs.solver_status == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1 ); - {%- endif %} - - {%- if simulink_opts.outputs.cost_value == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1 ); - {%- endif %} - - {%- if simulink_opts.outputs.KKT_residual == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1 ); - {%- endif %} - - {%- if simulink_opts.outputs.KKT_residuals == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 4 ); - {%- endif %} - - {%- if dims.N > 0 and simulink_opts.outputs.x1 == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, {{ dims.nx }} ); // state at shooting node 1 - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1); - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time_sim == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1); - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time_qp == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1); - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time_lin == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1); - {%- endif %} - - {%- if simulink_opts.outputs.sqp_iter == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1 ); - {%- endif %} - - // specify the direct feedthrough status - // should be set to 1 for all inputs used in mdlOutputs - {%- for i in range(end=n_inputs) %} - ssSetInputPortDirectFeedThrough(S, {{ i }}, 1); - {%- endfor %} - - // one sample time - ssSetNumSampleTimes(S, 1); -} - - -#if defined(MATLAB_MEX_FILE) - -#define MDL_SET_INPUT_PORT_DIMENSION_INFO -#define MDL_SET_OUTPUT_PORT_DIMENSION_INFO - -static void mdlSetInputPortDimensionInfo(SimStruct *S, int_T port, const DimsInfo_T *dimsInfo) -{ - if ( !ssSetInputPortDimensionInfo(S, port, dimsInfo) ) - return; -} - -static void mdlSetOutputPortDimensionInfo(SimStruct *S, int_T port, const DimsInfo_T *dimsInfo) -{ - if ( !ssSetOutputPortDimensionInfo(S, port, dimsInfo) ) - return; -} - -#endif /* MATLAB_MEX_FILE */ - - -static void mdlInitializeSampleTimes(SimStruct *S) -{ - ssSetSampleTime(S, 0, SAMPLINGTIME); - ssSetOffsetTime(S, 0, 0.0); -} - - -static void mdlStart(SimStruct *S) -{ - {{ model.name }}_solver_capsule *capsule = {{ model.name }}_acados_create_capsule(); - {{ model.name }}_acados_create(capsule); - - ssSetUserData(S, (void*)capsule); -} - - -static void mdlOutputs(SimStruct *S, int_T tid) -{ - {{ model.name }}_solver_capsule *capsule = ssGetUserData(S); - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(capsule); - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(capsule); - ocp_nlp_out *nlp_out = {{ model.name }}_acados_get_nlp_out(capsule); - - InputRealPtrsType in_sign; - - int N = {{ model.name | upper }}_N; - - {%- set buffer_sizes = [dims.nbx_0, dims.np, dims.nbx, dims.nbx_e, dims.nbu, dims.ng, dims.nh, dims.ng_e, dims.nh_e] -%} - - {%- if dims.ny_0 > 0 and simulink_opts.inputs.y_ref_0 %} {# y_ref_0 #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_0)) %} - {%- endif %} - {%- if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref %} {# y_ref #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny)) %} - {%- endif %} - {%- if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e %} {# y_ref_e #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_e)) %} - {%- endif %} - - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_0 * dims.ny_0)) %} - {%- endif %} - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny * dims.ny)) %} - {%- endif %} - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_e * dims.ny_e)) %} - {%- endif %} - - // local buffer - {%- set buffer_size = buffer_sizes | sort | last %} - real_t buffer[{{ buffer_size }}]; - - /* go through inputs */ - {%- set i_input = -1 %} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.lbx_0 -%} {#- lbx_0 #} - // lbx_0 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nbx_0 }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbx", buffer); - {%- endif %} - - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.ubx_0 -%} {#- ubx_0 #} - // ubx_0 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nbx_0 }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", buffer); - {%- endif %} - - {%- if dims.np > 0 and simulink_opts.inputs.parameter_traj -%} {#- parameter_traj #} - // parameters - stage-variant !!! - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - // update value of parameters - for (int ii = 0; ii <= N; ii++) - { - for (int jj = 0; jj < {{ dims.np }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{dims.np}}+jj]); - {{ model.name }}_acados_update_params(capsule, ii, buffer, {{ dims.np }}); - } - {%- endif %} - - {% if dims.ny_0 > 0 and simulink_opts.inputs.y_ref_0 %} - // y_ref_0 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.ny_0 }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "yref", (void *) buffer); - {%- endif %} - - {% if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref %} - // y_ref - for stages 1 to N-1 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 1; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.ny }}; jj++) - buffer[jj] = (double)(*in_sign[(ii-1)*{{ dims.ny }}+jj]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, ii, "yref", (void *) buffer); - } - {%- endif %} - - {% if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e %} - // y_ref_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.ny_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "yref", (void *) buffer); - {%- endif %} - - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.lbx -%} {#- lbx #} - // lbx - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 1; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nbx }}; jj++) - buffer[jj] = (double)(*in_sign[(ii-1)*{{ dims.nbx }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "lbx", (void *) buffer); - } - {%- endif %} - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.ubx -%} {#- ubx #} - // ubx - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 1; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nbx }}; jj++) - buffer[jj] = (double)(*in_sign[(ii-1)*{{ dims.nbx }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "ubx", (void *) buffer); - } - {%- endif %} - - - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.lbx_e -%} {#- lbx_e #} - // lbx_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.nbx_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lbx", buffer); - {%- endif %} - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.ubx_e -%} {#- ubx_e #} - // ubx_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.nbx_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ubx", buffer); - {%- endif %} - - - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.lbu -%} {#- lbu #} - // lbu - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nbu }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.nbu }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "lbu", (void *) buffer); - } - {%- endif -%} - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.ubu -%} {#- ubu #} - // ubu - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nbu }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.nbu }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "ubu", (void *) buffer); - } - {%- endif -%} - - {%- if dims.ng > 0 and simulink_opts.inputs.lg -%} {#- lg #} - // lg - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.ng }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.ng }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "lg", (void *) buffer); - } - {%- endif -%} - {%- if dims.ng > 0 and simulink_opts.inputs.ug -%} {#- ug #} - // ug - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.ng }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.ng }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "ug", (void *) buffer); - } - {%- endif -%} - - {%- if dims.nh > 0 and simulink_opts.inputs.lh -%} {#- lh #} - // lh - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nh }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.nh }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "lh", (void *) buffer); - } - {%- endif -%} - {%- if dims.nh > 0 and simulink_opts.inputs.uh -%} {#- uh #} - // uh - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nh }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.nh }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "uh", (void *) buffer); - } - {%- endif -%} - - - {%- if dims.nh_e > 0 and simulink_opts.inputs.lh_e -%} {#- lh_e #} - // lh_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nh_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lh", buffer); - {%- endif -%} - {%- if dims.nh_e > 0 and simulink_opts.inputs.uh_e -%} {#- uh_e #} - // uh_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nh_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uh", buffer); - {%- endif -%} - - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} - // cost_W_0 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.ny_0 * dims.ny_0 }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "W", buffer); - {%- endif %} - - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} - // cost_W - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.ny * dims.ny }}; i++) - buffer[i] = (double)(*in_sign[i]); - - for (int ii = 1; ii < N; ii++) - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, ii, "W", buffer); - {%- endif %} - - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} - // cost_W_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.ny_e * dims.ny_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "W", buffer); - {%- endif %} - - {%- if simulink_opts.inputs.reset_solver %} {#- reset_solver #} - // reset_solver - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - double reset = (double)(*in_sign[0]); - if (reset) - { - {{ model.name }}_acados_reset(capsule, 1); - } - {%- endif %} - - {%- if simulink_opts.inputs.x_init %} {#- x_init #} - // x_init - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 0; ii < {{ dims.N + 1 }}; ii++) - { - for (int jj = 0; jj < {{ dims.nx }}; jj++) - buffer[jj] = (double)(*in_sign[(ii)*{{ dims.nx }}+jj]); - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, ii, "x", (void *) buffer); - } - {%- endif %} - - {%- if simulink_opts.inputs.u_init %} {#- u_init #} - // u_init - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nu }}; jj++) - buffer[jj] = (double)(*in_sign[(ii)*{{ dims.nu }}+jj]); - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, ii, "u", (void *) buffer); - } - {%- endif %} - - /* call solver */ - int rti_phase = 0; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "rti_phase", &rti_phase); - int acados_status = {{ model.name }}_acados_solve(capsule); - - - /* set outputs */ - // assign pointers to output signals - real_t *out_u0, *out_utraj, *out_xtraj, *out_status, *out_sqp_iter, *out_KKT_res, *out_KKT_residuals, *out_x1, *out_cpu_time, *out_cpu_time_sim, *out_cpu_time_qp, *out_cpu_time_lin, *out_cost_value; - int tmp_int; - - {%- set i_output = -1 -%}{# note here i_output is 0-based #} - {%- if dims.nu > 0 and simulink_opts.outputs.u0 == 1 %} - {%- set i_output = i_output + 1 %} - out_u0 = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 0, "u", (void *) out_u0); - {%- endif %} - - {%- if simulink_opts.outputs.utraj == 1 %} - {%- set i_output = i_output + 1 %} - out_utraj = ssGetOutputPortRealSignal(S, {{ i_output }}); - for (int ii = 0; ii < N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, - "u", (void *) (out_utraj + ii * {{ dims.nu }})); - {%- endif %} - - {% if simulink_opts.outputs.xtraj == 1 %} - {%- set i_output = i_output + 1 %} - - out_xtraj = ssGetOutputPortRealSignal(S, {{ i_output }}); - for (int ii = 0; ii < {{ dims.N + 1 }}; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, - "x", (void *) (out_xtraj + ii * {{ dims.nx }})); - {%- endif %} - - {%- if simulink_opts.outputs.solver_status == 1 %} - {%- set i_output = i_output + 1 %} - out_status = ssGetOutputPortRealSignal(S, {{ i_output }}); - *out_status = (real_t) acados_status; - {%- endif %} - - {%- if simulink_opts.outputs.cost_value == 1 %} - {%- set i_output = i_output + 1 %} - out_cost_value = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_eval_cost(capsule->nlp_solver, nlp_in, nlp_out); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "cost_value", (void *) out_cost_value); - {%- endif %} - - {%- if simulink_opts.outputs.KKT_residual == 1 %} - {%- set i_output = i_output + 1 %} - out_KKT_res = ssGetOutputPortRealSignal(S, {{ i_output }}); - *out_KKT_res = (real_t) nlp_out->inf_norm_res; - {%- endif %} - - {%- if simulink_opts.outputs.KKT_residuals == 1 %} - {%- set i_output = i_output + 1 %} - out_KKT_residuals = ssGetOutputPortRealSignal(S, {{ i_output }}); - - {%- if solver_options.nlp_solver_type == "SQP_RTI" %} - ocp_nlp_eval_residuals(capsule->nlp_solver, nlp_in, nlp_out); - {%- endif %} - ocp_nlp_get(nlp_config, capsule->nlp_solver, "res_stat", (void *) &out_KKT_residuals[0]); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "res_eq", (void *) &out_KKT_residuals[1]); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "res_ineq", (void *) &out_KKT_residuals[2]); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "res_comp", (void *) &out_KKT_residuals[3]); - {%- endif %} - - {%- if dims.N > 0 and simulink_opts.outputs.x1 == 1 %} - {%- set i_output = i_output + 1 %} - out_x1 = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 1, "x", (void *) out_x1); - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time == 1 %} - {%- set i_output = i_output + 1 %} - out_cpu_time = ssGetOutputPortRealSignal(S, {{ i_output }}); - // get solution time - ocp_nlp_get(nlp_config, capsule->nlp_solver, "time_tot", (void *) out_cpu_time); - {%- endif -%} - - {%- if simulink_opts.outputs.CPU_time_sim == 1 %} - {%- set i_output = i_output + 1 %} - out_cpu_time_sim = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "time_sim", (void *) out_cpu_time_sim); - {%- endif -%} - - {%- if simulink_opts.outputs.CPU_time_qp == 1 %} - {%- set i_output = i_output + 1 %} - out_cpu_time_qp = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "time_qp", (void *) out_cpu_time_qp); - {%- endif -%} - - {%- if simulink_opts.outputs.CPU_time_lin == 1 %} - {%- set i_output = i_output + 1 %} - out_cpu_time_lin = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "time_lin", (void *) out_cpu_time_lin); - {%- endif -%} - - {%- if simulink_opts.outputs.sqp_iter == 1 %} - {%- set i_output = i_output + 1 %} - out_sqp_iter = ssGetOutputPortRealSignal(S, {{ i_output }}); - // get sqp iter - ocp_nlp_get(nlp_config, capsule->nlp_solver, "sqp_iter", (void *) &tmp_int); - *out_sqp_iter = (real_t) tmp_int; - {%- endif %} - -} - -static void mdlTerminate(SimStruct *S) -{ - {{ model.name }}_solver_capsule *capsule = ssGetUserData(S); - - {{ model.name }}_acados_free(capsule); - {{ model.name }}_acados_free_capsule(capsule); -} - - -#ifdef MATLAB_MEX_FILE -#include "simulink.c" -#else -#include "cg_sfun.h" -#endif diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/main_mex.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/main_mex.in.c deleted file mode 100644 index 851a3cc04f6fd3..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/main_mex.in.c +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -// standard -#include -#include -// acados -#include "acados/utils/print.h" -#include "acados/utils/math.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_solver_{{ model.name }}.h" -// mex -#include "mex.h" - -/* auxilary mex */ -// prints a matrix in column-major format (exponential notation) -void MEX_print_exp_mat(int m, int n, double *A, int lda) -{ - for (int i=0; iN; i++) - { - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x_init); - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0); - } - status = {{ model.name }}_acados_solve(); - ocp_nlp_get(nlp_config, nlp_solver, "time_tot", &elapsed_time); - min_time = MIN(elapsed_time, min_time); - } - - /* print solution and statistics */ - for (int ii = 0; ii <= nlp_dims->N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, "x", &xtraj[ii*{{ dims.nx }}]); - for (int ii = 0; ii < nlp_dims->N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, "u", &utraj[ii*{{ dims.nu }}]); - - mexPrintf("\n--- xtraj ---\n"); - MEX_print_exp_tran_mat( {{ dims.nx }}, {{ dims.N }}+1, xtraj, {{ dims.nx }} ); - mexPrintf("\n--- utraj ---\n"); - MEX_print_exp_tran_mat( {{ dims.nu }}, {{ dims.N }}, utraj, {{ dims.nu }} ); - - mexPrintf("\nsolved ocp %d times, solution printed above\n\n", NTIMINGS); - - if (status == ACADOS_SUCCESS) - mexPrintf("{{ model.name }}_acados_solve(): SUCCESS!\n"); - else - mexPrintf("{{ model.name }}_acados_solve() failed with status %d.\n", status); - - // get solution - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 0, "kkt_norm_inf", &kkt_norm_inf); - ocp_nlp_get(nlp_config, nlp_solver, "sqp_iter", &sqp_iter); - - mexPrintf("\nSolver info:\n"); - mexPrintf(" SQP iterations %2d\n minimum time for 1 solve %f [ms]\n KKT %e\n", - sqp_iter, min_time*1000, kkt_norm_inf); - - // free solver - status = {{ model.name }}_acados_free(); - if (status) - { - mexPrintf("{{ model.name }}_acados_free() returned status %d.\n", status); - } - - return; -} diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_main_mex.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_main_mex.in.m deleted file mode 100644 index d217948456b898..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_main_mex.in.m +++ /dev/null @@ -1,103 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following conditions are met: -% -% 1. Redistributions of source code must retain the above copyright notice, -% this list of conditions and the following disclaimer. -% -% 2. Redistributions in binary form must reproduce the above copyright notice, -% this list of conditions and the following disclaimer in the documentation -% and/or other materials provided with the distribution. -% -% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -% POSSIBILITY OF SUCH DAMAGE.; - -% - -function make_main_mex_{{ model.name }}() - - opts.output_dir = pwd; - - % get acados folder - acados_folder = getenv('ACADOS_INSTALL_DIR'); - - % set paths - acados_include = ['-I' fullfile(acados_folder, 'include')]; - template_lib_include = ['-l' 'acados_solver_{{ model.name }}']; - template_lib_path = ['-L' fullfile(pwd)]; - - acados_lib_path = ['-L' fullfile(acados_folder, 'lib')]; - external_include = ['-I', fullfile(acados_folder, 'external')]; - blasfeo_include = ['-I', fullfile(acados_folder, 'external', 'blasfeo', 'include')]; - hpipm_include = ['-I', fullfile(acados_folder, 'external', 'hpipm', 'include')]; - - mex_names = { ... - 'main_mex_{{ model.name }}' ... - }; - - mex_files = cell(length(mex_names), 1); - for k=1:length(mex_names) - mex_files{k} = fullfile([mex_names{k}, '.c']); - end - - %% octave C flags - if is_octave() - if ~exist(fullfile(opts.output_dir, 'cflags_octave.txt'), 'file') - diary(fullfile(opts.output_dir, 'cflags_octave.txt')); - diary on - mkoctfile -p CFLAGS - diary off - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'r'); - cflags_tmp = fscanf(input_file, '%[^\n]s'); - fclose(input_file); - if ~ismac() - cflags_tmp = [cflags_tmp, ' -std=c99 -fopenmp']; - else - cflags_tmp = [cflags_tmp, ' -std=c99']; - end - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'w'); - fprintf(input_file, '%s', cflags_tmp); - fclose(input_file); - end - % read cflags from file - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'r'); - cflags_tmp = fscanf(input_file, '%[^\n]s'); - fclose(input_file); - setenv('CFLAGS', cflags_tmp); - end - - %% compile mex - for ii=1:length(mex_files) - disp(['compiling ', mex_files{ii}]) - if is_octave() - % mkoctfile -p CFLAGS - mex(acados_include, template_lib_include, external_include, blasfeo_include, hpipm_include,... - acados_lib_path, template_lib_path, '-lacados', '-lhpipm', '-lblasfeo', mex_files{ii}) - else - if ismac() - FLAGS = 'CFLAGS=$CFLAGS -std=c99'; - else - FLAGS = 'CFLAGS=$CFLAGS -std=c99 -fopenmp'; - end - mex(FLAGS, acados_include, template_lib_include, external_include, blasfeo_include, hpipm_include,... - acados_lib_path, template_lib_path, '-lacados', '-lhpipm', '-lblasfeo', mex_files{ii}) - end - end - - -end \ No newline at end of file diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_mex.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_mex.in.m deleted file mode 100644 index 5e358271374ea2..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_mex.in.m +++ /dev/null @@ -1,127 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following conditions are met: -% -% 1. Redistributions of source code must retain the above copyright notice, -% this list of conditions and the following disclaimer. -% -% 2. Redistributions in binary form must reproduce the above copyright notice, -% this list of conditions and the following disclaimer in the documentation -% and/or other materials provided with the distribution. -% -% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -% POSSIBILITY OF SUCH DAMAGE.; - -% - -function make_mex_{{ model.name }}() - - opts.output_dir = pwd; - - % get acados folder - acados_folder = getenv('ACADOS_INSTALL_DIR'); - - % set paths - acados_include = ['-I' fullfile(acados_folder, 'include')]; - template_lib_include = ['-l' 'acados_ocp_solver_{{ model.name }}']; - template_lib_path = ['-L' fullfile(pwd)]; - - acados_lib_path = ['-L' fullfile(acados_folder, 'lib')]; - external_include = ['-I', fullfile(acados_folder, 'external')]; - blasfeo_include = ['-I', fullfile(acados_folder, 'external', 'blasfeo', 'include')]; - hpipm_include = ['-I', fullfile(acados_folder, 'external', 'hpipm', 'include')]; - - % load linking information of compiled acados - link_libs_core_filename = fullfile(acados_folder, 'lib', 'link_libs.json'); - addpath(fullfile(acados_folder, 'external', 'jsonlab')); - link_libs = loadjson(link_libs_core_filename); - - % add necessary link instructs - acados_lib_extra = {}; - lib_names = fieldnames(link_libs); - for idx = 1 : numel(lib_names) - lib_name = lib_names{idx}; - link_arg = link_libs.(lib_name); - if ~isempty(link_arg) - acados_lib_extra = [acados_lib_extra, link_arg]; - end - end - - - mex_include = ['-I', fullfile(acados_folder, 'interfaces', 'acados_matlab_octave')]; - - mex_names = { ... - 'acados_mex_create_{{ model.name }}' ... - 'acados_mex_free_{{ model.name }}' ... - 'acados_mex_solve_{{ model.name }}' ... - 'acados_mex_set_{{ model.name }}' ... - }; - - mex_files = cell(length(mex_names), 1); - for k=1:length(mex_names) - mex_files{k} = fullfile([mex_names{k}, '.c']); - end - - %% octave C flags - if is_octave() - if ~exist(fullfile(opts.output_dir, 'cflags_octave.txt'), 'file') - diary(fullfile(opts.output_dir, 'cflags_octave.txt')); - diary on - mkoctfile -p CFLAGS - diary off - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'r'); - cflags_tmp = fscanf(input_file, '%[^\n]s'); - fclose(input_file); - if ~ismac() - cflags_tmp = [cflags_tmp, ' -std=c99 -fopenmp']; - else - cflags_tmp = [cflags_tmp, ' -std=c99']; - end - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'w'); - fprintf(input_file, '%s', cflags_tmp); - fclose(input_file); - end - % read cflags from file - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'r'); - cflags_tmp = fscanf(input_file, '%[^\n]s'); - fclose(input_file); - setenv('CFLAGS', cflags_tmp); - end - - %% compile mex - for ii=1:length(mex_files) - disp(['compiling ', mex_files{ii}]) - if is_octave() - % mkoctfile -p CFLAGS - mex(acados_include, template_lib_include, external_include, blasfeo_include, hpipm_include,... - template_lib_path, mex_include, acados_lib_path, '-lacados', '-lhpipm', '-lblasfeo',... - acados_lib_extra{:}, mex_files{ii}) - else - if ismac() - FLAGS = 'CFLAGS=$CFLAGS -std=c99'; - else - FLAGS = 'CFLAGS=$CFLAGS -std=c99 -fopenmp'; - end - mex(FLAGS, acados_include, template_lib_include, external_include, blasfeo_include, hpipm_include,... - template_lib_path, mex_include, acados_lib_path, '-lacados', '-lhpipm', '-lblasfeo',... - acados_lib_extra{:}, mex_files{ii}) - end - end - - -end \ No newline at end of file diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun.in.m deleted file mode 100644 index 5d74c523f88bd0..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun.in.m +++ /dev/null @@ -1,432 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following conditions are met: -% -% 1. Redistributions of source code must retain the above copyright notice, -% this list of conditions and the following disclaimer. -% -% 2. Redistributions in binary form must reproduce the above copyright notice, -% this list of conditions and the following disclaimer in the documentation -% and/or other materials provided with the distribution. -% -% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -% POSSIBILITY OF SUCH DAMAGE.; - -% - -SOURCES = { ... - {%- if solver_options.integrator_type == 'ERK' %} - '{{ model.name }}_model/{{ model.name }}_expl_ode_fun.c', ... - '{{ model.name }}_model/{{ model.name }}_expl_vde_forw.c',... - {%- if solver_options.hessian_approx == 'EXACT' %} - '{{ model.name }}_model/{{ model.name }}_expl_ode_hess.c',... - {%- endif %} - {%- elif solver_options.integrator_type == "IRK" %} - '{{ model.name }}_model/{{ model.name }}_impl_dae_fun.c', ... - '{{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c', ... - '{{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c', ... - {%- if solver_options.hessian_approx == 'EXACT' %} - '{{ model.name }}_model/{{ model.name }}_impl_dae_hess.c',... - {%- endif %} - {%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c',... - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c',... - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c',... - {% if model.gnsf.nontrivial_f_LO == 1 %} - '{{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c',... - {%- endif %} - {%- endif %} - '{{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c',... - {%- elif solver_options.integrator_type == "DISCRETE" %} - '{{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c',... - '{{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c',... - {%- if solver_options.hessian_approx == "EXACT" %} - '{{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c',... - {%- endif %} - {%- endif %} - {%- if cost.cost_type_0 == "NONLINEAR_LS" %} - '{{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c',... - {%- elif cost.cost_type_0 == "EXTERNAL" %} - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c',... - {%- endif %} - - {%- if cost.cost_type == "NONLINEAR_LS" %} - '{{ model.name }}_cost/{{ model.name }}_cost_y_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_hess.c',... - {%- elif cost.cost_type == "EXTERNAL" %} - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c',... - {%- endif %} - {%- if cost.cost_type_e == "NONLINEAR_LS" %} - '{{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c',... - {%- elif cost.cost_type_e == "EXTERNAL" %} - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c',... - {%- endif %} - {%- if constraints.constr_type == "BGH" and dims.nh > 0 %} - '{{ model.name }}_constraints/{{ model.name }}_constr_h_fun.c', ... - '{{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c', ... - '{{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.c', ... - {%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %} - '{{ model.name }}_constraints/{{ model.name }}_phi_constraint.c', ... - {%- endif %} - {%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - '{{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.c', ... - '{{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c', ... - '{{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.c', ... - {%- elif constraints.constr_type_e == "BGP" and dims.nphi_e > 0 %} - '{{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.c', ... - {%- endif %} - 'acados_solver_sfunction_{{ model.name }}.c', ... - 'acados_solver_{{ model.name }}.c' - }; - -INC_PATH = '{{ acados_include_path }}'; - -INCS = {['-I', fullfile(INC_PATH, 'blasfeo', 'include')], ... - ['-I', fullfile(INC_PATH, 'hpipm', 'include')], ... - ['-I', fullfile(INC_PATH, 'acados')], ... - ['-I', fullfile(INC_PATH)]}; - -{% if solver_options.qp_solver is containing("QPOASES") %} -INCS{end+1} = ['-I', fullfile(INC_PATH, 'qpOASES_e')]; -{% endif %} - -CFLAGS = 'CFLAGS=$CFLAGS'; -LDFLAGS = 'LDFLAGS=$LDFLAGS'; -COMPFLAGS = 'COMPFLAGS=$COMPFLAGS'; -COMPDEFINES = 'COMPDEFINES=$COMPDEFINES'; - -{% if solver_options.qp_solver is containing("QPOASES") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_QPOASES ' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_QPOASES ' ]; -{%- elif solver_options.qp_solver is containing("OSQP") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_OSQP ' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_OSQP ' ]; -{%- elif solver_options.qp_solver is containing("QPDUNES") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_QPDUNES ' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_QPDUNES ' ]; -{%- elif solver_options.qp_solver is containing("DAQP") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_DAQP' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_DAQP' ]; -{%- elif solver_options.qp_solver is containing("HPMPC") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_HPMPC ' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_HPMPC ' ]; -{% endif %} - -LIB_PATH = ['-L', fullfile('{{ acados_lib_path }}')]; - -LIBS = {'-lacados', '-lhpipm', '-lblasfeo'}; - -% acados linking libraries and flags -{%- if acados_link_libs and os and os == "pc" %} -LDFLAGS = [LDFLAGS ' {{ acados_link_libs.openmp }}']; -COMPFLAGS = [COMPFLAGS ' {{ acados_link_libs.openmp }}']; -LIBS{end+1} = '{{ acados_link_libs.qpoases }}'; -LIBS{end+1} = '{{ acados_link_libs.hpmpc }}'; -LIBS{end+1} = '{{ acados_link_libs.osqp }}'; -{%- else %} - {% if solver_options.qp_solver is containing("QPOASES") %} -LIBS{end+1} = '-lqpOASES_e'; - {% endif %} - {% if solver_options.qp_solver is containing("DAQP") %} -LIBS{end+1} = '-ldaqp'; - {% endif %} -{%- endif %} - - -try - % mex('-v', '-O', CFLAGS, LDFLAGS, COMPFLAGS, COMPDEFINES, INCS{:}, ... - mex('-O', CFLAGS, LDFLAGS, COMPFLAGS, COMPDEFINES, INCS{:}, ... - LIB_PATH, LIBS{:}, SOURCES{:}, ... - '-output', 'acados_solver_sfunction_{{ model.name }}' ); -catch exception - disp('make_sfun failed with the following exception:') - disp(exception); - disp('Try adding -v to the mex command above to get more information.') - keyboard -end - -fprintf( [ '\n\nSuccessfully created sfunction:\nacados_solver_sfunction_{{ model.name }}', '.', ... - eval('mexext')] ); - - -%% print note on usage of s-function, and create I/O port names vectors -fprintf('\n\nNote: Usage of Sfunction is as follows:\n') -input_note = 'Inputs are:\n'; -i_in = 1; - -global sfun_input_names -sfun_input_names = {}; - -{%- if dims.nbx_0 > 0 and simulink_opts.inputs.lbx_0 -%} {#- lbx_0 #} -input_note = strcat(input_note, num2str(i_in), ') lbx_0 - lower bound on x for stage 0,',... - ' size [{{ dims.nbx_0 }}]\n '); -sfun_input_names = [sfun_input_names; 'lbx_0 [{{ dims.nbx_0 }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nbx_0 > 0 and simulink_opts.inputs.ubx_0 -%} {#- ubx_0 #} -input_note = strcat(input_note, num2str(i_in), ') ubx_0 - upper bound on x for stage 0,',... - ' size [{{ dims.nbx_0 }}]\n '); -sfun_input_names = [sfun_input_names; 'ubx_0 [{{ dims.nbx_0 }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.np > 0 and simulink_opts.inputs.parameter_traj -%} {#- parameter_traj #} -input_note = strcat(input_note, num2str(i_in), ') parameters - concatenated for all shooting nodes 0 to N,',... - ' size [{{ (dims.N+1)*dims.np }}]\n '); -sfun_input_names = [sfun_input_names; 'parameter_traj [{{ (dims.N+1)*dims.np }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny_0 > 0 and simulink_opts.inputs.y_ref_0 %} -input_note = strcat(input_note, num2str(i_in), ') y_ref_0, size [{{ dims.ny_0 }}]\n '); -sfun_input_names = [sfun_input_names; 'y_ref_0 [{{ dims.ny_0 }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref %} -input_note = strcat(input_note, num2str(i_in), ') y_ref - concatenated for shooting nodes 1 to N-1,',... - ' size [{{ (dims.N-1) * dims.ny }}]\n '); -sfun_input_names = [sfun_input_names; 'y_ref [{{ (dims.N-1) * dims.ny }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e %} -input_note = strcat(input_note, num2str(i_in), ') y_ref_e, size [{{ dims.ny_e }}]\n '); -sfun_input_names = [sfun_input_names; 'y_ref_e [{{ dims.ny_e }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.lbx -%} {#- lbx #} -input_note = strcat(input_note, num2str(i_in), ') lbx for shooting nodes 1 to N-1, size [{{ (dims.N-1) * dims.nbx }}]\n '); -sfun_input_names = [sfun_input_names; 'lbx [{{ (dims.N-1) * dims.nbx }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.ubx -%} {#- ubx #} -input_note = strcat(input_note, num2str(i_in), ') ubx for shooting nodes 1 to N-1, size [{{ (dims.N-1) * dims.nbx }}]\n '); -sfun_input_names = [sfun_input_names; 'ubx [{{ (dims.N-1) * dims.nbx }}]']; -i_in = i_in + 1; -{%- endif %} - - -{%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.lbx_e -%} {#- lbx_e #} -input_note = strcat(input_note, num2str(i_in), ') lbx_e (lbx at shooting node N), size [{{ dims.nbx_e }}]\n '); -sfun_input_names = [sfun_input_names; 'lbx_e [{{ dims.nbx_e }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.ubx_e -%} {#- ubx_e #} -input_note = strcat(input_note, num2str(i_in), ') ubx_e (ubx at shooting node N), size [{{ dims.nbx_e }}]\n '); -sfun_input_names = [sfun_input_names; 'ubx_e [{{ dims.nbx_e }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.lbu -%} {#- lbu #} -input_note = strcat(input_note, num2str(i_in), ') lbu for shooting nodes 0 to N-1, size [{{ dims.N*dims.nbu }}]\n '); -sfun_input_names = [sfun_input_names; 'lbu [{{ dims.N*dims.nbu }}]']; -i_in = i_in + 1; -{%- endif -%} -{%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.ubu -%} {#- ubu #} -input_note = strcat(input_note, num2str(i_in), ') ubu for shooting nodes 0 to N-1, size [{{ dims.N*dims.nbu }}]\n '); -sfun_input_names = [sfun_input_names; 'ubu [{{ dims.N*dims.nbu }}]']; -i_in = i_in + 1; -{%- endif -%} - -{%- if dims.ng > 0 and simulink_opts.inputs.lg -%} {#- lg #} -input_note = strcat(input_note, num2str(i_in), ') lg for shooting nodes 0 to N-1, size [{{ dims.N*dims.ng }}]\n '); -sfun_input_names = [sfun_input_names; 'lg [{{ dims.N*dims.ng }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.ng > 0 and simulink_opts.inputs.ug -%} {#- ug #} -input_note = strcat(input_note, num2str(i_in), ') ug for shooting nodes 0 to N-1, size [{{ dims.N*dims.ng }}]\n '); -sfun_input_names = [sfun_input_names; 'ug [{{ dims.N*dims.ng }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nh > 0 and simulink_opts.inputs.lh -%} {#- lh #} -input_note = strcat(input_note, num2str(i_in), ') lh for shooting nodes 0 to N-1, size [{{ dims.N*dims.nh }}]\n '); -sfun_input_names = [sfun_input_names; 'lh [{{ dims.N*dims.nh }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.nh > 0 and simulink_opts.inputs.uh -%} {#- uh #} -input_note = strcat(input_note, num2str(i_in), ') uh for shooting nodes 0 to N-1, size [{{ dims.N*dims.nh }}]\n '); -sfun_input_names = [sfun_input_names; 'uh [{{ dims.N*dims.nh }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nh_e > 0 and simulink_opts.inputs.lh_e -%} {#- lh_e #} -input_note = strcat(input_note, num2str(i_in), ') lh_e, size [{{ dims.nh_e }}]\n '); -sfun_input_names = [sfun_input_names; 'lh_e [{{ dims.nh_e }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.nh_e > 0 and simulink_opts.inputs.uh_e -%} {#- uh_e #} -input_note = strcat(input_note, num2str(i_in), ') uh_e, size [{{ dims.nh_e }}]\n '); -sfun_input_names = [sfun_input_names; 'uh_e [{{ dims.nh_e }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} -input_note = strcat(input_note, num2str(i_in), ') cost_W_0 in column-major format, size [{{ dims.ny_0 * dims.ny_0 }}]\n '); -sfun_input_names = [sfun_input_names; 'cost_W_0 [{{ dims.ny_0 * dims.ny_0 }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} -input_note = strcat(input_note, num2str(i_in), ') cost_W in column-major format, that is set for all intermediate shooting nodes: 1 to N-1, size [{{ dims.ny * dims.ny }}]\n '); -sfun_input_names = [sfun_input_names; 'cost_W [{{ dims.ny * dims.ny }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} -input_note = strcat(input_note, num2str(i_in), ') cost_W_e in column-major format, size [{{ dims.ny_e * dims.ny_e }}]\n '); -sfun_input_names = [sfun_input_names; 'cost_W_e [{{ dims.ny_e * dims.ny_e }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if simulink_opts.inputs.reset_solver %} {#- reset_solver #} -input_note = strcat(input_note, num2str(i_in), ') reset_solver determines if iterate is set to all zeros before other initializations (x_init, u_init) are set and before solver is called, size [1]\n '); -sfun_input_names = [sfun_input_names; 'reset_solver [1]']; -i_in = i_in + 1; -{%- endif %} - -{%- if simulink_opts.inputs.x_init %} {#- x_init #} -input_note = strcat(input_note, num2str(i_in), ') initialization of x for all shooting nodes, size [{{ dims.nx * (dims.N+1) }}]\n '); -sfun_input_names = [sfun_input_names; 'x_init [{{ dims.nx * (dims.N+1) }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if simulink_opts.inputs.u_init %} {#- u_init #} -input_note = strcat(input_note, num2str(i_in), ') initialization of u for shooting nodes 0 to N-1, size [{{ dims.nu * (dims.N) }}]\n '); -sfun_input_names = [sfun_input_names; 'u_init [{{ dims.nu * (dims.N) }}]']; -i_in = i_in + 1; -{%- endif %} - -fprintf(input_note) - -disp(' ') - -output_note = 'Outputs are:\n'; -i_out = 0; - -global sfun_output_names -sfun_output_names = {}; - -{%- if dims.nu > 0 and simulink_opts.outputs.u0 == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') u0, control input at node 0, size [{{ dims.nu }}]\n '); -sfun_output_names = [sfun_output_names; 'u0 [{{ dims.nu }}]']; -{%- endif %} - -{%- if simulink_opts.outputs.utraj == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') utraj, control input concatenated for nodes 0 to N-1, size [{{ dims.nu * dims.N }}]\n '); -sfun_output_names = [sfun_output_names; 'utraj [{{ dims.nu * dims.N }}]']; -{%- endif %} - -{%- if simulink_opts.outputs.xtraj == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') xtraj, state concatenated for nodes 0 to N, size [{{ dims.nx * (dims.N + 1) }}]\n '); -sfun_output_names = [sfun_output_names; 'xtraj [{{ dims.nx * (dims.N + 1) }}]']; -{%- endif %} - -{%- if simulink_opts.outputs.solver_status == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') acados solver status (0 = SUCCESS)\n '); -sfun_output_names = [sfun_output_names; 'solver_status']; -{%- endif %} - -{%- if simulink_opts.outputs.cost_value == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') cost function value\n '); -sfun_output_names = [sfun_output_names; 'cost_value']; -{%- endif %} - - -{%- if simulink_opts.outputs.KKT_residual == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') KKT residual\n '); -sfun_output_names = [sfun_output_names; 'KKT_residual']; -{%- endif %} - -{%- if simulink_opts.outputs.KKT_residuals == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') KKT residuals, size [4] (stat, eq, ineq, comp)\n '); -sfun_output_names = [sfun_output_names; 'KKT_residuals [4]']; -{%- endif %} - -{%- if dims.N > 0 and simulink_opts.outputs.x1 == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') x1, state at node 1\n '); -sfun_output_names = [sfun_output_names; 'x1']; -{%- endif %} - -{%- if simulink_opts.outputs.CPU_time == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') CPU time\n '); -sfun_output_names = [sfun_output_names; 'CPU_time']; -{%- endif %} - -{%- if simulink_opts.outputs.CPU_time_sim == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') CPU time integrator\n '); -sfun_output_names = [sfun_output_names; 'CPU_time_sim']; -{%- endif %} - -{%- if simulink_opts.outputs.CPU_time_qp == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') CPU time QP solution\n '); -sfun_output_names = [sfun_output_names; 'CPU_time_qp']; -{%- endif %} - -{%- if simulink_opts.outputs.CPU_time_lin == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') CPU time linearization (including integrator)\n '); -sfun_output_names = [sfun_output_names; 'CPU_time_lin']; -{%- endif %} - -{%- if simulink_opts.outputs.sqp_iter == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') SQP iterations\n '); -sfun_output_names = [sfun_output_names; 'sqp_iter']; -{%- endif %} - -fprintf(output_note) - -% The mask drawing command is: -% --- -% global sfun_input_names sfun_output_names -% for i = 1:length(sfun_input_names) -% port_label('input', i, sfun_input_names{i}) -% end -% for i = 1:length(sfun_output_names) -% port_label('output', i, sfun_output_names{i}) -% end -% --- -% It can be used by copying it in sfunction/Mask/Edit mask/Icon drawing commands -% (you can access it wirth ctrl+M on the s-function) \ No newline at end of file diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun_sim.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun_sim.in.m deleted file mode 100644 index e4c32a8c19a9d2..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun_sim.in.m +++ /dev/null @@ -1,137 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following conditions are met: -% -% 1. Redistributions of source code must retain the above copyright notice, -% this list of conditions and the following disclaimer. -% -% 2. Redistributions in binary form must reproduce the above copyright notice, -% this list of conditions and the following disclaimer in the documentation -% and/or other materials provided with the distribution. -% -% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -% POSSIBILITY OF SUCH DAMAGE.; - -% - -SOURCES = [ 'acados_sim_solver_sfunction_{{ model.name }}.c ', ... - 'acados_sim_solver_{{ model.name }}.c ', ... - {%- if solver_options.integrator_type == 'ERK' %} - '{{ model.name }}_model/{{ model.name }}_expl_ode_fun.c ',... - '{{ model.name }}_model/{{ model.name }}_expl_vde_forw.c ',... - '{{ model.name }}_model/{{ model.name }}_expl_vde_adj.c ',... - {%- if solver_options.hessian_approx == 'EXACT' %} - '{{ model.name }}_model/{{ model.name }}_expl_ode_hess.c ',... - {%- endif %} - {%- elif solver_options.integrator_type == "IRK" %} - '{{ model.name }}_model/{{ model.name }}_impl_dae_fun.c ', ... - '{{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c ', ... - '{{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c ', ... - {%- if solver_options.hessian_approx == 'EXACT' %} - '{{ model.name }}_model/{{ model.name }}_impl_dae_hess.c ',... - {%- endif %} - {%- elif solver_options.integrator_type == "GNSF" %} - {%- if model.gnsf.purely_linear != 1 %} - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c ',... - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c ',... - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c ',... - {%- if model.gnsf.nontrivial_f_LO == 1 %} - '{{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c ',... - {%- endif %} - {%- endif %} - '{{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c ',... - {%- endif %} - ]; - -INC_PATH = '{{ acados_include_path }}'; - -INCS = [ ' -I', fullfile(INC_PATH, 'blasfeo', 'include'), ... - ' -I', fullfile(INC_PATH, 'hpipm', 'include'), ... - ' -I', INC_PATH, ' -I', fullfile(INC_PATH, 'acados'), ' ']; - -CFLAGS = ' -O'; - -LIB_PATH = '{{ acados_lib_path }}'; - -LIBS = '-lacados -lblasfeo -lhpipm'; - -try - % eval( [ 'mex -v -output acados_sim_solver_sfunction_{{ model.name }} ', ... - eval( [ 'mex -output acados_sim_solver_sfunction_{{ model.name }} ', ... - CFLAGS, INCS, ' ', SOURCES, ' -L', LIB_PATH, ' ', LIBS ]); - -catch exception - disp('make_sfun failed with the following exception:') - disp(exception); - disp('Try adding -v to the mex command above to get more information.') - keyboard -end - - -fprintf( [ '\n\nSuccessfully created sfunction:\nacados_sim_solver_sfunction_{{ model.name }}', '.', ... - eval('mexext')] ); - - -global sfun_sim_input_names -sfun_sim_input_names = {}; - -%% print note on usage of s-function -fprintf('\n\nNote: Usage of Sfunction is as follows:\n') -input_note = 'Inputs are:\n1) x0, initial state, size [{{ dims.nx }}]\n '; -i_in = 2; -sfun_sim_input_names = [sfun_sim_input_names; 'x0 [{{ dims.nx }}]']; - -{%- if dims.nu > 0 %} -input_note = strcat(input_note, num2str(i_in), ') u, size [{{ dims.nu }}]\n '); -i_in = i_in + 1; -sfun_sim_input_names = [sfun_sim_input_names; 'u [{{ dims.nu }}]']; -{%- endif %} - -{%- if dims.np > 0 %} -input_note = strcat(input_note, num2str(i_in), ') parameters, size [{{ dims.np }}]\n '); -i_in = i_in + 1; -sfun_sim_input_names = [sfun_sim_input_names; 'p [{{ dims.np }}]']; -{%- endif %} - - -fprintf(input_note) - -disp(' ') - -global sfun_sim_output_names -sfun_sim_output_names = {}; - -output_note = strcat('Outputs are:\n', ... - '1) x1 - simulated state, size [{{ dims.nx }}]\n'); -sfun_sim_output_names = [sfun_sim_output_names; 'x1 [{{ dims.nx }}]']; - -fprintf(output_note) - - -% The mask drawing command is: -% --- -% global sfun_sim_input_names sfun_sim_output_names -% for i = 1:length(sfun_sim_input_names) -% port_label('input', i, sfun_sim_input_names{i}) -% end -% for i = 1:length(sfun_sim_output_names) -% port_label('output', i, sfun_sim_output_names{i}) -% end -% --- -% It can be used by copying it in sfunction/Mask/Edit mask/Icon drawing commands -% (you can access it wirth ctrl+M on the s-function) \ No newline at end of file diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/mex_solver.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/mex_solver.in.m deleted file mode 100644 index 374321283099bd..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/mex_solver.in.m +++ /dev/null @@ -1,270 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following conditions are met: -% -% 1. Redistributions of source code must retain the above copyright notice, -% this list of conditions and the following disclaimer. -% -% 2. Redistributions in binary form must reproduce the above copyright notice, -% this list of conditions and the following disclaimer in the documentation -% and/or other materials provided with the distribution. -% -% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -% POSSIBILITY OF SUCH DAMAGE.; - -% - -classdef {{ model.name }}_mex_solver < handle - - properties - C_ocp - C_ocp_ext_fun - cost_ext_fun_type - cost_ext_fun_type_e - N - name - code_gen_dir - end % properties - - - - methods - - % constructor - function obj = {{ model.name }}_mex_solver() - make_mex_{{ model.name }}(); - [obj.C_ocp, obj.C_ocp_ext_fun] = acados_mex_create_{{ model.name }}(); - % to have path to destructor when changing directory - addpath('.') - obj.cost_ext_fun_type = '{{ cost.cost_ext_fun_type }}'; - obj.cost_ext_fun_type_e = '{{ cost.cost_ext_fun_type_e }}'; - obj.N = {{ dims.N }}; - obj.name = '{{ model.name }}'; - obj.code_gen_dir = pwd(); - end - - % destructor - function delete(obj) - disp("delete template..."); - return_dir = pwd(); - cd(obj.code_gen_dir); - if ~isempty(obj.C_ocp) - acados_mex_free_{{ model.name }}(obj.C_ocp); - end - cd(return_dir); - disp("done."); - end - - % solve - function solve(obj) - acados_mex_solve_{{ model.name }}(obj.C_ocp); - end - - % set -- borrowed from MEX interface - function set(varargin) - obj = varargin{1}; - field = varargin{2}; - value = varargin{3}; - if ~isa(field, 'char') - error('field must be a char vector, use '' '''); - end - if nargin==3 - acados_mex_set_{{ model.name }}(obj.cost_ext_fun_type, obj.cost_ext_fun_type_e, obj.C_ocp, obj.C_ocp_ext_fun, field, value); - elseif nargin==4 - stage = varargin{4}; - acados_mex_set_{{ model.name }}(obj.cost_ext_fun_type, obj.cost_ext_fun_type_e, obj.C_ocp, obj.C_ocp_ext_fun, field, value, stage); - else - disp('acados_ocp.set: wrong number of input arguments (2 or 3 allowed)'); - end - end - - function value = get_cost(obj) - value = ocp_get_cost(obj.C_ocp); - end - - % get -- borrowed from MEX interface - function value = get(varargin) - % usage: - % obj.get(field, value, [stage]) - obj = varargin{1}; - field = varargin{2}; - if any(strfind('sens', field)) - error('field sens* (sensitivities of optimal solution) not yet supported for templated MEX.') - end - if ~isa(field, 'char') - error('field must be a char vector, use '' '''); - end - - if nargin==2 - value = ocp_get(obj.C_ocp, field); - elseif nargin==3 - stage = varargin{3}; - value = ocp_get(obj.C_ocp, field, stage); - else - disp('acados_ocp.get: wrong number of input arguments (1 or 2 allowed)'); - end - end - - - function [] = store_iterate(varargin) - %%% Stores the current iterate of the ocp solver in a json file. - %%% param1: filename: if not set, use model_name + timestamp + '.json' - %%% param2: overwrite: if false and filename exists add timestamp to filename - - obj = varargin{1}; - filename = ''; - overwrite = false; - - if nargin>=2 - filename = varargin{2}; - if ~isa(filename, 'char') - error('filename must be a char vector, use '' '''); - end - end - - if nargin==3 - overwrite = varargin{3}; - end - - if nargin > 3 - disp('acados_ocp.get: wrong number of input arguments (1 or 2 allowed)'); - end - - if strcmp(filename,'') - filename = [obj.name '_iterate.json']; - end - if ~overwrite - % append timestamp - if exist(filename, 'file') - filename = filename(1:end-5); - filename = [filename '_' datestr(now,'yyyy-mm-dd-HH:MM:SS') '.json']; - end - end - filename = fullfile(pwd, filename); - - % get iterate: - solution = struct(); - for i=0:obj.N - solution.(['x_' num2str(i)]) = obj.get('x', i); - solution.(['lam_' num2str(i)]) = obj.get('lam', i); - solution.(['t_' num2str(i)]) = obj.get('t', i); - solution.(['sl_' num2str(i)]) = obj.get('sl', i); - solution.(['su_' num2str(i)]) = obj.get('su', i); - end - for i=0:obj.N-1 - solution.(['z_' num2str(i)]) = obj.get('z', i); - solution.(['u_' num2str(i)]) = obj.get('u', i); - solution.(['pi_' num2str(i)]) = obj.get('pi', i); - end - - acados_folder = getenv('ACADOS_INSTALL_DIR'); - addpath(fullfile(acados_folder, 'external', 'jsonlab')); - savejson('', solution, filename); - - json_string = savejson('', solution, 'ForceRootName', 0); - - fid = fopen(filename, 'w'); - if fid == -1, error('store_iterate: Cannot create JSON file'); end - fwrite(fid, json_string, 'char'); - fclose(fid); - - disp(['stored current iterate in ' filename]); - end - - - function [] = load_iterate(obj, filename) - %%% Loads the iterate stored in json file with filename into the ocp solver. - acados_folder = getenv('ACADOS_INSTALL_DIR'); - addpath(fullfile(acados_folder, 'external', 'jsonlab')); - filename = fullfile(pwd, filename); - - if ~exist(filename, 'file') - error(['load_iterate: failed, file does not exist: ' filename]) - end - - solution = loadjson(filename); - keys = fieldnames(solution); - - for k = 1:numel(keys) - key = keys{k}; - key_parts = strsplit(key, '_'); - field = key_parts{1}; - stage = key_parts{2}; - - val = solution.(key); - - % check if array is empty (can happen for z) - if numel(val) > 0 - obj.set(field, val, str2num(stage)) - end - end - end - - - % print - function print(varargin) - if nargin < 2 - field = 'stat'; - else - field = varargin{2}; - end - - obj = varargin{1}; - - if strcmp(field, 'stat') - stat = obj.get('stat'); - {%- if solver_options.nlp_solver_type == "SQP" %} - fprintf('\niter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha'); - if size(stat,2)>8 - fprintf('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp'); - end - fprintf('\n'); - for jj=1:size(stat,1) - fprintf('%d\t%e\t%e\t%e\t%e\t%d\t%d\t%e', stat(jj,1), stat(jj,2), stat(jj,3), stat(jj,4), stat(jj,5), stat(jj,6), stat(jj,7), stat(jj, 8)); - if size(stat,2)>8 - fprintf('\t%e\t%e\t%e\t%e', stat(jj,9), stat(jj,10), stat(jj,11), stat(jj,12)); - end - fprintf('\n'); - end - fprintf('\n'); - {%- else %} - fprintf('\niter\tqp_status\tqp_iter'); - if size(stat,2)>3 - fprintf('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp'); - end - fprintf('\n'); - for jj=1:size(stat,1) - fprintf('%d\t%d\t\t%d', stat(jj,1), stat(jj,2), stat(jj,3)); - if size(stat,2)>3 - fprintf('\t%e\t%e\t%e\t%e', stat(jj,4), stat(jj,5), stat(jj,6), stat(jj,7)); - end - fprintf('\n'); - end - {% endif %} - - else - fprintf('unsupported field in function print of acados_ocp.print, got %s', field); - keyboard - end - - end - - end % methods - -end % class - diff --git a/third_party/acados/acados_template/c_templates_tera/model.in.h b/third_party/acados/acados_template/c_templates_tera/model.in.h deleted file mode 100644 index e5059df9ffa90b..00000000000000 --- a/third_party/acados/acados_template/c_templates_tera/model.in.h +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -#ifndef {{ model.name }}_MODEL -#define {{ model.name }}_MODEL - -#ifdef __cplusplus -extern "C" { -#endif - -{%- if solver_options.hessian_approx %} - {%- set hessian_approx = solver_options.hessian_approx %} -{%- elif solver_options.sens_hess %} - {%- set hessian_approx = "EXACT" %} -{%- else %} - {%- set hessian_approx = "GAUSS_NEWTON" %} -{%- endif %} - -{% if solver_options.integrator_type == "IRK" or solver_options.integrator_type == "LIFTED_IRK" %} - {% if model.dyn_ext_fun_type == "casadi" %} -// implicit ODE: function -int {{ model.name }}_impl_dae_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_fun_sparsity_in(int); -const int *{{ model.name }}_impl_dae_fun_sparsity_out(int); -int {{ model.name }}_impl_dae_fun_n_in(void); -int {{ model.name }}_impl_dae_fun_n_out(void); - -// implicit ODE: function + jacobians -int {{ model.name }}_impl_dae_fun_jac_x_xdot_z(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_z_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_in(int); -const int *{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_out(int); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_in(void); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_out(void); - -// implicit ODE: jacobians only -int {{ model.name }}_impl_dae_jac_x_xdot_u_z(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_jac_x_xdot_u_z_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_in(int); -const int *{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_out(int); -int {{ model.name }}_impl_dae_jac_x_xdot_u_z_n_in(void); -int {{ model.name }}_impl_dae_jac_x_xdot_u_z_n_out(void); - -// implicit ODE - for lifted_irk -int {{ model.name }}_impl_dae_fun_jac_x_xdot_u(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_u_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_fun_jac_x_xdot_u_sparsity_in(int); -const int *{{ model.name }}_impl_dae_fun_jac_x_xdot_u_sparsity_out(int); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_u_n_in(void); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_u_n_out(void); - - {%- if hessian_approx == "EXACT" %} -// implicit ODE - hessian -int {{ model.name }}_impl_dae_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_hess_sparsity_in(int); -const int *{{ model.name }}_impl_dae_hess_sparsity_out(int); -int {{ model.name }}_impl_dae_hess_n_in(void); -int {{ model.name }}_impl_dae_hess_n_out(void); - {% endif %} - {% else %}{# ext_fun_type #} - {%- if hessian_approx == "EXACT" %} -int {{ model.dyn_impl_dae_hess }}(void **, void **, void *); - {% endif %} -int {{ model.dyn_impl_dae_fun_jac }}(void **, void **, void *); -int {{ model.dyn_impl_dae_jac }}(void **, void **, void *); -int {{ model.dyn_impl_dae_fun }}(void **, void **, void *); - {% endif %}{# ext_fun_type #} - -{% elif solver_options.integrator_type == "GNSF" %} -/* GNSF Functions */ - {% if model.gnsf.purely_linear != 1 %} -// phi_fun -int {{ model.name }}_gnsf_phi_fun(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_phi_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_phi_fun_sparsity_in(int); -const int *{{ model.name }}_gnsf_phi_fun_sparsity_out(int); -int {{ model.name }}_gnsf_phi_fun_n_in(void); -int {{ model.name }}_gnsf_phi_fun_n_out(void); - -// phi_fun_jac_y -int {{ model.name }}_gnsf_phi_fun_jac_y(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_phi_fun_jac_y_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_in(int); -const int *{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_out(int); -int {{ model.name }}_gnsf_phi_fun_jac_y_n_in(void); -int {{ model.name }}_gnsf_phi_fun_jac_y_n_out(void); - -// phi_jac_y_uhat -int {{ model.name }}_gnsf_phi_jac_y_uhat(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_phi_jac_y_uhat_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_in(int); -const int *{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_out(int); -int {{ model.name }}_gnsf_phi_jac_y_uhat_n_in(void); -int {{ model.name }}_gnsf_phi_jac_y_uhat_n_out(void); - {% if model.gnsf.nontrivial_f_LO == 1 %} -// f_lo_fun_jac_x1k1uz -int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_in(int); -const int *{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out(int); -int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in(void); -int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out(void); - {%- endif %} - {%- endif %} -// used to import model matrices -int {{ model.name }}_gnsf_get_matrices_fun(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_get_matrices_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_get_matrices_fun_sparsity_in(int); -const int *{{ model.name }}_gnsf_get_matrices_fun_sparsity_out(int); -int {{ model.name }}_gnsf_get_matrices_fun_n_in(void); -int {{ model.name }}_gnsf_get_matrices_fun_n_out(void); - -{% elif solver_options.integrator_type == "ERK" %} -/* explicit ODE */ - -// explicit ODE -int {{ model.name }}_expl_ode_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_expl_ode_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_expl_ode_fun_sparsity_in(int); -const int *{{ model.name }}_expl_ode_fun_sparsity_out(int); -int {{ model.name }}_expl_ode_fun_n_in(void); -int {{ model.name }}_expl_ode_fun_n_out(void); - -// explicit forward VDE -int {{ model.name }}_expl_vde_forw(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_expl_vde_forw_work(int *, int *, int *, int *); -const int *{{ model.name }}_expl_vde_forw_sparsity_in(int); -const int *{{ model.name }}_expl_vde_forw_sparsity_out(int); -int {{ model.name }}_expl_vde_forw_n_in(void); -int {{ model.name }}_expl_vde_forw_n_out(void); - -// explicit adjoint VDE -int {{ model.name }}_expl_vde_adj(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_expl_vde_adj_work(int *, int *, int *, int *); -const int *{{ model.name }}_expl_vde_adj_sparsity_in(int); -const int *{{ model.name }}_expl_vde_adj_sparsity_out(int); -int {{ model.name }}_expl_vde_adj_n_in(void); -int {{ model.name }}_expl_vde_adj_n_out(void); - -{%- if hessian_approx == "EXACT" %} -int {{ model.name }}_expl_ode_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_expl_ode_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_expl_ode_hess_sparsity_in(int); -const int *{{ model.name }}_expl_ode_hess_sparsity_out(int); -int {{ model.name }}_expl_ode_hess_n_in(void); -int {{ model.name }}_expl_ode_hess_n_out(void); -{%- endif %} - -{% elif solver_options.integrator_type == "DISCRETE" %} - -{% if model.dyn_ext_fun_type == "casadi" %} -int {{ model.name }}_dyn_disc_phi_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_dyn_disc_phi_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_dyn_disc_phi_fun_sparsity_in(int); -const int *{{ model.name }}_dyn_disc_phi_fun_sparsity_out(int); -int {{ model.name }}_dyn_disc_phi_fun_n_in(void); -int {{ model.name }}_dyn_disc_phi_fun_n_out(void); - -int {{ model.name }}_dyn_disc_phi_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_dyn_disc_phi_fun_jac_work(int *, int *, int *, int *); -const int *{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_in(int); -const int *{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_out(int); -int {{ model.name }}_dyn_disc_phi_fun_jac_n_in(void); -int {{ model.name }}_dyn_disc_phi_fun_jac_n_out(void); - -{%- if hessian_approx == "EXACT" %} -int {{ model.name }}_dyn_disc_phi_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_dyn_disc_phi_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_dyn_disc_phi_fun_jac_hess_n_in(void); -int {{ model.name }}_dyn_disc_phi_fun_jac_hess_n_out(void); -{%- endif %} -{% else %} - {%- if hessian_approx == "EXACT" %} -int {{ model.dyn_disc_fun_jac_hess }}(void **, void **, void *); - {% endif %} -int {{ model.dyn_disc_fun_jac }}(void **, void **, void *); -int {{ model.dyn_disc_fun }}(void **, void **, void *); -{% endif %} - - -{% endif %} - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // {{ model.name }}_MODEL diff --git a/third_party/acados/acados_template/casadi_function_generation.py b/third_party/acados/acados_template/casadi_function_generation.py deleted file mode 100644 index 6373a2809dbc6b..00000000000000 --- a/third_party/acados/acados_template/casadi_function_generation.py +++ /dev/null @@ -1,708 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -import os -import casadi as ca -from .utils import is_empty, casadi_length - - -def get_casadi_symbol(x): - if isinstance(x, ca.MX): - return ca.MX.sym - elif isinstance(x, ca.SX): - return ca.SX.sym - else: - raise TypeError("Expected casadi SX or MX.") - -################ -# Dynamics -################ - - -def generate_c_code_discrete_dynamics( model, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - # load model - x = model.x - u = model.u - p = model.p - phi = model.disc_dyn_expr - model_name = model.name - nx = casadi_length(x) - - symbol = get_casadi_symbol(x) - # assume nx1 = nx !!! - lam = symbol('lam', nx, 1) - - # generate jacobians - ux = ca.vertcat(u,x) - jac_ux = ca.jacobian(phi, ux) - # generate adjoint - adj_ux = ca.jtimes(phi, ux, lam, True) - # generate hessian - hess_ux = ca.jacobian(adj_ux, ux) - - # change directory - cwd = os.getcwd() - model_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model_name}_model')) - if not os.path.exists(model_dir): - os.makedirs(model_dir) - os.chdir(model_dir) - - # set up & generate ca.Functions - fun_name = model_name + '_dyn_disc_phi_fun' - phi_fun = ca.Function(fun_name, [x, u, p], [phi]) - phi_fun.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_dyn_disc_phi_fun_jac' - phi_fun_jac_ut_xt = ca.Function(fun_name, [x, u, p], [phi, jac_ux.T]) - phi_fun_jac_ut_xt.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_dyn_disc_phi_fun_jac_hess' - phi_fun_jac_ut_xt_hess = ca.Function(fun_name, [x, u, lam, p], [phi, jac_ux.T, hess_ux]) - phi_fun_jac_ut_xt_hess.generate(fun_name, casadi_codegen_opts) - - os.chdir(cwd) - return - - - -def generate_c_code_explicit_ode( model, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - generate_hess = opts["generate_hess"] - - # load model - x = model.x - u = model.u - p = model.p - f_expl = model.f_expl_expr - model_name = model.name - - ## get model dimensions - nx = x.size()[0] - nu = u.size()[0] - - symbol = get_casadi_symbol(x) - - ## set up functions to be exported - Sx = symbol('Sx', nx, nx) - Sp = symbol('Sp', nx, nu) - lambdaX = symbol('lambdaX', nx, 1) - - fun_name = model_name + '_expl_ode_fun' - - ## Set up functions - expl_ode_fun = ca.Function(fun_name, [x, u, p], [f_expl]) - - vdeX = ca.jtimes(f_expl,x,Sx) - vdeP = ca.jacobian(f_expl,u) + ca.jtimes(f_expl,x,Sp) - - fun_name = model_name + '_expl_vde_forw' - - expl_vde_forw = ca.Function(fun_name, [x, Sx, Sp, u, p], [f_expl, vdeX, vdeP]) - - adj = ca.jtimes(f_expl, ca.vertcat(x, u), lambdaX, True) - - fun_name = model_name + '_expl_vde_adj' - expl_vde_adj = ca.Function(fun_name, [x, lambdaX, u, p], [adj]) - - if generate_hess: - S_forw = ca.vertcat(ca.horzcat(Sx, Sp), ca.horzcat(ca.DM.zeros(nu,nx), ca.DM.eye(nu))) - hess = ca.mtimes(ca.transpose(S_forw),ca.jtimes(adj, ca.vertcat(x,u), S_forw)) - hess2 = [] - for j in range(nx+nu): - for i in range(j,nx+nu): - hess2 = ca.vertcat(hess2, hess[i,j]) - - fun_name = model_name + '_expl_ode_hess' - expl_ode_hess = ca.Function(fun_name, [x, Sx, Sp, lambdaX, u, p], [adj, hess2]) - - # change directory - cwd = os.getcwd() - model_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model_name}_model')) - if not os.path.exists(model_dir): - os.makedirs(model_dir) - os.chdir(model_dir) - - # generate C code - fun_name = model_name + '_expl_ode_fun' - expl_ode_fun.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_expl_vde_forw' - expl_vde_forw.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_expl_vde_adj' - expl_vde_adj.generate(fun_name, casadi_codegen_opts) - - if generate_hess: - fun_name = model_name + '_expl_ode_hess' - expl_ode_hess.generate(fun_name, casadi_codegen_opts) - os.chdir(cwd) - - return - - -def generate_c_code_implicit_ode( model, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - # load model - x = model.x - xdot = model.xdot - u = model.u - z = model.z - p = model.p - f_impl = model.f_impl_expr - model_name = model.name - - # get model dimensions - nx = casadi_length(x) - nz = casadi_length(z) - - # generate jacobians - jac_x = ca.jacobian(f_impl, x) - jac_xdot = ca.jacobian(f_impl, xdot) - jac_u = ca.jacobian(f_impl, u) - jac_z = ca.jacobian(f_impl, z) - - # Set up functions - p = model.p - fun_name = model_name + '_impl_dae_fun' - impl_dae_fun = ca.Function(fun_name, [x, xdot, u, z, p], [f_impl]) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_z' - impl_dae_fun_jac_x_xdot_z = ca.Function(fun_name, [x, xdot, u, z, p], [f_impl, jac_x, jac_xdot, jac_z]) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_u_z' - impl_dae_fun_jac_x_xdot_u_z = ca.Function(fun_name, [x, xdot, u, z, p], [f_impl, jac_x, jac_xdot, jac_u, jac_z]) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_u' - impl_dae_fun_jac_x_xdot_u = ca.Function(fun_name, [x, xdot, u, z, p], [f_impl, jac_x, jac_xdot, jac_u]) - - fun_name = model_name + '_impl_dae_jac_x_xdot_u_z' - impl_dae_jac_x_xdot_u_z = ca.Function(fun_name, [x, xdot, u, z, p], [jac_x, jac_xdot, jac_u, jac_z]) - - if opts["generate_hess"]: - x_xdot_z_u = ca.vertcat(x, xdot, z, u) - symbol = get_casadi_symbol(x) - multiplier = symbol('multiplier', nx + nz) - ADJ = ca.jtimes(f_impl, x_xdot_z_u, multiplier, True) - HESS = ca.jacobian(ADJ, x_xdot_z_u) - fun_name = model_name + '_impl_dae_hess' - impl_dae_hess = ca.Function(fun_name, [x, xdot, u, z, multiplier, p], [HESS]) - - # change directory - cwd = os.getcwd() - model_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model_name}_model')) - if not os.path.exists(model_dir): - os.makedirs(model_dir) - os.chdir(model_dir) - - # generate C code - fun_name = model_name + '_impl_dae_fun' - impl_dae_fun.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_z' - impl_dae_fun_jac_x_xdot_z.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_impl_dae_jac_x_xdot_u_z' - impl_dae_jac_x_xdot_u_z.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_u_z' - impl_dae_fun_jac_x_xdot_u_z.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_u' - impl_dae_fun_jac_x_xdot_u.generate(fun_name, casadi_codegen_opts) - - if opts["generate_hess"]: - fun_name = model_name + '_impl_dae_hess' - impl_dae_hess.generate(fun_name, casadi_codegen_opts) - - os.chdir(cwd) - return - - -def generate_c_code_gnsf( model, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - model_name = model.name - - # set up directory - cwd = os.getcwd() - model_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model_name}_model')) - if not os.path.exists(model_dir): - os.makedirs(model_dir) - os.chdir(model_dir) - - # obtain gnsf dimensions - get_matrices_fun = model.get_matrices_fun - phi_fun = model.phi_fun - - size_gnsf_A = get_matrices_fun.size_out(0) - gnsf_nx1 = size_gnsf_A[1] - gnsf_nz1 = size_gnsf_A[0] - size_gnsf_A[1] - gnsf_nuhat = max(phi_fun.size_in(1)) - gnsf_ny = max(phi_fun.size_in(0)) - gnsf_nout = max(phi_fun.size_out(0)) - - # set up expressions - # if the model uses ca.MX because of cost/constraints - # the DAE can be exported as ca.SX -> detect GNSF in Matlab - # -> evaluated ca.SX GNSF functions with ca.MX. - u = model.u - symbol = get_casadi_symbol(u) - - y = symbol("y", gnsf_ny, 1) - uhat = symbol("uhat", gnsf_nuhat, 1) - p = model.p - x1 = symbol("gnsf_x1", gnsf_nx1, 1) - x1dot = symbol("gnsf_x1dot", gnsf_nx1, 1) - z1 = symbol("gnsf_z1", gnsf_nz1, 1) - dummy = symbol("gnsf_dummy", 1, 1) - empty_var = symbol("gnsf_empty_var", 0, 0) - - ## generate C code - fun_name = model_name + '_gnsf_phi_fun' - phi_fun_ = ca.Function(fun_name, [y, uhat, p], [phi_fun(y, uhat, p)]) - phi_fun_.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_gnsf_phi_fun_jac_y' - phi_fun_jac_y = model.phi_fun_jac_y - phi_fun_jac_y_ = ca.Function(fun_name, [y, uhat, p], phi_fun_jac_y(y, uhat, p)) - phi_fun_jac_y_.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_gnsf_phi_jac_y_uhat' - phi_jac_y_uhat = model.phi_jac_y_uhat - phi_jac_y_uhat_ = ca.Function(fun_name, [y, uhat, p], phi_jac_y_uhat(y, uhat, p)) - phi_jac_y_uhat_.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_gnsf_f_lo_fun_jac_x1k1uz' - f_lo_fun_jac_x1k1uz = model.f_lo_fun_jac_x1k1uz - f_lo_fun_jac_x1k1uz_eval = f_lo_fun_jac_x1k1uz(x1, x1dot, z1, u, p) - - # avoid codegeneration issue - if not isinstance(f_lo_fun_jac_x1k1uz_eval, tuple) and is_empty(f_lo_fun_jac_x1k1uz_eval): - f_lo_fun_jac_x1k1uz_eval = [empty_var] - - f_lo_fun_jac_x1k1uz_ = ca.Function(fun_name, [x1, x1dot, z1, u, p], - f_lo_fun_jac_x1k1uz_eval) - f_lo_fun_jac_x1k1uz_.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_gnsf_get_matrices_fun' - get_matrices_fun_ = ca.Function(fun_name, [dummy], get_matrices_fun(1)) - get_matrices_fun_.generate(fun_name, casadi_codegen_opts) - - # remove fields for json dump - del model.phi_fun - del model.phi_fun_jac_y - del model.phi_jac_y_uhat - del model.f_lo_fun_jac_x1k1uz - del model.get_matrices_fun - - os.chdir(cwd) - - return - - -################ -# Cost -################ - -def generate_c_code_external_cost(model, stage_type, opts): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - x = model.x - p = model.p - u = model.u - z = model.z - symbol = get_casadi_symbol(x) - - if stage_type == 'terminal': - suffix_name = "_cost_ext_cost_e_fun" - suffix_name_hess = "_cost_ext_cost_e_fun_jac_hess" - suffix_name_jac = "_cost_ext_cost_e_fun_jac" - ext_cost = model.cost_expr_ext_cost_e - custom_hess = model.cost_expr_ext_cost_custom_hess_e - # Last stage cannot depend on u and z - u = symbol("u", 0, 0) - z = symbol("z", 0, 0) - - elif stage_type == 'path': - suffix_name = "_cost_ext_cost_fun" - suffix_name_hess = "_cost_ext_cost_fun_jac_hess" - suffix_name_jac = "_cost_ext_cost_fun_jac" - ext_cost = model.cost_expr_ext_cost - custom_hess = model.cost_expr_ext_cost_custom_hess - - elif stage_type == 'initial': - suffix_name = "_cost_ext_cost_0_fun" - suffix_name_hess = "_cost_ext_cost_0_fun_jac_hess" - suffix_name_jac = "_cost_ext_cost_0_fun_jac" - ext_cost = model.cost_expr_ext_cost_0 - custom_hess = model.cost_expr_ext_cost_custom_hess_0 - - nunx = x.shape[0] + u.shape[0] - - # set up functions to be exported - fun_name = model.name + suffix_name - fun_name_hess = model.name + suffix_name_hess - fun_name_jac = model.name + suffix_name_jac - - # generate expression for full gradient and Hessian - hess_uxz, grad_uxz = ca.hessian(ext_cost, ca.vertcat(u, x, z)) - - hess_ux = hess_uxz[:nunx, :nunx] - hess_z = hess_uxz[nunx:, nunx:] - hess_z_ux = hess_uxz[nunx:, :nunx] - - if custom_hess is not None: - hess_ux = custom_hess - - ext_cost_fun = ca.Function(fun_name, [x, u, z, p], [ext_cost]) - - ext_cost_fun_jac_hess = ca.Function( - fun_name_hess, [x, u, z, p], [ext_cost, grad_uxz, hess_ux, hess_z, hess_z_ux] - ) - ext_cost_fun_jac = ca.Function( - fun_name_jac, [x, u, z, p], [ext_cost, grad_uxz] - ) - - # change directory - cwd = os.getcwd() - cost_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model.name}_cost')) - if not os.path.exists(cost_dir): - os.makedirs(cost_dir) - os.chdir(cost_dir) - - ext_cost_fun.generate(fun_name, casadi_codegen_opts) - ext_cost_fun_jac_hess.generate(fun_name_hess, casadi_codegen_opts) - ext_cost_fun_jac.generate(fun_name_jac, casadi_codegen_opts) - - os.chdir(cwd) - return - - -def generate_c_code_nls_cost( model, cost_name, stage_type, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - x = model.x - z = model.z - p = model.p - u = model.u - - symbol = get_casadi_symbol(x) - - if stage_type == 'terminal': - middle_name = '_cost_y_e' - u = symbol('u', 0, 0) - y_expr = model.cost_y_expr_e - - elif stage_type == 'initial': - middle_name = '_cost_y_0' - y_expr = model.cost_y_expr_0 - - elif stage_type == 'path': - middle_name = '_cost_y' - y_expr = model.cost_y_expr - - # change directory - cwd = os.getcwd() - cost_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model.name}_cost')) - if not os.path.exists(cost_dir): - os.makedirs(cost_dir) - os.chdir(cost_dir) - - # set up expressions - cost_jac_expr = ca.transpose(ca.jacobian(y_expr, ca.vertcat(u, x))) - dy_dz = ca.jacobian(y_expr, z) - ny = casadi_length(y_expr) - - y = symbol('y', ny, 1) - - y_adj = ca.jtimes(y_expr, ca.vertcat(u, x), y, True) - y_hess = ca.jacobian(y_adj, ca.vertcat(u, x)) - - ## generate C code - suffix_name = '_fun' - fun_name = cost_name + middle_name + suffix_name - y_fun = ca.Function( fun_name, [x, u, z, p], [ y_expr ]) - y_fun.generate( fun_name, casadi_codegen_opts ) - - suffix_name = '_fun_jac_ut_xt' - fun_name = cost_name + middle_name + suffix_name - y_fun_jac_ut_xt = ca.Function(fun_name, [x, u, z, p], [ y_expr, cost_jac_expr, dy_dz ]) - y_fun_jac_ut_xt.generate( fun_name, casadi_codegen_opts ) - - suffix_name = '_hess' - fun_name = cost_name + middle_name + suffix_name - y_hess = ca.Function(fun_name, [x, u, z, y, p], [ y_hess ]) - y_hess.generate( fun_name, casadi_codegen_opts ) - - os.chdir(cwd) - - return - - - -def generate_c_code_conl_cost(model, cost_name, stage_type, opts): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - x = model.x - z = model.z - p = model.p - - symbol = get_casadi_symbol(x) - - if stage_type == 'terminal': - u = symbol('u', 0, 0) - - yref = model.cost_r_in_psi_expr_e - inner_expr = model.cost_y_expr_e - yref - outer_expr = model.cost_psi_expr_e - res_expr = model.cost_r_in_psi_expr_e - - suffix_name_fun = '_conl_cost_e_fun' - suffix_name_fun_jac_hess = '_conl_cost_e_fun_jac_hess' - - custom_hess = model.cost_conl_custom_outer_hess_e - - elif stage_type == 'initial': - u = model.u - - yref = model.cost_r_in_psi_expr_0 - inner_expr = model.cost_y_expr_0 - yref - outer_expr = model.cost_psi_expr_0 - res_expr = model.cost_r_in_psi_expr_0 - - suffix_name_fun = '_conl_cost_0_fun' - suffix_name_fun_jac_hess = '_conl_cost_0_fun_jac_hess' - - custom_hess = model.cost_conl_custom_outer_hess_0 - - elif stage_type == 'path': - u = model.u - - yref = model.cost_r_in_psi_expr - inner_expr = model.cost_y_expr - yref - outer_expr = model.cost_psi_expr - res_expr = model.cost_r_in_psi_expr - - suffix_name_fun = '_conl_cost_fun' - suffix_name_fun_jac_hess = '_conl_cost_fun_jac_hess' - - custom_hess = model.cost_conl_custom_outer_hess - - # set up function names - fun_name_cost_fun = model.name + suffix_name_fun - fun_name_cost_fun_jac_hess = model.name + suffix_name_fun_jac_hess - - # set up functions to be exported - outer_loss_fun = ca.Function('psi', [res_expr, p], [outer_expr]) - cost_expr = outer_loss_fun(inner_expr, p) - - outer_loss_grad_fun = ca.Function('outer_loss_grad', [res_expr, p], [ca.jacobian(outer_expr, res_expr).T]) - - if custom_hess is None: - outer_hess_fun = ca.Function('inner_hess', [res_expr, p], [ca.hessian(outer_loss_fun(res_expr, p), res_expr)[0]]) - else: - outer_hess_fun = ca.Function('inner_hess', [res_expr, p], [custom_hess]) - - Jt_ux_expr = ca.jacobian(inner_expr, ca.vertcat(u, x)).T - Jt_z_expr = ca.jacobian(inner_expr, z).T - - cost_fun = ca.Function( - fun_name_cost_fun, - [x, u, z, yref, p], - [cost_expr]) - - cost_fun_jac_hess = ca.Function( - fun_name_cost_fun_jac_hess, - [x, u, z, yref, p], - [cost_expr, outer_loss_grad_fun(inner_expr, p), Jt_ux_expr, Jt_z_expr, outer_hess_fun(inner_expr, p)] - ) - # change directory - cwd = os.getcwd() - cost_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model.name}_cost')) - if not os.path.exists(cost_dir): - os.makedirs(cost_dir) - os.chdir(cost_dir) - - # generate C code - cost_fun.generate(fun_name_cost_fun, casadi_codegen_opts) - cost_fun_jac_hess.generate(fun_name_cost_fun_jac_hess, casadi_codegen_opts) - - os.chdir(cwd) - - return - - -################ -# Constraints -################ -def generate_c_code_constraint( model, con_name, is_terminal, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - # load constraint variables and expression - x = model.x - p = model.p - - symbol = get_casadi_symbol(x) - - if is_terminal: - con_h_expr = model.con_h_expr_e - con_phi_expr = model.con_phi_expr_e - # create dummy u, z - u = symbol('u', 0, 0) - z = symbol('z', 0, 0) - else: - con_h_expr = model.con_h_expr - con_phi_expr = model.con_phi_expr - u = model.u - z = model.z - - if (not is_empty(con_h_expr)) and (not is_empty(con_phi_expr)): - raise Exception("acados: you can either have constraint_h, or constraint_phi, not both.") - - if (is_empty(con_h_expr) and is_empty(con_phi_expr)): - # both empty -> nothing to generate - return - - if is_empty(con_h_expr): - constr_type = 'BGP' - else: - constr_type = 'BGH' - - if is_empty(p): - p = symbol('p', 0, 0) - - if is_empty(z): - z = symbol('z', 0, 0) - - if not (is_empty(con_h_expr)) and opts['generate_hess']: - # multipliers for hessian - nh = casadi_length(con_h_expr) - lam_h = symbol('lam_h', nh, 1) - - # set up & change directory - cwd = os.getcwd() - constraints_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model.name}_constraints')) - if not os.path.exists(constraints_dir): - os.makedirs(constraints_dir) - os.chdir(constraints_dir) - - # export casadi functions - if constr_type == 'BGH': - if is_terminal: - fun_name = con_name + '_constr_h_e_fun_jac_uxt_zt' - else: - fun_name = con_name + '_constr_h_fun_jac_uxt_zt' - - jac_ux_t = ca.transpose(ca.jacobian(con_h_expr, ca.vertcat(u,x))) - jac_z_t = ca.jacobian(con_h_expr, z) - constraint_fun_jac_tran = ca.Function(fun_name, [x, u, z, p], \ - [con_h_expr, jac_ux_t, jac_z_t]) - - constraint_fun_jac_tran.generate(fun_name, casadi_codegen_opts) - if opts['generate_hess']: - - if is_terminal: - fun_name = con_name + '_constr_h_e_fun_jac_uxt_zt_hess' - else: - fun_name = con_name + '_constr_h_fun_jac_uxt_zt_hess' - - # adjoint - adj_ux = ca.jtimes(con_h_expr, ca.vertcat(u, x), lam_h, True) - # hessian - hess_ux = ca.jacobian(adj_ux, ca.vertcat(u, x)) - - adj_z = ca.jtimes(con_h_expr, z, lam_h, True) - hess_z = ca.jacobian(adj_z, z) - - # set up functions - constraint_fun_jac_tran_hess = \ - ca.Function(fun_name, [x, u, lam_h, z, p], \ - [con_h_expr, jac_ux_t, hess_ux, jac_z_t, hess_z]) - - # generate C code - constraint_fun_jac_tran_hess.generate(fun_name, casadi_codegen_opts) - - if is_terminal: - fun_name = con_name + '_constr_h_e_fun' - else: - fun_name = con_name + '_constr_h_fun' - h_fun = ca.Function(fun_name, [x, u, z, p], [con_h_expr]) - h_fun.generate(fun_name, casadi_codegen_opts) - - else: # BGP constraint - if is_terminal: - fun_name = con_name + '_phi_e_constraint' - r = model.con_r_in_phi_e - con_r_expr = model.con_r_expr_e - else: - fun_name = con_name + '_phi_constraint' - r = model.con_r_in_phi - con_r_expr = model.con_r_expr - - nphi = casadi_length(con_phi_expr) - con_phi_expr_x_u_z = ca.substitute(con_phi_expr, r, con_r_expr) - phi_jac_u = ca.jacobian(con_phi_expr_x_u_z, u) - phi_jac_x = ca.jacobian(con_phi_expr_x_u_z, x) - phi_jac_z = ca.jacobian(con_phi_expr_x_u_z, z) - - hess = ca.hessian(con_phi_expr[0], r)[0] - for i in range(1, nphi): - hess = ca.vertcat(hess, ca.hessian(con_phi_expr[i], r)[0]) - - r_jac_u = ca.jacobian(con_r_expr, u) - r_jac_x = ca.jacobian(con_r_expr, x) - - constraint_phi = \ - ca.Function(fun_name, [x, u, z, p], \ - [con_phi_expr_x_u_z, \ - ca.vertcat(ca.transpose(phi_jac_u), ca.transpose(phi_jac_x)), \ - ca.transpose(phi_jac_z), \ - hess, - ca.vertcat(ca.transpose(r_jac_u), ca.transpose(r_jac_x))]) - - constraint_phi.generate(fun_name, casadi_codegen_opts) - - # change directory back - os.chdir(cwd) - - return - diff --git a/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.c b/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.c deleted file mode 100644 index b39ff2e23baf15..00000000000000 --- a/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.c +++ /dev/null @@ -1,819 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -// This is a template based custom_update function -#include -#include -#include -#include - -#include "custom_update_function.h" -#include "acados_solver_{{ model.name }}.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados/utils/mem.h" - -#include "blasfeo/include/blasfeo_d_aux_ext_dep.h" -#include "blasfeo/include/blasfeo_d_blasfeo_api.h" - - -typedef struct custom_memory -{ - // covariance matrics - struct blasfeo_dmat *uncertainty_matrix_buffer; // shape = (N+1, nx, nx) - // covariance matrix of the additive disturbance - struct blasfeo_dmat W_mat; // shape = (nw, nw) - struct blasfeo_dmat unc_jac_G_mat; // shape = (nx, nw) - struct blasfeo_dmat temp_GW_mat; // shape = (nx, nw) - struct blasfeo_dmat GWG_mat; // shape = (nx, nx) - // sensitivity matrices - struct blasfeo_dmat A_mat; // shape = (nx, nx) - struct blasfeo_dmat B_mat; // shape = (nx, nu) - // matrix in linear constraints - struct blasfeo_dmat Cg_mat; // shape = (ng, nx) - struct blasfeo_dmat Dg_mat; // shape = (ng, nu) - struct blasfeo_dmat Cg_e_mat; // shape = (ng_e, nx) - struct blasfeo_dmat dummy_Dgh_e_mat; // shape = (ngh_e_max, nu) - // matrix in nonlinear constraints - struct blasfeo_dmat Ch_mat; // shape = (nh, nx) - struct blasfeo_dmat Dh_mat; // shape = (nh, nu) - struct blasfeo_dmat Ch_e_mat; // shape = (nh_e, nx) - // feedback gain matrix - struct blasfeo_dmat K_mat; // shape = (nu, nx) - // AK = A - B@K - struct blasfeo_dmat AK_mat; // shape = (nx, nx) - // A@P_k - struct blasfeo_dmat temp_AP_mat; // shape = (nx, nx) - // K@P_k, K@P_k@K^T - struct blasfeo_dmat temp_KP_mat; // shape = (nu, nx) - struct blasfeo_dmat temp_KPK_mat; // shape = (nu, nu) - // C + D @ K, (C + D @ K) @ P_k - struct blasfeo_dmat temp_CaDK_mat; // shape = (ngh_me_max, nx) - struct blasfeo_dmat temp_CaDKmP_mat; // shape = (ngh_me_max, nx) - struct blasfeo_dmat temp_beta_mat; // shape = (ngh_me_max, ngh_me_max) - - double *d_A_mat; // shape = (nx, nx) - double *d_B_mat; // shape = (nx, nu) - double *d_Cg_mat; // shape = (ng, nx) - double *d_Dg_mat; // shape = (ng, nu) - double *d_Cg_e_mat; // shape = (ng_e, nx) - double *d_Cgh_mat; // shape = (ng+nh, nx) - double *d_Dgh_mat; // shape = (ng+nh, nu) - double *d_Cgh_e_mat; // shape = (ng_e+nh_e, nx) - double *d_state_vec; - // upper and lower bounds on state variables - double *d_lbx; // shape = (nbx,) - double *d_ubx; // shape = (nbx,) - double *d_lbx_e; // shape = (nbx_e,) - double *d_ubx_e; // shape = (nbx_e,) - // tightened upper and lower bounds on state variables - double *d_lbx_tightened; // shape = (nbx,) - double *d_ubx_tightened; // shape = (nbx,) - double *d_lbx_e_tightened; // shape = (nbx_e,) - double *d_ubx_e_tightened; // shape = (nbx_e,) - // upper and lower bounds on control inputs - double *d_lbu; // shape = (nbu,) - double *d_ubu; // shape = (nbu,) - // tightened upper and lower bounds on control inputs - double *d_lbu_tightened; // shape = (nbu,) - double *d_ubu_tightened; // shape = (nbu,) - // upper and lower bounds on polytopic constraints - double *d_lg; // shape = (ng,) - double *d_ug; // shape = (ng,) - double *d_lg_e; // shape = (ng_e,) - double *d_ug_e; // shape = (ng_e,) - // tightened lower bounds on polytopic constraints - double *d_lg_tightened; // shape = (ng,) - double *d_ug_tightened; // shape = (ng,) - double *d_lg_e_tightened; // shape = (ng_e,) - double *d_ug_e_tightened; // shape = (ng_e,) - // upper and lower bounds on nonlinear constraints - double *d_lh; // shape = (nh,) - double *d_uh; // shape = (nh,) - double *d_lh_e; // shape = (nh_e,) - double *d_uh_e; // shape = (nh_e,) - // tightened upper and lower bounds on nonlinear constraints - double *d_lh_tightened; // shape = (nh,) - double *d_uh_tightened; // shape = (nh,) - double *d_lh_e_tightened; // shape = (nh_e,) - double *d_uh_e_tightened; // shape = (nh_e,) - - int *idxbx; // shape = (nbx,) - int *idxbu; // shape = (nbu,) - int *idxbx_e; // shape = (nbx_e,) - - void *raw_memory; // Pointer to allocated memory, to be used for freeing -} custom_memory; - -static int int_max(int num1, int num2) -{ - return (num1 > num2 ) ? num1 : num2; -} - - -static int custom_memory_calculate_size(ocp_nlp_config *nlp_config, ocp_nlp_dims *nlp_dims) -{ - int N = nlp_dims->N; - int nx = {{ dims.nx }}; - int nu = {{ dims.nu }}; - int nw = {{ zoro_description.nw }}; - - int ng = {{ dims.ng }}; - int nh = {{ dims.nh }}; - int nbx = {{ dims.nbx }}; - int nbu = {{ dims.nbu }}; - - int ng_e = {{ dims.ng_e }}; - int nh_e = {{ dims.nh_e }}; - int ngh_e_max = int_max(ng_e, nh_e); - int ngh_me_max = int_max(ngh_e_max, int_max(ng, nh)); - int nbx_e = {{ dims.nbx_e }}; - - assert({{zoro_description.nlbx_t}} <= nbx); - assert({{zoro_description.nubx_t}} <= nbx); - assert({{zoro_description.nlbu_t}} <= nbu); - assert({{zoro_description.nubu_t}} <= nbu); - assert({{zoro_description.nlg_t}} <= ng); - assert({{zoro_description.nug_t}} <= ng); - assert({{zoro_description.nlh_t}} <= nh); - assert({{zoro_description.nuh_t}} <= nh); - assert({{zoro_description.nlbx_e_t}} <= nbx_e); - assert({{zoro_description.nubx_e_t}} <= nbx_e); - assert({{zoro_description.nlg_e_t}} <= ng_e); - assert({{zoro_description.nug_e_t}} <= ng_e); - assert({{zoro_description.nlh_e_t}} <= nh_e); - assert({{zoro_description.nuh_e_t}} <= nh_e); - - acados_size_t size = sizeof(custom_memory); - size += nbx * sizeof(int); - /* blasfeo structs */ - size += (N + 1) * sizeof(struct blasfeo_dmat); - /* blasfeo mem: mat */ - size += (N + 1) * blasfeo_memsize_dmat(nx, nx); // uncertainty_matrix_buffer - size += blasfeo_memsize_dmat(nw, nw); // W_mat - size += 2 * blasfeo_memsize_dmat(nx, nw); // unc_jac_G_mat, temp_GW_mat - size += 4 * blasfeo_memsize_dmat(nx, nx); // GWG_mat, A_mat, AK_mat, temp_AP_mat - size += blasfeo_memsize_dmat(nx, nu); // B_mat - size += 2 * blasfeo_memsize_dmat(nu, nx); // K_mat, temp_KP_mat - size += blasfeo_memsize_dmat(nu, nu); // temp_KPK_mat - size += blasfeo_memsize_dmat(ng, nx); // Cg_mat - size += blasfeo_memsize_dmat(ng, nu); // Dg_mat - size += blasfeo_memsize_dmat(ng_e, nx); // Cg_e_mat - size += blasfeo_memsize_dmat(ngh_e_max, nu); // dummy_Dgh_e_mat - size += blasfeo_memsize_dmat(nh, nx); // Ch_mat - size += blasfeo_memsize_dmat(nh, nu); // Dh_mat - size += blasfeo_memsize_dmat(nh_e, nx); // Ch_e_mat - size += 2 * blasfeo_memsize_dmat(ngh_me_max, nx); // temp_CaDK_mat, temp_CaDKmP_mat - size += blasfeo_memsize_dmat(ngh_me_max, ngh_me_max); // temp_beta_mat - /* blasfeo mem: vec */ - /* Arrays */ - size += nx*nx *sizeof(double); // d_A_mat - size += nx*nu *sizeof(double); // d_B_mat - size += (ng + ng_e) * nx * sizeof(double); // d_Cg_mat, d_Cg_e_mat - size += (ng) * nu * sizeof(double); // d_Dg_mat - size += (nh + nh_e + ng + ng_e) * nx * sizeof(double); // d_Cgh_mat, d_Cgh_e_mat - size += (nh + ng) * nu * sizeof(double); // d_Dgh_mat - // d_state_vec - size += nx *sizeof(double); - // constraints and tightened constraints - size += 4 * (nbx + nbu + ng + nh)*sizeof(double); - size += 4 * (nbx_e + ng_e + nh_e)*sizeof(double); - size += (nbx + nbu + nbx_e)*sizeof(int); // idxbx, idxbu, idxbx_e - - size += 1 * 8; // initial alignment - make_int_multiple_of(64, &size); - size += 1 * 64; - - return size; -} - - -static custom_memory *custom_memory_assign(ocp_nlp_config *nlp_config, ocp_nlp_dims *nlp_dims, void *raw_memory) -{ - int N = nlp_dims->N; - int nx = {{ dims.nx }}; - int nu = {{ dims.nu }}; - int nw = {{ zoro_description.nw }}; - - int ng = {{ dims.ng }}; - int nh = {{ dims.nh }}; - int nbx = {{ dims.nbx }}; - int nbu = {{ dims.nbu }}; - - int ng_e = {{ dims.ng_e }}; - int nh_e = {{ dims.nh_e }}; - int ngh_e_max = int_max(ng_e, nh_e); - int ngh_me_max = int_max(ngh_e_max, int_max(ng, nh)); - int nbx_e = {{ dims.nbx_e }}; - - char *c_ptr = (char *) raw_memory; - custom_memory *mem = (custom_memory *) c_ptr; - c_ptr += sizeof(custom_memory); - - align_char_to(8, &c_ptr); - assign_and_advance_blasfeo_dmat_structs(N+1, &mem->uncertainty_matrix_buffer, &c_ptr); - - align_char_to(64, &c_ptr); - - for (int ii = 0; ii <= N; ii++) - { - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->uncertainty_matrix_buffer[ii], &c_ptr); - } - // Disturbance Dynamics - assign_and_advance_blasfeo_dmat_mem(nw, nw, &mem->W_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nw, &mem->unc_jac_G_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nw, &mem->temp_GW_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->GWG_mat, &c_ptr); - // System Dynamics - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->A_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nu, &mem->B_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ng, nx, &mem->Cg_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ng, nu, &mem->Dg_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ng_e, nx, &mem->Cg_e_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ngh_e_max, nu, &mem->dummy_Dgh_e_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nh, nx, &mem->Ch_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nh, nu, &mem->Dh_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nh_e, nx, &mem->Ch_e_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nu, nx, &mem->K_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->AK_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->temp_AP_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nu, nx, &mem->temp_KP_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nu, nu, &mem->temp_KPK_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ngh_me_max, nx, &mem->temp_CaDK_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ngh_me_max, nx, &mem->temp_CaDKmP_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ngh_me_max, ngh_me_max, &mem->temp_beta_mat, &c_ptr); - - assign_and_advance_double(nx*nx, &mem->d_A_mat, &c_ptr); - assign_and_advance_double(nx*nu, &mem->d_B_mat, &c_ptr); - assign_and_advance_double(ng*nx, &mem->d_Cg_mat, &c_ptr); - assign_and_advance_double(ng*nu, &mem->d_Dg_mat, &c_ptr); - assign_and_advance_double(ng_e*nx, &mem->d_Cg_e_mat, &c_ptr); - assign_and_advance_double((ng + nh)*nx, &mem->d_Cgh_mat, &c_ptr); - assign_and_advance_double((ng + nh)*nu, &mem->d_Dgh_mat, &c_ptr); - assign_and_advance_double((ng_e + nh_e)*nx, &mem->d_Cgh_e_mat, &c_ptr); - assign_and_advance_double(nx, &mem->d_state_vec, &c_ptr); - assign_and_advance_double(nbx, &mem->d_lbx, &c_ptr); - assign_and_advance_double(nbx, &mem->d_ubx, &c_ptr); - assign_and_advance_double(nbx_e, &mem->d_lbx_e, &c_ptr); - assign_and_advance_double(nbx_e, &mem->d_ubx_e, &c_ptr); - assign_and_advance_double(nbx, &mem->d_lbx_tightened, &c_ptr); - assign_and_advance_double(nbx, &mem->d_ubx_tightened, &c_ptr); - assign_and_advance_double(nbx_e, &mem->d_lbx_e_tightened, &c_ptr); - assign_and_advance_double(nbx_e, &mem->d_ubx_e_tightened, &c_ptr); - assign_and_advance_double(nbu, &mem->d_lbu, &c_ptr); - assign_and_advance_double(nbu, &mem->d_ubu, &c_ptr); - assign_and_advance_double(nbu, &mem->d_lbu_tightened, &c_ptr); - assign_and_advance_double(nbu, &mem->d_ubu_tightened, &c_ptr); - assign_and_advance_double(ng, &mem->d_lg, &c_ptr); - assign_and_advance_double(ng, &mem->d_ug, &c_ptr); - assign_and_advance_double(ng_e, &mem->d_lg_e, &c_ptr); - assign_and_advance_double(ng_e, &mem->d_ug_e, &c_ptr); - assign_and_advance_double(ng, &mem->d_lg_tightened, &c_ptr); - assign_and_advance_double(ng, &mem->d_ug_tightened, &c_ptr); - assign_and_advance_double(ng_e, &mem->d_lg_e_tightened, &c_ptr); - assign_and_advance_double(ng_e, &mem->d_ug_e_tightened, &c_ptr); - assign_and_advance_double(nh, &mem->d_lh, &c_ptr); - assign_and_advance_double(nh, &mem->d_uh, &c_ptr); - assign_and_advance_double(nh_e, &mem->d_lh_e, &c_ptr); - assign_and_advance_double(nh_e, &mem->d_uh_e, &c_ptr); - assign_and_advance_double(nh, &mem->d_lh_tightened, &c_ptr); - assign_and_advance_double(nh, &mem->d_uh_tightened, &c_ptr); - assign_and_advance_double(nh_e, &mem->d_lh_e_tightened, &c_ptr); - assign_and_advance_double(nh_e, &mem->d_uh_e_tightened, &c_ptr); - - assign_and_advance_int(nbx, &mem->idxbx, &c_ptr); - assign_and_advance_int(nbu, &mem->idxbu, &c_ptr); - assign_and_advance_int(nbx_e, &mem->idxbx_e, &c_ptr); - - assert((char *) raw_memory + custom_memory_calculate_size(nlp_config, nlp_dims) >= c_ptr); - mem->raw_memory = raw_memory; - - return mem; -} - - - -static void *custom_memory_create({{ model.name }}_solver_capsule* capsule) -{ - printf("\nin custom_memory_create_function\n"); - - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(capsule); - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(capsule); - acados_size_t bytes = custom_memory_calculate_size(nlp_config, nlp_dims); - - void *ptr = acados_calloc(1, bytes); - - custom_memory *custom_mem = custom_memory_assign(nlp_config, nlp_dims, ptr); - custom_mem->raw_memory = ptr; - - return custom_mem; -} - - -static void custom_val_init_function(ocp_nlp_dims *nlp_dims, ocp_nlp_in *nlp_in, ocp_nlp_solver *nlp_solver, custom_memory *custom_mem) -{ - int N = nlp_dims->N; - int nx = {{ dims.nx }}; - int nu = {{ dims.nu }}; - int nw = {{ zoro_description.nw }}; - - int ng = {{ dims.ng }}; - int nh = {{ dims.nh }}; - int nbx = {{ dims.nbx }}; - int nbu = {{ dims.nbu }}; - - int ng_e = {{ dims.ng_e }}; - int nh_e = {{ dims.nh_e }}; - int ngh_e_max = int_max(ng_e, nh_e); - int nbx_e = {{ dims.nbx_e }}; - - /* Get the state constraint bounds */ - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "idxbx", custom_mem->idxbx); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "idxbx", custom_mem->idxbx_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lbx", custom_mem->d_lbx); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ubx", custom_mem->d_ubx); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lbx", custom_mem->d_lbx_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "ubx", custom_mem->d_ubx_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "idxbu", custom_mem->idxbu); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lbu", custom_mem->d_lbu); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ubu", custom_mem->d_ubu); - // Get the Jacobians and the bounds of the linear constraints - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lg", custom_mem->d_lg); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ug", custom_mem->d_ug); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lg", custom_mem->d_lg_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "ug", custom_mem->d_ug_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "C", custom_mem->d_Cg_mat); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "D", custom_mem->d_Dg_mat); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "C", custom_mem->d_Cg_e_mat); - blasfeo_pack_dmat(ng, nx, custom_mem->d_Cg_mat, ng, &custom_mem->Cg_mat, 0, 0); - blasfeo_pack_dmat(ng, nu, custom_mem->d_Dg_mat, ng, &custom_mem->Dg_mat, 0, 0); - blasfeo_pack_dmat(ng_e, nx, custom_mem->d_Cg_e_mat, ng_e, &custom_mem->Cg_e_mat, 0, 0); - blasfeo_dgese(ngh_e_max, nu, 0., &custom_mem->dummy_Dgh_e_mat, 0, 0); //fill with zeros - // NOTE: fixed lower and upper bounds of nonlinear constraints - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lh", custom_mem->d_lh); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "uh", custom_mem->d_uh); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lh", custom_mem->d_lh_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "uh", custom_mem->d_uh_e); - - /* Initilize tightened constraints*/ - // NOTE: tightened constraints are only initialized once - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lbx", custom_mem->d_lbx_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ubx", custom_mem->d_ubx_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lbx", custom_mem->d_lbx_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "ubx", custom_mem->d_ubx_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lbu", custom_mem->d_lbu_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ubu", custom_mem->d_ubu_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lg", custom_mem->d_lg_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ug", custom_mem->d_ug_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lg", custom_mem->d_lg_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "ug", custom_mem->d_ug_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lh", custom_mem->d_lh_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "uh", custom_mem->d_uh_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lh", custom_mem->d_lh_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "uh", custom_mem->d_uh_e_tightened); - - /* Initialize the W matrix */ - // blasfeo_dgese(nw, nw, 0., &custom_mem->W_mat, 0, 0); -{%- for ir in range(end=zoro_description.nw) %} - {%- for ic in range(end=zoro_description.nw) %} - blasfeo_dgein1({{zoro_description.W_mat[ir][ic]}}, &custom_mem->W_mat, {{ir}}, {{ic}}); - {%- endfor %} -{%- endfor %} - -{%- for ir in range(end=dims.nx) %} - {%- for ic in range(end=zoro_description.nw) %} - blasfeo_dgein1({{zoro_description.unc_jac_G_mat[ir][ic]}}, &custom_mem->unc_jac_G_mat, {{ir}}, {{ic}}); - {%- endfor %} -{%- endfor %} - - // NOTE: if G is changing this is not in init! - // temp_GW_mat = unc_jac_G_mat * W_mat - blasfeo_dgemm_nn(nx, nw, nw, 1.0, &custom_mem->unc_jac_G_mat, 0, 0, - &custom_mem->W_mat, 0, 0, 0.0, - &custom_mem->temp_GW_mat, 0, 0, &custom_mem->temp_GW_mat, 0, 0); - // GWG_mat = temp_GW_mat * unc_jac_G_mat^T - blasfeo_dgemm_nt(nx, nx, nw, 1.0, &custom_mem->temp_GW_mat, 0, 0, - &custom_mem->unc_jac_G_mat, 0, 0, 0.0, - &custom_mem->GWG_mat, 0, 0, &custom_mem->GWG_mat, 0, 0); - - /* Initialize the uncertainty_matrix_buffer[0] */ -{%- for ir in range(end=dims.nx) %} - {%- for ic in range(end=dims.nx) %} - blasfeo_dgein1({{zoro_description.P0_mat[ir][ic]}}, &custom_mem->uncertainty_matrix_buffer[0], {{ir}}, {{ic}}); - {%- endfor %} -{%- endfor %} - - /* Initialize the feedback gain matrix */ -{%- for ir in range(end=dims.nu) %} - {%- for ic in range(end=dims.nx) %} - blasfeo_dgein1({{zoro_description.fdbk_K_mat[ir][ic]}}, &custom_mem->K_mat, {{ir}}, {{ic}}); - {%- endfor %} -{%- endfor %} -} - - -int custom_update_init_function({{ model.name }}_solver_capsule* capsule) -{ - capsule->custom_update_memory = custom_memory_create(capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(capsule); - - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(capsule); - ocp_nlp_solver *nlp_solver = {{ model.name }}_acados_get_nlp_solver(capsule); - custom_val_init_function(nlp_dims, nlp_in, nlp_solver, capsule->custom_update_memory); - return 1; -} - -static void compute_gh_beta(struct blasfeo_dmat* K_mat, struct blasfeo_dmat* C_mat, - struct blasfeo_dmat* D_mat, struct blasfeo_dmat* CaDK_mat, - struct blasfeo_dmat* CaDKmP_mat, struct blasfeo_dmat* beta_mat, - struct blasfeo_dmat* P_mat, - int n_cstr, int nx, int nu) -{ - // (C+DK)@P@(C^T+K^TD^T) - // CaDK_mat = C_mat + D_mat @ K_mat - blasfeo_dgemm_nn(n_cstr, nx, nu, 1.0, D_mat, 0, 0, - K_mat, 0, 0, 1.0, - C_mat, 0, 0, CaDK_mat, 0, 0); - // CaDKmP_mat = CaDK_mat @ P_mat - blasfeo_dgemm_nn(n_cstr, nx, nx, 1.0, CaDK_mat, 0, 0, - P_mat, 0, 0, 0.0, - CaDKmP_mat, 0, 0, CaDKmP_mat, 0, 0); - // beta_mat = CaDKmP_mat @ CaDK_mat^T - blasfeo_dgemm_nt(n_cstr, n_cstr, nx, 1.0, CaDKmP_mat, 0, 0, - CaDK_mat, 0, 0, 0.0, - beta_mat, 0, 0, beta_mat, 0, 0); -} - -static void compute_KPK(struct blasfeo_dmat* K_mat, struct blasfeo_dmat* temp_KP_mat, - struct blasfeo_dmat* temp_KPK_mat, struct blasfeo_dmat* P_mat, - int nx, int nu) -{ - // K @ P_k @ K^T - // temp_KP_mat = K_mat @ P_mat - blasfeo_dgemm_nn(nu, nx, nx, 1.0, K_mat, 0, 0, - P_mat, 0, 0, 0.0, - temp_KP_mat, 0, 0, temp_KP_mat, 0, 0); - // temp_KPK_mat = temp_KP_mat @ K_mat^T - blasfeo_dgemm_nt(nu, nu, nx, 1.0, temp_KP_mat, 0, 0, - K_mat, 0, 0, 0.0, - temp_KPK_mat, 0, 0, temp_KPK_mat, 0, 0); -} - -static void compute_next_P_matrix(struct blasfeo_dmat* P_mat, struct blasfeo_dmat* P_next_mat, - struct blasfeo_dmat* A_mat, struct blasfeo_dmat* B_mat, - struct blasfeo_dmat* K_mat, struct blasfeo_dmat* W_mat, - struct blasfeo_dmat* AK_mat, struct blasfeo_dmat* temp_AP_mat, int nx, int nu) -{ - // AK_mat = -B@K + A - blasfeo_dgemm_nn(nx, nx, nu, -1.0, B_mat, 0, 0, K_mat, 0, 0, - 1.0, A_mat, 0, 0, AK_mat, 0, 0); - // temp_AP_mat = AK_mat @ P_k - blasfeo_dgemm_nn(nx, nx, nx, 1.0, AK_mat, 0, 0, - P_mat, 0, 0, 0.0, - temp_AP_mat, 0, 0, temp_AP_mat, 0, 0); - // P_{k+1} = temp_AP_mat @ AK_mat^T + GWG_mat - blasfeo_dgemm_nt(nx, nx, nx, 1.0, temp_AP_mat, 0, 0, - AK_mat, 0, 0, 1.0, - W_mat, 0, 0, P_next_mat, 0, 0); -} - -static void reset_P0_matrix(ocp_nlp_dims *nlp_dims, struct blasfeo_dmat* P_mat, double* data) -{ - int nx = nlp_dims->nx[0]; - blasfeo_pack_dmat(nx, nx, data, nx, P_mat, 0, 0); -} - -static void uncertainty_propagate_and_update(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out, custom_memory *custom_mem) -{ - ocp_nlp_config *nlp_config = solver->config; - ocp_nlp_dims *nlp_dims = solver->dims; - - int N = nlp_dims->N; - int nx = nlp_dims->nx[0]; - int nu = nlp_dims->nu[0]; - int nx_sqr = nx*nx; - int nbx = {{ dims.nbx }}; - int nbu = {{ dims.nbu }}; - int ng = {{ dims.ng }}; - int nh = {{ dims.nh }}; - int ng_e = {{ dims.ng_e }}; - int nh_e = {{ dims.nh_e }}; - int nbx_e = {{ dims.nbx_e }}; - double backoff_scaling_gamma = {{ zoro_description.backoff_scaling_gamma }}; - - // First Stage - // NOTE: lbx_0 and ubx_0 should not be tightened. - // NOTE: lg_0 and ug_0 are not tightened. - // NOTE: lh_0 and uh_0 are not tightened. -{%- if zoro_description.nlbu_t + zoro_description.nubu_t > 0 %} - compute_KPK(&custom_mem->K_mat, &custom_mem->temp_KP_mat, - &custom_mem->temp_KPK_mat, &(custom_mem->uncertainty_matrix_buffer[0]), nx, nu); - -{%- if zoro_description.nlbu_t > 0 %} - // backoff lbu - {%- for it in zoro_description.idx_lbu_t %} - custom_mem->d_lbu_tightened[{{it}}] - = custom_mem->d_lbu[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_KPK_mat, - custom_mem->idxbu[{{it}}],custom_mem->idxbu[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbu", custom_mem->d_lbu_tightened); -{%- endif %} -{%- if zoro_description.nubu_t > 0 %} - // backoff ubu - {%- for it in zoro_description.idx_ubu_t %} - custom_mem->d_ubu_tightened[{{it}}] - = custom_mem->d_ubu[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_KPK_mat, - custom_mem->idxbu[{{it}}],custom_mem->idxbu[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubu", custom_mem->d_ubu_tightened); -{%- endif %} -{%- endif %} - // Middle Stages - // constraint tightening: for next stage based on dynamics of ii stage - // P[ii+1] = (A-B@K) @ P[ii] @ (A-B@K).T + G@W@G.T - for (int ii = 0; ii < N-1; ii++) - { - // get and pack: A, B - ocp_nlp_get_at_stage(nlp_config, nlp_dims, solver, ii, "A", custom_mem->d_A_mat); - blasfeo_pack_dmat(nx, nx, custom_mem->d_A_mat, nx, &custom_mem->A_mat, 0, 0); - ocp_nlp_get_at_stage(nlp_config, nlp_dims, solver, ii, "B", custom_mem->d_B_mat); - blasfeo_pack_dmat(nx, nu, custom_mem->d_B_mat, nx, &custom_mem->B_mat, 0, 0); - - compute_next_P_matrix(&(custom_mem->uncertainty_matrix_buffer[ii]), - &(custom_mem->uncertainty_matrix_buffer[ii+1]), - &custom_mem->A_mat, &custom_mem->B_mat, - &custom_mem->K_mat, &custom_mem->GWG_mat, - &custom_mem->AK_mat, &custom_mem->temp_AP_mat, nx, nu); - - // state constraints -{%- if zoro_description.nlbx_t + zoro_description.nubx_t> 0 %} - {%- if zoro_description.nlbx_t > 0 %} - // lbx - {%- for it in zoro_description.idx_lbx_t %} - custom_mem->d_lbx_tightened[{{it}}] - = custom_mem->d_lbx[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->uncertainty_matrix_buffer[ii+1], - custom_mem->idxbx[{{it}}],custom_mem->idxbx[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "lbx", custom_mem->d_lbx_tightened); - {%- endif %} - {% if zoro_description.nubx_t > 0 %} - // ubx - {%- for it in zoro_description.idx_ubx_t %} - custom_mem->d_ubx_tightened[{{it}}] = custom_mem->d_ubx[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->uncertainty_matrix_buffer[ii+1], - custom_mem->idxbx[{{it}}],custom_mem->idxbx[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "ubx", custom_mem->d_ubx_tightened); - {%- endif %} -{%- endif %} - -{%- if zoro_description.nlbu_t + zoro_description.nubu_t > 0 %} - // input constraints - compute_KPK(&custom_mem->K_mat, &custom_mem->temp_KP_mat, - &custom_mem->temp_KPK_mat, &(custom_mem->uncertainty_matrix_buffer[ii+1]), nx, nu); - - {%- if zoro_description.nlbu_t > 0 %} - {%- for it in zoro_description.idx_lbu_t %} - custom_mem->d_lbu_tightened[{{it}}] = custom_mem->d_lbu[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_KPK_mat, - custom_mem->idxbu[{{it}}], custom_mem->idxbu[{{it}}])); - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "lbu", custom_mem->d_lbu_tightened); - {%- endif %} - {%- if zoro_description.nubu_t > 0 %} - {%- for it in zoro_description.idx_ubu_t %} - custom_mem->d_ubu_tightened[{{it}}] = custom_mem->d_ubu[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_KPK_mat, - custom_mem->idxbu[{{it}}], custom_mem->idxbu[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "ubu", custom_mem->d_ubu_tightened); - {%- endif %} -{%- endif %} - -{%- if zoro_description.nlg_t + zoro_description.nug_t > 0 %} - // Linear constraints: g - compute_gh_beta(&custom_mem->K_mat, &custom_mem->Cg_mat, - &custom_mem->Dg_mat, &custom_mem->temp_CaDK_mat, - &custom_mem->temp_CaDKmP_mat, &custom_mem->temp_beta_mat, - &custom_mem->uncertainty_matrix_buffer[ii+1], ng, nx, nu); - - {%- if zoro_description.nlg_t > 0 %} - {%- for it in zoro_description.idx_lg_t %} - custom_mem->d_lg_tightened[{{it}}] - = custom_mem->d_lg[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "lg", custom_mem->d_lg_tightened); - {%- endif %} - {%- if zoro_description.nug_t > 0 %} - {%- for it in zoro_description.idx_ug_t %} - custom_mem->d_ug_tightened[{{it}}] - = custom_mem->d_ug[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "ug", custom_mem->d_ug_tightened); - {%- endif %} -{%- endif %} - - -{%- if zoro_description.nlh_t + zoro_description.nuh_t > 0 %} - // nonlinear constraints: h - // Get C_{k+1} and D_{k+1} - ocp_nlp_get_at_stage(solver->config, nlp_dims, solver, ii+1, "C", custom_mem->d_Cgh_mat); - ocp_nlp_get_at_stage(solver->config, nlp_dims, solver, ii+1, "D", custom_mem->d_Dgh_mat); - // NOTE: the d_Cgh_mat is column-major, the first ng rows are the Jacobians of the linear constraints - blasfeo_pack_dmat(nh, nx, custom_mem->d_Cgh_mat+ng, ng+nh, &custom_mem->Ch_mat, 0, 0); - blasfeo_pack_dmat(nh, nu, custom_mem->d_Dgh_mat+ng, ng+nh, &custom_mem->Dh_mat, 0, 0); - - compute_gh_beta(&custom_mem->K_mat, &custom_mem->Ch_mat, - &custom_mem->Dh_mat, &custom_mem->temp_CaDK_mat, - &custom_mem->temp_CaDKmP_mat, &custom_mem->temp_beta_mat, - &custom_mem->uncertainty_matrix_buffer[ii+1], nh, nx, nu); - - {%- if zoro_description.nlh_t > 0 %} - {%- for it in zoro_description.idx_lh_t %} - custom_mem->d_lh_tightened[{{it}}] - = custom_mem->d_lh[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "lh", custom_mem->d_lh_tightened); - {%- endif %} - {%- if zoro_description.nuh_t > 0 %} - {%- for it in zoro_description.idx_uh_t %} - custom_mem->d_uh_tightened[{{it}}] = custom_mem->d_uh[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "uh", custom_mem->d_uh_tightened); - {%- endif %} -{%- endif %} - } - - // Last stage - // get and pack: A, B - ocp_nlp_get_at_stage(nlp_config, nlp_dims, solver, N-1, "A", custom_mem->d_A_mat); - blasfeo_pack_dmat(nx, nx, custom_mem->d_A_mat, nx, &custom_mem->A_mat, 0, 0); - ocp_nlp_get_at_stage(nlp_config, nlp_dims, solver, N-1, "B", custom_mem->d_B_mat); - blasfeo_pack_dmat(nx, nu, custom_mem->d_B_mat, nx, &custom_mem->B_mat, 0, 0); - // AK_mat = -B*K + A - compute_next_P_matrix(&(custom_mem->uncertainty_matrix_buffer[N-1]), - &(custom_mem->uncertainty_matrix_buffer[N]), - &custom_mem->A_mat, &custom_mem->B_mat, - &custom_mem->K_mat, &custom_mem->GWG_mat, - &custom_mem->AK_mat, &custom_mem->temp_AP_mat, nx, nu); - - // state constraints nlbx_e_t -{%- if zoro_description.nlbx_e_t + zoro_description.nubx_e_t> 0 %} -{%- if zoro_description.nlbx_e_t > 0 %} - // lbx_e - {%- for it in zoro_description.idx_lbx_e_t %} - custom_mem->d_lbx_e_tightened[{{it}}] - = custom_mem->d_lbx_e[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->uncertainty_matrix_buffer[N], - custom_mem->idxbx_e[{{it}}],custom_mem->idxbx_e[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lbx", custom_mem->d_lbx_e_tightened); -{%- endif %} -{% if zoro_description.nubx_e_t > 0 %} - // ubx_e - {%- for it in zoro_description.idx_ubx_e_t %} - custom_mem->d_ubx_e_tightened[{{it}}] = custom_mem->d_ubx_e[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->uncertainty_matrix_buffer[N], - custom_mem->idxbx_e[{{it}}],custom_mem->idxbx_e[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ubx", custom_mem->d_ubx_e_tightened); -{%- endif %} -{%- endif %} - -{%- if zoro_description.nlg_e_t + zoro_description.nug_e_t > 0 %} - // Linear constraints: g - compute_gh_beta(&custom_mem->K_mat, &custom_mem->Cg_mat, - &custom_mem->dummy_Dgh_e_mat, &custom_mem->temp_CaDK_mat, - &custom_mem->temp_CaDKmP_mat, &custom_mem->temp_beta_mat, - &custom_mem->uncertainty_matrix_buffer[N], ng, nx, nu); - -{%- if zoro_description.nlg_e_t > 0 %} - {%- for it in zoro_description.idx_lg_e_t %} - custom_mem->d_lg_e_tightened[{{it}}] - = custom_mem->d_lg_e[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lg", custom_mem->d_lg_e_tightened); -{%- endif %} -{%- if zoro_description.nug_e_t > 0 %} - {%- for it in zoro_description.idx_ug_e_t %} - custom_mem->d_ug_e_tightened[{{it}}] - = custom_mem->d_ug_e[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ug", custom_mem->d_ug_e_tightened); -{%- endif %} -{%- endif %} - - -{%- if zoro_description.nlh_e_t + zoro_description.nuh_e_t > 0 %} - // nonlinear constraints: h - // Get C_{k+1} and D_{k+1} - ocp_nlp_get_at_stage(solver->config, nlp_dims, solver, N, "C", custom_mem->d_Cgh_mat); - // NOTE: the d_Cgh_mat is column-major, the first ng rows are the Jacobians of the linear constraints - blasfeo_pack_dmat(nh, nx, custom_mem->d_Cgh_mat+ng, ng+nh, &custom_mem->Ch_mat, 0, 0); - - compute_gh_beta(&custom_mem->K_mat, &custom_mem->Ch_mat, - &custom_mem->dummy_Dgh_e_mat, &custom_mem->temp_CaDK_mat, - &custom_mem->temp_CaDKmP_mat, &custom_mem->temp_beta_mat, - &custom_mem->uncertainty_matrix_buffer[N], nh, nx, nu); - - {%- if zoro_description.nlh_e_t > 0 %} - {%- for it in zoro_description.idx_lh_e_t %} - custom_mem->d_lh_e_tightened[{{it}}] - = custom_mem->d_lh_e[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lh", custom_mem->d_lh_e_tightened); - {%- endif %} - {%- if zoro_description.nuh_e_t > 0 %} - {%- for it in zoro_description.idx_uh_e_t %} - custom_mem->d_uh_e_tightened[{{it}}] = custom_mem->d_uh_e[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uh", custom_mem->d_uh_e_tightened); - {%- endif %} -{%- endif %} - -} - - -int custom_update_function({{ model.name }}_solver_capsule* capsule, double* data, int data_len) -{ - custom_memory *custom_mem = (custom_memory *) capsule->custom_update_memory; - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(capsule); - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(capsule); - ocp_nlp_out *nlp_out = {{ model.name }}_acados_get_nlp_out(capsule); - ocp_nlp_solver *nlp_solver = {{ model.name }}_acados_get_nlp_solver(capsule); - void *nlp_opts = {{ model.name }}_acados_get_nlp_opts(capsule); - - if (data_len > 0) - { - reset_P0_matrix(nlp_dims, &custom_mem->uncertainty_matrix_buffer[0], data); - } - uncertainty_propagate_and_update(nlp_solver, nlp_in, nlp_out, custom_mem); - - return 1; -} - - -int custom_update_terminate_function({{ model.name }}_solver_capsule* capsule) -{ - custom_memory *mem = capsule->custom_update_memory; - - free(mem->raw_memory); - return 1; -} - -// useful prints for debugging - -/* -printf("A_mat:\n"); -blasfeo_print_exp_dmat(nx, nx, &custom_mem->A_mat, 0, 0); -printf("B_mat:\n"); -blasfeo_print_exp_dmat(nx, nu, &custom_mem->B_mat, 0, 0); -printf("K_mat:\n"); -blasfeo_print_exp_dmat(nu, nx, &custom_mem->K_mat, 0, 0); -printf("AK_mat:\n"); -blasfeo_print_exp_dmat(nx, nx, &custom_mem->AK_mat, 0, 0); -printf("temp_AP_mat:\n"); -blasfeo_print_exp_dmat(nx, nx, &custom_mem->temp_AP_mat, 0, 0); -printf("W_mat:\n"); -blasfeo_print_exp_dmat(nx, nx, &custom_mem->W_mat, 0, 0); -printf("P_k+1:\n"); -blasfeo_print_exp_dmat(nx, nx, &(custom_mem->uncertainty_matrix_buffer[ii+1]), 0, 0);*/ \ No newline at end of file diff --git a/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.h b/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.h deleted file mode 100644 index 9611ea210c9578..00000000000000 --- a/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -#include "acados_solver_{{ model.name }}.h" - -// Called at the end of solver creation. -// This is allowed to allocate memory and store the pointer to it into capsule->custom_update_memory. -int custom_update_init_function({{ model.name }}_solver_capsule* capsule); - - -// Custom update function that can be called between solver calls -int custom_update_function({{ model.name }}_solver_capsule* capsule, double* data, int data_len); - - -// Called just before destroying the solver. -// Responsible to free allocated memory, stored at capsule->custom_update_memory. -int custom_update_terminate_function({{ model.name }}_solver_capsule* capsule); diff --git a/third_party/acados/acados_template/gnsf/check_reformulation.py b/third_party/acados/acados_template/gnsf/check_reformulation.py deleted file mode 100644 index 2bdfbbc3363a61..00000000000000 --- a/third_party/acados/acados_template/gnsf/check_reformulation.py +++ /dev/null @@ -1,216 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -from acados_template.utils import casadi_length -from casadi import * -import numpy as np - - -def check_reformulation(model, gnsf, print_info): - - ## Description: - # this function takes the implicit ODE/ index-1 DAE and a gnsf structure - # to evaluate both models at num_eval random points x0, x0dot, z0, u0 - # if for all points the relative error is <= TOL, the function will return:: - # 1, otherwise it will give an error. - - TOL = 1e-14 - num_eval = 10 - - # get dimensions - nx = gnsf["nx"] - nu = gnsf["nu"] - nz = gnsf["nz"] - nx1 = gnsf["nx1"] - nx2 = gnsf["nx2"] - nz1 = gnsf["nz1"] - nz2 = gnsf["nz2"] - n_out = gnsf["n_out"] - - # get model matrices - A = gnsf["A"] - B = gnsf["B"] - C = gnsf["C"] - E = gnsf["E"] - c = gnsf["c"] - - L_x = gnsf["L_x"] - L_xdot = gnsf["L_xdot"] - L_z = gnsf["L_z"] - L_u = gnsf["L_u"] - - A_LO = gnsf["A_LO"] - E_LO = gnsf["E_LO"] - B_LO = gnsf["B_LO"] - c_LO = gnsf["c_LO"] - - I_x1 = range(nx1) - I_x2 = range(nx1, nx) - - I_z1 = range(nz1) - I_z2 = range(nz1, nz) - - idx_perm_f = gnsf["idx_perm_f"] - - # get casadi variables - x = gnsf["x"] - xdot = gnsf["xdot"] - z = gnsf["z"] - u = gnsf["u"] - y = gnsf["y"] - uhat = gnsf["uhat"] - p = gnsf["p"] - - # create functions - impl_dae_fun = Function("impl_dae_fun", [x, xdot, u, z, p], [model.f_impl_expr]) - phi_fun = Function("phi_fun", [y, uhat, p], [gnsf["phi_expr"]]) - f_lo_fun = Function( - "f_lo_fun", [x[range(nx1)], xdot[range(nx1)], z, u, p], [gnsf["f_lo_expr"]] - ) - - # print(gnsf) - # print(gnsf["n_out"]) - - for i_check in range(num_eval): - # generate random values - x0 = np.random.rand(nx, 1) - x0dot = np.random.rand(nx, 1) - z0 = np.random.rand(nz, 1) - u0 = np.random.rand(nu, 1) - - if gnsf["ny"] > 0: - y0 = L_x @ x0[I_x1] + L_xdot @ x0dot[I_x1] + L_z @ z0[I_z1] - else: - y0 = [] - if gnsf["nuhat"] > 0: - uhat0 = L_u @ u0 - else: - uhat0 = [] - - # eval functions - p0 = np.random.rand(gnsf["np"], 1) - f_impl_val = impl_dae_fun(x0, x0dot, u0, z0, p0).full() - phi_val = phi_fun(y0, uhat0, p0) - f_lo_val = f_lo_fun(x0[I_x1], x0dot[I_x1], z0[I_z1], u0, p0) - - f_impl_val = f_impl_val[idx_perm_f] - # eval gnsf - if n_out > 0: - C_phi = C @ phi_val - else: - C_phi = np.zeros((nx1 + nz1, 1)) - try: - gnsf_val1 = ( - A @ x0[I_x1] + B @ u0 + C_phi + c - E @ vertcat(x0dot[I_x1], z0[I_z1]) - ) - # gnsf_1 = (A @ x[I_x1] + B @ u + C_phi + c - E @ vertcat(xdot[I_x1], z[I_z1])) - except: - import pdb - - pdb.set_trace() - - if nx2 > 0: # eval LOS: - gnsf_val2 = ( - A_LO @ x0[I_x2] - + B_LO @ u0 - + c_LO - + f_lo_val - - E_LO @ vertcat(x0dot[I_x2], z0[I_z2]) - ) - gnsf_val = vertcat(gnsf_val1, gnsf_val2).full() - else: - gnsf_val = gnsf_val1.full() - # compute error and check - rel_error = np.linalg.norm(f_impl_val - gnsf_val) / np.linalg.norm(f_impl_val) - - if rel_error > TOL: - print("transcription failed rel_error > TOL") - print("you are in debug mode now: import pdb; pdb.set_trace()") - abs_error = gnsf_val - f_impl_val - # T = table(f_impl_val, gnsf_val, abs_error) - # print(T) - print("abs_error:", abs_error) - # error('transcription failed rel_error > TOL') - # check = 0 - import pdb - - pdb.set_trace() - if print_info: - print(" ") - print("model reformulation checked: relative error <= TOL = ", str(TOL)) - print(" ") - check = 1 - ## helpful for debugging: - # # use in calling function and compare - # # compare f_impl(i) with gnsf_val1(i) - # - - # nx = gnsf['nx'] - # nu = gnsf['nu'] - # nz = gnsf['nz'] - # nx1 = gnsf['nx1'] - # nx2 = gnsf['nx2'] - # - # A = gnsf['A'] - # B = gnsf['B'] - # C = gnsf['C'] - # E = gnsf['E'] - # c = gnsf['c'] - # - # L_x = gnsf['L_x'] - # L_z = gnsf['L_z'] - # L_xdot = gnsf['L_xdot'] - # L_u = gnsf['L_u'] - # - # A_LO = gnsf['A_LO'] - # - # x0 = rand(nx, 1) - # x0dot = rand(nx, 1) - # z0 = rand(nz, 1) - # u0 = rand(nu, 1) - # I_x1 = range(nx1) - # I_x2 = nx1+range(nx) - # - # y0 = L_x @ x0[I_x1] + L_xdot @ x0dot[I_x1] + L_z @ z0 - # uhat0 = L_u @ u0 - # - # gnsf_val1 = (A @ x[I_x1] + B @ u + # C @ phi_current + c) - E @ [xdot[I_x1] z] - # gnsf_val1 = gnsf_val1.simplify() - # - # # gnsf_val2 = A_LO @ x[I_x2] + gnsf['f_lo_fun'](x[I_x1], xdot[I_x1], z, u) - xdot[I_x2] - # gnsf_val2 = A_LO @ x[I_x2] + gnsf['f_lo_fun'](x[I_x1], xdot[I_x1], z, u) - xdot[I_x2] - # - # - # gnsf_val = [gnsf_val1 gnsf_val2] - # gnsf_val = gnsf_val.simplify() - # dyn_expr_f = dyn_expr_f.simplify() - # import pdb; pdb.set_trace() - - return check diff --git a/third_party/acados/acados_template/gnsf/detect_affine_terms_reduce_nonlinearity.py b/third_party/acados/acados_template/gnsf/detect_affine_terms_reduce_nonlinearity.py deleted file mode 100644 index ebf1f373a44665..00000000000000 --- a/third_party/acados/acados_template/gnsf/detect_affine_terms_reduce_nonlinearity.py +++ /dev/null @@ -1,278 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -from casadi import * -from .check_reformulation import check_reformulation -from .determine_input_nonlinearity_function import determine_input_nonlinearity_function -from ..utils import casadi_length, print_casadi_expression - - -def detect_affine_terms_reduce_nonlinearity(gnsf, acados_ocp, print_info): - - ## Description - # this function takes a gnsf structure with trivial model matrices (A, B, - # E, c are zeros, and C is eye). - # It detects all affine linear terms and sets up an equivalent model in the - # GNSF structure, where all affine linear terms are modeled through the - # matrices A, B, E, c and the linear output system (LOS) is empty. - # NOTE: model is just taken as an argument to check equivalence of the - # models within the function. - - model = acados_ocp.model - if print_info: - print(" ") - print("====================================================================") - print(" ") - print("============ Detect affine-linear dependencies ==================") - print(" ") - print("====================================================================") - print(" ") - # symbolics - x = gnsf["x"] - xdot = gnsf["xdot"] - u = gnsf["u"] - z = gnsf["z"] - - # dimensions - nx = gnsf["nx"] - nu = gnsf["nu"] - nz = gnsf["nz"] - - ny_old = gnsf["ny"] - nuhat_old = gnsf["nuhat"] - - ## Represent all affine dependencies through the model matrices A, B, E, c - ## determine A - n_nodes_current = n_nodes(gnsf["phi_expr"]) - - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - for ix in range(nx): - var = x[ix] - varname = var.name - # symbolic jacobian of fii w.r.t. xi - jac_fii_xi = jacobian(fii, var) - if jac_fii_xi.is_constant(): - # jacobian value - jac_fii_xi_fun = Function("jac_fii_xi_fun", [x[1]], [jac_fii_xi]) - # x[1] as input just to have a scalar input and call the function as follows: - gnsf["A"][ii, ix] = jac_fii_xi_fun(0).full() - else: - gnsf["A"][ii, ix] = 0 - if print_info: - print( - "phi(", - str(ii), - ") is nonlinear in x(", - str(ix), - ") = ", - varname, - ) - print(fii) - print("-----------------------------------------------------") - f_next = gnsf["phi_expr"] - gnsf["A"] @ x - f_next = simplify(f_next) - n_nodes_next = n_nodes(f_next) - - if print_info: - print("\n") - print(f"determined matrix A:") - print(gnsf["A"]) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - # assert(n_nodes_current >= n_nodes_next,'n_nodes_current >= n_nodes_next FAILED') - gnsf["phi_expr"] = f_next - - check_reformulation(model, gnsf, print_info) - - ## determine B - n_nodes_current = n_nodes(gnsf["phi_expr"]) - - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - for iu in range(nu): - var = u[iu] - varname = var.name - # symbolic jacobian of fii w.r.t. ui - jac_fii_ui = jacobian(fii, var) - if jac_fii_ui.is_constant(): # i.e. hessian is structural zero: - # jacobian value - jac_fii_ui_fun = Function("jac_fii_ui_fun", [x[1]], [jac_fii_ui]) - gnsf["B"][ii, iu] = jac_fii_ui_fun(0).full() - else: - gnsf["B"][ii, iu] = 0 - if print_info: - print(f"phi({ii}) is nonlinear in u(", str(iu), ") = ", varname) - print(fii) - print("-----------------------------------------------------") - f_next = gnsf["phi_expr"] - gnsf["B"] @ u - f_next = simplify(f_next) - n_nodes_next = n_nodes(f_next) - - if print_info: - print("\n") - print(f"determined matrix B:") - print(gnsf["B"]) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - - gnsf["phi_expr"] = f_next - - check_reformulation(model, gnsf, print_info) - - ## determine E - n_nodes_current = n_nodes(gnsf["phi_expr"]) - k = vertcat(xdot, z) - - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - for ik in range(casadi_length(k)): - # symbolic jacobian of fii w.r.t. ui - var = k[ik] - varname = var.name - jac_fii_ki = jacobian(fii, var) - if jac_fii_ki.is_constant(): - # jacobian value - jac_fii_ki_fun = Function("jac_fii_ki_fun", [x[1]], [jac_fii_ki]) - gnsf["E"][ii, ik] = -jac_fii_ki_fun(0).full() - else: - gnsf["E"][ii, ik] = 0 - if print_info: - print(f"phi( {ii}) is nonlinear in xdot_z({ik}) = ", varname) - print(fii) - print("-----------------------------------------------------") - f_next = gnsf["phi_expr"] + gnsf["E"] @ k - f_next = simplify(f_next) - n_nodes_next = n_nodes(f_next) - - if print_info: - print("\n") - print(f"determined matrix E:") - print(gnsf["E"]) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - - gnsf["phi_expr"] = f_next - check_reformulation(model, gnsf, print_info) - - ## determine constant term c - - n_nodes_current = n_nodes(gnsf["phi_expr"]) - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - if fii.is_constant(): - # function value goes into c - fii_fun = Function("fii_fun", [x[1]], [fii]) - gnsf["c"][ii] = fii_fun(0).full() - else: - gnsf["c"][ii] = 0 - if print_info: - print(f"phi(", str(ii), ") is NOT constant") - print(fii) - print("-----------------------------------------------------") - gnsf["phi_expr"] = gnsf["phi_expr"] - gnsf["c"] - gnsf["phi_expr"] = simplify(gnsf["phi_expr"]) - n_nodes_next = n_nodes(gnsf["phi_expr"]) - - if print_info: - print("\n") - print(f"determined vector c:") - print(gnsf["c"]) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - - check_reformulation(model, gnsf, print_info) - - ## determine nonlinearity & corresponding matrix C - ## Reduce dimension of phi - n_nodes_current = n_nodes(gnsf["phi_expr"]) - ind_non_zero = [] - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - fii = simplify(fii) - if not fii.is_zero(): - ind_non_zero = list(set.union(set(ind_non_zero), set([ii]))) - gnsf["phi_expr"] = gnsf["phi_expr"][ind_non_zero] - - # C - gnsf["C"] = np.zeros((nx + nz, len(ind_non_zero))) - for ii in range(len(ind_non_zero)): - gnsf["C"][ind_non_zero[ii], ii] = 1 - gnsf = determine_input_nonlinearity_function(gnsf) - n_nodes_next = n_nodes(gnsf["phi_expr"]) - - if print_info: - print(" ") - print("determined matrix C:") - print(gnsf["C"]) - print( - "---------------------------------------------------------------------------------" - ) - print( - "------------- Success: Affine linear terms detected -----------------------------" - ) - print( - "---------------------------------------------------------------------------------" - ) - print( - f'reduced nonlinearity dimension n_out from {nx+nz} to {gnsf["n_out"]}' - ) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - print(" ") - print("phi now reads as:") - print_casadi_expression(gnsf["phi_expr"]) - - ## determine input of nonlinearity function - check_reformulation(model, gnsf, print_info) - - gnsf["ny"] = casadi_length(gnsf["y"]) - gnsf["nuhat"] = casadi_length(gnsf["uhat"]) - - if print_info: - print( - "-----------------------------------------------------------------------------------" - ) - print(" ") - print( - f"reduced input ny of phi from ", - str(ny_old), - " to ", - str(gnsf["ny"]), - ) - print( - f"reduced input nuhat of phi from ", - str(nuhat_old), - " to ", - str(gnsf["nuhat"]), - ) - print( - "-----------------------------------------------------------------------------------" - ) - - # if print_info: - # print(f"gnsf: {gnsf}") - - return gnsf diff --git a/third_party/acados/acados_template/gnsf/detect_gnsf_structure.py b/third_party/acados/acados_template/gnsf/detect_gnsf_structure.py deleted file mode 100644 index 24ffe643b8ac2a..00000000000000 --- a/third_party/acados/acados_template/gnsf/detect_gnsf_structure.py +++ /dev/null @@ -1,240 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from casadi import Function, jacobian, SX, vertcat, horzcat - -from .determine_trivial_gnsf_transcription import determine_trivial_gnsf_transcription -from .detect_affine_terms_reduce_nonlinearity import ( - detect_affine_terms_reduce_nonlinearity, -) -from .reformulate_with_LOS import reformulate_with_LOS -from .reformulate_with_invertible_E_mat import reformulate_with_invertible_E_mat -from .structure_detection_print_summary import structure_detection_print_summary -from .check_reformulation import check_reformulation - - -def detect_gnsf_structure(acados_ocp, transcribe_opts=None): - - ## Description - # This function takes a CasADi implicit ODE or index-1 DAE model "model" - # consisting of a CasADi expression f_impl in the symbolic CasADi - # variables x, xdot, u, z, (and possibly parameters p), which are also part - # of the model, as well as a model name. - # It will create a struct "gnsf" containing all information needed to use - # it with the gnsf integrator in acados. - # Additionally it will create the struct "reordered_model" which contains - # the permuted state vector and permuted f_impl, in which additionally some - # functions, which were made part of the linear output system of the gnsf, - # have changed signs. - - # Options: transcribe_opts is a Matlab struct consisting of booleans: - # print_info: if extensive information on how the model is processed - # is printed to the console. - # generate_gnsf_model: if the neccessary C functions to simulate the gnsf - # model with the acados implementation of the GNSF exploiting - # integrator should be generated. - # generate_gnsf_model: if the neccessary C functions to simulate the - # reordered model with the acados implementation of the IRK - # integrator should be generated. - # check_E_invertibility: if the transcription method should check if the - # assumption that the main blocks of the matrix gnsf.E are invertible - # holds. If not, the method will try to reformulate the gnsf model - # with a different model, such that the assumption holds. - - # acados_root_dir = getenv('ACADOS_INSTALL_DIR') - - ## load transcribe_opts - if transcribe_opts is None: - print("WARNING: GNSF structure detection called without transcribe_opts") - print(" using default settings") - print("") - transcribe_opts = dict() - - if "print_info" in transcribe_opts: - print_info = transcribe_opts["print_info"] - else: - print_info = 1 - print("print_info option was not set - default is true") - - if "detect_LOS" in transcribe_opts: - detect_LOS = transcribe_opts["detect_LOS"] - else: - detect_LOS = 1 - if print_info: - print("detect_LOS option was not set - default is true") - - if "check_E_invertibility" in transcribe_opts: - check_E_invertibility = transcribe_opts["check_E_invertibility"] - else: - check_E_invertibility = 1 - if print_info: - print("check_E_invertibility option was not set - default is true") - - ## Reformulate implicit index-1 DAE into GNSF form - # (Generalized nonlinear static feedback) - gnsf = determine_trivial_gnsf_transcription(acados_ocp, print_info) - gnsf = detect_affine_terms_reduce_nonlinearity(gnsf, acados_ocp, print_info) - - if detect_LOS: - gnsf = reformulate_with_LOS(acados_ocp, gnsf, print_info) - - if check_E_invertibility: - gnsf = reformulate_with_invertible_E_mat(gnsf, acados_ocp, print_info) - - # detect purely linear model - if gnsf["nx1"] == 0 and gnsf["nz1"] == 0 and gnsf["nontrivial_f_LO"] == 0: - gnsf["purely_linear"] = 1 - else: - gnsf["purely_linear"] = 0 - - structure_detection_print_summary(gnsf, acados_ocp) - check_reformulation(acados_ocp.model, gnsf, print_info) - - ## copy relevant fields from gnsf to model - acados_ocp.model.get_matrices_fun = Function() - dummy = acados_ocp.model.x[0] - model_name = acados_ocp.model.name - - get_matrices_fun = Function( - f"{model_name}_gnsf_get_matrices_fun", - [dummy], - [ - gnsf["A"], - gnsf["B"], - gnsf["C"], - gnsf["E"], - gnsf["L_x"], - gnsf["L_xdot"], - gnsf["L_z"], - gnsf["L_u"], - gnsf["A_LO"], - gnsf["c"], - gnsf["E_LO"], - gnsf["B_LO"], - gnsf["nontrivial_f_LO"], - gnsf["purely_linear"], - gnsf["ipiv_x"] + 1, - gnsf["ipiv_z"] + 1, - gnsf["c_LO"], - ], - ) - - phi = gnsf["phi_expr"] - y = gnsf["y"] - uhat = gnsf["uhat"] - p = gnsf["p"] - - jac_phi_y = jacobian(phi, y) - jac_phi_uhat = jacobian(phi, uhat) - - phi_fun = Function(f"{model_name}_gnsf_phi_fun", [y, uhat, p], [phi]) - acados_ocp.model.phi_fun = phi_fun - acados_ocp.model.phi_fun_jac_y = Function( - f"{model_name}_gnsf_phi_fun_jac_y", [y, uhat, p], [phi, jac_phi_y] - ) - acados_ocp.model.phi_jac_y_uhat = Function( - f"{model_name}_gnsf_phi_jac_y_uhat", [y, uhat, p], [jac_phi_y, jac_phi_uhat] - ) - - x1 = acados_ocp.model.x[gnsf["idx_perm_x"][: gnsf["nx1"]]] - x1dot = acados_ocp.model.xdot[gnsf["idx_perm_x"][: gnsf["nx1"]]] - if gnsf["nz1"] > 0: - z1 = acados_ocp.model.z[gnsf["idx_perm_z"][: gnsf["nz1"]]] - else: - z1 = SX.sym("z1", 0, 0) - f_lo = gnsf["f_lo_expr"] - u = acados_ocp.model.u - acados_ocp.model.f_lo_fun_jac_x1k1uz = Function( - f"{model_name}_gnsf_f_lo_fun_jac_x1k1uz", - [x1, x1dot, z1, u, p], - [ - f_lo, - horzcat( - jacobian(f_lo, x1), - jacobian(f_lo, x1dot), - jacobian(f_lo, u), - jacobian(f_lo, z1), - ), - ], - ) - - acados_ocp.model.get_matrices_fun = get_matrices_fun - - size_gnsf_A = gnsf["A"].shape - acados_ocp.dims.gnsf_nx1 = size_gnsf_A[1] - acados_ocp.dims.gnsf_nz1 = size_gnsf_A[0] - size_gnsf_A[1] - acados_ocp.dims.gnsf_nuhat = max(phi_fun.size_in(1)) - acados_ocp.dims.gnsf_ny = max(phi_fun.size_in(0)) - acados_ocp.dims.gnsf_nout = max(phi_fun.size_out(0)) - - # # dim - # model['dim_gnsf_nx1'] = gnsf['nx1'] - # model['dim_gnsf_nx2'] = gnsf['nx2'] - # model['dim_gnsf_nz1'] = gnsf['nz1'] - # model['dim_gnsf_nz2'] = gnsf['nz2'] - # model['dim_gnsf_nuhat'] = gnsf['nuhat'] - # model['dim_gnsf_ny'] = gnsf['ny'] - # model['dim_gnsf_nout'] = gnsf['n_out'] - - # # sym - # model['sym_gnsf_y'] = gnsf['y'] - # model['sym_gnsf_uhat'] = gnsf['uhat'] - - # # data - # model['dyn_gnsf_A'] = gnsf['A'] - # model['dyn_gnsf_A_LO'] = gnsf['A_LO'] - # model['dyn_gnsf_B'] = gnsf['B'] - # model['dyn_gnsf_B_LO'] = gnsf['B_LO'] - # model['dyn_gnsf_E'] = gnsf['E'] - # model['dyn_gnsf_E_LO'] = gnsf['E_LO'] - # model['dyn_gnsf_C'] = gnsf['C'] - # model['dyn_gnsf_c'] = gnsf['c'] - # model['dyn_gnsf_c_LO'] = gnsf['c_LO'] - # model['dyn_gnsf_L_x'] = gnsf['L_x'] - # model['dyn_gnsf_L_xdot'] = gnsf['L_xdot'] - # model['dyn_gnsf_L_z'] = gnsf['L_z'] - # model['dyn_gnsf_L_u'] = gnsf['L_u'] - # model['dyn_gnsf_idx_perm_x'] = gnsf['idx_perm_x'] - # model['dyn_gnsf_ipiv_x'] = gnsf['ipiv_x'] - # model['dyn_gnsf_idx_perm_z'] = gnsf['idx_perm_z'] - # model['dyn_gnsf_ipiv_z'] = gnsf['ipiv_z'] - # model['dyn_gnsf_idx_perm_f'] = gnsf['idx_perm_f'] - # model['dyn_gnsf_ipiv_f'] = gnsf['ipiv_f'] - - # # flags - # model['dyn_gnsf_nontrivial_f_LO'] = gnsf['nontrivial_f_LO'] - # model['dyn_gnsf_purely_linear'] = gnsf['purely_linear'] - - # # casadi expr - # model['dyn_gnsf_expr_phi'] = gnsf['phi_expr'] - # model['dyn_gnsf_expr_f_lo'] = gnsf['f_lo_expr'] - - return acados_ocp diff --git a/third_party/acados/acados_template/gnsf/determine_input_nonlinearity_function.py b/third_party/acados/acados_template/gnsf/determine_input_nonlinearity_function.py deleted file mode 100644 index 94aa001c79528d..00000000000000 --- a/third_party/acados/acados_template/gnsf/determine_input_nonlinearity_function.py +++ /dev/null @@ -1,110 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from casadi import * -from ..utils import casadi_length, is_empty - - -def determine_input_nonlinearity_function(gnsf): - - ## Description - # this function takes a structure gnsf and updates the matrices L_x, - # L_xdot, L_z, L_u and CasADi vectors y, uhat of this structure as follows: - - # given a CasADi expression phi_expr, which may depend on the variables - # (x1, x1dot, z, u), this function determines a vector y (uhat) consisting - # of all components of (x1, x1dot, z) (respectively u) that enter phi_expr. - # Additionally matrices L_x, L_xdot, L_z, L_u are determined such that - # y = L_x * x + L_xdot * xdot + L_z * z - # uhat = L_u * u - # Furthermore the dimensions ny, nuhat, n_out are updated - - ## y - y = SX.sym('y', 0, 0) - # components of x1 - for ii in range(gnsf["nx1"]): - if which_depends(gnsf["phi_expr"], gnsf["x"][ii])[0]: - y = vertcat(y, gnsf["x"][ii]) - # else: - # x[ii] is not part of y - # components of x1dot - for ii in range(gnsf["nx1"]): - if which_depends(gnsf["phi_expr"], gnsf["xdot"][ii])[0]: - print(gnsf["phi_expr"], "depends on", gnsf["xdot"][ii]) - y = vertcat(y, gnsf["xdot"][ii]) - # else: - # xdot[ii] is not part of y - # components of z - for ii in range(gnsf["nz1"]): - if which_depends(gnsf["phi_expr"], gnsf["z"][ii])[0]: - y = vertcat(y, gnsf["z"][ii]) - # else: - # z[ii] is not part of y - ## uhat - uhat = SX.sym('uhat', 0, 0) - # components of u - for ii in range(gnsf["nu"]): - if which_depends(gnsf["phi_expr"], gnsf["u"][ii])[0]: - uhat = vertcat(uhat, gnsf["u"][ii]) - # else: - # u[ii] is not part of uhat - ## generate gnsf['phi_expr_fun'] - # linear input matrices - if is_empty(y): - gnsf["L_x"] = [] - gnsf["L_xdot"] = [] - gnsf["L_u"] = [] - gnsf["L_z"] = [] - else: - dummy = SX.sym("dummy_input", 0) - L_x_fun = Function( - "L_x_fun", [dummy], [jacobian(y, gnsf["x"][range(gnsf["nx1"])])] - ) - L_xdot_fun = Function( - "L_xdot_fun", [dummy], [jacobian(y, gnsf["xdot"][range(gnsf["nx1"])])] - ) - L_z_fun = Function( - "L_z_fun", [dummy], [jacobian(y, gnsf["z"][range(gnsf["nz1"])])] - ) - L_u_fun = Function("L_u_fun", [dummy], [jacobian(uhat, gnsf["u"])]) - - gnsf["L_x"] = L_x_fun(0).full() - gnsf["L_xdot"] = L_xdot_fun(0).full() - gnsf["L_u"] = L_u_fun(0).full() - gnsf["L_z"] = L_z_fun(0).full() - gnsf["y"] = y - gnsf["uhat"] = uhat - - gnsf["ny"] = casadi_length(y) - gnsf["nuhat"] = casadi_length(uhat) - gnsf["n_out"] = casadi_length(gnsf["phi_expr"]) - - return gnsf diff --git a/third_party/acados/acados_template/gnsf/determine_trivial_gnsf_transcription.py b/third_party/acados/acados_template/gnsf/determine_trivial_gnsf_transcription.py deleted file mode 100644 index 23c2440537cdba..00000000000000 --- a/third_party/acados/acados_template/gnsf/determine_trivial_gnsf_transcription.py +++ /dev/null @@ -1,155 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -from casadi import * -import numpy as np -from ..utils import casadi_length, idx_perm_to_ipiv -from .determine_input_nonlinearity_function import determine_input_nonlinearity_function -from .check_reformulation import check_reformulation - - -def determine_trivial_gnsf_transcription(acados_ocp, print_info): - ## Description - # this function takes a model of an implicit ODE/ index-1 DAE and sets up - # an equivalent model in the GNSF structure, with empty linear output - # system and trivial model matrices, i.e. A, B, E, c are zeros, and C is - # eye. - no structure is exploited - - model = acados_ocp.model - # initial print - print("*****************************************************************") - print(" ") - print(f"****** Restructuring {model.name} model ***********") - print(" ") - print("*****************************************************************") - - # load model - f_impl_expr = model.f_impl_expr - - model_name_prefix = model.name - - # x - x = model.x - nx = acados_ocp.dims.nx - # check type - if isinstance(x[0], SX): - isSX = True - else: - print("GNSF detection only works for SX CasADi type!!!") - import pdb - - pdb.set_trace() - # xdot - xdot = model.xdot - # u - nu = acados_ocp.dims.nu - if nu == 0: - u = SX.sym("u", 0, 0) - else: - u = model.u - - nz = acados_ocp.dims.nz - if nz == 0: - z = SX.sym("z", 0, 0) - else: - z = model.z - - p = model.p - nparam = acados_ocp.dims.np - - # avoid SX of size 0x1 - if casadi_length(u) == 0: - u = SX.sym("u", 0, 0) - nu = 0 - ## initialize gnsf struct - # dimensions - gnsf = {"nx": nx, "nu": nu, "nz": nz, "np": nparam} - gnsf["nx1"] = nx - gnsf["nx2"] = 0 - gnsf["nz1"] = nz - gnsf["nz2"] = 0 - gnsf["nuhat"] = nu - gnsf["ny"] = 2 * nx + nz - - gnsf["phi_expr"] = f_impl_expr - gnsf["A"] = np.zeros((nx + nz, nx)) - gnsf["B"] = np.zeros((nx + nz, nu)) - gnsf["E"] = np.zeros((nx + nz, nx + nz)) - gnsf["c"] = np.zeros((nx + nz, 1)) - gnsf["C"] = np.eye(nx + nz) - gnsf["name"] = model_name_prefix - - gnsf["x"] = x - gnsf["xdot"] = xdot - gnsf["z"] = z - gnsf["u"] = u - gnsf["p"] = p - - gnsf = determine_input_nonlinearity_function(gnsf) - - gnsf["A_LO"] = [] - gnsf["E_LO"] = [] - gnsf["B_LO"] = [] - gnsf["c_LO"] = [] - gnsf["f_lo_expr"] = [] - - # permutation - gnsf["idx_perm_x"] = range(nx) # matlab-style) - gnsf["ipiv_x"] = idx_perm_to_ipiv(gnsf["idx_perm_x"]) # blasfeo-style - gnsf["idx_perm_z"] = range(nz) - gnsf["ipiv_z"] = idx_perm_to_ipiv(gnsf["idx_perm_z"]) - gnsf["idx_perm_f"] = range((nx + nz)) - gnsf["ipiv_f"] = idx_perm_to_ipiv(gnsf["idx_perm_f"]) - - gnsf["nontrivial_f_LO"] = 0 - - check_reformulation(model, gnsf, print_info) - if print_info: - print(f"Success: Set up equivalent GNSF model with trivial matrices") - print(" ") - if print_info: - print( - "-----------------------------------------------------------------------------------" - ) - print(" ") - print( - "reduced input ny of phi from ", - str(2 * nx + nz), - " to ", - str(gnsf["ny"]), - ) - print( - "reduced input nuhat of phi from ", str(nu), " to ", str(gnsf["nuhat"]) - ) - print(" ") - print( - "-----------------------------------------------------------------------------------" - ) - return gnsf diff --git a/third_party/acados/acados_template/gnsf/matlab to python.md b/third_party/acados/acados_template/gnsf/matlab to python.md deleted file mode 100644 index 53a0ed971e5b65..00000000000000 --- a/third_party/acados/acados_template/gnsf/matlab to python.md +++ /dev/null @@ -1,43 +0,0 @@ -# matlab to python - -% -> # - -; -> - -from casadi import * --> -from casadi import * - - -print\('(.*)'\) -print('$1') - -print\(\['(.*)'\]\) -print(f'$1') - -keyboard -import pdb; pdb.set_trace() - - -range((([^))]*)) -range($1) - -\s*end --> -nothing - - -if (.*) -if $1: - -else -else: - -num2str -str - -for ([a-z_]*) = -for $1 in - -length\( -len( \ No newline at end of file diff --git a/third_party/acados/acados_template/gnsf/reformulate_with_LOS.py b/third_party/acados/acados_template/gnsf/reformulate_with_LOS.py deleted file mode 100644 index 297a56556c477b..00000000000000 --- a/third_party/acados/acados_template/gnsf/reformulate_with_LOS.py +++ /dev/null @@ -1,394 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from .determine_input_nonlinearity_function import determine_input_nonlinearity_function -from .check_reformulation import check_reformulation -from casadi import * -from ..utils import casadi_length, idx_perm_to_ipiv, is_empty - - -def reformulate_with_LOS(acados_ocp, gnsf, print_info): - - ## Description: - # This function takes an intitial transcription of the implicit ODE model - # "model" into "gnsf" and reformulates "gnsf" with a linear output system - # (LOS), containing as many states of the model as possible. - # Therefore it might be that the state vector and the implicit function - # vector have to be reordered. This reordered model is part of the output, - # namely reordered_model. - - ## import CasADi and load models - model = acados_ocp.model - - # symbolics - x = gnsf["x"] - xdot = gnsf["xdot"] - u = gnsf["u"] - z = gnsf["z"] - - # dimensions - nx = gnsf["nx"] - nz = gnsf["nz"] - - # get model matrices - A = gnsf["A"] - B = gnsf["B"] - C = gnsf["C"] - E = gnsf["E"] - c = gnsf["c"] - - A_LO = gnsf["A_LO"] - - y = gnsf["y"] - - phi_old = gnsf["phi_expr"] - - if print_info: - print(" ") - print("=================================================================") - print(" ") - print("================ Detect Linear Output System ===============") - print(" ") - print("=================================================================") - print(" ") - ## build initial I_x1 and I_x2_candidates - # I_xrange( all components of x for which either xii or xdot_ii enters y): - # I_LOS_candidates: the remaining components - - I_nsf_components = set() - I_LOS_candidates = set() - - if gnsf["ny"] > 0: - for ii in range(nx): - if which_depends(y, x[ii])[0] or which_depends(y, xdot[ii])[0]: - # i.e. xii or xiidot are part of y, and enter phi_expr - if print_info: - print(f"x_{ii} is part of x1") - I_nsf_components = set.union(I_nsf_components, set([ii])) - else: - # i.e. neither xii nor xiidot are part of y, i.e. enter phi_expr - I_LOS_candidates = set.union(I_LOS_candidates, set([ii])) - if print_info: - print(" ") - for ii in range(nz): - if which_depends(y, z[ii])[0]: - # i.e. xii or xiidot are part of y, and enter phi_expr - if print_info: - print(f"z_{ii} is part of x1") - I_nsf_components = set.union(I_nsf_components, set([ii + nx])) - else: - # i.e. neither xii nor xiidot are part of y, i.e. enter phi_expr - I_LOS_candidates = set.union(I_LOS_candidates, set([ii + nx])) - else: - I_LOS_candidates = set(range((nx + nz))) - if print_info: - print(" ") - print(f"I_LOS_candidates {I_LOS_candidates}") - new_nsf_components = I_nsf_components - I_nsf_eq = set([]) - unsorted_dyn = set(range(nx + nz)) - xdot_z = vertcat(xdot, z) - - ## determine components of Linear Output System - # determine maximal index set I_x2 - # such that the components x(I_x2) can be written as a LOS - Eq_map = [] - while True: - ## find equations corresponding to new_nsf_components - for ii in new_nsf_components: - current_var = xdot_z[ii] - var_name = current_var.name - - # print( unsorted_dyn) - # print("np.nonzero(E[:,ii])[0]",np.nonzero(E[:,ii])[0]) - I_eq = set.intersection(set(np.nonzero(E[:, ii])[0]), unsorted_dyn) - if len(I_eq) == 1: - i_eq = I_eq.pop() - if print_info: - print(f"component {i_eq} is associated with state {ii}") - elif len(I_eq) > 1: # x_ii_dot occurs in more than 1 eq linearly - # find the equation with least linear dependencies on - # I_LOS_cancidates - number_of_eq = 0 - candidate_dependencies = np.zeros(len(I_eq), 1) - I_x2_candidates = set.intersection(I_LOS_candidates, set(range(nx))) - for eq in I_eq: - depending_candidates = set.union( - np.nonzero(E[eq, I_LOS_candidates])[0], - np.nonzero(A[eq, I_x2_candidates])[0], - ) - candidate_dependencies[number_of_eq] = +len(depending_candidates) - number_of_eq += 1 - number_of_eq = np.argmin(candidate_dependencies) - i_eq = I_eq[number_of_eq] - else: ## x_ii_dot does not occur linearly in any of the unsorted dynamics - for j in unsorted_dyn: - phi_eq_j = gnsf["phi_expr"][np.nonzero(C[j, :])[0]] - if which_depends(phi_eq_j, xdot_z(ii))[0]: - I_eq = set.union(I_eq, j) - if is_empty(I_eq): - I_eq = unsorted_dyn - # find the equation with least linear dependencies on I_LOS_cancidates - number_of_eq = 0 - candidate_dependencies = np.zeros(len(I_eq), 1) - I_x2_candidates = set.intersection(I_LOS_candidates, set(range(nx))) - for eq in I_eq: - depending_candidates = set.union( - np.nonzero(E[eq, I_LOS_candidates])[0], - np.nonzero(A[eq, I_x2_candidates])[0], - ) - candidate_dependencies[number_of_eq] = +len(depending_candidates) - number_of_eq += 1 - number_of_eq = np.argmin(candidate_dependencies) - i_eq = I_eq[number_of_eq] - ## add 1 * [xdot,z](ii) to both sides of i_eq - if print_info: - print( - "adding 1 * ", - var_name, - " to both sides of equation ", - i_eq, - ".", - ) - gnsf["E"][i_eq, ii] = 1 - i_phi = np.nonzero(gnsf["C"][i_eq, :]) - if is_empty(i_phi): - i_phi = len(gnsf["phi_expr"]) + 1 - gnsf["C"][i_eq, i_phi] = 1 # add column to C with 1 entry - gnsf["phi_expr"] = vertcat(gnsf["phi_expr"], 0) - gnsf["phi_expr"][i_phi] = ( - gnsf["phi_expr"](i_phi) - + gnsf["E"][i_eq, ii] / gnsf["C"][i_eq, i_phi] * xdot_z[ii] - ) - if print_info: - print( - "detected equation ", - i_eq, - " to correspond to variable ", - var_name, - ) - I_nsf_eq = set.union(I_nsf_eq, {i_eq}) - # remove i_eq from unsorted_dyn - unsorted_dyn.remove(i_eq) - Eq_map.append([ii, i_eq]) - - ## add components to I_x1 - for eq in I_nsf_eq: - I_linear_dependence = set.union( - set(np.nonzero(A[eq, :])[0]), set(np.nonzero(E[eq, :])[0]) - ) - I_nsf_components = set.union(I_linear_dependence, I_nsf_components) - # I_nsf_components = I_nsf_components[:] - - new_nsf_components = set.intersection(I_LOS_candidates, I_nsf_components) - if is_empty(new_nsf_components): - if print_info: - print("new_nsf_components is empty") - break - # remove new_nsf_components from candidates - I_LOS_candidates = set.difference(I_LOS_candidates, new_nsf_components) - if not is_empty(Eq_map): - # [~, new_eq_order] = sort(Eq_map(1,:)) - # I_nsf_eq = Eq_map(2, new_eq_order ) - for count, m in enumerate(Eq_map): - m.append(count) - sorted(Eq_map, key=lambda x: x[1]) - new_eq_order = [m[2] for m in Eq_map] - Eq_map = [Eq_map[i] for i in new_eq_order] - I_nsf_eq = [m[1] for m in Eq_map] - - else: - I_nsf_eq = [] - - I_LOS_components = I_LOS_candidates - I_LOS_eq = sorted(set.difference(set(range(nx + nz)), I_nsf_eq)) - I_nsf_eq = sorted(I_nsf_eq) - - I_x1 = set.intersection(I_nsf_components, set(range(nx))) - I_z1 = set.intersection(I_nsf_components, set(range(nx, nx + nz))) - I_z1 = set([i - nx for i in I_z1]) - - I_x2 = set.intersection(I_LOS_components, set(range(nx))) - I_z2 = set.intersection(I_LOS_components, set(range(nx, nx + nz))) - I_z2 = set([i - nx for i in I_z2]) - - if print_info: - print(f"I_x1 {I_x1}, I_x2 {I_x2}") - - ## permute x, xdot - if is_empty(I_x1): - x1 = [] - x1dot = [] - else: - x1 = x[list(I_x1)] - x1dot = xdot[list(I_x1)] - if is_empty(I_x2): - x2 = [] - x2dot = [] - else: - x2 = x[list(I_x2)] - x2dot = xdot[list(I_x2)] - if is_empty(I_z1): - z1 = [] - else: - z1 = z(I_z1) - if is_empty(I_z2): - z2 = [] - else: - z2 = z[list(I_z2)] - - I_x1 = sorted(I_x1) - I_x2 = sorted(I_x2) - I_z1 = sorted(I_z1) - I_z2 = sorted(I_z2) - gnsf["xdot"] = vertcat(x1dot, x2dot) - gnsf["x"] = vertcat(x1, x2) - gnsf["z"] = vertcat(z1, z2) - gnsf["nx1"] = len(I_x1) - gnsf["nx2"] = len(I_x2) - gnsf["nz1"] = len(I_z1) - gnsf["nz2"] = len(I_z2) - - # store permutations - gnsf["idx_perm_x"] = I_x1 + I_x2 - gnsf["ipiv_x"] = idx_perm_to_ipiv(gnsf["idx_perm_x"]) - gnsf["idx_perm_z"] = I_z1 + I_z2 - gnsf["ipiv_z"] = idx_perm_to_ipiv(gnsf["idx_perm_z"]) - gnsf["idx_perm_f"] = I_nsf_eq + I_LOS_eq - gnsf["ipiv_f"] = idx_perm_to_ipiv(gnsf["idx_perm_f"]) - - f_LO = SX.sym("f_LO", 0, 0) - - ## rewrite I_LOS_eq as LOS - if gnsf["n_out"] == 0: - C_phi = np.zeros(gnsf["nx"] + gnsf["nz"], 1) - else: - C_phi = C @ phi_old - if gnsf["nx1"] == 0: - Ax1 = np.zeros(gnsf["nx"] + gnsf["nz"], 1) - else: - Ax1 = A[:, sorted(I_x1)] @ x1 - if gnsf["nx1"] + gnsf["nz1"] == 0: - lhs_nsf = np.zeros(gnsf["nx"] + gnsf["nz"], 1) - else: - lhs_nsf = E[:, sorted(I_nsf_components)] @ vertcat(x1, z1) - n_LO = len(I_LOS_eq) - B_LO = np.zeros((n_LO, gnsf["nu"])) - A_LO = np.zeros((gnsf["nx2"] + gnsf["nz2"], gnsf["nx2"])) - E_LO = np.zeros((n_LO, n_LO)) - c_LO = np.zeros((n_LO, 1)) - - I_LOS_eq = list(I_LOS_eq) - for eq in I_LOS_eq: - i_LO = I_LOS_eq.index(eq) - f_LO = vertcat(f_LO, Ax1[eq] + C_phi[eq] - lhs_nsf[eq]) - print(f"eq {eq} I_LOS_components {I_LOS_components}, i_LO {i_LO}, f_LO {f_LO}") - E_LO[i_LO, :] = E[eq, sorted(I_LOS_components)] - A_LO[i_LO, :] = A[eq, I_x2] - c_LO[i_LO, :] = c[eq] - B_LO[i_LO, :] = B[eq, :] - if casadi_length(f_LO) == 0: - f_LO = SX.zeros((gnsf["nx2"] + gnsf["nz2"], 1)) - f_LO = simplify(f_LO) - gnsf["A_LO"] = A_LO - gnsf["E_LO"] = E_LO - gnsf["B_LO"] = B_LO - gnsf["c_LO"] = c_LO - gnsf["f_lo_expr"] = f_LO - - ## remove I_LOS_eq from NSF type system - gnsf["A"] = gnsf["A"][np.ix_(sorted(I_nsf_eq), sorted(I_x1))] - gnsf["B"] = gnsf["B"][sorted(I_nsf_eq), :] - gnsf["C"] = gnsf["C"][sorted(I_nsf_eq), :] - gnsf["E"] = gnsf["E"][np.ix_(sorted(I_nsf_eq), sorted(I_nsf_components))] - gnsf["c"] = gnsf["c"][sorted(I_nsf_eq), :] - - ## reduce phi, C - I_nonzero = [] - for ii in range(gnsf["C"].shape[1]): # n_colums of C: - print(f"ii {ii}") - if not all(gnsf["C"][:, ii] == 0): # if column ~= 0 - I_nonzero.append(ii) - gnsf["C"] = gnsf["C"][:, I_nonzero] - gnsf["phi_expr"] = gnsf["phi_expr"][I_nonzero] - - gnsf = determine_input_nonlinearity_function(gnsf) - - check_reformulation(model, gnsf, print_info) - - gnsf["nontrivial_f_LO"] = 0 - if not is_empty(gnsf["f_lo_expr"]): - for ii in range(casadi_length(gnsf["f_lo_expr"])): - fii = gnsf["f_lo_expr"][ii] - if not fii.is_zero(): - gnsf["nontrivial_f_LO"] = 1 - if not gnsf["nontrivial_f_LO"] and print_info: - print("f_LO is fully trivial (== 0)") - check_reformulation(model, gnsf, print_info) - - if print_info: - print("") - print( - "---------------------------------------------------------------------------------" - ) - print( - "------------- Success: Linear Output System (LOS) detected ----------------------" - ) - print( - "---------------------------------------------------------------------------------" - ) - print("") - print( - "==>> moved ", - gnsf["nx2"], - "differential states and ", - gnsf["nz2"], - " algebraic variables to the Linear Output System", - ) - print( - "==>> recuced output dimension of phi from ", - casadi_length(phi_old), - " to ", - casadi_length(gnsf["phi_expr"]), - ) - print(" ") - print("Matrices defining the LOS read as") - print(" ") - print("E_LO =") - print(gnsf["E_LO"]) - print("A_LO =") - print(gnsf["A_LO"]) - print("B_LO =") - print(gnsf["B_LO"]) - print("c_LO =") - print(gnsf["c_LO"]) - - return gnsf diff --git a/third_party/acados/acados_template/gnsf/reformulate_with_invertible_E_mat.py b/third_party/acados/acados_template/gnsf/reformulate_with_invertible_E_mat.py deleted file mode 100644 index 21ab8ebfd53b78..00000000000000 --- a/third_party/acados/acados_template/gnsf/reformulate_with_invertible_E_mat.py +++ /dev/null @@ -1,167 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from casadi import * -from .determine_input_nonlinearity_function import determine_input_nonlinearity_function -from .check_reformulation import check_reformulation - - -def reformulate_with_invertible_E_mat(gnsf, model, print_info): - ## Description - # this function checks that the necessary condition to apply the gnsf - # structure exploiting integrator to a model, namely that the matrices E11, - # E22 are invertible holds. - # if this is not the case, it will make these matrices invertible and add: - # corresponding terms, to the term C * phi, such that the obtained model is - # still equivalent - - # check invertibility of E11, E22 and reformulate if needed: - ind_11 = range(gnsf["nx1"]) - ind_22 = range(gnsf["nx1"], gnsf["nx1"] + gnsf["nz1"]) - - if print_info: - print(" ") - print("----------------------------------------------------") - print("checking rank of E11 and E22") - print("----------------------------------------------------") - ## check if E11, E22 are invertible: - z_check = False - if gnsf["nz1"] > 0: - z_check = ( - np.linalg.matrix_rank(gnsf["E"][np.ix_(ind_22, ind_22)]) != gnsf["nz1"] - ) - - if ( - np.linalg.matrix_rank(gnsf["E"][np.ix_(ind_11, ind_11)]) != gnsf["nx1"] - or z_check - ): - # print warning (always) - print(f"the rank of E11 or E22 is not full after the reformulation") - print("") - print( - f"the script will try to reformulate the model with an invertible matrix instead" - ) - print( - f"NOTE: this feature is based on a heuristic, it should be used with care!!!" - ) - - ## load models - xdot = gnsf["xdot"] - z = gnsf["z"] - - # # GNSF - # get dimensions - nx1 = gnsf["nx1"] - x1dot = xdot[range(nx1)] - - k = vertcat(x1dot, z) - for i in [1, 2]: - if i == 1: - ind = range(gnsf["nx1"]) - else: - ind = range(gnsf["nx1"], gnsf["nx1"] + gnsf["nz1"]) - mat = gnsf["E"][np.ix_(ind, ind)] - import pdb - - pdb.set_trace() - while np.linalg.matrix_rank(mat) < len(ind): - # import pdb; pdb.set_trace() - if print_info: - print(" ") - print(f"the rank of E", str(i), str(i), " is not full") - print( - f"the algorithm will try to reformulate the model with an invertible matrix instead" - ) - print( - f"NOTE: this feature is not super stable and might need more testing!!!!!!" - ) - for sub_max in ind: - sub_ind = range(min(ind), sub_max) - # regard the submatrix mat(sub_ind, sub_ind) - sub_mat = gnsf["E"][sub_ind, sub_ind] - if np.linalg.matrix_rank(sub_mat) < len(sub_ind): - # reformulate the model by adding a 1 to last diagonal - # element and changing rhs respectively. - gnsf["E"][sub_max, sub_max] = gnsf["E"][sub_max, sub_max] + 1 - # this means adding the term 1 * k(sub_max) to the sub_max - # row of the l.h.s - if len(np.nonzero(gnsf["C"][sub_max, :])[0]) == 0: - # if isempty(find(gnsf['C'](sub_max,:), 1)): - # add new nonlinearity entry - gnsf["C"][sub_max, gnsf["n_out"] + 1] = 1 - gnsf["phi_expr"] = vertcat(gnsf["phi_expr"], k[sub_max]) - else: - ind_f = np.nonzero(gnsf["C"][sub_max, :])[0] - if len(ind_f) != 1: - raise Exception("C is assumed to be a selection matrix") - else: - ind_f = ind_f[0] - # add term to corresponding nonlinearity entry - # note: herbey we assume that C is a selection matrix, - # i.e. gnsf['phi_expr'](ind_f) is only entering one equation - - gnsf["phi_expr"][ind_f] = ( - gnsf["phi_expr"][ind_f] - + k[sub_max] / gnsf["C"][sub_max, ind_f] - ) - gnsf = determine_input_nonlinearity_function(gnsf) - check_reformulation(model, gnsf, print_info) - print("successfully reformulated the model with invertible matrices E11, E22") - else: - if print_info: - print(" ") - print( - "the rank of both E11 and E22 is naturally full after the reformulation " - ) - print("==> model reformulation finished") - print(" ") - if (gnsf['nx2'] > 0 or gnsf['nz2'] > 0) and det(gnsf["E_LO"]) == 0: - print( - "_______________________________________________________________________________________________________" - ) - print(" ") - print("TAKE CARE ") - print("E_LO matrix is NOT regular after automatic transcription!") - print("->> this means the model CANNOT be used with the gnsf integrator") - print( - "->> it probably means that one entry (of xdot or z) that was moved to the linear output type system" - ) - print(" does not appear in the model at all (zero column in E_LO)") - print(" OR: the columns of E_LO are linearly dependent ") - print(" ") - print( - " SOLUTIONs: a) go through your model & check equations the method wanted to move to LOS" - ) - print(" b) deactivate the detect_LOS option") - print( - "_______________________________________________________________________________________________________" - ) - return gnsf diff --git a/third_party/acados/acados_template/gnsf/structure_detection_print_summary.py b/third_party/acados/acados_template/gnsf/structure_detection_print_summary.py deleted file mode 100644 index db2d18758e99db..00000000000000 --- a/third_party/acados/acados_template/gnsf/structure_detection_print_summary.py +++ /dev/null @@ -1,174 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from casadi import n_nodes -import numpy as np - - -def structure_detection_print_summary(gnsf, acados_ocp): - - ## Description - # this function prints the most important info after determining a GNSF - # reformulation of the implicit model "initial_model" into "gnsf", which is - # equivalent to the "reordered_model". - model = acados_ocp.model - # # GNSF - # get dimensions - nx = gnsf["nx"] - nu = gnsf["nu"] - nz = gnsf["nz"] - - nx1 = gnsf["nx1"] - nx2 = gnsf["nx2"] - - nz1 = gnsf["nz1"] - nz2 = gnsf["nz2"] - - # np = gnsf['np'] - n_out = gnsf["n_out"] - ny = gnsf["ny"] - nuhat = gnsf["nuhat"] - - # - f_impl_expr = model.f_impl_expr - n_nodes_initial = n_nodes(model.f_impl_expr) - # x_old = model.x - # f_impl_old = model.f_impl_expr - - x = gnsf["x"] - z = gnsf["z"] - - phi_current = gnsf["phi_expr"] - - ## PRINT SUMMARY -- STRUCHTRE DETECTION - print(" ") - print( - "*********************************************************************************************" - ) - print(" ") - print( - "****************** SUCCESS: GNSF STRUCTURE DETECTION COMPLETE !!! ***************" - ) - print(" ") - print( - "*********************************************************************************************" - ) - print(" ") - print( - f"========================= STRUCTURE DETECTION SUMMARY ====================================" - ) - print(" ") - print("-------- Nonlinear Static Feedback type system --------") - print(" ") - print(" successfully transcribed dynamic system model into GNSF structure ") - print(" ") - print( - "reduced dimension of nonlinearity phi from ", - str(nx + nz), - " to ", - str(gnsf["n_out"]), - ) - print(" ") - print( - "reduced input dimension of nonlinearity phi from ", - 2 * nx + nz + nu, - " to ", - gnsf["ny"] + gnsf["nuhat"], - ) - print(" ") - print(f"reduced number of nodes in CasADi expression of nonlinearity phi from {n_nodes_initial} to {n_nodes(phi_current)}\n") - print("----------- Linear Output System (LOS) ---------------") - if nx2 + nz2 > 0: - print(" ") - print(f"introduced Linear Output System of size ", str(nx2 + nz2)) - print(" ") - if nx2 > 0: - print("consisting of the states:") - print(" ") - print(x[range(nx1, nx)]) - print(" ") - if nz2 > 0: - print("and algebraic variables:") - print(" ") - print(z[range(nz1, nz)]) - print(" ") - if gnsf["purely_linear"] == 1: - print(" ") - print("Model is fully linear!") - print(" ") - if not all(gnsf["idx_perm_x"] == np.array(range(nx))): - print(" ") - print( - "--------------------------------------------------------------------------------------------------" - ) - print( - "NOTE: permuted differential state vector x, such that x_gnsf = x(idx_perm_x) with idx_perm_x =" - ) - print(" ") - print(gnsf["idx_perm_x"]) - if nz != 0 and not all(gnsf["idx_perm_z"] == np.array(range(nz))): - print(" ") - print( - "--------------------------------------------------------------------------------------------------" - ) - print( - "NOTE: permuted algebraic state vector z, such that z_gnsf = z(idx_perm_z) with idx_perm_z =" - ) - print(" ") - print(gnsf["idx_perm_z"]) - if not all(gnsf["idx_perm_f"] == np.array(range(nx + nz))): - print(" ") - print( - "--------------------------------------------------------------------------------------------------" - ) - print( - "NOTE: permuted rhs expression vector f, such that f_gnsf = f(idx_perm_f) with idx_perm_f =" - ) - print(" ") - print(gnsf["idx_perm_f"]) - ## print GNSF dimensions - print( - "--------------------------------------------------------------------------------------------------------" - ) - print(" ") - print("The dimensions of the GNSF reformulated model read as:") - print(" ") - # T_dim = table(nx, nu, nz, np, nx1, nz1, n_out, ny, nuhat) - # print( T_dim ) - print(f"nx ", {nx}) - print(f"nu ", {nu}) - print(f"nz ", {nz}) - # print(f"np ", {np}) - print(f"nx1 ", {nx1}) - print(f"nz1 ", {nz1}) - print(f"n_out ", {n_out}) - print(f"ny ", {ny}) - print(f"nuhat ", {nuhat}) diff --git a/third_party/acados/acados_template/simulink_default_opts.json b/third_party/acados/acados_template/simulink_default_opts.json deleted file mode 100644 index 5d178fef85309c..00000000000000 --- a/third_party/acados/acados_template/simulink_default_opts.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "outputs": { - "u0": 1, - "utraj": 0, - "xtraj": 0, - "solver_status": 1, - "cost_value": 0, - "KKT_residual": 1, - "KKT_residuals": 0, - "x1": 1, - "CPU_time": 1, - "CPU_time_sim": 0, - "CPU_time_qp": 0, - "CPU_time_lin": 0, - "sqp_iter": 1 - }, - "inputs": { - "lbx_0": 1, - "ubx_0": 1, - "parameter_traj": 1, - "y_ref_0": 1, - "y_ref": 1, - "y_ref_e": 1, - "lbx": 1, - "ubx": 1, - "lbx_e": 1, - "ubx_e": 1, - "lbu": 1, - "ubu": 1, - "lg": 1, - "ug": 1, - "lh": 1, - "uh": 1, - "lh_e": 1, - "uh_e": 1, - "cost_W_0": 0, - "cost_W": 0, - "cost_W_e": 0, - "reset_solver": 0, - "x_init": 0, - "u_init": 0 - }, - "samplingtime": "t0" -} diff --git a/third_party/acados/acados_template/utils.py b/third_party/acados/acados_template/utils.py deleted file mode 100644 index d6f6c02f84ade0..00000000000000 --- a/third_party/acados/acados_template/utils.py +++ /dev/null @@ -1,435 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; -# - -import os, sys, json -import urllib.request -import shutil -import numpy as np -from casadi import SX, MX, DM, Function, CasadiMeta - -ALLOWED_CASADI_VERSIONS = ('3.5.6', '3.5.5', '3.5.4', '3.5.3', '3.5.2', '3.5.1', '3.4.5', '3.4.0') - -TERA_VERSION = "0.0.34" - -PLATFORM2TERA = { - "linux": "linux", - "darwin": "osx", - "win32": "windows" -} - - -def get_acados_path(): - ACADOS_PATH = os.environ.get('ACADOS_SOURCE_DIR') - if not ACADOS_PATH: - acados_template_path = os.path.dirname(os.path.abspath(__file__)) - acados_path = os.path.join(acados_template_path, '..','..','..') - ACADOS_PATH = os.path.realpath(acados_path) - msg = 'Warning: Did not find environment variable ACADOS_SOURCE_DIR, ' - msg += 'guessed ACADOS_PATH to be {}.\n'.format(ACADOS_PATH) - msg += 'Please export ACADOS_SOURCE_DIR to avoid this warning.' - print(msg) - return ACADOS_PATH - - -def get_python_interface_path(): - ACADOS_PYTHON_INTERFACE_PATH = os.environ.get('ACADOS_PYTHON_INTERFACE_PATH') - if not ACADOS_PYTHON_INTERFACE_PATH: - acados_path = get_acados_path() - ACADOS_PYTHON_INTERFACE_PATH = os.path.join(acados_path, 'interfaces', 'acados_template', 'acados_template') - return ACADOS_PYTHON_INTERFACE_PATH - - -def get_tera_exec_path(): - TERA_PATH = os.environ.get('TERA_PATH') - if not TERA_PATH: - TERA_PATH = os.path.join(get_acados_path(), 'bin', 't_renderer') - if os.name == 'nt': - TERA_PATH += '.exe' - return TERA_PATH - - -def check_casadi_version(): - casadi_version = CasadiMeta.version() - if casadi_version in ALLOWED_CASADI_VERSIONS: - return - else: - msg = 'Warning: Please note that the following versions of CasADi are ' - msg += 'officially supported: {}.\n '.format(" or ".join(ALLOWED_CASADI_VERSIONS)) - msg += 'If there is an incompatibility with the CasADi generated code, ' - msg += 'please consider changing your CasADi version.\n' - msg += 'Version {} currently in use.'.format(casadi_version) - print(msg) - - -def is_column(x): - if isinstance(x, np.ndarray): - if x.ndim == 1: - return True - elif x.ndim == 2 and x.shape[1] == 1: - return True - else: - return False - elif isinstance(x, (MX, SX, DM)): - if x.shape[1] == 1: - return True - elif x.shape[0] == 0 and x.shape[1] == 0: - return True - else: - return False - elif x == None or x == []: - return False - else: - raise Exception("is_column expects one of the following types: np.ndarray, casadi.MX, casadi.SX." - + " Got: " + str(type(x))) - - -def is_empty(x): - if isinstance(x, (MX, SX, DM)): - return x.is_empty() - elif isinstance(x, np.ndarray): - if np.prod(x.shape) == 0: - return True - else: - return False - elif x == None: - return True - elif isinstance(x, (set, list)): - if len(x)==0: - return True - else: - return False - else: - raise Exception("is_empty expects one of the following types: casadi.MX, casadi.SX, " - + "None, numpy array empty list, set. Got: " + str(type(x))) - - -def casadi_length(x): - if isinstance(x, (MX, SX, DM)): - return int(np.prod(x.shape)) - else: - raise Exception("casadi_length expects one of the following types: casadi.MX, casadi.SX." - + " Got: " + str(type(x))) - - -def make_model_consistent(model): - x = model.x - xdot = model.xdot - u = model.u - z = model.z - p = model.p - - if isinstance(x, MX): - symbol = MX.sym - elif isinstance(x, SX): - symbol = SX.sym - else: - raise Exception("model.x must be casadi.SX or casadi.MX, got {}".format(type(x))) - - if is_empty(p): - model.p = symbol('p', 0, 0) - - if is_empty(z): - model.z = symbol('z', 0, 0) - - return model - -def get_lib_ext(): - lib_ext = '.so' - if sys.platform == 'darwin': - lib_ext = '.dylib' - elif os.name == 'nt': - lib_ext = '' - - return lib_ext - -def get_tera(): - tera_path = get_tera_exec_path() - acados_path = get_acados_path() - - if os.path.exists(tera_path) and os.access(tera_path, os.X_OK): - return tera_path - - repo_url = "https://github.com/acados/tera_renderer/releases" - url = "{}/download/v{}/t_renderer-v{}-{}".format( - repo_url, TERA_VERSION, TERA_VERSION, PLATFORM2TERA[sys.platform]) - - manual_install = 'For manual installation follow these instructions:\n' - manual_install += '1 Download binaries from {}\n'.format(url) - manual_install += '2 Copy them in {}/bin\n'.format(acados_path) - manual_install += '3 Strip the version and platform from the binaries: ' - manual_install += 'as t_renderer-v0.0.34-X -> t_renderer)\n' - manual_install += '4 Enable execution privilege on the file "t_renderer" with:\n' - manual_install += '"chmod +x {}"\n\n'.format(tera_path) - - msg = "\n" - msg += 'Tera template render executable not found, ' - msg += 'while looking in path:\n{}\n'.format(tera_path) - msg += 'In order to be able to render the templates, ' - msg += 'you need to download the tera renderer binaries from:\n' - msg += '{}\n\n'.format(repo_url) - msg += 'Do you wish to set up Tera renderer automatically?\n' - msg += 'y/N? (press y to download tera or any key for manual installation)\n' - - if input(msg) == 'y': - print("Dowloading {}".format(url)) - with urllib.request.urlopen(url) as response, open(tera_path, 'wb') as out_file: - shutil.copyfileobj(response, out_file) - print("Successfully downloaded t_renderer.") - os.chmod(tera_path, 0o755) - return tera_path - - msg_cancel = "\nYou cancelled automatic download.\n\n" - msg_cancel += manual_install - msg_cancel += "Once installed re-run your script.\n\n" - print(msg_cancel) - - sys.exit(1) - - -def render_template(in_file, out_file, output_dir, json_path, template_glob=None): - - acados_path = os.path.dirname(os.path.abspath(__file__)) - if template_glob is None: - template_glob = os.path.join(acados_path, 'c_templates_tera', '**', '*') - cwd = os.getcwd() - - if not os.path.exists(output_dir): - os.makedirs(output_dir) - os.chdir(output_dir) - - tera_path = get_tera() - - # call tera as system cmd - os_cmd = f"{tera_path} '{template_glob}' '{in_file}' '{json_path}' '{out_file}'" - # Windows cmd.exe can not cope with '...', so use "..." instead: - if os.name == 'nt': - os_cmd = os_cmd.replace('\'', '\"') - - status = os.system(os_cmd) - if (status != 0): - raise Exception(f'Rendering of {in_file} failed!\n\nAttempted to execute OS command:\n{os_cmd}\n\n') - - os.chdir(cwd) - - -## Conversion functions -def make_object_json_dumpable(input): - if isinstance(input, (np.ndarray)): - return input.tolist() - elif isinstance(input, (SX)): - return input.serialize() - elif isinstance(input, (MX)): - # NOTE: MX expressions can not be serialized, only Functions. - return input.__str__() - elif isinstance(input, (DM)): - return input.full() - else: - raise TypeError(f"Cannot make input of type {type(input)} dumpable.") - - -def format_class_dict(d): - """ - removes the __ artifact from class to dict conversion - """ - out = {} - for k, v in d.items(): - if isinstance(v, dict): - v = format_class_dict(v) - - out_key = k.split('__', 1)[-1] - out[k.replace(k, out_key)] = v - return out - - -def get_ocp_nlp_layout() -> dict: - python_interface_path = get_python_interface_path() - abs_path = os.path.join(python_interface_path, 'acados_layout.json') - with open(abs_path, 'r') as f: - ocp_nlp_layout = json.load(f) - return ocp_nlp_layout - - -def get_default_simulink_opts() -> dict: - python_interface_path = get_python_interface_path() - abs_path = os.path.join(python_interface_path, 'simulink_default_opts.json') - with open(abs_path, 'r') as f: - simulink_opts = json.load(f) - return simulink_opts - - -def J_to_idx(J): - nrows = J.shape[0] - idx = np.zeros((nrows, )) - for i in range(nrows): - this_idx = np.nonzero(J[i,:])[0] - if len(this_idx) != 1: - raise Exception('Invalid J matrix structure detected, ' \ - 'must contain one nonzero element per row.') - if this_idx.size > 0 and J[i,this_idx[0]] != 1: - raise Exception('J matrices can only contain 1s.') - idx[i] = this_idx[0] - return idx - - -def J_to_idx_slack(J): - nrows = J.shape[0] - ncol = J.shape[1] - idx = np.zeros((ncol, )) - i_idx = 0 - for i in range(nrows): - this_idx = np.nonzero(J[i,:])[0] - if len(this_idx) == 1: - idx[i_idx] = i - i_idx = i_idx + 1 - elif len(this_idx) > 1: - raise Exception('J_to_idx_slack: Invalid J matrix. ' \ - 'Found more than one nonzero in row ' + str(i)) - if this_idx.size > 0 and J[i,this_idx[0]] != 1: - raise Exception('J_to_idx_slack: J matrices can only contain 1s, ' \ - 'got J(' + str(i) + ', ' + str(this_idx[0]) + ') = ' + str(J[i,this_idx[0]]) ) - if not i_idx == ncol: - raise Exception('J_to_idx_slack: J must contain a 1 in every column!') - return idx - - -def acados_dae_model_json_dump(model): - - # load model - x = model.x - xdot = model.xdot - u = model.u - z = model.z - p = model.p - - f_impl = model.f_impl_expr - model_name = model.name - - # create struct with impl_dae_fun, casadi_version - fun_name = model_name + '_impl_dae_fun' - impl_dae_fun = Function(fun_name, [x, xdot, u, z, p], [f_impl]) - - casadi_version = CasadiMeta.version() - str_impl_dae_fun = impl_dae_fun.serialize() - - dae_dict = {"str_impl_dae_fun": str_impl_dae_fun, "casadi_version": casadi_version} - - # dump - json_file = model_name + '_acados_dae.json' - with open(json_file, 'w') as f: - json.dump(dae_dict, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - print("dumped ", model_name, " dae to file:", json_file, "\n") - - -def set_up_imported_gnsf_model(acados_ocp): - - gnsf = acados_ocp.gnsf_model - - # check CasADi version - # dump_casadi_version = gnsf['casadi_version'] - # casadi_version = CasadiMeta.version() - - # if not casadi_version == dump_casadi_version: - # print("WARNING: GNSF model was dumped with another CasADi version.\n" - # + "This might yield errors. Please use the same version for compatibility, serialize version: " - # + dump_casadi_version + " current Python CasADi verison: " + casadi_version) - # input("Press any key to attempt to continue...") - - # load model - phi_fun = Function.deserialize(gnsf['phi_fun']) - phi_fun_jac_y = Function.deserialize(gnsf['phi_fun_jac_y']) - phi_jac_y_uhat = Function.deserialize(gnsf['phi_jac_y_uhat']) - get_matrices_fun = Function.deserialize(gnsf['get_matrices_fun']) - - # obtain gnsf dimensions - size_gnsf_A = get_matrices_fun.size_out(0) - acados_ocp.dims.gnsf_nx1 = size_gnsf_A[1] - acados_ocp.dims.gnsf_nz1 = size_gnsf_A[0] - size_gnsf_A[1] - acados_ocp.dims.gnsf_nuhat = max(phi_fun.size_in(1)) - acados_ocp.dims.gnsf_ny = max(phi_fun.size_in(0)) - acados_ocp.dims.gnsf_nout = max(phi_fun.size_out(0)) - - # save gnsf functions in model - acados_ocp.model.phi_fun = phi_fun - acados_ocp.model.phi_fun_jac_y = phi_fun_jac_y - acados_ocp.model.phi_jac_y_uhat = phi_jac_y_uhat - acados_ocp.model.get_matrices_fun = get_matrices_fun - - # get_matrices_fun = Function([model_name,'_gnsf_get_matrices_fun'], {dummy},... - # {A, B, C, E, L_x, L_xdot, L_z, L_u, A_LO, c, E_LO, B_LO,... - # nontrivial_f_LO, purely_linear, ipiv_x, ipiv_z, c_LO}); - get_matrices_out = get_matrices_fun(0) - acados_ocp.model.gnsf['nontrivial_f_LO'] = int(get_matrices_out[12]) - acados_ocp.model.gnsf['purely_linear'] = int(get_matrices_out[13]) - - if "f_lo_fun_jac_x1k1uz" in gnsf: - f_lo_fun_jac_x1k1uz = Function.deserialize(gnsf['f_lo_fun_jac_x1k1uz']) - acados_ocp.model.f_lo_fun_jac_x1k1uz = f_lo_fun_jac_x1k1uz - else: - dummy_var_x1 = SX.sym('dummy_var_x1', acados_ocp.dims.gnsf_nx1) - dummy_var_x1dot = SX.sym('dummy_var_x1dot', acados_ocp.dims.gnsf_nx1) - dummy_var_z1 = SX.sym('dummy_var_z1', acados_ocp.dims.gnsf_nz1) - dummy_var_u = SX.sym('dummy_var_z1', acados_ocp.dims.nu) - dummy_var_p = SX.sym('dummy_var_z1', acados_ocp.dims.np) - empty_var = SX.sym('empty_var', 0, 0) - - empty_fun = Function('empty_fun', \ - [dummy_var_x1, dummy_var_x1dot, dummy_var_z1, dummy_var_u, dummy_var_p], - [empty_var]) - acados_ocp.model.f_lo_fun_jac_x1k1uz = empty_fun - - del acados_ocp.gnsf_model - - -def idx_perm_to_ipiv(idx_perm): - n = len(idx_perm) - vec = list(range(n)) - ipiv = np.zeros(n) - - print(n, idx_perm) - # import pdb; pdb.set_trace() - for ii in range(n): - idx0 = idx_perm[ii] - for jj in range(ii,n): - if vec[jj]==idx0: - idx1 = jj - break - tmp = vec[ii] - vec[ii] = vec[idx1] - vec[idx1] = tmp - ipiv[ii] = idx1 - - ipiv = ipiv-1 # C 0-based indexing - return ipiv - - -def print_casadi_expression(f): - for ii in range(casadi_length(f)): - print(f[ii,:]) diff --git a/third_party/acados/acados_template/zoro_description.py b/third_party/acados/acados_template/zoro_description.py deleted file mode 100644 index 4d795c1502e1a5..00000000000000 --- a/third_party/acados/acados_template/zoro_description.py +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE.; - -from dataclasses import dataclass, field -import numpy as np - - -@dataclass -class ZoroDescription: - """ - Zero-Order Robust Optimization scheme. - - For advanced users. - """ - backoff_scaling_gamma: float = 1.0 - fdbk_K_mat: np.ndarray = None - unc_jac_G_mat: np.ndarray = None # default: an identity matrix - P0_mat: np.ndarray = None - W_mat: np.ndarray = None - idx_lbx_t: list = field(default_factory=list) - idx_ubx_t: list = field(default_factory=list) - idx_lbx_e_t: list = field(default_factory=list) - idx_ubx_e_t: list = field(default_factory=list) - idx_lbu_t: list = field(default_factory=list) - idx_ubu_t: list = field(default_factory=list) - idx_lg_t: list = field(default_factory=list) - idx_ug_t: list = field(default_factory=list) - idx_lg_e_t: list = field(default_factory=list) - idx_ug_e_t: list = field(default_factory=list) - idx_lh_t: list = field(default_factory=list) - idx_uh_t: list = field(default_factory=list) - idx_lh_e_t: list = field(default_factory=list) - idx_uh_e_t: list = field(default_factory=list) - -def process_zoro_description(zoro_description: ZoroDescription): - zoro_description.nw, _ = zoro_description.W_mat.shape - if zoro_description.unc_jac_G_mat is None: - zoro_description.unc_jac_G_mat = np.eye(zoro_description.nw) - zoro_description.nlbx_t = len(zoro_description.idx_lbx_t) - zoro_description.nubx_t = len(zoro_description.idx_ubx_t) - zoro_description.nlbx_e_t = len(zoro_description.idx_lbx_e_t) - zoro_description.nubx_e_t = len(zoro_description.idx_ubx_e_t) - zoro_description.nlbu_t = len(zoro_description.idx_lbu_t) - zoro_description.nubu_t = len(zoro_description.idx_ubu_t) - zoro_description.nlg_t = len(zoro_description.idx_lg_t) - zoro_description.nug_t = len(zoro_description.idx_ug_t) - zoro_description.nlg_e_t = len(zoro_description.idx_lg_e_t) - zoro_description.nug_e_t = len(zoro_description.idx_ug_e_t) - zoro_description.nlh_t = len(zoro_description.idx_lh_t) - zoro_description.nuh_t = len(zoro_description.idx_uh_t) - zoro_description.nlh_e_t = len(zoro_description.idx_lh_e_t) - zoro_description.nuh_e_t = len(zoro_description.idx_uh_e_t) - return zoro_description.__dict__ diff --git a/third_party/acados/build.sh b/third_party/acados/build.sh deleted file mode 100755 index b45c167b1643af..00000000000000 --- a/third_party/acados/build.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" - -ARCHNAME="x86_64" -BLAS_TARGET="X64_AUTOMATIC" -if [ -f /TICI ]; then - ARCHNAME="larch64" - BLAS_TARGET="ARMV8A_ARM_CORTEX_A57" -fi - -ACADOS_FLAGS="-DACADOS_WITH_QPOASES=ON -UBLASFEO_TARGET -DBLASFEO_TARGET=$BLAS_TARGET" - -if [[ "$OSTYPE" == "darwin"* ]]; then - ACADOS_FLAGS="$ACADOS_FLAGS -DCMAKE_OSX_ARCHITECTURES=arm64;x86_64 -DCMAKE_MACOSX_RPATH=1" - ARCHNAME="Darwin" -fi - -if [ ! -d acados_repo/ ]; then - git clone https://github.com/acados/acados.git $DIR/acados_repo - # git clone https://github.com/commaai/acados.git $DIR/acados_repo -fi -cd acados_repo -git fetch --all -git checkout 8af9b0ad180940ef611884574a0b27a43504311d # v0.2.2 -git submodule update --depth=1 --recursive --init - -# build -mkdir -p build -cd build -cmake $ACADOS_FLAGS .. -make -j20 install - -INSTALL_DIR="$DIR/$ARCHNAME" -rm -rf $INSTALL_DIR -mkdir -p $INSTALL_DIR - -rm $DIR/acados_repo/lib/*.json - -rm -rf $DIR/include $DIR/acados_template -cp -r $DIR/acados_repo/include $DIR -cp -r $DIR/acados_repo/lib $INSTALL_DIR -cp -r $DIR/acados_repo/interfaces/acados_template/acados_template $DIR/ -#pip3 install -e $DIR/acados/interfaces/acados_template - -# build tera -cd $DIR/acados_repo/interfaces/acados_template/tera_renderer/ -if [[ "$OSTYPE" == "darwin"* ]]; then - cargo build --verbose --release --target aarch64-apple-darwin - cargo build --verbose --release --target x86_64-apple-darwin - lipo -create -output target/release/t_renderer target/x86_64-apple-darwin/release/t_renderer target/aarch64-apple-darwin/release/t_renderer -else - cargo build --verbose --release -fi -cp target/release/t_renderer $INSTALL_DIR/ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_common.h b/third_party/acados/include/acados/dense_qp/dense_qp_common.h deleted file mode 100644 index 2a9a974f99b0d2..00000000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_common.h +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_COMMON_H_ -#define ACADOS_DENSE_QP_DENSE_QP_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_dense_qp.h" -#include "hpipm/include/hpipm_d_dense_qp_res.h" -#include "hpipm/include/hpipm_d_dense_qp_sol.h" -// acados -#include "acados/utils/types.h" - -typedef struct d_dense_qp_dim dense_qp_dims; -typedef struct d_dense_qp dense_qp_in; -typedef struct d_dense_qp_sol dense_qp_out; -typedef struct d_dense_qp_res dense_qp_res; -typedef struct d_dense_qp_res_ws dense_qp_res_ws; - - - -#ifndef QP_SOLVER_CONFIG_ -#define QP_SOLVER_CONFIG_ -typedef struct -{ - void (*dims_set)(void *config_, void *dims_, const char *field, const int* value); - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *args); - void (*opts_update)(void *config, void *dims, void *args); - void (*opts_set)(void *config_, void *opts_, const char *field, void* value); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *args); - void *(*memory_assign)(void *config, void *dims, void *args, void *raw_memory); - void (*memory_get)(void *config_, void *mem_, const char *field, void* value); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *args); - int (*evaluate)(void *config, void *qp_in, void *qp_out, void *args, void *mem, void *work); - void (*eval_sens)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); -} qp_solver_config; -#endif - - - -#ifndef QP_INFO_ -#define QP_INFO_ -typedef struct -{ - double solve_QP_time; - double condensing_time; - double interface_time; - double total_time; - int num_iter; - int t_computed; -} qp_info; -#endif - - - -/* config */ -// -acados_size_t dense_qp_solver_config_calculate_size(); -// -qp_solver_config *dense_qp_solver_config_assign(void *raw_memory); - -/* dims */ -// -acados_size_t dense_qp_dims_calculate_size(); -// -dense_qp_dims *dense_qp_dims_assign(void *raw_memory); -// -void dense_qp_dims_set(void *config_, void *dims_, const char *field, const int* value); -// - -/* in */ -// -acados_size_t dense_qp_in_calculate_size(dense_qp_dims *dims); -// -dense_qp_in *dense_qp_in_assign(dense_qp_dims *dims, void *raw_memory); - -/* out */ -// -acados_size_t dense_qp_out_calculate_size(dense_qp_dims *dims); -// -dense_qp_out *dense_qp_out_assign(dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_out_get(dense_qp_out *out, const char *field, void *value); - -/* res */ -// -acados_size_t dense_qp_res_calculate_size(dense_qp_dims *dims); -// -dense_qp_res *dense_qp_res_assign(dense_qp_dims *dims, void *raw_memory); -// -acados_size_t dense_qp_res_workspace_calculate_size(dense_qp_dims *dims); -// -dense_qp_res_ws *dense_qp_res_workspace_assign(dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_compute_t(dense_qp_in *qp_in, dense_qp_out *qp_out); -// -void dense_qp_res_compute(dense_qp_in *qp_in, dense_qp_out *qp_out, dense_qp_res *qp_res, dense_qp_res_ws *res_ws); -// -void dense_qp_res_compute_nrm_inf(dense_qp_res *qp_res, double res[4]); - -/* misc */ -// -void dense_qp_stack_slacks_dims(dense_qp_dims *in, dense_qp_dims *out); -// -void dense_qp_stack_slacks(dense_qp_in *in, dense_qp_in *out); -// -void dense_qp_unstack_slacks(dense_qp_out *in, dense_qp_in *qp_out, dense_qp_out *out); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_COMMON_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_daqp.h b/third_party/acados/include/acados/dense_qp/dense_qp_daqp.h deleted file mode 100644 index b262089b4ffe0e..00000000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_daqp.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_DAQP_H_ -#define ACADOS_DENSE_QP_DENSE_QP_DAQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// daqp -#include "daqp/include/types.h" - -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - - -typedef struct dense_qp_daqp_opts_ -{ - DAQPSettings* daqp_opts; - int warm_start; -} dense_qp_daqp_opts; - - -typedef struct dense_qp_daqp_memory_ -{ - double* lb_tmp; - double* ub_tmp; - int* idxb; - int* idxv_to_idxb; - int* idxs; - int* idxdaqp_to_idxs; - - double* Zl; - double* Zu; - double* zl; - double* zu; - double* d_ls; - double* d_us; - - double time_qp_solver_call; - int iter; - DAQPWorkspace * daqp_work; - -} dense_qp_daqp_memory; - -// opts -acados_size_t dense_qp_daqp_opts_calculate_size(void *config, dense_qp_dims *dims); -// -void *dense_qp_daqp_opts_assign(void *config, dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_daqp_opts_initialize_default(void *config, dense_qp_dims *dims, void *opts_); -// -void dense_qp_daqp_opts_update(void *config, dense_qp_dims *dims, void *opts_); -// -// memory -acados_size_t dense_qp_daqp_workspace_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_daqp_workspace_assign(void *config, dense_qp_dims *dims, void *raw_memory); -// -acados_size_t dense_qp_daqp_memory_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_daqp_memory_assign(void *config, dense_qp_dims *dims, void *opts_, void *raw_memory); -// -// functions -int dense_qp_daqp(void *config, dense_qp_in *qp_in, dense_qp_out *qp_out, void *opts_, void *memory_, void *work_); -// -void dense_qp_daqp_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_daqp_memory_reset(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_daqp_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_DAQP_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_hpipm.h b/third_party/acados/include/acados/dense_qp/dense_qp_hpipm.h deleted file mode 100644 index 136279d666144f..00000000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_hpipm.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_HPIPM_H_ -#define ACADOS_DENSE_QP_DENSE_QP_HPIPM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_dense_qp.h" -#include "hpipm/include/hpipm_d_dense_qp_ipm.h" -#include "hpipm/include/hpipm_d_dense_qp_sol.h" -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - - - -typedef struct dense_qp_hpipm_opts_ -{ - struct d_dense_qp_ipm_arg *hpipm_opts; -} dense_qp_hpipm_opts; - - - -typedef struct dense_qp_hpipm_memory_ -{ - struct d_dense_qp_ipm_ws *hpipm_workspace; - double time_qp_solver_call; - int iter; - -} dense_qp_hpipm_memory; - - - -// -acados_size_t dense_qp_hpipm_opts_calculate_size(void *config, void *dims); -// -void *dense_qp_hpipm_opts_assign(void *config, void *dims, void *raw_memory); -// -void dense_qp_hpipm_opts_initialize_default(void *config, void *dims, void *opts_); -// -void dense_qp_hpipm_opts_update(void *config, void *dims, void *opts_); -// -acados_size_t dense_qp_hpipm_calculate_memory_size(void *dims, void *opts_); -// -void *dense_qp_hpipm_assign_memory(void *dims, void *opts_, void *raw_memory); -// -acados_size_t dense_qp_hpipm_calculate_workspace_size(void *dims, void *opts_); -// -int dense_qp_hpipm(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_hpipm_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_hpipm_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_HPIPM_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_ooqp.h b/third_party/acados/include/acados/dense_qp/dense_qp_ooqp.h deleted file mode 100644 index d051cb15f70281..00000000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_ooqp.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_OOQP_H_ -#define ACADOS_DENSE_QP_DENSE_QP_OOQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - -enum dense_qp_ooqp_termination_code -{ - DENSE_SUCCESSFUL_TERMINATION = 0, - DENSE_NOT_FINISHED, - DENSE_MAX_ITS_EXCEEDED, - DENSE_INFEASIBLE, - DENSE_UNKNOWN -}; - -typedef struct dense_qp_ooqp_opts_ -{ - int printLevel; - int useDiagonalWeights; // TODO(dimitris): implement option - int fixHessian; - int fixDynamics; - int fixInequalities; -} dense_qp_ooqp_opts; - -typedef struct dense_qp_ooqp_workspace_ -{ - double *x; - double *gamma; - double *phi; - double *y; - double *z; - double *lambda; - double *pi; - double objectiveValue; -} dense_qp_ooqp_workspace; - -typedef struct dense_qp_ooqp_memory_ -{ - int firstRun; - int nx; - int my; - int mz; - double *c; - double *dQ; - double *xlow; - char *ixlow; - double *xupp; - char *ixupp; - double *dA; - double *bA; - double *dC; - double *clow; - char *iclow; - double *cupp; - char *icupp; - double time_qp_solver_call; - int iter; - -} dense_qp_ooqp_memory; - -// -acados_size_t dense_qp_ooqp_opts_calculate_size(void *config_, dense_qp_dims *dims); -// -void *dense_qp_ooqp_opts_assign(void *config_, dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_ooqp_opts_initialize_default(void *config_, dense_qp_dims *dims, void *opts_); -// -void dense_qp_ooqp_opts_update(void *config_, dense_qp_dims *dims, void *opts_); -// -acados_size_t dense_qp_ooqp_memory_calculate_size(void *config_, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_ooqp_memory_assign(void *config_, dense_qp_dims *dims, void *opts_, - void *raw_memory); -// -acados_size_t dense_qp_ooqp_workspace_calculate_size(void *config_, dense_qp_dims *dims, void *opts_); -// -int dense_qp_ooqp(void *config_, dense_qp_in *qp_in, dense_qp_out *qp_out, void *opts_, - void *memory_, void *work_); -// -void dense_qp_ooqp_destroy(void *mem_, void *work); -// -void dense_qp_ooqp_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_ooqp_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_OOQP_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_qore.h b/third_party/acados/include/acados/dense_qp/dense_qp_qore.h deleted file mode 100644 index 392e472918d613..00000000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_qore.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_QORE_H_ -#define ACADOS_DENSE_QP_DENSE_QP_QORE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// qore -#include "qore/QPSOLVER_DENSE/include/qpsolver_dense.h" -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - -typedef struct dense_qp_qore_opts_ -{ - int nsmax; // maximum size of Schur complement - int print_freq; // print frequency, - // prtfreq < 0: disable printing; - // prtfreq == 0: print on each call and include working set changes; - // prtfreq > 0: print on every prtfreq seconds, but do not include working set - // changes; - int warm_start; // warm start with updated matrices H and C - int warm_strategy; // 0: ramp-up from zero homotopy; 1: setup homotopy from the previous - // solution - int hot_start; // hot start with unchanged matrices H and C - int max_iter; // maximum number of iterations - int compute_t; // compute t in qp_out (to have correct residuals in NLP) -} dense_qp_qore_opts; - -typedef struct dense_qp_qore_memory_ -{ - double *H; - double *HH; - double *g; - double *gg; - double *Zl; - double *Zu; - double *zl; - double *zu; - double *A; - double *b; - double *C; - double *CC; - double *Ct; - double *CCt; - double *d_lb0; - double *d_ub0; - double *d_lb; - double *d_ub; - double *d_lg; - double *d_ug; - double *d_ls; - double *d_us; - double *lb; - double *ub; - int *idxb; - int *idxb_stacked; - int *idxs; - double *prim_sol; - double *dual_sol; - QoreProblemDense *QP; - int num_iter; - dense_qp_in *qp_stacked; - double time_qp_solver_call; - int iter; - -} dense_qp_qore_memory; - -acados_size_t dense_qp_qore_opts_calculate_size(void *config, dense_qp_dims *dims); -// -void *dense_qp_qore_opts_assign(void *config, dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_qore_opts_initialize_default(void *config, dense_qp_dims *dims, void *opts_); -// -void dense_qp_qore_opts_update(void *config, dense_qp_dims *dims, void *opts_); -// -acados_size_t dense_qp_qore_memory_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_qore_memory_assign(void *config, dense_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t dense_qp_qore_workspace_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -int dense_qp_qore(void *config, dense_qp_in *qp_in, dense_qp_out *qp_out, void *opts_, void *memory_, void *work_); -// -void dense_qp_qore_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_qore_config_initialize_default(void *config); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_QORE_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h b/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h deleted file mode 100644 index 0e13d3ef64ef6e..00000000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_QPOASES_H_ -#define ACADOS_DENSE_QP_DENSE_QP_QPOASES_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - -typedef struct dense_qp_qpoases_opts_ -{ - double max_cputime; // maximum cpu time in seconds - int max_nwsr; // maximum number of working set recalculations - int warm_start; // warm start with dual_sol in memory - int use_precomputed_cholesky; - int hotstart; // this option requires constant data matrices! (eg linear MPC, inexact schemes - // with frozen sensitivities) - int set_acado_opts; // use same options as in acado code generation - int compute_t; // compute t in qp_out (to have correct residuals in NLP) - double tolerance; // terminationTolerance -} dense_qp_qpoases_opts; - -typedef struct dense_qp_qpoases_memory_ -{ - double *H; - double *HH; - double *R; - double *g; - double *gg; - double *Zl; - double *Zu; - double *zl; - double *zu; - double *A; - double *b; - double *d_lb0; - double *d_ub0; - double *d_lb; - double *d_ub; - double *C; - double *CC; - double *d_lg0; - double *d_ug0; - double *d_lg; - double *d_ug; - double *d_ls; - double *d_us; - int *idxb; - int *idxb_stacked; - int *idxs; - double *prim_sol; - double *dual_sol; - void *QPB; // NOTE(giaf): cast to QProblemB to use - void *QP; // NOTE(giaf): cast to QProblem to use - double cputime; // cputime of qpoases - int nwsr; // performed number of working set recalculations - int first_it; // to be used with hotstart - dense_qp_in *qp_stacked; - double time_qp_solver_call; // equal to cputime - int iter; - -} dense_qp_qpoases_memory; - -acados_size_t dense_qp_qpoases_opts_calculate_size(void *config, dense_qp_dims *dims); -// -void *dense_qp_qpoases_opts_assign(void *config, dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_qpoases_opts_initialize_default(void *config, dense_qp_dims *dims, void *opts_); -// -void dense_qp_qpoases_opts_update(void *config, dense_qp_dims *dims, void *opts_); -// -acados_size_t dense_qp_qpoases__memorycalculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_qpoases_memory_assign(void *config, dense_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t dense_qp_qpoases_workspace_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -int dense_qp_qpoases(void *config, dense_qp_in *qp_in, dense_qp_out *qp_out, void *opts_, void *memory_, void *work_); -// -void dense_qp_qpoases_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_qpoases_memory_reset(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_qpoases_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_QPOASES_H_ diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h deleted file mode 100644 index ba97db97684245..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - - -/// \defgroup ocp_nlp ocp_nlp -/// @{ -/// @} - -/// \defgroup ocp_nlp_solver ocp_nlp_solver -/// @{ -/// @} - -/// \ingroup ocp_nlp -/// @{ - -/// \ingroup ocp_nlp_solver -/// @{ - -/// \defgroup ocp_nlp_common ocp_nlp_common -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_nlp/ocp_nlp_constraints_common.h" -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/ocp_nlp/ocp_nlp_dynamics_common.h" -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_qp/ocp_qp_xcond_solver.h" -#include "acados/sim/sim_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * config - ************************************************/ - -typedef struct ocp_nlp_config -{ - int N; // number of stages - - // solver-specific implementations of memory management functions - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts_); - void (*opts_update)(void *config, void *dims, void *opts_); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts_); - void *(*memory_assign)(void *config, void *dims, void *opts_, void *raw_memory); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts_); - void (*opts_set)(void *config_, void *opts_, const char *field, void* value); - void (*opts_set_at_stage)(void *config_, void *opts_, size_t stage, const char *field, void* value); - // evaluate solver // TODO rename into solve - int (*evaluate)(void *config, void *dims, void *nlp_in, void *nlp_out, void *opts_, void *mem, void *work); - void (*eval_param_sens)(void *config, void *dims, void *opts_, void *mem, void *work, - char *field, int stage, int index, void *sens_nlp_out); - // prepare memory - int (*precompute)(void *config, void *dims, void *nlp_in, void *nlp_out, void *opts_, void *mem, void *work); - void (*memory_reset_qp_solver)(void *config, void *dims, void *nlp_in, void *nlp_out, void *opts_, void *mem, void *work); - // initalize this struct with default values - void (*config_initialize_default)(void *config); - // general getter - void (*get)(void *config_, void *dims, void *mem_, const char *field, void *return_value_); - void (*opts_get)(void *config_, void *dims, void *opts_, const char *field, void *return_value_); - void (*work_get)(void *config_, void *dims, void *work_, const char *field, void *return_value_); - // config structs of submodules - ocp_qp_xcond_solver_config *qp_solver; // TODO rename xcond_solver - ocp_nlp_dynamics_config **dynamics; - ocp_nlp_cost_config **cost; - ocp_nlp_constraints_config **constraints; - ocp_nlp_reg_config *regularize; - -} ocp_nlp_config; - -// -acados_size_t ocp_nlp_config_calculate_size(int N); -// -ocp_nlp_config *ocp_nlp_config_assign(int N, void *raw_memory); - - - -/************************************************ - * dims - ************************************************/ - -/// Structure to store dimensions/number of variables. -typedef struct ocp_nlp_dims -{ - void **cost; - void **dynamics; - void **constraints; - ocp_qp_xcond_solver_dims *qp_solver; // xcond solver instead ?? - ocp_nlp_reg_dims *regularize; - - int *nv; // number of primal variables (states+controls+slacks) - int *nx; // number of differential states - int *nu; // number of inputs - int *ni; // number of two-sided inequality constraints: nb+ng+nh+ns - int *nz; // number of algebraic variables - int *ns; // number of slack variables - int N; // number of shooting nodes - - void *raw_memory; // Pointer to allocated memory, to be used for freeing -} ocp_nlp_dims; - -// -acados_size_t ocp_nlp_dims_calculate_size(void *config); -// -ocp_nlp_dims *ocp_nlp_dims_assign(void *config, void *raw_memory); - -/// Sets the dimension of optimization variables -/// (states, constrols, algebraic variables, slack variables). -/// -/// \param config_ The configuration struct. -/// \param dims_ The dimension struct. -/// \param field The type of optimization variables, either nx, nu, nz, or ns. -/// \param value_array Number of variables for each stage. -void ocp_nlp_dims_set_opt_vars(void *config_, void *dims_, - const char *field, const void* value_array); - -/// Sets the dimensions of constraints functions for a stage -/// (bounds on states, bounds on controls, equality constraints, -/// inequality constraints). -/// -/// \param config_ The configuration struct. -/// \param dims_ The dimension struct. -/// \param stage Stage number. -/// \param field The type of constraint/bound, either nbx, nbu, ng, or nh. -/// \param value_field Number of constraints/bounds for the given stage. -void ocp_nlp_dims_set_constraints(void *config_, void *dims_, int stage, - const char *field, const void* value_field); - -/// Sets the dimensions of the cost terms for a stage. -/// -/// \param config_ The configuration struct. -/// \param dims_ The dimension struct. -/// \param stage Stage number. -/// \param field Type of cost term, can be eiter ny. -/// \param value_field Number of cost terms/residuals for the given stage. -void ocp_nlp_dims_set_cost(void *config_, void *dims_, int stage, const char *field, - const void* value_field); - -/// Sets the dimensions of the dynamics for a stage. -/// -/// \param config_ The configuration struct. -/// \param dims_ The dimension struct. -/// \param stage Stage number. -/// \param field TBD -/// \param value TBD -void ocp_nlp_dims_set_dynamics(void *config_, void *dims_, int stage, const char *field, - const void* value); - -/************************************************ - * Inputs - ************************************************/ - -/// Struct for storing the inputs of an OCP NLP solver -typedef struct ocp_nlp_in -{ - /// Length of sampling intervals/timesteps. - double *Ts; - - /// Pointers to cost functions (TBC). - void **cost; - - /// Pointers to dynamics functions (TBC). - void **dynamics; - - /// Pointers to constraints functions (TBC). - void **constraints; - - /// Pointer to allocated memory, to be used for freeing. - void *raw_memory; - -} ocp_nlp_in; - -// -acados_size_t ocp_nlp_in_calculate_size_self(int N); -// -acados_size_t ocp_nlp_in_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims); -// -ocp_nlp_in *ocp_nlp_in_assign_self(int N, void *raw_memory); -// -ocp_nlp_in *ocp_nlp_in_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, void *raw_memory); - - -/************************************************ - * out - ************************************************/ - -typedef struct ocp_nlp_out -{ - struct blasfeo_dvec *ux; // NOTE: this contains [u; x; s_l; s_u]! - rename to uxs? - struct blasfeo_dvec *z; // algebraic vairables - struct blasfeo_dvec *pi; // multipliers for dynamics - struct blasfeo_dvec *lam; // inequality mulitpliers - struct blasfeo_dvec *t; // slack variables corresponding to evaluation of all inequalities (at the solution) - - // NOTE: the inequalities are internally organized in the following order: - // [ lbu lbx lg lh lphi ubu ubx ug uh uphi; lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - double inf_norm_res; - - void *raw_memory; // Pointer to allocated memory, to be used for freeing - -} ocp_nlp_out; - -// -acados_size_t ocp_nlp_out_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims); -// -ocp_nlp_out *ocp_nlp_out_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, - void *raw_memory); - - - -/************************************************ - * options - ************************************************/ - -/// Globalization types -typedef enum -{ - FIXED_STEP, - MERIT_BACKTRACKING, -} ocp_nlp_globalization_t; - -typedef struct ocp_nlp_opts -{ - ocp_qp_xcond_solver_opts *qp_solver_opts; // xcond solver opts instead ??? - void *regularize; - void **dynamics; // dynamics_opts - void **cost; // cost_opts - void **constraints; // constraints_opts - double step_length; // step length in case of FIXED_STEP - double levenberg_marquardt; // LM factor to be added to the hessian before regularization - int reuse_workspace; - int num_threads; - int print_level; - - // TODO: move to separate struct? - ocp_nlp_globalization_t globalization; - int full_step_dual; - int line_search_use_sufficient_descent; - int globalization_use_SOC; - double alpha_min; - double alpha_reduction; - double eps_sufficient_descent; -} ocp_nlp_opts; - -// -acados_size_t ocp_nlp_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_opts_set(void *config_, void *opts_, const char *field, void* value); -// -void ocp_nlp_opts_set_at_stage(void *config, void *opts, int stage, const char *field, void *value); - - -/************************************************ - * residuals - ************************************************/ - -typedef struct ocp_nlp_res -{ - struct blasfeo_dvec *res_stat; // stationarity - struct blasfeo_dvec *res_eq; // dynamics - struct blasfeo_dvec *res_ineq; // inequality constraints - struct blasfeo_dvec *res_comp; // complementarity - struct blasfeo_dvec tmp; // tmp - double inf_norm_res_stat; - double inf_norm_res_eq; - double inf_norm_res_ineq; - double inf_norm_res_comp; - acados_size_t memsize; -} ocp_nlp_res; - -// -acados_size_t ocp_nlp_res_calculate_size(ocp_nlp_dims *dims); -// -ocp_nlp_res *ocp_nlp_res_assign(ocp_nlp_dims *dims, void *raw_memory); -// -void ocp_nlp_res_get_inf_norm(ocp_nlp_res *res, double *out); - -/************************************************ - * memory - ************************************************/ - -typedef struct ocp_nlp_memory -{ -// void *qp_solver_mem; // xcond solver mem instead ??? - ocp_qp_xcond_solver_memory *qp_solver_mem; // xcond solver mem instead ??? - void *regularize_mem; - void **dynamics; // dynamics memory - void **cost; // cost memory - void **constraints; // constraints memory - - // residuals - ocp_nlp_res *nlp_res; - - // qp in & out - ocp_qp_in *qp_in; - ocp_qp_out *qp_out; - // QP stuff not entering the qp_in struct - struct blasfeo_dmat *dzduxt; // dzdux transposed - struct blasfeo_dvec *z_alg; // z_alg, output algebraic variables - - struct blasfeo_dvec *cost_grad; - struct blasfeo_dvec *ineq_fun; - struct blasfeo_dvec *ineq_adj; - struct blasfeo_dvec *dyn_fun; - struct blasfeo_dvec *dyn_adj; - - double cost_value; - - bool *set_sim_guess; // indicate if there is new explicitly provided guess for integration variables - struct blasfeo_dvec *sim_guess; - - int *sqp_iter; // pointer to iteration number - -} ocp_nlp_memory; - -// -acados_size_t ocp_nlp_memory_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_opts *opts); -// -ocp_nlp_memory *ocp_nlp_memory_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_opts *opts, void *raw_memory); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct ocp_nlp_workspace -{ - - void *qp_work; - void **dynamics; // dynamics_workspace - void **cost; // cost_workspace - void **constraints; // constraints_workspace - - // for globalization: -> move to module?! - ocp_nlp_out *tmp_nlp_out; - ocp_nlp_out *weight_merit_fun; - struct blasfeo_dvec tmp_nxu; - struct blasfeo_dvec tmp_ni; - struct blasfeo_dvec dxnext_dy; - -} ocp_nlp_workspace; - -// -acados_size_t ocp_nlp_workspace_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_opts *opts); -// -ocp_nlp_workspace *ocp_nlp_workspace_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_opts *opts, ocp_nlp_memory *mem, void *raw_memory); - - - -/************************************************ - * function - ************************************************/ - -void ocp_nlp_alias_memory_to_submodules(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_initialize_submodules(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_approximate_qp_matrices(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_approximate_qp_vectors_sqp(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_embed_initial_value(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_update_variables_sqp(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work, double alpha); -// -int ocp_nlp_precompute_common(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -double ocp_nlp_line_search(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work, - int check_early_termination); -// -double ocp_nlp_evaluate_merit_fun(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_initialize_t_slacks(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_res_compute(ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, - ocp_nlp_res *res, ocp_nlp_memory *mem); -// -void ocp_nlp_cost_compute(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COMMON_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgh.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgh.h deleted file mode 100644 index 9dbf16f6dc2df3..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgh.h +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_constraints -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGH_H_ -#define ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGH_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_nlp/ocp_nlp_constraints_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; - int nu; - int nz; - int nb; // nbx + nbu - int nbu; // number of input box constraints - int nbx; // number of state box constraints - int ng; // number of general linear constraints - int nh; // number of nonlinear path constraints - int ns; // nsbu + nsbx + nsg + nsh - int nsbu; // number of softened input bounds - int nsbx; // number of softened state bounds - int nsg; // number of softened general linear constraints - int nsh; // number of softened nonlinear constraints - int nbue; // number of input box constraints which are equality - int nbxe; // number of state box constraints which are equality - int nge; // number of general linear constraints which are equality - int nhe; // number of nonlinear path constraints which are equality -} ocp_nlp_constraints_bgh_dims; - -// -acados_size_t ocp_nlp_constraints_bgh_dims_calculate_size(void *config); -// -void *ocp_nlp_constraints_bgh_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_constraints_bgh_dims_get(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_constraints_bgh_dims_set(void *config_, void *dims_, - const char *field, const int* value); - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - int *idxb; - int *idxs; - int *idxe; - struct blasfeo_dvec d; // gathers bounds - struct blasfeo_dmat DCt; // general linear constraint matrix - // lg <= [D, C] * [u; x] <= ug - external_function_generic *nl_constr_h_fun; // nonlinear: lh <= h(x,u) <= uh - external_function_generic *nl_constr_h_fun_jac; // nonlinear: lh <= h(x,u) <= uh - external_function_generic *nl_constr_h_fun_jac_hess; // nonlinear: lh <= h(x,u) <= uh -} ocp_nlp_constraints_bgh_model; - -// -acados_size_t ocp_nlp_constraints_bgh_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_constraints_bgh_model_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_constraints_bgh_model_set(void *config_, void *dims_, - void *model_, const char *field, void *value); - -// -void ocp_nlp_constraints_bgh_model_get(void *config_, void *dims_, - void *model_, const char *field, void *value); - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - int compute_adj; - int compute_hess; -} ocp_nlp_constraints_bgh_opts; - -// -acados_size_t ocp_nlp_constraints_bgh_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_constraints_bgh_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_constraints_bgh_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_constraints_bgh_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_constraints_bgh_opts_set(void *config, void *opts, char *field, void *value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dvec fun; - struct blasfeo_dvec adj; - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out - struct blasfeo_dvec *lam; // pointer to lam in nlp_out - struct blasfeo_dvec *tmp_lam;// pointer to lam in tmp_nlp_out - struct blasfeo_dvec *z_alg; // pointer to z_alg in ocp_nlp memory - struct blasfeo_dmat *DCt; // pointer to DCt in qp_in - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dmat *dzduxt; // pointer to dzduxt in ocp_nlp memory - int *idxb; // pointer to idxb[ii] in qp_in - int *idxs_rev; // pointer to idxs_rev[ii] in qp_in - int *idxe; // pointer to idxe[ii] in qp_in -} ocp_nlp_constraints_bgh_memory; - -// -acados_size_t ocp_nlp_constraints_bgh_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_constraints_bgh_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -struct blasfeo_dvec *ocp_nlp_constraints_bgh_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_constraints_bgh_memory_get_adj_ptr(void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_lam_ptr(struct blasfeo_dvec *lam, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_tmp_lam_ptr(struct blasfeo_dvec *tmp_lam, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_DCt_ptr(struct blasfeo_dmat *DCt, void *memory); -// -void ocp_nlp_constraints_bgh_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_dzduxt_ptr(struct blasfeo_dmat *dzduxt, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_idxb_ptr(int *idxb, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_idxs_rev_ptr(int *idxs_rev, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_idxe_ptr(int *idxe, void *memory_); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat tmp_nv_nv; - struct blasfeo_dmat tmp_nz_nh; - struct blasfeo_dmat tmp_nv_nh; - struct blasfeo_dmat tmp_nz_nv; - struct blasfeo_dmat hess_z; - struct blasfeo_dvec tmp_ni; - struct blasfeo_dvec tmp_nh; -} ocp_nlp_constraints_bgh_workspace; - -// -acados_size_t ocp_nlp_constraints_bgh_workspace_calculate_size(void *config, void *dims, void *opts); - -/* functions */ - -// -void ocp_nlp_constraints_bgh_config_initialize_default(void *config); -// -void ocp_nlp_constraints_bgh_initialize(void *config, void *dims, void *model, void *opts, - void *mem, void *work); -// -void ocp_nlp_constraints_bgh_update_qp_matrices(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); - -// -void ocp_nlp_constraints_bgh_compute_fun(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); -// -void ocp_nlp_constraints_bgh_bounds_update(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGH_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgp.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgp.h deleted file mode 100644 index eb05edf7a6bf2d..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgp.h +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_constraints -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGP_H_ -#define ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_nlp/ocp_nlp_constraints_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/* dims */ - -typedef struct -{ - int nx; - int nu; - int nz; - int nb; // nbx + nbu - int nbu; - int nbx; - int ng; // number of general linear constraints - int nphi; // dimension of convex outer part - int ns; // nsbu + nsbx + nsg + nsphi - int nsbu; // number of softened input bounds - int nsbx; // number of softened state bounds - int nsg; // number of softened general linear constraints - int nsphi; // number of softened nonlinear constraints - int nr; // dimension of nonlinear function in convex_over_nonlinear constraint - int nbue; // number of input box constraints which are equality - int nbxe; // number of state box constraints which are equality - int nge; // number of general linear constraints which are equality - int nphie; // number of nonlinear path constraints which are equality -} ocp_nlp_constraints_bgp_dims; - -// -acados_size_t ocp_nlp_constraints_bgp_dims_calculate_size(void *config); -// -void *ocp_nlp_constraints_bgp_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_constraints_bgp_dims_get(void *config_, void *dims_, const char *field, int* value); - - -/* model */ - -typedef struct -{ - // ocp_nlp_constraints_bgp_dims *dims; - int *idxb; - int *idxs; - int *idxe; - struct blasfeo_dvec d; - struct blasfeo_dmat DCt; - external_function_generic *nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux; - external_function_generic *nl_constr_phi_o_r_fun; - external_function_generic *nl_constr_r_fun_jac; -} ocp_nlp_constraints_bgp_model; - -// -acados_size_t ocp_nlp_constraints_bgp_calculate_size(void *config, void *dims); -// -void *ocp_nlp_constraints_bgp_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_constraints_bgp_model_set(void *config_, void *dims_, - void *model_, const char *field, void *value); -// -void ocp_nlp_constraints_bgp_model_get(void *config_, void *dims_, - void *model_, const char *field, void *value); - -/* options */ - -typedef struct -{ - int compute_adj; - int compute_hess; -} ocp_nlp_constraints_bgp_opts; - -// -acados_size_t ocp_nlp_constraints_bgp_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_constraints_bgp_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_constraints_bgp_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_constraints_bgp_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_constraints_bgp_opts_set(void *config, void *opts, char *field, void *value); - -/* memory */ - -typedef struct -{ - struct blasfeo_dvec fun; - struct blasfeo_dvec adj; - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out - struct blasfeo_dvec *lam; // pointer to lam in nlp_out - struct blasfeo_dvec *tmp_lam;// pointer to lam in tmp_nlp_out - struct blasfeo_dvec *z_alg; // pointer to z_alg in ocp_nlp memory - struct blasfeo_dmat *DCt; // pointer to DCt in qp_in - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dmat *dzduxt; // pointer to dzduxt in ocp_nlp memory - int *idxb; // pointer to idxb[ii] in qp_in - int *idxs_rev; // pointer to idxs_rev[ii] in qp_in - int *idxe; // pointer to idxe[ii] in qp_in -} ocp_nlp_constraints_bgp_memory; - -// -acados_size_t ocp_nlp_constraints_bgp_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_constraints_bgp_memory_assign(void *config, void *dims, void *opts, - void *raw_memory); -// -struct blasfeo_dvec *ocp_nlp_constraints_bgp_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_constraints_bgp_memory_get_adj_ptr(void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_lam_ptr(struct blasfeo_dvec *lam, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_tmp_lam_ptr(struct blasfeo_dvec *tmp_lam, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_DCt_ptr(struct blasfeo_dmat *DCt, void *memory); -// -void ocp_nlp_constraints_bgp_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_dzduxt_ptr(struct blasfeo_dmat *dzduxt, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_idxb_ptr(int *idxb, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_idxs_rev_ptr(int *idxs_rev, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_idxe_ptr(int *idxe, void *memory_); - -/* workspace */ - -typedef struct -{ - struct blasfeo_dvec tmp_ni; - struct blasfeo_dmat jac_r_ux_tran; - struct blasfeo_dmat tmp_nr_nphi_nr; - struct blasfeo_dmat tmp_nv_nr; - struct blasfeo_dmat tmp_nv_nphi; - struct blasfeo_dmat tmp_nz_nphi; -} ocp_nlp_constraints_bgp_workspace; - -// -acados_size_t ocp_nlp_constraints_bgp_workspace_calculate_size(void *config, void *dims, void *opts); - -/* functions */ - -// -void ocp_nlp_constraints_bgp_config_initialize_default(void *config); -// -void ocp_nlp_constraints_bgp_initialize(void *config, void *dims, void *model, - void *opts, void *mem, void *work); -// -void ocp_nlp_constraints_bgp_update_qp_matrices(void *config_, void *dims, - void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_constraints_bgp_compute_fun(void *config_, void *dims, - void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_constraints_bgp_bounds_update(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGP_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_common.h deleted file mode 100644 index bb73c468deb377..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_common.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \ingroup ocp_nlp -/// @{ - -/// \defgroup ocp_nlp_constraints ocp_nlp_constraints -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * config - ************************************************/ - -typedef struct -{ - acados_size_t (*dims_calculate_size)(void *config); - void *(*dims_assign)(void *config, void *raw_memory); - acados_size_t (*model_calculate_size)(void *config, void *dims); - void *(*model_assign)(void *config, void *dims, void *raw_memory); - int (*model_set)(void *config_, void *dims_, void *model_, const char *field, void *value); - void (*model_get)(void *config_, void *dims_, void *model_, const char *field, void *value); - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts); - void (*opts_update)(void *config, void *dims, void *opts); - void (*opts_set)(void *config, void *opts, char *field, void *value); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - struct blasfeo_dvec *(*memory_get_fun_ptr)(void *memory); - struct blasfeo_dvec *(*memory_get_adj_ptr)(void *memory); - void (*memory_set_ux_ptr)(struct blasfeo_dvec *ux, void *memory); - void (*memory_set_tmp_ux_ptr)(struct blasfeo_dvec *tmp_ux, void *memory); - void (*memory_set_lam_ptr)(struct blasfeo_dvec *lam, void *memory); - void (*memory_set_tmp_lam_ptr)(struct blasfeo_dvec *tmp_lam, void *memory); - void (*memory_set_DCt_ptr)(struct blasfeo_dmat *DCt, void *memory); - void (*memory_set_RSQrq_ptr)(struct blasfeo_dmat *RSQrq, void *memory); - void (*memory_set_z_alg_ptr)(struct blasfeo_dvec *z_alg, void *memory); - void (*memory_set_dzdux_tran_ptr)(struct blasfeo_dmat *dzduxt, void *memory); - void (*memory_set_idxb_ptr)(int *idxb, void *memory); - void (*memory_set_idxs_rev_ptr)(int *idxs_rev, void *memory); - void (*memory_set_idxe_ptr)(int *idxe, void *memory); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - void (*initialize)(void *config, void *dims, void *model, void *opts, void *mem, void *work); - void (*update_qp_matrices)(void *config, void *dims, void *model, void *opts, void *mem, void *work); - void (*compute_fun)(void *config, void *dims, void *model, void *opts, void *mem, void *work); - void (*bounds_update)(void *config, void *dims, void *model, void *opts, void *mem, void *work); - void (*config_initialize_default)(void *config); - // dimension setters - void (*dims_set)(void *config_, void *dims_, const char *field, const int *value); - void (*dims_get)(void *config_, void *dims_, const char *field, int* value); -} ocp_nlp_constraints_config; - -// -acados_size_t ocp_nlp_constraints_config_calculate_size(); -// -ocp_nlp_constraints_config *ocp_nlp_constraints_config_assign(void *raw_memory); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_COMMON_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_common.h deleted file mode 100644 index eb4056403648c6..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_common.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// -/// \defgroup ocp_nlp_cost ocp_nlp_cost -/// - -/// \addtogroup ocp_nlp_cost ocp_nlp_cost -/// @{ -/// \addtogroup ocp_nlp_cost_common ocp_nlp_cost_common -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * config - ************************************************/ - -typedef struct -{ - acados_size_t (*dims_calculate_size)(void *config); - void *(*dims_assign)(void *config, void *raw_memory); - void (*dims_set)(void *config_, void *dims_, const char *field, int *value); - void (*dims_get)(void *config_, void *dims_, const char *field, int *value); - acados_size_t (*model_calculate_size)(void *config, void *dims); - void *(*model_assign)(void *config, void *dims, void *raw_memory); - int (*model_set)(void *config_, void *dims_, void *model_, const char *field, void *value_); - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts); - void (*opts_update)(void *config, void *dims, void *opts); - void (*opts_set)(void *config, void *opts, const char *field, void *value); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - double *(*memory_get_fun_ptr)(void *memory); - struct blasfeo_dvec *(*memory_get_grad_ptr)(void *memory); - void (*memory_set_ux_ptr)(struct blasfeo_dvec *ux, void *memory); - void (*memory_set_tmp_ux_ptr)(struct blasfeo_dvec *tmp_ux, void *memory); - void (*memory_set_z_alg_ptr)(struct blasfeo_dvec *z_alg, void *memory); - void (*memory_set_dzdux_tran_ptr)(struct blasfeo_dmat *dzdux, void *memory); - void (*memory_set_RSQrq_ptr)(struct blasfeo_dmat *RSQrq, void *memory); - void (*memory_set_Z_ptr)(struct blasfeo_dvec *Z, void *memory); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - void (*initialize)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - - // computes the function value, gradient and hessian (approximation) of the cost function - void (*update_qp_matrices)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - // computes the cost function value (intended for globalization) - void (*compute_fun)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - void (*config_initialize_default)(void *config); - void (*precompute)(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); - -} ocp_nlp_cost_config; - -// -acados_size_t ocp_nlp_cost_config_calculate_size(); -// -ocp_nlp_cost_config *ocp_nlp_cost_config_assign(void *raw_memory); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_COMMON_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_conl.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_conl.h deleted file mode 100644 index 2eb3f5d127a7a9..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_conl.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_cost ocp_nlp_cost -/// @{ -/// \addtogroup ocp_nlp_cost_conl ocp_nlp_cost_conl -/// \brief This module implements convex-over-nonlinear costs of the form -/// \f$\min_{x,u,z} \psi(y(x,u,z,p) - y_{\text{ref}}, p)\f$, - - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_CONL_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_CONL_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; // number of states - int nz; // number of algebraic variables - int nu; // number of inputs - int ny; // number of outputs - int ns; // number of slacks -} ocp_nlp_cost_conl_dims; - -// -acados_size_t ocp_nlp_cost_conl_dims_calculate_size(void *config); -// -void *ocp_nlp_cost_conl_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_cost_conl_dims_initialize(void *config, void *dims, int nx, int nu, int ny, int ns, int nz); -// -void ocp_nlp_cost_conl_dims_set(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_cost_conl_dims_get(void *config_, void *dims_, const char *field, int* value); - - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - // slack penalty has the form z^T * s + .5 * s^T * Z * s - external_function_generic *conl_cost_fun; - external_function_generic *conl_cost_fun_jac_hess; - struct blasfeo_dvec y_ref; - struct blasfeo_dvec Z; // diagonal Hessian of slacks as vector - struct blasfeo_dvec z; // gradient of slacks as vector - double scaling; -} ocp_nlp_cost_conl_model; - -// -acados_size_t ocp_nlp_cost_conl_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_conl_model_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_cost_conl_model_set(void *config_, void *dims_, void *model_, const char *field, void *value_); - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - bool gauss_newton_hess; // dummy options, we always use a gauss-newton hessian -} ocp_nlp_cost_conl_opts; - -// -acados_size_t ocp_nlp_cost_conl_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_conl_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_cost_conl_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_conl_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_conl_opts_set(void *config, void *opts, const char *field, void *value); - - - -/************************************************ - * memory - ************************************************/ -typedef struct -{ - struct blasfeo_dvec grad; // gradient of cost function - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec *Z; // pointer to Z in qp_in - struct blasfeo_dvec *z_alg; ///< pointer to z in sim_out - struct blasfeo_dmat *dzdux_tran; ///< pointer to sensitivity of a wrt ux in sim_out - double fun; ///< value of the cost function -} ocp_nlp_cost_conl_memory; - -// -acados_size_t ocp_nlp_cost_conl_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_cost_conl_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -double *ocp_nlp_cost_conl_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_cost_conl_memory_get_grad_ptr(void *memory_); -// -void ocp_nlp_cost_conl_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory); -// -void ocp_nlp_cost_conl_memory_set_Z_ptr(struct blasfeo_dvec *Z, void *memory); -// -void ocp_nlp_cost_conl_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_cost_conl_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_cost_conl_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_cost_conl_memory_set_dzdux_tran_ptr(struct blasfeo_dmat *dzdux_tran, void *memory_); - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat W; // hessian of outer loss function - struct blasfeo_dmat W_chol; // cholesky factor of hessian of outer loss function - struct blasfeo_dmat Jt_ux; // jacobian of inner residual function - struct blasfeo_dmat Jt_ux_tilde; // jacobian of inner residual function plus gradient contribution of algebraic variables - struct blasfeo_dmat Jt_z; // jacobian of inner residual function wrt algebraic variables - struct blasfeo_dmat tmp_nv_ny; - struct blasfeo_dvec tmp_ny; - struct blasfeo_dvec tmp_2ns; -} ocp_nlp_cost_conl_workspace; - -// -acados_size_t ocp_nlp_cost_conl_workspace_calculate_size(void *config, void *dims, void *opts); - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_cost_conl_precompute(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_conl_config_initialize_default(void *config); -// -void ocp_nlp_cost_conl_initialize(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); -// -void ocp_nlp_cost_conl_update_qp_matrices(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_conl_compute_fun(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_CONL_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_external.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_external.h deleted file mode 100644 index 78958270ded651..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_external.h +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_EXTERNAL_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_EXTERNAL_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; // number of states - int nz; // number of algebraic variables - int nu; // number of inputs - int ns; // number of slacks -} ocp_nlp_cost_external_dims; - -// -acados_size_t ocp_nlp_cost_external_dims_calculate_size(void *config); -// -void *ocp_nlp_cost_external_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_cost_external_dims_set(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_cost_external_dims_get(void *config_, void *dims_, const char *field, int* value); - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - external_function_generic *ext_cost_fun; // function - external_function_generic *ext_cost_fun_jac_hess; // function, gradient and hessian - external_function_generic *ext_cost_fun_jac; // function, gradient - struct blasfeo_dvec Z; - struct blasfeo_dvec z; - struct blasfeo_dmat numerical_hessian; // custom hessian approximation - double scaling; -} ocp_nlp_cost_external_model; - -// -acados_size_t ocp_nlp_cost_external_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_external_model_assign(void *config, void *dims, void *raw_memory); - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - int use_numerical_hessian; // > 0 indicating custom hessian is used instead of CasADi evaluation -} ocp_nlp_cost_external_opts; - -// -acados_size_t ocp_nlp_cost_external_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_external_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_cost_external_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_external_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_external_opts_set(void *config, void *opts, const char *field, void *value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dvec grad; // gradient of cost function - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to tmp_ux in nlp_out - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec *Z; // pointer to Z in qp_in - struct blasfeo_dvec *z_alg; ///< pointer to z in sim_out - struct blasfeo_dmat *dzdux_tran; ///< pointer to sensitivity of a wrt ux in sim_out - double fun; ///< value of the cost function -} ocp_nlp_cost_external_memory; - -// -acados_size_t ocp_nlp_cost_external_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_cost_external_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -double *ocp_nlp_cost_external_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_cost_external_memory_get_grad_ptr(void *memory_); -// -void ocp_nlp_cost_external_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory); -// -void ocp_nlp_cost_ls_memory_set_Z_ptr(struct blasfeo_dvec *Z, void *memory); -// -void ocp_nlp_cost_external_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_cost_external_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_cost_external_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_cost_external_memory_set_dzdux_tran_ptr(struct blasfeo_dmat *dzdux_tran, void *memory_); - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat tmp_nunx_nunx; - struct blasfeo_dmat tmp_nz_nz; - struct blasfeo_dmat tmp_nz_nunx; - struct blasfeo_dvec tmp_nunxnz; - struct blasfeo_dvec tmp_2ns; // temporary vector of dimension 2*ns -} ocp_nlp_cost_external_workspace; - -// -acados_size_t ocp_nlp_cost_external_workspace_calculate_size(void *config, void *dims, void *opts); - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_cost_external_precompute(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_external_config_initialize_default(void *config); -// -void ocp_nlp_cost_external_initialize(void *config_, void *dims, void *model_, - void *opts_, void *mem_, void *work_); -// -void ocp_nlp_cost_external_update_qp_matrices(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_external_compute_fun(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_EXTERNAL_H_ diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_ls.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_ls.h deleted file mode 100644 index 801e9a5b87b2d6..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_ls.h +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_cost ocp_nlp_cost -/// @{ -/// \addtogroup ocp_nlp_cost_ls ocp_nlp_cost_ls -/// \brief This module implements linear-least squares costs of the form -/// \f$\min_{x,u,z} \| V_x x + V_u u + V_z z - y_{\text{ref}}\|_W^2\f$. -/// @{ - - - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_LS_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_LS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - -//////////////////////////////////////////////////////////////////////////////// -// dims // -//////////////////////////////////////////////////////////////////////////////// - -typedef struct -{ - int nx; // number of states - int nz; // number of algebraic variables - int nu; // number of inputs - int ny; // number of outputs - int ns; // number of slacks -} ocp_nlp_cost_ls_dims; - - -/// Calculate the size of the ocp_nlp_cost_ls_dims struct -/// -/// \param[in] config_ structure containing configuration of ocp_nlp_cost -/// module -/// \param[out] [] -/// \return \c size of ocp_nlp_dims struct -acados_size_t ocp_nlp_cost_ls_dims_calculate_size(void *config); - - -/// Assign memory pointed to by raw_memory to ocp_nlp-cost_ls dims struct -/// -/// \param[in] config structure containing configuration of ocp_nlp_cost -/// module -/// \param[in] raw_memory pointer to memory location -/// \param[out] [] -/// \return dims -void *ocp_nlp_cost_ls_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_cost_ls_dims_set(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_cost_ls_dims_get(void *config_, void *dims_, const char *field, int* value); - - -//////////////////////////////////////////////////////////////////////////////// -// model // -//////////////////////////////////////////////////////////////////////////////// - - -/// structure containing the data describing the linear least-square cost -typedef struct -{ - // slack penalty has the form z^T * s + .5 * s^T * Z * s - struct blasfeo_dmat Cyt; ///< output matrix: Cy * [u,x] = y; in transposed form - struct blasfeo_dmat Vz; ///< Vz in ls cost Vx*x + Vu*u + Vz*z - struct blasfeo_dmat W; ///< ls norm corresponding to this matrix - struct blasfeo_dvec y_ref; ///< yref - struct blasfeo_dvec Z; ///< diagonal Hessian of slacks as vector (lower and upper) - struct blasfeo_dvec z; ///< gradient of slacks as vector (lower and upper) - double scaling; - int W_changed; ///< flag indicating whether W has changed and needs to be refactorized - int Cyt_or_scaling_changed; ///< flag indicating whether Cyt or scaling has changed and Hessian needs to be recomputed -} ocp_nlp_cost_ls_model; - -// -acados_size_t ocp_nlp_cost_ls_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_ls_model_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_cost_ls_model_set(void *config_, void *dims_, void *model_, - const char *field, void *value_); - - - -//////////////////////////////////////////////////////////////////////////////// -// options // -//////////////////////////////////////////////////////////////////////////////// - - - -typedef struct -{ - int dummy; // struct can't be void -} ocp_nlp_cost_ls_opts; - -// -acados_size_t ocp_nlp_cost_ls_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_ls_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_cost_ls_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_ls_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_ls_opts_set(void *config, void *opts, const char *field, void *value); - - - -//////////////////////////////////////////////////////////////////////////////// -// memory // -//////////////////////////////////////////////////////////////////////////////// - - - -/// structure containing the memory associated with cost_ls component -/// of the ocp_nlp module -typedef struct -{ - struct blasfeo_dmat hess; ///< hessian of cost function - struct blasfeo_dmat W_chol; ///< cholesky factor of weight matrix - struct blasfeo_dvec res; ///< ls residual r(x) - struct blasfeo_dvec grad; ///< gradient of cost function - struct blasfeo_dvec *ux; ///< pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; ///< pointer to ux in tmp_nlp_out - struct blasfeo_dvec *z_alg; ///< pointer to z in sim_out - struct blasfeo_dmat *dzdux_tran; ///< pointer to sensitivity of a wrt ux in sim_out - struct blasfeo_dmat *RSQrq; ///< pointer to RSQrq in qp_in - struct blasfeo_dvec *Z; ///< pointer to Z in qp_in - double fun; ///< value of the cost function -} ocp_nlp_cost_ls_memory; - -// -acados_size_t ocp_nlp_cost_ls_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_cost_ls_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -double *ocp_nlp_cost_ls_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_cost_ls_memory_get_grad_ptr(void *memory_); -// -void ocp_nlp_cost_ls_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory); -// -void ocp_nlp_cost_ls_memory_set_Z_ptr(struct blasfeo_dvec *Z, void *memory); -// -void ocp_nlp_cost_ls_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_cost_ls_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_cost_ls_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_cost_ls_memory_set_dzdux_tran_ptr(struct blasfeo_dmat *dzdux_tran, void *memory_); - - - -//////////////////////////////////////////////////////////////////////////////// -// workspace // -//////////////////////////////////////////////////////////////////////////////// - - - -typedef struct -{ - struct blasfeo_dmat tmp_nv_ny; // temporary matrix of dimensions nv, ny - struct blasfeo_dmat Cyt_tilde; // updated Cyt (after z elimination) - struct blasfeo_dmat dzdux_tran; // derivatives of z wrt u and x (tran) - struct blasfeo_dvec tmp_ny; // temporary vector of dimension ny - struct blasfeo_dvec tmp_2ns; // temporary vector of dimension ny - struct blasfeo_dvec tmp_nz; // temporary vector of dimension nz - struct blasfeo_dvec y_ref_tilde; // updated y_ref (after z elimination) -} ocp_nlp_cost_ls_workspace; - -// -acados_size_t ocp_nlp_cost_ls_workspace_calculate_size(void *config, void *dims, void *opts); - - - -//////////////////////////////////////////////////////////////////////////////// -// functions // -//////////////////////////////////////////////////////////////////////////////// - - -// computations that are done once when solver is created -void ocp_nlp_cost_ls_precompute(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_ls_config_initialize_default(void *config); -// -void ocp_nlp_cost_ls_initialize(void *config_, void *dims, void *model_, void *opts_, - void *mem_, void *work_); -// -void ocp_nlp_cost_ls_update_qp_matrices(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_ls_compute_fun(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_LS_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_nls.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_nls.h deleted file mode 100644 index 5ec68cf580a3e8..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_nls.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_cost ocp_nlp_cost -/// @{ -/// \addtogroup ocp_nlp_cost_nls ocp_nlp_cost_nls -/// \brief This module implements nonlinear-least squares costs of the form -/// \f$\min_{x,u,z} \| y(x,u,z,p) - y_{\text{ref}} \|_W^2\f$, - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_NLS_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_NLS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; // number of states - int nz; // number of algebraic variables - int nu; // number of inputs - int ny; // number of outputs - int ns; // number of slacks -} ocp_nlp_cost_nls_dims; - -// -acados_size_t ocp_nlp_cost_nls_dims_calculate_size(void *config); -// -void *ocp_nlp_cost_nls_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_cost_nls_dims_set(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_cost_nls_dims_get(void *config_, void *dims_, const char *field, int* value); - - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - // nonliner function nls_y(x,u) replaces Cy * [x,u] in ls_cost - // slack penalty has the form z^T * s + .5 * s^T * Z * s - external_function_generic *nls_y_fun; // evaluation of nls function - external_function_generic *nls_y_fun_jac; // evaluation nls function and jacobian - external_function_generic *nls_y_hess; // hessian*seeds of nls residuals - struct blasfeo_dmat W; // - struct blasfeo_dvec y_ref; - struct blasfeo_dvec Z; // diagonal Hessian of slacks as vector - struct blasfeo_dvec z; // gradient of slacks as vector - double scaling; - int W_changed; ///< flag indicating whether W has changed and needs to be refactorized -} ocp_nlp_cost_nls_model; - -// -acados_size_t ocp_nlp_cost_nls_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_nls_model_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_cost_nls_model_set(void *config_, void *dims_, void *model_, const char *field, void *value_); - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - bool gauss_newton_hess; // gauss-newton hessian approximation -} ocp_nlp_cost_nls_opts; - -// -acados_size_t ocp_nlp_cost_nls_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_nls_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_cost_nls_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_nls_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_nls_opts_set(void *config, void *opts, const char *field, void *value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat W_chol; // cholesky factor of weight matrix - struct blasfeo_dmat Jt; // jacobian of nls fun - struct blasfeo_dvec res; // nls residual r(x) - struct blasfeo_dvec grad; // gradient of cost function - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec *Z; // pointer to Z in qp_in - struct blasfeo_dvec *z_alg; ///< pointer to z in sim_out - struct blasfeo_dmat *dzdux_tran; ///< pointer to sensitivity of a wrt ux in sim_out - double fun; ///< value of the cost function -} ocp_nlp_cost_nls_memory; - -// -acados_size_t ocp_nlp_cost_nls_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_cost_nls_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -double *ocp_nlp_cost_nls_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_cost_nls_memory_get_grad_ptr(void *memory_); -// -void ocp_nlp_cost_nls_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory); -// -void ocp_nlp_cost_nls_memory_set_Z_ptr(struct blasfeo_dvec *Z, void *memory); -// -void ocp_nlp_cost_nls_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_cost_nls_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_cost_nls_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_cost_nls_memory_set_dzdux_tran_ptr(struct blasfeo_dmat *dzdux_tran, void *memory_); - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat tmp_nv_ny; - struct blasfeo_dmat tmp_nv_nv; - struct blasfeo_dmat Vz; - struct blasfeo_dmat Cyt_tilde; - struct blasfeo_dvec tmp_ny; - struct blasfeo_dvec tmp_2ns; - struct blasfeo_dvec tmp_nz; -} ocp_nlp_cost_nls_workspace; - -// -acados_size_t ocp_nlp_cost_nls_workspace_calculate_size(void *config, void *dims, void *opts); - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_cost_nls_precompute(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_nls_config_initialize_default(void *config); -// -void ocp_nlp_cost_nls_initialize(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); -// -void ocp_nlp_cost_nls_update_qp_matrices(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_nls_compute_fun(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_NLS_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h deleted file mode 100644 index 43fe71b12fcfbc..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \ingroup ocp_nlp -/// @{ - -/// \defgroup ocp_nlp_dynamics ocp_nlp_dynamics -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/sim/sim_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * config - ************************************************/ - -typedef struct -{ - void (*config_initialize_default)(void *config); - sim_config *sim_solver; - /* dims */ - acados_size_t (*dims_calculate_size)(void *config); - void *(*dims_assign)(void *config, void *raw_memory); - void (*dims_set)(void *config_, void *dims_, const char *field, int *value); - void (*dims_get)(void *config_, void *dims_, const char *field, int* value); - /* model */ - acados_size_t (*model_calculate_size)(void *config, void *dims); - void *(*model_assign)(void *config, void *dims, void *raw_memory); - void (*model_set)(void *config_, void *dims_, void *model_, const char *field, void *value_); - /* opts */ - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts); - void (*opts_set)(void *config_, void *opts_, const char *field, void *value); - void (*opts_update)(void *config, void *dims, void *opts); - /* memory */ - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - // get shooting node gap x_next(x_n, u_n) - x_{n+1} - struct blasfeo_dvec *(*memory_get_fun_ptr)(void *memory_); - struct blasfeo_dvec *(*memory_get_adj_ptr)(void *memory_); - void (*memory_set_ux_ptr)(struct blasfeo_dvec *ux, void *memory_); - void (*memory_set_tmp_ux_ptr)(struct blasfeo_dvec *tmp_ux, void *memory_); - void (*memory_set_ux1_ptr)(struct blasfeo_dvec *ux1, void *memory_); - void (*memory_set_tmp_ux1_ptr)(struct blasfeo_dvec *tmp_ux1, void *memory_); - void (*memory_set_pi_ptr)(struct blasfeo_dvec *pi, void *memory_); - void (*memory_set_tmp_pi_ptr)(struct blasfeo_dvec *tmp_pi, void *memory_); - void (*memory_set_BAbt_ptr)(struct blasfeo_dmat *BAbt, void *memory_); - void (*memory_set_RSQrq_ptr)(struct blasfeo_dmat *RSQrq, void *memory_); - void (*memory_set_dzduxt_ptr)(struct blasfeo_dmat *mat, void *memory_); - void (*memory_set_sim_guess_ptr)(struct blasfeo_dvec *vec, bool *bool_ptr, void *memory_); - void (*memory_set_z_alg_ptr)(struct blasfeo_dvec *vec, void *memory_); - void (*memory_get)(void *config, void *dims, void *mem, const char *field, void* value); - /* workspace */ - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - void (*initialize)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - void (*update_qp_matrices)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - void (*compute_fun)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - int (*precompute)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); -} ocp_nlp_dynamics_config; - -// -acados_size_t ocp_nlp_dynamics_config_calculate_size(); -// -ocp_nlp_dynamics_config *ocp_nlp_dynamics_config_assign(void *raw_memory); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_COMMON_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_cont.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_cont.h deleted file mode 100644 index 3afdc9f4ed83f2..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_cont.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_dynamics -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_CONT_H_ -#define ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_CONT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_dynamics_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" -#include "acados_c/sim_interface.h" - - - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - void *sim; - int nx; // number of states at the current stage - int nz; // number of algebraic states at the current stage - int nu; // number of inputs at the current stage - int nx1; // number of states at the next stage - int nu1; // number of inputes at the next stage -} ocp_nlp_dynamics_cont_dims; - -// -acados_size_t ocp_nlp_dynamics_cont_dims_calculate_size(void *config); -// -void *ocp_nlp_dynamics_cont_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_dynamics_cont_dims_set(void *config_, void *dims_, const char *field, int* value); - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - void *sim_solver; - int compute_adj; - int compute_hess; -} ocp_nlp_dynamics_cont_opts; - -// -acados_size_t ocp_nlp_dynamics_cont_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_dynamics_cont_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_dynamics_cont_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_dynamics_cont_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_dynamics_cont_opts_set(void *config, void *opts, const char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dvec fun; - struct blasfeo_dvec adj; - struct blasfeo_dvec *ux; // pointer to ux in nlp_out at current stage - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out at current stage - struct blasfeo_dvec *ux1; // pointer to ux in nlp_out at next stage - struct blasfeo_dvec *tmp_ux1; // pointer to ux in tmp_nlp_out at next stage - struct blasfeo_dvec *pi; // pointer to pi in nlp_out at current stage - struct blasfeo_dvec *tmp_pi; // pointer to pi in tmp_nlp_out at current stage - struct blasfeo_dmat *BAbt; // pointer to BAbt in qp_in - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec *z_alg; // pointer to output z at t = 0 - bool *set_sim_guess; // indicate if initialization for integrator is set from outside - struct blasfeo_dvec *sim_guess; // initializations for integrator - // struct blasfeo_dvec *z; // pointer to (input) z in nlp_out at current stage - struct blasfeo_dmat *dzduxt; // pointer to dzdux transposed - void *sim_solver; // sim solver memory -} ocp_nlp_dynamics_cont_memory; - -// -acados_size_t ocp_nlp_dynamics_cont_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_dynamics_cont_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -struct blasfeo_dvec *ocp_nlp_dynamics_cont_memory_get_fun_ptr(void *memory); -// -struct blasfeo_dvec *ocp_nlp_dynamics_cont_memory_get_adj_ptr(void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_ux1_ptr(struct blasfeo_dvec *ux1, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_tmp_ux1_ptr(struct blasfeo_dvec *tmp_ux1, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_pi_ptr(struct blasfeo_dvec *pi, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_tmp_pi_ptr(struct blasfeo_dvec *tmp_pi, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_BAbt_ptr(struct blasfeo_dmat *BAbt, void *memory); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat hess; - sim_in *sim_in; - sim_out *sim_out; - void *sim_solver; // sim solver workspace -} ocp_nlp_dynamics_cont_workspace; - -acados_size_t ocp_nlp_dynamics_cont_workspace_calculate_size(void *config, void *dims, void *opts); - - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - void *sim_model; - // double *state_transition; // TODO - double T; // simulation time -} ocp_nlp_dynamics_cont_model; - -// -acados_size_t ocp_nlp_dynamics_cont_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_dynamics_cont_model_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_dynamics_cont_model_set(void *config_, void *dims_, void *model_, const char *field, void *value); - - - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_dynamics_cont_config_initialize_default(void *config); -// -void ocp_nlp_dynamics_cont_initialize(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -void ocp_nlp_dynamics_cont_update_qp_matrices(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -void ocp_nlp_dynamics_cont_compute_fun(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -int ocp_nlp_dynamics_cont_precompute(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_CONT_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_disc.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_disc.h deleted file mode 100644 index 6ea26a70106fc6..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_disc.h +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_dynamics -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_DISC_H_ -#define ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_DISC_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_dynamics_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; // number of states at the current stage - int nu; // number of inputs at the current stage - int nx1; // number of states at the next stage - int nu1; // number of inputes at the next stage -} ocp_nlp_dynamics_disc_dims; - -// -acados_size_t ocp_nlp_dynamics_disc_dims_calculate_size(void *config); -// -void *ocp_nlp_dynamics_disc_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_dynamics_disc_dims_set(void *config_, void *dims_, const char *dim, int* value); - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - int compute_adj; - int compute_hess; -} ocp_nlp_dynamics_disc_opts; - -// -acados_size_t ocp_nlp_dynamics_disc_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_dynamics_disc_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_dynamics_disc_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_dynamics_disc_opts_update(void *config, void *dims, void *opts); -// -int ocp_nlp_dynamics_disc_precompute(void *config_, void *dims, void *model_, void *opts_, - void *mem_, void *work_); - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dvec fun; - struct blasfeo_dvec adj; - struct blasfeo_dvec *ux; // pointer to ux in nlp_out at current stage - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out at current stage - struct blasfeo_dvec *ux1; // pointer to ux in nlp_out at next stage - struct blasfeo_dvec *tmp_ux1;// pointer to ux in tmp_nlp_out at next stage - struct blasfeo_dvec *pi; // pointer to pi in nlp_out at current stage - struct blasfeo_dvec *tmp_pi; // pointer to pi in tmp_nlp_out at current stage - struct blasfeo_dmat *BAbt; // pointer to BAbt in qp_in - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in -} ocp_nlp_dynamics_disc_memory; - -// -acados_size_t ocp_nlp_dynamics_disc_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_dynamics_disc_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -struct blasfeo_dvec *ocp_nlp_dynamics_disc_memory_get_fun_ptr(void *memory); -// -struct blasfeo_dvec *ocp_nlp_dynamics_disc_memory_get_adj_ptr(void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_ux1_ptr(struct blasfeo_dvec *ux1, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_tmp_ux1_ptr(struct blasfeo_dvec *tmp_ux1, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_pi_ptr(struct blasfeo_dvec *pi, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_tmp_pi_ptr(struct blasfeo_dvec *tmp_pi, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_BAbt_ptr(struct blasfeo_dmat *BAbt, void *memory); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat tmp_nv_nv; -} ocp_nlp_dynamics_disc_workspace; - -acados_size_t ocp_nlp_dynamics_disc_workspace_calculate_size(void *config, void *dims, void *opts); - - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - external_function_generic *disc_dyn_fun; - external_function_generic *disc_dyn_fun_jac; - external_function_generic *disc_dyn_fun_jac_hess; -} ocp_nlp_dynamics_disc_model; - -// -acados_size_t ocp_nlp_dynamics_disc_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_dynamics_disc_model_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_dynamics_disc_model_set(void *config_, void *dims_, void *model_, const char *field, void *value); - - - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_dynamics_disc_config_initialize_default(void *config); -// -void ocp_nlp_dynamics_disc_initialize(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -void ocp_nlp_dynamics_disc_update_qp_matrices(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -void ocp_nlp_dynamics_disc_compute_fun(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_DISC_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_common.h deleted file mode 100644 index 9388f3fd24651a..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_common.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \ingroup ocp_nlp -/// @{ - -/// \defgroup ocp_nlp_reg ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" - - - -/* dims */ - -//typedef ocp_qp_dims ocp_nlp_reg_dims; -typedef struct -{ - int *nx; - int *nu; - int *nbu; - int *nbx; - int *ng; - int N; -} ocp_nlp_reg_dims; - -// -acados_size_t ocp_nlp_reg_dims_calculate_size(int N); -// -ocp_nlp_reg_dims *ocp_nlp_reg_dims_assign(int N, void *raw_memory); -// -void ocp_nlp_reg_dims_set(void *config_, ocp_nlp_reg_dims *dims, int stage, char *field, int* value); - - - -/* config */ - -typedef struct -{ - /* dims */ - acados_size_t (*dims_calculate_size)(int N); - ocp_nlp_reg_dims *(*dims_assign)(int N, void *raw_memory); - void (*dims_set)(void *config, ocp_nlp_reg_dims *dims, int stage, char *field, int *value); - /* opts */ - acados_size_t (*opts_calculate_size)(void); - void *(*opts_assign)(void *raw_memory); - void (*opts_initialize_default)(void *config, ocp_nlp_reg_dims *dims, void *opts); - void (*opts_set)(void *config, ocp_nlp_reg_dims *dims, void *opts, char *field, void* value); - /* memory */ - acados_size_t (*memory_calculate_size)(void *config, ocp_nlp_reg_dims *dims, void *opts); - void *(*memory_assign)(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - void (*memory_set)(void *config, ocp_nlp_reg_dims *dims, void *memory, char *field, void* value); - void (*memory_set_RSQrq_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dmat *mat, void *memory); - void (*memory_set_rq_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - void (*memory_set_BAbt_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dmat *mat, void *memory); - void (*memory_set_b_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - void (*memory_set_idxb_ptr)(ocp_nlp_reg_dims *dims, int **idxb, void *memory); - void (*memory_set_DCt_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dmat *mat, void *memory); - void (*memory_set_ux_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - void (*memory_set_pi_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - void (*memory_set_lam_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - /* functions */ - void (*regularize_hessian)(void *config, ocp_nlp_reg_dims *dims, void *opts, void *memory); - void (*correct_dual_sol)(void *config, ocp_nlp_reg_dims *dims, void *opts, void *memory); -} ocp_nlp_reg_config; - -// -acados_size_t ocp_nlp_reg_config_calculate_size(void); -// -void *ocp_nlp_reg_config_assign(void *raw_memory); - - - -/* regularization help functions */ -void acados_reconstruct_A(int dim, double *A, double *V, double *d); -void acados_mirror(int dim, double *A, double *V, double *d, double *e, double epsilon); -void acados_project(int dim, double *A, double *V, double *d, double *e, double epsilon); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_COMMON_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_convexify.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_convexify.h deleted file mode 100644 index cb523525e188bd..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_convexify.h +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_CONVEXIFY_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_CONVEXIFY_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - double delta; - double epsilon; -// double gamma; // 0.0 -} ocp_nlp_reg_convexify_opts; - -// -acados_size_t ocp_nlp_reg_convexify_opts_calculate_size(void); -// -void *ocp_nlp_reg_convexify_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_convexify_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_convexify_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct { - double *R; - double *V; // TODO move to workspace - double *d; // TODO move to workspace - double *e; // TODO move to workspace - double *reg_hess; // TODO move to workspace - - struct blasfeo_dmat Q_tilde; - struct blasfeo_dmat Q_bar; - struct blasfeo_dmat BAQ; - struct blasfeo_dmat L; - struct blasfeo_dmat delta_eye; - struct blasfeo_dmat St_copy; - - struct blasfeo_dmat *original_RSQrq; - struct blasfeo_dmat tmp_RSQ; - - struct blasfeo_dvec tmp_nuxM; - struct blasfeo_dvec tmp_nbgM; - -// struct blasfeo_dvec grad; -// struct blasfeo_dvec b2; - - // giaf's - struct blasfeo_dmat **RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec **rq; // pointer to rq in qp_in - struct blasfeo_dmat **BAbt; // pointer to BAbt in qp_in - struct blasfeo_dvec **b; // pointer to b in qp_in - struct blasfeo_dmat **DCt; // pointer to DCt in qp_in - struct blasfeo_dvec **ux; // pointer to ux in qp_out - struct blasfeo_dvec **pi; // pointer to pi in qp_out - struct blasfeo_dvec **lam; // pointer to lam in qp_out - int **idxb; // pointer to idxb in qp_in - -} ocp_nlp_reg_convexify_memory; - -// -acados_size_t ocp_nlp_reg_convexify_calculate_memory_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_convexify_assign_memory(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - - // TODO - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_convexify_config_initialize_default(ocp_nlp_reg_config *config); - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_CONVEXIFY_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_mirror.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_mirror.h deleted file mode 100644 index 84a023cb69f077..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_mirror.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_MIRROR_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_MIRROR_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - double epsilon; -} ocp_nlp_reg_mirror_opts; - -// -acados_size_t ocp_nlp_reg_mirror_opts_calculate_size(void); -// -void *ocp_nlp_reg_mirror_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_mirror_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_mirror_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - double *reg_hess; // TODO move to workspace - double *V; // TODO move to workspace - double *d; // TODO move to workspace - double *e; // TODO move to workspace - - // giaf's - struct blasfeo_dmat **RSQrq; // pointer to RSQrq in qp_in -} ocp_nlp_reg_mirror_memory; - -// -acados_size_t ocp_nlp_reg_mirror_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_mirror_memory_assign(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - - // TODO - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_mirror_config_initialize_default(ocp_nlp_reg_config *config); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_MIRROR_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h deleted file mode 100644 index b571f3bac1508d..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_NOREG_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_NOREG_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - - -/************************************************ - * options - ************************************************/ - -// -acados_size_t ocp_nlp_reg_noreg_opts_calculate_size(void); -// -void *ocp_nlp_reg_noreg_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_noreg_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_noreg_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ -// -acados_size_t ocp_nlp_reg_noreg_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_noreg_memory_assign(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - -// not needed - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_noreg_config_initialize_default(ocp_nlp_reg_config *config); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_NOREG_H_ - -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project.h deleted file mode 100644 index 682ea206dc50ae..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - double epsilon; -} ocp_nlp_reg_project_opts; - -// -acados_size_t ocp_nlp_reg_project_opts_calculate_size(void); -// -void *ocp_nlp_reg_project_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_project_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_project_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - double *reg_hess; // TODO move to workspace - double *V; // TODO move to workspace - double *d; // TODO move to workspace - double *e; // TODO move to workspace - - // giaf's - struct blasfeo_dmat **RSQrq; // pointer to RSQrq in qp_in -} ocp_nlp_reg_project_memory; - -// -acados_size_t ocp_nlp_reg_project_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_project_memory_assign(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - - // TODO - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_project_config_initialize_default(ocp_nlp_reg_config *config); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project_reduc_hess.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project_reduc_hess.h deleted file mode 100644 index 7e12952c15265a..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project_reduc_hess.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_REDUC_HESS_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_REDUC_HESS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - double thr_eig; - double min_eig; - double min_pivot; - int pivoting; -} ocp_nlp_reg_project_reduc_hess_opts; - -// -acados_size_t ocp_nlp_reg_project_reduc_hess_opts_calculate_size(void); -// -void *ocp_nlp_reg_project_reduc_hess_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_project_reduc_hess_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_project_reduc_hess_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - double *reg_hess; // TODO move to workspace - double *V; // TODO move to workspace - double *d; // TODO move to workspace - double *e; // TODO move to workspace - - // giaf's - struct blasfeo_dmat L; // TODO move to workspace - struct blasfeo_dmat L2; // TODO move to workspace - struct blasfeo_dmat L3; // TODO move to workspace - struct blasfeo_dmat Ls; // TODO move to workspace - struct blasfeo_dmat P; // TODO move to workspace - struct blasfeo_dmat AL; // TODO move to workspace - - struct blasfeo_dmat **RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dmat **BAbt; // pointer to RSQrq in qp_in -} ocp_nlp_reg_project_reduc_hess_memory; - -// -acados_size_t ocp_nlp_reg_project_reduc_hess_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_project_reduc_hess_memory_assign(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - - // TODO - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_project_reduc_hess_config_initialize_default(ocp_nlp_reg_config *config); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_REDUC_HESS_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h deleted file mode 100644 index fdb96417f94d71..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_solver -/// @{ -/// \addtogroup ocp_nlp_sqp ocp_nlp_sqp -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_SQP_H_ -#define ACADOS_OCP_NLP_OCP_NLP_SQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_nlp/ocp_nlp_common.h" -#include "acados/utils/types.h" - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - ocp_nlp_opts *nlp_opts; - double tol_stat; // exit tolerance on stationarity condition - double tol_eq; // exit tolerance on equality constraints - double tol_ineq; // exit tolerance on inequality constraints - double tol_comp; // exit tolerance on complementarity condition - int max_iter; - int ext_qp_res; // compute external QP residuals (i.e. at SQP level) at each SQP iteration (for debugging) - int qp_warm_start; // qp_warm_start in all but the first sqp iterations - bool warm_start_first_qp; // to set qp_warm_start in first iteration - int rti_phase; // only phase 0 at the moment - int initialize_t_slacks; // 0-false or 1-true - -} ocp_nlp_sqp_opts; - -// -acados_size_t ocp_nlp_sqp_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_sqp_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_sqp_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_sqp_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_sqp_opts_set(void *config_, void *opts_, const char *field, void* value); -// -void ocp_nlp_sqp_opts_set_at_stage(void *config_, void *opts_, size_t stage, const char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - // nlp memory - ocp_nlp_memory *nlp_mem; - - double time_qp_sol; - double time_qp_solver_call; - double time_qp_xcond; - double time_lin; - double time_reg; - double time_tot; - double time_glob; - double time_sim; - double time_sim_la; - double time_sim_ad; - double time_solution_sensitivities; - - // statistics - double *stat; - int stat_m; - int stat_n; - - int status; - int sqp_iter; - -} ocp_nlp_sqp_memory; - -// -acados_size_t ocp_nlp_sqp_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *ocp_nlp_sqp_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -// -void ocp_nlp_sqp_memory_reset_qp_solver(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, - void *opts_, void *mem_, void *work_); - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - ocp_nlp_workspace *nlp_work; - - // temp QP in & out (to be used as workspace in param sens) - ocp_qp_in *tmp_qp_in; - ocp_qp_out *tmp_qp_out; - - // qp residuals - ocp_qp_res *qp_res; - ocp_qp_res_ws *qp_res_ws; - -} ocp_nlp_sqp_workspace; - -// -acados_size_t ocp_nlp_sqp_workspace_calculate_size(void *config, void *dims, void *opts_); - - - -/************************************************ - * functions - ************************************************/ - -// -int ocp_nlp_sqp(void *config, void *dims, void *nlp_in, void *nlp_out, - void *args, void *mem, void *work_); -// -void ocp_nlp_sqp_config_initialize_default(void *config_); -// -int ocp_nlp_sqp_precompute(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, - void *opts_, void *mem_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_SQP_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h deleted file mode 100644 index 364d0f47178835..00000000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_solver -/// @{ -/// \addtogroup ocp_nlp_sqp_rti ocp_nlp_sqp_rti -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_SQP_RTI_H_ -#define ACADOS_OCP_NLP_OCP_NLP_SQP_RTI_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_nlp/ocp_nlp_common.h" -#include "acados/utils/types.h" - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - ocp_nlp_opts *nlp_opts; - int compute_dual_sol; - int ext_qp_res; // compute external QP residuals (i.e. at SQP level) at each SQP iteration (for debugging) - int qp_warm_start; // NOTE: this is not actually setting the warm_start! Just for compatibility with sqp. - bool warm_start_first_qp; // to set qp_warm_start in first iteration - int rti_phase; // phase of RTI. Possible values 1 (preparation), 2 (feedback) 0 (both) - -} ocp_nlp_sqp_rti_opts; - -// -acados_size_t ocp_nlp_sqp_rti_opts_calculate_size(void *config_, void *dims_); -// -void *ocp_nlp_sqp_rti_opts_assign(void *config_, void *dims_, void *raw_memory); -// -void ocp_nlp_sqp_rti_opts_initialize_default(void *config_, void *dims_, void *opts_); -// -void ocp_nlp_sqp_rti_opts_update(void *config_, void *dims_, void *opts_); -// -void ocp_nlp_sqp_rti_opts_set(void *config_, void *opts_, const char *field, void* value); -// -void ocp_nlp_sqp_rti_opts_set_at_stage(void *config_, void *opts_, size_t stage, - const char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - // nlp memory - ocp_nlp_memory *nlp_mem; - - double time_qp_sol; - double time_qp_solver_call; - double time_qp_xcond; - double time_lin; - double time_reg; - double time_tot; - double time_glob; - double time_solution_sensitivities; - - // statistics - double *stat; - int stat_m; - int stat_n; - - int status; - -} ocp_nlp_sqp_rti_memory; - -// -acados_size_t ocp_nlp_sqp_rti_memory_calculate_size(void *config_, void *dims_, void *opts_); -// -void *ocp_nlp_sqp_rti_memory_assign(void *config_, void *dims_, void *opts_, - void *raw_memory); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - ocp_nlp_workspace *nlp_work; - - // temp QP in & out (to be used as workspace in param sens) - ocp_qp_in *tmp_qp_in; - ocp_qp_out *tmp_qp_out; - - // qp residuals - ocp_qp_res *qp_res; - ocp_qp_res_ws *qp_res_ws; - - -} ocp_nlp_sqp_rti_workspace; - -// -acados_size_t ocp_nlp_sqp_rti_workspace_calculate_size(void *config_, void *dims_, void *opts_); - - - -/************************************************ - * functions - ************************************************/ -// -int ocp_nlp_sqp_rti(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, - void *opts_, void *mem_, void *work_); -// -void ocp_nlp_sqp_rti_config_initialize_default(void *config_); -// -int ocp_nlp_sqp_rti_precompute(void *config_, void *dims_, - void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_SQP_RTI_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h deleted file mode 100644 index d1a45635e40547..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_COMMON_H_ -#define ACADOS_OCP_QP_OCP_QP_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_ocp_qp.h" -#include "hpipm/include/hpipm_d_ocp_qp_dim.h" -#include "hpipm/include/hpipm_d_ocp_qp_res.h" -#include "hpipm/include/hpipm_d_ocp_qp_sol.h" -// acados -#include "acados/utils/types.h" - - - -typedef struct d_ocp_qp_dim ocp_qp_dims; -typedef struct d_ocp_qp ocp_qp_in; -typedef struct d_ocp_qp_sol ocp_qp_out; -typedef struct d_ocp_qp_res ocp_qp_res; -typedef struct d_ocp_qp_res_ws ocp_qp_res_ws; - - - -#ifndef QP_SOLVER_CONFIG_ -#define QP_SOLVER_CONFIG_ -typedef struct -{ - void (*dims_set)(void *config_, void *dims_, int stage, const char *field, int* value); - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts); - void (*opts_update)(void *config, void *dims, void *opts); - void (*opts_set)(void *config_, void *opts_, const char *field, void* value); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - void (*memory_get)(void *config_, void *mem_, const char *field, void* value); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - int (*evaluate)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); - void (*memory_reset)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); - void (*eval_sens)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); -} qp_solver_config; -#endif - - - -typedef struct -{ - acados_size_t (*dims_calculate_size)(void *config, int N); - void *(*dims_assign)(void *config, int N, void *raw_memory); - void (*dims_set)(void *config, void *dims_, int stage, const char *field, int* value); - void (*dims_get)(void *config, void *dims, const char *field, void* value); - // TODO add config everywhere !!!!! - acados_size_t (*opts_calculate_size)(void *dims); - void *(*opts_assign)(void *dims, void *raw_memory); - void (*opts_initialize_default)(void *dims, void *opts); - void (*opts_update)(void *dims, void *opts); - void (*opts_set)(void *opts_, const char *field, void* value); - acados_size_t (*memory_calculate_size)(void *dims, void *opts); - void *(*memory_assign)(void *dims, void *opts, void *raw_memory); - void (*memory_get)(void *config, void *mem, const char *field, void* value); - acados_size_t (*workspace_calculate_size)(void *dims, void *opts); - int (*condensing)(void *qp_in, void *qp_out, void *opts, void *mem, void *work); - int (*condensing_rhs)(void *qp_in, void *qp_out, void *opts, void *mem, void *work); - int (*expansion)(void *qp_in, void *qp_out, void *opts, void *mem, void *work); -} ocp_qp_xcond_config; - - - -/// Struct containing metrics of the qp solver. -#ifndef QP_INFO_ -#define QP_INFO_ -typedef struct -{ - double solve_QP_time; - double condensing_time; - double interface_time; - double total_time; - int num_iter; - int t_computed; -} qp_info; -#endif - - - -/* config */ -// -acados_size_t ocp_qp_solver_config_calculate_size(); -// -qp_solver_config *ocp_qp_solver_config_assign(void *raw_memory); -// -acados_size_t ocp_qp_condensing_config_calculate_size(); -// -ocp_qp_xcond_config *ocp_qp_condensing_config_assign(void *raw_memory); - - -/* dims */ -// -acados_size_t ocp_qp_dims_calculate_size(int N); -// -ocp_qp_dims *ocp_qp_dims_assign(int N, void *raw_memory); -// -void ocp_qp_dims_set(void *config_, void *dims, int stage, const char *field, int* value); -// -void ocp_qp_dims_get(void *config_, void *dims, int stage, const char *field, int* value); - - -/* in */ -// -acados_size_t ocp_qp_in_calculate_size(ocp_qp_dims *dims); -// -ocp_qp_in *ocp_qp_in_assign(ocp_qp_dims *dims, void *raw_memory); - - -/* out */ -// -acados_size_t ocp_qp_out_calculate_size(ocp_qp_dims *dims); -// -ocp_qp_out *ocp_qp_out_assign(ocp_qp_dims *dims, void *raw_memory); - -/* res */ -// -acados_size_t ocp_qp_res_calculate_size(ocp_qp_dims *dims); -// -ocp_qp_res *ocp_qp_res_assign(ocp_qp_dims *dims, void *raw_memory); -// -acados_size_t ocp_qp_res_workspace_calculate_size(ocp_qp_dims *dims); -// -ocp_qp_res_ws *ocp_qp_res_workspace_assign(ocp_qp_dims *dims, void *raw_memory); -// -void ocp_qp_res_compute(ocp_qp_in *qp_in, ocp_qp_out *qp_out, ocp_qp_res *qp_res, ocp_qp_res_ws *res_ws); -// -void ocp_qp_res_compute_nrm_inf(ocp_qp_res *qp_res, double res[4]); - - -/* misc */ -// -void ocp_qp_stack_slacks_dims(ocp_qp_dims *in, ocp_qp_dims *out); -// -void ocp_qp_stack_slacks(ocp_qp_in *in, ocp_qp_in *out); -// -void ocp_qp_compute_t(ocp_qp_in *qp_in, ocp_qp_out *qp_out); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_COMMON_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_common_frontend.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_common_frontend.h deleted file mode 100644 index f65f602c15c304..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_common_frontend.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_COMMON_FRONTEND_H_ -#define ACADOS_OCP_QP_OCP_QP_COMMON_FRONTEND_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" - -typedef struct -{ - int N; - int *nx; - int *nu; - int *nb; - int *nc; - double **A; - double **B; - double **b; - double **Q; - double **S; - double **R; - double **q; - double **r; - int **idxb; - double **lb; - double **ub; - double **Cx; - double **Cu; - double **lc; - double **uc; -} colmaj_ocp_qp_in; - -typedef struct -{ - double **x; - double **u; - double **pi; - double **lam; -} colmaj_ocp_qp_out; - -typedef struct -{ - double **res_r; - double **res_q; - double **res_ls; - double **res_us; - double **res_b; - double **res_d_lb; - double **res_d_ub; - double **res_d_lg; - double **res_d_ug; - double **res_d_ls; - double **res_d_us; - double **res_m_lb; - double **res_m_ub; - double **res_m_lg; - double **res_m_ug; - double **res_m_ls; - double **res_m_us; - double res_nrm_inf[4]; -} colmaj_ocp_qp_res; - -// -acados_size_t colmaj_ocp_qp_in_calculate_size(ocp_qp_dims *dims); -// -char *assign_colmaj_ocp_qp_in(ocp_qp_dims *dims, colmaj_ocp_qp_in **qp_in, void *ptr); -// -acados_size_t colmaj_ocp_qp_out_calculate_size(ocp_qp_dims *dims); -// -char *assign_colmaj_ocp_qp_out(ocp_qp_dims *dims, colmaj_ocp_qp_out **qp_out, void *ptr); -// -acados_size_t colmaj_ocp_qp_res_calculate_size(ocp_qp_dims *dims); -// -char *assign_colmaj_ocp_qp_res(ocp_qp_dims *dims, colmaj_ocp_qp_res **qp_res, void *ptr); -// -void convert_colmaj_to_ocp_qp_in(colmaj_ocp_qp_in *cm_qp_in, ocp_qp_in *qp_in); -// -void convert_ocp_qp_out_to_colmaj(ocp_qp_out *qp_out, colmaj_ocp_qp_out *cm_qp_out); -// -void convert_ocp_qp_res_to_colmaj(ocp_qp_res *qp_res, colmaj_ocp_qp_res *cm_qp_res); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_COMMON_FRONTEND_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_full_condensing.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_full_condensing.h deleted file mode 100644 index d23e658b4806c4..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_full_condensing.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_FULL_CONDENSING_H_ -#define ACADOS_OCP_QP_OCP_QP_FULL_CONDENSING_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_ocp_qp_red.h" -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - - - -typedef struct -{ - ocp_qp_dims *orig_dims; - ocp_qp_dims *red_dims; // dims of reduced qp - dense_qp_dims *fcond_dims; -} ocp_qp_full_condensing_dims; - - - -typedef struct ocp_qp_full_condensing_opts_ -{ - struct d_cond_qp_arg *hpipm_cond_opts; - struct d_ocp_qp_reduce_eq_dof_arg *hpipm_red_opts; -// dense_qp_dims *fcond_dims; // TODO(all): move to dims - int cond_hess; // 0 cond only rhs, 1 cond hess + rhs - int expand_dual_sol; // 0 primal sol only, 1 primal + dual sol - int ric_alg; - int mem_qp_in; // allocate qp_in in memory -} ocp_qp_full_condensing_opts; - - - -typedef struct ocp_qp_full_condensing_memory_ -{ - struct d_cond_qp_ws *hpipm_cond_work; - struct d_ocp_qp_reduce_eq_dof_ws *hpipm_red_work; - // in memory - dense_qp_in *fcond_qp_in; - dense_qp_out *fcond_qp_out; - ocp_qp_in *red_qp; // reduced qp - ocp_qp_out *red_sol; // reduced qp sol - // only pointer - ocp_qp_in *ptr_qp_in; - qp_info *qp_out_info; // info in fcond_qp_in - double time_qp_xcond; -} ocp_qp_full_condensing_memory; - - - -// -acados_size_t ocp_qp_full_condensing_opts_calculate_size(void *dims); -// -void *ocp_qp_full_condensing_opts_assign(void *dims, void *raw_memory); -// -void ocp_qp_full_condensing_opts_initialize_default(void *dims, void *opts_); -// -void ocp_qp_full_condensing_opts_update(void *dims, void *opts_); -// -void ocp_qp_full_condensing_opts_set(void *opts_, const char *field, void* value); -// -acados_size_t ocp_qp_full_condensing_memory_calculate_size(void *dims, void *opts_); -// -void *ocp_qp_full_condensing_memory_assign(void *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_full_condensing_workspace_calculate_size(void *dims, void *opts_); -// -int ocp_qp_full_condensing(void *in, void *out, void *opts, void *mem, void *work); -// -int ocp_qp_full_expansion(void *in, void *out, void *opts, void *mem, void *work); -// -void ocp_qp_full_condensing_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_FULL_CONDENSING_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h deleted file mode 100644 index 261606b8423a6a..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_HPIPM_H_ -#define ACADOS_OCP_QP_OCP_QP_HPIPM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_ocp_qp_ipm.h" -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - - - -// struct of arguments to the solver -// TODO(roversch): why not make this a typedef of the underlying struct? -typedef struct ocp_qp_hpipm_opts_ -{ - struct d_ocp_qp_ipm_arg *hpipm_opts; -} ocp_qp_hpipm_opts; - - - -// TODO(roversch): why not make this a typedef of the underlying struct? -// struct of the solver memory -typedef struct ocp_qp_hpipm_memory_ -{ - struct d_ocp_qp_ipm_ws *hpipm_workspace; - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_hpipm_memory; - - - -// -acados_size_t ocp_qp_hpipm_opts_calculate_size(void *config, void *dims); -// -void *ocp_qp_hpipm_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_qp_hpipm_opts_initialize_default(void *config, void *dims, void *opts_); -// -void ocp_qp_hpipm_opts_update(void *config, void *dims, void *opts_); -// -void ocp_qp_hpipm_opts_set(void *config_, void *opts_, const char *field, void *value); -// -acados_size_t ocp_qp_hpipm_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *ocp_qp_hpipm_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_hpipm_workspace_calculate_size(void *config, void *dims, void *opts_); -// -int ocp_qp_hpipm(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpipm_memory_reset(void *config_, void *qp_in_, void *qp_out_, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpipm_eval_sens(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpipm_config_initialize_default(void *config); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_HPIPM_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h deleted file mode 100644 index 8db53a279dbca6..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_HPMPC_H_ -#define ACADOS_OCP_QP_OCP_QP_HPMPC_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - -typedef enum hpmpc_options_t_ { HPMPC_DEFAULT_ARGUMENTS } hpmpc_options_t; - -typedef struct ocp_qp_hpmpc_opts_ -{ - double tol; - int max_iter; - double mu0; - double alpha_min; - int warm_start; - int N2; // horizion length of the partially condensed problem - - // partial tightening - double sigma_mu; - int N; - int M; -} ocp_qp_hpmpc_opts; - -// struct of the solver memory -typedef struct ocp_qp_hpmpc_memory_ -{ - struct blasfeo_dvec *hpi; - double *stats; - - // workspace - void *hpmpc_work; // raw workspace - - // partial tightening-specific (init of extra variables) - struct blasfeo_dvec *lam0; - struct blasfeo_dvec *ux0; - struct blasfeo_dvec *pi0; - struct blasfeo_dvec *t0; - - // 2. workspace - struct blasfeo_dmat *hsL; - struct blasfeo_dmat *hsric_work_mat; - struct blasfeo_dmat sLxM; - struct blasfeo_dmat sPpM; - - struct blasfeo_dvec *hsQx; - struct blasfeo_dvec *hsqx; - struct blasfeo_dvec *hstinv; - struct blasfeo_dvec *hsrq; - struct blasfeo_dvec *hsdux; - - struct blasfeo_dvec *hsdlam; - struct blasfeo_dvec *hsdt; - struct blasfeo_dvec *hsdpi; - struct blasfeo_dvec *hslamt; - - struct blasfeo_dvec *hsPb; - - void *work_ric; - - int out_iter; - - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_hpmpc_memory; - -acados_size_t ocp_qp_hpmpc_opts_calculate_size(void *config_, ocp_qp_dims *dims); -// -void *ocp_qp_hpmpc_opts_assign(void *config_, ocp_qp_dims *dims, void *raw_memory); -// -void ocp_qp_hpmpc_opts_initialize_default(void *config_, ocp_qp_dims *dims, void *opts_); -// -void ocp_qp_hpmpc_opts_update(void *config_, ocp_qp_dims *dims, void *opts_); -// -acados_size_t ocp_qp_hpmpc_memory_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -void *ocp_qp_hpmpc_memory_assign(void *config_, ocp_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_hpmpc_workspace_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -int ocp_qp_hpmpc(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpmpc_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpmpc_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_HPMPC_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h deleted file mode 100644 index a535503f215118..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_OOQP_H_ -#define ACADOS_OCP_QP_OCP_QP_OOQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - -enum ocp_qp_ooqp_termination_code -{ - SPARSE_SUCCESSFUL_TERMINATION = 0, - SPARSE_NOT_FINISHED, - SPARSE_MAX_ITS_EXCEEDED, - SPARSE_INFEASIBLE, - SPARSE_UNKNOWN -}; - -typedef struct ocp_qp_ooqp_opts_ -{ - int printLevel; - int useDiagonalWeights; // TODO(dimitris): implement option - int fixHessian; - int fixHessianSparsity; - int fixDynamics; - int fixDynamicsSparsity; - int fixInequalities; - int fixInequalitiesSparsity; -} ocp_qp_ooqp_opts; - -typedef struct ocp_qp_ooqp_workspace_ -{ - double *x; - double *gamma; - double *phi; - double *y; - double *z; - double *lambda; - double *pi; - double objectiveValue; - int *tmpInt; // temporary vector to sort indicies sparse matrices - double *tmpReal; // temporary vector to sort data of sparse matrices - // int ierr; -} ocp_qp_ooqp_workspace; - -typedef struct ocp_qp_ooqp_memory_ -{ - int firstRun; - double *c; - int nx; - int *irowQ; - int nnzQ; - int *jcolQ; - int *orderQ; - double *dQ; - double *xlow; - char *ixlow; - double *xupp; - char *ixupp; - int *irowA; - int nnzA; - int *jcolA; - int *orderA; - double *dA; - double *bA; - int my; - int *irowC; - int nnzC; - int *jcolC; - int *orderC; - double *dC; - double *clow; - int mz; - char *iclow; - double *cupp; - char *icupp; - int nnz; // max(nnzQ, nnzA, nnzC) - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_ooqp_memory; - -// -acados_size_t ocp_qp_ooqp_opts_calculate_size(void *config_, ocp_qp_dims *dims); -// -void *ocp_qp_ooqp_opts_assign(void *config_, ocp_qp_dims *dims, void *raw_memory); -// -void ocp_qp_ooqp_opts_initialize_default(void *config_, ocp_qp_dims *dims, void *opts_); -// -void ocp_qp_ooqp_opts_update(void *config_, ocp_qp_dims *dims, void *opts_); -// -acados_size_t ocp_qp_ooqp_memory_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -void *ocp_qp_ooqp_memory_assign(void *config_, ocp_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_ooqp_workspace_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -int ocp_qp_ooqp(void *config_, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts_, void *memory_, - void *work_); -// -void ocp_qp_ooqp_destroy(void *mem_, void *work); -// -void ocp_qp_ooqp_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_ooqp_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_OOQP_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h deleted file mode 100644 index 51df1b1cd68067..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_OSQP_H_ -#define ACADOS_OCP_QP_OCP_QP_OSQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// osqp -#include "osqp/include/types.h" - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - -typedef struct ocp_qp_osqp_opts_ -{ - OSQPSettings *osqp_opts; -} ocp_qp_osqp_opts; - - -typedef struct ocp_qp_osqp_memory_ -{ - c_int first_run; - - c_float *q; - c_float *l; - c_float *u; - - c_int P_nnzmax; - c_int *P_i; - c_int *P_p; - c_float *P_x; - - c_int A_nnzmax; - c_int *A_i; - c_int *A_p; - c_float *A_x; - - OSQPData *osqp_data; - OSQPWorkspace *osqp_work; - - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_osqp_memory; - -acados_size_t ocp_qp_osqp_opts_calculate_size(void *config, void *dims); -// -void *ocp_qp_osqp_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_qp_osqp_opts_initialize_default(void *config, void *dims, void *opts_); -// -void ocp_qp_osqp_opts_update(void *config, void *dims, void *opts_); -// -acados_size_t ocp_qp_osqp_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *ocp_qp_osqp_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_osqp_workspace_calculate_size(void *config, void *dims, void *opts_); -// -int ocp_qp_osqp(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_osqp_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_osqp_config_initialize_default(void *config); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_OSQP_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_partial_condensing.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_partial_condensing.h deleted file mode 100644 index 844f6048fe6220..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_partial_condensing.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_H_ -#define ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_ocp_qp_red.h" -// acados -#include "acados/ocp_qp/ocp_qp_common.h" - - - -typedef struct -{ - ocp_qp_dims *orig_dims; - ocp_qp_dims *red_dims; // dims of reduced qp - ocp_qp_dims *pcond_dims; - int *block_size; - int N2; - int N2_bkp; -} ocp_qp_partial_condensing_dims; - - - -typedef struct ocp_qp_partial_condensing_opts_ -{ - struct d_part_cond_qp_arg *hpipm_pcond_opts; - struct d_ocp_qp_reduce_eq_dof_arg *hpipm_red_opts; -// ocp_qp_dims *pcond_dims; // TODO(all): move to dims -// int *block_size; - int N2; - int N2_bkp; -// int expand_dual_sol; // 0 primal sol only, 1 primal + dual sol - int ric_alg; - int mem_qp_in; // allocate qp_in in memory -} ocp_qp_partial_condensing_opts; - - - -typedef struct ocp_qp_partial_condensing_memory_ -{ - struct d_part_cond_qp_ws *hpipm_pcond_work; - struct d_ocp_qp_reduce_eq_dof_ws *hpipm_red_work; - // in memory - ocp_qp_in *pcond_qp_in; - ocp_qp_out *pcond_qp_out; - ocp_qp_in *red_qp; // reduced qp - ocp_qp_out *red_sol; // reduced qp sol - // only pointer - ocp_qp_in *ptr_qp_in; - ocp_qp_in *ptr_pcond_qp_in; - qp_info *qp_out_info; // info in pcond_qp_in - double time_qp_xcond; -} ocp_qp_partial_condensing_memory; - - - -// -acados_size_t ocp_qp_partial_condensing_opts_calculate_size(void *dims); -// -void *ocp_qp_partial_condensing_opts_assign(void *dims, void *raw_memory); -// -void ocp_qp_partial_condensing_opts_initialize_default(void *dims, void *opts_); -// -void ocp_qp_partial_condensing_opts_update(void *dims, void *opts_); -// -void ocp_qp_partial_condensing_opts_set(void *opts_, const char *field, void* value); -// -acados_size_t ocp_qp_partial_condensing_memory_calculate_size(void *dims, void *opts_); -// -void *ocp_qp_partial_condensing_memory_assign(void *dims, void *opts, void *raw_memory); -// -acados_size_t ocp_qp_partial_condensing_workspace_calculate_size(void *dims, void *opts_); -// -int ocp_qp_partial_condensing(void *in, void *out, void *opts, void *mem, void *work); -// -int ocp_qp_partial_expansion(void *in, void *out, void *opts, void *mem, void *work); -// -void ocp_qp_partial_condensing_config_initialize_default(void *config_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h deleted file mode 100644 index 3b875caeb50419..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_QPDUNES_H_ -#define ACADOS_OCP_QP_OCP_QP_QPDUNES_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "qpDUNES.h" - -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - -typedef enum qpdunes_options_t_ { - QPDUNES_DEFAULT_ARGUMENTS, - QPDUNES_LINEAR_MPC, // TODO(dimitris): partly implemented - QPDUNES_NONLINEAR_MPC, // TODO(dimitris): not implemented yet - QPDUNES_ACADO_SETTINGS -} qpdunes_options_t; - -typedef enum { QPDUNES_WITH_QPOASES, QPDUNES_WITH_CLIPPING } qpdunes_stage_qp_solver_t; - -typedef struct ocp_qp_qpdunes_opts_ -{ - qpOptions_t options; - qpdunes_stage_qp_solver_t stageQpSolver; - int warmstart; // warmstart = 0: all multipliers set to zero, warmstart = 1: use previous mult. - bool isLinearMPC; -} ocp_qp_qpdunes_opts; - -typedef struct ocp_qp_qpdunes_memory_ -{ - int firstRun; - int nx; - int nu; - int nz; - int nDmax; // max(dims->ng) - qpData_t qpData; - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_qpdunes_memory; - -typedef struct ocp_qp_qpdunes_workspace_ -{ - double *H; - double *Q; - double *R; - double *S; - double *g; - double *ABt; - double *b; - double *Ct; - double *lc; - double *uc; - double *zLow; - double *zUpp; -} ocp_qp_qpdunes_workspace; - -// -acados_size_t ocp_qp_qpdunes_opts_calculate_size(void *config_, ocp_qp_dims *dims); -// -void *ocp_qp_qpdunes_opts_assign(void *config_, ocp_qp_dims *dims, void *raw_memory); -// -void ocp_qp_qpdunes_opts_initialize_default(void *config_, ocp_qp_dims *dims, void *opts_); -// -void ocp_qp_qpdunes_opts_update(void *config_, ocp_qp_dims *dims, void *opts_); -// -acados_size_t ocp_qp_qpdunes_memory_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -void *ocp_qp_qpdunes_memory_assign(void *config_, ocp_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_qpdunes_workspace_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -int ocp_qp_qpdunes(void *config_, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts_, void *memory_, - void *work_); -// -void ocp_qp_qpdunes_free_memory(void *mem_); -// -void ocp_qp_qpdunes_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_qpdunes_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_QPDUNES_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h deleted file mode 100644 index a78bc65bb9c621..00000000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_SOLVER_H_ -#define ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_SOLVER_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - - - -typedef struct -{ - ocp_qp_dims *orig_dims; - void *xcond_dims; -} ocp_qp_xcond_solver_dims; - - - -typedef struct ocp_qp_xcond_solver_opts_ -{ - void *xcond_opts; - void *qp_solver_opts; -} ocp_qp_xcond_solver_opts; - - - -typedef struct ocp_qp_xcond_solver_memory_ -{ - void *xcond_memory; - void *solver_memory; - void *xcond_qp_in; - void *xcond_qp_out; -} ocp_qp_xcond_solver_memory; - - - -typedef struct ocp_qp_xcond_solver_workspace_ -{ - void *xcond_work; - void *qp_solver_work; -} ocp_qp_xcond_solver_workspace; - - - -typedef struct -{ - acados_size_t (*dims_calculate_size)(void *config, int N); - ocp_qp_xcond_solver_dims *(*dims_assign)(void *config, int N, void *raw_memory); - void (*dims_set)(void *config_, ocp_qp_xcond_solver_dims *dims, int stage, const char *field, int* value); - void (*dims_get)(void *config_, ocp_qp_xcond_solver_dims *dims, int stage, const char *field, int* value); - acados_size_t (*opts_calculate_size)(void *config, ocp_qp_xcond_solver_dims *dims); - void *(*opts_assign)(void *config, ocp_qp_xcond_solver_dims *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); - void (*opts_update)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); - void (*opts_set)(void *config_, void *opts_, const char *field, void* value); - acados_size_t (*memory_calculate_size)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); - void *(*memory_assign)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts, void *raw_memory); - void (*memory_get)(void *config_, void *mem_, const char *field, void* value); - void (*memory_reset)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts, void *mem, void *work); - acados_size_t (*workspace_calculate_size)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); - int (*evaluate)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts, void *mem, void *work); - void (*eval_sens)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *param_qp_in, ocp_qp_out *sens_qp_out, void *opts, void *mem, void *work); - qp_solver_config *qp_solver; // either ocp_qp_solver or dense_solver - ocp_qp_xcond_config *xcond; -} ocp_qp_xcond_solver_config; // pcond - partial condensing or fcond - full condensing - - - -/* config */ -// -acados_size_t ocp_qp_xcond_solver_config_calculate_size(); -// -ocp_qp_xcond_solver_config *ocp_qp_xcond_solver_config_assign(void *raw_memory); - -/* dims */ -// -acados_size_t ocp_qp_xcond_solver_dims_calculate_size(void *config, int N); -// -ocp_qp_xcond_solver_dims *ocp_qp_xcond_solver_dims_assign(void *config, int N, void *raw_memory); -// -void ocp_qp_xcond_solver_dims_set_(void *config, ocp_qp_xcond_solver_dims *dims, int stage, const char *field, int* value); - -/* opts */ -// -acados_size_t ocp_qp_xcond_solver_opts_calculate_size(void *config, ocp_qp_xcond_solver_dims *dims); -// -void *ocp_qp_xcond_solver_opts_assign(void *config, ocp_qp_xcond_solver_dims *dims, void *raw_memory); -// -void ocp_qp_xcond_solver_opts_initialize_default(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_); -// -void ocp_qp_xcond_solver_opts_update(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_); -// -void ocp_qp_xcond_solver_opts_set_(void *config_, void *opts_, const char *field, void* value); - -/* memory */ -// -acados_size_t ocp_qp_xcond_solver_memory_calculate_size(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_); -// -void *ocp_qp_xcond_solver_memory_assign(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_, void *raw_memory); - -/* workspace */ -// -acados_size_t ocp_qp_xcond_solver_workspace_calculate_size(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_); - -/* config */ -// -int ocp_qp_xcond_solver(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts_, void *mem_, void *work_); - -// -void ocp_qp_xcond_solver_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_SOLVER_H_ diff --git a/third_party/acados/include/acados/sim/sim_collocation_utils.h b/third_party/acados/include/acados/sim/sim_collocation_utils.h deleted file mode 100644 index 045d165cbccee2..00000000000000 --- a/third_party/acados/include/acados/sim/sim_collocation_utils.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_SIM_SIM_COLLOCATION_UTILS_H_ -#define ACADOS_SIM_SIM_COLLOCATION_UTILS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/utils/types.h" - - - -// enum Newton_type_collocation -// { -// exact = 0, -// simplified_in, -// simplified_inis -// }; - - - -// typedef struct -// { -// enum Newton_type_collocation type; -// double *eig; -// double *low_tria; -// bool single; -// bool freeze; - -// double *transf1; -// double *transf2; - -// double *transf1_T; -// double *transf2_T; -// } Newton_scheme; - - -typedef enum -{ - GAUSS_LEGENDRE, - GAUSS_RADAU_IIA, -} sim_collocation_type; - - -// -// acados_size_t gauss_legendre_nodes_work_calculate_size(int ns); -// -// void gauss_legendre_nodes(int ns, double *nodes, void *raw_memory); -// -// acados_size_t gauss_simplified_work_calculate_size(int ns); -// // -// void gauss_simplified(int ns, Newton_scheme *scheme, void *work); -// -acados_size_t butcher_tableau_work_calculate_size(int ns); -// -// void calculate_butcher_tableau_from_nodes(int ns, double *nodes, double *b, double *A, void *work); -// -void calculate_butcher_tableau(int ns, sim_collocation_type collocation_type, double *c_vec, - double *b_vec, double *A_mat, void *work); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_COLLOCATION_UTILS_H_ diff --git a/third_party/acados/include/acados/sim/sim_common.h b/third_party/acados/include/acados/sim/sim_common.h deleted file mode 100644 index c4bbd6ed2b8de1..00000000000000 --- a/third_party/acados/include/acados/sim/sim_common.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_SIM_SIM_COMMON_H_ -#define ACADOS_SIM_SIM_COMMON_H_ - -#include - -#include "acados/sim/sim_collocation_utils.h" -#include "acados/utils/timing.h" -#include "acados/utils/types.h" - -#include "acados/utils/external_function_generic.h" - -// maximum number of integration stages -#define NS_MAX 15 - - - -typedef enum -{ - // ERK and LIFTED_ERK - EXPL_ODE_FUN, - EXPL_ODE_HES, // wrt x and u ??? - EXPL_VDE_FOR, - EXPL_VDE_ADJ, - // IRK - IMPL_ODE_FUN, - IMPL_ODE_FUN_JAC_X_XDOT, - IMPL_ODE_JAC_X_XDOT_U, - IMPL_ODE_FUN_JAC_X_XDOT_U, - IMPL_ODE_HESS, - // gnsf - PHI_FUN, - PHI_FUN_JAC_Y, - PHI_JAC_Y_UHAT, - LO_FUN, - GET_GNSF_MATRICES -} sim_function_t; - - - -typedef struct -{ - void *dims; - - double *x; // x[NX] - initial state value for simulation - double *u; // u[NU] - control - constant over simulation time - - double *S_forw; // forward seed [Sx, Su] - double *S_adj; // backward seed - - bool identity_seed; // indicating if S_forw = [eye(nx), zeros(nx x nu)] - - void *model; - - double T; // simulation time - -} sim_in; - - - -typedef struct -{ - double CPUtime; // in seconds - double LAtime; // in seconds - double ADtime; // in seconds - -} sim_info; - - - -typedef struct -{ - double *xn; // xn[NX] - double *S_forw; // S_forw[NX*(NX+NU)] - double *S_adj; // - double *S_hess; // - - double *zn; // z - algebraic variables - reported at start of simulation interval - double *S_algebraic; // sensitivities of reported value of algebraic variables w.r.t. - // initial stat & control (x_n,u) - - double *grad; // gradient correction - - sim_info *info; - -} sim_out; - - - -typedef struct -{ - int ns; // number of integration stages - - int num_steps; - int num_forw_sens; - - int tableau_size; // check that is consistent with ns - // only update when butcher tableau is changed - // kind of private -> no setter! - double *A_mat; - double *c_vec; - double *b_vec; - - bool sens_forw; - bool sens_adj; - bool sens_hess; - - bool output_z; // 1 -- if zn should be computed - bool sens_algebraic; // 1 -- if S_algebraic should be computed - bool exact_z_output; // 1 -- if z, S_algebraic should be computed exactly, extra Newton iterations - sim_collocation_type collocation_type; - - // for explicit integrators: newton_iter == 0 && scheme == NULL - // && jac_reuse=false - int newton_iter; - bool jac_reuse; - // Newton_scheme *scheme; - - double newton_tol; // optinally used in implicit integrators - - // workspace - void *work; - -} sim_opts; - - - -typedef struct -{ - int (*evaluate)(void *config_, sim_in *in, sim_out *out, void *opts, void *mem, void *work); - int (*precompute)(void *config_, sim_in *in, sim_out *out, void *opts, void *mem, void *work); - // opts - acados_size_t (*opts_calculate_size)(void *config_, void *dims); - void *(*opts_assign)(void *config_, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config_, void *dims, void *opts); - void (*opts_update)(void *config_, void *dims, void *opts); - void (*opts_set)(void *config_, void *opts_, const char *field, void *value); - void (*opts_get)(void *config_, void *opts_, const char *field, void *value); - // mem - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - int (*memory_set)(void *config, void *dims, void *mem, const char *field, void *value); - int (*memory_set_to_zero)(void *config, void *dims, void *opts, void *mem, const char *field); - void (*memory_get)(void *config, void *dims, void *mem, const char *field, void *value); - // work - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - // model - acados_size_t (*model_calculate_size)(void *config, void *dims); - void *(*model_assign)(void *config, void *dims, void *raw_memory); - int (*model_set)(void *model, const char *field, void *value); - // config - void (*config_initialize_default)(void *config); - // dims - acados_size_t (*dims_calculate_size)(); - void *(*dims_assign)(void *config, void *raw_memory); - void (*dims_set)(void *config, void *dims, const char *field, const int *value); - void (*dims_get)(void *config, void *dims, const char *field, int *value); - -} sim_config; - - - -/* config */ -// -acados_size_t sim_config_calculate_size(); -// -sim_config *sim_config_assign(void *raw_memory); - -/* in */ -// -acados_size_t sim_in_calculate_size(void *config, void *dims); -// -sim_in *sim_in_assign(void *config, void *dims, void *raw_memory); -// -int sim_in_set_(void *config_, void *dims_, sim_in *in, const char *field, void *value); - -/* out */ -// -acados_size_t sim_out_calculate_size(void *config, void *dims); -// -sim_out *sim_out_assign(void *config, void *dims, void *raw_memory); -// -int sim_out_get_(void *config, void *dims, sim_out *out, const char *field, void *value); - -/* opts */ -// -void sim_opts_set_(sim_opts *opts, const char *field, void *value); -// -void sim_opts_get_(sim_config *config, sim_opts *opts, const char *field, void *value); - -#endif // ACADOS_SIM_SIM_COMMON_H_ diff --git a/third_party/acados/include/acados/sim/sim_erk_integrator.h b/third_party/acados/include/acados/sim/sim_erk_integrator.h deleted file mode 100644 index fd46cb4d99c035..00000000000000 --- a/third_party/acados/include/acados/sim/sim_erk_integrator.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_SIM_SIM_ERK_INTEGRATOR_H_ -#define ACADOS_SIM_SIM_ERK_INTEGRATOR_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/sim/sim_common.h" -#include "acados/utils/types.h" - - - -typedef struct -{ - int nx; - int nu; - int nz; -} sim_erk_dims; - - - -typedef struct -{ - /* external functions */ - // explicit ode - external_function_generic *expl_ode_fun; - // hessian explicit ode - external_function_generic *expl_ode_hes; - // forward explicit vde - external_function_generic *expl_vde_for; - // adjoint explicit vde - external_function_generic *expl_vde_adj; - -} erk_model; - - - -typedef struct -{ - // memory - double time_sim; - double time_ad; - double time_la; - - // workspace structs -} sim_erk_memory; - - - -typedef struct -{ - // workspace mem - double *rhs_forw_in; // x + S + p - - double *K_traj; // (stages*nX) or (steps*stages*nX) for adj - double *out_forw_traj; // S or (steps+1)*nX for adj - - double *rhs_adj_in; - double *out_adj_tmp; - double *adj_traj; - -} sim_erk_workspace; - - - -// dims -acados_size_t sim_erk_dims_calculate_size(); -void *sim_erk_dims_assign(void *config_, void *raw_memory); -void sim_erk_dims_set(void *config_, void *dims_, const char *field, const int* value); -void sim_erk_dims_get(void *config_, void *dims_, const char *field, int* value); - -// model -acados_size_t sim_erk_model_calculate_size(void *config, void *dims); -void *sim_erk_model_assign(void *config, void *dims, void *raw_memory); -int sim_erk_model_set(void *model, const char *field, void *value); - -// opts -acados_size_t sim_erk_opts_calculate_size(void *config, void *dims); -// -void sim_erk_opts_update(void *config_, void *dims, void *opts_); -// -void *sim_erk_opts_assign(void *config, void *dims, void *raw_memory); -// -void sim_erk_opts_initialize_default(void *config, void *dims, void *opts_); -// -void sim_erk_opts_set(void *config_, void *opts_, const char *field, void *value); - - -// memory -acados_size_t sim_erk_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *sim_erk_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -// -int sim_erk_memory_set(void *config_, void *dims_, void *mem_, const char *field, void *value); - - -// workspace -acados_size_t sim_erk_workspace_calculate_size(void *config, void *dims, void *opts_); - -// -int sim_erk(void *config, sim_in *in, sim_out *out, void *opts_, void *mem_, void *work_); -// -void sim_erk_config_initialize_default(void *config); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_ERK_INTEGRATOR_H_ diff --git a/third_party/acados/include/acados/sim/sim_gnsf.h b/third_party/acados/include/acados/sim/sim_gnsf.h deleted file mode 100644 index 404532a7327622..00000000000000 --- a/third_party/acados/include/acados/sim/sim_gnsf.h +++ /dev/null @@ -1,364 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_SIM_SIM_GNSF_H_ -#define ACADOS_SIM_SIM_GNSF_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include "acados/utils/timing.h" -#include "acados/utils/types.h" -#include "acados/sim/sim_common.h" - -#include "blasfeo/include/blasfeo_common.h" -// #include "blasfeo/include/blasfeo_d_aux.h" -// #include "blasfeo/include/blasfeo_d_aux_ext_dep.h" -// #include "blasfeo/include/blasfeo_d_blas.h" -// #include "blasfeo/include/blasfeo_d_kernel.h" -// #include "blasfeo/include/blasfeo_i_aux_ext_dep.h" -// #include "blasfeo/include/blasfeo_target.h" - -/* -GNSF - Generalized Nonlinear Static Feedback Model -has the following form -https://github.com/acados/acados/files/3359595/gnsf_structure_blo.pdf - -Details on the algorithm can be found in master thesis of Jonathan Frey, -which presents a slightly different format without the terms B_LO, c_LO. -https://github.com/acados/acados/files/2318322/gnsf_structure.pdf -https://cdn.syscop.de/publications/Frey2018.pdf -https://cdn.syscop.de/publications/Frey2019.pdf -*/ - -typedef struct -{ - int nx; // total number of differential states - int nu; // total number of inputs - int nz; // total number of algebraic states - int nx1; // number of differential states in NSF part - int nz1; // number of algebraic states in NSF part - int n_out; // output dimension of phi - int ny; // dimension of first input of phi - int nuhat; // dimension of second input of phi - -} sim_gnsf_dims; - - - -typedef struct -{ - /* external functions */ - // phi: nonlinearity function - external_function_generic *phi_fun; - external_function_generic *phi_fun_jac_y; - external_function_generic *phi_jac_y_uhat; - - // f_lo: linear output function - external_function_generic *f_lo_fun_jac_x1_x1dot_u_z; - - // to import model matrices - external_function_generic *get_gnsf_matrices; - - // flag indicating, if model defining matrices are imported via external (casadi) function, - // [default]: true -> auto; - bool auto_import_gnsf; - - // booleans from structure detection - bool nontrivial_f_LO; // indicates if f_LO is constant zero function - bool fully_linear; // indicates if model is fully linear LOS - - /* model defining matrices */ - // TODO: add setters to set manually - double *A; - double *B; - double *C; - double *E; - - double *L_x; - double *L_xdot; - double *L_z; - double *L_u; - - double *A_LO; - double *B_LO; - double *E_LO; - - /* constant vector */ - double *c; - double *c_LO; - - // permutation vector - to have GNSF order of x, z within sim_gnsf only - int *ipiv_x; - int *ipiv_z; - - double *ipiv_x_double; - double *ipiv_z_double; - -} gnsf_model; - - - -// pre_workspace - workspace used in the precomputation phase -typedef struct -{ - struct blasfeo_dmat E11; - struct blasfeo_dmat E12; - struct blasfeo_dmat E21; - struct blasfeo_dmat E22; - - struct blasfeo_dmat A1; - struct blasfeo_dmat A2; - struct blasfeo_dmat B1; - struct blasfeo_dmat B2; - struct blasfeo_dmat C1; - struct blasfeo_dmat C2; - - struct blasfeo_dmat AA1; - struct blasfeo_dmat AA2; - struct blasfeo_dmat BB1; - struct blasfeo_dmat BB2; - struct blasfeo_dmat CC1; - struct blasfeo_dmat CC2; - struct blasfeo_dmat DD1; - struct blasfeo_dmat DD2; - struct blasfeo_dmat EE1; - struct blasfeo_dmat EE2; - - struct blasfeo_dmat QQ1; - - struct blasfeo_dmat LLZ; - struct blasfeo_dmat LLx; - struct blasfeo_dmat LLK; - - int *ipivEE1; // index of pivot vector - int *ipivEE2; - int *ipivQQ1; - - // for algebraic sensitivity propagation - struct blasfeo_dmat Q1; - - // for constant term in NSF - struct blasfeo_dvec cc1; - struct blasfeo_dvec cc2; - -} gnsf_pre_workspace; - - - -// workspace -typedef struct -{ - double *Z_work; // used to perform computations to get out->zn - - int *ipiv; // index of pivot vector - - struct blasfeo_dvec *vv_traj; - struct blasfeo_dvec *yy_traj; - struct blasfeo_dmat *f_LO_jac_traj; - - struct blasfeo_dvec K2_val; - struct blasfeo_dvec x0_traj; - struct blasfeo_dvec res_val; - struct blasfeo_dvec u0; - struct blasfeo_dvec lambda; - struct blasfeo_dvec lambda_old; - - struct blasfeo_dvec yyu; - struct blasfeo_dvec yyss; - - struct blasfeo_dvec K1_val; - struct blasfeo_dvec f_LO_val; - struct blasfeo_dvec x1_stage_val; - struct blasfeo_dvec Z1_val; - - struct blasfeo_dvec K1u; - struct blasfeo_dvec Zu; - struct blasfeo_dvec ALOtimesx02; - struct blasfeo_dvec BLOtimesu0; - - struct blasfeo_dvec uhat; - - struct blasfeo_dmat J_r_vv; - struct blasfeo_dmat J_r_x1u; - - struct blasfeo_dmat dK1_dx1; - struct blasfeo_dmat dK1_du; - struct blasfeo_dmat dZ_dx1; - struct blasfeo_dmat dZ_du; - struct blasfeo_dmat J_G2_K1; - - struct blasfeo_dmat dK2_dx1; - struct blasfeo_dmat dK2_dvv; - struct blasfeo_dmat dxf_dwn; - struct blasfeo_dmat S_forw_new; - struct blasfeo_dmat S_algebraic_aux; - - struct blasfeo_dmat dPsi_dvv; - struct blasfeo_dmat dPsi_dx; - struct blasfeo_dmat dPsi_du; - - struct blasfeo_dmat dPHI_dyuhat; - struct blasfeo_dvec z0; - - // memory only available if (opts->sens_algebraic) - // struct blasfeo_dvec y_one_stage; - // struct blasfeo_dvec x0dot_1; - // struct blasfeo_dmat dz10_dx1u; // (nz1) * (nx1+nu); - // struct blasfeo_dmat dr0_dvv0; // (n_out * n_out) - // struct blasfeo_dmat f_LO_jac0; // (nx2+nz2) * (2*nx1 + nz1 + nu) - // struct blasfeo_dmat sens_z2_rhs; // (nx2 + nz2) * (nx1 + nu) - // int *ipiv_vv0; - -} gnsf_workspace; - - - -// memory -typedef struct -{ - bool first_call; - - // simulation time for one step - double dt; - - // (scaled) butcher table - double *A_dt; - double *b_dt; - double *c_butcher; - - // value used to initialize integration variables - corresponding to value of phi - double *phi_guess; // n_out - - struct blasfeo_dmat S_forw; - struct blasfeo_dmat S_algebraic; - - // precomputed matrices - struct blasfeo_dmat KKv; - struct blasfeo_dmat KKx; - struct blasfeo_dmat KKu; - - struct blasfeo_dmat YYv; - struct blasfeo_dmat YYx; - struct blasfeo_dmat YYu; - - struct blasfeo_dmat ZZv; - struct blasfeo_dmat ZZx; - struct blasfeo_dmat ZZu; - - struct blasfeo_dmat ALO; - struct blasfeo_dmat BLO; - struct blasfeo_dmat M2_LU; - int *ipivM2; - - struct blasfeo_dmat dK2_dx2; - struct blasfeo_dmat dK2_du; - struct blasfeo_dmat dx2f_dx2u; - - struct blasfeo_dmat Lu; - - // precomputed vectors for constant term in NSF - struct blasfeo_dvec KK0; - struct blasfeo_dvec YY0; - struct blasfeo_dvec ZZ0; - - // for algebraic sensitivities only; - // struct blasfeo_dmat *Z0x; - // struct blasfeo_dmat *Z0u; - // struct blasfeo_dmat *Z0v; - - // struct blasfeo_dmat *Y0x; - // struct blasfeo_dmat *Y0u; - // struct blasfeo_dmat *Y0v; - - // struct blasfeo_dmat *K0x; - // struct blasfeo_dmat *K0u; - // struct blasfeo_dmat *K0v; - - // struct blasfeo_dmat *ELO_LU; - // int *ipiv_ELO; - // struct blasfeo_dmat *ELO_inv_ALO; - - // struct blasfeo_dmat *Lx; - // struct blasfeo_dmat *Lxdot; - // struct blasfeo_dmat *Lz; - - double time_sim; - double time_ad; - double time_la; - -} sim_gnsf_memory; - - - -// gnsf dims -acados_size_t sim_gnsf_dims_calculate_size(); -void *sim_gnsf_dims_assign(void *config_, void *raw_memory); - -// get & set functions -void sim_gnsf_dims_set(void *config_, void *dims_, const char *field, const int *value); -void sim_gnsf_dims_get(void *config_, void *dims_, const char *field, int* value); - -// opts -acados_size_t sim_gnsf_opts_calculate_size(void *config, void *dims); -void *sim_gnsf_opts_assign(void *config, void *dims, void *raw_memory); -void sim_gnsf_opts_initialize_default(void *config, void *dims, void *opts_); -void sim_gnsf_opts_update(void *config_, void *dims, void *opts_); -void sim_gnsf_opts_set(void *config_, void *opts_, const char *field, void *value); - -// model -acados_size_t sim_gnsf_model_calculate_size(void *config, void *dims_); -void *sim_gnsf_model_assign(void *config, void *dims_, void *raw_memory); -int sim_gnsf_model_set(void *model_, const char *field, void *value); - -// precomputation -int sim_gnsf_precompute(void *config_, sim_in *in, sim_out *out, void *opts_, void *mem_, - void *work_); - -// workspace & memory -acados_size_t sim_gnsf_workspace_calculate_size(void *config, void *dims_, void *args); -acados_size_t sim_gnsf_memory_calculate_size(void *config, void *dims_, void *opts_); -void *sim_gnsf_memory_assign(void *config, void *dims_, void *opts_, void *raw_memory); - -// interface -void sim_gnsf_config_initialize_default(void *config_); - -// integrator -int sim_gnsf(void *config, sim_in *in, sim_out *out, void *opts, void *mem_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_GNSF_H_ diff --git a/third_party/acados/include/acados/sim/sim_irk_integrator.h b/third_party/acados/include/acados/sim/sim_irk_integrator.h deleted file mode 100644 index 5090aa0bb52604..00000000000000 --- a/third_party/acados/include/acados/sim/sim_irk_integrator.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_SIM_SIM_IRK_INTEGRATOR_H_ -#define ACADOS_SIM_SIM_IRK_INTEGRATOR_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/sim/sim_common.h" -#include "acados/utils/types.h" - -#include "blasfeo/include/blasfeo_common.h" - -typedef struct -{ - int nx; - int nu; - int nz; - -} sim_irk_dims; - - - -typedef struct -{ - /* external functions */ - // implicit fun - can either be fully implicit ode or dae - // - i.e. dae has z as additional last argument & nz > 0 - external_function_generic *impl_ode_fun; - // implicit ode & jac_x & jax_xdot & jac_z - external_function_generic *impl_ode_fun_jac_x_xdot_z; - // jax_x & jac_xdot & jac_u & jac_z of implicit ode - external_function_generic *impl_ode_jac_x_xdot_u_z; - // hessian of implicit ode: - external_function_generic *impl_ode_hess; -} irk_model; - - - -typedef struct -{ - struct blasfeo_dvec *rG; // residuals of G (nx*ns) - struct blasfeo_dvec *K; // internal K variables ((nx+nz)*ns) - struct blasfeo_dvec *xt; // temporary x - struct blasfeo_dvec *xn; // x at each integration step - struct blasfeo_dvec xtdot; // temporary xdot - - struct blasfeo_dvec *lambda; // adjoint sensitivities (nx + nu) - struct blasfeo_dvec *lambdaK; // auxiliary variable ((nx+nz)*ns) for adjoint propagation - - struct blasfeo_dmat df_dx; // temporary Jacobian of ode w.r.t x (nx+nz, nx) - struct blasfeo_dmat df_dxdot; // temporary Jacobian of ode w.r.t xdot (nx+nz, nx) - struct blasfeo_dmat df_du; // temporary Jacobian of ode w.r.t u (nx+nz, nu) - struct blasfeo_dmat df_dz; // temporary Jacobian of ode w.r.t z (nx+nz, nu) - - /* NOTE: the memory allocation corresponding to the following fields is CONDITIONAL */ - - // only allocated if (opts->sens_algebraic || opts->output_z) - int *ipiv_one_stage; // index of pivot vector (nx + nz) - double *Z_work; // used to perform computations to get out->zn (ns) - - // df_dxdotz, dk0_dxu, only allocated if (opts->sens_algebraic && opts->exact_z_output) - // used for algebraic sensitivity generation - struct blasfeo_dmat df_dxdotz; // temporary Jacobian of ode w.r.t. xdot,z (nx+nz, nx+nz); - struct blasfeo_dmat dk0_dxu; // intermediate result, (nx+nz, nx+nu) - - // dK_dxu: if (!opts->sens_hess) - single blasfeo_dmat that is reused - // if ( opts->sens_hess) - array of (num_steps) blasfeo_dmat - // to store intermediate results - struct blasfeo_dmat *dK_dxu; // jacobian of (K,Z) over x and u ((nx+nz)*ns, nx+nu); - - // S_forw: if (!opts->sens_hess) - single blasfeo_dmat that is reused - // if ( opts->sens_hess) - array of (num_steps + 1) blasfeo_dmat - // to store intermediate results - struct blasfeo_dmat *S_forw; // forward sensitivities (nx, nx+nu) - - // dG_dxu: if (!opts->sens_hess) - single blasfeo_dmat that is reused - // if ( opts->sens_hess) - array of blasfeo_dmat to store intermediate results - struct blasfeo_dmat *dG_dxu; // jacobian of G over x and u ((nx+nz)*ns, nx+nu) - - // dG_dK: if (!opts->sens_hess) - single blasfeo_dmat that is reused - // if ( opts->sens_hess) - array of blasfeo_dmat to store intermediate results - struct blasfeo_dmat *dG_dK; // jacobian of G over K ((nx+nz)*ns, (nx+nz)*ns) - - // ipiv: index of pivot vector - // if (!opts->sens_hess) - array (ns * (nx + nz)) that is reused - // if ( opts->sens_hess) - array (ns * (nx + nz)) * num_steps, to store all - // pivot vectors for dG_dxu - int *ipiv; // index of pivot vector - - // xn_traj, K_traj only available if( opts->sens_adj || opts->sens_hess ) - struct blasfeo_dvec *xn_traj; // xn trajectory - struct blasfeo_dvec *K_traj; // K trajectory - - /* the following variables are only available if (opts->sens_hess) */ - // For Hessian propagation - struct blasfeo_dmat Hess; // temporary Hessian (nx + nu, nx + nu) - // output of impl_ode_hess - struct blasfeo_dmat f_hess; // size: (nx + nu, nx + nu) - struct blasfeo_dmat dxkzu_dw0; // size (2*nx + nu + nz) x (nx + nu) - struct blasfeo_dmat tmp_dxkzu_dw0; // size (2*nx + nu + nz) x (nx + nu) - -} sim_irk_workspace; - - -typedef struct -{ - double *xdot; // xdot[NX] - initialization for state derivatives k within the integrator - double *z; // z[NZ] - initialization for algebraic variables z - - double time_sim; - double time_ad; - double time_la; -} sim_irk_memory; - - -// get & set functions -void sim_irk_dims_set(void *config_, void *dims_, const char *field, const int *value); -void sim_irk_dims_get(void *config_, void *dims_, const char *field, int* value); - -// dims -acados_size_t sim_irk_dims_calculate_size(); -void *sim_irk_dims_assign(void *config_, void *raw_memory); - -// model -acados_size_t sim_irk_model_calculate_size(void *config, void *dims); -void *sim_irk_model_assign(void *config, void *dims, void *raw_memory); -int sim_irk_model_set(void *model, const char *field, void *value); - -// opts -acados_size_t sim_irk_opts_calculate_size(void *config, void *dims); -void *sim_irk_opts_assign(void *config, void *dims, void *raw_memory); -void sim_irk_opts_initialize_default(void *config, void *dims, void *opts_); -void sim_irk_opts_update(void *config_, void *dims, void *opts_); -void sim_irk_opts_set(void *config_, void *opts_, const char *field, void *value); - -// memory -acados_size_t sim_irk_memory_calculate_size(void *config, void *dims, void *opts_); -void *sim_irk_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -int sim_irk_memory_set(void *config_, void *dims_, void *mem_, const char *field, void *value); - -// workspace -acados_size_t sim_irk_workspace_calculate_size(void *config, void *dims, void *opts_); -void sim_irk_config_initialize_default(void *config); - -// main -int sim_irk(void *config, sim_in *in, sim_out *out, void *opts_, void *mem_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_IRK_INTEGRATOR_H_ diff --git a/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h b/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h deleted file mode 100644 index e60bb80ebf8b2f..00000000000000 --- a/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_SIM_SIM_LIFTED_IRK_INTEGRATOR_H_ -#define ACADOS_SIM_SIM_LIFTED_IRK_INTEGRATOR_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/sim/sim_common.h" -#include "acados/utils/types.h" - -typedef struct -{ - int nx; - int nu; - int nz; -} sim_lifted_irk_dims; - - - -typedef struct -{ - /* external functions */ - // implicit ode - external_function_generic *impl_ode_fun; - // implicit ode & jax_x & jac_xdot & jac_u implicit ode - external_function_generic *impl_ode_fun_jac_x_xdot_u; - -} lifted_irk_model; - - - -typedef struct -{ - - struct blasfeo_dmat *J_temp_x; // temporary Jacobian of ode w.r.t x (nx, nx) - struct blasfeo_dmat *J_temp_xdot; // temporary Jacobian of ode w.r.t xdot (nx, nx) - struct blasfeo_dmat *J_temp_u; // temporary Jacobian of ode w.r.t u (nx, nu) - - struct blasfeo_dvec *rG; // residuals of G (nx*ns) - struct blasfeo_dvec *xt; // temporary x - struct blasfeo_dvec *xn; // x at each integration step (for evaluations) - struct blasfeo_dvec *xn_out; // x at each integration step (output) - struct blasfeo_dvec *dxn; // dx at each integration step - struct blasfeo_dvec *w; // stacked x and u - - int *ipiv; // index of pivot vector - -} sim_lifted_irk_workspace; - - - -typedef struct -{ - // memory for lifted integrators - struct blasfeo_dmat *S_forw; // forward sensitivities - struct blasfeo_dmat *JGK; // jacobian of G over K (nx*ns, nx*ns) - struct blasfeo_dmat *JGf; // jacobian of G over x and u (nx*ns, nx+nu); - struct blasfeo_dmat *JKf; // jacobian of K over x and u (nx*ns, nx+nu); - - struct blasfeo_dvec *K; // internal variables (nx*ns) - struct blasfeo_dvec *x; // states (nx) -- for expansion step - struct blasfeo_dvec *u; // controls (nu) -- for expansion step - - int update_sens; - // int init_K; - - double time_sim; - double time_ad; - double time_la; - -} sim_lifted_irk_memory; - - - -/* dims */ -void sim_lifted_irk_dims_set(void *config_, void *dims_, const char *field, const int *value); -void sim_lifted_irk_dims_get(void *config_, void *dims_, const char *field, int* value); - -acados_size_t sim_lifted_irk_dims_calculate_size(); -// -void *sim_lifted_irk_dims_assign(void* config_, void *raw_memory); - -/* model */ -// -acados_size_t sim_lifted_irk_model_calculate_size(void *config, void *dims); -// -void *sim_lifted_irk_model_assign(void *config, void *dims, void *raw_memory); -// -int sim_lifted_irk_model_set(void *model_, const char *field, void *value); - -/* opts */ -// -acados_size_t sim_lifted_irk_opts_calculate_size(void *config, void *dims); -// -void *sim_lifted_irk_opts_assign(void *config, void *dims, void *raw_memory); -// -void sim_lifted_irk_opts_initialize_default(void *config, void *dims, void *opts_); -// -void sim_lifted_irk_opts_update(void *config_, void *dims, void *opts_); -// -void sim_lifted_irk_opts_set(void *config_, void *opts_, const char *field, void *value); - -/* memory */ -// -acados_size_t sim_lifted_irk_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *sim_lifted_irk_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); - -/* workspace */ -// -acados_size_t sim_lifted_irk_workspace_calculate_size(void *config, void *dims, void *opts_); -// -void sim_lifted_irk_config_initialize_default(void *config); - -/* solver */ -// -int sim_lifted_irk(void *config, sim_in *in, sim_out *out, void *opts_, - void *mem_, void *work_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_LIFTED_IRK_INTEGRATOR_H_ diff --git a/third_party/acados/include/acados/utils/external_function_generic.h b/third_party/acados/include/acados/utils/external_function_generic.h deleted file mode 100644 index 1e68dc155db82d..00000000000000 --- a/third_party/acados/include/acados/utils/external_function_generic.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_UTILS_EXTERNAL_FUNCTION_GENERIC_H_ -#define ACADOS_UTILS_EXTERNAL_FUNCTION_GENERIC_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/utils/types.h" - -/************************************************ - * generic external function - ************************************************/ - -// type of arguments -typedef enum { - COLMAJ, - BLASFEO_DMAT, - BLASFEO_DVEC, - COLMAJ_ARGS, - BLASFEO_DMAT_ARGS, - BLASFEO_DVEC_ARGS, - IGNORE_ARGUMENT -} ext_fun_arg_t; - -struct colmaj_args -{ - double *A; - int lda; -}; - -struct blasfeo_dmat_args -{ - struct blasfeo_dmat *A; - int ai; - int aj; -}; - -struct blasfeo_dvec_args -{ - struct blasfeo_dvec *x; - int xi; -}; - -// prototype of an external function -typedef struct -{ - // public members (have to be before private ones) - void (*evaluate)(void *, ext_fun_arg_t *, void **, ext_fun_arg_t *, void **); - // private members - // ..... -} external_function_generic; - - - -/************************************************ - * generic external parametric function - ************************************************/ - -// prototype of a parametric external function -typedef struct -{ - // public members for core (have to be before private ones) - void (*evaluate)(void *, ext_fun_arg_t *, void **, ext_fun_arg_t *, void **); - // public members for interfaces - void (*get_nparam)(void *, int *); - void (*set_param)(void *, double *); - void (*set_param_sparse)(void *, int n_update, int *idx, double *); - // private members - void *ptr_ext_mem; // pointer to external memory - int (*fun)(void **, void **, void *); - double *p; // parameters - int np; // number of parameters - // ..... -} external_function_param_generic; - -// -acados_size_t external_function_param_generic_struct_size(); -// -void external_function_param_generic_set_fun(external_function_param_generic *fun, void *value); -// -acados_size_t external_function_param_generic_calculate_size(external_function_param_generic *fun, int np); -// -void external_function_param_generic_assign(external_function_param_generic *fun, void *mem); -// -void external_function_param_generic_wrapper(void *self, ext_fun_arg_t *type_in, void **in, ext_fun_arg_t *type_out, void **out); -// -void external_function_param_generic_get_nparam(void *self, int *np); -// -void external_function_param_generic_set_param(void *self, double *p); - - -/************************************************ - * casadi external function - ************************************************/ - -typedef struct -{ - // public members (have to be the same as in the prototype, and before the private ones) - void (*evaluate)(void *, ext_fun_arg_t *, void **, ext_fun_arg_t *, void **); - // private members - void *ptr_ext_mem; // pointer to external memory - int (*casadi_fun)(const double **, double **, int *, double *, void *); - int (*casadi_work)(int *, int *, int *, int *); - const int *(*casadi_sparsity_in)(int); - const int *(*casadi_sparsity_out)(int); - int (*casadi_n_in)(void); - int (*casadi_n_out)(void); - double **args; - double **res; - double *w; - int *iw; - int *args_size; // size of args[i] - int *res_size; // size of res[i] - int args_num; // number of args arrays - int args_size_tot; // total size of args arrays - int res_num; // number of res arrays - int res_size_tot; // total size of res arrays - int in_num; // number of input arrays - int out_num; // number of output arrays - int iw_size; // number of ints for worksapce - int w_size; // number of doubles for workspace -} external_function_casadi; - -// -acados_size_t external_function_casadi_struct_size(); -// -void external_function_casadi_set_fun(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_work(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_sparsity_in(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_sparsity_out(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_n_in(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_n_out(external_function_casadi *fun, void *value); -// -acados_size_t external_function_casadi_calculate_size(external_function_casadi *fun); -// -void external_function_casadi_assign(external_function_casadi *fun, void *mem); -// -void external_function_casadi_wrapper(void *self, ext_fun_arg_t *type_in, void **in, - ext_fun_arg_t *type_out, void **out); - -/************************************************ - * casadi external parametric function - ************************************************/ - -typedef struct -{ - // public members for core (have to be the same as in the prototype, and before the private ones) - void (*evaluate)(void *, ext_fun_arg_t *, void **, ext_fun_arg_t *, void **); - // public members for interfaces - void (*get_nparam)(void *, int *); - void (*set_param)(void *, double *); - void (*set_param_sparse)(void *, int n_update, int *idx, double *); - // private members - void *ptr_ext_mem; // pointer to external memory - int (*casadi_fun)(const double **, double **, int *, double *, void *); - int (*casadi_work)(int *, int *, int *, int *); - const int *(*casadi_sparsity_in)(int); - const int *(*casadi_sparsity_out)(int); - int (*casadi_n_in)(void); - int (*casadi_n_out)(void); - double **args; - double **res; - double *w; - int *iw; - int *args_size; // size of args[i] - int *res_size; // size of res[i] - int args_num; // number of args arrays - int args_size_tot; // total size of args arrays - int res_num; // number of res arrays - int res_size_tot; // total size of res arrays - int in_num; // number of input arrays - int out_num; // number of output arrays - int iw_size; // number of ints for worksapce - int w_size; // number of doubles for workspace - int np; // number of parameters -} external_function_param_casadi; - -// -acados_size_t external_function_param_casadi_struct_size(); -// -void external_function_param_casadi_set_fun(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_work(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_sparsity_in(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_sparsity_out(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_n_in(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_n_out(external_function_param_casadi *fun, void *value); -// -acados_size_t external_function_param_casadi_calculate_size(external_function_param_casadi *fun, int np); -// -void external_function_param_casadi_assign(external_function_param_casadi *fun, void *mem); -// -void external_function_param_casadi_wrapper(void *self, ext_fun_arg_t *type_in, void **in, - ext_fun_arg_t *type_out, void **out); -// -void external_function_param_casadi_get_nparam(void *self, int *np); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_EXTERNAL_FUNCTION_GENERIC_H_ diff --git a/third_party/acados/include/acados/utils/math.h b/third_party/acados/include/acados/utils/math.h deleted file mode 100644 index 7156a82084267f..00000000000000 --- a/third_party/acados/include/acados/utils/math.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - -#ifndef ACADOS_UTILS_MATH_H_ -#define ACADOS_UTILS_MATH_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/utils/types.h" - -#if defined(__MABX2__) -double fmax(double a, double b); -int isnan(double x); -#endif - -#define MIN(a,b) (((a)<(b))?(a):(b)) -#define MAX(a,b) (((a)>(b))?(a):(b)) - -void dgemm_nn_3l(int m, int n, int k, double *A, int lda, double *B, int ldb, double *C, int ldc); -// void dgemv_n_3l(int m, int n, double *A, int lda, double *x, double *y); -// void dgemv_t_3l(int m, int n, double *A, int lda, double *x, double *y); -// void dcopy_3l(int n, double *x, int incx, double *y, int incy); -void daxpy_3l(int n, double da, double *dx, double *dy); -void dscal_3l(int n, double da, double *dx); -double twonormv(int n, double *ptrv); - -/* copies a matrix into another matrix */ -void dmcopy(int row, int col, double *ptrA, int lda, double *ptrB, int ldb); - -/* solution of a system of linear equations */ -void dgesv_3l(int n, int nrhs, double *A, int lda, int *ipiv, double *B, int ldb, int *info); - -/* matrix exponential */ -void expm(int row, double *A); - -int idamax_3l(int n, double *x); - -void dswap_3l(int n, double *x, int incx, double *y, int incy); - -void dger_3l(int m, int n, double alpha, double *x, int incx, double *y, int incy, double *A, - int lda); - -void dgetf2_3l(int m, int n, double *A, int lda, int *ipiv, int *info); - -void dlaswp_3l(int n, double *A, int lda, int k1, int k2, int *ipiv); - -void dtrsm_l_l_n_u_3l(int m, int n, double *A, int lda, double *B, int ldb); - -void dgetrs_3l(int n, int nrhs, double *A, int lda, int *ipiv, double *B, int ldb); - -void dgesv_3l(int n, int nrhs, double *A, int lda, int *ipiv, double *B, int ldb, int *info); - -double onenorm(int row, int col, double *ptrA); - -// double twonormv(int n, double *ptrv); - -void padeapprox(int m, int row, double *A); - -void expm(int row, double *A); - -// void d_compute_qp_size_ocp2dense_rev(int N, int *nx, int *nu, int *nb, int **hidxb, int *ng, -// int *nvd, int *ned, int *nbd, int *ngd); - -void acados_eigen_decomposition(int dim, double *A, double *V, double *d, double *e); - -double minimum_of_doubles(double *x, int n); - -void neville_algorithm(double xx, int n, double *x, double *Q, double *out); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_MATH_H_ diff --git a/third_party/acados/include/acados/utils/mem.h b/third_party/acados/include/acados/utils/mem.h deleted file mode 100644 index 681a371e360f64..00000000000000 --- a/third_party/acados/include/acados/utils/mem.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_UTILS_MEM_H_ -#define ACADOS_UTILS_MEM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -#include "types.h" - -// blasfeo -#include "blasfeo/include/blasfeo_d_aux.h" -#include "blasfeo/include/blasfeo_d_aux_ext_dep.h" - -// TODO(dimitris): probably does not belong here -typedef struct -{ - int (*fun)(void *); - acados_size_t (*calculate_args_size)(void *); - void *(*assign_args)(void *); - void (*initialize_default_args)(void *); - acados_size_t (*calculate_memory_size)(void *); - void *(*assign_memory)(void *); - acados_size_t (*calculate_workspace_size)(void *); -} module_solver; - -// make int counter of memory multiple of a number (typically 8 or 64) -void make_int_multiple_of(acados_size_t num, acados_size_t *size); - -// align char pointer to number (typically 8 for pointers and doubles, -// 64 for blasfeo structs) and return offset -int align_char_to(int num, char **c_ptr); - -// switch between malloc and calloc (for valgrinding) -void *acados_malloc(size_t nitems, acados_size_t size); - -// uses always calloc -void *acados_calloc(size_t nitems, acados_size_t size); - -// allocate vector of pointers to vectors of doubles and advance pointer -void assign_and_advance_double_ptrs(int n, double ***v, char **ptr); - -// allocate vector of pointers to vectors of ints and advance pointer -void assign_and_advance_int_ptrs(int n, int ***v, char **ptr); - -// allocate vector of pointers to strvecs and advance pointer -void assign_and_advance_blasfeo_dvec_structs(int n, struct blasfeo_dvec **sv, char **ptr); - -// allocate vector of pointers to strmats and advance pointer -void assign_and_advance_blasfeo_dmat_structs(int n, struct blasfeo_dmat **sm, char **ptr); - -// allocate vector of pointers to vector of pointers to strmats and advance pointer -void assign_and_advance_blasfeo_dmat_ptrs(int n, struct blasfeo_dmat ***sm, char **ptr); - -// allocate vector of chars and advance pointer -void assign_and_advance_char(int n, char **v, char **ptr); - -// allocate vector of ints and advance pointer -void assign_and_advance_int(int n, int **v, char **ptr); - -// allocate vector of bools and advance pointer -void assign_and_advance_bool(int n, bool **v, char **ptr); - -// allocate vector of doubles and advance pointer -void assign_and_advance_double(int n, double **v, char **ptr); - -// allocate strvec and advance pointer -void assign_and_advance_blasfeo_dvec_mem(int n, struct blasfeo_dvec *sv, char **ptr); - -// allocate strmat and advance pointer -void assign_and_advance_blasfeo_dmat_mem(int m, int n, struct blasfeo_dmat *sA, char **ptr); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_MEM_H_ diff --git a/third_party/acados/include/acados/utils/print.h b/third_party/acados/include/acados/utils/print.h deleted file mode 100644 index 824d3cee224a99..00000000000000 --- a/third_party/acados/include/acados/utils/print.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_UTILS_PRINT_H_ -#define ACADOS_UTILS_PRINT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/ocp_nlp/ocp_nlp_common.h" -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_qp/ocp_qp_common_frontend.h" -#include "acados/utils/types.h" - -// void print_matrix(char *file_name, const real_t *matrix, const int_t nrows, const int_t ncols); - -// void print_matrix_name(char *file_name, char *name, const real_t *matrix, const int_t nrows, -// const int_t ncols); - -// void print_int_matrix(char *file_name, const int_t *matrix, const int_t nrows, const int_t ncols); - -// void print_array(char *file_name, real_t *array, int_t size); - -// void print_int_array(char *file_name, const int_t *array, int_t size); - -void read_matrix(const char *file_name, real_t *array, const int_t nrows, const int_t ncols); - -void write_double_vector_to_txt(real_t *vec, int_t n, const char *fname); - -// ocp nlp -// TODO(andrea): inconsistent naming -void ocp_nlp_dims_print(ocp_nlp_dims *dims); -// TODO(andrea): inconsistent naming -void ocp_nlp_out_print(ocp_nlp_dims *dims, ocp_nlp_out *nlp_out); -// TODO(andrea): inconsistent naming -void ocp_nlp_res_print(ocp_nlp_dims *dims, ocp_nlp_res *nlp_res); - -// ocp qp -// TODO: move printing routines below that print qp structures to HPIPM! -void print_ocp_qp_dims(ocp_qp_dims *dims); - -// void print_dense_qp_dims(dense_qp_dims *dims); - -void print_ocp_qp_in(ocp_qp_in *qp_in); - -void print_ocp_qp_in_to_file(FILE *file, ocp_qp_in *qp_in); - -void print_ocp_qp_out(ocp_qp_out *qp_out); - -void print_ocp_qp_out_to_file(FILE *file, ocp_qp_out *qp_out); - -void print_ocp_qp_res(ocp_qp_res *qp_res); - -void print_dense_qp_in(dense_qp_in *qp_in); -// void print_ocp_qp_in_to_string(char string_out[], ocp_qp_in *qp_in); - -// void print_ocp_qp_out_to_string(char string_out[], ocp_qp_out *qp_out); - -// void print_colmaj_ocp_qp_in(colmaj_ocp_qp_in *qp); - -// void print_colmaj_ocp_qp_in_to_file(colmaj_ocp_qp_in *qp); - -// void print_colmaj_ocp_qp_out(char *filename, colmaj_ocp_qp_in *qp, colmaj_ocp_qp_out *out); - -void print_qp_info(qp_info *info); - -// void acados_warning(char warning_string[]); - -// void acados_error(char error_string[]); - -// void acados_not_implemented(char feature_string[]); - -// blasfeo -// void print_blasfeo_target(); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_PRINT_H_ diff --git a/third_party/acados/include/acados/utils/strsep.h b/third_party/acados/include/acados/utils/strsep.h deleted file mode 100644 index 62bdfb48913266..00000000000000 --- a/third_party/acados/include/acados/utils/strsep.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_UTILS_STRSEP_H_ -#define ACADOS_UTILS_STRSEP_H_ - -#ifdef __cplusplus -#include -#define STD(x) std::x -namespace std -{ -#else -#include -#define STD(x) x -#endif - -char* strsep_acados(char** stringp, const char* delim) -{ - char* result; - - if ((stringp == NULL) || (*stringp == NULL)) return NULL; - - result = *stringp; - - while (**stringp && !STD(strchr)(delim, **stringp)) ++*stringp; - - if (**stringp) - *(*stringp)++ = '\0'; - else - *stringp = NULL; - - return result; -} - -#ifdef __cplusplus -} // namespace std -#endif - -#undef STD - -#endif // ACADOS_UTILS_STRSEP_H_ diff --git a/third_party/acados/include/acados/utils/timing.h b/third_party/acados/include/acados/utils/timing.h deleted file mode 100644 index b0955932da3a2f..00000000000000 --- a/third_party/acados/include/acados/utils/timing.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_UTILS_TIMING_H_ -#define ACADOS_UTILS_TIMING_H_ - -#include "acados/utils/types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef MEASURE_TIMINGS -#if (defined _WIN32 || defined _WIN64) && !(defined __MINGW32__ || defined __MINGW64__) - -/* Use Windows QueryPerformanceCounter for timing. */ -#include - -/** A structure for keeping internal timer data. */ -typedef struct acados_timer_ -{ - LARGE_INTEGER tic; - LARGE_INTEGER toc; - LARGE_INTEGER freq; -} acados_timer; - -#elif defined(__APPLE__) - -#include - -/** A structure for keeping internal timer data. */ -typedef struct acados_timer_ -{ - uint64_t tic; - uint64_t toc; - mach_timebase_info_data_t tinfo; -} acados_timer; - -#elif defined(__MABX2__) - -#include - -typedef struct acados_timer_ -{ - double time; -} acados_timer; - -#else - -/* Use POSIX clock_gettime() for timing on non-Windows machines. */ -#include - -#if (__STDC_VERSION__ >= 199901L) && !(defined __MINGW32__ || defined __MINGW64__) // C99 Mode - -#include -#include - -typedef struct acados_timer_ -{ - struct timeval tic; - struct timeval toc; -} acados_timer; - -#else // ANSI C Mode - -/** A structure for keeping internal timer data. */ -typedef struct acados_timer_ -{ - struct timespec tic; - struct timespec toc; -} acados_timer; - -#endif // __STDC_VERSION__ >= 199901L - -#endif // (defined _WIN32 || defined _WIN64) - -#else - -// Dummy type when timings are off -typedef real_t acados_timer; - -#endif // MEASURE_TIMINGS - -/** A function for measurement of the current time. */ -void acados_tic(acados_timer* t); - -/** A function which returns the elapsed time. */ -real_t acados_toc(acados_timer* t); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_TIMING_H_ diff --git a/third_party/acados/include/acados/utils/types.h b/third_party/acados/include/acados/utils/types.h deleted file mode 100644 index a27ef9e552ce62..00000000000000 --- a/third_party/acados/include/acados/utils/types.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef ACADOS_UTILS_TYPES_H_ -#define ACADOS_UTILS_TYPES_H_ - -/* Symbol visibility in DLLs */ -#ifndef ACADOS_SYMBOL_EXPORT - #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) - #if defined(STATIC_LINKED) - #define ACADOS_SYMBOL_EXPORT - #else - #define ACADOS_SYMBOL_EXPORT __declspec(dllexport) - #endif - #elif defined(__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) - #define ACADOS_SYMBOL_EXPORT __attribute__ ((visibility ("default"))) - #else - #define ACADOS_SYMBOL_EXPORT - #endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -#define MAX_STR_LEN 256 -#define ACADOS_EPS 1e-12 -#define ACADOS_NEG_INFTY -1.0e9 -#define ACADOS_POS_INFTY +1.0e9 -#define UNUSED(x) ((void)(x)) - - - -typedef double real_t; -typedef int int_t; -typedef size_t acados_size_t; - - -typedef int (*casadi_function_t)(const double** arg, double** res, int* iw, double* w, void* mem); - - - -// enum of return values -enum return_values -{ - ACADOS_SUCCESS, - ACADOS_NAN_DETECTED, - ACADOS_MAXITER, - ACADOS_MINSTEP, - ACADOS_QP_FAILURE, - ACADOS_READY, -}; - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_TYPES_H_ diff --git a/third_party/acados/include/acados_c/condensing_interface.h b/third_party/acados/include/acados_c/condensing_interface.h deleted file mode 100644 index b4302078d63516..00000000000000 --- a/third_party/acados/include/acados_c/condensing_interface.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef INTERFACES_ACADOS_C_CONDENSING_INTERFACE_H_ -#define INTERFACES_ACADOS_C_CONDENSING_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_full_condensing.h" -#include "acados/ocp_qp/ocp_qp_partial_condensing.h" - -typedef enum { - PARTIAL_CONDENSING, - FULL_CONDENSING, -} condensing_t; - -typedef struct -{ - condensing_t condensing_type; -} condensing_plan; - -typedef struct -{ - ocp_qp_xcond_config *config; - void *dims; - void *opts; - void *mem; - void *work; -} condensing_module; - -ocp_qp_xcond_config *ocp_qp_condensing_config_create(condensing_plan *plan); -// -void *ocp_qp_condensing_opts_create(ocp_qp_xcond_config *config, void *dims_); -// -acados_size_t ocp_qp_condensing_calculate_size(ocp_qp_xcond_config *config, void *dims_, void *opts_); -// -condensing_module *ocp_qp_condensing_assign(ocp_qp_xcond_config *config, void *dims_, - void *opts_, void *raw_memory); -// -condensing_module *ocp_qp_condensing_create(ocp_qp_xcond_config *config, void *dims_, - void *opts_); -// -int ocp_qp_condense(condensing_module *module, void *qp_in, void *qp_out); -// -int ocp_qp_expand(condensing_module *module, void *qp_in, void *qp_out); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_CONDENSING_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/dense_qp_interface.h b/third_party/acados/include/acados_c/dense_qp_interface.h deleted file mode 100644 index b3af4bf68250a2..00000000000000 --- a/third_party/acados/include/acados_c/dense_qp_interface.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef INTERFACES_ACADOS_C_DENSE_QP_INTERFACE_H_ -#define INTERFACES_ACADOS_C_DENSE_QP_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/dense_qp/dense_qp_common.h" - -typedef enum { DENSE_QP_HPIPM, DENSE_QP_QORE, DENSE_QP_QPOASES, DENSE_QP_OOQP, DENSE_QP_DAQP } dense_qp_solver_t; - -typedef struct -{ - dense_qp_solver_t qp_solver; -} dense_qp_solver_plan; - -typedef struct -{ - qp_solver_config *config; - void *dims; - void *opts; - void *mem; - void *work; -} dense_qp_solver; - -qp_solver_config *dense_qp_config_create(dense_qp_solver_plan *plan); -// -dense_qp_dims *dense_qp_dims_create(); -// -dense_qp_in *dense_qp_in_create(qp_solver_config *config, dense_qp_dims *dims); -// -dense_qp_out *dense_qp_out_create(qp_solver_config *config, dense_qp_dims *dims); -// -void *dense_qp_opts_create(qp_solver_config *config, dense_qp_dims *dims); -// -acados_size_t dense_qp_calculate_size(qp_solver_config *config, dense_qp_dims *dims, void *opts_); -// -dense_qp_solver *dense_qp_assign(qp_solver_config *config, dense_qp_dims *dims, void *opts_, - void *raw_memory); -// -dense_qp_solver *dense_qp_create(qp_solver_config *config, dense_qp_dims *dims, void *opts_); -// -int dense_qp_solve(dense_qp_solver *solver, dense_qp_in *qp_in, dense_qp_out *qp_out); -// -void dense_qp_inf_norm_residuals(dense_qp_dims *dims, dense_qp_in *qp_in, dense_qp_out *qp_out, - double *res); -// -bool dense_qp_set_field_double_array(const char *field, double *arr, dense_qp_in *qp_in); -// -bool dense_qp_set_field_int_array(const char *field, int *arr, dense_qp_in *qp_in); -// -bool dense_qp_get_field_double_array(const char *field, dense_qp_in *qp_in, double *arr); -// -bool dense_qp_get_field_int_array(const char *field, dense_qp_in *qp_in, int *arr); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_DENSE_QP_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/external_function_interface.h b/third_party/acados/include/acados_c/external_function_interface.h deleted file mode 100644 index d4f52db8505981..00000000000000 --- a/third_party/acados/include/acados_c/external_function_interface.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef INTERFACES_ACADOS_C_EXTERNAL_FUNCTION_INTERFACE_H_ -#define INTERFACES_ACADOS_C_EXTERNAL_FUNCTION_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/utils/external_function_generic.h" - - - -/************************************************ - * generic external parametric function - ************************************************/ - -// -void external_function_param_generic_create(external_function_param_generic *fun, int np); -// -void external_function_param_generic_free(external_function_param_generic *fun); - - - -/************************************************ - * casadi external function - ************************************************/ - -// -void external_function_casadi_create(external_function_casadi *fun); -// -void external_function_casadi_free(external_function_casadi *fun); -// -void external_function_casadi_create_array(int size, external_function_casadi *funs); -// -void external_function_casadi_free_array(int size, external_function_casadi *funs); - - - -/************************************************ - * casadi external parametric function - ************************************************/ - -// -void external_function_param_casadi_create(external_function_param_casadi *fun, int np); -// -void external_function_param_casadi_free(external_function_param_casadi *fun); -// -void external_function_param_casadi_create_array(int size, external_function_param_casadi *funs, - int np); -// -void external_function_param_casadi_free_array(int size, external_function_param_casadi *funs); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_EXTERNAL_FUNCTION_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/ocp_nlp_interface.h b/third_party/acados/include/acados_c/ocp_nlp_interface.h deleted file mode 100644 index dd3e596f8be763..00000000000000 --- a/third_party/acados/include/acados_c/ocp_nlp_interface.h +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef INTERFACES_ACADOS_C_OCP_NLP_INTERFACE_H_ -#define INTERFACES_ACADOS_C_OCP_NLP_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_nlp/ocp_nlp_common.h" -#include "acados/ocp_nlp/ocp_nlp_constraints_bgh.h" -#include "acados/sim/sim_erk_integrator.h" -#include "acados/sim/sim_irk_integrator.h" -#include "acados/sim/sim_lifted_irk_integrator.h" -#include "acados/sim/sim_gnsf.h" -#include "acados/utils/types.h" -// acados_c -#include "acados_c/ocp_qp_interface.h" -#include "acados_c/sim_interface.h" - - -/// Solution methods for optimal control problems. -typedef enum -{ - SQP, - SQP_RTI, - INVALID_NLP_SOLVER, -} ocp_nlp_solver_t; - - -/// Types of the cost function. -typedef enum -{ - LINEAR_LS, - NONLINEAR_LS, - CONVEX_OVER_NONLINEAR, - EXTERNAL, - INVALID_COST, -} ocp_nlp_cost_t; - - -/// Types of the system dynamics, discrete or continuous time. -typedef enum -{ - CONTINUOUS_MODEL, - DISCRETE_MODEL, - INVALID_DYNAMICS, -} ocp_nlp_dynamics_t; - - -/// Constraint types -typedef enum -{ - /// Comprises simple bounds, polytopic constraints, - /// general non-linear constraints. - BGH, - - /// Comprises simple bounds, polytopic constraints, - /// general non-linear constraints, and positive definite constraints. - BGP, - - INVALID_CONSTRAINT, -} ocp_nlp_constraints_t; - - -/// Regularization types -typedef enum -{ - NO_REGULARIZE, - MIRROR, - PROJECT, - PROJECT_REDUC_HESS, - CONVEXIFY, - INVALID_REGULARIZE, -} ocp_nlp_reg_t; - - -/// Structure to store the configuration of a non-linear program -typedef struct ocp_nlp_plan_t -{ - /// QP solver configuration. - ocp_qp_solver_plan_t ocp_qp_solver_plan; - - /// Simulation solver configuration for each stage. - sim_solver_plan_t *sim_solver_plan; - - /// Nlp solver type. - ocp_nlp_solver_t nlp_solver; - - /// Regularization type, defaults to no regularization. - ocp_nlp_reg_t regularization; - - /// Cost type for each stage. - ocp_nlp_cost_t *nlp_cost; - - /// Dynamics type for each stage. - ocp_nlp_dynamics_t *nlp_dynamics; - - /// Constraints type for each stage. - ocp_nlp_constraints_t *nlp_constraints; - - /// Horizon length. - int N; - -} ocp_nlp_plan_t; - - -/// Structure to store the state/configuration for the non-linear programming solver -typedef struct ocp_nlp_solver -{ - ocp_nlp_config *config; - void *dims; - void *opts; - void *mem; - void *work; -} ocp_nlp_solver; - - -/// Constructs an empty plan struct (user nlp configuration), all fields are set to a -/// default/invalid state. -/// -/// \param N Horizon length -ACADOS_SYMBOL_EXPORT ocp_nlp_plan_t *ocp_nlp_plan_create(int N); - -/// Destructor for plan struct, frees memory. -/// -/// \param plan_ The plan struct to destroy. -ACADOS_SYMBOL_EXPORT void ocp_nlp_plan_destroy(void* plan_); - - -/// Constructs an nlp configuration struct from a plan. -/// -/// \param plan The plan (user nlp configuration). -ACADOS_SYMBOL_EXPORT ocp_nlp_config *ocp_nlp_config_create(ocp_nlp_plan_t plan); - -/// Desctructor of the nlp configuration. -/// -/// \param config_ The configuration struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_config_destroy(void *config_); - - -/// Constructs an struct that contains the dimensions of the variables. -/// -/// \param config_ The configuration struct. -ACADOS_SYMBOL_EXPORT ocp_nlp_dims *ocp_nlp_dims_create(void *config_); - -/// Destructor of The dimension struct. -/// -/// \param dims_ The dimension struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_dims_destroy(void *dims_); - - -/// Constructs an input struct for a non-linear programs. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -ACADOS_SYMBOL_EXPORT ocp_nlp_in *ocp_nlp_in_create(ocp_nlp_config *config, ocp_nlp_dims *dims); - -/// Destructor of the inputs struct. -/// -/// \param in The inputs struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_in_destroy(void *in); - - -/// Sets the sampling times for the given stage. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param in The inputs struct. -/// \param stage Stage number. -/// \param field Has to be "Ts" (TBC other options). -/// \param value The sampling times (floating point). -ACADOS_SYMBOL_EXPORT void ocp_nlp_in_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, - const char *field, void *value); - -/// -// void ocp_nlp_in_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, -// const char *field, void *value); - -/// Sets the function pointers to the dynamics functions for the given stage. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param in The inputs struct. -/// \param stage Stage number. -/// \param fun_type The name of the function type, either impl_ode_fun, -/// impl_ode_fun_jac_x_xdot, impl_ode_jac_x_xdot_u (TBC) -/// \param fun_ptr Function pointer to the dynamics function. -ACADOS_SYMBOL_EXPORT int ocp_nlp_dynamics_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - int stage, const char *fun_type, void *fun_ptr); - - -/// Sets the function pointers to the cost functions for the given stage. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param in The inputs struct. -/// \param stage Stage number. -/// \param field The name of the field, either nls_res_jac, -/// y_ref, W (others TBC) -/// \param value Cost values. -ACADOS_SYMBOL_EXPORT int ocp_nlp_cost_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - int stage, const char *field, void *value); - - -/// Sets the function pointers to the constraints functions for the given stage. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param in The inputs struct. -/// \param stage Stage number. -/// \param field The name of the field, either lb, ub (others TBC) -/// \param value Constraints function or values. -ACADOS_SYMBOL_EXPORT int ocp_nlp_constraints_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_in *in, int stage, const char *field, void *value); - -/// -ACADOS_SYMBOL_EXPORT void ocp_nlp_constraints_model_get(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_in *in, int stage, const char *field, void *value); - -/* out */ - -/// Constructs an output struct for the non-linear program. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -ACADOS_SYMBOL_EXPORT ocp_nlp_out *ocp_nlp_out_create(ocp_nlp_config *config, ocp_nlp_dims *dims); - -/// Destructor of the output struct. -/// -/// \param out The output struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_out_destroy(void *out); - - -/// Sets fields in the output struct of an nlp solver, used to initialize the solver. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param out The output struct. -/// \param stage Stage number. -/// \param field The name of the field, either x, u, pi. -/// \param value Initialization values. -ACADOS_SYMBOL_EXPORT void ocp_nlp_out_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, void *value); - - -/// Gets values of fields in the output struct of an nlp solver. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param out The output struct. -/// \param stage Stage number. -/// \param field The name of the field, either x, u, z, pi. -/// \param value Pointer to the output memory. -ACADOS_SYMBOL_EXPORT void ocp_nlp_out_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, void *value); - -// -ACADOS_SYMBOL_EXPORT void ocp_nlp_get_at_stage(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_solver *solver, - int stage, const char *field, void *value); - -// TODO(andrea): remove this once/if the MATLAB interface uses the new setters below? -ACADOS_SYMBOL_EXPORT int ocp_nlp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field); - -ACADOS_SYMBOL_EXPORT void ocp_nlp_constraint_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out); - -ACADOS_SYMBOL_EXPORT void ocp_nlp_cost_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out); - -ACADOS_SYMBOL_EXPORT void ocp_nlp_qp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out); - -/* opts */ - -/// Creates an options struct for the non-linear program. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -ACADOS_SYMBOL_EXPORT void *ocp_nlp_solver_opts_create(ocp_nlp_config *config, ocp_nlp_dims *dims); - -/// Destructor of the options. -/// -/// \param opts The options struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_destroy(void *opts); - -/// Sets an option. -/// -/// \param config The configuration struct. -/// \param opts_ The options struct. -/// \param field Name of the option. -/// \param value Value of the option. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_set(ocp_nlp_config *config, void *opts_, const char *field, void* value); - - -// ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_get(ocp_nlp_config *config, void *opts_, const char *field, void* value); - - -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_set_at_stage(ocp_nlp_config *config, void *opts_, int stage, const char *field, void* value); - - -/// TBC -/// Updates the options. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param opts_ The options struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_update(ocp_nlp_config *config, ocp_nlp_dims *dims, void *opts_); - - -/* solver */ - -/// Creates an ocp solver. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param opts_ The options struct. -/// \return The solver. -ACADOS_SYMBOL_EXPORT ocp_nlp_solver *ocp_nlp_solver_create(ocp_nlp_config *config, ocp_nlp_dims *dims, void *opts_); - -/// Destructor of the solver. -/// -/// \param solver The solver struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_destroy(void *solver); - -/// Solves the optimal control problem. Call ocp_nlp_precompute before -/// calling this functions (TBC). -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT int ocp_nlp_solve(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - - -/// Resets the memory of the QP solver -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_reset_qp_memory(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - -/// Performs precomputations for the solver. Needs to be called before -/// ocl_nlp_solve (TBC). -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT int ocp_nlp_precompute(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - -/// Computes cost function value. -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_cost(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - -/// Computes the residuals. -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_residuals(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - -// -ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_param_sens(ocp_nlp_solver *solver, char *field, int stage, int index, ocp_nlp_out *sens_nlp_out); - -/* get */ -/// \param config The configuration struct. -/// \param solver The solver struct. -/// \param field Supports "sqp_iter", "status", "nlp_res", "time_tot", ... -/// \param return_value_ Pointer to the output memory. -ACADOS_SYMBOL_EXPORT void ocp_nlp_get(ocp_nlp_config *config, ocp_nlp_solver *solver, - const char *field, void *return_value_); - -/* set */ -/// Sets the initial guesses for the integrator for the given stage. -/// -/// \param config The configuration struct. -/// \param solver The ocp_nlp_solver struct. -/// \param stage Stage number. -/// \param field Supports "z_guess", "xdot_guess" (IRK), "phi_guess" (GNSF-IRK) -/// \param value The initial guess for the algebraic variables in the integrator (if continuous model is used). -ACADOS_SYMBOL_EXPORT void ocp_nlp_set(ocp_nlp_config *config, ocp_nlp_solver *solver, - int stage, const char *field, void *value); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_OCP_NLP_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/ocp_qp_interface.h b/third_party/acados/include/acados_c/ocp_qp_interface.h deleted file mode 100644 index 3dc3f1a532e50c..00000000000000 --- a/third_party/acados/include/acados_c/ocp_qp_interface.h +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef INTERFACES_ACADOS_C_OCP_QP_INTERFACE_H_ -#define INTERFACES_ACADOS_C_OCP_QP_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_qp/ocp_qp_xcond_solver.h" - - -/// QP solver types (Enumeration). -/// -/// Full list of fields: -/// PARTIAL_CONDENSING_HPIPM -/// PARTIAL_CONDENSING_HPMPC -/// PARTIAL_CONDENSING_OOQP -/// PARTIAL_CONDENSING_OSQP -/// PARTIAL_CONDENSING_QPDUNES -/// FULL_CONDENSING_HPIPM -/// FULL_CONDENSING_QPOASES -/// FULL_CONDENSING_QORE -/// FULL_CONDENSING_OOQP -/// INVALID_QP_SOLVER -/// -/// Note: In this enumeration the partial condensing solvers have to be -/// specified before the full condensing solvers. -typedef enum { - PARTIAL_CONDENSING_HPIPM, -#ifdef ACADOS_WITH_HPMPC - PARTIAL_CONDENSING_HPMPC, -#else - PARTIAL_CONDENSING_HPMPC_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_OOQP - PARTIAL_CONDENSING_OOQP, -#else - PARTIAL_CONDENSING_OOQP_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_OSQP - PARTIAL_CONDENSING_OSQP, -#else - PARTIAL_CONDENSING_OSQP_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_QPDUNES - PARTIAL_CONDENSING_QPDUNES, -#else - PARTIAL_CONDENSING_QPDUNES_NOT_AVAILABLE, -#endif - FULL_CONDENSING_HPIPM, -#ifdef ACADOS_WITH_QPOASES - FULL_CONDENSING_QPOASES, -#else - FULL_CONDENSING_QPOASES_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_DAQP - FULL_CONDENSING_DAQP, -#else - FULL_CONDENSING_DAQP_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_QORE - FULL_CONDENSING_QORE, -#else - FULL_CONDENSING_QORE_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_OOQP - FULL_CONDENSING_OOQP, -#else - FULL_CONDENSING_OOQP_NOT_AVAILABLE, -#endif - INVALID_QP_SOLVER, -} ocp_qp_solver_t; - - -/// Struct containing qp solver -typedef struct -{ - ocp_qp_solver_t qp_solver; -} ocp_qp_solver_plan_t; - - -/// Linear ocp configuration. -typedef struct -{ - ocp_qp_xcond_solver_config *config; - ocp_qp_xcond_solver_dims *dims; - void *opts; - void *mem; - void *work; -} ocp_qp_solver; - - -/// Initializes the qp solver configuration. -/// TBC should this be private/static - no, used in ocp_nlp -void ocp_qp_xcond_solver_config_initialize_from_plan( - ocp_qp_solver_t solver_name, ocp_qp_xcond_solver_config *solver_config); - -/// Constructs a qp solver config and Initializes with default values. -/// -/// \param plan The qp solver plan struct. -ocp_qp_xcond_solver_config *ocp_qp_xcond_solver_config_create(ocp_qp_solver_plan_t plan); - -/// Destructor for config struct, frees memory. -/// -/// \param config The config object to destroy. -void ocp_qp_xcond_solver_config_free(ocp_qp_xcond_solver_config *config); - - -/// Constructs a struct that contains the dimensions for the variables of the qp. -/// -/// \param N The number of variables. -ocp_qp_dims *ocp_qp_dims_create(int N); - -/// Destructor of The dimension struct. -/// -/// \param dims The dimension struct. -void ocp_qp_dims_free(void *dims); - -// -ocp_qp_xcond_solver_dims *ocp_qp_xcond_solver_dims_create(ocp_qp_xcond_solver_config *config, int N); -// -ocp_qp_xcond_solver_dims *ocp_qp_xcond_solver_dims_create_from_ocp_qp_dims( - ocp_qp_xcond_solver_config *config, ocp_qp_dims *dims); -// -void ocp_qp_xcond_solver_dims_free(ocp_qp_xcond_solver_dims *dims_); - -void ocp_qp_xcond_solver_dims_set(void *config_, ocp_qp_xcond_solver_dims *dims, - int stage, const char *field, int* value); - - -/// Constructs an input object for the qp. -/// -/// \param dims The dimension struct. -ocp_qp_in *ocp_qp_in_create(ocp_qp_dims *dims); - - -void ocp_qp_in_set(ocp_qp_xcond_solver_config *config, ocp_qp_in *in, - int stage, char *field, void *value); - -/// Destructor of the inputs struct. -/// -/// \param in_ The inputs struct. -void ocp_qp_in_free(void *in_); - - -/// Constructs an outputs object for the qp. -/// -/// \param dims The dimension struct. -ocp_qp_out *ocp_qp_out_create(ocp_qp_dims *dims); - -/// Destructor of the output struct. -/// -/// \param out_ The output struct. -void ocp_qp_out_free(void *out_); - - -/// Getter of output struct -void ocp_qp_out_get(ocp_qp_out *out, const char *field, void *value); - - -/// Constructs an options object for the qp. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -void *ocp_qp_xcond_solver_opts_create(ocp_qp_xcond_solver_config *config, - ocp_qp_xcond_solver_dims *dims); - -/// Destructor of the options struct. -/// -/// \param opts The options struct to destroy. -void ocp_qp_xcond_solver_opts_free(ocp_qp_xcond_solver_opts *opts); - - -/// Setter of the options struct. -/// -/// \param opts The options struct. -void ocp_qp_xcond_solver_opts_set(ocp_qp_xcond_solver_config *config, - ocp_qp_xcond_solver_opts *opts, const char *field, void* value); - -/// TBC Should be private/static? -acados_size_t ocp_qp_calculate_size(ocp_qp_xcond_solver_config *config, ocp_qp_xcond_solver_dims *dims, void *opts_); - - -/// TBC Reserves memory? TBC Should this be private? -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param opts_ The options struct. -/// \param raw_memory Pointer to raw memory to assign to qp solver. -ocp_qp_solver *ocp_qp_assign(ocp_qp_xcond_solver_config *config, ocp_qp_xcond_solver_dims *dims, - void *opts_, void *raw_memory); - -/// Creates a qp solver. Reserves memory. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param opts_ The options struct. -ocp_qp_solver *ocp_qp_create(ocp_qp_xcond_solver_config *config, - ocp_qp_xcond_solver_dims *dims, void *opts_); - - -/// Destroys a qp solver. Frees memory. -/// -/// \param solver The qp solver -void ocp_qp_solver_destroy(ocp_qp_solver *solver); - -void ocp_qp_x_cond_solver_free(ocp_qp_xcond_solver_config *config, - ocp_qp_xcond_solver_dims *dims, void *opts_); - - -/// Solves the qp. -/// -/// \param solver The solver. -/// \param qp_in The inputs struct. -/// \param qp_out The output struct. -int ocp_qp_solve(ocp_qp_solver *solver, ocp_qp_in *qp_in, ocp_qp_out *qp_out); - - -/// Calculates the infinity norm of the residuals. -/// -/// \param dims The dimension struct. -/// \param qp_in The inputs struct. -/// \param qp_out The output struct. -/// \param res Output array for the residuals. -void ocp_qp_inf_norm_residuals(ocp_qp_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, - double *res); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_OCP_QP_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/sim_interface.h b/third_party/acados/include/acados_c/sim_interface.h deleted file mode 100644 index 09a05d6995cf3d..00000000000000 --- a/third_party/acados/include/acados_c/sim_interface.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE.; - */ - - -#ifndef INTERFACES_ACADOS_C_SIM_INTERFACE_H_ -#define INTERFACES_ACADOS_C_SIM_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/sim/sim_common.h" - - - -typedef enum -{ - ERK, - IRK, - GNSF, - LIFTED_IRK, - INVALID_SIM_SOLVER, -} sim_solver_t; - - - -typedef struct -{ - sim_solver_t sim_solver; -} sim_solver_plan_t; - - - -typedef struct -{ - sim_config *config; - void *dims; - void *opts; - void *mem; - void *work; -} sim_solver; - - - -/* config */ -// -ACADOS_SYMBOL_EXPORT sim_config *sim_config_create(sim_solver_plan_t plan); -// -ACADOS_SYMBOL_EXPORT void sim_config_destroy(void *config); - -/* dims */ -// -ACADOS_SYMBOL_EXPORT void *sim_dims_create(void *config_); -// -ACADOS_SYMBOL_EXPORT void sim_dims_destroy(void *dims); -// -ACADOS_SYMBOL_EXPORT void sim_dims_set(sim_config *config, void *dims, const char *field, const int* value); -// -ACADOS_SYMBOL_EXPORT void sim_dims_get(sim_config *config, void *dims, const char *field, int* value); -// -ACADOS_SYMBOL_EXPORT void sim_dims_get_from_attr(sim_config *config, void *dims, const char *field, int *dims_out); - -/* in */ -// -ACADOS_SYMBOL_EXPORT sim_in *sim_in_create(sim_config *config, void *dims); -// -ACADOS_SYMBOL_EXPORT void sim_in_destroy(void *out); -// -ACADOS_SYMBOL_EXPORT int sim_in_set(void *config_, void *dims_, sim_in *in, const char *field, void *value); - - -/* out */ -// -ACADOS_SYMBOL_EXPORT sim_out *sim_out_create(sim_config *config, void *dims); -// -ACADOS_SYMBOL_EXPORT void sim_out_destroy(void *out); -// -ACADOS_SYMBOL_EXPORT int sim_out_get(void *config, void *dims, sim_out *out, const char *field, void *value); - -/* opts */ -// -ACADOS_SYMBOL_EXPORT void *sim_opts_create(sim_config *config, void *dims); -// -ACADOS_SYMBOL_EXPORT void sim_opts_destroy(void *opts); -// -ACADOS_SYMBOL_EXPORT void sim_opts_set(sim_config *config, void *opts, const char *field, void *value); -// -ACADOS_SYMBOL_EXPORT void sim_opts_get(sim_config *config, void *opts, const char *field, void *value); - -/* solver */ -// -ACADOS_SYMBOL_EXPORT acados_size_t sim_calculate_size(sim_config *config, void *dims, void *opts_); -// -ACADOS_SYMBOL_EXPORT sim_solver *sim_assign(sim_config *config, void *dims, void *opts_, void *raw_memory); -// -ACADOS_SYMBOL_EXPORT sim_solver *sim_solver_create(sim_config *config, void *dims, void *opts_); -// -ACADOS_SYMBOL_EXPORT void sim_solver_destroy(void *solver); -// -ACADOS_SYMBOL_EXPORT int sim_solve(sim_solver *solver, sim_in *in, sim_out *out); -// -ACADOS_SYMBOL_EXPORT int sim_precompute(sim_solver *solver, sim_in *in, sim_out *out); -// -ACADOS_SYMBOL_EXPORT int sim_solver_set(sim_solver *solver, const char *field, void *value); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_SIM_INTERFACE_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo.h b/third_party/acados/include/blasfeo/include/blasfeo.h deleted file mode 100644 index c8549181937dee..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo.h +++ /dev/null @@ -1,52 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#include "blasfeo_processor_features.h" -#include "blasfeo_target.h" -#include "blasfeo_block_size.h" -#include "blasfeo_stdlib.h" -#include "blasfeo_common.h" -#include "blasfeo_d_aux.h" -#include "blasfeo_d_aux_ext_dep.h" -#include "blasfeo_d_kernel.h" -#include "blasfeo_d_blas.h" -#include "blasfeo_s_aux.h" -#include "blasfeo_s_aux_ext_dep.h" -#include "blasfeo_s_kernel.h" -#include "blasfeo_s_blas.h" -#include "blasfeo_i_aux_ext_dep.h" -#include "blasfeo_v_aux_ext_dep.h" -#include "blasfeo_timing.h" -#include "blasfeo_memory.h" diff --git a/third_party/acados/include/blasfeo/include/blasfeo_block_size.h b/third_party/acados/include/blasfeo/include/blasfeo_block_size.h deleted file mode 100644 index 5d0907a61cfea2..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_block_size.h +++ /dev/null @@ -1,447 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_BLOCK_SIZE_H_ -#define BLASFEO_BLOCK_SIZE_H_ - - - -#define D_EL_SIZE 8 // double precision -#define S_EL_SIZE 4 // single precision - - - -#if defined( TARGET_X64_INTEL_SKYLAKE_X ) -// common -#define CACHE_LINE_SIZE 64 // data cache size: 64 bytes -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 8-way -#define L2_CACHE_SIZE (256*1024) //(1024*1024) // L2 data cache size: 1 MB ; DTLB1 64*4 kB = 256 kB -#define LLC_CACHE_SIZE (6*1024*1024) //(8*1024*1024) // LLC cache size: 8 MB ; TLB 1536*4 kB = 6 MB -// double -#define D_PS 8 // panel size -#define D_PLD 8 // 4 // GCD of panel length -#define D_M_KERNEL 24 // max kernel size -#define D_N_KERNEL 8 // max kernel size -#define D_KC 128 //256 // 192 -#define D_NC 144 //72 //96 //72 // 120 // 512 -#define D_MC 2400 // 6000 -// single -#define S_PS 16 // panel size -#define S_PLD 4 // GCD of panel length TODO probably 16 when writing assebly -#define S_M_KERNEL 32 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 128 //256 -#define S_NC 128 //144 -#define S_MC 3000 - -#elif defined( TARGET_X64_INTEL_HASWELL ) -// common -#define CACHE_LINE_SIZE 64 // data cache size: 64 bytes -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 8-way -#define L2_CACHE_SIZE (256*1024) // L2 data cache size: 256 kB ; DTLB1 64*4 kB = 256 kB -#define LLC_CACHE_SIZE (6*1024*1024) // LLC cache size: 6 MB ; TLB 1024*4 kB = 4 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 12 // max kernel size -#define D_N_KERNEL 8 // max kernel size -#define D_KC 256 // 192 -#define D_NC 64 //96 //72 // 120 // 512 -#define D_MC 1500 -// single -#define S_PS 8 // panel size -#define S_PLD 4 // 2 // GCD of panel length -#define S_M_KERNEL 24 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 144 -#define S_MC 3000 - -#elif defined( TARGET_X64_INTEL_SANDY_BRIDGE ) -// common -#define CACHE_LINE_SIZE 64 // data cache size: 64 bytes -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 8-way -#define L2_CACHE_SIZE (256*1024) // L2 data cache size: 256 kB ; DTLB1 64*4 kB = 256 kB -#define LLC_CACHE_SIZE (4*1024*1024) // LLC cache size: 4 MB ; TLB 1024*4 kB = 4 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 //320 //256 //320 -#define D_NC 72 //64 //72 //60 // 120 -#define D_MC 1000 // 800 -// single -#define S_PS 8 // panel size -#define S_PLD 4 // 2 // GCD of panel length -#define S_M_KERNEL 16 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 144 -#define S_MC 2000 - -#elif defined( TARGET_X64_INTEL_CORE ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - -#elif defined( TARGET_X64_AMD_BULLDOZER ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_X86_AMD_JAGUAR ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_X86_AMD_BARCELONA ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined(TARGET_ARMV8A_APPLE_M1) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (128*1024) // L1 data cache size (big cores): 64 kB, ?-way ; DTLB1 ? -#define LLC_CACHE_SIZE (12*1024*1024) // LLC (L2) cache size (big cores): 12 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 512 //256 -#define D_NC 128 //256 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 512 -#define S_NC 256 -#define S_MC 6000 - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A76) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (64*1024) // L1 data cache size: 64 kB, 4-way ; DTLB1 48*4 kB = 192 kB -#define LLC_CACHE_SIZE (1*1024*1024) // LLC cache size: 1 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 512 //256 -#define D_NC 128 //256 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 512 -#define S_NC 256 -#define S_MC 6000 - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A73) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 (64?) kB, 4-way, seen as 8-(16-)way ; DTLB1 48*4 kB = 192 kB -#define LLC_CACHE_SIZE (1*1024*1024) // LLC cache size: 1 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 320 -#define D_NC 256 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A57) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 2-way ; DTLB1 32*4 kB = 128 kB -#define LLC_CACHE_SIZE (1*1024*1024) // LLC cache size: 1 MB // 2 MB ??? -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 128 //224 //256 //192 -#define D_NC 72 //40 //36 //48 -#define D_MC (4*192) //512 //488 //600 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A55) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 4-way ; DTLB1 16*4 kB = 64 kB -#define LLC_CACHE_SIZE (512*1024) // LLC cache size: 512 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 12 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 224 -#define D_NC 160 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A53) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 4-way ??? ; DTLB1 10*4 kB = 40 kB -#define LLC_CACHE_SIZE (256*1024) // LLC cache size: 256 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 12 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 160 -#define D_NC 128 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_ARMV7A_ARM_CORTEX_A15 ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_ARMV7A_ARM_CORTEX_A7 ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_ARMV7A_ARM_CORTEX_A9 ) -// common -#define CACHE_LINE_SIZE 32 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_GENERIC ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy - -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#else -#error "Unknown architecture" -#endif - - - -#define D_CACHE_LINE_EL (CACHE_LINE_SIZE/D_EL_SIZE) -#define D_L1_CACHE_EL (L1_CACHE_SIZE/D_EL_SIZE) -#define D_L2_CACHE_EL (L2_CACHE_SIZE/D_EL_SIZE) -#define D_LLC_CACHE_EL (LLC_CACHE_SIZE/D_EL_SIZE) - -#define S_CACHE_LINE_EL (CACHE_LINE_SIZE/S_EL_SIZE) -#define S_L1_CACHE_EL (L1_CACHE_SIZE/S_EL_SIZE) -#define S_L2_CACHE_EL (L2_CACHE_SIZE/S_EL_SIZE) -#define S_LLC_CACHE_EL (LLC_CACHE_SIZE/S_EL_SIZE) - - - -#endif // BLASFEO_BLOCK_SIZE_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_common.h b/third_party/acados/include/blasfeo/include/blasfeo_common.h deleted file mode 100644 index 03b6c36d84b9bd..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_common.h +++ /dev/null @@ -1,274 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_COMMON_H_ -#define BLASFEO_COMMON_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__INTEL_LLVM_COMPILER) -#define ALIGNED(VEC, BYTES) VEC __attribute__ ((aligned ( BYTES ))) -#elif defined (_MSC_VER) -#define ALIGNED(VEC, BYTES) __declspec(align( BYTES )) VEC -#else -#define ALIGNED(VEC, BYTES) VEC -#endif - - - - -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_PANELMAJ) ) | ( defined(LA_REFERENCE) & defined(MF_PANELMAJ) ) - -#include "blasfeo_block_size.h" - -// matrix structure -struct blasfeo_dmat - { - double *mem; // pointer to passed chunk of memory - double *pA; // pointer to a pm*pn array of doubles, the first is aligned to cache line size - double *dA; // pointer to a min(m,n) (or max???) array of doubles - int m; // rows - int n; // cols - int pm; // packed number or rows - int cn; // packed number or cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -struct blasfeo_smat - { - float *mem; // pointer to passed chunk of memory - float *pA; // pointer to a pm*pn array of floats, the first is aligned to cache line size - float *dA; // pointer to a min(m,n) (or max???) array of floats - int m; // rows - int n; // cols - int pm; // packed number or rows - int cn; // packed number or cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -// vector structure -struct blasfeo_dvec - { - double *mem; // pointer to passed chunk of memory - double *pa; // pointer to a pm array of doubles, the first is aligned to cache line size - int m; // size - int pm; // packed size - int memsize; // size of needed memory - }; - -struct blasfeo_svec - { - float *mem; // pointer to passed chunk of memory - float *pa; // pointer to a pm array of floats, the first is aligned to cache line size - int m; // size - int pm; // packed size - int memsize; // size of needed memory - }; - -#define BLASFEO_DMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&(D_PS-1)))*(sA)->cn+(aj)*D_PS+((ai)&(D_PS-1))]) -#define BLASFEO_SMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&(S_PS-1)))*(sA)->cn+(aj)*S_PS+((ai)&(S_PS-1))]) -#define BLASFEO_DVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_SVECEL(sa,ai) ((sa)->pa[ai]) - -#elif ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) | ( defined(LA_REFERENCE) & defined(MF_COLMAJ) ) | defined(LA_EXTERNAL_BLAS_WRAPPER) - -// matrix structure -struct blasfeo_dmat - { - double *mem; // pointer to passed chunk of memory - double *pA; // pointer to a m*n array of doubles - double *dA; // pointer to a min(m,n) (or max???) array of doubles - int m; // rows - int n; // cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -struct blasfeo_smat - { - float *mem; // pointer to passed chunk of memory - float *pA; // pointer to a m*n array of floats - float *dA; // pointer to a min(m,n) (or max???) array of floats - int m; // rows - int n; // cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -// vector structure -struct blasfeo_dvec - { - double *mem; // pointer to passed chunk of memory - double *pa; // pointer to a m array of doubles, the first is aligned to cache line size - int m; // size - int memsize; // size of needed memory - }; - -struct blasfeo_svec - { - float *mem; // pointer to passed chunk of memory - float *pa; // pointer to a m array of floats, the first is aligned to cache line size - int m; // size - int memsize; // size of needed memory - }; - -#define BLASFEO_DMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) -#define BLASFEO_SMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) -#define BLASFEO_DVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_SVECEL(sa,ai) ((sa)->pa[ai]) - -#else - -#error : wrong LA or MF choice - -#endif - - - -// Explicitly panel-major matrix structure -struct blasfeo_pm_dmat - { - double *mem; // pointer to passed chunk of memory - double *pA; // pointer to a pm*pn array of doubles, the first is aligned to cache line size - double *dA; // pointer to a min(m,n) (or max???) array of doubles - int m; // rows - int n; // cols - int pm; // packed number or rows - int cn; // packed number or cols - int use_dA; // flag to tell if dA can be used - int ps; // panel size - int memsize; // size of needed memory - }; - -struct blasfeo_pm_smat - { - float *mem; // pointer to passed chunk of memory - float *pA; // pointer to a pm*pn array of floats, the first is aligned to cache line size - float *dA; // pointer to a min(m,n) (or max???) array of floats - int m; // rows - int n; // cols - int pm; // packed number or rows - int cn; // packed number or cols - int use_dA; // flag to tell if dA can be used - int ps; // panel size - int memsize; // size of needed memory - }; - -struct blasfeo_pm_dvec - { - double *mem; // pointer to passed chunk of memory - double *pa; // pointer to a pm array of doubles, the first is aligned to cache line size - int m; // size - int pm; // packed size - int memsize; // size of needed memory - }; - -struct blasfeo_pm_svec - { - float *mem; // pointer to passed chunk of memory - float *pa; // pointer to a pm array of floats, the first is aligned to cache line size - int m; // size - int pm; // packed size - int memsize; // size of needed memory - }; - -// Explicitly column-major matrix structure -struct blasfeo_cm_dmat - { - double *mem; // pointer to passed chunk of memory - double *pA; // pointer to a m*n array of doubles - double *dA; // pointer to a min(m,n) (or max???) array of doubles - int m; // rows - int n; // cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -struct blasfeo_cm_smat - { - float *mem; // pointer to passed chunk of memory - float *pA; // pointer to a m*n array of floats - float *dA; // pointer to a min(m,n) (or max???) array of floats - int m; // rows - int n; // cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -struct blasfeo_cm_dvec - { - double *mem; // pointer to passed chunk of memory - double *pa; // pointer to a m array of doubles, the first is aligned to cache line size - int m; // size - int memsize; // size of needed memory - }; - -struct blasfeo_cm_svec - { - float *mem; // pointer to passed chunk of memory - float *pa; // pointer to a m array of floats, the first is aligned to cache line size - int m; // size - int memsize; // size of needed memory - }; - - -#define BLASFEO_PM_DMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&((sA)->ps-1)))*(sA)->cn+(aj)*((sA)->ps)+((ai)&((sA)->ps-1))]) -#define BLASFEO_PM_SMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&((sA)->ps-1)))*(sA)->cn+(aj)*((sA)->ps)+((ai)&((sA)->ps-1))]) -#define BLASFEO_PM_DVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_PM_SVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_CM_DMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) -#define BLASFEO_CM_SMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) -#define BLASFEO_CM_DVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_CM_SVECEL(sa,ai) ((sa)->pa[ai]) - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_COMMON_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h deleted file mode 100644 index a6d6119c6c1446..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h +++ /dev/null @@ -1,255 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * auxiliary algebra operations header - * - * include/blasfeo_aux_lib*.h - * - */ - -#ifndef BLASFEO_D_AUX_H_ -#define BLASFEO_D_AUX_H_ - - - -#include - -#include "blasfeo_common.h" -#include "blasfeo_d_aux_old.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - -// --- memory size calculations -// -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_memsize_dmat(int m, int n); -// returns the memory size (in bytes) needed for the diagonal of a dmat -size_t blasfeo_memsize_diag_dmat(int m, int n); -// returns the memory size (in bytes) needed for a dvec -size_t blasfeo_memsize_dvec(int m); - -// --- creation -// -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_create_dmat(int m, int n, struct blasfeo_dmat *sA, void *memory); -// create a strvec for a vector of size m by using memory passed by a pointer (pointer is not updated) -void blasfeo_create_dvec(int m, struct blasfeo_dvec *sA, void *memory); - -// --- packing -// pack the column-major matrix A into the matrix struct B -void blasfeo_pack_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the lower-triangular column-major matrix A into the matrix struct B -void blasfeo_pack_l_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the upper-triangular column-major matrix A into the matrix struct B -void blasfeo_pack_u_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// transpose and pack the column-major matrix A into the matrix struct B -void blasfeo_pack_tran_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the vector x into the vector structure y -void blasfeo_pack_dvec(int m, double *x, int xi, struct blasfeo_dvec *sy, int yi); -// unpack the matrix structure A into the column-major matrix B -void blasfeo_unpack_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *B, int ldb); -// transpose and unpack the matrix structure A into the column-major matrix B -void blasfeo_unpack_tran_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *B, int ldb); -// pack the vector structure x into the vector y -void blasfeo_unpack_dvec(int m, struct blasfeo_dvec *sx, int xi, double *y, int yi); - -// --- cast -// -//void d_cast_mat2strmat(double *A, struct blasfeo_dmat *sA); // TODO -//void d_cast_diag_mat2strmat(double *dA, struct blasfeo_dmat *sA); // TODO -//void d_cast_vec2vecmat(double *a, struct blasfeo_dvec *sx); // TODO - - -// ge -// --- insert/extract -// -// sA[ai, aj] <= a -void blasfeo_dgein1(double a, struct blasfeo_dmat *sA, int ai, int aj); -// <= sA[ai, aj] -double blasfeo_dgeex1(struct blasfeo_dmat *sA, int ai, int aj); - -// --- set -// A <= alpha -void blasfeo_dgese(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); - -// --- copy / scale -// B <= A -void blasfeo_dgecp(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// A <= alpha*A -void blasfeo_dgesc(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// B <= alpha*A -void blasfeo_dgecpsc(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A, A lower triangular -void blasfeo_dtrcp_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -void blasfeo_dtrcpsc_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -void blasfeo_dtrsc_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj); - -// --- sum -// B <= B + alpha*A -void blasfeo_dgead(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// y <= y + alpha*x -void blasfeo_dvecad(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); - -// --- traspositions -// B <= A' -void blasfeo_dgetr(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A', A lower triangular -void blasfeo_dtrtr_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A', A upper triangular -void blasfeo_dtrtr_u(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); - -// dia -// diag(A) += alpha -void blasfeo_ddiare(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A) <= alpha*x -void blasfeo_ddiain(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A)[idx] <= alpha*x -void blasfeo_ddiain_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// x <= diag(A) -void blasfeo_ddiaex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// x <= diag(A)[idx] -void blasfeo_ddiaex_sp(int kmax, double alpha, int *idx, struct blasfeo_dmat *sD, int di, int dj, struct blasfeo_dvec *sx, int xi); -// diag(A) += alpha*x -void blasfeo_ddiaad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A)[idx] += alpha*x -void blasfeo_ddiaad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// diag(A)[idx] = y + alpha*x -void blasfeo_ddiaadin_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, int *idx, struct blasfeo_dmat *sD, int di, int dj); - -// row -void blasfeo_drowin(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_drowex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -void blasfeo_drowad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_drowad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_drowsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -void blasfeo_drowpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -void blasfeo_drowpei(int kmax, int *ipiv, struct blasfeo_dmat *sA); - -// col -void blasfeo_dcolex(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -void blasfeo_dcolin(int kmax, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_dcolad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_dcolsc(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_dcolsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -void blasfeo_dcolpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -void blasfeo_dcolpei(int kmax, int *ipiv, struct blasfeo_dmat *sA); - -// vec -// a <= alpha -void blasfeo_dvecse(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// sx[xi] <= a -void blasfeo_dvecin1(double a, struct blasfeo_dvec *sx, int xi); -// <= sx[xi] -double blasfeo_dvecex1(struct blasfeo_dvec *sx, int xi); -// y <= x -void blasfeo_dveccp(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// x <= alpha*x -void blasfeo_dvecsc(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// y <= alpha*x -void blasfeo_dveccpsc(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// z[idx] += alpha * x -void blasfeo_dvecad_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -// z[idx] <= alpha * x -void blasfeo_dvecin_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -// z <= alpha * x[idx] -void blasfeo_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z += alpha * x[idx] -void blasfeo_dvecexad_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); - -void blasfeo_dveccl(int m, - struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, - struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi); - -void blasfeo_dveccl_mask(int m, - struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, - struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi, - struct blasfeo_dvec *sm, int mi); - -void blasfeo_dvecze(int m, struct blasfeo_dvec *sm, int mi, struct blasfeo_dvec *sv, int vi, struct blasfeo_dvec *se, int ei); -void blasfeo_dvecnrm_inf(int m, struct blasfeo_dvec *sx, int xi, double *ptr_norm); -void blasfeo_dvecnrm_2(int m, struct blasfeo_dvec *sx, int xi, double *ptr_norm); -void blasfeo_dvecpe(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); -void blasfeo_dvecpei(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); - - - - - -/* -* Explicitly panel-major matrix format -*/ - -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_pm_memsize_dmat(int ps, int m, int n); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_pm_create_dmat(int ps, int m, int n, struct blasfeo_pm_dmat *sA, void *memory); -// print -void blasfeo_pm_print_dmat(int m, int n, struct blasfeo_pm_dmat *sA, int ai, int aj); - - - -/* -* Explicitly panel-major matrix format -*/ - -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_cm_memsize_dmat(int m, int n); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_cm_create_dmat(int m, int n, struct blasfeo_pm_dmat *sA, void *memory); - - - -// -// BLAS API helper functions -// - -#if ( defined(BLAS_API) & defined(MF_PANELMAJ) ) -// aux -void blasfeo_cm_dgetr(int m, int n, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj); -#endif - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep.h deleted file mode 100644 index bee9e986f15d8f..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep.h +++ /dev/null @@ -1,145 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * auxiliary algebra operation external dependancies header - * - * include/blasfeo_d_aux_ext_dep.h - * - * - dynamic memory allocation - * - print - * - */ - -#ifndef BLASFEO_D_AUX_EXT_DEP_H_ -#define BLASFEO_D_AUX_EXT_DEP_H_ - - - -#include - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef EXT_DEP - -/* column-major matrices */ - -// dynamically allocate row*col doubles of memory and set accordingly a pointer to double; set allocated memory to zero -void d_zeros(double **pA, int row, int col); -// dynamically allocate row*col doubles of memory aligned to 64-byte boundaries and set accordingly a pointer to double; set allocated memory to zero -void d_zeros_align(double **pA, int row, int col); -// dynamically allocate size bytes of memory aligned to 64-byte boundaries and set accordingly a pointer to double; set allocated memory to zero -void d_zeros_align_bytes(double **pA, int size); -// free the memory allocated by d_zeros -void d_free(double *pA); -// free the memory allocated by d_zeros_align or d_zeros_align_bytes -void d_free_align(double *pA); -// print a column-major matrix -void d_print_mat(int m, int n, double *A, int lda); -// print the transposed of a column-major matrix -void d_print_tran_mat(int row, int col, double *A, int lda); -// print to file a column-major matrix -void d_print_to_file_mat(FILE *file, int row, int col, double *A, int lda); -// print to file a column-major matrix in exponential format -void d_print_to_file_exp_mat(FILE *file, int row, int col, double *A, int lda); -// print to string a column-major matrix -void d_print_to_string_mat(char **buf_out, int row, int col, double *A, int lda); -// print to file the transposed of a column-major matrix -void d_print_tran_to_file_mat(FILE *file, int row, int col, double *A, int lda); -// print to file the transposed of a column-major matrix in exponential format -void d_print_tran_to_file_exp_mat(FILE *file, int row, int col, double *A, int lda); -// print in exponential notation a column-major matrix -void d_print_exp_mat(int m, int n, double *A, int lda); -// print in exponential notation the transposed of a column-major matrix -void d_print_exp_tran_mat(int row, int col, double *A, int lda); - -/* strmat and strvec */ - -// create a strmat for a matrix of size m*n by dynamically allocating memory -void blasfeo_allocate_dmat(int m, int n, struct blasfeo_dmat *sA); -// create a strvec for a vector of size m by dynamically allocating memory -void blasfeo_allocate_dvec(int m, struct blasfeo_dvec *sa); -// free the memory allocated by blasfeo_allocate_dmat -void blasfeo_free_dmat(struct blasfeo_dmat *sA); -// free the memory allocated by blasfeo_allocate_dvec -void blasfeo_free_dvec(struct blasfeo_dvec *sa); -// print a strmat -void blasfeo_print_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print in exponential notation a strmat -void blasfeo_print_exp_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print to file a strmat -void blasfeo_print_to_file_dmat(FILE *file, int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print to file a strmat in exponential format -void blasfeo_print_to_file_exp_dmat(FILE *file, int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print to string a strmat -void blasfeo_print_to_string_dmat(char **buf_out, int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print the transposed of a strmat -void blasfeo_print_tran_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print a strvec -void blasfeo_print_dvec(int m, struct blasfeo_dvec *sa, int ai); -// print in exponential notation a strvec -void blasfeo_print_exp_dvec(int m, struct blasfeo_dvec *sa, int ai); -// print to file a strvec -void blasfeo_print_to_file_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -// print to string a strvec -void blasfeo_print_to_string_dvec(char **buf_out, int m, struct blasfeo_dvec *sa, int ai); -// print the transposed of a strvec -void blasfeo_print_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); -// print in exponential notation the transposed of a strvec -void blasfeo_print_exp_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); -// print to file the transposed of a strvec -void blasfeo_print_to_file_tran_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -// print to string the transposed of a strvec -void blasfeo_print_to_string_tran_dvec(char **buf_out, int m, struct blasfeo_dvec *sa, int ai); - -#endif // EXT_DEP - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_EXT_DEP_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep_ref.h deleted file mode 100644 index 81b811f0325039..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep_ref.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * auxiliary algebra operation external dependancies header - * - * include/blasfeo_d_aux_ext_dep.h - * - * - dynamic memory allocation - * - print - * - */ - -#ifndef BLASFEO_D_AUX_EXT_DEP_REF_H_ -#define BLASFEO_D_AUX_EXT_DEP_REF_H_ - - -#include - -#include "blasfeo_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// expose reference BLASFEO for testing -// see blasfeo_d_aux_exp_dep.h for help - -void blasfeo_print_dmat_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_allocate_dmat_ref(int m, int n, struct blasfeo_dmat_ref *sA); -void blasfeo_allocate_dvec_ref(int m, struct blasfeo_dvec_ref *sa); -void blasfeo_free_dmat_ref(struct blasfeo_dmat_ref *sA); -void blasfeo_free_dvec_ref(struct blasfeo_dvec_ref *sa); -void blasfeo_print_dmat_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_exp_dmat_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_to_file_dmat_ref(FILE *file, int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_to_file_exp_dmat_ref(FILE *file, int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_to_string_dmat_ref(char **buf_out, int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_dvec(int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_exp_dvec(int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_to_file_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_to_string_dvec(char **buf_out, int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_exp_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_to_file_tran_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_to_string_tran_dvec(char **buf_out, int m, struct blasfeo_dvec *sa, int ai); - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_EXT_DEP_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_old.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_old.h deleted file mode 100644 index 3a1847a6a0191d..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_old.h +++ /dev/null @@ -1,75 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * ----------- TOMOVE - * - * expecting column major matrices - * - */ - -#include "blasfeo_common.h" - - -void dtrcp_l_lib(int m, double alpha, int offsetA, double *A, int sda, int offsetB, double *B, int sdb); -void dgead_lib(int m, int n, double alpha, int offsetA, double *A, int sda, int offsetB, double *B, int sdb); -// TODO remove ??? -void ddiain_sqrt_lib(int kmax, double *x, int offset, double *pD, int sdd); -// TODO ddiaad1 -void ddiareg_lib(int kmax, double reg, int offset, double *pD, int sdd); - - -void dgetr_lib(int m, int n, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -void dtrtr_l_lib(int m, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -void dtrtr_u_lib(int m, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -void ddiaex_lib(int kmax, double alpha, int offset, double *pD, int sdd, double *x); -void ddiaad_lib(int kmax, double alpha, double *x, int offset, double *pD, int sdd); -void ddiain_libsp(int kmax, int *idx, double alpha, double *x, double *pD, int sdd); -void ddiaex_libsp(int kmax, int *idx, double alpha, double *pD, int sdd, double *x); -void ddiaad_libsp(int kmax, int *idx, double alpha, double *x, double *pD, int sdd); -void ddiaadin_libsp(int kmax, int *idx, double alpha, double *x, double *y, double *pD, int sdd); -void drowin_lib(int kmax, double alpha, double *x, double *pD); -void drowex_lib(int kmax, double alpha, double *pD, double *x); -void drowad_lib(int kmax, double alpha, double *x, double *pD); -void drowin_libsp(int kmax, double alpha, int *idx, double *x, double *pD); -void drowad_libsp(int kmax, int *idx, double alpha, double *x, double *pD); -void drowadin_libsp(int kmax, int *idx, double alpha, double *x, double *y, double *pD); -void dcolin_lib(int kmax, double *x, int offset, double *pD, int sdd); -void dcolad_lib(int kmax, double alpha, double *x, int offset, double *pD, int sdd); -void dcolin_libsp(int kmax, int *idx, double *x, double *pD, int sdd); -void dcolad_libsp(int kmax, double alpha, int *idx, double *x, double *pD, int sdd); -void dcolsw_lib(int kmax, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -void dvecin_libsp(int kmax, int *idx, double *x, double *y); -void dvecad_libsp(int kmax, int *idx, double alpha, double *x, double *y); diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h deleted file mode 100644 index 1e007fa89e4bd6..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h +++ /dev/null @@ -1,208 +0,0 @@ - -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_AUX_REF_H_ -#define BLASFEO_D_AUX_REF_H_ - - - -#include - -#include "blasfeo_common.h" -#include "blasfeo_d_aux_old.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - -// --- memory calculations -// -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_ref_memsize_dmat(int m, int n); -// returns the memory size (in bytes) needed for the diagonal of a dmat -size_t blasfeo_ref_memsize_diag_dmat(int m, int n); -// returns the memory size (in bytes) needed for a dvec -size_t blasfeo_ref_memsize_dvec(int m); - -// --- creation -// -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_ref_create_dmat(int m, int n, struct blasfeo_dmat *sA, void *memory); -// create a strvec for a vector of size m by using memory passed by a pointer (pointer is not updated) -void blasfeo_ref_create_dvec(int m, struct blasfeo_dvec *sA, void *memory); - -// --- packing -// pack the column-major matrix A into the matrix struct B -void blasfeo_ref_pack_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the lower-triangular column-major matrix A into the matrix struct B -void blasfeo_ref_pack_l_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the upper-triangular column-major matrix A into the matrix struct B -void blasfeo_ref_pack_u_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// transpose and pack the column-major matrix A into the matrix struct B -void blasfeo_ref_pack_tran_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the vector x into the vector structure y -void blasfeo_ref_pack_dvec(int m, double *x, int xi, struct blasfeo_dvec *sy, int yi); -// unpack the matrix structure A into the column-major matrix B -void blasfeo_ref_unpack_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *B, int ldb); -// transpose and unpack the matrix structure A into the column-major matrix B -void blasfeo_ref_unpack_tran_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *B, int ldb); -// pack the vector structure x into the vector y -void blasfeo_ref_unpack_dvec(int m, struct blasfeo_dvec *sx, int xi, double *y, int yi); - -// --- cast -// -void ref_d_cast_mat2strmat(double *A, struct blasfeo_dmat *sA); // TODO -void ref_d_cast_diag_mat2strmat(double *dA, struct blasfeo_dmat *sA); // TODO -void ref_d_cast_vec2vecmat(double *a, struct blasfeo_dvec *sx); // TODO - - -// ge -// --- insert/extract -// -// sA[ai, aj] <= a -void blasfeo_ref_dgein1(double a, struct blasfeo_dmat *sA, int ai, int aj); -// <= sA[ai, aj] -double blasfeo_ref_dgeex1(struct blasfeo_dmat *sA, int ai, int aj); - -// --- set -// A <= alpha -void blasfeo_ref_dgese(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); - -// --- copy / scale -// B <= A -void blasfeo_ref_dgecp(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// A <= alpha*A -void blasfeo_ref_dgesc(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// B <= alpha*A -void blasfeo_ref_dgecpsc(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A, A lower triangular -void blasfeo_ref_dtrcp_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -void blasfeo_ref_dtrcpsc_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -void blasfeo_ref_dtrsc_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj); - -// --- sum -// B <= B + alpha*A -void blasfeo_ref_dgead(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int yi, int cj); -// y <= y + alpha*x -void blasfeo_ref_dvecad(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); - -// --- traspositions -// B <= A' -void blasfeo_ref_dgetr(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A', A lower triangular -void blasfeo_ref_dtrtr_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A', A upper triangular -void blasfeo_ref_dtrtr_u(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); - -// dia -// diag(A) += alpha -void blasfeo_ref_ddiare(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A) <= alpha*x -void blasfeo_ref_ddiain(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A)[idx] <= alpha*x -void blasfeo_ref_ddiain_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// x <= diag(A) -void blasfeo_ref_ddiaex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// x <= diag(A)[idx] -void blasfeo_ref_ddiaex_sp(int kmax, double alpha, int *idx, struct blasfeo_dmat *sD, int di, int dj, struct blasfeo_dvec *sx, int xi); -// diag(A) += alpha*x -void blasfeo_ref_ddiaad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A)[idx] += alpha*x -void blasfeo_ref_ddiaad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// diag(A)[idx] = y + alpha*x -void blasfeo_ref_ddiaadin_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, int *idx, struct blasfeo_dmat *sD, int di, int dj); - -// row -void blasfeo_ref_drowin(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_drowex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -void blasfeo_ref_drowad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_drowad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_ref_drowsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -void blasfeo_ref_drowpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -void blasfeo_ref_drowpei(int kmax, int *ipiv, struct blasfeo_dmat *sA); - -// col -void blasfeo_ref_dcolex(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -void blasfeo_ref_dcolin(int kmax, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_dcolad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_dcolsc(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_dcolsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -void blasfeo_ref_dcolpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -void blasfeo_ref_dcolpei(int kmax, int *ipiv, struct blasfeo_dmat *sA); - -// vec -// a <= alpha -void blasfeo_ref_dvecse(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// sx[xi] <= a -void blasfeo_ref_dvecin1(double a, struct blasfeo_dvec *sx, int xi); -// <= sx[xi] -double blasfeo_ref_dvecex1(struct blasfeo_dvec *sx, int xi); -// y <= x -void blasfeo_ref_dveccp(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// x <= alpha*x -void blasfeo_ref_dvecsc(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// y <= alpha*x -void blasfeo_ref_dveccpsc(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -void blasfeo_ref_dvecad_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -void blasfeo_ref_dvecin_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -void blasfeo_ref_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int x, struct blasfeo_dvec *sz, int zi); -// z += alpha * x[idx] -void blasfeo_ref_dvecexad_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); - -void blasfeo_ref_dveccl(int m, - struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, - struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi); - -void blasfeo_ref_dveccl_mask(int m, - struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, - struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi, - struct blasfeo_dvec *sm, int mi); - -void blasfeo_ref_dvecze(int m, struct blasfeo_dvec *sm, int mi, struct blasfeo_dvec *sv, int vi, struct blasfeo_dvec *se, int ei); -void blasfeo_ref_dvecnrm_inf(int m, struct blasfeo_dvec *sx, int xi, double *ptr_norm); -void blasfeo_ref_dvecpe(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); -void blasfeo_ref_dvecpei(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_test.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_test.h deleted file mode 100644 index 1c61635f3ffbfa..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_test.h +++ /dev/null @@ -1,226 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * auxiliary algebra operations header - * - * include/blasfeo_aux_lib*.h - * - */ - -#ifndef BLASFEO_D_AUX_TEST_H_ -#define BLASFEO_D_AUX_TEST_H_ - -#include "blasfeo_common.h" - - -#ifdef __cplusplus -extern "C" { -#endif - -// --- memory calculations -int test_blasfeo_memsize_dmat(int m, int n); -int test_blasfeo_memsize_diag_dmat(int m, int n); -int test_blasfeo_memsize_dvec(int m); - -// --- creation -void test_blasfeo_create_dmat(int m, int n, struct blasfeo_dmat *sA, void *memory); -void test_blasfeo_create_dvec(int m, struct blasfeo_dvec *sA, void *memory); - -// --- conversion -void test_blasfeo_pack_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_pack_dvec(int m, double *x, int xi, struct blasfeo_dvec *sa, int ai); -void test_blasfeo_pack_tran_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_unpack_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *A, int lda); -void test_blasfeo_unpack_dvec(int m, struct blasfeo_dvec *sa, int ai, double *x, int xi); -void test_blasfeo_unpack_tran_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *A, int lda); - -// --- cast -void test_d_cast_mat2strmat(double *A, struct blasfeo_dmat *sA); -void test_d_cast_diag_mat2strmat(double *dA, struct blasfeo_dmat *sA); -void test_d_cast_vec2vecmat(double *a, struct blasfeo_dvec *sa); - -// ------ copy / scale - -// B <= A -void test_blasfeo_dgecp(int m, int n, - struct blasfeo_dmat *sA, int ai, int aj, - struct blasfeo_dmat *sB, int bi, int bj); - -// A <= alpha*A -void test_blasfeo_dgesc(int m, int n, - double alpha, - struct blasfeo_dmat *sA, int ai, int aj); - -// B <= alpha*A -void test_blasfeo_dgecpsc(int m, int n, - double alpha, - struct blasfeo_dmat *sA, int ai, int aj, - struct blasfeo_dmat *sB, int bi, int bj); - -// // --- insert/extract -// // -// // <= sA[ai, aj] -// void test_blasfeo_dgein1(double a, struct blasfeo_dmat *sA, int ai, int aj); -// // <= sA[ai, aj] -// double blasfeo_dgeex1(struct blasfeo_dmat *sA, int ai, int aj); -// // sx[xi] <= a -// void test_blasfeo_dvecin1(double a, struct blasfeo_dvec *sx, int xi); -// // <= sx[xi] -// double blasfeo_dvecex1(struct blasfeo_dvec *sx, int xi); -// // A <= alpha - -// // --- set -// void test_blasfeo_dgese(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// // a <= alpha -// void test_blasfeo_dvecse(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// // B <= A - - -// // --- vector -// // y <= x -// void test_blasfeo_dveccp(int m, struct blasfeo_dvec *sa, int ai, struct blasfeo_dvec *sc, int ci); -// // x <= alpha*x -// void test_blasfeo_dvecsc(int m, double alpha, struct blasfeo_dvec *sa, int ai); -// // TODO -// // x <= alpha*x -// void test_blasfeo_dveccpsc(int m, double alpha, struct blasfeo_dvec *sa, int ai, struct blasfeo_dvec *sc, int ci); - - -// // B <= A, A lower triangular -// void test_blasfeo_dtrcp_l(int m, -// struct blasfeo_dmat *sA, int ai, int aj, -// struct blasfeo_dmat *sB, int bi, int bj); - -// void test_blasfeo_dtrcpsc_l(int m, double alpha, -// struct blasfeo_dmat *sA, int ai, int aj, -// struct blasfeo_dmat *sB, int bi, int bj); - -// void test_blasfeo_dtrsc_l(int m, double alpha, -// struct blasfeo_dmat *sA, int ai, int aj); - - -// // B <= B + alpha*A -// void test_blasfeo_dgead(int m, int n, double alpha, -// struct blasfeo_dmat *sA, int ai, int aj, -// struct blasfeo_dmat *sC, int ci, int cj); - -// // y <= y + alpha*x -// void test_blasfeo_dvecad(int m, double alpha, -// struct blasfeo_dvec *sa, int ai, -// struct blasfeo_dvec *sc, int ci); - -// // --- traspositions -// void test_dgetr_lib(int m, int n, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -// void test_blasfeo_dgetr(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_dtrtr_l_lib(int m, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -// void test_blasfeo_dtrtr_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_dtrtr_u_lib(int m, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -// void test_blasfeo_dtrtr_u(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_blasfeo_ddiare(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// void test_blasfeo_ddiain(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_ddiaex_lib(int kmax, double alpha, int offset, double *pD, int sdd, double *x); -// void test_ddiaad_lib(int kmax, double alpha, double *x, int offset, double *pD, int sdd); -// void test_ddiain_libsp(int kmax, int *idx, double alpha, double *x, double *pD, int sdd); -// void test_blasfeo_ddiain_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// void test_ddiaex_libsp(int kmax, int *idx, double alpha, double *pD, int sdd, double *x); -// void test_blasfeo_ddiaex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// void test_blasfeo_ddiaex_sp(int kmax, double alpha, int *idx, struct blasfeo_dmat *sD, int di, int dj, struct blasfeo_dvec *sx, int xi); -// void test_blasfeo_ddiaad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_ddiaad_libsp(int kmax, int *idx, double alpha, double *x, double *pD, int sdd); -// void test_blasfeo_ddiaad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// void test_ddiaadin_libsp(int kmax, int *idx, double alpha, double *x, double *y, double *pD, int sdd); -// void test_blasfeo_ddiaadin_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// void test_drowin_lib(int kmax, double alpha, double *x, double *pD); -// void test_blasfeo_drowin(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_drowex_lib(int kmax, double alpha, double *pD, double *x); -// void test_blasfeo_drowex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// void test_drowad_lib(int kmax, double alpha, double *x, double *pD); -// void test_blasfeo_drowad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_drowin_libsp(int kmax, double alpha, int *idx, double *x, double *pD); -// void test_drowad_libsp(int kmax, int *idx, double alpha, double *x, double *pD); -// void test_blasfeo_drowad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// void test_drowadin_libsp(int kmax, int *idx, double alpha, double *x, double *y, double *pD); -// void test_drowsw_lib(int kmax, double *pA, double *pC); -// void test_blasfeo_drowsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_blasfeo_drowpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -// void test_blasfeo_dcolex(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// void test_dcolin_lib(int kmax, double *x, int offset, double *pD, int sdd); -// void test_blasfeo_dcolin(int kmax, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_dcolad_lib(int kmax, double alpha, double *x, int offset, double *pD, int sdd); -// void test_dcolin_libsp(int kmax, int *idx, double *x, double *pD, int sdd); -// void test_dcolad_libsp(int kmax, double alpha, int *idx, double *x, double *pD, int sdd); -// void test_dcolsw_lib(int kmax, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -// void test_blasfeo_dcolsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_blasfeo_dcolpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -// void test_dvecin_libsp(int kmax, int *idx, double *x, double *y); -// void test_dvecad_libsp(int kmax, int *idx, double alpha, double *x, double *y); -// void test_blasfeo_dvecad_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -// void test_blasfeo_dvecin_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -// void test_blasfeo_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int x, struct blasfeo_dvec *sz, int zi); -// void test_blasfeo_dveccl(int m, struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi); -// void test_blasfeo_dveccl_mask(int m, struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi, struct blasfeo_dvec *sm, int mi); -// void test_blasfeo_dvecze(int m, struct blasfeo_dvec *sm, int mi, struct blasfeo_dvec *sv, int vi, struct blasfeo_dvec *se, int ei); -// void test_blasfeo_dvecnrm_inf(int m, struct blasfeo_dvec *sx, int xi, double *ptr_norm); -// void test_blasfeo_dvecpe(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); -// void test_blasfeo_dvecpei(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); - -// ext_dep - -void test_blasfeo_allocate_dmat(int m, int n, struct blasfeo_dmat *sA); -void test_blasfeo_allocate_dvec(int m, struct blasfeo_dvec *sa); - -void test_blasfeo_free_dmat(struct blasfeo_dmat *sA); -void test_blasfeo_free_dvec(struct blasfeo_dvec *sa); - -void test_blasfeo_print_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_print_dvec(int m, struct blasfeo_dvec *sa, int ai); -void test_blasfeo_print_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); - -void test_blasfeo_print_to_file_dmat(FILE *file, int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_print_to_file_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -void test_blasfeo_print_to_file_tran_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); - -void test_blasfeo_print_exp_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_print_exp_dvec(int m, struct blasfeo_dvec *sa, int ai); -void test_blasfeo_print_exp_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_TEST_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blas.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blas.h deleted file mode 100644 index ea8d00673128bd..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blas.h +++ /dev/null @@ -1,46 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLAS_H_ -#define BLASFEO_D_BLAS_H_ - - - -#include "blasfeo_d_blasfeo_api.h" -#include "blasfeo_d_blas_api.h" - - - -#endif // BLASFEO_D_BLAS_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h deleted file mode 100644 index 2eab1e40949c22..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h +++ /dev/null @@ -1,281 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef BLASFEO_D_BLAS_API_H_ -#define BLASFEO_D_BLAS_API_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef BLAS_API -#ifdef CBLAS_API -#ifndef BLASFEO_CBLAS_ENUM -#define BLASFEO_CBLAS_ENUM -#ifdef FORTRAN_BLAS_API -#ifndef CBLAS_H -enum CBLAS_LAYOUT {CblasRowMajor=101, CblasColMajor=102}; -enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; -enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; -enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; -enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; -#define CBLAS_ORDER CBLAS_LAYOUT /* this for backward compatibility with CBLAS_ORDER */ -#endif // CBLAS_H -#else // FORTRAN_BLAS_API -enum BLASFEO_CBLAS_LAYOUT {BlasfeoCblasRowMajor=101, BlasfeoCblasColMajor=102}; -enum BLASFEO_CBLAS_TRANSPOSE {BlasfeoCblasNoTrans=111, BlasfeoCblasTrans=112, BlasfeoCblasConjTrans=113}; -enum BLASFEO_CBLAS_UPLO {BlasfeoCblasUpper=121, BlasfeoCblasLower=122}; -enum BLASFEO_CBLAS_DIAG {BlasfeoCblasNonUnit=131, BlasfeoCblasUnit=132}; -enum BLASFEO_CBLAS_SIDE {BlasfeoCblasLeft=141, BlasfeoCblasRight=142}; -#define BLASFEO_CBLAS_ORDER BLASFEO_CBLAS_LAYOUT /* this for backward compatibility with BLASFEO_CBLAS_ORDER */ -#endif // FORTRAN_BLAS_API -#endif // BLASFEO_CBLAS_ENUM -#endif // CBLAS_API -#endif // BLAS_API - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef BLAS_API - - - -#ifdef FORTRAN_BLAS_API - - - -// BLAS 1 -// -void daxpy_(int *n, double *alpha, double *x, int *incx, double *y, int *incy); -// -void dcopy_(int *n, double *x, int *incx, double *y, int *incy); -// -double ddot_(int *n, double *x, int *incx, double *y, int *incy); - -// BLAS 2 -// -void dgemv_(char *tran, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -// -void dsymv_(char *uplo, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -// -void dger_(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *A, int *lda); - -// BLAS 3 -// -void dgemm_(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); -// -void dsyrk_(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); -// -void dtrmm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -// -void dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -// -void dsyr2k_(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); - - - -// LAPACK -// -void dgesv_(int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); -// -void dgetrf_(int *m, int *n, double *A, int *lda, int *ipiv, int *info); -// -void dgetrf_np_(int *m, int *n, double *A, int *lda, int *info); -// -void dgetrs_(char *trans, int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); -// -void dlaswp_(int *n, double *A, int *lda, int *k1, int *k2, int *ipiv, int *incx); -// -void dposv_(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); -// -void dpotrf_(char *uplo, int *m, double *A, int *lda, int *info); -// -void dpotrs_(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); -// -void dtrtrs_(char *uplo, char *trans, char *diag, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); - - - -// aux -void dgetr_(int *m, int *n, double *A, int *lda, double *B, int *ldb); - - - -#ifdef CBLAS_API - - - -// CBLAS 1 -// -void cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY); -// -void cblas_dswap(const int N, double *X, const int incX, double *Y, const int incY); -// -void cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY); - -// CBLAS 2 -// -void cblas_dgemv(const enum CBLAS_LAYOUT layout, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY); - -// CBLAS 3 -// -void cblas_dgemm(const enum CBLAS_LAYOUT layout, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); -// -void cblas_dsyrk(const enum CBLAS_LAYOUT layout, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const double *A, const int lda, const double beta, double *C, const int ldc); -// -void cblas_dtrmm(const enum CBLAS_LAYOUT layout, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); -// -void cblas_dtrsm(const enum CBLAS_LAYOUT layout, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); - - - -#endif // CBLAS_API - - - -#else // BLASFEO_API - - - -// BLAS 1 -// -void blasfeo_blas_daxpy(int *n, double *alpha, double *x, int *incx, double *y, int *incy); -// -double blasfeo_blas_ddot(int *n, double *x, int *incx, double *y, int *incy); -// -void blasfeo_blas_dcopy(int *n, double *x, int *incx, double *y, int *incy); - -// BLAS 2 -// -void blasfeo_blas_dgemv(char *trans, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -// -void blasfeo_blas_dsymv(char *uplo, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -// -void blasfeo_blas_dger(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *A, int *lda); - -// BLAS 3 -// -void blasfeo_blas_dgemm(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); -// -void blasfeo_blas_dsyrk(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); -// -void blasfeo_blas_dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -// -void blasfeo_blas_dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -// -void blasfeo_blas_dsyr2k(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); - - - -// LAPACK -// -void blasfeo_lapack_dgesv(int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); -// -void blasfeo_lapack_dgetrf(int *m, int *n, double *A, int *lda, int *ipiv, int *info); -// -void blasfeo_lapack_dgetrf_np(int *m, int *n, double *A, int *lda, int *info); -// -void blasfeo_lapack_dgetrs(char *trans, int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); -// -void blasfeo_lapack_dlaswp(int *n, double *A, int *lda, int *k1, int *k2, int *ipiv, int *incx); -// -void blasfeo_lapack_dposv(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); -// -void blasfeo_lapack_dpotrf(char *uplo, int *m, double *A, int *lda, int *info); -// -void blasfeo_lapack_dpotrs(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); -// -void blasfeo_lapack_dtrtrs(char *uplo, char *trans, char *diag, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); - - - -// aux -void blasfeo_blas_dgetr(int *m, int *n, double *A, int *lda, double *B, int *ldb); - - - -#ifdef CBLAS_API - - - -// CBLAS 1 -// -void blasfeo_cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY); -// -void blasfeo_cblas_dswap(const int N, double *X, const int incX, double *Y, const int incY); -// -void blasfeo_cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY); - -// CBLAS 2 -// -void blasfeo_cblas_dgemv(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const int M, const int N, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY); - -// CBLAS 3 -// -void blasfeo_cblas_dgemm(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); -// -void blasfeo_cblas_dsyrk(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const double *A, const int lda, const double beta, double *C, const int ldc); -// -void blasfeo_cblas_dtrmm(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); -// -void blasfeo_cblas_dtrsm(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); - - - -#endif // CBLAS_API - - - -#endif // BLASFEO_API - - - -#endif // BLAS_API - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLAS_API_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h deleted file mode 100644 index 88bb3fce226248..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h +++ /dev/null @@ -1,364 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLASFEO_API_H_ -#define BLASFEO_D_BLASFEO_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -// level 1 BLAS -// - -// z = y + alpha*x -// z[zi:zi+n] = alpha*x[xi:xi+n] + y[yi:yi+n] -// NB: Different arguments semantic compare to equivalent standard BLAS routine -void blasfeo_daxpy(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = beta*y + alpha*x -void blasfeo_daxpby(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = x .* y -void blasfeo_dvecmul(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z += x .* y -void blasfeo_dvecmulacc(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = x .* y, return sum(z) = x^T * y -double blasfeo_dvecmuldot(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// return x^T * y -double blasfeo_ddot(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// construct givens plane rotation -void blasfeo_drotg(double a, double b, double *c, double *s); -// apply plane rotation [a b] [c -s; s; c] to the aj0 and aj1 columns of A at row index ai -void blasfeo_dcolrot(int m, struct blasfeo_dmat *sA, int ai, int aj0, int aj1, double c, double s); -// apply plane rotation [c s; -s c] [a; b] to the ai0 and ai1 rows of A at column index aj -void blasfeo_drowrot(int m, struct blasfeo_dmat *sA, int ai0, int ai1, int aj, double c, double s); - - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_dgemv_n(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A^T * x -void blasfeo_dgemv_t(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(n) -void blasfeo_dtrsv_lnn_mn(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(n) -void blasfeo_dtrsv_ltn_mn(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, not_unit -void blasfeo_dtrsv_lnn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, unit -void blasfeo_dtrsv_lnu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(m) lower, transposed, not_unit -void blasfeo_dtrsv_ltn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(m) lower, transposed, unit -void blasfeo_dtrsv_ltu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(m) upper, not_transposed, not_unit -void blasfeo_dtrsv_unn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(m) upper, transposed, not_unit -void blasfeo_dtrsv_utn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A * x ; A lower triangular -void blasfeo_dtrmv_lnn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A * x ; A lower triangular, unit diagonal -void blasfeo_dtrmv_lnu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A^T * x ; A lower triangular -void blasfeo_dtrmv_ltn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A^T * x ; A lower triangular, unit diagonal -void blasfeo_dtrmv_ltu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A * x ; A upper triangular -void blasfeo_dtrmv_unn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A^T * x ; A upper triangular -void blasfeo_dtrmv_utn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z_n <= beta_n * y_n + alpha_n * A * x_n -// z_t <= beta_t * y_t + alpha_t * A^T * x_t -void blasfeo_dgemv_nt(int m, int n, double alpha_n, double alpha_t, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx_n, int xi_n, struct blasfeo_dvec *sx_t, int xi_t, double beta_n, double beta_t, struct blasfeo_dvec *sy_n, int yi_n, struct blasfeo_dvec *sy_t, int yi_t, struct blasfeo_dvec *sz_n, int zi_n, struct blasfeo_dvec *sz_t, int zi_t); -// z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed -void blasfeo_dsymv_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -void blasfeo_dsymv_l_mn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed -void blasfeo_dsymv_u(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// D = C + alpha * x * y^T -void blasfeo_dger(int m, int n, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - -// diagonal - -// z <= beta * y + alpha * A * x, A diagonal -void blasfeo_dgemv_d(int m, double alpha, struct blasfeo_dvec *sA, int ai, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); - - - -// -// level 3 BLAS -// - -// dense - -// D <= beta * C + alpha * A * B -void blasfeo_dgemm_nn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T -void blasfeo_dgemm_nt(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B^T -void blasfeo_dgemm_tt(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D lower triangular -void blasfeo_dsyrk_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_dsyrk_ln_mn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) -void blasfeo_dsyrk3_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#endif -// D <= beta * C + alpha * A^T * B ; C, D lower triangular -void blasfeo_dsyrk_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) -void blasfeo_dsyrk3_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#endif -// D <= beta * C + alpha * A * B^T ; C, D upper triangular -void blasfeo_dsyrk_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) -void blasfeo_dsyrk3_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#endif -// D <= beta * C + alpha * A^T * B ; C, D upper triangular -void blasfeo_dsyrk_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) -void blasfeo_dsyrk3_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#endif -// D <= alpha * A * B ; A lower triangular -void blasfeo_dtrmm_llnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A lower triangular -void blasfeo_dtrmm_llnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A lower triangular -void blasfeo_dtrmm_lltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A lower triangular -void blasfeo_dtrmm_lltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A upper triangular -void blasfeo_dtrmm_lunn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A upper triangular -void blasfeo_dtrmm_lunu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A upper triangular -void blasfeo_dtrmm_lutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A upper triangular -void blasfeo_dtrmm_lutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_dtrmm_rlnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_dtrmm_rlnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A lower triangular -void blasfeo_dtrmm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A lower triangular -void blasfeo_dtrmm_rltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A upper triangular -void blasfeo_dtrmm_runn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A upper triangular -void blasfeo_dtrmm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A upper triangular -void blasfeo_dtrmm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A upper triangular -void blasfeo_dtrmm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular employint explicit inverse of diagonal -// D <= alpha * A^{-1} * B , with A lower triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_llnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular with unit diagonal -void blasfeo_dtrsm_llnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_lltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular with unit diagonal -void blasfeo_dtrsm_lltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_lunn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular with unit diagonal -void blasfeo_dtrsm_lunu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_lutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular with unit diagonal -void blasfeo_dtrsm_lutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_rlnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular with unit diagonal -void blasfeo_dtrsm_rlnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular with unit diagonal -void blasfeo_dtrsm_rltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_runn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular with unit diagonal -void blasfeo_dtrsm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal -void blasfeo_dtrsm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D lower triangular -void blasfeo_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D lower triangular -void blasfeo_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D upper triangular -void blasfeo_dsyr2k_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D upper triangular -void blasfeo_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - -// diagonal - -// D <= alpha * A * B + beta * C, with A diagonal (stored as strvec) -void dgemm_diag_left_lib(int m, int n, double alpha, double *dA, double *pB, int sdb, double beta, double *pC, int sdc, double *pD, int sdd); -void blasfeo_dgemm_dn(int m, int n, double alpha, struct blasfeo_dvec *sA, int ai, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B + beta * C, with B diagonal (stored as strvec) -void blasfeo_dgemm_nd(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sB, int bi, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - - - -// -// LAPACK -// - -// D <= chol( C ) ; C, D lower triangular -void blasfeo_dpotrf_l(int m, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_dpotrf_l_mn(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= chol( C ) ; C, D upper triangular -void blasfeo_dpotrf_u(int m, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= chol( C + A * B' ) ; C, D lower triangular -// D <= chol( C + A * B^T ) ; C, D lower triangular -void blasfeo_dsyrk_dpotrf_ln(int m, int k, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_dsyrk_dpotrf_ln_mn(int m, int n, int k, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= lu( C ) ; no pivoting -void blasfeo_dgetrf_np(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= lu( C ) ; row pivoting -void blasfeo_dgetrf_rp(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, int *ipiv); -// D <= qr( C ) -int blasfeo_dgeqrf_worksize(int m, int n); // in bytes -void blasfeo_dgeqrf(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// D <= Q factor, where C is the output of the LQ factorization -int blasfeo_dorglq_worksize(int m, int n, int k); // in bytes -void blasfeo_dorglq(int m, int n, int k, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// D <= lq( C ) -void blasfeo_dgelqf(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -int blasfeo_dgelqf_worksize(int m, int n); // in bytes -// D <= lq( C ), positive diagonal elements -void blasfeo_dgelqf_pd(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// [L, A] <= lq( [L, A] ), positive diagonal elements, array of matrices, with -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_dgelqf_pd_la(int m, int n1, struct blasfeo_dmat *sL, int li, int lj, struct blasfeo_dmat *sA, int ai, int aj, void *work); -// [L, L, A] <= lq( [L, L, A] ), positive diagonal elements, array of matrices, with: -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_dgelqf_pd_lla(int m, int n1, struct blasfeo_dmat *sL0, int l0i, int l0j, struct blasfeo_dmat *sL1, int l1i, int l1j, struct blasfeo_dmat *sA, int ai, int aj, void *work); - - - -// -// BLAS API helper functions -// - -#if ( defined(BLAS_API) & defined(MF_PANELMAJ) ) -// BLAS 3 -void blasfeo_cm_dgemm_nn(int m, int n, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dgemm_nt(int m, int n, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dgemm_tt(int m, int n, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk_ln(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk_lt(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk_un(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk_ut(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk3_ln(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk3_lt(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk3_un(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk3_ut(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_llnn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_llnu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lltn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lltu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lunn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lunu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rlnn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rlnu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rltu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_runn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_runu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_llnn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_llnu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lltn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lltu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lunn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lunu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rlnn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rlnu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rltn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rltu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_runn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_runu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyr2k_un(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -// BLAS 2 -void blasfeo_cm_dgemv_n(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); -void blasfeo_cm_dgemv_t(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); -void blasfeo_cm_dsymv_l(int m, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); -void blasfeo_cm_dsymv_u(int m, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); -void blasfeo_cm_dger(int m, int n, double alpha, struct blasfeo_cm_dvec *sx, int xi, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -// LAPACK -void blasfeo_cm_dpotrf_l(int m, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dpotrf_u(int m, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dgetrf_rp(int m, int n, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj, int *ipiv); -#endif - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLASFEO_API_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api_ref.h deleted file mode 100644 index 141a1f0f06082c..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api_ref.h +++ /dev/null @@ -1,147 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLASFEO_API_REF_H_ -#define BLASFEO_D_BLASFEO_API_REF_H_ - -#include "blasfeo_common.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - -// expose reference BLASFEO for testing - -// --- level 1 - -void blasfeo_daxpy_ref(int kmax, double alpha, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_daxpby_ref(int kmax, double alpha, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dvecmul_ref(int m, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dvecmulacc_ref(int m, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -double blasfeo_dvecmuldot_ref(int m, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -double blasfeo_ddot_ref(int m, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi); -void blasfeo_drotg_ref(double a, double b, double *c, double *s); -void blasfeo_dcolrot_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj0, int aj1, double c, double s); -void blasfeo_drowrot_ref(int m, struct blasfeo_dmat_ref *sA, int ai0, int ai1, int aj, double c, double s); - - -// --- level 2 - -// dense -void blasfeo_dgemv_n_ref(int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dgemv_t_ref(int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_lnn_mn_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_ltn_mn_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_lnn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_lnu_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_ltn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_ltu_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_unn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_utn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_unn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_utn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_lnn_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_ltn_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_lnu_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_ltu_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dgemv_nt_ref(int m, int n, double alpha_n, double alpha_t, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx_n, int xi_n, struct blasfeo_dvec_ref *sx_t, int xi_t, double beta_n, double beta_t, struct blasfeo_dvec_ref *sy_n, int yi_n, struct blasfeo_dvec_ref *sy_t, int yi_t, struct blasfeo_dvec_ref *sz_n, int zi_n, struct blasfeo_dvec_ref *sz_t, int zi_t); -void blasfeo_dsymv_l_ref(int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); - -// diagonal -void blasfeo_dgemv_d_ref(int m, double alpha, struct blasfeo_dvec_ref *sA, int ai, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); - - -// --- level 3 - -// dense -void blasfeo_dgemm_nn_ref( int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgemm_nt_ref( int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgemm_tn_ref(int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgemm_tt_ref(int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); - -void blasfeo_dsyrk_ln_mn_ref( int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_ln_ref( int m, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_lt_ref( int m, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_un_ref( int m, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_ut_ref( int m, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); - -void blasfeo_dtrmm_rutn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrmm_rlnn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); - -void blasfeo_dtrsm_lunu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lunn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lutu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lutn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_llnu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_llnn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lltu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lltn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_runu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_runn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rutu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rutn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rlnu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rlnn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rltu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rltn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); - -// diagonal -void dgemm_diag_left_lib_ref(int m, int n, double alpha, double *dA, double *pB, int sdb, double beta, double *pC, int sdc, double *pD, int sdd); -void blasfeo_dgemm_dn_ref(int m, int n, double alpha, struct blasfeo_dvec_ref *sA, int ai, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgemm_nd_ref(int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sB, int bi, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); - -// --- lapack - -void blasfeo_dgetrf_nopivot_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgetrf_rowpivot_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, int *ipiv); -void blasfeo_dpotrf_l_ref(int m, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dpotrf_l_mn_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_dpotrf_ln_ref(int m, int k, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_dpotrf_ln_mn_ref(int m, int n, int k, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgetrf_nopivot_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgetrf_rowpivot_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, int *ipiv); -void blasfeo_dgeqrf_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, void *work); -void blasfeo_dgelqf_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, void *work); -void blasfeo_dgelqf_pd_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, void *work); -void blasfeo_dgelqf_pd_la_ref(int m, int n1, struct blasfeo_dmat_ref *sL, int li, int lj, struct blasfeo_dmat_ref *sA, int ai, int aj, void *work); -void blasfeo_dgelqf_pd_lla_ref(int m, int n1, struct blasfeo_dmat_ref *sL0, int l0i, int l0j, struct blasfeo_dmat_ref *sL1, int l1i, int l1j, struct blasfeo_dmat_ref *sA, int ai, int aj, void *work); - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLASFEO_API_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h deleted file mode 100644 index 405733f13e89b3..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLASFEO_HP_API_H_ -#define BLASFEO_D_BLASFEO_HP_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -// level 3 BLAS -// - -// dense - - -// D <= beta * C + alpha * A^T * B -void blasfeo_hp_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T; C, D lower triangular -void blasfeo_hp_dsyrk_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * A^T ; C, D lower triangular -void blasfeo_hp_dsyrk3_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular -void blasfeo_hp_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_hp_dgemv_n(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLASFEO_HP_API_H_ - diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h deleted file mode 100644 index 1a8b22c67efc68..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h +++ /dev/null @@ -1,283 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLASFEO_REF_API_H_ -#define BLASFEO_D_BLASFEO_REF_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -// level 1 BLAS -// - -// z = y + alpha*x -// z[zi:zi+n] = alpha*x[xi:xi+n] + y[yi:yi+n] -// NB: Different arguments semantic compare to equivalent standard BLAS routine -void blasfeo_ref_daxpy(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = beta*y + alpha*x -void blasfeo_ref_daxpby(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = x .* y -void blasfeo_ref_dvecmul(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z += x .* y -void blasfeo_ref_dvecmulacc(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = x .* y, return sum(z) = x^T * y -double blasfeo_ref_dvecmuldot(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// return x^T * y -double blasfeo_ref_ddot(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// construct givens plane rotation -void blasfeo_ref_drotg(double a, double b, double *c, double *s); -// apply plane rotation [a b] [c -s; s; c] to the aj0 and aj1 columns of A at row index ai -void blasfeo_ref_dcolrot(int m, struct blasfeo_dmat *sA, int ai, int aj0, int aj1, double c, double s); -// apply plane rotation [c s; -s c] [a; b] to the ai0 and ai1 rows of A at column index aj -void blasfeo_ref_drowrot(int m, struct blasfeo_dmat *sA, int ai0, int ai1, int aj, double c, double s); - - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_ref_dgemv_n(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A' * x -void blasfeo_ref_dgemv_t(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(n) -void blasfeo_ref_dtrsv_lnn_mn(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(n) -void blasfeo_ref_dtrsv_ltn_mn(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, not_unit -void blasfeo_ref_dtrsv_lnn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, unit -void blasfeo_ref_dtrsv_lnu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, not_unit -void blasfeo_ref_dtrsv_ltn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, unit -void blasfeo_ref_dtrsv_ltu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, not_transposed, not_unit -void blasfeo_ref_dtrsv_unn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, transposed, not_unit -void blasfeo_ref_dtrsv_utn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A * x ; A lower triangular -void blasfeo_ref_dtrmv_lnn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A * x ; A lower triangular, unit diagonal -void blasfeo_ref_dtrmv_lnu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A' * x ; A lower triangular -void blasfeo_ref_dtrmv_ltn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A' * x ; A lower triangular, unit diagonal -void blasfeo_ref_dtrmv_ltu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A * x ; A upper triangular -void blasfeo_ref_dtrmv_unn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A' * x ; A upper triangular -void blasfeo_ref_dtrmv_utn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z_n <= beta_n * y_n + alpha_n * A * x_n -// z_t <= beta_t * y_t + alpha_t * A' * x_t -void blasfeo_ref_dgemv_nt(int m, int n, double alpha_n, double alpha_t, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx_n, int xi_n, struct blasfeo_dvec *sx_t, int xi_t, double beta_n, double beta_t, struct blasfeo_dvec *sy_n, int yi_n, struct blasfeo_dvec *sy_t, int yi_t, struct blasfeo_dvec *sz_n, int zi_n, struct blasfeo_dvec *sz_t, int zi_t); -// z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed -void blasfeo_ref_dsymv_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -void blasfeo_ref_dsymv_l_mn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed -void blasfeo_ref_dsymv_u(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// D = C + alpha * x * y^T -void blasfeo_ref_dger(int m, int n, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - -// diagonal - -// z <= beta * y + alpha * A * x, A diagonal -void blasfeo_ref_dgemv_d(int m, double alpha, struct blasfeo_dvec *sA, int ai, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); - - - -// -// level 3 BLAS -// - -// dense - -// D <= beta * C + alpha * A * B -void blasfeo_ref_dgemm_nn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T -void blasfeo_ref_dgemm_nt(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_ref_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B^T -void blasfeo_ref_dgemm_tt(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D lower triangular -void blasfeo_ref_dsyrk_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_ref_dsyrk_ln_mn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D lower triangular -void blasfeo_ref_dsyrk_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D upper triangular -void blasfeo_ref_dsyrk_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D upper triangular -void blasfeo_ref_dsyrk_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A lower triangular -void blasfeo_ref_dtrmm_llnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A lower triangular -void blasfeo_ref_dtrmm_llnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A lower triangular -void blasfeo_ref_dtrmm_lltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A lower triangular -void blasfeo_ref_dtrmm_lltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A upper triangular -void blasfeo_ref_dtrmm_lunn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A upper triangular -void blasfeo_ref_dtrmm_lunu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A upper triangular -void blasfeo_ref_dtrmm_lutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A upper triangular -void blasfeo_ref_dtrmm_lutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_ref_dtrmm_rlnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_ref_dtrmm_rlnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A lower triangular -void blasfeo_ref_dtrmm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A lower triangular -void blasfeo_ref_dtrmm_rltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A upper triangular -void blasfeo_ref_dtrmm_runn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A upper triangular -void blasfeo_ref_dtrmm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A upper triangular -void blasfeo_ref_dtrmm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A upper triangular -void blasfeo_ref_dtrmm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_ref_dtrsm_llnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular with unit diagonal -void blasfeo_ref_dtrsm_llnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_ref_dtrsm_lltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular with unit diagonal -void blasfeo_ref_dtrsm_lltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_lunn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular withunit diagonal -void blasfeo_ref_dtrsm_lunu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_lutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular withunit diagonal -void blasfeo_ref_dtrsm_lutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_rlnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular with unit diagonal -void blasfeo_ref_dtrsm_rlnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular with unit diagonal -void blasfeo_ref_dtrsm_rltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_runn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular with unit diagonal -void blasfeo_ref_dtrsm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal -void blasfeo_ref_dtrsm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D lower triangular -void blasfeo_ref_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D lower triangular -void blasfeo_ref_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D upper triangular -void blasfeo_ref_dsyr2k_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D upper triangular -void blasfeo_ref_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - -// diagonal - -// D <= alpha * A * B + beta * C, with A diagonal (stored as strvec) -void dgemm_diag_left_lib(int m, int n, double alpha, double *dA, double *pB, int sdb, double beta, double *pC, int sdc, double *pD, int sdd); -void blasfeo_ref_dgemm_dn(int m, int n, double alpha, struct blasfeo_dvec *sA, int ai, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B + beta * C, with B diagonal (stored as strvec) -void blasfeo_ref_dgemm_nd(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sB, int bi, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - - - -// -// LAPACK -// - -// D <= chol( C ) ; C, D lower triangular -void blasfeo_ref_dpotrf_l(int m, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_ref_dpotrf_l_mn(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= chol( C ) ; C, D upper triangular -void blasfeo_ref_dpotrf_u(int m, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= chol( C + A * B' ) ; C, D lower triangular -void blasfeo_ref_dsyrk_dpotrf_ln(int m, int k, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_ref_dsyrk_dpotrf_ln_mn(int m, int n, int k, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= lu( C ) ; no pivoting -void blasfeo_ref_dgetrf_np(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= lu( C ) ; row pivoting -void blasfeo_ref_dgetrf_rp(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, int *ipiv); -// D <= qr( C ) -int blasfeo_ref_dgeqrf_worksize(int m, int n); // in bytes -void blasfeo_ref_dgeqrf(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// D <= Q factor, where C is the output of the LQ factorization -int blasfeo_ref_dorglq_worksize(int m, int n, int k); // in bytes -void blasfeo_ref_dorglq(int m, int n, int k, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// D <= lq( C ) -void blasfeo_ref_dgelqf(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -int blasfeo_ref_dgelqf_worksize(int m, int n); // in bytes -// D <= lq( C ), positive diagonal elements -void blasfeo_ref_dgelqf_pd(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// [L, A] <= lq( [L, A] ), positive diagonal elements, array of matrices, with -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_ref_dgelqf_pd_la(int m, int n1, struct blasfeo_dmat *sL, int li, int lj, struct blasfeo_dmat *sA, int ai, int aj, void *work); -// [L, L, A] <= lq( [L, L, A] ), positive diagonal elements, array of matrices, with: -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_ref_dgelqf_pd_lla(int m, int n1, struct blasfeo_dmat *sL0, int l0i, int l0j, struct blasfeo_dmat *sL1, int l1i, int l1j, struct blasfeo_dmat *sA, int ai, int aj, void *work); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLASFEO_REF_API_H_ - diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h b/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h deleted file mode 100644 index d20ac38bbd043c..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h +++ /dev/null @@ -1,1321 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_KERNEL_H_ -#define BLASFEO_D_KERNEL_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// utils -void blasfeo_align_2MB(void *ptr, void **ptr_align); -void blasfeo_align_4096_byte(void *ptr, void **ptr_align); -void blasfeo_align_64_byte(void *ptr, void **ptr_align); - - -// -// lib8 -// - -// 24x8 -void kernel_dgemm_nt_24x8_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nt_24x8_vs_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dtrsm_nt_rl_inv_24x8_lib8(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); // -void kernel_dpotrf_nt_l_24x8_lib8(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_24x8_vs_lib8(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_24x8_vs_lib8(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int m1, int n1); // -void kernel_dgemm_dtrsm_nt_rl_inv_24x8_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_24x8_vs_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int m1, int n1); -void kernel_dsyrk_dpotrf_nt_l_24x8_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_24x8_vs_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int m1, int n1); -void kernel_dlarfb8_rn_24_lib8(int kmax, double *pV, double *pT, double *pD, int sdd); -// 16x8 -void kernel_dgemm_nt_16x8_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nt_16x8_vs_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nt_16x8_gen_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_nn_16x8_lib8(int k, double *alpha, double *A, int sda, int offB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_16x8_vs_lib8(int k, double *alpha, double *A, int sda, int offB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_16x8_gen_lib8(int k, double *alpha, double *A, int sda, int offB, double *B, int sdb, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dsyrk_nt_l_16x8_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nt_l_16x8_vs_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nt_l_16x8_gen_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dtrmm_nn_rl_16x8_lib8(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd); -void kernel_dtrmm_nn_rl_16x8_vs_lib8(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd, int m1, int n1); -void kernel_dtrmm_nn_rl_16x8_gen_lib8(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrsm_nt_rl_inv_16x8_lib8(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); // -void kernel_dtrsm_nt_rl_inv_16x8_vs_lib8(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int m1, int n1); // -void kernel_dpotrf_nt_l_16x8_lib8(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_16x8_vs_lib8(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int m1, int n1); -void kernel_dgemm_dtrsm_nt_rl_inv_16x8_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_16x8_vs_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int m1, int n1); -void kernel_dsyrk_dpotrf_nt_l_16x8_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_16x8_vs_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int m1, int n1); -void kernel_dlarfb8_rn_16_lib8(int kmax, double *pV, double *pT, double *pD, int sdd); -void kernel_dlarfb8_rn_la_16_lib8(int n1, double *pVA, double *pT, double *pD, int sdd, double *pA, int sda); -void kernel_dlarfb8_rn_lla_16_lib8(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, int sdd, double *pL, int sdl, double *pA, int sda); -// 8x16 -void kernel_dgemm_tt_8x16_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_tt_8x16_vs_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_8x16_gen_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, int sdb, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_nt_8x16_lib8(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nt_8x16_vs_lib8(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -// 8x8 -void kernel_dgemm_nt_8x8_lib8(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dgemm_nt_8x8_vs_lib8(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_nt_8x8_gen_lib8(int k, double *alpha, double *A, double *B, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_nn_8x8_lib8(int k, double *alpha, double *A, int offB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_8x8_vs_lib8(int k, double *alpha, double *A, int offB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_nn_8x8_gen_lib8(int k, double *alpha, double *A, int offB, double *B, int sdb, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_tt_8x8_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, double *beta, double *C, double *D); // -void kernel_dgemm_tt_8x8_vs_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_8x8_gen_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, double *beta, int offc, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dsyrk_nt_l_8x8_lib8(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_8x8_vs_lib8(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dsyrk_nt_l_8x8_gen_lib8(int k, double *alpha, double *A, double *B, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dtrmm_nn_rl_8x8_lib8(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D); -void kernel_dtrmm_nn_rl_8x8_vs_lib8(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D, int m1, int n1); -void kernel_dtrmm_nn_rl_8x8_gen_lib8(int k, double *alpha, double *A, int offsetB, double *B, int sdb, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrsm_nt_rl_inv_8x8_lib8(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_8x8_vs_lib8(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E, int m1, int n1); -void kernel_dpotrf_nt_l_8x8_lib8(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dpotrf_nt_l_8x8_vs_lib8(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int m1, int n1); -void kernel_dgemm_dtrsm_nt_rl_inv_8x8_lib8(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_8x8_vs_lib8(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E, int m1, int n1); -void kernel_dsyrk_dpotrf_nt_l_8x8_lib8(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_8x8_vs_lib8(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D, int m1, int n1); -void kernel_dgelqf_vs_lib8(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dgelqf_pd_vs_lib8(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dgelqf_8_lib8(int kmax, double *pD, double *dD); -void kernel_dgelqf_pd_8_lib8(int kmax, double *pD, double *dD); -void kernel_dlarft_8_lib8(int kmax, double *pD, double *dD, double *pT); -void kernel_dlarfb8_rn_8_lib8(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb8_rn_8_vs_lib8(int kmax, double *pV, double *pT, double *pD, int m1); -void kernel_dlarfb8_rn_1_lib8(int kmax, double *pV, double *pT, double *pD); -void kernel_dgelqf_dlarft8_8_lib8(int kmax, double *pD, double *dD, double *pT); -void kernel_dgelqf_pd_dlarft8_8_lib8(int kmax, double *pD, double *dD, double *pT); -void kernel_dgelqf_pd_la_vs_lib8(int m, int n1, int k, int offD, double *pD, int sdd, double *dD, int offA, double *pA, int sda); -void kernel_dgelqf_pd_la_dlarft8_8_lib8(int kmax, double *pD, double *dD, double *pA, double *pT); -void kernel_dlarft_la_8_lib8(int n1, double *dD, double *pA, double *pT); -void kernel_dlarfb8_rn_la_8_lib8(int n1, double *pVA, double *pT, double *pD, double *pA); -void kernel_dlarfb8_rn_la_8_vs_lib8(int n1, double *pVA, double *pT, double *pD, double *pA, int m1); -void kernel_dlarfb8_rn_la_1_lib8(int n1, double *pVA, double *pT, double *pD, double *pA); -void kernel_dgelqf_pd_lla_vs_lib8(int m, int n0, int n1, int k, int offD, double *pD, int sdd, double *dD, int offL, double *pL, int sdl, int offA, double *pA, int sda); -void kernel_dgelqf_pd_lla_dlarft8_8_lib8(int n0, int n1, double *pD, double *dD, double *pL, double *pA, double *pT); -void kernel_dlarft_lla_8_lib8(int n0, int n1, double *dD, double *pL, double *pA, double *pT); -void kernel_dlarfb8_rn_lla_8_lib8(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA); -void kernel_dlarfb8_rn_lla_8_vs_lib8(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA, int m1); -void kernel_dlarfb8_rn_lla_1_lib8(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA); - -// panel copy / pack -// 24 -void kernel_dpack_nn_24_lib8(int kmax, double *A, int lda, double *C, int sdc); -void kernel_dpack_nn_24_vs_lib8(int kmax, double *A, int lda, double *C, int sdc, int m1); -// 16 -void kernel_dpacp_nn_16_lib8(int kmax, int offsetA, double *A, int sda, double *B, int sdb); -void kernel_dpacp_nn_16_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int sdb, int m1); -void kernel_dpack_nn_16_lib8(int kmax, double *A, int lda, double *C, int sdc); -void kernel_dpack_nn_16_vs_lib8(int kmax, double *A, int lda, double *C, int sdc, int m1); -// 8 -void kernel_dpacp_nn_8_lib8(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_nn_8_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpacp_tn_8_lib8(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_tn_8_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpacp_l_nn_8_lib8(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_l_nn_8_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpacp_l_tn_8_lib8(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_l_tn_8_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpaad_nn_8_lib8(int kmax, double *alpha, int offsetA, double *A, int sda, double *B); -void kernel_dpaad_nn_8_vs_lib8(int kmax, double *alpha, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpack_nn_8_lib8(int kmax, double *A, int lda, double *C); -void kernel_dpack_nn_8_vs_lib8(int kmax, double *A, int lda, double *C, int m1); -void kernel_dpack_tn_8_lib8(int kmax, double *A, int lda, double *C); -void kernel_dpack_tn_8_vs_lib8(int kmax, double *A, int lda, double *C, int m1); -// 4 -void kernel_dpack_tt_4_lib8(int kmax, double *A, int lda, double *C, int sdc); // TODO offsetC -void kernel_dpack_tt_4_vs_lib8(int kmax, double *A, int lda, double *C, int sdc, int m1); // TODO offsetC - -// level 2 BLAS -// 16 -void kernel_dgemv_n_16_lib8(int k, double *alpha, double *A, int sda, double *x, double *beta, double *y, double *z); -// 8 -void kernel_dgemv_n_8_lib8(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z); -void kernel_dgemv_n_8_vs_lib8(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z, int m1); -//void kernel_dgemv_n_8_gen_lib8(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z, int m0, int m1); -void kernel_dgemv_n_8_gen_lib8(int k, double *alpha, int offsetA, double *A, double *x, double *beta, double *y, double *z, int m1); -void kernel_dgemv_t_8_lib8(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_8_vs_lib8(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z, int n1); -void kernel_dgemv_nt_8_lib8(int kmax, double *alpha_n, double *alpha_t, int offsetA, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t); -void kernel_dgemv_nt_8_vs_lib8(int kmax, double *alpha_n, double *alpha_t, int offsetA, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t, int n1); -void kernel_dsymv_l_8_lib8(int kmax, double *alpha, double *A, int sda, double *x, double *z); -void kernel_dsymv_l_8_vs_lib8(int kmax, double *alpha, double *A, int sda, double *x, double *z, int n1); -void kernel_dsymv_l_8_gen_lib8(int kmax, double *alpha, int offsetA, double *A, int sda, double *x, double *z, int n1); -void kernel_dtrmv_n_ln_8_lib8(int k, double *A, double *x, double *z); -void kernel_dtrmv_n_ln_8_vs_lib8(int k, double *A, double *x, double *z, int m1); -void kernel_dtrmv_n_ln_8_gen_lib8(int k, int offsetA, double *A, double *x, double *z, int m1); -void kernel_dtrmv_t_ln_8_lib8(int k, double *A, int sda, double *x, double *z); -void kernel_dtrmv_t_ln_8_vs_lib8(int k, double *A, int sda, double *x, double *z, int n1); -void kernel_dtrmv_t_ln_8_gen_lib8(int k, int offsetA, double *A, int sda, double *x, double *z, int n1); -void kernel_dtrsv_n_l_inv_8_lib8(int k, double *A, double *inv_diag_A, double *x, double *z); -void kernel_dtrsv_n_l_inv_8_vs_lib8(int k, double *A, double *inv_diag_A, double *x, double *z, int m1, int n1); -void kernel_dtrsv_t_l_inv_8_lib8(int k, double *A, int sda, double *inv_diag_A, double *x, double *z); -void kernel_dtrsv_t_l_inv_8_vs_lib8(int k, double *A, int sda, double *inv_diag_A, double *x, double *z, int m1, int n1); - - - -// -// lib4 -// - -// level 2 BLAS -// 12 -void kernel_dgemv_n_12_lib4(int k, double *alpha, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_12_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z); -// 8 -void kernel_dgemv_n_8_lib4(int k, double *alpha, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_8_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dtrmv_un_8_lib4(int k, double *A, int sda, double *x, double *z); -// 4 -void kernel_dgemv_n_4_lib4(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z); -void kernel_dgemv_n_4_vs_lib4(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z, int k1); -void kernel_dgemv_n_4_gen_lib4(int kmax, double *alpha, double *A, double *x, double *beta, double *y, double *z, int k0, int k1); -void kernel_dgemv_t_4_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_4_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z, int k1); -void kernel_dtrsv_ln_inv_4_lib4(int k, double *A, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_ln_inv_4_vs_lib4(int k, double *A, double *inv_diag_A, double *x, double *y, double *z, int km, int kn); -void kernel_dtrsv_lt_inv_4_lib4(int k, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_lt_inv_3_lib4(int k, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_lt_inv_2_lib4(int k, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_lt_inv_1_lib4(int k, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_lt_one_4_lib4(int k, double *A, int sda, double *x, double *y, double *z); -void kernel_dtrsv_lt_one_3_lib4(int k, double *A, int sda, double *x, double *y, double *z); -void kernel_dtrsv_lt_one_2_lib4(int k, double *A, int sda, double *x, double *y, double *z); -void kernel_dtrsv_lt_one_1_lib4(int k, double *A, int sda, double *x, double *y, double *z); -void kernel_dtrsv_ln_one_4_vs_lib4(int kmax, double *A, double *x, double *y, double *z, int km, int kn); -void kernel_dtrsv_ln_one_4_lib4(int kmax, double *A, double *x, double *y, double *z); -void kernel_dtrsv_un_inv_4_lib4(int kmax, double *A, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_ut_inv_4_lib4(int kmax, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_ut_inv_4_vs_lib4(int kmax, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z, int m1, int n1); -void kernel_dtrmv_un_4_lib4(int k, double *A, double *x, double *z); -void kernel_dtrmv_ut_4_lib4(int k, double *A, int sda, double *x, double *z); -void kernel_dtrmv_ut_4_vs_lib4(int k, double *A, int sda, double *x, double *z, int km); -void kernel_dgemv_nt_6_lib4(int kmax, double *alpha_n, double *alpha_t, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t); -void kernel_dgemv_nt_4_lib4(int kmax, double *alpha_n, double *alpha_t, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t); -void kernel_dgemv_nt_4_vs_lib4(int kmax, double *alpha_n, double *alpha_t, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t, int km); -void kernel_dsymv_l_4_lib4(int kmax, double *alpha, double *A, int sda, double *x, double *z); -void kernel_dsymv_l_4_gen_lib4(int kmax, double *alpha, int offA, double *A, int sda, double *x, double *z, int km); - - - -// level 3 BLAS -// 12x4 -void kernel_dgemm_nt_12x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nt_12x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dgemm_nt_12x4_gen_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int k0, int k1); -void kernel_dgemm_nn_12x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_12x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dgemm_nn_12x4_gen_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_tt_12x4_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_tt_12x4_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nn_u_12x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nn_u_12x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nt_l_12x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nt_l_12x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dtrmm_nt_ru_12x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *D, int sdd); // -void kernel_dtrmm_nt_ru_12x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *D, int sdd, int km, int kn); // -void kernel_dtrmm_nn_rl_12x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd); -void kernel_dtrmm_nn_rl_12x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd, int km, int kn); -void kernel_dtrsm_nt_rl_inv_12x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_one_12x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E); -void kernel_dtrsm_nt_rl_one_12x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, int km, int kn); -void kernel_dtrsm_nt_ru_inv_12x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_ru_inv_12x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_ru_one_12x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E); -void kernel_dtrsm_nt_ru_one_12x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, int km, int kn); -void kernel_dtrsm_nn_ru_inv_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ru_inv_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_inv_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde); -void kernel_dtrsm_nn_ll_one_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, int km, int kn); -void kernel_dtrsm_nn_lu_inv_12x4_lib4(int kmax, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_lu_inv_12x4_vs_lib4(int kmax, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -// 4x12 -void kernel_dgemm_nt_4x12_lib4(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nt_4x12_vs_lib4(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D, int km, int kn); // -void kernel_dgemm_nn_4x12_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_4x12_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x12_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_tt_4x12_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x12_gen_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dtrsm_nt_rl_inv_4x12_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *E, int sed, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_4x12_vs_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *E, int sed, double *inv_diag_E, int km, int kn); -// 8x8 -void kernel_dgemm_nt_8x8l_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // computes [A00 *; A10 A11] -void kernel_dgemm_nt_8x8u_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // computes [A00 *; A10 A11] -void kernel_dgemm_nt_8x8l_vs_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // computes [A00 *; A10 A11] -void kernel_dgemm_nt_8x8u_vs_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // computes [A00 *; A10 A11] -void kernel_dsyrk_nn_u_8x8_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nn_u_8x8_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nt_l_8x8_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // computes [L00 *; A10 L11] -void kernel_dsyrk_nt_l_8x8_vs_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // computes [L00 *; A10 L11] -void kernel_dtrsm_nt_rl_inv_8x8l_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sed, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_8x8l_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sed, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_8x8u_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sed, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_8x8u_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sed, double *inv_diag_E, int km, int kn); -// 8x4 -void kernel_dgemm_nt_8x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nt_8x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dgemm_nt_8x4_gen_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int k0, int k1); -void kernel_dgemm_nn_8x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_8x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_8x4_gen_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_tt_8x4_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_tt_8x4_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nn_u_8x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nn_u_8x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nt_l_8x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nt_l_8x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dsyrk_nt_l_8x4_gen_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int k0, int k1); -void kernel_dtrmm_nt_ru_8x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *D, int sdd); // -void kernel_dtrmm_nt_ru_8x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *D, int sdd, int km, int kn); // -void kernel_dtrmm_nn_rl_8x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd); -void kernel_dtrmm_nn_rl_8x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd, int km, int kn); -void kernel_dtrmm_nn_rl_8x4_gen_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_8x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_one_8x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E); -void kernel_dtrsm_nt_rl_one_8x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, int km, int kn); -void kernel_dtrsm_nt_ru_inv_8x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_ru_inv_8x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_ru_one_8x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E); -void kernel_dtrsm_nt_ru_one_8x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, int km, int kn); -void kernel_dtrsm_nn_ru_inv_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ru_inv_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_inv_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde); -void kernel_dtrsm_nn_ll_one_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, int km, int kn); -void kernel_dtrsm_nn_lu_inv_8x4_lib4(int kmax, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_lu_inv_8x4_vs_lib4(int kmax, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -// 4x8 -void kernel_dgemm_nt_4x8_lib4(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nt_4x8_vs_lib4(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D, int km, int kn); // -void kernel_dgemm_nn_4x8_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_4x8_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x8_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_tt_4x8_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x8_gen_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dtrsm_nt_rl_inv_4x8_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *E, int sed, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_4x8_vs_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *E, int sed, double *inv_diag_E, int km, int kn); -// 8x2 -void kernel_dgemm_nn_8x2_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_8x2_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -// 2x8 -void kernel_dgemm_nn_2x8_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_2x8_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -// 10xX -void kernel_dgemm_nn_10x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_10x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_10x2_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_10x2_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -// 6xX -void kernel_dgemm_nn_8x6_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_8x6_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_6x8_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_6x8_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_6x6_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_6x6_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_6x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_6x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_6x2_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_6x2_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -// 4x4 -void kernel_dgemm_nt_4x4_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dgemm_nt_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -void kernel_dgemm_nt_4x4_gen_lib4(int k, double *alpha, double *A, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dgemm_nn_4x4_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_4x4_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_nn_4x4_gen_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_tt_4x4_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, double *D); // -void kernel_dgemm_tt_4x4_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x4_gen_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dsyrk_nn_u_4x4_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dsyrk_nn_u_4x4_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dsyrk_nt_l_4x4_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -void kernel_dsyrk_nt_l_4x4_gen_lib4(int k, double *alpha, double *A, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dsyrk_nt_u_4x4_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_u_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -void kernel_dsyrk_nt_u_4x4_gen_lib4(int k, double *alpha, double *A, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrmm_nt_ru_4x4_lib4(int k, double *alpha, double *A, double *B, double *D); // -void kernel_dtrmm_nt_ru_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *D, int km, int kn); // -void kernel_dtrmm_nn_rl_4x4_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D); -void kernel_dtrmm_nn_rl_4x4_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D, int m1, int n1); -void kernel_dtrmm_nn_rl_4x4_gen_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrsm_nt_rl_inv_4x4_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_one_4x4_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E); -void kernel_dtrsm_nt_rl_one_4x4_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, int km, int kn); -void kernel_dtrsm_nt_ru_inv_4x4_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_ru_inv_4x4_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_ru_one_4x4_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E); -void kernel_dtrsm_nt_ru_one_4x4_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, int km, int kn); -void kernel_dtrsm_nn_ru_inv_4x4_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ru_inv_4x4_vs_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_inv_4x4_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_4x4_vs_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_4x4_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E); -void kernel_dtrsm_nn_ll_one_4x4_vs_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, int km, int kn); -void kernel_dtrsm_nn_lu_inv_4x4_lib4(int kmax, double *A, double *B, int sdb, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_lu_inv_4x4_vs_lib4(int kmax, double *A, double *B, int sdb, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_lu_one_4x4_lib4(int kmax, double *A, double *B, int sdb, double *C, double *D, double *E); -void kernel_dtrsm_nn_lu_one_4x4_vs_lib4(int kmax, double *A, double *B, int sdb, double *C, double *D, double *E, int km, int kn); -// 4x2 -void kernel_dgemm_nn_4x2_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_4x2_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_nt_4x2_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); -void kernel_dgemm_nt_4x2_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int m1, int n1); -void kernel_dsyrk_nt_l_4x2_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_4x2_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -void kernel_dtrmm_nn_rl_4x2_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D); -void kernel_dtrmm_nn_rl_4x2_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_4x2_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_4x2_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -// 2x4 -void kernel_dgemm_nn_2x4_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_2x4_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -// 2x2 -void kernel_dgemm_nn_2x2_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_2x2_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_2x2_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -// diag -void kernel_dgemm_diag_right_4_a0_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *D, int sdd); -void kernel_dgemm_diag_right_4_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); -void kernel_dgemm_diag_right_3_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); -void kernel_dgemm_diag_right_2_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); -void kernel_dgemm_diag_right_1_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); -void kernel_dgemm_diag_left_4_a0_lib4(int kmax, double *alpha, double *A, double *B, double *D); -void kernel_dgemm_diag_left_4_lib4(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D); -void kernel_dgemm_diag_left_3_lib4(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D); -void kernel_dgemm_diag_left_2_lib4(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D); -void kernel_dgemm_diag_left_1_lib4(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D); -// low rank update -void kernel_dger4_sub_12r_lib4(int k, double *A, int sda, double *B, double *C, int sdc); -void kernel_dger4_sub_12r_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, int km); -void kernel_dger4_sub_8r_lib4(int k, double *A, int sda, double *B, double *C, int sdc); -void kernel_dger4_sub_8r_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, int km); -void kernel_dger4_sub_4r_lib4(int n, double *A, double *B, double *C); -void kernel_dger4_sub_4r_vs_lib4(int n, double *A, double *B, double *C, int km); - - - -// LAPACK -// 12x4 -void kernel_dpotrf_nt_l_12x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_12x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_l_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_l_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_m_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_m_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_r_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_r_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_l_12x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_l_12x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_m_12x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_m_12x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_r_12x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_r_12x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 8x8 -void kernel_dpotrf_nt_l_8x8_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_8x8_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 8x4 -void kernel_dpotrf_nt_l_8x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_8x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_l_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_l_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_r_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_r_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_l_8x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_l_8x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_r_8x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_r_8x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 4x4 -void kernel_dpotrf_nt_l_4x4_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dpotrf_nt_l_4x4_vs_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int km, int kn); -#if defined(TARGET_X64_INTEL_SANDY_BRIDGE) -void kernel_dlauum_nt_4x4_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dlauum_nt_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -#endif -void kernel_dgetrf_nn_4x4_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *inv_diag_D); -void kernel_dgetrf_nn_4x4_vs_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_4x4_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dgetrf_nt_4x4_vs_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int km, int kn); -void kernel_dgeqrf_4_lib4(int m, double *pD, int sdd, double *dD); -void kernel_dgeqrf_vs_lib4(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dlarf_4_lib4(int m, int n, double *pV, int sdv, double *tau, double *pC, int sdc); // rank-4 reflector -void kernel_dlarf_t_4_lib4(int m, int n, double *pD, int sdd, double *pVt, double *dD, double *pC0, int sdc, double *pW); -void kernel_dgelqf_4_lib4(int n, double *pD, double *dD); -void kernel_dgelqf_vs_lib4(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dlarft_4_lib4(int kmax, double *pD, double *dD, double *pT); -void kernel_dlarft_3_lib4(int kmax, double *pD, double *dD, double *pT); -void kernel_dlarft_2_lib4(int kmax, double *pD, double *dD, double *pT); -void kernel_dlarft_1_lib4(int kmax, double *pD, double *dD, double *pT); -void kernel_dgelqf_dlarft12_12_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_dlarft4_12_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_dlarft4_8_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_dlarft4_4_lib4(int n, double *pD, double *dD, double *pT); -void kernel_dlarfb12_rn_12_lib4(int kmax, double *pV, int sdd, double *pT, double *pD, double *pK); -void kernel_dlarfb12_rn_4_lib4(int kmax, double *pV, int sdd, double *pT, double *pD, double *pK, int km); -void kernel_dlarfb4_rn_12_lib4(int kmax, double *pV, double *pT, double *pD, int sdd); -void kernel_dlarfb4_rn_8_lib4(int kmax, double *pV, double *pT, double *pD, int sdd); -void kernel_dlarfb4_rn_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb3_rn_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb2_rn_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb1_rn_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb4_rn_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb3_rn_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb2_rn_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb1_rn_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb4_rt_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb3_rt_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb2_rt_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb1_rt_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb4_rt_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb3_rt_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb2_rt_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb1_rt_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dgelqf_pd_dlarft12_12_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_pd_dlarft4_8_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_pd_dlarft4_4_lib4(int n, double *pD, double *dD, double *pT); -void kernel_dgelqf_pd_4_lib4(int n, double *pD, double *dD); -void kernel_dgelqf_pd_vs_lib4(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dgelqf_pd_la_vs_lib4(int m, int n1, int k, int offD, double *pD, int sdd, double *dD, int offA, double *pA, int sda); -void kernel_dlarft_4_la_lib4(int n1, double *dD, double *pA, double *pT); -void kernel_dlarfb4_rn_12_la_lib4(int n1, double *pVA, double *pT, double *pD, int sdd, double *pA, int sda); -void kernel_dlarfb4_rn_8_la_lib4(int n1, double *pVA, double *pT, double *pD, int sdd, double *pA, int sda); -void kernel_dlarfb4_rn_4_la_lib4(int n1, double *pVA, double *pT, double *pD, double *pA); -void kernel_dlarfb4_rn_1_la_lib4(int n1, double *pVA, double *pT, double *pD, double *pA); -void kernel_dgelqf_pd_lla_vs_lib4(int m, int n0, int n1, int k, int offD, double *pD, int sdd, double *dD, int offL, double *pL, int sdl, int offA, double *pA, int sda); -void kernel_dlarft_4_lla_lib4(int n0, int n1, double *dD, double *pL, double *pA, double *pT); -void kernel_dlarfb4_rn_12_lla_lib4(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, int sdd, double *pL, int sdl, double *pA, int sda); -void kernel_dlarfb4_rn_8_lla_lib4(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, int sdd, double *pL, int sdl, double *pA, int sda); -void kernel_dlarfb4_rn_4_lla_lib4(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA); -void kernel_dlarfb4_rn_1_lla_lib4(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA); -// 4x2 -void kernel_dpotrf_nt_l_4x2_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dpotrf_nt_l_4x2_vs_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int km, int kn); -// 2x2 -void kernel_dpotrf_nt_l_2x2_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dpotrf_nt_l_2x2_vs_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int km, int kn); -// 12 -void kernel_dgetrf_pivot_12_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_12_vs_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv, int n); -// 8 -void kernel_dgetrf_pivot_8_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_8_vs_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv, int n); -// 4 -void kernel_dgetrf_pivot_4_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_4_vs_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv, int n1); -// vector -void kernel_drowsw_lib4(int kmax, double *pA, double *pC); - - - -// merged routines -// 12x4 -void kernel_dgemm_dtrsm_nt_rl_inv_12x4_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_12x4_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dsyrk_dpotrf_nt_l_12x4_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_12x4_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 4x12 -void kernel_dgemm_dtrsm_nt_rl_inv_4x12_vs_lib4(int kp, double *Ap, double *Bp, int sdbp, int km_, double *Am, double *Bm, int sdbm, double *C, double *D, double *E, int sde, double *inv_diag_E, int km, int kn); -// 8x8 -void kernel_dsyrk_dpotrf_nt_l_8x8_lib4(int kp, double *Ap, int sdap, double *Bp, int sdbp, int km_, double *Am, int sdam, double *Bm, int sdbm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_8x8_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int sdbp, int km_, double *Am, int sdam, double *Bm, int sdbm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgemm_dtrsm_nt_rl_inv_8x8l_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int sdb, int km_, double *Am, int sdam, double *Bm, int sdbm, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dgemm_dtrsm_nt_rl_inv_8x8u_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int sdb, int km_, double *Am, int sdam, double *Bm, int sdbm, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -// 8x4 -void kernel_dgemm_dtrsm_nt_rl_inv_8x4_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_8x4_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dsyrk_dpotrf_nt_l_8x4_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_8x4_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 4x8 -void kernel_dgemm_dtrsm_nt_rl_inv_4x8_vs_lib4(int kp, double *Ap, double *Bp, int sdbp, int km_, double *Am, double *Bm, int sdbm, double *C, double *D, double *E, int sde, double *inv_diag_E, int km, int kn); -// 4x4 -void kernel_dgemm_dtrsm_nt_rl_inv_4x4_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_4x4_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dsyrk_dpotrf_nt_l_4x4_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_4x4_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D, int km, int kn); -// 4x2 -void kernel_dgemm_dtrsm_nt_rl_inv_4x2_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_4x2_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dsyrk_dpotrf_nt_l_4x2_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_4x2_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D, int km, int kn); -// 2x2 -void kernel_dsyrk_dpotrf_nt_l_2x2_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_2x2_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D, int km, int kn); - -/* - * - * Auxiliary routines - * - * cpsc copy and scale, scale - * cp copy - * add - * set and scale - * transpose and scale - * set and scale - * - */ - -// copy and scale -void kernel_dgecpsc_8_0_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgecpsc_8_1_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgecpsc_8_2_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgecpsc_8_3_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B, int sdb); - -void kernel_dgecpsc_4_0_lib4(int tri, int kmax, double alpha, double *A, double *B); -void kernel_dgecpsc_4_1_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgecpsc_4_2_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgecpsc_4_3_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); - -void kernel_dgecpsc_3_0_lib4(int tri, int kmax, double alpha, double *A, double *B); -void kernel_dgecpsc_3_2_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgecpsc_3_3_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); - -void kernel_dgecpsc_2_0_lib4(int tri, int kmax, double alpha, double *A, double *B); -void kernel_dgecpsc_2_3_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); - -void kernel_dgecpsc_1_0_lib4(int tri, int kmax, double alpha, double *A, double *B); - -// copy only -void kernel_dgecp_8_0_lib4(int tri, int kmax, double *A, int sda, double *B, int sdb); - -void kernel_dgecp_4_0_lib4(int tri, int kmax, double *A, double *B); - -// add -void kernel_dgead_8_0_lib4(int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgead_8_1_lib4(int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgead_8_2_lib4(int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgead_8_3_lib4(int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgead_4_0_lib4(int kmax, double alpha, double *A, double *B); -void kernel_dgead_4_1_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_4_2_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_4_3_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_3_0_lib4(int kmax, double alpha, double *A, double *B); -void kernel_dgead_3_2_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_3_3_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_2_0_lib4(int kmax, double alpha, double *A, double *B); -void kernel_dgead_2_3_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_1_0_lib4(int kmax, double alpha, double *A, double *B); - -// set -void kernel_dgeset_4_lib4(int kmax, double alpha, double *A); -void kernel_dtrset_4_lib4(int kmax, double alpha, double *A); - -// traspose -void kernel_dgetr_8_lib4(int tri, int kmax, int kna, double alpha, double *A, int sda, double *C, int sdc); -void kernel_dgetr_4_lib4(int tri, int kmax, int kna, double alpha, double *A, double *C, int sdc); -void kernel_dgetr_3_lib4(int tri, int kmax, int kna, double alpha, double *A, double *C, int sdc); -void kernel_dgetr_2_lib4(int tri, int kmax, int kna, double alpha, double *A, double *C, int sdc); -void kernel_dgetr_1_lib4(int tri, int kmax, int kna, double alpha, double *A, double *C, int sdc); -void kernel_dgetr_4_0_lib4(int m, double *A, int sda, double *B); - - - -// pack -// 12 -void kernel_dpack_nn_12_lib4(int kmax, double *A, int lda, double *B, int sdb); -void kernel_dpack_nn_12_vs_lib4(int kmax, double *A, int lda, double *B, int sdb, int m1); -void kernel_dpack_tt_12_lib4(int kmax, double *A, int lda, double *B, int sdb); -// 8 -void kernel_dpack_nn_8_lib4(int kmax, double *A, int lda, double *B, int sdb); -void kernel_dpack_nn_8_vs_lib4(int kmax, double *A, int lda, double *B, int sdb, int m1); -void kernel_dpack_tt_8_lib4(int kmax, double *A, int lda, double *B, int sdb); -// 4 -void kernel_dpack_nn_4_lib4(int kmax, double *A, int lda, double *B); -void kernel_dpack_nn_4_vs_lib4(int kmax, double *A, int lda, double *B, int m1); -void kernel_dpack_tn_4_p0_lib4(int kmax, double *A, int lda, double *B); -void kernel_dpack_tn_4_lib4(int kmax, double *A, int lda, double *B); -void kernel_dpack_tn_4_vs_lib4(int kmax, double *A, int lda, double *B, int m1); -void kernel_dpack_tt_4_lib4(int kmax, double *A, int lda, double *B, int sdb); -void kernel_dpack_tt_4_vs_lib4(int kmax, double *A, int lda, double *B, int sdb, int m1); -// unpack -// 12 -void kernel_dunpack_nn_12_lib4(int kmax, double *A, int sda, double *B, int ldb); -void kernel_dunpack_nn_12_vs_lib4(int kmax, double *A, int sda, double *B, int ldb, int m1); -void kernel_dunpack_tt_12_lib4(int kmax, double *A, int sda, double *B, int ldb); -// 8 -void kernel_dunpack_nn_8_lib4(int kmax, double *A, int sda, double *B, int ldb); -void kernel_dunpack_nn_8_vs_lib4(int kmax, double *A, int sda, double *B, int ldb, int m1); -void kernel_dunpack_tt_8_lib4(int kmax, double *A, int sda, double *B, int ldb); -// 4 -void kernel_dunpack_nn_4_lib4(int kmax, double *A, double *B, int ldb); -void kernel_dunpack_nn_4_vs_lib4(int kmax, double *A, double *B, int ldb, int m1); -void kernel_dunpack_nt_4_lib4(int kmax, double *A, double *B, int ldb); -void kernel_dunpack_nt_4_vs_lib4(int kmax, double *A, double *B, int ldb, int m1); -void kernel_dunpack_tt_4_lib4(int kmax, double *A, int sda, double *B, int ldb); - -// panel copy -// 12 -void kernel_dpacp_nn_12_lib4(int kmax, int offsetA, double *A, int sda, double *B, int sdb); -void kernel_dpacp_nn_12_vs_lib4(int kmax, int offsetA, double *A, int sda, double *B, int sdb, int m1); -// 8 -void kernel_dpacp_nn_8_lib4(int kmax, int offsetA, double *A, int sda, double *B, int sdb); -void kernel_dpacp_nn_8_vs_lib4(int kmax, int offsetA, double *A, int sda, double *B, int sdb, int m1); -// 4 -void kernel_dpacp_nt_4_lib4(int kmax, double *A, int offsetB, double *B, int sdb); -void kernel_dpacp_tn_4_lib4(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_nn_4_lib4(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_nn_4_vs_lib4(int kmax, int offsetA, double *A, int sda, double *B, int m1); - - - -/************************************************ -* BLAS API kernels -************************************************/ - -//#if defined(BLAS_API) - -// A, B panel-major bs=4; C, D column-major -// 12x4 -void kernel_dgemm_nt_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_12x4_p0_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -void kernel_dsyrk_nt_l_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_u_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_u_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_12x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_12x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyr2k_nt_l_12x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyr2k_nt_l_12x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_12x4_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_12x4_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nt_ll_inv_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nt_ll_inv_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_12x4_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_rl_one_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_ru_inv_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_ru_one_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dpotrf_nt_l_12x4_lib44cc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *dD); -void kernel_dpotrf_nt_l_12x4_vs_lib44cc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); -// 4x12 -void kernel_dgemm_nt_4x12_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x12_vs_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x12_p0_vs_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1, double *A_p, double *B_p); -void kernel_dtrmm_nt_rl_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -// 8x8 -void kernel_dsyrk_nt_l_8x8_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_8x8_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_u_8x8_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_u_8x8_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_8x8_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_8x8_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyr2k_nt_l_8x8_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyr2k_nt_l_8x8_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dpotrf_nt_l_8x8_lib44cc(int kmax, double *A, int sda, double *B, int sdb, double *C, int ldc, double *D, int ldd, double *dD); -void kernel_dpotrf_nt_l_8x8_vs_lib44cc(int kmax, double *A, int sda, double *B, int sdb, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); -// 8x4 -void kernel_dgemm_nt_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_8x4_p0_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -void kernel_dgemm_nt_8x4_p_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *A_p); -void kernel_dsyrk_nt_l_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_u_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_u_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_8x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_8x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyr2k_nt_l_8x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyr2k_nt_l_8x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_8x4_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_8x4_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nt_ll_inv_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nt_ll_inv_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_8x4_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_rl_one_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_ru_inv_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_ru_one_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dpotrf_nt_l_8x4_lib44cc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *dD); -void kernel_dpotrf_nt_l_8x4_vs_lib44cc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); -// 4x8 -void kernel_dgemm_nt_4x8_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x8_vs_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x8_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x8_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x8_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x8_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x8_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x8_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x8_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x8_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -// 4x4 -void kernel_dgemm_nt_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_l_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_u_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_u_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_4x4_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_4x4_vs_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyr2k_nt_l_4x4_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyr2k_nt_l_4x4_vs_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nt_ll_inv_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_ll_inv_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_4x4_lib44ccc(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib44ccc(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_rl_one_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_ru_inv_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_ru_one_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dpotrf_nt_l_4x4_lib44cc(int kmax, double *A, double *B, double *C, int ldc, double *D, int ldd, double *dD); -void kernel_dpotrf_nt_l_4x4_vs_lib44cc(int kmax, double *A, double *B, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); -// 4x2 -void kernel_dgemm_nt_4x2_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); - -// A panel-major bs=4; B, C, D column-major -// 12x4 -void kernel_dgemm_nn_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_l_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_12x4_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_12x4_vs_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nn_ll_inv_12x4_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_12x4_vs_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ll_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_rl_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dgetrf_nn_l_12x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_l_12x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -void kernel_dgetrf_nn_m_12x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_m_12x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -void kernel_dgetrf_nn_r_12x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_r_12x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -// 4x12 -void kernel_dgemm_nn_4x12_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x12_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x12_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x12_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_rl_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_ru_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -// 8x4 -void kernel_dgemm_nn_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_l_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_8x4_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_8x4_vs_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nn_ll_inv_8x4_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_8x4_vs_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ll_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_rl_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dgetrf_nn_l_8x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_l_8x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -void kernel_dgetrf_nn_r_8x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_r_8x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -// 4x8 -void kernel_dgemm_nn_4x8_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x8_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x8_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x8_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_rl_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_ru_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -// 4x4 -void kernel_dgemm_nn_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_l_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_4x4_lib4ccc(int kmax, double *alpha, double *A0, double *B0, int ldb0, double *A1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_4x4_vs_lib4ccc(int kmax, double *alpha, double *A0, double *B0, int ldb0, double *A1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nn_rl_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nn_ru_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nn_ll_inv_4x4_lib4ccc4(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_4x4_vs_lib4ccc4(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ll_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_rl_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dgetrf_nn_4x4_lib4ccc(int kmax, double *A, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_4x4_vs_lib4ccc(int kmax, double *A, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); - -// B panel-major bs=4; A, C, D column-major -// 12x4 -void kernel_dgemm_nt_12x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_12x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_12x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_12x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x12 -void kernel_dgemm_nt_4x12_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x12_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x12_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x12_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x4 -void kernel_dgemm_nt_8x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x8 -void kernel_dgemm_nt_4x8_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x8_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x8_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x8_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x4 -void kernel_dgemm_nt_4x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - -// A, C, D panel-major; B, E column-major -// TODO merge with above -// 12x4 -void kernel_dtrsm_nn_rl_inv_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -// 8x4 -void kernel_dtrsm_nn_rl_inv_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -// 4x4 -void kernel_dtrsm_nn_rl_inv_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde); -void kernel_dtrsm_nn_rl_one_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde); -void kernel_dtrsm_nn_ru_one_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde); -void kernel_dtrsm_nt_rl_one_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde); -void kernel_dtrsm_nt_ru_one_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, int m1, int n1); - -// A, B, C, D column-major -// 12x4 -void kernel_dgemm_nn_12x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_12x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_12x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_12x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_12x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_12x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x12 -void kernel_dgemm_nn_4x12_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x12_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x12_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x12_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x12_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x12_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x4 -void kernel_dgemm_nn_8x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_8x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_8x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x8 -void kernel_dgemm_nn_4x8_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x8_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x8_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x8_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x8_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x8_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x4 -void kernel_dgemm_nn_4x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - -// A column-major -// 12 -void kernel_dgetrf_pivot_12_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_12_vs_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv, int n); -// 8 -void kernel_dgetrf_pivot_8_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_8_vs_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv, int n); -// 4 -void kernel_dgetrf_pivot_4_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_4_vs_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv, int n); - -// vector -void kernel_ddot_11_lib(int n, double *x, double *y, double *res); -void kernel_daxpy_11_lib(int n, double *alpha, double *x, double *y); -void kernel_drowsw_lib(int kmax, double *pA, int lda, double *pC, int ldc); - -//#endif // BLAS_API - - - -// larger kernels -// 12 -void kernel_dgemm_nt_12xn_p0_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -void kernel_dgemm_nt_12xn_pl_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -void kernel_dgemm_nt_mx12_p0_lib44cc(int m, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -// 8 -void kernel_dgemm_nt_8xn_p0_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); - - - -// A, B panel-major bs=8; C, D column-major -// 24x8 -void kernel_dgemm_nt_24x8_lib88cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_24x8_vs_lib88cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 16x8 -void kernel_dgemm_nt_16x8_lib88cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_16x8_vs_lib88cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x8 -void kernel_dgemm_nt_8x8_lib88cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x8_vs_lib88cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - -// A, panel-major bs=8; B, C, D column-major -// 24x8 -void kernel_dgemm_nt_24x8_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_24x8_vs_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nn_24x8_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_24x8_vs_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 16x8 -void kernel_dgemm_nt_16x8_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_16x8_vs_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nn_16x8_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_16x8_vs_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x8 -void kernel_dgemm_nt_8x8_lib8ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x8_vs_lib8ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nn_8x8_lib8ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_8x8_vs_lib8ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - -// B, panel-major bs=8; A, C, D column-major -// 8x24 -void kernel_dgemm_nt_8x24_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x24_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x24_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x24_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x16 -void kernel_dgemm_nt_8x16_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x16_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x16_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x16_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x8 -void kernel_dgemm_nt_8x8_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x8_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x8_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x8_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - - -// level 2 BLAS -void kernel_dgemv_n_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); -void kernel_dgemv_n_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); -void kernel_dgemv_t_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *beta, double *y, double *z, int km); -void kernel_dsymv_l_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); -void kernel_dsymv_l_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); -void kernel_dsymv_u_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); -void kernel_dsymv_u_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); -void kernel_dger_4_libc(int kmax, double *alpha, double *x, double *y, double *C, int ldc, double *D, int ldd); -void kernel_dger_4_vs_libc(int kmax, double *alpha, double *x, double *y, double *C, int ldc, double *D, int ldd, int km); - - - -// aux -void kernel_dvecld_inc1(int kmax, double *x); -void kernel_dveccp_inc1(int kmax, double *x, double *y); - -//void kernel_dgetr_nt_8_p0_lib(int kmax, double *A, int lda, double *C, int ldc, double *Ap, double *Bp); -//void kernel_dgetr_nt_8_lib(int kmax, double *A, int lda, double *C, int ldc); -//void kernel_dgetr_nt_4_lib(int kmax, double *A, int lda, double *C, int ldc); -void kernel_dgetr_tn_8_p0_lib(int kmax, double *A, int lda, double *C, int ldc, double *Ap, double *Bp); -void kernel_dgetr_tn_8_lib(int kmax, double *A, int lda, double *C, int ldc); -void kernel_dgetr_tn_4_lib(int kmax, double *A, int lda, double *C, int ldc); -void kernel_dgetr_tn_4_vs_lib(int kmax, double *A, int lda, double *C, int ldc, int m1); - - -// building blocks for blocked algorithms -// -void blasfeo_hp_dgemm_nt_m2(int m, int n, int k, double alpha, double *pA, int sda, double *pB, int sdb, double beta, double *C, int ldc, double *D, int ldd); -void blasfeo_hp_dgemm_nt_n2(int m, int n, int k, double alpha, double *pA, int sda, double *pB, int sdb, double beta, double *C, int ldc, double *D, int ldd); -// -void kernel_dpack_buffer_fn(int m, int n, double *A, int lda, double *pA, int sda); -void kernel_dpack_buffer_ft(int m, int n, double *A, int lda, double *pA, int sda); -void kernel_dpack_buffer_ln(int m, double *A, int lda, double *pA, int sda); -void kernel_dpack_buffer_lt(int m, double *A, int lda, double *pA, int sda); -void kernel_dpack_buffer_ut(int m, double *A, int lda, double *pA, int sda); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_KERNEL_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_i_aux_ext_dep.h b/third_party/acados/include/blasfeo/include/blasfeo_i_aux_ext_dep.h deleted file mode 100644 index 74c3fb5c0a22ff..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_i_aux_ext_dep.h +++ /dev/null @@ -1,69 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_I_AUX_EXT_DEP_H_ -#define BLASFEO_I_AUX_EXT_DEP_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef EXT_DEP - -// i_aux_extern_depend_lib -void int_zeros(int **pA, int row, int col); -void int_zeros_align(int **pA, int row, int col); -void int_free(int *pA); -void int_free_align(int *pA); -void int_print_mat(int row, int col, int *A, int lda); -int int_print_to_string_mat(char **buf_out, int row, int col, int *A, int lda); - -#endif // EXT_DEP - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_I_AUX_EXT_DEP_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_m_aux.h b/third_party/acados/include/blasfeo/include/blasfeo_m_aux.h deleted file mode 100644 index 6248853e292fd2..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_m_aux.h +++ /dev/null @@ -1,57 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_M_AUX_H_ -#define BLASFEO_M_AUX_H_ - -#include "blasfeo_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -void blasfeo_cvt_d2s_vec(int m, struct blasfeo_dvec *vd, int vdi, struct blasfeo_svec *vs, int vsi); -void blasfeo_cvt_s2d_vec(int m, struct blasfeo_svec *vs, int vsi, struct blasfeo_dvec *vd, int vdi); -void blasfeo_cvt_d2s_mat(int m, int n, struct blasfeo_dmat *Md, int mid, int nid, struct blasfeo_smat *Ms, int mis, int nis); -void blasfeo_cvt_s2d_mat(int m, int n, struct blasfeo_smat *Ms, int mis, int nis, struct blasfeo_dmat *Md, int mid, int nid); - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_M_AUX_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_memory.h b/third_party/acados/include/blasfeo/include/blasfeo_memory.h deleted file mode 100644 index da4e7fa090078a..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_memory.h +++ /dev/null @@ -1,62 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2020 by Gianluca Frison. * -* All rights reserved. * -* * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -#ifndef BLASFEO_MEMORY_H_ -#define BLASFEO_MEMORY_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -int blasfeo_is_init(); -// -void blasfeo_init(); -// -void blasfeo_quit(); -// -void *blasfeo_get_buffer(); - - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_MEMORY_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_naming.h b/third_party/acados/include/blasfeo/include/blasfeo_naming.h deleted file mode 100644 index c289443b176793..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_naming.h +++ /dev/null @@ -1,77 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -/* - * ----------- Naming conventions - * - * (precision)(data) - * - * 1) d(double) - * s(single) - * - * 2) ge(general) - * tr(triangular) - * vec(vector) - * row(row) - * col(column) - * dia(diagonal) - * - * 3) se(set) - * cp(copy) - * sc(scale) - * ad(add) - * tr(transpose) - * in(insert) - * ex(extract) - * pe(premute) - * sw(swap) - * - * f(factorization) - * - * lqf(LQ factorization) - * qrf (factorization) - * trf (LU factorization using partial pivoting with row interchanges.) - * - * 4) _l(lower) / _u(upper) - * _lib8 (hp implementation, 8 rows kernel) - * _lib4 (hp implementation, 4 rows kernel) - * _lib0 (hp interface with reference implentation) - * _lib (reference implementation) - * _libref (reference implementation with dedicated namespace) - * - * 5) _sp(sparse) - * _exp(exponential format) - */ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h b/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h deleted file mode 100644 index 67a0a4da049bfb..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h +++ /dev/null @@ -1,88 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Ian McInerney * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_PROCESSOR_FEATURES_H_ -#define BLASFEO_PROCESSOR_FEATURES_H_ - -/** - * Flags to indicate the different processor features - */ -//enum -//{ -// // x86-64 CPU features -// BLASFEO_PROCESSOR_FEATURE_AVX = 0x0001, /// AVX instruction set -// BLASFEO_PROCESSOR_FEATURE_AVX2 = 0x0002, /// AVX2 instruction set -// BLASFEO_PROCESSOR_FEATURE_FMA = 0x0004, /// FMA instruction set -// BLASFEO_PROCESSOR_FEATURE_SSE3 = 0x0008, /// SSE3 instruction set -// -// // ARM CPU features -// BLASFEO_PROCESSOR_FEATURE_VFPv3 = 0x0100, /// VFPv3 instruction set -// BLASFEO_PROCESSOR_FEATURE_NEON = 0x0100, /// NEON instruction set -// BLASFEO_PROCESSOR_FEATURE_VFPv4 = 0x0100, /// VFPv4 instruction set -// BLASFEO_PROCESSOR_FEATURE_NEONv2 = 0x0100, /// NEONv2 instruction set -//} BLASFEO_PROCESSOR_FEATURES; - -/** - * Test the features that this processor provides against what the library was compiled with. - * - * @param features - Pointer to an integer to store the supported feature set (using the flags in the BLASFEO_PROCESSOR_FEATURES enum) - * @return 0 if current processor doesn't support all features required for this library, 1 otherwise - */ -int blasfeo_processor_cpu_features( int* features ); - -/** - * Test the features that this processor provides against what the library was compiled with. - * - * @param features - Pointer to an integer to store the supported feature set (using the flags in the BLASFEO_PROCESSOR_FEATURES enum) - * @return 0 if current processor doesn't support all features required for this library, 1 otherwise - */ -void blasfeo_processor_library_features( int* features ); - -/** - * Create a string listing the features the current processor supports. - * - * @param features - Flags from the BLASFEO_PROCESSOR_FEATURES enum indicating the features supported - * @param featureString - Character array to store the feature string in - */ -void blasfeo_processor_feature_string( int features, char* featureString ); - -/** - * Get a string listing the processor features that this library version needs to run. - * - * @param featureString - Character array to store the feature string in - */ -void blasfeo_processor_library_string( char* featureString ); - -#endif // BLASFEO_PROCESSOR_FEATURES_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h deleted file mode 100644 index f43f5e83ce9b31..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h +++ /dev/null @@ -1,168 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_H_ -#define BLASFEO_S_AUX_H_ - - - -#include - -#include "blasfeo_s_aux_old.h" -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************ -* d_aux_lib.c -************************************************/ - -// returns the memory size (in bytes) needed for a smat -size_t blasfeo_memsize_smat(int m, int n); -size_t blasfeo_memsize_smat_ps(int ps, int m, int n); -// returns the memory size (in bytes) needed for the diagonal of a smat -size_t blasfeo_memsize_diag_smat(int m, int n); -// returns the memory size (in bytes) needed for a svec -size_t blasfeo_memsize_svec(int m); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_create_smat(int m, int n, struct blasfeo_smat *sA, void *memory); -void blasfeo_create_smat_ps(int ps, int m, int n, struct blasfeo_smat *sA, void *memory); -// create a strvec for a vector of size m by using memory passed by a pointer (pointer is not updated) -void blasfeo_create_svec(int m, struct blasfeo_svec *sA, void *memory); -void blasfeo_pack_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_pack_l_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_pack_u_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_pack_tran_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_pack_svec(int m, float *x, int xi, struct blasfeo_svec *sa, int ai); -void blasfeo_unpack_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void blasfeo_unpack_tran_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void blasfeo_unpack_svec(int m, struct blasfeo_svec *sa, int ai, float *x, int xi); -//void s_cast_mat2strmat(float *A, struct blasfeo_smat *sA); -//void s_cast_diag_mat2strmat(float *dA, struct blasfeo_smat *sA); -//void s_cast_vec2vecmat(float *a, struct blasfeo_svec *sa); - -// ge -void blasfeo_sgese(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sgecpsc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_sgecp(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_sgesc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sgein1(float a, struct blasfeo_smat *sA, int ai, int aj); -float blasfeo_sgeex1(struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sgead(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_sgetr(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// tr -void blasfeo_strcp_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_strtr_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_strtr_u(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// dia -void blasfeo_sdiare(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sdiaex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_sdiain(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sdiain_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_sdiaex_sp(int kmax, float alpha, int *idx, struct blasfeo_smat *sD, int di, int dj, struct blasfeo_svec *sx, int xi); -void blasfeo_sdiaad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sdiaad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_sdiaadin_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// row -void blasfeo_srowin(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_srowex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_srowad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_srowad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_srowsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_srowpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -void blasfeo_srowpei(int kmax, int *ipiv, struct blasfeo_smat *sA); -// col -void blasfeo_scolex(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_scolin(int kmax, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_scolad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_scolsc(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_scolsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_scolpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -void blasfeo_scolpei(int kmax, int *ipiv, struct blasfeo_smat *sA); -// vec -void blasfeo_svecse(int m, float alpha, struct blasfeo_svec *sx, int xi); -void blasfeo_sveccp(int m, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_svecsc(int m, float alpha, struct blasfeo_svec *sa, int ai); -void blasfeo_sveccpsc(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_svecad(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_svecin1(float a, struct blasfeo_svec *sx, int xi); -float blasfeo_svecex1(struct blasfeo_svec *sx, int xi); -void blasfeo_svecad_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -void blasfeo_svecin_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -void blasfeo_svecex_sp(int m, float alpha, int *idx, struct blasfeo_svec *sx, int x, struct blasfeo_svec *sz, int zi); -// z += alpha * x[idx] -void blasfeo_svecexad_sp(int m, double alpha, int *idx, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -void blasfeo_sveccl(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi); -void blasfeo_sveccl_mask(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi, struct blasfeo_svec *sm, int mi); -void blasfeo_svecze(int m, struct blasfeo_svec *sm, int mi, struct blasfeo_svec *sv, int vi, struct blasfeo_svec *se, int ei); -void blasfeo_svecnrm_inf(int m, struct blasfeo_svec *sx, int xi, float *ptr_norm); -void blasfeo_svecnrm_2(int m, struct blasfeo_svec *sx, int xi, float *ptr_norm); -void blasfeo_svecpe(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); -void blasfeo_svecpei(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); - - - -/* -* Explicitly panel-major matrix format -*/ - -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_pm_memsize_smat(int ps, int m, int n); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_pm_create_smat(int ps, int m, int n, struct blasfeo_pm_smat *sA, void *memory); - - - -/* -* Explicitly column-major matrix format -*/ - -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_cm_memsize_smat(int m, int n); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_cm_create_smat(int m, int n, struct blasfeo_pm_smat *sA, void *memory); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_AUX_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep.h deleted file mode 100644 index 5209d20d377c21..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep.h +++ /dev/null @@ -1,141 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_EXT_DEP_H_ -#define BLASFEO_S_AUX_EXT_DEP_H_ - - - -#include - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef EXT_DEP - -/************************************************ -* s_aux_extern_depend_lib.c -************************************************/ - -/* column-major matrices */ - -// dynamically allocate row*col floats of memory and set accordingly a pointer to float; set allocated memory to zero -void s_zeros(float **pA, int row, int col); -// dynamically allocate row*col floats of memory aligned to 64-byte boundaries and set accordingly a pointer to float; set allocated memory to zero -void s_zeros_align(float **pA, int row, int col); -// dynamically allocate size bytes of memory aligned to 64-byte boundaries and set accordingly a pointer to float; set allocated memory to zero -void s_zeros_align_bytes(float **pA, int size); -// free the memory allocated by d_zeros -void s_free(float *pA); -// free the memory allocated by d_zeros_align or d_zeros_align_bytes -void s_free_align(float *pA); -// print a column-major matrix -void s_print_mat(int m, int n, float *A, int lda); -// print the transposed of a column-major matrix -void s_print_tran_mat(int row, int col, float *A, int lda); -// print to file a column-major matrix -void s_print_to_file_mat(FILE *file, int row, int col, float *A, int lda); -// print to file a column-major matrix in exponential format -void s_print_to_file_exp_mat(FILE *file, int row, int col, float *A, int lda); -// print to string a column-major matrix -void s_print_to_string_mat(char **buf_out, int row, int col, float *A, int lda); -// print to file the transposed of a column-major matrix -void s_print_tran_to_file_mat(FILE *file, int row, int col, float *A, int lda); -// print to file the transposed of a column-major matrix in exponential format -void s_print_tran_to_file_exp_mat(FILE *file, int row, int col, float *A, int lda); -// print in exponential notation a column-major matrix -void s_print_exp_mat(int m, int n, float *A, int lda); -// print in exponential notation the transposed of a column-major matrix -void s_print_exp_tran_mat(int row, int col, float *A, int lda); - -/* strmat and strvec */ - -// create a strmat for a matrix of size m*n by dynamically allocating memory -void blasfeo_allocate_smat(int m, int n, struct blasfeo_smat *sA); -// create a strvec for a vector of size m by dynamically allocating memory -void blasfeo_allocate_svec(int m, struct blasfeo_svec *sa); -// free the memory allocated by blasfeo_allocate_dmat -void blasfeo_free_smat(struct blasfeo_smat *sA); -// free the memory allocated by blasfeo_allocate_dvec -void blasfeo_free_svec(struct blasfeo_svec *sa); -// print a strmat -void blasfeo_print_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print in exponential notation a strmat -void blasfeo_print_exp_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print to file a strmat -void blasfeo_print_to_file_smat(FILE *file, int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print to file a strmat in exponential format -void blasfeo_print_to_file_exp_smat(FILE *file, int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print to string a strmat -void blasfeo_print_to_string_smat(char **buf_out, int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print the transpose of a strmat -void blasfeo_print_tran_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print a strvec -void blasfeo_print_svec(int m, struct blasfeo_svec *sa, int ai); -// print in exponential notation a strvec -void blasfeo_print_exp_svec(int m, struct blasfeo_svec *sa, int ai); -// print to file a strvec -void blasfeo_print_to_file_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -// print to string a strvec -void blasfeo_print_to_string_svec(char **buf_out, int m, struct blasfeo_svec *sa, int ai); -// print the transposed of a strvec -void blasfeo_print_tran_svec(int m, struct blasfeo_svec *sa, int ai); -// print in exponential notation the transposed of a strvec -void blasfeo_print_exp_tran_svec(int m, struct blasfeo_svec *sa, int ai); -// print to file the transposed of a strvec -void blasfeo_print_to_file_tran_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -// print to string the transposed of a strvec -void blasfeo_print_to_string_tran_svec(char **buf_out, int m, struct blasfeo_svec *sa, int ai); - -#endif // EXT_DEP - - - -#ifdef __cplusplus -} -#endif - - - -#endif // BLASFEO_S_AUX_EXT_DEP_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep_ref.h deleted file mode 100644 index 6640e20a406c85..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep_ref.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_EXT_DEP_REF_H_ -#define BLASFEO_S_AUX_EXT_DEP_REF_H_ - -#if defined(EXT_DEP) - - - -#include - -#include "blasfeo_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// expose reference BLASFEO for testing -// see blasfeo_s_aux_exp_dep.h for help - -void blasfeo_print_smat_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_allocate_smat_ref(int m, int n, struct blasfeo_smat_ref *sA); -void blasfeo_allocate_svec_ref(int m, struct blasfeo_svec_ref *sa); -void blasfeo_free_smat_ref(struct blasfeo_smat_ref *sA); -void blasfeo_free_svec_ref(struct blasfeo_svec_ref *sa); -void blasfeo_print_smat_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_exp_smat_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_to_file_smat_ref(FILE *file, int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_to_file_exp_smat_ref(FILE *file, int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_to_string_smat_ref(char **buf_out, int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_svec(int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_exp_svec(int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_to_file_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_to_string_svec(char **buf_out, int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_tran_svec(int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_exp_tran_svec(int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_to_file_tran_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_to_string_tran_svec(char **buf_out, int m, struct blasfeo_svec *sa, int ai); - - -#ifdef __cplusplus -} -#endif - - - -#endif // EXT_DEP - -#endif // BLASFEO_S_AUX_EXT_DEP_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_old.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_old.h deleted file mode 100644 index 5c6db37bab1b1d..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_old.h +++ /dev/null @@ -1,64 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -// TODO remove -// -void strcp_l_lib(int m, float alpha, int offsetA, float *A, int sda, int offsetB, float *B, int sdb); -void sgead_lib(int m, int n, float alpha, int offsetA, float *A, int sda, int offsetB, float *B, int sdb); -void sgetr_lib(int m, int n, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -void strtr_l_lib(int m, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -void strtr_u_lib(int m, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -void sdiareg_lib(int kmax, float reg, int offset, float *pD, int sdd); -void sdiain_sqrt_lib(int kmax, float *x, int offset, float *pD, int sdd); -void sdiaex_lib(int kmax, float alpha, int offset, float *pD, int sdd, float *x); -void sdiaad_lib(int kmax, float alpha, float *x, int offset, float *pD, int sdd); -void sdiain_libsp(int kmax, int *idx, float alpha, float *x, float *pD, int sdd); -void sdiaex_libsp(int kmax, int *idx, float alpha, float *pD, int sdd, float *x); -void sdiaad_libsp(int kmax, int *idx, float alpha, float *x, float *pD, int sdd); -void sdiaadin_libsp(int kmax, int *idx, float alpha, float *x, float *y, float *pD, int sdd); -void srowin_lib(int kmax, float alpha, float *x, float *pD); -void srowex_lib(int kmax, float alpha, float *pD, float *x); -void srowad_lib(int kmax, float alpha, float *x, float *pD); -void srowin_libsp(int kmax, float alpha, int *idx, float *x, float *pD); -void srowad_libsp(int kmax, int *idx, float alpha, float *x, float *pD); -void srowadin_libsp(int kmax, int *idx, float alpha, float *x, float *y, float *pD); -void srowsw_lib(int kmax, float *pA, float *pC); -void scolin_lib(int kmax, float *x, int offset, float *pD, int sdd); -void scolad_lib(int kmax, float alpha, float *x, int offset, float *pD, int sdd); -void scolin_libsp(int kmax, int *idx, float *x, float *pD, int sdd); -void scolad_libsp(int kmax, float alpha, int *idx, float *x, float *pD, int sdd); -void scolsw_lib(int kmax, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -void svecin_libsp(int kmax, int *idx, float *x, float *y); -void svecad_libsp(int kmax, int *idx, float alpha, float *x, float *y); diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h deleted file mode 100644 index 998e1d89997175..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h +++ /dev/null @@ -1,147 +0,0 @@ - -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_REF_H_ -#define BLASFEO_S_AUX_REF_H_ - - - -#include - -#include "blasfeo_s_aux_old.h" -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************ -* d_aux_lib.c -************************************************/ - -// returns the memory size (in bytes) needed for a smat -size_t blasfeo_ref_memsize_smat(int m, int n); -size_t blasfeo_ref_memsize_smat_ps(int ps, int m, int n); -// returns the memory size (in bytes) needed for the diagonal of a smat -size_t blasfeo_ref_memsize_diag_smat(int m, int n); -// returns the memory size (in bytes) needed for a svec -size_t blasfeo_ref_memsize_svec(int m); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_ref_create_smat(int m, int n, struct blasfeo_smat *sA, void *memory); -void blasfeo_ref_create_smat_ps(int ps, int m, int n, struct blasfeo_smat *sA, void *memory); -// create a strvec for a vector of size m by using memory passed by a pointer (pointer is not updated) -void blasfeo_ref_create_svec(int m, struct blasfeo_svec *sA, void *memory); -void blasfeo_ref_pack_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_pack_l_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sB, int bi, int bj); -void blasfeo_ref_pack_l_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sB, int bi, int bj); -void blasfeo_ref_pack_tran_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_pack_svec(int m, float *x, int xi, struct blasfeo_svec *sa, int ai); -void blasfeo_ref_unpack_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void blasfeo_ref_unpack_tran_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void blasfeo_ref_unpack_svec(int m, struct blasfeo_svec *sa, int ai, float *x, int xi); -void ref_s_cast_mat2strmat(float *A, struct blasfeo_smat *sA); -void ref_s_cast_diag_mat2strmat(float *dA, struct blasfeo_smat *sA); -void ref_s_cast_vec2vecmat(float *a, struct blasfeo_svec *sa); - -// ge -void blasfeo_ref_sgese(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sgecpsc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_sgecp(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_sgesc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sgein1(float a, struct blasfeo_smat *sA, int ai, int aj); -float blasfeo_ref_sgeex1(struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sgead(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_sgetr(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// tr -void blasfeo_ref_strcp_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_strtr_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_strtr_u(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// dia -void blasfeo_ref_sdiare(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sdiaex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_sdiain(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sdiain_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_sdiaex_sp(int kmax, float alpha, int *idx, struct blasfeo_smat *sD, int di, int dj, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_sdiaad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sdiaad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_sdiaadin_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// row -void blasfeo_ref_srowin(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_srowex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_srowad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_srowad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_srowsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_srowpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -void blasfeo_ref_srowpei(int kmax, int *ipiv, struct blasfeo_smat *sA); -// col -void blasfeo_ref_scolex(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_scolin(int kmax, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_scolad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_scolsc(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_scolsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_scolpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -void blasfeo_ref_scolpei(int kmax, int *ipiv, struct blasfeo_smat *sA); -// vec -void blasfeo_ref_svecse(int m, float alpha, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_sveccp(int m, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_ref_svecsc(int m, float alpha, struct blasfeo_svec *sa, int ai); -void blasfeo_ref_sveccpsc(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_ref_svecad(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_ref_svecin1(float a, struct blasfeo_svec *sx, int xi); -float blasfeo_ref_svecex1(struct blasfeo_svec *sx, int xi); -void blasfeo_ref_svecad_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_svecin_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_svecex_sp(int m, float alpha, int *idx, struct blasfeo_svec *sx, int x, struct blasfeo_svec *sz, int zi); -// z += alpha * x[idx] -void blasfeo_ref_svecexad_sp(int m, double alpha, int *idx, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_sveccl(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_sveccl_mask(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi, struct blasfeo_svec *sm, int mi); -void blasfeo_ref_svecze(int m, struct blasfeo_svec *sm, int mi, struct blasfeo_svec *sv, int vi, struct blasfeo_svec *se, int ei); -void blasfeo_ref_svecnrm_inf(int m, struct blasfeo_svec *sx, int xi, float *ptr_norm); -void blasfeo_ref_svecpe(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_svecpei(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_AUX_REF_H_ - diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_test.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_test.h deleted file mode 100644 index 08d9a14a6a7de4..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_test.h +++ /dev/null @@ -1,177 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_TEST_H_ -#define BLASFEO_S_AUX_TEST_H_ - -#include - -#include "blasfeo_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -/************************************************ -* d_aux_lib.c -************************************************/ - -int test_blasfeo_memsize_smat(int m, int n); -int test_blasfeo_memsize_diag_smat(int m, int n); -int test_blasfeo_memsize_svec(int m); - -void test_blasfeo_create_smat(int m, int n, struct blasfeo_smat *sA, void *memory); -void test_blasfeo_create_svec(int m, struct blasfeo_svec *sA, void *memory); - -void test_blasfeo_pack_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_pack_svec(int m, float *x, int xi, struct blasfeo_svec *sa, int ai); -void test_blasfeo_pack_tran_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_unpack_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void test_blasfeo_unpack_svec(int m, struct blasfeo_svec *sa, int ai, float *x, int xi); -void test_blasfeo_unpack_tran_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); - -void test_s_cast_mat2strmat(float *A, struct blasfeo_smat *sA); -void test_s_cast_diag_mat2strmat(float *dA, struct blasfeo_smat *sA); -void test_s_cast_vec2vecmat(float *a, struct blasfeo_svec *sa); -// copy and scale -void test_blasfeo_sgecpsc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void test_blasfeo_sgecp(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void test_blasfeo_sgesc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); - -// void test_blasfeo_sgein1(float a, struct blasfeo_smat *sA, int ai, int aj); -// float test_blasfeo_sgeex1(struct blasfeo_smat *sA, int ai, int aj); -// void test_blasfeo_svecin1(float a, struct blasfeo_svec *sx, int xi); -// float test_blasfeo_svecex1(struct blasfeo_svec *sx, int xi); - -// // A <= alpha -// void test_blasfeo_sgese(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -// // a <= alpha -// void test_blasfeo_svecse(int m, float alpha, struct blasfeo_svec *sx, int xi); - - -// void test_blasfeo_sveccp(int m, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -// void test_blasfeo_svecsc(int m, float alpha, struct blasfeo_svec *sa, int ai); - -// void test_strcp_l_lib(int m, float alpha, int offsetA, float *A, int sda, int offsetB, float *B, int sdb); -// void test_blasfeo_strcp_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); - -// void test_sgead_lib(int m, int n, float alpha, int offsetA, float *A, int sda, int offsetB, float *B, int sdb); -// void test_blasfeo_sgead(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// void test_blasfeo_svecad(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); - -// void test_sgetr_lib(int m, int n, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -// void test_blasfeo_sgetr(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); - -// void test_strtr_l_lib(int m, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -// void test_blasfeo_strtr_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// void test_strtr_u_lib(int m, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -// void test_blasfeo_strtr_u(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); - -// void test_sdiareg_lib(int kmax, float reg, int offset, float *pD, int sdd); -// void test_blasfeo_sdiaex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -// void test_blasfeo_sdiain(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_sdiain_sqrt_lib(int kmax, float *x, int offset, float *pD, int sdd); -// void test_sdiaex_lib(int kmax, float alpha, int offset, float *pD, int sdd, float *x); -// void test_sdiaad_lib(int kmax, float alpha, float *x, int offset, float *pD, int sdd); -// void test_sdiain_libsp(int kmax, int *idx, float alpha, float *x, float *pD, int sdd); -// void test_blasfeo_sdiain_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// void test_sdiaex_libsp(int kmax, int *idx, float alpha, float *pD, int sdd, float *x); -// void test_blasfeo_sdiaex_sp(int kmax, float alpha, int *idx, struct blasfeo_smat *sD, int di, int dj, struct blasfeo_svec *sx, int xi); -// void test_blasfeo_sdiaad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_sdiaad_libsp(int kmax, int *idx, float alpha, float *x, float *pD, int sdd); -// void test_blasfeo_sdiaad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// void test_sdiaadin_libsp(int kmax, int *idx, float alpha, float *x, float *y, float *pD, int sdd); -// void test_blasfeo_sdiaadin_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// void test_srowin_lib(int kmax, float alpha, float *x, float *pD); -// void test_blasfeo_srowin(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_srowex_lib(int kmax, float alpha, float *pD, float *x); -// void test_blasfeo_srowex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -// void test_srowad_lib(int kmax, float alpha, float *x, float *pD); -// void test_blasfeo_srowad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_srowin_libsp(int kmax, float alpha, int *idx, float *x, float *pD); -// void test_srowad_libsp(int kmax, int *idx, float alpha, float *x, float *pD); -// void test_blasfeo_srowad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// void test_srowadin_libsp(int kmax, int *idx, float alpha, float *x, float *y, float *pD); -// void test_srowsw_lib(int kmax, float *pA, float *pC); -// void test_blasfeo_srowsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// void test_blasfeo_srowpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -// void test_scolin_lib(int kmax, float *x, int offset, float *pD, int sdd); -// void test_blasfeo_scolin(int kmax, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_scolad_lib(int kmax, float alpha, float *x, int offset, float *pD, int sdd); -// void test_scolin_libsp(int kmax, int *idx, float *x, float *pD, int sdd); -// void test_scolad_libsp(int kmax, float alpha, int *idx, float *x, float *pD, int sdd); -// void test_scolsw_lib(int kmax, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -// void test_blasfeo_scolsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// void test_blasfeo_scolpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -// void test_svecin_libsp(int kmax, int *idx, float *x, float *y); -// void test_svecad_libsp(int kmax, int *idx, float alpha, float *x, float *y); -// void test_blasfeo_svecad_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -// void test_blasfeo_svecin_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -// void test_blasfeo_svecex_sp(int m, float alpha, int *idx, struct blasfeo_svec *sx, int x, struct blasfeo_svec *sz, int zi); -// void test_blasfeo_sveccl(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi); -// void test_blasfeo_sveccl_mask(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi, struct blasfeo_svec *sm, int mi); -// void test_blasfeo_svecze(int m, struct blasfeo_svec *sm, int mi, struct blasfeo_svec *sv, int vi, struct blasfeo_svec *se, int ei); -// void test_blasfeo_svecnrm_inf(int m, struct blasfeo_svec *sx, int xi, float *ptr_norm); -// void test_blasfeo_svecpe(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); - - -// ext_dep - -void test_blasfeo_allocate_smat(int m, int n, struct blasfeo_smat *sA); -void test_blasfeo_allocate_svec(int m, struct blasfeo_svec *sa); - -void test_blasfeo_free_smat(struct blasfeo_smat *sA); -void test_blasfeo_free_svec(struct blasfeo_svec *sa); - -void test_blasfeo_print_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_print_svec(int m, struct blasfeo_svec *sa, int ai); -void test_blasfeo_print_tran_svec(int m, struct blasfeo_svec *sa, int ai); - -void test_blasfeo_print_to_file_smat(FILE *file, int m, int n, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_print_to_file_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -void test_blasfeo_print_to_file_tran_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); - -void test_blasfeo_print_exp_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_print_exp_svec(int m, struct blasfeo_svec *sa, int ai); -void test_blasfeo_print_exp_tran_svec(int m, struct blasfeo_svec *sa, int ai); - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_AUX_TEST_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blas.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blas.h deleted file mode 100644 index 200f1f51b1daac..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blas.h +++ /dev/null @@ -1,46 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_BLAS_H_ -#define BLASFEO_S_BLAS_H_ - - - -#include "blasfeo_s_blasfeo_api.h" -#include "blasfeo_s_blas_api.h" - - - -#endif // BLASFEO_S_BLAS_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h deleted file mode 100644 index cf2b3e0a2d1d36..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h +++ /dev/null @@ -1,182 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef BLASFEO_S_BLAS_API_H_ -#define BLASFEO_S_BLAS_API_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef BLAS_API -#ifdef CBLAS_API -#ifndef BLASFEO_CBLAS_ENUM -#define BLASFEO_CBLAS_ENUM -#ifdef FORTRAN_BLAS_API -#ifndef CBLAS_H -enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; -enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; -enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; -enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; -enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; -#endif // CBLAS_H -#else // FORTRAN_BLAS_API -enum BLASFEO_CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; -enum BLASFEO_CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; -enum BLASFEO_CBLAS_UPLO {CblasUpper=121, CblasLower=122}; -enum BLASFEO_CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; -enum BLASFEO_CBLAS_SIDE {CblasLeft=141, CblasRight=142}; -#endif // FORTRAN_BLAS_API -#endif // BLASFEO_CBLAS_ENUM -#endif // CBLAS_API -#endif // BLAS_API - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef BLAS_API - - - -#ifdef FORTRAN_BLAS_API - - - -// BLAS 1 -// -void saxpy_(int *n, float *alpha, float *x, int *incx, float *y, int *incy); -// -float sdot_(int *n, float *x, int *incx, float *y, int *incy); - -// BLAS 3 -// -void sgemm_(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); -// -void strsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); - - - -// LAPACK -// -void spotrf_(char *uplo, int *m, float *A, int *lda, int *info); - - - -#ifdef CBLAS_API - - - -// CBLAS 1 -// -void cblas_saxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY); - -// CBLAS 3 -// -void cblas_sgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); -// -void cblas_strsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const float alpha, const float *A, const int lda, float *B, const int ldb); - - - -#endif // CBLAS_API - - - -#else // BLASFEO_API - - - -// BLAS 1 -// -void blasfeo_blas_saxpy(int *n, float *alpha, float *x, int *incx, float *y, int *incy); -// -float blasfeo_blas_sdot(int *n, float *x, int *incx, float *y, int *incy); - -// BLAS 3 -// -void blasfeo_blas_sgemm(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); -// -void blasfeo_blas_strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); - - - -// LAPACK -// -void blasfeo_lapack_spotrf(char *uplo, int *m, float *A, int *lda, int *info); - - - -#ifdef CBLAS_API - - - -// CBLAS 1 -// -void blasfeo_cblas_saxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY); - -// CBLAS 3 -// -void blasfeo_cblas_sgemm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); -// -void blasfeo_cblas_strsm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const float alpha, const float *A, const int lda, float *B, const int ldb); - - - -#endif // CBLAS_API - - - -#endif // BLASFEO_API - - - -#endif // BLAS_API - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_BLAS_API_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h deleted file mode 100644 index 8b98104735fc6f..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h +++ /dev/null @@ -1,284 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_BLASFEO_API_H_ -#define BLASFEO_S_BLASFEO_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -// -// level 1 BLAS -// - -// z = y + alpha*x -void blasfeo_saxpy(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = beta*y + alpha*x -void blasfeo_saxpby(int kmax, float alpha, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = x .* y -void blasfeo_svecmul(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z += x .* y -void blasfeo_svecmulacc(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = x .* y, return sum(z) = x^T * y -float blasfeo_svecmuldot(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// return x^T * y -float blasfeo_sdot(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi); -// construct givens plane rotation -void blasfeo_srotg(float a, float b, float *c, float *s); -// apply plane rotation [a b] [c -s; s; c] to the aj0 and aj1 columns of A at row index ai -void blasfeo_scolrot(int m, struct blasfeo_smat *sA, int ai, int aj0, int aj1, float c, float s); -// apply plane rotation [c s; -s c] [a; b] to the ai0 and ai1 rows of A at column index aj -void blasfeo_srowrot(int m, struct blasfeo_smat *sA, int ai0, int ai1, int aj, float c, float s); - - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_sgemv_n(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A' * x -void blasfeo_sgemv_t(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(n) -void blasfeo_strsv_lnn_mn(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(n) -void blasfeo_strsv_ltn_mn(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, not_unit -void blasfeo_strsv_lnn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, unit -void blasfeo_strsv_lnu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, not_unit -void blasfeo_strsv_ltn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, unit -void blasfeo_strsv_ltu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, not_transposed, not_unit -void blasfeo_strsv_unn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, transposed, not_unit -void blasfeo_strsv_utn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A * x ; A lower triangular -void blasfeo_strmv_lnn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A * x ; A lower triangular, unit diagonal -void blasfeo_strmv_lnu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A lower triangular -void blasfeo_strmv_ltn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A lower triangular, unit diagonal -void blasfeo_strmv_ltu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A * x ; A upper triangular -void blasfeo_strmv_unn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A upper triangular -void blasfeo_strmv_utn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z_n <= beta_n * y_n + alpha_n * A * x_n -// z_t <= beta_t * y_t + alpha_t * A' * x_t -void blasfeo_sgemv_nt(int m, int n, float alpha_n, float alpha_t, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx_n, int xi_n, struct blasfeo_svec *sx_t, int xi_t, float beta_n, float beta_t, struct blasfeo_svec *sy_n, int yi_n, struct blasfeo_svec *sy_t, int yi_t, struct blasfeo_svec *sz_n, int zi_n, struct blasfeo_svec *sz_t, int zi_t); -// z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed -void blasfeo_ssymv_l(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -void blasfeo_ssymv_l_mn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed -void blasfeo_ssymv_u(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// D = C + alpha * x * y^T -void blasfeo_sger(int m, int n, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - -// diagonal - -// z <= beta * y + alpha * A * x, A diagonal -void blasfeo_sgemv_d(int m, float alpha, struct blasfeo_svec *sA, int ai, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); - - - -// -// level 3 BLAS -// - -// dense - -// D <= beta * C + alpha * A * B -void blasfeo_sgemm_nn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T -void blasfeo_sgemm_nt(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_sgemm_tn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_sgemm_tt(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D lower triangular -void blasfeo_ssyrk_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ssyrk_ln_mn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D lower triangular -void blasfeo_ssyrk_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D upper triangular -void blasfeo_ssyrk_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D upper triangular -void blasfeo_ssyrk_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^T ; B upper triangular -void blasfeo_strmm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_strmm_rlnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_strsm_llnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular with unit diagonal -void blasfeo_strsm_llnu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_strsm_lltn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular with unit diagonal -void blasfeo_strsm_lltu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_strsm_lunn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular withunit diagonal -void blasfeo_strsm_lunu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_strsm_lutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular withunit diagonal -void blasfeo_strsm_lutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_strsm_rlnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular with unit diagonal -void blasfeo_strsm_rlnu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_strsm_rltn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular with unit diagonal -void blasfeo_strsm_rltu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_strsm_runn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular with unit diagonal -void blasfeo_strsm_runu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_strsm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal -void blasfeo_strsm_rutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D lower triangular -void blasfeo_ssyr2k_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D lower triangular -void blasfeo_ssyr2k_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D upper triangular -void blasfeo_ssyr2k_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D upper triangular -void blasfeo_ssyr2k_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - -// diagonal - -// D <= alpha * A * B + beta * C, with A diagonal (stored as strvec) -void sgemm_diag_left_ib(int m, int n, float alpha, float *dA, float *pB, int sdb, float beta, float *pC, int sdc, float *pD, int sdd); -void blasfeo_sgemm_dn(int m, int n, float alpha, struct blasfeo_svec *sA, int ai, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A * B + beta * C, with B diagonal (stored as strvec) -void blasfeo_sgemm_nd(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sB, int bi, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - - - -// -// LAPACK -// - -// D <= chol( C ) ; C, D lower triangular -void blasfeo_spotrf_l(int m, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_spotrf_l_mn(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= chol( C ) ; C, D upper triangular -void blasfeo_spotrf_u(int m, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= chol( C + A * B' ) ; C, D lower triangular -void blasfeo_ssyrk_spotrf_ln(int m, int k, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ssyrk_spotrf_ln_mn(int m, int n, int k, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= lu( C ) ; no pivoting -void blasfeo_sgetrf_np(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= lu( C ) ; row pivoting -void blasfeo_sgetrf_rp(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, int *ipiv); -// D <= qr( C ) -void blasfeo_sgeqrf(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -int blasfeo_sgeqrf_worksize(int m, int n); // in bytes -// D <= Q factor, where C is the output of the LQ factorization -int blasfeo_sorglq_worksize(int m, int n, int k); // in bytes -void blasfeo_sorglq(int m, int n, int k, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -// D <= lq( C ) -void blasfeo_sgelqf(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -int blasfeo_sgelqf_worksize(int m, int n); // in bytes -// D <= lq( C ), positive diagonal elements -void blasfeo_sgelqf_pd(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -// [L, A] <= lq( [L, A] ), positive diagonal elements, array of matrices, with -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_sgelqf_pd_la(int m, int n1, struct blasfeo_smat *sL, int li, int lj, struct blasfeo_smat *sA, int ai, int aj, void *work); -// [L, L, A] <= lq( [L, L, A] ), positive diagonal elements, array of matrices, with: -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_sgelqf_pd_lla(int m, int n1, struct blasfeo_smat *sL0, int l0i, int l0j, struct blasfeo_smat *sL1, int l1i, int l1j, struct blasfeo_smat *sA, int ai, int aj, void *work); - - - - -// -// BLAS API helper functions -// - -#if ( defined(BLAS_API) & defined(MF_PANELMAJ) ) -// BLAS 3 -void blasfeo_cm_sgemm_nn(int m, int n, int k, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, float beta, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_sgemm_nt(int m, int n, int k, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, float beta, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_sgemm_tn(int m, int n, int k, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, float beta, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_sgemm_tt(int m, int n, int k, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, float beta, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_llnn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_llnu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lltn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lltu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lunn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lunu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lutn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lutu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rlnn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rlnu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rltn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rltu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_runn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_runu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rutn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rutu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -// LAPACK -void blasfeo_cm_spotrf_l(int m, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_spotrf_u(int m, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -#endif - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_BLASFEO_API_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api_ref.h deleted file mode 100644 index f429a79dc3f45d..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api_ref.h +++ /dev/null @@ -1,135 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_BLASFEO_API_REF_H_ -#define BLASFEO_S_BLASFEO_API_REF_H_ - -#include "blasfeo_common.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - -// expose reference BLASFEO for testing - -// --- level 1 - -void blasfeo_saxpy_ref(int kmax, float alpha, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_saxpby_ref(int kmax, float alpha, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_svecmul_ref(int m, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_svecmulacc_ref(int m, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -float blasfeo_svecmuldot_ref(int m, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -float blasfeo_sdot_ref(int m, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi); -void blasfeo_srotg_ref(float a, float b, float *c, float *s); -void blasfeo_scolrot_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj0, int aj1, float c, float s); -void blasfeo_srowrot_ref(int m, struct blasfeo_smat_ref *sA, int ai0, int ai1, int aj, float c, float s); - - -// --- level 2 - -// dense -void blasfeo_sgemv_n_ref(int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_sgemv_t_ref(int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_lnn_mn_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_ltn_mn_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_lnn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_lnu_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_ltn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_ltu_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_unn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_utn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_unn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_utn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_lnn_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_ltn_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_lnu_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_ltu_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_sgemv_nt_ref(int m, int n, float alpha_n, float alpha_t, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx_n, int xi_n, struct blasfeo_svec_ref *sx_t, int xi_t, float beta_n, float beta_t, struct blasfeo_svec_ref *sy_n, int yi_n, struct blasfeo_svec_ref *sy_t, int yi_t, struct blasfeo_svec_ref *sz_n, int zi_n, struct blasfeo_svec_ref *sz_t, int zi_t); -void blasfeo_ssymv_l_ref(int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); - -// diagonal -void blasfeo_sgemv_d_ref(int m, float alpha, struct blasfeo_svec_ref *sA, int ai, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); - - -// --- level 3 - -// dense -void blasfeo_sgemm_nn_ref( int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgemm_nt_ref( int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgemm_tn_ref(int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgemm_tt_ref(int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); - -void blasfeo_ssyrk_ln_mn_ref( int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_ln_ref( int m, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_lt_ref( int m, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_un_ref( int m, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_ut_ref( int m, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); - -void blasfeo_strmm_rutn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strmm_rlnn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_rltn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_rltu_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_rutn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_llnu_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_lunn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); - -// diagonal -void dgemm_diag_left_lib_ref(int m, int n, float alpha, float *dA, float *pB, int sdb, float beta, float *pC, int sdc, float *pD, int sdd); -void blasfeo_sgemm_dn_ref(int m, int n, float alpha, struct blasfeo_svec_ref *sA, int ai, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgemm_nd_ref(int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sB, int bi, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); - -// --- lapack - -void blasfeo_sgetrf_nopivot_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgetrf_rowpivot_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, int *ipiv); -void blasfeo_spotrf_l_ref(int m, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_spotrf_l_mn_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_dpotrf_ln_ref(int m, int k, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_dpotrf_ln_mn_ref(int m, int n, int k, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgetrf_nopivot_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgetrf_rowpivot_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, int *ipiv); -void blasfeo_sgeqrf_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, void *work); -void blasfeo_sgelqf_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, void *work); -void blasfeo_sgelqf_pd_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, void *work); -void blasfeo_sgelqf_pd_la_ref(int m, int n1, struct blasfeo_smat_ref *sL, int li, int lj, struct blasfeo_smat_ref *sA, int ai, int aj, void *work); -void blasfeo_sgelqf_pd_lla_ref(int m, int n1, struct blasfeo_smat_ref *sL0, int l0i, int l0j, struct blasfeo_smat_ref *sL1, int l1i, int l1j, struct blasfeo_smat_ref *sA, int ai, int aj, void *work); - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_BLASFEO_API_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h deleted file mode 100644 index 17cb17969577ef..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h +++ /dev/null @@ -1,252 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_BLASFEO_REF_API_H_ -#define BLASFEO_S_BLASFEO_REF_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -// -// level 1 BLAS -// - -// z = y + alpha*x -void blasfeo_ref_saxpy(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = beta*y + alpha*x -void blasfeo_ref_saxpby(int kmax, float alpha, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = x .* y -void blasfeo_ref_svecmul(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z += x .* y -void blasfeo_ref_svecmulacc(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = x .* y, return sum(z) = x^T * y -float blasfeo_ref_svecmuldot(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// return x^T * y -float blasfeo_ref_sdot(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi); -// construct givens plane rotation -void blasfeo_ref_srotg(float a, float b, float *c, float *s); -// apply plane rotation [a b] [c -s; s; c] to the aj0 and aj1 columns of A at row index ai -void blasfeo_ref_scolrot(int m, struct blasfeo_smat *sA, int ai, int aj0, int aj1, float c, float s); -// apply plane rotation [c s; -s c] [a; b] to the ai0 and ai1 rows of A at column index aj -void blasfeo_ref_srowrot(int m, struct blasfeo_smat *sA, int ai0, int ai1, int aj, float c, float s); - - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_ref_sgemv_n(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A' * x -void blasfeo_ref_sgemv_t(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(n) -void blasfeo_ref_strsv_lnn_mn(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(n) -void blasfeo_ref_strsv_ltn_mn(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, not_unit -void blasfeo_ref_strsv_lnn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, unit -void blasfeo_ref_strsv_lnu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, not_unit -void blasfeo_ref_strsv_ltn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, unit -void blasfeo_ref_strsv_ltu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, not_transposed, not_unit -void blasfeo_ref_strsv_unn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, transposed, not_unit -void blasfeo_ref_strsv_utn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A * x ; A lower triangular -void blasfeo_ref_strmv_lnn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A * x ; A lower triangular, unit diagonal -void blasfeo_ref_strmv_lnu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A lower triangular -void blasfeo_ref_strmv_ltn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A lower triangular, unit diagonal -void blasfeo_ref_strmv_ltu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A * x ; A upper triangular -void blasfeo_ref_strmv_unn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A upper triangular -void blasfeo_ref_strmv_utn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z_n <= beta_n * y_n + alpha_n * A * x_n -// z_t <= beta_t * y_t + alpha_t * A' * x_t -void blasfeo_ref_sgemv_nt(int m, int n, float alpha_n, float alpha_t, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx_n, int xi_n, struct blasfeo_svec *sx_t, int xi_t, float beta_n, float beta_t, struct blasfeo_svec *sy_n, int yi_n, struct blasfeo_svec *sy_t, int yi_t, struct blasfeo_svec *sz_n, int zi_n, struct blasfeo_svec *sz_t, int zi_t); -// z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed -void blasfeo_ref_ssymv_l(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_ssymv_l_mn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed -void blasfeo_ref_ssymv_u(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// D = C + alpha * x * y^T -void blasfeo_ref_sger(int m, int n, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - -// diagonal - -// z <= beta * y + alpha * A * x, A diagonal -void blasfeo_ref_sgemv_d(int m, float alpha, struct blasfeo_svec *sA, int ai, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); - - - -// -// level 3 BLAS -// - -// dense - -// D <= beta * C + alpha * A * B -void blasfeo_ref_sgemm_nn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T -void blasfeo_ref_sgemm_nt(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_ref_sgemm_tn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_ref_sgemm_tt(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D lower triangular -void blasfeo_ref_ssyrk_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_ssyrk_ln_mn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D lower triangular -void blasfeo_ref_ssyrk_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D upper triangular -void blasfeo_ref_ssyrk_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D upper triangular -void blasfeo_ref_ssyrk_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^T ; B upper triangular -void blasfeo_ref_strmm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_ref_strmm_rlnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_ref_strsm_llnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular with unit diagonal -void blasfeo_ref_strsm_llnu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_ref_strsm_lltn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular with unit diagonal -void blasfeo_ref_strsm_lltu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_lunn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular withunit diagonal -void blasfeo_ref_strsm_lunu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_lutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular withunit diagonal -void blasfeo_ref_strsm_lutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_rlnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular with unit diagonal -void blasfeo_ref_strsm_rlnu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_rltn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular with unit diagonal -void blasfeo_ref_strsm_rltu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_runn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular with unit diagonal -void blasfeo_ref_strsm_runu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal -void blasfeo_ref_strsm_rutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D lower triangular -void blasfeo_ref_ssyr2k_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D lower triangular -void blasfeo_ref_ssyr2k_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D upper triangular -void blasfeo_ref_ssyr2k_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D upper triangular -void blasfeo_ref_ssyr2k_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - -// diagonal - -// D <= alpha * A * B + beta * C, with A diagonal (stored as strvec) -void sgemm_diag_left_ib(int m, int n, float alpha, float *dA, float *pB, int sdb, float beta, float *pC, int sdc, float *pD, int sdd); -void blasfeo_ref_sgemm_dn(int m, int n, float alpha, struct blasfeo_svec *sA, int ai, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A * B + beta * C, with B diagonal (stored as strvec) -void blasfeo_ref_sgemm_nd(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sB, int bi, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - - - -// -// LAPACK -// - -// D <= chol( C ) ; C, D lower triangular -void blasfeo_ref_spotrf_l(int m, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_spotrf_l_mn(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= chol( C ) ; C, D upper triangular -void blasfeo_ref_spotrf_u(int m, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= chol( C + A * B' ) ; C, D lower triangular -void blasfeo_ref_ssyrk_spotrf_ln(int m, int k, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_ssyrk_spotrf_ln_mn(int m, int n, int k, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= lu( C ) ; no pivoting -void blasfeo_ref_sgetrf_np(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= lu( C ) ; row pivoting -void blasfeo_ref_sgetrf_rp(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, int *ipiv); -// D <= qr( C ) -void blasfeo_ref_sgeqrf(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -int blasfeo_ref_sgeqrf_worksize(int m, int n); // in bytes -// D <= Q factor, where C is the output of the LQ factorization -int blasfeo_ref_sorglq_worksize(int m, int n, int k); // in bytes -void blasfeo_ref_sorglq(int m, int n, int k, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -// D <= lq( C ) -void blasfeo_ref_sgelqf(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -int blasfeo_ref_sgelqf_worksize(int m, int n); // in bytes -// D <= lq( C ), positive diagonal elements -void blasfeo_ref_sgelqf_pd(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -// [L, A] <= lq( [L, A] ), positive diagonal elements, array of matrices, with -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_ref_sgelqf_pd_la(int m, int n1, struct blasfeo_smat *sL, int li, int lj, struct blasfeo_smat *sA, int ai, int aj, void *work); -// [L, L, A] <= lq( [L, L, A] ), positive diagonal elements, array of matrices, with: -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_ref_sgelqf_pd_lla(int m, int n1, struct blasfeo_smat *sL0, int l0i, int l0j, struct blasfeo_smat *sL1, int l1i, int l1j, struct blasfeo_smat *sA, int ai, int aj, void *work); - - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_BLASFEO_REF_API_H_ - diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_kernel.h b/third_party/acados/include/blasfeo/include/blasfeo_s_kernel.h deleted file mode 100644 index 99d2b28c823d57..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_kernel.h +++ /dev/null @@ -1,692 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_KERNEL_H_ -#define BLASFEO_S_KERNEL_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// utils -void blasfeo_align_2MB(void *ptr, void **ptr_align); -void blasfeo_align_4096_byte(void *ptr, void **ptr_align); -void blasfeo_align_64_byte(void *ptr, void **ptr_align); - - - -// -// lib8 -// - -// 24x4 -void kernel_sgemm_nt_24x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_nt_24x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_sgemm_nt_24x4_gen_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_sgemm_nn_24x4_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_nn_24x4_vs_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_sgemm_nn_24x4_gen_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_ssyrk_nt_l_24x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_ssyrk_nt_l_24x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_ssyrk_nt_l_20x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_ssyrk_nt_l_20x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_spotrf_nt_l_24x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_24x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_spotrf_nt_l_20x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_20x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_strsm_nt_rl_inv_24x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_24x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int km, int kn); -void kernel_sgemm_strsm_nt_rl_inv_24x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_24x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_20x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_20x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_ssyrk_spotrf_nt_l_24x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_24x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_strmm_nn_rl_24x4_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *D, int sdd); -void kernel_strmm_nn_rl_24x4_vs_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *D, int sdd, int km, int kn); - -// 16x8 -void kernel_sgemm_nt_16x8_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *spil); - -// 16x4 -void kernel_sgemm_nt_16x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_nt_16x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_sgemm_nt_16x4_gen_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_sgemm_nn_16x4_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_nn_16x4_vs_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_sgemm_nn_16x4_gen_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_ssyrk_nt_l_16x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_ssyrk_nt_l_16x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_ssyrk_nt_l_12x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_ssyrk_nt_l_12x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_spotrf_nt_l_16x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_16x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_spotrf_nt_l_12x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_12x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_strsm_nt_rl_inv_16x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_16x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int km, int kn); -void kernel_sgemm_strsm_nt_rl_inv_16x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_16x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_12x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_12x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_ssyrk_spotrf_nt_l_16x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_16x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_strmm_nn_rl_16x4_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *D, int sdd); -void kernel_strmm_nn_rl_16x4_vs_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *D, int sdd, int km, int kn); -void kernel_strmm_nn_rl_16x4_gen_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); - -// 8x8 -void kernel_sgemm_nt_8x8_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_nt_8x8_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nt_8x8_gen_lib8(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_sgemm_nn_8x8_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D); -void kernel_sgemm_nn_8x8_vs_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nn_8x8_gen_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_ssyrk_nt_l_8x8_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_ssyrk_nt_l_8x8_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_spotrf_nt_l_8x8_lib8(int k, float *A, float *B, float *C, float *D, float *inv_diag_D); -void kernel_spotrf_nt_l_8x8_vs_lib8(int k, float *A, float *B, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_strsm_nt_rl_inv_8x8_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_8x8_vs_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_sgemm_strsm_nt_rl_inv_8x8_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_8x8_vs_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_8x8_vs_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_8x8_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D); - -// 8x4 -void kernel_sgemm_nt_8x4_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_nt_8x4_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nt_8x4_gen_lib8(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_sgemm_nn_8x4_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D); -void kernel_sgemm_nn_8x4_vs_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nn_8x4_gen_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -//void kernel_ssyrk_nt_l_8x4_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_ssyrk_nt_l_8x4_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_spotrf_nt_l_8x4_lib8(int k, float *A, float *B, float *C, float *D, float *inv_diag_D); -void kernel_spotrf_nt_l_8x4_vs_lib8(int k, float *A, float *B, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_strsm_nt_rl_inv_8x4_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_8x4_vs_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_sgemm_strsm_nt_rl_inv_8x4_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_8x4_vs_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_8x4_vs_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_8x4_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D); -void kernel_strmm_nn_rl_8x4_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *D); -void kernel_strmm_nn_rl_8x4_vs_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *D, int km, int kn); -void kernel_strmm_nn_rl_8x4_gen_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_strmm_nt_ru_8x4_lib8(int k, float *alpha, float *A, float *B, float *D); -void kernel_strmm_nt_ru_8x4_vs_lib8(int k, float *alpha, float *A, float *B, float *D, int km, int kn); - -// 4x8 -void kernel_sgemm_nt_4x8_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_nt_4x8_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nt_4x8_gen_lib8(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_strsm_nt_rl_inv_4x8_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_4x8_vs_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); - -// 8 -void kernel_sgemv_n_8_lib8(int k, float *alpha, float *A, float *x, float *beta, float *y, float *z); -void kernel_sgemv_n_8_vs_lib8(int k, float *alpha, float *A, float *x, float *beta, float *y, float *z, int k1); -void kernel_sgemv_n_8_gen_lib8(int kmax, float *alpha, float *A, float *x, float *beta, float *y, float *z, int k0, int k1); -void kernel_sgemv_t_8_lib8(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z); -void kernel_sgemv_t_8_vs_lib8(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z, int k1); -void kernel_sgemv_t_4_lib8(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z); -void kernel_sgemv_t_4_vs_lib8(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z, int k1); -void kernel_strsv_ln_inv_8_lib8(int k, float *A, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_ln_inv_8_vs_lib8(int k, float *A, float *inv_diag_A, float *x, float *y, float *z, int km, int kn); -void kernel_strsv_lt_inv_8_lib8(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_lt_inv_8_vs_lib8(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z, int km, int kn); -void kernel_sgemv_nt_4_lib8(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t); -void kernel_sgemv_nt_4_vs_lib8(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t, int km); -void kernel_ssymv_l_4l_lib8(int kmax, float *alpha, float *A, int sda, float *x, float *z); -void kernel_ssymv_l_4r_lib8(int kmax, float *alpha, float *A, int sda, float *x, float *z); -void kernel_ssymv_l_4l_gen_lib8(int kmax, float *alpha, int offA, float *A, int sda, float *x, float *z, int km); -void kernel_ssymv_l_4r_gen_lib8(int kmax, float *alpha, int offA, float *A, int sda, float *x, float *z, int km); - -// -------- aux - -// ---- copy - -// lib4 -// -void kernel_sgecpsc_4_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgecp_4_0_lib4(int kmax, float *A, float *B); - -void kernel_sgecpsc_4_1_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_4_1_lib4(int kmax, float *A0, int sda, float *B); -void kernel_sgecpsc_4_2_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_4_2_lib4(int kmax, float *A0, int sda, float *B); -void kernel_sgecpsc_4_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_4_3_lib4(int kmax, float *A0, int sda, float *B); - -void kernel_sgecpsc_3_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgecp_3_0_lib4(int kmax, float *A, float *B); -void kernel_sgecpsc_3_2_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_3_2_lib4(int kmax, float *A0, int sda, float *B); -void kernel_sgecpsc_3_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_3_3_lib4(int kmax, float *A0, int sda, float *B); - -void kernel_sgecpsc_2_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgecp_2_0_lib4(int kmax, float *A, float *B); -void kernel_sgecpsc_2_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_2_3_lib4(int kmax, float *A0, int sda, float *B); - -void kernel_sgecpsc_1_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgecp_1_0_lib4(int kmax, float *A, float *B); - -// lib8 -// -void kernel_sgecp_8_0_lib8(int m, float *A, float *B); -void kernel_sgecp_8_0_gen_lib8(int m, float *A, float *B, int m1); -void kernel_sgecp_8_0_gen_u_lib8(int m, float *A, float *B, int m1); - -void kernel_sgesc_8_0_lib8(int m, float *alpha, float *A); -void kernel_sgesc_8_0_gen_lib8(int m, float *alpha, float *A, int m1); -void kernel_sgesc_8_0_gen_u_lib8(int m, float *alpha, float *A, int m1); - -void kernel_sgecpsc_8_0_lib8(int m, float *alpha, float *A, float *B); -void kernel_sgecpsc_8_0_gen_lib8(int m, float *alpha, float *A, float *B, int m1); -void kernel_sgecpsc_8_0_gen_u_lib8(int m, float *alpha, float *A, float *B, int m1); - -void kernel_sgecp_8_1_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_1_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_1_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_1_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_2_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_2_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_2_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_2_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_3_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_3_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_3_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_3_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_4_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_4_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_4_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_4_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_5_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_5_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_5_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_5_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_6_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_6_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_6_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_6_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_7_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_7_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_7_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_7_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -// transpose -// -void kernel_sgetr_8_0_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_0_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_1_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_1_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_2_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_2_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_3_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_3_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_4_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_4_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_5_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_5_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_6_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_6_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_7_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_7_gen_lib8(int m, float *A, int sda, float *B, int m1); - -// add -// -void kernel_sgead_8_0_lib8(int m, float *alpha, float *A, float *B); -void kernel_sgead_8_0_gen_lib8(int m, float *alpha, float *A, float *B, int m1); -void kernel_sgead_8_1_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_1_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_2_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_2_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_3_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_3_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_4_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_4_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_5_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_5_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_6_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_6_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_7_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_7_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - - -// -// lib4 -// - - - -// level 2 BLAS -// 4 -void kernel_sgemv_n_4_lib4(int k, float *alpha, float *A, float *x, float *beta, float *y, float *z); -void kernel_sgemv_n_4_vs_lib4(int k, float *alpha, float *A, float *x, float *beta, float *y, float *z, int k1); -void kernel_sgemv_n_4_gen_lib4(int kmax, float *alpha, float *A, float *x, float *beta, float *y, float *z, int k0, int k1); -void kernel_sgemv_t_4_lib4(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z); -void kernel_sgemv_t_4_vs_lib4(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z, int k1); -void kernel_strsv_ln_inv_4_lib4(int k, float *A, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_ln_inv_4_vs_lib4(int k, float *A, float *inv_diag_A, float *x, float *y, float *z, int km, int kn); -void kernel_strsv_lt_inv_4_lib4(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_lt_inv_3_lib4(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_lt_inv_2_lib4(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_lt_inv_1_lib4(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strmv_un_4_lib4(int k, float *A, float *x, float *z); -void kernel_strmv_ut_4_lib4(int k, float *A, int sda, float *x, float *z); -void kernel_strmv_ut_4_vs_lib4(int k, float *A, int sda, float *x, float *z, int km); -void kernel_sgemv_nt_6_lib4(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t); -void kernel_sgemv_nt_4_lib4(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t); -void kernel_sgemv_nt_4_vs_lib4(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t, int km); -void kernel_ssymv_l_4_lib4(int kmax, float *alpha, float *A, int sda, float *x_n, float *z_n); -void kernel_ssymv_l_4_gen_lib4(int kmax, float *alpha, int offA, float *A, int sda, float *x_n, float *z_n, int km); - - - -// level 3 BLAS -// 12x4 -void kernel_sgemm_nt_16x4_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nt_16x4_vs_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_strsm_nt_rl_inv_16x4_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_16x4_vs_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int m1, int n1); -// 12x4 -void kernel_sgemm_nt_12x4_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nt_12x4_vs_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_strsm_nt_rl_inv_12x4_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_12x4_vs_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int m1, int n1); -// 8x8 -void kernel_sgemm_nt_8x8_lib4(int k, float *alpha, float *A, int sda, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nt_8x8_vs_lib4(int k, float *alpha, float *A, int sda, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_sgemm_nn_8x8_lib4(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nn_8x8_vs_lib4(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -// 8x4 -void kernel_sgemm_nt_8x4_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nt_8x4_vs_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_sgemm_nn_8x4_lib4(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nn_8x4_vs_lib4(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_ssyrk_nt_l_8x4_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_ssyrk_nt_l_8x4_vs_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); // -void kernel_strsm_nt_rl_inv_8x4_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_8x4_vs_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int m1, int n1); -// 4x4 -void kernel_sgemm_nt_4x4_lib4(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); // -void kernel_sgemm_nt_4x4_vs_lib4(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); // -void kernel_sgemm_nt_4x4_gen_lib4(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int k0, int k1); -void kernel_sgemm_nn_4x4_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D); // -void kernel_sgemm_nn_4x4_vs_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D, int km, int kn); // -void kernel_sgemm_nn_4x4_gen_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_ssyrk_nt_l_4x4_lib4(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); // -void kernel_ssyrk_nt_l_4x4_vs_lib4(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); // -void kernel_ssyrk_nt_l_4x4_gen_lib4(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_strmm_nt_ru_4x4_lib4(int k, float *alpha, float *A, float *B, float *D); // -void kernel_strmm_nt_ru_4x4_vs_lib4(int k, float *alpha, float *A, float *B, float *D, int km, int kn); // -void kernel_strmm_nn_rl_4x4_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *D); -void kernel_strmm_nn_rl_4x4_gen_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_4x4_vs_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_strsm_nt_rl_one_4x4_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E); -void kernel_strsm_nt_rl_one_4x4_vs_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, int km, int kn); -void kernel_strsm_nt_ru_inv_4x4_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_ru_inv_4x4_vs_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_strsm_nt_ru_one_4x4_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E); -void kernel_strsm_nt_ru_one_4x4_vs_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, int km, int kn); -void kernel_strsm_nn_ru_inv_4x4_lib4(int k, float *A, float *B, int sdb, float *beta, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nn_ru_inv_4x4_vs_lib4(int k, float *A, float *B, int sdb, float *beta, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_strsm_nn_ll_one_4x4_lib4(int k, float *A, float *B, int sdb, float *C, float *D, float *E); -void kernel_strsm_nn_ll_one_4x4_vs_lib4(int k, float *A, float *B, int sdb, float *C, float *D, float *E, int km, int kn); -void kernel_strsm_nn_lu_inv_4x4_lib4(int kmax, float *A, float *B, int sdb, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nn_lu_inv_4x4_vs_lib4(int kmax, float *A, float *B, int sdb, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -// diag -void kernel_sgemm_diag_right_4_a0_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *D, int sdd); -void kernel_sgemm_diag_right_4_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_diag_right_3_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_diag_right_2_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_diag_right_1_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_diag_left_4_a0_lib4(int kmax, float *alpha, float *A, float *B, float *D); -void kernel_sgemm_diag_left_4_lib4(int kmax, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_diag_left_3_lib4(int kmax, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_diag_left_2_lib4(int kmax, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_diag_left_1_lib4(int kmax, float *alpha, float *A, float *B, float *beta, float *C, float *D); - - - -// LAPACK -// 16x4 -void kernel_spotrf_nt_l_16x4_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_16x4_vs_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int m1, int n1); -// 12x4 -void kernel_spotrf_nt_l_12x4_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_12x4_vs_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int m1, int n1); -// 8x4 -void kernel_spotrf_nt_l_8x4_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_8x4_vs_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int m1, int n1); -// 4x4 -void kernel_spotrf_nt_l_4x4_lib4(int k, float *A, float *B, float *C, float *D, float *inv_diag_D); -void kernel_spotrf_nt_l_4x4_vs_lib4(int k, float *A, float *B, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_sgetrf_nn_4x4_lib4(int k, float *A, float *B, int sdb, float *C, float *D, float *inv_diag_D); -void kernel_sgetrf_nn_4x4_vs_lib4(int k, float *A, float *B, int sdb, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_sgetrf_pivot_4_lib4(int m, float *pA, int sda, float *inv_diag_A, int* ipiv); -void kernel_sgetrf_pivot_4_vs_lib4(int m, int n, float *pA, int sda, float *inv_diag_A, int* ipiv); - - - -// merged routines -// 4x4 -void kernel_sgemm_strsm_nt_rl_inv_4x4_lib4(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_4x4_vs_lib4(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_4x4_vs_lib4(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_4x4_lib4(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D); - - - -// auxiliary routines -void kernel_strcp_l_4_0_lib4(int kmax, float *A, float *B); -void kernel_strcp_l_4_1_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_4_2_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_4_3_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_3_0_lib4(int kmax, float *A, float *B); -void kernel_strcp_l_3_2_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_3_3_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_2_0_lib4(int kmax, float *A, float *B); -void kernel_strcp_l_2_3_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_1_0_lib4(int kmax, float *A, float *B); -void kernel_sgead_4_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgead_4_1_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_4_2_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_4_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_3_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgead_3_2_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_3_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_2_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgead_2_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_1_0_lib4(int kmax, float *alpha, float *A, float *B); -// TODO -void kernel_sgeset_4_lib4(int kmax, float alpha, float *A); -void kernel_strset_4_lib4(int kmax, float alpha, float *A); -void kernel_sgetr_4_lib4(int tri, int kmax, int kna, float alpha, float *A, float *C, int sdc); -void kernel_sgetr_3_lib4(int tri, int kmax, int kna, float alpha, float *A, float *C, int sdc); -void kernel_sgetr_2_lib4(int tri, int kmax, int kna, float alpha, float *A, float *C, int sdc); -void kernel_sgetr_1_lib4(int tri, int kmax, int kna, float alpha, float *A, float *C, int sdc); - - - -// pack -// 24 lib 8 -void kernel_spack_nn_24_lib8(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_nn_24_vs_lib8(int kmax, float *A, int lda, float *B, int sdb, int m1); -// 16 lib 8 -void kernel_spack_nn_16_lib8(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_nn_16_vs_lib8(int kmax, float *A, int lda, float *B, int sdb, int m1); -// 8 lib 8 -void kernel_spack_nn_8_lib8(int kmax, float *A, int lda, float *B); -void kernel_spack_nn_8_vs_lib8(int kmax, float *A, int lda, float *B, int m1); -void kernel_spack_tn_8_lib8(int kmax, float *A, int lda, float *B); -void kernel_spack_tn_8_vs_lib8(int kmax, float *A, int lda, float *B, int m1); -void kernel_spack_tt_8_lib8(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_tt_8_vs_lib8(int kmax, float *A, int lda, float *B, int sdb, int m1); -// 8 lib 4 -void kernel_spack_nn_8_lib4(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_nn_8_vs_lib4(int kmax, float *A, int lda, float *B, int sdb, int m1); -//void kernel_spack_tt_8_lib4(int kmax, float *A, int lda, float *B, int sdb); -// 4 -void kernel_spack_nn_4_lib4(int kmax, float *A, int lda, float *B); -void kernel_spack_nn_4_vs_lib4(int kmax, float *A, int lda, float *B, int m1); -void kernel_spack_tn_4_lib4(int kmax, float *A, int lda, float *B); -void kernel_spack_tn_4_vs_lib4(int kmax, float *A, int lda, float *B, int m1); -void kernel_spack_tt_4_lib4(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_tt_4_vs_lib4(int kmax, float *A, int lda, float *B, int sdb, int m1); -// unpack -// 8 -void kernel_sunpack_nn_8_lib4(int kmax, float *A, int sda, float *B, int ldb); -void kernel_sunpack_nn_8_vs_lib4(int kmax, float *A, int sda, float *B, int ldb, int m1); -//void kernel_sunpack_tt_8_lib4(int kmax, float *A, int sda, float *B, int ldb); -// 4 -void kernel_sunpack_nn_4_lib4(int kmax, float *A, float *B, int ldb); -void kernel_sunpack_nn_4_vs_lib4(int kmax, float *A, float *B, int ldb, int m1); -void kernel_sunpack_nt_4_lib4(int kmax, float *A, float *B, int ldb); -void kernel_sunpack_nt_4_vs_lib4(int kmax, float *A, float *B, int ldb, int m1); -void kernel_sunpack_tt_4_lib4(int kmax, float *A, int sda, float *B, int ldb); - -// panel copy -// 4 -void kernel_spacp_nt_4_lib4(int kmax, float *A, int offsetB, float *B, int sdb); -void kernel_spacp_tn_4_lib4(int kmax, int offsetA, float *A, int sda, float *B); -void kernel_spacp_nn_4_lib4(int kmax, int offsetA, float *A, int sda, float *B); -void kernel_spacp_nn_4_vs_lib4(int kmax, int offsetA, float *A, int sda, float *B, int m1); - - - -/************************************************ -* BLAS API kernels -************************************************/ - -//#if defined(BLAS_API) - -// A, B panel-major bs=8; C, D column-major -// 24x4 -void kernel_sgemm_nt_24x4_lib88cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_24x4_vs_lib88cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 16x4 -void kernel_sgemm_nt_16x4_lib88cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_16x4_vs_lib88cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 8x8 -void kernel_sgemm_nt_8x8_lib88cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_vs_lib88cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_spotrf_nt_l_8x8_lib88cc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *dD); -void kernel_spotrf_nt_l_8x8_vs_lib88cc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *dD, int m1, int n1); -void kernel_strsm_nt_rl_inv_8x8_lib88ccc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_8x8_vs_lib88ccc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -// 8x4 -void kernel_sgemm_nt_8x4_lib88cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x4_vs_lib88cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// A, B panel-major bs=4; C, D column-major -// 8x8 -void kernel_sgemm_nt_8x8_lib44cc(int kmax, float *alpha, float *A, int sda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -// 8x4 -void kernel_sgemm_nt_8x4_lib44cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x4_vs_lib44cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_spotrf_nt_l_8x4_lib44cc(int kmax, float *A, int sda, float *B, float *C, int ldc, float *D, int ldd, float *dD); -void kernel_strsm_nt_rl_inv_8x4_lib44ccc(int kmax, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_8x4_vs_lib44ccc(int kmax, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -// 4x4 -void kernel_sgemm_nt_4x4_lib44cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x4_vs_lib44cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, float *dE); -void kernel_strsm_nt_rl_inv_4x4_vs_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, float *dE, int m1, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib44ccc(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_4x4_vs_lib44ccc(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_rl_one_4x4_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E); -void kernel_strsm_nt_rl_one_4x4_vs_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int m1, int n1); -void kernel_strsm_nt_ru_inv_4x4_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, float *dE); -void kernel_strsm_nt_ru_inv_4x4_vs_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, float *dE, int m1, int n1); -void kernel_strsm_nt_ru_one_4x4_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E); -void kernel_strsm_nt_ru_one_4x4_vs_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int m1, int n1); -void kernel_spotrf_nt_l_4x4_lib44cc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *dD); -void kernel_spotrf_nt_l_4x4_vs_lib44cc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *dD, int m1, int n1); - -// B panel-major bs=8; A, C, D column-major -// 4x24 -void kernel_sgemm_nt_4x24_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x24_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x24_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x24_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x16 -void kernel_sgemm_nt_4x16_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x16_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x16_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x16_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 8x8 -void kernel_sgemm_nt_8x8_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_8x8_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_8x8_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x8 -void kernel_sgemm_nt_4x8_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x8_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x8_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x8_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// B panel-major bs=4; A, C, D column-major -// 8x8 -void kernel_sgemm_nt_8x8_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_8x8_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_8x8_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x8 -void kernel_sgemm_nt_4x8_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x8_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x8_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x8_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x4 -void kernel_sgemm_nt_4x4_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x4_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x4_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x4_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// A panel-major bs=8; B, C, D column-major -// 24x4 -void kernel_sgemm_nn_24x4_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_24x4_vs_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_24x4_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_24x4_vs_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 16x4 -void kernel_sgemm_nn_16x4_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_16x4_vs_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_16x4_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_16x4_vs_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 8x8 -void kernel_sgemm_nn_8x8_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_8x8_vs_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_8x8_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_vs_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 8x4 -void kernel_sgemm_nn_8x4_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_8x4_vs_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_8x4_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x4_vs_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// A panel-major bs=4; B, C, D column-major -// 8x8 -void kernel_sgemm_nn_8x8_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -// 8x4 -void kernel_sgemm_nn_8x4_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_8x4_vs_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_8x4_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x4_vs_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x4 -void kernel_sgemm_nn_4x4_lib4ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_4x4_vs_lib4ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_4x4_lib4ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x4_vs_lib4ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_strsm_nn_rl_inv_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nn_rl_inv_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nn_rl_one_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde); -void kernel_strsm_nn_rl_one_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, int m1, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_rl_one_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde); -void kernel_strsm_nt_rl_one_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, int m1, int n1); -void kernel_strsm_nn_ru_inv_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nn_ru_inv_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nn_ru_one_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde); -void kernel_strsm_nn_ru_one_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, int m1, int n1); -void kernel_strsm_nt_ru_inv_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_ru_inv_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_ru_one_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde); -void kernel_strsm_nt_ru_one_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, int m1, int n1); - -// A, C, D panel-major; B, E column-major -// TODO merge with above -// 4x4 -void kernel_strsm_nn_rl_inv_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE); -void kernel_strsm_nn_rl_inv_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nn_rl_one_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde); -void kernel_strsm_nn_rl_one_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, int m1, int n1); -void kernel_strsm_nn_ru_inv_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE); -void kernel_strsm_nn_ru_inv_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nn_ru_one_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde); -void kernel_strsm_nn_ru_one_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, int m1, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_rl_one_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde); -void kernel_strsm_nt_rl_one_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, int m1, int n1); -void kernel_strsm_nt_ru_inv_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE); -void kernel_strsm_nt_ru_inv_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_ru_one_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde); -void kernel_strsm_nt_ru_one_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, int m1, int n1); - -// A, B, C, D column-major -void kernel_sgemm_nn_4x4_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_4x4_vs_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_4x4_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x4_vs_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x4_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x4_vs_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// vector -void kernel_sdot_11_lib(int n, float *x, float *y, float *res); -void kernel_saxpy_11_lib(int n, float *alpha, float *x, float *y); - - -//#endif // BLAS_API - - - -// larger kernels -// 24 -void kernel_sgemm_nt_24xn_p0_lib88cc(int n, int k, float *alpha, float *A, int sda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, float *A_p, float *B_p); - - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_KERNEL_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_stdlib.h b/third_party/acados/include/blasfeo/include/blasfeo_stdlib.h deleted file mode 100644 index 9bd248b1d4f702..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_stdlib.h +++ /dev/null @@ -1,62 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_STDLIB_H_ -#define BLASFEO_STDLIB_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -#include - -// -void blasfeo_malloc(void **ptr, size_t size); -// -void blasfeo_malloc_align(void **ptr, size_t size); -// -void blasfeo_free(void *ptr); -// -void blasfeo_free_align(void *ptr); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_STDLIB_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_target.h b/third_party/acados/include/blasfeo/include/blasfeo_target.h deleted file mode 100644 index 51f617a6499273..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_target.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef TARGET_X64_INTEL_HASWELL -#define TARGET_X64_INTEL_HASWELL -#endif - -#ifndef TARGET_NEED_FEATURE_AVX2 -#define TARGET_NEED_FEATURE_AVX2 1 -#endif - -#ifndef TARGET_NEED_FEATURE_FMA -#define TARGET_NEED_FEATURE_FMA 1 -#endif - -#ifndef TARGET_NEED_FEATURE_SSE3 -/* #undef TARGET_NEED_FEATURE_SSE3 */ -#endif - -#ifndef TARGET_NEED_FEATURE_AVX -/* #undef TARGET_NEED_FEATURE_AVX */ -#endif - -#ifndef TARGET_NEED_FEATURE_VFPv3 -/* #undef TARGET_NEED_FEATURE_VFPv3 */ -#endif - -#ifndef TARGET_NEED_FEATURE_NEON -/* #undef TARGET_NEED_FEATURE_NEON */ -#endif - -#ifndef TARGET_NEED_FEATURE_VFPv4 -/* #undef TARGET_NEED_FEATURE_VFPv4 */ -#endif - -#ifndef TARGET_NEED_FEATURE_NEONv2 -/* #undef TARGET_NEED_FEATURE_NEONv2 */ -#endif - -#ifndef LA_HIGH_PERFORMANCE -#define LA_HIGH_PERFORMANCE -#endif - -#ifndef MF_PANELMAJ -#define MF_PANELMAJ -#endif - -#ifndef EXT_DEP -#define ON 1 -#define OFF 0 -#if ON==ON -#define EXT_DEP -#endif -#undef ON -#undef OFF -#endif - -#ifndef BLAS_API -#define ON 1 -#define OFF 0 -#if OFF==ON -#define BLAS_API -#endif -#undef ON -#undef OFF -#endif - -#ifndef FORTRAN_BLAS_API -#define ON 1 -#define OFF 0 -#if OFF==ON -#define FORTRAN_BLAS_API -#endif -#undef ON -#undef OFF -#endif diff --git a/third_party/acados/include/blasfeo/include/blasfeo_timing.h b/third_party/acados/include/blasfeo/include/blasfeo_timing.h deleted file mode 100644 index 5671b888feec39..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_timing.h +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_TIMING_H_ -#define BLASFEO_TIMING_H_ - -//#include - -#if (defined _WIN32 || defined _WIN64) && !(defined __MINGW32__ || defined __MINGW64__) - - /* Use Windows QueryPerformanceCounter for timing. */ - #include - - /** A structure for keeping internal timer data. */ - typedef struct blasfeo_timer_ { - LARGE_INTEGER tic; - LARGE_INTEGER toc; - LARGE_INTEGER freq; - } blasfeo_timer; - -#elif(defined __APPLE__) - - #include - - /** A structure for keeping internal timer data. */ - typedef struct blasfeo_timer_ { - uint64_t tic; - uint64_t toc; - mach_timebase_info_data_t tinfo; - } blasfeo_timer; - -#elif(defined __DSPACE__) - - #include - - typedef struct blasfeo_timer_ { - double time; - } blasfeo_timer; - -#elif(defined __XILINX_NONE_ELF__ || defined __XILINX_ULTRASCALE_NONE_ELF_JAILHOUSE__) - - #include "xtime_l.h" - - typedef struct blasfeo_timer_ { - uint64_t tic; - uint64_t toc; - } blasfeo_timer; - -#else - - /* Use POSIX clock_gettime() for timing on non-Windows machines. */ - #include - - #if __STDC_VERSION__ >= 199901L // C99 Mode - - #include - #include - - typedef struct blasfeo_timer_ { - struct timeval tic; - struct timeval toc; - } blasfeo_timer; - - #else // ANSI C Mode - - /** A structure for keeping internal timer data. */ - typedef struct blasfeo_timer_ { - struct timespec tic; - struct timespec toc; - } blasfeo_timer; - - #endif // __STDC_VERSION__ >= 199901L - -#endif // (defined _WIN32 || defined _WIN64) - -/** A function for measurement of the current time. */ -void blasfeo_tic(blasfeo_timer* t); - -/** A function which returns the elapsed time. */ -double blasfeo_toc(blasfeo_timer* t); - -#endif // BLASFEO_TIMING_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_v_aux_ext_dep.h b/third_party/acados/include/blasfeo/include/blasfeo_v_aux_ext_dep.h deleted file mode 100644 index 1598551185cc68..00000000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_v_aux_ext_dep.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_V_AUX_EXT_DEP_H_ -#define BLASFEO_V_AUX_EXT_DEP_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -/************************************************ -* d_aux_extern_depend_lib.c -************************************************/ - -#ifdef EXT_DEP - -void v_zeros(void **ptrA, int size); -// dynamically allocate size bytes of memory aligned to 64-byte boundaries and set accordingly a pointer to void; set allocated memory to zero -void v_zeros_align(void **ptrA, int size); -// free the memory allocated by v_zeros -void v_free(void *ptrA); -// free the memory allocated by v_zeros_aligned -void v_free_align(void *ptrA); -// dynamically allocate size bytes of memory and set accordingly a pointer to char; set allocated memory to zero -void c_zeros(char **ptrA, int size); -// dynamically allocate size bytes of memory aligned to 64-byte boundaries and set accordingly a pointer to char; set allocated memory to zero -void c_zeros_align(char **ptrA, int size); -// free the memory allocated by c_zeros -void c_free(char *ptrA); -// free the memory allocated by c_zeros_aligned -void c_free_align(char *ptrA); - -#endif // EXT_DEP - - - -#ifdef __cplusplus -} -#endif - - - -#endif // BLASFEO_V_AUX_EXT_DEP_H_ diff --git a/third_party/acados/include/blasfeo/include/d_blas.h b/third_party/acados/include/blasfeo/include/d_blas.h deleted file mode 100644 index ffd2578da3c54d..00000000000000 --- a/third_party/acados/include/blasfeo/include/d_blas.h +++ /dev/null @@ -1,78 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// headers to reference BLAS and LAPACK routines employed in BLASFEO WR - -// level 1 -double ddot_(int *m, double *x, int *incx, double *y, int *incy); -void dcopy_(int *m, double *x, int *incx, double *y, int *incy); -void daxpy_(int *m, double *alpha, double *x, int *incx, double *y, int *incy); -void dscal_(int *m, double *alpha, double *x, int *incx); -void drot_(int *m, double *x, int *incx, double *y, int *incy, double *c, double *s); -void drotg_(double *a, double *b, double *c, double *s); - -// level 2 -void dgemv_(char *ta, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -void dsymv_(char *uplo, int *m, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -void dtrmv_(char *uplo, char *trans, char *diag, int *n, double *A, int *lda, double *x, int *incx); -void dtrsv_(char *uplo, char *trans, char *diag, int *n, double *A, int *lda, double *x, int *incx); -void dger_(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *A, int *lda); - -// level 3 -void dgemm_(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); -void dsyrk_(char *uplo, char *trans, int *n, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); -void dtrmm_(char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -void dtrsm_(char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -void dsyr2k_(char *uplo, char *trans, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); - -// lapack -void dpotrf_(char *uplo, int *m, double *A, int *lda, int *info); -void dgetrf_(int *m, int *n, double *A, int *lda, int *ipiv, int *info); -void dgeqrf_(int *m, int *n, double *A, int *lda, double *tau, double *work, int *lwork, int *info); -void dgeqr2_(int *m, int *n, double *A, int *lda, double *tau, double *work, int *info); -void dgelqf_(int *m, int *n, double *A, int *lda, double *tau, double *work, int *lwork, int *info); -void dorglq_(int *m, int *n, int *k, double *A, int *lda, double *tau, double *work, int *lwork, int *info); - - - -#ifdef __cplusplus -} -#endif diff --git a/third_party/acados/include/blasfeo/include/d_blas_64.h b/third_party/acados/include/blasfeo/include/d_blas_64.h deleted file mode 100644 index 4f40d00dfb3fe8..00000000000000 --- a/third_party/acados/include/blasfeo/include/d_blas_64.h +++ /dev/null @@ -1,73 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// headers to reference BLAS and LAPACK routines employed in BLASFEO WR - -// level 1 -double ddot_(long long *m, double *x, long long *incx, double *y, long long *incy); -void dcopy_(long long *m, double *x, long long *incx, double *y, long long *incy); -void daxpy_(long long *m, double *alpha, double *x, long long *incx, double *y, long long *incy); -void dscal_(long long *m, double *alpha, double *x, long long *incx); - -// level 2 -void dgemv_(char *ta, long long *m, long long *n, double *alpha, double *A, long long *lda, double *x, long long *incx, double *beta, double *y, long long *incy); -void dsymv_(char *uplo, long long *m, double *alpha, double *A, long long *lda, double *x, long long *incx, double *beta, double *y, long long *incy); -void dtrmv_(char *uplo, char *trans, char *diag, long long *n, double *A, long long *lda, double *x, long long *incx); -void dtrsv_(char *uplo, char *trans, char *diag, long long *n, double *A, long long *lda, double *x, long long *incx); -void dger_(long long *m, long long *n, double *alpha, double *x, long long *incx, double *y, long long *incy, double *A, long long *lda); - -// level 3 -void dgemm_(char *ta, char *tb, long long *m, long long *n, long long *k, double *alpha, double *A, long long *lda, double *B, long long *ldb, double *beta, double *C, long long *ldc); -void dsyrk_(char *uplo, char *trans, long long *n, long long *k, double *alpha, double *A, long long *lda, double *beta, double *C, long long *ldc); -void dtrmm_(char *side, char *uplo, char *trans, char *diag, long long *m, long long *n, double *alpha, double *A, long long *lda, double *B, long long *ldb); -void dtrsm_(char *side, char *uplo, char *trans, char *diag, long long *m, long long *n, double *alpha, double *A, long long *lda, double *B, long long *ldb); - -// lapack -void dpotrf_(char *uplo, long long *m, double *A, long long *lda, long long *info); -void dgetrf_(long long *m, long long *n, double *A, long long *lda, long long *ipiv, long long *info); -void dgeqrf_(long long *m, long long *n, double *A, long long *lda, double *tau, double *work, long long *lwork, long long *info); -void dgeqr2_(long long *m, long long *n, double *A, long long *lda, double *tau, double *work, long long *info); - - - -#ifdef __cplusplus -} -#endif diff --git a/third_party/acados/include/blasfeo/include/s_blas.h b/third_party/acados/include/blasfeo/include/s_blas.h deleted file mode 100644 index 3b299ce64cdef6..00000000000000 --- a/third_party/acados/include/blasfeo/include/s_blas.h +++ /dev/null @@ -1,78 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// headers to reference BLAS and LAPACK routines employed in BLASFEO WR - -// level 1 -float sdot_(int *m, float *x, int *incx, float *y, int *incy); -void scopy_(int *m, float *x, int *incx, float *y, int *incy); -void saxpy_(int *m, float *alpha, float *x, int *incx, float *y, int *incy); -void sscal_(int *m, float *alpha, float *x, int *incx); -void srot_(int *m, float *x, int *incx, float *y, int *incy, float *c, float *s); -void srotg_(float *a, float *b, float *c, float *s); - -// level 2 -void sgemv_(char *ta, int *m, int *n, float *alpha, float *A, int *lda, float *x, int *incx, float *beta, float *y, int *incy); -void ssymv_(char *uplo, int *m, float *alpha, float *A, int *lda, float *x, int *incx, float *beta, float *y, int *incy); -void strmv_(char *uplo, char *trans, char *diag, int *n, float *A, int *lda, float *x, int *incx); -void strsv_(char *uplo, char *trans, char *diag, int *n, float *A, int *lda, float *x, int *incx); -void sger_(int *m, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *A, int *lda); - -// level 3 -void sgemm_(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); -void ssyrk_(char *uplo, char *trans, int *n, int *k, float *alpha, float *A, int *lda, float *beta, float *C, int *ldc); -void strmm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); -void strsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); -void ssyr2k_(char *uplo, char *trans, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); - -// lapack -void spotrf_(char *uplo, int *m, float *A, int *lda, int *info); -void sgetrf_(int *m, int *n, float *A, int *lda, int *ipiv, int *info); -void sgeqrf_(int *m, int *n, float *A, int *lda, float *tau, float *work, int *lwork, int *info); -void sgeqr2_(int *m, int *n, float *A, int *lda, float *tau, float *work, int *info); -void sgelqf_(int *m, int *n, float *A, int *lda, float *tau, float *work, int *lwork, int *info); -void sorglq_(int *m, int *n, int *k, float *A, int *lda, float *tau, float *work, int *lwork, int *info); - - - -#ifdef __cplusplus -} -#endif diff --git a/third_party/acados/include/blasfeo/include/s_blas_64.h b/third_party/acados/include/blasfeo/include/s_blas_64.h deleted file mode 100644 index b9efab6c236ed1..00000000000000 --- a/third_party/acados/include/blasfeo/include/s_blas_64.h +++ /dev/null @@ -1,73 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// headers to reference BLAS and LAPACK routines employed in BLASFEO WR - -// level 1 -float sdot_(long long *m, float *x, long long *incx, float *y, long long *incy); -void scopy_(long long *m, float *x, long long *incx, float *y, long long *incy); -void saxpy_(long long *m, float *alpha, float *x, long long *incx, float *y, long long *incy); -void sscal_(long long *m, float *alpha, float *x, long long *incx); - -// level 2 -void sgemv_(char *ta, long long *m, long long *n, float *alpha, float *A, long long *lda, float *x, long long *incx, float *beta, float *y, long long *incy); -void ssymv_(char *uplo, long long *m, float *alpha, float *A, long long *lda, float *x, long long *incx, float *beta, float *y, long long *incy); -void strmv_(char *uplo, char *trans, char *diag, long long *n, float *A, long long *lda, float *x, long long *incx); -void strsv_(char *uplo, char *trans, char *diag, long long *n, float *A, long long *lda, float *x, long long *incx); -void sger_(long long *m, long long *n, float *alpha, float *x, long long *incx, float *y, long long *incy, float *A, long long *lda); - -// level 3 -void sgemm_(char *ta, char *tb, long long *m, long long *n, long long *k, float *alpha, float *A, long long *lda, float *B, long long *ldb, float *beta, float *C, long long *ldc); -void ssyrk_(char *uplo, char *trans, long long *n, long long *k, float *alpha, float *A, long long *lda, float *beta, float *C, long long *ldc); -void strmm_(char *side, char *uplo, char *transa, char *diag, long long *m, long long *n, float *alpha, float *A, long long *lda, float *B, long long *ldb); -void strsm_(char *side, char *uplo, char *transa, char *diag, long long *m, long long *n, float *alpha, float *A, long long *lda, float *B, long long *ldb); - -// lapack -void spotrf_(char *uplo, long long *m, float *A, long long *lda, long long *info); -void sgetrf_(long long *m, long long *n, float *A, long long *lda, long long *ipiv, long long *info); -void sgeqrf_(long long *m, long long *n, float *A, long long *lda, float *tau, float *work, long long *lwork, long long *info); -void sgeqr2_(long long *m, long long *n, float *A, long long *lda, float *tau, float *work, long long *info); - - - -#ifdef __cplusplus -} -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_aux_mem.h b/third_party/acados/include/hpipm/include/hpipm_aux_mem.h deleted file mode 100644 index 7bd3d7e8bc53e9..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_aux_mem.h +++ /dev/null @@ -1,52 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_AUX_MEM_H_ -#define HPIPM_AUX_MEM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void hpipm_zero_memset(hpipm_size_t memsize, void *mem); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_AUX_MEM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_aux_string.h b/third_party/acados/include/hpipm/include/hpipm_aux_string.h deleted file mode 100644 index 804cba5dc1a88d..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_aux_string.h +++ /dev/null @@ -1,50 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_AUX_STRING_H_ -#define HPIPM_AUX_STRING_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#define MAX_STR_LEN 5 -int hpipm_strcmp(char *str1, char *str2); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_AUX_STRING_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_common.h b/third_party/acados/include/hpipm/include/hpipm_common.h deleted file mode 100644 index 0cc96a7b506568..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_common.h +++ /dev/null @@ -1,76 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_COMMON_H_ -#define HPIPM_COMMON_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef size_t hpipm_size_t; - -enum hpipm_mode - { - SPEED_ABS, // focus on speed, absolute IPM formulation - SPEED, // focus on speed, relative IPM formulation - BALANCE, // balanced mode, relative IPM formulation - ROBUST, // focus on robustness, relative IPM formulation - }; - -enum hpipm_status - { - SUCCESS, // found solution satisfying accuracy tolerance - MAX_ITER, // maximum iteration number reached - MIN_STEP, // minimum step length reached - NAN_SOL, // NaN in solution detected - INCONS_EQ, // unconsistent equality constraints - }; - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_COMMON_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_cast_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_cast_qcqp.h deleted file mode 100644 index 0e4c41f22159ac..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_cast_qcqp.h +++ /dev/null @@ -1,71 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_CAST_QCQP_H_ -#define HPIPM_D_CAST_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp.h" -#include "hpipm_d_dense_qcqp_sol.h" -#include "hpipm_d_ocp_qcqp.h" -#include "hpipm_d_ocp_qcqp_dim.h" -#include "hpipm_d_ocp_qcqp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_cast_qcqp_compute_dim(struct d_ocp_qcqp_dim *ocp_dim, struct d_dense_qcqp_dim *dense_dim); -// -void d_cast_qcqp_cond(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp *dense_qp); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_CAST_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_cond.h b/third_party/acados/include/hpipm/include/hpipm_d_cond.h deleted file mode 100644 index 5900a2ab10201e..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_cond.h +++ /dev/null @@ -1,135 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_COND_H_ -#define HPIPM_D_COND_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp.h" -#include "hpipm_d_dense_qp_sol.h" -#include "hpipm_d_ocp_qp.h" -#include "hpipm_d_ocp_qp_dim.h" -#include "hpipm_d_ocp_qp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_cond_qp_arg - { - int cond_last_stage; // condense last stage - int cond_alg; // condensing algorithm: 0 N2-nx3, 1 N3-nx2 - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution inequality constr (lam t) - int square_root_alg; // square root algorithm (faster but requires RSQ>0) - hpipm_size_t memsize; - }; - - - -struct d_cond_qp_ws - { - struct blasfeo_dmat *Gamma; - struct blasfeo_dmat *GammaQ; - struct blasfeo_dmat *L; - struct blasfeo_dmat *Lx; - struct blasfeo_dmat *AL; - struct blasfeo_dvec *Gammab; - struct blasfeo_dvec *l; - struct blasfeo_dvec *tmp_nbgM; - struct blasfeo_dvec *tmp_nuxM; - int bs; // block size - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_cond_qp_arg_memsize(); -// -void d_cond_qp_arg_create(struct d_cond_qp_arg *cond_arg, void *mem); -// -void d_cond_qp_arg_set_default(struct d_cond_qp_arg *cond_arg); -// condensing algorithm: 0 N2-nx3, 1 N3-nx2 -void d_cond_qp_arg_set_cond_alg(int cond_alg, struct d_cond_qp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 square-root -void d_cond_qp_arg_set_ric_alg(int ric_alg, struct d_cond_qp_arg *cond_arg); -// condense last stage: 0 last stage disregarded, 1 last stage condensed too -void d_cond_qp_arg_set_cond_last_stage(int cond_last_stage, struct d_cond_qp_arg *cond_arg); -// -void d_cond_qp_arg_set_comp_prim_sol(int value, struct d_cond_qp_arg *cond_arg); -// -void d_cond_qp_arg_set_comp_dual_sol_eq(int value, struct d_cond_qp_arg *cond_arg); -// -void d_cond_qp_arg_set_comp_dual_sol_ineq(int value, struct d_cond_qp_arg *cond_arg); - -// -void d_cond_qp_compute_dim(struct d_ocp_qp_dim *ocp_dim, struct d_dense_qp_dim *dense_dim); -// -hpipm_size_t d_cond_qp_ws_memsize(struct d_ocp_qp_dim *ocp_dim, struct d_cond_qp_arg *cond_arg); -// -void d_cond_qp_ws_create(struct d_ocp_qp_dim *ocp_dim, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws, void *mem); -// -void d_cond_qp_cond(struct d_ocp_qp *ocp_qp, struct d_dense_qp *dense_qp, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_qp_cond_lhs(struct d_ocp_qp *ocp_qp, struct d_dense_qp *dense_qp, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_qp_cond_rhs(struct d_ocp_qp *ocp_qp, struct d_dense_qp *dense_qp, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_qp_expand_sol(struct d_ocp_qp *ocp_qp, struct d_dense_qp_sol *dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_sol, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// TODO remove -void d_cond_qp_expand_primal_sol(struct d_ocp_qp *ocp_qp, struct d_dense_qp_sol *dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_sol, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); - -// -void d_cond_qp_update(int *idxc, struct d_ocp_qp *ocp_qp, struct d_dense_qp *dense_qp, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_COND_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_cond_aux.h b/third_party/acados/include/hpipm/include/hpipm_d_cond_aux.h deleted file mode 100644 index 73afba3c7e75e2..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_cond_aux.h +++ /dev/null @@ -1,92 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_COND_AUX_H_ -#define HPIPM_D_COND_AUX_H_ - - - -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_cond_BAbt(struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *BAbt2, struct blasfeo_dvec *b, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_BAt(struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *BAbt2, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_b(struct d_ocp_qp *ocp_qp, struct blasfeo_dvec *b, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_RSQrq(struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *RSQrq2, struct blasfeo_dvec *rq, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_RSQ(struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *RSQrq2, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_rq(struct d_ocp_qp *ocp_qp, struct blasfeo_dvec *rq, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_DCtd(struct d_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_dmat *DCt2, struct blasfeo_dvec *d2, struct blasfeo_dvec *d_mask2, int *idxs_rev2, struct blasfeo_dvec *Z2, struct blasfeo_dvec *z, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_DCt(struct d_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_dmat *DCt2, int *idxs_rev2, struct blasfeo_dvec *Z2, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_d(struct d_ocp_qp *ocp_qp, struct blasfeo_dvec *d2, struct blasfeo_dvec *d_mask2, struct blasfeo_dvec *z, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_expand_sol(struct d_ocp_qp *ocp_qp, struct d_dense_qp_sol *dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_so, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_expand_primal_sol(struct d_ocp_qp *ocp_qp, struct d_dense_qp_sol *dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_so, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); - -// -void d_update_cond_BAbt(int *idxc, struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *BAbt2, struct blasfeo_dvec *b, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_update_cond_RSQrq_N2nx3(int *idxc, struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *RSQrq2, struct blasfeo_dvec *rq, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_update_cond_DCtd(int *idxc, struct d_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_dmat *DCt2, struct blasfeo_dvec *d2, int *idxs2, struct blasfeo_dvec *Z2, struct blasfeo_dvec *z, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_COND_AUX_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_cond_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_cond_qcqp.h deleted file mode 100644 index 266567bb8dfeaf..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_cond_qcqp.h +++ /dev/null @@ -1,129 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_COND_QCQP_H_ -#define HPIPM_D_COND_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp.h" -#include "hpipm_d_dense_qcqp_sol.h" -#include "hpipm_d_ocp_qcqp.h" -#include "hpipm_d_ocp_qcqp_dim.h" -#include "hpipm_d_ocp_qcqp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_cond_qcqp_arg - { - struct d_cond_qp_arg *qp_arg; - int cond_last_stage; // condense last stage -// int cond_variant; // TODO - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution equality constr (lam t) - int square_root_alg; // square root algorithm (faster but requires RSQ>0) - hpipm_size_t memsize; - }; - - - -struct d_cond_qcqp_ws - { - struct d_cond_qp_ws *qp_ws; - struct blasfeo_dmat *hess_array; // TODO remove - struct blasfeo_dmat *zero_hess; // TODO remove - struct blasfeo_dvec *grad_array; // TODO remove - struct blasfeo_dvec *zero_grad; // TODO remove - struct blasfeo_dvec *tmp_nvc; - struct blasfeo_dvec *tmp_nuxM; - struct blasfeo_dmat *GammaQ; - struct blasfeo_dmat *tmp_DCt; - struct blasfeo_dmat *tmp_nuM_nxM; -// struct blasfeo_dvec *d_qp; -// struct blasfeo_dvec *d_mask_qp; - hpipm_size_t memsize; - }; - - -// -hpipm_size_t d_cond_qcqp_arg_memsize(); -// -void d_cond_qcqp_arg_create(struct d_cond_qcqp_arg *cond_arg, void *mem); -// -void d_cond_qcqp_arg_set_default(struct d_cond_qcqp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 square-root -void d_cond_qcqp_arg_set_ric_alg(int ric_alg, struct d_cond_qcqp_arg *cond_arg); -// condense last stage: 0 last stage disregarded, 1 last stage condensed too -void d_cond_qcqp_arg_set_cond_last_stage(int cond_last_stage, struct d_cond_qcqp_arg *cond_arg); - -// -void d_cond_qcqp_compute_dim(struct d_ocp_qcqp_dim *ocp_dim, struct d_dense_qcqp_dim *dense_dim); -// -hpipm_size_t d_cond_qcqp_ws_memsize(struct d_ocp_qcqp_dim *ocp_dim, struct d_cond_qcqp_arg *cond_arg); -// -void d_cond_qcqp_ws_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws, void *mem); -// -void d_cond_qcqp_qc(struct d_ocp_qcqp *ocp_qp, struct blasfeo_dmat *Hq2, int *Hq_nzero2, struct blasfeo_dmat *Ct2, struct blasfeo_dvec *d2, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_qc_lhs(struct d_ocp_qcqp *ocp_qp, struct blasfeo_dmat *Hq2, int *Hq_nzero2, struct blasfeo_dmat *Ct2, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_qc_rhs(struct d_ocp_qcqp *ocp_qp, struct blasfeo_dvec *d2, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_cond(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp *dense_qp, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_cond_rhs(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp *dense_qp, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_cond_lhs(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp *dense_qp, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_expand_sol(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp_sol *dense_qp_sol, struct d_ocp_qcqp_sol *ocp_qp_sol, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_COND_QCQP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm.h deleted file mode 100644 index f39d9a9b507a92..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm.h +++ /dev/null @@ -1,101 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_CORE_QP_IPM_ -#define HPIPM_D_CORE_QP_IPM_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_core_qp_ipm_workspace - { - double *v; // primal variables - double *pi; // equality constraints multipliers - double *lam; // inequality constraints multipliers - double *t; // inequality constraints slacks - double *t_inv; // inverse of t - double *v_bkp; // backup of primal variables - double *pi_bkp; // backup of equality constraints multipliers - double *lam_bkp; // backup of inequality constraints multipliers - double *t_bkp; // backup of inequality constraints slacks - double *dv; // step in v - double *dpi; // step in pi - double *dlam; // step in lam - double *dt; // step in t - double *res_g; // q-residuals - double *res_b; // b-residuals - double *res_d; // d-residuals - double *res_m; // m-residuals - double *res_m_bkp; // m-residuals - double *Gamma; // Hessian update - double *gamma; // gradient update - double alpha; // step length - double alpha_prim; // step length - double alpha_dual; // step length - double sigma; // centering XXX - double mu; // duality measuere - double mu_aff; // affine duality measuere - double nc_inv; // 1.0/nc, where nc is the total number of inequality constraints - double nc_mask_inv; // 1.0/nc_mask - double lam_min; // min value in lam vector - double t_min; // min value in t vector - double t_min_inv; // inverse of min value in t vector - double tau_min; // min value of barrier parameter - int nv; // number of primal variables - int ne; // number of equality constraints - int nc; // (twice the) number of (two-sided) inequality constraints - int nc_mask; // total number of ineq constr after masking - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam also in solution, or only in Gamma computation - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t d_memsize_core_qp_ipm(int nv, int ne, int nc); -// -void d_create_core_qp_ipm(int nv, int ne, int nc, struct d_core_qp_ipm_workspace *workspace, void *mem); -// -void d_core_qp_ipm(struct d_core_qp_ipm_workspace *workspace); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_D_CORE_QP_IPM_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm_aux.h b/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm_aux.h deleted file mode 100644 index 30cc824badba3a..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm_aux.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_CORE_QP_IPM_AUX_ -#define HPIPM_S_CORE_QP_IPM_AUX_ - -#ifdef __cplusplus -extern "C" { -#endif - -// -void d_compute_Gamma_gamma_qp(double *res_d, double *res_m, struct d_core_qp_ipm_workspace *rws); -// -void d_compute_gamma_qp(double *res_d, double *res_m, struct d_core_qp_ipm_workspace *rws); -// -void d_compute_lam_t_qp(double *res_d, double *res_m, double *dlam, double *dt, struct d_core_qp_ipm_workspace *rws); -// -void d_compute_alpha_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_update_var_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_compute_mu_aff_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_backup_res_m(struct d_core_qp_ipm_workspace *rws); -// -void d_compute_centering_correction_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_compute_centering_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_compute_tau_min_qp(struct d_core_qp_ipm_workspace *rws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_S_CORE_QP_IPM_AUX_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp.h deleted file mode 100644 index 3da57164937a91..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp.h +++ /dev/null @@ -1,199 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QCQP_H_ -#define HPIPM_D_DENSE_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp - { - struct d_dense_qcqp_dim *dim; - struct blasfeo_dmat *Hv; // hessian of cost & vector work space - struct blasfeo_dmat *A; // equality constraint matrix - struct blasfeo_dmat *Ct; // inequality constraints matrix - struct blasfeo_dmat *Hq; // hessians of quadratic constraints - struct blasfeo_dvec *gz; // gradient of cost & gradient of slacks - struct blasfeo_dvec *b; // equality constraint vector - struct blasfeo_dvec *d; // inequality constraints vector - struct blasfeo_dvec *d_mask; // inequality constraints mask vector - struct blasfeo_dvec *m; // rhs of complementarity condition - struct blasfeo_dvec *Z; // (diagonal) hessian of slacks - int *idxb; // indices of box constrained variables within [u; x] - int *idxs_rev; // index of soft constraints (reverse storage) - int *Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0 - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_dense_qcqp_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp *qp, void *memory); - -// -void d_dense_qcqp_set(char *field, void *value, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_H(double *H, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_g(double *g, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_A(double *A, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_b(double *b, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_idxb(int *idxb, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_lb(double *lb, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_lb_mask(double *lb, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ub(double *ub, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ub_mask(double *ub, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_C(double *C, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_lg(double *lg, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_lg_mask(double *lg, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ug(double *ug, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ug_mask(double *ug, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_Hq(double *Hq, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_gq(double *gq, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_uq(double *uq, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_uq_mask(double *uq, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_idxs(int *idxs, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_idxs_rev(int *idxs_rev, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_Zl(double *Zl, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_Zu(double *Zu, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_zl(double *zl, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_zu(double *zu, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ls(double *ls, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ls_mask(double *ls, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_us(double *us, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_us_mask(double *us, struct d_dense_qcqp *qp); - -// getters (COLMAJ) - -void d_dense_qcqp_get_H(struct d_dense_qcqp *qp, double *H); -// -void d_dense_qcqp_get_g(struct d_dense_qcqp *qp, double *g); -// -void d_dense_qcqp_get_A(struct d_dense_qcqp *qp, double *A); -// -void d_dense_qcqp_get_b(struct d_dense_qcqp *qp, double *b); -// -void d_dense_qcqp_get_idxb(struct d_dense_qcqp *qp, int *idxb); -// -void d_dense_qcqp_get_lb(struct d_dense_qcqp *qp, double *lb); -// -void d_dense_qcqp_get_lb_mask(struct d_dense_qcqp *qp, double *lb); -// -void d_dense_qcqp_get_ub(struct d_dense_qcqp *qp, double *ub); -// -void d_dense_qcqp_get_ub_mask(struct d_dense_qcqp *qp, double *ub); -// -void d_dense_qcqp_get_C(struct d_dense_qcqp *qp, double *C); -// -void d_dense_qcqp_get_lg(struct d_dense_qcqp *qp, double *lg); -// -void d_dense_qcqp_get_lg_mask(struct d_dense_qcqp *qp, double *lg); -// -void d_dense_qcqp_get_ug(struct d_dense_qcqp *qp, double *ug); -// -void d_dense_qcqp_get_ug_mask(struct d_dense_qcqp *qp, double *ug); -// -void d_dense_qcqp_get_idxs(struct d_dense_qcqp *qp, int *idxs); -// -void d_dense_qcqp_get_idxs_rev(struct d_dense_qcqp *qp, int *idxs_rev); -// -void d_dense_qcqp_get_Zl(struct d_dense_qcqp *qp, double *Zl); -// -void d_dense_qcqp_get_Zu(struct d_dense_qcqp *qp, double *Zu); -// -void d_dense_qcqp_get_zl(struct d_dense_qcqp *qp, double *zl); -// -void d_dense_qcqp_get_zu(struct d_dense_qcqp *qp, double *zu); -// -void d_dense_qcqp_get_ls(struct d_dense_qcqp *qp, double *ls); -// -void d_dense_qcqp_get_ls_mask(struct d_dense_qcqp *qp, double *ls); -// -void d_dense_qcqp_get_us(struct d_dense_qcqp *qp, double *us); -// -void d_dense_qcqp_get_us_mask(struct d_dense_qcqp *qp, double *us); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_dim.h deleted file mode 100644 index fa8c574a1ef0e2..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_dim.h +++ /dev/null @@ -1,98 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QCQP_DIM_H_ -#define HPIPM_D_DENSE_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp_dim - { - struct d_dense_qp_dim *qp_dim; // dim of qp approximation - int nv; // number of variables - int ne; // number of equality constraints - int nb; // number of box constraints - int ng; // number of general constraints - int nq; // number of quadratic constraints - int nsb; // number of softened box constraints - int nsg; // number of softened general constraints - int nsq; // number of softened quadratic constraints - int ns; // number of softened constraints (nsb+nsg+nsq) TODO number of slacks - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qcqp_dim_memsize(); -// -void d_dense_qcqp_dim_create(struct d_dense_qcqp_dim *dim, void *memory); -// -void d_dense_qcqp_dim_set(char *field_name, int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nv(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_ne(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nb(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_ng(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nq(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nsb(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nsg(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nsq(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_ns(int value, struct d_dense_qcqp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_DIM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_ipm.h deleted file mode 100644 index fa3f98fa79a6ca..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_ipm.h +++ /dev/null @@ -1,193 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QCQP_IPM_H_ -#define HPIPM_D_DENSE_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp_ipm_arg - { - struct d_dense_qp_ipm_arg *qp_arg; - double mu0; // initial value for duality measure - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double reg_dual; // reg of dual hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int scale; // scale hessian - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_res_exit; // compute residuals on exit (only for abs_form==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_dense_qcqp_ipm_ws - { - struct d_dense_qp_ipm_ws *qp_ws; - struct d_dense_qp *qp; - struct d_dense_qp_sol *qp_sol; - struct d_dense_qcqp_res_ws *qcqp_res_ws; - struct d_dense_qcqp_res *qcqp_res; - struct blasfeo_dvec *tmp_nv; - int iter; // iteration number - int status; - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t d_dense_qcqp_ipm_arg_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_ipm_arg_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp_ipm_arg *arg, void *mem); -// -void d_dense_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set(char *field, void *value, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_iter_max(int *iter_max, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_alpha_min(double *alpha_min, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_mu0(double *mu0, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_tol_stat(double *tol_stat, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_tol_eq(double *tol_eq, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_tol_ineq(double *tol_ineq, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_tol_comp(double *tol_comp, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_reg_prim(double *reg, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_reg_dual(double *reg, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_warm_start(int *warm_start, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_pred_corr(int *pred_corr, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_lam_min(double *value, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_t_min(double *value, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_split_step(int *value, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_t_lam_min(int *value, struct d_dense_qcqp_ipm_arg *arg); - -// -hpipm_size_t d_dense_qcqp_ipm_ws_memsize(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_ws_create(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws, void *mem); -// -void d_dense_qcqp_ipm_get(char *field, struct d_dense_qcqp_ipm_ws *ws, void *value); -// -void d_dense_qcqp_ipm_get_status(struct d_dense_qcqp_ipm_ws *ws, int *status); -// -void d_dense_qcqp_ipm_get_iter(struct d_dense_qcqp_ipm_ws *ws, int *iter); -// -void d_dense_qcqp_ipm_get_max_res_stat(struct d_dense_qcqp_ipm_ws *ws, double *res_stat); -// -void d_dense_qcqp_ipm_get_max_res_eq(struct d_dense_qcqp_ipm_ws *ws, double *res_eq); -// -void d_dense_qcqp_ipm_get_max_res_ineq(struct d_dense_qcqp_ipm_ws *ws, double *res_ineq); -// -void d_dense_qcqp_ipm_get_max_res_comp(struct d_dense_qcqp_ipm_ws *ws, double *res_comp); -// -void d_dense_qcqp_ipm_get_stat(struct d_dense_qcqp_ipm_ws *ws, double **stat); -// -void d_dense_qcqp_ipm_get_stat_m(struct d_dense_qcqp_ipm_ws *ws, int *stat_m); -// -void d_dense_qcqp_init_var(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws); -// -void d_dense_qcqp_ipm_solve(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws); -#if 0 -// -void d_dense_qcqp_ipm_predict(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws); -// -void d_dense_qcqp_ipm_sens(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws); -#endif - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_IPM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_res.h deleted file mode 100644 index a76f16215e3e45..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_res.h +++ /dev/null @@ -1,107 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QCQP_RES_H_ -#define HPIPM_D_DENSE_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp_res - { - struct d_dense_qcqp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // infinity norm of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_dense_qcqp_res_ws - { - struct blasfeo_dvec *tmp_nv; // work space of size nv - struct blasfeo_dvec *tmp_nbgq; // work space of size nbM+ngM+nqM - struct blasfeo_dvec *tmp_ns; // work space of size nsM - struct blasfeo_dvec *q_fun; // value for evaluation of quadr constr - struct blasfeo_dvec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qcqp_res_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_res_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp_res *res, void *mem); -// -hpipm_size_t d_dense_qcqp_res_ws_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_res_ws_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp_res_ws *workspace, void *mem); -// -void d_dense_qcqp_res_compute(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_res *res, struct d_dense_qcqp_res_ws *ws); -// -void d_dense_qcqp_res_compute_inf_norm(struct d_dense_qcqp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_DENSE_QCQP_RES_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_sol.h deleted file mode 100644 index 6c697a8e693b20..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_sol.h +++ /dev/null @@ -1,85 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QCQP_SOL_H_ -#define HPIPM_D_DENSE_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp_sol - { - struct d_dense_qcqp_dim *dim; - struct blasfeo_dvec *v; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qcqp_sol_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_sol_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp_sol *qp_sol, void *memory); -// -void d_dense_qcqp_sol_get_v(struct d_dense_qcqp_sol *qp_sol, double *v); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_SOL_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_utils.h deleted file mode 100644 index a34218bae4831a..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_utils.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QCQP_UTILS_H_ -#define HPIPM_D_DENSE_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp_dim.h" -#include "hpipm_d_dense_qcqp.h" -#include "hpipm_d_dense_qcqp_sol.h" -//#include "hpipm_d_dense_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_dense_qcqp_dim_print(struct d_dense_qcqp_dim *qp_dim); -// -//void d_dense_qcqp_dim_codegen(char *file_name, char *mode, struct d_dense_qcqp_dim *qp_dim); -// -void d_dense_qcqp_print(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp *qp); -// -//void d_dense_qcqp_codegen(char *file_name, char *mode, struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_sol_print(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_sol *dense_qcqp_sol); -// -//void d_dense_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_res_print(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_res *dense_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp.h deleted file mode 100644 index 02fba5a9229a21..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp.h +++ /dev/null @@ -1,207 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QP_H_ -#define HPIPM_D_DENSE_QP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp - { - struct d_dense_qp_dim *dim; - struct blasfeo_dmat *Hv; // hessian of cost & vector work space - struct blasfeo_dmat *A; // equality constraint matrix - struct blasfeo_dmat *Ct; // inequality constraints matrix - struct blasfeo_dvec *gz; // gradient of cost & gradient of slacks - struct blasfeo_dvec *b; // equality constraint vector - struct blasfeo_dvec *d; // inequality constraints vector - struct blasfeo_dvec *d_mask; // inequality constraints mask vector - struct blasfeo_dvec *m; // rhs of complementarity condition - struct blasfeo_dvec *Z; // (diagonal) hessian of slacks - int *idxb; // indices of box constrained variables within [u; x] - int *idxs_rev; // index of soft constraints (reverse storage) - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_dense_qp_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_create(struct d_dense_qp_dim *dim, struct d_dense_qp *qp, void *memory); - -// setters - colmaj -// -void d_dense_qp_set_all(double *H, double *g, double *A, double *b, int *idxb, double *d_lb, double *d_ub, double *C, double *d_lg, double *d_ug, double *Zl, double *Zu, double *zl, double *zu, int *idxs, double *d_ls, double *d_us, struct d_dense_qp *qp); -// -void d_dense_qp_get_all(struct d_dense_qp *qp, double *H, double *g, double *A, double *b, int *idxb, double *d_lb, double *d_ub, double *C, double *d_lg, double *d_ug, double *Zl, double *Zu, double *zl, double *zu, int *idxs, double *d_ls, double *d_us); -// -void d_dense_qp_set(char *field, void *value, struct d_dense_qp *qp); -// -void d_dense_qp_set_H(double *H, struct d_dense_qp *qp); -// -void d_dense_qp_set_g(double *g, struct d_dense_qp *qp); -// -void d_dense_qp_set_A(double *A, struct d_dense_qp *qp); -// -void d_dense_qp_set_b(double *b, struct d_dense_qp *qp); -// -void d_dense_qp_set_idxb(int *idxb, struct d_dense_qp *qp); -// -void d_dense_qp_set_Jb(double *Jb, struct d_dense_qp *qp); -// -void d_dense_qp_set_lb(double *lb, struct d_dense_qp *qp); -// -void d_dense_qp_set_lb_mask(double *lb, struct d_dense_qp *qp); -// -void d_dense_qp_set_ub(double *ub, struct d_dense_qp *qp); -// -void d_dense_qp_set_ub_mask(double *ub, struct d_dense_qp *qp); -// -void d_dense_qp_set_C(double *C, struct d_dense_qp *qp); -// -void d_dense_qp_set_lg(double *lg, struct d_dense_qp *qp); -// -void d_dense_qp_set_lg_mask(double *lg, struct d_dense_qp *qp); -// -void d_dense_qp_set_ug(double *ug, struct d_dense_qp *qp); -// -void d_dense_qp_set_ug_mask(double *ug, struct d_dense_qp *qp); -// -void d_dense_qp_set_idxs(int *idxs, struct d_dense_qp *qp); -// -void d_dense_qp_set_idxs_rev(int *idxs_rev, struct d_dense_qp *qp); -// -void d_dense_qp_set_Jsb(double *Jsb, struct d_dense_qp *qp); -// -void d_dense_qp_set_Jsg(double *Jsg, struct d_dense_qp *qp); -// -void d_dense_qp_set_Zl(double *Zl, struct d_dense_qp *qp); -// -void d_dense_qp_set_Zu(double *Zu, struct d_dense_qp *qp); -// -void d_dense_qp_set_zl(double *zl, struct d_dense_qp *qp); -// -void d_dense_qp_set_zu(double *zu, struct d_dense_qp *qp); -// -void d_dense_qp_set_ls(double *ls, struct d_dense_qp *qp); -// -void d_dense_qp_set_ls_mask(double *ls, struct d_dense_qp *qp); -// -void d_dense_qp_set_us(double *us, struct d_dense_qp *qp); -// -void d_dense_qp_set_us_mask(double *us, struct d_dense_qp *qp); - -// getters - colmaj -// -void d_dense_qp_get_H(struct d_dense_qp *qp, double *H); -// -void d_dense_qp_get_g(struct d_dense_qp *qp, double *g); -// -void d_dense_qp_get_A(struct d_dense_qp *qp, double *A); -// -void d_dense_qp_get_b(struct d_dense_qp *qp, double *b); -// -void d_dense_qp_get_idxb(struct d_dense_qp *qp, int *idxb); -// -void d_dense_qp_get_lb(struct d_dense_qp *qp, double *lb); -// -void d_dense_qp_get_lb_mask(struct d_dense_qp *qp, double *lb); -// -void d_dense_qp_get_ub(struct d_dense_qp *qp, double *ub); -// -void d_dense_qp_get_ub_mask(struct d_dense_qp *qp, double *ub); -// -void d_dense_qp_get_C(struct d_dense_qp *qp, double *C); -// -void d_dense_qp_get_lg(struct d_dense_qp *qp, double *lg); -// -void d_dense_qp_get_lg_mask(struct d_dense_qp *qp, double *lg); -// -void d_dense_qp_get_ug(struct d_dense_qp *qp, double *ug); -// -void d_dense_qp_get_ug_mask(struct d_dense_qp *qp, double *ug); -// -void d_dense_qp_get_idxs(struct d_dense_qp *qp, int *idxs); -// -void d_dense_qp_get_idxs_rev(struct d_dense_qp *qp, int *idxs_rev); -// -void d_dense_qp_get_Zl(struct d_dense_qp *qp, double *Zl); -// -void d_dense_qp_get_Zu(struct d_dense_qp *qp, double *Zu); -// -void d_dense_qp_get_zl(struct d_dense_qp *qp, double *zl); -// -void d_dense_qp_get_zu(struct d_dense_qp *qp, double *zu); -// -void d_dense_qp_get_ls(struct d_dense_qp *qp, double *ls); -// -void d_dense_qp_get_ls_mask(struct d_dense_qp *qp, double *ls); -// -void d_dense_qp_get_us(struct d_dense_qp *qp, double *us); -// -void d_dense_qp_get_us_mask(struct d_dense_qp *qp, double *us); - -// setters - rowmaj -// -void d_dense_qp_set_all_rowmaj(double *H, double *g, double *A, double *b, int *idxb, double *d_lb, double *d_ub, double *C, double *d_lg, double *d_ug, double *Zl, double *Zu, double *zl, double *zu, int *idxs, double *d_ls, double *d_us, struct d_dense_qp *qp); - -// getters - rowmaj -// -void d_dense_qp_get_all_rowmaj(struct d_dense_qp *qp, double *H, double *g, double *A, double *b, int *idxb, double *d_lb, double *d_ub, double *C, double *d_lg, double *d_ug, double *Zl, double *Zu, double *zl, double *zu, int *idxs, double *d_ls, double *d_us); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_dim.h deleted file mode 100644 index 98a551f31258bf..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_dim.h +++ /dev/null @@ -1,92 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QP_DIM_H_ -#define HPIPM_D_DENSE_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp_dim - { - int nv; // number of variables - int ne; // number of equality constraints - int nb; // number of box constraints - int ng; // number of general constraints - int nsb; // number of softened box constraints - int nsg; // number of softened general constraints - int ns; // number of softened constraints (nsb+nsg) - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qp_dim_memsize(); -// -void d_dense_qp_dim_create(struct d_dense_qp_dim *qp_dim, void *memory); -// -void d_dense_qp_dim_set_all(int nv, int ne, int nb, int ng, int nsb, int nsg, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set(char *field_name, int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_nv(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_ne(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_nb(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_ng(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_nsb(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_nsg(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_ns(int value, struct d_dense_qp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_DENSE_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_ipm.h deleted file mode 100644 index e6e5d5d9b5b89a..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_ipm.h +++ /dev/null @@ -1,260 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QP_IPM_H_ -#define HPIPM_D_DENSE_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp_ipm_arg - { - double mu0; // initial value for duality measure - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double reg_dual; // reg of dual hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - double tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int scale; // scale hessian - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_res_exit; // compute residuals on exit (only for abs_form==1) - int comp_res_pred; // compute residuals of prediction - int kkt_fact_alg; // 0 null-space, 1 schur-complement - int remove_lin_dep_eq; // 0 do not, 1 do check and remove linearly dependent equality constraints - int compute_obj; // compute obj on exit - int split_step; // use different steps for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_dense_qp_ipm_ws - { - struct d_core_qp_ipm_workspace *core_workspace; - struct d_dense_qp_res_ws *res_ws; - struct d_dense_qp_sol *sol_step; - struct d_dense_qp_sol *sol_itref; - struct d_dense_qp *qp_step; - struct d_dense_qp *qp_itref; - struct d_dense_qp_res *res; - struct d_dense_qp_res *res_itref; - struct d_dense_qp_res *res_step; - struct blasfeo_dvec *Gamma; // - struct blasfeo_dvec *gamma; // - struct blasfeo_dvec *Zs_inv; // - struct blasfeo_dmat *Lv; // - struct blasfeo_dmat *AL; // - struct blasfeo_dmat *Le; // - struct blasfeo_dmat *Ctx; // - struct blasfeo_dvec *lv; // - struct blasfeo_dvec *sv; // scale for Lv - struct blasfeo_dvec *se; // scale for Le - struct blasfeo_dvec *tmp_nbg; // work space of size nb+ng - struct blasfeo_dvec *tmp_ns; // work space of size ns - struct blasfeo_dmat *lq0; - struct blasfeo_dmat *lq1; - struct blasfeo_dvec *tmp_m; - struct blasfeo_dmat *A_LQ; - struct blasfeo_dmat *A_Q; - struct blasfeo_dmat *Zt; - struct blasfeo_dmat *ZtH; - struct blasfeo_dmat *ZtHZ; - struct blasfeo_dvec *xy; - struct blasfeo_dvec *Yxy; - struct blasfeo_dvec *xz; - struct blasfeo_dvec *tmp_nv; - struct blasfeo_dvec *tmp_2ns; - struct blasfeo_dvec *tmp_nv2ns; - struct blasfeo_dmat *A_li; // A of linearly independent equality constraints - struct blasfeo_dvec *b_li; // b of linearly independent equality constraints - struct blasfeo_dmat *A_bkp; // pointer to backup A - struct blasfeo_dvec *b_bkp; // pointer to backup b - struct blasfeo_dmat *Ab_LU; - double *stat; // convergence statistics - int *ipiv_v; - int *ipiv_e; - int *ipiv_e1; - void *lq_work0; - void *lq_work1; - void *lq_work_null; - void *orglq_work_null; - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // numer of recorded stat per ipm iter - int scale; - int use_hess_fact; - int use_A_fact; - int status; - int lq_fact; // cache from arg - int mask_constr; // use constr mask - int ne_li; // number of linearly independent equality constraints - int ne_bkp; // ne backup - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t d_dense_qp_ipm_arg_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_ipm_arg_create(struct d_dense_qp_dim *dim, struct d_dense_qp_ipm_arg *arg, void *mem); -// -void d_dense_qp_ipm_arg_set_default(enum hpipm_mode mode, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set(char *field, void *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_iter_max(int *iter_max, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_alpha_min(double *alpha_min, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_mu0(double *mu0, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tol_stat(double *tol_stat, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tol_eq(double *tol_eq, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tol_ineq(double *tol_ineq, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tol_comp(double *tol_comp, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_reg_prim(double *reg, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_reg_dual(double *reg, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_warm_start(int *warm_start, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_pred_corr(int *pred_corr, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_lam_min(double *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_t_min(double *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tau_min(double *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_kkt_fact_alg(int *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_remove_lin_dep_eq(int *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_compute_obj(int *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_t_lam_min(int *value, struct d_dense_qp_ipm_arg *arg); - -// -void d_dense_qp_ipm_arg_set_split_step(int *value, struct d_dense_qp_ipm_arg *arg); - -// -hpipm_size_t d_dense_qp_ipm_ws_memsize(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_ws_create(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws, void *mem); -// -void d_dense_qp_ipm_get(char *field, struct d_dense_qp_ipm_ws *ws, void *value); -// -void d_dense_qp_ipm_get_status(struct d_dense_qp_ipm_ws *ws, int *status); -// -void d_dense_qp_ipm_get_iter(struct d_dense_qp_ipm_ws *ws, int *iter); -// -void d_dense_qp_ipm_get_max_res_stat(struct d_dense_qp_ipm_ws *ws, double *res_stat); -// -void d_dense_qp_ipm_get_max_res_eq(struct d_dense_qp_ipm_ws *ws, double *res_eq); -// -void d_dense_qp_ipm_get_max_res_ineq(struct d_dense_qp_ipm_ws *ws, double *res_ineq); -// -void d_dense_qp_ipm_get_max_res_comp(struct d_dense_qp_ipm_ws *ws, double *res_comp); -// -void d_dense_qp_ipm_get_stat(struct d_dense_qp_ipm_ws *ws, double **stat); -// -void d_dense_qp_ipm_get_stat_m(struct d_dense_qp_ipm_ws *ws, int *stat_m); -// -void d_dense_qp_init_var(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_abs_step(int kk, struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_delta_step(int kk, struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_solve(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_predict(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_sens(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_compute_step_length(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_kkt.h deleted file mode 100644 index 6d05779f4bab57..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_kkt.h +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QP_KKT_H_ -#define HPIPM_D_DENSE_QP_KKT_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_fact_solve_kkt_unconstr_dense_qp(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_fact_solve_kkt_step_dense_qp(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_fact_lq_solve_kkt_step_dense_qp(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_solve_kkt_step_dense_qp(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_remove_lin_dep_eq(struct d_dense_qp *qp, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_restore_lin_dep_eq(struct d_dense_qp *qp, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_compute_obj(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QP_KKT_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_res.h deleted file mode 100644 index 7c2023257a3c18..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_res.h +++ /dev/null @@ -1,105 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QP_RES_H_ -#define HPIPM_D_DENSE_QP_RES_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp_res - { - struct d_dense_qp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_dense_qp_res_ws - { - struct blasfeo_dvec *tmp_nbg; // work space of size nbM+ngM - struct blasfeo_dvec *tmp_ns; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qp_res_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_res_create(struct d_dense_qp_dim *dim, struct d_dense_qp_res *res, void *mem); -// -hpipm_size_t d_dense_qp_res_ws_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_res_ws_create(struct d_dense_qp_dim *dim, struct d_dense_qp_res_ws *workspace, void *mem); -// -void d_dense_qp_res_compute(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_res *res, struct d_dense_qp_res_ws *ws); -// -void d_dense_qp_res_compute_lin(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_sol *qp_step, struct d_dense_qp_res *res, struct d_dense_qp_res_ws *ws); -// -void d_dense_qp_res_compute_inf_norm(struct d_dense_qp_res *res); -// -void d_dense_qp_res_get_all(struct d_dense_qp_res *res, double *res_g, double *res_ls, double *res_us, double *res_b, double *res_d_lb, double *res_d_ub, double *res_d_lg, double *res_d_ug, double *res_d_ls, double *res_d_us, double *res_m_lb, double *res_m_ub, double *res_m_lg, double *res_m_ug, double *res_m_ls, double *res_m_us); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_DENSE_QP_RES_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_sol.h deleted file mode 100644 index aaa3fdb0e4904a..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_sol.h +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QP_SOL_H_ -#define HPIPM_D_DENSE_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp_sol - { - struct d_dense_qp_dim *dim; - struct blasfeo_dvec *v; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - double obj; - int valid_obj; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qp_sol_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_sol_create(struct d_dense_qp_dim *dim, struct d_dense_qp_sol *qp_sol, void *memory); -// -void d_dense_qp_sol_get_all(struct d_dense_qp_sol *qp_sol, double *v, double *ls, double *us, double *pi, double *lam_lb, double *lam_ub, double *lam_lg, double *lam_ug, double *lam_ls, double *lam_us); -// -void d_dense_qp_sol_get(char *field, struct d_dense_qp_sol *sol, void *value); -// -void d_dense_qp_sol_get_v(struct d_dense_qp_sol *sol, double *v); -// -void d_dense_qp_sol_get_valid_obj(struct d_dense_qp_sol *sol, int *valid_obj); -// -void d_dense_qp_sol_get_obj(struct d_dense_qp_sol *sol, double *obj); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_utils.h deleted file mode 100644 index ccb77aaca3cee7..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_utils.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QP_UTILS_H_ -#define HPIPM_D_DENSE_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp_dim.h" -#include "hpipm_d_dense_qp.h" -#include "hpipm_d_dense_qp_sol.h" -#include "hpipm_d_dense_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_dense_qp_dim_print(struct d_dense_qp_dim *qp_dim); -// -//void d_dense_qp_dim_codegen(char *file_name, char *mode, struct d_dense_qp_dim *qp_dim); -// -void d_dense_qp_print(struct d_dense_qp_dim *qp_dim, struct d_dense_qp *qp); -// -//void d_dense_qp_codegen(char *file_name, char *mode, struct d_dense_qp_dim *qp_dim, struct d_dense_qp *qp); -// -void d_dense_qp_sol_print(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_sol *dense_qp_sol); -// -//void d_dense_qp_ipm_arg_codegen(char *file_name, char *mode, struct d_dense_qp_dim *qp_dim, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_res_print(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_res *dense_qp_res); -// -void d_dense_qp_arg_print(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_ipm_arg *qp_ipm_arg); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_DENSE_QP_UTILS_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp.h deleted file mode 100644 index 240c9b04be7578..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp.h +++ /dev/null @@ -1,303 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_H_ -#define HPIPM_D_OCP_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp - { - struct d_ocp_qcqp_dim *dim; - struct blasfeo_dmat *BAbt; // dynamics matrix & vector work space - struct blasfeo_dmat *RSQrq; // hessian of cost & vector work space - struct blasfeo_dmat *DCt; // inequality constraints matrix - struct blasfeo_dmat **Hq; // hessians of quadratic constraints - struct blasfeo_dvec *b; // dynamics vector - struct blasfeo_dvec *rqz; // gradient of cost & gradient of slacks - struct blasfeo_dvec *d; // inequality constraints vector - struct blasfeo_dvec *d_mask; // inequality constraints mask vector - struct blasfeo_dvec *m; // rhs of complementarity condition - struct blasfeo_dvec *Z; // (diagonal) hessian of slacks - int **idxb; // indices of box constrained variables within [u; x] - int **idxs_rev; // index of soft constraints (reverse storage) - int **Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0 - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_ocp_qcqp_strsize(); -// -hpipm_size_t d_ocp_qcqp_memsize(struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_create(struct d_ocp_qcqp_dim *dim, struct d_ocp_qcqp *qp, void *memory); -// -void d_ocp_qcqp_copy_all(struct d_ocp_qcqp *qp_orig, struct d_ocp_qcqp *qp_dest); - -// setters -// -void d_ocp_qcqp_set_all_zero(struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_rhs_zero(struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set(char *field_name, int stage, void *value, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_el(char *field_name, int stage, int index, void *value, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_A(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_B(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_b(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Q(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_S(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_R(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_q(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_r(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lb(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lb_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ub(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ub_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lbx(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lbx_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_el_lbx(int stage, int index, double *elem, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ubx(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ubx_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_el_ubx(int stage, int index, double *elem, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lbu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lbu_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ubu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ubu_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxb(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxbx(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jbx(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxbu(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jbu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_C(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_D(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lg(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lg_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ug(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ug_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Qq(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Sq(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Rq(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_qq(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_rq(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_uq(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_uq_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Zl(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Zu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_zl(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_zu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lls(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lls_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lus(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lus_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxs(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxs_rev(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jsbu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jsbx(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jsg(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jsq(int stage, double *vec, struct d_ocp_qcqp *qp); - -// getters -// -void d_ocp_qcqp_get(char *field, int stage, struct d_ocp_qcqp *qp, void *value); -// -void d_ocp_qcqp_get_A(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_B(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_b(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_Q(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_S(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_R(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_q(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_r(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ub(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ub_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lb(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lb_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lbx(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lbx_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ubx(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ubx_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lbu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lbu_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ubu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ubu_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_idxb(int stage, struct d_ocp_qcqp *qp, int *vec); -// -//void d_ocp_qcqp_get_idxbx(int stage, struct d_ocp_qcqp *qp, int *vec); -// -//void d_ocp_qcqp_get_Jbx(int stage, struct d_ocp_qcqp *qp, double *vec); -// -//void d_ocp_qcqp_get_idxbu(int stage, struct d_ocp_qcqp *qp, int *vec); -// -//void d_ocp_qcqp_get_Jbu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_C(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_D(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_lg(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lg_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ug(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ug_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_Zl(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_Zu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_zl(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_zu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lls(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lls_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lus(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lus_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// XXX only valid if there is one slack per softed constraint !!! -void d_ocp_qcqp_get_idxs(int stage, struct d_ocp_qcqp *qp, int *vec); -// -void d_ocp_qcqp_get_idxs_rev(int stage, struct d_ocp_qcqp *qp, int *vec); -// -//void d_ocp_qcqp_get_Jsbu(int stage, struct d_ocp_qcqp *qp, float *vec); -// -//void d_ocp_qcqp_get_Jsbx(int stage, struct d_ocp_qcqp *qp, float *vec); -// -//void d_ocp_qcqp_get_Jsg(int stage, struct d_ocp_qcqp *qp, float *vec); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_dim.h deleted file mode 100644 index 268628a2b2bfc5..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_dim.h +++ /dev/null @@ -1,118 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_DIM_H_ -#define HPIPM_D_OCP_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp_dim - { - struct d_ocp_qp_dim *qp_dim; // dim of qp approximation - int *nx; // number of states - int *nu; // number of inputs - int *nb; // number of box constraints - int *nbx; // number of (two-sided) state box constraints - int *nbu; // number of (two-sided) input box constraints - int *ng; // number of (two-sided) general constraints - int *nq; // number of (upper) quadratic constraints - int *ns; // number of soft constraints - int *nsbx; // number of (two-sided) soft state box constraints - int *nsbu; // number of (two-sided) soft input box constraints - int *nsg; // number of (two-sided) soft general constraints - int *nsq; // number of (upper) soft quadratic constraints - int N; // horizon length - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qcqp_dim_strsize(); -// -hpipm_size_t d_ocp_qcqp_dim_memsize(int N); -// -void d_ocp_qcqp_dim_create(int N, struct d_ocp_qcqp_dim *qp_dim, void *memory); -// -void d_ocp_qcqp_dim_copy_all(struct d_ocp_qcqp_dim *dim_orig, struct d_ocp_qcqp_dim *dim_dest); -// -void d_ocp_qcqp_dim_set(char *field, int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nx(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nu(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nbx(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nbu(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_ng(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nq(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_ns(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nsbx(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nsbu(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nsg(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nsq(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_get(struct d_ocp_qcqp_dim *dim, char *field, int stage, int *value); -// -void d_ocp_qcqp_dim_get_N(struct d_ocp_qcqp_dim *dim, int *value); -// -void d_ocp_qcqp_dim_get_nx(struct d_ocp_qcqp_dim *dim, int stage, int *value); -// -void d_ocp_qcqp_dim_get_nu(struct d_ocp_qcqp_dim *dim, int stage, int *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QCQP_DIM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_ipm.h deleted file mode 100644 index 99f2329dcc3f16..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_ipm.h +++ /dev/null @@ -1,190 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_IPM_H_ -#define HPIPM_D_OCP_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp_ipm_arg - { - struct d_ocp_qp_ipm_arg *qp_arg; - double mu0; // initial value for complementarity slackness - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constrains (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_ocp_qcqp_ipm_ws - { - struct d_ocp_qp_ipm_ws *qp_ws; - struct d_ocp_qp *qp; - struct d_ocp_qp_sol *qp_sol; - struct d_ocp_qcqp_res_ws *qcqp_res_ws; - struct d_ocp_qcqp_res *qcqp_res; - struct blasfeo_dvec *tmp_nuxM; - int iter; // iteration number - int status; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qcqp_ipm_arg_strsize(); -// -hpipm_size_t d_ocp_qcqp_ipm_arg_memsize(struct d_ocp_qcqp_dim *ocp_dim); -// -void d_ocp_qcqp_ipm_arg_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_ipm_arg *arg, void *mem); -// -void d_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct d_ocp_qcqp_ipm_arg *arg); -// -void d_ocp_qcqp_ipm_arg_set(char *field, void *value, struct d_ocp_qcqp_ipm_arg *arg); -// set maximum number of iterations -void d_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// set minimum step lenght -void d_ocp_qcqp_ipm_arg_set_alpha_min(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set initial value of barrier parameter -void d_ocp_qcqp_ipm_arg_set_mu0(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void d_ocp_qcqp_ipm_arg_set_tol_stat(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on equality constr -void d_ocp_qcqp_ipm_arg_set_tol_eq(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on inequality constr -void d_ocp_qcqp_ipm_arg_set_tol_ineq(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void d_ocp_qcqp_ipm_arg_set_tol_comp(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set regularization of primal variables -void d_ocp_qcqp_ipm_arg_set_reg_prim(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void d_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void d_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void d_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -void d_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// compute residuals after solution -void d_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// compute residuals of prediction -void d_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// min value of lam in the solution -void d_ocp_qcqp_ipm_arg_set_lam_min(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// min value of t in the solution -void d_ocp_qcqp_ipm_arg_set_t_min(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// use different step for primal and dual variables -void d_ocp_qcqp_ipm_arg_set_split_step(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void d_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct d_ocp_qcqp_ipm_arg *arg); - -// -hpipm_size_t d_ocp_qcqp_ipm_ws_strsize(); -// -hpipm_size_t d_ocp_qcqp_ipm_ws_memsize(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_ipm_arg *arg); -// -void d_ocp_qcqp_ipm_ws_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_ipm_arg *arg, struct d_ocp_qcqp_ipm_ws *ws, void *mem); -// -void d_ocp_qcqp_ipm_get(char *field, struct d_ocp_qcqp_ipm_ws *ws, void *value); -// -void d_ocp_qcqp_ipm_get_status(struct d_ocp_qcqp_ipm_ws *ws, int *status); -// -void d_ocp_qcqp_ipm_get_iter(struct d_ocp_qcqp_ipm_ws *ws, int *iter); -// -void d_ocp_qcqp_ipm_get_max_res_stat(struct d_ocp_qcqp_ipm_ws *ws, double *res_stat); -// -void d_ocp_qcqp_ipm_get_max_res_eq(struct d_ocp_qcqp_ipm_ws *ws, double *res_eq); -// -void d_ocp_qcqp_ipm_get_max_res_ineq(struct d_ocp_qcqp_ipm_ws *ws, double *res_ineq); -// -void d_ocp_qcqp_ipm_get_max_res_comp(struct d_ocp_qcqp_ipm_ws *ws, double *res_comp); -// -void d_ocp_qcqp_ipm_get_stat(struct d_ocp_qcqp_ipm_ws *ws, double **stat); -// -void d_ocp_qcqp_ipm_get_stat_m(struct d_ocp_qcqp_ipm_ws *ws, int *stat_m); -// -void d_ocp_qcqp_init_var(struct d_ocp_qcqp *qp, struct d_ocp_qcqp_sol *qp_sol, struct d_ocp_qcqp_ipm_arg *arg, struct d_ocp_qcqp_ipm_ws *ws); -// -void d_ocp_qcqp_ipm_solve(struct d_ocp_qcqp *qp, struct d_ocp_qcqp_sol *qp_sol, struct d_ocp_qcqp_ipm_arg *arg, struct d_ocp_qcqp_ipm_ws *ws); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_OCP_QCQP_IPM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_res.h deleted file mode 100644 index 077f134677a2cc..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_res.h +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_RES_H_ -#define HPIPM_D_OCP_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp_res - { - struct d_ocp_qcqp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_ocp_qcqp_res_ws - { - struct blasfeo_dvec *tmp_nuxM; // work space of size nuM+nxM - struct blasfeo_dvec *tmp_nbgqM; // work space of size nbM+ngM+nqM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - struct blasfeo_dvec *q_fun; // value for evaluation of quadr constr - struct blasfeo_dvec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qcqp_res_memsize(struct d_ocp_qcqp_dim *ocp_dim); -// -void d_ocp_qcqp_res_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_res *res, void *mem); -// -hpipm_size_t d_ocp_qcqp_res_ws_memsize(struct d_ocp_qcqp_dim *ocp_dim); -// -void d_ocp_qcqp_res_ws_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_res_ws *workspace, void *mem); -// -void d_ocp_qcqp_res_compute(struct d_ocp_qcqp *qp, struct d_ocp_qcqp_sol *qp_sol, struct d_ocp_qcqp_res *res, struct d_ocp_qcqp_res_ws *ws); -// -void d_ocp_qcqp_res_compute_inf_norm(struct d_ocp_qcqp_res *res); -// -void d_ocp_qcqp_res_get_max_res_stat(struct d_ocp_qcqp_res *res, double *value); -// -void d_ocp_qcqp_res_get_max_res_eq(struct d_ocp_qcqp_res *res, double *value); -// -void d_ocp_qcqp_res_get_max_res_ineq(struct d_ocp_qcqp_res *res, double *value); -// -void d_ocp_qcqp_res_get_max_res_comp(struct d_ocp_qcqp_res *res, double *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_OCP_QCQP_RES_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_sol.h deleted file mode 100644 index 68adbfce2d0296..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_sol.h +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_SOL_H_ -#define HPIPM_D_OCP_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp_sol - { - struct d_ocp_qcqp_dim *dim; - struct blasfeo_dvec *ux; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_ocp_qcqp_sol_strsize(); -// -hpipm_size_t d_ocp_qcqp_sol_memsize(struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_sol_create(struct d_ocp_qcqp_dim *dim, struct d_ocp_qcqp_sol *qp_sol, void *memory); -// -void d_ocp_qcqp_sol_copy_all(struct d_ocp_qcqp_sol *qp_sol_orig, struct d_ocp_qcqp_sol *qp_sol_dest); -// -void d_ocp_qcqp_sol_get(char *field, int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_u(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_x(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_sl(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_su(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_pi(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_lam_lb(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_lam_ub(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_lam_lg(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_lam_ug(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_set(char *field, int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); -// -void d_ocp_qcqp_sol_set_u(int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); -// -void d_ocp_qcqp_sol_set_x(int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); -// -void d_ocp_qcqp_sol_set_sl(int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); -// -void d_ocp_qcqp_sol_set_su(int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QCQP_SOL_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_utils.h deleted file mode 100644 index 00248f1dbe65e3..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_utils.h +++ /dev/null @@ -1,81 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_UTILS_H_ -#define HPIPM_D_OCP_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qcqp_dim.h" -#include "hpipm_d_ocp_qp.h" -#include "hpipm_d_ocp_qcqp_sol.h" -#include "hpipm_d_ocp_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_ocp_qcqp_dim_print(struct d_ocp_qcqp_dim *qcqp_dim); -// -void d_ocp_qcqp_dim_codegen(char *file_name, char *mode, struct d_ocp_qcqp_dim *qcqp_dim); -// -void d_ocp_qcqp_print(struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_codegen(char *file_name, char *mode, struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_sol_print(struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp_sol *ocp_qcqp_sol); -// -void d_ocp_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp_ipm_arg *arg); -// -void d_ocp_qcqp_res_print(struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp_res *ocp_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QCQP_UTILS_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp.h deleted file mode 100644 index ca26cdba3406a1..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp.h +++ /dev/null @@ -1,306 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_H_ -#define HPIPM_D_OCP_QP_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp - { - struct d_ocp_qp_dim *dim; - struct blasfeo_dmat *BAbt; // dynamics matrix & vector work space - struct blasfeo_dmat *RSQrq; // hessian of cost & vector work space - struct blasfeo_dmat *DCt; // inequality constraints matrix - struct blasfeo_dvec *b; // dynamics vector - struct blasfeo_dvec *rqz; // gradient of cost & gradient of slacks - struct blasfeo_dvec *d; // inequality constraints vector - struct blasfeo_dvec *d_mask; // inequality constraints mask vector - struct blasfeo_dvec *m; // rhs of complementarity condition - struct blasfeo_dvec *Z; // (diagonal) hessian of slacks - int **idxb; // indices of box constrained variables within [u; x] - int **idxs_rev; // index of soft constraints (reverse storage) - int **idxe; // indices of constraints within [bu, bx, g] that are equalities, subset of [0, ..., nbu+nbx+ng-1] - int *diag_H_flag; // flag the fact that Hessian is diagonal - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_ocp_qp_strsize(); -// -hpipm_size_t d_ocp_qp_memsize(struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_create(struct d_ocp_qp_dim *dim, struct d_ocp_qp *qp, void *memory); -// -void d_ocp_qp_copy_all(struct d_ocp_qp *qp_orig, struct d_ocp_qp *qp_dest); - -// setters -// -void d_ocp_qp_set_all_zero(struct d_ocp_qp *qp); -// -void d_ocp_qp_set_rhs_zero(struct d_ocp_qp *qp); -// -void d_ocp_qp_set_all(double **A, double **B, double **b, double **Q, double **S, double **R, double **q, double **r, int **idxbx, double **lbx, double **ubx, int **idxbu, double **lbu, double **ubu, double **C, double **D, double **lg, double **ug, double **Zl, double **Zu, double **zl, double **zu, int **idxs, double **ls, double **us, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_all_rowmaj(double **A, double **B, double **b, double **Q, double **S, double **R, double **q, double **r, int **idxbx, double **lbx, double **ubx, int **idxbu, double **lbu, double **ubu, double **C, double **D, double **lg, double **ug, double **Zl, double **Zu, double **zl, double **zu, int **idxs, double **ls, double **us, struct d_ocp_qp *qp); -// -void d_ocp_qp_set(char *field_name, int stage, void *value, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_el(char *field_name, int stage, int index, void *value, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_A(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_B(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_b(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Q(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_S(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_R(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_q(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_r(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lb(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lb_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ub(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ub_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lbx(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lbx_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_el_lbx(int stage, int index, double *elem, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ubx(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ubx_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_el_ubx(int stage, int index, double *elem, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lbu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lbu_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ubu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ubu_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxb(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxbx(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jbx(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxbu(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jbu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_C(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_D(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lg(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lg_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ug(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ug_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Zl(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Zu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_zl(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_zu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lls(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lls_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lus(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lus_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxs(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxs_rev(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jsbu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jsbx(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jsg(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxe(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxbxe(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxbue(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxge(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jbxe(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jbue(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jge(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_diag_H_flag(int stage, int *value, struct d_ocp_qp *qp); - -// getters -// -void d_ocp_qp_get(char *field, int stage, struct d_ocp_qp *qp, void *value); -// -void d_ocp_qp_get_A(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_B(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_b(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_Q(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_S(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_R(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_q(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_r(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ub(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ub_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lb(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lb_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lbx(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lbx_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ubx(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ubx_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lbu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lbu_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ubu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ubu_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_idxb(int stage, struct d_ocp_qp *qp, int *vec); -// -//void d_ocp_qp_get_idxbx(int stage, struct d_ocp_qp *qp, int *vec); -// -//void d_ocp_qp_get_Jbx(int stage, struct d_ocp_qp *qp, double *vec); -// -//void d_ocp_qp_get_idxbu(int stage, struct d_ocp_qp *qp, int *vec); -// -//void d_ocp_qp_get_Jbu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_C(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_D(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_lg(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lg_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ug(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ug_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_Zl(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_Zu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_zl(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_zu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lls(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lls_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lus(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lus_mask(int stage, struct d_ocp_qp *qp, double *vec); -// XXX only valid if there is one slack per softed constraint !!! -void d_ocp_qp_get_idxs(int stage, struct d_ocp_qp *qp, int *vec); -// -void d_ocp_qp_get_idxs_rev(int stage, struct d_ocp_qp *qp, int *vec); -// -//void d_ocp_qp_get_Jsbu(int stage, struct d_ocp_qp *qp, float *vec); -// -//void d_ocp_qp_get_Jsbx(int stage, struct d_ocp_qp *qp, float *vec); -// -//void d_ocp_qp_get_Jsg(int stage, struct d_ocp_qp *qp, float *vec); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_dim.h deleted file mode 100644 index dcfb801d31fdde..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_dim.h +++ /dev/null @@ -1,142 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_DIM_H_ -#define HPIPM_D_OCP_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_dim - { - int *nx; // number of states - int *nu; // number of inputs - int *nb; // number of box constraints - int *nbx; // number of state box constraints - int *nbu; // number of input box constraints - int *ng; // number of general constraints - int *ns; // number of soft constraints - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int *nbxe; // number of state box constraints which are equality - int *nbue; // number of input box constraints which are equality - int *nge; // number of general constraints which are equality - int N; // horizon length - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qp_dim_strsize(); -// -hpipm_size_t d_ocp_qp_dim_memsize(int N); -// -void d_ocp_qp_dim_create(int N, struct d_ocp_qp_dim *qp_dim, void *memory); -// -void d_ocp_qp_dim_copy_all(struct d_ocp_qp_dim *dim_orig, struct d_ocp_qp_dim *dim_dest); -// -void d_ocp_qp_dim_set_all(int *nx, int *nu, int *nbx, int *nbu, int *ng, int *nsbx, int *nsbu, int *nsg, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set(char *field, int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nx(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nu(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nbx(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nbu(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_ng(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_ns(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nsbx(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nsbu(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nsg(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nbxe(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nbue(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nge(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_get(struct d_ocp_qp_dim *dim, char *field, int stage, int *value); -// -void d_ocp_qp_dim_get_N(struct d_ocp_qp_dim *dim, int *value); -// -void d_ocp_qp_dim_get_nx(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nu(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nbx(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nbu(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_ng(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_ns(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nsbx(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nsbu(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nsg(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nbxe(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nbue(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nge(struct d_ocp_qp_dim *dim, int stage, int *value); - - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_ipm.h deleted file mode 100644 index d2a2833f224df8..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_ipm.h +++ /dev/null @@ -1,250 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_IPM_H_ -#define HPIPM_D_OCP_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_ipm_arg - { - double mu0; // initial value for complementarity slackness - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - double tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different steps for primal and dual variables - int var_init_scheme; // variables initialization scheme - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_ocp_qp_ipm_ws - { - double qp_res[4]; // infinity norm of residuals - struct d_core_qp_ipm_workspace *core_workspace; - struct d_ocp_qp_dim *dim; // cache dim - struct d_ocp_qp_res_ws *res_workspace; - struct d_ocp_qp_sol *sol_step; - struct d_ocp_qp_sol *sol_itref; - struct d_ocp_qp *qp_step; - struct d_ocp_qp *qp_itref; - struct d_ocp_qp_res *res_itref; - struct d_ocp_qp_res *res; - struct blasfeo_dvec *Gamma; // hessian update - struct blasfeo_dvec *gamma; // hessian update - struct blasfeo_dvec *tmp_nuxM; // work space of size nxM - struct blasfeo_dvec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - struct blasfeo_dvec *Pb; // Pb - struct blasfeo_dvec *Zs_inv; - struct blasfeo_dvec *tmp_m; - struct blasfeo_dvec *l; // cache linear part for _get_ric_xxx - struct blasfeo_dmat *L; - struct blasfeo_dmat *Ls; - struct blasfeo_dmat *P; - struct blasfeo_dmat *Lh; - struct blasfeo_dmat *AL; - struct blasfeo_dmat *lq0; - struct blasfeo_dmat *tmp_nxM_nxM; - double *stat; // convergence statistics - int *use_hess_fact; - void *lq_work0; - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int use_Pb; - int status; // solver status - int square_root_alg; // cache from arg - int lq_fact; // cache from arg - int mask_constr; // use constr mask - int valid_ric_vec; // meaningful riccati vectors - int valid_ric_p; // form of riccati p: 0 p*inv(L), 1 p - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qp_ipm_arg_strsize(); -// -hpipm_size_t d_ocp_qp_ipm_arg_memsize(struct d_ocp_qp_dim *ocp_dim); -// -void d_ocp_qp_ipm_arg_create(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_ipm_arg *arg, void *mem); -// -void d_ocp_qp_ipm_arg_set_default(enum hpipm_mode mode, struct d_ocp_qp_ipm_arg *arg); -// -void d_ocp_qp_ipm_arg_set(char *field, void *value, struct d_ocp_qp_ipm_arg *arg); -// set maximum number of iterations -void d_ocp_qp_ipm_arg_set_iter_max(int *iter_max, struct d_ocp_qp_ipm_arg *arg); -// set minimum step lenght -void d_ocp_qp_ipm_arg_set_alpha_min(double *alpha_min, struct d_ocp_qp_ipm_arg *arg); -// set initial value of barrier parameter -void d_ocp_qp_ipm_arg_set_mu0(double *mu0, struct d_ocp_qp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void d_ocp_qp_ipm_arg_set_tol_stat(double *tol_stat, struct d_ocp_qp_ipm_arg *arg); -// set exit tolerance on equality constr -void d_ocp_qp_ipm_arg_set_tol_eq(double *tol_eq, struct d_ocp_qp_ipm_arg *arg); -// set exit tolerance on inequality constr -void d_ocp_qp_ipm_arg_set_tol_ineq(double *tol_ineq, struct d_ocp_qp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void d_ocp_qp_ipm_arg_set_tol_comp(double *tol_comp, struct d_ocp_qp_ipm_arg *arg); -// set regularization of primal variables -void d_ocp_qp_ipm_arg_set_reg_prim(double *tol_comp, struct d_ocp_qp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void d_ocp_qp_ipm_arg_set_warm_start(int *warm_start, struct d_ocp_qp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void d_ocp_qp_ipm_arg_set_pred_corr(int *pred_corr, struct d_ocp_qp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void d_ocp_qp_ipm_arg_set_cond_pred_corr(int *value, struct d_ocp_qp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -void d_ocp_qp_ipm_arg_set_ric_alg(int *value, struct d_ocp_qp_ipm_arg *arg); -// dual solution of equality constraints (only for abs_form==1) -void d_ocp_qp_ipm_arg_set_comp_dual_sol_eq(int *value, struct d_ocp_qp_ipm_arg *arg); -// compute residuals after solution -void d_ocp_qp_ipm_arg_set_comp_res_exit(int *value, struct d_ocp_qp_ipm_arg *arg); -// compute residuals of prediction -void d_ocp_qp_ipm_arg_set_comp_res_pred(int *value, struct d_ocp_qp_ipm_arg *arg); -// min value of lam in the solution -void d_ocp_qp_ipm_arg_set_lam_min(double *value, struct d_ocp_qp_ipm_arg *arg); -// min value of t in the solution -void d_ocp_qp_ipm_arg_set_t_min(double *value, struct d_ocp_qp_ipm_arg *arg); -// min value of tau in the solution -void d_ocp_qp_ipm_arg_set_tau_min(double *value, struct d_ocp_qp_ipm_arg *arg); -// set split step: 0 same step, 1 different step for primal and dual variables -void d_ocp_qp_ipm_arg_set_split_step(int *value, struct d_ocp_qp_ipm_arg *arg); -// variables initialization scheme -void d_ocp_qp_ipm_arg_set_var_init_scheme(int *value, struct d_ocp_qp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void d_ocp_qp_ipm_arg_set_t_lam_min(int *value, struct d_ocp_qp_ipm_arg *arg); - -// -hpipm_size_t d_ocp_qp_ipm_ws_strsize(); -// -hpipm_size_t d_ocp_qp_ipm_ws_memsize(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_ipm_arg *arg); -// -void d_ocp_qp_ipm_ws_create(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, void *mem); -// -void d_ocp_qp_ipm_get(char *field, struct d_ocp_qp_ipm_ws *ws, void *value); -// -void d_ocp_qp_ipm_get_status(struct d_ocp_qp_ipm_ws *ws, int *status); -// -void d_ocp_qp_ipm_get_iter(struct d_ocp_qp_ipm_ws *ws, int *iter); -// -void d_ocp_qp_ipm_get_max_res_stat(struct d_ocp_qp_ipm_ws *ws, double *res_stat); -// -void d_ocp_qp_ipm_get_max_res_eq(struct d_ocp_qp_ipm_ws *ws, double *res_eq); -// -void d_ocp_qp_ipm_get_max_res_ineq(struct d_ocp_qp_ipm_ws *ws, double *res_ineq); -// -void d_ocp_qp_ipm_get_max_res_comp(struct d_ocp_qp_ipm_ws *ws, double *res_comp); -// -void d_ocp_qp_ipm_get_stat(struct d_ocp_qp_ipm_ws *ws, double **stat); -// -void d_ocp_qp_ipm_get_stat_m(struct d_ocp_qp_ipm_ws *ws, int *stat_m); -// -void d_ocp_qp_ipm_get_ric_Lr(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *Lr); -// -void d_ocp_qp_ipm_get_ric_Ls(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *Ls); -// -void d_ocp_qp_ipm_get_ric_P(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *P); -// -void d_ocp_qp_ipm_get_ric_lr(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *lr); -// -void d_ocp_qp_ipm_get_ric_p(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *p); -// feedback control gain in the form u = K x + k -void d_ocp_qp_ipm_get_ric_K(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *K); -// feedback control gain in the form u = K x + k -void d_ocp_qp_ipm_get_ric_k(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *k); -// -void d_ocp_qp_init_var(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_abs_step(int kk, struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_delta_step(int kk, struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_solve(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_predict(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_sens(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); - - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_OCP_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_kkt.h deleted file mode 100644 index 19dcec32caa974..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_kkt.h +++ /dev/null @@ -1,66 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_KKT_H_ -#define HPIPM_D_OCP_QP_KKT_H_ - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - -// -void d_ocp_qp_fact_solve_kkt_unconstr(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_fact_solve_kkt_step(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_fact_lq_solve_kkt_step(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_solve_kkt_step(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - -#endif // HPIPM_D_OCP_QP_KKT_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_red.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_red.h deleted file mode 100644 index f0482b04441eb9..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_red.h +++ /dev/null @@ -1,117 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_RED_H_ -#define HPIPM_D_OCP_QP_RED_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_reduce_eq_dof_arg - { - double lam_min; - double t_min; - int alias_unchanged; // do not keep copy unchanged stage - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution inequality constr (lam t) - hpipm_size_t memsize; // memory size in bytes - }; - - - -struct d_ocp_qp_reduce_eq_dof_ws - { - struct blasfeo_dvec *tmp_nuxM; - struct blasfeo_dvec *tmp_nbgM; - int *e_imask_ux; - int *e_imask_d; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -void d_ocp_qp_dim_reduce_eq_dof(struct d_ocp_qp_dim *dim, struct d_ocp_qp_dim *dim_red); -// -hpipm_size_t d_ocp_qp_reduce_eq_dof_arg_memsize(); -// -void d_ocp_qp_reduce_eq_dof_arg_create(struct d_ocp_qp_reduce_eq_dof_arg *arg, void *mem); -// -void d_ocp_qp_reduce_eq_dof_arg_set_default(struct d_ocp_qp_reduce_eq_dof_arg *arg); -// -void d_ocp_qp_reduce_eq_dof_arg_set_alias_unchanged(struct d_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void d_ocp_qp_reduce_eq_dof_arg_set_comp_prim_sol(struct d_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void d_ocp_qp_reduce_eq_dof_arg_set_comp_dual_sol_eq(struct d_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void d_ocp_qp_reduce_eq_dof_arg_set_comp_dual_sol_ineq(struct d_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -hpipm_size_t d_ocp_qp_reduce_eq_dof_ws_memsize(struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_reduce_eq_dof_ws_create(struct d_ocp_qp_dim *dim, struct d_ocp_qp_reduce_eq_dof_ws *work, void *mem); -// -void d_ocp_qp_reduce_eq_dof(struct d_ocp_qp *qp, struct d_ocp_qp *qp_red, struct d_ocp_qp_reduce_eq_dof_arg *arg, struct d_ocp_qp_reduce_eq_dof_ws *work); -// -void d_ocp_qp_reduce_eq_dof_lhs(struct d_ocp_qp *qp, struct d_ocp_qp *qp_red, struct d_ocp_qp_reduce_eq_dof_arg *arg, struct d_ocp_qp_reduce_eq_dof_ws *work); -// -void d_ocp_qp_reduce_eq_dof_rhs(struct d_ocp_qp *qp, struct d_ocp_qp *qp_red, struct d_ocp_qp_reduce_eq_dof_arg *arg, struct d_ocp_qp_reduce_eq_dof_ws *work); -// -void d_ocp_qp_restore_eq_dof(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol_red, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_reduce_eq_dof_arg *arg, struct d_ocp_qp_reduce_eq_dof_ws *work); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_RED_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_res.h deleted file mode 100644 index 061c5729cd6e76..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_res.h +++ /dev/null @@ -1,112 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_RES_H_ -#define HPIPM_D_OCP_QP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_res - { - struct d_ocp_qp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_ocp_qp_res_ws - { - struct blasfeo_dvec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qp_res_memsize(struct d_ocp_qp_dim *ocp_dim); -// -void d_ocp_qp_res_create(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_res *res, void *mem); -// -hpipm_size_t d_ocp_qp_res_ws_memsize(struct d_ocp_qp_dim *ocp_dim); -// -void d_ocp_qp_res_ws_create(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_res_ws *workspace, void *mem); -// -void d_ocp_qp_res_compute(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_res *res, struct d_ocp_qp_res_ws *ws); -// -void d_ocp_qp_res_compute_lin(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_sol *qp_step, struct d_ocp_qp_res *res, struct d_ocp_qp_res_ws *ws); -// -void d_ocp_qp_res_compute_inf_norm(struct d_ocp_qp_res *res); -// -void d_ocp_qp_res_get_all(struct d_ocp_qp_res *res, double **res_r, double **res_q, double **res_ls, double **res_us, double **res_b, double **res_d_lb, double **res_d_ub, double **res_d_lg, double **res_d_ug, double **res_d_ls, double **res_d_us, double **res_m_lb, double **res_m_ub, double **res_m_lg, double **res_m_ug, double **res_m_ls, double **res_m_us); -// -void d_ocp_qp_res_get_max_res_stat(struct d_ocp_qp_res *res, double *value); -// -void d_ocp_qp_res_get_max_res_eq(struct d_ocp_qp_res *res, double *value); -// -void d_ocp_qp_res_get_max_res_ineq(struct d_ocp_qp_res *res, double *value); -// -void d_ocp_qp_res_get_max_res_comp(struct d_ocp_qp_res *res, double *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_OCP_QP_RES_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_sol.h deleted file mode 100644 index eb91f3a7b1451f..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_sol.h +++ /dev/null @@ -1,128 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_SOL_H_ -#define HPIPM_D_OCP_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_sol - { - struct d_ocp_qp_dim *dim; - struct blasfeo_dvec *ux; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_ocp_qp_sol_strsize(); -// -hpipm_size_t d_ocp_qp_sol_memsize(struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_sol_create(struct d_ocp_qp_dim *dim, struct d_ocp_qp_sol *qp_sol, void *memory); -// -void d_ocp_qp_sol_copy_all(struct d_ocp_qp_sol *qp_sol_orig, struct d_ocp_qp_sol *qp_sol_dest); -// -void d_ocp_qp_sol_get_all(struct d_ocp_qp_sol *qp_sol, double **u, double **x, double **ls, double **us, double **pi, double **lam_lb, double **lam_ub, double **lam_lg, double **lam_ug, double **lam_ls, double **lam_us); -// -void d_ocp_qp_sol_get_all_rowmaj(struct d_ocp_qp_sol *qp_sol, double **u, double **x, double **ls, double **us, double **pi, double **lam_lb, double **lam_ub, double **lam_lg, double **lam_ug, double **lam_ls, double **lam_us); -// -void d_ocp_qp_sol_set_all(double **u, double **x, double **ls, double **us, double **pi, double **lam_lb, double **lam_ub, double **lam_lg, double **lam_ug, double **lam_ls, double **lam_us, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_get(char *field, int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_u(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_x(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_sl(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_su(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_pi(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_lb(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_lbu(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_lbx(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_ub(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_ubu(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_ubx(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_lg(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_ug(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_set(char *field, int stage, double *vec, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_set_u(int stage, double *vec, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_set_x(int stage, double *vec, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_set_sl(int stage, double *vec, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_set_su(int stage, double *vec, struct d_ocp_qp_sol *qp_sol); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_utils.h deleted file mode 100644 index 217e9d94ae7116..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_utils.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_UTILS_H_ -#define HPIPM_D_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qp_dim.h" -#include "hpipm_d_ocp_qp.h" -#include "hpipm_d_ocp_qp_sol.h" -#include "hpipm_d_ocp_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_ocp_qp_dim_print(struct d_ocp_qp_dim *qp_dim); -// -void d_ocp_qp_dim_codegen(char *file_name, char *mode, struct d_ocp_qp_dim *qp_dim); -// -void d_ocp_qp_print(struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp *qp); -// -void d_ocp_qp_codegen(char *file_name, char *mode, struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp *qp); -// -void d_ocp_qp_sol_print(struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp_sol *ocp_qp_sol); -// -void d_ocp_qp_ipm_arg_print(struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp_ipm_arg *arg); -// -void d_ocp_qp_ipm_arg_codegen(char *file_name, char *mode, struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp_ipm_arg *arg); -// -void d_ocp_qp_res_print(struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp_res *ocp_qp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_UTILS_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_part_cond.h b/third_party/acados/include/hpipm/include/hpipm_d_part_cond.h deleted file mode 100644 index 1c5f7850356a67..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_part_cond.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_PART_COND_H_ -#define HPIPM_D_PART_COND_H_ - - - -#include -#include - -#include "hpipm_common.h" -#include "hpipm_d_cond.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_part_cond_qp_arg - { - struct d_cond_qp_arg *cond_arg; - int N2; - hpipm_size_t memsize; - }; - - - -struct d_part_cond_qp_ws - { - struct d_cond_qp_ws *cond_workspace; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_part_cond_qp_arg_memsize(int N2); -// -void d_part_cond_qp_arg_create(int N2, struct d_part_cond_qp_arg *cond_arg, void *mem); -// -void d_part_cond_qp_arg_set_default(struct d_part_cond_qp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 squre-root -void d_part_cond_qp_arg_set_ric_alg(int ric_alg, struct d_part_cond_qp_arg *cond_arg); -// -void d_part_cond_qp_arg_set_comp_prim_sol(int value, struct d_part_cond_qp_arg *cond_arg); -// -void d_part_cond_qp_arg_set_comp_dual_sol_eq(int value, struct d_part_cond_qp_arg *cond_arg); -// -void d_part_cond_qp_arg_set_comp_dual_sol_ineq(int value, struct d_part_cond_qp_arg *cond_arg); - -// -void d_part_cond_qp_compute_block_size(int N, int N2, int *block_size); -// -void d_part_cond_qp_compute_dim(struct d_ocp_qp_dim *ocp_dim, int *block_size, struct d_ocp_qp_dim *part_dense_dim); -// -hpipm_size_t d_part_cond_qp_ws_memsize(struct d_ocp_qp_dim *ocp_dim, int *block_size, struct d_ocp_qp_dim *part_dense_dim, struct d_part_cond_qp_arg *cond_arg); -// -void d_part_cond_qp_ws_create(struct d_ocp_qp_dim *ocp_dim, int *block_size, struct d_ocp_qp_dim *part_dense_dim, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws, void *mem); -// -void d_part_cond_qp_cond(struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); -// -void d_part_cond_qp_cond_lhs(struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); -// -void d_part_cond_qp_cond_rhs(struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); -// -void d_part_cond_qp_expand_sol(struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_ocp_qp_sol *part_dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_sol, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); - -// -void d_part_cond_qp_update(int *idxc, struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_PART_COND_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_part_cond_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_part_cond_qcqp.h deleted file mode 100644 index 2d6624e5bbd0e6..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_part_cond_qcqp.h +++ /dev/null @@ -1,106 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_PART_COND_QCQP_H_ -#define HPIPM_D_PART_COND_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_cond_qcqp.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_part_cond_qcqp_arg - { - struct d_cond_qcqp_arg *cond_arg; - int N2; - hpipm_size_t memsize; - }; - - - -struct d_part_cond_qcqp_ws - { - struct d_cond_qcqp_ws *cond_ws; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_part_cond_qcqp_arg_memsize(int N2); -// -void d_part_cond_qcqp_arg_create(int N2, struct d_part_cond_qcqp_arg *cond_arg, void *mem); -// -void d_part_cond_qcqp_arg_set_default(struct d_part_cond_qcqp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 squre-root -void d_part_cond_qcqp_arg_set_ric_alg(int ric_alg, struct d_part_cond_qcqp_arg *cond_arg); - -// -void d_part_cond_qcqp_compute_block_size(int N, int N2, int *block_size); -// -void d_part_cond_qcqp_compute_dim(struct d_ocp_qcqp_dim *ocp_dim, int *block_size, struct d_ocp_qcqp_dim *part_dense_dim); -// -hpipm_size_t d_part_cond_qcqp_ws_memsize(struct d_ocp_qcqp_dim *ocp_dim, int *block_size, struct d_ocp_qcqp_dim *part_dense_dim, struct d_part_cond_qcqp_arg *cond_arg); -// -void d_part_cond_qcqp_ws_create(struct d_ocp_qcqp_dim *ocp_dim, int *block_size, struct d_ocp_qcqp_dim *part_dense_dim, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws, void *mem); -// -void d_part_cond_qcqp_cond(struct d_ocp_qcqp *ocp_qp, struct d_ocp_qcqp *part_dense_qp, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws); -// -void d_part_cond_qcqp_cond_lhs(struct d_ocp_qcqp *ocp_qp, struct d_ocp_qcqp *part_dense_qp, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws); -// -void d_part_cond_qcqp_cond_rhs(struct d_ocp_qcqp *ocp_qp, struct d_ocp_qcqp *part_dense_qp, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws); -// -void d_part_cond_qcqp_expand_sol(struct d_ocp_qcqp *ocp_qp, struct d_ocp_qcqp *part_dense_qp, struct d_ocp_qcqp_sol *part_dense_qp_sol, struct d_ocp_qcqp_sol *ocp_qp_sol, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_PART_COND_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_sim_erk.h b/third_party/acados/include/hpipm/include/hpipm_d_sim_erk.h deleted file mode 100644 index 320b66bb28c201..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_sim_erk.h +++ /dev/null @@ -1,122 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_SIM_ERK_H_ -#define HPIPM_D_SIM_ERK_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_sim_erk_arg - { - struct d_sim_rk_data *rk_data; // integrator data - double h; // step size - int steps; // number of steps -// int for_sens; // compute adjoint sensitivities -// int adj_sens; // compute adjoint sensitivities - hpipm_size_t memsize; - }; - - - -struct d_sim_erk_ws - { - void (*ode)(int t, double *x, double *p, void *ode_args, double *xdot); // function pointer to ode - void (*vde_for)(int t, double *x, double *p, void *ode_args, double *xdot); // function pointer to forward vde - void (*vde_adj)(int t, double *adj_in, void *ode_args, double *adj_out); // function pointer to adjoint vde - void *ode_args; // pointer to ode args - struct d_sim_erk_arg *erk_arg; // erk arg - double *K; // internal variables - double *x_for; // states and forward sensitivities - double *x_traj; // states at all steps - double *l; // adjoint sensitivities - double *p; // parameter - double *x_tmp; // temporary states and forward sensitivities - double *adj_in; - double *adj_tmp; - int nx; // number of states - int np; // number of parameters - int nf; // number of forward sensitivities - int na; // number of adjoint sensitivities - int nf_max; // max number of forward sensitivities - int na_max; // max number of adjoint sensitivities - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_sim_erk_arg_memsize(); -// -void d_sim_erk_arg_create(struct d_sim_erk_arg *erk_arg, void *mem); -// -void d_sim_erk_arg_set_all(struct d_sim_rk_data *rk_data, double h, int steps, struct d_sim_erk_arg *erk_arg); - -// -hpipm_size_t d_sim_erk_ws_memsize(struct d_sim_erk_arg *erk_arg, int nx, int np, int nf_max, int na_max); -// -void d_sim_erk_ws_create(struct d_sim_erk_arg *erk_arg, int nx, int np, int nf_max, int na_max, struct d_sim_erk_ws *work, void *memory); -// -void d_sim_erk_ws_set_all(int nf, int na, double *x, double *fs, double *bs, double *p, void (*ode)(int t, double *x, double *p, void *ode_args, double *xdot), void (*vde_for)(int t, double *x, double *p, void *ode_args, double *xdot), void (*vde_adj)(int t, double *adj_in, void *ode_args, double *adj_out), void *ode_args, struct d_sim_erk_ws *work); -// number of directions for forward sensitivities -void d_sim_erk_ws_set_nf(int *nf, struct d_sim_erk_ws *work); -// parameters (e.g. inputs) -void d_sim_erk_ws_set_p(double *p, struct d_sim_erk_ws *work); -// state -void d_sim_erk_ws_set_x(double *x, struct d_sim_erk_ws *work); -// forward sensitivities -void d_sim_erk_ws_set_fs(double *fs, struct d_sim_erk_ws *work); -// ode funtion -void d_sim_erk_ws_set_ode(void (*ode)(int t, double *x, double *p, void *ode_args, double *xdot), struct d_sim_erk_ws *work); -// forward vde function -void d_sim_erk_ws_set_vde_for(void (*ode)(int t, double *x, double *p, void *ode_args, double *xdot), struct d_sim_erk_ws *work); -// ode_args, passed straight to the ode/vde_for/vde_adj functions -void d_sim_erk_ws_set_ode_args(void *ode_args, struct d_sim_erk_ws *work); -// state -void d_sim_erk_ws_get_x(struct d_sim_erk_ws *work, double *x); -// forward sensitivities -void d_sim_erk_ws_get_fs(struct d_sim_erk_ws *work, double *fs); -// -void d_sim_erk_solve(struct d_sim_erk_arg *arg, struct d_sim_erk_ws *work); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_D_SIM_ERK_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_sim_rk.h b/third_party/acados/include/hpipm/include/hpipm_d_sim_rk.h deleted file mode 100644 index a50dcbb491ceea..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_sim_rk.h +++ /dev/null @@ -1,71 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_SIM_RK_H_ -#define HPIPM_D_SIM_RK_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_sim_rk_data - { - double *A_rk; // A in butcher tableau - double *B_rk; // b in butcher tableau - double *C_rk; // c in butcher tableau - int expl; // erk vs irk - int ns; // number of stages - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_sim_rk_data_memsize(int ns); -// -void d_sim_rk_data_create(int ns, struct d_sim_rk_data *rk_data, void *memory); -// -void d_sim_rk_data_init_default(char *field, struct d_sim_rk_data *rk_data); -// -void d_sim_rk_data_set_all(int expl, double *A_rk, double *B_rk, double *C_rk, struct d_sim_rk_data *rk_data); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_D_SIM_RK_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp.h deleted file mode 100644 index f36b51a06433f1..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp.h +++ /dev/null @@ -1,213 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_H_ -#define HPIPM_D_TREE_OCP_QCQP_H_ - - - -#include -#include - -#include "hpipm_common.h" -#include "hpipm_d_tree_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qcqp - { - struct d_tree_ocp_qcqp_dim *dim; - struct blasfeo_dmat *BAbt; // Nn-1 - struct blasfeo_dmat *RSQrq; // Nn - struct blasfeo_dmat *DCt; // Nn - struct blasfeo_dmat **Hq; // Nn - struct blasfeo_dvec *b; // Nn-1 - struct blasfeo_dvec *rqz; // Nn - struct blasfeo_dvec *d; // Nn - struct blasfeo_dvec *d_mask; // Nn - struct blasfeo_dvec *m; // Nn - struct blasfeo_dvec *Z; // Nn - int **idxb; // indices of box constrained variables within [u; x] // Nn - int **idxs_rev; // index of soft constraints - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_memsize(struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_create(struct d_tree_ocp_qcqp_dim *dim, struct d_tree_ocp_qcqp *qp, void *memory); -// -void d_tree_ocp_qcqp_set_all(double **A, double **B, double **b, double **Q, double **S, double **R, double **q, double **r, int **idxb, double **d_lb, double **d_ub, double **C, double **D, double **d_lg, double **d_ug, double **Zl, double **Zu, double **zl, double **zu, int **idxs, double **d_ls, double **d_us, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set(char *field_name, int node_edge, void *value, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_A(int edge, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_B(int edge, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_b(int edge, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Q(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_S(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_R(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_q(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_r(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lb(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lb_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ub(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ub_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lbx(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lbx_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ubx(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ubx_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lbu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lbu_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ubu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ubu_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxb(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxbx(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jbx(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxbu(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jbu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_C(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_D(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lg(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lg_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ug(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ug_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Qq(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Sq(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Rq(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_qq(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_rq(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_uq(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_uq_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Zl(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Zu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_zl(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_zu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lls(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lls_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lus(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lus_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxs(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxs_rev(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jsbu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jsbx(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jsg(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jsq(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_idxe(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_idxbxe(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_idxbue(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_idxge(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_Jbxe(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_Jbue(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_Jge(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_diag_H_flag(int node, int *value, struct d_tree_ocp_qcqp *qp); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_dim.h deleted file mode 100644 index 257b82b2522bfe..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_dim.h +++ /dev/null @@ -1,117 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_DIM_H_ -#define HPIPM_D_TREE_OCP_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qcqp_dim - { - struct d_tree_ocp_qp_dim *qp_dim; // dim of qp approximation - struct tree *ttree; // tree describing node conndection - int *nx; // number of states // Nn - int *nu; // number of inputs // Nn - int *nb; // number of box constraints // Nn - int *nbx; // number of state box constraints // Nn - int *nbu; // number of input box constraints // Nn - int *ng; // number of general constraints // Nn - int *nq; // number of (upper) quadratic constraints - int *ns; // number of soft constraints // Nn - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int *nsq; // number of (upper) soft quadratic constraints - int Nn; // number of nodes - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_dim_strsize(); -// -hpipm_size_t d_tree_ocp_qcqp_dim_memsize(int Nn); -// -void d_tree_ocp_qcqp_dim_create(int Nn, struct d_tree_ocp_qcqp_dim *qp_dim, void *memory); -// -void d_tree_ocp_qcqp_dim_set_tree(struct tree *ttree, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set(char *field, int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nx(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nu(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nbx(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nbu(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_ng(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nq(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_ns(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nsbx(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nsbu(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nsg(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nsq(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -//void d_tree_ocp_qcqp_dim_set_nbxe(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -//void d_tree_ocp_qcqp_dim_set_nbue(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -//void d_tree_ocp_qcqp_dim_set_nge(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_TREE_OCP_QCQP_DIM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_ipm.h deleted file mode 100644 index 4a0fed1067aac8..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_ipm.h +++ /dev/null @@ -1,191 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_IPM_H_ -#define HPIPM_D_TREE_OCP_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qcqp_ipm_arg - { - struct d_tree_ocp_qp_ipm_arg *qp_arg; - double mu0; // initial value for complementarity slackness - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol -// int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constrains (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) -// int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_tree_ocp_qcqp_ipm_ws - { - struct d_tree_ocp_qp_ipm_ws *qp_ws; - struct d_tree_ocp_qp *qp; - struct d_tree_ocp_qp_sol *qp_sol; - struct d_tree_ocp_qcqp_res_ws *qcqp_res_ws; - struct d_tree_ocp_qcqp_res *qcqp_res; - struct blasfeo_dvec *tmp_nuxM; - int iter; // iteration number - int status; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_ipm_arg_strsize(); -// -hpipm_size_t d_tree_ocp_qcqp_ipm_arg_memsize(struct d_tree_ocp_qcqp_dim *ocp_dim); -// -void d_tree_ocp_qcqp_ipm_arg_create(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg, void *mem); -// -void d_tree_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct d_tree_ocp_qcqp_ipm_arg *arg); -// -void d_tree_ocp_qcqp_ipm_arg_set(char *field, void *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set maximum number of iterations -void d_tree_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set minimum step lenght -void d_tree_ocp_qcqp_ipm_arg_set_alpha_min(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set initial value of barrier parameter -void d_tree_ocp_qcqp_ipm_arg_set_mu0(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void d_tree_ocp_qcqp_ipm_arg_set_tol_stat(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on equality constr -void d_tree_ocp_qcqp_ipm_arg_set_tol_eq(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on inequality constr -void d_tree_ocp_qcqp_ipm_arg_set_tol_ineq(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void d_tree_ocp_qcqp_ipm_arg_set_tol_comp(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set regularization of primal variables -void d_tree_ocp_qcqp_ipm_arg_set_reg_prim(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void d_tree_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void d_tree_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void d_tree_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -//void d_tree_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// compute residuals after solution -void d_tree_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// compute residuals of prediction -//void d_tree_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// min value of lam in the solution -void d_tree_ocp_qcqp_ipm_arg_set_lam_min(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// min value of t in the solution -void d_tree_ocp_qcqp_ipm_arg_set_t_min(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// use different step for primal and dual variables -void d_tree_ocp_qcqp_ipm_arg_set_split_step(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void d_tree_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); - -// -hpipm_size_t d_tree_ocp_qcqp_ipm_ws_strsize(); -// -hpipm_size_t d_tree_ocp_qcqp_ipm_ws_memsize(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg); -// -void d_tree_ocp_qcqp_ipm_ws_create(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg, struct d_tree_ocp_qcqp_ipm_ws *ws, void *mem); -// -void d_tree_ocp_qcqp_ipm_get(char *field, struct d_tree_ocp_qcqp_ipm_ws *ws, void *value); -// -void d_tree_ocp_qcqp_ipm_get_status(struct d_tree_ocp_qcqp_ipm_ws *ws, int *status); -// -void d_tree_ocp_qcqp_ipm_get_iter(struct d_tree_ocp_qcqp_ipm_ws *ws, int *iter); -// -void d_tree_ocp_qcqp_ipm_get_max_res_stat(struct d_tree_ocp_qcqp_ipm_ws *ws, double *res_stat); -// -void d_tree_ocp_qcqp_ipm_get_max_res_eq(struct d_tree_ocp_qcqp_ipm_ws *ws, double *res_eq); -// -void d_tree_ocp_qcqp_ipm_get_max_res_ineq(struct d_tree_ocp_qcqp_ipm_ws *ws, double *res_ineq); -// -void d_tree_ocp_qcqp_ipm_get_max_res_comp(struct d_tree_ocp_qcqp_ipm_ws *ws, double *res_comp); -// -void d_tree_ocp_qcqp_ipm_get_stat(struct d_tree_ocp_qcqp_ipm_ws *ws, double **stat); -// -void d_tree_ocp_qcqp_ipm_get_stat_m(struct d_tree_ocp_qcqp_ipm_ws *ws, int *stat_m); -// -void d_tree_ocp_qcqp_init_var(struct d_tree_ocp_qcqp *qp, struct d_tree_ocp_qcqp_sol *qp_sol, struct d_tree_ocp_qcqp_ipm_arg *arg, struct d_tree_ocp_qcqp_ipm_ws *ws); -// -void d_tree_ocp_qcqp_ipm_solve(struct d_tree_ocp_qcqp *qp, struct d_tree_ocp_qcqp_sol *qp_sol, struct d_tree_ocp_qcqp_ipm_arg *arg, struct d_tree_ocp_qcqp_ipm_ws *ws); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_TREE_OCP_QCQP_IPM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_res.h deleted file mode 100644 index 69eebb1ba4d674..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_res.h +++ /dev/null @@ -1,108 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_RES_H_ -#define HPIPM_D_TREE_OCP_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qcqp_res - { - struct d_tree_ocp_qcqp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_tree_ocp_qcqp_res_ws - { - struct blasfeo_dvec *tmp_nuxM; // work space of size nuM+nxM - struct blasfeo_dvec *tmp_nbgqM; // work space of size nbM+ngM+nqM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - struct blasfeo_dvec *q_fun; // value for evaluation of quadr constr - struct blasfeo_dvec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_res_memsize(struct d_tree_ocp_qcqp_dim *ocp_dim); -// -void d_tree_ocp_qcqp_res_create(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_res *res, void *mem); -// -hpipm_size_t d_tree_ocp_qcqp_res_ws_memsize(struct d_tree_ocp_qcqp_dim *ocp_dim); -// -void d_tree_ocp_qcqp_res_ws_create(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_res_ws *ws, void *mem); -// -void d_tree_ocp_qcqp_res_compute(struct d_tree_ocp_qcqp *qp, struct d_tree_ocp_qcqp_sol *qp_sol, struct d_tree_ocp_qcqp_res *res, struct d_tree_ocp_qcqp_res_ws *ws); -// -void d_tree_ocp_qcqp_res_compute_inf_norm(struct d_tree_ocp_qcqp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_TREE_OCP_QCQP_RES_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_sol.h deleted file mode 100644 index cde8de5c51b769..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_sol.h +++ /dev/null @@ -1,99 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_SOL_H_ -#define HPIPM_D_TREE_OCP_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_tree_ocp_qcqp_sol - { - struct d_tree_ocp_qcqp_dim *dim; - struct blasfeo_dvec *ux; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_sol_memsize(struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_sol_create(struct d_tree_ocp_qcqp_dim *dim, struct d_tree_ocp_qcqp_sol *qp_sol, void *memory); -// -void d_tree_ocp_qcqp_sol_get(char *field, int node_edge, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_u(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_x(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_sl(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_su(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_pi(int edge, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_lam_lb(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_lam_ub(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_lam_lg(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_lam_ug(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QCQP_SOL_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_utils.h deleted file mode 100644 index 5ef04fcf66fc56..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_utils.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_UTILS_H_ -#define HPIPM_D_TREE_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qcqp_dim.h" -#include "hpipm_d_tree_ocp_qcqp.h" -#include "hpipm_d_tree_ocp_qcqp_sol.h" -#include "hpipm_d_tree_ocp_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_tree_ocp_qcqp_dim_print(struct d_tree_ocp_qcqp_dim *qp_dim); -// -//void d_tree_ocp_qcqp_dim_codegen(char *file_name, char *mode, struct d_tree_ocp_qcqp_dim *qp_dim); -// -void d_tree_ocp_qcqp_print(struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_codegen(char *file_name, char *mode, struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_sol_print(struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp_sol *ocp_qcqp_sol); -// -void d_tree_ocp_qcqp_ipm_arg_print(struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg); -// -//void d_tree_ocp_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg); -// -void d_tree_ocp_qcqp_res_print(struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp_res *ocp_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp.h deleted file mode 100644 index 1666ad7c71bc3a..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp.h +++ /dev/null @@ -1,195 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_H_ -#define HPIPM_D_TREE_OCP_QP_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qp - { - struct d_tree_ocp_qp_dim *dim; - struct blasfeo_dmat *BAbt; // Nn-1 - struct blasfeo_dmat *RSQrq; // Nn - struct blasfeo_dmat *DCt; // Nn - struct blasfeo_dvec *b; // Nn-1 - struct blasfeo_dvec *rqz; // Nn - struct blasfeo_dvec *d; // Nn - struct blasfeo_dvec *d_mask; // Nn - struct blasfeo_dvec *m; // Nn - struct blasfeo_dvec *Z; // Nn - int **idxb; // indices of box constrained variables within [u; x] // Nn -// int **idxs; // index of soft constraints - int **idxs_rev; // index of soft constraints - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_tree_ocp_qp_memsize(struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_create(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp *qp, void *memory); -// -void d_tree_ocp_qp_set_all(double **A, double **B, double **b, double **Q, double **S, double **R, double **q, double **r, int **idxb, double **d_lb, double **d_ub, double **C, double **D, double **d_lg, double **d_ug, double **Zl, double **Zu, double **zl, double **zu, int **idxs, double **d_ls, double **d_us, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set(char *field_name, int node_edge, void *value, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_A(int edge, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_B(int edge, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_b(int edge, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Q(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_S(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_R(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_q(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_r(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lb(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lb_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ub(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ub_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lbx(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lbx_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ubx(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ubx_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lbu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lbu_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ubu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ubu_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxb(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxbx(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jbx(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxbu(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jbu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_C(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_D(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lg(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lg_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ug(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ug_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Zl(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Zu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_zl(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_zu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lls(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lls_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lus(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lus_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxs(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxs_rev(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jsbu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jsbx(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jsg(int node, double *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_idxe(int node, int *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_idxbxe(int node, int *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_idxbue(int node, int *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_idxge(int node, int *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_Jbxe(int node, double *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_Jbue(int node, double *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_Jge(int node, double *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_diag_H_flag(int node, int *value, struct d_tree_ocp_qp *qp); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_dim.h deleted file mode 100644 index 659b664594263e..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_dim.h +++ /dev/null @@ -1,111 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_DIM_H_ -#define HPIPM_D_TREE_OCP_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qp_dim - { - struct tree *ttree; // tree describing node conndection - int *nx; // number of states // Nn - int *nu; // number of inputs // Nn - int *nb; // number of box constraints // Nn - int *nbx; // number of state box constraints // Nn - int *nbu; // number of input box constraints // Nn - int *ng; // number of general constraints // Nn - int *ns; // number of soft constraints // Nn - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int Nn; // number of nodes - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qp_dim_strsize(); -// -hpipm_size_t d_tree_ocp_qp_dim_memsize(int Nn); -// -void d_tree_ocp_qp_dim_create(int Nn, struct d_tree_ocp_qp_dim *qp_dim, void *memory); -// -void d_tree_ocp_qp_dim_set_all(struct tree *ttree, int *nx, int *nu, int *nbx, int *nbu, int *ng, int *nsbx, int *nsbu, int *nsg, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_tree(struct tree *ttree, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set(char *field, int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nx(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nu(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nbx(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nbu(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_ng(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_ns(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nsbx(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nsbu(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nsg(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nbxe(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nbue(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nge(int stage, int value, struct d_tree_ocp_qp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_ipm.h deleted file mode 100644 index fb634208ce8845..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_ipm.h +++ /dev/null @@ -1,209 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_TREE_OCP_QP_IPM_H_ -#define HPIPM_D_TREE_OCP_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qp_ipm_arg - { - double mu0; // initial value for duality measure - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - double tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol==1) - int split_step; // use different steps for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_tree_ocp_qp_ipm_ws - { - struct d_core_qp_ipm_workspace *core_workspace; - struct d_tree_ocp_qp_res_ws *res_workspace; - struct d_tree_ocp_qp_sol *sol_step; - struct d_tree_ocp_qp_sol *sol_itref; - struct d_tree_ocp_qp *qp_step; - struct d_tree_ocp_qp *qp_itref; - struct d_tree_ocp_qp_res *res_itref; - struct d_tree_ocp_qp_res *res; - struct blasfeo_dvec *Gamma; // hessian update - struct blasfeo_dvec *gamma; // hessian update - struct blasfeo_dvec *tmp_nxM; // work space of size nxM - struct blasfeo_dvec *tmp_nbgM; // work space of size nbgM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - struct blasfeo_dvec *Pb; // Pb - struct blasfeo_dvec *Zs_inv; - struct blasfeo_dmat *L; - struct blasfeo_dmat *Lh; - struct blasfeo_dmat *AL; - struct blasfeo_dmat *lq0; - struct blasfeo_dvec *tmp_m; - double *stat; // convergence statistics - int *use_hess_fact; - void *lq_work0; - double qp_res[4]; // infinity norm of residuals - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int use_Pb; - int status; // solver status - int lq_fact; // cache from arg - int mask_constr; // use constr mask - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qp_ipm_arg_memsize(struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_ipm_arg_create(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp_ipm_arg *arg, void *mem); -// -void d_tree_ocp_qp_ipm_arg_set_default(enum hpipm_mode mode, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_iter_max(int *iter_max, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_alpha_min(double *alpha_min, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_mu0(double *mu0, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tol_stat(double *tol_stat, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tol_eq(double *tol_eq, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tol_ineq(double *tol_ineq, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tol_comp(double *tol_comp, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_reg_prim(double *reg, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_warm_start(int *warm_start, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_pred_corr(int *pred_corr, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_cond_pred_corr(int *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_comp_dual_sol_eq(int *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_comp_res_exit(int *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_lam_min(double *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_t_min(double *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tau_min(double *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_split_step(int *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_t_lam_min(int *value, struct d_tree_ocp_qp_ipm_arg *arg); - -// -hpipm_size_t d_tree_ocp_qp_ipm_ws_memsize(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_ws_create(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws, void *mem); -// -void d_tree_ocp_qp_ipm_get_status(struct d_tree_ocp_qp_ipm_ws *ws, int *status); -// -void d_tree_ocp_qp_ipm_get_iter(struct d_tree_ocp_qp_ipm_ws *ws, int *iter); -// -void d_tree_ocp_qp_ipm_get_max_res_stat(struct d_tree_ocp_qp_ipm_ws *ws, double *res_stat); -// -void d_tree_ocp_qp_ipm_get_max_res_eq(struct d_tree_ocp_qp_ipm_ws *ws, double *res_eq); -// -void d_tree_ocp_qp_ipm_get_max_res_ineq(struct d_tree_ocp_qp_ipm_ws *ws, double *res_ineq); -// -void d_tree_ocp_qp_ipm_get_max_res_comp(struct d_tree_ocp_qp_ipm_ws *ws, double *res_comp); -// -void d_tree_ocp_qp_ipm_get_stat(struct d_tree_ocp_qp_ipm_ws *ws, double **stat); -// -void d_tree_ocp_qp_ipm_get_stat_m(struct d_tree_ocp_qp_ipm_ws *ws, int *stat_m); -// -void d_tree_ocp_qp_init_var(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_ipm_abs_step(int kk, struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_ipm_delta_step(int kk, struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_ipm_solve(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_kkt.h deleted file mode 100644 index 4afd52fe4bf1cc..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_kkt.h +++ /dev/null @@ -1,52 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - -// -void d_tree_ocp_qp_fact_solve_kkt_unconstr(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_fact_solve_kkt_step(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_fact_lq_solve_kkt_step(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_solve_kkt_step(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_res.h deleted file mode 100644 index fe499080ea89a3..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_res.h +++ /dev/null @@ -1,106 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_RES_H_ -#define HPIPM_D_TREE_OCP_QP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qp_res - { - struct d_tree_ocp_qp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_tree_ocp_qp_res_ws - { - struct blasfeo_dvec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qp_res_memsize(struct d_tree_ocp_qp_dim *ocp_dim); -// -void d_tree_ocp_qp_res_create(struct d_tree_ocp_qp_dim *ocp_dim, struct d_tree_ocp_qp_res *res, void *mem); -// -hpipm_size_t d_tree_ocp_qp_res_ws_memsize(struct d_tree_ocp_qp_dim *ocp_dim); -// -void d_tree_ocp_qp_res_ws_create(struct d_tree_ocp_qp_dim *ocp_dim, struct d_tree_ocp_qp_res_ws *ws, void *mem); -// -void d_tree_ocp_qp_res_get_all(struct d_tree_ocp_qp_res *res, double **res_r, double **res_q, double **res_ls, double **res_us, double **res_b, double **res_d_lb, double **res_d_ub, double **res_d_lg, double **res_d_ug, double **res_d_ls, double **res_d_us, double **res_m_lb, double **res_m_ub, double **res_m_lg, double **res_m_ug, double **res_m_ls, double **res_m_us); -// -void d_tree_ocp_qp_res_compute(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_res *res, struct d_tree_ocp_qp_res_ws *ws); -// -void d_tree_ocp_qp_res_compute_lin(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_sol *qp_step, struct d_tree_ocp_qp_res *res, struct d_tree_ocp_qp_res_ws *ws); -// -void d_tree_ocp_qp_res_compute_inf_norm(struct d_tree_ocp_qp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_TREE_OCP_QP_RES_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_sol.h deleted file mode 100644 index 343d5e8ca6a171..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_sol.h +++ /dev/null @@ -1,100 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_SOL_H_ -#define HPIPM_D_TREE_OCP_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_tree_ocp_qp_sol - { - struct d_tree_ocp_qp_dim *dim; - struct blasfeo_dvec *ux; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_tree_ocp_qp_sol_memsize(struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_sol_create(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp_sol *qp_sol, void *memory); -// -void d_tree_ocp_qp_sol_get_all(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, double **u, double **x, double **ls, double **us, double **pi, double **lam_lb, double **lam_ub, double **lam_lg, double **lam_ug, double **lam_ls, double **lam_us); -// -void d_tree_ocp_qp_sol_get(char *field, int node_edge, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_u(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_x(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_sl(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_su(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_pi(int edge, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_lam_lb(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_lam_ub(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_lam_lg(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_lam_ug(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_utils.h deleted file mode 100644 index b689fdc0fa2d59..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_utils.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_UTILS_H_ -#define HPIPM_D_TREE_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qp_dim.h" -#include "hpipm_d_tree_ocp_qp.h" -#include "hpipm_d_tree_ocp_qp_sol.h" -#include "hpipm_d_tree_ocp_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_tree_ocp_qp_dim_print(struct d_tree_ocp_qp_dim *qp_dim); -// -//void d_tree_ocp_qp_dim_codegen(char *file_name, char *mode, struct d_tree_ocp_qp_dim *qp_dim); -// -void d_tree_ocp_qp_print(struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_codegen(char *file_name, char *mode, struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_sol_print(struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp_sol *ocp_qp_sol); -// -void d_tree_ocp_qp_ipm_arg_print(struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp_ipm_arg *arg); -// -//void d_tree_ocp_qp_ipm_arg_codegen(char *file_name, char *mode, struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_res_print(struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp_res *ocp_qp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_UTILS_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_m_dense_qp.h b/third_party/acados/include/hpipm/include/hpipm_m_dense_qp.h deleted file mode 100644 index 8bc101003e208a..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_dense_qp.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - - -#ifndef HPIPM_M_DENSE_QP_H_ -#define HPIPM_M_DENSE_QP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp.h" -#include "hpipm_s_dense_qp.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -void cvt_d2s_dense_qp(struct d_dense_qp *qpd, struct s_dense_qp *qps); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_M_DENSE_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_m_dense_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_m_dense_qp_dim.h deleted file mode 100644 index 4610321b970c9e..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_dense_qp_dim.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - - -#ifndef HPIPM_M_DENSE_QP_DIM_H_ -#define HPIPM_M_DENSE_QP_DIM_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp_dim.h" -#include "hpipm_s_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -void cvt_d2s_dense_qp_dim(struct d_dense_qp_dim *qpd, struct s_dense_qp_dim *qps); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_M_DENSE_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp.h deleted file mode 100644 index 95c3dad1aa02be..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp.h +++ /dev/null @@ -1,49 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -void m_cvt_d_ocp_qp_to_s_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp); - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_ipm_hard.h b/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_ipm_hard.h deleted file mode 100644 index 1c44acee2e8497..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_ipm_hard.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -struct m_ipm_hard_ocp_qp_workspace - { - struct d_ipm_hard_core_qp_workspace *core_workspace; - struct blasfeo_dvec *dux; - struct blasfeo_dvec *dpi; - struct blasfeo_dvec *dt_lb; - struct blasfeo_dvec *dt_lg; - struct blasfeo_svec *sdux; // XXX - struct blasfeo_svec *sdpi; // XXX - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals XXX remove ??? - struct blasfeo_dvec *res_d_lb; // d-residuals - struct blasfeo_dvec *res_d_ub; // d-residuals - struct blasfeo_dvec *res_d_lg; // d-residuals - struct blasfeo_dvec *res_d_ug; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - struct blasfeo_dvec *res_m_lb; // m-residuals - struct blasfeo_dvec *res_m_ub; // m-residuals - struct blasfeo_dvec *res_m_lg; // m-residuals - struct blasfeo_dvec *res_m_ug; // m-residuals - struct blasfeo_svec *sres_g; // q-residuals // XXX - struct blasfeo_svec *sres_b; // b-residuals // XXX - struct blasfeo_dvec *Qx_lb; // hessian update - struct blasfeo_dvec *Qx_lg; // hessian update - struct blasfeo_dvec *qx_lb; // gradient update - struct blasfeo_dvec *qx_lg; // gradient update - struct blasfeo_svec *sQx_lb; // hessian update // XXX - struct blasfeo_svec *sQx_lg; // hessian update // XXX - struct blasfeo_svec *sqx_lb; // gradient update // XXX - struct blasfeo_svec *sqx_lg; // gradient update // XXX - struct blasfeo_dvec *tmp_nbM; // work space of size nbM - struct blasfeo_svec *tmp_nxM; // work space of size nxM // XXX - struct blasfeo_dvec *tmp_ngM; // work space of size ngM - struct blasfeo_svec *Pb; // Pb // XXX - struct blasfeo_smat *L; // XXX - struct blasfeo_smat *AL; // XXX - struct blasfeo_svec *sSx; // scaling - struct blasfeo_svec *sSi; // scaling inverted - double *stat; // convergence statistics - double res_mu; // mu-residual - int iter; // iteration number - int compute_Pb; - int scale; - }; - - - -struct m_ipm_hard_ocp_qp_arg - { - double alpha_min; // exit cond on step length - double mu_max; // exit cond on duality measure - double mu0; // initial value for duality measure - int iter_max; // exit cond in iter number - }; - - - -// -hpipm_size_t m_memsize_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_arg *arg); -// -void m_create_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_arg *arg, struct m_ipm_hard_ocp_qp_workspace *ws, void *mem); -// -void m_solve_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct d_ocp_qp_sol *qp_sol, struct m_ipm_hard_ocp_qp_workspace *ws); -// -void m_solve_ipm2_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct d_ocp_qp_sol *qp_sol, struct m_ipm_hard_ocp_qp_workspace *ws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_kkt.h deleted file mode 100644 index 032fe95b1f9897..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_kkt.h +++ /dev/null @@ -1,45 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -void m_fact_solve_kkt_step_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_workspace *ws); -void m_solve_kkt_step_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_workspace *ws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_s_cast_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_cast_qcqp.h deleted file mode 100644 index ba01ecb3bd437e..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_cast_qcqp.h +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_CAST_QCQP_H_ -#define HPIPM_S_CAST_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp.h" -#include "hpipm_s_dense_qcqp_sol.h" -#include "hpipm_s_ocp_qcqp.h" -#include "hpipm_s_ocp_qcqp_dim.h" -#include "hpipm_s_ocp_qcqp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_cast_qcqp_compute_dim(struct s_ocp_qcqp_dim *ocp_dim, struct s_dense_qcqp_dim *dense_dim); -// -void s_cast_qcqp_cond(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp *dense_qp); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_CAST_QCQP_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_cond.h b/third_party/acados/include/hpipm/include/hpipm_s_cond.h deleted file mode 100644 index 30116798b77599..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_cond.h +++ /dev/null @@ -1,137 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_COND_H_ -#define HPIPM_S_COND_H_ - - - -#include -#include - -#include "hpipm_s_dense_qp.h" -#include "hpipm_s_dense_qp_sol.h" -#include "hpipm_s_ocp_qp.h" -#include "hpipm_s_ocp_qp_dim.h" -#include "hpipm_s_ocp_qp_sol.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_cond_qp_arg - { - int cond_last_stage; // condense last stage - int cond_alg; // condensing algorithm: 0 N2-nx3, 1 N3-nx2 - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution inequality constr (lam t) - int square_root_alg; // square root algorithm (faster but requires RSQ>0) - hpipm_size_t memsize; - }; - - - -struct s_cond_qp_ws - { - struct blasfeo_smat *Gamma; - struct blasfeo_smat *GammaQ; - struct blasfeo_smat *L; - struct blasfeo_smat *Lx; - struct blasfeo_smat *AL; - struct blasfeo_svec *Gammab; - struct blasfeo_svec *l; - struct blasfeo_svec *tmp_nbgM; - struct blasfeo_svec *tmp_nuxM; - int bs; // block size - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_cond_qp_arg_memsize(); -// -void s_cond_qp_arg_create(struct s_cond_qp_arg *cond_arg, void *mem); -// -void s_cond_qp_arg_set_default(struct s_cond_qp_arg *cond_arg); -// condensing algorithm: 0 N2-nx3, 1 N3-nx2 -void s_cond_qp_arg_set_cond_alg(int cond_alg, struct s_cond_qp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 square-root -void s_cond_qp_arg_set_ric_alg(int ric_alg, struct s_cond_qp_arg *cond_arg); -// condense last stage: 0 last stage disregarded, 1 last stage condensed too -void s_cond_qp_arg_set_cond_last_stage(int cond_last_stage, struct s_cond_qp_arg *cond_arg); -// -void s_cond_qp_arg_set_comp_prim_sol(int value, struct s_cond_qp_arg *cond_arg); -// -void s_cond_qp_arg_set_comp_dual_sol_eq(int value, struct s_cond_qp_arg *cond_arg); -// -void s_cond_qp_arg_set_comp_dual_sol_ineq(int value, struct s_cond_qp_arg *cond_arg); - -// -void s_cond_qp_compute_dim(struct s_ocp_qp_dim *ocp_dim, struct s_dense_qp_dim *dense_dim); -// -hpipm_size_t s_cond_qp_ws_memsize(struct s_ocp_qp_dim *ocp_dim, struct s_cond_qp_arg *cond_arg); -// -void s_cond_qp_ws_create(struct s_ocp_qp_dim *ocp_dim, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws, void *mem); -// -void s_cond_qp_cond(struct s_ocp_qp *ocp_qp, struct s_dense_qp *dense_qp, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_qp_cond_lhs(struct s_ocp_qp *ocp_qp, struct s_dense_qp *dense_qp, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_qp_cond_rhs(struct s_ocp_qp *ocp_qp, struct s_dense_qp *dense_qp, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_qp_expand_sol(struct s_ocp_qp *ocp_qp, struct s_dense_qp_sol *dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// TODO remove -void s_cond_qp_expand_primal_sol(struct s_ocp_qp *ocp_qp, struct s_dense_qp_sol *dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); - -// -void s_cond_qp_update(int *idxc, struct s_ocp_qp *ocp_qp, struct s_dense_qp *dense_qp, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_COND_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_cond_aux.h b/third_party/acados/include/hpipm/include/hpipm_s_cond_aux.h deleted file mode 100644 index 003472ab9f3069..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_cond_aux.h +++ /dev/null @@ -1,92 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_COND_AUX_H_ -#define HPIPM_S_COND_AUX_H_ - - - -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_cond_BAbt(struct s_ocp_qp *ocp_qp, struct blasfeo_smat *BAbt2, struct blasfeo_svec *b2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_BAt(struct s_ocp_qp *ocp_qp, struct blasfeo_smat *BAbt2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_b(struct s_ocp_qp *ocp_qp, struct blasfeo_svec *b2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_RSQrq(struct s_ocp_qp *ocp_qp, struct blasfeo_smat *RSQrq2, struct blasfeo_svec *rq2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_RSQ(struct s_ocp_qp *ocp_qp, struct blasfeo_smat *RSQrq2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_rq(struct s_ocp_qp *ocp_qp, struct blasfeo_svec *rq2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_DCtd(struct s_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_smat *DCt2, struct blasfeo_svec *d2, struct blasfeo_svec *d_mask2, int *idxs_rev2, struct blasfeo_svec *Z2, struct blasfeo_svec *z2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_DCt(struct s_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_smat *DCt2, int *idxs_rev2, struct blasfeo_svec *Z2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_d(struct s_ocp_qp *ocp_qp, struct blasfeo_svec *d2, struct blasfeo_svec *d_mask2, struct blasfeo_svec *z2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_expand_sol(struct s_ocp_qp *ocp_qp, struct s_dense_qp_sol *dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_expand_primal_sol(struct s_ocp_qp *ocp_qp, struct s_dense_qp_sol *dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); - -// -void s_update_cond_BAbt(int *idxc, struct s_ocp_qp *ocp_qp, struct blasfeo_smat *BAbt2, struct blasfeo_svec *b2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_update_cond_RSQrq_N2nx3(int *idxc, struct s_ocp_qp *ocp_qp, struct blasfeo_smat *RSQrq2, struct blasfeo_svec *rq2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_update_cond_DCtd(int *idxc, struct s_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_smat *DCt2, struct blasfeo_svec *d2, int *idxs2, struct blasfeo_svec *Z2, struct blasfeo_svec *z2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_COND_AUX_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_cond_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_cond_qcqp.h deleted file mode 100644 index c36678abd55953..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_cond_qcqp.h +++ /dev/null @@ -1,130 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_COND_QCQP_H_ -#define HPIPM_S_COND_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp.h" -#include "hpipm_s_dense_qcqp_sol.h" -#include "hpipm_s_ocp_qcqp.h" -#include "hpipm_s_ocp_qcqp_dim.h" -#include "hpipm_s_ocp_qcqp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_cond_qcqp_arg - { - struct s_cond_qp_arg *qp_arg; - int cond_last_stage; // condense last stage -// int cond_variant; // TODO - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution equality constr (lam t) - int square_root_alg; // square root algorithm (faster but requires RSQ>0) - hpipm_size_t memsize; - }; - - - -struct s_cond_qcqp_ws - { - struct s_cond_qp_ws *qp_ws; - struct blasfeo_smat *hess_array; // TODO remove - struct blasfeo_smat *zero_hess; // TODO remove - struct blasfeo_svec *zero_grad; // TODO remove - struct blasfeo_svec *grad_array; // TODO remove - struct blasfeo_svec *tmp_nvc; - struct blasfeo_svec *tmp_nuxM; - struct blasfeo_smat *GammaQ; - struct blasfeo_smat *tmp_DCt; - struct blasfeo_smat *tmp_nuM_nxM; -// struct blasfeo_svec *d_qp; -// struct blasfeo_svec *d_mask_qp; - hpipm_size_t memsize; - }; - - -// -hpipm_size_t s_cond_qcqp_arg_memsize(); -// -void s_cond_qcqp_arg_create(struct s_cond_qcqp_arg *cond_arg, void *mem); -// -void s_cond_qcqp_arg_set_default(struct s_cond_qcqp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 square-root -void s_cond_qcqp_arg_set_ric_alg(int ric_alg, struct s_cond_qcqp_arg *cond_arg); -// condense last stage: 0 last stage disregarded, 1 last stage condensed too -void s_cond_qcqp_arg_set_cond_last_stage(int cond_last_stage, struct s_cond_qcqp_arg *cond_arg); - -// -void s_cond_qcqp_compute_dim(struct s_ocp_qcqp_dim *ocp_dim, struct s_dense_qcqp_dim *dense_dim); -// -hpipm_size_t s_cond_qcqp_ws_memsize(struct s_ocp_qcqp_dim *ocp_dim, struct s_cond_qcqp_arg *cond_arg); -// -void s_cond_qcqp_ws_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws, void *mem); -// -void s_cond_qcqp_qc(struct s_ocp_qcqp *ocp_qp, struct blasfeo_smat *Hq2, int *Hq_nzero2, struct blasfeo_smat *Ct2, struct blasfeo_svec *d2, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_qc_lhs(struct s_ocp_qcqp *ocp_qp, struct blasfeo_smat *Hq2, int *Hq_nzero2, struct blasfeo_smat *Ct2, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_qc_rhs(struct s_ocp_qcqp *ocp_qp, struct blasfeo_svec *d2, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_cond(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp *dense_qp, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_cond_rhs(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp *dense_qp, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_cond_lhs(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp *dense_qp, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_expand_sol(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp_sol *dense_qp_sol, struct s_ocp_qcqp_sol *ocp_qp_sol, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_COND_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm.h deleted file mode 100644 index 480392c7d91f11..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm.h +++ /dev/null @@ -1,101 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_CORE_QP_IPM_ -#define HPIPM_S_CORE_QP_IPM_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_core_qp_ipm_workspace - { - float *v; // primal variables - float *pi; // equality constraints multipliers - float *lam; // inequality constraints multipliers - float *t; // inequality constraints slacks - float *t_inv; // inverse of t - float *v_bkp; // backup of primal variables - float *pi_bkp; // backup of equality constraints multipliers - float *lam_bkp; // backup of inequality constraints multipliers - float *t_bkp; // backup of inequality constraints slacks - float *dv; // step in v - float *dpi; // step in pi - float *dlam; // step in lam - float *dt; // step in t - float *res_g; // q-residuals - float *res_b; // b-residuals - float *res_d; // d-residuals - float *res_m; // m-residuals - float *res_m_bkp; // m-residuals - float *Gamma; // Hessian update - float *gamma; // gradient update - float alpha_prim; // step length - float alpha_dual; // step length - float alpha; // step length - float sigma; // centering XXX - float mu; // duality measuere - float mu_aff; // affine duality measuere - float nc_inv; // 1.0/nc, where nc is the total number of constraints - float nc_mask_inv; // 1.0/nc_mask - float lam_min; // min value in lam vector - float t_min; // min value in t vector - float t_min_inv; // inverse of min value in t vector - float tau_min; // min value of barrier parameter - int nv; // number of primal variables - int ne; // number of equality constraints - int nc; // (twice the) number of (two-sided) inequality constraints - int nc_mask; // total number of ineq constr after masking - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam also in solution, or only in Gamma computation - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t s_memsize_core_qp_ipm(int nv, int ne, int nc); -// -void s_create_core_qp_ipm(int nv, int ne, int nc, struct s_core_qp_ipm_workspace *workspace, void *mem); -// -void s_core_qp_ipm(struct s_core_qp_ipm_workspace *workspace); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_S_CORE_QP_IPM_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm_aux.h b/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm_aux.h deleted file mode 100644 index 1ac3d7ede9bba8..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm_aux.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_CORE_QP_IPM_AUX_ -#define HPIPM_S_CORE_QP_IPM_AUX_ - -#ifdef __cplusplus -extern "C" { -#endif - -// -void s_compute_Gamma_gamma_qp(float *res_d, float *res_m, struct s_core_qp_ipm_workspace *rws); -// -void s_compute_gamma_qp(float *res_d, float *res_m, struct s_core_qp_ipm_workspace *rws); -// -void s_compute_lam_t_qp(float *res_d, float *res_m, float *dlam, float *dt, struct s_core_qp_ipm_workspace *rws); -// -void s_compute_alpha_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_update_var_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_compute_mu_aff_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_backup_res_m(struct s_core_qp_ipm_workspace *rws); -// -void s_compute_centering_correction_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_compute_centering_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_compute_tau_min_qp(struct s_core_qp_ipm_workspace *rws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_S_CORE_QP_IPM_AUX_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp.h deleted file mode 100644 index d03c065375f323..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp.h +++ /dev/null @@ -1,200 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QCQP_H_ -#define HPIPM_S_DENSE_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp - { - struct s_dense_qcqp_dim *dim; - struct blasfeo_smat *Hv; // hessian of cost & vector work space - struct blasfeo_smat *A; // equality constraint matrix - struct blasfeo_smat *Ct; // inequality constraints matrix - struct blasfeo_smat *Hq; // hessians of quadratic constraints - struct blasfeo_svec *gz; // gradient of cost & gradient of slacks - struct blasfeo_svec *b; // equality constraint vector - struct blasfeo_svec *d; // inequality constraints vector - struct blasfeo_svec *d_mask; // inequality constraints mask vector - struct blasfeo_svec *m; // rhs of complementarity condition - struct blasfeo_svec *Z; // (diagonal) hessian of slacks - int *idxb; // indices of box constrained variables within [u; x] - int *idxs_rev; // index of soft constraints (reverse storage) - int *Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0 - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_dense_qcqp_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp *qp, void *memory); - -// -void s_dense_qcqp_set(char *field, void *value, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_H(float *H, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_g(float *g, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_A(float *A, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_b(float *b, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_idxb(int *idxb, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_lb(float *lb, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_lb_mask(float *lb, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ub(float *ub, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ub_mask(float *ub, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_C(float *C, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_lg(float *lg, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_lg_mask(float *lg, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ug(float *ug, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ug_mask(float *ug, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_Hq(float *Hq, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_gq(float *gq, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_uq(float *uq, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_uq_mask(float *uq, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_idxs(int *idxs, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_idxs_rev(int *idxs_rev, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_Zl(float *Zl, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_Zu(float *Zu, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_zl(float *zl, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_zu(float *zu, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ls(float *ls, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ls_mask(float *ls, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_us(float *us, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_us_mask(float *us, struct s_dense_qcqp *qp); - -// getters (COLMAJ) - -void s_dense_qcqp_get_H(struct s_dense_qcqp *qp, float *H); -// -void s_dense_qcqp_get_g(struct s_dense_qcqp *qp, float *g); -// -void s_dense_qcqp_get_A(struct s_dense_qcqp *qp, float *A); -// -void s_dense_qcqp_get_b(struct s_dense_qcqp *qp, float *b); -// -void s_dense_qcqp_get_idxb(struct s_dense_qcqp *qp, int *idxb); -// -void s_dense_qcqp_get_lb(struct s_dense_qcqp *qp, float *lb); -// -void s_dense_qcqp_get_lb_mask(struct s_dense_qcqp *qp, float *lb); -// -void s_dense_qcqp_get_ub(struct s_dense_qcqp *qp, float *ub); -// -void s_dense_qcqp_get_ub_mask(struct s_dense_qcqp *qp, float *ub); -// -void s_dense_qcqp_get_C(struct s_dense_qcqp *qp, float *C); -// -void s_dense_qcqp_get_lg(struct s_dense_qcqp *qp, float *lg); -// -void s_dense_qcqp_get_lg_mask(struct s_dense_qcqp *qp, float *lg); -// -void s_dense_qcqp_get_ug(struct s_dense_qcqp *qp, float *ug); -// -void s_dense_qcqp_get_ug_mask(struct s_dense_qcqp *qp, float *ug); -// -void s_dense_qcqp_get_idxs(struct s_dense_qcqp *qp, int *idxs); -// -void s_dense_qcqp_get_idxs_rev(struct s_dense_qcqp *qp, int *idxs_rev); -// -void s_dense_qcqp_get_Zl(struct s_dense_qcqp *qp, float *Zl); -// -void s_dense_qcqp_get_Zu(struct s_dense_qcqp *qp, float *Zu); -// -void s_dense_qcqp_get_zl(struct s_dense_qcqp *qp, float *zl); -// -void s_dense_qcqp_get_zu(struct s_dense_qcqp *qp, float *zu); -// -void s_dense_qcqp_get_ls(struct s_dense_qcqp *qp, float *ls); -// -void s_dense_qcqp_get_ls_mask(struct s_dense_qcqp *qp, float *ls); -// -void s_dense_qcqp_get_us(struct s_dense_qcqp *qp, float *us); -// -void s_dense_qcqp_get_us_mask(struct s_dense_qcqp *qp, float *us); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_dim.h deleted file mode 100644 index 04908c2c3ad97f..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_dim.h +++ /dev/null @@ -1,99 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QCQP_DIM_H_ -#define HPIPM_S_DENSE_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp_dim - { - struct s_dense_qp_dim *qp_dim; // dim of qp approximation - int nv; // number of variables - int ne; // number of equality constraints - int nb; // number of box constraints - int ng; // number of general constraints - int nq; // number of quadratic constraints - int nsb; // number of softened box constraints - int nsg; // number of softened general constraints - int nsq; // number of softened quadratic constraints - int ns; // number of softened constraints (nsb+nsg+nsq) TODO number of slacks - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qcqp_dim_memsize(); -// -void s_dense_qcqp_dim_create(struct s_dense_qcqp_dim *dim, void *memory); -// -void s_dense_qcqp_dim_set(char *fiels_name, int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nv(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_ne(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nb(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_ng(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nq(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nsb(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nsg(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nsq(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_ns(int value, struct s_dense_qcqp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_DIM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_ipm.h deleted file mode 100644 index 8f85768ee3d777..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_ipm.h +++ /dev/null @@ -1,204 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QCQP_IPM_H_ -#define HPIPM_S_DENSE_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp_ipm_arg - { - struct s_dense_qp_ipm_arg *qp_arg; - float mu0; // initial value for duality measure - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float reg_dual; // reg of dual hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int scale; // scale hessian - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_res_exit; // compute residuals on exit (only for abs_form==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_dense_qcqp_ipm_ws - { -// float qp_res[4]; // infinity norm of residuals - struct s_dense_qp_ipm_ws *qp_ws; - struct s_dense_qp *qp; - struct s_dense_qp_sol *qp_sol; - struct s_dense_qcqp_res_ws *qcqp_res_ws; - struct s_dense_qcqp_res *qcqp_res; - struct blasfeo_svec *tmp_nv; -// float *stat; // convergence statistics -// void *lq_work0; -// void *lq_work1; - int iter; // iteration number -// int stat_max; // iterations saved in stat -// int stat_m; // numer of recorded stat per ipm iter -// int scale; -// int use_hess_fact; - int status; - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t s_dense_qcqp_ipm_arg_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_ipm_arg_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp_ipm_arg *arg, void *mem); -// -void s_dense_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set(char *field, void *value, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_iter_max(int *iter_max, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_alpha_min(float *alpha_min, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_mu0(float *mu0, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_tol_stat(float *tol_stat, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_tol_eq(float *tol_eq, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_tol_comp(float *tol_comp, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_reg_prim(float *reg, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_reg_dual(float *reg, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_warm_start(int *warm_start, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_pred_corr(int *pred_corr, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_lam_min(float *value, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_t_min(float *value, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_split_step(int *value, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_t_lam_min(int *value, struct s_dense_qcqp_ipm_arg *arg); - -// -hpipm_size_t s_dense_qcqp_ipm_ws_memsize(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_ws_create(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws, void *mem); -// -void s_dense_qcqp_ipm_get(char *field, struct s_dense_qcqp_ipm_ws *ws, void *value); -// -void s_dense_qcqp_ipm_get_status(struct s_dense_qcqp_ipm_ws *ws, int *status); -// -void s_dense_qcqp_ipm_get_iter(struct s_dense_qcqp_ipm_ws *ws, int *iter); -// -void s_dense_qcqp_ipm_get_max_res_stat(struct s_dense_qcqp_ipm_ws *ws, float *res_stat); -// -void s_dense_qcqp_ipm_get_max_res_eq(struct s_dense_qcqp_ipm_ws *ws, float *res_eq); -// -void s_dense_qcqp_ipm_get_max_res_ineq(struct s_dense_qcqp_ipm_ws *ws, float *res_ineq); -// -void s_dense_qcqp_ipm_get_max_res_comp(struct s_dense_qcqp_ipm_ws *ws, float *res_comp); -// -void s_dense_qcqp_ipm_get_stat(struct s_dense_qcqp_ipm_ws *ws, float **stat); -// -void s_dense_qcqp_ipm_get_stat_m(struct s_dense_qcqp_ipm_ws *ws, int *stat_m); -#if 0 -// -void s_dense_qcqp_init_var(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws); -#endif -// -void s_dense_qcqp_ipm_solve(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws); -#if 0 -// -void s_dense_qcqp_ipm_predict(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws); -// -void s_dense_qcqp_ipm_sens(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws); -#endif - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_IPM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_res.h deleted file mode 100644 index 779658cc8f8b0a..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_res.h +++ /dev/null @@ -1,108 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QCQP_RES_H_ -#define HPIPM_S_DENSE_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp_res - { - struct s_dense_qcqp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // infinity norm of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_dense_qcqp_res_ws - { - struct blasfeo_svec *tmp_nv; // work space of size nv - struct blasfeo_svec *tmp_nbgq; // work space of size nbM+ngM+nqM - struct blasfeo_svec *tmp_ns; // work space of size nsM - struct blasfeo_svec *q_fun; // value for evaluation of quadr constr - struct blasfeo_svec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qcqp_res_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_res_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp_res *res, void *mem); -// -hpipm_size_t s_dense_qcqp_res_ws_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_res_ws_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp_res_ws *workspace, void *mem); -// -void s_dense_qcqp_res_compute(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_res *res, struct s_dense_qcqp_res_ws *ws); -// -void s_dense_qcqp_res_compute_inf_norm(struct s_dense_qcqp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_DENSE_QCQP_RES_H_ - - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_sol.h deleted file mode 100644 index 197a690e520ffa..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_sol.h +++ /dev/null @@ -1,86 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QCQP_SOL_H_ -#define HPIPM_S_DENSE_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp_sol - { - struct s_dense_qcqp_dim *dim; - struct blasfeo_svec *v; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qcqp_sol_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_sol_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp_sol *qp_sol, void *memory); -// -void s_dense_qcqp_sol_get_v(struct s_dense_qcqp_sol *qp_sol, float *v); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_SOL_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_utils.h deleted file mode 100644 index 4f5aae26eb1aba..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_utils.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QCQP_UTILS_H_ -#define HPIPM_S_DENSE_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp_dim.h" -#include "hpipm_s_dense_qcqp.h" -#include "hpipm_s_dense_qcqp_sol.h" -//#include "hpipm_s_dense_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_dense_qcqp_dim_print(struct s_dense_qcqp_dim *qp_dim); -// -//void s_dense_qcqp_dim_codegen(char *file_name, char *mode, struct s_dense_qcqp_dim *qp_dim); -// -void s_dense_qcqp_print(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp *qp); -// -//void s_dense_qcqp_codegen(char *file_name, char *mode, struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_sol_print(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_sol *dense_qcqp_sol); -// -//void s_dense_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_res_print(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_res *dense_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_UTILS_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp.h deleted file mode 100644 index 3c2517fe1b76fc..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp.h +++ /dev/null @@ -1,207 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QP_H_ -#define HPIPM_S_DENSE_QP_H_ - - - -#include -#include - -#include "hpipm_s_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp - { - struct s_dense_qp_dim *dim; - struct blasfeo_smat *Hv; // hessian & gradient - struct blasfeo_smat *A; // dynamics matrix - struct blasfeo_smat *Ct; // constraints matrix - struct blasfeo_svec *gz; // gradient & gradient of slacks - struct blasfeo_svec *b; // dynamics vector - struct blasfeo_svec *d; // constraints vector - struct blasfeo_svec *d_mask; // inequality constraints mask vector - struct blasfeo_svec *m; // rhs of complementarity condition - struct blasfeo_svec *Z; // (diagonal) hessian of slacks - int *idxb; // indices of box constrained variables within [u; x] - int *idxs_rev; // index of soft constraints (reverse storage) - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_dense_qp_memsize(struct s_dense_qp_dim *dim); -// -void s_dense_qp_create(struct s_dense_qp_dim *dim, struct s_dense_qp *qp, void *memory); - -// setters - colmaj -// -void s_dense_qp_set_all(float *H, float *g, float *A, float *b, int *idxb, float *d_lb, float *d_ub, float *C, float *d_lg, float *d_ug, float *Zl, float *Zu, float *zl, float *zu, int *idxs, float *d_ls, float *d_us, struct s_dense_qp *qp); -// -void s_dense_qp_get_all(struct s_dense_qp *qp, float *H, float *g, float *A, float *b, int *idxb, float *d_lb, float *d_ub, float *C, float *d_lg, float *d_ug, float *Zl, float *Zu, float *zl, float *zu, int *idxs, float *d_ls, float *d_us); -// -void s_dense_qp_set(char *field, void *value, struct s_dense_qp *qp); -// -void s_dense_qp_set_H(float *H, struct s_dense_qp *qp); -// -void s_dense_qp_set_g(float *g, struct s_dense_qp *qp); -// -void s_dense_qp_set_A(float *A, struct s_dense_qp *qp); -// -void s_dense_qp_set_b(float *b, struct s_dense_qp *qp); -// -void s_dense_qp_set_idxb(int *idxb, struct s_dense_qp *qp); -// -void s_dense_qp_set_Jb(float *Jb, struct s_dense_qp *qp); -// -void s_dense_qp_set_lb(float *lb, struct s_dense_qp *qp); -// -void s_dense_qp_set_lb_mask(float *lb, struct s_dense_qp *qp); -// -void s_dense_qp_set_ub(float *ub, struct s_dense_qp *qp); -// -void s_dense_qp_set_ub_mask(float *ub, struct s_dense_qp *qp); -// -void s_dense_qp_set_C(float *C, struct s_dense_qp *qp); -// -void s_dense_qp_set_lg(float *lg, struct s_dense_qp *qp); -// -void s_dense_qp_set_lg_mask(float *lg, struct s_dense_qp *qp); -// -void s_dense_qp_set_ug(float *ug, struct s_dense_qp *qp); -// -void s_dense_qp_set_ug_mask(float *ug, struct s_dense_qp *qp); -// -void s_dense_qp_set_idxs(int *idxs, struct s_dense_qp *qp); -// -void s_dense_qp_set_idxs_rev(int *idxs_rev, struct s_dense_qp *qp); -// -void s_dense_qp_set_Jsb(float *Jsb, struct s_dense_qp *qp); -// -void s_dense_qp_set_Jsg(float *Jsg, struct s_dense_qp *qp); -// -void s_dense_qp_set_Zl(float *Zl, struct s_dense_qp *qp); -// -void s_dense_qp_set_Zu(float *Zu, struct s_dense_qp *qp); -// -void s_dense_qp_set_zl(float *zl, struct s_dense_qp *qp); -// -void s_dense_qp_set_zu(float *zu, struct s_dense_qp *qp); -// -void s_dense_qp_set_ls(float *ls, struct s_dense_qp *qp); -// -void s_dense_qp_set_ls_mask(float *ls, struct s_dense_qp *qp); -// -void s_dense_qp_set_us(float *us, struct s_dense_qp *qp); -// -void s_dense_qp_set_us_mask(float *us, struct s_dense_qp *qp); - -// getters - colmaj -// -void s_dense_qp_get_H(struct s_dense_qp *qp, float *H); -// -void s_dense_qp_get_g(struct s_dense_qp *qp, float *g); -// -void s_dense_qp_get_A(struct s_dense_qp *qp, float *A); -// -void s_dense_qp_get_b(struct s_dense_qp *qp, float *b); -// -void s_dense_qp_get_idxb(struct s_dense_qp *qp, int *idxb); -// -void s_dense_qp_get_lb(struct s_dense_qp *qp, float *lb); -// -void s_dense_qp_get_lb_mask(struct s_dense_qp *qp, float *lb); -// -void s_dense_qp_get_ub(struct s_dense_qp *qp, float *ub); -// -void s_dense_qp_get_ub_mask(struct s_dense_qp *qp, float *ub); -// -void s_dense_qp_get_C(struct s_dense_qp *qp, float *C); -// -void s_dense_qp_get_lg(struct s_dense_qp *qp, float *lg); -// -void s_dense_qp_get_lg_mask(struct s_dense_qp *qp, float *lg); -// -void s_dense_qp_get_ug(struct s_dense_qp *qp, float *ug); -// -void s_dense_qp_get_ug_mask(struct s_dense_qp *qp, float *ug); -// -void s_dense_qp_get_idxs(struct s_dense_qp *qp, int *idxs); -// -void s_dense_qp_get_idxs_rev(struct s_dense_qp *qp, int *idxs_rev); -// -void s_dense_qp_get_Zl(struct s_dense_qp *qp, float *Zl); -// -void s_dense_qp_get_Zu(struct s_dense_qp *qp, float *Zu); -// -void s_dense_qp_get_zl(struct s_dense_qp *qp, float *zl); -// -void s_dense_qp_get_zu(struct s_dense_qp *qp, float *zu); -// -void s_dense_qp_get_ls(struct s_dense_qp *qp, float *ls); -// -void s_dense_qp_get_ls_mask(struct s_dense_qp *qp, float *ls); -// -void s_dense_qp_get_us(struct s_dense_qp *qp, float *us); -// -void s_dense_qp_get_us_mask(struct s_dense_qp *qp, float *us); - -// setters - rowmaj -// -void s_dense_qp_set_all_rowmaj(float *H, float *g, float *A, float *b, int *idxb, float *d_lb, float *d_ub, float *C, float *d_lg, float *d_ug, float *Zl, float *Zu, float *zl, float *zu, int *idxs, float *d_ls, float *d_us, struct s_dense_qp *qp); - -// getters - rowmaj -// -void s_dense_qp_get_all_rowmaj(struct s_dense_qp *qp, float *H, float *g, float *A, float *b, int *idxb, float *d_lb, float *d_ub, float *C, float *d_lg, float *d_ug, float *Zl, float *Zu, float *zl, float *zu, int *idxs, float *d_ls, float *d_us); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_dim.h deleted file mode 100644 index b979d24432a9ee..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_dim.h +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QP_DIM_H_ -#define HPIPM_S_DENSE_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp_dim - { - int nv; // number of variables - int ne; // number of equality constraints - int nb; // number of box constraints - int ng; // number of general constraints - int nsb; // number of softened box constraints - int nsg; // number of softened general constraints - int ns; // number of softened constraints (nsb+nsg) - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qp_dim_memsize(); -// -void s_dense_qp_dim_create(struct s_dense_qp_dim *qp_dim, void *memory); -// -void s_dense_qp_dim_set_all(int nv, int ne, int nb, int ng, int nsb, int nsg, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set(char *fiels_name, int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_nv(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_ne(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_nb(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_ng(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_nsb(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_nsg(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_ns(int value, struct s_dense_qp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_DENSE_QP_DIM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_ipm.h deleted file mode 100644 index f2d56d45299574..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_ipm.h +++ /dev/null @@ -1,260 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QP_IPM_H_ -#define HPIPM_S_DENSE_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp_ipm_arg - { - float mu0; // initial value for duality measure - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float reg_dual; // reg of dual hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - float tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int scale; // scale hessian - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_res_exit; // compute residuals on exit (only for abs_form==1) - int comp_res_pred; // compute residuals of prediction - int kkt_fact_alg; // 0 null-space, 1 schur-complement - int remove_lin_dep_eq; // 0 do not, 1 do check and remove linearly dependent equality constraints - int compute_obj; // compute obj on exit - int split_step; // use different steps for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_dense_qp_ipm_ws - { - struct s_core_qp_ipm_workspace *core_workspace; - struct s_dense_qp_res_ws *res_ws; - struct s_dense_qp_sol *sol_step; - struct s_dense_qp_sol *sol_itref; - struct s_dense_qp *qp_step; - struct s_dense_qp *qp_itref; - struct s_dense_qp_res *res; - struct s_dense_qp_res *res_itref; - struct s_dense_qp_res *res_step; - struct blasfeo_svec *Gamma; // - struct blasfeo_svec *gamma; // - struct blasfeo_svec *Zs_inv; // - struct blasfeo_smat *Lv; // - struct blasfeo_smat *AL; // - struct blasfeo_smat *Le; // - struct blasfeo_smat *Ctx; // - struct blasfeo_svec *lv; // - struct blasfeo_svec *sv; // scale for Lv - struct blasfeo_svec *se; // scale for Le - struct blasfeo_svec *tmp_nbg; // work space of size nb+ng - struct blasfeo_svec *tmp_ns; // work space of size ns - struct blasfeo_smat *lq0; - struct blasfeo_smat *lq1; - struct blasfeo_svec *tmp_m; - struct blasfeo_smat *A_LQ; - struct blasfeo_smat *A_Q; - struct blasfeo_smat *Zt; - struct blasfeo_smat *ZtH; - struct blasfeo_smat *ZtHZ; - struct blasfeo_svec *xy; - struct blasfeo_svec *Yxy; - struct blasfeo_svec *xz; - struct blasfeo_svec *tmp_nv; - struct blasfeo_svec *tmp_2ns; - struct blasfeo_svec *tmp_nv2ns; - struct blasfeo_smat *A_li; // A of linearly independent equality constraints - struct blasfeo_svec *b_li; // b of linearly independent equality constraints - struct blasfeo_smat *A_bkp; // pointer to backup A - struct blasfeo_svec *b_bkp; // pointer to backup b - struct blasfeo_smat *Ab_LU; - float *stat; // convergence statistics - int *ipiv_v; - int *ipiv_e; - int *ipiv_e1; - void *lq_work0; - void *lq_work1; - void *lq_work_null; - void *orglq_work_null; - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // numer of recorded stat per ipm iter - int scale; - int use_hess_fact; - int use_A_fact; - int status; - int lq_fact; // cache from arg - int mask_constr; // use constr mask - int ne_li; // number of linearly independent equality constraints - int ne_bkp; // ne backup - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t s_dense_qp_ipm_arg_memsize(struct s_dense_qp_dim *qp_dim); -// -void s_dense_qp_ipm_arg_create(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg, void *mem); -// -void s_dense_qp_ipm_arg_set_default(enum hpipm_mode mode, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set(char *field, void *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_iter_max(int *iter_max, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_alpha_min(float *alpha_min, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_mu0(float *mu0, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tol_stat(float *tol_stat, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tol_eq(float *tol_eq, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tol_comp(float *tol_comp, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_reg_prim(float *reg, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_reg_dual(float *reg, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_warm_start(int *warm_start, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_pred_corr(int *pred_corr, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_lam_min(float *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_t_min(float *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tau_min(float *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_kkt_fact_alg(int *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_remove_lin_dep_eq(int *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_compute_obj(int *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_split_step(int *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_t_lam_min(int *value, struct s_dense_qp_ipm_arg *arg); - -// -hpipm_size_t s_dense_qp_ipm_ws_memsize(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_ws_create(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws, void *mem); -// -void s_dense_qp_ipm_get(char *field, struct s_dense_qp_ipm_ws *ws, void *value); -// -void s_dense_qp_ipm_get_status(struct s_dense_qp_ipm_ws *ws, int *status); -// -void s_dense_qp_ipm_get_iter(struct s_dense_qp_ipm_ws *ws, int *iter); -// -void s_dense_qp_ipm_get_max_res_stat(struct s_dense_qp_ipm_ws *ws, float *res_stat); -// -void s_dense_qp_ipm_get_max_res_eq(struct s_dense_qp_ipm_ws *ws, float *res_eq); -// -void s_dense_qp_ipm_get_max_res_ineq(struct s_dense_qp_ipm_ws *ws, float *res_ineq); -// -void s_dense_qp_ipm_get_max_res_comp(struct s_dense_qp_ipm_ws *ws, float *res_comp); -// -void s_dense_qp_ipm_get_stat(struct s_dense_qp_ipm_ws *ws, float **stat); -// -void s_dense_qp_ipm_get_stat_m(struct s_dense_qp_ipm_ws *ws, int *stat_m); -// -void s_dense_qp_init_var(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_abs_step(int kk, struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_delta_step(int kk, struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_solve(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_predict(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_sens(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_compute_step_length(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_kkt.h deleted file mode 100644 index 260dc0ab21d5ef..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_kkt.h +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QP_KKT_H_ -#define HPIPM_S_DENSE_QP_KKT_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_fact_solve_kkt_unconstr_dense_qp(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_fact_solve_kkt_step_dense_qp(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_fact_lq_solve_kkt_step_dense_qp(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_solve_kkt_step_dense_qp(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_remove_lin_dep_eq(struct s_dense_qp *qp, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_restore_lin_dep_eq(struct s_dense_qp *qp, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_compute_obj(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QP_KKT_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_res.h deleted file mode 100644 index 06b609c537cb1e..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_res.h +++ /dev/null @@ -1,106 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QP_RES_H_ -#define HPIPM_S_DENSE_QP_RES_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp_res - { - struct s_dense_qp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_dense_qp_res_ws - { - struct blasfeo_svec *tmp_nbg; // work space of size nbM+ngM - struct blasfeo_svec *tmp_ns; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qp_res_memsize(struct s_dense_qp_dim *dim); -// -void s_dense_qp_res_create(struct s_dense_qp_dim *dim, struct s_dense_qp_res *res, void *mem); -// -hpipm_size_t s_dense_qp_res_ws_memsize(struct s_dense_qp_dim *dim); -// -void s_dense_qp_res_ws_create(struct s_dense_qp_dim *dim, struct s_dense_qp_res_ws *workspace, void *mem); -// -void s_dense_qp_res_compute(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_res *res, struct s_dense_qp_res_ws *ws); -// -void s_dense_qp_res_compute_lin(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_sol *qp_step, struct s_dense_qp_res *res, struct s_dense_qp_res_ws *ws); -// -void s_dense_qp_res_compute_inf_norm(struct s_dense_qp_res *res); -// -void s_dense_qp_res_get_all(struct s_dense_qp_res *res, float *res_g, float *res_ls, float *res_us, float *res_b, float *res_d_lb, float *res_d_ub, float *res_d_lg, float *res_d_ug, float *res_d_ls, float *res_d_us, float *res_m_lb, float *res_m_ub, float *res_m_lg, float *res_m_ug, float *res_m_ls, float *res_m_us); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_DENSE_QP_RES_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_sol.h deleted file mode 100644 index 1f40076378d833..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_sol.h +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QP_SOL_H_ -#define HPIPM_S_DENSE_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp_sol - { - struct s_dense_qp_dim *dim; - struct blasfeo_svec *v; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - float obj; - int valid_obj; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qp_sol_memsize(struct s_dense_qp_dim *dim); -// -void s_dense_qp_sol_create(struct s_dense_qp_dim *dim, struct s_dense_qp_sol *qp_sol, void *memory); -// -void s_dense_qp_sol_get_all(struct s_dense_qp_sol *qp_sol, float *v, float *ls, float *us, float *pi, float *lam_lb, float *lam_ub, float *lam_lg, float *lam_ug, float *lam_ls, float *lam_us); -// -void s_dense_qp_sol_get(char *field, struct s_dense_qp_sol *sol, void *value); -// -void s_dense_qp_sol_get_v(struct s_dense_qp_sol *sol, float *v); -// -void s_dense_qp_sol_get_valid_obj(struct s_dense_qp_sol *sol, int *valid_obj); -// -void s_dense_qp_sol_get_obj(struct s_dense_qp_sol *sol, float *obj); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_utils.h deleted file mode 100644 index 3dd93259a55a58..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_utils.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QP_UTILS_H_ -#define HPIPM_S_DENSE_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_dense_qp_dim.h" -#include "hpipm_s_dense_qp.h" -#include "hpipm_s_dense_qp_sol.h" -#include "hpipm_s_dense_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_dense_qp_dim_print(struct s_dense_qp_dim *qp_dim); -// -//void s_dense_qp_dim_codegen(char *file_name, char *mode, struct s_dense_qp_dim *qp_dim); -// -void s_dense_qp_print(struct s_dense_qp_dim *qp_dim, struct s_dense_qp *qp); -// -//void s_dense_qp_codegen(char *file_name, char *mode, struct s_dense_qp_dim *qp_dim, struct s_dense_qp *qp); -// -void s_dense_qp_sol_print(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_sol *dense_qp_sol); -// -//void s_dense_qp_ipm_arg_codegen(char *file_name, char *mode, struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_res_print(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_res *dense_qp_res); -// -void s_dense_qp_arg_print(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *qp_ipm_arg); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_DENSE_QP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp.h deleted file mode 100644 index b90b2ac6337580..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp.h +++ /dev/null @@ -1,303 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_H_ -#define HPIPM_S_OCP_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp - { - struct s_ocp_qcqp_dim *dim; - struct blasfeo_smat *BAbt; // dynamics matrix & vector work space - struct blasfeo_smat *RSQrq; // hessian of cost & vector work space - struct blasfeo_smat *DCt; // inequality constraints matrix - struct blasfeo_smat **Hq; // hessians of quadratic constraints - struct blasfeo_svec *b; // dynamics vector - struct blasfeo_svec *rqz; // gradient of cost & gradient of slacks - struct blasfeo_svec *d; // inequality constraints vector - struct blasfeo_svec *d_mask; // inequality constraints mask vector - struct blasfeo_svec *m; // rhs of complementarity condition - struct blasfeo_svec *Z; // (diagonal) hessian of slacks - int **idxb; // indices of box constrained variables within [u; x] - int **idxs_rev; // index of soft constraints (reverse storage) - int **Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0 - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_ocp_qcqp_strsize(); -// -hpipm_size_t s_ocp_qcqp_memsize(struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_create(struct s_ocp_qcqp_dim *dim, struct s_ocp_qcqp *qp, void *memory); -// -void s_ocp_qcqp_copy_all(struct s_ocp_qcqp *qp_orig, struct s_ocp_qcqp *qp_dest); - -// setters -// -void s_ocp_qcqp_set_all_zero(struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_rhs_zero(struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set(char *fiels_name, int stage, void *value, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_el(char *fiels_name, int stage, int index, void *value, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_A(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_B(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_b(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Q(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_S(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_R(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_q(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_r(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lb(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lb_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ub(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ub_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lbx(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lbx_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_el_lbx(int stage, int index, float *elem, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ubx(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ubx_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_el_ubx(int stage, int index, float *elem, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lbu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lbu_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ubu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ubu_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxb(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxbx(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jbx(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxbu(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jbu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_C(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_D(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lg(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lg_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ug(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ug_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Qq(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Sq(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Rq(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_qq(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_rq(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_uq(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_uq_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Zl(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Zu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_zl(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_zu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lls(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lls_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lus(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lus_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxs(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxs_rev(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jsbu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jsbx(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jsg(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jsq(int stage, float *vec, struct s_ocp_qcqp *qp); - -// getters -// -void s_ocp_qcqp_get(char *field, int stage, struct s_ocp_qcqp *qp, void *value); -// -void s_ocp_qcqp_get_A(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_B(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_b(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_Q(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_S(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_R(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_q(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_r(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ub(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ub_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lb(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lb_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lbx(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lbx_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ubx(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ubx_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lbu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lbu_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ubu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ubu_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_idxb(int stage, struct s_ocp_qcqp *qp, int *vec); -// -//void s_ocp_qcqp_get_idxbx(int stage, struct s_ocp_qcqp *qp, int *vec); -// -//void s_ocp_qcqp_get_Jbx(int stage, struct s_ocp_qcqp *qp, float *vec); -// -//void s_ocp_qcqp_get_idxbu(int stage, struct s_ocp_qcqp *qp, int *vec); -// -//void s_ocp_qcqp_get_Jbu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_C(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_D(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_lg(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lg_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ug(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ug_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_Zl(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_Zu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_zl(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_zu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lls(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lls_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lus(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lus_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// XXX only valid if there is one slack per softed constraint !!! -void s_ocp_qcqp_get_idxs(int stage, struct s_ocp_qcqp *qp, int *vec); -// -void s_ocp_qcqp_get_idxs_rev(int stage, struct s_ocp_qcqp *qp, int *vec); -// -//void s_ocp_qcqp_get_Jsbu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -//void s_ocp_qcqp_get_Jsbx(int stage, struct s_ocp_qcqp *qp, float *vec); -// -//void s_ocp_qcqp_get_Jsg(int stage, struct s_ocp_qcqp *qp, float *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_OCP_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_dim.h deleted file mode 100644 index c09903f07448ea..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_dim.h +++ /dev/null @@ -1,119 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_DIM_H_ -#define HPIPM_S_OCP_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp_dim - { - struct s_ocp_qp_dim *qp_dim; // dim of qp approximation - int *nx; // number of states - int *nu; // number of inputs - int *nb; // number of box constraints - int *nbx; // number of (two-sided) state box constraints - int *nbu; // number of (two-sided) input box constraints - int *ng; // number of (two-sided) general constraints - int *nq; // number of (upper) quadratic constraints - int *ns; // number of soft constraints - int *nsbx; // number of (two-sided) soft state box constraints - int *nsbu; // number of (two-sided) soft input box constraints - int *nsg; // number of (two-sided) soft general constraints - int *nsq; // number of (upper) soft quadratic constraints - int N; // horizon length - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qcqp_dim_strsize(); -// -hpipm_size_t s_ocp_qcqp_dim_memsize(int N); -// -void s_ocp_qcqp_dim_create(int N, struct s_ocp_qcqp_dim *qp_dim, void *memory); -// -void s_ocp_qcqp_dim_copy_all(struct s_ocp_qcqp_dim *dim_orig, struct s_ocp_qcqp_dim *dim_dest); -// -void s_ocp_qcqp_dim_set(char *field, int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nx(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nu(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nbx(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nbu(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_ng(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nq(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_ns(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nsbx(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nsbu(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nsg(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nsq(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_get(struct s_ocp_qcqp_dim *dim, char *field, int stage, int *value); -// -void s_ocp_qcqp_dim_get_N(struct s_ocp_qcqp_dim *dim, int *value); -// -void s_ocp_qcqp_dim_get_nx(struct s_ocp_qcqp_dim *dim, int stage, int *value); -// -void s_ocp_qcqp_dim_get_nu(struct s_ocp_qcqp_dim *dim, int stage, int *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QCQP_DIM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_ipm.h deleted file mode 100644 index c14fc1c9fd27a9..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_ipm.h +++ /dev/null @@ -1,191 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_IPM_H_ -#define HPIPM_S_OCP_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp_ipm_arg - { - struct s_ocp_qp_ipm_arg *qp_arg; - float mu0; // initial value for complementarity slackness - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_ocp_qcqp_ipm_ws - { - struct s_ocp_qp_ipm_ws *qp_ws; - struct s_ocp_qp *qp; - struct s_ocp_qp_sol *qp_sol; - struct s_ocp_qcqp_res_ws *qcqp_res_ws; - struct s_ocp_qcqp_res *qcqp_res; - struct blasfeo_svec *tmp_nuxM; - int iter; // iteration number - int status; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qcqp_ipm_arg_strsize(); -// -hpipm_size_t s_ocp_qcqp_ipm_arg_memsize(struct s_ocp_qcqp_dim *ocp_dim); -// -void s_ocp_qcqp_ipm_arg_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_ipm_arg *arg, void *mem); -// -void s_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct s_ocp_qcqp_ipm_arg *arg); -// -void s_ocp_qcqp_ipm_arg_set(char *field, void *value, struct s_ocp_qcqp_ipm_arg *arg); -// set maximum number of iterations -void s_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// set minimum step lenght -void s_ocp_qcqp_ipm_arg_set_alpha_min(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set initial value of barrier parameter -void s_ocp_qcqp_ipm_arg_set_mu0(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void s_ocp_qcqp_ipm_arg_set_tol_stat(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on equality constr -void s_ocp_qcqp_ipm_arg_set_tol_eq(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on inequality constr -void s_ocp_qcqp_ipm_arg_set_tol_ineq(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void s_ocp_qcqp_ipm_arg_set_tol_comp(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set regularization of primal variables -void s_ocp_qcqp_ipm_arg_set_reg_prim(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void s_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void s_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void s_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -void s_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// compute residuals after solution -void s_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// compute residuals of prediction -void s_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// min value of lam in the solution -void s_ocp_qcqp_ipm_arg_set_lam_min(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// min value of t in the solution -void s_ocp_qcqp_ipm_arg_set_t_min(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// use different step for primal and dual variables -void s_ocp_qcqp_ipm_arg_set_split_step(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void s_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct s_ocp_qcqp_ipm_arg *arg); - -// -hpipm_size_t s_ocp_qcqp_ipm_ws_strsize(); -// -hpipm_size_t s_ocp_qcqp_ipm_ws_memsize(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_ipm_arg *arg); -// -void s_ocp_qcqp_ipm_ws_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_ipm_arg *arg, struct s_ocp_qcqp_ipm_ws *ws, void *mem); -// -void s_ocp_qcqp_ipm_get(char *field, struct s_ocp_qcqp_ipm_ws *ws, void *value); -// -void s_ocp_qcqp_ipm_get_status(struct s_ocp_qcqp_ipm_ws *ws, int *status); -// -void s_ocp_qcqp_ipm_get_iter(struct s_ocp_qcqp_ipm_ws *ws, int *iter); -// -void s_ocp_qcqp_ipm_get_max_res_stat(struct s_ocp_qcqp_ipm_ws *ws, float *res_stat); -// -void s_ocp_qcqp_ipm_get_max_res_eq(struct s_ocp_qcqp_ipm_ws *ws, float *res_eq); -// -void s_ocp_qcqp_ipm_get_max_res_ineq(struct s_ocp_qcqp_ipm_ws *ws, float *res_ineq); -// -void s_ocp_qcqp_ipm_get_max_res_comp(struct s_ocp_qcqp_ipm_ws *ws, float *res_comp); -// -void s_ocp_qcqp_ipm_get_stat(struct s_ocp_qcqp_ipm_ws *ws, float **stat); -// -void s_ocp_qcqp_ipm_get_stat_m(struct s_ocp_qcqp_ipm_ws *ws, int *stat_m); -// -void s_ocp_qcqp_init_var(struct s_ocp_qcqp *qp, struct s_ocp_qcqp_sol *qp_sol, struct s_ocp_qcqp_ipm_arg *arg, struct s_ocp_qcqp_ipm_ws *ws); -// -void s_ocp_qcqp_ipm_solve(struct s_ocp_qcqp *qp, struct s_ocp_qcqp_sol *qp_sol, struct s_ocp_qcqp_ipm_arg *arg, struct s_ocp_qcqp_ipm_ws *ws); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_OCP_QCQP_IPM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_res.h deleted file mode 100644 index 1ceeec93b7ec5c..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_res.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_RES_H_ -#define HPIPM_S_OCP_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp_res - { - struct s_ocp_qcqp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_ocp_qcqp_res_ws - { - struct blasfeo_svec *tmp_nuxM; // work space of size nuM+nxM - struct blasfeo_svec *tmp_nbgqM; // work space of size nbM+ngM+nqM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - struct blasfeo_svec *q_fun; // value for evaluation of quadr constr - struct blasfeo_svec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qcqp_res_memsize(struct s_ocp_qcqp_dim *ocp_dim); -// -void s_ocp_qcqp_res_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_res *res, void *mem); -// -hpipm_size_t s_ocp_qcqp_res_ws_memsize(struct s_ocp_qcqp_dim *ocp_dim); -// -void s_ocp_qcqp_res_ws_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_res_ws *workspace, void *mem); -// -void s_ocp_qcqp_res_compute(struct s_ocp_qcqp *qp, struct s_ocp_qcqp_sol *qp_sol, struct s_ocp_qcqp_res *res, struct s_ocp_qcqp_res_ws *ws); -// -void s_ocp_qcqp_res_compute_inf_norm(struct s_ocp_qcqp_res *res); -// -void s_ocp_qcqp_res_get_max_res_stat(struct s_ocp_qcqp_res *res, float *value); -// -void s_ocp_qcqp_res_get_max_res_eq(struct s_ocp_qcqp_res *res, float *value); -// -void s_ocp_qcqp_res_get_max_res_ineq(struct s_ocp_qcqp_res *res, float *value); -// -void s_ocp_qcqp_res_get_max_res_comp(struct s_ocp_qcqp_res *res, float *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_OCP_QCQP_RES_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_sol.h deleted file mode 100644 index 3d58022cc9c8ff..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_sol.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_SOL_H_ -#define HPIPM_S_OCP_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp_sol - { - struct s_ocp_qcqp_dim *dim; - struct blasfeo_svec *ux; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_ocp_qcqp_sol_strsize(); -// -hpipm_size_t s_ocp_qcqp_sol_memsize(struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_sol_create(struct s_ocp_qcqp_dim *dim, struct s_ocp_qcqp_sol *qp_sol, void *memory); -// -void s_ocp_qcqp_sol_copy_all(struct s_ocp_qcqp_sol *qp_sol_orig, struct s_ocp_qcqp_sol *qp_sol_dest); -// -void s_ocp_qcqp_sol_get(char *field, int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_u(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_x(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_sl(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_su(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_pi(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_lam_lb(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_lam_ub(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_lam_lg(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_lam_ug(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_set(char *field, int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); -// -void s_ocp_qcqp_sol_set_u(int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); -// -void s_ocp_qcqp_sol_set_x(int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); -// -void s_ocp_qcqp_sol_set_sl(int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); -// -void s_ocp_qcqp_sol_set_su(int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QCQP_SOL_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_utils.h deleted file mode 100644 index d64e3aabe73742..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_utils.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_UTILS_H_ -#define HPIPM_S_OCP_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qcqp_dim.h" -#include "hpipm_s_ocp_qp.h" -#include "hpipm_s_ocp_qcqp_sol.h" -#include "hpipm_s_ocp_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_ocp_qcqp_dim_print(struct s_ocp_qcqp_dim *qcqp_dim); -// -void s_ocp_qcqp_dim_codegen(char *file_name, char *mode, struct s_ocp_qcqp_dim *qcqp_dim); -// -void s_ocp_qcqp_print(struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_codegen(char *file_name, char *mode, struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_sol_print(struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp_sol *ocp_qcqp_sol); -// -void s_ocp_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp_ipm_arg *arg); -// -void s_ocp_qcqp_res_print(struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp_res *ocp_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QCQP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp.h deleted file mode 100644 index b49191f192d83c..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp.h +++ /dev/null @@ -1,306 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_H_ -#define HPIPM_S_OCP_QP_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp - { - struct s_ocp_qp_dim *dim; - struct blasfeo_smat *BAbt; // dynamics matrix & vector work space - struct blasfeo_smat *RSQrq; // hessian of cost & vector work space - struct blasfeo_smat *DCt; // inequality constraints matrix - struct blasfeo_svec *b; // dynamics vector - struct blasfeo_svec *rqz; // gradient of cost & gradient of slacks - struct blasfeo_svec *d; // inequality constraints vector - struct blasfeo_svec *d_mask; // inequality constraints mask vector - struct blasfeo_svec *m; // rhs of complementarity condition - struct blasfeo_svec *Z; // (diagonal) hessian of slacks - int **idxb; // indices of box constrained variables within [u; x] - int **idxs_rev; // index of soft constraints (reverse storage) - int **idxe; // indices of constraints within [bu, bx, g] that are equalities, subset of [0, ..., nbu+nbx+ng-1] - int *diag_H_flag; // flag the fact that Hessian is diagonal - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_ocp_qp_strsize(); -// -hpipm_size_t s_ocp_qp_memsize(struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_create(struct s_ocp_qp_dim *dim, struct s_ocp_qp *qp, void *memory); -// -void s_ocp_qp_copy_all(struct s_ocp_qp *qp_orig, struct s_ocp_qp *qp_dest); - -// setters -// -void s_ocp_qp_set_all_zero(struct s_ocp_qp *qp); -// -void s_ocp_qp_set_rhs_zero(struct s_ocp_qp *qp); -// -void s_ocp_qp_set_all(float **A, float **B, float **b, float **Q, float **S, float **R, float **q, float **r, int **idxbx, float **lbx, float **ubx, int **idxbu, float **lbu, float **ubu, float **C, float **D, float **lg, float **ug, float **Zl, float **Zu, float **zl, float **zu, int **idxs, float **ls, float **us, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_all_rowmaj(float **A, float **B, float **b, float **Q, float **S, float **R, float **q, float **r, int **idxbx, float **lbx, float **ubx, int **idxbu, float **lbu, float **ubu, float **C, float **D, float **lg, float **ug, float **Zl, float **Zu, float **zl, float **zu, int **idxs, float **ls, float **us, struct s_ocp_qp *qp); -// -void s_ocp_qp_set(char *fiels_name, int stage, void *value, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_el(char *fiels_name, int stage, int index, void *value, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_A(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_B(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_b(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Q(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_S(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_R(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_q(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_r(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lb(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lb_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ub(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ub_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lbx(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lbx_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_el_lbx(int stage, int index, float *elem, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ubx(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ubx_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_el_ubx(int stage, int index, float *elem, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lbu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lbu_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ubu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ubu_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxb(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxbx(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jbx(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxbu(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jbu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_C(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_D(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lg(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lg_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ug(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ug_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Zl(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Zu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_zl(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_zu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lls(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lls_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lus(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lus_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxs(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxs_rev(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jsbu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jsbx(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jsg(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxe(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxbxe(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxbue(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxge(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jbxe(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jbue(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jge(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_diag_H_flag(int stage, int *value, struct s_ocp_qp *qp); - -// getters -// -void s_ocp_qp_get(char *field, int stage, struct s_ocp_qp *qp, void *value); -// -void s_ocp_qp_get_A(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_B(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_b(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_Q(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_S(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_R(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_q(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_r(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ub(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ub_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lb(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lb_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lbx(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lbx_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ubx(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ubx_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lbu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lbu_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ubu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ubu_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_idxb(int stage, struct s_ocp_qp *qp, int *vec); -// -//void s_ocp_qp_get_idxbx(int stage, struct s_ocp_qp *qp, int *vec); -// -//void s_ocp_qp_get_Jbx(int stage, struct s_ocp_qp *qp, float *vec); -// -//void s_ocp_qp_get_idxbu(int stage, struct s_ocp_qp *qp, int *vec); -// -//void s_ocp_qp_get_Jbu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_C(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_D(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_lg(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lg_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ug(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ug_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_Zl(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_Zu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_zl(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_zu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lls(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lls_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lus(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lus_mask(int stage, struct s_ocp_qp *qp, float *vec); -// XXX only valid if there is one slack per softed constraint !!! -void s_ocp_qp_get_idxs(int stage, struct s_ocp_qp *qp, int *vec); -// -void s_ocp_qp_get_idxs_rev(int stage, struct s_ocp_qp *qp, int *vec); -// -//void s_ocp_qp_get_Jsbu(int stage, struct s_ocp_qp *qp, float *vec); -// -//void s_ocp_qp_get_Jsbx(int stage, struct s_ocp_qp *qp, float *vec); -// -//void s_ocp_qp_get_Jsg(int stage, struct s_ocp_qp *qp, float *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_OCP_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_dim.h deleted file mode 100644 index bce80243b3eb2e..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_dim.h +++ /dev/null @@ -1,141 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_DIM_H_ -#define HPIPM_S_OCP_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_dim - { - int *nx; // number of states - int *nu; // number of inputs - int *nb; // number of box constraints - int *nbx; // number of state box constraints - int *nbu; // number of input box constraints - int *ng; // number of general constraints - int *ns; // number of soft constraints - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int *nbxe; // number of state box constraints which are equality - int *nbue; // number of input box constraints which are equality - int *nge; // number of general constraints which are equality - int N; // horizon length - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qp_dim_strsize(); -// -hpipm_size_t s_ocp_qp_dim_memsize(int N); -// -void s_ocp_qp_dim_create(int N, struct s_ocp_qp_dim *qp_dim, void *memory); -// -void s_ocp_qp_dim_copy_all(struct s_ocp_qp_dim *dim_orig, struct s_ocp_qp_dim *dim_dest); -// -void s_ocp_qp_dim_set_all(int *nx, int *nu, int *nbx, int *nbu, int *ng, int *nsbx, int *nsbu, int *nsg, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set(char *field, int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nx(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nu(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nbx(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nbu(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_ng(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_ns(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nsbx(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nsbu(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nsg(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nbxe(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nbue(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nge(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_get(struct s_ocp_qp_dim *dim, char *field, int stage, int *value); -// -void s_ocp_qp_dim_get_N(struct s_ocp_qp_dim *dim, int *value); -// -void s_ocp_qp_dim_get_nx(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nu(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nbx(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nbu(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_ng(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_ns(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nsbx(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nsbu(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nsg(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nbxe(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nbue(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nge(struct s_ocp_qp_dim *dim, int stage, int *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_ipm.h deleted file mode 100644 index 11f3c47be6ecd2..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_ipm.h +++ /dev/null @@ -1,250 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_IPM_H_ -#define HPIPM_S_OCP_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_ipm_arg - { - float mu0; // initial value for complementarity slackness - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - float tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different steps for primal and dual variables - int var_init_scheme; // variables initialization scheme - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_ocp_qp_ipm_ws - { - struct s_core_qp_ipm_workspace *core_workspace; - struct s_ocp_qp_res_ws *res_workspace; - struct s_ocp_qp_dim *dim; // cache dim - struct s_ocp_qp_sol *sol_step; - struct s_ocp_qp_sol *sol_itref; - struct s_ocp_qp *qp_step; - struct s_ocp_qp *qp_itref; - struct s_ocp_qp_res *res; - struct s_ocp_qp_res *res_itref; - struct blasfeo_svec *Gamma; // hessian update - struct blasfeo_svec *gamma; // hessian update - struct blasfeo_svec *tmp_nuxM; // work space of size nxM - struct blasfeo_svec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - struct blasfeo_svec *Pb; // Pb - struct blasfeo_svec *Zs_inv; - struct blasfeo_svec *tmp_m; - struct blasfeo_svec *l; // cache linear part for _get_ric_xxx - struct blasfeo_smat *L; - struct blasfeo_smat *Ls; - struct blasfeo_smat *P; - struct blasfeo_smat *Lh; - struct blasfeo_smat *AL; - struct blasfeo_smat *lq0; - struct blasfeo_smat *tmp_nxM_nxM; - float *stat; // convergence statistics - int *use_hess_fact; - void *lq_work0; - float qp_res[4]; // infinity norm of residuals - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int use_Pb; - int status; // solver status - int square_root_alg; // cache from arg - int lq_fact; // cache from arg - int mask_constr; // use constr mask - int valid_ric_vec; // meaningful riccati vectors - int valid_ric_p; // form of riccati p: 0 p*inv(L), 1 p - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qp_ipm_arg_strsize(); -// -hpipm_size_t s_ocp_qp_ipm_arg_memsize(struct s_ocp_qp_dim *ocp_dim); -// -void s_ocp_qp_ipm_arg_create(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_ipm_arg *arg, void *mem); -// -void s_ocp_qp_ipm_arg_set_default(enum hpipm_mode mode, struct s_ocp_qp_ipm_arg *arg); -// -void s_ocp_qp_ipm_arg_set(char *field, void *value, struct s_ocp_qp_ipm_arg *arg); -// set maximum number of iterations -void s_ocp_qp_ipm_arg_set_iter_max(int *iter_max, struct s_ocp_qp_ipm_arg *arg); -// set minimum step lenght -void s_ocp_qp_ipm_arg_set_alpha_min(float *alpha_min, struct s_ocp_qp_ipm_arg *arg); -// set initial value of barrier parameter -void s_ocp_qp_ipm_arg_set_mu0(float *mu0, struct s_ocp_qp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void s_ocp_qp_ipm_arg_set_tol_stat(float *tol_stat, struct s_ocp_qp_ipm_arg *arg); -// set exit tolerance on equality constr -void s_ocp_qp_ipm_arg_set_tol_eq(float *tol_eq, struct s_ocp_qp_ipm_arg *arg); -// set exit tolerance on inequality constr -void s_ocp_qp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_ocp_qp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void s_ocp_qp_ipm_arg_set_tol_comp(float *tol_comp, struct s_ocp_qp_ipm_arg *arg); -// set regularization of primal variables -void s_ocp_qp_ipm_arg_set_reg_prim(float *tol_comp, struct s_ocp_qp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void s_ocp_qp_ipm_arg_set_warm_start(int *warm_start, struct s_ocp_qp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void s_ocp_qp_ipm_arg_set_pred_corr(int *pred_corr, struct s_ocp_qp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void s_ocp_qp_ipm_arg_set_cond_pred_corr(int *value, struct s_ocp_qp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -void s_ocp_qp_ipm_arg_set_ric_alg(int *alg, struct s_ocp_qp_ipm_arg *arg); -// dual solution of equality constraints (only for abs_form==1) -void s_ocp_qp_ipm_arg_set_comp_dual_sol_eq(int *value, struct s_ocp_qp_ipm_arg *arg); -// compute residuals after solution -void s_ocp_qp_ipm_arg_set_comp_res_exit(int *value, struct s_ocp_qp_ipm_arg *arg); -// compute residuals of prediction -void s_ocp_qp_ipm_arg_set_comp_res_pred(int *alg, struct s_ocp_qp_ipm_arg *arg); -// min value of lam in the solution -void s_ocp_qp_ipm_arg_set_lam_min(float *value, struct s_ocp_qp_ipm_arg *arg); -// min value of t in the solution -void s_ocp_qp_ipm_arg_set_t_min(float *value, struct s_ocp_qp_ipm_arg *arg); -// min value of tau in the solution -void s_ocp_qp_ipm_arg_set_tau_min(float *value, struct s_ocp_qp_ipm_arg *arg); -// set split step: 0 same step, 1 different step for primal and dual variables -void s_ocp_qp_ipm_arg_set_split_step(int *value, struct s_ocp_qp_ipm_arg *arg); -// variables initialization scheme -void s_ocp_qp_ipm_arg_set_var_init_scheme(int *value, struct s_ocp_qp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void s_ocp_qp_ipm_arg_set_t_lam_min(int *value, struct s_ocp_qp_ipm_arg *arg); - -// -hpipm_size_t s_ocp_qp_ipm_ws_strsize(); -// -hpipm_size_t s_ocp_qp_ipm_ws_memsize(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_ipm_arg *arg); -// -void s_ocp_qp_ipm_ws_create(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, void *mem); -// -void s_ocp_qp_ipm_get(char *field, struct s_ocp_qp_ipm_ws *ws, void *value); -// -void s_ocp_qp_ipm_get_status(struct s_ocp_qp_ipm_ws *ws, int *status); -// -void s_ocp_qp_ipm_get_iter(struct s_ocp_qp_ipm_ws *ws, int *iter); -// -void s_ocp_qp_ipm_get_max_res_stat(struct s_ocp_qp_ipm_ws *ws, float *res_stat); -// -void s_ocp_qp_ipm_get_max_res_eq(struct s_ocp_qp_ipm_ws *ws, float *res_eq); -// -void s_ocp_qp_ipm_get_max_res_ineq(struct s_ocp_qp_ipm_ws *ws, float *res_ineq); -// -void s_ocp_qp_ipm_get_max_res_comp(struct s_ocp_qp_ipm_ws *ws, float *res_comp); -// -void s_ocp_qp_ipm_get_stat(struct s_ocp_qp_ipm_ws *ws, float **stat); -// -void s_ocp_qp_ipm_get_stat_m(struct s_ocp_qp_ipm_ws *ws, int *stat_m); -// -void s_ocp_qp_ipm_get_ric_Lr(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *Lr); -// -void s_ocp_qp_ipm_get_ric_Ls(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *Ls); -// -void s_ocp_qp_ipm_get_ric_P(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *P); -// -void s_ocp_qp_ipm_get_ric_lr(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *lr); -// -void s_ocp_qp_ipm_get_ric_p(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *p); -// feedback control gain in the form u = K x + k -void s_ocp_qp_ipm_get_ric_K(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *K); -// feedback control gain in the form u = K x + k -void s_ocp_qp_ipm_get_ric_k(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *k); -// -void s_ocp_qp_init_var(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_abs_step(int kk, struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_delta_step(int kk, struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_solve(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_predict(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_sens(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_OCP_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_kkt.h deleted file mode 100644 index 3eb1f4aae878d0..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_kkt.h +++ /dev/null @@ -1,66 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -#ifndef HPIPM_S_OCP_QP_KKT_H_ -#define HPIPM_S_OCP_QP_KKT_H_ - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - -// -void s_ocp_qp_fact_solve_kkt_unconstr(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_fact_solve_kkt_step(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_fact_lq_solve_kkt_step(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_solve_kkt_step(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - -#endif // HPIPM_S_OCP_QP_KKT_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_red.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_red.h deleted file mode 100644 index 5a7b3b070302b0..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_red.h +++ /dev/null @@ -1,118 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_RED_H_ -#define HPIPM_S_OCP_QP_RED_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_reduce_eq_dof_arg - { - float lam_min; - float t_min; - int alias_unchanged; // do not keep copy unchanged stage - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution inequality constr (lam t) - hpipm_size_t memsize; // memory size in bytes - }; - - - -struct s_ocp_qp_reduce_eq_dof_ws - { - struct blasfeo_svec *tmp_nuxM; - struct blasfeo_svec *tmp_nbgM; - int *e_imask_ux; - int *e_imask_d; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -void s_ocp_qp_dim_reduce_eq_dof(struct s_ocp_qp_dim *dim, struct s_ocp_qp_dim *dim_red); -// -hpipm_size_t s_ocp_qp_reduce_eq_dof_arg_memsize(); -// -void s_ocp_qp_reduce_eq_dof_arg_create(struct s_ocp_qp_reduce_eq_dof_arg *arg, void *mem); -// -void s_ocp_qp_reduce_eq_dof_arg_set_default(struct s_ocp_qp_reduce_eq_dof_arg *arg); -// -void s_ocp_qp_reduce_eq_dof_arg_set_alias_unchanged(struct s_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void s_ocp_qp_reduce_eq_dof_arg_set_comp_prim_sol(struct s_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void s_ocp_qp_reduce_eq_dof_arg_set_comp_dual_sol_eq(struct s_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void s_ocp_qp_reduce_eq_dof_arg_set_comp_dual_sol_ineq(struct s_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -hpipm_size_t s_ocp_qp_reduce_eq_dof_ws_memsize(struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_reduce_eq_dof_ws_create(struct s_ocp_qp_dim *dim, struct s_ocp_qp_reduce_eq_dof_ws *work, void *mem); -// -void s_ocp_qp_reduce_eq_dof(struct s_ocp_qp *qp, struct s_ocp_qp *qp_red, struct s_ocp_qp_reduce_eq_dof_arg *arg, struct s_ocp_qp_reduce_eq_dof_ws *work); -// -void s_ocp_qp_reduce_eq_dof_lhs(struct s_ocp_qp *qp, struct s_ocp_qp *qp_red, struct s_ocp_qp_reduce_eq_dof_arg *arg, struct s_ocp_qp_reduce_eq_dof_ws *work); -// -void s_ocp_qp_reduce_eq_dof_rhs(struct s_ocp_qp *qp, struct s_ocp_qp *qp_red, struct s_ocp_qp_reduce_eq_dof_arg *arg, struct s_ocp_qp_reduce_eq_dof_ws *work); -// -void s_ocp_qp_restore_eq_dof(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol_red, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_reduce_eq_dof_arg *arg, struct s_ocp_qp_reduce_eq_dof_ws *work); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QP_RED_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_res.h deleted file mode 100644 index 821585da6583dd..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_res.h +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_RES_H_ -#define HPIPM_S_OCP_QP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_res - { - struct s_ocp_qp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_ocp_qp_res_ws - { - struct blasfeo_svec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qp_res_memsize(struct s_ocp_qp_dim *ocp_dim); -// -void s_ocp_qp_res_create(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_res *res, void *mem); -// -hpipm_size_t s_ocp_qp_res_ws_memsize(struct s_ocp_qp_dim *ocp_dim); -// -void s_ocp_qp_res_ws_create(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_res_ws *workspace, void *mem); -// -void s_ocp_qp_res_compute(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_res *res, struct s_ocp_qp_res_ws *ws); -// -void s_ocp_qp_res_compute_lin(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_sol *qp_step, struct s_ocp_qp_res *res, struct s_ocp_qp_res_ws *ws); -// -void s_ocp_qp_res_compute_inf_norm(struct s_ocp_qp_res *res); -// -void s_ocp_qp_res_get_all(struct s_ocp_qp_res *res, float **res_r, float **res_q, float **res_ls, float **res_us, float **res_b, float **res_d_lb, float **res_d_ub, float **res_d_lg, float **res_d_ug, float **res_d_ls, float **res_d_us, float **res_m_lb, float **res_m_ub, float **res_m_lg, float **res_m_ug, float **res_m_ls, float **res_m_us); -// -void s_ocp_qp_res_get_max_res_stat(struct s_ocp_qp_res *res, float *value); -// -void s_ocp_qp_res_get_max_res_eq(struct s_ocp_qp_res *res, float *value); -// -void s_ocp_qp_res_get_max_res_ineq(struct s_ocp_qp_res *res, float *value); -// -void s_ocp_qp_res_get_max_res_comp(struct s_ocp_qp_res *res, float *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_OCP_QP_RES_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_sol.h deleted file mode 100644 index 94dfa0d003b5d2..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_sol.h +++ /dev/null @@ -1,128 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_SOL_H_ -#define HPIPM_S_OCP_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_sol - { - struct s_ocp_qp_dim *dim; - struct blasfeo_svec *ux; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_ocp_qp_sol_strsize(); -// -hpipm_size_t s_ocp_qp_sol_memsize(struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_sol_create(struct s_ocp_qp_dim *dim, struct s_ocp_qp_sol *qp_sol, void *memory); -// -void s_ocp_qp_sol_copy_all(struct s_ocp_qp_sol *qp_sol_orig, struct s_ocp_qp_sol *qp_sol_dest); -// -void s_qp_sol_get_all(struct s_ocp_qp_sol *qp_sol, float **u, float **x, float **ls, float **us, float **pi, float **lam_lb, float **lam_ub, float **lam_lg, float **lam_ug, float **lam_ls, float **lam_us); -// -void s_qp_sol_get_all_rowmaj(struct s_ocp_qp_sol *qp_sol, float **u, float **x, float **ls, float **us, float **pi, float **lam_lb, float **lam_ub, float **lam_lg, float **lam_ug, float **lam_ls, float **lam_us); -// -void s_ocp_qp_sol_set_all(float **u, float **x, float **ls, float **us, float **pi, float **lam_lb, float **lam_ub, float **lam_lg, float **lam_ug, float **lam_ls, float **lam_us, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_get(char *field, int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_u(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_x(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_sl(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_su(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_pi(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_lb(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_lbu(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_lbx(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_ub(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_ubu(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_ubx(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_lg(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_ug(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_set(char *field, int stage, float *vec, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_set_u(int stage, float *vec, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_set_x(int stage, float *vec, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_set_sl(int stage, float *vec, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_set_su(int stage, float *vec, struct s_ocp_qp_sol *qp_sol); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_OCP_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_utils.h deleted file mode 100644 index a4f832a5eac05b..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_utils.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_UTILS_H_ -#define HPIPM_S_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qp_dim.h" -#include "hpipm_s_ocp_qp.h" -#include "hpipm_s_ocp_qp_sol.h" -#include "hpipm_s_ocp_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_ocp_qp_dim_print(struct s_ocp_qp_dim *qp_dim); -// -void s_ocp_qp_dim_codegen(char *file_name, char *mode, struct s_ocp_qp_dim *qp_dim); -// -void s_ocp_qp_print(struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp *qp); -// -void s_ocp_qp_codegen(char *file_name, char *mode, struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp *qp); -// -void s_ocp_qp_sol_print(struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp_sol *ocp_qp_sol); -// -void s_ocp_qp_ipm_arg_print(struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp_ipm_arg *arg); -// -void s_ocp_qp_ipm_arg_codegen(char *file_name, char *mode, struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp_ipm_arg *arg); -// -void s_ocp_qp_res_print(struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp_res *ocp_qp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_UTILS_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_part_cond.h b/third_party/acados/include/hpipm/include/hpipm_s_part_cond.h deleted file mode 100644 index e40511e69f0c12..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_part_cond.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_PART_COND_H_ -#define HPIPM_S_PART_COND_H_ - - - -#include -#include - -#include "hpipm_s_cond.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_part_cond_qp_arg - { - struct s_cond_qp_arg *cond_arg; - int N2; - hpipm_size_t memsize; - }; - - - -struct s_part_cond_qp_ws - { - struct s_cond_qp_ws *cond_workspace; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_part_cond_qp_arg_memsize(int N2); -// -void s_part_cond_qp_arg_create(int N2, struct s_part_cond_qp_arg *cond_arg, void *mem); -// -void s_part_cond_qp_arg_set_default(struct s_part_cond_qp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 squre-root -void s_part_cond_qp_arg_set_ric_alg(int ric_alg, struct s_part_cond_qp_arg *cond_arg); -// -void s_part_cond_qp_arg_set_comp_prim_sol(int value, struct s_part_cond_qp_arg *cond_arg); -// -void s_part_cond_qp_arg_set_comp_dual_sol_eq(int value, struct s_part_cond_qp_arg *cond_arg); -// -void s_part_cond_qp_arg_set_comp_dual_sol_ineq(int value, struct s_part_cond_qp_arg *cond_arg); - -// -void s_part_cond_qp_compute_block_size(int N, int N2, int *block_size); -// -void s_part_cond_qp_compute_dim(struct s_ocp_qp_dim *ocp_dim, int *block_size, struct s_ocp_qp_dim *part_dense_dim); -// -hpipm_size_t s_part_cond_qp_ws_memsize(struct s_ocp_qp_dim *ocp_dim, int *block_size, struct s_ocp_qp_dim *part_dense_dim, struct s_part_cond_qp_arg *cond_arg); -// -void s_part_cond_qp_ws_create(struct s_ocp_qp_dim *ocp_dim, int *block_size, struct s_ocp_qp_dim *part_dense_dim, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws, void *mem); -// -void s_part_cond_qp_cond(struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); -// -void s_part_cond_qp_cond_lhs(struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); -// -void s_part_cond_qp_cond_rhs(struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); -// -void s_part_cond_qp_expand_sol(struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_ocp_qp_sol *part_dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); - -// -void s_part_cond_qp_update(int *idxc, struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_PART_COND_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_part_cond_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_part_cond_qcqp.h deleted file mode 100644 index 311f7000bf28ac..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_part_cond_qcqp.h +++ /dev/null @@ -1,107 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_PART_COND_QCQP_H_ -#define HPIPM_S_PART_COND_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_cond_qcqp.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_part_cond_qcqp_arg - { - struct s_cond_qcqp_arg *cond_arg; - int N2; - hpipm_size_t memsize; - }; - - - -struct s_part_cond_qcqp_ws - { - struct s_cond_qcqp_ws *cond_ws; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_part_cond_qcqp_arg_memsize(int N2); -// -void s_part_cond_qcqp_arg_create(int N2, struct s_part_cond_qcqp_arg *cond_arg, void *mem); -// -void s_part_cond_qcqp_arg_set_default(struct s_part_cond_qcqp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 squre-root -void s_part_cond_qcqp_arg_set_ric_alg(int ric_alg, struct s_part_cond_qcqp_arg *cond_arg); - -// -void s_part_cond_qcqp_compute_block_size(int N, int N2, int *block_size); -// -void s_part_cond_qcqp_compute_dim(struct s_ocp_qcqp_dim *ocp_dim, int *block_size, struct s_ocp_qcqp_dim *part_dense_dim); -// -hpipm_size_t s_part_cond_qcqp_ws_memsize(struct s_ocp_qcqp_dim *ocp_dim, int *block_size, struct s_ocp_qcqp_dim *part_dense_dim, struct s_part_cond_qcqp_arg *cond_arg); -// -void s_part_cond_qcqp_ws_create(struct s_ocp_qcqp_dim *ocp_dim, int *block_size, struct s_ocp_qcqp_dim *part_dense_dim, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws, void *mem); -// -void s_part_cond_qcqp_cond(struct s_ocp_qcqp *ocp_qp, struct s_ocp_qcqp *part_dense_qp, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws); -// -void s_part_cond_qcqp_cond_lhs(struct s_ocp_qcqp *ocp_qp, struct s_ocp_qcqp *part_dense_qp, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws); -// -void s_part_cond_qcqp_cond_rhs(struct s_ocp_qcqp *ocp_qp, struct s_ocp_qcqp *part_dense_qp, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws); -// -void s_part_cond_qcqp_expand_sol(struct s_ocp_qcqp *ocp_qp, struct s_ocp_qcqp *part_dense_qp, struct s_ocp_qcqp_sol *part_dense_qp_sol, struct s_ocp_qcqp_sol *ocp_qp_sol, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_PART_COND_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_sim_erk.h b/third_party/acados/include/hpipm/include/hpipm_s_sim_erk.h deleted file mode 100644 index 1a05ad1a283f85..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_sim_erk.h +++ /dev/null @@ -1,121 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_SIM_ERK_H_ -#define HPIPM_S_SIM_ERK_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_sim_erk_arg - { - struct s_sim_rk_data *rk_data; // integrator data - float h; // step size - int steps; // number of steps -// int for_sens; // compute adjoint sensitivities -// int adj_sens; // compute adjoint sensitivities - hpipm_size_t memsize; - }; - - - -struct s_sim_erk_ws - { - void (*ode)(int t, float *x, float *p, void *ode_args, float *xdot); // function pointer to ode - void (*vde_for)(int t, float *x, float *p, void *ode_args, float *xdot); // function pointer to forward vde - void (*vde_adj)(int t, float *adj_in, void *ode_args, float *adj_out); // function pointer to adjoint vde - void *ode_args; // pointer to ode args - struct s_sim_erk_arg *erk_arg; // erk arg - float *K; // internal variables - float *x_for; // states and forward sensitivities - float *x_traj; // states at all steps - float *l; // adjoint sensitivities - float *p; // parameter - float *x_tmp; // temporary states and forward sensitivities - float *adj_in; - float *adj_tmp; - int nx; // number of states - int np; // number of parameters - int nf; // number of forward sensitivities - int na; // number of adjoint sensitivities - int nf_max; // max number of forward sensitivities - int na_max; // max number of adjoint sensitivities - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_sim_erk_arg_memsize(); -// -void s_sim_erk_arg_create(struct s_sim_erk_arg *erk_arg, void *mem); -// -void s_sim_erk_arg_set_all(struct s_sim_rk_data *rk_data, float h, int steps, struct s_sim_erk_arg *erk_arg); - -// -hpipm_size_t s_sim_erk_ws_memsize(struct s_sim_erk_arg *erk_arg, int nx, int np, int nf_max, int na_max); -// -void s_sim_erk_ws_create(struct s_sim_erk_arg *erk_arg, int nx, int np, int nf_max, int na_max, struct s_sim_erk_ws *work, void *memory); -// -void s_sim_erk_ws_set_all(int nf, int na, float *x, float *fs, float *bs, float *p, void (*ode)(int t, float *x, float *p, void *ode_args, float *xdot), void (*vde_for)(int t, float *x, float *p, void *ode_args, float *xdot), void (*vde_adj)(int t, float *adj_in, void *ode_args, float *adj_out), void *ode_args, struct s_sim_erk_ws *work); -// number of directions for forward sensitivities -void s_sim_erk_ws_set_nf(int *nf, struct s_sim_erk_ws *work); -// parameters (e.g. inputs) -void s_sim_erk_ws_set_p(float *p, struct s_sim_erk_ws *work); -// state -void s_sim_erk_ws_set_x(float *x, struct s_sim_erk_ws *work); -// forward sensitivities -void s_sim_erk_ws_set_fs(float *fs, struct s_sim_erk_ws *work); -// ode funtion -void s_sim_erk_ws_set_ode(void (*ode)(int t, float *x, float *p, void *ode_args, float *xdot), struct s_sim_erk_ws *work); -// forward vde function -void s_sim_erk_ws_set_vde_for(void (*ode)(int t, float *x, float *p, void *ode_args, float *xdot), struct s_sim_erk_ws *work); -// ode_args, passed straight to the ode/vde_for/vde_adj functions -void s_sim_erk_ws_set_ode_args(void *ode_args, struct s_sim_erk_ws *work); -// state -void s_sim_erk_ws_get_x(struct s_sim_erk_ws *work, float *x); -// forward sensitivities -void s_sim_erk_ws_get_fs(struct s_sim_erk_ws *work, float *fs); -// -void s_sim_erk_solve(struct s_sim_erk_arg *arg, struct s_sim_erk_ws *work); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_D_SIM_ERK_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_sim_rk.h b/third_party/acados/include/hpipm/include/hpipm_s_sim_rk.h deleted file mode 100644 index 53acd71498f033..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_sim_rk.h +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_SIM_RK_H_ -#define HPIPM_S_SIM_RK_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_sim_rk_data - { - float *A_rk; // A in butcher tableau - float *B_rk; // b in butcher tableau - float *C_rk; // c in butcher tableau - int expl; // erk vs irk - int ns; // number of stages - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_sim_rk_data_memsize(int ns); -// -void s_sim_rk_data_create(int ns, struct s_sim_rk_data *rk_data, void *memory); -// -void s_sim_rk_data_init_default(char *field, struct s_sim_rk_data *rk_data); -// -void s_sim_rk_data_set_all(int expl, float *A_rk, float *B_rk, float *C_rk, struct s_sim_rk_data *rk_data); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_S_SIM_RK_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp.h deleted file mode 100644 index 450e992624b22b..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp.h +++ /dev/null @@ -1,213 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_H_ -#define HPIPM_S_TREE_OCP_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qcqp - { - struct s_tree_ocp_qcqp_dim *dim; - struct blasfeo_smat *BAbt; // Nn-1 - struct blasfeo_smat *RSQrq; // Nn - struct blasfeo_smat *DCt; // Nn - struct blasfeo_smat **Hq; // Nn - struct blasfeo_svec *b; // Nn-1 - struct blasfeo_svec *rqz; // Nn - struct blasfeo_svec *d; // Nn - struct blasfeo_svec *d_mask; // Nn - struct blasfeo_svec *m; // Nn - struct blasfeo_svec *Z; // Nn - int **idxb; // indices of box constrained variables within [u; x] // Nn - int **idxs_rev; // index of soft constraints - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_memsize(struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_create(struct s_tree_ocp_qcqp_dim *dim, struct s_tree_ocp_qcqp *qp, void *memory); -// -void s_tree_ocp_qcqp_set_all(float **A, float **B, float **b, float **Q, float **S, float **R, float **q, float **r, int **idxb, float **d_lb, float **d_ub, float **C, float **D, float **d_lg, float **d_ug, float **Zl, float **Zu, float **zl, float **zu, int **idxs, float **d_ls, float **d_us, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set(char *field_name, int node_edge, void *value, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_A(int edge, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_B(int edge, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_b(int edge, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Q(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_S(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_R(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_q(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_r(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lb(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lb_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ub(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ub_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lbx(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lbx_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ubx(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ubx_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lbu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lbu_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ubu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ubu_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxb(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxbx(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jbx(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxbu(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jbu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_C(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_D(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lg(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lg_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ug(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ug_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Qq(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Sq(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Rq(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_qq(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_rq(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_uq(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_uq_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Zl(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Zu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_zl(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_zu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lls(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lls_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lus(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lus_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxs(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxs_rev(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jsbu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jsbx(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jsg(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jsq(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_idxe(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_idxbxe(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_idxbue(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_idxge(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_Jbxe(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_Jbue(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_Jge(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_diag_H_flag(int node, int *value, struct s_tree_ocp_qcqp *qp); - - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_dim.h deleted file mode 100644 index 7a49d519959afb..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_dim.h +++ /dev/null @@ -1,118 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_DIM_H_ -#define HPIPM_S_TREE_OCP_QCQP_DIM_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qcqp_dim - { - struct s_tree_ocp_qp_dim *qp_dim; // dim of qp approximation - struct tree *ttree; // tree describing node conndection - int *nx; // number of states // Nn - int *nu; // number of inputs // Nn - int *nb; // number of box constraints // Nn - int *nbx; // number of state box constraints // Nn - int *nbu; // number of input box constraints // Nn - int *ng; // number of general constraints // Nn - int *nq; // number of (upper) quadratic constraints - int *ns; // number of soft constraints // Nn - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int *nsq; // number of (upper) soft quadratic constraints - int Nn; // number of nodes - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_dim_strsize(); -// -hpipm_size_t s_tree_ocp_qcqp_dim_memsize(int Nn); -// -void s_tree_ocp_qcqp_dim_create(int Nn, struct s_tree_ocp_qcqp_dim *qp_dim, void *memory); -// -void s_tree_ocp_qcqp_dim_set_tree(struct tree *ttree, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set(char *field, int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nx(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nu(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nbx(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nbu(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_ng(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nq(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_ns(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nsbx(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nsbu(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nsg(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nsq(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -//void s_tree_ocp_qcqp_dim_set_nbxe(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -//void s_tree_ocp_qcqp_dim_set_nbue(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -//void s_tree_ocp_qcqp_dim_set_nge(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_TREE_OCP_QCQP_DIM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_ipm.h deleted file mode 100644 index 69d65914c527c4..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_ipm.h +++ /dev/null @@ -1,192 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_IPM_H_ -#define HPIPM_S_TREE_OCP_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qcqp_ipm_arg - { - struct s_tree_ocp_qp_ipm_arg *qp_arg; - float mu0; // initial value for complementarity slackness - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol -// int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) -// int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_tree_ocp_qcqp_ipm_ws - { - struct s_tree_ocp_qp_ipm_ws *qp_ws; - struct s_tree_ocp_qp *qp; - struct s_tree_ocp_qp_sol *qp_sol; - struct s_tree_ocp_qcqp_res_ws *qcqp_res_ws; - struct s_tree_ocp_qcqp_res *qcqp_res; - struct blasfeo_svec *tmp_nuxM; - int iter; // iteration number - int status; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_ipm_arg_strsize(); -// -hpipm_size_t s_tree_ocp_qcqp_ipm_arg_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim); -// -void s_tree_ocp_qcqp_ipm_arg_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg, void *mem); -// -void s_tree_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct s_tree_ocp_qcqp_ipm_arg *arg); -// -void s_tree_ocp_qcqp_ipm_arg_set(char *field, void *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set maximum number of iterations -void s_tree_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set minimum step lenght -void s_tree_ocp_qcqp_ipm_arg_set_alpha_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set initial value of barrier parameter -void s_tree_ocp_qcqp_ipm_arg_set_mu0(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void s_tree_ocp_qcqp_ipm_arg_set_tol_stat(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on equality constr -void s_tree_ocp_qcqp_ipm_arg_set_tol_eq(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on inequality constr -void s_tree_ocp_qcqp_ipm_arg_set_tol_ineq(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void s_tree_ocp_qcqp_ipm_arg_set_tol_comp(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set regularization of primal variables -void s_tree_ocp_qcqp_ipm_arg_set_reg_prim(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void s_tree_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void s_tree_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void s_tree_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -//void s_tree_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// compute residuals after solution -void s_tree_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// compute residuals of prediction -//void s_tree_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// min value of lam in the solution -void s_tree_ocp_qcqp_ipm_arg_set_lam_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// min value of t in the solution -void s_tree_ocp_qcqp_ipm_arg_set_t_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// use different step for primal and dual variables -void s_tree_ocp_qcqp_ipm_arg_set_split_step(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void s_tree_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); - -// -hpipm_size_t s_tree_ocp_qcqp_ipm_ws_strsize(); -// -hpipm_size_t s_tree_ocp_qcqp_ipm_ws_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg); -// -void s_tree_ocp_qcqp_ipm_ws_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws, void *mem); -// -void s_tree_ocp_qcqp_ipm_get(char *field, struct s_tree_ocp_qcqp_ipm_ws *ws, void *value); -// -void s_tree_ocp_qcqp_ipm_get_status(struct s_tree_ocp_qcqp_ipm_ws *ws, int *status); -// -void s_tree_ocp_qcqp_ipm_get_iter(struct s_tree_ocp_qcqp_ipm_ws *ws, int *iter); -// -void s_tree_ocp_qcqp_ipm_get_max_res_stat(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_stat); -// -void s_tree_ocp_qcqp_ipm_get_max_res_eq(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_eq); -// -void s_tree_ocp_qcqp_ipm_get_max_res_ineq(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_ineq); -// -void s_tree_ocp_qcqp_ipm_get_max_res_comp(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_comp); -// -void s_tree_ocp_qcqp_ipm_get_stat(struct s_tree_ocp_qcqp_ipm_ws *ws, float **stat); -// -void s_tree_ocp_qcqp_ipm_get_stat_m(struct s_tree_ocp_qcqp_ipm_ws *ws, int *stat_m); -// -void s_tree_ocp_qcqp_init_var(struct s_tree_ocp_qcqp *qp, struct s_tree_ocp_qcqp_sol *qp_sol, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws); -// -void s_tree_ocp_qcqp_ipm_solve(struct s_tree_ocp_qcqp *qp, struct s_tree_ocp_qcqp_sol *qp_sol, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_TREE_OCP_QCQP_IPM_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_res.h deleted file mode 100644 index d0d84a6f23952f..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_res.h +++ /dev/null @@ -1,109 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_RES_H_ -#define HPIPM_S_TREE_OCP_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qcqp_res - { - struct s_tree_ocp_qcqp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_tree_ocp_qcqp_res_ws - { - struct blasfeo_svec *tmp_nuxM; // work space of size nuM+nxM - struct blasfeo_svec *tmp_nbgqM; // work space of size nbM+ngM+nqM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - struct blasfeo_svec *q_fun; // value for evaluation of quadr constr - struct blasfeo_svec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_res_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim); -// -void s_tree_ocp_qcqp_res_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_res *res, void *mem); -// -hpipm_size_t s_tree_ocp_qcqp_res_ws_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim); -// -void s_tree_ocp_qcqp_res_ws_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_res_ws *ws, void *mem); -// -void s_tree_ocp_qcqp_res_compute(struct s_tree_ocp_qcqp *qp, struct s_tree_ocp_qcqp_sol *qp_sol, struct s_tree_ocp_qcqp_res *res, struct s_tree_ocp_qcqp_res_ws *ws); -// -void s_tree_ocp_qcqp_res_compute_inf_norm(struct s_tree_ocp_qcqp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_TREE_OCP_QCQP_RES_H_ - - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_sol.h deleted file mode 100644 index 47f038c6b3dfe5..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_sol.h +++ /dev/null @@ -1,97 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_SOL_H_ -#define HPIPM_S_TREE_OCP_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_tree_ocp_qcqp_sol - { - struct s_tree_ocp_qcqp_dim *dim; - struct blasfeo_svec *ux; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_sol_memsize(struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_sol_create(struct s_tree_ocp_qcqp_dim *dim, struct s_tree_ocp_qcqp_sol *qp_sol, void *memory); -// -void s_tree_ocp_qcqp_sol_get_u(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_x(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_sl(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_su(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_pi(int edge, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_lam_lb(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_lam_ub(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_lam_lg(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_lam_ug(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QCQP_SOL_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_utils.h deleted file mode 100644 index 79528de1ce74fa..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_utils.h +++ /dev/null @@ -1,85 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_UTILS_H_ -#define HPIPM_S_TREE_OCP_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qcqp_dim.h" -#include "hpipm_s_tree_ocp_qcqp.h" -#include "hpipm_s_tree_ocp_qcqp_sol.h" -#include "hpipm_s_tree_ocp_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_tree_ocp_qcqp_dim_print(struct s_tree_ocp_qcqp_dim *qp_dim); -// -//void s_tree_ocp_qcqp_dim_codegen(char *file_name, char *mode, struct s_tree_ocp_qcqp_dim *qp_dim); -// -void s_tree_ocp_qcqp_print(struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_codegen(char *file_name, char *mode, struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_sol_print(struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp_sol *ocp_qcqp_sol); -// -void s_tree_ocp_qcqp_ipm_arg_print(struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg); -// -//void s_tree_ocp_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg); -// -void s_tree_ocp_qcqp_res_print(struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp_res *ocp_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_TREE_OCP_QCQP_UTILS_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp.h deleted file mode 100644 index 722b930b9a45c8..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp.h +++ /dev/null @@ -1,196 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_H_ -#define HPIPM_S_TREE_OCP_QP_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qp - { - struct s_tree_ocp_qp_dim *dim; - struct blasfeo_smat *BAbt; // Nn-1 - struct blasfeo_smat *RSQrq; // Nn - struct blasfeo_smat *DCt; // Nn - struct blasfeo_svec *b; // Nn-1 - struct blasfeo_svec *rqz; // Nn - struct blasfeo_svec *d; // Nn - struct blasfeo_svec *d_mask; // Nn - struct blasfeo_svec *m; // Nn - struct blasfeo_svec *Z; // Nn - int **idxb; // indices of box constrained variables within [u; x] // Nn -// int **idxs; // index of soft constraints - int **idxs_rev; // index of soft constraints - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_tree_ocp_qp_memsize(struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_create(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp *qp, void *memory); -// -void s_tree_ocp_qp_set_all(float **A, float **B, float **b, float **Q, float **S, float **R, float **q, float **r, int **idxb, float **d_lb, float **d_ub, float **C, float **D, float **d_lg, float **d_ug, float **Zl, float **Zu, float **zl, float **zu, int **idxs, float **d_ls, float **d_us, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set(char *field_name, int node_edge, void *value, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_A(int edge, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_B(int edge, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_b(int edge, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Q(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_S(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_R(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_q(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_r(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lb(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lb_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ub(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ub_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lbx(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lbx_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ubx(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ubx_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lbu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lbu_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ubu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ubu_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxb(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxbx(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jbx(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxbu(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jbu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_C(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_D(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lg(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lg_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ug(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ug_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Zl(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Zu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_zl(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_zu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lls(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lls_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lus(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lus_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxs(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxs_rev(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jsbu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jsbx(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jsg(int node, float *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_idxe(int node, int *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_idxbxe(int node, int *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_idxbue(int node, int *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_idxge(int node, int *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_Jbxe(int node, float *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_Jbue(int node, float *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_Jge(int node, float *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_diag_H_flag(int node, int *value, struct s_tree_ocp_qp *qp); - - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_dim.h deleted file mode 100644 index 90df57182b7993..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_dim.h +++ /dev/null @@ -1,111 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_DIM_H_ -#define HPIPM_S_TREE_OCP_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qp_dim - { - struct tree *ttree; // tree describing node conndection - int *nx; // number of states // Nn - int *nu; // number of inputs // Nn - int *nb; // number of box constraints // Nn - int *nbx; // number of state box constraints // Nn - int *nbu; // number of input box constraints // Nn - int *ng; // number of general constraints // Nn - int *ns; // number of soft constraints // Nn - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int Nn; // number of nodes - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qp_dim_strsize(); -// -hpipm_size_t s_tree_ocp_qp_dim_memsize(int Nn); -// -void s_tree_ocp_qp_dim_create(int Nn, struct s_tree_ocp_qp_dim *qp_dim, void *memory); -// -void s_tree_ocp_qp_dim_set_all(struct tree *ttree, int *nx, int *nu, int *nbx, int *nbu, int *ng, int *nsbx, int *nsbu, int *nsg, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_tree(struct tree *ttree, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set(char *field, int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nx(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nu(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nbx(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nbu(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_ng(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_ns(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nsbx(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nsbu(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nsg(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nbxe(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nbue(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nge(int stage, int value, struct s_tree_ocp_qp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_ipm.h deleted file mode 100644 index f8c26d31737f0d..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_ipm.h +++ /dev/null @@ -1,208 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_TREE_OCP_QP_IPM_H_ -#define HPIPM_S_TREE_OCP_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qp_ipm_arg - { - float mu0; // initial value for duality measure - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - float tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol==1) - int split_step; // use different steps for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_tree_ocp_qp_ipm_ws - { - struct s_core_qp_ipm_workspace *core_workspace; - struct s_tree_ocp_qp_res_ws *res_workspace; - struct s_tree_ocp_qp_sol *sol_step; - struct s_tree_ocp_qp_sol *sol_itref; - struct s_tree_ocp_qp *qp_step; - struct s_tree_ocp_qp *qp_itref; - struct s_tree_ocp_qp_res *res_itref; - struct s_tree_ocp_qp_res *res; - struct blasfeo_svec *Gamma; // hessian update - struct blasfeo_svec *gamma; // hessian update - struct blasfeo_svec *tmp_nxM; // work space of size nxM - struct blasfeo_svec *tmp_nbgM; // work space of size nbgM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - struct blasfeo_svec *Pb; // Pb - struct blasfeo_svec *Zs_inv; - struct blasfeo_smat *L; - struct blasfeo_smat *Lh; - struct blasfeo_smat *AL; - struct blasfeo_smat *lq0; - struct blasfeo_svec *tmp_m; - float *stat; // convergence statistics - int *use_hess_fact; - void *lq_work0; - float qp_res[4]; // infinity norm of residuals - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int use_Pb; - int status; // solver status - int lq_fact; // cache from arg - int mask_constr; // use constr mask - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qp_ipm_arg_memsize(struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_ipm_arg_create(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp_ipm_arg *arg, void *mem); -// -void s_tree_ocp_qp_ipm_arg_set_default(enum hpipm_mode mode, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_iter_max(int *iter_max, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_alpha_min(float *alpha_min, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_mu0(float *mu0, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tol_stat(float *tol_stat, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tol_eq(float *tol_eq, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tol_comp(float *tol_comp, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_reg_prim(float *reg, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_warm_start(int *warm_start, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_pred_corr(int *pred_corr, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_cond_pred_corr(int *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_comp_dual_sol_eq(int *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_comp_res_exit(int *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_lam_min(float *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_t_min(float *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tau_min(float *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_split_step(int *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_t_lam_min(int *value, struct s_tree_ocp_qp_ipm_arg *arg); - -// -hpipm_size_t s_tree_ocp_qp_ipm_ws_memsize(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_ws_create(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws, void *mem); -// -void s_tree_ocp_qp_ipm_get_status(struct s_tree_ocp_qp_ipm_ws *ws, int *status); -// -void s_tree_ocp_qp_ipm_get_iter(struct s_tree_ocp_qp_ipm_ws *ws, int *iter); -// -void s_tree_ocp_qp_ipm_get_max_res_stat(struct s_tree_ocp_qp_ipm_ws *ws, float *res_stat); -// -void s_tree_ocp_qp_ipm_get_max_res_eq(struct s_tree_ocp_qp_ipm_ws *ws, float *res_eq); -// -void s_tree_ocp_qp_ipm_get_max_res_ineq(struct s_tree_ocp_qp_ipm_ws *ws, float *res_ineq); -// -void s_tree_ocp_qp_ipm_get_max_res_comp(struct s_tree_ocp_qp_ipm_ws *ws, float *res_comp); -// -void s_tree_ocp_qp_ipm_get_stat(struct s_tree_ocp_qp_ipm_ws *ws, float **stat); -// -void s_tree_ocp_qp_ipm_get_stat_m(struct s_tree_ocp_qp_ipm_ws *ws, int *stat_m); -// -void s_tree_ocp_qp_init_var(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_ipm_abs_step(int kk, struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_ipm_delta_step(int kk, struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_ipm_solve(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_kkt.h deleted file mode 100644 index bcf7354783d2c3..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_kkt.h +++ /dev/null @@ -1,54 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -#ifdef __cplusplus -extern "C" { -#endif - -// -void s_tree_ocp_qp_fact_solve_kkt_unconstr(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_fact_solve_kkt_step(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_fact_lq_solve_kkt_step(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_solve_kkt_step(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_res.h deleted file mode 100644 index 5c6797204f847a..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_res.h +++ /dev/null @@ -1,107 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_RES_H_ -#define HPIPM_S_TREE_OCP_QP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qp_res - { - struct s_tree_ocp_qp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_tree_ocp_qp_res_ws - { - struct blasfeo_svec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qp_res_memsize(struct s_tree_ocp_qp_dim *ocp_dim); -// -void s_tree_ocp_qp_res_create(struct s_tree_ocp_qp_dim *ocp_dim, struct s_tree_ocp_qp_res *res, void *mem); -// -hpipm_size_t s_tree_ocp_qp_res_ws_memsize(struct s_tree_ocp_qp_dim *ocp_dim); -// -void s_tree_ocp_qp_res_ws_create(struct s_tree_ocp_qp_dim *ocp_dim, struct s_tree_ocp_qp_res_ws *ws, void *mem); -// -void s_tree_ocp_qp_res_get_all(struct s_tree_ocp_qp_res *res, float **res_r, float **res_q, float **res_ls, float **res_us, float **res_b, float **res_d_lb, float **res_d_ub, float **res_d_lg, float **res_d_ug, float **res_d_ls, float **res_d_us, float **res_m_lb, float **res_m_ub, float **res_m_lg, float **res_m_ug, float **res_m_ls, float **res_m_us); -// -void s_tree_ocp_qp_res_compute(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_res *res, struct s_tree_ocp_qp_res_ws *ws); -// -void s_tree_ocp_qp_res_compute_lin(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_sol *qp_step, struct s_tree_ocp_qp_res *res, struct s_tree_ocp_qp_res_ws *ws); -// -void s_tree_ocp_qp_res_compute_inf_norm(struct s_tree_ocp_qp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_TREE_OCP_QP_RES_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_sol.h deleted file mode 100644 index 71e887675bc3d0..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_sol.h +++ /dev/null @@ -1,98 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_SOL_H_ -#define HPIPM_S_TREE_OCP_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_tree_ocp_qp_sol - { - struct s_tree_ocp_qp_dim *dim; - struct blasfeo_svec *ux; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_tree_ocp_qp_sol_memsize(struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_sol_create(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp_sol *qp_sol, void *memory); -// -void s_tree_ocp_qp_sol_get_all(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, float **u, float **x, float **ls, float **us, float **pi, float **lam_lb, float **lam_ub, float **lam_lg, float **lam_ug, float **lam_ls, float **lam_us); -// -void s_tree_ocp_qp_sol_get_u(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_x(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_sl(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_su(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_pi(int edge, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_lam_lb(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_lam_ub(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_lam_lg(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_lam_ug(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_utils.h deleted file mode 100644 index ec1747568f08a8..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_utils.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_UTILS_H_ -#define HPIPM_S_TREE_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qp_dim.h" -#include "hpipm_s_tree_ocp_qp.h" -#include "hpipm_s_tree_ocp_qp_sol.h" -#include "hpipm_s_tree_ocp_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_tree_ocp_qp_dim_print(struct s_tree_ocp_qp_dim *qp_dim); -// -//void s_tree_ocp_qp_dim_codegen(char *file_name, char *mode, struct s_tree_ocp_qp_dim *qp_dim); -// -void s_tree_ocp_qp_print(struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_codegen(char *file_name, char *mode, struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_sol_print(struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp_sol *ocp_qp_sol); -// -void s_tree_ocp_qp_ipm_arg_print(struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp_ipm_arg *arg); -// -//void s_tree_ocp_qp_ipm_arg_codegen(char *file_name, char *mode, struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_res_print(struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp_res *ocp_qp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_scenario_tree.h b/third_party/acados/include/hpipm/include/hpipm_scenario_tree.h deleted file mode 100644 index a3c77a670a1d02..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_scenario_tree.h +++ /dev/null @@ -1,70 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_SCENARIO_TREE_H_ -#define HPIPM_SCENARIO_TREE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct sctree - { - struct node *root; // pointer to root - int *kids; // pointer to array of kids - int Nn; // numer of nodes - int md; // number of realizations - int Nr; // robust horizion - int Nh; // control horizion - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t sctree_memsize(int md, int Nr, int Nh); -// -void sctree_create(int md, int Nr, int Nh, struct sctree *st, void *memory); -// -void sctree_cast_to_tree(struct sctree *st, struct tree *tt); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_SCENARIO_TREE_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_timing.h b/third_party/acados/include/hpipm/include/hpipm_timing.h deleted file mode 100644 index bd0f2dbcb34c5f..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_timing.h +++ /dev/null @@ -1,67 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_TIMING_H_ -#define HPIPM_TIMING_H_ - - - -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -typedef blasfeo_timer hpipm_timer; - - - -// -void hpipm_tic(hpipm_timer *t); -// -double hpipm_toc(hpipm_timer *t); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_TIMING_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_tree.h b/third_party/acados/include/hpipm/include/hpipm_tree.h deleted file mode 100644 index f9d69ecdddda74..00000000000000 --- a/third_party/acados/include/hpipm/include/hpipm_tree.h +++ /dev/null @@ -1,76 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are met: * -* * -* 1. Redistributions of source code must retain the above copyright notice, this * -* list of conditions and the following disclaimer. * -* 2. Redistributions in binary form must reproduce the above copyright notice, * -* this list of conditions and the following disclaimer in the documentation * -* and/or other materials provided with the distribution. * -* * -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -#ifndef HPIPM_TREE_H_ -#define HPIPM_TREE_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct node - { - int *kids; // 64 bits - int idx; // 32 bits - int dad; // 32 bits - int nkids; // 32 bits - int stage; // 32 bits - int real; // 32 bits - int idxkid; // 32 bits // XXX needed ??? - // total 256 bits - }; - - - -struct tree - { - struct node *root; // pointer to root - int *kids; // pointer to array of kids - int Nn; // numer of nodes - hpipm_size_t memsize; - }; - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_TREE_H_ diff --git a/third_party/acados/include/qpOASES_e/Bounds.h b/third_party/acados/include/qpOASES_e/Bounds.h deleted file mode 100644 index 4e41c1d163b63d..00000000000000 --- a/third_party/acados/include/qpOASES_e/Bounds.h +++ /dev/null @@ -1,543 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Bounds.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Bounds class designed to manage working sets of - * bounds within a QProblem. - */ - - -#ifndef QPOASES_BOUNDS_H -#define QPOASES_BOUNDS_H - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Manages working sets of bounds (= box constraints). - * - * This class manages working sets of bounds (= box constraints) - * by storing index sets and other status information. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - Indexlist *freee; /**< Index list of free variables. */ - Indexlist *fixed; /**< Index list of fixed variables. */ - - Indexlist *shiftedFreee; /**< Memory for shifting free variables. */ - Indexlist *shiftedFixed; /**< Memory for shifting fixed variables. */ - - Indexlist *rotatedFreee; /**< Memory for rotating free variables. */ - Indexlist *rotatedFixed; /**< Memory for rotating fixed variables. */ - - SubjectToType *type; /**< Type of bounds. */ - SubjectToStatus *status; /**< Status of bounds. */ - - SubjectToType *typeTmp; /**< Temp memory for type of bounds. */ - SubjectToStatus *statusTmp; /**< Temp memory for status of bounds. */ - - BooleanType noLower; /**< This flag indicates if there is no lower bound on any variable. */ - BooleanType noUpper; /**< This flag indicates if there is no upper bound on any variable. */ - - int n; /**< Total number of bounds. */ -} Bounds; - -int Bounds_calculateMemorySize( int n); - -char *Bounds_assignMemory(int n, Bounds **mem, void *raw_memory); - -Bounds *Bounds_createMemory( int n ); - -/** Constructor which takes the number of bounds. */ -void BoundsCON( Bounds* _THIS, - int _n /**< Number of bounds. */ - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void BoundsCPY( Bounds* FROM, - Bounds* TO - ); - - -/** Initialises object with given number of bounds. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_init( Bounds* _THIS, - int _n /**< Number of bounds. */ - ); - - -/** Initially adds number of a new (i.e. not yet in the list) bound to - * given index set. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_setupBound( Bounds* _THIS, - int number, /**< Number of new bound. */ - SubjectToStatus _status /**< Status of new bound. */ - ); - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set of free bounds; the order depends on the SujectToType - * of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED */ -returnValue Bounds_setupAllFree( Bounds* _THIS - ); - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set of fixed bounds (on their lower bounds); - * the order depends on the SujectToType of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED */ -returnValue Bounds_setupAllLower( Bounds* _THIS - ); - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set of fixed bounds (on their upper bounds); - * the order depends on the SujectToType of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED */ -returnValue Bounds_setupAllUpper( Bounds* _THIS - ); - - -/** Moves index of a bound from index list of fixed to that of free bounds. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_BOUND_FAILED \n - RET_INDEX_OUT_OF_BOUNDS */ -returnValue Bounds_moveFixedToFree( Bounds* _THIS, - int number /**< Number of bound to be freed. */ - ); - -/** Moves index of a bound from index list of free to that of fixed bounds. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_BOUND_FAILED \n - RET_INDEX_OUT_OF_BOUNDS */ -returnValue Bounds_moveFreeToFixed( Bounds* _THIS, - int number, /**< Number of bound to be fixed. */ - SubjectToStatus _status /**< Status of bound to be fixed. */ - ); - -/** Flip fixed bound. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_BOUND_FAILED \n - RET_INDEX_OUT_OF_BOUNDS */ -returnValue Bounds_flipFixed( Bounds* _THIS, - int number - ); - -/** Swaps the indices of two free bounds within the index set. - * \return SUCCESSFUL_RETURN \n - RET_SWAPINDEX_FAILED */ -returnValue Bounds_swapFree( Bounds* _THIS, - int number1, /**< Number of first bound. */ - int number2 /**< Number of second bound. */ - ); - - -/** Returns number of variables. - * \return Number of variables. */ -static inline int Bounds_getNV( Bounds* _THIS - ); - -/** Returns number of implicitly fixed variables. - * \return Number of implicitly fixed variables. */ -static inline int Bounds_getNFV( Bounds* _THIS - ); - -/** Returns number of bounded (but possibly free) variables. - * \return Number of bounded (but possibly free) variables. */ -static inline int Bounds_getNBV( Bounds* _THIS - ); - -/** Returns number of unbounded variables. - * \return Number of unbounded variables. */ -static inline int Bounds_getNUV( Bounds* _THIS - ); - -/** Returns number of free variables. - * \return Number of free variables. */ -static inline int Bounds_getNFR( Bounds* _THIS - ); - -/** Returns number of fixed variables. - * \return Number of fixed variables. */ -static inline int Bounds_getNFX( Bounds* _THIS - ); - - -/** Returns a pointer to free variables index list. - * \return Pointer to free variables index list. */ -static inline Indexlist* Bounds_getFree( Bounds* _THIS - ); - -/** Returns a pointer to fixed variables index list. - * \return Pointer to fixed variables index list. */ -static inline Indexlist* Bounds_getFixed( Bounds* _THIS - ); - - -/** Returns number of bounds with given SubjectTo type. - * \return Number of bounds with given type. */ -static inline int Bounds_getNumberOfType( Bounds* _THIS, - SubjectToType _type /**< Type of bound. */ - ); - - -/** Returns type of bound. - * \return Type of bound \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline SubjectToType Bounds_getType( Bounds* _THIS, - int i /**< Number of bound. */ - ); - -/** Returns status of bound. - * \return Status of bound \n - ST_UNDEFINED */ -static inline SubjectToStatus Bounds_getStatus( Bounds* _THIS, - int i /**< Number of bound. */ - ); - - -/** Sets type of bound. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue Bounds_setType( Bounds* _THIS, - int i, /**< Number of bound. */ - SubjectToType value /**< Type of bound. */ - ); - -/** Sets status of bound. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue Bounds_setStatus( Bounds* _THIS, - int i, /**< Number of bound. */ - SubjectToStatus value /**< Status of bound. */ - ); - - -/** Sets status of lower bounds. */ -static inline void Bounds_setNoLower( Bounds* _THIS, - BooleanType _status /**< Status of lower bounds. */ - ); - -/** Sets status of upper bounds. */ -static inline void Bounds_setNoUpper( Bounds* _THIS, - BooleanType _status /**< Status of upper bounds. */ - ); - - -/** Returns status of lower bounds. - * \return BT_TRUE if there is no lower bound on any variable. */ -static inline BooleanType Bounds_hasNoLower( Bounds* _THIS - ); - -/** Returns status of upper bounds. - * \return BT_TRUE if there is no upper bound on any variable. */ -static inline BooleanType Bounds_hasNoUpper( Bounds* _THIS - ); - - -/** Shifts forward type and status of all bounds by a given - * offset. This offset has to lie within the range [0,n/2] and has to - * be an integer divisor of the total number of bounds n. - * Type and status of the first \ bounds is thrown away, - * type and status of the last \ bounds is doubled, - * e.g. for offset = 2: \n - * shift( {b1,b2,b3,b4,b5,b6} ) = {b3,b4,b5,b6,b5,b6} - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_INVALID_ARGUMENTS \n - RET_SHIFTING_FAILED */ -returnValue Bounds_shift( Bounds* _THIS, - int offset /**< Shift offset within the range [0,n/2] and integer divisor of n. */ - ); - -/** Rotates forward type and status of all bounds by a given - * offset. This offset has to lie within the range [0,n]. - * Example for offset = 2: \n - * rotate( {b1,b2,b3,b4,b5,b6} ) = {b3,b4,b5,b6,b1,b2} - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_ROTATING_FAILED */ -returnValue Bounds_rotate( Bounds* _THIS, - int offset /**< Rotation offset within the range [0,n]. */ - ); - - -/** Prints information on bounds object - * (in particular, lists of free and fixed bounds. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue Bounds_print( Bounds* _THIS - ); - - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set corresponding to the desired status; - * the order depends on the SujectToType of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED */ -returnValue Bounds_setupAll( Bounds* _THIS, - SubjectToStatus _status /**< Desired initial status for all bounds. */ - ); - - -/** Adds the index of a new bound to index set. - * \return SUCCESSFUL_RETURN \n - RET_ADDINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_addIndex( Bounds* _THIS, - Indexlist* const indexlist, /**< Index list to which the new index shall be added. */ - int newnumber, /**< Number of new bound. */ - SubjectToStatus newstatus /**< Status of new bound. */ - ); - -/** Removes the index of a bound from index set. - * \return SUCCESSFUL_RETURN \n - RET_REMOVEINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_removeIndex( Bounds* _THIS, - Indexlist* const indexlist, /**< Index list from which the new index shall be removed. */ - int removenumber /**< Number of bound to be removed. */ - ); - -/** Swaps the indices of two constraints or bounds within the index set. - * \return SUCCESSFUL_RETURN \n - RET_SWAPINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_swapIndex( Bounds* _THIS, - Indexlist* const indexlist, /**< Index list in which the indices shold be swapped. */ - int number1, /**< Number of first bound. */ - int number2 /**< Number of second bound. */ - ); - - - -/* - * g e t N u m b e r O f T y p e - */ -static inline int Bounds_getNumberOfType( Bounds* _THIS, SubjectToType _type ) -{ - int i; - int numberOfType = 0; - - if ( _THIS->type != 0 ) - { - for( i=0; i<_THIS->n; ++i ) - if ( _THIS->type[i] == _type ) - ++numberOfType; - } - - return numberOfType; -} - - -/* - * g e t T y p e - */ -static inline SubjectToType Bounds_getType( Bounds* _THIS, int i ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - return _THIS->type[i]; - - return ST_UNKNOWN; -} - - -/* - * g e t S t a t u s - */ -static inline SubjectToStatus Bounds_getStatus( Bounds* _THIS, int i ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - return _THIS->status[i]; - - return ST_UNDEFINED; -} - - -/* - * s e t T y p e - */ -static inline returnValue Bounds_setType( Bounds* _THIS, int i, SubjectToType value ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - { - _THIS->type[i] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t S t a t u s - */ -static inline returnValue Bounds_setStatus( Bounds* _THIS, int i, SubjectToStatus value ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - { - _THIS->status[i] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t N o L o w e r - */ -static inline void Bounds_setNoLower( Bounds* _THIS, BooleanType _status ) -{ - _THIS->noLower = _status; -} - - -/* - * s e t N o U p p e r - */ -static inline void Bounds_setNoUpper( Bounds* _THIS, BooleanType _status ) -{ - _THIS->noUpper = _status; -} - - -/* - * h a s N o L o w e r - */ -static inline BooleanType Bounds_hasNoLower( Bounds* _THIS ) -{ - return _THIS->noLower; -} - - -/* - * h a s N o U p p p e r - */ -static inline BooleanType Bounds_hasNoUpper( Bounds* _THIS ) -{ - return _THIS->noUpper; -} - - - -/* - * g e t N V - */ -static inline int Bounds_getNV( Bounds* _THIS ) -{ - return _THIS->n; -} - - -/* - * g e t N F V - */ -static inline int Bounds_getNFV( Bounds* _THIS ) -{ - return Bounds_getNumberOfType( _THIS,ST_EQUALITY ); -} - - -/* - * g e t N B V - */ -static inline int Bounds_getNBV( Bounds* _THIS ) -{ - return Bounds_getNumberOfType( _THIS,ST_BOUNDED ); -} - - -/* - * g e t N U V - */ -static inline int Bounds_getNUV( Bounds* _THIS ) -{ - return Bounds_getNumberOfType( _THIS,ST_UNBOUNDED ); -} - - -/* - * g e t N F R - */ -static inline int Bounds_getNFR( Bounds* _THIS ) -{ - return Indexlist_getLength( _THIS->freee ); -} - - -/* - * g e t N F X - */ -static inline int Bounds_getNFX( Bounds* _THIS ) -{ - return Indexlist_getLength( _THIS->fixed ); -} - - -/* - * g e t F r e e - */ -static inline Indexlist* Bounds_getFree( Bounds* _THIS ) -{ - return _THIS->freee; -} - - -/* - * g e t F i x e d - */ -static inline Indexlist* Bounds_getFixed( Bounds* _THIS ) -{ - return _THIS->fixed; -} - - -END_NAMESPACE_QPOASES - -#endif /* QPOASES_BOUNDS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Constants.h b/third_party/acados/include/qpOASES_e/Constants.h deleted file mode 100644 index 13c777d75b83a3..00000000000000 --- a/third_party/acados/include/qpOASES_e/Constants.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Constants.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Definition of all global constants. - */ - - -#ifndef QPOASES_CONSTANTS_H -#define QPOASES_CONSTANTS_H - - -#include - -#ifdef __CODE_GENERATION__ - - #define CONVERTTOSTRINGAUX(x) #x - #define CONVERTTOSTRING(x) CONVERTTOSTRINGAUX(x) - - #ifndef QPOASES_CUSTOM_INTERFACE - #include "acado_qpoases3_interface.h" - #else - #include CONVERTTOSTRING(QPOASES_CUSTOM_INTERFACE) - #endif - -#endif - - -BEGIN_NAMESPACE_QPOASES - - -#ifndef __EXTERNAL_DIMENSIONS__ - - /*#define QPOASES_NVMAX 50 - #define QPOASES_NCMAX 100*/ - #define QPOASES_NVMAX 287 - #define QPOASES_NCMAX 709 - -#endif /* __EXTERNAL_DIMENSIONS__ */ - - -/** Maximum number of variables within a QP formulation. - * Note: this value has to be positive! */ -#define NVMAX QPOASES_NVMAX - -/** Maximum number of constraints within a QP formulation. - * Note: this value has to be positive! */ -#define NCMAX QPOASES_NCMAX - -#if ( QPOASES_NVMAX > QPOASES_NCMAX ) -#define NVCMAX QPOASES_NVMAX -#else -#define NVCMAX QPOASES_NCMAX -#endif - -#if ( QPOASES_NVMAX > QPOASES_NCMAX ) -#define NVCMIN QPOASES_NCMAX -#else -#define NVCMIN QPOASES_NVMAX -#endif - - -/** Maximum number of QPs in a sequence solved by means of the OQP interface. - * Note: this value has to be positive! */ -#define NQPMAX 1000 - - -/** Numerical value of machine precision (min eps, s.t. 1+eps > 1). - * Note: this value has to be positive! */ -#ifndef __CODE_GENERATION__ - - #ifdef __USE_SINGLE_PRECISION__ - static const real_t QPOASES_EPS = 1.193e-07; - #else - static const real_t QPOASES_EPS = 2.221e-16; - #endif /* __USE_SINGLE_PRECISION__ */ - -#endif /* __CODE_GENERATION__ */ - - -/** Numerical value of zero (for situations in which it would be - * unreasonable to compare with 0.0). - * Note: this value has to be positive! */ -static const real_t QPOASES_ZERO = 1.0e-25; - -/** Numerical value of infinity (e.g. for non-existing bounds). - * Note: this value has to be positive! */ -static const real_t QPOASES_INFTY = 1.0e20; - -/** Tolerance to used for isEqual, isZero etc. - * Note: this value has to be positive! */ -static const real_t QPOASES_TOL = 1.0e-25; - - -/** Maximum number of characters within a string. - * Note: this value should be at least 41! */ -#define QPOASES_MAX_STRING_LENGTH 160 - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_CONSTANTS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/ConstraintProduct.h b/third_party/acados/include/qpOASES_e/ConstraintProduct.h deleted file mode 100644 index eb5400c6cb91fa..00000000000000 --- a/third_party/acados/include/qpOASES_e/ConstraintProduct.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/ConstraintProduct.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches (thanks to D. Kwame Minde Kufoalor) - * \version 3.1embedded - * \date 2009-2015 - * - * Declaration of the ConstraintProduct interface which allows to specify a - * user-defined function for evaluating the constraint product at the - * current iterate to speed-up QP solution in case of a specially structured - * constraint matrix. - */ - - - -#ifndef QPOASES_CONSTRAINT_PRODUCT_H -#define QPOASES_CONSTRAINT_PRODUCT_H - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Interface for specifying user-defined evaluations of constraint products. - * - * An interface which allows to specify a user-defined function for evaluating the - * constraint product at the current iterate to speed-up QP solution in case - * of a specially structured constraint matrix. - * - * \author Hans Joachim Ferreau (thanks to Kwame Minde Kufoalor) - * \version 3.1embedded - * \date 2009-2015 - */ -typedef int(*ConstraintProduct)( int, const real_t* const, real_t* const ); - - -END_NAMESPACE_QPOASES - -#endif /* QPOASES_CONSTRAINT_PRODUCT_H */ diff --git a/third_party/acados/include/qpOASES_e/Constraints.h b/third_party/acados/include/qpOASES_e/Constraints.h deleted file mode 100644 index 8aca10d5d979a8..00000000000000 --- a/third_party/acados/include/qpOASES_e/Constraints.h +++ /dev/null @@ -1,535 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Constraints.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Constraints class designed to manage working sets of - * constraints within a QProblem. - */ - - -#ifndef QPOASES_CONSTRAINTS_H -#define QPOASES_CONSTRAINTS_H - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Manages working sets of constraints. - * - * This class manages working sets of constraints by storing - * index sets and other status information. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - Indexlist *active; /**< Index list of active constraints. */ - Indexlist *inactive; /**< Index list of inactive constraints. */ - - Indexlist *shiftedActive; /**< Memory for shifting active constraints. */ - Indexlist *shiftedInactive; /**< Memory for shifting inactive constraints. */ - - Indexlist *rotatedActive; /**< Memory for rotating active constraints. */ - Indexlist *rotatedInactive; /**< Memory for rotating inactive constraints. */ - - SubjectToType *type; /**< Type of constraints. */ - SubjectToStatus *status; /**< Status of constraints. */ - - SubjectToType *typeTmp; /**< Temp memory for type of constraints. */ - SubjectToStatus *statusTmp; /**< Temp memory for status of constraints. */ - - BooleanType noLower; /**< This flag indicates if there is no lower bound on any variable. */ - BooleanType noUpper; /**< This flag indicates if there is no upper bound on any variable. */ - - int n; /**< Total number of constraints. */ -} Constraints; - -int Constraints_calculateMemorySize( int n); - -char *Constraints_assignMemory(int n, Constraints **mem, void *raw_memory); - -Constraints *Constraints_createMemory( int n ); - -/** Constructor which takes the number of constraints. */ -void ConstraintsCON( Constraints* _THIS, - int _n /**< Number of constraints. */ - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void ConstraintsCPY( Constraints* FROM, - Constraints* TO - ); - - -/** Initialises object with given number of constraints. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_init( Constraints* _THIS, - int _n /**< Number of constraints. */ - ); - - -/** Initially adds number of a new (i.e. not yet in the list) constraint to - * a given index set. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_setupConstraint( Constraints* _THIS, - int number, /**< Number of new constraint. */ - SubjectToStatus _status /**< Status of new constraint. */ - ); - -/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to - * to the index set of inactive constraints; the order depends on the SujectToType - * of each index. Only disabled constraints are added to index set of disabled constraints! - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED */ -returnValue Constraints_setupAllInactive( Constraints* _THIS - ); - -/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to - * to the index set of active constraints (on their lower bounds); the order depends on the SujectToType - * of each index. Only disabled constraints are added to index set of disabled constraints! - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED */ -returnValue Constraints_setupAllLower( Constraints* _THIS - ); - -/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to - * to the index set of active constraints (on their upper bounds); the order depends on the SujectToType - * of each index. Only disabled constraints are added to index set of disabled constraints! - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED */ -returnValue Constraints_setupAllUpper( Constraints* _THIS - ); - - -/** Moves index of a constraint from index list of active to that of inactive constraints. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_CONSTRAINT_FAILED */ -returnValue Constraints_moveActiveToInactive( Constraints* _THIS, - int number /**< Number of constraint to become inactive. */ - ); - -/** Moves index of a constraint from index list of inactive to that of active constraints. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_CONSTRAINT_FAILED */ -returnValue Constraints_moveInactiveToActive( Constraints* _THIS, - int number, /**< Number of constraint to become active. */ - SubjectToStatus _status /**< Status of constraint to become active. */ - ); - -/** Flip fixed constraint. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_CONSTRAINT_FAILED \n - RET_INDEX_OUT_OF_BOUNDS */ -returnValue Constraints_flipFixed( Constraints* _THIS, - int number - ); - - -/** Returns the number of constraints. - * \return Number of constraints. */ -static inline int Constraints_getNC( Constraints* _THIS - ); - -/** Returns the number of implicit equality constraints. - * \return Number of implicit equality constraints. */ -static inline int Constraints_getNEC( Constraints* _THIS - ); - -/** Returns the number of "real" inequality constraints. - * \return Number of "real" inequality constraints. */ -static inline int Constraints_getNIC( Constraints* _THIS - ); - -/** Returns the number of unbounded constraints (i.e. without any bounds). - * \return Number of unbounded constraints (i.e. without any bounds). */ -static inline int Constraints_getNUC( Constraints* _THIS - ); - -/** Returns the number of active constraints. - * \return Number of active constraints. */ -static inline int Constraints_getNAC( Constraints* _THIS - ); - -/** Returns the number of inactive constraints. - * \return Number of inactive constraints. */ -static inline int Constraints_getNIAC( Constraints* _THIS - ); - - -/** Returns a pointer to active constraints index list. - * \return Pointer to active constraints index list. */ -static inline Indexlist* Constraints_getActive( Constraints* _THIS - ); - -/** Returns a pointer to inactive constraints index list. - * \return Pointer to inactive constraints index list. */ -static inline Indexlist* Constraints_getInactive( Constraints* _THIS - ); - - -/** Returns number of constraints with given SubjectTo type. - * \return Number of constraints with given type. */ -static inline int Constraints_getNumberOfType( Constraints* _THIS, - SubjectToType _type /**< Type of constraints' bound. */ - ); - - -/** Returns type of constraints' bound. - * \return Type of constraints' bound \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline SubjectToType Constraints_getType( Constraints* _THIS, - int i /**< Number of constraints' bound. */ - ); - -/** Returns status of constraints' bound. - * \return Status of constraints' bound \n - ST_UNDEFINED */ -static inline SubjectToStatus Constraints_getStatus( Constraints* _THIS, - int i /**< Number of constraints' bound. */ - ); - - -/** Sets type of constraints' bound. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue Constraints_setType( Constraints* _THIS, - int i, /**< Number of constraints' bound. */ - SubjectToType value /**< Type of constraints' bound. */ - ); - -/** Sets status of constraints' bound. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue Constraints_setStatus( Constraints* _THIS, - int i, /**< Number of constraints' bound. */ - SubjectToStatus value /**< Status of constraints' bound. */ - ); - - -/** Sets status of lower constraints' bounds. */ -static inline void Constraints_setNoLower( Constraints* _THIS, - BooleanType _status /**< Status of lower constraints' bounds. */ - ); - -/** Sets status of upper constraints' bounds. */ -static inline void Constraints_setNoUpper( Constraints* _THIS, - BooleanType _status /**< Status of upper constraints' bounds. */ - ); - - -/** Returns status of lower constraints' bounds. - * \return BT_TRUE if there is no lower constraints' bound on any variable. */ -static inline BooleanType Constraints_hasNoLower( Constraints* _THIS - ); - -/** Returns status of upper bounds. - * \return BT_TRUE if there is no upper constraints' bound on any variable. */ -static inline BooleanType Constraints_hasNoUpper( Constraints* _THIS - ); - - -/** Shifts forward type and status of all constraints by a given - * offset. This offset has to lie within the range [0,n/2] and has to - * be an integer divisor of the total number of constraints n. - * Type and status of the first \ constraints is thrown away, - * type and status of the last \ constraints is doubled, - * e.g. for offset = 2: \n - * shift( {c/b1,c/b2,c/b3,c/b4,c/b5,c/b6} ) = {c/b3,c/b4,c/b5,c/b6,c/b5,c/b6} - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_INVALID_ARGUMENTS \n - RET_SHIFTING_FAILED */ -returnValue Constraints_shift( Constraints* _THIS, - int offset /**< Shift offset within the range [0,n/2] and integer divisor of n. */ - ); - -/** Rotates forward type and status of all constraints by a given - * offset. This offset has to lie within the range [0,n]. - * Example for offset = 2: \n - * rotate( {c1,c2,c3,c4,c5,c6} ) = {c3,c4,c5,c6,c1,c2} - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_ROTATING_FAILED */ -returnValue Constraints_rotate( Constraints* _THIS, - int offset /**< Rotation offset within the range [0,n]. */ - ); - - -/** Prints information on constraints object - * (in particular, lists of inactive and active constraints. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue Constraints_print( Constraints* _THIS - ); - - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set corresponding to the desired status; - * the order depends on the SujectToType of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED */ -returnValue Constraints_setupAll( Constraints* _THIS, - SubjectToStatus _status /**< Desired initial status for all bounds. */ - ); - - -/** Adds the index of a new constraint to index set. - * \return SUCCESSFUL_RETURN \n - RET_ADDINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_addIndex( Constraints* _THIS, - Indexlist* const indexlist, /**< Index list to which the new index shall be added. */ - int newnumber, /**< Number of new constraint. */ - SubjectToStatus newstatus /**< Status of new constraint. */ - ); - -/** Removes the index of a constraint from index set. - * \return SUCCESSFUL_RETURN \n - RET_REMOVEINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_removeIndex( Constraints* _THIS, - Indexlist* const indexlist, /**< Index list from which the new index shall be removed. */ - int removenumber /**< Number of constraint to be removed. */ - ); - -/** Swaps the indices of two constraints or bounds within the index set. - * \return SUCCESSFUL_RETURN \n - RET_SWAPINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_swapIndex( Constraints* _THIS, - Indexlist* const indexlist, /**< Index list in which the indices shold be swapped. */ - int number1, /**< Number of first constraint. */ - int number2 /**< Number of second constraint. */ - ); - - - -/* - * g e t N u m b e r O f T y p e - */ -static inline int Constraints_getNumberOfType( Constraints* _THIS, SubjectToType _type ) -{ - int i; - int numberOfType = 0; - - if ( _THIS->type != 0 ) - { - for( i=0; i<_THIS->n; ++i ) - if ( _THIS->type[i] == _type ) - ++numberOfType; - } - - return numberOfType; -} - - -/* - * g e t T y p e - */ -static inline SubjectToType Constraints_getType( Constraints* _THIS, int i ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - return _THIS->type[i]; - - return ST_UNKNOWN; -} - - -/* - * g e t S t a t u s - */ -static inline SubjectToStatus Constraints_getStatus( Constraints* _THIS, int i ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - return _THIS->status[i]; - - return ST_UNDEFINED; -} - - -/* - * s e t T y p e - */ -static inline returnValue Constraints_setType( Constraints* _THIS, int i, SubjectToType value ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - { - _THIS->type[i] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t S t a t u s - */ -static inline returnValue Constraints_setStatus( Constraints* _THIS, int i, SubjectToStatus value ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - { - _THIS->status[i] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t N o L o w e r - */ -static inline void Constraints_setNoLower( Constraints* _THIS, BooleanType _status ) -{ - _THIS->noLower = _status; -} - - -/* - * s e t N o U p p e r - */ -static inline void Constraints_setNoUpper( Constraints* _THIS, BooleanType _status ) -{ - _THIS->noUpper = _status; -} - - -/* - * h a s N o L o w e r - */ -static inline BooleanType Constraints_hasNoLower( Constraints* _THIS ) -{ - return _THIS->noLower; -} - - -/* - * h a s N o U p p p e r - */ -static inline BooleanType Constraints_hasNoUpper( Constraints* _THIS ) -{ - return _THIS->noUpper; -} - - - -/* - * g e t N C - */ -static inline int Constraints_getNC( Constraints* _THIS ) -{ - return _THIS->n; -} - - -/* - * g e t N E C - */ -static inline int Constraints_getNEC( Constraints* _THIS ) -{ - return Constraints_getNumberOfType( _THIS,ST_EQUALITY ); -} - - -/* - * g e t N I C - */ -static inline int Constraints_getNIC( Constraints* _THIS ) -{ - return Constraints_getNumberOfType( _THIS,ST_BOUNDED ); -} - - -/* - * g e t N U C - */ -static inline int Constraints_getNUC( Constraints* _THIS ) -{ - return Constraints_getNumberOfType( _THIS,ST_UNBOUNDED ); -} - - -/* - * g e t N A C - */ -static inline int Constraints_getNAC( Constraints* _THIS ) -{ - return Indexlist_getLength( _THIS->active ); -} - - -/* - * g e t N I A C - */ -static inline int Constraints_getNIAC( Constraints* _THIS ) -{ - return Indexlist_getLength( _THIS->inactive ); -} - - - -/* - * g e t A c t i v e - */ -static inline Indexlist* Constraints_getActive( Constraints* _THIS ) -{ - return _THIS->active; -} - - -/* - * g e t I n a c t i v e - */ -static inline Indexlist* Constraints_getInactive( Constraints* _THIS ) -{ - return _THIS->inactive; -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_CONSTRAINTS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Flipper.h b/third_party/acados/include/qpOASES_e/Flipper.h deleted file mode 100644 index 63526a30f368e4..00000000000000 --- a/third_party/acados/include/qpOASES_e/Flipper.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Flipper.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Options class designed to manage user-specified - * options for solving a QProblem. - */ - - -#ifndef QPOASES_FLIPPER_H -#define QPOASES_FLIPPER_H - - -#include -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Auxiliary class for storing a copy of the current matrix factorisations. - * - * This auxiliary class stores a copy of the current matrix factorisations. It - * is used by the classe QProblemB and QProblem in case flipping bounds are enabled. - * - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - Bounds *bounds; /**< Data structure for problem's bounds. */ - Constraints *constraints; /**< Data structure for problem's constraints. */ - - real_t *R; /**< Cholesky factor of H (i.e. H = R^T*R). */ - real_t *Q; /**< Orthonormal quadratic matrix, A = [0 T]*Q'. */ - real_t *T; /**< Reverse triangular matrix, A = [0 T]*Q'. */ - - unsigned int nV; /**< Number of variables. */ - unsigned int nC; /**< Number of constraints. */ -} Flipper; - -int Flipper_calculateMemorySize( unsigned int nV, unsigned int nC ); - -char *Flipper_assignMemory( unsigned int nV, unsigned int nC, Flipper **mem, void *raw_memory ); - -Flipper *Flipper_createMemory( unsigned int nV, unsigned int nC ); - -/** Constructor which takes the number of bounds and constraints. */ -void FlipperCON( Flipper* _THIS, - unsigned int _nV, /**< Number of bounds. */ - unsigned int _nC /**< Number of constraints. */ - ); - -/** Copy constructor (deep copy). */ -void FlipperCPY( Flipper* FROM, - Flipper* TO - ); - -/** Initialises object with given number of bounds and constraints. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue Flipper_init( Flipper* _THIS, - unsigned int _nV, /**< Number of bounds. */ - unsigned int _nC /**< Number of constraints. */ - ); - - -/** Copies current values to non-null arguments (assumed to be allocated with consistent size). - * \return SUCCESSFUL_RETURN */ -returnValue Flipper_get( Flipper* _THIS, - Bounds* const _bounds, /**< Pointer to new bounds. */ - real_t* const R, /**< New matrix R. */ - Constraints* const _constraints, /**< Pointer to new constraints. */ - real_t* const _Q, /**< New matrix Q. */ - real_t* const _T /**< New matrix T. */ - ); - -/** Assigns new values to non-null arguments. - * \return SUCCESSFUL_RETURN */ -returnValue Flipper_set( Flipper* _THIS, - const Bounds* const _bounds, /**< Pointer to new bounds. */ - const real_t* const _R, /**< New matrix R. */ - const Constraints* const _constraints, /**< Pointer to new constraints. */ - const real_t* const _Q, /**< New matrix Q. */ - const real_t* const _T /**< New matrix T. */ - ); - -/** Returns dimension of matrix T. - * \return Dimension of matrix T. */ -unsigned int Flipper_getDimT( Flipper* _THIS ); - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_FLIPPER_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Indexlist.h b/third_party/acados/include/qpOASES_e/Indexlist.h deleted file mode 100644 index 02d259d63d03db..00000000000000 --- a/third_party/acados/include/qpOASES_e/Indexlist.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Indexlist.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Indexlist class designed to manage index lists of - * constraints and bounds within a SubjectTo object. - */ - - -#ifndef QPOASES_INDEXLIST_H -#define QPOASES_INDEXLIST_H - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Stores and manages index lists. - * - * This class manages index lists of active/inactive bounds/constraints. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - int *number; /**< Array to store numbers of constraints or bounds. */ - int *iSort; /**< Index list to sort vector \a number */ - - int length; /**< Length of index list. */ - int first; /**< Physical index of first element. */ - int last; /**< Physical index of last element. */ - int lastusedindex; /**< Physical index of last entry in index list. */ - int physicallength; /**< Physical length of index list. */ -} Indexlist; - -int Indexlist_calculateMemorySize( int n); - -char *Indexlist_assignMemory(int n, Indexlist **mem, void *raw_memory); - -Indexlist *Indexlist_createMemory( int n ); - -/** Constructor which takes the desired physical length of the index list. */ -void IndexlistCON( Indexlist* _THIS, - int n /**< Physical length of index list. */ - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void IndexlistCPY( Indexlist* FROM, - Indexlist* TO - ); - -/** Initialises index list of desired physical length. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue Indexlist_init( Indexlist* _THIS, - int n /**< Physical length of index list. */ - ); - -/** Creates an array of all numbers within the index set in correct order. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue Indexlist_getNumberArray( Indexlist* _THIS, - int** const numberarray /**< Output: Array of numbers (NULL on error). */ - ); - -/** Creates an array of all numbers within the index set in correct order. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue Indexlist_getISortArray( Indexlist* _THIS, - int** const iSortArray /**< Output: iSort Array. */ - ); - - -/** Determines the index within the index list at which a given number is stored. - * \return >= 0: Index of given number. \n - -1: Number not found. */ -int Indexlist_getIndex( Indexlist* _THIS, - int givennumber /**< Number whose index shall be determined. */ - ); - -/** Returns the number stored at a given physical index. - * \return >= 0: Number stored at given physical index. \n - -RET_INDEXLIST_OUTOFBOUNDS */ -static inline int Indexlist_getNumber( Indexlist* _THIS, - int physicalindex /**< Physical index of the number to be returned. */ - ); - - -/** Returns the current length of the index list. - * \return Current length of the index list. */ -static inline int Indexlist_getLength( Indexlist* _THIS - ); - -/** Returns last number within the index list. - * \return Last number within the index list. */ -static inline int Indexlist_getLastNumber( Indexlist* _THIS - ); - - -/** Adds number to index list. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_MUST_BE_REORDERD \n - RET_INDEXLIST_EXCEEDS_MAX_LENGTH */ -returnValue Indexlist_addNumber( Indexlist* _THIS, - int addnumber /**< Number to be added. */ - ); - -/** Removes number from index list. - * \return SUCCESSFUL_RETURN */ -returnValue Indexlist_removeNumber( Indexlist* _THIS, - int removenumber /**< Number to be removed. */ - ); - -/** Swaps two numbers within index list. - * \return SUCCESSFUL_RETURN */ -returnValue Indexlist_swapNumbers( Indexlist* _THIS, - int number1, /**< First number for swapping. */ - int number2 /**< Second number for swapping. */ - ); - -/** Determines if a given number is contained in the index set. - * \return BT_TRUE iff number is contain in the index set */ -static inline BooleanType Indexlist_isMember( Indexlist* _THIS, - int _number /**< Number to be tested for membership. */ - ); - - -/** Find first index j between -1 and length in sorted list of indices - * iSort such that numbers[iSort[j]] <= i < numbers[iSort[j+1]]. Uses - * bisection. - * \return j. */ -int Indexlist_findInsert( Indexlist* _THIS, - int i - ); - - - -/* - * g e t N u m b e r - */ -static inline int Indexlist_getNumber( Indexlist* _THIS, int physicalindex ) -{ - /* consistency check */ - if ( ( physicalindex < 0 ) || ( physicalindex > _THIS->length ) ) - return -RET_INDEXLIST_OUTOFBOUNDS; - - return _THIS->number[physicalindex]; -} - - -/* - * g e t L e n g t h - */ -static inline int Indexlist_getLength( Indexlist* _THIS ) -{ - return _THIS->length; -} - - -/* - * g e t L a s t N u m b e r - */ -static inline int Indexlist_getLastNumber( Indexlist* _THIS ) -{ - return _THIS->number[_THIS->length-1]; -} - - -/* - * g e t L a s t N u m b e r - */ -static inline BooleanType Indexlist_isMember( Indexlist* _THIS, int _number ) -{ - if ( Indexlist_getIndex( _THIS,_number ) >= 0 ) - return BT_TRUE; - else - return BT_FALSE; -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_INDEXLIST_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Matrices.h b/third_party/acados/include/qpOASES_e/Matrices.h deleted file mode 100644 index e2a46b3a9daeda..00000000000000 --- a/third_party/acados/include/qpOASES_e/Matrices.h +++ /dev/null @@ -1,287 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Matrices.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2009-2015 - * - * Various matrix classes: Abstract base matrix class, dense and sparse matrices, - * including symmetry exploiting specializations. - */ - - - -#ifndef QPOASES_MATRICES_H -#define QPOASES_MATRICES_H - -#ifdef __USE_SINGLE_PRECISION__ - - // single precision - #define GEMM sgemm_ - #define GEMV sgemv_ -// #define SYR ssyr_ -// #define SYR2 ssyr2_ - #define POTRF spotrf_ - -#else - - // double precision - #define GEMM dgemm_ - #define GEMV dgemv_ -// #define SYR dsyr_ -// #define SYR2 dsyr2_ - #define POTRF dpotrf_ - -#endif /* __USE_SINGLE_PRECISION__ */ - - -#ifdef EXTERNAL_BLAS - // double precision - void dgemm_(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int ldb, double *beta, double *C, int *ldc); - void dgemv_(char *ta, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); - void dpotrf_(char *uplo, int *m, double *A, int *lda, int *info); - // single precision - void sgemm_(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int ldb, float *beta, float *C, int *ldc); - void sgemv_(char *ta, int *m, int *n, float *alpha, float *A, int *lda, float *x, int *incx, float *beta, float *y, int *incy); - void spotrf_(char *uplo, int *m, float *A, int *lda, int *info); -#else - /** Performs one of the matrix-matrix operation in double precision. */ - void dgemm_ ( const char*, const char*, const unsigned long*, const unsigned long*, const unsigned long*, - const double*, const double*, const unsigned long*, const double*, const unsigned long*, - const double*, double*, const unsigned long* ); - /** Performs one of the matrix-matrix operation in single precision. */ - void sgemm_ ( const char*, const char*, const unsigned long*, const unsigned long*, const unsigned long*, - const float*, const float*, const unsigned long*, const float*, const unsigned long*, - const float*, float*, const unsigned long* ); - - /** Calculates the Cholesky factorization of a real symmetric positive definite matrix in double precision. */ - void dpotrf_ ( const char *, const unsigned long *, double *, const unsigned long *, long * ); - /** Calculates the Cholesky factorization of a real symmetric positive definite matrix in single precision. */ - void spotrf_ ( const char *, const unsigned long *, float *, const unsigned long *, long * ); - -#endif - - /** Performs a symmetric rank 1 operation in double precision. */ -// void dsyr_ ( const char *, const unsigned long *, const double *, const double *, -// const unsigned long *, double *, const unsigned long *); - /** Performs a symmetric rank 1 operation in single precision. */ -// void ssyr_ ( const char *, const unsigned long *, const float *, const float *, -// const unsigned long *, float *, const unsigned long *); - - /** Performs a symmetric rank 2 operation in double precision. */ -// void dsyr2_ ( const char *, const unsigned long *, const double *, const double *, -// const unsigned long *, const double *, const unsigned long *, double *, const unsigned long *); - /** Performs a symmetric rank 2 operation in single precision. */ -// void ssyr2_ ( const char *, const unsigned long *, const float *, const float *, -// const unsigned long *, const float *, const unsigned long *, float *, const unsigned long *); - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Interfaces matrix-vector operations tailored to general dense matrices. - * - * Dense matrix class (row major format). - * - * \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau - * \version 3.1embedded - * \date 2011-2015 - */ -typedef struct -{ - real_t *val; /**< Vector of entries. */ - int nRows; /**< Number of rows. */ - int nCols; /**< Number of columns. */ - int leaDim; /**< Leading dimension. */ -} DenseMatrix; - -int DenseMatrix_calculateMemorySize( int m, int n ); - -char *DenseMatrix_assignMemory( int m, int n, DenseMatrix **mem, void *raw_memory ); - -DenseMatrix *DenseMatrix_createMemory( int m, int n ); - -/** Constructor from vector of values. - * Caution: Data pointer must be valid throughout lifetime - */ -void DenseMatrixCON( DenseMatrix* _THIS, - int m, /**< Number of rows. */ - int n, /**< Number of columns. */ - int lD, /**< Leading dimension. */ - real_t *v /**< Values. */ - ); - -void DenseMatrixCPY( DenseMatrix* FROM, - DenseMatrix* TO - ); - - -/** Frees all internal memory. */ -void DenseMatrix_free( DenseMatrix* _THIS ); - -/** Constructor from vector of values. - * Caution: Data pointer must be valid throughout lifetime - */ -returnValue DenseMatrix_init( DenseMatrix* _THIS, - int m, /**< Number of rows. */ - int n, /**< Number of columns. */ - int lD, /**< Leading dimension. */ - real_t *v /**< Values. */ - ); - - -/** Returns i-th diagonal entry. - * \return i-th diagonal entry */ -real_t DenseMatrix_diag( DenseMatrix* _THIS, - int i /**< Index. */ - ); - -/** Checks whether matrix is square and diagonal. - * \return BT_TRUE iff matrix is square and diagonal; \n - * BT_FALSE otherwise. */ -BooleanType DenseMatrix_isDiag( DenseMatrix* _THIS ); - -/** Get the N-norm of the matrix - * \return N-norm of the matrix - */ -real_t DenseMatrix_getNorm( DenseMatrix* _THIS, - int type /**< Norm type, 1: one-norm, 2: Euclidean norm. */ - ); - -/** Get the N-norm of a row - * \return N-norm of row \a rNum - */ -real_t DenseMatrix_getRowNorm( DenseMatrix* _THIS, - int rNum, /**< Row number. */ - int type /**< Norm type, 1: one-norm, 2: Euclidean norm. */ - ); - -/** Retrieve indexed entries of matrix row multiplied by alpha. - * \return SUCCESSFUL_RETURN */ -returnValue DenseMatrix_getRow( DenseMatrix* _THIS, - int rNum, /**< Row number. */ - const Indexlist* const icols, /**< Index list specifying columns. */ - real_t alpha, /**< Scalar factor. */ - real_t *row /**< Output row vector. */ - ); - -/** Retrieve indexed entries of matrix column multiplied by alpha. - * \return SUCCESSFUL_RETURN */ - returnValue DenseMatrix_getCol( DenseMatrix* _THIS, - int cNum, /**< Column number. */ - const Indexlist* const irows, /**< Index list specifying rows. */ - real_t alpha, /**< Scalar factor. */ - real_t *col /**< Output column vector. */ - ); - -/** Evaluate Y=alpha*A*X + beta*Y. - * \return SUCCESSFUL_RETURN. */ -returnValue DenseMatrix_times( DenseMatrix* _THIS, - int xN, /**< Number of vectors to multiply. */ - real_t alpha, /**< Scalar factor for matrix vector product. */ - const real_t *x, /**< Input vector to be multiplied. */ - int xLD, /**< Leading dimension of input x. */ - real_t beta, /**< Scalar factor for y. */ - real_t *y, /**< Output vector of results. */ - int yLD /**< Leading dimension of output y. */ - ); - -/** Evaluate Y=alpha*A'*X + beta*Y. - * \return SUCCESSFUL_RETURN. */ -returnValue DenseMatrix_transTimes( DenseMatrix* _THIS, - int xN, /**< Number of vectors to multiply. */ - real_t alpha, /**< Scalar factor for matrix vector product. */ - const real_t *x, /**< Input vector to be multiplied. */ - int xLD, /**< Leading dimension of input x. */ - real_t beta, /**< Scalar factor for y. */ - real_t *y, /**< Output vector of results. */ - int yLD /**< Leading dimension of output y. */ - ); - -/** Evaluate matrix vector product with submatrix given by Indexlist. - * \return SUCCESSFUL_RETURN */ - returnValue DenseMatrix_subTimes( DenseMatrix* _THIS, - const Indexlist* const irows, /**< Index list specifying rows. */ - const Indexlist* const icols, /**< Index list specifying columns. */ - int xN, /**< Number of vectors to multiply. */ - real_t alpha, /**< Scalar factor for matrix vector product. */ - const real_t *x, /**< Input vector to be multiplied. */ - int xLD, /**< Leading dimension of input x. */ - real_t beta, /**< Scalar factor for y. */ - real_t *y, /**< Output vector of results. */ - int yLD, /**< Leading dimension of output y. */ - BooleanType yCompr /**< Compressed storage for y. */ - ); - -/** Evaluate matrix transpose vector product. - * \return SUCCESSFUL_RETURN */ -returnValue DenseMatrix_subTransTimes( DenseMatrix* _THIS, - const Indexlist* const irows, /**< Index list specifying rows. */ - const Indexlist* const icols, /**< Index list specifying columns. */ - int xN, /**< Number of vectors to multiply. */ - real_t alpha, /**< Scalar factor for matrix vector product. */ - const real_t *x, /**< Input vector to be multiplied. */ - int xLD, /**< Leading dimension of input x. */ - real_t beta, /**< Scalar factor for y. */ - real_t *y, /**< Output vector of results. */ - int yLD /**< Leading dimension of output y. */ - ); - -/** Adds given offset to diagonal of matrix. - * \return SUCCESSFUL_RETURN \n - RET_NO_DIAGONAL_AVAILABLE */ -returnValue DenseMatrix_addToDiag( DenseMatrix* _THIS, - real_t alpha /**< Diagonal offset. */ - ); - -/** Prints matrix to screen. - * \return SUCCESSFUL_RETURN */ -returnValue DenseMatrix_print( DenseMatrix* _THIS - ); - -static inline real_t* DenseMatrix_getVal( DenseMatrix* _THIS ) { return _THIS->val; } - -/** Compute bilinear form y = x'*H*x using submatrix given by index list. - * \return SUCCESSFUL_RETURN */ -returnValue DenseMatrix_bilinear( DenseMatrix* _THIS, - const Indexlist* const icols, /**< Index list specifying columns of x. */ - int xN, /**< Number of vectors to multiply. */ - const real_t *x, /**< Input vector to be multiplied (uncompressed). */ - int xLD, /**< Leading dimension of input x. */ - real_t *y, /**< Output vector of results (compressed). */ - int yLD /**< Leading dimension of output y. */ - ); - - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_MATRICES_H */ diff --git a/third_party/acados/include/qpOASES_e/MessageHandling.h b/third_party/acados/include/qpOASES_e/MessageHandling.h deleted file mode 100644 index fe5524948a8b2c..00000000000000 --- a/third_party/acados/include/qpOASES_e/MessageHandling.h +++ /dev/null @@ -1,544 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/MessageHandling.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches (thanks to Leonard Wirsching) - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the MessageHandling class including global return values. - */ - - -#ifndef QPOASES_MESSAGEHANDLING_H -#define QPOASES_MESSAGEHANDLING_H - - -#include -#include -#include -#include - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** Default file to display messages. */ -#define stdFile stderr - - -/** - * \brief Defines all symbols for global return values. - * - * The enumeration returnValueType defines all symbols for global return values. - * Important: All return values are assumed to be nonnegative! - * - * \author Hans Joachim Ferreau - */ -typedef enum -{ -TERMINAL_LIST_ELEMENT = -1, /**< Terminal list element, internal usage only! */ -/* miscellaneous */ -SUCCESSFUL_RETURN = 0, /**< Successful return. */ -RET_DIV_BY_ZERO, /**< Division by zero. */ -RET_INDEX_OUT_OF_BOUNDS, /**< Index out of bounds. */ -RET_INVALID_ARGUMENTS, /**< At least one of the arguments is invalid. */ -RET_ERROR_UNDEFINED, /**< Error number undefined. */ -RET_WARNING_UNDEFINED, /**< Warning number undefined. */ -RET_INFO_UNDEFINED, /**< Info number undefined. */ -RET_EWI_UNDEFINED, /**< Error/warning/info number undefined. */ -RET_AVAILABLE_WITH_LINUX_ONLY, /**< This function is available under Linux only. */ -RET_UNKNOWN_BUG, /**< The error occurred is not yet known. */ -RET_PRINTLEVEL_CHANGED, /**< Print level changed. (10) */ -RET_NOT_YET_IMPLEMENTED, /**< Requested function is not yet implemented in this version of qpOASES. */ -/* Indexlist */ -RET_INDEXLIST_MUST_BE_REORDERD, /**< Index list has to be reordered. */ -RET_INDEXLIST_EXCEEDS_MAX_LENGTH, /**< Index list exceeds its maximal physical length. */ -RET_INDEXLIST_CORRUPTED, /**< Index list corrupted. */ -RET_INDEXLIST_OUTOFBOUNDS, /**< Physical index is out of bounds. */ -RET_INDEXLIST_ADD_FAILED, /**< Adding indices from another index set failed. */ -RET_INDEXLIST_INTERSECT_FAILED, /**< Intersection with another index set failed. */ -/* SubjectTo / Bounds / Constraints */ -RET_INDEX_ALREADY_OF_DESIRED_STATUS, /**< Index is already of desired status. (18) */ -RET_ADDINDEX_FAILED, /**< Adding index to index set failed. */ -RET_REMOVEINDEX_FAILED, /**< Removing index from index set failed. (20) */ -RET_SWAPINDEX_FAILED, /**< Cannot swap between different indexsets. */ -RET_NOTHING_TO_DO, /**< Nothing to do. */ -RET_SETUP_BOUND_FAILED, /**< Setting up bound index failed. */ -RET_SETUP_CONSTRAINT_FAILED, /**< Setting up constraint index failed. */ -RET_MOVING_BOUND_FAILED, /**< Moving bound between index sets failed. */ -RET_MOVING_CONSTRAINT_FAILED, /**< Moving constraint between index sets failed. */ -RET_SHIFTING_FAILED, /**< Shifting of bounds/constraints failed. */ -RET_ROTATING_FAILED, /**< Rotating of bounds/constraints failed. */ -/* QProblem */ -RET_QPOBJECT_NOT_SETUP, /**< The QP object has not been setup correctly, use another constructor. */ -RET_QP_ALREADY_INITIALISED, /**< QProblem has already been initialised. (30) */ -RET_NO_INIT_WITH_STANDARD_SOLVER, /**< Initialisation via extern QP solver is not yet implemented. */ -RET_RESET_FAILED, /**< Reset failed. */ -RET_INIT_FAILED, /**< Initialisation failed. */ -RET_INIT_FAILED_TQ, /**< Initialisation failed due to TQ factorisation. */ -RET_INIT_FAILED_CHOLESKY, /**< Initialisation failed due to Cholesky decomposition. */ -RET_INIT_FAILED_HOTSTART, /**< Initialisation failed! QP could not be solved! */ -RET_INIT_FAILED_INFEASIBILITY, /**< Initial QP could not be solved due to infeasibility! */ -RET_INIT_FAILED_UNBOUNDEDNESS, /**< Initial QP could not be solved due to unboundedness! */ -RET_INIT_FAILED_REGULARISATION, /**< Initialisation failed as Hessian matrix could not be regularised. */ -RET_INIT_SUCCESSFUL, /**< Initialisation done. (40) */ -RET_OBTAINING_WORKINGSET_FAILED, /**< Failed to obtain working set for auxiliary QP. */ -RET_SETUP_WORKINGSET_FAILED, /**< Failed to setup working set for auxiliary QP. */ -RET_SETUP_AUXILIARYQP_FAILED, /**< Failed to setup auxiliary QP for initialised homotopy. */ -RET_NO_CHOLESKY_WITH_INITIAL_GUESS, /**< Externally computed Cholesky factor cannot be combined with an initial guess. */ -RET_NO_EXTERN_SOLVER, /**< No extern QP solver available. */ -RET_QP_UNBOUNDED, /**< QP is unbounded. */ -RET_QP_INFEASIBLE, /**< QP is infeasible. */ -RET_QP_NOT_SOLVED, /**< Problems occurred while solving QP with standard solver. */ -RET_QP_SOLVED, /**< QP successfully solved. */ -RET_UNABLE_TO_SOLVE_QP, /**< Problems occurred while solving QP. (50) */ -RET_INITIALISATION_STARTED, /**< Starting problem initialisation... */ -RET_HOTSTART_FAILED, /**< Unable to perform homotopy due to internal error. */ -RET_HOTSTART_FAILED_TO_INIT, /**< Unable to initialise problem. */ -RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED, /**< Unable to perform homotopy as previous QP is not solved. */ -RET_ITERATION_STARTED, /**< Iteration... */ -RET_SHIFT_DETERMINATION_FAILED, /**< Determination of shift of the QP data failed. */ -RET_STEPDIRECTION_DETERMINATION_FAILED, /**< Determination of step direction failed. */ -RET_STEPLENGTH_DETERMINATION_FAILED, /**< Determination of step direction failed. */ -RET_OPTIMAL_SOLUTION_FOUND, /**< Optimal solution of neighbouring QP found. */ -RET_HOMOTOPY_STEP_FAILED, /**< Unable to perform homotopy step. (60) */ -RET_HOTSTART_STOPPED_INFEASIBILITY, /**< Premature homotopy termination because QP is infeasible. */ -RET_HOTSTART_STOPPED_UNBOUNDEDNESS, /**< Premature homotopy termination because QP is unbounded. */ -RET_WORKINGSET_UPDATE_FAILED, /**< Unable to update working sets according to initial guesses. */ -RET_MAX_NWSR_REACHED, /**< Maximum number of working set recalculations performed. */ -RET_CONSTRAINTS_NOT_SPECIFIED, /**< Problem does comprise constraints! You also have to specify new constraints' bounds. */ -RET_INVALID_FACTORISATION_FLAG, /**< Invalid factorisation flag. */ -RET_UNABLE_TO_SAVE_QPDATA, /**< Unable to save QP data. */ -RET_STEPDIRECTION_FAILED_TQ, /**< Abnormal termination due to TQ factorisation. */ -RET_STEPDIRECTION_FAILED_CHOLESKY, /**< Abnormal termination due to Cholesky factorisation. */ -RET_CYCLING_DETECTED, /**< Cycling detected. (70) */ -RET_CYCLING_NOT_RESOLVED, /**< Cycling cannot be resolved, QP probably infeasible. */ -RET_CYCLING_RESOLVED, /**< Cycling probably resolved. */ -RET_STEPSIZE, /**< For displaying performed stepsize. */ -RET_STEPSIZE_NONPOSITIVE, /**< For displaying non-positive stepsize. */ -RET_SETUPSUBJECTTOTYPE_FAILED, /**< Setup of SubjectToTypes failed. */ -RET_ADDCONSTRAINT_FAILED, /**< Addition of constraint to working set failed. */ -RET_ADDCONSTRAINT_FAILED_INFEASIBILITY, /**< Addition of constraint to working set failed (due to QP infeasibility). */ -RET_ADDBOUND_FAILED, /**< Addition of bound to working set failed. */ -RET_ADDBOUND_FAILED_INFEASIBILITY, /**< Addition of bound to working set failed (due to QP infeasibility). */ -RET_REMOVECONSTRAINT_FAILED, /**< Removal of constraint from working set failed. (80) */ -RET_REMOVEBOUND_FAILED, /**< Removal of bound from working set failed. */ -RET_REMOVE_FROM_ACTIVESET, /**< Removing from active set... */ -RET_ADD_TO_ACTIVESET, /**< Adding to active set... */ -RET_REMOVE_FROM_ACTIVESET_FAILED, /**< Removing from active set failed. */ -RET_ADD_TO_ACTIVESET_FAILED, /**< Adding to active set failed. */ -RET_CONSTRAINT_ALREADY_ACTIVE, /**< Constraint is already active. */ -RET_ALL_CONSTRAINTS_ACTIVE, /**< All constraints are active, no further constraint can be added. */ -RET_LINEARLY_DEPENDENT, /**< New bound/constraint is linearly dependent. */ -RET_LINEARLY_INDEPENDENT, /**< New bound/constraint is linearly independent. */ -RET_LI_RESOLVED, /**< Linear independence of active constraint matrix successfully resolved. (90) */ -RET_ENSURELI_FAILED, /**< Failed to ensure linear independence of active constraint matrix. */ -RET_ENSURELI_FAILED_TQ, /**< Abnormal termination due to TQ factorisation. */ -RET_ENSURELI_FAILED_NOINDEX, /**< QP is infeasible. */ -RET_ENSURELI_FAILED_CYCLING, /**< QP is infeasible. */ -RET_BOUND_ALREADY_ACTIVE, /**< Bound is already active. */ -RET_ALL_BOUNDS_ACTIVE, /**< All bounds are active, no further bound can be added. */ -RET_CONSTRAINT_NOT_ACTIVE, /**< Constraint is not active. */ -RET_BOUND_NOT_ACTIVE, /**< Bound is not active. */ -RET_HESSIAN_NOT_SPD, /**< Projected Hessian matrix not positive definite. */ -RET_HESSIAN_INDEFINITE, /**< Hessian matrix is indefinite. (100) */ -RET_MATRIX_SHIFT_FAILED, /**< Unable to update matrices or to transform vectors. */ -RET_MATRIX_FACTORISATION_FAILED, /**< Unable to calculate new matrix factorisations. */ -RET_PRINT_ITERATION_FAILED, /**< Unable to print information on current iteration. */ -RET_NO_GLOBAL_MESSAGE_OUTPUTFILE, /**< No global message output file initialised. */ -RET_DISABLECONSTRAINTS_FAILED, /**< Unable to disbable constraints. */ -RET_ENABLECONSTRAINTS_FAILED, /**< Unable to enbable constraints. */ -RET_ALREADY_ENABLED, /**< Bound or constraint is already enabled. */ -RET_ALREADY_DISABLED, /**< Bound or constraint is already disabled. */ -RET_NO_HESSIAN_SPECIFIED, /**< No Hessian matrix has been specified. */ -RET_USING_REGULARISATION, /**< Using regularisation as Hessian matrix is not positive definite. (110) */ -RET_EPS_MUST_BE_POSITVE, /**< Eps for regularisation must be sufficiently positive. */ -RET_REGSTEPS_MUST_BE_POSITVE, /**< Maximum number of regularisation steps must be non-negative. */ -RET_HESSIAN_ALREADY_REGULARISED, /**< Hessian has been already regularised. */ -RET_CANNOT_REGULARISE_IDENTITY, /**< Identity Hessian matrix cannot be regularised. */ -RET_CANNOT_REGULARISE_SPARSE, /**< Sparse matrix cannot be regularised as diagonal entry is missing. */ -RET_NO_REGSTEP_NWSR, /**< No additional regularisation step could be performed due to limits. */ -RET_FEWER_REGSTEPS_NWSR, /**< Fewer additional regularisation steps have been performed due to limits. */ -RET_CHOLESKY_OF_ZERO_HESSIAN, /**< Cholesky decomposition of (unregularised) zero Hessian matrix. */ -RET_ZERO_HESSIAN_ASSUMED, /**< Zero Hessian matrix assumed as null pointer passed without specifying hessianType. */ -RET_CONSTRAINTS_ARE_NOT_SCALED, /**< (no longer in use) (120) */ -RET_INITIAL_BOUNDS_STATUS_NYI, /**< (no longer in use) */ -RET_ERROR_IN_CONSTRAINTPRODUCT, /**< Error in user-defined constraint product function. */ -RET_FIX_BOUNDS_FOR_LP, /**< All initial bounds must be fixed when solving an (unregularised) LP. */ -RET_USE_REGULARISATION_FOR_LP, /**< Set options.enableRegularisation=BT_TRUE for solving LPs. */ -/* SQProblem */ -RET_UPDATEMATRICES_FAILED, /**< Unable to update QP matrices. */ -RET_UPDATEMATRICES_FAILED_AS_QP_NOT_SOLVED, /**< Unable to update matrices as previous QP is not solved. */ -/* Utils */ -RET_UNABLE_TO_OPEN_FILE, /**< Unable to open file. */ -RET_UNABLE_TO_WRITE_FILE, /**< Unable to write into file. */ -RET_UNABLE_TO_READ_FILE, /**< Unable to read from file. */ -RET_FILEDATA_INCONSISTENT, /**< File contains inconsistent data. (130) */ -/* Options */ -RET_OPTIONS_ADJUSTED, /**< Options needed to be adjusted for consistency reasons. */ -/* SolutionAnalysis */ -RET_UNABLE_TO_ANALYSE_QPROBLEM, /**< Unable to analyse (S)QProblem(B) object. */ -/* Benchmark */ -RET_NWSR_SET_TO_ONE, /**< Maximum number of working set changes was set to 1. */ -RET_UNABLE_TO_READ_BENCHMARK, /**< Unable to read benchmark data. */ -RET_BENCHMARK_ABORTED, /**< Benchmark aborted. */ -RET_INITIAL_QP_SOLVED, /**< Initial QP solved. */ -RET_QP_SOLUTION_STARTED, /**< Solving QP... */ -RET_BENCHMARK_SUCCESSFUL, /**< Benchmark terminated successfully. */ -/* Sparse matrices */ -RET_NO_DIAGONAL_AVAILABLE, /**< Sparse matrix does not have entries on full diagonal. */ -RET_DIAGONAL_NOT_INITIALISED, /**< Diagonal data of sparse matrix has not been initialised. (140) */ -/* Dropping of infeasible constraints */ -RET_ENSURELI_DROPPED, /**< Linear independence resolved by dropping blocking constraint. */ -/* Simple exitflags */ -RET_SIMPLE_STATUS_P1, /**< QP problem could not be solved within given number of iterations. */ -RET_SIMPLE_STATUS_P0, /**< QP problem solved. */ -RET_SIMPLE_STATUS_M1, /**< QP problem could not be solved due to an internal error. */ -RET_SIMPLE_STATUS_M2, /**< QP problem is infeasible (and thus could not be solved). */ -RET_SIMPLE_STATUS_M3 /**< QP problem is unbounded (and thus could not be solved). (146) */ -} returnValue; - - -/** - * \brief Data structure for entries in global message list. - * - * Data structure for entries in global message list. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - returnValue key; /**< Global return value. */ - const char* data; /**< Corresponding message. */ - VisibilityStatus globalVisibilityStatus; /**< Determines if message can be printed. - * If this value is set to VS_HIDDEN, no message is printed! */ -} ReturnValueList; - - - -/** - * \brief Handles all kind of error messages, warnings and other information. - * - * This class handles all kinds of messages (errors, warnings, infos) initiated - * by qpOASES modules and stores the corresponding global preferences. - * - * \author Hans Joachim Ferreau (thanks to Leonard Wirsching) - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - VisibilityStatus errorVisibility; /**< Error messages visible? */ - VisibilityStatus warningVisibility; /**< Warning messages visible? */ - VisibilityStatus infoVisibility; /**< Info messages visible? */ - - FILE* outputFile; /**< Output file for messages. */ - - int errorCount; /**< Counts number of errors (for nicer output only). */ -} MessageHandling; - - - -/** Constructor which takes the desired output file and desired visibility states. */ -void MessageHandlingCON( MessageHandling* _THIS, - FILE* _outputFile, /**< Output file. */ - VisibilityStatus _errorVisibility, /**< Visibility status for error messages. */ - VisibilityStatus _warningVisibility,/**< Visibility status for warning messages. */ - VisibilityStatus _infoVisibility /**< Visibility status for info messages. */ - ); - -void MessageHandlingCPY( MessageHandling* FROM, - MessageHandling* TO - ); - - -/** Prints an error message(a simplified macro THROWERROR is also provided). \n - * Errors are definied as abnormal events which cause an immediate termination of the current (sub) function. - * Errors of a sub function should be commented by the calling function by means of a warning message - * (if this error does not cause an error of the calling function, either)! - * \return Error number returned by sub function call - */ -returnValue MessageHandling_throwError( MessageHandling* _THIS, - returnValue Enumber, /**< Error number returned by sub function call. */ - const char* additionaltext, /**< Additional error text (0, if none). */ - const char* functionname, /**< Name of function which caused the error. */ - const char* filename, /**< Name of file which caused the error. */ - const unsigned long linenumber, /**< Number of line which caused the error.incompatible binary file */ - VisibilityStatus localVisibilityStatus /**< Determines (locally) if error message can be printed to stderr. - * If GLOBAL visibility status of the message is set to VS_HIDDEN, - * no message is printed, anyway! */ - ); - -/** Prints a warning message (a simplified macro THROWWARNING is also provided). - * Warnings are definied as abnormal events which does NOT cause an immediate termination of the current (sub) function. - * \return Warning number returned by sub function call - */ -returnValue MessageHandling_throwWarning( MessageHandling* _THIS, - returnValue Wnumber, /**< Warning number returned by sub function call. */ - const char* additionaltext, /**< Additional warning text (0, if none). */ - const char* functionname, /**< Name of function which caused the warning. */ - const char* filename, /**< Name of file which caused the warning. */ - const unsigned long linenumber, /**< Number of line which caused the warning. */ - VisibilityStatus localVisibilityStatus /**< Determines (locally) if warning message can be printed to stderr. - * If GLOBAL visibility status of the message is set to VS_HIDDEN, - * no message is printed, anyway! */ - ); - -/** Prints a info message (a simplified macro THROWINFO is also provided). - * \return Info number returned by sub function call - */ -returnValue MessageHandling_throwInfo( MessageHandling* _THIS, - returnValue Inumber, /**< Info number returned by sub function call. */ - const char* additionaltext, /**< Additional warning text (0, if none). */ - const char* functionname, /**< Name of function which submitted the info. */ - const char* filename, /**< Name of file which submitted the info. */ - const unsigned long linenumber, /**< Number of line which submitted the info. */ - VisibilityStatus localVisibilityStatus /**< Determines (locally) if info message can be printed to stderr. - * If GLOBAL visibility status of the message is set to VS_HIDDEN, - * no message is printed, anyway! */ - ); - - -/** Resets all preferences to default values. - * \return SUCCESSFUL_RETURN */ -returnValue MessageHandling_reset( MessageHandling* _THIS ); - - -/** Prints a complete list of all messages to output file. - * \return SUCCESSFUL_RETURN */ -returnValue MessageHandling_listAllMessages( MessageHandling* _THIS ); - - -/** Returns visibility status for error messages. - * \return Visibility status for error messages. */ -static inline VisibilityStatus MessageHandling_getErrorVisibilityStatus( MessageHandling* _THIS ); - -/** Returns visibility status for warning messages. - * \return Visibility status for warning messages. */ -static inline VisibilityStatus MessageHandling_getWarningVisibilityStatus( MessageHandling* _THIS ); - -/** Returns visibility status for info messages. - * \return Visibility status for info messages. */ -static inline VisibilityStatus MessageHandling_getInfoVisibilityStatus( MessageHandling* _THIS ); - -/** Returns pointer to output file. - * \return Pointer to output file. */ -static inline FILE* MessageHandling_getOutputFile( MessageHandling* _THIS ); - -/** Returns error count value. - * \return Error count value. */ -static inline int MessageHandling_getErrorCount( MessageHandling* _THIS ); - - -/** Changes visibility status for error messages. */ -static inline void MessageHandling_setErrorVisibilityStatus( MessageHandling* _THIS, - VisibilityStatus _errorVisibility /**< New visibility status for error messages. */ - ); - -/** Changes visibility status for warning messages. */ -static inline void MessageHandling_setWarningVisibilityStatus( MessageHandling* _THIS, - VisibilityStatus _warningVisibility /**< New visibility status for warning messages. */ - ); - -/** Changes visibility status for info messages. */ -static inline void MessageHandling_setInfoVisibilityStatus( MessageHandling* _THIS, - VisibilityStatus _infoVisibility /**< New visibility status for info messages. */ - ); - -/** Changes output file for messages. */ -static inline void MessageHandling_setOutputFile( MessageHandling* _THIS, - FILE* _outputFile /**< New output file for messages. */ - ); - -/** Changes error count. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENT */ -static inline returnValue MessageHandling_setErrorCount( MessageHandling* _THIS, - int _errorCount /**< New error count value. */ - ); - -/** Provides message text corresponding to given \a returnValue. - * \return String containing message text. */ -const char* MessageHandling_getErrorCodeMessage( MessageHandling* _THIS, - const returnValue _returnValue - ); - - -returnValue MessageHandling_throwMessage( MessageHandling* _THIS, - returnValue RETnumber, /**< Error/warning/info number returned by sub function call. */ - const char* additionaltext, /**< Additional warning text (0, if none). */ - const char* functionname, /**< Name of function which caused the error/warning/info. */ - const char* filename, /**< Name of file which caused the error/warning/info. */ - const unsigned long linenumber, /**< Number of line which caused the error/warning/info. */ - VisibilityStatus localVisibilityStatus, /**< Determines (locally) if info message can be printed to stderr. - * If GLOBAL visibility status of the message is set to VS_HIDDEN, - * no message is printed, anyway! */ - const char* RETstring /**< Leading string of error/warning/info message. */ - ); - - -#ifndef __FILE__ - /** Ensures that __FILE__ macro is defined. */ - #define __FILE__ 0 -#endif - -#ifndef __LINE__ - /** Ensures that __LINE__ macro is defined. */ - #define __LINE__ 0 -#endif - -/** Define __FUNC__ macro providing current function for debugging. */ -/*#define __FUNC__ 0*/ -#define __FUNC__ ("(no function name provided)") -/*#define __FUNC__ __func__*/ -/*#define __FUNC__ __FUNCTION__*/ - - -/** Short version of throwError with default values, only returnValue is needed */ -#define THROWERROR(retval) ( MessageHandling_throwError( qpOASES_getGlobalMessageHandler(),(retval),0,__FUNC__,__FILE__,__LINE__,VS_VISIBLE) ) - -/** Short version of throwWarning with default values, only returnValue is needed */ -#define THROWWARNING(retval) ( MessageHandling_throwWarning( qpOASES_getGlobalMessageHandler(),(retval),0,__FUNC__,__FILE__,__LINE__,VS_VISIBLE) ) - -/** Short version of throwInfo with default values, only returnValue is needed */ -#define THROWINFO(retval) ( MessageHandling_throwInfo( qpOASES_getGlobalMessageHandler(),(retval),0,__FUNC__,__FILE__,__LINE__,VS_VISIBLE) ) - - -/** Returns a pointer to global message handler. - * \return Pointer to global message handler. - */ -MessageHandling* qpOASES_getGlobalMessageHandler( ); - - -/* - * g e t E r r o r V i s i b i l i t y S t a t u s - */ -static inline VisibilityStatus MessageHandling_getErrorVisibilityStatus( MessageHandling* _THIS ) -{ - return _THIS->errorVisibility; -} - - -/* - * g e t W a r n i n g V i s i b i l i t y S t a t u s - */ -static inline VisibilityStatus MessageHandling_getWarningVisibilityStatus( MessageHandling* _THIS ) -{ - return _THIS->warningVisibility; -} - - -/* - * g e t I n f o V i s i b i l i t y S t a t u s - */ -static inline VisibilityStatus MessageHandling_getInfoVisibilityStatus( MessageHandling* _THIS ) -{ - return _THIS->infoVisibility; -} - - -/* - * g e t O u t p u t F i l e - */ -static inline FILE* MessageHandling_getOutputFile( MessageHandling* _THIS ) -{ - return _THIS->outputFile; -} - - -/* - * g e t E r r o r C o u n t - */ -static inline int MessageHandling_getErrorCount( MessageHandling* _THIS ) -{ - return _THIS->errorCount; -} - - -/* - * s e t E r r o r V i s i b i l i t y S t a t u s - */ -static inline void MessageHandling_setErrorVisibilityStatus( MessageHandling* _THIS, VisibilityStatus _errorVisibility ) -{ - _THIS->errorVisibility = _errorVisibility; -} - - -/* - * s e t W a r n i n g V i s i b i l i t y S t a t u s - */ -static inline void MessageHandling_setWarningVisibilityStatus( MessageHandling* _THIS, VisibilityStatus _warningVisibility ) -{ - _THIS->warningVisibility = _warningVisibility; -} - - -/* - * s e t I n f o V i s i b i l i t y S t a t u s - */ -static inline void MessageHandling_setInfoVisibilityStatus( MessageHandling* _THIS, VisibilityStatus _infoVisibility ) -{ - _THIS->infoVisibility = _infoVisibility; -} - - -/* - * s e t O u t p u t F i l e - */ -static inline void MessageHandling_setOutputFile( MessageHandling* _THIS, FILE* _outputFile ) -{ - _THIS->outputFile = _outputFile; -} - - -/* - * s e t E r r o r C o u n t - */ -static inline returnValue MessageHandling_setErrorCount( MessageHandling* _THIS, int _errorCount ) -{ - if ( _errorCount >= 0 ) - { - _THIS->errorCount = _errorCount; - return SUCCESSFUL_RETURN; - } - else - return RET_INVALID_ARGUMENTS; -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_MESSAGEHANDLING_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Options.h b/third_party/acados/include/qpOASES_e/Options.h deleted file mode 100644 index ca8086d2cc64ed..00000000000000 --- a/third_party/acados/include/qpOASES_e/Options.h +++ /dev/null @@ -1,153 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Options.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Options class designed to manage user-specified - * options for solving a QProblem. - */ - - -#ifndef QPOASES_OPTIONS_H -#define QPOASES_OPTIONS_H - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Manages all user-specified options for solving QPs. - * - * This class manages all user-specified options used for solving - * quadratic programs. - * - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - PrintLevel printLevel; /**< Print level. */ - - BooleanType enableRamping; /**< Specifies whether ramping shall be enabled or not. */ - BooleanType enableFarBounds; /**< Specifies whether far bounds shall be used or not. */ - BooleanType enableFlippingBounds; /**< Specifies whether flipping bounds shall be used or not. */ - BooleanType enableRegularisation; /**< Specifies whether Hessian matrix shall be regularised in case semi-definiteness is detected. */ - BooleanType enableFullLITests; /**< Specifies whether condition-hardened LI test shall be used or not. */ - BooleanType enableNZCTests; /**< Specifies whether nonzero curvature tests shall be used. */ - int enableDriftCorrection; /**< Specifies the frequency of drift corrections (0 = off). */ - int enableCholeskyRefactorisation; /**< Specifies the frequency of full refactorisation of proj. Hessian (otherwise updates). */ - BooleanType enableEqualities; /**< Specifies whether equalities shall be always treated as active constraints. */ - - real_t terminationTolerance; /**< Termination tolerance. */ - real_t boundTolerance; /**< Lower/upper (constraints') bound tolerance (an inequality constraint whose lower and upper bounds differ by less is regarded to be an equality constraint). */ - real_t boundRelaxation; /**< Offset for relaxing (constraints') bounds at beginning of an initial homotopy. It is also as initial value for far bounds. */ - real_t epsNum; /**< Numerator tolerance for ratio tests. */ - real_t epsDen; /**< Denominator tolerance for ratio tests. */ - real_t maxPrimalJump; /**< Maximum allowed jump in primal variables in nonzero curvature tests. */ - real_t maxDualJump; /**< Maximum allowed jump in dual variables in linear independence tests. */ - - real_t initialRamping; /**< Start value for Ramping Strategy. */ - real_t finalRamping; /**< Final value for Ramping Strategy. */ - real_t initialFarBounds; /**< Initial size of Far Bounds. */ - real_t growFarBounds; /**< Factor to grow Far Bounds. */ - SubjectToStatus initialStatusBounds; /**< Initial status of bounds at first iteration. */ - real_t epsFlipping; /**< Tolerance of squared Cholesky diagonal factor which triggers flipping bound. */ - int numRegularisationSteps; /**< Maximum number of successive regularisation steps. */ - real_t epsRegularisation; /**< Scaling factor of identity matrix used for Hessian regularisation. */ - int numRefinementSteps; /**< Maximum number of iterative refinement steps. */ - real_t epsIterRef; /**< Early termination tolerance for iterative refinement. */ - real_t epsLITests; /**< Tolerance for linear independence tests. */ - real_t epsNZCTests; /**< Tolerance for nonzero curvature tests. */ - - BooleanType enableDropInfeasibles; /**< ... */ - int dropBoundPriority; /**< ... */ - int dropEqConPriority; /**< ... */ - int dropIneqConPriority; /**< ... */ -} Options; - - -void OptionsCON( Options* _THIS - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void OptionsCPY( Options* FROM, - Options* TO - ); - - -/** Sets all options to default values. - * \return SUCCESSFUL_RETURN */ -returnValue Options_setToDefault( Options* _THIS - ); - -/** Sets all options to values resulting in maximum reliabilty. - * \return SUCCESSFUL_RETURN */ -returnValue Options_setToReliable( Options* _THIS - ); - -/** Sets all options to values resulting in minimum solution time. - * \return SUCCESSFUL_RETURN */ -returnValue Options_setToMPC( Options* _THIS - ); - -/** Same as setToMPC( ), for ensuring backwards compatibility. - * \return SUCCESSFUL_RETURN */ -returnValue Options_setToFast( Options* _THIS - ); - - -/** Ensures that all options have consistent values by automatically - * adjusting inconsistent ones. - * Note: This routine cannot (and does not try to) ensure that values - * are set to reasonable values that make the QP solution work! - * \return SUCCESSFUL_RETURN \n - * RET_OPTIONS_ADJUSTED */ -returnValue Options_ensureConsistency( Options* _THIS - ); - - -/** Prints values of all options. - * \return SUCCESSFUL_RETURN */ -returnValue Options_print( Options* _THIS - ); - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_OPTIONS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/QProblem.h b/third_party/acados/include/qpOASES_e/QProblem.h deleted file mode 100644 index 91a4a6f396720a..00000000000000 --- a/third_party/acados/include/qpOASES_e/QProblem.h +++ /dev/null @@ -1,2369 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/QProblem.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the QProblem class which is able to use the newly - * developed online active set strategy for parametric quadratic programming. - */ - - - -#ifndef QPOASES_QPROBLEM_H -#define QPOASES_QPROBLEM_H - - -#include -#include -#include -#include -#include -#include - - -BEGIN_NAMESPACE_QPOASES - -typedef struct { - Bounds *auxiliaryBounds; - Constraints *auxiliaryConstraints; - - real_t *ub_new_far; - real_t *lb_new_far; - real_t *ubA_new_far; - real_t *lbA_new_far; - - real_t *g_new; - real_t *lb_new; - real_t *ub_new; - real_t *lbA_new; - real_t *ubA_new; - - real_t *g_new2; - real_t *lb_new2; - real_t *ub_new2; - real_t *lbA_new2; - real_t *ubA_new2; - - real_t *delta_xFX5; - real_t *delta_xFR5; - real_t *delta_yAC5; - real_t *delta_yFX5; - - real_t *Hx; - - real_t *_H; - - real_t *g_original; - real_t *lb_original; - real_t *ub_original; - real_t *lbA_original; - real_t *ubA_original; - - real_t *delta_xFR; - real_t *delta_xFX; - real_t *delta_yAC; - real_t *delta_yFX; - real_t *delta_g; - real_t *delta_lb; - real_t *delta_ub; - real_t *delta_lbA; - real_t *delta_ubA; - - real_t *gMod; - - real_t *aFR; - real_t *wZ; - - real_t *delta_g2; - real_t *delta_xFX2; - real_t *delta_xFR2; - real_t *delta_yAC2; - real_t *delta_yFX2; - real_t *nul; - real_t *Arow; - - real_t *xiC; - real_t *xiC_TMP; - real_t *xiB; - real_t *Arow2; - real_t *num; - - real_t *w; - real_t *tmp; - - real_t *delta_g3; - real_t *delta_xFX3; - real_t *delta_xFR3; - real_t *delta_yAC3; - real_t *delta_yFX3; - real_t *nul2; - - real_t *xiC2; - real_t *xiC_TMP2; - real_t *xiB2; - real_t *num2; - - real_t *Hz; - real_t *z; - real_t *ZHz; - real_t *r; - - real_t *tmp2; - real_t *Hz2; - real_t *z2; - real_t *r2; - real_t *rhs; - - real_t *delta_xFX4; - real_t *delta_xFR4; - real_t *delta_yAC4; - real_t *delta_yFX4; - real_t *nul3; - real_t *ek; - real_t *x_W; - real_t *As; - real_t *Ax_W; - - real_t *num3; - real_t *den; - real_t *delta_Ax_l; - real_t *delta_Ax_u; - real_t *delta_Ax; - real_t *delta_x; - - real_t *_A; - - real_t *grad; - real_t *AX; -} QProblem_ws; - -int QProblem_ws_calculateMemorySize( unsigned int nV, unsigned int nC ); - -char *QProblem_ws_assignMemory( unsigned int nV, unsigned int nC, QProblem_ws **mem, void *raw_memory ); - -QProblem_ws *QProblem_ws_createMemory( unsigned int nV, unsigned int nC ); - -/** - * \brief Implements the online active set strategy for QPs with general constraints. - * - * A class for setting up and solving quadratic programs. The main feature is - * the possibily to use the newly developed online active set strategy for - * parametric quadratic programming. - * - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - QProblem_ws *ws; /**< Workspace */ - Bounds *bounds; /**< Data structure for problem's bounds. */ - Constraints *constraints; /**< Data structure for problem's constraints. */ - Flipper *flipper; /**< Struct for making a temporary copy of the matrix factorisations. */ - - DenseMatrix* H; /**< Hessian matrix pointer. */ - DenseMatrix* A; /**< Constraint matrix pointer. */ - - Options options; /**< Struct containing all user-defined options for solving QPs. */ - TabularOutput tabularOutput; /**< Struct storing information for tabular output (printLevel == PL_TABULAR). */ - - real_t *g; /**< Gradient. */ - - real_t *lb; /**< Lower bound vector (on variables). */ - real_t *ub; /**< Upper bound vector (on variables). */ - real_t *lbA; /**< Lower constraints' bound vector. */ - real_t *ubA; /**< Upper constraints' bound vector. */ - - real_t *R; /**< Cholesky factor of H (i.e. H = R^T*R). */ - - real_t *T; /**< Reverse triangular matrix, A = [0 T]*Q'. */ - real_t *Q; /**< Orthonormal quadratic matrix, A = [0 T]*Q'. */ - - real_t *Ax; /**< Stores the current A*x \n - * (for increased efficiency only). */ - real_t *Ax_l; /**< Stores the current distance to lower constraints' bounds A*x-lbA \n - * (for increased efficiency only). */ - real_t *Ax_u; /**< Stores the current distance to lower constraints' bounds ubA-A*x \n - * (for increased efficiency only). */ - - real_t *x; /**< Primal solution vector. */ - real_t *y; /**< Dual solution vector. */ - - real_t *delta_xFR_TMP; /**< Temporary for determineStepDirection */ - real_t *tempA; /**< Temporary for determineStepDirection. */ - real_t *tempB; /**< Temporary for determineStepDirection. */ - real_t *ZFR_delta_xFRz; /**< Temporary for determineStepDirection. */ - real_t *delta_xFRy; /**< Temporary for determineStepDirection. */ - real_t *delta_xFRz; /**< Temporary for determineStepDirection. */ - real_t *delta_yAC_TMP; /**< Temporary for determineStepDirection. */ - - ConstraintProduct constraintProduct; /**< Pointer to user-defined constraint product function. */ - - real_t tau; /**< Last homotopy step length. */ - real_t regVal; /**< Holds the offset used to regularise Hessian matrix (zero by default). */ - - real_t ramp0; /**< Start value for Ramping Strategy. */ - real_t ramp1; /**< Final value for Ramping Strategy. */ - - QProblemStatus status; /**< Current status of the solution process. */ - HessianType hessianType; /**< Type of Hessian matrix. */ - - BooleanType haveCholesky; /**< Flag indicating whether Cholesky decomposition has already been setup. */ - BooleanType infeasible; /**< QP infeasible? */ - BooleanType unbounded; /**< QP unbounded? */ - - int rampOffset; /**< Offset index for Ramping. */ - unsigned int count; /**< Counts the number of hotstart function calls (internal usage only!). */ - - int sizeT; /**< Matrix T is stored in a (sizeT x sizeT) array. */ -} QProblem; - -int QProblem_calculateMemorySize( unsigned int nV, unsigned int nC ); - -char *QProblem_assignMemory( unsigned int nV, unsigned int nC, QProblem **mem, void *raw_memory ); - -QProblem *QProblem_createMemory( unsigned int nV, unsigned int nC ); - - -/** Constructor which takes the QP dimension and Hessian type - * information. If the Hessian is the zero (i.e. HST_ZERO) or the - * identity matrix (i.e. HST_IDENTITY), respectively, no memory - * is allocated for it and a NULL pointer can be passed for it - * to the init() functions. */ -void QProblemCON( QProblem* _THIS, - int _nV, /**< Number of variables. */ - int _nC, /**< Number of constraints. */ - HessianType _hessianType /**< Type of Hessian matrix. */ - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void QProblemCPY( QProblem* FROM, - QProblem* TO - ); - - -/** Clears all data structures of QProblem except for QP data. - * \return SUCCESSFUL_RETURN \n - RET_RESET_FAILED */ -returnValue QProblem_reset( QProblem* _THIS ); - - -/** Initialises a QP problem with given QP data and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_initM( QProblem* _THIS, - DenseMatrix *_H, /**< Hessian matrix. */ - const real_t* const _g, /**< Gradient vector. */ - DenseMatrix *_A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA, /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - - -/** Initialises a QP problem with given QP data and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_init( QProblem* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - real_t* const _A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA, /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a QP problem with given QP data to be read from files and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_UNABLE_TO_READ_FILE */ -returnValue QProblem_initF( QProblem* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix is stored. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient vector is stored. */ - const char* const A_file, /**< Name of file where constraint matrix is stored. */ - const char* const lb_file, /**< Name of file where lower bound vector. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bound vector. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bound vector. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a QP problem with given QP data and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB/gC empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB/gC by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB/gC from yOpt != 0, \n - * 4. 0, 0, gB/gC: starts with xOpt = 0, yOpt = 0 and gB/gC, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB/gC from yOpt != 0, \n - * 6. xOpt, 0, gB/gC: starts with xOpt, yOpt = 0 and gB/gC, \n - * 7. xOpt, yOpt, gB/gC: starts with xOpt, yOpt and gB/gC (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_initMW( QProblem* _THIS, - DenseMatrix *_H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - DenseMatrix *_A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA, /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - * Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Optimal working set of constraints for solution (xOpt,yOpt). */ - const real_t* const _R /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Initialises a QP problem with given QP data and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB/gC empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB/gC by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB/gC from yOpt != 0, \n - * 4. 0, 0, gB/gC: starts with xOpt = 0, yOpt = 0 and gB/gC, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB/gC from yOpt != 0, \n - * 6. xOpt, 0, gB/gC: starts with xOpt, yOpt = 0 and gB/gC, \n - * 7. xOpt, yOpt, gB/gC: starts with xOpt, yOpt and gB/gC (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_initW( QProblem* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - real_t* const _A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA, /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - * Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Optimal working set of constraints for solution (xOpt,yOpt). */ - const real_t* const _R /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Initialises a QP problem with given QP data to be ream from files and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB/gC empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB/gC by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB/gC from yOpt != 0, \n - * 4. 0, 0, gB/gC: starts with xOpt = 0, yOpt = 0 and gB/gC, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB/gC from yOpt != 0, \n - * 6. xOpt, 0, gB/gC: starts with xOpt, yOpt = 0 and gB/gC, \n - * 7. xOpt, yOpt, gB/gC: starts with xOpt, yOpt and gB/gC (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_UNABLE_TO_READ_FILE */ -returnValue QProblem_initFW( QProblem* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix is stored. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient vector is stored. */ - const char* const A_file, /**< Name of file where constraint matrix is stored. */ - const char* const lb_file, /**< Name of file where lower bound vector. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bound vector. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bound vector. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Optimal working set of constraints for solution (xOpt,yOpt). */ - const char* const R_file /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Solves an initialised QP sequence using the online active set strategy. - * QP solution is started from previous solution. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblem_hotstart( QProblem* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QP sequence using the online active set strategy, - * where QP data is read from files. QP solution is started from previous solution. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_hotstartF( QProblem* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QP sequence using the online active set strategy. - * By default, QP solution is started from previous solution. If a guess - * for the working set is provided, an initialised homotopy is performed. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_SETUP_AUXILIARYQP_FAILED */ -returnValue QProblem_hotstartW( QProblem* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set of bounds is kept!) */ - Constraints* const guessedConstraints /**< Optimal working set of constraints for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set of constraints is kept!) */ - ); - -/** Solves an initialised QP sequence using the online active set strategy, - * where QP data is read from files. - * By default, QP solution is started from previous solution. If a guess - * for the working set is provided, an initialised homotopy is performed. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_SETUP_AUXILIARYQP_FAILED \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_hotstartFW( QProblem* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set of bounds is kept!) */ - Constraints* const guessedConstraints /**< Optimal working set of constraints for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set of constraints is kept!) */ - ); - - -/** Solves using the current working set - * \return SUCCESSFUL_RETURN \n - * RET_STEPDIRECTION_FAILED_TQ \n - * RET_STEPDIRECTION_FAILED_CHOLESKY \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblem_solveCurrentEQP ( QProblem* _THIS, - const int n_rhs, /**< Number of consecutive right hand sides */ - const real_t* g_in, /**< Gradient of neighbouring QP to be solved. */ - const real_t* lb_in, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* ub_in, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* lbA_in, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* ubA_in, /**< Upper constraints' bounds of neighbouring QP to be solved. \n */ - real_t* x_out, /**< Output: Primal solution */ - real_t* y_out /**< Output: Dual solution */ - ); - - - -/** Returns current constraints object of the QP (deep copy). - * \return SUCCESSFUL_RETURN \n - RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblem_getConstraints( QProblem* _THIS, - Constraints* _constraints /** Output: Constraints object. */ - ); - - -/** Returns the number of constraints. - * \return Number of constraints. */ -static inline int QProblem_getNC( QProblem* _THIS ); - -/** Returns the number of (implicitly defined) equality constraints. - * \return Number of (implicitly defined) equality constraints. */ -static inline int QProblem_getNEC( QProblem* _THIS ); - -/** Returns the number of active constraints. - * \return Number of active constraints. */ -static inline int QProblem_getNAC( QProblem* _THIS ); - -/** Returns the number of inactive constraints. - * \return Number of inactive constraints. */ -static inline int QProblem_getNIAC( QProblem* _THIS ); - -/** Returns the dimension of null space. - * \return Dimension of null space. */ -int QProblem_getNZ( QProblem* _THIS ); - - -/** Returns the dual solution vector (deep copy). - * \return SUCCESSFUL_RETURN \n - RET_QP_NOT_SOLVED */ -returnValue QProblem_getDualSolution( QProblem* _THIS, - real_t* const yOpt /**< Output: Dual solution vector (if QP has been solved). */ - ); - - -/** Defines user-defined routine for calculating the constraint product A*x - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblem_setConstraintProduct( QProblem* _THIS, - ConstraintProduct _constraintProduct - ); - - -/** Prints concise list of properties of the current QP. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblem_printProperties( QProblem* _THIS ); - - - -/** Writes a vector with the state of the working set -* \return SUCCESSFUL_RETURN */ -returnValue QProblem_getWorkingSet( QProblem* _THIS, - real_t* workingSet /** Output: array containing state of the working set. */ - ); - -/** Writes a vector with the state of the working set of bounds - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblem_getWorkingSetBounds( QProblem* _THIS, - real_t* workingSetB /** Output: array containing state of the working set of bounds. */ - ); - -/** Writes a vector with the state of the working set of constraints - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblem_getWorkingSetConstraints( QProblem* _THIS, - real_t* workingSetC /** Output: array containing state of the working set of constraints. */ - ); - - -/** Returns current bounds object of the QP (deep copy). - * \return SUCCESSFUL_RETURN \n - RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblem_getBounds( QProblem* _THIS, - Bounds* _bounds /** Output: Bounds object. */ - ); - - -/** Returns the number of variables. - * \return Number of variables. */ -static inline int QProblem_getNV( QProblem* _THIS ); - -/** Returns the number of free variables. - * \return Number of free variables. */ -static inline int QProblem_getNFR( QProblem* _THIS ); - -/** Returns the number of fixed variables. - * \return Number of fixed variables. */ -static inline int QProblem_getNFX( QProblem* _THIS ); - -/** Returns the number of implicitly fixed variables. - * \return Number of implicitly fixed variables. */ -static inline int QProblem_getNFV( QProblem* _THIS ); - - -/** Returns the optimal objective function value. - * \return finite value: Optimal objective function value (QP was solved) \n - +infinity: QP was not yet solved */ -real_t QProblem_getObjVal( QProblem* _THIS ); - -/** Returns the objective function value at an arbitrary point x. - * \return Objective function value at point x */ -real_t QProblem_getObjValX( QProblem* _THIS, - const real_t* const _x /**< Point at which the objective function shall be evaluated. */ - ); - -/** Returns the primal solution vector. - * \return SUCCESSFUL_RETURN \n - RET_QP_NOT_SOLVED */ -returnValue QProblem_getPrimalSolution( QProblem* _THIS, - real_t* const xOpt /**< Output: Primal solution vector (if QP has been solved). */ - ); - - -/** Returns status of the solution process. - * \return Status of solution process. */ -static inline QProblemStatus QProblem_getStatus( QProblem* _THIS ); - - -/** Returns if the QProblem object is initialised. - * \return BT_TRUE: QProblem initialised \n - BT_FALSE: QProblem not initialised */ -static inline BooleanType QProblem_isInitialised( QProblem* _THIS ); - -/** Returns if the QP has been solved. - * \return BT_TRUE: QProblem solved \n - BT_FALSE: QProblem not solved */ -static inline BooleanType QProblem_isSolved( QProblem* _THIS ); - -/** Returns if the QP is infeasible. - * \return BT_TRUE: QP infeasible \n - BT_FALSE: QP feasible (or not known to be infeasible!) */ -static inline BooleanType QProblem_isInfeasible( QProblem* _THIS ); - -/** Returns if the QP is unbounded. - * \return BT_TRUE: QP unbounded \n - BT_FALSE: QP unbounded (or not known to be unbounded!) */ -static inline BooleanType QProblem_isUnbounded( QProblem* _THIS ); - - -/** Returns Hessian type flag (type is not determined due to _THIS call!). - * \return Hessian type. */ -static inline HessianType QProblem_getHessianType( QProblem* _THIS ); - -/** Changes the print level. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblem_setHessianType( QProblem* _THIS, - HessianType _hessianType /**< New Hessian type. */ - ); - -/** Returns if the QP has been internally regularised. - * \return BT_TRUE: Hessian is internally regularised for QP solution \n - BT_FALSE: No internal Hessian regularisation is used for QP solution */ -static inline BooleanType QProblem_usingRegularisation( QProblem* _THIS ); - -/** Returns current options struct. - * \return Current options struct. */ -static inline Options QProblem_getOptions( QProblem* _THIS ); - -/** Overrides current options with given ones. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblem_setOptions( QProblem* _THIS, - Options _options /**< New options. */ - ); - -/** Returns the print level. - * \return Print level. */ -static inline PrintLevel QProblem_getPrintLevel( QProblem* _THIS ); - -/** Changes the print level. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_setPrintLevel( QProblem* _THIS, - PrintLevel _printlevel /**< New print level. */ - ); - - -/** Returns the current number of QP problems solved. - * \return Number of QP problems solved. */ -static inline unsigned int QProblem_getCount( QProblem* _THIS ); - -/** Resets QP problem counter (to zero). - * \return SUCCESSFUL_RETURN. */ -static inline returnValue QProblem_resetCounter( QProblem* _THIS ); - - -/** Prints a list of all options and their current values. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblem_printOptions( QProblem* _THIS ); - - -/** Solves a QProblem whose QP data is assumed to be stored in the member variables. - * A guess for its primal/dual optimal solution vectors and the corresponding - * working sets of bounds and constraints can be provided. - * Note: This function is internally called by all init functions! - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED */ -returnValue QProblem_solveInitialQP( QProblem* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector.*/ - const real_t* const yOpt, /**< Optimal dual solution vector. */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Optimal working set of constraints for solution (xOpt,yOpt). */ - const real_t* const _R, /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - * Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - * Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves QProblem using online active set strategy. - * Note: This function is internally called by all hotstart functions! - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblem_solveQP( QProblem* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - int nWSRperformed, /**< Number of working set recalculations already performed to solve - this QP within previous solveQP() calls. This number is - always zero, except for successive calls from solveRegularisedQP() - or when using the far bound strategy. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Solves QProblem using online active set strategy. - * Note: This function is internally called by all hotstart functions! - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblem_solveRegularisedQP( QProblem* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - int nWSRperformed, /**< Number of working set recalculations already performed to solve - this QP within previous solveRegularisedQP() calls. This number is - always zero, except for successive calls when using the far bound strategy. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Determines type of existing constraints and bounds (i.e. implicitly fixed, unbounded etc.). - * \return SUCCESSFUL_RETURN \n - RET_SETUPSUBJECTTOTYPE_FAILED */ -returnValue QProblem_setupSubjectToType( QProblem* _THIS ); - -/** Determines type of new constraints and bounds (i.e. implicitly fixed, unbounded etc.). - * \return SUCCESSFUL_RETURN \n - RET_SETUPSUBJECTTOTYPE_FAILED */ -returnValue QProblem_setupSubjectToTypeNew( QProblem* _THIS, - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new, /**< New upper bounds. */ - const real_t* const lbA_new, /**< New lower constraints' bounds. */ - const real_t* const ubA_new /**< New upper constraints' bounds. */ - ); - -/** Computes the Cholesky decomposition of the projected Hessian (i.e. R^T*R = Z^T*H*Z). - * Note: If Hessian turns out not to be positive definite, the Hessian type - * is set to HST_SEMIDEF accordingly. - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblem_computeProjectedCholesky( QProblem* _THIS ); - -/** Computes initial Cholesky decomposition of the projected Hessian making - * use of the function setupCholeskyDecomposition() or setupCholeskyDecompositionProjected(). - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblem_setupInitialCholesky( QProblem* _THIS ); - -/** Initialises TQ factorisation of A (i.e. A*Q = [0 T]) if NO constraint is active. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue QProblem_setupTQfactorisation( QProblem* _THIS ); - - -/** Obtains the desired working set for the auxiliary initial QP in - * accordance with the user specifications - * (assumes that member AX has already been initialised!) - * \return SUCCESSFUL_RETURN \n - RET_OBTAINING_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_obtainAuxiliaryWorkingSet( QProblem* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - const real_t* const yOpt, /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - Bounds* const guessedBounds, /**< Guessed working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Guessed working set for solution (xOpt,yOpt). */ - Bounds* auxiliaryBounds, /**< Input: Allocated bound object. \n - * Ouput: Working set of constraints for auxiliary QP. */ - Constraints* auxiliaryConstraints /**< Input: Allocated bound object. \n - * Ouput: Working set for auxiliary QP. */ - ); - -/** Sets up bound and constraints data structures according to auxiliaryBounds/Constraints. - * (If the working set shall be setup afresh, make sure that - * bounds and constraints data structure have been resetted - * and the TQ factorisation has been initialised!) - * \return SUCCESSFUL_RETURN \n - RET_SETUP_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS \n - RET_UNKNOWN_BUG */ -returnValue QProblem_setupAuxiliaryWorkingSet( QProblem* _THIS, - Bounds* const auxiliaryBounds, /**< Working set of bounds for auxiliary QP. */ - Constraints* const auxiliaryConstraints, /**< Working set of constraints for auxiliary QP. */ - BooleanType setupAfresh /**< Flag indicating if given working set shall be - * setup afresh or by updating the current one. */ - ); - -/** Sets up the optimal primal/dual solution of the auxiliary initial QP. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_setupAuxiliaryQPsolution( QProblem* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are set to zero. */ - const real_t* const yOpt /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are set to zero. */ - ); - -/** Sets up gradient of the auxiliary initial QP for given - * optimal primal/dual solution and given initial working set - * (assumes that members X, Y and BOUNDS, CONSTRAINTS have already been initialised!). - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_setupAuxiliaryQPgradient( QProblem* _THIS ); - -/** Sets up (constraints') bounds of the auxiliary initial QP for given - * optimal primal/dual solution and given initial working set - * (assumes that members X, Y and BOUNDS, CONSTRAINTS have already been initialised!). - * \return SUCCESSFUL_RETURN \n - RET_UNKNOWN_BUG */ -returnValue QProblem_setupAuxiliaryQPbounds( QProblem* _THIS, - Bounds* const auxiliaryBounds, /**< Working set of bounds for auxiliary QP. */ - Constraints* const auxiliaryConstraints, /**< Working set of constraints for auxiliary QP. */ - BooleanType useRelaxation /**< Flag indicating if inactive (constraints') bounds shall be relaxed. */ - ); - - -/** Adds a constraint to active set. - * \return SUCCESSFUL_RETURN \n - RET_ADDCONSTRAINT_FAILED \n - RET_ADDCONSTRAINT_FAILED_INFEASIBILITY \n - RET_ENSURELI_FAILED */ -returnValue QProblem_addConstraint( QProblem* _THIS, - int number, /**< Number of constraint to be added to active set. */ - SubjectToStatus C_status, /**< Status of new active constraint. */ - BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */ - BooleanType ensureLI /**< Ensure linear independence by exchange rules by default. */ - ); - -/** Checks if new active constraint to be added is linearly dependent from - * from row of the active constraints matrix. - * \return RET_LINEARLY_DEPENDENT \n - RET_LINEARLY_INDEPENDENT \n - RET_INDEXLIST_CORRUPTED */ -returnValue QProblem_addConstraint_checkLI( QProblem* _THIS, - int number /**< Number of constraint to be added to active set. */ - ); - -/** Ensures linear independence of constraint matrix when a new constraint is added. - * To _THIS end a bound or constraint is removed simultaneously if necessary. - * \return SUCCESSFUL_RETURN \n - RET_LI_RESOLVED \n - RET_ENSURELI_FAILED \n - RET_ENSURELI_FAILED_TQ \n - RET_ENSURELI_FAILED_NOINDEX \n - RET_REMOVE_FROM_ACTIVESET */ -returnValue QProblem_addConstraint_ensureLI( QProblem* _THIS, - int number, /**< Number of constraint to be added to active set. */ - SubjectToStatus C_status /**< Status of new active bound. */ - ); - -/** Adds a bound to active set. - * \return SUCCESSFUL_RETURN \n - RET_ADDBOUND_FAILED \n - RET_ADDBOUND_FAILED_INFEASIBILITY \n - RET_ENSURELI_FAILED */ -returnValue QProblem_addBound( QProblem* _THIS, - int number, /**< Number of bound to be added to active set. */ - SubjectToStatus B_status, /**< Status of new active bound. */ - BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */ - BooleanType ensureLI /**< Ensure linear independence by exchange rules by default. */ - ); - -/** Checks if new active bound to be added is linearly dependent from - * from row of the active constraints matrix. - * \return RET_LINEARLY_DEPENDENT \n - RET_LINEARLY_INDEPENDENT */ -returnValue QProblem_addBound_checkLI( QProblem* _THIS, - int number /**< Number of bound to be added to active set. */ - ); - -/** Ensures linear independence of constraint matrix when a new bound is added. - * To _THIS end a bound or constraint is removed simultaneously if necessary. - * \return SUCCESSFUL_RETURN \n - RET_LI_RESOLVED \n - RET_ENSURELI_FAILED \n - RET_ENSURELI_FAILED_TQ \n - RET_ENSURELI_FAILED_NOINDEX \n - RET_REMOVE_FROM_ACTIVESET */ -returnValue QProblem_addBound_ensureLI( QProblem* _THIS, - int number, /**< Number of bound to be added to active set. */ - SubjectToStatus B_status /**< Status of new active bound. */ - ); - -/** Removes a constraint from active set. - * \return SUCCESSFUL_RETURN \n - RET_CONSTRAINT_NOT_ACTIVE \n - RET_REMOVECONSTRAINT_FAILED \n - RET_HESSIAN_NOT_SPD */ -returnValue QProblem_removeConstraint( QProblem* _THIS, - int number, /**< Number of constraint to be removed from active set. */ - BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */ - BooleanType allowFlipping, /**< Flag indicating if flipping bounds are allowed. */ - BooleanType ensureNZC /**< Flag indicating if non-zero curvature is ensured by exchange rules. */ - ); - -/** Removes a bounds from active set. - * \return SUCCESSFUL_RETURN \n - RET_BOUND_NOT_ACTIVE \n - RET_HESSIAN_NOT_SPD \n - RET_REMOVEBOUND_FAILED */ -returnValue QProblem_removeBound( QProblem* _THIS, - int number, /**< Number of bound to be removed from active set. */ - BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */ - BooleanType allowFlipping, /**< Flag indicating if flipping bounds are allowed. */ - BooleanType ensureNZC /**< Flag indicating if non-zero curvature is ensured by exchange rules. */ - ); - - -/** Performs robustified ratio test yield the maximum possible step length - * along the homotopy path. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performPlainRatioTest( QProblem* _THIS, - int nIdx, /**< Number of ratios to be checked. */ - const int* const idxList, /**< Array containing the indices of all ratios to be checked. */ - const real_t* const num, /**< Array containing all numerators for performing the ratio test. */ - const real_t* const den, /**< Array containing all denominators for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t, /**< Output: Maximum possible step length along the homotopy path. */ - int* BC_idx /**< Output: Index of blocking constraint. */ - ); - - -/** Ensure non-zero curvature by primal jump. - * \return SUCCESSFUL_RETURN \n - * RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblem_ensureNonzeroCurvature( QProblem* _THIS, - BooleanType removeBoundNotConstraint, /**< SubjectTo to be removed is a bound. */ - int remIdx, /**< Index of bound/constraint to be removed. */ - BooleanType* exchangeHappened, /**< Output: Exchange was necessary to ensure. */ - BooleanType* addBoundNotConstraint, /**< SubjectTo to be added is a bound. */ - int* addIdx, /**< Index of bound/constraint to be added. */ - SubjectToStatus* addStatus /**< Status of bound/constraint to be added. */ - ); - - -/** Solves the system Ta = b or T^Ta = b where T is a reverse upper triangular matrix. - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblem_backsolveT( QProblem* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - real_t* const a /**< Output: Solution vector */ - ); - - -/** Determines step direction of the shift of the QP data. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_determineDataShift( QProblem* _THIS, - const real_t* const g_new, /**< New gradient vector. */ - const real_t* const lbA_new, /**< New lower constraints' bounds. */ - const real_t* const ubA_new, /**< New upper constraints' bounds. */ - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new, /**< New upper bounds. */ - real_t* const delta_g, /**< Output: Step direction of gradient vector. */ - real_t* const delta_lbA, /**< Output: Step direction of lower constraints' bounds. */ - real_t* const delta_ubA, /**< Output: Step direction of upper constraints' bounds. */ - real_t* const delta_lb, /**< Output: Step direction of lower bounds. */ - real_t* const delta_ub, /**< Output: Step direction of upper bounds. */ - BooleanType* Delta_bC_isZero, /**< Output: Indicates if active constraints' bounds are to be shifted. */ - BooleanType* Delta_bB_isZero /**< Output: Indicates if active bounds are to be shifted. */ - ); - -/** Determines step direction of the homotopy path. - * \return SUCCESSFUL_RETURN \n - RET_STEPDIRECTION_FAILED_TQ \n - RET_STEPDIRECTION_FAILED_CHOLESKY */ -returnValue QProblem_determineStepDirection( QProblem* _THIS, - const real_t* const delta_g, /**< Step direction of gradient vector. */ - const real_t* const delta_lbA, /**< Step direction of lower constraints' bounds. */ - const real_t* const delta_ubA, /**< Step direction of upper constraints' bounds. */ - const real_t* const delta_lb, /**< Step direction of lower bounds. */ - const real_t* const delta_ub, /**< Step direction of upper bounds. */ - BooleanType Delta_bC_isZero, /**< Indicates if active constraints' bounds are to be shifted. */ - BooleanType Delta_bB_isZero, /**< Indicates if active bounds are to be shifted. */ - real_t* const delta_xFX, /**< Output: Primal homotopy step direction of fixed variables. */ - real_t* const delta_xFR, /**< Output: Primal homotopy step direction of free variables. */ - real_t* const delta_yAC, /**< Output: Dual homotopy step direction of active constraints' multiplier. */ - real_t* const delta_yFX /**< Output: Dual homotopy step direction of fixed variables' multiplier. */ - ); - -/** Determines the maximum possible step length along the homotopy path - * and performs _THIS step (without changing working set). - * \return SUCCESSFUL_RETURN \n - * RET_ERROR_IN_CONSTRAINTPRODUCT \n - * RET_QP_INFEASIBLE */ -returnValue QProblem_performStep( QProblem* _THIS, - const real_t* const delta_g, /**< Step direction of gradient. */ - const real_t* const delta_lbA, /**< Step direction of lower constraints' bounds. */ - const real_t* const delta_ubA, /**< Step direction of upper constraints' bounds. */ - const real_t* const delta_lb, /**< Step direction of lower bounds. */ - const real_t* const delta_ub, /**< Step direction of upper bounds. */ - const real_t* const delta_xFX, /**< Primal homotopy step direction of fixed variables. */ - const real_t* const delta_xFR, /**< Primal homotopy step direction of free variables. */ - const real_t* const delta_yAC, /**< Dual homotopy step direction of active constraints' multiplier. */ - const real_t* const delta_yFX, /**< Dual homotopy step direction of fixed variables' multiplier. */ - int* BC_idx, /**< Output: Index of blocking constraint. */ - SubjectToStatus* BC_status, /**< Output: Status of blocking constraint. */ - BooleanType* BC_isBound /**< Output: Indicates if blocking constraint is a bound. */ - ); - -/** Updates the active set. - * \return SUCCESSFUL_RETURN \n - RET_REMOVE_FROM_ACTIVESET_FAILED \n - RET_ADD_TO_ACTIVESET_FAILED */ -returnValue QProblem_changeActiveSet( QProblem* _THIS, - int BC_idx, /**< Index of blocking constraint. */ - SubjectToStatus BC_status, /**< Status of blocking constraint. */ - BooleanType BC_isBound /**< Indicates if blocking constraint is a bound. */ - ); - - -/** Compute relative length of homotopy in data space for termination - * criterion. - * \return Relative length in data space. */ -real_t QProblem_getRelativeHomotopyLength( QProblem* _THIS, - const real_t* const g_new, /**< Final gradient. */ - const real_t* const lb_new, /**< Final lower variable bounds. */ - const real_t* const ub_new, /**< Final upper variable bounds. */ - const real_t* const lbA_new, /**< Final lower constraint bounds. */ - const real_t* const ubA_new /**< Final upper constraint bounds. */ - ); - - -/** Ramping Strategy to avoid ties. Modifies homotopy start without - * changing current active set. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performRamping( QProblem* _THIS ); - - -/** ... */ -returnValue QProblem_updateFarBounds( QProblem* _THIS, - real_t curFarBound, /**< ... */ - int nRamp, /**< ... */ - const real_t* const lb_new, /**< ... */ - real_t* const lb_new_far, /**< ... */ - const real_t* const ub_new, /**< ... */ - real_t* const ub_new_far, /**< ... */ - const real_t* const lbA_new, /**< ... */ - real_t* const lbA_new_far, /**< ... */ - const real_t* const ubA_new, /**< ... */ - real_t* const ubA_new_far /**< ... */ - ); - -/** ... */ -returnValue QProblemBCPY_updateFarBounds( QProblem* _THIS, - real_t curFarBound, /**< ... */ - int nRamp, /**< ... */ - const real_t* const lb_new, /**< ... */ - real_t* const lb_new_far, /**< ... */ - const real_t* const ub_new, /**< ... */ - real_t* const ub_new_far /**< ... */ - ); - - - -/** Performs robustified ratio test yield the maximum possible step length - * along the homotopy path. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performRatioTestC( QProblem* _THIS, - int nIdx, /**< Number of ratios to be checked. */ - const int* const idxList, /**< Array containing the indices of all ratios to be checked. */ - Constraints* const subjectTo, /**< Constraint object corresponding to ratios to be checked. */ - const real_t* const num, /**< Array containing all numerators for performing the ratio test. */ - const real_t* const den, /**< Array containing all denominators for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t, /**< Output: Maximum possible step length along the homotopy path. */ - int* BC_idx /**< Output: Index of blocking constraint. */ - ); - - -/** Drift correction at end of each active set iteration - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performDriftCorrection( QProblem* _THIS ); - - -/** Updates QP vectors, working sets and internal data structures in order to - start from an optimal solution corresponding to initial guesses of the working - set for bounds and constraints. - * \return SUCCESSFUL_RETURN \n - * RET_SETUP_AUXILIARYQP_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_setupAuxiliaryQP( QProblem* _THIS, - Bounds* const guessedBounds, /**< Initial guess for working set of bounds. */ - Constraints* const guessedConstraints /**< Initial guess for working set of constraints. */ - ); - -/** Determines if it is more efficient to refactorise the matrices when - * hotstarting or not (i.e. better to update the existing factorisations). - * \return BT_TRUE iff matrices shall be refactorised afresh - */ -BooleanType QProblem_shallRefactorise( QProblem* _THIS, - Bounds* const guessedBounds, /**< Guessed new working set of bounds. */ - Constraints* const guessedConstraints /**< Guessed new working set of constraints. */ - ); - -/** Setups internal QP data. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_UNKNONW_BUG */ -returnValue QProblem_setupQPdataM( QProblem* _THIS, - DenseMatrix *_H, /**< Hessian matrix. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - DenseMatrix *_A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - ); - - -/** Sets up dense internal QP data. If the current Hessian is trivial - * (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_UNKNONW_BUG */ -returnValue QProblem_setupQPdata( QProblem* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - real_t* const _A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data by loading it from files. If the current Hessian - * is trivial (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS \n - RET_UNKNONW_BUG */ -returnValue QProblem_setupQPdataFromFile( QProblem* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix, of neighbouring QP to be solved, is stored. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const A_file, /**< Name of file where constraint matrix, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - ); - -/** Loads new QP vectors from files (internal members are not affected!). - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_loadQPvectorsFromFile( QProblem* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - real_t* const g_new, /**< Output: Gradient of neighbouring QP to be solved. */ - real_t* const lb_new, /**< Output: Lower bounds of neighbouring QP to be solved */ - real_t* const ub_new, /**< Output: Upper bounds of neighbouring QP to be solved */ - real_t* const lbA_new, /**< Output: Lower constraints' bounds of neighbouring QP to be solved */ - real_t* const ubA_new /**< Output: Upper constraints' bounds of neighbouring QP to be solved */ - ); - - -/** Prints concise information on the current iteration. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblem_printIteration( QProblem* _THIS, - int iter, /**< Number of current iteration. */ - int BC_idx, /**< Index of blocking constraint. */ - SubjectToStatus BC_status, /**< Status of blocking constraint. */ - BooleanType BC_isBound, /**< Indicates if blocking constraint is a bound. */ - real_t homotopyLength, /**< Current homotopy distance. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Sets constraint matrix of the QP. \n - Note: Also internal vector Ax is recomputed! - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setAM( QProblem* _THIS, - DenseMatrix *A_new /**< New constraint matrix. */ - ); - -/** Sets dense constraint matrix of the QP. \n - Note: Also internal vector Ax is recomputed! - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setA( QProblem* _THIS, - real_t* const A_new /**< New dense constraint matrix (with correct dimension!). */ - ); - - -/** Sets constraints' lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblem_setLBA( QProblem* _THIS, - const real_t* const lbA_new /**< New constraints' lower bound vector (with correct dimension!). */ - ); - -/** Changes single entry of lower constraints' bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP \n - * RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblem_setLBAn( QProblem* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of lower constraints' bound vector (with correct dimension!). */ - ); - -/** Sets constraints' upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblem_setUBA( QProblem* _THIS, - const real_t* const ubA_new /**< New constraints' upper bound vector (with correct dimension!). */ - ); - -/** Changes single entry of upper constraints' bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP \n - * RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblem_setUBAn( QProblem* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of upper constraints' bound vector (with correct dimension!). */ - ); - - -/** Decides if lower bounds are smaller than upper bounds - * - * \return SUCCESSFUL_RETURN \n - * RET_QP_INFEASIBLE */ -returnValue QProblem_areBoundsConsistent( QProblem* _THIS, - const real_t* const lb, /**< Vector of lower bounds*/ - const real_t* const ub, /**< Vector of upper bounds*/ - const real_t* const lbA, /**< Vector of lower constraints*/ - const real_t* const ubA /**< Vector of upper constraints*/ - ); - - -/** Drops the blocking bound/constraint that led to infeasibility, or finds another - * bound/constraint to drop according to drop priorities. - * \return SUCCESSFUL_RETURN \n - */ -returnValue QProblem_dropInfeasibles ( QProblem* _THIS, - int BC_number, /**< Number of the bound or constraint to be added */ - SubjectToStatus BC_status, /**< New status of the bound or constraint to be added */ - BooleanType BC_isBound, /**< Whether a bound or a constraint is to be added */ - real_t *xiB, - real_t *xiC - ); - - -/** If Hessian type has been set by the user, nothing is done. - * Otherwise the Hessian type is set to HST_IDENTITY, HST_ZERO, or - * HST_POSDEF (default), respectively. - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_INDEFINITE */ -returnValue QProblem_determineHessianType( QProblem* _THIS ); - -/** Computes the Cholesky decomposition of the (simply projected) Hessian - * (i.e. R^T*R = Z^T*H*Z). It only works in the case where Z is a simple - * projection matrix! - * Note: If Hessian turns out not to be positive definite, the Hessian type - * is set to HST_SEMIDEF accordingly. - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblemBCPY_computeCholesky( QProblem* _THIS ); - -/** Obtains the desired working set for the auxiliary initial QP in - * accordance with the user specifications - * \return SUCCESSFUL_RETURN \n - RET_OBTAINING_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemBCPY_obtainAuxiliaryWorkingSet( QProblem* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - const real_t* const yOpt, /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - Bounds* const guessedBounds, /**< Guessed working set for solution (xOpt,yOpt). */ - Bounds* auxiliaryBounds /**< Input: Allocated bound object. \n - * Output: Working set for auxiliary QP. */ - ); - - -/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblem_backsolveR( QProblem* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - real_t* const a /**< Output: Solution vector */ - ); - -/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. \n - * Special variant for the case that _THIS function is called from within "removeBound()". - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblem_backsolveRrem( QProblem* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - BooleanType removingBound, /**< Indicates if function is called from "removeBound()". */ - real_t* const a /**< Output: Solution vector */ - ); - - -/** Determines step direction of the shift of the QP data. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemBCPY_determineDataShift( QProblem* _THIS, - const real_t* const g_new, /**< New gradient vector. */ - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new, /**< New upper bounds. */ - real_t* const delta_g, /**< Output: Step direction of gradient vector. */ - real_t* const delta_lb, /**< Output: Step direction of lower bounds. */ - real_t* const delta_ub, /**< Output: Step direction of upper bounds. */ - BooleanType* Delta_bB_isZero /**< Output: Indicates if active bounds are to be shifted. */ - ); - - -/** Sets up internal QP data. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemBCPY_setupQPdataM( QProblem* _THIS, - DenseMatrix *_H, /**< Hessian matrix.*/ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data. If the current Hessian is trivial - * (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_NO_HESSIAN_SPECIFIED */ -returnValue QProblemBCPY_setupQPdata( QProblem* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data by loading it from files. If the current Hessian - * is trivial (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS \n - RET_NO_HESSIAN_SPECIFIED */ -returnValue QProblemBCPY_setupQPdataFromFile( QProblem* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix, of neighbouring QP to be solved, is stored. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Loads new QP vectors from files (internal members are not affected!). - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemBCPY_loadQPvectorsFromFile( QProblem* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - real_t* const g_new, /**< Output: Gradient of neighbouring QP to be solved. */ - real_t* const lb_new, /**< Output: Lower bounds of neighbouring QP to be solved */ - real_t* const ub_new /**< Output: Upper bounds of neighbouring QP to be solved */ - ); - - -/** Sets internal infeasibility flag and throws given error in case the far bound - * strategy is not enabled (as QP might actually not be infeasible in _THIS case). - * \return RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_ENSURELI_FAILED_CYCLING \n - RET_ENSURELI_FAILED_NOINDEX */ -returnValue QProblem_setInfeasibilityFlag( QProblem* _THIS, - returnValue returnvalue, /**< Returnvalue to be tunneled. */ - BooleanType doThrowError /**< Flag forcing to throw an error. */ - ); - - -/** Determines if next QP iteration can be performed within given CPU time limit. - * \return BT_TRUE: CPU time limit is exceeded, stop QP solution. \n - BT_FALSE: Sufficient CPU time for next QP iteration. */ -BooleanType QProblem_isCPUtimeLimitExceeded( QProblem* _THIS, - const real_t* const cputime, /**< Maximum CPU time allowed for QP solution. */ - real_t starttime, /**< Start time of current QP solution. */ - int nWSR /**< Number of working set recalculations performed so far. */ - ); - - -/** Regularise Hessian matrix by adding a scaled identity matrix to it. - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_ALREADY_REGULARISED */ -returnValue QProblem_regulariseHessian( QProblem* _THIS ); - - -/** Sets Hessian matrix of the QP. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblem_setHM( QProblem* _THIS, - DenseMatrix* H_new /**< New Hessian matrix. */ - ); - -/** Sets dense Hessian matrix of the QP. - * If a null pointer is passed and - * a) hessianType is HST_IDENTITY, nothing is done, - * b) hessianType is not HST_IDENTITY, Hessian matrix is set to zero. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblem_setH( QProblem* _THIS, - real_t* const H_new /**< New dense Hessian matrix (with correct dimension!). */ - ); - -/** Changes gradient vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setG( QProblem* _THIS, - const real_t* const g_new /**< New gradient vector (with correct dimension!). */ - ); - -/** Changes lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setLB( QProblem* _THIS, - const real_t* const lb_new /**< New lower bound vector (with correct dimension!). */ - ); - -/** Changes single entry of lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblem_setLBn( QProblem* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of lower bound vector. */ - ); - -/** Changes upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setUB( QProblem* _THIS, - const real_t* const ub_new /**< New upper bound vector (with correct dimension!). */ - ); - -/** Changes single entry of upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblem_setUBn( QProblem* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of upper bound vector. */ - ); - - - -/** Compute relative length of homotopy in data space for termination - * criterion. - * \return Relative length in data space. */ -real_t QProblemBCPY_getRelativeHomotopyLength( QProblem* _THIS, - const real_t* const g_new, /**< Final gradient. */ - const real_t* const lb_new, /**< Final lower variable bounds. */ - const real_t* const ub_new /**< Final upper variable bounds. */ - ); - - - -/** Performs robustified ratio test yield the maximum possible step length - * along the homotopy path. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performRatioTestB( QProblem* _THIS, - int nIdx, /**< Number of ratios to be checked. */ - const int* const idxList, /**< Array containing the indices of all ratios to be checked. */ - Bounds* const subjectTo, /**< Bound object corresponding to ratios to be checked. */ - const real_t* const num, /**< Array containing all numerators for performing the ratio test. */ - const real_t* const den, /**< Array containing all denominators for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t, /**< Output: Maximum possible step length along the homotopy path. */ - int* BC_idx /**< Output: Index of blocking constraint. */ - ); - -/** Checks whether given ratio is blocking, i.e. limits the maximum step length - * along the homotopy path to a value lower than given one. - * \return SUCCESSFUL_RETURN */ -static inline BooleanType QProblem_isBlocking( QProblem* _THIS, - real_t num, /**< Numerator for performing the ratio test. */ - real_t den, /**< Denominator for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t /**< Input: Current maximum step length along the homotopy path, - * Output: Updated maximum possible step length along the homotopy path. */ - ); - - -/** ... - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue QProblem_writeQpDataIntoMatFile( QProblem* _THIS, - const char* const filename /**< Mat file name. */ - ); - -/** ... -* \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue QProblem_writeQpWorkspaceIntoMatFile( QProblem* _THIS, - const char* const filename /**< Mat file name. */ - ); - - -/* - * g e t B o u n d s - */ -static inline returnValue QProblem_getBounds( QProblem* _THIS, Bounds* _bounds ) -{ - int nV = QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - _bounds = _THIS->bounds; - - return SUCCESSFUL_RETURN; -} - - -/* - * g e t N V - */ -static inline int QProblem_getNV( QProblem* _THIS ) -{ - return Bounds_getNV( _THIS->bounds ); -} - - -/* - * g e t N F R - */ -static inline int QProblem_getNFR( QProblem* _THIS ) -{ - return Bounds_getNFR( _THIS->bounds ); -} - - -/* - * g e t N F X - */ -static inline int QProblem_getNFX( QProblem* _THIS ) -{ - return Bounds_getNFX( _THIS->bounds ); -} - - -/* - * g e t N F V - */ -static inline int QProblem_getNFV( QProblem* _THIS ) -{ - return Bounds_getNFV( _THIS->bounds ); -} - - -/* - * g e t S t a t u s - */ -static inline QProblemStatus QProblem_getStatus( QProblem* _THIS ) -{ - return _THIS->status; -} - - -/* - * i s I n i t i a l i s e d - */ -static inline BooleanType QProblem_isInitialised( QProblem* _THIS ) -{ - if ( _THIS->status == QPS_NOTINITIALISED ) - return BT_FALSE; - else - return BT_TRUE; -} - - -/* - * i s S o l v e d - */ -static inline BooleanType QProblem_isSolved( QProblem* _THIS ) -{ - if ( _THIS->status == QPS_SOLVED ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * i s I n f e a s i b l e - */ -static inline BooleanType QProblem_isInfeasible( QProblem* _THIS ) -{ - return _THIS->infeasible; -} - - -/* - * i s U n b o u n d e d - */ -static inline BooleanType QProblem_isUnbounded( QProblem* _THIS ) -{ - return _THIS->unbounded; -} - - -/* - * g e t H e s s i a n T y p e - */ -static inline HessianType QProblem_getHessianType( QProblem* _THIS ) -{ - return _THIS->hessianType; -} - - -/* - * s e t H e s s i a n T y p e - */ -static inline returnValue QProblem_setHessianType( QProblem* _THIS, HessianType _hessianType ) -{ - _THIS->hessianType = _hessianType; - return SUCCESSFUL_RETURN; -} - - -/* - * u s i n g R e g u l a r i s a t i o n - */ -static inline BooleanType QProblem_usingRegularisation( QProblem* _THIS ) -{ - if ( _THIS->regVal > QPOASES_ZERO ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * g e t O p t i o n s - */ -static inline Options QProblem_getOptions( QProblem* _THIS ) -{ - return _THIS->options; -} - - -/* - * s e t O p t i o n s - */ -static inline returnValue QProblem_setOptions( QProblem* _THIS, - Options _options - ) -{ - OptionsCPY( &_options,&(_THIS->options) ); - Options_ensureConsistency( &(_THIS->options) ); - - QProblem_setPrintLevel( _THIS,_THIS->options.printLevel ); - - return SUCCESSFUL_RETURN; -} - - -/* - * g e t P r i n t L e v e l - */ -static inline PrintLevel QProblem_getPrintLevel( QProblem* _THIS ) -{ - return _THIS->options.printLevel; -} - - -/* - * g e t C o u n t - */ -static inline unsigned int QProblem_getCount( QProblem* _THIS ) -{ - return _THIS->count; -} - - -/* - * r e s e t C o u n t e r - */ -static inline returnValue QProblem_resetCounter( QProblem* _THIS ) -{ - _THIS->count = 0; - return SUCCESSFUL_RETURN; -} - - - -/***************************************************************************** - * P R O T E C T E D * - *****************************************************************************/ - - -/* - * s e t H - */ -static inline returnValue QProblem_setHM( QProblem* _THIS, DenseMatrix* H_new ) -{ - if ( H_new == 0 ) - return QProblem_setH( _THIS,(real_t*)0 ); - else - return QProblem_setH( _THIS,DenseMatrix_getVal(H_new) ); -} - - -/* - * s e t H - */ -static inline returnValue QProblem_setH( QProblem* _THIS, real_t* const H_new ) -{ - /* if null pointer is passed, Hessian is set to zero matrix - * (or stays identity matrix) */ - if ( H_new == 0 ) - { - if ( _THIS->hessianType == HST_IDENTITY ) - return SUCCESSFUL_RETURN; - - _THIS->hessianType = HST_ZERO; - - _THIS->H = 0; - } - else - { - DenseMatrixCON( _THIS->H,QProblem_getNV( _THIS ),QProblem_getNV( _THIS ),QProblem_getNV( _THIS ),H_new ); - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t G - */ -static inline returnValue QProblem_setG( QProblem* _THIS, const real_t* const g_new ) -{ - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( g_new == 0 ) - return THROWERROR( RET_INVALID_ARGUMENTS ); - - memcpy( _THIS->g,g_new,nV*sizeof(real_t) ); - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B - */ -static inline returnValue QProblem_setLB( QProblem* _THIS, const real_t* const lb_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( lb_new != 0 ) - { - memcpy( _THIS->lb,lb_new,nV*sizeof(real_t) ); - } - else - { - /* if no lower bounds are specified, set them to -infinity */ - for( i=0; ilb[i] = -QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B - */ -static inline returnValue QProblem_setLBn( QProblem* _THIS, int number, real_t value ) -{ - int nV = QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nV ) ) - { - _THIS->lb[number] = value; - return SUCCESSFUL_RETURN; - } - else - { - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); - } -} - - -/* - * s e t U B - */ -static inline returnValue QProblem_setUB( QProblem* _THIS, const real_t* const ub_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ub_new != 0 ) - { - memcpy( _THIS->ub,ub_new,nV*sizeof(real_t) ); - } - else - { - /* if no upper bounds are specified, set them to infinity */ - for( i=0; iub[i] = QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t U B - */ -static inline returnValue QProblem_setUBn( QProblem* _THIS, int number, real_t value ) -{ - int nV = QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nV ) ) - { - _THIS->ub[number] = value; - - return SUCCESSFUL_RETURN; - } - else - { - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); - } -} - - - -/* - * i s B l o c k i n g - */ -static inline BooleanType QProblem_isBlocking( QProblem* _THIS, - real_t num, - real_t den, - real_t epsNum, - real_t epsDen, - real_t* t - ) -{ - if ( ( den >= epsDen ) && ( num >= epsNum ) ) - { - if ( num < (*t)*den ) - return BT_TRUE; - } - - return BT_FALSE; -} - - - -/* - * g e t C o n s t r a i n t s - */ -static inline returnValue QProblem_getConstraints( QProblem* _THIS, Constraints* _constraints ) -{ - int nV = QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - ConstraintsCPY( _THIS->constraints,_constraints ); - - return SUCCESSFUL_RETURN; -} - - - -/* - * g e t N C - */ -static inline int QProblem_getNC( QProblem* _THIS ) -{ - return Constraints_getNC( _THIS->constraints ); -} - - -/* - * g e t N E C - */ -static inline int QProblem_getNEC( QProblem* _THIS ) -{ - return Constraints_getNEC( _THIS->constraints ); -} - - -/* - * g e t N A C - */ -static inline int QProblem_getNAC( QProblem* _THIS ) -{ - return Constraints_getNAC( _THIS->constraints ); -} - - -/* - * g e t N I A C - */ -static inline int QProblem_getNIAC( QProblem* _THIS ) -{ - return Constraints_getNIAC( _THIS->constraints ); -} - - - -/***************************************************************************** - * P R O T E C T E D * - *****************************************************************************/ - - -/* - * s e t A - */ -static inline returnValue QProblem_setAM( QProblem* _THIS, DenseMatrix *A_new ) -{ - if ( A_new == 0 ) - return QProblem_setA( _THIS,(real_t*)0 ); - else - return QProblem_setA( _THIS,DenseMatrix_getVal(A_new) ); -} - - -/* - * s e t A - */ -static inline returnValue QProblem_setA( QProblem* _THIS, real_t* const A_new ) -{ - int j; - int nV = QProblem_getNV( _THIS ); - int nC = QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( A_new == 0 ) - return THROWERROR( RET_INVALID_ARGUMENTS ); - - DenseMatrixCON( _THIS->A,QProblem_getNC( _THIS ),QProblem_getNV( _THIS ),QProblem_getNV( _THIS ),A_new ); - - DenseMatrix_times( _THIS->A,1, 1.0, _THIS->x, nV, 0.0, _THIS->Ax, nC); - - for( j=0; jAx_u[j] = _THIS->ubA[j] - _THIS->Ax[j]; - _THIS->Ax_l[j] = _THIS->Ax[j] - _THIS->lbA[j]; - - /* (ckirches) disable constraints with empty rows */ - if ( qpOASES_isZero( DenseMatrix_getRowNorm( _THIS->A,j,2 ),QPOASES_ZERO ) == BT_TRUE ) - Constraints_setType( _THIS->constraints,j,ST_DISABLED ); - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B A - */ -static inline returnValue QProblem_setLBA( QProblem* _THIS, const real_t* const lbA_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - unsigned int nC = (unsigned int)QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( lbA_new != 0 ) - { - memcpy( _THIS->lbA,lbA_new,nC*sizeof(real_t) ); - } - else - { - /* if no lower constraints' bounds are specified, set them to -infinity */ - for( i=0; ilbA[i] = -QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B A - */ -static inline returnValue QProblem_setLBAn( QProblem* _THIS, int number, real_t value ) -{ - int nV = QProblem_getNV( _THIS ); - int nC = QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nC ) ) - { - _THIS->lbA[number] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t U B A - */ -static inline returnValue QProblem_setUBA( QProblem* _THIS, const real_t* const ubA_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - unsigned int nC = (unsigned int)QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ubA_new != 0 ) - { - memcpy( _THIS->ubA,ubA_new,nC*sizeof(real_t) ); - } - else - { - /* if no upper constraints' bounds are specified, set them to infinity */ - for( i=0; iubA[i] = QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t U B A - */ -static inline returnValue QProblem_setUBAn( QProblem* _THIS, int number, real_t value ) -{ - int nV = QProblem_getNV( _THIS ); - int nC = QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nC ) ) - { - _THIS->ubA[number] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_QPROBLEM_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/QProblemB.h b/third_party/acados/include/qpOASES_e/QProblemB.h deleted file mode 100644 index ee5157dda77e8b..00000000000000 --- a/third_party/acados/include/qpOASES_e/QProblemB.h +++ /dev/null @@ -1,1641 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/QProblemB.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the QProblemB class which is able to use the newly - * developed online active set strategy for parametric quadratic programming - * for problems with (simple) bounds only. - */ - - - -#ifndef QPOASES_QPROBLEMB_H -#define QPOASES_QPROBLEMB_H - - -#include -#include -#include -#include - - -BEGIN_NAMESPACE_QPOASES - -typedef struct { - Bounds *emptyBounds; - Bounds *auxiliaryBounds; - - real_t *ub_new_far; - real_t *lb_new_far; - - real_t *g_new; - real_t *lb_new; - real_t *ub_new; - - real_t *g_new2; - real_t *lb_new2; - real_t *ub_new2; - - real_t *Hx; - - real_t *_H; - - real_t *g_original; - real_t *lb_original; - real_t *ub_original; - - real_t *delta_xFR; - real_t *delta_xFX; - real_t *delta_yFX; - real_t *delta_g; - real_t *delta_lb; - real_t *delta_ub; - - real_t *gMod; - - real_t *num; - real_t *den; - - real_t *rhs; - real_t *r; -} QProblemB_ws; - -int QProblemB_ws_calculateMemorySize( unsigned int nV ); - -char *QProblemB_ws_assignMemory( unsigned int nV, QProblemB_ws **mem, void *raw_memory ); - -QProblemB_ws *QProblemB_ws_createMemory( unsigned int nV ); - - -/** - * \brief Implements the online active set strategy for box-constrained QPs. - * - * Class for setting up and solving quadratic programs with bounds (= box constraints) only. - * The main feature is the possibility to use the newly developed online active set strategy - * for parametric quadratic programming. - * - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - QProblemB_ws *ws; - Bounds *bounds; /**< Data structure for problem's bounds. */ - Flipper *flipper; /**< Struct for making a temporary copy of the matrix factorisations. */ - - DenseMatrix* H; /**< Hessian matrix pointer. */ - - Options options; /**< Struct containing all user-defined options for solving QPs. */ - TabularOutput tabularOutput; /**< Struct storing information for tabular output (printLevel == PL_TABULAR). */ - - real_t *g; /**< Gradient. */ - real_t *lb; /**< Lower bound vector (on variables). */ - real_t *ub; /**< Upper bound vector (on variables). */ - - real_t *R; /**< Cholesky factor of H (i.e. H = R^T*R). */ - - real_t *x; /**< Primal solution vector. */ - real_t *y; /**< Dual solution vector. */ - - real_t *delta_xFR_TMP; /**< Temporary for determineStepDirection */ - - real_t tau; /**< Last homotopy step length. */ - real_t regVal; /**< Holds the offset used to regularise Hessian matrix (zero by default). */ - - real_t ramp0; /**< Start value for Ramping Strategy. */ - real_t ramp1; /**< Final value for Ramping Strategy. */ - - QProblemStatus status; /**< Current status of the solution process. */ - HessianType hessianType; /**< Type of Hessian matrix. */ - - BooleanType haveCholesky; /**< Flag indicating whether Cholesky decomposition has already been setup. */ - BooleanType infeasible; /**< QP infeasible? */ - BooleanType unbounded; /**< QP unbounded? */ - - int rampOffset; /**< Offset index for Ramping. */ - unsigned int count; /**< Counts the number of hotstart function calls (internal usage only!). */ -} QProblemB; - -int QProblemB_calculateMemorySize( unsigned int nV ); - -char *QProblemB_assignMemory( unsigned int nV, QProblemB **mem, void *raw_memory ); - -QProblemB *QProblemB_createMemory( unsigned int nV ); - - -/** Constructor which takes the QP dimension and Hessian type - * information. If the Hessian is the zero (i.e. HST_ZERO) or the - * identity matrix (i.e. HST_IDENTITY), respectively, no memory - * is allocated for it and a NULL pointer can be passed for it - * to the init() functions. */ -void QProblemBCON( QProblemB* _THIS, - int _nV, /**< Number of variables. */ - HessianType _hessianType /**< Type of Hessian matrix. */ - ); - -void QProblemBCPY( QProblemB* FROM, - QProblemB* TO - ); - - -/** Clears all data structures of QProblemB except for QP data. - * \return SUCCESSFUL_RETURN \n - RET_RESET_FAILED */ -returnValue QProblemB_reset( QProblemB* _THIS ); - - -/** Initialises a simply bounded QP problem with given QP data and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_initM( QProblemB* _THIS, - DenseMatrix *_H, /**< Hessian matrix. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a simply bounded QP problem with given QP data and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_init( QProblemB* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a simply bounded QP problem with given QP data to be read from files and solves it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_UNABLE_TO_READ_FILE */ -returnValue QProblemB_initF( QProblemB* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix is stored. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient vector is stored. */ - const char* const lb_file, /**< Name of file where lower bound vector. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bound vector. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a simply bounded QP problem with given QP data and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB from yOpt != 0, \n - * 4. 0, 0, gB: starts with xOpt = 0, yOpt = 0 and gB, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB from yOpt != 0, \n - * 6. xOpt, 0, gB: starts with xOpt, yOpt = 0 and gB, \n - * 7. xOpt, yOpt, gB: starts with xOpt, yOpt and gB (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_initMW( QProblemB* _THIS, - DenseMatrix *_H, /**< Hessian matrix. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, all bounds are assumed inactive!) */ - const real_t* const _R /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Initialises a simply bounded QP problem with given QP data and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB from yOpt != 0, \n - * 4. 0, 0, gB: starts with xOpt = 0, yOpt = 0 and gB, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB from yOpt != 0, \n - * 6. xOpt, 0, gB: starts with xOpt, yOpt = 0 and gB, \n - * 7. xOpt, yOpt, gB: starts with xOpt, yOpt and gB (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_initW( QProblemB* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, all bounds are assumed inactive!) */ - const real_t* const _R /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Initialises a simply bounded QP problem with given QP data to be read from files and solves it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB from yOpt != 0, \n - * 4. 0, 0, gB: starts with xOpt = 0, yOpt = 0 and gB, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB from yOpt != 0, \n - * 6. xOpt, 0, gB: starts with xOpt, yOpt = 0 and gB, \n - * 7. xOpt, yOpt, gB: starts with xOpt, yOpt and gB (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_UNABLE_TO_READ_FILE */ -returnValue QProblemB_initFW( QProblemB* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix is stored. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient vector is stored. */ - const char* const lb_file, /**< Name of file where lower bound vector. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bound vector. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, all bounds are assumed inactive!) */ - const char* const R_file /**< Name of the file where a pre-computed (upper triangular) Cholesky factor - of the Hessian matrix is stored. \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - - -/** Solves an initialised QP sequence using the online active set strategy. - * By default, QP solution is started from previous solution. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblemB_hotstart( QProblemB* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QP sequence using the online active set strategy, - * where QP data is read from files. QP solution is started from previous solution. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_hotstartF( QProblemB* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QP sequence using the online active set strategy. - * By default, QP solution is started from previous solution. If a guess - * for the working set is provided, an initialised homotopy is performed. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_SETUP_AUXILIARYQP_FAILED */ -returnValue QProblemB_hotstartW( QProblemB* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - Bounds* const guessedBounds /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set is kept!) */ - ); - -/** Solves an initialised QP sequence using the online active set strategy, - * where QP data is read from files. - * By default, QP solution is started from previous solution. If a guess - * for the working set is provided, an initialised homotopy is performed. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS \n - RET_SETUP_AUXILIARYQP_FAILED */ -returnValue QProblemB_hotstartFW( QProblemB* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - Bounds* const guessedBounds /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set is kept!) */ - ); - - -/** Writes a vector with the state of the working set - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblemB_getWorkingSet( QProblemB* _THIS, - real_t* workingSet /** Output: array containing state of the working set. */ - ); - -/** Writes a vector with the state of the working set of bounds - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblemB_getWorkingSetBounds( QProblemB* _THIS, - real_t* workingSetB /** Output: array containing state of the working set of bounds. */ - ); - -/** Writes a vector with the state of the working set of constraints - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblemB_getWorkingSetConstraints( QProblemB* _THIS, - real_t* workingSetC /** Output: array containing state of the working set of constraints. */ - ); - - -/** Returns current bounds object of the QP (deep copy). - * \return SUCCESSFUL_RETURN \n - RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblemB_getBounds( QProblemB* _THIS, - Bounds* _bounds /** Output: Bounds object. */ - ); - - -/** Returns the number of variables. - * \return Number of variables. */ -static inline int QProblemB_getNV( QProblemB* _THIS ); - -/** Returns the number of free variables. - * \return Number of free variables. */ -static inline int QProblemB_getNFR( QProblemB* _THIS ); - -/** Returns the number of fixed variables. - * \return Number of fixed variables. */ -static inline int QProblemB_getNFX( QProblemB* _THIS ); - -/** Returns the number of implicitly fixed variables. - * \return Number of implicitly fixed variables. */ -static inline int QProblemB_getNFV( QProblemB* _THIS ); - -/** Returns the dimension of null space. - * \return Dimension of null space. */ -int QProblemB_getNZ( QProblemB* _THIS ); - - -/** Returns the optimal objective function value. - * \return finite value: Optimal objective function value (QP was solved) \n - +infinity: QP was not yet solved */ -real_t QProblemB_getObjVal( QProblemB* _THIS ); - -/** Returns the objective function value at an arbitrary point x. - * \return Objective function value at point x */ -real_t QProblemB_getObjValX( QProblemB* _THIS, - const real_t* const _x /**< Point at which the objective function shall be evaluated. */ - ); - -/** Returns the primal solution vector. - * \return SUCCESSFUL_RETURN \n - RET_QP_NOT_SOLVED */ -returnValue QProblemB_getPrimalSolution( QProblemB* _THIS, - real_t* const xOpt /**< Output: Primal solution vector (if QP has been solved). */ - ); - -/** Returns the dual solution vector. - * \return SUCCESSFUL_RETURN \n - RET_QP_NOT_SOLVED */ -returnValue QProblemB_getDualSolution( QProblemB* _THIS, - real_t* const yOpt /**< Output: Dual solution vector (if QP has been solved). */ - ); - - -/** Returns status of the solution process. - * \return Status of solution process. */ -static inline QProblemStatus QProblemB_getStatus( QProblemB* _THIS ); - - -/** Returns if the QProblem object is initialised. - * \return BT_TRUE: QProblemB initialised \n - BT_FALSE: QProblemB not initialised */ -static inline BooleanType QProblemB_isInitialised( QProblemB* _THIS ); - -/** Returns if the QP has been solved. - * \return BT_TRUE: QProblemB solved \n - BT_FALSE: QProblemB not solved */ -static inline BooleanType QProblemB_isSolved( QProblemB* _THIS ); - -/** Returns if the QP is infeasible. - * \return BT_TRUE: QP infeasible \n - BT_FALSE: QP feasible (or not known to be infeasible!) */ -static inline BooleanType QProblemB_isInfeasible( QProblemB* _THIS ); - -/** Returns if the QP is unbounded. - * \return BT_TRUE: QP unbounded \n - BT_FALSE: QP unbounded (or not known to be unbounded!) */ -static inline BooleanType QProblemB_isUnbounded( QProblemB* _THIS ); - - -/** Returns Hessian type flag (type is not determined due to _THIS call!). - * \return Hessian type. */ -static inline HessianType QProblemB_getHessianType( QProblemB* _THIS ); - -/** Changes the print level. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblemB_setHessianType( QProblemB* _THIS, - HessianType _hessianType /**< New Hessian type. */ - ); - -/** Returns if the QP has been internally regularised. - * \return BT_TRUE: Hessian is internally regularised for QP solution \n - BT_FALSE: No internal Hessian regularisation is used for QP solution */ -static inline BooleanType QProblemB_usingRegularisation( QProblemB* _THIS ); - -/** Returns current options struct. - * \return Current options struct. */ -static inline Options QProblemB_getOptions( QProblemB* _THIS ); - -/** Overrides current options with given ones. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblemB_setOptions( QProblemB* _THIS, - Options _options /**< New options. */ - ); - -/** Returns the print level. - * \return Print level. */ -static inline PrintLevel QProblemB_getPrintLevel( QProblemB* _THIS ); - -/** Changes the print level. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_setPrintLevel( QProblemB* _THIS, - PrintLevel _printlevel /**< New print level. */ - ); - -/** Returns the current number of QP problems solved. - * \return Number of QP problems solved. */ -static inline unsigned int QProblemB_getCount( QProblemB* _THIS ); - -/** Resets QP problem counter (to zero). - * \return SUCCESSFUL_RETURN. */ -static inline returnValue QProblemB_resetCounter( QProblemB* _THIS ); - - -/** Prints concise list of properties of the current QP. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblemB_printProperties( QProblemB* _THIS ); - -/** Prints a list of all options and their current values. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblemB_printOptions( QProblemB* _THIS ); - - -/** If Hessian type has been set by the user, nothing is done. - * Otherwise the Hessian type is set to HST_IDENTITY, HST_ZERO, or - * HST_POSDEF (default), respectively. - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_INDEFINITE */ -returnValue QProblemB_determineHessianType( QProblemB* _THIS ); - -/** Determines type of existing constraints and bounds (i.e. implicitly fixed, unbounded etc.). - * \return SUCCESSFUL_RETURN \n - RET_SETUPSUBJECTTOTYPE_FAILED */ -returnValue QProblemB_setupSubjectToType( QProblemB* _THIS ); - -/** Determines type of new constraints and bounds (i.e. implicitly fixed, unbounded etc.). - * \return SUCCESSFUL_RETURN \n - RET_SETUPSUBJECTTOTYPE_FAILED */ -returnValue QProblemB_setupSubjectToTypeNew( QProblemB* _THIS, - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new /**< New upper bounds. */ - ); - -/** Computes the Cholesky decomposition of the (simply projected) Hessian - * (i.e. R^T*R = Z^T*H*Z). It only works in the case where Z is a simple - * projection matrix! - * Note: If Hessian turns out not to be positive definite, the Hessian type - * is set to HST_SEMIDEF accordingly. - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblemB_computeCholesky( QProblemB* _THIS ); - -/** Computes initial Cholesky decomposition of the projected Hessian making - * use of the function setupCholeskyDecomposition() or setupCholeskyDecompositionProjected(). - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblemB_setupInitialCholesky( QProblemB* _THIS ); - - -/** Obtains the desired working set for the auxiliary initial QP in - * accordance with the user specifications - * \return SUCCESSFUL_RETURN \n - RET_OBTAINING_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_obtainAuxiliaryWorkingSet( QProblemB* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - const real_t* const yOpt, /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - Bounds* const guessedBounds, /**< Guessed working set for solution (xOpt,yOpt). */ - Bounds* auxiliaryBounds /**< Input: Allocated bound object. \n - * Ouput: Working set for auxiliary QP. */ - ); - -/** Decides if lower bounds are smaller than upper bounds - * - * \return SUCCESSFUL_RETURN \n - * RET_QP_INFEASIBLE */ -returnValue QProblemB_areBoundsConsistent( QProblemB* _THIS, - const real_t* const lb, /**< Vector of lower bounds*/ - const real_t* const ub /**< Vector of upper bounds*/ - ); - -/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblemB_backsolveR( QProblemB* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - real_t* const a /**< Output: Solution vector */ - ); - -/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. \n - * Special variant for the case that _THIS function is called from within "removeBound()". - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblemB_backsolveRrem( QProblemB* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - BooleanType removingBound, /**< Indicates if function is called from "removeBound()". */ - real_t* const a /**< Output: Solution vector */ - ); - - -/** Determines step direction of the shift of the QP data. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_determineDataShift( QProblemB* _THIS, - const real_t* const g_new, /**< New gradient vector. */ - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new, /**< New upper bounds. */ - real_t* const delta_g, /**< Output: Step direction of gradient vector. */ - real_t* const delta_lb, /**< Output: Step direction of lower bounds. */ - real_t* const delta_ub, /**< Output: Step direction of upper bounds. */ - BooleanType* Delta_bB_isZero/**< Output: Indicates if active bounds are to be shifted. */ - ); - - -/** Sets up internal QP data. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_setupQPdataM( QProblemB* _THIS, - DenseMatrix *_H, /**< Hessian matrix.*/ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data. If the current Hessian is trivial - * (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_NO_HESSIAN_SPECIFIED */ -returnValue QProblemB_setupQPdata( QProblemB* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data by loading it from files. If the current Hessian - * is trivial (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS \n - RET_NO_HESSIAN_SPECIFIED */ -returnValue QProblemB_setupQPdataFromFile( QProblemB* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix, of neighbouring QP to be solved, is stored. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Loads new QP vectors from files (internal members are not affected!). - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_loadQPvectorsFromFile( QProblemB* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - real_t* const g_new, /**< Output: Gradient of neighbouring QP to be solved. */ - real_t* const lb_new, /**< Output: Lower bounds of neighbouring QP to be solved */ - real_t* const ub_new /**< Output: Upper bounds of neighbouring QP to be solved */ - ); - - -/** Sets internal infeasibility flag and throws given error in case the far bound - * strategy is not enabled (as QP might actually not be infeasible in _THIS case). - * \return RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_ENSURELI_FAILED_CYCLING \n - RET_ENSURELI_FAILED_NOINDEX */ -returnValue QProblemB_setInfeasibilityFlag( QProblemB* _THIS, - returnValue returnvalue, /**< Returnvalue to be tunneled. */ - BooleanType doThrowError /**< Flag forcing to throw an error. */ - ); - - -/** Determines if next QP iteration can be performed within given CPU time limit. - * \return BT_TRUE: CPU time limit is exceeded, stop QP solution. \n - BT_FALSE: Sufficient CPU time for next QP iteration. */ -BooleanType QProblemB_isCPUtimeLimitExceeded( QProblemB* _THIS, - const real_t* const cputime, /**< Maximum CPU time allowed for QP solution. */ - real_t starttime, /**< Start time of current QP solution. */ - int nWSR /**< Number of working set recalculations performed so far. */ - ); - - -/** Regularise Hessian matrix by adding a scaled identity matrix to it. - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_ALREADY_REGULARISED */ -returnValue QProblemB_regulariseHessian( QProblemB* _THIS ); - - -/** Sets Hessian matrix of the QP. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblemB_setHM( QProblemB* _THIS, - DenseMatrix* H_new /**< New Hessian matrix. */ - ); - -/** Sets dense Hessian matrix of the QP. - * If a null pointer is passed and - * a) hessianType is HST_IDENTITY, nothing is done, - * b) hessianType is not HST_IDENTITY, Hessian matrix is set to zero. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblemB_setH( QProblemB* _THIS, - real_t* const H_new /**< New dense Hessian matrix (with correct dimension!). */ - ); - -/** Changes gradient vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblemB_setG( QProblemB* _THIS, - const real_t* const g_new /**< New gradient vector (with correct dimension!). */ - ); - -/** Changes lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblemB_setLB( QProblemB* _THIS, - const real_t* const lb_new /**< New lower bound vector (with correct dimension!). */ - ); - -/** Changes single entry of lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP \n - * RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblemB_setLBn( QProblemB* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of lower bound vector. */ - ); - -/** Changes upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblemB_setUB( QProblemB* _THIS, - const real_t* const ub_new /**< New upper bound vector (with correct dimension!). */ - ); - -/** Changes single entry of upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP \n - * RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblemB_setUBn( QProblemB* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of upper bound vector. */ - ); - - -/** Computes parameters for the Givens matrix G for which [x,y]*G = [z,0] - * \return SUCCESSFUL_RETURN */ -static inline void QProblemB_computeGivens( real_t xold, /**< Matrix entry to be normalised. */ - real_t yold, /**< Matrix entry to be annihilated. */ - real_t* xnew, /**< Output: Normalised matrix entry. */ - real_t* ynew, /**< Output: Annihilated matrix entry. */ - real_t* c, /**< Output: Cosine entry of Givens matrix. */ - real_t* s /**< Output: Sine entry of Givens matrix. */ - ); - -/** Applies Givens matrix determined by c and s (cf. computeGivens). - * \return SUCCESSFUL_RETURN */ -static inline void QProblemB_applyGivens( real_t c, /**< Cosine entry of Givens matrix. */ - real_t s, /**< Sine entry of Givens matrix. */ - real_t nu, /**< Further factor: s/(1+c). */ - real_t xold, /**< Matrix entry to be transformed corresponding to - * the normalised entry of the original matrix. */ - real_t yold, /**< Matrix entry to be transformed corresponding to - * the annihilated entry of the original matrix. */ - real_t* xnew, /**< Output: Transformed matrix entry corresponding to - * the normalised entry of the original matrix. */ - real_t* ynew /**< Output: Transformed matrix entry corresponding to - * the annihilated entry of the original matrix. */ - ); - - - -/** Compute relative length of homotopy in data space for termination - * criterion. - * \return Relative length in data space. */ -real_t QProblemB_getRelativeHomotopyLength( QProblemB* _THIS, - const real_t* const g_new, /**< Final gradient. */ - const real_t* const lb_new, /**< Final lower variable bounds. */ - const real_t* const ub_new /**< Final upper variable bounds. */ - ); - -/** Ramping Strategy to avoid ties. Modifies homotopy start without - * changing current active set. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_performRamping( QProblemB* _THIS ); - - -/** ... */ -returnValue QProblemB_updateFarBounds( QProblemB* _THIS, - real_t curFarBound, /**< ... */ - int nRamp, /**< ... */ - const real_t* const lb_new, /**< ... */ - real_t* const lb_new_far, /**< ... */ - const real_t* const ub_new, /**< ... */ - real_t* const ub_new_far /**< ... */ - ); - - - -/** Performs robustified ratio test yield the maximum possible step length - * along the homotopy path. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_performRatioTestB( QProblemB* _THIS, - int nIdx, /**< Number of ratios to be checked. */ - const int* const idxList, /**< Array containing the indices of all ratios to be checked. */ - Bounds* const subjectTo, /**< Bound object corresponding to ratios to be checked. */ - const real_t* const num, /**< Array containing all numerators for performing the ratio test. */ - const real_t* const den, /**< Array containing all denominators for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t, /**< Output: Maximum possible step length along the homotopy path. */ - int* BC_idx /**< Output: Index of blocking constraint. */ - ); - -/** Checks whether given ratio is blocking, i.e. limits the maximum step length - * along the homotopy path to a value lower than given one. - * \return SUCCESSFUL_RETURN */ -static inline BooleanType QProblemB_isBlocking( QProblemB* _THIS, - real_t num, /**< Numerator for performing the ratio test. */ - real_t den, /**< Denominator for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t /**< Input: Current maximum step length along the homotopy path, - * Output: Updated maximum possible step length along the homotopy path. */ - ); - - -/** Solves a QProblemB whose QP data is assumed to be stored in the member variables. - * A guess for its primal/dual optimal solution vectors and the corresponding - * optimal working set can be provided. - * Note: This function is internally called by all init functions! - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED */ -returnValue QProblemB_solveInitialQP( QProblemB* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector.*/ - const real_t* const yOpt, /**< Optimal dual solution vector. */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - const real_t* const _R, /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - * Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - * Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QProblemB using online active set strategy. - * Note: This function is internally called by all hotstart functions! - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblemB_solveQP( QProblemB* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - int nWSRperformed, /**< Number of working set recalculations already performed to solve - this QP within previous solveQP() calls. This number is - always zero, except for successive calls from solveRegularisedQP() - or when using the far bound strategy. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Solves an initialised QProblemB using online active set strategy. - * Note: This function is internally called by all hotstart functions! - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblemB_solveRegularisedQP( QProblemB* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - int nWSRperformed, /**< Number of working set recalculations already performed to solve - this QP within previous solveRegularisedQP() calls. This number is - always zero, except for successive calls when using the far bound strategy. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Sets up bound data structure according to auxiliaryBounds. - * (If the working set shall be setup afresh, make sure that - * bounds data structure has been resetted!) - * \return SUCCESSFUL_RETURN \n - RET_SETUP_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS \n - RET_UNKNOWN_BUG */ -returnValue QProblemB_setupAuxiliaryWorkingSet( QProblemB* _THIS, - Bounds* const auxiliaryBounds, /**< Working set for auxiliary QP. */ - BooleanType setupAfresh /**< Flag indicating if given working set shall be - * setup afresh or by updating the current one. */ - ); - -/** Sets up the optimal primal/dual solution of the auxiliary initial QP. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_setupAuxiliaryQPsolution( QProblemB* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are set to zero. */ - const real_t* const yOpt /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are set to zero. */ - ); - -/** Sets up gradient of the auxiliary initial QP for given - * optimal primal/dual solution and given initial working set - * (assumes that members X, Y and BOUNDS have already been (ialised!). - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_setupAuxiliaryQPgradient( QProblemB* _THIS ); - -/** Sets up bounds of the auxiliary initial QP for given - * optimal primal/dual solution and given initial working set - * (assumes that members X, Y and BOUNDS have already been initialised!). - * \return SUCCESSFUL_RETURN \n - RET_UNKNOWN_BUG */ -returnValue QProblemB_setupAuxiliaryQPbounds( QProblemB* _THIS, - BooleanType useRelaxation /**< Flag indicating if inactive bounds shall be relaxed. */ - ); - - -/** Updates QP vectors, working sets and internal data structures in order to - start from an optimal solution corresponding to initial guesses of the working - set for bounds - * \return SUCCESSFUL_RETURN \n - * RET_SETUP_AUXILIARYQP_FAILED */ -returnValue QProblemB_setupAuxiliaryQP( QProblemB* _THIS, - Bounds* const guessedBounds /**< Initial guess for working set of bounds. */ - ); - -/** Determines step direction of the homotopy path. - * \return SUCCESSFUL_RETURN \n - RET_STEPDIRECTION_FAILED_CHOLESKY */ -returnValue QProblemB_determineStepDirection( QProblemB* _THIS, - const real_t* const delta_g, /**< Step direction of gradient vector. */ - const real_t* const delta_lb, /**< Step direction of lower bounds. */ - const real_t* const delta_ub, /**< Step direction of upper bounds. */ - BooleanType Delta_bB_isZero, /**< Indicates if active bounds are to be shifted. */ - real_t* const delta_xFX, /**< Output: Primal homotopy step direction of fixed variables. */ - real_t* const delta_xFR, /**< Output: Primal homotopy step direction of free variables. */ - real_t* const delta_yFX /**< Output: Dual homotopy step direction of fixed variables' multiplier. */ - ); - -/** Determines the maximum possible step length along the homotopy path - * and performs _THIS step (without changing working set). - * \return SUCCESSFUL_RETURN \n - * RET_QP_INFEASIBLE \n - */ -returnValue QProblemB_performStep( QProblemB* _THIS, - const real_t* const delta_g, /**< Step direction of gradient. */ - const real_t* const delta_lb, /**< Step direction of lower bounds. */ - const real_t* const delta_ub, /**< Step direction of upper bounds. */ - const real_t* const delta_xFX, /**< Primal homotopy step direction of fixed variables. */ - const real_t* const delta_xFR, /**< Primal homotopy step direction of free variables. */ - const real_t* const delta_yFX, /**< Dual homotopy step direction of fixed variables' multiplier. */ - int* BC_idx, /**< Output: Index of blocking constraint. */ - SubjectToStatus* BC_status /**< Output: Status of blocking constraint. */ - ); - -/** Updates active set. - * \return SUCCESSFUL_RETURN \n - RET_REMOVE_FROM_ACTIVESET_FAILED \n - RET_ADD_TO_ACTIVESET_FAILED */ -returnValue QProblemB_changeActiveSet( QProblemB* _THIS, - int BC_idx, /**< Index of blocking constraint. */ - SubjectToStatus BC_status /**< Status of blocking constraint. */ - ); - -/** Drift correction at end of each active set iteration - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_performDriftCorrection( QProblemB* _THIS ); - -/** Determines if it is more efficient to refactorise the matrices when - * hotstarting or not (i.e. better to update the existing factorisations). - * \return BT_TRUE iff matrices shall be refactorised afresh - */ -BooleanType QProblemB_shallRefactorise( QProblemB* _THIS, - Bounds* const guessedBounds /**< Guessed new working set. */ - ); - - -/** Adds a bound to active set (specialised version for the case where no constraints exist). - * \return SUCCESSFUL_RETURN \n - RET_ADDBOUND_FAILED */ -returnValue QProblemB_addBound( QProblemB* _THIS, - int number, /**< Number of bound to be added to active set. */ - SubjectToStatus B_status, /**< Status of new active bound. */ - BooleanType updateCholesky /**< Flag indicating if Cholesky decomposition shall be updated. */ - ); - -/** Removes a bounds from active set (specialised version for the case where no constraints exist). - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_NOT_SPD \n - RET_REMOVEBOUND_FAILED */ -returnValue QProblemB_removeBound( QProblemB* _THIS, - int number, /**< Number of bound to be removed from active set. */ - BooleanType updateCholesky /**< Flag indicating if Cholesky decomposition shall be updated. */ - ); - - -/** Prints concise information on the current iteration. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblemB_printIteration( QProblemB* _THIS, - int iter, /**< Number of current iteration. */ - int BC_idx, /**< Index of blocking bound. */ - SubjectToStatus BC_status, /**< Status of blocking bound. */ - real_t homotopyLength, /**< Current homotopy distance. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - - -/* - * g e t B o u n d s - */ -static inline returnValue QProblemB_getBounds( QProblemB* _THIS, Bounds* _bounds ) -{ - int nV = QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - _bounds = _THIS->bounds; - - return SUCCESSFUL_RETURN; -} - - -/* - * g e t N V - */ -static inline int QProblemB_getNV( QProblemB* _THIS ) -{ - return Bounds_getNV( _THIS->bounds ); -} - - -/* - * g e t N F R - */ -static inline int QProblemB_getNFR( QProblemB* _THIS ) -{ - return Bounds_getNFR( _THIS->bounds ); -} - - -/* - * g e t N F X - */ -static inline int QProblemB_getNFX( QProblemB* _THIS ) -{ - return Bounds_getNFX( _THIS->bounds ); -} - - -/* - * g e t N F V - */ -static inline int QProblemB_getNFV( QProblemB* _THIS ) -{ - return Bounds_getNFV( _THIS->bounds ); -} - - -/* - * g e t S t a t u s - */ -static inline QProblemStatus QProblemB_getStatus( QProblemB* _THIS ) -{ - return _THIS->status; -} - - -/* - * i s I n i t i a l i s e d - */ -static inline BooleanType QProblemB_isInitialised( QProblemB* _THIS ) -{ - if ( _THIS->status == QPS_NOTINITIALISED ) - return BT_FALSE; - else - return BT_TRUE; -} - - -/* - * i s S o l v e d - */ -static inline BooleanType QProblemB_isSolved( QProblemB* _THIS ) -{ - if ( _THIS->status == QPS_SOLVED ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * i s I n f e a s i b l e - */ -static inline BooleanType QProblemB_isInfeasible( QProblemB* _THIS ) -{ - return _THIS->infeasible; -} - - -/* - * i s U n b o u n d e d - */ -static inline BooleanType QProblemB_isUnbounded( QProblemB* _THIS ) -{ - return _THIS->unbounded; -} - - -/* - * g e t H e s s i a n T y p e - */ -static inline HessianType QProblemB_getHessianType( QProblemB* _THIS ) -{ - return _THIS->hessianType; -} - - -/* - * s e t H e s s i a n T y p e - */ -static inline returnValue QProblemB_setHessianType( QProblemB* _THIS, HessianType _hessianType ) -{ - _THIS->hessianType = _hessianType; - return SUCCESSFUL_RETURN; -} - - -/* - * u s i n g R e g u l a r i s a t i o n - */ -static inline BooleanType QProblemB_usingRegularisation( QProblemB* _THIS ) -{ - if ( _THIS->regVal > QPOASES_ZERO ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * g e t O p t i o n s - */ -static inline Options QProblemB_getOptions( QProblemB* _THIS ) -{ - return _THIS->options; -} - - -/* - * s e t O p t i o n s - */ -static inline returnValue QProblemB_setOptions( QProblemB* _THIS, - Options _options - ) -{ - OptionsCPY( &_options,&(_THIS->options) ); - Options_ensureConsistency( &(_THIS->options) ); - - QProblemB_setPrintLevel( _THIS,_THIS->options.printLevel ); - - return SUCCESSFUL_RETURN; -} - - -/* - * g e t P r i n t L e v e l - */ -static inline PrintLevel QProblemB_getPrintLevel( QProblemB* _THIS ) -{ - return _THIS->options.printLevel; -} - - - -/* - * g e t C o u n t - */ -static inline unsigned int QProblemB_getCount( QProblemB* _THIS ) -{ - return _THIS->count; -} - - -/* - * r e s e t C o u n t e r - */ -static inline returnValue QProblemB_resetCounter( QProblemB* _THIS ) -{ - _THIS->count = 0; - return SUCCESSFUL_RETURN; -} - - - -/***************************************************************************** - * P R O T E C T E D * - *****************************************************************************/ - - -/* - * s e t H - */ -static inline returnValue QProblemB_setHM( QProblemB* _THIS, DenseMatrix* H_new ) -{ - if ( H_new == 0 ) - return QProblemB_setH( _THIS,(real_t*)0 ); - else - return QProblemB_setH( _THIS,DenseMatrix_getVal(H_new) ); -} - - -/* - * s e t H - */ -static inline returnValue QProblemB_setH( QProblemB* _THIS, real_t* const H_new ) -{ - /* if null pointer is passed, Hessian is set to zero matrix - * (or stays identity matrix) */ - if ( H_new == 0 ) - { - if ( _THIS->hessianType == HST_IDENTITY ) - return SUCCESSFUL_RETURN; - - _THIS->hessianType = HST_ZERO; - - _THIS->H = 0; - } - else - { - DenseMatrixCON( _THIS->H,QProblemB_getNV( _THIS ),QProblemB_getNV( _THIS ),QProblemB_getNV( _THIS ),H_new ); - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t G - */ -static inline returnValue QProblemB_setG( QProblemB* _THIS, const real_t* const g_new ) -{ - unsigned int nV = (unsigned int)QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( g_new == 0 ) - return THROWERROR( RET_INVALID_ARGUMENTS ); - - memcpy( _THIS->g,g_new,nV*sizeof(real_t) ); - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B - */ -static inline returnValue QProblemB_setLB( QProblemB* _THIS, const real_t* const lb_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( lb_new != 0 ) - { - memcpy( _THIS->lb,lb_new,nV*sizeof(real_t) ); - } - else - { - /* if no lower bounds are specified, set them to -infinity */ - for( i=0; ilb[i] = -QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B - */ -static inline returnValue QProblemB_setLBn( QProblemB* _THIS, int number, real_t value ) -{ - int nV = QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nV ) ) - { - _THIS->lb[number] = value; - return SUCCESSFUL_RETURN; - } - else - { - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); - } -} - - -/* - * s e t U B - */ -static inline returnValue QProblemB_setUB( QProblemB* _THIS, const real_t* const ub_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ub_new != 0 ) - { - memcpy( _THIS->ub,ub_new,nV*sizeof(real_t) ); - } - else - { - /* if no upper bounds are specified, set them to infinity */ - for( i=0; iub[i] = QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t U B - */ -static inline returnValue QProblemB_setUBn( QProblemB* _THIS, int number, real_t value ) -{ - int nV = QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nV ) ) - { - _THIS->ub[number] = value; - - return SUCCESSFUL_RETURN; - } - else - { - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); - } -} - - -/* - * c o m p u t e G i v e n s - */ -static inline void QProblemB_computeGivens( real_t xold, real_t yold, - real_t* xnew, real_t* ynew, real_t* c, real_t* s - ) -{ - real_t t, mu; - - if ( fabs( yold ) <= QPOASES_ZERO ) - { - *c = 1.0; - *s = 0.0; - - *xnew = xold; - *ynew = yold; - } - else - { - mu = fabs( xold ); - if ( fabs( yold ) > mu ) - mu = fabs( yold ); - - t = mu * sqrt( (xold/mu)*(xold/mu) + (yold/mu)*(yold/mu) ); - - if ( xold < 0.0 ) - t = -t; - - *c = xold/t; - *s = yold/t; - *xnew = t; - *ynew = 0.0; - } - - return; -} - - -/* - * a p p l y G i v e n s - */ -static inline void QProblemB_applyGivens( real_t c, real_t s, real_t nu, real_t xold, real_t yold, - real_t* xnew, real_t* ynew - ) -{ - #ifdef __USE_THREE_MULTS_GIVENS__ - - /* Givens plane rotation requiring only three multiplications, - * cf. Hammarling, S.: A note on modifications to the givens plane rotation. - * J. Inst. Maths Applics, 13:215-218, 1974. */ - *xnew = xold*c + yold*s; - *ynew = (*xnew+xold)*nu - yold; - - #else - - /* Usual Givens plane rotation requiring four multiplications. */ - *xnew = c*xold + s*yold; - *ynew = -s*xold + c*yold; - - #endif - - return; -} - - -/* - * i s B l o c k i n g - */ -static inline BooleanType QProblemB_isBlocking( QProblemB* _THIS, - real_t num, - real_t den, - real_t epsNum, - real_t epsDen, - real_t* t - ) -{ - if ( ( den >= epsDen ) && ( num >= epsNum ) ) - { - if ( num < (*t)*den ) - return BT_TRUE; - } - - return BT_FALSE; -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_QPROBLEMB_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Types.h b/third_party/acados/include/qpOASES_e/Types.h deleted file mode 100644 index fc042aed826872..00000000000000 --- a/third_party/acados/include/qpOASES_e/Types.h +++ /dev/null @@ -1,310 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Types.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of all non-built-in types (except for classes). - */ - - -#ifndef QPOASES_TYPES_H -#define QPOASES_TYPES_H - -#ifdef USE_ACADOS_TYPES -#include "acados/utils/types.h" -#endif - -/* If your compiler does not support the snprintf() function, - * uncomment the following line and try to compile again. */ -/* #define __NO_SNPRINTF__ */ - - -/* Uncomment the following line for setting the __DSPACE__ flag. */ -/* #define __DSPACE__ */ - -/* Uncomment the following line for setting the __XPCTARGET__ flag. */ -/* #define __XPCTARGET__ */ - - -/* Uncomment the following line for setting the __NO_FMATH__ flag. */ -/* #define __NO_FMATH__ */ - -/* Uncomment the following line to enable debug information. */ -/* #define __DEBUG__ */ - -/* Uncomment the following line to enable suppress any kind of console output. */ -/* #define __SUPPRESSANYOUTPUT__ */ - - -/** Forces to always include all implicitly fixed bounds and all equality constraints - * into the initial working set when setting up an auxiliary QP. */ -#define __ALWAYS_INITIALISE_WITH_ALL_EQUALITIES__ - -/* Uncomment the following line to activate the use of an alternative Givens - * plane rotation requiring only three multiplications. */ -/* #define __USE_THREE_MULTS_GIVENS__ */ - -/* Uncomment the following line to activate the use of single precision arithmetic. */ -/* #define __USE_SINGLE_PRECISION__ */ - -/* The inline keyword is skipped by default as it is not part of the C90 standard. - * However, by uncommenting the following line, use of the inline keyword can be enforced. */ -/* #define __USE_INLINE__ */ - - -/* Work-around for Borland BCC 5.5 compiler. */ -#ifdef __BORLANDC__ -#if __BORLANDC__ < 0x0561 - #define __STDC__ 1 -#endif -#endif - - -/* Work-around for Microsoft compilers. */ -#ifdef _MSC_VER - #define __NO_SNPRINTF__ - #pragma warning( disable : 4061 4100 4250 4514 4996 ) -#endif - - -/* Apply pre-processor settings when using qpOASES within auto-generated code. */ -#ifdef __CODE_GENERATION__ - #define __NO_COPYRIGHT__ - #define __EXTERNAL_DIMENSIONS__ -#endif /* __CODE_GENERATION__ */ - - -/* Avoid using static variables declaration within functions. */ -#ifdef __NO_STATIC__ - #define myStatic -#else - #define myStatic static -#endif /* __NO_STATIC__ */ - - -/* Skip inline keyword if not specified otherwise. */ -#ifndef __USE_INLINE__ - #define inline -#endif - - -/* Avoid any printing on embedded platforms. */ -#if defined(__DSPACE__) || defined(__XPCTARGET__) - #define __SUPPRESSANYOUTPUT__ - #define __NO_SNPRINTF__ -#endif - - -#ifdef __NO_SNPRINTF__ - #if (!defined(_MSC_VER)) || defined(__DSPACE__) || defined(__XPCTARGET__) - /* If snprintf is not available, provide an empty implementation... */ - int snprintf( char* s, size_t n, const char* format, ... ); - #else - /* ... or substitute snprintf by _snprintf for Microsoft compilers. */ - #define snprintf _snprintf - #endif -#endif /* __NO_SNPRINTF__ */ - - -/** Macro for switching on/off the beginning of the qpOASES namespace definition. */ -#define BEGIN_NAMESPACE_QPOASES - -/** Macro for switching on/off the end of the qpOASES namespace definition. */ -#define END_NAMESPACE_QPOASES - -/** Macro for switching on/off the use of the qpOASES namespace. */ -#define USING_NAMESPACE_QPOASES - -/** Macro for switching on/off references to the qpOASES namespace. */ -#define REFER_NAMESPACE_QPOASES /*::*/ - - -/** Macro for accessing the Cholesky factor R. */ -#define RR( I,J ) _THIS->R[(I)+nV*(J)] - -/** Macro for accessing the orthonormal matrix Q of the QT factorisation. */ -#define QQ( I,J ) _THIS->Q[(I)+nV*(J)] - -/** Macro for accessing the triangular matrix T of the QT factorisation. */ -#define TT( I,J ) _THIS->T[(I)*nVC_min+(J)] - - - -BEGIN_NAMESPACE_QPOASES - - -/** Defines real_t for facilitating switching between double and float. */ - -#ifndef USE_ACADOS_TYPES -#ifndef __CODE_GENERATION__ - - #ifdef __USE_SINGLE_PRECISION__ - typedef float real_t; - #else - typedef double real_t; - #endif /* __USE_SINGLE_PRECISION__ */ - -#endif /* __CODE_GENERATION__ */ -#endif /* USE_ACADOS_TYPES */ - -/** Summarises all possible logical values. */ -typedef enum -{ - BT_FALSE = 0, /**< Logical value for "false". */ - BT_TRUE /**< Logical value for "true". */ -} BooleanType; - - -/** Summarises all possible print levels. Print levels are used to describe - * the desired amount of output during runtime of qpOASES. */ -typedef enum -{ - PL_DEBUG_ITER = -2, /**< Full tabular debugging output. */ - PL_TABULAR, /**< Tabular output. */ - PL_NONE, /**< No output. */ - PL_LOW, /**< Print error messages only. */ - PL_MEDIUM, /**< Print error and warning messages as well as concise info messages. */ - PL_HIGH /**< Print all messages with full details. */ -} PrintLevel; - - -/** Defines visibility status of a message. */ -typedef enum -{ - VS_HIDDEN, /**< Message not visible. */ - VS_VISIBLE /**< Message visible. */ -} VisibilityStatus; - - -/** Summarises all possible states of the (S)QProblem(B) object during the -solution process of a QP sequence. */ -typedef enum -{ - QPS_NOTINITIALISED, /**< QProblem object is freshly instantiated or reset. */ - QPS_PREPARINGAUXILIARYQP, /**< An auxiliary problem is currently setup, either at the very beginning - * via an initial homotopy or after changing the QP matrices. */ - QPS_AUXILIARYQPSOLVED, /**< An auxilary problem was solved, either at the very beginning - * via an initial homotopy or after changing the QP matrices. */ - QPS_PERFORMINGHOMOTOPY, /**< A homotopy according to the main idea of the online active - * set strategy is performed. */ - QPS_HOMOTOPYQPSOLVED, /**< An intermediate QP along the homotopy path was solved. */ - QPS_SOLVED /**< The solution of the actual QP was found. */ -} QProblemStatus; - - -/** Summarises all possible types of the QP's Hessian matrix. */ -typedef enum -{ - HST_ZERO, /**< Hessian is zero matrix (i.e. LP formulation). */ - HST_IDENTITY, /**< Hessian is identity matrix. */ - HST_POSDEF, /**< Hessian is (strictly) positive definite. */ - HST_POSDEF_NULLSPACE, /**< Hessian is positive definite on null space of active bounds/constraints. */ - HST_SEMIDEF, /**< Hessian is positive semi-definite. */ - HST_INDEF, /**< Hessian is indefinite. */ - HST_UNKNOWN /**< Hessian type is unknown. */ -} HessianType; - - -/** Summarises all possible types of bounds and constraints. */ -typedef enum -{ - ST_UNBOUNDED, /**< Bound/constraint is unbounded. */ - ST_BOUNDED, /**< Bound/constraint is bounded but not fixed. */ - ST_EQUALITY, /**< Bound/constraint is fixed (implicit equality bound/constraint). */ - ST_DISABLED, /**< Bound/constraint is disabled (i.e. ignored when solving QP). */ - ST_UNKNOWN /**< Type of bound/constraint unknown. */ -} SubjectToType; - - -/** Summarises all possible states of bounds and constraints. */ -typedef enum -{ - ST_LOWER = -1, /**< Bound/constraint is at its lower bound. */ - ST_INACTIVE, /**< Bound/constraint is inactive. */ - ST_UPPER, /**< Bound/constraint is at its upper bound. */ - ST_INFEASIBLE_LOWER, /**< (to be documented) */ - ST_INFEASIBLE_UPPER, /**< (to be documented) */ - ST_UNDEFINED /**< Status of bound/constraint undefined. */ -} SubjectToStatus; - - -/** - * \brief Stores internal information for tabular (debugging) output. - * - * Struct storing internal information for tabular (debugging) output - * when using the (S)QProblem(B) objects. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2013-2015 - */ -typedef struct -{ - int idxAddB; /**< Index of bound that has been added to working set. */ - int idxRemB; /**< Index of bound that has been removed from working set. */ - int idxAddC; /**< Index of constraint that has been added to working set. */ - int idxRemC; /**< Index of constraint that has been removed from working set. */ - int excAddB; /**< Flag indicating whether a bound has been added to working set to keep a regular projected Hessian. */ - int excRemB; /**< Flag indicating whether a bound has been removed from working set to keep a regular projected Hessian. */ - int excAddC; /**< Flag indicating whether a constraint has been added to working set to keep a regular projected Hessian. */ - int excRemC; /**< Flag indicating whether a constraint has been removed from working set to keep a regular projected Hessian. */ -} TabularOutput; - -/** - * \brief Struct containing the variable header for mat file. - * - * Struct storing the header of a variable to be stored in - * Matlab's binary format (using the outdated Level 4 variant - * for simplictiy). - * - * Note, this code snippet has been inspired from the document - * "Matlab(R) MAT-file Format, R2013b" by MathWorks - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2013-2015 - */ -typedef struct -{ - long numericFormat; /**< Flag indicating numerical format. */ - long nRows; /**< Number of rows. */ - long nCols; /**< Number of rows. */ - long imaginaryPart; /**< (to be documented) */ - long nCharName; /**< Number of character in name. */ -} MatMatrixHeader; - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_TYPES_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/UnitTesting.h b/third_party/acados/include/qpOASES_e/UnitTesting.h deleted file mode 100644 index dbff201039eb58..00000000000000 --- a/third_party/acados/include/qpOASES_e/UnitTesting.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/UnitTesting.h - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2014-2015 - * - * Definition of auxiliary functions/macros for unit testing. - */ - - -#ifndef QPOASES_UNIT_TESTING_H -#define QPOASES_UNIT_TESTING_H - - -#ifndef TEST_TOL_FACTOR -#define TEST_TOL_FACTOR 1 -#endif - - -/** Return value for tests that passed. */ -#define TEST_PASSED 0 - -/** Return value for tests that failed. */ -#define TEST_FAILED 1 - -/** Return value for tests that could not run due to missing external data. */ -#define TEST_DATA_NOT_FOUND 99 - - -/** Macro verifying that two numerical values are equal in order to pass unit test. */ -#define QPOASES_TEST_FOR_EQUAL( x,y ) if ( REFER_NAMESPACE_QPOASES isEqual( (x),(y) ) == BT_FALSE ) { return TEST_FAILED; } - -/** Macro verifying that two numerical values are close to each other in order to pass unit test. */ -#define QPOASES_TEST_FOR_NEAR( x,y ) if ( REFER_NAMESPACE_QPOASES getAbs((x)-(y)) / REFER_NAMESPACE_QPOASES getMax( 1.0,REFER_NAMESPACE_QPOASES getAbs(x) ) >= 1e-10 ) { return TEST_FAILED; } - -/** Macro verifying that first quantity is lower or equal than second one in order to pass unit test. */ -#define QPOASES_TEST_FOR_TOL( x,tol ) if ( (x) > (tol)*(TEST_TOL_FACTOR) ) { return TEST_FAILED; } - -/** Macro verifying that a logical expression holds in order to pass unit test. */ -#define QPOASES_TEST_FOR_TRUE( x ) if ( (x) == 0 ) { return TEST_FAILED; } - - - -BEGIN_NAMESPACE_QPOASES - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_UNIT_TESTING_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Utils.h b/third_party/acados/include/qpOASES_e/Utils.h deleted file mode 100644 index 75e45a56a08c55..00000000000000 --- a/third_party/acados/include/qpOASES_e/Utils.h +++ /dev/null @@ -1,500 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Utils.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of some utilities for working with the different QProblem classes. - */ - - -#ifndef QPOASES_UTILS_H -#define QPOASES_UTILS_H - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** Prints a vector. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printV( const real_t* const v, /**< Vector to be printed. */ - int n /**< Length of vector. */ - ); - -/** Prints a permuted vector. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printPV( const real_t* const v, /**< Vector to be printed. */ - int n, /**< Length of vector. */ - const int* const V_idx /**< Pemutation vector. */ - ); - -/** Prints a named vector. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printNV( const real_t* const v, /**< Vector to be printed. */ - int n, /**< Length of vector. */ - const char* name /** Name of vector. */ - ); - -/** Prints a matrix. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printM( const real_t* const M, /**< Matrix to be printed. */ - int nrow, /**< Row number of matrix. */ - int ncol /**< Column number of matrix. */ - ); - -/** Prints a permuted matrix. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printPM( const real_t* const M, /**< Matrix to be printed. */ - int nrow, /**< Row number of matrix. */ - int ncol , /**< Column number of matrix. */ - const int* const ROW_idx, /**< Row pemutation vector. */ - const int* const COL_idx /**< Column pemutation vector. */ - ); - -/** Prints a named matrix. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printNM( const real_t* const M, /**< Matrix to be printed. */ - int nrow, /**< Row number of matrix. */ - int ncol, /**< Column number of matrix. */ - const char* name /** Name of matrix. */ - ); - -/** Prints an index array. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printI( const int* const _index, /**< Index array to be printed. */ - int n /**< Length of index array. */ - ); - -/** Prints a named index array. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printNI( const int* const _index, /**< Index array to be printed. */ - int n, /**< Length of index array. */ - const char* name /**< Name of index array. */ - ); - - -/** Prints a string to desired output target (useful also for MATLAB output!). - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_myPrintf( const char* s /**< String to be written. */ - ); - - -/** Prints qpOASES copyright notice. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printCopyrightNotice( ); - - -/** Reads a real_t matrix from file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE */ -returnValue qpOASES_readFromFileM( real_t* data, /**< Matrix to be read from file. */ - int nrow, /**< Row number of matrix. */ - int ncol, /**< Column number of matrix. */ - const char* datafilename /**< Data file name. */ - ); - -/** Reads a real_t vector from file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE */ -returnValue qpOASES_readFromFileV( real_t* data, /**< Vector to be read from file. */ - int n, /**< Length of vector. */ - const char* datafilename /**< Data file name. */ - ); - -/** Reads an integer (column) vector from file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE */ -returnValue qpOASES_readFromFileI( int* data, /**< Vector to be read from file. */ - int n, /**< Length of vector. */ - const char* datafilename /**< Data file name. */ - ); - - -/** Writes a real_t matrix into a file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue qpOASES_writeIntoFileM( const real_t* const data, /**< Matrix to be written into file. */ - int nrow, /**< Row number of matrix. */ - int ncol, /**< Column number of matrix. */ - const char* datafilename, /**< Data file name. */ - BooleanType append /**< Indicates if data shall be appended if the file already exists (otherwise it is overwritten). */ - ); - -/** Writes a real_t vector into a file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue qpOASES_writeIntoFileV( const real_t* const data, /**< Vector to be written into file. */ - int n, /**< Length of vector. */ - const char* datafilename, /**< Data file name. */ - BooleanType append /**< Indicates if data shall be appended if the file already exists (otherwise it is overwritten). */ - ); - -/** Writes an integer (column) vector into a file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue qpOASES_writeIntoFileI( const int* const integer, /**< Integer vector to be written into file. */ - int n, /**< Length of vector. */ - const char* datafilename, /**< Data file name. */ - BooleanType append /**< Indicates if integer shall be appended if the file already exists (otherwise it is overwritten). */ - ); - -/** Writes a real_t matrix/vector into a Matlab binary file. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS - RET_UNABLE_TO_WRITE_FILE */ -returnValue qpOASES_writeIntoMatFile( FILE* const matFile, /**< Pointer to Matlab binary file. */ - const real_t* const data, /**< Data to be written into file. */ - int nRows, /**< Row number of matrix. */ - int nCols, /**< Column number of matrix. */ - const char* name /**< Matlab name of matrix/vector to be stored. */ - ); - -/** Writes in integer matrix/vector into a Matlab binary file. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS - RET_UNABLE_TO_WRITE_FILE */ -returnValue qpOASES_writeIntoMatFileI( FILE* const matFile, /**< Pointer to Matlab binary file. */ - const int* const data, /**< Data to be written into file. */ - int nRows, /**< Row number of matrix. */ - int nCols, /**< Column number of matrix. */ - const char* name /**< Matlab name of matrix/vector to be stored. */ - ); - - -/** Returns the current system time. - * \return current system time */ -real_t qpOASES_getCPUtime( ); - - -/** Returns the N-norm of a vector. - * \return >= 0.0: successful */ -real_t qpOASES_getNorm( const real_t* const v, /**< Vector. */ - int n, /**< Vector's dimension. */ - int type /**< Norm type, 1: one-norm, 2: Euclidean norm. */ - ); - -/** Tests whether two real-valued arguments are (numerically) equal. - * \return BT_TRUE: arguments differ not more than TOL \n - BT_FALSE: arguments differ more than TOL */ -static inline BooleanType qpOASES_isEqual( real_t x, /**< First real number. */ - real_t y, /**< Second real number. */ - real_t TOL /**< Tolerance for comparison. */ - ); - - -/** Tests whether a real-valued argument is (numerically) zero. - * \return BT_TRUE: argument differs from 0.0 not more than TOL \n - BT_FALSE: argument differs from 0.0 more than TOL */ -static inline BooleanType qpOASES_isZero( real_t x, /**< Real number. */ - real_t TOL /**< Tolerance for comparison. */ - ); - - -/** Returns sign of a real-valued argument. - * \return 1.0: argument is non-negative \n - -1.0: argument is negative */ -static inline real_t qpOASES_getSign( real_t arg /**< real-valued argument whose sign is to be determined. */ - ); - - -/** Returns maximum of two integers. - * \return Maximum of two integers */ -static inline int qpOASES_getMaxI( int x, /**< First integer. */ - int y /**< Second integer. */ - ); - - -/** Returns minimum of two integers. - * \return Minimum of two integers */ -static inline int qpOASES_getMinI( int x, /**< First integer. */ - int y /**< Second integer. */ - ); - - -/** Returns maximum of two reals. - * \return Maximum of two reals */ -static inline real_t qpOASES_getMax( real_t x, /**< First real number. */ - real_t y /**< Second real number. */ - ); - - -/** Returns minimum of two reals. - * \return Minimum of two reals */ -static inline real_t qpOASES_getMin( real_t x, /**< First real number. */ - real_t y /**< Second real number. */ - ); - - -/** Returns the absolute value of a real_t-valued argument. - * \return Absolute value of a real_t-valued argument */ -static inline real_t qpOASES_getAbs( real_t x /**< real_t-valued argument. */ - ); - -/** Returns the square-root of a real number. - * \return Square-root of a real number */ -static inline real_t qpOASES_getSqrt( real_t x /**< Non-negative real number. */ - ); - - -/** Computes the maximum violation of the KKT optimality conditions - * of given iterate for given QP data. */ -returnValue qpOASES_getKktViolation( int nV, /**< Number of variables. */ - int nC, /**< Number of constraints. */ - const real_t* const H, /**< Hessian matrix (may be NULL if Hessian is zero or identity matrix). */ - const real_t* const g, /**< Gradient vector. */ - const real_t* const A, /**< Constraint matrix. */ - const real_t* const lb, /**< Lower bound vector (on variables). */ - const real_t* const ub, /**< Upper bound vector (on variables). */ - const real_t* const lbA, /**< Lower constraints' bound vector. */ - const real_t* const ubA, /**< Upper constraints' bound vector. */ - const real_t* const x, /**< Primal trial vector. */ - const real_t* const y, /**< Dual trial vector. */ - real_t* const _stat, /**< Output: maximum value of stationarity condition residual. */ - real_t* const feas, /**< Output: maximum value of primal feasibility violation. */ - real_t* const cmpl /**< Output: maximum value of complementarity residual. */ - ); - -/** Computes the maximum violation of the KKT optimality conditions - * of given iterate for given QP data. */ -returnValue qpOASES_getKktViolationSB( int nV, /**< Number of variables. */ - const real_t* const H, /**< Hessian matrix (may be NULL if Hessian is zero or identity matrix). */ - const real_t* const g, /**< Gradient vector. */ - const real_t* const lb, /**< Lower bound vector (on variables). */ - const real_t* const ub, /**< Upper bound vector (on variables). */ - const real_t* const x, /**< Primal trial vector. */ - const real_t* const y, /**< Dual trial vector. */ - real_t* const _stat, /**< Output: maximum value of stationarity condition residual. */ - real_t* const feas, /**< Output: maximum value of primal feasibility violation. */ - real_t* const cmpl /**< Output: maximum value of complementarity residual. */ - ); - - -/** Writes a value of BooleanType into a string. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_convertBooleanTypeToString( BooleanType value, /**< Value to be written. */ - char* const string /**< Input: String of sufficient size, \n - Output: String containing value. */ - ); - -/** Writes a value of SubjectToStatus into a string. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_convertSubjectToStatusToString( SubjectToStatus value, /**< Value to be written. */ - char* const string /**< Input: String of sufficient size, \n - Output: String containing value. */ - ); - -/** Writes a value of PrintLevel into a string. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_convertPrintLevelToString( PrintLevel value, /**< Value to be written. */ - char* const string /**< Input: String of sufficient size, \n - Output: String containing value. */ - ); - - -/** Converts a returnValue from an QProblem(B) object into a more - * simple status flag. - * - * \return 0: QP problem solved - * 1: QP could not be solved within given number of iterations - * -1: QP could not be solved due to an internal error - * -2: QP is infeasible (and thus could not be solved) - * -3: QP is unbounded (and thus could not be solved) - */ -int qpOASES_getSimpleStatus( returnValue returnvalue, /**< ReturnValue to be analysed. */ - BooleanType doPrintStatus /**< Flag indicating whether simple status shall be printed to screen. */ - ); - -/** Normalises QP constraints. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue qpOASES_normaliseConstraints( int nV, /**< Number of variables. */ - int nC, /**< Number of constraints. */ - real_t* A, /**< Input: Constraint matrix, \n - Output: Normalised constraint matrix. */ - real_t* lbA, /**< Input: Constraints' lower bound vector, \n - Output: Normalised constraints' lower bound vector. */ - real_t* ubA, /**< Input: Constraints' upper bound vector, \n - Output: Normalised constraints' upper bound vector. */ - int type /**< Norm type, 1: one-norm, 2: Euclidean norm. */ - ); - - -#ifdef __DEBUG__ -/** Writes matrix with given dimension into specified file. */ -void gdb_printmat( const char *fname, /**< File name. */ - real_t *M, /**< Matrix to be written. */ - int n, /**< Number of rows. */ - int m, /**< Number of columns. */ - int ldim /**< Leading dimension. */ - ); -#endif /* __DEBUG__ */ - - -#if defined(__DSPACE__) || defined(__XPCTARGET__) -void __cxa_pure_virtual( void ); -#endif /* __DSPACE__ || __XPCTARGET__*/ - - - -/* - * i s E q u a l - */ -static inline BooleanType qpOASES_isEqual( real_t x, - real_t y, - real_t TOL - ) -{ - if ( qpOASES_getAbs(x-y) <= TOL ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * i s Z e r o - */ -static inline BooleanType qpOASES_isZero( real_t x, - real_t TOL - ) -{ - if ( qpOASES_getAbs(x) <= TOL ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * g e t S i g n - */ -static inline real_t qpOASES_getSign( real_t arg - ) -{ - if ( arg >= 0.0 ) - return 1.0; - else - return -1.0; -} - - - -/* - * g e t M a x - */ -static inline int qpOASES_getMaxI( int x, - int y - ) -{ - return (yx) ? x : y; -} - - -/* - * g e t M a x - */ -static inline real_t qpOASES_getMax( real_t x, - real_t y - ) -{ - #ifdef __NO_FMATH__ - return (yx) ? x : y; - #else - return (y>x) ? x : y; - /*return fmin(x,y); seems to be slower */ - #endif -} - - -/* - * g e t A b s - */ -static inline real_t qpOASES_getAbs( real_t x - ) -{ - #ifdef __NO_FMATH__ - return (x>=0.0) ? x : -x; - #else - return fabs(x); - #endif -} - -/* - * g e t S q r t - */ -static inline real_t qpOASES_getSqrt( real_t x - ) -{ - #ifdef __NO_FMATH__ - return sqrt(x); /* put your custom sqrt-replacement here */ - #else - return sqrt(x); - #endif -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_UTILS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/extras/OQPinterface.h b/third_party/acados/include/qpOASES_e/extras/OQPinterface.h deleted file mode 100644 index da59ea9db6483f..00000000000000 --- a/third_party/acados/include/qpOASES_e/extras/OQPinterface.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/extras/OQPinterface.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of an interface comprising several utility functions - * for solving test problems from the Online QP Benchmark Collection - * (This collection is no longer maintained, see - * http://www.qpOASES.org/onlineQP for a backup). - */ - - -#ifndef QPOASES_OQPINTERFACE_H -#define QPOASES_OQPINTERFACE_H - - -#include -#include - -#include -#include - - -BEGIN_NAMESPACE_QPOASES - -typedef struct { - QProblem *qp; - - DenseMatrix *H; - DenseMatrix *A; - - real_t *x; - real_t *y; -} OQPbenchmark_ws; - -int OQPbenchmark_ws_calculateMemorySize( unsigned int nV, unsigned int nC ); - -char *OQPbenchmark_ws_assignMemory( unsigned int nV, unsigned int nC, OQPbenchmark_ws **mem, void *raw_memory ); - -OQPbenchmark_ws *OQPbenchmark_ws_createMemory( unsigned int nV, unsigned int nC ); - -typedef struct { - QProblemB *qp; - - DenseMatrix *H; - - real_t *x; - real_t *y; -} OQPbenchmarkB_ws; - -int OQPbenchmarkB_ws_calculateMemorySize( unsigned int nV ); - -char *OQPbenchmarkB_ws_assignMemory( unsigned int nV, OQPbenchmarkB_ws **mem, void *raw_memory ); - -OQPbenchmarkB_ws *OQPbenchmarkB_ws_createMemory( unsigned int nV ); - -typedef struct { - OQPbenchmark_ws *qp_ws; - OQPbenchmarkB_ws *qpB_ws; - - real_t *H; - real_t *g; - real_t *A; - real_t *lb; - real_t *ub; - real_t *lbA; - real_t *ubA; -} OQPinterface_ws; - -int OQPinterface_ws_calculateMemorySize( unsigned int nV, unsigned int nC, unsigned int nQP ); - -char *OQPinterface_ws_assignMemory( unsigned int nV, unsigned int nC, unsigned int nQP, OQPinterface_ws **mem, void *raw_memory ); - -OQPinterface_ws *OQPinterface_ws_createMemory( unsigned int nV, unsigned int nC, unsigned int nQP ); - -/** Reads dimensions of an Online QP Benchmark problem from file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_READ_FILE \n - RET_FILEDATA_INCONSISTENT */ -returnValue readOQPdimensions( const char* path, /**< Full path of the data files (without trailing slash!). */ - int* nQP, /**< Output: Number of QPs. */ - int* nV, /**< Output: Number of variables. */ - int* nC, /**< Output: Number of constraints. */ - int* nEC /**< Output: Number of equality constraints. */ - ); - -/** Reads data of an Online QP Benchmark problem from file. - * This function allocates the required memory for all data; after successfully calling it, - * you have to free this memory yourself! - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_UNABLE_TO_READ_FILE \n - RET_FILEDATA_INCONSISTENT */ -returnValue readOQPdata( const char* path, /**< Full path of the data files (without trailing slash!). */ - int* nQP, /**< Output: Number of QPs. */ - int* nV, /**< Output: Number of variables. */ - int* nC, /**< Output: Number of constraints. */ - int* nEC, /**< Output: Number of equality constraints. */ - real_t* H, /**< Output: Hessian matrix. */ - real_t* g, /**< Output: Sequence of gradient vectors. */ - real_t* A, /**< Output: Constraint matrix. */ - real_t* lb, /**< Output: Sequence of lower bound vectors (on variables). */ - real_t* ub, /**< Output: Sequence of upper bound vectors (on variables). */ - real_t* lbA, /**< Output: Sequence of lower constraints' bound vectors. */ - real_t* ubA, /**< Output: Sequence of upper constraints' bound vectors. */ - real_t* xOpt, /**< Output: Sequence of primal solution vectors - * (not read if a null pointer is passed). */ - real_t* yOpt, /**< Output: Sequence of dual solution vectors - * (not read if a null pointer is passed). */ - real_t* objOpt /**< Output: Sequence of optimal objective function values - * (not read if a null pointer is passed). */ - ); - - -/** Solves an Online QP Benchmark problem as specified by the arguments. - * The maximum deviations from the given optimal solution as well as the - * maximum CPU time to solve each QP are determined. - * \return SUCCESSFUL_RETURN \n - RET_BENCHMARK_ABORTED */ -returnValue solveOQPbenchmark( int nQP, /**< Number of QPs. */ - int nV, /**< Number of variables. */ - int nC, /**< Number of constraints. */ - int nEC, /**< Number of equality constraints. */ - real_t* _H, /**< Hessian matrix. */ - const real_t* const g, /**< Sequence of gradient vectors. */ - real_t* _A, /**< Constraint matrix. */ - const real_t* const lb, /**< Sequence of lower bound vectors (on variables). */ - const real_t* const ub, /**< Sequence of upper bound vectors (on variables). */ - const real_t* const lbA, /**< Sequence of lower constraints' bound vectors. */ - const real_t* const ubA, /**< Sequence of upper constraints' bound vectors. */ - BooleanType isSparse, /**< Shall convert matrices to sparse format before solution? */ - BooleanType useHotstarts, /**< Shall QP solution be hotstarted? */ - const Options* options, /**< QP solver options to be used while solving benchmark problems. */ - int maxAllowedNWSR, /**< Maximum number of working set recalculations to be performed. */ - real_t* maxNWSR, /**< Output: Maximum number of performed working set recalculations. */ - real_t* avgNWSR, /**< Output: Average number of performed working set recalculations. */ - real_t* maxCPUtime, /**< Output: Maximum CPU time required for solving each QP. */ - real_t* avgCPUtime, /**< Output: Average CPU time required for solving each QP. */ - real_t* maxStationarity, /**< Output: Maximum residual of stationarity condition. */ - real_t* maxFeasibility, /**< Output: Maximum residual of primal feasibility condition. */ - real_t* maxComplementarity, /**< Output: Maximum residual of complementarity condition. */ - OQPbenchmark_ws *work /**< Workspace. */ - ); - -/** Solves an Online QP Benchmark problem (without constraints) as specified - * by the arguments. The maximum deviations from the given optimal solution - * as well as the maximum CPU time to solve each QP are determined. - * \return SUCCESSFUL_RETURN \n - RET_BENCHMARK_ABORTED */ -returnValue solveOQPbenchmarkB( int nQP, /**< Number of QPs. */ - int nV, /**< Number of variables. */ - real_t* _H, /**< Hessian matrix. */ - const real_t* const g, /**< Sequence of gradient vectors. */ - const real_t* const lb, /**< Sequence of lower bound vectors (on variables). */ - const real_t* const ub, /**< Sequence of upper bound vectors (on variables). */ - BooleanType isSparse, /**< Shall convert matrices to sparse format before solution? */ - BooleanType useHotstarts, /**< Shall QP solution be hotstarted? */ - const Options* options, /**< QP solver options to be used while solving benchmark problems. */ - int maxAllowedNWSR, /**< Maximum number of working set recalculations to be performed. */ - real_t* maxNWSR, /**< Output: Maximum number of performed working set recalculations. */ - real_t* avgNWSR, /**< Output: Average number of performed working set recalculations. */ - real_t* maxCPUtime, /**< Output: Maximum CPU time required for solving each QP. */ - real_t* avgCPUtime, /**< Output: Average CPU time required for solving each QP. */ - real_t* maxStationarity, /**< Output: Maximum residual of stationarity condition. */ - real_t* maxFeasibility, /**< Output: Maximum residual of primal feasibility condition. */ - real_t* maxComplementarity, /**< Output: Maximum residual of complementarity condition. */ - OQPbenchmarkB_ws *work /**< Workspace. */ - ); - - -/** Runs an Online QP Benchmark problem and determines the maximum - * violation of the KKT optimality conditions as well as the - * maximum and average number of iterations and CPU time to solve - * each QP. - * - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_READ_BENCHMARK \n - RET_BENCHMARK_ABORTED */ -returnValue runOQPbenchmark( const char* path, /**< Full path of the benchmark files (without trailing slash!). */ - BooleanType isSparse, /**< Shall convert matrices to sparse format before solution? */ - BooleanType useHotstarts, /**< Shall QP solution be hotstarted? */ - const Options* options, /**< QP solver options to be used while solving benchmark problems. */ - int maxAllowedNWSR, /**< Maximum number of working set recalculations to be performed. */ - real_t* maxNWSR, /**< Output: Maximum number of performed working set recalculations. */ - real_t* avgNWSR, /**< Output: Average number of performed working set recalculations. */ - real_t* maxCPUtime, /**< Output: Maximum CPU time required for solving each QP. */ - real_t* avgCPUtime, /**< Output: Average CPU time required for solving each QP. */ - real_t* maxStationarity, /**< Output: Maximum residual of stationarity condition. */ - real_t* maxFeasibility, /**< Output: Maximum residual of primal feasibility condition. */ - real_t* maxComplementarity, /**< Output: Maximum residual of complementarity condition. */ - OQPinterface_ws* work /**< Workspace. */ - ); - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_OQPINTERFACE_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/larch64/lib/libacados.so b/third_party/acados/larch64/lib/libacados.so deleted file mode 100644 index a081e31ab178fd..00000000000000 --- a/third_party/acados/larch64/lib/libacados.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:091ed10ea2b52866b826ef6867b3413d6fd61af66fcedf3d932c9adf3fb329de -size 512912 diff --git a/third_party/acados/larch64/lib/libblasfeo.so b/third_party/acados/larch64/lib/libblasfeo.so deleted file mode 100644 index e2191897a10225..00000000000000 --- a/third_party/acados/larch64/lib/libblasfeo.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d40b25de85318c8349c9894a3cbeaa713efae4158d8cc2c5c77af9f1bfbbb28e -size 1150320 diff --git a/third_party/acados/larch64/lib/libhpipm.so b/third_party/acados/larch64/lib/libhpipm.so deleted file mode 100644 index 002eda375a5265..00000000000000 --- a/third_party/acados/larch64/lib/libhpipm.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:91b9276e74c7d7750288d76087d586ed27932939bc7bca2ad1494b6558fc43e3 -size 1367352 diff --git a/third_party/acados/larch64/lib/libqpOASES_e.so b/third_party/acados/larch64/lib/libqpOASES_e.so deleted file mode 120000 index 14048625a1c2d3..00000000000000 --- a/third_party/acados/larch64/lib/libqpOASES_e.so +++ /dev/null @@ -1 +0,0 @@ -libqpOASES_e.so.3.1 \ No newline at end of file diff --git a/third_party/acados/larch64/lib/libqpOASES_e.so.3.1 b/third_party/acados/larch64/lib/libqpOASES_e.so.3.1 deleted file mode 100644 index d64e40ec607035..00000000000000 --- a/third_party/acados/larch64/lib/libqpOASES_e.so.3.1 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c0a84042e5315af18e6e33b9b9c5e96573248e41ff165657eb9d83da4da2889f -size 223152 diff --git a/third_party/acados/larch64/t_renderer b/third_party/acados/larch64/t_renderer deleted file mode 100755 index f9e7d16601d24a..00000000000000 --- a/third_party/acados/larch64/t_renderer +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4660fe00e03e29d90459ac2fd46a6e10982577d0ba558b9f05e5712df66814b4 -size 17915048 diff --git a/third_party/acados/x86_64/lib/libacados.so b/third_party/acados/x86_64/lib/libacados.so deleted file mode 100644 index 4e80f7c76bace2..00000000000000 --- a/third_party/acados/x86_64/lib/libacados.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:821ce18f417d211c4845b60482d465b809f90dc7d04f023d652d8221e87679b1 -size 553544 diff --git a/third_party/acados/x86_64/lib/libblasfeo.so b/third_party/acados/x86_64/lib/libblasfeo.so deleted file mode 100644 index 26d5a3dbe917ef..00000000000000 --- a/third_party/acados/x86_64/lib/libblasfeo.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3feea7927d004064bbc5a13c3287467669ce801cb0a3c616cf9e089816da5a0b -size 2155088 diff --git a/third_party/acados/x86_64/lib/libhpipm.so b/third_party/acados/x86_64/lib/libhpipm.so deleted file mode 100644 index 40e2e4e7d4775d..00000000000000 --- a/third_party/acados/x86_64/lib/libhpipm.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a042716f515913786581dff39799eb71fc66caddfa18b1c9f0d54f00c1568fd2 -size 1572648 diff --git a/third_party/acados/x86_64/lib/libqpOASES_e.so b/third_party/acados/x86_64/lib/libqpOASES_e.so deleted file mode 120000 index 14048625a1c2d3..00000000000000 --- a/third_party/acados/x86_64/lib/libqpOASES_e.so +++ /dev/null @@ -1 +0,0 @@ -libqpOASES_e.so.3.1 \ No newline at end of file diff --git a/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 b/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 deleted file mode 100644 index cf5e550faa95f7..00000000000000 --- a/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a6abea4815e3f03cff06fe8a9602e97f9acf102f18f803571460a94595b93be4 -size 262824 diff --git a/third_party/acados/x86_64/t_renderer b/third_party/acados/x86_64/t_renderer deleted file mode 100755 index e995a209b79a11..00000000000000 --- a/third_party/acados/x86_64/t_renderer +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7a360d4b53826b91ada3358156d44a14d497bdd8ace88707fd4b386ed6d194c7 -size 17503920 diff --git a/third_party/bootstrap/.gitignore b/third_party/bootstrap/.gitignore deleted file mode 100644 index ac06c0cf85b3ae..00000000000000 --- a/third_party/bootstrap/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/icons/ diff --git a/third_party/bootstrap/bootstrap-icons.svg b/third_party/bootstrap/bootstrap-icons.svg deleted file mode 100644 index 692a27ea55c32c..00000000000000 --- a/third_party/bootstrap/bootstrap-icons.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d7ecfaac355e51c9b95319fdf4681cf4c423109fd477e961af588b92607a76da -size 1087239 diff --git a/third_party/bootstrap/pull.sh b/third_party/bootstrap/pull.sh deleted file mode 100755 index 0b03b4db9eff3e..00000000000000 --- a/third_party/bootstrap/pull.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -cd $DIR - -if [ ! -d icons/ ]; then - git clone https://github.com/twbs/icons/ -fi - -cd icons -git fetch --all -git checkout d5aa187483a1b0b186f87adcfa8576350d970d98 -cp bootstrap-icons.svg ../ diff --git a/third_party/catch2/include/catch2/catch.hpp b/third_party/catch2/include/catch2/catch.hpp deleted file mode 100644 index 6a31e5b0ca8cd4..00000000000000 --- a/third_party/catch2/include/catch2/catch.hpp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:27da57c7a06d09be8dd81fab7246b79e7892b6ae7e4e49ba8631f1d5a955e3fc -size 657276 diff --git a/third_party/catch2/include/catch2/catch_reporter_automake.hpp b/third_party/catch2/include/catch2/catch_reporter_automake.hpp deleted file mode 100644 index dbebe975163c98..00000000000000 --- a/third_party/catch2/include/catch2/catch_reporter_automake.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Created by Justin R. Wilson on 2/19/2017. - * Copyright 2017 Justin R. Wilson. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -namespace Catch { - - struct AutomakeReporter : StreamingReporterBase { - AutomakeReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - {} - - ~AutomakeReporter() override; - - static std::string getDescription() { - return "Reports test results in the format of Automake .trs files"; - } - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& /*_assertionStats*/ ) override { return true; } - - void testCaseEnded( TestCaseStats const& _testCaseStats ) override { - // Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR. - stream << ":test-result: "; - if (_testCaseStats.totals.assertions.allPassed()) { - stream << "PASS"; - } else if (_testCaseStats.totals.assertions.allOk()) { - stream << "XFAIL"; - } else { - stream << "FAIL"; - } - stream << ' ' << _testCaseStats.testInfo.name << '\n'; - StreamingReporterBase::testCaseEnded( _testCaseStats ); - } - - void skipTest( TestCaseInfo const& testInfo ) override { - stream << ":test-result: SKIP " << testInfo.name << '\n'; - } - - }; - -#ifdef CATCH_IMPL - AutomakeReporter::~AutomakeReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "automake", AutomakeReporter) - -} // end namespace Catch - -#endif // TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED diff --git a/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp b/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp deleted file mode 100644 index bf7d9299a50ab6..00000000000000 --- a/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Created by Daniel Garcia on 2018-12-04. - * Copyright Social Point SL. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef CATCH_REPORTER_SONARQUBE_HPP_INCLUDED -#define CATCH_REPORTER_SONARQUBE_HPP_INCLUDED - - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -namespace Catch { - - struct SonarQubeReporter : CumulativeReporterBase { - - SonarQubeReporter(ReporterConfig const& config) - : CumulativeReporterBase(config) - , xml(config.stream()) { - m_reporterPrefs.shouldRedirectStdOut = true; - m_reporterPrefs.shouldReportAllAssertions = true; - } - - ~SonarQubeReporter() override; - - static std::string getDescription() { - return "Reports test results in the Generic Test Data SonarQube XML format"; - } - - static std::set getSupportedVerbosities() { - return { Verbosity::Normal }; - } - - void noMatchingTestCases(std::string const& /*spec*/) override {} - - void testRunStarting(TestRunInfo const& testRunInfo) override { - CumulativeReporterBase::testRunStarting(testRunInfo); - xml.startElement("testExecutions"); - xml.writeAttribute("version", "1"); - } - - void testGroupEnded(TestGroupStats const& testGroupStats) override { - CumulativeReporterBase::testGroupEnded(testGroupStats); - writeGroup(*m_testGroups.back()); - } - - void testRunEndedCumulative() override { - xml.endElement(); - } - - void writeGroup(TestGroupNode const& groupNode) { - std::map testsPerFile; - for(auto const& child : groupNode.children) - testsPerFile[child->value.testInfo.lineInfo.file].push_back(child); - - for(auto const& kv : testsPerFile) - writeTestFile(kv.first.c_str(), kv.second); - } - - void writeTestFile(const char* filename, TestGroupNode::ChildNodes const& testCaseNodes) { - XmlWriter::ScopedElement e = xml.scopedElement("file"); - xml.writeAttribute("path", filename); - - for(auto const& child : testCaseNodes) - writeTestCase(*child); - } - - void writeTestCase(TestCaseNode const& testCaseNode) { - // All test cases have exactly one section - which represents the - // test case itself. That section may have 0-n nested sections - assert(testCaseNode.children.size() == 1); - SectionNode const& rootSection = *testCaseNode.children.front(); - writeSection("", rootSection, testCaseNode.value.testInfo.okToFail()); - } - - void writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail) { - std::string name = trim(sectionNode.stats.sectionInfo.name); - if(!rootName.empty()) - name = rootName + '/' + name; - - if(!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty()) { - XmlWriter::ScopedElement e = xml.scopedElement("testCase"); - xml.writeAttribute("name", name); - xml.writeAttribute("duration", static_cast(sectionNode.stats.durationInSeconds * 1000)); - - writeAssertions(sectionNode, okToFail); - } - - for(auto const& childNode : sectionNode.childSections) - writeSection(name, *childNode, okToFail); - } - - void writeAssertions(SectionNode const& sectionNode, bool okToFail) { - for(auto const& assertion : sectionNode.assertions) - writeAssertion( assertion, okToFail); - } - - void writeAssertion(AssertionStats const& stats, bool okToFail) { - AssertionResult const& result = stats.assertionResult; - if(!result.isOk()) { - std::string elementName; - if(okToFail) { - elementName = "skipped"; - } - else { - switch(result.getResultType()) { - case ResultWas::ThrewException: - case ResultWas::FatalErrorCondition: - elementName = "error"; - break; - case ResultWas::ExplicitFailure: - elementName = "failure"; - break; - case ResultWas::ExpressionFailed: - elementName = "failure"; - break; - case ResultWas::DidntThrowException: - elementName = "failure"; - break; - - // We should never see these here: - case ResultWas::Info: - case ResultWas::Warning: - case ResultWas::Ok: - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - elementName = "internalError"; - break; - } - } - - XmlWriter::ScopedElement e = xml.scopedElement(elementName); - - ReusableStringStream messageRss; - messageRss << result.getTestMacroName() << "(" << result.getExpression() << ")"; - xml.writeAttribute("message", messageRss.str()); - - ReusableStringStream textRss; - if (stats.totals.assertions.total() > 0) { - textRss << "FAILED:\n"; - if (result.hasExpression()) { - textRss << "\t" << result.getExpressionInMacro() << "\n"; - } - if (result.hasExpandedExpression()) { - textRss << "with expansion:\n\t" << result.getExpandedExpression() << "\n"; - } - } - - if(!result.getMessage().empty()) - textRss << result.getMessage() << "\n"; - - for(auto const& msg : stats.infoMessages) - if(msg.type == ResultWas::Info) - textRss << msg.message << "\n"; - - textRss << "at " << result.getSourceInfo(); - xml.writeText(textRss.str(), XmlFormatting::Newline); - } - } - - private: - XmlWriter xml; - }; - -#ifdef CATCH_IMPL - SonarQubeReporter::~SonarQubeReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "sonarqube", SonarQubeReporter ) - -} // end namespace Catch - -#endif // CATCH_REPORTER_SONARQUBE_HPP_INCLUDED \ No newline at end of file diff --git a/third_party/catch2/include/catch2/catch_reporter_tap.hpp b/third_party/catch2/include/catch2/catch_reporter_tap.hpp deleted file mode 100644 index 5ac8524ce7abeb..00000000000000 --- a/third_party/catch2/include/catch2/catch_reporter_tap.hpp +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Created by Colton Wolkins on 2015-08-15. - * Copyright 2015 Martin Moene. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED - - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -namespace Catch { - - struct TAPReporter : StreamingReporterBase { - - using StreamingReporterBase::StreamingReporterBase; - - TAPReporter( ReporterConfig const& config ): - StreamingReporterBase( config ) { - m_reporterPrefs.shouldReportAllAssertions = true; - } - - ~TAPReporter() override; - - static std::string getDescription() { - return "Reports test results in TAP format, suitable for test harnesses"; - } - - void noMatchingTestCases( std::string const& spec ) override { - stream << "# No test cases matched '" << spec << "'" << std::endl; - } - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& _assertionStats ) override { - ++counter; - - stream << "# " << currentTestCaseInfo->name << std::endl; - AssertionPrinter printer( stream, _assertionStats, counter ); - printer.print(); - - stream << std::endl; - return true; - } - - void testRunEnded( TestRunStats const& _testRunStats ) override { - printTotals( _testRunStats.totals ); - stream << "\n" << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - std::size_t counter = 0; - class AssertionPrinter { - public: - AssertionPrinter& operator= ( AssertionPrinter const& ) = delete; - AssertionPrinter( AssertionPrinter const& ) = delete; - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter ) - : stream( _stream ) - , result( _stats.assertionResult ) - , messages( _stats.infoMessages ) - , itMessage( _stats.infoMessages.begin() ) - , printInfoMessages( true ) - , counter(_counter) - {} - - void print() { - itMessage = messages.begin(); - - switch( result.getResultType() ) { - case ResultWas::Ok: - printResultType( passedString() ); - printOriginalExpression(); - printReconstructedExpression(); - if ( ! result.hasExpression() ) - printRemainingMessages( Colour::None ); - else - printRemainingMessages(); - break; - case ResultWas::ExpressionFailed: - if (result.isOk()) { - printResultType(passedString()); - } else { - printResultType(failedString()); - } - printOriginalExpression(); - printReconstructedExpression(); - if (result.isOk()) { - printIssue(" # TODO"); - } - printRemainingMessages(); - break; - case ResultWas::ThrewException: - printResultType( failedString() ); - printIssue( "unexpected exception with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::FatalErrorCondition: - printResultType( failedString() ); - printIssue( "fatal error condition with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::DidntThrowException: - printResultType( failedString() ); - printIssue( "expected exception, got none" ); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::Info: - printResultType( "info" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::Warning: - printResultType( "warning" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::ExplicitFailure: - printResultType( failedString() ); - printIssue( "explicitly" ); - printRemainingMessages( Colour::None ); - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - printResultType( "** internal error **" ); - break; - } - } - - private: - static Colour::Code dimColour() { return Colour::FileName; } - - static const char* failedString() { return "not ok"; } - static const char* passedString() { return "ok"; } - - void printSourceInfo() const { - Colour colourGuard( dimColour() ); - stream << result.getSourceInfo() << ":"; - } - - void printResultType( std::string const& passOrFail ) const { - if( !passOrFail.empty() ) { - stream << passOrFail << ' ' << counter << " -"; - } - } - - void printIssue( std::string const& issue ) const { - stream << " " << issue; - } - - void printExpressionWas() { - if( result.hasExpression() ) { - stream << ";"; - { - Colour colour( dimColour() ); - stream << " expression was:"; - } - printOriginalExpression(); - } - } - - void printOriginalExpression() const { - if( result.hasExpression() ) { - stream << " " << result.getExpression(); - } - } - - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - { - Colour colour( dimColour() ); - stream << " for: "; - } - std::string expr = result.getExpandedExpression(); - std::replace( expr.begin(), expr.end(), '\n', ' '); - stream << expr; - } - } - - void printMessage() { - if ( itMessage != messages.end() ) { - stream << " '" << itMessage->message << "'"; - ++itMessage; - } - } - - void printRemainingMessages( Colour::Code colour = dimColour() ) { - if (itMessage == messages.end()) { - return; - } - - const auto itEnd = messages.cend(); - const auto N = static_cast( std::distance( itMessage, itEnd ) ); - - { - Colour colourGuard( colour ); - stream << " with " << pluralise( N, "message" ) << ":"; - } - - while( itMessage != itEnd ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || itMessage->type != ResultWas::Info ) { - stream << " '" << itMessage->message << "'"; - if ( ++itMessage != itEnd ) { - Colour colourGuard( dimColour() ); - stream << " and"; - } - continue; - } - ++itMessage; - } - } - - private: - std::ostream& stream; - AssertionResult const& result; - std::vector messages; - std::vector::const_iterator itMessage; - bool printInfoMessages; - std::size_t counter; - }; - - void printTotals( const Totals& totals ) const { - stream << "1.." << totals.assertions.total(); - if( totals.testCases.total() == 0 ) { - stream << " # Skipped: No tests ran."; - } - } - }; - -#ifdef CATCH_IMPL - TAPReporter::~TAPReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "tap", TAPReporter ) - -} // end namespace Catch - -#endif // TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED diff --git a/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp b/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp deleted file mode 100644 index 47b7e4aac30f94..00000000000000 --- a/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Created by Phil Nash on 19th December 2014 - * Copyright 2014 Two Blue Cubes Ltd. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -#ifdef __clang__ -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - struct TeamCityReporter : StreamingReporterBase { - TeamCityReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - { - m_reporterPrefs.shouldRedirectStdOut = true; - } - - static std::string escape( std::string const& str ) { - std::string escaped = str; - replaceInPlace( escaped, "|", "||" ); - replaceInPlace( escaped, "'", "|'" ); - replaceInPlace( escaped, "\n", "|n" ); - replaceInPlace( escaped, "\r", "|r" ); - replaceInPlace( escaped, "[", "|[" ); - replaceInPlace( escaped, "]", "|]" ); - return escaped; - } - ~TeamCityReporter() override; - - static std::string getDescription() { - return "Reports test results as TeamCity service messages"; - } - - void skipTest( TestCaseInfo const& /* testInfo */ ) override { - } - - void noMatchingTestCases( std::string const& /* spec */ ) override {} - - void testGroupStarting( GroupInfo const& groupInfo ) override { - StreamingReporterBase::testGroupStarting( groupInfo ); - stream << "##teamcity[testSuiteStarted name='" - << escape( groupInfo.name ) << "']\n"; - } - void testGroupEnded( TestGroupStats const& testGroupStats ) override { - StreamingReporterBase::testGroupEnded( testGroupStats ); - stream << "##teamcity[testSuiteFinished name='" - << escape( testGroupStats.groupInfo.name ) << "']\n"; - } - - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& assertionStats ) override { - AssertionResult const& result = assertionStats.assertionResult; - if( !result.isOk() ) { - - ReusableStringStream msg; - if( !m_headerPrintedForThisSection ) - printSectionHeader( msg.get() ); - m_headerPrintedForThisSection = true; - - msg << result.getSourceInfo() << "\n"; - - switch( result.getResultType() ) { - case ResultWas::ExpressionFailed: - msg << "expression failed"; - break; - case ResultWas::ThrewException: - msg << "unexpected exception"; - break; - case ResultWas::FatalErrorCondition: - msg << "fatal error condition"; - break; - case ResultWas::DidntThrowException: - msg << "no exception was thrown where one was expected"; - break; - case ResultWas::ExplicitFailure: - msg << "explicit failure"; - break; - - // We shouldn't get here because of the isOk() test - case ResultWas::Ok: - case ResultWas::Info: - case ResultWas::Warning: - CATCH_ERROR( "Internal error in TeamCity reporter" ); - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - CATCH_ERROR( "Not implemented" ); - } - if( assertionStats.infoMessages.size() == 1 ) - msg << " with message:"; - if( assertionStats.infoMessages.size() > 1 ) - msg << " with messages:"; - for( auto const& messageInfo : assertionStats.infoMessages ) - msg << "\n \"" << messageInfo.message << "\""; - - - if( result.hasExpression() ) { - msg << - "\n " << result.getExpressionInMacro() << "\n" - "with expansion:\n" << - " " << result.getExpandedExpression() << "\n"; - } - - if( currentTestCaseInfo->okToFail() ) { - msg << "- failure ignore as test marked as 'ok to fail'\n"; - stream << "##teamcity[testIgnored" - << " name='" << escape( currentTestCaseInfo->name )<< "'" - << " message='" << escape( msg.str() ) << "'" - << "]\n"; - } - else { - stream << "##teamcity[testFailed" - << " name='" << escape( currentTestCaseInfo->name )<< "'" - << " message='" << escape( msg.str() ) << "'" - << "]\n"; - } - } - stream.flush(); - return true; - } - - void sectionStarting( SectionInfo const& sectionInfo ) override { - m_headerPrintedForThisSection = false; - StreamingReporterBase::sectionStarting( sectionInfo ); - } - - void testCaseStarting( TestCaseInfo const& testInfo ) override { - m_testTimer.start(); - StreamingReporterBase::testCaseStarting( testInfo ); - stream << "##teamcity[testStarted name='" - << escape( testInfo.name ) << "']\n"; - stream.flush(); - } - - void testCaseEnded( TestCaseStats const& testCaseStats ) override { - StreamingReporterBase::testCaseEnded( testCaseStats ); - if( !testCaseStats.stdOut.empty() ) - stream << "##teamcity[testStdOut name='" - << escape( testCaseStats.testInfo.name ) - << "' out='" << escape( testCaseStats.stdOut ) << "']\n"; - if( !testCaseStats.stdErr.empty() ) - stream << "##teamcity[testStdErr name='" - << escape( testCaseStats.testInfo.name ) - << "' out='" << escape( testCaseStats.stdErr ) << "']\n"; - stream << "##teamcity[testFinished name='" - << escape( testCaseStats.testInfo.name ) << "' duration='" - << m_testTimer.getElapsedMilliseconds() << "']\n"; - stream.flush(); - } - - private: - void printSectionHeader( std::ostream& os ) { - assert( !m_sectionStack.empty() ); - - if( m_sectionStack.size() > 1 ) { - os << getLineOfChars<'-'>() << "\n"; - - std::vector::const_iterator - it = m_sectionStack.begin()+1, // Skip first section (test case) - itEnd = m_sectionStack.end(); - for( ; it != itEnd; ++it ) - printHeaderString( os, it->name ); - os << getLineOfChars<'-'>() << "\n"; - } - - SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; - - os << lineInfo << "\n"; - os << getLineOfChars<'.'>() << "\n\n"; - } - - // if string has a : in first line will set indent to follow it on - // subsequent lines - static void printHeaderString( std::ostream& os, std::string const& _string, std::size_t indent = 0 ) { - std::size_t i = _string.find( ": " ); - if( i != std::string::npos ) - i+=2; - else - i = 0; - os << Column( _string ) - .indent( indent+i) - .initialIndent( indent ) << "\n"; - } - private: - bool m_headerPrintedForThisSection = false; - Timer m_testTimer; - }; - -#ifdef CATCH_IMPL - TeamCityReporter::~TeamCityReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "teamcity", TeamCityReporter ) - -} // end namespace Catch - -#ifdef __clang__ -# pragma clang diagnostic pop -#endif - -#endif // TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED diff --git a/third_party/json11/json11.cpp b/third_party/json11/json11.cpp deleted file mode 100644 index bc4045f07d1954..00000000000000 --- a/third_party/json11/json11.cpp +++ /dev/null @@ -1,784 +0,0 @@ -/* Copyright (c) 2013 Dropbox, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "json11.hpp" -#include -#include -#include -#include -#include - -namespace json11 { - -static const int max_depth = 200; - -using std::string; -using std::vector; -using std::map; -using std::make_shared; -using std::initializer_list; -using std::move; - -/* Helper for representing null - just a do-nothing struct, plus comparison - * operators so the helpers in JsonValue work. We can't use nullptr_t because - * it may not be orderable. - */ -struct NullStruct { - bool operator==(NullStruct) const { return true; } - bool operator<(NullStruct) const { return false; } -}; - -/* * * * * * * * * * * * * * * * * * * * - * Serialization - */ - -static void dump(NullStruct, string &out) { - out += "null"; -} - -static void dump(double value, string &out) { - if (std::isfinite(value)) { - char buf[32]; - snprintf(buf, sizeof buf, "%.17g", value); - out += buf; - } else { - out += "null"; - } -} - -static void dump(int value, string &out) { - char buf[32]; - snprintf(buf, sizeof buf, "%d", value); - out += buf; -} - -static void dump(bool value, string &out) { - out += value ? "true" : "false"; -} - -static void dump(const string &value, string &out) { - out += '"'; - for (size_t i = 0; i < value.length(); i++) { - const char ch = value[i]; - if (ch == '\\') { - out += "\\\\"; - } else if (ch == '"') { - out += "\\\""; - } else if (ch == '\b') { - out += "\\b"; - } else if (ch == '\f') { - out += "\\f"; - } else if (ch == '\n') { - out += "\\n"; - } else if (ch == '\r') { - out += "\\r"; - } else if (ch == '\t') { - out += "\\t"; - } else if (static_cast(ch) <= 0x1f) { - char buf[8]; - snprintf(buf, sizeof buf, "\\u%04x", ch); - out += buf; - } else if (static_cast(ch) == 0xe2 && static_cast(value[i+1]) == 0x80 - && static_cast(value[i+2]) == 0xa8) { - out += "\\u2028"; - i += 2; - } else if (static_cast(ch) == 0xe2 && static_cast(value[i+1]) == 0x80 - && static_cast(value[i+2]) == 0xa9) { - out += "\\u2029"; - i += 2; - } else { - out += ch; - } - } - out += '"'; -} - -static void dump(const Json::array &values, string &out) { - bool first = true; - out += "["; - for (const auto &value : values) { - if (!first) - out += ", "; - value.dump(out); - first = false; - } - out += "]"; -} - -static void dump(const Json::object &values, string &out) { - bool first = true; - out += "{"; - for (const auto &kv : values) { - if (!first) - out += ", "; - dump(kv.first, out); - out += ": "; - kv.second.dump(out); - first = false; - } - out += "}"; -} - -void Json::dump(string &out) const { - m_ptr->dump(out); -} - -/* * * * * * * * * * * * * * * * * * * * - * Value wrappers - */ - -template -class Value : public JsonValue { -protected: - - // Constructors - explicit Value(const T &value) : m_value(value) {} - explicit Value(T &&value) : m_value(move(value)) {} - - // Get type tag - Json::Type type() const override { - return tag; - } - - // Comparisons - bool equals(const JsonValue * other) const override { - return m_value == static_cast *>(other)->m_value; - } - bool less(const JsonValue * other) const override { - return m_value < static_cast *>(other)->m_value; - } - - const T m_value; - void dump(string &out) const override { json11::dump(m_value, out); } -}; - -class JsonDouble final : public Value { - double number_value() const override { return m_value; } - int int_value() const override { return static_cast(m_value); } - bool equals(const JsonValue * other) const override { return m_value == other->number_value(); } - bool less(const JsonValue * other) const override { return m_value < other->number_value(); } -public: - explicit JsonDouble(double value) : Value(value) {} -}; - -class JsonInt final : public Value { - double number_value() const override { return m_value; } - int int_value() const override { return m_value; } - bool equals(const JsonValue * other) const override { return m_value == other->number_value(); } - bool less(const JsonValue * other) const override { return m_value < other->number_value(); } -public: - explicit JsonInt(int value) : Value(value) {} -}; - -class JsonBoolean final : public Value { - bool bool_value() const override { return m_value; } -public: - explicit JsonBoolean(bool value) : Value(value) {} -}; - -class JsonString final : public Value { - const string &string_value() const override { return m_value; } -public: - explicit JsonString(const string &value) : Value(value) {} - explicit JsonString(string &&value) : Value(move(value)) {} -}; - -class JsonArray final : public Value { - const Json::array &array_items() const override { return m_value; } - const Json & operator[](size_t i) const override; -public: - explicit JsonArray(const Json::array &value) : Value(value) {} - explicit JsonArray(Json::array &&value) : Value(move(value)) {} -}; - -class JsonObject final : public Value { - const Json::object &object_items() const override { return m_value; } - const Json & operator[](const string &key) const override; -public: - explicit JsonObject(const Json::object &value) : Value(value) {} - explicit JsonObject(Json::object &&value) : Value(move(value)) {} -}; - -class JsonNull final : public Value { -public: - JsonNull() : Value({}) {} -}; - -/* * * * * * * * * * * * * * * * * * * * - * Static globals - static-init-safe - */ -struct Statics { - const std::shared_ptr null = make_shared(); - const std::shared_ptr t = make_shared(true); - const std::shared_ptr f = make_shared(false); - const string empty_string; - const vector empty_vector; - const map empty_map; - Statics() {} -}; - -static const Statics & statics() { - static const Statics s {}; - return s; -} - -static const Json & static_null() { - // This has to be separate, not in Statics, because Json() accesses statics().null. - static const Json json_null; - return json_null; -} - -/* * * * * * * * * * * * * * * * * * * * - * Constructors - */ - -Json::Json() noexcept : m_ptr(statics().null) {} -Json::Json(std::nullptr_t) noexcept : m_ptr(statics().null) {} -Json::Json(double value) : m_ptr(make_shared(value)) {} -Json::Json(int value) : m_ptr(make_shared(value)) {} -Json::Json(bool value) : m_ptr(value ? statics().t : statics().f) {} -Json::Json(const string &value) : m_ptr(make_shared(value)) {} -Json::Json(string &&value) : m_ptr(make_shared(move(value))) {} -Json::Json(const char * value) : m_ptr(make_shared(value)) {} -Json::Json(const Json::array &values) : m_ptr(make_shared(values)) {} -Json::Json(Json::array &&values) : m_ptr(make_shared(move(values))) {} -Json::Json(const Json::object &values) : m_ptr(make_shared(values)) {} -Json::Json(Json::object &&values) : m_ptr(make_shared(move(values))) {} - -/* * * * * * * * * * * * * * * * * * * * - * Accessors - */ - -Json::Type Json::type() const { return m_ptr->type(); } -double Json::number_value() const { return m_ptr->number_value(); } -int Json::int_value() const { return m_ptr->int_value(); } -bool Json::bool_value() const { return m_ptr->bool_value(); } -const string & Json::string_value() const { return m_ptr->string_value(); } -const vector & Json::array_items() const { return m_ptr->array_items(); } -const map & Json::object_items() const { return m_ptr->object_items(); } -const Json & Json::operator[] (size_t i) const { return (*m_ptr)[i]; } -const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key]; } - -double JsonValue::number_value() const { return 0; } -int JsonValue::int_value() const { return 0; } -bool JsonValue::bool_value() const { return false; } -const string & JsonValue::string_value() const { return statics().empty_string; } -const vector & JsonValue::array_items() const { return statics().empty_vector; } -const map & JsonValue::object_items() const { return statics().empty_map; } -const Json & JsonValue::operator[] (size_t) const { return static_null(); } -const Json & JsonValue::operator[] (const string &) const { return static_null(); } - -const Json & JsonObject::operator[] (const string &key) const { - auto iter = m_value.find(key); - return (iter == m_value.end()) ? static_null() : iter->second; -} -const Json & JsonArray::operator[] (size_t i) const { - if (i >= m_value.size()) return static_null(); - else return m_value[i]; -} - -/* * * * * * * * * * * * * * * * * * * * - * Comparison - */ - -bool Json::operator== (const Json &other) const { - if (m_ptr->type() != other.m_ptr->type()) - return false; - - return m_ptr->equals(other.m_ptr.get()); -} - -bool Json::operator< (const Json &other) const { - if (m_ptr->type() != other.m_ptr->type()) - return m_ptr->type() < other.m_ptr->type(); - - return m_ptr->less(other.m_ptr.get()); -} - -/* * * * * * * * * * * * * * * * * * * * - * Parsing - */ - -/* esc(c) - * - * Format char c suitable for printing in an error message. - */ -static inline string esc(char c) { - char buf[12]; - if (static_cast(c) >= 0x20 && static_cast(c) <= 0x7f) { - snprintf(buf, sizeof buf, "'%c' (%d)", c, c); - } else { - snprintf(buf, sizeof buf, "(%d)", c); - } - return string(buf); -} - -static inline bool in_range(long x, long lower, long upper) { - return (x >= lower && x <= upper); -} - -namespace { -/* JsonParser - * - * Object that tracks all state of an in-progress parse. - */ -struct JsonParser final { - - /* State - */ - const string &str; - size_t i; - string &err; - bool failed; - const JsonParse strategy; - - /* fail(msg, err_ret = Json()) - * - * Mark this parse as failed. - */ - Json fail(string &&msg) { - return fail(move(msg), Json()); - } - - template - T fail(string &&msg, const T err_ret) { - if (!failed) - err = std::move(msg); - failed = true; - return err_ret; - } - - /* consume_whitespace() - * - * Advance until the current character is non-whitespace. - */ - void consume_whitespace() { - while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t') - i++; - } - - /* consume_comment() - * - * Advance comments (c-style inline and multiline). - */ - bool consume_comment() { - bool comment_found = false; - if (str[i] == '/') { - i++; - if (i == str.size()) - return fail("unexpected end of input after start of comment", false); - if (str[i] == '/') { // inline comment - i++; - // advance until next line, or end of input - while (i < str.size() && str[i] != '\n') { - i++; - } - comment_found = true; - } - else if (str[i] == '*') { // multiline comment - i++; - if (i > str.size()-2) - return fail("unexpected end of input inside multi-line comment", false); - // advance until closing tokens - while (!(str[i] == '*' && str[i+1] == '/')) { - i++; - if (i > str.size()-2) - return fail( - "unexpected end of input inside multi-line comment", false); - } - i += 2; - comment_found = true; - } - else - return fail("malformed comment", false); - } - return comment_found; - } - - /* consume_garbage() - * - * Advance until the current character is non-whitespace and non-comment. - */ - void consume_garbage() { - consume_whitespace(); - if(strategy == JsonParse::COMMENTS) { - bool comment_found = false; - do { - comment_found = consume_comment(); - if (failed) return; - consume_whitespace(); - } - while(comment_found); - } - } - - /* get_next_token() - * - * Return the next non-whitespace character. If the end of the input is reached, - * flag an error and return 0. - */ - char get_next_token() { - consume_garbage(); - if (failed) return (char)0; - if (i == str.size()) - return fail("unexpected end of input", (char)0); - - return str[i++]; - } - - /* encode_utf8(pt, out) - * - * Encode pt as UTF-8 and add it to out. - */ - void encode_utf8(long pt, string & out) { - if (pt < 0) - return; - - if (pt < 0x80) { - out += static_cast(pt); - } else if (pt < 0x800) { - out += static_cast((pt >> 6) | 0xC0); - out += static_cast((pt & 0x3F) | 0x80); - } else if (pt < 0x10000) { - out += static_cast((pt >> 12) | 0xE0); - out += static_cast(((pt >> 6) & 0x3F) | 0x80); - out += static_cast((pt & 0x3F) | 0x80); - } else { - out += static_cast((pt >> 18) | 0xF0); - out += static_cast(((pt >> 12) & 0x3F) | 0x80); - out += static_cast(((pt >> 6) & 0x3F) | 0x80); - out += static_cast((pt & 0x3F) | 0x80); - } - } - - /* parse_string() - * - * Parse a string, starting at the current position. - */ - string parse_string() { - string out; - long last_escaped_codepoint = -1; - while (true) { - if (i == str.size()) - return fail("unexpected end of input in string", ""); - - char ch = str[i++]; - - if (ch == '"') { - encode_utf8(last_escaped_codepoint, out); - return out; - } - - if (in_range(ch, 0, 0x1f)) - return fail("unescaped " + esc(ch) + " in string", ""); - - // The usual case: non-escaped characters - if (ch != '\\') { - encode_utf8(last_escaped_codepoint, out); - last_escaped_codepoint = -1; - out += ch; - continue; - } - - // Handle escapes - if (i == str.size()) - return fail("unexpected end of input in string", ""); - - ch = str[i++]; - - if (ch == 'u') { - // Extract 4-byte escape sequence - string esc = str.substr(i, 4); - // Explicitly check length of the substring. The following loop - // relies on std::string returning the terminating NUL when - // accessing str[length]. Checking here reduces brittleness. - if (esc.length() < 4) { - return fail("bad \\u escape: " + esc, ""); - } - for (size_t j = 0; j < 4; j++) { - if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F') - && !in_range(esc[j], '0', '9')) - return fail("bad \\u escape: " + esc, ""); - } - - long codepoint = strtol(esc.data(), nullptr, 16); - - // JSON specifies that characters outside the BMP shall be encoded as a pair - // of 4-hex-digit \u escapes encoding their surrogate pair components. Check - // whether we're in the middle of such a beast: the previous codepoint was an - // escaped lead (high) surrogate, and this is a trail (low) surrogate. - if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF) - && in_range(codepoint, 0xDC00, 0xDFFF)) { - // Reassemble the two surrogate pairs into one astral-plane character, per - // the UTF-16 algorithm. - encode_utf8((((last_escaped_codepoint - 0xD800) << 10) - | (codepoint - 0xDC00)) + 0x10000, out); - last_escaped_codepoint = -1; - } else { - encode_utf8(last_escaped_codepoint, out); - last_escaped_codepoint = codepoint; - } - - i += 4; - continue; - } - - encode_utf8(last_escaped_codepoint, out); - last_escaped_codepoint = -1; - - if (ch == 'b') { - out += '\b'; - } else if (ch == 'f') { - out += '\f'; - } else if (ch == 'n') { - out += '\n'; - } else if (ch == 'r') { - out += '\r'; - } else if (ch == 't') { - out += '\t'; - } else if (ch == '"' || ch == '\\' || ch == '/') { - out += ch; - } else { - return fail("invalid escape character " + esc(ch), ""); - } - } - } - - /* parse_number() - * - * Parse a double. - */ - Json parse_number() { - size_t start_pos = i; - - if (str[i] == '-') - i++; - - // Integer part - if (str[i] == '0') { - i++; - if (in_range(str[i], '0', '9')) - return fail("leading 0s not permitted in numbers"); - } else if (in_range(str[i], '1', '9')) { - i++; - while (in_range(str[i], '0', '9')) - i++; - } else { - return fail("invalid " + esc(str[i]) + " in number"); - } - - if (str[i] != '.' && str[i] != 'e' && str[i] != 'E' - && (i - start_pos) <= static_cast(std::numeric_limits::digits10)) { - return std::atoi(str.c_str() + start_pos); - } - - // Decimal part - if (str[i] == '.') { - i++; - if (!in_range(str[i], '0', '9')) - return fail("at least one digit required in fractional part"); - - while (in_range(str[i], '0', '9')) - i++; - } - - // Exponent part - if (str[i] == 'e' || str[i] == 'E') { - i++; - - if (str[i] == '+' || str[i] == '-') - i++; - - if (!in_range(str[i], '0', '9')) - return fail("at least one digit required in exponent"); - - while (in_range(str[i], '0', '9')) - i++; - } - - return std::strtod(str.c_str() + start_pos, nullptr); - } - - /* expect(str, res) - * - * Expect that 'str' starts at the character that was just read. If it does, advance - * the input and return res. If not, flag an error. - */ - Json expect(const string &expected, Json res) { - assert(i != 0); - i--; - if (str.compare(i, expected.length(), expected) == 0) { - i += expected.length(); - return res; - } else { - return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length())); - } - } - - /* parse_json() - * - * Parse a JSON object. - */ - Json parse_json(int depth) { - if (depth > max_depth) { - return fail("exceeded maximum nesting depth"); - } - - char ch = get_next_token(); - if (failed) - return Json(); - - if (ch == '-' || (ch >= '0' && ch <= '9')) { - i--; - return parse_number(); - } - - if (ch == 't') - return expect("true", true); - - if (ch == 'f') - return expect("false", false); - - if (ch == 'n') - return expect("null", Json()); - - if (ch == '"') - return parse_string(); - - if (ch == '{') { - map data; - ch = get_next_token(); - if (ch == '}') - return data; - - while (1) { - if (ch != '"') - return fail("expected '\"' in object, got " + esc(ch)); - - string key = parse_string(); - if (failed) - return Json(); - - ch = get_next_token(); - if (ch != ':') - return fail("expected ':' in object, got " + esc(ch)); - - data[std::move(key)] = parse_json(depth + 1); - if (failed) - return Json(); - - ch = get_next_token(); - if (ch == '}') - break; - if (ch != ',') - return fail("expected ',' in object, got " + esc(ch)); - - ch = get_next_token(); - } - return data; - } - - if (ch == '[') { - vector data; - ch = get_next_token(); - if (ch == ']') - return data; - - while (1) { - i--; - data.push_back(parse_json(depth + 1)); - if (failed) - return Json(); - - ch = get_next_token(); - if (ch == ']') - break; - if (ch != ',') - return fail("expected ',' in list, got " + esc(ch)); - - ch = get_next_token(); - (void)ch; - } - return data; - } - - return fail("expected value, got " + esc(ch)); - } -}; -}//namespace { - -Json Json::parse(const string &in, string &err, JsonParse strategy) { - JsonParser parser { in, 0, err, false, strategy }; - Json result = parser.parse_json(0); - - // Check for any trailing garbage - parser.consume_garbage(); - if (parser.failed) - return Json(); - if (parser.i != in.size()) - return parser.fail("unexpected trailing " + esc(in[parser.i])); - - return result; -} - -// Documented in json11.hpp -vector Json::parse_multi(const string &in, - std::string::size_type &parser_stop_pos, - string &err, - JsonParse strategy) { - JsonParser parser { in, 0, err, false, strategy }; - parser_stop_pos = 0; - vector json_vec; - while (parser.i != in.size() && !parser.failed) { - json_vec.push_back(parser.parse_json(0)); - if (parser.failed) - break; - - // Check for another object - parser.consume_garbage(); - if (parser.failed) - break; - parser_stop_pos = parser.i; - } - return json_vec; -} - -/* * * * * * * * * * * * * * * * * * * * - * Shape-checking - */ - -bool Json::has_shape(const shape & types, string & err) const { - if (!is_object()) { - err = "expected JSON object, got " + dump(); - return false; - } - - for (auto & item : types) { - if ((*this)[item.first].type() != item.second) { - err = "bad type for " + item.first + " in " + dump(); - return false; - } - } - - return true; -} - -} // namespace json11 diff --git a/third_party/json11/json11.hpp b/third_party/json11/json11.hpp deleted file mode 100644 index 5202ef9323bb79..00000000000000 --- a/third_party/json11/json11.hpp +++ /dev/null @@ -1,232 +0,0 @@ -/* json11 - * - * json11 is a tiny JSON library for C++11, providing JSON parsing and serialization. - * - * The core object provided by the library is json11::Json. A Json object represents any JSON - * value: null, bool, number (int or double), string (std::string), array (std::vector), or - * object (std::map). - * - * Json objects act like values: they can be assigned, copied, moved, compared for equality or - * order, etc. There are also helper methods Json::dump, to serialize a Json to a string, and - * Json::parse (static) to parse a std::string as a Json object. - * - * Internally, the various types of Json object are represented by the JsonValue class - * hierarchy. - * - * A note on numbers - JSON specifies the syntax of number formatting but not its semantics, - * so some JSON implementations distinguish between integers and floating-point numbers, while - * some don't. In json11, we choose the latter. Because some JSON implementations (namely - * Javascript itself) treat all numbers as the same type, distinguishing the two leads - * to JSON that will be *silently* changed by a round-trip through those implementations. - * Dangerous! To avoid that risk, json11 stores all numbers as double internally, but also - * provides integer helpers. - * - * Fortunately, double-precision IEEE754 ('double') can precisely store any integer in the - * range +/-2^53, which includes every 'int' on most systems. (Timestamps often use int64 - * or long long to avoid the Y2038K problem; a double storing microseconds since some epoch - * will be exact for +/- 275 years.) - */ - -/* Copyright (c) 2013 Dropbox, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#pragma once - -#include -#include -#include -#include -#include - -#ifdef _MSC_VER - #if _MSC_VER <= 1800 // VS 2013 - #ifndef noexcept - #define noexcept throw() - #endif - - #ifndef snprintf - #define snprintf _snprintf_s - #endif - #endif -#endif - -namespace json11 { - -enum JsonParse { - STANDARD, COMMENTS -}; - -class JsonValue; - -class Json final { -public: - // Types - enum Type { - NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT - }; - - // Array and object typedefs - typedef std::vector array; - typedef std::map object; - - // Constructors for the various types of JSON value. - Json() noexcept; // NUL - Json(std::nullptr_t) noexcept; // NUL - Json(double value); // NUMBER - Json(int value); // NUMBER - Json(bool value); // BOOL - Json(const std::string &value); // STRING - Json(std::string &&value); // STRING - Json(const char * value); // STRING - Json(const array &values); // ARRAY - Json(array &&values); // ARRAY - Json(const object &values); // OBJECT - Json(object &&values); // OBJECT - - // Implicit constructor: anything with a to_json() function. - template - Json(const T & t) : Json(t.to_json()) {} - - // Implicit constructor: map-like objects (std::map, std::unordered_map, etc) - template ::value - && std::is_constructible::value, - int>::type = 0> - Json(const M & m) : Json(object(m.begin(), m.end())) {} - - // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc) - template ::value, - int>::type = 0> - Json(const V & v) : Json(array(v.begin(), v.end())) {} - - // This prevents Json(some_pointer) from accidentally producing a bool. Use - // Json(bool(some_pointer)) if that behavior is desired. - Json(void *) = delete; - - // Accessors - Type type() const; - - bool is_null() const { return type() == NUL; } - bool is_number() const { return type() == NUMBER; } - bool is_bool() const { return type() == BOOL; } - bool is_string() const { return type() == STRING; } - bool is_array() const { return type() == ARRAY; } - bool is_object() const { return type() == OBJECT; } - - // Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not - // distinguish between integer and non-integer numbers - number_value() and int_value() - // can both be applied to a NUMBER-typed object. - double number_value() const; - int int_value() const; - - // Return the enclosed value if this is a boolean, false otherwise. - bool bool_value() const; - // Return the enclosed string if this is a string, "" otherwise. - const std::string &string_value() const; - // Return the enclosed std::vector if this is an array, or an empty vector otherwise. - const array &array_items() const; - // Return the enclosed std::map if this is an object, or an empty map otherwise. - const object &object_items() const; - - // Return a reference to arr[i] if this is an array, Json() otherwise. - const Json & operator[](size_t i) const; - // Return a reference to obj[key] if this is an object, Json() otherwise. - const Json & operator[](const std::string &key) const; - - // Serialize. - void dump(std::string &out) const; - std::string dump() const { - std::string out; - dump(out); - return out; - } - - // Parse. If parse fails, return Json() and assign an error message to err. - static Json parse(const std::string & in, - std::string & err, - JsonParse strategy = JsonParse::STANDARD); - static Json parse(const char * in, - std::string & err, - JsonParse strategy = JsonParse::STANDARD) { - if (in) { - return parse(std::string(in), err, strategy); - } else { - err = "null input"; - return nullptr; - } - } - // Parse multiple objects, concatenated or separated by whitespace - static std::vector parse_multi( - const std::string & in, - std::string::size_type & parser_stop_pos, - std::string & err, - JsonParse strategy = JsonParse::STANDARD); - - static inline std::vector parse_multi( - const std::string & in, - std::string & err, - JsonParse strategy = JsonParse::STANDARD) { - std::string::size_type parser_stop_pos; - return parse_multi(in, parser_stop_pos, err, strategy); - } - - bool operator== (const Json &rhs) const; - bool operator< (const Json &rhs) const; - bool operator!= (const Json &rhs) const { return !(*this == rhs); } - bool operator<= (const Json &rhs) const { return !(rhs < *this); } - bool operator> (const Json &rhs) const { return (rhs < *this); } - bool operator>= (const Json &rhs) const { return !(*this < rhs); } - - /* has_shape(types, err) - * - * Return true if this is a JSON object and, for each item in types, has a field of - * the given type. If not, return false and set err to a descriptive message. - */ - typedef std::initializer_list> shape; - bool has_shape(const shape & types, std::string & err) const; - -private: - std::shared_ptr m_ptr; -}; - -// Internal class hierarchy - JsonValue objects are not exposed to users of this API. -class JsonValue { -protected: - friend class Json; - friend class JsonInt; - friend class JsonDouble; - virtual Json::Type type() const = 0; - virtual bool equals(const JsonValue * other) const = 0; - virtual bool less(const JsonValue * other) const = 0; - virtual void dump(std::string &out) const = 0; - virtual double number_value() const; - virtual int int_value() const; - virtual bool bool_value() const; - virtual const std::string &string_value() const; - virtual const Json::array &array_items() const; - virtual const Json &operator[](size_t i) const; - virtual const Json::object &object_items() const; - virtual const Json &operator[](const std::string &key) const; - virtual ~JsonValue() {} -}; - -} // namespace json11 diff --git a/third_party/kaitai/custom_decoder.h b/third_party/kaitai/custom_decoder.h deleted file mode 100644 index 6da7f5fd23cd63..00000000000000 --- a/third_party/kaitai/custom_decoder.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef KAITAI_CUSTOM_DECODER_H -#define KAITAI_CUSTOM_DECODER_H - -#include - -namespace kaitai { - -class custom_decoder { -public: - virtual ~custom_decoder() {}; - virtual std::string decode(std::string src) = 0; -}; - -} - -#endif diff --git a/third_party/kaitai/exceptions.h b/third_party/kaitai/exceptions.h deleted file mode 100644 index 5c09c4672b8c25..00000000000000 --- a/third_party/kaitai/exceptions.h +++ /dev/null @@ -1,189 +0,0 @@ -#ifndef KAITAI_EXCEPTIONS_H -#define KAITAI_EXCEPTIONS_H - -#include - -#include -#include - -// We need to use "noexcept" in virtual destructor of our exceptions -// subclasses. Different compilers have different ideas on how to -// achieve that: C++98 compilers prefer `throw()`, C++11 and later -// use `noexcept`. We define KS_NOEXCEPT macro for that. - -#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900) -#define KS_NOEXCEPT noexcept -#else -#define KS_NOEXCEPT throw() -#endif - -namespace kaitai { - -/** - * Common ancestor for all error originating from Kaitai Struct usage. - * Stores KSY source path, pointing to an element supposedly guilty of - * an error. - */ -class kstruct_error: public std::runtime_error { -public: - kstruct_error(const std::string what, const std::string src_path): - std::runtime_error(src_path + ": " + what), - m_src_path(src_path) - { - } - - virtual ~kstruct_error() KS_NOEXCEPT {}; - -protected: - const std::string m_src_path; -}; - -/** - * Error that occurs when default endianness should be decided with - * a switch, but nothing matches (although using endianness expression - * implies that there should be some positive result). - */ -class undecided_endianness_error: public kstruct_error { -public: - undecided_endianness_error(const std::string src_path): - kstruct_error("unable to decide on endianness for a type", src_path) - { - } - - virtual ~undecided_endianness_error() KS_NOEXCEPT {}; -}; - -/** - * Common ancestor for all validation failures. Stores pointer to - * KaitaiStream IO object which was involved in an error. - */ -class validation_failed_error: public kstruct_error { -public: - validation_failed_error(const std::string what, kstream* io, const std::string src_path): - kstruct_error("at pos " + kstream::to_string(static_cast(io->pos())) + ": validation failed: " + what, src_path), - m_io(io) - { - } - -// "at pos #{io.pos}: validation failed: #{msg}" - - virtual ~validation_failed_error() KS_NOEXCEPT {}; - -protected: - kstream* m_io; -}; - -/** - * Signals validation failure: we required "actual" value to be equal to - * "expected", but it turned out that it's not. - */ -template -class validation_not_equal_error: public validation_failed_error { -public: - validation_not_equal_error(const T& expected, const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not equal", io, src_path), - m_expected(expected), - m_actual(actual) - { - } - - // "not equal, expected #{expected.inspect}, but got #{actual.inspect}" - - virtual ~validation_not_equal_error() KS_NOEXCEPT {}; - -protected: - const T& m_expected; - const T& m_actual; -}; - -/** - * Signals validation failure: we required "actual" value to be greater - * than or equal to "min", but it turned out that it's not. - */ -template -class validation_less_than_error: public validation_failed_error { -public: - validation_less_than_error(const T& min, const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not in range", io, src_path), - m_min(min), - m_actual(actual) - { - } - - // "not in range, min #{min.inspect}, but got #{actual.inspect}" - - virtual ~validation_less_than_error() KS_NOEXCEPT {}; - -protected: - const T& m_min; - const T& m_actual; -}; - -/** - * Signals validation failure: we required "actual" value to be less - * than or equal to "max", but it turned out that it's not. - */ -template -class validation_greater_than_error: public validation_failed_error { -public: - validation_greater_than_error(const T& max, const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not in range", io, src_path), - m_max(max), - m_actual(actual) - { - } - - // "not in range, max #{max.inspect}, but got #{actual.inspect}" - - virtual ~validation_greater_than_error() KS_NOEXCEPT {}; - -protected: - const T& m_max; - const T& m_actual; -}; - -/** - * Signals validation failure: we required "actual" value to be from - * the list, but it turned out that it's not. - */ -template -class validation_not_any_of_error: public validation_failed_error { -public: - validation_not_any_of_error(const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not any of the list", io, src_path), - m_actual(actual) - { - } - - // "not any of the list, got #{actual.inspect}" - - virtual ~validation_not_any_of_error() KS_NOEXCEPT {}; - -protected: - const T& m_actual; -}; - -/** - * Signals validation failure: we required "actual" value to match - * the expression, but it turned out that it doesn't. - */ -template -class validation_expr_error: public validation_failed_error { -public: - validation_expr_error(const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not matching the expression", io, src_path), - m_actual(actual) - { - } - - // "not matching the expression, got #{actual.inspect}" - - virtual ~validation_expr_error() KS_NOEXCEPT {}; - -protected: - const T& m_actual; -}; - -} - -#endif diff --git a/third_party/kaitai/kaitaistream.cpp b/third_party/kaitai/kaitaistream.cpp deleted file mode 100644 index d82ddb7e8279ec..00000000000000 --- a/third_party/kaitai/kaitaistream.cpp +++ /dev/null @@ -1,689 +0,0 @@ -#include - -#if defined(__APPLE__) -#include -#include -#define bswap_16(x) OSSwapInt16(x) -#define bswap_32(x) OSSwapInt32(x) -#define bswap_64(x) OSSwapInt64(x) -#define __BYTE_ORDER BYTE_ORDER -#define __BIG_ENDIAN BIG_ENDIAN -#define __LITTLE_ENDIAN LITTLE_ENDIAN -#elif defined(_MSC_VER) // !__APPLE__ -#include -#define __LITTLE_ENDIAN 1234 -#define __BIG_ENDIAN 4321 -#define __BYTE_ORDER __LITTLE_ENDIAN -#define bswap_16(x) _byteswap_ushort(x) -#define bswap_32(x) _byteswap_ulong(x) -#define bswap_64(x) _byteswap_uint64(x) -#else // !__APPLE__ or !_MSC_VER -#include -#include -#endif - -#include -#include -#include - -kaitai::kstream::kstream(std::istream* io) { - m_io = io; - init(); -} - -kaitai::kstream::kstream(std::string& data): m_io_str(data) { - m_io = &m_io_str; - init(); -} - -void kaitai::kstream::init() { - exceptions_enable(); - align_to_byte(); -} - -void kaitai::kstream::close() { - // m_io->close(); -} - -void kaitai::kstream::exceptions_enable() const { - m_io->exceptions( - std::istream::eofbit | - std::istream::failbit | - std::istream::badbit - ); -} - -// ======================================================================== -// Stream positioning -// ======================================================================== - -bool kaitai::kstream::is_eof() const { - if (m_bits_left > 0) { - return false; - } - char t; - m_io->exceptions( - std::istream::badbit - ); - m_io->get(t); - if (m_io->eof()) { - m_io->clear(); - exceptions_enable(); - return true; - } else { - m_io->unget(); - exceptions_enable(); - return false; - } -} - -void kaitai::kstream::seek(uint64_t pos) { - m_io->seekg(pos); -} - -uint64_t kaitai::kstream::pos() { - return m_io->tellg(); -} - -uint64_t kaitai::kstream::size() { - std::iostream::pos_type cur_pos = m_io->tellg(); - m_io->seekg(0, std::ios::end); - std::iostream::pos_type len = m_io->tellg(); - m_io->seekg(cur_pos); - return len; -} - -// ======================================================================== -// Integer numbers -// ======================================================================== - -// ------------------------------------------------------------------------ -// Signed -// ------------------------------------------------------------------------ - -int8_t kaitai::kstream::read_s1() { - char t; - m_io->get(t); - return t; -} - -// ........................................................................ -// Big-endian -// ........................................................................ - -int16_t kaitai::kstream::read_s2be() { - int16_t t; - m_io->read(reinterpret_cast(&t), 2); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_16(t); -#endif - return t; -} - -int32_t kaitai::kstream::read_s4be() { - int32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_32(t); -#endif - return t; -} - -int64_t kaitai::kstream::read_s8be() { - int64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_64(t); -#endif - return t; -} - -// ........................................................................ -// Little-endian -// ........................................................................ - -int16_t kaitai::kstream::read_s2le() { - int16_t t; - m_io->read(reinterpret_cast(&t), 2); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_16(t); -#endif - return t; -} - -int32_t kaitai::kstream::read_s4le() { - int32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_32(t); -#endif - return t; -} - -int64_t kaitai::kstream::read_s8le() { - int64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_64(t); -#endif - return t; -} - -// ------------------------------------------------------------------------ -// Unsigned -// ------------------------------------------------------------------------ - -uint8_t kaitai::kstream::read_u1() { - char t; - m_io->get(t); - return t; -} - -// ........................................................................ -// Big-endian -// ........................................................................ - -uint16_t kaitai::kstream::read_u2be() { - uint16_t t; - m_io->read(reinterpret_cast(&t), 2); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_16(t); -#endif - return t; -} - -uint32_t kaitai::kstream::read_u4be() { - uint32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_32(t); -#endif - return t; -} - -uint64_t kaitai::kstream::read_u8be() { - uint64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_64(t); -#endif - return t; -} - -// ........................................................................ -// Little-endian -// ........................................................................ - -uint16_t kaitai::kstream::read_u2le() { - uint16_t t; - m_io->read(reinterpret_cast(&t), 2); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_16(t); -#endif - return t; -} - -uint32_t kaitai::kstream::read_u4le() { - uint32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_32(t); -#endif - return t; -} - -uint64_t kaitai::kstream::read_u8le() { - uint64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_64(t); -#endif - return t; -} - -// ======================================================================== -// Floating point numbers -// ======================================================================== - -// ........................................................................ -// Big-endian -// ........................................................................ - -float kaitai::kstream::read_f4be() { - uint32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_32(t); -#endif - return reinterpret_cast(t); -} - -double kaitai::kstream::read_f8be() { - uint64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_64(t); -#endif - return reinterpret_cast(t); -} - -// ........................................................................ -// Little-endian -// ........................................................................ - -float kaitai::kstream::read_f4le() { - uint32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_32(t); -#endif - return reinterpret_cast(t); -} - -double kaitai::kstream::read_f8le() { - uint64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_64(t); -#endif - return reinterpret_cast(t); -} - -// ======================================================================== -// Unaligned bit values -// ======================================================================== - -void kaitai::kstream::align_to_byte() { - m_bits_left = 0; - m_bits = 0; -} - -uint64_t kaitai::kstream::read_bits_int_be(int n) { - int bits_needed = n - m_bits_left; - if (bits_needed > 0) { - // 1 bit => 1 byte - // 8 bits => 1 byte - // 9 bits => 2 bytes - int bytes_needed = ((bits_needed - 1) / 8) + 1; - if (bytes_needed > 8) - throw std::runtime_error("read_bits_int: more than 8 bytes requested"); - char buf[8]; - m_io->read(buf, bytes_needed); - for (int i = 0; i < bytes_needed; i++) { - uint8_t b = buf[i]; - m_bits <<= 8; - m_bits |= b; - m_bits_left += 8; - } - } - - // raw mask with required number of 1s, starting from lowest bit - uint64_t mask = get_mask_ones(n); - // shift mask to align with highest bits available in @bits - int shift_bits = m_bits_left - n; - mask <<= shift_bits; - // derive reading result - uint64_t res = (m_bits & mask) >> shift_bits; - // clear top bits that we've just read => AND with 1s - m_bits_left -= n; - mask = get_mask_ones(m_bits_left); - m_bits &= mask; - - return res; -} - -// Deprecated, use read_bits_int_be() instead. -uint64_t kaitai::kstream::read_bits_int(int n) { - return read_bits_int_be(n); -} - -uint64_t kaitai::kstream::read_bits_int_le(int n) { - int bits_needed = n - m_bits_left; - if (bits_needed > 0) { - // 1 bit => 1 byte - // 8 bits => 1 byte - // 9 bits => 2 bytes - int bytes_needed = ((bits_needed - 1) / 8) + 1; - if (bytes_needed > 8) - throw std::runtime_error("read_bits_int_le: more than 8 bytes requested"); - char buf[8]; - m_io->read(buf, bytes_needed); - for (int i = 0; i < bytes_needed; i++) { - uint8_t b = buf[i]; - m_bits |= (static_cast(b) << m_bits_left); - m_bits_left += 8; - } - } - - // raw mask with required number of 1s, starting from lowest bit - uint64_t mask = get_mask_ones(n); - // derive reading result - uint64_t res = m_bits & mask; - // remove bottom bits that we've just read by shifting - m_bits >>= n; - m_bits_left -= n; - - return res; -} - -uint64_t kaitai::kstream::get_mask_ones(int n) { - if (n == 64) { - return 0xFFFFFFFFFFFFFFFF; - } else { - return ((uint64_t) 1 << n) - 1; - } -} - -// ======================================================================== -// Byte arrays -// ======================================================================== - -std::string kaitai::kstream::read_bytes(std::streamsize len) { - std::vector result(len); - - // NOTE: streamsize type is signed, negative values are only *supposed* to not be used. - // http://en.cppreference.com/w/cpp/io/streamsize - if (len < 0) { - throw std::runtime_error("read_bytes: requested a negative amount"); - } - - if (len > 0) { - m_io->read(&result[0], len); - } - - return std::string(result.begin(), result.end()); -} - -std::string kaitai::kstream::read_bytes_full() { - std::iostream::pos_type p1 = m_io->tellg(); - m_io->seekg(0, std::ios::end); - std::iostream::pos_type p2 = m_io->tellg(); - size_t len = p2 - p1; - - // Note: this requires a std::string to be backed with a - // contiguous buffer. Officially, it's a only requirement since - // C++11 (C++98 and C++03 didn't have this requirement), but all - // major implementations had contiguous buffers anyway. - std::string result(len, ' '); - m_io->seekg(p1); - m_io->read(&result[0], len); - - return result; -} - -std::string kaitai::kstream::read_bytes_term(char term, bool include, bool consume, bool eos_error) { - std::string result; - std::getline(*m_io, result, term); - if (m_io->eof()) { - // encountered EOF - if (eos_error) { - throw std::runtime_error("read_bytes_term: encountered EOF"); - } - } else { - // encountered terminator - if (include) - result.push_back(term); - if (!consume) - m_io->unget(); - } - return result; -} - -std::string kaitai::kstream::ensure_fixed_contents(std::string expected) { - std::string actual = read_bytes(expected.length()); - - if (actual != expected) { - // NOTE: I think printing it outright is not best idea, it could contain non-ascii charactes like backspace and beeps and whatnot. It would be better to print hexlified version, and also to redirect it to stderr. - throw std::runtime_error("ensure_fixed_contents: actual data does not match expected data"); - } - - return actual; -} - -std::string kaitai::kstream::bytes_strip_right(std::string src, char pad_byte) { - std::size_t new_len = src.length(); - - while (new_len > 0 && src[new_len - 1] == pad_byte) - new_len--; - - return src.substr(0, new_len); -} - -std::string kaitai::kstream::bytes_terminate(std::string src, char term, bool include) { - std::size_t new_len = 0; - std::size_t max_len = src.length(); - - while (new_len < max_len && src[new_len] != term) - new_len++; - - if (include && new_len < max_len) - new_len++; - - return src.substr(0, new_len); -} - -// ======================================================================== -// Byte array processing -// ======================================================================== - -std::string kaitai::kstream::process_xor_one(std::string data, uint8_t key) { - size_t len = data.length(); - std::string result(len, ' '); - - for (size_t i = 0; i < len; i++) - result[i] = data[i] ^ key; - - return result; -} - -std::string kaitai::kstream::process_xor_many(std::string data, std::string key) { - size_t len = data.length(); - size_t kl = key.length(); - std::string result(len, ' '); - - size_t ki = 0; - for (size_t i = 0; i < len; i++) { - result[i] = data[i] ^ key[ki]; - ki++; - if (ki >= kl) - ki = 0; - } - - return result; -} - -std::string kaitai::kstream::process_rotate_left(std::string data, int amount) { - size_t len = data.length(); - std::string result(len, ' '); - - for (size_t i = 0; i < len; i++) { - uint8_t bits = data[i]; - result[i] = (bits << amount) | (bits >> (8 - amount)); - } - - return result; -} - -#ifdef KS_ZLIB -#include - -std::string kaitai::kstream::process_zlib(std::string data) { - int ret; - - unsigned char *src_ptr = reinterpret_cast(&data[0]); - std::stringstream dst_strm; - - z_stream strm; - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - - ret = inflateInit(&strm); - if (ret != Z_OK) - throw std::runtime_error("process_zlib: inflateInit error"); - - strm.next_in = src_ptr; - strm.avail_in = data.length(); - - unsigned char outbuffer[ZLIB_BUF_SIZE]; - std::string outstring; - - // get the decompressed bytes blockwise using repeated calls to inflate - do { - strm.next_out = reinterpret_cast(outbuffer); - strm.avail_out = sizeof(outbuffer); - - ret = inflate(&strm, 0); - - if (outstring.size() < strm.total_out) - outstring.append(reinterpret_cast(outbuffer), strm.total_out - outstring.size()); - } while (ret == Z_OK); - - if (ret != Z_STREAM_END) { // an error occurred that was not EOF - std::ostringstream exc_msg; - exc_msg << "process_zlib: error #" << ret << "): " << strm.msg; - throw std::runtime_error(exc_msg.str()); - } - - if (inflateEnd(&strm) != Z_OK) - throw std::runtime_error("process_zlib: inflateEnd error"); - - return outstring; -} -#endif - -// ======================================================================== -// Misc utility methods -// ======================================================================== - -int kaitai::kstream::mod(int a, int b) { - if (b <= 0) - throw std::invalid_argument("mod: divisor b <= 0"); - int r = a % b; - if (r < 0) - r += b; - return r; -} - -#include -std::string kaitai::kstream::to_string(int val) { - // if int is 32 bits, "-2147483648" is the longest string representation - // => 11 chars + zero => 12 chars - // if int is 64 bits, "-9223372036854775808" is the longest - // => 20 chars + zero => 21 chars - char buf[25]; - int got_len = snprintf(buf, sizeof(buf), "%d", val); - - // should never happen, but check nonetheless - if (got_len > sizeof(buf)) - throw std::invalid_argument("to_string: integer is longer than string buffer"); - - return std::string(buf); -} - -#include -std::string kaitai::kstream::reverse(std::string val) { - std::reverse(val.begin(), val.end()); - - return val; -} - -uint8_t kaitai::kstream::byte_array_min(const std::string val) { - uint8_t min = 0xff; // UINT8_MAX - std::string::const_iterator end = val.end(); - for (std::string::const_iterator it = val.begin(); it != end; ++it) { - uint8_t cur = static_cast(*it); - if (cur < min) { - min = cur; - } - } - return min; -} - -uint8_t kaitai::kstream::byte_array_max(const std::string val) { - uint8_t max = 0; // UINT8_MIN - std::string::const_iterator end = val.end(); - for (std::string::const_iterator it = val.begin(); it != end; ++it) { - uint8_t cur = static_cast(*it); - if (cur > max) { - max = cur; - } - } - return max; -} - -// ======================================================================== -// Other internal methods -// ======================================================================== - -#ifndef KS_STR_DEFAULT_ENCODING -#define KS_STR_DEFAULT_ENCODING "UTF-8" -#endif - -#ifdef KS_STR_ENCODING_ICONV - -#include -#include -#include - -std::string kaitai::kstream::bytes_to_str(std::string src, std::string src_enc) { - iconv_t cd = iconv_open(KS_STR_DEFAULT_ENCODING, src_enc.c_str()); - - if (cd == (iconv_t) -1) { - if (errno == EINVAL) { - throw std::runtime_error("bytes_to_str: invalid encoding pair conversion requested"); - } else { - throw std::runtime_error("bytes_to_str: error opening iconv"); - } - } - - size_t src_len = src.length(); - size_t src_left = src_len; - - // Start with a buffer length of double the source length. - size_t dst_len = src_len * 2; - std::string dst(dst_len, ' '); - size_t dst_left = dst_len; - - char *src_ptr = &src[0]; - char *dst_ptr = &dst[0]; - - while (true) { - size_t res = iconv(cd, &src_ptr, &src_left, &dst_ptr, &dst_left); - - if (res == (size_t) -1) { - if (errno == E2BIG) { - // dst buffer is not enough to accomodate whole string - // enlarge the buffer and try again - size_t dst_used = dst_len - dst_left; - dst_left += dst_len; - dst_len += dst_len; - dst.resize(dst_len); - - // dst.resize might have allocated destination buffer in another area - // of memory, thus our previous pointer "dst" will be invalid; re-point - // it using "dst_used". - dst_ptr = &dst[dst_used]; - } else { - throw std::runtime_error("bytes_to_str: iconv error"); - } - } else { - // conversion successful - dst.resize(dst_len - dst_left); - break; - } - } - - if (iconv_close(cd) != 0) { - throw std::runtime_error("bytes_to_str: iconv close error"); - } - - return dst; -} -#elif defined(KS_STR_ENCODING_NONE) -std::string kaitai::kstream::bytes_to_str(std::string src, std::string src_enc) { - return src; -} -#else -#error Need to decide how to handle strings: please define one of: KS_STR_ENCODING_ICONV, KS_STR_ENCODING_NONE -#endif diff --git a/third_party/kaitai/kaitaistream.h b/third_party/kaitai/kaitaistream.h deleted file mode 100644 index e7f4c6ce347d5b..00000000000000 --- a/third_party/kaitai/kaitaistream.h +++ /dev/null @@ -1,268 +0,0 @@ -#ifndef KAITAI_STREAM_H -#define KAITAI_STREAM_H - -// Kaitai Struct runtime API version: x.y.z = 'xxxyyyzzz' decimal -#define KAITAI_STRUCT_VERSION 9000L - -#include -#include -#include -#include - -namespace kaitai { - -/** - * Kaitai Stream class (kaitai::kstream) is an implementation of - * Kaitai Struct stream API - * for C++/STL. It's implemented as a wrapper over generic STL std::istream. - * - * It provides a wide variety of simple methods to read (parse) binary - * representations of primitive types, such as integer and floating - * point numbers, byte arrays and strings, and also provides stream - * positioning / navigation methods with unified cross-language and - * cross-toolkit semantics. - * - * Typically, end users won't access Kaitai Stream class manually, but would - * describe a binary structure format using .ksy language and then would use - * Kaitai Struct compiler to generate source code in desired target language. - * That code, in turn, would use this class and API to do the actual parsing - * job. - */ -class kstream { -public: - /** - * Constructs new Kaitai Stream object, wrapping a given std::istream. - * \param io istream object to use for this Kaitai Stream - */ - kstream(std::istream* io); - - /** - * Constructs new Kaitai Stream object, wrapping a given in-memory data - * buffer. - * \param data data buffer to use for this Kaitai Stream - */ - kstream(std::string& data); - - void close(); - - /** @name Stream positioning */ - //@{ - /** - * Check if stream pointer is at the end of stream. Note that the semantics - * are different from traditional STL semantics: one does *not* need to do a - * read (which will fail) after the actual end of the stream to trigger EOF - * flag, which can be accessed after that read. It is sufficient to just be - * at the end of the stream for this method to return true. - * \return "true" if we are located at the end of the stream. - */ - bool is_eof() const; - - /** - * Set stream pointer to designated position. - * \param pos new position (offset in bytes from the beginning of the stream) - */ - void seek(uint64_t pos); - - /** - * Get current position of a stream pointer. - * \return pointer position, number of bytes from the beginning of the stream - */ - uint64_t pos(); - - /** - * Get total size of the stream in bytes. - * \return size of the stream in bytes - */ - uint64_t size(); - //@} - - /** @name Integer numbers */ - //@{ - - // ------------------------------------------------------------------------ - // Signed - // ------------------------------------------------------------------------ - - int8_t read_s1(); - - // ........................................................................ - // Big-endian - // ........................................................................ - - int16_t read_s2be(); - int32_t read_s4be(); - int64_t read_s8be(); - - // ........................................................................ - // Little-endian - // ........................................................................ - - int16_t read_s2le(); - int32_t read_s4le(); - int64_t read_s8le(); - - // ------------------------------------------------------------------------ - // Unsigned - // ------------------------------------------------------------------------ - - uint8_t read_u1(); - - // ........................................................................ - // Big-endian - // ........................................................................ - - uint16_t read_u2be(); - uint32_t read_u4be(); - uint64_t read_u8be(); - - // ........................................................................ - // Little-endian - // ........................................................................ - - uint16_t read_u2le(); - uint32_t read_u4le(); - uint64_t read_u8le(); - - //@} - - /** @name Floating point numbers */ - //@{ - - // ........................................................................ - // Big-endian - // ........................................................................ - - float read_f4be(); - double read_f8be(); - - // ........................................................................ - // Little-endian - // ........................................................................ - - float read_f4le(); - double read_f8le(); - - //@} - - /** @name Unaligned bit values */ - //@{ - - void align_to_byte(); - uint64_t read_bits_int_be(int n); - uint64_t read_bits_int(int n); - uint64_t read_bits_int_le(int n); - - //@} - - /** @name Byte arrays */ - //@{ - - std::string read_bytes(std::streamsize len); - std::string read_bytes_full(); - std::string read_bytes_term(char term, bool include, bool consume, bool eos_error); - std::string ensure_fixed_contents(std::string expected); - - static std::string bytes_strip_right(std::string src, char pad_byte); - static std::string bytes_terminate(std::string src, char term, bool include); - static std::string bytes_to_str(std::string src, std::string src_enc); - - //@} - - /** @name Byte array processing */ - //@{ - - /** - * Performs a XOR processing with given data, XORing every byte of input with a single - * given value. - * @param data data to process - * @param key value to XOR with - * @return processed data - */ - static std::string process_xor_one(std::string data, uint8_t key); - - /** - * Performs a XOR processing with given data, XORing every byte of input with a key - * array, repeating key array many times, if necessary (i.e. if data array is longer - * than key array). - * @param data data to process - * @param key array of bytes to XOR with - * @return processed data - */ - static std::string process_xor_many(std::string data, std::string key); - - /** - * Performs a circular left rotation shift for a given buffer by a given amount of bits, - * using groups of 1 bytes each time. Right circular rotation should be performed - * using this procedure with corrected amount. - * @param data source data to process - * @param amount number of bits to shift by - * @return copy of source array with requested shift applied - */ - static std::string process_rotate_left(std::string data, int amount); - -#ifdef KS_ZLIB - /** - * Performs an unpacking ("inflation") of zlib-compressed data with usual zlib headers. - * @param data data to unpack - * @return unpacked data - * @throws IOException - */ - static std::string process_zlib(std::string data); -#endif - - //@} - - /** - * Performs modulo operation between two integers: dividend `a` - * and divisor `b`. Divisor `b` is expected to be positive. The - * result is always 0 <= x <= b - 1. - */ - static int mod(int a, int b); - - /** - * Converts given integer `val` to a decimal string representation. - * Should be used in place of std::to_string() (which is available only - * since C++11) in older C++ implementations. - */ - static std::string to_string(int val); - - /** - * Reverses given string `val`, so that the first character becomes the - * last and the last one becomes the first. This should be used to avoid - * the need of local variables at the caller. - */ - static std::string reverse(std::string val); - - /** - * Finds the minimal byte in a byte array, treating bytes as - * unsigned values. - * @param val byte array to scan - * @return minimal byte in byte array as integer - */ - static uint8_t byte_array_min(const std::string val); - - /** - * Finds the maximal byte in a byte array, treating bytes as - * unsigned values. - * @param val byte array to scan - * @return maximal byte in byte array as integer - */ - static uint8_t byte_array_max(const std::string val); - -private: - std::istream* m_io; - std::istringstream m_io_str; - int m_bits_left; - uint64_t m_bits; - - void init(); - void exceptions_enable() const; - - static uint64_t get_mask_ones(int n); - - static const int ZLIB_BUF_SIZE = 128 * 1024; -}; - -} - -#endif diff --git a/third_party/kaitai/kaitaistruct.h b/third_party/kaitai/kaitaistruct.h deleted file mode 100644 index 8172ede6c98195..00000000000000 --- a/third_party/kaitai/kaitaistruct.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef KAITAI_STRUCT_H -#define KAITAI_STRUCT_H - -#include - -namespace kaitai { - -class kstruct { -public: - kstruct(kstream *_io) { m__io = _io; } - virtual ~kstruct() {} -protected: - kstream *m__io; -public: - kstream *_io() { return m__io; } -}; - -} - -#endif diff --git a/third_party/libyuv/.gitignore b/third_party/libyuv/.gitignore deleted file mode 100644 index 450712e47d2af8..00000000000000 --- a/third_party/libyuv/.gitignore +++ /dev/null @@ -1 +0,0 @@ -libyuv/ diff --git a/third_party/libyuv/Darwin/lib/libyuv.a b/third_party/libyuv/Darwin/lib/libyuv.a deleted file mode 100644 index b72979ef19c58e..00000000000000 --- a/third_party/libyuv/Darwin/lib/libyuv.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:497e01c39e1629a89afa730341fe066c2e926966c5f050003e7fde2ce46d9da3 -size 863648 diff --git a/third_party/libyuv/LICENSE b/third_party/libyuv/LICENSE deleted file mode 100644 index c911747a6b53f0..00000000000000 --- a/third_party/libyuv/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -Copyright 2011 The LibYuv Project Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - - * Neither the name of Google nor the names of its contributors may - be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/libyuv/aarch64 b/third_party/libyuv/aarch64 deleted file mode 120000 index 062c65e8d99c64..00000000000000 --- a/third_party/libyuv/aarch64 +++ /dev/null @@ -1 +0,0 @@ -larch64/ \ No newline at end of file diff --git a/third_party/libyuv/build.sh b/third_party/libyuv/build.sh deleted file mode 100755 index b960f60ef5f5cb..00000000000000 --- a/third_party/libyuv/build.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" - -ARCHNAME=$(uname -m) -if [ -f /TICI ]; then - ARCHNAME="larch64" -fi - -if [[ "$OSTYPE" == "darwin"* ]]; then - ARCHNAME="Darwin" -fi - -cd $DIR -if [ ! -d libyuv ]; then - git clone --single-branch https://chromium.googlesource.com/libyuv/libyuv -fi - -cd libyuv -git checkout 4a14cb2e81235ecd656e799aecaaf139db8ce4a2 - -# build -cmake . -make -j$(nproc) - -INSTALL_DIR="$DIR/$ARCHNAME" -rm -rf $INSTALL_DIR -mkdir -p $INSTALL_DIR - -rm -rf $DIR/include -mkdir -p $INSTALL_DIR/lib -cp $DIR/libyuv/libyuv.a $INSTALL_DIR/lib -cp -r $DIR/libyuv/include $DIR - -## To create universal binary on Darwin: -## ``` -## lipo -create -output Darwin/libyuv.a path-to-x64/libyuv.a path-to-arm64/libyuv.a -## ``` diff --git a/third_party/libyuv/include/libyuv.h b/third_party/libyuv/include/libyuv.h deleted file mode 100644 index aeffd5ef7a4ca2..00000000000000 --- a/third_party/libyuv/include/libyuv.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_H_ -#define INCLUDE_LIBYUV_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/compare.h" -#include "libyuv/convert.h" -#include "libyuv/convert_argb.h" -#include "libyuv/convert_from.h" -#include "libyuv/convert_from_argb.h" -#include "libyuv/cpu_id.h" -#include "libyuv/mjpeg_decoder.h" -#include "libyuv/planar_functions.h" -#include "libyuv/rotate.h" -#include "libyuv/rotate_argb.h" -#include "libyuv/row.h" -#include "libyuv/scale.h" -#include "libyuv/scale_argb.h" -#include "libyuv/scale_row.h" -#include "libyuv/version.h" -#include "libyuv/video_common.h" - -#endif // INCLUDE_LIBYUV_H_ diff --git a/third_party/libyuv/include/libyuv/basic_types.h b/third_party/libyuv/include/libyuv/basic_types.h deleted file mode 100644 index 5b760ee0d4d4a2..00000000000000 --- a/third_party/libyuv/include/libyuv/basic_types.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_BASIC_TYPES_H_ -#define INCLUDE_LIBYUV_BASIC_TYPES_H_ - -#include // for NULL, size_t - -#if defined(_MSC_VER) && (_MSC_VER < 1600) -#include // for uintptr_t on x86 -#else -#include // for uintptr_t -#endif - -#ifndef GG_LONGLONG -#ifndef INT_TYPES_DEFINED -#define INT_TYPES_DEFINED -#ifdef COMPILER_MSVC -typedef unsigned __int64 uint64; -typedef __int64 int64; -#ifndef INT64_C -#define INT64_C(x) x ## I64 -#endif -#ifndef UINT64_C -#define UINT64_C(x) x ## UI64 -#endif -#define INT64_F "I64" -#else // COMPILER_MSVC -#if defined(__LP64__) && !defined(__OpenBSD__) && !defined(__APPLE__) -typedef unsigned long uint64; // NOLINT -typedef long int64; // NOLINT -#ifndef INT64_C -#define INT64_C(x) x ## L -#endif -#ifndef UINT64_C -#define UINT64_C(x) x ## UL -#endif -#define INT64_F "l" -#else // defined(__LP64__) && !defined(__OpenBSD__) && !defined(__APPLE__) -typedef unsigned long long uint64; // NOLINT -typedef long long int64; // NOLINT -#ifndef INT64_C -#define INT64_C(x) x ## LL -#endif -#ifndef UINT64_C -#define UINT64_C(x) x ## ULL -#endif -#define INT64_F "ll" -#endif // __LP64__ -#endif // COMPILER_MSVC -typedef unsigned int uint32; -typedef int int32; -typedef unsigned short uint16; // NOLINT -typedef short int16; // NOLINT -typedef unsigned char uint8; -typedef signed char int8; -#endif // INT_TYPES_DEFINED -#endif // GG_LONGLONG - -// Detect compiler is for x86 or x64. -#if defined(__x86_64__) || defined(_M_X64) || \ - defined(__i386__) || defined(_M_IX86) -#define CPU_X86 1 -#endif -// Detect compiler is for ARM. -#if defined(__arm__) || defined(_M_ARM) -#define CPU_ARM 1 -#endif - -#ifndef ALIGNP -#ifdef __cplusplus -#define ALIGNP(p, t) \ - (reinterpret_cast(((reinterpret_cast(p) + \ - ((t) - 1)) & ~((t) - 1)))) -#else -#define ALIGNP(p, t) \ - ((uint8*)((((uintptr_t)(p) + ((t) - 1)) & ~((t) - 1)))) /* NOLINT */ -#endif -#endif - -#if !defined(LIBYUV_API) -#if defined(_WIN32) || defined(__CYGWIN__) -#if defined(LIBYUV_BUILDING_SHARED_LIBRARY) -#define LIBYUV_API __declspec(dllexport) -#elif defined(LIBYUV_USING_SHARED_LIBRARY) -#define LIBYUV_API __declspec(dllimport) -#else -#define LIBYUV_API -#endif // LIBYUV_BUILDING_SHARED_LIBRARY -#elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__APPLE__) && \ - (defined(LIBYUV_BUILDING_SHARED_LIBRARY) || \ - defined(LIBYUV_USING_SHARED_LIBRARY)) -#define LIBYUV_API __attribute__ ((visibility ("default"))) -#else -#define LIBYUV_API -#endif // __GNUC__ -#endif // LIBYUV_API - -#define LIBYUV_BOOL int -#define LIBYUV_FALSE 0 -#define LIBYUV_TRUE 1 - -// Visual C x86 or GCC little endian. -#if defined(__x86_64__) || defined(_M_X64) || \ - defined(__i386__) || defined(_M_IX86) || \ - defined(__arm__) || defined(_M_ARM) || \ - (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) -#define LIBYUV_LITTLE_ENDIAN -#endif - -#endif // INCLUDE_LIBYUV_BASIC_TYPES_H_ diff --git a/third_party/libyuv/include/libyuv/compare.h b/third_party/libyuv/include/libyuv/compare.h deleted file mode 100644 index 550712de6e589b..00000000000000 --- a/third_party/libyuv/include/libyuv/compare.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_COMPARE_H_ -#define INCLUDE_LIBYUV_COMPARE_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Compute a hash for specified memory. Seed of 5381 recommended. -LIBYUV_API -uint32 HashDjb2(const uint8* src, uint64 count, uint32 seed); - -// Scan an opaque argb image and return fourcc based on alpha offset. -// Returns FOURCC_ARGB, FOURCC_BGRA, or 0 if unknown. -LIBYUV_API -uint32 ARGBDetect(const uint8* argb, int stride_argb, int width, int height); - -// Sum Square Error - used to compute Mean Square Error or PSNR. -LIBYUV_API -uint64 ComputeSumSquareError(const uint8* src_a, - const uint8* src_b, int count); - -LIBYUV_API -uint64 ComputeSumSquareErrorPlane(const uint8* src_a, int stride_a, - const uint8* src_b, int stride_b, - int width, int height); - -static const int kMaxPsnr = 128; - -LIBYUV_API -double SumSquareErrorToPsnr(uint64 sse, uint64 count); - -LIBYUV_API -double CalcFramePsnr(const uint8* src_a, int stride_a, - const uint8* src_b, int stride_b, - int width, int height); - -LIBYUV_API -double I420Psnr(const uint8* src_y_a, int stride_y_a, - const uint8* src_u_a, int stride_u_a, - const uint8* src_v_a, int stride_v_a, - const uint8* src_y_b, int stride_y_b, - const uint8* src_u_b, int stride_u_b, - const uint8* src_v_b, int stride_v_b, - int width, int height); - -LIBYUV_API -double CalcFrameSsim(const uint8* src_a, int stride_a, - const uint8* src_b, int stride_b, - int width, int height); - -LIBYUV_API -double I420Ssim(const uint8* src_y_a, int stride_y_a, - const uint8* src_u_a, int stride_u_a, - const uint8* src_v_a, int stride_v_a, - const uint8* src_y_b, int stride_y_b, - const uint8* src_u_b, int stride_u_b, - const uint8* src_v_b, int stride_v_b, - int width, int height); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_COMPARE_H_ diff --git a/third_party/libyuv/include/libyuv/compare_row.h b/third_party/libyuv/include/libyuv/compare_row.h deleted file mode 100644 index 781cad3e65aba0..00000000000000 --- a/third_party/libyuv/include/libyuv/compare_row.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2013 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_COMPARE_ROW_H_ -#define INCLUDE_LIBYUV_COMPARE_ROW_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif - -// Visual C 2012 required for AVX2. -#if defined(_M_IX86) && !defined(__clang__) && \ - defined(_MSC_VER) && _MSC_VER >= 1700 -#define VISUALC_HAS_AVX2 1 -#endif // VisualStudio >= 2012 - -// clang >= 3.4.0 required for AVX2. -#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) -#if (__clang_major__ > 3) || (__clang_major__ == 3 && (__clang_minor__ >= 4)) -#define CLANG_HAS_AVX2 1 -#endif // clang >= 3.4 -#endif // __clang__ - -#if !defined(LIBYUV_DISABLE_X86) && \ - defined(_M_IX86) && (defined(VISUALC_HAS_AVX2) || defined(CLANG_HAS_AVX2)) -#define HAS_HASHDJB2_AVX2 -#endif - -// The following are available for Visual C and GCC: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(__x86_64__) || (defined(__i386__) || defined(_M_IX86))) -#define HAS_HASHDJB2_SSE41 -#define HAS_SUMSQUAREERROR_SSE2 -#endif - -// The following are available for Visual C and clangcl 32 bit: -#if !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) && \ - (defined(VISUALC_HAS_AVX2) || defined(CLANG_HAS_AVX2)) -#define HAS_HASHDJB2_AVX2 -#define HAS_SUMSQUAREERROR_AVX2 -#endif - -// The following are available for Neon: -#if !defined(LIBYUV_DISABLE_NEON) && \ - (defined(__ARM_NEON__) || defined(LIBYUV_NEON) || defined(__aarch64__)) -#define HAS_SUMSQUAREERROR_NEON -#endif - -uint32 SumSquareError_C(const uint8* src_a, const uint8* src_b, int count); -uint32 SumSquareError_SSE2(const uint8* src_a, const uint8* src_b, int count); -uint32 SumSquareError_AVX2(const uint8* src_a, const uint8* src_b, int count); -uint32 SumSquareError_NEON(const uint8* src_a, const uint8* src_b, int count); - -uint32 HashDjb2_C(const uint8* src, int count, uint32 seed); -uint32 HashDjb2_SSE41(const uint8* src, int count, uint32 seed); -uint32 HashDjb2_AVX2(const uint8* src, int count, uint32 seed); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_COMPARE_ROW_H_ diff --git a/third_party/libyuv/include/libyuv/convert.h b/third_party/libyuv/include/libyuv/convert.h deleted file mode 100644 index d44485847be1d6..00000000000000 --- a/third_party/libyuv/include/libyuv/convert.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CONVERT_H_ -#define INCLUDE_LIBYUV_CONVERT_H_ - -#include "libyuv/basic_types.h" - -#include "libyuv/rotate.h" // For enum RotationMode. - -// TODO(fbarchard): fix WebRTC source to include following libyuv headers: -#include "libyuv/convert_argb.h" // For WebRTC I420ToARGB. b/620 -#include "libyuv/convert_from.h" // For WebRTC ConvertFromI420. b/620 -#include "libyuv/planar_functions.h" // For WebRTC I420Rect, CopyPlane. b/618 - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Convert I444 to I420. -LIBYUV_API -int I444ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert I422 to I420. -LIBYUV_API -int I422ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert I411 to I420. -LIBYUV_API -int I411ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Copy I420 to I420. -#define I420ToI420 I420Copy -LIBYUV_API -int I420Copy(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert I400 (grey) to I420. -LIBYUV_API -int I400ToI420(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -#define J400ToJ420 I400ToI420 - -// Convert NV12 to I420. -LIBYUV_API -int NV12ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_uv, int src_stride_uv, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert NV21 to I420. -LIBYUV_API -int NV21ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_vu, int src_stride_vu, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert YUY2 to I420. -LIBYUV_API -int YUY2ToI420(const uint8* src_yuy2, int src_stride_yuy2, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert UYVY to I420. -LIBYUV_API -int UYVYToI420(const uint8* src_uyvy, int src_stride_uyvy, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert M420 to I420. -LIBYUV_API -int M420ToI420(const uint8* src_m420, int src_stride_m420, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert Android420 to I420. -LIBYUV_API -int Android420ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - int pixel_stride_uv, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// ARGB little endian (bgra in memory) to I420. -LIBYUV_API -int ARGBToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// BGRA little endian (argb in memory) to I420. -LIBYUV_API -int BGRAToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// ABGR little endian (rgba in memory) to I420. -LIBYUV_API -int ABGRToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGBA little endian (abgr in memory) to I420. -LIBYUV_API -int RGBAToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB little endian (bgr in memory) to I420. -LIBYUV_API -int RGB24ToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB big endian (rgb in memory) to I420. -LIBYUV_API -int RAWToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB16 (RGBP fourcc) little endian to I420. -LIBYUV_API -int RGB565ToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB15 (RGBO fourcc) little endian to I420. -LIBYUV_API -int ARGB1555ToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB12 (R444 fourcc) little endian to I420. -LIBYUV_API -int ARGB4444ToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -#ifdef HAVE_JPEG -// src_width/height provided by capture. -// dst_width/height for clipping determine final size. -LIBYUV_API -int MJPGToI420(const uint8* sample, size_t sample_size, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int src_width, int src_height, - int dst_width, int dst_height); - -// Query size of MJPG in pixels. -LIBYUV_API -int MJPGSize(const uint8* sample, size_t sample_size, - int* width, int* height); -#endif - -// Convert camera sample to I420 with cropping, rotation and vertical flip. -// "src_size" is needed to parse MJPG. -// "dst_stride_y" number of bytes in a row of the dst_y plane. -// Normally this would be the same as dst_width, with recommended alignment -// to 16 bytes for better efficiency. -// If rotation of 90 or 270 is used, stride is affected. The caller should -// allocate the I420 buffer according to rotation. -// "dst_stride_u" number of bytes in a row of the dst_u plane. -// Normally this would be the same as (dst_width + 1) / 2, with -// recommended alignment to 16 bytes for better efficiency. -// If rotation of 90 or 270 is used, stride is affected. -// "crop_x" and "crop_y" are starting position for cropping. -// To center, crop_x = (src_width - dst_width) / 2 -// crop_y = (src_height - dst_height) / 2 -// "src_width" / "src_height" is size of src_frame in pixels. -// "src_height" can be negative indicating a vertically flipped image source. -// "crop_width" / "crop_height" is the size to crop the src to. -// Must be less than or equal to src_width/src_height -// Cropping parameters are pre-rotation. -// "rotation" can be 0, 90, 180 or 270. -// "format" is a fourcc. ie 'I420', 'YUY2' -// Returns 0 for successful; -1 for invalid parameter. Non-zero for failure. -LIBYUV_API -int ConvertToI420(const uint8* src_frame, size_t src_size, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int crop_x, int crop_y, - int src_width, int src_height, - int crop_width, int crop_height, - enum RotationMode rotation, - uint32 format); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CONVERT_H_ diff --git a/third_party/libyuv/include/libyuv/convert_argb.h b/third_party/libyuv/include/libyuv/convert_argb.h deleted file mode 100644 index dc03ac8d5dc4e1..00000000000000 --- a/third_party/libyuv/include/libyuv/convert_argb.h +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CONVERT_ARGB_H_ -#define INCLUDE_LIBYUV_CONVERT_ARGB_H_ - -#include "libyuv/basic_types.h" - -#include "libyuv/rotate.h" // For enum RotationMode. - -// TODO(fbarchard): This set of functions should exactly match convert.h -// TODO(fbarchard): Add tests. Create random content of right size and convert -// with C vs Opt and or to I420 and compare. -// TODO(fbarchard): Some of these functions lack parameter setting. - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Alias. -#define ARGBToARGB ARGBCopy - -// Copy ARGB to ARGB. -LIBYUV_API -int ARGBCopy(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I420 to ARGB. -LIBYUV_API -int I420ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Duplicate prototype for function in convert_from.h for remoting. -LIBYUV_API -int I420ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I422 to ARGB. -LIBYUV_API -int I422ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I444 to ARGB. -LIBYUV_API -int I444ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J444 to ARGB. -LIBYUV_API -int J444ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I444 to ABGR. -LIBYUV_API -int I444ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert I411 to ARGB. -LIBYUV_API -int I411ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I420 with Alpha to preattenuated ARGB. -LIBYUV_API -int I420AlphaToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - const uint8* src_a, int src_stride_a, - uint8* dst_argb, int dst_stride_argb, - int width, int height, int attenuate); - -// Convert I420 with Alpha to preattenuated ABGR. -LIBYUV_API -int I420AlphaToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - const uint8* src_a, int src_stride_a, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height, int attenuate); - -// Convert I400 (grey) to ARGB. Reverse of ARGBToI400. -LIBYUV_API -int I400ToARGB(const uint8* src_y, int src_stride_y, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J400 (jpeg grey) to ARGB. -LIBYUV_API -int J400ToARGB(const uint8* src_y, int src_stride_y, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Alias. -#define YToARGB I400ToARGB - -// Convert NV12 to ARGB. -LIBYUV_API -int NV12ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_uv, int src_stride_uv, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert NV21 to ARGB. -LIBYUV_API -int NV21ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_vu, int src_stride_vu, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert M420 to ARGB. -LIBYUV_API -int M420ToARGB(const uint8* src_m420, int src_stride_m420, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert YUY2 to ARGB. -LIBYUV_API -int YUY2ToARGB(const uint8* src_yuy2, int src_stride_yuy2, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert UYVY to ARGB. -LIBYUV_API -int UYVYToARGB(const uint8* src_uyvy, int src_stride_uyvy, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J420 to ARGB. -LIBYUV_API -int J420ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J422 to ARGB. -LIBYUV_API -int J422ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J420 to ABGR. -LIBYUV_API -int J420ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert J422 to ABGR. -LIBYUV_API -int J422ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert H420 to ARGB. -LIBYUV_API -int H420ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert H422 to ARGB. -LIBYUV_API -int H422ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert H420 to ABGR. -LIBYUV_API -int H420ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert H422 to ABGR. -LIBYUV_API -int H422ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// BGRA little endian (argb in memory) to ARGB. -LIBYUV_API -int BGRAToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// ABGR little endian (rgba in memory) to ARGB. -LIBYUV_API -int ABGRToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGBA little endian (abgr in memory) to ARGB. -LIBYUV_API -int RGBAToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Deprecated function name. -#define BG24ToARGB RGB24ToARGB - -// RGB little endian (bgr in memory) to ARGB. -LIBYUV_API -int RGB24ToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGB big endian (rgb in memory) to ARGB. -LIBYUV_API -int RAWToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGB16 (RGBP fourcc) little endian to ARGB. -LIBYUV_API -int RGB565ToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGB15 (RGBO fourcc) little endian to ARGB. -LIBYUV_API -int ARGB1555ToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGB12 (R444 fourcc) little endian to ARGB. -LIBYUV_API -int ARGB4444ToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -#ifdef HAVE_JPEG -// src_width/height provided by capture -// dst_width/height for clipping determine final size. -LIBYUV_API -int MJPGToARGB(const uint8* sample, size_t sample_size, - uint8* dst_argb, int dst_stride_argb, - int src_width, int src_height, - int dst_width, int dst_height); -#endif - -// Convert camera sample to ARGB with cropping, rotation and vertical flip. -// "src_size" is needed to parse MJPG. -// "dst_stride_argb" number of bytes in a row of the dst_argb plane. -// Normally this would be the same as dst_width, with recommended alignment -// to 16 bytes for better efficiency. -// If rotation of 90 or 270 is used, stride is affected. The caller should -// allocate the I420 buffer according to rotation. -// "dst_stride_u" number of bytes in a row of the dst_u plane. -// Normally this would be the same as (dst_width + 1) / 2, with -// recommended alignment to 16 bytes for better efficiency. -// If rotation of 90 or 270 is used, stride is affected. -// "crop_x" and "crop_y" are starting position for cropping. -// To center, crop_x = (src_width - dst_width) / 2 -// crop_y = (src_height - dst_height) / 2 -// "src_width" / "src_height" is size of src_frame in pixels. -// "src_height" can be negative indicating a vertically flipped image source. -// "crop_width" / "crop_height" is the size to crop the src to. -// Must be less than or equal to src_width/src_height -// Cropping parameters are pre-rotation. -// "rotation" can be 0, 90, 180 or 270. -// "format" is a fourcc. ie 'I420', 'YUY2' -// Returns 0 for successful; -1 for invalid parameter. Non-zero for failure. -LIBYUV_API -int ConvertToARGB(const uint8* src_frame, size_t src_size, - uint8* dst_argb, int dst_stride_argb, - int crop_x, int crop_y, - int src_width, int src_height, - int crop_width, int crop_height, - enum RotationMode rotation, - uint32 format); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CONVERT_ARGB_H_ diff --git a/third_party/libyuv/include/libyuv/convert_from.h b/third_party/libyuv/include/libyuv/convert_from.h deleted file mode 100644 index 59c40474f1ef24..00000000000000 --- a/third_party/libyuv/include/libyuv/convert_from.h +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CONVERT_FROM_H_ -#define INCLUDE_LIBYUV_CONVERT_FROM_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/rotate.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// See Also convert.h for conversions from formats to I420. - -// I420Copy in convert to I420ToI420. - -LIBYUV_API -int I420ToI422(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -LIBYUV_API -int I420ToI444(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -LIBYUV_API -int I420ToI411(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Copy to I400. Source can be I420, I422, I444, I400, NV12 or NV21. -LIBYUV_API -int I400Copy(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - int width, int height); - -LIBYUV_API -int I420ToNV12(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -LIBYUV_API -int I420ToNV21(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_vu, int dst_stride_vu, - int width, int height); - -LIBYUV_API -int I420ToYUY2(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToUYVY(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -LIBYUV_API -int I420ToBGRA(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -LIBYUV_API -int I420ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -LIBYUV_API -int I420ToRGBA(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_rgba, int dst_stride_rgba, - int width, int height); - -LIBYUV_API -int I420ToRGB24(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToRAW(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToRGB565(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -// Convert I420 To RGB565 with 4x4 dither matrix (16 bytes). -// Values in dither matrix from 0 to 7 recommended. -// The order of the dither matrix is first byte is upper left. - -LIBYUV_API -int I420ToRGB565Dither(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - const uint8* dither4x4, int width, int height); - -LIBYUV_API -int I420ToARGB1555(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToARGB4444(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -// Convert I420 to specified format. -// "dst_sample_stride" is bytes in a row for the destination. Pass 0 if the -// buffer has contiguous rows. Can be negative. A multiple of 16 is optimal. -LIBYUV_API -int ConvertFromI420(const uint8* y, int y_stride, - const uint8* u, int u_stride, - const uint8* v, int v_stride, - uint8* dst_sample, int dst_sample_stride, - int width, int height, - uint32 format); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CONVERT_FROM_H_ diff --git a/third_party/libyuv/include/libyuv/convert_from_argb.h b/third_party/libyuv/include/libyuv/convert_from_argb.h deleted file mode 100644 index 8d7f02f8c4dde6..00000000000000 --- a/third_party/libyuv/include/libyuv/convert_from_argb.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CONVERT_FROM_ARGB_H_ -#define INCLUDE_LIBYUV_CONVERT_FROM_ARGB_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Copy ARGB to ARGB. -#define ARGBToARGB ARGBCopy -LIBYUV_API -int ARGBCopy(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert ARGB To BGRA. -LIBYUV_API -int ARGBToBGRA(const uint8* src_argb, int src_stride_argb, - uint8* dst_bgra, int dst_stride_bgra, - int width, int height); - -// Convert ARGB To ABGR. -LIBYUV_API -int ARGBToABGR(const uint8* src_argb, int src_stride_argb, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert ARGB To RGBA. -LIBYUV_API -int ARGBToRGBA(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgba, int dst_stride_rgba, - int width, int height); - -// Convert ARGB To RGB24. -LIBYUV_API -int ARGBToRGB24(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgb24, int dst_stride_rgb24, - int width, int height); - -// Convert ARGB To RAW. -LIBYUV_API -int ARGBToRAW(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgb, int dst_stride_rgb, - int width, int height); - -// Convert ARGB To RGB565. -LIBYUV_API -int ARGBToRGB565(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgb565, int dst_stride_rgb565, - int width, int height); - -// Convert ARGB To RGB565 with 4x4 dither matrix (16 bytes). -// Values in dither matrix from 0 to 7 recommended. -// The order of the dither matrix is first byte is upper left. -// TODO(fbarchard): Consider pointer to 2d array for dither4x4. -// const uint8(*dither)[4][4]; -LIBYUV_API -int ARGBToRGB565Dither(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgb565, int dst_stride_rgb565, - const uint8* dither4x4, int width, int height); - -// Convert ARGB To ARGB1555. -LIBYUV_API -int ARGBToARGB1555(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb1555, int dst_stride_argb1555, - int width, int height); - -// Convert ARGB To ARGB4444. -LIBYUV_API -int ARGBToARGB4444(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb4444, int dst_stride_argb4444, - int width, int height); - -// Convert ARGB To I444. -LIBYUV_API -int ARGBToI444(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB To I422. -LIBYUV_API -int ARGBToI422(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB To I420. (also in convert.h) -LIBYUV_API -int ARGBToI420(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB to J420. (JPeg full range I420). -LIBYUV_API -int ARGBToJ420(const uint8* src_argb, int src_stride_argb, - uint8* dst_yj, int dst_stride_yj, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB to J422. -LIBYUV_API -int ARGBToJ422(const uint8* src_argb, int src_stride_argb, - uint8* dst_yj, int dst_stride_yj, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB To I411. -LIBYUV_API -int ARGBToI411(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB to J400. (JPeg full range). -LIBYUV_API -int ARGBToJ400(const uint8* src_argb, int src_stride_argb, - uint8* dst_yj, int dst_stride_yj, - int width, int height); - -// Convert ARGB to I400. -LIBYUV_API -int ARGBToI400(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Convert ARGB to G. (Reverse of J400toARGB, which replicates G back to ARGB) -LIBYUV_API -int ARGBToG(const uint8* src_argb, int src_stride_argb, - uint8* dst_g, int dst_stride_g, - int width, int height); - -// Convert ARGB To NV12. -LIBYUV_API -int ARGBToNV12(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -// Convert ARGB To NV21. -LIBYUV_API -int ARGBToNV21(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_vu, int dst_stride_vu, - int width, int height); - -// Convert ARGB To NV21. -LIBYUV_API -int ARGBToNV21(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_vu, int dst_stride_vu, - int width, int height); - -// Convert ARGB To YUY2. -LIBYUV_API -int ARGBToYUY2(const uint8* src_argb, int src_stride_argb, - uint8* dst_yuy2, int dst_stride_yuy2, - int width, int height); - -// Convert ARGB To UYVY. -LIBYUV_API -int ARGBToUYVY(const uint8* src_argb, int src_stride_argb, - uint8* dst_uyvy, int dst_stride_uyvy, - int width, int height); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CONVERT_FROM_ARGB_H_ diff --git a/third_party/libyuv/include/libyuv/cpu_id.h b/third_party/libyuv/include/libyuv/cpu_id.h deleted file mode 100644 index 7c6c9aeb00515d..00000000000000 --- a/third_party/libyuv/include/libyuv/cpu_id.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CPU_ID_H_ -#define INCLUDE_LIBYUV_CPU_ID_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Internal flag to indicate cpuid requires initialization. -static const int kCpuInitialized = 0x1; - -// These flags are only valid on ARM processors. -static const int kCpuHasARM = 0x2; -static const int kCpuHasNEON = 0x4; -// 0x8 reserved for future ARM flag. - -// These flags are only valid on x86 processors. -static const int kCpuHasX86 = 0x10; -static const int kCpuHasSSE2 = 0x20; -static const int kCpuHasSSSE3 = 0x40; -static const int kCpuHasSSE41 = 0x80; -static const int kCpuHasSSE42 = 0x100; -static const int kCpuHasAVX = 0x200; -static const int kCpuHasAVX2 = 0x400; -static const int kCpuHasERMS = 0x800; -static const int kCpuHasFMA3 = 0x1000; -static const int kCpuHasAVX3 = 0x2000; -// 0x2000, 0x4000, 0x8000 reserved for future X86 flags. - -// These flags are only valid on MIPS processors. -static const int kCpuHasMIPS = 0x10000; -static const int kCpuHasDSPR2 = 0x20000; -static const int kCpuHasMSA = 0x40000; - -// Internal function used to auto-init. -LIBYUV_API -int InitCpuFlags(void); - -// Internal function for parsing /proc/cpuinfo. -LIBYUV_API -int ArmCpuCaps(const char* cpuinfo_name); - -// Detect CPU has SSE2 etc. -// Test_flag parameter should be one of kCpuHas constants above. -// returns non-zero if instruction set is detected -static __inline int TestCpuFlag(int test_flag) { - LIBYUV_API extern int cpu_info_; - return (!cpu_info_ ? InitCpuFlags() : cpu_info_) & test_flag; -} - -// For testing, allow CPU flags to be disabled. -// ie MaskCpuFlags(~kCpuHasSSSE3) to disable SSSE3. -// MaskCpuFlags(-1) to enable all cpu specific optimizations. -// MaskCpuFlags(1) to disable all cpu specific optimizations. -LIBYUV_API -void MaskCpuFlags(int enable_flags); - -// Low level cpuid for X86. Returns zeros on other CPUs. -// eax is the info type that you want. -// ecx is typically the cpu number, and should normally be zero. -LIBYUV_API -void CpuId(uint32 eax, uint32 ecx, uint32* cpu_info); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CPU_ID_H_ diff --git a/third_party/libyuv/include/libyuv/macros_msa.h b/third_party/libyuv/include/libyuv/macros_msa.h deleted file mode 100644 index 92ed21c38532d4..00000000000000 --- a/third_party/libyuv/include/libyuv/macros_msa.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2016 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_MACROS_MSA_H_ -#define INCLUDE_LIBYUV_MACROS_MSA_H_ - -#if !defined(LIBYUV_DISABLE_MSA) && defined(__mips_msa) -#include -#include - -#define LD_B(RTYPE, psrc) *((RTYPE*)(psrc)) /* NOLINT */ -#define LD_UB(...) LD_B(v16u8, __VA_ARGS__) - -#define ST_B(RTYPE, in, pdst) *((RTYPE*)(pdst)) = (in) /* NOLINT */ -#define ST_UB(...) ST_B(v16u8, __VA_ARGS__) - -/* Description : Load two vectors with 16 'byte' sized elements - Arguments : Inputs - psrc, stride - Outputs - out0, out1 - Return Type - as per RTYPE - Details : Load 16 byte elements in 'out0' from (psrc) - Load 16 byte elements in 'out1' from (psrc + stride) -*/ -#define LD_B2(RTYPE, psrc, stride, out0, out1) { \ - out0 = LD_B(RTYPE, (psrc)); \ - out1 = LD_B(RTYPE, (psrc) + stride); \ -} -#define LD_UB2(...) LD_B2(v16u8, __VA_ARGS__) - -#define LD_B4(RTYPE, psrc, stride, out0, out1, out2, out3) { \ - LD_B2(RTYPE, (psrc), stride, out0, out1); \ - LD_B2(RTYPE, (psrc) + 2 * stride , stride, out2, out3); \ -} -#define LD_UB4(...) LD_B4(v16u8, __VA_ARGS__) - -/* Description : Store two vectors with stride each having 16 'byte' sized - elements - Arguments : Inputs - in0, in1, pdst, stride - Details : Store 16 byte elements from 'in0' to (pdst) - Store 16 byte elements from 'in1' to (pdst + stride) -*/ -#define ST_B2(RTYPE, in0, in1, pdst, stride) { \ - ST_B(RTYPE, in0, (pdst)); \ - ST_B(RTYPE, in1, (pdst) + stride); \ -} -#define ST_UB2(...) ST_B2(v16u8, __VA_ARGS__) -# -#define ST_B4(RTYPE, in0, in1, in2, in3, pdst, stride) { \ - ST_B2(RTYPE, in0, in1, (pdst), stride); \ - ST_B2(RTYPE, in2, in3, (pdst) + 2 * stride, stride); \ -} -#define ST_UB4(...) ST_B4(v16u8, __VA_ARGS__) -# -/* Description : Shuffle byte vector elements as per mask vector - Arguments : Inputs - in0, in1, in2, in3, mask0, mask1 - Outputs - out0, out1 - Return Type - as per RTYPE - Details : Byte elements from 'in0' & 'in1' are copied selectively to - 'out0' as per control vector 'mask0' -*/ -#define VSHF_B2(RTYPE, in0, in1, in2, in3, mask0, mask1, out0, out1) { \ - out0 = (RTYPE) __msa_vshf_b((v16i8) mask0, (v16i8) in1, (v16i8) in0); \ - out1 = (RTYPE) __msa_vshf_b((v16i8) mask1, (v16i8) in3, (v16i8) in2); \ -} -#define VSHF_B2_UB(...) VSHF_B2(v16u8, __VA_ARGS__) - -#endif /* !defined(LIBYUV_DISABLE_MSA) && defined(__mips_msa) */ - -#endif // INCLUDE_LIBYUV_MACROS_MSA_H_ diff --git a/third_party/libyuv/include/libyuv/mjpeg_decoder.h b/third_party/libyuv/include/libyuv/mjpeg_decoder.h deleted file mode 100644 index 4975bae5b76ef1..00000000000000 --- a/third_party/libyuv/include/libyuv/mjpeg_decoder.h +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_MJPEG_DECODER_H_ -#define INCLUDE_LIBYUV_MJPEG_DECODER_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -// NOTE: For a simplified public API use convert.h MJPGToI420(). - -struct jpeg_common_struct; -struct jpeg_decompress_struct; -struct jpeg_source_mgr; - -namespace libyuv { - -#ifdef __cplusplus -extern "C" { -#endif - -LIBYUV_BOOL ValidateJpeg(const uint8* sample, size_t sample_size); - -#ifdef __cplusplus -} // extern "C" -#endif - -static const uint32 kUnknownDataSize = 0xFFFFFFFF; - -enum JpegSubsamplingType { - kJpegYuv420, - kJpegYuv422, - kJpegYuv411, - kJpegYuv444, - kJpegYuv400, - kJpegUnknown -}; - -struct Buffer { - const uint8* data; - int len; -}; - -struct BufferVector { - Buffer* buffers; - int len; - int pos; -}; - -struct SetJmpErrorMgr; - -// MJPEG ("Motion JPEG") is a pseudo-standard video codec where the frames are -// simply independent JPEG images with a fixed huffman table (which is omitted). -// It is rarely used in video transmission, but is common as a camera capture -// format, especially in Logitech devices. This class implements a decoder for -// MJPEG frames. -// -// See http://tools.ietf.org/html/rfc2435 -class LIBYUV_API MJpegDecoder { - public: - typedef void (*CallbackFunction)(void* opaque, - const uint8* const* data, - const int* strides, - int rows); - - static const int kColorSpaceUnknown; - static const int kColorSpaceGrayscale; - static const int kColorSpaceRgb; - static const int kColorSpaceYCbCr; - static const int kColorSpaceCMYK; - static const int kColorSpaceYCCK; - - MJpegDecoder(); - ~MJpegDecoder(); - - // Loads a new frame, reads its headers, and determines the uncompressed - // image format. - // Returns LIBYUV_TRUE if image looks valid and format is supported. - // If return value is LIBYUV_TRUE, then the values for all the following - // getters are populated. - // src_len is the size of the compressed mjpeg frame in bytes. - LIBYUV_BOOL LoadFrame(const uint8* src, size_t src_len); - - // Returns width of the last loaded frame in pixels. - int GetWidth(); - - // Returns height of the last loaded frame in pixels. - int GetHeight(); - - // Returns format of the last loaded frame. The return value is one of the - // kColorSpace* constants. - int GetColorSpace(); - - // Number of color components in the color space. - int GetNumComponents(); - - // Sample factors of the n-th component. - int GetHorizSampFactor(int component); - - int GetVertSampFactor(int component); - - int GetHorizSubSampFactor(int component); - - int GetVertSubSampFactor(int component); - - // Public for testability. - int GetImageScanlinesPerImcuRow(); - - // Public for testability. - int GetComponentScanlinesPerImcuRow(int component); - - // Width of a component in bytes. - int GetComponentWidth(int component); - - // Height of a component. - int GetComponentHeight(int component); - - // Width of a component in bytes with padding for DCTSIZE. Public for testing. - int GetComponentStride(int component); - - // Size of a component in bytes. - int GetComponentSize(int component); - - // Call this after LoadFrame() if you decide you don't want to decode it - // after all. - LIBYUV_BOOL UnloadFrame(); - - // Decodes the entire image into a one-buffer-per-color-component format. - // dst_width must match exactly. dst_height must be <= to image height; if - // less, the image is cropped. "planes" must have size equal to at least - // GetNumComponents() and they must point to non-overlapping buffers of size - // at least GetComponentSize(i). The pointers in planes are incremented - // to point to after the end of the written data. - // TODO(fbarchard): Add dst_x, dst_y to allow specific rect to be decoded. - LIBYUV_BOOL DecodeToBuffers(uint8** planes, int dst_width, int dst_height); - - // Decodes the entire image and passes the data via repeated calls to a - // callback function. Each call will get the data for a whole number of - // image scanlines. - // TODO(fbarchard): Add dst_x, dst_y to allow specific rect to be decoded. - LIBYUV_BOOL DecodeToCallback(CallbackFunction fn, void* opaque, - int dst_width, int dst_height); - - // The helper function which recognizes the jpeg sub-sampling type. - static JpegSubsamplingType JpegSubsamplingTypeHelper( - int* subsample_x, int* subsample_y, int number_of_components); - - private: - void AllocOutputBuffers(int num_outbufs); - void DestroyOutputBuffers(); - - LIBYUV_BOOL StartDecode(); - LIBYUV_BOOL FinishDecode(); - - void SetScanlinePointers(uint8** data); - LIBYUV_BOOL DecodeImcuRow(); - - int GetComponentScanlinePadding(int component); - - // A buffer holding the input data for a frame. - Buffer buf_; - BufferVector buf_vec_; - - jpeg_decompress_struct* decompress_struct_; - jpeg_source_mgr* source_mgr_; - SetJmpErrorMgr* error_mgr_; - - // LIBYUV_TRUE iff at least one component has scanline padding. (i.e., - // GetComponentScanlinePadding() != 0.) - LIBYUV_BOOL has_scanline_padding_; - - // Temporaries used to point to scanline outputs. - int num_outbufs_; // Outermost size of all arrays below. - uint8*** scanlines_; - int* scanlines_sizes_; - // Temporary buffer used for decoding when we can't decode directly to the - // output buffers. Large enough for just one iMCU row. - uint8** databuf_; - int* databuf_strides_; -}; - -} // namespace libyuv - -#endif // __cplusplus -#endif // INCLUDE_LIBYUV_MJPEG_DECODER_H_ diff --git a/third_party/libyuv/include/libyuv/planar_functions.h b/third_party/libyuv/include/libyuv/planar_functions.h deleted file mode 100644 index 1b57b29261eeb3..00000000000000 --- a/third_party/libyuv/include/libyuv/planar_functions.h +++ /dev/null @@ -1,529 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_ -#define INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_ - -#include "libyuv/basic_types.h" - -// TODO(fbarchard): Remove the following headers includes. -#include "libyuv/convert.h" -#include "libyuv/convert_argb.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Copy a plane of data. -LIBYUV_API -void CopyPlane(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - int width, int height); - -LIBYUV_API -void CopyPlane_16(const uint16* src_y, int src_stride_y, - uint16* dst_y, int dst_stride_y, - int width, int height); - -// Set a plane of data to a 32 bit value. -LIBYUV_API -void SetPlane(uint8* dst_y, int dst_stride_y, - int width, int height, - uint32 value); - -// Split interleaved UV plane into separate U and V planes. -LIBYUV_API -void SplitUVPlane(const uint8* src_uv, int src_stride_uv, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Merge separate U and V planes into one interleaved UV plane. -LIBYUV_API -void MergeUVPlane(const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -// Copy I400. Supports inverting. -LIBYUV_API -int I400ToI400(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - int width, int height); - -#define J400ToJ400 I400ToI400 - -// Copy I422 to I422. -#define I422ToI422 I422Copy -LIBYUV_API -int I422Copy(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Copy I444 to I444. -#define I444ToI444 I444Copy -LIBYUV_API -int I444Copy(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert YUY2 to I422. -LIBYUV_API -int YUY2ToI422(const uint8* src_yuy2, int src_stride_yuy2, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert UYVY to I422. -LIBYUV_API -int UYVYToI422(const uint8* src_uyvy, int src_stride_uyvy, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -LIBYUV_API -int YUY2ToNV12(const uint8* src_yuy2, int src_stride_yuy2, - uint8* dst_y, int dst_stride_y, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -LIBYUV_API -int UYVYToNV12(const uint8* src_uyvy, int src_stride_uyvy, - uint8* dst_y, int dst_stride_y, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -// Convert I420 to I400. (calls CopyPlane ignoring u/v). -LIBYUV_API -int I420ToI400(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Alias -#define J420ToJ400 I420ToI400 -#define I420ToI420Mirror I420Mirror - -// I420 mirror. -LIBYUV_API -int I420Mirror(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Alias -#define I400ToI400Mirror I400Mirror - -// I400 mirror. A single plane is mirrored horizontally. -// Pass negative height to achieve 180 degree rotation. -LIBYUV_API -int I400Mirror(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Alias -#define ARGBToARGBMirror ARGBMirror - -// ARGB mirror. -LIBYUV_API -int ARGBMirror(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert NV12 to RGB565. -LIBYUV_API -int NV12ToRGB565(const uint8* src_y, int src_stride_y, - const uint8* src_uv, int src_stride_uv, - uint8* dst_rgb565, int dst_stride_rgb565, - int width, int height); - -// I422ToARGB is in convert_argb.h -// Convert I422 to BGRA. -LIBYUV_API -int I422ToBGRA(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_bgra, int dst_stride_bgra, - int width, int height); - -// Convert I422 to ABGR. -LIBYUV_API -int I422ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert I422 to RGBA. -LIBYUV_API -int I422ToRGBA(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_rgba, int dst_stride_rgba, - int width, int height); - -// Alias -#define RGB24ToRAW RAWToRGB24 - -LIBYUV_API -int RAWToRGB24(const uint8* src_raw, int src_stride_raw, - uint8* dst_rgb24, int dst_stride_rgb24, - int width, int height); - -// Draw a rectangle into I420. -LIBYUV_API -int I420Rect(uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int x, int y, int width, int height, - int value_y, int value_u, int value_v); - -// Draw a rectangle into ARGB. -LIBYUV_API -int ARGBRect(uint8* dst_argb, int dst_stride_argb, - int x, int y, int width, int height, uint32 value); - -// Convert ARGB to gray scale ARGB. -LIBYUV_API -int ARGBGrayTo(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Make a rectangle of ARGB gray scale. -LIBYUV_API -int ARGBGray(uint8* dst_argb, int dst_stride_argb, - int x, int y, int width, int height); - -// Make a rectangle of ARGB Sepia tone. -LIBYUV_API -int ARGBSepia(uint8* dst_argb, int dst_stride_argb, - int x, int y, int width, int height); - -// Apply a matrix rotation to each ARGB pixel. -// matrix_argb is 4 signed ARGB values. -128 to 127 representing -2 to 2. -// The first 4 coefficients apply to B, G, R, A and produce B of the output. -// The next 4 coefficients apply to B, G, R, A and produce G of the output. -// The next 4 coefficients apply to B, G, R, A and produce R of the output. -// The last 4 coefficients apply to B, G, R, A and produce A of the output. -LIBYUV_API -int ARGBColorMatrix(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - const int8* matrix_argb, - int width, int height); - -// Deprecated. Use ARGBColorMatrix instead. -// Apply a matrix rotation to each ARGB pixel. -// matrix_argb is 3 signed ARGB values. -128 to 127 representing -1 to 1. -// The first 4 coefficients apply to B, G, R, A and produce B of the output. -// The next 4 coefficients apply to B, G, R, A and produce G of the output. -// The last 4 coefficients apply to B, G, R, A and produce R of the output. -LIBYUV_API -int RGBColorMatrix(uint8* dst_argb, int dst_stride_argb, - const int8* matrix_rgb, - int x, int y, int width, int height); - -// Apply a color table each ARGB pixel. -// Table contains 256 ARGB values. -LIBYUV_API -int ARGBColorTable(uint8* dst_argb, int dst_stride_argb, - const uint8* table_argb, - int x, int y, int width, int height); - -// Apply a color table each ARGB pixel but preserve destination alpha. -// Table contains 256 ARGB values. -LIBYUV_API -int RGBColorTable(uint8* dst_argb, int dst_stride_argb, - const uint8* table_argb, - int x, int y, int width, int height); - -// Apply a luma/color table each ARGB pixel but preserve destination alpha. -// Table contains 32768 values indexed by [Y][C] where 7 it 7 bit luma from -// RGB (YJ style) and C is an 8 bit color component (R, G or B). -LIBYUV_API -int ARGBLumaColorTable(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - const uint8* luma_rgb_table, - int width, int height); - -// Apply a 3 term polynomial to ARGB values. -// poly points to a 4x4 matrix. The first row is constants. The 2nd row is -// coefficients for b, g, r and a. The 3rd row is coefficients for b squared, -// g squared, r squared and a squared. The 4rd row is coefficients for b to -// the 3, g to the 3, r to the 3 and a to the 3. The values are summed and -// result clamped to 0 to 255. -// A polynomial approximation can be dirived using software such as 'R'. - -LIBYUV_API -int ARGBPolynomial(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - const float* poly, - int width, int height); - -// Convert plane of 16 bit shorts to half floats. -// Source values are multiplied by scale before storing as half float. -LIBYUV_API -int HalfFloatPlane(const uint16* src_y, int src_stride_y, - uint16* dst_y, int dst_stride_y, - float scale, - int width, int height); - -// Quantize a rectangle of ARGB. Alpha unaffected. -// scale is a 16 bit fractional fixed point scaler between 0 and 65535. -// interval_size should be a value between 1 and 255. -// interval_offset should be a value between 0 and 255. -LIBYUV_API -int ARGBQuantize(uint8* dst_argb, int dst_stride_argb, - int scale, int interval_size, int interval_offset, - int x, int y, int width, int height); - -// Copy ARGB to ARGB. -LIBYUV_API -int ARGBCopy(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Copy Alpha channel of ARGB to alpha of ARGB. -LIBYUV_API -int ARGBCopyAlpha(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Extract the alpha channel from ARGB. -LIBYUV_API -int ARGBExtractAlpha(const uint8* src_argb, int src_stride_argb, - uint8* dst_a, int dst_stride_a, - int width, int height); - -// Copy Y channel to Alpha of ARGB. -LIBYUV_API -int ARGBCopyYToAlpha(const uint8* src_y, int src_stride_y, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -typedef void (*ARGBBlendRow)(const uint8* src_argb0, const uint8* src_argb1, - uint8* dst_argb, int width); - -// Get function to Alpha Blend ARGB pixels and store to destination. -LIBYUV_API -ARGBBlendRow GetARGBBlend(); - -// Alpha Blend ARGB images and store to destination. -// Source is pre-multiplied by alpha using ARGBAttenuate. -// Alpha of destination is set to 255. -LIBYUV_API -int ARGBBlend(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Alpha Blend plane and store to destination. -// Source is not pre-multiplied by alpha. -LIBYUV_API -int BlendPlane(const uint8* src_y0, int src_stride_y0, - const uint8* src_y1, int src_stride_y1, - const uint8* alpha, int alpha_stride, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Alpha Blend YUV images and store to destination. -// Source is not pre-multiplied by alpha. -// Alpha is full width x height and subsampled to half size to apply to UV. -LIBYUV_API -int I420Blend(const uint8* src_y0, int src_stride_y0, - const uint8* src_u0, int src_stride_u0, - const uint8* src_v0, int src_stride_v0, - const uint8* src_y1, int src_stride_y1, - const uint8* src_u1, int src_stride_u1, - const uint8* src_v1, int src_stride_v1, - const uint8* alpha, int alpha_stride, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Multiply ARGB image by ARGB image. Shifted down by 8. Saturates to 255. -LIBYUV_API -int ARGBMultiply(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Add ARGB image with ARGB image. Saturates to 255. -LIBYUV_API -int ARGBAdd(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Subtract ARGB image (argb1) from ARGB image (argb0). Saturates to 0. -LIBYUV_API -int ARGBSubtract(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I422 to YUY2. -LIBYUV_API -int I422ToYUY2(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -// Convert I422 to UYVY. -LIBYUV_API -int I422ToUYVY(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -// Convert unattentuated ARGB to preattenuated ARGB. -LIBYUV_API -int ARGBAttenuate(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert preattentuated ARGB to unattenuated ARGB. -LIBYUV_API -int ARGBUnattenuate(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Internal function - do not call directly. -// Computes table of cumulative sum for image where the value is the sum -// of all values above and to the left of the entry. Used by ARGBBlur. -LIBYUV_API -int ARGBComputeCumulativeSum(const uint8* src_argb, int src_stride_argb, - int32* dst_cumsum, int dst_stride32_cumsum, - int width, int height); - -// Blur ARGB image. -// dst_cumsum table of width * (height + 1) * 16 bytes aligned to -// 16 byte boundary. -// dst_stride32_cumsum is number of ints in a row (width * 4). -// radius is number of pixels around the center. e.g. 1 = 3x3. 2=5x5. -// Blur is optimized for radius of 5 (11x11) or less. -LIBYUV_API -int ARGBBlur(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int32* dst_cumsum, int dst_stride32_cumsum, - int width, int height, int radius); - -// Multiply ARGB image by ARGB value. -LIBYUV_API -int ARGBShade(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height, uint32 value); - -// Interpolate between two images using specified amount of interpolation -// (0 to 255) and store to destination. -// 'interpolation' is specified as 8 bit fraction where 0 means 100% src0 -// and 255 means 1% src0 and 99% src1. -LIBYUV_API -int InterpolatePlane(const uint8* src0, int src_stride0, - const uint8* src1, int src_stride1, - uint8* dst, int dst_stride, - int width, int height, int interpolation); - -// Interpolate between two ARGB images using specified amount of interpolation -// Internally calls InterpolatePlane with width * 4 (bpp). -LIBYUV_API -int ARGBInterpolate(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height, int interpolation); - -// Interpolate between two YUV images using specified amount of interpolation -// Internally calls InterpolatePlane on each plane where the U and V planes -// are half width and half height. -LIBYUV_API -int I420Interpolate(const uint8* src0_y, int src0_stride_y, - const uint8* src0_u, int src0_stride_u, - const uint8* src0_v, int src0_stride_v, - const uint8* src1_y, int src1_stride_y, - const uint8* src1_u, int src1_stride_u, - const uint8* src1_v, int src1_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height, int interpolation); - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif -// The following are available on all x86 platforms: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)) -#define HAS_ARGBAFFINEROW_SSE2 -#endif - -// Row function for copying pixels from a source with a slope to a row -// of destination. Useful for scaling, rotation, mirror, texture mapping. -LIBYUV_API -void ARGBAffineRow_C(const uint8* src_argb, int src_argb_stride, - uint8* dst_argb, const float* uv_dudv, int width); -LIBYUV_API -void ARGBAffineRow_SSE2(const uint8* src_argb, int src_argb_stride, - uint8* dst_argb, const float* uv_dudv, int width); - -// Shuffle ARGB channel order. e.g. BGRA to ARGB. -// shuffler is 16 bytes and must be aligned. -LIBYUV_API -int ARGBShuffle(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_argb, int dst_stride_argb, - const uint8* shuffler, int width, int height); - -// Sobel ARGB effect with planar output. -LIBYUV_API -int ARGBSobelToPlane(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Sobel ARGB effect. -LIBYUV_API -int ARGBSobel(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Sobel ARGB effect w/ Sobel X, Sobel, Sobel Y in ARGB. -LIBYUV_API -int ARGBSobelXY(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_ diff --git a/third_party/libyuv/include/libyuv/rotate.h b/third_party/libyuv/include/libyuv/rotate.h deleted file mode 100644 index 8a2da9a5aad5c5..00000000000000 --- a/third_party/libyuv/include/libyuv/rotate.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_ROTATE_H_ -#define INCLUDE_LIBYUV_ROTATE_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Supported rotation. -typedef enum RotationMode { - kRotate0 = 0, // No rotation. - kRotate90 = 90, // Rotate 90 degrees clockwise. - kRotate180 = 180, // Rotate 180 degrees. - kRotate270 = 270, // Rotate 270 degrees clockwise. - - // Deprecated. - kRotateNone = 0, - kRotateClockwise = 90, - kRotateCounterClockwise = 270, -} RotationModeEnum; - -// Rotate I420 frame. -LIBYUV_API -int I420Rotate(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int src_width, int src_height, enum RotationMode mode); - -// Rotate NV12 input and store in I420. -LIBYUV_API -int NV12ToI420Rotate(const uint8* src_y, int src_stride_y, - const uint8* src_uv, int src_stride_uv, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int src_width, int src_height, enum RotationMode mode); - -// Rotate a plane by 0, 90, 180, or 270. -LIBYUV_API -int RotatePlane(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int src_width, int src_height, enum RotationMode mode); - -// Rotate planes by 90, 180, 270. Deprecated. -LIBYUV_API -void RotatePlane90(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); - -LIBYUV_API -void RotatePlane180(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); - -LIBYUV_API -void RotatePlane270(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); - -LIBYUV_API -void RotateUV90(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -// Rotations for when U and V are interleaved. -// These functions take one input pointer and -// split the data into two buffers while -// rotating them. Deprecated. -LIBYUV_API -void RotateUV180(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -LIBYUV_API -void RotateUV270(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -// The 90 and 270 functions are based on transposes. -// Doing a transpose with reversing the read/write -// order will result in a rotation by +- 90 degrees. -// Deprecated. -LIBYUV_API -void TransposePlane(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); - -LIBYUV_API -void TransposeUV(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_ROTATE_H_ diff --git a/third_party/libyuv/include/libyuv/rotate_argb.h b/third_party/libyuv/include/libyuv/rotate_argb.h deleted file mode 100644 index 21fe7e1807c334..00000000000000 --- a/third_party/libyuv/include/libyuv/rotate_argb.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_ROTATE_ARGB_H_ -#define INCLUDE_LIBYUV_ROTATE_ARGB_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/rotate.h" // For RotationMode. - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Rotate ARGB frame -LIBYUV_API -int ARGBRotate(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int src_width, int src_height, enum RotationMode mode); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_ROTATE_ARGB_H_ diff --git a/third_party/libyuv/include/libyuv/rotate_row.h b/third_party/libyuv/include/libyuv/rotate_row.h deleted file mode 100644 index 6abd201677460b..00000000000000 --- a/third_party/libyuv/include/libyuv/rotate_row.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2013 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_ROTATE_ROW_H_ -#define INCLUDE_LIBYUV_ROTATE_ROW_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif -// The following are available for Visual C and clangcl 32 bit: -#if !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) -#define HAS_TRANSPOSEWX8_SSSE3 -#define HAS_TRANSPOSEUVWX8_SSE2 -#endif - -// The following are available for GCC 32 or 64 bit but not NaCL for 64 bit: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(__i386__) || (defined(__x86_64__) && !defined(__native_client__))) -#define HAS_TRANSPOSEWX8_SSSE3 -#endif - -// The following are available for 64 bit GCC but not NaCL: -#if !defined(LIBYUV_DISABLE_X86) && !defined(__native_client__) && \ - defined(__x86_64__) -#define HAS_TRANSPOSEWX8_FAST_SSSE3 -#define HAS_TRANSPOSEUVWX8_SSE2 -#endif - -#if !defined(LIBYUV_DISABLE_NEON) && !defined(__native_client__) && \ - (defined(__ARM_NEON__) || defined(LIBYUV_NEON) || defined(__aarch64__)) -#define HAS_TRANSPOSEWX8_NEON -#define HAS_TRANSPOSEUVWX8_NEON -#endif - -#if !defined(LIBYUV_DISABLE_MIPS) && !defined(__native_client__) && \ - defined(__mips__) && \ - defined(__mips_dsp) && (__mips_dsp_rev >= 2) -#define HAS_TRANSPOSEWX8_DSPR2 -#define HAS_TRANSPOSEUVWX8_DSPR2 -#endif // defined(__mips__) - -void TransposeWxH_C(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width, int height); - -void TransposeWx8_C(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_NEON(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_SSSE3(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Fast_SSSE3(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_DSPR2(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Fast_DSPR2(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); - -void TransposeWx8_Any_NEON(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Any_SSSE3(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Fast_Any_SSSE3(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Any_DSPR2(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); - -void TransposeUVWxH_C(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -void TransposeUVWx8_C(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_SSE2(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_NEON(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_DSPR2(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); - -void TransposeUVWx8_Any_SSE2(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_Any_NEON(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_Any_DSPR2(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_ROTATE_ROW_H_ diff --git a/third_party/libyuv/include/libyuv/row.h b/third_party/libyuv/include/libyuv/row.h deleted file mode 100644 index b810221ec7a787..00000000000000 --- a/third_party/libyuv/include/libyuv/row.h +++ /dev/null @@ -1,1963 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_ROW_H_ -#define INCLUDE_LIBYUV_ROW_H_ - -#include // For malloc. - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -#define IS_ALIGNED(p, a) (!((uintptr_t)(p) & ((a) - 1))) - -#define align_buffer_64(var, size) \ - uint8* var##_mem = (uint8*)(malloc((size) + 63)); /* NOLINT */ \ - uint8* var = (uint8*)(((intptr_t)(var##_mem) + 63) & ~63) /* NOLINT */ - -#define free_aligned_buffer_64(var) \ - free(var##_mem); \ - var = 0 - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif -// True if compiling for SSSE3 as a requirement. -#if defined(__SSSE3__) || (defined(_M_IX86_FP) && (_M_IX86_FP >= 3)) -#define LIBYUV_SSSE3_ONLY -#endif - -#if defined(__native_client__) -#define LIBYUV_DISABLE_NEON -#endif -// clang >= 3.5.0 required for Arm64. -#if defined(__clang__) && defined(__aarch64__) && !defined(LIBYUV_DISABLE_NEON) -#if (__clang_major__ < 3) || (__clang_major__ == 3 && (__clang_minor__ < 5)) -#define LIBYUV_DISABLE_NEON -#endif // clang >= 3.5 -#endif // __clang__ - -// GCC >= 4.7.0 required for AVX2. -#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) -#if (__GNUC__ > 4) || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 7)) -#define GCC_HAS_AVX2 1 -#endif // GNUC >= 4.7 -#endif // __GNUC__ - -// clang >= 3.4.0 required for AVX2. -#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) -#if (__clang_major__ > 3) || (__clang_major__ == 3 && (__clang_minor__ >= 4)) -#define CLANG_HAS_AVX2 1 -#endif // clang >= 3.4 -#endif // __clang__ - -// Visual C 2012 required for AVX2. -#if defined(_M_IX86) && !defined(__clang__) && \ - defined(_MSC_VER) && _MSC_VER >= 1700 -#define VISUALC_HAS_AVX2 1 -#endif // VisualStudio >= 2012 - -// The following are available on all x86 platforms: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)) -// Conversions: -#define HAS_ABGRTOUVROW_SSSE3 -#define HAS_ABGRTOYROW_SSSE3 -#define HAS_ARGB1555TOARGBROW_SSE2 -#define HAS_ARGB4444TOARGBROW_SSE2 -#define HAS_ARGBSETROW_X86 -#define HAS_ARGBSHUFFLEROW_SSE2 -#define HAS_ARGBSHUFFLEROW_SSSE3 -#define HAS_ARGBTOARGB1555ROW_SSE2 -#define HAS_ARGBTOARGB4444ROW_SSE2 -#define HAS_ARGBTORAWROW_SSSE3 -#define HAS_ARGBTORGB24ROW_SSSE3 -#define HAS_ARGBTORGB565DITHERROW_SSE2 -#define HAS_ARGBTORGB565ROW_SSE2 -#define HAS_ARGBTOUV444ROW_SSSE3 -#define HAS_ARGBTOUVJROW_SSSE3 -#define HAS_ARGBTOUVROW_SSSE3 -#define HAS_ARGBTOYJROW_SSSE3 -#define HAS_ARGBTOYROW_SSSE3 -#define HAS_ARGBEXTRACTALPHAROW_SSE2 -#define HAS_BGRATOUVROW_SSSE3 -#define HAS_BGRATOYROW_SSSE3 -#define HAS_COPYROW_ERMS -#define HAS_COPYROW_SSE2 -#define HAS_H422TOARGBROW_SSSE3 -#define HAS_I400TOARGBROW_SSE2 -#define HAS_I422TOARGB1555ROW_SSSE3 -#define HAS_I422TOARGB4444ROW_SSSE3 -#define HAS_I422TOARGBROW_SSSE3 -#define HAS_I422TORGB24ROW_SSSE3 -#define HAS_I422TORGB565ROW_SSSE3 -#define HAS_I422TORGBAROW_SSSE3 -#define HAS_I422TOUYVYROW_SSE2 -#define HAS_I422TOYUY2ROW_SSE2 -#define HAS_I444TOARGBROW_SSSE3 -#define HAS_J400TOARGBROW_SSE2 -#define HAS_J422TOARGBROW_SSSE3 -#define HAS_MERGEUVROW_SSE2 -#define HAS_MIRRORROW_SSSE3 -#define HAS_MIRRORUVROW_SSSE3 -#define HAS_NV12TOARGBROW_SSSE3 -#define HAS_NV12TORGB565ROW_SSSE3 -#define HAS_NV21TOARGBROW_SSSE3 -#define HAS_RAWTOARGBROW_SSSE3 -#define HAS_RAWTORGB24ROW_SSSE3 -#define HAS_RAWTOYROW_SSSE3 -#define HAS_RGB24TOARGBROW_SSSE3 -#define HAS_RGB24TOYROW_SSSE3 -#define HAS_RGB565TOARGBROW_SSE2 -#define HAS_RGBATOUVROW_SSSE3 -#define HAS_RGBATOYROW_SSSE3 -#define HAS_SETROW_ERMS -#define HAS_SETROW_X86 -#define HAS_SPLITUVROW_SSE2 -#define HAS_UYVYTOARGBROW_SSSE3 -#define HAS_UYVYTOUV422ROW_SSE2 -#define HAS_UYVYTOUVROW_SSE2 -#define HAS_UYVYTOYROW_SSE2 -#define HAS_YUY2TOARGBROW_SSSE3 -#define HAS_YUY2TOUV422ROW_SSE2 -#define HAS_YUY2TOUVROW_SSE2 -#define HAS_YUY2TOYROW_SSE2 - -// Effects: -#define HAS_ARGBADDROW_SSE2 -#define HAS_ARGBAFFINEROW_SSE2 -#define HAS_ARGBATTENUATEROW_SSSE3 -#define HAS_ARGBBLENDROW_SSSE3 -#define HAS_ARGBCOLORMATRIXROW_SSSE3 -#define HAS_ARGBCOLORTABLEROW_X86 -#define HAS_ARGBCOPYALPHAROW_SSE2 -#define HAS_ARGBCOPYYTOALPHAROW_SSE2 -#define HAS_ARGBGRAYROW_SSSE3 -#define HAS_ARGBLUMACOLORTABLEROW_SSSE3 -#define HAS_ARGBMIRRORROW_SSE2 -#define HAS_ARGBMULTIPLYROW_SSE2 -#define HAS_ARGBPOLYNOMIALROW_SSE2 -#define HAS_ARGBQUANTIZEROW_SSE2 -#define HAS_ARGBSEPIAROW_SSSE3 -#define HAS_ARGBSHADEROW_SSE2 -#define HAS_ARGBSUBTRACTROW_SSE2 -#define HAS_ARGBUNATTENUATEROW_SSE2 -#define HAS_BLENDPLANEROW_SSSE3 -#define HAS_COMPUTECUMULATIVESUMROW_SSE2 -#define HAS_CUMULATIVESUMTOAVERAGEROW_SSE2 -#define HAS_INTERPOLATEROW_SSSE3 -#define HAS_RGBCOLORTABLEROW_X86 -#define HAS_SOBELROW_SSE2 -#define HAS_SOBELTOPLANEROW_SSE2 -#define HAS_SOBELXROW_SSE2 -#define HAS_SOBELXYROW_SSE2 -#define HAS_SOBELYROW_SSE2 - -// The following functions fail on gcc/clang 32 bit with fpic and framepointer. -// caveat: clangcl uses row_win.cc which works. -#if defined(NDEBUG) || !(defined(_DEBUG) && defined(__i386__)) || \ - !defined(__i386__) || defined(_MSC_VER) -// TODO(fbarchard): fix build error on x86 debug -// https://code.google.com/p/libyuv/issues/detail?id=524 -#define HAS_I411TOARGBROW_SSSE3 -// TODO(fbarchard): fix build error on android_full_debug=1 -// https://code.google.com/p/libyuv/issues/detail?id=517 -#define HAS_I422ALPHATOARGBROW_SSSE3 -#endif -#endif - -// The following are available on all x86 platforms, but -// require VS2012, clang 3.4 or gcc 4.7. -// The code supports NaCL but requires a new compiler and validator. -#if !defined(LIBYUV_DISABLE_X86) && (defined(VISUALC_HAS_AVX2) || \ - defined(CLANG_HAS_AVX2) || defined(GCC_HAS_AVX2)) -#define HAS_ARGBCOPYALPHAROW_AVX2 -#define HAS_ARGBCOPYYTOALPHAROW_AVX2 -#define HAS_ARGBMIRRORROW_AVX2 -#define HAS_ARGBPOLYNOMIALROW_AVX2 -#define HAS_ARGBSHUFFLEROW_AVX2 -#define HAS_ARGBTORGB565DITHERROW_AVX2 -#define HAS_ARGBTOUVJROW_AVX2 -#define HAS_ARGBTOUVROW_AVX2 -#define HAS_ARGBTOYJROW_AVX2 -#define HAS_ARGBTOYROW_AVX2 -#define HAS_COPYROW_AVX -#define HAS_H422TOARGBROW_AVX2 -#define HAS_I400TOARGBROW_AVX2 -#if !(defined(_DEBUG) && defined(__i386__)) -// TODO(fbarchard): fix build error on android_full_debug=1 -// https://code.google.com/p/libyuv/issues/detail?id=517 -#define HAS_I422ALPHATOARGBROW_AVX2 -#endif -#define HAS_I411TOARGBROW_AVX2 -#define HAS_I422TOARGB1555ROW_AVX2 -#define HAS_I422TOARGB4444ROW_AVX2 -#define HAS_I422TOARGBROW_AVX2 -#define HAS_I422TORGB24ROW_AVX2 -#define HAS_I422TORGB565ROW_AVX2 -#define HAS_I422TORGBAROW_AVX2 -#define HAS_I444TOARGBROW_AVX2 -#define HAS_INTERPOLATEROW_AVX2 -#define HAS_J422TOARGBROW_AVX2 -#define HAS_MERGEUVROW_AVX2 -#define HAS_MIRRORROW_AVX2 -#define HAS_NV12TOARGBROW_AVX2 -#define HAS_NV12TORGB565ROW_AVX2 -#define HAS_NV21TOARGBROW_AVX2 -#define HAS_SPLITUVROW_AVX2 -#define HAS_UYVYTOARGBROW_AVX2 -#define HAS_UYVYTOUV422ROW_AVX2 -#define HAS_UYVYTOUVROW_AVX2 -#define HAS_UYVYTOYROW_AVX2 -#define HAS_YUY2TOARGBROW_AVX2 -#define HAS_YUY2TOUV422ROW_AVX2 -#define HAS_YUY2TOUVROW_AVX2 -#define HAS_YUY2TOYROW_AVX2 -#define HAS_HALFFLOATROW_AVX2 - -// Effects: -#define HAS_ARGBADDROW_AVX2 -#define HAS_ARGBATTENUATEROW_AVX2 -#define HAS_ARGBMULTIPLYROW_AVX2 -#define HAS_ARGBSUBTRACTROW_AVX2 -#define HAS_ARGBUNATTENUATEROW_AVX2 -#define HAS_BLENDPLANEROW_AVX2 -#endif - -// The following are available for AVX2 Visual C and clangcl 32 bit: -// TODO(fbarchard): Port to gcc. -#if !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) && \ - (defined(VISUALC_HAS_AVX2) || defined(CLANG_HAS_AVX2)) -#define HAS_ARGB1555TOARGBROW_AVX2 -#define HAS_ARGB4444TOARGBROW_AVX2 -#define HAS_ARGBTOARGB1555ROW_AVX2 -#define HAS_ARGBTOARGB4444ROW_AVX2 -#define HAS_ARGBTORGB565ROW_AVX2 -#define HAS_J400TOARGBROW_AVX2 -#define HAS_RGB565TOARGBROW_AVX2 -#endif - -// The following are also available on x64 Visual C. -#if !defined(LIBYUV_DISABLE_X86) && defined(_MSC_VER) && defined(_M_X64) && \ - (!defined(__clang__) || defined(__SSSE3__)) -#define HAS_I422ALPHATOARGBROW_SSSE3 -#define HAS_I422TOARGBROW_SSSE3 -#endif - -// The following are available on gcc x86 platforms: -// TODO(fbarchard): Port to Visual C. -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(__x86_64__) || (defined(__i386__) && !defined(_MSC_VER))) -#define HAS_HALFFLOATROW_SSE2 -#endif - -// The following are available on Neon platforms: -#if !defined(LIBYUV_DISABLE_NEON) && \ - (defined(__aarch64__) || defined(__ARM_NEON__) || defined(LIBYUV_NEON)) -#define HAS_ABGRTOUVROW_NEON -#define HAS_ABGRTOYROW_NEON -#define HAS_ARGB1555TOARGBROW_NEON -#define HAS_ARGB1555TOUVROW_NEON -#define HAS_ARGB1555TOYROW_NEON -#define HAS_ARGB4444TOARGBROW_NEON -#define HAS_ARGB4444TOUVROW_NEON -#define HAS_ARGB4444TOYROW_NEON -#define HAS_ARGBSETROW_NEON -#define HAS_ARGBTOARGB1555ROW_NEON -#define HAS_ARGBTOARGB4444ROW_NEON -#define HAS_ARGBTORAWROW_NEON -#define HAS_ARGBTORGB24ROW_NEON -#define HAS_ARGBTORGB565DITHERROW_NEON -#define HAS_ARGBTORGB565ROW_NEON -#define HAS_ARGBTOUV411ROW_NEON -#define HAS_ARGBTOUV444ROW_NEON -#define HAS_ARGBTOUVJROW_NEON -#define HAS_ARGBTOUVROW_NEON -#define HAS_ARGBTOYJROW_NEON -#define HAS_ARGBTOYROW_NEON -#define HAS_ARGBEXTRACTALPHAROW_NEON -#define HAS_BGRATOUVROW_NEON -#define HAS_BGRATOYROW_NEON -#define HAS_COPYROW_NEON -#define HAS_I400TOARGBROW_NEON -#define HAS_I411TOARGBROW_NEON -#define HAS_I422ALPHATOARGBROW_NEON -#define HAS_I422TOARGB1555ROW_NEON -#define HAS_I422TOARGB4444ROW_NEON -#define HAS_I422TOARGBROW_NEON -#define HAS_I422TORGB24ROW_NEON -#define HAS_I422TORGB565ROW_NEON -#define HAS_I422TORGBAROW_NEON -#define HAS_I422TOUYVYROW_NEON -#define HAS_I422TOYUY2ROW_NEON -#define HAS_I444TOARGBROW_NEON -#define HAS_J400TOARGBROW_NEON -#define HAS_MERGEUVROW_NEON -#define HAS_MIRRORROW_NEON -#define HAS_MIRRORUVROW_NEON -#define HAS_NV12TOARGBROW_NEON -#define HAS_NV12TORGB565ROW_NEON -#define HAS_NV21TOARGBROW_NEON -#define HAS_RAWTOARGBROW_NEON -#define HAS_RAWTORGB24ROW_NEON -#define HAS_RAWTOUVROW_NEON -#define HAS_RAWTOYROW_NEON -#define HAS_RGB24TOARGBROW_NEON -#define HAS_RGB24TOUVROW_NEON -#define HAS_RGB24TOYROW_NEON -#define HAS_RGB565TOARGBROW_NEON -#define HAS_RGB565TOUVROW_NEON -#define HAS_RGB565TOYROW_NEON -#define HAS_RGBATOUVROW_NEON -#define HAS_RGBATOYROW_NEON -#define HAS_SETROW_NEON -#define HAS_SPLITUVROW_NEON -#define HAS_UYVYTOARGBROW_NEON -#define HAS_UYVYTOUV422ROW_NEON -#define HAS_UYVYTOUVROW_NEON -#define HAS_UYVYTOYROW_NEON -#define HAS_YUY2TOARGBROW_NEON -#define HAS_YUY2TOUV422ROW_NEON -#define HAS_YUY2TOUVROW_NEON -#define HAS_YUY2TOYROW_NEON - -// Effects: -#define HAS_ARGBADDROW_NEON -#define HAS_ARGBATTENUATEROW_NEON -#define HAS_ARGBBLENDROW_NEON -#define HAS_ARGBCOLORMATRIXROW_NEON -#define HAS_ARGBGRAYROW_NEON -#define HAS_ARGBMIRRORROW_NEON -#define HAS_ARGBMULTIPLYROW_NEON -#define HAS_ARGBQUANTIZEROW_NEON -#define HAS_ARGBSEPIAROW_NEON -#define HAS_ARGBSHADEROW_NEON -#define HAS_ARGBSHUFFLEROW_NEON -#define HAS_ARGBSUBTRACTROW_NEON -#define HAS_INTERPOLATEROW_NEON -#define HAS_SOBELROW_NEON -#define HAS_SOBELTOPLANEROW_NEON -#define HAS_SOBELXROW_NEON -#define HAS_SOBELXYROW_NEON -#define HAS_SOBELYROW_NEON -#endif - -// The following are available on Mips platforms: -#if !defined(LIBYUV_DISABLE_MIPS) && defined(__mips__) && \ - (_MIPS_SIM == _MIPS_SIM_ABI32) && (__mips_isa_rev < 6) -#define HAS_COPYROW_MIPS -#if defined(__mips_dsp) && (__mips_dsp_rev >= 2) -#define HAS_I422TOARGBROW_DSPR2 -#define HAS_INTERPOLATEROW_DSPR2 -#define HAS_MIRRORROW_DSPR2 -#define HAS_MIRRORUVROW_DSPR2 -#define HAS_SPLITUVROW_DSPR2 -#endif -#endif - -#if !defined(LIBYUV_DISABLE_MSA) && defined(__mips_msa) -#define HAS_MIRRORROW_MSA -#define HAS_ARGBMIRRORROW_MSA -#endif - -#if defined(_MSC_VER) && !defined(__CLR_VER) && !defined(__clang__) -#if defined(VISUALC_HAS_AVX2) -#define SIMD_ALIGNED(var) __declspec(align(32)) var -#else -#define SIMD_ALIGNED(var) __declspec(align(16)) var -#endif -typedef __declspec(align(16)) int16 vec16[8]; -typedef __declspec(align(16)) int32 vec32[4]; -typedef __declspec(align(16)) int8 vec8[16]; -typedef __declspec(align(16)) uint16 uvec16[8]; -typedef __declspec(align(16)) uint32 uvec32[4]; -typedef __declspec(align(16)) uint8 uvec8[16]; -typedef __declspec(align(32)) int16 lvec16[16]; -typedef __declspec(align(32)) int32 lvec32[8]; -typedef __declspec(align(32)) int8 lvec8[32]; -typedef __declspec(align(32)) uint16 ulvec16[16]; -typedef __declspec(align(32)) uint32 ulvec32[8]; -typedef __declspec(align(32)) uint8 ulvec8[32]; -#elif !defined(__pnacl__) && (defined(__GNUC__) || defined(__clang__)) -// Caveat GCC 4.2 to 4.7 have a known issue using vectors with const. -#if defined(CLANG_HAS_AVX2) || defined(GCC_HAS_AVX2) -#define SIMD_ALIGNED(var) var __attribute__((aligned(32))) -#else -#define SIMD_ALIGNED(var) var __attribute__((aligned(16))) -#endif -typedef int16 __attribute__((vector_size(16))) vec16; -typedef int32 __attribute__((vector_size(16))) vec32; -typedef int8 __attribute__((vector_size(16))) vec8; -typedef uint16 __attribute__((vector_size(16))) uvec16; -typedef uint32 __attribute__((vector_size(16))) uvec32; -typedef uint8 __attribute__((vector_size(16))) uvec8; -typedef int16 __attribute__((vector_size(32))) lvec16; -typedef int32 __attribute__((vector_size(32))) lvec32; -typedef int8 __attribute__((vector_size(32))) lvec8; -typedef uint16 __attribute__((vector_size(32))) ulvec16; -typedef uint32 __attribute__((vector_size(32))) ulvec32; -typedef uint8 __attribute__((vector_size(32))) ulvec8; -#else -#define SIMD_ALIGNED(var) var -typedef int16 vec16[8]; -typedef int32 vec32[4]; -typedef int8 vec8[16]; -typedef uint16 uvec16[8]; -typedef uint32 uvec32[4]; -typedef uint8 uvec8[16]; -typedef int16 lvec16[16]; -typedef int32 lvec32[8]; -typedef int8 lvec8[32]; -typedef uint16 ulvec16[16]; -typedef uint32 ulvec32[8]; -typedef uint8 ulvec8[32]; -#endif - -#if defined(__aarch64__) -// This struct is for Arm64 color conversion. -struct YuvConstants { - uvec16 kUVToRB; - uvec16 kUVToRB2; - uvec16 kUVToG; - uvec16 kUVToG2; - vec16 kUVBiasBGR; - vec32 kYToRgb; -}; -#elif defined(__arm__) -// This struct is for ArmV7 color conversion. -struct YuvConstants { - uvec8 kUVToRB; - uvec8 kUVToG; - vec16 kUVBiasBGR; - vec32 kYToRgb; -}; -#else -// This struct is for Intel color conversion. -struct YuvConstants { - int8 kUVToB[32]; - int8 kUVToG[32]; - int8 kUVToR[32]; - int16 kUVBiasB[16]; - int16 kUVBiasG[16]; - int16 kUVBiasR[16]; - int16 kYToRgb[16]; -}; - -// Offsets into YuvConstants structure -#define KUVTOB 0 -#define KUVTOG 32 -#define KUVTOR 64 -#define KUVBIASB 96 -#define KUVBIASG 128 -#define KUVBIASR 160 -#define KYTORGB 192 -#endif - -// Conversion matrix for YUV to RGB -extern const struct YuvConstants SIMD_ALIGNED(kYuvI601Constants); // BT.601 -extern const struct YuvConstants SIMD_ALIGNED(kYuvJPEGConstants); // JPeg -extern const struct YuvConstants SIMD_ALIGNED(kYuvH709Constants); // BT.709 - -// Conversion matrix for YVU to BGR -extern const struct YuvConstants SIMD_ALIGNED(kYvuI601Constants); // BT.601 -extern const struct YuvConstants SIMD_ALIGNED(kYvuJPEGConstants); // JPeg -extern const struct YuvConstants SIMD_ALIGNED(kYvuH709Constants); // BT.709 - -#if defined(__APPLE__) || defined(__x86_64__) || defined(__llvm__) -#define OMITFP -#else -#define OMITFP __attribute__((optimize("omit-frame-pointer"))) -#endif - -// NaCL macros for GCC x86 and x64. -#if defined(__native_client__) -#define LABELALIGN ".p2align 5\n" -#else -#define LABELALIGN -#endif -#if defined(__native_client__) && defined(__x86_64__) -// r14 is used for MEMOP macros. -#define NACL_R14 "r14", -#define BUNDLELOCK ".bundle_lock\n" -#define BUNDLEUNLOCK ".bundle_unlock\n" -#define MEMACCESS(base) "%%nacl:(%%r15,%q" #base ")" -#define MEMACCESS2(offset, base) "%%nacl:" #offset "(%%r15,%q" #base ")" -#define MEMLEA(offset, base) #offset "(%q" #base ")" -#define MEMLEA3(offset, index, scale) \ - #offset "(,%q" #index "," #scale ")" -#define MEMLEA4(offset, base, index, scale) \ - #offset "(%q" #base ",%q" #index "," #scale ")" -#define MEMMOVESTRING(s, d) "%%nacl:(%q" #s "),%%nacl:(%q" #d "), %%r15" -#define MEMSTORESTRING(reg, d) "%%" #reg ",%%nacl:(%q" #d "), %%r15" -#define MEMOPREG(opcode, offset, base, index, scale, reg) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #opcode " (%%r15,%%r14),%%" #reg "\n" \ - BUNDLEUNLOCK -#define MEMOPMEM(opcode, reg, offset, base, index, scale) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #opcode " %%" #reg ",(%%r15,%%r14)\n" \ - BUNDLEUNLOCK -#define MEMOPARG(opcode, offset, base, index, scale, arg) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #opcode " (%%r15,%%r14),%" #arg "\n" \ - BUNDLEUNLOCK -#define VMEMOPREG(opcode, offset, base, index, scale, reg1, reg2) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #opcode " (%%r15,%%r14),%%" #reg1 ",%%" #reg2 "\n" \ - BUNDLEUNLOCK -#define VEXTOPMEM(op, sel, reg, offset, base, index, scale) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #op " $" #sel ",%%" #reg ",(%%r15,%%r14)\n" \ - BUNDLEUNLOCK -#else // defined(__native_client__) && defined(__x86_64__) -#define NACL_R14 -#define BUNDLEALIGN -#define MEMACCESS(base) "(%" #base ")" -#define MEMACCESS2(offset, base) #offset "(%" #base ")" -#define MEMLEA(offset, base) #offset "(%" #base ")" -#define MEMLEA3(offset, index, scale) \ - #offset "(,%" #index "," #scale ")" -#define MEMLEA4(offset, base, index, scale) \ - #offset "(%" #base ",%" #index "," #scale ")" -#define MEMMOVESTRING(s, d) -#define MEMSTORESTRING(reg, d) -#define MEMOPREG(opcode, offset, base, index, scale, reg) \ - #opcode " " #offset "(%" #base ",%" #index "," #scale "),%%" #reg "\n" -#define MEMOPMEM(opcode, reg, offset, base, index, scale) \ - #opcode " %%" #reg ","#offset "(%" #base ",%" #index "," #scale ")\n" -#define MEMOPARG(opcode, offset, base, index, scale, arg) \ - #opcode " " #offset "(%" #base ",%" #index "," #scale "),%" #arg "\n" -#define VMEMOPREG(opcode, offset, base, index, scale, reg1, reg2) \ - #opcode " " #offset "(%" #base ",%" #index "," #scale "),%%" #reg1 ",%%" \ - #reg2 "\n" -#define VEXTOPMEM(op, sel, reg, offset, base, index, scale) \ - #op " $" #sel ",%%" #reg ","#offset "(%" #base ",%" #index "," #scale ")\n" -#endif // defined(__native_client__) && defined(__x86_64__) - -#if defined(__arm__) || defined(__aarch64__) -#undef MEMACCESS -#if defined(__native_client__) -#define MEMACCESS(base) ".p2align 3\nbic %" #base ", #0xc0000000\n" -#else -#define MEMACCESS(base) -#endif -#endif - -void I444ToARGBRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_NEON(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb24, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb565, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb1555, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb4444, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_NEON(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_NEON(const uint8* src_y, - const uint8* src_uv, - uint8* dst_rgb565, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_NEON(const uint8* src_y, - const uint8* src_vu, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_NEON(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_NEON(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); - -void ARGBToYRow_AVX2(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYRow_Any_AVX2(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYRow_SSSE3(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_AVX2(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_Any_AVX2(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_SSSE3(const uint8* src_argb, uint8* dst_y, int width); -void BGRAToYRow_SSSE3(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_SSSE3(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_SSSE3(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_SSSE3(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_SSSE3(const uint8* src_raw, uint8* dst_y, int width); -void ARGBToYRow_NEON(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_NEON(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToUV444Row_NEON(const uint8* src_argb, uint8* dst_u, uint8* dst_v, - int width); -void ARGBToUV411Row_NEON(const uint8* src_argb, uint8* dst_u, uint8* dst_v, - int width); -void ARGBToUVRow_NEON(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_NEON(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_NEON(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_NEON(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_NEON(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void RGB24ToUVRow_NEON(const uint8* src_rgb24, int src_stride_rgb24, - uint8* dst_u, uint8* dst_v, int width); -void RAWToUVRow_NEON(const uint8* src_raw, int src_stride_raw, - uint8* dst_u, uint8* dst_v, int width); -void RGB565ToUVRow_NEON(const uint8* src_rgb565, int src_stride_rgb565, - uint8* dst_u, uint8* dst_v, int width); -void ARGB1555ToUVRow_NEON(const uint8* src_argb1555, int src_stride_argb1555, - uint8* dst_u, uint8* dst_v, int width); -void ARGB4444ToUVRow_NEON(const uint8* src_argb4444, int src_stride_argb4444, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToYRow_NEON(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_NEON(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_NEON(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_NEON(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_NEON(const uint8* src_raw, uint8* dst_y, int width); -void RGB565ToYRow_NEON(const uint8* src_rgb565, uint8* dst_y, int width); -void ARGB1555ToYRow_NEON(const uint8* src_argb1555, uint8* dst_y, int width); -void ARGB4444ToYRow_NEON(const uint8* src_argb4444, uint8* dst_y, int width); -void ARGBToYRow_C(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_C(const uint8* src_argb, uint8* dst_y, int width); -void BGRAToYRow_C(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_C(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_C(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_C(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_C(const uint8* src_raw, uint8* dst_y, int width); -void RGB565ToYRow_C(const uint8* src_rgb565, uint8* dst_y, int width); -void ARGB1555ToYRow_C(const uint8* src_argb1555, uint8* dst_y, int width); -void ARGB4444ToYRow_C(const uint8* src_argb4444, uint8* dst_y, int width); -void ARGBToYRow_Any_SSSE3(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_Any_SSSE3(const uint8* src_argb, uint8* dst_y, int width); -void BGRAToYRow_Any_SSSE3(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_Any_SSSE3(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_Any_SSSE3(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_Any_SSSE3(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_Any_SSSE3(const uint8* src_raw, uint8* dst_y, int width); -void ARGBToYRow_Any_NEON(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_Any_NEON(const uint8* src_argb, uint8* dst_y, int width); -void BGRAToYRow_Any_NEON(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_Any_NEON(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_Any_NEON(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_Any_NEON(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_Any_NEON(const uint8* src_raw, uint8* dst_y, int width); -void RGB565ToYRow_Any_NEON(const uint8* src_rgb565, uint8* dst_y, int width); -void ARGB1555ToYRow_Any_NEON(const uint8* src_argb1555, uint8* dst_y, - int width); -void ARGB4444ToYRow_Any_NEON(const uint8* src_argb4444, uint8* dst_y, - int width); - -void ARGBToUVRow_AVX2(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_AVX2(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVRow_SSSE3(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_SSSE3(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_SSSE3(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_SSSE3(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_SSSE3(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVRow_Any_AVX2(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_Any_AVX2(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVRow_Any_SSSE3(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_Any_SSSE3(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_Any_SSSE3(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_Any_SSSE3(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_Any_SSSE3(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUV444Row_Any_NEON(const uint8* src_argb, uint8* dst_u, uint8* dst_v, - int width); -void ARGBToUV411Row_Any_NEON(const uint8* src_argb, uint8* dst_u, uint8* dst_v, - int width); -void ARGBToUVRow_Any_NEON(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_Any_NEON(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_Any_NEON(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_Any_NEON(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_Any_NEON(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void RGB24ToUVRow_Any_NEON(const uint8* src_rgb24, int src_stride_rgb24, - uint8* dst_u, uint8* dst_v, int width); -void RAWToUVRow_Any_NEON(const uint8* src_raw, int src_stride_raw, - uint8* dst_u, uint8* dst_v, int width); -void RGB565ToUVRow_Any_NEON(const uint8* src_rgb565, int src_stride_rgb565, - uint8* dst_u, uint8* dst_v, int width); -void ARGB1555ToUVRow_Any_NEON(const uint8* src_argb1555, - int src_stride_argb1555, - uint8* dst_u, uint8* dst_v, int width); -void ARGB4444ToUVRow_Any_NEON(const uint8* src_argb4444, - int src_stride_argb4444, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVRow_C(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_C(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_C(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_C(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_C(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void RGB24ToUVRow_C(const uint8* src_rgb24, int src_stride_rgb24, - uint8* dst_u, uint8* dst_v, int width); -void RAWToUVRow_C(const uint8* src_raw, int src_stride_raw, - uint8* dst_u, uint8* dst_v, int width); -void RGB565ToUVRow_C(const uint8* src_rgb565, int src_stride_rgb565, - uint8* dst_u, uint8* dst_v, int width); -void ARGB1555ToUVRow_C(const uint8* src_argb1555, int src_stride_argb1555, - uint8* dst_u, uint8* dst_v, int width); -void ARGB4444ToUVRow_C(const uint8* src_argb4444, int src_stride_argb4444, - uint8* dst_u, uint8* dst_v, int width); - -void ARGBToUV444Row_SSSE3(const uint8* src_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUV444Row_Any_SSSE3(const uint8* src_argb, - uint8* dst_u, uint8* dst_v, int width); - -void ARGBToUV444Row_C(const uint8* src_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUV411Row_C(const uint8* src_argb, - uint8* dst_u, uint8* dst_v, int width); - -void MirrorRow_AVX2(const uint8* src, uint8* dst, int width); -void MirrorRow_SSSE3(const uint8* src, uint8* dst, int width); -void MirrorRow_NEON(const uint8* src, uint8* dst, int width); -void MirrorRow_DSPR2(const uint8* src, uint8* dst, int width); -void MirrorRow_MSA(const uint8* src, uint8* dst, int width); -void MirrorRow_C(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_AVX2(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_SSSE3(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_SSE2(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_NEON(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_MSA(const uint8* src, uint8* dst, int width); - -void MirrorUVRow_SSSE3(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void MirrorUVRow_NEON(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void MirrorUVRow_DSPR2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void MirrorUVRow_C(const uint8* src_uv, uint8* dst_u, uint8* dst_v, int width); - -void ARGBMirrorRow_AVX2(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_SSE2(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_NEON(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_MSA(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_C(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_Any_AVX2(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_Any_SSE2(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_Any_NEON(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_Any_MSA(const uint8* src, uint8* dst, int width); - -void SplitUVRow_C(const uint8* src_uv, uint8* dst_u, uint8* dst_v, int width); -void SplitUVRow_SSE2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_AVX2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_NEON(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_DSPR2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_Any_SSE2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_Any_AVX2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_Any_NEON(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_Any_DSPR2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); - -void MergeUVRow_C(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_SSE2(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_AVX2(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_NEON(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_Any_SSE2(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_Any_AVX2(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_Any_NEON(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); - -void CopyRow_SSE2(const uint8* src, uint8* dst, int count); -void CopyRow_AVX(const uint8* src, uint8* dst, int count); -void CopyRow_ERMS(const uint8* src, uint8* dst, int count); -void CopyRow_NEON(const uint8* src, uint8* dst, int count); -void CopyRow_MIPS(const uint8* src, uint8* dst, int count); -void CopyRow_C(const uint8* src, uint8* dst, int count); -void CopyRow_Any_SSE2(const uint8* src, uint8* dst, int count); -void CopyRow_Any_AVX(const uint8* src, uint8* dst, int count); -void CopyRow_Any_NEON(const uint8* src, uint8* dst, int count); - -void CopyRow_16_C(const uint16* src, uint16* dst, int count); - -void ARGBCopyAlphaRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBCopyAlphaRow_SSE2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBCopyAlphaRow_AVX2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBCopyAlphaRow_Any_SSE2(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBCopyAlphaRow_Any_AVX2(const uint8* src_argb, uint8* dst_argb, - int width); - -void ARGBExtractAlphaRow_C(const uint8* src_argb, uint8* dst_a, int width); -void ARGBExtractAlphaRow_SSE2(const uint8* src_argb, uint8* dst_a, int width); -void ARGBExtractAlphaRow_NEON(const uint8* src_argb, uint8* dst_a, int width); -void ARGBExtractAlphaRow_Any_SSE2(const uint8* src_argb, uint8* dst_a, - int width); -void ARGBExtractAlphaRow_Any_NEON(const uint8* src_argb, uint8* dst_a, - int width); - -void ARGBCopyYToAlphaRow_C(const uint8* src_y, uint8* dst_argb, int width); -void ARGBCopyYToAlphaRow_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void ARGBCopyYToAlphaRow_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void ARGBCopyYToAlphaRow_Any_SSE2(const uint8* src_y, uint8* dst_argb, - int width); -void ARGBCopyYToAlphaRow_Any_AVX2(const uint8* src_y, uint8* dst_argb, - int width); - -void SetRow_C(uint8* dst, uint8 v8, int count); -void SetRow_X86(uint8* dst, uint8 v8, int count); -void SetRow_ERMS(uint8* dst, uint8 v8, int count); -void SetRow_NEON(uint8* dst, uint8 v8, int count); -void SetRow_Any_X86(uint8* dst, uint8 v8, int count); -void SetRow_Any_NEON(uint8* dst, uint8 v8, int count); - -void ARGBSetRow_C(uint8* dst_argb, uint32 v32, int count); -void ARGBSetRow_X86(uint8* dst_argb, uint32 v32, int count); -void ARGBSetRow_NEON(uint8* dst_argb, uint32 v32, int count); -void ARGBSetRow_Any_NEON(uint8* dst_argb, uint32 v32, int count); - -// ARGBShufflers for BGRAToARGB etc. -void ARGBShuffleRow_C(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_SSE2(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_SSSE3(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_AVX2(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_NEON(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_Any_SSE2(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_Any_SSSE3(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_Any_AVX2(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_Any_NEON(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); - -void RGB24ToARGBRow_SSSE3(const uint8* src_rgb24, uint8* dst_argb, int width); -void RAWToARGBRow_SSSE3(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_SSSE3(const uint8* src_raw, uint8* dst_rgb24, int width); -void RGB565ToARGBRow_SSE2(const uint8* src_rgb565, uint8* dst_argb, int width); -void ARGB1555ToARGBRow_SSE2(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_SSE2(const uint8* src_argb4444, uint8* dst_argb, - int width); -void RGB565ToARGBRow_AVX2(const uint8* src_rgb565, uint8* dst_argb, int width); -void ARGB1555ToARGBRow_AVX2(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_AVX2(const uint8* src_argb4444, uint8* dst_argb, - int width); - -void RGB24ToARGBRow_NEON(const uint8* src_rgb24, uint8* dst_argb, int width); -void RAWToARGBRow_NEON(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_NEON(const uint8* src_raw, uint8* dst_rgb24, int width); -void RGB565ToARGBRow_NEON(const uint8* src_rgb565, uint8* dst_argb, int width); -void ARGB1555ToARGBRow_NEON(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_NEON(const uint8* src_argb4444, uint8* dst_argb, - int width); -void RGB24ToARGBRow_C(const uint8* src_rgb24, uint8* dst_argb, int width); -void RAWToARGBRow_C(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_C(const uint8* src_raw, uint8* dst_rgb24, int width); -void RGB565ToARGBRow_C(const uint8* src_rgb, uint8* dst_argb, int width); -void ARGB1555ToARGBRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGB4444ToARGBRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void RGB24ToARGBRow_Any_SSSE3(const uint8* src_rgb24, uint8* dst_argb, - int width); -void RAWToARGBRow_Any_SSSE3(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_Any_SSSE3(const uint8* src_raw, uint8* dst_rgb24, int width); - -void RGB565ToARGBRow_Any_SSE2(const uint8* src_rgb565, uint8* dst_argb, - int width); -void ARGB1555ToARGBRow_Any_SSE2(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_Any_SSE2(const uint8* src_argb4444, uint8* dst_argb, - int width); -void RGB565ToARGBRow_Any_AVX2(const uint8* src_rgb565, uint8* dst_argb, - int width); -void ARGB1555ToARGBRow_Any_AVX2(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_Any_AVX2(const uint8* src_argb4444, uint8* dst_argb, - int width); - -void RGB24ToARGBRow_Any_NEON(const uint8* src_rgb24, uint8* dst_argb, - int width); -void RAWToARGBRow_Any_NEON(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_Any_NEON(const uint8* src_raw, uint8* dst_rgb24, int width); -void RGB565ToARGBRow_Any_NEON(const uint8* src_rgb565, uint8* dst_argb, - int width); -void ARGB1555ToARGBRow_Any_NEON(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_Any_NEON(const uint8* src_argb4444, uint8* dst_argb, - int width); - -void ARGBToRGB24Row_SSSE3(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_SSSE3(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_SSE2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_SSE2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB4444Row_SSE2(const uint8* src_argb, uint8* dst_rgb, int width); - -void ARGBToRGB565DitherRow_C(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); -void ARGBToRGB565DitherRow_SSE2(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); -void ARGBToRGB565DitherRow_AVX2(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); - -void ARGBToRGB565Row_AVX2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_AVX2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB4444Row_AVX2(const uint8* src_argb, uint8* dst_rgb, int width); - -void ARGBToRGB24Row_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB4444Row_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565DitherRow_NEON(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); - -void ARGBToRGBARow_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB24Row_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB4444Row_C(const uint8* src_argb, uint8* dst_rgb, int width); - -void J400ToARGBRow_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_NEON(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_C(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_Any_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_Any_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_Any_NEON(const uint8* src_y, uint8* dst_argb, int width); - -void I444ToARGBRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_C(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_C(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_C(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_C(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_C(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_C(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb24, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb4444, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb4444, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb565, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_SSSE3(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_AVX2(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_SSSE3(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_SSSE3(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_AVX2(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_AVX2(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb24, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb24, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_Any_SSSE3(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_Any_AVX2(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_vu, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_vu, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_Any_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_Any_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_Any_SSSE3(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_Any_SSSE3(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_Any_AVX2(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_Any_AVX2(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); - -void I400ToARGBRow_C(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_NEON(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_Any_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_Any_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_Any_NEON(const uint8* src_y, uint8* dst_argb, int width); - -// ARGB preattenuated alpha blend. -void ARGBBlendRow_SSSE3(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBBlendRow_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBBlendRow_C(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); - -// Unattenuated planar alpha blend. -void BlendPlaneRow_SSSE3(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); -void BlendPlaneRow_Any_SSSE3(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); -void BlendPlaneRow_AVX2(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); -void BlendPlaneRow_Any_AVX2(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); -void BlendPlaneRow_C(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); - -// ARGB multiply images. Same API as Blend, but these require -// pointer and width alignment for SSE2. -void ARGBMultiplyRow_C(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_Any_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_Any_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_Any_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); - -// ARGB add images. -void ARGBAddRow_C(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_Any_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_Any_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_Any_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); - -// ARGB subtract images. Same API as Blend, but these require -// pointer and width alignment for SSE2. -void ARGBSubtractRow_C(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_Any_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_Any_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_Any_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); - -void ARGBToRGB24Row_Any_SSSE3(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_Any_SSSE3(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_Any_SSE2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_Any_SSE2(const uint8* src_argb, uint8* dst_rgb, - int width); -void ARGBToARGB4444Row_Any_SSE2(const uint8* src_argb, uint8* dst_rgb, - int width); - -void ARGBToRGB565DitherRow_Any_SSE2(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); -void ARGBToRGB565DitherRow_Any_AVX2(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); - -void ARGBToRGB565Row_Any_AVX2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_Any_AVX2(const uint8* src_argb, uint8* dst_rgb, - int width); -void ARGBToARGB4444Row_Any_AVX2(const uint8* src_argb, uint8* dst_rgb, - int width); - -void ARGBToRGB24Row_Any_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_Any_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_Any_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_Any_NEON(const uint8* src_argb, uint8* dst_rgb, - int width); -void ARGBToARGB4444Row_Any_NEON(const uint8* src_argb, uint8* dst_rgb, - int width); -void ARGBToRGB565DitherRow_Any_NEON(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); - -void I444ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - const uint8* src_a, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_vu, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_Any_NEON(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_Any_NEON(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_Any_NEON(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_DSPR2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_DSPR2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); - -void YUY2ToYRow_AVX2(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_AVX2(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_AVX2(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_SSE2(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_SSE2(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_SSE2(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_NEON(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_NEON(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_NEON(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_C(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_C(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_C(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_Any_AVX2(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_Any_AVX2(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_Any_AVX2(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_Any_SSE2(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_Any_SSE2(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_Any_SSE2(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_Any_NEON(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_Any_NEON(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_Any_NEON(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_AVX2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_AVX2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_AVX2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_SSE2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_SSE2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_SSE2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_AVX2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_AVX2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_AVX2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_NEON(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_NEON(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_NEON(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); - -void UYVYToYRow_C(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_C(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_C(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_Any_AVX2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_Any_AVX2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_Any_AVX2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_Any_SSE2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_Any_SSE2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_Any_SSE2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_Any_NEON(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_Any_NEON(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_Any_NEON(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); - -void I422ToYUY2Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); -void I422ToYUY2Row_SSE2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_SSE2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); -void I422ToYUY2Row_Any_SSE2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_Any_SSE2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); -void I422ToYUY2Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); -void I422ToYUY2Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); - -// Effects related row functions. -void ARGBAttenuateRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBAttenuateRow_SSSE3(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBAttenuateRow_AVX2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBAttenuateRow_NEON(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBAttenuateRow_Any_SSE2(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBAttenuateRow_Any_SSSE3(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBAttenuateRow_Any_AVX2(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBAttenuateRow_Any_NEON(const uint8* src_argb, uint8* dst_argb, - int width); - -// Inverse table for unattenuate, shared by C and SSE2. -extern const uint32 fixed_invtbl8[256]; -void ARGBUnattenuateRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBUnattenuateRow_SSE2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBUnattenuateRow_AVX2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBUnattenuateRow_Any_SSE2(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBUnattenuateRow_Any_AVX2(const uint8* src_argb, uint8* dst_argb, - int width); - -void ARGBGrayRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBGrayRow_SSSE3(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBGrayRow_NEON(const uint8* src_argb, uint8* dst_argb, int width); - -void ARGBSepiaRow_C(uint8* dst_argb, int width); -void ARGBSepiaRow_SSSE3(uint8* dst_argb, int width); -void ARGBSepiaRow_NEON(uint8* dst_argb, int width); - -void ARGBColorMatrixRow_C(const uint8* src_argb, uint8* dst_argb, - const int8* matrix_argb, int width); -void ARGBColorMatrixRow_SSSE3(const uint8* src_argb, uint8* dst_argb, - const int8* matrix_argb, int width); -void ARGBColorMatrixRow_NEON(const uint8* src_argb, uint8* dst_argb, - const int8* matrix_argb, int width); - -void ARGBColorTableRow_C(uint8* dst_argb, const uint8* table_argb, int width); -void ARGBColorTableRow_X86(uint8* dst_argb, const uint8* table_argb, int width); - -void RGBColorTableRow_C(uint8* dst_argb, const uint8* table_argb, int width); -void RGBColorTableRow_X86(uint8* dst_argb, const uint8* table_argb, int width); - -void ARGBQuantizeRow_C(uint8* dst_argb, int scale, int interval_size, - int interval_offset, int width); -void ARGBQuantizeRow_SSE2(uint8* dst_argb, int scale, int interval_size, - int interval_offset, int width); -void ARGBQuantizeRow_NEON(uint8* dst_argb, int scale, int interval_size, - int interval_offset, int width); - -void ARGBShadeRow_C(const uint8* src_argb, uint8* dst_argb, int width, - uint32 value); -void ARGBShadeRow_SSE2(const uint8* src_argb, uint8* dst_argb, int width, - uint32 value); -void ARGBShadeRow_NEON(const uint8* src_argb, uint8* dst_argb, int width, - uint32 value); - -// Used for blur. -void CumulativeSumToAverageRow_SSE2(const int32* topleft, const int32* botleft, - int width, int area, uint8* dst, int count); -void ComputeCumulativeSumRow_SSE2(const uint8* row, int32* cumsum, - const int32* previous_cumsum, int width); - -void CumulativeSumToAverageRow_C(const int32* topleft, const int32* botleft, - int width, int area, uint8* dst, int count); -void ComputeCumulativeSumRow_C(const uint8* row, int32* cumsum, - const int32* previous_cumsum, int width); - -LIBYUV_API -void ARGBAffineRow_C(const uint8* src_argb, int src_argb_stride, - uint8* dst_argb, const float* uv_dudv, int width); -LIBYUV_API -void ARGBAffineRow_SSE2(const uint8* src_argb, int src_argb_stride, - uint8* dst_argb, const float* uv_dudv, int width); - -// Used for I420Scale, ARGBScale, and ARGBInterpolate. -void InterpolateRow_C(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, - int width, int source_y_fraction); -void InterpolateRow_SSSE3(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_AVX2(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_NEON(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_DSPR2(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_Any_NEON(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_Any_SSSE3(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_Any_AVX2(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_Any_DSPR2(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); - -void InterpolateRow_16_C(uint16* dst_ptr, const uint16* src_ptr, - ptrdiff_t src_stride_ptr, - int width, int source_y_fraction); - -// Sobel images. -void SobelXRow_C(const uint8* src_y0, const uint8* src_y1, const uint8* src_y2, - uint8* dst_sobelx, int width); -void SobelXRow_SSE2(const uint8* src_y0, const uint8* src_y1, - const uint8* src_y2, uint8* dst_sobelx, int width); -void SobelXRow_NEON(const uint8* src_y0, const uint8* src_y1, - const uint8* src_y2, uint8* dst_sobelx, int width); -void SobelYRow_C(const uint8* src_y0, const uint8* src_y1, - uint8* dst_sobely, int width); -void SobelYRow_SSE2(const uint8* src_y0, const uint8* src_y1, - uint8* dst_sobely, int width); -void SobelYRow_NEON(const uint8* src_y0, const uint8* src_y1, - uint8* dst_sobely, int width); -void SobelRow_C(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelRow_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelRow_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelToPlaneRow_C(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelToPlaneRow_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelToPlaneRow_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelXYRow_C(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelXYRow_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelXYRow_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelRow_Any_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelRow_Any_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelToPlaneRow_Any_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelToPlaneRow_Any_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelXYRow_Any_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelXYRow_Any_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); - -void ARGBPolynomialRow_C(const uint8* src_argb, - uint8* dst_argb, const float* poly, - int width); -void ARGBPolynomialRow_SSE2(const uint8* src_argb, - uint8* dst_argb, const float* poly, - int width); -void ARGBPolynomialRow_AVX2(const uint8* src_argb, - uint8* dst_argb, const float* poly, - int width); - -// Scale and convert to half float. -void HalfFloatRow_C(const uint16* src, uint16* dst, float scale, int width); -void HalfFloatRow_AVX2(const uint16* src, uint16* dst, float scale, int width); -void HalfFloatRow_Any_AVX2(const uint16* src, uint16* dst, float scale, - int width); -void HalfFloatRow_SSE2(const uint16* src, uint16* dst, float scale, int width); -void HalfFloatRow_Any_SSE2(const uint16* src, uint16* dst, float scale, - int width); - -void ARGBLumaColorTableRow_C(const uint8* src_argb, uint8* dst_argb, int width, - const uint8* luma, uint32 lumacoeff); -void ARGBLumaColorTableRow_SSSE3(const uint8* src_argb, uint8* dst_argb, - int width, - const uint8* luma, uint32 lumacoeff); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_ROW_H_ diff --git a/third_party/libyuv/include/libyuv/scale.h b/third_party/libyuv/include/libyuv/scale.h deleted file mode 100644 index ae14694598b2cc..00000000000000 --- a/third_party/libyuv/include/libyuv/scale.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_SCALE_H_ -#define INCLUDE_LIBYUV_SCALE_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Supported filtering. -typedef enum FilterMode { - kFilterNone = 0, // Point sample; Fastest. - kFilterLinear = 1, // Filter horizontally only. - kFilterBilinear = 2, // Faster than box, but lower quality scaling down. - kFilterBox = 3 // Highest quality. -} FilterModeEnum; - -// Scale a YUV plane. -LIBYUV_API -void ScalePlane(const uint8* src, int src_stride, - int src_width, int src_height, - uint8* dst, int dst_stride, - int dst_width, int dst_height, - enum FilterMode filtering); - -LIBYUV_API -void ScalePlane_16(const uint16* src, int src_stride, - int src_width, int src_height, - uint16* dst, int dst_stride, - int dst_width, int dst_height, - enum FilterMode filtering); - -// Scales a YUV 4:2:0 image from the src width and height to the -// dst width and height. -// If filtering is kFilterNone, a simple nearest-neighbor algorithm is -// used. This produces basic (blocky) quality at the fastest speed. -// If filtering is kFilterBilinear, interpolation is used to produce a better -// quality image, at the expense of speed. -// If filtering is kFilterBox, averaging is used to produce ever better -// quality image, at further expense of speed. -// Returns 0 if successful. - -LIBYUV_API -int I420Scale(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - int src_width, int src_height, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int dst_width, int dst_height, - enum FilterMode filtering); - -LIBYUV_API -int I420Scale_16(const uint16* src_y, int src_stride_y, - const uint16* src_u, int src_stride_u, - const uint16* src_v, int src_stride_v, - int src_width, int src_height, - uint16* dst_y, int dst_stride_y, - uint16* dst_u, int dst_stride_u, - uint16* dst_v, int dst_stride_v, - int dst_width, int dst_height, - enum FilterMode filtering); - -#ifdef __cplusplus -// Legacy API. Deprecated. -LIBYUV_API -int Scale(const uint8* src_y, const uint8* src_u, const uint8* src_v, - int src_stride_y, int src_stride_u, int src_stride_v, - int src_width, int src_height, - uint8* dst_y, uint8* dst_u, uint8* dst_v, - int dst_stride_y, int dst_stride_u, int dst_stride_v, - int dst_width, int dst_height, - LIBYUV_BOOL interpolate); - -// Legacy API. Deprecated. -LIBYUV_API -int ScaleOffset(const uint8* src_i420, int src_width, int src_height, - uint8* dst_i420, int dst_width, int dst_height, int dst_yoffset, - LIBYUV_BOOL interpolate); - -// For testing, allow disabling of specialized scalers. -LIBYUV_API -void SetUseReferenceImpl(LIBYUV_BOOL use); -#endif // __cplusplus - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_SCALE_H_ diff --git a/third_party/libyuv/include/libyuv/scale_argb.h b/third_party/libyuv/include/libyuv/scale_argb.h deleted file mode 100644 index 35cd191c0f6123..00000000000000 --- a/third_party/libyuv/include/libyuv/scale_argb.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_SCALE_ARGB_H_ -#define INCLUDE_LIBYUV_SCALE_ARGB_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/scale.h" // For FilterMode - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -LIBYUV_API -int ARGBScale(const uint8* src_argb, int src_stride_argb, - int src_width, int src_height, - uint8* dst_argb, int dst_stride_argb, - int dst_width, int dst_height, - enum FilterMode filtering); - -// Clipped scale takes destination rectangle coordinates for clip values. -LIBYUV_API -int ARGBScaleClip(const uint8* src_argb, int src_stride_argb, - int src_width, int src_height, - uint8* dst_argb, int dst_stride_argb, - int dst_width, int dst_height, - int clip_x, int clip_y, int clip_width, int clip_height, - enum FilterMode filtering); - -// Scale with YUV conversion to ARGB and clipping. -LIBYUV_API -int YUVToARGBScaleClip(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint32 src_fourcc, - int src_width, int src_height, - uint8* dst_argb, int dst_stride_argb, - uint32 dst_fourcc, - int dst_width, int dst_height, - int clip_x, int clip_y, int clip_width, int clip_height, - enum FilterMode filtering); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_SCALE_ARGB_H_ diff --git a/third_party/libyuv/include/libyuv/scale_row.h b/third_party/libyuv/include/libyuv/scale_row.h deleted file mode 100644 index 791fbf7d0538fb..00000000000000 --- a/third_party/libyuv/include/libyuv/scale_row.h +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Copyright 2013 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_SCALE_ROW_H_ -#define INCLUDE_LIBYUV_SCALE_ROW_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/scale.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif - -// GCC >= 4.7.0 required for AVX2. -#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) -#if (__GNUC__ > 4) || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 7)) -#define GCC_HAS_AVX2 1 -#endif // GNUC >= 4.7 -#endif // __GNUC__ - -// clang >= 3.4.0 required for AVX2. -#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) -#if (__clang_major__ > 3) || (__clang_major__ == 3 && (__clang_minor__ >= 4)) -#define CLANG_HAS_AVX2 1 -#endif // clang >= 3.4 -#endif // __clang__ - -// Visual C 2012 required for AVX2. -#if defined(_M_IX86) && !defined(__clang__) && \ - defined(_MSC_VER) && _MSC_VER >= 1700 -#define VISUALC_HAS_AVX2 1 -#endif // VisualStudio >= 2012 - -// The following are available on all x86 platforms: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)) -#define HAS_FIXEDDIV1_X86 -#define HAS_FIXEDDIV_X86 -#define HAS_SCALEARGBCOLS_SSE2 -#define HAS_SCALEARGBCOLSUP2_SSE2 -#define HAS_SCALEARGBFILTERCOLS_SSSE3 -#define HAS_SCALEARGBROWDOWN2_SSE2 -#define HAS_SCALEARGBROWDOWNEVEN_SSE2 -#define HAS_SCALECOLSUP2_SSE2 -#define HAS_SCALEFILTERCOLS_SSSE3 -#define HAS_SCALEROWDOWN2_SSSE3 -#define HAS_SCALEROWDOWN34_SSSE3 -#define HAS_SCALEROWDOWN38_SSSE3 -#define HAS_SCALEROWDOWN4_SSSE3 -#define HAS_SCALEADDROW_SSE2 -#endif - -// The following are available on all x86 platforms, but -// require VS2012, clang 3.4 or gcc 4.7. -// The code supports NaCL but requires a new compiler and validator. -#if !defined(LIBYUV_DISABLE_X86) && (defined(VISUALC_HAS_AVX2) || \ - defined(CLANG_HAS_AVX2) || defined(GCC_HAS_AVX2)) -#define HAS_SCALEADDROW_AVX2 -#define HAS_SCALEROWDOWN2_AVX2 -#define HAS_SCALEROWDOWN4_AVX2 -#endif - -// The following are available on Neon platforms: -#if !defined(LIBYUV_DISABLE_NEON) && !defined(__native_client__) && \ - (defined(__ARM_NEON__) || defined(LIBYUV_NEON) || defined(__aarch64__)) -#define HAS_SCALEARGBCOLS_NEON -#define HAS_SCALEARGBROWDOWN2_NEON -#define HAS_SCALEARGBROWDOWNEVEN_NEON -#define HAS_SCALEFILTERCOLS_NEON -#define HAS_SCALEROWDOWN2_NEON -#define HAS_SCALEROWDOWN34_NEON -#define HAS_SCALEROWDOWN38_NEON -#define HAS_SCALEROWDOWN4_NEON -#define HAS_SCALEARGBFILTERCOLS_NEON -#endif - -// The following are available on Mips platforms: -#if !defined(LIBYUV_DISABLE_MIPS) && !defined(__native_client__) && \ - defined(__mips__) && defined(__mips_dsp) && (__mips_dsp_rev >= 2) -#define HAS_SCALEROWDOWN2_DSPR2 -#define HAS_SCALEROWDOWN4_DSPR2 -#define HAS_SCALEROWDOWN34_DSPR2 -#define HAS_SCALEROWDOWN38_DSPR2 -#endif - -// Scale ARGB vertically with bilinear interpolation. -void ScalePlaneVertical(int src_height, - int dst_width, int dst_height, - int src_stride, int dst_stride, - const uint8* src_argb, uint8* dst_argb, - int x, int y, int dy, - int bpp, enum FilterMode filtering); - -void ScalePlaneVertical_16(int src_height, - int dst_width, int dst_height, - int src_stride, int dst_stride, - const uint16* src_argb, uint16* dst_argb, - int x, int y, int dy, - int wpp, enum FilterMode filtering); - -// Simplify the filtering based on scale factors. -enum FilterMode ScaleFilterReduce(int src_width, int src_height, - int dst_width, int dst_height, - enum FilterMode filtering); - -// Divide num by div and return as 16.16 fixed point result. -int FixedDiv_C(int num, int div); -int FixedDiv_X86(int num, int div); -// Divide num - 1 by div - 1 and return as 16.16 fixed point result. -int FixedDiv1_C(int num, int div); -int FixedDiv1_X86(int num, int div); -#ifdef HAS_FIXEDDIV_X86 -#define FixedDiv FixedDiv_X86 -#define FixedDiv1 FixedDiv1_X86 -#else -#define FixedDiv FixedDiv_C -#define FixedDiv1 FixedDiv1_C -#endif - -// Compute slope values for stepping. -void ScaleSlope(int src_width, int src_height, - int dst_width, int dst_height, - enum FilterMode filtering, - int* x, int* y, int* dx, int* dy); - -void ScaleRowDown2_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown2Linear_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Linear_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown2Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_Odd_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown4_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown4Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown34_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown34_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown34_0_Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* d, int dst_width); -void ScaleRowDown34_0_Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* d, int dst_width); -void ScaleRowDown34_1_Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* d, int dst_width); -void ScaleRowDown34_1_Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* d, int dst_width); -void ScaleCols_C(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); -void ScaleCols_16_C(uint16* dst_ptr, const uint16* src_ptr, - int dst_width, int x, int dx); -void ScaleColsUp2_C(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int, int); -void ScaleColsUp2_16_C(uint16* dst_ptr, const uint16* src_ptr, - int dst_width, int, int); -void ScaleFilterCols_C(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); -void ScaleFilterCols_16_C(uint16* dst_ptr, const uint16* src_ptr, - int dst_width, int x, int dx); -void ScaleFilterCols64_C(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); -void ScaleFilterCols64_16_C(uint16* dst_ptr, const uint16* src_ptr, - int dst_width, int x, int dx); -void ScaleRowDown38_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown38_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown38_3_Box_C(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_3_Box_16_C(const uint16* src_ptr, - ptrdiff_t src_stride, - uint16* dst_ptr, int dst_width); -void ScaleRowDown38_2_Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_2_Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst_ptr, int dst_width); -void ScaleAddRow_C(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_16_C(const uint16* src_ptr, uint32* dst_ptr, int src_width); -void ScaleARGBRowDown2_C(const uint8* src_argb, - ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Linear_C(const uint8* src_argb, - ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_C(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEven_C(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_C(const uint8* src_argb, - ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBCols_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBCols64_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBColsUp2_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int, int); -void ScaleARGBFilterCols_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBFilterCols64_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); - -// Specialized scalers for x86. -void ScaleRowDown2_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Linear_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Linear_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleRowDown34_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_1_Box_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_0_Box_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_3_Box_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_2_Box_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Linear_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_Odd_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Linear_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_Odd_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleRowDown34_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_1_Box_Any_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_0_Box_Any_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_3_Box_Any_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_2_Box_Any_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleAddRow_SSE2(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_AVX2(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_Any_SSE2(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_Any_AVX2(const uint8* src_ptr, uint16* dst_ptr, int src_width); - -void ScaleFilterCols_SSSE3(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); -void ScaleColsUp2_SSE2(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); - - -// ARGB Column functions -void ScaleARGBCols_SSE2(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBFilterCols_SSSE3(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBColsUp2_SSE2(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBFilterCols_NEON(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBCols_NEON(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBFilterCols_Any_NEON(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBCols_Any_NEON(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); - -// ARGB Row functions -void ScaleARGBRowDown2_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Linear_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleARGBRowDown2Linear_NEON(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleARGBRowDown2_Any_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Linear_Any_SSE2(const uint8* src_argb, - ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_Any_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleARGBRowDown2Linear_Any_NEON(const uint8* src_argb, - ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); - -void ScaleARGBRowDownEven_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEven_NEON(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_NEON(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEven_Any_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_Any_SSE2(const uint8* src_argb, - ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEven_Any_NEON(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_Any_NEON(const uint8* src_argb, - ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); - -// ScaleRowDown2Box also used by planar functions -// NEON downscalers with interpolation. - -// Note - not static due to reuse in convert for 444 to 420. -void ScaleRowDown2_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Linear_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); - -void ScaleRowDown4_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -// Down scale from 4 to 3 pixels. Use the neon multilane read/write -// to load up the every 4th pixel into a 4 different registers. -// Point samples 32 pixels to 24 pixels. -void ScaleRowDown34_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_0_Box_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_1_Box_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -// 32 -> 12 -void ScaleRowDown38_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32x3 -> 12x1 -void ScaleRowDown38_3_Box_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32x2 -> 12x1 -void ScaleRowDown38_2_Box_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleRowDown2_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Linear_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_Odd_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_0_Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_1_Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32 -> 12 -void ScaleRowDown38_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32x3 -> 12x1 -void ScaleRowDown38_3_Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32x2 -> 12x1 -void ScaleRowDown38_2_Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleAddRow_NEON(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_Any_NEON(const uint8* src_ptr, uint16* dst_ptr, int src_width); - -void ScaleFilterCols_NEON(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); - -void ScaleFilterCols_Any_NEON(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); - -void ScaleRowDown2_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown34_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown34_0_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* d, int dst_width); -void ScaleRowDown34_1_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* d, int dst_width); -void ScaleRowDown38_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown38_2_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_3_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_SCALE_ROW_H_ diff --git a/third_party/libyuv/include/libyuv/version.h b/third_party/libyuv/include/libyuv/version.h deleted file mode 100644 index 3a8f6337ca22cd..00000000000000 --- a/third_party/libyuv/include/libyuv/version.h +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_VERSION_H_ -#define INCLUDE_LIBYUV_VERSION_H_ - -#define LIBYUV_VERSION 1622 - -#endif // INCLUDE_LIBYUV_VERSION_H_ diff --git a/third_party/libyuv/include/libyuv/video_common.h b/third_party/libyuv/include/libyuv/video_common.h deleted file mode 100644 index cb425426a256e0..00000000000000 --- a/third_party/libyuv/include/libyuv/video_common.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -// Common definitions for video, including fourcc and VideoFormat. - -#ifndef INCLUDE_LIBYUV_VIDEO_COMMON_H_ -#define INCLUDE_LIBYUV_VIDEO_COMMON_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -////////////////////////////////////////////////////////////////////////////// -// Definition of FourCC codes -////////////////////////////////////////////////////////////////////////////// - -// Convert four characters to a FourCC code. -// Needs to be a macro otherwise the OS X compiler complains when the kFormat* -// constants are used in a switch. -#ifdef __cplusplus -#define FOURCC(a, b, c, d) ( \ - (static_cast(a)) | (static_cast(b) << 8) | \ - (static_cast(c) << 16) | (static_cast(d) << 24)) -#else -#define FOURCC(a, b, c, d) ( \ - ((uint32)(a)) | ((uint32)(b) << 8) | /* NOLINT */ \ - ((uint32)(c) << 16) | ((uint32)(d) << 24)) /* NOLINT */ -#endif - -// Some pages discussing FourCC codes: -// http://www.fourcc.org/yuv.php -// http://v4l2spec.bytesex.org/spec/book1.htm -// http://developer.apple.com/quicktime/icefloe/dispatch020.html -// http://msdn.microsoft.com/library/windows/desktop/dd206750.aspx#nv12 -// http://people.xiph.org/~xiphmont/containers/nut/nut4cc.txt - -// FourCC codes grouped according to implementation efficiency. -// Primary formats should convert in 1 efficient step. -// Secondary formats are converted in 2 steps. -// Auxilliary formats call primary converters. -enum FourCC { - // 9 Primary YUV formats: 5 planar, 2 biplanar, 2 packed. - FOURCC_I420 = FOURCC('I', '4', '2', '0'), - FOURCC_I422 = FOURCC('I', '4', '2', '2'), - FOURCC_I444 = FOURCC('I', '4', '4', '4'), - FOURCC_I411 = FOURCC('I', '4', '1', '1'), - FOURCC_I400 = FOURCC('I', '4', '0', '0'), - FOURCC_NV21 = FOURCC('N', 'V', '2', '1'), - FOURCC_NV12 = FOURCC('N', 'V', '1', '2'), - FOURCC_YUY2 = FOURCC('Y', 'U', 'Y', '2'), - FOURCC_UYVY = FOURCC('U', 'Y', 'V', 'Y'), - - // 2 Secondary YUV formats: row biplanar. - FOURCC_M420 = FOURCC('M', '4', '2', '0'), - FOURCC_Q420 = FOURCC('Q', '4', '2', '0'), // deprecated. - - // 9 Primary RGB formats: 4 32 bpp, 2 24 bpp, 3 16 bpp. - FOURCC_ARGB = FOURCC('A', 'R', 'G', 'B'), - FOURCC_BGRA = FOURCC('B', 'G', 'R', 'A'), - FOURCC_ABGR = FOURCC('A', 'B', 'G', 'R'), - FOURCC_24BG = FOURCC('2', '4', 'B', 'G'), - FOURCC_RAW = FOURCC('r', 'a', 'w', ' '), - FOURCC_RGBA = FOURCC('R', 'G', 'B', 'A'), - FOURCC_RGBP = FOURCC('R', 'G', 'B', 'P'), // rgb565 LE. - FOURCC_RGBO = FOURCC('R', 'G', 'B', 'O'), // argb1555 LE. - FOURCC_R444 = FOURCC('R', '4', '4', '4'), // argb4444 LE. - - // 4 Secondary RGB formats: 4 Bayer Patterns. deprecated. - FOURCC_RGGB = FOURCC('R', 'G', 'G', 'B'), - FOURCC_BGGR = FOURCC('B', 'G', 'G', 'R'), - FOURCC_GRBG = FOURCC('G', 'R', 'B', 'G'), - FOURCC_GBRG = FOURCC('G', 'B', 'R', 'G'), - - // 1 Primary Compressed YUV format. - FOURCC_MJPG = FOURCC('M', 'J', 'P', 'G'), - - // 5 Auxiliary YUV variations: 3 with U and V planes are swapped, 1 Alias. - FOURCC_YV12 = FOURCC('Y', 'V', '1', '2'), - FOURCC_YV16 = FOURCC('Y', 'V', '1', '6'), - FOURCC_YV24 = FOURCC('Y', 'V', '2', '4'), - FOURCC_YU12 = FOURCC('Y', 'U', '1', '2'), // Linux version of I420. - FOURCC_J420 = FOURCC('J', '4', '2', '0'), - FOURCC_J400 = FOURCC('J', '4', '0', '0'), // unofficial fourcc - FOURCC_H420 = FOURCC('H', '4', '2', '0'), // unofficial fourcc - - // 14 Auxiliary aliases. CanonicalFourCC() maps these to canonical fourcc. - FOURCC_IYUV = FOURCC('I', 'Y', 'U', 'V'), // Alias for I420. - FOURCC_YU16 = FOURCC('Y', 'U', '1', '6'), // Alias for I422. - FOURCC_YU24 = FOURCC('Y', 'U', '2', '4'), // Alias for I444. - FOURCC_YUYV = FOURCC('Y', 'U', 'Y', 'V'), // Alias for YUY2. - FOURCC_YUVS = FOURCC('y', 'u', 'v', 's'), // Alias for YUY2 on Mac. - FOURCC_HDYC = FOURCC('H', 'D', 'Y', 'C'), // Alias for UYVY. - FOURCC_2VUY = FOURCC('2', 'v', 'u', 'y'), // Alias for UYVY on Mac. - FOURCC_JPEG = FOURCC('J', 'P', 'E', 'G'), // Alias for MJPG. - FOURCC_DMB1 = FOURCC('d', 'm', 'b', '1'), // Alias for MJPG on Mac. - FOURCC_BA81 = FOURCC('B', 'A', '8', '1'), // Alias for BGGR. - FOURCC_RGB3 = FOURCC('R', 'G', 'B', '3'), // Alias for RAW. - FOURCC_BGR3 = FOURCC('B', 'G', 'R', '3'), // Alias for 24BG. - FOURCC_CM32 = FOURCC(0, 0, 0, 32), // Alias for BGRA kCMPixelFormat_32ARGB - FOURCC_CM24 = FOURCC(0, 0, 0, 24), // Alias for RAW kCMPixelFormat_24RGB - FOURCC_L555 = FOURCC('L', '5', '5', '5'), // Alias for RGBO. - FOURCC_L565 = FOURCC('L', '5', '6', '5'), // Alias for RGBP. - FOURCC_5551 = FOURCC('5', '5', '5', '1'), // Alias for RGBO. - - // 1 Auxiliary compressed YUV format set aside for capturer. - FOURCC_H264 = FOURCC('H', '2', '6', '4'), - - // Match any fourcc. - FOURCC_ANY = -1, -}; - -enum FourCCBpp { - // Canonical fourcc codes used in our code. - FOURCC_BPP_I420 = 12, - FOURCC_BPP_I422 = 16, - FOURCC_BPP_I444 = 24, - FOURCC_BPP_I411 = 12, - FOURCC_BPP_I400 = 8, - FOURCC_BPP_NV21 = 12, - FOURCC_BPP_NV12 = 12, - FOURCC_BPP_YUY2 = 16, - FOURCC_BPP_UYVY = 16, - FOURCC_BPP_M420 = 12, - FOURCC_BPP_Q420 = 12, - FOURCC_BPP_ARGB = 32, - FOURCC_BPP_BGRA = 32, - FOURCC_BPP_ABGR = 32, - FOURCC_BPP_RGBA = 32, - FOURCC_BPP_24BG = 24, - FOURCC_BPP_RAW = 24, - FOURCC_BPP_RGBP = 16, - FOURCC_BPP_RGBO = 16, - FOURCC_BPP_R444 = 16, - FOURCC_BPP_RGGB = 8, - FOURCC_BPP_BGGR = 8, - FOURCC_BPP_GRBG = 8, - FOURCC_BPP_GBRG = 8, - FOURCC_BPP_YV12 = 12, - FOURCC_BPP_YV16 = 16, - FOURCC_BPP_YV24 = 24, - FOURCC_BPP_YU12 = 12, - FOURCC_BPP_J420 = 12, - FOURCC_BPP_J400 = 8, - FOURCC_BPP_H420 = 12, - FOURCC_BPP_MJPG = 0, // 0 means unknown. - FOURCC_BPP_H264 = 0, - FOURCC_BPP_IYUV = 12, - FOURCC_BPP_YU16 = 16, - FOURCC_BPP_YU24 = 24, - FOURCC_BPP_YUYV = 16, - FOURCC_BPP_YUVS = 16, - FOURCC_BPP_HDYC = 16, - FOURCC_BPP_2VUY = 16, - FOURCC_BPP_JPEG = 1, - FOURCC_BPP_DMB1 = 1, - FOURCC_BPP_BA81 = 8, - FOURCC_BPP_RGB3 = 24, - FOURCC_BPP_BGR3 = 24, - FOURCC_BPP_CM32 = 32, - FOURCC_BPP_CM24 = 24, - - // Match any fourcc. - FOURCC_BPP_ANY = 0, // 0 means unknown. -}; - -// Converts fourcc aliases into canonical ones. -LIBYUV_API uint32 CanonicalFourCC(uint32 fourcc); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_VIDEO_COMMON_H_ diff --git a/third_party/libyuv/larch64/lib/libyuv.a b/third_party/libyuv/larch64/lib/libyuv.a deleted file mode 100644 index 1c91250231fa88..00000000000000 --- a/third_party/libyuv/larch64/lib/libyuv.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:320bef5a75a62dd2731a496040921d5000f1ed237ae70fd7aeb6c010a1534363 -size 462482 diff --git a/third_party/libyuv/x86_64/include b/third_party/libyuv/x86_64/include deleted file mode 120000 index f5030fe8899824..00000000000000 --- a/third_party/libyuv/x86_64/include +++ /dev/null @@ -1 +0,0 @@ -../include \ No newline at end of file diff --git a/third_party/libyuv/x86_64/lib/libyuv.a b/third_party/libyuv/x86_64/lib/libyuv.a deleted file mode 100644 index 8915f167dcf326..00000000000000 --- a/third_party/libyuv/x86_64/lib/libyuv.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e21a3bd8df01cf4ce5461e7bf6654239196036c3f829255145265c7bf31a791d -size 511974 diff --git a/third_party/linux/include/linux/ion.h b/third_party/linux/include/linux/ion.h deleted file mode 100644 index 7b5b031f57fa0e..00000000000000 --- a/third_party/linux/include/linux/ion.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** - **************************************************************************** - *** - *** This header was automatically generated from a Linux kernel header - *** of the same name, to make information necessary for userspace to - *** call into the kernel available to libc. It contains only constants, - *** structures, and macros generated from the original header, and thus, - *** contains no copyrightable information. - *** - *** To edit the content of this header, modify the corresponding - *** source file (e.g. under external/kernel-headers/original/) then - *** run bionic/libc/kernel/tools/update_all.py - *** - *** Any manual change here will be lost the next time this script will - *** be run. You've been warned! - *** - **************************************************************************** - ****************************************************************************/ -#ifndef _UAPI_LINUX_ION_H -#define _UAPI_LINUX_ION_H -#include -#include -typedef int ion_user_handle_t; -enum ion_heap_type { - ION_HEAP_TYPE_SYSTEM, - ION_HEAP_TYPE_SYSTEM_CONTIG, - ION_HEAP_TYPE_CARVEOUT, - ION_HEAP_TYPE_CHUNK, - ION_HEAP_TYPE_DMA, - ION_HEAP_TYPE_CUSTOM, -}; -#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8) -#define ION_FLAG_CACHED 1 -#define ION_FLAG_CACHED_NEEDS_SYNC 2 -struct ion_allocation_data { - size_t len; - size_t align; - unsigned int heap_id_mask; - unsigned int flags; - ion_user_handle_t handle; -}; -struct ion_fd_data { - ion_user_handle_t handle; - int fd; -}; -struct ion_handle_data { - ion_user_handle_t handle; -}; -struct ion_custom_data { - unsigned int cmd; - unsigned long arg; -}; -#define MAX_HEAP_NAME 32 -struct ion_heap_data { - char name[MAX_HEAP_NAME]; - __u32 type; - __u32 heap_id; - __u32 reserved0; - __u32 reserved1; - __u32 reserved2; -}; -struct ion_heap_query { - __u32 cnt; - __u32 reserved0; - __u64 heaps; - __u32 reserved1; - __u32 reserved2; -}; -#define ION_IOC_MAGIC 'I' -#define ION_IOC_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_allocation_data) -#define ION_IOC_FREE _IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data) -#define ION_IOC_MAP _IOWR(ION_IOC_MAGIC, 2, struct ion_fd_data) -#define ION_IOC_SHARE _IOWR(ION_IOC_MAGIC, 4, struct ion_fd_data) -#define ION_IOC_IMPORT _IOWR(ION_IOC_MAGIC, 5, struct ion_fd_data) -#define ION_IOC_SYNC _IOWR(ION_IOC_MAGIC, 7, struct ion_fd_data) -#define ION_IOC_CUSTOM _IOWR(ION_IOC_MAGIC, 6, struct ion_custom_data) -#define ION_IOC_HEAP_QUERY _IOWR(ION_IOC_MAGIC, 8, struct ion_heap_query) -#endif diff --git a/third_party/linux/include/media/cam_cpas.h b/third_party/linux/include/media/cam_cpas.h deleted file mode 100644 index c5cbac82e71b50..00000000000000 --- a/third_party/linux/include/media/cam_cpas.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef __UAPI_CAM_CPAS_H__ -#define __UAPI_CAM_CPAS_H__ - -#include "cam_defs.h" - -#define CAM_FAMILY_CAMERA_SS 1 -#define CAM_FAMILY_CPAS_SS 2 - -/** - * struct cam_cpas_query_cap - CPAS query device capability payload - * - * @camera_family : Camera family type - * @reserved : Reserved field for alignment - * @camera_version : Camera platform version - * @cpas_version : Camera CPAS version within camera platform - * - */ -struct cam_cpas_query_cap { - uint32_t camera_family; - uint32_t reserved; - struct cam_hw_version camera_version; - struct cam_hw_version cpas_version; -}; - -#endif /* __UAPI_CAM_CPAS_H__ */ diff --git a/third_party/linux/include/media/cam_defs.h b/third_party/linux/include/media/cam_defs.h deleted file mode 100644 index e006463d2aa6c3..00000000000000 --- a/third_party/linux/include/media/cam_defs.h +++ /dev/null @@ -1,477 +0,0 @@ -#ifndef __UAPI_CAM_DEFS_H__ -#define __UAPI_CAM_DEFS_H__ - -#include -#include -#include - - -/* camera op codes */ -#define CAM_COMMON_OPCODE_BASE 0x100 -#define CAM_QUERY_CAP (CAM_COMMON_OPCODE_BASE + 0x1) -#define CAM_ACQUIRE_DEV (CAM_COMMON_OPCODE_BASE + 0x2) -#define CAM_START_DEV (CAM_COMMON_OPCODE_BASE + 0x3) -#define CAM_STOP_DEV (CAM_COMMON_OPCODE_BASE + 0x4) -#define CAM_CONFIG_DEV (CAM_COMMON_OPCODE_BASE + 0x5) -#define CAM_RELEASE_DEV (CAM_COMMON_OPCODE_BASE + 0x6) -#define CAM_SD_SHUTDOWN (CAM_COMMON_OPCODE_BASE + 0x7) -#define CAM_FLUSH_REQ (CAM_COMMON_OPCODE_BASE + 0x8) -#define CAM_COMMON_OPCODE_MAX (CAM_COMMON_OPCODE_BASE + 0x9) - -#define CAM_EXT_OPCODE_BASE 0x200 -#define CAM_CONFIG_DEV_EXTERNAL (CAM_EXT_OPCODE_BASE + 0x1) - -/* camera handle type */ -#define CAM_HANDLE_USER_POINTER 1 -#define CAM_HANDLE_MEM_HANDLE 2 - -/* Generic Blob CmdBuffer header properties */ -#define CAM_GENERIC_BLOB_CMDBUFFER_SIZE_MASK 0xFFFFFF00 -#define CAM_GENERIC_BLOB_CMDBUFFER_SIZE_SHIFT 8 -#define CAM_GENERIC_BLOB_CMDBUFFER_TYPE_MASK 0xFF -#define CAM_GENERIC_BLOB_CMDBUFFER_TYPE_SHIFT 0 - -/* Command Buffer Types */ -#define CAM_CMD_BUF_DMI 0x1 -#define CAM_CMD_BUF_DMI16 0x2 -#define CAM_CMD_BUF_DMI32 0x3 -#define CAM_CMD_BUF_DMI64 0x4 -#define CAM_CMD_BUF_DIRECT 0x5 -#define CAM_CMD_BUF_INDIRECT 0x6 -#define CAM_CMD_BUF_I2C 0x7 -#define CAM_CMD_BUF_FW 0x8 -#define CAM_CMD_BUF_GENERIC 0x9 -#define CAM_CMD_BUF_LEGACY 0xA - -/** - * enum flush_type_t - Identifies the various flush types - * - * @CAM_FLUSH_TYPE_REQ: Flush specific request - * @CAM_FLUSH_TYPE_ALL: Flush all requests belonging to a context - * @CAM_FLUSH_TYPE_MAX: Max enum to validate flush type - * - */ -enum flush_type_t { - CAM_FLUSH_TYPE_REQ, - CAM_FLUSH_TYPE_ALL, - CAM_FLUSH_TYPE_MAX -}; - -/** - * struct cam_control - Structure used by ioctl control for camera - * - * @op_code: This is the op code for camera control - * @size: Control command size - * @handle_type: User pointer or shared memory handle - * @reserved: Reserved field for 64 bit alignment - * @handle: Control command payload - */ -struct cam_control { - uint32_t op_code; - uint32_t size; - uint32_t handle_type; - uint32_t reserved; - uint64_t handle; -}; - -/* camera IOCTL */ -#define VIDIOC_CAM_CONTROL \ - _IOWR('V', BASE_VIDIOC_PRIVATE, struct cam_control) - -/** - * struct cam_hw_version - Structure for HW version of camera devices - * - * @major : Hardware version major - * @minor : Hardware version minor - * @incr : Hardware version increment - * @reserved : Reserved for 64 bit aligngment - */ -struct cam_hw_version { - uint32_t major; - uint32_t minor; - uint32_t incr; - uint32_t reserved; -}; - -/** - * struct cam_iommu_handle - Structure for IOMMU handles of camera hw devices - * - * @non_secure: Device Non Secure IOMMU handle - * @secure: Device Secure IOMMU handle - * - */ -struct cam_iommu_handle { - int32_t non_secure; - int32_t secure; -}; - -/* camera secure mode */ -#define CAM_SECURE_MODE_NON_SECURE 0 -#define CAM_SECURE_MODE_SECURE 1 - -/* Camera Format Type */ -#define CAM_FORMAT_BASE 0 -#define CAM_FORMAT_MIPI_RAW_6 1 -#define CAM_FORMAT_MIPI_RAW_8 2 -#define CAM_FORMAT_MIPI_RAW_10 3 -#define CAM_FORMAT_MIPI_RAW_12 4 -#define CAM_FORMAT_MIPI_RAW_14 5 -#define CAM_FORMAT_MIPI_RAW_16 6 -#define CAM_FORMAT_MIPI_RAW_20 7 -#define CAM_FORMAT_QTI_RAW_8 8 -#define CAM_FORMAT_QTI_RAW_10 9 -#define CAM_FORMAT_QTI_RAW_12 10 -#define CAM_FORMAT_QTI_RAW_14 11 -#define CAM_FORMAT_PLAIN8 12 -#define CAM_FORMAT_PLAIN16_8 13 -#define CAM_FORMAT_PLAIN16_10 14 -#define CAM_FORMAT_PLAIN16_12 15 -#define CAM_FORMAT_PLAIN16_14 16 -#define CAM_FORMAT_PLAIN16_16 17 -#define CAM_FORMAT_PLAIN32_20 18 -#define CAM_FORMAT_PLAIN64 19 -#define CAM_FORMAT_PLAIN128 20 -#define CAM_FORMAT_ARGB 21 -#define CAM_FORMAT_ARGB_10 22 -#define CAM_FORMAT_ARGB_12 23 -#define CAM_FORMAT_ARGB_14 24 -#define CAM_FORMAT_DPCM_10_6_10 25 -#define CAM_FORMAT_DPCM_10_8_10 26 -#define CAM_FORMAT_DPCM_12_6_12 27 -#define CAM_FORMAT_DPCM_12_8_12 28 -#define CAM_FORMAT_DPCM_14_8_14 29 -#define CAM_FORMAT_DPCM_14_10_14 30 -#define CAM_FORMAT_NV21 31 -#define CAM_FORMAT_NV12 32 -#define CAM_FORMAT_TP10 33 -#define CAM_FORMAT_YUV422 34 -#define CAM_FORMAT_PD8 35 -#define CAM_FORMAT_PD10 36 -#define CAM_FORMAT_UBWC_NV12 37 -#define CAM_FORMAT_UBWC_NV12_4R 38 -#define CAM_FORMAT_UBWC_TP10 39 -#define CAM_FORMAT_UBWC_P010 40 -#define CAM_FORMAT_PLAIN8_SWAP 41 -#define CAM_FORMAT_PLAIN8_10 42 -#define CAM_FORMAT_PLAIN8_10_SWAP 43 -#define CAM_FORMAT_YV12 44 -#define CAM_FORMAT_Y_ONLY 45 -#define CAM_FORMAT_MAX 46 - -/* camera rotaion */ -#define CAM_ROTATE_CW_0_DEGREE 0 -#define CAM_ROTATE_CW_90_DEGREE 1 -#define CAM_RORATE_CW_180_DEGREE 2 -#define CAM_ROTATE_CW_270_DEGREE 3 - -/* camera Color Space */ -#define CAM_COLOR_SPACE_BASE 0 -#define CAM_COLOR_SPACE_BT601_FULL 1 -#define CAM_COLOR_SPACE_BT601625 2 -#define CAM_COLOR_SPACE_BT601525 3 -#define CAM_COLOR_SPACE_BT709 4 -#define CAM_COLOR_SPACE_DEPTH 5 -#define CAM_COLOR_SPACE_MAX 6 - -/* camera buffer direction */ -#define CAM_BUF_INPUT 1 -#define CAM_BUF_OUTPUT 2 -#define CAM_BUF_IN_OUT 3 - -/* camera packet device Type */ -#define CAM_PACKET_DEV_BASE 0 -#define CAM_PACKET_DEV_IMG_SENSOR 1 -#define CAM_PACKET_DEV_ACTUATOR 2 -#define CAM_PACKET_DEV_COMPANION 3 -#define CAM_PACKET_DEV_EEPOM 4 -#define CAM_PACKET_DEV_CSIPHY 5 -#define CAM_PACKET_DEV_OIS 6 -#define CAM_PACKET_DEV_FLASH 7 -#define CAM_PACKET_DEV_FD 8 -#define CAM_PACKET_DEV_JPEG_ENC 9 -#define CAM_PACKET_DEV_JPEG_DEC 10 -#define CAM_PACKET_DEV_VFE 11 -#define CAM_PACKET_DEV_CPP 12 -#define CAM_PACKET_DEV_CSID 13 -#define CAM_PACKET_DEV_ISPIF 14 -#define CAM_PACKET_DEV_IFE 15 -#define CAM_PACKET_DEV_ICP 16 -#define CAM_PACKET_DEV_LRME 17 -#define CAM_PACKET_DEV_MAX 18 - - -/* constants */ -#define CAM_PACKET_MAX_PLANES 3 - -/** - * struct cam_plane_cfg - Plane configuration info - * - * @width: Plane width in pixels - * @height: Plane height in lines - * @plane_stride: Plane stride in pixel - * @slice_height: Slice height in line (not used by ISP) - * @meta_stride: UBWC metadata stride - * @meta_size: UBWC metadata plane size - * @meta_offset: UBWC metadata offset - * @packer_config: UBWC packer config - * @mode_config: UBWC mode config - * @tile_config: UBWC tile config - * @h_init: UBWC horizontal initial coordinate in pixels - * @v_init: UBWC vertical initial coordinate in lines - * - */ -struct cam_plane_cfg { - uint32_t width; - uint32_t height; - uint32_t plane_stride; - uint32_t slice_height; - uint32_t meta_stride; - uint32_t meta_size; - uint32_t meta_offset; - uint32_t packer_config; - uint32_t mode_config; - uint32_t tile_config; - uint32_t h_init; - uint32_t v_init; -}; - -/** - * struct cam_cmd_buf_desc - Command buffer descriptor - * - * @mem_handle: Command buffer handle - * @offset: Command start offset - * @size: Size of the command buffer in bytes - * @length: Used memory in command buffer in bytes - * @type: Type of the command buffer - * @meta_data: Data type for private command buffer - * Between UMD and KMD - * - */ -struct cam_cmd_buf_desc { - int32_t mem_handle; - uint32_t offset; - uint32_t size; - uint32_t length; - uint32_t type; - uint32_t meta_data; -}; - -/** - * struct cam_buf_io_cfg - Buffer io configuration for buffers - * - * @mem_handle: Mem_handle array for the buffers. - * @offsets: Offsets for each planes in the buffer - * @planes: Per plane information - * @width: Main plane width in pixel - * @height: Main plane height in lines - * @format: Format of the buffer - * @color_space: Color space for the buffer - * @color_pattern: Color pattern in the buffer - * @bpp: Bit per pixel - * @rotation: Rotation information for the buffer - * @resource_type: Resource type associated with the buffer - * @fence: Fence handle - * @early_fence: Fence handle for early signal - * @aux_cmd_buf: An auxiliary command buffer that may be - * used for programming the IO - * @direction: Direction of the config - * @batch_size: Batch size in HFR mode - * @subsample_pattern: Subsample pattern. Used in HFR mode. It - * should be consistent with batchSize and - * CAMIF programming. - * @subsample_period: Subsample period. Used in HFR mode. It - * should be consistent with batchSize and - * CAMIF programming. - * @framedrop_pattern: Framedrop pattern - * @framedrop_period: Framedrop period - * @flag: Flags for extra information - * @direction: Buffer direction: input or output - * @padding: Padding for the structure - * - */ -struct cam_buf_io_cfg { - int32_t mem_handle[CAM_PACKET_MAX_PLANES]; - uint32_t offsets[CAM_PACKET_MAX_PLANES]; - struct cam_plane_cfg planes[CAM_PACKET_MAX_PLANES]; - uint32_t format; - uint32_t color_space; - uint32_t color_pattern; - uint32_t bpp; - uint32_t rotation; - uint32_t resource_type; - int32_t fence; - int32_t early_fence; - struct cam_cmd_buf_desc aux_cmd_buf; - uint32_t direction; - uint32_t batch_size; - uint32_t subsample_pattern; - uint32_t subsample_period; - uint32_t framedrop_pattern; - uint32_t framedrop_period; - uint32_t flag; - uint32_t padding; -}; - -/** - * struct cam_packet_header - Camera packet header - * - * @op_code: Camera packet opcode - * @size: Size of the camera packet in bytes - * @request_id: Request id for this camera packet - * @flags: Flags for the camera packet - * @padding: Padding - * - */ -struct cam_packet_header { - uint32_t op_code; - uint32_t size; - uint64_t request_id; - uint32_t flags; - uint32_t padding; -}; - -/** - * struct cam_patch_desc - Patch structure - * - * @dst_buf_hdl: Memory handle for the dest buffer - * @dst_offset: Offset byte in the dest buffer - * @src_buf_hdl: Memory handle for the source buffer - * @src_offset: Offset byte in the source buffer - * - */ -struct cam_patch_desc { - int32_t dst_buf_hdl; - uint32_t dst_offset; - int32_t src_buf_hdl; - uint32_t src_offset; -}; - -/** - * struct cam_packet - Camera packet structure - * - * @header: Camera packet header - * @cmd_buf_offset: Command buffer start offset - * @num_cmd_buf: Number of the command buffer in the packet - * @io_config_offset: Buffer io configuration start offset - * @num_io_configs: Number of the buffer io configurations - * @patch_offset: Patch offset for the patch structure - * @num_patches: Number of the patch structure - * @kmd_cmd_buf_index: Command buffer index which contains extra - * space for the KMD buffer - * @kmd_cmd_buf_offset: Offset from the beginning of the command - * buffer for KMD usage. - * @payload: Camera packet payload - * - */ -struct cam_packet { - struct cam_packet_header header; - uint32_t cmd_buf_offset; - uint32_t num_cmd_buf; - uint32_t io_configs_offset; - uint32_t num_io_configs; - uint32_t patch_offset; - uint32_t num_patches; - uint32_t kmd_cmd_buf_index; - uint32_t kmd_cmd_buf_offset; - uint64_t payload[1]; - -}; - -/** - * struct cam_release_dev_cmd - Control payload for release devices - * - * @session_handle: Session handle for the release - * @dev_handle: Device handle for the release - */ -struct cam_release_dev_cmd { - int32_t session_handle; - int32_t dev_handle; -}; - -/** - * struct cam_start_stop_dev_cmd - Control payload for start/stop device - * - * @session_handle: Session handle for the start/stop command - * @dev_handle: Device handle for the start/stop command - * - */ -struct cam_start_stop_dev_cmd { - int32_t session_handle; - int32_t dev_handle; -}; - -/** - * struct cam_config_dev_cmd - Command payload for configure device - * - * @session_handle: Session handle for the command - * @dev_handle: Device handle for the command - * @offset: Offset byte in the packet handle. - * @packet_handle: Packet memory handle for the actual packet: - * struct cam_packet. - * - */ -struct cam_config_dev_cmd { - int32_t session_handle; - int32_t dev_handle; - uint64_t offset; - uint64_t packet_handle; -}; - -/** - * struct cam_query_cap_cmd - Payload for query device capability - * - * @size: Handle size - * @handle_type: User pointer or shared memory handle - * @caps_handle: Device specific query command payload - * - */ -struct cam_query_cap_cmd { - uint32_t size; - uint32_t handle_type; - uint64_t caps_handle; -}; - -/** - * struct cam_acquire_dev_cmd - Control payload for acquire devices - * - * @session_handle: Session handle for the acquire command - * @dev_handle: Device handle to be returned - * @handle_type: Resource handle type: - * 1 = user pointer, 2 = mem handle - * @num_resources: Number of the resources to be acquired - * @resources_hdl: Resource handle that refers to the actual - * resource array. Each item in this - * array is device specific resource structure - * - */ -struct cam_acquire_dev_cmd { - int32_t session_handle; - int32_t dev_handle; - uint32_t handle_type; - uint32_t num_resources; - uint64_t resource_hdl; -}; - -/** - * struct cam_flush_dev_cmd - Control payload for flush devices - * - * @version: Version - * @session_handle: Session handle for the acquire command - * @dev_handle: Device handle to be returned - * @flush_type: Flush type: - * 0 = flush specific request - * 1 = flush all - * @reserved: Reserved for 64 bit aligngment - * @req_id: Request id that needs to cancel - * - */ -struct cam_flush_dev_cmd { - uint64_t version; - int32_t session_handle; - int32_t dev_handle; - uint32_t flush_type; - uint32_t reserved; - int64_t req_id; -}; - -#endif /* __UAPI_CAM_DEFS_H__ */ diff --git a/third_party/linux/include/media/cam_fd.h b/third_party/linux/include/media/cam_fd.h deleted file mode 100644 index 8feb6e4da89a79..00000000000000 --- a/third_party/linux/include/media/cam_fd.h +++ /dev/null @@ -1,127 +0,0 @@ -#ifndef __UAPI_CAM_FD_H__ -#define __UAPI_CAM_FD_H__ - -#include "cam_defs.h" - -#define CAM_FD_MAX_FACES 35 -#define CAM_FD_RAW_RESULT_ENTRIES 512 - -/* FD Op Codes */ -#define CAM_PACKET_OPCODES_FD_FRAME_UPDATE 0x0 - -/* FD Command Buffer identifiers */ -#define CAM_FD_CMD_BUFFER_ID_GENERIC 0x0 -#define CAM_FD_CMD_BUFFER_ID_CDM 0x1 -#define CAM_FD_CMD_BUFFER_ID_MAX 0x2 - -/* FD Blob types */ -#define CAM_FD_BLOB_TYPE_SOC_CLOCK_BW_REQUEST 0x0 -#define CAM_FD_BLOB_TYPE_RAW_RESULTS_REQUIRED 0x1 - -/* FD Resource IDs */ -#define CAM_FD_INPUT_PORT_ID_IMAGE 0x0 -#define CAM_FD_INPUT_PORT_ID_MAX 0x1 - -#define CAM_FD_OUTPUT_PORT_ID_RESULTS 0x0 -#define CAM_FD_OUTPUT_PORT_ID_RAW_RESULTS 0x1 -#define CAM_FD_OUTPUT_PORT_ID_WORK_BUFFER 0x2 -#define CAM_FD_OUTPUT_PORT_ID_MAX 0x3 - -/** - * struct cam_fd_soc_clock_bw_request - SOC clock, bandwidth request info - * - * @clock_rate : Clock rate required while processing frame - * @bandwidth : Bandwidth required while processing frame - * @reserved : Reserved for future use - */ -struct cam_fd_soc_clock_bw_request { - uint64_t clock_rate; - uint64_t bandwidth; - uint64_t reserved[4]; -}; - -/** - * struct cam_fd_face - Face properties - * - * @prop1 : Property 1 of face - * @prop2 : Property 2 of face - * @prop3 : Property 3 of face - * @prop4 : Property 4 of face - * - * Do not change this layout, this is inline with how HW writes - * these values directly when the buffer is programmed to HW - */ -struct cam_fd_face { - uint32_t prop1; - uint32_t prop2; - uint32_t prop3; - uint32_t prop4; -}; - -/** - * struct cam_fd_results - FD results layout - * - * @faces : Array of faces with face properties - * @face_count : Number of faces detected - * @reserved : Reserved for alignment - * - * Do not change this layout, this is inline with how HW writes - * these values directly when the buffer is programmed to HW - */ -struct cam_fd_results { - struct cam_fd_face faces[CAM_FD_MAX_FACES]; - uint32_t face_count; - uint32_t reserved[3]; -}; - -/** - * struct cam_fd_hw_caps - Face properties - * - * @core_version : FD core version - * @wrapper_version : FD wrapper version - * @raw_results_available : Whether raw results are available on this HW - * @supported_modes : Modes supported by this HW. - * @reserved : Reserved for future use - */ -struct cam_fd_hw_caps { - struct cam_hw_version core_version; - struct cam_hw_version wrapper_version; - uint32_t raw_results_available; - uint32_t supported_modes; - uint64_t reserved; -}; - -/** - * struct cam_fd_query_cap_cmd - FD Query capabilities information - * - * @device_iommu : FD IOMMU handles - * @cdm_iommu : CDM iommu handles - * @hw_caps : FD HW capabilities - * @reserved : Reserved for alignment - */ -struct cam_fd_query_cap_cmd { - struct cam_iommu_handle device_iommu; - struct cam_iommu_handle cdm_iommu; - struct cam_fd_hw_caps hw_caps; - uint64_t reserved; -}; - -/** - * struct cam_fd_acquire_dev_info - FD acquire device information - * - * @clk_bw_request : SOC clock, bandwidth request - * @priority : Priority for this acquire - * @mode : Mode in which to run FD HW. - * @get_raw_results : Whether this acquire needs face raw results - * while frame processing - * @reserved : Reserved field for 64 bit alignment - */ -struct cam_fd_acquire_dev_info { - struct cam_fd_soc_clock_bw_request clk_bw_request; - uint32_t priority; - uint32_t mode; - uint32_t get_raw_results; - uint32_t reserved[13]; -}; - -#endif /* __UAPI_CAM_FD_H__ */ diff --git a/third_party/linux/include/media/cam_icp.h b/third_party/linux/include/media/cam_icp.h deleted file mode 100644 index 680d05b630a67e..00000000000000 --- a/third_party/linux/include/media/cam_icp.h +++ /dev/null @@ -1,179 +0,0 @@ -#ifndef __UAPI_CAM_ICP_H__ -#define __UAPI_CAM_ICP_H__ - -#include "cam_defs.h" - -/* icp, ipe, bps, cdm(ipe/bps) are used in querycap */ -#define CAM_ICP_DEV_TYPE_A5 1 -#define CAM_ICP_DEV_TYPE_IPE 2 -#define CAM_ICP_DEV_TYPE_BPS 3 -#define CAM_ICP_DEV_TYPE_IPE_CDM 4 -#define CAM_ICP_DEV_TYPE_BPS_CDM 5 -#define CAM_ICP_DEV_TYPE_MAX 5 - -/* definitions needed for icp aquire device */ -#define CAM_ICP_RES_TYPE_BPS 1 -#define CAM_ICP_RES_TYPE_IPE_RT 2 -#define CAM_ICP_RES_TYPE_IPE 3 -#define CAM_ICP_RES_TYPE_MAX 4 - -/* packet opcode types */ -#define CAM_ICP_OPCODE_IPE_UPDATE 0 -#define CAM_ICP_OPCODE_BPS_UPDATE 1 - -/* IPE input port resource type */ -#define CAM_ICP_IPE_INPUT_IMAGE_FULL 0x0 -#define CAM_ICP_IPE_INPUT_IMAGE_DS4 0x1 -#define CAM_ICP_IPE_INPUT_IMAGE_DS16 0x2 -#define CAM_ICP_IPE_INPUT_IMAGE_DS64 0x3 -#define CAM_ICP_IPE_INPUT_IMAGE_FULL_REF 0x4 -#define CAM_ICP_IPE_INPUT_IMAGE_DS4_REF 0x5 -#define CAM_ICP_IPE_INPUT_IMAGE_DS16_REF 0x6 -#define CAM_ICP_IPE_INPUT_IMAGE_DS64_REF 0x7 - -/* IPE output port resource type */ -#define CAM_ICP_IPE_OUTPUT_IMAGE_DISPLAY 0x8 -#define CAM_ICP_IPE_OUTPUT_IMAGE_VIDEO 0x9 -#define CAM_ICP_IPE_OUTPUT_IMAGE_FULL_REF 0xA -#define CAM_ICP_IPE_OUTPUT_IMAGE_DS4_REF 0xB -#define CAM_ICP_IPE_OUTPUT_IMAGE_DS16_REF 0xC -#define CAM_ICP_IPE_OUTPUT_IMAGE_DS64_REF 0xD - -#define CAM_ICP_IPE_IMAGE_MAX 0xE - -/* BPS input port resource type */ -#define CAM_ICP_BPS_INPUT_IMAGE 0x0 - -/* BPS output port resource type */ -#define CAM_ICP_BPS_OUTPUT_IMAGE_FULL 0x1 -#define CAM_ICP_BPS_OUTPUT_IMAGE_DS4 0x2 -#define CAM_ICP_BPS_OUTPUT_IMAGE_DS16 0x3 -#define CAM_ICP_BPS_OUTPUT_IMAGE_DS64 0x4 -#define CAM_ICP_BPS_OUTPUT_IMAGE_STATS_BG 0x5 -#define CAM_ICP_BPS_OUTPUT_IMAGE_STATS_BHIST 0x6 -#define CAM_ICP_BPS_OUTPUT_IMAGE_REG1 0x7 -#define CAM_ICP_BPS_OUTPUT_IMAGE_REG2 0x8 - -#define CAM_ICP_BPS_IO_IMAGES_MAX 0x9 - -/* Command meta types */ -#define CAM_ICP_CMD_META_GENERIC_BLOB 0x1 - -/* Generic blob types */ -#define CAM_ICP_CMD_GENERIC_BLOB_CLK 0x1 -#define CAM_ICP_CMD_GENERIC_BLOB_CFG_IO 0x2 - -/** - * struct cam_icp_clk_bw_request - * - * @budget_ns: Time required to process frame - * @frame_cycles: Frame cycles needed to process the frame - * @rt_flag: Flag to indicate real time stream - * @uncompressed_bw: Bandwidth required to process frame - * @compressed_bw: Compressed bandwidth to process frame - */ -struct cam_icp_clk_bw_request { - uint64_t budget_ns; - uint32_t frame_cycles; - uint32_t rt_flag; - uint64_t uncompressed_bw; - uint64_t compressed_bw; -}; - -/** - * struct cam_icp_dev_ver - Device information for particular hw type - * - * This is used to get device version info of - * ICP, IPE, BPS and CDM related IPE and BPS from firmware - * and use this info in CAM_QUERY_CAP IOCTL - * - * @dev_type: hardware type for the cap info(icp, ipe, bps, cdm(ipe/bps)) - * @reserved: reserved field - * @hw_ver: major, minor and incr values of a device version - */ -struct cam_icp_dev_ver { - uint32_t dev_type; - uint32_t reserved; - struct cam_hw_version hw_ver; -}; - -/** - * struct cam_icp_ver - ICP version info - * - * This strcuture is used for fw and api version - * this is used to get firmware version and api version from firmware - * and use this info in CAM_QUERY_CAP IOCTL - * - * @major: FW version major - * @minor: FW version minor - * @revision: FW version increment - */ -struct cam_icp_ver { - uint32_t major; - uint32_t minor; - uint32_t revision; - uint32_t reserved; -}; - -/** - * struct cam_icp_query_cap_cmd - ICP query device capability payload - * - * @dev_iommu_handle: icp iommu handles for secure/non secure modes - * @cdm_iommu_handle: iommu handles for secure/non secure modes - * @fw_version: firmware version info - * @api_version: api version info - * @num_ipe: number of ipes - * @num_bps: number of bps - * @dev_ver: returned device capability array - */ -struct cam_icp_query_cap_cmd { - struct cam_iommu_handle dev_iommu_handle; - struct cam_iommu_handle cdm_iommu_handle; - struct cam_icp_ver fw_version; - struct cam_icp_ver api_version; - uint32_t num_ipe; - uint32_t num_bps; - struct cam_icp_dev_ver dev_ver[CAM_ICP_DEV_TYPE_MAX]; -}; - -/** - * struct cam_icp_res_info - ICP output resource info - * - * @format: format of the resource - * @width: width in pixels - * @height: height in lines - * @fps: fps - */ -struct cam_icp_res_info { - uint32_t format; - uint32_t width; - uint32_t height; - uint32_t fps; -}; - -/** - * struct cam_icp_acquire_dev_info - An ICP device info - * - * @scratch_mem_size: Output param - size of scratch memory - * @dev_type: device type (IPE_RT/IPE_NON_RT/BPS) - * @io_config_cmd_size: size of IO config command - * @io_config_cmd_handle: IO config command for each acquire - * @secure_mode: camera mode (secure/non secure) - * @chain_info: chaining info of FW device handles - * @in_res: resource info used for clock and bandwidth calculation - * @num_out_res: number of output resources - * @out_res: output resource - */ -struct cam_icp_acquire_dev_info { - uint32_t scratch_mem_size; - uint32_t dev_type; - uint32_t io_config_cmd_size; - int32_t io_config_cmd_handle; - uint32_t secure_mode; - int32_t chain_info; - struct cam_icp_res_info in_res; - uint32_t num_out_res; - struct cam_icp_res_info out_res[1]; -} __attribute__((__packed__)); - -#endif /* __UAPI_CAM_ICP_H__ */ diff --git a/third_party/linux/include/media/cam_isp.h b/third_party/linux/include/media/cam_isp.h deleted file mode 100644 index 266840d38c2547..00000000000000 --- a/third_party/linux/include/media/cam_isp.h +++ /dev/null @@ -1,379 +0,0 @@ -#ifndef __UAPI_CAM_ISP_H__ -#define __UAPI_CAM_ISP_H__ - -#include "cam_defs.h" -#include "cam_isp_vfe.h" -#include "cam_isp_ife.h" - - -/* ISP driver name */ -#define CAM_ISP_DEV_NAME "cam-isp" - -/* HW type */ -#define CAM_ISP_HW_BASE 0 -#define CAM_ISP_HW_CSID 1 -#define CAM_ISP_HW_VFE 2 -#define CAM_ISP_HW_IFE 3 -#define CAM_ISP_HW_ISPIF 4 -#define CAM_ISP_HW_MAX 5 - -/* Color Pattern */ -#define CAM_ISP_PATTERN_BAYER_RGRGRG 0 -#define CAM_ISP_PATTERN_BAYER_GRGRGR 1 -#define CAM_ISP_PATTERN_BAYER_BGBGBG 2 -#define CAM_ISP_PATTERN_BAYER_GBGBGB 3 -#define CAM_ISP_PATTERN_YUV_YCBYCR 4 -#define CAM_ISP_PATTERN_YUV_YCRYCB 5 -#define CAM_ISP_PATTERN_YUV_CBYCRY 6 -#define CAM_ISP_PATTERN_YUV_CRYCBY 7 -#define CAM_ISP_PATTERN_MAX 8 - -/* Usage Type */ -#define CAM_ISP_RES_USAGE_SINGLE 0 -#define CAM_ISP_RES_USAGE_DUAL 1 -#define CAM_ISP_RES_USAGE_MAX 2 - -/* Resource ID */ -#define CAM_ISP_RES_ID_PORT 0 -#define CAM_ISP_RES_ID_CLK 1 -#define CAM_ISP_RES_ID_MAX 2 - -/* Resource Type - Type of resource for the resource id - * defined in cam_isp_vfe.h, cam_isp_ife.h - */ - -/* Lane Type in input resource for Port */ -#define CAM_ISP_LANE_TYPE_DPHY 0 -#define CAM_ISP_LANE_TYPE_CPHY 1 -#define CAM_ISP_LANE_TYPE_MAX 2 - -/* ISP Resurce Composite Group ID */ -#define CAM_ISP_RES_COMP_GROUP_NONE 0 -#define CAM_ISP_RES_COMP_GROUP_ID_0 1 -#define CAM_ISP_RES_COMP_GROUP_ID_1 2 -#define CAM_ISP_RES_COMP_GROUP_ID_2 3 -#define CAM_ISP_RES_COMP_GROUP_ID_3 4 -#define CAM_ISP_RES_COMP_GROUP_ID_4 5 -#define CAM_ISP_RES_COMP_GROUP_ID_5 6 -#define CAM_ISP_RES_COMP_GROUP_ID_MAX 6 - -/* ISP packet opcode for ISP */ -#define CAM_ISP_PACKET_OP_BASE 0 -#define CAM_ISP_PACKET_INIT_DEV 1 -#define CAM_ISP_PACKET_UPDATE_DEV 2 -#define CAM_ISP_PACKET_OP_MAX 3 - -/* ISP packet meta_data type for command buffer */ -#define CAM_ISP_PACKET_META_BASE 0 -#define CAM_ISP_PACKET_META_LEFT 1 -#define CAM_ISP_PACKET_META_RIGHT 2 -#define CAM_ISP_PACKET_META_COMMON 3 -#define CAM_ISP_PACKET_META_DMI_LEFT 4 -#define CAM_ISP_PACKET_META_DMI_RIGHT 5 -#define CAM_ISP_PACKET_META_DMI_COMMON 6 -#define CAM_ISP_PACKET_META_CLOCK 7 -#define CAM_ISP_PACKET_META_CSID 8 -#define CAM_ISP_PACKET_META_DUAL_CONFIG 9 -#define CAM_ISP_PACKET_META_GENERIC_BLOB_LEFT 10 -#define CAM_ISP_PACKET_META_GENERIC_BLOB_RIGHT 11 -#define CAM_ISP_PACKET_META_GENERIC_BLOB_COMMON 12 - -/* DSP mode */ -#define CAM_ISP_DSP_MODE_NONE 0 -#define CAM_ISP_DSP_MODE_ONE_WAY 1 -#define CAM_ISP_DSP_MODE_ROUND 2 - -/* ISP Generic Cmd Buffer Blob types */ -#define CAM_ISP_GENERIC_BLOB_TYPE_HFR_CONFIG 0 -#define CAM_ISP_GENERIC_BLOB_TYPE_CLOCK_CONFIG 1 -#define CAM_ISP_GENERIC_BLOB_TYPE_BW_CONFIG 2 - -/* Query devices */ -/** - * struct cam_isp_dev_cap_info - A cap info for particular hw type - * - * @hw_type: Hardware type for the cap info - * @reserved: reserved field for alignment - * @hw_version: Hardware version - * - */ -struct cam_isp_dev_cap_info { - uint32_t hw_type; - uint32_t reserved; - struct cam_hw_version hw_version; -}; - -/** - * struct cam_isp_query_cap_cmd - ISP query device capability payload - * - * @device_iommu: returned iommu handles for device - * @cdm_iommu: returned iommu handles for cdm - * @num_dev: returned number of device capabilities - * @reserved: reserved field for alignment - * @dev_caps: returned device capability array - * - */ -struct cam_isp_query_cap_cmd { - struct cam_iommu_handle device_iommu; - struct cam_iommu_handle cdm_iommu; - int32_t num_dev; - uint32_t reserved; - struct cam_isp_dev_cap_info dev_caps[CAM_ISP_HW_MAX]; -}; - -/* Acquire Device */ -/** - * struct cam_isp_out_port_info - An output port resource info - * - * @res_type: output resource type defined in file - * cam_isp_vfe.h or cam_isp_ife.h - * @format: output format of the resource - * @wdith: output width in pixels - * @height: output height in lines - * @comp_grp_id: composite group id for the resource. - * @split_point: split point in pixels for the dual VFE. - * @secure_mode: flag to tell if output should be run in secure - * mode or not. See cam_defs.h for definition - * @reserved: reserved field for alignment - * - */ -struct cam_isp_out_port_info { - uint32_t res_type; - uint32_t format; - uint32_t width; - uint32_t height; - uint32_t comp_grp_id; - uint32_t split_point; - uint32_t secure_mode; - uint32_t reserved; -}; - -/** - * struct cam_isp_in_port_info - An input port resource info - * - * @res_type: input resource type define in file - * cam_isp_vfe.h or cam_isp_ife.h - * @lane_type: lane type: c-phy or d-phy. - * @lane_num: active lane number - * @lane_cfg: lane configurations: 4 bits per lane - * @vc: input virtual channel number - * @dt: input data type number - * @format: input format - * @test_pattern: test pattern for the testgen - * @usage_type: whether dual vfe is required - * @left_start: left input start offset in pixels - * @left_stop: left input stop offset in pixels - * @left_width: left input width in pixels - * @right_start: right input start offset in pixels. - * Only for Dual VFE - * @right_stop: right input stop offset in pixels. - * Only for Dual VFE - * @right_width: right input width in pixels. - * Only for dual VFE - * @line_start: top of the line number - * @line_stop: bottome of the line number - * @height: input height in lines - * @pixel_clk; sensor output clock - * @batch_size: batch size for HFR mode - * @dsp_mode: DSP stream mode (Defines as CAM_ISP_DSP_MODE_*) - * @hbi_cnt: HBI count for the camif input - * @reserved: Reserved field for alignment - * @num_out_res: number of the output resource associated - * @data: payload that contains the output resources - * - */ -struct cam_isp_in_port_info { - uint32_t res_type; - uint32_t lane_type; - uint32_t lane_num; - uint32_t lane_cfg; - uint32_t vc; - uint32_t dt; - uint32_t format; - uint32_t test_pattern; - uint32_t usage_type; - uint32_t left_start; - uint32_t left_stop; - uint32_t left_width; - uint32_t right_start; - uint32_t right_stop; - uint32_t right_width; - uint32_t line_start; - uint32_t line_stop; - uint32_t height; - uint32_t pixel_clk; - uint32_t batch_size; - uint32_t dsp_mode; - uint32_t hbi_cnt; - uint32_t custom_csid; - uint32_t reserved; - uint32_t num_out_res; - struct cam_isp_out_port_info data[1]; -}; - -/** - * struct cam_isp_resource - A resource bundle - * - * @resoruce_id: resource id for the resource bundle - * @length: length of the while resource blob - * @handle_type: type of the resource handle - * @reserved: reserved field for alignment - * @res_hdl: resource handle that points to the - * resource array; - * - */ -struct cam_isp_resource { - uint32_t resource_id; - uint32_t length; - uint32_t handle_type; - uint32_t reserved; - uint64_t res_hdl; -}; - -/** - * struct cam_isp_port_hfr_config - HFR configuration for this port - * - * @resource_type: Resource type - * @subsample_pattern: Subsample pattern. Used in HFR mode. It - * should be consistent with batchSize and - * CAMIF programming. - * @subsample_period: Subsample period. Used in HFR mode. It - * should be consistent with batchSize and - * CAMIF programming. - * @framedrop_pattern: Framedrop pattern - * @framedrop_period: Framedrop period - * @reserved: Reserved for alignment - */ -struct cam_isp_port_hfr_config { - uint32_t resource_type; - uint32_t subsample_pattern; - uint32_t subsample_period; - uint32_t framedrop_pattern; - uint32_t framedrop_period; - uint32_t reserved; -} __attribute__((packed)); - -/** - * struct cam_isp_resource_hfr_config - Resource HFR configuration - * - * @num_ports: Number of ports - * @reserved: Reserved for alignment - * @port_hfr_config: HFR configuration for each IO port - */ -struct cam_isp_resource_hfr_config { - uint32_t num_ports; - uint32_t reserved; - struct cam_isp_port_hfr_config port_hfr_config[1]; -} __attribute__((packed)); - -/** - * struct cam_isp_dual_split_params - dual isp spilt parameters - * - * @split_point: Split point information x, where (0 < x < width) - * left ISP's input ends at x + righ padding and - * Right ISP's input starts at x - left padding - * @right_padding: Padding added past the split point for left - * ISP's input - * @left_padding: Padding added before split point for right - * ISP's input - * @reserved: Reserved filed for alignment - * - */ -struct cam_isp_dual_split_params { - uint32_t split_point; - uint32_t right_padding; - uint32_t left_padding; - uint32_t reserved; -}; - -/** - * struct cam_isp_dual_stripe_config - stripe config per bus client - * - * @offset: Start horizontal offset relative to - * output buffer - * In UBWC mode, this value indicates the H_INIT - * value in pixel - * @width: Width of the stripe in bytes - * @tileconfig Ubwc meta tile config. Contain the partial - * tile info - * @port_id: port id of ISP output - * - */ -struct cam_isp_dual_stripe_config { - uint32_t offset; - uint32_t width; - uint32_t tileconfig; - uint32_t port_id; -}; - -/** - * struct cam_isp_dual_config - dual isp configuration - * - * @num_ports Number of isp output ports - * @reserved Reserved field for alignment - * @split_params: Inpput split parameters - * @stripes: Stripe information - * - */ -struct cam_isp_dual_config { - uint32_t num_ports; - uint32_t reserved; - struct cam_isp_dual_split_params split_params; - struct cam_isp_dual_stripe_config stripes[1]; -} __attribute__((packed)); - -/** - * struct cam_isp_clock_config - Clock configuration - * - * @usage_type: Usage type (Single/Dual) - * @num_rdi: Number of RDI votes - * @left_pix_hz: Pixel Clock for Left ISP - * @right_pix_hz: Pixel Clock for Right ISP, valid only if Dual - * @rdi_hz: RDI Clock. ISP clock will be max of RDI and - * PIX clocks. For a particular context which ISP - * HW the RDI is allocated to is not known to UMD. - * Hence pass the clock and let KMD decide. - */ -struct cam_isp_clock_config { - uint32_t usage_type; - uint32_t num_rdi; - uint64_t left_pix_hz; - uint64_t right_pix_hz; - uint64_t rdi_hz[1]; -} __attribute__((packed)); - -/** - * struct cam_isp_bw_vote - Bandwidth vote information - * - * @resource_id: Resource ID - * @reserved: Reserved field for alignment - * @cam_bw_bps: Bandwidth vote for CAMNOC - * @ext_bw_bps: Bandwidth vote for path-to-DDR after CAMNOC - */ - -struct cam_isp_bw_vote { - uint32_t resource_id; - uint32_t reserved; - uint64_t cam_bw_bps; - uint64_t ext_bw_bps; -} __attribute__((packed)); - -/** - * struct cam_isp_bw_config - Bandwidth configuration - * - * @usage_type: Usage type (Single/Dual) - * @num_rdi: Number of RDI votes - * @left_pix_vote: Bandwidth vote for left ISP - * @right_pix_vote: Bandwidth vote for right ISP - * @rdi_vote: RDI bandwidth requirements - */ - -struct cam_isp_bw_config { - uint32_t usage_type; - uint32_t num_rdi; - struct cam_isp_bw_vote left_pix_vote; - struct cam_isp_bw_vote right_pix_vote; - struct cam_isp_bw_vote rdi_vote[1]; -} __attribute__((packed)); - -#endif /* __UAPI_CAM_ISP_H__ */ diff --git a/third_party/linux/include/media/cam_isp_ife.h b/third_party/linux/include/media/cam_isp_ife.h deleted file mode 100644 index f5e72813fc0d2d..00000000000000 --- a/third_party/linux/include/media/cam_isp_ife.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef __UAPI_CAM_ISP_IFE_H__ -#define __UAPI_CAM_ISP_IFE_H__ - -/* IFE output port resource type (global unique)*/ -#define CAM_ISP_IFE_OUT_RES_BASE 0x3000 - -#define CAM_ISP_IFE_OUT_RES_FULL (CAM_ISP_IFE_OUT_RES_BASE + 0) -#define CAM_ISP_IFE_OUT_RES_DS4 (CAM_ISP_IFE_OUT_RES_BASE + 1) -#define CAM_ISP_IFE_OUT_RES_DS16 (CAM_ISP_IFE_OUT_RES_BASE + 2) -#define CAM_ISP_IFE_OUT_RES_RAW_DUMP (CAM_ISP_IFE_OUT_RES_BASE + 3) -#define CAM_ISP_IFE_OUT_RES_FD (CAM_ISP_IFE_OUT_RES_BASE + 4) -#define CAM_ISP_IFE_OUT_RES_PDAF (CAM_ISP_IFE_OUT_RES_BASE + 5) -#define CAM_ISP_IFE_OUT_RES_RDI_0 (CAM_ISP_IFE_OUT_RES_BASE + 6) -#define CAM_ISP_IFE_OUT_RES_RDI_1 (CAM_ISP_IFE_OUT_RES_BASE + 7) -#define CAM_ISP_IFE_OUT_RES_RDI_2 (CAM_ISP_IFE_OUT_RES_BASE + 8) -#define CAM_ISP_IFE_OUT_RES_RDI_3 (CAM_ISP_IFE_OUT_RES_BASE + 9) -#define CAM_ISP_IFE_OUT_RES_STATS_HDR_BE (CAM_ISP_IFE_OUT_RES_BASE + 10) -#define CAM_ISP_IFE_OUT_RES_STATS_HDR_BHIST (CAM_ISP_IFE_OUT_RES_BASE + 11) -#define CAM_ISP_IFE_OUT_RES_STATS_TL_BG (CAM_ISP_IFE_OUT_RES_BASE + 12) -#define CAM_ISP_IFE_OUT_RES_STATS_BF (CAM_ISP_IFE_OUT_RES_BASE + 13) -#define CAM_ISP_IFE_OUT_RES_STATS_AWB_BG (CAM_ISP_IFE_OUT_RES_BASE + 14) -#define CAM_ISP_IFE_OUT_RES_STATS_BHIST (CAM_ISP_IFE_OUT_RES_BASE + 15) -#define CAM_ISP_IFE_OUT_RES_STATS_RS (CAM_ISP_IFE_OUT_RES_BASE + 16) -#define CAM_ISP_IFE_OUT_RES_STATS_CS (CAM_ISP_IFE_OUT_RES_BASE + 17) -#define CAM_ISP_IFE_OUT_RES_STATS_IHIST (CAM_ISP_IFE_OUT_RES_BASE + 18) -#define CAM_ISP_IFE_OUT_RES_MAX (CAM_ISP_IFE_OUT_RES_BASE + 19) - - -/* IFE input port resource type (global unique) */ -#define CAM_ISP_IFE_IN_RES_BASE 0x4000 - -#define CAM_ISP_IFE_IN_RES_TPG (CAM_ISP_IFE_IN_RES_BASE + 0) -#define CAM_ISP_IFE_IN_RES_PHY_0 (CAM_ISP_IFE_IN_RES_BASE + 1) -#define CAM_ISP_IFE_IN_RES_PHY_1 (CAM_ISP_IFE_IN_RES_BASE + 2) -#define CAM_ISP_IFE_IN_RES_PHY_2 (CAM_ISP_IFE_IN_RES_BASE + 3) -#define CAM_ISP_IFE_IN_RES_PHY_3 (CAM_ISP_IFE_IN_RES_BASE + 4) -#define CAM_ISP_IFE_IN_RES_MAX (CAM_ISP_IFE_IN_RES_BASE + 5) - -#endif /* __UAPI_CAM_ISP_IFE_H__ */ diff --git a/third_party/linux/include/media/cam_isp_vfe.h b/third_party/linux/include/media/cam_isp_vfe.h deleted file mode 100644 index e48db2f98d91c2..00000000000000 --- a/third_party/linux/include/media/cam_isp_vfe.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef __UAPI_CAM_ISP_VFE_H__ -#define __UAPI_CAM_ISP_VFE_H__ - -/* VFE output port resource type (global unique) */ -#define CAM_ISP_VFE_OUT_RES_BASE 0x1000 - -#define CAM_ISP_VFE_OUT_RES_ENC (CAM_ISP_VFE_OUT_RES_BASE + 0) -#define CAM_ISP_VFE_OUT_RES_VIEW (CAM_ISP_VFE_OUT_RES_BASE + 1) -#define CAM_ISP_VFE_OUT_RES_VID (CAM_ISP_VFE_OUT_RES_BASE + 2) -#define CAM_ISP_VFE_OUT_RES_RDI_0 (CAM_ISP_VFE_OUT_RES_BASE + 3) -#define CAM_ISP_VFE_OUT_RES_RDI_1 (CAM_ISP_VFE_OUT_RES_BASE + 4) -#define CAM_ISP_VFE_OUT_RES_RDI_2 (CAM_ISP_VFE_OUT_RES_BASE + 5) -#define CAM_ISP_VFE_OUT_RES_RDI_3 (CAM_ISP_VFE_OUT_RES_BASE + 6) -#define CAM_ISP_VFE_OUT_RES_STATS_AEC (CAM_ISP_VFE_OUT_RES_BASE + 7) -#define CAM_ISP_VFE_OUT_RES_STATS_AF (CAM_ISP_VFE_OUT_RES_BASE + 8) -#define CAM_ISP_VFE_OUT_RES_STATS_AWB (CAM_ISP_VFE_OUT_RES_BASE + 9) -#define CAM_ISP_VFE_OUT_RES_STATS_RS (CAM_ISP_VFE_OUT_RES_BASE + 10) -#define CAM_ISP_VFE_OUT_RES_STATS_CS (CAM_ISP_VFE_OUT_RES_BASE + 11) -#define CAM_ISP_VFE_OUT_RES_STATS_IHIST (CAM_ISP_VFE_OUT_RES_BASE + 12) -#define CAM_ISP_VFE_OUT_RES_STATS_SKIN (CAM_ISP_VFE_OUT_RES_BASE + 13) -#define CAM_ISP_VFE_OUT_RES_STATS_BG (CAM_ISP_VFE_OUT_RES_BASE + 14) -#define CAM_ISP_VFE_OUT_RES_STATS_BF (CAM_ISP_VFE_OUT_RES_BASE + 15) -#define CAM_ISP_VFE_OUT_RES_STATS_BE (CAM_ISP_VFE_OUT_RES_BASE + 16) -#define CAM_ISP_VFE_OUT_RES_STATS_BHIST (CAM_ISP_VFE_OUT_RES_BASE + 17) -#define CAM_ISP_VFE_OUT_RES_STATS_BF_SCALE (CAM_ISP_VFE_OUT_RES_BASE + 18) -#define CAM_ISP_VFE_OUT_RES_STATS_HDR_BE (CAM_ISP_VFE_OUT_RES_BASE + 19) -#define CAM_ISP_VFE_OUT_RES_STATS_HDR_BHIST (CAM_ISP_VFE_OUT_RES_BASE + 20) -#define CAM_ISP_VFE_OUT_RES_STATS_AEC_BG (CAM_ISP_VFE_OUT_RES_BASE + 21) -#define CAM_ISP_VFE_OUT_RES_CAMIF_RAW (CAM_ISP_VFE_OUT_RES_BASE + 22) -#define CAM_ISP_VFE_OUT_RES_IDEAL_RAW (CAM_ISP_VFE_OUT_RES_BASE + 23) -#define CAM_ISP_VFE_OUT_RES_MAX (CAM_ISP_VFE_OUT_RES_BASE + 24) - -/* VFE input port_ resource type (global unique) */ -#define CAM_ISP_VFE_IN_RES_BASE 0x2000 - -#define CAM_ISP_VFE_IN_RES_TPG (CAM_ISP_VFE_IN_RES_BASE + 0) -#define CAM_ISP_VFE_IN_RES_PHY_0 (CAM_ISP_VFE_IN_RES_BASE + 1) -#define CAM_ISP_VFE_IN_RES_PHY_1 (CAM_ISP_VFE_IN_RES_BASE + 2) -#define CAM_ISP_VFE_IN_RES_PHY_2 (CAM_ISP_VFE_IN_RES_BASE + 3) -#define CAM_ISP_VFE_IN_RES_PHY_3 (CAM_ISP_VFE_IN_RES_BASE + 4) -#define CAM_ISP_VFE_IN_RES_FE (CAM_ISP_VFE_IN_RES_BASE + 5) -#define CAM_ISP_VFE_IN_RES_MAX (CAM_ISP_VFE_IN_RES_BASE + 6) - -#endif /* __UAPI_CAM_ISP_VFE_H__ */ diff --git a/third_party/linux/include/media/cam_jpeg.h b/third_party/linux/include/media/cam_jpeg.h deleted file mode 100644 index f3082f3bfe295b..00000000000000 --- a/third_party/linux/include/media/cam_jpeg.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef __UAPI_CAM_JPEG_H__ -#define __UAPI_CAM_JPEG_H__ - -#include "cam_defs.h" - -/* enc, dma, cdm(enc/dma) are used in querycap */ -#define CAM_JPEG_DEV_TYPE_ENC 0 -#define CAM_JPEG_DEV_TYPE_DMA 1 -#define CAM_JPEG_DEV_TYPE_MAX 2 - -#define CAM_JPEG_NUM_DEV_PER_RES_MAX 1 - -/* definitions needed for jpeg aquire device */ -#define CAM_JPEG_RES_TYPE_ENC 0 -#define CAM_JPEG_RES_TYPE_DMA 1 -#define CAM_JPEG_RES_TYPE_MAX 2 - -/* packet opcode types */ -#define CAM_JPEG_OPCODE_ENC_UPDATE 0 -#define CAM_JPEG_OPCODE_DMA_UPDATE 1 - -/* ENC input port resource type */ -#define CAM_JPEG_ENC_INPUT_IMAGE 0x0 - -/* ENC output port resource type */ -#define CAM_JPEG_ENC_OUTPUT_IMAGE 0x1 - -#define CAM_JPEG_ENC_IO_IMAGES_MAX 0x2 - -/* DMA input port resource type */ -#define CAM_JPEG_DMA_INPUT_IMAGE 0x0 - -/* DMA output port resource type */ -#define CAM_JPEG_DMA_OUTPUT_IMAGE 0x1 - -#define CAM_JPEG_DMA_IO_IMAGES_MAX 0x2 - -#define CAM_JPEG_IMAGE_MAX 0x2 - -/** - * struct cam_jpeg_dev_ver - Device information for particular hw type - * - * This is used to get device version info of JPEG ENC, JPEG DMA - * from hardware and use this info in CAM_QUERY_CAP IOCTL - * - * @size : Size of struct passed - * @dev_type: Hardware type for the cap info(jpeg enc, jpeg dma) - * @hw_ver: Major, minor and incr values of a device version - */ -struct cam_jpeg_dev_ver { - uint32_t size; - uint32_t dev_type; - struct cam_hw_version hw_ver; -}; - -/** - * struct cam_jpeg_query_cap_cmd - JPEG query device capability payload - * - * @dev_iommu_handle: Jpeg iommu handles for secure/non secure - * modes - * @cdm_iommu_handle: Iommu handles for secure/non secure modes - * @num_enc: Number of encoder - * @num_dma: Number of dma - * @dev_ver: Returned device capability array - */ -struct cam_jpeg_query_cap_cmd { - struct cam_iommu_handle dev_iommu_handle; - struct cam_iommu_handle cdm_iommu_handle; - uint32_t num_enc; - uint32_t num_dma; - struct cam_jpeg_dev_ver dev_ver[CAM_JPEG_DEV_TYPE_MAX]; -}; - -/** - * struct cam_jpeg_res_info - JPEG output resource info - * - * @format: Format of the resource - * @width: Width in pixels - * @height: Height in lines - * @fps: Fps - */ -struct cam_jpeg_res_info { - uint32_t format; - uint32_t width; - uint32_t height; - uint32_t fps; -}; - -/** - * struct cam_jpeg_acquire_dev_info - An JPEG device info - * - * @dev_type: Device type (ENC/DMA) - * @reserved: Reserved Bytes - * @in_res: In resource info - * @in_res: Iut resource info - */ -struct cam_jpeg_acquire_dev_info { - uint32_t dev_type; - uint32_t reserved; - struct cam_jpeg_res_info in_res; - struct cam_jpeg_res_info out_res; -}; - -/** - * struct cam_jpeg_config_inout_param_info - JPEG Config time - * input output params - * - * @clk_index: Input Param- clock selection index.(-1 default) - * @output_size: Output Param - jpeg encode/dma output size in - * bytes - */ -struct cam_jpeg_config_inout_param_info { - int32_t clk_index; - int32_t output_size; -}; - -#endif /* __UAPI_CAM_JPEG_H__ */ diff --git a/third_party/linux/include/media/cam_lrme.h b/third_party/linux/include/media/cam_lrme.h deleted file mode 100644 index 97d957835ee3b7..00000000000000 --- a/third_party/linux/include/media/cam_lrme.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef __UAPI_CAM_LRME_H__ -#define __UAPI_CAM_LRME_H__ - -#include "cam_defs.h" - -/* LRME Resource Types */ - -enum CAM_LRME_IO_TYPE { - CAM_LRME_IO_TYPE_TAR, - CAM_LRME_IO_TYPE_REF, - CAM_LRME_IO_TYPE_RES, - CAM_LRME_IO_TYPE_DS2, -}; - -#define CAM_LRME_INPUT_PORT_TYPE_TAR (1 << 0) -#define CAM_LRME_INPUT_PORT_TYPE_REF (1 << 1) - -#define CAM_LRME_OUTPUT_PORT_TYPE_DS2 (1 << 0) -#define CAM_LRME_OUTPUT_PORT_TYPE_RES (1 << 1) - -#define CAM_LRME_DEV_MAX 1 - - -struct cam_lrme_hw_version { - uint32_t gen; - uint32_t rev; - uint32_t step; -}; - -struct cam_lrme_dev_cap { - struct cam_lrme_hw_version clc_hw_version; - struct cam_lrme_hw_version bus_rd_hw_version; - struct cam_lrme_hw_version bus_wr_hw_version; - struct cam_lrme_hw_version top_hw_version; - struct cam_lrme_hw_version top_titan_version; -}; - -/** - * struct cam_lrme_query_cap_cmd - LRME query device capability payload - * - * @dev_iommu_handle: LRME iommu handles for secure/non secure - * modes - * @cdm_iommu_handle: Iommu handles for secure/non secure modes - * @num_devices: number of hardware devices - * @dev_caps: Returned device capability array - */ -struct cam_lrme_query_cap_cmd { - struct cam_iommu_handle device_iommu; - struct cam_iommu_handle cdm_iommu; - uint32_t num_devices; - struct cam_lrme_dev_cap dev_caps[CAM_LRME_DEV_MAX]; -}; - -struct cam_lrme_soc_info { - uint64_t clock_rate; - uint64_t bandwidth; - uint64_t reserved[4]; -}; - -struct cam_lrme_acquire_args { - struct cam_lrme_soc_info lrme_soc_info; -}; - -#endif /* __UAPI_CAM_LRME_H__ */ - diff --git a/third_party/linux/include/media/cam_req_mgr.h b/third_party/linux/include/media/cam_req_mgr.h deleted file mode 100644 index ae65649964ff0a..00000000000000 --- a/third_party/linux/include/media/cam_req_mgr.h +++ /dev/null @@ -1,436 +0,0 @@ -#ifndef __UAPI_LINUX_CAM_REQ_MGR_H -#define __UAPI_LINUX_CAM_REQ_MGR_H - -#include -#include -#include -#include -#include - -#define CAM_REQ_MGR_VNODE_NAME "cam-req-mgr-devnode" - -#define CAM_DEVICE_TYPE_BASE (MEDIA_ENT_F_OLD_BASE) -#define CAM_VNODE_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE) -#define CAM_SENSOR_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 1) -#define CAM_IFE_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 2) -#define CAM_ICP_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 3) -#define CAM_LRME_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 4) -#define CAM_JPEG_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 5) -#define CAM_FD_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 6) -#define CAM_CPAS_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 7) -#define CAM_CSIPHY_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 8) -#define CAM_ACTUATOR_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 9) -#define CAM_CCI_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 10) -#define CAM_FLASH_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 11) -#define CAM_EEPROM_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 12) -#define CAM_OIS_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 13) - -/* cam_req_mgr hdl info */ -#define CAM_REQ_MGR_HDL_IDX_POS 8 -#define CAM_REQ_MGR_HDL_IDX_MASK ((1 << CAM_REQ_MGR_HDL_IDX_POS) - 1) -#define CAM_REQ_MGR_GET_HDL_IDX(hdl) (hdl & CAM_REQ_MGR_HDL_IDX_MASK) - -/** - * Max handles supported by cam_req_mgr - * It includes both session and device handles - */ -#define CAM_REQ_MGR_MAX_HANDLES 64 -#define MAX_LINKS_PER_SESSION 2 - -/* V4L event type which user space will subscribe to */ -#define V4L_EVENT_CAM_REQ_MGR_EVENT (V4L2_EVENT_PRIVATE_START + 0) - -/* Specific event ids to get notified in user space */ -#define V4L_EVENT_CAM_REQ_MGR_SOF 0 -#define V4L_EVENT_CAM_REQ_MGR_ERROR 1 -#define V4L_EVENT_CAM_REQ_MGR_SOF_BOOT_TS 2 - -/* SOF Event status */ -#define CAM_REQ_MGR_SOF_EVENT_SUCCESS 0 -#define CAM_REQ_MGR_SOF_EVENT_ERROR 1 - -/* Link control operations */ -#define CAM_REQ_MGR_LINK_ACTIVATE 0 -#define CAM_REQ_MGR_LINK_DEACTIVATE 1 - -/** - * Request Manager : flush_type - * @CAM_REQ_MGR_FLUSH_TYPE_ALL: Req mgr will remove all the pending - * requests from input/processing queue. - * @CAM_REQ_MGR_FLUSH_TYPE_CANCEL_REQ: Req mgr will remove only particular - * request id from input/processing queue. - * @CAM_REQ_MGR_FLUSH_TYPE_MAX: Max number of the flush type - * @opcode: CAM_REQ_MGR_FLUSH_REQ - */ -#define CAM_REQ_MGR_FLUSH_TYPE_ALL 0 -#define CAM_REQ_MGR_FLUSH_TYPE_CANCEL_REQ 1 -#define CAM_REQ_MGR_FLUSH_TYPE_MAX 2 - -/** - * Request Manager : Sync Mode type - * @CAM_REQ_MGR_SYNC_MODE_NO_SYNC: Req mgr will apply non-sync mode for this - * request. - * @CAM_REQ_MGR_SYNC_MODE_SYNC: Req mgr will apply sync mode for this request. - */ -#define CAM_REQ_MGR_SYNC_MODE_NO_SYNC 0 -#define CAM_REQ_MGR_SYNC_MODE_SYNC 1 - -/** - * struct cam_req_mgr_event_data - * @session_hdl: session handle - * @link_hdl: link handle - * @frame_id: frame id - * @reserved: reserved for 64 bit aligngment - * @req_id: request id - * @tv_sec: timestamp in seconds - * @tv_usec: timestamp in micro seconds - */ -struct cam_req_mgr_event_data { - int32_t session_hdl; - int32_t link_hdl; - int32_t frame_id; - int32_t reserved; - int64_t req_id; - uint64_t tv_sec; - uint64_t tv_usec; -}; - -/** - * struct cam_req_mgr_session_info - * @session_hdl: In/Output param - session_handle - * @opcode1: CAM_REQ_MGR_CREATE_SESSION - * @opcode2: CAM_REQ_MGR_DESTROY_SESSION - */ -struct cam_req_mgr_session_info { - int32_t session_hdl; - int32_t reserved; -}; - -/** - * struct cam_req_mgr_link_info - * @session_hdl: Input param - Identifier for CSL session - * @num_devices: Input Param - Num of devices to be linked - * @dev_hdls: Input param - List of device handles to be linked - * @link_hdl: Output Param -Identifier for link - * @opcode: CAM_REQ_MGR_LINK - */ -struct cam_req_mgr_link_info { - int32_t session_hdl; - uint32_t num_devices; - int32_t dev_hdls[CAM_REQ_MGR_MAX_HANDLES]; - int32_t link_hdl; -}; - -/** - * struct cam_req_mgr_unlink_info - * @session_hdl: input param - session handle - * @link_hdl: input param - link handle - * @opcode: CAM_REQ_MGR_UNLINK - */ -struct cam_req_mgr_unlink_info { - int32_t session_hdl; - int32_t link_hdl; -}; - -/** - * struct cam_req_mgr_flush_info - * @brief: User can tell drivers to flush a particular request id or - * flush all requests from its pending processing queue. Flush is a - * blocking call and driver shall ensure all requests are flushed - * before returning. - * @session_hdl: Input param - Identifier for CSL session - * @link_hdl: Input Param -Identifier for link - * @flush_type: User can cancel a particular req id or can flush - * all requests in queue - * @reserved: reserved for 64 bit aligngment - * @req_id: field is valid only if flush type is cancel request - * for flush all this field value is not considered. - * @opcode: CAM_REQ_MGR_FLUSH_REQ - */ -struct cam_req_mgr_flush_info { - int32_t session_hdl; - int32_t link_hdl; - uint32_t flush_type; - uint32_t reserved; - int64_t req_id; -}; - -/** struct cam_req_mgr_sched_info - * @session_hdl: Input param - Identifier for CSL session - * @link_hdl: Input Param -Identifier for link - * inluding itself. - * @bubble_enable: Input Param - Cam req mgr will do bubble recovery if this - * flag is set. - * @sync_mode: Type of Sync mode for this request - * @req_id: Input Param - Request Id from which all requests will be flushed - */ -struct cam_req_mgr_sched_request { - int32_t session_hdl; - int32_t link_hdl; - int32_t bubble_enable; - int32_t sync_mode; - int64_t req_id; -}; - -/** - * struct cam_req_mgr_sync_mode - * @session_hdl: Input param - Identifier for CSL session - * @sync_mode: Input Param - Type of sync mode - * @num_links: Input Param - Num of links in sync mode (Valid only - * when sync_mode is one of SYNC enabled modes) - * @link_hdls: Input Param - Array of link handles to be in sync mode - * (Valid only when sync_mode is one of SYNC - * enabled modes) - * @master_link_hdl: Input Param - To dictate which link's SOF drives system - * (Valid only when sync_mode is one of SYNC - * enabled modes) - * - * @opcode: CAM_REQ_MGR_SYNC_MODE - */ -struct cam_req_mgr_sync_mode { - int32_t session_hdl; - int32_t sync_mode; - int32_t num_links; - int32_t link_hdls[MAX_LINKS_PER_SESSION]; - int32_t master_link_hdl; - int32_t reserved; -}; - -/** - * struct cam_req_mgr_link_control - * @ops: Link operations: activate/deactive - * @session_hdl: Input param - Identifier for CSL session - * @num_links: Input Param - Num of links - * @reserved: reserved field - * @link_hdls: Input Param - Links to be activated/deactivated - * - * @opcode: CAM_REQ_MGR_LINK_CONTROL - */ -struct cam_req_mgr_link_control { - int32_t ops; - int32_t session_hdl; - int32_t num_links; - int32_t reserved; - int32_t link_hdls[MAX_LINKS_PER_SESSION]; -}; - -/** - * cam_req_mgr specific opcode ids - */ -#define CAM_REQ_MGR_CREATE_DEV_NODES (CAM_COMMON_OPCODE_MAX + 1) -#define CAM_REQ_MGR_CREATE_SESSION (CAM_COMMON_OPCODE_MAX + 2) -#define CAM_REQ_MGR_DESTROY_SESSION (CAM_COMMON_OPCODE_MAX + 3) -#define CAM_REQ_MGR_LINK (CAM_COMMON_OPCODE_MAX + 4) -#define CAM_REQ_MGR_UNLINK (CAM_COMMON_OPCODE_MAX + 5) -#define CAM_REQ_MGR_SCHED_REQ (CAM_COMMON_OPCODE_MAX + 6) -#define CAM_REQ_MGR_FLUSH_REQ (CAM_COMMON_OPCODE_MAX + 7) -#define CAM_REQ_MGR_SYNC_MODE (CAM_COMMON_OPCODE_MAX + 8) -#define CAM_REQ_MGR_ALLOC_BUF (CAM_COMMON_OPCODE_MAX + 9) -#define CAM_REQ_MGR_MAP_BUF (CAM_COMMON_OPCODE_MAX + 10) -#define CAM_REQ_MGR_RELEASE_BUF (CAM_COMMON_OPCODE_MAX + 11) -#define CAM_REQ_MGR_CACHE_OPS (CAM_COMMON_OPCODE_MAX + 12) -#define CAM_REQ_MGR_LINK_CONTROL (CAM_COMMON_OPCODE_MAX + 13) -/* end of cam_req_mgr opcodes */ - -#define CAM_MEM_FLAG_HW_READ_WRITE (1<<0) -#define CAM_MEM_FLAG_HW_READ_ONLY (1<<1) -#define CAM_MEM_FLAG_HW_WRITE_ONLY (1<<2) -#define CAM_MEM_FLAG_KMD_ACCESS (1<<3) -#define CAM_MEM_FLAG_UMD_ACCESS (1<<4) -#define CAM_MEM_FLAG_PROTECTED_MODE (1<<5) -#define CAM_MEM_FLAG_CMD_BUF_TYPE (1<<6) -#define CAM_MEM_FLAG_PIXEL_BUF_TYPE (1<<7) -#define CAM_MEM_FLAG_STATS_BUF_TYPE (1<<8) -#define CAM_MEM_FLAG_PACKET_BUF_TYPE (1<<9) -#define CAM_MEM_FLAG_CACHE (1<<10) -#define CAM_MEM_FLAG_HW_SHARED_ACCESS (1<<11) - -#define CAM_MEM_MMU_MAX_HANDLE 16 - -/* Maximum allowed buffers in existence */ -#define CAM_MEM_BUFQ_MAX 1024 - -#define CAM_MEM_MGR_SECURE_BIT_POS 15 -#define CAM_MEM_MGR_HDL_IDX_SIZE 15 -#define CAM_MEM_MGR_HDL_FD_SIZE 16 -#define CAM_MEM_MGR_HDL_IDX_END_POS 16 -#define CAM_MEM_MGR_HDL_FD_END_POS 32 - -#define CAM_MEM_MGR_HDL_IDX_MASK ((1 << CAM_MEM_MGR_HDL_IDX_SIZE) - 1) - -#define GET_MEM_HANDLE(idx, fd) \ - ((idx & CAM_MEM_MGR_HDL_IDX_MASK) | \ - (fd << (CAM_MEM_MGR_HDL_FD_END_POS - CAM_MEM_MGR_HDL_FD_SIZE))) \ - -#define GET_FD_FROM_HANDLE(hdl) \ - (hdl >> (CAM_MEM_MGR_HDL_FD_END_POS - CAM_MEM_MGR_HDL_FD_SIZE)) \ - -#define CAM_MEM_MGR_GET_HDL_IDX(hdl) (hdl & CAM_MEM_MGR_HDL_IDX_MASK) - -#define CAM_MEM_MGR_SET_SECURE_HDL(hdl, flag) \ - ((flag) ? (hdl |= (1 << CAM_MEM_MGR_SECURE_BIT_POS)) : \ - ((hdl) &= ~(1 << CAM_MEM_MGR_SECURE_BIT_POS))) - -#define CAM_MEM_MGR_IS_SECURE_HDL(hdl) \ - (((hdl) & \ - (1<> CAM_MEM_MGR_SECURE_BIT_POS) - -/** - * memory allocation type - */ -#define CAM_MEM_DMA_NONE 0 -#define CAM_MEM_DMA_BIDIRECTIONAL 1 -#define CAM_MEM_DMA_TO_DEVICE 2 -#define CAM_MEM_DMA_FROM_DEVICE 3 - - -/** - * memory cache operation - */ -#define CAM_MEM_CLEAN_CACHE 1 -#define CAM_MEM_INV_CACHE 2 -#define CAM_MEM_CLEAN_INV_CACHE 3 - - -/** - * struct cam_mem_alloc_out_params - * @buf_handle: buffer handle - * @fd: output buffer file descriptor - * @vaddr: virtual address pointer - */ -struct cam_mem_alloc_out_params { - uint32_t buf_handle; - int32_t fd; - uint64_t vaddr; -}; - -/** - * struct cam_mem_map_out_params - * @buf_handle: buffer handle - * @reserved: reserved for future - * @vaddr: virtual address pointer - */ -struct cam_mem_map_out_params { - uint32_t buf_handle; - uint32_t reserved; - uint64_t vaddr; -}; - -/** - * struct cam_mem_mgr_alloc_cmd - * @len: size of buffer to allocate - * @align: alignment of the buffer - * @mmu_hdls: array of mmu handles - * @num_hdl: number of handles - * @flags: flags of the buffer - * @out: out params - */ -/* CAM_REQ_MGR_ALLOC_BUF */ -struct cam_mem_mgr_alloc_cmd { - uint64_t len; - uint64_t align; - int32_t mmu_hdls[CAM_MEM_MMU_MAX_HANDLE]; - uint32_t num_hdl; - uint32_t flags; - struct cam_mem_alloc_out_params out; -}; - -/** - * struct cam_mem_mgr_map_cmd - * @mmu_hdls: array of mmu handles - * @num_hdl: number of handles - * @flags: flags of the buffer - * @fd: output buffer file descriptor - * @reserved: reserved field - * @out: out params - */ - -/* CAM_REQ_MGR_MAP_BUF */ -struct cam_mem_mgr_map_cmd { - int32_t mmu_hdls[CAM_MEM_MMU_MAX_HANDLE]; - uint32_t num_hdl; - uint32_t flags; - int32_t fd; - uint32_t reserved; - struct cam_mem_map_out_params out; -}; - -/** - * struct cam_mem_mgr_map_cmd - * @buf_handle: buffer handle - * @reserved: reserved field - */ -/* CAM_REQ_MGR_RELEASE_BUF */ -struct cam_mem_mgr_release_cmd { - int32_t buf_handle; - uint32_t reserved; -}; - -/** - * struct cam_mem_mgr_map_cmd - * @buf_handle: buffer handle - * @ops: cache operations - */ -/* CAM_REQ_MGR_CACHE_OPS */ -struct cam_mem_cache_ops_cmd { - int32_t buf_handle; - uint32_t mem_cache_ops; -}; - -/** - * Request Manager : error message type - * @CAM_REQ_MGR_ERROR_TYPE_DEVICE: Device error message, fatal to session - * @CAM_REQ_MGR_ERROR_TYPE_REQUEST: Error on a single request, not fatal - * @CAM_REQ_MGR_ERROR_TYPE_BUFFER: Buffer was not filled, not fatal - */ -#define CAM_REQ_MGR_ERROR_TYPE_DEVICE 0 -#define CAM_REQ_MGR_ERROR_TYPE_REQUEST 1 -#define CAM_REQ_MGR_ERROR_TYPE_BUFFER 2 - -/** - * struct cam_req_mgr_error_msg - * @error_type: type of error - * @request_id: request id of frame - * @device_hdl: device handle - * @linke_hdl: link_hdl - * @resource_size: size of the resource - */ -struct cam_req_mgr_error_msg { - uint32_t error_type; - uint32_t request_id; - int32_t device_hdl; - int32_t link_hdl; - uint64_t resource_size; -}; - -/** - * struct cam_req_mgr_frame_msg - * @request_id: request id of the frame - * @frame_id: frame id of the frame - * @timestamp: timestamp of the frame - * @link_hdl: link handle associated with this message - * @sof_status: sof status success or fail - */ -struct cam_req_mgr_frame_msg { - uint64_t request_id; - uint64_t frame_id; - uint64_t timestamp; - int32_t link_hdl; - uint32_t sof_status; -}; - -/** - * struct cam_req_mgr_message - * @session_hdl: session to which the frame belongs to - * @reserved: reserved field - * @u: union which can either be error or frame message - */ -struct cam_req_mgr_message { - int32_t session_hdl; - int32_t reserved; - union { - struct cam_req_mgr_error_msg err_msg; - struct cam_req_mgr_frame_msg frame_msg; - } u; -}; -#endif /* __UAPI_LINUX_CAM_REQ_MGR_H */ diff --git a/third_party/linux/include/media/cam_sensor.h b/third_party/linux/include/media/cam_sensor.h deleted file mode 100644 index f5af6047f5ac88..00000000000000 --- a/third_party/linux/include/media/cam_sensor.h +++ /dev/null @@ -1,477 +0,0 @@ -#ifndef __UAPI_CAM_SENSOR_H__ -#define __UAPI_CAM_SENSOR_H__ - -#include -#include -#include - -#define CAM_SENSOR_PROBE_CMD (CAM_COMMON_OPCODE_MAX + 1) -#define CAM_FLASH_MAX_LED_TRIGGERS 3 -#define MAX_OIS_NAME_SIZE 32 -#define CAM_CSIPHY_SECURE_MODE_ENABLED 1 -/** - * struct cam_sensor_query_cap - capabilities info for sensor - * - * @slot_info : Indicates about the slotId or cell Index - * @secure_camera : Camera is in secure/Non-secure mode - * @pos_pitch : Sensor position pitch - * @pos_roll : Sensor position roll - * @pos_yaw : Sensor position yaw - * @actuator_slot_id : Actuator slot id which connected to sensor - * @eeprom_slot_id : EEPROM slot id which connected to sensor - * @ois_slot_id : OIS slot id which connected to sensor - * @flash_slot_id : Flash slot id which connected to sensor - * @csiphy_slot_id : CSIphy slot id which connected to sensor - * - */ -struct cam_sensor_query_cap { - uint32_t slot_info; - uint32_t secure_camera; - uint32_t pos_pitch; - uint32_t pos_roll; - uint32_t pos_yaw; - uint32_t actuator_slot_id; - uint32_t eeprom_slot_id; - uint32_t ois_slot_id; - uint32_t flash_slot_id; - uint32_t csiphy_slot_id; -} __attribute__((packed)); - -/** - * struct cam_csiphy_query_cap - capabilities info for csiphy - * - * @slot_info : Indicates about the slotId or cell Index - * @version : CSIphy version - * @clk lane : Of the 5 lanes, informs lane configured - * as clock lane - * @reserved - */ -struct cam_csiphy_query_cap { - uint32_t slot_info; - uint32_t version; - uint32_t clk_lane; - uint32_t reserved; -} __attribute__((packed)); - -/** - * struct cam_actuator_query_cap - capabilities info for actuator - * - * @slot_info : Indicates about the slotId or cell Index - * @reserved - */ -struct cam_actuator_query_cap { - uint32_t slot_info; - uint32_t reserved; -} __attribute__((packed)); - -/** - * struct cam_eeprom_query_cap_t - capabilities info for eeprom - * - * @slot_info : Indicates about the slotId or cell Index - * @eeprom_kernel_probe : Indicates about the kernel or userspace probe - */ -struct cam_eeprom_query_cap_t { - uint32_t slot_info; - uint16_t eeprom_kernel_probe; - uint16_t reserved; -} __attribute__((packed)); - -/** - * struct cam_ois_query_cap_t - capabilities info for ois - * - * @slot_info : Indicates about the slotId or cell Index - */ -struct cam_ois_query_cap_t { - uint32_t slot_info; - uint16_t reserved; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_info - Contains slave I2C related info - * - * @slave_addr : Slave address - * @i2c_freq_mode : 4 bits are used for I2c freq mode - * @cmd_type : Explains type of command - */ -struct cam_cmd_i2c_info { - uint16_t slave_addr; - uint8_t i2c_freq_mode; - uint8_t cmd_type; -} __attribute__((packed)); - -/** - * struct cam_ois_opcode - Contains OIS opcode - * - * @prog : OIS FW prog register address - * @coeff : OIS FW coeff register address - * @pheripheral : OIS pheripheral - * @memory : OIS memory - */ -struct cam_ois_opcode { - uint32_t prog; - uint32_t coeff; - uint32_t pheripheral; - uint32_t memory; -} __attribute__((packed)); - -/** - * struct cam_cmd_ois_info - Contains OIS slave info - * - * @slave_addr : OIS i2c slave address - * @i2c_freq_mode : i2c frequency mode - * @cmd_type : Explains type of command - * @ois_fw_flag : indicates if fw is present or not - * @is_ois_calib : indicates the calibration data is available - * @ois_name : OIS name - * @opcode : opcode - */ -struct cam_cmd_ois_info { - uint16_t slave_addr; - uint8_t i2c_freq_mode; - uint8_t cmd_type; - uint8_t ois_fw_flag; - uint8_t is_ois_calib; - char ois_name[MAX_OIS_NAME_SIZE]; - struct cam_ois_opcode opcode; -} __attribute__((packed)); - -/** - * struct cam_cmd_probe - Contains sensor slave info - * - * @data_type : Slave register data type - * @addr_type : Slave register address type - * @op_code : Don't Care - * @cmd_type : Explains type of command - * @reg_addr : Slave register address - * @expected_data : Data expected at slave register address - * @data_mask : Data mask if only few bits are valid - * @camera_id : Indicates the slot to which camera - * needs to be probed - * @reserved - */ -struct cam_cmd_probe { - uint8_t data_type; - uint8_t addr_type; - uint8_t op_code; - uint8_t cmd_type; - uint32_t reg_addr; - uint32_t expected_data; - uint32_t data_mask; - uint16_t camera_id; - uint16_t reserved; -} __attribute__((packed)); - -/** - * struct cam_power_settings - Contains sensor power setting info - * - * @power_seq_type : Type of power sequence - * @reserved - * @config_val_low : Lower 32 bit value configuration value - * @config_val_high : Higher 32 bit value configuration value - * - */ -struct cam_power_settings { - uint16_t power_seq_type; - uint16_t reserved; - uint32_t config_val_low; - uint32_t config_val_high; -} __attribute__((packed)); - -/** - * struct cam_cmd_power - Explains about the power settings - * - * @count : Number of power settings follows - * @reserved - * @cmd_type : Explains type of command - * @power_settings : Contains power setting info - */ -struct cam_cmd_power { - uint16_t count; - uint8_t reserved; - uint8_t cmd_type; - struct cam_power_settings power_settings[1]; -} __attribute__((packed)); - -/** - * struct i2c_rdwr_header - header of READ/WRITE I2C command - * - * @ count : Number of registers / data / reg-data pairs - * @ op_code : Operation code - * @ cmd_type : Command buffer type - * @ data_type : I2C data type - * @ addr_type : I2C address type - * @ reserved - */ -struct i2c_rdwr_header { - uint16_t count; - uint8_t op_code; - uint8_t cmd_type; - uint8_t data_type; - uint8_t addr_type; - uint16_t reserved; -} __attribute__((packed)); - -/** - * struct i2c_random_wr_payload - payload for I2C random write - * - * @ reg_addr : Register address - * @ reg_data : Register data - * - */ -struct i2c_random_wr_payload { - uint32_t reg_addr; - uint32_t reg_data; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_random_wr - I2C random write command - * @ header : header of READ/WRITE I2C command - * @ random_wr_payload : payload for I2C random write - */ -struct cam_cmd_i2c_random_wr { - struct i2c_rdwr_header header; - struct i2c_random_wr_payload random_wr_payload[1]; -} __attribute__((packed)); - -/** - * struct cam_cmd_read - I2C read command - * @ reg_data : Register data - * @ reserved - */ -struct cam_cmd_read { - uint32_t reg_data; - uint32_t reserved; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_continuous_wr - I2C continuous write command - * @ header : header of READ/WRITE I2C command - * @ reg_addr : Register address - * @ data_read : I2C read command - */ -struct cam_cmd_i2c_continuous_wr { - struct i2c_rdwr_header header; - uint32_t reg_addr; - struct cam_cmd_read data_read[1]; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_random_rd - I2C random read command - * @ header : header of READ/WRITE I2C command - * @ data_read : I2C read command - */ -struct cam_cmd_i2c_random_rd { - struct i2c_rdwr_header header; - struct cam_cmd_read data_read[1]; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_continuous_rd - I2C continuous continuous read command - * @ header : header of READ/WRITE I2C command - * @ reg_addr : Register address - * - */ -struct cam_cmd_i2c_continuous_rd { - struct i2c_rdwr_header header; - uint32_t reg_addr; -} __attribute__((packed)); - -/** - * struct cam_cmd_conditional_wait - Conditional wait command - * @data_type : Data type - * @addr_type : Address type - * @op_code : Opcode - * @cmd_type : Explains type of command - * @timeout : Timeout for retries - * @reserved - * @reg_addr : Register Address - * @reg_data : Register data - * @data_mask : Data mask if only few bits are valid - * @camera_id : Indicates the slot to which camera - * needs to be probed - * - */ -struct cam_cmd_conditional_wait { - uint8_t data_type; - uint8_t addr_type; - uint8_t op_code; - uint8_t cmd_type; - uint16_t timeout; - uint16_t reserved; - uint32_t reg_addr; - uint32_t reg_data; - uint32_t data_mask; -} __attribute__((packed)); - -/** - * struct cam_cmd_unconditional_wait - Un-conditional wait command - * @delay : Delay - * @op_code : Opcode - * @cmd_type : Explains type of command - */ -struct cam_cmd_unconditional_wait { - int16_t delay; - uint8_t op_code; - uint8_t cmd_type; -} __attribute__((packed)); - -/** - * cam_csiphy_info: Provides cmdbuffer structre - * @lane_mask : Lane mask details - * @lane_assign : Lane sensor will be using - * @csiphy_3phase : Total number of lanes - * @combo_mode : Info regarding combo_mode is enable / disable - * @lane_cnt : Total number of lanes - * @secure_mode : Secure mode flag to enable / disable - * @3phase : Details whether 3Phase / 2Phase operation - * @settle_time : Settling time in ms - * @data_rate : Data rate - * - */ -struct cam_csiphy_info { - uint16_t lane_mask; - uint16_t lane_assign; - uint8_t csiphy_3phase; - uint8_t combo_mode; - uint8_t lane_cnt; - uint8_t secure_mode; - uint64_t settle_time; - uint64_t data_rate; -} __attribute__((packed)); - -/** - * cam_csiphy_acquire_dev_info : Information needed for - * csiphy at the time of acquire - * @combo_mode : Indicates the device mode of operation - * @reserved - * - */ -struct cam_csiphy_acquire_dev_info { - uint32_t combo_mode; - uint32_t reserved; -} __attribute__((packed)); - -/** - * cam_sensor_acquire_dev : Updates sensor acuire cmd - * @device_handle : Updates device handle - * @session_handle : Session handle for acquiring device - * @handle_type : Resource handle type - * @reserved - * @info_handle : Handle to additional info - * needed for sensor sub modules - * - */ -struct cam_sensor_acquire_dev { - uint32_t session_handle; - uint32_t device_handle; - uint32_t handle_type; - uint32_t reserved; - uint64_t info_handle; -} __attribute__((packed)); - -/** - * cam_sensor_streamon_dev : StreamOn command for the sensor - * @session_handle : Session handle for acquiring device - * @device_handle : Updates device handle - * @handle_type : Resource handle type - * @reserved - * @info_handle : Information Needed at the time of streamOn - * - */ -struct cam_sensor_streamon_dev { - uint32_t session_handle; - uint32_t device_handle; - uint32_t handle_type; - uint32_t reserved; - uint64_t info_handle; -} __attribute__((packed)); - -/** - * struct cam_flash_init : Init command for the flash - * @flash_type : flash hw type - * @reserved - * @cmd_type : command buffer type - */ -struct cam_flash_init { - uint8_t flash_type; - uint16_t reserved; - uint8_t cmd_type; -} __attribute__((packed)); - -/** - * struct cam_flash_set_rer : RedEyeReduction command buffer - * - * @count : Number of flash leds - * @opcode : Command buffer opcode - * CAM_FLASH_FIRE_RER - * @cmd_type : command buffer operation type - * @num_iteration : Number of led turn on/off sequence - * @reserved - * @led_on_delay_ms : flash led turn on time in ms - * @led_off_delay_ms : flash led turn off time in ms - * @led_current_ma : flash led current in ma - * - */ -struct cam_flash_set_rer { - uint16_t count; - uint8_t opcode; - uint8_t cmd_type; - uint16_t num_iteration; - uint16_t reserved; - uint32_t led_on_delay_ms; - uint32_t led_off_delay_ms; - uint32_t led_current_ma[CAM_FLASH_MAX_LED_TRIGGERS]; -} __attribute__((packed)); - -/** - * struct cam_flash_set_on_off : led turn on/off command buffer - * - * @count : Number of Flash leds - * @opcode : command buffer opcodes - * CAM_FLASH_FIRE_LOW - * CAM_FLASH_FIRE_HIGH - * CAM_FLASH_OFF - * @cmd_type : command buffer operation type - * @led_current_ma : flash led current in ma - * - */ -struct cam_flash_set_on_off { - uint16_t count; - uint8_t opcode; - uint8_t cmd_type; - uint32_t led_current_ma[CAM_FLASH_MAX_LED_TRIGGERS]; -} __attribute__((packed)); - -/** - * struct cam_flash_query_curr : query current command buffer - * - * @reserved - * @opcode : command buffer opcode - * @cmd_type : command buffer operation type - * @query_current_ma : battery current in ma - * - */ -struct cam_flash_query_curr { - uint16_t reserved; - uint8_t opcode; - uint8_t cmd_type; - uint32_t query_current_ma; -} __attribute__ ((packed)); - -/** - * struct cam_flash_query_cap : capabilities info for flash - * - * @slot_info : Indicates about the slotId or cell Index - * @max_current_flash : max supported current for flash - * @max_duration_flash : max flash turn on duration - * @max_current_torch : max supported current for torch - * - */ -struct cam_flash_query_cap_info { - uint32_t slot_info; - uint32_t max_current_flash[CAM_FLASH_MAX_LED_TRIGGERS]; - uint32_t max_duration_flash[CAM_FLASH_MAX_LED_TRIGGERS]; - uint32_t max_current_torch[CAM_FLASH_MAX_LED_TRIGGERS]; -} __attribute__ ((packed)); - -#endif diff --git a/third_party/linux/include/media/cam_sensor_cmn_header.h b/third_party/linux/include/media/cam_sensor_cmn_header.h deleted file mode 100644 index 24617b39bd1266..00000000000000 --- a/third_party/linux/include/media/cam_sensor_cmn_header.h +++ /dev/null @@ -1,391 +0,0 @@ -/* Copyright (c) 2017-2018, The Linux Foundation. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - */ - -#ifndef _CAM_SENSOR_CMN_HEADER_ -#define _CAM_SENSOR_CMN_HEADER_ - -#include -#include -#include - -#define MAX_REGULATOR 5 -#define MAX_POWER_CONFIG 12 - -#define MAX_PER_FRAME_ARRAY 32 -#define BATCH_SIZE_MAX 16 - -#define CAM_SENSOR_NAME "cam-sensor" -#define CAM_ACTUATOR_NAME "cam-actuator" -#define CAM_CSIPHY_NAME "cam-csiphy" -#define CAM_FLASH_NAME "cam-flash" -#define CAM_EEPROM_NAME "cam-eeprom" -#define CAM_OIS_NAME "cam-ois" - -#define MAX_SYSTEM_PIPELINE_DELAY 2 - -#define CAM_PKT_NOP_OPCODE 127 - -enum camera_sensor_cmd_type { - CAMERA_SENSOR_CMD_TYPE_INVALID, - CAMERA_SENSOR_CMD_TYPE_PROBE, - CAMERA_SENSOR_CMD_TYPE_PWR_UP, - CAMERA_SENSOR_CMD_TYPE_PWR_DOWN, - CAMERA_SENSOR_CMD_TYPE_I2C_INFO, - CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_WR, - CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_RD, - CAMERA_SENSOR_CMD_TYPE_I2C_CONT_WR, - CAMERA_SENSOR_CMD_TYPE_I2C_CONT_RD, - CAMERA_SENSOR_CMD_TYPE_WAIT, - CAMERA_SENSOR_FLASH_CMD_TYPE_INIT_INFO, - CAMERA_SENSOR_FLASH_CMD_TYPE_FIRE, - CAMERA_SENSOR_FLASH_CMD_TYPE_RER, - CAMERA_SENSOR_FLASH_CMD_TYPE_QUERYCURR, - CAMERA_SENSOR_FLASH_CMD_TYPE_WIDGET, - CAMERA_SENSOR_CMD_TYPE_RD_DATA, - CAMERA_SENSOR_FLASH_CMD_TYPE_INIT_FIRE, - CAMERA_SENSOR_CMD_TYPE_MAX, -}; - -enum camera_sensor_i2c_op_code { - CAMERA_SENSOR_I2C_OP_INVALID, - CAMERA_SENSOR_I2C_OP_RNDM_WR, - CAMERA_SENSOR_I2C_OP_RNDM_WR_VERF, - CAMERA_SENSOR_I2C_OP_CONT_WR_BRST, - CAMERA_SENSOR_I2C_OP_CONT_WR_BRST_VERF, - CAMERA_SENSOR_I2C_OP_CONT_WR_SEQN, - CAMERA_SENSOR_I2C_OP_CONT_WR_SEQN_VERF, - CAMERA_SENSOR_I2C_OP_MAX, -}; - -enum camera_sensor_wait_op_code { - CAMERA_SENSOR_WAIT_OP_INVALID, - CAMERA_SENSOR_WAIT_OP_COND, - CAMERA_SENSOR_WAIT_OP_HW_UCND, - CAMERA_SENSOR_WAIT_OP_SW_UCND, - CAMERA_SENSOR_WAIT_OP_MAX, -}; - -enum camera_flash_opcode { - CAMERA_SENSOR_FLASH_OP_INVALID, - CAMERA_SENSOR_FLASH_OP_OFF, - CAMERA_SENSOR_FLASH_OP_FIRELOW, - CAMERA_SENSOR_FLASH_OP_FIREHIGH, - CAMERA_SENSOR_FLASH_OP_MAX, -}; - -enum camera_sensor_i2c_type { - CAMERA_SENSOR_I2C_TYPE_INVALID, - CAMERA_SENSOR_I2C_TYPE_BYTE, - CAMERA_SENSOR_I2C_TYPE_WORD, - CAMERA_SENSOR_I2C_TYPE_3B, - CAMERA_SENSOR_I2C_TYPE_DWORD, - CAMERA_SENSOR_I2C_TYPE_MAX, -}; - -enum i2c_freq_mode { - I2C_STANDARD_MODE, - I2C_FAST_MODE, - I2C_CUSTOM_MODE, - I2C_FAST_PLUS_MODE, - I2C_MAX_MODES, -}; - -enum position_roll { - ROLL_0 = 0, - ROLL_90 = 90, - ROLL_180 = 180, - ROLL_270 = 270, - ROLL_INVALID = 360, -}; - -enum position_yaw { - FRONT_CAMERA_YAW = 0, - REAR_CAMERA_YAW = 180, - INVALID_YAW = 360, -}; - -enum position_pitch { - LEVEL_PITCH = 0, - INVALID_PITCH = 360, -}; - -enum sensor_sub_module { - SUB_MODULE_SENSOR, - SUB_MODULE_ACTUATOR, - SUB_MODULE_EEPROM, - SUB_MODULE_LED_FLASH, - SUB_MODULE_CSID, - SUB_MODULE_CSIPHY, - SUB_MODULE_OIS, - SUB_MODULE_EXT, - SUB_MODULE_MAX, -}; - -enum msm_camera_power_seq_type { - SENSOR_MCLK, - SENSOR_VANA, - SENSOR_VDIG, - SENSOR_VIO, - SENSOR_VAF, - SENSOR_VAF_PWDM, - SENSOR_CUSTOM_REG1, - SENSOR_CUSTOM_REG2, - SENSOR_RESET, - SENSOR_STANDBY, - SENSOR_CUSTOM_GPIO1, - SENSOR_CUSTOM_GPIO2, - SENSOR_SEQ_TYPE_MAX, -}; - -enum cam_sensor_packet_opcodes { - CAM_SENSOR_PACKET_OPCODE_SENSOR_STREAMON, - CAM_SENSOR_PACKET_OPCODE_SENSOR_UPDATE, - CAM_SENSOR_PACKET_OPCODE_SENSOR_INITIAL_CONFIG, - CAM_SENSOR_PACKET_OPCODE_SENSOR_PROBE, - CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, - CAM_SENSOR_PACKET_OPCODE_SENSOR_STREAMOFF, - CAM_SENSOR_PACKET_OPCODE_SENSOR_NOP = 127 -}; - -enum cam_actuator_packet_opcodes { - CAM_ACTUATOR_PACKET_OPCODE_INIT, - CAM_ACTUATOR_PACKET_AUTO_MOVE_LENS, - CAM_ACTUATOR_PACKET_MANUAL_MOVE_LENS -}; - -enum cam_eeprom_packet_opcodes { - CAM_EEPROM_PACKET_OPCODE_INIT -}; - -enum cam_ois_packet_opcodes { - CAM_OIS_PACKET_OPCODE_INIT, - CAM_OIS_PACKET_OPCODE_OIS_CONTROL -}; - -enum msm_bus_perf_setting { - S_INIT, - S_PREVIEW, - S_VIDEO, - S_CAPTURE, - S_ZSL, - S_STEREO_VIDEO, - S_STEREO_CAPTURE, - S_DEFAULT, - S_LIVESHOT, - S_DUAL, - S_EXIT -}; - -enum msm_camera_device_type_t { - MSM_CAMERA_I2C_DEVICE, - MSM_CAMERA_PLATFORM_DEVICE, - MSM_CAMERA_SPI_DEVICE, -}; - -enum cam_flash_device_type { - CAMERA_FLASH_DEVICE_TYPE_PMIC = 0, - CAMERA_FLASH_DEVICE_TYPE_I2C, - CAMERA_FLASH_DEVICE_TYPE_GPIO, -}; - -enum cci_i2c_master_t { - MASTER_0, - MASTER_1, - MASTER_MAX, -}; - -enum camera_vreg_type { - VREG_TYPE_DEFAULT, - VREG_TYPE_CUSTOM, -}; - -enum cam_sensor_i2c_cmd_type { - CAM_SENSOR_I2C_WRITE_RANDOM, - CAM_SENSOR_I2C_WRITE_BURST, - CAM_SENSOR_I2C_WRITE_SEQ, - CAM_SENSOR_I2C_READ, - CAM_SENSOR_I2C_POLL -}; - -struct common_header { - uint16_t first_word; - uint8_t third_byte; - uint8_t cmd_type; -}; - -struct camera_vreg_t { - const char *reg_name; - int min_voltage; - int max_voltage; - int op_mode; - uint32_t delay; - const char *custom_vreg_name; - enum camera_vreg_type type; -}; - -struct msm_camera_gpio_num_info { - uint16_t gpio_num[SENSOR_SEQ_TYPE_MAX]; - uint8_t valid[SENSOR_SEQ_TYPE_MAX]; -}; - -struct msm_cam_clk_info { - const char *clk_name; - long clk_rate; - uint32_t delay; -}; - -struct msm_pinctrl_info { - struct pinctrl *pinctrl; - struct pinctrl_state *gpio_state_active; - struct pinctrl_state *gpio_state_suspend; - bool use_pinctrl; -}; - -struct cam_sensor_i2c_reg_array { - uint32_t reg_addr; - uint32_t reg_data; - uint32_t delay; - uint32_t data_mask; -}; - -struct cam_sensor_i2c_reg_setting { - struct cam_sensor_i2c_reg_array *reg_setting; - unsigned short size; - enum camera_sensor_i2c_type addr_type; - enum camera_sensor_i2c_type data_type; - unsigned short delay; -}; - -/*struct i2c_settings_list { - struct cam_sensor_i2c_reg_setting i2c_settings; - enum cam_sensor_i2c_cmd_type op_code; - struct list_head list; -}; - -struct i2c_settings_array { - struct list_head list_head; - int32_t is_settings_valid; - int64_t request_id; -}; - -struct i2c_data_settings { - struct i2c_settings_array init_settings; - struct i2c_settings_array config_settings; - struct i2c_settings_array streamon_settings; - struct i2c_settings_array streamoff_settings; - struct i2c_settings_array *per_frame; -};*/ - -struct cam_sensor_power_ctrl_t { - struct device *dev; - struct cam_sensor_power_setting *power_setting; - uint16_t power_setting_size; - struct cam_sensor_power_setting *power_down_setting; - uint16_t power_down_setting_size; - struct msm_camera_gpio_num_info *gpio_num_info; - struct msm_pinctrl_info pinctrl_info; - uint8_t cam_pinctrl_status; -}; - -struct cam_camera_slave_info { - uint16_t sensor_slave_addr; - uint16_t sensor_id_reg_addr; - uint16_t sensor_id; - uint16_t sensor_id_mask; -}; - -struct msm_sensor_init_params { - int modes_supported; - unsigned int sensor_mount_angle; -}; - -enum msm_sensor_camera_id_t { - CAMERA_0, - CAMERA_1, - CAMERA_2, - CAMERA_3, - CAMERA_4, - CAMERA_5, - CAMERA_6, - MAX_CAMERAS, -}; - -struct msm_sensor_id_info_t { - unsigned short sensor_id_reg_addr; - unsigned short sensor_id; - unsigned short sensor_id_mask; -}; - -enum msm_sensor_output_format_t { - MSM_SENSOR_BAYER, - MSM_SENSOR_YCBCR, - MSM_SENSOR_META, -}; - -struct cam_sensor_power_setting { - enum msm_camera_power_seq_type seq_type; - unsigned short seq_val; - long config_val; - unsigned short delay; - void *data[10]; -}; - -struct cam_sensor_board_info { - struct cam_camera_slave_info slave_info; - int32_t sensor_mount_angle; - int32_t secure_mode; - int modes_supported; - int32_t pos_roll; - int32_t pos_yaw; - int32_t pos_pitch; - int32_t subdev_id[SUB_MODULE_MAX]; - int32_t subdev_intf[SUB_MODULE_MAX]; - const char *misc_regulator; - struct cam_sensor_power_ctrl_t power_info; -}; - -enum msm_camera_vreg_name_t { - CAM_VDIG, - CAM_VIO, - CAM_VANA, - CAM_VAF, - CAM_V_CUSTOM1, - CAM_V_CUSTOM2, - CAM_VREG_MAX, -}; - -struct msm_camera_gpio_conf { - void *cam_gpiomux_conf_tbl; - uint8_t cam_gpiomux_conf_tbl_size; - struct gpio *cam_gpio_common_tbl; - uint8_t cam_gpio_common_tbl_size; - struct gpio *cam_gpio_req_tbl; - uint8_t cam_gpio_req_tbl_size; - uint32_t gpio_no_mux; - uint32_t *camera_off_table; - uint8_t camera_off_table_size; - uint32_t *camera_on_table; - uint8_t camera_on_table_size; - struct msm_camera_gpio_num_info *gpio_num_info; -}; - -/*for tof camera Begin*/ -enum EEPROM_DATA_OP_T{ - EEPROM_DEFAULT_DATA = 0, - EEPROM_INIT_DATA, - EEPROM_CONFIG_DATA, - EEPROM_STREAMON_DATA, - EEPROM_STREAMOFF_DATA, - EEPROM_OTHER_DATA, -}; -/*for tof camera End*/ -#endif /* _CAM_SENSOR_CMN_HEADER_ */ diff --git a/third_party/linux/include/media/cam_sync.h b/third_party/linux/include/media/cam_sync.h deleted file mode 100644 index 4a8781fc823d54..00000000000000 --- a/third_party/linux/include/media/cam_sync.h +++ /dev/null @@ -1,134 +0,0 @@ -#ifndef __UAPI_CAM_SYNC_H__ -#define __UAPI_CAM_SYNC_H__ - -#include -#include -#include -#include - -#define CAM_SYNC_DEVICE_NAME "cam_sync_device" - -/* V4L event which user space will subscribe to */ -#define CAM_SYNC_V4L_EVENT (V4L2_EVENT_PRIVATE_START + 0) - -/* Specific event ids to get notified in user space */ -#define CAM_SYNC_V4L_EVENT_ID_CB_TRIG 0 - -/* Size of opaque payload sent to kernel for safekeeping until signal time */ -#define CAM_SYNC_USER_PAYLOAD_SIZE 2 - -/* Device type for sync device needed for device discovery */ -#define CAM_SYNC_DEVICE_TYPE (MEDIA_ENT_F_OLD_BASE) - -#define CAM_SYNC_GET_PAYLOAD_PTR(ev, type) \ - (type *)((char *)ev.u.data + sizeof(struct cam_sync_ev_header)) - -#define CAM_SYNC_GET_HEADER_PTR(ev) \ - ((struct cam_sync_ev_header *)ev.u.data) - -#define CAM_SYNC_STATE_INVALID 0 -#define CAM_SYNC_STATE_ACTIVE 1 -#define CAM_SYNC_STATE_SIGNALED_SUCCESS 2 -#define CAM_SYNC_STATE_SIGNALED_ERROR 3 - -/** - * struct cam_sync_ev_header - Event header for sync event notification - * - * @sync_obj: Sync object - * @status: Status of the object - */ -struct cam_sync_ev_header { - int32_t sync_obj; - int32_t status; -}; - -/** - * struct cam_sync_info - Sync object creation information - * - * @name: Optional string representation of the sync object - * @sync_obj: Sync object returned after creation in kernel - */ -struct cam_sync_info { - char name[64]; - int32_t sync_obj; -}; - -/** - * struct cam_sync_signal - Sync object signaling struct - * - * @sync_obj: Sync object to be signaled - * @sync_state: State of the sync object to which it should be signaled - */ -struct cam_sync_signal { - int32_t sync_obj; - uint32_t sync_state; -}; - -/** - * struct cam_sync_merge - Merge information for sync objects - * - * @sync_objs: Pointer to sync objects - * @num_objs: Number of objects in the array - * @merged: Merged sync object - */ -struct cam_sync_merge { - __u64 sync_objs; - uint32_t num_objs; - int32_t merged; -}; - -/** - * struct cam_sync_userpayload_info - Payload info from user space - * - * @sync_obj: Sync object for which payload has to be registered for - * @reserved: Reserved - * @payload: Pointer to user payload - */ -struct cam_sync_userpayload_info { - int32_t sync_obj; - uint32_t reserved; - __u64 payload[CAM_SYNC_USER_PAYLOAD_SIZE]; -}; - -/** - * struct cam_sync_wait - Sync object wait information - * - * @sync_obj: Sync object to wait on - * @reserved: Reserved - * @timeout_ms: Timeout in milliseconds - */ -struct cam_sync_wait { - int32_t sync_obj; - uint32_t reserved; - uint64_t timeout_ms; -}; - -/** - * struct cam_private_ioctl_arg - Sync driver ioctl argument - * - * @id: IOCTL command id - * @size: Size of command payload - * @result: Result of command execution - * @reserved: Reserved - * @ioctl_ptr: Pointer to user data - */ -struct cam_private_ioctl_arg { - __u32 id; - __u32 size; - __u32 result; - __u32 reserved; - __u64 ioctl_ptr; -}; - -#define CAM_PRIVATE_IOCTL_CMD \ - _IOWR('V', BASE_VIDIOC_PRIVATE, struct cam_private_ioctl_arg) - -#define CAM_SYNC_CREATE 0 -#define CAM_SYNC_DESTROY 1 -#define CAM_SYNC_SIGNAL 2 -#define CAM_SYNC_MERGE 3 -#define CAM_SYNC_REGISTER_PAYLOAD 4 -#define CAM_SYNC_DEREGISTER_PAYLOAD 5 -#define CAM_SYNC_WAIT 6 - -#endif /* __UAPI_CAM_SYNC_H__ */ diff --git a/third_party/linux/include/msm_cam_sensor.h b/third_party/linux/include/msm_cam_sensor.h deleted file mode 100644 index c75d1fd5272444..00000000000000 --- a/third_party/linux/include/msm_cam_sensor.h +++ /dev/null @@ -1,829 +0,0 @@ -#ifndef __LINUX_MSM_CAM_SENSOR_H -#define __LINUX_MSM_CAM_SENSOR_H - -#ifdef MSM_CAMERA_BIONIC -#include -#endif - -//#include -#include "msm_camsensor_sdk.h" - -#include -#include -#ifdef CONFIG_COMPAT -#include -#endif - -#define I2C_SEQ_REG_SETTING_MAX 5 - -#define MSM_SENSOR_MCLK_8HZ 8000000 -#define MSM_SENSOR_MCLK_16HZ 16000000 -#define MSM_SENSOR_MCLK_24HZ 24000000 - -#define MAX_SENSOR_NAME 32 -#define MAX_ACTUATOR_AF_TOTAL_STEPS 1024 - -#define MAX_OIS_MOD_NAME_SIZE 32 -#define MAX_OIS_NAME_SIZE 32 -#define MAX_OIS_REG_SETTINGS 800 - -#define MOVE_NEAR 0 -#define MOVE_FAR 1 - -#define MSM_ACTUATOR_MOVE_SIGNED_FAR -1 -#define MSM_ACTUATOR_MOVE_SIGNED_NEAR 1 - -#define MAX_ACTUATOR_REGION 5 - -#define MAX_EEPROM_NAME 32 - -#define MAX_AF_ITERATIONS 3 -#define MAX_NUMBER_OF_STEPS 47 -#define MAX_REGULATOR 5 - -#define MSM_V4L2_PIX_FMT_META v4l2_fourcc('M', 'E', 'T', 'A') /* META */ -#define MSM_V4L2_PIX_FMT_SBGGR14 v4l2_fourcc('B', 'G', '1', '4') - /* 14 BGBG.. GRGR.. */ -#define MSM_V4L2_PIX_FMT_SGBRG14 v4l2_fourcc('G', 'B', '1', '4') - /* 14 GBGB.. RGRG.. */ -#define MSM_V4L2_PIX_FMT_SGRBG14 v4l2_fourcc('B', 'A', '1', '4') - /* 14 GRGR.. BGBG.. */ -#define MSM_V4L2_PIX_FMT_SRGGB14 v4l2_fourcc('R', 'G', '1', '4') - /* 14 RGRG.. GBGB.. */ - -enum flash_type { - LED_FLASH = 1, - STROBE_FLASH, - GPIO_FLASH -}; - -enum msm_sensor_resolution_t { - MSM_SENSOR_RES_FULL, - MSM_SENSOR_RES_QTR, - MSM_SENSOR_RES_2, - MSM_SENSOR_RES_3, - MSM_SENSOR_RES_4, - MSM_SENSOR_RES_5, - MSM_SENSOR_RES_6, - MSM_SENSOR_RES_7, - MSM_SENSOR_INVALID_RES, -}; - -enum msm_camera_stream_type_t { - MSM_CAMERA_STREAM_PREVIEW, - MSM_CAMERA_STREAM_SNAPSHOT, - MSM_CAMERA_STREAM_VIDEO, - MSM_CAMERA_STREAM_INVALID, -}; - -enum sensor_sub_module_t { - SUB_MODULE_SENSOR, - SUB_MODULE_CHROMATIX, - SUB_MODULE_ACTUATOR, - SUB_MODULE_EEPROM, - SUB_MODULE_LED_FLASH, - SUB_MODULE_STROBE_FLASH, - SUB_MODULE_CSID, - SUB_MODULE_CSID_3D, - SUB_MODULE_CSIPHY, - SUB_MODULE_CSIPHY_3D, - SUB_MODULE_OIS, - SUB_MODULE_EXT, - SUB_MODULE_MAX, -}; - -enum { - MSM_CAMERA_EFFECT_MODE_OFF, - MSM_CAMERA_EFFECT_MODE_MONO, - MSM_CAMERA_EFFECT_MODE_NEGATIVE, - MSM_CAMERA_EFFECT_MODE_SOLARIZE, - MSM_CAMERA_EFFECT_MODE_SEPIA, - MSM_CAMERA_EFFECT_MODE_POSTERIZE, - MSM_CAMERA_EFFECT_MODE_WHITEBOARD, - MSM_CAMERA_EFFECT_MODE_BLACKBOARD, - MSM_CAMERA_EFFECT_MODE_AQUA, - MSM_CAMERA_EFFECT_MODE_EMBOSS, - MSM_CAMERA_EFFECT_MODE_SKETCH, - MSM_CAMERA_EFFECT_MODE_NEON, - MSM_CAMERA_EFFECT_MODE_MAX -}; - -enum { - MSM_CAMERA_WB_MODE_AUTO, - MSM_CAMERA_WB_MODE_CUSTOM, - MSM_CAMERA_WB_MODE_INCANDESCENT, - MSM_CAMERA_WB_MODE_FLUORESCENT, - MSM_CAMERA_WB_MODE_WARM_FLUORESCENT, - MSM_CAMERA_WB_MODE_DAYLIGHT, - MSM_CAMERA_WB_MODE_CLOUDY_DAYLIGHT, - MSM_CAMERA_WB_MODE_TWILIGHT, - MSM_CAMERA_WB_MODE_SHADE, - MSM_CAMERA_WB_MODE_OFF, - MSM_CAMERA_WB_MODE_MAX -}; - -enum { - MSM_CAMERA_SCENE_MODE_OFF, - MSM_CAMERA_SCENE_MODE_AUTO, - MSM_CAMERA_SCENE_MODE_LANDSCAPE, - MSM_CAMERA_SCENE_MODE_SNOW, - MSM_CAMERA_SCENE_MODE_BEACH, - MSM_CAMERA_SCENE_MODE_SUNSET, - MSM_CAMERA_SCENE_MODE_NIGHT, - MSM_CAMERA_SCENE_MODE_PORTRAIT, - MSM_CAMERA_SCENE_MODE_BACKLIGHT, - MSM_CAMERA_SCENE_MODE_SPORTS, - MSM_CAMERA_SCENE_MODE_ANTISHAKE, - MSM_CAMERA_SCENE_MODE_FLOWERS, - MSM_CAMERA_SCENE_MODE_CANDLELIGHT, - MSM_CAMERA_SCENE_MODE_FIREWORKS, - MSM_CAMERA_SCENE_MODE_PARTY, - MSM_CAMERA_SCENE_MODE_NIGHT_PORTRAIT, - MSM_CAMERA_SCENE_MODE_THEATRE, - MSM_CAMERA_SCENE_MODE_ACTION, - MSM_CAMERA_SCENE_MODE_AR, - MSM_CAMERA_SCENE_MODE_FACE_PRIORITY, - MSM_CAMERA_SCENE_MODE_BARCODE, - MSM_CAMERA_SCENE_MODE_HDR, - MSM_CAMERA_SCENE_MODE_MAX -}; - -enum csid_cfg_type_t { - CSID_INIT, - CSID_CFG, - CSID_TESTMODE_CFG, - CSID_RELEASE, -}; - -enum csiphy_cfg_type_t { - CSIPHY_INIT, - CSIPHY_CFG, - CSIPHY_RELEASE, -}; - -enum camera_vreg_type { - VREG_TYPE_DEFAULT, - VREG_TYPE_CUSTOM, -}; - -enum sensor_af_t { - SENSOR_AF_FOCUSSED, - SENSOR_AF_NOT_FOCUSSED, -}; - -enum cci_i2c_master_t { - MASTER_0, - MASTER_1, - MASTER_MAX, -}; - -struct msm_camera_i2c_array_write_config { - struct msm_camera_i2c_reg_setting conf_array; - uint16_t slave_addr; -}; - -struct msm_camera_i2c_read_config { - uint16_t slave_addr; - uint16_t reg_addr; - enum msm_camera_i2c_reg_addr_type addr_type; - enum msm_camera_i2c_data_type data_type; - uint16_t data; -}; - -struct msm_camera_csi2_params { - struct msm_camera_csid_params csid_params; - struct msm_camera_csiphy_params csiphy_params; - uint8_t csi_clk_scale_enable; -}; - -struct msm_camera_csi_lane_params { - uint16_t csi_lane_assign; - uint16_t csi_lane_mask; -}; - -struct csi_lane_params_t { - uint16_t csi_lane_assign; - uint8_t csi_lane_mask; - uint8_t csi_if; - int8_t csid_core[2]; - uint8_t csi_phy_sel; -}; - -struct msm_sensor_info_t { - char sensor_name[MAX_SENSOR_NAME]; - uint32_t session_id; - int32_t subdev_id[SUB_MODULE_MAX]; - int32_t subdev_intf[SUB_MODULE_MAX]; - uint8_t is_mount_angle_valid; - uint32_t sensor_mount_angle; - int modes_supported; - enum camb_position_t position; -}; - -struct camera_vreg_t { - const char *reg_name; - int min_voltage; - int max_voltage; - int op_mode; - uint32_t delay; - const char *custom_vreg_name; - enum camera_vreg_type type; -}; - -struct sensorb_cfg_data { - int cfgtype; - union { - struct msm_sensor_info_t sensor_info; - struct msm_sensor_init_params sensor_init_params; - void *setting; - struct msm_sensor_i2c_sync_params sensor_i2c_sync_params; - } cfg; -}; - -struct csid_cfg_data { - enum csid_cfg_type_t cfgtype; - union { - uint32_t csid_version; - struct msm_camera_csid_params *csid_params; - struct msm_camera_csid_testmode_parms *csid_testmode_params; - } cfg; -}; - -struct csiphy_cfg_data { - enum csiphy_cfg_type_t cfgtype; - union { - struct msm_camera_csiphy_params *csiphy_params; - struct msm_camera_csi_lane_params *csi_lane_params; - } cfg; -}; - -enum eeprom_cfg_type_t { - CFG_EEPROM_GET_INFO, - CFG_EEPROM_GET_CAL_DATA, - CFG_EEPROM_READ_CAL_DATA, - CFG_EEPROM_WRITE_DATA, - CFG_EEPROM_GET_MM_INFO, - CFG_EEPROM_INIT, -}; - -struct eeprom_get_t { - uint32_t num_bytes; -}; - -struct eeprom_read_t { - uint8_t *dbuffer; - uint32_t num_bytes; -}; - -struct eeprom_write_t { - uint8_t *dbuffer; - uint32_t num_bytes; -}; - -struct eeprom_get_cmm_t { - uint32_t cmm_support; - uint32_t cmm_compression; - uint32_t cmm_size; -}; - -struct msm_eeprom_info_t { - struct msm_sensor_power_setting_array *power_setting_array; - enum i2c_freq_mode_t i2c_freq_mode; - struct msm_eeprom_memory_map_array *mem_map_array; -}; - -struct msm_eeprom_cfg_data { - enum eeprom_cfg_type_t cfgtype; - uint8_t is_supported; - union { - char eeprom_name[MAX_SENSOR_NAME]; - struct eeprom_get_t get_data; - struct eeprom_read_t read_data; - struct eeprom_write_t write_data; - struct eeprom_get_cmm_t get_cmm_data; - struct msm_eeprom_info_t eeprom_info; - } cfg; -}; - -#ifdef CONFIG_COMPAT -struct msm_sensor_power_setting32 { - enum msm_sensor_power_seq_type_t seq_type; - uint16_t seq_val; - compat_uint_t config_val; - uint16_t delay; - compat_uptr_t data[10]; -}; - -struct msm_sensor_power_setting_array32 { - struct msm_sensor_power_setting32 power_setting_a[MAX_POWER_CONFIG]; - compat_uptr_t power_setting; - uint16_t size; - struct msm_sensor_power_setting32 - power_down_setting_a[MAX_POWER_CONFIG]; - compat_uptr_t power_down_setting; - uint16_t size_down; -}; - -struct msm_camera_sensor_slave_info32 { - char sensor_name[32]; - char eeprom_name[32]; - char actuator_name[32]; - char ois_name[32]; - char flash_name[32]; - enum msm_sensor_camera_id_t camera_id; - uint16_t slave_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_camera_i2c_reg_addr_type addr_type; - struct msm_sensor_id_info_t sensor_id_info; - struct msm_sensor_power_setting_array32 power_setting_array; - uint8_t is_init_params_valid; - struct msm_sensor_init_params sensor_init_params; - enum msm_sensor_output_format_t output_format; -}; - -struct msm_camera_csid_lut_params32 { - uint8_t num_cid; - struct msm_camera_csid_vc_cfg vc_cfg_a[MAX_CID]; - compat_uptr_t vc_cfg[MAX_CID]; -}; - -struct msm_camera_csid_params32 { - uint8_t lane_cnt; - uint16_t lane_assign; - uint8_t phy_sel; - uint32_t csi_clk; - struct msm_camera_csid_lut_params32 lut_params; - uint8_t csi_3p_sel; -}; - -struct msm_camera_csi2_params32 { - struct msm_camera_csid_params32 csid_params; - struct msm_camera_csiphy_params csiphy_params; - uint8_t csi_clk_scale_enable; -}; - -struct csid_cfg_data32 { - enum csid_cfg_type_t cfgtype; - union { - uint32_t csid_version; - compat_uptr_t csid_params; - compat_uptr_t csid_testmode_params; - } cfg; -}; - -struct eeprom_read_t32 { - compat_uptr_t dbuffer; - uint32_t num_bytes; -}; - -struct eeprom_write_t32 { - compat_uptr_t dbuffer; - uint32_t num_bytes; -}; - -struct msm_eeprom_info_t32 { - compat_uptr_t power_setting_array; - enum i2c_freq_mode_t i2c_freq_mode; - compat_uptr_t mem_map_array; -}; - -struct msm_eeprom_cfg_data32 { - enum eeprom_cfg_type_t cfgtype; - uint8_t is_supported; - union { - char eeprom_name[MAX_SENSOR_NAME]; - struct eeprom_get_t get_data; - struct eeprom_read_t32 read_data; - struct eeprom_write_t32 write_data; - struct msm_eeprom_info_t32 eeprom_info; - } cfg; -}; - -struct msm_camera_i2c_seq_reg_setting32 { - compat_uptr_t reg_setting; - uint16_t size; - enum msm_camera_i2c_reg_addr_type addr_type; - uint16_t delay; -}; -#endif - -enum msm_sensor_cfg_type_t { - CFG_SET_SLAVE_INFO, - CFG_SLAVE_READ_I2C, - CFG_WRITE_I2C_ARRAY, - CFG_SLAVE_WRITE_I2C_ARRAY, - CFG_WRITE_I2C_SEQ_ARRAY, - CFG_POWER_UP, - CFG_POWER_DOWN, - CFG_SET_STOP_STREAM_SETTING, - CFG_GET_SENSOR_INFO, - CFG_GET_SENSOR_INIT_PARAMS, - CFG_SET_INIT_SETTING, - CFG_SET_RESOLUTION, - CFG_SET_STOP_STREAM, - CFG_SET_START_STREAM, - CFG_SET_SATURATION, - CFG_SET_CONTRAST, - CFG_SET_SHARPNESS, - CFG_SET_ISO, - CFG_SET_EXPOSURE_COMPENSATION, - CFG_SET_ANTIBANDING, - CFG_SET_BESTSHOT_MODE, - CFG_SET_EFFECT, - CFG_SET_WHITE_BALANCE, - CFG_SET_AUTOFOCUS, - CFG_CANCEL_AUTOFOCUS, - CFG_SET_STREAM_TYPE, - CFG_SET_I2C_SYNC_PARAM, - CFG_WRITE_I2C_ARRAY_ASYNC, - CFG_WRITE_I2C_ARRAY_SYNC, - CFG_WRITE_I2C_ARRAY_SYNC_BLOCK, -}; - -enum msm_actuator_cfg_type_t { - CFG_GET_ACTUATOR_INFO, - CFG_SET_ACTUATOR_INFO, - CFG_SET_DEFAULT_FOCUS, - CFG_MOVE_FOCUS, - CFG_SET_POSITION, - CFG_ACTUATOR_POWERDOWN, - CFG_ACTUATOR_POWERUP, - CFG_ACTUATOR_INIT, -}; - -enum msm_ois_cfg_type_t { - CFG_OIS_INIT, - CFG_OIS_POWERDOWN, - CFG_OIS_POWERUP, - CFG_OIS_CONTROL, - CFG_OIS_I2C_WRITE_SEQ_TABLE, -}; - -enum msm_ois_i2c_operation { - MSM_OIS_WRITE = 0, - MSM_OIS_POLL, -}; - -struct reg_settings_ois_t { - uint16_t reg_addr; - enum msm_camera_i2c_reg_addr_type addr_type; - uint32_t reg_data; - enum msm_camera_i2c_data_type data_type; - enum msm_ois_i2c_operation i2c_operation; - uint32_t delay; -#define OIS_REG_DATA_SEQ_MAX 128 - unsigned char reg_data_seq[OIS_REG_DATA_SEQ_MAX]; - uint32_t reg_data_seq_size; -}; - -struct msm_ois_params_t { - uint16_t data_size; - uint16_t setting_size; - uint32_t i2c_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_camera_i2c_reg_addr_type i2c_addr_type; - enum msm_camera_i2c_data_type i2c_data_type; - struct reg_settings_ois_t *settings; -}; - -struct msm_ois_set_info_t { - struct msm_ois_params_t ois_params; -}; - -struct msm_actuator_move_params_t { - int8_t dir; - int8_t sign_dir; - int16_t dest_step_pos; - int32_t num_steps; - uint16_t curr_lens_pos; - struct damping_params_t *ringing_params; -}; - -struct msm_actuator_tuning_params_t { - int16_t initial_code; - uint16_t pwd_step; - uint16_t region_size; - uint32_t total_steps; - struct region_params_t *region_params; -}; - -struct park_lens_data_t { - uint32_t damping_step; - uint32_t damping_delay; - uint32_t hw_params; - uint32_t max_step; -}; - -struct msm_actuator_params_t { - enum actuator_type act_type; - uint8_t reg_tbl_size; - uint16_t data_size; - uint16_t init_setting_size; - uint32_t i2c_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_actuator_addr_type i2c_addr_type; - enum msm_actuator_data_type i2c_data_type; - struct msm_actuator_reg_params_t *reg_tbl_params; - struct reg_settings_t *init_settings; - struct park_lens_data_t park_lens; -}; - -struct msm_actuator_set_info_t { - struct msm_actuator_params_t actuator_params; - struct msm_actuator_tuning_params_t af_tuning_params; -}; - -struct msm_actuator_get_info_t { - uint32_t focal_length_num; - uint32_t focal_length_den; - uint32_t f_number_num; - uint32_t f_number_den; - uint32_t f_pix_num; - uint32_t f_pix_den; - uint32_t total_f_dist_num; - uint32_t total_f_dist_den; - uint32_t hor_view_angle_num; - uint32_t hor_view_angle_den; - uint32_t ver_view_angle_num; - uint32_t ver_view_angle_den; -}; - -enum af_camera_name { - ACTUATOR_MAIN_CAM_0, - ACTUATOR_MAIN_CAM_1, - ACTUATOR_MAIN_CAM_2, - ACTUATOR_MAIN_CAM_3, - ACTUATOR_MAIN_CAM_4, - ACTUATOR_MAIN_CAM_5, - ACTUATOR_WEB_CAM_0, - ACTUATOR_WEB_CAM_1, - ACTUATOR_WEB_CAM_2, -}; - -struct msm_ois_cfg_data { - int cfgtype; - union { - struct msm_ois_set_info_t set_info; - struct msm_camera_i2c_seq_reg_setting *settings; - } cfg; -}; - -struct msm_actuator_set_position_t { - uint16_t number_of_steps; - uint32_t hw_params; - uint16_t pos[MAX_NUMBER_OF_STEPS]; - uint16_t delay[MAX_NUMBER_OF_STEPS]; -}; - -struct msm_actuator_cfg_data { - int cfgtype; - uint8_t is_af_supported; - union { - struct msm_actuator_move_params_t move; - struct msm_actuator_set_info_t set_info; - struct msm_actuator_get_info_t get_info; - struct msm_actuator_set_position_t setpos; - enum af_camera_name cam_name; - } cfg; -}; - -enum msm_camera_led_config_t { - MSM_CAMERA_LED_OFF, - MSM_CAMERA_LED_LOW, - MSM_CAMERA_LED_HIGH, - MSM_CAMERA_LED_INIT, - MSM_CAMERA_LED_RELEASE, -}; - -struct msm_camera_led_cfg_t { - enum msm_camera_led_config_t cfgtype; - int32_t torch_current[MAX_LED_TRIGGERS]; - int32_t flash_current[MAX_LED_TRIGGERS]; - int32_t flash_duration[MAX_LED_TRIGGERS]; -}; - -struct msm_flash_init_info_t { - enum msm_flash_driver_type flash_driver_type; - uint32_t slave_addr; - enum i2c_freq_mode_t i2c_freq_mode; - struct msm_sensor_power_setting_array *power_setting_array; - struct msm_camera_i2c_reg_setting_array *settings; -}; - -struct msm_flash_cfg_data_t { - enum msm_flash_cfg_type_t cfg_type; - int32_t flash_current[MAX_LED_TRIGGERS]; - int32_t flash_duration[MAX_LED_TRIGGERS]; - union { - struct msm_flash_init_info_t *flash_init_info; - struct msm_camera_i2c_reg_setting_array *settings; - } cfg; -}; - -/* sensor init structures and enums */ -enum msm_sensor_init_cfg_type_t { - CFG_SINIT_PROBE, - CFG_SINIT_PROBE_DONE, - CFG_SINIT_PROBE_WAIT_DONE, -}; - -struct sensor_init_cfg_data { - enum msm_sensor_init_cfg_type_t cfgtype; - struct msm_sensor_info_t probed_info; - char entity_name[MAX_SENSOR_NAME]; - union { - void *setting; - } cfg; -}; - -#define VIDIOC_MSM_SENSOR_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 1, struct sensorb_cfg_data) - -#define VIDIOC_MSM_SENSOR_RELEASE \ - _IO('V', BASE_VIDIOC_PRIVATE + 2) - -#define VIDIOC_MSM_SENSOR_GET_SUBDEV_ID \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 3, uint32_t) - -#define VIDIOC_MSM_CSIPHY_IO_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 4, struct csiphy_cfg_data) - -#define VIDIOC_MSM_CSID_IO_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 5, struct csid_cfg_data) - -#define VIDIOC_MSM_ACTUATOR_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 6, struct msm_actuator_cfg_data) - -#define VIDIOC_MSM_FLASH_LED_DATA_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 7, struct msm_camera_led_cfg_t) - -#define VIDIOC_MSM_EEPROM_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 8, struct msm_eeprom_cfg_data) - -#define VIDIOC_MSM_SENSOR_GET_AF_STATUS \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 9, uint32_t) - -#define VIDIOC_MSM_SENSOR_INIT_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 10, struct sensor_init_cfg_data) - -#define VIDIOC_MSM_OIS_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 11, struct msm_ois_cfg_data) - -#define VIDIOC_MSM_FLASH_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 13, struct msm_flash_cfg_data_t) - -#ifdef CONFIG_COMPAT -struct msm_camera_i2c_reg_setting32 { - compat_uptr_t reg_setting; - uint16_t size; - enum msm_camera_i2c_reg_addr_type addr_type; - enum msm_camera_i2c_data_type data_type; - uint16_t delay; -}; - -struct msm_camera_i2c_array_write_config32 { - struct msm_camera_i2c_reg_setting32 conf_array; - uint16_t slave_addr; -}; - -struct msm_actuator_tuning_params_t32 { - int16_t initial_code; - uint16_t pwd_step; - uint16_t region_size; - uint32_t total_steps; - compat_uptr_t region_params; -}; - -struct msm_actuator_params_t32 { - enum actuator_type act_type; - uint8_t reg_tbl_size; - uint16_t data_size; - uint16_t init_setting_size; - uint32_t i2c_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_actuator_addr_type i2c_addr_type; - enum msm_actuator_data_type i2c_data_type; - compat_uptr_t reg_tbl_params; - compat_uptr_t init_settings; - struct park_lens_data_t park_lens; -}; - -struct msm_actuator_set_info_t32 { - struct msm_actuator_params_t32 actuator_params; - struct msm_actuator_tuning_params_t32 af_tuning_params; -}; - -struct sensor_init_cfg_data32 { - enum msm_sensor_init_cfg_type_t cfgtype; - struct msm_sensor_info_t probed_info; - char entity_name[MAX_SENSOR_NAME]; - union { - compat_uptr_t setting; - } cfg; -}; - -struct msm_actuator_move_params_t32 { - int8_t dir; - int8_t sign_dir; - int16_t dest_step_pos; - int32_t num_steps; - uint16_t curr_lens_pos; - compat_uptr_t ringing_params; -}; - -struct msm_actuator_cfg_data32 { - int cfgtype; - uint8_t is_af_supported; - union { - struct msm_actuator_move_params_t32 move; - struct msm_actuator_set_info_t32 set_info; - struct msm_actuator_get_info_t get_info; - struct msm_actuator_set_position_t setpos; - enum af_camera_name cam_name; - } cfg; -}; - -struct csiphy_cfg_data32 { - enum csiphy_cfg_type_t cfgtype; - union { - compat_uptr_t csiphy_params; - compat_uptr_t csi_lane_params; - } cfg; -}; - -struct sensorb_cfg_data32 { - int cfgtype; - union { - struct msm_sensor_info_t sensor_info; - struct msm_sensor_init_params sensor_init_params; - compat_uptr_t setting; - struct msm_sensor_i2c_sync_params sensor_i2c_sync_params; - } cfg; -}; - -struct msm_ois_params_t32 { - uint16_t data_size; - uint16_t setting_size; - uint32_t i2c_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_camera_i2c_reg_addr_type i2c_addr_type; - enum msm_camera_i2c_data_type i2c_data_type; - compat_uptr_t settings; -}; - -struct msm_ois_set_info_t32 { - struct msm_ois_params_t32 ois_params; -}; - -struct msm_ois_cfg_data32 { - int cfgtype; - union { - struct msm_ois_set_info_t32 set_info; - compat_uptr_t settings; - } cfg; -}; - -struct msm_flash_init_info_t32 { - enum msm_flash_driver_type flash_driver_type; - uint32_t slave_addr; - enum i2c_freq_mode_t i2c_freq_mode; - compat_uptr_t power_setting_array; - compat_uptr_t settings; -}; - -struct msm_flash_cfg_data_t32 { - enum msm_flash_cfg_type_t cfg_type; - int32_t flash_current[MAX_LED_TRIGGERS]; - int32_t flash_duration[MAX_LED_TRIGGERS]; - union { - compat_uptr_t flash_init_info; - compat_uptr_t settings; - } cfg; -}; - -#define VIDIOC_MSM_ACTUATOR_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 6, struct msm_actuator_cfg_data32) - -#define VIDIOC_MSM_SENSOR_INIT_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 10, struct sensor_init_cfg_data32) - -#define VIDIOC_MSM_CSIPHY_IO_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 4, struct csiphy_cfg_data32) - -#define VIDIOC_MSM_SENSOR_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 1, struct sensorb_cfg_data32) - -#define VIDIOC_MSM_EEPROM_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 8, struct msm_eeprom_cfg_data32) - -#define VIDIOC_MSM_OIS_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 11, struct msm_ois_cfg_data32) - -#define VIDIOC_MSM_CSID_IO_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 5, struct csid_cfg_data32) - -#define VIDIOC_MSM_FLASH_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 13, struct msm_flash_cfg_data_t32) -#endif - -#endif /* __LINUX_MSM_CAM_SENSOR_H */ diff --git a/third_party/linux/include/msm_camsensor_sdk.h b/third_party/linux/include/msm_camsensor_sdk.h deleted file mode 100644 index 62a4da253c9345..00000000000000 --- a/third_party/linux/include/msm_camsensor_sdk.h +++ /dev/null @@ -1,386 +0,0 @@ -#ifndef __LINUX_MSM_CAMSENSOR_SDK_H -#define __LINUX_MSM_CAMSENSOR_SDK_H - -#define KVERSION 0x1 - -#define MAX_POWER_CONFIG 12 -#define GPIO_OUT_LOW (0 << 1) -#define GPIO_OUT_HIGH (1 << 1) -#define CSI_EMBED_DATA 0x12 -#define CSI_RESERVED_DATA_0 0x13 -#define CSI_YUV422_8 0x1E -#define CSI_RAW8 0x2A -#define CSI_RAW10 0x2B -#define CSI_RAW12 0x2C -#define CSI_DECODE_6BIT 0 -#define CSI_DECODE_8BIT 1 -#define CSI_DECODE_10BIT 2 -#define CSI_DECODE_12BIT 3 -#define CSI_DECODE_DPCM_10_8_10 5 -#define MAX_CID 16 -#define I2C_SEQ_REG_DATA_MAX 1024 -#define I2C_REG_DATA_MAX (8*1024) - -#define MSM_V4L2_PIX_FMT_META v4l2_fourcc('M', 'E', 'T', 'A') /* META */ -#define MSM_V4L2_PIX_FMT_SBGGR14 v4l2_fourcc('B', 'G', '1', '4') - /* 14 BGBG.. GRGR.. */ -#define MSM_V4L2_PIX_FMT_SGBRG14 v4l2_fourcc('G', 'B', '1', '4') - /* 14 GBGB.. RGRG.. */ -#define MSM_V4L2_PIX_FMT_SGRBG14 v4l2_fourcc('B', 'A', '1', '4') - /* 14 GRGR.. BGBG.. */ -#define MSM_V4L2_PIX_FMT_SRGGB14 v4l2_fourcc('R', 'G', '1', '4') - /* 14 RGRG.. GBGB.. */ - -#define MAX_ACTUATOR_REG_TBL_SIZE 8 -#define MAX_ACTUATOR_REGION 5 -#define NUM_ACTUATOR_DIR 2 -#define MAX_ACTUATOR_SCENARIO 8 -#define MAX_ACT_MOD_NAME_SIZE 32 -#define MAX_ACT_NAME_SIZE 32 -#define MAX_ACTUATOR_INIT_SET 120 -#define MAX_I2C_REG_SET 12 - -#define MAX_LED_TRIGGERS 3 - -#define MSM_EEPROM_MEMORY_MAP_MAX_SIZE 80 -#define MSM_EEPROM_MAX_MEM_MAP_CNT 8 - -enum msm_sensor_camera_id_t { - CAMERA_0, - CAMERA_1, - CAMERA_2, - CAMERA_3, - MAX_CAMERAS, -}; - -enum i2c_freq_mode_t { - I2C_STANDARD_MODE, - I2C_FAST_MODE, - I2C_CUSTOM_MODE, - I2C_FAST_PLUS_MODE, - I2C_MAX_MODES, -}; - -enum camb_position_t { - BACK_CAMERA_B, - FRONT_CAMERA_B, - AUX_CAMERA_B = 0x100, - INVALID_CAMERA_B, -}; - -enum msm_sensor_power_seq_type_t { - SENSOR_CLK, - SENSOR_GPIO, - SENSOR_VREG, - SENSOR_I2C_MUX, - SENSOR_I2C, -}; - -enum msm_camera_i2c_reg_addr_type { - MSM_CAMERA_I2C_BYTE_ADDR = 1, - MSM_CAMERA_I2C_WORD_ADDR, - MSM_CAMERA_I2C_3B_ADDR, - MSM_CAMERA_I2C_ADDR_TYPE_MAX, -}; - -enum msm_camera_i2c_data_type { - MSM_CAMERA_I2C_BYTE_DATA = 1, - MSM_CAMERA_I2C_WORD_DATA, - MSM_CAMERA_I2C_DWORD_DATA, - MSM_CAMERA_I2C_SET_BYTE_MASK, - MSM_CAMERA_I2C_UNSET_BYTE_MASK, - MSM_CAMERA_I2C_SET_WORD_MASK, - MSM_CAMERA_I2C_UNSET_WORD_MASK, - MSM_CAMERA_I2C_SET_BYTE_WRITE_MASK_DATA, - MSM_CAMERA_I2C_SEQ_DATA, - MSM_CAMERA_I2C_DATA_TYPE_MAX, -}; - -enum msm_sensor_power_seq_gpio_t { - SENSOR_GPIO_RESET, - SENSOR_GPIO_STANDBY, - SENSOR_GPIO_AF_PWDM, - SENSOR_GPIO_VIO, - SENSOR_GPIO_VANA, - SENSOR_GPIO_VDIG, - SENSOR_GPIO_VAF, - SENSOR_GPIO_FL_EN, - SENSOR_GPIO_FL_NOW, - SENSOR_GPIO_FL_RESET, - SENSOR_GPIO_CUSTOM1, - SENSOR_GPIO_CUSTOM2, - SENSOR_GPIO_MAX, -}; - -enum msm_camera_vreg_name_t { - CAM_VDIG, - CAM_VIO, - CAM_VANA, - CAM_VAF, - CAM_V_CUSTOM1, - CAM_V_CUSTOM2, - CAM_VREG_MAX, -}; - -enum msm_sensor_clk_type_t { - SENSOR_CAM_MCLK, - SENSOR_CAM_CLK, - SENSOR_CAM_CLK_MAX, -}; - -enum camerab_mode_t { - CAMERA_MODE_2D_B = (1<<0), - CAMERA_MODE_3D_B = (1<<1), - CAMERA_MODE_INVALID = (1<<2), -}; - -enum msm_actuator_data_type { - MSM_ACTUATOR_BYTE_DATA = 1, - MSM_ACTUATOR_WORD_DATA, -}; - -enum msm_actuator_addr_type { - MSM_ACTUATOR_BYTE_ADDR = 1, - MSM_ACTUATOR_WORD_ADDR, -}; - -enum msm_actuator_write_type { - MSM_ACTUATOR_WRITE_HW_DAMP, - MSM_ACTUATOR_WRITE_DAC, - MSM_ACTUATOR_WRITE, - MSM_ACTUATOR_WRITE_DIR_REG, - MSM_ACTUATOR_POLL, - MSM_ACTUATOR_READ_WRITE, -}; - -enum msm_actuator_i2c_operation { - MSM_ACT_WRITE = 0, - MSM_ACT_POLL, -}; - -enum actuator_type { - ACTUATOR_VCM, - ACTUATOR_PIEZO, - ACTUATOR_HVCM, - ACTUATOR_BIVCM, -}; - -enum msm_flash_driver_type { - FLASH_DRIVER_PMIC, - FLASH_DRIVER_I2C, - FLASH_DRIVER_GPIO, - FLASH_DRIVER_DEFAULT -}; - -enum msm_flash_cfg_type_t { - CFG_FLASH_INIT, - CFG_FLASH_RELEASE, - CFG_FLASH_OFF, - CFG_FLASH_LOW, - CFG_FLASH_HIGH, -}; - -enum msm_sensor_output_format_t { - MSM_SENSOR_BAYER, - MSM_SENSOR_YCBCR, - MSM_SENSOR_META, -}; - -struct msm_sensor_power_setting { - enum msm_sensor_power_seq_type_t seq_type; - unsigned short seq_val; - long config_val; - unsigned short delay; - void *data[10]; -}; - -struct msm_sensor_power_setting_array { - struct msm_sensor_power_setting power_setting_a[MAX_POWER_CONFIG]; - struct msm_sensor_power_setting *power_setting; - unsigned short size; - struct msm_sensor_power_setting power_down_setting_a[MAX_POWER_CONFIG]; - struct msm_sensor_power_setting *power_down_setting; - unsigned short size_down; -}; - -enum msm_camera_i2c_operation { - MSM_CAM_WRITE = 0, - MSM_CAM_POLL, - MSM_CAM_READ, -}; - -struct msm_sensor_i2c_sync_params { - unsigned int cid; - int csid; - unsigned short line; - unsigned short delay; -}; - -struct msm_camera_reg_settings_t { - uint16_t reg_addr; - enum msm_camera_i2c_reg_addr_type addr_type; - uint16_t reg_data; - enum msm_camera_i2c_data_type data_type; - enum msm_camera_i2c_operation i2c_operation; - uint16_t delay; -}; - -struct msm_eeprom_mem_map_t { - int slave_addr; - struct msm_camera_reg_settings_t - mem_settings[MSM_EEPROM_MEMORY_MAP_MAX_SIZE]; - int memory_map_size; -}; - -struct msm_eeprom_memory_map_array { - struct msm_eeprom_mem_map_t memory_map[MSM_EEPROM_MAX_MEM_MAP_CNT]; - uint32_t msm_size_of_max_mappings; -}; - -struct msm_sensor_init_params { - /* mask of modes supported: 2D, 3D */ - int modes_supported; - /* sensor position: front, back */ - enum camb_position_t position; - /* sensor mount angle */ - unsigned int sensor_mount_angle; -}; - -struct msm_sensor_id_info_t { - unsigned short sensor_id_reg_addr; - unsigned short sensor_id; - unsigned short sensor_id_mask; - // added in LeEco - unsigned char module_id; - unsigned char vcm_id; -}; - -struct msm_camera_sensor_slave_info { - char sensor_name[32]; - char eeprom_name[32]; - char actuator_name[32]; - char ois_name[32]; - char flash_name[32]; - enum msm_sensor_camera_id_t camera_id; - unsigned short slave_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_camera_i2c_reg_addr_type addr_type; - struct msm_sensor_id_info_t sensor_id_info; - struct msm_sensor_power_setting_array power_setting_array; - unsigned char is_init_params_valid; - struct msm_sensor_init_params sensor_init_params; - enum msm_sensor_output_format_t output_format; -}; - -struct msm_camera_i2c_reg_array { - unsigned short reg_addr; - unsigned short reg_data; - unsigned int delay; -}; - -struct msm_camera_i2c_reg_setting { - struct msm_camera_i2c_reg_array *reg_setting; - unsigned short size; - enum msm_camera_i2c_reg_addr_type addr_type; - enum msm_camera_i2c_data_type data_type; - unsigned short delay; -}; - -struct msm_camera_csid_vc_cfg { - unsigned char cid; - unsigned char dt; - unsigned char decode_format; -}; - -struct msm_camera_csid_lut_params { - unsigned char num_cid; - struct msm_camera_csid_vc_cfg vc_cfg_a[MAX_CID]; - struct msm_camera_csid_vc_cfg *vc_cfg[MAX_CID]; -}; - -struct msm_camera_csid_params { - unsigned char lane_cnt; - unsigned short lane_assign; - unsigned char phy_sel; - unsigned int csi_clk; - struct msm_camera_csid_lut_params lut_params; - unsigned char csi_3p_sel; -}; - -struct msm_camera_csid_testmode_parms { - unsigned int num_bytes_per_line; - unsigned int num_lines; - unsigned int h_blanking_count; - unsigned int v_blanking_count; - unsigned int payload_mode; -}; - -struct msm_camera_csiphy_params { - unsigned char lane_cnt; - unsigned char settle_cnt; - unsigned short lane_mask; - unsigned char combo_mode; - unsigned char csid_core; - unsigned int csiphy_clk; - unsigned char csi_3phase; -}; - -struct msm_camera_i2c_seq_reg_array { - unsigned short reg_addr; - unsigned char reg_data[I2C_SEQ_REG_DATA_MAX]; - unsigned short reg_data_size; -}; - -struct msm_camera_i2c_seq_reg_setting { - struct msm_camera_i2c_seq_reg_array *reg_setting; - unsigned short size; - enum msm_camera_i2c_reg_addr_type addr_type; - unsigned short delay; -}; - -struct msm_actuator_reg_params_t { - enum msm_actuator_write_type reg_write_type; - unsigned int hw_mask; - unsigned short reg_addr; - unsigned short hw_shift; - unsigned short data_shift; - unsigned short data_type; - unsigned short addr_type; - unsigned short reg_data; - unsigned short delay; -}; - - -struct damping_params_t { - unsigned int damping_step; - unsigned int damping_delay; - unsigned int hw_params; -}; - -struct region_params_t { - /* [0] = ForwardDirection Macro boundary - [1] = ReverseDirection Inf boundary - */ - unsigned short step_bound[2]; - unsigned short code_per_step; - /* qvalue for converting float type numbers to integer format */ - unsigned int qvalue; -}; - -struct reg_settings_t { - unsigned short reg_addr; - enum msm_actuator_addr_type addr_type; - unsigned short reg_data; - enum msm_actuator_data_type data_type; - enum msm_actuator_i2c_operation i2c_operation; - unsigned int delay; -}; - -struct msm_camera_i2c_reg_setting_array { - struct msm_camera_i2c_reg_array reg_setting_a[MAX_I2C_REG_SET]; - unsigned short size; - enum msm_camera_i2c_reg_addr_type addr_type; - enum msm_camera_i2c_data_type data_type; - unsigned short delay; -}; -#endif /* __LINUX_MSM_CAM_SENSOR_H */ diff --git a/third_party/linux/include/msm_ion.h b/third_party/linux/include/msm_ion.h deleted file mode 100644 index d5caed5eb36e1b..00000000000000 --- a/third_party/linux/include/msm_ion.h +++ /dev/null @@ -1,211 +0,0 @@ -#ifndef _UAPI_MSM_ION_H -#define _UAPI_MSM_ION_H - -#include - -enum msm_ion_heap_types { - ION_HEAP_TYPE_MSM_START = ION_HEAP_TYPE_CUSTOM + 1, - ION_HEAP_TYPE_SECURE_DMA = ION_HEAP_TYPE_MSM_START, - ION_HEAP_TYPE_SYSTEM_SECURE, - ION_HEAP_TYPE_HYP_CMA, - /* - * if you add a heap type here you should also add it to - * heap_types_info[] in msm_ion.c - */ -}; - -/** - * These are the only ids that should be used for Ion heap ids. - * The ids listed are the order in which allocation will be attempted - * if specified. Don't swap the order of heap ids unless you know what - * you are doing! - * Id's are spaced by purpose to allow new Id's to be inserted in-between (for - * possible fallbacks) - */ - -enum ion_heap_ids { - INVALID_HEAP_ID = -1, - ION_CP_MM_HEAP_ID = 8, - ION_SECURE_HEAP_ID = 9, - ION_SECURE_DISPLAY_HEAP_ID = 10, - ION_CP_MFC_HEAP_ID = 12, - ION_CP_WB_HEAP_ID = 16, /* 8660 only */ - ION_CAMERA_HEAP_ID = 20, /* 8660 only */ - ION_SYSTEM_CONTIG_HEAP_ID = 21, - ION_ADSP_HEAP_ID = 22, - ION_PIL1_HEAP_ID = 23, /* Currently used for other PIL images */ - ION_SF_HEAP_ID = 24, - ION_SYSTEM_HEAP_ID = 25, - ION_PIL2_HEAP_ID = 26, /* Currently used for modem firmware images */ - ION_QSECOM_HEAP_ID = 27, - ION_AUDIO_HEAP_ID = 28, - - ION_MM_FIRMWARE_HEAP_ID = 29, - - ION_HEAP_ID_RESERVED = 31 /** Bit reserved for ION_FLAG_SECURE flag */ -}; - -/* - * The IOMMU heap is deprecated! Here are some aliases for backwards - * compatibility: - */ -#define ION_IOMMU_HEAP_ID ION_SYSTEM_HEAP_ID -#define ION_HEAP_TYPE_IOMMU ION_HEAP_TYPE_SYSTEM - -enum ion_fixed_position { - NOT_FIXED, - FIXED_LOW, - FIXED_MIDDLE, - FIXED_HIGH, -}; - -enum cp_mem_usage { - VIDEO_BITSTREAM = 0x1, - VIDEO_PIXEL = 0x2, - VIDEO_NONPIXEL = 0x3, - DISPLAY_SECURE_CP_USAGE = 0x4, - CAMERA_SECURE_CP_USAGE = 0x5, - MAX_USAGE = 0x6, - UNKNOWN = 0x7FFFFFFF, -}; - -/** - * Flags to be used when allocating from the secure heap for - * content protection - */ -#define ION_FLAG_CP_TOUCH (1 << 17) -#define ION_FLAG_CP_BITSTREAM (1 << 18) -#define ION_FLAG_CP_PIXEL (1 << 19) -#define ION_FLAG_CP_NON_PIXEL (1 << 20) -#define ION_FLAG_CP_CAMERA (1 << 21) -#define ION_FLAG_CP_HLOS (1 << 22) -#define ION_FLAG_CP_HLOS_FREE (1 << 23) -#define ION_FLAG_CP_SEC_DISPLAY (1 << 25) -#define ION_FLAG_CP_APP (1 << 26) - -/** - * Flag to allow non continguous allocation of memory from secure - * heap - */ -#define ION_FLAG_ALLOW_NON_CONTIG (1 << 24) - -/** - * Flag to use when allocating to indicate that a heap is secure. - */ -#define ION_FLAG_SECURE (1 << ION_HEAP_ID_RESERVED) - -/** - * Flag for clients to force contiguous memort allocation - * - * Use of this flag is carefully monitored! - */ -#define ION_FLAG_FORCE_CONTIGUOUS (1 << 30) - -/* - * Used in conjunction with heap which pool memory to force an allocation - * to come from the page allocator directly instead of from the pool allocation - */ -#define ION_FLAG_POOL_FORCE_ALLOC (1 << 16) - - -#define ION_FLAG_POOL_PREFETCH (1 << 27) - -/** -* Deprecated! Please use the corresponding ION_FLAG_* -*/ -#define ION_SECURE ION_FLAG_SECURE -#define ION_FORCE_CONTIGUOUS ION_FLAG_FORCE_CONTIGUOUS - -/** - * Macro should be used with ion_heap_ids defined above. - */ -#define ION_HEAP(bit) (1 << (bit)) - -#define ION_ADSP_HEAP_NAME "adsp" -#define ION_SYSTEM_HEAP_NAME "system" -#define ION_VMALLOC_HEAP_NAME ION_SYSTEM_HEAP_NAME -#define ION_KMALLOC_HEAP_NAME "kmalloc" -#define ION_AUDIO_HEAP_NAME "audio" -#define ION_SF_HEAP_NAME "sf" -#define ION_MM_HEAP_NAME "mm" -#define ION_CAMERA_HEAP_NAME "camera_preview" -#define ION_IOMMU_HEAP_NAME "iommu" -#define ION_MFC_HEAP_NAME "mfc" -#define ION_WB_HEAP_NAME "wb" -#define ION_MM_FIRMWARE_HEAP_NAME "mm_fw" -#define ION_PIL1_HEAP_NAME "pil_1" -#define ION_PIL2_HEAP_NAME "pil_2" -#define ION_QSECOM_HEAP_NAME "qsecom" -#define ION_SECURE_HEAP_NAME "secure_heap" -#define ION_SECURE_DISPLAY_HEAP_NAME "secure_display" - -#define ION_SET_CACHED(__cache) (__cache | ION_FLAG_CACHED) -#define ION_SET_UNCACHED(__cache) (__cache & ~ION_FLAG_CACHED) - -#define ION_IS_CACHED(__flags) ((__flags) & ION_FLAG_CACHED) - -/* struct ion_flush_data - data passed to ion for flushing caches - * - * @handle: handle with data to flush - * @fd: fd to flush - * @vaddr: userspace virtual address mapped with mmap - * @offset: offset into the handle to flush - * @length: length of handle to flush - * - * Performs cache operations on the handle. If p is the start address - * of the handle, p + offset through p + offset + length will have - * the cache operations performed - */ -struct ion_flush_data { - ion_user_handle_t handle; - int fd; - void *vaddr; - unsigned int offset; - unsigned int length; -}; - -struct ion_prefetch_regions { - unsigned int vmid; - size_t *sizes; - unsigned int nr_sizes; -}; - -struct ion_prefetch_data { - int heap_id; - unsigned long len; - /* Is unsigned long bad? 32bit compiler vs 64 bit compiler*/ - struct ion_prefetch_regions *regions; - unsigned int nr_regions; -}; - -#define ION_IOC_MSM_MAGIC 'M' - -/** - * DOC: ION_IOC_CLEAN_CACHES - clean the caches - * - * Clean the caches of the handle specified. - */ -#define ION_IOC_CLEAN_CACHES _IOWR(ION_IOC_MSM_MAGIC, 0, \ - struct ion_flush_data) -/** - * DOC: ION_IOC_INV_CACHES - invalidate the caches - * - * Invalidate the caches of the handle specified. - */ -#define ION_IOC_INV_CACHES _IOWR(ION_IOC_MSM_MAGIC, 1, \ - struct ion_flush_data) -/** - * DOC: ION_IOC_CLEAN_INV_CACHES - clean and invalidate the caches - * - * Clean and invalidate the caches of the handle specified. - */ -#define ION_IOC_CLEAN_INV_CACHES _IOWR(ION_IOC_MSM_MAGIC, 2, \ - struct ion_flush_data) - -#define ION_IOC_PREFETCH _IOWR(ION_IOC_MSM_MAGIC, 3, \ - struct ion_prefetch_data) - -#define ION_IOC_DRAIN _IOWR(ION_IOC_MSM_MAGIC, 4, \ - struct ion_prefetch_data) - -#endif diff --git a/third_party/linux/include/msm_kgsl.h b/third_party/linux/include/msm_kgsl.h deleted file mode 100644 index 93582eb066db77..00000000000000 --- a/third_party/linux/include/msm_kgsl.h +++ /dev/null @@ -1,1449 +0,0 @@ -#ifndef _UAPI_MSM_KGSL_H -#define _UAPI_MSM_KGSL_H - -#include -#include - -/* - * The KGSL version has proven not to be very useful in userspace if features - * are cherry picked into other trees out of order so it is frozen as of 3.14. - * It is left here for backwards compatabilty and as a reminder that - * software releases are never linear. Also, I like pie. - */ - -#define KGSL_VERSION_MAJOR 3 -#define KGSL_VERSION_MINOR 14 - -/* - * We have traditionally mixed context and issueibcmds / command batch flags - * together into a big flag stew. This worked fine until we started adding a - * lot more command batch flags and we started running out of bits. Turns out - * we have a bit of room in the context type / priority mask that we could use - * for command batches, but that means we need to split out the flags into two - * coherent sets. - * - * If any future definitions are for both context and cmdbatch add both defines - * and link the cmdbatch to the context define as we do below. Otherwise feel - * free to add exclusive bits to either set. - */ - -/* --- context flags --- */ -#define KGSL_CONTEXT_SAVE_GMEM 0x00000001 -#define KGSL_CONTEXT_NO_GMEM_ALLOC 0x00000002 -/* This is a cmdbatch exclusive flag - use the CMDBATCH equivalent instead */ -#define KGSL_CONTEXT_SUBMIT_IB_LIST 0x00000004 -#define KGSL_CONTEXT_CTX_SWITCH 0x00000008 -#define KGSL_CONTEXT_PREAMBLE 0x00000010 -#define KGSL_CONTEXT_TRASH_STATE 0x00000020 -#define KGSL_CONTEXT_PER_CONTEXT_TS 0x00000040 -#define KGSL_CONTEXT_USER_GENERATED_TS 0x00000080 -/* This is a cmdbatch exclusive flag - use the CMDBATCH equivalent instead */ -#define KGSL_CONTEXT_END_OF_FRAME 0x00000100 -#define KGSL_CONTEXT_NO_FAULT_TOLERANCE 0x00000200 -/* This is a cmdbatch exclusive flag - use the CMDBATCH equivalent instead */ -#define KGSL_CONTEXT_SYNC 0x00000400 -#define KGSL_CONTEXT_PWR_CONSTRAINT 0x00000800 - -#define KGSL_CONTEXT_PRIORITY_MASK 0x0000F000 -#define KGSL_CONTEXT_PRIORITY_SHIFT 12 -#define KGSL_CONTEXT_PRIORITY_UNDEF 0 - -#define KGSL_CONTEXT_IFH_NOP 0x00010000 -#define KGSL_CONTEXT_SECURE 0x00020000 - -#define KGSL_CONTEXT_PREEMPT_STYLE_MASK 0x0E000000 -#define KGSL_CONTEXT_PREEMPT_STYLE_SHIFT 25 -#define KGSL_CONTEXT_PREEMPT_STYLE_DEFAULT 0x0 -#define KGSL_CONTEXT_PREEMPT_STYLE_RINGBUFFER 0x1 -#define KGSL_CONTEXT_PREEMPT_STYLE_FINEGRAIN 0x2 - -#define KGSL_CONTEXT_TYPE_MASK 0x01F00000 -#define KGSL_CONTEXT_TYPE_SHIFT 20 -#define KGSL_CONTEXT_TYPE_ANY 0 -#define KGSL_CONTEXT_TYPE_GL 1 -#define KGSL_CONTEXT_TYPE_CL 2 -#define KGSL_CONTEXT_TYPE_C2D 3 -#define KGSL_CONTEXT_TYPE_RS 4 -#define KGSL_CONTEXT_TYPE_UNKNOWN 0x1E - -#define KGSL_CONTEXT_INVALID 0xffffffff - -/* - * --- command batch flags --- - * The bits that are linked to a KGSL_CONTEXT equivalent are either legacy - * definitions or bits that are valid for both contexts and cmdbatches. To be - * safe the other 8 bits that are still available in the context field should be - * omitted here in case we need to share - the other bits are available for - * cmdbatch only flags as needed - */ -#define KGSL_CMDBATCH_MEMLIST 0x00000001 -#define KGSL_CMDBATCH_MARKER 0x00000002 -#define KGSL_CMDBATCH_SUBMIT_IB_LIST KGSL_CONTEXT_SUBMIT_IB_LIST /* 0x004 */ -#define KGSL_CMDBATCH_CTX_SWITCH KGSL_CONTEXT_CTX_SWITCH /* 0x008 */ -#define KGSL_CMDBATCH_PROFILING 0x00000010 -#define KGSL_CMDBATCH_PROFILING_KTIME 0x00000020 -#define KGSL_CMDBATCH_END_OF_FRAME KGSL_CONTEXT_END_OF_FRAME /* 0x100 */ -#define KGSL_CMDBATCH_SYNC KGSL_CONTEXT_SYNC /* 0x400 */ -#define KGSL_CMDBATCH_PWR_CONSTRAINT KGSL_CONTEXT_PWR_CONSTRAINT /* 0x800 */ - -/* - * Reserve bits [16:19] and bits [28:31] for possible bits shared between - * contexts and command batches. Update this comment as new flags are added. - */ - -/* - * gpu_command_object flags - these flags communicate the type of command or - * memory object being submitted for a GPU command - */ - -/* Flags for GPU command objects */ -#define KGSL_CMDLIST_IB 0x00000001U -#define KGSL_CMDLIST_CTXTSWITCH_PREAMBLE 0x00000002U -#define KGSL_CMDLIST_IB_PREAMBLE 0x00000004U - -/* Flags for GPU command memory objects */ -#define KGSL_OBJLIST_MEMOBJ 0x00000008U -#define KGSL_OBJLIST_PROFILE 0x00000010U - -/* Flags for GPU command sync points */ -#define KGSL_CMD_SYNCPOINT_TYPE_TIMESTAMP 0 -#define KGSL_CMD_SYNCPOINT_TYPE_FENCE 1 - -/* --- Memory allocation flags --- */ - -/* General allocation hints */ -#define KGSL_MEMFLAGS_SECURE 0x00000008ULL -#define KGSL_MEMFLAGS_GPUREADONLY 0x01000000U -#define KGSL_MEMFLAGS_GPUWRITEONLY 0x02000000U -#define KGSL_MEMFLAGS_FORCE_32BIT 0x100000000ULL - -/* Memory caching hints */ -#define KGSL_CACHEMODE_MASK 0x0C000000U -#define KGSL_CACHEMODE_SHIFT 26 - -#define KGSL_CACHEMODE_WRITECOMBINE 0 -#define KGSL_CACHEMODE_UNCACHED 1 -#define KGSL_CACHEMODE_WRITETHROUGH 2 -#define KGSL_CACHEMODE_WRITEBACK 3 - -#define KGSL_MEMFLAGS_USE_CPU_MAP 0x10000000ULL - -/* Memory types for which allocations are made */ -#define KGSL_MEMTYPE_MASK 0x0000FF00 -#define KGSL_MEMTYPE_SHIFT 8 - -#define KGSL_MEMTYPE_OBJECTANY 0 -#define KGSL_MEMTYPE_FRAMEBUFFER 1 -#define KGSL_MEMTYPE_RENDERBUFFER 2 -#define KGSL_MEMTYPE_ARRAYBUFFER 3 -#define KGSL_MEMTYPE_ELEMENTARRAYBUFFER 4 -#define KGSL_MEMTYPE_VERTEXARRAYBUFFER 5 -#define KGSL_MEMTYPE_TEXTURE 6 -#define KGSL_MEMTYPE_SURFACE 7 -#define KGSL_MEMTYPE_EGL_SURFACE 8 -#define KGSL_MEMTYPE_GL 9 -#define KGSL_MEMTYPE_CL 10 -#define KGSL_MEMTYPE_CL_BUFFER_MAP 11 -#define KGSL_MEMTYPE_CL_BUFFER_NOMAP 12 -#define KGSL_MEMTYPE_CL_IMAGE_MAP 13 -#define KGSL_MEMTYPE_CL_IMAGE_NOMAP 14 -#define KGSL_MEMTYPE_CL_KERNEL_STACK 15 -#define KGSL_MEMTYPE_COMMAND 16 -#define KGSL_MEMTYPE_2D 17 -#define KGSL_MEMTYPE_EGL_IMAGE 18 -#define KGSL_MEMTYPE_EGL_SHADOW 19 -#define KGSL_MEMTYPE_MULTISAMPLE 20 -#define KGSL_MEMTYPE_KERNEL 255 - -/* - * Alignment hint, passed as the power of 2 exponent. - * i.e 4k (2^12) would be 12, 64k (2^16)would be 16. - */ -#define KGSL_MEMALIGN_MASK 0x00FF0000 -#define KGSL_MEMALIGN_SHIFT 16 - -enum kgsl_user_mem_type { - KGSL_USER_MEM_TYPE_PMEM = 0x00000000, - KGSL_USER_MEM_TYPE_ASHMEM = 0x00000001, - KGSL_USER_MEM_TYPE_ADDR = 0x00000002, - KGSL_USER_MEM_TYPE_ION = 0x00000003, - /* - * ION type is retained for backwards compatibilty but Ion buffers are - * dma-bufs so try to use that naming if we can - */ - KGSL_USER_MEM_TYPE_DMABUF = 0x00000003, - KGSL_USER_MEM_TYPE_MAX = 0x00000007, -}; -#define KGSL_MEMFLAGS_USERMEM_MASK 0x000000e0 -#define KGSL_MEMFLAGS_USERMEM_SHIFT 5 - -/* - * Unfortunately, enum kgsl_user_mem_type starts at 0 which does not - * leave a good value for allocated memory. In the flags we use - * 0 to indicate allocated memory and thus need to add 1 to the enum - * values. - */ -#define KGSL_USERMEM_FLAG(x) (((x) + 1) << KGSL_MEMFLAGS_USERMEM_SHIFT) - -#define KGSL_MEMFLAGS_NOT_USERMEM 0 -#define KGSL_MEMFLAGS_USERMEM_PMEM KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_PMEM) -#define KGSL_MEMFLAGS_USERMEM_ASHMEM \ - KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ASHMEM) -#define KGSL_MEMFLAGS_USERMEM_ADDR KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ADDR) -#define KGSL_MEMFLAGS_USERMEM_ION KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ION) - -/* --- generic KGSL flag values --- */ - -#define KGSL_FLAGS_NORMALMODE 0x00000000 -#define KGSL_FLAGS_SAFEMODE 0x00000001 -#define KGSL_FLAGS_INITIALIZED0 0x00000002 -#define KGSL_FLAGS_INITIALIZED 0x00000004 -#define KGSL_FLAGS_STARTED 0x00000008 -#define KGSL_FLAGS_ACTIVE 0x00000010 -#define KGSL_FLAGS_RESERVED0 0x00000020 -#define KGSL_FLAGS_RESERVED1 0x00000040 -#define KGSL_FLAGS_RESERVED2 0x00000080 -#define KGSL_FLAGS_SOFT_RESET 0x00000100 -#define KGSL_FLAGS_PER_CONTEXT_TIMESTAMPS 0x00000200 - -/* Server Side Sync Timeout in milliseconds */ -#define KGSL_SYNCOBJ_SERVER_TIMEOUT 2000 - -/* - * Reset status values for context - */ -enum kgsl_ctx_reset_stat { - KGSL_CTX_STAT_NO_ERROR = 0x00000000, - KGSL_CTX_STAT_GUILTY_CONTEXT_RESET_EXT = 0x00000001, - KGSL_CTX_STAT_INNOCENT_CONTEXT_RESET_EXT = 0x00000002, - KGSL_CTX_STAT_UNKNOWN_CONTEXT_RESET_EXT = 0x00000003 -}; - -#define KGSL_CONVERT_TO_MBPS(val) \ - (val*1000*1000U) - -/* device id */ -enum kgsl_deviceid { - KGSL_DEVICE_3D0 = 0x00000000, - KGSL_DEVICE_MAX -}; - -struct kgsl_devinfo { - - unsigned int device_id; - /* chip revision id - * coreid:8 majorrev:8 minorrev:8 patch:8 - */ - unsigned int chip_id; - unsigned int mmu_enabled; - unsigned long gmem_gpubaseaddr; - /* - * This field contains the adreno revision - * number 200, 205, 220, etc... - */ - unsigned int gpu_id; - size_t gmem_sizebytes; -}; - -/* - * struct kgsl_devmemstore - this structure defines the region of memory - * that can be mmap()ed from this driver. The timestamp fields are volatile - * because they are written by the GPU - * @soptimestamp: Start of pipeline timestamp written by GPU before the - * commands in concern are processed - * @sbz: Unused, kept for 8 byte alignment - * @eoptimestamp: End of pipeline timestamp written by GPU after the - * commands in concern are processed - * @sbz2: Unused, kept for 8 byte alignment - * @preempted: Indicates if the context was preempted - * @sbz3: Unused, kept for 8 byte alignment - * @ref_wait_ts: Timestamp on which to generate interrupt, unused now. - * @sbz4: Unused, kept for 8 byte alignment - * @current_context: The current context the GPU is working on - * @sbz5: Unused, kept for 8 byte alignment - */ -struct kgsl_devmemstore { - volatile unsigned int soptimestamp; - unsigned int sbz; - volatile unsigned int eoptimestamp; - unsigned int sbz2; - volatile unsigned int preempted; - unsigned int sbz3; - volatile unsigned int ref_wait_ts; - unsigned int sbz4; - unsigned int current_context; - unsigned int sbz5; -}; - -#define KGSL_MEMSTORE_OFFSET(ctxt_id, field) \ - ((ctxt_id)*sizeof(struct kgsl_devmemstore) + \ - offsetof(struct kgsl_devmemstore, field)) - -/* timestamp id*/ -enum kgsl_timestamp_type { - KGSL_TIMESTAMP_CONSUMED = 0x00000001, /* start-of-pipeline timestamp */ - KGSL_TIMESTAMP_RETIRED = 0x00000002, /* end-of-pipeline timestamp*/ - KGSL_TIMESTAMP_QUEUED = 0x00000003, -}; - -/* property types - used with kgsl_device_getproperty */ -#define KGSL_PROP_DEVICE_INFO 0x1 -#define KGSL_PROP_DEVICE_SHADOW 0x2 -#define KGSL_PROP_DEVICE_POWER 0x3 -#define KGSL_PROP_SHMEM 0x4 -#define KGSL_PROP_SHMEM_APERTURES 0x5 -#define KGSL_PROP_MMU_ENABLE 0x6 -#define KGSL_PROP_INTERRUPT_WAITS 0x7 -#define KGSL_PROP_VERSION 0x8 -#define KGSL_PROP_GPU_RESET_STAT 0x9 -#define KGSL_PROP_PWRCTRL 0xE -#define KGSL_PROP_PWR_CONSTRAINT 0x12 -#define KGSL_PROP_UCHE_GMEM_VADDR 0x13 -#define KGSL_PROP_SP_GENERIC_MEM 0x14 -#define KGSL_PROP_UCODE_VERSION 0x15 -#define KGSL_PROP_GPMU_VERSION 0x16 -#define KGSL_PROP_DEVICE_BITNESS 0x18 - -struct kgsl_shadowprop { - unsigned long gpuaddr; - size_t size; - unsigned int flags; /* contains KGSL_FLAGS_ values */ -}; - -struct kgsl_version { - unsigned int drv_major; - unsigned int drv_minor; - unsigned int dev_major; - unsigned int dev_minor; -}; - -struct kgsl_sp_generic_mem { - uint64_t local; - uint64_t pvt; -}; - -struct kgsl_ucode_version { - unsigned int pfp; - unsigned int pm4; -}; - -struct kgsl_gpmu_version { - unsigned int major; - unsigned int minor; - unsigned int features; -}; - -/* Performance counter groups */ - -#define KGSL_PERFCOUNTER_GROUP_CP 0x0 -#define KGSL_PERFCOUNTER_GROUP_RBBM 0x1 -#define KGSL_PERFCOUNTER_GROUP_PC 0x2 -#define KGSL_PERFCOUNTER_GROUP_VFD 0x3 -#define KGSL_PERFCOUNTER_GROUP_HLSQ 0x4 -#define KGSL_PERFCOUNTER_GROUP_VPC 0x5 -#define KGSL_PERFCOUNTER_GROUP_TSE 0x6 -#define KGSL_PERFCOUNTER_GROUP_RAS 0x7 -#define KGSL_PERFCOUNTER_GROUP_UCHE 0x8 -#define KGSL_PERFCOUNTER_GROUP_TP 0x9 -#define KGSL_PERFCOUNTER_GROUP_SP 0xA -#define KGSL_PERFCOUNTER_GROUP_RB 0xB -#define KGSL_PERFCOUNTER_GROUP_PWR 0xC -#define KGSL_PERFCOUNTER_GROUP_VBIF 0xD -#define KGSL_PERFCOUNTER_GROUP_VBIF_PWR 0xE -#define KGSL_PERFCOUNTER_GROUP_MH 0xF -#define KGSL_PERFCOUNTER_GROUP_PA_SU 0x10 -#define KGSL_PERFCOUNTER_GROUP_SQ 0x11 -#define KGSL_PERFCOUNTER_GROUP_SX 0x12 -#define KGSL_PERFCOUNTER_GROUP_TCF 0x13 -#define KGSL_PERFCOUNTER_GROUP_TCM 0x14 -#define KGSL_PERFCOUNTER_GROUP_TCR 0x15 -#define KGSL_PERFCOUNTER_GROUP_L2 0x16 -#define KGSL_PERFCOUNTER_GROUP_VSC 0x17 -#define KGSL_PERFCOUNTER_GROUP_CCU 0x18 -#define KGSL_PERFCOUNTER_GROUP_LRZ 0x19 -#define KGSL_PERFCOUNTER_GROUP_CMP 0x1A -#define KGSL_PERFCOUNTER_GROUP_ALWAYSON 0x1B -#define KGSL_PERFCOUNTER_GROUP_SP_PWR 0x1C -#define KGSL_PERFCOUNTER_GROUP_TP_PWR 0x1D -#define KGSL_PERFCOUNTER_GROUP_RB_PWR 0x1E -#define KGSL_PERFCOUNTER_GROUP_CCU_PWR 0x1F -#define KGSL_PERFCOUNTER_GROUP_UCHE_PWR 0x20 -#define KGSL_PERFCOUNTER_GROUP_CP_PWR 0x21 -#define KGSL_PERFCOUNTER_GROUP_GPMU_PWR 0x22 -#define KGSL_PERFCOUNTER_GROUP_ALWAYSON_PWR 0x23 -#define KGSL_PERFCOUNTER_GROUP_MAX 0x24 - -#define KGSL_PERFCOUNTER_NOT_USED 0xFFFFFFFF -#define KGSL_PERFCOUNTER_BROKEN 0xFFFFFFFE - -/* structure holds list of ibs */ -struct kgsl_ibdesc { - unsigned long gpuaddr; - unsigned long __pad; - size_t sizedwords; - unsigned int ctrl; -}; - -/** - * struct kgsl_cmdbatch_profiling_buffer - * @wall_clock_s: Ringbuffer submission time (seconds). - * If KGSL_CMDBATCH_PROFILING_KTIME is set, time is provided - * in kernel clocks, otherwise wall clock time is used. - * @wall_clock_ns: Ringbuffer submission time (nanoseconds). - * If KGSL_CMDBATCH_PROFILING_KTIME is set time is provided - * in kernel clocks, otherwise wall clock time is used. - * @gpu_ticks_queued: GPU ticks at ringbuffer submission - * @gpu_ticks_submitted: GPU ticks when starting cmdbatch execution - * @gpu_ticks_retired: GPU ticks when finishing cmdbatch execution - * - * This structure defines the profiling buffer used to measure cmdbatch - * execution time - */ -struct kgsl_cmdbatch_profiling_buffer { - uint64_t wall_clock_s; - uint64_t wall_clock_ns; - uint64_t gpu_ticks_queued; - uint64_t gpu_ticks_submitted; - uint64_t gpu_ticks_retired; -}; - -/* ioctls */ -#define KGSL_IOC_TYPE 0x09 - -/* get misc info about the GPU - type should be a value from enum kgsl_property_type - value points to a structure that varies based on type - sizebytes is sizeof() that structure - for KGSL_PROP_DEVICE_INFO, use struct kgsl_devinfo - this structure contaings hardware versioning info. - for KGSL_PROP_DEVICE_SHADOW, use struct kgsl_shadowprop - this is used to find mmap() offset and sizes for mapping - struct kgsl_memstore into userspace. -*/ -struct kgsl_device_getproperty { - unsigned int type; - void __user *value; - size_t sizebytes; -}; - -#define IOCTL_KGSL_DEVICE_GETPROPERTY \ - _IOWR(KGSL_IOC_TYPE, 0x2, struct kgsl_device_getproperty) - -/* IOCTL_KGSL_DEVICE_READ (0x3) - removed 03/2012 - */ - -/* block until the GPU has executed past a given timestamp - * timeout is in milliseconds. - */ -struct kgsl_device_waittimestamp { - unsigned int timestamp; - unsigned int timeout; -}; - -#define IOCTL_KGSL_DEVICE_WAITTIMESTAMP \ - _IOW(KGSL_IOC_TYPE, 0x6, struct kgsl_device_waittimestamp) - -struct kgsl_device_waittimestamp_ctxtid { - unsigned int context_id; - unsigned int timestamp; - unsigned int timeout; -}; - -#define IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID \ - _IOW(KGSL_IOC_TYPE, 0x7, struct kgsl_device_waittimestamp_ctxtid) - -/* DEPRECATED: issue indirect commands to the GPU. - * drawctxt_id must have been created with IOCTL_KGSL_DRAWCTXT_CREATE - * ibaddr and sizedwords must specify a subset of a buffer created - * with IOCTL_KGSL_SHAREDMEM_FROM_PMEM - * flags may be a mask of KGSL_CONTEXT_ values - * timestamp is a returned counter value which can be passed to - * other ioctls to determine when the commands have been executed by - * the GPU. - * - * This fucntion is deprecated - consider using IOCTL_KGSL_SUBMIT_COMMANDS - * instead - */ -struct kgsl_ringbuffer_issueibcmds { - unsigned int drawctxt_id; - unsigned long ibdesc_addr; - unsigned int numibs; - unsigned int timestamp; /*output param */ - unsigned int flags; -}; - -#define IOCTL_KGSL_RINGBUFFER_ISSUEIBCMDS \ - _IOWR(KGSL_IOC_TYPE, 0x10, struct kgsl_ringbuffer_issueibcmds) - -/* read the most recently executed timestamp value - * type should be a value from enum kgsl_timestamp_type - */ -struct kgsl_cmdstream_readtimestamp { - unsigned int type; - unsigned int timestamp; /*output param */ -}; - -#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_OLD \ - _IOR(KGSL_IOC_TYPE, 0x11, struct kgsl_cmdstream_readtimestamp) - -#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP \ - _IOWR(KGSL_IOC_TYPE, 0x11, struct kgsl_cmdstream_readtimestamp) - -/* free memory when the GPU reaches a given timestamp. - * gpuaddr specify a memory region created by a - * IOCTL_KGSL_SHAREDMEM_FROM_PMEM call - * type should be a value from enum kgsl_timestamp_type - */ -struct kgsl_cmdstream_freememontimestamp { - unsigned long gpuaddr; - unsigned int type; - unsigned int timestamp; -}; - -#define IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP \ - _IOW(KGSL_IOC_TYPE, 0x12, struct kgsl_cmdstream_freememontimestamp) - -/* Previous versions of this header had incorrectly defined - IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP as a read-only ioctl instead - of a write only ioctl. To ensure binary compatability, the following - #define will be used to intercept the incorrect ioctl -*/ - -#define IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP_OLD \ - _IOR(KGSL_IOC_TYPE, 0x12, struct kgsl_cmdstream_freememontimestamp) - -/* create a draw context, which is used to preserve GPU state. - * The flags field may contain a mask KGSL_CONTEXT_* values - */ -struct kgsl_drawctxt_create { - unsigned int flags; - unsigned int drawctxt_id; /*output param */ -}; - -#define IOCTL_KGSL_DRAWCTXT_CREATE \ - _IOWR(KGSL_IOC_TYPE, 0x13, struct kgsl_drawctxt_create) - -/* destroy a draw context */ -struct kgsl_drawctxt_destroy { - unsigned int drawctxt_id; -}; - -#define IOCTL_KGSL_DRAWCTXT_DESTROY \ - _IOW(KGSL_IOC_TYPE, 0x14, struct kgsl_drawctxt_destroy) - -/* add a block of pmem, fb, ashmem or user allocated address - * into the GPU address space */ -struct kgsl_map_user_mem { - int fd; - unsigned long gpuaddr; /*output param */ - size_t len; - size_t offset; - unsigned long hostptr; /*input param */ - enum kgsl_user_mem_type memtype; - unsigned int flags; -}; - -#define IOCTL_KGSL_MAP_USER_MEM \ - _IOWR(KGSL_IOC_TYPE, 0x15, struct kgsl_map_user_mem) - -struct kgsl_cmdstream_readtimestamp_ctxtid { - unsigned int context_id; - unsigned int type; - unsigned int timestamp; /*output param */ -}; - -#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID \ - _IOWR(KGSL_IOC_TYPE, 0x16, struct kgsl_cmdstream_readtimestamp_ctxtid) - -struct kgsl_cmdstream_freememontimestamp_ctxtid { - unsigned int context_id; - unsigned long gpuaddr; - unsigned int type; - unsigned int timestamp; -}; - -#define IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP_CTXTID \ - _IOW(KGSL_IOC_TYPE, 0x17, \ - struct kgsl_cmdstream_freememontimestamp_ctxtid) - -/* add a block of pmem or fb into the GPU address space */ -struct kgsl_sharedmem_from_pmem { - int pmem_fd; - unsigned long gpuaddr; /*output param */ - unsigned int len; - unsigned int offset; -}; - -#define IOCTL_KGSL_SHAREDMEM_FROM_PMEM \ - _IOWR(KGSL_IOC_TYPE, 0x20, struct kgsl_sharedmem_from_pmem) - -/* remove memory from the GPU's address space */ -struct kgsl_sharedmem_free { - unsigned long gpuaddr; -}; - -#define IOCTL_KGSL_SHAREDMEM_FREE \ - _IOW(KGSL_IOC_TYPE, 0x21, struct kgsl_sharedmem_free) - -struct kgsl_cff_user_event { - unsigned char cff_opcode; - unsigned int op1; - unsigned int op2; - unsigned int op3; - unsigned int op4; - unsigned int op5; - unsigned int __pad[2]; -}; - -#define IOCTL_KGSL_CFF_USER_EVENT \ - _IOW(KGSL_IOC_TYPE, 0x31, struct kgsl_cff_user_event) - -struct kgsl_gmem_desc { - unsigned int x; - unsigned int y; - unsigned int width; - unsigned int height; - unsigned int pitch; -}; - -struct kgsl_buffer_desc { - void *hostptr; - unsigned long gpuaddr; - int size; - unsigned int format; - unsigned int pitch; - unsigned int enabled; -}; - -struct kgsl_bind_gmem_shadow { - unsigned int drawctxt_id; - struct kgsl_gmem_desc gmem_desc; - unsigned int shadow_x; - unsigned int shadow_y; - struct kgsl_buffer_desc shadow_buffer; - unsigned int buffer_id; -}; - -#define IOCTL_KGSL_DRAWCTXT_BIND_GMEM_SHADOW \ - _IOW(KGSL_IOC_TYPE, 0x22, struct kgsl_bind_gmem_shadow) - -/* add a block of memory into the GPU address space */ - -/* - * IOCTL_KGSL_SHAREDMEM_FROM_VMALLOC deprecated 09/2012 - * use IOCTL_KGSL_GPUMEM_ALLOC instead - */ - -struct kgsl_sharedmem_from_vmalloc { - unsigned long gpuaddr; /*output param */ - unsigned int hostptr; - unsigned int flags; -}; - -#define IOCTL_KGSL_SHAREDMEM_FROM_VMALLOC \ - _IOWR(KGSL_IOC_TYPE, 0x23, struct kgsl_sharedmem_from_vmalloc) - -/* - * This is being deprecated in favor of IOCTL_KGSL_GPUMEM_CACHE_SYNC which - * supports both directions (flush and invalidate). This code will still - * work, but by definition it will do a flush of the cache which might not be - * what you want to have happen on a buffer following a GPU operation. It is - * safer to go with IOCTL_KGSL_GPUMEM_CACHE_SYNC - */ - -#define IOCTL_KGSL_SHAREDMEM_FLUSH_CACHE \ - _IOW(KGSL_IOC_TYPE, 0x24, struct kgsl_sharedmem_free) - -struct kgsl_drawctxt_set_bin_base_offset { - unsigned int drawctxt_id; - unsigned int offset; -}; - -#define IOCTL_KGSL_DRAWCTXT_SET_BIN_BASE_OFFSET \ - _IOW(KGSL_IOC_TYPE, 0x25, struct kgsl_drawctxt_set_bin_base_offset) - -enum kgsl_cmdwindow_type { - KGSL_CMDWINDOW_MIN = 0x00000000, - KGSL_CMDWINDOW_2D = 0x00000000, - KGSL_CMDWINDOW_3D = 0x00000001, /* legacy */ - KGSL_CMDWINDOW_MMU = 0x00000002, - KGSL_CMDWINDOW_ARBITER = 0x000000FF, - KGSL_CMDWINDOW_MAX = 0x000000FF, -}; - -/* write to the command window */ -struct kgsl_cmdwindow_write { - enum kgsl_cmdwindow_type target; - unsigned int addr; - unsigned int data; -}; - -#define IOCTL_KGSL_CMDWINDOW_WRITE \ - _IOW(KGSL_IOC_TYPE, 0x2e, struct kgsl_cmdwindow_write) - -struct kgsl_gpumem_alloc { - unsigned long gpuaddr; /* output param */ - size_t size; - unsigned int flags; -}; - -#define IOCTL_KGSL_GPUMEM_ALLOC \ - _IOWR(KGSL_IOC_TYPE, 0x2f, struct kgsl_gpumem_alloc) - -struct kgsl_cff_syncmem { - unsigned long gpuaddr; - size_t len; - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_CFF_SYNCMEM \ - _IOW(KGSL_IOC_TYPE, 0x30, struct kgsl_cff_syncmem) - -/* - * A timestamp event allows the user space to register an action following an - * expired timestamp. Note IOCTL_KGSL_TIMESTAMP_EVENT has been redefined to - * _IOWR to support fences which need to return a fd for the priv parameter. - */ - -struct kgsl_timestamp_event { - int type; /* Type of event (see list below) */ - unsigned int timestamp; /* Timestamp to trigger event on */ - unsigned int context_id; /* Context for the timestamp */ - void __user *priv; /* Pointer to the event specific blob */ - size_t len; /* Size of the event specific blob */ -}; - -#define IOCTL_KGSL_TIMESTAMP_EVENT_OLD \ - _IOW(KGSL_IOC_TYPE, 0x31, struct kgsl_timestamp_event) - -/* A genlock timestamp event releases an existing lock on timestamp expire */ - -#define KGSL_TIMESTAMP_EVENT_GENLOCK 1 - -struct kgsl_timestamp_event_genlock { - int handle; /* Handle of the genlock lock to release */ -}; - -/* A fence timestamp event releases an existing lock on timestamp expire */ - -#define KGSL_TIMESTAMP_EVENT_FENCE 2 - -struct kgsl_timestamp_event_fence { - int fence_fd; /* Fence to signal */ -}; - -/* - * Set a property within the kernel. Uses the same structure as - * IOCTL_KGSL_GETPROPERTY - */ - -#define IOCTL_KGSL_SETPROPERTY \ - _IOW(KGSL_IOC_TYPE, 0x32, struct kgsl_device_getproperty) - -#define IOCTL_KGSL_TIMESTAMP_EVENT \ - _IOWR(KGSL_IOC_TYPE, 0x33, struct kgsl_timestamp_event) - -/** - * struct kgsl_gpumem_alloc_id - argument to IOCTL_KGSL_GPUMEM_ALLOC_ID - * @id: returned id value for this allocation. - * @flags: mask of KGSL_MEM* values requested and actual flags on return. - * @size: requested size of the allocation and actual size on return. - * @mmapsize: returned size to pass to mmap() which may be larger than 'size' - * @gpuaddr: returned GPU address for the allocation - * - * Allocate memory for access by the GPU. The flags and size fields are echoed - * back by the kernel, so that the caller can know if the request was - * adjusted. - * - * Supported flags: - * KGSL_MEMFLAGS_GPUREADONLY: the GPU will be unable to write to the buffer - * KGSL_MEMTYPE*: usage hint for debugging aid - * KGSL_MEMALIGN*: alignment hint, may be ignored or adjusted by the kernel. - * KGSL_MEMFLAGS_USE_CPU_MAP: If set on call and return, the returned GPU - * address will be 0. Calling mmap() will set the GPU address. - */ -struct kgsl_gpumem_alloc_id { - unsigned int id; - unsigned int flags; - size_t size; - size_t mmapsize; - unsigned long gpuaddr; -/* private: reserved for future use*/ - unsigned long __pad[2]; -}; - -#define IOCTL_KGSL_GPUMEM_ALLOC_ID \ - _IOWR(KGSL_IOC_TYPE, 0x34, struct kgsl_gpumem_alloc_id) - -/** - * struct kgsl_gpumem_free_id - argument to IOCTL_KGSL_GPUMEM_FREE_ID - * @id: GPU allocation id to free - * - * Free an allocation by id, in case a GPU address has not been assigned or - * is unknown. Freeing an allocation by id with this ioctl or by GPU address - * with IOCTL_KGSL_SHAREDMEM_FREE are equivalent. - */ -struct kgsl_gpumem_free_id { - unsigned int id; -/* private: reserved for future use*/ - unsigned int __pad; -}; - -#define IOCTL_KGSL_GPUMEM_FREE_ID \ - _IOWR(KGSL_IOC_TYPE, 0x35, struct kgsl_gpumem_free_id) - -/** - * struct kgsl_gpumem_get_info - argument to IOCTL_KGSL_GPUMEM_GET_INFO - * @gpuaddr: GPU address to query. Also set on return. - * @id: GPU allocation id to query. Also set on return. - * @flags: returned mask of KGSL_MEM* values. - * @size: returned size of the allocation. - * @mmapsize: returned size to pass mmap(), which may be larger than 'size' - * @useraddr: returned address of the userspace mapping for this buffer - * - * This ioctl allows querying of all user visible attributes of an existing - * allocation, by either the GPU address or the id returned by a previous - * call to IOCTL_KGSL_GPUMEM_ALLOC_ID. Legacy allocation ioctls may not - * return all attributes so this ioctl can be used to look them up if needed. - * - */ -struct kgsl_gpumem_get_info { - unsigned long gpuaddr; - unsigned int id; - unsigned int flags; - size_t size; - size_t mmapsize; - unsigned long useraddr; -/* private: reserved for future use*/ - unsigned long __pad[4]; -}; - -#define IOCTL_KGSL_GPUMEM_GET_INFO\ - _IOWR(KGSL_IOC_TYPE, 0x36, struct kgsl_gpumem_get_info) - -/** - * struct kgsl_gpumem_sync_cache - argument to IOCTL_KGSL_GPUMEM_SYNC_CACHE - * @gpuaddr: GPU address of the buffer to sync. - * @id: id of the buffer to sync. Either gpuaddr or id is sufficient. - * @op: a mask of KGSL_GPUMEM_CACHE_* values - * @offset: offset into the buffer - * @length: number of bytes starting from offset to perform - * the cache operation on - * - * Sync the L2 cache for memory headed to and from the GPU - this replaces - * KGSL_SHAREDMEM_FLUSH_CACHE since it can handle cache management for both - * directions - * - */ -struct kgsl_gpumem_sync_cache { - unsigned long gpuaddr; - unsigned int id; - unsigned int op; - size_t offset; - size_t length; -}; - -#define KGSL_GPUMEM_CACHE_CLEAN (1 << 0) -#define KGSL_GPUMEM_CACHE_TO_GPU KGSL_GPUMEM_CACHE_CLEAN - -#define KGSL_GPUMEM_CACHE_INV (1 << 1) -#define KGSL_GPUMEM_CACHE_FROM_GPU KGSL_GPUMEM_CACHE_INV - -#define KGSL_GPUMEM_CACHE_FLUSH \ - (KGSL_GPUMEM_CACHE_CLEAN | KGSL_GPUMEM_CACHE_INV) - -/* Flag to ensure backwards compatibility of kgsl_gpumem_sync_cache struct */ -#define KGSL_GPUMEM_CACHE_RANGE (1 << 31U) - -#define IOCTL_KGSL_GPUMEM_SYNC_CACHE \ - _IOW(KGSL_IOC_TYPE, 0x37, struct kgsl_gpumem_sync_cache) - -/** - * struct kgsl_perfcounter_get - argument to IOCTL_KGSL_PERFCOUNTER_GET - * @groupid: Performance counter group ID - * @countable: Countable to select within the group - * @offset: Return offset of the reserved LO counter - * @offset_hi: Return offset of the reserved HI counter - * - * Get an available performance counter from a specified groupid. The offset - * of the performance counter will be returned after successfully assigning - * the countable to the counter for the specified group. An error will be - * returned and an offset of 0 if the groupid is invalid or there are no - * more counters left. After successfully getting a perfcounter, the user - * must call kgsl_perfcounter_put(groupid, contable) when finished with - * the perfcounter to clear up perfcounter resources. - * - */ -struct kgsl_perfcounter_get { - unsigned int groupid; - unsigned int countable; - unsigned int offset; - unsigned int offset_hi; -/* private: reserved for future use */ - unsigned int __pad; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_PERFCOUNTER_GET \ - _IOWR(KGSL_IOC_TYPE, 0x38, struct kgsl_perfcounter_get) - -/** - * struct kgsl_perfcounter_put - argument to IOCTL_KGSL_PERFCOUNTER_PUT - * @groupid: Performance counter group ID - * @countable: Countable to release within the group - * - * Put an allocated performance counter to allow others to have access to the - * resource that was previously taken. This is only to be called after - * successfully getting a performance counter from kgsl_perfcounter_get(). - * - */ -struct kgsl_perfcounter_put { - unsigned int groupid; - unsigned int countable; -/* private: reserved for future use */ - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_PERFCOUNTER_PUT \ - _IOW(KGSL_IOC_TYPE, 0x39, struct kgsl_perfcounter_put) - -/** - * struct kgsl_perfcounter_query - argument to IOCTL_KGSL_PERFCOUNTER_QUERY - * @groupid: Performance counter group ID - * @countable: Return active countables array - * @size: Size of active countables array - * @max_counters: Return total number counters for the group ID - * - * Query the available performance counters given a groupid. The array - * *countables is used to return the current active countables in counters. - * The size of the array is passed in so the kernel will only write at most - * size or counter->size for the group id. The total number of available - * counters for the group ID is returned in max_counters. - * If the array or size passed in are invalid, then only the maximum number - * of counters will be returned, no data will be written to *countables. - * If the groupid is invalid an error code will be returned. - * - */ -struct kgsl_perfcounter_query { - unsigned int groupid; - /* Array to return the current countable for up to size counters */ - unsigned int __user *countables; - unsigned int count; - unsigned int max_counters; -/* private: reserved for future use */ - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_PERFCOUNTER_QUERY \ - _IOWR(KGSL_IOC_TYPE, 0x3A, struct kgsl_perfcounter_query) - -/** - * struct kgsl_perfcounter_query - argument to IOCTL_KGSL_PERFCOUNTER_QUERY - * @groupid: Performance counter group IDs - * @countable: Performance counter countable IDs - * @value: Return performance counter reads - * @size: Size of all arrays (groupid/countable pair and return value) - * - * Read in the current value of a performance counter given by the groupid - * and countable. - * - */ - -struct kgsl_perfcounter_read_group { - unsigned int groupid; - unsigned int countable; - unsigned long long value; -}; - -struct kgsl_perfcounter_read { - struct kgsl_perfcounter_read_group __user *reads; - unsigned int count; -/* private: reserved for future use */ - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_PERFCOUNTER_READ \ - _IOWR(KGSL_IOC_TYPE, 0x3B, struct kgsl_perfcounter_read) -/* - * struct kgsl_gpumem_sync_cache_bulk - argument to - * IOCTL_KGSL_GPUMEM_SYNC_CACHE_BULK - * @id_list: list of GPU buffer ids of the buffers to sync - * @count: number of GPU buffer ids in id_list - * @op: a mask of KGSL_GPUMEM_CACHE_* values - * - * Sync the cache for memory headed to and from the GPU. Certain - * optimizations can be made on the cache operation based on the total - * size of the working set of memory to be managed. - */ -struct kgsl_gpumem_sync_cache_bulk { - unsigned int __user *id_list; - unsigned int count; - unsigned int op; -/* private: reserved for future use */ - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_GPUMEM_SYNC_CACHE_BULK \ - _IOWR(KGSL_IOC_TYPE, 0x3C, struct kgsl_gpumem_sync_cache_bulk) - -/* - * struct kgsl_cmd_syncpoint_timestamp - * @context_id: ID of a KGSL context - * @timestamp: GPU timestamp - * - * This structure defines a syncpoint comprising a context/timestamp pair. A - * list of these may be passed by IOCTL_KGSL_SUBMIT_COMMANDS to define - * dependencies that must be met before the command can be submitted to the - * hardware - */ -struct kgsl_cmd_syncpoint_timestamp { - unsigned int context_id; - unsigned int timestamp; -}; - -struct kgsl_cmd_syncpoint_fence { - int fd; -}; - -/** - * struct kgsl_cmd_syncpoint - Define a sync point for a command batch - * @type: type of sync point defined here - * @priv: Pointer to the type specific buffer - * @size: Size of the type specific buffer - * - * This structure contains pointers defining a specific command sync point. - * The pointer and size should point to a type appropriate structure. - */ -struct kgsl_cmd_syncpoint { - int type; - void __user *priv; - size_t size; -}; - -/* Flag to indicate that the cmdlist may contain memlists */ -#define KGSL_IBDESC_MEMLIST 0x1 - -/* Flag to point out the cmdbatch profiling buffer in the memlist */ -#define KGSL_IBDESC_PROFILING_BUFFER 0x2 - -/** - * struct kgsl_submit_commands - Argument to IOCTL_KGSL_SUBMIT_COMMANDS - * @context_id: KGSL context ID that owns the commands - * @flags: - * @cmdlist: User pointer to a list of kgsl_ibdesc structures - * @numcmds: Number of commands listed in cmdlist - * @synclist: User pointer to a list of kgsl_cmd_syncpoint structures - * @numsyncs: Number of sync points listed in synclist - * @timestamp: On entry the a user defined timestamp, on exist the timestamp - * assigned to the command batch - * - * This structure specifies a command to send to the GPU hardware. This is - * similar to kgsl_issueibcmds expect that it doesn't support the legacy way to - * submit IB lists and it adds sync points to block the IB until the - * dependencies are satisified. This entry point is the new and preferred way - * to submit commands to the GPU. The memory list can be used to specify all - * memory that is referrenced in the current set of commands. - */ - -struct kgsl_submit_commands { - unsigned int context_id; - unsigned int flags; - struct kgsl_ibdesc __user *cmdlist; - unsigned int numcmds; - struct kgsl_cmd_syncpoint __user *synclist; - unsigned int numsyncs; - unsigned int timestamp; -/* private: reserved for future use */ - unsigned int __pad[4]; -}; - -#define IOCTL_KGSL_SUBMIT_COMMANDS \ - _IOWR(KGSL_IOC_TYPE, 0x3D, struct kgsl_submit_commands) - -/** - * struct kgsl_device_constraint - device constraint argument - * @context_id: KGSL context ID - * @type: type of constraint i.e pwrlevel/none - * @data: constraint data - * @size: size of the constraint data - */ -struct kgsl_device_constraint { - unsigned int type; - unsigned int context_id; - void __user *data; - size_t size; -}; - -/* Constraint Type*/ -#define KGSL_CONSTRAINT_NONE 0 -#define KGSL_CONSTRAINT_PWRLEVEL 1 - -/* PWRLEVEL constraint level*/ -/* set to min frequency */ -#define KGSL_CONSTRAINT_PWR_MIN 0 -/* set to max frequency */ -#define KGSL_CONSTRAINT_PWR_MAX 1 - -struct kgsl_device_constraint_pwrlevel { - unsigned int level; -}; - -/** - * struct kgsl_syncsource_create - Argument to IOCTL_KGSL_SYNCSOURCE_CREATE - * @id: returned id for the syncsource that was created. - * - * This ioctl creates a userspace sync timeline. - */ - -struct kgsl_syncsource_create { - unsigned int id; -/* private: reserved for future use */ - unsigned int __pad[3]; -}; - -#define IOCTL_KGSL_SYNCSOURCE_CREATE \ - _IOWR(KGSL_IOC_TYPE, 0x40, struct kgsl_syncsource_create) - -/** - * struct kgsl_syncsource_destroy - Argument to IOCTL_KGSL_SYNCSOURCE_DESTROY - * @id: syncsource id to destroy - * - * This ioctl creates a userspace sync timeline. - */ - -struct kgsl_syncsource_destroy { - unsigned int id; -/* private: reserved for future use */ - unsigned int __pad[3]; -}; - -#define IOCTL_KGSL_SYNCSOURCE_DESTROY \ - _IOWR(KGSL_IOC_TYPE, 0x41, struct kgsl_syncsource_destroy) - -/** - * struct kgsl_syncsource_create_fence - Argument to - * IOCTL_KGSL_SYNCSOURCE_CREATE_FENCE - * @id: syncsource id - * @fence_fd: returned sync_fence fd - * - * Create a fence that may be signaled by userspace by calling - * IOCTL_KGSL_SYNCSOURCE_SIGNAL_FENCE. There are no order dependencies between - * these fences. - */ -struct kgsl_syncsource_create_fence { - unsigned int id; - int fence_fd; -/* private: reserved for future use */ - unsigned int __pad[4]; -}; - -/** - * struct kgsl_syncsource_signal_fence - Argument to - * IOCTL_KGSL_SYNCSOURCE_SIGNAL_FENCE - * @id: syncsource id - * @fence_fd: sync_fence fd to signal - * - * Signal a fence that was created by a IOCTL_KGSL_SYNCSOURCE_CREATE_FENCE - * call using the same syncsource id. This allows a fence to be shared - * to other processes but only signaled by the process owning the fd - * used to create the fence. - */ -#define IOCTL_KGSL_SYNCSOURCE_CREATE_FENCE \ - _IOWR(KGSL_IOC_TYPE, 0x42, struct kgsl_syncsource_create_fence) - -struct kgsl_syncsource_signal_fence { - unsigned int id; - int fence_fd; -/* private: reserved for future use */ - unsigned int __pad[4]; -}; - -#define IOCTL_KGSL_SYNCSOURCE_SIGNAL_FENCE \ - _IOWR(KGSL_IOC_TYPE, 0x43, struct kgsl_syncsource_signal_fence) - -/** - * struct kgsl_cff_sync_gpuobj - Argument to IOCTL_KGSL_CFF_SYNC_GPUOBJ - * @offset: Offset into the GPU object to sync - * @length: Number of bytes to sync - * @id: ID of the GPU object to sync - */ -struct kgsl_cff_sync_gpuobj { - uint64_t offset; - uint64_t length; - unsigned int id; -}; - -#define IOCTL_KGSL_CFF_SYNC_GPUOBJ \ - _IOW(KGSL_IOC_TYPE, 0x44, struct kgsl_cff_sync_gpuobj) - -/** - * struct kgsl_gpuobj_alloc - Argument to IOCTL_KGSL_GPUOBJ_ALLOC - * @size: Size in bytes of the object to allocate - * @flags: mask of KGSL_MEMFLAG_* bits - * @va_len: Size in bytes of the virtual region to allocate - * @mmapsize: Returns the mmap() size of the object - * @id: Returns the GPU object ID of the new object - * @metadata_len: Length of the metdata to copy from the user - * @metadata: Pointer to the user specified metadata to store for the object - */ -struct kgsl_gpuobj_alloc { - uint64_t size; - uint64_t flags; - uint64_t va_len; - uint64_t mmapsize; - unsigned int id; - unsigned int metadata_len; - uint64_t metadata; -}; - -/* Let the user know that this header supports the gpuobj metadata */ -#define KGSL_GPUOBJ_ALLOC_METADATA_MAX 64 - -#define IOCTL_KGSL_GPUOBJ_ALLOC \ - _IOWR(KGSL_IOC_TYPE, 0x45, struct kgsl_gpuobj_alloc) - -/** - * struct kgsl_gpuobj_free - Argument to IOCTL_KGLS_GPUOBJ_FREE - * @flags: Mask of: KGSL_GUPOBJ_FREE_ON_EVENT - * @priv: Pointer to the private object if KGSL_GPUOBJ_FREE_ON_EVENT is - * specified - * @id: ID of the GPU object to free - * @type: If KGSL_GPUOBJ_FREE_ON_EVENT is specified, the type of asynchronous - * event to free on - * @len: Length of the data passed in priv - */ -struct kgsl_gpuobj_free { - uint64_t flags; - uint64_t __user priv; - unsigned int id; - unsigned int type; - unsigned int len; -}; - -#define KGSL_GPUOBJ_FREE_ON_EVENT 1 - -#define KGSL_GPU_EVENT_TIMESTAMP 1 -#define KGSL_GPU_EVENT_FENCE 2 - -/** - * struct kgsl_gpu_event_timestamp - Specifies a timestamp event to free a GPU - * object on - * @context_id: ID of the timestamp event to wait for - * @timestamp: Timestamp of the timestamp event to wait for - */ -struct kgsl_gpu_event_timestamp { - unsigned int context_id; - unsigned int timestamp; -}; - -/** - * struct kgsl_gpu_event_fence - Specifies a fence ID to to free a GPU object on - * @fd: File descriptor for the fence - */ -struct kgsl_gpu_event_fence { - int fd; -}; - -#define IOCTL_KGSL_GPUOBJ_FREE \ - _IOW(KGSL_IOC_TYPE, 0x46, struct kgsl_gpuobj_free) - -/** - * struct kgsl_gpuobj_info - argument to IOCTL_KGSL_GPUOBJ_INFO - * @gpuaddr: GPU address of the object - * @flags: Current flags for the object - * @size: Size of the object - * @va_len: VA size of the object - * @va_addr: Virtual address of the object (if it is mapped) - * id - GPU object ID of the object to query - */ -struct kgsl_gpuobj_info { - uint64_t gpuaddr; - uint64_t flags; - uint64_t size; - uint64_t va_len; - uint64_t va_addr; - unsigned int id; -}; - -#define IOCTL_KGSL_GPUOBJ_INFO \ - _IOWR(KGSL_IOC_TYPE, 0x47, struct kgsl_gpuobj_info) - -/** - * struct kgsl_gpuobj_import - argument to IOCTL_KGSL_GPUOBJ_IMPORT - * @priv: Pointer to the private data for the import type - * @priv_len: Length of the private data - * @flags: Mask of KGSL_MEMFLAG_ flags - * @type: Type of the import (KGSL_USER_MEM_TYPE_*) - * @id: Returns the ID of the new GPU object - */ -struct kgsl_gpuobj_import { - uint64_t __user priv; - uint64_t priv_len; - uint64_t flags; - unsigned int type; - unsigned int id; -}; - -/** - * struct kgsl_gpuobj_import_dma_buf - import a dmabuf object - * @fd: File descriptor for the dma-buf object - */ -struct kgsl_gpuobj_import_dma_buf { - int fd; -}; - -/** - * struct kgsl_gpuobj_import_useraddr - import an object based on a useraddr - * @virtaddr: Virtual address of the object to import - */ -struct kgsl_gpuobj_import_useraddr { - uint64_t virtaddr; -}; - -#define IOCTL_KGSL_GPUOBJ_IMPORT \ - _IOWR(KGSL_IOC_TYPE, 0x48, struct kgsl_gpuobj_import) - -/** - * struct kgsl_gpuobj_sync_obj - Individual GPU object to sync - * @offset: Offset within the GPU object to sync - * @length: Number of bytes to sync - * @id: ID of the GPU object to sync - * @op: Cache operation to execute - */ - -struct kgsl_gpuobj_sync_obj { - uint64_t offset; - uint64_t length; - unsigned int id; - unsigned int op; -}; - -/** - * struct kgsl_gpuobj_sync - Argument for IOCTL_KGSL_GPUOBJ_SYNC - * @objs: Pointer to an array of kgsl_gpuobj_sync_obj structs - * @obj_len: Size of each item in the array - * @count: Number of items in the array - */ - -struct kgsl_gpuobj_sync { - uint64_t __user objs; - unsigned int obj_len; - unsigned int count; -}; - -#define IOCTL_KGSL_GPUOBJ_SYNC \ - _IOW(KGSL_IOC_TYPE, 0x49, struct kgsl_gpuobj_sync) - -/** - * struct kgsl_command_object - GPU command object - * @offset: GPU address offset of the object - * @gpuaddr: GPU address of the object - * @size: Size of the object - * @flags: Current flags for the object - * @id - GPU command object ID - */ -struct kgsl_command_object { - uint64_t offset; - uint64_t gpuaddr; - uint64_t size; - unsigned int flags; - unsigned int id; -}; - -/** - * struct kgsl_command_syncpoint - GPU syncpoint object - * @priv: Pointer to the type specific buffer - * @size: Size of the type specific buffer - * @type: type of sync point defined here - */ -struct kgsl_command_syncpoint { - uint64_t __user priv; - uint64_t size; - unsigned int type; -}; - -/** - * struct kgsl_command_object - Argument for IOCTL_KGSL_GPU_COMMAND - * @flags: Current flags for the object - * @cmdlist: List of kgsl_command_objects for submission - * @cmd_size: Size of kgsl_command_objects structure - * @numcmds: Number of kgsl_command_objects in command list - * @objlist: List of kgsl_command_objects for tracking - * @obj_size: Size of kgsl_command_objects structure - * @numobjs: Number of kgsl_command_objects in object list - * @synclist: List of kgsl_command_syncpoints - * @sync_size: Size of kgsl_command_syncpoint structure - * @numsyncs: Number of kgsl_command_syncpoints in syncpoint list - * @context_id: Context ID submittin ghte kgsl_gpu_command - * @timestamp: Timestamp for the submitted commands - */ -struct kgsl_gpu_command { - uint64_t flags; - uint64_t __user cmdlist; - unsigned int cmdsize; - unsigned int numcmds; - uint64_t __user objlist; - unsigned int objsize; - unsigned int numobjs; - uint64_t __user synclist; - unsigned int syncsize; - unsigned int numsyncs; - unsigned int context_id; - unsigned int timestamp; -}; - -#define IOCTL_KGSL_GPU_COMMAND \ - _IOWR(KGSL_IOC_TYPE, 0x4A, struct kgsl_gpu_command) - -/** - * struct kgsl_preemption_counters_query - argument to - * IOCTL_KGSL_PREEMPTIONCOUNTER_QUERY - * @counters: Return preemption counters array - * @size_user: Size allocated by userspace - * @size_priority_level: Size of preemption counters for each - * priority level - * @max_priority_level: Return max number of priority levels - * - * Query the available preemption counters. The array counters - * is used to return preemption counters. The size of the array - * is passed in so the kernel will only write at most size_user - * or max available preemption counters. The total number of - * preemption counters is returned in max_priority_level. If the - * array or size passed in are invalid, then an error is - * returned back. - */ -struct kgsl_preemption_counters_query { - uint64_t __user counters; - unsigned int size_user; - unsigned int size_priority_level; - unsigned int max_priority_level; -}; - -#define IOCTL_KGSL_PREEMPTIONCOUNTER_QUERY \ - _IOWR(KGSL_IOC_TYPE, 0x4B, struct kgsl_preemption_counters_query) - -/** - * struct kgsl_gpuobj_set_info - argument for IOCTL_KGSL_GPUOBJ_SET_INFO - * @flags: Flags to indicate which paramaters to change - * @metadata: If KGSL_GPUOBJ_SET_INFO_METADATA is set, a pointer to the new - * metadata - * @id: GPU memory object ID to change - * @metadata_len: If KGSL_GPUOBJ_SET_INFO_METADATA is set, the length of the - * new metadata string - * @type: If KGSL_GPUOBJ_SET_INFO_TYPE is set, the new type of the memory object - */ - -#define KGSL_GPUOBJ_SET_INFO_METADATA (1 << 0) -#define KGSL_GPUOBJ_SET_INFO_TYPE (1 << 1) - -struct kgsl_gpuobj_set_info { - uint64_t flags; - uint64_t metadata; - unsigned int id; - unsigned int metadata_len; - unsigned int type; -}; - -#define IOCTL_KGSL_GPUOBJ_SET_INFO \ - _IOW(KGSL_IOC_TYPE, 0x4C, struct kgsl_gpuobj_set_info) - -#endif /* _UAPI_MSM_KGSL_H */ diff --git a/third_party/linux/include/msm_media_info.h b/third_party/linux/include/msm_media_info.h deleted file mode 100644 index 39dceb2c49f147..00000000000000 --- a/third_party/linux/include/msm_media_info.h +++ /dev/null @@ -1,819 +0,0 @@ -#ifndef __MEDIA_INFO_H__ -#define __MEDIA_INFO_H__ - -#ifndef MSM_MEDIA_ALIGN -#define MSM_MEDIA_ALIGN(__sz, __align) (((__sz) + (__align-1)) & (~(__align-1))) -#endif - -#ifndef MSM_MEDIA_ROUNDUP -#define MSM_MEDIA_ROUNDUP(__sz, __r) (((__sz) + ((__r) - 1)) / (__r)) -#endif - -#ifndef MSM_MEDIA_MAX -#define MSM_MEDIA_MAX(__a, __b) ((__a) > (__b)?(__a):(__b)) -#endif - -enum color_fmts { - /* Venus NV12: - * YUV 4:2:0 image with a plane of 8 bit Y samples followed - * by an interleaved U/V plane containing 8 bit 2x2 subsampled - * colour difference samples. - * - * <-------- Y/UV_Stride --------> - * <------- Width -------> - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * U V U V U V U V U V U V . . . . ^ - * U V U V U V U V U V U V . . . . | - * U V U V U V U V U V U V . . . . | - * U V U V U V U V U V U V . . . . UV_Scanlines - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . . . --> Buffer size alignment - * - * Y_Stride : Width aligned to 128 - * UV_Stride : Width aligned to 128 - * Y_Scanlines: Height aligned to 32 - * UV_Scanlines: Height/2 aligned to 16 - * Extradata: Arbitrary (software-imposed) padding - * Total size = align((Y_Stride * Y_Scanlines - * + UV_Stride * UV_Scanlines - * + max(Extradata, Y_Stride * 8), 4096) - */ - COLOR_FMT_NV12, - - /* Venus NV21: - * YUV 4:2:0 image with a plane of 8 bit Y samples followed - * by an interleaved V/U plane containing 8 bit 2x2 subsampled - * colour difference samples. - * - * <-------- Y/UV_Stride --------> - * <------- Width -------> - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * V U V U V U V U V U V U . . . . ^ - * V U V U V U V U V U V U . . . . | - * V U V U V U V U V U V U . . . . | - * V U V U V U V U V U V U . . . . UV_Scanlines - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . . . --> Padding & Buffer size alignment - * - * Y_Stride : Width aligned to 128 - * UV_Stride : Width aligned to 128 - * Y_Scanlines: Height aligned to 32 - * UV_Scanlines: Height/2 aligned to 16 - * Extradata: Arbitrary (software-imposed) padding - * Total size = align((Y_Stride * Y_Scanlines - * + UV_Stride * UV_Scanlines - * + max(Extradata, Y_Stride * 8), 4096) - */ - COLOR_FMT_NV21, - /* Venus NV12_MVTB: - * Two YUV 4:2:0 images/views one after the other - * in a top-bottom layout, same as NV12 - * with a plane of 8 bit Y samples followed - * by an interleaved U/V plane containing 8 bit 2x2 subsampled - * colour difference samples. - * - * - * <-------- Y/UV_Stride --------> - * <------- Width -------> - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ ^ - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | | - * . . . . . . . . . . . . . . . . | View_1 - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . V | - * U V U V U V U V U V U V . . . . ^ | - * U V U V U V U V U V U V . . . . | | - * U V U V U V U V U V U V . . . . | | - * U V U V U V U V U V U V . . . . UV_Scanlines | - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . V V - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ ^ - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | | - * . . . . . . . . . . . . . . . . | View_2 - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . V | - * U V U V U V U V U V U V . . . . ^ | - * U V U V U V U V U V U V . . . . | | - * U V U V U V U V U V U V . . . . | | - * U V U V U V U V U V U V . . . . UV_Scanlines | - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . V V - * . . . . . . . . . . . . . . . . --> Buffer size alignment - * - * Y_Stride : Width aligned to 128 - * UV_Stride : Width aligned to 128 - * Y_Scanlines: Height aligned to 32 - * UV_Scanlines: Height/2 aligned to 16 - * View_1 begin at: 0 (zero) - * View_2 begin at: Y_Stride * Y_Scanlines + UV_Stride * UV_Scanlines - * Extradata: Arbitrary (software-imposed) padding - * Total size = align((2*(Y_Stride * Y_Scanlines) - * + 2*(UV_Stride * UV_Scanlines) + Extradata), 4096) - */ - COLOR_FMT_NV12_MVTB, - /* Venus NV12 UBWC: - * Compressed Macro-tile format for NV12. - * Contains 4 planes in the following order - - * (A) Y_Meta_Plane - * (B) Y_UBWC_Plane - * (C) UV_Meta_Plane - * (D) UV_UBWC_Plane - * - * Y_Meta_Plane consists of meta information to decode compressed - * tile data in Y_UBWC_Plane. - * Y_UBWC_Plane consists of Y data in compressed macro-tile format. - * UBWC decoder block will use the Y_Meta_Plane data together with - * Y_UBWC_Plane data to produce loss-less uncompressed 8 bit Y samples. - * - * UV_Meta_Plane consists of meta information to decode compressed - * tile data in UV_UBWC_Plane. - * UV_UBWC_Plane consists of UV data in compressed macro-tile format. - * UBWC decoder block will use UV_Meta_Plane data together with - * UV_UBWC_Plane data to produce loss-less uncompressed 8 bit 2x2 - * subsampled color difference samples. - * - * Each tile in Y_UBWC_Plane/UV_UBWC_Plane is independently decodable - * and randomly accessible. There is no dependency between tiles. - * - * <----- Y_Meta_Stride ----> - * <-------- Width ------> - * M M M M M M M M M M M M . . ^ ^ - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . Height | - * M M M M M M M M M M M M . . | Meta_Y_Scanlines - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . V | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . V - * <--Compressed tile Y Stride---> - * <------- Width -------> - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . ^ ^ - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . Height | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | Macro_tile_Y_Scanlines - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . . . V - * <----- UV_Meta_Stride ----> - * M M M M M M M M M M M M . . ^ - * M M M M M M M M M M M M . . | - * M M M M M M M M M M M M . . | - * M M M M M M M M M M M M . . M_UV_Scanlines - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * <--Compressed tile UV Stride---> - * U* V* U* V* U* V* U* V* . . . . ^ - * U* V* U* V* U* V* U* V* . . . . | - * U* V* U* V* U* V* U* V* . . . . | - * U* V* U* V* U* V* U* V* . . . . UV_Scanlines - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * - * Y_Stride = align(Width, 128) - * UV_Stride = align(Width, 128) - * Y_Scanlines = align(Height, 32) - * UV_Scanlines = align(Height/2, 16) - * Y_UBWC_Plane_size = align(Y_Stride * Y_Scanlines, 4096) - * UV_UBWC_Plane_size = align(UV_Stride * UV_Scanlines, 4096) - * Y_Meta_Stride = align(roundup(Width, Y_TileWidth), 64) - * Y_Meta_Scanlines = align(roundup(Height, Y_TileHeight), 16) - * Y_Meta_Plane_size = align(Y_Meta_Stride * Y_Meta_Scanlines, 4096) - * UV_Meta_Stride = align(roundup(Width, UV_TileWidth), 64) - * UV_Meta_Scanlines = align(roundup(Height, UV_TileHeight), 16) - * UV_Meta_Plane_size = align(UV_Meta_Stride * UV_Meta_Scanlines, 4096) - * Extradata = 8k - * - * Total size = align( Y_UBWC_Plane_size + UV_UBWC_Plane_size + - * Y_Meta_Plane_size + UV_Meta_Plane_size - * + max(Extradata, Y_Stride * 48), 4096) - */ - COLOR_FMT_NV12_UBWC, - /* Venus NV12 10-bit UBWC: - * Compressed Macro-tile format for NV12. - * Contains 4 planes in the following order - - * (A) Y_Meta_Plane - * (B) Y_UBWC_Plane - * (C) UV_Meta_Plane - * (D) UV_UBWC_Plane - * - * Y_Meta_Plane consists of meta information to decode compressed - * tile data in Y_UBWC_Plane. - * Y_UBWC_Plane consists of Y data in compressed macro-tile format. - * UBWC decoder block will use the Y_Meta_Plane data together with - * Y_UBWC_Plane data to produce loss-less uncompressed 10 bit Y samples. - * - * UV_Meta_Plane consists of meta information to decode compressed - * tile data in UV_UBWC_Plane. - * UV_UBWC_Plane consists of UV data in compressed macro-tile format. - * UBWC decoder block will use UV_Meta_Plane data together with - * UV_UBWC_Plane data to produce loss-less uncompressed 10 bit 2x2 - * subsampled color difference samples. - * - * Each tile in Y_UBWC_Plane/UV_UBWC_Plane is independently decodable - * and randomly accessible. There is no dependency between tiles. - * - * <----- Y_Meta_Stride -----> - * <-------- Width ------> - * M M M M M M M M M M M M . . ^ ^ - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . Height | - * M M M M M M M M M M M M . . | Meta_Y_Scanlines - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . V | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . V - * <--Compressed tile Y Stride---> - * <------- Width -------> - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . ^ ^ - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . Height | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | Macro_tile_Y_Scanlines - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . . . V - * <----- UV_Meta_Stride ----> - * M M M M M M M M M M M M . . ^ - * M M M M M M M M M M M M . . | - * M M M M M M M M M M M M . . | - * M M M M M M M M M M M M . . M_UV_Scanlines - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * <--Compressed tile UV Stride---> - * U* V* U* V* U* V* U* V* . . . . ^ - * U* V* U* V* U* V* U* V* . . . . | - * U* V* U* V* U* V* U* V* . . . . | - * U* V* U* V* U* V* U* V* . . . . UV_Scanlines - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * - * - * Y_Stride = align(Width * 4/3, 128) - * UV_Stride = align(Width * 4/3, 128) - * Y_Scanlines = align(Height, 32) - * UV_Scanlines = align(Height/2, 16) - * Y_UBWC_Plane_Size = align(Y_Stride * Y_Scanlines, 4096) - * UV_UBWC_Plane_Size = align(UV_Stride * UV_Scanlines, 4096) - * Y_Meta_Stride = align(roundup(Width, Y_TileWidth), 64) - * Y_Meta_Scanlines = align(roundup(Height, Y_TileHeight), 16) - * Y_Meta_Plane_size = align(Y_Meta_Stride * Y_Meta_Scanlines, 4096) - * UV_Meta_Stride = align(roundup(Width, UV_TileWidth), 64) - * UV_Meta_Scanlines = align(roundup(Height, UV_TileHeight), 16) - * UV_Meta_Plane_size = align(UV_Meta_Stride * UV_Meta_Scanlines, 4096) - * Extradata = 8k - * - * Total size = align(Y_UBWC_Plane_size + UV_UBWC_Plane_size + - * Y_Meta_Plane_size + UV_Meta_Plane_size - * + max(Extradata, Y_Stride * 48), 4096) - */ - COLOR_FMT_NV12_BPP10_UBWC, - /* Venus RGBA8888 format: - * Contains 1 plane in the following order - - * (A) RGBA plane - * - * <-------- RGB_Stride --------> - * <------- Width -------> - * R R R R R R R R R R R R . . . . ^ ^ - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . Height | - * R R R R R R R R R R R R . . . . | RGB_Scanlines - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * - * RGB_Stride = align(Width * 4, 128) - * RGB_Scanlines = align(Height, 32) - * RGB_Plane_size = align(RGB_Stride * RGB_Scanlines, 4096) - * Extradata = 8k - * - * Total size = align(RGB_Plane_size + Extradata, 4096) - */ - COLOR_FMT_RGBA8888, - /* Venus RGBA8888 UBWC format: - * Contains 2 planes in the following order - - * (A) Meta plane - * (B) RGBA plane - * - * <--- RGB_Meta_Stride ----> - * <-------- Width ------> - * M M M M M M M M M M M M . . ^ ^ - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . Height | - * M M M M M M M M M M M M . . | Meta_RGB_Scanlines - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . V | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . V - * <-------- RGB_Stride --------> - * <------- Width -------> - * R R R R R R R R R R R R . . . . ^ ^ - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . Height | - * R R R R R R R R R R R R . . . . | RGB_Scanlines - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . . . V - * - * RGB_Stride = align(Width * 4, 128) - * RGB_Scanlines = align(Height, 32) - * RGB_Plane_size = align(RGB_Stride * RGB_Scanlines, 4096) - * RGB_Meta_Stride = align(roundup(Width, RGB_TileWidth), 64) - * RGB_Meta_Scanline = align(roundup(Height, RGB_TileHeight), 16) - * RGB_Meta_Plane_size = align(RGB_Meta_Stride * - * RGB_Meta_Scanlines, 4096) - * Extradata = 8k - * - * Total size = align(RGB_Meta_Plane_size + RGB_Plane_size + - * Extradata, 4096) - */ - COLOR_FMT_RGBA8888_UBWC, -}; - -static inline unsigned int VENUS_EXTRADATA_SIZE(int width, int height) -{ - (void)height; - (void)width; - - /* - * In the future, calculate the size based on the w/h but just - * hardcode it for now since 16K satisfies all current usecases. - */ - return 16 * 1024; -} - -static inline unsigned int VENUS_Y_STRIDE(int color_fmt, int width) -{ - unsigned int alignment, stride = 0; - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - case COLOR_FMT_NV12_MVTB: - case COLOR_FMT_NV12_UBWC: - alignment = 128; - stride = MSM_MEDIA_ALIGN(width, alignment); - break; - case COLOR_FMT_NV12_BPP10_UBWC: - alignment = 256; - stride = MSM_MEDIA_ALIGN(width, 192); - stride = MSM_MEDIA_ALIGN(stride * 4/3, alignment); - break; - default: - break; - } -invalid_input: - return stride; -} - -static inline unsigned int VENUS_UV_STRIDE(int color_fmt, int width) -{ - unsigned int alignment, stride = 0; - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - case COLOR_FMT_NV12_MVTB: - case COLOR_FMT_NV12_UBWC: - alignment = 128; - stride = MSM_MEDIA_ALIGN(width, alignment); - break; - case COLOR_FMT_NV12_BPP10_UBWC: - alignment = 256; - stride = MSM_MEDIA_ALIGN(width, 192); - stride = MSM_MEDIA_ALIGN(stride * 4/3, alignment); - break; - default: - break; - } -invalid_input: - return stride; -} - -static inline unsigned int VENUS_Y_SCANLINES(int color_fmt, int height) -{ - unsigned int alignment, sclines = 0; - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - case COLOR_FMT_NV12_MVTB: - case COLOR_FMT_NV12_UBWC: - alignment = 32; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - alignment = 16; - break; - default: - return 0; - } - sclines = MSM_MEDIA_ALIGN(height, alignment); -invalid_input: - return sclines; -} - -static inline unsigned int VENUS_UV_SCANLINES(int color_fmt, int height) -{ - unsigned int alignment, sclines = 0; - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - case COLOR_FMT_NV12_MVTB: - case COLOR_FMT_NV12_BPP10_UBWC: - alignment = 16; - break; - case COLOR_FMT_NV12_UBWC: - alignment = 32; - break; - default: - goto invalid_input; - } - - sclines = MSM_MEDIA_ALIGN(height / 2, alignment); - -invalid_input: - return sclines; -} - -static inline unsigned int VENUS_Y_META_STRIDE(int color_fmt, int width) -{ - int y_tile_width = 0, y_meta_stride = 0; - - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV12_UBWC: - y_tile_width = 32; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - y_tile_width = 48; - break; - default: - goto invalid_input; - } - - y_meta_stride = MSM_MEDIA_ROUNDUP(width, y_tile_width); - y_meta_stride = MSM_MEDIA_ALIGN(y_meta_stride, 64); - -invalid_input: - return y_meta_stride; -} - -static inline unsigned int VENUS_Y_META_SCANLINES(int color_fmt, int height) -{ - int y_tile_height = 0, y_meta_scanlines = 0; - - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV12_UBWC: - y_tile_height = 8; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - y_tile_height = 4; - break; - default: - goto invalid_input; - } - - y_meta_scanlines = MSM_MEDIA_ROUNDUP(height, y_tile_height); - y_meta_scanlines = MSM_MEDIA_ALIGN(y_meta_scanlines, 16); - -invalid_input: - return y_meta_scanlines; -} - -static inline unsigned int VENUS_UV_META_STRIDE(int color_fmt, int width) -{ - int uv_tile_width = 0, uv_meta_stride = 0; - - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV12_UBWC: - uv_tile_width = 16; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - uv_tile_width = 24; - break; - default: - goto invalid_input; - } - - uv_meta_stride = MSM_MEDIA_ROUNDUP(width / 2, uv_tile_width); - uv_meta_stride = MSM_MEDIA_ALIGN(uv_meta_stride, 64); - -invalid_input: - return uv_meta_stride; -} - -static inline unsigned int VENUS_UV_META_SCANLINES(int color_fmt, int height) -{ - int uv_tile_height = 0, uv_meta_scanlines = 0; - - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV12_UBWC: - uv_tile_height = 8; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - uv_tile_height = 4; - break; - default: - goto invalid_input; - } - - uv_meta_scanlines = MSM_MEDIA_ROUNDUP(height / 2, uv_tile_height); - uv_meta_scanlines = MSM_MEDIA_ALIGN(uv_meta_scanlines, 16); - -invalid_input: - return uv_meta_scanlines; -} - -static inline unsigned int VENUS_RGB_STRIDE(int color_fmt, int width) -{ - unsigned int alignment = 0, stride = 0; - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_RGBA8888: - alignment = 128; - break; - case COLOR_FMT_RGBA8888_UBWC: - alignment = 256; - break; - default: - goto invalid_input; - } - - stride = MSM_MEDIA_ALIGN(width * 4, alignment); - -invalid_input: - return stride; -} - -static inline unsigned int VENUS_RGB_SCANLINES(int color_fmt, int height) -{ - unsigned int alignment = 0, scanlines = 0; - - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_RGBA8888: - alignment = 32; - break; - case COLOR_FMT_RGBA8888_UBWC: - alignment = 16; - break; - default: - goto invalid_input; - } - - scanlines = MSM_MEDIA_ALIGN(height, alignment); - -invalid_input: - return scanlines; -} - -static inline unsigned int VENUS_RGB_META_STRIDE(int color_fmt, int width) -{ - int rgb_tile_width = 0, rgb_meta_stride = 0; - - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_RGBA8888_UBWC: - rgb_tile_width = 16; - break; - default: - goto invalid_input; - } - - rgb_meta_stride = MSM_MEDIA_ROUNDUP(width, rgb_tile_width); - rgb_meta_stride = MSM_MEDIA_ALIGN(rgb_meta_stride, 64); - -invalid_input: - return rgb_meta_stride; -} - -static inline unsigned int VENUS_RGB_META_SCANLINES(int color_fmt, int height) -{ - int rgb_tile_height = 0, rgb_meta_scanlines = 0; - - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_RGBA8888_UBWC: - rgb_tile_height = 4; - break; - default: - goto invalid_input; - } - - rgb_meta_scanlines = MSM_MEDIA_ROUNDUP(height, rgb_tile_height); - rgb_meta_scanlines = MSM_MEDIA_ALIGN(rgb_meta_scanlines, 16); - -invalid_input: - return rgb_meta_scanlines; -} - -static inline unsigned int VENUS_BUFFER_SIZE( - int color_fmt, int width, int height) -{ - const unsigned int extra_size = VENUS_EXTRADATA_SIZE(width, height); - unsigned int uv_alignment = 0, size = 0; - unsigned int y_plane, uv_plane, y_stride, - uv_stride, y_sclines, uv_sclines; - unsigned int y_ubwc_plane = 0, uv_ubwc_plane = 0; - unsigned int y_meta_stride = 0, y_meta_scanlines = 0; - unsigned int uv_meta_stride = 0, uv_meta_scanlines = 0; - unsigned int y_meta_plane = 0, uv_meta_plane = 0; - unsigned int rgb_stride = 0, rgb_scanlines = 0; - unsigned int rgb_plane = 0, rgb_ubwc_plane = 0, rgb_meta_plane = 0; - unsigned int rgb_meta_stride = 0, rgb_meta_scanlines = 0; - - if (!width || !height) - goto invalid_input; - - y_stride = VENUS_Y_STRIDE(color_fmt, width); - uv_stride = VENUS_UV_STRIDE(color_fmt, width); - y_sclines = VENUS_Y_SCANLINES(color_fmt, height); - uv_sclines = VENUS_UV_SCANLINES(color_fmt, height); - rgb_stride = VENUS_RGB_STRIDE(color_fmt, width); - rgb_scanlines = VENUS_RGB_SCANLINES(color_fmt, height); - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - uv_alignment = 4096; - y_plane = y_stride * y_sclines; - uv_plane = uv_stride * uv_sclines + uv_alignment; - size = y_plane + uv_plane + - MSM_MEDIA_MAX(extra_size, 8 * y_stride); - size = MSM_MEDIA_ALIGN(size, 4096); - break; - case COLOR_FMT_NV12_MVTB: - uv_alignment = 4096; - y_plane = y_stride * y_sclines; - uv_plane = uv_stride * uv_sclines + uv_alignment; - size = y_plane + uv_plane; - size = 2 * size + extra_size; - size = MSM_MEDIA_ALIGN(size, 4096); - break; - case COLOR_FMT_NV12_UBWC: - case COLOR_FMT_NV12_BPP10_UBWC: - y_ubwc_plane = MSM_MEDIA_ALIGN(y_stride * y_sclines, 4096); - uv_ubwc_plane = MSM_MEDIA_ALIGN(uv_stride * uv_sclines, 4096); - y_meta_stride = VENUS_Y_META_STRIDE(color_fmt, width); - y_meta_scanlines = VENUS_Y_META_SCANLINES(color_fmt, height); - y_meta_plane = MSM_MEDIA_ALIGN( - y_meta_stride * y_meta_scanlines, 4096); - uv_meta_stride = VENUS_UV_META_STRIDE(color_fmt, width); - uv_meta_scanlines = VENUS_UV_META_SCANLINES(color_fmt, height); - uv_meta_plane = MSM_MEDIA_ALIGN(uv_meta_stride * - uv_meta_scanlines, 4096); - - size = y_ubwc_plane + uv_ubwc_plane + y_meta_plane + - uv_meta_plane + - MSM_MEDIA_MAX(extra_size + 8192, 48 * y_stride); - size = MSM_MEDIA_ALIGN(size, 4096); - break; - case COLOR_FMT_RGBA8888: - rgb_plane = MSM_MEDIA_ALIGN(rgb_stride * rgb_scanlines, 4096); - size = rgb_plane; - size = MSM_MEDIA_ALIGN(size, 4096); - break; - case COLOR_FMT_RGBA8888_UBWC: - rgb_ubwc_plane = MSM_MEDIA_ALIGN(rgb_stride * rgb_scanlines, - 4096); - rgb_meta_stride = VENUS_RGB_META_STRIDE(color_fmt, width); - rgb_meta_scanlines = VENUS_RGB_META_SCANLINES(color_fmt, - height); - rgb_meta_plane = MSM_MEDIA_ALIGN(rgb_meta_stride * - rgb_meta_scanlines, 4096); - size = rgb_ubwc_plane + rgb_meta_plane; - size = MSM_MEDIA_ALIGN(size, 4096); - break; - default: - break; - } -invalid_input: - return size; -} - -static inline unsigned int VENUS_VIEW2_OFFSET( - int color_fmt, int width, int height) -{ - unsigned int offset = 0; - unsigned int y_plane, uv_plane, y_stride, - uv_stride, y_sclines, uv_sclines; - if (!width || !height) - goto invalid_input; - - y_stride = VENUS_Y_STRIDE(color_fmt, width); - uv_stride = VENUS_UV_STRIDE(color_fmt, width); - y_sclines = VENUS_Y_SCANLINES(color_fmt, height); - uv_sclines = VENUS_UV_SCANLINES(color_fmt, height); - switch (color_fmt) { - case COLOR_FMT_NV12_MVTB: - y_plane = y_stride * y_sclines; - uv_plane = uv_stride * uv_sclines; - offset = y_plane + uv_plane; - break; - default: - break; - } -invalid_input: - return offset; -} - -#endif diff --git a/third_party/linux/include/msmb_camera.h b/third_party/linux/include/msmb_camera.h deleted file mode 100644 index f4c4b3e183e86c..00000000000000 --- a/third_party/linux/include/msmb_camera.h +++ /dev/null @@ -1,220 +0,0 @@ -#ifndef __LINUX_MSMB_CAMERA_H -#define __LINUX_MSMB_CAMERA_H - -#include -#include -#include - -#define MSM_CAM_LOGSYNC_FILE_NAME "logsync" -#define MSM_CAM_LOGSYNC_FILE_BASEDIR "camera" - -#define MSM_CAM_V4L2_IOCTL_NOTIFY \ - _IOW('V', BASE_VIDIOC_PRIVATE + 30, struct msm_v4l2_event_data) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_META \ - _IOW('V', BASE_VIDIOC_PRIVATE + 31, struct msm_v4l2_event_data) - -#define MSM_CAM_V4L2_IOCTL_CMD_ACK \ - _IOW('V', BASE_VIDIOC_PRIVATE + 32, struct msm_v4l2_event_data) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_ERROR \ - _IOW('V', BASE_VIDIOC_PRIVATE + 33, struct msm_v4l2_event_data) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_DEBUG \ - _IOW('V', BASE_VIDIOC_PRIVATE + 34, struct msm_v4l2_event_data) - -#ifdef CONFIG_COMPAT -#define MSM_CAM_V4L2_IOCTL_NOTIFY32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 30, struct v4l2_event32) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_META32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 31, struct v4l2_event32) - -#define MSM_CAM_V4L2_IOCTL_CMD_ACK32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 32, struct v4l2_event32) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_ERROR32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 33, struct v4l2_event32) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_DEBUG32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 34, struct v4l2_event32) - -#endif - -#define QCAMERA_DEVICE_GROUP_ID 1 -#define QCAMERA_VNODE_GROUP_ID 2 -#define MSM_CAMERA_NAME "msm_camera" -#define MSM_CONFIGURATION_NAME "msm_config" - -#define MSM_CAMERA_SUBDEV_CSIPHY 0 -#define MSM_CAMERA_SUBDEV_CSID 1 -#define MSM_CAMERA_SUBDEV_ISPIF 2 -#define MSM_CAMERA_SUBDEV_VFE 3 -#define MSM_CAMERA_SUBDEV_AXI 4 -#define MSM_CAMERA_SUBDEV_VPE 5 -#define MSM_CAMERA_SUBDEV_SENSOR 6 -#define MSM_CAMERA_SUBDEV_ACTUATOR 7 -#define MSM_CAMERA_SUBDEV_EEPROM 8 -#define MSM_CAMERA_SUBDEV_CPP 9 -#define MSM_CAMERA_SUBDEV_CCI 10 -#define MSM_CAMERA_SUBDEV_LED_FLASH 11 -#define MSM_CAMERA_SUBDEV_STROBE_FLASH 12 -#define MSM_CAMERA_SUBDEV_BUF_MNGR 13 -#define MSM_CAMERA_SUBDEV_SENSOR_INIT 14 -#define MSM_CAMERA_SUBDEV_OIS 15 -#define MSM_CAMERA_SUBDEV_FLASH 16 -#define MSM_CAMERA_SUBDEV_EXT 17 - -#define MSM_MAX_CAMERA_SENSORS 5 - -/* The below macro is defined to put an upper limit on maximum - * number of buffer requested per stream. In case of extremely - * large value for number of buffer due to data structure corruption - * we return error to avoid integer overflow. Group processing - * can have max of 9 groups of 8 bufs each. This value may be - * configured in future*/ -#define MSM_CAMERA_MAX_STREAM_BUF 72 - -/* Max batch size of processing */ -#define MSM_CAMERA_MAX_USER_BUFF_CNT 16 - -/* featur base */ -#define MSM_CAMERA_FEATURE_BASE 0x00010000 -#define MSM_CAMERA_FEATURE_SHUTDOWN (MSM_CAMERA_FEATURE_BASE + 1) - -#define MSM_CAMERA_STATUS_BASE 0x00020000 -#define MSM_CAMERA_STATUS_FAIL (MSM_CAMERA_STATUS_BASE + 1) -#define MSM_CAMERA_STATUS_SUCCESS (MSM_CAMERA_STATUS_BASE + 2) - -/* event type */ -#define MSM_CAMERA_V4L2_EVENT_TYPE (V4L2_EVENT_PRIVATE_START + 0x00002000) - -/* event id */ -#define MSM_CAMERA_EVENT_MIN 0 -#define MSM_CAMERA_NEW_SESSION (MSM_CAMERA_EVENT_MIN + 1) -#define MSM_CAMERA_DEL_SESSION (MSM_CAMERA_EVENT_MIN + 2) -#define MSM_CAMERA_SET_PARM (MSM_CAMERA_EVENT_MIN + 3) -#define MSM_CAMERA_GET_PARM (MSM_CAMERA_EVENT_MIN + 4) -#define MSM_CAMERA_MAPPING_CFG (MSM_CAMERA_EVENT_MIN + 5) -#define MSM_CAMERA_MAPPING_SES (MSM_CAMERA_EVENT_MIN + 6) -#define MSM_CAMERA_MSM_NOTIFY (MSM_CAMERA_EVENT_MIN + 7) -#define MSM_CAMERA_EVENT_MAX (MSM_CAMERA_EVENT_MIN + 8) - -/* data.command */ -#define MSM_CAMERA_PRIV_S_CROP (V4L2_CID_PRIVATE_BASE + 1) -#define MSM_CAMERA_PRIV_G_CROP (V4L2_CID_PRIVATE_BASE + 2) -#define MSM_CAMERA_PRIV_G_FMT (V4L2_CID_PRIVATE_BASE + 3) -#define MSM_CAMERA_PRIV_S_FMT (V4L2_CID_PRIVATE_BASE + 4) -#define MSM_CAMERA_PRIV_TRY_FMT (V4L2_CID_PRIVATE_BASE + 5) -#define MSM_CAMERA_PRIV_METADATA (V4L2_CID_PRIVATE_BASE + 6) -#define MSM_CAMERA_PRIV_QUERY_CAP (V4L2_CID_PRIVATE_BASE + 7) -#define MSM_CAMERA_PRIV_STREAM_ON (V4L2_CID_PRIVATE_BASE + 8) -#define MSM_CAMERA_PRIV_STREAM_OFF (V4L2_CID_PRIVATE_BASE + 9) -#define MSM_CAMERA_PRIV_NEW_STREAM (V4L2_CID_PRIVATE_BASE + 10) -#define MSM_CAMERA_PRIV_DEL_STREAM (V4L2_CID_PRIVATE_BASE + 11) -#define MSM_CAMERA_PRIV_SHUTDOWN (V4L2_CID_PRIVATE_BASE + 12) -#define MSM_CAMERA_PRIV_STREAM_INFO_SYNC \ - (V4L2_CID_PRIVATE_BASE + 13) -#define MSM_CAMERA_PRIV_G_SESSION_ID (V4L2_CID_PRIVATE_BASE + 14) -#define MSM_CAMERA_PRIV_CMD_MAX 20 - -/* data.status - success */ -#define MSM_CAMERA_CMD_SUCESS 0x00000001 -#define MSM_CAMERA_BUF_MAP_SUCESS 0x00000002 - -/* data.status - error */ -#define MSM_CAMERA_ERR_EVT_BASE 0x00010000 -#define MSM_CAMERA_ERR_CMD_FAIL (MSM_CAMERA_ERR_EVT_BASE + 1) -#define MSM_CAMERA_ERR_MAPPING (MSM_CAMERA_ERR_EVT_BASE + 2) -#define MSM_CAMERA_ERR_DEVICE_BUSY (MSM_CAMERA_ERR_EVT_BASE + 3) - -/* The msm_v4l2_event_data structure should match the - * v4l2_event.u.data field. - * should not exceed 16 elements */ -struct msm_v4l2_event_data { - /*word 0*/ - unsigned int command; - /*word 1*/ - unsigned int status; - /*word 2*/ - unsigned int session_id; - /*word 3*/ - unsigned int stream_id; - /*word 4*/ - unsigned int map_op; - /*word 5*/ - unsigned int map_buf_idx; - /*word 6*/ - unsigned int notify; - /*word 7*/ - unsigned int arg_value; - /*word 8*/ - unsigned int ret_value; - /*word 9*/ - unsigned int v4l2_event_type; - /*word 10*/ - unsigned int v4l2_event_id; - /*word 11*/ - unsigned int handle; - /*word 12*/ - unsigned int nop6; - /*word 13*/ - unsigned int nop7; - /*word 14*/ - unsigned int nop8; - /*word 15*/ - unsigned int nop9; -}; - -/* map to v4l2_format.fmt.raw_data */ -struct msm_v4l2_format_data { - enum v4l2_buf_type type; - unsigned int width; - unsigned int height; - unsigned int pixelformat; /* FOURCC */ - unsigned char num_planes; - unsigned int plane_sizes[VIDEO_MAX_PLANES]; -}; - -/* MSM Four-character-code (FOURCC) */ -#define msm_v4l2_fourcc(a, b, c, d)\ - ((__u32)(a) | ((__u32)(b) << 8) | ((__u32)(c) << 16) |\ - ((__u32)(d) << 24)) - -/* Composite stats */ -#define MSM_V4L2_PIX_FMT_STATS_COMB v4l2_fourcc('S', 'T', 'C', 'M') -/* AEC stats */ -#define MSM_V4L2_PIX_FMT_STATS_AE v4l2_fourcc('S', 'T', 'A', 'E') -/* AF stats */ -#define MSM_V4L2_PIX_FMT_STATS_AF v4l2_fourcc('S', 'T', 'A', 'F') -/* AWB stats */ -#define MSM_V4L2_PIX_FMT_STATS_AWB v4l2_fourcc('S', 'T', 'W', 'B') -/* IHIST stats */ -#define MSM_V4L2_PIX_FMT_STATS_IHST v4l2_fourcc('I', 'H', 'S', 'T') -/* Column count stats */ -#define MSM_V4L2_PIX_FMT_STATS_CS v4l2_fourcc('S', 'T', 'C', 'S') -/* Row count stats */ -#define MSM_V4L2_PIX_FMT_STATS_RS v4l2_fourcc('S', 'T', 'R', 'S') -/* Bayer Grid stats */ -#define MSM_V4L2_PIX_FMT_STATS_BG v4l2_fourcc('S', 'T', 'B', 'G') -/* Bayer focus stats */ -#define MSM_V4L2_PIX_FMT_STATS_BF v4l2_fourcc('S', 'T', 'B', 'F') -/* Bayer hist stats */ -#define MSM_V4L2_PIX_FMT_STATS_BHST v4l2_fourcc('B', 'H', 'S', 'T') - -enum smmu_attach_mode { - NON_SECURE_MODE = 0x01, - SECURE_MODE = 0x02, - MAX_PROTECTION_MODE = 0x03, -}; - -struct msm_camera_smmu_attach_type { - enum smmu_attach_mode attach; -}; - -struct msm_camera_user_buf_cont_t { - unsigned int buf_cnt; - unsigned int buf_idx[MSM_CAMERA_MAX_USER_BUFF_CNT]; -}; - -#endif /* __LINUX_MSMB_CAMERA_H */ diff --git a/third_party/linux/include/msmb_isp.h b/third_party/linux/include/msmb_isp.h deleted file mode 100644 index 35589e050a4d06..00000000000000 --- a/third_party/linux/include/msmb_isp.h +++ /dev/null @@ -1,880 +0,0 @@ -#ifndef __MSMB_ISP__ -#define __MSMB_ISP__ - -#include - -#define MAX_PLANES_PER_STREAM 3 -#define MAX_NUM_STREAM 7 - -#define ISP_VERSION_47 47 -#define ISP_VERSION_46 46 -#define ISP_VERSION_44 44 -#define ISP_VERSION_40 40 -#define ISP_VERSION_32 32 -#define ISP_NATIVE_BUF_BIT (0x10000 << 0) -#define ISP0_BIT (0x10000 << 1) -#define ISP1_BIT (0x10000 << 2) -#define ISP_META_CHANNEL_BIT (0x10000 << 3) -#define ISP_SCRATCH_BUF_BIT (0x10000 << 4) -#define ISP_OFFLINE_STATS_BIT (0x10000 << 5) -#define ISP_STATS_STREAM_BIT 0x80000000 - -struct msm_vfe_cfg_cmd_list; - -enum ISP_START_PIXEL_PATTERN { - ISP_BAYER_RGRGRG, - ISP_BAYER_GRGRGR, - ISP_BAYER_BGBGBG, - ISP_BAYER_GBGBGB, - ISP_YUV_YCbYCr, - ISP_YUV_YCrYCb, - ISP_YUV_CbYCrY, - ISP_YUV_CrYCbY, - ISP_PIX_PATTERN_MAX -}; - -enum msm_vfe_plane_fmt { - Y_PLANE, - CB_PLANE, - CR_PLANE, - CRCB_PLANE, - CBCR_PLANE, - VFE_PLANE_FMT_MAX -}; - -enum msm_vfe_input_src { - VFE_PIX_0, - VFE_RAW_0, - VFE_RAW_1, - VFE_RAW_2, - VFE_SRC_MAX, -}; - -enum msm_vfe_axi_stream_src { - PIX_ENCODER, - PIX_VIEWFINDER, - PIX_VIDEO, - CAMIF_RAW, - IDEAL_RAW, - RDI_INTF_0, - RDI_INTF_1, - RDI_INTF_2, - VFE_AXI_SRC_MAX -}; - -enum msm_vfe_frame_skip_pattern { - NO_SKIP, - EVERY_2FRAME, - EVERY_3FRAME, - EVERY_4FRAME, - EVERY_5FRAME, - EVERY_6FRAME, - EVERY_7FRAME, - EVERY_8FRAME, - EVERY_16FRAME, - EVERY_32FRAME, - SKIP_ALL, - SKIP_RANGE, - MAX_SKIP, -}; - -/* - * Define an unused period. When this period is set it means that the stream is - * stopped(i.e the pattern is 0). We don't track the current pattern, just the - * period defines what the pattern is, if period is this then pattern is 0 else - * pattern is 1 - */ -#define MSM_VFE_STREAM_STOP_PERIOD 15 - -enum msm_isp_stats_type { - MSM_ISP_STATS_AEC, /* legacy based AEC */ - MSM_ISP_STATS_AF, /* legacy based AF */ - MSM_ISP_STATS_AWB, /* legacy based AWB */ - MSM_ISP_STATS_RS, /* legacy based RS */ - MSM_ISP_STATS_CS, /* legacy based CS */ - MSM_ISP_STATS_IHIST, /* legacy based HIST */ - MSM_ISP_STATS_SKIN, /* legacy based SKIN */ - MSM_ISP_STATS_BG, /* Bayer Grids */ - MSM_ISP_STATS_BF, /* Bayer Focus */ - MSM_ISP_STATS_BE, /* Bayer Exposure*/ - MSM_ISP_STATS_BHIST, /* Bayer Hist */ - MSM_ISP_STATS_BF_SCALE, /* Bayer Focus scale */ - MSM_ISP_STATS_HDR_BE, /* HDR Bayer Exposure */ - MSM_ISP_STATS_HDR_BHIST, /* HDR Bayer Hist */ - MSM_ISP_STATS_AEC_BG, /* AEC BG */ - MSM_ISP_STATS_MAX /* MAX */ -}; - -/* - * @stats_type_mask: Stats type mask (enum msm_isp_stats_type). - * @stream_src_mask: Stream src mask (enum msm_vfe_axi_stream_src) - * @skip_mode: skip pattern, if skip mode is range only then min/max is used - * @min_frame_id: minimum frame id (valid only if skip_mode = RANGE) - * @max_frame_id: maximum frame id (valid only if skip_mode = RANGE) -*/ -struct msm_isp_sw_framskip { - uint32_t stats_type_mask; - uint32_t stream_src_mask; - enum msm_vfe_frame_skip_pattern skip_mode; - uint32_t min_frame_id; - uint32_t max_frame_id; -}; - -enum msm_vfe_testgen_color_pattern { - COLOR_BAR_8_COLOR, - UNICOLOR_WHITE, - UNICOLOR_YELLOW, - UNICOLOR_CYAN, - UNICOLOR_GREEN, - UNICOLOR_MAGENTA, - UNICOLOR_RED, - UNICOLOR_BLUE, - UNICOLOR_BLACK, - MAX_COLOR, -}; - -enum msm_vfe_camif_input { - CAMIF_DISABLED, - CAMIF_PAD_REG_INPUT, - CAMIF_MIDDI_INPUT, - CAMIF_MIPI_INPUT, -}; - -struct msm_vfe_fetch_engine_cfg { - uint32_t input_format; - uint32_t buf_width; - uint32_t buf_height; - uint32_t fetch_width; - uint32_t fetch_height; - uint32_t x_offset; - uint32_t y_offset; - uint32_t buf_stride; -}; - -enum msm_vfe_camif_output_format { - CAMIF_QCOM_RAW, - CAMIF_MIPI_RAW, - CAMIF_PLAIN_8, - CAMIF_PLAIN_16, - CAMIF_MAX_FORMAT, -}; - -/* - * Camif output general configuration - */ -struct msm_vfe_camif_subsample_cfg { - uint32_t irq_subsample_period; - uint32_t irq_subsample_pattern; - uint32_t sof_counter_step; - uint32_t pixel_skip; - uint32_t line_skip; - uint32_t first_line; - uint32_t last_line; - uint32_t first_pixel; - uint32_t last_pixel; - enum msm_vfe_camif_output_format output_format; -}; - -/* - * Camif frame and window configuration - */ -struct msm_vfe_camif_cfg { - uint32_t lines_per_frame; - uint32_t pixels_per_line; - uint32_t first_pixel; - uint32_t last_pixel; - uint32_t first_line; - uint32_t last_line; - uint32_t epoch_line0; - uint32_t epoch_line1; - uint32_t is_split; - enum msm_vfe_camif_input camif_input; - struct msm_vfe_camif_subsample_cfg subsample_cfg; -}; - -struct msm_vfe_testgen_cfg { - uint32_t lines_per_frame; - uint32_t pixels_per_line; - uint32_t v_blank; - uint32_t h_blank; - enum ISP_START_PIXEL_PATTERN pixel_bayer_pattern; - uint32_t rotate_period; - enum msm_vfe_testgen_color_pattern color_bar_pattern; - uint32_t burst_num_frame; -}; - -enum msm_vfe_inputmux { - CAMIF, - TESTGEN, - EXTERNAL_READ, -}; - -enum msm_vfe_stats_composite_group { - STATS_COMPOSITE_GRP_NONE, - STATS_COMPOSITE_GRP_1, - STATS_COMPOSITE_GRP_2, - STATS_COMPOSITE_GRP_MAX, -}; - -enum msm_vfe_hvx_streaming_cmd { - HVX_DISABLE, - HVX_ONE_WAY, - HVX_ROUND_TRIP -}; - -struct msm_vfe_pix_cfg { - struct msm_vfe_camif_cfg camif_cfg; - struct msm_vfe_testgen_cfg testgen_cfg; - struct msm_vfe_fetch_engine_cfg fetch_engine_cfg; - enum msm_vfe_inputmux input_mux; - enum ISP_START_PIXEL_PATTERN pixel_pattern; - uint32_t input_format; - enum msm_vfe_hvx_streaming_cmd hvx_cmd; - uint32_t is_split; -}; - -struct msm_vfe_rdi_cfg { - uint8_t cid; - uint8_t frame_based; -}; - -struct msm_vfe_input_cfg { - union { - struct msm_vfe_pix_cfg pix_cfg; - struct msm_vfe_rdi_cfg rdi_cfg; - } d; - enum msm_vfe_input_src input_src; - uint32_t input_pix_clk; -}; - -struct msm_vfe_fetch_eng_start { - uint32_t session_id; - uint32_t stream_id; - uint32_t buf_idx; - uint8_t offline_mode; - uint32_t fd; - uint32_t buf_addr; - uint32_t frame_id; -}; - -struct msm_vfe_axi_plane_cfg { - uint32_t output_width; /*Include padding*/ - uint32_t output_height; - uint32_t output_stride; - uint32_t output_scan_lines; - uint32_t output_plane_format; /*Y/Cb/Cr/CbCr*/ - uint32_t plane_addr_offset; - uint8_t csid_src; /*RDI 0-2*/ - uint8_t rdi_cid;/*CID 1-16*/ -}; - -enum msm_stream_memory_input_t { - MEMORY_INPUT_DISABLED, - MEMORY_INPUT_ENABLED -}; - -struct msm_vfe_axi_stream_request_cmd { - uint32_t session_id; - uint32_t stream_id; - uint32_t vt_enable; - uint32_t output_format;/*Planar/RAW/Misc*/ - enum msm_vfe_axi_stream_src stream_src; /*CAMIF/IDEAL/RDIs*/ - struct msm_vfe_axi_plane_cfg plane_cfg[MAX_PLANES_PER_STREAM]; - - uint32_t burst_count; - uint32_t hfr_mode; - uint8_t frame_base; - - uint32_t init_frame_drop; /*MAX 31 Frames*/ - enum msm_vfe_frame_skip_pattern frame_skip_pattern; - uint8_t buf_divert; /* if TRUE no vb2 buf done. */ - /*Return values*/ - uint32_t axi_stream_handle; - uint32_t controllable_output; - uint32_t burst_len; - /* Flag indicating memory input stream */ - enum msm_stream_memory_input_t memory_input; -}; - -struct msm_vfe_axi_stream_release_cmd { - uint32_t stream_handle; -}; - -enum msm_vfe_axi_stream_cmd { - STOP_STREAM, - START_STREAM, - STOP_IMMEDIATELY, -}; - -struct msm_vfe_axi_stream_cfg_cmd { - uint8_t num_streams; - uint32_t stream_handle[VFE_AXI_SRC_MAX]; - enum msm_vfe_axi_stream_cmd cmd; - uint8_t sync_frame_id_src; -}; - -enum msm_vfe_axi_stream_update_type { - ENABLE_STREAM_BUF_DIVERT, - DISABLE_STREAM_BUF_DIVERT, - UPDATE_STREAM_FRAMEDROP_PATTERN, - UPDATE_STREAM_STATS_FRAMEDROP_PATTERN, - UPDATE_STREAM_AXI_CONFIG, - UPDATE_STREAM_REQUEST_FRAMES, - UPDATE_STREAM_ADD_BUFQ, - UPDATE_STREAM_REMOVE_BUFQ, - UPDATE_STREAM_SW_FRAME_DROP, -}; - -enum msm_vfe_iommu_type { - IOMMU_ATTACH, - IOMMU_DETACH, -}; - -enum msm_vfe_buff_queue_id { - VFE_BUF_QUEUE_DEFAULT, - VFE_BUF_QUEUE_SHARED, - VFE_BUF_QUEUE_MAX, -}; - -struct msm_vfe_axi_stream_cfg_update_info { - uint32_t stream_handle; - uint32_t output_format; - uint32_t user_stream_id; - uint32_t frame_id; - enum msm_vfe_frame_skip_pattern skip_pattern; - struct msm_vfe_axi_plane_cfg plane_cfg[MAX_PLANES_PER_STREAM]; - struct msm_isp_sw_framskip sw_skip_info; -}; - -struct msm_vfe_axi_halt_cmd { - uint32_t stop_camif; - uint32_t overflow_detected; - uint32_t blocking_halt; -}; - -struct msm_vfe_axi_reset_cmd { - uint32_t blocking; - uint32_t frame_id; -}; - -struct msm_vfe_axi_restart_cmd { - uint32_t enable_camif; -}; - -struct msm_vfe_axi_stream_update_cmd { - uint32_t num_streams; - enum msm_vfe_axi_stream_update_type update_type; - struct msm_vfe_axi_stream_cfg_update_info - update_info[MSM_ISP_STATS_MAX]; -}; - -struct msm_vfe_smmu_attach_cmd { - uint32_t security_mode; - uint32_t iommu_attach_mode; -}; - -struct msm_vfe_stats_stream_request_cmd { - uint32_t session_id; - uint32_t stream_id; - enum msm_isp_stats_type stats_type; - uint32_t composite_flag; - uint32_t framedrop_pattern; - uint32_t init_frame_drop; /*MAX 31 Frames*/ - uint32_t irq_subsample_pattern; - uint32_t buffer_offset; - uint32_t stream_handle; -}; - -struct msm_vfe_stats_stream_release_cmd { - uint32_t stream_handle; -}; -struct msm_vfe_stats_stream_cfg_cmd { - uint8_t num_streams; - uint32_t stream_handle[MSM_ISP_STATS_MAX]; - uint8_t enable; - uint32_t stats_burst_len; -}; - -enum msm_vfe_reg_cfg_type { - VFE_WRITE, - VFE_WRITE_MB, - VFE_READ, - VFE_CFG_MASK, - VFE_WRITE_DMI_16BIT, - VFE_WRITE_DMI_32BIT, - VFE_WRITE_DMI_64BIT, - VFE_READ_DMI_16BIT, - VFE_READ_DMI_32BIT, - VFE_READ_DMI_64BIT, - GET_MAX_CLK_RATE, - GET_CLK_RATES, - GET_ISP_ID, - VFE_HW_UPDATE_LOCK, - VFE_HW_UPDATE_UNLOCK, - SET_WM_UB_SIZE, - SET_UB_POLICY, -}; - -struct msm_vfe_cfg_cmd2 { - uint16_t num_cfg; - uint16_t cmd_len; - void __user *cfg_data; - void __user *cfg_cmd; -}; - -struct msm_vfe_cfg_cmd_list { - struct msm_vfe_cfg_cmd2 cfg_cmd; - struct msm_vfe_cfg_cmd_list *next; - uint32_t next_size; -}; - -struct msm_vfe_reg_rw_info { - uint32_t reg_offset; - uint32_t cmd_data_offset; - uint32_t len; -}; - -struct msm_vfe_reg_mask_info { - uint32_t reg_offset; - uint32_t mask; - uint32_t val; -}; - -struct msm_vfe_reg_dmi_info { - uint32_t hi_tbl_offset; /*Optional*/ - uint32_t lo_tbl_offset; /*Required*/ - uint32_t len; -}; - -struct msm_vfe_reg_cfg_cmd { - union { - struct msm_vfe_reg_rw_info rw_info; - struct msm_vfe_reg_mask_info mask_info; - struct msm_vfe_reg_dmi_info dmi_info; - } u; - - enum msm_vfe_reg_cfg_type cmd_type; -}; - -enum vfe_sd_type { - VFE_SD_0 = 0, - VFE_SD_1, - VFE_SD_COMMON, - VFE_SD_MAX, -}; - -/* When you change the value below, check for the sof event_data size. - * V4l2 limits payload to 64 bytes */ -#define MS_NUM_SLAVE_MAX 1 - -/* Usecases when 2 HW need to be related or synced */ -enum msm_vfe_dual_hw_type { - DUAL_NONE = 0, - DUAL_HW_VFE_SPLIT = 1, - DUAL_HW_MASTER_SLAVE = 2, -}; - -/* Type for 2 INTF when used in Master-Slave mode */ -enum msm_vfe_dual_hw_ms_type { - MS_TYPE_NONE, - MS_TYPE_MASTER, - MS_TYPE_SLAVE, -}; - -struct msm_isp_set_dual_hw_ms_cmd { - uint8_t num_src; - /* Each session can be only one type but multiple intf if YUV cam */ - enum msm_vfe_dual_hw_ms_type dual_hw_ms_type; - /* Primary intf is mostly associated with preview. - * This primary intf SOF frame_id and timestamp is tracked - * and used to calculate delta */ - enum msm_vfe_input_src primary_intf; - /* input_src array indicates other input INTF that may be Master/Slave. - * For these additional intf, frame_id and timestamp are not saved. - * However, if these are slaves then they will still get their - * frame_id from Master */ - enum msm_vfe_input_src input_src[VFE_SRC_MAX]; - uint32_t sof_delta_threshold; /* In milliseconds. Sent for Master */ -}; - -enum msm_isp_buf_type { - ISP_PRIVATE_BUF, - ISP_SHARE_BUF, - MAX_ISP_BUF_TYPE, -}; - -struct msm_isp_unmap_buf_req { - uint32_t fd; -}; - -struct msm_isp_buf_request { - uint32_t session_id; - uint32_t stream_id; - uint8_t num_buf; - uint32_t handle; - enum msm_isp_buf_type buf_type; -}; - -struct msm_isp_qbuf_plane { - uint32_t addr; - uint32_t offset; - uint32_t length; -}; - -struct msm_isp_qbuf_buffer { - struct msm_isp_qbuf_plane planes[MAX_PLANES_PER_STREAM]; - uint32_t num_planes; -}; - -struct msm_isp_qbuf_info { - uint32_t handle; - int32_t buf_idx; - /*Only used for prepare buffer*/ - struct msm_isp_qbuf_buffer buffer; - /*Only used for diverted buffer*/ - uint32_t dirty_buf; -}; - -struct msm_isp_clk_rates { - uint32_t svs_rate; - uint32_t nominal_rate; - uint32_t high_rate; -}; - -struct msm_vfe_axi_src_state { - enum msm_vfe_input_src input_src; - uint32_t src_active; - uint32_t src_frame_id; -}; - -enum msm_isp_event_mask_index { - ISP_EVENT_MASK_INDEX_STATS_NOTIFY = 0, - ISP_EVENT_MASK_INDEX_ERROR = 1, - ISP_EVENT_MASK_INDEX_IOMMU_P_FAULT = 2, - ISP_EVENT_MASK_INDEX_STREAM_UPDATE_DONE = 3, - ISP_EVENT_MASK_INDEX_REG_UPDATE = 4, - ISP_EVENT_MASK_INDEX_SOF = 5, - ISP_EVENT_MASK_INDEX_BUF_DIVERT = 6, - ISP_EVENT_MASK_INDEX_COMP_STATS_NOTIFY = 7, - ISP_EVENT_MASK_INDEX_MASK_FE_READ_DONE = 8, - ISP_EVENT_MASK_INDEX_BUF_DONE = 9, - ISP_EVENT_MASK_INDEX_REG_UPDATE_MISSING = 10, - ISP_EVENT_MASK_INDEX_PING_PONG_MISMATCH = 11, - ISP_EVENT_MASK_INDEX_BUF_FATAL_ERROR = 12, -}; - - -#define ISP_EVENT_SUBS_MASK_NONE 0 - -#define ISP_EVENT_SUBS_MASK_STATS_NOTIFY \ - (1 << ISP_EVENT_MASK_INDEX_STATS_NOTIFY) - -#define ISP_EVENT_SUBS_MASK_ERROR \ - (1 << ISP_EVENT_MASK_INDEX_ERROR) - -#define ISP_EVENT_SUBS_MASK_IOMMU_P_FAULT \ - (1 << ISP_EVENT_MASK_INDEX_IOMMU_P_FAULT) - -#define ISP_EVENT_SUBS_MASK_STREAM_UPDATE_DONE \ - (1 << ISP_EVENT_MASK_INDEX_STREAM_UPDATE_DONE) - -#define ISP_EVENT_SUBS_MASK_REG_UPDATE \ - (1 << ISP_EVENT_MASK_INDEX_REG_UPDATE) - -#define ISP_EVENT_SUBS_MASK_SOF \ - (1 << ISP_EVENT_MASK_INDEX_SOF) - -#define ISP_EVENT_SUBS_MASK_BUF_DIVERT \ - (1 << ISP_EVENT_MASK_INDEX_BUF_DIVERT) - -#define ISP_EVENT_SUBS_MASK_COMP_STATS_NOTIFY \ - (1 << ISP_EVENT_MASK_INDEX_COMP_STATS_NOTIFY) - -#define ISP_EVENT_SUBS_MASK_FE_READ_DONE \ - (1 << ISP_EVENT_MASK_INDEX_MASK_FE_READ_DONE) - -#define ISP_EVENT_SUBS_MASK_BUF_DONE \ - (1 << ISP_EVENT_MASK_INDEX_BUF_DONE) - -#define ISP_EVENT_SUBS_MASK_REG_UPDATE_MISSING \ - (1 << ISP_EVENT_MASK_INDEX_REG_UPDATE_MISSING) - -#define ISP_EVENT_SUBS_MASK_PING_PONG_MISMATCH \ - (1 << ISP_EVENT_MASK_INDEX_PING_PONG_MISMATCH) - -#define ISP_EVENT_SUBS_MASK_BUF_FATAL_ERROR \ - (1 << ISP_EVENT_MASK_INDEX_BUF_FATAL_ERROR) - -enum msm_isp_event_idx { - ISP_REG_UPDATE = 0, - ISP_EPOCH_0 = 1, - ISP_EPOCH_1 = 2, - ISP_START_ACK = 3, - ISP_STOP_ACK = 4, - ISP_IRQ_VIOLATION = 5, - ISP_STATS_OVERFLOW = 6, - ISP_BUF_DONE = 7, - ISP_FE_RD_DONE = 8, - ISP_IOMMU_P_FAULT = 9, - ISP_ERROR = 10, - ISP_HW_FATAL_ERROR = 11, - ISP_PING_PONG_MISMATCH = 12, - ISP_REG_UPDATE_MISSING = 13, - ISP_BUF_FATAL_ERROR = 14, - ISP_EVENT_MAX = 15 -}; - -#define ISP_EVENT_OFFSET 8 -#define ISP_EVENT_BASE (V4L2_EVENT_PRIVATE_START) -#define ISP_BUF_EVENT_BASE (ISP_EVENT_BASE + (1 << ISP_EVENT_OFFSET)) -#define ISP_STATS_EVENT_BASE (ISP_EVENT_BASE + (2 << ISP_EVENT_OFFSET)) -#define ISP_CAMIF_EVENT_BASE (ISP_EVENT_BASE + (3 << ISP_EVENT_OFFSET)) -#define ISP_STREAM_EVENT_BASE (ISP_EVENT_BASE + (4 << ISP_EVENT_OFFSET)) -#define ISP_EVENT_REG_UPDATE (ISP_EVENT_BASE + ISP_REG_UPDATE) -#define ISP_EVENT_EPOCH_0 (ISP_EVENT_BASE + ISP_EPOCH_0) -#define ISP_EVENT_EPOCH_1 (ISP_EVENT_BASE + ISP_EPOCH_1) -#define ISP_EVENT_START_ACK (ISP_EVENT_BASE + ISP_START_ACK) -#define ISP_EVENT_STOP_ACK (ISP_EVENT_BASE + ISP_STOP_ACK) -#define ISP_EVENT_IRQ_VIOLATION (ISP_EVENT_BASE + ISP_IRQ_VIOLATION) -#define ISP_EVENT_STATS_OVERFLOW (ISP_EVENT_BASE + ISP_STATS_OVERFLOW) -#define ISP_EVENT_ERROR (ISP_EVENT_BASE + ISP_ERROR) -#define ISP_EVENT_SOF (ISP_CAMIF_EVENT_BASE) -#define ISP_EVENT_EOF (ISP_CAMIF_EVENT_BASE + 1) -#define ISP_EVENT_BUF_DONE (ISP_EVENT_BASE + ISP_BUF_DONE) -#define ISP_EVENT_BUF_DIVERT (ISP_BUF_EVENT_BASE) -#define ISP_EVENT_STATS_NOTIFY (ISP_STATS_EVENT_BASE) -#define ISP_EVENT_COMP_STATS_NOTIFY (ISP_EVENT_STATS_NOTIFY + MSM_ISP_STATS_MAX) -#define ISP_EVENT_FE_READ_DONE (ISP_EVENT_BASE + ISP_FE_RD_DONE) -#define ISP_EVENT_IOMMU_P_FAULT (ISP_EVENT_BASE + ISP_IOMMU_P_FAULT) -#define ISP_EVENT_HW_FATAL_ERROR (ISP_EVENT_BASE + ISP_HW_FATAL_ERROR) -#define ISP_EVENT_PING_PONG_MISMATCH (ISP_EVENT_BASE + ISP_PING_PONG_MISMATCH) -#define ISP_EVENT_REG_UPDATE_MISSING (ISP_EVENT_BASE + ISP_REG_UPDATE_MISSING) -#define ISP_EVENT_BUF_FATAL_ERROR (ISP_EVENT_BASE + ISP_BUF_FATAL_ERROR) -#define ISP_EVENT_STREAM_UPDATE_DONE (ISP_STREAM_EVENT_BASE) - -/* The msm_v4l2_event_data structure should match the - * v4l2_event.u.data field. - * should not exceed 64 bytes */ - -struct msm_isp_buf_event { - uint32_t session_id; - uint32_t stream_id; - uint32_t handle; - uint32_t output_format; - int8_t buf_idx; -}; -struct msm_isp_fetch_eng_event { - uint32_t session_id; - uint32_t stream_id; - uint32_t handle; - uint32_t fd; - int8_t buf_idx; - int8_t offline_mode; -}; -struct msm_isp_stats_event { - uint32_t stats_mask; /* 4 bytes */ - uint8_t stats_buf_idxs[MSM_ISP_STATS_MAX]; /* 11 bytes */ -}; - -struct msm_isp_stream_ack { - uint32_t session_id; - uint32_t stream_id; - uint32_t handle; -}; - -enum msm_vfe_error_type { - ISP_ERROR_NONE, - ISP_ERROR_CAMIF, - ISP_ERROR_BUS_OVERFLOW, - ISP_ERROR_RETURN_EMPTY_BUFFER, - ISP_ERROR_FRAME_ID_MISMATCH, - ISP_ERROR_MAX, -}; - -struct msm_isp_error_info { - enum msm_vfe_error_type err_type; - uint32_t session_id; - uint32_t stream_id; - uint32_t stream_id_mask; -}; - -/* This structure reports delta between master and slave */ -struct msm_isp_ms_delta_info { - uint8_t num_delta_info; - uint32_t delta[MS_NUM_SLAVE_MAX]; -}; - -/* This is sent in EPOCH irq */ -struct msm_isp_output_info { - uint8_t regs_not_updated; - /* mask with bufq_handle for regs not updated or return empty */ - uint16_t output_err_mask; - /* mask with stream_idx for get_buf failed */ - uint8_t stream_framedrop_mask; - /* mask with stats stream_idx for get_buf failed */ - uint16_t stats_framedrop_mask; - /* delta between master and slave */ -}; - -/* This structure is piggybacked with SOF event */ -struct msm_isp_sof_info { - uint8_t regs_not_updated; - /* mask with AXI_SRC for regs not updated */ - uint16_t reg_update_fail_mask; - /* mask with bufq_handle for get_buf failed */ - uint32_t stream_get_buf_fail_mask; - /* mask with stats stream_idx for get_buf failed */ - uint16_t stats_get_buf_fail_mask; - /* delta between master and slave */ - struct msm_isp_ms_delta_info ms_delta_info; -}; - -struct msm_isp_event_data { - /*Wall clock except for buffer divert events - *which use monotonic clock - */ - struct timeval timestamp; - /* Monotonic timestamp since bootup */ - struct timeval mono_timestamp; - uint32_t frame_id; - union { - /* Sent for Stats_Done event */ - struct msm_isp_stats_event stats; - /* Sent for Buf_Divert event */ - struct msm_isp_buf_event buf_done; - /* Sent for offline fetch done event */ - struct msm_isp_fetch_eng_event fetch_done; - /* Sent for Error_Event */ - struct msm_isp_error_info error_info; - /* - * This struct needs to be removed once - * userspace switches to sof_info - */ - struct msm_isp_output_info output_info; - /* Sent for SOF event */ - struct msm_isp_sof_info sof_info; - } u; /* union can have max 52 bytes */ -}; - -#ifdef CONFIG_COMPAT -struct msm_isp_event_data32 { - struct compat_timeval timestamp; - struct compat_timeval mono_timestamp; - uint32_t frame_id; - union { - struct msm_isp_stats_event stats; - struct msm_isp_buf_event buf_done; - struct msm_isp_fetch_eng_event fetch_done; - struct msm_isp_error_info error_info; - struct msm_isp_output_info output_info; - struct msm_isp_sof_info sof_info; - } u; -}; -#endif - -#define V4L2_PIX_FMT_QBGGR8 v4l2_fourcc('Q', 'B', 'G', '8') -#define V4L2_PIX_FMT_QGBRG8 v4l2_fourcc('Q', 'G', 'B', '8') -#define V4L2_PIX_FMT_QGRBG8 v4l2_fourcc('Q', 'G', 'R', '8') -#define V4L2_PIX_FMT_QRGGB8 v4l2_fourcc('Q', 'R', 'G', '8') -#define V4L2_PIX_FMT_QBGGR10 v4l2_fourcc('Q', 'B', 'G', '0') -#define V4L2_PIX_FMT_QGBRG10 v4l2_fourcc('Q', 'G', 'B', '0') -#define V4L2_PIX_FMT_QGRBG10 v4l2_fourcc('Q', 'G', 'R', '0') -#define V4L2_PIX_FMT_QRGGB10 v4l2_fourcc('Q', 'R', 'G', '0') -#define V4L2_PIX_FMT_QBGGR12 v4l2_fourcc('Q', 'B', 'G', '2') -#define V4L2_PIX_FMT_QGBRG12 v4l2_fourcc('Q', 'G', 'B', '2') -#define V4L2_PIX_FMT_QGRBG12 v4l2_fourcc('Q', 'G', 'R', '2') -#define V4L2_PIX_FMT_QRGGB12 v4l2_fourcc('Q', 'R', 'G', '2') -#define V4L2_PIX_FMT_QBGGR14 v4l2_fourcc('Q', 'B', 'G', '4') -#define V4L2_PIX_FMT_QGBRG14 v4l2_fourcc('Q', 'G', 'B', '4') -#define V4L2_PIX_FMT_QGRBG14 v4l2_fourcc('Q', 'G', 'R', '4') -#define V4L2_PIX_FMT_QRGGB14 v4l2_fourcc('Q', 'R', 'G', '4') -#define V4L2_PIX_FMT_P16BGGR10 v4l2_fourcc('P', 'B', 'G', '0') -#define V4L2_PIX_FMT_P16GBRG10 v4l2_fourcc('P', 'G', 'B', '0') -#define V4L2_PIX_FMT_P16GRBG10 v4l2_fourcc('P', 'G', 'R', '0') -#define V4L2_PIX_FMT_P16RGGB10 v4l2_fourcc('P', 'R', 'G', '0') -#define V4L2_PIX_FMT_NV14 v4l2_fourcc('N', 'V', '1', '4') -#define V4L2_PIX_FMT_NV41 v4l2_fourcc('N', 'V', '4', '1') -#define V4L2_PIX_FMT_META v4l2_fourcc('Q', 'M', 'E', 'T') -#define V4L2_PIX_FMT_SBGGR14 v4l2_fourcc('B', 'G', '1', '4') /* 14 BGBG.GRGR.*/ -#define V4L2_PIX_FMT_SGBRG14 v4l2_fourcc('G', 'B', '1', '4') /* 14 GBGB.RGRG.*/ -#define V4L2_PIX_FMT_SGRBG14 v4l2_fourcc('B', 'A', '1', '4') /* 14 GRGR.BGBG.*/ -#define V4L2_PIX_FMT_SRGGB14 v4l2_fourcc('R', 'G', '1', '4') /* 14 RGRG.GBGB.*/ - -#define VIDIOC_MSM_VFE_REG_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE, struct msm_vfe_cfg_cmd2) - -#define VIDIOC_MSM_ISP_REQUEST_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+1, struct msm_isp_buf_request) - -#define VIDIOC_MSM_ISP_ENQUEUE_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+2, struct msm_isp_qbuf_info) - -#define VIDIOC_MSM_ISP_RELEASE_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+3, struct msm_isp_buf_request) - -#define VIDIOC_MSM_ISP_REQUEST_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+4, struct msm_vfe_axi_stream_request_cmd) - -#define VIDIOC_MSM_ISP_CFG_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+5, struct msm_vfe_axi_stream_cfg_cmd) - -#define VIDIOC_MSM_ISP_RELEASE_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+6, struct msm_vfe_axi_stream_release_cmd) - -#define VIDIOC_MSM_ISP_INPUT_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE+7, struct msm_vfe_input_cfg) - -#define VIDIOC_MSM_ISP_SET_SRC_STATE \ - _IOWR('V', BASE_VIDIOC_PRIVATE+8, struct msm_vfe_axi_src_state) - -#define VIDIOC_MSM_ISP_REQUEST_STATS_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+9, \ - struct msm_vfe_stats_stream_request_cmd) - -#define VIDIOC_MSM_ISP_CFG_STATS_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+10, struct msm_vfe_stats_stream_cfg_cmd) - -#define VIDIOC_MSM_ISP_RELEASE_STATS_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+11, \ - struct msm_vfe_stats_stream_release_cmd) - -#define VIDIOC_MSM_ISP_REG_UPDATE_CMD \ - _IOWR('V', BASE_VIDIOC_PRIVATE+12, enum msm_vfe_input_src) - -#define VIDIOC_MSM_ISP_UPDATE_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+13, struct msm_vfe_axi_stream_update_cmd) - -#define VIDIOC_MSM_VFE_REG_LIST_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE+14, struct msm_vfe_cfg_cmd_list) - -#define VIDIOC_MSM_ISP_SMMU_ATTACH \ - _IOWR('V', BASE_VIDIOC_PRIVATE+15, struct msm_vfe_smmu_attach_cmd) - -#define VIDIOC_MSM_ISP_UPDATE_STATS_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+16, struct msm_vfe_axi_stream_update_cmd) - -#define VIDIOC_MSM_ISP_AXI_HALT \ - _IOWR('V', BASE_VIDIOC_PRIVATE+17, struct msm_vfe_axi_halt_cmd) - -#define VIDIOC_MSM_ISP_AXI_RESET \ - _IOWR('V', BASE_VIDIOC_PRIVATE+18, struct msm_vfe_axi_reset_cmd) - -#define VIDIOC_MSM_ISP_AXI_RESTART \ - _IOWR('V', BASE_VIDIOC_PRIVATE+19, struct msm_vfe_axi_restart_cmd) - -#define VIDIOC_MSM_ISP_FETCH_ENG_START \ - _IOWR('V', BASE_VIDIOC_PRIVATE+20, struct msm_vfe_fetch_eng_start) - -#define VIDIOC_MSM_ISP_DEQUEUE_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+21, struct msm_isp_qbuf_info) - -#define VIDIOC_MSM_ISP_SET_DUAL_HW_MASTER_SLAVE \ - _IOWR('V', BASE_VIDIOC_PRIVATE+22, struct msm_isp_set_dual_hw_ms_cmd) - -#define VIDIOC_MSM_ISP_MAP_BUF_START_FE \ - _IOWR('V', BASE_VIDIOC_PRIVATE+23, struct msm_vfe_fetch_eng_start) - -#define VIDIOC_MSM_ISP_UNMAP_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+24, struct msm_isp_unmap_buf_req) - -#endif /* __MSMB_ISP__ */ diff --git a/third_party/linux/include/msmb_ispif.h b/third_party/linux/include/msmb_ispif.h deleted file mode 100644 index 2564c33b7b31ed..00000000000000 --- a/third_party/linux/include/msmb_ispif.h +++ /dev/null @@ -1,125 +0,0 @@ -#ifndef MSM_CAM_ISPIF_H -#define MSM_CAM_ISPIF_H - -#define CSID_VERSION_V20 0x02000011 -#define CSID_VERSION_V22 0x02001000 -#define CSID_VERSION_V30 0x30000000 -#define CSID_VERSION_V3 0x30000000 - -enum msm_ispif_vfe_intf { - VFE0, - VFE1, - VFE_MAX -}; -#define VFE0_MASK (1 << VFE0) -#define VFE1_MASK (1 << VFE1) - -enum msm_ispif_intftype { - PIX0, - RDI0, - PIX1, - RDI1, - RDI2, - INTF_MAX -}; -#define MAX_PARAM_ENTRIES (INTF_MAX * 2) -#define MAX_CID_CH 8 - -#define PIX0_MASK (1 << PIX0) -#define PIX1_MASK (1 << PIX1) -#define RDI0_MASK (1 << RDI0) -#define RDI1_MASK (1 << RDI1) -#define RDI2_MASK (1 << RDI2) - - -enum msm_ispif_vc { - VC0, - VC1, - VC2, - VC3, - VC_MAX -}; - -enum msm_ispif_cid { - CID0, - CID1, - CID2, - CID3, - CID4, - CID5, - CID6, - CID7, - CID8, - CID9, - CID10, - CID11, - CID12, - CID13, - CID14, - CID15, - CID_MAX -}; - -enum msm_ispif_csid { - CSID0, - CSID1, - CSID2, - CSID3, - CSID_MAX -}; - -struct msm_ispif_params_entry { - enum msm_ispif_vfe_intf vfe_intf; - enum msm_ispif_intftype intftype; - int num_cids; - enum msm_ispif_cid cids[3]; - enum msm_ispif_csid csid; - int crop_enable; - uint16_t crop_start_pixel; - uint16_t crop_end_pixel; -}; - -struct msm_ispif_param_data { - uint32_t num; - struct msm_ispif_params_entry entries[MAX_PARAM_ENTRIES]; -}; - -struct msm_isp_info { - uint32_t max_resolution; - uint32_t id; - uint32_t ver; -}; - -struct msm_ispif_vfe_info { - int num_vfe; - struct msm_isp_info info[VFE_MAX]; -}; - -enum ispif_cfg_type_t { - ISPIF_CLK_ENABLE, - ISPIF_CLK_DISABLE, - ISPIF_INIT, - ISPIF_CFG, - ISPIF_START_FRAME_BOUNDARY, - ISPIF_RESTART_FRAME_BOUNDARY, - ISPIF_STOP_FRAME_BOUNDARY, - ISPIF_STOP_IMMEDIATELY, - ISPIF_RELEASE, - ISPIF_ENABLE_REG_DUMP, - ISPIF_SET_VFE_INFO, -}; - -struct ispif_cfg_data { - enum ispif_cfg_type_t cfg_type; - union { - int reg_dump; /* ISPIF_ENABLE_REG_DUMP */ - uint32_t csid_version; /* ISPIF_INIT */ - struct msm_ispif_vfe_info vfe_info; /* ISPIF_SET_VFE_INFO */ - struct msm_ispif_param_data params; /* CFG, START, STOP */ - }; -}; - -#define VIDIOC_MSM_ISPIF_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE, struct ispif_cfg_data) - -#endif /* MSM_CAM_ISPIF_H */ diff --git a/third_party/linux/include/v4l2-controls.h b/third_party/linux/include/v4l2-controls.h deleted file mode 100644 index d14cd8fabee1c7..00000000000000 --- a/third_party/linux/include/v4l2-controls.h +++ /dev/null @@ -1,1696 +0,0 @@ -/* - * Video for Linux Two controls header file - * - * Copyright (C) 1999-2012 the contributors - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * Alternatively you can redistribute this file under the terms of the - * BSD license as stated below: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. The names of its contributors may not be used to endorse or promote - * products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The contents of this header was split off from videodev2.h. All control - * definitions should be added to this header, which is included by - * videodev2.h. - */ - -#ifndef __LINUX_V4L2_CONTROLS_H -#define __LINUX_V4L2_CONTROLS_H - -/* Control classes */ -#define V4L2_CTRL_CLASS_USER 0x00980000 /* Old-style 'user' controls */ -#define V4L2_CTRL_CLASS_MPEG 0x00990000 /* MPEG-compression controls */ -#define V4L2_CTRL_CLASS_CAMERA 0x009a0000 /* Camera class controls */ -#define V4L2_CTRL_CLASS_FM_TX 0x009b0000 /* FM Modulator controls */ -#define V4L2_CTRL_CLASS_FLASH 0x009c0000 /* Camera flash controls */ -#define V4L2_CTRL_CLASS_JPEG 0x009d0000 /* JPEG-compression controls */ -#define V4L2_CTRL_CLASS_IMAGE_SOURCE 0x009e0000 /* Image source controls */ -#define V4L2_CTRL_CLASS_IMAGE_PROC 0x009f0000 /* Image processing controls */ -#define V4L2_CTRL_CLASS_DV 0x00a00000 /* Digital Video controls */ -#define V4L2_CTRL_CLASS_FM_RX 0x00a10000 /* FM Receiver controls */ -#define V4L2_CTRL_CLASS_RF_TUNER 0x00a20000 /* RF tuner controls */ -#define V4L2_CTRL_CLASS_DETECT 0x00a30000 /* Detection controls */ - -/* User-class control IDs */ - -#define V4L2_CID_BASE (V4L2_CTRL_CLASS_USER | 0x900) -#define V4L2_CID_USER_BASE V4L2_CID_BASE -#define V4L2_CID_USER_CLASS (V4L2_CTRL_CLASS_USER | 1) -#define V4L2_CID_BRIGHTNESS (V4L2_CID_BASE+0) -#define V4L2_CID_CONTRAST (V4L2_CID_BASE+1) -#define V4L2_CID_SATURATION (V4L2_CID_BASE+2) -#define V4L2_CID_HUE (V4L2_CID_BASE+3) -#define V4L2_CID_AUDIO_VOLUME (V4L2_CID_BASE+5) -#define V4L2_CID_AUDIO_BALANCE (V4L2_CID_BASE+6) -#define V4L2_CID_AUDIO_BASS (V4L2_CID_BASE+7) -#define V4L2_CID_AUDIO_TREBLE (V4L2_CID_BASE+8) -#define V4L2_CID_AUDIO_MUTE (V4L2_CID_BASE+9) -#define V4L2_CID_AUDIO_LOUDNESS (V4L2_CID_BASE+10) -#define V4L2_CID_BLACK_LEVEL (V4L2_CID_BASE+11) /* Deprecated */ -#define V4L2_CID_AUTO_WHITE_BALANCE (V4L2_CID_BASE+12) -#define V4L2_CID_DO_WHITE_BALANCE (V4L2_CID_BASE+13) -#define V4L2_CID_RED_BALANCE (V4L2_CID_BASE+14) -#define V4L2_CID_BLUE_BALANCE (V4L2_CID_BASE+15) -#define V4L2_CID_GAMMA (V4L2_CID_BASE+16) -#define V4L2_CID_WHITENESS (V4L2_CID_GAMMA) /* Deprecated */ -#define V4L2_CID_EXPOSURE (V4L2_CID_BASE+17) -#define V4L2_CID_AUTOGAIN (V4L2_CID_BASE+18) -#define V4L2_CID_GAIN (V4L2_CID_BASE+19) -#define V4L2_CID_HFLIP (V4L2_CID_BASE+20) -#define V4L2_CID_VFLIP (V4L2_CID_BASE+21) - -#define V4L2_CID_POWER_LINE_FREQUENCY (V4L2_CID_BASE+24) -enum v4l2_power_line_frequency { - V4L2_CID_POWER_LINE_FREQUENCY_DISABLED = 0, - V4L2_CID_POWER_LINE_FREQUENCY_50HZ = 1, - V4L2_CID_POWER_LINE_FREQUENCY_60HZ = 2, - V4L2_CID_POWER_LINE_FREQUENCY_AUTO = 3, -}; -#define V4L2_CID_HUE_AUTO (V4L2_CID_BASE+25) -#define V4L2_CID_WHITE_BALANCE_TEMPERATURE (V4L2_CID_BASE+26) -#define V4L2_CID_SHARPNESS (V4L2_CID_BASE+27) -#define V4L2_CID_BACKLIGHT_COMPENSATION (V4L2_CID_BASE+28) -#define V4L2_CID_CHROMA_AGC (V4L2_CID_BASE+29) -#define V4L2_CID_COLOR_KILLER (V4L2_CID_BASE+30) -#define V4L2_CID_COLORFX (V4L2_CID_BASE+31) -enum v4l2_colorfx { - V4L2_COLORFX_NONE = 0, - V4L2_COLORFX_BW = 1, - V4L2_COLORFX_SEPIA = 2, - V4L2_COLORFX_NEGATIVE = 3, - V4L2_COLORFX_EMBOSS = 4, - V4L2_COLORFX_SKETCH = 5, - V4L2_COLORFX_SKY_BLUE = 6, - V4L2_COLORFX_GRASS_GREEN = 7, - V4L2_COLORFX_SKIN_WHITEN = 8, - V4L2_COLORFX_VIVID = 9, - V4L2_COLORFX_AQUA = 10, - V4L2_COLORFX_ART_FREEZE = 11, - V4L2_COLORFX_SILHOUETTE = 12, - V4L2_COLORFX_SOLARIZATION = 13, - V4L2_COLORFX_ANTIQUE = 14, - V4L2_COLORFX_SET_CBCR = 15, -}; -#define V4L2_CID_AUTOBRIGHTNESS (V4L2_CID_BASE+32) -#define V4L2_CID_BAND_STOP_FILTER (V4L2_CID_BASE+33) - -#define V4L2_CID_ROTATE (V4L2_CID_BASE+34) -#define V4L2_CID_BG_COLOR (V4L2_CID_BASE+35) - -#define V4L2_CID_CHROMA_GAIN (V4L2_CID_BASE+36) - -#define V4L2_CID_ILLUMINATORS_1 (V4L2_CID_BASE+37) -#define V4L2_CID_ILLUMINATORS_2 (V4L2_CID_BASE+38) - -#define V4L2_CID_MIN_BUFFERS_FOR_CAPTURE (V4L2_CID_BASE+39) -#define V4L2_CID_MIN_BUFFERS_FOR_OUTPUT (V4L2_CID_BASE+40) - -#define V4L2_CID_ALPHA_COMPONENT (V4L2_CID_BASE+41) -#define V4L2_CID_COLORFX_CBCR (V4L2_CID_BASE+42) - -/* last CID + 1 */ -#define V4L2_CID_LASTP1 (V4L2_CID_BASE+43) - -/* USER-class private control IDs */ - -/* The base for the meye driver controls. See linux/meye.h for the list - * of controls. We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_MEYE_BASE (V4L2_CID_USER_BASE + 0x1000) - -/* The base for the bttv driver controls. - * We reserve 32 controls for this driver. */ -#define V4L2_CID_USER_BTTV_BASE (V4L2_CID_USER_BASE + 0x1010) - - -/* The base for the s2255 driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_S2255_BASE (V4L2_CID_USER_BASE + 0x1030) - -/* - * The base for the si476x driver controls. See include/media/drv-intf/si476x.h - * for the list of controls. Total of 16 controls is reserved for this driver - */ -#define V4L2_CID_USER_SI476X_BASE (V4L2_CID_USER_BASE + 0x1040) - -/* The base for the TI VPE driver controls. Total of 16 controls is reserved for - * this driver */ -#define V4L2_CID_USER_TI_VPE_BASE (V4L2_CID_USER_BASE + 0x1050) - -/* The base for the saa7134 driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_SAA7134_BASE (V4L2_CID_USER_BASE + 0x1060) - -/* The base for the adv7180 driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_ADV7180_BASE (V4L2_CID_USER_BASE + 0x1070) - -/* The base for the tc358743 driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_TC358743_BASE (V4L2_CID_USER_BASE + 0x1080) - -/* MPEG-class control IDs */ -/* The MPEG controls are applicable to all codec controls - * and the 'MPEG' part of the define is historical */ - -#define V4L2_CID_MPEG_BASE (V4L2_CTRL_CLASS_MPEG | 0x900) -#define V4L2_CID_MPEG_CLASS (V4L2_CTRL_CLASS_MPEG | 1) - -/* MPEG streams, specific to multiplexed streams */ -#define V4L2_CID_MPEG_STREAM_TYPE (V4L2_CID_MPEG_BASE+0) -enum v4l2_mpeg_stream_type { - V4L2_MPEG_STREAM_TYPE_MPEG2_PS = 0, /* MPEG-2 program stream */ - V4L2_MPEG_STREAM_TYPE_MPEG2_TS = 1, /* MPEG-2 transport stream */ - V4L2_MPEG_STREAM_TYPE_MPEG1_SS = 2, /* MPEG-1 system stream */ - V4L2_MPEG_STREAM_TYPE_MPEG2_DVD = 3, /* MPEG-2 DVD-compatible stream */ - V4L2_MPEG_STREAM_TYPE_MPEG1_VCD = 4, /* MPEG-1 VCD-compatible stream */ - V4L2_MPEG_STREAM_TYPE_MPEG2_SVCD = 5, /* MPEG-2 SVCD-compatible stream */ -}; -#define V4L2_CID_MPEG_STREAM_PID_PMT (V4L2_CID_MPEG_BASE+1) -#define V4L2_CID_MPEG_STREAM_PID_AUDIO (V4L2_CID_MPEG_BASE+2) -#define V4L2_CID_MPEG_STREAM_PID_VIDEO (V4L2_CID_MPEG_BASE+3) -#define V4L2_CID_MPEG_STREAM_PID_PCR (V4L2_CID_MPEG_BASE+4) -#define V4L2_CID_MPEG_STREAM_PES_ID_AUDIO (V4L2_CID_MPEG_BASE+5) -#define V4L2_CID_MPEG_STREAM_PES_ID_VIDEO (V4L2_CID_MPEG_BASE+6) -#define V4L2_CID_MPEG_STREAM_VBI_FMT (V4L2_CID_MPEG_BASE+7) -enum v4l2_mpeg_stream_vbi_fmt { - V4L2_MPEG_STREAM_VBI_FMT_NONE = 0, /* No VBI in the MPEG stream */ - V4L2_MPEG_STREAM_VBI_FMT_IVTV = 1, /* VBI in private packets, IVTV format */ -}; - -/* MPEG audio controls specific to multiplexed streams */ -#define V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ (V4L2_CID_MPEG_BASE+100) -enum v4l2_mpeg_audio_sampling_freq { - V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100 = 0, - V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000 = 1, - V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000 = 2, -}; -#define V4L2_CID_MPEG_AUDIO_ENCODING (V4L2_CID_MPEG_BASE+101) -enum v4l2_mpeg_audio_encoding { - V4L2_MPEG_AUDIO_ENCODING_LAYER_1 = 0, - V4L2_MPEG_AUDIO_ENCODING_LAYER_2 = 1, - V4L2_MPEG_AUDIO_ENCODING_LAYER_3 = 2, - V4L2_MPEG_AUDIO_ENCODING_AAC = 3, - V4L2_MPEG_AUDIO_ENCODING_AC3 = 4, -}; -#define V4L2_CID_MPEG_AUDIO_L1_BITRATE (V4L2_CID_MPEG_BASE+102) -enum v4l2_mpeg_audio_l1_bitrate { - V4L2_MPEG_AUDIO_L1_BITRATE_32K = 0, - V4L2_MPEG_AUDIO_L1_BITRATE_64K = 1, - V4L2_MPEG_AUDIO_L1_BITRATE_96K = 2, - V4L2_MPEG_AUDIO_L1_BITRATE_128K = 3, - V4L2_MPEG_AUDIO_L1_BITRATE_160K = 4, - V4L2_MPEG_AUDIO_L1_BITRATE_192K = 5, - V4L2_MPEG_AUDIO_L1_BITRATE_224K = 6, - V4L2_MPEG_AUDIO_L1_BITRATE_256K = 7, - V4L2_MPEG_AUDIO_L1_BITRATE_288K = 8, - V4L2_MPEG_AUDIO_L1_BITRATE_320K = 9, - V4L2_MPEG_AUDIO_L1_BITRATE_352K = 10, - V4L2_MPEG_AUDIO_L1_BITRATE_384K = 11, - V4L2_MPEG_AUDIO_L1_BITRATE_416K = 12, - V4L2_MPEG_AUDIO_L1_BITRATE_448K = 13, -}; -#define V4L2_CID_MPEG_AUDIO_L2_BITRATE (V4L2_CID_MPEG_BASE+103) -enum v4l2_mpeg_audio_l2_bitrate { - V4L2_MPEG_AUDIO_L2_BITRATE_32K = 0, - V4L2_MPEG_AUDIO_L2_BITRATE_48K = 1, - V4L2_MPEG_AUDIO_L2_BITRATE_56K = 2, - V4L2_MPEG_AUDIO_L2_BITRATE_64K = 3, - V4L2_MPEG_AUDIO_L2_BITRATE_80K = 4, - V4L2_MPEG_AUDIO_L2_BITRATE_96K = 5, - V4L2_MPEG_AUDIO_L2_BITRATE_112K = 6, - V4L2_MPEG_AUDIO_L2_BITRATE_128K = 7, - V4L2_MPEG_AUDIO_L2_BITRATE_160K = 8, - V4L2_MPEG_AUDIO_L2_BITRATE_192K = 9, - V4L2_MPEG_AUDIO_L2_BITRATE_224K = 10, - V4L2_MPEG_AUDIO_L2_BITRATE_256K = 11, - V4L2_MPEG_AUDIO_L2_BITRATE_320K = 12, - V4L2_MPEG_AUDIO_L2_BITRATE_384K = 13, -}; -#define V4L2_CID_MPEG_AUDIO_L3_BITRATE (V4L2_CID_MPEG_BASE+104) -enum v4l2_mpeg_audio_l3_bitrate { - V4L2_MPEG_AUDIO_L3_BITRATE_32K = 0, - V4L2_MPEG_AUDIO_L3_BITRATE_40K = 1, - V4L2_MPEG_AUDIO_L3_BITRATE_48K = 2, - V4L2_MPEG_AUDIO_L3_BITRATE_56K = 3, - V4L2_MPEG_AUDIO_L3_BITRATE_64K = 4, - V4L2_MPEG_AUDIO_L3_BITRATE_80K = 5, - V4L2_MPEG_AUDIO_L3_BITRATE_96K = 6, - V4L2_MPEG_AUDIO_L3_BITRATE_112K = 7, - V4L2_MPEG_AUDIO_L3_BITRATE_128K = 8, - V4L2_MPEG_AUDIO_L3_BITRATE_160K = 9, - V4L2_MPEG_AUDIO_L3_BITRATE_192K = 10, - V4L2_MPEG_AUDIO_L3_BITRATE_224K = 11, - V4L2_MPEG_AUDIO_L3_BITRATE_256K = 12, - V4L2_MPEG_AUDIO_L3_BITRATE_320K = 13, -}; -#define V4L2_CID_MPEG_AUDIO_MODE (V4L2_CID_MPEG_BASE+105) -enum v4l2_mpeg_audio_mode { - V4L2_MPEG_AUDIO_MODE_STEREO = 0, - V4L2_MPEG_AUDIO_MODE_JOINT_STEREO = 1, - V4L2_MPEG_AUDIO_MODE_DUAL = 2, - V4L2_MPEG_AUDIO_MODE_MONO = 3, -}; -#define V4L2_CID_MPEG_AUDIO_MODE_EXTENSION (V4L2_CID_MPEG_BASE+106) -enum v4l2_mpeg_audio_mode_extension { - V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_4 = 0, - V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_8 = 1, - V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_12 = 2, - V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_16 = 3, -}; -#define V4L2_CID_MPEG_AUDIO_EMPHASIS (V4L2_CID_MPEG_BASE+107) -enum v4l2_mpeg_audio_emphasis { - V4L2_MPEG_AUDIO_EMPHASIS_NONE = 0, - V4L2_MPEG_AUDIO_EMPHASIS_50_DIV_15_uS = 1, - V4L2_MPEG_AUDIO_EMPHASIS_CCITT_J17 = 2, -}; -#define V4L2_CID_MPEG_AUDIO_CRC (V4L2_CID_MPEG_BASE+108) -enum v4l2_mpeg_audio_crc { - V4L2_MPEG_AUDIO_CRC_NONE = 0, - V4L2_MPEG_AUDIO_CRC_CRC16 = 1, -}; -#define V4L2_CID_MPEG_AUDIO_MUTE (V4L2_CID_MPEG_BASE+109) -#define V4L2_CID_MPEG_AUDIO_AAC_BITRATE (V4L2_CID_MPEG_BASE+110) -#define V4L2_CID_MPEG_AUDIO_AC3_BITRATE (V4L2_CID_MPEG_BASE+111) -enum v4l2_mpeg_audio_ac3_bitrate { - V4L2_MPEG_AUDIO_AC3_BITRATE_32K = 0, - V4L2_MPEG_AUDIO_AC3_BITRATE_40K = 1, - V4L2_MPEG_AUDIO_AC3_BITRATE_48K = 2, - V4L2_MPEG_AUDIO_AC3_BITRATE_56K = 3, - V4L2_MPEG_AUDIO_AC3_BITRATE_64K = 4, - V4L2_MPEG_AUDIO_AC3_BITRATE_80K = 5, - V4L2_MPEG_AUDIO_AC3_BITRATE_96K = 6, - V4L2_MPEG_AUDIO_AC3_BITRATE_112K = 7, - V4L2_MPEG_AUDIO_AC3_BITRATE_128K = 8, - V4L2_MPEG_AUDIO_AC3_BITRATE_160K = 9, - V4L2_MPEG_AUDIO_AC3_BITRATE_192K = 10, - V4L2_MPEG_AUDIO_AC3_BITRATE_224K = 11, - V4L2_MPEG_AUDIO_AC3_BITRATE_256K = 12, - V4L2_MPEG_AUDIO_AC3_BITRATE_320K = 13, - V4L2_MPEG_AUDIO_AC3_BITRATE_384K = 14, - V4L2_MPEG_AUDIO_AC3_BITRATE_448K = 15, - V4L2_MPEG_AUDIO_AC3_BITRATE_512K = 16, - V4L2_MPEG_AUDIO_AC3_BITRATE_576K = 17, - V4L2_MPEG_AUDIO_AC3_BITRATE_640K = 18, -}; -#define V4L2_CID_MPEG_AUDIO_DEC_PLAYBACK (V4L2_CID_MPEG_BASE+112) -enum v4l2_mpeg_audio_dec_playback { - V4L2_MPEG_AUDIO_DEC_PLAYBACK_AUTO = 0, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_STEREO = 1, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_LEFT = 2, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_RIGHT = 3, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_MONO = 4, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_SWAPPED_STEREO = 5, -}; -#define V4L2_CID_MPEG_AUDIO_DEC_MULTILINGUAL_PLAYBACK (V4L2_CID_MPEG_BASE+113) - -/* MPEG video controls specific to multiplexed streams */ -#define V4L2_CID_MPEG_VIDEO_ENCODING (V4L2_CID_MPEG_BASE+200) -enum v4l2_mpeg_video_encoding { - V4L2_MPEG_VIDEO_ENCODING_MPEG_1 = 0, - V4L2_MPEG_VIDEO_ENCODING_MPEG_2 = 1, - V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC = 2, -}; -#define V4L2_CID_MPEG_VIDEO_ASPECT (V4L2_CID_MPEG_BASE+201) -enum v4l2_mpeg_video_aspect { - V4L2_MPEG_VIDEO_ASPECT_1x1 = 0, - V4L2_MPEG_VIDEO_ASPECT_4x3 = 1, - V4L2_MPEG_VIDEO_ASPECT_16x9 = 2, - V4L2_MPEG_VIDEO_ASPECT_221x100 = 3, -}; -#define V4L2_CID_MPEG_VIDEO_B_FRAMES (V4L2_CID_MPEG_BASE+202) -#define V4L2_CID_MPEG_VIDEO_GOP_SIZE (V4L2_CID_MPEG_BASE+203) -#define V4L2_CID_MPEG_VIDEO_GOP_CLOSURE (V4L2_CID_MPEG_BASE+204) -#define V4L2_CID_MPEG_VIDEO_PULLDOWN (V4L2_CID_MPEG_BASE+205) -#define V4L2_CID_MPEG_VIDEO_BITRATE_MODE (V4L2_CID_MPEG_BASE+206) -enum v4l2_mpeg_video_bitrate_mode { - V4L2_MPEG_VIDEO_BITRATE_MODE_VBR = 0, - V4L2_MPEG_VIDEO_BITRATE_MODE_CBR = 1, -}; -#define V4L2_CID_MPEG_VIDEO_BITRATE (V4L2_CID_MPEG_BASE+207) -#define V4L2_CID_MPEG_VIDEO_BITRATE_PEAK (V4L2_CID_MPEG_BASE+208) -#define V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION (V4L2_CID_MPEG_BASE+209) -#define V4L2_CID_MPEG_VIDEO_MUTE (V4L2_CID_MPEG_BASE+210) -#define V4L2_CID_MPEG_VIDEO_MUTE_YUV (V4L2_CID_MPEG_BASE+211) -#define V4L2_CID_MPEG_VIDEO_DECODER_SLICE_INTERFACE (V4L2_CID_MPEG_BASE+212) -#define V4L2_CID_MPEG_VIDEO_DECODER_MPEG4_DEBLOCK_FILTER (V4L2_CID_MPEG_BASE+213) -#define V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB (V4L2_CID_MPEG_BASE+214) -#define V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE (V4L2_CID_MPEG_BASE+215) -#define V4L2_CID_MPEG_VIDEO_HEADER_MODE (V4L2_CID_MPEG_BASE+216) -enum v4l2_mpeg_video_header_mode { - V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE = 0, - V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME = 1, - V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_I_FRAME = 2, -}; -#define V4L2_CID_MPEG_VIDEO_MAX_REF_PIC (V4L2_CID_MPEG_BASE+217) -#define V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE (V4L2_CID_MPEG_BASE+218) -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES (V4L2_CID_MPEG_BASE+219) -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB (V4L2_CID_MPEG_BASE+220) -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE (V4L2_CID_MPEG_BASE+221) -enum v4l2_mpeg_video_multi_slice_mode { - V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE = 0, - V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_MB = 1, - V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES = 2, - V4L2_MPEG_VIDEO_MULTI_SLICE_GOB = 3, -}; -#define V4L2_CID_MPEG_VIDEO_VBV_SIZE (V4L2_CID_MPEG_BASE+222) -#define V4L2_CID_MPEG_VIDEO_DEC_PTS (V4L2_CID_MPEG_BASE+223) -#define V4L2_CID_MPEG_VIDEO_DEC_FRAME (V4L2_CID_MPEG_BASE+224) -#define V4L2_CID_MPEG_VIDEO_VBV_DELAY (V4L2_CID_MPEG_BASE+225) -#define V4L2_CID_MPEG_VIDEO_REPEAT_SEQ_HEADER (V4L2_CID_MPEG_BASE+226) -#define V4L2_CID_MPEG_VIDEO_MV_H_SEARCH_RANGE (V4L2_CID_MPEG_BASE+227) -#define V4L2_CID_MPEG_VIDEO_MV_V_SEARCH_RANGE (V4L2_CID_MPEG_BASE+228) -#define V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME (V4L2_CID_MPEG_BASE+229) - -#define V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP (V4L2_CID_MPEG_BASE+300) -#define V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP (V4L2_CID_MPEG_BASE+301) -#define V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP (V4L2_CID_MPEG_BASE+302) -#define V4L2_CID_MPEG_VIDEO_H263_MIN_QP (V4L2_CID_MPEG_BASE+303) -#define V4L2_CID_MPEG_VIDEO_H263_MAX_QP (V4L2_CID_MPEG_BASE+304) -#define V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP (V4L2_CID_MPEG_BASE+350) -#define V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP (V4L2_CID_MPEG_BASE+351) -#define V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP (V4L2_CID_MPEG_BASE+352) -#define V4L2_CID_MPEG_VIDEO_H264_MIN_QP (V4L2_CID_MPEG_BASE+353) -#define V4L2_CID_MPEG_VIDEO_H264_MAX_QP (V4L2_CID_MPEG_BASE+354) -#define V4L2_CID_MPEG_VIDEO_H264_8X8_TRANSFORM (V4L2_CID_MPEG_BASE+355) -#define V4L2_CID_MPEG_VIDEO_H264_CPB_SIZE (V4L2_CID_MPEG_BASE+356) -#define V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE (V4L2_CID_MPEG_BASE+357) -enum v4l2_mpeg_video_h264_entropy_mode { - V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CAVLC = 0, - V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC = 1, -}; -#define V4L2_CID_MPEG_VIDEO_H264_I_PERIOD (V4L2_CID_MPEG_BASE+358) -#define V4L2_CID_MPEG_VIDEO_H264_LEVEL (V4L2_CID_MPEG_BASE+359) -enum v4l2_mpeg_video_h264_level { - V4L2_MPEG_VIDEO_H264_LEVEL_1_0 = 0, - V4L2_MPEG_VIDEO_H264_LEVEL_1B = 1, - V4L2_MPEG_VIDEO_H264_LEVEL_1_1 = 2, - V4L2_MPEG_VIDEO_H264_LEVEL_1_2 = 3, - V4L2_MPEG_VIDEO_H264_LEVEL_1_3 = 4, - V4L2_MPEG_VIDEO_H264_LEVEL_2_0 = 5, - V4L2_MPEG_VIDEO_H264_LEVEL_2_1 = 6, - V4L2_MPEG_VIDEO_H264_LEVEL_2_2 = 7, - V4L2_MPEG_VIDEO_H264_LEVEL_3_0 = 8, - V4L2_MPEG_VIDEO_H264_LEVEL_3_1 = 9, - V4L2_MPEG_VIDEO_H264_LEVEL_3_2 = 10, - V4L2_MPEG_VIDEO_H264_LEVEL_4_0 = 11, - V4L2_MPEG_VIDEO_H264_LEVEL_4_1 = 12, - V4L2_MPEG_VIDEO_H264_LEVEL_4_2 = 13, - V4L2_MPEG_VIDEO_H264_LEVEL_5_0 = 14, - V4L2_MPEG_VIDEO_H264_LEVEL_5_1 = 15, - V4L2_MPEG_VIDEO_H264_LEVEL_5_2 = 16, -#define V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN \ - V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN - V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN = 17, -}; -#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA (V4L2_CID_MPEG_BASE+360) -#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA (V4L2_CID_MPEG_BASE+361) -#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE (V4L2_CID_MPEG_BASE+362) -enum v4l2_mpeg_video_h264_loop_filter_mode { - V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED = 0, - V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED = 1, - V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY = 2, -}; -#define V4L2_CID_MPEG_VIDEO_H264_PROFILE (V4L2_CID_MPEG_BASE+363) -enum v4l2_mpeg_video_h264_profile { - V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE = 0, - V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE = 1, - V4L2_MPEG_VIDEO_H264_PROFILE_MAIN = 2, - V4L2_MPEG_VIDEO_H264_PROFILE_EXTENDED = 3, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH = 4, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10 = 5, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422 = 6, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_PREDICTIVE = 7, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10_INTRA = 8, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422_INTRA = 9, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_INTRA = 10, - V4L2_MPEG_VIDEO_H264_PROFILE_CAVLC_444_INTRA = 11, - V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_BASELINE = 12, - V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH = 13, - V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH_INTRA = 14, - V4L2_MPEG_VIDEO_H264_PROFILE_STEREO_HIGH = 15, - V4L2_MPEG_VIDEO_H264_PROFILE_MULTIVIEW_HIGH = 16, - V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_HIGH = 17, -}; -#define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_HEIGHT (V4L2_CID_MPEG_BASE+364) -#define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_WIDTH (V4L2_CID_MPEG_BASE+365) -#define V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_ENABLE (V4L2_CID_MPEG_BASE+366) -#define V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_IDC (V4L2_CID_MPEG_BASE+367) -enum v4l2_mpeg_video_h264_vui_sar_idc { - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_UNSPECIFIED = 0, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_1x1 = 1, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_12x11 = 2, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_10x11 = 3, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_16x11 = 4, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_40x33 = 5, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_24x11 = 6, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_20x11 = 7, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_32x11 = 8, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_80x33 = 9, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_18x11 = 10, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_15x11 = 11, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_64x33 = 12, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_160x99 = 13, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_4x3 = 14, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_3x2 = 15, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_2x1 = 16, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_EXTENDED = 17, -}; -#define V4L2_CID_MPEG_VIDEO_H264_SEI_FRAME_PACKING (V4L2_CID_MPEG_BASE+368) -#define V4L2_CID_MPEG_VIDEO_H264_SEI_FP_CURRENT_FRAME_0 (V4L2_CID_MPEG_BASE+369) -#define V4L2_CID_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE (V4L2_CID_MPEG_BASE+370) -enum v4l2_mpeg_video_h264_sei_fp_arrangement_type { - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_CHECKERBOARD = 0, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_COLUMN = 1, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_ROW = 2, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_SIDE_BY_SIDE = 3, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TOP_BOTTOM = 4, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TEMPORAL = 5, -}; -#define V4L2_CID_MPEG_VIDEO_H264_FMO (V4L2_CID_MPEG_BASE+371) -#define V4L2_CID_MPEG_VIDEO_H264_FMO_MAP_TYPE (V4L2_CID_MPEG_BASE+372) -enum v4l2_mpeg_video_h264_fmo_map_type { - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_INTERLEAVED_SLICES = 0, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_SCATTERED_SLICES = 1, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_FOREGROUND_WITH_LEFT_OVER = 2, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_BOX_OUT = 3, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_RASTER_SCAN = 4, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_WIPE_SCAN = 5, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_EXPLICIT = 6, -}; -#define V4L2_CID_MPEG_VIDEO_H264_FMO_SLICE_GROUP (V4L2_CID_MPEG_BASE+373) -#define V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_DIRECTION (V4L2_CID_MPEG_BASE+374) -enum v4l2_mpeg_video_h264_fmo_change_dir { - V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_RIGHT = 0, - V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_LEFT = 1, -}; -#define V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_RATE (V4L2_CID_MPEG_BASE+375) -#define V4L2_CID_MPEG_VIDEO_H264_FMO_RUN_LENGTH (V4L2_CID_MPEG_BASE+376) -#define V4L2_CID_MPEG_VIDEO_H264_ASO (V4L2_CID_MPEG_BASE+377) -#define V4L2_CID_MPEG_VIDEO_H264_ASO_SLICE_ORDER (V4L2_CID_MPEG_BASE+378) -#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING (V4L2_CID_MPEG_BASE+379) -#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_TYPE (V4L2_CID_MPEG_BASE+380) -enum v4l2_mpeg_video_h264_hierarchical_coding_type { - V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_B = 0, - V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_P = 1, -}; -#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER (V4L2_CID_MPEG_BASE+381) -#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER_QP (V4L2_CID_MPEG_BASE+382) -#define V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP (V4L2_CID_MPEG_BASE+400) -#define V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP (V4L2_CID_MPEG_BASE+401) -#define V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP (V4L2_CID_MPEG_BASE+402) -#define V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP (V4L2_CID_MPEG_BASE+403) -#define V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP (V4L2_CID_MPEG_BASE+404) -#define V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL (V4L2_CID_MPEG_BASE+405) -enum v4l2_mpeg_video_mpeg4_level { - V4L2_MPEG_VIDEO_MPEG4_LEVEL_0 = 0, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_0B = 1, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_1 = 2, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_2 = 3, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_3 = 4, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_3B = 5, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_4 = 6, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_5 = 7, -}; -#define V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE (V4L2_CID_MPEG_BASE+406) -enum v4l2_mpeg_video_mpeg4_profile { - V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE = 0, - V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_SIMPLE = 1, - V4L2_MPEG_VIDEO_MPEG4_PROFILE_CORE = 2, - V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE_SCALABLE = 3, - V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY = 4, -}; -#define V4L2_CID_MPEG_VIDEO_MPEG4_QPEL (V4L2_CID_MPEG_BASE+407) - -/* Control IDs for VP8 streams - * Although VP8 is not part of MPEG we add these controls to the MPEG class - * as that class is already handling other video compression standards - */ -#define V4L2_CID_MPEG_VIDEO_VPX_NUM_PARTITIONS (V4L2_CID_MPEG_BASE+500) -enum v4l2_vp8_num_partitions { - V4L2_CID_MPEG_VIDEO_VPX_1_PARTITION = 0, - V4L2_CID_MPEG_VIDEO_VPX_2_PARTITIONS = 1, - V4L2_CID_MPEG_VIDEO_VPX_4_PARTITIONS = 2, - V4L2_CID_MPEG_VIDEO_VPX_8_PARTITIONS = 3, -}; -#define V4L2_CID_MPEG_VIDEO_VPX_IMD_DISABLE_4X4 (V4L2_CID_MPEG_BASE+501) -#define V4L2_CID_MPEG_VIDEO_VPX_NUM_REF_FRAMES (V4L2_CID_MPEG_BASE+502) -enum v4l2_vp8_num_ref_frames { - V4L2_CID_MPEG_VIDEO_VPX_1_REF_FRAME = 0, - V4L2_CID_MPEG_VIDEO_VPX_2_REF_FRAME = 1, - V4L2_CID_MPEG_VIDEO_VPX_3_REF_FRAME = 2, -}; -#define V4L2_CID_MPEG_VIDEO_VPX_FILTER_LEVEL (V4L2_CID_MPEG_BASE+503) -#define V4L2_CID_MPEG_VIDEO_VPX_FILTER_SHARPNESS (V4L2_CID_MPEG_BASE+504) -#define V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_REF_PERIOD (V4L2_CID_MPEG_BASE+505) -#define V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_SEL (V4L2_CID_MPEG_BASE+506) -enum v4l2_vp8_golden_frame_sel { - V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_PREV = 0, - V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_REF_PERIOD = 1, -}; -#define V4L2_CID_MPEG_VIDEO_VPX_MIN_QP (V4L2_CID_MPEG_BASE+507) -#define V4L2_CID_MPEG_VIDEO_VPX_MAX_QP (V4L2_CID_MPEG_BASE+508) -#define V4L2_CID_MPEG_VIDEO_VPX_I_FRAME_QP (V4L2_CID_MPEG_BASE+509) -#define V4L2_CID_MPEG_VIDEO_VPX_P_FRAME_QP (V4L2_CID_MPEG_BASE+510) -#define V4L2_CID_MPEG_VIDEO_VPX_PROFILE (V4L2_CID_MPEG_BASE+511) - -/* MPEG-class control IDs specific to the CX2341x driver as defined by V4L2 */ -#define V4L2_CID_MPEG_CX2341X_BASE (V4L2_CTRL_CLASS_MPEG | 0x1000) -#define V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE (V4L2_CID_MPEG_CX2341X_BASE+0) -enum v4l2_mpeg_cx2341x_video_spatial_filter_mode { - V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_MANUAL = 0, - V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_AUTO = 1, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER (V4L2_CID_MPEG_CX2341X_BASE+1) -#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+2) -enum v4l2_mpeg_cx2341x_video_luma_spatial_filter_type { - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_OFF = 0, - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_VERT = 2, - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_HV_SEPARABLE = 3, - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_SYM_NON_SEPARABLE = 4, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+3) -enum v4l2_mpeg_cx2341x_video_chroma_spatial_filter_type { - V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_OFF = 0, - V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE (V4L2_CID_MPEG_CX2341X_BASE+4) -enum v4l2_mpeg_cx2341x_video_temporal_filter_mode { - V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_MANUAL = 0, - V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_AUTO = 1, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER (V4L2_CID_MPEG_CX2341X_BASE+5) -#define V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+6) -enum v4l2_mpeg_cx2341x_video_median_filter_type { - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_OFF = 0, - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR = 1, - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_VERT = 2, - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR_VERT = 3, - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_DIAG = 4, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM (V4L2_CID_MPEG_CX2341X_BASE+7) -#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP (V4L2_CID_MPEG_CX2341X_BASE+8) -#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM (V4L2_CID_MPEG_CX2341X_BASE+9) -#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP (V4L2_CID_MPEG_CX2341X_BASE+10) -#define V4L2_CID_MPEG_CX2341X_STREAM_INSERT_NAV_PACKETS (V4L2_CID_MPEG_CX2341X_BASE+11) - -/* MPEG-class control IDs specific to the Samsung MFC 5.1 driver as defined by V4L2 */ -#define V4L2_CID_MPEG_MFC51_BASE (V4L2_CTRL_CLASS_MPEG | 0x1100) - -#define V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY (V4L2_CID_MPEG_MFC51_BASE+0) -#define V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY_ENABLE (V4L2_CID_MPEG_MFC51_BASE+1) -#define V4L2_CID_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE (V4L2_CID_MPEG_MFC51_BASE+2) -enum v4l2_mpeg_mfc51_video_frame_skip_mode { - V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_DISABLED = 0, - V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_LEVEL_LIMIT = 1, - V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_BUF_LIMIT = 2, -}; -#define V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE (V4L2_CID_MPEG_MFC51_BASE+3) -enum v4l2_mpeg_mfc51_video_force_frame_type { - V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_DISABLED = 0, - V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME = 1, - V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_NOT_CODED = 2, -}; -#define V4L2_CID_MPEG_MFC51_VIDEO_PADDING (V4L2_CID_MPEG_MFC51_BASE+4) -#define V4L2_CID_MPEG_MFC51_VIDEO_PADDING_YUV (V4L2_CID_MPEG_MFC51_BASE+5) -#define V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT (V4L2_CID_MPEG_MFC51_BASE+6) -#define V4L2_CID_MPEG_MFC51_VIDEO_RC_REACTION_COEFF (V4L2_CID_MPEG_MFC51_BASE+7) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_ACTIVITY (V4L2_CID_MPEG_MFC51_BASE+50) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_DARK (V4L2_CID_MPEG_MFC51_BASE+51) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_SMOOTH (V4L2_CID_MPEG_MFC51_BASE+52) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_STATIC (V4L2_CID_MPEG_MFC51_BASE+53) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_NUM_REF_PIC_FOR_P (V4L2_CID_MPEG_MFC51_BASE+54) - -/* MPEG-class control IDs specific to the msm_vidc driver */ -#define V4L2_CID_MPEG_MSM_VIDC_BASE (V4L2_CTRL_CLASS_MPEG | 0x2000) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PICTYPE_DEC_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+0) -enum v4l2_mpeg_vidc_video_pictype_dec_mode { - V4L2_MPEG_VIDC_VIDEO_PICTYPE_DECODE_OFF = 0, - V4L2_MPEG_VIDC_VIDEO_PICTYPE_DECODE_ON = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_KEEP_ASPECT_RATIO \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+1) - -#define V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT (V4L2_CID_MPEG_MSM_VIDC_BASE+2) -enum v4l2_mpeg_vidc_video_stream_format { - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES = 0, - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_ONE_NAL_PER_BUFFER = 1, - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_ONE_BYTE_LENGTH = 2, - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH = 3, - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH = 4, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER (V4L2_CID_MPEG_MSM_VIDC_BASE+3) -enum v4l2_mpeg_vidc_video_output_order { - V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DISPLAY = 0, - V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_RATE (V4L2_CID_MPEG_MSM_VIDC_BASE+4) -#define V4L2_CID_MPEG_VIDC_VIDEO_IDR_PERIOD (V4L2_CID_MPEG_MSM_VIDC_BASE+5) -#define V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES (V4L2_CID_MPEG_MSM_VIDC_BASE+6) -#define V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES (V4L2_CID_MPEG_MSM_VIDC_BASE+7) -#define V4L2_CID_MPEG_VIDC_VIDEO_REQUEST_IFRAME (V4L2_CID_MPEG_MSM_VIDC_BASE+8) - -#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL (V4L2_CID_MPEG_MSM_VIDC_BASE+9) -enum v4l2_mpeg_vidc_video_rate_control { - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_OFF = 0, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_VFR = 1, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_CFR = 2, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CBR_VFR = 3, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CBR_CFR = 4, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR = 5, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR = 6, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CQ = 7, -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR \ - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR -#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR \ - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR - -#define V4L2_CID_MPEG_VIDC_VIDEO_ROTATION (V4L2_CID_MPEG_MSM_VIDC_BASE+10) -enum v4l2_mpeg_vidc_video_rotation { - V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_NONE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_90 = 1, - V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_180 = 2, - V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_270 = 3, -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+11) -enum v4l2_mpeg_vidc_h264_cabac_model { - V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_0 = 0, - V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_1 = 1, - V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_2 = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+12) -enum v4l2_mpeg_vidc_video_intra_refresh_mode { - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_NONE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_CYCLIC = 1, - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_RANDOM = 2, - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_ADAPTIVE = 3, - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_CYCLIC_ADAPTIVE = 4, -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_IR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE+13) - -#define V4L2_CID_MPEG_VIDC_VIDEO_AU_DELIMITER \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 14) -enum v4l2_mpeg_vidc_video_au_delimiter { - V4L2_MPEG_VIDC_VIDEO_AU_DELIMITER_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_AU_DELIMITER_ENABLED = 1 -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 15) -enum v4l2_mpeg_vidc_video_sync_frame_decode { - V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_DISABLE = 0, - V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_ENABLE = 1 -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_SECURE (V4L2_CID_MPEG_MSM_VIDC_BASE+16) -#define V4L2_CID_MPEG_VIDC_VIDEO_EXTRADATA \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 17) -enum v4l2_mpeg_vidc_extradata { - V4L2_MPEG_VIDC_EXTRADATA_NONE = 0, - V4L2_MPEG_VIDC_EXTRADATA_MB_QUANTIZATION = 1, - V4L2_MPEG_VIDC_EXTRADATA_INTERLACE_VIDEO = 2, - V4L2_MPEG_VIDC_EXTRADATA_VC1_FRAMEDISP = 3, - V4L2_MPEG_VIDC_EXTRADATA_VC1_SEQDISP = 4, - V4L2_MPEG_VIDC_EXTRADATA_TIMESTAMP = 5, - V4L2_MPEG_VIDC_EXTRADATA_S3D_FRAME_PACKING = 6, - V4L2_MPEG_VIDC_EXTRADATA_FRAME_RATE = 7, - V4L2_MPEG_VIDC_EXTRADATA_PANSCAN_WINDOW = 8, - V4L2_MPEG_VIDC_EXTRADATA_RECOVERY_POINT_SEI = 9, - V4L2_MPEG_VIDC_EXTRADATA_MULTISLICE_INFO = 10, - V4L2_MPEG_VIDC_EXTRADATA_NUM_CONCEALED_MB = 11, - V4L2_MPEG_VIDC_EXTRADATA_METADATA_FILLER = 12, - V4L2_MPEG_VIDC_EXTRADATA_INPUT_CROP = 13, - V4L2_MPEG_VIDC_EXTRADATA_DIGITAL_ZOOM = 14, - V4L2_MPEG_VIDC_EXTRADATA_ASPECT_RATIO = 15, - V4L2_MPEG_VIDC_EXTRADATA_MPEG2_SEQDISP = 16, - V4L2_MPEG_VIDC_EXTRADATA_STREAM_USERDATA = 17, - V4L2_MPEG_VIDC_EXTRADATA_FRAME_QP = 18, - V4L2_MPEG_VIDC_EXTRADATA_FRAME_BITS_INFO = 19, - V4L2_MPEG_VIDC_EXTRADATA_LTR = 20, - V4L2_MPEG_VIDC_EXTRADATA_METADATA_MBI = 21, - V4L2_MPEG_VIDC_EXTRADATA_VQZIP_SEI = 22, - V4L2_MPEG_VIDC_EXTRADATA_YUV_STATS = 23, - V4L2_MPEG_VIDC_EXTRADATA_ROI_QP = 24, -#define V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP \ - V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP - V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP = 25, -#define V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI \ - V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI - V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI = 26, -#define V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI \ - V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI - V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI = 27, -#define V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO \ - V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO - V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO = 28, -#define V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY \ - V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY - V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY = 29, -#define V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE \ - V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE - V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE = 30, -#define V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO \ - V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO - V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO = 31, -#define V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP \ - V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP - V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP = 32, -}; - -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_DELIVERY_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 18) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VUI_TIMING_INFO \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 19) -enum v4l2_mpeg_vidc_video_vui_timing_info { - V4L2_MPEG_VIDC_VIDEO_VUI_TIMING_INFO_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_VUI_TIMING_INFO_ENABLED = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_PROFILE_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 20) -enum v4l2_mpeg_vidc_video_vp8_profile_level { - V4L2_MPEG_VIDC_VIDEO_VP8_UNUSED, - V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_0, - V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_1, - V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_2, - V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_3, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 21) -enum v4l2_mpeg_vidc_video_preserve_text_quality { - V4L2_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY_ENABLED = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 22) -enum v4l2_mpeg_vidc_video_decoder_multi_stream { - V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_PRIMARY = 0, - V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG2_LEVEL (V4L2_CID_MPEG_MSM_VIDC_BASE+23) -enum v4l2_mpeg_vidc_video_mpeg2_level { - V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_0 = 0, - V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_1 = 1, - V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_2 = 2, - V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_3 = 3, -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG2_PROFILE (V4L2_CID_MPEG_MSM_VIDC_BASE+24) -enum v4l2_mpeg_vidc_video_mpeg2_profile { - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SIMPLE = 0, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_MAIN = 1, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_422 = 2, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SNR_SCALABLE = 3, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SPATIAL_SCALABLE = 4, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_HIGH = 5, -}; - -enum v4l2_mpeg_vidc_video_mvc_layout { - V4L2_MPEG_VIDC_VIDEO_MVC_SEQUENTIAL = 0, - V4L2_MPEG_VIDC_VIDEO_MVC_TOP_BOTTOM = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 25) - -#define V4L2_CID_MPEG_VIDC_VIDEO_LTRMODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 26) - -enum v4l2_mpeg_vidc_video_ltrmode { - V4L2_MPEG_VIDC_VIDEO_LTR_MODE_DISABLE = 0, - V4L2_MPEG_VIDC_VIDEO_LTR_MODE_MANUAL = 1, - V4L2_MPEG_VIDC_VIDEO_LTR_MODE_PERIODIC = 2 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_LTRCOUNT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 27) - -#define V4L2_CID_MPEG_VIDC_VIDEO_USELTRFRAME \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 28) - -#define V4L2_CID_MPEG_VIDC_VIDEO_MARKLTRFRAME \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 29) - -#define V4L2_CID_MPEG_VIDC_VIDEO_HIER_P_NUM_LAYERS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 30) - -#define V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_OUTPUT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+31) -enum v4l2_mpeg_vidc_video_alloc_mode_type { - V4L2_MPEG_VIDC_VIDEO_STATIC = 0, - V4L2_MPEG_VIDC_VIDEO_RING = 1, - V4L2_MPEG_VIDC_VIDEO_DYNAMIC = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_X_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 32) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PFRAME_X_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 33) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BFRAME_X_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 34) - -#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_Y_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 35) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PFRAME_Y_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 36) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BFRAME_Y_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 37) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 38) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BUFFER_SIZE_LIMIT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 39) - -enum vl42_mpeg_vidc_video_vpx_error_resilience { - V4L2_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE_ENABLED = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_HEVC_PROFILE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 40) -enum v4l2_mpeg_video_hevc_profile { - V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN = 0, - V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN10 = 1, - V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN_STILL_PIC = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_HEVC_TIER_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 41) -enum v4l2_mpeg_video_hevc_level { - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_1 = 0, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_1 = 1, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_2 = 2, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_2 = 3, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_2_1 = 4, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_2_1 = 5, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_3 = 6, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_3 = 7, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_3_1 = 8, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_3_1 = 9, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_4 = 10, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_4 = 11, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_4_1 = 12, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_4_1 = 13, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5 = 14, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5 = 15, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5_1 = 16, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5_1 = 17, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5_2 = 18, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5_2 = 19, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6 = 20, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6 = 21, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6_1 = 22, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6_1 = 23, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6_2 = 24, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6_2 = 25, -#define V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN \ - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN = 26, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_HIER_B_NUM_LAYERS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 42) - -#define V4L2_CID_MPEG_VIDC_VIDEO_HYBRID_HIERP_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 43) - -#define V4L2_CID_MPEG_VIDC_VIDEO_DPB_COLOR_FORMAT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 44) - -enum v4l2_mpeg_vidc_video_dpb_color_format { - V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_NONE = 0, - V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_UBWC = 1, - V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_TP10_UBWC = 2 -}; - -#define V4L2_CID_VIDC_QBUF_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 45) -enum v4l2_vidc_qbuf_mode { - V4L2_VIDC_QBUF_STANDARD = 0, - V4L2_VIDC_QBUF_BATCHED = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MAX_HIERP_LAYERS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 46) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BASELAYER_ID \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 47) - -#define V4L2_CID_MPEG_VIDC_VENC_PARAM_SAR_WIDTH \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 48) - -#define V4L2_CID_MPEG_VIDC_VENC_PARAM_SAR_HEIGHT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 49) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 50) - -enum v4l2_mpeg_vidc_video_vqzip_sei_enable { - V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI_ENABLE = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VENC_PARAM_LAYER_BITRATE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 51) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 52) - -enum v4l2_mpeg_vidc_video_priority { - V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE = 0, - V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 53) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_TYPE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 54) - -enum v4l2_mpeg_vidc_video_venc_bitrate_type_enable { - V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_ENABLE = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 55) - -enum v4l2_cid_mpeg_vidc_video_vpe_csc_type_enable { - V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_ENABLE = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 56) - -enum v4l2_mpeg_vidc_video_lowlatency_mode { - V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_ENABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_BLUR_WIDTH \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 57) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BLUR_HEIGHT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 58) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 59) -enum v4l2_mpeg_vidc_video_h264_transform_8x8 { - V4L2_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8_DISABLE = 0, - V4L2_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8_ENABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_COLOR_SPACE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 60) - -#define V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 61) - -enum v4l2_cid_mpeg_vidc_video_full_range { - V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE_ENABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_TRANSFER_CHARS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 62) - -#define V4L2_CID_MPEG_VIDC_VIDEO_MATRIX_COEFFS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 63) - -#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_TYPE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 64) - -#define V4L2_CID_MPEG_VIDC_VIDEO_LAYER_ID \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 65) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VP9_PROFILE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 66) -enum v4l2_mpeg_vidc_video_vp9_profile { - V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_UNUSED = 0, - V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_P0 = 1, - V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_P2_10 = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_VP9_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 67) -enum v4l2_mpeg_vidc_video_vp9_level { - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_UNUSED = 0, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_1 = 1, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_11 = 2, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_2 = 3, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_21 = 4, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_3 = 5, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_31 = 6, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_4 = 7, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_41 = 8, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_5 = 9, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_51 = 10, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MB_ERROR_MAP_REPORTING \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 68) -#define V4L2_CID_MPEG_VIDC_VIDEO_CONTINUE_DATA_TRANSFER \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 69) - -#define V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_INPUT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 70) - -#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_ASSEMBLY \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 71) -enum v4l2_mpeg_vidc_video_assembly { - V4L2_MPEG_VIDC_FRAME_ASSEMBLY_DISABLE = 0, - V4L2_MPEG_VIDC_FRAME_ASSEMBLY_ENABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_H263_PROFILE\ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 72) -enum v4l2_mpeg_vidc_video_h263_profile { - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_BASELINE = 0, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_H320CODING = 1, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_BACKWARDCOMPATIBLE = 2, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_ISWV2 = 3, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_ISWV3 = 4, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_HIGHCOMPRESSION = 5, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_INTERNET = 6, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_INTERLACE = 7, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_HIGHLATENCY = 8, -}; - -#define V4L2_CID_MPEG_VIDEO_MIN_QP_PACKED \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 97) -#define V4L2_CID_MPEG_VIDEO_MAX_QP_PACKED \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 98) -#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 99) -#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 100) -#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 101) -#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP_MIN \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 102) -#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP_MIN \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 103) -#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP_MIN \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 104) -#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP_MAX \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 105) -#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP_MAX \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 106) -#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP_MAX \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 107) -#define V4L2_CID_MPEG_VIDC_VIDEO_QP_MASK \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 108) - -enum v4l2_mpeg_vidc_video_venc_iframesize_type { - V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_DEFAULT, - V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_MEDIUM, - V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_HUGE, - V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_UNLIMITED, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR_8BIT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 109) -#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR_10BIT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 110) - -#define V4L2_CID_MPEG_VIDC_VIDEO_TME_PROFILE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 111) - -enum v4l2_mpeg_vidc_video_tme_profile { - V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_0 = 0, - V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_1 = 1, - V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_2 = 2, - V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_3 = 3, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_TME_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 112) - -enum v4l2_mpeg_vidc_video_tme_level { - V4L2_MPEG_VIDC_VIDEO_TME_LEVEL_INTEGER = 0, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_TME_PAYLOAD_VERSION \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 113) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_CUSTOM_MATRIX \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 114) - -#define V4L2_CID_MPEG_VIDC_VIDEO_FLIP (V4L2_CID_MPEG_MSM_VIDC_BASE + 115) -enum v4l2_mpeg_vidc_video_flip { - V4L2_CID_MPEG_VIDC_VIDEO_FLIP_NONE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_FLIP_HORI = 1, - V4L2_CID_MPEG_VIDC_VIDEO_FLIP_VERT = 2, - V4L2_CID_MPEG_VIDC_VIDEO_FLIP_BOTH = 3, -}; - -/* HDR SEI INFO related control IDs and definitions*/ -#define V4L2_MPEG_VIDC_VENC_HDR_INFO_ENABLED 1 -#define V4L2_MPEG_VIDC_VENC_HDR_INFO_DISABLED 0 - -#define V4L2_CID_MPEG_VIDC_VENC_HDR_INFO \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 116) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_00 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 117) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_01 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 118) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_10 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 119) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_11 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 120) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_20 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 121) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_21 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 122) -#define V4L2_CID_MPEG_VIDC_VENC_WHITEPOINT_X \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 123) -#define V4L2_CID_MPEG_VIDC_VENC_WHITEPOINT_Y \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 124) -#define V4L2_CID_MPEG_VIDC_VENC_MAX_DISP_LUM \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 125) -#define V4L2_CID_MPEG_VIDC_VENC_MIN_DISP_LUM \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 126) -#define V4L2_CID_MPEG_VIDC_VENC_MAX_CLL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 127) -#define V4L2_CID_MPEG_VIDC_VENC_MAX_FLL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 128) - -#define V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 129) -enum v4l2_mpeg_vidc_perf_level { - V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL = 0, - V4L2_CID_MPEG_VIDC_PERF_LEVEL_PERFORMANCE = 1, - V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_AIR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE + 130) -#define V4L2_CID_MPEG_VIDC_VIDEO_AIR_REF (V4L2_CID_MPEG_MSM_VIDC_BASE + 131) -#define V4L2_CID_MPEG_VIDC_VIDEO_CIR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE + 132) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 135) - -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_GOB \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 136) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 137) -enum v4l2_mpeg_vidc_video_h264_vui_bitstream_restrict { - V4L2_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT_ENABLED = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 138) -enum v4l2_mpeg_vidc_video_deinterlace { - V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE_DISABLED = 0, - V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE_ENABLED = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG4_TIME_RESOLUTION \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 139) - -#define V4L2_CID_MPEG_VIDC_VIDEO_REQUEST_SEQ_HEADER \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 140) - -#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 141) -enum v4l2_mpeg_vidc_video_rate_control_timestamp_mode { - V4L2_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE_HONOR = 0, - V4L2_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE_IGNORE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 142) -enum vl42_mpeg_vidc_video_enable_initial_qp { - V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_IFRAME = 0x1, - V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_PFRAME = 0x2, - V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_BFRAME = 0x4, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_I_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 143) - -#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_P_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 144) - -#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_B_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 145) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 146) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PERF_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 147) -enum v4l2_mpeg_vidc_video_perf_mode { - V4L2_MPEG_VIDC_VIDEO_PERF_MAX_QUALITY = 1, - V4L2_MPEG_VIDC_VIDEO_PERF_POWER_SAVE = 2 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MBI_STATISTICS_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 148) - -#define V4L2_CID_MPEG_VIDC_VIDEO_CONFIG_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 149) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_PIC_ORDER_CNT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 150) - -#define V4L2_CID_MPEG_VIDC_VIDEO_SCS_THRESHOLD \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 151) - -#define V4L2_CID_MPEG_VIDC_VIDEO_MVC_BUFFER_LAYOUT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 152) - - -#define V4L2_CID_MPEG_VIDC_VIDEO_SECURE_SCALING_THRESHOLD \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 153) - -#define V4L2_CID_MPEG_VIDC_VIDEO_NON_SECURE_OUTPUT2 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 154) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_MIN_QP (V4L2_CID_MPEG_MSM_VIDC_BASE + 155) -#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_MAX_QP (V4L2_CID_MPEG_MSM_VIDC_BASE + 156) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H263_LEVEL (V4L2_CID_MPEG_MSM_VIDC_BASE + 157) -enum v4l2_mpeg_vidc_video_h263_level { - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_1_0 = 0, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_2_0 = 1, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_3_0 = 2, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_4_0 = 3, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_4_5 = 4, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_5_0 = 5, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_6_0 = 6, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_7_0 = 7, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_POST_LOOP_DEBLOCKER_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 158) - - -#define V4L2_CID_MPEG_VIDC_VIDEO_DIVX_FORMAT (V4L2_CID_MPEG_MSM_VIDC_BASE+159) - -enum v4l2_mpeg_vidc_video_divx_format_type { - V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_4 = 0, - V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_5 = 1, - V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_6 = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_QUALITY \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+160) - -#define V4L2_CID_MPEG_VIDC_IMG_GRID_DIMENSION \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+161) - -enum v4l2_mpeg_vidc_video_mbi_statistics_mode { - V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_DEFAULT = 0, - V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_1 = 1, - V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_2 = 2, - V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_3 = 3, -}; - -enum vl42_mpeg_vidc_video_h264_svc_nal { - V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC_DISABLED = 0, - V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC_ENABLED = 1, -}; - -enum v4l2_mpeg_vidc_video_h264_vui_timing_info { - V4L2_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO_ENABLED = 1 -}; - -/* Camera class control IDs */ - -#define V4L2_CID_CAMERA_CLASS_BASE (V4L2_CTRL_CLASS_CAMERA | 0x900) -#define V4L2_CID_CAMERA_CLASS (V4L2_CTRL_CLASS_CAMERA | 1) - -#define V4L2_CID_EXPOSURE_AUTO (V4L2_CID_CAMERA_CLASS_BASE+1) -enum v4l2_exposure_auto_type { - V4L2_EXPOSURE_AUTO = 0, - V4L2_EXPOSURE_MANUAL = 1, - V4L2_EXPOSURE_SHUTTER_PRIORITY = 2, - V4L2_EXPOSURE_APERTURE_PRIORITY = 3 -}; -#define V4L2_CID_EXPOSURE_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+2) -#define V4L2_CID_EXPOSURE_AUTO_PRIORITY (V4L2_CID_CAMERA_CLASS_BASE+3) - -#define V4L2_CID_PAN_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+4) -#define V4L2_CID_TILT_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+5) -#define V4L2_CID_PAN_RESET (V4L2_CID_CAMERA_CLASS_BASE+6) -#define V4L2_CID_TILT_RESET (V4L2_CID_CAMERA_CLASS_BASE+7) - -#define V4L2_CID_PAN_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+8) -#define V4L2_CID_TILT_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+9) - -#define V4L2_CID_FOCUS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+10) -#define V4L2_CID_FOCUS_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+11) -#define V4L2_CID_FOCUS_AUTO (V4L2_CID_CAMERA_CLASS_BASE+12) - -#define V4L2_CID_ZOOM_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+13) -#define V4L2_CID_ZOOM_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+14) -#define V4L2_CID_ZOOM_CONTINUOUS (V4L2_CID_CAMERA_CLASS_BASE+15) - -#define V4L2_CID_PRIVACY (V4L2_CID_CAMERA_CLASS_BASE+16) - -#define V4L2_CID_IRIS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+17) -#define V4L2_CID_IRIS_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+18) - -#define V4L2_CID_AUTO_EXPOSURE_BIAS (V4L2_CID_CAMERA_CLASS_BASE+19) - -#define V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE (V4L2_CID_CAMERA_CLASS_BASE+20) -enum v4l2_auto_n_preset_white_balance { - V4L2_WHITE_BALANCE_MANUAL = 0, - V4L2_WHITE_BALANCE_AUTO = 1, - V4L2_WHITE_BALANCE_INCANDESCENT = 2, - V4L2_WHITE_BALANCE_FLUORESCENT = 3, - V4L2_WHITE_BALANCE_FLUORESCENT_H = 4, - V4L2_WHITE_BALANCE_HORIZON = 5, - V4L2_WHITE_BALANCE_DAYLIGHT = 6, - V4L2_WHITE_BALANCE_FLASH = 7, - V4L2_WHITE_BALANCE_CLOUDY = 8, - V4L2_WHITE_BALANCE_SHADE = 9, -}; - -#define V4L2_CID_WIDE_DYNAMIC_RANGE (V4L2_CID_CAMERA_CLASS_BASE+21) -#define V4L2_CID_IMAGE_STABILIZATION (V4L2_CID_CAMERA_CLASS_BASE+22) - -#define V4L2_CID_ISO_SENSITIVITY (V4L2_CID_CAMERA_CLASS_BASE+23) -#define V4L2_CID_ISO_SENSITIVITY_AUTO (V4L2_CID_CAMERA_CLASS_BASE+24) -enum v4l2_iso_sensitivity_auto_type { - V4L2_ISO_SENSITIVITY_MANUAL = 0, - V4L2_ISO_SENSITIVITY_AUTO = 1, -}; - -#define V4L2_CID_EXPOSURE_METERING (V4L2_CID_CAMERA_CLASS_BASE+25) -enum v4l2_exposure_metering { - V4L2_EXPOSURE_METERING_AVERAGE = 0, - V4L2_EXPOSURE_METERING_CENTER_WEIGHTED = 1, - V4L2_EXPOSURE_METERING_SPOT = 2, - V4L2_EXPOSURE_METERING_MATRIX = 3, -}; - -#define V4L2_CID_SCENE_MODE (V4L2_CID_CAMERA_CLASS_BASE+26) -enum v4l2_scene_mode { - V4L2_SCENE_MODE_NONE = 0, - V4L2_SCENE_MODE_BACKLIGHT = 1, - V4L2_SCENE_MODE_BEACH_SNOW = 2, - V4L2_SCENE_MODE_CANDLE_LIGHT = 3, - V4L2_SCENE_MODE_DAWN_DUSK = 4, - V4L2_SCENE_MODE_FALL_COLORS = 5, - V4L2_SCENE_MODE_FIREWORKS = 6, - V4L2_SCENE_MODE_LANDSCAPE = 7, - V4L2_SCENE_MODE_NIGHT = 8, - V4L2_SCENE_MODE_PARTY_INDOOR = 9, - V4L2_SCENE_MODE_PORTRAIT = 10, - V4L2_SCENE_MODE_SPORTS = 11, - V4L2_SCENE_MODE_SUNSET = 12, - V4L2_SCENE_MODE_TEXT = 13, -}; - -#define V4L2_CID_3A_LOCK (V4L2_CID_CAMERA_CLASS_BASE+27) -#define V4L2_LOCK_EXPOSURE (1 << 0) -#define V4L2_LOCK_WHITE_BALANCE (1 << 1) -#define V4L2_LOCK_FOCUS (1 << 2) - -#define V4L2_CID_AUTO_FOCUS_START (V4L2_CID_CAMERA_CLASS_BASE+28) -#define V4L2_CID_AUTO_FOCUS_STOP (V4L2_CID_CAMERA_CLASS_BASE+29) -#define V4L2_CID_AUTO_FOCUS_STATUS (V4L2_CID_CAMERA_CLASS_BASE+30) -#define V4L2_AUTO_FOCUS_STATUS_IDLE (0 << 0) -#define V4L2_AUTO_FOCUS_STATUS_BUSY (1 << 0) -#define V4L2_AUTO_FOCUS_STATUS_REACHED (1 << 1) -#define V4L2_AUTO_FOCUS_STATUS_FAILED (1 << 2) - -#define V4L2_CID_AUTO_FOCUS_RANGE (V4L2_CID_CAMERA_CLASS_BASE+31) -enum v4l2_auto_focus_range { - V4L2_AUTO_FOCUS_RANGE_AUTO = 0, - V4L2_AUTO_FOCUS_RANGE_NORMAL = 1, - V4L2_AUTO_FOCUS_RANGE_MACRO = 2, - V4L2_AUTO_FOCUS_RANGE_INFINITY = 3, -}; - -#define V4L2_CID_PAN_SPEED (V4L2_CID_CAMERA_CLASS_BASE+32) -#define V4L2_CID_TILT_SPEED (V4L2_CID_CAMERA_CLASS_BASE+33) - -/* FM Modulator class control IDs */ - -#define V4L2_CID_FM_TX_CLASS_BASE (V4L2_CTRL_CLASS_FM_TX | 0x900) -#define V4L2_CID_FM_TX_CLASS (V4L2_CTRL_CLASS_FM_TX | 1) - -#define V4L2_CID_RDS_TX_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 1) -#define V4L2_CID_RDS_TX_PI (V4L2_CID_FM_TX_CLASS_BASE + 2) -#define V4L2_CID_RDS_TX_PTY (V4L2_CID_FM_TX_CLASS_BASE + 3) -#define V4L2_CID_RDS_TX_PS_NAME (V4L2_CID_FM_TX_CLASS_BASE + 5) -#define V4L2_CID_RDS_TX_RADIO_TEXT (V4L2_CID_FM_TX_CLASS_BASE + 6) -#define V4L2_CID_RDS_TX_MONO_STEREO (V4L2_CID_FM_TX_CLASS_BASE + 7) -#define V4L2_CID_RDS_TX_ARTIFICIAL_HEAD (V4L2_CID_FM_TX_CLASS_BASE + 8) -#define V4L2_CID_RDS_TX_COMPRESSED (V4L2_CID_FM_TX_CLASS_BASE + 9) -#define V4L2_CID_RDS_TX_DYNAMIC_PTY (V4L2_CID_FM_TX_CLASS_BASE + 10) -#define V4L2_CID_RDS_TX_TRAFFIC_ANNOUNCEMENT (V4L2_CID_FM_TX_CLASS_BASE + 11) -#define V4L2_CID_RDS_TX_TRAFFIC_PROGRAM (V4L2_CID_FM_TX_CLASS_BASE + 12) -#define V4L2_CID_RDS_TX_MUSIC_SPEECH (V4L2_CID_FM_TX_CLASS_BASE + 13) -#define V4L2_CID_RDS_TX_ALT_FREQS_ENABLE (V4L2_CID_FM_TX_CLASS_BASE + 14) -#define V4L2_CID_RDS_TX_ALT_FREQS (V4L2_CID_FM_TX_CLASS_BASE + 15) - -#define V4L2_CID_AUDIO_LIMITER_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 64) -#define V4L2_CID_AUDIO_LIMITER_RELEASE_TIME (V4L2_CID_FM_TX_CLASS_BASE + 65) -#define V4L2_CID_AUDIO_LIMITER_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 66) - -#define V4L2_CID_AUDIO_COMPRESSION_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 80) -#define V4L2_CID_AUDIO_COMPRESSION_GAIN (V4L2_CID_FM_TX_CLASS_BASE + 81) -#define V4L2_CID_AUDIO_COMPRESSION_THRESHOLD (V4L2_CID_FM_TX_CLASS_BASE + 82) -#define V4L2_CID_AUDIO_COMPRESSION_ATTACK_TIME (V4L2_CID_FM_TX_CLASS_BASE + 83) -#define V4L2_CID_AUDIO_COMPRESSION_RELEASE_TIME (V4L2_CID_FM_TX_CLASS_BASE + 84) - -#define V4L2_CID_PILOT_TONE_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 96) -#define V4L2_CID_PILOT_TONE_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 97) -#define V4L2_CID_PILOT_TONE_FREQUENCY (V4L2_CID_FM_TX_CLASS_BASE + 98) - -#define V4L2_CID_TUNE_PREEMPHASIS (V4L2_CID_FM_TX_CLASS_BASE + 112) -enum v4l2_preemphasis { - V4L2_PREEMPHASIS_DISABLED = 0, - V4L2_PREEMPHASIS_50_uS = 1, - V4L2_PREEMPHASIS_75_uS = 2, -}; -#define V4L2_CID_TUNE_POWER_LEVEL (V4L2_CID_FM_TX_CLASS_BASE + 113) -#define V4L2_CID_TUNE_ANTENNA_CAPACITOR (V4L2_CID_FM_TX_CLASS_BASE + 114) - - -/* Flash and privacy (indicator) light controls */ - -#define V4L2_CID_FLASH_CLASS_BASE (V4L2_CTRL_CLASS_FLASH | 0x900) -#define V4L2_CID_FLASH_CLASS (V4L2_CTRL_CLASS_FLASH | 1) - -#define V4L2_CID_FLASH_LED_MODE (V4L2_CID_FLASH_CLASS_BASE + 1) -enum v4l2_flash_led_mode { - V4L2_FLASH_LED_MODE_NONE, - V4L2_FLASH_LED_MODE_FLASH, - V4L2_FLASH_LED_MODE_TORCH, -}; - -#define V4L2_CID_FLASH_STROBE_SOURCE (V4L2_CID_FLASH_CLASS_BASE + 2) -enum v4l2_flash_strobe_source { - V4L2_FLASH_STROBE_SOURCE_SOFTWARE, - V4L2_FLASH_STROBE_SOURCE_EXTERNAL, -}; - -#define V4L2_CID_FLASH_STROBE (V4L2_CID_FLASH_CLASS_BASE + 3) -#define V4L2_CID_FLASH_STROBE_STOP (V4L2_CID_FLASH_CLASS_BASE + 4) -#define V4L2_CID_FLASH_STROBE_STATUS (V4L2_CID_FLASH_CLASS_BASE + 5) - -#define V4L2_CID_FLASH_TIMEOUT (V4L2_CID_FLASH_CLASS_BASE + 6) -#define V4L2_CID_FLASH_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 7) -#define V4L2_CID_FLASH_TORCH_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 8) -#define V4L2_CID_FLASH_INDICATOR_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 9) - -#define V4L2_CID_FLASH_FAULT (V4L2_CID_FLASH_CLASS_BASE + 10) -#define V4L2_FLASH_FAULT_OVER_VOLTAGE (1 << 0) -#define V4L2_FLASH_FAULT_TIMEOUT (1 << 1) -#define V4L2_FLASH_FAULT_OVER_TEMPERATURE (1 << 2) -#define V4L2_FLASH_FAULT_SHORT_CIRCUIT (1 << 3) -#define V4L2_FLASH_FAULT_OVER_CURRENT (1 << 4) -#define V4L2_FLASH_FAULT_INDICATOR (1 << 5) -#define V4L2_FLASH_FAULT_UNDER_VOLTAGE (1 << 6) -#define V4L2_FLASH_FAULT_INPUT_VOLTAGE (1 << 7) -#define V4L2_FLASH_FAULT_LED_OVER_TEMPERATURE (1 << 8) - -#define V4L2_CID_FLASH_CHARGE (V4L2_CID_FLASH_CLASS_BASE + 11) -#define V4L2_CID_FLASH_READY (V4L2_CID_FLASH_CLASS_BASE + 12) - - -/* JPEG-class control IDs */ - -#define V4L2_CID_JPEG_CLASS_BASE (V4L2_CTRL_CLASS_JPEG | 0x900) -#define V4L2_CID_JPEG_CLASS (V4L2_CTRL_CLASS_JPEG | 1) - -#define V4L2_CID_JPEG_CHROMA_SUBSAMPLING (V4L2_CID_JPEG_CLASS_BASE + 1) -enum v4l2_jpeg_chroma_subsampling { - V4L2_JPEG_CHROMA_SUBSAMPLING_444 = 0, - V4L2_JPEG_CHROMA_SUBSAMPLING_422 = 1, - V4L2_JPEG_CHROMA_SUBSAMPLING_420 = 2, - V4L2_JPEG_CHROMA_SUBSAMPLING_411 = 3, - V4L2_JPEG_CHROMA_SUBSAMPLING_410 = 4, - V4L2_JPEG_CHROMA_SUBSAMPLING_GRAY = 5, -}; -#define V4L2_CID_JPEG_RESTART_INTERVAL (V4L2_CID_JPEG_CLASS_BASE + 2) -#define V4L2_CID_JPEG_COMPRESSION_QUALITY (V4L2_CID_JPEG_CLASS_BASE + 3) - -#define V4L2_CID_JPEG_ACTIVE_MARKER (V4L2_CID_JPEG_CLASS_BASE + 4) -#define V4L2_JPEG_ACTIVE_MARKER_APP0 (1 << 0) -#define V4L2_JPEG_ACTIVE_MARKER_APP1 (1 << 1) -#define V4L2_JPEG_ACTIVE_MARKER_COM (1 << 16) -#define V4L2_JPEG_ACTIVE_MARKER_DQT (1 << 17) -#define V4L2_JPEG_ACTIVE_MARKER_DHT (1 << 18) - - -/* Image source controls */ -#define V4L2_CID_IMAGE_SOURCE_CLASS_BASE (V4L2_CTRL_CLASS_IMAGE_SOURCE | 0x900) -#define V4L2_CID_IMAGE_SOURCE_CLASS (V4L2_CTRL_CLASS_IMAGE_SOURCE | 1) - -#define V4L2_CID_VBLANK (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 1) -#define V4L2_CID_HBLANK (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 2) -#define V4L2_CID_ANALOGUE_GAIN (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 3) -#define V4L2_CID_TEST_PATTERN_RED (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 4) -#define V4L2_CID_TEST_PATTERN_GREENR (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 5) -#define V4L2_CID_TEST_PATTERN_BLUE (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 6) -#define V4L2_CID_TEST_PATTERN_GREENB (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 7) - - -/* Image processing controls */ - -#define V4L2_CID_IMAGE_PROC_CLASS_BASE (V4L2_CTRL_CLASS_IMAGE_PROC | 0x900) -#define V4L2_CID_IMAGE_PROC_CLASS (V4L2_CTRL_CLASS_IMAGE_PROC | 1) - -#define V4L2_CID_LINK_FREQ (V4L2_CID_IMAGE_PROC_CLASS_BASE + 1) -#define V4L2_CID_PIXEL_RATE (V4L2_CID_IMAGE_PROC_CLASS_BASE + 2) -#define V4L2_CID_TEST_PATTERN (V4L2_CID_IMAGE_PROC_CLASS_BASE + 3) - - -/* DV-class control IDs defined by V4L2 */ -#define V4L2_CID_DV_CLASS_BASE (V4L2_CTRL_CLASS_DV | 0x900) -#define V4L2_CID_DV_CLASS (V4L2_CTRL_CLASS_DV | 1) - -#define V4L2_CID_DV_TX_HOTPLUG (V4L2_CID_DV_CLASS_BASE + 1) -#define V4L2_CID_DV_TX_RXSENSE (V4L2_CID_DV_CLASS_BASE + 2) -#define V4L2_CID_DV_TX_EDID_PRESENT (V4L2_CID_DV_CLASS_BASE + 3) -#define V4L2_CID_DV_TX_MODE (V4L2_CID_DV_CLASS_BASE + 4) -enum v4l2_dv_tx_mode { - V4L2_DV_TX_MODE_DVI_D = 0, - V4L2_DV_TX_MODE_HDMI = 1, -}; -#define V4L2_CID_DV_TX_RGB_RANGE (V4L2_CID_DV_CLASS_BASE + 5) -enum v4l2_dv_rgb_range { - V4L2_DV_RGB_RANGE_AUTO = 0, - V4L2_DV_RGB_RANGE_LIMITED = 1, - V4L2_DV_RGB_RANGE_FULL = 2, -}; - -#define V4L2_CID_DV_TX_IT_CONTENT_TYPE (V4L2_CID_DV_CLASS_BASE + 6) -enum v4l2_dv_it_content_type { - V4L2_DV_IT_CONTENT_TYPE_GRAPHICS = 0, - V4L2_DV_IT_CONTENT_TYPE_PHOTO = 1, - V4L2_DV_IT_CONTENT_TYPE_CINEMA = 2, - V4L2_DV_IT_CONTENT_TYPE_GAME = 3, - V4L2_DV_IT_CONTENT_TYPE_NO_ITC = 4, -}; - -#define V4L2_CID_DV_RX_POWER_PRESENT (V4L2_CID_DV_CLASS_BASE + 100) -#define V4L2_CID_DV_RX_RGB_RANGE (V4L2_CID_DV_CLASS_BASE + 101) -#define V4L2_CID_DV_RX_IT_CONTENT_TYPE (V4L2_CID_DV_CLASS_BASE + 102) - -#define V4L2_CID_FM_RX_CLASS_BASE (V4L2_CTRL_CLASS_FM_RX | 0x900) -#define V4L2_CID_FM_RX_CLASS (V4L2_CTRL_CLASS_FM_RX | 1) - -#define V4L2_CID_TUNE_DEEMPHASIS (V4L2_CID_FM_RX_CLASS_BASE + 1) -enum v4l2_deemphasis { - V4L2_DEEMPHASIS_DISABLED = V4L2_PREEMPHASIS_DISABLED, - V4L2_DEEMPHASIS_50_uS = V4L2_PREEMPHASIS_50_uS, - V4L2_DEEMPHASIS_75_uS = V4L2_PREEMPHASIS_75_uS, -}; - -#define V4L2_CID_RDS_RECEPTION (V4L2_CID_FM_RX_CLASS_BASE + 2) -#define V4L2_CID_RDS_RX_PTY (V4L2_CID_FM_RX_CLASS_BASE + 3) -#define V4L2_CID_RDS_RX_PS_NAME (V4L2_CID_FM_RX_CLASS_BASE + 4) -#define V4L2_CID_RDS_RX_RADIO_TEXT (V4L2_CID_FM_RX_CLASS_BASE + 5) -#define V4L2_CID_RDS_RX_TRAFFIC_ANNOUNCEMENT (V4L2_CID_FM_RX_CLASS_BASE + 6) -#define V4L2_CID_RDS_RX_TRAFFIC_PROGRAM (V4L2_CID_FM_RX_CLASS_BASE + 7) -#define V4L2_CID_RDS_RX_MUSIC_SPEECH (V4L2_CID_FM_RX_CLASS_BASE + 8) - -#define V4L2_CID_RF_TUNER_CLASS_BASE (V4L2_CTRL_CLASS_RF_TUNER | 0x900) -#define V4L2_CID_RF_TUNER_CLASS (V4L2_CTRL_CLASS_RF_TUNER | 1) - -#define V4L2_CID_RF_TUNER_BANDWIDTH_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 11) -#define V4L2_CID_RF_TUNER_BANDWIDTH (V4L2_CID_RF_TUNER_CLASS_BASE + 12) -#define V4L2_CID_RF_TUNER_RF_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 32) -#define V4L2_CID_RF_TUNER_LNA_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 41) -#define V4L2_CID_RF_TUNER_LNA_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 42) -#define V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 51) -#define V4L2_CID_RF_TUNER_MIXER_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 52) -#define V4L2_CID_RF_TUNER_IF_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 61) -#define V4L2_CID_RF_TUNER_IF_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 62) -#define V4L2_CID_RF_TUNER_PLL_LOCK (V4L2_CID_RF_TUNER_CLASS_BASE + 91) - - -/* Detection-class control IDs defined by V4L2 */ -#define V4L2_CID_DETECT_CLASS_BASE (V4L2_CTRL_CLASS_DETECT | 0x900) -#define V4L2_CID_DETECT_CLASS (V4L2_CTRL_CLASS_DETECT | 1) - -#define V4L2_CID_DETECT_MD_MODE (V4L2_CID_DETECT_CLASS_BASE + 1) -enum v4l2_detect_md_mode { - V4L2_DETECT_MD_MODE_DISABLED = 0, - V4L2_DETECT_MD_MODE_GLOBAL = 1, - V4L2_DETECT_MD_MODE_THRESHOLD_GRID = 2, - V4L2_DETECT_MD_MODE_REGION_GRID = 3, -}; -#define V4L2_CID_DETECT_MD_GLOBAL_THRESHOLD (V4L2_CID_DETECT_CLASS_BASE + 2) -#define V4L2_CID_DETECT_MD_THRESHOLD_GRID (V4L2_CID_DETECT_CLASS_BASE + 3) -#define V4L2_CID_DETECT_MD_REGION_GRID (V4L2_CID_DETECT_CLASS_BASE + 4) - -#endif diff --git a/third_party/opencl/include/CL/cl.h b/third_party/opencl/include/CL/cl.h deleted file mode 100644 index 0086319f5faf1b..00000000000000 --- a/third_party/opencl/include/CL/cl.h +++ /dev/null @@ -1,1452 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -#ifndef __OPENCL_CL_H -#define __OPENCL_CL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ - -typedef struct _cl_platform_id * cl_platform_id; -typedef struct _cl_device_id * cl_device_id; -typedef struct _cl_context * cl_context; -typedef struct _cl_command_queue * cl_command_queue; -typedef struct _cl_mem * cl_mem; -typedef struct _cl_program * cl_program; -typedef struct _cl_kernel * cl_kernel; -typedef struct _cl_event * cl_event; -typedef struct _cl_sampler * cl_sampler; - -typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ -typedef cl_ulong cl_bitfield; -typedef cl_bitfield cl_device_type; -typedef cl_uint cl_platform_info; -typedef cl_uint cl_device_info; -typedef cl_bitfield cl_device_fp_config; -typedef cl_uint cl_device_mem_cache_type; -typedef cl_uint cl_device_local_mem_type; -typedef cl_bitfield cl_device_exec_capabilities; -typedef cl_bitfield cl_device_svm_capabilities; -typedef cl_bitfield cl_command_queue_properties; -typedef intptr_t cl_device_partition_property; -typedef cl_bitfield cl_device_affinity_domain; - -typedef intptr_t cl_context_properties; -typedef cl_uint cl_context_info; -typedef cl_bitfield cl_queue_properties; -typedef cl_uint cl_command_queue_info; -typedef cl_uint cl_channel_order; -typedef cl_uint cl_channel_type; -typedef cl_bitfield cl_mem_flags; -typedef cl_bitfield cl_svm_mem_flags; -typedef cl_uint cl_mem_object_type; -typedef cl_uint cl_mem_info; -typedef cl_bitfield cl_mem_migration_flags; -typedef cl_uint cl_image_info; -typedef cl_uint cl_buffer_create_type; -typedef cl_uint cl_addressing_mode; -typedef cl_uint cl_filter_mode; -typedef cl_uint cl_sampler_info; -typedef cl_bitfield cl_map_flags; -typedef intptr_t cl_pipe_properties; -typedef cl_uint cl_pipe_info; -typedef cl_uint cl_program_info; -typedef cl_uint cl_program_build_info; -typedef cl_uint cl_program_binary_type; -typedef cl_int cl_build_status; -typedef cl_uint cl_kernel_info; -typedef cl_uint cl_kernel_arg_info; -typedef cl_uint cl_kernel_arg_address_qualifier; -typedef cl_uint cl_kernel_arg_access_qualifier; -typedef cl_bitfield cl_kernel_arg_type_qualifier; -typedef cl_uint cl_kernel_work_group_info; -typedef cl_uint cl_kernel_sub_group_info; -typedef cl_uint cl_event_info; -typedef cl_uint cl_command_type; -typedef cl_uint cl_profiling_info; -typedef cl_bitfield cl_sampler_properties; -typedef cl_uint cl_kernel_exec_info; - -typedef struct _cl_image_format { - cl_channel_order image_channel_order; - cl_channel_type image_channel_data_type; -} cl_image_format; - -typedef struct _cl_image_desc { - cl_mem_object_type image_type; - size_t image_width; - size_t image_height; - size_t image_depth; - size_t image_array_size; - size_t image_row_pitch; - size_t image_slice_pitch; - cl_uint num_mip_levels; - cl_uint num_samples; -#ifdef __GNUC__ - __extension__ /* Prevents warnings about anonymous union in -pedantic builds */ -#endif - union { - cl_mem buffer; - cl_mem mem_object; - }; -} cl_image_desc; - -typedef struct _cl_buffer_region { - size_t origin; - size_t size; -} cl_buffer_region; - - -/******************************************************************************/ - -/* Error Codes */ -#define CL_SUCCESS 0 -#define CL_DEVICE_NOT_FOUND -1 -#define CL_DEVICE_NOT_AVAILABLE -2 -#define CL_COMPILER_NOT_AVAILABLE -3 -#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 -#define CL_OUT_OF_RESOURCES -5 -#define CL_OUT_OF_HOST_MEMORY -6 -#define CL_PROFILING_INFO_NOT_AVAILABLE -7 -#define CL_MEM_COPY_OVERLAP -8 -#define CL_IMAGE_FORMAT_MISMATCH -9 -#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 -#define CL_BUILD_PROGRAM_FAILURE -11 -#define CL_MAP_FAILURE -12 -#define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 -#define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 -#define CL_COMPILE_PROGRAM_FAILURE -15 -#define CL_LINKER_NOT_AVAILABLE -16 -#define CL_LINK_PROGRAM_FAILURE -17 -#define CL_DEVICE_PARTITION_FAILED -18 -#define CL_KERNEL_ARG_INFO_NOT_AVAILABLE -19 - -#define CL_INVALID_VALUE -30 -#define CL_INVALID_DEVICE_TYPE -31 -#define CL_INVALID_PLATFORM -32 -#define CL_INVALID_DEVICE -33 -#define CL_INVALID_CONTEXT -34 -#define CL_INVALID_QUEUE_PROPERTIES -35 -#define CL_INVALID_COMMAND_QUEUE -36 -#define CL_INVALID_HOST_PTR -37 -#define CL_INVALID_MEM_OBJECT -38 -#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 -#define CL_INVALID_IMAGE_SIZE -40 -#define CL_INVALID_SAMPLER -41 -#define CL_INVALID_BINARY -42 -#define CL_INVALID_BUILD_OPTIONS -43 -#define CL_INVALID_PROGRAM -44 -#define CL_INVALID_PROGRAM_EXECUTABLE -45 -#define CL_INVALID_KERNEL_NAME -46 -#define CL_INVALID_KERNEL_DEFINITION -47 -#define CL_INVALID_KERNEL -48 -#define CL_INVALID_ARG_INDEX -49 -#define CL_INVALID_ARG_VALUE -50 -#define CL_INVALID_ARG_SIZE -51 -#define CL_INVALID_KERNEL_ARGS -52 -#define CL_INVALID_WORK_DIMENSION -53 -#define CL_INVALID_WORK_GROUP_SIZE -54 -#define CL_INVALID_WORK_ITEM_SIZE -55 -#define CL_INVALID_GLOBAL_OFFSET -56 -#define CL_INVALID_EVENT_WAIT_LIST -57 -#define CL_INVALID_EVENT -58 -#define CL_INVALID_OPERATION -59 -#define CL_INVALID_GL_OBJECT -60 -#define CL_INVALID_BUFFER_SIZE -61 -#define CL_INVALID_MIP_LEVEL -62 -#define CL_INVALID_GLOBAL_WORK_SIZE -63 -#define CL_INVALID_PROPERTY -64 -#define CL_INVALID_IMAGE_DESCRIPTOR -65 -#define CL_INVALID_COMPILER_OPTIONS -66 -#define CL_INVALID_LINKER_OPTIONS -67 -#define CL_INVALID_DEVICE_PARTITION_COUNT -68 -#define CL_INVALID_PIPE_SIZE -69 -#define CL_INVALID_DEVICE_QUEUE -70 - -/* OpenCL Version */ -#define CL_VERSION_1_0 1 -#define CL_VERSION_1_1 1 -#define CL_VERSION_1_2 1 -#define CL_VERSION_2_0 1 -#define CL_VERSION_2_1 1 - -/* cl_bool */ -#define CL_FALSE 0 -#define CL_TRUE 1 -#define CL_BLOCKING CL_TRUE -#define CL_NON_BLOCKING CL_FALSE - -/* cl_platform_info */ -#define CL_PLATFORM_PROFILE 0x0900 -#define CL_PLATFORM_VERSION 0x0901 -#define CL_PLATFORM_NAME 0x0902 -#define CL_PLATFORM_VENDOR 0x0903 -#define CL_PLATFORM_EXTENSIONS 0x0904 -#define CL_PLATFORM_HOST_TIMER_RESOLUTION 0x0905 - -/* cl_device_type - bitfield */ -#define CL_DEVICE_TYPE_DEFAULT (1 << 0) -#define CL_DEVICE_TYPE_CPU (1 << 1) -#define CL_DEVICE_TYPE_GPU (1 << 2) -#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) -#define CL_DEVICE_TYPE_CUSTOM (1 << 4) -#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF - -/* cl_device_info */ -#define CL_DEVICE_TYPE 0x1000 -#define CL_DEVICE_VENDOR_ID 0x1001 -#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 -#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 -#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 -#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B -#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C -#define CL_DEVICE_ADDRESS_BITS 0x100D -#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E -#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F -#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 -#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 -#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 -#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 -#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 -#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 -#define CL_DEVICE_IMAGE_SUPPORT 0x1016 -#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 -#define CL_DEVICE_MAX_SAMPLERS 0x1018 -#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 -#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A -#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B -#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C -#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D -#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E -#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F -#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 -#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 -#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 -#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 -#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 -#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 -#define CL_DEVICE_ENDIAN_LITTLE 0x1026 -#define CL_DEVICE_AVAILABLE 0x1027 -#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 -#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 -#define CL_DEVICE_QUEUE_PROPERTIES 0x102A /* deprecated */ -#define CL_DEVICE_QUEUE_ON_HOST_PROPERTIES 0x102A -#define CL_DEVICE_NAME 0x102B -#define CL_DEVICE_VENDOR 0x102C -#define CL_DRIVER_VERSION 0x102D -#define CL_DEVICE_PROFILE 0x102E -#define CL_DEVICE_VERSION 0x102F -#define CL_DEVICE_EXTENSIONS 0x1030 -#define CL_DEVICE_PLATFORM 0x1031 -#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 -/* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG */ -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 -#define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 /* deprecated */ -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C -#define CL_DEVICE_OPENCL_C_VERSION 0x103D -#define CL_DEVICE_LINKER_AVAILABLE 0x103E -#define CL_DEVICE_BUILT_IN_KERNELS 0x103F -#define CL_DEVICE_IMAGE_MAX_BUFFER_SIZE 0x1040 -#define CL_DEVICE_IMAGE_MAX_ARRAY_SIZE 0x1041 -#define CL_DEVICE_PARENT_DEVICE 0x1042 -#define CL_DEVICE_PARTITION_MAX_SUB_DEVICES 0x1043 -#define CL_DEVICE_PARTITION_PROPERTIES 0x1044 -#define CL_DEVICE_PARTITION_AFFINITY_DOMAIN 0x1045 -#define CL_DEVICE_PARTITION_TYPE 0x1046 -#define CL_DEVICE_REFERENCE_COUNT 0x1047 -#define CL_DEVICE_PREFERRED_INTEROP_USER_SYNC 0x1048 -#define CL_DEVICE_PRINTF_BUFFER_SIZE 0x1049 -#define CL_DEVICE_IMAGE_PITCH_ALIGNMENT 0x104A -#define CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT 0x104B -#define CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS 0x104C -#define CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE 0x104D -#define CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES 0x104E -#define CL_DEVICE_QUEUE_ON_DEVICE_PREFERRED_SIZE 0x104F -#define CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE 0x1050 -#define CL_DEVICE_MAX_ON_DEVICE_QUEUES 0x1051 -#define CL_DEVICE_MAX_ON_DEVICE_EVENTS 0x1052 -#define CL_DEVICE_SVM_CAPABILITIES 0x1053 -#define CL_DEVICE_GLOBAL_VARIABLE_PREFERRED_TOTAL_SIZE 0x1054 -#define CL_DEVICE_MAX_PIPE_ARGS 0x1055 -#define CL_DEVICE_PIPE_MAX_ACTIVE_RESERVATIONS 0x1056 -#define CL_DEVICE_PIPE_MAX_PACKET_SIZE 0x1057 -#define CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT 0x1058 -#define CL_DEVICE_PREFERRED_GLOBAL_ATOMIC_ALIGNMENT 0x1059 -#define CL_DEVICE_PREFERRED_LOCAL_ATOMIC_ALIGNMENT 0x105A -#define CL_DEVICE_IL_VERSION 0x105B -#define CL_DEVICE_MAX_NUM_SUB_GROUPS 0x105C -#define CL_DEVICE_SUB_GROUP_INDEPENDENT_FORWARD_PROGRESS 0x105D - -/* cl_device_fp_config - bitfield */ -#define CL_FP_DENORM (1 << 0) -#define CL_FP_INF_NAN (1 << 1) -#define CL_FP_ROUND_TO_NEAREST (1 << 2) -#define CL_FP_ROUND_TO_ZERO (1 << 3) -#define CL_FP_ROUND_TO_INF (1 << 4) -#define CL_FP_FMA (1 << 5) -#define CL_FP_SOFT_FLOAT (1 << 6) -#define CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7) - -/* cl_device_mem_cache_type */ -#define CL_NONE 0x0 -#define CL_READ_ONLY_CACHE 0x1 -#define CL_READ_WRITE_CACHE 0x2 - -/* cl_device_local_mem_type */ -#define CL_LOCAL 0x1 -#define CL_GLOBAL 0x2 - -/* cl_device_exec_capabilities - bitfield */ -#define CL_EXEC_KERNEL (1 << 0) -#define CL_EXEC_NATIVE_KERNEL (1 << 1) - -/* cl_command_queue_properties - bitfield */ -#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) -#define CL_QUEUE_PROFILING_ENABLE (1 << 1) -#define CL_QUEUE_ON_DEVICE (1 << 2) -#define CL_QUEUE_ON_DEVICE_DEFAULT (1 << 3) - -/* cl_context_info */ -#define CL_CONTEXT_REFERENCE_COUNT 0x1080 -#define CL_CONTEXT_DEVICES 0x1081 -#define CL_CONTEXT_PROPERTIES 0x1082 -#define CL_CONTEXT_NUM_DEVICES 0x1083 - -/* cl_context_properties */ -#define CL_CONTEXT_PLATFORM 0x1084 -#define CL_CONTEXT_INTEROP_USER_SYNC 0x1085 - -/* cl_device_partition_property */ -#define CL_DEVICE_PARTITION_EQUALLY 0x1086 -#define CL_DEVICE_PARTITION_BY_COUNTS 0x1087 -#define CL_DEVICE_PARTITION_BY_COUNTS_LIST_END 0x0 -#define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN 0x1088 - -/* cl_device_affinity_domain */ -#define CL_DEVICE_AFFINITY_DOMAIN_NUMA (1 << 0) -#define CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE (1 << 1) -#define CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE (1 << 2) -#define CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE (1 << 3) -#define CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE (1 << 4) -#define CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE (1 << 5) - -/* cl_device_svm_capabilities */ -#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER (1 << 0) -#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER (1 << 1) -#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM (1 << 2) -#define CL_DEVICE_SVM_ATOMICS (1 << 3) - -/* cl_command_queue_info */ -#define CL_QUEUE_CONTEXT 0x1090 -#define CL_QUEUE_DEVICE 0x1091 -#define CL_QUEUE_REFERENCE_COUNT 0x1092 -#define CL_QUEUE_PROPERTIES 0x1093 -#define CL_QUEUE_SIZE 0x1094 -#define CL_QUEUE_DEVICE_DEFAULT 0x1095 - -/* cl_mem_flags and cl_svm_mem_flags - bitfield */ -#define CL_MEM_READ_WRITE (1 << 0) -#define CL_MEM_WRITE_ONLY (1 << 1) -#define CL_MEM_READ_ONLY (1 << 2) -#define CL_MEM_USE_HOST_PTR (1 << 3) -#define CL_MEM_ALLOC_HOST_PTR (1 << 4) -#define CL_MEM_COPY_HOST_PTR (1 << 5) -/* reserved (1 << 6) */ -#define CL_MEM_HOST_WRITE_ONLY (1 << 7) -#define CL_MEM_HOST_READ_ONLY (1 << 8) -#define CL_MEM_HOST_NO_ACCESS (1 << 9) -#define CL_MEM_SVM_FINE_GRAIN_BUFFER (1 << 10) /* used by cl_svm_mem_flags only */ -#define CL_MEM_SVM_ATOMICS (1 << 11) /* used by cl_svm_mem_flags only */ -#define CL_MEM_KERNEL_READ_AND_WRITE (1 << 12) - -/* cl_mem_migration_flags - bitfield */ -#define CL_MIGRATE_MEM_OBJECT_HOST (1 << 0) -#define CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED (1 << 1) - -/* cl_channel_order */ -#define CL_R 0x10B0 -#define CL_A 0x10B1 -#define CL_RG 0x10B2 -#define CL_RA 0x10B3 -#define CL_RGB 0x10B4 -#define CL_RGBA 0x10B5 -#define CL_BGRA 0x10B6 -#define CL_ARGB 0x10B7 -#define CL_INTENSITY 0x10B8 -#define CL_LUMINANCE 0x10B9 -#define CL_Rx 0x10BA -#define CL_RGx 0x10BB -#define CL_RGBx 0x10BC -#define CL_DEPTH 0x10BD -#define CL_DEPTH_STENCIL 0x10BE -#define CL_sRGB 0x10BF -#define CL_sRGBx 0x10C0 -#define CL_sRGBA 0x10C1 -#define CL_sBGRA 0x10C2 -#define CL_ABGR 0x10C3 - -/* cl_channel_type */ -#define CL_SNORM_INT8 0x10D0 -#define CL_SNORM_INT16 0x10D1 -#define CL_UNORM_INT8 0x10D2 -#define CL_UNORM_INT16 0x10D3 -#define CL_UNORM_SHORT_565 0x10D4 -#define CL_UNORM_SHORT_555 0x10D5 -#define CL_UNORM_INT_101010 0x10D6 -#define CL_SIGNED_INT8 0x10D7 -#define CL_SIGNED_INT16 0x10D8 -#define CL_SIGNED_INT32 0x10D9 -#define CL_UNSIGNED_INT8 0x10DA -#define CL_UNSIGNED_INT16 0x10DB -#define CL_UNSIGNED_INT32 0x10DC -#define CL_HALF_FLOAT 0x10DD -#define CL_FLOAT 0x10DE -#define CL_UNORM_INT24 0x10DF -#define CL_UNORM_INT_101010_2 0x10E0 - -/* cl_mem_object_type */ -#define CL_MEM_OBJECT_BUFFER 0x10F0 -#define CL_MEM_OBJECT_IMAGE2D 0x10F1 -#define CL_MEM_OBJECT_IMAGE3D 0x10F2 -#define CL_MEM_OBJECT_IMAGE2D_ARRAY 0x10F3 -#define CL_MEM_OBJECT_IMAGE1D 0x10F4 -#define CL_MEM_OBJECT_IMAGE1D_ARRAY 0x10F5 -#define CL_MEM_OBJECT_IMAGE1D_BUFFER 0x10F6 -#define CL_MEM_OBJECT_PIPE 0x10F7 - -/* cl_mem_info */ -#define CL_MEM_TYPE 0x1100 -#define CL_MEM_FLAGS 0x1101 -#define CL_MEM_SIZE 0x1102 -#define CL_MEM_HOST_PTR 0x1103 -#define CL_MEM_MAP_COUNT 0x1104 -#define CL_MEM_REFERENCE_COUNT 0x1105 -#define CL_MEM_CONTEXT 0x1106 -#define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 -#define CL_MEM_OFFSET 0x1108 -#define CL_MEM_USES_SVM_POINTER 0x1109 - -/* cl_image_info */ -#define CL_IMAGE_FORMAT 0x1110 -#define CL_IMAGE_ELEMENT_SIZE 0x1111 -#define CL_IMAGE_ROW_PITCH 0x1112 -#define CL_IMAGE_SLICE_PITCH 0x1113 -#define CL_IMAGE_WIDTH 0x1114 -#define CL_IMAGE_HEIGHT 0x1115 -#define CL_IMAGE_DEPTH 0x1116 -#define CL_IMAGE_ARRAY_SIZE 0x1117 -#define CL_IMAGE_BUFFER 0x1118 -#define CL_IMAGE_NUM_MIP_LEVELS 0x1119 -#define CL_IMAGE_NUM_SAMPLES 0x111A - -/* cl_pipe_info */ -#define CL_PIPE_PACKET_SIZE 0x1120 -#define CL_PIPE_MAX_PACKETS 0x1121 - -/* cl_addressing_mode */ -#define CL_ADDRESS_NONE 0x1130 -#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 -#define CL_ADDRESS_CLAMP 0x1132 -#define CL_ADDRESS_REPEAT 0x1133 -#define CL_ADDRESS_MIRRORED_REPEAT 0x1134 - -/* cl_filter_mode */ -#define CL_FILTER_NEAREST 0x1140 -#define CL_FILTER_LINEAR 0x1141 - -/* cl_sampler_info */ -#define CL_SAMPLER_REFERENCE_COUNT 0x1150 -#define CL_SAMPLER_CONTEXT 0x1151 -#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 -#define CL_SAMPLER_ADDRESSING_MODE 0x1153 -#define CL_SAMPLER_FILTER_MODE 0x1154 -#define CL_SAMPLER_MIP_FILTER_MODE 0x1155 -#define CL_SAMPLER_LOD_MIN 0x1156 -#define CL_SAMPLER_LOD_MAX 0x1157 - -/* cl_map_flags - bitfield */ -#define CL_MAP_READ (1 << 0) -#define CL_MAP_WRITE (1 << 1) -#define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2) - -/* cl_program_info */ -#define CL_PROGRAM_REFERENCE_COUNT 0x1160 -#define CL_PROGRAM_CONTEXT 0x1161 -#define CL_PROGRAM_NUM_DEVICES 0x1162 -#define CL_PROGRAM_DEVICES 0x1163 -#define CL_PROGRAM_SOURCE 0x1164 -#define CL_PROGRAM_BINARY_SIZES 0x1165 -#define CL_PROGRAM_BINARIES 0x1166 -#define CL_PROGRAM_NUM_KERNELS 0x1167 -#define CL_PROGRAM_KERNEL_NAMES 0x1168 -#define CL_PROGRAM_IL 0x1169 - -/* cl_program_build_info */ -#define CL_PROGRAM_BUILD_STATUS 0x1181 -#define CL_PROGRAM_BUILD_OPTIONS 0x1182 -#define CL_PROGRAM_BUILD_LOG 0x1183 -#define CL_PROGRAM_BINARY_TYPE 0x1184 -#define CL_PROGRAM_BUILD_GLOBAL_VARIABLE_TOTAL_SIZE 0x1185 - -/* cl_program_binary_type */ -#define CL_PROGRAM_BINARY_TYPE_NONE 0x0 -#define CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT 0x1 -#define CL_PROGRAM_BINARY_TYPE_LIBRARY 0x2 -#define CL_PROGRAM_BINARY_TYPE_EXECUTABLE 0x4 - -/* cl_build_status */ -#define CL_BUILD_SUCCESS 0 -#define CL_BUILD_NONE -1 -#define CL_BUILD_ERROR -2 -#define CL_BUILD_IN_PROGRESS -3 - -/* cl_kernel_info */ -#define CL_KERNEL_FUNCTION_NAME 0x1190 -#define CL_KERNEL_NUM_ARGS 0x1191 -#define CL_KERNEL_REFERENCE_COUNT 0x1192 -#define CL_KERNEL_CONTEXT 0x1193 -#define CL_KERNEL_PROGRAM 0x1194 -#define CL_KERNEL_ATTRIBUTES 0x1195 -#define CL_KERNEL_MAX_NUM_SUB_GROUPS 0x11B9 -#define CL_KERNEL_COMPILE_NUM_SUB_GROUPS 0x11BA - -/* cl_kernel_arg_info */ -#define CL_KERNEL_ARG_ADDRESS_QUALIFIER 0x1196 -#define CL_KERNEL_ARG_ACCESS_QUALIFIER 0x1197 -#define CL_KERNEL_ARG_TYPE_NAME 0x1198 -#define CL_KERNEL_ARG_TYPE_QUALIFIER 0x1199 -#define CL_KERNEL_ARG_NAME 0x119A - -/* cl_kernel_arg_address_qualifier */ -#define CL_KERNEL_ARG_ADDRESS_GLOBAL 0x119B -#define CL_KERNEL_ARG_ADDRESS_LOCAL 0x119C -#define CL_KERNEL_ARG_ADDRESS_CONSTANT 0x119D -#define CL_KERNEL_ARG_ADDRESS_PRIVATE 0x119E - -/* cl_kernel_arg_access_qualifier */ -#define CL_KERNEL_ARG_ACCESS_READ_ONLY 0x11A0 -#define CL_KERNEL_ARG_ACCESS_WRITE_ONLY 0x11A1 -#define CL_KERNEL_ARG_ACCESS_READ_WRITE 0x11A2 -#define CL_KERNEL_ARG_ACCESS_NONE 0x11A3 - -/* cl_kernel_arg_type_qualifer */ -#define CL_KERNEL_ARG_TYPE_NONE 0 -#define CL_KERNEL_ARG_TYPE_CONST (1 << 0) -#define CL_KERNEL_ARG_TYPE_RESTRICT (1 << 1) -#define CL_KERNEL_ARG_TYPE_VOLATILE (1 << 2) -#define CL_KERNEL_ARG_TYPE_PIPE (1 << 3) - -/* cl_kernel_work_group_info */ -#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 -#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 -#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 -#define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 -#define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 -#define CL_KERNEL_GLOBAL_WORK_SIZE 0x11B5 - -/* cl_kernel_sub_group_info */ -#define CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE 0x2033 -#define CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE 0x2034 -#define CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT 0x11B8 - -/* cl_kernel_exec_info */ -#define CL_KERNEL_EXEC_INFO_SVM_PTRS 0x11B6 -#define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM 0x11B7 - -/* cl_event_info */ -#define CL_EVENT_COMMAND_QUEUE 0x11D0 -#define CL_EVENT_COMMAND_TYPE 0x11D1 -#define CL_EVENT_REFERENCE_COUNT 0x11D2 -#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 -#define CL_EVENT_CONTEXT 0x11D4 - -/* cl_command_type */ -#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 -#define CL_COMMAND_TASK 0x11F1 -#define CL_COMMAND_NATIVE_KERNEL 0x11F2 -#define CL_COMMAND_READ_BUFFER 0x11F3 -#define CL_COMMAND_WRITE_BUFFER 0x11F4 -#define CL_COMMAND_COPY_BUFFER 0x11F5 -#define CL_COMMAND_READ_IMAGE 0x11F6 -#define CL_COMMAND_WRITE_IMAGE 0x11F7 -#define CL_COMMAND_COPY_IMAGE 0x11F8 -#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 -#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA -#define CL_COMMAND_MAP_BUFFER 0x11FB -#define CL_COMMAND_MAP_IMAGE 0x11FC -#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD -#define CL_COMMAND_MARKER 0x11FE -#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF -#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 -#define CL_COMMAND_READ_BUFFER_RECT 0x1201 -#define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 -#define CL_COMMAND_COPY_BUFFER_RECT 0x1203 -#define CL_COMMAND_USER 0x1204 -#define CL_COMMAND_BARRIER 0x1205 -#define CL_COMMAND_MIGRATE_MEM_OBJECTS 0x1206 -#define CL_COMMAND_FILL_BUFFER 0x1207 -#define CL_COMMAND_FILL_IMAGE 0x1208 -#define CL_COMMAND_SVM_FREE 0x1209 -#define CL_COMMAND_SVM_MEMCPY 0x120A -#define CL_COMMAND_SVM_MEMFILL 0x120B -#define CL_COMMAND_SVM_MAP 0x120C -#define CL_COMMAND_SVM_UNMAP 0x120D - -/* command execution status */ -#define CL_COMPLETE 0x0 -#define CL_RUNNING 0x1 -#define CL_SUBMITTED 0x2 -#define CL_QUEUED 0x3 - -/* cl_buffer_create_type */ -#define CL_BUFFER_CREATE_TYPE_REGION 0x1220 - -/* cl_profiling_info */ -#define CL_PROFILING_COMMAND_QUEUED 0x1280 -#define CL_PROFILING_COMMAND_SUBMIT 0x1281 -#define CL_PROFILING_COMMAND_START 0x1282 -#define CL_PROFILING_COMMAND_END 0x1283 -#define CL_PROFILING_COMMAND_COMPLETE 0x1284 - -/********************************************************************************************************/ - -/* Platform API */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformIDs(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformInfo(cl_platform_id /* platform */, - cl_platform_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Device APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceIDs(cl_platform_id /* platform */, - cl_device_type /* device_type */, - cl_uint /* num_entries */, - cl_device_id * /* devices */, - cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceInfo(cl_device_id /* device */, - cl_device_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateSubDevices(cl_device_id /* in_device */, - const cl_device_partition_property * /* properties */, - cl_uint /* num_devices */, - cl_device_id * /* out_devices */, - cl_uint * /* num_devices_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainDevice(cl_device_id /* device */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseDevice(cl_device_id /* device */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetDefaultDeviceCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_2_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceAndHostTimer(cl_device_id /* device */, - cl_ulong* /* device_timestamp */, - cl_ulong* /* host_timestamp */) CL_API_SUFFIX__VERSION_2_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetHostTimer(cl_device_id /* device */, - cl_ulong * /* host_timestamp */) CL_API_SUFFIX__VERSION_2_1; - - -/* Context APIs */ -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContext(const cl_context_properties * /* properties */, - cl_uint /* num_devices */, - const cl_device_id * /* devices */, - void (CL_CALLBACK * /* pfn_notify */)(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContextFromType(const cl_context_properties * /* properties */, - cl_device_type /* device_type */, - void (CL_CALLBACK * /* pfn_notify*/ )(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetContextInfo(cl_context /* context */, - cl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Command Queue APIs */ -extern CL_API_ENTRY cl_command_queue CL_API_CALL -clCreateCommandQueueWithProperties(cl_context /* context */, - cl_device_id /* device */, - const cl_queue_properties * /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetCommandQueueInfo(cl_command_queue /* command_queue */, - cl_command_queue_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Memory Object APIs */ -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - size_t /* size */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateSubBuffer(cl_mem /* buffer */, - cl_mem_flags /* flags */, - cl_buffer_create_type /* buffer_create_type */, - const void * /* buffer_create_info */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - const cl_image_desc * /* image_desc */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreatePipe(cl_context /* context */, - cl_mem_flags /* flags */, - cl_uint /* pipe_packet_size */, - cl_uint /* pipe_max_packets */, - const cl_pipe_properties * /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSupportedImageFormats(cl_context /* context */, - cl_mem_flags /* flags */, - cl_mem_object_type /* image_type */, - cl_uint /* num_entries */, - cl_image_format * /* image_formats */, - cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetMemObjectInfo(cl_mem /* memobj */, - cl_mem_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetImageInfo(cl_mem /* image */, - cl_image_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPipeInfo(cl_mem /* pipe */, - cl_pipe_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_2_0; - - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetMemObjectDestructorCallback(cl_mem /* memobj */, - void (CL_CALLBACK * /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_API_SUFFIX__VERSION_1_1; - -/* SVM Allocation APIs */ -extern CL_API_ENTRY void * CL_API_CALL -clSVMAlloc(cl_context /* context */, - cl_svm_mem_flags /* flags */, - size_t /* size */, - cl_uint /* alignment */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY void CL_API_CALL -clSVMFree(cl_context /* context */, - void * /* svm_pointer */) CL_API_SUFFIX__VERSION_2_0; - -/* Sampler APIs */ -extern CL_API_ENTRY cl_sampler CL_API_CALL -clCreateSamplerWithProperties(cl_context /* context */, - const cl_sampler_properties * /* normalized_coords */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSamplerInfo(cl_sampler /* sampler */, - cl_sampler_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Program Object APIs */ -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithSource(cl_context /* context */, - cl_uint /* count */, - const char ** /* strings */, - const size_t * /* lengths */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBinary(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const size_t * /* lengths */, - const unsigned char ** /* binaries */, - cl_int * /* binary_status */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBuiltInKernels(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* kernel_names */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithIL(cl_context /* context */, - const void* /* il */, - size_t /* length */, - cl_int* /* errcode_ret */) CL_API_SUFFIX__VERSION_2_1; - - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clBuildProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCompileProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - cl_uint /* num_input_headers */, - const cl_program * /* input_headers */, - const char ** /* header_include_names */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_program CL_API_CALL -clLinkProgram(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - cl_uint /* num_input_programs */, - const cl_program * /* input_programs */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */, - cl_int * /* errcode_ret */ ) CL_API_SUFFIX__VERSION_1_2; - - -extern CL_API_ENTRY cl_int CL_API_CALL -clUnloadPlatformCompiler(cl_platform_id /* platform */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramInfo(cl_program /* program */, - cl_program_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramBuildInfo(cl_program /* program */, - cl_device_id /* device */, - cl_program_build_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Kernel Object APIs */ -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCreateKernel(cl_program /* program */, - const char * /* kernel_name */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateKernelsInProgram(cl_program /* program */, - cl_uint /* num_kernels */, - cl_kernel * /* kernels */, - cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCloneKernel(cl_kernel /* source_kernel */, - cl_int* /* errcode_ret */) CL_API_SUFFIX__VERSION_2_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArg(cl_kernel /* kernel */, - cl_uint /* arg_index */, - size_t /* arg_size */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArgSVMPointer(cl_kernel /* kernel */, - cl_uint /* arg_index */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelExecInfo(cl_kernel /* kernel */, - cl_kernel_exec_info /* param_name */, - size_t /* param_value_size */, - const void * /* param_value */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelInfo(cl_kernel /* kernel */, - cl_kernel_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelArgInfo(cl_kernel /* kernel */, - cl_uint /* arg_indx */, - cl_kernel_arg_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelWorkGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_work_group_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelSubGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_sub_group_info /* param_name */, - size_t /* input_value_size */, - const void* /*input_value */, - size_t /* param_value_size */, - void* /* param_value */, - size_t* /* param_value_size_ret */ ) CL_API_SUFFIX__VERSION_2_1; - - -/* Event Object APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clWaitForEvents(cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventInfo(cl_event /* event */, - cl_event_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateUserEvent(cl_context /* context */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetUserEventStatus(cl_event /* event */, - cl_int /* execution_status */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetEventCallback( cl_event /* event */, - cl_int /* command_exec_callback_type */, - void (CL_CALLBACK * /* pfn_notify */)(cl_event, cl_int, void *), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_1; - -/* Profiling APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventProfilingInfo(cl_event /* event */, - cl_profiling_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Flush and Finish APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -/* Enqueued Commands APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - size_t /* offset */, - size_t /* size */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - size_t /* offset */, - size_t /* size */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueFillBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - const void * /* pattern */, - size_t /* pattern_size */, - size_t /* offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - size_t /* src_offset */, - size_t /* dst_offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferRect(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin */, - const size_t * /* dst_origin */, - const size_t * /* region */, - size_t /* src_row_pitch */, - size_t /* src_slice_pitch */, - size_t /* dst_row_pitch */, - size_t /* dst_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_read */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* row_pitch */, - size_t /* slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_write */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* input_row_pitch */, - size_t /* input_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueFillImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - const void * /* fill_color */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImage(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_image */, - const size_t * /* src_origin[3] */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin[3] */, - const size_t * /* region[3] */, - size_t /* dst_offset */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_image */, - size_t /* src_offset */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - size_t /* offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t * /* image_row_pitch */, - size_t * /* image_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, - cl_mem /* memobj */, - void * /* mapped_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMigrateMemObjects(cl_command_queue /* command_queue */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_objects */, - cl_mem_migration_flags /* flags */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* work_dim */, - const size_t * /* global_work_offset */, - const size_t * /* global_work_size */, - const size_t * /* local_work_size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNativeKernel(cl_command_queue /* command_queue */, - void (CL_CALLBACK * /*user_func*/)(void *), - void * /* args */, - size_t /* cb_args */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_list */, - const void ** /* args_mem_loc */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMarkerWithWaitList(cl_command_queue /* command_queue */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueBarrierWithWaitList(cl_command_queue /* command_queue */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMFree(cl_command_queue /* command_queue */, - cl_uint /* num_svm_pointers */, - void *[] /* svm_pointers[] */, - void (CL_CALLBACK * /*pfn_free_func*/)(cl_command_queue /* queue */, - cl_uint /* num_svm_pointers */, - void *[] /* svm_pointers[] */, - void * /* user_data */), - void * /* user_data */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMMemcpy(cl_command_queue /* command_queue */, - cl_bool /* blocking_copy */, - void * /* dst_ptr */, - const void * /* src_ptr */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMMemFill(cl_command_queue /* command_queue */, - void * /* svm_ptr */, - const void * /* pattern */, - size_t /* pattern_size */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMMap(cl_command_queue /* command_queue */, - cl_bool /* blocking_map */, - cl_map_flags /* flags */, - void * /* svm_ptr */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMUnmap(cl_command_queue /* command_queue */, - void * /* svm_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMMigrateMem(cl_command_queue /* command_queue */, - cl_uint /* num_svm_pointers */, - const void ** /* svm_pointers */, - const size_t * /* sizes */, - cl_mem_migration_flags /* flags */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_1; - - -/* Extension function access - * - * Returns the extension function address for the given function name, - * or NULL if a valid function can not be found. The client must - * check to make sure the address is not NULL, before using or - * calling the returned function address. - */ -extern CL_API_ENTRY void * CL_API_CALL -clGetExtensionFunctionAddressForPlatform(cl_platform_id /* platform */, - const char * /* func_name */) CL_API_SUFFIX__VERSION_1_2; - - -/* Deprecated OpenCL 1.1 APIs */ -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL -clCreateImage2D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_row_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL -clCreateImage3D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_depth */, - size_t /* image_row_pitch */, - size_t /* image_slice_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL -clEnqueueMarker(cl_command_queue /* command_queue */, - cl_event * /* event */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL -clEnqueueWaitForEvents(cl_command_queue /* command_queue */, - cl_uint /* num_events */, - const cl_event * /* event_list */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL -clEnqueueBarrier(cl_command_queue /* command_queue */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL -clUnloadCompiler(void) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED void * CL_API_CALL -clGetExtensionFunctionAddress(const char * /* func_name */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -/* Deprecated OpenCL 2.0 APIs */ -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_2_DEPRECATED cl_command_queue CL_API_CALL -clCreateCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue_properties /* properties */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED; - - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_2_DEPRECATED cl_sampler CL_API_CALL -clCreateSampler(cl_context /* context */, - cl_bool /* normalized_coords */, - cl_addressing_mode /* addressing_mode */, - cl_filter_mode /* filter_mode */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_2_DEPRECATED cl_int CL_API_CALL -clEnqueueTask(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_H */ - diff --git a/third_party/opencl/include/CL/cl_d3d10.h b/third_party/opencl/include/CL/cl_d3d10.h deleted file mode 100644 index d5960a43f72123..00000000000000 --- a/third_party/opencl/include/CL/cl_d3d10.h +++ /dev/null @@ -1,131 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_CL_D3D10_H -#define __OPENCL_CL_D3D10_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/****************************************************************************** - * cl_khr_d3d10_sharing */ -#define cl_khr_d3d10_sharing 1 - -typedef cl_uint cl_d3d10_device_source_khr; -typedef cl_uint cl_d3d10_device_set_khr; - -/******************************************************************************/ - -/* Error Codes */ -#define CL_INVALID_D3D10_DEVICE_KHR -1002 -#define CL_INVALID_D3D10_RESOURCE_KHR -1003 -#define CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR -1004 -#define CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR -1005 - -/* cl_d3d10_device_source_nv */ -#define CL_D3D10_DEVICE_KHR 0x4010 -#define CL_D3D10_DXGI_ADAPTER_KHR 0x4011 - -/* cl_d3d10_device_set_nv */ -#define CL_PREFERRED_DEVICES_FOR_D3D10_KHR 0x4012 -#define CL_ALL_DEVICES_FOR_D3D10_KHR 0x4013 - -/* cl_context_info */ -#define CL_CONTEXT_D3D10_DEVICE_KHR 0x4014 -#define CL_CONTEXT_D3D10_PREFER_SHARED_RESOURCES_KHR 0x402C - -/* cl_mem_info */ -#define CL_MEM_D3D10_RESOURCE_KHR 0x4015 - -/* cl_image_info */ -#define CL_IMAGE_D3D10_SUBRESOURCE_KHR 0x4016 - -/* cl_command_type */ -#define CL_COMMAND_ACQUIRE_D3D10_OBJECTS_KHR 0x4017 -#define CL_COMMAND_RELEASE_D3D10_OBJECTS_KHR 0x4018 - -/******************************************************************************/ - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D10KHR_fn)( - cl_platform_id platform, - cl_d3d10_device_source_khr d3d_device_source, - void * d3d_object, - cl_d3d10_device_set_khr d3d_device_set, - cl_uint num_entries, - cl_device_id * devices, - cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10BufferKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D10Buffer * resource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture2DKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D10Texture2D * resource, - UINT subresource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture3DKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D10Texture3D * resource, - UINT subresource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D10ObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D10ObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_0; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_D3D10_H */ - diff --git a/third_party/opencl/include/CL/cl_d3d11.h b/third_party/opencl/include/CL/cl_d3d11.h deleted file mode 100644 index 39f9072398a29a..00000000000000 --- a/third_party/opencl/include/CL/cl_d3d11.h +++ /dev/null @@ -1,131 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_CL_D3D11_H -#define __OPENCL_CL_D3D11_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/****************************************************************************** - * cl_khr_d3d11_sharing */ -#define cl_khr_d3d11_sharing 1 - -typedef cl_uint cl_d3d11_device_source_khr; -typedef cl_uint cl_d3d11_device_set_khr; - -/******************************************************************************/ - -/* Error Codes */ -#define CL_INVALID_D3D11_DEVICE_KHR -1006 -#define CL_INVALID_D3D11_RESOURCE_KHR -1007 -#define CL_D3D11_RESOURCE_ALREADY_ACQUIRED_KHR -1008 -#define CL_D3D11_RESOURCE_NOT_ACQUIRED_KHR -1009 - -/* cl_d3d11_device_source */ -#define CL_D3D11_DEVICE_KHR 0x4019 -#define CL_D3D11_DXGI_ADAPTER_KHR 0x401A - -/* cl_d3d11_device_set */ -#define CL_PREFERRED_DEVICES_FOR_D3D11_KHR 0x401B -#define CL_ALL_DEVICES_FOR_D3D11_KHR 0x401C - -/* cl_context_info */ -#define CL_CONTEXT_D3D11_DEVICE_KHR 0x401D -#define CL_CONTEXT_D3D11_PREFER_SHARED_RESOURCES_KHR 0x402D - -/* cl_mem_info */ -#define CL_MEM_D3D11_RESOURCE_KHR 0x401E - -/* cl_image_info */ -#define CL_IMAGE_D3D11_SUBRESOURCE_KHR 0x401F - -/* cl_command_type */ -#define CL_COMMAND_ACQUIRE_D3D11_OBJECTS_KHR 0x4020 -#define CL_COMMAND_RELEASE_D3D11_OBJECTS_KHR 0x4021 - -/******************************************************************************/ - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D11KHR_fn)( - cl_platform_id platform, - cl_d3d11_device_source_khr d3d_device_source, - void * d3d_object, - cl_d3d11_device_set_khr d3d_device_set, - cl_uint num_entries, - cl_device_id * devices, - cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11BufferKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D11Buffer * resource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11Texture2DKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D11Texture2D * resource, - UINT subresource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11Texture3DKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D11Texture3D * resource, - UINT subresource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D11ObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D11ObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_2; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_D3D11_H */ - diff --git a/third_party/opencl/include/CL/cl_dx9_media_sharing.h b/third_party/opencl/include/CL/cl_dx9_media_sharing.h deleted file mode 100644 index 2729e8b9e89a10..00000000000000 --- a/third_party/opencl/include/CL/cl_dx9_media_sharing.h +++ /dev/null @@ -1,132 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_CL_DX9_MEDIA_SHARING_H -#define __OPENCL_CL_DX9_MEDIA_SHARING_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ -/* cl_khr_dx9_media_sharing */ -#define cl_khr_dx9_media_sharing 1 - -typedef cl_uint cl_dx9_media_adapter_type_khr; -typedef cl_uint cl_dx9_media_adapter_set_khr; - -#if defined(_WIN32) -#include -typedef struct _cl_dx9_surface_info_khr -{ - IDirect3DSurface9 *resource; - HANDLE shared_handle; -} cl_dx9_surface_info_khr; -#endif - - -/******************************************************************************/ - -/* Error Codes */ -#define CL_INVALID_DX9_MEDIA_ADAPTER_KHR -1010 -#define CL_INVALID_DX9_MEDIA_SURFACE_KHR -1011 -#define CL_DX9_MEDIA_SURFACE_ALREADY_ACQUIRED_KHR -1012 -#define CL_DX9_MEDIA_SURFACE_NOT_ACQUIRED_KHR -1013 - -/* cl_media_adapter_type_khr */ -#define CL_ADAPTER_D3D9_KHR 0x2020 -#define CL_ADAPTER_D3D9EX_KHR 0x2021 -#define CL_ADAPTER_DXVA_KHR 0x2022 - -/* cl_media_adapter_set_khr */ -#define CL_PREFERRED_DEVICES_FOR_DX9_MEDIA_ADAPTER_KHR 0x2023 -#define CL_ALL_DEVICES_FOR_DX9_MEDIA_ADAPTER_KHR 0x2024 - -/* cl_context_info */ -#define CL_CONTEXT_ADAPTER_D3D9_KHR 0x2025 -#define CL_CONTEXT_ADAPTER_D3D9EX_KHR 0x2026 -#define CL_CONTEXT_ADAPTER_DXVA_KHR 0x2027 - -/* cl_mem_info */ -#define CL_MEM_DX9_MEDIA_ADAPTER_TYPE_KHR 0x2028 -#define CL_MEM_DX9_MEDIA_SURFACE_INFO_KHR 0x2029 - -/* cl_image_info */ -#define CL_IMAGE_DX9_MEDIA_PLANE_KHR 0x202A - -/* cl_command_type */ -#define CL_COMMAND_ACQUIRE_DX9_MEDIA_SURFACES_KHR 0x202B -#define CL_COMMAND_RELEASE_DX9_MEDIA_SURFACES_KHR 0x202C - -/******************************************************************************/ - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromDX9MediaAdapterKHR_fn)( - cl_platform_id platform, - cl_uint num_media_adapters, - cl_dx9_media_adapter_type_khr * media_adapter_type, - void * media_adapters, - cl_dx9_media_adapter_set_khr media_adapter_set, - cl_uint num_entries, - cl_device_id * devices, - cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromDX9MediaSurfaceKHR_fn)( - cl_context context, - cl_mem_flags flags, - cl_dx9_media_adapter_type_khr adapter_type, - void * surface_info, - cl_uint plane, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireDX9MediaSurfacesKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseDX9MediaSurfacesKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_2; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_DX9_MEDIA_SHARING_H */ - diff --git a/third_party/opencl/include/CL/cl_egl.h b/third_party/opencl/include/CL/cl_egl.h deleted file mode 100644 index a765bd5266c02f..00000000000000 --- a/third_party/opencl/include/CL/cl_egl.h +++ /dev/null @@ -1,136 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -#ifndef __OPENCL_CL_EGL_H -#define __OPENCL_CL_EGL_H - -#ifdef __APPLE__ - -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -/* Command type for events created with clEnqueueAcquireEGLObjectsKHR */ -#define CL_COMMAND_EGL_FENCE_SYNC_OBJECT_KHR 0x202F -#define CL_COMMAND_ACQUIRE_EGL_OBJECTS_KHR 0x202D -#define CL_COMMAND_RELEASE_EGL_OBJECTS_KHR 0x202E - -/* Error type for clCreateFromEGLImageKHR */ -#define CL_INVALID_EGL_OBJECT_KHR -1093 -#define CL_EGL_RESOURCE_NOT_ACQUIRED_KHR -1092 - -/* CLeglImageKHR is an opaque handle to an EGLImage */ -typedef void* CLeglImageKHR; - -/* CLeglDisplayKHR is an opaque handle to an EGLDisplay */ -typedef void* CLeglDisplayKHR; - -/* CLeglSyncKHR is an opaque handle to an EGLSync object */ -typedef void* CLeglSyncKHR; - -/* properties passed to clCreateFromEGLImageKHR */ -typedef intptr_t cl_egl_image_properties_khr; - - -#define cl_khr_egl_image 1 - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromEGLImageKHR(cl_context /* context */, - CLeglDisplayKHR /* egldisplay */, - CLeglImageKHR /* eglimage */, - cl_mem_flags /* flags */, - const cl_egl_image_properties_khr * /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromEGLImageKHR_fn)( - cl_context context, - CLeglDisplayKHR egldisplay, - CLeglImageKHR eglimage, - cl_mem_flags flags, - const cl_egl_image_properties_khr * properties, - cl_int * errcode_ret); - - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireEGLObjectsKHR(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireEGLObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event); - - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseEGLObjectsKHR(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseEGLObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event); - - -#define cl_khr_egl_event 1 - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateEventFromEGLSyncKHR(cl_context /* context */, - CLeglSyncKHR /* sync */, - CLeglDisplayKHR /* display */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_event (CL_API_CALL *clCreateEventFromEGLSyncKHR_fn)( - cl_context context, - CLeglSyncKHR sync, - CLeglDisplayKHR display, - cl_int * errcode_ret); - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_EGL_H */ diff --git a/third_party/opencl/include/CL/cl_ext.h b/third_party/opencl/include/CL/cl_ext.h deleted file mode 100644 index 7941583895c57b..00000000000000 --- a/third_party/opencl/include/CL/cl_ext.h +++ /dev/null @@ -1,391 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11928 $ on $Date: 2010-07-13 09:04:56 -0700 (Tue, 13 Jul 2010) $ */ - -/* cl_ext.h contains OpenCL extensions which don't have external */ -/* (OpenGL, D3D) dependencies. */ - -#ifndef __CL_EXT_H -#define __CL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include - #include -#else - #include -#endif - -/* cl_khr_fp16 extension - no extension #define since it has no functions */ -#define CL_DEVICE_HALF_FP_CONFIG 0x1033 - -/* Memory object destruction - * - * Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR - * - * Registers a user callback function that will be called when the memory object is deleted and its resources - * freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback - * stack associated with memobj. The registered user callback functions are called in the reverse order in - * which they were registered. The user callback functions are called and then the memory object is deleted - * and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be - * notified when the memory referenced by host_ptr, specified when the memory object is created and used as - * the storage bits for the memory object, can be reused or freed. - * - * The application may not call CL api's with the cl_mem object passed to the pfn_notify. - * - * Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - */ -#define cl_APPLE_SetMemObjectDestructor 1 -cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem /* memobj */, - void (* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/* Context Logging Functions - * - * The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext(). - * Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - * - * clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger - */ -#define cl_APPLE_ContextLoggingFunctions 1 -extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStdout sends all log messages to the file descriptor stdout */ -extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStderr sends all log messages to the file descriptor stderr */ -extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/************************ -* cl_khr_icd extension * -************************/ -#define cl_khr_icd 1 - -/* cl_platform_info */ -#define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920 - -/* Additional Error Codes */ -#define CL_PLATFORM_NOT_FOUND_KHR -1001 - -extern CL_API_ENTRY cl_int CL_API_CALL -clIcdGetPlatformIDsKHR(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)( - cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - - -/* Extension: cl_khr_image2D_buffer - * - * This extension allows a 2D image to be created from a cl_mem buffer without a copy. - * The type associated with a 2D image created from a buffer in an OpenCL program is image2d_t. - * Both the sampler and sampler-less read_image built-in functions are supported for 2D images - * and 2D images created from a buffer. Similarly, the write_image built-ins are also supported - * for 2D images created from a buffer. - * - * When the 2D image from buffer is created, the client must specify the width, - * height, image format (i.e. channel order and channel data type) and optionally the row pitch - * - * The pitch specified must be a multiple of CL_DEVICE_IMAGE_PITCH_ALIGNMENT pixels. - * The base address of the buffer must be aligned to CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT pixels. - */ - -/************************************* - * cl_khr_initalize_memory extension * - *************************************/ - -#define CL_CONTEXT_MEMORY_INITIALIZE_KHR 0x2030 - - -/************************************** - * cl_khr_terminate_context extension * - **************************************/ - -#define CL_DEVICE_TERMINATE_CAPABILITY_KHR 0x2031 -#define CL_CONTEXT_TERMINATE_KHR 0x2032 - -#define cl_khr_terminate_context 1 -extern CL_API_ENTRY cl_int CL_API_CALL clTerminateContextKHR(cl_context /* context */) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clTerminateContextKHR_fn)(cl_context /* context */) CL_EXT_SUFFIX__VERSION_1_2; - - -/* - * Extension: cl_khr_spir - * - * This extension adds support to create an OpenCL program object from a - * Standard Portable Intermediate Representation (SPIR) instance - */ - -#define CL_DEVICE_SPIR_VERSIONS 0x40E0 -#define CL_PROGRAM_BINARY_TYPE_INTERMEDIATE 0x40E1 - - -/****************************************** -* cl_nv_device_attribute_query extension * -******************************************/ -/* cl_nv_device_attribute_query extension - no extension #define since it has no functions */ -#define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000 -#define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001 -#define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002 -#define CL_DEVICE_WARP_SIZE_NV 0x4003 -#define CL_DEVICE_GPU_OVERLAP_NV 0x4004 -#define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005 -#define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006 - -/********************************* -* cl_amd_device_attribute_query * -*********************************/ -#define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036 - -/********************************* -* cl_arm_printf extension -*********************************/ -#define CL_PRINTF_CALLBACK_ARM 0x40B0 -#define CL_PRINTF_BUFFERSIZE_ARM 0x40B1 - -#ifdef CL_VERSION_1_1 - /*********************************** - * cl_ext_device_fission extension * - ***********************************/ - #define cl_ext_device_fission 1 - - extern CL_API_ENTRY cl_int CL_API_CALL - clReleaseDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clReleaseDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - extern CL_API_ENTRY cl_int CL_API_CALL - clRetainDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clRetainDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef cl_ulong cl_device_partition_property_ext; - extern CL_API_ENTRY cl_int CL_API_CALL - clCreateSubDevicesEXT( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - ( CL_API_CALL * clCreateSubDevicesEXT_fn)( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - /* cl_device_partition_property_ext */ - #define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050 - #define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051 - #define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052 - #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053 - - /* clDeviceGetInfo selectors */ - #define CL_DEVICE_PARENT_DEVICE_EXT 0x4054 - #define CL_DEVICE_PARTITION_TYPES_EXT 0x4055 - #define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056 - #define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057 - #define CL_DEVICE_PARTITION_STYLE_EXT 0x4058 - - /* error codes */ - #define CL_DEVICE_PARTITION_FAILED_EXT -1057 - #define CL_INVALID_PARTITION_COUNT_EXT -1058 - #define CL_INVALID_PARTITION_NAME_EXT -1059 - - /* CL_AFFINITY_DOMAINs */ - #define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1 - #define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2 - #define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3 - #define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4 - #define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10 - #define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100 - - /* cl_device_partition_property_ext list terminators */ - #define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1) - -/********************************* -* cl_qcom_ext_host_ptr extension -*********************************/ - -#define CL_MEM_EXT_HOST_PTR_QCOM (1 << 29) - -#define CL_DEVICE_EXT_MEM_PADDING_IN_BYTES_QCOM 0x40A0 -#define CL_DEVICE_PAGE_SIZE_QCOM 0x40A1 -#define CL_IMAGE_ROW_ALIGNMENT_QCOM 0x40A2 -#define CL_IMAGE_SLICE_ALIGNMENT_QCOM 0x40A3 -#define CL_MEM_HOST_UNCACHED_QCOM 0x40A4 -#define CL_MEM_HOST_WRITEBACK_QCOM 0x40A5 -#define CL_MEM_HOST_WRITETHROUGH_QCOM 0x40A6 -#define CL_MEM_HOST_WRITE_COMBINING_QCOM 0x40A7 - -typedef cl_uint cl_image_pitch_info_qcom; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceImageInfoQCOM(cl_device_id device, - size_t image_width, - size_t image_height, - const cl_image_format *image_format, - cl_image_pitch_info_qcom param_name, - size_t param_value_size, - void *param_value, - size_t *param_value_size_ret); - -typedef struct _cl_mem_ext_host_ptr -{ - /* Type of external memory allocation. */ - /* Legal values will be defined in layered extensions. */ - cl_uint allocation_type; - - /* Host cache policy for this external memory allocation. */ - cl_uint host_cache_policy; - -} cl_mem_ext_host_ptr; - -/********************************* -* cl_qcom_ion_host_ptr extension -*********************************/ - -#define CL_MEM_ION_HOST_PTR_QCOM 0x40A8 - -typedef struct _cl_mem_ion_host_ptr -{ - /* Type of external memory allocation. */ - /* Must be CL_MEM_ION_HOST_PTR_QCOM for ION allocations. */ - cl_mem_ext_host_ptr ext_host_ptr; - - /* ION file descriptor */ - int ion_filedesc; - - /* Host pointer to the ION allocated memory */ - void* ion_hostptr; - -} cl_mem_ion_host_ptr; - -#endif /* CL_VERSION_1_1 */ - - -#ifdef CL_VERSION_2_0 -/********************************* -* cl_khr_sub_groups extension -*********************************/ -#define cl_khr_sub_groups 1 - -typedef cl_uint cl_kernel_sub_group_info_khr; - -/* cl_khr_sub_group_info */ -#define CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE_KHR 0x2033 -#define CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE_KHR 0x2034 - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelSubGroupInfoKHR(cl_kernel /* in_kernel */, - cl_device_id /*in_device*/, - cl_kernel_sub_group_info_khr /* param_name */, - size_t /*input_value_size*/, - const void * /*input_value*/, - size_t /*param_value_size*/, - void* /*param_value*/, - size_t* /*param_value_size_ret*/ ) CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED; - -typedef CL_API_ENTRY cl_int - ( CL_API_CALL * clGetKernelSubGroupInfoKHR_fn)(cl_kernel /* in_kernel */, - cl_device_id /*in_device*/, - cl_kernel_sub_group_info_khr /* param_name */, - size_t /*input_value_size*/, - const void * /*input_value*/, - size_t /*param_value_size*/, - void* /*param_value*/, - size_t* /*param_value_size_ret*/ ) CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED; -#endif /* CL_VERSION_2_0 */ - -#ifdef CL_VERSION_2_1 -/********************************* -* cl_khr_priority_hints extension -*********************************/ -#define cl_khr_priority_hints 1 - -typedef cl_uint cl_queue_priority_khr; - -/* cl_command_queue_properties */ -#define CL_QUEUE_PRIORITY_KHR 0x1096 - -/* cl_queue_priority_khr */ -#define CL_QUEUE_PRIORITY_HIGH_KHR (1<<0) -#define CL_QUEUE_PRIORITY_MED_KHR (1<<1) -#define CL_QUEUE_PRIORITY_LOW_KHR (1<<2) - -#endif /* CL_VERSION_2_1 */ - -#ifdef CL_VERSION_2_1 -/********************************* -* cl_khr_throttle_hints extension -*********************************/ -#define cl_khr_throttle_hints 1 - -typedef cl_uint cl_queue_throttle_khr; - -/* cl_command_queue_properties */ -#define CL_QUEUE_THROTTLE_KHR 0x1097 - -/* cl_queue_throttle_khr */ -#define CL_QUEUE_THROTTLE_HIGH_KHR (1<<0) -#define CL_QUEUE_THROTTLE_MED_KHR (1<<1) -#define CL_QUEUE_THROTTLE_LOW_KHR (1<<2) - -#endif /* CL_VERSION_2_1 */ - -#ifdef __cplusplus -} -#endif - - -#endif /* __CL_EXT_H */ diff --git a/third_party/opencl/include/CL/cl_ext_qcom.h b/third_party/opencl/include/CL/cl_ext_qcom.h deleted file mode 100644 index 6328a1cd93a10e..00000000000000 --- a/third_party/opencl/include/CL/cl_ext_qcom.h +++ /dev/null @@ -1,255 +0,0 @@ -/* Copyright (c) 2009-2017 Qualcomm Technologies, Inc. All Rights Reserved. - * Qualcomm Technologies Proprietary and Confidential. - */ - -#ifndef __OPENCL_CL_EXT_QCOM_H -#define __OPENCL_CL_EXT_QCOM_H - -// Needed by cl_khr_egl_event extension -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************ - * cl_qcom_create_buffer_from_image * - ************************************/ - -#define CL_BUFFER_FROM_IMAGE_ROW_PITCH_QCOM 0x40C0 -#define CL_BUFFER_FROM_IMAGE_SLICE_PITCH_QCOM 0x40C1 - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBufferFromImageQCOM(cl_mem image, - cl_mem_flags flags, - cl_int *errcode_ret); - - -/************************************ - * cl_qcom_limited_printf extension * - ************************************/ - -/* Builtin printf function buffer size in bytes. */ -#define CL_DEVICE_PRINTF_BUFFER_SIZE_QCOM 0x1049 - - -/************************************* - * cl_qcom_extended_images extension * - *************************************/ - -#define CL_CONTEXT_ENABLE_EXTENDED_IMAGES_QCOM 0x40AA -#define CL_DEVICE_EXTENDED_IMAGE2D_MAX_WIDTH_QCOM 0x40AB -#define CL_DEVICE_EXTENDED_IMAGE2D_MAX_HEIGHT_QCOM 0x40AC -#define CL_DEVICE_EXTENDED_IMAGE3D_MAX_WIDTH_QCOM 0x40AD -#define CL_DEVICE_EXTENDED_IMAGE3D_MAX_HEIGHT_QCOM 0x40AE -#define CL_DEVICE_EXTENDED_IMAGE3D_MAX_DEPTH_QCOM 0x40AF - -/************************************* - * cl_qcom_perf_hint extension * - *************************************/ - -typedef cl_uint cl_perf_hint; - -#define CL_CONTEXT_PERF_HINT_QCOM 0x40C2 - -/*cl_perf_hint*/ -#define CL_PERF_HINT_HIGH_QCOM 0x40C3 -#define CL_PERF_HINT_NORMAL_QCOM 0x40C4 -#define CL_PERF_HINT_LOW_QCOM 0x40C5 - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetPerfHintQCOM(cl_context context, - cl_perf_hint perf_hint); - -// This extension is published at Khronos, so its definitions are made in cl_ext.h. -// This duplication is for backward compatibility. - -#ifndef CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM - -/********************************* -* cl_qcom_android_native_buffer_host_ptr extension -*********************************/ - -#define CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM 0x40C6 - - -typedef struct _cl_mem_android_native_buffer_host_ptr -{ - // Type of external memory allocation. - // Must be CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM for Android native buffers. - cl_mem_ext_host_ptr ext_host_ptr; - - // Virtual pointer to the android native buffer - void* anb_ptr; - -} cl_mem_android_native_buffer_host_ptr; - -#endif //#ifndef CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM - -/*********************************** -* cl_img_egl_image extension * -************************************/ -typedef void* CLeglImageIMG; -typedef void* CLeglDisplayIMG; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromEGLImageIMG(cl_context context, - cl_mem_flags flags, - CLeglImageIMG image, - CLeglDisplayIMG display, - cl_int *errcode_ret); - - -/********************************* -* cl_qcom_other_image extension -*********************************/ - -// Extended flag for creating/querying QCOM non-standard images -#define CL_MEM_OTHER_IMAGE_QCOM (1<<25) - -// cl_channel_type -#define CL_QCOM_UNORM_MIPI10 0x4159 -#define CL_QCOM_UNORM_MIPI12 0x415A -#define CL_QCOM_UNSIGNED_MIPI10 0x415B -#define CL_QCOM_UNSIGNED_MIPI12 0x415C -#define CL_QCOM_UNORM_INT10 0x415D -#define CL_QCOM_UNORM_INT12 0x415E -#define CL_QCOM_UNSIGNED_INT16 0x415F - -// cl_channel_order -// Dedicate 0x4130-0x415F range for QCOM extended image formats -// 0x4130 - 0x4132 range is assigned to pixel-oriented compressed format -#define CL_QCOM_BAYER 0x414E - -#define CL_QCOM_NV12 0x4133 -#define CL_QCOM_NV12_Y 0x4134 -#define CL_QCOM_NV12_UV 0x4135 - -#define CL_QCOM_TILED_NV12 0x4136 -#define CL_QCOM_TILED_NV12_Y 0x4137 -#define CL_QCOM_TILED_NV12_UV 0x4138 - -#define CL_QCOM_P010 0x413C -#define CL_QCOM_P010_Y 0x413D -#define CL_QCOM_P010_UV 0x413E - -#define CL_QCOM_TILED_P010 0x413F -#define CL_QCOM_TILED_P010_Y 0x4140 -#define CL_QCOM_TILED_P010_UV 0x4141 - - -#define CL_QCOM_TP10 0x4145 -#define CL_QCOM_TP10_Y 0x4146 -#define CL_QCOM_TP10_UV 0x4147 - -#define CL_QCOM_TILED_TP10 0x4148 -#define CL_QCOM_TILED_TP10_Y 0x4149 -#define CL_QCOM_TILED_TP10_UV 0x414A - -/********************************* -* cl_qcom_compressed_image extension -*********************************/ - -// Extended flag for creating/querying QCOM non-planar compressed images -#define CL_MEM_COMPRESSED_IMAGE_QCOM (1<<27) - -// Extended image format -// cl_channel_order -#define CL_QCOM_COMPRESSED_RGBA 0x4130 -#define CL_QCOM_COMPRESSED_RGBx 0x4131 - -#define CL_QCOM_COMPRESSED_NV12_Y 0x413A -#define CL_QCOM_COMPRESSED_NV12_UV 0x413B - -#define CL_QCOM_COMPRESSED_P010 0x4142 -#define CL_QCOM_COMPRESSED_P010_Y 0x4143 -#define CL_QCOM_COMPRESSED_P010_UV 0x4144 - -#define CL_QCOM_COMPRESSED_TP10 0x414B -#define CL_QCOM_COMPRESSED_TP10_Y 0x414C -#define CL_QCOM_COMPRESSED_TP10_UV 0x414D - -#define CL_QCOM_COMPRESSED_NV12_4R 0x414F -#define CL_QCOM_COMPRESSED_NV12_4R_Y 0x4150 -#define CL_QCOM_COMPRESSED_NV12_4R_UV 0x4151 -/********************************* -* cl_qcom_compressed_yuv_image_read extension -*********************************/ - -// Extended flag for creating/querying QCOM compressed images -#define CL_MEM_COMPRESSED_YUV_IMAGE_QCOM (1<<28) - -// Extended image format -#define CL_QCOM_COMPRESSED_NV12 0x10C4 - -// Extended flag for setting ION buffer allocation type -#define CL_MEM_ION_HOST_PTR_COMPRESSED_YUV_QCOM 0x40CD -#define CL_MEM_ION_HOST_PTR_PROTECTED_COMPRESSED_YUV_QCOM 0x40CE - -/********************************* -* cl_qcom_accelerated_image_ops -*********************************/ -#define CL_MEM_OBJECT_WEIGHT_IMAGE_QCOM 0x4110 -#define CL_DEVICE_HOF_MAX_NUM_PHASES_QCOM 0x4111 -#define CL_DEVICE_HOF_MAX_FILTER_SIZE_X_QCOM 0x4112 -#define CL_DEVICE_HOF_MAX_FILTER_SIZE_Y_QCOM 0x4113 -#define CL_DEVICE_BLOCK_MATCHING_MAX_REGION_SIZE_X_QCOM 0x4114 -#define CL_DEVICE_BLOCK_MATCHING_MAX_REGION_SIZE_Y_QCOM 0x4115 - -//Extended flag for specifying weight image type -#define CL_WEIGHT_IMAGE_SEPARABLE_QCOM (1<<0) - -// Box Filter -typedef struct _cl_box_filter_size_qcom -{ - // Width of box filter on X direction. - float box_filter_width; - - // Height of box filter on Y direction. - float box_filter_height; -} cl_box_filter_size_qcom; - -// HOF Weight Image Desc -typedef struct _cl_weight_desc_qcom -{ - /** Coordinate of the "center" point of the weight image, - based on the weight image's top-left corner as the origin. */ - size_t center_coord_x; - size_t center_coord_y; - cl_bitfield flags; -} cl_weight_desc_qcom; - -typedef struct _cl_weight_image_desc_qcom -{ - cl_image_desc image_desc; - cl_weight_desc_qcom weight_desc; -} cl_weight_image_desc_qcom; - -/************************************* - * cl_qcom_protected_context extension * - *************************************/ - -#define CL_CONTEXT_PROTECTED_QCOM 0x40C7 -#define CL_MEM_ION_HOST_PTR_PROTECTED_QCOM 0x40C8 - -/************************************* - * cl_qcom_priority_hint extension * - *************************************/ -#define CL_PRIORITY_HINT_NONE_QCOM 0 -typedef cl_uint cl_priority_hint; - -#define CL_CONTEXT_PRIORITY_HINT_QCOM 0x40C9 - -/*cl_priority_hint*/ -#define CL_PRIORITY_HINT_HIGH_QCOM 0x40CA -#define CL_PRIORITY_HINT_NORMAL_QCOM 0x40CB -#define CL_PRIORITY_HINT_LOW_QCOM 0x40CC - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_EXT_QCOM_H */ diff --git a/third_party/opencl/include/CL/cl_gl.h b/third_party/opencl/include/CL/cl_gl.h deleted file mode 100644 index 945daa83d7f712..00000000000000 --- a/third_party/opencl/include/CL/cl_gl.h +++ /dev/null @@ -1,167 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -#ifndef __OPENCL_CL_GL_H -#define __OPENCL_CL_GL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef cl_uint cl_gl_object_type; -typedef cl_uint cl_gl_texture_info; -typedef cl_uint cl_gl_platform_info; -typedef struct __GLsync *cl_GLsync; - -/* cl_gl_object_type = 0x2000 - 0x200F enum values are currently taken */ -#define CL_GL_OBJECT_BUFFER 0x2000 -#define CL_GL_OBJECT_TEXTURE2D 0x2001 -#define CL_GL_OBJECT_TEXTURE3D 0x2002 -#define CL_GL_OBJECT_RENDERBUFFER 0x2003 -#define CL_GL_OBJECT_TEXTURE2D_ARRAY 0x200E -#define CL_GL_OBJECT_TEXTURE1D 0x200F -#define CL_GL_OBJECT_TEXTURE1D_ARRAY 0x2010 -#define CL_GL_OBJECT_TEXTURE_BUFFER 0x2011 - -/* cl_gl_texture_info */ -#define CL_GL_TEXTURE_TARGET 0x2004 -#define CL_GL_MIPMAP_LEVEL 0x2005 -#define CL_GL_NUM_SAMPLES 0x2012 - - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* bufobj */, - int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLRenderbuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* renderbuffer */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLObjectInfo(cl_mem /* memobj */, - cl_gl_object_type * /* gl_object_type */, - cl_GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLTextureInfo(cl_mem /* memobj */, - cl_gl_texture_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - - -/* Deprecated OpenCL 1.1 APIs */ -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL -clCreateFromGLTexture2D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL -clCreateFromGLTexture3D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -/* cl_khr_gl_sharing extension */ - -#define cl_khr_gl_sharing 1 - -typedef cl_uint cl_gl_context_info; - -/* Additional Error Codes */ -#define CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR -1000 - -/* cl_gl_context_info */ -#define CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR 0x2006 -#define CL_DEVICES_FOR_GL_CONTEXT_KHR 0x2007 - -/* Additional cl_context_properties */ -#define CL_GL_CONTEXT_KHR 0x2008 -#define CL_EGL_DISPLAY_KHR 0x2009 -#define CL_GLX_DISPLAY_KHR 0x200A -#define CL_WGL_HDC_KHR 0x200B -#define CL_CGL_SHAREGROUP_KHR 0x200C - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLContextInfoKHR(const cl_context_properties * /* properties */, - cl_gl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetGLContextInfoKHR_fn)( - const cl_context_properties * properties, - cl_gl_context_info param_name, - size_t param_value_size, - void * param_value, - size_t * param_value_size_ret); - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_H */ diff --git a/third_party/opencl/include/CL/cl_gl_ext.h b/third_party/opencl/include/CL/cl_gl_ext.h deleted file mode 100644 index e3c14c6408c441..00000000000000 --- a/third_party/opencl/include/CL/cl_gl_ext.h +++ /dev/null @@ -1,74 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -/* cl_gl_ext.h contains vendor (non-KHR) OpenCL extensions which have */ -/* OpenGL dependencies. */ - -#ifndef __OPENCL_CL_GL_EXT_H -#define __OPENCL_CL_GL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include -#else - #include -#endif - -/* - * For each extension, follow this template - * cl_VEN_extname extension */ -/* #define cl_VEN_extname 1 - * ... define new types, if any - * ... define new tokens, if any - * ... define new APIs, if any - * - * If you need GLtypes here, mirror them with a cl_GLtype, rather than including a GL header - * This allows us to avoid having to decide whether to include GL headers or GLES here. - */ - -/* - * cl_khr_gl_event extension - * See section 9.9 in the OpenCL 1.1 spec for more information - */ -#define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateEventFromGLsyncKHR(cl_context /* context */, - cl_GLsync /* cl_GLsync */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_EXT_H */ diff --git a/third_party/opencl/include/CL/cl_platform.h b/third_party/opencl/include/CL/cl_platform.h deleted file mode 100644 index 4e334a2918390d..00000000000000 --- a/third_party/opencl/include/CL/cl_platform.h +++ /dev/null @@ -1,1333 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11803 $ on $Date: 2010-06-25 10:02:12 -0700 (Fri, 25 Jun 2010) $ */ - -#ifndef __CL_PLATFORM_H -#define __CL_PLATFORM_H - -#ifdef __APPLE__ - /* Contains #defines for AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER below */ - #include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_WIN32) - #define CL_API_ENTRY - #define CL_API_CALL __stdcall - #define CL_CALLBACK __stdcall -#else - #define CL_API_ENTRY - #define CL_API_CALL - #define CL_CALLBACK -#endif - -/* - * Deprecation flags refer to the last version of the header in which the - * feature was not deprecated. - * - * E.g. VERSION_1_1_DEPRECATED means the feature is present in 1.1 without - * deprecation but is deprecated in versions later than 1.1. - */ - -#ifdef __APPLE__ - #define CL_EXTENSION_WEAK_LINK __attribute__((weak_import)) - #define CL_API_SUFFIX__VERSION_1_0 AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_0 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_API_SUFFIX__VERSION_1_1 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define GCL_API_SUFFIX__VERSION_1_1 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_7 - - #ifdef AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER - #define CL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER - #define GCL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_2 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_8 - #else - #warning This path should never happen outside of internal operating system development. AvailabilityMacros do not function correctly here! - #define CL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define GCL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_2 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #endif -#else - #define CL_EXTENSION_WEAK_LINK - #define CL_API_SUFFIX__VERSION_1_0 - #define CL_EXT_SUFFIX__VERSION_1_0 - #define CL_API_SUFFIX__VERSION_1_1 - #define CL_EXT_SUFFIX__VERSION_1_1 - #define CL_API_SUFFIX__VERSION_1_2 - #define CL_EXT_SUFFIX__VERSION_1_2 - #define CL_API_SUFFIX__VERSION_2_0 - #define CL_EXT_SUFFIX__VERSION_2_0 - #define CL_API_SUFFIX__VERSION_2_1 - #define CL_EXT_SUFFIX__VERSION_2_1 - - #ifdef __GNUC__ - #ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED __attribute__((deprecated)) - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_1_1_APIS - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED __attribute__((deprecated)) - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_1_2_APIS - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED __attribute__((deprecated)) - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_2_0_APIS - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED __attribute__((deprecated)) - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED - #endif - #elif _WIN32 - #ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED __declspec(deprecated) - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_1_1_APIS - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED __declspec(deprecated) - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_1_2_APIS - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED __declspec(deprecated) - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_2_0_APIS - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED __declspec(deprecated) - #endif - #else - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED - - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED - - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED - #endif -#endif - -#if (defined (_WIN32) && defined(_MSC_VER)) - -/* scalar types */ -typedef signed __int8 cl_char; -typedef unsigned __int8 cl_uchar; -typedef signed __int16 cl_short; -typedef unsigned __int16 cl_ushort; -typedef signed __int32 cl_int; -typedef unsigned __int32 cl_uint; -typedef signed __int64 cl_long; -typedef unsigned __int64 cl_ulong; - -typedef unsigned __int16 cl_half; -typedef float cl_float; -typedef double cl_double; - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 340282346638528859811704183484516925440.0f -#define CL_FLT_MIN 1.175494350822287507969e-38f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0 -#define CL_DBL_MIN 2.225073858507201383090e-308 -#define CL_DBL_EPSILON 2.220446049250313080847e-16 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#define CL_NAN (CL_INFINITY - CL_INFINITY) -#define CL_HUGE_VALF ((cl_float) 1e50) -#define CL_HUGE_VAL ((cl_double) 1e500) -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#else - -#include - -/* scalar types */ -typedef int8_t cl_char; -typedef uint8_t cl_uchar; -typedef int16_t cl_short __attribute__((aligned(2))); -typedef uint16_t cl_ushort __attribute__((aligned(2))); -typedef int32_t cl_int __attribute__((aligned(4))); -typedef uint32_t cl_uint __attribute__((aligned(4))); -typedef int64_t cl_long __attribute__((aligned(8))); -typedef uint64_t cl_ulong __attribute__((aligned(8))); - -typedef uint16_t cl_half __attribute__((aligned(2))); -typedef float cl_float __attribute__((aligned(4))); -typedef double cl_double __attribute__((aligned(8))); - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 0x1.fffffep127f -#define CL_FLT_MIN 0x1.0p-126f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 0x1.fffffffffffffp1023 -#define CL_DBL_MIN 0x1.0p-1022 -#define CL_DBL_EPSILON 0x1.0p-52 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#if defined( __GNUC__ ) - #define CL_HUGE_VALF __builtin_huge_valf() - #define CL_HUGE_VAL __builtin_huge_val() - #define CL_NAN __builtin_nanf( "" ) -#else - #define CL_HUGE_VALF ((cl_float) 1e50) - #define CL_HUGE_VAL ((cl_double) 1e500) - float nanf( const char * ); - #define CL_NAN nanf( "" ) -#endif -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#endif - -#include - -/* Mirror types to GL types. Mirror types allow us to avoid deciding which 87s to load based on whether we are using GL or GLES here. */ -typedef unsigned int cl_GLuint; -typedef int cl_GLint; -typedef unsigned int cl_GLenum; - -/* - * Vector types - * - * Note: OpenCL requires that all types be naturally aligned. - * This means that vector types must be naturally aligned. - * For example, a vector of four floats must be aligned to - * a 16 byte boundary (calculated as 4 * the natural 4-byte - * alignment of the float). The alignment qualifiers here - * will only function properly if your compiler supports them - * and if you don't actively work to defeat them. For example, - * in order for a cl_float4 to be 16 byte aligned in a struct, - * the start of the struct must itself be 16-byte aligned. - * - * Maintaining proper alignment is the user's responsibility. - */ - -/* Define basic vector types */ -#if defined( __VEC__ ) - #include /* may be omitted depending on compiler. AltiVec spec provides no way to detect whether the header is required. */ - typedef vector unsigned char __cl_uchar16; - typedef vector signed char __cl_char16; - typedef vector unsigned short __cl_ushort8; - typedef vector signed short __cl_short8; - typedef vector unsigned int __cl_uint4; - typedef vector signed int __cl_int4; - typedef vector float __cl_float4; - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_UINT4__ 1 - #define __CL_INT4__ 1 - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef float __cl_float4 __attribute__((vector_size(16))); - #else - typedef __m128 __cl_float4; - #endif - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE2__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar16 __attribute__((vector_size(16))); - typedef cl_char __cl_char16 __attribute__((vector_size(16))); - typedef cl_ushort __cl_ushort8 __attribute__((vector_size(16))); - typedef cl_short __cl_short8 __attribute__((vector_size(16))); - typedef cl_uint __cl_uint4 __attribute__((vector_size(16))); - typedef cl_int __cl_int4 __attribute__((vector_size(16))); - typedef cl_ulong __cl_ulong2 __attribute__((vector_size(16))); - typedef cl_long __cl_long2 __attribute__((vector_size(16))); - typedef cl_double __cl_double2 __attribute__((vector_size(16))); - #else - typedef __m128i __cl_uchar16; - typedef __m128i __cl_char16; - typedef __m128i __cl_ushort8; - typedef __m128i __cl_short8; - typedef __m128i __cl_uint4; - typedef __m128i __cl_int4; - typedef __m128i __cl_ulong2; - typedef __m128i __cl_long2; - typedef __m128d __cl_double2; - #endif - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_INT4__ 1 - #define __CL_UINT4__ 1 - #define __CL_ULONG2__ 1 - #define __CL_LONG2__ 1 - #define __CL_DOUBLE2__ 1 -#endif - -#if defined( __MMX__ ) - #include - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar8 __attribute__((vector_size(8))); - typedef cl_char __cl_char8 __attribute__((vector_size(8))); - typedef cl_ushort __cl_ushort4 __attribute__((vector_size(8))); - typedef cl_short __cl_short4 __attribute__((vector_size(8))); - typedef cl_uint __cl_uint2 __attribute__((vector_size(8))); - typedef cl_int __cl_int2 __attribute__((vector_size(8))); - typedef cl_ulong __cl_ulong1 __attribute__((vector_size(8))); - typedef cl_long __cl_long1 __attribute__((vector_size(8))); - typedef cl_float __cl_float2 __attribute__((vector_size(8))); - #else - typedef __m64 __cl_uchar8; - typedef __m64 __cl_char8; - typedef __m64 __cl_ushort4; - typedef __m64 __cl_short4; - typedef __m64 __cl_uint2; - typedef __m64 __cl_int2; - typedef __m64 __cl_ulong1; - typedef __m64 __cl_long1; - typedef __m64 __cl_float2; - #endif - #define __CL_UCHAR8__ 1 - #define __CL_CHAR8__ 1 - #define __CL_USHORT4__ 1 - #define __CL_SHORT4__ 1 - #define __CL_INT2__ 1 - #define __CL_UINT2__ 1 - #define __CL_ULONG1__ 1 - #define __CL_LONG1__ 1 - #define __CL_FLOAT2__ 1 -#endif - -#if defined( __AVX__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_float __cl_float8 __attribute__((vector_size(32))); - typedef cl_double __cl_double4 __attribute__((vector_size(32))); - #else - typedef __m256 __cl_float8; - typedef __m256d __cl_double4; - #endif - #define __CL_FLOAT8__ 1 - #define __CL_DOUBLE4__ 1 -#endif - -/* Define capabilities for anonymous struct members. */ -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) -#define __CL_HAS_ANON_STRUCT__ 1 -#define __CL_ANON_STRUCT__ __extension__ -#elif defined( _WIN32) && (_MSC_VER >= 1500) - /* Microsoft Developer Studio 2008 supports anonymous structs, but - * complains by default. */ -#define __CL_HAS_ANON_STRUCT__ 1 -#define __CL_ANON_STRUCT__ - /* Disable warning C4201: nonstandard extension used : nameless - * struct/union */ -#pragma warning( push ) -#pragma warning( disable : 4201 ) -#else -#define __CL_HAS_ANON_STRUCT__ 0 -#define __CL_ANON_STRUCT__ -#endif - -/* Define alignment keys */ -#if defined( __GNUC__ ) - #define CL_ALIGNED(_x) __attribute__ ((aligned(_x))) -#elif defined( _WIN32) && (_MSC_VER) - /* Alignment keys neutered on windows because MSVC can't swallow function arguments with alignment requirements */ - /* http://msdn.microsoft.com/en-us/library/373ak2y1%28VS.71%29.aspx */ - /* #include */ - /* #define CL_ALIGNED(_x) _CRT_ALIGN(_x) */ - #define CL_ALIGNED(_x) -#else - #warning Need to implement some method to align data here - #define CL_ALIGNED(_x) -#endif - -/* Indicate whether .xyzw, .s0123 and .hi.lo are supported */ -#if __CL_HAS_ANON_STRUCT__ - /* .xyzw and .s0123...{f|F} are supported */ - #define CL_HAS_NAMED_VECTOR_FIELDS 1 - /* .hi and .lo are supported */ - #define CL_HAS_HI_LO_VECTOR_FIELDS 1 -#endif - -/* Define cl_vector types */ - -/* ---- cl_charn ---- */ -typedef union -{ - cl_char CL_ALIGNED(2) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_char x, y; }; - __CL_ANON_STRUCT__ struct{ cl_char s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_char lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2; -#endif -}cl_char2; - -typedef union -{ - cl_char CL_ALIGNED(4) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_char2 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[2]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4; -#endif -}cl_char4; - -/* cl_char3 is identical in size, alignment and behavior to cl_char4. See section 6.1.5. */ -typedef cl_char4 cl_char3; - -typedef union -{ - cl_char CL_ALIGNED(8) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_char4 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[4]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[2]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8; -#endif -}cl_char8; - -typedef union -{ - cl_char CL_ALIGNED(16) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_char8 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[8]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[4]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8[2]; -#endif -#if defined( __CL_CHAR16__ ) - __cl_char16 v16; -#endif -}cl_char16; - - -/* ---- cl_ucharn ---- */ -typedef union -{ - cl_uchar CL_ALIGNED(2) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uchar x, y; }; - __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_uchar lo, hi; }; -#endif -#if defined( __cl_uchar2__) - __cl_uchar2 v2; -#endif -}cl_uchar2; - -typedef union -{ - cl_uchar CL_ALIGNED(4) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_uchar2 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[2]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4; -#endif -}cl_uchar4; - -/* cl_uchar3 is identical in size, alignment and behavior to cl_uchar4. See section 6.1.5. */ -typedef cl_uchar4 cl_uchar3; - -typedef union -{ - cl_uchar CL_ALIGNED(8) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_uchar4 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[4]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[2]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8; -#endif -}cl_uchar8; - -typedef union -{ - cl_uchar CL_ALIGNED(16) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_uchar8 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[8]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[4]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8[2]; -#endif -#if defined( __CL_UCHAR16__ ) - __cl_uchar16 v16; -#endif -}cl_uchar16; - - -/* ---- cl_shortn ---- */ -typedef union -{ - cl_short CL_ALIGNED(4) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_short x, y; }; - __CL_ANON_STRUCT__ struct{ cl_short s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_short lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2; -#endif -}cl_short2; - -typedef union -{ - cl_short CL_ALIGNED(8) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_short2 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[2]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4; -#endif -}cl_short4; - -/* cl_short3 is identical in size, alignment and behavior to cl_short4. See section 6.1.5. */ -typedef cl_short4 cl_short3; - -typedef union -{ - cl_short CL_ALIGNED(16) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_short4 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[4]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[2]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8; -#endif -}cl_short8; - -typedef union -{ - cl_short CL_ALIGNED(32) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_short8 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[8]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[4]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8[2]; -#endif -#if defined( __CL_SHORT16__ ) - __cl_short16 v16; -#endif -}cl_short16; - - -/* ---- cl_ushortn ---- */ -typedef union -{ - cl_ushort CL_ALIGNED(4) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ushort x, y; }; - __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_ushort lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2; -#endif -}cl_ushort2; - -typedef union -{ - cl_ushort CL_ALIGNED(8) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_ushort2 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[2]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4; -#endif -}cl_ushort4; - -/* cl_ushort3 is identical in size, alignment and behavior to cl_ushort4. See section 6.1.5. */ -typedef cl_ushort4 cl_ushort3; - -typedef union -{ - cl_ushort CL_ALIGNED(16) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_ushort4 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[4]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[2]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8; -#endif -}cl_ushort8; - -typedef union -{ - cl_ushort CL_ALIGNED(32) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_ushort8 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[8]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[4]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8[2]; -#endif -#if defined( __CL_USHORT16__ ) - __cl_ushort16 v16; -#endif -}cl_ushort16; - -/* ---- cl_intn ---- */ -typedef union -{ - cl_int CL_ALIGNED(8) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_int x, y; }; - __CL_ANON_STRUCT__ struct{ cl_int s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_int lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2; -#endif -}cl_int2; - -typedef union -{ - cl_int CL_ALIGNED(16) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_int2 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[2]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4; -#endif -}cl_int4; - -/* cl_int3 is identical in size, alignment and behavior to cl_int4. See section 6.1.5. */ -typedef cl_int4 cl_int3; - -typedef union -{ - cl_int CL_ALIGNED(32) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_int4 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[4]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[2]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8; -#endif -}cl_int8; - -typedef union -{ - cl_int CL_ALIGNED(64) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_int8 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[8]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[4]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8[2]; -#endif -#if defined( __CL_INT16__ ) - __cl_int16 v16; -#endif -}cl_int16; - - -/* ---- cl_uintn ---- */ -typedef union -{ - cl_uint CL_ALIGNED(8) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uint x, y; }; - __CL_ANON_STRUCT__ struct{ cl_uint s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_uint lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2; -#endif -}cl_uint2; - -typedef union -{ - cl_uint CL_ALIGNED(16) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_uint2 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[2]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4; -#endif -}cl_uint4; - -/* cl_uint3 is identical in size, alignment and behavior to cl_uint4. See section 6.1.5. */ -typedef cl_uint4 cl_uint3; - -typedef union -{ - cl_uint CL_ALIGNED(32) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_uint4 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[4]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[2]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8; -#endif -}cl_uint8; - -typedef union -{ - cl_uint CL_ALIGNED(64) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_uint8 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[8]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[4]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8[2]; -#endif -#if defined( __CL_UINT16__ ) - __cl_uint16 v16; -#endif -}cl_uint16; - -/* ---- cl_longn ---- */ -typedef union -{ - cl_long CL_ALIGNED(16) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_long x, y; }; - __CL_ANON_STRUCT__ struct{ cl_long s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_long lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2; -#endif -}cl_long2; - -typedef union -{ - cl_long CL_ALIGNED(32) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_long2 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[2]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4; -#endif -}cl_long4; - -/* cl_long3 is identical in size, alignment and behavior to cl_long4. See section 6.1.5. */ -typedef cl_long4 cl_long3; - -typedef union -{ - cl_long CL_ALIGNED(64) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_long4 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[4]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[2]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8; -#endif -}cl_long8; - -typedef union -{ - cl_long CL_ALIGNED(128) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_long8 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[8]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[4]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8[2]; -#endif -#if defined( __CL_LONG16__ ) - __cl_long16 v16; -#endif -}cl_long16; - - -/* ---- cl_ulongn ---- */ -typedef union -{ - cl_ulong CL_ALIGNED(16) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ulong x, y; }; - __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_ulong lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2; -#endif -}cl_ulong2; - -typedef union -{ - cl_ulong CL_ALIGNED(32) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_ulong2 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[2]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4; -#endif -}cl_ulong4; - -/* cl_ulong3 is identical in size, alignment and behavior to cl_ulong4. See section 6.1.5. */ -typedef cl_ulong4 cl_ulong3; - -typedef union -{ - cl_ulong CL_ALIGNED(64) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_ulong4 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[4]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[2]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8; -#endif -}cl_ulong8; - -typedef union -{ - cl_ulong CL_ALIGNED(128) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_ulong8 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[8]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[4]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8[2]; -#endif -#if defined( __CL_ULONG16__ ) - __cl_ulong16 v16; -#endif -}cl_ulong16; - - -/* --- cl_floatn ---- */ - -typedef union -{ - cl_float CL_ALIGNED(8) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_float x, y; }; - __CL_ANON_STRUCT__ struct{ cl_float s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_float lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2; -#endif -}cl_float2; - -typedef union -{ - cl_float CL_ALIGNED(16) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_float2 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[2]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4; -#endif -}cl_float4; - -/* cl_float3 is identical in size, alignment and behavior to cl_float4. See section 6.1.5. */ -typedef cl_float4 cl_float3; - -typedef union -{ - cl_float CL_ALIGNED(32) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_float4 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[4]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[2]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8; -#endif -}cl_float8; - -typedef union -{ - cl_float CL_ALIGNED(64) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_float8 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[8]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[4]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8[2]; -#endif -#if defined( __CL_FLOAT16__ ) - __cl_float16 v16; -#endif -}cl_float16; - -/* --- cl_doublen ---- */ - -typedef union -{ - cl_double CL_ALIGNED(16) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_double x, y; }; - __CL_ANON_STRUCT__ struct{ cl_double s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_double lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2; -#endif -}cl_double2; - -typedef union -{ - cl_double CL_ALIGNED(32) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_double2 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[2]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4; -#endif -}cl_double4; - -/* cl_double3 is identical in size, alignment and behavior to cl_double4. See section 6.1.5. */ -typedef cl_double4 cl_double3; - -typedef union -{ - cl_double CL_ALIGNED(64) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_double4 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[4]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[2]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8; -#endif -}cl_double8; - -typedef union -{ - cl_double CL_ALIGNED(128) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_double8 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[8]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[4]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8[2]; -#endif -#if defined( __CL_DOUBLE16__ ) - __cl_double16 v16; -#endif -}cl_double16; - -/* Macro to facilitate debugging - * Usage: - * Place CL_PROGRAM_STRING_DEBUG_INFO on the line before the first line of your source. - * The first line ends with: CL_PROGRAM_STRING_DEBUG_INFO \" - * Each line thereafter of OpenCL C source must end with: \n\ - * The last line ends in "; - * - * Example: - * - * const char *my_program = CL_PROGRAM_STRING_DEBUG_INFO "\ - * kernel void foo( int a, float * b ) \n\ - * { \n\ - * // my comment \n\ - * *b[ get_global_id(0)] = a; \n\ - * } \n\ - * "; - * - * This should correctly set up the line, (column) and file information for your source - * string so you can do source level debugging. - */ -#define __CL_STRINGIFY( _x ) # _x -#define _CL_STRINGIFY( _x ) __CL_STRINGIFY( _x ) -#define CL_PROGRAM_STRING_DEBUG_INFO "#line " _CL_STRINGIFY(__LINE__) " \"" __FILE__ "\" \n\n" - -#ifdef __cplusplus -} -#endif - -#undef __CL_HAS_ANON_STRUCT__ -#undef __CL_ANON_STRUCT__ -#if defined( _WIN32) && (_MSC_VER >= 1500) -#pragma warning( pop ) -#endif - -#endif /* __CL_PLATFORM_H */ diff --git a/third_party/opencl/include/CL/opencl.h b/third_party/opencl/include/CL/opencl.h deleted file mode 100644 index 9855cd75e7da06..00000000000000 --- a/third_party/opencl/include/CL/opencl.h +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_H -#define __OPENCL_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - -#include -#include -#include -#include - -#else - -#include -#include -#include -#include - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_H */ - diff --git a/third_party/qrcode/QrCode.cc b/third_party/qrcode/QrCode.cc deleted file mode 100644 index b9de86215e204a..00000000000000 --- a/third_party/qrcode/QrCode.cc +++ /dev/null @@ -1,862 +0,0 @@ -/* - * QR Code generator library (C++) - * - * Copyright (c) Project Nayuki. (MIT License) - * https://www.nayuki.io/page/qr-code-generator-library - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - The Software is provided "as is", without warranty of any kind, express or - * implied, including but not limited to the warranties of merchantability, - * fitness for a particular purpose and noninfringement. In no event shall the - * authors or copyright holders be liable for any claim, damages or other - * liability, whether in an action of contract, tort or otherwise, arising from, - * out of or in connection with the Software or the use or other dealings in the - * Software. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "QrCode.hpp" - -using std::int8_t; -using std::uint8_t; -using std::size_t; -using std::vector; - - -namespace qrcodegen { - -QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) : - modeBits(mode) { - numBitsCharCount[0] = cc0; - numBitsCharCount[1] = cc1; - numBitsCharCount[2] = cc2; -} - - -int QrSegment::Mode::getModeBits() const { - return modeBits; -} - - -int QrSegment::Mode::numCharCountBits(int ver) const { - return numBitsCharCount[(ver + 7) / 17]; -} - - -const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14); -const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13); -const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16); -const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12); -const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0); - - -QrSegment QrSegment::makeBytes(const vector &data) { - if (data.size() > static_cast(INT_MAX)) - throw std::length_error("Data too long"); - BitBuffer bb; - for (uint8_t b : data) - bb.appendBits(b, 8); - return QrSegment(Mode::BYTE, static_cast(data.size()), std::move(bb)); -} - - -QrSegment QrSegment::makeNumeric(const char *digits) { - BitBuffer bb; - int accumData = 0; - int accumCount = 0; - int charCount = 0; - for (; *digits != '\0'; digits++, charCount++) { - char c = *digits; - if (c < '0' || c > '9') - throw std::domain_error("String contains non-numeric characters"); - accumData = accumData * 10 + (c - '0'); - accumCount++; - if (accumCount == 3) { - bb.appendBits(static_cast(accumData), 10); - accumData = 0; - accumCount = 0; - } - } - if (accumCount > 0) // 1 or 2 digits remaining - bb.appendBits(static_cast(accumData), accumCount * 3 + 1); - return QrSegment(Mode::NUMERIC, charCount, std::move(bb)); -} - - -QrSegment QrSegment::makeAlphanumeric(const char *text) { - BitBuffer bb; - int accumData = 0; - int accumCount = 0; - int charCount = 0; - for (; *text != '\0'; text++, charCount++) { - const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text); - if (temp == nullptr) - throw std::domain_error("String contains unencodable characters in alphanumeric mode"); - accumData = accumData * 45 + static_cast(temp - ALPHANUMERIC_CHARSET); - accumCount++; - if (accumCount == 2) { - bb.appendBits(static_cast(accumData), 11); - accumData = 0; - accumCount = 0; - } - } - if (accumCount > 0) // 1 character remaining - bb.appendBits(static_cast(accumData), 6); - return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb)); -} - - -vector QrSegment::makeSegments(const char *text) { - // Select the most efficient segment encoding automatically - vector result; - if (*text == '\0'); // Leave result empty - else if (isNumeric(text)) - result.push_back(makeNumeric(text)); - else if (isAlphanumeric(text)) - result.push_back(makeAlphanumeric(text)); - else { - vector bytes; - for (; *text != '\0'; text++) - bytes.push_back(static_cast(*text)); - result.push_back(makeBytes(bytes)); - } - return result; -} - - -QrSegment QrSegment::makeEci(long assignVal) { - BitBuffer bb; - if (assignVal < 0) - throw std::domain_error("ECI assignment value out of range"); - else if (assignVal < (1 << 7)) - bb.appendBits(static_cast(assignVal), 8); - else if (assignVal < (1 << 14)) { - bb.appendBits(2, 2); - bb.appendBits(static_cast(assignVal), 14); - } else if (assignVal < 1000000L) { - bb.appendBits(6, 3); - bb.appendBits(static_cast(assignVal), 21); - } else - throw std::domain_error("ECI assignment value out of range"); - return QrSegment(Mode::ECI, 0, std::move(bb)); -} - - -QrSegment::QrSegment(Mode md, int numCh, const std::vector &dt) : - mode(md), - numChars(numCh), - data(dt) { - if (numCh < 0) - throw std::domain_error("Invalid value"); -} - - -QrSegment::QrSegment(Mode md, int numCh, std::vector &&dt) : - mode(md), - numChars(numCh), - data(std::move(dt)) { - if (numCh < 0) - throw std::domain_error("Invalid value"); -} - - -int QrSegment::getTotalBits(const vector &segs, int version) { - int result = 0; - for (const QrSegment &seg : segs) { - int ccbits = seg.mode.numCharCountBits(version); - if (seg.numChars >= (1L << ccbits)) - return -1; // The segment's length doesn't fit the field's bit width - if (4 + ccbits > INT_MAX - result) - return -1; // The sum will overflow an int type - result += 4 + ccbits; - if (seg.data.size() > static_cast(INT_MAX - result)) - return -1; // The sum will overflow an int type - result += static_cast(seg.data.size()); - } - return result; -} - - -bool QrSegment::isAlphanumeric(const char *text) { - for (; *text != '\0'; text++) { - if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr) - return false; - } - return true; -} - - -bool QrSegment::isNumeric(const char *text) { - for (; *text != '\0'; text++) { - char c = *text; - if (c < '0' || c > '9') - return false; - } - return true; -} - - -QrSegment::Mode QrSegment::getMode() const { - return mode; -} - - -int QrSegment::getNumChars() const { - return numChars; -} - - -const std::vector &QrSegment::getData() const { - return data; -} - - -const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; - - - -int QrCode::getFormatBits(Ecc ecl) { - switch (ecl) { - case Ecc::LOW : return 1; - case Ecc::MEDIUM : return 0; - case Ecc::QUARTILE: return 3; - case Ecc::HIGH : return 2; - default: throw std::logic_error("Assertion error"); - } -} - - -QrCode QrCode::encodeText(const char *text, Ecc ecl) { - vector segs = QrSegment::makeSegments(text); - return encodeSegments(segs, ecl); -} - - -QrCode QrCode::encodeBinary(const vector &data, Ecc ecl) { - vector segs{QrSegment::makeBytes(data)}; - return encodeSegments(segs, ecl); -} - - -QrCode QrCode::encodeSegments(const vector &segs, Ecc ecl, - int minVersion, int maxVersion, int mask, bool boostEcl) { - if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) - throw std::invalid_argument("Invalid value"); - - // Find the minimal version number to use - int version, dataUsedBits; - for (version = minVersion; ; version++) { - int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available - dataUsedBits = QrSegment::getTotalBits(segs, version); - if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) - break; // This version number is found to be suitable - if (version >= maxVersion) { // All versions in the range could not fit the given data - std::ostringstream sb; - if (dataUsedBits == -1) - sb << "Segment too long"; - else { - sb << "Data length = " << dataUsedBits << " bits, "; - sb << "Max capacity = " << dataCapacityBits << " bits"; - } - throw data_too_long(sb.str()); - } - } - if (dataUsedBits == -1) - throw std::logic_error("Assertion error"); - - // Increase the error correction level while the data still fits in the current version number - for (Ecc newEcl : vector{Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high - if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) - ecl = newEcl; - } - - // Concatenate all segments to create the data bit string - BitBuffer bb; - for (const QrSegment &seg : segs) { - bb.appendBits(static_cast(seg.getMode().getModeBits()), 4); - bb.appendBits(static_cast(seg.getNumChars()), seg.getMode().numCharCountBits(version)); - bb.insert(bb.end(), seg.getData().begin(), seg.getData().end()); - } - if (bb.size() != static_cast(dataUsedBits)) - throw std::logic_error("Assertion error"); - - // Add terminator and pad up to a byte if applicable - size_t dataCapacityBits = static_cast(getNumDataCodewords(version, ecl)) * 8; - if (bb.size() > dataCapacityBits) - throw std::logic_error("Assertion error"); - bb.appendBits(0, std::min(4, static_cast(dataCapacityBits - bb.size()))); - bb.appendBits(0, (8 - static_cast(bb.size() % 8)) % 8); - if (bb.size() % 8 != 0) - throw std::logic_error("Assertion error"); - - // Pad with alternating bytes until data capacity is reached - for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) - bb.appendBits(padByte, 8); - - // Pack bits into bytes in big endian - vector dataCodewords(bb.size() / 8); - for (size_t i = 0; i < bb.size(); i++) - dataCodewords[i >> 3] |= (bb.at(i) ? 1 : 0) << (7 - (i & 7)); - - // Create the QR Code object - return QrCode(version, ecl, dataCodewords, mask); -} - - -QrCode::QrCode(int ver, Ecc ecl, const vector &dataCodewords, int msk) : - // Initialize fields and check arguments - version(ver), - errorCorrectionLevel(ecl) { - if (ver < MIN_VERSION || ver > MAX_VERSION) - throw std::domain_error("Version value out of range"); - if (msk < -1 || msk > 7) - throw std::domain_error("Mask value out of range"); - size = ver * 4 + 17; - size_t sz = static_cast(size); - modules = vector >(sz, vector(sz)); // Initially all white - isFunction = vector >(sz, vector(sz)); - - // Compute ECC, draw modules - drawFunctionPatterns(); - const vector allCodewords = addEccAndInterleave(dataCodewords); - drawCodewords(allCodewords); - - // Do masking - if (msk == -1) { // Automatically choose best mask - long minPenalty = LONG_MAX; - for (int i = 0; i < 8; i++) { - applyMask(i); - drawFormatBits(i); - long penalty = getPenaltyScore(); - if (penalty < minPenalty) { - msk = i; - minPenalty = penalty; - } - applyMask(i); // Undoes the mask due to XOR - } - } - if (msk < 0 || msk > 7) - throw std::logic_error("Assertion error"); - this->mask = msk; - applyMask(msk); // Apply the final choice of mask - drawFormatBits(msk); // Overwrite old format bits - - isFunction.clear(); - isFunction.shrink_to_fit(); -} - - -int QrCode::getVersion() const { - return version; -} - - -int QrCode::getSize() const { - return size; -} - - -QrCode::Ecc QrCode::getErrorCorrectionLevel() const { - return errorCorrectionLevel; -} - - -int QrCode::getMask() const { - return mask; -} - - -bool QrCode::getModule(int x, int y) const { - return 0 <= x && x < size && 0 <= y && y < size && module(x, y); -} - - -std::string QrCode::toSvgString(int border) const { - if (border < 0) - throw std::domain_error("Border must be non-negative"); - if (border > INT_MAX / 2 || border * 2 > INT_MAX - size) - throw std::overflow_error("Border too large"); - - std::ostringstream sb; - sb << "\n"; - sb << "\n"; - sb << "\n"; - sb << "\t\n"; - sb << "\t\n"; - sb << "\n"; - return sb.str(); -} - - -void QrCode::drawFunctionPatterns() { - // Draw horizontal and vertical timing patterns - for (int i = 0; i < size; i++) { - setFunctionModule(6, i, i % 2 == 0); - setFunctionModule(i, 6, i % 2 == 0); - } - - // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) - drawFinderPattern(3, 3); - drawFinderPattern(size - 4, 3); - drawFinderPattern(3, size - 4); - - // Draw numerous alignment patterns - const vector alignPatPos = getAlignmentPatternPositions(); - size_t numAlign = alignPatPos.size(); - for (size_t i = 0; i < numAlign; i++) { - for (size_t j = 0; j < numAlign; j++) { - // Don't draw on the three finder corners - if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) - drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j)); - } - } - - // Draw configuration data - drawFormatBits(0); // Dummy mask value; overwritten later in the constructor - drawVersion(); -} - - -void QrCode::drawFormatBits(int msk) { - // Calculate error correction code and pack bits - int data = getFormatBits(errorCorrectionLevel) << 3 | msk; // errCorrLvl is uint2, msk is uint3 - int rem = data; - for (int i = 0; i < 10; i++) - rem = (rem << 1) ^ ((rem >> 9) * 0x537); - int bits = (data << 10 | rem) ^ 0x5412; // uint15 - if (bits >> 15 != 0) - throw std::logic_error("Assertion error"); - - // Draw first copy - for (int i = 0; i <= 5; i++) - setFunctionModule(8, i, getBit(bits, i)); - setFunctionModule(8, 7, getBit(bits, 6)); - setFunctionModule(8, 8, getBit(bits, 7)); - setFunctionModule(7, 8, getBit(bits, 8)); - for (int i = 9; i < 15; i++) - setFunctionModule(14 - i, 8, getBit(bits, i)); - - // Draw second copy - for (int i = 0; i < 8; i++) - setFunctionModule(size - 1 - i, 8, getBit(bits, i)); - for (int i = 8; i < 15; i++) - setFunctionModule(8, size - 15 + i, getBit(bits, i)); - setFunctionModule(8, size - 8, true); // Always black -} - - -void QrCode::drawVersion() { - if (version < 7) - return; - - // Calculate error correction code and pack bits - int rem = version; // version is uint6, in the range [7, 40] - for (int i = 0; i < 12; i++) - rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); - long bits = static_cast(version) << 12 | rem; // uint18 - if (bits >> 18 != 0) - throw std::logic_error("Assertion error"); - - // Draw two copies - for (int i = 0; i < 18; i++) { - bool bit = getBit(bits, i); - int a = size - 11 + i % 3; - int b = i / 3; - setFunctionModule(a, b, bit); - setFunctionModule(b, a, bit); - } -} - - -void QrCode::drawFinderPattern(int x, int y) { - for (int dy = -4; dy <= 4; dy++) { - for (int dx = -4; dx <= 4; dx++) { - int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm - int xx = x + dx, yy = y + dy; - if (0 <= xx && xx < size && 0 <= yy && yy < size) - setFunctionModule(xx, yy, dist != 2 && dist != 4); - } - } -} - - -void QrCode::drawAlignmentPattern(int x, int y) { - for (int dy = -2; dy <= 2; dy++) { - for (int dx = -2; dx <= 2; dx++) - setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1); - } -} - - -void QrCode::setFunctionModule(int x, int y, bool isBlack) { - size_t ux = static_cast(x); - size_t uy = static_cast(y); - modules .at(uy).at(ux) = isBlack; - isFunction.at(uy).at(ux) = true; -} - - -bool QrCode::module(int x, int y) const { - return modules.at(static_cast(y)).at(static_cast(x)); -} - - -vector QrCode::addEccAndInterleave(const vector &data) const { - if (data.size() != static_cast(getNumDataCodewords(version, errorCorrectionLevel))) - throw std::invalid_argument("Invalid argument"); - - // Calculate parameter numbers - int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast(errorCorrectionLevel)][version]; - int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast(errorCorrectionLevel)][version]; - int rawCodewords = getNumRawDataModules(version) / 8; - int numShortBlocks = numBlocks - rawCodewords % numBlocks; - int shortBlockLen = rawCodewords / numBlocks; - - // Split data into blocks and append ECC to each block - vector > blocks; - const vector rsDiv = reedSolomonComputeDivisor(blockEccLen); - for (int i = 0, k = 0; i < numBlocks; i++) { - vector dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1))); - k += static_cast(dat.size()); - const vector ecc = reedSolomonComputeRemainder(dat, rsDiv); - if (i < numShortBlocks) - dat.push_back(0); - dat.insert(dat.end(), ecc.cbegin(), ecc.cend()); - blocks.push_back(std::move(dat)); - } - - // Interleave (not concatenate) the bytes from every block into a single sequence - vector result; - for (size_t i = 0; i < blocks.at(0).size(); i++) { - for (size_t j = 0; j < blocks.size(); j++) { - // Skip the padding byte in short blocks - if (i != static_cast(shortBlockLen - blockEccLen) || j >= static_cast(numShortBlocks)) - result.push_back(blocks.at(j).at(i)); - } - } - if (result.size() != static_cast(rawCodewords)) - throw std::logic_error("Assertion error"); - return result; -} - - -void QrCode::drawCodewords(const vector &data) { - if (data.size() != static_cast(getNumRawDataModules(version) / 8)) - throw std::invalid_argument("Invalid argument"); - - size_t i = 0; // Bit index into the data - // Do the funny zigzag scan - for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair - if (right == 6) - right = 5; - for (int vert = 0; vert < size; vert++) { // Vertical counter - for (int j = 0; j < 2; j++) { - size_t x = static_cast(right - j); // Actual x coordinate - bool upward = ((right + 1) & 2) == 0; - size_t y = static_cast(upward ? size - 1 - vert : vert); // Actual y coordinate - if (!isFunction.at(y).at(x) && i < data.size() * 8) { - modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast(i & 7)); - i++; - } - // If this QR Code has any remainder bits (0 to 7), they were assigned as - // 0/false/white by the constructor and are left unchanged by this method - } - } - } - if (i != data.size() * 8) - throw std::logic_error("Assertion error"); -} - - -void QrCode::applyMask(int msk) { - if (msk < 0 || msk > 7) - throw std::domain_error("Mask value out of range"); - size_t sz = static_cast(size); - for (size_t y = 0; y < sz; y++) { - for (size_t x = 0; x < sz; x++) { - bool invert; - switch (msk) { - case 0: invert = (x + y) % 2 == 0; break; - case 1: invert = y % 2 == 0; break; - case 2: invert = x % 3 == 0; break; - case 3: invert = (x + y) % 3 == 0; break; - case 4: invert = (x / 3 + y / 2) % 2 == 0; break; - case 5: invert = x * y % 2 + x * y % 3 == 0; break; - case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; - case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; - default: throw std::logic_error("Assertion error"); - } - modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x)); - } - } -} - - -long QrCode::getPenaltyScore() const { - long result = 0; - - // Adjacent modules in row having same color, and finder-like patterns - for (int y = 0; y < size; y++) { - bool runColor = false; - int runX = 0; - std::array runHistory = {}; - for (int x = 0; x < size; x++) { - if (module(x, y) == runColor) { - runX++; - if (runX == 5) - result += PENALTY_N1; - else if (runX > 5) - result++; - } else { - finderPenaltyAddHistory(runX, runHistory); - if (!runColor) - result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; - runColor = module(x, y); - runX = 1; - } - } - result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; - } - // Adjacent modules in column having same color, and finder-like patterns - for (int x = 0; x < size; x++) { - bool runColor = false; - int runY = 0; - std::array runHistory = {}; - for (int y = 0; y < size; y++) { - if (module(x, y) == runColor) { - runY++; - if (runY == 5) - result += PENALTY_N1; - else if (runY > 5) - result++; - } else { - finderPenaltyAddHistory(runY, runHistory); - if (!runColor) - result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; - runColor = module(x, y); - runY = 1; - } - } - result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; - } - - // 2*2 blocks of modules having same color - for (int y = 0; y < size - 1; y++) { - for (int x = 0; x < size - 1; x++) { - bool color = module(x, y); - if ( color == module(x + 1, y) && - color == module(x, y + 1) && - color == module(x + 1, y + 1)) - result += PENALTY_N2; - } - } - - // Balance of black and white modules - int black = 0; - for (const vector &row : modules) { - for (bool color : row) { - if (color) - black++; - } - } - int total = size * size; // Note that size is odd, so black/total != 1/2 - // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)% - int k = static_cast((std::abs(black * 20L - total * 10L) + total - 1) / total) - 1; - result += k * PENALTY_N4; - return result; -} - - -vector QrCode::getAlignmentPatternPositions() const { - if (version == 1) - return vector(); - else { - int numAlign = version / 7 + 2; - int step = (version == 32) ? 26 : - (version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2; - vector result; - for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step) - result.insert(result.begin(), pos); - result.insert(result.begin(), 6); - return result; - } -} - - -int QrCode::getNumRawDataModules(int ver) { - if (ver < MIN_VERSION || ver > MAX_VERSION) - throw std::domain_error("Version number out of range"); - int result = (16 * ver + 128) * ver + 64; - if (ver >= 2) { - int numAlign = ver / 7 + 2; - result -= (25 * numAlign - 10) * numAlign - 55; - if (ver >= 7) - result -= 36; - } - if (!(208 <= result && result <= 29648)) - throw std::logic_error("Assertion error"); - return result; -} - - -int QrCode::getNumDataCodewords(int ver, Ecc ecl) { - return getNumRawDataModules(ver) / 8 - - ECC_CODEWORDS_PER_BLOCK [static_cast(ecl)][ver] - * NUM_ERROR_CORRECTION_BLOCKS[static_cast(ecl)][ver]; -} - - -vector QrCode::reedSolomonComputeDivisor(int degree) { - if (degree < 1 || degree > 255) - throw std::domain_error("Degree out of range"); - // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. - // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. - vector result(static_cast(degree)); - result.at(result.size() - 1) = 1; // Start off with the monomial x^0 - - // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), - // and drop the highest monomial term which is always 1x^degree. - // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). - uint8_t root = 1; - for (int i = 0; i < degree; i++) { - // Multiply the current product by (x - r^i) - for (size_t j = 0; j < result.size(); j++) { - result.at(j) = reedSolomonMultiply(result.at(j), root); - if (j + 1 < result.size()) - result.at(j) ^= result.at(j + 1); - } - root = reedSolomonMultiply(root, 0x02); - } - return result; -} - - -vector QrCode::reedSolomonComputeRemainder(const vector &data, const vector &divisor) { - vector result(divisor.size()); - for (uint8_t b : data) { // Polynomial division - uint8_t factor = b ^ result.at(0); - result.erase(result.begin()); - result.push_back(0); - for (size_t i = 0; i < result.size(); i++) - result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor); - } - return result; -} - - -uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) { - // Russian peasant multiplication - int z = 0; - for (int i = 7; i >= 0; i--) { - z = (z << 1) ^ ((z >> 7) * 0x11D); - z ^= ((y >> i) & 1) * x; - } - if (z >> 8 != 0) - throw std::logic_error("Assertion error"); - return static_cast(z); -} - - -int QrCode::finderPenaltyCountPatterns(const std::array &runHistory) const { - int n = runHistory.at(1); - if (n > size * 3) - throw std::logic_error("Assertion error"); - bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n; - return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0) - + (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0); -} - - -int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array &runHistory) const { - if (currentRunColor) { // Terminate black run - finderPenaltyAddHistory(currentRunLength, runHistory); - currentRunLength = 0; - } - currentRunLength += size; // Add white border to final run - finderPenaltyAddHistory(currentRunLength, runHistory); - return finderPenaltyCountPatterns(runHistory); -} - - -void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array &runHistory) const { - if (runHistory.at(0) == 0) - currentRunLength += size; // Add white border to initial run - std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end()); - runHistory.at(0) = currentRunLength; -} - - -bool QrCode::getBit(long x, int i) { - return ((x >> i) & 1) != 0; -} - - -/*---- Tables of constants ----*/ - -const int QrCode::PENALTY_N1 = 3; -const int QrCode::PENALTY_N2 = 3; -const int QrCode::PENALTY_N3 = 40; -const int QrCode::PENALTY_N4 = 10; - - -const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = { - // Version: (note that index 0 is for padding, and is set to an illegal value) - //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level - {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low - {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium - {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile - {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High -}; - -const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = { - // Version: (note that index 0 is for padding, and is set to an illegal value) - //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level - {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low - {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium - {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile - {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High -}; - - -data_too_long::data_too_long(const std::string &msg) : - std::length_error(msg) {} - - - -BitBuffer::BitBuffer() - : std::vector() {} - - -void BitBuffer::appendBits(std::uint32_t val, int len) { - if (len < 0 || len > 31 || val >> len != 0) - throw std::domain_error("Value out of range"); - for (int i = len - 1; i >= 0; i--) // Append bit by bit - this->push_back(((val >> i) & 1) != 0); -} - -} diff --git a/third_party/qrcode/QrCode.hpp b/third_party/qrcode/QrCode.hpp deleted file mode 100644 index 7341e410292001..00000000000000 --- a/third_party/qrcode/QrCode.hpp +++ /dev/null @@ -1,556 +0,0 @@ -/* - * QR Code generator library (C++) - * - * Copyright (c) Project Nayuki. (MIT License) - * https://www.nayuki.io/page/qr-code-generator-library - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - The Software is provided "as is", without warranty of any kind, express or - * implied, including but not limited to the warranties of merchantability, - * fitness for a particular purpose and noninfringement. In no event shall the - * authors or copyright holders be liable for any claim, damages or other - * liability, whether in an action of contract, tort or otherwise, arising from, - * out of or in connection with the Software or the use or other dealings in the - * Software. - */ - -#pragma once - -#include -#include -#include -#include -#include - - -namespace qrcodegen { - -/* - * A segment of character/binary/control data in a QR Code symbol. - * Instances of this class are immutable. - * The mid-level way to create a segment is to take the payload data - * and call a static factory function such as QrSegment::makeNumeric(). - * The low-level way to create a segment is to custom-make the bit buffer - * and call the QrSegment() constructor with appropriate values. - * This segment class imposes no length restrictions, but QR Codes have restrictions. - * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. - * Any segment longer than this is meaningless for the purpose of generating QR Codes. - */ -class QrSegment final { - - /*---- Public helper enumeration ----*/ - - /* - * Describes how a segment's data bits are interpreted. Immutable. - */ - public: class Mode final { - - /*-- Constants --*/ - - public: static const Mode NUMERIC; - public: static const Mode ALPHANUMERIC; - public: static const Mode BYTE; - public: static const Mode KANJI; - public: static const Mode ECI; - - - /*-- Fields --*/ - - // The mode indicator bits, which is a uint4 value (range 0 to 15). - private: int modeBits; - - // Number of character count bits for three different version ranges. - private: int numBitsCharCount[3]; - - - /*-- Constructor --*/ - - private: Mode(int mode, int cc0, int cc1, int cc2); - - - /*-- Methods --*/ - - /* - * (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15). - */ - public: int getModeBits() const; - - /* - * (Package-private) Returns the bit width of the character count field for a segment in - * this mode in a QR Code at the given version number. The result is in the range [0, 16]. - */ - public: int numCharCountBits(int ver) const; - - }; - - - - /*---- Static factory functions (mid level) ----*/ - - /* - * Returns a segment representing the given binary data encoded in - * byte mode. All input byte vectors are acceptable. Any text string - * can be converted to UTF-8 bytes and encoded as a byte mode segment. - */ - public: static QrSegment makeBytes(const std::vector &data); - - - /* - * Returns a segment representing the given string of decimal digits encoded in numeric mode. - */ - public: static QrSegment makeNumeric(const char *digits); - - - /* - * Returns a segment representing the given text string encoded in alphanumeric mode. - * The characters allowed are: 0 to 9, A to Z (uppercase only), space, - * dollar, percent, asterisk, plus, hyphen, period, slash, colon. - */ - public: static QrSegment makeAlphanumeric(const char *text); - - - /* - * Returns a list of zero or more segments to represent the given text string. The result - * may use various segment modes and switch modes to optimize the length of the bit stream. - */ - public: static std::vector makeSegments(const char *text); - - - /* - * Returns a segment representing an Extended Channel Interpretation - * (ECI) designator with the given assignment value. - */ - public: static QrSegment makeEci(long assignVal); - - - /*---- Public static helper functions ----*/ - - /* - * Tests whether the given string can be encoded as a segment in alphanumeric mode. - * A string is encodable iff each character is in the following set: 0 to 9, A to Z - * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. - */ - public: static bool isAlphanumeric(const char *text); - - - /* - * Tests whether the given string can be encoded as a segment in numeric mode. - * A string is encodable iff each character is in the range 0 to 9. - */ - public: static bool isNumeric(const char *text); - - - - /*---- Instance fields ----*/ - - /* The mode indicator of this segment. Accessed through getMode(). */ - private: Mode mode; - - /* The length of this segment's unencoded data. Measured in characters for - * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. - * Always zero or positive. Not the same as the data's bit length. - * Accessed through getNumChars(). */ - private: int numChars; - - /* The data bits of this segment. Accessed through getData(). */ - private: std::vector data; - - - /*---- Constructors (low level) ----*/ - - /* - * Creates a new QR Code segment with the given attributes and data. - * The character count (numCh) must agree with the mode and the bit buffer length, - * but the constraint isn't checked. The given bit buffer is copied and stored. - */ - public: QrSegment(Mode md, int numCh, const std::vector &dt); - - - /* - * Creates a new QR Code segment with the given parameters and data. - * The character count (numCh) must agree with the mode and the bit buffer length, - * but the constraint isn't checked. The given bit buffer is moved and stored. - */ - public: QrSegment(Mode md, int numCh, std::vector &&dt); - - - /*---- Methods ----*/ - - /* - * Returns the mode field of this segment. - */ - public: Mode getMode() const; - - - /* - * Returns the character count field of this segment. - */ - public: int getNumChars() const; - - - /* - * Returns the data bits of this segment. - */ - public: const std::vector &getData() const; - - - // (Package-private) Calculates the number of bits needed to encode the given segments at - // the given version. Returns a non-negative number if successful. Otherwise returns -1 if a - // segment has too many characters to fit its length field, or the total bits exceeds INT_MAX. - public: static int getTotalBits(const std::vector &segs, int version); - - - /*---- Private constant ----*/ - - /* The set of all legal characters in alphanumeric mode, where - * each character value maps to the index in the string. */ - private: static const char *ALPHANUMERIC_CHARSET; - -}; - - - -/* - * A QR Code symbol, which is a type of two-dimension barcode. - * Invented by Denso Wave and described in the ISO/IEC 18004 standard. - * Instances of this class represent an immutable square grid of black and white cells. - * The class provides static factory functions to create a QR Code from text or binary data. - * The class covers the QR Code Model 2 specification, supporting all versions (sizes) - * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. - * - * Ways to create a QR Code object: - * - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary(). - * - Mid level: Custom-make the list of segments and call QrCode::encodeSegments(). - * - Low level: Custom-make the array of data codeword bytes (including - * segment headers and final padding, excluding error correction codewords), - * supply the appropriate version number, and call the QrCode() constructor. - * (Note that all ways require supplying the desired error correction level.) - */ -class QrCode final { - - /*---- Public helper enumeration ----*/ - - /* - * The error correction level in a QR Code symbol. - */ - public: enum class Ecc { - LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords - MEDIUM , // The QR Code can tolerate about 15% erroneous codewords - QUARTILE, // The QR Code can tolerate about 25% erroneous codewords - HIGH , // The QR Code can tolerate about 30% erroneous codewords - }; - - - // Returns a value in the range 0 to 3 (unsigned 2-bit integer). - private: static int getFormatBits(Ecc ecl); - - - - /*---- Static factory functions (high level) ----*/ - - /* - * Returns a QR Code representing the given Unicode text string at the given error correction level. - * As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer - * UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible - * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than - * the ecl argument if it can be done without increasing the version. - */ - public: static QrCode encodeText(const char *text, Ecc ecl); - - - /* - * Returns a QR Code representing the given binary data at the given error correction level. - * This function always encodes using the binary segment mode, not any text mode. The maximum number of - * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. - * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. - */ - public: static QrCode encodeBinary(const std::vector &data, Ecc ecl); - - - /*---- Static factory functions (mid level) ----*/ - - /* - * Returns a QR Code representing the given segments with the given encoding parameters. - * The smallest possible QR Code version within the given range is automatically - * chosen for the output. Iff boostEcl is true, then the ECC level of the result - * may be higher than the ecl argument if it can be done without increasing the - * version. The mask number is either between 0 to 7 (inclusive) to force that - * mask, or -1 to automatically choose an appropriate mask (which may be slow). - * This function allows the user to create a custom sequence of segments that switches - * between modes (such as alphanumeric and byte) to encode text in less space. - * This is a mid-level API; the high-level API is encodeText() and encodeBinary(). - */ - public: static QrCode encodeSegments(const std::vector &segs, Ecc ecl, - int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters - - - - /*---- Instance fields ----*/ - - // Immutable scalar parameters: - - /* The version number of this QR Code, which is between 1 and 40 (inclusive). - * This determines the size of this barcode. */ - private: int version; - - /* The width and height of this QR Code, measured in modules, between - * 21 and 177 (inclusive). This is equal to version * 4 + 17. */ - private: int size; - - /* The error correction level used in this QR Code. */ - private: Ecc errorCorrectionLevel; - - /* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). - * Even if a QR Code is created with automatic masking requested (mask = -1), - * the resulting object still has a mask value between 0 and 7. */ - private: int mask; - - // Private grids of modules/pixels, with dimensions of size*size: - - // The modules of this QR Code (false = white, true = black). - // Immutable after constructor finishes. Accessed through getModule(). - private: std::vector > modules; - - // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. - private: std::vector > isFunction; - - - - /*---- Constructor (low level) ----*/ - - /* - * Creates a new QR Code with the given version number, - * error correction level, data codeword bytes, and mask number. - * This is a low-level API that most users should not use directly. - * A mid-level API is the encodeSegments() function. - */ - public: QrCode(int ver, Ecc ecl, const std::vector &dataCodewords, int msk); - - - - /*---- Public instance methods ----*/ - - /* - * Returns this QR Code's version, in the range [1, 40]. - */ - public: int getVersion() const; - - - /* - * Returns this QR Code's size, in the range [21, 177]. - */ - public: int getSize() const; - - - /* - * Returns this QR Code's error correction level. - */ - public: Ecc getErrorCorrectionLevel() const; - - - /* - * Returns this QR Code's mask, in the range [0, 7]. - */ - public: int getMask() const; - - - /* - * Returns the color of the module (pixel) at the given coordinates, which is false - * for white or true for black. The top left corner has the coordinates (x=0, y=0). - * If the given coordinates are out of bounds, then false (white) is returned. - */ - public: bool getModule(int x, int y) const; - - - /* - * Returns a string of SVG code for an image depicting this QR Code, with the given number - * of border modules. The string always uses Unix newlines (\n), regardless of the platform. - */ - public: std::string toSvgString(int border) const; - - - - /*---- Private helper methods for constructor: Drawing function modules ----*/ - - // Reads this object's version field, and draws and marks all function modules. - private: void drawFunctionPatterns(); - - - // Draws two copies of the format bits (with its own error correction code) - // based on the given mask and this object's error correction level field. - private: void drawFormatBits(int msk); - - - // Draws two copies of the version bits (with its own error correction code), - // based on this object's version field, iff 7 <= version <= 40. - private: void drawVersion(); - - - // Draws a 9*9 finder pattern including the border separator, - // with the center module at (x, y). Modules can be out of bounds. - private: void drawFinderPattern(int x, int y); - - - // Draws a 5*5 alignment pattern, with the center module - // at (x, y). All modules must be in bounds. - private: void drawAlignmentPattern(int x, int y); - - - // Sets the color of a module and marks it as a function module. - // Only used by the constructor. Coordinates must be in bounds. - private: void setFunctionModule(int x, int y, bool isBlack); - - - // Returns the color of the module at the given coordinates, which must be in range. - private: bool module(int x, int y) const; - - - /*---- Private helper methods for constructor: Codewords and masking ----*/ - - // Returns a new byte string representing the given data with the appropriate error correction - // codewords appended to it, based on this object's version and error correction level. - private: std::vector addEccAndInterleave(const std::vector &data) const; - - - // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire - // data area of this QR Code. Function modules need to be marked off before this is called. - private: void drawCodewords(const std::vector &data); - - - // XORs the codeword modules in this QR Code with the given mask pattern. - // The function modules must be marked and the codeword bits must be drawn - // before masking. Due to the arithmetic of XOR, calling applyMask() with - // the same mask value a second time will undo the mask. A final well-formed - // QR Code needs exactly one (not zero, two, etc.) mask applied. - private: void applyMask(int msk); - - - // Calculates and returns the penalty score based on state of this QR Code's current modules. - // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. - private: long getPenaltyScore() const; - - - - /*---- Private helper functions ----*/ - - // Returns an ascending list of positions of alignment patterns for this version number. - // Each position is in the range [0,177), and are used on both the x and y axes. - // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. - private: std::vector getAlignmentPatternPositions() const; - - - // Returns the number of data bits that can be stored in a QR Code of the given version number, after - // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. - // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. - private: static int getNumRawDataModules(int ver); - - - // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any - // QR Code of the given version number and error correction level, with remainder bits discarded. - // This stateless pure function could be implemented as a (40*4)-cell lookup table. - private: static int getNumDataCodewords(int ver, Ecc ecl); - - - // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be - // implemented as a lookup table over all possible parameter values, instead of as an algorithm. - private: static std::vector reedSolomonComputeDivisor(int degree); - - - // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. - private: static std::vector reedSolomonComputeRemainder(const std::vector &data, const std::vector &divisor); - - - // Returns the product of the two given field elements modulo GF(2^8/0x11D). - // All inputs are valid. This could be implemented as a 256*256 lookup table. - private: static std::uint8_t reedSolomonMultiply(std::uint8_t x, std::uint8_t y); - - - // Can only be called immediately after a white run is added, and - // returns either 0, 1, or 2. A helper function for getPenaltyScore(). - private: int finderPenaltyCountPatterns(const std::array &runHistory) const; - - - // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). - private: int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array &runHistory) const; - - - // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). - private: void finderPenaltyAddHistory(int currentRunLength, std::array &runHistory) const; - - - // Returns true iff the i'th bit of x is set to 1. - private: static bool getBit(long x, int i); - - - /*---- Constants and tables ----*/ - - // The minimum version number supported in the QR Code Model 2 standard. - public: static constexpr int MIN_VERSION = 1; - - // The maximum version number supported in the QR Code Model 2 standard. - public: static constexpr int MAX_VERSION = 40; - - - // For use in getPenaltyScore(), when evaluating which mask is best. - private: static const int PENALTY_N1; - private: static const int PENALTY_N2; - private: static const int PENALTY_N3; - private: static const int PENALTY_N4; - - - private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41]; - private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41]; - -}; - - - -/*---- Public exception class ----*/ - -/* - * Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include: - * - Decrease the error correction level if it was greater than Ecc::LOW. - * - If the encodeSegments() function was called with a maxVersion argument, then increase - * it if it was less than QrCode::MAX_VERSION. (This advice does not apply to the other - * factory functions because they search all versions up to QrCode::MAX_VERSION.) - * - Split the text data into better or optimal segments in order to reduce the number of bits required. - * - Change the text or binary data to be shorter. - * - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric). - * - Propagate the error upward to the caller/user. - */ -class data_too_long : public std::length_error { - - public: explicit data_too_long(const std::string &msg); - -}; - - - -/* - * An appendable sequence of bits (0s and 1s). Mainly used by QrSegment. - */ -class BitBuffer final : public std::vector { - - /*---- Constructor ----*/ - - // Creates an empty bit buffer (length 0). - public: BitBuffer(); - - - - /*---- Method ----*/ - - // Appends the given number of low-order bits of the given value - // to this buffer. Requires 0 <= len <= 31 and val < 2^len. - public: void appendBits(std::uint32_t val, int len); - -}; - -} diff --git a/third_party/qt5/larch64/bin/lrelease b/third_party/qt5/larch64/bin/lrelease deleted file mode 100755 index 5891f85851f256..00000000000000 --- a/third_party/qt5/larch64/bin/lrelease +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:56ddfc4ead01eaf43cba41e2095ec4f52309c53a60ba9e351d8dbd900151228f -size 546824 diff --git a/third_party/qt5/larch64/bin/lupdate b/third_party/qt5/larch64/bin/lupdate deleted file mode 100755 index 0055aae2294826..00000000000000 --- a/third_party/qt5/larch64/bin/lupdate +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7af679aa708031f6d19baabbd48e92d23462c6ff287caccdcb5c6324168d985d -size 1095744 diff --git a/third_party/raylib/.gitignore b/third_party/raylib/.gitignore deleted file mode 100644 index efe2c09437e7e5..00000000000000 --- a/third_party/raylib/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/raylib_repo/ diff --git a/third_party/raylib/Darwin/libraylib.a b/third_party/raylib/Darwin/libraylib.a deleted file mode 100644 index 837ad8818e4dad..00000000000000 --- a/third_party/raylib/Darwin/libraylib.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7ffe1fc6497f0c111fc507988e94fd29ce4db53a4876dc82ab9267895ad82584 -size 6515352 diff --git a/third_party/raylib/include/raylib.h b/third_party/raylib/include/raylib.h deleted file mode 100644 index 1c4c4a09fa2365..00000000000000 --- a/third_party/raylib/include/raylib.h +++ /dev/null @@ -1,1662 +0,0 @@ -/********************************************************************************************** -* -* raylib v5.0 - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com) -* -* FEATURES: -* - NO external dependencies, all required libraries included with raylib -* - Multiplatform: Windows, Linux, FreeBSD, OpenBSD, NetBSD, DragonFly, -* MacOS, Haiku, Android, Raspberry Pi, DRM native, HTML5. -* - Written in plain C code (C99) in PascalCase/camelCase notation -* - Hardware accelerated with OpenGL (1.1, 2.1, 3.3, 4.3 or ES2 - choose at compile) -* - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] -* - Multiple Fonts formats supported (TTF, XNA fonts, AngelCode fonts) -* - Outstanding texture formats support, including compressed formats (DXT, ETC, ASTC) -* - Full 3d support for 3d Shapes, Models, Billboards, Heightmaps and more! -* - Flexible Materials system, supporting classic maps and PBR maps -* - Animated 3D models supported (skeletal bones animation) (IQM) -* - Shaders support, including Model shaders and Postprocessing shaders -* - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] -* - Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, XM, MOD) -* - VR stereo rendering with configurable HMD device parameters -* - Bindings to multiple programming languages available! -* -* NOTES: -* - One default Font is loaded on InitWindow()->LoadFontDefault() [core, text] -* - One default Texture2D is loaded on rlglInit(), 1x1 white pixel R8G8B8A8 [rlgl] (OpenGL 3.3 or ES2) -* - One default Shader is loaded on rlglInit()->rlLoadShaderDefault() [rlgl] (OpenGL 3.3 or ES2) -* - One default RenderBatch is loaded on rlglInit()->rlLoadRenderBatch() [rlgl] (OpenGL 3.3 or ES2) -* -* DEPENDENCIES (included): -* [rcore] rglfw (Camilla Löwy - github.com/glfw/glfw) for window/context management and input (PLATFORM_DESKTOP) -* [rlgl] glad (David Herberth - github.com/Dav1dde/glad) for OpenGL 3.3 extensions loading (PLATFORM_DESKTOP) -* [raudio] miniaudio (David Reid - github.com/mackron/miniaudio) for audio device/context management -* -* OPTIONAL DEPENDENCIES (included): -* [rcore] msf_gif (Miles Fogle) for GIF recording -* [rcore] sinfl (Micha Mettke) for DEFLATE decompression algorithm -* [rcore] sdefl (Micha Mettke) for DEFLATE compression algorithm -* [rtextures] stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...) -* [rtextures] stb_image_write (Sean Barret) for image writing (BMP, TGA, PNG, JPG) -* [rtextures] stb_image_resize (Sean Barret) for image resizing algorithms -* [rtext] stb_truetype (Sean Barret) for ttf fonts loading -* [rtext] stb_rect_pack (Sean Barret) for rectangles packing -* [rmodels] par_shapes (Philip Rideout) for parametric 3d shapes generation -* [rmodels] tinyobj_loader_c (Syoyo Fujita) for models loading (OBJ, MTL) -* [rmodels] cgltf (Johannes Kuhlmann) for models loading (glTF) -* [rmodels] Model3D (bzt) for models loading (M3D, https://bztsrc.gitlab.io/model3d) -* [raudio] dr_wav (David Reid) for WAV audio file loading -* [raudio] dr_flac (David Reid) for FLAC audio file loading -* [raudio] dr_mp3 (David Reid) for MP3 audio file loading -* [raudio] stb_vorbis (Sean Barret) for OGG audio loading -* [raudio] jar_xm (Joshua Reisenauer) for XM audio module loading -* [raudio] jar_mod (Joshua Reisenauer) for MOD audio module loading -* -* -* LICENSE: zlib/libpng -* -* raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, -* BSD-like license that allows static linking with closed source software: -* -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYLIB_H -#define RAYLIB_H - -#include // Required for: va_list - Only used by TraceLogCallback - -#define RAYLIB_VERSION_MAJOR 5 -#define RAYLIB_VERSION_MINOR 0 -#define RAYLIB_VERSION_PATCH 0 -#define RAYLIB_VERSION "5.0" - -// Function specifiers in case library is build/used as a shared library (Windows) -// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -#if defined(_WIN32) - #if defined(BUILD_LIBTYPE_SHARED) - #if defined(__TINYC__) - #define __declspec(x) __attribute__((x)) - #endif - #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) - #elif defined(USE_LIBTYPE_SHARED) - #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) - #endif -#endif - -#ifndef RLAPI - #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) -#endif - -//---------------------------------------------------------------------------------- -// Some basic Defines -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -// Allow custom memory allocators -// NOTE: Require recompiling raylib sources -#ifndef RL_MALLOC - #define RL_MALLOC(sz) malloc(sz) -#endif -#ifndef RL_CALLOC - #define RL_CALLOC(n,sz) calloc(n,sz) -#endif -#ifndef RL_REALLOC - #define RL_REALLOC(ptr,sz) realloc(ptr,sz) -#endif -#ifndef RL_FREE - #define RL_FREE(ptr) free(ptr) -#endif - -// NOTE: MSVC C++ compiler does not support compound literals (C99 feature) -// Plain structures in C++ (without constructors) can be initialized with { } -// This is called aggregate initialization (C++11 feature) -#if defined(__cplusplus) - #define CLITERAL(type) type -#else - #define CLITERAL(type) (type) -#endif - -// Some compilers (mostly macos clang) default to C++98, -// where aggregate initialization can't be used -// So, give a more clear error stating how to fix this -#if !defined(_MSC_VER) && (defined(__cplusplus) && __cplusplus < 201103L) - #error "C++11 or later is required. Add -std=c++11" -#endif - -// NOTE: We set some defines with some data types declared by raylib -// Other modules (raymath, rlgl) also require some of those types, so, -// to be able to use those other modules as standalone (not depending on raylib) -// this defines are very useful for internal check and avoid type (re)definitions -#define RL_COLOR_TYPE -#define RL_RECTANGLE_TYPE -#define RL_VECTOR2_TYPE -#define RL_VECTOR3_TYPE -#define RL_VECTOR4_TYPE -#define RL_QUATERNION_TYPE -#define RL_MATRIX_TYPE - -// Some Basic Colors -// NOTE: Custom raylib color palette for amazing visuals on WHITE background -#define LIGHTGRAY CLITERAL(Color){ 200, 200, 200, 255 } // Light Gray -#define GRAY CLITERAL(Color){ 130, 130, 130, 255 } // Gray -#define DARKGRAY CLITERAL(Color){ 80, 80, 80, 255 } // Dark Gray -#define YELLOW CLITERAL(Color){ 253, 249, 0, 255 } // Yellow -#define GOLD CLITERAL(Color){ 255, 203, 0, 255 } // Gold -#define ORANGE CLITERAL(Color){ 255, 161, 0, 255 } // Orange -#define PINK CLITERAL(Color){ 255, 109, 194, 255 } // Pink -#define RED CLITERAL(Color){ 230, 41, 55, 255 } // Red -#define MAROON CLITERAL(Color){ 190, 33, 55, 255 } // Maroon -#define GREEN CLITERAL(Color){ 0, 228, 48, 255 } // Green -#define LIME CLITERAL(Color){ 0, 158, 47, 255 } // Lime -#define DARKGREEN CLITERAL(Color){ 0, 117, 44, 255 } // Dark Green -#define SKYBLUE CLITERAL(Color){ 102, 191, 255, 255 } // Sky Blue -#define BLUE CLITERAL(Color){ 0, 121, 241, 255 } // Blue -#define DARKBLUE CLITERAL(Color){ 0, 82, 172, 255 } // Dark Blue -#define PURPLE CLITERAL(Color){ 200, 122, 255, 255 } // Purple -#define VIOLET CLITERAL(Color){ 135, 60, 190, 255 } // Violet -#define DARKPURPLE CLITERAL(Color){ 112, 31, 126, 255 } // Dark Purple -#define BEIGE CLITERAL(Color){ 211, 176, 131, 255 } // Beige -#define BROWN CLITERAL(Color){ 127, 106, 79, 255 } // Brown -#define DARKBROWN CLITERAL(Color){ 76, 63, 47, 255 } // Dark Brown - -#define WHITE CLITERAL(Color){ 255, 255, 255, 255 } // White -#define BLACK CLITERAL(Color){ 0, 0, 0, 255 } // Black -#define BLANK CLITERAL(Color){ 0, 0, 0, 0 } // Blank (Transparent) -#define MAGENTA CLITERAL(Color){ 255, 0, 255, 255 } // Magenta -#define RAYWHITE CLITERAL(Color){ 245, 245, 245, 255 } // My own White (raylib logo) - -//---------------------------------------------------------------------------------- -// Structures Definition -//---------------------------------------------------------------------------------- -// Boolean type -#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) - #include -#elif !defined(__cplusplus) && !defined(bool) - typedef enum bool { false = 0, true = !false } bool; - #define RL_BOOL_TYPE -#endif - -// Vector2, 2 components -typedef struct Vector2 { - float x; // Vector x component - float y; // Vector y component -} Vector2; - -// Vector3, 3 components -typedef struct Vector3 { - float x; // Vector x component - float y; // Vector y component - float z; // Vector z component -} Vector3; - -// Vector4, 4 components -typedef struct Vector4 { - float x; // Vector x component - float y; // Vector y component - float z; // Vector z component - float w; // Vector w component -} Vector4; - -// Quaternion, 4 components (Vector4 alias) -typedef Vector4 Quaternion; - -// Matrix, 4x4 components, column major, OpenGL style, right-handed -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; - -// Color, 4 components, R8G8B8A8 (32bit) -typedef struct Color { - unsigned char r; // Color red value - unsigned char g; // Color green value - unsigned char b; // Color blue value - unsigned char a; // Color alpha value -} Color; - -// Rectangle, 4 components -typedef struct Rectangle { - float x; // Rectangle top-left corner position x - float y; // Rectangle top-left corner position y - float width; // Rectangle width - float height; // Rectangle height -} Rectangle; - -// Image, pixel data stored in CPU memory (RAM) -typedef struct Image { - void *data; // Image raw data - int width; // Image base width - int height; // Image base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (PixelFormat type) -} Image; - -// Texture, tex data stored in GPU memory (VRAM) -typedef struct Texture { - unsigned int id; // OpenGL texture id - int width; // Texture base width - int height; // Texture base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (PixelFormat type) -} Texture; - -// Texture2D, same as Texture -typedef Texture Texture2D; - -// TextureCubemap, same as Texture -typedef Texture TextureCubemap; - -// RenderTexture, fbo for texture rendering -typedef struct RenderTexture { - unsigned int id; // OpenGL framebuffer object id - Texture texture; // Color buffer attachment texture - Texture depth; // Depth buffer attachment texture -} RenderTexture; - -// RenderTexture2D, same as RenderTexture -typedef RenderTexture RenderTexture2D; - -// NPatchInfo, n-patch layout info -typedef struct NPatchInfo { - Rectangle source; // Texture source rectangle - int left; // Left border offset - int top; // Top border offset - int right; // Right border offset - int bottom; // Bottom border offset - int layout; // Layout of the n-patch: 3x3, 1x3 or 3x1 -} NPatchInfo; - -// GlyphInfo, font characters glyphs info -typedef struct GlyphInfo { - int value; // Character value (Unicode) - int offsetX; // Character offset X when drawing - int offsetY; // Character offset Y when drawing - int advanceX; // Character advance position X - Image image; // Character image data -} GlyphInfo; - -// Font, font texture and GlyphInfo array data -typedef struct Font { - int baseSize; // Base size (default chars height) - int glyphCount; // Number of glyph characters - int glyphPadding; // Padding around the glyph characters - Texture2D texture; // Texture atlas containing the glyphs - Rectangle *recs; // Rectangles in texture for the glyphs - GlyphInfo *glyphs; // Glyphs info data -} Font; - -// Camera, defines position/orientation in 3d space -typedef struct Camera3D { - Vector3 position; // Camera position - Vector3 target; // Camera target it looks-at - Vector3 up; // Camera up vector (rotation over its axis) - float fovy; // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic - int projection; // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC -} Camera3D; - -typedef Camera3D Camera; // Camera type fallback, defaults to Camera3D - -// Camera2D, defines position/orientation in 2d space -typedef struct Camera2D { - Vector2 offset; // Camera offset (displacement from target) - Vector2 target; // Camera target (rotation and zoom origin) - float rotation; // Camera rotation in degrees - float zoom; // Camera zoom (scaling), should be 1.0f by default -} Camera2D; - -// Mesh, vertex data and vao/vbo -typedef struct Mesh { - int vertexCount; // Number of vertices stored in arrays - int triangleCount; // Number of triangles stored (indexed or not) - - // Vertex attributes data - float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - float *texcoords2; // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) - float *normals; // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) - float *tangents; // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) - unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) - unsigned short *indices; // Vertex indices (in case vertex data comes indexed) - - // Animation vertex data - float *animVertices; // Animated vertex positions (after bones transformations) - float *animNormals; // Animated normals (after bones transformations) - unsigned char *boneIds; // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) - float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning) - - // OpenGL identifiers - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int *vboId; // OpenGL Vertex Buffer Objects id (default vertex data) -} Mesh; - -// Shader -typedef struct Shader { - unsigned int id; // Shader program id - int *locs; // Shader locations array (RL_MAX_SHADER_LOCATIONS) -} Shader; - -// MaterialMap -typedef struct MaterialMap { - Texture2D texture; // Material map texture - Color color; // Material map color - float value; // Material map value -} MaterialMap; - -// Material, includes shader and maps -typedef struct Material { - Shader shader; // Material shader - MaterialMap *maps; // Material maps array (MAX_MATERIAL_MAPS) - float params[4]; // Material generic parameters (if required) -} Material; - -// Transform, vertex transformation data -typedef struct Transform { - Vector3 translation; // Translation - Quaternion rotation; // Rotation - Vector3 scale; // Scale -} Transform; - -// Bone, skeletal animation bone -typedef struct BoneInfo { - char name[32]; // Bone name - int parent; // Bone parent -} BoneInfo; - -// Model, meshes, materials and animation data -typedef struct Model { - Matrix transform; // Local transform matrix - - int meshCount; // Number of meshes - int materialCount; // Number of materials - Mesh *meshes; // Meshes array - Material *materials; // Materials array - int *meshMaterial; // Mesh material number - - // Animation data - int boneCount; // Number of bones - BoneInfo *bones; // Bones information (skeleton) - Transform *bindPose; // Bones base transformation (pose) -} Model; - -// ModelAnimation -typedef struct ModelAnimation { - int boneCount; // Number of bones - int frameCount; // Number of animation frames - BoneInfo *bones; // Bones information (skeleton) - Transform **framePoses; // Poses array by frame - char name[32]; // Animation name -} ModelAnimation; - -// Ray, ray for raycasting -typedef struct Ray { - Vector3 position; // Ray position (origin) - Vector3 direction; // Ray direction -} Ray; - -// RayCollision, ray hit information -typedef struct RayCollision { - bool hit; // Did the ray hit something? - float distance; // Distance to the nearest hit - Vector3 point; // Point of the nearest hit - Vector3 normal; // Surface normal of hit -} RayCollision; - -// BoundingBox -typedef struct BoundingBox { - Vector3 min; // Minimum vertex box-corner - Vector3 max; // Maximum vertex box-corner -} BoundingBox; - -// Wave, audio wave data -typedef struct Wave { - unsigned int frameCount; // Total number of frames (considering channels) - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) - void *data; // Buffer data pointer -} Wave; - -// Opaque structs declaration -// NOTE: Actual structs are defined internally in raudio module -typedef struct rAudioBuffer rAudioBuffer; -typedef struct rAudioProcessor rAudioProcessor; - -// AudioStream, custom audio stream -typedef struct AudioStream { - rAudioBuffer *buffer; // Pointer to internal data used by the audio system - rAudioProcessor *processor; // Pointer to internal data processor, useful for audio effects - - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) -} AudioStream; - -// Sound -typedef struct Sound { - AudioStream stream; // Audio stream - unsigned int frameCount; // Total number of frames (considering channels) -} Sound; - -// Music, audio stream, anything longer than ~10 seconds should be streamed -typedef struct Music { - AudioStream stream; // Audio stream - unsigned int frameCount; // Total number of frames (considering channels) - bool looping; // Music looping enable - - int ctxType; // Type of music context (audio filetype) - void *ctxData; // Audio context data, depends on type -} Music; - -// VrDeviceInfo, Head-Mounted-Display device parameters -typedef struct VrDeviceInfo { - int hResolution; // Horizontal resolution in pixels - int vResolution; // Vertical resolution in pixels - float hScreenSize; // Horizontal size in meters - float vScreenSize; // Vertical size in meters - float vScreenCenter; // Screen center in meters - float eyeToScreenDistance; // Distance between eye and display in meters - float lensSeparationDistance; // Lens separation distance in meters - float interpupillaryDistance; // IPD (distance between pupils) in meters - float lensDistortionValues[4]; // Lens distortion constant parameters - float chromaAbCorrection[4]; // Chromatic aberration correction parameters -} VrDeviceInfo; - -// VrStereoConfig, VR stereo rendering configuration for simulator -typedef struct VrStereoConfig { - Matrix projection[2]; // VR projection matrices (per eye) - Matrix viewOffset[2]; // VR view offset matrices (per eye) - float leftLensCenter[2]; // VR left lens center - float rightLensCenter[2]; // VR right lens center - float leftScreenCenter[2]; // VR left screen center - float rightScreenCenter[2]; // VR right screen center - float scale[2]; // VR distortion scale - float scaleIn[2]; // VR distortion scale in -} VrStereoConfig; - -// File path list -typedef struct FilePathList { - unsigned int capacity; // Filepaths max entries - unsigned int count; // Filepaths entries count - char **paths; // Filepaths entries -} FilePathList; - -// Automation event -typedef struct AutomationEvent { - unsigned int frame; // Event frame - unsigned int type; // Event type (AutomationEventType) - int params[4]; // Event parameters (if required) -} AutomationEvent; - -// Automation event list -typedef struct AutomationEventList { - unsigned int capacity; // Events max entries (MAX_AUTOMATION_EVENTS) - unsigned int count; // Events entries count - AutomationEvent *events; // Events entries -} AutomationEventList; - -//---------------------------------------------------------------------------------- -// Enumerators Definition -//---------------------------------------------------------------------------------- -// System/Window config flags -// NOTE: Every bit registers one state (use it with bit masks) -// By default all flags are set to 0 -typedef enum { - FLAG_VSYNC_HINT = 0x00000040, // Set to try enabling V-Sync on GPU - FLAG_FULLSCREEN_MODE = 0x00000002, // Set to run program in fullscreen - FLAG_WINDOW_RESIZABLE = 0x00000004, // Set to allow resizable window - FLAG_WINDOW_UNDECORATED = 0x00000008, // Set to disable window decoration (frame and buttons) - FLAG_WINDOW_HIDDEN = 0x00000080, // Set to hide window - FLAG_WINDOW_MINIMIZED = 0x00000200, // Set to minimize window (iconify) - FLAG_WINDOW_MAXIMIZED = 0x00000400, // Set to maximize window (expanded to monitor) - FLAG_WINDOW_UNFOCUSED = 0x00000800, // Set to window non focused - FLAG_WINDOW_TOPMOST = 0x00001000, // Set to window always on top - FLAG_WINDOW_ALWAYS_RUN = 0x00000100, // Set to allow windows running while minimized - FLAG_WINDOW_TRANSPARENT = 0x00000010, // Set to allow transparent framebuffer - FLAG_WINDOW_HIGHDPI = 0x00002000, // Set to support HighDPI - FLAG_WINDOW_MOUSE_PASSTHROUGH = 0x00004000, // Set to support mouse passthrough, only supported when FLAG_WINDOW_UNDECORATED - FLAG_BORDERLESS_WINDOWED_MODE = 0x00008000, // Set to run program in borderless windowed mode - FLAG_MSAA_4X_HINT = 0x00000020, // Set to try enabling MSAA 4X - FLAG_INTERLACED_HINT = 0x00010000 // Set to try enabling interlaced video format (for V3D) -} ConfigFlags; - -// Trace log level -// NOTE: Organized by priority level -typedef enum { - LOG_ALL = 0, // Display all logs - LOG_TRACE, // Trace logging, intended for internal use only - LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds - LOG_INFO, // Info logging, used for program execution info - LOG_WARNING, // Warning logging, used on recoverable failures - LOG_ERROR, // Error logging, used on unrecoverable failures - LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) - LOG_NONE // Disable logging -} TraceLogLevel; - -// Keyboard keys (US keyboard layout) -// NOTE: Use GetKeyPressed() to allow redefining -// required keys for alternative layouts -typedef enum { - KEY_NULL = 0, // Key: NULL, used for no key pressed - // Alphanumeric keys - KEY_APOSTROPHE = 39, // Key: ' - KEY_COMMA = 44, // Key: , - KEY_MINUS = 45, // Key: - - KEY_PERIOD = 46, // Key: . - KEY_SLASH = 47, // Key: / - KEY_ZERO = 48, // Key: 0 - KEY_ONE = 49, // Key: 1 - KEY_TWO = 50, // Key: 2 - KEY_THREE = 51, // Key: 3 - KEY_FOUR = 52, // Key: 4 - KEY_FIVE = 53, // Key: 5 - KEY_SIX = 54, // Key: 6 - KEY_SEVEN = 55, // Key: 7 - KEY_EIGHT = 56, // Key: 8 - KEY_NINE = 57, // Key: 9 - KEY_SEMICOLON = 59, // Key: ; - KEY_EQUAL = 61, // Key: = - KEY_A = 65, // Key: A | a - KEY_B = 66, // Key: B | b - KEY_C = 67, // Key: C | c - KEY_D = 68, // Key: D | d - KEY_E = 69, // Key: E | e - KEY_F = 70, // Key: F | f - KEY_G = 71, // Key: G | g - KEY_H = 72, // Key: H | h - KEY_I = 73, // Key: I | i - KEY_J = 74, // Key: J | j - KEY_K = 75, // Key: K | k - KEY_L = 76, // Key: L | l - KEY_M = 77, // Key: M | m - KEY_N = 78, // Key: N | n - KEY_O = 79, // Key: O | o - KEY_P = 80, // Key: P | p - KEY_Q = 81, // Key: Q | q - KEY_R = 82, // Key: R | r - KEY_S = 83, // Key: S | s - KEY_T = 84, // Key: T | t - KEY_U = 85, // Key: U | u - KEY_V = 86, // Key: V | v - KEY_W = 87, // Key: W | w - KEY_X = 88, // Key: X | x - KEY_Y = 89, // Key: Y | y - KEY_Z = 90, // Key: Z | z - KEY_LEFT_BRACKET = 91, // Key: [ - KEY_BACKSLASH = 92, // Key: '\' - KEY_RIGHT_BRACKET = 93, // Key: ] - KEY_GRAVE = 96, // Key: ` - // Function keys - KEY_SPACE = 32, // Key: Space - KEY_ESCAPE = 256, // Key: Esc - KEY_ENTER = 257, // Key: Enter - KEY_TAB = 258, // Key: Tab - KEY_BACKSPACE = 259, // Key: Backspace - KEY_INSERT = 260, // Key: Ins - KEY_DELETE = 261, // Key: Del - KEY_RIGHT = 262, // Key: Cursor right - KEY_LEFT = 263, // Key: Cursor left - KEY_DOWN = 264, // Key: Cursor down - KEY_UP = 265, // Key: Cursor up - KEY_PAGE_UP = 266, // Key: Page up - KEY_PAGE_DOWN = 267, // Key: Page down - KEY_HOME = 268, // Key: Home - KEY_END = 269, // Key: End - KEY_CAPS_LOCK = 280, // Key: Caps lock - KEY_SCROLL_LOCK = 281, // Key: Scroll down - KEY_NUM_LOCK = 282, // Key: Num lock - KEY_PRINT_SCREEN = 283, // Key: Print screen - KEY_PAUSE = 284, // Key: Pause - KEY_F1 = 290, // Key: F1 - KEY_F2 = 291, // Key: F2 - KEY_F3 = 292, // Key: F3 - KEY_F4 = 293, // Key: F4 - KEY_F5 = 294, // Key: F5 - KEY_F6 = 295, // Key: F6 - KEY_F7 = 296, // Key: F7 - KEY_F8 = 297, // Key: F8 - KEY_F9 = 298, // Key: F9 - KEY_F10 = 299, // Key: F10 - KEY_F11 = 300, // Key: F11 - KEY_F12 = 301, // Key: F12 - KEY_LEFT_SHIFT = 340, // Key: Shift left - KEY_LEFT_CONTROL = 341, // Key: Control left - KEY_LEFT_ALT = 342, // Key: Alt left - KEY_LEFT_SUPER = 343, // Key: Super left - KEY_RIGHT_SHIFT = 344, // Key: Shift right - KEY_RIGHT_CONTROL = 345, // Key: Control right - KEY_RIGHT_ALT = 346, // Key: Alt right - KEY_RIGHT_SUPER = 347, // Key: Super right - KEY_KB_MENU = 348, // Key: KB menu - // Keypad keys - KEY_KP_0 = 320, // Key: Keypad 0 - KEY_KP_1 = 321, // Key: Keypad 1 - KEY_KP_2 = 322, // Key: Keypad 2 - KEY_KP_3 = 323, // Key: Keypad 3 - KEY_KP_4 = 324, // Key: Keypad 4 - KEY_KP_5 = 325, // Key: Keypad 5 - KEY_KP_6 = 326, // Key: Keypad 6 - KEY_KP_7 = 327, // Key: Keypad 7 - KEY_KP_8 = 328, // Key: Keypad 8 - KEY_KP_9 = 329, // Key: Keypad 9 - KEY_KP_DECIMAL = 330, // Key: Keypad . - KEY_KP_DIVIDE = 331, // Key: Keypad / - KEY_KP_MULTIPLY = 332, // Key: Keypad * - KEY_KP_SUBTRACT = 333, // Key: Keypad - - KEY_KP_ADD = 334, // Key: Keypad + - KEY_KP_ENTER = 335, // Key: Keypad Enter - KEY_KP_EQUAL = 336, // Key: Keypad = - // Android key buttons - KEY_BACK = 4, // Key: Android back button - KEY_MENU = 82, // Key: Android menu button - KEY_VOLUME_UP = 24, // Key: Android volume up button - KEY_VOLUME_DOWN = 25 // Key: Android volume down button -} KeyboardKey; - -// Add backwards compatibility support for deprecated names -#define MOUSE_LEFT_BUTTON MOUSE_BUTTON_LEFT -#define MOUSE_RIGHT_BUTTON MOUSE_BUTTON_RIGHT -#define MOUSE_MIDDLE_BUTTON MOUSE_BUTTON_MIDDLE - -// Mouse buttons -typedef enum { - MOUSE_BUTTON_LEFT = 0, // Mouse button left - MOUSE_BUTTON_RIGHT = 1, // Mouse button right - MOUSE_BUTTON_MIDDLE = 2, // Mouse button middle (pressed wheel) - MOUSE_BUTTON_SIDE = 3, // Mouse button side (advanced mouse device) - MOUSE_BUTTON_EXTRA = 4, // Mouse button extra (advanced mouse device) - MOUSE_BUTTON_FORWARD = 5, // Mouse button forward (advanced mouse device) - MOUSE_BUTTON_BACK = 6, // Mouse button back (advanced mouse device) -} MouseButton; - -// Mouse cursor -typedef enum { - MOUSE_CURSOR_DEFAULT = 0, // Default pointer shape - MOUSE_CURSOR_ARROW = 1, // Arrow shape - MOUSE_CURSOR_IBEAM = 2, // Text writing cursor shape - MOUSE_CURSOR_CROSSHAIR = 3, // Cross shape - MOUSE_CURSOR_POINTING_HAND = 4, // Pointing hand cursor - MOUSE_CURSOR_RESIZE_EW = 5, // Horizontal resize/move arrow shape - MOUSE_CURSOR_RESIZE_NS = 6, // Vertical resize/move arrow shape - MOUSE_CURSOR_RESIZE_NWSE = 7, // Top-left to bottom-right diagonal resize/move arrow shape - MOUSE_CURSOR_RESIZE_NESW = 8, // The top-right to bottom-left diagonal resize/move arrow shape - MOUSE_CURSOR_RESIZE_ALL = 9, // The omnidirectional resize/move cursor shape - MOUSE_CURSOR_NOT_ALLOWED = 10 // The operation-not-allowed shape -} MouseCursor; - -// Gamepad buttons -typedef enum { - GAMEPAD_BUTTON_UNKNOWN = 0, // Unknown button, just for error checking - GAMEPAD_BUTTON_LEFT_FACE_UP, // Gamepad left DPAD up button - GAMEPAD_BUTTON_LEFT_FACE_RIGHT, // Gamepad left DPAD right button - GAMEPAD_BUTTON_LEFT_FACE_DOWN, // Gamepad left DPAD down button - GAMEPAD_BUTTON_LEFT_FACE_LEFT, // Gamepad left DPAD left button - GAMEPAD_BUTTON_RIGHT_FACE_UP, // Gamepad right button up (i.e. PS3: Triangle, Xbox: Y) - GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, // Gamepad right button right (i.e. PS3: Square, Xbox: X) - GAMEPAD_BUTTON_RIGHT_FACE_DOWN, // Gamepad right button down (i.e. PS3: Cross, Xbox: A) - GAMEPAD_BUTTON_RIGHT_FACE_LEFT, // Gamepad right button left (i.e. PS3: Circle, Xbox: B) - GAMEPAD_BUTTON_LEFT_TRIGGER_1, // Gamepad top/back trigger left (first), it could be a trailing button - GAMEPAD_BUTTON_LEFT_TRIGGER_2, // Gamepad top/back trigger left (second), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_1, // Gamepad top/back trigger right (one), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // Gamepad top/back trigger right (second), it could be a trailing button - GAMEPAD_BUTTON_MIDDLE_LEFT, // Gamepad center buttons, left one (i.e. PS3: Select) - GAMEPAD_BUTTON_MIDDLE, // Gamepad center buttons, middle one (i.e. PS3: PS, Xbox: XBOX) - GAMEPAD_BUTTON_MIDDLE_RIGHT, // Gamepad center buttons, right one (i.e. PS3: Start) - GAMEPAD_BUTTON_LEFT_THUMB, // Gamepad joystick pressed button left - GAMEPAD_BUTTON_RIGHT_THUMB // Gamepad joystick pressed button right -} GamepadButton; - -// Gamepad axis -typedef enum { - GAMEPAD_AXIS_LEFT_X = 0, // Gamepad left stick X axis - GAMEPAD_AXIS_LEFT_Y = 1, // Gamepad left stick Y axis - GAMEPAD_AXIS_RIGHT_X = 2, // Gamepad right stick X axis - GAMEPAD_AXIS_RIGHT_Y = 3, // Gamepad right stick Y axis - GAMEPAD_AXIS_LEFT_TRIGGER = 4, // Gamepad back trigger left, pressure level: [1..-1] - GAMEPAD_AXIS_RIGHT_TRIGGER = 5 // Gamepad back trigger right, pressure level: [1..-1] -} GamepadAxis; - -// Material map index -typedef enum { - MATERIAL_MAP_ALBEDO = 0, // Albedo material (same as: MATERIAL_MAP_DIFFUSE) - MATERIAL_MAP_METALNESS, // Metalness material (same as: MATERIAL_MAP_SPECULAR) - MATERIAL_MAP_NORMAL, // Normal material - MATERIAL_MAP_ROUGHNESS, // Roughness material - MATERIAL_MAP_OCCLUSION, // Ambient occlusion material - MATERIAL_MAP_EMISSION, // Emission material - MATERIAL_MAP_HEIGHT, // Heightmap material - MATERIAL_MAP_CUBEMAP, // Cubemap material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_IRRADIANCE, // Irradiance material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_PREFILTER, // Prefilter material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_BRDF // Brdf material -} MaterialMapIndex; - -#define MATERIAL_MAP_DIFFUSE MATERIAL_MAP_ALBEDO -#define MATERIAL_MAP_SPECULAR MATERIAL_MAP_METALNESS - -// Shader location index -typedef enum { - SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position - SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 - SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 - SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal - SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent - SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color - SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection - SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) - SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection - SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) - SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal - SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view - SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color - SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color - SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color - SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: SHADER_LOC_MAP_DIFFUSE) - SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: SHADER_LOC_MAP_SPECULAR) - SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal - SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness - SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion - SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission - SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height - SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap - SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance - SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter - SHADER_LOC_MAP_BRDF // Shader location: sampler2d texture: brdf -} ShaderLocationIndex; - -#define SHADER_LOC_MAP_DIFFUSE SHADER_LOC_MAP_ALBEDO -#define SHADER_LOC_MAP_SPECULAR SHADER_LOC_MAP_METALNESS - -// Shader uniform data type -typedef enum { - SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float - SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) - SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) - SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) - SHADER_UNIFORM_INT, // Shader uniform type: int - SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) - SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) - SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) - SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d -} ShaderUniformDataType; - -// Shader attribute data types -typedef enum { - SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float - SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) - SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) - SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) -} ShaderAttributeDataType; - -// Pixel formats -// NOTE: Support depends on OpenGL version and platform -typedef enum { - PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) - PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp - PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp - PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp - PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) - PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) - PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) - PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) - PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) - PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) - PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp - PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp -} PixelFormat; - -// Texture parameters: filter mode -// NOTE 1: Filtering considers mipmaps if available in the texture -// NOTE 2: Filter is accordingly set for minification and magnification -typedef enum { - TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation - TEXTURE_FILTER_BILINEAR, // Linear filtering - TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) - TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x - TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x - TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x -} TextureFilter; - -// Texture parameters: wrap mode -typedef enum { - TEXTURE_WRAP_REPEAT = 0, // Repeats texture in tiled mode - TEXTURE_WRAP_CLAMP, // Clamps texture to edge pixel in tiled mode - TEXTURE_WRAP_MIRROR_REPEAT, // Mirrors and repeats the texture in tiled mode - TEXTURE_WRAP_MIRROR_CLAMP // Mirrors and clamps to border the texture in tiled mode -} TextureWrap; - -// Cubemap layouts -typedef enum { - CUBEMAP_LAYOUT_AUTO_DETECT = 0, // Automatically detect layout type - CUBEMAP_LAYOUT_LINE_VERTICAL, // Layout is defined by a vertical line with faces - CUBEMAP_LAYOUT_LINE_HORIZONTAL, // Layout is defined by a horizontal line with faces - CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR, // Layout is defined by a 3x4 cross with cubemap faces - CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE, // Layout is defined by a 4x3 cross with cubemap faces - CUBEMAP_LAYOUT_PANORAMA // Layout is defined by a panorama image (equirrectangular map) -} CubemapLayout; - -// Font type, defines generation method -typedef enum { - FONT_DEFAULT = 0, // Default font generation, anti-aliased - FONT_BITMAP, // Bitmap font generation, no anti-aliasing - FONT_SDF // SDF font generation, requires external shader -} FontType; - -// Color blending modes (pre-defined) -typedef enum { - BLEND_ALPHA = 0, // Blend textures considering alpha (default) - BLEND_ADDITIVE, // Blend textures adding colors - BLEND_MULTIPLIED, // Blend textures multiplying colors - BLEND_ADD_COLORS, // Blend textures adding colors (alternative) - BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) - BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha - BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) - BLEND_CUSTOM_SEPARATE // Blend textures using custom rgb/alpha separate src/dst factors (use rlSetBlendFactorsSeparate()) -} BlendMode; - -// Gesture -// NOTE: Provided as bit-wise flags to enable only desired gestures -typedef enum { - GESTURE_NONE = 0, // No gesture - GESTURE_TAP = 1, // Tap gesture - GESTURE_DOUBLETAP = 2, // Double tap gesture - GESTURE_HOLD = 4, // Hold gesture - GESTURE_DRAG = 8, // Drag gesture - GESTURE_SWIPE_RIGHT = 16, // Swipe right gesture - GESTURE_SWIPE_LEFT = 32, // Swipe left gesture - GESTURE_SWIPE_UP = 64, // Swipe up gesture - GESTURE_SWIPE_DOWN = 128, // Swipe down gesture - GESTURE_PINCH_IN = 256, // Pinch in gesture - GESTURE_PINCH_OUT = 512 // Pinch out gesture -} Gesture; - -// Camera system modes -typedef enum { - CAMERA_CUSTOM = 0, // Custom camera - CAMERA_FREE, // Free camera - CAMERA_ORBITAL, // Orbital camera - CAMERA_FIRST_PERSON, // First person camera - CAMERA_THIRD_PERSON // Third person camera -} CameraMode; - -// Camera projection -typedef enum { - CAMERA_PERSPECTIVE = 0, // Perspective projection - CAMERA_ORTHOGRAPHIC // Orthographic projection -} CameraProjection; - -// N-patch layout -typedef enum { - NPATCH_NINE_PATCH = 0, // Npatch layout: 3x3 tiles - NPATCH_THREE_PATCH_VERTICAL, // Npatch layout: 1x3 tiles - NPATCH_THREE_PATCH_HORIZONTAL // Npatch layout: 3x1 tiles -} NPatchLayout; - -// Callbacks to hook some internal functions -// WARNING: These callbacks are intended for advance users -typedef void (*TraceLogCallback)(int logLevel, const char *text, va_list args); // Logging: Redirect trace log messages -typedef unsigned char *(*LoadFileDataCallback)(const char *fileName, int *dataSize); // FileIO: Load binary data -typedef bool (*SaveFileDataCallback)(const char *fileName, void *data, int dataSize); // FileIO: Save binary data -typedef char *(*LoadFileTextCallback)(const char *fileName); // FileIO: Load text data -typedef bool (*SaveFileTextCallback)(const char *fileName, char *text); // FileIO: Save text data - -//------------------------------------------------------------------------------------ -// Global Variables Definition -//------------------------------------------------------------------------------------ -// It's lonely here... - -//------------------------------------------------------------------------------------ -// Window and Graphics Device Functions (Module: core) -//------------------------------------------------------------------------------------ - -#if defined(__cplusplus) -extern "C" { // Prevents name mangling of functions -#endif - -// Window-related functions -RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context -RLAPI void CloseWindow(void); // Close window and unload OpenGL context -RLAPI bool WindowShouldClose(void); // Check if application should close (KEY_ESCAPE pressed or windows close icon clicked) -RLAPI bool IsWindowReady(void); // Check if window has been initialized successfully -RLAPI bool IsWindowFullscreen(void); // Check if window is currently fullscreen -RLAPI bool IsWindowHidden(void); // Check if window is currently hidden (only PLATFORM_DESKTOP) -RLAPI bool IsWindowMinimized(void); // Check if window is currently minimized (only PLATFORM_DESKTOP) -RLAPI bool IsWindowMaximized(void); // Check if window is currently maximized (only PLATFORM_DESKTOP) -RLAPI bool IsWindowFocused(void); // Check if window is currently focused (only PLATFORM_DESKTOP) -RLAPI bool IsWindowResized(void); // Check if window has been resized last frame -RLAPI bool IsWindowState(unsigned int flag); // Check if one specific window flag is enabled -RLAPI void SetWindowState(unsigned int flags); // Set window configuration state using flags (only PLATFORM_DESKTOP) -RLAPI void ClearWindowState(unsigned int flags); // Clear window configuration state flags -RLAPI void ToggleFullscreen(void); // Toggle window state: fullscreen/windowed (only PLATFORM_DESKTOP) -RLAPI void ToggleBorderlessWindowed(void); // Toggle window state: borderless windowed (only PLATFORM_DESKTOP) -RLAPI void MaximizeWindow(void); // Set window state: maximized, if resizable (only PLATFORM_DESKTOP) -RLAPI void MinimizeWindow(void); // Set window state: minimized, if resizable (only PLATFORM_DESKTOP) -RLAPI void RestoreWindow(void); // Set window state: not minimized/maximized (only PLATFORM_DESKTOP) -RLAPI void SetWindowIcon(Image image); // Set icon for window (single image, RGBA 32bit, only PLATFORM_DESKTOP) -RLAPI void SetWindowIcons(Image *images, int count); // Set icon for window (multiple images, RGBA 32bit, only PLATFORM_DESKTOP) -RLAPI void SetWindowTitle(const char *title); // Set title for window (only PLATFORM_DESKTOP and PLATFORM_WEB) -RLAPI void SetWindowPosition(int x, int y); // Set window position on screen (only PLATFORM_DESKTOP) -RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window -RLAPI void SetWindowMinSize(int width, int height); // Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) -RLAPI void SetWindowMaxSize(int width, int height); // Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) -RLAPI void SetWindowSize(int width, int height); // Set window dimensions -RLAPI void SetWindowOpacity(float opacity); // Set window opacity [0.0f..1.0f] (only PLATFORM_DESKTOP) -RLAPI void SetWindowFocused(void); // Set window focused (only PLATFORM_DESKTOP) -RLAPI void *GetWindowHandle(void); // Get native window handle -RLAPI int GetScreenWidth(void); // Get current screen width -RLAPI int GetScreenHeight(void); // Get current screen height -RLAPI int GetRenderWidth(void); // Get current render width (it considers HiDPI) -RLAPI int GetRenderHeight(void); // Get current render height (it considers HiDPI) -RLAPI int GetMonitorCount(void); // Get number of connected monitors -RLAPI int GetCurrentMonitor(void); // Get current connected monitor -RLAPI Vector2 GetMonitorPosition(int monitor); // Get specified monitor position -RLAPI int GetMonitorWidth(int monitor); // Get specified monitor width (current video mode used by monitor) -RLAPI int GetMonitorHeight(int monitor); // Get specified monitor height (current video mode used by monitor) -RLAPI int GetMonitorPhysicalWidth(int monitor); // Get specified monitor physical width in millimetres -RLAPI int GetMonitorPhysicalHeight(int monitor); // Get specified monitor physical height in millimetres -RLAPI int GetMonitorRefreshRate(int monitor); // Get specified monitor refresh rate -RLAPI Vector2 GetWindowPosition(void); // Get window position XY on monitor -RLAPI Vector2 GetWindowScaleDPI(void); // Get window scale DPI factor -RLAPI const char *GetMonitorName(int monitor); // Get the human-readable, UTF-8 encoded name of the specified monitor -RLAPI void SetClipboardText(const char *text); // Set clipboard text content -RLAPI const char *GetClipboardText(void); // Get clipboard text content -RLAPI void EnableEventWaiting(void); // Enable waiting for events on EndDrawing(), no automatic event polling -RLAPI void DisableEventWaiting(void); // Disable waiting for events on EndDrawing(), automatic events polling - -// Cursor-related functions -RLAPI void ShowCursor(void); // Shows cursor -RLAPI void HideCursor(void); // Hides cursor -RLAPI bool IsCursorHidden(void); // Check if cursor is not visible -RLAPI void EnableCursor(void); // Enables cursor (unlock cursor) -RLAPI void DisableCursor(void); // Disables cursor (lock cursor) -RLAPI bool IsCursorOnScreen(void); // Check if cursor is on the screen - -// Drawing-related functions -RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) -RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing -RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) -RLAPI void BeginMode2D(Camera2D camera); // Begin 2D mode with custom camera (2D) -RLAPI void EndMode2D(void); // Ends 2D mode with custom camera -RLAPI void BeginMode3D(Camera3D camera); // Begin 3D mode with custom camera (3D) -RLAPI void EndMode3D(void); // Ends 3D mode and returns to default 2D orthographic mode -RLAPI void BeginTextureMode(RenderTexture2D target); // Begin drawing to render texture -RLAPI void EndTextureMode(void); // Ends drawing to render texture -RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing -RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) -RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied, subtract, custom) -RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) -RLAPI void BeginScissorMode(int x, int y, int width, int height); // Begin scissor mode (define screen area for following drawing) -RLAPI void EndScissorMode(void); // End scissor mode -RLAPI void BeginVrStereoMode(VrStereoConfig config); // Begin stereo rendering (requires VR simulator) -RLAPI void EndVrStereoMode(void); // End stereo rendering (requires VR simulator) - -// VR stereo config functions for VR simulator -RLAPI VrStereoConfig LoadVrStereoConfig(VrDeviceInfo device); // Load VR stereo config for VR simulator device parameters -RLAPI void UnloadVrStereoConfig(VrStereoConfig config); // Unload VR stereo config - -// Shader management functions -// NOTE: Shader functionality is not available on OpenGL 1.1 -RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations -RLAPI Shader LoadShaderFromMemory(const char *vsCode, const char *fsCode); // Load shader from code strings and bind default locations -RLAPI bool IsShaderReady(Shader shader); // Check if a shader is ready -RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location -RLAPI int GetShaderLocationAttrib(Shader shader, const char *attribName); // Get shader attribute location -RLAPI void SetShaderValue(Shader shader, int locIndex, const void *value, int uniformType); // Set shader uniform value -RLAPI void SetShaderValueV(Shader shader, int locIndex, const void *value, int uniformType, int count); // Set shader uniform value vector -RLAPI void SetShaderValueMatrix(Shader shader, int locIndex, Matrix mat); // Set shader uniform value (matrix 4x4) -RLAPI void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture); // Set shader uniform value for texture (sampler2d) -RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) - -// Screen-space-related functions -RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Get a ray trace from mouse position -RLAPI Matrix GetCameraMatrix(Camera camera); // Get camera transform matrix (view matrix) -RLAPI Matrix GetCameraMatrix2D(Camera2D camera); // Get camera 2d transform matrix -RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Get the screen space position for a 3d world space position -RLAPI Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera); // Get the world space position for a 2d camera screen space position -RLAPI Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height); // Get size position for a 3d world space position -RLAPI Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera); // Get the screen space position for a 2d camera world space position - -// Timing-related functions -RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) -RLAPI float GetFrameTime(void); // Get time in seconds for last frame drawn (delta time) -RLAPI double GetTime(void); // Get elapsed time in seconds since InitWindow() -RLAPI int GetFPS(void); // Get current FPS - -// Custom frame control functions -// NOTE: Those functions are intended for advance users that want full control over the frame processing -// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() -// To avoid that behaviour and control frame processes manually, enable in config.h: SUPPORT_CUSTOM_FRAME_CONTROL -RLAPI void SwapScreenBuffer(void); // Swap back buffer with front buffer (screen drawing) -RLAPI void PollInputEvents(void); // Register all input events -RLAPI void WaitTime(double seconds); // Wait for some time (halt program execution) - -// Random values generation functions -RLAPI void SetRandomSeed(unsigned int seed); // Set the seed for the random number generator -RLAPI int GetRandomValue(int min, int max); // Get a random value between min and max (both included) -RLAPI int *LoadRandomSequence(unsigned int count, int min, int max); // Load random values sequence, no values repeated -RLAPI void UnloadRandomSequence(int *sequence); // Unload random values sequence - -// Misc. functions -RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (filename extension defines format) -RLAPI void SetConfigFlags(unsigned int flags); // Setup init configuration flags (view FLAGS) -RLAPI void OpenURL(const char *url); // Open URL with default system browser (if available) - -// NOTE: Following functions implemented in module [utils] -//------------------------------------------------------------------ -RLAPI void TraceLog(int logLevel, const char *text, ...); // Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...) -RLAPI void SetTraceLogLevel(int logLevel); // Set the current threshold (minimum) log level -RLAPI void *MemAlloc(unsigned int size); // Internal memory allocator -RLAPI void *MemRealloc(void *ptr, unsigned int size); // Internal memory reallocator -RLAPI void MemFree(void *ptr); // Internal memory free - -// Set custom callbacks -// WARNING: Callbacks setup is intended for advance users -RLAPI void SetTraceLogCallback(TraceLogCallback callback); // Set custom trace log -RLAPI void SetLoadFileDataCallback(LoadFileDataCallback callback); // Set custom file binary data loader -RLAPI void SetSaveFileDataCallback(SaveFileDataCallback callback); // Set custom file binary data saver -RLAPI void SetLoadFileTextCallback(LoadFileTextCallback callback); // Set custom file text data loader -RLAPI void SetSaveFileTextCallback(SaveFileTextCallback callback); // Set custom file text data saver - -// Files management functions -RLAPI unsigned char *LoadFileData(const char *fileName, int *dataSize); // Load file data as byte array (read) -RLAPI void UnloadFileData(unsigned char *data); // Unload file data allocated by LoadFileData() -RLAPI bool SaveFileData(const char *fileName, void *data, int dataSize); // Save data to file from byte array (write), returns true on success -RLAPI bool ExportDataAsCode(const unsigned char *data, int dataSize, const char *fileName); // Export data to code (.h), returns true on success -RLAPI char *LoadFileText(const char *fileName); // Load text data from file (read), returns a '\0' terminated string -RLAPI void UnloadFileText(char *text); // Unload file text data allocated by LoadFileText() -RLAPI bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated, returns true on success -//------------------------------------------------------------------ - -// File system functions -RLAPI bool FileExists(const char *fileName); // Check if file exists -RLAPI bool DirectoryExists(const char *dirPath); // Check if a directory path exists -RLAPI bool IsFileExtension(const char *fileName, const char *ext); // Check file extension (including point: .png, .wav) -RLAPI int GetFileLength(const char *fileName); // Get file length in bytes (NOTE: GetFileSize() conflicts with windows.h) -RLAPI const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes dot: '.png') -RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string -RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string) -RLAPI const char *GetDirectoryPath(const char *filePath); // Get full path for a given fileName with path (uses static string) -RLAPI const char *GetPrevDirectoryPath(const char *dirPath); // Get previous directory path for a given path (uses static string) -RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string) -RLAPI const char *GetApplicationDirectory(void); // Get the directory of the running application (uses static string) -RLAPI bool ChangeDirectory(const char *dir); // Change working directory, return true on success -RLAPI bool IsPathFile(const char *path); // Check if a given path is a file or a directory -RLAPI FilePathList LoadDirectoryFiles(const char *dirPath); // Load directory filepaths -RLAPI FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs); // Load directory filepaths with extension filtering and recursive directory scan -RLAPI void UnloadDirectoryFiles(FilePathList files); // Unload filepaths -RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window -RLAPI FilePathList LoadDroppedFiles(void); // Load dropped filepaths -RLAPI void UnloadDroppedFiles(FilePathList files); // Unload dropped filepaths -RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time) - -// Compression/Encoding functionality -RLAPI unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize); // Compress data (DEFLATE algorithm), memory must be MemFree() -RLAPI unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize); // Decompress data (DEFLATE algorithm), memory must be MemFree() -RLAPI char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize); // Encode data to Base64 string, memory must be MemFree() -RLAPI unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize); // Decode Base64 string data, memory must be MemFree() - -// Automation events functionality -RLAPI AutomationEventList LoadAutomationEventList(const char *fileName); // Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS -RLAPI void UnloadAutomationEventList(AutomationEventList *list); // Unload automation events list from file -RLAPI bool ExportAutomationEventList(AutomationEventList list, const char *fileName); // Export automation events list as text file -RLAPI void SetAutomationEventList(AutomationEventList *list); // Set automation event list to record to -RLAPI void SetAutomationEventBaseFrame(int frame); // Set automation event internal base frame to start recording -RLAPI void StartAutomationEventRecording(void); // Start recording automation events (AutomationEventList must be set) -RLAPI void StopAutomationEventRecording(void); // Stop recording automation events -RLAPI void PlayAutomationEvent(AutomationEvent event); // Play a recorded automation event - -//------------------------------------------------------------------------------------ -// Input Handling Functions (Module: core) -//------------------------------------------------------------------------------------ - -// Input-related functions: keyboard -RLAPI bool IsKeyPressed(int key); // Check if a key has been pressed once -RLAPI bool IsKeyPressedRepeat(int key); // Check if a key has been pressed again (Only PLATFORM_DESKTOP) -RLAPI bool IsKeyDown(int key); // Check if a key is being pressed -RLAPI bool IsKeyReleased(int key); // Check if a key has been released once -RLAPI bool IsKeyUp(int key); // Check if a key is NOT being pressed -RLAPI int GetKeyPressed(void); // Get key pressed (keycode), call it multiple times for keys queued, returns 0 when the queue is empty -RLAPI int GetCharPressed(void); // Get char pressed (unicode), call it multiple times for chars queued, returns 0 when the queue is empty -RLAPI void SetExitKey(int key); // Set a custom key to exit program (default is ESC) - -// Input-related functions: gamepads -RLAPI bool IsGamepadAvailable(int gamepad); // Check if a gamepad is available -RLAPI const char *GetGamepadName(int gamepad); // Get gamepad internal name id -RLAPI bool IsGamepadButtonPressed(int gamepad, int button); // Check if a gamepad button has been pressed once -RLAPI bool IsGamepadButtonDown(int gamepad, int button); // Check if a gamepad button is being pressed -RLAPI bool IsGamepadButtonReleased(int gamepad, int button); // Check if a gamepad button has been released once -RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Check if a gamepad button is NOT being pressed -RLAPI int GetGamepadButtonPressed(void); // Get the last gamepad button pressed -RLAPI int GetGamepadAxisCount(int gamepad); // Get gamepad axis count for a gamepad -RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Get axis movement value for a gamepad axis -RLAPI int SetGamepadMappings(const char *mappings); // Set internal gamepad mappings (SDL_GameControllerDB) - -// Input-related functions: mouse -RLAPI bool IsMouseButtonPressed(int button); // Check if a mouse button has been pressed once -RLAPI bool IsMouseButtonDown(int button); // Check if a mouse button is being pressed -RLAPI bool IsMouseButtonReleased(int button); // Check if a mouse button has been released once -RLAPI bool IsMouseButtonUp(int button); // Check if a mouse button is NOT being pressed -RLAPI int GetMouseX(void); // Get mouse position X -RLAPI int GetMouseY(void); // Get mouse position Y -RLAPI Vector2 GetMousePosition(void); // Get mouse position XY -RLAPI Vector2 GetMouseDelta(void); // Get mouse delta between frames -RLAPI void SetMousePosition(int x, int y); // Set mouse position XY -RLAPI void SetMouseOffset(int offsetX, int offsetY); // Set mouse offset -RLAPI void SetMouseScale(float scaleX, float scaleY); // Set mouse scaling -RLAPI float GetMouseWheelMove(void); // Get mouse wheel movement for X or Y, whichever is larger -RLAPI Vector2 GetMouseWheelMoveV(void); // Get mouse wheel movement for both X and Y -RLAPI void SetMouseCursor(int cursor); // Set mouse cursor - -// Input-related functions: touch -RLAPI int GetTouchX(void); // Get touch position X for touch point 0 (relative to screen size) -RLAPI int GetTouchY(void); // Get touch position Y for touch point 0 (relative to screen size) -RLAPI Vector2 GetTouchPosition(int index); // Get touch position XY for a touch point index (relative to screen size) -RLAPI int GetTouchPointId(int index); // Get touch point identifier for given index -RLAPI int GetTouchPointCount(void); // Get number of touch points - -//------------------------------------------------------------------------------------ -// Gestures and Touch Handling Functions (Module: rgestures) -//------------------------------------------------------------------------------------ -RLAPI void SetGesturesEnabled(unsigned int flags); // Enable a set of gestures using flags -RLAPI bool IsGestureDetected(unsigned int gesture); // Check if a gesture have been detected -RLAPI int GetGestureDetected(void); // Get latest detected gesture -RLAPI float GetGestureHoldDuration(void); // Get gesture hold time in milliseconds -RLAPI Vector2 GetGestureDragVector(void); // Get gesture drag vector -RLAPI float GetGestureDragAngle(void); // Get gesture drag angle -RLAPI Vector2 GetGesturePinchVector(void); // Get gesture pinch delta -RLAPI float GetGesturePinchAngle(void); // Get gesture pinch angle - -//------------------------------------------------------------------------------------ -// Camera System Functions (Module: rcamera) -//------------------------------------------------------------------------------------ -RLAPI void UpdateCamera(Camera *camera, int mode); // Update camera position for selected mode -RLAPI void UpdateCameraPro(Camera *camera, Vector3 movement, Vector3 rotation, float zoom); // Update camera movement/rotation - -//------------------------------------------------------------------------------------ -// Basic Shapes Drawing Functions (Module: shapes) -//------------------------------------------------------------------------------------ -// Set texture and rectangle to be used on shapes drawing -// NOTE: It can be useful when using basic shapes and one single font, -// defining a font char white rectangle would allow drawing everything in a single draw call -RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Set texture and rectangle to be used on shapes drawing - -// Basic shapes drawing functions -RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel -RLAPI void DrawPixelV(Vector2 position, Color color); // Draw a pixel (Vector version) -RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line -RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (using gl lines) -RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line (using triangles/quads) -RLAPI void DrawLineStrip(Vector2 *points, int pointCount, Color color); // Draw lines sequence (using gl lines) -RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw line segment cubic-bezier in-out interpolation -RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle -RLAPI void DrawCircleSector(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw a piece of a circle -RLAPI void DrawCircleSectorLines(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw circle sector outline -RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2); // Draw a gradient-filled circle -RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) -RLAPI void DrawCircleLines(int centerX, int centerY, float radius, Color color); // Draw circle outline -RLAPI void DrawCircleLinesV(Vector2 center, float radius, Color color); // Draw circle outline (Vector version) -RLAPI void DrawEllipse(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse -RLAPI void DrawEllipseLines(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse outline -RLAPI void DrawRing(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring -RLAPI void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring outline -RLAPI void DrawRectangle(int posX, int posY, int width, int height, Color color); // Draw a color-filled rectangle -RLAPI void DrawRectangleV(Vector2 position, Vector2 size, Color color); // Draw a color-filled rectangle (Vector version) -RLAPI void DrawRectangleRec(Rectangle rec, Color color); // Draw a color-filled rectangle -RLAPI void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color); // Draw a color-filled rectangle with pro parameters -RLAPI void DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2);// Draw a vertical-gradient-filled rectangle -RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Color color1, Color color2);// Draw a horizontal-gradient-filled rectangle -RLAPI void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4); // Draw a gradient-filled rectangle with custom vertex colors -RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline -RLAPI void DrawRectangleLinesEx(Rectangle rec, float lineThick, Color color); // Draw rectangle outline with extended parameters -RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges -RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, float lineThick, Color color); // Draw rectangle with rounded edges outline -RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) -RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline (vertex in counter-clockwise order!) -RLAPI void DrawTriangleFan(Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points (first vertex is the center) -RLAPI void DrawTriangleStrip(Vector2 *points, int pointCount, Color color); // Draw a triangle strip defined by points -RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) -RLAPI void DrawPolyLines(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a polygon outline of n sides -RLAPI void DrawPolyLinesEx(Vector2 center, int sides, float radius, float rotation, float lineThick, Color color); // Draw a polygon outline of n sides with extended parameters - -// Splines drawing functions -RLAPI void DrawSplineLinear(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Linear, minimum 2 points -RLAPI void DrawSplineBasis(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: B-Spline, minimum 4 points -RLAPI void DrawSplineCatmullRom(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Catmull-Rom, minimum 4 points -RLAPI void DrawSplineBezierQuadratic(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Quadratic Bezier, minimum 3 points (1 control point): [p1, c2, p3, c4...] -RLAPI void DrawSplineBezierCubic(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Cubic Bezier, minimum 4 points (2 control points): [p1, c2, c3, p4, c5, c6...] -RLAPI void DrawSplineSegmentLinear(Vector2 p1, Vector2 p2, float thick, Color color); // Draw spline segment: Linear, 2 points -RLAPI void DrawSplineSegmentBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: B-Spline, 4 points -RLAPI void DrawSplineSegmentCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: Catmull-Rom, 4 points -RLAPI void DrawSplineSegmentBezierQuadratic(Vector2 p1, Vector2 c2, Vector2 p3, float thick, Color color); // Draw spline segment: Quadratic Bezier, 2 points, 1 control point -RLAPI void DrawSplineSegmentBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float thick, Color color); // Draw spline segment: Cubic Bezier, 2 points, 2 control points - -// Spline segment point evaluation functions, for a given t [0.0f .. 1.0f] -RLAPI Vector2 GetSplinePointLinear(Vector2 startPos, Vector2 endPos, float t); // Get (evaluate) spline point: Linear -RLAPI Vector2 GetSplinePointBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: B-Spline -RLAPI Vector2 GetSplinePointCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: Catmull-Rom -RLAPI Vector2 GetSplinePointBezierQuad(Vector2 p1, Vector2 c2, Vector2 p3, float t); // Get (evaluate) spline point: Quadratic Bezier -RLAPI Vector2 GetSplinePointBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float t); // Get (evaluate) spline point: Cubic Bezier - -// Basic shapes collision detection functions -RLAPI bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2); // Check collision between two rectangles -RLAPI bool CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2); // Check collision between two circles -RLAPI bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec); // Check collision between circle and rectangle -RLAPI bool CheckCollisionPointRec(Vector2 point, Rectangle rec); // Check if point is inside rectangle -RLAPI bool CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius); // Check if point is inside circle -RLAPI bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3); // Check if point is inside a triangle -RLAPI bool CheckCollisionPointPoly(Vector2 point, Vector2 *points, int pointCount); // Check if point is within a polygon described by array of vertices -RLAPI bool CheckCollisionLines(Vector2 startPos1, Vector2 endPos1, Vector2 startPos2, Vector2 endPos2, Vector2 *collisionPoint); // Check the collision between two lines defined by two points each, returns collision point by reference -RLAPI bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshold); // Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] -RLAPI Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2); // Get collision rectangle for two rectangles collision - -//------------------------------------------------------------------------------------ -// Texture Loading and Drawing Functions (Module: textures) -//------------------------------------------------------------------------------------ - -// Image loading functions -// NOTE: These functions do not require GPU access -RLAPI Image LoadImage(const char *fileName); // Load image from file into CPU memory (RAM) -RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize); // Load image from RAW file data -RLAPI Image LoadImageSvg(const char *fileNameOrString, int width, int height); // Load image from SVG file data or string with specified size -RLAPI Image LoadImageAnim(const char *fileName, int *frames); // Load image sequence from file (frames appended to image.data) -RLAPI Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load image from memory buffer, fileType refers to extension: i.e. '.png' -RLAPI Image LoadImageFromTexture(Texture2D texture); // Load image from GPU texture data -RLAPI Image LoadImageFromScreen(void); // Load image from screen buffer and (screenshot) -RLAPI bool IsImageReady(Image image); // Check if an image is ready -RLAPI void UnloadImage(Image image); // Unload image from CPU memory (RAM) -RLAPI bool ExportImage(Image image, const char *fileName); // Export image data to file, returns true on success -RLAPI unsigned char *ExportImageToMemory(Image image, const char *fileType, int *fileSize); // Export image to memory buffer -RLAPI bool ExportImageAsCode(Image image, const char *fileName); // Export image as code file defining an array of bytes, returns true on success - -// Image generation functions -RLAPI Image GenImageColor(int width, int height, Color color); // Generate image: plain color -RLAPI Image GenImageGradientLinear(int width, int height, int direction, Color start, Color end); // Generate image: linear gradient, direction in degrees [0..360], 0=Vertical gradient -RLAPI Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer); // Generate image: radial gradient -RLAPI Image GenImageGradientSquare(int width, int height, float density, Color inner, Color outer); // Generate image: square gradient -RLAPI Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2); // Generate image: checked -RLAPI Image GenImageWhiteNoise(int width, int height, float factor); // Generate image: white noise -RLAPI Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale); // Generate image: perlin noise -RLAPI Image GenImageCellular(int width, int height, int tileSize); // Generate image: cellular algorithm, bigger tileSize means bigger cells -RLAPI Image GenImageText(int width, int height, const char *text); // Generate image: grayscale image from text data - -// Image manipulation functions -RLAPI Image ImageCopy(Image image); // Create an image duplicate (useful for transformations) -RLAPI Image ImageFromImage(Image image, Rectangle rec); // Create an image from another image piece -RLAPI Image ImageText(const char *text, int fontSize, Color color); // Create an image from text (default font) -RLAPI Image ImageTextEx(Font font, const char *text, float fontSize, float spacing, Color tint); // Create an image from text (custom sprite font) -RLAPI void ImageFormat(Image *image, int newFormat); // Convert image data to desired format -RLAPI void ImageToPOT(Image *image, Color fill); // Convert image to POT (power-of-two) -RLAPI void ImageCrop(Image *image, Rectangle crop); // Crop an image to a defined rectangle -RLAPI void ImageAlphaCrop(Image *image, float threshold); // Crop image depending on alpha value -RLAPI void ImageAlphaClear(Image *image, Color color, float threshold); // Clear alpha channel to desired color -RLAPI void ImageAlphaMask(Image *image, Image alphaMask); // Apply alpha mask to image -RLAPI void ImageAlphaPremultiply(Image *image); // Premultiply alpha channel -RLAPI void ImageBlurGaussian(Image *image, int blurSize); // Apply Gaussian blur using a box blur approximation -RLAPI void ImageResize(Image *image, int newWidth, int newHeight); // Resize image (Bicubic scaling algorithm) -RLAPI void ImageResizeNN(Image *image, int newWidth,int newHeight); // Resize image (Nearest-Neighbor scaling algorithm) -RLAPI void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color fill); // Resize canvas and fill with color -RLAPI void ImageMipmaps(Image *image); // Compute all mipmap levels for a provided image -RLAPI void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp); // Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -RLAPI void ImageFlipVertical(Image *image); // Flip image vertically -RLAPI void ImageFlipHorizontal(Image *image); // Flip image horizontally -RLAPI void ImageRotate(Image *image, int degrees); // Rotate image by input angle in degrees (-359 to 359) -RLAPI void ImageRotateCW(Image *image); // Rotate image clockwise 90deg -RLAPI void ImageRotateCCW(Image *image); // Rotate image counter-clockwise 90deg -RLAPI void ImageColorTint(Image *image, Color color); // Modify image color: tint -RLAPI void ImageColorInvert(Image *image); // Modify image color: invert -RLAPI void ImageColorGrayscale(Image *image); // Modify image color: grayscale -RLAPI void ImageColorContrast(Image *image, float contrast); // Modify image color: contrast (-100 to 100) -RLAPI void ImageColorBrightness(Image *image, int brightness); // Modify image color: brightness (-255 to 255) -RLAPI void ImageColorReplace(Image *image, Color color, Color replace); // Modify image color: replace color -RLAPI Color *LoadImageColors(Image image); // Load color data from image as a Color array (RGBA - 32bit) -RLAPI Color *LoadImagePalette(Image image, int maxPaletteSize, int *colorCount); // Load colors palette from image as a Color array (RGBA - 32bit) -RLAPI void UnloadImageColors(Color *colors); // Unload color data loaded with LoadImageColors() -RLAPI void UnloadImagePalette(Color *colors); // Unload colors palette loaded with LoadImagePalette() -RLAPI Rectangle GetImageAlphaBorder(Image image, float threshold); // Get image alpha border rectangle -RLAPI Color GetImageColor(Image image, int x, int y); // Get image pixel color at (x, y) position - -// Image drawing functions -// NOTE: Image software-rendering functions (CPU) -RLAPI void ImageClearBackground(Image *dst, Color color); // Clear image background with given color -RLAPI void ImageDrawPixel(Image *dst, int posX, int posY, Color color); // Draw pixel within an image -RLAPI void ImageDrawPixelV(Image *dst, Vector2 position, Color color); // Draw pixel within an image (Vector version) -RLAPI void ImageDrawLine(Image *dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw line within an image -RLAPI void ImageDrawLineV(Image *dst, Vector2 start, Vector2 end, Color color); // Draw line within an image (Vector version) -RLAPI void ImageDrawCircle(Image *dst, int centerX, int centerY, int radius, Color color); // Draw a filled circle within an image -RLAPI void ImageDrawCircleV(Image *dst, Vector2 center, int radius, Color color); // Draw a filled circle within an image (Vector version) -RLAPI void ImageDrawCircleLines(Image *dst, int centerX, int centerY, int radius, Color color); // Draw circle outline within an image -RLAPI void ImageDrawCircleLinesV(Image *dst, Vector2 center, int radius, Color color); // Draw circle outline within an image (Vector version) -RLAPI void ImageDrawRectangle(Image *dst, int posX, int posY, int width, int height, Color color); // Draw rectangle within an image -RLAPI void ImageDrawRectangleV(Image *dst, Vector2 position, Vector2 size, Color color); // Draw rectangle within an image (Vector version) -RLAPI void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color); // Draw rectangle within an image -RLAPI void ImageDrawRectangleLines(Image *dst, Rectangle rec, int thick, Color color); // Draw rectangle lines within an image -RLAPI void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint); // Draw a source image within a destination image (tint applied to source) -RLAPI void ImageDrawText(Image *dst, const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) within an image (destination) -RLAPI void ImageDrawTextEx(Image *dst, Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text (custom sprite font) within an image (destination) - -// Texture loading functions -// NOTE: These functions require GPU access -RLAPI Texture2D LoadTexture(const char *fileName); // Load texture from file into GPU memory (VRAM) -RLAPI Texture2D LoadTextureFromImage(Image image); // Load texture from image data -RLAPI TextureCubemap LoadTextureCubemap(Image image, int layout); // Load cubemap from image, multiple image cubemap layouts supported -RLAPI RenderTexture2D LoadRenderTexture(int width, int height); // Load texture for rendering (framebuffer) -RLAPI bool IsTextureReady(Texture2D texture); // Check if a texture is ready -RLAPI void UnloadTexture(Texture2D texture); // Unload texture from GPU memory (VRAM) -RLAPI bool IsRenderTextureReady(RenderTexture2D target); // Check if a render texture is ready -RLAPI void UnloadRenderTexture(RenderTexture2D target); // Unload render texture from GPU memory (VRAM) -RLAPI void UpdateTexture(Texture2D texture, const void *pixels); // Update GPU texture with new data -RLAPI void UpdateTextureRec(Texture2D texture, Rectangle rec, const void *pixels); // Update GPU texture rectangle with new data - -// Texture configuration functions -RLAPI void GenTextureMipmaps(Texture2D *texture); // Generate GPU mipmaps for a texture -RLAPI void SetTextureFilter(Texture2D texture, int filter); // Set texture scaling filter mode -RLAPI void SetTextureWrap(Texture2D texture, int wrap); // Set texture wrapping mode - -// Texture drawing functions -RLAPI void DrawTexture(Texture2D texture, int posX, int posY, Color tint); // Draw a Texture2D -RLAPI void DrawTextureV(Texture2D texture, Vector2 position, Color tint); // Draw a Texture2D with position defined as Vector2 -RLAPI void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint); // Draw a Texture2D with extended parameters -RLAPI void DrawTextureRec(Texture2D texture, Rectangle source, Vector2 position, Color tint); // Draw a part of a texture defined by a rectangle -RLAPI void DrawTexturePro(Texture2D texture, Rectangle source, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draw a part of a texture defined by a rectangle with 'pro' parameters -RLAPI void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draws a texture (or part of it) that stretches or shrinks nicely - -// Color/pixel related functions -RLAPI Color Fade(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f -RLAPI int ColorToInt(Color color); // Get hexadecimal value for a Color -RLAPI Vector4 ColorNormalize(Color color); // Get Color normalized as float [0..1] -RLAPI Color ColorFromNormalized(Vector4 normalized); // Get Color from normalized values [0..1] -RLAPI Vector3 ColorToHSV(Color color); // Get HSV values for a Color, hue [0..360], saturation/value [0..1] -RLAPI Color ColorFromHSV(float hue, float saturation, float value); // Get a Color from HSV values, hue [0..360], saturation/value [0..1] -RLAPI Color ColorTint(Color color, Color tint); // Get color multiplied with another color -RLAPI Color ColorBrightness(Color color, float factor); // Get color with brightness correction, brightness factor goes from -1.0f to 1.0f -RLAPI Color ColorContrast(Color color, float contrast); // Get color with contrast correction, contrast values between -1.0f and 1.0f -RLAPI Color ColorAlpha(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f -RLAPI Color ColorAlphaBlend(Color dst, Color src, Color tint); // Get src alpha-blended into dst color with tint -RLAPI Color GetColor(unsigned int hexValue); // Get Color structure from hexadecimal value -RLAPI Color GetPixelColor(void *srcPtr, int format); // Get Color from a source pixel pointer of certain format -RLAPI void SetPixelColor(void *dstPtr, Color color, int format); // Set color formatted into destination pixel pointer -RLAPI int GetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes for certain format - -//------------------------------------------------------------------------------------ -// Font Loading and Text Drawing Functions (Module: text) -//------------------------------------------------------------------------------------ - -// Font loading/unloading functions -RLAPI Font GetFontDefault(void); // Get the default Font -RLAPI Font LoadFont(const char *fileName); // Load font from file into GPU memory (VRAM) -RLAPI Font LoadFontEx(const char *fileName, int fontSize, int *codepoints, int codepointCount); // Load font from file with extended parameters, use NULL for codepoints and 0 for codepointCount to load the default character set -RLAPI Font LoadFontFromImage(Image image, Color key, int firstChar); // Load font from Image (XNA style) -RLAPI Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount); // Load font from memory buffer, fileType refers to extension: i.e. '.ttf' -RLAPI bool IsFontReady(Font font); // Check if a font is ready -RLAPI GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount, int type); // Load font data for further use -RLAPI Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyphCount, int fontSize, int padding, int packMethod); // Generate image font atlas using chars info -RLAPI void UnloadFontData(GlyphInfo *glyphs, int glyphCount); // Unload font chars info data (RAM) -RLAPI void UnloadFont(Font font); // Unload font from GPU memory (VRAM) -RLAPI bool ExportFontAsCode(Font font, const char *fileName); // Export font as code file, returns true on success - -// Text drawing functions -RLAPI void DrawFPS(int posX, int posY); // Draw current FPS -RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) -RLAPI void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters -RLAPI void DrawTextPro(Font font, const char *text, Vector2 position, Vector2 origin, float rotation, float fontSize, float spacing, Color tint); // Draw text using Font and pro parameters (rotation) -RLAPI void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float fontSize, Color tint); // Draw one character (codepoint) -RLAPI void DrawTextCodepoints(Font font, const int *codepoints, int codepointCount, Vector2 position, float fontSize, float spacing, Color tint); // Draw multiple character (codepoint) - -// Text font info functions -RLAPI void SetTextLineSpacing(int spacing); // Set vertical line spacing when drawing with line-breaks -RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font -RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font -RLAPI int GetGlyphIndex(Font font, int codepoint); // Get glyph index position in font for a codepoint (unicode character), fallback to '?' if not found -RLAPI GlyphInfo GetGlyphInfo(Font font, int codepoint); // Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found -RLAPI Rectangle GetGlyphAtlasRec(Font font, int codepoint); // Get glyph rectangle in font atlas for a codepoint (unicode character), fallback to '?' if not found - -// Text codepoints management functions (unicode characters) -RLAPI char *LoadUTF8(const int *codepoints, int length); // Load UTF-8 text encoded from codepoints array -RLAPI void UnloadUTF8(char *text); // Unload UTF-8 text encoded from codepoints array -RLAPI int *LoadCodepoints(const char *text, int *count); // Load all codepoints from a UTF-8 text string, codepoints count returned by parameter -RLAPI void UnloadCodepoints(int *codepoints); // Unload codepoints data from memory -RLAPI int GetCodepointCount(const char *text); // Get total number of codepoints in a UTF-8 encoded string -RLAPI int GetCodepoint(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI int GetCodepointNext(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI int GetCodepointPrevious(const char *text, int *codepointSize); // Get previous codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI const char *CodepointToUTF8(int codepoint, int *utf8Size); // Encode one codepoint into UTF-8 byte array (array length returned as parameter) - -// Text strings management functions (no UTF-8 strings, only byte chars) -// NOTE: Some strings allocate memory internally for returned strings, just be careful! -RLAPI int TextCopy(char *dst, const char *src); // Copy one string to another, returns bytes copied -RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal -RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending -RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf() style) -RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string -RLAPI char *TextReplace(char *text, const char *replace, const char *by); // Replace text string (WARNING: memory must be freed!) -RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (WARNING: memory must be freed!) -RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter -RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings -RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor! -RLAPI int TextFindIndex(const char *text, const char *find); // Find first text occurrence within a string -RLAPI const char *TextToUpper(const char *text); // Get upper case version of provided string -RLAPI const char *TextToLower(const char *text); // Get lower case version of provided string -RLAPI const char *TextToPascal(const char *text); // Get Pascal case notation version of provided string -RLAPI int TextToInteger(const char *text); // Get integer value from text (negative values not supported) - -//------------------------------------------------------------------------------------ -// Basic 3d Shapes Drawing Functions (Module: models) -//------------------------------------------------------------------------------------ - -// Basic geometric 3D shapes drawing functions -RLAPI void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color); // Draw a line in 3D world space -RLAPI void DrawPoint3D(Vector3 position, Color color); // Draw a point in 3D space, actually a small line -RLAPI void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color); // Draw a circle in 3D world space -RLAPI void DrawTriangle3D(Vector3 v1, Vector3 v2, Vector3 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) -RLAPI void DrawTriangleStrip3D(Vector3 *points, int pointCount, Color color); // Draw a triangle strip defined by points -RLAPI void DrawCube(Vector3 position, float width, float height, float length, Color color); // Draw cube -RLAPI void DrawCubeV(Vector3 position, Vector3 size, Color color); // Draw cube (Vector version) -RLAPI void DrawCubeWires(Vector3 position, float width, float height, float length, Color color); // Draw cube wires -RLAPI void DrawCubeWiresV(Vector3 position, Vector3 size, Color color); // Draw cube wires (Vector version) -RLAPI void DrawSphere(Vector3 centerPos, float radius, Color color); // Draw sphere -RLAPI void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere with extended parameters -RLAPI void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere wires -RLAPI void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone -RLAPI void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder with base at startPos and top at endPos -RLAPI void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone wires -RLAPI void DrawCylinderWiresEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder wires with base at startPos and top at endPos -RLAPI void DrawCapsule(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw a capsule with the center of its sphere caps at startPos and endPos -RLAPI void DrawCapsuleWires(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw capsule wireframe with the center of its sphere caps at startPos and endPos -RLAPI void DrawPlane(Vector3 centerPos, Vector2 size, Color color); // Draw a plane XZ -RLAPI void DrawRay(Ray ray, Color color); // Draw a ray line -RLAPI void DrawGrid(int slices, float spacing); // Draw a grid (centered at (0, 0, 0)) - -//------------------------------------------------------------------------------------ -// Model 3d Loading and Drawing Functions (Module: models) -//------------------------------------------------------------------------------------ - -// Model management functions -RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) -RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh (default material) -RLAPI bool IsModelReady(Model model); // Check if a model is ready -RLAPI void UnloadModel(Model model); // Unload model (including meshes) from memory (RAM and/or VRAM) -RLAPI BoundingBox GetModelBoundingBox(Model model); // Compute model bounding box limits (considers all meshes) - -// Model drawing functions -RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) -RLAPI void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model with extended parameters -RLAPI void DrawModelWires(Model model, Vector3 position, float scale, Color tint); // Draw a model wires (with texture if set) -RLAPI void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model wires (with texture if set) with extended parameters -RLAPI void DrawBoundingBox(BoundingBox box, Color color); // Draw bounding box (wires) -RLAPI void DrawBillboard(Camera camera, Texture2D texture, Vector3 position, float size, Color tint); // Draw a billboard texture -RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector2 size, Color tint); // Draw a billboard texture defined by source -RLAPI void DrawBillboardPro(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector3 up, Vector2 size, Vector2 origin, float rotation, Color tint); // Draw a billboard texture defined by source and rotation - -// Mesh management functions -RLAPI void UploadMesh(Mesh *mesh, bool dynamic); // Upload mesh vertex data in GPU and provide VAO/VBO ids -RLAPI void UpdateMeshBuffer(Mesh mesh, int index, const void *data, int dataSize, int offset); // Update mesh vertex data in GPU for a specific buffer index -RLAPI void UnloadMesh(Mesh mesh); // Unload mesh data from CPU and GPU -RLAPI void DrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform -RLAPI void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, int instances); // Draw multiple mesh instances with material and different transforms -RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success -RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits -RLAPI void GenMeshTangents(Mesh *mesh); // Compute mesh tangents - -// Mesh generation functions -RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh -RLAPI Mesh GenMeshPlane(float width, float length, int resX, int resZ); // Generate plane mesh (with subdivisions) -RLAPI Mesh GenMeshCube(float width, float height, float length); // Generate cuboid mesh -RLAPI Mesh GenMeshSphere(float radius, int rings, int slices); // Generate sphere mesh (standard sphere) -RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices); // Generate half-sphere mesh (no bottom cap) -RLAPI Mesh GenMeshCylinder(float radius, float height, int slices); // Generate cylinder mesh -RLAPI Mesh GenMeshCone(float radius, float height, int slices); // Generate cone/pyramid mesh -RLAPI Mesh GenMeshTorus(float radius, float size, int radSeg, int sides); // Generate torus mesh -RLAPI Mesh GenMeshKnot(float radius, float size, int radSeg, int sides); // Generate trefoil knot mesh -RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size); // Generate heightmap mesh from image data -RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data - -// Material loading/unloading functions -RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file -RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -RLAPI bool IsMaterialReady(Material material); // Check if a material is ready -RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) -RLAPI void SetMaterialTexture(Material *material, int mapType, Texture2D texture); // Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) -RLAPI void SetModelMeshMaterial(Model *model, int meshId, int materialId); // Set material for a mesh - -// Model animations loading/unloading functions -RLAPI ModelAnimation *LoadModelAnimations(const char *fileName, int *animCount); // Load model animations from file -RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose -RLAPI void UnloadModelAnimation(ModelAnimation anim); // Unload animation data -RLAPI void UnloadModelAnimations(ModelAnimation *animations, int animCount); // Unload animation array data -RLAPI bool IsModelAnimationValid(Model model, ModelAnimation anim); // Check model animation skeleton match - -// Collision detection functions -RLAPI bool CheckCollisionSpheres(Vector3 center1, float radius1, Vector3 center2, float radius2); // Check collision between two spheres -RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Check collision between two bounding boxes -RLAPI bool CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius); // Check collision between box and sphere -RLAPI RayCollision GetRayCollisionSphere(Ray ray, Vector3 center, float radius); // Get collision info between ray and sphere -RLAPI RayCollision GetRayCollisionBox(Ray ray, BoundingBox box); // Get collision info between ray and box -RLAPI RayCollision GetRayCollisionMesh(Ray ray, Mesh mesh, Matrix transform); // Get collision info between ray and mesh -RLAPI RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3); // Get collision info between ray and triangle -RLAPI RayCollision GetRayCollisionQuad(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4); // Get collision info between ray and quad - -//------------------------------------------------------------------------------------ -// Audio Loading and Playing Functions (Module: audio) -//------------------------------------------------------------------------------------ -typedef void (*AudioCallback)(void *bufferData, unsigned int frames); - -// Audio device management functions -RLAPI void InitAudioDevice(void); // Initialize audio device and context -RLAPI void CloseAudioDevice(void); // Close the audio device and context -RLAPI bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully -RLAPI void SetMasterVolume(float volume); // Set master volume (listener) -RLAPI float GetMasterVolume(void); // Get master volume (listener) - -// Wave/Sound loading/unloading functions -RLAPI Wave LoadWave(const char *fileName); // Load wave data from file -RLAPI Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load wave from memory buffer, fileType refers to extension: i.e. '.wav' -RLAPI bool IsWaveReady(Wave wave); // Checks if wave data is ready -RLAPI Sound LoadSound(const char *fileName); // Load sound from file -RLAPI Sound LoadSoundFromWave(Wave wave); // Load sound from wave data -RLAPI Sound LoadSoundAlias(Sound source); // Create a new sound that shares the same sample data as the source sound, does not own the sound data -RLAPI bool IsSoundReady(Sound sound); // Checks if a sound is ready -RLAPI void UpdateSound(Sound sound, const void *data, int sampleCount); // Update sound buffer with new data -RLAPI void UnloadWave(Wave wave); // Unload wave data -RLAPI void UnloadSound(Sound sound); // Unload sound -RLAPI void UnloadSoundAlias(Sound alias); // Unload a sound alias (does not deallocate sample data) -RLAPI bool ExportWave(Wave wave, const char *fileName); // Export wave data to file, returns true on success -RLAPI bool ExportWaveAsCode(Wave wave, const char *fileName); // Export wave sample data to code (.h), returns true on success - -// Wave/Sound management functions -RLAPI void PlaySound(Sound sound); // Play a sound -RLAPI void StopSound(Sound sound); // Stop playing a sound -RLAPI void PauseSound(Sound sound); // Pause a sound -RLAPI void ResumeSound(Sound sound); // Resume a paused sound -RLAPI bool IsSoundPlaying(Sound sound); // Check if a sound is currently playing -RLAPI void SetSoundVolume(Sound sound, float volume); // Set volume for a sound (1.0 is max level) -RLAPI void SetSoundPitch(Sound sound, float pitch); // Set pitch for a sound (1.0 is base level) -RLAPI void SetSoundPan(Sound sound, float pan); // Set pan for a sound (0.5 is center) -RLAPI Wave WaveCopy(Wave wave); // Copy a wave to a new wave -RLAPI void WaveCrop(Wave *wave, int initSample, int finalSample); // Crop a wave to defined samples range -RLAPI void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); // Convert wave data to desired format -RLAPI float *LoadWaveSamples(Wave wave); // Load samples data from wave as a 32bit float data array -RLAPI void UnloadWaveSamples(float *samples); // Unload samples data loaded with LoadWaveSamples() - -// Music management functions -RLAPI Music LoadMusicStream(const char *fileName); // Load music stream from file -RLAPI Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, int dataSize); // Load music stream from data -RLAPI bool IsMusicReady(Music music); // Checks if a music stream is ready -RLAPI void UnloadMusicStream(Music music); // Unload music stream -RLAPI void PlayMusicStream(Music music); // Start music playing -RLAPI bool IsMusicStreamPlaying(Music music); // Check if music is playing -RLAPI void UpdateMusicStream(Music music); // Updates buffers for music streaming -RLAPI void StopMusicStream(Music music); // Stop music playing -RLAPI void PauseMusicStream(Music music); // Pause music playing -RLAPI void ResumeMusicStream(Music music); // Resume playing paused music -RLAPI void SeekMusicStream(Music music, float position); // Seek music to a position (in seconds) -RLAPI void SetMusicVolume(Music music, float volume); // Set volume for music (1.0 is max level) -RLAPI void SetMusicPitch(Music music, float pitch); // Set pitch for a music (1.0 is base level) -RLAPI void SetMusicPan(Music music, float pan); // Set pan for a music (0.5 is center) -RLAPI float GetMusicTimeLength(Music music); // Get music time length (in seconds) -RLAPI float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) - -// AudioStream management functions -RLAPI AudioStream LoadAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Load audio stream (to stream raw audio pcm data) -RLAPI bool IsAudioStreamReady(AudioStream stream); // Checks if an audio stream is ready -RLAPI void UnloadAudioStream(AudioStream stream); // Unload audio stream and free memory -RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int frameCount); // Update audio stream buffers with data -RLAPI bool IsAudioStreamProcessed(AudioStream stream); // Check if any audio stream buffers requires refill -RLAPI void PlayAudioStream(AudioStream stream); // Play audio stream -RLAPI void PauseAudioStream(AudioStream stream); // Pause audio stream -RLAPI void ResumeAudioStream(AudioStream stream); // Resume audio stream -RLAPI bool IsAudioStreamPlaying(AudioStream stream); // Check if audio stream is playing -RLAPI void StopAudioStream(AudioStream stream); // Stop audio stream -RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level) -RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level) -RLAPI void SetAudioStreamPan(AudioStream stream, float pan); // Set pan for audio stream (0.5 is centered) -RLAPI void SetAudioStreamBufferSizeDefault(int size); // Default size for new audio streams -RLAPI void SetAudioStreamCallback(AudioStream stream, AudioCallback callback); // Audio thread callback to request new data - -RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Attach audio stream processor to stream, receives the samples as s -RLAPI void DetachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Detach audio stream processor from stream - -RLAPI void AttachAudioMixedProcessor(AudioCallback processor); // Attach audio stream processor to the entire audio pipeline, receives the samples as s -RLAPI void DetachAudioMixedProcessor(AudioCallback processor); // Detach audio stream processor from the entire audio pipeline - -#if defined(__cplusplus) -} -#endif - -#endif // RAYLIB_H diff --git a/third_party/raylib/include/raymath.h b/third_party/raylib/include/raymath.h deleted file mode 100644 index ff601703905b8e..00000000000000 --- a/third_party/raylib/include/raymath.h +++ /dev/null @@ -1,2190 +0,0 @@ -/********************************************************************************************** -* -* raymath v1.5 - Math functions to work with Vector2, Vector3, Matrix and Quaternions -* -* CONVENTIONS: -* - Matrix structure is defined as row-major (memory layout) but parameters naming AND all -* math operations performed by the library consider the structure as it was column-major -* It is like transposed versions of the matrices are used for all the maths -* It benefits some functions making them cache-friendly and also avoids matrix -* transpositions sometimes required by OpenGL -* Example: In memory order, row0 is [m0 m4 m8 m12] but in semantic math row0 is [m0 m1 m2 m3] -* - Functions are always self-contained, no function use another raymath function inside, -* required code is directly re-implemented inside -* - Functions input parameters are always received by value (2 unavoidable exceptions) -* - Functions use always a "result" variable for return -* - Functions are always defined inline -* - Angles are always in radians (DEG2RAD/RAD2DEG macros provided for convenience) -* - No compound literals used to make sure libray is compatible with C++ -* -* CONFIGURATION: -* #define RAYMATH_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define RAYMATH_STATIC_INLINE -* Define static inline functions code, so #include header suffices for use. -* This may use up lots of memory. -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2015-2023 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYMATH_H -#define RAYMATH_H - -#if defined(RAYMATH_IMPLEMENTATION) && defined(RAYMATH_STATIC_INLINE) - #error "Specifying both RAYMATH_IMPLEMENTATION and RAYMATH_STATIC_INLINE is contradictory" -#endif - -// Function specifiers definition -#if defined(RAYMATH_IMPLEMENTATION) - #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) - #define RMAPI __declspec(dllexport) extern inline // We are building raylib as a Win32 shared library (.dll). - #elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) - #define RMAPI __declspec(dllimport) // We are using raylib as a Win32 shared library (.dll) - #else - #define RMAPI extern inline // Provide external definition - #endif -#elif defined(RAYMATH_STATIC_INLINE) - #define RMAPI static inline // Functions may be inlined, no external out-of-line definition -#else - #if defined(__TINYC__) - #define RMAPI static inline // plain inline not supported by tinycc (See issue #435) - #else - #define RMAPI inline // Functions may be inlined or external definition used - #endif -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif - -#ifndef EPSILON - #define EPSILON 0.000001f -#endif - -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif - -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -// Get float vector for Matrix -#ifndef MatrixToFloat - #define MatrixToFloat(mat) (MatrixToFloatV(mat).v) -#endif - -// Get float vector for Vector3 -#ifndef Vector3ToFloat - #define Vector3ToFloat(vec) (Vector3ToFloatV(vec).v) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if !defined(RL_VECTOR2_TYPE) -// Vector2 type -typedef struct Vector2 { - float x; - float y; -} Vector2; -#define RL_VECTOR2_TYPE -#endif - -#if !defined(RL_VECTOR3_TYPE) -// Vector3 type -typedef struct Vector3 { - float x; - float y; - float z; -} Vector3; -#define RL_VECTOR3_TYPE -#endif - -#if !defined(RL_VECTOR4_TYPE) -// Vector4 type -typedef struct Vector4 { - float x; - float y; - float z; - float w; -} Vector4; -#define RL_VECTOR4_TYPE -#endif - -#if !defined(RL_QUATERNION_TYPE) -// Quaternion type -typedef Vector4 Quaternion; -#define RL_QUATERNION_TYPE -#endif - -#if !defined(RL_MATRIX_TYPE) -// Matrix type (OpenGL style 4x4 - right handed, column major) -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; -#define RL_MATRIX_TYPE -#endif - -// NOTE: Helper types to be used instead of array return types for *ToFloat functions -typedef struct float3 { - float v[3]; -} float3; - -typedef struct float16 { - float v[16]; -} float16; - -#include // Required for: sinf(), cosf(), tan(), atan2f(), sqrtf(), floor(), fminf(), fmaxf(), fabs() - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Utils math -//---------------------------------------------------------------------------------- - -// Clamp float value -RMAPI float Clamp(float value, float min, float max) -{ - float result = (value < min)? min : value; - - if (result > max) result = max; - - return result; -} - -// Calculate linear interpolation between two floats -RMAPI float Lerp(float start, float end, float amount) -{ - float result = start + amount*(end - start); - - return result; -} - -// Normalize input value within input range -RMAPI float Normalize(float value, float start, float end) -{ - float result = (value - start)/(end - start); - - return result; -} - -// Remap input value within input range to output range -RMAPI float Remap(float value, float inputStart, float inputEnd, float outputStart, float outputEnd) -{ - float result = (value - inputStart)/(inputEnd - inputStart)*(outputEnd - outputStart) + outputStart; - - return result; -} - -// Wrap input value from min to max -RMAPI float Wrap(float value, float min, float max) -{ - float result = value - (max - min)*floorf((value - min)/(max - min)); - - return result; -} - -// Check whether two given floats are almost equal -RMAPI int FloatEquals(float x, float y) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = (fabsf(x - y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(x), fabsf(y)))); - - return result; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector2 math -//---------------------------------------------------------------------------------- - -// Vector with components value 0.0f -RMAPI Vector2 Vector2Zero(void) -{ - Vector2 result = { 0.0f, 0.0f }; - - return result; -} - -// Vector with components value 1.0f -RMAPI Vector2 Vector2One(void) -{ - Vector2 result = { 1.0f, 1.0f }; - - return result; -} - -// Add two vectors (v1 + v2) -RMAPI Vector2 Vector2Add(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x + v2.x, v1.y + v2.y }; - - return result; -} - -// Add vector and float value -RMAPI Vector2 Vector2AddValue(Vector2 v, float add) -{ - Vector2 result = { v.x + add, v.y + add }; - - return result; -} - -// Subtract two vectors (v1 - v2) -RMAPI Vector2 Vector2Subtract(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x - v2.x, v1.y - v2.y }; - - return result; -} - -// Subtract vector by float value -RMAPI Vector2 Vector2SubtractValue(Vector2 v, float sub) -{ - Vector2 result = { v.x - sub, v.y - sub }; - - return result; -} - -// Calculate vector length -RMAPI float Vector2Length(Vector2 v) -{ - float result = sqrtf((v.x*v.x) + (v.y*v.y)); - - return result; -} - -// Calculate vector square length -RMAPI float Vector2LengthSqr(Vector2 v) -{ - float result = (v.x*v.x) + (v.y*v.y); - - return result; -} - -// Calculate two vectors dot product -RMAPI float Vector2DotProduct(Vector2 v1, Vector2 v2) -{ - float result = (v1.x*v2.x + v1.y*v2.y); - - return result; -} - -// Calculate distance between two vectors -RMAPI float Vector2Distance(Vector2 v1, Vector2 v2) -{ - float result = sqrtf((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); - - return result; -} - -// Calculate square distance between two vectors -RMAPI float Vector2DistanceSqr(Vector2 v1, Vector2 v2) -{ - float result = ((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); - - return result; -} - -// Calculate angle between two vectors -// NOTE: Angle is calculated from origin point (0, 0) -RMAPI float Vector2Angle(Vector2 v1, Vector2 v2) -{ - float result = 0.0f; - - float dot = v1.x*v2.x + v1.y*v2.y; - float det = v1.x*v2.y - v1.y*v2.x; - - result = atan2f(det, dot); - - return result; -} - -// Calculate angle defined by a two vectors line -// NOTE: Parameters need to be normalized -// Current implementation should be aligned with glm::angle -RMAPI float Vector2LineAngle(Vector2 start, Vector2 end) -{ - float result = 0.0f; - - // TODO(10/9/2023): Currently angles move clockwise, determine if this is wanted behavior - result = -atan2f(end.y - start.y, end.x - start.x); - - return result; -} - -// Scale vector (multiply by value) -RMAPI Vector2 Vector2Scale(Vector2 v, float scale) -{ - Vector2 result = { v.x*scale, v.y*scale }; - - return result; -} - -// Multiply vector by vector -RMAPI Vector2 Vector2Multiply(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x*v2.x, v1.y*v2.y }; - - return result; -} - -// Negate vector -RMAPI Vector2 Vector2Negate(Vector2 v) -{ - Vector2 result = { -v.x, -v.y }; - - return result; -} - -// Divide vector by vector -RMAPI Vector2 Vector2Divide(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x/v2.x, v1.y/v2.y }; - - return result; -} - -// Normalize provided vector -RMAPI Vector2 Vector2Normalize(Vector2 v) -{ - Vector2 result = { 0 }; - float length = sqrtf((v.x*v.x) + (v.y*v.y)); - - if (length > 0) - { - float ilength = 1.0f/length; - result.x = v.x*ilength; - result.y = v.y*ilength; - } - - return result; -} - -// Transforms a Vector2 by a given Matrix -RMAPI Vector2 Vector2Transform(Vector2 v, Matrix mat) -{ - Vector2 result = { 0 }; - - float x = v.x; - float y = v.y; - float z = 0; - - result.x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; - result.y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; - - return result; -} - -// Calculate linear interpolation between two vectors -RMAPI Vector2 Vector2Lerp(Vector2 v1, Vector2 v2, float amount) -{ - Vector2 result = { 0 }; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - - return result; -} - -// Calculate reflected vector to normal -RMAPI Vector2 Vector2Reflect(Vector2 v, Vector2 normal) -{ - Vector2 result = { 0 }; - - float dotProduct = (v.x*normal.x + v.y*normal.y); // Dot product - - result.x = v.x - (2.0f*normal.x)*dotProduct; - result.y = v.y - (2.0f*normal.y)*dotProduct; - - return result; -} - -// Rotate vector by angle -RMAPI Vector2 Vector2Rotate(Vector2 v, float angle) -{ - Vector2 result = { 0 }; - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.x = v.x*cosres - v.y*sinres; - result.y = v.x*sinres + v.y*cosres; - - return result; -} - -// Move Vector towards target -RMAPI Vector2 Vector2MoveTowards(Vector2 v, Vector2 target, float maxDistance) -{ - Vector2 result = { 0 }; - - float dx = target.x - v.x; - float dy = target.y - v.y; - float value = (dx*dx) + (dy*dy); - - if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; - - float dist = sqrtf(value); - - result.x = v.x + dx/dist*maxDistance; - result.y = v.y + dy/dist*maxDistance; - - return result; -} - -// Invert the given vector -RMAPI Vector2 Vector2Invert(Vector2 v) -{ - Vector2 result = { 1.0f/v.x, 1.0f/v.y }; - - return result; -} - -// Clamp the components of the vector between -// min and max values specified by the given vectors -RMAPI Vector2 Vector2Clamp(Vector2 v, Vector2 min, Vector2 max) -{ - Vector2 result = { 0 }; - - result.x = fminf(max.x, fmaxf(min.x, v.x)); - result.y = fminf(max.y, fmaxf(min.y, v.y)); - - return result; -} - -// Clamp the magnitude of the vector between two min and max values -RMAPI Vector2 Vector2ClampValue(Vector2 v, float min, float max) -{ - Vector2 result = v; - - float length = (v.x*v.x) + (v.y*v.y); - if (length > 0.0f) - { - length = sqrtf(length); - - if (length < min) - { - float scale = min/length; - result.x = v.x*scale; - result.y = v.y*scale; - } - else if (length > max) - { - float scale = max/length; - result.x = v.x*scale; - result.y = v.y*scale; - } - } - - return result; -} - -// Check whether two given vectors are almost equal -RMAPI int Vector2Equals(Vector2 p, Vector2 q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))); - - return result; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector3 math -//---------------------------------------------------------------------------------- - -// Vector with components value 0.0f -RMAPI Vector3 Vector3Zero(void) -{ - Vector3 result = { 0.0f, 0.0f, 0.0f }; - - return result; -} - -// Vector with components value 1.0f -RMAPI Vector3 Vector3One(void) -{ - Vector3 result = { 1.0f, 1.0f, 1.0f }; - - return result; -} - -// Add two vectors -RMAPI Vector3 Vector3Add(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x + v2.x, v1.y + v2.y, v1.z + v2.z }; - - return result; -} - -// Add vector and float value -RMAPI Vector3 Vector3AddValue(Vector3 v, float add) -{ - Vector3 result = { v.x + add, v.y + add, v.z + add }; - - return result; -} - -// Subtract two vectors -RMAPI Vector3 Vector3Subtract(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x - v2.x, v1.y - v2.y, v1.z - v2.z }; - - return result; -} - -// Subtract vector by float value -RMAPI Vector3 Vector3SubtractValue(Vector3 v, float sub) -{ - Vector3 result = { v.x - sub, v.y - sub, v.z - sub }; - - return result; -} - -// Multiply vector by scalar -RMAPI Vector3 Vector3Scale(Vector3 v, float scalar) -{ - Vector3 result = { v.x*scalar, v.y*scalar, v.z*scalar }; - - return result; -} - -// Multiply vector by vector -RMAPI Vector3 Vector3Multiply(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x*v2.x, v1.y*v2.y, v1.z*v2.z }; - - return result; -} - -// Calculate two vectors cross product -RMAPI Vector3 Vector3CrossProduct(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x }; - - return result; -} - -// Calculate one vector perpendicular vector -RMAPI Vector3 Vector3Perpendicular(Vector3 v) -{ - Vector3 result = { 0 }; - - float min = (float) fabs(v.x); - Vector3 cardinalAxis = {1.0f, 0.0f, 0.0f}; - - if (fabsf(v.y) < min) - { - min = (float) fabs(v.y); - Vector3 tmp = {0.0f, 1.0f, 0.0f}; - cardinalAxis = tmp; - } - - if (fabsf(v.z) < min) - { - Vector3 tmp = {0.0f, 0.0f, 1.0f}; - cardinalAxis = tmp; - } - - // Cross product between vectors - result.x = v.y*cardinalAxis.z - v.z*cardinalAxis.y; - result.y = v.z*cardinalAxis.x - v.x*cardinalAxis.z; - result.z = v.x*cardinalAxis.y - v.y*cardinalAxis.x; - - return result; -} - -// Calculate vector length -RMAPI float Vector3Length(const Vector3 v) -{ - float result = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - - return result; -} - -// Calculate vector square length -RMAPI float Vector3LengthSqr(const Vector3 v) -{ - float result = v.x*v.x + v.y*v.y + v.z*v.z; - - return result; -} - -// Calculate two vectors dot product -RMAPI float Vector3DotProduct(Vector3 v1, Vector3 v2) -{ - float result = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - - return result; -} - -// Calculate distance between two vectors -RMAPI float Vector3Distance(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - float dz = v2.z - v1.z; - result = sqrtf(dx*dx + dy*dy + dz*dz); - - return result; -} - -// Calculate square distance between two vectors -RMAPI float Vector3DistanceSqr(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - float dz = v2.z - v1.z; - result = dx*dx + dy*dy + dz*dz; - - return result; -} - -// Calculate angle between two vectors -RMAPI float Vector3Angle(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - Vector3 cross = { v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x }; - float len = sqrtf(cross.x*cross.x + cross.y*cross.y + cross.z*cross.z); - float dot = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - result = atan2f(len, dot); - - return result; -} - -// Negate provided vector (invert direction) -RMAPI Vector3 Vector3Negate(Vector3 v) -{ - Vector3 result = { -v.x, -v.y, -v.z }; - - return result; -} - -// Divide vector by vector -RMAPI Vector3 Vector3Divide(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x/v2.x, v1.y/v2.y, v1.z/v2.z }; - - return result; -} - -// Normalize provided vector -RMAPI Vector3 Vector3Normalize(Vector3 v) -{ - Vector3 result = v; - - float length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length != 0.0f) - { - float ilength = 1.0f/length; - - result.x *= ilength; - result.y *= ilength; - result.z *= ilength; - } - - return result; -} - -//Calculate the projection of the vector v1 on to v2 -RMAPI Vector3 Vector3Project(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); - - float mag = v1dv2/v2dv2; - - result.x = v2.x*mag; - result.y = v2.y*mag; - result.z = v2.z*mag; - - return result; -} - -//Calculate the rejection of the vector v1 on to v2 -RMAPI Vector3 Vector3Reject(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); - - float mag = v1dv2/v2dv2; - - result.x = v1.x - (v2.x*mag); - result.y = v1.y - (v2.y*mag); - result.z = v1.z - (v2.z*mag); - - return result; -} - -// Orthonormalize provided vectors -// Makes vectors normalized and orthogonal to each other -// Gram-Schmidt function implementation -RMAPI void Vector3OrthoNormalize(Vector3 *v1, Vector3 *v2) -{ - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Normalize(*v1); - Vector3 v = *v1; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - v1->x *= ilength; - v1->y *= ilength; - v1->z *= ilength; - - // Vector3CrossProduct(*v1, *v2) - Vector3 vn1 = { v1->y*v2->z - v1->z*v2->y, v1->z*v2->x - v1->x*v2->z, v1->x*v2->y - v1->y*v2->x }; - - // Vector3Normalize(vn1); - v = vn1; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vn1.x *= ilength; - vn1.y *= ilength; - vn1.z *= ilength; - - // Vector3CrossProduct(vn1, *v1) - Vector3 vn2 = { vn1.y*v1->z - vn1.z*v1->y, vn1.z*v1->x - vn1.x*v1->z, vn1.x*v1->y - vn1.y*v1->x }; - - *v2 = vn2; -} - -// Transforms a Vector3 by a given Matrix -RMAPI Vector3 Vector3Transform(Vector3 v, Matrix mat) -{ - Vector3 result = { 0 }; - - float x = v.x; - float y = v.y; - float z = v.z; - - result.x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; - result.y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; - result.z = mat.m2*x + mat.m6*y + mat.m10*z + mat.m14; - - return result; -} - -// Transform a vector by quaternion rotation -RMAPI Vector3 Vector3RotateByQuaternion(Vector3 v, Quaternion q) -{ - Vector3 result = { 0 }; - - result.x = v.x*(q.x*q.x + q.w*q.w - q.y*q.y - q.z*q.z) + v.y*(2*q.x*q.y - 2*q.w*q.z) + v.z*(2*q.x*q.z + 2*q.w*q.y); - result.y = v.x*(2*q.w*q.z + 2*q.x*q.y) + v.y*(q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z) + v.z*(-2*q.w*q.x + 2*q.y*q.z); - result.z = v.x*(-2*q.w*q.y + 2*q.x*q.z) + v.y*(2*q.w*q.x + 2*q.y*q.z)+ v.z*(q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z); - - return result; -} - -// Rotates a vector around an axis -RMAPI Vector3 Vector3RotateByAxisAngle(Vector3 v, Vector3 axis, float angle) -{ - // Using Euler-Rodrigues Formula - // Ref.: https://en.wikipedia.org/w/index.php?title=Euler%E2%80%93Rodrigues_formula - - Vector3 result = v; - - // Vector3Normalize(axis); - float length = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f / length; - axis.x *= ilength; - axis.y *= ilength; - axis.z *= ilength; - - angle /= 2.0f; - float a = sinf(angle); - float b = axis.x*a; - float c = axis.y*a; - float d = axis.z*a; - a = cosf(angle); - Vector3 w = { b, c, d }; - - // Vector3CrossProduct(w, v) - Vector3 wv = { w.y*v.z - w.z*v.y, w.z*v.x - w.x*v.z, w.x*v.y - w.y*v.x }; - - // Vector3CrossProduct(w, wv) - Vector3 wwv = { w.y*wv.z - w.z*wv.y, w.z*wv.x - w.x*wv.z, w.x*wv.y - w.y*wv.x }; - - // Vector3Scale(wv, 2*a) - a *= 2; - wv.x *= a; - wv.y *= a; - wv.z *= a; - - // Vector3Scale(wwv, 2) - wwv.x *= 2; - wwv.y *= 2; - wwv.z *= 2; - - result.x += wv.x; - result.y += wv.y; - result.z += wv.z; - - result.x += wwv.x; - result.y += wwv.y; - result.z += wwv.z; - - return result; -} - -// Calculate linear interpolation between two vectors -RMAPI Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount) -{ - Vector3 result = { 0 }; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - result.z = v1.z + amount*(v2.z - v1.z); - - return result; -} - -// Calculate reflected vector to normal -RMAPI Vector3 Vector3Reflect(Vector3 v, Vector3 normal) -{ - Vector3 result = { 0 }; - - // I is the original vector - // N is the normal of the incident plane - // R = I - (2*N*(DotProduct[I, N])) - - float dotProduct = (v.x*normal.x + v.y*normal.y + v.z*normal.z); - - result.x = v.x - (2.0f*normal.x)*dotProduct; - result.y = v.y - (2.0f*normal.y)*dotProduct; - result.z = v.z - (2.0f*normal.z)*dotProduct; - - return result; -} - -// Get min value for each pair of components -RMAPI Vector3 Vector3Min(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - result.x = fminf(v1.x, v2.x); - result.y = fminf(v1.y, v2.y); - result.z = fminf(v1.z, v2.z); - - return result; -} - -// Get max value for each pair of components -RMAPI Vector3 Vector3Max(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - result.x = fmaxf(v1.x, v2.x); - result.y = fmaxf(v1.y, v2.y); - result.z = fmaxf(v1.z, v2.z); - - return result; -} - -// Compute barycenter coordinates (u, v, w) for point p with respect to triangle (a, b, c) -// NOTE: Assumes P is on the plane of the triangle -RMAPI Vector3 Vector3Barycenter(Vector3 p, Vector3 a, Vector3 b, Vector3 c) -{ - Vector3 result = { 0 }; - - Vector3 v0 = { b.x - a.x, b.y - a.y, b.z - a.z }; // Vector3Subtract(b, a) - Vector3 v1 = { c.x - a.x, c.y - a.y, c.z - a.z }; // Vector3Subtract(c, a) - Vector3 v2 = { p.x - a.x, p.y - a.y, p.z - a.z }; // Vector3Subtract(p, a) - float d00 = (v0.x*v0.x + v0.y*v0.y + v0.z*v0.z); // Vector3DotProduct(v0, v0) - float d01 = (v0.x*v1.x + v0.y*v1.y + v0.z*v1.z); // Vector3DotProduct(v0, v1) - float d11 = (v1.x*v1.x + v1.y*v1.y + v1.z*v1.z); // Vector3DotProduct(v1, v1) - float d20 = (v2.x*v0.x + v2.y*v0.y + v2.z*v0.z); // Vector3DotProduct(v2, v0) - float d21 = (v2.x*v1.x + v2.y*v1.y + v2.z*v1.z); // Vector3DotProduct(v2, v1) - - float denom = d00*d11 - d01*d01; - - result.y = (d11*d20 - d01*d21)/denom; - result.z = (d00*d21 - d01*d20)/denom; - result.x = 1.0f - (result.z + result.y); - - return result; -} - -// Projects a Vector3 from screen space into object space -// NOTE: We are avoiding calling other raymath functions despite available -RMAPI Vector3 Vector3Unproject(Vector3 source, Matrix projection, Matrix view) -{ - Vector3 result = { 0 }; - - // Calculate unprojected matrix (multiply view matrix by projection matrix) and invert it - Matrix matViewProj = { // MatrixMultiply(view, projection); - view.m0*projection.m0 + view.m1*projection.m4 + view.m2*projection.m8 + view.m3*projection.m12, - view.m0*projection.m1 + view.m1*projection.m5 + view.m2*projection.m9 + view.m3*projection.m13, - view.m0*projection.m2 + view.m1*projection.m6 + view.m2*projection.m10 + view.m3*projection.m14, - view.m0*projection.m3 + view.m1*projection.m7 + view.m2*projection.m11 + view.m3*projection.m15, - view.m4*projection.m0 + view.m5*projection.m4 + view.m6*projection.m8 + view.m7*projection.m12, - view.m4*projection.m1 + view.m5*projection.m5 + view.m6*projection.m9 + view.m7*projection.m13, - view.m4*projection.m2 + view.m5*projection.m6 + view.m6*projection.m10 + view.m7*projection.m14, - view.m4*projection.m3 + view.m5*projection.m7 + view.m6*projection.m11 + view.m7*projection.m15, - view.m8*projection.m0 + view.m9*projection.m4 + view.m10*projection.m8 + view.m11*projection.m12, - view.m8*projection.m1 + view.m9*projection.m5 + view.m10*projection.m9 + view.m11*projection.m13, - view.m8*projection.m2 + view.m9*projection.m6 + view.m10*projection.m10 + view.m11*projection.m14, - view.m8*projection.m3 + view.m9*projection.m7 + view.m10*projection.m11 + view.m11*projection.m15, - view.m12*projection.m0 + view.m13*projection.m4 + view.m14*projection.m8 + view.m15*projection.m12, - view.m12*projection.m1 + view.m13*projection.m5 + view.m14*projection.m9 + view.m15*projection.m13, - view.m12*projection.m2 + view.m13*projection.m6 + view.m14*projection.m10 + view.m15*projection.m14, - view.m12*projection.m3 + view.m13*projection.m7 + view.m14*projection.m11 + view.m15*projection.m15 }; - - // Calculate inverted matrix -> MatrixInvert(matViewProj); - // Cache the matrix values (speed optimization) - float a00 = matViewProj.m0, a01 = matViewProj.m1, a02 = matViewProj.m2, a03 = matViewProj.m3; - float a10 = matViewProj.m4, a11 = matViewProj.m5, a12 = matViewProj.m6, a13 = matViewProj.m7; - float a20 = matViewProj.m8, a21 = matViewProj.m9, a22 = matViewProj.m10, a23 = matViewProj.m11; - float a30 = matViewProj.m12, a31 = matViewProj.m13, a32 = matViewProj.m14, a33 = matViewProj.m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - Matrix matViewProjInv = { - (a11*b11 - a12*b10 + a13*b09)*invDet, - (-a01*b11 + a02*b10 - a03*b09)*invDet, - (a31*b05 - a32*b04 + a33*b03)*invDet, - (-a21*b05 + a22*b04 - a23*b03)*invDet, - (-a10*b11 + a12*b08 - a13*b07)*invDet, - (a00*b11 - a02*b08 + a03*b07)*invDet, - (-a30*b05 + a32*b02 - a33*b01)*invDet, - (a20*b05 - a22*b02 + a23*b01)*invDet, - (a10*b10 - a11*b08 + a13*b06)*invDet, - (-a00*b10 + a01*b08 - a03*b06)*invDet, - (a30*b04 - a31*b02 + a33*b00)*invDet, - (-a20*b04 + a21*b02 - a23*b00)*invDet, - (-a10*b09 + a11*b07 - a12*b06)*invDet, - (a00*b09 - a01*b07 + a02*b06)*invDet, - (-a30*b03 + a31*b01 - a32*b00)*invDet, - (a20*b03 - a21*b01 + a22*b00)*invDet }; - - // Create quaternion from source point - Quaternion quat = { source.x, source.y, source.z, 1.0f }; - - // Multiply quat point by unprojecte matrix - Quaternion qtransformed = { // QuaternionTransform(quat, matViewProjInv) - matViewProjInv.m0*quat.x + matViewProjInv.m4*quat.y + matViewProjInv.m8*quat.z + matViewProjInv.m12*quat.w, - matViewProjInv.m1*quat.x + matViewProjInv.m5*quat.y + matViewProjInv.m9*quat.z + matViewProjInv.m13*quat.w, - matViewProjInv.m2*quat.x + matViewProjInv.m6*quat.y + matViewProjInv.m10*quat.z + matViewProjInv.m14*quat.w, - matViewProjInv.m3*quat.x + matViewProjInv.m7*quat.y + matViewProjInv.m11*quat.z + matViewProjInv.m15*quat.w }; - - // Normalized world points in vectors - result.x = qtransformed.x/qtransformed.w; - result.y = qtransformed.y/qtransformed.w; - result.z = qtransformed.z/qtransformed.w; - - return result; -} - -// Get Vector3 as float array -RMAPI float3 Vector3ToFloatV(Vector3 v) -{ - float3 buffer = { 0 }; - - buffer.v[0] = v.x; - buffer.v[1] = v.y; - buffer.v[2] = v.z; - - return buffer; -} - -// Invert the given vector -RMAPI Vector3 Vector3Invert(Vector3 v) -{ - Vector3 result = { 1.0f/v.x, 1.0f/v.y, 1.0f/v.z }; - - return result; -} - -// Clamp the components of the vector between -// min and max values specified by the given vectors -RMAPI Vector3 Vector3Clamp(Vector3 v, Vector3 min, Vector3 max) -{ - Vector3 result = { 0 }; - - result.x = fminf(max.x, fmaxf(min.x, v.x)); - result.y = fminf(max.y, fmaxf(min.y, v.y)); - result.z = fminf(max.z, fmaxf(min.z, v.z)); - - return result; -} - -// Clamp the magnitude of the vector between two values -RMAPI Vector3 Vector3ClampValue(Vector3 v, float min, float max) -{ - Vector3 result = v; - - float length = (v.x*v.x) + (v.y*v.y) + (v.z*v.z); - if (length > 0.0f) - { - length = sqrtf(length); - - if (length < min) - { - float scale = min/length; - result.x = v.x*scale; - result.y = v.y*scale; - result.z = v.z*scale; - } - else if (length > max) - { - float scale = max/length; - result.x = v.x*scale; - result.y = v.y*scale; - result.z = v.z*scale; - } - } - - return result; -} - -// Check whether two given vectors are almost equal -RMAPI int Vector3Equals(Vector3 p, Vector3 q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))); - - return result; -} - -// Compute the direction of a refracted ray -// v: normalized direction of the incoming ray -// n: normalized normal vector of the interface of two optical media -// r: ratio of the refractive index of the medium from where the ray comes -// to the refractive index of the medium on the other side of the surface -RMAPI Vector3 Vector3Refract(Vector3 v, Vector3 n, float r) -{ - Vector3 result = { 0 }; - - float dot = v.x*n.x + v.y*n.y + v.z*n.z; - float d = 1.0f - r*r*(1.0f - dot*dot); - - if (d >= 0.0f) - { - d = sqrtf(d); - v.x = r*v.x - (r*dot + d)*n.x; - v.y = r*v.y - (r*dot + d)*n.y; - v.z = r*v.z - (r*dot + d)*n.z; - - result = v; - } - - return result; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Matrix math -//---------------------------------------------------------------------------------- - -// Compute matrix determinant -RMAPI float MatrixDeterminant(Matrix mat) -{ - float result = 0.0f; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - result = a30*a21*a12*a03 - a20*a31*a12*a03 - a30*a11*a22*a03 + a10*a31*a22*a03 + - a20*a11*a32*a03 - a10*a21*a32*a03 - a30*a21*a02*a13 + a20*a31*a02*a13 + - a30*a01*a22*a13 - a00*a31*a22*a13 - a20*a01*a32*a13 + a00*a21*a32*a13 + - a30*a11*a02*a23 - a10*a31*a02*a23 - a30*a01*a12*a23 + a00*a31*a12*a23 + - a10*a01*a32*a23 - a00*a11*a32*a23 - a20*a11*a02*a33 + a10*a21*a02*a33 + - a20*a01*a12*a33 - a00*a21*a12*a33 - a10*a01*a22*a33 + a00*a11*a22*a33; - - return result; -} - -// Get the trace of the matrix (sum of the values along the diagonal) -RMAPI float MatrixTrace(Matrix mat) -{ - float result = (mat.m0 + mat.m5 + mat.m10 + mat.m15); - - return result; -} - -// Transposes provided matrix -RMAPI Matrix MatrixTranspose(Matrix mat) -{ - Matrix result = { 0 }; - - result.m0 = mat.m0; - result.m1 = mat.m4; - result.m2 = mat.m8; - result.m3 = mat.m12; - result.m4 = mat.m1; - result.m5 = mat.m5; - result.m6 = mat.m9; - result.m7 = mat.m13; - result.m8 = mat.m2; - result.m9 = mat.m6; - result.m10 = mat.m10; - result.m11 = mat.m14; - result.m12 = mat.m3; - result.m13 = mat.m7; - result.m14 = mat.m11; - result.m15 = mat.m15; - - return result; -} - -// Invert provided matrix -RMAPI Matrix MatrixInvert(Matrix mat) -{ - Matrix result = { 0 }; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - result.m0 = (a11*b11 - a12*b10 + a13*b09)*invDet; - result.m1 = (-a01*b11 + a02*b10 - a03*b09)*invDet; - result.m2 = (a31*b05 - a32*b04 + a33*b03)*invDet; - result.m3 = (-a21*b05 + a22*b04 - a23*b03)*invDet; - result.m4 = (-a10*b11 + a12*b08 - a13*b07)*invDet; - result.m5 = (a00*b11 - a02*b08 + a03*b07)*invDet; - result.m6 = (-a30*b05 + a32*b02 - a33*b01)*invDet; - result.m7 = (a20*b05 - a22*b02 + a23*b01)*invDet; - result.m8 = (a10*b10 - a11*b08 + a13*b06)*invDet; - result.m9 = (-a00*b10 + a01*b08 - a03*b06)*invDet; - result.m10 = (a30*b04 - a31*b02 + a33*b00)*invDet; - result.m11 = (-a20*b04 + a21*b02 - a23*b00)*invDet; - result.m12 = (-a10*b09 + a11*b07 - a12*b06)*invDet; - result.m13 = (a00*b09 - a01*b07 + a02*b06)*invDet; - result.m14 = (-a30*b03 + a31*b01 - a32*b00)*invDet; - result.m15 = (a20*b03 - a21*b01 + a22*b00)*invDet; - - return result; -} - -// Get identity matrix -RMAPI Matrix MatrixIdentity(void) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Add two matrices -RMAPI Matrix MatrixAdd(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0 + right.m0; - result.m1 = left.m1 + right.m1; - result.m2 = left.m2 + right.m2; - result.m3 = left.m3 + right.m3; - result.m4 = left.m4 + right.m4; - result.m5 = left.m5 + right.m5; - result.m6 = left.m6 + right.m6; - result.m7 = left.m7 + right.m7; - result.m8 = left.m8 + right.m8; - result.m9 = left.m9 + right.m9; - result.m10 = left.m10 + right.m10; - result.m11 = left.m11 + right.m11; - result.m12 = left.m12 + right.m12; - result.m13 = left.m13 + right.m13; - result.m14 = left.m14 + right.m14; - result.m15 = left.m15 + right.m15; - - return result; -} - -// Subtract two matrices (left - right) -RMAPI Matrix MatrixSubtract(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0 - right.m0; - result.m1 = left.m1 - right.m1; - result.m2 = left.m2 - right.m2; - result.m3 = left.m3 - right.m3; - result.m4 = left.m4 - right.m4; - result.m5 = left.m5 - right.m5; - result.m6 = left.m6 - right.m6; - result.m7 = left.m7 - right.m7; - result.m8 = left.m8 - right.m8; - result.m9 = left.m9 - right.m9; - result.m10 = left.m10 - right.m10; - result.m11 = left.m11 - right.m11; - result.m12 = left.m12 - right.m12; - result.m13 = left.m13 - right.m13; - result.m14 = left.m14 - right.m14; - result.m15 = left.m15 - right.m15; - - return result; -} - -// Get two matrix multiplication -// NOTE: When multiplying matrices... the order matters! -RMAPI Matrix MatrixMultiply(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; - result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; - result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; - result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; - result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; - result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; - result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; - result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; - result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; - result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; - result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; - result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; - result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; - result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; - result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; - result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; - - return result; -} - -// Get translation matrix -RMAPI Matrix MatrixTranslate(float x, float y, float z) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, x, - 0.0f, 1.0f, 0.0f, y, - 0.0f, 0.0f, 1.0f, z, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Create rotation matrix from axis and angle -// NOTE: Angle should be provided in radians -RMAPI Matrix MatrixRotate(Vector3 axis, float angle) -{ - Matrix result = { 0 }; - - float x = axis.x, y = axis.y, z = axis.z; - - float lengthSquared = x*x + y*y + z*z; - - if ((lengthSquared != 1.0f) && (lengthSquared != 0.0f)) - { - float ilength = 1.0f/sqrtf(lengthSquared); - x *= ilength; - y *= ilength; - z *= ilength; - } - - float sinres = sinf(angle); - float cosres = cosf(angle); - float t = 1.0f - cosres; - - result.m0 = x*x*t + cosres; - result.m1 = y*x*t + z*sinres; - result.m2 = z*x*t - y*sinres; - result.m3 = 0.0f; - - result.m4 = x*y*t - z*sinres; - result.m5 = y*y*t + cosres; - result.m6 = z*y*t + x*sinres; - result.m7 = 0.0f; - - result.m8 = x*z*t + y*sinres; - result.m9 = y*z*t - x*sinres; - result.m10 = z*z*t + cosres; - result.m11 = 0.0f; - - result.m12 = 0.0f; - result.m13 = 0.0f; - result.m14 = 0.0f; - result.m15 = 1.0f; - - return result; -} - -// Get x-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateX(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m5 = cosres; - result.m6 = sinres; - result.m9 = -sinres; - result.m10 = cosres; - - return result; -} - -// Get y-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateY(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m0 = cosres; - result.m2 = -sinres; - result.m8 = sinres; - result.m10 = cosres; - - return result; -} - -// Get z-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateZ(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m0 = cosres; - result.m1 = sinres; - result.m4 = -sinres; - result.m5 = cosres; - - return result; -} - - -// Get xyz-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateXYZ(Vector3 angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosz = cosf(-angle.z); - float sinz = sinf(-angle.z); - float cosy = cosf(-angle.y); - float siny = sinf(-angle.y); - float cosx = cosf(-angle.x); - float sinx = sinf(-angle.x); - - result.m0 = cosz*cosy; - result.m1 = (cosz*siny*sinx) - (sinz*cosx); - result.m2 = (cosz*siny*cosx) + (sinz*sinx); - - result.m4 = sinz*cosy; - result.m5 = (sinz*siny*sinx) + (cosz*cosx); - result.m6 = (sinz*siny*cosx) - (cosz*sinx); - - result.m8 = -siny; - result.m9 = cosy*sinx; - result.m10= cosy*cosx; - - return result; -} - -// Get zyx-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateZYX(Vector3 angle) -{ - Matrix result = { 0 }; - - float cz = cosf(angle.z); - float sz = sinf(angle.z); - float cy = cosf(angle.y); - float sy = sinf(angle.y); - float cx = cosf(angle.x); - float sx = sinf(angle.x); - - result.m0 = cz*cy; - result.m4 = cz*sy*sx - cx*sz; - result.m8 = sz*sx + cz*cx*sy; - result.m12 = 0; - - result.m1 = cy*sz; - result.m5 = cz*cx + sz*sy*sx; - result.m9 = cx*sz*sy - cz*sx; - result.m13 = 0; - - result.m2 = -sy; - result.m6 = cy*sx; - result.m10 = cy*cx; - result.m14 = 0; - - result.m3 = 0; - result.m7 = 0; - result.m11 = 0; - result.m15 = 1; - - return result; -} - -// Get scaling matrix -RMAPI Matrix MatrixScale(float x, float y, float z) -{ - Matrix result = { x, 0.0f, 0.0f, 0.0f, - 0.0f, y, 0.0f, 0.0f, - 0.0f, 0.0f, z, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Get perspective projection matrix -RMAPI Matrix MatrixFrustum(double left, double right, double bottom, double top, double near, double far) -{ - Matrix result = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(far - near); - - result.m0 = ((float)near*2.0f)/rl; - result.m1 = 0.0f; - result.m2 = 0.0f; - result.m3 = 0.0f; - - result.m4 = 0.0f; - result.m5 = ((float)near*2.0f)/tb; - result.m6 = 0.0f; - result.m7 = 0.0f; - - result.m8 = ((float)right + (float)left)/rl; - result.m9 = ((float)top + (float)bottom)/tb; - result.m10 = -((float)far + (float)near)/fn; - result.m11 = -1.0f; - - result.m12 = 0.0f; - result.m13 = 0.0f; - result.m14 = -((float)far*(float)near*2.0f)/fn; - result.m15 = 0.0f; - - return result; -} - -// Get perspective projection matrix -// NOTE: Fovy angle must be provided in radians -RMAPI Matrix MatrixPerspective(double fovY, double aspect, double nearPlane, double farPlane) -{ - Matrix result = { 0 }; - - double top = nearPlane*tan(fovY*0.5); - double bottom = -top; - double right = top*aspect; - double left = -right; - - // MatrixFrustum(-right, right, -top, top, near, far); - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(farPlane - nearPlane); - - result.m0 = ((float)nearPlane*2.0f)/rl; - result.m5 = ((float)nearPlane*2.0f)/tb; - result.m8 = ((float)right + (float)left)/rl; - result.m9 = ((float)top + (float)bottom)/tb; - result.m10 = -((float)farPlane + (float)nearPlane)/fn; - result.m11 = -1.0f; - result.m14 = -((float)farPlane*(float)nearPlane*2.0f)/fn; - - return result; -} - -// Get orthographic projection matrix -RMAPI Matrix MatrixOrtho(double left, double right, double bottom, double top, double nearPlane, double farPlane) -{ - Matrix result = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(farPlane - nearPlane); - - result.m0 = 2.0f/rl; - result.m1 = 0.0f; - result.m2 = 0.0f; - result.m3 = 0.0f; - result.m4 = 0.0f; - result.m5 = 2.0f/tb; - result.m6 = 0.0f; - result.m7 = 0.0f; - result.m8 = 0.0f; - result.m9 = 0.0f; - result.m10 = -2.0f/fn; - result.m11 = 0.0f; - result.m12 = -((float)left + (float)right)/rl; - result.m13 = -((float)top + (float)bottom)/tb; - result.m14 = -((float)farPlane + (float)nearPlane)/fn; - result.m15 = 1.0f; - - return result; -} - -// Get camera look-at matrix (view matrix) -RMAPI Matrix MatrixLookAt(Vector3 eye, Vector3 target, Vector3 up) -{ - Matrix result = { 0 }; - - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Subtract(eye, target) - Vector3 vz = { eye.x - target.x, eye.y - target.y, eye.z - target.z }; - - // Vector3Normalize(vz) - Vector3 v = vz; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vz.x *= ilength; - vz.y *= ilength; - vz.z *= ilength; - - // Vector3CrossProduct(up, vz) - Vector3 vx = { up.y*vz.z - up.z*vz.y, up.z*vz.x - up.x*vz.z, up.x*vz.y - up.y*vz.x }; - - // Vector3Normalize(x) - v = vx; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vx.x *= ilength; - vx.y *= ilength; - vx.z *= ilength; - - // Vector3CrossProduct(vz, vx) - Vector3 vy = { vz.y*vx.z - vz.z*vx.y, vz.z*vx.x - vz.x*vx.z, vz.x*vx.y - vz.y*vx.x }; - - result.m0 = vx.x; - result.m1 = vy.x; - result.m2 = vz.x; - result.m3 = 0.0f; - result.m4 = vx.y; - result.m5 = vy.y; - result.m6 = vz.y; - result.m7 = 0.0f; - result.m8 = vx.z; - result.m9 = vy.z; - result.m10 = vz.z; - result.m11 = 0.0f; - result.m12 = -(vx.x*eye.x + vx.y*eye.y + vx.z*eye.z); // Vector3DotProduct(vx, eye) - result.m13 = -(vy.x*eye.x + vy.y*eye.y + vy.z*eye.z); // Vector3DotProduct(vy, eye) - result.m14 = -(vz.x*eye.x + vz.y*eye.y + vz.z*eye.z); // Vector3DotProduct(vz, eye) - result.m15 = 1.0f; - - return result; -} - -// Get float array of matrix data -RMAPI float16 MatrixToFloatV(Matrix mat) -{ - float16 result = { 0 }; - - result.v[0] = mat.m0; - result.v[1] = mat.m1; - result.v[2] = mat.m2; - result.v[3] = mat.m3; - result.v[4] = mat.m4; - result.v[5] = mat.m5; - result.v[6] = mat.m6; - result.v[7] = mat.m7; - result.v[8] = mat.m8; - result.v[9] = mat.m9; - result.v[10] = mat.m10; - result.v[11] = mat.m11; - result.v[12] = mat.m12; - result.v[13] = mat.m13; - result.v[14] = mat.m14; - result.v[15] = mat.m15; - - return result; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Quaternion math -//---------------------------------------------------------------------------------- - -// Add two quaternions -RMAPI Quaternion QuaternionAdd(Quaternion q1, Quaternion q2) -{ - Quaternion result = {q1.x + q2.x, q1.y + q2.y, q1.z + q2.z, q1.w + q2.w}; - - return result; -} - -// Add quaternion and float value -RMAPI Quaternion QuaternionAddValue(Quaternion q, float add) -{ - Quaternion result = {q.x + add, q.y + add, q.z + add, q.w + add}; - - return result; -} - -// Subtract two quaternions -RMAPI Quaternion QuaternionSubtract(Quaternion q1, Quaternion q2) -{ - Quaternion result = {q1.x - q2.x, q1.y - q2.y, q1.z - q2.z, q1.w - q2.w}; - - return result; -} - -// Subtract quaternion and float value -RMAPI Quaternion QuaternionSubtractValue(Quaternion q, float sub) -{ - Quaternion result = {q.x - sub, q.y - sub, q.z - sub, q.w - sub}; - - return result; -} - -// Get identity quaternion -RMAPI Quaternion QuaternionIdentity(void) -{ - Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Computes the length of a quaternion -RMAPI float QuaternionLength(Quaternion q) -{ - float result = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - - return result; -} - -// Normalize provided quaternion -RMAPI Quaternion QuaternionNormalize(Quaternion q) -{ - Quaternion result = { 0 }; - - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Invert provided quaternion -RMAPI Quaternion QuaternionInvert(Quaternion q) -{ - Quaternion result = q; - - float lengthSq = q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w; - - if (lengthSq != 0.0f) - { - float invLength = 1.0f/lengthSq; - - result.x *= -invLength; - result.y *= -invLength; - result.z *= -invLength; - result.w *= invLength; - } - - return result; -} - -// Calculate two quaternion multiplication -RMAPI Quaternion QuaternionMultiply(Quaternion q1, Quaternion q2) -{ - Quaternion result = { 0 }; - - float qax = q1.x, qay = q1.y, qaz = q1.z, qaw = q1.w; - float qbx = q2.x, qby = q2.y, qbz = q2.z, qbw = q2.w; - - result.x = qax*qbw + qaw*qbx + qay*qbz - qaz*qby; - result.y = qay*qbw + qaw*qby + qaz*qbx - qax*qbz; - result.z = qaz*qbw + qaw*qbz + qax*qby - qay*qbx; - result.w = qaw*qbw - qax*qbx - qay*qby - qaz*qbz; - - return result; -} - -// Scale quaternion by float value -RMAPI Quaternion QuaternionScale(Quaternion q, float mul) -{ - Quaternion result = { 0 }; - - result.x = q.x*mul; - result.y = q.y*mul; - result.z = q.z*mul; - result.w = q.w*mul; - - return result; -} - -// Divide two quaternions -RMAPI Quaternion QuaternionDivide(Quaternion q1, Quaternion q2) -{ - Quaternion result = { q1.x/q2.x, q1.y/q2.y, q1.z/q2.z, q1.w/q2.w }; - - return result; -} - -// Calculate linear interpolation between two quaternions -RMAPI Quaternion QuaternionLerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - - result.x = q1.x + amount*(q2.x - q1.x); - result.y = q1.y + amount*(q2.y - q1.y); - result.z = q1.z + amount*(q2.z - q1.z); - result.w = q1.w + amount*(q2.w - q1.w); - - return result; -} - -// Calculate slerp-optimized interpolation between two quaternions -RMAPI Quaternion QuaternionNlerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - - // QuaternionLerp(q1, q2, amount) - result.x = q1.x + amount*(q2.x - q1.x); - result.y = q1.y + amount*(q2.y - q1.y); - result.z = q1.z + amount*(q2.z - q1.z); - result.w = q1.w + amount*(q2.w - q1.w); - - // QuaternionNormalize(q); - Quaternion q = result; - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Calculates spherical linear interpolation between two quaternions -RMAPI Quaternion QuaternionSlerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - float cosHalfTheta = q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.w*q2.w; - - if (cosHalfTheta < 0) - { - q2.x = -q2.x; q2.y = -q2.y; q2.z = -q2.z; q2.w = -q2.w; - cosHalfTheta = -cosHalfTheta; - } - - if (fabsf(cosHalfTheta) >= 1.0f) result = q1; - else if (cosHalfTheta > 0.95f) result = QuaternionNlerp(q1, q2, amount); - else - { - float halfTheta = acosf(cosHalfTheta); - float sinHalfTheta = sqrtf(1.0f - cosHalfTheta*cosHalfTheta); - - if (fabsf(sinHalfTheta) < EPSILON) - { - result.x = (q1.x*0.5f + q2.x*0.5f); - result.y = (q1.y*0.5f + q2.y*0.5f); - result.z = (q1.z*0.5f + q2.z*0.5f); - result.w = (q1.w*0.5f + q2.w*0.5f); - } - else - { - float ratioA = sinf((1 - amount)*halfTheta)/sinHalfTheta; - float ratioB = sinf(amount*halfTheta)/sinHalfTheta; - - result.x = (q1.x*ratioA + q2.x*ratioB); - result.y = (q1.y*ratioA + q2.y*ratioB); - result.z = (q1.z*ratioA + q2.z*ratioB); - result.w = (q1.w*ratioA + q2.w*ratioB); - } - } - - return result; -} - -// Calculate quaternion based on the rotation from one vector to another -RMAPI Quaternion QuaternionFromVector3ToVector3(Vector3 from, Vector3 to) -{ - Quaternion result = { 0 }; - - float cos2Theta = (from.x*to.x + from.y*to.y + from.z*to.z); // Vector3DotProduct(from, to) - Vector3 cross = { from.y*to.z - from.z*to.y, from.z*to.x - from.x*to.z, from.x*to.y - from.y*to.x }; // Vector3CrossProduct(from, to) - - result.x = cross.x; - result.y = cross.y; - result.z = cross.z; - result.w = 1.0f + cos2Theta; - - // QuaternionNormalize(q); - // NOTE: Normalize to essentially nlerp the original and identity to 0.5 - Quaternion q = result; - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Get a quaternion for a given rotation matrix -RMAPI Quaternion QuaternionFromMatrix(Matrix mat) -{ - Quaternion result = { 0 }; - - float fourWSquaredMinus1 = mat.m0 + mat.m5 + mat.m10; - float fourXSquaredMinus1 = mat.m0 - mat.m5 - mat.m10; - float fourYSquaredMinus1 = mat.m5 - mat.m0 - mat.m10; - float fourZSquaredMinus1 = mat.m10 - mat.m0 - mat.m5; - - int biggestIndex = 0; - float fourBiggestSquaredMinus1 = fourWSquaredMinus1; - if (fourXSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourXSquaredMinus1; - biggestIndex = 1; - } - - if (fourYSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourYSquaredMinus1; - biggestIndex = 2; - } - - if (fourZSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourZSquaredMinus1; - biggestIndex = 3; - } - - float biggestVal = sqrtf(fourBiggestSquaredMinus1 + 1.0f)*0.5f; - float mult = 0.25f / biggestVal; - - switch (biggestIndex) - { - case 0: - result.w = biggestVal; - result.x = (mat.m6 - mat.m9)*mult; - result.y = (mat.m8 - mat.m2)*mult; - result.z = (mat.m1 - mat.m4)*mult; - break; - case 1: - result.x = biggestVal; - result.w = (mat.m6 - mat.m9)*mult; - result.y = (mat.m1 + mat.m4)*mult; - result.z = (mat.m8 + mat.m2)*mult; - break; - case 2: - result.y = biggestVal; - result.w = (mat.m8 - mat.m2)*mult; - result.x = (mat.m1 + mat.m4)*mult; - result.z = (mat.m6 + mat.m9)*mult; - break; - case 3: - result.z = biggestVal; - result.w = (mat.m1 - mat.m4)*mult; - result.x = (mat.m8 + mat.m2)*mult; - result.y = (mat.m6 + mat.m9)*mult; - break; - } - - return result; -} - -// Get a matrix for a given quaternion -RMAPI Matrix QuaternionToMatrix(Quaternion q) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float a2 = q.x*q.x; - float b2 = q.y*q.y; - float c2 = q.z*q.z; - float ac = q.x*q.z; - float ab = q.x*q.y; - float bc = q.y*q.z; - float ad = q.w*q.x; - float bd = q.w*q.y; - float cd = q.w*q.z; - - result.m0 = 1 - 2*(b2 + c2); - result.m1 = 2*(ab + cd); - result.m2 = 2*(ac - bd); - - result.m4 = 2*(ab - cd); - result.m5 = 1 - 2*(a2 + c2); - result.m6 = 2*(bc + ad); - - result.m8 = 2*(ac + bd); - result.m9 = 2*(bc - ad); - result.m10 = 1 - 2*(a2 + b2); - - return result; -} - -// Get rotation quaternion for an angle and axis -// NOTE: Angle must be provided in radians -RMAPI Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle) -{ - Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; - - float axisLength = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); - - if (axisLength != 0.0f) - { - angle *= 0.5f; - - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Normalize(axis) - Vector3 v = axis; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - axis.x *= ilength; - axis.y *= ilength; - axis.z *= ilength; - - float sinres = sinf(angle); - float cosres = cosf(angle); - - result.x = axis.x*sinres; - result.y = axis.y*sinres; - result.z = axis.z*sinres; - result.w = cosres; - - // QuaternionNormalize(q); - Quaternion q = result; - length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - } - - return result; -} - -// Get the rotation angle and axis for a given quaternion -RMAPI void QuaternionToAxisAngle(Quaternion q, Vector3 *outAxis, float *outAngle) -{ - if (fabsf(q.w) > 1.0f) - { - // QuaternionNormalize(q); - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - q.x = q.x*ilength; - q.y = q.y*ilength; - q.z = q.z*ilength; - q.w = q.w*ilength; - } - - Vector3 resAxis = { 0.0f, 0.0f, 0.0f }; - float resAngle = 2.0f*acosf(q.w); - float den = sqrtf(1.0f - q.w*q.w); - - if (den > EPSILON) - { - resAxis.x = q.x/den; - resAxis.y = q.y/den; - resAxis.z = q.z/den; - } - else - { - // This occurs when the angle is zero. - // Not a problem: just set an arbitrary normalized axis. - resAxis.x = 1.0f; - } - - *outAxis = resAxis; - *outAngle = resAngle; -} - -// Get the quaternion equivalent to Euler angles -// NOTE: Rotation order is ZYX -RMAPI Quaternion QuaternionFromEuler(float pitch, float yaw, float roll) -{ - Quaternion result = { 0 }; - - float x0 = cosf(pitch*0.5f); - float x1 = sinf(pitch*0.5f); - float y0 = cosf(yaw*0.5f); - float y1 = sinf(yaw*0.5f); - float z0 = cosf(roll*0.5f); - float z1 = sinf(roll*0.5f); - - result.x = x1*y0*z0 - x0*y1*z1; - result.y = x0*y1*z0 + x1*y0*z1; - result.z = x0*y0*z1 - x1*y1*z0; - result.w = x0*y0*z0 + x1*y1*z1; - - return result; -} - -// Get the Euler angles equivalent to quaternion (roll, pitch, yaw) -// NOTE: Angles are returned in a Vector3 struct in radians -RMAPI Vector3 QuaternionToEuler(Quaternion q) -{ - Vector3 result = { 0 }; - - // Roll (x-axis rotation) - float x0 = 2.0f*(q.w*q.x + q.y*q.z); - float x1 = 1.0f - 2.0f*(q.x*q.x + q.y*q.y); - result.x = atan2f(x0, x1); - - // Pitch (y-axis rotation) - float y0 = 2.0f*(q.w*q.y - q.z*q.x); - y0 = y0 > 1.0f ? 1.0f : y0; - y0 = y0 < -1.0f ? -1.0f : y0; - result.y = asinf(y0); - - // Yaw (z-axis rotation) - float z0 = 2.0f*(q.w*q.z + q.x*q.y); - float z1 = 1.0f - 2.0f*(q.y*q.y + q.z*q.z); - result.z = atan2f(z0, z1); - - return result; -} - -// Transform a quaternion given a transformation matrix -RMAPI Quaternion QuaternionTransform(Quaternion q, Matrix mat) -{ - Quaternion result = { 0 }; - - result.x = mat.m0*q.x + mat.m4*q.y + mat.m8*q.z + mat.m12*q.w; - result.y = mat.m1*q.x + mat.m5*q.y + mat.m9*q.z + mat.m13*q.w; - result.z = mat.m2*q.x + mat.m6*q.y + mat.m10*q.z + mat.m14*q.w; - result.w = mat.m3*q.x + mat.m7*q.y + mat.m11*q.z + mat.m15*q.w; - - return result; -} - -// Check whether two given quaternions are almost equal -RMAPI int QuaternionEquals(Quaternion p, Quaternion q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = (((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && - ((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))) || - (((fabsf(p.x + q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y + q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z + q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && - ((fabsf(p.w + q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))); - - return result; -} - -#endif // RAYMATH_H diff --git a/third_party/raylib/include/rlgl.h b/third_party/raylib/include/rlgl.h deleted file mode 100644 index 6cf9c7e99ddf06..00000000000000 --- a/third_party/raylib/include/rlgl.h +++ /dev/null @@ -1,4859 +0,0 @@ -/********************************************************************************************** -* -* rlgl v4.5 - A multi-OpenGL abstraction layer with an immediate-mode style API -* -* DESCRIPTION: -* An abstraction layer for multiple OpenGL versions (1.1, 2.1, 3.3 Core, 4.3 Core, ES 2.0) -* that provides a pseudo-OpenGL 1.1 immediate-mode style API (rlVertex, rlTranslate, rlRotate...) -* -* ADDITIONAL NOTES: -* When choosing an OpenGL backend different than OpenGL 1.1, some internal buffer are -* initialized on rlglInit() to accumulate vertex data. -* -* When an internal state change is required all the stored vertex data is renderer in batch, -* additionally, rlDrawRenderBatchActive() could be called to force flushing of the batch. -* -* Some resources are also loaded for convenience, here the complete list: -* - Default batch (RLGL.defaultBatch): RenderBatch system to accumulate vertex data -* - Default texture (RLGL.defaultTextureId): 1x1 white pixel R8G8B8A8 -* - Default shader (RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs) -* -* Internal buffer (and resources) must be manually unloaded calling rlglClose(). -* -* CONFIGURATION: -* #define GRAPHICS_API_OPENGL_11 -* #define GRAPHICS_API_OPENGL_21 -* #define GRAPHICS_API_OPENGL_33 -* #define GRAPHICS_API_OPENGL_43 -* #define GRAPHICS_API_OPENGL_ES2 -* #define GRAPHICS_API_OPENGL_ES3 -* Use selected OpenGL graphics backend, should be supported by platform -* Those preprocessor defines are only used on rlgl module, if OpenGL version is -* required by any other module, use rlGetVersion() to check it -* -* #define RLGL_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define RLGL_RENDER_TEXTURES_HINT -* Enable framebuffer objects (fbo) support (enabled by default) -* Some GPUs could not support them despite the OpenGL version -* -* #define RLGL_SHOW_GL_DETAILS_INFO -* Show OpenGL extensions and capabilities detailed logs on init -* -* #define RLGL_ENABLE_OPENGL_DEBUG_CONTEXT -* Enable debug context (only available on OpenGL 4.3) -* -* rlgl capabilities could be customized just defining some internal -* values before library inclusion (default values listed): -* -* #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 // Default internal render batch elements limits -* #define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering) -* #define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture) -* #define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture()) -* -* #define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of internal Matrix stack -* #define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported -* #define RL_CULL_DISTANCE_NEAR 0.01 // Default projection matrix near cull distance -* #define RL_CULL_DISTANCE_FAR 1000.0 // Default projection matrix far cull distance -* -* When loading a shader, the following vertex attributes and uniform -* location names are tried to be set automatically: -* -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: 0 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: 1 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: 2 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: 3 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: 4 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: 5 -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView)) -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2) -* -* DEPENDENCIES: -* - OpenGL libraries (depending on platform and OpenGL version selected) -* - GLAD OpenGL extensions loading library (only for OpenGL 3.3 Core, 4.3 Core) -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2023 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RLGL_H -#define RLGL_H - -#define RLGL_VERSION "4.5" - -// Function specifiers in case library is build/used as a shared library (Windows) -// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -#if defined(_WIN32) - #if defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) - #elif defined(USE_LIBTYPE_SHARED) - #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) - #endif -#endif - -// Function specifiers definition -#ifndef RLAPI - #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) -#endif - -// Support TRACELOG macros -#ifndef TRACELOG - #define TRACELOG(level, ...) (void)0 - #define TRACELOGD(...) (void)0 -#endif - -// Allow custom memory allocators -#ifndef RL_MALLOC - #define RL_MALLOC(sz) malloc(sz) -#endif -#ifndef RL_CALLOC - #define RL_CALLOC(n,sz) calloc(n,sz) -#endif -#ifndef RL_REALLOC - #define RL_REALLOC(n,sz) realloc(n,sz) -#endif -#ifndef RL_FREE - #define RL_FREE(p) free(p) -#endif - -// Security check in case no GRAPHICS_API_OPENGL_* defined -#if !defined(GRAPHICS_API_OPENGL_11) && \ - !defined(GRAPHICS_API_OPENGL_21) && \ - !defined(GRAPHICS_API_OPENGL_33) && \ - !defined(GRAPHICS_API_OPENGL_43) && \ - !defined(GRAPHICS_API_OPENGL_ES2) && \ - !defined(GRAPHICS_API_OPENGL_ES3) - #define GRAPHICS_API_OPENGL_33 -#endif - -// Security check in case multiple GRAPHICS_API_OPENGL_* defined -#if defined(GRAPHICS_API_OPENGL_11) - #if defined(GRAPHICS_API_OPENGL_21) - #undef GRAPHICS_API_OPENGL_21 - #endif - #if defined(GRAPHICS_API_OPENGL_33) - #undef GRAPHICS_API_OPENGL_33 - #endif - #if defined(GRAPHICS_API_OPENGL_43) - #undef GRAPHICS_API_OPENGL_43 - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - #undef GRAPHICS_API_OPENGL_ES2 - #endif -#endif - -// OpenGL 2.1 uses most of OpenGL 3.3 Core functionality -// WARNING: Specific parts are checked with #if defines -#if defined(GRAPHICS_API_OPENGL_21) - #define GRAPHICS_API_OPENGL_33 -#endif - -// OpenGL 4.3 uses OpenGL 3.3 Core functionality -#if defined(GRAPHICS_API_OPENGL_43) - #define GRAPHICS_API_OPENGL_33 -#endif - -// OpenGL ES 3.0 uses OpenGL ES 2.0 functionality (and more) -#if defined(GRAPHICS_API_OPENGL_ES3) - #define GRAPHICS_API_OPENGL_ES2 -#endif - -// Support framebuffer objects by default -// NOTE: Some driver implementation do not support it, despite they should -#define RLGL_RENDER_TEXTURES_HINT - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- - -// Default internal render batch elements limits -#ifndef RL_DEFAULT_BATCH_BUFFER_ELEMENTS - #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // This is the maximum amount of elements (quads) per batch - // NOTE: Be careful with text, every letter maps to a quad - #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - // We reduce memory sizes for embedded systems (RPI and HTML5) - // NOTE: On HTML5 (emscripten) this is allocated on heap, - // by default it's only 16MB!...just take care... - #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 2048 - #endif -#endif -#ifndef RL_DEFAULT_BATCH_BUFFERS - #define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering) -#endif -#ifndef RL_DEFAULT_BATCH_DRAWCALLS - #define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture) -#endif -#ifndef RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS - #define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture()) -#endif - -// Internal Matrix stack -#ifndef RL_MAX_MATRIX_STACK_SIZE - #define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of Matrix stack -#endif - -// Shader limits -#ifndef RL_MAX_SHADER_LOCATIONS - #define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported -#endif - -// Projection matrix culling -#ifndef RL_CULL_DISTANCE_NEAR - #define RL_CULL_DISTANCE_NEAR 0.01 // Default near cull distance -#endif -#ifndef RL_CULL_DISTANCE_FAR - #define RL_CULL_DISTANCE_FAR 1000.0 // Default far cull distance -#endif - -// Texture parameters (equivalent to OpenGL defines) -#define RL_TEXTURE_WRAP_S 0x2802 // GL_TEXTURE_WRAP_S -#define RL_TEXTURE_WRAP_T 0x2803 // GL_TEXTURE_WRAP_T -#define RL_TEXTURE_MAG_FILTER 0x2800 // GL_TEXTURE_MAG_FILTER -#define RL_TEXTURE_MIN_FILTER 0x2801 // GL_TEXTURE_MIN_FILTER - -#define RL_TEXTURE_FILTER_NEAREST 0x2600 // GL_NEAREST -#define RL_TEXTURE_FILTER_LINEAR 0x2601 // GL_LINEAR -#define RL_TEXTURE_FILTER_MIP_NEAREST 0x2700 // GL_NEAREST_MIPMAP_NEAREST -#define RL_TEXTURE_FILTER_NEAREST_MIP_LINEAR 0x2702 // GL_NEAREST_MIPMAP_LINEAR -#define RL_TEXTURE_FILTER_LINEAR_MIP_NEAREST 0x2701 // GL_LINEAR_MIPMAP_NEAREST -#define RL_TEXTURE_FILTER_MIP_LINEAR 0x2703 // GL_LINEAR_MIPMAP_LINEAR -#define RL_TEXTURE_FILTER_ANISOTROPIC 0x3000 // Anisotropic filter (custom identifier) -#define RL_TEXTURE_MIPMAP_BIAS_RATIO 0x4000 // Texture mipmap bias, percentage ratio (custom identifier) - -#define RL_TEXTURE_WRAP_REPEAT 0x2901 // GL_REPEAT -#define RL_TEXTURE_WRAP_CLAMP 0x812F // GL_CLAMP_TO_EDGE -#define RL_TEXTURE_WRAP_MIRROR_REPEAT 0x8370 // GL_MIRRORED_REPEAT -#define RL_TEXTURE_WRAP_MIRROR_CLAMP 0x8742 // GL_MIRROR_CLAMP_EXT - -// Matrix modes (equivalent to OpenGL) -#define RL_MODELVIEW 0x1700 // GL_MODELVIEW -#define RL_PROJECTION 0x1701 // GL_PROJECTION -#define RL_TEXTURE 0x1702 // GL_TEXTURE - -// Primitive assembly draw modes -#define RL_LINES 0x0001 // GL_LINES -#define RL_TRIANGLES 0x0004 // GL_TRIANGLES -#define RL_QUADS 0x0007 // GL_QUADS - -// GL equivalent data types -#define RL_UNSIGNED_BYTE 0x1401 // GL_UNSIGNED_BYTE -#define RL_FLOAT 0x1406 // GL_FLOAT - -// GL buffer usage hint -#define RL_STREAM_DRAW 0x88E0 // GL_STREAM_DRAW -#define RL_STREAM_READ 0x88E1 // GL_STREAM_READ -#define RL_STREAM_COPY 0x88E2 // GL_STREAM_COPY -#define RL_STATIC_DRAW 0x88E4 // GL_STATIC_DRAW -#define RL_STATIC_READ 0x88E5 // GL_STATIC_READ -#define RL_STATIC_COPY 0x88E6 // GL_STATIC_COPY -#define RL_DYNAMIC_DRAW 0x88E8 // GL_DYNAMIC_DRAW -#define RL_DYNAMIC_READ 0x88E9 // GL_DYNAMIC_READ -#define RL_DYNAMIC_COPY 0x88EA // GL_DYNAMIC_COPY - -// GL Shader type -#define RL_FRAGMENT_SHADER 0x8B30 // GL_FRAGMENT_SHADER -#define RL_VERTEX_SHADER 0x8B31 // GL_VERTEX_SHADER -#define RL_COMPUTE_SHADER 0x91B9 // GL_COMPUTE_SHADER - -// GL blending factors -#define RL_ZERO 0 // GL_ZERO -#define RL_ONE 1 // GL_ONE -#define RL_SRC_COLOR 0x0300 // GL_SRC_COLOR -#define RL_ONE_MINUS_SRC_COLOR 0x0301 // GL_ONE_MINUS_SRC_COLOR -#define RL_SRC_ALPHA 0x0302 // GL_SRC_ALPHA -#define RL_ONE_MINUS_SRC_ALPHA 0x0303 // GL_ONE_MINUS_SRC_ALPHA -#define RL_DST_ALPHA 0x0304 // GL_DST_ALPHA -#define RL_ONE_MINUS_DST_ALPHA 0x0305 // GL_ONE_MINUS_DST_ALPHA -#define RL_DST_COLOR 0x0306 // GL_DST_COLOR -#define RL_ONE_MINUS_DST_COLOR 0x0307 // GL_ONE_MINUS_DST_COLOR -#define RL_SRC_ALPHA_SATURATE 0x0308 // GL_SRC_ALPHA_SATURATE -#define RL_CONSTANT_COLOR 0x8001 // GL_CONSTANT_COLOR -#define RL_ONE_MINUS_CONSTANT_COLOR 0x8002 // GL_ONE_MINUS_CONSTANT_COLOR -#define RL_CONSTANT_ALPHA 0x8003 // GL_CONSTANT_ALPHA -#define RL_ONE_MINUS_CONSTANT_ALPHA 0x8004 // GL_ONE_MINUS_CONSTANT_ALPHA - -// GL blending functions/equations -#define RL_FUNC_ADD 0x8006 // GL_FUNC_ADD -#define RL_MIN 0x8007 // GL_MIN -#define RL_MAX 0x8008 // GL_MAX -#define RL_FUNC_SUBTRACT 0x800A // GL_FUNC_SUBTRACT -#define RL_FUNC_REVERSE_SUBTRACT 0x800B // GL_FUNC_REVERSE_SUBTRACT -#define RL_BLEND_EQUATION 0x8009 // GL_BLEND_EQUATION -#define RL_BLEND_EQUATION_RGB 0x8009 // GL_BLEND_EQUATION_RGB // (Same as BLEND_EQUATION) -#define RL_BLEND_EQUATION_ALPHA 0x883D // GL_BLEND_EQUATION_ALPHA -#define RL_BLEND_DST_RGB 0x80C8 // GL_BLEND_DST_RGB -#define RL_BLEND_SRC_RGB 0x80C9 // GL_BLEND_SRC_RGB -#define RL_BLEND_DST_ALPHA 0x80CA // GL_BLEND_DST_ALPHA -#define RL_BLEND_SRC_ALPHA 0x80CB // GL_BLEND_SRC_ALPHA -#define RL_BLEND_COLOR 0x8005 // GL_BLEND_COLOR - - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) - #include -#elif !defined(__cplusplus) && !defined(bool) && !defined(RL_BOOL_TYPE) - // Boolean type -typedef enum bool { false = 0, true = !false } bool; -#endif - -#if !defined(RL_MATRIX_TYPE) -// Matrix, 4x4 components, column major, OpenGL style, right handed -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; -#define RL_MATRIX_TYPE -#endif - -// Dynamic vertex buffers (position + texcoords + colors + indices arrays) -typedef struct rlVertexBuffer { - int elementCount; // Number of elements in the buffer (QUADS) - - float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - unsigned int *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - unsigned short *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) -#endif - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int vboId[4]; // OpenGL Vertex Buffer Objects id (4 types of vertex data) -} rlVertexBuffer; - -// Draw call type -// NOTE: Only texture changes register a new draw, other state-change-related elements are not -// used at this moment (vaoId, shaderId, matrices), raylib just forces a batch draw call if any -// of those state-change happens (this is done in core module) -typedef struct rlDrawCall { - int mode; // Drawing mode: LINES, TRIANGLES, QUADS - int vertexCount; // Number of vertex of the draw - int vertexAlignment; // Number of vertex required for index alignment (LINES, TRIANGLES) - //unsigned int vaoId; // Vertex array id to be used on the draw -> Using RLGL.currentBatch->vertexBuffer.vaoId - //unsigned int shaderId; // Shader id to be used on the draw -> Using RLGL.currentShaderId - unsigned int textureId; // Texture id to be used on the draw -> Use to create new draw call if changes - - //Matrix projection; // Projection matrix for this draw -> Using RLGL.projection by default - //Matrix modelview; // Modelview matrix for this draw -> Using RLGL.modelview by default -} rlDrawCall; - -// rlRenderBatch type -typedef struct rlRenderBatch { - int bufferCount; // Number of vertex buffers (multi-buffering support) - int currentBuffer; // Current buffer tracking in case of multi-buffering - rlVertexBuffer *vertexBuffer; // Dynamic buffer(s) for vertex data - - rlDrawCall *draws; // Draw calls array, depends on textureId - int drawCounter; // Draw calls counter - float currentDepth; // Current depth value for next draw -} rlRenderBatch; - -// OpenGL version -typedef enum { - RL_OPENGL_11 = 1, // OpenGL 1.1 - RL_OPENGL_21, // OpenGL 2.1 (GLSL 120) - RL_OPENGL_33, // OpenGL 3.3 (GLSL 330) - RL_OPENGL_43, // OpenGL 4.3 (using GLSL 330) - RL_OPENGL_ES_20, // OpenGL ES 2.0 (GLSL 100) - RL_OPENGL_ES_30 // OpenGL ES 3.0 (GLSL 300 es) -} rlGlVersion; - -// Trace log level -// NOTE: Organized by priority level -typedef enum { - RL_LOG_ALL = 0, // Display all logs - RL_LOG_TRACE, // Trace logging, intended for internal use only - RL_LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds - RL_LOG_INFO, // Info logging, used for program execution info - RL_LOG_WARNING, // Warning logging, used on recoverable failures - RL_LOG_ERROR, // Error logging, used on unrecoverable failures - RL_LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) - RL_LOG_NONE // Disable logging -} rlTraceLogLevel; - -// Texture pixel formats -// NOTE: Support depends on OpenGL version -typedef enum { - RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) - RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) - RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) - RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) - RL_PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) - RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) - RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) - RL_PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp -} rlPixelFormat; - -// Texture parameters: filter mode -// NOTE 1: Filtering considers mipmaps if available in the texture -// NOTE 2: Filter is accordingly set for minification and magnification -typedef enum { - RL_TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation - RL_TEXTURE_FILTER_BILINEAR, // Linear filtering - RL_TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) - RL_TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x - RL_TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x - RL_TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x -} rlTextureFilter; - -// Color blending modes (pre-defined) -typedef enum { - RL_BLEND_ALPHA = 0, // Blend textures considering alpha (default) - RL_BLEND_ADDITIVE, // Blend textures adding colors - RL_BLEND_MULTIPLIED, // Blend textures multiplying colors - RL_BLEND_ADD_COLORS, // Blend textures adding colors (alternative) - RL_BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) - RL_BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha - RL_BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) - RL_BLEND_CUSTOM_SEPARATE // Blend textures using custom src/dst factors (use rlSetBlendFactorsSeparate()) -} rlBlendMode; - -// Shader location point type -typedef enum { - RL_SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position - RL_SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 - RL_SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 - RL_SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal - RL_SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent - RL_SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color - RL_SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection - RL_SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) - RL_SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection - RL_SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) - RL_SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal - RL_SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view - RL_SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color - RL_SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color - RL_SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color - RL_SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: RL_SHADER_LOC_MAP_DIFFUSE) - RL_SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: RL_SHADER_LOC_MAP_SPECULAR) - RL_SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal - RL_SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness - RL_SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion - RL_SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission - RL_SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height - RL_SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap - RL_SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance - RL_SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter - RL_SHADER_LOC_MAP_BRDF // Shader location: sampler2d texture: brdf -} rlShaderLocationIndex; - -#define RL_SHADER_LOC_MAP_DIFFUSE RL_SHADER_LOC_MAP_ALBEDO -#define RL_SHADER_LOC_MAP_SPECULAR RL_SHADER_LOC_MAP_METALNESS - -// Shader uniform data type -typedef enum { - RL_SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float - RL_SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) - RL_SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) - RL_SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) - RL_SHADER_UNIFORM_INT, // Shader uniform type: int - RL_SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) - RL_SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) - RL_SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) - RL_SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d -} rlShaderUniformDataType; - -// Shader attribute data types -typedef enum { - RL_SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float - RL_SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) - RL_SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) - RL_SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) -} rlShaderAttributeDataType; - -// Framebuffer attachment type -// NOTE: By default up to 8 color channels defined, but it can be more -typedef enum { - RL_ATTACHMENT_COLOR_CHANNEL0 = 0, // Framebuffer attachment type: color 0 - RL_ATTACHMENT_COLOR_CHANNEL1 = 1, // Framebuffer attachment type: color 1 - RL_ATTACHMENT_COLOR_CHANNEL2 = 2, // Framebuffer attachment type: color 2 - RL_ATTACHMENT_COLOR_CHANNEL3 = 3, // Framebuffer attachment type: color 3 - RL_ATTACHMENT_COLOR_CHANNEL4 = 4, // Framebuffer attachment type: color 4 - RL_ATTACHMENT_COLOR_CHANNEL5 = 5, // Framebuffer attachment type: color 5 - RL_ATTACHMENT_COLOR_CHANNEL6 = 6, // Framebuffer attachment type: color 6 - RL_ATTACHMENT_COLOR_CHANNEL7 = 7, // Framebuffer attachment type: color 7 - RL_ATTACHMENT_DEPTH = 100, // Framebuffer attachment type: depth - RL_ATTACHMENT_STENCIL = 200, // Framebuffer attachment type: stencil -} rlFramebufferAttachType; - -// Framebuffer texture attachment type -typedef enum { - RL_ATTACHMENT_CUBEMAP_POSITIVE_X = 0, // Framebuffer texture attachment type: cubemap, +X side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_X = 1, // Framebuffer texture attachment type: cubemap, -X side - RL_ATTACHMENT_CUBEMAP_POSITIVE_Y = 2, // Framebuffer texture attachment type: cubemap, +Y side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_Y = 3, // Framebuffer texture attachment type: cubemap, -Y side - RL_ATTACHMENT_CUBEMAP_POSITIVE_Z = 4, // Framebuffer texture attachment type: cubemap, +Z side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_Z = 5, // Framebuffer texture attachment type: cubemap, -Z side - RL_ATTACHMENT_TEXTURE2D = 100, // Framebuffer texture attachment type: texture2d - RL_ATTACHMENT_RENDERBUFFER = 200, // Framebuffer texture attachment type: renderbuffer -} rlFramebufferAttachTextureType; - -// Face culling mode -typedef enum { - RL_CULL_FACE_FRONT = 0, - RL_CULL_FACE_BACK -} rlCullMode; - -//------------------------------------------------------------------------------------ -// Functions Declaration - Matrix operations -//------------------------------------------------------------------------------------ - -#if defined(__cplusplus) -extern "C" { // Prevents name mangling of functions -#endif - -RLAPI void rlMatrixMode(int mode); // Choose the current matrix to be transformed -RLAPI void rlPushMatrix(void); // Push the current matrix to stack -RLAPI void rlPopMatrix(void); // Pop latest inserted matrix from stack -RLAPI void rlLoadIdentity(void); // Reset current matrix to identity matrix -RLAPI void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix -RLAPI void rlRotatef(float angle, float x, float y, float z); // Multiply the current matrix by a rotation matrix -RLAPI void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix -RLAPI void rlMultMatrixf(const float *matf); // Multiply the current matrix by another matrix -RLAPI void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar); -RLAPI void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar); -RLAPI void rlViewport(int x, int y, int width, int height); // Set the viewport area - -//------------------------------------------------------------------------------------ -// Functions Declaration - Vertex level operations -//------------------------------------------------------------------------------------ -RLAPI void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) -RLAPI void rlEnd(void); // Finish vertex providing -RLAPI void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int -RLAPI void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float -RLAPI void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float -RLAPI void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float -RLAPI void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float -RLAPI void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Define one vertex (color) - 4 byte -RLAPI void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float -RLAPI void rlColor4f(float x, float y, float z, float w); // Define one vertex (color) - 4 float - -//------------------------------------------------------------------------------------ -// Functions Declaration - OpenGL style functions (common to 1.1, 3.3+, ES2) -// NOTE: This functions are used to completely abstract raylib code from OpenGL layer, -// some of them are direct wrappers over OpenGL calls, some others are custom -//------------------------------------------------------------------------------------ - -// Vertex buffers state -RLAPI bool rlEnableVertexArray(unsigned int vaoId); // Enable vertex array (VAO, if supported) -RLAPI void rlDisableVertexArray(void); // Disable vertex array (VAO, if supported) -RLAPI void rlEnableVertexBuffer(unsigned int id); // Enable vertex buffer (VBO) -RLAPI void rlDisableVertexBuffer(void); // Disable vertex buffer (VBO) -RLAPI void rlEnableVertexBufferElement(unsigned int id);// Enable vertex buffer element (VBO element) -RLAPI void rlDisableVertexBufferElement(void); // Disable vertex buffer element (VBO element) -RLAPI void rlEnableVertexAttribute(unsigned int index); // Enable vertex attribute index -RLAPI void rlDisableVertexAttribute(unsigned int index);// Disable vertex attribute index -#if defined(GRAPHICS_API_OPENGL_11) -RLAPI void rlEnableStatePointer(int vertexAttribType, void *buffer); // Enable attribute state pointer -RLAPI void rlDisableStatePointer(int vertexAttribType); // Disable attribute state pointer -#endif - -// Textures state -RLAPI void rlActiveTextureSlot(int slot); // Select and active a texture slot -RLAPI void rlEnableTexture(unsigned int id); // Enable texture -RLAPI void rlDisableTexture(void); // Disable texture -RLAPI void rlEnableTextureCubemap(unsigned int id); // Enable texture cubemap -RLAPI void rlDisableTextureCubemap(void); // Disable texture cubemap -RLAPI void rlTextureParameters(unsigned int id, int param, int value); // Set texture parameters (filter, wrap) -RLAPI void rlCubemapParameters(unsigned int id, int param, int value); // Set cubemap parameters (filter, wrap) - -// Shader state -RLAPI void rlEnableShader(unsigned int id); // Enable shader program -RLAPI void rlDisableShader(void); // Disable shader program - -// Framebuffer state -RLAPI void rlEnableFramebuffer(unsigned int id); // Enable render texture (fbo) -RLAPI void rlDisableFramebuffer(void); // Disable render texture (fbo), return to default framebuffer -RLAPI void rlActiveDrawBuffers(int count); // Activate multiple draw color buffers -RLAPI void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask); // Blit active framebuffer to main framebuffer - -// General render state -RLAPI void rlEnableColorBlend(void); // Enable color blending -RLAPI void rlDisableColorBlend(void); // Disable color blending -RLAPI void rlEnableDepthTest(void); // Enable depth test -RLAPI void rlDisableDepthTest(void); // Disable depth test -RLAPI void rlEnableDepthMask(void); // Enable depth write -RLAPI void rlDisableDepthMask(void); // Disable depth write -RLAPI void rlEnableBackfaceCulling(void); // Enable backface culling -RLAPI void rlDisableBackfaceCulling(void); // Disable backface culling -RLAPI void rlSetCullFace(int mode); // Set face culling mode -RLAPI void rlEnableScissorTest(void); // Enable scissor test -RLAPI void rlDisableScissorTest(void); // Disable scissor test -RLAPI void rlScissor(int x, int y, int width, int height); // Scissor test -RLAPI void rlEnableWireMode(void); // Enable wire mode -RLAPI void rlEnablePointMode(void); // Enable point mode -RLAPI void rlDisableWireMode(void); // Disable wire mode ( and point ) maybe rename -RLAPI void rlSetLineWidth(float width); // Set the line drawing width -RLAPI float rlGetLineWidth(void); // Get the line drawing width -RLAPI void rlEnableSmoothLines(void); // Enable line aliasing -RLAPI void rlDisableSmoothLines(void); // Disable line aliasing -RLAPI void rlEnableStereoRender(void); // Enable stereo rendering -RLAPI void rlDisableStereoRender(void); // Disable stereo rendering -RLAPI bool rlIsStereoRenderEnabled(void); // Check if stereo render is enabled - -RLAPI void rlClearColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Clear color buffer with color -RLAPI void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) -RLAPI void rlCheckErrors(void); // Check and log OpenGL error codes -RLAPI void rlSetBlendMode(int mode); // Set blending mode -RLAPI void rlSetBlendFactors(int glSrcFactor, int glDstFactor, int glEquation); // Set blending mode factor and equation (using OpenGL factors) -RLAPI void rlSetBlendFactorsSeparate(int glSrcRGB, int glDstRGB, int glSrcAlpha, int glDstAlpha, int glEqRGB, int glEqAlpha); // Set blending mode factors and equations separately (using OpenGL factors) - -//------------------------------------------------------------------------------------ -// Functions Declaration - rlgl functionality -//------------------------------------------------------------------------------------ -// rlgl initialization functions -RLAPI void rlglInit(int width, int height); // Initialize rlgl (buffers, shaders, textures, states) -RLAPI void rlglClose(void); // De-initialize rlgl (buffers, shaders, textures) -RLAPI void rlLoadExtensions(void *loader); // Load OpenGL extensions (loader function required) -RLAPI int rlGetVersion(void); // Get current OpenGL version -RLAPI void rlSetFramebufferWidth(int width); // Set current framebuffer width -RLAPI int rlGetFramebufferWidth(void); // Get default framebuffer width -RLAPI void rlSetFramebufferHeight(int height); // Set current framebuffer height -RLAPI int rlGetFramebufferHeight(void); // Get default framebuffer height - -RLAPI unsigned int rlGetTextureIdDefault(void); // Get default texture id -RLAPI unsigned int rlGetShaderIdDefault(void); // Get default shader id -RLAPI int *rlGetShaderLocsDefault(void); // Get default shader locations - -// Render batch management -// NOTE: rlgl provides a default render batch to behave like OpenGL 1.1 immediate mode -// but this render batch API is exposed in case of custom batches are required -RLAPI rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements); // Load a render batch system -RLAPI void rlUnloadRenderBatch(rlRenderBatch batch); // Unload render batch system -RLAPI void rlDrawRenderBatch(rlRenderBatch *batch); // Draw render batch data (Update->Draw->Reset) -RLAPI void rlSetRenderBatchActive(rlRenderBatch *batch); // Set the active render batch for rlgl (NULL for default internal) -RLAPI void rlDrawRenderBatchActive(void); // Update and draw internal render batch -RLAPI bool rlCheckRenderBatchLimit(int vCount); // Check internal buffer overflow for a given number of vertex - -RLAPI void rlSetTexture(unsigned int id); // Set current texture for render batch and check buffers limits - -//------------------------------------------------------------------------------------------------------------------------ - -// Vertex buffers management -RLAPI unsigned int rlLoadVertexArray(void); // Load vertex array (vao) if supported -RLAPI unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic); // Load a vertex buffer attribute -RLAPI unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic); // Load a new attributes element buffer -RLAPI void rlUpdateVertexBuffer(unsigned int bufferId, const void *data, int dataSize, int offset); // Update GPU buffer with new data -RLAPI void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset); // Update vertex buffer elements with new data -RLAPI void rlUnloadVertexArray(unsigned int vaoId); -RLAPI void rlUnloadVertexBuffer(unsigned int vboId); -RLAPI void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, const void *pointer); -RLAPI void rlSetVertexAttributeDivisor(unsigned int index, int divisor); -RLAPI void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count); // Set vertex attribute default value -RLAPI void rlDrawVertexArray(int offset, int count); -RLAPI void rlDrawVertexArrayElements(int offset, int count, const void *buffer); -RLAPI void rlDrawVertexArrayInstanced(int offset, int count, int instances); -RLAPI void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances); - -// Textures management -RLAPI unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount); // Load texture in GPU -RLAPI unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer); // Load depth texture/renderbuffer (to be attached to fbo) -RLAPI unsigned int rlLoadTextureCubemap(const void *data, int size, int format); // Load texture cubemap -RLAPI void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data); // Update GPU texture with new data -RLAPI void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType); // Get OpenGL internal formats -RLAPI const char *rlGetPixelFormatName(unsigned int format); // Get name string for pixel format -RLAPI void rlUnloadTexture(unsigned int id); // Unload texture from GPU memory -RLAPI void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps); // Generate mipmap data for selected texture -RLAPI void *rlReadTexturePixels(unsigned int id, int width, int height, int format); // Read texture pixel data -RLAPI unsigned char *rlReadScreenPixels(int width, int height); // Read screen pixel data (color buffer) - -// Framebuffer management (fbo) -RLAPI unsigned int rlLoadFramebuffer(int width, int height); // Load an empty framebuffer -RLAPI void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel); // Attach texture/renderbuffer to a framebuffer -RLAPI bool rlFramebufferComplete(unsigned int id); // Verify framebuffer is complete -RLAPI void rlUnloadFramebuffer(unsigned int id); // Delete framebuffer from GPU - -// Shaders management -RLAPI unsigned int rlLoadShaderCode(const char *vsCode, const char *fsCode); // Load shader from code strings -RLAPI unsigned int rlCompileShader(const char *shaderCode, int type); // Compile custom shader and return shader id (type: RL_VERTEX_SHADER, RL_FRAGMENT_SHADER, RL_COMPUTE_SHADER) -RLAPI unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId); // Load custom shader program -RLAPI void rlUnloadShaderProgram(unsigned int id); // Unload shader program -RLAPI int rlGetLocationUniform(unsigned int shaderId, const char *uniformName); // Get shader location uniform -RLAPI int rlGetLocationAttrib(unsigned int shaderId, const char *attribName); // Get shader location attribute -RLAPI void rlSetUniform(int locIndex, const void *value, int uniformType, int count); // Set shader value uniform -RLAPI void rlSetUniformMatrix(int locIndex, Matrix mat); // Set shader value matrix -RLAPI void rlSetUniformSampler(int locIndex, unsigned int textureId); // Set shader value sampler -RLAPI void rlSetShader(unsigned int id, int *locs); // Set shader currently active (id and locations) - -// Compute shader management -RLAPI unsigned int rlLoadComputeShaderProgram(unsigned int shaderId); // Load compute shader program -RLAPI void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ); // Dispatch compute shader (equivalent to *draw* for graphics pipeline) - -// Shader buffer storage object management (ssbo) -RLAPI unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint); // Load shader storage buffer object (SSBO) -RLAPI void rlUnloadShaderBuffer(unsigned int ssboId); // Unload shader storage buffer object (SSBO) -RLAPI void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset); // Update SSBO buffer data -RLAPI void rlBindShaderBuffer(unsigned int id, unsigned int index); // Bind SSBO buffer -RLAPI void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset); // Read SSBO buffer data (GPU->CPU) -RLAPI void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count); // Copy SSBO data between buffers -RLAPI unsigned int rlGetShaderBufferSize(unsigned int id); // Get SSBO buffer size - -// Buffer management -RLAPI void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly); // Bind image texture - -// Matrix state management -RLAPI Matrix rlGetMatrixModelview(void); // Get internal modelview matrix -RLAPI Matrix rlGetMatrixProjection(void); // Get internal projection matrix -RLAPI Matrix rlGetMatrixTransform(void); // Get internal accumulated transform matrix -RLAPI Matrix rlGetMatrixProjectionStereo(int eye); // Get internal projection matrix for stereo render (selected eye) -RLAPI Matrix rlGetMatrixViewOffsetStereo(int eye); // Get internal view offset matrix for stereo render (selected eye) -RLAPI void rlSetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) -RLAPI void rlSetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) -RLAPI void rlSetMatrixProjectionStereo(Matrix right, Matrix left); // Set eyes projection matrices for stereo rendering -RLAPI void rlSetMatrixViewOffsetStereo(Matrix right, Matrix left); // Set eyes view offsets matrices for stereo rendering - -// Quick and dirty cube/quad buffers load->draw->unload -RLAPI void rlLoadDrawCube(void); // Load and draw a cube -RLAPI void rlLoadDrawQuad(void); // Load and draw a quad - -#if defined(__cplusplus) -} -#endif - -#endif // RLGL_H - -/*********************************************************************************** -* -* RLGL IMPLEMENTATION -* -************************************************************************************/ - -#if defined(RLGL_IMPLEMENTATION) - -#if defined(GRAPHICS_API_OPENGL_11) - #if defined(__APPLE__) - #include // OpenGL 1.1 library for OSX - #include // OpenGL extensions library - #else - // APIENTRY for OpenGL function pointer declarations is required - #if !defined(APIENTRY) - #if defined(_WIN32) - #define APIENTRY __stdcall - #else - #define APIENTRY - #endif - #endif - // WINGDIAPI definition. Some Windows OpenGL headers need it - #if !defined(WINGDIAPI) && defined(_WIN32) - #define WINGDIAPI __declspec(dllimport) - #endif - - #include // OpenGL 1.1 library - #endif -#endif - -#if defined(GRAPHICS_API_OPENGL_33) - #define GLAD_MALLOC RL_MALLOC - #define GLAD_FREE RL_FREE - - #define GLAD_GL_IMPLEMENTATION - #include "external/glad.h" // GLAD extensions loading library, includes OpenGL headers -#endif - -#if defined(GRAPHICS_API_OPENGL_ES3) - #include // OpenGL ES 3.0 library - #define GL_GLEXT_PROTOTYPES - #include // OpenGL ES 2.0 extensions library -#elif defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: OpenGL ES 2.0 can be enabled on PLATFORM_DESKTOP, - // in that case, functions are loaded from a custom glad for OpenGL ES 2.0 - #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_DESKTOP_SDL) - #define GLAD_GLES2_IMPLEMENTATION - #include "external/glad_gles2.h" - #else - #define GL_GLEXT_PROTOTYPES - //#include // EGL library -> not required, platform layer - #include // OpenGL ES 2.0 library - #include // OpenGL ES 2.0 extensions library - #endif - - // It seems OpenGL ES 2.0 instancing entry points are not defined on Raspberry Pi - // provided headers (despite being defined in official Khronos GLES2 headers) - #if defined(PLATFORM_DRM) - typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); - typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); - typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISOREXTPROC) (GLuint index, GLuint divisor); - #endif -#endif - -#include // Required for: malloc(), free() -#include // Required for: strcmp(), strlen() [Used in rlglInit(), on extensions loading] -#include // Required for: sqrtf(), sinf(), cosf(), floor(), log() - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -#ifndef GL_SHADING_LANGUAGE_VERSION - #define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#endif - -#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT - #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 -#endif -#ifndef GL_ETC1_RGB8_OES - #define GL_ETC1_RGB8_OES 0x8D64 -#endif -#ifndef GL_COMPRESSED_RGB8_ETC2 - #define GL_COMPRESSED_RGB8_ETC2 0x9274 -#endif -#ifndef GL_COMPRESSED_RGBA8_ETC2_EAC - #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#endif -#ifndef GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG - #define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 -#endif -#ifndef GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG - #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 -#endif -#ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR - #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93b0 -#endif -#ifndef GL_COMPRESSED_RGBA_ASTC_8x8_KHR - #define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93b7 -#endif - -#ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -#endif -#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - #define GL_UNSIGNED_SHORT_5_6_5 0x8363 - #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 - #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#endif - -#if defined(GRAPHICS_API_OPENGL_21) - #define GL_LUMINANCE 0x1909 - #define GL_LUMINANCE_ALPHA 0x190A -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - #define glClearDepth glClearDepthf - #if !defined(GRAPHICS_API_OPENGL_ES3) - #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER - #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER - #endif -#endif - -// Default shader vertex attribute names to set location points -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION - #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: 0 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: 1 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL - #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: 2 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR - #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: 3 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: 4 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: 5 -#endif - -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MVP - #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW - #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION - #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL - #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL - #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView)) -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR - #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -typedef struct rlglData { - rlRenderBatch *currentBatch; // Current render batch - rlRenderBatch defaultBatch; // Default internal render batch - - struct { - int vertexCounter; // Current active render batch vertex counter (generic, used for all batches) - float texcoordx, texcoordy; // Current active texture coordinate (added on glVertex*()) - float normalx, normaly, normalz; // Current active normal (added on glVertex*()) - unsigned char colorr, colorg, colorb, colora; // Current active color (added on glVertex*()) - - int currentMatrixMode; // Current matrix mode - Matrix *currentMatrix; // Current matrix pointer - Matrix modelview; // Default modelview matrix - Matrix projection; // Default projection matrix - Matrix transform; // Transform matrix to be used with rlTranslate, rlRotate, rlScale - bool transformRequired; // Require transform matrix application to current draw-call vertex (if required) - Matrix stack[RL_MAX_MATRIX_STACK_SIZE];// Matrix stack for push/pop - int stackCounter; // Matrix stack counter - - unsigned int defaultTextureId; // Default texture used on shapes/poly drawing (required by shader) - unsigned int activeTextureId[RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS]; // Active texture ids to be enabled on batch drawing (0 active by default) - unsigned int defaultVShaderId; // Default vertex shader id (used by default shader program) - unsigned int defaultFShaderId; // Default fragment shader id (used by default shader program) - unsigned int defaultShaderId; // Default shader program id, supports vertex color and diffuse texture - int *defaultShaderLocs; // Default shader locations pointer to be used on rendering - unsigned int currentShaderId; // Current shader id to be used on rendering (by default, defaultShaderId) - int *currentShaderLocs; // Current shader locations pointer to be used on rendering (by default, defaultShaderLocs) - - bool stereoRender; // Stereo rendering flag - Matrix projectionStereo[2]; // VR stereo rendering eyes projection matrices - Matrix viewOffsetStereo[2]; // VR stereo rendering eyes view offset matrices - - // Blending variables - int currentBlendMode; // Blending mode active - int glBlendSrcFactor; // Blending source factor - int glBlendDstFactor; // Blending destination factor - int glBlendEquation; // Blending equation - int glBlendSrcFactorRGB; // Blending source RGB factor - int glBlendDestFactorRGB; // Blending destination RGB factor - int glBlendSrcFactorAlpha; // Blending source alpha factor - int glBlendDestFactorAlpha; // Blending destination alpha factor - int glBlendEquationRGB; // Blending equation for RGB - int glBlendEquationAlpha; // Blending equation for alpha - bool glCustomBlendModeModified; // Custom blending factor and equation modification status - - int framebufferWidth; // Current framebuffer width - int framebufferHeight; // Current framebuffer height - - } State; // Renderer state - struct { - bool vao; // VAO support (OpenGL ES2 could not support VAO extension) (GL_ARB_vertex_array_object) - bool instancing; // Instancing supported (GL_ANGLE_instanced_arrays, GL_EXT_draw_instanced + GL_EXT_instanced_arrays) - bool texNPOT; // NPOT textures full support (GL_ARB_texture_non_power_of_two, GL_OES_texture_npot) - bool texDepth; // Depth textures supported (GL_ARB_depth_texture, GL_OES_depth_texture) - bool texDepthWebGL; // Depth textures supported WebGL specific (GL_WEBGL_depth_texture) - bool texFloat32; // float textures support (32 bit per channel) (GL_OES_texture_float) - bool texFloat16; // half float textures support (16 bit per channel) (GL_OES_texture_half_float) - bool texCompDXT; // DDS texture compression support (GL_EXT_texture_compression_s3tc, GL_WEBGL_compressed_texture_s3tc, GL_WEBKIT_WEBGL_compressed_texture_s3tc) - bool texCompETC1; // ETC1 texture compression support (GL_OES_compressed_ETC1_RGB8_texture, GL_WEBGL_compressed_texture_etc1) - bool texCompETC2; // ETC2/EAC texture compression support (GL_ARB_ES3_compatibility) - bool texCompPVRT; // PVR texture compression support (GL_IMG_texture_compression_pvrtc) - bool texCompASTC; // ASTC texture compression support (GL_KHR_texture_compression_astc_hdr, GL_KHR_texture_compression_astc_ldr) - bool texMirrorClamp; // Clamp mirror wrap mode supported (GL_EXT_texture_mirror_clamp) - bool texAnisoFilter; // Anisotropic texture filtering support (GL_EXT_texture_filter_anisotropic) - bool computeShader; // Compute shaders support (GL_ARB_compute_shader) - bool ssbo; // Shader storage buffer object support (GL_ARB_shader_storage_buffer_object) - - float maxAnisotropyLevel; // Maximum anisotropy level supported (minimum is 2.0f) - int maxDepthBits; // Maximum bits for depth component - - } ExtSupported; // Extensions supported flags -} rlglData; - -typedef void *(*rlglLoadProc)(const char *name); // OpenGL extension functions loader signature (same as GLADloadproc) - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -static rlglData RLGL = { 0 }; -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -#if defined(GRAPHICS_API_OPENGL_ES2) && !defined(GRAPHICS_API_OPENGL_ES3) -// NOTE: VAO functionality is exposed through extensions (OES) -static PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays = NULL; -static PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray = NULL; -static PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays = NULL; - -// NOTE: Instancing functionality could also be available through extension -static PFNGLDRAWARRAYSINSTANCEDEXTPROC glDrawArraysInstanced = NULL; -static PFNGLDRAWELEMENTSINSTANCEDEXTPROC glDrawElementsInstanced = NULL; -static PFNGLVERTEXATTRIBDIVISOREXTPROC glVertexAttribDivisor = NULL; -#endif - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -static void rlLoadShaderDefault(void); // Load default shader -static void rlUnloadShaderDefault(void); // Unload default shader -#if defined(RLGL_SHOW_GL_DETAILS_INFO) -static const char *rlGetCompressedFormatName(int format); // Get compressed format official GL identifier name -#endif // RLGL_SHOW_GL_DETAILS_INFO -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -static int rlGetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes (image or texture) - -// Auxiliar matrix math functions -static Matrix rlMatrixIdentity(void); // Get identity matrix -static Matrix rlMatrixMultiply(Matrix left, Matrix right); // Multiply two matrices - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Matrix operations -//---------------------------------------------------------------------------------- - -#if defined(GRAPHICS_API_OPENGL_11) -// Fallback to OpenGL 1.1 function calls -//--------------------------------------- -void rlMatrixMode(int mode) -{ - switch (mode) - { - case RL_PROJECTION: glMatrixMode(GL_PROJECTION); break; - case RL_MODELVIEW: glMatrixMode(GL_MODELVIEW); break; - case RL_TEXTURE: glMatrixMode(GL_TEXTURE); break; - default: break; - } -} - -void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) -{ - glFrustum(left, right, bottom, top, znear, zfar); -} - -void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) -{ - glOrtho(left, right, bottom, top, znear, zfar); -} - -void rlPushMatrix(void) { glPushMatrix(); } -void rlPopMatrix(void) { glPopMatrix(); } -void rlLoadIdentity(void) { glLoadIdentity(); } -void rlTranslatef(float x, float y, float z) { glTranslatef(x, y, z); } -void rlRotatef(float angle, float x, float y, float z) { glRotatef(angle, x, y, z); } -void rlScalef(float x, float y, float z) { glScalef(x, y, z); } -void rlMultMatrixf(const float *matf) { glMultMatrixf(matf); } -#endif -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Choose the current matrix to be transformed -void rlMatrixMode(int mode) -{ - if (mode == RL_PROJECTION) RLGL.State.currentMatrix = &RLGL.State.projection; - else if (mode == RL_MODELVIEW) RLGL.State.currentMatrix = &RLGL.State.modelview; - //else if (mode == RL_TEXTURE) // Not supported - - RLGL.State.currentMatrixMode = mode; -} - -// Push the current matrix into RLGL.State.stack -void rlPushMatrix(void) -{ - if (RLGL.State.stackCounter >= RL_MAX_MATRIX_STACK_SIZE) TRACELOG(RL_LOG_ERROR, "RLGL: Matrix stack overflow (RL_MAX_MATRIX_STACK_SIZE)"); - - if (RLGL.State.currentMatrixMode == RL_MODELVIEW) - { - RLGL.State.transformRequired = true; - RLGL.State.currentMatrix = &RLGL.State.transform; - } - - RLGL.State.stack[RLGL.State.stackCounter] = *RLGL.State.currentMatrix; - RLGL.State.stackCounter++; -} - -// Pop lattest inserted matrix from RLGL.State.stack -void rlPopMatrix(void) -{ - if (RLGL.State.stackCounter > 0) - { - Matrix mat = RLGL.State.stack[RLGL.State.stackCounter - 1]; - *RLGL.State.currentMatrix = mat; - RLGL.State.stackCounter--; - } - - if ((RLGL.State.stackCounter == 0) && (RLGL.State.currentMatrixMode == RL_MODELVIEW)) - { - RLGL.State.currentMatrix = &RLGL.State.modelview; - RLGL.State.transformRequired = false; - } -} - -// Reset current matrix to identity matrix -void rlLoadIdentity(void) -{ - *RLGL.State.currentMatrix = rlMatrixIdentity(); -} - -// Multiply the current matrix by a translation matrix -void rlTranslatef(float x, float y, float z) -{ - Matrix matTranslation = { - 1.0f, 0.0f, 0.0f, x, - 0.0f, 1.0f, 0.0f, y, - 0.0f, 0.0f, 1.0f, z, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matTranslation, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by a rotation matrix -// NOTE: The provided angle must be in degrees -void rlRotatef(float angle, float x, float y, float z) -{ - Matrix matRotation = rlMatrixIdentity(); - - // Axis vector (x, y, z) normalization - float lengthSquared = x*x + y*y + z*z; - if ((lengthSquared != 1.0f) && (lengthSquared != 0.0f)) - { - float inverseLength = 1.0f/sqrtf(lengthSquared); - x *= inverseLength; - y *= inverseLength; - z *= inverseLength; - } - - // Rotation matrix generation - float sinres = sinf(DEG2RAD*angle); - float cosres = cosf(DEG2RAD*angle); - float t = 1.0f - cosres; - - matRotation.m0 = x*x*t + cosres; - matRotation.m1 = y*x*t + z*sinres; - matRotation.m2 = z*x*t - y*sinres; - matRotation.m3 = 0.0f; - - matRotation.m4 = x*y*t - z*sinres; - matRotation.m5 = y*y*t + cosres; - matRotation.m6 = z*y*t + x*sinres; - matRotation.m7 = 0.0f; - - matRotation.m8 = x*z*t + y*sinres; - matRotation.m9 = y*z*t - x*sinres; - matRotation.m10 = z*z*t + cosres; - matRotation.m11 = 0.0f; - - matRotation.m12 = 0.0f; - matRotation.m13 = 0.0f; - matRotation.m14 = 0.0f; - matRotation.m15 = 1.0f; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matRotation, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by a scaling matrix -void rlScalef(float x, float y, float z) -{ - Matrix matScale = { - x, 0.0f, 0.0f, 0.0f, - 0.0f, y, 0.0f, 0.0f, - 0.0f, 0.0f, z, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matScale, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by another matrix -void rlMultMatrixf(const float *matf) -{ - // Matrix creation from array - Matrix mat = { matf[0], matf[4], matf[8], matf[12], - matf[1], matf[5], matf[9], matf[13], - matf[2], matf[6], matf[10], matf[14], - matf[3], matf[7], matf[11], matf[15] }; - - *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, mat); -} - -// Multiply the current matrix by a perspective matrix generated by parameters -void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) -{ - Matrix matFrustum = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(zfar - znear); - - matFrustum.m0 = ((float) znear*2.0f)/rl; - matFrustum.m1 = 0.0f; - matFrustum.m2 = 0.0f; - matFrustum.m3 = 0.0f; - - matFrustum.m4 = 0.0f; - matFrustum.m5 = ((float) znear*2.0f)/tb; - matFrustum.m6 = 0.0f; - matFrustum.m7 = 0.0f; - - matFrustum.m8 = ((float)right + (float)left)/rl; - matFrustum.m9 = ((float)top + (float)bottom)/tb; - matFrustum.m10 = -((float)zfar + (float)znear)/fn; - matFrustum.m11 = -1.0f; - - matFrustum.m12 = 0.0f; - matFrustum.m13 = 0.0f; - matFrustum.m14 = -((float)zfar*(float)znear*2.0f)/fn; - matFrustum.m15 = 0.0f; - - *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, matFrustum); -} - -// Multiply the current matrix by an orthographic matrix generated by parameters -void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) -{ - // NOTE: If left-right and top-botton values are equal it could create a division by zero, - // response to it is platform/compiler dependant - Matrix matOrtho = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(zfar - znear); - - matOrtho.m0 = 2.0f/rl; - matOrtho.m1 = 0.0f; - matOrtho.m2 = 0.0f; - matOrtho.m3 = 0.0f; - matOrtho.m4 = 0.0f; - matOrtho.m5 = 2.0f/tb; - matOrtho.m6 = 0.0f; - matOrtho.m7 = 0.0f; - matOrtho.m8 = 0.0f; - matOrtho.m9 = 0.0f; - matOrtho.m10 = -2.0f/fn; - matOrtho.m11 = 0.0f; - matOrtho.m12 = -((float)left + (float)right)/rl; - matOrtho.m13 = -((float)top + (float)bottom)/tb; - matOrtho.m14 = -((float)zfar + (float)znear)/fn; - matOrtho.m15 = 1.0f; - - *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, matOrtho); -} -#endif - -// Set the viewport area (transformation from normalized device coordinates to window coordinates) -// NOTE: We store current viewport dimensions -void rlViewport(int x, int y, int width, int height) -{ - glViewport(x, y, width, height); -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vertex level operations -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_11) -// Fallback to OpenGL 1.1 function calls -//--------------------------------------- -void rlBegin(int mode) -{ - switch (mode) - { - case RL_LINES: glBegin(GL_LINES); break; - case RL_TRIANGLES: glBegin(GL_TRIANGLES); break; - case RL_QUADS: glBegin(GL_QUADS); break; - default: break; - } -} - -void rlEnd() { glEnd(); } -void rlVertex2i(int x, int y) { glVertex2i(x, y); } -void rlVertex2f(float x, float y) { glVertex2f(x, y); } -void rlVertex3f(float x, float y, float z) { glVertex3f(x, y, z); } -void rlTexCoord2f(float x, float y) { glTexCoord2f(x, y); } -void rlNormal3f(float x, float y, float z) { glNormal3f(x, y, z); } -void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { glColor4ub(r, g, b, a); } -void rlColor3f(float x, float y, float z) { glColor3f(x, y, z); } -void rlColor4f(float x, float y, float z, float w) { glColor4f(x, y, z, w); } -#endif -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Initialize drawing mode (how to organize vertex) -void rlBegin(int mode) -{ - // Draw mode can be RL_LINES, RL_TRIANGLES and RL_QUADS - // NOTE: In all three cases, vertex are accumulated over default internal vertex buffer - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode != mode) - { - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount > 0) - { - // Make sure current RLGL.currentBatch->draws[i].vertexCount is aligned a multiple of 4, - // that way, following QUADS drawing will keep aligned with index processing - // It implies adding some extra alignment vertex at the end of the draw, - // those vertex are not processed but they are considered as an additional offset - // for the next set of vertex to be drawn - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount : RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4); - else if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? 1 : (4 - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4))); - else RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = 0; - - if (!rlCheckRenderBatchLimit(RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment)) - { - RLGL.State.vertexCounter += RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment; - RLGL.currentBatch->drawCounter++; - } - } - - if (RLGL.currentBatch->drawCounter >= RL_DEFAULT_BATCH_DRAWCALLS) rlDrawRenderBatch(RLGL.currentBatch); - - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode = mode; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount = 0; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = RLGL.State.defaultTextureId; - } -} - -// Finish vertex providing -void rlEnd(void) -{ - // NOTE: Depth increment is dependant on rlOrtho(): z-near and z-far values, - // as well as depth buffer bit-depth (16bit or 24bit or 32bit) - // Correct increment formula would be: depthInc = (zfar - znear)/pow(2, bits) - RLGL.currentBatch->currentDepth += (1.0f/20000.0f); -} - -// Define one vertex (position) -// NOTE: Vertex position data is the basic information required for drawing -void rlVertex3f(float x, float y, float z) -{ - float tx = x; - float ty = y; - float tz = z; - - // Transform provided vector if required - if (RLGL.State.transformRequired) - { - tx = RLGL.State.transform.m0*x + RLGL.State.transform.m4*y + RLGL.State.transform.m8*z + RLGL.State.transform.m12; - ty = RLGL.State.transform.m1*x + RLGL.State.transform.m5*y + RLGL.State.transform.m9*z + RLGL.State.transform.m13; - tz = RLGL.State.transform.m2*x + RLGL.State.transform.m6*y + RLGL.State.transform.m10*z + RLGL.State.transform.m14; - } - - // WARNING: We can't break primitives when launching a new batch. - // RL_LINES comes in pairs, RL_TRIANGLES come in groups of 3 vertices and RL_QUADS come in groups of 4 vertices. - // We must check current draw.mode when a new vertex is required and finish the batch only if the draw.mode draw.vertexCount is %2, %3 or %4 - if (RLGL.State.vertexCounter > (RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4 - 4)) - { - if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%2 == 0)) - { - // Reached the maximum number of vertices for RL_LINES drawing - // Launch a draw call but keep current state for next vertices comming - // NOTE: We add +1 vertex to the check for security - rlCheckRenderBatchLimit(2 + 1); - } - else if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%3 == 0)) - { - rlCheckRenderBatchLimit(3 + 1); - } - else if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_QUADS) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4 == 0)) - { - rlCheckRenderBatchLimit(4 + 1); - } - } - - // Add vertices - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter] = tx; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter + 1] = ty; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter + 2] = tz; - - // Add current texcoord - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter] = RLGL.State.texcoordx; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter + 1] = RLGL.State.texcoordy; - - // WARNING: By default rlVertexBuffer struct does not store normals - - // Add current color - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter] = RLGL.State.colorr; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 1] = RLGL.State.colorg; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 2] = RLGL.State.colorb; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 3] = RLGL.State.colora; - - RLGL.State.vertexCounter++; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount++; -} - -// Define one vertex (position) -void rlVertex2f(float x, float y) -{ - rlVertex3f(x, y, RLGL.currentBatch->currentDepth); -} - -// Define one vertex (position) -void rlVertex2i(int x, int y) -{ - rlVertex3f((float)x, (float)y, RLGL.currentBatch->currentDepth); -} - -// Define one vertex (texture coordinate) -// NOTE: Texture coordinates are limited to QUADS only -void rlTexCoord2f(float x, float y) -{ - RLGL.State.texcoordx = x; - RLGL.State.texcoordy = y; -} - -// Define one vertex (normal) -// NOTE: Normals limited to TRIANGLES only? -void rlNormal3f(float x, float y, float z) -{ - RLGL.State.normalx = x; - RLGL.State.normaly = y; - RLGL.State.normalz = z; -} - -// Define one vertex (color) -void rlColor4ub(unsigned char x, unsigned char y, unsigned char z, unsigned char w) -{ - RLGL.State.colorr = x; - RLGL.State.colorg = y; - RLGL.State.colorb = z; - RLGL.State.colora = w; -} - -// Define one vertex (color) -void rlColor4f(float r, float g, float b, float a) -{ - rlColor4ub((unsigned char)(r*255), (unsigned char)(g*255), (unsigned char)(b*255), (unsigned char)(a*255)); -} - -// Define one vertex (color) -void rlColor3f(float x, float y, float z) -{ - rlColor4ub((unsigned char)(x*255), (unsigned char)(y*255), (unsigned char)(z*255), 255); -} - -#endif - -//-------------------------------------------------------------------------------------- -// Module Functions Definition - OpenGL style functions (common to 1.1, 3.3+, ES2) -//-------------------------------------------------------------------------------------- - -// Set current texture to use -void rlSetTexture(unsigned int id) -{ - if (id == 0) - { -#if defined(GRAPHICS_API_OPENGL_11) - rlDisableTexture(); -#else - // NOTE: If quads batch limit is reached, we force a draw call and next batch starts - if (RLGL.State.vertexCounter >= - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4) - { - rlDrawRenderBatch(RLGL.currentBatch); - } -#endif - } - else - { -#if defined(GRAPHICS_API_OPENGL_11) - rlEnableTexture(id); -#else - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId != id) - { - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount > 0) - { - // Make sure current RLGL.currentBatch->draws[i].vertexCount is aligned a multiple of 4, - // that way, following QUADS drawing will keep aligned with index processing - // It implies adding some extra alignment vertex at the end of the draw, - // those vertex are not processed but they are considered as an additional offset - // for the next set of vertex to be drawn - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount : RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4); - else if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? 1 : (4 - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4))); - else RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = 0; - - if (!rlCheckRenderBatchLimit(RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment)) - { - RLGL.State.vertexCounter += RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment; - - RLGL.currentBatch->drawCounter++; - } - } - - if (RLGL.currentBatch->drawCounter >= RL_DEFAULT_BATCH_DRAWCALLS) rlDrawRenderBatch(RLGL.currentBatch); - - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = id; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount = 0; - } -#endif - } -} - -// Select and active a texture slot -void rlActiveTextureSlot(int slot) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glActiveTexture(GL_TEXTURE0 + slot); -#endif -} - -// Enable texture -void rlEnableTexture(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glEnable(GL_TEXTURE_2D); -#endif - glBindTexture(GL_TEXTURE_2D, id); -} - -// Disable texture -void rlDisableTexture(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glDisable(GL_TEXTURE_2D); -#endif - glBindTexture(GL_TEXTURE_2D, 0); -} - -// Enable texture cubemap -void rlEnableTextureCubemap(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_CUBE_MAP, id); -#endif -} - -// Disable texture cubemap -void rlDisableTextureCubemap(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif -} - -// Set texture parameters (wrap mode/filter mode) -void rlTextureParameters(unsigned int id, int param, int value) -{ - glBindTexture(GL_TEXTURE_2D, id); - -#if !defined(GRAPHICS_API_OPENGL_11) - // Reset anisotropy filter, in case it was set - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); -#endif - - switch (param) - { - case RL_TEXTURE_WRAP_S: - case RL_TEXTURE_WRAP_T: - { - if (value == RL_TEXTURE_WRAP_MIRROR_CLAMP) - { -#if !defined(GRAPHICS_API_OPENGL_11) - if (RLGL.ExtSupported.texMirrorClamp) glTexParameteri(GL_TEXTURE_2D, param, value); - else TRACELOG(RL_LOG_WARNING, "GL: Clamp mirror wrap mode not supported (GL_MIRROR_CLAMP_EXT)"); -#endif - } - else glTexParameteri(GL_TEXTURE_2D, param, value); - - } break; - case RL_TEXTURE_MAG_FILTER: - case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_2D, param, value); break; - case RL_TEXTURE_FILTER_ANISOTROPIC: - { -#if !defined(GRAPHICS_API_OPENGL_11) - if (value <= RLGL.ExtSupported.maxAnisotropyLevel) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - else if (RLGL.ExtSupported.maxAnisotropyLevel > 0.0f) - { - TRACELOG(RL_LOG_WARNING, "GL: Maximum anisotropic filter level supported is %iX", id, (int)RLGL.ExtSupported.maxAnisotropyLevel); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - } - else TRACELOG(RL_LOG_WARNING, "GL: Anisotropic filtering not supported"); -#endif - } break; -#if defined(GRAPHICS_API_OPENGL_33) - case RL_TEXTURE_MIPMAP_BIAS_RATIO: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, value/100.0f); -#endif - default: break; - } - - glBindTexture(GL_TEXTURE_2D, 0); -} - -// Set cubemap parameters (wrap mode/filter mode) -void rlCubemapParameters(unsigned int id, int param, int value) -{ -#if !defined(GRAPHICS_API_OPENGL_11) - glBindTexture(GL_TEXTURE_CUBE_MAP, id); - - // Reset anisotropy filter, in case it was set - glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); - - switch (param) - { - case RL_TEXTURE_WRAP_S: - case RL_TEXTURE_WRAP_T: - { - if (value == RL_TEXTURE_WRAP_MIRROR_CLAMP) - { - if (RLGL.ExtSupported.texMirrorClamp) glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); - else TRACELOG(RL_LOG_WARNING, "GL: Clamp mirror wrap mode not supported (GL_MIRROR_CLAMP_EXT)"); - } - else glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); - - } break; - case RL_TEXTURE_MAG_FILTER: - case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); break; - case RL_TEXTURE_FILTER_ANISOTROPIC: - { - if (value <= RLGL.ExtSupported.maxAnisotropyLevel) glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - else if (RLGL.ExtSupported.maxAnisotropyLevel > 0.0f) - { - TRACELOG(RL_LOG_WARNING, "GL: Maximum anisotropic filter level supported is %iX", id, (int)RLGL.ExtSupported.maxAnisotropyLevel); - glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - } - else TRACELOG(RL_LOG_WARNING, "GL: Anisotropic filtering not supported"); - } break; -#if defined(GRAPHICS_API_OPENGL_33) - case RL_TEXTURE_MIPMAP_BIAS_RATIO: glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_LOD_BIAS, value/100.0f); -#endif - default: break; - } - - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif -} - -// Enable shader program -void rlEnableShader(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - glUseProgram(id); -#endif -} - -// Disable shader program -void rlDisableShader(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - glUseProgram(0); -#endif -} - -// Enable rendering to texture (fbo) -void rlEnableFramebuffer(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, id); -#endif -} - -// Disable rendering to texture -void rlDisableFramebuffer(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, 0); -#endif -} - -// Blit active framebuffer to main framebuffer -void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBlitFramebuffer(srcX, srcY, srcWidth, srcHeight, dstX, dstY, dstWidth, dstHeight, bufferMask, GL_NEAREST); -#endif -} - -// Activate multiple draw color buffers -// NOTE: One color buffer is always active by default -void rlActiveDrawBuffers(int count) -{ -#if ((defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT)) - // NOTE: Maximum number of draw buffers supported is implementation dependant, - // it can be queried with glGet*() but it must be at least 8 - //GLint maxDrawBuffers = 0; - //glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); - - if (count > 0) - { - if (count > 8) TRACELOG(LOG_WARNING, "GL: Max color buffers limited to 8"); - else - { - unsigned int buffers[8] = { -#if defined(GRAPHICS_API_OPENGL_ES3) - GL_COLOR_ATTACHMENT0_EXT, - GL_COLOR_ATTACHMENT1_EXT, - GL_COLOR_ATTACHMENT2_EXT, - GL_COLOR_ATTACHMENT3_EXT, - GL_COLOR_ATTACHMENT4_EXT, - GL_COLOR_ATTACHMENT5_EXT, - GL_COLOR_ATTACHMENT6_EXT, - GL_COLOR_ATTACHMENT7_EXT, -#else - GL_COLOR_ATTACHMENT0, - GL_COLOR_ATTACHMENT1, - GL_COLOR_ATTACHMENT2, - GL_COLOR_ATTACHMENT3, - GL_COLOR_ATTACHMENT4, - GL_COLOR_ATTACHMENT5, - GL_COLOR_ATTACHMENT6, - GL_COLOR_ATTACHMENT7, -#endif - }; - -#if defined(GRAPHICS_API_OPENGL_ES3) - glDrawBuffersEXT(count, buffers); -#else - glDrawBuffers(count, buffers); -#endif - } - } - else TRACELOG(LOG_WARNING, "GL: One color buffer active by default"); -#endif -} - -//---------------------------------------------------------------------------------- -// General render state configuration -//---------------------------------------------------------------------------------- - -// Enable color blending -void rlEnableColorBlend(void) { glEnable(GL_BLEND); } - -// Disable color blending -void rlDisableColorBlend(void) { glDisable(GL_BLEND); } - -// Enable depth test -void rlEnableDepthTest(void) { glEnable(GL_DEPTH_TEST); } - -// Disable depth test -void rlDisableDepthTest(void) { glDisable(GL_DEPTH_TEST); } - -// Enable depth write -void rlEnableDepthMask(void) { glDepthMask(GL_TRUE); } - -// Disable depth write -void rlDisableDepthMask(void) { glDepthMask(GL_FALSE); } - -// Enable backface culling -void rlEnableBackfaceCulling(void) { glEnable(GL_CULL_FACE); } - -// Disable backface culling -void rlDisableBackfaceCulling(void) { glDisable(GL_CULL_FACE); } - -// Set face culling mode -void rlSetCullFace(int mode) -{ - switch (mode) - { - case RL_CULL_FACE_BACK: glCullFace(GL_BACK); break; - case RL_CULL_FACE_FRONT: glCullFace(GL_FRONT); break; - default: break; - } -} - -// Enable scissor test -void rlEnableScissorTest(void) { glEnable(GL_SCISSOR_TEST); } - -// Disable scissor test -void rlDisableScissorTest(void) { glDisable(GL_SCISSOR_TEST); } - -// Scissor test -void rlScissor(int x, int y, int width, int height) { glScissor(x, y, width, height); } - -// Enable wire mode -void rlEnableWireMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); -#endif -} - -void rlEnablePointMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); - glEnable(GL_PROGRAM_POINT_SIZE); -#endif -} -// Disable wire mode -void rlDisableWireMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); -#endif -} - -// Set the line drawing width -void rlSetLineWidth(float width) { glLineWidth(width); } - -// Get the line drawing width -float rlGetLineWidth(void) -{ - float width = 0; - glGetFloatv(GL_LINE_WIDTH, &width); - return width; -} - -// Enable line aliasing -void rlEnableSmoothLines(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_11) - glEnable(GL_LINE_SMOOTH); -#endif -} - -// Disable line aliasing -void rlDisableSmoothLines(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_11) - glDisable(GL_LINE_SMOOTH); -#endif -} - -// Enable stereo rendering -void rlEnableStereoRender(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - RLGL.State.stereoRender = true; -#endif -} - -// Disable stereo rendering -void rlDisableStereoRender(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - RLGL.State.stereoRender = false; -#endif -} - -// Check if stereo render is enabled -bool rlIsStereoRenderEnabled(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - return RLGL.State.stereoRender; -#else - return false; -#endif -} - -// Clear color buffer with color -void rlClearColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - // Color values clamp to 0.0f(0) and 1.0f(255) - float cr = (float)r/255; - float cg = (float)g/255; - float cb = (float)b/255; - float ca = (float)a/255; - - glClearColor(cr, cg, cb, ca); -} - -// Clear used screen buffers (color and depth) -void rlClearScreenBuffers(void) -{ - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear used buffers: Color and Depth (Depth is used for 3D) - //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Stencil buffer not used... -} - -// Check and log OpenGL error codes -void rlCheckErrors() -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - int check = 1; - while (check) - { - const GLenum err = glGetError(); - switch (err) - { - case GL_NO_ERROR: check = 0; break; - case 0x0500: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_ENUM"); break; - case 0x0501: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_VALUE"); break; - case 0x0502: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_OPERATION"); break; - case 0x0503: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_STACK_OVERFLOW"); break; - case 0x0504: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_STACK_UNDERFLOW"); break; - case 0x0505: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_OUT_OF_MEMORY"); break; - case 0x0506: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_FRAMEBUFFER_OPERATION"); break; - default: TRACELOG(RL_LOG_WARNING, "GL: Error detected: Unknown error code: %x", err); break; - } - } -#endif -} - -// Set blend mode -void rlSetBlendMode(int mode) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.currentBlendMode != mode) || ((mode == RL_BLEND_CUSTOM || mode == RL_BLEND_CUSTOM_SEPARATE) && RLGL.State.glCustomBlendModeModified)) - { - rlDrawRenderBatch(RLGL.currentBatch); - - switch (mode) - { - case RL_BLEND_ALPHA: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_MULTIPLIED: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_ADD_COLORS: glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_SUBTRACT_COLORS: glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_SUBTRACT); break; - case RL_BLEND_ALPHA_PREMULTIPLY: glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_CUSTOM: - { - // NOTE: Using GL blend src/dst factors and GL equation configured with rlSetBlendFactors() - glBlendFunc(RLGL.State.glBlendSrcFactor, RLGL.State.glBlendDstFactor); glBlendEquation(RLGL.State.glBlendEquation); - - } break; - case RL_BLEND_CUSTOM_SEPARATE: - { - // NOTE: Using GL blend src/dst factors and GL equation configured with rlSetBlendFactorsSeparate() - glBlendFuncSeparate(RLGL.State.glBlendSrcFactorRGB, RLGL.State.glBlendDestFactorRGB, RLGL.State.glBlendSrcFactorAlpha, RLGL.State.glBlendDestFactorAlpha); - glBlendEquationSeparate(RLGL.State.glBlendEquationRGB, RLGL.State.glBlendEquationAlpha); - - } break; - default: break; - } - - RLGL.State.currentBlendMode = mode; - RLGL.State.glCustomBlendModeModified = false; - } -#endif -} - -// Set blending mode factor and equation -void rlSetBlendFactors(int glSrcFactor, int glDstFactor, int glEquation) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.glBlendSrcFactor != glSrcFactor) || - (RLGL.State.glBlendDstFactor != glDstFactor) || - (RLGL.State.glBlendEquation != glEquation)) - { - RLGL.State.glBlendSrcFactor = glSrcFactor; - RLGL.State.glBlendDstFactor = glDstFactor; - RLGL.State.glBlendEquation = glEquation; - - RLGL.State.glCustomBlendModeModified = true; - } -#endif -} - -// Set blending mode factor and equation separately for RGB and alpha -void rlSetBlendFactorsSeparate(int glSrcRGB, int glDstRGB, int glSrcAlpha, int glDstAlpha, int glEqRGB, int glEqAlpha) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.glBlendSrcFactorRGB != glSrcRGB) || - (RLGL.State.glBlendDestFactorRGB != glDstRGB) || - (RLGL.State.glBlendSrcFactorAlpha != glSrcAlpha) || - (RLGL.State.glBlendDestFactorAlpha != glDstAlpha) || - (RLGL.State.glBlendEquationRGB != glEqRGB) || - (RLGL.State.glBlendEquationAlpha != glEqAlpha)) - { - RLGL.State.glBlendSrcFactorRGB = glSrcRGB; - RLGL.State.glBlendDestFactorRGB = glDstRGB; - RLGL.State.glBlendSrcFactorAlpha = glSrcAlpha; - RLGL.State.glBlendDestFactorAlpha = glDstAlpha; - RLGL.State.glBlendEquationRGB = glEqRGB; - RLGL.State.glBlendEquationAlpha = glEqAlpha; - - RLGL.State.glCustomBlendModeModified = true; - } -#endif -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - OpenGL Debug -//---------------------------------------------------------------------------------- -#if defined(RLGL_ENABLE_OPENGL_DEBUG_CONTEXT) && defined(GRAPHICS_API_OPENGL_43) -static void GLAPIENTRY rlDebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) -{ - // Ignore non-significant error/warning codes (NVidia drivers) - // NOTE: Here there are the details with a sample output: - // - #131169 - Framebuffer detailed info: The driver allocated storage for renderbuffer 2. (severity: low) - // - #131185 - Buffer detailed info: Buffer object 1 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_ENUM_88e4) - // will use VIDEO memory as the source for buffer object operations. (severity: low) - // - #131218 - Program/shader state performance warning: Vertex shader in program 7 is being recompiled based on GL state. (severity: medium) - // - #131204 - Texture state usage warning: The texture object (0) bound to texture image unit 0 does not have - // a defined base level and cannot be used for texture mapping. (severity: low) - if ((id == 131169) || (id == 131185) || (id == 131218) || (id == 131204)) return; - - const char *msgSource = NULL; - switch (source) - { - case GL_DEBUG_SOURCE_API: msgSource = "API"; break; - case GL_DEBUG_SOURCE_WINDOW_SYSTEM: msgSource = "WINDOW_SYSTEM"; break; - case GL_DEBUG_SOURCE_SHADER_COMPILER: msgSource = "SHADER_COMPILER"; break; - case GL_DEBUG_SOURCE_THIRD_PARTY: msgSource = "THIRD_PARTY"; break; - case GL_DEBUG_SOURCE_APPLICATION: msgSource = "APPLICATION"; break; - case GL_DEBUG_SOURCE_OTHER: msgSource = "OTHER"; break; - default: break; - } - - const char *msgType = NULL; - switch (type) - { - case GL_DEBUG_TYPE_ERROR: msgType = "ERROR"; break; - case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: msgType = "DEPRECATED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: msgType = "UNDEFINED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_PORTABILITY: msgType = "PORTABILITY"; break; - case GL_DEBUG_TYPE_PERFORMANCE: msgType = "PERFORMANCE"; break; - case GL_DEBUG_TYPE_MARKER: msgType = "MARKER"; break; - case GL_DEBUG_TYPE_PUSH_GROUP: msgType = "PUSH_GROUP"; break; - case GL_DEBUG_TYPE_POP_GROUP: msgType = "POP_GROUP"; break; - case GL_DEBUG_TYPE_OTHER: msgType = "OTHER"; break; - default: break; - } - - const char *msgSeverity = "DEFAULT"; - switch (severity) - { - case GL_DEBUG_SEVERITY_LOW: msgSeverity = "LOW"; break; - case GL_DEBUG_SEVERITY_MEDIUM: msgSeverity = "MEDIUM"; break; - case GL_DEBUG_SEVERITY_HIGH: msgSeverity = "HIGH"; break; - case GL_DEBUG_SEVERITY_NOTIFICATION: msgSeverity = "NOTIFICATION"; break; - default: break; - } - - TRACELOG(LOG_WARNING, "GL: OpenGL debug message: %s", message); - TRACELOG(LOG_WARNING, " > Type: %s", msgType); - TRACELOG(LOG_WARNING, " > Source = %s", msgSource); - TRACELOG(LOG_WARNING, " > Severity = %s", msgSeverity); -} -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition - rlgl functionality -//---------------------------------------------------------------------------------- - -// Initialize rlgl: OpenGL extensions, default buffers/shaders/textures, OpenGL states -void rlglInit(int width, int height) -{ - // Enable OpenGL debug context if required -#if defined(RLGL_ENABLE_OPENGL_DEBUG_CONTEXT) && defined(GRAPHICS_API_OPENGL_43) - if ((glDebugMessageCallback != NULL) && (glDebugMessageControl != NULL)) - { - glDebugMessageCallback(rlDebugMessageCallback, 0); - // glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_ERROR, GL_DEBUG_SEVERITY_HIGH, 0, 0, GL_TRUE); - - // Debug context options: - // - GL_DEBUG_OUTPUT - Faster version but not useful for breakpoints - // - GL_DEBUG_OUTPUT_SYNCHRONUS - Callback is in sync with errors, so a breakpoint can be placed on the callback in order to get a stacktrace for the GL error - glEnable(GL_DEBUG_OUTPUT); - glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); - } -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Init default white texture - unsigned char pixels[4] = { 255, 255, 255, 255 }; // 1 pixel RGBA (4 bytes) - RLGL.State.defaultTextureId = rlLoadTexture(pixels, 1, 1, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1); - - if (RLGL.State.defaultTextureId != 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Default texture loaded successfully", RLGL.State.defaultTextureId); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load default texture"); - - // Init default Shader (customized for GL 3.3 and ES2) - // Loaded: RLGL.State.defaultShaderId + RLGL.State.defaultShaderLocs - rlLoadShaderDefault(); - RLGL.State.currentShaderId = RLGL.State.defaultShaderId; - RLGL.State.currentShaderLocs = RLGL.State.defaultShaderLocs; - - // Init default vertex arrays buffers - RLGL.defaultBatch = rlLoadRenderBatch(RL_DEFAULT_BATCH_BUFFERS, RL_DEFAULT_BATCH_BUFFER_ELEMENTS); - RLGL.currentBatch = &RLGL.defaultBatch; - - // Init stack matrices (emulating OpenGL 1.1) - for (int i = 0; i < RL_MAX_MATRIX_STACK_SIZE; i++) RLGL.State.stack[i] = rlMatrixIdentity(); - - // Init internal matrices - RLGL.State.transform = rlMatrixIdentity(); - RLGL.State.projection = rlMatrixIdentity(); - RLGL.State.modelview = rlMatrixIdentity(); - RLGL.State.currentMatrix = &RLGL.State.modelview; -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - - // Initialize OpenGL default states - //---------------------------------------------------------- - // Init state: Depth test - glDepthFunc(GL_LEQUAL); // Type of depth testing to apply - glDisable(GL_DEPTH_TEST); // Disable depth testing for 2D (only used for 3D) - - // Init state: Blending mode - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Color blending function (how colors are mixed) - glEnable(GL_BLEND); // Enable color blending (required to work with transparencies) - - // Init state: Culling - // NOTE: All shapes/models triangles are drawn CCW - glCullFace(GL_BACK); // Cull the back face (default) - glFrontFace(GL_CCW); // Front face are defined counter clockwise (default) - glEnable(GL_CULL_FACE); // Enable backface culling - - // Init state: Cubemap seamless -#if defined(GRAPHICS_API_OPENGL_33) - glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); // Seamless cubemaps (not supported on OpenGL ES 2.0) -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - // Init state: Color hints (deprecated in OpenGL 3.0+) - glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Improve quality of color and texture coordinate interpolation - glShadeModel(GL_SMOOTH); // Smooth shading between vertex (vertex colors interpolation) -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Store screen size into global variables - RLGL.State.framebufferWidth = width; - RLGL.State.framebufferHeight = height; - - TRACELOG(RL_LOG_INFO, "RLGL: Default OpenGL state initialized successfully"); - //---------------------------------------------------------- -#endif - - // Init state: Color/Depth buffers clear - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set clear color (black) - glClearDepth(1.0f); // Set clear depth value (default) - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers (depth buffer required for 3D) -} - -// Vertex Buffer Object deinitialization (memory free) -void rlglClose(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlUnloadRenderBatch(RLGL.defaultBatch); - - rlUnloadShaderDefault(); // Unload default shader - - glDeleteTextures(1, &RLGL.State.defaultTextureId); // Unload default texture - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Default texture unloaded successfully", RLGL.State.defaultTextureId); -#endif -} - -// Load OpenGL extensions -// NOTE: External loader function must be provided -void rlLoadExtensions(void *loader) -{ -#if defined(GRAPHICS_API_OPENGL_33) // Also defined for GRAPHICS_API_OPENGL_21 - // NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions (and lower versions) - if (gladLoadGL((GLADloadfunc)loader) == 0) TRACELOG(RL_LOG_WARNING, "GLAD: Cannot load OpenGL extensions"); - else TRACELOG(RL_LOG_INFO, "GLAD: OpenGL extensions loaded successfully"); - - // Get number of supported extensions - GLint numExt = 0; - glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); - TRACELOG(RL_LOG_INFO, "GL: Supported extensions count: %i", numExt); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - // Get supported extensions list - // WARNING: glGetStringi() not available on OpenGL 2.1 - TRACELOG(RL_LOG_INFO, "GL: OpenGL extensions:"); - for (int i = 0; i < numExt; i++) TRACELOG(RL_LOG_INFO, " %s", glGetStringi(GL_EXTENSIONS, i)); -#endif - -#if defined(GRAPHICS_API_OPENGL_21) - // Register supported extensions flags - // Optional OpenGL 2.1 extensions - RLGL.ExtSupported.vao = GLAD_GL_ARB_vertex_array_object; - RLGL.ExtSupported.instancing = (GLAD_GL_EXT_draw_instanced && GLAD_GL_ARB_instanced_arrays); - RLGL.ExtSupported.texNPOT = GLAD_GL_ARB_texture_non_power_of_two; - RLGL.ExtSupported.texFloat32 = GLAD_GL_ARB_texture_float; - RLGL.ExtSupported.texFloat16 = GLAD_GL_ARB_texture_float; - RLGL.ExtSupported.texDepth = GLAD_GL_ARB_depth_texture; - RLGL.ExtSupported.maxDepthBits = 32; - RLGL.ExtSupported.texAnisoFilter = GLAD_GL_EXT_texture_filter_anisotropic; - RLGL.ExtSupported.texMirrorClamp = GLAD_GL_EXT_texture_mirror_clamp; -#else - // Register supported extensions flags - // OpenGL 3.3 extensions supported by default (core) - RLGL.ExtSupported.vao = true; - RLGL.ExtSupported.instancing = true; - RLGL.ExtSupported.texNPOT = true; - RLGL.ExtSupported.texFloat32 = true; - RLGL.ExtSupported.texFloat16 = true; - RLGL.ExtSupported.texDepth = true; - RLGL.ExtSupported.maxDepthBits = 32; - RLGL.ExtSupported.texAnisoFilter = true; - RLGL.ExtSupported.texMirrorClamp = true; -#endif - - // Optional OpenGL 3.3 extensions - RLGL.ExtSupported.texCompASTC = GLAD_GL_KHR_texture_compression_astc_hdr && GLAD_GL_KHR_texture_compression_astc_ldr; - RLGL.ExtSupported.texCompDXT = GLAD_GL_EXT_texture_compression_s3tc; // Texture compression: DXT - RLGL.ExtSupported.texCompETC2 = GLAD_GL_ARB_ES3_compatibility; // Texture compression: ETC2/EAC - #if defined(GRAPHICS_API_OPENGL_43) - RLGL.ExtSupported.computeShader = GLAD_GL_ARB_compute_shader; - RLGL.ExtSupported.ssbo = GLAD_GL_ARB_shader_storage_buffer_object; - #endif - -#endif // GRAPHICS_API_OPENGL_33 - -#if defined(GRAPHICS_API_OPENGL_ES3) - // Register supported extensions flags - // OpenGL ES 3.0 extensions supported by default (or it should be) - RLGL.ExtSupported.vao = true; - RLGL.ExtSupported.instancing = true; - RLGL.ExtSupported.texNPOT = true; - RLGL.ExtSupported.texFloat32 = true; - RLGL.ExtSupported.texFloat16 = true; - RLGL.ExtSupported.texDepth = true; - RLGL.ExtSupported.texDepthWebGL = true; - RLGL.ExtSupported.maxDepthBits = 24; - RLGL.ExtSupported.texAnisoFilter = true; - RLGL.ExtSupported.texMirrorClamp = true; - // TODO: Check for additional OpenGL ES 3.0 supported extensions: - //RLGL.ExtSupported.texCompDXT = true; - //RLGL.ExtSupported.texCompETC1 = true; - //RLGL.ExtSupported.texCompETC2 = true; - //RLGL.ExtSupported.texCompPVRT = true; - //RLGL.ExtSupported.texCompASTC = true; - //RLGL.ExtSupported.maxAnisotropyLevel = true; - //RLGL.ExtSupported.computeShader = true; - //RLGL.ExtSupported.ssbo = true; - -#elif defined(GRAPHICS_API_OPENGL_ES2) - - #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_DESKTOP_SDL) - // TODO: Support GLAD loader for OpenGL ES 3.0 - if (gladLoadGLES2((GLADloadfunc)loader) == 0) TRACELOG(RL_LOG_WARNING, "GLAD: Cannot load OpenGL ES2.0 functions"); - else TRACELOG(RL_LOG_INFO, "GLAD: OpenGL ES 2.0 loaded successfully"); - #endif - - // Get supported extensions list - GLint numExt = 0; - const char **extList = RL_MALLOC(512*sizeof(const char *)); // Allocate 512 strings pointers (2 KB) - const char *extensions = (const char *)glGetString(GL_EXTENSIONS); // One big const string - - // NOTE: We have to duplicate string because glGetString() returns a const string - int size = strlen(extensions) + 1; // Get extensions string size in bytes - char *extensionsDup = (char *)RL_CALLOC(size, sizeof(char)); - strcpy(extensionsDup, extensions); - extList[numExt] = extensionsDup; - - for (int i = 0; i < size; i++) - { - if (extensionsDup[i] == ' ') - { - extensionsDup[i] = '\0'; - numExt++; - extList[numExt] = &extensionsDup[i + 1]; - } - } - - TRACELOG(RL_LOG_INFO, "GL: Supported extensions count: %i", numExt); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - TRACELOG(RL_LOG_INFO, "GL: OpenGL extensions:"); - for (int i = 0; i < numExt; i++) TRACELOG(RL_LOG_INFO, " %s", extList[i]); -#endif - - // Check required extensions - for (int i = 0; i < numExt; i++) - { - // Check VAO support - // NOTE: Only check on OpenGL ES, OpenGL 3.3 has VAO support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_vertex_array_object") == 0) - { - // The extension is supported by our hardware and driver, try to get related functions pointers - // NOTE: emscripten does not support VAOs natively, it uses emulation and it reduces overall performance... - glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)((rlglLoadProc)loader)("glGenVertexArraysOES"); - glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)((rlglLoadProc)loader)("glBindVertexArrayOES"); - glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)((rlglLoadProc)loader)("glDeleteVertexArraysOES"); - //glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)loader("glIsVertexArrayOES"); // NOTE: Fails in WebGL, omitted - - if ((glGenVertexArrays != NULL) && (glBindVertexArray != NULL) && (glDeleteVertexArrays != NULL)) RLGL.ExtSupported.vao = true; - } - - // Check instanced rendering support - if (strcmp(extList[i], (const char *)"GL_ANGLE_instanced_arrays") == 0) // Web ANGLE - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedANGLE"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedANGLE"); - glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorANGLE"); - - if ((glDrawArraysInstanced != NULL) && (glDrawElementsInstanced != NULL) && (glVertexAttribDivisor != NULL)) RLGL.ExtSupported.instancing = true; - } - else - { - if ((strcmp(extList[i], (const char *)"GL_EXT_draw_instanced") == 0) && // Standard EXT - (strcmp(extList[i], (const char *)"GL_EXT_instanced_arrays") == 0)) - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedEXT"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedEXT"); - glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorEXT"); - - if ((glDrawArraysInstanced != NULL) && (glDrawElementsInstanced != NULL) && (glVertexAttribDivisor != NULL)) RLGL.ExtSupported.instancing = true; - } - } - - // Check NPOT textures support - // NOTE: Only check on OpenGL ES, OpenGL 3.3 has NPOT textures full support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_texture_npot") == 0) RLGL.ExtSupported.texNPOT = true; - - // Check texture float support - if (strcmp(extList[i], (const char *)"GL_OES_texture_float") == 0) RLGL.ExtSupported.texFloat32 = true; - if (strcmp(extList[i], (const char *)"GL_OES_texture_half_float") == 0) RLGL.ExtSupported.texFloat16 = true; - - // Check depth texture support - if (strcmp(extList[i], (const char *)"GL_OES_depth_texture") == 0) RLGL.ExtSupported.texDepth = true; - if (strcmp(extList[i], (const char *)"GL_WEBGL_depth_texture") == 0) RLGL.ExtSupported.texDepthWebGL = true; // WebGL requires unsized internal format - if (RLGL.ExtSupported.texDepthWebGL) RLGL.ExtSupported.texDepth = true; - - if (strcmp(extList[i], (const char *)"GL_OES_depth24") == 0) RLGL.ExtSupported.maxDepthBits = 24; // Not available on WebGL - if (strcmp(extList[i], (const char *)"GL_OES_depth32") == 0) RLGL.ExtSupported.maxDepthBits = 32; // Not available on WebGL - - // Check texture compression support: DXT - if ((strcmp(extList[i], (const char *)"GL_EXT_texture_compression_s3tc") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_s3tc") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBKIT_WEBGL_compressed_texture_s3tc") == 0)) RLGL.ExtSupported.texCompDXT = true; - - // Check texture compression support: ETC1 - if ((strcmp(extList[i], (const char *)"GL_OES_compressed_ETC1_RGB8_texture") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_etc1") == 0)) RLGL.ExtSupported.texCompETC1 = true; - - // Check texture compression support: ETC2/EAC - if (strcmp(extList[i], (const char *)"GL_ARB_ES3_compatibility") == 0) RLGL.ExtSupported.texCompETC2 = true; - - // Check texture compression support: PVR - if (strcmp(extList[i], (const char *)"GL_IMG_texture_compression_pvrtc") == 0) RLGL.ExtSupported.texCompPVRT = true; - - // Check texture compression support: ASTC - if (strcmp(extList[i], (const char *)"GL_KHR_texture_compression_astc_hdr") == 0) RLGL.ExtSupported.texCompASTC = true; - - // Check anisotropic texture filter support - if (strcmp(extList[i], (const char *)"GL_EXT_texture_filter_anisotropic") == 0) RLGL.ExtSupported.texAnisoFilter = true; - - // Check clamp mirror wrap mode support - if (strcmp(extList[i], (const char *)"GL_EXT_texture_mirror_clamp") == 0) RLGL.ExtSupported.texMirrorClamp = true; - } - - // Free extensions pointers - RL_FREE(extList); - RL_FREE(extensionsDup); // Duplicated string must be deallocated -#endif // GRAPHICS_API_OPENGL_ES2 - - // Check OpenGL information and capabilities - //------------------------------------------------------------------------------ - // Show current OpenGL and GLSL version - TRACELOG(RL_LOG_INFO, "GL: OpenGL device information:"); - TRACELOG(RL_LOG_INFO, " > Vendor: %s", glGetString(GL_VENDOR)); - TRACELOG(RL_LOG_INFO, " > Renderer: %s", glGetString(GL_RENDERER)); - TRACELOG(RL_LOG_INFO, " > Version: %s", glGetString(GL_VERSION)); - TRACELOG(RL_LOG_INFO, " > GLSL: %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Anisotropy levels capability is an extension - #ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF - #endif - glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &RLGL.ExtSupported.maxAnisotropyLevel); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - // Show some OpenGL GPU capabilities - TRACELOG(RL_LOG_INFO, "GL: OpenGL capabilities:"); - GLint capability = 0; - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_SIZE: %i", capability); - glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_CUBE_MAP_TEXTURE_SIZE: %i", capability); - glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_IMAGE_UNITS: %i", capability); - glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_VERTEX_ATTRIBS: %i", capability); - #if !defined(GRAPHICS_API_OPENGL_ES2) - glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_UNIFORM_BLOCK_SIZE: %i", capability); - glGetIntegerv(GL_MAX_DRAW_BUFFERS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_DRAW_BUFFERS: %i", capability); - if (RLGL.ExtSupported.texAnisoFilter) TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_MAX_ANISOTROPY: %.0f", RLGL.ExtSupported.maxAnisotropyLevel); - #endif - glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &capability); - TRACELOG(RL_LOG_INFO, " GL_NUM_COMPRESSED_TEXTURE_FORMATS: %i", capability); - GLint *compFormats = (GLint *)RL_CALLOC(capability, sizeof(GLint)); - glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compFormats); - for (int i = 0; i < capability; i++) TRACELOG(RL_LOG_INFO, " %s", rlGetCompressedFormatName(compFormats[i])); - RL_FREE(compFormats); - -#if defined(GRAPHICS_API_OPENGL_43) - glGetIntegerv(GL_MAX_VERTEX_ATTRIB_BINDINGS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_VERTEX_ATTRIB_BINDINGS: %i", capability); - glGetIntegerv(GL_MAX_UNIFORM_LOCATIONS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_UNIFORM_LOCATIONS: %i", capability); -#endif // GRAPHICS_API_OPENGL_43 -#else // RLGL_SHOW_GL_DETAILS_INFO - - // Show some basic info about GL supported features - if (RLGL.ExtSupported.vao) TRACELOG(RL_LOG_INFO, "GL: VAO extension detected, VAO functions loaded successfully"); - else TRACELOG(RL_LOG_WARNING, "GL: VAO extension not found, VAO not supported"); - if (RLGL.ExtSupported.texNPOT) TRACELOG(RL_LOG_INFO, "GL: NPOT textures extension detected, full NPOT textures supported"); - else TRACELOG(RL_LOG_WARNING, "GL: NPOT textures extension not found, limited NPOT support (no-mipmaps, no-repeat)"); - if (RLGL.ExtSupported.texCompDXT) TRACELOG(RL_LOG_INFO, "GL: DXT compressed textures supported"); - if (RLGL.ExtSupported.texCompETC1) TRACELOG(RL_LOG_INFO, "GL: ETC1 compressed textures supported"); - if (RLGL.ExtSupported.texCompETC2) TRACELOG(RL_LOG_INFO, "GL: ETC2/EAC compressed textures supported"); - if (RLGL.ExtSupported.texCompPVRT) TRACELOG(RL_LOG_INFO, "GL: PVRT compressed textures supported"); - if (RLGL.ExtSupported.texCompASTC) TRACELOG(RL_LOG_INFO, "GL: ASTC compressed textures supported"); - if (RLGL.ExtSupported.computeShader) TRACELOG(RL_LOG_INFO, "GL: Compute shaders supported"); - if (RLGL.ExtSupported.ssbo) TRACELOG(RL_LOG_INFO, "GL: Shader storage buffer objects supported"); -#endif // RLGL_SHOW_GL_DETAILS_INFO - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 -} - -// Get current OpenGL version -int rlGetVersion(void) -{ - int glVersion = 0; -#if defined(GRAPHICS_API_OPENGL_11) - glVersion = RL_OPENGL_11; -#endif -#if defined(GRAPHICS_API_OPENGL_21) - glVersion = RL_OPENGL_21; -#elif defined(GRAPHICS_API_OPENGL_43) - glVersion = RL_OPENGL_43; -#elif defined(GRAPHICS_API_OPENGL_33) - glVersion = RL_OPENGL_33; -#endif -#if defined(GRAPHICS_API_OPENGL_ES3) - glVersion = RL_OPENGL_ES_30; -#elif defined(GRAPHICS_API_OPENGL_ES2) - glVersion = RL_OPENGL_ES_20; -#endif - - return glVersion; -} - -// Set current framebuffer width -void rlSetFramebufferWidth(int width) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.framebufferWidth = width; -#endif -} - -// Set current framebuffer height -void rlSetFramebufferHeight(int height) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.framebufferHeight = height; -#endif -} - -// Get default framebuffer width -int rlGetFramebufferWidth(void) -{ - int width = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - width = RLGL.State.framebufferWidth; -#endif - return width; -} - -// Get default framebuffer height -int rlGetFramebufferHeight(void) -{ - int height = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - height = RLGL.State.framebufferHeight; -#endif - return height; -} - -// Get default internal texture (white texture) -// NOTE: Default texture is a 1x1 pixel UNCOMPRESSED_R8G8B8A8 -unsigned int rlGetTextureIdDefault(void) -{ - unsigned int id = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - id = RLGL.State.defaultTextureId; -#endif - return id; -} - -// Get default shader id -unsigned int rlGetShaderIdDefault(void) -{ - unsigned int id = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - id = RLGL.State.defaultShaderId; -#endif - return id; -} - -// Get default shader locs -int *rlGetShaderLocsDefault(void) -{ - int *locs = NULL; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - locs = RLGL.State.defaultShaderLocs; -#endif - return locs; -} - -// Render batch management -//------------------------------------------------------------------------------------------------ -// Load render batch -rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements) -{ - rlRenderBatch batch = { 0 }; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Initialize CPU (RAM) vertex buffers (position, texcoord, color data and indexes) - //-------------------------------------------------------------------------------------------- - batch.vertexBuffer = (rlVertexBuffer *)RL_MALLOC(numBuffers*sizeof(rlVertexBuffer)); - - for (int i = 0; i < numBuffers; i++) - { - batch.vertexBuffer[i].elementCount = bufferElements; - - batch.vertexBuffer[i].vertices = (float *)RL_MALLOC(bufferElements*3*4*sizeof(float)); // 3 float by vertex, 4 vertex by quad - batch.vertexBuffer[i].texcoords = (float *)RL_MALLOC(bufferElements*2*4*sizeof(float)); // 2 float by texcoord, 4 texcoord by quad - batch.vertexBuffer[i].colors = (unsigned char *)RL_MALLOC(bufferElements*4*4*sizeof(unsigned char)); // 4 float by color, 4 colors by quad -#if defined(GRAPHICS_API_OPENGL_33) - batch.vertexBuffer[i].indices = (unsigned int *)RL_MALLOC(bufferElements*6*sizeof(unsigned int)); // 6 int by quad (indices) -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - batch.vertexBuffer[i].indices = (unsigned short *)RL_MALLOC(bufferElements*6*sizeof(unsigned short)); // 6 int by quad (indices) -#endif - - for (int j = 0; j < (3*4*bufferElements); j++) batch.vertexBuffer[i].vertices[j] = 0.0f; - for (int j = 0; j < (2*4*bufferElements); j++) batch.vertexBuffer[i].texcoords[j] = 0.0f; - for (int j = 0; j < (4*4*bufferElements); j++) batch.vertexBuffer[i].colors[j] = 0; - - int k = 0; - - // Indices can be initialized right now - for (int j = 0; j < (6*bufferElements); j += 6) - { - batch.vertexBuffer[i].indices[j] = 4*k; - batch.vertexBuffer[i].indices[j + 1] = 4*k + 1; - batch.vertexBuffer[i].indices[j + 2] = 4*k + 2; - batch.vertexBuffer[i].indices[j + 3] = 4*k; - batch.vertexBuffer[i].indices[j + 4] = 4*k + 2; - batch.vertexBuffer[i].indices[j + 5] = 4*k + 3; - - k++; - } - - RLGL.State.vertexCounter = 0; - } - - TRACELOG(RL_LOG_INFO, "RLGL: Render batch vertex buffers loaded successfully in RAM (CPU)"); - //-------------------------------------------------------------------------------------------- - - // Upload to GPU (VRAM) vertex data and initialize VAOs/VBOs - //-------------------------------------------------------------------------------------------- - for (int i = 0; i < numBuffers; i++) - { - if (RLGL.ExtSupported.vao) - { - // Initialize Quads VAO - glGenVertexArrays(1, &batch.vertexBuffer[i].vaoId); - glBindVertexArray(batch.vertexBuffer[i].vaoId); - } - - // Quads - Vertex buffers binding and attributes enable - // Vertex position buffer (shader-location = 0) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[0]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[0]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*3*4*sizeof(float), batch.vertexBuffer[i].vertices, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - - // Vertex texcoord buffer (shader-location = 1) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[1]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[1]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*2*4*sizeof(float), batch.vertexBuffer[i].texcoords, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - - // Vertex color buffer (shader-location = 3) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[2]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[2]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*4*4*sizeof(unsigned char), batch.vertexBuffer[i].colors, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - - // Fill index buffer - glGenBuffers(1, &batch.vertexBuffer[i].vboId[3]); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[3]); -#if defined(GRAPHICS_API_OPENGL_33) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(int), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(short), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); -#endif - } - - TRACELOG(RL_LOG_INFO, "RLGL: Render batch vertex buffers loaded successfully in VRAM (GPU)"); - - // Unbind the current VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(0); - //-------------------------------------------------------------------------------------------- - - // Init draw calls tracking system - //-------------------------------------------------------------------------------------------- - batch.draws = (rlDrawCall *)RL_MALLOC(RL_DEFAULT_BATCH_DRAWCALLS*sizeof(rlDrawCall)); - - for (int i = 0; i < RL_DEFAULT_BATCH_DRAWCALLS; i++) - { - batch.draws[i].mode = RL_QUADS; - batch.draws[i].vertexCount = 0; - batch.draws[i].vertexAlignment = 0; - //batch.draws[i].vaoId = 0; - //batch.draws[i].shaderId = 0; - batch.draws[i].textureId = RLGL.State.defaultTextureId; - //batch.draws[i].RLGL.State.projection = rlMatrixIdentity(); - //batch.draws[i].RLGL.State.modelview = rlMatrixIdentity(); - } - - batch.bufferCount = numBuffers; // Record buffer count - batch.drawCounter = 1; // Reset draws counter - batch.currentDepth = -1.0f; // Reset depth value - //-------------------------------------------------------------------------------------------- -#endif - - return batch; -} - -// Unload default internal buffers vertex data from CPU and GPU -void rlUnloadRenderBatch(rlRenderBatch batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Unbind everything - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - // Unload all vertex buffers data - for (int i = 0; i < batch.bufferCount; i++) - { - // Unbind VAO attribs data - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(batch.vertexBuffer[i].vaoId); - glDisableVertexAttribArray(0); - glDisableVertexAttribArray(1); - glDisableVertexAttribArray(2); - glDisableVertexAttribArray(3); - glBindVertexArray(0); - } - - // Delete VBOs from GPU (VRAM) - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[0]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[1]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[2]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[3]); - - // Delete VAOs from GPU (VRAM) - if (RLGL.ExtSupported.vao) glDeleteVertexArrays(1, &batch.vertexBuffer[i].vaoId); - - // Free vertex arrays memory from CPU (RAM) - RL_FREE(batch.vertexBuffer[i].vertices); - RL_FREE(batch.vertexBuffer[i].texcoords); - RL_FREE(batch.vertexBuffer[i].colors); - RL_FREE(batch.vertexBuffer[i].indices); - } - - // Unload arrays - RL_FREE(batch.vertexBuffer); - RL_FREE(batch.draws); -#endif -} - -// Draw render batch -// NOTE: We require a pointer to reset batch and increase current buffer (multi-buffer) -void rlDrawRenderBatch(rlRenderBatch *batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Update batch vertex buffers - //------------------------------------------------------------------------------------------------------------ - // NOTE: If there is not vertex data, buffers doesn't need to be updated (vertexCount > 0) - // TODO: If no data changed on the CPU arrays --> No need to re-update GPU arrays (use a change detector flag?) - if (RLGL.State.vertexCounter > 0) - { - // Activate elements VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); - - // Vertex positions buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[0]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*3*sizeof(float), batch->vertexBuffer[batch->currentBuffer].vertices); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].vertices, GL_DYNAMIC_DRAW); // Update all buffer - - // Texture coordinates buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[1]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*2*sizeof(float), batch->vertexBuffer[batch->currentBuffer].texcoords); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].texcoords, GL_DYNAMIC_DRAW); // Update all buffer - - // Colors buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*4*sizeof(unsigned char), batch->vertexBuffer[batch->currentBuffer].colors); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].colors, GL_DYNAMIC_DRAW); // Update all buffer - - // NOTE: glMapBuffer() causes sync issue. - // If GPU is working with this buffer, glMapBuffer() will wait(stall) until GPU to finish its job. - // To avoid waiting (idle), you can call first glBufferData() with NULL pointer before glMapBuffer(). - // If you do that, the previous data in PBO will be discarded and glMapBuffer() returns a new - // allocated pointer immediately even if GPU is still working with the previous data. - - // Another option: map the buffer object into client's memory - // Probably this code could be moved somewhere else... - // batch->vertexBuffer[batch->currentBuffer].vertices = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); - // if (batch->vertexBuffer[batch->currentBuffer].vertices) - // { - // Update vertex data - // } - // glUnmapBuffer(GL_ARRAY_BUFFER); - - // Unbind the current VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(0); - } - //------------------------------------------------------------------------------------------------------------ - - // Draw batch vertex buffers (considering VR stereo if required) - //------------------------------------------------------------------------------------------------------------ - Matrix matProjection = RLGL.State.projection; - Matrix matModelView = RLGL.State.modelview; - - int eyeCount = 1; - if (RLGL.State.stereoRender) eyeCount = 2; - - for (int eye = 0; eye < eyeCount; eye++) - { - if (eyeCount == 2) - { - // Setup current eye viewport (half screen width) - rlViewport(eye*RLGL.State.framebufferWidth/2, 0, RLGL.State.framebufferWidth/2, RLGL.State.framebufferHeight); - - // Set current eye view offset to modelview matrix - rlSetMatrixModelview(rlMatrixMultiply(matModelView, RLGL.State.viewOffsetStereo[eye])); - // Set current eye projection matrix - rlSetMatrixProjection(RLGL.State.projectionStereo[eye]); - } - - // Draw buffers - if (RLGL.State.vertexCounter > 0) - { - // Set current shader and upload current MVP matrix - glUseProgram(RLGL.State.currentShaderId); - - // Create modelview-projection matrix and upload to shader - Matrix matMVP = rlMatrixMultiply(RLGL.State.modelview, RLGL.State.projection); - float matMVPfloat[16] = { - matMVP.m0, matMVP.m1, matMVP.m2, matMVP.m3, - matMVP.m4, matMVP.m5, matMVP.m6, matMVP.m7, - matMVP.m8, matMVP.m9, matMVP.m10, matMVP.m11, - matMVP.m12, matMVP.m13, matMVP.m14, matMVP.m15 - }; - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MVP], 1, false, matMVPfloat); - - if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); - else - { - // Bind vertex attrib: position (shader-location = 0) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[0]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION]); - - // Bind vertex attrib: texcoord (shader-location = 1) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[1]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); - - // Bind vertex attrib: color (shader-location = 3) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); - } - - // Setup some default shader values - glUniform4f(RLGL.State.currentShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE], 1.0f, 1.0f, 1.0f, 1.0f); - glUniform1i(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE], 0); // Active default sampler2D: texture0 - - // Activate additional sampler textures - // Those additional textures will be common for all draw calls of the batch - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) - { - if (RLGL.State.activeTextureId[i] > 0) - { - glActiveTexture(GL_TEXTURE0 + 1 + i); - glBindTexture(GL_TEXTURE_2D, RLGL.State.activeTextureId[i]); - } - } - - // Activate default sampler2D texture0 (one texture is always active for default batch shader) - // NOTE: Batch system accumulates calls by texture0 changes, additional textures are enabled for all the draw calls - glActiveTexture(GL_TEXTURE0); - - for (int i = 0, vertexOffset = 0; i < batch->drawCounter; i++) - { - // Bind current draw call texture, activated as GL_TEXTURE0 and Bound to sampler2D texture0 by default - glBindTexture(GL_TEXTURE_2D, batch->draws[i].textureId); - - if ((batch->draws[i].mode == RL_LINES) || (batch->draws[i].mode == RL_TRIANGLES)) glDrawArrays(batch->draws[i].mode, vertexOffset, batch->draws[i].vertexCount); - else - { -#if defined(GRAPHICS_API_OPENGL_33) - // We need to define the number of indices to be processed: elementCount*6 - // NOTE: The final parameter tells the GPU the offset in bytes from the - // start of the index buffer to the location of the first index to process - glDrawElements(GL_TRIANGLES, batch->draws[i].vertexCount/4*6, GL_UNSIGNED_INT, (GLvoid *)(vertexOffset/4*6*sizeof(GLuint))); -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - glDrawElements(GL_TRIANGLES, batch->draws[i].vertexCount/4*6, GL_UNSIGNED_SHORT, (GLvoid *)(vertexOffset/4*6*sizeof(GLushort))); -#endif - } - - vertexOffset += (batch->draws[i].vertexCount + batch->draws[i].vertexAlignment); - } - - if (!RLGL.ExtSupported.vao) - { - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } - - glBindTexture(GL_TEXTURE_2D, 0); // Unbind textures - } - - if (RLGL.ExtSupported.vao) glBindVertexArray(0); // Unbind VAO - - glUseProgram(0); // Unbind shader program - } - - // Restore viewport to default measures - if (eyeCount == 2) rlViewport(0, 0, RLGL.State.framebufferWidth, RLGL.State.framebufferHeight); - //------------------------------------------------------------------------------------------------------------ - - // Reset batch buffers - //------------------------------------------------------------------------------------------------------------ - // Reset vertex counter for next frame - RLGL.State.vertexCounter = 0; - - // Reset depth for next draw - batch->currentDepth = -1.0f; - - // Restore projection/modelview matrices - RLGL.State.projection = matProjection; - RLGL.State.modelview = matModelView; - - // Reset RLGL.currentBatch->draws array - for (int i = 0; i < RL_DEFAULT_BATCH_DRAWCALLS; i++) - { - batch->draws[i].mode = RL_QUADS; - batch->draws[i].vertexCount = 0; - batch->draws[i].textureId = RLGL.State.defaultTextureId; - } - - // Reset active texture units for next batch - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) RLGL.State.activeTextureId[i] = 0; - - // Reset draws counter to one draw for the batch - batch->drawCounter = 1; - //------------------------------------------------------------------------------------------------------------ - - // Change to next buffer in the list (in case of multi-buffering) - batch->currentBuffer++; - if (batch->currentBuffer >= batch->bufferCount) batch->currentBuffer = 0; -#endif -} - -// Set the active render batch for rlgl -void rlSetRenderBatchActive(rlRenderBatch *batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlDrawRenderBatch(RLGL.currentBatch); - - if (batch != NULL) RLGL.currentBatch = batch; - else RLGL.currentBatch = &RLGL.defaultBatch; -#endif -} - -// Update and draw internal render batch -void rlDrawRenderBatchActive(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlDrawRenderBatch(RLGL.currentBatch); // NOTE: Stereo rendering is checked inside -#endif -} - -// Check internal buffer overflow for a given number of vertex -// and force a rlRenderBatch draw call if required -bool rlCheckRenderBatchLimit(int vCount) -{ - bool overflow = false; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.vertexCounter + vCount) >= - (RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4)) - { - overflow = true; - - // Store current primitive drawing mode and texture id - int currentMode = RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode; - int currentTexture = RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId; - - rlDrawRenderBatch(RLGL.currentBatch); // NOTE: Stereo rendering is checked inside - - // Restore state of last batch so we can continue adding vertices - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode = currentMode; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = currentTexture; - } -#endif - - return overflow; -} - -// Textures data management -//----------------------------------------------------------------------------------------- -// Convert image data to OpenGL texture (returns OpenGL valid Id) -unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount) -{ - unsigned int id = 0; - - glBindTexture(GL_TEXTURE_2D, 0); // Free any old binding - - // Check texture format support by OpenGL 1.1 (compressed textures not supported) -#if defined(GRAPHICS_API_OPENGL_11) - if (format >= RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) - { - TRACELOG(RL_LOG_WARNING, "GL: OpenGL 1.1 does not support GPU compressed texture formats"); - return id; - } -#else - if ((!RLGL.ExtSupported.texCompDXT) && ((format == RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA) || - (format == RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA) || (format == RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: DXT compressed texture format not supported"); - return id; - } -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((!RLGL.ExtSupported.texCompETC1) && (format == RL_PIXELFORMAT_COMPRESSED_ETC1_RGB)) - { - TRACELOG(RL_LOG_WARNING, "GL: ETC1 compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompETC2) && ((format == RL_PIXELFORMAT_COMPRESSED_ETC2_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: ETC2 compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompPVRT) && ((format == RL_PIXELFORMAT_COMPRESSED_PVRT_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: PVRT compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompASTC) && ((format == RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA) || (format == RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: ASTC compressed texture format not supported"); - return id; - } -#endif -#endif // GRAPHICS_API_OPENGL_11 - - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - - glGenTextures(1, &id); // Generate texture id - - glBindTexture(GL_TEXTURE_2D, id); - - int mipWidth = width; - int mipHeight = height; - int mipOffset = 0; // Mipmap data offset, only used for tracelog - - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned char *dataPtr = NULL; - if (data != NULL) dataPtr = (unsigned char *)data; - - // Load the different mipmap levels - for (int i = 0; i < mipmapCount; i++) - { - unsigned int mipSize = rlGetPixelDataSize(mipWidth, mipHeight, format); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - TRACELOGD("TEXTURE: Load mipmap level %i (%i x %i), size: %i, offset: %i", i, mipWidth, mipHeight, mipSize, mipOffset); - - if (glInternalFormat != 0) - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, dataPtr); -#if !defined(GRAPHICS_API_OPENGL_11) - else glCompressedTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, mipSize, dataPtr); -#endif - -#if defined(GRAPHICS_API_OPENGL_33) - if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) - { - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } - else if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) - { -#if defined(GRAPHICS_API_OPENGL_21) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; -#elif defined(GRAPHICS_API_OPENGL_33) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; -#endif - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } -#endif - } - - mipWidth /= 2; - mipHeight /= 2; - mipOffset += mipSize; // Increment offset position to next mipmap - if (data != NULL) dataPtr += mipSize; // Increment data pointer to next mipmap - - // Security check for NPOT textures - if (mipWidth < 1) mipWidth = 1; - if (mipHeight < 1) mipHeight = 1; - } - - // Texture parameters configuration - // NOTE: glTexParameteri does NOT affect texture uploading, just the way it's used -#if defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: OpenGL ES 2.0 with no GL_OES_texture_npot support (i.e. WebGL) has limited NPOT support, so CLAMP_TO_EDGE must be used - if (RLGL.ExtSupported.texNPOT) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis - } - else - { - // NOTE: If using negative texture coordinates (LoadOBJ()), it does not work! - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // Set texture to clamp on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Set texture to clamp on y-axis - } -#else - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis -#endif - - // Magnification and minification filters - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Alternative: GL_LINEAR - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // Alternative: GL_LINEAR - -#if defined(GRAPHICS_API_OPENGL_33) - if (mipmapCount > 1) - { - // Activate Trilinear filtering if mipmaps are available - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - } -#endif - - // At this point we have the texture loaded in GPU and texture parameters configured - - // NOTE: If mipmaps were not in data, they are not generated automatically - - // Unbind current texture - glBindTexture(GL_TEXTURE_2D, 0); - - if (id > 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Texture loaded successfully (%ix%i | %s | %i mipmaps)", id, width, height, rlGetPixelFormatName(format), mipmapCount); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load texture"); - - return id; -} - -// Load depth texture/renderbuffer (to be attached to fbo) -// WARNING: OpenGL ES 2.0 requires GL_OES_depth_texture and WebGL requires WEBGL_depth_texture extensions -unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // In case depth textures not supported, we force renderbuffer usage - if (!RLGL.ExtSupported.texDepth) useRenderBuffer = true; - - // NOTE: We let the implementation to choose the best bit-depth - // Possible formats: GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32 and GL_DEPTH_COMPONENT32F - unsigned int glInternalFormat = GL_DEPTH_COMPONENT; - -#if (defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_ES3)) - // WARNING: WebGL platform requires unsized internal format definition (GL_DEPTH_COMPONENT) - // while other platforms using OpenGL ES 2.0 require/support sized internal formats depending on the GPU capabilities - if (!RLGL.ExtSupported.texDepthWebGL || useRenderBuffer) - { - if (RLGL.ExtSupported.maxDepthBits == 32) glInternalFormat = GL_DEPTH_COMPONENT32_OES; - else if (RLGL.ExtSupported.maxDepthBits == 24) glInternalFormat = GL_DEPTH_COMPONENT24_OES; - else glInternalFormat = GL_DEPTH_COMPONENT16; - } -#endif - - if (!useRenderBuffer && RLGL.ExtSupported.texDepth) - { - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_2D, id); - glTexImage2D(GL_TEXTURE_2D, 0, glInternalFormat, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - glBindTexture(GL_TEXTURE_2D, 0); - - TRACELOG(RL_LOG_INFO, "TEXTURE: Depth texture loaded successfully"); - } - else - { - // Create the renderbuffer that will serve as the depth attachment for the framebuffer - // NOTE: A renderbuffer is simpler than a texture and could offer better performance on embedded devices - glGenRenderbuffers(1, &id); - glBindRenderbuffer(GL_RENDERBUFFER, id); - glRenderbufferStorage(GL_RENDERBUFFER, glInternalFormat, width, height); - - glBindRenderbuffer(GL_RENDERBUFFER, 0); - - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Depth renderbuffer loaded successfully (%i bits)", id, (RLGL.ExtSupported.maxDepthBits >= 24)? RLGL.ExtSupported.maxDepthBits : 16); - } -#endif - - return id; -} - -// Load texture cubemap -// NOTE: Cubemap data is expected to be 6 images in a single data array (one after the other), -// expected the following convention: +X, -X, +Y, -Y, +Z, -Z -unsigned int rlLoadTextureCubemap(const void *data, int size, int format) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int dataSize = rlGetPixelDataSize(size, size, format); - - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_CUBE_MAP, id); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - if (glInternalFormat != 0) - { - // Load cubemap faces - for (unsigned int i = 0; i < 6; i++) - { - if (data == NULL) - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) - { - if ((format == RL_PIXELFORMAT_UNCOMPRESSED_R32) || (format == RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32) - || (format == RL_PIXELFORMAT_UNCOMPRESSED_R16) || (format == RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16)) - TRACELOG(RL_LOG_WARNING, "TEXTURES: Cubemap requested format not supported"); - else glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, size, size, 0, glFormat, glType, NULL); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURES: Empty cubemap creation does not support compressed format"); - } - else - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, size, size, 0, glFormat, glType, (unsigned char *)data + i*dataSize); - else glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, size, size, 0, dataSize, (unsigned char *)data + i*dataSize); - } - -#if defined(GRAPHICS_API_OPENGL_33) - if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) - { - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; - glTexParameteriv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } - else if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) - { -#if defined(GRAPHICS_API_OPENGL_21) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; -#elif defined(GRAPHICS_API_OPENGL_33) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; -#endif - glTexParameteriv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } -#endif - } - } - - // Set cubemap texture sampling parameters - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); -#if defined(GRAPHICS_API_OPENGL_33) - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); // Flag not supported on OpenGL ES 2.0 -#endif - - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif - - if (id > 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Cubemap texture loaded successfully (%ix%i)", id, size, size); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load cubemap texture"); - - return id; -} - -// Update already loaded texture in GPU with new data -// NOTE: We don't know safely if internal texture format is the expected one... -void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data) -{ - glBindTexture(GL_TEXTURE_2D, id); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - if ((glInternalFormat != 0) && (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB)) - { - glTexSubImage2D(GL_TEXTURE_2D, 0, offsetX, offsetY, width, height, glFormat, glType, data); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Failed to update for current texture format (%i)", id, format); -} - -// Get OpenGL internal formats and data type from raylib PixelFormat -void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType) -{ - *glInternalFormat = 0; - *glFormat = 0; - *glType = 0; - - switch (format) - { - #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_21) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: on OpenGL ES 2.0 (WebGL), internalFormat must match format and options allowed are: GL_LUMINANCE, GL_RGB, GL_RGBA - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: *glInternalFormat = GL_LUMINANCE_ALPHA; *glFormat = GL_LUMINANCE_ALPHA; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_UNSIGNED_SHORT_5_6_5; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_5_5_5_1; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_4_4_4_4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; - #if !defined(GRAPHICS_API_OPENGL_11) - #if defined(GRAPHICS_API_OPENGL_ES3) - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_R32F_EXT; *glFormat = GL_RED_EXT; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB32F_EXT; *glFormat = GL_RGB; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA32F_EXT; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_R16F_EXT; *glFormat = GL_RED_EXT; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB16F_EXT; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA16F_EXT; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; - #else - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - #if defined(GRAPHICS_API_OPENGL_21) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_HALF_FLOAT_ARB; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT_ARB; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT_ARB; break; - #else // defined(GRAPHICS_API_OPENGL_ES2) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - #endif - #endif - #endif - #elif defined(GRAPHICS_API_OPENGL_33) - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: *glInternalFormat = GL_R8; *glFormat = GL_RED; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: *glInternalFormat = GL_RG8; *glFormat = GL_RG; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: *glInternalFormat = GL_RGB565; *glFormat = GL_RGB; *glType = GL_UNSIGNED_SHORT_5_6_5; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: *glInternalFormat = GL_RGB8; *glFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: *glInternalFormat = GL_RGB5_A1; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_5_5_5_1; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: *glInternalFormat = GL_RGBA4; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_4_4_4_4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: *glInternalFormat = GL_RGBA8; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_R32F; *glFormat = GL_RED; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB32F; *glFormat = GL_RGB; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA32F; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_R16F; *glFormat = GL_RED; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB16F; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA16F; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; - #endif - #if !defined(GRAPHICS_API_OPENGL_11) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: if (RLGL.ExtSupported.texCompETC1) *glInternalFormat = GL_ETC1_RGB8_OES; break; // NOTE: Requires OpenGL ES 2.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: if (RLGL.ExtSupported.texCompETC2) *glInternalFormat = GL_COMPRESSED_RGB8_ETC2; break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: if (RLGL.ExtSupported.texCompETC2) *glInternalFormat = GL_COMPRESSED_RGBA8_ETC2_EAC; break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: if (RLGL.ExtSupported.texCompPVRT) *glInternalFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; break; // NOTE: Requires PowerVR GPU - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: if (RLGL.ExtSupported.texCompPVRT) *glInternalFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; break; // NOTE: Requires PowerVR GPU - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: if (RLGL.ExtSupported.texCompASTC) *glInternalFormat = GL_COMPRESSED_RGBA_ASTC_4x4_KHR; break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: if (RLGL.ExtSupported.texCompASTC) *glInternalFormat = GL_COMPRESSED_RGBA_ASTC_8x8_KHR; break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - #endif - default: TRACELOG(RL_LOG_WARNING, "TEXTURE: Current format not supported (%i)", format); break; - } -} - -// Unload texture from GPU memory -void rlUnloadTexture(unsigned int id) -{ - glDeleteTextures(1, &id); -} - -// Generate mipmap data for selected texture -// NOTE: Only supports GPU mipmap generation -void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_2D, id); - - // Check if texture is power-of-two (POT) - bool texIsPOT = false; - - if (((width > 0) && ((width & (width - 1)) == 0)) && - ((height > 0) && ((height & (height - 1)) == 0))) texIsPOT = true; - - if ((texIsPOT) || (RLGL.ExtSupported.texNPOT)) - { - //glHint(GL_GENERATE_MIPMAP_HINT, GL_DONT_CARE); // Hint for mipmaps generation algorithm: GL_FASTEST, GL_NICEST, GL_DONT_CARE - glGenerateMipmap(GL_TEXTURE_2D); // Generate mipmaps automatically - - #define MIN(a,b) (((a)<(b))? (a):(b)) - #define MAX(a,b) (((a)>(b))? (a):(b)) - - *mipmaps = 1 + (int)floor(log(MAX(width, height))/log(2)); - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Mipmaps generated automatically, total: %i", id, *mipmaps); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Failed to generate mipmaps", id); - - glBindTexture(GL_TEXTURE_2D, 0); -#else - TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] GPU mipmap generation not supported", id); -#endif -} - - -// Read texture pixel data -void *rlReadTexturePixels(unsigned int id, int width, int height, int format) -{ - void *pixels = NULL; - -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - glBindTexture(GL_TEXTURE_2D, id); - - // NOTE: Using texture id, we can retrieve some texture info (but not on OpenGL ES 2.0) - // Possible texture info: GL_TEXTURE_RED_SIZE, GL_TEXTURE_GREEN_SIZE, GL_TEXTURE_BLUE_SIZE, GL_TEXTURE_ALPHA_SIZE - //int width, height, format; - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format); - - // NOTE: Each row written to or read from by OpenGL pixel operations like glGetTexImage are aligned to a 4 byte boundary by default, which may add some padding. - // Use glPixelStorei to modify padding with the GL_[UN]PACK_ALIGNMENT setting. - // GL_PACK_ALIGNMENT affects operations that read from OpenGL memory (glReadPixels, glGetTexImage, etc.) - // GL_UNPACK_ALIGNMENT affects operations that write to OpenGL memory (glTexImage, etc.) - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - unsigned int size = rlGetPixelDataSize(width, height, format); - - if ((glInternalFormat != 0) && (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB)) - { - pixels = RL_MALLOC(size); - glGetTexImage(GL_TEXTURE_2D, 0, glFormat, glType, pixels); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Data retrieval not suported for pixel format (%i)", id, format); - - glBindTexture(GL_TEXTURE_2D, 0); -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - // glGetTexImage() is not available on OpenGL ES 2.0 - // Texture width and height are required on OpenGL ES 2.0. There is no way to get it from texture id. - // Two possible Options: - // 1 - Bind texture to color fbo attachment and glReadPixels() - // 2 - Create an fbo, activate it, render quad with texture, glReadPixels() - // We are using Option 1, just need to care for texture format on retrieval - // NOTE: This behaviour could be conditioned by graphic driver... - unsigned int fboId = rlLoadFramebuffer(width, height); - - glBindFramebuffer(GL_FRAMEBUFFER, fboId); - glBindTexture(GL_TEXTURE_2D, 0); - - // Attach our texture to FBO - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, id, 0); - - // We read data as RGBA because FBO texture is configured as RGBA, despite binding another texture format - pixels = (unsigned char *)RL_MALLOC(rlGetPixelDataSize(width, height, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8)); - glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - // Clean up temporal fbo - rlUnloadFramebuffer(fboId); -#endif - - return pixels; -} - -// Read screen pixel data (color buffer) -unsigned char *rlReadScreenPixels(int width, int height) -{ - unsigned char *screenData = (unsigned char *)RL_CALLOC(width*height*4, sizeof(unsigned char)); - - // NOTE 1: glReadPixels returns image flipped vertically -> (0,0) is the bottom left corner of the framebuffer - // NOTE 2: We are getting alpha channel! Be careful, it can be transparent if not cleared properly! - glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, screenData); - - // Flip image vertically! - unsigned char *imgData = (unsigned char *)RL_MALLOC(width*height*4*sizeof(unsigned char)); - - for (int y = height - 1; y >= 0; y--) - { - for (int x = 0; x < (width*4); x++) - { - imgData[((height - 1) - y)*width*4 + x] = screenData[(y*width*4) + x]; // Flip line - - // Set alpha component value to 255 (no trasparent image retrieval) - // NOTE: Alpha value has already been applied to RGB in framebuffer, we don't need it! - if (((x + 1)%4) == 0) imgData[((height - 1) - y)*width*4 + x] = 255; - } - } - - RL_FREE(screenData); - - return imgData; // NOTE: image data should be freed -} - -// Framebuffer management (fbo) -//----------------------------------------------------------------------------------------- -// Load a framebuffer to be used for rendering -// NOTE: No textures attached -unsigned int rlLoadFramebuffer(int width, int height) -{ - unsigned int fboId = 0; - -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glGenFramebuffers(1, &fboId); // Create the framebuffer object - glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind any framebuffer -#endif - - return fboId; -} - -// Attach color buffer texture to an fbo (unloads previous attachment) -// NOTE: Attach type: 0-Color, 1-Depth renderbuffer, 2-Depth texture -void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, fboId); - - switch (attachType) - { - case RL_ATTACHMENT_COLOR_CHANNEL0: - case RL_ATTACHMENT_COLOR_CHANNEL1: - case RL_ATTACHMENT_COLOR_CHANNEL2: - case RL_ATTACHMENT_COLOR_CHANNEL3: - case RL_ATTACHMENT_COLOR_CHANNEL4: - case RL_ATTACHMENT_COLOR_CHANNEL5: - case RL_ATTACHMENT_COLOR_CHANNEL6: - case RL_ATTACHMENT_COLOR_CHANNEL7: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_RENDERBUFFER, texId); - else if (texType >= RL_ATTACHMENT_CUBEMAP_POSITIVE_X) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_TEXTURE_CUBE_MAP_POSITIVE_X + texType, texId, mipLevel); - - } break; - case RL_ATTACHMENT_DEPTH: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, texId); - - } break; - case RL_ATTACHMENT_STENCIL: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, texId); - - } break; - default: break; - } - - glBindFramebuffer(GL_FRAMEBUFFER, 0); -#endif -} - -// Verify render texture is complete -bool rlFramebufferComplete(unsigned int id) -{ - bool result = false; - -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, id); - - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - - if (status != GL_FRAMEBUFFER_COMPLETE) - { - switch (status) - { - case GL_FRAMEBUFFER_UNSUPPORTED: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer is unsupported", id); break; - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has incomplete attachment", id); break; -#if defined(GRAPHICS_API_OPENGL_ES2) - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has incomplete dimensions", id); break; -#endif - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has a missing attachment", id); break; - default: break; - } - } - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - result = (status == GL_FRAMEBUFFER_COMPLETE); -#endif - - return result; -} - -// Unload framebuffer from GPU memory -// NOTE: All attached textures/cubemaps/renderbuffers are also deleted -void rlUnloadFramebuffer(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - // Query depth attachment to automatically delete texture/renderbuffer - int depthType = 0, depthId = 0; - glBindFramebuffer(GL_FRAMEBUFFER, id); // Bind framebuffer to query depth texture type - glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &depthType); - - // TODO: Review warning retrieving object name in WebGL - // WARNING: WebGL: INVALID_ENUM: getFramebufferAttachmentParameter: invalid parameter name - // https://registry.khronos.org/webgl/specs/latest/1.0/ - glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthId); - - unsigned int depthIdU = (unsigned int)depthId; - if (depthType == GL_RENDERBUFFER) glDeleteRenderbuffers(1, &depthIdU); - else if (depthType == GL_TEXTURE) glDeleteTextures(1, &depthIdU); - - // NOTE: If a texture object is deleted while its image is attached to the *currently bound* framebuffer, - // the texture image is automatically detached from the currently bound framebuffer. - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glDeleteFramebuffers(1, &id); - - TRACELOG(RL_LOG_INFO, "FBO: [ID %i] Unloaded framebuffer from VRAM (GPU)", id); -#endif -} - -// Vertex data management -//----------------------------------------------------------------------------------------- -// Load a new attributes buffer -unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glGenBuffers(1, &id); - glBindBuffer(GL_ARRAY_BUFFER, id); - glBufferData(GL_ARRAY_BUFFER, size, buffer, dynamic? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); -#endif - - return id; -} - -// Load a new attributes element buffer -unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glGenBuffers(1, &id); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, buffer, dynamic? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); -#endif - - return id; -} - -// Enable vertex buffer (VBO) -void rlEnableVertexBuffer(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, id); -#endif -} - -// Disable vertex buffer (VBO) -void rlDisableVertexBuffer(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif -} - -// Enable vertex buffer element (VBO element) -void rlEnableVertexBufferElement(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); -#endif -} - -// Disable vertex buffer element (VBO element) -void rlDisableVertexBufferElement(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); -#endif -} - -// Update vertex buffer with new data -// NOTE: dataSize and offset must be provided in bytes -void rlUpdateVertexBuffer(unsigned int id, const void *data, int dataSize, int offset) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, id); - glBufferSubData(GL_ARRAY_BUFFER, offset, dataSize, data); -#endif -} - -// Update vertex buffer elements with new data -// NOTE: dataSize and offset must be provided in bytes -void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, dataSize, data); -#endif -} - -// Enable vertex array object (VAO) -bool rlEnableVertexArray(unsigned int vaoId) -{ - bool result = false; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(vaoId); - result = true; - } -#endif - return result; -} - -// Disable vertex array object (VAO) -void rlDisableVertexArray(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) glBindVertexArray(0); -#endif -} - -// Enable vertex attribute index -void rlEnableVertexAttribute(unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glEnableVertexAttribArray(index); -#endif -} - -// Disable vertex attribute index -void rlDisableVertexAttribute(unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDisableVertexAttribArray(index); -#endif -} - -// Draw vertex array -void rlDrawVertexArray(int offset, int count) -{ - glDrawArrays(GL_TRIANGLES, offset, count); -} - -// Draw vertex array elements -void rlDrawVertexArrayElements(int offset, int count, const void *buffer) -{ - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned short *bufferPtr = (unsigned short *)buffer; - if (offset > 0) bufferPtr += offset; - - glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, (const unsigned short *)bufferPtr); -} - -// Draw vertex array instanced -void rlDrawVertexArrayInstanced(int offset, int count, int instances) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDrawArraysInstanced(GL_TRIANGLES, 0, count, instances); -#endif -} - -// Draw vertex array elements instanced -void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned short *bufferPtr = (unsigned short *)buffer; - if (offset > 0) bufferPtr += offset; - - glDrawElementsInstanced(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, (const unsigned short *)bufferPtr, instances); -#endif -} - -#if defined(GRAPHICS_API_OPENGL_11) -// Enable vertex state pointer -void rlEnableStatePointer(int vertexAttribType, void *buffer) -{ - if (buffer != NULL) glEnableClientState(vertexAttribType); - switch (vertexAttribType) - { - case GL_VERTEX_ARRAY: glVertexPointer(3, GL_FLOAT, 0, buffer); break; - case GL_TEXTURE_COORD_ARRAY: glTexCoordPointer(2, GL_FLOAT, 0, buffer); break; - case GL_NORMAL_ARRAY: if (buffer != NULL) glNormalPointer(GL_FLOAT, 0, buffer); break; - case GL_COLOR_ARRAY: if (buffer != NULL) glColorPointer(4, GL_UNSIGNED_BYTE, 0, buffer); break; - //case GL_INDEX_ARRAY: if (buffer != NULL) glIndexPointer(GL_SHORT, 0, buffer); break; // Indexed colors - default: break; - } -} - -// Disable vertex state pointer -void rlDisableStatePointer(int vertexAttribType) -{ - glDisableClientState(vertexAttribType); -} -#endif - -// Load vertex array object (VAO) -unsigned int rlLoadVertexArray(void) -{ - unsigned int vaoId = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glGenVertexArrays(1, &vaoId); - } -#endif - return vaoId; -} - -// Set vertex attribute -void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, const void *pointer) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glVertexAttribPointer(index, compSize, type, normalized, stride, pointer); -#endif -} - -// Set vertex attribute divisor -void rlSetVertexAttributeDivisor(unsigned int index, int divisor) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glVertexAttribDivisor(index, divisor); -#endif -} - -// Unload vertex array object (VAO) -void rlUnloadVertexArray(unsigned int vaoId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(0); - glDeleteVertexArrays(1, &vaoId); - TRACELOG(RL_LOG_INFO, "VAO: [ID %i] Unloaded vertex array data from VRAM (GPU)", vaoId); - } -#endif -} - -// Unload vertex buffer (VBO) -void rlUnloadVertexBuffer(unsigned int vboId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDeleteBuffers(1, &vboId); - //TRACELOG(RL_LOG_INFO, "VBO: Unloaded vertex data from VRAM (GPU)"); -#endif -} - -// Shaders management -//----------------------------------------------------------------------------------------------- -// Load shader from code strings -// NOTE: If shader string is NULL, using default vertex/fragment shaders -unsigned int rlLoadShaderCode(const char *vsCode, const char *fsCode) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int vertexShaderId = 0; - unsigned int fragmentShaderId = 0; - - // Compile vertex shader (if provided) - if (vsCode != NULL) vertexShaderId = rlCompileShader(vsCode, GL_VERTEX_SHADER); - // In case no vertex shader was provided or compilation failed, we use default vertex shader - if (vertexShaderId == 0) vertexShaderId = RLGL.State.defaultVShaderId; - - // Compile fragment shader (if provided) - if (fsCode != NULL) fragmentShaderId = rlCompileShader(fsCode, GL_FRAGMENT_SHADER); - // In case no fragment shader was provided or compilation failed, we use default fragment shader - if (fragmentShaderId == 0) fragmentShaderId = RLGL.State.defaultFShaderId; - - // In case vertex and fragment shader are the default ones, no need to recompile, we can just assign the default shader program id - if ((vertexShaderId == RLGL.State.defaultVShaderId) && (fragmentShaderId == RLGL.State.defaultFShaderId)) id = RLGL.State.defaultShaderId; - else - { - // One of or both shader are new, we need to compile a new shader program - id = rlLoadShaderProgram(vertexShaderId, fragmentShaderId); - - // We can detach and delete vertex/fragment shaders (if not default ones) - // NOTE: We detach shader before deletion to make sure memory is freed - if (vertexShaderId != RLGL.State.defaultVShaderId) - { - // WARNING: Shader program linkage could fail and returned id is 0 - if (id > 0) glDetachShader(id, vertexShaderId); - glDeleteShader(vertexShaderId); - } - if (fragmentShaderId != RLGL.State.defaultFShaderId) - { - // WARNING: Shader program linkage could fail and returned id is 0 - if (id > 0) glDetachShader(id, fragmentShaderId); - glDeleteShader(fragmentShaderId); - } - - // In case shader program loading failed, we assign default shader - if (id == 0) - { - // In case shader loading fails, we return the default shader - TRACELOG(RL_LOG_WARNING, "SHADER: Failed to load custom shader code, using default shader"); - id = RLGL.State.defaultShaderId; - } - /* - else - { - // Get available shader uniforms - // NOTE: This information is useful for debug... - int uniformCount = -1; - glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &uniformCount); - - for (int i = 0; i < uniformCount; i++) - { - int namelen = -1; - int num = -1; - char name[256] = { 0 }; // Assume no variable names longer than 256 - GLenum type = GL_ZERO; - - // Get the name of the uniforms - glGetActiveUniform(id, i, sizeof(name) - 1, &namelen, &num, &type, name); - - name[namelen] = 0; - TRACELOGD("SHADER: [ID %i] Active uniform (%s) set at location: %i", id, name, glGetUniformLocation(id, name)); - } - } - */ - } -#endif - - return id; -} - -// Compile custom shader and return shader id -unsigned int rlCompileShader(const char *shaderCode, int type) -{ - unsigned int shader = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - shader = glCreateShader(type); - glShaderSource(shader, 1, &shaderCode, NULL); - - GLint success = 0; - glCompileShader(shader); - glGetShaderiv(shader, GL_COMPILE_STATUS, &success); - - if (success == GL_FALSE) - { - switch (type) - { - case GL_VERTEX_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile vertex shader code", shader); break; - case GL_FRAGMENT_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile fragment shader code", shader); break; - //case GL_GEOMETRY_SHADER: - #if defined(GRAPHICS_API_OPENGL_43) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile compute shader code", shader); break; - #endif - default: break; - } - - int maxLength = 0; - glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetShaderInfoLog(shader, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Compile error: %s", shader, log); - RL_FREE(log); - } - } - else - { - switch (type) - { - case GL_VERTEX_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Vertex shader compiled successfully", shader); break; - case GL_FRAGMENT_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Fragment shader compiled successfully", shader); break; - //case GL_GEOMETRY_SHADER: - #if defined(GRAPHICS_API_OPENGL_43) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Compute shader compiled successfully", shader); break; - #endif - default: break; - } - } -#endif - - return shader; -} - -// Load custom shader strings and return program id -unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId) -{ - unsigned int program = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - GLint success = 0; - program = glCreateProgram(); - - glAttachShader(program, vShaderId); - glAttachShader(program, fShaderId); - - // NOTE: Default attribute shader locations must be Bound before linking - glBindAttribLocation(program, 0, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); - glBindAttribLocation(program, 1, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); - glBindAttribLocation(program, 2, RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL); - glBindAttribLocation(program, 3, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); - glBindAttribLocation(program, 4, RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT); - glBindAttribLocation(program, 5, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2); - - // NOTE: If some attrib name is no found on the shader, it locations becomes -1 - - glLinkProgram(program); - - // NOTE: All uniform variables are intitialised to 0 when a program links - - glGetProgramiv(program, GL_LINK_STATUS, &success); - - if (success == GL_FALSE) - { - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to link shader program", program); - - int maxLength = 0; - glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetProgramInfoLog(program, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Link error: %s", program, log); - RL_FREE(log); - } - - glDeleteProgram(program); - - program = 0; - } - else - { - // Get the size of compiled shader program (not available on OpenGL ES 2.0) - // NOTE: If GL_LINK_STATUS is GL_FALSE, program binary length is zero. - //GLint binarySize = 0; - //glGetProgramiv(id, GL_PROGRAM_BINARY_LENGTH, &binarySize); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Program shader loaded successfully", program); - } -#endif - return program; -} - -// Unload shader program -void rlUnloadShaderProgram(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDeleteProgram(id); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Unloaded shader program data from VRAM (GPU)", id); -#endif -} - -// Get shader location uniform -int rlGetLocationUniform(unsigned int shaderId, const char *uniformName) -{ - int location = -1; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - location = glGetUniformLocation(shaderId, uniformName); - - //if (location == -1) TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to find shader uniform: %s", shaderId, uniformName); - //else TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Shader uniform (%s) set at location: %i", shaderId, uniformName, location); -#endif - return location; -} - -// Get shader location attribute -int rlGetLocationAttrib(unsigned int shaderId, const char *attribName) -{ - int location = -1; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - location = glGetAttribLocation(shaderId, attribName); - - //if (location == -1) TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to find shader attribute: %s", shaderId, attribName); - //else TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Shader attribute (%s) set at location: %i", shaderId, attribName, location); -#endif - return location; -} - -// Set shader value uniform -void rlSetUniform(int locIndex, const void *value, int uniformType, int count) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - switch (uniformType) - { - case RL_SHADER_UNIFORM_FLOAT: glUniform1fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC2: glUniform2fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC3: glUniform3fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC4: glUniform4fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_INT: glUniform1iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC2: glUniform2iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC3: glUniform3iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC4: glUniform4iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_SAMPLER2D: glUniform1iv(locIndex, count, (int *)value); break; - default: TRACELOG(RL_LOG_WARNING, "SHADER: Failed to set uniform value, data type not recognized"); - } -#endif -} - -// Set shader value attribute -void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - switch (attribType) - { - case RL_SHADER_ATTRIB_FLOAT: if (count == 1) glVertexAttrib1fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC2: if (count == 2) glVertexAttrib2fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC3: if (count == 3) glVertexAttrib3fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC4: if (count == 4) glVertexAttrib4fv(locIndex, (float *)value); break; - default: TRACELOG(RL_LOG_WARNING, "SHADER: Failed to set attrib default value, data type not recognized"); - } -#endif -} - -// Set shader value uniform matrix -void rlSetUniformMatrix(int locIndex, Matrix mat) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - float matfloat[16] = { - mat.m0, mat.m1, mat.m2, mat.m3, - mat.m4, mat.m5, mat.m6, mat.m7, - mat.m8, mat.m9, mat.m10, mat.m11, - mat.m12, mat.m13, mat.m14, mat.m15 - }; - glUniformMatrix4fv(locIndex, 1, false, matfloat); -#endif -} - -// Set shader value uniform sampler -void rlSetUniformSampler(int locIndex, unsigned int textureId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Check if texture is already active - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) if (RLGL.State.activeTextureId[i] == textureId) return; - - // Register a new active texture for the internal batch system - // NOTE: Default texture is always activated as GL_TEXTURE0 - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) - { - if (RLGL.State.activeTextureId[i] == 0) - { - glUniform1i(locIndex, 1 + i); // Activate new texture unit - RLGL.State.activeTextureId[i] = textureId; // Save texture id for binding on drawing - break; - } - } -#endif -} - -// Set shader currently active (id and locations) -void rlSetShader(unsigned int id, int *locs) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.State.currentShaderId != id) - { - rlDrawRenderBatch(RLGL.currentBatch); - RLGL.State.currentShaderId = id; - RLGL.State.currentShaderLocs = locs; - } -#endif -} - -// Load compute shader program -unsigned int rlLoadComputeShaderProgram(unsigned int shaderId) -{ - unsigned int program = 0; - -#if defined(GRAPHICS_API_OPENGL_43) - GLint success = 0; - program = glCreateProgram(); - glAttachShader(program, shaderId); - glLinkProgram(program); - - // NOTE: All uniform variables are intitialised to 0 when a program links - - glGetProgramiv(program, GL_LINK_STATUS, &success); - - if (success == GL_FALSE) - { - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to link compute shader program", program); - - int maxLength = 0; - glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetProgramInfoLog(program, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Link error: %s", program, log); - RL_FREE(log); - } - - glDeleteProgram(program); - - program = 0; - } - else - { - // Get the size of compiled shader program (not available on OpenGL ES 2.0) - // NOTE: If GL_LINK_STATUS is GL_FALSE, program binary length is zero. - //GLint binarySize = 0; - //glGetProgramiv(id, GL_PROGRAM_BINARY_LENGTH, &binarySize); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Compute shader program loaded successfully", program); - } -#endif - - return program; -} - -// Dispatch compute shader (equivalent to *draw* for graphics pilepine) -void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glDispatchCompute(groupX, groupY, groupZ); -#endif -} - -// Load shader storage buffer object (SSBO) -unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint) -{ - unsigned int ssbo = 0; - -#if defined(GRAPHICS_API_OPENGL_43) - glGenBuffers(1, &ssbo); - glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo); - glBufferData(GL_SHADER_STORAGE_BUFFER, size, data, usageHint? usageHint : RL_STREAM_COPY); - if (data == NULL) glClearBufferData(GL_SHADER_STORAGE_BUFFER, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, NULL); // Clear buffer data to 0 - glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); -#endif - - return ssbo; -} - -// Unload shader storage buffer object (SSBO) -void rlUnloadShaderBuffer(unsigned int ssboId) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glDeleteBuffers(1, &ssboId); -#endif -} - -// Update SSBO buffer data -void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glBufferSubData(GL_SHADER_STORAGE_BUFFER, offset, dataSize, data); -#endif -} - -// Get SSBO buffer size -unsigned int rlGetShaderBufferSize(unsigned int id) -{ - long long size = 0; - -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glGetInteger64v(GL_SHADER_STORAGE_BUFFER_SIZE, &size); -#endif - - return (size > 0)? (unsigned int)size : 0; -} - -// Read SSBO buffer data (GPU->CPU) -void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, offset, count, dest); -#endif -} - -// Bind SSBO buffer -void rlBindShaderBuffer(unsigned int id, unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, index, id); -#endif -} - -// Copy SSBO buffer data -void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_COPY_READ_BUFFER, srcId); - glBindBuffer(GL_COPY_WRITE_BUFFER, destId); - glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, srcOffset, destOffset, count); -#endif -} - -// Bind image texture -void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly) -{ -#if defined(GRAPHICS_API_OPENGL_43) - unsigned int glInternalFormat = 0, glFormat = 0, glType = 0; - - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - glBindImageTexture(index, id, 0, 0, 0, readonly? GL_READ_ONLY : GL_READ_WRITE, glInternalFormat); -#endif -} - -// Matrix state management -//----------------------------------------------------------------------------------------- -// Get internal modelview matrix -Matrix rlGetMatrixModelview(void) -{ - Matrix matrix = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_11) - float mat[16]; - glGetFloatv(GL_MODELVIEW_MATRIX, mat); - matrix.m0 = mat[0]; - matrix.m1 = mat[1]; - matrix.m2 = mat[2]; - matrix.m3 = mat[3]; - matrix.m4 = mat[4]; - matrix.m5 = mat[5]; - matrix.m6 = mat[6]; - matrix.m7 = mat[7]; - matrix.m8 = mat[8]; - matrix.m9 = mat[9]; - matrix.m10 = mat[10]; - matrix.m11 = mat[11]; - matrix.m12 = mat[12]; - matrix.m13 = mat[13]; - matrix.m14 = mat[14]; - matrix.m15 = mat[15]; -#else - matrix = RLGL.State.modelview; -#endif - return matrix; -} - -// Get internal projection matrix -Matrix rlGetMatrixProjection(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) - float mat[16]; - glGetFloatv(GL_PROJECTION_MATRIX,mat); - Matrix m; - m.m0 = mat[0]; - m.m1 = mat[1]; - m.m2 = mat[2]; - m.m3 = mat[3]; - m.m4 = mat[4]; - m.m5 = mat[5]; - m.m6 = mat[6]; - m.m7 = mat[7]; - m.m8 = mat[8]; - m.m9 = mat[9]; - m.m10 = mat[10]; - m.m11 = mat[11]; - m.m12 = mat[12]; - m.m13 = mat[13]; - m.m14 = mat[14]; - m.m15 = mat[15]; - return m; -#else - return RLGL.State.projection; -#endif -} - -// Get internal accumulated transform matrix -Matrix rlGetMatrixTransform(void) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // TODO: Consider possible transform matrices in the RLGL.State.stack - // Is this the right order? or should we start with the first stored matrix instead of the last one? - //Matrix matStackTransform = rlMatrixIdentity(); - //for (int i = RLGL.State.stackCounter; i > 0; i--) matStackTransform = rlMatrixMultiply(RLGL.State.stack[i], matStackTransform); - mat = RLGL.State.transform; -#endif - return mat; -} - -// Get internal projection matrix for stereo render (selected eye) -RLAPI Matrix rlGetMatrixProjectionStereo(int eye) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - mat = RLGL.State.projectionStereo[eye]; -#endif - return mat; -} - -// Get internal view offset matrix for stereo render (selected eye) -RLAPI Matrix rlGetMatrixViewOffsetStereo(int eye) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - mat = RLGL.State.viewOffsetStereo[eye]; -#endif - return mat; -} - -// Set a custom modelview matrix (replaces internal modelview matrix) -void rlSetMatrixModelview(Matrix view) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.modelview = view; -#endif -} - -// Set a custom projection matrix (replaces internal projection matrix) -void rlSetMatrixProjection(Matrix projection) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.projection = projection; -#endif -} - -// Set eyes projection matrices for stereo rendering -void rlSetMatrixProjectionStereo(Matrix right, Matrix left) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.projectionStereo[0] = right; - RLGL.State.projectionStereo[1] = left; -#endif -} - -// Set eyes view offsets matrices for stereo rendering -void rlSetMatrixViewOffsetStereo(Matrix right, Matrix left) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.viewOffsetStereo[0] = right; - RLGL.State.viewOffsetStereo[1] = left; -#endif -} - -// Load and draw a quad in NDC -void rlLoadDrawQuad(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int quadVAO = 0; - unsigned int quadVBO = 0; - - float vertices[] = { - // Positions Texcoords - -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, - 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, - }; - - // Gen VAO to contain VBO - glGenVertexArrays(1, &quadVAO); - glBindVertexArray(quadVAO); - - // Gen and fill vertex buffer (VBO) - glGenBuffers(1, &quadVBO); - glBindBuffer(GL_ARRAY_BUFFER, quadVBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); - - // Bind vertex attributes (position, texcoords) - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)0); // Positions - glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)(3*sizeof(float))); // Texcoords - - // Draw quad - glBindVertexArray(quadVAO); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - glBindVertexArray(0); - - // Delete buffers (VBO and VAO) - glDeleteBuffers(1, &quadVBO); - glDeleteVertexArrays(1, &quadVAO); -#endif -} - -// Load and draw a cube in NDC -void rlLoadDrawCube(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int cubeVAO = 0; - unsigned int cubeVBO = 0; - - float vertices[] = { - // Positions Normals Texcoords - -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - -1.0f, -1.0f, -1.0f, -1.0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, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f - }; - - // Gen VAO to contain VBO - glGenVertexArrays(1, &cubeVAO); - glBindVertexArray(cubeVAO); - - // Gen and fill vertex buffer (VBO) - glGenBuffers(1, &cubeVBO); - glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - - // Bind vertex attributes (position, normals, texcoords) - glBindVertexArray(cubeVAO); - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)0); // Positions - glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(3*sizeof(float))); // Normals - glEnableVertexAttribArray(2); - glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(6*sizeof(float))); // Texcoords - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - - // Draw cube - glBindVertexArray(cubeVAO); - glDrawArrays(GL_TRIANGLES, 0, 36); - glBindVertexArray(0); - - // Delete VBO and VAO - glDeleteBuffers(1, &cubeVBO); - glDeleteVertexArrays(1, &cubeVAO); -#endif -} - -// Get name string for pixel format -const char *rlGetPixelFormatName(unsigned int format) -{ - switch (format) - { - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: return "GRAYSCALE"; break; // 8 bit per pixel (no alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: return "GRAY_ALPHA"; break; // 8*2 bpp (2 channels) - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: return "R5G6B5"; break; // 16 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: return "R8G8B8"; break; // 24 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: return "R5G5B5A1"; break; // 16 bpp (1 bit alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: return "R4G4B4A4"; break; // 16 bpp (4 bit alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: return "R8G8B8A8"; break; // 32 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R32: return "R32"; break; // 32 bpp (1 channel - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: return "R32G32B32"; break; // 32*3 bpp (3 channels - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: return "R32G32B32A32"; break; // 32*4 bpp (4 channels - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: return "R16"; break; // 16 bpp (1 channel - half float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: return "R16G16B16"; break; // 16*3 bpp (3 channels - half float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: return "R16G16B16A16"; break; // 16*4 bpp (4 channels - half float) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: return "DXT1_RGB"; break; // 4 bpp (no alpha) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: return "DXT1_RGBA"; break; // 4 bpp (1 bit alpha) - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: return "DXT3_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: return "DXT5_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: return "ETC1_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: return "ETC2_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: return "ETC2_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: return "PVRT_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: return "PVRT_RGBA"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: return "ASTC_4x4_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: return "ASTC_8x8_RGBA"; break; // 2 bpp - default: return "UNKNOWN"; break; - } -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Load default shader (just vertex positioning and texture coloring) -// NOTE: This shader program is used for internal buffers -// NOTE: Loaded: RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs -static void rlLoadShaderDefault(void) -{ - RLGL.State.defaultShaderLocs = (int *)RL_CALLOC(RL_MAX_SHADER_LOCATIONS, sizeof(int)); - - // NOTE: All locations must be reseted to -1 (no location) - for (int i = 0; i < RL_MAX_SHADER_LOCATIONS; i++) RLGL.State.defaultShaderLocs[i] = -1; - - // Vertex shader directly defined, no external file required - const char *defaultVShaderCode = -#if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" - "attribute vec3 vertexPosition; \n" - "attribute vec2 vertexTexCoord; \n" - "attribute vec4 vertexColor; \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec3 vertexPosition; \n" - "in vec2 vertexTexCoord; \n" - "in vec4 vertexColor; \n" - "out vec2 fragTexCoord; \n" - "out vec4 fragColor; \n" -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" - "precision mediump float; \n" // Precision required for OpenGL ES2 (WebGL) (on some browsers) - "attribute vec3 vertexPosition; \n" - "attribute vec2 vertexTexCoord; \n" - "attribute vec4 vertexColor; \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" -#endif - "uniform mat4 mvp; \n" - "void main() \n" - "{ \n" - " fragTexCoord = vertexTexCoord; \n" - " fragColor = vertexColor; \n" - " gl_Position = mvp*vec4(vertexPosition, 1.0); \n" - "} \n"; - - // Fragment shader directly defined, no external file required - const char *defaultFShaderCode = -#if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" - " gl_FragColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec2 fragTexCoord; \n" - "in vec4 fragColor; \n" - "out vec4 finalColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture(texture0, fragTexCoord); \n" - " finalColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" - "precision mediump float; \n" // Precision required for OpenGL ES2 (WebGL) - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" - " gl_FragColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#endif - - // NOTE: Compiled vertex/fragment shaders are not deleted, - // they are kept for re-use as default shaders in case some shader loading fails - RLGL.State.defaultVShaderId = rlCompileShader(defaultVShaderCode, GL_VERTEX_SHADER); // Compile default vertex shader - RLGL.State.defaultFShaderId = rlCompileShader(defaultFShaderCode, GL_FRAGMENT_SHADER); // Compile default fragment shader - - RLGL.State.defaultShaderId = rlLoadShaderProgram(RLGL.State.defaultVShaderId, RLGL.State.defaultFShaderId); - - if (RLGL.State.defaultShaderId > 0) - { - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader loaded successfully", RLGL.State.defaultShaderId); - - // Set default shader locations: attributes locations - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_POSITION] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexPosition"); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexTexCoord"); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_COLOR] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexColor"); - - // Set default shader locations: uniform locations - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MATRIX_MVP] = glGetUniformLocation(RLGL.State.defaultShaderId, "mvp"); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, "colDiffuse"); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, "texture0"); - } - else TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to load default shader", RLGL.State.defaultShaderId); -} - -// Unload default shader -// NOTE: Unloads: RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs -static void rlUnloadShaderDefault(void) -{ - glUseProgram(0); - - glDetachShader(RLGL.State.defaultShaderId, RLGL.State.defaultVShaderId); - glDetachShader(RLGL.State.defaultShaderId, RLGL.State.defaultFShaderId); - glDeleteShader(RLGL.State.defaultVShaderId); - glDeleteShader(RLGL.State.defaultFShaderId); - - glDeleteProgram(RLGL.State.defaultShaderId); - - RL_FREE(RLGL.State.defaultShaderLocs); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader unloaded successfully", RLGL.State.defaultShaderId); -} - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) -// Get compressed format official GL identifier name -static const char *rlGetCompressedFormatName(int format) -{ - switch (format) - { - // GL_EXT_texture_compression_s3tc - case 0x83F0: return "GL_COMPRESSED_RGB_S3TC_DXT1_EXT"; break; - case 0x83F1: return "GL_COMPRESSED_RGBA_S3TC_DXT1_EXT"; break; - case 0x83F2: return "GL_COMPRESSED_RGBA_S3TC_DXT3_EXT"; break; - case 0x83F3: return "GL_COMPRESSED_RGBA_S3TC_DXT5_EXT"; break; - // GL_3DFX_texture_compression_FXT1 - case 0x86B0: return "GL_COMPRESSED_RGB_FXT1_3DFX"; break; - case 0x86B1: return "GL_COMPRESSED_RGBA_FXT1_3DFX"; break; - // GL_IMG_texture_compression_pvrtc - case 0x8C00: return "GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; break; - case 0x8C01: return "GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; break; - case 0x8C02: return "GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; break; - case 0x8C03: return "GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; break; - // GL_OES_compressed_ETC1_RGB8_texture - case 0x8D64: return "GL_ETC1_RGB8_OES"; break; - // GL_ARB_texture_compression_rgtc - case 0x8DBB: return "GL_COMPRESSED_RED_RGTC1"; break; - case 0x8DBC: return "GL_COMPRESSED_SIGNED_RED_RGTC1"; break; - case 0x8DBD: return "GL_COMPRESSED_RG_RGTC2"; break; - case 0x8DBE: return "GL_COMPRESSED_SIGNED_RG_RGTC2"; break; - // GL_ARB_texture_compression_bptc - case 0x8E8C: return "GL_COMPRESSED_RGBA_BPTC_UNORM_ARB"; break; - case 0x8E8D: return "GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB"; break; - case 0x8E8E: return "GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB"; break; - case 0x8E8F: return "GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB"; break; - // GL_ARB_ES3_compatibility - case 0x9274: return "GL_COMPRESSED_RGB8_ETC2"; break; - case 0x9275: return "GL_COMPRESSED_SRGB8_ETC2"; break; - case 0x9276: return "GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; break; - case 0x9277: return "GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; break; - case 0x9278: return "GL_COMPRESSED_RGBA8_ETC2_EAC"; break; - case 0x9279: return "GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; break; - case 0x9270: return "GL_COMPRESSED_R11_EAC"; break; - case 0x9271: return "GL_COMPRESSED_SIGNED_R11_EAC"; break; - case 0x9272: return "GL_COMPRESSED_RG11_EAC"; break; - case 0x9273: return "GL_COMPRESSED_SIGNED_RG11_EAC"; break; - // GL_KHR_texture_compression_astc_hdr - case 0x93B0: return "GL_COMPRESSED_RGBA_ASTC_4x4_KHR"; break; - case 0x93B1: return "GL_COMPRESSED_RGBA_ASTC_5x4_KHR"; break; - case 0x93B2: return "GL_COMPRESSED_RGBA_ASTC_5x5_KHR"; break; - case 0x93B3: return "GL_COMPRESSED_RGBA_ASTC_6x5_KHR"; break; - case 0x93B4: return "GL_COMPRESSED_RGBA_ASTC_6x6_KHR"; break; - case 0x93B5: return "GL_COMPRESSED_RGBA_ASTC_8x5_KHR"; break; - case 0x93B6: return "GL_COMPRESSED_RGBA_ASTC_8x6_KHR"; break; - case 0x93B7: return "GL_COMPRESSED_RGBA_ASTC_8x8_KHR"; break; - case 0x93B8: return "GL_COMPRESSED_RGBA_ASTC_10x5_KHR"; break; - case 0x93B9: return "GL_COMPRESSED_RGBA_ASTC_10x6_KHR"; break; - case 0x93BA: return "GL_COMPRESSED_RGBA_ASTC_10x8_KHR"; break; - case 0x93BB: return "GL_COMPRESSED_RGBA_ASTC_10x10_KHR"; break; - case 0x93BC: return "GL_COMPRESSED_RGBA_ASTC_12x10_KHR"; break; - case 0x93BD: return "GL_COMPRESSED_RGBA_ASTC_12x12_KHR"; break; - case 0x93D0: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"; break; - case 0x93D1: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"; break; - case 0x93D2: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"; break; - case 0x93D3: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"; break; - case 0x93D4: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"; break; - case 0x93D5: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"; break; - case 0x93D6: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"; break; - case 0x93D7: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"; break; - case 0x93D8: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"; break; - case 0x93D9: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"; break; - case 0x93DA: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"; break; - case 0x93DB: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"; break; - case 0x93DC: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"; break; - case 0x93DD: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"; break; - default: return "GL_COMPRESSED_UNKNOWN"; break; - } -} -#endif // RLGL_SHOW_GL_DETAILS_INFO - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -// Get pixel data size in bytes (image or texture) -// NOTE: Size depends on pixel format -static int rlGetPixelDataSize(int width, int height, int format) -{ - int dataSize = 0; // Size in bytes - int bpp = 0; // Bits per pixel - - switch (format) - { - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: bpp = 8; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: bpp = 16; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: bpp = 32; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: bpp = 24; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32: bpp = 32; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: bpp = 32*3; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: bpp = 32*4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: bpp = 16; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: bpp = 16*3; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: bpp = 16*4; break; - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: bpp = 4; break; - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: bpp = 8; break; - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: bpp = 2; break; - default: break; - } - - dataSize = width*height*bpp/8; // Total data size in bytes - - // Most compressed formats works on 4x4 blocks, - // if texture is smaller, minimum dataSize is 8 or 16 - if ((width < 4) && (height < 4)) - { - if ((format >= RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) && (format < RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA)) dataSize = 8; - else if ((format >= RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA) && (format < RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA)) dataSize = 16; - } - - return dataSize; -} - -// Auxiliar math functions - -// Get identity matrix -static Matrix rlMatrixIdentity(void) -{ - Matrix result = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - return result; -} - -// Get two matrix multiplication -// NOTE: When multiplying matrices... the order matters! -static Matrix rlMatrixMultiply(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; - result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; - result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; - result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; - result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; - result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; - result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; - result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; - result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; - result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; - result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; - result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; - result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; - result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; - result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; - result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; - - return result; -} - -#endif // RLGL_IMPLEMENTATION diff --git a/third_party/raylib/larch64/libraylib.a b/third_party/raylib/larch64/libraylib.a deleted file mode 100644 index 2bb6f985d9f38d..00000000000000 --- a/third_party/raylib/larch64/libraylib.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fac99ffbab698b99a47019ff02ff839f7536c32996b5e7aa827ef4820b288212 -size 10630538 diff --git a/third_party/raylib/setup.sh b/third_party/raylib/setup.sh deleted file mode 100755 index 3e51185743bc4f..00000000000000 --- a/third_party/raylib/setup.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -cd $DIR - -ARCHNAME=$(uname -m) -if [ -f /TICI ]; then - ARCHNAME="larch64" -fi - -if [[ "$OSTYPE" == "darwin"* ]]; then - ARCHNAME="Darwin" -fi - -if [ ! -d raylib_repo ]; then - git clone https://github.com/raysan5/raylib.git raylib_repo -fi - -cd raylib_repo -git fetch --tags origin 5.0 -git checkout 5.0 - -git clean -xdff . -mkdir build -cd build -cmake .. -make -j$(nproc) - -INSTALL_DIR="$DIR/$ARCHNAME" -rm -rf $INSTALL_DIR -mkdir -p $INSTALL_DIR - -rm -rf $DIR/include -cp $DIR/raylib_repo/build/raylib/libraylib.a $INSTALL_DIR/ -cp -r $DIR/raylib_repo/build/raylib/include $DIR diff --git a/third_party/raylib/x86_64/libraylib.a b/third_party/raylib/x86_64/libraylib.a deleted file mode 100644 index 28aa5b21de73a0..00000000000000 --- a/third_party/raylib/x86_64/libraylib.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0c07c718e411baefd74fd761d18f18fcc681ccd606d477118acff96732d21791 -size 10233524 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so deleted file mode 100644 index a1c6fed9107b7d..00000000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fb3b1fd29d958e9a3a6625eac9fac9e7cd6eb40309b285ad973324761db0b4c9 -size 1202792 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so deleted file mode 100644 index 54c0c32e41ff53..00000000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:161a5d0bf7347465b53ae49690a38fbacf03d606ef204147b3b148a5f59188da -size 9008016 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so deleted file mode 100644 index 21542030263916..00000000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e0e66c12a1eb3b5b4b2b2694831ca51e5132818f400dad789adbcc30e0e0793 -size 14032 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so deleted file mode 100644 index 1d81abd3a5cfac..00000000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:784f2e80fa3534cf7934c5ecbbda37db633104380f2b41d896b4721ad6006eb2 -size 2420312 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so deleted file mode 100644 index 40e3d5af74980e..00000000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:33afe465e74bbe2c409350d2ca8e86cfadf050ceb8feac75a86adc19ff1f9c48 -size 26016 diff --git a/third_party/snpe/dsp/libcalculator_skel.so b/third_party/snpe/dsp/libcalculator_skel.so deleted file mode 100644 index 9e9e9221be9da2..00000000000000 --- a/third_party/snpe/dsp/libcalculator_skel.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7bee94d38195478ffdd0ce15292a2dfa7813377f4c3b7d99c270e05079d1746b -size 20828 diff --git a/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so deleted file mode 100644 index 3f1b7a8b8c4a9d..00000000000000 --- a/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4e040c87072aa915c47859c8c7f74076b98c6919b83ddd5dc4bb555870d586a7 -size 1813866 diff --git a/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so deleted file mode 100644 index aa42b5e830c26f..00000000000000 --- a/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:838bc58ac0094ba9593cf7c44ab6e8a94ae3dbbe176e320d9fbe86ceead53c5e -size 1817962 diff --git a/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so deleted file mode 100644 index 9423da1b94e388..00000000000000 --- a/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:77d025d59521e13e4ed012f0d9d2b684cdb858208d70426078df51219eaeb9bd -size 10098673 diff --git a/third_party/snpe/include/DiagLog/IDiagLog.hpp b/third_party/snpe/include/DiagLog/IDiagLog.hpp deleted file mode 100644 index 018b5672561c0b..00000000000000 --- a/third_party/snpe/include/DiagLog/IDiagLog.hpp +++ /dev/null @@ -1,84 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#ifndef __IDIAGLOG_HPP_ -#define __IDIAGLOG_HPP_ - -#include - -#include "DiagLog/Options.hpp" -#include "DlSystem/String.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl -{ -namespace DiagLog -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/// @brief . -/// -/// Interface for controlling logging for zdl components. - -class ZDL_EXPORT IDiagLog -{ -public: - - /// @brief . - /// - /// Sets the options after initialization occurs. - /// - /// @param[in] loggingOptions The options to set up diagnostic logging. - /// - /// @return False if the options could not be set. Ensure logging is not started. - virtual bool setOptions(const Options& loggingOptions) = 0; - - /// @brief . - /// - /// Gets the curent options for the diag logger. - /// - /// @return Diag log options object. - virtual Options getOptions() = 0; - - /// @brief . - /// - /// Allows for setting the log mask once diag logging has started - /// - /// @return True if the level was set successfully, false if a failure occurred. - virtual bool setDiagLogMask(const std::string& mask) = 0; - - /// @brief . - /// - /// Allows for setting the log mask once diag logging has started - /// - /// @return True if the level was set successfully, false if a failure occurred. - virtual bool setDiagLogMask(const zdl::DlSystem::String& mask) = 0; - - /// @brief . - /// - /// Enables logging for zdl components. - /// - /// Logging should be started prior to the instantiation of zdl components - /// to ensure all events are captured. - /// - /// @return False if diagnostic logging could not be started. - virtual bool start(void) = 0; - - /// @brief Disables logging for zdl components. - virtual bool stop(void) = 0; - - virtual ~IDiagLog() {}; -}; - -} // DiagLog namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif diff --git a/third_party/snpe/include/DiagLog/Options.hpp b/third_party/snpe/include/DiagLog/Options.hpp deleted file mode 100644 index 798fa3f1240a62..00000000000000 --- a/third_party/snpe/include/DiagLog/Options.hpp +++ /dev/null @@ -1,79 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#ifndef __DIAGLOG_OPTIONS_HPP_ -#define __DIAGLOG_OPTIONS_HPP_ - -#include -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl -{ -namespace DiagLog -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/// @brief . -/// -/// Options for setting up diagnostic logging for zdl components. -class ZDL_EXPORT Options -{ -public: - Options() : - DiagLogMask(""), - LogFileDirectory("diaglogs"), - LogFileName("DiagLog"), - LogFileRotateCount(20), - LogFileReplace(true) - { - // Solves the empty string problem with multiple std libs - DiagLogMask.reserve(1); - } - - /// @brief . - /// - /// Enables diag logging only on the specified area mask (DNN_RUNTIME=ON | OFF) - std::string DiagLogMask; - - /// @brief . - /// - /// The path to the directory where log files will be written. - /// The path may be relative or absolute. Relative paths are interpreted - /// from the current working directory. - /// Default value is "diaglogs" - std::string LogFileDirectory; - - /// @brief . - /// - //// The name used for log files. If this value is empty then BaseName will be - /// used as the default file name. - /// Default value is "DiagLog" - std::string LogFileName; - - /// @brief . - /// - /// The maximum number of log files to create. If set to 0 no log rotation - /// will be used and the log file name specified will be used each time, overwriting - /// any existing log file that may exist. - /// Default value is 20 - uint32_t LogFileRotateCount; - - /// @brief - /// - /// If the log file already exists, control whether it will be replaced - /// (existing contents truncated), or appended. - /// Default value is true - bool LogFileReplace; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // DiagLog namespace -} // zdl namespace - - -#endif diff --git a/third_party/snpe/include/DlContainer/IDlContainer.hpp b/third_party/snpe/include/DlContainer/IDlContainer.hpp deleted file mode 100644 index 4e29b39bb41eb8..00000000000000 --- a/third_party/snpe/include/DlContainer/IDlContainer.hpp +++ /dev/null @@ -1,191 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef ZEROTH_IDNC_CONTAINER_HPP -#define ZEROTH_IDNC_CONTAINER_HPP - -#include -#include -#include -#include -#include - -#include "DlSystem/ZdlExportDefine.hpp" -#include "DlSystem/String.hpp" - -namespace zdl { -namespace DlContainer { - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -class IDlContainer; -class dlc_error; - -/** - * The structure of a record in a DL container. - */ -struct ZDL_EXPORT DlcRecord -{ - /// Name of the record. - std::string name; - /// Byte blob holding the data for the record. - std::vector data; - - DlcRecord(); - DlcRecord( DlcRecord&& other ) - : name(std::move(other.name)) - , data(std::move(other.data)) - {} - DlcRecord(const std::string& new_name) - : name(new_name) - , data() - { - if(name.empty()) - { - name.reserve(1); - } - } - DlcRecord(const DlcRecord&) = delete; -}; - -// The maximum length of any record name. -extern const uint32_t RECORD_NAME_MAX_SIZE; -// The maximum size of the record payload (bytes). -extern const uint32_t RECORD_DATA_MAX_SIZE; -// The maximum number of records in an archive at one time. -extern const uint32_t ARCHIVE_MAX_RECORDS; - -/** - * Represents a container for a neural network model which can - * be used to load the model into the SNPE runtime. - */ -class ZDL_EXPORT IDlContainer -{ -public: - /** - * Initializes a container from a container archive file. - * - * @param[in] filename Container archive file path. - * - * @return A pointer to the initialized container - */ - static std::unique_ptr - open(const std::string &filename) noexcept; - - /** - * Initializes a container from a container archive file. - * - * @param[in] filename Container archive file path. - * - * @return A pointer to the initialized container - */ - static std::unique_ptr - open(const zdl::DlSystem::String &filename) noexcept; - - /** - * Initializes a container from a byte buffer. - * - * @param[in] buffer Byte buffer holding the contents of an archive - * file. - * - * @return A pointer to the initialized container - */ - static std::unique_ptr - open(const std::vector &buffer) noexcept; - - /** - * Initializes a container from a byte buffer. - * - * @param[in] buffer Byte buffer holding the contents of an archive - * file. - * - * @param[in] size Size of the byte buffer. - * - * @return A pointer to the initialized container - */ - static std::unique_ptr - open(const uint8_t* buffer, const size_t size) noexcept; - - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - - /** - * Get the record catalog for a container. - * - * @param[out] catalog Buffer that will hold the record names on - * return. - */ - virtual void getCatalog(std::set &catalog) const = 0; - - /** - * Get the record catalog for a container. - * - * @param[out] catalog Buffer that will hold the record names on - * return. - */ - virtual void getCatalog(std::set &catalog) const = 0; - - /** - * Get a record from a container by name. - * - * @param[in] name Name of the record to fetch. - * @param[out] record The passed in record will be populated with the - * record data on return. Note that the caller - * will own the data in the record and is - * responsible for freeing it if needed. - */ - virtual void getRecord(const std::string &name, DlcRecord &record) const = 0; - - /** - * Get a record from a container by name. - * - * @param[in] name Name of the record to fetch. - * @param[out] record The passed in record will be populated with the - * record data on return. Note that the caller - * will own the data in the record and is - * responsible for freeing it if needed. - */ - virtual void getRecord(const zdl::DlSystem::String &name, DlcRecord &record) const = 0; - - /** - * Save the container to an archive on disk. This function will save the - * container if the filename is different from the file that it was opened - * from, or if at least one record was modified since the container was - * opened. - * - * It will truncate any existing file at the target path. - * - * @param filename Container archive file path. - * - * @return indication of success/failure - */ - virtual bool save(const std::string &filename) = 0; - - /** - * Save the container to an archive on disk. This function will save the - * container if the filename is different from the file that it was opened - * from, or if at least one record was modified since the container was - * opened. - * - * It will truncate any existing file at the target path. - * - * @param filename Container archive file path. - * - * @return indication of success/failure - */ - virtual bool save (const zdl::DlSystem::String &filename) = 0; - - virtual ~IDlContainer() {} -}; - -} // ns DlContainer -} // ns zdl - - -#endif diff --git a/third_party/snpe/include/DlSystem/DlEnums.hpp b/third_party/snpe/include/DlSystem/DlEnums.hpp deleted file mode 100644 index c9b3ef970a2aaa..00000000000000 --- a/third_party/snpe/include/DlSystem/DlEnums.hpp +++ /dev/null @@ -1,234 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2014-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _DL_ENUMS_HPP_ -#define _DL_ENUMS_HPP_ - -#include "DlSystem/ZdlExportDefine.hpp" - - -namespace zdl { -namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * Enumeration of supported target runtimes. - */ -enum class Runtime_t -{ - /// Run the processing on Snapdragon CPU. - /// Data: float 32bit - /// Math: float 32bit - CPU_FLOAT32 = 0, - - /// Run the processing on the Adreno GPU. - /// Data: float 16bit - /// Math: float 32bit - GPU_FLOAT32_16_HYBRID = 1, - - /// Run the processing on the Hexagon DSP. - /// Data: 8bit fixed point Tensorflow style format - /// Math: 8bit fixed point Tensorflow style format - DSP_FIXED8_TF = 2, - - /// Run the processing on the Adreno GPU. - /// Data: float 16bit - /// Math: float 16bit - GPU_FLOAT16 = 3, - - /// Run the processing on Snapdragon AIX+HVX. - /// Data: 8bit fixed point Tensorflow style format - /// Math: 8bit fixed point Tensorflow style format - AIP_FIXED8_TF = 5, - AIP_FIXED_TF = AIP_FIXED8_TF, - - /// Default legacy enum to retain backward compatibility. - /// CPU = CPU_FLOAT32 - CPU = CPU_FLOAT32, - - /// Default legacy enum to retain backward compatibility. - /// GPU = GPU_FLOAT32_16_HYBRID - GPU = GPU_FLOAT32_16_HYBRID, - - /// Default legacy enum to retain backward compatibility. - /// DSP = DSP_FIXED8_TF - DSP = DSP_FIXED8_TF, - - /// Special value indicating the property is unset. - UNSET = -1 -}; - -/** - * Enumeration of runtime available check options. - */ -enum class RuntimeCheckOption_t -{ - /// Perform standard runtime available check - DEFAULT = 0, - /// Perform standard runtime available check - NORMAL_CHECK = 0, - /// Perform basic runtime available check, may be runtime specific - BASIC_CHECK = 1, - /// Perform unsignedPD runtime available check - UNSIGNEDPD_CHECK = 2, -}; - -/** - * Enumeration of various performance profiles that can be requested. - */ -enum class PerformanceProfile_t -{ - /// Run in a standard mode. - /// This mode will be deprecated in the future and replaced with BALANCED. - DEFAULT = 0, - /// Run in a balanced mode. - BALANCED = 0, - - /// Run in high performance mode - HIGH_PERFORMANCE = 1, - - /// Run in a power sensitive mode, at the expense of performance. - POWER_SAVER = 2, - - /// Use system settings. SNPE makes no calls to any performance related APIs. - SYSTEM_SETTINGS = 3, - - /// Run in sustained high performance mode - SUSTAINED_HIGH_PERFORMANCE = 4, - - /// Run in burst mode - BURST = 5, - - /// Run in lower clock than POWER_SAVER, at the expense of performance. - LOW_POWER_SAVER = 6, - - /// Run in higher clock and provides better performance than POWER_SAVER. - HIGH_POWER_SAVER = 7, - - /// Run in lower balanced mode - LOW_BALANCED = 8, -}; - -/** - * Enumeration of various profilngLevels that can be requested. - */ -enum class ProfilingLevel_t -{ - /// No profiling. - /// Collects no runtime stats in the DiagLog - OFF = 0, - - /// Basic profiling - /// Collects some runtime stats in the DiagLog - BASIC = 1, - - /// Detailed profiling - /// Collects more runtime stats in the DiagLog, including per-layer statistics - /// Performance may be impacted - DETAILED = 2, - - /// Moderate profiling - /// Collects more runtime stats in the DiagLog, no per-layer statistics - MODERATE = 3 -}; - -/** - * Enumeration of various execution priority hints. - */ -enum class ExecutionPriorityHint_t -{ - /// Normal priority - NORMAL = 0, - - /// Higher than normal priority - HIGH = 1, - - /// Lower priority - LOW = 2 - -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++*/ - -/** - * Enumeration that lists the supported image encoding formats. - */ -enum class ImageEncoding_t -{ - /// For unknown image type. Also used as a default value for ImageEncoding_t. - UNKNOWN = 0, - - /// The RGB format consists of 3 bytes per pixel: one byte for - /// Red, one for Green, and one for Blue. The byte ordering is - /// endian independent and is always in RGB byte order. - RGB = 1, - - /// The ARGB32 format consists of 4 bytes per pixel: one byte for - /// Red, one for Green, one for Blue, and one for the alpha channel. - /// The alpha channel is ignored. The byte ordering depends on the - /// underlying CPU. For little endian CPUs, the byte order is BGRA. - /// For big endian CPUs, the byte order is ARGB. - ARGB32 = 2, - - /// The RGBA format consists of 4 bytes per pixel: one byte for - /// Red, one for Green, one for Blue, and one for the alpha channel. - /// The alpha channel is ignored. The byte ordering is endian independent - /// and is always in RGBA byte order. - RGBA = 3, - - /// The GRAYSCALE format is for 8-bit grayscale. - GRAYSCALE = 4, - - /// NV21 is the Android version of YUV. The Chrominance is down - /// sampled and has a subsampling ratio of 4:2:0. Note that this - /// image format has 3 channels, but the U and V channels - /// are subsampled. For every four Y pixels there is one U and one V pixel. @newpage - NV21 = 5, - - /// The BGR format consists of 3 bytes per pixel: one byte for - /// Red, one for Green and one for Blue. The byte ordering is - /// endian independent and is always BGR byte order. - BGR = 6 -}; - -/** - * Enumeration that lists the supported LogLevels that can be set by users. - */ -enum class LogLevel_t -{ - /// Enumeration variable to be used by user to set logging level to FATAL. - LOG_FATAL = 0, - - /// Enumeration variable to be used by user to set logging level to ERROR. - LOG_ERROR = 1, - - /// Enumeration variable to be used by user to set logging level to WARN. - LOG_WARN = 2, - - /// Enumeration variable to be used by user to set logging level to INFO. - LOG_INFO = 3, - - /// Enumeration variable to be used by user to set logging level to VERBOSE. - LOG_VERBOSE = 4 -}; - -typedef enum : int -{ - UNSPECIFIED = 0, - FLOATING_POINT_32 = 1, - FLOATING_POINT_16 = 2, - FIXED_POINT_8 = 3, - FIXED_POINT_16 = 4 -} IOBufferDataType_t; - -}} // namespaces end - - -#endif diff --git a/third_party/snpe/include/DlSystem/DlError.hpp b/third_party/snpe/include/DlSystem/DlError.hpp deleted file mode 100644 index 57592f01baed27..00000000000000 --- a/third_party/snpe/include/DlSystem/DlError.hpp +++ /dev/null @@ -1,259 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _DL_ERROR_HPP_ -#define _DL_ERROR_HPP_ - -#include -#include // numeric_limits - -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl { -namespace DlSystem { - -// clang and arm gcc different in how ZDL_EXPORT is used with enum class -#if !defined (__clang__) -enum class ErrorCode : uint32_t ZDL_EXPORT { -#else -enum class ZDL_EXPORT ErrorCode : uint32_t { -#endif // ARM64V8A - NONE = 0, - - // System config errors - SNPE_CONFIG_MISSING_PARAM = 100, - SNPE_CONFIG_INVALID_PARAM = 101, - SNPE_CONFIG_MISSING_FILE = 102, - SNPE_CONFIG_NNCONFIG_NOT_SET = 103, - SNPE_CONFIG_NNCONFIG_INVALID = 104, - SNPE_CONFIG_WRONG_INPUT_NAME = 105, - SNPE_CONFIG_INCORRECT_INPUT_DIMENSIONS = 106, - SNPE_CONFIG_DIMENSIONS_MODIFICATION_NOT_SUPPORTED = 107, - SNPE_CONFIG_BOTH_OUTPUT_LAYER_TENSOR_NAMES_SET = 108, - - SNPE_CONFIG_NNCONFIG_ONLY_TENSOR_SUPPORTED = 120, - SNPE_CONFIG_NNCONFIG_ONLY_USER_BUFFER_SUPPORTED = 121, - - // DlSystem errors - SNPE_DLSYSTEM_MISSING_BUFFER = 200, - SNPE_DLSYSTEM_TENSOR_CAST_FAILED = 201, - SNPE_DLSYSTEM_FIXED_POINT_PARAM_INVALID = 202, - SNPE_DLSYSTEM_SIZE_MISMATCH = 203, - SNPE_DLSYSTEM_NAME_NOT_FOUND = 204, - SNPE_DLSYSTEM_VALUE_MISMATCH = 205, - SNPE_DLSYSTEM_INSERT_FAILED = 206, - SNPE_DLSYSTEM_TENSOR_FILE_READ_FAILED = 207, - SNPE_DLSYSTEM_DIAGLOG_FAILURE = 208, - SNPE_DLSYSTEM_LAYER_NOT_SET = 209, - SNPE_DLSYSTEM_WRONG_NUMBER_INPUT_BUFFERS = 210, - SNPE_DLSYSTEM_RUNTIME_TENSOR_SHAPE_MISMATCH = 211, - SNPE_DLSYSTEM_TENSOR_MISSING = 212, - SNPE_DLSYSTEM_TENSOR_ITERATION_UNSUPPORTED = 213, - SNPE_DLSYSTEM_BUFFER_MANAGER_MISSING = 214, - SNPE_DLSYSTEM_RUNTIME_BUFFER_SOURCE_UNSUPPORTED = 215, - SNPE_DLSYSTEM_BUFFER_CAST_FAILED = 216, - SNPE_DLSYSTEM_WRONG_TRANSITION_TYPE = 217, - SNPE_DLSYSTEM_LAYER_ALREADY_REGISTERED = 218, - SNPE_DLSYSTEM_TENSOR_DIM_INVALID = 219, - - SNPE_DLSYSTEM_BUFFERENCODING_UNKNOWN = 240, - SNPE_DLSYSTEM_BUFFER_INVALID_PARAM = 241, - - // DlContainer errors - SNPE_DLCONTAINER_MODEL_PARSING_FAILED = 300, - SNPE_DLCONTAINER_UNKNOWN_LAYER_CODE = 301, - SNPE_DLCONTAINER_MISSING_LAYER_PARAM = 302, - SNPE_DLCONTAINER_LAYER_PARAM_NOT_SUPPORTED = 303, - SNPE_DLCONTAINER_LAYER_PARAM_INVALID = 304, - SNPE_DLCONTAINER_TENSOR_DATA_MISSING = 305, - SNPE_DLCONTAINER_MODEL_LOAD_FAILED = 306, - SNPE_DLCONTAINER_MISSING_RECORDS = 307, - SNPE_DLCONTAINER_INVALID_RECORD = 308, - SNPE_DLCONTAINER_WRITE_FAILURE = 309, - SNPE_DLCONTAINER_READ_FAILURE = 310, - SNPE_DLCONTAINER_BAD_CONTAINER = 311, - SNPE_DLCONTAINER_BAD_DNN_FORMAT_VERSION = 312, - SNPE_DLCONTAINER_UNKNOWN_AXIS_ANNOTATION = 313, - SNPE_DLCONTAINER_UNKNOWN_SHUFFLE_TYPE = 314, - SNPE_DLCONTAINER_TEMP_FILE_FAILURE = 315, - - // Network errors - SNPE_NETWORK_EMPTY_NETWORK = 400, - SNPE_NETWORK_CREATION_FAILED = 401, - SNPE_NETWORK_PARTITION_FAILED = 402, - SNPE_NETWORK_NO_OUTPUT_DEFINED = 403, - SNPE_NETWORK_MISMATCH_BETWEEN_NAMES_AND_DIMS = 404, - SNPE_NETWORK_MISSING_INPUT_NAMES = 405, - SNPE_NETWORK_MISSING_OUTPUT_NAMES = 406, - SNPE_NETWORK_EXECUTION_FAILED = 407, - - // Host runtime errors - SNPE_HOST_RUNTIME_TARGET_UNAVAILABLE = 500, - - // CPU runtime errors - SNPE_CPU_LAYER_NOT_SUPPORTED = 600, - SNPE_CPU_LAYER_PARAM_NOT_SUPPORTED = 601, - SNPE_CPU_LAYER_PARAM_INVALID = 602, - SNPE_CPU_LAYER_PARAM_COMBINATION_INVALID = 603, - SNPE_CPU_BUFFER_NOT_FOUND = 604, - SNPE_CPU_NETWORK_NOT_SUPPORTED = 605, - SNPE_CPU_UDO_OPERATION_FAILED = 606, - - // CPU fixed-point runtime errors - SNPE_CPU_FXP_LAYER_NOT_SUPPORTED = 700, - SNPE_CPU_FXP_LAYER_PARAM_NOT_SUPPORTED = 701, - SNPE_CPU_FXP_LAYER_PARAM_INVALID = 702, - - // GPU runtime errors - SNPE_GPU_LAYER_NOT_SUPPORTED = 800, - SNPE_GPU_LAYER_PARAM_NOT_SUPPORTED = 801, - SNPE_GPU_LAYER_PARAM_INVALID = 802, - SNPE_GPU_LAYER_PARAM_COMBINATION_INVALID = 803, - SNPE_GPU_KERNEL_COMPILATION_FAILED = 804, - SNPE_GPU_CONTEXT_NOT_SET = 805, - SNPE_GPU_KERNEL_NOT_SET = 806, - SNPE_GPU_KERNEL_PARAM_INVALID = 807, - SNPE_GPU_OPENCL_CHECK_FAILED = 808, - SNPE_GPU_OPENCL_FUNCTION_ERROR = 809, - SNPE_GPU_BUFFER_NOT_FOUND = 810, - SNPE_GPU_TENSOR_DIM_INVALID = 811, - SNPE_GPU_MEMORY_FLAGS_INVALID = 812, - SNPE_GPU_UNEXPECTED_NUMBER_OF_IO = 813, - SNPE_GPU_LAYER_PROXY_ERROR = 814, - SNPE_GPU_BUFFER_IN_USE = 815, - SNPE_GPU_BUFFER_MODIFICATION_ERROR = 816, - SNPE_GPU_DATA_ARRANGEMENT_INVALID = 817, - SNPE_GPU_UDO_OPERATION_FAILED = 818, - // DSP runtime errors - SNPE_DSP_LAYER_NOT_SUPPORTED = 900, - SNPE_DSP_LAYER_PARAM_NOT_SUPPORTED = 901, - SNPE_DSP_LAYER_PARAM_INVALID = 902, - SNPE_DSP_LAYER_PARAM_COMBINATION_INVALID = 903, - SNPE_DSP_STUB_NOT_PRESENT = 904, - SNPE_DSP_LAYER_NAME_TRUNCATED = 905, - SNPE_DSP_LAYER_INPUT_BUFFER_NAME_TRUNCATED = 906, - SNPE_DSP_LAYER_OUTPUT_BUFFER_NAME_TRUNCATED = 907, - SNPE_DSP_RUNTIME_COMMUNICATION_ERROR = 908, - SNPE_DSP_RUNTIME_INVALID_PARAM_ERROR = 909, - SNPE_DSP_RUNTIME_SYSTEM_ERROR = 910, - SNPE_DSP_RUNTIME_CRASHED_ERROR = 911, - SNPE_DSP_BUFFER_SIZE_ERROR = 912, - SNPE_DSP_UDO_EXECUTE_ERROR = 913, - SNPE_DSP_UDO_LIB_NOT_REGISTERED_ERROR = 914, - SNPE_DSP_UDO_INVALID_QUANTIZATION_TYPE_ERROR = 915, - SNPE_DSP_RUNTIME_INVALID_RPC_DRIVER = 916, - SNPE_DSP_RUNTIME_RPC_PERMISSION_ERROR = 917, - SNPE_DSP_RUNTIME_DSP_FILE_OPEN_ERROR = 918, - - // Model validataion errors - SNPE_MODEL_VALIDATION_LAYER_NOT_SUPPORTED = 1000, - SNPE_MODEL_VALIDATION_LAYER_PARAM_NOT_SUPPORTED = 1001, - SNPE_MODEL_VALIDATION_LAYER_PARAM_INVALID = 1002, - SNPE_MODEL_VALIDATION_LAYER_PARAM_MISSING = 1003, - SNPE_MODEL_VALIDATION_LAYER_PARAM_COMBINATION_INVALID = 1004, - SNPE_MODEL_VALIDATION_LAYER_ORDERING_INVALID = 1005, - SNPE_MODEL_VALIDATION_INVALID_CONSTRAINT = 1006, - SNPE_MODEL_VALIDATION_MISSING_BUFFER = 1007, - SNPE_MODEL_VALIDATION_BUFFER_REUSE_NOT_SUPPORTED = 1008, - SNPE_MODEL_VALIDATION_LAYER_COULD_NOT_BE_ASSIGNED = 1009, - SNPE_MODEL_VALIDATION_UDO_LAYER_FAILED = 1010, - - // UDL errors - SNPE_UDL_LAYER_EMPTY_UDL_NETWORK = 1100, - SNPE_UDL_LAYER_PARAM_INVALID = 1101, - SNPE_UDL_LAYER_INSTANCE_MISSING = 1102, - SNPE_UDL_LAYER_SETUP_FAILED = 1103, - SNPE_UDL_EXECUTE_FAILED = 1104, - SNPE_UDL_BUNDLE_INVALID = 1105, - SNPE_UDO_REGISTRATION_FAILED = 1106, - SNPE_UDO_GET_PACKAGE_FAILED = 1107, - SNPE_UDO_GET_IMPLEMENTATION_FAILED = 1108, - - // Dependent library errors - SNPE_STD_LIBRARY_ERROR = 1200, - - // Unknown exception (catch (...)), Has no component attached to this - SNPE_UNKNOWN_EXCEPTION = 1210, - - // Storage Errors - SNPE_STORAGE_INVALID_KERNEL_REPO = 1300, - - // AIP runtime errors - SNPE_AIP_LAYER_NOT_SUPPORTED = 1400, - SNPE_AIP_LAYER_PARAM_NOT_SUPPORTED = 1401, - SNPE_AIP_LAYER_PARAM_INVALID = 1402, - SNPE_AIP_LAYER_PARAM_COMBINATION_INVALID = 1403, - SNPE_AIP_STUB_NOT_PRESENT = 1404, - SNPE_AIP_LAYER_NAME_TRUNCATED = 1405, - SNPE_AIP_LAYER_INPUT_BUFFER_NAME_TRUNCATED = 1406, - SNPE_AIP_LAYER_OUTPUT_BUFFER_NAME_TRUNCATED = 1407, - SNPE_AIP_RUNTIME_COMMUNICATION_ERROR = 1408, - SNPE_AIP_RUNTIME_INVALID_PARAM_ERROR = 1409, - SNPE_AIP_RUNTIME_SYSTEM_ERROR = 1410, - SNPE_AIP_RUNTIME_TENSOR_MISSING = 1411, - SNPE_AIP_RUNTIME_TENSOR_SHAPE_MISMATCH = 1412, - SNPE_AIP_RUNTIME_BAD_AIX_RECORD = 1413, - - // DlCaching errors - SNPE_DLCACHING_INVALID_METADATA = 1500, - SNPE_DLCACHING_INVALID_INITBLOB = 1501, - - // Infrastructure Errors - SNPE_INFRA_CLUSTERMGR_INSTANCE_INVALID = 1600, - SNPE_INFRA_CLUSTERMGR_EXECUTE_SYNC_FAILED = 1601, - - // Memory Errors - SNPE_MEMORY_CORRUPTION_ERROR = 1700 - -}; - - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * Returns the error code of the last error encountered. - * - * @return The error code. - * - * @note The returned error code is significant only when the return - * value of the call indicated an error. - */ -ZDL_EXPORT ErrorCode getLastErrorCode(); - -/** - * Returns the error string of the last error encountered. - * - * @return The error string. - * - * @note The returned error string is significant only when the return - * value of the call indicated an error. - */ -ZDL_EXPORT const char* getLastErrorString(); - -/** - * Returns the info string of the last error encountered. - */ -ZDL_EXPORT const char* getLastInfoString(); - -/** - * Returns the uint32_t representation of the error code enum. - * - * @param[in] code The error code to be converted. - * - * @return uint32_t representation of the error code. - */ -ZDL_EXPORT uint32_t enumToUInt32(zdl::DlSystem::ErrorCode code); - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // DlSystem -} // zdl - -#endif // _DL_ERROR_HPP_ - diff --git a/third_party/snpe/include/DlSystem/DlOptional.hpp b/third_party/snpe/include/DlSystem/DlOptional.hpp deleted file mode 100644 index 4f83e6b4e417fc..00000000000000 --- a/third_party/snpe/include/DlSystem/DlOptional.hpp +++ /dev/null @@ -1,225 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2016, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _DL_SYSTEM_OPTIONAL_HPP_ -#define _DL_SYSTEM_OPTIONAL_HPP_ - -#include -#include -#include - -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl { -namespace DlSystem { - -template - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * Class to manage a value that may or may not exist. The boolean value - * of the Optional class is true if the object contains a value and false - * if it does not contain a value. - * - * The class must be evaluated and confirmed as true (containing a value) - * before being dereferenced. - */ -class ZDL_EXPORT Optional final { -public: - enum class LIFECYCLE { - NONE = 0, - REFERENCE_OWNED = 1, - POINTER_OWNED = 2, - POINTER_NOT_OWNED = 3 - }; - - struct ReferenceCount { - size_t count = 0; - - void increment() { count++; } - - size_t decrement() { - if (count > 0) { - count--; - } - return count; - } - }; - - using U = typename std::remove_pointer::type; - - /** - * The default constructor is set to not have any value, and is - * therefore evaluated as false. - */ - // Do not explicit it so we can return {} - Optional() { - m_Type = LIFECYCLE::NONE; - } - - /** - * Construct an Optional class using an object. - * @param[in] Reference to an object v - * @param[out] Optional instance of object v - */ - template - Optional (const T& v, typename std::enable_if::value>::type* = 0) - : m_Type(LIFECYCLE::REFERENCE_OWNED) { - try { - m_StoragePtr = new T(v); - } catch (...) { - m_StoragePtr = nullptr; - m_Type = LIFECYCLE::NONE; - } - } - - template - Optional(U* v, LIFECYCLE type, typename std::enable_if::value>::type* = 0) - : m_Type(type) { - switch (m_Type) { - case LIFECYCLE::POINTER_OWNED: - m_StoragePtr = v; - m_Count = new ReferenceCount(); - m_Count->increment(); - break; - case LIFECYCLE::POINTER_NOT_OWNED: - m_StoragePtr = v; - break; - case LIFECYCLE::REFERENCE_OWNED: - throw std::bad_exception(); - case LIFECYCLE::NONE: - break; - } - } - - Optional(const Optional &other) : m_Type(other.m_Type), m_Count(other.m_Count) { - if (isReference()) { - m_StoragePtr = new U(*other.m_StoragePtr); - } else if (isPointer()) { - m_StoragePtr = other.m_StoragePtr; - if (isOwned()) { - m_Count->increment(); - } - } - } - - Optional& operator=(const Optional& other) noexcept { - Optional tmp(other); - swap(std::move(tmp)); - return *this; - } - - Optional(Optional&& other) noexcept { - swap(std::move(other)); - } - - Optional& operator=(Optional&& other) noexcept { - swap(std::move(other)); - return *this; - } - - ~Optional() { - if (isOwned()) { - if (isReference() || (isPointer() && m_Count->decrement() == 0)) { - delete m_StoragePtr; - delete m_Count; - } - } - } - - /** - * Boolean value of Optional class is only true when there exists a value. - */ - operator bool() const noexcept { return isValid(); } - - bool operator!() const noexcept { return !isValid(); } - - /** - * Get reference of Optional object - * @warning User must validate Optional has value before. - */ - const T& operator*() { return this->GetReference(); } - - /** - * Get reference of Optional object - * @warning User must validate Optional has value before. - */ - const T& operator*() const { return this->GetReference(); } - - operator T&() { return this->GetReference(); } - - T operator->() { - T self = this->GetReference(); - return self; - } -private: - void swap(Optional&& other) { - m_Type = other.m_Type; - m_StoragePtr = other.m_StoragePtr; - m_Count = other.m_Count; - - other.m_Type = LIFECYCLE::NONE; - other.m_StoragePtr = nullptr; - other.m_Count = nullptr; - } - - template - typename std::enable_if::value, const Q&>::type GetReference() const noexcept { - if (!isReference()) std::terminate(); - return *static_cast(m_StoragePtr); - } - - template - typename std::enable_if::value, const Q&>::type GetReference() const noexcept { - if (!isPointer()) std::terminate(); - return static_cast(m_StoragePtr); - } - - template - typename std::enable_if::value, Q&>::type GetReference() noexcept { - if (!isReference()) std::terminate(); - return *m_StoragePtr; - } - - template - typename std::enable_if::value, Q&>::type GetReference() noexcept { - if (!isPointer()) std::terminate(); - return m_StoragePtr; - } - - bool isPointer() const { - return m_Type == LIFECYCLE::POINTER_OWNED || m_Type == LIFECYCLE::POINTER_NOT_OWNED; - } - - bool isOwned() const { - return m_Type == LIFECYCLE::REFERENCE_OWNED || m_Type == LIFECYCLE::POINTER_OWNED; - } - - bool isReference() const { - return m_Type == LIFECYCLE::REFERENCE_OWNED; - } - - bool isValid() const { - return m_Type != LIFECYCLE::NONE; - } - - U* m_StoragePtr = nullptr; - LIFECYCLE m_Type; - ReferenceCount *m_Count = nullptr; -}; - -} // ns DlSystem -} // ns zdl - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // _DL_SYSTEM_OPTIONAL_HPP_ diff --git a/third_party/snpe/include/DlSystem/DlVersion.hpp b/third_party/snpe/include/DlSystem/DlVersion.hpp deleted file mode 100644 index beb8d75f218caf..00000000000000 --- a/third_party/snpe/include/DlSystem/DlVersion.hpp +++ /dev/null @@ -1,78 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2014-2015 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - - -#ifndef _DL_VERSION_HPP_ -#define _DL_VERSION_HPP_ - -#include "ZdlExportDefine.hpp" -#include -#include -#include "DlSystem/String.hpp" - - -namespace zdl { -namespace DlSystem -{ - class Version_t; -}} - - -namespace zdl { namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * A class that contains the different portions of a version number. - */ -class ZDL_EXPORT Version_t -{ -public: - /// Holds the major version number. Changes in this value indicate - /// major changes that break backward compatibility. - int32_t Major; - - /// Holds the minor version number. Changes in this value indicate - /// minor changes made to library that are backwards compatible - /// (such as additions to the interface). - int32_t Minor; - - /// Holds the teeny version number. Changes in this value indicate - /// changes such as bug fixes and patches made to the library that - /// do not affect the interface. - int32_t Teeny; - - /// This string holds information about the build version. - /// - std::string Build; - - static zdl::DlSystem::Version_t fromString(const std::string &stringValue); - - static zdl::DlSystem::Version_t fromString(const zdl::DlSystem::String &stringValue); - - /** - * @brief Returns a string in the form Major.Minor.Teeny.Build - * - * @return A formatted string holding the version information. - */ - const std::string toString() const; - - /** - * @brief Returns a string in the form Major.Minor.Teeny.Build - * - * @return A formatted string holding the version information. - */ - const zdl::DlSystem::String asString() const; -}; - -}} - -/** @} */ /* end_addtogroup c_plus_plus_apis */ - -#endif diff --git a/third_party/snpe/include/DlSystem/IBufferAttributes.hpp b/third_party/snpe/include/DlSystem/IBufferAttributes.hpp deleted file mode 100644 index f893e0a2370880..00000000000000 --- a/third_party/snpe/include/DlSystem/IBufferAttributes.hpp +++ /dev/null @@ -1,86 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2017-2019 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _IBUFFER_ATTRIBUTES_HPP -#define _IBUFFER_ATTRIBUTES_HPP -#include "IUserBuffer.hpp" -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" - -namespace zdl { - namespace DlSystem { - class UserBufferEncoding; - } -} - -namespace zdl { -namespace DlSystem { - -/** - * @brief IBufferAttributes returns a buffer's dimension and alignment - * requirements, along with info on its encoding type - */ -class ZDL_EXPORT IBufferAttributes { -public: - - /** - * @brief Gets the buffer's element size, in bytes - * - * This can be used to compute the memory size required - * to back this buffer. - * - * @return Element size, in bytes - */ - virtual size_t getElementSize() const noexcept = 0; - - /** - * @brief Gets the element's encoding type - * - * @return encoding type - */ - virtual zdl::DlSystem::UserBufferEncoding::ElementType_t getEncodingType() const noexcept = 0; - - /** - * @brief Gets the number of elements in each dimension - * - * @return Dimension size, in terms of number of elements - */ - virtual const TensorShape getDims() const noexcept = 0; - - /** - * @brief Gets the alignment requirement of each dimension - * - * Alignment per each dimension is expressed as an multiple, for - * example, if one particular dimension can accept multiples of 8, - * the alignment will be 8. - * - * @return Alignment in each dimension, in terms of multiple of - * number of elements - */ - virtual const TensorShape getAlignments() const noexcept = 0; - - /** - * @brief Gets the buffer encoding returned from the network responsible - * for generating this buffer. Depending on the encoding type, this will - * be an instance of an encoding type specific derived class. - * - * @return Derived user buffer encoding object. - */ - virtual zdl::DlSystem::UserBufferEncoding* getEncoding() const noexcept = 0; - - virtual ~IBufferAttributes() {} -}; - - - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} -} - -#endif diff --git a/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp b/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp deleted file mode 100644 index ac33c84af81198..00000000000000 --- a/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp +++ /dev/null @@ -1,127 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2021-2022 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - - -#ifndef DL_SYSTEM_IOBUFFER_DATATYPE_MAP_HPP -#define DL_SYSTEM_IOBUFFER_DATATYPE_MAP_HPP - -#include -#include -#include "DlSystem/DlEnums.hpp" - -namespace DlSystem -{ - // Forward declaration of IOBufferDataTypeMapImpl implementation. - class IOBufferDataTypeMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * The IoBufferDataTypeMap class definition - */ -class ZDL_EXPORT IOBufferDataTypeMap final -{ -public: - - /** - * @brief . - * - * Creates a new Buffer Data type map - * - */ - IOBufferDataTypeMap(); - - /** - * @brief Adds a name and the corresponding buffer data type - * to the map - * - * @param[name] name The name of the buffer - * @param[bufferDataType] buffer Data Type of the buffer - * - * @note If a buffer with the same name already exists, no new - * buffer is added. - */ - void add(const char* name, zdl::DlSystem::IOBufferDataType_t bufferDataType); - - /** - * @brief Removes a buffer name from the map - * - * @param[name] name The name of the buffer - * - */ - void remove(const char* name); - - /** - * @brief Returns the type of the named buffer - * - * @param[name] name The name of the buffer - * - * @return The type of the buffer, or UNSPECIFIED if the buffer does not exist - * - */ - zdl::DlSystem::IOBufferDataType_t getBufferDataType(const char* name); - - /** - * @brief Returns the type of the first buffer - * - * @return The type of the first buffer, or UNSPECIFIED if the map is empty. - * - */ - zdl::DlSystem::IOBufferDataType_t getBufferDataType(); - - /** - * @brief Returns the size of the buffer type map. - * - * @return The size of the map - * - */ - size_t size(); - - /** - * @brief Checks the existence of the named buffer in the map - * - * @return True if the named buffer exists, false otherwise. - * - */ - bool find(const char* name); - - /** - * @brief Resets the map - * - */ - void clear(); - - /** - * @brief Checks whether the map is empty - * - * @return True if the map is empty, false otherwise. - * - */ - bool empty(); - - /** - * @brief Destroys the map - * - */ - ~IOBufferDataTypeMap(); - -private: - std::shared_ptr<::DlSystem::IOBufferDataTypeMapImpl> m_IOBufferDataTypeMapImpl; -}; -} - -} -#endif diff --git a/third_party/snpe/include/DlSystem/ITensor.hpp b/third_party/snpe/include/DlSystem/ITensor.hpp deleted file mode 100644 index 2f006c857fc442..00000000000000 --- a/third_party/snpe/include/DlSystem/ITensor.hpp +++ /dev/null @@ -1,146 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _ITENSOR_HPP_ -#define _ITENSOR_HPP_ - -#include "ITensorItr.hpp" -#include "ITensorItrImpl.hpp" -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" -#include -#include -#include - -namespace zdl { -namespace DlSystem -{ - class ITensor; -}} - -namespace zdl { namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * Represents a tensor which holds n-dimensional data. It is important to - * understand how the tensor data is represented in memory - * relative to the tensor dimensions. Tensors store data in - * memory in row-major order (i.e. the last tensor dimension is - * the fastest varying one). For example, if you have a two - * dimensional tensor with 3 rows and 2 columns (i.e. the tensor - * dimensions are 3,2 as returned in tensor dimension vectors) - * with the following data in terms rows and columns: - * - * | 1 2 |
- * | 3 4 |
- * | 5 6 |
- * - * This data would be stored in memory as 1,2,3,4,5,6. - */ -class ZDL_EXPORT ITensor -{ -public: - - typedef zdl::DlSystem::ITensorItr iterator; - typedef zdl::DlSystem::ITensorItr const_iterator; - - virtual ~ITensor() {} - - /** - * Returns a tensor iterator pointing to the beginning - * of the data in the tensor. - * - * @return A tensor iterator that points to the first data - * element in the tensor. - */ - virtual iterator begin() = 0; - - /** - * Returns the const version of a tensor iterator - * pointing to the beginning of the data in the tensor. - * - * @return A tensor const iterator that points to the first data - * element in the tensor. - */ - virtual const_iterator cbegin() const = 0; - - /** - * Returns a tensor iterator pointing to the end of the - * data in the tensor. This tensor should not be - * dereferenced. - * - * @return A tensor iterator that points to the end of the data - * (one past the last element) in the tensor. - */ - virtual iterator end() = 0; - - /** - * Returns the const version of a tensor iterator - * pointing to the end of the data in the tensor. This - * tensor should not be dereferenced. - * - * @return A tensor const iterator that points to the end of the - * data (one past the last element) in the tensor. - */ - virtual const_iterator cend() const = 0; - - /** - * @brief Gets the shape of this tensor. - * - * The last element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying dimension, etc. - * - * @return A shape class holding the tensor dimensions. - */ - virtual TensorShape getShape() const = 0; - - /** - * Returns the element size of the data in the tensor - * (discounting strides). This is how big a buffer would - * need to be to hold the tensor data contiguously in - * memory. - * - * @return The size of the tensor (in elements). - */ - virtual size_t getSize() const = 0; - - /** - * @brief Serializes the tensor to an output stream. - * - * @param[in] output The output stream to which to write the tensor - * - * @throw std::runtime_error If the stream is ever in a bad - * state before the tensor is fully serialized. - */ - virtual void serialize(std::ostream &output) const = 0; - - friend iterator; - friend const_iterator; - - virtual bool isQuantized() {return false;} - virtual float GetDelta() {return NAN;}; - virtual float GetOffset() {return NAN;}; - -protected: - - /** - * Returns the tensor iterator implementation. - * - * @return A pointer to the tensor iterator implementation. - */ - virtual std::unique_ptr<::DlSystem::ITensorItrImpl> getItrImpl() const = 0; -}; - -}} - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif diff --git a/third_party/snpe/include/DlSystem/ITensorFactory.hpp b/third_party/snpe/include/DlSystem/ITensorFactory.hpp deleted file mode 100644 index 57d2c8ea992375..00000000000000 --- a/third_party/snpe/include/DlSystem/ITensorFactory.hpp +++ /dev/null @@ -1,92 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015-2016 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _ITENSOR_FACTORY_HPP -#define _ITENSOR_FACTORY_HPP - -#include "ITensor.hpp" -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" -#include - -namespace zdl { - namespace DlSystem - { - class ITensor; - class TensorShape; - } -} - -namespace zdl { namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * Factory interface class to create ITensor objects. - */ -class ZDL_EXPORT ITensorFactory -{ -public: - virtual ~ITensorFactory() = default; - - /** - * Creates a new ITensor with uninitialized data. - * - * The strides for the tensor will match the tensor dimensions - * (i.e., the tensor data is contiguous in memory). - * - * @param[in] shape The dimensions for the tensor in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - * @return A pointer to the created tensor or nullptr if creating failed. - */ - virtual std::unique_ptr - createTensor(const TensorShape &shape) noexcept = 0; - - /** - * Creates a new ITensor by loading it from a file. - * - * @param[in] input The input stream from which to read the tensor - * data. - * - * @return A pointer to the created tensor or nullptr if creating failed. - * - */ - virtual std::unique_ptr createTensor(std::istream &input) noexcept = 0; - - /** - * Create a new ITensor with specific data. - * (i.e. the tensor data is contiguous in memory). This tensor is - * primarily used to create a tensor where tensor size can't be - * computed directly from dimension. One such example is - * NV21-formatted image, or any YUV formatted image - * - * @param[in] shape The dimensions for the tensor in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - * @param[in] data The actual data with which the Tensor object is filled. - * - * @param[in] dataSize The size of data - * - * @return A pointer to the created tensor - */ - virtual std::unique_ptr - createTensor(const TensorShape &shape, const unsigned char *data, size_t dataSize) noexcept = 0; -}; - -}} - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif diff --git a/third_party/snpe/include/DlSystem/ITensorItr.hpp b/third_party/snpe/include/DlSystem/ITensorItr.hpp deleted file mode 100644 index 4ce12a9f113acb..00000000000000 --- a/third_party/snpe/include/DlSystem/ITensorItr.hpp +++ /dev/null @@ -1,182 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _ITENSOR_ITR_HPP_ -#define _ITENSOR_ITR_HPP_ - -#include "ZdlExportDefine.hpp" -#include "ITensorItrImpl.hpp" - -#include -#include -#include - -namespace zdl { -namespace DlSystem -{ - template class ITensorItr; - class ITensor; - void ZDL_EXPORT fill(ITensorItr first, ITensorItr end, float val); - template OutItr ZDL_EXPORT copy(InItr first, InItr last, OutItr result) - { - return std::copy(first, last, result); - } -}} -namespace DlSystem -{ - class ITensorItrImpl; -} - -namespace zdl { namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * A bidirectional iterator (with limited random access - * capabilities) for the zdl::DlSystem::ITensor class. - * - * This is a standard bidrectional iterator and is compatible - * with standard algorithm functions that operate on bidirectional - * access iterators (e.g., std::copy, std::fill, etc.). It uses a - * template parameter to create const and non-const iterators - * from the same code. Iterators are easiest to declare via the - * typedefs iterator and const_iterator in the ITensor class - * (e.g., zdl::DlSystem::ITensor::iterator). - * - * Note that if the tensor the iterator is traversing was - * created with nondefault (i.e., nontrivial) strides, the - * iterator will obey the strides when traversing the tensor - * data. - * - * Also note that nontrivial strides dramatically affect the - * performance of the iterator (on the order of 20x slower). - */ -template -class ZDL_EXPORT ITensorItr : public std::iterator -{ -public: - - typedef typename std::conditional::type VALUE_REF; - - ITensorItr() = delete; - virtual ~ITensorItr() {} - - ITensorItr(std::unique_ptr<::DlSystem::ITensorItrImpl> impl, - bool isTrivial = false, - float* data = nullptr) - : m_Impl(impl->clone()) - , m_IsTrivial(isTrivial) - , m_Data(data) - , m_DataStart(data) {} - - ITensorItr(const ITensorItr& itr) - : m_Impl(itr.m_Impl->clone()), - m_IsTrivial(itr.m_IsTrivial), - m_Data(itr.m_Data), - m_DataStart(itr.m_DataStart) {} - - zdl::DlSystem::ITensorItr& operator=(const ITensorItr& other) - { - if (this == &other) return *this; - m_Impl = std::move(other.m_Impl->clone()); - m_IsTrivial = other.m_IsTrivial; - m_Data = other.m_Data; - m_DataStart = other.m_DataStart; - return *this; - } - - inline zdl::DlSystem::ITensorItr& operator++() - { - if (m_IsTrivial) m_Data++; else m_Impl->increment(); - return *this; - } - inline zdl::DlSystem::ITensorItr operator++(int) - { - ITensorItr tmp(*this); - operator++(); - return tmp; - } - inline zdl::DlSystem::ITensorItr& operator--() - { - if (m_IsTrivial) m_Data--; else m_Impl->decrement(); - return *this; - } - inline zdl::DlSystem::ITensorItr operator--(int) - { - ITensorItr tmp(*this); - operator--(); - return tmp; - } - inline zdl::DlSystem::ITensorItr& operator+=(int rhs) - { - if (m_IsTrivial) m_Data += rhs; else m_Impl->increment(rhs); - return *this; - } - inline friend zdl::DlSystem::ITensorItr operator+(zdl::DlSystem::ITensorItr lhs, int rhs) - { lhs += rhs; return lhs; } - inline zdl::DlSystem::ITensorItr& operator-=(int rhs) - { - if (m_IsTrivial) m_Data -= rhs; else m_Impl->decrement(rhs); - return *this; - } - inline friend zdl::DlSystem::ITensorItr operator-(zdl::DlSystem::ITensorItr lhs, int rhs) - { lhs -= rhs; return lhs; } - - inline size_t operator-(const zdl::DlSystem::ITensorItr& rhs) - { - if (m_IsTrivial) return (m_Data - m_DataStart) - (rhs.m_Data - rhs.m_DataStart); - return m_Impl->getPosition() - rhs.m_Impl->getPosition(); - } - - inline friend bool operator<(const ITensorItr& lhs, const ITensorItr& rhs) - { - if (lhs.m_IsTrivial) return lhs.m_Data < rhs.m_Data; - return lhs.m_Impl->dataPointer() < rhs.m_Impl->dataPointer(); - } - inline friend bool operator>(const ITensorItr& lhs, const ITensorItr& rhs) - { return rhs < lhs; } - inline friend bool operator<=(const ITensorItr& lhs, const ITensorItr& rhs) - { return !(lhs > rhs); } - inline friend bool operator>=(const ITensorItr& lhs, const ITensorItr& rhs) - { return !(lhs < rhs); } - - inline bool operator==(const ITensorItr& rhs) const - { - if (m_IsTrivial) return m_Data == rhs.m_Data; - return m_Impl->dataPointer() == rhs.m_Impl->dataPointer(); - } - inline bool operator!=(const ITensorItr& rhs) const - { return !operator==(rhs); } - - inline VALUE_REF operator[](size_t idx) - { - if (m_IsTrivial) return *(m_DataStart + idx); - return m_Impl->getReferenceAt(idx); - } - inline VALUE_REF operator*() - { if (m_IsTrivial) return *m_Data; else return m_Impl->getReference(); } - inline VALUE_REF operator->() - { return *(*this); } - inline float* dataPointer() const - { if (m_IsTrivial) return m_Data; else return m_Impl->dataPointer(); } - - -protected: - std::unique_ptr<::DlSystem::ITensorItrImpl> m_Impl; - bool m_IsTrivial = false; - float* m_Data = nullptr; - float* m_DataStart = nullptr; -}; - -}} - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif diff --git a/third_party/snpe/include/DlSystem/ITensorItrImpl.hpp b/third_party/snpe/include/DlSystem/ITensorItrImpl.hpp deleted file mode 100644 index 069e7a1d69031f..00000000000000 --- a/third_party/snpe/include/DlSystem/ITensorItrImpl.hpp +++ /dev/null @@ -1,42 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _ITENSOR_ITR_IMPL_HPP_ -#define _ITENSOR_ITR_IMPL_HPP_ - -#include "ZdlExportDefine.hpp" - -#include -#include - -namespace DlSystem -{ - class ITensorItrImpl; -} - -class ZDL_EXPORT DlSystem::ITensorItrImpl -{ -public: - ITensorItrImpl() {} - virtual ~ITensorItrImpl() {} - - virtual float getValue() const = 0; - virtual float& getReference() = 0; - virtual float& getReferenceAt(size_t idx) = 0; - virtual float* dataPointer() const = 0; - virtual void increment(int incVal = 1) = 0; - virtual void decrement(int decVal = 1) = 0; - virtual size_t getPosition() = 0; - virtual std::unique_ptr clone() = 0; - -private: - ITensorItrImpl& operator=(const ITensorItrImpl& other) = delete; - ITensorItrImpl(const ITensorItrImpl& other) = delete; -}; - -#endif diff --git a/third_party/snpe/include/DlSystem/IUDL.hpp b/third_party/snpe/include/DlSystem/IUDL.hpp deleted file mode 100644 index a171ac7e81d6a3..00000000000000 --- a/third_party/snpe/include/DlSystem/IUDL.hpp +++ /dev/null @@ -1,105 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _DL_SYSTEM_IUDL_HPP_ -#define _DL_SYSTEM_IUDL_HPP_ - -#include "ZdlExportDefine.hpp" - -namespace zdl { -namespace DlSystem { - -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * Base class user concrete UDL implementation. - * - * All functions are marked as: - * - * - virtual - * - noexcept - * - * User should make sure no exceptions are propagated outside of - * their module. Errors can be communicated via return values. - */ -class ZDL_EXPORT IUDL { -public: - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * Destructor - */ - virtual ~IUDL() = default; - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief Sets up the user's environment. - * This is called by the SNPE framework to allow the user the - * opportunity to setup anything which is needed for running - * user defined layers. - * - * @param cookie User provided opaque data returned by the SNPE - * runtime - * - * @param insz How many elements in input size array - * @param indim Pointer to a buffer that holds input dimension - * array - * @param indimsz Input dimension size array of the buffer - * 'indim'. Corresponds to indim - * - * @param outsz How many elements in output size array - * @param outdim Pointer to a buffer that holds output - * dimension array - * @param outdimsz Output dimension size of the buffer 'oudim'. - * Corresponds to indim - * - * @return true on success, false otherwise - */ - virtual bool setup(void *cookie, - size_t insz, const size_t **indim, const size_t *indimsz, - size_t outsz, const size_t **outdim, const size_t *outdimsz) = 0; - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief Close the instance. Invoked by the SNPE - * framework to allow the user the opportunity to release any resources - * allocated during setup. - * - * @param cookie - User provided opaque data returned by the SNPE runtime - */ - virtual void close(void *cookie) noexcept = 0; - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief Execute the user defined layer - * - * @param cookie User provided opaque data returned by the SNPE - * runtime - * - * @param input Const pointer to a float buffer that contains - * the input - * - * @param output Float pointer to a buffer that would hold - * the user defined layer's output. This buffer - * is allocated and owned by SNPE runtime. - */ - virtual bool execute(void *cookie, const float **input, float **output) = 0; -}; - -} // ns DlSystem - -} // ns zdl - -#endif // _DL_SYSTEM_IUDL_HPP_ diff --git a/third_party/snpe/include/DlSystem/IUserBuffer.hpp b/third_party/snpe/include/DlSystem/IUserBuffer.hpp deleted file mode 100644 index ea491a545b3269..00000000000000 --- a/third_party/snpe/include/DlSystem/IUserBuffer.hpp +++ /dev/null @@ -1,358 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2017-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _IUSER_BUFFER_HPP -#define _IUSER_BUFFER_HPP - -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" -#include - -namespace zdl { -namespace DlSystem { - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - - -/** - * @brief . - * - * A base class buffer encoding type - */ -class ZDL_EXPORT UserBufferEncoding { -public: - - /** - * @brief . - * - * An enum class of all supported element types in a IUserBuffer - */ - enum class ElementType_t - { - /// Unknown element type. - UNKNOWN = 0, - - /// Each element is presented by float. - FLOAT = 1, - - /// Each element is presented by an unsigned int. - UNSIGNED8BIT = 2, - - /// Each element is presented by an 8-bit quantized value. - TF8 = 10, - - /// Each element is presented by an 16-bit quantized value. - TF16 = 11 - }; - - /** - * @brief Retrieves the size of the element, in bytes. - * - * @return Size of the element, in bytes. - */ - virtual size_t getElementSize() const noexcept = 0; - - /** - * @brief Retrieves the element type - * - * @return Element type - */ - ElementType_t getElementType() const noexcept {return m_ElementType;}; - - virtual ~UserBufferEncoding() {} - -protected: - UserBufferEncoding(ElementType_t elementType) : m_ElementType(elementType) {}; -private: - const ElementType_t m_ElementType; -}; - -/** - * @brief . - * - * A base class buffer source type - * - * @note User buffer from CPU support all kinds of runtimes; - * User buffer from GLBUFFER support only GPU runtime. - */ -class ZDL_EXPORT UserBufferSource { -public: - enum class SourceType_t - { - /// Unknown buffer source type. - UNKNOWN = 0, - - /// The network inputs are from CPU buffer. - CPU = 1, - - /// The network inputs are from OpenGL buffer. - GLBUFFER = 2 - }; - - /** - * @brief Retrieves the source type - * - * @return Source type - */ - SourceType_t getSourceType() const noexcept {return m_SourceType;}; - -protected: - UserBufferSource(SourceType_t sourceType): m_SourceType(sourceType) {}; -private: - const SourceType_t m_SourceType; -}; - -/** - * @brief . - * - * An source type where input data is delivered from OpenGL buffer - */ -class ZDL_EXPORT UserBufferSourceGLBuffer : public UserBufferSource{ -public: - UserBufferSourceGLBuffer() : UserBufferSource(SourceType_t::GLBUFFER) {}; -}; - -/** - * @brief . - * - * An encoding type where each element is represented by an unsigned int - */ -class ZDL_EXPORT UserBufferEncodingUnsigned8Bit : public UserBufferEncoding { -public: - UserBufferEncodingUnsigned8Bit() : UserBufferEncoding(ElementType_t::UNSIGNED8BIT) {}; - size_t getElementSize() const noexcept override; - -protected: - UserBufferEncodingUnsigned8Bit(ElementType_t elementType) : UserBufferEncoding(elementType) {}; - -}; - -/** - * @brief . - * - * An encoding type where each element is represented by a float - */ -class ZDL_EXPORT UserBufferEncodingFloat : public UserBufferEncoding { -public: - UserBufferEncodingFloat() : UserBufferEncoding(ElementType_t::FLOAT) {}; - size_t getElementSize() const noexcept override; - -}; - -/** - * @brief . - * - * An encoding type where each element is represented by tf8, which is an - * 8-bit quantizd value, which has an exact representation of 0.0 - */ -class ZDL_EXPORT UserBufferEncodingTfN : public UserBufferEncoding { -public: - UserBufferEncodingTfN() = delete; - UserBufferEncodingTfN(uint64_t stepFor0, float stepSize, uint8_t bWidth=8): - UserBufferEncoding(getTypeFromWidth(bWidth)), - bitWidth(bWidth), - m_StepExactly0(stepFor0), - m_QuantizedStepSize(stepSize){}; - - UserBufferEncodingTfN(const zdl::DlSystem::UserBufferEncoding &ubEncoding) : UserBufferEncoding(ubEncoding.getElementType()){ - const zdl::DlSystem::UserBufferEncodingTfN* ubEncodingTfN - = dynamic_cast (&ubEncoding); - if (ubEncodingTfN) { - m_StepExactly0 = ubEncodingTfN->getStepExactly0(); - m_QuantizedStepSize = ubEncodingTfN->getQuantizedStepSize(); - bitWidth = ubEncodingTfN->bitWidth; - } - } - - size_t getElementSize() const noexcept override; - /** - * @brief Sets the step value that represents 0 - * - * @param[in] stepExactly0 The step value that represents 0 - * - */ - void setStepExactly0(uint64_t stepExactly0) { - m_StepExactly0 = stepExactly0; - } - - /** - * @brief Sets the float value that each step represents - * - * @param[in] quantizedStepSize The float value of each step size - * - */ - void setQuantizedStepSize(const float quantizedStepSize) { - m_QuantizedStepSize = quantizedStepSize; - } - - /** - * @brief Retrieves the step that represents 0.0 - * - * @return Step value - */ - uint64_t getStepExactly0() const { - return m_StepExactly0; - } - - /** - * Calculates the minimum floating point value that - * can be represented with this encoding. - * - * @return Minimum representable floating point value - */ - float getMin() const { - return static_cast(m_QuantizedStepSize * (0 - (double)m_StepExactly0)); - } - - /** - * Calculates the maximum floating point value that - * can be represented with this encoding. - * - * @return Maximum representable floating point value - */ - float getMax() const{ - return static_cast(m_QuantizedStepSize * (pow(2,bitWidth)-1 - (double)m_StepExactly0)); - }; - - /** - * @brief Retrieves the step size - * - * @return Step size - */ - float getQuantizedStepSize() const { - return m_QuantizedStepSize; - } - - ElementType_t getTypeFromWidth(uint8_t width); - - uint8_t bitWidth; -protected: - uint64_t m_StepExactly0; - float m_QuantizedStepSize; -}; - - -class ZDL_EXPORT UserBufferEncodingTf8 : public UserBufferEncodingTfN { -public: - UserBufferEncodingTf8() = delete; - UserBufferEncodingTf8(unsigned char stepFor0, float stepSize) : - UserBufferEncodingTfN(stepFor0, stepSize) {}; - - UserBufferEncodingTf8(const zdl::DlSystem::UserBufferEncoding &ubEncoding) : UserBufferEncodingTfN(ubEncoding){} - -/** - * @brief Sets the step value that represents 0 - * - * @param[in] stepExactly0 The step value that represents 0 - * - */ - - void setStepExactly0(const unsigned char stepExactly0) { - UserBufferEncodingTfN::m_StepExactly0 = stepExactly0; - } - -/** - * @brief Retrieves the step that represents 0.0 - * - * @return Step value - */ - - unsigned char getStepExactly0() const { - return UserBufferEncodingTfN::m_StepExactly0; - } - -}; - - -/** - * @brief UserBuffer contains a pointer and info on how to walk it and interpret its content. - */ -class ZDL_EXPORT IUserBuffer { -public: - virtual ~IUserBuffer() = default; - - /** - * @brief Retrieves the total number of bytes between elements in each dimension if - * the buffer were to be interpreted as a multi-dimensional array. - * - * @return Number of bytes between elements in each dimension. - * e.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would - * return strides of [24, 8, 4]. - */ - virtual const TensorShape& getStrides() const = 0; - - /** - * @brief Retrieves the size of the buffer, in bytes. - * - * @return Size of the underlying buffer, in bytes. - */ - virtual size_t getSize() const = 0; - - /** - * @brief Retrieves the size of the inference data in the buffer, in bytes. - * - * The inference results from a dynamic-sized model may not be exactly the same size - * as the UserBuffer provided to SNPE. This function can be used to get the amount - * of output inference data, which may be less or greater than the size of the UserBuffer. - * - * If the inference results fit in the UserBuffer, getOutputSize() would be less than - * or equal to getSize(). But if the inference results were more than the capacity of - * the provided UserBuffer, the results would be truncated to fit the UserBuffer. But, - * getOutputSize() would be greater than getSize(), which indicates a bigger buffer - * needs to be provided to SNPE to hold all of the inference results. - * - * @return Size required for the buffer to hold all inference results, which can be less - * or more than the size of the buffer, in bytes. - */ - virtual size_t getOutputSize() const = 0; - - /** - * @brief Changes the underlying memory that backs the UserBuffer. - * - * This can be used to avoid creating multiple UserBuffer objects - * when the only thing that differs is the memory location. - * - * @param[in] buffer Pointer to the memory location - * - * @return Whether the set succeeds. - */ - virtual bool setBufferAddress(void *buffer) noexcept = 0; - - /** - * @brief Gets a const reference to the data encoding object of - * the underlying buffer - * - * This is necessary when the UserBuffer is filled by SNPE with - * data types such as TF8, where the caller needs to know the quantization - * parameters in order to interpret the data properly - * - * @return A read-only encoding object - */ - virtual const UserBufferEncoding& getEncoding() const noexcept = 0; - - /** - * @brief Gets a reference to the data encoding object of - * the underlying buffer - * - * This is necessary when the UserBuffer is re-used, and the encoding - * parameters can change. For example, each input can be quantized with - * different step sizes. - * - * @return Data encoding meta-data - */ - virtual UserBufferEncoding& getEncoding() noexcept = 0; - -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} -} - -#endif diff --git a/third_party/snpe/include/DlSystem/IUserBufferFactory.hpp b/third_party/snpe/include/DlSystem/IUserBufferFactory.hpp deleted file mode 100644 index 59803fbd8f8772..00000000000000 --- a/third_party/snpe/include/DlSystem/IUserBufferFactory.hpp +++ /dev/null @@ -1,81 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _IUSERBUFFER_FACTORY_HPP -#define _IUSERBUFFER_FACTORY_HPP - -#include "IUserBuffer.hpp" -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" -#include "DlEnums.hpp" -namespace zdl { - namespace DlSystem { - class IUserBuffer; - - class TensorShape; - } -} - -namespace zdl { -namespace DlSystem { - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** -* Factory interface class to create IUserBuffer objects. -*/ -class ZDL_EXPORT IUserBufferFactory { -public: - virtual ~IUserBufferFactory() = default; - - /** - * @brief Creates a UserBuffer - * - * @param[in] buffer Pointer to the buffer that the caller supplies - * - * @param[in] bufSize Buffer size, in bytes - * - * @param[in] strides Total number of bytes between elements in each dimension. - * E.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would have strides of [24, 8, 4]. - * - * @param[in] userBufferEncoding Reference to an UserBufferEncoding object - * - * @note Caller has to ensure that memory pointed to by buffer stays accessible - * for the lifetime of the object created - */ - virtual std::unique_ptr - createUserBuffer(void *buffer, size_t bufSize, const zdl::DlSystem::TensorShape &strides, zdl::DlSystem::UserBufferEncoding* userBufferEncoding) noexcept = 0; - - /** - * @brief Creates a UserBuffer - * - * @param[in] buffer Pointer to the buffer that the caller supplies - * - * @param[in] bufSize Buffer size, in bytes - * - * @param[in] strides Total number of bytes between elements in each dimension. - * E.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would have strides of [24, 8, 4]. - * - * @param[in] userBufferEncoding Reference to an UserBufferEncoding object - * - * @param[in] userBufferSource Reference to an UserBufferSource object - * - * @note Caller has to ensure that memory pointed to by buffer stays accessible - * for the lifetime of the object created - */ - virtual std::unique_ptr - createUserBuffer(void *buffer, size_t bufSize, const zdl::DlSystem::TensorShape &strides, zdl::DlSystem::UserBufferEncoding* userBufferEncoding, zdl::DlSystem::UserBufferSource* userBufferSource) noexcept = 0; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} -} - - -#endif diff --git a/third_party/snpe/include/DlSystem/PlatformConfig.hpp b/third_party/snpe/include/DlSystem/PlatformConfig.hpp deleted file mode 100644 index c7b85f43c1274b..00000000000000 --- a/third_party/snpe/include/DlSystem/PlatformConfig.hpp +++ /dev/null @@ -1,230 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017-2018,2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _DL_SYSTEM_PLATFORM_CONFIG_HPP_ -#define _DL_SYSTEM_PLATFORM_CONFIG_HPP_ - -#include "DlSystem/ZdlExportDefine.hpp" -#include - -namespace zdl{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - - -/** - * @brief . - * - * A structure OpenGL configuration - * - * @note When certain OpenGL context and display are provided to UserGLConfig for using - * GPU buffer as input directly, the user MUST ensure the particular OpenGL - * context and display remain vaild throughout the execution of neural network models. - */ -struct ZDL_EXPORT UserGLConfig -{ - /// Holds user EGL context. - /// - void* userGLContext = nullptr; - - /// Holds user EGL display. - void* userGLDisplay = nullptr; -}; - -/** - * @brief . - * - * A structure Gpu configuration - */ -struct ZDL_EXPORT UserGpuConfig{ - /// Holds user OpenGL configuration. - /// - UserGLConfig userGLConfig; -}; - -/** - * @brief . - * - * A class user platform configuration - */ -class ZDL_EXPORT PlatformConfig -{ -public: - - /** - * @brief . - * - * An enum class of all supported platform types - */ - enum class PlatformType_t - { - /// Unknown platform type. - UNKNOWN = 0, - - /// Snapdragon CPU. - CPU = 1, - - /// Adreno GPU. - GPU = 2, - - /// Hexagon DSP. - DSP = 3 - }; - - /** - * @brief . - * - * A union class user platform configuration information - */ - union PlatformConfigInfo - { - /// Holds user GPU Configuration. - /// - UserGpuConfig userGpuConfig; - - PlatformConfigInfo(){}; - }; - - PlatformConfig() : m_PlatformType(PlatformType_t::UNKNOWN), - m_PlatformOptions("") {}; - - /** - * @brief Retrieves the platform type - * - * @return Platform type - */ - PlatformType_t getPlatformType() const {return m_PlatformType;}; - - /** - * @brief Indicates whther the plaform configuration is valid. - * - * @return True if the platform configuration is valid; false otherwise. - */ - bool isValid() const {return (PlatformType_t::UNKNOWN != m_PlatformType);}; - - /** - * @brief Retrieves the Gpu configuration - * - * @param[out] userGpuConfig The passed in userGpuConfig populated with the Gpu configuration on return. - * - * @return True if Gpu configuration was retrieved; false otherwise. - */ - bool getUserGpuConfig(UserGpuConfig& userGpuConfig) const - { - if(m_PlatformType == PlatformType_t::GPU) - { - userGpuConfig = m_PlatformConfigInfo.userGpuConfig; - return true; - } - else - { - return false; - } - } - - /** - * @brief Sets the Gpu configuration - * - * @param[in] userGpuConfig Gpu Configuration - * - * @return True if Gpu configuration was successfully set; false otherwise. - */ - bool setUserGpuConfig(UserGpuConfig& userGpuConfig) - { - if((userGpuConfig.userGLConfig.userGLContext != nullptr) && (userGpuConfig.userGLConfig.userGLDisplay != nullptr)) - { - switch (m_PlatformType) - { - case PlatformType_t::GPU: - m_PlatformConfigInfo.userGpuConfig = userGpuConfig; - return true; - case PlatformType_t::UNKNOWN: - m_PlatformType = PlatformType_t::GPU; - m_PlatformConfigInfo.userGpuConfig = userGpuConfig; - return true; - default: - return false; - } - } - else - return false; - } - - /** - * @brief Sets the platform options - * - * @param[in] options Options as a string in the form of "keyword:options" - * - * @return True if options are pass validation; otherwise false. If false, the options are not updated. - */ - bool setPlatformOptions(std::string options) { - std::string oldOptions = m_PlatformOptions; - m_PlatformOptions = options; - if (isOptionsValid()) { - return true; - } else { - m_PlatformOptions = oldOptions; - return false; - } - } - - /** - * @brief Indicates whther the plaform configuration is valid. - * - * @return True if the platform configuration is valid; false otherwise. - */ - bool isOptionsValid() const; - - /** - * @brief Gets the platform options - * - * @return Options as a string - */ - std::string getPlatformOptions() const { return m_PlatformOptions; } - - /** - * @brief Sets the platform options - * - * @param[in] optionName Name of platform options" - * @param[in] value Value of specified optionName - * - * @return If true, add "optionName:value" to platform options if optionName don't exist, otherwise update the - * value of specified optionName. - * If false, the platform options will not be changed. - */ - bool setPlatformOptionValue(const std::string& optionName, const std::string& value); - - /** - * @brief Removes the platform options - * - * @param[in] optionName Name of platform options" - * @param[in] value Value of specified optionName - * - * @return If true, removed "optionName:value" to platform options if optionName don't exist, do nothing. - * If false, the platform options will not be changed. - */ - bool removePlatformOptionValue(const std::string& optionName, const std::string& value); - - static void SetIsUserGLBuffer(bool isUserGLBuffer); - static bool GetIsUserGLBuffer(); - -private: - PlatformType_t m_PlatformType; - PlatformConfigInfo m_PlatformConfigInfo; - std::string m_PlatformOptions; - static bool m_IsUserGLBuffer; -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -}} //namespace end - -#endif diff --git a/third_party/snpe/include/DlSystem/RuntimeList.hpp b/third_party/snpe/include/DlSystem/RuntimeList.hpp deleted file mode 100644 index 1088a5b31f4538..00000000000000 --- a/third_party/snpe/include/DlSystem/RuntimeList.hpp +++ /dev/null @@ -1,154 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2019 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#include "ZdlExportDefine.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/StringList.hpp" -#include -#include - -#ifndef DL_SYSTEM_RUNTIME_LIST_HPP -#define DL_SYSTEM_RUNTIME_LIST_HPP - -namespace DlSystem -{ - // Forward declaration of Runtime List implementation. - class RuntimeListImpl; -} - -namespace zdl -{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing list of runtimes - */ -class ZDL_EXPORT RuntimeList final -{ -public: - - /** - * @brief . - * - * Creates a new runtime list - * - */ - RuntimeList(); - - /** - * @brief . - * - * copy constructor. - * @param[in] other object to copy. - */ - RuntimeList(const RuntimeList& other); - - /** - * @brief . - * - * constructor with single Runtime_t object - * @param[in] Runtime_t object - */ - RuntimeList(const zdl::DlSystem::Runtime_t& runtime); - - /** - * @brief . - * - * assignment operator. - */ - RuntimeList& operator=(const RuntimeList& other); - - /** - * @brief . - * - * subscript operator. - */ - Runtime_t& operator[](size_t index); - - /** - * @brief Adds runtime to the end of the runtime list - * order of precedence is former followed by latter entry - * - * @param[in] runtime to add - * - * Ruturns false If the runtime already exists - */ - bool add(const zdl::DlSystem::Runtime_t& runtime); - - /** - * @brief Removes the runtime from the list - * - * @param[in] runtime to be removed - * - * @note If the runtime is not found, nothing is done. - */ - void remove(const zdl::DlSystem::Runtime_t runtime) noexcept; - - /** - * @brief Returns the number of runtimes in the list - */ - size_t size() const noexcept; - - /** - * @brief Returns true if the list is empty - */ - bool empty() const noexcept; - - /** - * @brief . - * - * Removes all runtime from the list - */ - void clear() noexcept; - - /** - * @brief . - * - * Returns a StringList of names from the runtime list in - * order of precedence - */ - zdl::DlSystem::StringList getRuntimeListNames() const; - - /** - * @brief . - * - * @param[in] runtime string - * Returns a Runtime enum corresponding to the in param string - * - */ - static zdl::DlSystem::Runtime_t stringToRuntime(const char* runtimeStr); - - /** - * @brief . - * - * @param[in] runtime - * Returns a string corresponding to the in param runtime enum - * - */ - static const char* runtimeToString(const zdl::DlSystem::Runtime_t runtime); - - ~RuntimeList(); - -private: - void deepCopy(const RuntimeList &other); - std::unique_ptr<::DlSystem::RuntimeListImpl> m_RuntimeListImpl; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_RUNTIME_LIST_HPP - diff --git a/third_party/snpe/include/DlSystem/String.hpp b/third_party/snpe/include/DlSystem/String.hpp deleted file mode 100644 index c1eba3bad96b02..00000000000000 --- a/third_party/snpe/include/DlSystem/String.hpp +++ /dev/null @@ -1,104 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef PLATFORM_STANDARD_STRING_HPP -#define PLATFORM_STANDARD_STRING_HPP - -#include -#include -#include -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl -{ -namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * Class for wrapping char * as a really stripped down std::string replacement. - */ -class ZDL_EXPORT String final -{ -public: - String() = delete; - - /** - * Construct a string from std::string reference. - * @param str Reference to a std::string - */ - explicit String(const std::string& str); - - /** - * Construct a string from char* reference. - * @param a char* - */ - explicit String(const char* str); - - /** - * move constructor. - */ - String(String&& other) noexcept; - - /** - * copy constructor. - */ - String(const String& other) = delete; - - /** - * assignment operator. - */ - String& operator=(const String&) = delete; - - /** - * move assignment operator. - */ - String& operator=(String&&) = delete; - - /** - * class comparators - */ - bool operator<(const String& rhs) const noexcept; - bool operator>(const String& rhs) const noexcept; - bool operator<=(const String& rhs) const noexcept; - bool operator>=(const String& rhs) const noexcept; - bool operator==(const String& rhs) const noexcept; - bool operator!=(const String& rhs) const noexcept; - - /** - * class comparators against std::string - */ - bool operator<(const std::string& rhs) const noexcept; - bool operator>(const std::string& rhs) const noexcept; - bool operator<=(const std::string& rhs) const noexcept; - bool operator>=(const std::string& rhs) const noexcept; - bool operator==(const std::string& rhs) const noexcept; - bool operator!=(const std::string& rhs) const noexcept; - - const char* c_str() const noexcept; - - ~String(); -private: - - char* m_string; -}; - -/** - * overloaded << operator - */ -ZDL_EXPORT std::ostream& operator<<(std::ostream& os, const String& str) noexcept; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // PLATFORM_STANDARD_STRING_HPP diff --git a/third_party/snpe/include/DlSystem/StringList.hpp b/third_party/snpe/include/DlSystem/StringList.hpp deleted file mode 100644 index a9a7d5ed89674c..00000000000000 --- a/third_party/snpe/include/DlSystem/StringList.hpp +++ /dev/null @@ -1,107 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2016 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include "ZdlExportDefine.hpp" - -#ifndef DL_SYSTEM_STRINGLIST_HPP -#define DL_SYSTEM_STRINGLIST_HPP - -namespace zdl -{ -namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * Class for holding an order list of null-terminated ASCII strings. - */ -class ZDL_EXPORT StringList final -{ -public: - StringList() {} - - /** - * Construct a string list with some pre-allocated memory. - * @warning Contents of the list will be uninitialized - * @param[in] length Number of elements for which to pre-allocate space. - */ - explicit StringList(size_t length); - - /** - * Append a string to the list. - * @param[in] str Null-terminated ASCII string to append to the list. - */ - void append(const char* str); - - /** - * Returns the string at the indicated position, - * or an empty string if the positions is greater than the size - * of the list. - * @param[in] idx Position in the list of the desired string - */ - const char* at(size_t idx) const noexcept; - - /** - * Pointer to the first string in the list. - * Can be used to iterate through the list. - */ - const char** begin() const noexcept; - - /** - * Pointer to one after the last string in the list. - * Can be used to iterate through the list. - */ - const char** end() const noexcept; - - /** - * Return the number of valid string pointers held by this list. - */ - size_t size() const noexcept; - - - /** - * assignment operator. - */ - StringList& operator=(const StringList&) noexcept; - - /** - * copy constructor. - * @param[in] other object to copy. - */ - StringList(const StringList& other); - - /** - * move constructor. - * @param[in] other object to move. - */ - StringList(StringList&& other) noexcept; - - ~StringList(); -private: - void copy(const StringList& other); - - void resize(size_t length); - - void clear(); - - static const char* s_Empty; - const char** m_Strings = nullptr; - const char** m_End = nullptr; - size_t m_Size = 0; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_STRINGLIST_HPP - diff --git a/third_party/snpe/include/DlSystem/TensorMap.hpp b/third_party/snpe/include/DlSystem/TensorMap.hpp deleted file mode 100644 index feecec666729ad..00000000000000 --- a/third_party/snpe/include/DlSystem/TensorMap.hpp +++ /dev/null @@ -1,120 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2016 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include "ZdlExportDefine.hpp" -#include "ITensor.hpp" -#include "StringList.hpp" - -#ifndef DL_SYSTEM_TENSOR_MAP_HPP -#define DL_SYSTEM_TENSOR_MAP_HPP - -namespace DlSystem -{ - // Forward declaration of tensor map implementation. - class TensorMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the map of tensor. - */ -class ZDL_EXPORT TensorMap final -{ -public: - - /** - * @brief . - * - * Creates a new empty tensor map - */ - TensorMap(); - - /** - * copy constructor. - * @param[in] other object to copy. - */ - TensorMap(const TensorMap& other); - - /** - * assignment operator. - */ - TensorMap& operator=(const TensorMap& other); - - /** - * @brief Adds a name and the corresponding tensor pointer - * to the map - * - * @param[in] name The name of the tensor - * @param[out] tensor The pointer to the tensor - * - * @note If a tensor with the same name already exists, the - * tensor is replaced with the existing tensor. - */ - void add(const char *name, zdl::DlSystem::ITensor *tensor); - - /** - * @brief Removes a mapping of tensor and its name by its name - * - * @param[in] name The name of tensor to be removed - * - * @note If no tensor with the specified name is found, nothing - * is done. - */ - void remove(const char *name) noexcept; - - /** - * @brief Returns the number of tensors in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all tensors from the map - */ - void clear() noexcept; - - /** - * @brief Returns the tensor given its name. - * - * @param[in] name The name of the tensor to get. - * - * @return nullptr if no tensor with the specified name is - * found; otherwise, a valid pointer to the tensor. - */ - zdl::DlSystem::ITensor* getTensor(const char *name) const noexcept; - - /** - * @brief . - * - * Returns the names of all tensors - */ - zdl::DlSystem::StringList getTensorNames() const; - - ~TensorMap(); -private: - void swap(const TensorMap &other); - std::unique_ptr<::DlSystem::TensorMapImpl> m_TensorMapImpl; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_TENSOR_MAP_HPP - diff --git a/third_party/snpe/include/DlSystem/TensorShape.hpp b/third_party/snpe/include/DlSystem/TensorShape.hpp deleted file mode 100644 index 99583dccb40bac..00000000000000 --- a/third_party/snpe/include/DlSystem/TensorShape.hpp +++ /dev/null @@ -1,203 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2016 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include -#include -#include -#include "ZdlExportDefine.hpp" - -#ifndef DL_SYSTEM_TENSOR_SHAPE_HPP -#define DL_SYSTEM_TENSOR_SHAPE_HPP - -namespace DlSystem -{ - // Forward declaration of tensor shape implementation. - class TensorShapeImpl; -} - -namespace zdl -{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * Convenient typedef to represent dimension - */ -using Dimension = size_t; - -/** - * @brief . - * - * A class representing the shape of tensor. It is used at the - * time of creation of tensor. - */ -class ZDL_EXPORT TensorShape final -{ -public: - - /** - * @brief . - * - * Creates a new shape with a list of dims specified in - * initializer list fashion. - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - */ - TensorShape(std::initializer_list dims); - - /** - * @brief . - * - * Creates a new shape with a list of dims specified in array - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - * @param[in] size Size of the array. - * - */ - TensorShape(const Dimension *dims, size_t size); - - /** - * @brief . - * - * Creates a new shape with a vector of dims specified in - * vector fashion. - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - */ - TensorShape(std::vector dims); - - /** - * @brief . - * - * copy constructor. - * @param[in] other object to copy. - */ - TensorShape(const TensorShape& other); - - /** - * @brief . - * - * assignment operator. - */ - TensorShape& operator=(const TensorShape& other); - - /** - * @brief . - * - * Creates a new shape with no dims. It can be extended later - * by invoking concatenate. - */ - TensorShape(); - - /** - * @brief . - * - * Concatenates additional dimensions specified in - * initializer list fashion to the existing dimensions. - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - */ - void concatenate(std::initializer_list dims); - - /** - * @brief . - * - * Concatenates additional dimensions specified in - * the array to the existing dimensions. - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - * @param[in] size Size of the array. - * - */ - void concatenate(const Dimension *dims, size_t size); - - /** - * @brief . - * - * Concatenates an additional dimension to the existing - * dimensions. - * - * @param[in] dim The dimensions are specified in which the last element - * of the vector represents the fastest varying dimension and the - * zeroth element represents the slowest varying, etc. - * - */ - void concatenate(const Dimension &dim); - - /** - * @brief . - * - * Retrieves a single dimension, based on its index. - * - * @return The value of dimension - * - * @throws std::out_of_range if the index is >= the number of - * dimensions (or rank). - */ - Dimension& operator[](size_t index); - Dimension& operator[](size_t index) const; - - /** - * @brief . - * - * Retrieves the rank i.e. number of dimensions. - * - * @return The rank - */ - size_t rank() const; - - /** - * @brief . - * - * Retrieves a pointer to the first dimension of shape - * - * @return nullptr if no dimension exists; otherwise, points to - * the first dimension. - * - */ - const Dimension* getDimensions() const; - - ~TensorShape(); - -private: - void swap(const TensorShape &other); - std::unique_ptr<::DlSystem::TensorShapeImpl> m_TensorShapeImpl; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_TENSOR_SHAPE_HPP - diff --git a/third_party/snpe/include/DlSystem/TensorShapeMap.hpp b/third_party/snpe/include/DlSystem/TensorShapeMap.hpp deleted file mode 100644 index cef946e2e6dbc9..00000000000000 --- a/third_party/snpe/include/DlSystem/TensorShapeMap.hpp +++ /dev/null @@ -1,127 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include -#include -#include "ZdlExportDefine.hpp" -#include "DlSystem/TensorShape.hpp" -#include "DlSystem/StringList.hpp" - -#ifndef DL_SYSTEM_TENSOR_SHAPE_MAP_HPP -#define DL_SYSTEM_TENSOR_SHAPE_MAP_HPP - -namespace DlSystem -{ - // Forward declaration of tensor shape map implementation. - class TensorShapeMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the map of names and tensorshapes. - */ -class ZDL_EXPORT TensorShapeMap final -{ -public: - - /** - * @brief . - * - * Creates a new tensor shape map - * - */ - TensorShapeMap(); - - /** - * @brief . - * - * copy constructor. - * @param[in] other object to copy. - */ - TensorShapeMap(const TensorShapeMap& other); - - /** - * @brief . - * - * assignment operator. - */ - TensorShapeMap& operator=(const TensorShapeMap& other); - - /** - * @brief Adds a name and the corresponding tensor pointer - * to the map - * - * @param[in] name The name of the tensor - * @param[out] tensor The pointer to the tensor - * - * @note If a tensor with the same name already exists, no new - * tensor is added. - */ - void add(const char *name, const zdl::DlSystem::TensorShape& tensorShape); - - /** - * @brief Removes a mapping of tensor and its name by its name - * - * @param[in] name The name of tensor to be removed - * - * @note If no tensor with the specified name is found, nothing - * is done. - */ - void remove(const char *name) noexcept; - - /** - * @brief Returns the number of tensors in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all tensors from the map - */ - void clear() noexcept; - - /** - * @brief Returns the tensor given its name. - * - * @param[in] name The name of the tensor to get. - * - * @return nullptr if no tensor with the specified name is - * found; otherwise, a valid pointer to the tensor. - */ - zdl::DlSystem::TensorShape getTensorShape(const char *name) const noexcept; - - /** - * @brief . - * - * Returns the names of all tensor shapes - */ - zdl::DlSystem::StringList getTensorShapeNames() const; - - ~TensorShapeMap(); -private: - void swap(const TensorShapeMap &other); - std::unique_ptr<::DlSystem::TensorShapeMapImpl> m_TensorShapeMapImpl; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_TENSOR_SHAPE_MAP_HPP - diff --git a/third_party/snpe/include/DlSystem/UDLContext.hpp b/third_party/snpe/include/DlSystem/UDLContext.hpp deleted file mode 100644 index 21fce1b04ae308..00000000000000 --- a/third_party/snpe/include/DlSystem/UDLContext.hpp +++ /dev/null @@ -1,243 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef UDL_CONTEXT_HPP -#define UDL_CONTEXT_HPP - -#include // memset -#include - -#include "ZdlExportDefine.hpp" - -namespace zdl { namespace DlSystem { - -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * UDLContext holds the user defined layer context which - * consists of a layer name, layer ID, blob and blob size. - * - * An instance of UDLContext is passed as an argument to the - * UDLFactoryFunc provided by the user every time the SNPE - * runtime encounters an unknown layer descriptor. The instance - * of a UDLContext is created by the SNPE runtime and is - * consumed by the user's factory function. The user should - * obtain a copy of this class and should not assume any - * prolonged object lifetime beyond the UDLFactoryFunction. - */ -class ZDL_EXPORT UDLContext final { -public: - /** - * @brief Constructor - * - * @param[in] name name of the layer - * - * @param[in] type layer type - * - * @param[in] id identifier for the layer - * - * @param[in] id Blob/bytes as packed by the user code as part of - * the Python converter script - */ - UDLContext(const std::string& name, - const std::string& type, - int32_t id, - const std::string& blob) : - m_Name(name), m_Type(type), m_Size(blob.size()), m_Id(id) { - // FIXME not dealing with alloc error - m_Buffer = new uint8_t[m_Size]; - std::memcpy(m_Buffer, blob.data(), m_Size); - } - - /** - * @brief . - * - * Empty constructor is useful for - * creating an empty UDLContext and then run copy constructor - * from a fully initialized one. - */ - explicit UDLContext() {} - - /** - * @brief . - * - * destructor Deallocates any internal allocated memory - */ - ~UDLContext() { release(); } - - /** - * @brief . - * - * Deallocate any internally allocated memory - */ - void release() { - if (m_Buffer && m_Size) - std::memset(m_Buffer, 0, m_Size); - delete []m_Buffer; - m_Buffer = nullptr; - m_Size = 0; - } - - /** - * @brief . - * - * Copy Constructor - makes a copy from ctx - * - * @param[in] ctx Source UDLContext to copy from - */ - UDLContext(const UDLContext& ctx) : m_Name(ctx.m_Name), - m_Type(ctx.m_Type), - m_Id(ctx.m_Id) { - std::tuple cpy = ctx.getCopy(); - // current compiler does not support get - m_Buffer = std::get<0>(cpy); - m_Size = std::get<1>(cpy); - } - - /** - * @brief - * - * Assignment operator - makes a copy from ctx - * - * @param[in] ctx Source UDLContext to copy from - * - * @return this - */ - UDLContext& operator=(const UDLContext& ctx) { - UDLContext c (ctx); - this->swap(c); // non throwing swap - return *this; - } - - /** - * @brief . - * - * Move Constructor - Move internals from ctx into this - * - * @param[in] ctx Source UDLContext to move from - */ - UDLContext(UDLContext&& ctx) : - m_Name(std::move(ctx.m_Name)), - m_Type(std::move(ctx.m_Type)), - m_Buffer(ctx.m_Buffer), - m_Size(ctx.m_Size), - m_Id(ctx.m_Id) { - ctx.clear(); - } - - /** - * @brief . - * - * Assignment move - Move assignment operator from ctx - * - * @param[in] ctx Source UDLContext to move from - * - * @return this - */ - UDLContext& operator=(UDLContext&& ctx) { - m_Name = std::move(ctx.m_Name); - m_Type = std::move(ctx.m_Type); - m_Buffer = ctx.m_Buffer; - m_Size = ctx.m_Size; - m_Id = ctx.m_Id; - ctx.clear(); - return *this; - } - - /** - * @brief . - * - * Obtain the name of the layer - * - * @return const reference to the name of the layer - */ - const std::string& getName() const noexcept { return m_Name; } - - /** - * @brief . - * - * Obtain the type of the layer - * - * @return const reference to the type of the layer - */ - const std::string& getType() const noexcept { return m_Type; } - - /** - * @brief . - * - * Obtain the Id of the layer - * - * @return The id of the layer - */ - int32_t getId() const noexcept { return m_Id; } - - /** - * @brief . - * - * Obtain the size of the blob - * - * @return Size of the internal blob - */ - size_t getSize() const noexcept { return m_Size; } - - /** - * @brief . - * - * Get a const pointer to the internal blob - * - * @return Const pointer to the internal blob - */ - const uint8_t* getBlob() const noexcept { return m_Buffer; } - - /** - * @brief . - * - * Get a copy of the blob/size into a tuple - * - * @return A tuple with a pointer to a copy of the blob and a - * size - */ - std::tuple getCopy() const { - uint8_t* buf = new uint8_t[m_Size]; - // FIXME missing memcpy - std::memcpy(buf, m_Buffer, m_Size); - return std::make_tuple(buf, m_Size); - } - - /** - * @brief . - * - * Set zeros in the internals members - */ - void clear() { - m_Name.clear(); - m_Type.clear(); - m_Buffer = 0; - m_Size = 0; - m_Id = -1; - } -private: - void swap(UDLContext& c) noexcept { - std::swap(m_Name, c.m_Name); - std::swap(m_Type, c.m_Type); - std::swap(m_Id, c.m_Id); - std::swap(m_Buffer, c.m_Buffer); - std::swap(m_Size, c.m_Size); - } - std::string m_Name; // name of the layer instance - std::string m_Type; // The actual layer type - uint8_t* m_Buffer = nullptr; - size_t m_Size = 0; - int32_t m_Id = -1; -}; - -}} - -#endif /* UDL_CONTEXT_HPP */ diff --git a/third_party/snpe/include/DlSystem/UDLFunc.hpp b/third_party/snpe/include/DlSystem/UDLFunc.hpp deleted file mode 100644 index 6a95eef1702ecc..00000000000000 --- a/third_party/snpe/include/DlSystem/UDLFunc.hpp +++ /dev/null @@ -1,87 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _UDL_FUNC_HPP_ -#define _UDL_FUNC_HPP_ - -#include - -#include "ZdlExportDefine.hpp" -#include - -namespace zdl { - namespace DlSystem { - class UDLContext; - } -} - -namespace zdl { namespace DlSystem { -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * Definition of UDLFactoyFunc, using/typedef and default FactoryFunction - * UDLBundle - a simple way to bundle func and cookie into one type - */ - - -/** - * @brief . - * - * Convenient typedef for user defined layer creation factory - * - * @param[out] void* Cookie - a user opaque data that was passed during SNPE's runtime's - * CreateInstance. SNPE's runtime is passing this back to the user. - * - * @param[out] DlSystem::UDLContext* - The specific Layer Description context what is passe - * SNPE runtime. - * - * @return IUDL* - a Concrete instance of IUDL derivative - */ -using UDLFactoryFunc = std::function; - -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * default UDL factory implementation - * - * @param[out] DlSystem::UDLContext* - The specific Layer Description context what is passe - * SNPE runtime. - * - * @param[out] void* Cookie - a user opaque data that was passed during SNPE's runtime's - * CreateInstance. SNPE's runtime is passing this back to the user. - * - * @return IUDL* - nullptr to indicate SNPE's runtime that there is no specific - * implementation for UDL. When SNPE's runtime sees nullptr as a return - * value from the factory, it will halt execution if model has an unknown layer - * - */ -inline ZDL_EXPORT zdl::DlSystem::IUDL* DefaultUDLFunc(void*, const zdl::DlSystem::UDLContext*) { return nullptr; } - -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * Simple struct to bundle 2 elements. - * A user defined cookie that would be returned for each - * IUDL call. The user can place anything there and the - * SNPE runtime will provide it back - */ -struct ZDL_EXPORT UDLBundle { - void *cookie = nullptr; - UDLFactoryFunc func = DefaultUDLFunc; -}; - -}} - - -#endif // _UDL_FUNC_HPP_ diff --git a/third_party/snpe/include/DlSystem/UserBufferMap.hpp b/third_party/snpe/include/DlSystem/UserBufferMap.hpp deleted file mode 100644 index a03ddfe1d11ad8..00000000000000 --- a/third_party/snpe/include/DlSystem/UserBufferMap.hpp +++ /dev/null @@ -1,122 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include "ZdlExportDefine.hpp" -#include "StringList.hpp" - -#ifndef DL_SYSTEM_USER_BUFFER_MAP_HPP -#define DL_SYSTEM_USER_BUFFER_MAP_HPP - -namespace DlSystem -{ - // Forward declaration of UserBuffer map implementation. - class UserBufferMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ -class IUserBuffer; - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the map of UserBuffer. - */ -class ZDL_EXPORT UserBufferMap final -{ -public: - - /** - * @brief . - * - * Creates a new empty UserBuffer map - */ - UserBufferMap(); - - /** - * copy constructor. - * @param[in] other object to copy. - */ - UserBufferMap(const UserBufferMap& other); - - /** - * assignment operator. - */ - UserBufferMap& operator=(const UserBufferMap& other); - - /** - * @brief Adds a name and the corresponding UserBuffer pointer - * to the map - * - * @param[in] name The name of the UserBuffer - * @param[in] userBuffer The pointer to the UserBuffer - * - * @note If a UserBuffer with the same name already exists, the new - * UserBuffer pointer would be updated. - */ - void add(const char *name, zdl::DlSystem::IUserBuffer *buffer); - - /** - * @brief Removes a mapping of one UserBuffer and its name by its name - * - * @param[in] name The name of UserBuffer to be removed - * - * @note If no UserBuffer with the specified name is found, nothing - * is done. - */ - void remove(const char *name) noexcept; - - /** - * @brief Returns the number of UserBuffers in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all UserBuffers from the map - */ - void clear() noexcept; - - /** - * @brief Returns the UserBuffer given its name. - * - * @param[in] name The name of the UserBuffer to get. - * - * @return nullptr if no UserBuffer with the specified name is - * found; otherwise, a valid pointer to the UserBuffer. - */ - zdl::DlSystem::IUserBuffer* getUserBuffer(const char *name) const noexcept; - - /** - * @brief . - * - * Returns the names of all UserBuffers - * - * @return A list of UserBuffer names. - */ - zdl::DlSystem::StringList getUserBufferNames() const; - - ~UserBufferMap(); -private: - void swap(const UserBufferMap &other); - std::unique_ptr<::DlSystem::UserBufferMapImpl> m_UserBufferMapImpl; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // DlSystem namespace -} // zdl namespace - - -#endif // DL_SYSTEM_TENSOR_MAP_HPP - diff --git a/third_party/snpe/include/DlSystem/UserMemoryMap.hpp b/third_party/snpe/include/DlSystem/UserMemoryMap.hpp deleted file mode 100644 index 3685a8ddabed69..00000000000000 --- a/third_party/snpe/include/DlSystem/UserMemoryMap.hpp +++ /dev/null @@ -1,129 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include "ZdlExportDefine.hpp" -#include "StringList.hpp" - -#ifndef DL_SYSTEM_USER_MEMORY_MAP_HPP -#define DL_SYSTEM_USER_MEMORY_MAP_HPP - -namespace DlSystem -{ - // Forward declaration of UserMemory map implementation. - class UserMemoryMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ -class IUserBuffer; - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the map of UserMemory. - */ -class ZDL_EXPORT UserMemoryMap final -{ -public: - - /** - * @brief . - * - * Creates a new empty UserMemory map - */ - UserMemoryMap(); - - /** - * copy constructor. - * @param[in] other object to copy. - */ - UserMemoryMap(const UserMemoryMap& other); - - /** - * assignment operator. - */ - UserMemoryMap& operator=(const UserMemoryMap& other); - - /** - * @brief Adds a name and the corresponding buffer address - * to the map - * - * @param[in] name The name of the UserMemory - * @param[in] address The pointer to the Buffer Memory - * - * @note If a UserBuffer with the same name already exists, the new - * address would be updated. - */ - void add(const char *name, void *address); - - /** - * @brief Removes a mapping of one Buffer address and its name by its name - * - * @param[in] name The name of Memory address to be removed - * - * @note If no UserBuffer with the specified name is found, nothing - * is done. - */ - void remove(const char *name) noexcept; - - /** - * @brief Returns the number of User Memory addresses in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all User Memory from the map - */ - void clear() noexcept; - - /** - * @brief . - * - * Returns the names of all User Memory - * - * @return A list of Buffer names. - */ - zdl::DlSystem::StringList getUserBufferNames() const; - - /** - * @brief Returns the no of UserMemory addresses mapped to the buffer - * - * @param[in] name The name of the UserMemory - * - */ - size_t getUserMemoryAddressCount(const char *name) const noexcept; - - /** - * @brief Returns address at a specified index corresponding to a UserMemory buffer name - * - * @param[in] name The name of the buffer - * @param[in] index The index in the list of addresses - * - */ - void* getUserMemoryAddressAtIndex(const char *name, uint32_t index) const noexcept; - - ~UserMemoryMap(); -private: - void swap(const UserMemoryMap &other); - std::unique_ptr<::DlSystem::UserMemoryMapImpl> m_UserMemoryMapImpl; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // DlSystem namespace -} // zdl namespace - - -#endif // DL_SYSTEM_TENSOR_MAP_HPP - diff --git a/third_party/snpe/include/DlSystem/ZdlExportDefine.hpp b/third_party/snpe/include/DlSystem/ZdlExportDefine.hpp deleted file mode 100644 index 92eb786d312f6d..00000000000000 --- a/third_party/snpe/include/DlSystem/ZdlExportDefine.hpp +++ /dev/null @@ -1,13 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#pragma once - -#ifndef ZDL_EXPORT -#define ZDL_EXPORT -#endif diff --git a/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp b/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp deleted file mode 100644 index 66097ba569f629..00000000000000 --- a/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp +++ /dev/null @@ -1,118 +0,0 @@ -// ============================================================================= -// -// Copyright (c) 2018-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -// ============================================================================= - -#ifndef SNPE_PLATFORMVALIDATOR_HPP -#define SNPE_PLATFORMVALIDATOR_HPP - -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -#define DO_PRAGMA(s) _Pragma(#s) -#define NO_WARNING "-Wunused-variable" - -#ifdef __clang__ -#define SNPE_DISABLE_WARNINGS(clang_warning,gcc_warning) \ -_Pragma("clang diagnostic push") \ -DO_PRAGMA(clang diagnostic ignored clang_warning) - -#define SNPE_ENABLE_WARNINGS \ -_Pragma("clang diagnostic pop") - -#elif defined __GNUC__ -#define SNPE_DISABLE_WARNINGS(clang_warning,gcc_warning) \ -_Pragma("GCC diagnostic push") \ -DO_PRAGMA(GCC diagnostic ignored gcc_warning) - -#define SNPE_ENABLE_WARNINGS \ -_Pragma("GCC diagnostic pop") - -#else -#define SNPE_DISABLE_WARNINGS(...) -#define SNPE_ENABLE_WARNINGS -#endif - -SNPE_DISABLE_WARNINGS("-Wdelete-non-virtual-dtor","-Wdelete-non-virtual-dtor") -#include -#include -SNPE_ENABLE_WARNINGS - -namespace zdl -{ - namespace SNPE - { - class PlatformValidator; - - class IPlatformValidatorRuntime; - } -} - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** -* The class for checking SNPE compatibility/capability of a device. -* -*/ - -class ZDL_EXPORT zdl::SNPE::PlatformValidator -{ -public: - /** - * @brief Default Constructor of the PlatformValidator Class - * - * @return A new instance of a PlatformValidator object - * that can be used to check the SNPE compatibility - * of a device - */ - PlatformValidator(); - - ~PlatformValidator(); - - /** - * @brief Sets the runtime processor for compatibility check - * - * @return Void - */ - void setRuntime(zdl::DlSystem::Runtime_t runtime); - - /** - * @brief Checks if the Runtime prerequisites for SNPE are available. - * - * @return True if the Runtime prerequisites are available, else false. - */ - bool isRuntimeAvailable(); - - /** - * @brief Returns the core version for the Runtime selected. - * - * @return String which contains the actual core version value - */ - std::string getCoreVersion(); - - /** - * @brief Returns the library version for the Runtime selected. - * - * @return String which contains the actual lib version value - */ - std::string getLibVersion(); - - /** - * @brief Runs a small program on the runtime and Checks if SNPE is supported for Runtime. - * - * @return If True, the device is ready for SNPE execution, else not. - */ - - bool runtimeCheck(); - -private: - zdl::DlSystem::Runtime_t m_runtimeType; - std::unique_ptr m_platformValidatorRuntime; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif //SNPE_PLATFORMVALIDATOR_HPP diff --git a/third_party/snpe/include/SNPE/ApplicationBufferMap.hpp b/third_party/snpe/include/SNPE/ApplicationBufferMap.hpp deleted file mode 100644 index 380a3e0e6e77ee..00000000000000 --- a/third_party/snpe/include/SNPE/ApplicationBufferMap.hpp +++ /dev/null @@ -1,101 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef PSNPE_APPLICATIONBUFFERMAP_HPP -#define PSNPE_APPLICATIONBUFFERMAP_HPP -#include -#include -#include - -#include "DlSystem/UserBufferMap.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl -{ -namespace PSNPE -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the UserBufferMap of Input and Output asynchronous mode. - */ - -class ZDL_EXPORT ApplicationBufferMap final -{ - - public: - /** - * @brief Adds a name and the corresponding buffer - * to the map - * - * @param[in] name The name of the UserBuffer - * @param[in] buffer The vector of the uint8_t data - * - * @note If a UserBuffer with the same name already exists, the new - * UserBuffer pointer would be updated. - */ - void add(const char* name, std::vector& buff) noexcept; - void add(const char* name, std::vector& buff) noexcept; - /** - * @brief Removes a mapping of one UserBuffer and its name by its name - * - * @param[in] name The name of UserBuffer to be removed - * - * @note If no UserBuffer with the specified name is found, nothing - * is done. - */ - void remove(const char* name) noexcept; - - /** - * @brief Returns the number of UserBuffers in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all UserBuffers from the map - */ - void clear() noexcept; - - /** - * @brief Returns the UserBuffer given its name. - * - * @param[in] name The name of the UserBuffer to get. - * - * @return nullptr if no UserBuffer with the specified name is - * found; otherwise, a valid pointer to the UserBuffer. - */ - const std::vector& getUserBuffer(const char* name) const; - const std::vector& operator[](const char* name) const; - /** - * @brief . - * - * Returns the names of all UserAsyncBufferMap - * - * @return A list of UserBuffer names. - */ - zdl::DlSystem::StringList getUserBufferNames() const; - const std::unordered_map>& getUserBuffer() const; - explicit ApplicationBufferMap(); - ~ApplicationBufferMap(); - explicit ApplicationBufferMap( - const std::unordered_map> buffer); - - private: - std::unordered_map> m_UserMap; -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ -} // namespace PSNPE -} // namespace zdl - -#endif // PSNPE_APPLICATIONBUFFERMAP_HPP diff --git a/third_party/snpe/include/SNPE/PSNPE.hpp b/third_party/snpe/include/SNPE/PSNPE.hpp deleted file mode 100644 index a823c0c7fa1d78..00000000000000 --- a/third_party/snpe/include/SNPE/PSNPE.hpp +++ /dev/null @@ -1,205 +0,0 @@ -// ============================================================================= -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -// ============================================================================= - -#ifndef PSNPE_HPP -#define PSNPE_HPP - -#include -#include -#include "SNPE/SNPE.hpp" -#include "DlSystem/UserBufferMap.hpp" -#include "DlContainer/IDlContainer.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -#include "UserBufferList.hpp" -#include "RuntimeConfigList.hpp" -#include "ApplicationBufferMap.hpp" - -namespace zdl -{ -namespace PSNPE -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - *@ brief build snpe instance in serial or parallel - * - */ -enum ZDL_EXPORT BuildMode { - SERIAL = 0, - PARALLEL = 1 -}; -/** - * @brief Input and output transmission mode - */ -enum ZDL_EXPORT InputOutputTransmissionMode -{ - sync = 0, - outputAsync = 1, - inputOutputAsync = 2 -}; - -/** - * @brief A structure representing parameters of callback function of Async Output mode - */ -struct ZDL_EXPORT OutputAsyncCallbackParam -{ - size_t dataIndex; - bool executeStatus; - std::string errorMsg; - OutputAsyncCallbackParam(size_t _index,bool _status, const std::string& _errorMsg = std::string()) - : dataIndex(_index),executeStatus(_status), errorMsg(_errorMsg){}; -}; -/** - * @brief A structure representing parameters of callback function of Async Input/Output mode - */ -struct ZDL_EXPORT InputOutputAsyncCallbackParam -{ - size_t dataIndex; - const ApplicationBufferMap& outputMap; - bool executeStatus; - std::string errorMsg; - InputOutputAsyncCallbackParam(size_t _index, const ApplicationBufferMap& output_map,bool _status, - const std::string _ErrorMsg = std::string()) - : dataIndex(_index) - , outputMap(output_map) - , executeStatus(_status) - , errorMsg(_ErrorMsg){}; -}; -/** - * @brief This callback is called when the output data is ready, only use for Output Async mode - */ -using OutputAsyncCallbackFunc = std::function; -/** - * @brief This callback is called when the output data is ready, only use for Output-Input Async mode - */ -using InputOutputAsyncCallbackFunc = std::function; -/** - * @brief This callback is called when the input data is ready,only use for Output-Input Async mode - */ -using InputOutputAsyncInputCallback = std::function(const std::vector &, - const zdl::DlSystem::StringList &)>; -/** - * @brief . - * - * A structure PSNPE configuration - * - */ -struct ZDL_EXPORT BuildConfig final -{ - BuildMode buildMode = BuildMode::SERIAL; ///< Specify build in serial mode or parallel mode - zdl::DlContainer::IDlContainer* container;///< The opened container ptr - zdl::DlSystem::StringList outputBufferNames;///< Specify the output layer name - zdl::DlSystem::StringList outputTensors;///< Specify the output layer name - RuntimeConfigList runtimeConfigList;///< The runtime config list for PSNPE, @see RuntimeConfig - size_t inputThreadNumbers = 1;///< Specify the number of threads used in the execution phase to process input data, only used in inputOutputAsync mode - size_t outputThreadNumbers = 1;///< Specify the number of threads used in the execution phase to process output data, only used in inputOutputAsync and outputAsync mode - OutputAsyncCallbackFunc outputCallback;///< The callback to deal with output data ,only used in outputAsync mode - InputOutputAsyncCallbackFunc inputOutputCallback;///< The callback to deal with output data ,only used in inputOutputAsync mode - InputOutputAsyncInputCallback inputOutputInputCallback;///< The callback to deal with input data ,only used in inputOutputAsync mode - InputOutputTransmissionMode inputOutputTransmissionMode = InputOutputTransmissionMode::sync;///< Specify execution mode - zdl::DlSystem::ProfilingLevel_t profilingLevel = zdl::DlSystem::ProfilingLevel_t::OFF;///< Specify profiling level for Diaglog - uint64_t encode[2] = {0, 0}; - bool enableInitCache = false; - std::string platformOptions; - std::string diaglogOutputDir = "./diaglogs/"; ///< Specify a diaglog output directory to save the generated Diaglog files. -}; -/** - * @brief . - * - * The class for executing SNPE instances in parallel. - */ -class ZDL_EXPORT PSNPE final -{ - public: - ~PSNPE(); - - explicit PSNPE() noexcept :m_TransmissionMode(InputOutputTransmissionMode::sync){}; - - /** - * @brief Build snpe instances. - * - */ - bool build(BuildConfig& buildConfig) noexcept; - - /** - * @brief Execute snpe instances in Async Output mode and Sync mode - * - * @param[in] inputBufferList A list of user buffers that contains the input data - * - * @param[in,out] outputBufferList A list of user buffers that will hold the output data - * - */ - bool execute(UserBufferList& inputBufferList, UserBufferList& outputBufferList) noexcept; - - /** - * @brief Execute snpe instances in Async Input/Output mode - * - * @param[in]inputMap A map of input buffers that contains input data. The names of buffers - * need to be matched with names retrived through getInputTensorNames() - * - * @param dataIndex Index of the input data - * - * @param isTF8buff Whether prefer to using 8 bit quantized element for inference - * - * @return True if executed successfully; flase, otherwise. - */ - bool executeInputOutputAsync(const std::vector& inputMap, size_t dataIndex, bool isTF8buff) noexcept; - bool executeInputOutputAsync(const std::vector& inputMap, size_t dataIndex, bool isTF8buff,bool isTF8Outputbuff) noexcept; - /** - * @brief Returns the input layer names of the network. - * - * @return StringList which contains the input layer names - */ - const zdl::DlSystem::StringList getInputTensorNames() const noexcept; - - /** - * @brief Returns the output layer names of the network. - * - * @return StringList which contains the output layer names - */ - const zdl::DlSystem::StringList getOutputTensorNames() const noexcept; - - /** - * @brief Returns the input tensor dimensions of the network. - * - * @return TensorShape which contains the dimensions. - */ - const zdl::DlSystem::TensorShape getInputDimensions() const noexcept; - - const zdl::DlSystem::TensorShape getInputDimensions(const char *name) const noexcept; - - /** - * @brief Returns attributes of buffers. - * - * @see zdl::SNPE - * - * @return BufferAttributes of input/output tensor named. - */ - const zdl::DlSystem::TensorShape getBufferAttributesDims(const char *name) const noexcept; - - zdl::DlSystem::Optional getInputOutputBufferAttributes(const char *name) const noexcept; - bool registerIonBuffers(const zdl::DlSystem::UserMemoryMap& ionBufferMap) const noexcept; - bool deregisterIonBuffers(const zdl::DlSystem::StringList& ionBufferNames) const noexcept; - - const char* getLastErrorString(); - - private: - PSNPE(const PSNPE&) = delete; - PSNPE& operator=(const PSNPE&) = delete; - zdl::PSNPE::InputOutputTransmissionMode m_TransmissionMode; - -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ -} // namespace PSNPE -} // namespace zdl -#endif // PSNPE_HPP diff --git a/third_party/snpe/include/SNPE/RuntimeConfigList.hpp b/third_party/snpe/include/SNPE/RuntimeConfigList.hpp deleted file mode 100644 index 837dba092a1d21..00000000000000 --- a/third_party/snpe/include/SNPE/RuntimeConfigList.hpp +++ /dev/null @@ -1,85 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== -#ifndef PSNPE_RUNTIMECONFIGLIST_HPP -#define PSNPE_RUNTIMECONFIGLIST_HPP - -#include -#include "DlContainer/IDlContainer.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/RuntimeList.hpp" -#include "DlSystem/TensorShapeMap.hpp" -#include "DlSystem/ZdlExportDefine.hpp" -namespace zdl { -namespace PSNPE { - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * The structure for configuring a BulkSNPE runtime - * - */ -struct ZDL_EXPORT RuntimeConfig final { - zdl::DlSystem::Runtime_t runtime; - zdl::DlSystem::RuntimeList runtimeList; - zdl::DlSystem::PerformanceProfile_t perfProfile; - zdl::DlSystem::TensorShapeMap inputDimensionsMap; - bool enableCPUFallback; - RuntimeConfig() - : runtime{zdl::DlSystem::Runtime_t::CPU_FLOAT32}, - perfProfile{zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE}, - enableCPUFallback{false} {} - RuntimeConfig(const RuntimeConfig& other) { - runtime = other.runtime; - runtimeList = other.runtimeList; - perfProfile = other.perfProfile; - enableCPUFallback = other.enableCPUFallback; - inputDimensionsMap = other.inputDimensionsMap; - } - - RuntimeConfig& operator=(const RuntimeConfig& other) { - this->runtimeList = other.runtimeList; - this->runtime = other.runtime; - this->perfProfile = other.perfProfile; - this->enableCPUFallback = other.enableCPUFallback; - this->inputDimensionsMap = other.inputDimensionsMap; - return *this; - } - - ~RuntimeConfig() {} -}; - -/** - * @brief . - * - * The class for creating a RuntimeConfig container. - * - */ -class ZDL_EXPORT RuntimeConfigList final { - public: - RuntimeConfigList(); - RuntimeConfigList(const size_t size); - void push_back(const RuntimeConfig& runtimeConfig); - RuntimeConfig& operator[](const size_t index); - RuntimeConfigList& operator=(const RuntimeConfigList& other); - size_t size() const noexcept; - size_t capacity() const noexcept; - void clear() noexcept; - ~RuntimeConfigList() = default; - - private: - void swap(const RuntimeConfigList& other); - std::vector m_runtimeConfigs; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // namespace PSNPE -} // namespace zdl -#endif // PSNPE_RUNTIMECONFIGLIST_HPP diff --git a/third_party/snpe/include/SNPE/SNPE.hpp b/third_party/snpe/include/SNPE/SNPE.hpp deleted file mode 100644 index 5ab45b82eedc85..00000000000000 --- a/third_party/snpe/include/SNPE/SNPE.hpp +++ /dev/null @@ -1,258 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _SNPE_SNPE_HPP_ -#define _SNPE_SNPE_HPP_ - -#include "DlSystem/DlOptional.hpp" -#include "DlSystem/DlVersion.hpp" -#include "DlSystem/IBufferAttributes.hpp" -#include "DlSystem/ITensor.hpp" -#include "DlSystem/TensorShape.hpp" -#include "DlSystem/TensorMap.hpp" -#include "DlSystem/String.hpp" -#include "DlSystem/StringList.hpp" -#include "DlSystem/IUserBuffer.hpp" -#include "DlSystem/UserBufferMap.hpp" -#include "DlSystem/UserMemoryMap.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl { - namespace SNPE - { - class SnpeRuntime; - } -} -namespace zdl { - namespace DiagLog - { - class IDiagLog; - } -} - -namespace zdl { namespace SNPE { -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * The SNPE interface class definition - */ -class ZDL_EXPORT SNPE final -{ -public: - - // keep this undocumented to be hidden in doxygen using HIDE_UNDOC_MEMBERS - explicit SNPE(std::unique_ptr&& runtime) noexcept; - ~SNPE(); - - /** - * @brief Gets the names of input tensors to the network - * - * To support multiple input scenarios, where multiple tensors are - * passed through execute() in a TensorMap, each tensor needs to - * be uniquely named. The names of tensors can be retrieved - * through this function. - * - * In the case of a single input, one name will be returned. - * - * @note Note that because the returned value is an Optional list, - * the list must be verified as boolean true value before being - * dereferenced. - * - * @return An Optional List of input tensor names. - * - * @see zdl::DlSystem::Optional - */ - zdl::DlSystem::Optional - getInputTensorNames() const noexcept; - - /** - * @brief Gets the names of output tensors to the network - * - * @return List of output tensor names. - */ - zdl::DlSystem::Optional - getOutputTensorNames() const noexcept; - - /** - * @brief Gets the name of output tensor from the input layer name - * - * @return Output tensor name. - */ - zdl::DlSystem::StringList - getOutputTensorNamesByLayerName(const char *name) const noexcept; - - /** - * @brief Processes the input data and returns the output - * - * @param[in] A map of tensors that contains the input data for - * each input. The names of tensors needs to be - * matched with names retrieved through - * getInputTensorNames() - * - * @param[in,out] An empty map of tensors that will contain the output - * data of potentially multiple layers (the key - * in the map is the layer name) upon return - * - * @note output tensormap has to be empty. To forward propagate - * and get results in user-supplied tensors, use - * executeWithSuppliedOutputTensors. - */ - bool execute(const zdl::DlSystem::TensorMap &input, - zdl::DlSystem::TensorMap &output) noexcept; - - /** - * @brief Processes the input data and returns the output - * - * @param[in] A single tensor contains the input data. - * - * @param[in,out] An empty map of tensors that will contain the output - * data of potentially multiple layers (the key - * in the map is the layer name) upon return - * - * @note output tensormap has to be empty. - */ - bool execute(const zdl::DlSystem::ITensor *input, - zdl::DlSystem::TensorMap &output) noexcept; - - /** - * @brief Processes the input data and returns the output, using - * user-supplied buffers - * - * @param[in] A map of UserBuffers that contains the input data for - * each input. The names of UserBuffers needs to be - * matched with names retrieved through - * getInputTensorNames() - * - * @param[in,out] A map of UserBuffers that will hold the output - * data of potentially multiple layers (the key - * in the map is the UserBuffer name) - * - * @note input and output UserBuffer maps must be fully pre-populated. with - * dimensions matching what the network expects. - * For example, if there are 5 output UserBuffers they all have to be - * present in map. - * - * Caller must guarantee that for the duration of execute(), the buffer - * stored in UserBuffer would remain valid. For more detail on buffer - * ownership and lifetime requirements, please refer to zdl::DlSystem::UserBuffer - * documentation. - */ - bool execute(const zdl::DlSystem::UserBufferMap &input, - const zdl::DlSystem::UserBufferMap &output) noexcept; - - - /** - * @brief Regiter Client ION Buffers - * @param[in] A UserMemoryMap of virtual addresses - * - */ - bool registerIonBuffers(const zdl::DlSystem::UserMemoryMap& ionBufferMap) noexcept; - - /** - * @brief Regiter Client ION Buffers - * @param[in] A StringList of ION Buffer names - * - */ - bool deregisterIonBuffers(const zdl::DlSystem::StringList& ionBufferNames) noexcept; - - /** - * @brief Returns the version string embedded at model conversion - * time. - * - * @return Model version string, which is a free-form string - * supplied at the time of the conversion - * - */ - zdl::DlSystem::String getModelVersion() const noexcept; - - /** - * @brief Returns the dimensions of the input data to the model in the - * form of TensorShape. The dimensions in TensorShape corresponds to - * what the tensor dimensions would need to be for an input tensor to - * the model. - * - * @param[in] layer input name. - * - * @note Note that this function only makes sense for networks - * that have a fixed input size. For networks in which the - * input size varies with each call of Execute(), this - * function should not be used. - * - * @note Because the returned type is an Optional instance, it must - * be verified as a boolean true value before being dereferenced. - * - * @return An Optional instance of TensorShape that maintains dimensions, - * matching the tensor dimensions for input to the model, - * where the last entry is the fastest varying dimension, etc. - * - * @see zdl::DlSystem::ITensor - * @see zdl::DlSystem::TensorShape - * @see zdl::DlSystem::Optional - */ - zdl::DlSystem::Optional - getInputDimensions() const noexcept; - zdl::DlSystem::Optional - getInputDimensions(const char *name) const noexcept; - - /** - * @brief Gets the output layer(s) for the network. - * - * Note that the output layers returned by this function may be - * different than those specified when the network was created - * via the zdl::SNPE::SNPEBuilder. For example, if the - * network was created in debug mode with no explicit output - * layers specified, this will contain all layers. - * - * @note Note that because the returned value is an Optional StringList, - * the list must be verified as a boolean true value before being - * dereferenced. - * - * @return A List of output layer names. - * - * @see zdl::DlSystem::Optional - */ - zdl::DlSystem::Optional - getOutputLayerNames() const noexcept; - - /** - * @brief Returns attributes of buffers used to feed input tensors and receive result from output tensors. - * - * @param[in] Tensor name. - * - * @return BufferAttributes of input/output tensor named - */ - zdl::DlSystem::Optional getInputOutputBufferAttributes(const char *name) const noexcept; - - /** - * @brief . - * - * Get the diagnostic logging interface - * - * @note Note that because the returned type is an Optional instance, - * it must be verified as a boolean true value before being - * dereferenced. - * - * @see zdl::DlSystem::Optional - */ - zdl::DlSystem::Optional - getDiagLogInterface() noexcept; - -private: - SNPE(const SNPE&) = delete; - SNPE& operator=(const SNPE&) = delete; - - std::unique_ptr m_Runtime; -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ -}} - -#endif diff --git a/third_party/snpe/include/SNPE/SNPEBuilder.hpp b/third_party/snpe/include/SNPE/SNPEBuilder.hpp deleted file mode 100644 index 5fc7846ced6486..00000000000000 --- a/third_party/snpe/include/SNPE/SNPEBuilder.hpp +++ /dev/null @@ -1,306 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2017-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _SNPE_BUILDER_HPP_ -#define _SNPE_BUILDER_HPP_ - -#include "SNPE/SNPE.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/UDLFunc.hpp" -#include "DlSystem/DlOptional.hpp" -#include "DlSystem/TensorShapeMap.hpp" -#include "DlSystem/PlatformConfig.hpp" -#include "DlSystem/IOBufferDataTypeMap.hpp" -#include "DlSystem/RuntimeList.hpp" - -namespace zdl { - namespace DlContainer - { - class IDlContainer; - } -} - -struct SNPEBuilderImpl; - - -namespace zdl { namespace SNPE { -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * The builder class for creating SNPE objects. - * Not meant to be extended. - */ -class ZDL_EXPORT SNPEBuilder final -{ -private: - std::unique_ptr<::SNPEBuilderImpl> m_Impl; -public: - - /** - * @brief Constructor of NeuralNetwork Builder with a supplied model. - * - * @param[in] container A container holding the model. - * - * @return A new instance of a SNPEBuilder object - * that can be used to configure and build - * an instance of SNPE. - * - */ - explicit SNPEBuilder( - zdl::DlContainer::IDlContainer* container); - ~SNPEBuilder(); - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. Please use - * setRuntimeProcessorOrder() - * - * @brief Sets the runtime processor. - * - * @param[in] targetRuntimeProcessor The target runtime. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setRuntimeProcessor( - zdl::DlSystem::Runtime_t targetRuntimeProcessor); - - /** - * @brief Requests a performance profile. - * - * @param[in] targetRuntimeProfile The target performance profile. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setPerformanceProfile( - zdl::DlSystem::PerformanceProfile_t performanceProfile); - - /** - * @brief Sets the profiling level. Default profiling level for - * SNPEBuilder is off. Off and basic only applies to DSP runtime. - * - * @param[in] profilingLevel The target profiling level. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setProfilingLevel( - zdl::DlSystem::ProfilingLevel_t profilingLevel); - - /** - * @brief Sets a preference for execution priority. - * - * This allows the caller to give coarse hint to SNPE runtime - * about the priority of the network. SNPE runtime is free to use - * this information to co-ordinate between different workloads - * that may or may not extend beyond SNPE. - * - * @param[in] ExecutionPriorityHint_t The target performance profile. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setExecutionPriorityHint( - zdl::DlSystem::ExecutionPriorityHint_t priority); - - /** - * @brief Sets the layers that will generate output. - * - * @param[in] outputLayerNames List of layer names to - * output. An empty list will - * result in only the final - * layer of the model being - * the output layer. The list - * will be copied. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setOutputLayers( - const zdl::DlSystem::StringList& outputLayerNames); - - /** - * @brief Sets the output tensor names. - * - * @param[in] outputTensorNames List of tensor names to - * output. An empty list will - * result in producing output for the final - * output tensor of the model. - * The list will be copied. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setOutputTensors( - const zdl::DlSystem::StringList& outputTensorNames); - - /** - * @brief Passes in a User-defined layer. - * - * @param udlBundle Bundle of udl factory function and a cookie - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setUdlBundle( - zdl::DlSystem::UDLBundle udlBundle); - - /** - * @brief Sets whether this neural network will perform inference with - * input from user-supplied buffers, and write output to user-supplied - * buffers. Default behaviour is to use tensors created by - * ITensorFactory. - * - * @param[in] bufferMode Whether to use user-supplied buffer or not. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setUseUserSuppliedBuffers( - bool bufferMode); - - /** - * @brief Sets the debug mode of the runtime. - * - * @param[in] debugMode This enables debug mode for the runtime. It - * does two things. For an empty - * outputLayerNames list, all layers will be - * output. It might also disable some internal - * runtime optimizations (e.g., some networks - * might be optimized by combining layers, - * etc.). - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setDebugMode( - bool debugMode); - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. Please use - * setRuntimeProcessorOrder() - * - * @brief Sets the mode of CPU fallback functionality. - * - * @param[in] mode This flag enables/disables the functionality - * of CPU fallback. When the CPU fallback - * functionality is enabled, layers in model that - * violates runtime constraints will run on CPU - * while the rest of non-violating layers will - * run on the chosen runtime processor. In - * disabled mode, models with layers violating - * runtime constraints will NOT run on the chosen - * runtime processor and will result in runtime - * exception. By default, the functionality is - * enabled. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setCPUFallbackMode( - bool mode); - - - /** - * @brief Sets network's input dimensions to enable resizing of - * the spatial dimensions of each layer for fully convolutional networks, - * and the batch dimension for all networks. - * - * @param[in] tensorShapeMap The map of input names and their new dimensions. - * The new dimensions overwrite the input dimensions - * embedded in the model and then resize each layer - * of the model. If the model contains - * layers whose dimensions cannot be resized e.g FullyConnected, - * exception will be thrown when SNPE instance is actually built. - * In general the batch dimension is always resizable. - * After resizing of layers' dimensions in model based - * on new input dimensions, the new model is revalidated - * against all runtime constraints, whose failures may - * result in cpu fallback situation. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setInputDimensions(const zdl::DlSystem::TensorShapeMap& inputDimensionsMap); - - /** - * @brief Sets the mode of init caching functionality. - * - * @param[in] mode This flag enables/disables the functionality of init caching. - * When init caching functionality is enabled, a set of init caches - * will be created during network building/initialization process - * and will be added to DLC container. If such DLC container is saved - * by the user, in subsequent network building/initialization processes - * these init caches will be loaded from the DLC so as to reduce initialization time. - * In disable mode, no init caches will be added to DLC container. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setInitCacheMode( - bool cacheMode); - - /** - * @brief Returns an instance of SNPE based on the current parameters. - * - * @return A new instance of a SNPE object that can be used - * to execute models or null if any errors occur. - */ - std::unique_ptr build() noexcept; - - /** - * @brief Sets the platform configuration. - * - * @param[in] platformConfig The platform configuration. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setPlatformConfig(const zdl::DlSystem::PlatformConfig& platformConfig); - - /** - * @brief Sets network's runtime order of precedence. Example: - * CPU_FLOAT32, GPU_FLOAT16, AIP_FIXED8_TF - * Note:- setRuntimeProcessor() or setCPUFallbackMode() will be silently ignored when - * setRuntimeProcessorOrder() is invoked - * - * @param[in] runtimeList The list of runtime in order of precedence - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setRuntimeProcessorOrder(const zdl::DlSystem::RuntimeList& runtimeList); - - /** - * @brief Sets the unconsumed tensors as output - * - * @param[in] setOutput This enables unconsumed tensors (i.e) - * outputs which are not inputs to any - * layer (basically dead ends) to be marked - * for output - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setUnconsumedTensorsAsOutputs( - bool setOutput); - - /** - * @brief Execution terminated when exceeding time limit. - * Only valid for dsp runtime currently. - * - * @param[in] timeout Time limit value - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setTimeOut( - uint64_t timeout); - - - /** - * @brief Sets the datatype of the buffer. - * Only valid for dsp runtime currently. - * - * @param[in] Map of the buffer names and the datatype that needs to be set. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setBufferDataType(const zdl::DlSystem::IOBufferDataTypeMap& dataTypeMap); - -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -}} - -#endif diff --git a/third_party/snpe/include/SNPE/SNPEFactory.hpp b/third_party/snpe/include/SNPE/SNPEFactory.hpp deleted file mode 100644 index 2d78e81b173d2c..00000000000000 --- a/third_party/snpe/include/SNPE/SNPEFactory.hpp +++ /dev/null @@ -1,220 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _SNPE_FACTORY_HPP_ -#define _SNPE_FACTORY_HPP_ - -#include "SNPE/SNPE.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/UDLFunc.hpp" -#include "DlSystem/ZdlExportDefine.hpp" -#include "DlSystem/DlOptional.hpp" - -namespace zdl { - namespace DlSystem - { - class ITensorFactory; - class IUserBufferFactory; - } - namespace DlContainer - { - class IDlContainer; - } -} - - - -namespace zdl { namespace SNPE { -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * The factory class for creating SNPE objects. - * - */ -class ZDL_EXPORT SNPEFactory -{ -public: - - /** - * Indicates whether the supplied runtime is available on the - * current platform. - * - * @param[in] runtime The target runtime to check. - * - * @return True if the supplied runtime is available; false, - * otherwise. - */ - static bool isRuntimeAvailable(zdl::DlSystem::Runtime_t runtime); - - /** - * Indicates whether the supplied runtime is available on the - * current platform. - * - * @param[in] runtime The target runtime to check. - * - * @param[in] option Extent to perform runtime available check. - * - * @return True if the supplied runtime is available; false, - * otherwise. - */ - static bool isRuntimeAvailable(zdl::DlSystem::Runtime_t runtime, - zdl::DlSystem::RuntimeCheckOption_t option); - - /** - * Gets a reference to the tensor factory. - * - * @return A reference to the tensor factory. - */ - static zdl::DlSystem::ITensorFactory& getTensorFactory(); - - /** - * Gets a reference to the UserBuffer factory. - * - * @return A reference to the UserBuffer factory. - */ - static zdl::DlSystem::IUserBufferFactory& getUserBufferFactory(); - - /** - * Gets the version of the SNPE library. - * - * @return Version of the SNPE library. - * - */ - static zdl::DlSystem::Version_t getLibraryVersion(); - - /** - * Set the SNPE storage location for all SNPE instances in this - * process. Note that this may only be called once, and if so - * must be called before creating any SNPE instances. - * - * @param[in] storagePath Absolute path to a directory which SNPE may - * use for caching and other storage purposes. - * - * @return True if the supplied path was succesfully set as - * the SNPE storage location, false otherwise. - */ - static bool setSNPEStorageLocation(const char* storagePath); - - /** - * @brief Register a user-defined op package with SNPE. - * - * @param[in] regLibraryPath Path to the registration library - * that allows clients to register a set of operations that are - * part of the package, and share op info with SNPE - * - * @return True if successful, False otherwise. - */ - static bool addOpPackage( const std::string& regLibraryPath ); - - /** - * Indicates whether the OpenGL and OpenCL interoperability is supported - * on GPU platform. - * - * @return True if the OpenGL and OpenCl interop is supported; false, - * otherwise. - */ - static bool isGLCLInteropSupported(); - - static const char* getLastError(); - - /** - * Initializes logging with the specified log level. - * initializeLogging with level, is used on Android platforms - * and after successful initialization, SNPE - * logs are printed in android logcat logs. - * - * It is recommended to initializeLogging before creating any - * SNPE instances, in order to capture information related to - * core initialization. If this is called again after first - * time initialization, subsequent calls are ignored. - * Also, Logging can be re-initialized after a call to - * terminateLogging API by calling initializeLogging again. - * - * A typical usage of Logging life cycle can be - * initializeLogging() - * any other SNPE API like isRuntimeAvailable() - * * setLogLevel() - optional - can be called anytime - * between initializeLogging & terminateLogging - * SNPE instance creation, inference, destroy - * terminateLogging(). - * - * Please note, enabling logging can have performance impact. - * - * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). - * - * @return True if successful, False otherwise. - */ - static bool initializeLogging(const zdl::DlSystem::LogLevel_t& level); - - /** - * Initializes logging with the specified log level and log path. - * initializeLogging with level & log path, is used on non Android - * platforms and after successful initialization, SNPE - * logs are printed in std output & into log files created in the - * log path. - * - * It is recommended to initializeLogging before creating any - * SNPE instances, in order to capture information related to - * core initialization. If this is called again after first - * time initialization, subsequent calls are ignored. - * Also, Logging can be re-initialized after a call to - * terminateLogging API by calling initializeLogging again. - * - * A typical usage of Logging life cycle can be - * initializeLogging() - * any other SNPE API like isRuntimeAvailable() - * * setLogLevel() - optional - can be called anytime - * between initializeLogging & terminateLogging - * SNPE instance creation, inference, destroy - * terminateLogging() - * - * Please note, enabling logging can have performance impact - * - * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). - * - * @param[in] Path of directory to store logs. - * If path is empty, the default path is "./Log". - * For android, the log path is ignored. - * - * @return True if successful, False otherwise. - */ - static bool initializeLogging(const zdl::DlSystem::LogLevel_t& level, const std::string& logPath); - - /** - * Updates the current logging level with the specified level. - * setLogLevel is optional, called anytime after initializeLogging - * and before terminateLogging, to update the log level set. - * Log levels can be updated multiple times by calling setLogLevel - * A call to setLogLevel() is ignored if it is made before - * initializeLogging() or after terminateLogging() - * - * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). - * - * @return True if successful, False otherwise. - */ - static bool setLogLevel(const zdl::DlSystem::LogLevel_t& level); - - /** - * Terminates logging. - * - * It is recommended to terminateLogging after initializeLogging - * in order to disable logging information. - * If this is called before initialization or after first time termination, - * calls are ignored. - * - * @return True if successful, False otherwise. - */ - static bool terminateLogging(void); -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ -}} - - -#endif diff --git a/third_party/snpe/include/SNPE/UserBufferList.hpp b/third_party/snpe/include/SNPE/UserBufferList.hpp deleted file mode 100644 index a660bca0f6a525..00000000000000 --- a/third_party/snpe/include/SNPE/UserBufferList.hpp +++ /dev/null @@ -1,49 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== -#ifndef PSNPE_USERBUFFERLIST_HPP -#define PSNPE_USERBUFFERLIST_HPP - -#include -#include "DlSystem/UserBufferMap.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl { -namespace PSNPE -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ -/** -* @brief . -* -* The class for creating a UserBufferMap container. -* -*/ -class ZDL_EXPORT UserBufferList final -{ -public: - UserBufferList(); - UserBufferList(const size_t size); - void push_back(const zdl::DlSystem::UserBufferMap &userBufferMap); - zdl::DlSystem::UserBufferMap& operator[](const size_t index); - UserBufferList& operator =(const UserBufferList &other); - size_t size() const noexcept; - size_t capacity() const noexcept; - void clear() noexcept; - ~UserBufferList() = default; - -private: - void swap(const UserBufferList &other); - std::vector m_userBufferMaps; - -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // namespace PSNPE -} // namespace zdl -#endif //PSNPE_USERBUFFERLIST_HPP diff --git a/third_party/snpe/include/SnpeUdo/UdoBase.h b/third_party/snpe/include/SnpeUdo/UdoBase.h deleted file mode 100644 index 7b2567920e3525..00000000000000 --- a/third_party/snpe/include/SnpeUdo/UdoBase.h +++ /dev/null @@ -1,537 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef SNPE_UDO_BASE_H -#define SNPE_UDO_BASE_H - -#include - -// Provide values to use for API version. -#define API_VERSION_MAJOR 1 -#define API_VERSION_MINOR 6 -#define API_VERSION_TEENY 0 - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -// Defines a bitmask of enum values. -typedef uint32_t SnpeUdo_Bitmask_t; -typedef SnpeUdo_Bitmask_t Udo_Bitmask_t; - -// A string of characters, rather than an array of bytes. -// Assumed to be UTF-8. -typedef char* SnpeUdo_String_t; -typedef SnpeUdo_String_t Udo_String_t; - -// The maximum allowable length of a SnpeUdo_String_t in bytes, -// including null terminator. SNPE will truncate strings longer -// than this. -#define SNPE_UDO_MAX_STRING_SIZE 1024 - -/** - * An enum which holds the various error types. - * The error types are divided to classes : - * 0 - 99 : generic errors - * 100 - 200 : errors related to configuration - * - */ -typedef enum -{ - /// No Error - SNPE_UDO_NO_ERROR = 0, UDO_NO_ERROR = 0, - /// Unsupported value for core type - SNPE_UDO_WRONG_CORE = 1, UDO_WRONG_CORE = 1, - /// Invalid attribute/argument passed into UDO API - SNPE_UDO_INVALID_ARGUMENT = 2, UDO_INVALID_ARGUMENT = 2, - /// Unsupported feature error - SNPE_UDO_UNSUPPORTED_FEATURE = 3, UDO_UNSUPPORTED_FEATURE = 3, - /// Error relating to memory allocation - SNPE_UDO_MEM_ALLOC_ERROR = 4, UDO_MEM_ALLOC_ERROR = 4, - /* Configuration Specific errors */ - /// No op with given attributes available in library - SNPE_UDO_WRONG_OPERATION = 100, UDO_WRONG_OPERATION = 100, - /// Unsupported value for core type in UDO configuration - SNPE_UDO_WRONG_CORE_TYPE = 101, UDO_WRONG_CORE_TYPE = 101, - /// Wrong number of params in UDO definition - SNPE_UDO_WRONG_NUM_OF_PARAMS = 102, UDO_WRONG_NUM_OF_PARAMS = 102, - /// Wrong number of dimensions for tensor(s) in UDO definition - SNPE_UDO_WRONG_NUM_OF_DIMENSIONS = 103, UDO_WRONG_NUM_OF_DIMENSIONS = 103, - /// Wrong number of input tensors in UDO definition - SNPE_UDO_WRONG_NUM_OF_INPUTS = 104, UDO_WRONG_NUM_OF_INPUTS = 104, - /// Wrong number of output tensors in UDO definition - SNPE_UDO_WRONG_NUM_OF_OUTPUTS = 105, UDO_WRONG_NUM_OF_OUTPUTS = 105, - SNPE_UDO_PROGRAM_CACHE_NOT_FOUND = 106, UDO_PROGRAM_CACHE_NOT_FOUND = 106, - SNPE_UDO_UNKNOWN_ERROR = 0xFFFFFFFF, UDO_UNKNOWN_ERROR = 0xFFFFFFFF -} SnpeUdo_ErrorType_t; - -typedef SnpeUdo_ErrorType_t Udo_ErrorType_t; - -/** - * An enum which holds the various data types. - * Designed to be used as single values or combined into a bitfield parameter - * (0x1, 0x2, 0x4, etc) - * \n FIXED_XX types are targeted for data in tensors. - * \n UINT / INT types are targeted for scalar params - */ -typedef enum -{ - /// data type: 16-bit floating point - SNPE_UDO_DATATYPE_FLOAT_16 = 0x01, UDO_DATATYPE_FLOAT_16 = 0x01, - /// data type: 32-bit floating point - SNPE_UDO_DATATYPE_FLOAT_32 = 0x02, UDO_DATATYPE_FLOAT_32 = 0x02, - /// data type: 4-bit fixed point - SNPE_UDO_DATATYPE_FIXED_4 = 0x04, UDO_DATATYPE_FIXED_4 = 0x04, - /// data type: 8-bit fixed point - SNPE_UDO_DATATYPE_FIXED_8 = 0x08, UDO_DATATYPE_FIXED_8 = 0x08, - /// data type: 16-bit fixed point - SNPE_UDO_DATATYPE_FIXED_16 = 0x10, UDO_DATATYPE_FIXED_16 = 0x10, - /// data type: 32-bit fixed point - SNPE_UDO_DATATYPE_FIXED_32 = 0x20, UDO_DATATYPE_FIXED_32 = 0x20, - /// data type: 8-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_8 = 0x100, UDO_DATATYPE_UINT_8 = 0x100, - /// data type: 16-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_16 = 0x200, UDO_DATATYPE_UINT_16 = 0x200, - /// data type: 32-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_32 = 0x400, UDO_DATATYPE_UINT_32 = 0x400, - /// data type: 8-bit signed integer - SNPE_UDO_DATATYPE_INT_8 = 0x1000, UDO_DATATYPE_INT_8 = 0x1000, - /// data type: 16-bit signed integer - SNPE_UDO_DATATYPE_INT_16 = 0x2000, UDO_DATATYPE_INT_16 = 0x2000, - /// data type: 32-bit signed integer - SNPE_UDO_DATATYPE_INT_32 = 0x4000, UDO_DATATYPE_INT_32 = 0x4000, - SNPE_UDO_DATATYPE_LAST = 0xFFFFFFFF, UDO_DATATYPE_LAST = 0xFFFFFFFF -} SnpeUdo_DataType_t; - -typedef SnpeUdo_DataType_t Udo_DataType_t; - -/** - * An enum which holds the various layouts. - * Designed to be used as single values or combined into a bitfield parameter - * (0x1, 0x2, 0x4, etc) - */ -typedef enum -{ - /// data layout (4D): NHWC (batch-height-width-channel) - SNPE_UDO_LAYOUT_NHWC = 0x01, UDO_LAYOUT_NHWC = 0x01, - /// data layout (4D): NCHW (batch-channel-height-width) - SNPE_UDO_LAYOUT_NCHW = 0x02, UDO_LAYOUT_NCHW = 0x02, - /// data layout (5D): NDHWC (batch-dimension-height-width-channel) - SNPE_UDO_LAYOUT_NDHWC = 0x04, UDO_LAYOUT_NDHWC = 0x04, - SNPE_UDO_LAYOUT_GPU_OPTIMAL1 = 0x08, UDO_LAYOUT_GPU_OPTIMAL1 = 0x08, - SNPE_UDO_LAYOUT_GPU_OPTIMAL2 = 0x10, UDO_LAYOUT_GPU_OPTIMAL2 = 0x10, - SNPE_UDO_LAYOUT_DSP_OPTIMAL1 = 0x11, UDO_LAYOUT_DSP_OPTIMAL1 = 0x11, - SNPE_UDO_LAYOUT_DSP_OPTIMAL2 = 0x12, UDO_LAYOUT_DSP_OPTIMAL2 = 0x12, - // Indicates no data will be allocated for this tensor. - // Used to specify optional inputs/outputs positionally. - SNPE_UDO_LAYOUT_NULL = 0x13, UDO_LAYOUT_NULL = 0x13, - SNPE_UDO_LAYOUT_LAST = 0xFFFFFFFF, UDO_LAYOUT_LAST = 0xFFFFFFFF -} SnpeUdo_TensorLayout_t; - -typedef SnpeUdo_TensorLayout_t Udo_TensorLayout_t; - -/** - * An enum which holds the UDO library Core type . - * Designed to be used as single values or combined into a bitfield parameter - * (0x1, 0x2, 0x4, etc) - */ -typedef enum -{ - /// Library target IP Core is undefined - SNPE_UDO_CORETYPE_UNDEFINED = 0x00, UDO_CORETYPE_UNDEFINED = 0x00, - /// Library target IP Core is CPU - SNPE_UDO_CORETYPE_CPU = 0x01, UDO_CORETYPE_CPU = 0x01, - /// Library target IP Core is GPU - SNPE_UDO_CORETYPE_GPU = 0x02, UDO_CORETYPE_GPU = 0x02, - /// Library target IP Core is DSP - SNPE_UDO_CORETYPE_DSP = 0x04, UDO_CORETYPE_DSP = 0x04, - SNPE_UDO_CORETYPE_LAST = 0xFFFFFFFF, UDO_CORETYPE_LAST = 0xFFFFFFFF -} SnpeUdo_CoreType_t; - -typedef SnpeUdo_CoreType_t Udo_CoreType_t; - -/** - * An enum to specify the parameter type : Scalar or Tensor - */ -typedef enum -{ - /// UDO static param type: scalar - SNPE_UDO_PARAMTYPE_SCALAR = 0x00, UDO_PARAMTYPE_SCALAR = 0x00, - /// UDO static param type: string - SNPE_UDO_PARAMTYPE_STRING = 0x01, UDO_PARAMTYPE_STRING = 0x01, - /// UDO static param type: tensor - SNPE_UDO_PARAMTYPE_TENSOR = 0x02, UDO_PARAMTYPE_TENSOR = 0x02, - SNPE_UDO_PARAMTYPE_LAST = 0xFFFFFFFF, UDO_PARAMTYPE_LAST = 0xFFFFFFFF -} SnpeUdo_ParamType_t; - -typedef SnpeUdo_ParamType_t Udo_ParamType_t; - -/** - * An enum to specify quantization type - */ -typedef enum -{ - /// Tensor Quantization type: NONE. Signifies unquantized tensor data - SNPE_UDO_QUANTIZATION_NONE = 0x00, UDO_QUANTIZATION_NONE = 0x00, - /// Tensor Quantization type: Tensorflow-style - SNPE_UDO_QUANTIZATION_TF = 0x01, UDO_QUANTIZATION_TF = 0x01, - SNPE_UDO_QUANTIZATION_QMN = 0x02, UDO_QUANTIZATION_QMN = 0x02, - SNPE_UDO_QUANTIZATION_LAST = 0xFFFFFFFF, UDO_QUANTIZATION_LAST = 0xFFFFFFFF -} SnpeUdo_QuantizationType_t; - -typedef SnpeUdo_QuantizationType_t Udo_QuantizationType_t; - -/** - * @brief A struct which is used to provide a version number using 3 values : major, minor, teeny - * - */ -typedef struct -{ - /// version field: major - for backward-incompatible changes - uint32_t major; - /// version field: minor - for backward-compatible feature updates - uint32_t minor; - /// version field: teeny - for minor bug-fixes and clean-up - uint32_t teeny; -} SnpeUdo_Version_t; - -typedef SnpeUdo_Version_t Udo_Version_t; - -/** - * @brief A struct returned from version query, contains the Library version and API version - * - */ -typedef struct -{ - /// Version of UDO library. Controlled by users - SnpeUdo_Version_t libVersion; - /// Version of SNPE UDO API used in compiling library. Determined by SNPE - SnpeUdo_Version_t apiVersion; -} SnpeUdo_LibVersion_t; - -/** - * @brief A struct returned from version query, contains the package version - * - */ -typedef struct -{ - /// Version of UDO API used in package. - Udo_Version_t apiVersion; -} Udo_PkgVersion_t; - -/** - * @brief A union to hold the value of a generic type. Allows defining a parameter struct - * in a generic way, with a "value" location that holds the data regardless of the type. - * - */ -typedef union -{ - /// value type: float - float floatValue; - /// value type: unsigned 32-bit integer - uint32_t uint32Value; - /// value type: signed 32-bit integer - int32_t int32Value; - /// value type: unsigned 16-bit integer - uint16_t uint16Value; - /// value type: signed 16-bit integer - int16_t int16Value; - /// value type: unsigned 8-bit integer - uint8_t uint8Value; - /// value type: signed 8-bit integer - int8_t int8Value; -} SnpeUdo_Value_t; - -typedef SnpeUdo_Value_t Udo_Value_t; - -/** - * @brief A struct which defines a scalar parameter : name, data type, and union of values - * - */ -typedef struct -{ - /// The parameter data type : float, int, etc. - SnpeUdo_DataType_t dataType; - /// a union of specified type which holds the data - SnpeUdo_Value_t dataValue; -} SnpeUdo_ScalarParam_t; - -typedef SnpeUdo_ScalarParam_t Udo_ScalarParam_t; - -/** - * @brief A struct which defines the quantization parameters in case of Tensorflow style quantization - * - */ -typedef struct -{ - /// minimum value of the quantization range of data - float minValue; - /// maximum value of the quantization range of data - float maxValue; -} SnpeUdo_TFQuantize_t; - -typedef SnpeUdo_TFQuantize_t Udo_TFQuantize_t; - -/** - * @brief A struct which defines the quantization type, and union of supported quantization structs - * - */ -typedef struct -{ - /// quantization type (only TF-style currently supported) - SnpeUdo_QuantizationType_t quantizeType; - union - { - /// TF-style min-max quantization ranges - SnpeUdo_TFQuantize_t TFParams; - }; -} SnpeUdo_QuantizeParams_t; - -typedef SnpeUdo_QuantizeParams_t Udo_QuantizeParams_t; - -/** - * @brief A struct which defines the datatype associated with a specified core-type - * This should be used to denote the datatypes for a single tensor info, depending - * on the intended execution core. - * - */ -typedef struct -{ - /// The IP Core - SnpeUdo_CoreType_t coreType; - /// The associated datatype for this coreType - SnpeUdo_DataType_t dataType; -} SnpeUdo_PerCoreDatatype_t; - -typedef SnpeUdo_PerCoreDatatype_t Udo_PerCoreDatatype_t; - -/** - * @brief A struct which defines a tensor parameter : name, data type, layout, quantization, more. - * Also holds a pointer to the tensor data. - * - */ -typedef struct -{ - /// The maximum allowable dimensions of the tensor. The memory held in - /// _tensorData_ is guaranteed to be large enough for this. - uint32_t* maxDimensions; - /// The current dimensions of the tensor. An operation may modify the current - /// dimensions of its output, to indicate cases where the output has been - /// "resized". - /// Note that for static parameters, the current and max dimensions must - /// match. - uint32_t* currDimensions; - /// Quantization params applicable to the tensor. Currently only supports - /// Tensorflow quantization style. - SnpeUdo_QuantizeParams_t quantizeParams; - /// Number of dimensions to the tensor: 3D, 4D, etc. - uint32_t tensorRank; - /// The parameter data type: float, int, etc. - SnpeUdo_DataType_t dataType; - /// The tensor layout type: NCHW, NHWC, etc. - SnpeUdo_TensorLayout_t layout; - /// Opaque pointer to tensor data. User may be required to re-interpret the pointer - /// based on core-specific definitions. - void* tensorData; -} SnpeUdo_TensorParam_t; - -typedef SnpeUdo_TensorParam_t Udo_TensorParam_t; - -/** - * @brief A struct which defines tensor information for activation tensors only - * - * It describes an activation tensor object using its name, the intended layout and the datatype - * it will take depending on the intended runtime core. The repeated field indicates that - * that the tensor info describes several input/output activation tensors, which all share the - * aforementioned properties. - */ -typedef struct -{ - /// The tensor name - SnpeUdo_String_t tensorName; - /// The tensor layout type: NCHW, NHWC, etc. - SnpeUdo_TensorLayout_t layout; - /// The per core datatype: {SNPE_UDO_DATATYPE, SNPE_UDO_CORE_TYPE} - SnpeUdo_PerCoreDatatype_t* perCoreDatatype; - /// A boolean field indicating that this tensorinfo will be repeated e.x for ops such as Concat or Split - bool repeated; - /// A boolean field indicating whether input is static or not. - bool isStatic; -} SnpeUdo_TensorInfo_t; - -typedef SnpeUdo_TensorInfo_t Udo_TensorInfo_t; - -/** - * @brief struct which defines a UDO parameter - a union of scalar, tensor and string parameters - * - */ -typedef struct -{ - /// Type is scalar or tensor - SnpeUdo_ParamType_t paramType; - /// The param name, for example : "offset", "activation_type" - SnpeUdo_String_t paramName; - union - { - /// scalar param value - SnpeUdo_ScalarParam_t scalarParam; - /// tensor param value - SnpeUdo_TensorParam_t tensorParam; - /// string param value - SnpeUdo_String_t stringParam; - }; -} SnpeUdo_Param_t; - -typedef SnpeUdo_Param_t Udo_Param_t; - -/** - * @brief A struct which defines Operation information which is specific for IP core (CPU, GPU, DSP ...) - * - */ -typedef struct -{ - /// The IP Core - SnpeUdo_CoreType_t udoCoreType; - /// Bitmask, defines supported internal calculation types (like FLOAT_32, etc) - /// Based on SnpeUdo_DataType - SnpeUdo_Bitmask_t operationCalculationTypes; -} SnpeUdo_OpCoreInfo_t; - -typedef SnpeUdo_OpCoreInfo_t Udo_OpCoreInfo_t; - -/** - * @brief A struct which defines the common and core-specific Operation information - * - */ -typedef struct -{ - /// Operation type - SnpeUdo_String_t operationType; - /// A bitmask describing which IP Cores (CPU, GPU, DSP ...) support this operation - /// Translated based on SnpeUdo_CoreType - SnpeUdo_Bitmask_t supportedByCores; - /// Number of static parameters defined by the op - uint32_t numOfStaticParams; - /// Array of static parameters. Can be scalar or tensor params - SnpeUdo_Param_t* staticParams; - /// Number of input tensors this op receives - uint32_t numOfInputs; - /// Array of input tensor names to this operation - SnpeUdo_String_t* inputNames; - /// Number of output tensors this op receives - uint32_t numOfOutputs; - /// Array of output tensor names to this operation - SnpeUdo_String_t* outputNames; - /// Number of cores that the op can execute on - uint32_t numOfCoreInfo; - /// Array of per-core information entries - SnpeUdo_OpCoreInfo_t* opPerCoreInfo; - /// Array of input tensor infos for this operation - SnpeUdo_TensorInfo_t* inputInfos; - /// Array of output tensor infos for this operation - SnpeUdo_TensorInfo_t* outputInfos; -} SnpeUdo_OperationInfo_t; - -typedef SnpeUdo_OperationInfo_t Udo_OperationInfo_t; - -/** - * @brief A struct which provides the implementation library info : type, name - * - */ -typedef struct -{ - /// Defines the IP Core that this implementation library is targeting - SnpeUdo_CoreType_t udoCoreType; - /// library name. will be looked at in the standard library path - SnpeUdo_String_t libraryName; -} SnpeUdo_LibraryInfo_t; - -typedef SnpeUdo_LibraryInfo_t Udo_LibraryInfo_t; - -/** - * @brief A struct returned by the registration library and contains information on the UDO package : - * name, operations, libraries, etc. - * - */ -typedef struct -{ - /// A string containing the package name - SnpeUdo_String_t packageName; - /// A bitmask describing supported IP cores (CPU, GPU, DSP ...) - /// Translated based on SnpeUdo_CoreType - SnpeUdo_Bitmask_t supportedCoreTypes; - /// The number of implementation libraries in the package - uint32_t numOfImplementationLib; - /// Array of implementation libraries names/types - SnpeUdo_LibraryInfo_t* implementationLib; - /// A string containing all operation types separated by space - SnpeUdo_String_t operationsString; - /// Number of supported operations - uint32_t numOfOperations; - /// Array of Operation info structs. Each entry describes one - /// Operation (name, params, inputs, outputs) - SnpeUdo_OperationInfo_t* operationsInfo; -} SnpeUdo_RegInfo_t; - -typedef SnpeUdo_RegInfo_t Udo_RegInfo_t; - -/** -* @brief A struct returned by the implementation library and contains information on the -* specific library: name, IP Core, operations, etc. -* -*/ -typedef struct -{ - /// Defines the IP Core that this implementation library is targeting - SnpeUdo_CoreType_t udoCoreType; - /// A string containing the package name - SnpeUdo_String_t packageName; - /// A string containing all operation types separated by space - SnpeUdo_String_t operationsString; - /// Number of supported operations - uint32_t numOfOperations; -} SnpeUdo_ImpInfo_t; - -typedef SnpeUdo_ImpInfo_t Udo_ImpInfo_t; - -/** - * @brief This struct defines an operation. It is used for validation - * or creation of an operation. - * In case of using it for creation, the static params which are tensors - * contain pointers to the real data (weights, for example), and input/output - * tensors also include pointers to the buffers used. - */ -typedef struct -{ - /// The IP Core that the operation is defined for - CPU, GPU, DSP... - SnpeUdo_CoreType_t udoCoreType; - /// Operation type - SnpeUdo_String_t operationType; - /// The number of static parameters provided in the staticParams array. - /// this number has to match the number provided by the UDO Registration library information - uint32_t numOfStaticParams; - /// Array of static parameters - SnpeUdo_Param_t* staticParams; - /// The number of input parameters provided in inputs array. - /// this number has to match the number provided by the UDO Registration library information - uint32_t numOfInputs; - /// Array of input tensors, providing layout, data type, sizes, etc - /// When used to create an operation, also contains the initial location of the data - SnpeUdo_TensorParam_t* inputs; - /// The number of output parameters provided in inputs array. - /// this number has to match the number provided by the UDO Registration library information - uint32_t numOfOutputs; - /// Array of output tensors, providing layout, data type, sizes, etc - /// When used to create an operation, also contains the initial location of the data - SnpeUdo_TensorParam_t* outputs; -} SnpeUdo_OpDefinition_t; - -typedef SnpeUdo_OpDefinition_t Udo_OpDefinition_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif //SNPE_UDO_BASE_H diff --git a/third_party/snpe/include/SnpeUdo/UdoImpl.h b/third_party/snpe/include/SnpeUdo/UdoImpl.h deleted file mode 100644 index a0cb648cf725f8..00000000000000 --- a/third_party/snpe/include/SnpeUdo/UdoImpl.h +++ /dev/null @@ -1,343 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef SNPE_UDO_IMPL_H -#define SNPE_UDO_IMPL_H - -#include - -#include "SnpeUdo/UdoShared.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -typedef struct _SnpeUdo_OpFactory_t* SnpeUdo_OpFactory_t; -typedef struct _SnpeUdo_Operation_t* SnpeUdo_Operation_t; - -typedef SnpeUdo_OpFactory_t Udo_OpFactory_t; -typedef SnpeUdo_Operation_t Udo_Operation_t; - -/** - * @brief Initialize the shared library's data structures. Calling any other - * library function before this one will result in error. - * - * @param[in] globalInfrastructure Global core-specific infrastructure to be - * used by operations created in this library. The definition and - * semantics of this object will be defined in the corresponding - * implementation header for the core type. - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_initImplLibrary(void* globalInfrastructure); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_InitImplLibraryFunction_t)(void*); - -/** - * @brief A function to query the API version of the UDO implementation library. - * The function populates a SnpeUdo_LibVersion_t struct, which contains a SnpeUdo_Version_t - * struct for API version and library version. - * - * @param[in, out] version A pointer to struct which contains major, minor, teeny information for - * library and api versions. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_getImplVersion(SnpeUdo_LibVersion_t** version); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_getImplVersion_t)(SnpeUdo_LibVersion_t** version); - -/** - * @brief Release the shared library's data structures, and invalidate any - * handles returned by the library. The behavior of any outstanding - * asynchronous calls made to this library when this function is called - * are undefined. All library functions (except SnpeUdo_initImplLibrary) will - * return an error after this function has been successfully called. - * - * It should be possible to call SnpeUdo_initImplLibrary after calling this - * function, and re-initialize the library. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_terminateImplLibrary(void); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_TerminateImplLibraryFunction_t)(void); - - -/** - * @brief A function to query info on the UDO implementation library. - * The function populates a structure which contains information about - * operations that are part of this library - * - * @param[in, out] implementationInfo A pointer to struct which contains information - * on the operations - * - * @return error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_getImpInfo(SnpeUdo_ImpInfo_t** implementationInfo); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_GetImpInfoFunction_t)(SnpeUdo_ImpInfo_t** implementationInfo); - -typedef SnpeUdo_GetImpInfoFunction_t Udo_GetImpInfoFunction_t; - -/** - * @brief A function to create an operation factory. - * The function receives the operation type, and an array of static parameters, - * and returns operation factory handler - * - * @param[in] udoCoreType The Core type to create the operation on. An error will - * be returned if this does not match the core type of the library. - * - * @param[in] perFactoryInfrastructure CreateOpFactory infrastructure appropriate to this - * core type. The definition and semantics of this object will be defined - * in the corresponding implementation header for the core type. - * - * @param[in] operationType A string containing Operation type. for example "MY_CONV" - * - * @param[in] numOfStaticParams The number of static parameters. - * - * @param[in] staticParams Array of static parameters - * - * @param[in,out] opFactory Handler to Operation Factory, to be used when creating operations - * - * @return Error Code - */ -SnpeUdo_ErrorType_t -SnpeUdo_createOpFactory(SnpeUdo_CoreType_t udoCoreType, - void* perFactoryInfrastructure, - SnpeUdo_String_t operationType, - uint32_t numOfStaticParams, - SnpeUdo_Param_t* staticParams, - SnpeUdo_OpFactory_t* opFactory); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_CreateOpFactoryFunction_t)(SnpeUdo_CoreType_t, - void*, - SnpeUdo_String_t, - uint32_t, - SnpeUdo_Param_t*, - SnpeUdo_OpFactory_t*); - -typedef SnpeUdo_CreateOpFactoryFunction_t Udo_CreateOpFactoryFunction_t; - -/** - * @brief A function to release the resources allocated for an operation factory - * created by this library. - * - * @param[in] factory The operation factory to release. Upon success this handle will be invalidated. - * - * @return Error Code - */ -SnpeUdo_ErrorType_t -SnpeUdo_releaseOpFactory(SnpeUdo_OpFactory_t opFactory); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ReleaseOpFactoryFunction_t)(SnpeUdo_OpFactory_t); - -typedef SnpeUdo_ReleaseOpFactoryFunction_t Udo_ReleaseOpFactoryFunction_t; - -/** - * @brief A function to create an operation from the factory. - * The function receives array of inputs and array of outputs, and creates an operation - * instance, returning the operation instance handler. - * - * @param[in] opFactory OpFactory instance containing the parameters for this operation. - * - * @param[in] perOpInfrastructure Per-Op infrastructure for this operation. The definition - * and semantics of this object will be defined in the implementation header - * appropriate to this core type. - * - * @param[in] numOfInputs The number of input tensors this operation will receive. - * - * @param[in] inputs Array of input tensors, providing both the sizes and initial - * location of the data. - * - * @param[in] numOfOutputs Number of output tensors this operation will produce. - * - * @param[in] outputs Array of output tensors, providing both the sizes and - * initial location of the data. - * - * @param[in,out] operation Handle for newly created operation instance. - * - * @return Error Code - */ -SnpeUdo_ErrorType_t -SnpeUdo_createOperation(SnpeUdo_OpFactory_t opFactory, - void* perOpInfrastructure, - uint32_t numOfInputs, - SnpeUdo_TensorParam_t* inputs, - uint32_t numOfOutputs, - SnpeUdo_TensorParam_t* outputs, - SnpeUdo_Operation_t* operation); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_CreateOperationFunction_t)(SnpeUdo_OpFactory_t, - void*, - uint32_t, - SnpeUdo_TensorParam_t*, - uint32_t, - SnpeUdo_TensorParam_t*, - SnpeUdo_Operation_t*); - -typedef SnpeUdo_CreateOperationFunction_t Udo_CreateOperationFunction_t; - -/** - * @brief A pointer to notification function. - * - * The notification function supports the non-blocking (e.g. asynchronous) execution use-case. - * In case an "executeUdoOp" function is called with "blocking" set to zero, and a - * notify function, this function will be called by the implementation library at the - * end of execution. The implementation library will pass the notify function the ID - * that was provided to it when "executeUdoOp" was called. - * - * @param[in] ID 32-bit value, that was provided to executeUdoOp by the calling entity. - * Can be used to track the notifications, in case of multiple execute calls issued. - * - * @return Error code - * - */ -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ExternalNotify_t)(const uint32_t ID); - -typedef SnpeUdo_ExternalNotify_t Udo_ExternalNotify_t; - -/** - * @brief Operation execution function. - * - * Calling this function will run the operation on set of inputs, generating a set of outputs. - * The call can be blocking (synchronous) or non-blocking (asynchronous). To support the - * non-blocking mode, the calling entity can pass an ID and a notification function. - * At the end of the execution this notification function would be called, passing it the ID. - * NOTE: Asynchronous execution mode not supported in this release. - * - * @param[in] operation handle to the operation on which execute is invoked - * @param[in] blocking flag to indicate execution mode. - * If set, execution is blocking, - * e.g SnpeUdo_executeOp call does not return until execution is done. - * If not set, SnpeUdo_executeOp returns immediately, and the - * library will call the notification function (if set) when execution is done. - * - * @param[in] ID 32-bit number that can be used by the calling entity to track execution - * in case of non-blocking execution. - * For example, it can be a sequence number, increased by one on each call. - * - * @param[in] notifyFunc Pointer to notification function. if the pointer is set, and execution is - * non-blocking, the library will call this function at end of execution, - * passing the number provided as ID - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_executeOp(SnpeUdo_Operation_t operation, - bool blocking, - const uint32_t ID, - SnpeUdo_ExternalNotify_t notifyFunc); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ExecuteOpFunction_t)(SnpeUdo_Operation_t, - bool, - const uint32_t, - SnpeUdo_ExternalNotify_t); - -typedef SnpeUdo_ExecuteOpFunction_t Udo_ExecuteOpFunction_t; - -/** - * @brief A function to setting the inputs & outputs. part of SnpeUdo_Operation struct, - * returned from creation of a new operation instance. - * Not supported in this release. - * - * This function allows the calling entity to change some of the inputs and outputs - * between calls to execute. - * Note that the change is limited to changing the pointer to the tensor data only. - * Any other change may be rejected by the implementation library, causing - * immediate invalidation of the operation instance - * - * @param[in] operation Operation on which IO tensors are set - * - * @param[in] inputs array of tensor parameters. The calling entity may provide a subset of the - * operation inputs, providing only those that it wants to change. - * - * @param[in] outputs array of tensor parameters. The calling entity may provide a subset of the - * operation outputs, providing only those that it wants to change. - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_setOpIO(SnpeUdo_Operation_t operation, - SnpeUdo_TensorParam_t* inputs, - SnpeUdo_TensorParam_t* outputs); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_SetOpIOFunction_t)(SnpeUdo_Operation_t, - SnpeUdo_TensorParam_t*, - SnpeUdo_TensorParam_t*); - -typedef SnpeUdo_SetOpIOFunction_t Udo_SetOpIOFunction_t; - -/** - * @brief A function to return execution times. - * - * This function can be called to query the operation execution times on the IP core - * on which the operation is run. The time is provided in micro-seconds - * - * @param[in] operation Handle to operation whose execution time is being profiled - * - * @param[in,out] executionTime pointer to a uint32 value.This function writes the operation - * execution time in usec into this value. - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_profileOp(SnpeUdo_Operation_t operation, uint32_t *executionTime); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ProfileOpFunction_t)(SnpeUdo_Operation_t, uint32_t*); - -typedef SnpeUdo_ProfileOpFunction_t Udo_ProfileOpFunction_t; - -/** - * @brief A function to release the operation instance - * \n When it is called, the implementation library needs to release all resources - * allocated for this operation instance. - * \n Note that all function pointers which are part of SnpeUdo_Operation become - * invalid once releaseUdoOp call returns. - * - * @param[in] operation Handle to operation to be released - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_releaseOp(SnpeUdo_Operation_t operation); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ReleaseOpFunction_t)(SnpeUdo_Operation_t); - -typedef SnpeUdo_ReleaseOpFunction_t Udo_ReleaseOpFunction_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif //SNPE_UDO_IMPL_H diff --git a/third_party/snpe/include/SnpeUdo/UdoImplCpu.h b/third_party/snpe/include/SnpeUdo/UdoImplCpu.h deleted file mode 100644 index 3bbe0638e60fc8..00000000000000 --- a/third_party/snpe/include/SnpeUdo/UdoImplCpu.h +++ /dev/null @@ -1,44 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -// Header to be used by a CPU UDO Implementation library - -#ifndef SNPE_UDO_IMPL_CPU_H -#define SNPE_UDO_IMPL_CPU_H - -#include - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief This struct provides the infrastructure needed by a developer of - * CPU UDO Implementation library. - * - * The framework/runtime which loads the CPU UDO implementation library provides - * this infrastructure data to the loaded library at the time of op factory creation. - * as an opaque pointer. It contains hooks for the UDO library to invoke supported - * functionality at the time of execution - * - * @param getData function pointer to retrieve raw tensor data from opaque pointer - * passed into the UDO when creating an instance. - * @param getDataSize function pointer to retrieve tensor data size from opaque pointer - */ - -typedef struct -{ - /// function pointer to retrieve raw tensor data from opaque pointer - /// passed into the UDO when creating an instance. - float* (*getData)(void*); - /// function pointer to retrieve tensor data size from opaque pointer - size_t (*getDataSize) (void*); -} SnpeUdo_CpuInfrastructure_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // SNPE_UDO_IMPL_CPU_H \ No newline at end of file diff --git a/third_party/snpe/include/SnpeUdo/UdoImplDsp.h b/third_party/snpe/include/SnpeUdo/UdoImplDsp.h deleted file mode 100644 index b97a6493202ae8..00000000000000 --- a/third_party/snpe/include/SnpeUdo/UdoImplDsp.h +++ /dev/null @@ -1,207 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -//============================================================================== -/* - * THIS HEADER FILE IS COPIED FROM HEXAGON-NN PROJECT - * - */ -//============================================================================== - - -// Header to be used by a DSP Hexnn UDO Implementation library - -#ifndef SNPE_UDO_IMPL_DSP_H -#define SNPE_UDO_IMPL_DSP_H -#include -#include "SnpeUdo/UdoImpl.h" - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief A function to validate that a set of params is supported by an operation - * This function is HexNN specific, use case is when registration library is not in use. - * Optional function. - * - * @param[in] operationType Operation type - * @param[in] numOfStaticParams Number of static params defined by the op - * @param[in] staticParams Array of static params to the op - * @return Error code, indicating if the operation can be created on this set of configuration or not. - * - */ - -SnpeUdo_ErrorType_t -SnpeUdo_validateOperation (SnpeUdo_String_t operationType, - uint32_t numOfStaticParams, - const SnpeUdo_Param_t* staticParams); - -typedef SnpeUdo_ErrorType_t (*SnpeUdo_ValidateOperationFunction_t) (SnpeUdo_String_t, - uint32_t, - const SnpeUdo_Param_t*); - -typedef SnpeUdo_ValidateOperationFunction_t Udo_ValidateOperationFunction_t; - -// enum used for indicating input/outout tensor data layouts on DSP, plain vs d32 -typedef enum { - SNPE_UDO_DSP_TENSOR_LAYOUT_PLAIN = 0x00, UDO_DSP_TENSOR_LAYOUT_PLAIN = 0x00, - SNPE_UDO_DSP_TENSOR_LAYOUT_D32 = 0x01, UDO_DSP_TENSOR_LAYOUT_D32 = 0x01 -} SnpeUdo_HexNNTensorLayout_t; - -typedef SnpeUdo_HexNNTensorLayout_t Udo_HexNNTensorLayout_t; - -/** - * @brief A function to query numbers of inputs and outputs, - * quantization type of each input and each output as arrays, - * and data layout (plain vs d32) of each input and each output as arrays - * of an operation. - * inputsQuantTypes and inputsLayouts should point to arrays of size numOfInputs - * outputsQuantTypes and outputsLayouts should point to arrays of size numOfOutputs - * - * Note: inputsLayouts and inputsLayouts can point to NULL, in this case, it is - * assumed all inputs and/or outputs have plain data layouts, i.e. no D32 - * - * @param[in] operationType Operation type - * @param[in] numOfStaticParams Number of static params defined by the op - * @param[in] staticParams Array of static params to the op - * @param[in,out] numOfInputs Number of input tensors to the op - * @param[in,out] inputsQuantTypes Array of Quantization info for each input tensor - * @param[in,out] inputsLayouts Array of layout type for each input tensor - * @param[in,out] numOfOutputs Number of output tensors to the op - * @param[in,out] outputsQuantTypes Array of Quantization info for each output tensor - * @param[in,out] outputsLayouts Array of layout type for each output tensor - * @return error code, indicating status of query - */ - -SnpeUdo_ErrorType_t -SnpeUdo_queryOperation (SnpeUdo_String_t operationType, - uint32_t numOfStaticParams, - const SnpeUdo_Param_t* staticParams, - uint32_t* numOfInputs, - SnpeUdo_QuantizationType_t** inputsQuantTypes, - SnpeUdo_HexNNTensorLayout_t** inputsLayouts, - uint32_t* numOfOutputs, - SnpeUdo_QuantizationType_t** outputsQuantTypes, - SnpeUdo_HexNNTensorLayout_t** outputsLayouts); - -typedef SnpeUdo_ErrorType_t (*SnpeUdo_QueryOperationFunction_t) (SnpeUdo_String_t, - uint32_t, - const SnpeUdo_Param_t*, - uint32_t*, - SnpeUdo_QuantizationType_t**, - SnpeUdo_HexNNTensorLayout_t**, - uint32_t*, - SnpeUdo_QuantizationType_t**, - SnpeUdo_HexNNTensorLayout_t**); - -typedef SnpeUdo_QueryOperationFunction_t Udo_QueryOperationFunction_t; - -// Global infrastructure functions supported by Hexagon-NN v2 -typedef void (*workerThread_t) (void* perOpInfrastructure, void* userData); -typedef int (*udoSetOutputTensorSize_t) (void* perOpInfrastructure, uint32_t outIdx, uint32_t size); -typedef int (*udoGetInputD32Paddings_t) (void* perOpInfrastructure, uint32_t inIdx, - uint32_t* heightPadBefore, uint32_t* heightPadAfter, - uint32_t* widthPadBefore, uint32_t* widthPadAfter, - uint32_t* depthPadBefore, uint32_t* depthPadAfter); -typedef int (*udoSetOutputD32ShapeSizePaddings_t) (void* perOpInfrastructure, uint32_t outIdx, - uint32_t batch, - uint32_t height, uint32_t heightPadBefore, uint32_t heightPadAfter, - uint32_t width, uint32_t widthPadBefore, uint32_t widthPadAfter, - uint32_t depth, uint32_t depthPadBefore, uint32_t depthPadAfter, - SnpeUdo_DataType_t dataType); -typedef void* (*udoMemalign_t) (size_t n, size_t size); -typedef void* (*udoMalloc_t) (size_t size); -typedef void* (*udoCalloc_t) (size_t n, size_t size); -typedef void (*udoFree_t) (void* ptr); -typedef uint32_t (*udoGetVtcmSize_t) (void* perOpInfrastructure); -typedef void* (*udoGetVtcmPtr_t) (void* perOpInfrastructure); -typedef uint32_t (*udoVtcmIsReal_t) (void* perOpInfrastructure); -typedef void (*udoRunWorkerThreads_t) (void* perOpInfrastructure, uint32_t nThreads, workerThread_t w, void* userData); - -typedef struct hexNNv2GlobalInfra { - udoSetOutputTensorSize_t udoSetOutputTensorSize; - udoGetInputD32Paddings_t udoGetInputD32Paddings; - udoSetOutputD32ShapeSizePaddings_t udoSetOutputD32ShapeSizePaddings; - udoMemalign_t udoMemalign; - udoMalloc_t udoMalloc; - udoCalloc_t udoCalloc; - udoFree_t udoFree; - udoGetVtcmSize_t udoGetVtcmSize; - udoGetVtcmPtr_t udoGetVtcmPtr; - udoVtcmIsReal_t udoVtcmIsReal; - udoRunWorkerThreads_t udoRunWorkerThreads; -} SnpeUdo_HexNNv2GlobalInfra_t; - -typedef SnpeUdo_HexNNv2GlobalInfra_t Udo_HexNNv2GlobalInfra_t; - -// hexnn types -typedef enum hexnnInfraType { - UDO_INFRA_HEXNN_V2, - UDO_INFRA_HEXNN_V3 // reserved, do not use -} SnpeUdo_HexNNInfraType_t; - -typedef SnpeUdo_HexNNInfraType_t Udo_HexNNInfraType_t; - -typedef struct { - Udo_CreateOpFactoryFunction_t create_op_factory; - Udo_CreateOperationFunction_t create_operation; - Udo_ExecuteOpFunction_t execute_op; - Udo_ReleaseOpFunction_t release_op; - Udo_ReleaseOpFactoryFunction_t release_op_factory; - Udo_ValidateOperationFunction_t validate_op; - Udo_QueryOperationFunction_t query_op; -} udo_func_package_t; - -/** - * @brief Infrastructures needed by a developer of DSP Hexnn UDO Implementation library. - * - * The framework/runtime which loads the Hexnn UDO implementation library provides - * this infrastructure to the loaded library by calling "SnpeUdo_initImplLibrary" - * function, and passing it (cast to void*). The Hexnn UDO library is expected - * to cast it back to this structure. - * - */ -typedef struct dspGlobalInfrastructure { - SnpeUdo_Version_t dspInfraVersion; // api version - SnpeUdo_HexNNInfraType_t infraType; - SnpeUdo_HexNNv2GlobalInfra_t hexNNv2Infra; -} SnpeUdo_DspGlobalInfrastructure_t; - -typedef SnpeUdo_DspGlobalInfrastructure_t Udo_DspGlobalInfrastructure_t; - -/** - * hexnn v2 per op factory infrastructure - * - * The framework/runtime passes per op factory infrastructure as a void pointer - * to HexNN UDO implementation library by calling function "SnpeUdo_createOpFactory". - * UDO implementation library is expected to cast it back to this following struct. - * - */ -typedef struct hexnnv2OpFactoryInfra { - unsigned long graphId; -} SnpeUdo_HexNNv2OpFactoryInfra_t; - -typedef SnpeUdo_HexNNv2OpFactoryInfra_t Udo_HexNNv2OpFactoryInfra_t; - -/** - * hexnn v2 per operation infrastructure - * - * The framework/runtime passes per operation infrastructure as a void pointer - * to HexNN UDO implementation library by calling function "SnpeUdo_createOperation". - * UDO implementation library is expected to cast it to the following type and save it. - * - * This is needed to be passed back into some functions from global infrastructure. - * - */ -typedef void* SnpeUdo_HexNNv2OpInfra_t; - -typedef SnpeUdo_HexNNv2OpInfra_t Udo_HexNNv2OpInfra_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // SNPE_UDO_IMPL_DSP_H diff --git a/third_party/snpe/include/SnpeUdo/UdoImplGpu.h b/third_party/snpe/include/SnpeUdo/UdoImplGpu.h deleted file mode 100644 index 1af654d110c26b..00000000000000 --- a/third_party/snpe/include/SnpeUdo/UdoImplGpu.h +++ /dev/null @@ -1,112 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -// Header to be used by a GPU UDO Implementation library - -#ifndef SNPE_UDO_IMPL_GPU_H -#define SNPE_UDO_IMPL_GPU_H - -#include "CL/cl.h" -#include "SnpeUdo/UdoBase.h" - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * This header defines version 0.0.0 of the GPU UDO Infrastructure. - * It defines the interpretation of the global and per-OpFactory infrastructure pointers - * as well as the interpretation of tensorData pointers. - * - * The per-Operation infrastructure pointer is defined to be null, and should not be used. - * - * The SnpeUdoTensorParam_t struct below provides the interpretation for - * the tensorData opaque pointer for SnpeUdoTensorParams representing inputs or outputs. - * - * The tensorData opaque pointer populated in SnpeUdoScalarParam_t structs should be interpreted - * as a host-readable data pointer. - * - */ - -/** - * @brief Function to retrieve opencl program from Program Cache repository. - * @param programCache is opaque pointer to Program Cache repository provided by - * SNPE GPU UDO runtime. - * @param programName is name associated with opencl program for UDO. - * @param program is pointer to opencl program which will be populated with - * valid opencl program if found in Program Cache repository. - * @return SnpeUdo_ErrorType_t is error type returned. SNPE_UDO_NO_ERROR is returned - * on success. - */ -typedef SnpeUdo_ErrorType_t (*SnpeUdo_getProgram_t) - (void* programCache, const char* programName, cl_program* program); - -/** - * @brief Function to store valid opencl program in Program Cache repository. - * @param programCache is opaque pointer to Program Cache repository provided by - * SNPE GPU UDO runtime. - * @param programName is name associated with opencl program for UDO. - * @param program is valid opencl program after program is built. - * @return SnpeUdo_ErrorType_t is error type returned. SNPE_UDO_NO_ERROR is returned - * on success. - * */ -typedef SnpeUdo_ErrorType_t (*SnpeUdo_storeProgram_t) - (void* programCache, const char * programName, cl_program program); - -/** - * @brief Global Infrastructure Definition for GPU UDO Implementations. - */ -typedef struct { - // Infrastructure definition version. This header is 0.0.0 - SnpeUdo_Version_t gpuInfraVersion; - SnpeUdo_getProgram_t SnpeUdo_getProgram; - SnpeUdo_storeProgram_t SnpeUdo_storeProgram; -} SnpeUdo_GpuInfrastructure_t; - -/** - * @brief Per OpFactory Infrastructure Definition for GPU UDO Implementations. - * @note This version of the infrastructure definition guarantees that the same - * Per OpFactory infrastructure pointer will be provided to all OpFactories - * in the same network. - */ -typedef struct -{ - cl_context context; - cl_command_queue commandQueue; - void* programCache; -} SnpeUdo_GpuOpFactoryInfrastructure_t; - -/** - * @brief Opaque tensorData definition for operation inputs and outputs. - * - * The following is a list of all SnpeUdoTensorLayout_t values supported by the - * GPU UDO implementation, and how the parameters of the struct should be - * interpreted in each case: - * - * SNPE_UDO_LAYOUT_NHWC: - * mem shall be single-element array, pointing to a cl buffer memory object. - * the dimensions of this object match the dimensions specified in the encompassing - * SnpeUdoTensorParam_t's currDimensions. - * - * memCount shall be 1. - * - * paddedRank and paddedDimensions are undefined and shall be ignored by the UDO - * implementation. - * - */ -typedef struct -{ - cl_mem* mem; - uint32_t memCount; - uint32_t paddedRank; - uint32_t* paddedDimensions; - -} SnpeUdo_GpuTensorData_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // SNPE_UDO_IMPL_GPU_H diff --git a/third_party/snpe/include/SnpeUdo/UdoReg.h b/third_party/snpe/include/SnpeUdo/UdoReg.h deleted file mode 100644 index a5d239883355ab..00000000000000 --- a/third_party/snpe/include/SnpeUdo/UdoReg.h +++ /dev/null @@ -1,108 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef SNPE_UDO_REG_H -#define SNPE_UDO_REG_H - -#include "SnpeUdo/UdoShared.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief Initialize the shared library's data structures. Calling any other - * library function before this one will result in an error being returned. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_initRegLibrary(void); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_InitRegLibraryFunction_t)(void); - -/** - * @brief A function to query the API version of the UDO registration library. - * The function populates a SnpeUdo_LibVersion_t struct, which contains a SnpeUdo_Version_t - * struct for API version and library version. - * - * @param[in, out] version A pointer to struct which contains major, minor, teeny information for - * library and api versions. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_getRegLibraryVersion(SnpeUdo_LibVersion_t** version); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_getRegLibraryVersion_t)(SnpeUdo_LibVersion_t** version); - -/** - * @brief Release the shared library's data structures, and invalidate any - * handles returned by the library. The behavior of any outstanding - * asynchronous calls made to this library when this function is called - * are undefined. All library functions (except SnpeUdo_InitRegLibrary) will - * return an error after this function has been successfully called. - * - * It should be possible to call SnpeUdo_InitRegLibrary after calling this - * function, and re-initialize the library. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_terminateRegLibrary(void); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_TerminateRegLibraryFunction_t)(void); - - -/** - * @brief A function to query the info on the UDO set. - * The function populates a structure which contains information about - * the package and operations contained in it. - * - * @param[in, out] registrationInfo A struct which contains information on the set of UDOs - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_getRegInfo(SnpeUdo_RegInfo_t** registrationInfo); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_GetRegInfoFunction_t)(SnpeUdo_RegInfo_t** registrationInfo); - -/** - * @brief A function to validate that a set of params is supported by an operation - * The function receives an operation definition struct, and returns if this configuration is - * supported (e.g. if an operation can be created using this configuration) - * - * @param[in] opDefinition A struct of SnpeUdo_OpDefinition type, containing the information needed to - * validate that an operation can be created with this configuration. - * - * @return Error code, indicating is the operation can be created on this set or not. - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_validateOperation(SnpeUdo_OpDefinition_t* opDefinition); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ValidateOperationFunction_t)(SnpeUdo_OpDefinition_t* opDefinition); - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif //SNPE_UDO_REG_H diff --git a/third_party/snpe/include/SnpeUdo/UdoShared.h b/third_party/snpe/include/SnpeUdo/UdoShared.h deleted file mode 100644 index 418d9db9e2f91b..00000000000000 --- a/third_party/snpe/include/SnpeUdo/UdoShared.h +++ /dev/null @@ -1,48 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef SNPE_UDO_SHARED_H -#define SNPE_UDO_SHARED_H - -#include "SnpeUdo/UdoBase.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief A function to return the various versions as they relate to the UDO - * The function returns a struct containing the the following: - * libVersion: the version of the implementation library compiled for the UDO. Set by user - * apiVersion: the version of the UDO API used in compiling the implementation library. - * Set by SNPE - * - * @param[in, out] version A pointer to Version struct of type SnpeUdo_LibVersion_t - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_getVersion (SnpeUdo_LibVersion_t** version); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_GetVersionFunction_t) (SnpeUdo_LibVersion_t** version); - -typedef SnpeUdo_GetVersionFunction_t Udo_GetVersionFunction_t; - -#ifdef __cplusplus -} // extern "C" -#endif - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // SNPE_UDO_SHARED_H diff --git a/third_party/snpe/larch64 b/third_party/snpe/larch64 deleted file mode 120000 index 2e2a1c315bf7d8..00000000000000 --- a/third_party/snpe/larch64 +++ /dev/null @@ -1 +0,0 @@ -aarch64-ubuntu-gcc7.5 \ No newline at end of file diff --git a/third_party/snpe/x86_64 b/third_party/snpe/x86_64 deleted file mode 120000 index 700025efab335e..00000000000000 --- a/third_party/snpe/x86_64 +++ /dev/null @@ -1 +0,0 @@ -x86_64-linux-clang \ No newline at end of file diff --git a/third_party/snpe/x86_64-linux-clang/libHtpPrepare.so b/third_party/snpe/x86_64-linux-clang/libHtpPrepare.so deleted file mode 100644 index 20d1377a014366..00000000000000 --- a/third_party/snpe/x86_64-linux-clang/libHtpPrepare.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c4c33680010a8c7b2eef33e809844c0ad1d5ab0f0ec37abd49d924204670b357 -size 13556072 diff --git a/third_party/snpe/x86_64-linux-clang/libSNPE.so b/third_party/snpe/x86_64-linux-clang/libSNPE.so deleted file mode 100644 index 0367b1106ba571..00000000000000 --- a/third_party/snpe/x86_64-linux-clang/libSNPE.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:024891d2e4e4e265a1e7e72b27bad41ee6ae077d2197f45959bb32f8071dc8cf -size 5350008 diff --git a/third_party/snpe/x86_64-linux-clang/libomp.so b/third_party/snpe/x86_64-linux-clang/libomp.so deleted file mode 100755 index db98cba162e784..00000000000000 --- a/third_party/snpe/x86_64-linux-clang/libomp.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f4784aa68e7ebdbe97db732eab87618b0a5fb73abeab4daed5476e01829b0e6e -size 759208 diff --git a/tinygrad_repo b/tinygrad_repo index ae5d1407ee844a..eecd4706fffe3a 160000 --- a/tinygrad_repo +++ b/tinygrad_repo @@ -1 +1 @@ -Subproject commit ae5d1407ee844a97a52ad3756835d38e7e2b9e1b +Subproject commit eecd4706fffe3ad8bdd7350e8db52d86d7214be2 diff --git a/tools/CTF.md b/tools/CTF.md index a14a41d55da106..32891cd389a0fc 100644 --- a/tools/CTF.md +++ b/tools/CTF.md @@ -11,7 +11,7 @@ Welcome to the first part of the comma CTF! getting started ```bash -# start the route reply +# start the route replay cd tools/replay ./replay '0c7f0c7f0c7f0c7f|2021-10-13--13-00-00' --dcam --ecam diff --git a/tools/README.md b/tools/README.md index 7f5c6b4d06df06..1ea42bbe1d129f 100644 --- a/tools/README.md +++ b/tools/README.md @@ -4,67 +4,41 @@ openpilot is developed and tested on **Ubuntu 24.04**, which is the primary development target aside from the [supported embedded hardware](https://github.com/commaai/openpilot#running-on-a-dedicated-device-in-a-car). -Running natively on any other system is not recommended and will require modifications. On Windows you can use WSL, and on macOS or incompatible Linux systems, it is recommended to use the dev containers. +Most of openpilot should work natively on macOS. On Windows you can use WSL for a nearly native Ubuntu experience. Running natively on any other system is not currently recommended and will likely require modifications. -## Native setup on Ubuntu 24.04 +## Native setup on Ubuntu 24.04 and macOS -**1. Clone openpilot** - -NOTE: This repository uses Git LFS for large files. Ensure you have [Git LFS](https://git-lfs.com/) installed and set up before cloning or working with it. - -Either do a partial clone for faster download: -``` bash -git clone --filter=blob:none --recurse-submodules --also-filter-submodules https://github.com/commaai/openpilot.git -``` +Follow these instructions for a fully managed setup experience. If you'd like to manage the dependencies yourself, just read the setup scripts in this directory. -or do a full clone: +**1. Clone openpilot** ``` bash -git clone --recurse-submodules https://github.com/commaai/openpilot.git +git clone https://github.com/commaai/openpilot.git ``` **2. Run the setup script** - ``` bash cd openpilot -tools/ubuntu_setup.sh -``` - -**3. Git LFS** - -``` bash -git lfs pull +tools/op.sh setup ``` -**4. Activate a python shell** - +**3. Activate a Python shell** Activate a shell with the Python dependencies installed: ``` bash source .venv/bin/activate ``` -**5. Build openpilot** - +**4. Build openpilot** ``` bash -scons -u -j$(nproc) +scons -u ``` -## Dev Container on any Linux or macOS - -openpilot supports [Dev Containers](https://containers.dev/). Dev containers provide customizable and consistent development environment wrapped inside a container. This means you can develop in a designated environment matching our primary development target, regardless of your local setup. - -Dev containers are supported in [multiple editors and IDEs](https://containers.dev/supporting), including Visual Studio Code. Use the following [guide](https://code.visualstudio.com/docs/devcontainers/containers) to start using them with VSCode. - -#### X11 forwarding on macOS - -GUI apps like `ui` or `cabana` can also run inside the container by leveraging X11 forwarding. To make use of it on macOS, additional configuration steps must be taken. Follow [these](https://gist.github.com/sorny/969fe55d85c9b0035b0109a31cbcb088) steps to setup X11 forwarding on macOS. - ## WSL on Windows [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/en-us/windows/wsl/about) should provide a similar experience to native Ubuntu. [WSL 2](https://docs.microsoft.com/en-us/windows/wsl/compare-versions) specifically has been reported by several users to be a seamless experience. Follow [these instructions](https://docs.microsoft.com/en-us/windows/wsl/install) to setup the WSL and install the `Ubuntu-24.04` distribution. Once your Ubuntu WSL environment is setup, follow the Linux setup instructions to finish setting up your environment. See [these instructions](https://learn.microsoft.com/en-us/windows/wsl/tutorials/gui-apps) for running GUI apps. -**NOTE**: If you are running WSL and any GUIs are failing (segfaulting or other strange issues) even after following the steps above, you may need to enable software rendering with `LIBGL_ALWAYS_SOFTWARE=1`, e.g. `LIBGL_ALWAYS_SOFTWARE=1 selfdrive/ui/ui`. +**NOTE**: If you are running WSL 2 and experiencing performance issues with the UI or simulator, you may need to explicitly enable hardware acceleration by setting `GALLIUM_DRIVER=d3d12` before commands. Add `export GALLIUM_DRIVER=d3d12` to your `~/.bashrc` file to make it automatic for future sessions. ## CTF Learn about the openpilot ecosystem and tools by playing our [CTF](/tools/CTF.md). @@ -72,8 +46,6 @@ Learn about the openpilot ecosystem and tools by playing our [CTF](/tools/CTF.md ## Directory Structure ``` -├── ubuntu_setup.sh # Setup script for Ubuntu -├── mac_setup.sh # Setup script for macOS ├── cabana/ # View and plot CAN messages from drives or in realtime ├── camerastream/ # Cameras stream over the network ├── joystick/ # Control your car with a joystick diff --git a/tools/auto_source.py b/tools/auto_source.py new file mode 100755 index 00000000000000..bef6a43e5323f7 --- /dev/null +++ b/tools/auto_source.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import sys +from openpilot.tools.lib.logreader import LogReader, ReadMode + + +def main(): + if len(sys.argv) != 2: + print("Usage: python auto_source.py ") + sys.exit(1) + + log_path = sys.argv[1] + lr = LogReader(log_path, default_mode=ReadMode.AUTO, sort_by_time=True) + print("\n".join(lr.logreader_identifiers)) + + +if __name__ == "__main__": + main() diff --git a/tools/bodyteleop/.gitignore b/tools/bodyteleop/.gitignore deleted file mode 100644 index adeab99a95e722..00000000000000 --- a/tools/bodyteleop/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -av -av-10.0.0/* -key.pem -cert.pem \ No newline at end of file diff --git a/tools/bodyteleop/static/index.html b/tools/bodyteleop/static/index.html index 365476975625c1..48672dbbf0c16b 100644 --- a/tools/bodyteleop/static/index.html +++ b/tools/bodyteleop/static/index.html @@ -15,29 +15,23 @@

comma body

- -
-
-
-
-
- - - -
-

body

+
+
+
+
+
W
-
-
- - -
-

you

+
+
A
+
S
+
D
-
+
+
+
@@ -53,43 +47,6 @@
- -
-
-
-
-
-
W
-
0,0x,y
-
-
-
A
-
S
-
D
-
-
-
- - - - -
-
-
-
-
-
-

Play Sounds

-
-
- - - -
-
diff --git a/tools/bodyteleop/static/js/controls.js b/tools/bodyteleop/static/js/controls.js index b1e0e7ee70e340..3a11f78b9efada 100644 --- a/tools/bodyteleop/static/js/controls.js +++ b/tools/bodyteleop/static/js/controls.js @@ -18,37 +18,3 @@ export const handleKeyX = (key, setValue) => { $("#pos-vals").text(x+","+y); } }; - -export async function executePlan() { - let plan = $("#plan-text").val(); - const planList = []; - plan.split("\n").forEach(function(e){ - let line = e.split(",").map(k=>parseInt(k)); - if (line.length != 5 || line.slice(0, 4).map(e=>[1, 0].includes(e)).includes(false) || line[4] < 0 || line[4] > 10){ - console.log("invalid plan"); - } - else{ - planList.push(line) - } - }); - - async function execute() { - for (var i = 0; i < planList.length; i++) { - let [w, a, s, d, t] = planList[i]; - while(t > 0){ - console.log(w, a, s, d, t); - if(w==1){$("#key-w").mousedown();} - if(a==1){$("#key-a").mousedown();} - if(s==1){$("#key-s").mousedown();} - if(d==1){$("#key-d").mousedown();} - await sleep(50); - $("#key-w").mouseup(); - $("#key-a").mouseup(); - $("#key-s").mouseup(); - $("#key-d").mouseup(); - t = t - 0.05; - } - } - } - execute(); -} \ No newline at end of file diff --git a/tools/bodyteleop/static/js/jsmain.js b/tools/bodyteleop/static/js/jsmain.js index 83205a876bd4c2..0db1dcd9b3084d 100644 --- a/tools/bodyteleop/static/js/jsmain.js +++ b/tools/bodyteleop/static/js/jsmain.js @@ -1,5 +1,5 @@ -import { handleKeyX, executePlan } from "./controls.js"; -import { start, stop, lastChannelMessageTime, playSoundRequest } from "./webrtc.js"; +import { handleKeyX } from "./controls.js"; +import { start, stop, lastChannelMessageTime } from "./webrtc.js"; export var pc = null; export var dc = null; @@ -8,12 +8,6 @@ document.addEventListener('keydown', (e)=>(handleKeyX(e.key.toLowerCase(), 1))); document.addEventListener('keyup', (e)=>(handleKeyX(e.key.toLowerCase(), 0))); $(".keys").bind("mousedown touchstart", (e)=>handleKeyX($(e.target).attr('id').replace('key-', ''), 1)); $(".keys").bind("mouseup touchend", (e)=>handleKeyX($(e.target).attr('id').replace('key-', ''), 0)); -$("#plan-button").click(executePlan); -$(".sound").click((e)=>{ - const sound = $(e.target).attr('id').replace('sound-', '') - return playSoundRequest(sound); -}); - setInterval( () => { const dt = new Date().getTime(); if ((dt - lastChannelMessageTime) > 1000) { diff --git a/tools/bodyteleop/static/js/webrtc.js b/tools/bodyteleop/static/js/webrtc.js index 165a2ce6c4b9bc..28bea238e62614 100644 --- a/tools/bodyteleop/static/js/webrtc.js +++ b/tools/bodyteleop/static/js/webrtc.js @@ -15,15 +15,6 @@ export function offerRtcRequest(sdp, type) { } -export function playSoundRequest(sound) { - return fetch('/sound', { - body: JSON.stringify({sound}), - headers: {'Content-Type': 'application/json'}, - method: 'POST' - }); -} - - export function pingHeadRequest() { return fetch('/', { method: 'HEAD' @@ -38,20 +29,18 @@ export function createPeerConnection(pc) { pc = new RTCPeerConnection(config); - // connect audio / video + // connect video pc.addEventListener('track', function(evt) { console.log("Adding Tracks!") if (evt.track.kind == 'video') document.getElementById('video').srcObject = evt.streams[0]; - else - document.getElementById('audio').srcObject = evt.streams[0]; }); return pc; } export function negotiate(pc) { - return pc.createOffer({offerToReceiveAudio:true, offerToReceiveVideo:true}).then(function(offer) { + return pc.createOffer({offerToReceiveVideo:true}).then(function(offer) { return pc.setLocalDescription(offer); }).then(function() { return new Promise(function(resolve) { @@ -90,14 +79,6 @@ function isMobile() { export const constraints = { - audio: { - autoGainControl: false, - sampleRate: 48000, - sampleSize: 16, - echoCancellation: true, - noiseSuppression: true, - channelCount: 1 - }, video: isMobile() }; @@ -105,23 +86,8 @@ export const constraints = { export function start(pc, dc) { pc = createPeerConnection(pc); - // add audio track - navigator.mediaDevices.enumerateDevices() - .then(function(devices) { - const hasAudioInput = devices.find((device) => device.kind === "audioinput"); - var modifiedConstraints = {}; - modifiedConstraints.video = constraints.video; - modifiedConstraints.audio = hasAudioInput ? constraints.audio : false; - - return Promise.resolve(modifiedConstraints); - }) - .then(function(constraints) { - if (constraints.audio || constraints.video) { - return navigator.mediaDevices.getUserMedia(constraints); - } else{ - return Promise.resolve(null); - } - }) + // add a local video track on mobile + (constraints.video ? navigator.mediaDevices.getUserMedia(constraints) : Promise.resolve(null)) .then(function(stream) { if (stream) { stream.getTracks().forEach(function(track) { diff --git a/tools/bodyteleop/static/main.css b/tools/bodyteleop/static/main.css index 1bfb5982b4ec98..79fe8052ff9cb7 100644 --- a/tools/bodyteleop/static/main.css +++ b/tools/bodyteleop/static/main.css @@ -172,13 +172,6 @@ video { display: none; } -.plan-form { - display: flex; - flex-direction: column; - justify-content: space-between; - align-items: center; -} - .details { display: flex; padding: 0px 10px 0px 10px; diff --git a/tools/bodyteleop/web.py b/tools/bodyteleop/web.py index fd8f691d199ee8..d357561b22d254 100644 --- a/tools/bodyteleop/web.py +++ b/tools/bodyteleop/web.py @@ -1,4 +1,3 @@ -import asyncio import dataclasses import json import logging @@ -6,8 +5,6 @@ import ssl import subprocess -import pyaudio -import wave from aiohttp import web from aiohttp import ClientSession @@ -22,35 +19,6 @@ WEBRTCD_HOST, WEBRTCD_PORT = "localhost", 5001 -## UTILS -async def play_sound(sound: str): - SOUNDS = { - "engage": "selfdrive/assets/sounds/engage.wav", - "disengage": "selfdrive/assets/sounds/disengage.wav", - "error": "selfdrive/assets/sounds/warning_immediate.wav", - } - assert sound in SOUNDS - - chunk = 5120 - with wave.open(os.path.join(BASEDIR, SOUNDS[sound]), "rb") as wf: - def callback(in_data, frame_count, time_info, status): - data = wf.readframes(frame_count) - return data, pyaudio.paContinue - - p = pyaudio.PyAudio() - stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), - channels=wf.getnchannels(), - rate=wf.getframerate(), - output=True, - frames_per_buffer=chunk, - stream_callback=callback) - stream.start_stream() - while stream.is_active(): - await asyncio.sleep(0) - stream.stop_stream() - stream.close() - p.terminate() - ## SSL def create_ssl_cert(cert_path: str, key_path: str): try: @@ -86,17 +54,9 @@ async def ping(request: 'web.Request'): return web.Response(text="pong") -async def sound(request: 'web.Request'): - params = await request.json() - sound_to_play = params["sound"] - - await play_sound(sound_to_play) - return web.json_response({"status": "ok"}) - - async def offer(request: 'web.Request'): params = await request.json() - body = StreamRequestBody(params["sdp"], ["driver"], ["testJoystick"], ["carState"]) + body = StreamRequestBody(params["sdp"], "driver", ["testJoystick"], ["carState"]) body_json = json.dumps(dataclasses.asdict(body)) logger.info("Sending offer to webrtcd...") @@ -109,16 +69,15 @@ async def offer(request: 'web.Request'): def main(): # Enable joystick debug mode - Params().put_bool("JoystickDebugMode", True) + Params().put_bool("JoystickDebugMode", True, block=True) - # App needs to be HTTPS for microphone and audio autoplay to work on the browser + # App needs to be HTTPS for WebRTC to work on the browser ssl_context = create_ssl_context() app = web.Application() app.router.add_get("/", index) app.router.add_get("/ping", ping, allow_head=True) app.router.add_post("/offer", offer) - app.router.add_post("/sound", sound) app.router.add_static('/static', os.path.join(TELEOPDIR, 'static')) web.run_app(app, access_log=None, host="0.0.0.0", port=5000, ssl_context=ssl_context) diff --git a/tools/cabana/.gitignore b/tools/cabana/.gitignore index 362a51f5c9231d..927b05e34abf0f 100644 --- a/tools/cabana/.gitignore +++ b/tools/cabana/.gitignore @@ -1,6 +1,9 @@ moc_* *.moc +*.generated.qrc -cabana +assets.cc + +_cabana dbc/car_fingerprint_to_dbc.json tests/test_cabana diff --git a/tools/cabana/README.md b/tools/cabana/README.md index 27829979c05c93..a721b1aa13ba76 100644 --- a/tools/cabana/README.md +++ b/tools/cabana/README.md @@ -12,13 +12,15 @@ Options: -h, --help Displays help on commandline options. --help-all Displays help including Qt specific options. --demo use a demo route instead of providing your own + --auto Auto load the route from the best available source (no video): + internal, openpilotci, comma_api, car_segments, testing_closet --qcam load qcamera --ecam load wide road camera - --stream read can messages from live streaming + --msgq read can messages from msgq --panda read can messages from panda --panda-serial read can messages from panda with given serial --socketcan read can messages from given SocketCAN device - --zmq the ip address on which to receive zmq + --zmq read can messages from zmq at the specified ip-address messages --data_dir local directory with routes --no-vipc do not output video @@ -43,17 +45,17 @@ cabana --demo To load a specific route for replay, provide the route as an argument: ```shell -cabana "a2a0ccea32023010|2023-07-27--13-01-19" +cabana "5beb9b58bd12b691/0000010a--a51155e496" ``` -Replace "0ccea32023010|2023-07-27--13-01-19" with your desired route identifier. +Replace "5beb9b58bd12b691/0000010a--a51155e496" with your desired route identifier. ### Running Cabana with multiple cameras To run Cabana with multiple cameras, use the following command: ```shell -cabana "a2a0ccea32023010|2023-07-27--13-01-19" --dcam --ecam +cabana "5beb9b58bd12b691/0000010a--a51155e496" --dcam --ecam ``` ### Streaming CAN Messages from a comma Device @@ -68,7 +70,7 @@ cd /data/openpilot/cereal/messaging/ Then Run Cabana with the device's IP address: ```shell -cabana --stream +cabana --zmq ``` Replace <ipaddress> with your comma device's IP address. diff --git a/tools/cabana/SConscript b/tools/cabana/SConscript index 74dc4d9f50ee0a..04389a9ebf30ad 100644 --- a/tools/cabana/SConscript +++ b/tools/cabana/SConscript @@ -1,36 +1,113 @@ -Import('qt_env', 'arch', 'common', 'messaging', 'visionipc', 'replay_lib', 'cereal', 'widgets') +import subprocess +import os +import shutil + +import bootstrap_icons +import libusb + +Import('env', 'arch', 'common', 'messaging', 'visionipc', 'cereal', 'replay_lib') + +# Detect Qt - skip build if not available +if arch == "Darwin": + try: + brew_prefix = subprocess.check_output(['brew', '--prefix'], encoding='utf8').strip() + has_qt = os.path.isdir(os.path.join(brew_prefix, "opt/qt@5")) + except (FileNotFoundError, subprocess.CalledProcessError): + has_qt = False +else: + has_qt = shutil.which('qmake') is not None +if not has_qt: + Return() + +qt_env = env.Clone() +qt_modules = ["Widgets", "Gui", "Core"] + +qt_libs = [] +if arch == "Darwin": + qt_env['QTDIR'] = f"{brew_prefix}/opt/qt@5" + qt_dirs = [ + os.path.join(qt_env['QTDIR'], "include"), + ] + qt_dirs += [f"{qt_env['QTDIR']}/include/Qt{m}" for m in qt_modules] + qt_env["LINKFLAGS"] += ["-F" + os.path.join(qt_env['QTDIR'], "lib")] + qt_env["FRAMEWORKS"] += [f"Qt{m}" for m in qt_modules] + ["OpenGL"] + qt_env.AppendENVPath('PATH', os.path.join(qt_env['QTDIR'], "bin")) +else: + qt_install_prefix = subprocess.check_output(['qmake', '-query', 'QT_INSTALL_PREFIX'], encoding='utf8').strip() + qt_install_headers = subprocess.check_output(['qmake', '-query', 'QT_INSTALL_HEADERS'], encoding='utf8').strip() + + qt_env['QTDIR'] = qt_install_prefix + qt_dirs = [ + f"{qt_install_headers}", + ] + + qt_gui_path = os.path.join(qt_install_headers, "QtGui") + qt_gui_dirs = [d for d in os.listdir(qt_gui_path) if os.path.isdir(os.path.join(qt_gui_path, d))] + qt_dirs += [f"{qt_install_headers}/QtGui/{qt_gui_dirs[0]}/QtGui", ] if qt_gui_dirs else [] + qt_dirs += [f"{qt_install_headers}/Qt{m}" for m in qt_modules] + + qt_libs = [f"Qt5{m}" for m in qt_modules] + ["GL"] +qt_env['QT3DIR'] = qt_env['QTDIR'] +qt_env.Tool('qt3') + +qt_env['CPPPATH'] += qt_dirs +qt_flags = [ + "-D_REENTRANT", + "-DQT_NO_DEBUG", + "-DQT_WIDGETS_LIB", + "-DQT_GUI_LIB", + "-DQT_CORE_LIB", + "-DQT_MESSAGELOGCONTEXT", +] +qt_env['CXXFLAGS'] += qt_flags +qt_env['LIBPATH'] += ['#selfdrive/ui', ] +qt_env['LIBS'] = qt_libs base_frameworks = qt_env['FRAMEWORKS'] -base_libs = [common, messaging, cereal, visionipc, 'qt_util', 'm', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] +base_libs = [common, messaging, cereal, visionipc, 'm', 'pthread'] + qt_env["LIBS"] if arch == "Darwin": - base_frameworks.append('OpenCL') - base_frameworks.append('QtCharts') - base_frameworks.append('QtSerialBus') + base_frameworks += ['QtCharts', 'CoreFoundation', 'CoreVideo', 'CoreMedia', 'IOKit', 'Security', 'VideoToolbox'] else: - base_libs.append('OpenCL') base_libs.append('Qt5Charts') - base_libs.append('Qt5SerialBus') - -qt_libs = ['qt_util'] + base_libs cabana_env = qt_env.Clone() -cabana_libs = [widgets, cereal, messaging, visionipc, replay_lib, 'panda', 'avutil', 'avcodec', 'avformat', 'bz2', 'zstd', 'curl', 'yuv', 'usb-1.0'] + qt_libs +cabana_env['CPPPATH'] += [libusb.INCLUDE_DIR] +cabana_env['LIBPATH'] += [libusb.LIB_DIR] + +cabana_libs = [cereal, messaging, visionipc, replay_lib, 'avformat', 'avcodec', 'swresample', 'avutil', 'x264', 'z', 'bz2', 'zstd', 'yuv', 'usb-1.0'] + base_libs +if arch != "Darwin": + cabana_libs += ['va', 'va-drm', 'drm'] opendbc_path = '-DOPENDBC_FILE_PATH=\'"%s"\'' % (cabana_env.Dir("../../opendbc/dbc").abspath) cabana_env['CXXFLAGS'] += [opendbc_path] +def write_assets_qrc(target, source, env): + with open(str(source[0])) as f: + qrc = f.read() + with open(str(target[0]), "w") as f: + f.write(qrc.replace("@BOOTSTRAP_ICONS_SVG@", str(bootstrap_icons.SVG_PATH))) + # build assets assets = "assets/assets.cc" -assets_src = "assets/assets.qrc" +assets_src = cabana_env.Command( + "assets/assets.generated.qrc", + "assets/assets.qrc", + write_assets_qrc, +) cabana_env.Command(assets, assets_src, f"rcc $SOURCES -o $TARGET") +cabana_env.Depends(assets_src, str(bootstrap_icons.SVG_PATH)) cabana_env.Depends(assets, Glob('/assets/*', exclude=[assets, assets_src, "assets/assets.o"])) -cabana_lib = cabana_env.Library("cabana_lib", ['mainwin.cc', 'streams/socketcanstream.cc', 'streams/pandastream.cc', 'streams/devicestream.cc', 'streams/livestream.cc', 'streams/abstractstream.cc', 'streams/replaystream.cc', 'binaryview.cc', 'historylog.cc', 'videowidget.cc', 'signalview.cc', - 'streams/routes.cc', 'dbc/dbc.cc', 'dbc/dbcfile.cc', 'dbc/dbcmanager.cc', - 'utils/export.cc', 'utils/util.cc', - 'chart/chartswidget.cc', 'chart/chart.cc', 'chart/signalselector.cc', 'chart/tiplabel.cc', 'chart/sparkline.cc', - 'commands.cc', 'messageswidget.cc', 'streamselector.cc', 'settings.cc', 'detailwidget.cc', 'tools/findsimilarbits.cc', 'tools/findsignal.cc'], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) -cabana_env.Program('cabana', ['cabana.cc', cabana_lib, assets], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) +cabana_srcs = ['mainwin.cc', 'streams/pandastream.cc', 'streams/devicestream.cc', 'streams/livestream.cc', 'streams/abstractstream.cc', 'streams/replaystream.cc', 'binaryview.cc', 'historylog.cc', 'videowidget.cc', 'signalview.cc', + 'streams/routes.cc', 'dbc/dbc.cc', 'dbc/dbcfile.cc', 'dbc/dbcmanager.cc', + 'utils/export.cc', 'utils/util.cc', 'utils/elidedlabel.cc', + 'chart/chartswidget.cc', 'chart/chart.cc', 'chart/signalselector.cc', 'chart/tiplabel.cc', 'chart/sparkline.cc', + 'commands.cc', 'messageswidget.cc', 'streamselector.cc', 'settings.cc', 'panda.cc', + 'cameraview.cc', 'detailwidget.cc', 'tools/findsimilarbits.cc', 'tools/findsignal.cc', 'tools/routeinfo.cc'] +if arch != "Darwin": + cabana_srcs += ['streams/socketcanstream.cc'] +cabana_lib = cabana_env.Library("cabana_lib", cabana_srcs, LIBS=cabana_libs, FRAMEWORKS=base_frameworks) +cabana_env.Program('_cabana', ['cabana.cc', cabana_lib, assets], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) if GetOption('extras'): cabana_env.Program('tests/test_cabana', ['tests/test_runner.cc', 'tests/test_cabana.cc', cabana_lib], LIBS=[cabana_libs]) @@ -39,4 +116,4 @@ output_json_file = 'tools/cabana/dbc/car_fingerprint_to_dbc.json' generate_dbc = cabana_env.Command('#' + output_json_file, ['dbc/generate_dbc_json.py'], "python3 tools/cabana/dbc/generate_dbc_json.py --out " + output_json_file) -cabana_env.Depends(generate_dbc, ["#common", "#selfdrive/pandad", '#opendbc', "#cereal", "#msgq_repo", Glob("#opendbc/*.dbc")]) +cabana_env.Depends(generate_dbc, ["#common", '#opendbc_repo', "#cereal", "#msgq_repo"]) diff --git a/tools/cabana/assets/.gitignore b/tools/cabana/assets/.gitignore deleted file mode 100644 index 283034ca8b4104..00000000000000 --- a/tools/cabana/assets/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.cc diff --git a/tools/cabana/assets/assets.qrc b/tools/cabana/assets/assets.qrc index 6a8e5a3414fd17..f5880e55800f4e 100644 --- a/tools/cabana/assets/assets.qrc +++ b/tools/cabana/assets/assets.qrc @@ -1,6 +1,6 @@ - ../../../third_party/bootstrap/bootstrap-icons.svg + @BOOTSTRAP_ICONS_SVG@ cabana-icon.png diff --git a/tools/cabana/binaryview.cc b/tools/cabana/binaryview.cc index 2950a67ff225f1..c86b3ebdae1128 100644 --- a/tools/cabana/binaryview.cc +++ b/tools/cabana/binaryview.cc @@ -40,14 +40,14 @@ BinaryView::BinaryView(QWidget *parent) : QTableView(parent) { addShortcuts(); setWhatsThis(R"( Binary View
- + Shortcuts
Delete Signal:  x ,  Backspace ,  Delete 
Change endianness:  e 
- Change singedness:  s 
+ Change signedness:  s 
Open chart:  c ,  p , @@ -111,7 +111,8 @@ void BinaryView::highlight(const cabana::Signal *sig) { if (sig != hovered_sig) { for (int i = 0; i < model->items.size(); ++i) { auto &item_sigs = model->items[i].sigs; - if ((sig && item_sigs.contains(sig)) || (hovered_sig && item_sigs.contains(hovered_sig))) { + auto has = [](const auto &v, auto p) { return std::find(v.begin(), v.end(), p) != v.end(); }; + if ((sig && has(item_sigs, sig)) || (hovered_sig && has(item_sigs, hovered_sig))) { auto index = model->index(i / model->columnCount(), i % model->columnCount()); emit model->dataChanged(index, index, {Qt::DisplayRole}); } @@ -157,7 +158,7 @@ void BinaryView::mousePressEvent(QMouseEvent *event) { void BinaryView::highlightPosition(const QPoint &pos) { if (auto index = indexAt(viewport()->mapFromGlobal(pos)); index.isValid()) { auto item = (BinaryViewModel::Item *)index.internalPointer(); - const cabana::Signal *sig = item->sigs.isEmpty() ? nullptr : item->sigs.back(); + const cabana::Signal *sig = item->sigs.empty() ? nullptr : item->sigs.back(); highlight(sig); } } @@ -208,12 +209,12 @@ void BinaryView::refresh() { highlightPosition(QCursor::pos()); } -QSet BinaryView::getOverlappingSignals() const { - QSet overlapping; +std::set BinaryView::getOverlappingSignals() const { + std::set overlapping; for (const auto &item : model->items) { if (item.sigs.size() > 1) { for (auto s : item.sigs) { - if (s->type == cabana::Signal::Type::Normal) overlapping += s; + if (s->type == cabana::Signal::Type::Normal) overlapping.insert(s); } } } @@ -248,6 +249,7 @@ std::tuple BinaryView::getSelection(QModelIndex index) { void BinaryViewModel::refresh() { beginResetModel(); + bit_flip_tracker = {}; items.clear(); if (auto dbc_msg = dbc()->msg(msg_id)) { row_count = dbc_msg->size; @@ -257,7 +259,7 @@ void BinaryViewModel::refresh() { int pos = sig->is_little_endian ? flipBitPos(sig->start_bit + j) : flipBitPos(sig->start_bit) + j; int idx = column_count * (pos / 8) + pos % 8; if (idx >= items.size()) { - qWarning() << "signal " << sig->name << "out of bounds.start_bit:" << sig->start_bit << "size:" << sig->size; + qWarning() << "signal " << sig->name.c_str() << "out of bounds.start_bit:" << sig->start_bit << "size:" << sig->size; break; } if (j == 0) sig->is_little_endian ? items[idx].is_lsb = true : items[idx].is_msb = true; @@ -274,16 +276,13 @@ void BinaryViewModel::refresh() { row_count = can->lastMessage(msg_id).dat.size(); items.resize(row_count * column_count); } - int valid_rows = std::min(can->lastMessage(msg_id).dat.size(), row_count); - for (int i = 0; i < valid_rows * column_count; ++i) { - items[i].valid = true; - } endResetModel(); updateState(); } void BinaryViewModel::updateItem(int row, int col, uint8_t val, const QColor &color) { auto &item = items[row * column_count + col]; + item.valid = true; if (item.val != val || item.bg_color != color) { item.val = val; item.bg_color = color; @@ -295,7 +294,7 @@ void BinaryViewModel::updateItem(int row, int col, uint8_t val, const QColor &co void BinaryViewModel::updateState() { const auto &last_msg = can->lastMessage(msg_id); const auto &binary = last_msg.dat; - // data size may changed. + // Handle size changes in binary data if (binary.size() > row_count) { beginInsertRows({}, row_count, binary.size() - 1); row_count = binary.size(); @@ -303,26 +302,74 @@ void BinaryViewModel::updateState() { endInsertRows(); } - const double max_f = 255.0; - const double factor = 0.25; - const double scaler = max_f / log2(1.0 + factor); - for (int i = 0; i < binary.size(); ++i) { + auto &bit_flips = heatmap_live_mode ? last_msg.bit_flip_counts : getBitFlipChanges(binary.size()); + // Find the maximum bit flip count across the message + uint32_t max_bit_flip_count = 1; // Default to 1 to avoid division by zero + for (const auto &row : bit_flips) { + for (uint32_t count : row) { + max_bit_flip_count = std::max(max_bit_flip_count, count); + } + } + + const double max_alpha = 255.0; + const double min_alpha_with_signal = 25.0; // Base alpha for small flip counts + const double min_alpha_no_signal = 10.0; // Base alpha for small flip counts for no signal bits + const double log_factor = 1.0 + 0.2; // Factor for logarithmic scaling + const double log_scaler = max_alpha / log2(log_factor * max_bit_flip_count); + + for (size_t i = 0; i < binary.size(); ++i) { for (int j = 0; j < 8; ++j) { auto &item = items[i * column_count + j]; - int val = ((binary[i] >> (7 - j)) & 1) != 0 ? 1 : 0; - // Bit update frequency based highlighting - double offset = !item.sigs.empty() ? 50 : 0; - auto n = last_msg.last_changes[i].bit_change_counts[j]; - double min_f = n == 0 ? offset : offset + 25; - double alpha = std::clamp(offset + log2(1.0 + factor * (double)n / (double)last_msg.count) * scaler, min_f, max_f); + int bit_val = (binary[i] >> (7 - j)) & 1; + + double alpha = item.sigs.empty() ? 0 : min_alpha_with_signal; + uint32_t flip_count = bit_flips[i][j]; + if (flip_count > 0) { + double normalized_alpha = log2(1.0 + flip_count * log_factor) * log_scaler; + double min_alpha = item.sigs.empty() ? min_alpha_no_signal : min_alpha_with_signal; + alpha = std::clamp(normalized_alpha, min_alpha, max_alpha); + } + auto color = item.bg_color; color.setAlpha(alpha); - updateItem(i, j, val, color); + updateItem(i, j, bit_val, color); } updateItem(i, 8, binary[i], last_msg.colors[i]); } } +const std::vector> &BinaryViewModel::getBitFlipChanges(size_t msg_size) { + // Return cached results if time range and data are unchanged + auto time_range = can->timeRange(); + if (bit_flip_tracker.time_range == time_range && !bit_flip_tracker.flip_counts.empty()) + return bit_flip_tracker.flip_counts; + + bit_flip_tracker.time_range = time_range; + bit_flip_tracker.flip_counts.assign(msg_size, std::array{}); + + // Iterate over events within the specified time range and calculate bit flips + auto [first, last] = can->eventsInRange(msg_id, time_range); + if (std::distance(first, last) <= 1) return bit_flip_tracker.flip_counts; + + std::vector prev_values((*first)->dat, (*first)->dat + (*first)->size); + for (auto it = std::next(first); it != last; ++it) { + const CanEvent *event = *it; + int size = std::min(msg_size, event->size); + for (int i = 0; i < size; ++i) { + const uint8_t diff = event->dat[i] ^ prev_values[i]; + if (!diff) continue; + + auto &bit_flips = bit_flip_tracker.flip_counts[i]; + for (int bit = 0; bit < 8; ++bit) { + if (diff & (1u << bit)) ++bit_flips[7 - bit]; + } + prev_values[i] = event->dat[i]; + } + } + + return bit_flip_tracker.flip_counts; +} + QVariant BinaryViewModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical) { switch (role) { @@ -358,7 +405,9 @@ bool BinaryItemDelegate::hasSignal(const QModelIndex &index, int dx, int dy, con if (!index.isValid()) return false; auto model = (const BinaryViewModel*)(index.model()); int idx = (index.row() + dy) * model->columnCount() + index.column() + dx; - return (idx >=0 && idx < model->items.size()) ? model->items[idx].sigs.contains(sig) : false; + if (idx < 0 || idx >= (int)model->items.size()) return false; + auto &s = model->items[idx].sigs; + return std::find(s.begin(), s.end(), sig) != s.end(); } void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { @@ -375,7 +424,7 @@ void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op auto color = bin_view->resize_sig ? bin_view->resize_sig->color : option.palette.color(QPalette::Active, QPalette::Highlight); painter->fillRect(option.rect, color); painter->setPen(option.palette.color(QPalette::BrightText)); - } else if (!bin_view->selectionModel()->hasSelection() || !item->sigs.contains(bin_view->resize_sig)) { // not resizing + } else if (!bin_view->selectionModel()->hasSelection() || std::find(item->sigs.begin(), item->sigs.end(), bin_view->resize_sig) == item->sigs.end()) { // not resizing if (item->sigs.size() > 0) { for (auto &s : item->sigs) { if (s == bin_view->hovered_sig) { @@ -387,8 +436,8 @@ void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op } else if (item->valid && item->bg_color.alpha() > 0) { painter->fillRect(option.rect, item->bg_color); } - auto color_role = item->sigs.contains(bin_view->hovered_sig) ? QPalette::BrightText : QPalette::Text; - painter->setPen(option.palette.color(color_role)); + auto color_role = (std::find(item->sigs.begin(), item->sigs.end(), bin_view->hovered_sig) != item->sigs.end()) ? QPalette::BrightText : QPalette::Text; + painter->setPen(option.palette.color(bin_view->is_message_active ? QPalette::Normal : QPalette::Disabled, color_role)); } if (item->sigs.size() > 1) { diff --git a/tools/cabana/binaryview.h b/tools/cabana/binaryview.h index 584910dc8304a7..e568228b37d518 100644 --- a/tools/cabana/binaryview.h +++ b/tools/cabana/binaryview.h @@ -1,10 +1,9 @@ #pragma once +#include #include #include -#include -#include #include #include @@ -39,17 +38,23 @@ class BinaryViewModel : public QAbstractTableModel { Qt::ItemFlags flags(const QModelIndex &index) const override { return (index.column() == column_count - 1) ? Qt::ItemIsEnabled : Qt::ItemIsEnabled | Qt::ItemIsSelectable; } + const std::vector> &getBitFlipChanges(size_t msg_size); + + struct BitFlipTracker { + std::optional> time_range; + std::vector> flip_counts; + } bit_flip_tracker; struct Item { QColor bg_color = QColor(102, 86, 169, 255); bool is_msb = false; bool is_lsb = false; uint8_t val; - QList sigs; + std::vector sigs; bool valid = false; }; std::vector items; - + bool heatmap_live_mode = true; MessageId msg_id; int row_count = 0; const int column_count = 9; @@ -62,9 +67,14 @@ class BinaryView : public QTableView { BinaryView(QWidget *parent = nullptr); void setMessage(const MessageId &message_id); void highlight(const cabana::Signal *sig); - QSet getOverlappingSignals() const; - inline void updateState() { model->updateState(); } + std::set getOverlappingSignals() const; + void updateState() { model->updateState(); } + void paintEvent(QPaintEvent *event) override { + is_message_active = can->isMessageActive(model->msg_id); + QTableView::paintEvent(event); + } QSize minimumSizeHint() const override; + void setHeatmapLiveMode(bool live) { model->heatmap_live_mode = live; updateState(); } signals: void signalClicked(const cabana::Signal *sig); @@ -86,6 +96,7 @@ class BinaryView : public QTableView { QModelIndex anchor_index; BinaryViewModel *model; BinaryItemDelegate *delegate; + bool is_message_active = false; const cabana::Signal *resize_sig = nullptr; const cabana::Signal *hovered_sig = nullptr; friend class BinaryItemDelegate; diff --git a/tools/cabana/cabana b/tools/cabana/cabana new file mode 100755 index 00000000000000..5eb15eabf08148 --- /dev/null +++ b/tools/cabana/cabana @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +ROOT="$(cd "$DIR/../../" && pwd)" + +install_qt() { + if [[ "$(uname)" == "Darwin" ]]; then + brew install qt@5 + brew link qt@5 || true + else + SUDO="" + if [[ ! $(id -u) -eq 0 ]]; then + SUDO="sudo" + fi + $SUDO apt-get install -y --no-install-recommends \ + qtbase5-dev \ + qtbase5-dev-tools \ + qttools5-dev-tools \ + libqt5charts5-dev \ + libqt5svg5-dev \ + libqt5serialbus5-dev \ + libqt5x11extras5-dev \ + libqt5opengl5-dev + fi +} + +# Install Qt if not found +if ! command -v qmake &> /dev/null; then + echo "Qt not found, installing dependencies..." + install_qt +fi + +# Build _cabana +cd "$ROOT" +scons tools/cabana/_cabana cereal/messaging/bridge + +exec "$DIR/_cabana" "$@" diff --git a/tools/cabana/cabana.cc b/tools/cabana/cabana.cc index a798d13a81b65e..db26b4067ac6eb 100644 --- a/tools/cabana/cabana.cc +++ b/tools/cabana/cabana.cc @@ -1,12 +1,13 @@ #include #include -#include "selfdrive/ui/qt/util.h" #include "tools/cabana/mainwin.h" #include "tools/cabana/streams/devicestream.h" #include "tools/cabana/streams/pandastream.h" #include "tools/cabana/streams/replaystream.h" +#ifdef __linux__ #include "tools/cabana/streams/socketcanstream.h" +#endif int main(int argc, char *argv[]) { QCoreApplication::setApplicationName("Cabana"); @@ -23,16 +24,19 @@ int main(int argc, char *argv[]) { cmd_parser.addHelpOption(); cmd_parser.addPositionalArgument("route", "the drive to replay. find your drives at connect.comma.ai"); cmd_parser.addOption({"demo", "use a demo route instead of providing your own"}); + cmd_parser.addOption({"auto", "Auto load the route from the best available source (no video): internal, openpilotci, comma_api, car_segments, testing_closet"}); cmd_parser.addOption({"qcam", "load qcamera"}); cmd_parser.addOption({"ecam", "load wide road camera"}); cmd_parser.addOption({"dcam", "load driver camera"}); - cmd_parser.addOption({"stream", "read can messages from live streaming"}); + cmd_parser.addOption({"msgq", "read can messages from the msgq"}); cmd_parser.addOption({"panda", "read can messages from panda"}); cmd_parser.addOption({"panda-serial", "read can messages from panda with given serial", "panda-serial"}); +#ifdef __linux__ if (SocketCanStream::available()) { cmd_parser.addOption({"socketcan", "read can messages from given SocketCAN device", "socketcan"}); } - cmd_parser.addOption({"zmq", "the ip address on which to receive zmq messages", "zmq"}); +#endif + cmd_parser.addOption({"zmq", "read can messages from zmq at the specified ip-address", "ip-address"}); cmd_parser.addOption({"data_dir", "local directory with routes", "data_dir"}); cmd_parser.addOption({"no-vipc", "do not output video"}); cmd_parser.addOption({"dbc", "dbc file to open", "dbc"}); @@ -40,17 +44,21 @@ int main(int argc, char *argv[]) { AbstractStream *stream = nullptr; - if (cmd_parser.isSet("stream")) { + if (cmd_parser.isSet("msgq")) { + stream = new DeviceStream(&app); + } else if (cmd_parser.isSet("zmq")) { stream = new DeviceStream(&app, cmd_parser.value("zmq")); } else if (cmd_parser.isSet("panda") || cmd_parser.isSet("panda-serial")) { try { - stream = new PandaStream(&app, {.serial = cmd_parser.value("panda-serial")}); + stream = new PandaStream(&app, {.serial = cmd_parser.value("panda-serial").toStdString()}); } catch (std::exception &e) { qWarning() << e.what(); return 0; } - } else if (cmd_parser.isSet("socketcan")) { - stream = new SocketCanStream(&app, {.device = cmd_parser.value("socketcan")}); +#ifdef __linux__ + } else if (SocketCanStream::available() && cmd_parser.isSet("socketcan")) { + stream = new SocketCanStream(&app, {.device = cmd_parser.value("socketcan").toStdString()}); +#endif } else { uint32_t replay_flags = REPLAY_FLAG_NONE; if (cmd_parser.isSet("ecam")) replay_flags |= REPLAY_FLAG_ECAM; @@ -67,7 +75,8 @@ int main(int argc, char *argv[]) { } if (!route.isEmpty()) { auto replay_stream = std::make_unique(&app); - if (!replay_stream->loadRoute(route, cmd_parser.value("data_dir"), replay_flags)) { + bool auto_source = cmd_parser.isSet("auto"); + if (!replay_stream->loadRoute(route.toStdString(), cmd_parser.value("data_dir").toStdString(), replay_flags, auto_source)) { return 0; } stream = replay_stream.release(); diff --git a/tools/cabana/cameraview.cc b/tools/cabana/cameraview.cc new file mode 100644 index 00000000000000..13c838efd8e1e8 --- /dev/null +++ b/tools/cabana/cameraview.cc @@ -0,0 +1,261 @@ +#include "tools/cabana/cameraview.h" + +#ifdef __APPLE__ +#include +#else +#include +#endif + +#include + +namespace { + +const char frame_vertex_shader[] = +#ifdef __APPLE__ + "#version 330 core\n" +#else + "#version 300 es\n" +#endif + "layout(location = 0) in vec4 aPosition;\n" + "layout(location = 1) in vec2 aTexCoord;\n" + "uniform mat4 uTransform;\n" + "out vec2 vTexCoord;\n" + "void main() {\n" + " gl_Position = uTransform * aPosition;\n" + " vTexCoord = aTexCoord;\n" + "}\n"; + +const char frame_fragment_shader[] = +#ifdef __APPLE__ + "#version 330 core\n" +#else + "#version 300 es\n" + "precision mediump float;\n" +#endif + "uniform sampler2D uTextureY;\n" + "uniform sampler2D uTextureUV;\n" + "in vec2 vTexCoord;\n" + "out vec4 colorOut;\n" + "void main() {\n" + " float y = texture(uTextureY, vTexCoord).r;\n" + " vec2 uv = texture(uTextureUV, vTexCoord).rg - 0.5;\n" + " float r = y + 1.402 * uv.y;\n" + " float g = y - 0.344 * uv.x - 0.714 * uv.y;\n" + " float b = y + 1.772 * uv.x;\n" + " colorOut = vec4(r, g, b, 1.0);\n" + "}\n"; + +} // namespace + +CameraWidget::CameraWidget(std::string stream_name, VisionStreamType type, QWidget* parent) : + stream_name(stream_name), active_stream_type(type), requested_stream_type(type), QOpenGLWidget(parent) { + setAttribute(Qt::WA_OpaquePaintEvent); + qRegisterMetaType>("availableStreams"); + QObject::connect(this, &CameraWidget::vipcThreadConnected, this, &CameraWidget::vipcConnected, Qt::BlockingQueuedConnection); + QObject::connect(this, &CameraWidget::vipcThreadFrameReceived, this, &CameraWidget::vipcFrameReceived, Qt::QueuedConnection); + QObject::connect(this, &CameraWidget::vipcAvailableStreamsUpdated, this, &CameraWidget::availableStreamsUpdated, Qt::QueuedConnection); + QObject::connect(QApplication::instance(), &QCoreApplication::aboutToQuit, this, &CameraWidget::stopVipcThread); +} + +CameraWidget::~CameraWidget() { + makeCurrent(); + stopVipcThread(); + if (isValid()) { + glDeleteVertexArrays(1, &frame_vao); + glDeleteBuffers(1, &frame_vbo); + glDeleteBuffers(1, &frame_ibo); + glDeleteTextures(2, textures); + shader_program_.reset(); + } + doneCurrent(); +} + +void CameraWidget::initializeGL() { + initializeOpenGLFunctions(); + + shader_program_ = std::make_unique(context()); + shader_program_->addShaderFromSourceCode(QOpenGLShader::Vertex, frame_vertex_shader); + shader_program_->addShaderFromSourceCode(QOpenGLShader::Fragment, frame_fragment_shader); + shader_program_->link(); + + GLint frame_pos_loc = shader_program_->attributeLocation("aPosition"); + GLint frame_texcoord_loc = shader_program_->attributeLocation("aTexCoord"); + + auto [x1, x2, y1, y2] = requested_stream_type == VISION_STREAM_DRIVER ? std::tuple(0.f, 1.f, 1.f, 0.f) : std::tuple(1.f, 0.f, 1.f, 0.f); + const uint8_t frame_indicies[] = {0, 1, 2, 0, 2, 3}; + const float frame_coords[4][4] = { + {-1.0, -1.0, x2, y1}, // bl + {-1.0, 1.0, x2, y2}, // tl + { 1.0, 1.0, x1, y2}, // tr + { 1.0, -1.0, x1, y1}, // br + }; + + glGenVertexArrays(1, &frame_vao); + glBindVertexArray(frame_vao); + glGenBuffers(1, &frame_vbo); + glBindBuffer(GL_ARRAY_BUFFER, frame_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(frame_coords), frame_coords, GL_STATIC_DRAW); + glEnableVertexAttribArray(frame_pos_loc); + glVertexAttribPointer(frame_pos_loc, 2, GL_FLOAT, GL_FALSE, + sizeof(frame_coords[0]), (const void *)0); + glEnableVertexAttribArray(frame_texcoord_loc); + glVertexAttribPointer(frame_texcoord_loc, 2, GL_FLOAT, GL_FALSE, + sizeof(frame_coords[0]), (const void *)(sizeof(float) * 2)); + glGenBuffers(1, &frame_ibo); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, frame_ibo); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(frame_indicies), frame_indicies, GL_STATIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); + + glGenTextures(2, textures); + + shader_program_->bind(); + shader_program_->setUniformValue("uTextureY", 0); + shader_program_->setUniformValue("uTextureUV", 1); + shader_program_->release(); +} + +void CameraWidget::showEvent(QShowEvent *event) { + if (!vipc_thread) { + clearFrames(); + vipc_thread = new QThread(); + connect(vipc_thread, &QThread::started, [=]() { vipcThread(); }); + connect(vipc_thread, &QThread::finished, vipc_thread, &QObject::deleteLater); + vipc_thread->start(); + } +} + +void CameraWidget::stopVipcThread() { + makeCurrent(); + if (vipc_thread) { + vipc_thread->requestInterruption(); + vipc_thread->quit(); + vipc_thread->wait(); + vipc_thread = nullptr; + } +} + +void CameraWidget::availableStreamsUpdated(std::set streams) { + available_streams = streams; +} + +void CameraWidget::paintGL() { + glClearColor(bg.redF(), bg.greenF(), bg.blueF(), bg.alphaF()); + glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT); + + std::lock_guard lk(frame_lock); + if (!current_frame_) return; + + // Scale for aspect ratio + float widget_ratio = (float)width() / height(); + float frame_ratio = (float)stream_width / stream_height; + float scale_x = std::min(frame_ratio / widget_ratio, 1.0f); + float scale_y = std::min(widget_ratio / frame_ratio, 1.0f); + + glViewport(0, 0, width() * devicePixelRatio(), height() * devicePixelRatio()); + + shader_program_->bind(); + QMatrix4x4 transform; + transform.scale(scale_x, scale_y, 1.0f); + shader_program_->setUniformValue("uTransform", transform); + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, textures[0]); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width, stream_height, GL_RED, GL_UNSIGNED_BYTE, current_frame_->y); + + glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride/2); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, textures[1]); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width/2, stream_height/2, GL_RG, GL_UNSIGNED_BYTE, current_frame_->uv); + + glBindVertexArray(frame_vao); + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, nullptr); + glBindVertexArray(0); + + // Reset both texture units + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, 0); + glPixelStorei(GL_UNPACK_ALIGNMENT, 4); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + + shader_program_->release(); +} + +void CameraWidget::vipcConnected(VisionIpcClient *vipc_client) { + makeCurrent(); + stream_width = vipc_client->buffers[0].width; + stream_height = vipc_client->buffers[0].height; + stream_stride = vipc_client->buffers[0].stride; + + glBindTexture(GL_TEXTURE_2D, textures[0]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, stream_width, stream_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr); + assert(glGetError() == GL_NO_ERROR); + + glBindTexture(GL_TEXTURE_2D, textures[1]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, stream_width/2, stream_height/2, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr); + assert(glGetError() == GL_NO_ERROR); +} + +void CameraWidget::vipcFrameReceived() { + update(); +} + +void CameraWidget::vipcThread() { + VisionStreamType cur_stream = requested_stream_type; + std::unique_ptr vipc_client; + VisionIpcBufExtra frame_meta = {}; + + while (!QThread::currentThread()->isInterruptionRequested()) { + if (!vipc_client || cur_stream != requested_stream_type) { + clearFrames(); + qDebug().nospace() << "connecting to stream " << requested_stream_type << ", was connected to " << cur_stream; + cur_stream = requested_stream_type; + vipc_client.reset(new VisionIpcClient(stream_name, cur_stream, false)); + } + active_stream_type = cur_stream; + + if (!vipc_client->connected) { + clearFrames(); + auto streams = VisionIpcClient::getAvailableStreams(stream_name, false); + if (streams.empty()) { + QThread::msleep(100); + continue; + } + emit vipcAvailableStreamsUpdated(streams); + + if (!vipc_client->connect(false)) { + QThread::msleep(100); + continue; + } + emit vipcThreadConnected(vipc_client.get()); + } + + if (VisionBuf *buf = vipc_client->recv(&frame_meta, 100)) { + { + std::lock_guard lk(frame_lock); + current_frame_ = buf; + frame_meta_ = frame_meta; + } + emit vipcThreadFrameReceived(); + } + } +} + +void CameraWidget::clearFrames() { + std::lock_guard lk(frame_lock); + current_frame_ = nullptr; + available_streams.clear(); +} diff --git a/tools/cabana/cameraview.h b/tools/cabana/cameraview.h new file mode 100644 index 00000000000000..930b13d82ca29c --- /dev/null +++ b/tools/cabana/cameraview.h @@ -0,0 +1,64 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "msgq/visionipc/visionipc_client.h" + +class CameraWidget : public QOpenGLWidget, protected QOpenGLFunctions { + Q_OBJECT + +public: + using QOpenGLWidget::QOpenGLWidget; + explicit CameraWidget(std::string stream_name, VisionStreamType stream_type, QWidget* parent = nullptr); + ~CameraWidget(); + void setStreamType(VisionStreamType type) { requested_stream_type = type; } + VisionStreamType getStreamType() { return active_stream_type; } + void stopVipcThread(); + +signals: + void clicked(); + void vipcThreadConnected(VisionIpcClient *); + void vipcThreadFrameReceived(); + void vipcAvailableStreamsUpdated(std::set); + +protected: + void paintGL() override; + void initializeGL() override; + void showEvent(QShowEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override { emit clicked(); } + void vipcThread(); + void clearFrames(); + + GLuint frame_vao, frame_vbo, frame_ibo; + GLuint textures[2]; + std::unique_ptr shader_program_; + QColor bg = Qt::black; + + std::string stream_name; + int stream_width = 0; + int stream_height = 0; + int stream_stride = 0; + std::atomic active_stream_type; + std::atomic requested_stream_type; + std::set available_streams; + QThread *vipc_thread = nullptr; + std::recursive_mutex frame_lock; + VisionBuf* current_frame_ = nullptr; + VisionIpcBufExtra frame_meta_ = {}; + +protected slots: + void vipcConnected(VisionIpcClient *vipc_client); + void vipcFrameReceived(); + void availableStreamsUpdated(std::set streams); +}; + +Q_DECLARE_METATYPE(std::set); diff --git a/tools/cabana/chart/chart.cc b/tools/cabana/chart/chart.cc index 6c13252e80753b..9dfdc595f023af 100644 --- a/tools/cabana/chart/chart.cc +++ b/tools/cabana/chart/chart.cc @@ -45,7 +45,7 @@ ChartView::ChartView(const std::pair &x_range, ChartsWidget *par createToolButtons(); setRubberBand(QChartView::HorizontalRubberBand); setMouseTracking(true); - setTheme(settings.theme == DARK_THEME ? QChart::QChart::ChartThemeDark : QChart::ChartThemeLight); + setTheme(utils::isDarkTheme() ? QChart::QChart::ChartThemeDark : QChart::ChartThemeLight); signal_value_font.setPointSize(9); QObject::connect(axis_y, &QValueAxis::rangeChanged, this, &ChartView::resetChartCache); @@ -237,8 +237,8 @@ void ChartView::updateTitle() { for (auto &s : sigs) { auto decoration = s.series->isVisible() ? "none" : "line-through"; s.series->setName(QString("%3 %5 %6") - .arg(decoration, titleColorCss, s.sig->name, - msgColorCss, msgName(s.msg_id), s.msg_id.toString())); + .arg(decoration, titleColorCss, QString::fromStdString(s.sig->name), + msgColorCss, QString::fromStdString(msgName(s.msg_id)), QString::fromStdString(s.msg_id.toString()))); } split_chart_act->setEnabled(sigs.size() > 1); resetChartCache(); @@ -324,7 +324,8 @@ void ChartView::updateSeries(const cabana::Signal *sig, const MessageEventsMap * if (!can->liveStreaming()) { s.segment_tree.build(s.vals); } - s.series->replace(QVector::fromStdVector(series_type == SeriesType::StepLine ? s.step_vals : s.vals)); + const auto &points = series_type == SeriesType::StepLine ? s.step_vals : s.vals; + s.series->replace(QVector(points.cbegin(), points.cend())); } } updateAxisY(); @@ -338,13 +339,13 @@ void ChartView::updateAxisY() { double min = std::numeric_limits::max(); double max = std::numeric_limits::lowest(); - QString unit = sigs[0].sig->unit; + QString unit = QString::fromStdString(sigs[0].sig->unit); for (auto &s : sigs) { if (!s.series->isVisible()) continue; // Only show unit when all signals have the same unit - if (unit != s.sig->unit) { + if (unit != QString::fromStdString(s.sig->unit)) { unit.clear(); } @@ -382,7 +383,7 @@ void ChartView::updateAxisY() { QFontMetrics fm(axis_y->labelsFont()); for (int i = 0; i < tick_count; i++) { qreal value = min_y + (i * (max_y - min_y) / (tick_count - 1)); - max_label_width = std::max(max_label_width, fm.width(QString::number(value, 'f', n))); + max_label_width = std::max(max_label_width, fm.horizontalAdvance(QString::number(value, 'f', n))); } int title_spacing = unit.isEmpty() ? 0 : QFontMetrics(axis_y->titleFont()).size(Qt::TextSingleLine, unit).height(); @@ -570,13 +571,13 @@ void ChartView::showTip(double sec) { if (s.series->isVisible()) { QString value = "--"; // use reverse iterator to find last item <= sec. - auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), sec, [](auto &p, double x) { return p.x() > x; }); + auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), sec, [](auto &p, double v) { return p.x() > v; }); if (it != s.vals.crend() && it->x() >= axis_x->min()) { - value = s.sig->formatValue(it->y(), false); + value = QString::fromStdString(s.sig->formatValue(it->y(), false)); s.track_pt = *it; x = std::max(x, chart()->mapToPosition(*it).x()); } - QString name = sigs.size() > 1 ? s.sig->name + ": " : ""; + QString name = sigs.size() > 1 ? QString::fromStdString(s.sig->name) + ": " : ""; QString min = s.min == std::numeric_limits::max() ? "--" : QString::number(s.min); QString max = s.max == std::numeric_limits::lowest() ? "--" : QString::number(s.max); text_list << QString("■ %2%3 (%4, %5)") @@ -747,7 +748,7 @@ void ChartView::drawTimeline(QPainter *painter) { QRectF time_str_rect(QPointF(x - time_str_size.width() / 2.0, plot_area.bottom() + AXIS_X_TOP_MARGIN), time_str_size); QPainterPath path; path.addRoundedRect(time_str_rect, 3, 3); - painter->fillPath(path, settings.theme == DARK_THEME ? Qt::darkGray : Qt::gray); + painter->fillPath(path, utils::isDarkTheme() ? Qt::darkGray : Qt::gray); painter->setPen(palette().color(QPalette::BrightText)); painter->setFont(axis_x->labelsFont()); painter->drawText(time_str_rect, Qt::AlignCenter, time_str); @@ -765,7 +766,7 @@ void ChartView::drawSignalValue(QPainter *painter) { for (auto &s : sigs) { auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), cur_sec, [](auto &p, double x) { return p.x() > x + EPSILON; }); - QString value = (it != s.vals.crend() && it->x() >= axis_x->min()) ? s.sig->formatValue(it->y()) : "--"; + QString value = (it != s.vals.crend() && it->x() >= axis_x->min()) ? QString::fromStdString(s.sig->formatValue(it->y())) : "--"; QRectF marker_rect = legend_markers[i++]->sceneBoundingRect(); QRectF value_rect(marker_rect.bottomLeft() - QPoint(0, 1), marker_rect.size()); QString elided_val = painter->fontMetrics().elidedText(value, Qt::ElideRight, value_rect.width()); @@ -838,10 +839,13 @@ void ChartView::setSeriesType(SeriesType type) { } for (auto &s : sigs) { s.series = createSeries(series_type, s.sig->color); - s.series->replace(QVector::fromStdVector(series_type == SeriesType::StepLine ? s.step_vals : s.vals)); + const auto &points = series_type == SeriesType::StepLine ? s.step_vals : s.vals; + s.series->replace(QVector(points.cbegin(), points.cend())); } updateSeriesPoints(); updateTitle(); + + menu->actions()[(int)type]->setChecked(true); } } diff --git a/tools/cabana/chart/chartswidget.cc b/tools/cabana/chart/chartswidget.cc index 27846f9c925990..44dca42152e57f 100644 --- a/tools/cabana/chart/chartswidget.cc +++ b/tools/cabana/chart/chartswidget.cc @@ -1,13 +1,13 @@ #include "tools/cabana/chart/chartswidget.h" #include +#include #include -#include #include +#include #include #include -#include #include "tools/cabana/chart/chart.h" @@ -23,7 +23,7 @@ ChartsWidget::ChartsWidget(QWidget *parent) : QFrame(parent) { main_layout->setSpacing(0); // toolbar - QToolBar *toolbar = new QToolBar(tr("Charts"), this); + toolbar = new QToolBar(tr("Charts"), this); int icon_size = style()->pixelMetric(QStyle::PM_SmallIconSize); toolbar->setIconSize({icon_size, icon_size}); @@ -34,6 +34,21 @@ ChartsWidget::ChartsWidget(QWidget *parent) : QFrame(parent) { toolbar->addWidget(title_label = new QLabel()); title_label->setContentsMargins(0, 0, style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing), 0); + auto chart_type_action = toolbar->addAction(""); + QMenu *chart_type_menu = new QMenu(this); + auto types = std::array{tr("Line"), tr("Step"), tr("Scatter")}; + for (int i = 0; i < types.size(); ++i) { + QString type_text = types[i]; + chart_type_menu->addAction(type_text, this, [=]() { + settings.chart_series_type = i; + chart_type_action->setText("Type: " + type_text); + settingChanged(); + }); + } + chart_type_action->setText("Type: " + types[settings.chart_series_type]); + chart_type_action->setMenu(chart_type_menu); + qobject_cast(toolbar->widgetForAction(chart_type_action))->setPopupMode(QToolButton::InstantPopup); + QMenu *menu = new QMenu(this); for (int i = 0; i < MAX_COLUMN_COUNT; ++i) { menu->addAction(tr("%1").arg(i + 1), [=]() { setColumnCount(i + 1); }); @@ -42,13 +57,13 @@ ChartsWidget::ChartsWidget(QWidget *parent) : QFrame(parent) { columns_action->setMenu(menu); qobject_cast(toolbar->widgetForAction(columns_action))->setPopupMode(QToolButton::InstantPopup); - QLabel *stretch_label = new QLabel(this); - stretch_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - toolbar->addWidget(stretch_label); + QWidget *spacer = new QWidget(this); + spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); + toolbar->addWidget(spacer); range_lb_action = toolbar->addWidget(range_lb = new QLabel(this)); range_slider = new LogSlider(1000, Qt::Horizontal, this); - range_slider->setMaximumWidth(200); + range_slider->setFixedWidth(150 * qApp->devicePixelRatio()); range_slider->setToolTip(tr("Set the chart range")); range_slider->setRange(1, settings.max_cached_minutes * 60); range_slider->setSingleStep(1); @@ -121,10 +136,12 @@ ChartsWidget::ChartsWidget(QWidget *parent) : QFrame(parent) { setIsDocked(true); newTab(); qApp->installEventFilter(this); - setWhatsThis(tr(R"( - Chart view
- + Chart View
+ Click: Click to seek to a corresponding time.
+ Drag: Zoom into the chart.
+ Shift + Drag: Scrub through the chart to view values.
+ Right Mouse: Open the context menu.
)")); } @@ -149,15 +166,16 @@ void ChartsWidget::removeTab(int index) { void ChartsWidget::updateTabBar() { for (int i = 0; i < tabbar->count(); ++i) { const auto &charts_in_tab = tab_charts[tabbar->tabData(i).toInt()]; - tabbar->setTabText(i, QString("Tab %1 (%2)").arg(i + 1).arg(charts_in_tab.count())); + tabbar->setTabText(i, QString("Tab %1 (%2)").arg(i + 1).arg((int)charts_in_tab.size())); } } void ChartsWidget::eventsMerged(const MessageEventsMap &new_events) { - QFutureSynchronizer future_synchronizer; + std::vector> futures; for (auto c : charts) { - future_synchronizer.addFuture(QtConcurrent::run(c, &ChartView::updateSeries, nullptr, &new_events)); + futures.push_back(std::async(std::launch::async, &ChartView::updateSeries, c, nullptr, &new_events)); } + for (auto &f : futures) f.get(); } void ChartsWidget::timeRangeChanged(const std::optional> &time_range) { @@ -176,6 +194,7 @@ QRect ChartsWidget::chartVisibleRect(ChartView *chart) { } void ChartsWidget::showValueTip(double sec) { + emit showTip(sec); if (sec < 0 && !value_tip_visible_) return; value_tip_visible_ = sec >= 0; @@ -185,7 +204,7 @@ void ChartsWidget::showValueTip(double sec) { } void ChartsWidget::updateState() { - if (charts.isEmpty()) return; + if (charts.empty()) return; const auto &time_range = can->timeRange(); const double cur_sec = can->currentSec(); @@ -219,7 +238,7 @@ void ChartsWidget::setIsDocked(bool docked) { void ChartsWidget::updateToolBar() { title_label->setText(tr("Charts: %1").arg(charts.size())); - columns_action->setText(tr("Column: %1").arg(column_count)); + columns_action->setText(tr("Columns: %1").arg(column_count)); range_lb->setText(utils::formatSeconds(max_chart_range)); bool is_zoomed = can->timeRange().has_value(); @@ -229,19 +248,21 @@ void ChartsWidget::updateToolBar() { redo_zoom_action->setVisible(is_zoomed); reset_zoom_action->setVisible(is_zoomed); reset_zoom_btn->setText(is_zoomed ? tr("%1-%2").arg(can->timeRange()->first, 0, 'f', 2).arg(can->timeRange()->second, 0, 'f', 2) : ""); - remove_all_btn->setEnabled(!charts.isEmpty()); + remove_all_btn->setEnabled(!charts.empty()); } void ChartsWidget::settingChanged() { if (std::exchange(current_theme, settings.theme) != current_theme) { undo_zoom_action->setIcon(utils::icon("arrow-counterclockwise")); redo_zoom_action->setIcon(utils::icon("arrow-clockwise")); - auto theme = settings.theme == DARK_THEME ? QChart::QChart::ChartThemeDark : QChart::ChartThemeLight; + auto theme = utils::isDarkTheme() ? QChart::QChart::ChartThemeDark : QChart::ChartThemeLight; for (auto c : charts) { c->setTheme(theme); } } - range_slider->setRange(1, settings.max_cached_minutes * 60); + if (range_slider->maximum() != settings.max_cached_minutes * 60) { + range_slider->setRange(1, settings.max_cached_minutes * 60); + } for (auto c : charts) { c->setFixedHeight(settings.chart_height); c->setSeriesType((SeriesType)settings.chart_series_type); @@ -255,14 +276,15 @@ ChartView *ChartsWidget::findChart(const MessageId &id, const cabana::Signal *si return nullptr; } -ChartView *ChartsWidget::createChart() { +ChartView *ChartsWidget::createChart(int pos) { auto chart = new ChartView(can->timeRange().value_or(display_range), this); chart->setFixedHeight(settings.chart_height); chart->setMinimumWidth(CHART_MIN_WIDTH); chart->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); QObject::connect(chart, &ChartView::axisYLabelWidthChanged, align_timer, qOverload<>(&QTimer::start)); - charts.push_front(chart); - currentCharts().push_front(chart); + pos = std::clamp(pos, 0, (int)charts.size()); + charts.insert(charts.begin() + pos, chart); + currentCharts().insert(currentCharts().begin() + pos, chart); updateLayout(true); updateToolBar(); return chart; @@ -281,8 +303,9 @@ void ChartsWidget::showChart(const MessageId &id, const cabana::Signal *sig, boo void ChartsWidget::splitChart(ChartView *src_chart) { if (src_chart->sigs.size() > 1) { + int pos = std::find(charts.begin(), charts.end(), src_chart) - charts.begin() + 1; for (auto it = src_chart->sigs.begin() + 1; it != src_chart->sigs.end(); /**/) { - auto c = createChart(); + auto c = createChart(pos); src_chart->chart()->removeSeries(it->series); // Restore to the original color @@ -300,6 +323,32 @@ void ChartsWidget::splitChart(ChartView *src_chart) { } } +QStringList ChartsWidget::serializeChartIds() const { + QStringList chart_ids; + for (auto c : charts) { + QStringList ids; + for (const auto& s : c->sigs) + ids += QString("%1|%2").arg(QString::fromStdString(s.msg_id.toString()), QString::fromStdString(s.sig->name)); + chart_ids += ids.join(','); + } + std::reverse(chart_ids.begin(), chart_ids.end()); + return chart_ids; +} + +void ChartsWidget::restoreChartsFromIds(const QStringList& chart_ids) { + for (const auto& chart_id : chart_ids) { + int index = 0; + for (const auto& part : chart_id.split(',')) { + const auto sig_parts = part.split('|'); + if (sig_parts.size() != 2) continue; + MessageId msg_id = MessageId::fromString(sig_parts[0].toStdString()); + if (auto* msg = dbc()->msg(msg_id)) + if (auto* sig = msg->sig(sig_parts[1].toStdString())) + showChart(msg_id, sig, true, index++ > 0); + } + } +} + void ChartsWidget::setColumnCount(int n) { n = std::clamp(n, 1, MAX_COLUMN_COUNT); if (column_count != n) { @@ -378,14 +427,14 @@ void ChartsWidget::doAutoScroll() { } QSize ChartsWidget::minimumSizeHint() const { - return QSize(CHART_MIN_WIDTH, QWidget::minimumSizeHint().height()); + return QSize(CHART_MIN_WIDTH * 1.5, QWidget::minimumSizeHint().height()); } void ChartsWidget::newChart() { SignalSelector dlg(tr("New Chart"), this); if (dlg.exec() == QDialog::Accepted) { auto items = dlg.seletedItems(); - if (!items.isEmpty()) { + if (!items.empty()) { auto c = createChart(); for (auto it : items) { c->addSignal(it->msg_id, it->sig); @@ -395,10 +444,10 @@ void ChartsWidget::newChart() { } void ChartsWidget::removeChart(ChartView *chart) { - charts.removeOne(chart); + charts.erase(std::remove(charts.begin(), charts.end(), chart), charts.end()); chart->deleteLater(); for (auto &[_, list] : tab_charts) { - list.removeOne(chart); + list.erase(std::remove(list.begin(), list.end(), chart), list.end()); } updateToolBar(); updateLayout(true); @@ -412,7 +461,7 @@ void ChartsWidget::removeAll() { } tab_charts.clear(); - if (!charts.isEmpty()) { + if (!charts.empty()) { for (auto c : charts) { delete c; } @@ -434,7 +483,9 @@ void ChartsWidget::alignCharts() { } bool ChartsWidget::eventFilter(QObject *o, QEvent *e) { - if (value_tip_visible_ && e->type() == QEvent::MouseMove) { + if (!value_tip_visible_) return false; + + if (e->type() == QEvent::MouseMove) { bool on_tip = qobject_cast(o) != nullptr; auto global_pos = static_cast(e)->globalPos(); @@ -449,6 +500,11 @@ bool ChartsWidget::eventFilter(QObject *o, QEvent *e) { } showValueTip(-1); + } else if (e->type() == QEvent::Wheel) { + if (auto tip = qobject_cast(o)) { + // Forward the event to the parent widget + QCoreApplication::sendEvent(tip->parentWidget(), e); + } } return false; } @@ -505,10 +561,11 @@ void ChartsContainer::dropEvent(QDropEvent *event) { auto chart = qobject_cast(event->source()); if (w != chart) { for (auto &[_, list] : charts_widget->tab_charts) { - list.removeOne(chart); + list.erase(std::remove(list.begin(), list.end(), chart), list.end()); } - int to = w ? charts_widget->currentCharts().indexOf(w) + 1 : 0; - charts_widget->currentCharts().insert(to, chart); + auto &cur = charts_widget->currentCharts(); + int to = w ? std::find(cur.begin(), cur.end(), w) - cur.begin() + 1 : 0; + cur.insert(cur.begin() + to, chart); charts_widget->updateLayout(true); charts_widget->updateTabBar(); event->acceptProposedAction(); @@ -520,20 +577,14 @@ void ChartsContainer::dropEvent(QDropEvent *event) { void ChartsContainer::paintEvent(QPaintEvent *ev) { if (!drop_indictor_pos.isNull() && !childAt(drop_indictor_pos)) { - QRect r; + QRect r = geometry(); + r.setHeight(CHART_SPACING); if (auto insert_after = getDropAfter(drop_indictor_pos)) { - QRect area = insert_after->geometry(); - r = QRect(area.left(), area.bottom() + 1, area.width(), CHART_SPACING); - } else { - r = geometry(); - r.setHeight(CHART_SPACING); + r.moveTop(insert_after->geometry().bottom()); } QPainter p(this); - p.setPen(QPen(palette().highlight(), 2)); - p.drawLine(r.topLeft() + QPoint(1, 0), r.bottomLeft() + QPoint(1, 0)); - p.drawLine(r.topLeft() + QPoint(0, r.height() / 2), r.topRight() + QPoint(0, r.height() / 2)); - p.drawLine(r.topRight(), r.bottomRight()); + p.fillRect(r, palette().highlight()); } } diff --git a/tools/cabana/chart/chartswidget.h b/tools/cabana/chart/chartswidget.h index a9251917924eb3..ef3fbc471acbaa 100644 --- a/tools/cabana/chart/chartswidget.h +++ b/tools/cabana/chart/chartswidget.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -42,6 +43,8 @@ class ChartsWidget : public QFrame { ChartsWidget(QWidget *parent = nullptr); void showChart(const MessageId &id, const cabana::Signal *sig, bool show, bool merge); inline bool hasSignal(const MessageId &id, const cabana::Signal *sig) { return findChart(id, sig) != nullptr; } + QStringList serializeChartIds() const; + void restoreChartsFromIds(const QStringList &chart_ids); public slots: void setColumnCount(int n); @@ -52,13 +55,14 @@ public slots: signals: void toggleChartsDocking(); void seriesChanged(); + void showTip(double seconds); private: QSize minimumSizeHint() const override; bool event(QEvent *event) override; void alignCharts(); void newChart(); - ChartView *createChart(); + ChartView *createChart(int pos = 0); void removeChart(ChartView *chart); void splitChart(ChartView *chart); QRect chartVisibleRect(ChartView *chart); @@ -77,7 +81,7 @@ public slots: bool eventFilter(QObject *obj, QEvent *event) override; void newTab(); void removeTab(int index); - inline QList ¤tCharts() { return tab_charts[tabbar->tabData(tabbar->currentIndex()).toInt()]; } + inline std::vector ¤tCharts() { return tab_charts[tabbar->tabData(tabbar->currentIndex()).toInt()]; } ChartView *findChart(const MessageId &id, const cabana::Signal *sig); QLabel *title_label; @@ -88,6 +92,7 @@ public slots: bool is_docked = true; ToolButton *dock_btn; + QToolBar *toolbar; QAction *undo_zoom_action; QAction *redo_zoom_action; QAction *reset_zoom_action; @@ -95,8 +100,8 @@ public slots: QUndoStack *zoom_undo_stack; ToolButton *remove_all_btn; - QList charts; - std::unordered_map> tab_charts; + std::vector charts; + std::unordered_map> tab_charts; TabBar *tabbar; ChartsContainer *charts_container; QScrollArea *charts_scroll; diff --git a/tools/cabana/chart/signalselector.cc b/tools/cabana/chart/signalselector.cc index 63f3a7d575082e..6f2fd8de46b914 100644 --- a/tools/cabana/chart/signalselector.cc +++ b/tools/cabana/chart/signalselector.cc @@ -46,7 +46,7 @@ SignalSelector::SignalSelector(QString title, QWidget *parent) : QDialog(parent) for (const auto &[id, _] : can->lastMessages()) { if (auto m = dbc()->msg(id)) { - msgs_combo->addItem(QString("%1 (%2)").arg(m->name).arg(id.toString()), QVariant::fromValue(id)); + msgs_combo->addItem(QString("%1 (%2)").arg(QString::fromStdString(m->name)).arg(QString::fromStdString(id.toString())), QVariant::fromValue(id)); } } msgs_combo->model()->sort(0); @@ -92,8 +92,8 @@ void SignalSelector::updateAvailableList(int index) { } void SignalSelector::addItemToList(QListWidget *parent, const MessageId id, const cabana::Signal *sig, bool show_msg_name) { - QString text = QString("■ %1").arg(sig->color.name(), sig->name); - if (show_msg_name) text += QString(" %0 %1").arg(msgName(id), id.toString()); + QString text = QString("■ %1").arg(sig->color.name(), QString::fromStdString(sig->name)); + if (show_msg_name) text += QString(" %0 %1").arg(QString::fromStdString(msgName(id)), QString::fromStdString(id.toString())); QLabel *label = new QLabel(text); label->setContentsMargins(5, 0, 5, 0); @@ -102,8 +102,8 @@ void SignalSelector::addItemToList(QListWidget *parent, const MessageId id, cons parent->setItemWidget(new_item, label); } -QList SignalSelector::seletedItems() { - QList ret; +std::vector SignalSelector::seletedItems() { + std::vector ret; for (int i = 0; i < selected_list->count(); ++i) ret.push_back((ListItem *)selected_list->item(i)); return ret; } diff --git a/tools/cabana/chart/signalselector.h b/tools/cabana/chart/signalselector.h index f46779f044e4b4..5b6e37e56aa2ff 100644 --- a/tools/cabana/chart/signalselector.h +++ b/tools/cabana/chart/signalselector.h @@ -15,7 +15,7 @@ class SignalSelector : public QDialog { }; SignalSelector(QString title, QWidget *parent); - QList seletedItems(); + std::vector seletedItems(); inline void addSelected(const MessageId &id, const cabana::Signal *sig) { addItemToList(selected_list, id, sig, true); } private: diff --git a/tools/cabana/chart/sparkline.cc b/tools/cabana/chart/sparkline.cc index 094fe96182777c..91435cd5ac8352 100644 --- a/tools/cabana/chart/sparkline.cc +++ b/tools/cabana/chart/sparkline.cc @@ -4,57 +4,97 @@ #include #include -void Sparkline::update(const MessageId &msg_id, const cabana::Signal *sig, double last_msg_ts, int range, QSize size) { - const auto &msgs = can->events(msg_id); +void Sparkline::update(const cabana::Signal *sig, CanEventIter first, CanEventIter last, int range, QSize size) { + if (first == last || size.isEmpty()) { + pixmap = QPixmap(); + return; + } - auto range_start = can->toMonoTime(last_msg_ts - range); - auto range_end = can->toMonoTime(last_msg_ts); - auto first = std::lower_bound(msgs.cbegin(), msgs.cend(), range_start, CompareCanEvent()); - auto last = std::upper_bound(first, msgs.cend(), range_end, CompareCanEvent()); + points_.clear(); + min_val = std::numeric_limits::max(); + max_val = std::numeric_limits::lowest(); + points_.reserve(std::distance(first, last)); - points.clear(); - double value = 0; + uint64_t start_time = (*first)->mono_time; + double value = 0.0; for (auto it = first; it != last; ++it) { if (sig->getValue((*it)->dat, (*it)->size, &value)) { - points.emplace_back(((*it)->mono_time - (*first)->mono_time) / 1e9, value); + min_val = std::min(min_val, value); + max_val = std::max(max_val, value); + points_.emplace_back(((*it)->mono_time - start_time) / 1e9, value); } } - if (points.empty() || size.isEmpty()) { + if (points_.empty()) { pixmap = QPixmap(); return; } - const auto [min, max] = std::minmax_element(points.begin(), points.end(), - [](auto &l, auto &r) { return l.y() < r.y(); }); - min_val = min->y() == max->y() ? min->y() - 1 : min->y(); - max_val = min->y() == max->y() ? max->y() + 1 : max->y(); - freq_ = points.size() / std::max(points.back().x() - points.front().x(), 1.0); + freq_ = points_.size() / std::max(points_.back().x() - points_.front().x(), 1.0); render(sig->color, range, size); } void Sparkline::render(const QColor &color, int range, QSize size) { + // Adjust for flat lines + bool is_flat_line = min_val == max_val; + if (is_flat_line) { + min_val -= 1.0; + max_val += 1.0; + } + + // Calculate scaling const double xscale = (size.width() - 1) / (double)range; const double yscale = (size.height() - 3) / (max_val - min_val); - for (auto &v : points) { - v = QPoint(v.x() * xscale, 1 + std::abs(v.y() - max_val) * yscale); + bool draw_individual_points = (points_.back().x() * xscale / points_.size()) > 8.0; + + // Transform or downsample points + render_points_.reserve(points_.size()); + render_points_.clear(); + if (draw_individual_points) { + for (const auto &p : points_) { + render_points_.emplace_back(p.x() * xscale, 1.0 + (max_val - p.y()) * yscale); + } + } else if (is_flat_line) { + double y = size.height() / 2.0; + render_points_.emplace_back(0.0, y); + render_points_.emplace_back(points_.back().x() * xscale, y); + } else { + double prev_y = points_.front().y(); + render_points_.emplace_back(points_.front().x() * xscale, 1.0 + (max_val - prev_y) * yscale); + bool in_flat = false; + + for (size_t i = 1; i < points_.size(); ++i) { + const auto &p = points_[i]; + double y = p.y(); + if (std::abs(y - prev_y) < 1e-6) { + in_flat = true; + } else { + if (in_flat) render_points_.emplace_back(points_[i - 1].x() * xscale, 1.0 + (max_val - prev_y) * yscale); + render_points_.emplace_back(p.x() * xscale, 1.0 + (max_val - y) * yscale); + in_flat = false; + } + prev_y = y; + } + if (in_flat) render_points_.emplace_back(points_.back().x() * xscale, 1.0 + (max_val - prev_y) * yscale); } + // Render to pixmap qreal dpr = qApp->devicePixelRatio(); - size *= dpr; - if (size != pixmap.size()) { - pixmap = QPixmap(size); + const QSize pixmap_size = size * dpr; + if (pixmap.size() != pixmap_size) { + pixmap = QPixmap(pixmap_size); } pixmap.setDevicePixelRatio(dpr); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); - painter.setRenderHint(QPainter::Antialiasing, points.size() < 500); + painter.setRenderHint(QPainter::Antialiasing, render_points_.size() <= 500); painter.setPen(color); - painter.drawPolyline(points.data(), points.size()); + painter.drawPolyline(render_points_.data(), render_points_.size()); + painter.setPen(QPen(color, 3)); - if ((points.back().x() - points.front().x()) / points.size() > 8) { - painter.drawPoints(points.data(), points.size()); + if (draw_individual_points) { + painter.drawPoints(render_points_.data(), render_points_.size()); } else { - painter.drawPoint(points.back()); + painter.drawPoint(render_points_.back()); } } diff --git a/tools/cabana/chart/sparkline.h b/tools/cabana/chart/sparkline.h index 806f0a61ebf65a..7f30047d0d3109 100644 --- a/tools/cabana/chart/sparkline.h +++ b/tools/cabana/chart/sparkline.h @@ -9,7 +9,7 @@ class Sparkline { public: - void update(const MessageId &msg_id, const cabana::Signal *sig, double last_msg_ts, int range, QSize size); + void update(const cabana::Signal *sig, CanEventIter first, CanEventIter last, int range, QSize size); inline double freq() const { return freq_; } bool isEmpty() const { return pixmap.isNull(); } @@ -20,6 +20,7 @@ class Sparkline { private: void render(const QColor &color, int range, QSize size); - std::vector points; + std::vector points_; + std::vector render_points_; double freq_ = 0; }; diff --git a/tools/cabana/chart/tiplabel.cc b/tools/cabana/chart/tiplabel.cc index be71602838196a..233fa80373a70b 100644 --- a/tools/cabana/chart/tiplabel.cc +++ b/tools/cabana/chart/tiplabel.cc @@ -7,6 +7,7 @@ #include #include "tools/cabana/settings.h" +#include "tools/cabana/utils/util.h" TipLabel::TipLabel(QWidget *parent) : QLabel(parent, Qt::ToolTip | Qt::FramelessWindowHint) { setAttribute(Qt::WA_ShowWithoutActivating); @@ -19,7 +20,7 @@ TipLabel::TipLabel(QWidget *parent) : QLabel(parent, Qt::ToolTip | Qt::Frameless font.setPointSizeF(8.34563465); setFont(font); auto palette = QToolTip::palette(); - if (settings.theme != DARK_THEME) { + if (!utils::isDarkTheme()) { palette.setColor(QPalette::ToolTipBase, QApplication::palette().color(QPalette::Base)); palette.setColor(QPalette::ToolTipText, QRgb(0x404044)); // same color as chart label brush } diff --git a/tools/cabana/commands.cc b/tools/cabana/commands.cc index 52861723f4166f..f158528b51efd7 100644 --- a/tools/cabana/commands.cc +++ b/tools/cabana/commands.cc @@ -4,22 +4,22 @@ // EditMsgCommand -EditMsgCommand::EditMsgCommand(const MessageId &id, const QString &name, int size, - const QString &node, const QString &comment, QUndoCommand *parent) +EditMsgCommand::EditMsgCommand(const MessageId &id, const std::string &name, int size, + const std::string &node, const std::string &comment, QUndoCommand *parent) : id(id), new_name(name), new_size(size), new_node(node), new_comment(comment), QUndoCommand(parent) { if (auto msg = dbc()->msg(id)) { old_name = msg->name; old_size = msg->size; old_node = msg->transmitter; old_comment = msg->comment; - setText(QObject::tr("edit message %1:%2").arg(name).arg(id.address)); + setText(QObject::tr("edit message %1:%2").arg(QString::fromStdString(name)).arg(id.address)); } else { - setText(QObject::tr("new message %1:%2").arg(name).arg(id.address)); + setText(QObject::tr("new message %1:%2").arg(QString::fromStdString(name)).arg(id.address)); } } void EditMsgCommand::undo() { - if (old_name.isEmpty()) + if (old_name.empty()) dbc()->removeMsg(id); else dbc()->updateMsg(id, old_name, old_size, old_node, old_comment); @@ -34,12 +34,12 @@ void EditMsgCommand::redo() { RemoveMsgCommand::RemoveMsgCommand(const MessageId &id, QUndoCommand *parent) : id(id), QUndoCommand(parent) { if (auto msg = dbc()->msg(id)) { message = *msg; - setText(QObject::tr("remove message %1:%2").arg(message.name).arg(id.address)); + setText(QObject::tr("remove message %1:%2").arg(QString::fromStdString(message.name)).arg(id.address)); } } void RemoveMsgCommand::undo() { - if (!message.name.isEmpty()) { + if (!message.name.empty()) { dbc()->updateMsg(id, message.name, message.size, message.transmitter, message.comment); for (auto s : message.getSignals()) dbc()->addSignal(id, *s); @@ -47,7 +47,7 @@ void RemoveMsgCommand::undo() { } void RemoveMsgCommand::redo() { - if (!message.name.isEmpty()) + if (!message.name.empty()) dbc()->removeMsg(id); } @@ -55,7 +55,7 @@ void RemoveMsgCommand::redo() { AddSigCommand::AddSigCommand(const MessageId &id, const cabana::Signal &sig, QUndoCommand *parent) : id(id), signal(sig), QUndoCommand(parent) { - setText(QObject::tr("add signal %1 to %2:%3").arg(sig.name).arg(msgName(id)).arg(id.address)); + setText(QObject::tr("add signal %1 to %2:%3").arg(QString::fromStdString(sig.name)).arg(QString::fromStdString(msgName(id))).arg(id.address)); } void AddSigCommand::undo() { @@ -85,7 +85,7 @@ RemoveSigCommand::RemoveSigCommand(const MessageId &id, const cabana::Signal *si } } } - setText(QObject::tr("remove signal %1 from %2:%3").arg(sig->name).arg(msgName(id)).arg(id.address)); + setText(QObject::tr("remove signal %1 from %2:%3").arg(QString::fromStdString(sig->name)).arg(QString::fromStdString(msgName(id))).arg(id.address)); } void RemoveSigCommand::undo() { for (const auto &s : sigs) dbc()->addSignal(id, s); } @@ -108,7 +108,7 @@ EditSignalCommand::EditSignalCommand(const MessageId &id, const cabana::Signal * } } } - setText(QObject::tr("edit signal %1 in %2:%3").arg(sig->name).arg(msgName(id)).arg(id.address)); + setText(QObject::tr("edit signal %1 in %2:%3").arg(QString::fromStdString(sig->name)).arg(QString::fromStdString(msgName(id))).arg(id.address)); } void EditSignalCommand::undo() { for (const auto &s : sigs) dbc()->updateSignal(id, s.second.name, s.first); } diff --git a/tools/cabana/commands.h b/tools/cabana/commands.h index 0736d9b83f6031..4081f86985861b 100644 --- a/tools/cabana/commands.h +++ b/tools/cabana/commands.h @@ -1,6 +1,8 @@ #pragma once +#include #include +#include #include #include @@ -10,14 +12,14 @@ class EditMsgCommand : public QUndoCommand { public: - EditMsgCommand(const MessageId &id, const QString &name, int size, const QString &node, - const QString &comment, QUndoCommand *parent = nullptr); + EditMsgCommand(const MessageId &id, const std::string &name, int size, const std::string &node, + const std::string &comment, QUndoCommand *parent = nullptr); void undo() override; void redo() override; private: const MessageId id; - QString old_name, new_name, old_comment, new_comment, old_node, new_node; + std::string old_name, new_name, old_comment, new_comment, old_node, new_node; int old_size = 0, new_size = 0; }; @@ -52,7 +54,7 @@ class RemoveSigCommand : public QUndoCommand { private: const MessageId id; - QList sigs; + std::vector sigs; }; class EditSignalCommand : public QUndoCommand { @@ -63,7 +65,7 @@ class EditSignalCommand : public QUndoCommand { private: const MessageId id; - QList> sigs; // QList<{old_sig, new_sig}> + std::vector> sigs; // {old_sig, new_sig} }; namespace UndoStack { diff --git a/tools/cabana/dbc/dbc.cc b/tools/cabana/dbc/dbc.cc index 149bb9f59a5eb1..8e41cf54e394d0 100644 --- a/tools/cabana/dbc/dbc.cc +++ b/tools/cabana/dbc/dbc.cc @@ -4,10 +4,6 @@ #include "tools/cabana/utils/util.h" -uint qHash(const MessageId &item) { - return qHash(item.source) ^ qHash(item.address); -} - // cabana::Msg cabana::Msg::~Msg() { @@ -22,7 +18,7 @@ cabana::Signal *cabana::Msg::addSignal(const cabana::Signal &sig) { return s; } -cabana::Signal *cabana::Msg::updateSignal(const QString &sig_name, const cabana::Signal &new_sig) { +cabana::Signal *cabana::Msg::updateSignal(const std::string &sig_name, const cabana::Signal &new_sig) { auto s = sig(sig_name); if (s) { *s = new_sig; @@ -31,7 +27,7 @@ cabana::Signal *cabana::Msg::updateSignal(const QString &sig_name, const cabana: return s; } -void cabana::Msg::removeSignal(const QString &sig_name) { +void cabana::Msg::removeSignal(const std::string &sig_name) { auto it = std::find_if(sigs.begin(), sigs.end(), [&](auto &s) { return s->name == sig_name; }); if (it != sigs.end()) { delete *it; @@ -45,6 +41,7 @@ cabana::Msg &cabana::Msg::operator=(const cabana::Msg &other) { name = other.name; size = other.size; comment = other.comment; + transmitter = other.transmitter; for (auto s : sigs) delete s; sigs.clear(); @@ -56,7 +53,7 @@ cabana::Msg &cabana::Msg::operator=(const cabana::Msg &other) { return *this; } -cabana::Signal *cabana::Msg::sig(const QString &sig_name) const { +cabana::Signal *cabana::Msg::sig(const std::string &sig_name) const { auto it = std::find_if(sigs.begin(), sigs.end(), [&](auto &s) { return s->name == sig_name; }); return it != sigs.end() ? *it : nullptr; } @@ -68,17 +65,17 @@ int cabana::Msg::indexOf(const cabana::Signal *sig) const { return -1; } -QString cabana::Msg::newSignalName() { - QString new_name; +std::string cabana::Msg::newSignalName() { + std::string new_name; for (int i = 1; /**/; ++i) { - new_name = QString("NEW_SIGNAL_%1").arg(i); + new_name = "NEW_SIGNAL_" + std::to_string(i); if (sig(new_name) == nullptr) break; } return new_name; } void cabana::Msg::update() { - if (transmitter.isEmpty()) { + if (transmitter.empty()) { transmitter = DEFAULT_NODE_NAME; } mask.assign(size, 0x00); @@ -108,7 +105,7 @@ void cabana::Msg::update() { mask[i] |= ((1ULL << sz) - 1) << shift; - bits -= size; + bits -= sz; i = sig->is_little_endian ? i - 1 : i + 1; } } @@ -128,13 +125,13 @@ void cabana::Msg::update() { void cabana::Signal::update() { updateMsbLsb(*this); - if (receiver_name.isEmpty()) { + if (receiver_name.empty()) { receiver_name = DEFAULT_NODE_NAME; } float h = 19 * (float)lsb / 64.0; h = fmod(h, 1.0); - size_t hash = qHash(name); + size_t hash = std::hash{}(name); float s = 0.25 + 0.25 * (float)(hash & 0xff) / 255.0; float v = 0.75 + 0.25 * (float)((hash >> 8) & 0xff) / 255.0; @@ -142,7 +139,7 @@ void cabana::Signal::update() { precision = std::max(num_decimals(factor), num_decimals(offset)); } -QString cabana::Signal::formatValue(double value, bool with_unit) const { +std::string cabana::Signal::formatValue(double value, bool with_unit) const { // Show enum string int64_t raw_value = round((value - offset) / factor); for (const auto &[val, desc] : val_desc) { @@ -151,8 +148,10 @@ QString cabana::Signal::formatValue(double value, bool with_unit) const { } } - QString val_str = QString::number(value, 'f', precision); - if (with_unit && !unit.isEmpty()) { + char buf[64]; + snprintf(buf, sizeof(buf), "%.*f", precision, value); + std::string val_str(buf); + if (with_unit && !unit.empty()) { val_str += " " + unit; } return val_str; @@ -179,25 +178,36 @@ bool cabana::Signal::operator==(const cabana::Signal &other) const { // helper functions double get_raw_value(const uint8_t *data, size_t data_size, const cabana::Signal &sig) { - int64_t val = 0; + const int msb_byte = sig.msb / 8; + if (msb_byte >= (int)data_size) return 0; - int i = sig.msb / 8; - int bits = sig.size; - while (i >= 0 && i < data_size && bits > 0) { - int lsb = (int)(sig.lsb / 8) == i ? sig.lsb : i * 8; - int msb = (int)(sig.msb / 8) == i ? sig.msb : (i + 1) * 8 - 1; - int size = msb - lsb + 1; + const int lsb_byte = sig.lsb / 8; + uint64_t val = 0; - uint64_t d = (data[i] >> (lsb - (i * 8))) & ((1ULL << size) - 1); - val |= d << (bits - size); - - bits -= size; - i = sig.is_little_endian ? i - 1 : i + 1; + // Fast path: signal fits in a single byte + if (msb_byte == lsb_byte) { + val = (data[msb_byte] >> (sig.lsb & 7)) & ((1ULL << sig.size) - 1); + } else { + // Multi-byte case: signal spans across multiple bytes + int bits = sig.size; + int i = msb_byte; + const int step = sig.is_little_endian ? -1 : 1; + while (i >= 0 && i < (int)data_size && bits > 0) { + const int msb = (i == msb_byte) ? sig.msb & 7 : 7; + const int lsb = (i == lsb_byte) ? sig.lsb & 7 : 0; + const int nbits = msb - lsb + 1; + val = (val << nbits) | ((data[i] >> lsb) & ((1ULL << nbits) - 1)); + bits -= nbits; + i += step; + } } - if (sig.is_signed) { - val -= ((val >> (sig.size - 1)) & 0x1) ? (1ULL << sig.size) : 0; + + // Sign extension (if needed) + if (sig.is_signed && (val & (1ULL << (sig.size - 1)))) { + val |= ~((1ULL << sig.size) - 1); } - return val * sig.factor + sig.offset; + + return static_cast(val) * sig.factor + sig.offset; } void updateMsbLsb(cabana::Signal &s) { diff --git a/tools/cabana/dbc/dbc.h b/tools/cabana/dbc/dbc.h index da44319b5c3ab3..a10e7871fee0dc 100644 --- a/tools/cabana/dbc/dbc.h +++ b/tools/cabana/dbc/dbc.h @@ -1,23 +1,35 @@ #pragma once +#include +#include +#include #include +#include #include #include #include #include -#include - -const QString UNTITLED = "untitled"; -const QString DEFAULT_NODE_NAME = "XXX"; +const std::string UNTITLED = "untitled"; +const std::string DEFAULT_NODE_NAME = "XXX"; +constexpr int CAN_MAX_DATA_BYTES = 64; struct MessageId { uint8_t source = 0; uint32_t address = 0; - QString toString() const { - return QString("%1:%2").arg(source).arg(address, 1, 16); + std::string toString() const { + char buf[64]; + snprintf(buf, sizeof(buf), "%u:%X", source, address); + return buf; + } + + inline static MessageId fromString(const std::string &str) { + auto pos = str.find(':'); + if (pos == std::string::npos) return {}; + return MessageId{.source = uint8_t(std::stoul(str.substr(0, pos))), + .address = uint32_t(std::stoul(str.substr(pos + 1), nullptr, 16))}; } bool operator==(const MessageId &other) const { @@ -37,15 +49,17 @@ struct MessageId { } }; -uint qHash(const MessageId &item); Q_DECLARE_METATYPE(MessageId); template <> struct std::hash { - std::size_t operator()(const MessageId &k) const noexcept { return qHash(k); } + std::size_t operator()(const MessageId &k) const noexcept { + return std::hash{}(k.source) ^ (std::hash{}(k.address) << 1); + } }; -typedef std::vector> ValueDescription; +typedef std::vector> ValueDescription; +Q_DECLARE_METATYPE(ValueDescription); namespace cabana { @@ -55,7 +69,7 @@ class Signal { Signal(const Signal &other) = default; void update(); bool getValue(const uint8_t *data, size_t data_size, double *val) const; - QString formatValue(double value, bool with_unit = true) const; + std::string formatValue(double value, bool with_unit = true) const; bool operator==(const cabana::Signal &other) const; inline bool operator!=(const cabana::Signal &other) const { return !(*this == other); } @@ -66,16 +80,16 @@ class Signal { }; Type type = Type::Normal; - QString name; + std::string name; int start_bit, msb, lsb, size; double factor = 1.0; double offset = 0; bool is_signed; bool is_little_endian; double min, max; - QString unit; - QString comment; - QString receiver_name; + std::string unit; + std::string comment; + std::string receiver_name; ValueDescription val_desc; int precision = 0; QColor color; @@ -91,20 +105,20 @@ class Msg { Msg(const Msg &other) { *this = other; } ~Msg(); cabana::Signal *addSignal(const cabana::Signal &sig); - cabana::Signal *updateSignal(const QString &sig_name, const cabana::Signal &sig); - void removeSignal(const QString &sig_name); + cabana::Signal *updateSignal(const std::string &sig_name, const cabana::Signal &sig); + void removeSignal(const std::string &sig_name); Msg &operator=(const Msg &other); int indexOf(const cabana::Signal *sig) const; - cabana::Signal *sig(const QString &sig_name) const; - QString newSignalName(); + cabana::Signal *sig(const std::string &sig_name) const; + std::string newSignalName(); void update(); inline const std::vector &getSignals() const { return sigs; } uint32_t address; - QString name; + std::string name; uint32_t size; - QString comment; - QString transmitter; + std::string comment; + std::string transmitter; std::vector sigs; std::vector mask; @@ -117,4 +131,8 @@ class Msg { double get_raw_value(const uint8_t *data, size_t data_size, const cabana::Signal &sig); void updateMsbLsb(cabana::Signal &s); inline int flipBitPos(int start_bit) { return 8 * (start_bit / 8) + 7 - start_bit % 8; } -inline QString doubleToString(double value) { return QString::number(value, 'g', std::numeric_limits::digits10); } +inline std::string doubleToString(double value) { + char buf[64]; + snprintf(buf, sizeof(buf), "%.*g", std::numeric_limits::digits10, value); + return buf; +} diff --git a/tools/cabana/dbc/dbcfile.cc b/tools/cabana/dbc/dbcfile.cc index cca9d0c0fab3f4..d9c129ee8158ba 100644 --- a/tools/cabana/dbc/dbcfile.cc +++ b/tools/cabana/dbc/dbcfile.cc @@ -3,11 +3,12 @@ #include #include #include +#include -DBCFile::DBCFile(const QString &dbc_file_name) { - QFile file(dbc_file_name); +DBCFile::DBCFile(const std::string &dbc_file_name) { + QFile file(QString::fromStdString(dbc_file_name)); if (file.open(QIODevice::ReadOnly)) { - name_ = QFileInfo(dbc_file_name).baseName(); + name_ = QFileInfo(QString::fromStdString(dbc_file_name)).baseName().toStdString(); filename = dbc_file_name; parse(file.readAll()); } else { @@ -15,34 +16,35 @@ DBCFile::DBCFile(const QString &dbc_file_name) { } } -DBCFile::DBCFile(const QString &name, const QString &content) : name_(name), filename("") { - parse(content); +DBCFile::DBCFile(const std::string &name, const std::string &content) : name_(name), filename("") { + parse(QString::fromStdString(content)); } bool DBCFile::save() { - assert(!filename.isEmpty()); + assert(!filename.empty()); return writeContents(filename); } -bool DBCFile::saveAs(const QString &new_filename) { +bool DBCFile::saveAs(const std::string &new_filename) { filename = new_filename; return save(); } -bool DBCFile::writeContents(const QString &fn) { - QFile file(fn); +bool DBCFile::writeContents(const std::string &fn) { + QFile file(QString::fromStdString(fn)); if (file.open(QIODevice::WriteOnly)) { - return file.write(generateDBC().toUtf8()) >= 0; + std::string content = generateDBC(); + return file.write(content.c_str(), content.size()) >= 0; } return false; } -void DBCFile::updateMsg(const MessageId &id, const QString &name, uint32_t size, const QString &node, const QString &comment) { +void DBCFile::updateMsg(const MessageId &id, const std::string &name, uint32_t size, const std::string &node, const std::string &comment) { auto &m = msgs[id.address]; m.address = id.address; m.name = name; m.size = size; - m.transmitter = node.isEmpty() ? DEFAULT_NODE_NAME : node; + m.transmitter = node.empty() ? DEFAULT_NODE_NAME : node; m.comment = comment; } @@ -51,12 +53,12 @@ cabana::Msg *DBCFile::msg(uint32_t address) { return it != msgs.end() ? &it->second : nullptr; } -cabana::Msg *DBCFile::msg(const QString &name) { +cabana::Msg *DBCFile::msg(const std::string &name) { auto it = std::find_if(msgs.begin(), msgs.end(), [&name](auto &m) { return m.second.name == name; }); return it != msgs.end() ? &(it->second) : nullptr; } -cabana::Signal *DBCFile::signal(uint32_t address, const QString &name) { +cabana::Signal *DBCFile::signal(uint32_t address, const std::string &name) { auto m = msg(address); return m ? (cabana::Signal *)m->sig(name) : nullptr; } @@ -93,13 +95,13 @@ void DBCFile::parse(const QString &content) { seen = false; } } catch (std::exception &e) { - throw std::runtime_error(QString("[%1:%2]%3: %4").arg(filename).arg(line_num).arg(e.what()).arg(line).toStdString()); + throw std::runtime_error(QString("[%1:%2]%3: %4").arg(QString::fromStdString(filename)).arg(line_num).arg(e.what()).arg(line).toStdString()); } if (seen) { seen_first = true; } else if (!seen_first) { - header += raw_line + "\n"; + header += raw_line.toStdString() + "\n"; } } @@ -122,9 +124,9 @@ cabana::Msg *DBCFile::parseBO(const QString &line) { // Create a new message object cabana::Msg *msg = &msgs[address]; msg->address = address; - msg->name = match.captured("name"); + msg->name = match.captured("name").toStdString(); msg->size = match.captured("size").toULong(); - msg->transmitter = match.captured("transmitter").trimmed(); + msg->transmitter = match.captured("transmitter").trimmed().toStdString(); return msg; } @@ -141,11 +143,11 @@ void DBCFile::parseCM_BO(const QString &line, const QString &content, const QStr throw std::runtime_error("Invalid message comment format"); if (auto m = (cabana::Msg *)msg(match.captured("address").toUInt())) - m->comment = match.captured("comment").trimmed().replace("\\\"", "\""); + m->comment = match.captured("comment").trimmed().replace("\\\"", "\"").toStdString(); } void DBCFile::parseSG(const QString &line, cabana::Msg *current_msg, int &multiplexor_cnt) { - static QRegularExpression sg_regexp(R"(^SG_ (\w+) : (\d+)\|(\d+)@(\d+)([\+|\-]) \(([0-9.+\-eE]+),([0-9.+\-eE]+)\) \[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\] \"(.*)\" (.*))"); + static QRegularExpression sg_regexp(R"(^SG_ (\w+) *: (\d+)\|(\d+)@(\d+)([\+|\-]) \(([0-9.+\-eE]+),([0-9.+\-eE]+)\) \[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\] \"(.*)\" (.*))"); static QRegularExpression sgm_regexp(R"(^SG_ (\w+) (\w+) *: (\d+)\|(\d+)@(\d+)([\+|\-]) \(([0-9.+\-eE]+),([0-9.+\-eE]+)\) \[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\] \"(.*)\" (.*))"); if (!current_msg) @@ -160,7 +162,7 @@ void DBCFile::parseSG(const QString &line, cabana::Msg *current_msg, int &multip if (!match.hasMatch()) throw std::runtime_error("Invalid SG_ line format"); - QString name = match.captured(1); + std::string name = match.captured(1).toStdString(); if (current_msg->sig(name) != nullptr) throw std::runtime_error("Duplicate signal name"); @@ -188,8 +190,8 @@ void DBCFile::parseSG(const QString &line, cabana::Msg *current_msg, int &multip s.offset = match.captured(offset + 7).toDouble(); s.min = match.captured(8 + offset).toDouble(); s.max = match.captured(9 + offset).toDouble(); - s.unit = match.captured(10 + offset); - s.receiver_name = match.captured(11 + offset).trimmed(); + s.unit = match.captured(10 + offset).toStdString(); + s.receiver_name = match.captured(11 + offset).trimmed().toStdString(); current_msg->sigs.push_back(new cabana::Signal(s)); } @@ -205,8 +207,8 @@ void DBCFile::parseCM_SG(const QString &line, const QString &content, const QStr if (!match.hasMatch()) throw std::runtime_error("Invalid CM_ SG_ line format"); - if (auto s = signal(match.captured(1).toUInt(), match.captured(2))) { - s->comment = match.captured(3).trimmed().replace("\\\"", "\""); + if (auto s = signal(match.captured(1).toUInt(), match.captured(2).toStdString())) { + s->comment = match.captured(3).trimmed().replace("\\\"", "\"").toStdString(); } } @@ -217,55 +219,60 @@ void DBCFile::parseVAL(const QString &line) { if (!match.hasMatch()) throw std::runtime_error("invalid VAL_ line format"); - if (auto s = signal(match.captured(1).toUInt(), match.captured(2))) { + if (auto s = signal(match.captured(1).toUInt(), match.captured(2).toStdString())) { QStringList desc_list = match.captured(3).trimmed().split('"'); for (int i = 0; i < desc_list.size(); i += 2) { auto val = desc_list[i].trimmed(); if (!val.isEmpty() && (i + 1) < desc_list.size()) { auto desc = desc_list[i + 1].trimmed(); - s->val_desc.push_back({val.toDouble(), desc}); + s->val_desc.push_back({val.toDouble(), desc.toStdString()}); } } } } -QString DBCFile::generateDBC() { - QString dbc_string, comment, val_desc; +std::string DBCFile::generateDBC() { + std::string dbc_string, comment, val_desc; for (const auto &[address, m] : msgs) { - const QString transmitter = m.transmitter.isEmpty() ? DEFAULT_NODE_NAME : m.transmitter; - dbc_string += QString("BO_ %1 %2: %3 %4\n").arg(address).arg(m.name).arg(m.size).arg(transmitter); - if (!m.comment.isEmpty()) { - comment += QString("CM_ BO_ %1 \"%2\";\n").arg(address).arg(QString(m.comment).replace("\"", "\\\"")); + const std::string &transmitter = m.transmitter.empty() ? DEFAULT_NODE_NAME : m.transmitter; + dbc_string += "BO_ " + std::to_string(address) + " " + m.name + ": " + std::to_string(m.size) + " " + transmitter + "\n"; + if (!m.comment.empty()) { + std::string escaped_comment = m.comment; + // Replace " with \" + for (size_t pos = 0; (pos = escaped_comment.find('"', pos)) != std::string::npos; pos += 2) + escaped_comment.replace(pos, 1, "\\\""); + comment += "CM_ BO_ " + std::to_string(address) + " \"" + escaped_comment + "\";\n"; } for (auto sig : m.getSignals()) { - QString multiplexer_indicator; + std::string multiplexer_indicator; if (sig->type == cabana::Signal::Type::Multiplexor) { multiplexer_indicator = "M "; } else if (sig->type == cabana::Signal::Type::Multiplexed) { - multiplexer_indicator = QString("m%1 ").arg(sig->multiplex_value); + multiplexer_indicator = "m" + std::to_string(sig->multiplex_value) + " "; } - dbc_string += QString(" SG_ %1 %2: %3|%4@%5%6 (%7,%8) [%9|%10] \"%11\" %12\n") - .arg(sig->name) - .arg(multiplexer_indicator) - .arg(sig->start_bit) - .arg(sig->size) - .arg(sig->is_little_endian ? '1' : '0') - .arg(sig->is_signed ? '-' : '+') - .arg(doubleToString(sig->factor)) - .arg(doubleToString(sig->offset)) - .arg(doubleToString(sig->min)) - .arg(doubleToString(sig->max)) - .arg(sig->unit) - .arg(sig->receiver_name.isEmpty() ? DEFAULT_NODE_NAME : sig->receiver_name); - if (!sig->comment.isEmpty()) { - comment += QString("CM_ SG_ %1 %2 \"%3\";\n").arg(address).arg(sig->name).arg(QString(sig->comment).replace("\"", "\\\"")); + const std::string &recv = sig->receiver_name.empty() ? DEFAULT_NODE_NAME : sig->receiver_name; + dbc_string += " SG_ " + sig->name + " " + multiplexer_indicator + ": " + + std::to_string(sig->start_bit) + "|" + std::to_string(sig->size) + "@" + + std::string(1, sig->is_little_endian ? '1' : '0') + + std::string(1, sig->is_signed ? '-' : '+') + + " (" + doubleToString(sig->factor) + "," + doubleToString(sig->offset) + ")" + + " [" + doubleToString(sig->min) + "|" + doubleToString(sig->max) + "]" + + " \"" + sig->unit + "\" " + recv + "\n"; + if (!sig->comment.empty()) { + std::string escaped_comment = sig->comment; + for (size_t pos = 0; (pos = escaped_comment.find('"', pos)) != std::string::npos; pos += 2) + escaped_comment.replace(pos, 1, "\\\""); + comment += "CM_ SG_ " + std::to_string(address) + " " + sig->name + " \"" + escaped_comment + "\";\n"; } if (!sig->val_desc.empty()) { - QStringList text; + std::string text; for (auto &[val, desc] : sig->val_desc) { - text << QString("%1 \"%2\"").arg(val).arg(desc); + if (!text.empty()) text += " "; + char val_buf[64]; + snprintf(val_buf, sizeof(val_buf), "%g", val); + text += std::string(val_buf) + " \"" + desc + "\""; } - val_desc += QString("VAL_ %1 %2 %3;\n").arg(address).arg(sig->name).arg(text.join(" ")); + val_desc += "VAL_ " + std::to_string(address) + " " + sig->name + " " + text + ";\n"; } } dbc_string += "\n"; diff --git a/tools/cabana/dbc/dbcfile.h b/tools/cabana/dbc/dbcfile.h index bd267898f94e5b..decb566abd4652 100644 --- a/tools/cabana/dbc/dbcfile.h +++ b/tools/cabana/dbc/dbcfile.h @@ -1,34 +1,35 @@ #pragma once #include +#include #include #include "tools/cabana/dbc/dbc.h" class DBCFile { public: - DBCFile(const QString &dbc_file_name); - DBCFile(const QString &name, const QString &content); + DBCFile(const std::string &dbc_file_name); + DBCFile(const std::string &name, const std::string &content); ~DBCFile() {} bool save(); - bool saveAs(const QString &new_filename); - bool writeContents(const QString &fn); - QString generateDBC(); + bool saveAs(const std::string &new_filename); + bool writeContents(const std::string &fn); + std::string generateDBC(); - void updateMsg(const MessageId &id, const QString &name, uint32_t size, const QString &node, const QString &comment); + void updateMsg(const MessageId &id, const std::string &name, uint32_t size, const std::string &node, const std::string &comment); inline void removeMsg(const MessageId &id) { msgs.erase(id.address); } inline const std::map &getMessages() const { return msgs; } cabana::Msg *msg(uint32_t address); - cabana::Msg *msg(const QString &name); + cabana::Msg *msg(const std::string &name); inline cabana::Msg *msg(const MessageId &id) { return msg(id.address); } - cabana::Signal *signal(uint32_t address, const QString &name); + cabana::Signal *signal(uint32_t address, const std::string &name); - inline QString name() const { return name_.isEmpty() ? "untitled" : name_; } - inline bool isEmpty() const { return msgs.empty() && name_.isEmpty(); } + inline std::string name() const { return name_.empty() ? "untitled" : name_; } + inline bool isEmpty() const { return msgs.empty() && name_.empty(); } - QString filename; + std::string filename; private: void parse(const QString &content); @@ -38,7 +39,7 @@ class DBCFile { void parseCM_SG(const QString &line, const QString &content, const QString &raw_line, const QTextStream &stream); void parseVAL(const QString &line); - QString header; + std::string header; std::map msgs; - QString name_; + std::string name_; }; diff --git a/tools/cabana/dbc/dbcmanager.cc b/tools/cabana/dbc/dbcmanager.cc index 8e98d95322c739..2236a93da1407e 100644 --- a/tools/cabana/dbc/dbcmanager.cc +++ b/tools/cabana/dbc/dbcmanager.cc @@ -1,10 +1,9 @@ #include "tools/cabana/dbc/dbcmanager.h" -#include #include -#include +#include -bool DBCManager::open(const SourceSet &sources, const QString &dbc_file_name, QString *error) { +bool DBCManager::open(const SourceSet &sources, const std::string &dbc_file_name, QString *error) { try { auto it = std::find_if(dbc_files.begin(), dbc_files.end(), [&](auto &f) { return f.second && f.second->filename == dbc_file_name; }); @@ -21,7 +20,7 @@ bool DBCManager::open(const SourceSet &sources, const QString &dbc_file_name, QS return true; } -bool DBCManager::open(const SourceSet &sources, const QString &name, const QString &content, QString *error) { +bool DBCManager::open(const SourceSet &sources, const std::string &name, const std::string &content, QString *error) { try { auto file = std::make_shared(name, content); for (auto s : sources) { @@ -64,7 +63,7 @@ void DBCManager::addSignal(const MessageId &id, const cabana::Signal &sig) { } } -void DBCManager::updateSignal(const MessageId &id, const QString &sig_name, const cabana::Signal &sig) { +void DBCManager::updateSignal(const MessageId &id, const std::string &sig_name, const cabana::Signal &sig) { if (auto m = msg(id)) { if (auto s = m->updateSignal(sig_name, sig)) { emit signalUpdated(s); @@ -73,7 +72,7 @@ void DBCManager::updateSignal(const MessageId &id, const QString &sig_name, cons } } -void DBCManager::removeSignal(const MessageId &id, const QString &sig_name) { +void DBCManager::removeSignal(const MessageId &id, const std::string &sig_name) { if (auto m = msg(id)) { if (auto s = m->sig(sig_name)) { emit signalRemoved(s); @@ -83,7 +82,7 @@ void DBCManager::removeSignal(const MessageId &id, const QString &sig_name) { } } -void DBCManager::updateMsg(const MessageId &id, const QString &name, uint32_t size, const QString &node, const QString &comment) { +void DBCManager::updateMsg(const MessageId &id, const std::string &name, uint32_t size, const std::string &node, const std::string &comment) { auto dbc_file = findDBCFile(id); assert(dbc_file); // This should be impossible dbc_file->updateMsg(id, name, size, node, comment); @@ -98,11 +97,13 @@ void DBCManager::removeMsg(const MessageId &id) { emit maskUpdated(); } -QString DBCManager::newMsgName(const MessageId &id) { - return QString("NEW_MSG_") + QString::number(id.address, 16).toUpper(); +std::string DBCManager::newMsgName(const MessageId &id) { + char buf[64]; + snprintf(buf, sizeof(buf), "NEW_MSG_%X", id.address); + return buf; } -QString DBCManager::newSignalName(const MessageId &id) { +std::string DBCManager::newSignalName(const MessageId &id) { auto m = msg(id); return m ? m->newSignalName() : ""; } @@ -118,14 +119,14 @@ cabana::Msg *DBCManager::msg(const MessageId &id) { return dbc_file ? dbc_file->msg(id) : nullptr; } -cabana::Msg *DBCManager::msg(uint8_t source, const QString &name) { +cabana::Msg *DBCManager::msg(uint8_t source, const std::string &name) { auto dbc_file = findDBCFile(source); return dbc_file ? dbc_file->msg(name) : nullptr; } -QStringList DBCManager::signalNames() { +std::vector DBCManager::signalNames() { // Used for autocompletion - QSet names; + std::set names; for (auto &f : allDBCFiles()) { for (auto &[_, m] : f->getMessages()) { for (auto sig : m.getSignals()) { @@ -133,8 +134,8 @@ QStringList DBCManager::signalNames() { } } } - QStringList ret = names.values(); - ret.sort(); + std::vector ret(names.begin(), names.end()); + std::sort(ret.begin(), ret.end()); return ret; } @@ -165,11 +166,13 @@ const SourceSet DBCManager::sources(const DBCFile *dbc_file) const { return sources; } -QString toString(const SourceSet &ss) { - return std::accumulate(ss.cbegin(), ss.cend(), QString(), [](QString str, int source) { - if (!str.isEmpty()) str += ", "; - return str + (source == -1 ? QStringLiteral("all") : QString::number(source)); - }); +std::string toString(const SourceSet &ss) { + std::string result; + for (int source : ss) { + if (!result.empty()) result += ", "; + result += (source == -1) ? "all" : std::to_string(source); + } + return result; } DBCManager *dbc() { diff --git a/tools/cabana/dbc/dbcmanager.h b/tools/cabana/dbc/dbcmanager.h index 5f183752d295bf..4a122073eaad58 100644 --- a/tools/cabana/dbc/dbcmanager.h +++ b/tools/cabana/dbc/dbcmanager.h @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include "tools/cabana/dbc/dbcfile.h" @@ -18,27 +20,27 @@ class DBCManager : public QObject { public: DBCManager(QObject *parent) : QObject(parent) {} ~DBCManager() {} - bool open(const SourceSet &sources, const QString &dbc_file_name, QString *error = nullptr); - bool open(const SourceSet &sources, const QString &name, const QString &content, QString *error = nullptr); + bool open(const SourceSet &sources, const std::string &dbc_file_name, QString *error = nullptr); + bool open(const SourceSet &sources, const std::string &name, const std::string &content, QString *error = nullptr); void close(const SourceSet &sources); void close(DBCFile *dbc_file); void closeAll(); void addSignal(const MessageId &id, const cabana::Signal &sig); - void updateSignal(const MessageId &id, const QString &sig_name, const cabana::Signal &sig); - void removeSignal(const MessageId &id, const QString &sig_name); + void updateSignal(const MessageId &id, const std::string &sig_name, const cabana::Signal &sig); + void removeSignal(const MessageId &id, const std::string &sig_name); - void updateMsg(const MessageId &id, const QString &name, uint32_t size, const QString &node, const QString &comment); + void updateMsg(const MessageId &id, const std::string &name, uint32_t size, const std::string &node, const std::string &comment); void removeMsg(const MessageId &id); - QString newMsgName(const MessageId &id); - QString newSignalName(const MessageId &id); + std::string newMsgName(const MessageId &id); + std::string newSignalName(const MessageId &id); const std::map &getMessages(uint8_t source); cabana::Msg *msg(const MessageId &id); - cabana::Msg* msg(uint8_t source, const QString &name); + cabana::Msg* msg(uint8_t source, const std::string &name); - QStringList signalNames(); + std::vector signalNames(); inline int dbcCount() { return allDBCFiles().size(); } int nonEmptyDBCCount(); @@ -62,8 +64,8 @@ class DBCManager : public QObject { DBCManager *dbc(); -QString toString(const SourceSet &ss); -inline QString msgName(const MessageId &id) { +std::string toString(const SourceSet &ss); +inline std::string msgName(const MessageId &id) { auto msg = dbc()->msg(id); return msg ? msg->name : UNTITLED; } diff --git a/tools/cabana/dbc/generate_dbc_json.py b/tools/cabana/dbc/generate_dbc_json.py index 04d45f304a64af..d002a50ef82cac 100755 --- a/tools/cabana/dbc/generate_dbc_json.py +++ b/tools/cabana/dbc/generate_dbc_json.py @@ -2,18 +2,29 @@ import argparse import json +from opendbc.car import Bus from opendbc.car.fingerprints import MIGRATION from opendbc.car.values import PLATFORMS -def generate_dbc_json() -> str: - dbc_map = {platform.name: platform.config.dbc_dict['pt'] for platform in PLATFORMS.values() if platform != "MOCK"} +def generate_dbc_dict() -> dict[str, str]: + dbc_map = {} + for platform in PLATFORMS.values(): + if platform != "MOCK": + if Bus.pt in platform.config.dbc_dict: + dbc_map[platform.name] = platform.config.dbc_dict[Bus.pt] + elif Bus.main in platform.config.dbc_dict: + dbc_map[platform.name] = platform.config.dbc_dict[Bus.main] + elif Bus.party in platform.config.dbc_dict: + dbc_map[platform.name] = platform.config.dbc_dict[Bus.party] + else: + raise ValueError("Unknown main type") for m in MIGRATION: if MIGRATION[m] in dbc_map: dbc_map[m] = dbc_map[MIGRATION[m]] - return json.dumps(dict(sorted(dbc_map.items())), indent=2) + return dbc_map if __name__ == "__main__": @@ -24,5 +35,5 @@ def generate_dbc_json() -> str: args = parser.parse_args() with open(args.out, 'w') as f: - f.write(generate_dbc_json()) + f.write(json.dumps(dict(sorted(generate_dbc_dict().items())), indent=2)) print(f"Generated and written to {args.out}") diff --git a/tools/cabana/detailwidget.cc b/tools/cabana/detailwidget.cc index 7befadb7227169..148b059e5b7e80 100644 --- a/tools/cabana/detailwidget.cc +++ b/tools/cabana/detailwidget.cc @@ -2,7 +2,9 @@ #include #include -#include +#include +#include +#include #include "tools/cabana/commands.h" #include "tools/cabana/mainwin.h" @@ -20,19 +22,7 @@ DetailWidget::DetailWidget(ChartsWidget *charts, QWidget *parent) : charts(chart tabbar->setContextMenuPolicy(Qt::CustomContextMenu); main_layout->addWidget(tabbar); - // message title - QHBoxLayout *title_layout = new QHBoxLayout(); - title_layout->setContentsMargins(3, 6, 3, 0); - auto spacer = new QSpacerItem(0, 1); - title_layout->addItem(spacer); - title_layout->addWidget(name_label = new ElidedLabel(this), 1); - name_label->setStyleSheet("QLabel{font-weight:bold;}"); - name_label->setAlignment(Qt::AlignCenter); - auto edit_btn = new ToolButton("pencil", tr("Edit Message")); - title_layout->addWidget(edit_btn); - title_layout->addWidget(remove_btn = new ToolButton("x-lg", tr("Remove Message"))); - spacer->changeSize(edit_btn->sizeHint().width() * 2 + 9, 1); - main_layout->addLayout(title_layout); + createToolBar(); // warning warning_widget = new QWidget(this); @@ -58,8 +48,6 @@ DetailWidget::DetailWidget(ChartsWidget *charts, QWidget *parent) : charts(chart tab_widget->addTab(history_log = new LogsWidget(this), utils::icon("stopwatch"), "&Logs"); main_layout->addWidget(tab_widget); - QObject::connect(edit_btn, &QToolButton::clicked, this, &DetailWidget::editMsg); - QObject::connect(remove_btn, &QToolButton::clicked, this, &DetailWidget::removeMsg); QObject::connect(binary_view, &BinaryView::signalHovered, signal_view, &SignalView::signalHovered); QObject::connect(binary_view, &BinaryView::signalClicked, [this](const cabana::Signal *s) { signal_view->selectSignal(s, true); }); QObject::connect(binary_view, &BinaryView::editSignal, signal_view->model, &SignalModel::saveSignal); @@ -80,6 +68,41 @@ DetailWidget::DetailWidget(ChartsWidget *charts, QWidget *parent) : charts(chart QObject::connect(charts, &ChartsWidget::seriesChanged, signal_view, &SignalView::updateChartState); } +void DetailWidget::createToolBar() { + QToolBar *toolbar = new QToolBar(this); + int icon_size = style()->pixelMetric(QStyle::PM_SmallIconSize); + toolbar->setIconSize({icon_size, icon_size}); + toolbar->addWidget(name_label = new ElidedLabel(this)); + name_label->setStyleSheet("QLabel{font-weight:bold;}"); + + QWidget *spacer = new QWidget(); + spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + toolbar->addWidget(spacer); + +// Heatmap label and radio buttons + toolbar->addWidget(new QLabel(tr("Heatmap:"), this)); + auto *heatmap_live = new QRadioButton(tr("Live"), this); + auto *heatmap_all = new QRadioButton(tr("All"), this); + heatmap_live->setChecked(true); + + toolbar->addWidget(heatmap_live); + toolbar->addWidget(heatmap_all); + + // Edit and remove buttons + toolbar->addSeparator(); + toolbar->addAction(utils::icon("pencil"), tr("Edit Message"), this, &DetailWidget::editMsg); + action_remove_msg = toolbar->addAction(utils::icon("x-lg"), tr("Remove Message"), this, &DetailWidget::removeMsg); + + layout()->addWidget(toolbar); + + connect(heatmap_live, &QAbstractButton::toggled, this, [this](bool on) { binary_view->setHeatmapLiveMode(on); }); + connect(can, &AbstractStream::timeRangeChanged, this, [=](const std::optional> &range) { + auto text = range ? QString("%1 - %2").arg(range->first, 0, 'f', 3).arg(range->second, 0, 'f', 3) : "All"; + heatmap_all->setText(text); + (range ? heatmap_all : heatmap_live)->setChecked(true); + }); +} + void DetailWidget::showTabBarContextMenu(const QPoint &pt) { int index = tabbar->tabAt(pt); if (index >= 0) { @@ -95,19 +118,24 @@ void DetailWidget::showTabBarContextMenu(const QPoint &pt) { } } -void DetailWidget::setMessage(const MessageId &message_id) { - if (std::exchange(msg_id, message_id) == message_id) return; - - tabbar->blockSignals(true); +int DetailWidget::findOrAddTab(const MessageId& message_id) { int index = tabbar->count() - 1; for (/**/; index >= 0; --index) { if (tabbar->tabData(index).value() == message_id) break; } if (index == -1) { - index = tabbar->addTab(message_id.toString()); + index = tabbar->addTab(QString::fromStdString(message_id.toString())); tabbar->setTabData(index, QVariant::fromValue(message_id)); - tabbar->setTabToolTip(index, msgName(message_id)); + tabbar->setTabToolTip(index, QString::fromStdString(msgName(message_id))); } + return index; +} + +void DetailWidget::setMessage(const MessageId &message_id) { + if (std::exchange(msg_id, message_id) == message_id) return; + + tabbar->blockSignals(true); + int index = findOrAddTab(message_id); tabbar->setCurrentIndex(index); tabbar->blockSignals(false); @@ -119,6 +147,29 @@ void DetailWidget::setMessage(const MessageId &message_id) { setUpdatesEnabled(true); } +std::pair DetailWidget::serializeMessageIds() const { + QStringList msgs; + for (int i = 0; i < tabbar->count(); ++i) { + MessageId id = tabbar->tabData(i).value(); + msgs.append(QString::fromStdString(id.toString())); + } + return std::make_pair(QString::fromStdString(msg_id.toString()), msgs); +} + +void DetailWidget::restoreTabs(const QString active_msg_id, const QStringList& msg_ids) { + tabbar->blockSignals(true); + for (const auto& str_id : msg_ids) { + MessageId id = MessageId::fromString(str_id.toStdString()); + if (dbc()->msg(id) != nullptr) + findOrAddTab(id); + } + tabbar->blockSignals(false); + + auto active_id = MessageId::fromString(active_msg_id.toStdString()); + if (dbc()->msg(active_id) != nullptr) + setMessage(active_id); +} + void DetailWidget::refresh() { QStringList warnings; auto msg = dbc()->msg(msg_id); @@ -129,16 +180,13 @@ void DetailWidget::refresh() { warnings.push_back(tr("Message size (%1) is incorrect.").arg(msg->size)); } for (auto s : binary_view->getOverlappingSignals()) { - warnings.push_back(tr("%1 has overlapping bits.").arg(s->name)); + warnings.push_back(tr("%1 has overlapping bits.").arg(QString::fromStdString(s->name))); } - } else { - warnings.push_back(tr("Drag-Select in binary view to create new signal.")); } - - QString msg_name = msg ? QString("%1 (%2)").arg(msg->name, msg->transmitter) : msgName(msg_id); + QString msg_name = msg ? QString("%1 (%2)").arg(QString::fromStdString(msg->name), QString::fromStdString(msg->transmitter)) : QString::fromStdString(msgName(msg_id)); name_label->setText(msg_name); name_label->setToolTip(msg_name); - remove_btn->setEnabled(msg != nullptr); + action_remove_msg->setEnabled(msg != nullptr); if (!warnings.isEmpty()) { warning_label->setText(warnings.join('\n')); @@ -160,10 +208,10 @@ void DetailWidget::updateState(const std::set *msgs) { void DetailWidget::editMsg() { auto msg = dbc()->msg(msg_id); int size = msg ? msg->size : can->lastMessage(msg_id).dat.size(); - EditMessageDialog dlg(msg_id, msgName(msg_id), size, this); + EditMessageDialog dlg(msg_id, QString::fromStdString(msgName(msg_id)), size, this); if (dlg.exec()) { - UndoStack::push(new EditMsgCommand(msg_id, dlg.name_edit->text().trimmed(), dlg.size_spin->value(), - dlg.node->text().trimmed(), dlg.comment_edit->toPlainText().trimmed())); + UndoStack::push(new EditMsgCommand(msg_id, dlg.name_edit->text().trimmed().toStdString(), dlg.size_spin->value(), + dlg.node->text().trimmed().toStdString(), dlg.comment_edit->toPlainText().trimmed().toStdString())); } } @@ -175,7 +223,7 @@ void DetailWidget::removeMsg() { EditMessageDialog::EditMessageDialog(const MessageId &msg_id, const QString &title, int size, QWidget *parent) : original_name(title), msg_id(msg_id), QDialog(parent) { - setWindowTitle(tr("Edit message: %1").arg(msg_id.toString())); + setWindowTitle(tr("Edit message: %1").arg(QString::fromStdString(msg_id.toString()))); QFormLayout *form_layout = new QFormLayout(this); form_layout->addRow("", error_label = new QLabel); @@ -184,8 +232,7 @@ EditMessageDialog::EditMessageDialog(const MessageId &msg_id, const QString &tit name_edit->setValidator(new NameValidator(name_edit)); form_layout->addRow(tr("Size"), size_spin = new QSpinBox(this)); - // TODO: limit the maximum? - size_spin->setMinimum(1); + size_spin->setRange(1, CAN_MAX_DATA_BYTES); size_spin->setValue(size); form_layout->addRow(tr("Node"), node = new QLineEdit(this)); @@ -194,8 +241,8 @@ EditMessageDialog::EditMessageDialog(const MessageId &msg_id, const QString &tit form_layout->addRow(btn_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel)); if (auto msg = dbc()->msg(msg_id)) { - node->setText(msg->transmitter); - comment_edit->setText(msg->comment); + node->setText(QString::fromStdString(msg->transmitter)); + comment_edit->setText(QString::fromStdString(msg->comment)); } validateName(name_edit->text()); setFixedWidth(parent->width() * 0.9); @@ -205,10 +252,10 @@ EditMessageDialog::EditMessageDialog(const MessageId &msg_id, const QString &tit } void EditMessageDialog::validateName(const QString &text) { - bool valid = text.compare(UNTITLED, Qt::CaseInsensitive) != 0; + bool valid = text.compare(QString::fromStdString(UNTITLED), Qt::CaseInsensitive) != 0; error_label->setVisible(false); if (!text.isEmpty() && valid && text != original_name) { - valid = dbc()->msg(msg_id.source, text) == nullptr; + valid = dbc()->msg(msg_id.source, text.toStdString()) == nullptr; if (!valid) { error_label->setText(tr("Name already exists")); error_label->setVisible(true); @@ -225,13 +272,13 @@ CenterWidget::CenterWidget(QWidget *parent) : QWidget(parent) { main_layout->addWidget(welcome_widget = createWelcomeWidget()); } -void CenterWidget::setMessage(const MessageId &msg_id) { +DetailWidget* CenterWidget::ensureDetailWidget() { if (!detail_widget) { delete welcome_widget; welcome_widget = nullptr; layout()->addWidget(detail_widget = new DetailWidget(((MainWindow*)parentWidget())->charts_widget, this)); } - detail_widget->setMessage(msg_id); + return detail_widget; } void CenterWidget::clear() { diff --git a/tools/cabana/detailwidget.h b/tools/cabana/detailwidget.h index 15e1ee5f2f954b..0fe1535c7ab265 100644 --- a/tools/cabana/detailwidget.h +++ b/tools/cabana/detailwidget.h @@ -6,11 +6,11 @@ #include #include -#include "selfdrive/ui/qt/widgets/controls.h" #include "tools/cabana/binaryview.h" #include "tools/cabana/chart/chartswidget.h" #include "tools/cabana/historylog.h" #include "tools/cabana/signalview.h" +#include "tools/cabana/utils/elidedlabel.h" class EditMessageDialog : public QDialog { public: @@ -34,8 +34,12 @@ class DetailWidget : public QWidget { DetailWidget(ChartsWidget *charts, QWidget *parent); void setMessage(const MessageId &message_id); void refresh(); + std::pair serializeMessageIds() const; + void restoreTabs(const QString active_msg_id, const QStringList &msg_ids); private: + void createToolBar(); + int findOrAddTab(const MessageId& message_id); void showTabBarContextMenu(const QPoint &pt); void editMsg(); void removeMsg(); @@ -47,7 +51,7 @@ class DetailWidget : public QWidget { QWidget *warning_widget; TabBar *tabbar; QTabWidget *tab_widget; - QToolButton *remove_btn; + QAction *action_remove_msg; LogsWidget *history_log; BinaryView *binary_view; SignalView *signal_view; @@ -59,7 +63,9 @@ class CenterWidget : public QWidget { Q_OBJECT public: CenterWidget(QWidget *parent); - void setMessage(const MessageId &msg_id); + void setMessage(const MessageId &message_id) { ensureDetailWidget()->setMessage(message_id); } + DetailWidget* getDetailWidget() { return detail_widget; } + DetailWidget* ensureDetailWidget(); void clear(); private: diff --git a/tools/cabana/historylog.cc b/tools/cabana/historylog.cc index 7e73da55f08844..fb79ff9cea1d79 100644 --- a/tools/cabana/historylog.cc +++ b/tools/cabana/historylog.cc @@ -14,7 +14,7 @@ QVariant HistoryLogModel::data(const QModelIndex &index, int role) const { const int col = index.column(); if (role == Qt::DisplayRole) { if (col == 0) return QString::number(can->toSeconds(m.mono_time), 'f', 3); - if (!isHexMode()) return sigs[col - 1]->formatValue(m.sig_values[col - 1], false); + if (!isHexMode()) return QString::fromStdString(sigs[col - 1]->formatValue(m.sig_values[col - 1], false)); } else if (role == Qt::TextAlignmentRole) { return (uint32_t)(Qt::AlignRight | Qt::AlignVCenter); } @@ -49,8 +49,8 @@ QVariant HistoryLogModel::headerData(int section, Qt::Orientation orientation, i if (section == 0) return "Time"; if (isHexMode()) return "Data"; - QString name = sigs[section - 1]->name; - QString unit = sigs[section - 1]->unit; + QString name = QString::fromStdString(sigs[section - 1]->name); + QString unit = QString::fromStdString(sigs[section - 1]->unit); return unit.isEmpty() ? name : QString("%1 (%2)").arg(name, unit); } else if (role == Qt::BackgroundRole && section > 0 && !isHexMode()) { // Alpha-blend the signal color with the background to ensure contrast @@ -153,7 +153,7 @@ void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalI painter->fillRect(rect, bg_role.value()); } QString text = model()->headerData(logicalIndex, Qt::Horizontal, Qt::DisplayRole).toString(); - painter->setPen(palette().color(settings.theme == DARK_THEME ? QPalette::BrightText : QPalette::Text)); + painter->setPen(palette().color(utils::isDarkTheme() ? QPalette::BrightText : QPalette::Text)); painter->drawText(rect.adjusted(5, 3, -5, -3), defaultAlignment(), text.replace(QChar('_'), ' ')); } @@ -216,7 +216,7 @@ LogsWidget::LogsWidget(QWidget *parent) : QFrame(parent) { void LogsWidget::modelReset() { signals_cb->clear(); for (auto s : model->sigs) { - signals_cb->addItem(s->name); + signals_cb->addItem(QString::fromStdString(s->name)); } export_btn->setEnabled(false); value_edit->clear(); @@ -238,8 +238,8 @@ void LogsWidget::filterChanged() { } void LogsWidget::exportToCSV() { - QString dir = QString("%1/%2_%3.csv").arg(settings.last_dir).arg(can->routeName()).arg(msgName(model->msg_id)); - QString fn = QFileDialog::getSaveFileName(this, QString("Export %1 to CSV file").arg(msgName(model->msg_id)), + QString dir = QString("%1/%2_%3.csv").arg(settings.last_dir).arg(QString::fromStdString(can->routeName())).arg(QString::fromStdString(msgName(model->msg_id))); + QString fn = QFileDialog::getSaveFileName(this, QString("Export %1 to CSV file").arg(QString::fromStdString(msgName(model->msg_id))), dir, tr("csv (*.csv)")); if (!fn.isEmpty()) { model->isHexMode() ? utils::exportToCSV(fn, model->msg_id) diff --git a/tools/cabana/mainwin.cc b/tools/cabana/mainwin.cc index ee8f42ea727dac..39fb979c798b0b 100644 --- a/tools/cabana/mainwin.cc +++ b/tools/cabana/mainwin.cc @@ -24,6 +24,8 @@ #include "tools/cabana/streamselector.h" #include "tools/cabana/tools/findsignal.h" #include "tools/cabana/utils/export.h" +#include "tools/replay/py_downloader.h" +#include "tools/replay/util.h" MainWindow::MainWindow(AbstractStream *stream, const QString &dbc_file) : QMainWindow() { loadFingerprints(); @@ -51,7 +53,7 @@ MainWindow::MainWindow(AbstractStream *stream, const QString &dbc_file) : QMainW emit static_main_win->updateProgressBar(cur, total, success); }); qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &context, const QString &msg) { - if (type == QtDebugMsg) std::cout << msg.toStdString() << std::endl; + if (type == QtDebugMsg) return; emit static_main_win->showMessage(msg, 2000); }); installMessageHandler([](ReplyMsgType type, const std::string msg) { qInfo() << msg.c_str(); }); @@ -122,7 +124,7 @@ void MainWindow::createActions() { auto undo_act = UndoStack::instance()->createUndoAction(this, tr("&Undo")); undo_act->setShortcuts(QKeySequence::Undo); edit_menu->addAction(undo_act); - auto redo_act = UndoStack::instance()->createRedoAction(this, tr("&Rndo")); + auto redo_act = UndoStack::instance()->createRedoAction(this, tr("&Redo")); redo_act->setShortcuts(QKeySequence::Redo); edit_menu->addAction(redo_act); edit_menu->addSeparator(); @@ -191,6 +193,7 @@ void MainWindow::createDockWidgets() { video_splitter->handle(1)->setEnabled(!can->liveStreaming()); video_dock->setWidget(video_splitter); QObject::connect(charts_widget, &ChartsWidget::toggleChartsDocking, this, &MainWindow::toggleChartsDocking); + QObject::connect(charts_widget, &ChartsWidget::showTip, video_widget, &VideoWidget::showThumbnail); } void MainWindow::createStatusBar() { @@ -231,9 +234,11 @@ void MainWindow::DBCFileChanged() { QStringList title; for (auto f : dbc()->allDBCFiles()) { - title.push_back(tr("(%1) %2").arg(toString(dbc()->sources(f)), f->name())); + title.push_back(tr("(%1) %2").arg(QString::fromStdString(toString(dbc()->sources(f))), QString::fromStdString(f->name()))); } setWindowFilePath(title.join(" | ")); + + QTimer::singleShot(0, this, &::MainWindow::restoreSessionState); } void MainWindow::selectAndOpenStream() { @@ -254,7 +259,7 @@ void MainWindow::closeStream() { } void MainWindow::exportToCSV() { - QString dir = QString("%1/%2.csv").arg(settings.last_dir).arg(can->routeName()); + QString dir = QString("%1/%2.csv").arg(settings.last_dir).arg(QString::fromStdString(can->routeName())); QString fn = QFileDialog::getSaveFileName(this, "Export stream to CSV file", dir, tr("csv (*.csv)")); if (!fn.isEmpty()) { utils::exportToCSV(fn); @@ -263,7 +268,7 @@ void MainWindow::exportToCSV() { void MainWindow::newFile(SourceSet s) { closeFile(s); - dbc()->open(s, "", ""); + dbc()->open(s, std::string(""), std::string("")); } void MainWindow::openFile(SourceSet s) { @@ -279,7 +284,7 @@ void MainWindow::loadFile(const QString &fn, SourceSet s) { closeFile(s); QString error; - if (dbc()->open(s, fn, &error)) { + if (dbc()->open(s, fn.toStdString(), &error)) { updateRecentFiles(fn); statusBar()->showMessage(tr("DBC File %1 loaded").arg(fn), 2000); } else { @@ -299,7 +304,7 @@ void MainWindow::loadFromClipboard(SourceSet s, bool close_all) { QString dbc_str = QGuiApplication::clipboard()->text(); QString error; - bool ret = dbc()->open(s, "", dbc_str, &error); + bool ret = dbc()->open(s, std::string(""), dbc_str.toStdString(), &error); if (ret && dbc()->nonEmptyDBCCount() > 0) { QMessageBox::information(this, tr("Load From Clipboard"), tr("DBC Successfully Loaded!")); } else { @@ -310,17 +315,25 @@ void MainWindow::loadFromClipboard(SourceSet s, bool close_all) { } void MainWindow::openStream(AbstractStream *stream, const QString &dbc_file) { + if (can) { + QObject::connect(can, &QObject::destroyed, this, [=]() { startStream(stream, dbc_file); }); + can->deleteLater(); + } else { + startStream(stream, dbc_file); + } +} + +void MainWindow::startStream(AbstractStream *stream, QString dbc_file) { center_widget->clear(); delete messages_widget; delete video_splitter; - delete can; can = stream; can->setParent(this); // take ownership can->start(); loadFile(dbc_file); - statusBar()->showMessage(tr("Stream [%1] started").arg(can->routeName()), 2000); + statusBar()->showMessage(tr("Stream [%1] started").arg(QString::fromStdString(can->routeName())), 2000); bool has_stream = dynamic_cast(can) == nullptr; close_stream_act->setEnabled(has_stream); @@ -328,7 +341,7 @@ void MainWindow::openStream(AbstractStream *stream, const QString &dbc_file) { tools_menu->setEnabled(has_stream); createDockWidgets(); - video_dock->setWindowTitle(can->routeName()); + video_dock->setWindowTitle(QString::fromStdString(can->routeName())); if (can->liveStreaming() || video_splitter->sizes()[0] == 0) { // display video at minimum size. video_splitter->setSizes({1, 1}); @@ -355,9 +368,9 @@ void MainWindow::openStream(AbstractStream *stream, const QString &dbc_file) { } void MainWindow::eventsMerged() { - if (!can->liveStreaming() && std::exchange(car_fingerprint, can->carFingerprint()) != car_fingerprint) { + if (!can->liveStreaming() && std::exchange(car_fingerprint, QString::fromStdString(can->carFingerprint())) != car_fingerprint) { video_dock->setWindowTitle(tr("ROUTE: %1 FINGERPRINT: %2") - .arg(can->routeName()) + .arg(QString::fromStdString(can->routeName())) .arg(car_fingerprint.isEmpty() ? tr("Unknown Car") : car_fingerprint)); // Don't overwrite already loaded DBC if (!dbc()->nonEmptyDBCCount() && fingerprint_to_dbc.object().contains(car_fingerprint)) { @@ -403,7 +416,7 @@ void MainWindow::closeFile(DBCFile *dbc_file) { void MainWindow::saveFile(DBCFile *dbc_file) { assert(dbc_file != nullptr); - if (!dbc_file->filename.isEmpty()) { + if (!dbc_file->filename.empty()) { dbc_file->save(); UndoStack::instance()->setClean(); statusBar()->showMessage(tr("File saved"), 2000); @@ -413,10 +426,10 @@ void MainWindow::saveFile(DBCFile *dbc_file) { } void MainWindow::saveFileAs(DBCFile *dbc_file) { - QString title = tr("Save File (bus: %1)").arg(toString(dbc()->sources(dbc_file))); + QString title = tr("Save File (bus: %1)").arg(QString::fromStdString(toString(dbc()->sources(dbc_file)))); QString fn = QFileDialog::getSaveFileName(this, title, QDir::cleanPath(settings.last_dir + "/untitled.dbc"), tr("DBC (*.dbc)")); if (!fn.isEmpty()) { - dbc_file->saveAs(fn); + dbc_file->saveAs(fn.toStdString()); UndoStack::instance()->setClean(); statusBar()->showMessage(tr("File saved as %1").arg(fn), 2000); updateRecentFiles(fn); @@ -433,7 +446,7 @@ void MainWindow::saveToClipboard() { void MainWindow::saveFileToClipboard(DBCFile *dbc_file) { assert(dbc_file != nullptr); - QGuiApplication::clipboard()->setText(dbc_file->generateDBC()); + QGuiApplication::clipboard()->setText(QString::fromStdString(dbc_file->generateDBC())); QMessageBox::information(this, tr("Copy To Clipboard"), tr("DBC Successfully copied!")); } @@ -454,14 +467,14 @@ void MainWindow::updateLoadSaveMenus() { auto dbc_file = dbc()->findDBCFile(source); if (dbc_file) { bus_menu->addSeparator(); - bus_menu->addAction(dbc_file->name() + " (" + toString(dbc()->sources(dbc_file)) + ")")->setEnabled(false); + bus_menu->addAction(QString::fromStdString(dbc_file->name()) + " (" + QString::fromStdString(toString(dbc()->sources(dbc_file))) + ")")->setEnabled(false); bus_menu->addAction(tr("Save..."), [=]() { saveFile(dbc_file); }); bus_menu->addAction(tr("Save As..."), [=]() { saveFileAs(dbc_file); }); bus_menu->addAction(tr("Copy to Clipboard..."), [=]() { saveFileToClipboard(dbc_file); }); bus_menu->addAction(tr("Remove from this bus..."), [=]() { closeFile(ss); }); bus_menu->addAction(tr("Remove from all buses..."), [=]() { closeFile(dbc_file); }); } - bus_menu->setTitle(tr("Bus %1 (%2)").arg(source).arg(dbc_file ? dbc_file->name() : "No DBCs loaded")); + bus_menu->setTitle(tr("Bus %1 (%2)").arg(source).arg(dbc_file ? QString::fromStdString(dbc_file->name()) : "No DBCs loaded")); manage_dbcs_menu->addMenu(bus_menu); } @@ -558,8 +571,11 @@ void MainWindow::closeEvent(QCloseEvent *event) { if (can && !can->liveStreaming()) { settings.video_splitter_state = video_splitter->saveState(); } - settings.message_header_state = messages_widget->saveHeaderState(); + if (messages_widget) { + settings.message_header_state = messages_widget->saveHeaderState(); + } + saveSessionState(); QWidget::closeEvent(event); } @@ -604,6 +620,39 @@ void MainWindow::toggleFullScreen() { } } +void MainWindow::saveSessionState() { + settings.recent_dbc_file = ""; + settings.active_msg_id = ""; + settings.selected_msg_ids.clear(); + settings.active_charts.clear(); + + for (auto &f : dbc()->allDBCFiles()) + if (!f->isEmpty()) { settings.recent_dbc_file = QString::fromStdString(f->filename); break; } + + if (auto *detail = center_widget->getDetailWidget()) { + auto [active_id, ids] = detail->serializeMessageIds(); + settings.active_msg_id = active_id; + settings.selected_msg_ids = ids; + } + if (charts_widget) + settings.active_charts = charts_widget->serializeChartIds(); +} + +void MainWindow::restoreSessionState() { + if (settings.recent_dbc_file.isEmpty() || dbc()->nonEmptyDBCCount() == 0) return; + + QString dbc_file; + for (auto& f : dbc()->allDBCFiles()) + if (!f->isEmpty()) { dbc_file = QString::fromStdString(f->filename); break; } + if (dbc_file != settings.recent_dbc_file) return; + + if (!settings.selected_msg_ids.isEmpty()) + center_widget->ensureDetailWidget()->restoreTabs(settings.active_msg_id, settings.selected_msg_ids); + + if (charts_widget != nullptr && !settings.active_charts.empty()) + charts_widget->restoreChartsFromIds(settings.active_charts); +} + // HelpOverlay HelpOverlay::HelpOverlay(MainWindow *parent) : QWidget(parent) { setAttribute(Qt::WA_NoSystemBackground, true); diff --git a/tools/cabana/mainwin.h b/tools/cabana/mainwin.h index 9bc94c090f7d71..92c2714ae70221 100644 --- a/tools/cabana/mainwin.h +++ b/tools/cabana/mainwin.h @@ -44,6 +44,7 @@ public slots: void updateProgressBar(uint64_t cur, uint64_t total, bool success); protected: + void startStream(AbstractStream *stream, QString dbc_file); bool eventFilter(QObject *obj, QEvent *event) override; void remindSaveChanges(); void closeFile(SourceSet s = SOURCE_ALL); @@ -72,6 +73,8 @@ public slots: void updateLoadSaveMenus(); void createDockWidgets(); void eventsMerged(); + void saveSessionState(); + void restoreSessionState(); VideoWidget *video_widget = nullptr; QDockWidget *video_dock; diff --git a/tools/cabana/messageswidget.cc b/tools/cabana/messageswidget.cc index d6c2fd0ea929ec..75cdaa7cc3a64a 100644 --- a/tools/cabana/messageswidget.cc +++ b/tools/cabana/messageswidget.cc @@ -13,19 +13,6 @@ #include "tools/cabana/commands.h" -static bool isMessageActive(const MessageId &id) { - if (auto dummy_stream = dynamic_cast(can)) { - return true; - } - if (id.source == INVALID_SOURCE) { - return false; - } - // Check if the message is active based on time difference and frequency - const auto &m = can->lastMessage(id); - float delta = can->currentSec() - m.ts; - return (m.freq == 0 && delta < 1.5) || (m.freq > 0 && ((delta - 1.0 / settings.fps) < (5.0 / m.freq))); -} - MessagesWidget::MessagesWidget(QWidget *parent) : menu(new QMenu(this)), QWidget(parent) { QVBoxLayout *main_layout = new QVBoxLayout(this); main_layout->setContentsMargins(0, 0, 0, 0); @@ -77,7 +64,7 @@ MessagesWidget::MessagesWidget(QWidget *parent) : menu(new QMenu(this)), QWidget setWhatsThis(tr(R"( Message View
- + Byte color
■ constant changing
■ increasing
@@ -159,7 +146,7 @@ void MessagesWidget::menuAboutToShow() { action->setCheckable(true); action->setChecked(settings.multiple_lines_hex); - action = menu->addAction(tr("Show inactive Messages"), model, &MessageListModel::showInactivemessages); + action = menu->addAction(tr("Show inactive messages"), model, &MessageListModel::showInactiveMessages); action->setCheckable(true); action->setChecked(model->show_inactive_messages); } @@ -199,13 +186,13 @@ QVariant MessageListModel::data(const QModelIndex &index, int role) const { } }; - const static QString NA = QStringLiteral("N/A"); + const static QString NA = QStringLiteral("N/A"); const auto &item = items_[index.row()]; if (role == Qt::DisplayRole) { switch (index.column()) { case Column::NAME: return item.name; case Column::SOURCE: return item.id.source != INVALID_SOURCE ? QString::number(item.id.source) : NA; - case Column::ADDRESS: return QString::number(item.id.address, 16); + case Column::ADDRESS: return toHexString(item.id.address); case Column::NODE: return item.node; case Column::FREQ: return item.id.source != INVALID_SOURCE ? getFreq(can->lastMessage(item.id).freq) : NA; case Column::COUNT: return item.id.source != INVALID_SOURCE ? QString::number(can->lastMessage(item.id).count) : NA; @@ -215,12 +202,10 @@ QVariant MessageListModel::data(const QModelIndex &index, int role) const { return QVariant::fromValue((void*)(&can->lastMessage(item.id).colors)); } else if (role == BytesRole && index.column() == Column::DATA && item.id.source != INVALID_SOURCE) { return QVariant::fromValue((void*)(&can->lastMessage(item.id).dat)); - } else if (role == Qt::ForegroundRole && !item.active) { - return settings.theme == DARK_THEME ? QApplication::palette().color(QPalette::Text).darker(150) : QColor(Qt::gray); } else if (role == Qt::ToolTipRole && index.column() == Column::NAME) { auto msg = dbc()->msg(item.id); auto tooltip = item.name; - if (msg && !msg->comment.isEmpty()) tooltip += "
" + msg->comment + ""; + if (msg && !msg->comment.empty()) tooltip += "
" + QString::fromStdString(msg->comment) + ""; return tooltip; } return {}; @@ -231,7 +216,7 @@ void MessageListModel::setFilterStrings(const QMap &filters) { filterAndSort(); } -void MessageListModel::showInactivemessages(bool show) { +void MessageListModel::showInactiveMessages(bool show) { show_inactive_messages = show; filterAndSort(); } @@ -292,7 +277,7 @@ bool MessageListModel::match(const MessageListModel::Item &item) { if (!match) { const auto m = dbc()->msg(item.id); match = m && std::any_of(m->sigs.cbegin(), m->sigs.cend(), - [&txt](const auto &s) { return s->name.contains(txt, Qt::CaseInsensitive); }); + [&txt](const auto &s) { return QString::fromStdString(s->name).contains(txt, Qt::CaseInsensitive); }); } break; } @@ -300,7 +285,7 @@ bool MessageListModel::match(const MessageListModel::Item &item) { match = parseRange(txt, item.id.source); break; case Column::ADDRESS: - match = QString::number(item.id.address, 16).contains(txt, Qt::CaseInsensitive); + match = toHexString(item.id.address).contains(txt, Qt::CaseInsensitive); match = match || parseRange(txt, item.id.address, 16); break; case Column::NODE: @@ -335,13 +320,11 @@ bool MessageListModel::filterAndSort() { std::vector items; items.reserve(all_messages.size()); for (const auto &id : all_messages) { - bool active = isMessageActive(id); - if (active || show_inactive_messages) { + if (show_inactive_messages || can->isMessageActive(id)) { auto msg = dbc()->msg(id); Item item = {.id = id, - .active = active, - .name = msg ? msg->name : UNTITLED, - .node = msg ? msg->transmitter : QString()}; + .name = msg ? QString::fromStdString(msg->name) : QString::fromStdString(UNTITLED), + .node = msg ? QString::fromStdString(msg->transmitter) : QString()}; if (match(item)) items.emplace_back(item); } @@ -364,9 +347,6 @@ void MessageListModel::msgsReceived(const std::set *new_msgs, bool ha if (filterAndSort()) return; } - for (auto &item : items_) { - item.active = isMessageActive(item.id); - } // Update viewport emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); } @@ -382,7 +362,17 @@ void MessageListModel::sort(int column, Qt::SortOrder order) { // MessageView void MessageView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - QTreeView::drawRow(painter, option, index); + const auto &item = ((MessageListModel*)model())->items_[index.row()]; + if (!can->isMessageActive(item.id)) { + QStyleOptionViewItem custom_option = option; + custom_option.palette.setBrush(QPalette::Text, custom_option.palette.color(QPalette::Disabled, QPalette::Text)); + auto color = QApplication::palette().color(QPalette::HighlightedText); + color.setAlpha(100); + custom_option.palette.setBrush(QPalette::HighlightedText, color); + QTreeView::drawRow(painter, custom_option, index); + } else { + QTreeView::drawRow(painter, option, index); + } QPen oldPen = painter->pen(); const int gridHint = style()->styleHint(QStyle::SH_Table_GridLineColor, &option, this); diff --git a/tools/cabana/messageswidget.h b/tools/cabana/messageswidget.h index 823fcb74e35ebe..9ffb156604d9be 100644 --- a/tools/cabana/messageswidget.h +++ b/tools/cabana/messageswidget.h @@ -36,7 +36,7 @@ Q_OBJECT int rowCount(const QModelIndex &parent = QModelIndex()) const override { return items_.size(); } void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; void setFilterStrings(const QMap &filters); - void showInactivemessages(bool show); + void showInactiveMessages(bool show); void msgsReceived(const std::set *new_msgs, bool has_new_ids); bool filterAndSort(); void dbcModified(); @@ -45,7 +45,6 @@ Q_OBJECT MessageId id; QString name; QString node; - bool active; bool operator==(const Item &other) const { return id == other.id && name == other.name && node == other.node; } diff --git a/tools/cabana/panda.cc b/tools/cabana/panda.cc new file mode 100644 index 00000000000000..0612d677469a03 --- /dev/null +++ b/tools/cabana/panda.cc @@ -0,0 +1,346 @@ +#include "tools/cabana/panda.h" + +#include +#include +#include +#include +#include + +#include "cereal/messaging/messaging.h" +#include "common/swaglog.h" +#include "common/util.h" + +static libusb_context *init_usb_ctx() { + libusb_context *context = nullptr; + int err = libusb_init(&context); + if (err != 0) { + LOGE("libusb initialization error"); + return nullptr; + } + +#if LIBUSB_API_VERSION >= 0x01000106 + libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); +#else + libusb_set_debug(context, 3); +#endif + return context; +} + +Panda::Panda(std::string serial, uint32_t bus_offset) : bus_offset(bus_offset) { + if (!init_usb_connection(serial)) { + throw std::runtime_error("Error connecting to panda"); + } + + LOGW("connected to %s over USB", serial.c_str()); + hw_type = get_hw_type(); + can_reset_communications(); +} + +Panda::~Panda() { + cleanup_usb(); +} + +bool Panda::connected() { + return connected_flag; +} + +bool Panda::comms_healthy() { + return comms_healthy_flag; +} + +std::string Panda::hw_serial() { + return hw_serial_str; +} + +std::vector Panda::list(bool usb_only) { + static std::unique_ptr context(init_usb_ctx(), libusb_exit); + + ssize_t num_devices; + libusb_device **dev_list = NULL; + std::vector serials; + if (!context) { return serials; } + + num_devices = libusb_get_device_list(context.get(), &dev_list); + if (num_devices < 0) { + LOGE("libusb can't get device list"); + goto finish; + } + + for (size_t i = 0; i < num_devices; ++i) { + libusb_device *device = dev_list[i]; + libusb_device_descriptor desc; + libusb_get_device_descriptor(device, &desc); + if (desc.idVendor == 0x3801 && desc.idProduct == 0xddcc) { + libusb_device_handle *handle = NULL; + int ret = libusb_open(device, &handle); + if (ret < 0) { goto finish; } + + unsigned char desc_serial[26] = { 0 }; + ret = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); + libusb_close(handle); + if (ret < 0) { goto finish; } + + serials.push_back(std::string((char *)desc_serial, ret)); + } + } + +finish: + if (dev_list != NULL) { + libusb_free_device_list(dev_list, 1); + } + return serials; +} + +void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param) { + control_write(0xdc, (uint16_t)safety_model, safety_param); +} + + +cereal::PandaState::PandaType Panda::get_hw_type() { + unsigned char hw_query[1] = {0}; + + control_read(0xc1, 0, 0, hw_query, 1); + return (cereal::PandaState::PandaType)(hw_query[0]); +} + + + + +void Panda::send_heartbeat(bool engaged) { + control_write(0xf3, engaged, 0); +} + +void Panda::set_can_speed_kbps(uint16_t bus, uint16_t speed) { + control_write(0xde, bus, (speed * 10)); +} + + +void Panda::set_data_speed_kbps(uint16_t bus, uint16_t speed) { + control_write(0xf9, bus, (speed * 10)); +} + + + +bool Panda::can_receive(std::vector& out_vec) { + // Check if enough space left in buffer to store RECV_SIZE data + assert(receive_buffer_size + RECV_SIZE <= sizeof(receive_buffer)); + + int recv = bulk_read(0x81, &receive_buffer[receive_buffer_size], RECV_SIZE); + if (!comms_healthy()) { + return false; + } + + bool ret = true; + if (recv > 0) { + receive_buffer_size += recv; + ret = unpack_can_buffer(receive_buffer, receive_buffer_size, out_vec); + } + return ret; +} + +void Panda::can_reset_communications() { + control_write(0xc0, 0, 0); +} + +bool Panda::unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec) { + int pos = 0; + + while (pos <= size - sizeof(can_header)) { + can_header header; + memcpy(&header, &data[pos], sizeof(can_header)); + + const uint8_t data_len = dlc_to_len[header.data_len_code]; + if (pos + sizeof(can_header) + data_len > size) { + // we don't have all the data for this message yet + break; + } + + if (calculate_checksum(&data[pos], sizeof(can_header) + data_len) != 0) { + LOGE("Panda CAN checksum failed"); + size = 0; + can_reset_communications(); + return false; + } + + can_frame &canData = out_vec.emplace_back(); + canData.address = header.addr; + canData.src = header.bus + bus_offset; + if (header.rejected) { + canData.src += CAN_REJECTED_BUS_OFFSET; + } + if (header.returned) { + canData.src += CAN_RETURNED_BUS_OFFSET; + } + + canData.dat.assign((char *)&data[pos + sizeof(can_header)], data_len); + + pos += sizeof(can_header) + data_len; + } + + // move the overflowing data to the beginning of the buffer for the next round + memmove(data, &data[pos], size - pos); + size -= pos; + + return true; +} + +uint8_t Panda::calculate_checksum(uint8_t *data, uint32_t len) { + uint8_t checksum = 0U; + for (uint32_t i = 0U; i < len; i++) { + checksum ^= data[i]; + } + return checksum; +} + +// USB implementation methods +bool Panda::init_usb_connection(const std::string& serial) { + ssize_t num_devices; + libusb_device **dev_list = NULL; + int err = 0; + + ctx = init_usb_ctx(); + if (!ctx) { goto fail; } + + // connect by serial + num_devices = libusb_get_device_list(ctx, &dev_list); + if (num_devices < 0) { goto fail; } + + for (size_t i = 0; i < num_devices; ++i) { + libusb_device_descriptor desc; + libusb_get_device_descriptor(dev_list[i], &desc); + if (desc.idVendor == 0x3801 && desc.idProduct == 0xddcc) { + int ret = libusb_open(dev_list[i], &dev_handle); + if (dev_handle == NULL || ret < 0) { goto fail; } + + unsigned char desc_serial[26] = { 0 }; + ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); + if (ret < 0) { goto fail; } + + hw_serial_str = std::string((char *)desc_serial, ret); + if (serial.empty() || serial == hw_serial_str) { + break; + } + libusb_close(dev_handle); + dev_handle = NULL; + } + } + if (dev_handle == NULL) goto fail; + libusb_free_device_list(dev_list, 1); + + if (libusb_kernel_driver_active(dev_handle, 0) == 1) { + libusb_detach_kernel_driver(dev_handle, 0); + } + + err = libusb_set_configuration(dev_handle, 1); + if (err != 0) { goto fail; } + + err = libusb_claim_interface(dev_handle, 0); + if (err != 0) { goto fail; } + + return true; + +fail: + if (dev_list != NULL) { + libusb_free_device_list(dev_list, 1); + } + cleanup_usb(); + return false; +} + +void Panda::cleanup_usb() { + if (dev_handle) { + libusb_release_interface(dev_handle, 0); + libusb_close(dev_handle); + dev_handle = nullptr; + } + + if (ctx) { + libusb_exit(ctx); + ctx = nullptr; + } + connected_flag = false; +} + +void Panda::handle_usb_issue(int err, const char func[]) { + LOGE_100("usb error %d \"%s\" in %s", err, libusb_strerror((enum libusb_error)err), func); + if (err == LIBUSB_ERROR_NO_DEVICE) { + LOGE("lost connection"); + connected_flag = false; + } +} + +int Panda::control_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout) { + int err; + const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; + + if (!connected_flag) { + return LIBUSB_ERROR_NO_DEVICE; + } + + do { + err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, NULL, 0, timeout); + if (err < 0) handle_usb_issue(err, __func__); + } while (err < 0 && connected_flag); + + return err; +} + +int Panda::control_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { + int err; + const uint8_t bmRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; + + if (!connected_flag) { + return LIBUSB_ERROR_NO_DEVICE; + } + + do { + err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); + if (err < 0) handle_usb_issue(err, __func__); + } while (err < 0 && connected_flag); + + return err; +} + +int Panda::bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { + int err; + int transferred = 0; + + if (!connected_flag) { + return 0; + } + + do { + err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); + if (err == LIBUSB_ERROR_TIMEOUT) { + LOGW("Transmit buffer full"); + break; + } else if (err != 0 || length != transferred) { + handle_usb_issue(err, __func__); + } + } while (err != 0 && connected_flag); + + return transferred; +} + +int Panda::bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { + int err; + int transferred = 0; + + if (!connected_flag) { + return 0; + } + + do { + err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); + if (err == LIBUSB_ERROR_TIMEOUT) { + break; // timeout is okay to exit, recv still happened + } else if (err == LIBUSB_ERROR_OVERFLOW) { + comms_healthy_flag = false; + LOGE_100("overflow got 0x%x", transferred); + } else if (err != 0) { + handle_usb_issue(err, __func__); + } + } while (err != 0 && connected_flag); + + return transferred; +} diff --git a/tools/cabana/panda.h b/tools/cabana/panda.h new file mode 100644 index 00000000000000..d318c33f4d8457 --- /dev/null +++ b/tools/cabana/panda.h @@ -0,0 +1,95 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "cereal/gen/cpp/car.capnp.h" +#include "cereal/gen/cpp/log.capnp.h" +#include "panda/board/health.h" +#include "panda/board/can.h" + +#define USB_TX_SOFT_LIMIT (0x100U) +#define USBPACKET_MAX_SIZE (0x40) +#define RECV_SIZE (0x4000U) +#define TIMEOUT 0 + +#define CAN_REJECTED_BUS_OFFSET 0xC0U +#define CAN_RETURNED_BUS_OFFSET 0x80U + +#define PANDA_BUS_OFFSET 4 + +struct __attribute__((packed)) can_header { + uint8_t reserved : 1; + uint8_t bus : 3; + uint8_t data_len_code : 4; + uint8_t rejected : 1; + uint8_t returned : 1; + uint8_t extended : 1; + uint32_t addr : 29; + uint8_t checksum : 8; +}; + +struct can_frame { + long address; + std::string dat; + long src; +}; + + +class Panda { +public: + Panda(std::string serial="", uint32_t bus_offset=0); + ~Panda(); + + cereal::PandaState::PandaType hw_type = cereal::PandaState::PandaType::UNKNOWN; + const uint32_t bus_offset; + + bool connected(); + bool comms_healthy(); + std::string hw_serial(); + + // Static functions + static std::vector list(bool usb_only=false); + + // Panda functionality + cereal::PandaState::PandaType get_hw_type(); + void set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param=0U); + void send_heartbeat(bool engaged); + void set_can_speed_kbps(uint16_t bus, uint16_t speed); + void set_data_speed_kbps(uint16_t bus, uint16_t speed); + bool can_receive(std::vector& out_vec); + void can_reset_communications(); + +private: + // USB connection members + libusb_context *ctx = nullptr; + libusb_device_handle *dev_handle = nullptr; + std::string hw_serial_str; + std::atomic connected_flag = true; + std::atomic comms_healthy_flag = true; + + // CAN buffer members + uint8_t receive_buffer[RECV_SIZE + sizeof(can_header) + 64]; + uint32_t receive_buffer_size = 0; + + // Internal methods + bool init_usb_connection(const std::string& serial); + void cleanup_usb(); + void handle_usb_issue(int err, const char func[]); + int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); + int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); + int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + bool unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec); + uint8_t calculate_checksum(uint8_t *data, uint32_t len); +}; diff --git a/tools/cabana/settings.cc b/tools/cabana/settings.cc index 523cbf3be70c09..e7b1129a3043b7 100644 --- a/tools/cabana/settings.cc +++ b/tools/cabana/settings.cc @@ -41,6 +41,10 @@ void settings_op(SettingOperation op) { op(s, "log_path", settings.log_path); op(s, "drag_direction", (int &)settings.drag_direction); op(s, "suppress_defined_signals", settings.suppress_defined_signals); + op(s, "recent_dbc_file", settings.recent_dbc_file); + op(s, "active_msg_id", settings.active_msg_id); + op(s, "selected_msg_ids", settings.selected_msg_ids); + op(s, "active_charts", settings.active_charts); } Settings::Settings() { @@ -89,10 +93,6 @@ SettingsDlg::SettingsDlg(QWidget *parent) : QDialog(parent) { groupbox = new QGroupBox("Chart"); form_layout = new QFormLayout(groupbox); - form_layout->addRow(tr("Default Series Type"), chart_series_type = new QComboBox(this)); - chart_series_type->addItems({tr("Line"), tr("Step Line"), tr("Scatter")}); - chart_series_type->setCurrentIndex(settings.chart_series_type); - form_layout->addRow(tr("Chart Height"), chart_height = new QSpinBox(this)); chart_height->setRange(100, 500); chart_height->setSingleStep(10); @@ -132,7 +132,6 @@ void SettingsDlg::save() { } settings.fps = fps->value(); settings.max_cached_minutes = cached_minutes->value(); - settings.chart_series_type = chart_series_type->currentIndex(); settings.chart_height = chart_height->value(); settings.log_livestream = log_livestream->isChecked(); settings.log_path = log_path->text(); diff --git a/tools/cabana/settings.h b/tools/cabana/settings.h index e75c519ac73e90..7ab50d149411c2 100644 --- a/tools/cabana/settings.h +++ b/tools/cabana/settings.h @@ -46,6 +46,12 @@ class Settings : public QObject { QByteArray message_header_state; DragDirection drag_direction = MsbFirst; + // session data + QString recent_dbc_file; + QString active_msg_id; + QStringList selected_msg_ids; + QStringList active_charts; + signals: void changed(); }; diff --git a/tools/cabana/signalview.cc b/tools/cabana/signalview.cc index 130b76d5023144..a204512e83d48b 100644 --- a/tools/cabana/signalview.cc +++ b/tools/cabana/signalview.cc @@ -1,6 +1,7 @@ #include "tools/cabana/signalview.h" #include +#include #include #include @@ -11,7 +12,6 @@ #include #include #include -#include #include #include "tools/cabana/commands.h" @@ -34,12 +34,12 @@ SignalModel::SignalModel(QObject *parent) : root(new Item), QAbstractItemModel(p } void SignalModel::insertItem(SignalModel::Item *root_item, int pos, const cabana::Signal *sig) { - Item *parent_item = new Item{.sig = sig, .parent = root_item, .title = sig->name, .type = Item::Sig}; - root_item->children.insert(pos, parent_item); + Item *parent_item = new Item{.type = Item::Sig, .parent = root_item, .sig = sig, .title = QString::fromStdString(sig->name)}; + root_item->children.insert(root_item->children.begin() + pos, parent_item); QString titles[]{"Name", "Size", "Receiver Nodes", "Little Endian", "Signed", "Offset", "Factor", "Type", "Multiplex Value", "Extra Info", "Unit", "Comment", "Minimum Value", "Maximum Value", "Value Table"}; for (int i = 0; i < std::size(titles); ++i) { - auto item = new Item{.sig = sig, .parent = parent_item, .title = titles[i], .type = (Item::Type)(i + Item::Name)}; + auto item = new Item{.type = (Item::Type)(i + Item::Name), .parent = parent_item, .sig = sig, .title = titles[i]}; parent_item->children.push_back(item); if (item->type == Item::ExtraInfo) { parent_item = item; @@ -63,7 +63,7 @@ void SignalModel::refresh() { root.reset(new SignalModel::Item); if (auto msg = dbc()->msg(msg_id)) { for (auto s : msg->getSignals()) { - if (filter_str.isEmpty() || s->name.contains(filter_str, Qt::CaseInsensitive)) { + if (filter_str.isEmpty() || QString::fromStdString(s->name).contains(filter_str, Qt::CaseInsensitive)) { insertItem(root.get(), root->children.size(), s); } } @@ -124,25 +124,25 @@ QVariant SignalModel::data(const QModelIndex &index, int role) const { const Item *item = getItem(index); if (role == Qt::DisplayRole || role == Qt::EditRole) { if (index.column() == 0) { - return item->type == Item::Sig ? item->sig->name : item->title; + return item->type == Item::Sig ? QString::fromStdString(item->sig->name) : item->title; } else { switch (item->type) { case Item::Sig: return item->sig_val; - case Item::Name: return item->sig->name; + case Item::Name: return QString::fromStdString(item->sig->name); case Item::Size: return item->sig->size; - case Item::Node: return item->sig->receiver_name; + case Item::Node: return QString::fromStdString(item->sig->receiver_name); case Item::SignalType: return signalTypeToString(item->sig->type); case Item::MultiplexValue: return item->sig->multiplex_value; - case Item::Offset: return doubleToString(item->sig->offset); - case Item::Factor: return doubleToString(item->sig->factor); - case Item::Unit: return item->sig->unit; - case Item::Comment: return item->sig->comment; - case Item::Min: return doubleToString(item->sig->min); - case Item::Max: return doubleToString(item->sig->max); + case Item::Offset: return QString::fromStdString(doubleToString(item->sig->offset)); + case Item::Factor: return QString::fromStdString(doubleToString(item->sig->factor)); + case Item::Unit: return QString::fromStdString(item->sig->unit); + case Item::Comment: return QString::fromStdString(item->sig->comment); + case Item::Min: return QString::fromStdString(doubleToString(item->sig->min)); + case Item::Max: return QString::fromStdString(doubleToString(item->sig->max)); case Item::Desc: { QStringList val_desc; for (auto &[val, desc] : item->sig->val_desc) { - val_desc << QString("%1 \"%2\"").arg(val).arg(desc); + val_desc << QString("%1 \"%2\"").arg(val).arg(QString::fromStdString(desc)); } return val_desc.join(" "); } @@ -165,17 +165,17 @@ bool SignalModel::setData(const QModelIndex &index, const QVariant &value, int r Item *item = getItem(index); cabana::Signal s = *item->sig; switch (item->type) { - case Item::Name: s.name = value.toString(); break; + case Item::Name: s.name = value.toString().toStdString(); break; case Item::Size: s.size = value.toInt(); break; - case Item::Node: s.receiver_name = value.toString().trimmed(); break; + case Item::Node: s.receiver_name = value.toString().trimmed().toStdString(); break; case Item::SignalType: s.type = (cabana::Signal::Type)value.toInt(); break; case Item::MultiplexValue: s.multiplex_value = value.toInt(); break; case Item::Endian: s.is_little_endian = value.toBool(); break; case Item::Signed: s.is_signed = value.toBool(); break; case Item::Offset: s.offset = value.toDouble(); break; case Item::Factor: s.factor = value.toDouble(); break; - case Item::Unit: s.unit = value.toString(); break; - case Item::Comment: s.comment = value.toString(); break; + case Item::Unit: s.unit = value.toString().toStdString(); break; + case Item::Comment: s.comment = value.toString().toStdString(); break; case Item::Min: s.min = value.toDouble(); break; case Item::Max: s.max = value.toDouble(); break; case Item::Desc: s.val_desc = value.value(); break; @@ -189,7 +189,7 @@ bool SignalModel::setData(const QModelIndex &index, const QVariant &value, int r bool SignalModel::saveSignal(const cabana::Signal *origin_s, cabana::Signal &s) { auto msg = dbc()->msg(msg_id); if (s.name != origin_s->name && msg->sig(s.name) != nullptr) { - QString text = tr("There is already a signal with the same name '%1'").arg(s.name); + QString text = tr("There is already a signal with the same name '%1'").arg(QString::fromStdString(s.name)); QMessageBox::warning(nullptr, tr("Failed to save signal"), text); return false; } @@ -214,7 +214,7 @@ void SignalModel::handleSignalAdded(MessageId id, const cabana::Signal *sig) { beginInsertRows({}, i, i); insertItem(root.get(), i, sig); endInsertRows(); - } else if (sig->name.contains(filter_str, Qt::CaseInsensitive)) { + } else if (QString::fromStdString(sig->name).contains(filter_str, Qt::CaseInsensitive)) { refresh(); } } @@ -229,7 +229,9 @@ void SignalModel::handleSignalUpdated(const cabana::Signal *sig) { int to = dbc()->msg(msg_id)->indexOf(sig); if (to != row) { beginMoveRows({}, row, row, {}, to > row ? to + 1 : to); - root->children.move(row, to); + auto item = root->children[row]; + root->children.erase(root->children.begin() + row); + root->children.insert(root->children.begin() + to, item); endMoveRows(); } } @@ -239,7 +241,8 @@ void SignalModel::handleSignalUpdated(const cabana::Signal *sig) { void SignalModel::handleSignalRemoved(const cabana::Signal *sig) { if (int row = signalRow(sig); row != -1) { beginRemoveRows({}, row, row); - delete root->children.takeAt(row); + delete root->children[row]; + root->children.erase(root->children.begin() + row); endRemoveRows(); } } @@ -265,7 +268,7 @@ QSize SignalItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QMo text += item->sig->type == cabana::Signal::Type::Multiplexor ? QString(" M ") : QString(" m%1 ").arg(item->sig->multiplex_value); spacing += (option.widget->style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1) * 2; } - width = std::min(option.widget->size().width() / 3.0, option.fontMetrics.width(text) + spacing); + width = std::min(option.widget->size().width() / 3.0, option.fontMetrics.horizontalAdvance(text) + spacing); } return {width, option.fontMetrics.height() + option.widget->style()->pixelMetric(QStyle::PM_FocusFrameVMargin) * 2}; } @@ -308,7 +311,7 @@ void SignalItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op // multiplexer indicator if (item->sig->type != cabana::Signal::Type::Normal) { QString indicator = item->sig->type == cabana::Signal::Type::Multiplexor ? QString(" M ") : QString(" m%1 ").arg(item->sig->multiplex_value); - QRect indicator_rect{rect.x(), rect.y(), option.fontMetrics.width(indicator), rect.height()}; + QRect indicator_rect{rect.x(), rect.y(), option.fontMetrics.horizontalAdvance(indicator), rect.height()}; painter->setBrush(Qt::gray); painter->setPen(Qt::NoPen); painter->drawRoundedRect(indicator_rect, 3, 3); @@ -342,13 +345,13 @@ void SignalItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op painter->drawText(rect, Qt::AlignLeft | Qt::AlignTop, max); painter->drawText(rect, Qt::AlignLeft | Qt::AlignBottom, min); QFontMetrics fm(minmax_font); - value_adjust = std::max(fm.width(min), fm.width(max)) + 5; + value_adjust = std::max(fm.horizontalAdvance(min), fm.horizontalAdvance(max)) + 5; } else if (!item->sparkline.isEmpty() && item->sig->type == cabana::Signal::Type::Multiplexed) { // display freq of multiplexed signal painter->setFont(label_font); QString freq = QString("%1 hz").arg(item->sparkline.freq(), 0, 'g', 2); painter->drawText(rect.adjusted(5, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, freq); - value_adjust = QFontMetrics(label_font).width(freq) + 10; + value_adjust = QFontMetrics(label_font).horizontalAdvance(freq) + 10; } // signal value painter->setFont(option.font); @@ -373,7 +376,10 @@ QWidget *SignalItemDelegate::createEditor(QWidget *parent, const QStyleOptionVie else e->setValidator(double_validator); if (item->type == SignalModel::Item::Name) { - QCompleter *completer = new QCompleter(dbc()->signalNames(), e); + auto names = dbc()->signalNames(); + QStringList qnames; + for (const auto &n : names) qnames.push_back(QString::fromStdString(n)); + QCompleter *completer = new QCompleter(qnames, e); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setFilterMode(Qt::MatchContains); e->setCompleter(completer); @@ -382,7 +388,7 @@ QWidget *SignalItemDelegate::createEditor(QWidget *parent, const QStyleOptionVie } else if (item->type == SignalModel::Item::Size) { QSpinBox *spin = new QSpinBox(parent); spin->setFrame(false); - spin->setRange(1, 64); + spin->setRange(1, CAN_MAX_DATA_BYTES); return spin; } else if (item->type == SignalModel::Item::SignalType) { QComboBox *c = new QComboBox(parent); @@ -395,7 +401,7 @@ QWidget *SignalItemDelegate::createEditor(QWidget *parent, const QStyleOptionVie return c; } else if (item->type == SignalModel::Item::Desc) { ValueDescriptionDlg dlg(item->sig->val_desc, parent); - dlg.setWindowTitle(item->sig->name); + dlg.setWindowTitle(QString::fromStdString(item->sig->name)); if (dlg.exec()) { ((QAbstractItemModel *)index.model())->setData(index, QVariant::fromValue(dlg.val_desc)); } @@ -489,7 +495,7 @@ SignalView::SignalView(ChartsWidget *charts, QWidget *parent) : charts(charts), setWhatsThis(tr(R"( Signal view
- + )")); } @@ -621,26 +627,27 @@ void SignalView::updateState(const std::set *msgs) { for (auto item : model->root->children) { double value = 0; if (item->sig->getValue(last_msg.dat.data(), last_msg.dat.size(), &value)) { - item->sig_val = item->sig->formatValue(value); - max_value_width = std::max(max_value_width, fontMetrics().width(item->sig_val)); + item->sig_val = QString::fromStdString(item->sig->formatValue(value)); + max_value_width = std::max(max_value_width, fontMetrics().horizontalAdvance(item->sig_val)); } } auto [first_visible, last_visible] = visibleSignalRange(); if (first_visible.isValid() && last_visible.isValid()) { - const static int min_max_width = QFontMetrics(delegate->minmax_font).width("-000.00") + 5; + const static int min_max_width = QFontMetrics(delegate->minmax_font).horizontalAdvance("-000.00") + 5; int available_width = value_column_width - delegate->button_size.width(); int value_width = std::min(max_value_width + min_max_width, available_width / 2); QSize size(available_width - value_width, delegate->button_size.height() - style()->pixelMetric(QStyle::PM_FocusFrameVMargin) * 2); - QFutureSynchronizer synchronizer; + auto [first, last] = can->eventsInRange(model->msg_id, std::make_pair(last_msg.ts -settings.sparkline_range, last_msg.ts)); + std::vector> futures; for (int i = first_visible.row(); i <= last_visible.row(); ++i) { auto item = model->getItem(model->index(i, 1)); - synchronizer.addFuture(QtConcurrent::run( - &item->sparkline, &Sparkline::update, model->msg_id, item->sig, last_msg.ts, settings.sparkline_range, size)); + futures.push_back(std::async(std::launch::async, + &Sparkline::update, &item->sparkline, item->sig, first, last, settings.sparkline_range, size)); } - synchronizer.waitForFinished(); + for (auto &f : futures) f.get(); } for (int i = 0; i < model->rowCount(); ++i) { @@ -676,7 +683,7 @@ ValueDescriptionDlg::ValueDescriptionDlg(const ValueDescription &descriptions, Q int row = 0; for (auto &[val, desc] : descriptions) { table->setItem(row, 0, new QTableWidgetItem(QString::number(val))); - table->setItem(row, 1, new QTableWidgetItem(desc)); + table->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(desc))); ++row; } @@ -705,7 +712,7 @@ void ValueDescriptionDlg::save() { QString val = table->item(i, 0)->text().trimmed(); QString desc = table->item(i, 1)->text().trimmed(); if (!val.isEmpty() && !desc.isEmpty()) { - val_desc.push_back({val.toDouble(), desc}); + val_desc.push_back({val.toDouble(), desc.toStdString()}); } } QDialog::accept(); diff --git a/tools/cabana/signalview.h b/tools/cabana/signalview.h index 4e746ea105bb11..42db830df7f635 100644 --- a/tools/cabana/signalview.h +++ b/tools/cabana/signalview.h @@ -20,12 +20,15 @@ class SignalModel : public QAbstractItemModel { public: struct Item { enum Type {Root, Sig, Name, Size, Node, Endian, Signed, Offset, Factor, SignalType, MultiplexValue, ExtraInfo, Unit, Comment, Min, Max, Desc }; - ~Item() { qDeleteAll(children); } - inline int row() { return parent->children.indexOf(this); } + ~Item() { for (auto c : children) delete c; } + inline int row() { + auto it = std::find(parent->children.begin(), parent->children.end(), this); + return it != parent->children.end() ? std::distance(parent->children.begin(), it) : -1; + } Type type = Type::Root; Item *parent = nullptr; - QList children; + std::vector children; const cabana::Signal *sig = nullptr; QString title; diff --git a/tools/cabana/streams/abstractstream.cc b/tools/cabana/streams/abstractstream.cc index 9bf80deb98ac86..1582fcd34dd7ea 100644 --- a/tools/cabana/streams/abstractstream.cc +++ b/tools/cabana/streams/abstractstream.cc @@ -1,5 +1,6 @@ #include "tools/cabana/streams/abstractstream.h" +#include #include #include @@ -38,7 +39,7 @@ void AbstractStream::updateMasks() { const int size = std::min(mask.size(), m.last_changes.size()); for (int i = 0; i < size; ++i) { for (int j = 0; j < 8; ++j) { - if (((mask[i] >> (7 - j)) & 1) != 0) m.last_changes[i].bit_change_counts[j] = 0; + if (((mask[i] >> (7 - j)) & 1) != 0) m.bit_flip_counts[i][j] = 0; } } } @@ -58,9 +59,9 @@ size_t AbstractStream::suppressHighlighted() { if (dt < 2.0) { last_change.suppressed = true; } - last_change.bit_change_counts.fill(0); cnt += last_change.suppressed; } + for (auto &flip_counts : m.bit_flip_counts) flip_counts.fill(0); } return cnt; } @@ -126,8 +127,21 @@ const CanData &AbstractStream::lastMessage(const MessageId &id) const { return it != last_msgs.end() ? it->second : empty_data; } -// it is thread safe to update data in updateLastMsgsTo. -// updateLastMsgsTo is always called in UI thread. +bool AbstractStream::isMessageActive(const MessageId &id) const { + if (id.source == INVALID_SOURCE) { + return false; + } + // Check if the message is active based on time difference and frequency + const auto &m = lastMessage(id); + float delta = currentSec() - m.ts; + + if (m.freq < std::numeric_limits::epsilon()) { + return delta < 1.5; + } + + return delta < (5.0 / m.freq) + (1.0 / settings.fps); +} + void AbstractStream::updateLastMsgsTo(double sec) { current_sec_ = sec; uint64_t last_ts = toMonoTime(sec); @@ -161,6 +175,16 @@ void AbstractStream::updateLastMsgsTo(double sec) { [this](const auto &m) { return !last_msgs.count(m.first); }); last_msgs = messages_; emit msgsReceived(nullptr, id_changed); + + std::lock_guard lk(mutex_); + seek_finished_ = true; + seek_finished_cv_.notify_one(); +} + +void AbstractStream::waitForSeekFinshed() { + std::unique_lock lock(mutex_); + seek_finished_cv_.wait(lock, [this]() { return seek_finished_; }); + seek_finished_ = false; } const CanEvent *AbstractStream::newEvent(uint64_t mono_time, const cereal::CanData::Reader &c) { @@ -197,6 +221,15 @@ void AbstractStream::mergeEvents(const std::vector &events) { } } +std::pair AbstractStream::eventsInRange(const MessageId &id, std::optional> time_range) const { + const auto &events = can->events(id); + if (!time_range) return {events.begin(), events.end()}; + + auto first = std::lower_bound(events.begin(), events.end(), can->toMonoTime(time_range->first), CompareCanEvent()); + auto last = std::upper_bound(first, events.end(), can->toMonoTime(time_range->second), CompareCanEvent()); + return {first, last}; +} + namespace { enum Color { GREYISH_BLUE, CYAN, RED}; @@ -216,21 +249,12 @@ inline QColor blend(const QColor &a, const QColor &b) { // Calculate the frequency from the past one minute data double calc_freq(const MessageId &msg_id, double current_sec) { - const auto &events = can->events(msg_id); - if (events.empty()) return 0.0; - - auto current_mono_time = can->toMonoTime(current_sec); - auto start_mono_time = can->toMonoTime(current_sec - 59); - - auto first = std::lower_bound(events.begin(), events.end(), start_mono_time, CompareCanEvent()); - auto last = std::upper_bound(first, events.end(), current_mono_time, CompareCanEvent()); - + auto [first, last] = can->eventsInRange(msg_id, std::make_pair(current_sec - 59, current_sec)); int count = std::distance(first, last); - if (count > 1) { - double duration = ((*std::prev(last))->mono_time - (*first)->mono_time) / 1e9; - return count / duration; - } - return 0; + if (count <= 1) return 0.0; + + double duration = ((*std::prev(last))->mono_time - (*first)->mono_time) / 1e9; + return duration > std::numeric_limits::epsilon() ? (count - 1) / duration : 0.0; } } // namespace @@ -246,9 +270,10 @@ void CanData::compute(const MessageId &msg_id, const uint8_t *can_data, const in } if (dat.size() != size) { - dat.resize(size); + dat.assign(can_data, can_data + size); colors.assign(size, QColor(0, 0, 0, 0)); last_changes.resize(size); + bit_flip_counts.resize(size); std::for_each(last_changes.begin(), last_changes.end(), [current_sec](auto &c) { c.ts = current_sec; }); } else { constexpr int periodic_threshold = 10; @@ -280,10 +305,11 @@ void CanData::compute(const MessageId &msg_id, const uint8_t *can_data, const in } // Track bit level changes + auto &row_bit_flips = bit_flip_counts[i]; const uint8_t diff = (cur ^ last); for (int bit = 0; bit < 8; bit++) { if (diff & (1u << bit)) { - ++last_change.bit_change_counts[7 - bit]; + ++row_bit_flips[7 - bit]; } } diff --git a/tools/cabana/streams/abstractstream.h b/tools/cabana/streams/abstractstream.h index 7ae119bcf0cff8..7d66a420dc8eca 100644 --- a/tools/cabana/streams/abstractstream.h +++ b/tools/cabana/streams/abstractstream.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -33,9 +34,9 @@ struct CanData { int delta = 0; int same_delta_counter = 0; bool suppressed = false; - std::array bit_change_counts; }; std::vector last_changes; + std::vector> bit_flip_counts; double last_freq_update_ts = 0; }; @@ -53,6 +54,7 @@ struct CompareCanEvent { }; typedef std::unordered_map> MessageEventsMap; +using CanEventIter = std::vector::const_iterator; class AbstractStream : public QObject { Q_OBJECT @@ -63,8 +65,8 @@ class AbstractStream : public QObject { virtual void start() = 0; virtual bool liveStreaming() const { return true; } virtual void seekTo(double ts) {} - virtual QString routeName() const = 0; - virtual QString carFingerprint() const { return ""; } + virtual std::string routeName() const = 0; + virtual std::string carFingerprint() const { return ""; } virtual QDateTime beginDateTime() const { return {}; } virtual uint64_t beginMonoTime() const { return 0; } virtual double minSeconds() const { return 0; } @@ -81,10 +83,12 @@ class AbstractStream : public QObject { inline double toSeconds(uint64_t mono_time) const { return std::max(0.0, (mono_time - beginMonoTime()) / 1e9); } inline const std::unordered_map &lastMessages() const { return last_msgs; } + bool isMessageActive(const MessageId &id) const; inline const MessageEventsMap &eventsMap() const { return events_; } inline const std::vector &allEvents() const { return all_events_; } const CanData &lastMessage(const MessageId &id) const; const std::vector &events(const MessageId &id) const; + std::pair eventsInRange(const MessageId &id, std::optional> time_range) const; size_t suppressHighlighted(); void clearSuppressed(); @@ -108,7 +112,7 @@ class AbstractStream : public QObject { void mergeEvents(const std::vector &events); const CanEvent *newEvent(uint64_t mono_time, const cereal::CanData::Reader &c); void updateEvent(const MessageId &id, double sec, const uint8_t *data, uint8_t size); - + void waitForSeekFinshed(); std::vector all_events_; double current_sec_ = 0; std::optional> time_range_; @@ -124,6 +128,8 @@ class AbstractStream : public QObject { // Members accessed in multiple threads. (mutex protected) std::mutex mutex_; + std::condition_variable seek_finished_cv_; + bool seek_finished_ = false; std::set new_msgs_; std::unordered_map messages_; std::unordered_map> masks_; @@ -143,7 +149,7 @@ class DummyStream : public AbstractStream { Q_OBJECT public: DummyStream(QObject *parent) : AbstractStream(parent) {} - QString routeName() const override { return tr("No Stream"); } + std::string routeName() const override { return "No Stream"; } void start() override {} }; diff --git a/tools/cabana/streams/devicestream.cc b/tools/cabana/streams/devicestream.cc index 6de63dfbbc347e..20eaa70cd6b56f 100644 --- a/tools/cabana/streams/devicestream.cc +++ b/tools/cabana/streams/devicestream.cc @@ -3,8 +3,12 @@ #include #include +#include "cereal/services.h" + #include +#include #include +#include #include #include #include @@ -15,12 +19,37 @@ DeviceStream::DeviceStream(QObject *parent, QString address) : zmq_address(address), LiveStream(parent) { } +DeviceStream::~DeviceStream() { + if (!bridge_process) + return; + + bridge_process->terminate(); + if (!bridge_process->waitForFinished(3000)) { + bridge_process->kill(); + bridge_process->waitForFinished(); + } +} + +void DeviceStream::start() { + if (!zmq_address.isEmpty()) { + bridge_process = new QProcess(this); + QString bridge_path = QCoreApplication::applicationDirPath() + "/../../cereal/messaging/bridge"; + bridge_process->start(QFileInfo(bridge_path).absoluteFilePath(), QStringList { zmq_address, "/\"can/\"" }); + + if (!bridge_process->waitForStarted()) { + QMessageBox::warning(nullptr, tr("Error"), tr("Failed to start bridge: %1").arg(bridge_process->errorString())); + return; + } + } + + LiveStream::start(); +} + void DeviceStream::streamThread() { zmq_address.isEmpty() ? unsetenv("ZMQ") : setenv("ZMQ", "1", 1); std::unique_ptr context(Context::create()); - std::string address = zmq_address.isEmpty() ? "127.0.0.1" : zmq_address.toStdString(); - std::unique_ptr sock(SubSocket::create(context.get(), "can", address)); + std::unique_ptr sock(SubSocket::create(context.get(), "can", "127.0.0.1", false, true, services.at("can").queue_size)); assert(sock != NULL); // run as fast as messages come in while (!QThread::currentThread()->isInterruptionRequested()) { diff --git a/tools/cabana/streams/devicestream.h b/tools/cabana/streams/devicestream.h index 3bdf22499868e5..4bcdb5351d0ece 100644 --- a/tools/cabana/streams/devicestream.h +++ b/tools/cabana/streams/devicestream.h @@ -2,16 +2,21 @@ #include "tools/cabana/streams/livestream.h" +#include + class DeviceStream : public LiveStream { Q_OBJECT public: DeviceStream(QObject *parent, QString address = {}); - inline QString routeName() const override { - return QString("Live Streaming From %1").arg(zmq_address.isEmpty() ? "127.0.0.1" : zmq_address); + ~DeviceStream(); + inline std::string routeName() const override { + return "Live Streaming From " + (zmq_address.isEmpty() ? std::string("127.0.0.1") : zmq_address.toStdString()); } protected: + void start() override; void streamThread() override; + QProcess *bridge_process = nullptr; const QString zmq_address; }; diff --git a/tools/cabana/streams/pandastream.cc b/tools/cabana/streams/pandastream.cc index b2a006b22faad9..3692f71a11cf36 100644 --- a/tools/cabana/streams/pandastream.cc +++ b/tools/cabana/streams/pandastream.cc @@ -16,15 +16,15 @@ PandaStream::PandaStream(QObject *parent, PandaStreamConfig config_) : config(co bool PandaStream::connect() { try { - qDebug() << "Connecting to panda " << config.serial; - panda.reset(new Panda(config.serial.toStdString())); + qDebug() << "Connecting to panda " << config.serial.c_str(); + panda.reset(new Panda(config.serial)); config.bus_config.resize(3); qDebug() << "Connected"; } catch (const std::exception& e) { return false; } - panda->set_safety_model(cereal::CarParams::SafetyModel::SILENT); + panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); for (int bus = 0; bus < config.bus_config.size(); bus++) { panda->set_can_speed_kbps(bus, config.bus_config[bus].can_speed_kbps); @@ -81,7 +81,7 @@ void PandaStream::streamThread() { OpenPandaWidget::OpenPandaWidget(QWidget *parent) : AbstractOpenStreamWidget(parent) { form_layout = new QFormLayout(this); if (can && dynamic_cast(can) != nullptr) { - form_layout->addWidget(new QLabel(tr("Already connected to %1.").arg(can->routeName()))); + form_layout->addWidget(new QLabel(tr("Already connected to %1.").arg(QString::fromStdString(can->routeName())))); form_layout->addWidget(new QLabel("Close the current connection via [File menu -> Close Stream] before connecting to another Panda.")); QTimer::singleShot(0, [this]() { emit enableOpenButton(false); }); return; @@ -129,7 +129,7 @@ void OpenPandaWidget::buildConfigForm() { } if (has_panda) { - config.serial = serial; + config.serial = serial.toStdString(); config.bus_config.resize(3); for (int i = 0; i < config.bus_config.size(); i++) { QHBoxLayout *bus_layout = new QHBoxLayout; diff --git a/tools/cabana/streams/pandastream.h b/tools/cabana/streams/pandastream.h index 826b1aa986b91a..f8847f65e5eaf9 100644 --- a/tools/cabana/streams/pandastream.h +++ b/tools/cabana/streams/pandastream.h @@ -7,7 +7,7 @@ #include #include "tools/cabana/streams/livestream.h" -#include "selfdrive/pandad/panda.h" +#include "tools/cabana/panda.h" const uint32_t speeds[] = {10U, 20U, 50U, 100U, 125U, 250U, 500U, 1000U}; const uint32_t data_speeds[] = {10U, 20U, 50U, 100U, 125U, 250U, 500U, 1000U, 2000U, 5000U}; @@ -19,7 +19,7 @@ struct BusConfig { }; struct PandaStreamConfig { - QString serial = ""; + std::string serial = ""; std::vector bus_config; }; @@ -28,8 +28,8 @@ class PandaStream : public LiveStream { public: PandaStream(QObject *parent, PandaStreamConfig config_ = {}); ~PandaStream() { stop(); } - inline QString routeName() const override { - return QString("Panda: %1").arg(config.serial); + inline std::string routeName() const override { + return "Panda: " + config.serial; } protected: diff --git a/tools/cabana/streams/replaystream.cc b/tools/cabana/streams/replaystream.cc index 293b363532f29c..f42bf2601cae15 100644 --- a/tools/cabana/streams/replaystream.cc +++ b/tools/cabana/streams/replaystream.cc @@ -7,6 +7,7 @@ #include #include "common/timing.h" +#include "common/util.h" #include "tools/cabana/streams/routes.h" ReplayStream::ReplayStream(QObject *parent) : AbstractStream(parent) { @@ -23,13 +24,10 @@ ReplayStream::ReplayStream(QObject *parent) : AbstractStream(parent) { }); } -static bool event_filter(const Event *e, void *opaque) { - return ((ReplayStream *)opaque)->eventFilter(e); -} - void ReplayStream::mergeSegments() { - for (auto &[n, seg] : replay->segments()) { - if (seg && seg->isLoaded() && !processed_segments.count(n)) { + auto event_data = replay->getEventData(); + for (const auto &[n, seg] : event_data->segments) { + if (!processed_segments.count(n)) { processed_segments.insert(n); std::vector new_events; @@ -48,17 +46,24 @@ void ReplayStream::mergeSegments() { } } -bool ReplayStream::loadRoute(const QString &route, const QString &data_dir, uint32_t replay_flags) { +bool ReplayStream::loadRoute(const std::string &route, const std::string &data_dir, uint32_t replay_flags, bool auto_source) { replay.reset(new Replay(route, {"can", "roadEncodeIdx", "driverEncodeIdx", "wideRoadEncodeIdx", "carParams"}, - {}, nullptr, replay_flags, data_dir, this)); + {}, nullptr, replay_flags, data_dir, auto_source)); replay->setSegmentCacheLimit(settings.max_cached_minutes); - replay->installEventFilter(event_filter, this); - QObject::connect(replay.get(), &Replay::seeking, this, &AbstractStream::seeking); - QObject::connect(replay.get(), &Replay::seekedTo, this, &AbstractStream::seekedTo); - QObject::connect(replay.get(), &Replay::segmentsMerged, this, &ReplayStream::mergeSegments); + replay->installEventFilter([this](const Event *event) { return eventFilter(event); }); + + // Forward replay callbacks to corresponding Qt signals. + replay->onSeeking = [this](double sec) { emit seeking(sec); }; + replay->onSeekedTo = [this](double sec) { + emit seekedTo(sec); + waitForSeekFinshed(); + }; + replay->onQLogLoaded = [this](std::shared_ptr qlog) { emit qLogLoaded(qlog); }; + replay->onSegmentsMerged = [this]() { QMetaObject::invokeMethod(this, &ReplayStream::mergeSegments, Qt::BlockingQueuedConnection); }; + bool success = replay->load(); if (!success) { - if (replay->lastRouteError() == RouteLoadError::AccessDenied) { + if (replay->lastRouteError() == RouteLoadError::Unauthorized) { auto auth_content = util::read_file(util::getenv("HOME") + "/.comma/auth.json"); QString message; if (auth_content.empty()) { @@ -67,17 +72,17 @@ bool ReplayStream::loadRoute(const QString &route, const QString &data_dir, uint "This will grant access to routes from your comma account."; } else { message = tr("Access Denied. You do not have permission to access route:\n\n%1\n\n" - "This is likely a private route.").arg(route); + "This is likely a private route.").arg(QString::fromStdString(route)); } QMessageBox::warning(nullptr, tr("Access Denied"), message); } else if (replay->lastRouteError() == RouteLoadError::NetworkError) { QMessageBox::warning(nullptr, tr("Network Error"), - tr("Unable to load the route:\n\n %1.\n\nPlease check your network connection and try again.").arg(route)); + tr("Unable to load the route:\n\n %1.\n\nPlease check your network connection and try again.").arg(QString::fromStdString(route))); } else if (replay->lastRouteError() == RouteLoadError::FileNotFound) { QMessageBox::warning(nullptr, tr("Route Not Found"), - tr("The specified route could not be found:\n\n %1.\n\nPlease check the route name and try again.").arg(route)); + tr("The specified route could not be found:\n\n %1.\n\nPlease check the route name and try again.").arg(QString::fromStdString(route))); } else { - QMessageBox::warning(nullptr, tr("Route Load Failed"), tr("Failed to load route: '%1'").arg(route)); + QMessageBox::warning(nullptr, tr("Route Load Failed"), tr("Failed to load route: '%1'").arg(QString::fromStdString(route))); } } return success; @@ -153,7 +158,7 @@ AbstractStream *OpenReplayWidget::open() { route = route.mid(idx + 1); } - bool is_valid_format = Route::parseRoute(route).str.size() > 0; + bool is_valid_format = Route::parseRoute(route.toStdString()).str.size() > 0; if (!is_valid_format) { QMessageBox::warning(nullptr, tr("Warning"), tr("Invalid route format: '%1'").arg(route)); } else { @@ -163,7 +168,7 @@ AbstractStream *OpenReplayWidget::open() { if (cameras[2]->isChecked()) flags |= REPLAY_FLAG_ECAM; if (flags == REPLAY_FLAG_NONE && !cameras[0]->isChecked()) flags = REPLAY_FLAG_NO_VIPC; - if (replay_stream->loadRoute(route, data_dir, flags)) { + if (replay_stream->loadRoute(route.toStdString(), data_dir.toStdString(), flags)) { return replay_stream.release(); } } diff --git a/tools/cabana/streams/replaystream.h b/tools/cabana/streams/replaystream.h index 25d6ef4a72eda1..40f8ec8cfbd9e5 100644 --- a/tools/cabana/streams/replaystream.h +++ b/tools/cabana/streams/replaystream.h @@ -10,21 +10,23 @@ #include "tools/cabana/streams/abstractstream.h" #include "tools/replay/replay.h" +Q_DECLARE_METATYPE(std::shared_ptr); + class ReplayStream : public AbstractStream { Q_OBJECT public: ReplayStream(QObject *parent); void start() override { replay->start(); } - bool loadRoute(const QString &route, const QString &data_dir, uint32_t replay_flags = REPLAY_FLAG_NONE); + bool loadRoute(const std::string &route, const std::string &data_dir, uint32_t replay_flags = REPLAY_FLAG_NONE, bool auto_source = false); bool eventFilter(const Event *event); void seekTo(double ts) override { replay->seekTo(std::max(double(0), ts), false); } bool liveStreaming() const override { return false; } - inline QString routeName() const override { return replay->route()->name(); } - inline QString carFingerprint() const override { return replay->carFingerprint().c_str(); } + inline std::string routeName() const override { return replay->route().name(); } + inline std::string carFingerprint() const override { return replay->carFingerprint(); } double minSeconds() const override { return replay->minSeconds(); } double maxSeconds() const { return replay->maxSeconds(); } - inline QDateTime beginDateTime() const { return replay->routeDateTime(); } + inline QDateTime beginDateTime() const { return QDateTime::fromSecsSinceEpoch(replay->routeDateTime()); } inline uint64_t beginMonoTime() const override { return replay->routeStartNanos(); } inline void setSpeed(float speed) override { replay->setSpeed(speed); } inline float getSpeed() const { return replay->getSpeed(); } @@ -32,6 +34,9 @@ class ReplayStream : public AbstractStream { inline bool isPaused() const override { return replay->isPaused(); } void pause(bool pause) override; +signals: + void qLogLoaded(std::shared_ptr qlog); + private: void mergeSegments(); std::unique_ptr replay = nullptr; diff --git a/tools/cabana/streams/routes.cc b/tools/cabana/streams/routes.cc index c805e7d60d8273..1e69a45cea90c3 100644 --- a/tools/cabana/streams/routes.cc +++ b/tools/cabana/streams/routes.cc @@ -1,15 +1,33 @@ #include "tools/cabana/streams/routes.h" +#include #include #include #include #include #include +#include #include #include #include +#include +#include -#include "system/hardware/hw.h" +#include "tools/replay/py_downloader.h" + +namespace { + +// Parse a PyDownloader JSON response into (success, error_code). +std::pair checkApiResponse(const std::string &result) { + if (result.empty()) return {false, 500}; + auto doc = QJsonDocument::fromJson(QByteArray::fromStdString(result)); + if (doc.isObject() && doc.object().contains("error")) { + return {false, doc.object()["error"].toString() == "unauthorized" ? 401 : 500}; + } + return {true, 0}; +} + +} // namespace // The RouteListWidget class extends QListWidget to display a custom message when empty class RouteListWidget : public QListWidget { @@ -34,45 +52,45 @@ RoutesDialog::RoutesDialog(QWidget *parent) : QDialog(parent) { QFormLayout *layout = new QFormLayout(this); layout->addRow(tr("Device"), device_list_ = new QComboBox(this)); - layout->addRow(tr("Duration"), period_selector_ = new QComboBox(this)); + layout->addRow(period_selector_ = new QComboBox(this)); layout->addRow(route_list_ = new RouteListWidget(this)); auto button_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); layout->addRow(button_box); device_list_->addItem(tr("Loading...")); - // Populate period selector with predefined durations period_selector_->addItem(tr("Last week"), 7); period_selector_->addItem(tr("Last 2 weeks"), 14); period_selector_->addItem(tr("Last month"), 30); period_selector_->addItem(tr("Last 6 months"), 180); + period_selector_->addItem(tr("Preserved"), -1); - // Connect signals and slots connect(device_list_, QOverload::of(&QComboBox::currentIndexChanged), this, &RoutesDialog::fetchRoutes); connect(period_selector_, QOverload::of(&QComboBox::currentIndexChanged), this, &RoutesDialog::fetchRoutes); connect(route_list_, &QListWidget::itemDoubleClicked, this, &QDialog::accept); - QObject::connect(button_box, &QDialogButtonBox::accepted, this, &QDialog::accept); - QObject::connect(button_box, &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(button_box, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(button_box, &QDialogButtonBox::rejected, this, &QDialog::reject); - // Send request to fetch devices - HttpRequest *http = new HttpRequest(this, !Hardware::PC()); - QObject::connect(http, &HttpRequest::requestDone, this, &RoutesDialog::parseDeviceList); - http->sendRequest(CommaApi::BASE_URL + "/v1/me/devices/"); + // Fetch devices + QPointer self = this; + std::thread([self]() { + std::string result = PyDownloader::getDevices(); + QMetaObject::invokeMethod(qApp, [self, r = QString::fromStdString(result), response = checkApiResponse(result)]() { + if (self) self->parseDeviceList(r, response.first, response.second); + }, Qt::QueuedConnection); + }).detach(); } -void RoutesDialog::parseDeviceList(const QString &json, bool success, QNetworkReply::NetworkError err) { +void RoutesDialog::parseDeviceList(const QString &json, bool success, int error_code) { if (success) { device_list_->clear(); - auto devices = QJsonDocument::fromJson(json.toUtf8()).array(); - for (const QJsonValue &device : devices) { + for (const QJsonValue &device : QJsonDocument::fromJson(json.toUtf8()).array()) { QString dongle_id = device["dongle_id"].toString(); device_list_->addItem(dongle_id, dongle_id); } } else { - bool unauthorized = (err == QNetworkReply::ContentAccessDenied || err == QNetworkReply::AuthenticationRequiredError); - QMessageBox::warning(this, tr("Error"), unauthorized ? tr("Unauthorized, Authenticate with tools/lib/auth.py") : tr("Network error")); + QMessageBox::warning(this, tr("Error"), error_code == 401 ? tr("Unauthorized. Authenticate with tools/lib/auth.py") : tr("Network error")); reject(); } - sender()->deleteLater(); } void RoutesDialog::fetchRoutes() { @@ -82,42 +100,52 @@ void RoutesDialog::fetchRoutes() { route_list_->clear(); route_list_->setEmptyText(tr("Loading...")); - HttpRequest *http = new HttpRequest(this, !Hardware::PC()); - QObject::connect(http, &HttpRequest::requestDone, this, &RoutesDialog::parseRouteList); - - // Construct URL with selected device and date range - auto dongle_id = device_list_->currentData().toString(); - QDateTime current = QDateTime::currentDateTime(); - QString url = QString("%1/v1/devices/%2/routes_segments?start=%3&end=%4") - .arg(CommaApi::BASE_URL).arg(dongle_id) - .arg(current.addDays(-(period_selector_->currentData().toInt())).toMSecsSinceEpoch()) - .arg(current.toMSecsSinceEpoch()); - http->sendRequest(url); + std::string did = device_list_->currentText().toStdString(); + int period = period_selector_->currentData().toInt(); + + bool preserved = (period == -1); + int64_t start_ms = 0, end_ms = 0; + if (!preserved) { + QDateTime now = QDateTime::currentDateTime(); + start_ms = now.addDays(-period).toMSecsSinceEpoch(); + end_ms = now.toMSecsSinceEpoch(); + } + + int request_id = ++fetch_id_; + QPointer self = this; + std::thread([self, did, start_ms, end_ms, preserved, request_id]() { + std::string result = PyDownloader::getDeviceRoutes(did, start_ms, end_ms, preserved); + if (!self || self->fetch_id_ != request_id) return; + QMetaObject::invokeMethod(qApp, [self, r = QString::fromStdString(result), response = checkApiResponse(result), request_id]() { + if (self && self->fetch_id_ == request_id) self->parseRouteList(r, response.first, response.second); + }, Qt::QueuedConnection); + }).detach(); } -void RoutesDialog::parseRouteList(const QString &json, bool success, QNetworkReply::NetworkError err) { +void RoutesDialog::parseRouteList(const QString &json, bool success, int error_code) { if (success) { for (const QJsonValue &route : QJsonDocument::fromJson(json.toUtf8()).array()) { - uint64_t start_time = route["start_time_utc_millis"].toDouble(); - uint64_t end_time = route["end_time_utc_millis"].toDouble(); - auto datetime = QDateTime::fromMSecsSinceEpoch(start_time); - auto item = new QListWidgetItem(QString("%1 %2min").arg(datetime.toString()).arg((end_time - start_time) / (1000 * 60))); + QDateTime from, to; + if (period_selector_->currentData().toInt() == -1) { + from = QDateTime::fromString(route["start_time"].toString(), Qt::ISODateWithMs); + to = QDateTime::fromString(route["end_time"].toString(), Qt::ISODateWithMs); + } else { + from = QDateTime::fromMSecsSinceEpoch(route["start_time_utc_millis"].toDouble()); + to = QDateTime::fromMSecsSinceEpoch(route["end_time_utc_millis"].toDouble()); + } + auto item = new QListWidgetItem(QString("%1 %2min").arg(from.toString()).arg(from.secsTo(to) / 60)); item->setData(Qt::UserRole, route["fullname"].toString()); route_list_->addItem(item); } - // Select first route if available if (route_list_->count() > 0) route_list_->setCurrentRow(0); } else { QMessageBox::warning(this, tr("Error"), tr("Failed to fetch routes. Check your network connection.")); reject(); } route_list_->setEmptyText(tr("No items")); - sender()->deleteLater(); } -void RoutesDialog::accept() { - if (auto current_item = route_list_->currentItem()) { - route_ = current_item->data(Qt::UserRole).toString(); - } - QDialog::accept(); +QString RoutesDialog::route() { + auto current_item = route_list_->currentItem(); + return current_item ? current_item->data(Qt::UserRole).toString() : ""; } diff --git a/tools/cabana/streams/routes.h b/tools/cabana/streams/routes.h index 31e42fb0750422..99fa67ef8c158f 100644 --- a/tools/cabana/streams/routes.h +++ b/tools/cabana/streams/routes.h @@ -1,26 +1,24 @@ #pragma once +#include #include #include -#include "selfdrive/ui/qt/api.h" - class RouteListWidget; class RoutesDialog : public QDialog { Q_OBJECT public: RoutesDialog(QWidget *parent); - QString route() const { return route_; } + QString route(); protected: - void accept() override; - void parseDeviceList(const QString &json, bool success, QNetworkReply::NetworkError err); - void parseRouteList(const QString &json, bool success, QNetworkReply::NetworkError err); + void parseDeviceList(const QString &json, bool success, int error_code); + void parseRouteList(const QString &json, bool success, int error_code); void fetchRoutes(); QComboBox *device_list_; QComboBox *period_selector_; RouteListWidget *route_list_; - QString route_; + std::atomic fetch_id_{0}; }; diff --git a/tools/cabana/streams/socketcanstream.cc b/tools/cabana/streams/socketcanstream.cc index 1346a496bb8e2d..768465d5a3c3f7 100644 --- a/tools/cabana/streams/socketcanstream.cc +++ b/tools/cabana/streams/socketcanstream.cc @@ -1,6 +1,14 @@ #include "tools/cabana/streams/socketcanstream.h" +#include +#include +#include +#include +#include +#include + #include +#include #include #include #include @@ -9,58 +17,82 @@ SocketCanStream::SocketCanStream(QObject *parent, SocketCanStreamConfig config_) : config(config_), LiveStream(parent) { if (!available()) { - throw std::runtime_error("SocketCAN plugin not available"); + throw std::runtime_error("SocketCAN not available"); } - qDebug() << "Connecting to SocketCAN device" << config.device; + qDebug() << "Connecting to SocketCAN device" << config.device.c_str(); if (!connect()) { throw std::runtime_error("Failed to connect to SocketCAN device"); } } +SocketCanStream::~SocketCanStream() { + stop(); + if (sock_fd >= 0) { + ::close(sock_fd); + sock_fd = -1; + } +} + bool SocketCanStream::available() { - return QCanBus::instance()->plugins().contains("socketcan"); + int fd = socket(PF_CAN, SOCK_RAW, CAN_RAW); + if (fd < 0) return false; + ::close(fd); + return true; } bool SocketCanStream::connect() { - // Connecting might generate some warnings about missing socketcan/libsocketcan libraries - // These are expected and can be ignored, we don't need the advanced features of libsocketcan - QString errorString; - device.reset(QCanBus::instance()->createDevice("socketcan", config.device, &errorString)); + sock_fd = socket(PF_CAN, SOCK_RAW, CAN_RAW); + if (sock_fd < 0) { + qDebug() << "Failed to create CAN socket"; + return false; + } + + // Enable CAN-FD + int fd_enable = 1; + setsockopt(sock_fd, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &fd_enable, sizeof(fd_enable)); - if (!device) { - qDebug() << "Failed to create SocketCAN device" << errorString; + struct ifreq ifr = {}; + strncpy(ifr.ifr_name, config.device.c_str(), IFNAMSIZ - 1); + if (ioctl(sock_fd, SIOCGIFINDEX, &ifr) < 0) { + qDebug() << "Failed to get interface index for" << config.device.c_str(); + ::close(sock_fd); + sock_fd = -1; return false; } - if (!device->connectDevice()) { - qDebug() << "Failed to connect to device"; + struct sockaddr_can addr = {}; + addr.can_family = AF_CAN; + addr.can_ifindex = ifr.ifr_ifindex; + if (bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + qDebug() << "Failed to bind CAN socket"; + ::close(sock_fd); + sock_fd = -1; return false; } + // Set read timeout so the thread can check for interruption + struct timeval tv = {.tv_sec = 0, .tv_usec = 100000}; // 100ms + setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + return true; } void SocketCanStream::streamThread() { + struct canfd_frame frame; + while (!QThread::currentThread()->isInterruptionRequested()) { - QThread::msleep(1); + ssize_t nbytes = read(sock_fd, &frame, sizeof(frame)); + if (nbytes <= 0) continue; - auto frames = device->readAllFrames(); - if (frames.size() == 0) continue; + uint8_t len = (nbytes == CAN_MTU) ? frame.len : frame.len; // works for both CAN and CAN-FD MessageBuilder msg; auto evt = msg.initEvent(); - auto canData = evt.initCan(frames.size()); - - for (uint i = 0; i < frames.size(); i++) { - if (!frames[i].isValid()) continue; - - canData[i].setAddress(frames[i].frameId()); - canData[i].setSrc(0); - - auto payload = frames[i].payload(); - canData[i].setDat(kj::arrayPtr((uint8_t*)payload.data(), payload.size())); - } + auto canData = evt.initCan(1); + canData[0].setAddress(frame.can_id & CAN_EFF_MASK); + canData[0].setSrc(0); + canData[0].setDat(kj::arrayPtr(frame.data, len)); handleEvent(capnp::messageToFlatArray(msg)); } @@ -86,7 +118,7 @@ OpenSocketCanWidget::OpenSocketCanWidget(QWidget *parent) : AbstractOpenStreamWi main_layout->addStretch(1); QObject::connect(refresh, &QPushButton::clicked, this, &OpenSocketCanWidget::refreshDevices); - QObject::connect(device_edit, &QComboBox::currentTextChanged, this, [=]{ config.device = device_edit->currentText(); }); + QObject::connect(device_edit, &QComboBox::currentTextChanged, this, [=]{ config.device = device_edit->currentText().toStdString(); }); // Populate devices refreshDevices(); @@ -94,12 +126,19 @@ OpenSocketCanWidget::OpenSocketCanWidget(QWidget *parent) : AbstractOpenStreamWi void OpenSocketCanWidget::refreshDevices() { device_edit->clear(); - for (auto device : QCanBus::instance()->availableDevices(QStringLiteral("socketcan"))) { - device_edit->addItem(device.name()); + // Scan /sys/class/net/ for CAN interfaces (type 280 = ARPHRD_CAN) + QDir net_dir("/sys/class/net"); + for (const auto &iface : net_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { + QFile type_file(net_dir.filePath(iface) + "/type"); + if (type_file.open(QIODevice::ReadOnly)) { + int type = type_file.readAll().trimmed().toInt(); + if (type == 280) { + device_edit->addItem(iface); + } + } } } - AbstractStream *OpenSocketCanWidget::open() { try { return new SocketCanStream(qApp, config); diff --git a/tools/cabana/streams/socketcanstream.h b/tools/cabana/streams/socketcanstream.h index 8083b687e93b53..3c5cd184f74bee 100644 --- a/tools/cabana/streams/socketcanstream.h +++ b/tools/cabana/streams/socketcanstream.h @@ -1,27 +1,22 @@ #pragma once -#include - -#include -#include -#include #include #include "tools/cabana/streams/livestream.h" struct SocketCanStreamConfig { - QString device = ""; // TODO: support multiple devices/buses at once + std::string device = ""; // TODO: support multiple devices/buses at once }; class SocketCanStream : public LiveStream { Q_OBJECT public: SocketCanStream(QObject *parent, SocketCanStreamConfig config_ = {}); - ~SocketCanStream() { stop(); } + ~SocketCanStream(); static bool available(); - inline QString routeName() const override { - return QString("Live Streaming From Socket CAN %1").arg(config.device); + inline std::string routeName() const override { + return "Live Streaming From Socket CAN " + config.device; } protected: @@ -29,7 +24,7 @@ class SocketCanStream : public LiveStream { bool connect(); SocketCanStreamConfig config = {}; - std::unique_ptr device; + int sock_fd = -1; }; class OpenSocketCanWidget : public AbstractOpenStreamWidget { diff --git a/tools/cabana/streamselector.cc b/tools/cabana/streamselector.cc index efd00d39857a48..4ad552d4b4c96c 100644 --- a/tools/cabana/streamselector.cc +++ b/tools/cabana/streamselector.cc @@ -4,11 +4,12 @@ #include #include -#include "streams/socketcanstream.h" #include "tools/cabana/streams/devicestream.h" #include "tools/cabana/streams/pandastream.h" #include "tools/cabana/streams/replaystream.h" +#ifdef __linux__ #include "tools/cabana/streams/socketcanstream.h" +#endif StreamSelector::StreamSelector(QWidget *parent) : QDialog(parent) { setWindowTitle(tr("Open stream")); @@ -35,9 +36,11 @@ StreamSelector::StreamSelector(QWidget *parent) : QDialog(parent) { addStreamWidget(new OpenReplayWidget, tr("&Replay")); addStreamWidget(new OpenPandaWidget, tr("&Panda")); +#ifdef __linux__ if (SocketCanStream::available()) { addStreamWidget(new OpenSocketCanWidget, tr("&SocketCAN")); } +#endif addStreamWidget(new OpenDeviceWidget, tr("&Device")); QObject::connect(btn_box, &QDialogButtonBox::rejected, this, &QDialog::reject); diff --git a/tools/cabana/tests/test_cabana.cc b/tools/cabana/tests/test_cabana.cc index d9fcae6f21a7ba..833cfbe4b58fc6 100644 --- a/tools/cabana/tests/test_cabana.cc +++ b/tools/cabana/tests/test_cabana.cc @@ -8,7 +8,7 @@ const std::string TEST_RLOG_URL = "https://commadataci.blob.core.windows.net/openpilotci/0c94aa1e1296d7c6/2021-05-05--19-48-37/0/rlog.bz2"; TEST_CASE("DBCFile::generateDBC") { - QString fn = QString("%1/%2.dbc").arg(OPENDBC_FILE_PATH, "tesla_can"); + std::string fn = std::string(OPENDBC_FILE_PATH) + "/tesla_can.dbc"; DBCFile dbc_origin(fn); DBCFile dbc_from_generated("", dbc_origin.generateDBC()); @@ -30,7 +30,7 @@ TEST_CASE("DBCFile::generateDBC") { TEST_CASE("DBCFile::generateDBC - comment order") { // Ensure that message comments are followed by signal comments and in the correct order - auto content = R"(BO_ 160 message_1: 8 EON + std::string content = R"(BO_ 160 message_1: 8 EON SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX BO_ 162 message_2: 8 EON @@ -46,7 +46,7 @@ CM_ SG_ 162 signal_2 "signal comment"; } TEST_CASE("DBCFile::generateDBC -- preserve original header") { - QString content = R"(VERSION "1.0" + std::string content = R"(VERSION "1.0" NS_ : CM_ @@ -66,7 +66,7 @@ CM_ SG_ 160 signal_1 "signal comment"; } TEST_CASE("DBCFile::generateDBC - escaped quotes") { - QString content = R"(BO_ 160 message_1: 8 EON + std::string content = R"(BO_ 160 message_1: 8 EON SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX CM_ BO_ 160 "message comment with \"escaped quotes\""; @@ -77,7 +77,7 @@ CM_ SG_ 160 signal_1 "signal comment with \"escaped quotes\""; } TEST_CASE("parse_dbc") { - QString content = R"( + std::string content = R"( BO_ 160 message_1: 8 EON SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX SG_ signal_2 : 12|1@1+ (1.0,0.0) [0.0|1] "" XXX @@ -119,9 +119,9 @@ CM_ SG_ 162 signal_1 "signal comment with \"escaped quotes\""; REQUIRE(sig_1->comment == "signal comment"); REQUIRE(sig_1->receiver_name == "XXX"); REQUIRE(sig_1->val_desc.size() == 3); - REQUIRE(sig_1->val_desc[0] == std::pair{0, "disabled"}); - REQUIRE(sig_1->val_desc[1] == std::pair{1.2, "initializing"}); - REQUIRE(sig_1->val_desc[2] == std::pair{2, "fault"}); + REQUIRE(sig_1->val_desc[0] == std::pair{0, "disabled"}); + REQUIRE(sig_1->val_desc[1] == std::pair{1.2, "initializing"}); + REQUIRE(sig_1->val_desc[2] == std::pair{2, "fault"}); auto &sig_2 = msg->sigs[1]; REQUIRE(sig_2->comment == "multiple line comment \n1\n2"); @@ -147,7 +147,7 @@ TEST_CASE("parse_opendbc") { QStringList errors; for (auto fn : dir.entryList({"*.dbc"}, QDir::Files, QDir::Name)) { try { - auto dbc = DBCFile(dir.filePath(fn)); + auto dbc = DBCFile(dir.filePath(fn).toStdString()); } catch (std::exception &e) { errors.push_back(e.what()); } diff --git a/tools/cabana/tools/findsignal.cc b/tools/cabana/tools/findsignal.cc index 8e1749ba8e4a54..b13189394275ff 100644 --- a/tools/cabana/tools/findsignal.cc +++ b/tools/cabana/tools/findsignal.cc @@ -1,10 +1,11 @@ #include "tools/cabana/tools/findsignal.h" +#include + #include #include #include #include -#include #include #include @@ -20,7 +21,7 @@ QVariant FindSignalModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { const auto &s = filtered_signals[index.row()]; switch (index.column()) { - case 0: return s.id.toString(); + case 0: return QString::fromStdString(s.id.toString()); case 1: return QString("%1, %2").arg(s.sig.start_bit).arg(s.sig.size); case 2: return s.values.join(" "); } @@ -32,36 +33,49 @@ void FindSignalModel::search(std::function cmp) { beginResetModel(); std::mutex lock; - const auto prev_sigs = !histories.isEmpty() ? histories.back() : initial_signals; + const auto prev_sigs = !histories.empty() ? histories.back() : initial_signals; filtered_signals.clear(); filtered_signals.reserve(prev_sigs.size()); - QtConcurrent::blockingMap(prev_sigs, [&](auto &s) { - const auto &events = can->events(s.id); - auto first = std::upper_bound(events.cbegin(), events.cend(), s.mono_time, CompareCanEvent()); - auto last = events.cend(); - if (last_time < std::numeric_limits::max()) { - last = std::upper_bound(events.cbegin(), events.cend(), last_time, CompareCanEvent()); - } - auto it = std::find_if(first, last, [&](const CanEvent *e) { return cmp(get_raw_value(e->dat, e->size, s.sig)); }); - if (it != last) { - auto values = s.values; - values += QString("(%1, %2)").arg(can->toSeconds((*it)->mono_time), 0, 'f', 3).arg(get_raw_value((*it)->dat, (*it)->size, s.sig)); - std::lock_guard lk(lock); - filtered_signals.push_back({.id = s.id, .mono_time = (*it)->mono_time, .sig = s.sig, .values = values}); - } - }); + unsigned int num_threads = std::max(1u, std::thread::hardware_concurrency()); + size_t chunk = (prev_sigs.size() + num_threads - 1) / num_threads; + std::vector threads; + for (unsigned int t = 0; t < num_threads && t * chunk < (size_t)prev_sigs.size(); ++t) { + size_t start = t * chunk; + size_t end = std::min(start + chunk, (size_t)prev_sigs.size()); + threads.emplace_back([&, start, end]() { + for (size_t i = start; i < end; ++i) { + const auto &s = prev_sigs[i]; + const auto &events = can->events(s.id); + auto first = std::upper_bound(events.cbegin(), events.cend(), s.mono_time, CompareCanEvent()); + auto last = events.cend(); + if (last_time < std::numeric_limits::max()) { + last = std::upper_bound(events.cbegin(), events.cend(), last_time, CompareCanEvent()); + } + + auto it = std::find_if(first, last, [&](const CanEvent *e) { return cmp(get_raw_value(e->dat, e->size, s.sig)); }); + if (it != last) { + auto values = s.values; + values += QString("(%1, %2)").arg(can->toSeconds((*it)->mono_time), 0, 'f', 3).arg(get_raw_value((*it)->dat, (*it)->size, s.sig)); + std::lock_guard lk(lock); + filtered_signals.push_back({.id = s.id, .mono_time = (*it)->mono_time, .sig = s.sig, .values = values}); + } + } + }); + } + for (auto &th : threads) th.join(); + histories.push_back(filtered_signals); endResetModel(); } void FindSignalModel::undo() { - if (!histories.isEmpty()) { + if (!histories.empty()) { beginResetModel(); histories.pop_back(); filtered_signals.clear(); - if (!histories.isEmpty()) filtered_signals = histories.back(); + if (!histories.empty()) filtered_signals = histories.back(); endResetModel(); } } @@ -172,7 +186,7 @@ FindSignalDlg::FindSignalDlg(QWidget *parent) : QDialog(parent, Qt::WindowFlags( } void FindSignalDlg::search() { - if (model->histories.isEmpty()) { + if (model->histories.empty()) { setInitialSignals(); } auto v1 = value1->text().toDouble(); @@ -225,7 +239,7 @@ void FindSignalDlg::setInitialSignals() { model->initial_signals.clear(); for (const auto &[id, m] : can->lastMessages()) { - if (buses.isEmpty() || buses.contains(id.source) && (addresses.isEmpty() || addresses.contains(id.address))) { + if ((buses.isEmpty() || buses.contains(id.source)) && (addresses.isEmpty() || addresses.contains(id.address))) { const auto &events = can->events(id); auto e = std::lower_bound(events.cbegin(), events.cend(), first_time, CompareCanEvent()); if (e != events.cend()) { @@ -246,12 +260,12 @@ void FindSignalDlg::setInitialSignals() { } void FindSignalDlg::modelReset() { - properties_group->setEnabled(model->histories.isEmpty()); - message_group->setEnabled(model->histories.isEmpty()); - search_btn->setText(model->histories.isEmpty() ? tr("Find") : tr("Find Next")); - reset_btn->setEnabled(!model->histories.isEmpty()); + properties_group->setEnabled(model->histories.empty()); + message_group->setEnabled(model->histories.empty()); + search_btn->setText(model->histories.empty() ? tr("Find") : tr("Find Next")); + reset_btn->setEnabled(!model->histories.empty()); undo_btn->setEnabled(model->histories.size() > 1); - search_btn->setEnabled(model->rowCount() > 0 || model->histories.isEmpty()); + search_btn->setEnabled(model->rowCount() > 0 || model->histories.empty()); stats_label->setVisible(true); stats_label->setText(tr("%1 matches. right click on an item to create signal. double click to open message").arg(model->filtered_signals.size())); } diff --git a/tools/cabana/tools/findsignal.h b/tools/cabana/tools/findsignal.h index 5ef7461fee276b..239a08c9c48769 100644 --- a/tools/cabana/tools/findsignal.h +++ b/tools/cabana/tools/findsignal.h @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -26,14 +28,14 @@ class FindSignalModel : public QAbstractTableModel { QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 3; } - int rowCount(const QModelIndex &parent = QModelIndex()) const override { return std::min(filtered_signals.size(), 300); } + int rowCount(const QModelIndex &parent = QModelIndex()) const override { return std::min((int)filtered_signals.size(), 300); } void search(std::function cmp); void reset(); void undo(); - QList filtered_signals; - QList initial_signals; - QList> histories; + std::vector filtered_signals; + std::vector initial_signals; + std::vector> histories; uint64_t last_time = std::numeric_limits::max(); }; diff --git a/tools/cabana/tools/findsimilarbits.cc b/tools/cabana/tools/findsimilarbits.cc index c3c659791a7098..8062b611990f0e 100644 --- a/tools/cabana/tools/findsimilarbits.cc +++ b/tools/cabana/tools/findsimilarbits.cc @@ -1,6 +1,7 @@ #include "tools/cabana/tools/findsimilarbits.h" #include +#include #include #include @@ -31,7 +32,7 @@ FindSimilarBitsDlg::FindSimilarBitsDlg(QWidget *parent) : QDialog(parent, Qt::Wi msg_cb = new QComboBox(this); // TODO: update when src_bus_combo changes for (auto &[address, msg] : dbc()->getMessages(-1)) { - msg_cb->addItem(msg.name, address); + msg_cb->addItem(QString::fromStdString(msg.name), address); } msg_cb->model()->sort(0); msg_cb->setCurrentIndex(0); @@ -114,10 +115,10 @@ void FindSimilarBitsDlg::find() { search_btn->setEnabled(true); } -QList FindSimilarBitsDlg::calcBits(uint8_t bus, uint32_t selected_address, int byte_idx, - int bit_idx, uint8_t find_bus, bool equal, int min_msgs_cnt) { - QHash> mismatches; - QHash msg_count; +std::vector FindSimilarBitsDlg::calcBits(uint8_t bus, uint32_t selected_address, int byte_idx, + int bit_idx, uint8_t find_bus, bool equal, int min_msgs_cnt) { + std::unordered_map> mismatches; + std::unordered_map msg_count; const auto &events = can->allEvents(); int bit_to_find = -1; for (const CanEvent *e : events) { @@ -143,14 +144,14 @@ QList FindSimilarBitsDlg::calcBits(uint8_ } } - QList result; + std::vector result; result.reserve(mismatches.size()); for (auto it = mismatches.begin(); it != mismatches.end(); ++it) { - if (auto cnt = msg_count[it.key()]; cnt > min_msgs_cnt) { - auto &mismatched = it.value(); - for (int i = 0; i < mismatched.size(); ++i) { + if (auto cnt = msg_count[it->first]; cnt > (uint32_t)min_msgs_cnt) { + auto &mismatched = it->second; + for (int i = 0; i < (int)mismatched.size(); ++i) { if (float perc = (mismatched[i] / (double)cnt) * 100; perc < 50) { - result.push_back({it.key(), (uint32_t)i / 8, (uint32_t)i % 8, mismatched[i], cnt, perc}); + result.push_back({it->first, (uint32_t)i / 8, (uint32_t)i % 8, mismatched[i], cnt, perc}); } } } diff --git a/tools/cabana/tools/findsimilarbits.h b/tools/cabana/tools/findsimilarbits.h index 77bfac19cae43f..3451360654d382 100644 --- a/tools/cabana/tools/findsimilarbits.h +++ b/tools/cabana/tools/findsimilarbits.h @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -22,7 +24,7 @@ class FindSimilarBitsDlg : public QDialog { uint32_t address, byte_idx, bit_idx, mismatches, total; float perc; }; - QList calcBits(uint8_t bus, uint32_t selected_address, int byte_idx, int bit_idx, uint8_t find_bus, + std::vector calcBits(uint8_t bus, uint32_t selected_address, int byte_idx, int bit_idx, uint8_t find_bus, bool equal, int min_msgs_cnt); void find(); diff --git a/tools/cabana/tools/routeinfo.cc b/tools/cabana/tools/routeinfo.cc new file mode 100644 index 00000000000000..77a0e065cd40e9 --- /dev/null +++ b/tools/cabana/tools/routeinfo.cc @@ -0,0 +1,40 @@ +#include "tools/cabana/tools/routeinfo.h" +#include +#include +#include +#include +#include "tools/cabana/streams/replaystream.h" + +RouteInfoDlg::RouteInfoDlg(QWidget *parent) : QDialog(parent) { + auto *replay = qobject_cast(can)->getReplay(); + setWindowTitle(tr("Route: %1").arg(QString::fromStdString(replay->route().name()))); + + auto *table = new QTableWidget(replay->route().segments().size(), 7, this); + table->setToolTip(tr("Click on a row to seek to the corresponding segment.")); + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + table->setSelectionBehavior(QAbstractItemView::SelectRows); + table->setSelectionMode(QAbstractItemView::SingleSelection); + table->setHorizontalHeaderLabels({"", "rlog", "fcam", "ecam", "dcam", "qlog", "qcam"}); + table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + table->verticalHeader()->setVisible(false); + table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + + int row = 0; + for (const auto &[seg_num, seg] : replay->route().segments()) { + table->setItem(row, 0, new QTableWidgetItem(QString::number(seg_num))); + table->setItem(row, 1, new QTableWidgetItem(seg.rlog.empty() ? "--" : "Yes")); + table->setItem(row, 2, new QTableWidgetItem(seg.road_cam.empty() ? "--" : "Yes")); + table->setItem(row, 3, new QTableWidgetItem(seg.wide_road_cam.empty() ? "--" : "Yes")); + table->setItem(row, 4, new QTableWidgetItem(seg.driver_cam.empty() ? "--" : "Yes")); + table->setItem(row, 5, new QTableWidgetItem(seg.qlog.empty() ? "--" : "Yes")); + table->setItem(row, 6, new QTableWidgetItem(seg.qcamera.empty() ? "--" : "Yes")); + ++row; + } + table->setMinimumWidth(table->horizontalHeader()->length() + table->verticalScrollBar()->sizeHint().width()); + table->setMinimumHeight(table->rowHeight(0) * std::min(table->rowCount(), 13) + table->horizontalHeader()->height() + table->frameWidth() * 2); + + connect(table, &QTableWidget::itemClicked, [](QTableWidgetItem *item) { can->seekTo(item->row() * 60.0); }); + + QVBoxLayout *layout = new QVBoxLayout(this); + layout->addWidget(table); +} diff --git a/tools/cabana/tools/routeinfo.h b/tools/cabana/tools/routeinfo.h new file mode 100644 index 00000000000000..36f32b4bf4553f --- /dev/null +++ b/tools/cabana/tools/routeinfo.h @@ -0,0 +1,8 @@ +#pragma once +#include + +class RouteInfoDlg : public QDialog { + Q_OBJECT +public: + RouteInfoDlg(QWidget *parent = nullptr); +}; diff --git a/tools/cabana/utils/elidedlabel.cc b/tools/cabana/utils/elidedlabel.cc new file mode 100644 index 00000000000000..629a108b1683f3 --- /dev/null +++ b/tools/cabana/utils/elidedlabel.cc @@ -0,0 +1,29 @@ +#include "tools/cabana/utils/elidedlabel.h" +#include +#include + +ElidedLabel::ElidedLabel(QWidget *parent) : ElidedLabel({}, parent) {} + +ElidedLabel::ElidedLabel(const QString &text, QWidget *parent) : QLabel(text.trimmed(), parent) { + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + setMinimumWidth(1); +} + +void ElidedLabel::resizeEvent(QResizeEvent* event) { + QLabel::resizeEvent(event); + lastText_ = elidedText_ = ""; +} + +void ElidedLabel::paintEvent(QPaintEvent *event) { + const QString curText = text(); + if (curText != lastText_) { + elidedText_ = fontMetrics().elidedText(curText, Qt::ElideRight, contentsRect().width()); + lastText_ = curText; + } + + QPainter painter(this); + drawFrame(&painter); + QStyleOption opt; + opt.initFrom(this); + style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elidedText_, foregroundRole()); +} diff --git a/tools/cabana/utils/elidedlabel.h b/tools/cabana/utils/elidedlabel.h new file mode 100644 index 00000000000000..577eea12a02829 --- /dev/null +++ b/tools/cabana/utils/elidedlabel.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +class ElidedLabel : public QLabel { + Q_OBJECT + +public: + explicit ElidedLabel(QWidget *parent = 0); + explicit ElidedLabel(const QString &text, QWidget *parent = 0); + +signals: + void clicked(); + +protected: + void paintEvent(QPaintEvent *event) override; + void resizeEvent(QResizeEvent* event) override; + void mouseReleaseEvent(QMouseEvent *event) override { + if (rect().contains(event->pos())) { + emit clicked(); + } + } + QString lastText_, elidedText_; +}; diff --git a/tools/cabana/utils/export.cc b/tools/cabana/utils/export.cc index 79ca97ba8f219d..a7f910193f2e6c 100644 --- a/tools/cabana/utils/export.cc +++ b/tools/cabana/utils/export.cc @@ -26,7 +26,7 @@ void exportSignalsToCSV(const QString &file_name, const MessageId &msg_id) { QTextStream stream(&file); stream << "time,addr,bus"; for (auto s : msg->sigs) - stream << "," << s->name; + stream << "," << s->name.c_str(); stream << "\n"; for (auto e : can->events(msg_id)) { diff --git a/tools/cabana/utils/util.cc b/tools/cabana/utils/util.cc index 4556f908506430..50ab7644235d1b 100644 --- a/tools/cabana/utils/util.cc +++ b/tools/cabana/utils/util.cc @@ -10,11 +10,15 @@ #include #include +#include #include #include #include - -#include "selfdrive/ui/qt/util.h" +#include +#include +#include +#include +#include "common/util.h" // SegmentTree @@ -161,13 +165,13 @@ UnixSignalHandler::~UnixSignalHandler() { } void UnixSignalHandler::signalHandler(int s) { - ::write(sig_fd[0], &s, sizeof(s)); + (void)!::write(sig_fd[0], &s, sizeof(s)); } void UnixSignalHandler::handleSigTerm() { sn->setEnabled(false); int tmp; - ::read(sig_fd[1], &tmp, sizeof(tmp)); + (void)!::read(sig_fd[1], &tmp, sizeof(tmp)); printf("\nexiting...\n"); qApp->closeAllWindows(); @@ -191,8 +195,15 @@ DoubleValidator::DoubleValidator(QObject *parent) : QDoubleValidator(parent) { } namespace utils { + +bool isDarkTheme() { + QColor windowColor = QApplication::palette().color(QPalette::Window); + return windowColor.lightness() < 128; +} + QPixmap icon(const QString &id) { - bool dark_theme = settings.theme == DARK_THEME; + bool dark_theme = isDarkTheme(); + QPixmap pm; QString key = "bootstrap_" % id % (dark_theme ? "1" : "0"); if (!QPixmapCache::find(key, &pm)) { @@ -266,6 +277,96 @@ QString signalToolTip(const cabana::Signal *sig) { Start Bit: %2 Size: %3
MSB: %4 LSB: %5
Little Endian: %6 Signed: %7 - )").arg(sig->name).arg(sig->start_bit).arg(sig->size).arg(sig->msb).arg(sig->lsb) + )").arg(QString::fromStdString(sig->name)).arg(sig->start_bit).arg(sig->size).arg(sig->msb).arg(sig->lsb) .arg(sig->is_little_endian ? "Y" : "N").arg(sig->is_signed ? "Y" : "N"); } + +void setSurfaceFormat() { + QSurfaceFormat fmt; +#ifdef __APPLE__ + fmt.setVersion(3, 2); + fmt.setProfile(QSurfaceFormat::OpenGLContextProfile::CoreProfile); + fmt.setRenderableType(QSurfaceFormat::OpenGL); +#else + fmt.setRenderableType(QSurfaceFormat::OpenGLES); +#endif + fmt.setSamples(16); + fmt.setStencilBufferSize(1); + QSurfaceFormat::setDefaultFormat(fmt); +} + +void sigTermHandler(int s) { + std::signal(s, SIG_DFL); + qApp->quit(); +} + +void initApp(int argc, char *argv[], bool disable_hidpi) { + // setup signal handlers to exit gracefully + std::signal(SIGINT, sigTermHandler); + std::signal(SIGTERM, sigTermHandler); + + QString app_dir; +#ifdef __APPLE__ + // Get the devicePixelRatio, and scale accordingly to maintain 1:1 rendering + QApplication tmp(argc, argv); + app_dir = QCoreApplication::applicationDirPath(); + if (disable_hidpi) { + qputenv("QT_SCALE_FACTOR", QString::number(1.0 / tmp.devicePixelRatio()).toLocal8Bit()); + } +#else + app_dir = QFileInfo(util::readlink("/proc/self/exe").c_str()).path(); +#endif + + qputenv("QT_DBL_CLICK_DIST", QByteArray::number(150)); + // ensure the current dir matches the exectuable's directory + QDir::setCurrent(app_dir); + + setSurfaceFormat(); +} + +static std::unordered_map load_bootstrap_icons() { + std::unordered_map icons; + + QFile f(":/bootstrap-icons.svg"); + if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { + std::string content = f.readAll().toStdString(); + const std::string sym_open = " with + svg_str.replace(0, 7, " ""); // "" (9) -> "" (6) + icons[id] = std::move(svg_str); + } + } + pos = end; + } + } + return icons; +} + +QPixmap bootstrapPixmap(const QString &id) { + static auto icons = load_bootstrap_icons(); + + QPixmap pixmap; + auto it = icons.find(id.toStdString()); + if (it != icons.end()) { + pixmap.loadFromData((const uchar *)it->second.data(), it->second.size(), "svg"); + } + return pixmap; +} diff --git a/tools/cabana/utils/util.h b/tools/cabana/utils/util.h index 0ebd7e41f84681..f839ffe7fe576f 100644 --- a/tools/cabana/utils/util.h +++ b/tools/cabana/utils/util.h @@ -98,7 +98,9 @@ class DoubleValidator : public QDoubleValidator { }; namespace utils { + QPixmap icon(const QString &id); +bool isDarkTheme(); void setTheme(int theme); QString formatSeconds(double sec, bool include_milliseconds = false, bool absolute_time = false); inline void drawStaticText(QPainter *p, const QRect &r, const QStaticText &text) { @@ -163,3 +165,6 @@ public slots: int num_decimals(double num); QString signalToolTip(const cabana::Signal *sig); +inline QString toHexString(int value) { return QString("0x%1").arg(QString::number(value, 16).toUpper(), 2, '0'); } +void initApp(int argc, char *argv[], bool disable_hidpi = true); +QPixmap bootstrapPixmap(const QString &id); diff --git a/tools/cabana/videowidget.cc b/tools/cabana/videowidget.cc index 48f768c819ddf5..87d3cbec956556 100644 --- a/tools/cabana/videowidget.cc +++ b/tools/cabana/videowidget.cc @@ -1,45 +1,45 @@ #include "tools/cabana/videowidget.h" #include -#include +#include #include #include #include #include #include -#include #include #include -#include -#include "tools/cabana/streams/replaystream.h" +#include "tools/cabana/tools/routeinfo.h" const int MIN_VIDEO_HEIGHT = 100; const int THUMBNAIL_MARGIN = 3; +// Indexed by TimelineType: None, Engaged, AlertInfo, AlertWarning, AlertCritical, UserBookmark static const QColor timeline_colors[] = { - [(int)TimelineType::None] = QColor(111, 143, 175), - [(int)TimelineType::Engaged] = QColor(0, 163, 108), - [(int)TimelineType::UserFlag] = Qt::magenta, - [(int)TimelineType::AlertInfo] = Qt::green, - [(int)TimelineType::AlertWarning] = QColor(255, 195, 0), - [(int)TimelineType::AlertCritical] = QColor(199, 0, 57), + QColor(111, 143, 175), + QColor(0, 163, 108), + Qt::green, + QColor(255, 195, 0), + QColor(199, 0, 57), + Qt::magenta, }; static Replay *getReplay() { auto stream = qobject_cast(can); - if (!stream) return nullptr; - - return stream->getReplay(); + return stream ? stream->getReplay() : nullptr; } VideoWidget::VideoWidget(QWidget *parent) : QFrame(parent) { setFrameStyle(QFrame::StyledPanel | QFrame::Plain); auto main_layout = new QVBoxLayout(this); + main_layout->setContentsMargins(0, 0, 0, 0); + main_layout->setSpacing(0); if (!can->liveStreaming()) main_layout->addWidget(createCameraWidget()); - main_layout->addLayout(createPlaybackController()); + + createPlaybackController(); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); QObject::connect(can, &AbstractStream::paused, this, &VideoWidget::updatePlayBtnState); @@ -51,7 +51,7 @@ VideoWidget::VideoWidget(QWidget *parent) : QFrame(parent) { updatePlayBtnState(); setWhatsThis(tr(R"( Video
- + Timeline color @@ -65,21 +65,25 @@ VideoWidget::VideoWidget(QWidget *parent) : QFrame(parent) { Pause/Resume:  space  )").arg(timeline_colors[(int)TimelineType::None].name(), timeline_colors[(int)TimelineType::Engaged].name(), - timeline_colors[(int)TimelineType::UserFlag].name(), + timeline_colors[(int)TimelineType::UserBookmark].name(), timeline_colors[(int)TimelineType::AlertInfo].name(), timeline_colors[(int)TimelineType::AlertWarning].name(), timeline_colors[(int)TimelineType::AlertCritical].name())); } -QHBoxLayout *VideoWidget::createPlaybackController() { - QHBoxLayout *layout = new QHBoxLayout(); - layout->addWidget(seek_backward_btn = new ToolButton("rewind", tr("Seek backward"))); - layout->addWidget(play_btn = new ToolButton("play", tr("Play"))); - layout->addWidget(seek_forward_btn = new ToolButton("fast-forward", tr("Seek forward"))); +void VideoWidget::createPlaybackController() { + QToolBar *toolbar = new QToolBar(this); + layout()->addWidget(toolbar); + + int icon_size = style()->pixelMetric(QStyle::PM_SmallIconSize); + toolbar->setIconSize({icon_size, icon_size}); + + toolbar->addAction(utils::icon("rewind"), tr("Seek backward"), []() { can->seekTo(can->currentSec() - 1); }); + play_toggle_action = toolbar->addAction(utils::icon("play"), tr("Play"), []() { can->pause(!can->isPaused()); }); + toolbar->addAction(utils::icon("fast-forward"), tr("Seek forward"), []() { can->seekTo(can->currentSec() + 1); }); if (can->liveStreaming()) { - layout->addWidget(skip_to_end_btn = new ToolButton("skip-end", tr("Skip to the end"), this)); - QObject::connect(skip_to_end_btn, &QToolButton::clicked, [this]() { + skip_to_end_action = toolbar->addAction(utils::icon("skip-end"), tr("Skip to the end"), this, [this]() { // set speed to 1.0 speed_btn->menu()->actions()[7]->setChecked(true); can->pause(false); @@ -87,53 +91,51 @@ QHBoxLayout *VideoWidget::createPlaybackController() { }); } - layout->addWidget(time_btn = new QToolButton); - time_btn->setToolTip(settings.absolute_time ? tr("Elapsed time") : tr("Absolute time")); - time_btn->setAutoRaise(true); - layout->addStretch(0); + time_display_action = toolbar->addAction("", this, [this]() { + settings.absolute_time = !settings.absolute_time; + time_display_action->setToolTip(settings.absolute_time ? tr("Elapsed time") : tr("Absolute time")); + updateState(); + }); + + QWidget *spacer = new QWidget(); + spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + toolbar->addWidget(spacer); if (!can->liveStreaming()) { - layout->addWidget(loop_btn = new ToolButton("repeat", tr("Loop playback"))); - QObject::connect(loop_btn, &QToolButton::clicked, this, &VideoWidget::loopPlaybackClicked); + toolbar->addAction(utils::icon("repeat"), tr("Loop playback"), this, &VideoWidget::loopPlaybackClicked); + createSpeedDropdown(toolbar); + toolbar->addSeparator(); + toolbar->addAction(utils::icon("info-circle"), tr("View route details"), this, &VideoWidget::showRouteInfo); + } else { + createSpeedDropdown(toolbar); } +} - // speed selector - layout->addWidget(speed_btn = new QToolButton(this)); - speed_btn->setAutoRaise(true); +void VideoWidget::createSpeedDropdown(QToolBar *toolbar) { + toolbar->addWidget(speed_btn = new QToolButton(this)); speed_btn->setMenu(new QMenu(speed_btn)); speed_btn->setPopupMode(QToolButton::InstantPopup); QActionGroup *speed_group = new QActionGroup(this); speed_group->setExclusive(true); - int max_width = 0; - QFont font = speed_btn->font(); - font.setBold(true); - speed_btn->setFont(font); - QFontMetrics fm(font); for (float speed : {0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.8, 1., 2., 3., 5.}) { - QString name = QString("%1x").arg(speed); - max_width = std::max(max_width, fm.width(name) + fm.horizontalAdvance(QLatin1Char(' ')) * 2); - - QAction *act = new QAction(name, speed_group); - act->setCheckable(true); - QObject::connect(act, &QAction::toggled, [this, speed]() { + auto act = speed_btn->menu()->addAction(QString("%1x").arg(speed), this, [this, speed]() { can->setSpeed(speed); speed_btn->setText(QString("%1x ").arg(speed)); }); - speed_btn->menu()->addAction(act); - if (speed == 1.0)act->setChecked(true); + + speed_group->addAction(act); + act->setCheckable(true); + if (speed == 1.0) { + act->setChecked(true); + act->trigger(); + } } - speed_btn->setMinimumWidth(max_width + style()->pixelMetric(QStyle::PM_MenuButtonIndicator)); - QObject::connect(play_btn, &QToolButton::clicked, []() { can->pause(!can->isPaused()); }); - QObject::connect(seek_backward_btn, &QToolButton::clicked, []() { can->seekTo(can->currentSec() - 1); }); - QObject::connect(seek_forward_btn, &QToolButton::clicked, []() { can->seekTo(can->currentSec() + 1); }); - QObject::connect(time_btn, &QToolButton::clicked, [this]() { - settings.absolute_time = !settings.absolute_time; - time_btn->setToolTip(settings.absolute_time ? tr("Elapsed time") : tr("Absolute time")); - updateState(); - }); - return layout; + QFont font = speed_btn->font(); + font.setBold(true); + speed_btn->setFont(font); + speed_btn->setMinimumWidth(speed_btn->fontMetrics().horizontalAdvance("0.05x ") + style()->pixelMetric(QStyle::PM_MenuButtonIndicator)); } QWidget *VideoWidget::createCameraWidget() { @@ -146,13 +148,9 @@ QWidget *VideoWidget::createCameraWidget() { camera_tab->setAutoHide(true); camera_tab->setExpanding(false); - QStackedLayout *stacked = new QStackedLayout(); - stacked->setStackingMode(QStackedLayout::StackAll); - stacked->addWidget(cam_widget = new StreamCameraView("camerad", VISION_STREAM_ROAD, false)); + l->addWidget(cam_widget = new StreamCameraView("camerad", VISION_STREAM_ROAD)); cam_widget->setMinimumHeight(MIN_VIDEO_HEIGHT); cam_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); - stacked->addWidget(alert_label = new InfoLabel(this)); - l->addLayout(stacked); l->addWidget(slider = new Slider(w)); slider->setSingleStep(0); @@ -160,26 +158,19 @@ QWidget *VideoWidget::createCameraWidget() { QObject::connect(slider, &QSlider::sliderReleased, [this]() { can->seekTo(slider->currentSecond()); }); QObject::connect(can, &AbstractStream::paused, cam_widget, [c = cam_widget]() { c->showPausedOverlay(); }); - QObject::connect(can, &AbstractStream::resume, cam_widget, [c = cam_widget]() { c->update(); }); QObject::connect(can, &AbstractStream::eventsMerged, this, [this]() { slider->update(); }); QObject::connect(cam_widget, &CameraWidget::clicked, []() { can->pause(!can->isPaused()); }); QObject::connect(cam_widget, &CameraWidget::vipcAvailableStreamsUpdated, this, &VideoWidget::vipcAvailableStreamsUpdated); QObject::connect(camera_tab, &QTabBar::currentChanged, [this](int index) { if (index != -1) cam_widget->setStreamType((VisionStreamType)camera_tab->tabData(index).toInt()); }); - - auto replay = static_cast(can)->getReplay(); - QObject::connect(replay, &Replay::qLogLoaded, slider, &Slider::parseQLog, Qt::QueuedConnection); - QObject::connect(replay, &Replay::minMaxTimeChanged, this, &VideoWidget::timeRangeChanged, Qt::QueuedConnection); + QObject::connect(static_cast(can), &ReplayStream::qLogLoaded, cam_widget, &StreamCameraView::parseQLog, Qt::QueuedConnection); + slider->installEventFilter(this); return w; } void VideoWidget::vipcAvailableStreamsUpdated(std::set streams) { - static const QString stream_names[] = { - [VISION_STREAM_ROAD] = "Road camera", - [VISION_STREAM_WIDE_ROAD] = "Wide road camera", - [VISION_STREAM_DRIVER] = "Driver camera"}; - + static const QString stream_names[] = {"Road camera", "Driver camera", "Wide road camera"}; for (int i = 0; i < streams.size(); ++i) { if (camera_tab->count() <= i) { camera_tab->addTab(QString()); @@ -194,22 +185,15 @@ void VideoWidget::vipcAvailableStreamsUpdated(std::set streams } void VideoWidget::loopPlaybackClicked() { - auto replay = getReplay(); - if (!replay) return; - - if (replay->hasFlag(REPLAY_FLAG_NO_LOOP)) { - replay->removeFlag(REPLAY_FLAG_NO_LOOP); - loop_btn->setIcon("repeat"); - } else { - replay->addFlag(REPLAY_FLAG_NO_LOOP); - loop_btn->setIcon("repeat-1"); - } + bool is_looping = getReplay()->loop(); + getReplay()->setLoop(!is_looping); + qobject_cast(sender())->setIcon(utils::icon(!is_looping ? "repeat" : "repeat-1")); } void VideoWidget::timeRangeChanged() { const auto time_range = can->timeRange(); if (can->liveStreaming()) { - skip_to_end_btn->setEnabled(!time_range.has_value()); + skip_to_end_action->setEnabled(!time_range.has_value()); return; } time_range ? slider->setTimeRange(time_range->first, time_range->second) @@ -228,103 +212,105 @@ void VideoWidget::updateState() { if (!slider->isSliderDown()) { slider->setCurrentSecond(can->currentSec()); } - alert_label->showAlert(slider->alertInfo(can->currentSec())); - time_btn->setText(QString("%1 / %2").arg(formatTime(can->currentSec(), true), + if (camera_tab->count() == 0) { // No streams available + cam_widget->update(); // Manually refresh to show alert events + } + time_display_action->setText(QString("%1 / %2").arg(formatTime(can->currentSec(), true), formatTime(slider->maximum() / slider->factor))); } else { - time_btn->setText(formatTime(can->currentSec(), true)); + time_display_action->setText(formatTime(can->currentSec(), true)); } } void VideoWidget::updatePlayBtnState() { - play_btn->setIcon(can->isPaused() ? "play" : "pause"); - play_btn->setToolTip(can->isPaused() ? tr("Play") : tr("Pause")); + play_toggle_action->setIcon(utils::icon(can->isPaused() ? "play" : "pause")); + play_toggle_action->setToolTip(can->isPaused() ? tr("Play") : tr("Pause")); } -// Slider +void VideoWidget::showThumbnail(double seconds) { + if (can->liveStreaming()) return; -Slider::Slider(QWidget *parent) : QSlider(Qt::Horizontal, parent) { - thumbnail_label = new InfoLabel(parent); - setMouseTracking(true); -} - -AlertInfo Slider::alertInfo(double seconds) { - uint64_t mono_time = can->toMonoTime(seconds); - auto alert_it = alerts.lower_bound(mono_time); - bool has_alert = (alert_it != alerts.end()) && ((alert_it->first - mono_time) <= 1e8); - return has_alert ? alert_it->second : AlertInfo{}; + cam_widget->thumbnail_dispaly_time = seconds; + slider->thumbnail_dispaly_time = seconds; + cam_widget->update(); + slider->update(); } -QPixmap Slider::thumbnail(double seconds) { - auto it = thumbnails.lowerBound(can->toMonoTime(seconds)); - return it != thumbnails.end() ? it.value() : QPixmap(); +void VideoWidget::showRouteInfo() { + RouteInfoDlg *route_info = new RouteInfoDlg(this); + route_info->setAttribute(Qt::WA_DeleteOnClose); + route_info->show(); } -void Slider::setTimeRange(double min, double max) { - assert(min < max); - setRange(min * factor, max * factor); +bool VideoWidget::eventFilter(QObject *obj, QEvent *event) { + if (event->type() == QEvent::MouseMove) { + auto [min_sec, max_sec] = can->timeRange().value_or(std::make_pair(can->minSeconds(), can->maxSeconds())); + showThumbnail(min_sec + static_cast(event)->pos().x() * (max_sec - min_sec) / slider->width()); + } else if (event->type() == QEvent::Leave) { + showThumbnail(-1); + } + return false; } -void Slider::parseQLog(std::shared_ptr qlog) { - std::mutex mutex; - QtConcurrent::blockingMap(qlog->events.cbegin(), qlog->events.cend(), [&mutex, this](const Event &e) { - if (e.which == cereal::Event::Which::THUMBNAIL) { - capnp::FlatArrayMessageReader reader(e.data); - auto thumb = reader.getRoot().getThumbnail(); - auto data = thumb.getThumbnail(); - if (QPixmap pm; pm.loadFromData(data.begin(), data.size(), "jpeg")) { - QPixmap scaled = pm.scaledToHeight(MIN_VIDEO_HEIGHT - THUMBNAIL_MARGIN * 2, Qt::SmoothTransformation); - std::lock_guard lk(mutex); - thumbnails[thumb.getTimestampEof()] = scaled; - } - } else if (e.which == cereal::Event::Which::SELFDRIVE_STATE) { - capnp::FlatArrayMessageReader reader(e.data); - auto cs = reader.getRoot().getSelfdriveState(); - if (cs.getAlertType().size() > 0 && cs.getAlertText1().size() > 0 && - cs.getAlertSize() != cereal::SelfdriveState::AlertSize::NONE) { - std::lock_guard lk(mutex); - alerts.emplace(e.mono_time, AlertInfo{cs.getAlertStatus(), cs.getAlertText1().cStr(), cs.getAlertText2().cStr()}); - } - } - }); - update(); +// Slider +Slider::Slider(QWidget *parent) : QSlider(Qt::Horizontal, parent) { + setMouseTracking(true); } void Slider::paintEvent(QPaintEvent *ev) { QPainter p(this); - QRect r = rect().adjusted(0, 4, 0, -4); - p.fillRect(r, timeline_colors[(int)TimelineType::None]); + + QStyleOptionSlider opt; + initStyleOption(&opt); + QRect handle_rect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); + QRect groove_rect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); + + // Adjust groove height to match handle height + int handle_height = handle_rect.height(); + groove_rect.setHeight(handle_height * 0.5); + groove_rect.moveCenter(QPoint(groove_rect.center().x(), rect().center().y())); + + p.fillRect(groove_rect, timeline_colors[(int)TimelineType::None]); + double min = minimum() / factor; double max = maximum() / factor; auto fillRange = [&](double begin, double end, const QColor &color) { if (begin > max || end < min) return; + + QRect r = groove_rect; r.setLeft(((std::max(min, begin) - min) / (max - min)) * width()); r.setRight(((std::min(max, end) - min) / (max - min)) * width()); p.fillRect(r, color); }; - auto replay = getReplay(); - if (replay) { - for (auto [begin, end, type] : replay->getTimeline()) { - fillRange(begin, end, timeline_colors[(int)type]); + if (auto replay = getReplay()) { + for (const auto &entry : *replay->getTimeline()) { + fillRange(entry.start_time, entry.end_time, timeline_colors[(int)entry.type]); } QColor empty_color = palette().color(QPalette::Window); empty_color.setAlpha(160); - for (const auto &[n, seg] : replay->segments()) { - if (!(seg && seg->isLoaded())) + const auto event_data = replay->getEventData(); + for (const auto &[n, _] : replay->route().segments()) { + if (!event_data->isSegmentLoaded(n)) fillRange(n * 60.0, (n + 1) * 60.0, empty_color); } } - QStyleOptionSlider opt; - opt.initFrom(this); opt.minimum = minimum(); opt.maximum = maximum(); opt.subControls = QStyle::SC_SliderHandle; opt.sliderPosition = value(); style()->drawComplexControl(QStyle::CC_Slider, &opt, &p); + + if (thumbnail_dispaly_time >= 0) { + int left = (thumbnail_dispaly_time - min) * width() / (max - min) - 1; + QRect rc(left, rect().top() + 1, 2, rect().height() - 2); + p.setBrush(palette().highlight()); + p.setPen(Qt::NoPen); + p.drawRoundedRect(rc, 1.5, 1.5); + } } void Slider::mousePressEvent(QMouseEvent *e) { @@ -335,106 +321,119 @@ void Slider::mousePressEvent(QMouseEvent *e) { } } -void Slider::mouseMoveEvent(QMouseEvent *e) { - int pos = std::clamp(e->pos().x(), 0, width()); - double seconds = (minimum() + pos * ((maximum() - minimum()) / (double)width())) / factor; - QPixmap thumb = thumbnail(seconds); - if (!thumb.isNull()) { - int x = std::clamp(pos - thumb.width() / 2, THUMBNAIL_MARGIN, width() - thumb.width() - THUMBNAIL_MARGIN + 1); - int y = -thumb.height() - THUMBNAIL_MARGIN; - thumbnail_label->showPixmap(mapToParent(QPoint(x, y)), utils::formatSeconds(seconds), thumb, alertInfo(seconds)); - } else { - thumbnail_label->hide(); - } - QSlider::mouseMoveEvent(e); +// StreamCameraView +StreamCameraView::StreamCameraView(std::string stream_name, VisionStreamType stream_type, QWidget *parent) + : CameraWidget(stream_name, stream_type, parent) { + fade_animation = new QPropertyAnimation(this, "overlayOpacity"); + fade_animation->setDuration(500); + fade_animation->setStartValue(0.2f); + fade_animation->setEndValue(0.7f); + fade_animation->setEasingCurve(QEasingCurve::InOutQuad); + connect(fade_animation, &QPropertyAnimation::valueChanged, this, QOverload<>::of(&StreamCameraView::update)); } -bool Slider::event(QEvent *event) { - switch (event->type()) { - case QEvent::WindowActivate: - case QEvent::WindowDeactivate: - case QEvent::FocusIn: - case QEvent::FocusOut: - case QEvent::Leave: - thumbnail_label->hide(); - break; - default: - break; +void StreamCameraView::parseQLog(std::shared_ptr qlog) { + std::mutex mutex; + const auto &events = qlog->events; + unsigned int num_threads = std::max(1u, std::thread::hardware_concurrency()); + size_t chunk = (events.size() + num_threads - 1) / num_threads; + std::vector threads; + for (unsigned int t = 0; t < num_threads && t * chunk < events.size(); ++t) { + size_t start = t * chunk; + size_t end = std::min(start + chunk, events.size()); + threads.emplace_back([this, &mutex, &events, start, end]() { + for (size_t i = start; i < end; ++i) { + const Event &e = events[i]; + if (e.which == cereal::Event::Which::THUMBNAIL) { + capnp::FlatArrayMessageReader reader(e.data); + auto thumb_data = reader.getRoot().getThumbnail(); + auto image_data = thumb_data.getThumbnail(); + if (QPixmap thumb; thumb.loadFromData(image_data.begin(), image_data.size(), "jpeg")) { + QPixmap generated_thumb = generateThumbnail(thumb, can->toSeconds(thumb_data.getTimestampEof())); + std::lock_guard lock(mutex); + thumbnails[thumb_data.getTimestampEof()] = generated_thumb; + big_thumbnails[thumb_data.getTimestampEof()] = thumb; + } + } + } + }); } - return QSlider::event(event); + for (auto &th : threads) th.join(); + update(); } -// InfoLabel - -InfoLabel::InfoLabel(QWidget *parent) : QWidget(parent, Qt::WindowStaysOnTopHint) { - setAttribute(Qt::WA_ShowWithoutActivating); - setVisible(false); -} +void StreamCameraView::paintGL() { + CameraWidget::paintGL(); -void InfoLabel::showPixmap(const QPoint &pt, const QString &sec, const QPixmap &pm, const AlertInfo &alert) { - second = sec; - pixmap = pm; - alert_info = alert; - setGeometry(QRect(pt, pm.size())); - setVisible(true); - update(); -} + QPainter p(this); + bool scrubbing = false; + if (thumbnail_dispaly_time >= 0) { + scrubbing = can->isPaused(); + scrubbing ? drawScrubThumbnail(p) : drawThumbnail(p); + } + if (auto alert = getReplay()->findAlertAtTime(scrubbing ? thumbnail_dispaly_time : can->currentSec())) { + drawAlert(p, rect(), *alert); + } -void InfoLabel::showAlert(const AlertInfo &alert) { - alert_info = alert; - pixmap = {}; - setVisible(!alert_info.text1.isEmpty()); - update(); + if (can->isPaused()) { + p.setPen(QColor(200, 200, 200, static_cast(255 * fade_animation->currentValue().toFloat()))); + p.setFont(QFont(font().family(), 16, QFont::Bold)); + p.drawText(rect(), Qt::AlignCenter, tr("PAUSED")); + } } -void InfoLabel::paintEvent(QPaintEvent *event) { - QPainter p(this); +QPixmap StreamCameraView::generateThumbnail(QPixmap thumb, double seconds) { + QPixmap scaled = thumb.scaledToHeight(MIN_VIDEO_HEIGHT - THUMBNAIL_MARGIN * 2, Qt::SmoothTransformation); + QPainter p(&scaled); p.setPen(QPen(palette().color(QPalette::BrightText), 2)); - if (!pixmap.isNull()) { - p.drawPixmap(0, 0, pixmap); - p.drawRect(rect()); - p.drawText(rect().adjusted(0, 0, 0, -THUMBNAIL_MARGIN), second, Qt::AlignHCenter | Qt::AlignBottom); + p.drawRect(scaled.rect()); + if (auto alert = getReplay()->findAlertAtTime(seconds)) { + p.setFont(QFont(font().family(), 10)); + drawAlert(p, scaled.rect(), *alert); } - if (alert_info.text1.size() > 0) { - QColor color = timeline_colors[(int)TimelineType::AlertInfo]; - if (alert_info.status == cereal::SelfdriveState::AlertStatus::USER_PROMPT) { - color = timeline_colors[(int)TimelineType::AlertWarning]; - } else if (alert_info.status == cereal::SelfdriveState::AlertStatus::CRITICAL) { - color = timeline_colors[(int)TimelineType::AlertCritical]; - } - color.setAlphaF(0.5); - QString text = alert_info.text1; - if (!alert_info.text2.isEmpty()) { - text += "\n" + alert_info.text2; - } + return scaled; +} - if (!pixmap.isNull()) { - QFont font; - font.setPixelSize(11); - p.setFont(font); - } - QRect text_rect = rect().adjusted(1, 1, -1, -1); - QRect r = p.fontMetrics().boundingRect(text_rect, Qt::AlignTop | Qt::AlignHCenter | Qt::TextWordWrap, text); - p.fillRect(text_rect.left(), r.top(), text_rect.width(), r.height(), color); - p.drawText(text_rect, Qt::AlignTop | Qt::AlignHCenter | Qt::TextWordWrap, text); +void StreamCameraView::drawScrubThumbnail(QPainter &p) { + p.fillRect(rect(), Qt::black); + auto it = big_thumbnails.lower_bound(can->toMonoTime(thumbnail_dispaly_time)); + if (it != big_thumbnails.end()) { + QPixmap scaled_thumb = it->second.scaled(rect().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); + QRect thumb_rect(rect().center() - scaled_thumb.rect().center(), scaled_thumb.size()); + p.drawPixmap(thumb_rect.topLeft(), scaled_thumb); + drawTime(p, thumb_rect, thumbnail_dispaly_time); } } -StreamCameraView::StreamCameraView(std::string stream_name, VisionStreamType stream_type, bool zoom, QWidget *parent) - : CameraWidget(stream_name, stream_type, zoom, parent) { - fade_animation = new QPropertyAnimation(this, "overlayOpacity"); - fade_animation->setDuration(500); - fade_animation->setStartValue(0.2f); - fade_animation->setEndValue(0.7f); +void StreamCameraView::drawThumbnail(QPainter &p) { + auto it = thumbnails.lower_bound(can->toMonoTime(thumbnail_dispaly_time)); + if (it != thumbnails.end()) { + const QPixmap &thumb = it->second; + auto [min_sec, max_sec] = can->timeRange().value_or(std::make_pair(can->minSeconds(), can->maxSeconds())); + int pos = (thumbnail_dispaly_time - min_sec) * width() / (max_sec - min_sec); + int x = std::clamp(pos - thumb.width() / 2, THUMBNAIL_MARGIN, width() - thumb.width() - THUMBNAIL_MARGIN + 1); + int y = height() - thumb.height() - THUMBNAIL_MARGIN; + + p.drawPixmap(x, y, thumb); + drawTime(p, QRect{x, y, thumb.width(), thumb.height()}, thumbnail_dispaly_time); + } } -void StreamCameraView::paintGL() { - CameraWidget::paintGL(); +void StreamCameraView::drawTime(QPainter &p, const QRect &rect, double seconds) { + p.setPen(palette().color(QPalette::BrightText)); + p.setFont(QFont(font().family(), 10)); + p.drawText(rect.adjusted(0, 0, 0, -THUMBNAIL_MARGIN), Qt::AlignHCenter | Qt::AlignBottom, QString::number(seconds, 'f', 3)); +} - if (can->isPaused()) { - QPainter p(this); - p.setPen(QColor(200, 200, 200, static_cast(255 * overlay_opacity))); - p.setFont(QFont(font().family(), 16, QFont::Bold)); - p.drawText(rect(), Qt::AlignCenter, tr("PAUSED")); - } +void StreamCameraView::drawAlert(QPainter &p, const QRect &rect, const Timeline::Entry &alert) { + p.setPen(QPen(palette().color(QPalette::BrightText), 2)); + QColor color = timeline_colors[int(alert.type)]; + color.setAlphaF(0.5); + QString text = QString::fromStdString(alert.text1); + if (!alert.text2.empty()) text += "\n" + QString::fromStdString(alert.text2); + + QRect text_rect = rect.adjusted(1, 1, -1, -1); + QRect r = p.fontMetrics().boundingRect(text_rect, Qt::AlignTop | Qt::AlignHCenter | Qt::TextWordWrap, text); + p.fillRect(text_rect.left(), r.top(), text_rect.width(), r.height(), color); + p.drawText(text_rect, Qt::AlignTop | Qt::AlignHCenter | Qt::TextWordWrap, text); } diff --git a/tools/cabana/videowidget.h b/tools/cabana/videowidget.h index 76364083a8f2f3..e52e92ebd120db 100644 --- a/tools/cabana/videowidget.h +++ b/tools/cabana/videowidget.h @@ -2,37 +2,20 @@ #include #include -#include #include #include #include -#include #include #include #include +#include #include -#include "selfdrive/ui/qt/widgets/cameraview.h" +#include "tools/cabana/cameraview.h" #include "tools/cabana/utils/util.h" #include "tools/replay/logreader.h" - -struct AlertInfo { - cereal::SelfdriveState::AlertStatus status; - QString text1; - QString text2; -}; - -class InfoLabel : public QWidget { -public: - InfoLabel(QWidget *parent); - void showPixmap(const QPoint &pt, const QString &sec, const QPixmap &pm, const AlertInfo &alert); - void showAlert(const AlertInfo &alert); - void paintEvent(QPaintEvent *event) override; - QPixmap pixmap; - QString second; - AlertInfo alert_info; -}; +#include "tools/cabana/streams/replaystream.h" class Slider : public QSlider { Q_OBJECT @@ -41,41 +24,34 @@ class Slider : public QSlider { Slider(QWidget *parent); double currentSecond() const { return value() / factor; } void setCurrentSecond(double sec) { setValue(sec * factor); } - void setTimeRange(double min, double max); - AlertInfo alertInfo(double sec); - QPixmap thumbnail(double sec); - void parseQLog(std::shared_ptr qlog); - - const double factor = 1000.0; - -private: + void setTimeRange(double min, double max) { setRange(min * factor, max * factor); } void mousePressEvent(QMouseEvent *e) override; - void mouseMoveEvent(QMouseEvent *e) override; - bool event(QEvent *event) override; void paintEvent(QPaintEvent *ev) override; - - QMap thumbnails; - std::map alerts; - InfoLabel *thumbnail_label; + const double factor = 1000.0; + double thumbnail_dispaly_time = -1; }; class StreamCameraView : public CameraWidget { Q_OBJECT - Q_PROPERTY(float overlayOpacity READ overlayOpacity WRITE setOverlayOpacity) public: - StreamCameraView(std::string stream_name, VisionStreamType stream_type, bool zoom, QWidget *parent = nullptr); + StreamCameraView(std::string stream_name, VisionStreamType stream_type, QWidget *parent = nullptr); void paintGL() override; void showPausedOverlay() { fade_animation->start(); } - float overlayOpacity() const { return overlay_opacity; } - void setOverlayOpacity(float opacity) { - overlay_opacity = opacity; - update(); - } + void parseQLog(std::shared_ptr qlog); private: - float overlay_opacity; + QPixmap generateThumbnail(QPixmap thumbnail, double seconds); + void drawAlert(QPainter &p, const QRect &rect, const Timeline::Entry &alert); + void drawThumbnail(QPainter &p); + void drawScrubThumbnail(QPainter &p); + void drawTime(QPainter &p, const QRect &rect, double seconds); + QPropertyAnimation *fade_animation; + std::map big_thumbnails; + std::map thumbnails; + double thumbnail_dispaly_time = -1; + friend class VideoWidget; }; class VideoWidget : public QFrame { @@ -83,26 +59,26 @@ class VideoWidget : public QFrame { public: VideoWidget(QWidget *parnet = nullptr); + void showThumbnail(double seconds); protected: + bool eventFilter(QObject *obj, QEvent *event) override; QString formatTime(double sec, bool include_milliseconds = false); void timeRangeChanged(); void updateState(); void updatePlayBtnState(); QWidget *createCameraWidget(); - QHBoxLayout *createPlaybackController(); + void createPlaybackController(); + void createSpeedDropdown(QToolBar *toolbar); void loopPlaybackClicked(); void vipcAvailableStreamsUpdated(std::set streams); + void showRouteInfo(); StreamCameraView *cam_widget; - QToolButton *time_btn = nullptr; - ToolButton *seek_backward_btn = nullptr; - ToolButton *play_btn = nullptr; - ToolButton *seek_forward_btn = nullptr; - ToolButton *loop_btn = nullptr; + QAction *time_display_action = nullptr; + QAction *play_toggle_action = nullptr; QToolButton *speed_btn = nullptr; - ToolButton *skip_to_end_btn = nullptr; - InfoLabel *alert_label = nullptr; + QAction *skip_to_end_action = nullptr; Slider *slider = nullptr; QTabBar *camera_tab = nullptr; }; diff --git a/tools/camerastream/README.md b/tools/camerastream/README.md index 7dbafb4be5f8b4..2f7498a07c05d8 100644 --- a/tools/camerastream/README.md +++ b/tools/camerastream/README.md @@ -39,7 +39,7 @@ Decode the stream with `compressed_vipc.py`: To actually display the stream, run `watch3` in separate terminal: -```cd ~/openpilot/selfdrive/ui/ && ./watch3``` +```cd ~/openpilot/selfdrive/ui/ && ./watch3.py``` ## compressed_vipc.py usage ``` @@ -62,5 +62,5 @@ options: ## Example: ``` cd ~/openpilot/tools/camerastream && ./compressed_vipc.py comma-ffffffff --cams 0 -cd ~/openpilot/selfdrive/ui/ && ./watch3 +cd ~/openpilot/selfdrive/ui/ && ./watch3.py ``` diff --git a/tools/camerastream/compressed_vipc.py b/tools/camerastream/compressed_vipc.py index f531a289f91ffa..4dc74272ea50be 100755 --- a/tools/camerastream/compressed_vipc.py +++ b/tools/camerastream/compressed_vipc.py @@ -62,7 +62,7 @@ def decoder(addr, vipc_server, vst, nvidia, W, H, debug=False): print("waiting for iframe") continue time_q.append(time.monotonic()) - network_latency = (int(time.time()*1e9) - evta.unixTimestampNanos)/1e6 + network_latency = (int(time.time()*1e9) - evta.unixTimestampNanos)/1e6 # noqa: TID251 frame_latency = ((evta.idx.timestampEof/1e9) - (evta.idx.timestampSof/1e9))*1000 process_latency = ((evt.logMonoTime/1e9) - (evta.idx.timestampEof/1e9))*1000 @@ -101,13 +101,13 @@ def decoder(addr, vipc_server, vst, nvidia, W, H, debug=False): pc_latency = (time.monotonic()-time_q[0])*1000 time_q = time_q[1:] if debug: - print("%2d %4d %.3f %.3f roll %6.2f ms latency %6.2f ms + %6.2f ms + %6.2f ms = %6.2f ms" - % (len(msgs), evta.idx.encodeId, evt.logMonoTime/1e9, evta.idx.timestampEof/1e6, frame_latency, - process_latency, network_latency, pc_latency, process_latency+network_latency+pc_latency ), len(evta.data), sock_name) + print(f"{len(msgs):2d} {evta.idx.encodeId:4d} {evt.logMonoTime/1e9:.3f} {evta.idx.timestampEof/1e6:.3f} \ + roll {frame_latency:6.2f} ms latency {process_latency:6.2f} ms + {network_latency:6.2f} ms + {pc_latency:6.2f} ms \ + = {process_latency+network_latency+pc_latency:6.2f} ms", len(evta.data), sock_name) class CompressedVipc: - def __init__(self, addr, vision_streams, nvidia=False, debug=False): + def __init__(self, addr, vision_streams, server_name, nvidia=False, debug=False): print("getting frame sizes") os.environ["ZMQ"] = "1" messaging.reset_context() @@ -117,10 +117,10 @@ def __init__(self, addr, vision_streams, nvidia=False, debug=False): os.environ.pop("ZMQ") messaging.reset_context() - self.vipc_server = VisionIpcServer("camerad") + self.vipc_server = VisionIpcServer(server_name) for vst in vision_streams: ed = sm[ENCODE_SOCKETS[vst]] - self.vipc_server.create_buffers(vst, 4, False, ed.width, ed.height) + self.vipc_server.create_buffers(vst, 4, ed.width, ed.height) self.vipc_server.start_listener() self.procs = [] @@ -144,6 +144,7 @@ def kill(self): parser.add_argument("addr", help="Address of comma three") parser.add_argument("--nvidia", action="store_true", help="Use nvidia instead of ffmpeg") parser.add_argument("--cams", default="0,1,2", help="Cameras to decode") + parser.add_argument("--server", default="camerad", help="choose vipc server name") parser.add_argument("--silent", action="store_true", help="Suppress debug output") args = parser.parse_args() @@ -154,7 +155,7 @@ def kill(self): ] vsts = [vision_streams[int(x)] for x in args.cams.split(",")] - cvipc = CompressedVipc(args.addr, vsts, args.nvidia, debug=(not args.silent)) + cvipc = CompressedVipc(args.addr, vsts, args.server, args.nvidia, debug=(not args.silent)) # register exit handler signal.signal(signal.SIGINT, lambda sig, frame: cvipc.kill()) diff --git a/tools/car_porting/README.md b/tools/car_porting/README.md index 68b0a57fb37039..77492035cabc31 100644 --- a/tools/car_porting/README.md +++ b/tools/car_porting/README.md @@ -57,7 +57,21 @@ Traceback (most recent call last): AssertionError: 1 is not false : panda safety doesn't agree with openpilot: {'gasPressed': 116} ``` -### [tools/car_porting/examples/subaru_steer_temp_fault.ipynb](/tools/car_porting/examples/subaru_steer_temp_fault.ipynb) +## Jupyter notebooks + +To use these notebooks, install Jupyter within your [openpilot virtual environment](/tools/README.md). + +```bash +uv pip install jupyter ipykernel +``` + +Launching: + +```bash +jupyter notebook +``` + +### [examples/subaru_steer_temp_fault.ipynb](/tools/car_porting/examples/subaru_steer_temp_fault.ipynb) An example of searching through a database of segments for a specific condition, and plotting the results. @@ -65,7 +79,7 @@ An example of searching through a database of segments for a specific condition, *a plot of the steer_warning vs steering angle, where we can see it is clearly caused by a large steering angle change* -### [tools/car_porting/examples/subaru_long_accel.ipynb](/tools/car_porting/examples/subaru_long_accel.ipynb) +### [examples/subaru_long_accel.ipynb](/tools/car_porting/examples/subaru_long_accel.ipynb) An example of plotting the response of an actuator when it is active. @@ -73,7 +87,7 @@ An example of plotting the response of an actuator when it is active. *a plot of the brake_pressure vs acceleration, where we can see it is a fairly linear response.* -### [tools/car_porting/examples/ford_vin_fingerprint.ipynb](/tools/car_porting/examples/ford_vin_fingerprint.ipynb) +### [examples/ford_vin_fingerprint.ipynb](/tools/car_porting/examples/ford_vin_fingerprint.ipynb) In this example, we use the public comma car segments database to check if vin fingerprinting is feasible for ford. @@ -94,3 +108,22 @@ vin: 5LM5J7XC8MGXXXXXX real platform: FORD EXPLORER 6TH GEN determi vin: 3FTTW8E31PRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False vin: 3FTTW8E99NRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False ``` + +### [examples/find_segments_with_message.ipynb](/tools/car_porting/examples/find_segments_with_message.ipynb) + +Searches for segments where a set of given CAN message IDs are present. In the example, we search for all messages +used for CAN-based ignition detection. + +``` +Match found: 46b21f1c5f7aa885/2024-01-23--15-19-34/20/s JEEP GRAND CHEROKEE V6 2018 ['VW CAN Ign'] +Match found: a63a23c3e628f288/2023-11-05--18-36-20/8/s JEEP GRAND CHEROKEE V6 2018 ['VW CAN Ign'] +Match found: ce31b7a998781ba8/2024-01-19--07-05-29/23/s JEEP GRAND CHEROKEE 2019 ['VW CAN Ign'] +Match found: e1dfba62a4e33f7b/2023-12-25--19-31-00/4/s JEEP GRAND CHEROKEE 2019 ['VW CAN Ign'] +Match found: e1dfba62a4e33f7b/2024-01-10--14-33-57/2/s JEEP GRAND CHEROKEE 2019 ['VW CAN Ign'] +Match found: ae679616266f4096/2023-12-05--15-43-46/4/s RAM HD 5TH GEN ['Tesla 3/Y CAN Ign'] +Match found: ae679616266f4096/2023-11-18--17-49-42/3/s RAM HD 5TH GEN ['Tesla 3/Y CAN Ign'] +Match found: ae679616266f4096/2024-01-03--21-57-09/25/s RAM HD 5TH GEN ['Tesla 3/Y CAN Ign'] +Match found: 6dae2984cc53cd7f/2023-12-10--11-53-15/17/s FORD BRONCO SPORT 1ST GEN ['Rivian CAN Ign'] +Match found: 6dae2984cc53cd7f/2023-12-03--17-31-17/29/s FORD BRONCO SPORT 1ST GEN ['Rivian CAN Ign'] +Match found: 6dae2984cc53cd7f/2023-11-27--23-29-07/1/s FORD BRONCO SPORT 1ST GEN ['Rivian CAN Ign'] +``` diff --git a/tools/car_porting/auto_fingerprint.py b/tools/car_porting/auto_fingerprint.py index 5080293e29ebcc..abae8d9f17a042 100755 --- a/tools/car_porting/auto_fingerprint.py +++ b/tools/car_porting/auto_fingerprint.py @@ -2,7 +2,7 @@ import argparse from collections import defaultdict -from openpilot.selfdrive.debug.format_fingerprints import format_brand_fw_versions +from opendbc.car.debug.format_fingerprints import format_brand_fw_versions from opendbc.car.fingerprints import MIGRATION from opendbc.car.fw_versions import MODEL_TO_BRAND, match_fw_to_car diff --git a/tools/car_porting/examples/find_segments_with_message.ipynb b/tools/car_porting/examples/find_segments_with_message.ipynb new file mode 100644 index 00000000000000..af17bde52bc9c2 --- /dev/null +++ b/tools/car_porting/examples/find_segments_with_message.ipynb @@ -0,0 +1,232 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 85, + "id": "facb8edc-9924-491a-a4dd-fe6135b0c6c4", + "metadata": {}, + "outputs": [], + "source": [ + "# Import all cars from opendbc\n", + "\n", + "from opendbc.car import structs\n", + "from opendbc.car.values import PLATFORMS as TEST_PLATFORMS\n", + "\n", + "# Example: add additional platforms/segments to test outside of commaCarSegments\n", + "\n", + "EXTRA_SEGMENTS = {\n", + " # \"81dd9e9fe256c397/0000001f--97c42cf98d\", # Volkswagen ID.4 test route, new car port, not in public dataset\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": 86, + "id": "ed1c8aec-c274-4c61-b83d-711ea194bf86", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Searching 221 platforms\n", + "No segments available for DODGE_DURANGO\n", + "No segments available for FORD_RANGER_MK2\n", + "No segments available for HOLDEN_ASTRA\n", + "No segments available for CADILLAC_ATS\n", + "No segments available for CHEVROLET_MALIBU\n", + "No segments available for CADILLAC_XT4\n", + "No segments available for CHEVROLET_VOLT_2019\n", + "No segments available for CHEVROLET_TRAVERSE\n", + "No segments available for GMC_YUKON\n", + "No segments available for HONDA_ODYSSEY_CHN\n", + "No segments available for HYUNDAI_KONA_2022\n", + "No segments available for HYUNDAI_NEXO_1ST_GEN\n", + "No segments available for GENESIS_GV70_ELECTRIFIED_1ST_GEN\n", + "No segments available for GENESIS_G80_2ND_GEN_FL\n", + "No segments available for RIVIAN_R1_GEN1\n", + "No segments available for SUBARU_FORESTER_HYBRID\n", + "No segments available for TESLA_MODEL_3\n", + "No segments available for TESLA_MODEL_Y\n", + "No segments available for TOYOTA_RAV4_PRIME\n", + "No segments available for TOYOTA_SIENNA_4TH_GEN\n", + "No segments available for LEXUS_LC_TSS2\n", + "No segments available for VOLKSWAGEN_CADDY_MK3\n", + "No segments available for VOLKSWAGEN_CRAFTER_MK2\n", + "No segments available for VOLKSWAGEN_JETTA_MK6\n", + "Searching 577 segments\n" + ] + } + ], + "source": [ + "import random\n", + "\n", + "from openpilot.tools.lib.logreader import LogReader\n", + "from openpilot.tools.lib.comma_car_segments import get_comma_car_segments_database\n", + "\n", + "\n", + "MAX_SEGS_PER_PLATFORM = 3 # Increase this to search more segments\n", + "\n", + "database = get_comma_car_segments_database()\n", + "TEST_SEGMENTS = []\n", + "\n", + "print(f\"Searching {len(TEST_PLATFORMS)} platforms\")\n", + "\n", + "for platform in TEST_PLATFORMS:\n", + " if platform not in database:\n", + " print(f\"No segments available for {platform}\")\n", + " continue\n", + "\n", + " all_segments = database[platform]\n", + " NUM_SEGMENTS = min(len(all_segments), MAX_SEGS_PER_PLATFORM)\n", + " TEST_SEGMENTS.extend(random.sample(all_segments, NUM_SEGMENTS))\n", + "\n", + "TEST_SEGMENTS.extend(EXTRA_SEGMENTS)\n", + "\n", + "print(f\"Searching {len(TEST_SEGMENTS)} segments\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0c75e8f2-4f5f-4f89-b8db-5223a6534a9f", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "27a243c33de44498b2b946190df44b23", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "segments searched: 0%| | 0/577 [00:00 0:\n", + " message_names = [MESSAGES_TO_FIND[message] for message in matched_messages]\n", + " print(f\"Match found: {segment:<45} {CP.carFingerprint:<38} {message_names}\")\n", + "\n", + " progress_bar.update()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7724dd97-f62e-4fd3-9f64-63d49be669d2", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9f393e00-8efd-40fb-a41e-d312531a83e8", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.0" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tools/car_porting/examples/ford_vin_fingerprint.ipynb b/tools/car_porting/examples/ford_vin_fingerprint.ipynb index 21d1cb62c0fde6..6b806d22d2b698 100644 --- a/tools/car_porting/examples/ford_vin_fingerprint.ipynb +++ b/tools/car_porting/examples/ford_vin_fingerprint.ipynb @@ -2,19 +2,32 @@ "cells": [ { "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], + "execution_count": 12, + "metadata": { + "jupyter": { + "is_executing": true + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Got 9 Ford cars from opendbc\n" + ] + } + ], "source": [ "\"\"\"In this example, we use the public comma car segments database to check if vin fingerprinting is feasible for ford.\"\"\"\n", "\n", - "from openpilot.tools.lib.logreader import LogReader\n", + "from openpilot.tools.lib.logreader import LogReader, comma_car_segments_source\n", "from openpilot.tools.lib.comma_car_segments import get_comma_car_segments_database\n", - "from openpilot.selfdrive.car.ford.values import CAR\n", + "from opendbc.car.ford.values import CAR\n", "\n", "database = get_comma_car_segments_database()\n", "\n", - "platforms = [c.value for c in CAR]" + "platforms = [c.value for c in CAR]\n", + "print(f\"Got {len(platforms)} Ford cars from opendbc\")" ] }, { @@ -54,21 +67,24 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Got 287 segments for platform FORD BRONCO SPORT 1ST GEN, sampling 5 segments\n", - "Got 137 segments for platform FORD ESCAPE 4TH GEN, sampling 5 segments\n", - "Got 1041 segments for platform FORD EXPLORER 6TH GEN, sampling 5 segments\n", - "Got 5 segments for platform FORD F-150 14TH GEN, sampling 5 segments\n", - "Got 56 segments for platform FORD FOCUS 4TH GEN, sampling 5 segments\n", - "Got 637 segments for platform FORD MAVERICK 1ST GEN, sampling 5 segments\n", - "Got 3 segments for platform FORD F-150 LIGHTNING 1ST GEN, sampling 3 segments\n", - "Got 3 segments for platform FORD MUSTANG MACH-E 1ST GEN, sampling 3 segments\n" + "Collecting segments from commaCarSegments dataset:\n", + "Got 287 segments for platform FORD_BRONCO_SPORT_MK1, sampling 5 segments\n", + "Got 137 segments for platform FORD_ESCAPE_MK4, sampling 5 segments\n", + "Got 1041 segments for platform FORD_EXPLORER_MK6, sampling 5 segments\n", + "Got 5 segments for platform FORD_F_150_MK14, sampling 5 segments\n", + "Got 3 segments for platform FORD_F_150_LIGHTNING_MK1, sampling 3 segments\n", + "Got 56 segments for platform FORD_FOCUS_MK4, sampling 5 segments\n", + "Got 637 segments for platform FORD_MAVERICK_MK1, sampling 5 segments\n", + "Got 3 segments for platform FORD_MUSTANG_MACH_E_MK1, sampling 3 segments\n", + "Skipping platform: FORD_RANGER_MK2, no data available\n", + "Segment collection finished\n" ] } ], @@ -79,11 +95,12 @@ "\n", "VINS_TO_CHECK = set()\n", "\n", + "print(\"Collecting segments from commaCarSegments dataset:\")\n", "for platform in platforms:\n", " if platform not in database:\n", " print(f\"Skipping platform: {platform}, no data available\")\n", " continue\n", - " \n", + "\n", " all_segments = database[platform]\n", "\n", " NUM_SEGMENTS = min(len(all_segments), MAX_SEGS_PER_PLATFORM)\n", @@ -93,35 +110,37 @@ " segments = random.sample(all_segments, NUM_SEGMENTS)\n", "\n", " for segment in segments:\n", - " lr = LogReader(segment)\n", + " lr = LogReader(segment, sources=[comma_car_segments_source])\n", " CP = lr.first(\"carParams\")\n", " if \"FORD\" not in CP.carFingerprint:\n", " print(segment, CP.carFingerprint)\n", - " VINS_TO_CHECK.add((CP.carVin, CP.carFingerprint))" + " VINS_TO_CHECK.add((CP.carVin, CP.carFingerprint))\n", + "\n", + "print(\"Segment collection finished\")" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "vin: 3FTTW8E34PRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False\n", + "vin: 3FMCR9B69NRXXXXXX real platform: FORD BRONCO SPORT 1ST GEN determined platform: mock correct: False\n", "vin: 00000000000XXXXXX real platform: FORD F-150 14TH GEN determined platform: mock correct: False\n", + "vin: 1FMCU9J94MUXXXXXX real platform: FORD ESCAPE 4TH GEN determined platform: mock correct: False\n", "vin: 3FMTK3SU0MMXXXXXX real platform: FORD MUSTANG MACH-E 1ST GEN determined platform: FORD MUSTANG MACH-E 1ST GEN correct: True\n", + "vin: 1FM5K8HC7MGXXXXXX real platform: FORD EXPLORER 6TH GEN determined platform: mock correct: False\n", + "vin: 5LM5J7XC9LGXXXXXX real platform: FORD EXPLORER 6TH GEN determined platform: mock correct: False\n", "vin: 1FTVW1EL4NWXXXXXX real platform: FORD F-150 LIGHTNING 1ST GEN determined platform: FORD F-150 LIGHTNING 1ST GEN correct: True\n", "vin: WF0NXXGCHNJXXXXXX real platform: FORD FOCUS 4TH GEN determined platform: mock correct: False\n", - "vin: 1FMCU9J94MUXXXXXX real platform: FORD ESCAPE 4TH GEN determined platform: mock correct: False\n", - "vin: 3FTTW8E33NRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False\n", - "vin: 3FMCR9B69NRXXXXXX real platform: FORD BRONCO SPORT 1ST GEN determined platform: mock correct: False\n", + "vin: 3FTTW8E99NRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False\n", "vin: 1FM5K8GC7LGXXXXXX real platform: FORD EXPLORER 6TH GEN determined platform: mock correct: False\n", - "vin: 5LM5J7XC9LGXXXXXX real platform: FORD EXPLORER 6TH GEN determined platform: mock correct: False\n", + "vin: 3FTTW8E33NRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False\n", "vin: 5LM5J7XC1LGXXXXXX real platform: FORD EXPLORER 6TH GEN determined platform: mock correct: False\n", - "vin: 3FTTW8F97NRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False\n", - "vin: 3FTTW8E99NRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False\n" + "vin: 3FTTW8E3XPRXXXXXX real platform: FORD MAVERICK 1ST GEN determined platform: mock correct: False\n" ] } ], @@ -134,7 +153,7 @@ ], "metadata": { "kernelspec": { - "display_name": ".venv", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -148,9 +167,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.12.3" } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/tools/car_porting/examples/hkg_canfd_gear_message.ipynb b/tools/car_porting/examples/hkg_canfd_gear_message.ipynb new file mode 100644 index 00000000000000..f0bca8decca385 --- /dev/null +++ b/tools/car_porting/examples/hkg_canfd_gear_message.ipynb @@ -0,0 +1,277 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 62, + "id": "228a6736-de31-4255-9d72-a6ff391b968d", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found 6 qualifying vehicles:\n", + " KIA_EV6\n", + " HYUNDAI_KONA_EV_2ND_GEN\n", + " HYUNDAI_IONIQ_5\n", + " KIA_NIRO_EV_2ND_GEN\n", + " HYUNDAI_IONIQ_6\n", + " GENESIS_GV60_EV_1ST_GEN\n" + ] + } + ], + "source": [ + "from opendbc.car import structs\n", + "from opendbc.car.hyundai.values import CAR, HyundaiFlags\n", + "from opendbc.car.hyundai.fingerprints import FW_VERSIONS\n", + "\n", + "TEST_PLATFORMS = set(CAR.with_flags(HyundaiFlags.CANFD)) & set(CAR.with_flags(HyundaiFlags.EV)) # CAN-FD electric vehicles only\n", + "#TEST_PLATFORMS = set(CAR.with_flags(HyundaiFlags.CANFD)) - set(CAR.with_flags(HyundaiFlags.EV)) # CAN-FD hybrid and ICE vehicles only\n", + "\n", + "print(f\"Found {len(TEST_PLATFORMS)} qualifying vehicles:\")\n", + "for platform in TEST_PLATFORMS:\n", + " print(f\" {platform}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "id": "ed1c8aec-c274-4c61-b83d-711ea194bf86", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Collecting segments from commaCarSegments dataset:\n", + "Got 1300 segments for platform KIA_EV6, sampling 5 segments\n", + "Got 9 segments for platform HYUNDAI_KONA_EV_2ND_GEN, sampling 5 segments\n", + "Got 1570 segments for platform HYUNDAI_IONIQ_5, sampling 5 segments\n", + "Got 34 segments for platform KIA_NIRO_EV_2ND_GEN, sampling 5 segments\n", + "Got 974 segments for platform HYUNDAI_IONIQ_6, sampling 5 segments\n", + "Got 157 segments for platform GENESIS_GV60_EV_1ST_GEN, sampling 5 segments\n", + "Collected 30 segments for analysis\n" + ] + } + ], + "source": [ + "import random\n", + "\n", + "from openpilot.tools.lib.logreader import LogReader\n", + "from openpilot.tools.lib.comma_car_segments import get_comma_car_segments_database\n", + "from opendbc.car.hyundai.values import CAR\n", + "\n", + "database = get_comma_car_segments_database()\n", + "TEST_SEGMENTS = []\n", + "\n", + "MAX_SEGS_PER_PLATFORM = 5 # TODO: Increase this to search more segments\n", + "\n", + "print(\"Collecting segments from commaCarSegments dataset:\")\n", + "for platform in TEST_PLATFORMS:\n", + " assert(platform in database)\n", + " #if platform not in database:\n", + " # print(f\"Skipping platform: {platform}, no data available\")\n", + " # continue\n", + "\n", + " all_segments = database[platform]\n", + "\n", + " NUM_SEGMENTS = min(len(all_segments), MAX_SEGS_PER_PLATFORM)\n", + "\n", + " print(f\"Got {len(all_segments)} segments for platform {platform}, sampling {NUM_SEGMENTS} segments\")\n", + "\n", + " TEST_SEGMENTS.extend(random.sample(all_segments, NUM_SEGMENTS))\n", + "\n", + "print(f\"Collected {len(TEST_SEGMENTS)} segments for analysis\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "id": "0c75e8f2-4f5f-4f89-b8db-5223a6534a9f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Analyzing segment ff2bd20623fcaeaa/2023-11-26--16-27-04/5/s for KIA EV6 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 3f1a6480f940cf9a/2024-01-10--23-06-11/16/s for KIA EV6 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment b0a9998109ed0053/2023-12-15--11-10-18/12/s for KIA EV6 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 6e14aa2ed85025df/2023-11-15--13-18-12/24/s for KIA EV6 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment a43f21df3a1ca12d/2024-01-25--08-56-22/16/s for KIA EV6 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 1618132d68afc876/2023-12-05--13-49-24/11/s for HYUNDAI KONA ELECTRIC 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 1618132d68afc876/2023-11-26--12-31-18/17/s for HYUNDAI KONA ELECTRIC 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 1618132d68afc876/2023-12-05--11-51-44/3/s for HYUNDAI KONA ELECTRIC 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 1618132d68afc876/2023-08-27--09-32-14/13/s for HYUNDAI KONA 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 1618132d68afc876/2024-01-25--15-07-04/24/s for HYUNDAI KONA ELECTRIC 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 223780ed74116bc2/2023-11-16--09-44-56/15/s for HYUNDAI IONIQ 5 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment ba9951252624f37d/2024-01-20--22-33-23/118/s for HYUNDAI IONIQ 5 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 8379b28e51ceb3b1/2023-11-09--23-21-58/92/s for HYUNDAI IONIQ 5 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 26fac43e27cd6091/2023-11-06--12-23-21/9/s for HYUNDAI IONIQ 5 2022\n", + " GEAR_SHIFTER gear=1.0\n", + " ACCELERATOR gear=0.0\n", + "Analyzing segment 5edb897a0ec7a477/2024-01-13--20-41-36/101/s for HYUNDAI IONIQ 5 2022\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 66cf8ea23b7c2789/2023-12-04--13-48-53/5/s for KIA NIRO EV 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment b153671049a867b3/2023-12-10--20-31-37/2/s for KIA NIRO EV 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment b153671049a867b3/2023-12-03--21-08-30/14/s for KIA NIRO EV 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment b153671049a867b3/2023-11-07--19-52-23/0/s for KIA NIRO EV 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment b153671049a867b3/2023-07-12--19-25-18/6/s for KIA NIRO EV 2ND GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 9ea4578ee2b1abcb/2023-11-18--07-59-26/11/s for HYUNDAI IONIQ 6 2023\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 0ad7facc77922c3e/2023-12-21--17-47-25/18/s for HYUNDAI IONIQ 6 2023\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 26968f888e7330d3/2024-01-02--11-18-37/8/s for HYUNDAI IONIQ 6 2023\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 9ea4578ee2b1abcb/2023-11-27--21-03-24/33/s for HYUNDAI IONIQ 6 2023\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment df7fdd56970d90fe/2024-01-07--01-04-39/26/s for HYUNDAI IONIQ 6 2023\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 94542b2d06f7a9a6/2023-12-11--14-45-44/0/s for GENESIS GV60 ELECTRIC 1ST GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 94542b2d06f7a9a6/2023-12-11--20-57-09/8/s for GENESIS GV60 ELECTRIC 1ST GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 94542b2d06f7a9a6/2024-01-03--12-52-38/5/s for GENESIS GV60 ELECTRIC 1ST GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 94542b2d06f7a9a6/2024-01-19--19-57-52/47/s for GENESIS GV60 ELECTRIC 1ST GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analyzing segment 94542b2d06f7a9a6/2024-01-03--13-01-23/1/s for GENESIS GV60 ELECTRIC 1ST GEN\n", + " GEAR_SHIFTER gear=4.0\n", + " ACCELERATOR gear=5.0\n", + "Analysis finished\n" + ] + } + ], + "source": [ + "import copy\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "from opendbc.can.parser import CANParser\n", + "from opendbc.car.hyundai.values import DBC\n", + "from opendbc.car.hyundai.hyundaicanfd import CanBus\n", + "\n", + "from openpilot.selfdrive.pandad import can_capnp_to_list\n", + "from openpilot.tools.lib.logreader import LogReader, comma_car_segments_source\n", + "\n", + "message_names = [\"GEAR_SHIFTER\", \"ACCELERATOR\", \"GEAR\", \"GEAR_ALT\", \"GEAR_ALT_2\"]\n", + "\n", + "for segment in TEST_SEGMENTS:\n", + " lr = LogReader(segment, sources=[comma_car_segments_source])\n", + " CP = lr.first(\"carParams\")\n", + " if CP is None:\n", + " continue\n", + "\n", + " can_msgs = [msg for msg in lr if msg.which() == \"can\"]\n", + " parser_messages = []\n", + " for name in message_names:\n", + " parser_messages.append((name, 0))\n", + " cp = CANParser(DBC[platform][\"pt\"], parser_messages, CanBus(CP).ECAN)\n", + "\n", + " parsed_message_history = []\n", + " examples = []\n", + "\n", + " for msg in can_msgs:\n", + " cp.update_strings(can_capnp_to_list([msg.as_builder().to_bytes()]))\n", + " parsed_message_history.append(copy.copy(cp.vl))\n", + "\n", + " print(f\"Analyzing segment {segment:<44} for {CP.carFingerprint}\")\n", + " for name in message_names:\n", + " if parsed_message_history[0][name][\"CHECKSUM\"] != 0: # Message is present for this segment\n", + " gear_prev = parsed_message_history[0][name][\"GEAR\"]\n", + " print(f\" {name:<15} gear={gear_prev}\")\n", + " for i, parsed_messages in enumerate(parsed_message_history):\n", + " gear = parsed_messages[name][\"GEAR\"]\n", + " if gear != gear_prev:\n", + " print(f\" *** Signal transition found! ***\")\n", + " examples.append(i)\n", + " gear_prev = gear\n", + "\n", + "print(f\"Analysis finished\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7724dd97-f62e-4fd3-9f64-63d49be669d2", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9f393e00-8efd-40fb-a41e-d312531a83e8", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tools/car_porting/examples/subaru_fuzzy_fingerprint.ipynb b/tools/car_porting/examples/subaru_fuzzy_fingerprint.ipynb index 1048011c05c126..708e55865bc1bf 100644 --- a/tools/car_porting/examples/subaru_fuzzy_fingerprint.ipynb +++ b/tools/car_porting/examples/subaru_fuzzy_fingerprint.ipynb @@ -2,32 +2,24 @@ "cells": [ { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "kj/filesystem-disk-unix.c++:1703: warning: PWD environment variable doesn't match current directory; pwd = /home/batman\n" - ] - } - ], + "outputs": [], "source": [ - "from cereal import car\n", - "from openpilot.selfdrive.car.subaru.values import CAR, SubaruFlags\n", - "from openpilot.selfdrive.car.subaru.fingerprints import FW_VERSIONS\n", + "from opendbc.car import structs\n", + "from opendbc.car.subaru.values import CAR, SubaruFlags\n", + "from opendbc.car.subaru.fingerprints import FW_VERSIONS\n", "\n", "TEST_PLATFORMS = set(CAR) - CAR.with_flags(SubaruFlags.PREGLOBAL)\n", "\n", - "Ecu = car.CarParams.Ecu\n", + "Ecu = structs.CarParams.Ecu\n", "\n", "FW_BY_ECU = {platform: {ecu: versions for (ecu, addr, sub_addr), versions in fw_versions.items()} for platform, fw_versions in FW_VERSIONS.items()}" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "metadata": {}, "outputs": [], "source": [ @@ -59,7 +51,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 8, "metadata": {}, "outputs": [], "source": [ @@ -83,64 +75,66 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "SUBARU IMPREZA LIMITED 2019 08 not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", - "SUBARU IMPREZA LIMITED 2019 08 not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", - "SUBARU IMPREZA LIMITED 2019 0c not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", - "SUBARU IMPREZA LIMITED 2019 0c not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", - "SUBARU IMPREZA LIMITED 2019 2e not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", - "SUBARU IMPREZA LIMITED 2019 3f not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", - "correct_year=True platform=SUBARU OUTBACK 7TH GEN year=2023 years=[2023]\n", - "correct_year=True platform=SUBARU OUTBACK 7TH GEN year=2023 years=[2023]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2022 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU OUTBACK 6TH GEN year=2022 years=[2020, 2021, 2022]\n", - "correct_year=False platform=SUBARU CROSSTREK HYBRID 2020 year=2019 years=[2020]\n", - "correct_year=False platform=SUBARU CROSSTREK HYBRID 2020 year=2021 years=[2020]\n", - "correct_year=False platform=SUBARU FORESTER HYBRID 2020 year=2019 years=[2020]\n", - "correct_year=True platform=SUBARU LEGACY 7TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU LEGACY 7TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU LEGACY 7TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU LEGACY 7TH GEN year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU IMPREZA LIMITED 2019 year=2019 years=[2017, 2018, 2019]\n", - "correct_year=True platform=SUBARU IMPREZA LIMITED 2019 year=2019 years=[2017, 2018, 2019]\n", - "correct_year=True platform=SUBARU IMPREZA LIMITED 2019 year=2018 years=[2017, 2018, 2019]\n", - "correct_year=True platform=SUBARU IMPREZA LIMITED 2019 year=2019 years=[2017, 2018, 2019]\n", - "correct_year=True platform=SUBARU IMPREZA LIMITED 2019 year=2019 years=[2017, 2018, 2019]\n", - "correct_year=True platform=SUBARU IMPREZA LIMITED 2019 year=2019 years=[2017, 2018, 2019]\n", - "correct_year=False platform=SUBARU FORESTER 2022 year=2021 years=[2022, 2023, 2024]\n", - "correct_year=False platform=SUBARU FORESTER 2022 year=2021 years=[2022, 2023, 2024]\n", - "correct_year=True platform=SUBARU FORESTER 2022 year=2022 years=[2022, 2023, 2024]\n", - "correct_year=True platform=SUBARU FORESTER 2022 year=2022 years=[2022, 2023, 2024]\n", - "correct_year=False platform=SUBARU IMPREZA SPORT 2020 year=2019 years=[2020, 2021, 2022]\n", - "correct_year=False platform=SUBARU IMPREZA SPORT 2020 year=2019 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU IMPREZA SPORT 2020 year=2020 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU IMPREZA SPORT 2020 year=2021 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU IMPREZA SPORT 2020 year=2021 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU IMPREZA SPORT 2020 year=2021 years=[2020, 2021, 2022]\n", - "correct_year=True platform=SUBARU ASCENT 2023 year=2023 years=[2023]\n", - "correct_year=True platform=SUBARU ASCENT LIMITED 2019 year=2019 years=[2019, 2020, 2021]\n", - "correct_year=True platform=SUBARU ASCENT LIMITED 2019 year=2021 years=[2019, 2020, 2021]\n", - "correct_year=False platform=SUBARU FORESTER 2019 year=2018 years=[2019, 2020, 2021]\n", - "correct_year=False platform=SUBARU FORESTER 2019 year=2018 years=[2019, 2020, 2021]\n", - "correct_year=True platform=SUBARU FORESTER 2019 year=2019 years=[2019, 2020, 2021]\n", - "correct_year=True platform=SUBARU FORESTER 2019 year=2019 years=[2019, 2020, 2021]\n", - "correct_year=True platform=SUBARU FORESTER 2019 year=2020 years=[2019, 2020, 2021]\n", - "correct_year=True platform=SUBARU FORESTER 2019 year=2020 years=[2019, 2020, 2021]\n" + "SUBARU_IMPREZA 08 not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", + "SUBARU_IMPREZA 08 not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", + "SUBARU_IMPREZA 0c not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", + "SUBARU_IMPREZA 0c not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", + "SUBARU_IMPREZA 2e not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", + "SUBARU_IMPREZA 3f not in dict_keys([b'\\x18', b'\\x19', b' ', b'!', b'\"', b'#'])\n", + "correct_year=False platform=SUBARU_FORESTER year=2018 years=[2019, 2020, 2021]\n", + "correct_year=False platform=SUBARU_FORESTER year=2018 years=[2019, 2020, 2021]\n", + "correct_year=True platform=SUBARU_FORESTER year=2019 years=[2019, 2020, 2021]\n", + "correct_year=True platform=SUBARU_FORESTER year=2019 years=[2019, 2020, 2021]\n", + "correct_year=True platform=SUBARU_FORESTER year=2019 years=[2019, 2020, 2021]\n", + "correct_year=True platform=SUBARU_FORESTER year=2020 years=[2019, 2020, 2021]\n", + "correct_year=True platform=SUBARU_FORESTER year=2020 years=[2019, 2020, 2021]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2022 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_OUTBACK year=2022 years=[2020, 2021, 2022]\n", + "correct_year=False platform=SUBARU_FORESTER_HYBRID year=2019 years=[2020]\n", + "correct_year=False platform=SUBARU_CROSSTREK_HYBRID year=2019 years=[2020]\n", + "correct_year=False platform=SUBARU_CROSSTREK_HYBRID year=2021 years=[2020]\n", + "correct_year=True platform=SUBARU_ASCENT_2023 year=2023 years=[2023]\n", + "correct_year=True platform=SUBARU_IMPREZA year=2019 years=[2017, 2018, 2019]\n", + "correct_year=True platform=SUBARU_IMPREZA year=2019 years=[2017, 2018, 2019]\n", + "correct_year=True platform=SUBARU_IMPREZA year=2018 years=[2017, 2018, 2019]\n", + "correct_year=True platform=SUBARU_IMPREZA year=2019 years=[2017, 2018, 2019]\n", + "correct_year=True platform=SUBARU_IMPREZA year=2019 years=[2017, 2018, 2019]\n", + "correct_year=True platform=SUBARU_IMPREZA year=2019 years=[2017, 2018, 2019]\n", + "correct_year=False platform=SUBARU_FORESTER_2022 year=2021 years=[2022, 2023, 2024]\n", + "correct_year=False platform=SUBARU_FORESTER_2022 year=2021 years=[2022, 2023, 2024]\n", + "correct_year=True platform=SUBARU_FORESTER_2022 year=2022 years=[2022, 2023, 2024]\n", + "correct_year=True platform=SUBARU_FORESTER_2022 year=2022 years=[2022, 2023, 2024]\n", + "correct_year=True platform=SUBARU_ASCENT year=2019 years=[2019, 2020, 2021]\n", + "correct_year=True platform=SUBARU_ASCENT year=2021 years=[2019, 2020, 2021]\n", + "correct_year=True platform=SUBARU_OUTBACK_2023 year=2023 years=[2023]\n", + "correct_year=True platform=SUBARU_OUTBACK_2023 year=2023 years=[2023]\n", + "correct_year=False platform=SUBARU_IMPREZA_2020 year=2019 years=[2020, 2021, 2022]\n", + "correct_year=False platform=SUBARU_IMPREZA_2020 year=2019 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_IMPREZA_2020 year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_IMPREZA_2020 year=2021 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_IMPREZA_2020 year=2021 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_IMPREZA_2020 year=2021 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_IMPREZA_2020 year=2021 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_LEGACY year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_LEGACY year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_LEGACY year=2020 years=[2020, 2021, 2022]\n", + "correct_year=True platform=SUBARU_LEGACY year=2020 years=[2020, 2021, 2022]\n" ] } ], @@ -160,64 +154,66 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "in_possible_platforms=True platform=SUBARU OUTBACK 7TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 7TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU OUTBACK 6TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU CROSSTREK HYBRID 2020 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU CROSSTREK HYBRID 2020 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU FORESTER HYBRID 2020 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU LEGACY 7TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU LEGACY 7TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU LEGACY 7TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU LEGACY 7TH GEN platforms=['SUBARU OUTBACK 6TH GEN', 'SUBARU LEGACY 7TH GEN', 'SUBARU OUTBACK 7TH GEN']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA LIMITED 2019 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2022 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2022 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2022 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2022 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA SPORT 2020 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA SPORT 2020 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA SPORT 2020 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA SPORT 2020 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA SPORT 2020 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU IMPREZA SPORT 2020 platforms=['SUBARU IMPREZA LIMITED 2019', 'SUBARU IMPREZA SPORT 2020', 'SUBARU CROSSTREK HYBRID 2020']\n", - "in_possible_platforms=True platform=SUBARU ASCENT 2023 platforms=['SUBARU ASCENT LIMITED 2019', 'SUBARU ASCENT 2023']\n", - "in_possible_platforms=True platform=SUBARU ASCENT LIMITED 2019 platforms=['SUBARU ASCENT LIMITED 2019', 'SUBARU ASCENT 2023']\n", - "in_possible_platforms=True platform=SUBARU ASCENT LIMITED 2019 platforms=['SUBARU ASCENT LIMITED 2019', 'SUBARU ASCENT 2023']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2019 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2019 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2019 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2019 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2019 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n", - "in_possible_platforms=True platform=SUBARU FORESTER 2019 platforms=['SUBARU FORESTER 2019', 'SUBARU FORESTER HYBRID 2020', 'SUBARU FORESTER 2022']\n" + "in_possible_platforms=True platform=SUBARU_FORESTER platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER_HYBRID platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_CROSSTREK_HYBRID platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_CROSSTREK_HYBRID platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_ASCENT_2023 platforms=['SUBARU_ASCENT', 'SUBARU_ASCENT_2023']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER_2022 platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER_2022 platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER_2022 platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_FORESTER_2022 platforms=['SUBARU_FORESTER', 'SUBARU_FORESTER_HYBRID', 'SUBARU_FORESTER_2022']\n", + "in_possible_platforms=True platform=SUBARU_ASCENT platforms=['SUBARU_ASCENT', 'SUBARU_ASCENT_2023']\n", + "in_possible_platforms=True platform=SUBARU_ASCENT platforms=['SUBARU_ASCENT', 'SUBARU_ASCENT_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK_2023 platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_OUTBACK_2023 platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA_2020 platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA_2020 platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA_2020 platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA_2020 platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA_2020 platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA_2020 platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_IMPREZA_2020 platforms=['SUBARU_IMPREZA', 'SUBARU_IMPREZA_2020', 'SUBARU_CROSSTREK_HYBRID']\n", + "in_possible_platforms=True platform=SUBARU_LEGACY platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_LEGACY platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_LEGACY platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n", + "in_possible_platforms=True platform=SUBARU_LEGACY platforms=['SUBARU_OUTBACK', 'SUBARU_LEGACY', 'SUBARU_OUTBACK_2023']\n" ] } ], @@ -231,11 +227,18 @@ "for platform, possible_platforms in codes:\n", " test_platform_code(platform, possible_platforms)" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { - "display_name": ".venv", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -249,9 +252,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.12.3" } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/tools/car_porting/examples/subaru_long_accel.ipynb b/tools/car_porting/examples/subaru_long_accel.ipynb index 35b92702a7e991..d4a4705d9554bc 100644 --- a/tools/car_porting/examples/subaru_long_accel.ipynb +++ b/tools/car_porting/examples/subaru_long_accel.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": {}, "outputs": [], "source": [ @@ -14,7 +14,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": {}, "outputs": [], "source": [ @@ -22,8 +22,8 @@ "import numpy as np\n", "\n", "from opendbc.can.parser import CANParser\n", + "from opendbc.car.subaru.values import DBC\n", "\n", - "from openpilot.selfdrive.car.subaru.values import DBC\n", "from openpilot.selfdrive.pandad import can_capnp_to_list\n", "from openpilot.tools.lib.logreader import LogReader\n", "\n", @@ -64,7 +64,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "metadata": {}, "outputs": [], "source": [ @@ -95,11 +95,18 @@ "ax.set_ylabel(\"Acceleration\")\n", "ax.scatter(cruise_brake[valid_brake], -acceleration[valid_brake])" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -113,9 +120,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.12.3" } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/tools/car_porting/examples/subaru_steer_temp_fault.ipynb b/tools/car_porting/examples/subaru_steer_temp_fault.ipynb index 8b762fecb8461b..10abe8ed31f9e7 100644 --- a/tools/car_porting/examples/subaru_steer_temp_fault.ipynb +++ b/tools/car_porting/examples/subaru_steer_temp_fault.ipynb @@ -25,8 +25,8 @@ "import numpy as np\n", "\n", "from opendbc.can.parser import CANParser\n", + "from opendbc.car.subaru.values import CanBus, DBC\n", "\n", - "from openpilot.selfdrive.car.subaru.values import CanBus, DBC\n", "from openpilot.selfdrive.pandad import can_capnp_to_list\n", "from openpilot.tools.lib.logreader import LogReader\n", "\n", @@ -85,11 +85,18 @@ "\n", " plt.show()\n" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -103,9 +110,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.12.3" } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/tools/tuning/measure_steering_accuracy.py b/tools/car_porting/measure_steering_accuracy.py similarity index 94% rename from tools/tuning/measure_steering_accuracy.py rename to tools/car_porting/measure_steering_accuracy.py index 0b8916343e9e2d..ae3344c2eb1548 100755 --- a/tools/tuning/measure_steering_accuracy.py +++ b/tools/car_porting/measure_steering_accuracy.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# type: ignore import os import time @@ -47,9 +46,9 @@ def update(self, sm): v_ego = sm['carState'].vEgo active = sm['controlsState'].active - steer = sm['carOutput'].actuatorsOutput.steer + steer = sm['carOutput'].actuatorsOutput.torque standstill = sm['carState'].standstill - steer_limited = abs(sm['carControl'].actuators.steer - sm['carControl'].actuatorsOutput.steer) > 1e-2 + steer_limited_by_safety = abs(sm['carControl'].actuators.torque - sm['carControl'].actuatorsOutput.torque) > 1e-2 overriding = sm['carState'].steeringPressed changing_lanes = sm['modelV2'].meta.laneChangeState != 0 model_points = sm['modelV2'].position.y @@ -77,7 +76,7 @@ def update(self, sm): self.speed_group_stats[group][angle_abs]["steer"] += abs(steer) if len(model_points): self.speed_group_stats[group][angle_abs]["dpp"] += abs(model_points[0]) - if steer_limited: + if steer_limited_by_safety: self.speed_group_stats[group][angle_abs]["limited"] += 1 if control_state.saturated: self.speed_group_stats[group][angle_abs]["saturated"] += 1 @@ -118,12 +117,8 @@ def update(self, sm): parser.add_argument('--route', help="route name") parser.add_argument('--addr', default='127.0.0.1', help="IP address for optional ZMQ listener, default to msgq") parser.add_argument('--group', default='all', help="speed group to display, [crawl|slow|medium|fast|veryfast|germany|all], default to all") - parser.add_argument('--cache', default=False, action='store_true', help="use cached data, default to False") args = parser.parse_args() - if args.cache: - os.environ['FILEREADER_CACHE'] = '1' - tool = SteeringAccuracyTool(args) if args.route is not None: diff --git a/tools/car_porting/test_car_model.py b/tools/car_porting/test_car_model.py index 6f274aaf698e7c..dd248f562e59e7 100755 --- a/tools/car_porting/test_car_model.py +++ b/tools/car_porting/test_car_model.py @@ -5,14 +5,14 @@ from opendbc.car.tests.routes import CarTestRoute from openpilot.selfdrive.car.tests.test_models import TestCarModel -from openpilot.tools.lib.route import SegmentName +from openpilot.tools.lib.route import SegmentRange -def create_test_models_suite(routes: list[CarTestRoute], ci=False) -> unittest.TestSuite: +def create_test_models_suite(routes: list[CarTestRoute]) -> unittest.TestSuite: test_suite = unittest.TestSuite() for test_route in routes: # create new test case and discover tests - test_case_args = {"platform": test_route.car_model, "test_route": test_route, "test_route_on_bucket": ci} + test_case_args = {"platform": test_route.car_model, "test_route": test_route} CarModelTestCase = type("CarModelTestCase", (TestCarModel,), test_case_args) test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(CarModelTestCase)) return test_suite @@ -23,16 +23,14 @@ def create_test_models_suite(routes: list[CarTestRoute], ci=False) -> unittest.T "Uses selfdrive/car/tests/test_models.py") parser.add_argument("route_or_segment_name", help="Specify route to run tests on") parser.add_argument("--car", help="Specify car model for test route") - parser.add_argument("--ci", action="store_true", help="Attempt to get logs using openpilotci, need to specify car") args = parser.parse_args() if len(sys.argv) == 1: parser.print_help() sys.exit() - route_or_segment_name = SegmentName(args.route_or_segment_name.strip(), allow_route_name=True) - segment_num = route_or_segment_name.segment_num if route_or_segment_name.segment_num != -1 else None + sr = SegmentRange(args.route_or_segment_name) - test_route = CarTestRoute(route_or_segment_name.route_name.canonical_name, args.car, segment=segment_num) - test_suite = create_test_models_suite([test_route], ci=args.ci) + test_routes = [CarTestRoute(sr.route_name, args.car, segment=seg_idx) for seg_idx in sr.seg_idxs] + test_suite = create_test_models_suite(test_routes) unittest.TextTestRunner().run(test_suite) diff --git a/tools/ci/Dockerfile.replay b/tools/ci/Dockerfile.replay new file mode 100644 index 00000000000000..0f36ba2f12bb50 --- /dev/null +++ b/tools/ci/Dockerfile.replay @@ -0,0 +1,74 @@ +# Digest-pinned base for trusted private-runner replay jobs. +# Build/runtime packages install as root; the image default USER is 1001:1001 with no sudo. +# Source is NOT COPY'd: nap-replay-job bind-mounts / ephemeral /src (not executed on the host). +# Because there is no sudo, one-shot setup_dependencies / uv sync must be started as root by +# the launcher (podman --user 0), then replay drops back to --user 1001:1001 --network=none. +# Python deps land in the mounted /src/.venv (VIRTUAL_ENV=/src/.venv); they are not baked in. +FROM ubuntu:24.04@sha256:561618e2c15bf2397621dd04f96926663a3b5616c189cf7e38db7e82f5c538ea + +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONUNBUFFERED=1 \ + LANG=en_US.UTF-8 \ + LANGUAGE=en_US:en \ + LC_ALL=en_US.UTF-8 \ + OPENPILOT_PATH=/src \ + VIRTUAL_ENV=/src/.venv \ + PYTHONPATH=/src \ + HOME=/home/runner \ + PATH="/usr/local/bin:/src/.venv/bin:/home/runner/.local/bin:${PATH}" + +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates \ + build-essential \ + cmake \ + pkg-config \ + curl \ + libcurl4-openssl-dev \ + libssl-dev \ + libusb-1.0-0-dev \ + libzmq3-dev \ + libsqlite3-dev \ + libbz2-dev \ + zlib1g-dev \ + libva-dev \ + libva-drm2 \ + libdrm-dev \ + git \ + git-lfs \ + locales \ + python3 \ + python3-venv \ + xz-utils \ + zstd \ + time \ + xvfb \ + && sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen \ + && locale-gen \ + && git lfs install --system \ + && UV_VERSION=0.12.2 \ + && UV_ARCH=x86_64-unknown-linux-gnu \ + && UV_TARBALL="uv-${UV_ARCH}.tar.gz" \ + && UV_SHA256=d66e96b5f1ca3b99806eee283a8125d33a0bd669e6e6d9bc4ab7ffda63c41bf4 \ + && curl -fsSL "https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${UV_TARBALL}" -o "/tmp/${UV_TARBALL}" \ + && echo "${UV_SHA256} /tmp/${UV_TARBALL}" | sha256sum -c - \ + && tar -xzf "/tmp/${UV_TARBALL}" -C /tmp \ + && install -m 0755 "/tmp/uv-${UV_ARCH}/uv" /usr/local/bin/uv \ + && rm -rf "/tmp/${UV_TARBALL}" "/tmp/uv-${UV_ARCH}" \ + && test -x /usr/local/bin/uv \ + && uv --version | grep -F "uv ${UV_VERSION}" \ + && groupadd --gid 1001 runner \ + && useradd --uid 1001 --gid 1001 --create-home --home-dir /home/runner \ + --shell /usr/sbin/nologin runner \ + && passwd -l runner \ + && mkdir -p /src \ + && chown 1001:1001 /src \ + && rm -rf /var/lib/apt/lists/* \ + && ! command -v sudo >/dev/null + +WORKDIR /src + +# No sudoers entry. Default runtime is unprivileged; launcher may override to root for setup. +USER 1001:1001 + +# Controller invokes replay under --userns=keep-id:uid=1001,gid=1001 --network=none. +CMD ["bash", "-lc", "selfdrive/test/process_replay/test_processes.py --help"] diff --git a/tools/ci/assemble_replay_release.py b/tools/ci/assemble_replay_release.py new file mode 100755 index 00000000000000..228f9e1d068de8 --- /dev/null +++ b/tools/ci/assemble_replay_release.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""Assemble a process-replay release/ tree from harness fakedata candidates. + +Layout (public consumer contract): + release/ref_commit + release/manifest.json (canonical sorted JSON + LF) + release/{case_id}__{process}__{source_sha}.zst + +This tool only assembles the active inventory (16 cases / 66 refs). Staged / +pending descriptors are rejected so non-executable sources cannot be published +through this path. + +Manifest is NOT final unless every case/ref identity carries harness +params_digest + source_sha256 (and aggregate sources_digest/params_digest), +plus openpilot/opendbc SHAs, previous_accepted_tag, filenames/sizes/hashes. + +results.json / timing / run metadata must stay outside release/. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +from pathlib import Path + +NAME_RE_TMPL = r"^[a-z0-9][a-z0-9-]*__[a-z0-9_]+__{sha}\.zst$" +CASE_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$") +PROC_RE = re.compile(r"^[a-z0-9_]+$") +SHA_RE = re.compile(r"^[0-9a-f]{40}$") +DIGEST_RE = re.compile(r"^[0-9a-f]{64}$") +TAG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$") + +# Active inventory only: 16 cases / 66 tasks. +EXPECTED_CASES = 16 +EXPECTED_TASKS = 66 +EXPECTED_PARTITION = {"card": 16, "controlsd": 16, "lagd": 16, "other": 18} + + +def die(msg: str) -> None: + raise SystemExit(f"assemble_replay_release: {msg}") + + +def canonical_json(obj: object) -> bytes: + return (json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n").encode("utf-8") + + +def sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def require_digest(label: str, value: object) -> str: + text = str(value or "") + if not DIGEST_RE.fullmatch(text): + die(f"{label} must be 64 lowercase hex (harness digest); omitted/invalid values reject the manifest") + return text + + +def validate_case_record(rec: dict) -> dict: + cid = str(rec.get("case_id", "")) + if not CASE_RE.fullmatch(cid): + die(f"invalid case_id {cid!r}") + for key in ( + "car_brand", + "source", + "processes", + "custom_params", + "params_digest", + "executable", + "source_sha256", + "source_bytes", + ): + if key not in rec: + die(f"case {cid} missing {key}") + if rec["executable"] is not True: + die(f"case {cid} must be executable for release assembly") + if not isinstance(rec["source"], str) or not rec["source"]: + die(f"case {cid} source must be non-empty string") + if not isinstance(rec["processes"], list) or not rec["processes"]: + die(f"case {cid} processes must be non-empty list") + if not isinstance(rec["custom_params"], dict): + die(f"case {cid} custom_params must be object") + params = require_digest(f"case {cid} params_digest", rec["params_digest"]) + source_sha256 = require_digest(f"case {cid} source_sha256", rec["source_sha256"]) + try: + source_bytes = int(rec["source_bytes"]) + except (TypeError, ValueError): + die(f"case {cid} source_bytes must be int") + if source_bytes <= 0: + die(f"case {cid} source_bytes must be > 0") + # Preserve harness record fields; normalize digests for identity. + out = dict(rec) + out["case_id"] = cid + out["params_digest"] = params + out["source_sha256"] = source_sha256 + out["source_bytes"] = source_bytes + return out + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + "--operation", + required=True, + choices=("generate-active",), + help="Only generate-active is supported (staged publication is rejected)", + ) + parser.add_argument("--source-sha", required=True) + parser.add_argument("--fakedata-dir", required=True, type=Path) + parser.add_argument("--release-dir", required=True, type=Path) + parser.add_argument("--opendbc-sha", required=True) + parser.add_argument("--cases-json", required=True, type=Path, help="Harness --list-cases JSON for exact records") + parser.add_argument( + "--previous-accepted-tag", + required=True, + help="Immutable previous-accepted tag/ref identity (required provenance; no empty default)", + ) + args = parser.parse_args() + + source_sha = args.source_sha.strip() + if source_sha != source_sha.lower() or not SHA_RE.fullmatch(source_sha): + die("source_sha must be 40 lowercase hex") + opendbc_sha = args.opendbc_sha.strip() + if opendbc_sha != opendbc_sha.lower() or not SHA_RE.fullmatch(opendbc_sha): + die("opendbc_sha must be 40 lowercase hex") + + previous_accepted_tag = str(args.previous_accepted_tag).strip() + if not TAG_RE.fullmatch(previous_accepted_tag): + die("previous_accepted_tag missing or invalid") + + if not args.cases_json.is_file(): + die(f"cases json missing: {args.cases_json}") + case_records = json.loads(args.cases_json.read_text(encoding="utf-8")) + if not isinstance(case_records, list): + die("cases json must be a list") + if len(case_records) != EXPECTED_CASES: + die(f"cases json count {len(case_records)} != {EXPECTED_CASES}") + + by_id: dict[str, dict] = {} + for raw in case_records: + if not isinstance(raw, dict): + die("case record must be object") + rec = validate_case_record(raw) + cid = rec["case_id"] + if cid in by_id: + die(f"duplicate case_id {cid}") + by_id[cid] = rec + + fakedata = args.fakedata_dir + if not fakedata.is_dir(): + die(f"fakedata dir missing: {fakedata}") + + release = args.release_dir + if release.exists(): + for p in sorted(release.rglob("*"), reverse=True): + if p.is_symlink(): + die(f"symlink forbidden in release: {p}") + if p.is_file(): + p.unlink() + elif p.is_dir(): + p.rmdir() + release.mkdir(parents=True, exist_ok=True) + + name_re = re.compile(NAME_RE_TMPL.format(sha=re.escape(source_sha))) + refs: dict[str, dict[str, object]] = {} + case_ids: set[str] = set() + counts = {"card": 0, "controlsd": 0, "lagd": 0, "other": 0} + + for path in sorted(fakedata.glob(f"*__*__{source_sha}.zst")): + if path.is_symlink() or not path.is_file(): + die(f"invalid candidate: {path}") + name = path.name + if not name_re.fullmatch(name): + die(f"candidate name rejected: {name}") + case_id, process, _rest = name.split("__", 2) + if not CASE_RE.fullmatch(case_id) or not PROC_RE.fullmatch(process): + die(f"bad case/process in {name}") + if case_id not in by_id: + die(f"candidate case {case_id} not in harness case list") + rec = by_id[case_id] + if process not in set(rec["processes"]): + die(f"process {process} not in case {case_id} process set") + task_id = f"{case_id}:{process}" + if task_id in refs: + die(f"duplicate task {task_id}") + data = path.read_bytes() + digest = sha256_bytes(data) + dest = release / name + dest.write_bytes(data) + # Per-ref identity: filename/size/hash + harness source/params digests. + refs[task_id] = { + "filename": name, + "size": len(data), + "sha256": digest, + "source": rec["source"], + "source_sha256": rec["source_sha256"], + "source_bytes": rec["source_bytes"], + "params_digest": rec["params_digest"], + } + case_ids.add(case_id) + counts[process if process in counts else "other"] += 1 + + if len(refs) != EXPECTED_TASKS: + die(f"expected {EXPECTED_TASKS} tasks, found {len(refs)}") + if len(case_ids) != EXPECTED_CASES: + die(f"expected {EXPECTED_CASES} cases, found {len(case_ids)}") + if case_ids != set(by_id): + die(f"assembled cases {sorted(case_ids)} != harness cases {sorted(by_id)}") + if counts != EXPECTED_PARTITION: + die(f"partition mismatch: {counts} != {EXPECTED_PARTITION}") + + # Exact task identity set: every process in every case record must be present. + expected_task_ids = sorted( + f"{cid}:{proc}" for cid, rec in by_id.items() for proc in rec["processes"] + ) + if sorted(refs) != expected_task_ids: + die("assembled task identities do not match harness case process sets") + + ordered_cases = [by_id[cid] for cid in sorted(by_id)] + ordered_refs = {k: refs[k] for k in sorted(refs)} + + # Match validator/trusted-inventory aggregate digests exactly: sorted arrays of + # records (not case-id-keyed dicts). + sources_payload = [ + { + "case_id": cid, + "source": by_id[cid]["source"], + "source_bytes": by_id[cid]["source_bytes"], + "source_sha256": by_id[cid]["source_sha256"], + } + for cid in sorted(by_id) + ] + params_payload = [ + {"case_id": cid, "params_digest": by_id[cid]["params_digest"]} + for cid in sorted(by_id) + ] + sources_digest = sha256_bytes(canonical_json(sources_payload)) + params_digest_all = sha256_bytes(canonical_json(params_payload)) + + manifest: dict[str, object] = { + "cases": ordered_cases, + "openpilot_sha": source_sha, + "opendbc_sha": opendbc_sha, + "params_digest": params_digest_all, + "previous_accepted_tag": previous_accepted_tag, + "refs": ordered_refs, + "schema_version": 1, + "sources_digest": sources_digest, + } + + # Fail closed: every case/ref identity still carries digests after assembly. + for cid, rec in by_id.items(): + require_digest(f"assembled case {cid} params_digest", rec["params_digest"]) + require_digest(f"assembled case {cid} source_sha256", rec["source_sha256"]) + for tid, entry in ordered_refs.items(): + require_digest(f"assembled ref {tid} sha256", entry["sha256"]) + require_digest(f"assembled ref {tid} params_digest", entry["params_digest"]) + require_digest(f"assembled ref {tid} source_sha256", entry["source_sha256"]) + require_digest("manifest sources_digest", sources_digest) + require_digest("manifest params_digest", params_digest_all) + + manifest_bytes = canonical_json(manifest) + (release / "manifest.json").write_bytes(manifest_bytes) + (release / "ref_commit").write_text(source_sha + "\n", encoding="utf-8") + + rel_files = sorted(p.name for p in release.iterdir() if p.is_file()) + zsts = [n for n in rel_files if n.endswith(".zst")] + if "ref_commit" not in rel_files or "manifest.json" not in rel_files: + die("release missing ref_commit or manifest.json") + if len(zsts) != EXPECTED_TASKS: + die("zst count self-check failed") + extras = [n for n in rel_files if n not in {"ref_commit", "manifest.json"} and not n.endswith(".zst")] + if extras: + die(f"unexpected release files: {extras}") + + # Independent rebuild check: re-canonicalize must be byte-identical. + rebuild = canonical_json(json.loads(manifest_bytes.decode("utf-8"))) + if rebuild != manifest_bytes: + die("manifest failed independent byte-identical rebuild check") + + manifest_sha = sha256_bytes(manifest_bytes) + print(f"assembled release/ inventory=active tasks={len(zsts)} cases={len(case_ids)}") + print(f"sha={source_sha} previous_accepted_tag={previous_accepted_tag}") + print(f"manifest_sha256={manifest_sha}") + print(f"sources_digest={sources_digest}") + print(f"params_digest={params_digest_all}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/clip/run.py b/tools/clip/run.py new file mode 100755 index 00000000000000..d3a0496b1e6e96 --- /dev/null +++ b/tools/clip/run.py @@ -0,0 +1,361 @@ +#!/usr/bin/env python3 +import os +import sys +import time +import logging +import subprocess +import threading +import queue +import multiprocessing +import itertools +import numpy as np +import tqdm +from argparse import ArgumentParser +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor, as_completed + +from openpilot.tools.lib.route import Route +from openpilot.tools.lib.logreader import LogReader +from openpilot.tools.lib.filereader import FileReader +from openpilot.tools.lib.framereader import FrameReader, ffprobe +from openpilot.selfdrive.test.process_replay.migration import migrate_all +from openpilot.common.prefix import OpenpilotPrefix +from openpilot.common.utils import Timer +from msgq.visionipc import VisionIpcServer, VisionStreamType + +FRAMERATE = 20 +DEMO_ROUTE, DEMO_START, DEMO_END = '5beb9b58bd12b691/0000010a--a51155e496', 90, 105 + +logger = logging.getLogger('clip') + + +def parse_args(): + parser = ArgumentParser(description="Direct clip renderer") + parser.add_argument("route", nargs="?", help="Route ID (dongle/route or dongle/route/start/end)") + parser.add_argument("-s", "--start", type=int, help="Start time in seconds") + parser.add_argument("-e", "--end", type=int, help="End time in seconds") + parser.add_argument("-o", "--output", default="output.mp4", help="Output file path") + parser.add_argument("-d", "--data-dir", help="Local directory with route data") + parser.add_argument("-t", "--title", help="Title overlay text") + parser.add_argument("-f", "--file-size", type=float, default=9.0, help="Target file size in MB") + parser.add_argument("-x", "--speed", type=int, default=1, help="Speed multiplier") + parser.add_argument("--demo", action="store_true", help="Use demo route with default timing") + parser.add_argument("--big", action="store_true", help="Use big UI (2160x1080)") + parser.add_argument("--qcam", action="store_true", help="Use qcamera instead of fcamera") + parser.add_argument("--windowed", action="store_true", help="Show window") + parser.add_argument("--no-metadata", action="store_true", help="Disable metadata overlay") + parser.add_argument("--no-time-overlay", action="store_true", help="Disable time overlay") + args = parser.parse_args() + + if args.demo: + args.route, args.start, args.end = args.route or DEMO_ROUTE, args.start or DEMO_START, args.end or DEMO_END + elif not args.route: + parser.error("route is required (or use --demo)") + + if args.route and args.route.count('/') == 3: + parts = args.route.split('/') + args.route, args.start, args.end = '/'.join(parts[:2]), args.start or int(parts[2]), args.end or int(parts[3]) + + if args.start is None or args.end is None: + parser.error("--start and --end are required") + if args.end <= args.start: + parser.error(f"end ({args.end}) must be greater than start ({args.start})") + return args + + +def setup_env(output_path: str, big: bool = False, speed: int = 1, target_mb: float = 0, duration: int = 0, headless: bool = True): + os.environ.update({"RECORD": "1", "RECORD_OUTPUT": str(Path(output_path).with_suffix(".mp4"))}) + if headless: + os.environ["OFFSCREEN"] = "1" + if speed > 1: + os.environ["RECORD_SPEED"] = str(speed) + if target_mb > 0 and duration > 0: + os.environ["RECORD_BITRATE"] = f"{int(target_mb * 8 * 1024 / (duration / speed))}k" + if big: + os.environ["BIG"] = "1" + + +def _download_segment(path: str) -> bytes: + with FileReader(path) as f: + return bytes(f.read()) + + +def _parse_and_chunk_segment(args: tuple) -> list[dict]: + raw_data, fps = args + from openpilot.tools.lib.logreader import _LogFileReader + messages = migrate_all(list(_LogFileReader("", dat=raw_data, sort_by_time=True))) + if not messages: + return [] + + dt_ns, chunks, current, next_time = 1e9 / fps, [], {}, messages[0].logMonoTime + 1e9 / fps + for msg in messages: + if msg.logMonoTime >= next_time: + chunks.append(current) + current, next_time = {}, next_time + dt_ns * ((msg.logMonoTime - next_time) // dt_ns + 1) + current[msg.which()] = msg + return chunks + [current] if current else chunks + + +def load_logs_parallel(log_paths: list[str], fps: int = 20) -> list[dict]: + num_workers = min(16, len(log_paths), (multiprocessing.cpu_count() or 1)) + logger.info(f"Downloading {len(log_paths)} segments with {num_workers} workers...") + + with ThreadPoolExecutor(max_workers=num_workers) as pool: + futures = {pool.submit(_download_segment, path): idx for idx, path in enumerate(log_paths)} + raw_data = {futures[f]: f.result() for f in as_completed(futures)} + + logger.info("Parsing and chunking segments...") + with multiprocessing.Pool(num_workers) as pool: + return list(itertools.chain.from_iterable(pool.map(_parse_and_chunk_segment, [(raw_data[i], fps) for i in range(len(log_paths))]))) + + +def patch_submaster(message_chunks, ui_state): + # Reset started_frame so alerts render correctly (recv_frame must be >= started_frame) + ui_state.started_frame = 0 + ui_state.started_time = time.monotonic() + + def mock_update(timeout=None): + sm, t = ui_state.sm, time.monotonic() + sm.updated = dict.fromkeys(sm.services, False) + if sm.frame < len(message_chunks): + for svc, msg in message_chunks[sm.frame].items(): + if svc in sm.data: + sm.seen[svc] = sm.updated[svc] = sm.alive[svc] = sm.valid[svc] = True + sm.data[svc] = getattr(msg.as_builder(), svc) + sm.logMonoTime[svc], sm.recv_time[svc], sm.recv_frame[svc] = msg.logMonoTime, t, sm.frame + sm.frame += 1 + ui_state.sm.update = mock_update + + +def get_frame_dimensions(camera_path: str) -> tuple[int, int]: + """Get frame dimensions from a video file using ffprobe.""" + probe = ffprobe(camera_path) + stream = probe["streams"][0] + return stream["width"], stream["height"] + + +def iter_segment_frames(camera_paths, start_time, end_time, fps=20, use_qcam=False, frame_size: tuple[int, int] | None = None): + frames_per_seg = fps * 60 + start_frame, end_frame = int(start_time * fps), int(end_time * fps) + current_seg: int = -1 + seg_frames: FrameReader | np.ndarray | None = None + + for global_idx in range(start_frame, end_frame): + seg_idx, local_idx = global_idx // frames_per_seg, global_idx % frames_per_seg + + if seg_idx != current_seg: + current_seg = seg_idx + path = camera_paths[seg_idx] if seg_idx < len(camera_paths) else None + if not path: + raise RuntimeError(f"No camera file for segment {seg_idx}") + + if use_qcam: + w, h = frame_size or get_frame_dimensions(path) + with FileReader(path) as f: + result = subprocess.run(["ffmpeg", "-v", "quiet", "-i", "-", "-f", "rawvideo", "-pix_fmt", "nv12", "-"], + input=f.read(), capture_output=True) + if result.returncode != 0: + raise RuntimeError(f"ffmpeg failed: {result.stderr.decode()}") + seg_frames = np.frombuffer(result.stdout, dtype=np.uint8).reshape(-1, w * h * 3 // 2) + else: + seg_frames = FrameReader(path, pix_fmt="nv12") + + assert seg_frames is not None + frame = seg_frames[local_idx] if use_qcam else seg_frames.get(local_idx) + yield global_idx, frame + + +class FrameQueue: + def __init__(self, camera_paths, start_time, end_time, fps=20, prefetch_count=60, use_qcam=False): + # Probe first valid camera file for dimensions + first_path = next((p for p in camera_paths if p), None) + if not first_path: + raise RuntimeError("No valid camera paths") + self.frame_w, self.frame_h = get_frame_dimensions(first_path) + + self._queue, self._stop, self._error = queue.Queue(maxsize=prefetch_count), threading.Event(), None + self._thread = threading.Thread(target=self._worker, + args=(camera_paths, start_time, end_time, fps, use_qcam, (self.frame_w, self.frame_h)), daemon=True) + self._thread.start() + + def _worker(self, camera_paths, start_time, end_time, fps, use_qcam, frame_size): + try: + for idx, data in iter_segment_frames(camera_paths, start_time, end_time, fps, use_qcam, frame_size): + if self._stop.is_set(): + break + self._queue.put((idx, data.tobytes())) + except Exception as e: + logger.exception("Decode error") + self._error = e + finally: + self._queue.put(None) + + def get(self, timeout=60.0): + if self._error: + raise self._error + result = self._queue.get(timeout=timeout) + if result is None: + raise StopIteration("No more frames") + return result + + def stop(self): + self._stop.set() + while not self._queue.empty(): + try: + self._queue.get_nowait() + except queue.Empty: + break + self._thread.join(timeout=2.0) + + +def load_route_metadata(route): + from openpilot.common.params import Params, UnknownKeyName + path = next((item for item in route.log_paths() if item), None) + if not path: + raise Exception('error getting route metadata: cannot find any uploaded logs') + lr = LogReader(path) + init_data, car_params = lr.first('initData'), lr.first('carParams') + + params = Params() + for entry in init_data.params.entries: + try: + params.put(entry.key, params.cpp2python(entry.key, entry.value), block=True) + except UnknownKeyName: + pass + + origin = init_data.gitRemote.split('/')[3] if len(init_data.gitRemote.split('/')) > 3 else 'unknown' + return { + 'version': init_data.version, 'route': route.name.canonical_name, + 'car': car_params.carFingerprint if car_params else 'unknown', 'origin': origin, + 'branch': init_data.gitBranch, 'commit': init_data.gitCommit[:7], 'modified': str(init_data.dirty).lower(), + } + + +def draw_text_box(text, x, y, size, gui_app, font, color=None, center=False): + import pyray as rl + from openpilot.system.ui.lib.text_measure import measure_text_cached + box_color, text_color = rl.Color(0, 0, 0, 85), color or rl.WHITE + text_size = measure_text_cached(font, text, size) + text_width, text_height = int(text_size.x), int(text_size.y) + if center: + x = (gui_app.width - text_width) // 2 + rl.draw_rectangle(x - 8, y - 4, text_width + 16, text_height + 8, box_color) + rl.draw_text_ex(font, text, rl.Vector2(x, y), size, 0, text_color) + + +def render_overlays(gui_app, font, big, metadata, title, start_time, frame_idx, show_metadata, show_time): + from openpilot.system.ui.lib.text_measure import measure_text_cached + from openpilot.system.ui.lib.wrap_text import wrap_text + metadata_size = 16 if big else 12 + title_size = 32 if big else 24 + time_size = 24 if big else 16 + + # Time overlay + time_width = 0 + if show_time: + t = start_time + frame_idx / FRAMERATE + time_text = f"{int(t) // 60:02d}:{int(t) % 60:02d}" + time_width = int(measure_text_cached(font, time_text, time_size).x) + draw_text_box(time_text, gui_app.width - time_width - 5, 0, time_size, gui_app, font) + + # Metadata overlay (first 5 seconds) + if show_metadata and metadata and frame_idx < FRAMERATE * 5: + m = metadata + text = ", ".join([f"openpilot v{m['version']}", f"route: {m['route']}", f"car: {m['car']}", f"origin: {m['origin']}", + f"branch: {m['branch']}", f"commit: {m['commit']}", f"modified: {m['modified']}"]) + # Wrap text if too wide (leave margin on each side) + margin = 2 * (time_width + 10 if show_time else 20) # leave enough margin for time overlay + max_width = gui_app.width - margin + lines = wrap_text(font, text, metadata_size, max_width) + + # Draw wrapped metadata text + y_offset = 6 + for line in lines: + draw_text_box(line, 0, y_offset, metadata_size, gui_app, font, center=True) + line_height = int(measure_text_cached(font, line, metadata_size).y) + 4 + y_offset += line_height + + # Title overlay + if title: + draw_text_box(title, 0, 60, title_size, gui_app, font, center=True) + + +def clip(route: Route, output: str, start: int, end: int, headless: bool = True, big: bool = False, + title: str | None = None, show_metadata: bool = True, show_time: bool = True, use_qcam: bool = False): + timer, duration = Timer(), end - start + + import pyray as rl + if big: + from openpilot.selfdrive.ui.onroad.augmented_road_view import AugmentedRoadView + else: + from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import AugmentedRoadView + from openpilot.selfdrive.ui.ui_state import ui_state + from openpilot.system.ui.lib.application import gui_app, FontWeight + timer.lap("import") + + logger.info(f"Clipping {route.name.canonical_name}, {start}s-{end}s ({duration}s)") + seg_start, seg_end = start // 60, (end - 1) // 60 + 1 + all_chunks = load_logs_parallel(route.log_paths()[seg_start:seg_end], fps=FRAMERATE) + timer.lap("logs") + + frame_start = (start - seg_start * 60) * FRAMERATE + message_chunks = all_chunks[frame_start:frame_start + duration * FRAMERATE] + if not message_chunks: + logger.error("No messages to render") + sys.exit(1) + + if headless: + rl.set_config_flags(rl.ConfigFlags.FLAG_WINDOW_HIDDEN) + + with OpenpilotPrefix(shared_download_cache=True): + metadata = load_route_metadata(route) if show_metadata else None + camera_paths = route.qcamera_paths() if use_qcam else route.camera_paths() + frame_queue = FrameQueue(camera_paths, start, end, fps=FRAMERATE, use_qcam=use_qcam) + + vipc = VisionIpcServer("camerad") + vipc.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 4, frame_queue.frame_w, frame_queue.frame_h) + vipc.start_listener() + + patch_submaster(message_chunks, ui_state) + gui_app.init_window("clip", fps=FRAMERATE) + + road_view = AugmentedRoadView() + road_view.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + font = gui_app.font(FontWeight.NORMAL) + timer.lap("setup") + + frame_idx = 0 + with tqdm.tqdm(total=len(message_chunks), desc="Rendering", unit="frame") as pbar: + for should_render, _, _ in gui_app.render(): + if frame_idx >= len(message_chunks): + break + _, frame_bytes = frame_queue.get() + vipc.send(VisionStreamType.VISION_STREAM_ROAD, frame_bytes, frame_idx, int(frame_idx * 5e7), int(frame_idx * 5e7)) + ui_state.update() + if should_render: + road_view.render() + render_overlays(gui_app, font, big, metadata, title, start, frame_idx, show_metadata, show_time) + frame_idx += 1 + pbar.update(1) + timer.lap("render") + + frame_queue.stop() + gui_app.close() + timer.lap("ffmpeg") + + logger.info(f"Clip saved to: {Path(output).resolve()}") + logger.info(f"Generated {timer.fmt(duration)}") + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s\t%(message)s") + args = parse_args() + + headless = not args.windowed + setup_env(args.output, big=args.big, speed=args.speed, target_mb=args.file_size, duration=args.end - args.start, headless=headless) + clip(Route(args.route, data_dir=args.data_dir), args.output, args.start, args.end, headless, + args.big, args.title, not args.no_metadata, not args.no_time_overlay, args.qcam) + + +if __name__ == "__main__": + main() diff --git a/tools/install_python_dependencies.sh b/tools/install_python_dependencies.sh deleted file mode 100755 index 8621ee0b004c2d..00000000000000 --- a/tools/install_python_dependencies.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env bash -set -e - -# Increase the pip timeout to handle TimeoutError -export PIP_DEFAULT_TIMEOUT=200 - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -ROOT=$DIR/../ -cd $ROOT - -# updating uv on macOS results in 403 sometimes -function update_uv() { - for i in $(seq 1 5); - do - if uv self update; then - return 0 - else - sleep 2 - fi - done - echo "Failed to update uv 5 times!" -} - -if ! command -v "uv" > /dev/null 2>&1; then - echo "installing uv..." - curl -LsSf https://astral.sh/uv/install.sh | sh - UV_BIN='$HOME/.cargo/env' - ADD_PATH_CMD=". \"$UV_BIN\"" - eval $ADD_PATH_CMD -fi - -echo "updating uv..." -update_uv - -echo "installing python packages..." -uv sync --frozen --all-extras -source .venv/bin/activate - -echo "PYTHONPATH=${PWD}" > $ROOT/.env -if [[ "$(uname)" == 'Darwin' ]]; then - echo "# msgq doesn't work on mac" >> $ROOT/.env - echo "export ZMQ=1" >> $ROOT/.env - echo "export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES" >> $ROOT/.env -fi diff --git a/tools/install_ubuntu_dependencies.sh b/tools/install_ubuntu_dependencies.sh deleted file mode 100755 index be5c479c366c32..00000000000000 --- a/tools/install_ubuntu_dependencies.sh +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env bash -set -e - -SUDO="" - -# Use sudo if not root -if [[ ! $(id -u) -eq 0 ]]; then - if [[ -z $(which sudo) ]]; then - echo "Please install sudo or run as root" - exit 1 - fi - SUDO="sudo" -fi - -# Check if stdin is open -if [ -t 0 ]; then - INTERACTIVE=1 -fi - -# Install common packages -function install_ubuntu_common_requirements() { - $SUDO apt-get update - $SUDO apt-get install -y --no-install-recommends \ - ca-certificates \ - clang \ - cppcheck \ - build-essential \ - gcc-arm-none-eabi \ - liblzma-dev \ - capnproto \ - libcapnp-dev \ - curl \ - libcurl4-openssl-dev \ - git \ - git-lfs \ - ffmpeg \ - libavformat-dev \ - libavcodec-dev \ - libavdevice-dev \ - libavutil-dev \ - libavfilter-dev \ - libbz2-dev \ - libeigen3-dev \ - libffi-dev \ - libglew-dev \ - libgles2-mesa-dev \ - libglfw3-dev \ - libglib2.0-0 \ - libqt5charts5-dev \ - libncurses5-dev \ - libssl-dev \ - libusb-1.0-0-dev \ - libzmq3-dev \ - libzstd-dev \ - libsqlite3-dev \ - libsystemd-dev \ - locales \ - opencl-headers \ - ocl-icd-libopencl1 \ - ocl-icd-opencl-dev \ - portaudio19-dev \ - qttools5-dev-tools \ - libqt5svg5-dev \ - libqt5serialbus5-dev \ - libqt5x11extras5-dev \ - libqt5opengl5-dev -} - -# Install Ubuntu 24.04 LTS packages -function install_ubuntu_lts_latest_requirements() { - install_ubuntu_common_requirements - - $SUDO apt-get install -y --no-install-recommends \ - g++-12 \ - qtbase5-dev \ - qtchooser \ - qt5-qmake \ - qtbase5-dev-tools \ - python3-dev \ - python3-venv -} - -# Install Ubuntu 20.04 packages -function install_ubuntu_focal_requirements() { - install_ubuntu_common_requirements - - $SUDO apt-get install -y --no-install-recommends \ - libavresample-dev \ - qt5-default \ - python-dev -} - -# Detect OS using /etc/os-release file -if [ -f "/etc/os-release" ]; then - source /etc/os-release - case "$VERSION_CODENAME" in - "jammy" | "kinetic" | "noble") - install_ubuntu_lts_latest_requirements - ;; - "focal") - install_ubuntu_focal_requirements - ;; - *) - echo "$ID $VERSION_ID is unsupported. This setup script is written for Ubuntu 20.04." - read -p "Would you like to attempt installation anyway? " -n 1 -r - echo "" - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - exit 1 - fi - if [ "$UBUNTU_CODENAME" = "focal" ]; then - install_ubuntu_focal_requirements - else - install_ubuntu_lts_latest_requirements - fi - esac - - if [[ -d "/etc/udev/rules.d/" ]]; then - # Setup panda udev rules - $SUDO tee /etc/udev/rules.d/12-panda_jungle.rules > /dev/null < /dev/null <", + "#include ", + "", + "inline constexpr std::pair kCarFingerprintToDbc[] = {", + ] + lines.extend(f' {{"{fingerprint}", "{dbc}"}},' for fingerprint, dbc in sorted(pairs.items())) + lines.extend([ + "};", + "", + "inline std::string_view dbc_for_car_fingerprint(std::string_view fingerprint) {", + " for (const auto &[car_fingerprint, dbc] : kCarFingerprintToDbc) {", + " if (car_fingerprint == fingerprint) return dbc;", + " }", + " return {};", + "}", + "", + ]) + + with open(str(target[0]), "w") as f: + f.write("\n".join(lines)) + + return None + +def generate_event_extractors(target, source, env): + subprocess.check_call([ + "python3", + "tools/jotpluggler/generate_event_extractors.py", + os.path.realpath(BASEDIR), + str(target[0]), + ]) + return None + +generated_dbc_stamp = jot_env.Command(f"generated_dbcs/.stamp", [], materialize_generated_dbcs) +car_fingerprint_to_dbc = jot_env.Command("car_fingerprint_to_dbc.h", [], write_car_fingerprint_to_dbc_header) +event_extractors = jot_env.Command("generated_event_extractors.h", [ + "generate_event_extractors.py", + jot_env.Glob("#cereal/*.capnp"), + jot_env.Glob("#cereal/include/*.capnp"), + ], + generate_event_extractors, +) + +libs = [replay_lib, common, messaging, visionipc, cereal, File(f"{imgui.LIB_DIR}/libimgui.a"), File(f"{imgui.LIB_DIR}/libglfw3.a"), + "avformat", "avcodec", "avutil", "x264", "yuv", "z", "bz2", "zstd", "m", "pthread", "usb-1.0"] +if arch == "Darwin": + jot_env["FRAMEWORKS"] = ["OpenGL", "Cocoa", "IOKit", "CoreFoundation", "CoreVideo", "CoreMedia", "VideoToolbox"] +else: + libs += ["GL", "dl", "va", "va-drm", "drm"] + +program = jot_env.Program("jotpluggler", jot_env.Glob("*.cc"), LIBS=libs) +jot_env.Depends(program, generated_dbc_stamp) +jot_env.Depends(program, car_fingerprint_to_dbc) +jot_env.Depends(program, event_extractors) diff --git a/tools/jotpluggler/app.cc b/tools/jotpluggler/app.cc new file mode 100644 index 00000000000000..22a9f9021c0081 --- /dev/null +++ b/tools/jotpluggler/app.cc @@ -0,0 +1,1900 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/camera.h" +#include "tools/jotpluggler/common.h" +#include "tools/jotpluggler/internal.h" +#include "tools/jotpluggler/map.h" +#include "system/hardware/hw.h" +#include "imgui_impl_glfw.h" + +#include "imgui_internal.h" +#include "imgui_impl_opengl3.h" +#include "imgui_impl_opengl3_loader.h" +#include "implot.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "json11/json11.hpp" + +namespace fs = std::filesystem; + +constexpr const char *UNTITLED_PANE_TITLE = "..."; +ImFont *g_ui_font = nullptr; +ImFont *g_ui_bold_font = nullptr; +ImFont *g_mono_font = nullptr; + +std::string layout_name_from_arg(const std::string &layout_arg) { + const fs::path raw(layout_arg); + if (raw.extension() == ".xml" || raw.extension() == ".json") { + return raw.stem().string(); + } + if (raw.filename() != raw) { + return raw.filename().replace_extension("").string(); + } + fs::path stem_path = raw; + return stem_path.replace_extension("").string(); +} + +fs::path layouts_dir() { + return repo_root() / "tools" / "jotpluggler" / "layouts"; +} + +std::string sanitize_layout_stem(std::string_view name) { + std::string out; + out.reserve(name.size()); + bool last_was_dash = false; + for (const char raw : name) { + const unsigned char c = static_cast(raw); + if (std::isalnum(c) != 0) { + out.push_back(static_cast(std::tolower(c))); + last_was_dash = false; + } else if (raw == '-' || raw == '_') { + out.push_back(raw); + last_was_dash = false; + } else if (!last_was_dash && !out.empty()) { + out.push_back('-'); + last_was_dash = true; + } + } + while (!out.empty() && out.back() == '-') { + out.pop_back(); + } + return out.empty() ? "untitled" : out; +} + +fs::path autosave_dir() { + return layouts_dir() / ".jotpluggler_autosave"; +} + +fs::path resolve_layout_path(const std::string &layout_arg) { + const fs::path direct(layout_arg); + if (fs::exists(direct)) { + if (direct.extension() == ".json") return fs::absolute(direct); + const fs::path sibling_json = direct.parent_path() / (direct.stem().string() + ".json"); + if (direct.extension() == ".xml" && fs::exists(sibling_json)) { + return fs::absolute(sibling_json); + } + } + const fs::path candidate = layouts_dir() / (layout_name_from_arg(layout_arg) + ".json"); + if (!fs::exists(candidate)) throw std::runtime_error("Unknown layout: " + layout_arg); + return candidate; +} + +fs::path autosave_path_for_layout(const fs::path &layout_path) { + const std::string stem = layout_path.empty() ? "untitled" : layout_path.stem().string(); + return autosave_dir() / (sanitize_layout_stem(stem) + ".json"); +} + +std::vector available_layout_names() { + std::vector names; + const fs::path root = layouts_dir(); + if (!fs::exists(root) || !fs::is_directory(root)) { + return names; + } + for (const auto &entry : fs::directory_iterator(root)) { + if (!entry.is_regular_file() || entry.path().extension() != ".json") { + continue; + } + names.push_back(entry.path().stem().string()); + } + std::sort(names.begin(), names.end()); + return names; +} + +void refresh_replaced_layout_ui(AppSession *session, UiState *state, bool mark_docks) { + state->tabs.clear(); + cancel_rename_tab(state); + sync_ui_state(state, session->layout); + sync_layout_buffers(state, *session); + if (mark_docks) { + mark_all_docks_dirty(state); + } +} + +void start_new_layout(AppSession *session, UiState *state, const std::string &status_text) { + session->layout = make_empty_layout(); + session->layout_path.clear(); + session->autosave_path.clear(); + state->undo.reset(session->layout); + state->layout_dirty = false; + state->status_text = status_text; + refresh_replaced_layout_ui(session, state, true); + reset_shared_range(state, *session); +} + +bool is_decoded_can_series_path(std::string_view path) { + const std::string value(path); + return util::starts_with(value, "/can/") || util::starts_with(value, "/sendcan/"); +} + +bool apply_route_can_decode_update(AppSession *session, UiState *state); + +void rebuild_series_lookup_preserving_formats(AppSession *session, + std::string_view updated_prefix, + bool refresh_updated_formats_only) { + const std::string prefix(updated_prefix); + if (!updated_prefix.empty()) { + for (auto it = session->route_data.series_formats.begin(); it != session->route_data.series_formats.end();) { + if (util::starts_with(it->first, prefix)) { + it = session->route_data.series_formats.erase(it); + } else { + ++it; + } + } + } + session->series_by_path.clear(); + session->series_by_path.reserve(session->route_data.series.size()); + for (RouteSeries &series : session->route_data.series) { + session->series_by_path.emplace(series.path, &series); + if (refresh_updated_formats_only) { + if (!updated_prefix.empty() && util::starts_with(series.path, prefix)) { + const bool enum_like = session->route_data.enum_info.find(series.path) != session->route_data.enum_info.end(); + session->route_data.series_formats[series.path] = compute_series_format(series.values, enum_like); + } + } else { + const bool enum_like = session->route_data.enum_info.find(series.path) != session->route_data.enum_info.end(); + session->route_data.series_formats[series.path] = compute_series_format(series.values, enum_like); + } + } +} + +bool apply_route_can_decode_update(AppSession *session, UiState *state) { + const std::string active_dbc_name = !session->dbc_override.empty() ? session->dbc_override : session->route_data.dbc_name; + if (!active_dbc_name.empty() && !load_dbc_by_name(active_dbc_name).has_value()) { + state->error_text = "DBC not found: " + active_dbc_name; + state->open_error_popup = true; + return false; + } + std::unordered_map can_enum_info; + std::vector can_series = decode_can_messages(session->route_data.can_messages, active_dbc_name, &can_enum_info); + + std::vector updated_series; + updated_series.reserve(session->route_data.series.size() + can_series.size()); + for (RouteSeries &series : session->route_data.series) { + if (!is_decoded_can_series_path(series.path)) { + updated_series.push_back(std::move(series)); + } + } + for (RouteSeries &series : can_series) { + updated_series.push_back(std::move(series)); + } + std::sort(updated_series.begin(), updated_series.end(), [](const RouteSeries &a, const RouteSeries &b) { + return a.path < b.path; + }); + + std::unordered_map updated_enum_info; + updated_enum_info.reserve(session->route_data.enum_info.size() + can_enum_info.size()); + for (auto &[path, info] : session->route_data.enum_info) { + if (!is_decoded_can_series_path(path)) { + updated_enum_info.emplace(path, std::move(info)); + } + } + for (auto &[path, info] : can_enum_info) { + updated_enum_info[path] = std::move(info); + } + + session->route_data.series = std::move(updated_series); + session->route_data.enum_info = std::move(updated_enum_info); + session->route_data.paths.clear(); + session->route_data.paths.reserve(session->route_data.series.size()); + for (const RouteSeries &series : session->route_data.series) { + session->route_data.paths.push_back(series.path); + } + std::sort(session->route_data.paths.begin(), session->route_data.paths.end()); + session->route_data.roots = collect_route_roots_for_paths(session->route_data.paths); + + rebuild_route_index(session); + rebuild_browser_nodes(session, state); + refresh_all_custom_curves(session, state); + sync_camera_feeds(session); + return true; +} + +void apply_dbc_override_change(AppSession *session, UiState *state, const std::string &dbc_override) { + session->dbc_override = dbc_override; + if (session->data_mode == SessionDataMode::Stream) { + start_stream_session(session, state, session->stream_source, session->stream_buffer_seconds, false); + } else if (!session->route_name.empty()) { + const bool ok = apply_route_can_decode_update(session, state); + if (ok) { + state->status_text = dbc_override.empty() ? "DBC auto-detect enabled" : "DBC set to " + dbc_override; + } else { + state->status_text = "Failed to apply DBC"; + } + } else if (dbc_override.empty()) { + state->status_text = "DBC auto-detect enabled"; + } else { + state->status_text = "DBC set to " + dbc_override; + } +} + +void configure_style() { + ImGui::StyleColorsLight(); + ImPlot::StyleColorsLight(); + + ImGuiIO &io = ImGui::GetIO(); + g_ui_font = nullptr; + g_ui_bold_font = nullptr; + g_mono_font = nullptr; + const fs::path fonts_dir = repo_root() / "selfdrive" / "assets" / "fonts"; + ImFontConfig font_cfg; + font_cfg.OversampleH = 2; + font_cfg.OversampleV = 2; + font_cfg.RasterizerDensity = 1.0f; + icon_add_font(16.0f); + const auto add_font_with_icons = [&](const fs::path &path, float size) -> ImFont * { + ImFont *font = io.Fonts->AddFontFromFileTTF(path.c_str(), size, &font_cfg); + if (font != nullptr) { + icon_add_font(size, true, font); + } + return font; + }; + if (ImFont *font = add_font_with_icons(fonts_dir / "Inter-Regular.ttf", 16.0f); font != nullptr) { + g_ui_font = font; + io.FontDefault = font; + } + g_ui_bold_font = add_font_with_icons(fonts_dir / "Inter-SemiBold.ttf", 16.75f); + if (g_ui_font == nullptr) { + if (ImFont *font = add_font_with_icons(fonts_dir / "JetBrainsMono-Medium.ttf", 15.75f); font != nullptr) { + g_mono_font = font; + io.FontDefault = font; + } + } + if (g_mono_font == nullptr) { + g_mono_font = add_font_with_icons(fonts_dir / "JetBrainsMono-Medium.ttf", 15.75f); + } + if (g_ui_bold_font == nullptr) { + g_ui_bold_font = g_ui_font; + } + + ImGuiStyle &style = ImGui::GetStyle(); + style.WindowRounding = 0.0f; + style.ChildRounding = 0.0f; + style.PopupRounding = 0.0f; + style.FrameRounding = 2.0f; + style.ScrollbarRounding = 2.0f; + style.GrabRounding = 2.0f; + style.TabRounding = 0.0f; + style.WindowBorderSize = 1.0f; + style.ChildBorderSize = 1.0f; + style.FrameBorderSize = 1.0f; + style.WindowPadding = ImVec2(8.0f, 7.0f); + style.FramePadding = ImVec2(6.0f, 3.0f); + style.ItemSpacing = ImVec2(8.0f, 5.0f); + style.ItemInnerSpacing = ImVec2(6.0f, 3.0f); + struct ColorDef { ImGuiCol idx; int r, g, b; }; + constexpr ColorDef COLORS[] = { + {ImGuiCol_WindowBg, 250, 250, 251}, {ImGuiCol_ChildBg, 255, 255, 255}, + {ImGuiCol_Border, 194, 198, 204}, {ImGuiCol_TitleBg, 252, 252, 253}, + {ImGuiCol_TitleBgActive, 252, 252, 253}, {ImGuiCol_TitleBgCollapsed, 252, 252, 253}, + {ImGuiCol_Text, 74, 80, 88}, {ImGuiCol_TextDisabled, 108, 118, 128}, + {ImGuiCol_Button, 255, 255, 255}, {ImGuiCol_ButtonHovered, 246, 248, 250}, + {ImGuiCol_ButtonActive, 238, 240, 244}, {ImGuiCol_FrameBg, 255, 255, 255}, + {ImGuiCol_FrameBgHovered, 248, 249, 251}, {ImGuiCol_FrameBgActive, 241, 244, 248}, + {ImGuiCol_Header, 243, 245, 248}, {ImGuiCol_HeaderHovered, 237, 240, 244}, + {ImGuiCol_HeaderActive, 232, 236, 240}, {ImGuiCol_PopupBg, 248, 249, 251}, + {ImGuiCol_MenuBarBg, 232, 236, 241}, {ImGuiCol_Separator, 194, 198, 204}, + {ImGuiCol_ScrollbarBg, 240, 242, 245}, {ImGuiCol_ScrollbarGrab, 202, 207, 214}, + {ImGuiCol_ScrollbarGrabHovered, 180, 186, 194}, {ImGuiCol_ScrollbarGrabActive, 164, 171, 180}, + {ImGuiCol_Tab, 219, 224, 230}, {ImGuiCol_TabHovered, 232, 236, 241}, + {ImGuiCol_TabSelected, 250, 251, 253}, {ImGuiCol_TabSelectedOverline, 92, 109, 136}, + {ImGuiCol_TabDimmed, 213, 219, 226}, {ImGuiCol_TabDimmedSelected, 244, 247, 249}, + {ImGuiCol_TabDimmedSelectedOverline, 92, 109, 136}, {ImGuiCol_DockingEmptyBg, 244, 246, 248}, + }; + for (const auto &c : COLORS) { style.Colors[c.idx] = color_rgb(c.r, c.g, c.b); } + style.Colors[ImGuiCol_DockingPreview] = color_rgb(69, 115, 184, 0.22f); + + ImPlotStyle &plot_style = ImPlot::GetStyle(); + plot_style.PlotBorderSize = 1.0f; + plot_style.MinorAlpha = 0.65f; + plot_style.LegendPadding = ImVec2(6.0f, 5.0f); + plot_style.LegendInnerPadding = ImVec2(6.0f, 3.0f); + plot_style.LegendSpacing = ImVec2(7.0f, 2.0f); + plot_style.PlotPadding = ImVec2(4.0f, 8.0f); + plot_style.FitPadding = ImVec2(0.02f, static_cast(PLOT_Y_PADDING_FRACTION)); + + ImPlot::MapInputDefault(); + ImPlotInputMap &input_map = ImPlot::GetInputMap(); + input_map.Pan = ImGuiMouseButton_Right; + input_map.PanMod = ImGuiMod_None; + input_map.Select = ImGuiMouseButton_Left; + input_map.SelectCancel = ImGuiMouseButton_Right; + input_map.SelectMod = ImGuiMod_None; +} + +void app_push_mono_font() { + if (g_mono_font != nullptr) { + ImGui::PushFont(g_mono_font); + } +} + +void app_pop_mono_font() { + if (g_mono_font != nullptr) { + ImGui::PopFont(); + } +} + +void app_push_bold_font() { + if (g_ui_bold_font != nullptr) { + ImGui::PushFont(g_ui_bold_font); + } +} + +void app_pop_bold_font() { + if (g_ui_bold_font != nullptr) { + ImGui::PopFont(); + } +} + +UiMetrics compute_ui_metrics(const ImVec2 &size, float top_offset, float sidebar_width) { + UiMetrics ui; + ui.width = size.x; + ui.height = size.y; + ui.top_offset = top_offset; + ui.sidebar_width = sidebar_width <= 0.0f + ? 0.0f + : std::clamp(sidebar_width, SIDEBAR_MIN_WIDTH, std::min(SIDEBAR_MAX_WIDTH, size.x * 0.6f)); + ui.content_x = ui.sidebar_width; + ui.content_y = top_offset; + ui.content_w = std::max(1.0f, size.x - ui.content_x); + ui.content_h = std::max(1.0f, size.y - ui.content_y - STATUS_BAR_HEIGHT); + ui.status_bar_y = std::max(0.0f, size.y - STATUS_BAR_HEIGHT); + return ui; +} + +void sync_ui_state(UiState *state, const SketchLayout &layout) { + const bool initializing = state->tabs.empty(); + state->tabs.resize(layout.tabs.size()); + if (layout.tabs.empty()) { + state->active_tab_index = 0; + state->requested_tab_index = -1; + return; + } + if (initializing) { + state->active_tab_index = std::clamp(layout.current_tab_index, 0, static_cast(layout.tabs.size()) - 1); + state->requested_tab_index = state->active_tab_index; + } + state->active_tab_index = std::clamp(state->active_tab_index, 0, static_cast(layout.tabs.size()) - 1); + for (size_t i = 0; i < layout.tabs.size(); ++i) { + if (state->tabs[i].runtime_id == 0) { + state->tabs[i].runtime_id = state->next_tab_runtime_id++; + } + const int pane_count = static_cast(layout.tabs[i].panes.size()); + state->tabs[i].map_panes.resize(static_cast(std::max(0, pane_count))); + state->tabs[i].camera_panes.resize(static_cast(std::max(0, pane_count))); + state->tabs[i].active_pane_index = pane_count <= 0 + ? 0 + : std::clamp(state->tabs[i].active_pane_index, 0, pane_count - 1); + } +} + +void resize_tab_pane_state(TabUiState *tab_state, size_t pane_count) { + if (tab_state == nullptr) return; + tab_state->map_panes.resize(pane_count); + tab_state->camera_panes.resize(pane_count); +} + +void sync_route_buffers(UiState *state, const AppSession &session) { + state->route_buffer = session.route_name; + state->data_dir_buffer = session.data_dir; +} + +void sync_stream_buffers(UiState *state, const AppSession &session) { + state->stream_address_buffer = session.stream_source.address; + state->stream_source_kind = session.stream_source.kind; + state->stream_buffer_seconds = session.stream_buffer_seconds; +} + +fs::path default_layout_save_path(const AppSession &session) { + return session.layout_path.empty() ? layouts_dir() / "new-layout.json" : session.layout_path; +} + +void sync_layout_buffers(UiState *state, const AppSession &session) { + state->load_layout_buffer = session.layout_path.empty() ? std::string() : session.layout_path.string(); + state->save_layout_buffer = default_layout_save_path(session).string(); +} + +const WorkspaceTab *app_active_tab(const SketchLayout &layout, const UiState &state) { + if (layout.tabs.empty()) return nullptr; + const int index = std::clamp(state.active_tab_index, 0, static_cast(layout.tabs.size()) - 1); + return &layout.tabs[static_cast(index)]; +} + +WorkspaceTab *app_active_tab(SketchLayout *layout, const UiState &state) { + if (layout->tabs.empty()) return nullptr; + const int index = std::clamp(state.active_tab_index, 0, static_cast(layout->tabs.size()) - 1); + return &layout->tabs[static_cast(index)]; +} + +TabUiState *app_active_tab_state(UiState *state) { + if (state->tabs.empty()) return nullptr; + const int index = std::clamp(state->active_tab_index, 0, static_cast(state->tabs.size()) - 1); + return &state->tabs[static_cast(index)]; +} + +std::string pane_window_name(int tab_runtime_id, int pane_index, const Pane &pane) { + const char *title = pane.title.empty() ? UNTITLED_PANE_TITLE : pane.title.c_str(); + return util::string_format("%s###tab%d_pane%d", title, tab_runtime_id, pane_index); +} + +std::string tab_item_label(const WorkspaceTab &tab, int tab_runtime_id) { + return util::string_format("%s##workspace_tab_%d", tab.tab_name.c_str(), tab_runtime_id); +} + +void request_tab_selection(UiState *state, int tab_index) { + state->active_tab_index = tab_index; + state->requested_tab_index = tab_index; +} + +void begin_rename_tab(const SketchLayout &layout, UiState *state, int tab_index) { + if (tab_index < 0 || tab_index >= static_cast(layout.tabs.size())) { + return; + } + state->rename_tab_buffer = layout.tabs[static_cast(tab_index)].tab_name; + state->rename_tab_index = tab_index; + state->focus_rename_tab_input = true; + request_tab_selection(state, tab_index); +} + +void cancel_rename_tab(UiState *state) { + state->rename_tab_index = -1; + state->focus_rename_tab_input = false; +} + +ImGuiID dockspace_id_for_tab(int tab_runtime_id) { + return ImHashStr(util::string_format("jotpluggler_dockspace_%d", tab_runtime_id).c_str()); +} + +bool curve_has_local_samples(const Curve &curve) { + return curve.xs.size() > 1 && curve.xs.size() == curve.ys.size(); +} + +void mark_all_docks_dirty(UiState *state) { + for (TabUiState &tab_state : state->tabs) { + tab_state.dock_needs_build = true; + } +} + +void mark_tab_dock_dirty(UiState *state, int tab_index) { + if (tab_index >= 0 && tab_index < static_cast(state->tabs.size())) { + state->tabs[static_cast(tab_index)].dock_needs_build = true; + } +} + +void normalize_split_node(WorkspaceNode *node) { + if (node->is_pane) { + return; + } + for (WorkspaceNode &child : node->children) { + normalize_split_node(&child); + } + if (node->children.empty()) { + return; + } + if (node->children.size() == 1) { + *node = node->children.front(); + return; + } + if (node->sizes.size() != node->children.size()) { + node->sizes.assign(node->children.size(), 1.0f / static_cast(node->children.size())); + return; + } + float total = 0.0f; + for (float &size : node->sizes) { + size = std::max(size, 0.0f); + total += size; + } + if (total <= 0.0f) { + node->sizes.assign(node->children.size(), 1.0f / static_cast(node->children.size())); + return; + } + for (float &size : node->sizes) { + size /= total; + } +} + +void decrement_pane_indices(WorkspaceNode *node, int removed_index) { + if (node->is_pane) { + if (node->pane_index > removed_index) { + node->pane_index -= 1; + } + return; + } + for (WorkspaceNode &child : node->children) { + decrement_pane_indices(&child, removed_index); + } +} + +bool remove_pane_node(WorkspaceNode *node, int pane_index) { + if (node->is_pane) return node->pane_index == pane_index; + + for (size_t i = 0; i < node->children.size();) { + if (remove_pane_node(&node->children[i], pane_index)) { + node->children.erase(node->children.begin() + static_cast(i)); + if (i < node->sizes.size()) { + node->sizes.erase(node->sizes.begin() + static_cast(i)); + } + } else { + ++i; + } + } + + normalize_split_node(node); + return !node->is_pane && node->children.empty(); +} + +bool split_pane_node(WorkspaceNode *node, int target_pane_index, SplitOrientation orientation, + bool new_before, int new_pane_index) { + if (node->is_pane) { + if (node->pane_index != target_pane_index) return false; + WorkspaceNode existing_pane; + existing_pane.is_pane = true; + existing_pane.pane_index = target_pane_index; + + WorkspaceNode new_pane; + new_pane.is_pane = true; + new_pane.pane_index = new_pane_index; + + node->is_pane = false; + node->pane_index = -1; + node->orientation = orientation; + node->sizes = {0.5f, 0.5f}; + node->children.clear(); + if (new_before) { + node->children.push_back(std::move(new_pane)); + node->children.push_back(std::move(existing_pane)); + } else { + node->children.push_back(std::move(existing_pane)); + node->children.push_back(std::move(new_pane)); + } + return true; + } + + if (node->orientation == orientation) { + for (size_t i = 0; i < node->children.size(); ++i) { + WorkspaceNode &child = node->children[i]; + if (!child.is_pane || child.pane_index != target_pane_index) { + continue; + } + + WorkspaceNode new_pane; + new_pane.is_pane = true; + new_pane.pane_index = new_pane_index; + + const auto insert_it = node->children.begin() + static_cast(new_before ? i : i + 1); + node->children.insert(insert_it, std::move(new_pane)); + node->sizes.assign(node->children.size(), 1.0f / static_cast(node->children.size())); + return true; + } + } + + for (WorkspaceNode &child : node->children) { + if (split_pane_node(&child, target_pane_index, orientation, new_before, new_pane_index)) return true; + } + return false; +} + +Pane make_empty_pane(const std::string &title = UNTITLED_PANE_TITLE) { + Pane pane; + pane.title = title; + return pane; +} + +WorkspaceTab make_empty_tab(const std::string &tab_name) { + WorkspaceTab tab; + tab.tab_name = tab_name; + tab.panes.push_back(make_empty_pane()); + tab.root.is_pane = true; + tab.root.pane_index = 0; + return tab; +} + +SketchLayout make_empty_layout() { + SketchLayout layout; + layout.tabs.push_back(make_empty_tab("tab1")); + layout.current_tab_index = 0; + layout.roots.push_back("layout"); + return layout; +} + +bool tab_name_exists(const SketchLayout &layout, const std::string &name) { + return std::any_of(layout.tabs.begin(), layout.tabs.end(), [&](const WorkspaceTab &tab) { + return tab.tab_name == name; + }); +} + +std::string next_tab_name(const SketchLayout &layout, const std::string &base_name) { + if (base_name == "tab" || base_name == "tab1") { + int max_suffix = 0; + for (const WorkspaceTab &tab : layout.tabs) { + if (tab.tab_name.size() > 3 && util::starts_with(tab.tab_name, "tab")) { + const std::string suffix = tab.tab_name.substr(3); + if (!suffix.empty() && std::all_of(suffix.begin(), suffix.end(), ::isdigit)) { + max_suffix = std::max(max_suffix, std::stoi(suffix)); + } + } + } + return "tab" + std::to_string(std::max(1, max_suffix + 1)); + } + std::string base = base_name.empty() ? "tab" : base_name; + if (!tab_name_exists(layout, base)) return base; + for (int i = 2; i < 1000; ++i) { + const std::string candidate = base + " " + std::to_string(i); + if (!tab_name_exists(layout, candidate)) return candidate; + } + return base + " copy"; +} + +void clear_layout_autosave(const AppSession &session) { + if (!session.autosave_path.empty() && fs::exists(session.autosave_path)) { + fs::remove(session.autosave_path); + } +} + +bool autosave_layout(AppSession *session, UiState *state) { + try { + if (session->autosave_path.empty()) { + session->autosave_path = autosave_path_for_layout(session->layout_path); + } + session->layout.current_tab_index = state->active_tab_index; + save_layout_json(session->layout, session->autosave_path); + state->layout_dirty = true; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to save layout draft"; + return false; + } +} + +bool mark_layout_dirty(AppSession *session, UiState *state) { + return autosave_layout(session, state); +} + +bool active_tab_has_map_pane(const SketchLayout &layout) { + if (layout.tabs.empty()) { + return false; + } + const int tab_index = std::clamp(layout.current_tab_index, 0, static_cast(layout.tabs.size()) - 1); + const WorkspaceTab &tab = layout.tabs[static_cast(tab_index)]; + return std::any_of(tab.panes.begin(), tab.panes.end(), [](const Pane &pane) { + return pane_kind_is_special(pane.kind); + }); +} + +void draw_browser_special_item(const char *item_id, const char *label) { + const ImGuiStyle &style = ImGui::GetStyle(); + const ImVec2 row_size(std::max(1.0f, ImGui::GetContentRegionAvail().x), ImGui::GetFrameHeight()); + ImGui::PushID(item_id); + ImGui::InvisibleButton("##special_data_row", row_size); + const bool hovered = ImGui::IsItemHovered(); + const bool held = ImGui::IsItemActive(); + const ImRect rect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + if (hovered) { + const ImU32 bg = ImGui::GetColorU32(held ? ImGuiCol_HeaderActive : ImGuiCol_HeaderHovered); + draw_list->AddRectFilled(rect.Min, rect.Max, bg, 0.0f); + } + ImGui::RenderTextEllipsis(draw_list, + ImVec2(rect.Min.x + style.FramePadding.x, rect.Min.y + style.FramePadding.y), + ImVec2(rect.Max.x - style.FramePadding.x, rect.Max.y), + rect.Max.x - style.FramePadding.x, + label, + nullptr, + nullptr); + if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID)) { + ImGui::SetDragDropPayload("JOTP_SPECIAL_ITEM", item_id, std::strlen(item_id) + 1); + ImGui::TextUnformatted(label); + ImGui::EndDragDropSource(); + } + ImGui::PopID(); +} + +std::array app_next_curve_color(const Pane &pane) { + static constexpr std::array, 10> PALETTE = {{ + {35, 107, 180}, + {220, 82, 52}, + {67, 160, 71}, + {243, 156, 18}, + {123, 97, 255}, + {0, 150, 136}, + {214, 48, 49}, + {52, 73, 94}, + {197, 90, 17}, + {96, 125, 139}, + }}; + return PALETTE[pane.curves.size() % PALETTE.size()]; +} + +void draw_sidebar(AppSession *session, const UiMetrics &ui, UiState *state, bool show_camera_feed) { + ImGui::SetNextWindowPos(ImVec2(0.0f, ui.top_offset)); + ImGui::SetNextWindowSize(ImVec2(ui.sidebar_width, std::max(1.0f, ui.height - ui.top_offset))); + ImGui::PushStyleColor(ImGuiCol_WindowBg, color_rgb(238, 240, 244)); + ImGui::PushStyleColor(ImGuiCol_Border, color_rgb(190, 197, 205)); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoSavedSettings; + if (ImGui::Begin("##sidebar", nullptr, flags)) { + const RouteLoadSnapshot load = session->route_loader ? session->route_loader->snapshot() : RouteLoadSnapshot{}; + const bool show_load_progress = session->route_loader && (load.active || load.total_segments > 0); + const bool streaming = session->data_mode == SessionDataMode::Stream; + CameraFeedView *sidebar_camera = session->pane_camera_feeds[static_cast(sidebar_preview_camera_view(*session))].get(); + if (show_camera_feed && sidebar_camera != nullptr) { + sidebar_camera->draw(ImGui::GetContentRegionAvail().x, load.active); + } else if (streaming) { + ImGui::SeparatorText("Camera"); + ImGui::TextDisabled("Camera not available during live stream."); + ImGui::Spacing(); + } + + ImGui::SeparatorText(streaming ? "Stream" : "Route"); + if (streaming) { + const StreamPollSnapshot stream = session->stream_poller ? session->stream_poller->snapshot() : StreamPollSnapshot{}; + const bool paused = stream.paused || session->stream_paused; + const bool live = stream.connected && !paused; + const ImVec4 status_color = live ? color_rgb(38, 135, 67) : (paused ? color_rgb(168, 119, 34) : color_rgb(155, 63, 63)); + ImGui::TextColored(status_color, "%s %s", live ? "●" : "○", stream.source_label.c_str()); + ImGui::TextDisabled("%s%s", stream_source_kind_label(stream.source_kind), paused ? " paused" : ""); + const double span = session->route_data.has_time_range ? (session->route_data.x_max - session->route_data.x_min) : 0.0; + const float fill = stream.buffer_seconds <= 0.0 + ? 0.0f + : std::clamp(static_cast(span / stream.buffer_seconds), 0.0f, 1.0f); + ImGui::ProgressBar(fill, ImVec2(-FLT_MIN, 0.0f), nullptr); + ImGui::TextDisabled("%.0fs buffer | %zu series", session->stream_buffer_seconds, session->route_data.series.size()); + const char *button_label = paused ? "Resume" : "Pause"; + if (ImGui::Button(button_label, ImVec2(std::max(1.0f, ImGui::GetContentRegionAvail().x), 0.0f))) { + if (paused) { + start_stream_session(session, state, session->stream_source, session->stream_buffer_seconds, true); + } else { + stop_stream_session(session, state); + state->status_text = "Paused stream " + stream_source_target_label(session->stream_source); + } + } + } else if (session->route_name.empty()) { + ImGui::TextDisabled("No route loaded"); + } + if (!session->route_data.car_fingerprint.empty()) { + ImGui::TextWrapped("Car: %s", session->route_data.car_fingerprint.c_str()); + } + const std::vector dbc_names = available_dbc_names(); + ImGui::SetNextItemWidth(-FLT_MIN); + if (ImGui::BeginCombo("##dbc_combo", dbc_combo_label(*session).c_str())) { + const bool auto_selected = session->dbc_override.empty(); + if (ImGui::Selectable("Auto", auto_selected)) { + apply_dbc_override_change(session, state, {}); + } + if (auto_selected) { + ImGui::SetItemDefaultFocus(); + } + ImGui::Separator(); + for (const std::string &dbc_name : dbc_names) { + const bool selected = session->dbc_override == dbc_name; + if (ImGui::Selectable(dbc_name.c_str(), selected) && !selected) { + apply_dbc_override_change(session, state, dbc_name); + } + if (selected) { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + ImGui::SeparatorText("Layout"); + ImGui::SetNextItemWidth(-FLT_MIN); + const std::string layout_combo_label = [&] { + const std::string base = session->layout_path.empty() ? std::string("untitled") : session->layout_path.stem().string(); + return state->layout_dirty ? base + " *" : base; + }(); + if (ImGui::BeginCombo("##layout_combo", layout_combo_label.c_str())) { + if (ImGui::Selectable("New Layout")) { + start_new_layout(session, state); + } + ImGui::Separator(); + const std::vector layouts = available_layout_names(); + const std::string current_layout = session->layout_path.empty() ? std::string("untitled") : session->layout_path.stem().string(); + for (const std::string &layout_name : layouts) { + const bool selected = layout_name == current_layout; + if (ImGui::Selectable(layout_name.c_str(), selected) && !selected) { + reload_layout(session, state, layout_name); + } + if (selected) { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + const float layout_button_gap = ImGui::GetStyle().ItemSpacing.x; + const float layout_row_width = std::max(1.0f, ImGui::GetContentRegionAvail().x); + const float layout_button_width = std::max(1.0f, (layout_row_width - 2.0f * layout_button_gap) / 3.0f); + if (ImGui::Button("New", ImVec2(layout_button_width, 0.0f))) { + start_new_layout(session, state); + } + ImGui::SameLine(0.0f, layout_button_gap); + if (ImGui::Button("Save", ImVec2(layout_button_width, 0.0f))) { + state->request_save_layout = true; + } + ImGui::SameLine(0.0f, layout_button_gap); + ImGui::BeginDisabled(!state->layout_dirty); + if (ImGui::Button("Reset", ImVec2(layout_button_width, 0.0f))) { + state->request_reset_layout = true; + } + ImGui::EndDisabled(); + ImGui::Spacing(); + + ImGui::SeparatorText("Data Sources"); + ImGui::SetNextItemWidth(-FLT_MIN); + input_text_with_hint_string("##browser_filter", "Search...", &state->browser_filter); + const float footer_height = ImGui::GetFrameHeightWithSpacing() + + ImGui::GetTextLineHeightWithSpacing() + + 16.0f + + (show_load_progress ? (ImGui::GetFrameHeightWithSpacing() + 12.0f) : 0.0f); + const float browser_height = std::max(1.0f, ImGui::GetContentRegionAvail().y - footer_height); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6.0f, 2.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8.0f, 3.0f)); + if (ImGui::BeginChild("##timeseries_browser", ImVec2(0.0f, browser_height), true)) { + const std::string filter = lowercase_copy(state->browser_filter); + std::vector visible_paths; + for (const BrowserNode &node : session->browser_nodes) { + collect_visible_leaf_paths(node, filter, &visible_paths); + } + for (const SpecialItemSpec &spec : kSpecialItemSpecs) { + draw_browser_special_item(spec.id, spec.label); + } + ImGui::Dummy(ImVec2(0.0f, 2.0f)); + ImGui::Separator(); + ImGui::Dummy(ImVec2(0.0f, 2.0f)); + for (const BrowserNode &node : session->browser_nodes) { + draw_browser_node(session, node, state, filter, visible_paths); + } + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + + ImGui::SeparatorText("Custom Series"); + if (ImGui::Button("Create...", ImVec2(std::max(1.0f, ImGui::GetContentRegionAvail().x), 0.0f))) { + open_custom_series_editor(state, state->selected_browser_path); + } + if (show_load_progress) { + const float total = static_cast(std::max(1, load.total_segments)); + const bool finalizing = load.active + && load.total_segments > 0 + && load.segments_downloaded >= load.total_segments + && load.segments_parsed >= load.total_segments; + const float progress = load.total_segments == 0 + ? 0.0f + : (finalizing + ? 0.99f + : std::clamp(static_cast(load.segments_downloaded + load.segments_parsed) / (2.0f * total), 0.0f, 0.99f)); + ImGui::Dummy(ImVec2(0.0f, 8.0f)); + ImGui::ProgressBar(progress, ImVec2(-FLT_MIN, 0.0f), finalizing ? "Finalizing..." : nullptr); + } + } + ImGui::End(); + ImGui::PopStyleColor(2); +} + +std::string app_curve_display_name(const Curve &curve) { + if (!curve.label.empty()) return curve.label; + if (!curve.name.empty()) return curve.name; + return "curve"; +} + +Curve make_curve_for_path(const Pane &pane, const std::string &path) { + Curve curve; + curve.name = path; + curve.label = path; + curve.color = app_next_curve_color(pane); + return curve; +} + +bool add_curve_to_pane(WorkspaceTab *tab, int pane_index, Curve curve) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return false; + } + Pane &pane = tab->panes[static_cast(pane_index)]; + if (pane.kind != PaneKind::Plot) { + pane.kind = PaneKind::Plot; + if (is_default_special_title(pane.title)) { + pane.title = UNTITLED_PANE_TITLE; + } + } + for (Curve &existing : pane.curves) { + const bool same_named_curve = !curve.name.empty() && existing.name == curve.name; + const bool same_unnamed_curve = curve.name.empty() && existing.name.empty() && existing.label == curve.label; + if (same_named_curve || same_unnamed_curve) { + existing.visible = true; + return false; + } + } + pane.curves.push_back(std::move(curve)); + return true; +} + +bool add_path_curve_to_pane(AppSession *session, UiState *state, int pane_index, const std::string &path) { + if (app_find_route_series(*session, path) == nullptr) { + state->status_text = "Path not found in route"; + return false; + } + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + if (tab == nullptr || pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + state->status_text = "No active pane"; + return false; + } + const SketchLayout before_layout = session->layout; + const bool inserted = add_curve_to_pane(tab, pane_index, make_curve_for_path(tab->panes[static_cast(pane_index)], path)); + bool autosave_ok = true; + if (inserted) { + state->undo.push(before_layout); + autosave_ok = mark_layout_dirty(session, state); + } + if (autosave_ok) { + state->status_text = inserted ? "Added " + path : "Curve already present"; + } + return true; +} + +int add_path_curves_to_pane(AppSession *session, UiState *state, int pane_index, const std::vector &paths) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + if (tab == nullptr || pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + state->status_text = "No active pane"; + return 0; + } + + int inserted_count = 0; + int duplicate_count = 0; + const SketchLayout before_layout = session->layout; + for (const std::string &path : paths) { + if (app_find_route_series(*session, path) == nullptr) continue; + if (add_curve_to_pane(tab, pane_index, make_curve_for_path(tab->panes[static_cast(pane_index)], path))) { + ++inserted_count; + } else { + ++duplicate_count; + } + } + + if (inserted_count > 0) { + state->undo.push(before_layout); + if (mark_layout_dirty(session, state)) { + state->status_text = inserted_count == 1 + ? "Added " + paths.front() + : "Added " + std::to_string(inserted_count) + " curves"; + } + return inserted_count; + } + + if (duplicate_count > 0) { + state->status_text = duplicate_count == 1 ? "Curve already present" : "Curves already present"; + } else { + state->status_text = "No matching series found"; + } + return 0; +} + +bool app_add_curve_to_active_pane(AppSession *session, UiState *state, const std::string &path) { + const TabUiState *tab_state = app_active_tab_state(state); + if (tab_state == nullptr) { + state->status_text = "No active pane"; + return false; + } + return add_path_curve_to_pane(session, state, tab_state->active_pane_index, path); +} + +bool apply_special_item_to_pane(WorkspaceTab *tab, TabUiState *tab_state, int pane_index, std::string_view item_id) { + if (tab == nullptr || tab_state == nullptr) return false; + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) return false; + const SpecialItemSpec *spec = special_item_spec(item_id); + if (spec == nullptr) return false; + Pane &pane = tab->panes[static_cast(pane_index)]; + if (!((pane.kind == PaneKind::Plot && pane.curves.empty()) || pane_kind_is_special(pane.kind))) { + return false; + } + if (pane.kind == spec->kind && (spec->kind != PaneKind::Camera || pane.camera_view == spec->camera_view)) { + tab_state->active_pane_index = pane_index; + return false; + } + const PaneKind previous_kind = pane.kind; + pane.kind = spec->kind; + pane.camera_view = spec->camera_view; + if (spec->kind == PaneKind::Map) { + if (pane.title == UNTITLED_PANE_TITLE || previous_kind != PaneKind::Plot) { + pane.title = spec->label; + } + } else { + pane.title = spec->label; + resize_tab_pane_state(tab_state, tab->panes.size()); + tab_state->camera_panes[static_cast(pane_index)].fit_to_pane = true; + } + tab_state->active_pane_index = pane_index; + return true; +} + +bool split_pane(WorkspaceTab *tab, int pane_index, PaneDropZone zone, std::optional curve = std::nullopt) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return false; + } + if (zone == PaneDropZone::Center) return false; + + const int new_pane_index = static_cast(tab->panes.size()); + Pane new_pane = make_empty_pane(); + if (curve.has_value()) { + new_pane.curves.push_back(*curve); + } + tab->panes.push_back(std::move(new_pane)); + + const bool vertical = zone == PaneDropZone::Top || zone == PaneDropZone::Bottom; + const bool new_before = zone == PaneDropZone::Left || zone == PaneDropZone::Top; + return split_pane_node(&tab->root, pane_index, + vertical ? SplitOrientation::Vertical : SplitOrientation::Horizontal, + new_before, new_pane_index); +} + +bool close_pane(WorkspaceTab *tab, int pane_index) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return false; + } + if (tab->panes.size() <= 1) { + tab->panes[static_cast(pane_index)] = make_empty_pane(); + return true; + } + if (remove_pane_node(&tab->root, pane_index)) return false; + tab->panes.erase(tab->panes.begin() + static_cast(pane_index)); + decrement_pane_indices(&tab->root, pane_index); + normalize_split_node(&tab->root); + return true; +} + +void clear_pane(WorkspaceTab *tab, int pane_index) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return; + } + Pane &pane = tab->panes[static_cast(pane_index)]; + pane.curves.clear(); + pane.title = UNTITLED_PANE_TITLE; +} + +void create_runtime_tab(SketchLayout *layout, UiState *state) { + const std::string tab_name = next_tab_name(*layout, "tab1"); + layout->tabs.push_back(make_empty_tab(tab_name)); + state->tabs.push_back(TabUiState{.dock_needs_build = true, .active_pane_index = 0, .runtime_id = state->next_tab_runtime_id++}); + request_tab_selection(state, static_cast(layout->tabs.size()) - 1); + state->status_text = "Created " + tab_name; +} + +void duplicate_runtime_tab(SketchLayout *layout, UiState *state) { + if (layout->tabs.empty()) { + return; + } + const int source_index = std::clamp(state->active_tab_index, 0, static_cast(layout->tabs.size()) - 1); + WorkspaceTab copy = layout->tabs[static_cast(source_index)]; + copy.tab_name = next_tab_name(*layout, copy.tab_name + " copy"); + layout->tabs.push_back(std::move(copy)); + const int active_pane_index = source_index < static_cast(state->tabs.size()) ? state->tabs[static_cast(source_index)].active_pane_index : 0; + state->tabs.push_back(TabUiState{.dock_needs_build = true, .active_pane_index = active_pane_index, .runtime_id = state->next_tab_runtime_id++}); + request_tab_selection(state, static_cast(layout->tabs.size()) - 1); + state->status_text = "Duplicated tab"; +} + +void close_runtime_tab(SketchLayout *layout, UiState *state) { + if (layout->tabs.empty()) { + return; + } + const int tab_index = std::clamp(state->active_tab_index, 0, static_cast(layout->tabs.size()) - 1); + if (layout->tabs.size() == 1) { + layout->tabs[0] = make_empty_tab(layout->tabs[0].tab_name.empty() ? "tab1" : layout->tabs[0].tab_name); + if (state->tabs.empty()) { + state->tabs.push_back(TabUiState{.dock_needs_build = true, .active_pane_index = 0}); + } else { + state->tabs.resize(1); + state->tabs[0] = TabUiState{ + .dock_needs_build = true, + .active_pane_index = 0, + .runtime_id = state->tabs[0].runtime_id == 0 ? state->next_tab_runtime_id++ : state->tabs[0].runtime_id, + }; + } + state->active_tab_index = 0; + state->requested_tab_index = 0; + layout->current_tab_index = 0; + cancel_rename_tab(state); + state->status_text = "Closed tab"; + return; + } + layout->tabs.erase(layout->tabs.begin() + static_cast(tab_index)); + if (tab_index < static_cast(state->tabs.size())) { + state->tabs.erase(state->tabs.begin() + static_cast(tab_index)); + } + if (state->active_tab_index >= static_cast(layout->tabs.size())) { + state->active_tab_index = static_cast(layout->tabs.size()) - 1; + } + sync_ui_state(state, *layout); + state->requested_tab_index = state->active_tab_index; + state->status_text = "Closed tab"; +} + +void rename_runtime_tab(SketchLayout *layout, UiState *state) { + if (state->rename_tab_index < 0 || state->rename_tab_index >= static_cast(layout->tabs.size())) { + return; + } + layout->tabs[static_cast(state->rename_tab_index)].tab_name = state->rename_tab_buffer; + state->status_text = "Renamed tab"; + layout->current_tab_index = state->rename_tab_index; + cancel_rename_tab(state); +} + +void draw_inline_tab_editor(AppSession *session, UiState *state, const ImRect &tab_rect) { + const int rename_tab_index = state->rename_tab_index; + if (rename_tab_index < 0 || rename_tab_index >= static_cast(session->layout.tabs.size())) { + return; + } + + const float width = std::max(48.0f, tab_rect.Max.x - tab_rect.Min.x - 10.0f); + const ImVec2 pos = ImVec2(tab_rect.Min.x + 5.0f, tab_rect.Min.y + 2.0f); + ImGui::SetCursorScreenPos(pos); + ImGui::PushItemWidth(width); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 2.0f)); + if (state->focus_rename_tab_input) { + ImGui::SetKeyboardFocusHere(); + state->focus_rename_tab_input = false; + } + const bool submitted = input_text_string("##rename_tab_inline", + &state->rename_tab_buffer, + ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue); + const bool active = ImGui::IsItemActive(); + const bool escape = active && ImGui::IsKeyPressed(ImGuiKey_Escape); + const bool deactivated = ImGui::IsItemDeactivated(); + ImGui::PopStyleVar(); + ImGui::PopItemWidth(); + + if (escape) { + cancel_rename_tab(state); + } else if (submitted || deactivated) { + const SketchLayout before_layout = session->layout; + rename_runtime_tab(&session->layout, state); + state->undo.push(before_layout); + mark_layout_dirty(session, state); + } +} + + +std::optional draw_pane_drop_target(int tab_index, int pane_index, const Pane &target_pane) { + if (ImGui::GetDragDropPayload() == nullptr) return std::nullopt; + + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 content_min = ImGui::GetWindowContentRegionMin(); + const ImVec2 content_max = ImGui::GetWindowContentRegionMax(); + ImRect content_rect(ImVec2(window_pos.x + content_min.x, window_pos.y + content_min.y), + ImVec2(window_pos.x + content_max.x, window_pos.y + content_max.y)); + content_rect.Expand(ImVec2(-6.0f, -6.0f)); + if (content_rect.GetWidth() < 60.0f || content_rect.GetHeight() < 60.0f) { + return std::nullopt; + } + + const float edge_w = std::min(90.0f, content_rect.GetWidth() * 0.24f); + const float edge_h = std::min(72.0f, content_rect.GetHeight() * 0.24f); + struct ZoneRect { + PaneDropZone zone; + ImRect rect; + }; + const std::array zones = {{ + {PaneDropZone::Left, ImRect(content_rect.Min, ImVec2(content_rect.Min.x + edge_w, content_rect.Max.y))}, + {PaneDropZone::Right, ImRect(ImVec2(content_rect.Max.x - edge_w, content_rect.Min.y), content_rect.Max)}, + {PaneDropZone::Top, ImRect(content_rect.Min, ImVec2(content_rect.Max.x, content_rect.Min.y + edge_h))}, + {PaneDropZone::Bottom, ImRect(ImVec2(content_rect.Min.x, content_rect.Max.y - edge_h), content_rect.Max)}, + {PaneDropZone::Center, ImRect(ImVec2(content_rect.Min.x + edge_w, content_rect.Min.y + edge_h), + ImVec2(content_rect.Max.x - edge_w, content_rect.Max.y - edge_h))}, + }}; + + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + for (const ZoneRect &zone : zones) { + if (zone.rect.GetWidth() <= 0.0f || zone.rect.GetHeight() <= 0.0f) { + continue; + } + + ImGui::PushID(static_cast(zone.zone) * 1000 + pane_index + tab_index * 100); + ImGui::SetCursorScreenPos(zone.rect.Min); + ImGui::InvisibleButton("##drop_zone", zone.rect.GetSize()); + if (ImGui::BeginDragDropTarget()) { + auto try_accept = [&](const char *type) -> const ImGuiPayload * { + const ImGuiPayload *p = ImGui::AcceptDragDropPayload(type, ImGuiDragDropFlags_AcceptBeforeDelivery); + if (p && p->Preview) { + draw_list->AddRectFilled(zone.rect.Min, zone.rect.Max, IM_COL32(70, 130, 220, 55)); + draw_list->AddRect(zone.rect.Min, zone.rect.Max, IM_COL32(45, 95, 175, 220), 0.0f, 0, 2.0f); + } + return p; + }; + auto deliver = [&](PaneDropAction action) -> std::optional { + action.zone = zone.zone; + action.target_pane_index = pane_index; + ImGui::EndDragDropTarget(); + ImGui::PopID(); + return action; + }; + if (const ImGuiPayload *p = try_accept("JOTP_BROWSER_PATHS"); p && p->Delivery) { + if (zone.zone != PaneDropZone::Center || target_pane.kind == PaneKind::Plot) { + PaneDropAction action; + action.from_browser = true; + action.browser_paths = decode_browser_drag_payload(static_cast(p->Data)); + return deliver(std::move(action)); + } + } + if (zone.zone != PaneDropZone::Center || (target_pane.kind == PaneKind::Plot && target_pane.curves.empty()) || pane_kind_is_special(target_pane.kind)) { + if (const ImGuiPayload *p = try_accept("JOTP_SPECIAL_ITEM"); p && p->Delivery) { + PaneDropAction action; + action.special_item_id = static_cast(p->Data); + return deliver(std::move(action)); + } + } + if (const ImGuiPayload *p = try_accept("JOTP_PANE_CURVE"); p && p->Delivery) { + if (zone.zone != PaneDropZone::Center || target_pane.kind == PaneKind::Plot) { + PaneDropAction action; + action.curve_ref = *static_cast(p->Data); + return deliver(std::move(action)); + } + } + ImGui::EndDragDropTarget(); + } + ImGui::PopID(); + } + return std::nullopt; +} + +bool commit_tab_layout_change(AppSession *session, + UiState *state, + WorkspaceTab *tab, + TabUiState *tab_state, + const SketchLayout &before_layout, + std::string_view status_text, + bool dock_changed) { + if (dock_changed) { + mark_tab_dock_dirty(state, state->active_tab_index); + } + resize_tab_pane_state(tab_state, tab->panes.size()); + state->undo.push(before_layout); + if (mark_layout_dirty(session, state)) { + state->status_text = std::string(status_text); + } + return true; +} + +bool apply_pane_menu_action(AppSession *session, UiState *state, int pane_index, + const PaneMenuAction &action) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + if (tab == nullptr || tab_state == nullptr) return false; + + const int original_pane_count = static_cast(tab->panes.size()); + const SketchLayout before_layout = session->layout; + bool dock_changed = false; + bool layout_changed = false; + std::string_view success_status = "Workspace updated"; + switch (action.kind) { + case PaneMenuActionKind::OpenAxisLimits: + tab_state->active_pane_index = pane_index; + open_axis_limits_editor(*session, state, pane_index); + state->status_text = "Axis limits editor opened"; + return true; + case PaneMenuActionKind::OpenCustomSeries: + tab_state->active_pane_index = pane_index; + open_custom_series_editor(state, preferred_custom_series_source(tab->panes[static_cast(pane_index)])); + state->status_text = "Custom series editor opened"; + return true; + case PaneMenuActionKind::SplitLeft: + case PaneMenuActionKind::SplitRight: + case PaneMenuActionKind::SplitTop: + case PaneMenuActionKind::SplitBottom: { + constexpr PaneDropZone kZones[] = {PaneDropZone::Left, PaneDropZone::Right, PaneDropZone::Top, PaneDropZone::Bottom}; + const auto zone = kZones[static_cast(action.kind) - static_cast(PaneMenuActionKind::SplitLeft)]; + if (split_pane(tab, pane_index, zone)) { + tab_state->active_pane_index = static_cast(tab->panes.size()) - 1; + dock_changed = true; + layout_changed = true; + } + break; + } + case PaneMenuActionKind::ResetView: + reset_shared_range(state, *session); + state->follow_latest = session->data_mode == SessionDataMode::Stream; + state->suppress_range_side_effects = true; + clamp_shared_range(state, *session); + persist_shared_range_to_tab(tab, *state); + clear_pane_vertical_limits(&tab->panes[static_cast(pane_index)]); + layout_changed = true; + success_status = "Plot view reset"; + break; + case PaneMenuActionKind::Clear: + clear_pane(tab, pane_index); + tab_state->active_pane_index = pane_index; + layout_changed = true; + break; + case PaneMenuActionKind::Close: + if (close_pane(tab, pane_index)) { + tab_state->active_pane_index = std::clamp(pane_index, 0, static_cast(tab->panes.size()) - 1); + layout_changed = true; + dock_changed = static_cast(tab->panes.size()) != original_pane_count; + } + break; + case PaneMenuActionKind::None: + return false; + } + + if (!layout_changed) { + return false; + } + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, success_status, dock_changed); +} + +bool apply_pane_drop_action(AppSession *session, UiState *state, const PaneDropAction &action) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + if (tab == nullptr || tab_state == nullptr) return false; + + if (!action.special_item_id.empty()) { + const SpecialItemSpec *spec = special_item_spec(action.special_item_id); + if (spec == nullptr) { + return false; + } + if (action.zone == PaneDropZone::Center) { + if (action.target_pane_index < 0 || action.target_pane_index >= static_cast(tab->panes.size())) { + return false; + } + if (!((tab->panes[static_cast(action.target_pane_index)].kind == PaneKind::Plot + && tab->panes[static_cast(action.target_pane_index)].curves.empty()) + || pane_kind_is_special(tab->panes[static_cast(action.target_pane_index)].kind))) { + state->status_text = std::string(special_item_label(action.special_item_id)) + " can only replace another special pane or use an empty pane"; + return false; + } + const SketchLayout before_layout = session->layout; + const bool changed = apply_special_item_to_pane(tab, tab_state, action.target_pane_index, spec->id); + if (!changed) { + state->status_text = std::string(special_item_label(action.special_item_id)) + " already shown in pane"; + return false; + } + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, + std::string(special_item_label(action.special_item_id)) + " added to pane", + false); + } + const SketchLayout before_layout = session->layout; + if (split_pane(tab, action.target_pane_index, action.zone)) { + tab_state->active_pane_index = static_cast(tab->panes.size()) - 1; + const bool changed = apply_special_item_to_pane(tab, tab_state, tab_state->active_pane_index, spec->id); + if (!changed) { + return false; + } + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, + "Split pane and added " + std::string(special_item_label(action.special_item_id)), + true); + } + return false; + } + + if (action.from_browser) { + if (action.browser_paths.empty()) return false; + if (action.zone == PaneDropZone::Center) { + const int inserted_count = add_path_curves_to_pane(session, state, action.target_pane_index, action.browser_paths); + if (inserted_count > 0) { + tab_state->active_pane_index = action.target_pane_index; + } + return inserted_count > 0; + } + const SketchLayout before_layout = session->layout; + if (split_pane(tab, action.target_pane_index, action.zone)) { + tab_state->active_pane_index = static_cast(tab->panes.size()) - 1; + int inserted_count = 0; + for (const std::string &path : action.browser_paths) { + if (app_find_route_series(*session, path) == nullptr) continue; + if (add_curve_to_pane(tab, tab_state->active_pane_index, + make_curve_for_path(tab->panes[static_cast(tab_state->active_pane_index)], path))) { + ++inserted_count; + } + } + if (inserted_count > 0) { + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, + inserted_count == 1 + ? "Split pane and added " + action.browser_paths.front() + : "Split pane and added " + std::to_string(inserted_count) + " curves", + true); + } + return false; + } + return false; + } + + if (action.curve_ref.tab_index < 0 + || action.curve_ref.tab_index >= static_cast(session->layout.tabs.size())) { + return false; + } + WorkspaceTab &source_tab = session->layout.tabs[static_cast(action.curve_ref.tab_index)]; + if (action.curve_ref.pane_index < 0 + || action.curve_ref.pane_index >= static_cast(source_tab.panes.size())) { + return false; + } + const Pane &source_pane = source_tab.panes[static_cast(action.curve_ref.pane_index)]; + if (action.curve_ref.curve_index < 0 + || action.curve_ref.curve_index >= static_cast(source_pane.curves.size())) { + return false; + } + const Curve curve = source_pane.curves[static_cast(action.curve_ref.curve_index)]; + + if (action.zone == PaneDropZone::Center) { + const SketchLayout before_layout = session->layout; + const bool inserted = add_curve_to_pane(tab, action.target_pane_index, curve); + tab_state->active_pane_index = action.target_pane_index; + if (inserted) { + state->undo.push(before_layout); + if (mark_layout_dirty(session, state)) { + state->status_text = "Added " + app_curve_display_name(curve); + } + } else { + state->status_text = "Curve already present"; + } + return true; + } + const SketchLayout before_layout = session->layout; + if (split_pane(tab, action.target_pane_index, action.zone, curve)) { + tab_state->active_pane_index = static_cast(tab->panes.size()) - 1; + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, + "Split pane and added " + app_curve_display_name(curve), + true); + } + return false; +} + +ImGuiDir dock_direction(SplitOrientation orientation) { + return orientation == SplitOrientation::Horizontal ? ImGuiDir_Left : ImGuiDir_Up; +} + +void build_dock_tree(const WorkspaceNode &node, const WorkspaceTab &tab, int tab_runtime_id, ImGuiID dock_id) { + if (node.is_pane) { + if (node.pane_index >= 0 && node.pane_index < static_cast(tab.panes.size())) { + ImGui::DockBuilderDockWindow( + pane_window_name(tab_runtime_id, node.pane_index, tab.panes[static_cast(node.pane_index)]).c_str(), + dock_id); + if (ImGuiDockNode *dock_node = ImGui::DockBuilderGetNode(dock_id); dock_node != nullptr) { + dock_node->LocalFlags |= ImGuiDockNodeFlags_AutoHideTabBar | + ImGuiDockNodeFlags_NoWindowMenuButton | + ImGuiDockNodeFlags_NoCloseButton; + } + } + return; + } + if (node.children.empty()) { + return; + } + if (node.children.size() == 1) { + build_dock_tree(node.children.front(), tab, tab_runtime_id, dock_id); + return; + } + + float remaining = 1.0f; + ImGuiID current = dock_id; + for (size_t i = 0; i + 1 < node.children.size(); ++i) { + const float child_size = i < node.sizes.size() ? node.sizes[i] : 0.0f; + const float ratio = remaining <= 0.0f ? 0.5f : std::clamp(child_size / remaining, 0.05f, 0.95f); + ImGuiID child_id = 0; + ImGuiID remainder_id = 0; + ImGui::DockBuilderSplitNode(current, dock_direction(node.orientation), ratio, &child_id, &remainder_id); + build_dock_tree(node.children[i], tab, tab_runtime_id, child_id); + current = remainder_id; + remaining = std::max(0.0f, remaining - child_size); + } + build_dock_tree(node.children.back(), tab, tab_runtime_id, current); +} + +void ensure_dockspace(const WorkspaceTab &tab, TabUiState *tab_state, ImVec2 dockspace_size) { + if (dockspace_size.x <= 0.0f || dockspace_size.y <= 0.0f || tab_state == nullptr) { + return; + } + const bool size_changed = std::abs(tab_state->last_dockspace_size.x - dockspace_size.x) > 1.0f + || std::abs(tab_state->last_dockspace_size.y - dockspace_size.y) > 1.0f; + if (!tab_state->dock_needs_build && !size_changed) { + return; + } + + const ImGuiID dockspace_id = dockspace_id_for_tab(tab_state->runtime_id); + ImGui::DockBuilderRemoveNode(dockspace_id); + ImGui::DockBuilderAddNode(dockspace_id, ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_AutoHideTabBar); + ImGui::DockBuilderSetNodeSize(dockspace_id, dockspace_size); + build_dock_tree(tab.root, tab, tab_state->runtime_id, dockspace_id); + ImGui::DockBuilderFinish(dockspace_id); + tab_state->dock_needs_build = false; + tab_state->last_dockspace_size = dockspace_size; +} + +void draw_pane_windows(AppSession *session, UiState *state) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + if (tab == nullptr || tab_state == nullptr) { + return; + } + + std::optional> pending_menu_action; + std::optional pending_close_pane; + std::optional pending_drop_action; + + for (size_t i = 0; i < tab->panes.size(); ++i) { + Pane &pane = tab->panes[i]; + std::optional menu_action; + std::optional drop_action; + bool close_pane_requested = false; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(2.0f, 2.0f)); + ImGui::PushStyleColor(ImGuiCol_WindowBg, color_rgb(250, 250, 251)); + ImGui::PushStyleColor(ImGuiCol_Border, color_rgb(194, 198, 204)); + ImGui::PushStyleColor(ImGuiCol_TitleBg, color_rgb(252, 252, 253)); + ImGui::PushStyleColor(ImGuiCol_TitleBgActive, color_rgb(252, 252, 253)); + ImGui::PushStyleColor(ImGuiCol_TitleBgCollapsed, color_rgb(252, 252, 253)); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoCollapse; + const std::string window_name = pane_window_name(tab_state->runtime_id, static_cast(i), pane); + const bool opened = ImGui::Begin(window_name.c_str(), nullptr, flags); + if (opened) { + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) + || (ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) && ImGui::IsMouseClicked(0))) { + tab_state->active_pane_index = static_cast(i); + } + if (pane.kind == PaneKind::Map) { + draw_map_pane(session, state, &pane, static_cast(i)); + } else if (pane.kind == PaneKind::Camera) { + draw_camera_pane(session, state, tab_state, static_cast(i), pane); + } else { + draw_plot(*session, &pane, state); + } + draw_pane_frame_overlay(); + close_pane_requested = draw_pane_close_button_overlay(); + menu_action = draw_pane_context_menu(*tab, static_cast(i)); + drop_action = draw_pane_drop_target(state->active_tab_index, static_cast(i), pane); + } + ImGui::End(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(5); + if (!pending_menu_action.has_value() && menu_action.has_value()) { + pending_menu_action = std::make_pair(static_cast(i), *menu_action); + } + if (!pending_menu_action.has_value() && !pending_close_pane.has_value() && close_pane_requested) { + pending_close_pane = static_cast(i); + } + if (!pending_menu_action.has_value() && !pending_close_pane.has_value() + && !pending_drop_action.has_value() && drop_action.has_value()) { + pending_drop_action = *drop_action; + } + } + + if (pending_menu_action.has_value()) { + apply_pane_menu_action(session, state, pending_menu_action->first, pending_menu_action->second); + return; + } + if (pending_close_pane.has_value()) { + PaneMenuAction action; + action.kind = PaneMenuActionKind::Close; + action.pane_index = *pending_close_pane; + apply_pane_menu_action(session, state, *pending_close_pane, action); + return; + } + if (pending_drop_action.has_value()) { + apply_pane_drop_action(session, state, *pending_drop_action); + } +} + +void draw_workspace(AppSession *session, const UiMetrics &ui, UiState *state) { + state->custom_series.selected = false; + state->logs.selected = false; + ImGui::SetNextWindowPos(ImVec2(ui.content_x, ui.content_y)); + ImGui::SetNextWindowSize(ImVec2(ui.content_w, ui.content_h)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_WindowBg, color_rgb(244, 246, 248)); + ImGui::PushStyleColor(ImGuiCol_Border, color_rgb(186, 191, 198)); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoScrollWithMouse; + if (ImGui::Begin("##workspace_host", nullptr, flags)) { + const int selection_request = state->requested_tab_index; + std::optional rename_tab_rect; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10.0f, 6.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(8.0f, 4.0f)); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + if (ImGui::BeginTabBar("##layout_tabs", ImGuiTabBarFlags_FittingPolicyScroll)) { + enum class TabActionKind { + None, + New, + Rename, + Duplicate, + Close, + }; + TabActionKind pending_action = TabActionKind::None; + int pending_tab_index = -1; + bool custom_series_tab_open = state->custom_series.open; + bool suppress_aux_tabs_this_frame = state->request_close_tab && session->layout.tabs.size() == 1; + for (size_t i = 0; i < session->layout.tabs.size(); ++i) { + const WorkspaceTab &tab = session->layout.tabs[i]; + const TabUiState &tab_ui = state->tabs[i]; + ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_None; + if (static_cast(i) == selection_request) { + tab_flags |= ImGuiTabItemFlags_SetSelected; + } + bool tab_open = true; + const bool opened = ImGui::BeginTabItem(tab_item_label(tab, tab_ui.runtime_id).c_str(), &tab_open, tab_flags); + if (state->rename_tab_index == static_cast(i)) { + rename_tab_rect = ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + } + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { + pending_action = TabActionKind::Rename; + pending_tab_index = static_cast(i); + } + if (!tab_open) { + pending_action = TabActionKind::Close; + pending_tab_index = static_cast(i); + if (session->layout.tabs.size() == 1) { + suppress_aux_tabs_this_frame = true; + } + } + if (ImGui::BeginPopupContextItem()) { + if (ImGui::MenuItem("New Tab")) { + pending_action = TabActionKind::New; + } + if (ImGui::MenuItem("Rename Tab...")) { + pending_action = TabActionKind::Rename; + pending_tab_index = static_cast(i); + } + if (ImGui::MenuItem("Duplicate Tab")) { + pending_action = TabActionKind::Duplicate; + pending_tab_index = static_cast(i); + } + if (ImGui::MenuItem("Close Tab")) { + pending_action = TabActionKind::Close; + pending_tab_index = static_cast(i); + } + ImGui::EndPopup(); + } + if (opened) { + state->active_tab_index = static_cast(i); + session->layout.current_tab_index = state->active_tab_index; + if (i < state->tabs.size()) { + ensure_dockspace(tab, &state->tabs[i], ImGui::GetContentRegionAvail()); + } + ImGui::DockSpace(dockspace_id_for_tab(tab_ui.runtime_id), + ImVec2(0.0f, 0.0f), + ImGuiDockNodeFlags_AutoHideTabBar | + ImGuiDockNodeFlags_NoWindowMenuButton | + ImGuiDockNodeFlags_NoCloseButton); + ImGui::EndTabItem(); + } + } + if (!suppress_aux_tabs_this_frame) { + ImGuiTabItemFlags logs_flags = ImGuiTabItemFlags_None; + if (state->logs.request_select) { + logs_flags |= ImGuiTabItemFlags_SetSelected; + } + if (ImGui::BeginTabItem("Logs##workspace_logs", nullptr, logs_flags)) { + state->logs.request_select = false; + state->logs.selected = true; + draw_logs_tab(session, state); + ImGui::EndTabItem(); + } + if (custom_series_tab_open) { + ImGuiTabItemFlags custom_flags = ImGuiTabItemFlags_None; + if (state->custom_series.request_select) { + custom_flags |= ImGuiTabItemFlags_SetSelected; + } + if (ImGui::BeginTabItem("Custom Series##workspace_custom_series", &custom_series_tab_open, custom_flags)) { + state->custom_series.request_select = false; + state->custom_series.selected = true; + draw_custom_series_editor(session, state); + ImGui::EndTabItem(); + } + } + } + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(12.0f, 5.0f)); + ImGui::PushStyleColor(ImGuiCol_Tab, color_rgb(210, 217, 225)); + ImGui::PushStyleColor(ImGuiCol_TabHovered, color_rgb(224, 230, 237)); + ImGui::PushStyleColor(ImGuiCol_TabSelected, color_rgb(242, 245, 248)); + if (ImGui::TabItemButton(" ##new_tab_button", ImGuiTabItemFlags_Trailing)) { + pending_action = TabActionKind::New; + } + { + const ImRect rect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + const ImU32 color = ImGui::GetColorU32(color_rgb(72, 79, 88)); + const ImVec2 center((rect.Min.x + rect.Max.x) * 0.5f, (rect.Min.y + rect.Max.y) * 0.5f); + constexpr float half_extent = 6.25f; + constexpr float thickness = 2.0f; + draw_list->AddLine(ImVec2(center.x - half_extent, center.y), + ImVec2(center.x + half_extent, center.y), + color, + thickness); + draw_list->AddLine(ImVec2(center.x, center.y - half_extent), + ImVec2(center.x, center.y + half_extent), + color, + thickness); + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8.0f, 6.0f)); + ImGui::BeginTooltip(); + ImGui::TextUnformatted("New Tab"); + ImGui::EndTooltip(); + ImGui::PopStyleVar(); + } + ImGui::PopStyleColor(3); + ImGui::PopStyleVar(); + ImGui::EndTabBar(); + + if (!custom_series_tab_open) { + state->custom_series.open = false; + state->custom_series.request_select = false; + } + + if (rename_tab_rect.has_value()) { + draw_inline_tab_editor(session, state, *rename_tab_rect); + } + + if (state->request_new_tab || pending_action == TabActionKind::New) { + const SketchLayout before_layout = session->layout; + create_runtime_tab(&session->layout, state); + state->undo.push(before_layout); + mark_layout_dirty(session, state); + state->request_new_tab = false; + } else if (pending_action == TabActionKind::Rename) { + begin_rename_tab(session->layout, state, pending_tab_index); + } else if (state->request_duplicate_tab || pending_action == TabActionKind::Duplicate) { + if (pending_tab_index >= 0) { + request_tab_selection(state, pending_tab_index); + } + const SketchLayout before_layout = session->layout; + duplicate_runtime_tab(&session->layout, state); + state->undo.push(before_layout); + mark_layout_dirty(session, state); + state->request_duplicate_tab = false; + } else if (state->request_close_tab || pending_action == TabActionKind::Close) { + if (pending_tab_index >= 0) { + request_tab_selection(state, pending_tab_index); + } + const SketchLayout before_layout = session->layout; + close_runtime_tab(&session->layout, state); + state->undo.push(before_layout); + mark_layout_dirty(session, state); + state->request_close_tab = false; + } + if (state->requested_tab_index == selection_request) { + state->requested_tab_index = -1; + } + } + ImGui::PopStyleColor(3); + ImGui::PopStyleVar(2); + } + ImGui::End(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(2); +} + +int run(const Options &options) { + try { + const fs::path layout_path = options.layout.empty() ? fs::path() : resolve_layout_path(options.layout); + AppSession session = { + .layout_path = layout_path, + .autosave_path = layout_path.empty() ? fs::path() : autosave_path_for_layout(layout_path), + .route_name = options.route_name, + .data_dir = options.data_dir, + .dbc_override = {}, + .stream_source = StreamSourceConfig{.kind = is_local_stream_address(options.stream_address) + ? StreamSourceKind::CerealLocal + : StreamSourceKind::CerealRemote, + .address = options.stream_address}, + .stream_buffer_seconds = options.stream_buffer_seconds, + .data_mode = options.stream ? SessionDataMode::Stream : SessionDataMode::Route, + .route_id = options.stream ? RouteIdentifier{} : parse_route_identifier(options.route_name), + .layout = options.layout.empty() ? make_empty_layout() : load_sketch_layout(layout_path), + }; + UiState ui_state; + if (!layout_path.empty() && !session.autosave_path.empty() && fs::exists(session.autosave_path)) { + session.layout = load_sketch_layout(session.autosave_path); + ui_state.layout_dirty = true; + } + ui_state.undo.reset(session.layout); + sync_ui_state(&ui_state, session.layout); + sync_route_buffers(&ui_state, session); + sync_stream_buffers(&ui_state, session); + sync_layout_buffers(&ui_state, session); + + session.async_route_loading = session.data_mode == SessionDataMode::Route + && options.show && options.output_path.empty() && !options.sync_load; + if (session.data_mode == SessionDataMode::Route && !session.async_route_loading) { + TerminalRouteProgress route_progress(::isatty(STDERR_FILENO) != 0); + rebuild_session_route_data(&session, &ui_state, [&](const RouteLoadProgress &update) { + route_progress.update(update); + }); + route_progress.finish(); + } + + GlfwRuntime glfw_runtime(options); + ImGuiRuntime imgui_runtime(glfw_runtime.window()); + configure_style(); + session.map_data = std::make_unique(); + for (std::unique_ptr &feed : session.pane_camera_feeds) { + feed = std::make_unique(); + } + sync_camera_feeds(&session); + + if (session.async_route_loading) { + session.route_loader = std::make_unique(::isatty(STDERR_FILENO) != 0); + start_async_route_load(&session, &ui_state); + } else if (session.data_mode == SessionDataMode::Stream) { + session.stream_poller = std::make_unique(); + start_stream_session(&session, &ui_state, session.stream_source, session.stream_buffer_seconds); + } + + const bool should_capture = !options.output_path.empty(); + const fs::path output_path = should_capture ? fs::path(options.output_path) : fs::path(); + const bool capture_has_map = should_capture && active_tab_has_map_pane(session.layout); + if (options.show) { + bool captured = false; + const auto capture_ready_at = std::chrono::steady_clock::now() + (capture_has_map ? std::chrono::milliseconds(1800) + : std::chrono::milliseconds(0)); + while (!glfwWindowShouldClose(glfw_runtime.window())) { + const bool capture_ready = std::chrono::steady_clock::now() >= capture_ready_at; + const fs::path *capture_path = (!captured && should_capture && capture_ready) ? &output_path : nullptr; + render_frame(glfw_runtime.window(), &session, &ui_state, capture_path); + captured = captured || capture_path != nullptr; + } + } else { + render_frame(glfw_runtime.window(), &session, &ui_state, nullptr); + if (should_capture) { + for (int i = 0; i < 3; ++i) { + render_frame(glfw_runtime.window(), &session, &ui_state, nullptr); + } + if (capture_has_map) { + for (int i = 0; i < 18; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + render_frame(glfw_runtime.window(), &session, &ui_state, nullptr); + } + } + render_frame(glfw_runtime.window(), &session, &ui_state, &output_path); + } + } + if (session.stream_poller) { + session.stream_poller->stop(); + } + session.map_data.reset(); + for (std::unique_ptr &feed : session.pane_camera_feeds) { + feed.reset(); + } + return 0; + } catch (const std::exception &err) { + std::cerr << err.what() << "\n"; + return 1; + } +} diff --git a/tools/jotpluggler/app.h b/tools/jotpluggler/app.h new file mode 100644 index 00000000000000..872a6973d786c8 --- /dev/null +++ b/tools/jotpluggler/app.h @@ -0,0 +1,887 @@ +#pragma once + +#include "cereal/gen/cpp/log.capnp.h" +#include "imgui.h" +#include "tools/jotpluggler/dbc.h" +#include "tools/jotpluggler/util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ***** +// app options & entry point +// ***** + +struct Options { + std::string layout; + std::string route_name; + std::string data_dir; + std::string output_path; + std::string stream_address = "127.0.0.1"; + int width = 1600; + int height = 900; + bool show = false; + bool sync_load = false; + bool stream = false; + double stream_buffer_seconds = 30.0; +}; + +int run(const Options &options); + +// ***** +// sketch layout & route data +// ***** + +struct PlotRange { + bool valid = false; + double left = 0.0; + double right = 0.0; + double bottom = 0.0; + double top = 1.0; + bool has_y_limit_min = false; + bool has_y_limit_max = false; + double y_limit_min = 0.0; + double y_limit_max = 1.0; +}; + +struct CustomPythonSeries { + std::string linked_source; + std::vector additional_sources; + std::string globals_code; + std::string function_code; +}; + +struct Curve { + std::string name; + std::string label; + std::array color = {160, 170, 180}; + bool visible = true; + bool derivative = false; + double derivative_dt = 0.0; + double value_scale = 1.0; + double value_offset = 0.0; + bool runtime_only = false; + std::optional custom_python; + std::string runtime_error_message; + std::vector xs; + std::vector ys; +}; + +enum class PaneKind : uint8_t { + Plot, + Map, + Camera, +}; + +enum class CameraViewKind : uint8_t { + Road, + Driver, + WideRoad, + QRoad, +}; + +struct Pane { + PaneKind kind = PaneKind::Plot; + CameraViewKind camera_view = CameraViewKind::Road; + std::string title; + PlotRange range; + std::vector curves; +}; + +enum class SplitOrientation { + Horizontal, + Vertical, +}; + +struct WorkspaceNode { + bool is_pane = false; + int pane_index = -1; + SplitOrientation orientation = SplitOrientation::Horizontal; + std::vector sizes; + std::vector children; +}; + +struct WorkspaceTab { + std::string tab_name; + WorkspaceNode root; + std::vector panes; +}; + +struct RouteSeries { + std::string path; + std::vector times; + std::vector values; +}; + +struct CameraSegmentFile { + int segment = -1; + std::string path; +}; + +struct CameraFrameIndexEntry { + double timestamp = 0.0; + int segment = -1; + int decode_index = -1; + uint32_t frame_id = 0; +}; + +struct CameraFeedIndex { + std::vector segment_files; + std::vector entries; +}; + +enum class LogOrigin : uint8_t { + Log, + Android, + Alert, +}; + +struct LogEntry { + double mono_time = 0.0; + double boot_time = 0.0; + double wall_time = 0.0; + uint8_t level = 20; + std::string source; + std::string func; + std::string message; + std::string context; + LogOrigin origin = LogOrigin::Log; +}; + +struct EnumInfo { + std::vector names; +}; + +struct SeriesFormat { + int decimals = 3; + bool integer_like = false; + bool has_negative = false; + int digits_before = 1; + int total_width = 0; + char fmt[16] = "%7.3f"; +}; + +enum class CanServiceKind : uint8_t { + Can, + Sendcan, +}; + +struct CanMessageId { + CanServiceKind service = CanServiceKind::Can; + uint8_t bus = 0; + uint32_t address = 0; + + bool operator==(const CanMessageId &other) const { + return service == other.service && bus == other.bus && address == other.address; + } +}; + +struct CanMessageIdHash { + size_t operator()(const CanMessageId &id) const { + return (static_cast(id.service) << 40) + ^ (static_cast(id.bus) << 32) + ^ static_cast(id.address); + } +}; + +struct CanFrameSample { + double mono_time = 0.0; + uint16_t bus_time = 0; + std::string data; +}; + +struct LiveCanFrame { + double mono_time = 0.0; + uint8_t bus = 0; + uint32_t address = 0; + uint16_t bus_time = 0; + std::string data; +}; + +struct CanMessageData { + CanMessageId id; + std::vector samples; +}; + +struct TimelineEntry { + enum class Type : uint8_t { + None, + Engaged, + AlertInfo, + AlertWarning, + AlertCritical, + }; + + double start_time = 0.0; + double end_time = 0.0; + Type type = Type::None; +}; + +struct GpsPoint { + double time = 0.0; + double lat = 0.0; + double lon = 0.0; + float bearing = 0.0f; + TimelineEntry::Type type = TimelineEntry::Type::None; +}; + +struct GpsTrace { + std::vector points; + double min_lat = 0.0; + double max_lat = 0.0; + double min_lon = 0.0; + double max_lon = 0.0; +}; + +enum class LogSelector : uint8_t { + Auto, + RLog, + QLog, +}; + +struct RouteIdentifier { + std::string dongle_id; + std::string log_id; + int slice_begin = 0; + int slice_end = -1; + bool slice_explicit = false; + LogSelector selector = LogSelector::Auto; + bool selector_explicit = false; + int available_begin = 0; + int available_end = 0; + + bool empty() const { + return dongle_id.empty() || log_id.empty(); + } + + std::string canonical() const { + return empty() ? std::string() : dongle_id + "/" + log_id; + } + + std::string onebox() const { + return empty() ? std::string() : dongle_id + "|" + log_id; + } + + std::string display_slice() const { + const int begin = slice_explicit ? slice_begin : available_begin; + const int end = slice_explicit ? slice_end : available_end; + if (end < 0) { + return std::to_string(begin) + ":"; + } + if (end == begin) { + return std::to_string(begin); + } + return std::to_string(begin) + ":" + std::to_string(end); + } + + char selector_char() const { + switch (selector) { + case LogSelector::RLog: return 'r'; + case LogSelector::QLog: return 'q'; + case LogSelector::Auto: + default: return 'a'; + } + } + + std::string full_spec() const { + if (empty()) return {}; + std::string spec = dongle_id + "/" + log_id; + if (slice_explicit) { + spec += "/"; + spec += display_slice(); + } + if (selector_explicit) { + spec += "/"; + spec.push_back(selector_char()); + } + return spec; + } +}; + +struct RouteData { + std::vector series; + std::vector paths; + std::vector roots; + std::vector can_messages; + CameraFeedIndex road_camera; + CameraFeedIndex driver_camera; + CameraFeedIndex wide_road_camera; + CameraFeedIndex qroad_camera; + GpsTrace gps_trace; + std::vector logs; + std::vector timeline; + std::unordered_map enum_info; + std::unordered_map series_formats; + std::string car_fingerprint; + std::string dbc_name; + RouteIdentifier route_id; + bool has_time_range = false; + double x_min = 0.0; + double x_max = 1.0; +}; + +struct StreamExtractBatch { + std::vector series; + std::vector can_messages; + std::vector logs; + std::vector timeline; + std::unordered_map enum_info; + std::string car_fingerprint; + std::string dbc_name; + bool has_time_offset = false; + double time_offset = 0.0; +}; + +struct SketchLayout { + std::vector tabs; + std::vector roots; + int current_tab_index = 0; +}; + +enum class RouteLoadStage { + Resolving, + DownloadingSegment, + ParsingSegment, + Finished, +}; + +struct RouteLoadProgress { + RouteLoadStage stage = RouteLoadStage::Resolving; + size_t segment_index = 0; + size_t segment_count = 0; + uint64_t current = 0; + uint64_t total = 0; + size_t segments_downloaded = 0; + size_t segments_parsed = 0; + size_t total_segments = 0; + uint64_t bytes_downloaded = 0; + int num_workers = 1; + std::string segment_name; +}; + +using RouteLoadProgressCallback = std::function; + +class StreamAccumulator { +public: + explicit StreamAccumulator(const std::string &dbc_name = {}, std::optional time_offset = std::nullopt); + ~StreamAccumulator(); + + StreamAccumulator(const StreamAccumulator &) = delete; + StreamAccumulator &operator=(const StreamAccumulator &) = delete; + + void setDbcName(const std::string &dbc_name); + void appendEvent(kj::ArrayPtr data); + void appendCanFrames(CanServiceKind service, const std::vector &frames); + StreamExtractBatch takeBatch(); + const std::string &carFingerprint() const; + const std::string &dbc_name() const; + std::optional timeOffset() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +SketchLayout load_sketch_layout(const std::filesystem::path &layout_path); +std::vector available_dbc_names(); +std::vector collect_route_roots_for_paths(const std::vector &paths); +std::optional load_dbc_by_name(const std::string &dbc_name); +std::vector decode_can_messages(const std::vector &can_messages, + const std::string &dbc_name, + std::unordered_map *enum_info = nullptr); +RouteData load_route_data(const std::string &route_name, + const std::string &data_dir = {}, + const std::string &dbc_name = {}, + const RouteLoadProgressCallback &progress = {}); +RouteIdentifier parse_route_identifier(std::string_view route_name); +void rebuild_gps_trace(RouteData *route_data); + +// ***** +// icons +// ***** + +namespace icon { +constexpr const char ARROW_DOWN_UP[] = "\xef\x84\xa7"; +constexpr const char ARROW_LEFT_RIGHT[] = "\xef\x84\xab"; +constexpr const char BAR_CHART[] = "\xef\x85\xbe"; +constexpr const char BOX_ARROW_UP_RIGHT[] = "\xef\x87\x85"; +constexpr const char CLIPBOARD[] = "\xef\x8a\x90"; +constexpr const char CLIPBOARD2[] = "\xef\x9c\xb3"; +constexpr const char DISTRIBUTE_HORIZONTAL[] = "\xef\x8c\x83"; +constexpr const char DISTRIBUTE_VERTICAL[] = "\xef\x8c\x84"; +constexpr const char FILE_EARMARK_IMAGE[] = "\xef\x8d\xad"; +constexpr const char FILES[] = "\xef\x8f\x82"; +constexpr const char INFO_CIRCLE[] = "\xef\x90\xb1"; +constexpr const char PALETTE[] = "\xef\x92\xb1"; +constexpr const char PLUS_SLASH_MINUS[] = "\xef\x9a\xaa"; +constexpr const char SAVE[] = "\xef\x94\xa5"; +constexpr const char SLIDERS[] = "\xef\x95\xab"; +constexpr const char TRASH[] = "\xef\x97\x9e"; +constexpr const char X_SQUARE[] = "\xef\x98\xa9"; +constexpr const char ZOOM_OUT[] = "\xef\x98\xad"; +} // namespace icon + +void icon_add_font(float size, bool merge = false, const ImFont *base_font = nullptr); +bool icon_menu_item(const char *glyph, + const char *label, + const char *shortcut = nullptr, + bool selected = false, + bool enabled = true); + +// ***** +// app session, UI state, & internal API +// ***** + +class AsyncRouteLoader; +class CameraFeedView; +class StreamPoller; +class MapDataManager; + +enum class SessionDataMode : uint8_t { + Route, + Stream, +}; + +enum class StreamSourceKind : uint8_t { + CerealLocal, + CerealRemote, +}; + +struct StreamSourceConfig { + StreamSourceKind kind = StreamSourceKind::CerealLocal; + std::string address = "127.0.0.1"; +}; + +struct BrowserNode { + std::string label; + std::string full_path; + std::vector children; +}; + +struct AppSession { + std::filesystem::path layout_path; + std::filesystem::path autosave_path; + std::string route_name; + std::string data_dir; + std::string dbc_override; + StreamSourceConfig stream_source; + double stream_buffer_seconds = 30.0; + SessionDataMode data_mode = SessionDataMode::Route; + RouteIdentifier route_id; + SketchLayout layout; + RouteData route_data; + std::unordered_map series_by_path; + std::vector browser_nodes; + std::unique_ptr route_loader; + std::unique_ptr stream_poller; + std::array, 4> pane_camera_feeds; + std::unique_ptr map_data; + bool async_route_loading = false; + double next_stream_custom_refresh_time = 0.0; + bool stream_paused = false; + std::optional stream_time_offset; +}; + +struct TabUiState { + struct MapPaneState { + bool initialized = false; + bool follow = false; + float zoom = 1.0f; + double center_lat = 0.0; + double center_lon = 0.0; + }; + + struct CameraPaneState { + bool fit_to_pane = true; + }; + + bool dock_needs_build = true; + int active_pane_index = 0; + int runtime_id = 0; + ImVec2 last_dockspace_size = ImVec2(0.0f, 0.0f); + std::vector map_panes; + std::vector camera_panes; +}; + +struct CustomSeriesEditorState { + bool open = false; + bool open_help = false; + bool request_select = false; + bool selected = false; + bool focus_name = false; + int selected_template = 0; + int selected_additional_source = -1; + std::string name; + std::string linked_source; + std::vector additional_sources; + std::string globals_code; + std::string function_code = "return value"; + std::string preview_label; + std::vector preview_xs; + std::vector preview_ys; + bool preview_is_result = false; +}; + +enum class LogTimeMode : uint8_t { + Route, + Boot, + WallClock, +}; + +struct LogsUiState { + bool selected = false; + bool request_select = false; + bool all_sources = true; + uint32_t enabled_levels_mask = 0b11110; + int expanded_index = -1; + std::string search; + std::vector selected_sources; + double last_auto_scroll_time = -1.0; + LogTimeMode time_mode = LogTimeMode::Route; +}; + +struct AxisLimitsEditorState { + bool open = false; + int pane_index = -1; + double x_min = 0.0; + double x_max = 1.0; + bool y_min_enabled = false; + bool y_max_enabled = false; + double y_min = 0.0; + double y_max = 1.0; +}; + +struct DbcEditorState { + bool open = false; + bool loaded = false; + std::string source_name; + std::filesystem::path source_path; + enum class SourceKind : uint8_t { + None, + Generated, + Opendbc, + }; + SourceKind source_kind = SourceKind::None; + std::string save_name; + std::string text; +}; + +enum class TimelineDragMode : uint8_t { + None, + ScrubCursor, + PanViewport, + ResizeLeft, + ResizeRight, +}; + +struct UndoStack { + static constexpr size_t kMaxHistory = 50; + + std::vector history; + int position = -1; + + void reset(const SketchLayout &layout) { + history.clear(); + history.push_back(layout); + position = 0; + } + + void push(const SketchLayout &layout) { + if (position < 0) { + reset(layout); + return; + } + if (position + 1 < static_cast(history.size())) { + history.resize(static_cast(position + 1)); + } + history.push_back(layout); + if (history.size() > kMaxHistory) { + history.erase(history.begin()); + } + position = static_cast(history.size()) - 1; + } + + bool can_undo() const { + return position > 0; + } + + bool can_redo() const { + return position >= 0 && position + 1 < static_cast(history.size()); + } + + const SketchLayout &undo() { + return history[static_cast(--position)]; + } + + const SketchLayout &redo() { + return history[static_cast(++position)]; + } +}; + +struct UiState { + bool open_open_route = false; + bool open_stream = false; + bool open_load_layout = false; + bool open_save_layout = false; + bool open_preferences = false; + bool open_find_signal = false; + bool request_close = false; + bool request_reset_layout = false; + bool request_save_layout = false; + bool request_new_tab = false; + bool request_duplicate_tab = false; + bool request_close_tab = false; + bool follow_latest = false; + bool has_shared_range = false; + bool has_tracker_time = false; + bool layout_dirty = false; + bool playback_loop = false; + bool playback_playing = false; + bool show_deprecated_fields = false; + bool show_fps_overlay = false; + bool fps_overlay_initialized = false; + bool suppress_range_side_effects = false; + bool browser_nodes_dirty = false; + int active_tab_index = 0; + int next_tab_runtime_id = 1; + int requested_tab_index = -1; + int rename_tab_index = -1; + bool focus_rename_tab_input = false; + std::vector tabs; + std::string route_buffer; + std::string stream_address_buffer; + std::string rename_tab_buffer; + std::string browser_filter; + std::string data_dir_buffer; + std::string load_layout_buffer; + std::string save_layout_buffer; + std::string find_signal_buffer; + std::string selected_browser_path; + std::vector selected_browser_paths; + std::string browser_selection_anchor; + std::string route_slice_buffer; + std::string error_text; + bool open_error_popup = false; + std::string status_text = "Ready"; + std::string route_copy_feedback_text; + double route_copy_feedback_until = 0.0; + bool editing_route_slice = false; + bool focus_route_slice_input = false; + StreamSourceKind stream_source_kind = StreamSourceKind::CerealLocal; + float sidebar_width = 320.0f; + double route_x_min = 0.0; + double route_x_max = 1.0; + double x_view_min = 0.0; + double x_view_max = 1.0; + double tracker_time = 0.0; + double playback_rate = 1.0; + double playback_step = 0.1; + double stream_buffer_seconds = 30.0; + TimelineDragMode timeline_drag_mode = TimelineDragMode::None; + double timeline_drag_anchor_time = 0.0; + double timeline_drag_anchor_x_min = 0.0; + double timeline_drag_anchor_x_max = 0.0; + AxisLimitsEditorState axis_limits; + DbcEditorState dbc_editor; + CustomSeriesEditorState custom_series; + LogsUiState logs; + UndoStack undo; +}; + +// app.cc public API + +const WorkspaceTab *app_active_tab(const SketchLayout &layout, const UiState &state); +WorkspaceTab *app_active_tab(SketchLayout *layout, const UiState &state); +TabUiState *app_active_tab_state(UiState *state); + +void app_push_mono_font(); +void app_pop_mono_font(); +bool app_add_curve_to_active_pane(AppSession *session, UiState *state, const std::string &path); + +std::string app_curve_display_name(const Curve &curve); +std::array app_next_curve_color(const Pane &pane); +const RouteSeries *app_find_route_series(const AppSession &session, const std::string &path); +void app_decimate_samples(const std::vector &xs_in, + const std::vector &ys_in, + int max_points, + std::vector *xs_out, + std::vector *ys_out); +std::optional app_sample_xy_value_at_time(const std::vector &xs, + const std::vector &ys, + bool stairs, + double tm); +void save_layout_json(const SketchLayout &layout, const std::filesystem::path &path); + +// ***** +// browser +// ***** + +void rebuild_route_index(AppSession *session); +void rebuild_browser_nodes(AppSession *session, UiState *state); +SeriesFormat compute_series_format(const std::vector &values, bool enum_like = false); +std::string format_display_value(double display_value, + const SeriesFormat &format, + const EnumInfo *enum_info); +std::vector decode_browser_drag_payload(std::string_view payload); +void collect_visible_leaf_paths(const BrowserNode &node, + const std::string &filter, + std::vector *out); +void draw_browser_node(AppSession *session, + const BrowserNode &node, + UiState *state, + const std::string &filter, + const std::vector &visible_paths); + +// ***** +// custom series +// ***** + +void open_custom_series_editor(UiState *state, const std::string &preferred_source = {}); +std::string preferred_custom_series_source(const Pane &pane); +void refresh_all_custom_curves(AppSession *session, UiState *state); +void draw_custom_series_editor(AppSession *session, UiState *state); + +// ***** +// logs +// ***** + +void draw_logs_tab(AppSession *session, UiState *state); + +// ***** +// map +// ***** + +void draw_map_pane(AppSession *session, UiState *state, Pane *pane, int pane_index); + +// ***** +// runtime (GLFW, async loaders, streaming, camera) +// ***** + +struct GLFWwindow; + +struct RouteLoadSnapshot { + bool active = false; + size_t total_segments = 0; + size_t segments_downloaded = 0; + size_t segments_parsed = 0; +}; + +struct StreamPollSnapshot { + bool active = false; + bool connected = false; + bool paused = false; + StreamSourceKind source_kind = StreamSourceKind::CerealLocal; + std::string source_label; + std::string dbc_name; + std::string car_fingerprint; + double buffer_seconds = 30.0; + uint64_t received_messages = 0; +}; + +class GlfwRuntime { +public: + explicit GlfwRuntime(const Options &options); + ~GlfwRuntime(); + + GlfwRuntime(const GlfwRuntime &) = delete; + GlfwRuntime &operator=(const GlfwRuntime &) = delete; + + GLFWwindow *window() const; + +private: + GLFWwindow *window_ = nullptr; +}; + +class ImGuiRuntime { +public: + explicit ImGuiRuntime(GLFWwindow *window); + ~ImGuiRuntime(); + + ImGuiRuntime(const ImGuiRuntime &) = delete; + ImGuiRuntime &operator=(const ImGuiRuntime &) = delete; +}; + +class TerminalRouteProgress { +public: + explicit TerminalRouteProgress(bool enabled); + ~TerminalRouteProgress(); + + TerminalRouteProgress(const TerminalRouteProgress &) = delete; + TerminalRouteProgress &operator=(const TerminalRouteProgress &) = delete; + + void update(const RouteLoadProgress &progress); + void finish(); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +class AsyncRouteLoader { +public: + explicit AsyncRouteLoader(bool enable_terminal_progress); + ~AsyncRouteLoader(); + + AsyncRouteLoader(const AsyncRouteLoader &) = delete; + AsyncRouteLoader &operator=(const AsyncRouteLoader &) = delete; + + void start(const std::string &route_name, const std::string &data_dir, const std::string &dbc_name); + RouteLoadSnapshot snapshot() const; + bool consume(RouteData *route_data, std::string *error_text); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +class StreamPoller { +public: + StreamPoller(); + ~StreamPoller(); + + StreamPoller(const StreamPoller &) = delete; + StreamPoller &operator=(const StreamPoller &) = delete; + + void start(const StreamSourceConfig &source, + double buffer_seconds, + const std::string &dbc_name, + std::optional time_offset = std::nullopt); + void setPaused(bool paused); + void stop(); + StreamPollSnapshot snapshot() const; + bool consume(StreamExtractBatch *batch, std::string *error_text); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +class CameraFeedView { +public: + CameraFeedView(); + ~CameraFeedView(); + + CameraFeedView(const CameraFeedView &) = delete; + CameraFeedView &operator=(const CameraFeedView &) = delete; + + void setRouteData(const RouteData &route_data); + void setCameraIndex(const CameraFeedIndex &camera_index, CameraViewKind view); + void update(double tracker_time); + void draw(float width, bool loading); + void drawSized(ImVec2 size, bool loading, bool fit_to_pane = false); + +private: + struct Impl; + std::unique_ptr impl_; +}; diff --git a/tools/jotpluggler/browser.cc b/tools/jotpluggler/browser.cc new file mode 100644 index 00000000000000..91e4a707da7942 --- /dev/null +++ b/tools/jotpluggler/browser.cc @@ -0,0 +1,458 @@ +#include "tools/jotpluggler/app.h" + +#include "imgui_internal.h" + +#include +#include +#include + +namespace { + +constexpr float BROWSER_VALUE_WIDTH = 88.0f; + +bool path_matches_filter(const std::string &path, const std::string &lower_filter) { + if (lower_filter.empty()) return true; + return lowercase_copy(path).find(lower_filter) != std::string::npos; +} + +void insert_browser_path(std::vector *nodes, const std::string &path) { + size_t start = 0; + while (start < path.size() && path[start] == '/') { + ++start; + } + std::vector parts; + while (start < path.size()) { + const size_t end = path.find('/', start); + parts.push_back(path.substr(start, end == std::string::npos ? std::string::npos : end - start)); + if (end == std::string::npos) break; + start = end + 1; + } + if (parts.empty()) { + return; + } + + std::vector *current_nodes = nodes; + std::string current_path; + for (size_t i = 0; i < parts.size(); ++i) { + if (!current_path.empty()) { + current_path += "/"; + } + current_path += parts[i]; + auto it = std::find_if(current_nodes->begin(), current_nodes->end(), + [&](const BrowserNode &node) { return node.label == parts[i]; }); + if (it == current_nodes->end()) { + current_nodes->push_back(BrowserNode{.label = parts[i]}); + it = std::prev(current_nodes->end()); + } + if (i + 1 == parts.size()) { + it->full_path = "/" + current_path; + } + current_nodes = &it->children; + } +} + +void sort_browser_nodes(std::vector *nodes) { + std::sort(nodes->begin(), nodes->end(), [](const BrowserNode &a, const BrowserNode &b) { + if (a.children.empty() != b.children.empty()) { + return !a.children.empty(); + } + return a.label < b.label; + }); + for (BrowserNode &node : *nodes) { + sort_browser_nodes(&node.children); + } +} + +std::vector build_browser_tree(const std::vector &paths) { + std::vector nodes; + for (const std::string &path : paths) { + insert_browser_path(&nodes, path); + } + sort_browser_nodes(&nodes); + return nodes; +} + +bool is_deprecated_browser_path(const std::string &path) { + return path.find("DEPRECATED") != std::string::npos || path.find("/deprecated/") != std::string::npos; +} + +std::vector visible_browser_paths(const RouteData &route_data, bool show_deprecated_fields) { + if (show_deprecated_fields) return route_data.paths; + std::vector filtered; + filtered.reserve(route_data.paths.size()); + for (const std::string &path : route_data.paths) { + if (!is_deprecated_browser_path(path)) { + filtered.push_back(path); + } + } + return filtered; +} + +bool browser_selection_contains(const UiState &state, std::string_view path) { + return std::find(state.selected_browser_paths.begin(), state.selected_browser_paths.end(), path) + != state.selected_browser_paths.end(); +} + +std::vector browser_drag_paths(const UiState &state, const std::string &dragged_path) { + if (browser_selection_contains(state, dragged_path) && !state.selected_browser_paths.empty()) { + return state.selected_browser_paths; + } + return {dragged_path}; +} + +std::string encode_browser_drag_payload(const std::vector &paths) { + std::string payload; + for (size_t i = 0; i < paths.size(); ++i) { + if (i != 0) { + payload.push_back('\n'); + } + payload += paths[i]; + } + return payload; +} + +void set_browser_selection_single(UiState *state, const std::string &path) { + state->selected_browser_paths = {path}; + state->selected_browser_path = path; + state->browser_selection_anchor = path; +} + +void toggle_browser_selection(UiState *state, const std::string &path) { + auto it = std::find(state->selected_browser_paths.begin(), state->selected_browser_paths.end(), path); + if (it == state->selected_browser_paths.end()) { + state->selected_browser_paths.push_back(path); + } else { + state->selected_browser_paths.erase(it); + } + state->selected_browser_path = path; + state->browser_selection_anchor = path; + if (state->selected_browser_paths.empty()) { + state->selected_browser_path.clear(); + } +} + +void select_browser_range(UiState *state, const std::vector &visible_paths, const std::string &clicked_path) { + if (visible_paths.empty()) { + set_browser_selection_single(state, clicked_path); + return; + } + + const std::string anchor = state->browser_selection_anchor.empty() ? clicked_path : state->browser_selection_anchor; + const auto anchor_it = std::find(visible_paths.begin(), visible_paths.end(), anchor); + const auto clicked_it = std::find(visible_paths.begin(), visible_paths.end(), clicked_path); + if (clicked_it == visible_paths.end()) { + return; + } + if (anchor_it == visible_paths.end()) { + set_browser_selection_single(state, clicked_path); + return; + } + + const auto [begin_it, end_it] = std::minmax(anchor_it, clicked_it); + std::vector selected; + selected.reserve(static_cast(std::distance(begin_it, end_it)) + 1); + for (auto it = begin_it; it != end_it + 1; ++it) { + selected.push_back(*it); + } + state->selected_browser_paths = std::move(selected); + state->selected_browser_path = clicked_path; +} + +void prune_browser_selection(UiState *state, const std::vector &visible_paths) { + const std::unordered_set visible_set(visible_paths.begin(), visible_paths.end()); + auto is_visible = [&](const std::string &path) { + return visible_set.count(path) > 0; + }; + + state->selected_browser_paths.erase( + std::remove_if(state->selected_browser_paths.begin(), state->selected_browser_paths.end(), + [&](const std::string &path) { return !is_visible(path); }), + state->selected_browser_paths.end()); + + if (!state->selected_browser_path.empty() && !is_visible(state->selected_browser_path)) { + state->selected_browser_path.clear(); + } + if (!state->browser_selection_anchor.empty() && !is_visible(state->browser_selection_anchor)) { + state->browser_selection_anchor.clear(); + } + if (state->selected_browser_paths.empty()) { + state->selected_browser_path.clear(); + } else if (state->selected_browser_path.empty()) { + state->selected_browser_path = state->selected_browser_paths.back(); + } +} + +std::optional sample_route_series_value(const RouteSeries &series, double tm, bool stairs) { + return app_sample_xy_value_at_time(series.times, series.values, stairs, tm); +} + +std::string browser_series_value_text(const AppSession &session, const UiState &state, std::string_view path) { + auto it = session.series_by_path.find(std::string(path)); + if (it == session.series_by_path.end() || it->second == nullptr) return {}; + + const RouteSeries &series = *it->second; + if (series.values.empty()) return {}; + + const auto enum_it = session.route_data.enum_info.find(series.path); + const EnumInfo *enum_info = enum_it == session.route_data.enum_info.end() ? nullptr : &enum_it->second; + const bool stairs = enum_info != nullptr; + + std::optional value; + if (state.has_tracker_time) { + value = sample_route_series_value(series, state.tracker_time, stairs); + } else { + value = series.values.back(); + } + if (!value.has_value()) return {}; + + const auto display_it = session.route_data.series_formats.find(series.path); + const SeriesFormat display_info = display_it == session.route_data.series_formats.end() + ? compute_series_format(series.values, enum_info != nullptr) + : display_it->second; + + return format_display_value(*value, display_info, enum_info); +} + +bool browser_node_matches(const BrowserNode &node, const std::string &filter) { + if (filter.empty()) return true; + if (!node.full_path.empty() && path_matches_filter(node.full_path, filter)) { + return true; + } + for (const BrowserNode &child : node.children) { + if (browser_node_matches(child, filter)) return true; + } + return false; +} + +} // namespace + +namespace { + +int decimals_needed(double value) { + const double abs_value = std::abs(value); + if (abs_value < 1.0e-12) return 0; + for (int decimals = 0; decimals <= 6; ++decimals) { + const double scale = std::pow(10.0, decimals); + if (std::abs(abs_value * scale - std::round(abs_value * scale)) < 1.0e-6) { + return decimals; + } + } + return 6; +} + +void finalize_series_format(SeriesFormat *format) { + format->digits_before = std::max(format->digits_before, 1); + format->decimals = std::clamp(format->decimals, 0, 6); + format->integer_like = format->decimals == 0; + const int sign_width = format->has_negative ? 1 : 0; + const int dot_width = format->decimals > 0 ? 1 : 0; + format->total_width = sign_width + format->digits_before + dot_width + format->decimals; + std::snprintf(format->fmt, sizeof(format->fmt), "%%%d.%df", format->total_width, format->decimals); +} + +} // namespace + +SeriesFormat compute_series_format(const std::vector &values, bool enum_like) { + SeriesFormat format; + if (values.empty()) return format; + + const size_t step = std::max(1, values.size() / 256); + bool saw_finite = false; + bool all_integer = enum_like; + double min_value = 0.0; + double max_value = 0.0; + int max_needed_decimals = 0; + + for (size_t i = 0; i < values.size(); i += step) { + const double value = values[i]; + if (!std::isfinite(value)) continue; + if (!saw_finite) { + min_value = value; + max_value = value; + saw_finite = true; + } else { + min_value = std::min(min_value, value); + max_value = std::max(max_value, value); + } + if (std::abs(value - std::round(value)) > 1.0e-9) { + all_integer = false; + } + if (!all_integer) { + max_needed_decimals = std::max(max_needed_decimals, decimals_needed(value)); + } + } + + if (!saw_finite) return format; + + format.has_negative = min_value < 0.0; + const double peak = std::max(std::abs(min_value), std::abs(max_value)); + format.digits_before = peak < 1.0 ? 1 : static_cast(std::floor(std::log10(peak))) + 1; + + if (enum_like || all_integer) { + format.decimals = 0; + } else if (peak >= 1000.0) { + format.decimals = std::min(max_needed_decimals, 1); + } else if (peak >= 100.0) { + format.decimals = std::min(max_needed_decimals, 2); + } else { + format.decimals = std::min(max_needed_decimals, 4); + } + + finalize_series_format(&format); + return format; +} + +std::string format_display_value(double display_value, + const SeriesFormat &display_info, + const EnumInfo *enum_info) { + if (!std::isfinite(display_value)) return "---"; + if (enum_info != nullptr) { + const int idx = static_cast(std::llround(display_value)); + if (idx >= 0 && std::abs(display_value - static_cast(idx)) < 0.01 + && static_cast(idx) < enum_info->names.size() + && !enum_info->names[static_cast(idx)].empty()) { + return enum_info->names[static_cast(idx)]; + } + } + char buf[64] = {}; + std::snprintf(buf, sizeof(buf), display_info.fmt, display_value); + return buf; +} + +std::vector decode_browser_drag_payload(std::string_view payload) { + std::vector out; + size_t begin = 0; + while (begin <= payload.size()) { + const size_t end = payload.find('\n', begin); + const size_t length = (end == std::string_view::npos ? payload.size() : end) - begin; + if (length > 0) { + out.emplace_back(payload.substr(begin, length)); + } + if (end == std::string_view::npos) break; + begin = end + 1; + } + return out; +} + +void collect_visible_leaf_paths(const BrowserNode &node, + const std::string &filter, + std::vector *out) { + if (!browser_node_matches(node, filter)) { + return; + } + if (node.children.empty()) { + if (!node.full_path.empty()) { + out->push_back(node.full_path); + } + return; + } + for (const BrowserNode &child : node.children) { + collect_visible_leaf_paths(child, filter, out); + } +} + +void rebuild_browser_nodes(AppSession *session, UiState *state) { + const std::vector paths = visible_browser_paths(session->route_data, state->show_deprecated_fields); + session->browser_nodes = build_browser_tree(paths); + prune_browser_selection(state, paths); +} + +void rebuild_route_index(AppSession *session) { + session->series_by_path.clear(); + session->route_data.series_formats.clear(); + for (RouteSeries &series : session->route_data.series) { + session->series_by_path.emplace(series.path, &series); + const bool enum_like = session->route_data.enum_info.find(series.path) != session->route_data.enum_info.end(); + session->route_data.series_formats.emplace(series.path, compute_series_format(series.values, enum_like)); + } +} + +void draw_browser_node(AppSession *session, + const BrowserNode &node, + UiState *state, + const std::string &filter, + const std::vector &visible_paths) { + if (!browser_node_matches(node, filter)) { + return; + } + + if (node.children.empty()) { + const std::string value_text = browser_series_value_text(*session, *state, node.full_path); + const ImGuiStyle &style = ImGui::GetStyle(); + const ImVec2 row_size(std::max(1.0f, ImGui::GetContentRegionAvail().x), ImGui::GetFrameHeight()); + ImGui::PushID(node.full_path.c_str()); + const bool clicked = ImGui::InvisibleButton("##browser_leaf", row_size); + const bool hovered = ImGui::IsItemHovered(); + const ImRect rect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + if (hovered) { + const ImU32 bg = ImGui::GetColorU32(ImGuiCol_HeaderHovered); + draw_list->AddRectFilled(rect.Min, rect.Max, bg, 0.0f); + } + + const float value_right = rect.Max.x - style.FramePadding.x; + const float value_left = value_right - (value_text.empty() ? 0.0f : BROWSER_VALUE_WIDTH); + const float label_left = rect.Min.x + style.FramePadding.x; + const float label_right = value_text.empty() + ? rect.Max.x - style.FramePadding.x + : std::max(label_left + 40.0f, value_left - 10.0f); + ImGui::RenderTextEllipsis(draw_list, + ImVec2(label_left, rect.Min.y + style.FramePadding.y), + ImVec2(label_right, rect.Max.y), + label_right, + node.label.c_str(), + nullptr, + nullptr); + if (!value_text.empty()) { + app_push_mono_font(); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(116, 124, 133)); + ImGui::RenderTextClipped(ImVec2(value_left, rect.Min.y + style.FramePadding.y), + ImVec2(value_right, rect.Max.y), + value_text.c_str(), + nullptr, + nullptr, + ImVec2(1.0f, 0.0f)); + ImGui::PopStyleColor(); + app_pop_mono_font(); + } + + if (clicked) { + const bool shift_down = ImGui::GetIO().KeyShift; + const bool ctrl_down = ImGui::GetIO().KeyCtrl || ImGui::GetIO().KeySuper; + if (shift_down) { + select_browser_range(state, visible_paths, node.full_path); + } else if (ctrl_down) { + toggle_browser_selection(state, node.full_path); + } else { + set_browser_selection_single(state, node.full_path); + } + } + if (hovered && ImGui::IsMouseDoubleClicked(0)) { + set_browser_selection_single(state, node.full_path); + app_add_curve_to_active_pane(session, state, node.full_path); + } + if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID)) { + const std::vector drag_paths = browser_drag_paths(*state, node.full_path); + const std::string payload = encode_browser_drag_payload(drag_paths); + ImGui::SetDragDropPayload("JOTP_BROWSER_PATHS", payload.c_str(), payload.size() + 1); + if (drag_paths.size() == 1) { + ImGui::TextUnformatted(drag_paths.front().c_str()); + } else { + ImGui::Text("%zu timeseries", drag_paths.size()); + ImGui::TextUnformatted(drag_paths.front().c_str()); + } + ImGui::EndDragDropSource(); + } + ImGui::PopID(); + return; + } + + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_SpanAvailWidth; + const bool open = ImGui::TreeNodeEx(node.label.c_str(), flags); + if (open) { + for (const BrowserNode &child : node.children) { + draw_browser_node(session, child, state, filter, visible_paths); + } + ImGui::TreePop(); + } +} diff --git a/tools/jotpluggler/camera.cc b/tools/jotpluggler/camera.cc new file mode 100644 index 00000000000000..24a35d87943597 --- /dev/null +++ b/tools/jotpluggler/camera.cc @@ -0,0 +1,54 @@ +#include "tools/jotpluggler/camera.h" + +#include "imgui.h" +#include "imgui_internal.h" + +namespace { + +bool draw_camera_fit_toggle_overlay(bool fit_to_pane) { + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 content_min = ImGui::GetWindowContentRegionMin(); + const ImRect rect(ImVec2(window_pos.x + content_min.x + 8.0f, window_pos.y + content_min.y + 8.0f), + ImVec2(window_pos.x + content_min.x + 58.0f, window_pos.y + content_min.y + 28.0f)); + const bool hovered = ImGui::IsMouseHoveringRect(rect.Min, rect.Max, false); + const bool held = hovered && ImGui::IsMouseDown(ImGuiMouseButton_Left); + if (hovered) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(rect.Min, rect.Max, hovered ? IM_COL32(255, 255, 255, 234) : IM_COL32(255, 255, 255, 214), 4.0f); + draw_list->AddRect(rect.Min, rect.Max, IM_COL32(184, 189, 196, 255), 4.0f, 0, 1.0f); + const ImRect box(ImVec2(rect.Min.x + 6.0f, rect.Min.y + 4.0f), ImVec2(rect.Min.x + 18.0f, rect.Min.y + 16.0f)); + draw_list->AddRect(box.Min, box.Max, IM_COL32(112, 120, 129, 255), 2.0f, 0, 1.0f); + if (fit_to_pane) { + draw_list->AddLine(ImVec2(box.Min.x + 2.5f, box.Min.y + 6.5f), ImVec2(box.Min.x + 5.5f, box.Max.y - 2.5f), IM_COL32(60, 111, 202, 255), 1.8f); + draw_list->AddLine(ImVec2(box.Min.x + 5.5f, box.Max.y - 2.5f), ImVec2(box.Max.x - 2.5f, box.Min.y + 2.5f), IM_COL32(60, 111, 202, 255), 1.8f); + } + draw_list->AddText(ImVec2(box.Max.x + 6.0f, rect.Min.y + 3.0f), IM_COL32(72, 79, 88, 255), "Fit"); + return hovered && !held && ImGui::IsMouseReleased(ImGuiMouseButton_Left); +} + +} // namespace + +void draw_camera_pane(AppSession *session, UiState *state, TabUiState *tab_state, int pane_index, const Pane &pane) { + CameraFeedView *feed = session->pane_camera_feeds[static_cast(pane.camera_view)].get(); + if (feed == nullptr) { + ImGui::TextDisabled("Camera unavailable"); + return; + } + + const bool fit_to_pane = tab_state != nullptr + && pane_index >= 0 + && pane_index < static_cast(tab_state->camera_panes.size()) + ? tab_state->camera_panes[static_cast(pane_index)].fit_to_pane + : true; + if (state->has_tracker_time) { + feed->update(state->tracker_time); + } + feed->drawSized(ImGui::GetContentRegionAvail(), session->async_route_loading, fit_to_pane); + if (tab_state != nullptr + && pane_index >= 0 + && pane_index < static_cast(tab_state->camera_panes.size()) + && draw_camera_fit_toggle_overlay(fit_to_pane)) { + tab_state->camera_panes[static_cast(pane_index)].fit_to_pane = !fit_to_pane; + } +} diff --git a/tools/jotpluggler/camera.h b/tools/jotpluggler/camera.h new file mode 100644 index 00000000000000..666e335af89d43 --- /dev/null +++ b/tools/jotpluggler/camera.h @@ -0,0 +1,5 @@ +#pragma once + +#include "tools/jotpluggler/app.h" + +void draw_camera_pane(AppSession *session, UiState *state, TabUiState *tab_state, int pane_index, const Pane &pane); diff --git a/tools/jotpluggler/common.cc b/tools/jotpluggler/common.cc new file mode 100644 index 00000000000000..8f696657bd5490 --- /dev/null +++ b/tools/jotpluggler/common.cc @@ -0,0 +1,187 @@ +#include "tools/jotpluggler/common.h" + +#include +#include +#include + +namespace { + +std::string format_coord(const GpsPoint &point) { + return util::string_format("%.5f,%.5f", point.lat, point.lon); +} + +} // namespace + +const CameraViewSpec &camera_view_spec(CameraViewKind view) { + auto it = std::find_if(kCameraViewSpecs.begin(), kCameraViewSpecs.end(), [&](const CameraViewSpec &spec) { + return spec.view == view; + }); + return it != kCameraViewSpecs.end() ? *it : kCameraViewSpecs.front(); +} + +const CameraViewSpec *camera_view_spec_from_special_item(std::string_view item_id) { + auto it = std::find_if(kCameraViewSpecs.begin(), kCameraViewSpecs.end(), [&](const CameraViewSpec &spec) { + return item_id == spec.special_item_id; + }); + return it != kCameraViewSpecs.end() ? &*it : nullptr; +} + +const CameraViewSpec *camera_view_spec_from_layout_name(std::string_view layout_name) { + auto it = std::find_if(kCameraViewSpecs.begin(), kCameraViewSpecs.end(), [&](const CameraViewSpec &spec) { + return layout_name == spec.layout_name; + }); + return it != kCameraViewSpecs.end() ? &*it : nullptr; +} + +const SpecialItemSpec *special_item_spec(std::string_view item_id) { + auto it = std::find_if(kSpecialItemSpecs.begin(), kSpecialItemSpecs.end(), [&](const SpecialItemSpec &spec) { + return item_id == spec.id; + }); + return it != kSpecialItemSpecs.end() ? &*it : nullptr; +} + +const char *special_item_label(std::string_view item_id) { + const SpecialItemSpec *spec = special_item_spec(item_id); + return spec != nullptr ? spec->label : "Item"; +} + +bool pane_kind_is_special(PaneKind kind) { + return kind == PaneKind::Map || kind == PaneKind::Camera; +} + +bool is_default_special_title(std::string_view title) { + if (title == "Map") return true; + return std::any_of(kCameraViewSpecs.begin(), kCameraViewSpecs.end(), [&](const CameraViewSpec &spec) { + return title == spec.label; + }); +} + +CameraViewKind sidebar_preview_camera_view(const AppSession &session) { + return session.route_data.road_camera.entries.empty() && !session.route_data.qroad_camera.entries.empty() + ? CameraViewKind::QRoad + : CameraViewKind::Road; +} + +const std::filesystem::path &repo_root() { + static const std::filesystem::path root(JOTP_REPO_ROOT); + return root; +} + +ImU32 timeline_entry_color(TimelineEntry::Type type, float alpha) { + return timeline_entry_color(type, alpha, {111, 143, 175}); +} + +ImU32 timeline_entry_color(TimelineEntry::Type type, float alpha, std::array none_color) { + switch (type) { + case TimelineEntry::Type::Engaged: + return ImGui::GetColorU32(color_rgb(0, 163, 108, alpha)); + case TimelineEntry::Type::AlertInfo: + return ImGui::GetColorU32(color_rgb(255, 195, 0, alpha)); + case TimelineEntry::Type::AlertWarning: + case TimelineEntry::Type::AlertCritical: + return ImGui::GetColorU32(color_rgb(199, 0, 57, alpha)); + case TimelineEntry::Type::None: + default: + return ImGui::GetColorU32(color_rgb(none_color, alpha)); + } +} + +const char *timeline_entry_label(TimelineEntry::Type type) { + static constexpr const char *kLabels[] = { + "disengaged", + "engaged", + "alert info", + "alert warning", + "alert critical", + }; + const size_t index = static_cast(type); + return index < std::size(kLabels) ? kLabels[index] : kLabels[0]; +} + +TimelineEntry::Type timeline_type_at_time(const std::vector &timeline, double time_value) { + for (const TimelineEntry &entry : timeline) { + if (time_value >= entry.start_time && time_value <= entry.end_time) { + return entry.type; + } + } + return TimelineEntry::Type::None; +} + +std::string normalize_stream_address(std::string address) { + return is_local_stream_address(address) ? "127.0.0.1" : address; +} + +const char *stream_source_kind_label(StreamSourceKind kind) { + static constexpr const char *kLabels[] = { + "Local (MSGQ)", + "Remote (ZMQ)", + }; + const size_t index = static_cast(kind); + return index < std::size(kLabels) ? kLabels[index] : kLabels[0]; +} + +std::string stream_source_target_label(const StreamSourceConfig &source) { + switch (source.kind) { + case StreamSourceKind::CerealRemote: + return normalize_stream_address(source.address); + case StreamSourceKind::CerealLocal: + default: + return "127.0.0.1"; + } +} + +bool env_flag_enabled(const char *name, bool default_value) { + const char *raw = std::getenv(name); + if (raw == nullptr || raw[0] == '\0') { + return default_value; + } + const std::string value = lowercase_copy(util::strip(raw)); + return !(value == "0" || value == "false" || value == "no" || value == "off"); +} + +bool app_begin_popup(const char *str_id, ImGuiWindowFlags flags) { + return ImGui::BeginPopup(str_id, flags | ImGuiWindowFlags_NoMove); +} + +bool app_begin_popup_modal(const char *name, bool *p_open, ImGuiWindowFlags flags) { + return ImGui::BeginPopupModal(name, p_open, flags | ImGuiWindowFlags_NoMove); +} + +void open_external_url(std::string_view url) { +#ifdef __APPLE__ + const std::string command = "open " + shell_quote(url) + " &"; +#else + const std::string command = "xdg-open " + shell_quote(url) + " >/dev/null 2>&1 &"; +#endif + util::check_system(command); +} + +std::string route_useradmin_url(const RouteIdentifier &route_id) { + return route_id.empty() ? std::string() + : "https://useradmin.comma.ai/?onebox=" + route_id.dongle_id + "%7C" + route_id.log_id; +} + +std::string route_connect_url(const RouteIdentifier &route_id) { + return route_id.empty() ? std::string() + : "https://connect.comma.ai/" + route_id.canonical(); +} + +std::string route_google_maps_url(const GpsTrace &trace) { + if (trace.points.size() < 2) { + return {}; + } + + const std::string prefix = "https://www.google.com/maps/dir/?api=1&travelmode=driving&origin=" + + format_coord(trace.points.front()) + "&destination=" + format_coord(trace.points.back()); + for (size_t n = std::min(9, trace.points.size() > 2 ? trace.points.size() - 2 : 0); ; --n) { + std::string url = prefix; + if (n > 0) { + url += "&waypoints="; + for (size_t i = 0; i < n; ++i) { + if (i) url += "%7C"; + url += format_coord(trace.points[1 + ((trace.points.size() - 2) * (i + 1)) / (n + 1)]); + } + } + if (url.size() <= 1900 || n == 0) return url; + } +} diff --git a/tools/jotpluggler/common.h b/tools/jotpluggler/common.h new file mode 100644 index 00000000000000..14db83fd337eb8 --- /dev/null +++ b/tools/jotpluggler/common.h @@ -0,0 +1,67 @@ +#pragma once + +#include "tools/jotpluggler/app.h" + +#include +#include + +struct CameraViewSpec { + CameraViewKind view = CameraViewKind::Road; + const char *label = ""; + const char *runtime_name = ""; + const char *layout_name = ""; + const char *special_item_id = ""; + CameraFeedIndex RouteData::*route_member = nullptr; +}; + +struct SpecialItemSpec { + const char *id = ""; + const char *label = ""; + PaneKind kind = PaneKind::Plot; + CameraViewKind camera_view = CameraViewKind::Road; +}; + +inline constexpr std::array kCameraViewSpecs = {{ + {CameraViewKind::Road, "Road Camera", "road", "road", "camera_road", &RouteData::road_camera}, + {CameraViewKind::Driver, "Driver Camera", "driver", "driver", "camera_driver", &RouteData::driver_camera}, + {CameraViewKind::WideRoad, "Wide Road Camera", "wide", "wide_road", "camera_wide_road", &RouteData::wide_road_camera}, + {CameraViewKind::QRoad, "qRoad Camera", "qroad", "qroad", "camera_qroad", &RouteData::qroad_camera}, +}}; + +inline constexpr std::array kSpecialItemSpecs = {{ + {"map", "Map", PaneKind::Map, CameraViewKind::Road}, + {kCameraViewSpecs[0].special_item_id, kCameraViewSpecs[0].label, PaneKind::Camera, kCameraViewSpecs[0].view}, + {kCameraViewSpecs[1].special_item_id, kCameraViewSpecs[1].label, PaneKind::Camera, kCameraViewSpecs[1].view}, + {kCameraViewSpecs[2].special_item_id, kCameraViewSpecs[2].label, PaneKind::Camera, kCameraViewSpecs[2].view}, + {kCameraViewSpecs[3].special_item_id, kCameraViewSpecs[3].label, PaneKind::Camera, kCameraViewSpecs[3].view}, +}}; + +const CameraViewSpec &camera_view_spec(CameraViewKind view); +const CameraViewSpec *camera_view_spec_from_special_item(std::string_view item_id); +const CameraViewSpec *camera_view_spec_from_layout_name(std::string_view layout_name); + +const SpecialItemSpec *special_item_spec(std::string_view item_id); +const char *special_item_label(std::string_view item_id); + +bool pane_kind_is_special(PaneKind kind); +bool is_default_special_title(std::string_view title); +CameraViewKind sidebar_preview_camera_view(const AppSession &session); +const std::filesystem::path &repo_root(); + +ImU32 timeline_entry_color(TimelineEntry::Type type, float alpha = 1.0f); +ImU32 timeline_entry_color(TimelineEntry::Type type, float alpha, std::array none_color); +const char *timeline_entry_label(TimelineEntry::Type type); +TimelineEntry::Type timeline_type_at_time(const std::vector &timeline, double time_value); +std::string normalize_stream_address(std::string address); +const char *stream_source_kind_label(StreamSourceKind kind); +std::string stream_source_target_label(const StreamSourceConfig &source); + +bool env_flag_enabled(const char *name, bool default_value = false); +bool app_begin_popup(const char *str_id, ImGuiWindowFlags flags = 0); +bool app_begin_popup_modal(const char *name, + bool *p_open = nullptr, + ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize); +void open_external_url(std::string_view url); +std::string route_useradmin_url(const RouteIdentifier &route_id); +std::string route_connect_url(const RouteIdentifier &route_id); +std::string route_google_maps_url(const GpsTrace &trace); diff --git a/tools/jotpluggler/custom_series.cc b/tools/jotpluggler/custom_series.cc new file mode 100644 index 00000000000000..aabf78a0dbc59e --- /dev/null +++ b/tools/jotpluggler/custom_series.cc @@ -0,0 +1,750 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" + +#include "implot.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "json11/json11.hpp" + +namespace fs = std::filesystem; + +namespace { + +struct PythonEvalResult { + std::vector xs; + std::vector ys; +}; + +struct CustomSeriesTemplate { + const char *name; + const char *globals_code; + const char *function_code; + const char *preview_text; + int required_additional_sources; + const char *requirement_text; +}; + +void write_binary_vector(const fs::path &path, const std::vector &values) { + write_file_or_throw(path, values.data(), values.size() * sizeof(double)); +} + +std::vector read_binary_vector(const fs::path &path) { + const std::string raw = read_file_or_throw(path); + if (raw.size() % sizeof(double) != 0) { + throw std::runtime_error("Invalid binary series file: " + path.string()); + } + std::vector values(raw.size() / sizeof(double)); + if (!values.empty()) { + std::memcpy(values.data(), raw.data(), raw.size()); + } + return values; +} + +void write_text_file(const fs::path &path, std::string_view text) { + write_file_or_throw(path, text); +} + +fs::path create_custom_series_temp_dir() { + const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + const fs::path dir = fs::temp_directory_path() / ("jotpluggler_math_" + std::to_string(::getpid()) + "_" + std::to_string(stamp)); + fs::create_directories(dir); + return dir; +} + +void reset_custom_series_editor(CustomSeriesEditorState *editor) { + *editor = CustomSeriesEditorState{}; +} + +bool add_additional_source(CustomSeriesEditorState *editor, const std::string &path) { + if (path.empty() || path == editor->linked_source) return false; + if (std::find(editor->additional_sources.begin(), editor->additional_sources.end(), path) != editor->additional_sources.end()) { + return false; + } + editor->additional_sources.push_back(path); + return true; +} + +std::string next_custom_curve_name(const Pane &pane) { + std::set used; + for (const Curve &curve : pane.curves) { + if (!curve.label.empty()) { + used.insert(curve.label); + } + if (!curve.name.empty()) { + used.insert(curve.name); + } + } + for (int i = 1; i < 1000; ++i) { + const std::string candidate = "series" + std::to_string(i); + if (used.find(candidate) == used.end()) { + return candidate; + } + } + return "series"; +} + +Curve make_custom_curve(const Pane &pane, + const std::string &name, + const CustomPythonSeries &spec, + PythonEvalResult result) { + Curve curve; + curve.name = name; + curve.label = name; + curve.color = app_next_curve_color(pane); + curve.runtime_only = true; + curve.custom_python = spec; + curve.xs = std::move(result.xs); + curve.ys = std::move(result.ys); + return curve; +} + +bool upsert_custom_curve_in_pane(WorkspaceTab *tab, int pane_index, Curve curve) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return false; + } + Pane &pane = tab->panes[static_cast(pane_index)]; + for (Curve &existing : pane.curves) { + if (existing.runtime_only && existing.name == curve.name) { + existing.visible = true; + existing.label = curve.label; + existing.custom_python = curve.custom_python; + existing.xs = std::move(curve.xs); + existing.ys = std::move(curve.ys); + return false; + } + } + pane.curves.push_back(std::move(curve)); + return true; +} + +std::set collect_custom_series_paths(const CustomPythonSeries &spec, + std::string_view globals_code, + std::string_view function_code) { + std::set paths; + if (!spec.linked_source.empty()) { + paths.insert(spec.linked_source); + } + paths.insert(spec.additional_sources.begin(), spec.additional_sources.end()); + + static const std::regex kPathRegex(R"([tv]\(\s*["']([^"']+)["']\s*\))"); + const auto collect_from = [&](std::string_view code) { + std::string owned(code); + for (std::sregex_iterator it(owned.begin(), owned.end(), kPathRegex), end; it != end; ++it) { + paths.insert((*it)[1].str()); + } + }; + collect_from(globals_code); + collect_from(function_code); + return paths; +} + +PythonEvalResult evaluate_custom_python_series(const AppSession &session, + const CustomPythonSeries &spec) { + const std::set referenced_paths = + collect_custom_series_paths(spec, spec.globals_code, spec.function_code); + if (referenced_paths.empty()) throw std::runtime_error("No input series referenced. Set an input timeseries or reference route paths in code."); + + const fs::path temp_dir = create_custom_series_temp_dir(); + try { + const fs::path globals_path = temp_dir / "globals.py"; + const fs::path code_path = temp_dir / "code.py"; + const fs::path manifest_path = temp_dir / "manifest.json"; + const fs::path out_t_path = temp_dir / "result.t.bin"; + const fs::path out_v_path = temp_dir / "result.v.bin"; + + write_text_file(globals_path, spec.globals_code); + write_text_file(code_path, spec.function_code); + + json11::Json::array paths_json(session.route_data.paths.begin(), session.route_data.paths.end()); + json11::Json::array additional_json(spec.additional_sources.begin(), spec.additional_sources.end()); + json11::Json::array series_json; + size_t series_index = 0; + for (const std::string &path : referenced_paths) { + const RouteSeries *series = app_find_route_series(session, path); + if (series == nullptr || series->times.size() < 2 || series->times.size() != series->values.size()) { + throw std::runtime_error("Missing route series " + path); + } + const std::string prefix = "series_" + std::to_string(series_index++); + const fs::path time_path = temp_dir / (prefix + ".t.bin"); + const fs::path value_path = temp_dir / (prefix + ".v.bin"); + write_binary_vector(time_path, series->times); + write_binary_vector(value_path, series->values); + series_json.push_back(json11::Json::object{ + {"path", path}, {"t", time_path.string()}, {"v", value_path.string()}}); + } + const json11::Json manifest_json = json11::Json::object{ + {"paths", std::move(paths_json)}, + {"linked_source", spec.linked_source}, + {"additional_sources", std::move(additional_json)}, + {"series", std::move(series_json)}, + }; + write_text_file(manifest_path, manifest_json.dump()); + + const CommandResult process = run_process_capture_output({ + "python3", + (repo_root() / "tools" / "jotpluggler" / "math_eval.py").string(), + manifest_path.string(), + globals_path.string(), + code_path.string(), + out_t_path.string(), + out_v_path.string(), + }); + if (process.exit_code != 0) { + const std::string error_text = util::strip(process.output); + throw std::runtime_error(error_text.empty() ? "Python evaluation failed" : error_text); + } + + PythonEvalResult result; + result.xs = read_binary_vector(out_t_path); + result.ys = read_binary_vector(out_v_path); + if (result.xs.size() < 2 || result.xs.size() != result.ys.size()) { + throw std::runtime_error("Custom series returned invalid output"); + } + fs::remove_all(temp_dir); + return result; + } catch (...) { + std::error_code ignore_error; + fs::remove_all(temp_dir, ignore_error); + throw; + } +} + +void refresh_custom_curve_samples(AppSession *session, UiState *state, Curve *curve) { + if (!curve->custom_python.has_value()) { + return; + } + if (!session->route_data.has_time_range || session->route_data.series.empty()) { + curve->runtime_error_message.clear(); + curve->xs.clear(); + curve->ys.clear(); + return; + } + try { + PythonEvalResult result = evaluate_custom_python_series(*session, *curve->custom_python); + curve->runtime_error_message.clear(); + curve->xs = std::move(result.xs); + curve->ys = std::move(result.ys); + } catch (const std::exception &err) { + curve->xs.clear(); + curve->ys.clear(); + const std::string err_text = err.what(); + if (session->data_mode == SessionDataMode::Stream && util::starts_with(err_text, "Missing route series ")) { + curve->runtime_error_message = err_text; + return; + } + const std::string error_message = std::string("Failed to evaluate custom series \"") + + app_curve_display_name(*curve) + "\":\n\n" + err_text; + if (curve->runtime_error_message != error_message) { + curve->runtime_error_message = error_message; + state->error_text = error_message; + state->open_error_popup = true; + } + } +} + +const std::array &custom_series_templates() { + static constexpr std::array kTemplates = {{ + { + .name = "Derivative", + .globals_code = "", + .function_code = "return np.gradient(value, time)", + .preview_text = "return np.gradient(value, time)", + .required_additional_sources = 0, + .requirement_text = "", + }, + { + .name = "Difference", + .globals_code = "", + .function_code = "return value - v1", + .preview_text = "Requires one additional source timeseries.\n\nreturn value - v1", + .required_additional_sources = 1, + .requirement_text = "Difference requires one additional source timeseries for v1.", + }, + { + .name = "Smoothing", + .globals_code = "window = 20\nweights = np.ones(window) / window", + .function_code = "return np.convolve(value, weights, mode='same')", + .preview_text = "window = 20\nweights = np.ones(window) / window\n\nreturn np.convolve(value, weights, mode='same')", + .required_additional_sources = 0, + .requirement_text = "", + }, + { + .name = "Integral", + .globals_code = "", + .function_code = "dt = np.mean(np.diff(time))\nreturn np.cumsum(value) * dt", + .preview_text = "dt = np.mean(np.diff(time))\nreturn np.cumsum(value) * dt", + .required_additional_sources = 0, + .requirement_text = "", + }, + }}; + return kTemplates; +} + +void draw_custom_series_help_popup(CustomSeriesEditorState *editor) { + if (editor->open_help) { + ImGui::OpenPopup("Custom Series Help"); + editor->open_help = false; + } + if (!app_begin_popup_modal("Custom Series Help")) { + return; + } + ImGui::TextUnformatted("Available variables"); + ImGui::Separator(); + ImGui::BulletText("np: numpy"); + ImGui::BulletText("t(path), v(path): timestamps and values for a route series"); + ImGui::BulletText("paths: all available route series paths"); + ImGui::BulletText("time, value: linked input timeseries"); + ImGui::BulletText("t1, v1, t2, v2, ...: additional source timeseries"); + ImGui::Spacing(); + ImGui::TextWrapped("Write either a single expression like \"return np.gradient(value, time)\" " + "or a multi-line Python body that returns an array or a (times, values) tuple."); + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void draw_custom_series_preview(const AppSession &session, CustomSeriesEditorState *editor) { + std::vector preview_xs; + std::vector preview_ys; + std::string preview_label = editor->preview_label; + if (editor->preview_is_result && editor->preview_xs.size() > 1 && editor->preview_xs.size() == editor->preview_ys.size()) { + preview_xs = editor->preview_xs; + preview_ys = editor->preview_ys; + if (preview_label.empty()) { + preview_label = "Result preview"; + } + } else if (!editor->linked_source.empty()) { + if (const RouteSeries *series = app_find_route_series(session, editor->linked_source); series != nullptr + && series->times.size() > 1 && series->times.size() == series->values.size()) { + preview_xs = series->times; + preview_ys = series->values; + preview_label = "Input preview (not result)"; + } + } + + if (!preview_xs.empty() && preview_xs.size() == preview_ys.size()) { + std::vector plot_xs; + std::vector plot_ys; + app_decimate_samples(preview_xs, preview_ys, 1200, &plot_xs, &plot_ys); + const double preview_x_min = preview_xs.front(); + const double preview_x_max = preview_xs.back() > preview_xs.front() + ? preview_xs.back() + : preview_xs.front() + 1e-6; + std::string plot_id = "##custom_series_preview"; + if (editor->preview_is_result) { + plot_id += "_result_"; + plot_id += editor->name.empty() ? preview_label : editor->name; + } else if (!editor->linked_source.empty()) { + plot_id += "_input_"; + plot_id += editor->linked_source; + } + ImGui::TextUnformatted(preview_label.c_str()); + if (!editor->linked_source.empty() && !editor->preview_is_result) { + ImGui::SameLine(); + ImGui::TextDisabled("%s", editor->linked_source.c_str()); + } + if (ImPlot::BeginPlot(plot_id.c_str(), + ImVec2(-1.0f, std::max(180.0f, ImGui::GetContentRegionAvail().y - 6.0f)), + ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoLegend)) { + ImPlot::SetupAxes(nullptr, nullptr, ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_NoHighlight, + ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_NoHighlight | ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit); + ImPlot::SetupAxisLimitsConstraints(ImAxis_X1, preview_x_min, preview_x_max); + ImPlot::SetupAxisLimits(ImAxis_X1, preview_x_min, preview_x_max, ImPlotCond_Once); + ImPlot::SetupAxisFormat(ImAxis_X1, "%.1f"); + ImPlot::SetupAxisFormat(ImAxis_Y1, "%.6g"); + ImPlotSpec spec; + spec.LineColor = color_rgb(35, 107, 180); + spec.LineWeight = 2.0f; + ImPlot::PlotLine("##custom_preview_line", plot_xs.data(), plot_ys.data(), static_cast(plot_xs.size()), spec); + ImPlot::EndPlot(); + } + } else { + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 72.0f); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(116, 124, 133)); + ImGui::TextWrapped("Choose an input timeseries or click Preview to evaluate the custom result."); + ImGui::PopStyleColor(); + } +} + +std::string custom_series_name_status(const Pane &pane, std::string_view name) { + const std::string trimmed = util::strip(std::string(name)); + if (trimmed.empty()) return "name required"; + if (!trimmed.empty() && trimmed.front() == '/') { + return "cannot start with /"; + } + for (const Curve &curve : pane.curves) { + if (curve.runtime_only && curve.name == trimmed) return "updates existing curve"; + } + return "new curve"; +} + +const CustomSeriesTemplate &selected_custom_series_template(const CustomSeriesEditorState &editor) { + const auto &templates = custom_series_templates(); + return templates[static_cast(std::clamp(editor.selected_template, 0, static_cast(templates.size()) - 1))]; +} + +bool custom_series_template_ready(const CustomSeriesEditorState &editor) { + const CustomSeriesTemplate &templ = selected_custom_series_template(editor); + return !editor.linked_source.empty() + && static_cast(editor.additional_sources.size()) >= templ.required_additional_sources; +} + +bool prepare_custom_series_spec(CustomSeriesEditorState *editor, + UiState *state, + bool require_name, + CustomPythonSeries *out_spec) { + editor->name = util::strip(editor->name); + editor->linked_source = util::strip(editor->linked_source); + for (std::string &path : editor->additional_sources) { + path = util::strip(path); + } + editor->additional_sources.erase( + std::remove_if(editor->additional_sources.begin(), editor->additional_sources.end(), + [&](const std::string &path) { return path.empty() || path == editor->linked_source; }), + editor->additional_sources.end()); + + if (require_name && editor->name.empty()) { + state->error_text = "Custom series name is required."; + state->open_error_popup = true; + return false; + } + if (require_name && !editor->name.empty() && editor->name.front() == '/') { + state->error_text = "Custom series names may not start with '/'."; + state->open_error_popup = true; + return false; + } + + *out_spec = CustomPythonSeries{ + .linked_source = editor->linked_source, + .additional_sources = editor->additional_sources, + .globals_code = editor->globals_code, + .function_code = editor->function_code, + }; + return true; +} + +bool preview_custom_series_editor(AppSession *session, UiState *state) { + CustomSeriesEditorState &editor = state->custom_series; + const CustomSeriesTemplate &templ = selected_custom_series_template(editor); + if (editor.linked_source.empty()) { + state->error_text = "Choose an input timeseries before previewing."; + state->open_error_popup = true; + state->status_text = "Custom series preview failed"; + return false; + } + if (static_cast(editor.additional_sources.size()) < templ.required_additional_sources) { + state->error_text = templ.requirement_text; + state->open_error_popup = true; + state->status_text = "Custom series preview failed"; + return false; + } + CustomPythonSeries spec; + if (!prepare_custom_series_spec(&editor, state, false, &spec)) return false; + + try { + PythonEvalResult result = evaluate_custom_python_series(*session, spec); + editor.preview_label = editor.name.empty() ? "Result preview" : editor.name; + editor.preview_xs = std::move(result.xs); + editor.preview_ys = std::move(result.ys); + editor.preview_is_result = true; + state->status_text = "Previewed custom series"; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Custom series preview failed"; + return false; + } +} + +bool apply_custom_series_editor(AppSession *session, UiState *state) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + if (tab == nullptr || tab_state == nullptr) { + state->status_text = "No active pane"; + return false; + } + if (tab_state->active_pane_index < 0 || tab_state->active_pane_index >= static_cast(tab->panes.size())) { + state->status_text = "No active pane"; + return false; + } + + CustomSeriesEditorState &editor = state->custom_series; + CustomPythonSeries spec; + if (!prepare_custom_series_spec(&editor, state, true, &spec)) return false; + + try { + PythonEvalResult result = evaluate_custom_python_series(*session, spec); + const SketchLayout before_layout = session->layout; + Pane &pane = tab->panes[static_cast(tab_state->active_pane_index)]; + editor.preview_label = editor.name; + editor.preview_xs = result.xs; + editor.preview_ys = result.ys; + editor.preview_is_result = true; + const bool inserted = upsert_custom_curve_in_pane(tab, + tab_state->active_pane_index, + make_custom_curve(pane, editor.name, spec, std::move(result))); + state->undo.push(before_layout); + state->status_text = inserted ? "Created custom series " + editor.name + : "Updated custom series " + editor.name; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Custom series failed"; + return false; + } +} + +} // namespace + +void open_custom_series_editor(UiState *state, const std::string &preferred_source) { + CustomSeriesEditorState &editor = state->custom_series; + if (!editor.open && editor.name.empty() && editor.linked_source.empty() && editor.function_code == "return value") { + editor.focus_name = true; + } + if (editor.linked_source.empty() && !preferred_source.empty()) { + editor.linked_source = preferred_source; + } + editor.open = true; + editor.request_select = true; +} + +std::string preferred_custom_series_source(const Pane &pane) { + for (const Curve &curve : pane.curves) { + if (!curve.name.empty() && curve.name.front() == '/') { + return curve.name; + } + if (curve.custom_python.has_value() && !curve.custom_python->linked_source.empty()) { + return curve.custom_python->linked_source; + } + } + return {}; +} + +void refresh_all_custom_curves(AppSession *session, UiState *state) { + for (WorkspaceTab &tab : session->layout.tabs) { + for (Pane &pane : tab.panes) { + for (Curve &curve : pane.curves) { + refresh_custom_curve_samples(session, state, &curve); + } + } + } +} + +void draw_editor_source_panel(UiState *state, CustomSeriesEditorState &editor) { + ImGui::TextWrapped("Input timeseries. Provides arguments time and value:"); + ImGui::SetNextItemWidth(-FLT_MIN); + input_text_string("##custom_linked_source", &editor.linked_source, ImGuiInputTextFlags_ReadOnly); + if (ImGui::BeginDragDropTarget()) { + if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("JOTP_BROWSER_PATH")) { + editor.linked_source = static_cast(payload->Data); + editor.additional_sources.erase( + std::remove(editor.additional_sources.begin(), editor.additional_sources.end(), editor.linked_source), + editor.additional_sources.end()); + editor.preview_is_result = false; + } + ImGui::EndDragDropTarget(); + } + if (ImGui::Button("Use Selected", ImVec2(120.0f, 0.0f)) && !state->selected_browser_path.empty()) { + editor.linked_source = state->selected_browser_path; + editor.additional_sources.erase( + std::remove(editor.additional_sources.begin(), editor.additional_sources.end(), editor.linked_source), + editor.additional_sources.end()); + editor.preview_is_result = false; + } + ImGui::SameLine(); + if (ImGui::Button("Clear", ImVec2(120.0f, 0.0f))) { + editor.linked_source.clear(); + editor.preview_is_result = false; + } + + ImGui::Spacing(); + ImGui::TextUnformatted("Additional source timeseries:"); + ImGui::SameLine(); + const CustomSeriesTemplate &tmpl = selected_custom_series_template(editor); + if (tmpl.required_additional_sources > 0) { + const bool ready = static_cast(editor.additional_sources.size()) >= tmpl.required_additional_sources; + ImGui::TextColored(ready ? color_rgb(58, 126, 73) : color_rgb(180, 122, 44), "%s", tmpl.requirement_text); + } + ImGui::SameLine(); + ImGui::BeginDisabled(editor.selected_additional_source < 0 + || editor.selected_additional_source >= static_cast(editor.additional_sources.size())); + if (ImGui::Button("Remove Selected", ImVec2(140.0f, 0.0f)) + && editor.selected_additional_source >= 0 + && editor.selected_additional_source < static_cast(editor.additional_sources.size())) { + editor.additional_sources.erase(editor.additional_sources.begin() + + static_cast(editor.selected_additional_source)); + editor.selected_additional_source = editor.additional_sources.empty() + ? -1 : std::clamp(editor.selected_additional_source, 0, static_cast(editor.additional_sources.size()) - 1); + editor.preview_is_result = false; + } + ImGui::EndDisabled(); + + if (ImGui::BeginChild("##custom_additional_sources", ImVec2(0.0f, 156.0f), true)) { + if (ImGui::BeginTable("##custom_additional_table", 2, + ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) { + ImGui::TableSetupColumn("id", ImGuiTableColumnFlags_WidthFixed, 42.0f); + ImGui::TableSetupColumn("path", ImGuiTableColumnFlags_WidthStretch); + for (size_t i = 0; i < editor.additional_sources.size(); ++i) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("v%zu", i + 1); + ImGui::TableNextColumn(); + if (ImGui::Selectable(editor.additional_sources[i].c_str(), + editor.selected_additional_source == static_cast(i), + ImGuiSelectableFlags_SpanAllColumns)) { + editor.selected_additional_source = static_cast(i); + } + } + ImGui::EndTable(); + } + if (ImGui::BeginDragDropTarget()) { + if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("JOTP_BROWSER_PATH")) { + if (add_additional_source(&editor, static_cast(payload->Data))) + editor.preview_is_result = false; + } + ImGui::EndDragDropTarget(); + } + } + ImGui::EndChild(); + if (ImGui::Button("Add Selected", ImVec2(120.0f, 0.0f))) { + for (const std::string &path : state->selected_browser_paths) { + if (add_additional_source(&editor, path)) editor.preview_is_result = false; + } + } + + ImGui::Spacing(); + ImGui::SeparatorText("Function library"); + const auto &templates = custom_series_templates(); + if (ImGui::BeginChild("##custom_series_template_list", ImVec2(0.0f, 132.0f), true)) { + for (size_t i = 0; i < templates.size(); ++i) { + if (ImGui::Selectable(templates[i].name, editor.selected_template == static_cast(i), + ImGuiSelectableFlags_AllowDoubleClick)) { + editor.selected_template = static_cast(i); + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { + editor.globals_code = templates[i].globals_code; + editor.function_code = templates[i].function_code; + editor.preview_is_result = false; + } + } + } + } + ImGui::EndChild(); + if (ImGui::Button("Use Selected Example")) { + const auto &sel = selected_custom_series_template(editor); + editor.globals_code = sel.globals_code; + editor.function_code = sel.function_code; + editor.preview_is_result = false; + } + ImGui::Spacing(); + ImGui::TextDisabled("Preview"); + ImGui::BeginChild("##custom_series_template_preview", ImVec2(0.0f, 0.0f), true); + ImGui::TextUnformatted(selected_custom_series_template(editor).preview_text); + ImGui::EndChild(); +} + +void draw_editor_code_panel(CustomSeriesEditorState &editor, const Pane *active_pane) { + const std::string name_status = active_pane != nullptr ? custom_series_name_status(*active_pane, editor.name) : "no active pane"; + ImGui::TextUnformatted("New name:"); + ImGui::SameLine(); + const bool name_error = name_status == "name required" || name_status == "cannot start with /"; + ImGui::TextColored(name_error ? color_rgb(200, 72, 64) : color_rgb(58, 126, 73), "%s", name_status.c_str()); + if (editor.focus_name) { ImGui::SetKeyboardFocusHere(); editor.focus_name = false; } + ImGui::SetNextItemWidth(-FLT_MIN); + input_text_string("##custom_series_name", &editor.name, ImGuiInputTextFlags_AutoSelectAll); + + ImGui::Spacing(); + ImGui::SeparatorText("Global variables"); + ImGui::SameLine(); + if (ImGui::SmallButton("Help")) editor.open_help = true; + const float globals_h = std::max(96.0f, ImGui::GetContentRegionAvail().y * 0.28f); + if (input_text_multiline_string("##custom_series_globals", &editor.globals_code, + ImVec2(-FLT_MIN, globals_h), ImGuiInputTextFlags_AllowTabInput)) + editor.preview_is_result = false; + + ImGui::Spacing(); + ImGui::TextUnformatted("def calc(time, value):"); + const float func_h = std::max(180.0f, ImGui::GetContentRegionAvail().y - 16.0f); + if (input_text_multiline_string("##custom_series_function", &editor.function_code, + ImVec2(-FLT_MIN, func_h), ImGuiInputTextFlags_AllowTabInput)) + editor.preview_is_result = false; +} + +void draw_custom_series_editor(AppSession *session, UiState *state) { + CustomSeriesEditorState &editor = state->custom_series; + if (!editor.open) return; + + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + Pane *active_pane = (tab && tab_state && tab_state->active_pane_index >= 0 + && tab_state->active_pane_index < static_cast(tab->panes.size())) + ? &tab->panes[static_cast(tab_state->active_pane_index)] : nullptr; + if (editor.focus_name && active_pane && editor.name.empty()) + editor.name = next_custom_curve_name(*active_pane); + + draw_custom_series_help_popup(&editor); + + if (ImGui::BeginTabBar("##custom_series_tabs")) { + if (ImGui::BeginTabItem("Single Function")) { + const float footer_height = ImGui::GetFrameHeightWithSpacing() * 2.0f + 10.0f; + if (ImGui::BeginChild("##custom_series_body", + ImVec2(0.0f, std::max(1.0f, ImGui::GetContentRegionAvail().y - footer_height)), false)) { + if (ImGui::BeginChild("##custom_series_preview_child", + ImVec2(0.0f, std::max(200.0f, ImGui::GetContentRegionAvail().y * 0.28f)), true)) + draw_custom_series_preview(*session, &editor); + ImGui::EndChild(); + ImGui::Spacing(); + + if (ImGui::BeginTable("##custom_series_editor_table", 2, + ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_SizingStretchProp, + ImVec2(0.0f, std::max(1.0f, ImGui::GetContentRegionAvail().y)))) { + ImGui::TableSetupColumn("left", ImGuiTableColumnFlags_WidthFixed, 320.0f); + ImGui::TableSetupColumn("right", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableNextColumn(); + if (ImGui::BeginChild("##custom_series_left", ImVec2(0.0f, 0.0f), false)) + draw_editor_source_panel(state, editor); + ImGui::EndChild(); + ImGui::TableNextColumn(); + if (ImGui::BeginChild("##custom_series_right", ImVec2(0.0f, 0.0f), false)) + draw_editor_code_panel(editor, active_pane); + ImGui::EndChild(); + ImGui::EndTable(); + } + } + ImGui::EndChild(); + + ImGui::Spacing(); + if (ImGui::Button("New", ImVec2(120.0f, 0.0f))) { + reset_custom_series_editor(&editor); + if (!state->selected_browser_path.empty()) editor.linked_source = state->selected_browser_path; + editor.open = true; + editor.focus_name = true; + } + ImGui::SameLine(); + ImGui::BeginDisabled(!custom_series_template_ready(editor)); + if (ImGui::Button("Preview Result", ImVec2(120.0f, 0.0f))) + preview_custom_series_editor(session, state); + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !custom_series_template_ready(editor)) { + if (editor.linked_source.empty()) ImGui::SetTooltip("Choose an input timeseries first."); + else ImGui::SetTooltip("%s", selected_custom_series_template(editor).requirement_text); + } + ImGui::SameLine(); + if (ImGui::Button("Apply", ImVec2(120.0f, 0.0f))) apply_custom_series_editor(session, state); + ImGui::SameLine(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { editor.open = false; editor.request_select = false; } + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } +} diff --git a/tools/jotpluggler/dbc.h b/tools/jotpluggler/dbc.h new file mode 100644 index 00000000000000..d7c5461502b0e9 --- /dev/null +++ b/tools/jotpluggler/dbc.h @@ -0,0 +1,400 @@ +#pragma once + +#include "common/util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dbc { + + +struct ValueDescriptionEntry { + double value = 0.0; + std::string text; +}; + +struct Signal { + enum class Type { + Normal = 0, + Multiplexed, + Multiplexor, + }; + + Type type = Type::Normal; + std::string name; + int start_bit = 0; + int msb = 0; + int lsb = 0; + int size = 0; + double factor = 1.0; + double offset = 0.0; + double min = 0.0; + double max = 0.0; + bool is_signed = false; + bool is_little_endian = false; + std::string unit; + std::string comment; + std::string receiver_name; + int multiplex_value = 0; + int multiplexor_index = -1; + std::vector value_descriptions; +}; + +struct Message { + uint32_t address = 0; + std::string name; + uint32_t size = 0; + std::string comment; + std::string transmitter; + std::vector signals; + int multiplexor_index = -1; + + const std::vector &getSignals() const { return signals; } +}; + +class Database { +public: + Database() = default; + explicit Database(const std::filesystem::path &path); + static Database fromContent(const std::string &content, const std::string &filename = ""); + + const Message *message(uint32_t address) const; + const std::unordered_map &messages() const { return messages_; } + std::vector enumNames(const Signal &signal) const; + +private: + void parse(const std::string &content, const std::string &filename); + void parseBo(const std::string &line, int line_number, Message **current_message); + void parseSg(const std::string &line, int line_number, Message *current_message); + void parseVal(const std::string &line, int line_number); + void parseCmBo(const std::string &line, int line_number); + void parseCmSg(const std::string &line, int line_number); + void finalize(); + + std::string filename_; + std::unordered_map messages_; +}; + +void updateMsbLsb(Signal *signal); +double rawSignalValue(const Signal &signal, const uint8_t *data, size_t data_size); +std::optional signalValue(const Signal &signal, const Message &message, const uint8_t *data, size_t data_size); + +namespace { + +std::string unescape_dbc_string(std::string text) { + size_t pos = 0; + while ((pos = text.find("\\\"", pos)) != std::string::npos) { + text.replace(pos, 2, "\""); + ++pos; + } + return text; +} + +int flip_bit_pos(int start_bit) { + return 8 * (start_bit / 8) + 7 - start_bit % 8; +} + +std::string read_multiline_statement(std::istream &stream, std::string statement, int *line_number) { + static const std::regex statement_end(R"(\"\s*;\s*$)"); + while (true) { + const std::string trimmed = util::strip(statement); + if (std::regex_search(trimmed, statement_end)) { + return trimmed; + } + + std::string next_line; + if (!std::getline(stream, next_line)) { + return trimmed; + } + statement += "\n"; + statement += next_line; + ++(*line_number); + } +} + +} // namespace + +inline void updateMsbLsb(Signal *signal) { + if (signal->is_little_endian) { + signal->lsb = signal->start_bit; + signal->msb = signal->start_bit + signal->size - 1; + } else { + signal->lsb = flip_bit_pos(flip_bit_pos(signal->start_bit) + signal->size - 1); + signal->msb = signal->start_bit; + } +} + +inline double rawSignalValue(const Signal &signal, const uint8_t *data, size_t data_size) { + const int msb_byte = signal.msb / 8; + if (msb_byte >= static_cast(data_size)) return 0.0; + + const int lsb_byte = signal.lsb / 8; + uint64_t val = 0; + if (msb_byte == lsb_byte) { + val = (data[msb_byte] >> (signal.lsb & 7)) & ((1ULL << signal.size) - 1); + } else { + int bits = signal.size; + int i = msb_byte; + const int step = signal.is_little_endian ? -1 : 1; + while (i >= 0 && i < static_cast(data_size) && bits > 0) { + const int msb = (i == msb_byte) ? signal.msb & 7 : 7; + const int lsb = (i == lsb_byte) ? signal.lsb & 7 : 0; + const int nbits = msb - lsb + 1; + val = (val << nbits) | ((data[i] >> lsb) & ((1ULL << nbits) - 1)); + bits -= nbits; + i += step; + } + } + + if (signal.is_signed && (val & (1ULL << (signal.size - 1)))) { + val |= ~((1ULL << signal.size) - 1); + } + + return static_cast(val) * signal.factor + signal.offset; +} + +[[noreturn]] inline void parse_error(const std::string &filename, int line_number, const std::string &message, const std::string &line) { + std::ostringstream out; + out << "[" << filename << ":" << line_number << "] " << message << ": " << line; + throw std::runtime_error(out.str()); +} + +inline Database::Database(const std::filesystem::path &path) { + const std::string content = util::read_file(path.string()); + if (content.empty() && !std::filesystem::exists(path)) { + throw std::runtime_error("Failed to open DBC " + path.string()); + } + parse(content, path.filename().string()); +} + +inline Database Database::fromContent(const std::string &content, const std::string &filename) { + Database db; + db.parse(content, filename); + return db; +} + +inline const Message *Database::message(uint32_t address) const { + auto it = messages_.find(address); + return it == messages_.end() ? nullptr : &it->second; +} + +inline std::vector Database::enumNames(const Signal &signal) const { + if (signal.value_descriptions.empty()) return {}; + int max_index = -1; + for (const auto &entry : signal.value_descriptions) { + const double rounded = std::round(entry.value); + if (std::abs(entry.value - rounded) > 1e-6 || rounded < 0.0 || rounded > 512.0) return {}; + max_index = std::max(max_index, static_cast(rounded)); + } + if (max_index < 0) return {}; + std::vector names(static_cast(max_index + 1)); + for (const auto &entry : signal.value_descriptions) { + names[static_cast(std::llround(entry.value))] = entry.text; + } + return names; +} + +inline void Database::parse(const std::string &content, const std::string &filename) { + filename_ = filename; + messages_.clear(); + std::istringstream stream(content); + std::string raw_line; + Message *current_message = nullptr; + int line_number = 0; + while (std::getline(stream, raw_line)) { + ++line_number; + std::string line = util::strip(raw_line); + if (line.empty()) continue; + if (util::starts_with(line, "BO_ ")) { + parseBo(line, line_number, ¤t_message); + } else if (util::starts_with(line, "SG_ ")) { + if (current_message == nullptr) { + parse_error(filename, line_number, "Signal without current message", line); + } + parseSg(line, line_number, current_message); + } else if (util::starts_with(line, "VAL_ ")) { + parseVal(line, line_number); + } else if (util::starts_with(line, "CM_ BO_")) { + parseCmBo(read_multiline_statement(stream, raw_line, &line_number), line_number); + } else if (util::starts_with(line, "CM_ SG_")) { + parseCmSg(read_multiline_statement(stream, raw_line, &line_number), line_number); + } + } + finalize(); +} + +inline void Database::parseBo(const std::string &line, int line_number, Message **current_message) { + static const std::regex pattern(R"(^BO_\s+(\w+)\s+(\w+)\s*:\s*(\w+)\s+(\w+)\s*$)"); + std::smatch match; + if (!std::regex_match(line, match, pattern)) { + parse_error("", line_number, "Invalid BO_ line format", line); + } + uint32_t address = static_cast(std::stoul(match[1].str(), nullptr, 0)); + if (messages_.find(address) != messages_.end()) { + parse_error(filename_, line_number, "Duplicate message address", line); + } + Message &message = messages_[address]; + message.address = address; + message.name = match[2].str(); + message.size = static_cast(std::stoul(match[3].str(), nullptr, 0)); + message.transmitter = match[4].str(); + message.signals.clear(); + message.multiplexor_index = -1; + *current_message = &message; +} + +inline void Database::parseSg(const std::string &line, int line_number, Message *current_message) { + static const std::regex multiplex_pattern(R"(^SG_\s+(\w+)\s+(\w+)\s*:\s*(\d+)\|(\d+)@(\d)([+-])\s+\(([0-9.+\-eE]+),([0-9.+\-eE]+)\)\s+\[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\]\s+\"(.*)\"\s+(.*)$)"); + static const std::regex normal_pattern(R"(^SG_\s+(\w+)\s*:\s*(\d+)\|(\d+)@(\d)([+-])\s+\(([0-9.+\-eE]+),([0-9.+\-eE]+)\)\s+\[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\]\s+\"(.*)\"\s+(.*)$)"); + + std::smatch match; + Signal signal; + int offset = 0; + if (std::regex_match(line, match, normal_pattern)) { + offset = 0; + } else if (std::regex_match(line, match, multiplex_pattern)) { + offset = 1; + const std::string indicator = match[2].str(); + if (indicator == "M") { + if (std::any_of(current_message->signals.begin(), current_message->signals.end(), [](const Signal &existing) { + return existing.type == Signal::Type::Multiplexor; + })) { + parse_error(filename_, line_number, "Multiple multiplexor", line); + } + signal.type = Signal::Type::Multiplexor; + } else if (!indicator.empty() && indicator.front() == 'm') { + signal.type = Signal::Type::Multiplexed; + signal.multiplex_value = std::stoi(indicator.substr(1)); + } else { + parse_error("", line_number, "Invalid multiplex indicator", line); + } + } else { + parse_error("", line_number, "Invalid SG_ line format", line); + } + + signal.name = match[1].str(); + if (std::any_of(current_message->signals.begin(), current_message->signals.end(), [&](const Signal &existing) { + return existing.name == signal.name; + })) { + parse_error(filename_, line_number, "Duplicate signal name", line); + } + signal.start_bit = std::stoi(match[2 + offset].str()); + signal.size = std::stoi(match[3 + offset].str()); + signal.is_little_endian = match[4 + offset].str() == "1"; + signal.is_signed = match[5 + offset].str() == "-"; + signal.factor = std::stod(match[6 + offset].str()); + signal.offset = std::stod(match[7 + offset].str()); + signal.min = std::stod(match[8 + offset].str()); + signal.max = std::stod(match[9 + offset].str()); + signal.unit = match[10 + offset].str(); + signal.receiver_name = util::strip(match[11 + offset].str()); + updateMsbLsb(&signal); + current_message->signals.push_back(std::move(signal)); +} + +inline void Database::parseVal(const std::string &line, int line_number) { + static const std::regex prefix(R"(^VAL_\s+(\w+)\s+(\w+)\s+(.*);$)"); + std::smatch match; + if (!std::regex_match(line, match, prefix)) { + parse_error("", line_number, "Invalid VAL_ line format", line); + } + + const uint32_t address = static_cast(std::stoul(match[1].str(), nullptr, 0)); + auto msg_it = messages_.find(address); + if (msg_it == messages_.end()) { + return; + } + auto sig_it = std::find_if(msg_it->second.signals.begin(), msg_it->second.signals.end(), [&](const Signal &signal) { + return signal.name == match[2].str(); + }); + if (sig_it == msg_it->second.signals.end()) { + return; + } + + static const std::regex entry_pattern(R"(([+-]?\d+(?:\.\d+)?)\s+\"((?:[^\"\\]|\\.)*)\")"); + const std::string defs = match[3].str(); + for (std::sregex_iterator it(defs.begin(), defs.end(), entry_pattern), end; it != end; ++it) { + sig_it->value_descriptions.push_back(ValueDescriptionEntry{ + .value = std::stod((*it)[1].str()), + .text = (*it)[2].str(), + }); + } +} + +inline void Database::parseCmBo(const std::string &line, int line_number) { + static const std::regex pattern(R"(^CM_\s+BO_\s*(\w+)\s*\"((?:[^\"\\]|\\.|[\r\n])*)\"\s*;\s*$)"); + std::smatch match; + if (!std::regex_match(line, match, pattern)) { + parse_error(filename_, line_number, "Invalid message comment format", line); + } + const uint32_t address = static_cast(std::stoul(match[1].str(), nullptr, 0)); + auto it = messages_.find(address); + if (it != messages_.end()) { + it->second.comment = unescape_dbc_string(match[2].str()); + } +} + +inline void Database::parseCmSg(const std::string &line, int line_number) { + static const std::regex pattern(R"(^CM_\s+SG_\s*(\w+)\s*(\w+)\s*\"((?:[^\"\\]|\\.|[\r\n])*)\"\s*;\s*$)"); + std::smatch match; + if (!std::regex_match(line, match, pattern)) { + parse_error(filename_, line_number, "Invalid signal comment format", line); + } + + const uint32_t address = static_cast(std::stoul(match[1].str(), nullptr, 0)); + auto msg_it = messages_.find(address); + if (msg_it == messages_.end()) return; + + auto sig_it = std::find_if(msg_it->second.signals.begin(), msg_it->second.signals.end(), [&](const Signal &signal) { + return signal.name == match[2].str(); + }); + if (sig_it != msg_it->second.signals.end()) { + sig_it->comment = unescape_dbc_string(match[3].str()); + } +} + +inline void Database::finalize() { + for (auto &[_, message] : messages_) { + std::sort(message.signals.begin(), message.signals.end(), [](const Signal &left, const Signal &right) { + return std::tie(right.type, left.multiplex_value, left.start_bit, left.name) + < std::tie(left.type, right.multiplex_value, right.start_bit, right.name); + }); + message.multiplexor_index = -1; + for (size_t i = 0; i < message.signals.size(); ++i) { + if (message.signals[i].type == Signal::Type::Multiplexor) { + message.multiplexor_index = static_cast(i); + break; + } + } + for (Signal &signal : message.signals) { + signal.multiplexor_index = signal.type == Signal::Type::Multiplexed ? message.multiplexor_index : -1; + if (signal.type == Signal::Type::Multiplexed && signal.multiplexor_index < 0) { + signal.type = Signal::Type::Normal; + signal.multiplex_value = 0; + } + } + } +} + +inline std::optional signalValue(const Signal &signal, const Message &message, const uint8_t *data, size_t data_size) { + if (signal.multiplexor_index >= 0) { + const Signal &multiplexor = message.signals[static_cast(signal.multiplexor_index)]; + const double mux_value = rawSignalValue(multiplexor, data, data_size); + if (std::llround(mux_value) != signal.multiplex_value) return std::nullopt; + } + return rawSignalValue(signal, data, data_size); +} + +} // namespace dbc diff --git a/tools/jotpluggler/generate_event_extractors.py b/tools/jotpluggler/generate_event_extractors.py new file mode 100644 index 00000000000000..1aba9578cd1a66 --- /dev/null +++ b/tools/jotpluggler/generate_event_extractors.py @@ -0,0 +1,327 @@ +import sys +import capnp +from pathlib import Path + +NO_DISCRIMINANT = 65535 +SCALAR_KINDS = { + "bool": "Bool", + "int8": "Int", + "int16": "Int", + "int32": "Int", + "int64": "Int", + "uint8": "UInt", + "uint16": "UInt", + "uint32": "UInt", + "uint64": "UInt", + "float32": "Float", + "float64": "Float", + "enum": "Enum", +} +NESTED_TYPE_KINDS = {"struct", "list"} +IGNORED_TYPE_KINDS = {"void", "text", "data", "interface", "anyPointer"} + + +def cxx_string(value): + return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def accessor(prefix, name): + return prefix + name[:1].upper() + name[1:] + + +def field_type(field): + if field.proto.which() == "group": + return "struct" + return field.proto.slot.type.which() + + +def field_type_proto(field): + return field.proto.slot.type if field.proto.which() == "slot" else None + + +def scalar_kind(type_proto): + if type_proto is None: + return None + return SCALAR_KINDS.get(type_proto.which()) + + +def enum_names(schema): + if schema is None: + return [] + names_by_ordinal = schema.enumerants + if not names_by_ordinal: + return [] + max_ordinal = max(names_by_ordinal.values()) + out = [""] * (max_ordinal + 1) + for name, ordinal in names_by_ordinal.items(): + out[ordinal] = name + return out + + +class Generator: + def __init__(self, event_schema): + self.event_schema = event_schema + self.fixed_paths = [] + self.tmp_index = 0 + self.lines = [] + self.emits_memo = {} + + def tmp(self, prefix): + self.tmp_index += 1 + return f"{prefix}_{self.tmp_index}" + + def add_fixed_path(self, path): + slot = len(self.fixed_paths) + self.fixed_paths.append(path) + return slot + + def emit(self, indent, text=""): + self.lines.append(" " * indent + text) + + def scalar_double_expr(self, value_expr, kind): + if kind == "Bool": + return f"({value_expr} ? 1.0 : 0.0)" + if kind == "Enum": + return f"static_cast(static_cast({value_expr}))" + return f"static_cast({value_expr})" + + def emit_enum_capture(self, indent, path_expr, names): + if not names: + return + names_expr = "{" + ", ".join(cxx_string(name) for name in names) + "}" + self.emit(indent, f"capture_static_enum_info({path_expr}, {names_expr}, series);") + + def emit_node(self, indent, type_kind, type_proto, schema, expr, path, path_expr, dynamic_path): + if not self.node_emits(type_kind, type_proto, schema): + return + kind = scalar_kind(type_proto) + if kind is not None: + double_expr = self.scalar_double_expr(expr, kind) + if dynamic_path: + if kind == "Enum": + self.emit_enum_capture(indent, path_expr, enum_names(schema)) + self.emit(indent, f"append_dynamic_scalar_point({path_expr}, tm, {double_expr}, series);") + else: + slot = self.add_fixed_path(path) + if kind == "Enum": + self.emit_enum_capture(indent, cxx_string(path), enum_names(schema)) + self.emit(indent, f"append_fixed_scalar_point(&series->fixed_series[{slot}], tm, {double_expr});") + return + + if type_kind == "struct": + self.emit_struct(indent, schema, expr, path, path_expr, dynamic_path) + return + + if type_kind == "list": + self.emit_list(indent, type_proto, schema, expr, path, path_expr, dynamic_path) + + def emit_field(self, indent, struct_schema, reader_expr, field_name, base_path, base_path_expr, dynamic_path): + field = struct_schema.fields[field_name] + proto = field.proto + type_kind = field_type(field) + type_proto = field_type_proto(field) + kind = scalar_kind(type_proto) + value_schema = field.schema if kind == "Enum" or type_kind in NESTED_TYPE_KINDS else None + if not self.node_emits(type_kind, type_proto, value_schema): + return + + field_path = f"{base_path}/{field_name}" + field_path_expr = None + if dynamic_path: + field_path_var = self.tmp("path") + self.emit(indent, f"const std::string {field_path_var} = {base_path_expr} + {cxx_string('/' + field_name)};") + field_path_expr = field_path_var + + get_call = f"{reader_expr}.{accessor('get', field_name)}()" + has_call = f"{reader_expr}.{accessor('has', field_name)}()" + conditions = [] + if proto.discriminantValue != NO_DISCRIMINANT: + conditions.append(f"{reader_expr}.which() == static_cast({proto.discriminantValue})") + if proto.which() == "slot" and type_kind in NESTED_TYPE_KINDS: + conditions.append(has_call) + + if conditions: + self.emit(indent, f"if ({' && '.join(conditions)}) {{") + indent += 2 + + value_var = self.tmp("value") + self.emit(indent, f"const auto {value_var} = {get_call};") + self.emit_node(indent, type_kind, type_proto, value_schema, value_var, field_path, field_path_expr, dynamic_path) + + if conditions: + indent -= 2 + self.emit(indent, "}") + + def emit_struct(self, indent, schema, reader_expr, path, path_expr, dynamic_path): + if schema is None: + return + for field_name in schema.fieldnames: + self.emit_field(indent, schema, reader_expr, field_name, path, path_expr, dynamic_path) + + def emit_list(self, indent, type_proto, schema, list_expr, path, path_expr, dynamic_path): + elem_type = type_proto.list.elementType + elem_kind = elem_type.which() + if elem_kind in IGNORED_TYPE_KINDS: + return + + base_path_var = path_expr + if base_path_var is None: + base_path_var = self.tmp("base_path") + self.emit(indent, f"const std::string {base_path_var} = {cxx_string(path)};") + + elem_scalar = scalar_kind(elem_type) + if elem_scalar is not None: + self.emit(indent, f"if ({list_expr}.size() <= 16) {{") + index_var = self.tmp("i") + self.emit(indent + 2, f"for (uint {index_var} = 0; {index_var} < {list_expr}.size(); ++{index_var}) {{") + item_series = self.tmp("item_series") + self.emit(indent + 4, f"RouteSeries *{item_series} = ensure_list_scalar_series({base_path_var}, {index_var}, series);") + if elem_scalar == "Enum": + self.emit_enum_capture(indent + 4, f"{item_series}->path", enum_names(schema.elementType)) + self.emit(indent + 4, f"append_fixed_scalar_point({item_series}, tm, {self.scalar_double_expr(f'{list_expr}[{index_var}]', elem_scalar)});") + self.emit(indent + 2, "}") + self.emit(indent, "}") + return + + if elem_kind in {"struct", "list"}: + index_var = self.tmp("i") + self.emit(indent, f"for (uint {index_var} = 0; {index_var} < {list_expr}.size(); ++{index_var}) {{") + item_path = self.tmp("item_path") + self.emit(indent + 2, f"const std::string {item_path} = {base_path_var} + \"/\" + std::to_string({index_var});") + item = self.tmp("item") + self.emit(indent + 2, f"const auto {item} = {list_expr}[{index_var}];") + if elem_kind == "struct": + self.emit_struct(indent + 2, schema.elementType, item, path, item_path, True) + else: + self.emit_list(indent + 2, elem_type, schema.elementType, item, path, item_path, True) + self.emit(indent, "}") + + def node_emits(self, type_kind, type_proto, schema, seen=frozenset()): + if scalar_kind(type_proto) is not None: + return True + if type_kind == "struct": + if schema is None: + return False + schema_id = int(schema.node.id) + if schema_id in seen: + return False + if schema_id in self.emits_memo: + return self.emits_memo[schema_id] + next_seen = seen | {schema_id} + for field_name in schema.fieldnames: + field = schema.fields[field_name] + ft = field_type(field) + ftp = field_type_proto(field) + fkind = scalar_kind(ftp) + if ft in IGNORED_TYPE_KINDS: + continue + fschema = field.schema if fkind == "Enum" or ft in NESTED_TYPE_KINDS else None + if self.node_emits(ft, ftp, fschema, next_seen): + self.emits_memo[schema_id] = True + return True + self.emits_memo[schema_id] = False + return False + if type_kind == "list": + if type_proto is None or schema is None: + return False + elem_type = type_proto.list.elementType + elem_kind = elem_type.which() + if elem_kind in IGNORED_TYPE_KINDS: + return False + if scalar_kind(elem_type) is not None: + return True + if elem_kind == "struct": + return self.node_emits("struct", None, schema.elementType, seen) + if elem_kind == "list": + return self.node_emits("list", elem_type, schema.elementType, seen) + return False + + def emit_can_special(self, indent, service_name): + service_kind = "CanServiceKind::Can" if service_name == "can" else "CanServiceKind::Sendcan" + self.emit(indent, f"const CanServiceKind can_service = {service_kind};") + self.emit(indent, f"for (const auto &msg : event.{accessor('get', service_name)}()) {{") + self.emit(indent + 2, "append_can_frame(can_service, static_cast(msg.getSrc()), msg.getAddress(), msg.getDeprecated().getBusTime(), msg.getDat(), tm, series);") # noqa: E501 + self.emit(indent + 2, "if (skip_raw_can) {") + self.emit(indent + 4, "const auto dat = msg.getDat();") + self.emit(indent + 4, f"decode_can_frame(can_dbc, {cxx_string(service_name)}, static_cast(msg.getSrc()), msg.getAddress(), dat.begin(), dat.size(), tm, series);") # noqa: E501 + self.emit(indent + 2, "}") + self.emit(indent, "}") + self.emit(indent, "if (skip_raw_can) {") + self.emit(indent + 2, "return true;") + self.emit(indent, "}") + + def emit_event_case(self, field_name): + field = self.event_schema.fields[field_name] + proto = field.proto + type_kind = field_type(field) + type_proto = field_type_proto(field) + kind = scalar_kind(type_proto) + schema = field.schema if kind == "Enum" or type_kind in NESTED_TYPE_KINDS else None + self.emit(4, f"case static_cast({proto.discriminantValue}): {{") + valid_slot = self.add_fixed_path(f"/{field_name}/valid") + mono_slot = self.add_fixed_path(f"/{field_name}/logMonoTime") + seconds_slot = self.add_fixed_path(f"/{field_name}/t") + self.emit(6, f"append_fixed_scalar_point(&series->fixed_series[{valid_slot}], tm, event.getValid() ? 1.0 : 0.0);") + self.emit(6, f"append_fixed_scalar_point(&series->fixed_series[{mono_slot}], tm, static_cast(event.getLogMonoTime()));") + self.emit(6, f"append_fixed_scalar_point(&series->fixed_series[{seconds_slot}], tm, tm);") + if field_name in {"can", "sendcan"}: + self.emit_can_special(6, field_name) + if self.node_emits(type_kind, type_proto, schema): + payload = self.tmp("payload") + self.emit(6, f"const auto {payload} = event.{accessor('get', field_name)}();") + self.emit_node(6, type_kind, type_proto, schema, payload, f"/{field_name}", None, False) + self.emit(6, "return true;") + self.emit(4, "}") + + def generate(self): + self.lines = [] + self.emit(0, "// Generated by tools/jotpluggler/generate_event_extractors.py; do not edit.") + self.emit(0, "") + self.emit(0, "const std::vector &static_event_fixed_paths() {") + self.emit(2, "static const std::vector paths = {") + path_insert_at = len(self.lines) + self.emit(2, "};") + self.emit(2, "return paths;") + self.emit(0, "}") + self.emit(0, "") + self.emit(0, "void capture_static_enum_info(const std::string &path, std::initializer_list names, SeriesAccumulator *series) {") + self.emit(2, "if (series->enum_info.find(path) != series->enum_info.end()) {") + self.emit(4, "return;") + self.emit(2, "}") + self.emit(2, "EnumInfo info;") + self.emit(2, "info.names.reserve(names.size());") + self.emit(2, "for (std::string_view name : names) {") + self.emit(4, "info.names.emplace_back(name);") + self.emit(2, "}") + self.emit(2, "if (!info.names.empty()) {") + self.emit(4, "series->enum_info.emplace(path, std::move(info));") + self.emit(2, "}") + self.emit(0, "}") + self.emit(0, "") + self.emit(0, "bool append_event_static_reader(cereal::Event::Which which, const cereal::Event::Reader &event, const dbc::Database *can_dbc, bool skip_raw_can, double time_offset, SeriesAccumulator *series) {") # noqa: E501 + self.emit(2, "const double tm = static_cast(event.getLogMonoTime()) / 1.0e9 - time_offset;") + self.emit(2, "switch (which) {") + for field_name in self.event_schema.union_fields: + self.emit_event_case(field_name) + self.emit(4, "default:") + self.emit(6, "return false;") + self.emit(2, "}") + self.emit(0, "}") + + path_lines = [" " + cxx_string(path) + "," for path in self.fixed_paths] + self.lines[path_insert_at:path_insert_at] = path_lines + return "\n".join(self.lines) + "\n" + + +if __name__ == "__main__": + if len(sys.argv) != 3: + print(f"usage: {sys.argv[0]} ", file=sys.stderr) + sys.exit(2) + + repo_root = Path(sys.argv[1]).resolve() + output = Path(sys.argv[2]) + capnp.remove_import_hook() + log = capnp.load(str(repo_root / "cereal" / "log.capnp")) + generated = Generator(log.Event.schema).generate() + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(generated) diff --git a/tools/jotpluggler/generated_dbcs/.gitignore b/tools/jotpluggler/generated_dbcs/.gitignore new file mode 100644 index 00000000000000..d6b7ef32c8478a --- /dev/null +++ b/tools/jotpluggler/generated_dbcs/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/tools/jotpluggler/icons.cc b/tools/jotpluggler/icons.cc new file mode 100644 index 00000000000000..29edabad4ee3df --- /dev/null +++ b/tools/jotpluggler/icons.cc @@ -0,0 +1,24 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" + +#include + +void icon_add_font(float size, bool merge, const ImFont *base_font) { + const std::filesystem::path ttf = BOOTSTRAP_ICONS_TTF; + ImGuiIO &io = ImGui::GetIO(); + ImFontConfig config; + config.MergeMode = merge; + config.GlyphMinAdvanceX = size; + if (base_font != nullptr) { + ImFontBaked *baked = const_cast(base_font)->GetFontBaked(size); + const float base_center = baked != nullptr ? (baked->Ascent + baked->Descent) * 0.5f : size * 0.5f; + config.GlyphOffset.y = std::round(size * 0.5f - base_center); + } + static const ImWchar ranges[] = {0xF000, 0xF8FF, 0}; + io.Fonts->AddFontFromFileTTF(ttf.c_str(), size, &config, ranges); +} + +bool icon_menu_item(const char *glyph, const char *label, const char *shortcut, bool selected, bool enabled) { + assert(glyph != nullptr && glyph[0] != '\0'); + return ImGui::MenuItem(util::string_format("%s %s", glyph, label).c_str(), shortcut, selected, enabled); +} diff --git a/tools/jotpluggler/internal.h b/tools/jotpluggler/internal.h new file mode 100644 index 00000000000000..7b898f04618a07 --- /dev/null +++ b/tools/jotpluggler/internal.h @@ -0,0 +1,165 @@ +#pragma once + +#include "tools/jotpluggler/common.h" +#include "tools/jotpluggler/map.h" + +#include +#include +#include + +struct GLFWwindow; + +enum class PaneDropZone { + Center, + Left, + Right, + Top, + Bottom, +}; + +enum class PaneMenuActionKind { + None, + OpenAxisLimits, + OpenCustomSeries, + SplitLeft, + SplitRight, + SplitTop, + SplitBottom, + ResetView, + Clear, + Close, +}; + +struct PaneMenuAction { + PaneMenuActionKind kind = PaneMenuActionKind::None; + int pane_index = -1; +}; + +struct PaneCurveDragPayload { + int tab_index = -1; + int pane_index = -1; + int curve_index = -1; +}; + +struct PaneDropAction { + PaneDropZone zone = PaneDropZone::Center; + int target_pane_index = -1; + bool from_browser = false; + std::vector browser_paths; + std::string special_item_id; + PaneCurveDragPayload curve_ref; +}; + +inline constexpr float SIDEBAR_WIDTH = 320.0f; +inline constexpr float SIDEBAR_MIN_WIDTH = 220.0f; +inline constexpr float SIDEBAR_MAX_WIDTH = 520.0f; +inline constexpr float TIMELINE_BAR_HEIGHT = 14.0f; +inline constexpr float STATUS_BAR_HEIGHT = 52.0f; +inline constexpr double MIN_HORIZONTAL_ZOOM_SECONDS = 2.0; +inline constexpr double PLOT_Y_PADDING_FRACTION = 0.05; + +struct UiMetrics { + float width = 0.0f; + float height = 0.0f; + float top_offset = 0.0f; + float sidebar_width = SIDEBAR_WIDTH; + float content_x = 0.0f; + float content_y = 0.0f; + float content_w = 0.0f; + float content_h = 0.0f; + float status_bar_y = 0.0f; +}; + +std::filesystem::path resolve_layout_path(const std::string &layout_arg); +std::filesystem::path autosave_path_for_layout(const std::filesystem::path &layout_path); +std::vector available_layout_names(); + +SketchLayout make_empty_layout(); +void cancel_rename_tab(UiState *state); +void sync_ui_state(UiState *state, const SketchLayout &layout); +void sync_route_buffers(UiState *state, const AppSession &session); +void sync_stream_buffers(UiState *state, const AppSession &session); +void sync_layout_buffers(UiState *state, const AppSession &session); +void mark_all_docks_dirty(UiState *state); +void clear_layout_autosave(const AppSession &session); +bool autosave_layout(AppSession *session, UiState *state); +bool apply_axis_limits_editor(AppSession *session, UiState *state); +void open_axis_limits_editor(const AppSession &session, UiState *state, int pane_index); +void persist_shared_range_to_tab(WorkspaceTab *tab, const UiState &state); +void clear_pane_vertical_limits(Pane *pane); + +void refresh_replaced_layout_ui(AppSession *session, UiState *state, bool mark_docks); +void start_new_layout(AppSession *session, UiState *state, const std::string &status_text = "New untitled layout"); +void apply_dbc_override_change(AppSession *session, UiState *state, const std::string &dbc_override); + +void app_push_bold_font(); +void app_pop_bold_font(); +void draw_vertical_splitter(const char *id, float height, float min_left, float max_left, float *left_width); +void draw_right_splitter(const char *id, float height, float min_right, float max_right, float *right_width); +bool draw_horizontal_splitter(const char *id, float width, float min_top, float max_top, float *top_height); +void draw_payload_bytes(std::string_view data, const std::string *prev_data = nullptr); +void draw_payload_preview_boxes(const char *id, std::string_view data, const std::string *prev_data, float max_width); +void draw_signal_sparkline(const AppSession &session, + const UiState &state, + std::string_view signal_path, + bool selected, + ImVec2 size = ImVec2(0.0f, 24.0f)); +ImU32 mix_color(ImU32 a, ImU32 b, float t); +void draw_empty_panel(const char *title, const char *message); + +UiMetrics compute_ui_metrics(const ImVec2 &size, float top_offset, float sidebar_width); +void draw_sidebar(AppSession *session, const UiMetrics &ui, UiState *state, bool show_camera_feed); +void draw_workspace(AppSession *session, const UiMetrics &ui, UiState *state); +void draw_pane_windows(AppSession *session, UiState *state); + +// plot.cc +void draw_plot(const AppSession &session, Pane *pane, UiState *state); +bool draw_pane_close_button_overlay(); +void draw_pane_frame_overlay(); +std::optional draw_pane_context_menu(const WorkspaceTab &tab, int pane_index); +bool curve_has_samples(const AppSession &session, const Curve &curve); +bool curve_has_local_samples(const Curve &curve); +std::string app_curve_display_name(const Curve &curve); +bool mark_layout_dirty(AppSession *session, UiState *state); + +const RouteSeries *app_find_route_series(const AppSession &session, const std::string &path); +void sync_camera_feeds(AppSession *session); +void apply_route_data(AppSession *session, UiState *state, RouteData route_data); +bool apply_undo(AppSession *session, UiState *state); +bool apply_redo(AppSession *session, UiState *state); +bool infer_stream_follow_state(const UiState &state, const AppSession &session); +void ensure_shared_range(UiState *state, const AppSession &session); +void clamp_shared_range(UiState *state, const AppSession &session); +void reset_shared_range(UiState *state, const AppSession &session); +void update_follow_range(UiState *state, const AppSession &session); +void advance_playback(UiState *state, const AppSession &session); +void step_tracker(UiState *state, double direction); +std::string dbc_combo_label(const AppSession &session); +const char *log_selector_name(LogSelector selector); +const char *log_selector_description(LogSelector selector); +std::string format_cache_bytes(uint64_t bytes); +MapCacheStats directory_cache_stats(const std::filesystem::path &root); +float draw_main_menu_bar(AppSession *session, UiState *state); + +bool reset_layout(AppSession *session, UiState *state); +bool reload_layout(AppSession *session, UiState *state, const std::string &layout_arg); +bool save_layout(AppSession *session, UiState *state, const std::string &layout_path); +void rebuild_session_route_data(AppSession *session, UiState *state, + const RouteLoadProgressCallback &progress = {}); +void stop_stream_session(AppSession *session, UiState *state, bool preserve_data = true); +bool start_stream_session(AppSession *session, + UiState *state, + const StreamSourceConfig &source, + double buffer_seconds, + bool preserve_existing_data = false); +void start_async_route_load(AppSession *session, UiState *state); +void poll_async_route_load(AppSession *session, UiState *state); +bool reload_session(AppSession *session, UiState *state, const std::string &route_name, const std::string &data_dir); +void draw_popups(AppSession *session, UiState *state); + +void draw_status_bar(const AppSession &session, const UiMetrics &ui, UiState *state); +void draw_sidebar_resizer(const UiMetrics &ui, UiState *state); + +void apply_stream_batch(AppSession *session, UiState *state, StreamExtractBatch batch); + +void render_frame(GLFWwindow *window, AppSession *session, UiState *state, const std::filesystem::path *capture_path); diff --git a/tools/jotpluggler/layout.cc b/tools/jotpluggler/layout.cc new file mode 100644 index 00000000000000..0d3b82c25461fb --- /dev/null +++ b/tools/jotpluggler/layout.cc @@ -0,0 +1,704 @@ +#include "tools/jotpluggler/internal.h" +#include "system/hardware/hw.h" + +#include + +namespace fs = std::filesystem; + +namespace { + +enum class ModalAction { + None, + Primary, + Secondary, +}; + +struct FindSignalMatch { + const std::string *path = nullptr; + int score = 0; +}; + +struct DbcEditorSource { + fs::path path; + DbcEditorState::SourceKind kind = DbcEditorState::SourceKind::None; +}; + +StreamSourceConfig stream_source_config_from_ui(const UiState &state) { + StreamSourceConfig source; + source.kind = state.stream_source_kind; + source.address = util::strip(state.stream_address_buffer); + if (source.kind == StreamSourceKind::CerealLocal) { + source.address = "127.0.0.1"; + } else { + source.address = normalize_stream_address(std::move(source.address)); + } + return source; +} + +void open_queued_popup(bool &flag, const char *name) { + if (flag) { + ImGui::OpenPopup(name); + flag = false; + } +} + +ModalAction draw_modal_action_row(const char *primary_label, + const char *secondary_label = "Cancel", + float width = 120.0f) { + if (ImGui::Button(primary_label, ImVec2(width, 0.0f))) { + return ModalAction::Primary; + } + ImGui::SameLine(); + if (ImGui::Button(secondary_label, ImVec2(width, 0.0f))) { + return ModalAction::Secondary; + } + return ModalAction::None; +} + +std::vector find_signal_matches(const AppSession &session, std::string_view query) { + std::vector matches; + if (query.empty()) { + return matches; + } + const std::string needle = lowercase_copy(query); + for (const std::string &path : session.route_data.paths) { + const std::string hay = lowercase_copy(path); + const size_t pos = hay.find(needle); + if (pos == std::string::npos) { + continue; + } + const size_t slash = path.find_last_of('/'); + const std::string_view label = slash == std::string::npos ? std::string_view(path) : std::string_view(path).substr(slash + 1); + int score = static_cast(pos * 8 + path.size()); + if (lowercase_copy(label) == needle) score -= 60; + if (util::starts_with(hay, needle)) score -= 30; + matches.push_back({.path = &path, .score = score}); + } + std::sort(matches.begin(), matches.end(), [](const FindSignalMatch &a, const FindSignalMatch &b) { + return std::tie(a.score, *a.path) < std::tie(b.score, *b.path); + }); + if (matches.size() > 200) { + matches.resize(200); + } + return matches; +} + +bool open_find_signal_result(UiState *state, const std::string &path) { + state->selected_browser_paths = {path}; + state->selected_browser_path = path; + state->browser_selection_anchor = path; + state->status_text = "Selected signal " + path; + return true; +} + +void draw_open_route_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Open Route")) { + return; + } + ImGui::TextUnformatted("Load a route into the current layout."); + ImGui::Separator(); + input_text_string("Route", &state->route_buffer); + input_text_string("Data Dir", &state->data_dir_buffer); + ImGui::Spacing(); + switch (draw_modal_action_row("Load")) { + case ModalAction::Primary: + reload_session(session, state, state->route_buffer, state->data_dir_buffer); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::Secondary: + sync_route_buffers(state, *session); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_stream_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Live Stream")) { + return; + } + + ImGui::TextUnformatted("Connect to a live source."); + ImGui::Separator(); + if (ImGui::RadioButton("Local (MSGQ)", state->stream_source_kind == StreamSourceKind::CerealLocal)) { + state->stream_source_kind = StreamSourceKind::CerealLocal; + } + if (ImGui::RadioButton("Remote (ZMQ)", state->stream_source_kind == StreamSourceKind::CerealRemote)) { + state->stream_source_kind = StreamSourceKind::CerealRemote; + } + + if (state->stream_source_kind == StreamSourceKind::CerealRemote) { + input_text_string("Address", &state->stream_address_buffer); + } + ImGui::InputDouble("Buffer (seconds)", &state->stream_buffer_seconds, 0.0, 0.0, "%.0f"); + ImGui::Spacing(); + switch (draw_modal_action_row("Connect")) { + case ModalAction::Primary: { + const StreamSourceConfig source = stream_source_config_from_ui(*state); + if (start_stream_session(session, state, source, state->stream_buffer_seconds, false)) { + ImGui::CloseCurrentPopup(); + } + break; + } + case ModalAction::Secondary: + sync_stream_buffers(state, *session); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_load_layout_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Load Layout")) { + return; + } + ImGui::TextUnformatted("Load a JotPlugger JSON layout."); + ImGui::Separator(); + input_text_string("Layout", &state->load_layout_buffer); + ImGui::Spacing(); + switch (draw_modal_action_row("Load")) { + case ModalAction::Primary: + if (reload_layout(session, state, state->load_layout_buffer)) { + ImGui::CloseCurrentPopup(); + } + break; + case ModalAction::Secondary: + sync_layout_buffers(state, *session); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_save_layout_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Save Layout")) { + return; + } + ImGui::TextUnformatted("Save the current workspace as a JotPlugger JSON layout."); + ImGui::Separator(); + input_text_string("Layout", &state->save_layout_buffer); + ImGui::Spacing(); + switch (draw_modal_action_row("Save")) { + case ModalAction::Primary: + if (save_layout(session, state, state->save_layout_buffer)) { + ImGui::CloseCurrentPopup(); + } + break; + case ModalAction::Secondary: + sync_layout_buffers(state, *session); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_preferences_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Preferences")) { + return; + } + if (session->map_data) { + const MapCacheStats map_cache = session->map_data->cacheStats(); + const MapCacheStats download_cache = directory_cache_stats(Path::download_cache_root()); + ImGui::TextUnformatted("Map"); + ImGui::Separator(); + ImGui::Text("Map cache: %s in %zu file%s", + format_cache_bytes(map_cache.bytes).c_str(), + map_cache.files, + map_cache.files == 1 ? "" : "s"); + if (ImGui::Button("Clear Map Cache", ImVec2(120.0f, 0.0f))) { + session->map_data->clearCache(); + state->status_text = "Cleared map cache"; + } + ImGui::Spacing(); + ImGui::TextUnformatted("comma Download Cache"); + ImGui::Separator(); + ImGui::Text("Download cache: %s in %zu file%s", + format_cache_bytes(download_cache.bytes).c_str(), + download_cache.files, + download_cache.files == 1 ? "" : "s"); + ImGui::TextDisabled("%s", Path::download_cache_root().c_str()); + ImGui::Spacing(); + } + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void draw_find_signal_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Find Signal")) { + return; + } + ImGui::TextUnformatted("Search decoded signals across the loaded route."); + ImGui::Separator(); + ImGui::SetNextItemWidth(560.0f); + input_text_with_hint_string("##find_signal_query", "Search signal path or name...", &state->find_signal_buffer); + if (ImGui::IsWindowAppearing()) { + ImGui::SetKeyboardFocusHere(-1); + } + const std::vector matches = find_signal_matches(*session, state->find_signal_buffer); + ImGui::Spacing(); + ImGui::TextDisabled("%zu match%s", matches.size(), matches.size() == 1 ? "" : "es"); + if (ImGui::BeginChild("##find_signal_results", ImVec2(760.0f, 360.0f), true)) { + for (const FindSignalMatch &match : matches) { + const std::string &path = *match.path; + const size_t slash = path.find_last_of('/'); + const std::string_view label = slash == std::string::npos ? std::string_view(path) : std::string_view(path).substr(slash + 1); + if (ImGui::Selectable((std::string(label) + "##" + path).c_str(), false, ImGuiSelectableFlags_SpanAllColumns)) { + if (open_find_signal_result(state, path)) { + ImGui::CloseCurrentPopup(); + } + } + ImGui::SameLine(280.0f); + ImGui::TextDisabled("%s", path.c_str()); + } + } + ImGui::EndChild(); + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +std::string default_dbc_template() { + return "VERSION \"\"\n\nNS_ :\nBS_:\nBU_: XXX\n"; +} + +DbcEditorSource resolve_dbc_editor_source(const std::string &dbc_name) { + const fs::path generated_dbc_dir = repo_root() / "tools" / "jotpluggler" / "generated_dbcs"; + const std::array candidates = {{ + {.path = repo_root() / "opendbc" / "dbc" / (dbc_name + ".dbc"), .kind = DbcEditorState::SourceKind::Opendbc}, + {.path = generated_dbc_dir / (dbc_name + ".dbc"), .kind = DbcEditorState::SourceKind::Generated}, + }}; + for (const DbcEditorSource &candidate : candidates) { + if (fs::exists(candidate.path)) { + return candidate; + } + } + return {}; +} + +void load_dbc_editor_state(const AppSession &session, UiState *state) { + DbcEditorState &editor = state->dbc_editor; + const std::string dbc_name = !session.dbc_override.empty() ? session.dbc_override : session.route_data.dbc_name; + editor.source_name = dbc_name.empty() ? "untitled" : dbc_name; + editor.source_path.clear(); + editor.source_kind = DbcEditorState::SourceKind::None; + if (dbc_name.empty()) { + editor.save_name = "custom_can"; + editor.text = default_dbc_template(); + } else { + const DbcEditorSource source = resolve_dbc_editor_source(dbc_name); + editor.source_kind = source.kind; + editor.source_path = source.path; + editor.text = source.path.empty() ? default_dbc_template() : read_file_or_throw(source.path); + editor.save_name = source.kind == DbcEditorState::SourceKind::Generated ? dbc_name : dbc_name + "_edited"; + } + editor.loaded = true; +} + +bool ensure_dbc_editor_loaded(const AppSession &session, UiState *state) { + if (!state->dbc_editor.loaded) { + try { + load_dbc_editor_state(session, state); + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + return false; + } + } + return true; +} + +bool save_dbc_editor_contents(AppSession *session, UiState *state) { + DbcEditorState &editor = state->dbc_editor; + editor.save_name = util::strip(editor.save_name); + if (editor.save_name.empty()) { + state->error_text = "DBC name cannot be empty"; + state->open_error_popup = true; + return false; + } + if (editor.source_kind == DbcEditorState::SourceKind::Opendbc && editor.save_name == editor.source_name) { + state->error_text = "Save edited opendbc files under a new name"; + state->open_error_popup = true; + return false; + } + try { + dbc::Database::fromContent(editor.text, editor.save_name + ".dbc"); + const fs::path generated_dbc_dir = repo_root() / "tools" / "jotpluggler" / "generated_dbcs"; + fs::create_directories(generated_dbc_dir); + const fs::path output = generated_dbc_dir / (editor.save_name + ".dbc"); + write_file_or_throw(output, editor.text); + apply_dbc_override_change(session, state, editor.save_name); + editor.source_name = editor.save_name; + editor.source_path = output; + editor.source_kind = DbcEditorState::SourceKind::Generated; + editor.loaded = false; + state->status_text = "Saved DBC " + editor.save_name; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + return false; + } +} + +void draw_dbc_editor_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("DBC Editor")) { + return; + } + DbcEditorState &editor = state->dbc_editor; + if (!ensure_dbc_editor_loaded(*session, state)) { + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + return; + } + ImGui::TextUnformatted("Edit DBC text and save it into generated_dbcs."); + ImGui::Separator(); + ImGui::SetNextItemWidth(260.0f); + input_text_string("DBC Name", &editor.save_name, ImGuiInputTextFlags_AutoSelectAll); + if (!editor.source_path.empty()) { + ImGui::TextDisabled("%s", editor.source_path.string().c_str()); + } else { + ImGui::TextDisabled("New in-memory DBC"); + } + ImGui::Spacing(); + input_text_multiline_string("##dbc_editor_text", &editor.text, ImVec2(920.0f, 520.0f), ImGuiInputTextFlags_AllowTabInput); + ImGui::Spacing(); + if (ImGui::Button("Apply + Save", ImVec2(140.0f, 0.0f))) { + if (save_dbc_editor_contents(session, state)) { + ImGui::CloseCurrentPopup(); + } + } + ImGui::SameLine(); + if (ImGui::Button("Reload Source", ImVec2(140.0f, 0.0f))) { + editor.loaded = false; + } + ImGui::SameLine(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + editor.loaded = false; + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void draw_axis_limits_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Edit Axis Limits")) { + return; + } + const WorkspaceTab *tab = app_active_tab(session->layout, *state); + const bool valid_pane = tab != nullptr + && state->axis_limits.pane_index >= 0 + && state->axis_limits.pane_index < static_cast(tab->panes.size()); + if (!valid_pane) { + ImGui::TextWrapped("The selected pane is no longer available."); + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + state->axis_limits.pane_index = -1; + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + return; + } + + ImGui::TextUnformatted("X range applies to the active tab. Y limits apply to the selected pane."); + ImGui::Separator(); + ImGui::TextUnformatted("Horizontal"); + ImGui::SetNextItemWidth(180.0f); + ImGui::InputDouble("X Min", &state->axis_limits.x_min, 0.0, 0.0, "%.3f"); + ImGui::SetNextItemWidth(180.0f); + ImGui::InputDouble("X Max", &state->axis_limits.x_max, 0.0, 0.0, "%.3f"); + ImGui::Spacing(); + ImGui::TextUnformatted("Vertical"); + ImGui::Checkbox("Use Y Min", &state->axis_limits.y_min_enabled); + ImGui::BeginDisabled(!state->axis_limits.y_min_enabled); + ImGui::SetNextItemWidth(180.0f); + ImGui::InputDouble("Y Min", &state->axis_limits.y_min, 0.0, 0.0, "%.6g"); + ImGui::EndDisabled(); + ImGui::Checkbox("Use Y Max", &state->axis_limits.y_max_enabled); + ImGui::BeginDisabled(!state->axis_limits.y_max_enabled); + ImGui::SetNextItemWidth(180.0f); + ImGui::InputDouble("Y Max", &state->axis_limits.y_max, 0.0, 0.0, "%.6g"); + ImGui::EndDisabled(); + ImGui::Spacing(); + switch (draw_modal_action_row("Apply")) { + case ModalAction::Primary: + if (apply_axis_limits_editor(session, state)) { + state->axis_limits.pane_index = -1; + ImGui::CloseCurrentPopup(); + } + break; + case ModalAction::Secondary: + state->axis_limits.pane_index = -1; + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_error_popup(UiState *state) { + if (state->open_error_popup) { + ImGui::OpenPopup("Error"); + state->open_error_popup = false; + } + if (!app_begin_popup_modal("Error")) { + return; + } + ImGui::TextWrapped("%s", state->error_text.c_str()); + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +} // namespace + +bool reset_layout(AppSession *session, UiState *state) { + try { + if (session->layout_path.empty()) { + start_new_layout(session, state, "Reset layout"); + return true; + } + clear_layout_autosave(*session); + session->layout = load_sketch_layout(session->layout_path); + state->layout_dirty = false; + session->autosave_path = autosave_path_for_layout(session->layout_path); + state->undo.reset(session->layout); + refresh_replaced_layout_ui(session, state, false); + reset_shared_range(state, *session); + state->status_text = "Reset layout"; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to reset layout"; + return false; + } +} + +bool reload_layout(AppSession *session, UiState *state, const std::string &layout_arg) { + try { + const bool preserve_shared_range = session->route_data.has_time_range && state->has_shared_range; + const double preserved_x_min = state->x_view_min; + const double preserved_x_max = state->x_view_max; + const fs::path layout_path = resolve_layout_path(layout_arg); + session->autosave_path = autosave_path_for_layout(layout_path); + const bool load_draft = fs::exists(session->autosave_path); + session->layout = load_sketch_layout(load_draft ? session->autosave_path : layout_path); + session->layout_path = layout_path; + state->layout_dirty = load_draft; + state->undo.reset(session->layout); + refresh_replaced_layout_ui(session, state, true); + if (preserve_shared_range) { + state->has_shared_range = true; + state->x_view_min = preserved_x_min; + state->x_view_max = preserved_x_max; + clamp_shared_range(state, *session); + } else { + reset_shared_range(state, *session); + } + state->status_text = std::string(load_draft ? "Loaded layout draft " : "Loaded layout ") + + layout_path.filename().string(); + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to load layout"; + return false; + } +} + +bool save_layout(AppSession *session, UiState *state, const std::string &layout_path) { + try { + if (layout_path.empty()) throw std::runtime_error("Layout path is empty"); + session->layout.current_tab_index = state->active_tab_index; + const fs::path previous_autosave = session->autosave_path; + const fs::path output = fs::absolute(fs::path(layout_path)); + save_layout_json(session->layout, output); + session->layout_path = output; + session->autosave_path = autosave_path_for_layout(output); + if (!previous_autosave.empty() && previous_autosave != session->autosave_path && fs::exists(previous_autosave)) { + fs::remove(previous_autosave); + } + clear_layout_autosave(*session); + state->layout_dirty = false; + sync_layout_buffers(state, *session); + state->status_text = "Saved layout " + output.filename().string(); + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to save layout"; + return false; + } +} + +void rebuild_session_route_data(AppSession *session, UiState *state, + const RouteLoadProgressCallback &progress) { + apply_route_data(session, state, load_route_data(session->route_name, session->data_dir, session->dbc_override, progress)); +} + +void stop_stream_session(AppSession *session, UiState *state, bool preserve_data) { + if (preserve_data && session->stream_poller && session->data_mode == SessionDataMode::Stream) { + session->stream_poller->setPaused(true); + } else if (session->stream_poller) { + session->stream_poller->stop(); + } + session->stream_paused = preserve_data && session->data_mode == SessionDataMode::Stream; + if (!preserve_data) { + session->stream_time_offset.reset(); + apply_route_data(session, state, RouteData{}); + } + sync_stream_buffers(state, *session); +} + +bool start_stream_session(AppSession *session, + UiState *state, + const StreamSourceConfig &source, + double buffer_seconds, + bool preserve_existing_data) { + try { + if (session->route_loader) { + session->route_loader.reset(); + } + session->data_mode = SessionDataMode::Stream; + session->route_id = {}; + session->route_name.clear(); + session->data_dir.clear(); + session->stream_source = source; + if (session->stream_source.kind == StreamSourceKind::CerealLocal) { + session->stream_source.address = "127.0.0.1"; + } + session->stream_buffer_seconds = std::max(1.0, buffer_seconds); + session->next_stream_custom_refresh_time = 0.0; + session->stream_paused = false; + if (preserve_existing_data && session->stream_poller) { + StreamPollSnapshot snapshot = session->stream_poller->snapshot(); + if (snapshot.active) { + session->stream_poller->setPaused(false); + sync_route_buffers(state, *session); + sync_stream_buffers(state, *session); + state->follow_latest = true; + state->playback_playing = false; + state->status_text = "Resumed stream " + stream_source_target_label(session->stream_source); + return true; + } + } + if (!preserve_existing_data) { + session->stream_time_offset.reset(); + apply_route_data(session, state, RouteData{}); + } + if (!session->stream_poller) { + session->stream_poller = std::make_unique(); + } + session->stream_poller->start(session->stream_source, + session->stream_buffer_seconds, + session->dbc_override, + session->stream_time_offset); + sync_route_buffers(state, *session); + sync_stream_buffers(state, *session); + state->follow_latest = true; + state->playback_playing = false; + state->status_text = preserve_existing_data ? "Resumed stream " + stream_source_target_label(session->stream_source) + : "Streaming from " + stream_source_target_label(session->stream_source); + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to start stream"; + return false; + } +} + +void start_async_route_load(AppSession *session, UiState *state) { + if (!session->route_loader) { + return; + } + apply_route_data(session, state, RouteData{}); + session->route_loader->start(session->route_name, session->data_dir, session->dbc_override); + state->status_text = session->route_name.empty() ? "Ready" : "Loading route " + session->route_name; +} + +void poll_async_route_load(AppSession *session, UiState *state) { + if (!session->route_loader) { + return; + } + RouteData loaded_route; + std::string error_text; + if (!session->route_loader->consume(&loaded_route, &error_text)) { + return; + } + if (!error_text.empty()) { + state->error_text = error_text; + state->open_error_popup = true; + state->status_text = "Failed to load route"; + return; + } + apply_route_data(session, state, std::move(loaded_route)); + state->status_text = session->route_name.empty() ? "Ready" : "Loaded route " + session->route_name; +} + +bool reload_session(AppSession *session, UiState *state, const std::string &route_name, const std::string &data_dir) { + try { + stop_stream_session(session, state, false); + session->data_mode = SessionDataMode::Route; + session->route_name = route_name; + session->route_id = parse_route_identifier(route_name); + session->data_dir = data_dir; + if (session->async_route_loading) { + if (!session->route_loader) { + session->route_loader = std::make_unique(::isatty(STDERR_FILENO) != 0); + } + start_async_route_load(session, state); + } else { + rebuild_session_route_data(session, state); + state->status_text = "Loaded route " + route_name; + } + sync_route_buffers(state, *session); + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to load route"; + return false; + } +} + +void draw_popups(AppSession *session, UiState *state) { + open_queued_popup(state->open_open_route, "Open Route"); + if (state->open_stream) { + sync_stream_buffers(state, *session); + } + open_queued_popup(state->open_stream, "Live Stream"); + if (state->open_load_layout || state->open_save_layout) { + sync_layout_buffers(state, *session); + } + open_queued_popup(state->open_load_layout, "Load Layout"); + open_queued_popup(state->open_save_layout, "Save Layout"); + open_queued_popup(state->open_preferences, "Preferences"); + open_queued_popup(state->dbc_editor.open, "DBC Editor"); + open_queued_popup(state->open_find_signal, "Find Signal"); + open_queued_popup(state->axis_limits.open, "Edit Axis Limits"); + + draw_open_route_popup(session, state); + draw_stream_popup(session, state); + draw_load_layout_popup(session, state); + draw_save_layout_popup(session, state); + draw_preferences_popup(session, state); + draw_dbc_editor_popup(session, state); + draw_find_signal_popup(session, state); + draw_axis_limits_popup(session, state); + draw_error_popup(state); +} diff --git a/tools/jotpluggler/layout_io.cc b/tools/jotpluggler/layout_io.cc new file mode 100644 index 00000000000000..5c70f7a42add43 --- /dev/null +++ b/tools/jotpluggler/layout_io.cc @@ -0,0 +1,128 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" + +#include +#include +#include +#include + +#include "json11/json11.hpp" + +namespace fs = std::filesystem; + +namespace { + +std::string curve_color_hex(const std::array &color) { + std::ostringstream hex; + hex << "#" << std::hex << std::setfill('0') + << std::setw(2) << static_cast(color[0]) + << std::setw(2) << static_cast(color[1]) + << std::setw(2) << static_cast(color[2]); + return hex.str(); +} + +json11::Json curve_to_json(const Curve &curve) { + json11::Json::object obj = { + {"name", curve.name}, + {"color", curve_color_hex(curve.color)}, + }; + if (curve.derivative) { + obj["transform"] = "derivative"; + if (curve.derivative_dt > 0.0) { + obj["derivative_dt"] = curve.derivative_dt; + } + } else if (std::abs(curve.value_scale - 1.0) > 1.0e-9 || std::abs(curve.value_offset) > 1.0e-9) { + obj["transform"] = "scale"; + obj["scale"] = curve.value_scale; + obj["offset"] = curve.value_offset; + } + if (curve.custom_python.has_value()) { + json11::Json::array additional_sources; + for (const std::string &path : curve.custom_python->additional_sources) { + additional_sources.push_back(path); + } + obj["custom_python"] = json11::Json::object{ + {"linked_source", curve.custom_python->linked_source}, + {"additional_sources", additional_sources}, + {"globals_code", curve.custom_python->globals_code}, + {"function_code", curve.custom_python->function_code}, + }; + } + return obj; +} + +json11::Json workspace_node_to_json(const WorkspaceNode &node, const WorkspaceTab &tab) { + if (node.is_pane) { + if (node.pane_index < 0 || node.pane_index >= static_cast(tab.panes.size())) { + return nullptr; + } + const Pane &pane = tab.panes[static_cast(node.pane_index)]; + json11::Json::object obj = { + {"title", pane.title.empty() ? std::string("...") : pane.title}, + }; + if (pane.kind == PaneKind::Map) { + obj["kind"] = "map"; + } else if (pane.kind == PaneKind::Camera) { + obj["kind"] = "camera"; + obj["camera_view"] = camera_view_spec(pane.camera_view).layout_name; + } + if (pane.range.valid) { + obj["range"] = json11::Json::object{ + {"left", pane.range.left}, {"right", pane.range.right}, + {"top", pane.range.top}, {"bottom", pane.range.bottom}, + }; + } + if (pane.range.has_y_limit_min || pane.range.has_y_limit_max) { + json11::Json::object limits; + if (pane.range.has_y_limit_min) { + limits["min"] = pane.range.y_limit_min; + } + if (pane.range.has_y_limit_max) { + limits["max"] = pane.range.y_limit_max; + } + obj["y_limits"] = limits; + } + json11::Json::array curves; + for (const Curve &curve : pane.curves) { + if (!curve.runtime_only) { + curves.push_back(curve_to_json(curve)); + } + } + obj["curves"] = curves; + return obj; + } + + if (node.children.empty()) return nullptr; + json11::Json::array sizes; + for (size_t i = 0; i < node.children.size(); ++i) { + sizes.push_back(i < node.sizes.size() ? static_cast(node.sizes[i]) + : 1.0 / static_cast(node.children.size())); + } + json11::Json::array children; + for (const WorkspaceNode &child : node.children) { + children.push_back(workspace_node_to_json(child, tab)); + } + return json11::Json::object{ + {"split", node.orientation == SplitOrientation::Horizontal ? "horizontal" : "vertical"}, + {"sizes", sizes}, + {"children", children}, + }; +} + +} // namespace + +void save_layout_json(const SketchLayout &layout, const fs::path &path) { + ensure_parent_dir(path); + json11::Json::array tabs; + for (const WorkspaceTab &tab : layout.tabs) { + tabs.push_back(json11::Json::object{ + {"name", tab.tab_name}, + {"root", workspace_node_to_json(tab.root, tab)}, + }); + } + const json11::Json root = json11::Json::object{ + {"current_tab_index", std::clamp(layout.current_tab_index, 0, std::max(0, static_cast(layout.tabs.size()) - 1))}, + {"tabs", tabs}, + }; + write_file_or_throw(path, root.dump() + "\n"); +} diff --git a/tools/jotpluggler/layouts/.gitignore b/tools/jotpluggler/layouts/.gitignore new file mode 100644 index 00000000000000..a965bb777d6c66 --- /dev/null +++ b/tools/jotpluggler/layouts/.gitignore @@ -0,0 +1 @@ +.jotpluggler_autosave/ diff --git a/tools/jotpluggler/layouts/CAN-bus-debug.json b/tools/jotpluggler/layouts/CAN-bus-debug.json new file mode 100644 index 00000000000000..496993a1fd4835 --- /dev/null +++ b/tools/jotpluggler/layouts/CAN-bus-debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.33362,0.33276,0.33362],"children":[{"title":"CAN RX","range":{"left":0.0,"right":60.526742,"top":1101.875,"bottom":-26.875},"curves":[{"name":"/pandaStates/0/canState0/totalRxCnt","color":"#f14cc1","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState1/totalRxCnt","color":"#9467bd","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState2/totalRxCnt","color":"#ff7f0e","transform":"derivative","derivative_dt":1.0}]},{"title":"CAN TX","range":{"left":0.0,"right":60.526742,"top":455.1,"bottom":-11.1},"curves":[{"name":"/pandaStates/0/canState0/totalTxCnt","color":"#17becf","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState1/totalTxCnt","color":"#bcbd22","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState2/totalTxCnt","color":"#1f77b4","transform":"derivative","derivative_dt":1.0}]},{"title":"CAN errors","range":{"left":0.0,"right":60.526742,"top":2515.35,"bottom":-61.35},"curves":[{"name":"/pandaStates/0/canState0/totalErrorCnt","color":"#1f77b4","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState1/totalErrorCnt","color":"#d62728","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState2/totalErrorCnt","color":"#1ac938","transform":"derivative","derivative_dt":1.0}]}]}}]} diff --git a/tools/jotpluggler/layouts/camera-timings.json b/tools/jotpluggler/layouts/camera-timings.json new file mode 100644 index 00000000000000..64decf15d387e5 --- /dev/null +++ b/tools/jotpluggler/layouts/camera-timings.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"SOF / EOF (encodeIdx)","root":{"split":"vertical","sizes":[0.500885,0.499115],"children":[{"title":"...","range":{"left":0.0,"right":630.006367,"top":65000000.0,"bottom":35000000.0},"curves":[{"name":"/driverEncodeIdx/timestampSof","color":"#1f77b4","transform":"derivative","derivative_dt":1.0},{"name":"/roadEncodeIdx/timestampSof","color":"#d62728","transform":"derivative","derivative_dt":1.0},{"name":"/wideRoadEncodeIdx/timestampSof","color":"#1ac938","transform":"derivative","derivative_dt":1.0}],"y_limits":{"min":35000000.0,"max":65000000.0}},{"title":"...","range":{"left":0.0,"right":630.006367,"top":65000000.0,"bottom":35000000.0},"curves":[{"name":"/driverEncodeIdx/timestampEof","color":"#f14cc1","transform":"derivative","derivative_dt":1.0},{"name":"/roadEncodeIdx/timestampEof","color":"#9467bd","transform":"derivative","derivative_dt":1.0},{"name":"/wideRoadEncodeIdx/timestampEof","color":"#17becf","transform":"derivative","derivative_dt":1.0}],"y_limits":{"min":35000000.0,"max":65000000.0}}]}},{"name":"model timings","root":{"split":"vertical","sizes":[0.5,0.5],"children":[{"title":"...","range":{"left":0.0,"right":630.006367,"top":0.016865,"bottom":0.015143},"curves":[{"name":"/modelV2/modelExecutionTime","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.0,"right":630.006367,"top":0.1,"bottom":-0.1},"curves":[{"name":"/modelV2/frameDropPerc","color":"#f14cc1"}]}]}},{"name":"sensor info","root":{"split":"vertical","sizes":[1.0],"children":[{"title":"...","range":{"left":0.0,"right":630.006367,"top":0.1,"bottom":-0.1},"curves":[{"name":"/driverCameraState/sensor","color":"#bcbd22"},{"name":"/roadCameraState/sensor","color":"#1f77b4"},{"name":"/wideRoadCameraState/sensor","color":"#d62728"}]}]}},{"name":"SOF / EOF (cameraState)","root":{"split":"vertical","sizes":[0.500885,0.499115],"children":[{"title":"...","range":{"left":0.0,"right":630.006367,"top":65000000.0,"bottom":35000000.0},"curves":[{"name":"/driverCameraState/timestampSof","color":"#1f77b4","transform":"derivative","derivative_dt":1.0},{"name":"/roadCameraState/timestampSof","color":"#d62728","transform":"derivative","derivative_dt":1.0},{"name":"/wideRoadCameraState/timestampSof","color":"#1ac938","transform":"derivative","derivative_dt":1.0}],"y_limits":{"min":35000000.0,"max":65000000.0}},{"title":"...","range":{"left":0.0,"right":630.006367,"top":65000000.0,"bottom":35000000.0},"curves":[{"name":"/driverCameraState/timestampEof","color":"#ff7f0e","transform":"derivative","derivative_dt":1.0},{"name":"/roadCameraState/timestampEof","color":"#f14cc1","transform":"derivative","derivative_dt":1.0},{"name":"/wideRoadCameraState/timestampEof","color":"#9467bd","transform":"derivative","derivative_dt":1.0}],"y_limits":{"min":35000000.0,"max":65000000.0}}]}}]} diff --git a/tools/jotpluggler/layouts/cameras-and-map.json b/tools/jotpluggler/layouts/cameras-and-map.json new file mode 100644 index 00000000000000..68c590f7bc5711 --- /dev/null +++ b/tools/jotpluggler/layouts/cameras-and-map.json @@ -0,0 +1 @@ +{"current_tab_index": 0, "tabs": [{"name": "tab1", "root": {"children": [{"children": [{"curves": [], "kind": "map", "title": "Map"}, {"camera_view": "road", "curves": [], "kind": "camera", "title": "Road Camera"}], "sizes": [0.5, 0.5], "split": "horizontal"}, {"children": [{"camera_view": "wide_road", "curves": [], "kind": "camera", "title": "Wide Road Camera"}, {"camera_view": "driver", "curves": [], "kind": "camera", "title": "Driver Camera"}], "sizes": [0.5, 0.5], "split": "horizontal"}], "sizes": [0.5, 0.5], "split": "vertical"}}]} diff --git a/tools/jotpluggler/layouts/can-states.json b/tools/jotpluggler/layouts/can-states.json new file mode 100644 index 00000000000000..6f04940a33527d --- /dev/null +++ b/tools/jotpluggler/layouts/can-states.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.500381,0.499619],"children":[{"split":"horizontal","sizes":[0.5,0.5],"children":[{"title":"...","range":{"left":0.0,"right":632.799721,"top":771630.925,"bottom":-17755.925},"curves":[{"name":"/pandaStates/0/canState0/totalRxCnt","color":"#1f77b4"},{"name":"/pandaStates/0/canState1/totalRxCnt","color":"#d62728"},{"name":"/pandaStates/0/canState2/totalRxCnt","color":"#1ac938"}]},{"title":"...","range":{"left":0.0,"right":632.799721,"top":760365.5,"bottom":-18545.5},"curves":[{"name":"/pandaStates/0/canState0/totalTxCnt","color":"#ff7f0e"},{"name":"/pandaStates/0/canState1/totalTxCnt","color":"#f14cc1"},{"name":"/pandaStates/0/canState2/totalTxCnt","color":"#9467bd"}]}]},{"split":"horizontal","sizes":[0.333333,0.333333,0.333333],"children":[{"title":"...","range":{"left":0.0,"right":632.799721,"top":55.35,"bottom":-1.35},"curves":[{"name":"/pandaStates/0/canState0/totalRxLostCnt","color":"#ff7f0e"},{"name":"/pandaStates/0/canState1/totalRxLostCnt","color":"#f14cc1"},{"name":"/pandaStates/0/canState2/totalRxLostCnt","color":"#9467bd"}]},{"title":"...","range":{"left":0.0,"right":632.799721,"top":2.05,"bottom":-0.05},"curves":[{"name":"/pandaStates/0/canState0/totalTxLostCnt","color":"#17becf"},{"name":"/pandaStates/0/canState1/totalTxLostCnt","color":"#bcbd22"},{"name":"/pandaStates/0/canState2/totalTxLostCnt","color":"#1f77b4"}]},{"title":"...","range":{"left":0.0,"right":632.799721,"top":0.1,"bottom":-0.1},"curves":[{"name":"/pandaStates/0/canState0/busOffCnt","color":"#17becf"},{"name":"/pandaStates/0/canState1/busOffCnt","color":"#1ac938"},{"name":"/pandaStates/0/canState2/busOffCnt","color":"#bcbd22"}]}]}]}}]} diff --git a/tools/jotpluggler/layouts/controls_mismatch_debug.json b/tools/jotpluggler/layouts/controls_mismatch_debug.json new file mode 100644 index 00000000000000..16912cd68401fe --- /dev/null +++ b/tools/jotpluggler/layouts/controls_mismatch_debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.2,0.2,0.2,0.2,0.2],"children":[{"title":"...","range":{"left":0.018309,"right":59.674401,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carControl/enabled","color":"#1f77b4"},{"name":"/pandaStates/0/controlsAllowed","color":"#d62728"}]},{"title":"...","range":{"left":0.018309,"right":59.674401,"top":27.087398,"bottom":-0.905168},"curves":[{"name":"/carState/cumLagMs","color":"#9467bd"}]},{"title":"...","range":{"left":0.018309,"right":59.674401,"top":1.025,"bottom":-0.025},"curves":[{"name":"/pandaStates/0/safetyRxInvalid","color":"#1f77b4"},{"name":"/pandaStates/0/safetyRxChecksInvalid","color":"#e801ce"}]},{"title":"...","range":{"left":0.018309,"right":59.674401,"top":158.85,"bottom":-2.85},"curves":[{"name":"/pandaStates/0/safetyTxBlocked","color":"#d62728"}]},{"title":"...","range":{"left":0.018309,"right":59.674401,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carState/gasPressed","color":"#1ac938"},{"name":"/carState/brakePressed","color":"#ff7f0e"}]}]}}]} diff --git a/tools/jotpluggler/layouts/driver-monitoring-debug.json b/tools/jotpluggler/layouts/driver-monitoring-debug.json new file mode 100644 index 00000000000000..07a5c2fd6e5d28 --- /dev/null +++ b/tools/jotpluggler/layouts/driver-monitoring-debug.json @@ -0,0 +1 @@ +{"current_tab_index": 0, "tabs": [{"name": "tab1", "root": {"children": [{"children": [{"camera_view": "driver", "curves": [], "kind": "camera", "title": "Driver Camera"}, {"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/alertLevel"}], "title": "..."}], "sizes": [0.5, 0.5], "split": "vertical"}, {"children": [{"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/activePolicy"}], "title": "..."}, {"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/visionPolicyState/faceDetected"}], "title": "..."}, {"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/visionPolicyState/distractedTypes/eye"}, {"color": "#dc5234", "name": "/driverMonitoringState/visionPolicyState/distractedTypes/phone"}, {"color": "#43a047", "name": "/driverMonitoringState/visionPolicyState/distractedTypes/pose"}], "title": "..."}, {"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/visionPolicyState/awarenessPercent"}], "title": "..."}], "sizes": [0.25, 0.25, 0.25, 0.25], "split": "vertical"}], "sizes": [0.5, 0.5], "split": "horizontal"}}]} diff --git a/tools/jotpluggler/layouts/gps.json b/tools/jotpluggler/layouts/gps.json new file mode 100644 index 00000000000000..fdabbfd381c6ad --- /dev/null +++ b/tools/jotpluggler/layouts/gps.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.24977,0.250689,0.24977,0.24977],"children":[{"title":"...","range":{"left":0.0,"right":1678.753571,"top":1.025,"bottom":-0.025},"curves":[{"name":"/gpsLocationExternal/hasFix","color":"#1f77b4"}]},{"title":"...","range":{"left":0.0,"right":1678.753571,"top":17.425,"bottom":-0.425},"curves":[{"name":"/gpsLocationExternal/satelliteCount","color":"#d62728"}]},{"title":"...","range":{"left":0.0,"right":1678.753571,"top":3.0,"bottom":0.0},"curves":[{"name":"/gpsLocationExternal/horizontalAccuracy","color":"#1ac938"}],"y_limits":{"min":0.0,"max":3.0}},{"title":"...","range":{"left":0.0,"right":1678.753571,"top":766.374004,"bottom":-17.262},"curves":[{"name":"/gpsLocationExternal/horizontalAccuracy","color":"#1ac938"}]}]}}]} diff --git a/tools/jotpluggler/layouts/gps_vs_llk.json b/tools/jotpluggler/layouts/gps_vs_llk.json new file mode 100644 index 00000000000000..878e0a57a81405 --- /dev/null +++ b/tools/jotpluggler/layouts/gps_vs_llk.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.333805,0.33239,0.333805],"children":[{"title":"...","range":{"left":76.646983,"right":196.811937,"top":32.070386,"bottom":0.368228},"curves":[{"name":"haversine distance [m]","color":"#1f77b4","custom_python":{"linked_source":"/gpsLocationExternal/latitude","additional_sources":["/gpsLocationExternal/longitude","/liveLocationKalmanDEPRECATED/positionGeodetic/value/0","/liveLocationKalmanDEPRECATED/positionGeodetic/value/1"],"globals_code":"R = 6378.137 # Radius of earth in KM","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global R\n # Compute the Haversine distance between\n # two points defined by latitude and longitude.\n # Return the distance in meters\n lat1, lon1 = value, v1\n lat2, lon2 = v2, v3\n dLat = (lat2 - lat1) * np.pi / 180\n dLon = (lon2 - lon1) * np.pi / 180\n a = np.sin(dLat/2) * np.sin(dLat/2) +\n np.cos(lat1 * np.pi / 180) * np.cos(lat2 * np.pi / 180) *\n np.sin(dLon/2) * np.sin(dLon/2)\n c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))\n d = R * c\n distance = d * 1000 # meters\n return distance\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"...","range":{"left":76.646983,"right":196.811937,"top":12.637299,"bottom":-0.259115},"curves":[{"name":"/carState/vEgo","color":"#17becf"},{"name":"/gpsLocationExternal/speed","color":"#bcbd22"}]},{"split":"horizontal","sizes":[0.500516,0.499484],"children":[{"title":"...","range":{"left":76.646983,"right":196.811937,"top":0.1,"bottom":-0.1},"curves":[{"name":"/liveLocationKalmanDEPRECATED/positionGeodetic/std/0","color":"#d62728"},{"name":"/liveLocationKalmanDEPRECATED/positionGeodetic/std/1","color":"#1ac938"}]},{"title":"...","range":{"left":76.646983,"right":196.811937,"top":7.160833,"bottom":-0.449385},"curves":[{"name":"/gpsLocationExternal/horizontalAccuracy","color":"#ff7f0e"},{"name":"/gpsLocationExternal/verticalAccuracy","color":"#f14cc1"},{"name":"/gpsLocationExternal/speedAccuracy","color":"#9467bd"}]}]}]}}]} diff --git a/tools/jotpluggler/layouts/locationd_debug.json b/tools/jotpluggler/layouts/locationd_debug.json new file mode 100644 index 00000000000000..0541427bc1e29e --- /dev/null +++ b/tools/jotpluggler/layouts/locationd_debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.166588,0.167062,0.166113,0.166588,0.167062,0.166588],"children":[{"title":"...","range":{"left":0.0,"right":2280.128382,"top":1.025,"bottom":-0.025},"curves":[{"name":"/livePose/inputsOK","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":14.542814,"bottom":-5.586039},"curves":[{"name":"/accelerometer/acceleration/v/0","color":"#f14cc1"},{"name":"/accelerometer/acceleration/v/1","color":"#9467bd"},{"name":"/accelerometer/acceleration/v/2","color":"#17becf"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":0.988911,"bottom":-0.745939},"curves":[{"name":"/gyroscope/gyroUncalibrated/v/0","color":"#d62728"},{"name":"/gyroscope/gyroUncalibrated/v/1","color":"#1ac938"},{"name":"/gyroscope/gyroUncalibrated/v/2","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":1.025,"bottom":-0.025},"curves":[{"name":"/accelerometer/__valid","color":"#17becf"},{"name":"/gyroscope/__valid","color":"#bcbd22"},{"name":"/carState/__valid","color":"#f14cc1"},{"name":"/liveCalibration/__valid","color":"#1ac938"},{"name":"/cameraOdometry/__valid","color":"#9467bd"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":1000000000.292252,"bottom":999999999.735447},"curves":[{"name":"/gyroscope/__logMonoTime","color":"#1f77b4","transform":"derivative"},{"name":"/accelerometer/__logMonoTime","color":"#d62728","transform":"derivative"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":20790107743.93223,"bottom":-529653831.495853},"curves":[{"name":"/accelerometer/timestamp","color":"#bcbd22","transform":"derivative"},{"name":"/gyroscope/timestamp","color":"#1f77b4","transform":"derivative"}]}]}}]} diff --git a/tools/jotpluggler/layouts/longitudinal.json b/tools/jotpluggler/layouts/longitudinal.json new file mode 100644 index 00000000000000..27f43eb35775d1 --- /dev/null +++ b/tools/jotpluggler/layouts/longitudinal.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.250401,0.249599,0.250401,0.249599],"children":[{"title":"...","range":{"left":104.907277,"right":126.285782,"top":1.391623,"bottom":-2.563614},"curves":[{"name":"/carState/aEgo","color":"#f14cc1"},{"name":"/longitudinalPlan/accels/0","color":"#9467bd"},{"name":"/carControl/actuators/accel","color":"#17becf"},{"name":"/carOutput/actuatorsOutput/accel","color":"#d62728"}]},{"title":"...","range":{"left":104.907277,"right":126.285782,"top":1.18496,"bottom":-1.811222},"curves":[{"name":"/controlsState/upAccelCmd","color":"#1f77b4"},{"name":"/controlsState/uiAccelCmd","color":"#d62728"},{"name":"/controlsState/ufAccelCmd","color":"#1ac938"}]},{"title":"...","range":{"left":104.907277,"right":126.285782,"top":15.862889,"bottom":-0.568809},"curves":[{"name":"/carState/vEgo","color":"#1ac938"},{"name":"/longitudinalPlan/speeds/0","color":"#ff7f0e"}]},{"title":"...","range":{"left":104.907277,"right":126.285782,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carControl/longActive","color":"#1f77b4"},{"name":"/carState/gasPressed","color":"#d62728"}]}]}}]} diff --git a/tools/jotpluggler/layouts/max-torque-debug.json b/tools/jotpluggler/layouts/max-torque-debug.json new file mode 100644 index 00000000000000..3a87fb3217bf20 --- /dev/null +++ b/tools/jotpluggler/layouts/max-torque-debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.249724,0.250829,0.249724,0.249724],"children":[{"title":"...","range":{"left":0.00045,"right":2483.624998,"top":6.050533,"bottom":-7.599037},"curves":[{"name":"Actual lateral accel (roll compensated)","color":"#1ac938","custom_python":{"linked_source":"/controlsState/curvature","additional_sources":["/carState/vEgo","/liveParameters/roll"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n return (value * v1 ** 2) - (v2 * 9.81)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"Desired lateral accel (roll compensated)","color":"#ff7f0e","custom_python":{"linked_source":"/controlsState/desiredCurvature","additional_sources":["/carState/vEgo","/liveParameters/roll"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n return (value * v1 ** 2) - (v2 * 9.81)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"...","range":{"left":0.00045,"right":2483.624998,"top":5.384416,"bottom":-7.503945},"curves":[{"name":"roll compensated lateral acceleration","color":"#1ac938","custom_python":{"linked_source":"/controlsState/curvature","additional_sources":["/carState/vEgo","/liveParameters/roll","/carState/steeringPressed","/carControl/latActive"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3, v4):\n if (v3 == 0 and v4 == 1):\n return (value * v1 ** 2) - (v2 * 9.81)\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i], v4[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"...","range":{"left":0.00045,"right":2483.624998,"top":1.05,"bottom":-1.05},"curves":[{"name":"/carState/steeringPressed","color":"#0097ff"},{"name":"/carOutput/actuatorsOutput/torque","color":"#d62728"}]},{"title":"...","range":{"left":0.00045,"right":2483.624998,"top":80.762969,"bottom":-2.181837},"curves":[{"name":"/carState/vEgo","color":"#f14cc1","transform":"scale","scale":2.23694,"offset":0.0}]}]}}]} diff --git a/tools/jotpluggler/layouts/new-layout.json b/tools/jotpluggler/layouts/new-layout.json new file mode 100644 index 00000000000000..bffb62d7c76c1e --- /dev/null +++ b/tools/jotpluggler/layouts/new-layout.json @@ -0,0 +1 @@ +{"current_tab_index": 0, "tabs": [{"name": "tab1", "root": {"curves": [], "title": "..."}}]} diff --git a/tools/jotpluggler/layouts/system_lag_debug.json b/tools/jotpluggler/layouts/system_lag_debug.json new file mode 100644 index 00000000000000..281de440faa363 --- /dev/null +++ b/tools/jotpluggler/layouts/system_lag_debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.249729,0.250814,0.249729,0.249729],"children":[{"title":"...","range":{"left":0.0,"right":59.992103,"top":102.5,"bottom":-2.5},"curves":[{"name":"/deviceState/cpuUsagePercent/0","color":"#1f77b4"},{"name":"/deviceState/cpuUsagePercent/1","color":"#d62728"},{"name":"/deviceState/cpuUsagePercent/2","color":"#1ac938"},{"name":"/deviceState/cpuUsagePercent/3","color":"#ff7f0e"},{"name":"/deviceState/cpuUsagePercent/4","color":"#f14cc1"},{"name":"/deviceState/cpuUsagePercent/5","color":"#9467bd"},{"name":"/deviceState/cpuUsagePercent/6","color":"#17becf"},{"name":"/deviceState/cpuUsagePercent/7","color":"#bcbd22"}]},{"title":"...","range":{"left":0.0,"right":59.992103,"top":64.005001,"bottom":51.195},"curves":[{"name":"/deviceState/cpuTempC/0","color":"#d62728"},{"name":"/deviceState/cpuTempC/1","color":"#1ac938"},{"name":"/deviceState/cpuTempC/2","color":"#ff7f0e"},{"name":"/deviceState/cpuTempC/3","color":"#f14cc1"},{"name":"/deviceState/cpuTempC/4","color":"#9467bd"},{"name":"/deviceState/cpuTempC/5","color":"#17becf"},{"name":"/deviceState/cpuTempC/6","color":"#bcbd22"},{"name":"/deviceState/cpuTempC/7","color":"#1f77b4"},{"name":"/deviceState/gpuTempC/0","color":"#d62728"},{"name":"/deviceState/gpuTempC/1","color":"#1ac938"}]},{"title":"...","range":{"left":0.0,"right":59.992103,"top":37.371108,"bottom":-0.91149},"curves":[{"name":"/modelV2/frameDropPerc","color":"#f14cc1"}]},{"title":"...","range":{"left":0.0,"right":59.992103,"top":-3.593455,"bottom":-12.190956},"curves":[{"name":"/carState/cumLagMs","color":"#9467bd"}]}]}}]} diff --git a/tools/jotpluggler/layouts/thermal_debug.json b/tools/jotpluggler/layouts/thermal_debug.json new file mode 100644 index 00000000000000..3a7ce454cf6f83 --- /dev/null +++ b/tools/jotpluggler/layouts/thermal_debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.166785,0.166785,0.166075,0.166785,0.166785,0.166785],"children":[{"title":"...","range":{"left":0.006955,"right":301.842654,"top":87.987497,"bottom":75.912497},"curves":[{"name":"/deviceState/cpuTempC/0","color":"#1f77b4"},{"name":"/deviceState/cpuTempC/1","color":"#d62728"},{"name":"/deviceState/cpuTempC/2","color":"#1ac938"},{"name":"/deviceState/cpuTempC/3","color":"#ff7f0e"},{"name":"/deviceState/cpuTempC/4","color":"#f14cc1"},{"name":"/deviceState/cpuTempC/5","color":"#9467bd"},{"name":"/deviceState/cpuTempC/6","color":"#17becf"},{"name":"/deviceState/cpuTempC/7","color":"#bcbd22"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":85.861052,"bottom":66.49695},"curves":[{"name":"/deviceState/pmicTempC/0","color":"#1f77b4"},{"name":"/deviceState/gpuTempC/0","color":"#d62728"},{"name":"/deviceState/gpuTempC/1","color":"#1ac938"},{"name":"/deviceState/memoryTempC","color":"#f14cc1"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":86.207876,"bottom":70.665918},"curves":[{"name":"/deviceState/maxTempC","color":"#1f77b4"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":1.025,"bottom":-0.025},"curves":[{"name":"/deviceState/thermalStatus","color":"#1f77b4"}]},{"split":"horizontal","sizes":[0.333124,0.333752,0.333124],"children":[{"title":"...","range":{"left":0.006955,"right":301.842654,"top":12.057358,"bottom":4.843517},"curves":[{"name":"/deviceState/powerDrawW","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":100.0,"bottom":0.0},"curves":[{"name":"/deviceState/fanSpeedPercentDesired","color":"#9467bd"},{"name":"/pandaStates/0/fanPower","color":"#1f77b4"}],"y_limits":{"min":0.0,"max":100.0}},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":5018.4,"bottom":255.6},"curves":[{"name":"/peripheralState/fanSpeedRpm","color":"#1f77b4"}]}]},{"split":"horizontal","sizes":[0.502513,0.497487],"children":[{"title":"...","range":{"left":0.006955,"right":301.842654,"top":100.025,"bottom":14.975},"curves":[{"name":"/deviceState/cpuUsagePercent/0","color":"#1f77b4"},{"name":"/deviceState/cpuUsagePercent/1","color":"#d62728"},{"name":"/deviceState/cpuUsagePercent/2","color":"#1ac938"},{"name":"/deviceState/cpuUsagePercent/3","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":102.5,"bottom":-2.5},"curves":[{"name":"/deviceState/cpuUsagePercent/4","color":"#f14cc1"},{"name":"/deviceState/cpuUsagePercent/5","color":"#9467bd"},{"name":"/deviceState/cpuUsagePercent/6","color":"#17becf"},{"name":"/deviceState/cpuUsagePercent/7","color":"#bcbd22"}]}]}]}}]} diff --git a/tools/jotpluggler/layouts/torque-controller.json b/tools/jotpluggler/layouts/torque-controller.json new file mode 100644 index 00000000000000..7e269e59e6c95d --- /dev/null +++ b/tools/jotpluggler/layouts/torque-controller.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"Lateral Plan Conformance","root":{"split":"vertical","sizes":[0.250949,0.249051,0.250949,0.249051],"children":[{"title":"desired vs actual lateral acceleration (closer means better conformance to plan)","range":{"left":0.000194,"right":1138.891674,"top":1.858161,"bottom":-1.823407},"curves":[{"name":"/controlsState/lateralControlState/torqueState/actualLateralAccel","color":"#1f77b4"},{"name":"/controlsState/lateralControlState/torqueState/desiredLateralAccel","color":"#d62728"}]},{"title":"desired vs actual lateral acceleration, road-roll factored out (closer means better conformance to plan)","range":{"left":0.000194,"right":1138.891674,"top":2.749816,"bottom":-3.723091},"curves":[{"name":"Actual lateral accel (roll compensated)","color":"#1ac938","custom_python":{"linked_source":"/controlsState/curvature","additional_sources":["/carState/vEgo","/liveParameters/roll"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n return (value * v1 ** 2) - (v2 * 9.81)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"Desired lateral accel (roll compensated)","color":"#ff7f0e","custom_python":{"linked_source":"/controlsState/desiredCurvature","additional_sources":["/carState/vEgo","/liveParameters/roll"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n return (value * v1 ** 2) - (v2 * 9.81)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"controller feed-forward vs actuator output (closer means controller prediction is more accurate)","range":{"left":0.000194,"right":1138.891674,"top":1.978032,"bottom":-1.570956},"curves":[{"name":"/carOutput/actuatorsOutput/torque","color":"#9467bd","transform":"scale","scale":-1.0,"offset":0.0},{"name":"/controlsState/lateralControlState/torqueState/f","color":"#1f77b4"},{"name":"/carState/steeringPressed","color":"#ff000f"}]},{"title":"vehicle speed","range":{"left":0.000194,"right":1138.891674,"top":105.981304,"bottom":-2.709314},"curves":[{"name":"carState.vEgo mph","color":"#d62728","custom_python":{"linked_source":"/carState/vEgo","additional_sources":[],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value):\n return value * 2.23694\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"carState.vEgo kmh","color":"#1ac938","custom_python":{"linked_source":"/carState/vEgo","additional_sources":[],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value):\n return value * 3.6\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"/carState/vEgo","color":"#ff7f0e"}]}]}},{"name":"Vehicle Dynamics","root":{"split":"vertical","sizes":[0.334282,0.331437,0.334282],"children":[{"title":"configured-initial vs online-learned steerRatio, set configured value to match learned","range":{"left":0.0,"right":1138.816328,"top":19.665784,"bottom":19.359553},"curves":[{"name":"/carParams/steerRatio","color":"#1f77b4"},{"name":"/liveParameters/steerRatio","color":"#1ac938"}]},{"title":"configured-initial vs online-learned tireStiffnessRatio, set configured value to match learned","range":{"left":0.0,"right":1138.816328,"top":1.11221,"bottom":0.995631},"curves":[{"name":"/carParams/tireStiffnessFactor","color":"#d62728"},{"name":"/liveParameters/stiffnessFactor","color":"#ff7f0e"}]},{"title":"live steering angle offsets for straight-ahead driving, large values here may indicate alignment problems","range":{"left":0.0,"right":1138.816328,"top":-1.081041,"bottom":-4.494133},"curves":[{"name":"/liveParameters/angleOffsetAverageDeg","color":"#f14cc1"},{"name":"/liveParameters/angleOffsetDeg","color":"#9467bd"}]}]}},{"name":"Actuator Performance","root":{"split":"vertical","sizes":[0.333333,0.333333,0.333333],"children":[{"title":"offline-calculated vs online-learned lateral accel scaling factor, accel obtained from 100% actuator output","range":{"left":0.0,"right":1138.920072,"top":1.21611,"bottom":0.539474},"curves":[{"name":"/liveTorqueParameters/latAccelFactorFiltered","color":"#1f77b4"},{"name":"/liveTorqueParameters/latAccelFactorRaw","color":"#d62728"},{"name":"/carParams/lateralTuning/torque/latAccelFactor","color":"#1c9222"}]},{"title":"learned lateral accel offset, vehicle-specific compensation to obtain true zero lateral accel","range":{"left":0.0,"right":1138.920072,"top":-0.304367,"bottom":-0.418688},"curves":[{"name":"/liveTorqueParameters/latAccelOffsetFiltered","color":"#1ac938"},{"name":"/liveTorqueParameters/latAccelOffsetRaw","color":"#ff7f0e"}]},{"title":"offline-calculated vs online-learned EPS friction factor, necessary to start moving the steering wheel","range":{"left":0.0,"right":1138.920072,"top":0.226389,"bottom":0.15805},"curves":[{"name":"/liveTorqueParameters/frictionCoefficientFiltered","color":"#f14cc1"},{"name":"/liveTorqueParameters/frictionCoefficientRaw","color":"#9467bd"},{"name":"/carParams/lateralTuning/torque/friction","color":"#1c9222"}]}]}},{"name":"Actuator Delay","root":{"split":"vertical","sizes":[0.30441,0.358464,0.337127],"children":[{"title":"actuator lag learning state, 0 = learning, 1 = learned/applying, 2 = invalid","range":{"left":0.0,"right":1138.749979,"top":1.025,"bottom":-0.025},"curves":[{"name":"/liveDelay/status","color":"#ff7f0e"}]},{"title":"offline default vs online estimated steering actuator lag","range":{"left":0.0,"right":1138.749979,"top":0.419648,"bottom":0.318362},"curves":[{"name":"/liveDelay/lateralDelay","color":"#1f77b4"},{"name":"/liveDelay/lateralDelayEstimate","color":"#d62728"},{"name":"opendbc default steering lag","color":"#1ac938","custom_python":{"linked_source":"/carParams/steerActuatorDelay","additional_sources":[],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value):\n return value + 0.2\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"online estimated steering actuator lag, standard deviation","range":{"left":0.0,"right":1138.749979,"top":0.06732,"bottom":-0.001642},"curves":[{"name":"/liveDelay/lateralDelayEstimateStd","color":"#f14cc1"}]}]}},{"name":"Controls Performance","root":{"split":"vertical","sizes":[0.265655,0.251898,0.245731,0.236717],"children":[{"title":"rate-of-change limits on steering actuator (blue = original, green = rate-limited before CAN output)","range":{"left":0.000194,"right":1138.891921,"top":1.05,"bottom":-1.05},"curves":[{"name":"/carControl/actuators/torque","color":"#0c00f2"},{"name":"/carOutput/actuatorsOutput/torque","color":"#2cd63a"}]},{"title":"controller feed-forward vs actuator output (closer means controller prediction is more accurate)","range":{"left":0.000194,"right":1138.891921,"top":1.978032,"bottom":-1.570956},"curves":[{"name":"/carOutput/actuatorsOutput/torque","color":"#9467bd","transform":"scale","scale":-1.0,"offset":0.0},{"name":"/controlsState/lateralControlState/torqueState/f","color":"#1f77b4"},{"name":"/carState/steeringPressed","color":"#ff000f"}]},{"title":"proportional, integral, and feed-forward terms (actuator output = sum of PIF terms)","range":{"left":0.000194,"right":1138.891921,"top":2.099784,"bottom":-4.027542},"curves":[{"name":"/controlsState/lateralControlState/torqueState/f","color":"#0ab027"},{"name":"/controlsState/lateralControlState/torqueState/p","color":"#d62728"},{"name":"/controlsState/lateralControlState/torqueState/i","color":"#ffaf00"},{"name":"Zero","color":"#756a6a","custom_python":{"linked_source":"/carState/canValid","additional_sources":[],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value):\n return (0)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"road roll angle, from openpilot localizer","range":{"left":0.000194,"right":1138.891921,"top":0.109446,"bottom":-0.045525},"curves":[{"name":"/liveParameters/roll","color":"#f14cc1"}]}]}}]} diff --git a/tools/jotpluggler/layouts/tuning.json b/tools/jotpluggler/layouts/tuning.json new file mode 100644 index 00000000000000..0a8e81743eb596 --- /dev/null +++ b/tools/jotpluggler/layouts/tuning.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"Lateral","root":{"split":"vertical","sizes":[0.200458,0.199313,0.200458,0.199313,0.200458],"children":[{"title":"Velocity [m/s]","range":{"left":1.253354,"right":631.055584,"top":29.954036,"bottom":-0.841715},"curves":[{"name":"/carState/vEgo","color":"#0072b2"}]},{"title":"Curvature [1/m] True [blue] Vehicle Model [purple] Plan [green]","range":{"left":0.0,"right":631.055209,"top":0.006648,"bottom":-0.00315},"curves":[{"name":"engaged curvature plan","color":"#009e73","custom_python":{"linked_source":"/modelV2/action/desiredCurvature","additional_sources":["/carState/steeringPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n global engage_delay, last_bad_time\n curvature = value\n pressed = v1\n enabled = v2\n if (pressed == 1 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"engaged curvature vehicle model","color":"#785ef0","custom_python":{"linked_source":"/controlsState/curvature","additional_sources":["/carState/steeringPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n global engage_delay, last_bad_time\n curvature = value\n pressed = v1\n enabled = v2\n if (pressed == 1 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"engaged curvature yaw","color":"#0072b2","custom_python":{"linked_source":"/carControl/angularVelocity/2","additional_sources":["/carState/steeringPressed","/carControl/enabled","/carState/vEgo"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global engage_delay, last_bad_time\n curvature = value / v3\n pressed = v1\n enabled = v2\n if (pressed == 1 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return curvature\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"Roll [rad]","range":{"left":0.0,"right":631.038276,"top":0.166067,"bottom":-1.598381},"curves":[{"name":"/carControl/orientationNED/0","color":"#ffb000"}]},{"title":"Engaged [green] Steering Pressed [blue]","range":{"left":1.252984,"right":631.055584,"top":1.025,"bottom":-0.025},"curves":[{"name":"/selfdriveState/enabled","color":"#009e73"},{"name":"/carState/steeringPressed","color":"#0072b2"}]},{"title":"Steering Limited: Rate [orange] Saturated [magenta]","range":{"left":1.253354,"right":631.055584,"top":1.025,"bottom":-0.025},"curves":[{"name":"steering rate limited","color":"#ffb000","custom_python":{"linked_source":"/carControl/actuators/torque","additional_sources":["/carOutput/actuatorsOutput/torque","/carControl/actuators/steeringAngleDeg","/carOutput/actuatorsOutput/steeringAngleDeg"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n return (np.abs(value - v1) > 0.001 or np.abs(v2 - v3) > 0.05) and 1 or 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"/controlsState/lateralControlState/pidState/saturated","color":"#dc267f"}]}]}},{"name":"Longitudinal","root":{"split":"vertical","sizes":[0.1875,0.1875,0.1875,0.1875,0.25],"children":[{"title":"Velocity [m/s] True [blue] Plan [green] Cruise [magenta]","range":{"left":0.0,"right":631.055584,"top":42.713492,"bottom":-1.041792},"curves":[{"name":"/carState/cruiseState/speed","color":"#dc267f"},{"name":"/longitudinalPlan/speeds/0","color":"#009e73"},{"name":"/carState/vEgo","color":"#0072b2"}]},{"title":"Acceleration [m/s^2] True [blue] Actuator [purple] Plan [green]","range":{"left":1.253354,"right":631.055759,"top":0.808303,"bottom":-1.213305},"curves":[{"name":"engaged_accel_plan","color":"#009e73","custom_python":{"linked_source":"/longitudinalPlan/accels/0","additional_sources":["/carState/brakePressed","/carState/gasPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global engage_delay, last_bad_time\n accel = value\n brake = v1\n gas = v2\n enabled = v3\n if (brake != 0 or gas != 0 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"engaged_accel_actuator","color":"#785ef0","custom_python":{"linked_source":"/carControl/actuators/accel","additional_sources":["/carState/brakePressed","/carState/gasPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global engage_delay, last_bad_time\n accel = value\n brake = v1\n gas = v2\n enabled = v3\n if (brake != 0 or gas != 0 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"engaged_accel_actual","color":"#0072b2","custom_python":{"linked_source":"/carState/aEgo","additional_sources":["/carState/brakePressed","/carState/gasPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global engage_delay, last_bad_time\n accel = value\n brake = v1\n gas = v2\n enabled = v3\n if (brake != 0 or gas != 0 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"Pitch [rad]","range":{"left":0.0,"right":631.038276,"top":0.158854,"bottom":-0.594843},"curves":[{"name":"/carControl/orientationNED/1","color":"#ffb000"}]},{"title":"Engaged [green] Gas [orange] Brake [magenta]","range":{"left":1.253354,"right":631.055759,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carControl/enabled","color":"#009e73"},{"name":"/carState/gasPressed","color":"#ffb000"},{"name":"/carState/brakePressed","color":"#dc267f"}]},{"title":"State [blue: off,pid,stop,start] Source [green: cruise,lead0,lead1,lead2,e2e]","range":{"left":1.25362,"right":631.055759,"top":5.125,"bottom":-0.125},"curves":[{"name":"/carControl/actuators/longControlState","color":"#0072b2"},{"name":"/longitudinalPlan/longitudinalPlanSource","color":"#009e73"}]}]}},{"name":"Lateral Debug","root":{"split":"vertical","sizes":[0.25,0.25,0.25,0.25],"children":[{"title":"Controller F [magenta] P [purple] I [blue]","range":{"left":0.0,"right":1.0,"top":1.0,"bottom":0.0},"curves":[{"name":"/controlsState/lateralControlState/pidState/f","color":"#f14cc1"},{"name":"/controlsState/lateralControlState/pidState/p","color":"#9467bd"},{"name":"/controlsState/lateralControlState/pidState/i","color":"#17becf"}]},{"title":"Driver Torque [blue] EPS Torque [green]","range":{"left":1.253354,"right":631.055584,"top":2690.99903,"bottom":-3450.198981},"curves":[{"name":"/carState/steeringTorqueEps","color":"#009e73"},{"name":"/carState/steeringTorque","color":"#0072b2"}]},{"title":"Engaged [green] Steering Pressed [blue]","range":{"left":1.253354,"right":631.055759,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carControl/enabled","color":"#009e73"},{"name":"/carState/steeringPressed","color":"#0072b2"}]},{"title":"Steering Limited: Rate [orange] Saturated [magenta]","range":{"left":1.253354,"right":631.055584,"top":1.025,"bottom":-0.025},"curves":[{"name":"steering rate limited","color":"#ffb000","custom_python":{"linked_source":"/carControl/actuators/torque","additional_sources":["/carOutput/actuatorsOutput/torque","/carControl/actuators/steeringAngleDeg","/carOutput/actuatorsOutput/steeringAngleDeg"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n return (np.abs(value - v1) > 0.001 or np.abs(v2 - v3) > 0.05) and 1 or 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"/controlsState/lateralControlState/pidState/saturated","color":"#dc267f"}]}]}}]} diff --git a/tools/jotpluggler/layouts/ublox-debug.json b/tools/jotpluggler/layouts/ublox-debug.json new file mode 100644 index 00000000000000..4509a192df130c --- /dev/null +++ b/tools/jotpluggler/layouts/ublox-debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.333333,0.333333,0.333333],"children":[{"title":"...","range":{"left":0.0,"right":134.825489,"top":4402341.574525,"bottom":-107369.555525},"curves":[{"name":"/gpsLocationExternal/horizontalAccuracy","color":"#1f77b4"}]},{"title":"...","range":{"left":0.0,"right":134.825489,"top":1.025,"bottom":-0.025},"curves":[{"name":"/gpsLocationExternal/flags","color":"#d62728"}]},{"title":"...","range":{"left":0.0,"right":134.825489,"top":6.15,"bottom":-0.15},"curves":[{"name":"/ubloxGnss/measurementReport/numMeas","color":"#1ac938"}]}]}}]} diff --git a/tools/jotpluggler/logs.cc b/tools/jotpluggler/logs.cc new file mode 100644 index 00000000000000..4da1cbf501a02c --- /dev/null +++ b/tools/jotpluggler/logs.cc @@ -0,0 +1,419 @@ +#include "tools/jotpluggler/app.h" + +#include +#include + +namespace { + +struct LevelOption { + const char *label; + int value; +}; + +constexpr std::array LEVEL_OPTIONS = {{ + {"DEBUG", 10}, + {"INFO", 20}, + {"WARNING", 30}, + {"ERROR", 40}, + {"CRITICAL", 50}, +}}; +constexpr uint32_t ALL_LEVEL_MASK = (1u << LEVEL_OPTIONS.size()) - 1u; + +bool log_matches_search(const LogEntry &entry, std::string_view query) { + if (query.empty()) return true; + const std::string needle = lowercase_copy(query); + const auto contains = [&](std::string_view haystack) { + return lowercase_copy(haystack).find(needle) != std::string::npos; + }; + return contains(entry.message) || contains(entry.source) || contains(entry.func); +} + +std::vector collect_log_sources(const std::vector &logs) { + std::vector sources; + for (const LogEntry &entry : logs) { + if (entry.source.empty()) continue; + if (std::find(sources.begin(), sources.end(), entry.source) == sources.end()) { + sources.push_back(entry.source); + } + } + std::sort(sources.begin(), sources.end()); + return sources; +} + +std::vector filter_log_indices(const RouteData &route_data, const LogsUiState &logs_state) { + std::vector indices; + indices.reserve(route_data.logs.size()); + for (size_t i = 0; i < route_data.logs.size(); ++i) { + const LogEntry &entry = route_data.logs[i]; + int level_index = 0; + if (entry.level >= 50) { + level_index = 4; + } else if (entry.level >= 40) { + level_index = 3; + } else if (entry.level >= 30) { + level_index = 2; + } else if (entry.level >= 20) { + level_index = 1; + } + if ((logs_state.enabled_levels_mask & (1u << level_index)) == 0) { + continue; + } + if (!logs_state.all_sources) { + const auto it = std::find(logs_state.selected_sources.begin(), + logs_state.selected_sources.end(), + entry.source); + if (it == logs_state.selected_sources.end()) continue; + } + if (!log_matches_search(entry, logs_state.search)) continue; + indices.push_back(static_cast(i)); + } + return indices; +} + +int find_active_log_position(const RouteData &route_data, + const std::vector &filtered_indices, + double tracker_time) { + if (filtered_indices.empty()) return -1; + auto it = std::lower_bound(filtered_indices.begin(), filtered_indices.end(), tracker_time, + [&](int log_index, double tm) { + return route_data.logs[static_cast(log_index)].mono_time < tm; + }); + if (it == filtered_indices.begin()) return static_cast(std::distance(filtered_indices.begin(), it)); + if (it == filtered_indices.end()) return static_cast(filtered_indices.size()) - 1; + if (route_data.logs[static_cast(*it)].mono_time > tracker_time) { + --it; + } + return static_cast(std::distance(filtered_indices.begin(), it)); +} + +std::string format_route_time(double seconds) { + if (seconds < 0.0) { + seconds = 0.0; + } + const int minutes = static_cast(seconds / 60.0); + const double remaining = seconds - static_cast(minutes) * 60.0; + return util::string_format("%d:%06.3f", minutes, remaining); +} + +std::string format_boot_time(double seconds) { + return util::string_format("%.3f", seconds); +} + +std::string format_wall_time(double seconds) { + if (seconds <= 0.0) return "--"; + const time_t wall_seconds = static_cast(seconds); + std::tm wall_tm = {}; + localtime_r(&wall_seconds, &wall_tm); + const int millis = static_cast(std::llround((seconds - std::floor(seconds)) * 1000.0)); + return util::string_format("%02d:%02d:%02d.%03d", + wall_tm.tm_hour, wall_tm.tm_min, wall_tm.tm_sec, millis); +} + +std::string format_log_time(const LogEntry &entry, LogTimeMode mode) { + switch (mode) { + case LogTimeMode::Route: + return format_route_time(entry.mono_time); + case LogTimeMode::Boot: + return format_boot_time(entry.boot_time); + case LogTimeMode::WallClock: + return format_wall_time(entry.wall_time); + } + return format_route_time(entry.mono_time); +} + +const char *time_mode_label(LogTimeMode mode) { + switch (mode) { + case LogTimeMode::Route: return "Route"; + case LogTimeMode::Boot: return "Boot"; + case LogTimeMode::WallClock: return "Wall clock"; + } + return "Route"; +} + +std::string level_filter_label(uint32_t mask) { + if (mask == ALL_LEVEL_MASK) return "All levels"; + if (mask == 0b11110) return "INFO+"; + if (mask == 0b11100) return "WARNING+"; + if (mask == 0b11000) return "ERROR+"; + if (mask == 0b10000) return "CRITICAL"; + + int enabled_count = 0; + const char *last_label = "None"; + for (size_t i = 0; i < LEVEL_OPTIONS.size(); ++i) { + if ((mask & (1u << i)) == 0) { + continue; + } + ++enabled_count; + last_label = LEVEL_OPTIONS[i].label; + } + if (enabled_count == 0) return "None"; + if (enabled_count == 1) return last_label; + return "Custom"; +} + +std::string source_filter_label(const LogsUiState &logs_state, const std::vector &sources) { + if (logs_state.all_sources || logs_state.selected_sources.size() == sources.size()) { + return "All sources"; + } + if (logs_state.selected_sources.empty()) return "No sources"; + if (logs_state.selected_sources.size() == 1) return logs_state.selected_sources.front(); + return std::to_string(logs_state.selected_sources.size()) + " sources"; +} + +const char *level_label(const LogEntry &entry) { + if (entry.origin == LogOrigin::Alert) return "ALRT"; + if (entry.level >= 50) return "CRIT"; + if (entry.level >= 40) return "ERR"; + if (entry.level >= 30) return "WARN"; + if (entry.level >= 20) return "INFO"; + return "DBG"; +} + +ImVec4 level_text_color(const LogEntry &entry, bool active) { + if (active) return color_rgb(46, 54, 63); + if (entry.origin == LogOrigin::Alert) return color_rgb(50, 100, 200); + if (entry.level >= 50) return color_rgb(176, 26, 18); + if (entry.level >= 40) return color_rgb(200, 50, 40); + if (entry.level >= 30) return color_rgb(200, 130, 0); + if (entry.level >= 20) return color_rgb(80, 86, 94); + return color_rgb(126, 133, 141); +} + +ImU32 row_bg_color(const LogEntry &entry, bool active) { + if (active) return IM_COL32(80, 140, 210, 38); + return 0; +} + +void set_tracker_to_log(UiState *state, const LogEntry &entry) { + state->tracker_time = entry.mono_time; + state->has_tracker_time = true; + state->logs.last_auto_scroll_time = entry.mono_time; +} + +void draw_log_expansion_row(const LogEntry &entry) { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::TextUnformatted(""); + ImGui::TableSetColumnIndex(1); + ImGui::TextUnformatted(""); + ImGui::TableSetColumnIndex(2); + ImGui::TextUnformatted(entry.func.empty() ? "" : entry.func.c_str()); + ImGui::TableSetColumnIndex(3); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(96, 104, 113)); + ImGui::TextWrapped("%s", entry.message.c_str()); + if (!entry.func.empty()) { + ImGui::TextWrapped("func: %s", entry.func.c_str()); + } + if (!entry.context.empty()) { + ImGui::TextWrapped("ctx: %s", entry.context.c_str()); + } + ImGui::PopStyleColor(); +} + +void draw_log_row(const LogEntry &entry, + int log_index, + bool active, + UiState *state) { + ImGui::PushID(log_index); + const ImU32 bg = row_bg_color(entry, active); + ImGui::TableNextRow(); + if (bg != 0) { + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, bg); + } + + const std::string time_text = std::string(active ? "\xE2\x96\xB6 " : " ") + format_log_time(entry, state->logs.time_mode); + const auto clickable_text = [&](const char *id, const std::string &text, ImVec4 color = color_rgb(74, 80, 88)) { + ImGui::PushID(id); + ImGui::PushStyleColor(ImGuiCol_Text, color); + ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_HeaderActive, ImVec4(0, 0, 0, 0)); + const bool clicked = ImGui::Selectable(text.c_str(), false, ImGuiSelectableFlags_AllowDoubleClick); + ImGui::PopStyleColor(4); + ImGui::PopID(); + return clicked; + }; + + bool clicked = false; + ImGui::TableSetColumnIndex(0); + app_push_mono_font(); + clicked = clickable_text("time", time_text); + app_pop_mono_font(); + + ImGui::TableSetColumnIndex(1); + clicked = clickable_text("level", level_label(entry), level_text_color(entry, active)) || clicked; + + ImGui::TableSetColumnIndex(2); + clicked = clickable_text("source", entry.source) || clicked; + + ImGui::TableSetColumnIndex(3); + clicked = clickable_text("message", entry.message) || clicked; + + if (clicked) { + set_tracker_to_log(state, entry); + state->logs.expanded_index = state->logs.expanded_index == log_index ? -1 : log_index; + } + ImGui::PopID(); +} + +} // namespace + +void draw_logs_tab(AppSession *session, UiState *state) { + LogsUiState &logs_state = state->logs; + const RouteData &route_data = session->route_data; + const RouteLoadSnapshot load = session->route_loader ? session->route_loader->snapshot() : RouteLoadSnapshot{}; + const bool loading_logs = load.active && route_data.logs.empty(); + const std::vector sources = collect_log_sources(route_data.logs); + + if (!logs_state.all_sources) { + logs_state.selected_sources.erase( + std::remove_if(logs_state.selected_sources.begin(), + logs_state.selected_sources.end(), + [&](const std::string &source) { + return std::find(sources.begin(), sources.end(), source) == sources.end(); + }), + logs_state.selected_sources.end()); + } + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6.0f, 3.0f)); + ImGui::SetNextItemWidth(110.0f); + const std::string levels_label = level_filter_label(logs_state.enabled_levels_mask); + if (ImGui::BeginCombo("##logs_level", levels_label.c_str())) { + bool all_levels = logs_state.enabled_levels_mask == ALL_LEVEL_MASK; + if (ImGui::Checkbox("All levels", &all_levels)) { + logs_state.enabled_levels_mask = all_levels ? ALL_LEVEL_MASK : 0u; + } + ImGui::Separator(); + for (size_t i = 0; i < LEVEL_OPTIONS.size(); ++i) { + bool enabled = (logs_state.enabled_levels_mask & (1u << i)) != 0; + if (ImGui::Checkbox(LEVEL_OPTIONS[i].label, &enabled)) { + if (enabled) { + logs_state.enabled_levels_mask |= (1u << i); + } else { + logs_state.enabled_levels_mask &= ~(1u << i); + } + } + } + ImGui::EndCombo(); + } + ImGui::SameLine(); + + ImGui::SetNextItemWidth(150.0f); + input_text_with_hint_string("##logs_search", "Search...", &logs_state.search); + ImGui::SameLine(); + + const std::string sources_label = source_filter_label(logs_state, sources); + ImGui::SetNextItemWidth(180.0f); + if (ImGui::BeginCombo("##logs_source", sources_label.c_str())) { + bool all_sources = logs_state.all_sources; + if (ImGui::Checkbox("All sources", &all_sources)) { + logs_state.all_sources = all_sources; + if (logs_state.all_sources) { + logs_state.selected_sources.clear(); + } else { + logs_state.selected_sources = sources; + } + } + ImGui::Separator(); + for (const std::string &source : sources) { + bool enabled = logs_state.all_sources + || std::find(logs_state.selected_sources.begin(), logs_state.selected_sources.end(), source) != logs_state.selected_sources.end(); + if (ImGui::Checkbox(source.c_str(), &enabled)) { + if (logs_state.all_sources) { + logs_state.all_sources = false; + logs_state.selected_sources = sources; + } + auto it = std::find(logs_state.selected_sources.begin(), logs_state.selected_sources.end(), source); + if (enabled) { + if (it == logs_state.selected_sources.end()) { + logs_state.selected_sources.push_back(source); + } + } else if (it != logs_state.selected_sources.end()) { + logs_state.selected_sources.erase(it); + } + if (logs_state.selected_sources.size() == sources.size()) { + logs_state.all_sources = true; + logs_state.selected_sources.clear(); + } + } + } + ImGui::EndCombo(); + } + ImGui::SameLine(); + + ImGui::SetNextItemWidth(110.0f); + if (ImGui::BeginCombo("##logs_time_mode", time_mode_label(logs_state.time_mode))) { + for (LogTimeMode mode : {LogTimeMode::Route, LogTimeMode::Boot, LogTimeMode::WallClock}) { + const bool selected = logs_state.time_mode == mode; + if (ImGui::Selectable(time_mode_label(mode), selected)) { + logs_state.time_mode = mode; + } + } + ImGui::EndCombo(); + } + + const std::vector filtered_indices = filter_log_indices(route_data, logs_state); + const bool have_tracker = state->has_tracker_time && !filtered_indices.empty(); + const int active_pos = have_tracker ? find_active_log_position(route_data, filtered_indices, state->tracker_time) : -1; + + ImGui::SameLine(); + ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(), ImGui::GetWindowContentRegionMax().x - 110.0f)); + ImGui::Text("%zu / %zu", filtered_indices.size(), route_data.logs.size()); + ImGui::PopStyleVar(); + + if (route_data.logs.empty()) { + ImGui::Spacing(); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(116, 124, 133)); + ImGui::TextWrapped("%s", loading_logs ? "Loading logs..." : "No text logs available for this route."); + ImGui::PopStyleColor(); + return; + } + + if (ImGui::BeginChild("##logs_table_child", ImVec2(0.0f, 0.0f), false)) { + if (have_tracker && std::abs(logs_state.last_auto_scroll_time - state->tracker_time) > 1.0e-6) { + const float row_height = ImGui::GetTextLineHeightWithSpacing() + 6.0f; + const float visible_h = std::max(1.0f, ImGui::GetWindowHeight()); + const float target = std::max(0.0f, static_cast(active_pos) * row_height - visible_h * 0.45f); + ImGui::SetScrollY(target); + logs_state.last_auto_scroll_time = state->tracker_time; + } + + if (ImGui::BeginTable("##logs_table", + 4, + ImGuiTableFlags_BordersInnerV | + ImGuiTableFlags_RowBg | + ImGuiTableFlags_Resizable | + ImGuiTableFlags_SizingStretchProp)) { + ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthFixed, 120.0f); + ImGui::TableSetupColumn("Level", ImGuiTableColumnFlags_WidthFixed, 72.0f); + ImGui::TableSetupColumn("Source", ImGuiTableColumnFlags_WidthFixed, 180.0f); + ImGui::TableSetupColumn("Message", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableHeadersRow(); + + const bool use_clipper = logs_state.expanded_index < 0; + if (use_clipper) { + ImGuiListClipper clipper; + clipper.Begin(static_cast(filtered_indices.size())); + while (clipper.Step()) { + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) { + const int log_index = filtered_indices[static_cast(i)]; + const LogEntry &entry = route_data.logs[static_cast(log_index)]; + draw_log_row(entry, log_index, i == active_pos, state); + } + } + } else { + for (int i = 0; i < static_cast(filtered_indices.size()); ++i) { + const int log_index = filtered_indices[static_cast(i)]; + const LogEntry &entry = route_data.logs[static_cast(log_index)]; + draw_log_row(entry, log_index, i == active_pos, state); + if (logs_state.expanded_index == log_index) { + draw_log_expansion_row(entry); + } + } + } + + ImGui::EndTable(); + } + } + ImGui::EndChild(); +} diff --git a/tools/jotpluggler/main.cc b/tools/jotpluggler/main.cc new file mode 100644 index 00000000000000..22bc29664c2616 --- /dev/null +++ b/tools/jotpluggler/main.cc @@ -0,0 +1,126 @@ +#include +#include + +#include "tools/jotpluggler/app.h" + +namespace { + +constexpr const char *DEMO_ROUTE = "5beb9b58bd12b691/0000010a--a51155e496"; + +void print_usage(const char *argv0) { + std::cerr + << "Usage: " << argv0 << " [--layout ] [options] [route]\n" + << "\n" + << "Options:\n" + << " --demo\n" + << " --data-dir \n" + << " --stream\n" + << " --address \n" + << " --buffer-seconds \n" + << " --width \n" + << " --height \n" + << " --output \n" + << " --show\n" + << " --sync-load\n" + << "\n" + << "Examples:\n" + << " " << argv0 << "\n" + << " " << argv0 << " --demo\n" + << " " << argv0 << " --layout longitudinal --demo\n" + << " " << argv0 << " --layout longitudinal --demo --output /tmp/longitudinal.png\n" + << " " << argv0 << " --stream --show\n" + << " " << argv0 << " --stream --address 192.168.60.52 --buffer-seconds 45 --show\n"; +} + +bool parse_int(const char *value, int *out) { + char *end = nullptr; + const long parsed = std::strtol(value, &end, 10); + if (end == nullptr || *end != '\0') return false; + *out = static_cast(parsed); + return true; +} + +bool parse_double(const char *value, double *out) { + char *end = nullptr; + const double parsed = std::strtod(value, &end); + if (end == nullptr || *end != '\0') return false; + *out = parsed; + return true; +} + +} // namespace + +int main(int argc, char *argv[]) { + Options options; + for (int i = 1; i < argc; ++i) { + const std::string arg = argv[i]; + const auto require_value = [&](const char *flag) -> const char * { + if (i + 1 >= argc) { + std::cerr << "Missing value for " << flag << "\n"; + print_usage(argv[0]); + std::exit(2); + } + return argv[++i]; + }; + + if (arg == "--layout") { + options.layout = require_value("--layout"); + } else if (arg == "--demo") { + options.route_name = DEMO_ROUTE; + } else if (arg == "--data-dir") { + options.data_dir = require_value("--data-dir"); + } else if (arg == "--stream") { + options.stream = true; + } else if (arg == "--address") { + options.stream_address = require_value("--address"); + } else if (arg == "--buffer-seconds") { + if (!parse_double(require_value("--buffer-seconds"), &options.stream_buffer_seconds)) { + std::cerr << "Invalid buffer seconds\n"; + return 2; + } + } else if (arg == "--output") { + options.output_path = require_value("--output"); + } else if (arg == "--width") { + if (!parse_int(require_value("--width"), &options.width)) { + std::cerr << "Invalid width\n"; + return 2; + } + } else if (arg == "--height") { + if (!parse_int(require_value("--height"), &options.height)) { + std::cerr << "Invalid height\n"; + return 2; + } + } else if (arg == "--show") { + options.show = true; + } else if (arg == "--sync-load") { + options.sync_load = true; + } else if (arg == "--help" || arg == "-h") { + print_usage(argv[0]); + return 0; + } else if (!arg.empty() && arg[0] != '-' && options.route_name.empty()) { + options.route_name = arg; + } else { + std::cerr << "Unknown argument: " << arg << "\n"; + print_usage(argv[0]); + return 2; + } + } + + if (options.output_path.empty() && !options.show) { + options.show = true; + } + if (options.width <= 0 || options.height <= 0) { + std::cerr << "Width and height must be positive\n"; + return 2; + } + if (options.stream && !options.route_name.empty()) { + std::cerr << "Route/file mode and --stream are mutually exclusive\n"; + return 2; + } + if (options.stream_buffer_seconds <= 0.0) { + std::cerr << "Buffer seconds must be positive\n"; + return 2; + } + + return run(options); +} diff --git a/tools/jotpluggler/map.cc b/tools/jotpluggler/map.cc new file mode 100644 index 00000000000000..fb4e03c9122a34 --- /dev/null +++ b/tools/jotpluggler/map.cc @@ -0,0 +1,1328 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" +#include "tools/jotpluggler/map.h" + +#include + +extern "C" { +#include +} + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/util.h" +#include "json11/json11.hpp" + +namespace fs = std::filesystem; + +namespace { + +constexpr int MAP_MIN_ZOOM = 1; +constexpr int MAP_MAX_ZOOM = 18; +constexpr int MAP_SINGLE_POINT_MIN_ZOOM = 14; +constexpr float MAP_WHEEL_ZOOM_STEP = 0.25f; +constexpr double MAP_TRACE_PAD_FRAC = 0.45; +constexpr double MAP_TRACE_MIN_LAT_PAD = 0.01; +constexpr double MAP_BOUNDS_GRID = 0.005; +constexpr double MAP_CORRIDOR_LAT_PAD = 0.010; +constexpr double MAP_CORRIDOR_MIN_STEP_S = 1.5; +constexpr size_t MAP_CORRIDOR_MAX_BOXES = 36; +constexpr float MAP_INITIAL_FIT_FILL = 0.88f; +constexpr float MAP_MIN_ZOOM_FILL = 0.98f; +constexpr float MAP_EDGE_FADE_FRAC = 0.28f; +constexpr const char *MAP_QUERY_ENDPOINTS[] = { + "https://overpass-api.de/api/interpreter", + "https://overpass.private.coffee/api/interpreter", +}; +struct GeoPoint { + double lat = 0.0; + double lon = 0.0; +}; + +struct ProjectedPoint { + float x = 0.0f; + float y = 0.0f; +}; + +struct ProjectedBounds { + float min_x = 0.0f; + float min_y = 0.0f; + float max_x = 0.0f; + float max_y = 0.0f; + + bool valid() const { + return max_x >= min_x && max_y >= min_y; + } +}; + +enum class RoadClass : uint8_t { + Motorway, + Primary, + Secondary, + Local, +}; + +struct RoadFeature { + RoadClass road_class = RoadClass::Local; + ProjectedBounds bounds; + std::vector points; +}; + +struct WaterLineFeature { + ProjectedBounds bounds; + std::vector points; +}; + +struct WaterPolygonFeature { + ProjectedBounds bounds; + std::vector ring; +}; + +} // namespace + +struct RouteBasemap { + std::string key; + GeoBounds bounds; + ProjectedBounds projected_bounds; + std::vector roads; + std::vector water_lines; + std::vector water_polygons; +}; + +struct MapRequestSpec { + std::string key; + GeoBounds bounds; + std::string query; +}; + +namespace { + +double lon_to_world_x(double lon, double zoom) { + return (lon + 180.0) / 360.0 * 256.0 * std::exp2(zoom); +} + +double lat_to_world_y(double lat, double zoom) { + const double lat_rad = lat * M_PI / 180.0; + return (1.0 - std::log(std::tan(lat_rad) + 1.0 / std::cos(lat_rad)) / M_PI) / 2.0 * 256.0 * std::exp2(zoom); +} + +double world_x_to_lon(double x, double zoom) { + return x / std::exp2(zoom) / 256.0 * 360.0 - 180.0; +} + +double world_y_to_lat(double y, double zoom) { + const double n = M_PI - (2.0 * M_PI * (y / std::exp2(zoom))) / 256.0; + return 180.0 / M_PI * std::atan(std::sinh(n)); +} + +double map_trace_center_lat(const GpsTrace &trace) { + return (trace.min_lat + trace.max_lat) * 0.5; +} + +double map_trace_center_lon(const GpsTrace &trace) { + return (trace.min_lon + trace.max_lon) * 0.5; +} + +double clamp_lat(double lat) { + return std::clamp(lat, -85.0, 85.0); +} + +double clamp_lon(double lon) { + return std::clamp(lon, -179.999, 179.999); +} + +float project_lon0(double lon) { + return static_cast((lon + 180.0) / 360.0 * 256.0); +} + +float project_lat0(double lat) { + const double lat_rad = lat * M_PI / 180.0; + return static_cast((1.0 - std::log(std::tan(lat_rad) + 1.0 / std::cos(lat_rad)) / M_PI) / 2.0 * 256.0); +} + +double cos_lat_scale(double lat) { + return std::max(0.2, std::cos(lat * M_PI / 180.0)); +} + +double quantize_down(double value, double step) { + return std::floor(value / step) * step; +} + +double quantize_up(double value, double step) { + return std::ceil(value / step) * step; +} + +ProjectedBounds compute_projected_bounds(const std::vector &points) { + ProjectedBounds bounds; + if (points.empty()) { + return bounds; + } + bounds.min_x = bounds.max_x = points.front().x; + bounds.min_y = bounds.max_y = points.front().y; + for (const ProjectedPoint &point : points) { + bounds.min_x = std::min(bounds.min_x, point.x); + bounds.max_x = std::max(bounds.max_x, point.x); + bounds.min_y = std::min(bounds.min_y, point.y); + bounds.max_y = std::max(bounds.max_y, point.y); + } + return bounds; +} + +ProjectedBounds project_bounds0(const GeoBounds &bounds) { + if (!bounds.valid()) { + return {}; + } + return ProjectedBounds{ + .min_x = project_lon0(bounds.west), + .min_y = project_lat0(bounds.north), + .max_x = project_lon0(bounds.east), + .max_y = project_lat0(bounds.south), + }; +} + +bool feature_intersects_view(const ProjectedBounds &feature, const ProjectedBounds &view, float zoom_scale) { + const float min_x = feature.min_x * zoom_scale; + const float max_x = feature.max_x * zoom_scale; + const float min_y = feature.min_y * zoom_scale; + const float max_y = feature.max_y * zoom_scale; + return !(max_x < view.min_x || min_x > view.max_x + || max_y < view.min_y || min_y > view.max_y); +} + +GeoBounds requested_bounds_for_trace(const GpsTrace &trace) { + if (trace.points.empty()) { + return {}; + } + const double center_lat = map_trace_center_lat(trace); + const double lat_span = std::max(trace.max_lat - trace.min_lat, 0.002); + const double lon_span = std::max(trace.max_lon - trace.min_lon, 0.002 / cos_lat_scale(center_lat)); + const double lat_pad = std::max(lat_span * MAP_TRACE_PAD_FRAC, MAP_TRACE_MIN_LAT_PAD); + const double lon_pad = std::max(lon_span * MAP_TRACE_PAD_FRAC, MAP_TRACE_MIN_LAT_PAD / cos_lat_scale(center_lat)); + + GeoBounds bounds; + bounds.south = clamp_lat(quantize_down(trace.min_lat - lat_pad, MAP_BOUNDS_GRID)); + bounds.north = clamp_lat(quantize_up(trace.max_lat + lat_pad, MAP_BOUNDS_GRID)); + bounds.west = clamp_lon(quantize_down(trace.min_lon - lon_pad, MAP_BOUNDS_GRID)); + bounds.east = clamp_lon(quantize_up(trace.max_lon + lon_pad, MAP_BOUNDS_GRID)); + return bounds; +} + +GeoBounds merge_bounds(const GeoBounds &a, const GeoBounds &b) { + if (!a.valid()) return b; + if (!b.valid()) return a; + return GeoBounds{ + .south = std::min(a.south, b.south), + .west = std::min(a.west, b.west), + .north = std::max(a.north, b.north), + .east = std::max(a.east, b.east), + }; +} + +bool bounds_overlap_or_touch(const GeoBounds &a, const GeoBounds &b) { + return !(a.east < b.west || b.east < a.west || a.north < b.south || b.north < a.south); +} + +std::vector corridor_boxes_for_trace(const GpsTrace &trace) { + std::vector boxes; + if (trace.points.empty()) { + return boxes; + } + + const double center_lat = map_trace_center_lat(trace); + const double lon_pad = MAP_CORRIDOR_LAT_PAD / cos_lat_scale(center_lat); + const double total_time = trace.points.back().time - trace.points.front().time; + const double target_boxes = std::min(MAP_CORRIDOR_MAX_BOXES, std::max(8.0, total_time / MAP_CORRIDOR_MIN_STEP_S)); + const size_t stride = std::max(1, static_cast(std::ceil(trace.points.size() / target_boxes))); + + auto add_box = [&](double lat, double lon) { + GeoBounds box{ + .south = clamp_lat(quantize_down(lat - MAP_CORRIDOR_LAT_PAD, MAP_BOUNDS_GRID)), + .west = clamp_lon(quantize_down(lon - lon_pad, MAP_BOUNDS_GRID)), + .north = clamp_lat(quantize_up(lat + MAP_CORRIDOR_LAT_PAD, MAP_BOUNDS_GRID)), + .east = clamp_lon(quantize_up(lon + lon_pad, MAP_BOUNDS_GRID)), + }; + if (!box.valid()) { + return; + } + for (GeoBounds &existing : boxes) { + if (bounds_overlap_or_touch(existing, box)) { + existing = merge_bounds(existing, box); + return; + } + } + boxes.push_back(box); + }; + + add_box(trace.points.front().lat, trace.points.front().lon); + for (size_t i = stride; i < trace.points.size(); i += stride) { + add_box(trace.points[i].lat, trace.points[i].lon); + } + add_box(trace.points.back().lat, trace.points.back().lon); + + bool merged = true; + while (merged) { + merged = false; + for (size_t i = 0; i < boxes.size() && !merged; ++i) { + for (size_t j = i + 1; j < boxes.size(); ++j) { + if (bounds_overlap_or_touch(boxes[i], boxes[j])) { + boxes[i] = merge_bounds(boxes[i], boxes[j]); + boxes.erase(boxes.begin() + static_cast(j)); + merged = true; + break; + } + } + } + } + return boxes; +} + +ProjectedBounds view_bounds(double top_left_x, double top_left_y, float width, float height) { + return ProjectedBounds{ + .min_x = static_cast(top_left_x), + .min_y = static_cast(top_left_y), + .max_x = static_cast(top_left_x + width), + .max_y = static_cast(top_left_y + height), + }; +} + +int fit_map_zoom_for_bounds(const GeoBounds &bounds, float width, float height, float fill_fraction) { + if (!bounds.valid()) { + return MAP_MIN_ZOOM; + } + const double max_width = std::max(1.0f, width * fill_fraction); + const double max_height = std::max(1.0f, height * fill_fraction); + for (int z = MAP_MAX_ZOOM; z >= MAP_MIN_ZOOM; --z) { + const double pixel_width = std::abs(lon_to_world_x(bounds.east, z) - lon_to_world_x(bounds.west, z)); + const double pixel_height = std::abs(lat_to_world_y(bounds.south, z) - lat_to_world_y(bounds.north, z)); + if (pixel_width <= max_width && pixel_height <= max_height) { + return z; + } + } + return MAP_MIN_ZOOM; +} + +int fit_map_zoom_for_trace(const GpsTrace &trace, float width, float height) { + return fit_map_zoom_for_bounds(requested_bounds_for_trace(trace), width, height, MAP_INITIAL_FIT_FILL); +} + +int minimum_allowed_map_zoom(const GeoBounds &bounds, const GpsTrace &trace, ImVec2 size) { + if (trace.points.size() <= 1) { + return MAP_SINGLE_POINT_MIN_ZOOM; + } + const int fit_zoom = fit_map_zoom_for_bounds(bounds.valid() ? bounds : requested_bounds_for_trace(trace), + size.x, size.y, MAP_MIN_ZOOM_FILL); + return std::clamp(fit_zoom, MAP_MIN_ZOOM, MAP_MAX_ZOOM); +} + +std::optional interpolate_gps(const GpsTrace &trace, double time_value) { + if (trace.points.empty()) { + return std::nullopt; + } + if (time_value <= trace.points.front().time) { + return trace.points.front(); + } + if (time_value >= trace.points.back().time) { + return trace.points.back(); + } + auto upper = std::lower_bound(trace.points.begin(), trace.points.end(), time_value, + [](const GpsPoint &point, double target) { + return point.time < target; + }); + if (upper == trace.points.begin()) { + return trace.points.front(); + } + const GpsPoint &p1 = *upper; + const GpsPoint &p0 = *(upper - 1); + const double dt = p1.time - p0.time; + if (dt <= 1.0e-9) { + return p0; + } + const double alpha = (time_value - p0.time) / dt; + GpsPoint out; + out.time = time_value; + out.lat = p0.lat + (p1.lat - p0.lat) * alpha; + out.lon = p0.lon + (p1.lon - p0.lon) * alpha; + out.bearing = static_cast(p0.bearing + (p1.bearing - p0.bearing) * alpha); + out.type = alpha < 0.5 ? p0.type : p1.type; + return out; +} + +ImU32 map_timeline_color(TimelineEntry::Type type, float alpha = 1.0f) { + return timeline_entry_color(type, alpha, {140, 150, 165}); +} + +ImVec2 gps_to_screen(double lat, double lon, double zoom, double top_left_x, double top_left_y, const ImVec2 &rect_min) { + return ImVec2(rect_min.x + static_cast(lon_to_world_x(lon, zoom) - top_left_x), + rect_min.y + static_cast(lat_to_world_y(lat, zoom) - top_left_y)); +} + +bool point_in_rect_with_margin(const ImVec2 &point, const ImVec2 &rect_min, const ImVec2 &rect_max, + float margin_fraction) { + const float width = rect_max.x - rect_min.x; + const float height = rect_max.y - rect_min.y; + const float margin_x = width * margin_fraction; + const float margin_y = height * margin_fraction; + return point.x >= rect_min.x + margin_x && point.x <= rect_max.x - margin_x + && point.y >= rect_min.y + margin_y && point.y <= rect_max.y - margin_y; +} + +void draw_car_marker(ImDrawList *draw_list, ImVec2 center, float bearing_deg, ImU32 color, float size) { + const float rad = bearing_deg * static_cast(M_PI / 180.0); + const ImVec2 forward(std::sin(rad), -std::cos(rad)); + const ImVec2 perp(-forward.y, forward.x); + const ImVec2 tip(center.x + forward.x * size, center.y + forward.y * size); + const ImVec2 base(center.x - forward.x * size * 0.45f, center.y - forward.y * size * 0.45f); + const ImVec2 left(base.x + perp.x * size * 0.6f, base.y + perp.y * size * 0.6f); + const ImVec2 right(base.x - perp.x * size * 0.6f, base.y - perp.y * size * 0.6f); + draw_list->AddTriangleFilled(tip, left, right, color); + draw_list->AddTriangle(tip, left, right, IM_COL32(255, 255, 255, 210), 2.0f); +} + +bool is_convex_ring(const std::vector &points) { + if (points.size() < 4) { + return false; + } + float sign = 0.0f; + const size_t n = points.size(); + for (size_t i = 0; i < n; ++i) { + const ImVec2 &a = points[i]; + const ImVec2 &b = points[(i + 1) % n]; + const ImVec2 &c = points[(i + 2) % n]; + const float cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x); + if (std::abs(cross) < 1.0e-3f) { + continue; + } + if (sign == 0.0f) { + sign = cross; + } else if ((cross > 0.0f) != (sign > 0.0f)) { + return false; + } + } + return sign != 0.0f; +} + +uint64_t fnv1a64(std::string_view text) { + uint64_t value = 1469598103934665603ULL; + for (unsigned char c : text) { + value ^= static_cast(c); + value *= 1099511628211ULL; + } + return value; +} + +fs::path basemap_cache_root() { + const char *home = std::getenv("HOME"); + fs::path root = home != nullptr ? fs::path(home) / ".comma" : fs::temp_directory_path(); + root /= "jotpluggler_vector_map"; + fs::create_directories(root); + return root; +} + +std::string bounds_key(const GeoBounds &bounds) { + return util::string_format("v2_%.5f_%.5f_%.5f_%.5f", + bounds.south, bounds.west, bounds.north, bounds.east); +} + +fs::path basemap_cache_path(const std::string &key) { + const uint64_t hash = fnv1a64(key); + return basemap_cache_root() / util::string_format("%016llx.bin.zst", static_cast(hash)); +} + +uint64_t cache_directory_size_bytes() { + uint64_t total = 0; + const fs::path root = basemap_cache_root(); + if (!fs::exists(root)) { + return 0; + } + for (const fs::directory_entry &entry : fs::directory_iterator(root)) { + if (entry.is_regular_file()) { + total += static_cast(entry.file_size()); + } + } + return total; +} + +size_t cache_directory_file_count() { + size_t count = 0; + const fs::path root = basemap_cache_root(); + if (!fs::exists(root)) { + return 0; + } + for (const fs::directory_entry &entry : fs::directory_iterator(root)) { + if (entry.is_regular_file()) { + ++count; + } + } + return count; +} + +void clear_cache_directory() { + const fs::path root = basemap_cache_root(); + if (!fs::exists(root)) { + return; + } + for (const fs::directory_entry &entry : fs::directory_iterator(root)) { + if (entry.is_regular_file()) { + std::error_code ec; + fs::remove(entry.path(), ec); + } + } +} + +std::string percent_encode(std::string_view text) { + std::string out; + out.reserve(text.size() * 3); + for (unsigned char c : text) { + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c == '-' || c == '_' || c == '.' || c == '~') { + out.push_back(static_cast(c)); + } else { + out += util::string_format("%%%02X", static_cast(c)); + } + } + return out; +} + +std::string bbox_string(const GeoBounds &bounds) { + return util::string_format("%.6f,%.6f,%.6f,%.6f", + bounds.south, bounds.west, bounds.north, bounds.east); +} + +MapRequestSpec build_request_for_trace(const GpsTrace &trace) { + const std::vector boxes = corridor_boxes_for_trace(trace); + GeoBounds union_bounds; + std::string query = "[out:json][timeout:25];("; + for (const GeoBounds &box : boxes) { + union_bounds = merge_bounds(union_bounds, box); + const std::string bbox = bbox_string(box); + query += "way[\"highway\"][\"area\"!=\"yes\"](" + bbox + ");"; + query += "way[\"natural\"=\"water\"](" + bbox + ");"; + query += "way[\"waterway\"=\"riverbank\"](" + bbox + ");"; + query += "way[\"waterway\"~\"river|stream|canal\"](" + bbox + ");"; + } + query += ");out tags geom;"; + + std::string key = bounds_key(union_bounds); + key += ":"; + key += std::to_string(boxes.size()); + for (const GeoBounds &box : boxes) { + key += ":"; + key += bbox_string(box); + } + return MapRequestSpec{ + .key = std::move(key), + .bounds = union_bounds, + .query = std::move(query), + }; +} + +bool fetch_overpass_json(std::string_view query, std::string *out) { + const std::string body = std::string("data=") + percent_encode(query); + for (const char *endpoint : MAP_QUERY_ENDPOINTS) { + const std::string command = "curl -fsSL --compressed --connect-timeout 8 --max-time 30 " + "-A 'jotpluggler-vector-map/1.0' " + "-H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' " + "--data-raw " + shell_quote(body) + " " + + shell_quote(endpoint); + const std::string response = util::check_output(command); + if (!response.empty() && response.front() == '{') { + *out = response; + return true; + } + } + return false; +} + +std::string load_overpass_json(std::string_view query) { + std::string response; + if (!fetch_overpass_json(query, &response)) { + return {}; + } + return response; +} + +template +void append_pod(std::string *out, const T &value) { + const size_t start = out->size(); + out->resize(start + sizeof(T)); + std::memcpy(out->data() + start, &value, sizeof(T)); +} + +template +bool read_pod(std::string_view data, size_t *offset, T *value) { + if (*offset + sizeof(T) > data.size()) { + return false; + } + std::memcpy(value, data.data() + *offset, sizeof(T)); + *offset += sizeof(T); + return true; +} + +void append_points(std::string *out, const std::vector &points) { + const uint32_t count = static_cast(points.size()); + append_pod(out, count); + for (const ProjectedPoint &point : points) { + append_pod(out, point.x); + append_pod(out, point.y); + } +} + +bool read_points(std::string_view data, size_t *offset, std::vector *points) { + uint32_t count = 0; + if (!read_pod(data, offset, &count)) { + return false; + } + points->clear(); + points->reserve(count); + for (uint32_t i = 0; i < count; ++i) { + ProjectedPoint point; + if (!read_pod(data, offset, &point.x) || !read_pod(data, offset, &point.y)) { + return false; + } + points->push_back(point); + } + return true; +} + +std::string serialize_basemap_payload(const RouteBasemap &basemap) { + std::string raw; + raw.reserve(1024 + basemap.roads.size() * 48); + raw.append("JBM2", 4); + append_pod(&raw, basemap.bounds.south); + append_pod(&raw, basemap.bounds.west); + append_pod(&raw, basemap.bounds.north); + append_pod(&raw, basemap.bounds.east); + + const uint32_t road_count = static_cast(basemap.roads.size()); + const uint32_t water_line_count = static_cast(basemap.water_lines.size()); + const uint32_t water_polygon_count = static_cast(basemap.water_polygons.size()); + append_pod(&raw, road_count); + append_pod(&raw, water_line_count); + append_pod(&raw, water_polygon_count); + + for (const RoadFeature &road : basemap.roads) { + const uint8_t kind = static_cast(road.road_class); + append_pod(&raw, kind); + append_points(&raw, road.points); + } + for (const WaterLineFeature &water : basemap.water_lines) { + append_points(&raw, water.points); + } + for (const WaterPolygonFeature &water : basemap.water_polygons) { + append_points(&raw, water.ring); + } + return raw; +} + +std::optional deserialize_basemap_payload(std::string_view raw, const std::string &key) { + if (!util::starts_with(std::string(raw), "JBM2")) { + return std::nullopt; + } + size_t offset = 4; + RouteBasemap basemap; + basemap.key = key; + if (!read_pod(raw, &offset, &basemap.bounds.south) + || !read_pod(raw, &offset, &basemap.bounds.west) + || !read_pod(raw, &offset, &basemap.bounds.north) + || !read_pod(raw, &offset, &basemap.bounds.east)) { + return std::nullopt; + } + basemap.projected_bounds = project_bounds0(basemap.bounds); + + uint32_t road_count = 0; + uint32_t water_line_count = 0; + uint32_t water_polygon_count = 0; + if (!read_pod(raw, &offset, &road_count) + || !read_pod(raw, &offset, &water_line_count) + || !read_pod(raw, &offset, &water_polygon_count)) { + return std::nullopt; + } + + basemap.roads.reserve(road_count); + for (uint32_t i = 0; i < road_count; ++i) { + uint8_t kind = 0; + std::vector points; + if (!read_pod(raw, &offset, &kind) || !read_points(raw, &offset, &points)) { + return std::nullopt; + } + basemap.roads.push_back(RoadFeature{ + .road_class = static_cast(kind), + .bounds = compute_projected_bounds(points), + .points = std::move(points), + }); + } + + basemap.water_lines.reserve(water_line_count); + for (uint32_t i = 0; i < water_line_count; ++i) { + std::vector points; + if (!read_points(raw, &offset, &points)) { + return std::nullopt; + } + basemap.water_lines.push_back(WaterLineFeature{ + .bounds = compute_projected_bounds(points), + .points = std::move(points), + }); + } + + basemap.water_polygons.reserve(water_polygon_count); + for (uint32_t i = 0; i < water_polygon_count; ++i) { + std::vector ring; + if (!read_points(raw, &offset, &ring)) { + return std::nullopt; + } + basemap.water_polygons.push_back(WaterPolygonFeature{ + .bounds = compute_projected_bounds(ring), + .ring = std::move(ring), + }); + } + return basemap; +} + +bool save_compressed_basemap(const fs::path &path, const RouteBasemap &basemap) { + const std::string raw = serialize_basemap_payload(basemap); + const size_t bound = ZSTD_compressBound(raw.size()); + std::string compressed(bound, '\0'); + const size_t size = ZSTD_compress(compressed.data(), compressed.size(), raw.data(), raw.size(), 5); + if (ZSTD_isError(size)) { + return false; + } + compressed.resize(size); + ensure_parent_dir(path); + const std::string path_string = path.string(); + return util::write_file(path_string.c_str(), compressed.data(), compressed.size(), O_WRONLY | O_CREAT | O_TRUNC) == 0; +} + +std::optional load_compressed_basemap(const fs::path &path, const std::string &key) { + const std::string compressed = util::read_file(path.string()); + if (compressed.empty()) { + return std::nullopt; + } + const unsigned long long raw_size = ZSTD_getFrameContentSize(compressed.data(), compressed.size()); + if (raw_size == ZSTD_CONTENTSIZE_ERROR || raw_size == ZSTD_CONTENTSIZE_UNKNOWN || raw_size > (1ULL << 31)) { + return std::nullopt; + } + std::string raw(static_cast(raw_size), '\0'); + const size_t actual = ZSTD_decompress(raw.data(), raw.size(), compressed.data(), compressed.size()); + if (ZSTD_isError(actual)) { + return std::nullopt; + } + raw.resize(actual); + return deserialize_basemap_payload(raw, key); +} + +std::vector geometry_points(const json11::Json &geometry_json) { + std::vector points; + const auto items = geometry_json.array_items(); + points.reserve(items.size()); + for (const json11::Json &point : items) { + if (!point["lat"].is_number() || !point["lon"].is_number()) { + continue; + } + points.push_back(ProjectedPoint{ + .x = project_lon0(point["lon"].number_value()), + .y = project_lat0(point["lat"].number_value()), + }); + } + return points; +} + +std::optional classify_road(std::string_view highway) { + if (highway == "motorway" || highway == "motorway_link" || highway == "trunk" || highway == "trunk_link") { + return RoadClass::Motorway; + } + if (highway == "primary" || highway == "primary_link") { + return RoadClass::Primary; + } + if (highway == "secondary" || highway == "secondary_link" || highway == "tertiary" || highway == "tertiary_link") { + return RoadClass::Secondary; + } + if (highway == "residential" || highway == "unclassified" || highway == "living_street" || highway == "road") { + return RoadClass::Local; + } + return std::nullopt; +} + +std::optional parse_basemap_json(const std::string &raw, const GeoBounds &bounds, const std::string &key) { + std::string parse_error; + const json11::Json root = json11::Json::parse(raw, parse_error); + if (!parse_error.empty() || !root.is_object()) { + return std::nullopt; + } + + RouteBasemap basemap; + basemap.key = key; + basemap.bounds = bounds; + basemap.projected_bounds = project_bounds0(bounds); + + for (const json11::Json &element : root["elements"].array_items()) { + if (element["type"].string_value() != "way") { + continue; + } + const json11::Json &tags = element["tags"]; + const std::vector points = geometry_points(element["geometry"]); + if (points.size() < 2) { + continue; + } + + const std::string highway = tags["highway"].string_value(); + if (!highway.empty()) { + const std::optional road_class = classify_road(highway); + if (!road_class.has_value()) { + continue; + } + basemap.roads.push_back(RoadFeature{ + .road_class = *road_class, + .bounds = compute_projected_bounds(points), + .points = points, + }); + continue; + } + + const std::string natural = tags["natural"].string_value(); + const std::string waterway = tags["waterway"].string_value(); + const bool closed = points.size() >= 4 + && std::abs(points.front().x - points.back().x) < 1.0e-6f + && std::abs(points.front().y - points.back().y) < 1.0e-6f; + if ((natural == "water" || waterway == "riverbank") && closed) { + basemap.water_polygons.push_back(WaterPolygonFeature{ + .bounds = compute_projected_bounds(points), + .ring = points, + }); + continue; + } + if (waterway == "river" || waterway == "stream" || waterway == "canal") { + basemap.water_lines.push_back(WaterLineFeature{ + .bounds = compute_projected_bounds(points), + .points = points, + }); + } + } + + return basemap; +} + +struct RoadPaint { + ImU32 casing = 0; + ImU32 fill = 0; + float casing_width = 1.0f; + float fill_width = 1.0f; +}; + +constexpr ImU32 MAP_BG_COLOR = IM_COL32(244, 243, 238, 255); +constexpr ImU32 MAP_WATER_FILL = IM_COL32(193, 216, 235, 185); +constexpr ImU32 MAP_WATER_OUTLINE = IM_COL32(143, 173, 201, 220); +constexpr ImU32 MAP_WATER_LINE = IM_COL32(156, 186, 214, 205); +constexpr ImU32 MAP_ROUTE_HALO = IM_COL32(31, 40, 50, 92); + +RoadPaint road_paint(RoadClass road_class, float zoom) { + const float scale = std::clamp(0.88f + 0.12f * (zoom - 12.0f), 0.76f, 1.95f); + switch (road_class) { + case RoadClass::Motorway: + return { + .casing = IM_COL32(163, 157, 149, 235), + .fill = IM_COL32(245, 235, 215, 255), + .casing_width = 5.6f * scale, + .fill_width = 3.7f * scale, + }; + case RoadClass::Primary: + return { + .casing = IM_COL32(171, 171, 168, 220), + .fill = IM_COL32(249, 246, 237, 248), + .casing_width = 4.6f * scale, + .fill_width = 2.95f * scale, + }; + case RoadClass::Secondary: + return { + .casing = IM_COL32(183, 186, 189, 210), + .fill = IM_COL32(252, 251, 247, 240), + .casing_width = 3.5f * scale, + .fill_width = 2.15f * scale, + }; + case RoadClass::Local: + default: + return { + .casing = IM_COL32(200, 202, 205, 195), + .fill = IM_COL32(255, 255, 254, 230), + .casing_width = 2.5f * scale, + .fill_width = 1.5f * scale, + }; + } +} + +void clamp_map_center(TabUiState::MapPaneState *map_state, const GeoBounds &bounds, const ImVec2 &size) { + if (!bounds.valid() || size.x <= 1.0f || size.y <= 1.0f) { + return; + } + const double zoom = map_state->zoom; + const double min_x = lon_to_world_x(bounds.west, zoom); + const double max_x = lon_to_world_x(bounds.east, zoom); + const double min_y = lat_to_world_y(bounds.north, zoom); + const double max_y = lat_to_world_y(bounds.south, zoom); + const double half_w = size.x * 0.5; + const double half_h = size.y * 0.5; + double center_x = lon_to_world_x(map_state->center_lon, zoom); + double center_y = lat_to_world_y(map_state->center_lat, zoom); + if (max_x - min_x <= size.x) { + center_x = (min_x + max_x) * 0.5; + } else { + center_x = std::clamp(center_x, min_x + half_w, max_x - half_w); + } + if (max_y - min_y <= size.y) { + center_y = (min_y + max_y) * 0.5; + } else { + center_y = std::clamp(center_y, min_y + half_h, max_y - half_h); + } + map_state->center_lon = world_x_to_lon(center_x, zoom); + map_state->center_lat = world_y_to_lat(center_y, zoom); +} + +void initialize_map_pane_state(TabUiState::MapPaneState *map_state, + const GpsTrace &trace, + const GeoBounds &bounds, + ImVec2 size, + SessionDataMode mode, + std::optional cursor_point) { + if (trace.points.empty()) { + return; + } + map_state->initialized = true; + map_state->follow = mode == SessionDataMode::Stream; + const int min_zoom = minimum_allowed_map_zoom(bounds, trace, size); + if (mode == SessionDataMode::Stream && cursor_point.has_value()) { + map_state->zoom = std::max(16.0f, static_cast(min_zoom)); + map_state->center_lat = cursor_point->lat; + map_state->center_lon = cursor_point->lon; + } else { + map_state->zoom = std::max(static_cast(fit_map_zoom_for_trace(trace, size.x, size.y)), + static_cast(min_zoom)); + map_state->center_lat = map_trace_center_lat(trace); + map_state->center_lon = map_trace_center_lon(trace); + } + clamp_map_center(map_state, bounds, size); +} + +void draw_feature_polyline(ImDrawList *draw_list, + const std::vector &points, + float zoom_scale, + double top_left_x, + double top_left_y, + const ImVec2 &rect_min, + ImU32 color, + float thickness, + bool closed = false) { + if (points.size() < 2) { + return; + } + std::vector screen; + screen.reserve(points.size()); + for (const ProjectedPoint &point : points) { + screen.push_back(ImVec2(rect_min.x + point.x * zoom_scale - static_cast(top_left_x), + rect_min.y + point.y * zoom_scale - static_cast(top_left_y))); + } + draw_list->AddPolyline(screen.data(), static_cast(screen.size()), color, + closed ? ImDrawFlags_Closed : ImDrawFlags_None, thickness); +} + +void draw_water_polygon(ImDrawList *draw_list, + const WaterPolygonFeature &feature, + float zoom_scale, + double top_left_x, + double top_left_y, + const ImVec2 &rect_min) { + if (feature.ring.size() < 3) { + return; + } + std::vector screen; + screen.reserve(feature.ring.size()); + for (const ProjectedPoint &point : feature.ring) { + screen.push_back(ImVec2(rect_min.x + point.x * zoom_scale - static_cast(top_left_x), + rect_min.y + point.y * zoom_scale - static_cast(top_left_y))); + } + if (screen.size() >= 3 && is_convex_ring(screen)) { + draw_list->AddConvexPolyFilled(screen.data(), static_cast(screen.size()), MAP_WATER_FILL); + } + draw_list->AddPolyline(screen.data(), static_cast(screen.size()), MAP_WATER_OUTLINE, + ImDrawFlags_Closed, 1.8f); +} + +void draw_edge_fade(ImDrawList *draw_list, + const GeoBounds &bounds, + double zoom, + double top_left_x, + double top_left_y, + const ImVec2 &rect_min, + const ImVec2 &rect_max) { + if (!bounds.valid()) { + return; + } + + const float west_x = rect_min.x + static_cast(lon_to_world_x(bounds.west, zoom) - top_left_x); + const float east_x = rect_min.x + static_cast(lon_to_world_x(bounds.east, zoom) - top_left_x); + const float north_y = rect_min.y + static_cast(lat_to_world_y(bounds.north, zoom) - top_left_y); + const float south_y = rect_min.y + static_cast(lat_to_world_y(bounds.south, zoom) - top_left_y); + + const float fade_x = std::max(28.0f, (rect_max.x - rect_min.x) * MAP_EDGE_FADE_FRAC); + const float fade_y = std::max(28.0f, (rect_max.y - rect_min.y) * MAP_EDGE_FADE_FRAC); + const ImU32 solid = MAP_BG_COLOR; + const ImU32 clear = IM_COL32(244, 243, 238, 6); + + if (west_x > rect_min.x) { + const float x0 = rect_min.x; + const float x1 = std::min(rect_max.x, west_x); + const float xfade = std::max(x0, x1 - fade_x); + draw_list->AddRectFilledMultiColor(ImVec2(x0, rect_min.y), ImVec2(xfade, rect_max.y), solid, solid, solid, solid); + draw_list->AddRectFilledMultiColor(ImVec2(xfade, rect_min.y), ImVec2(x1, rect_max.y), solid, clear, clear, solid); + } + if (east_x < rect_max.x) { + const float x0 = std::max(rect_min.x, east_x); + const float x1 = rect_max.x; + const float xfade = std::min(x1, x0 + fade_x); + draw_list->AddRectFilledMultiColor(ImVec2(x0, rect_min.y), ImVec2(xfade, rect_max.y), clear, solid, solid, clear); + draw_list->AddRectFilledMultiColor(ImVec2(xfade, rect_min.y), ImVec2(x1, rect_max.y), solid, solid, solid, solid); + } + if (north_y > rect_min.y) { + const float y0 = rect_min.y; + const float y1 = std::min(rect_max.y, north_y); + const float yfade = std::max(y0, y1 - fade_y); + draw_list->AddRectFilledMultiColor(ImVec2(rect_min.x, y0), ImVec2(rect_max.x, yfade), solid, solid, solid, solid); + draw_list->AddRectFilledMultiColor(ImVec2(rect_min.x, yfade), ImVec2(rect_max.x, y1), solid, solid, clear, clear); + } + if (south_y < rect_max.y) { + const float y0 = std::max(rect_min.y, south_y); + const float y1 = rect_max.y; + const float yfade = std::min(y1, y0 + fade_y); + draw_list->AddRectFilledMultiColor(ImVec2(rect_min.x, y0), ImVec2(rect_max.x, yfade), clear, clear, solid, solid); + draw_list->AddRectFilledMultiColor(ImVec2(rect_min.x, yfade), ImVec2(rect_max.x, y1), solid, solid, solid, solid); + } +} + +} // namespace + +MapDataManager::MapDataManager() : worker_([this]() { run(); }) {} + +MapDataManager::~MapDataManager() { + { + std::lock_guard lock(mutex_); + stopping_ = true; + } + cv_.notify_all(); + if (worker_.joinable()) { + worker_.join(); + } +} + +void MapDataManager::pump() { + std::unique_ptr ready; + { + std::lock_guard lock(mutex_); + ready = std::move(completed_); + } + if (ready) { + current_ = std::move(ready); + } +} + +void MapDataManager::ensureTrace(const GpsTrace &trace) { + if (trace.points.empty()) { + return; + } + const MapRequestSpec wanted = build_request_for_trace(trace); + if (!wanted.bounds.valid()) { + return; + } + + std::lock_guard lock(mutex_); + if ((current_ && current_->key == wanted.key) || (pending_ && pending_->key == wanted.key)) { + return; + } + + if (const auto cached = load_compressed_basemap(basemap_cache_path(wanted.key), wanted.key)) { + current_ = std::make_unique(std::move(*cached)); + completed_.reset(); + pending_.reset(); + active_.reset(); + return; + } + + pending_ = std::make_unique(Request{ + .key = wanted.key, + .bounds = wanted.bounds, + .query = wanted.query, + }); + cv_.notify_one(); +} + +bool MapDataManager::loading() const { + std::lock_guard lock(mutex_); + return active_ || pending_; +} + +const RouteBasemap *MapDataManager::current() const { + return current_.get(); +} + +void MapDataManager::clearCache() { + std::lock_guard lock(mutex_); + clear_cache_directory(); +} + +MapCacheStats MapDataManager::cacheStats() const { + return MapCacheStats{ + .bytes = cache_directory_size_bytes(), + .files = cache_directory_file_count(), + }; +} + +void MapDataManager::run() { + while (true) { + Request request; + { + std::unique_lock lock(mutex_); + cv_.wait(lock, [&]() { return stopping_ || pending_ != nullptr; }); + if (stopping_) { + return; + } + request = *pending_; + active_ = std::move(pending_); + } + + std::unique_ptr parsed; + const std::string raw = load_overpass_json(request.query); + if (!raw.empty()) { + if (auto basemap = parse_basemap_json(raw, request.bounds, request.key)) { + save_compressed_basemap(basemap_cache_path(request.key), *basemap); + parsed = std::make_unique(std::move(*basemap)); + } + } + + { + std::lock_guard lock(mutex_); + if (active_ && active_->key == request.key) { + completed_ = std::move(parsed); + active_.reset(); + } + } + } +} + +void draw_map_pane(AppSession *session, UiState *state, Pane *, int pane_index) { + TabUiState *tab_state = app_active_tab_state(state); + if (tab_state == nullptr || pane_index < 0 || pane_index >= static_cast(tab_state->map_panes.size())) { + ImGui::TextUnformatted("Map unavailable"); + return; + } + if (!session->map_data) { + ImGui::TextUnformatted("Map unavailable"); + return; + } + + session->map_data->ensureTrace(session->route_data.gps_trace); + session->map_data->pump(); + + TabUiState::MapPaneState &map_state = tab_state->map_panes[static_cast(pane_index)]; + const GpsTrace &trace = session->route_data.gps_trace; + const RouteBasemap *basemap = session->map_data->current(); + const GeoBounds map_bounds = basemap != nullptr ? basemap->bounds : requested_bounds_for_trace(trace); + + const ImVec2 rect_min = ImGui::GetCursorScreenPos(); + const ImVec2 size = ImGui::GetContentRegionAvail(); + const ImVec2 input_size(std::max(1.0f, size.x - 22.0f), std::max(1.0f, size.y)); + ImGui::SetNextItemAllowOverlap(); + ImGui::InvisibleButton("##map_canvas", input_size); + const ImVec2 rect_max(rect_min.x + size.x, rect_min.y + size.y); + const float rect_width = rect_max.x - rect_min.x; + const float rect_height = rect_max.y - rect_min.y; + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + + draw_list->PushClipRect(rect_min, rect_max, true); + draw_list->AddRectFilled(rect_min, rect_max, MAP_BG_COLOR); + + if (trace.points.empty()) { + const char *label = session->async_route_loading ? "Loading map..." : "No GPS trace"; + const ImVec2 text = ImGui::CalcTextSize(label); + draw_list->AddText(ImVec2(rect_min.x + (rect_width - text.x) * 0.5f, + rect_min.y + (rect_height - text.y) * 0.5f), + IM_COL32(110, 118, 128, 255), label); + draw_list->PopClipRect(); + return; + } + + const std::optional cursor_point = state->has_tracker_time + ? interpolate_gps(trace, state->tracker_time) + : std::optional{}; + if (!map_state.initialized) { + initialize_map_pane_state(&map_state, trace, map_bounds, size, session->data_mode, cursor_point); + } + + const int min_zoom = minimum_allowed_map_zoom(map_bounds, trace, size); + if (map_state.follow && cursor_point.has_value()) { + const float follow_zoom = std::clamp(map_state.zoom, static_cast(min_zoom), static_cast(MAP_MAX_ZOOM)); + const double center_x = lon_to_world_x(map_state.center_lon, follow_zoom); + const double center_y = lat_to_world_y(map_state.center_lat, follow_zoom); + const double top_left_x = center_x - rect_width * 0.5; + const double top_left_y = center_y - rect_height * 0.5; + const ImVec2 car_screen = gps_to_screen(cursor_point->lat, cursor_point->lon, follow_zoom, top_left_x, top_left_y, rect_min); + if (!point_in_rect_with_margin(car_screen, rect_min, rect_max, 0.22f)) { + map_state.center_lat = cursor_point->lat; + map_state.center_lon = cursor_point->lon; + } + } + + map_state.zoom = std::clamp(map_state.zoom, static_cast(min_zoom), static_cast(MAP_MAX_ZOOM)); + clamp_map_center(&map_state, map_bounds, size); + + const double zoom = map_state.zoom; + const float zoom_scale = static_cast(std::exp2(zoom)); + const double center_x = lon_to_world_x(map_state.center_lon, zoom); + const double center_y = lat_to_world_y(map_state.center_lat, zoom); + const double top_left_x = center_x - rect_width * 0.5; + const double top_left_y = center_y - rect_height * 0.5; + const ProjectedBounds current_view = view_bounds(top_left_x, top_left_y, rect_width, rect_height); + + if (basemap != nullptr) { + for (const WaterPolygonFeature &water : basemap->water_polygons) { + if (feature_intersects_view(water.bounds, current_view, zoom_scale)) { + draw_water_polygon(draw_list, water, zoom_scale, top_left_x, top_left_y, rect_min); + } + } + for (const WaterLineFeature &water : basemap->water_lines) { + if (feature_intersects_view(water.bounds, current_view, zoom_scale)) { + draw_feature_polyline(draw_list, water.points, zoom_scale, top_left_x, top_left_y, rect_min, + MAP_WATER_LINE, 2.4f); + } + } + + std::array order = { + RoadClass::Local, + RoadClass::Secondary, + RoadClass::Primary, + RoadClass::Motorway, + }; + for (RoadClass road_class : order) { + const RoadPaint paint = road_paint(road_class, static_cast(zoom)); + for (const RoadFeature &road : basemap->roads) { + if (road.road_class != road_class || !feature_intersects_view(road.bounds, current_view, zoom_scale)) { + continue; + } + draw_feature_polyline(draw_list, road.points, zoom_scale, top_left_x, top_left_y, rect_min, + paint.casing, paint.casing_width); + draw_feature_polyline(draw_list, road.points, zoom_scale, top_left_x, top_left_y, rect_min, + paint.fill, paint.fill_width); + } + } + } + + if (basemap != nullptr) { + draw_edge_fade(draw_list, basemap->bounds, zoom, top_left_x, top_left_y, rect_min, rect_max); + } + + for (size_t i = 1; i < trace.points.size(); ++i) { + const GpsPoint &p0 = trace.points[i - 1]; + const GpsPoint &p1 = trace.points[i]; + const ImVec2 s0 = gps_to_screen(p0.lat, p0.lon, zoom, top_left_x, top_left_y, rect_min); + const ImVec2 s1 = gps_to_screen(p1.lat, p1.lon, zoom, top_left_x, top_left_y, rect_min); + draw_list->AddLine(s0, s1, MAP_ROUTE_HALO, 5.8f); + draw_list->AddLine(s0, s1, map_timeline_color(p1.type, 1.0f), 3.25f); + } + + if (cursor_point.has_value()) { + const ImVec2 marker = gps_to_screen(cursor_point->lat, cursor_point->lon, zoom, top_left_x, top_left_y, rect_min); + const float marker_size = std::clamp(9.0f + 1.0f * static_cast(zoom - min_zoom), 9.0f, 20.0f); + draw_car_marker(draw_list, marker, cursor_point->bearing, map_timeline_color(cursor_point->type, 1.0f), marker_size); + } + + if (session->map_data->loading()) { + const char *label = basemap != nullptr ? "Refreshing roads..." : "Loading roads..."; + const ImVec2 text = ImGui::CalcTextSize(label); + const ImVec2 pos(rect_min.x + 12.0f, rect_max.y - text.y - 12.0f); + draw_list->AddRectFilled(ImVec2(pos.x - 6.0f, pos.y - 4.0f), + ImVec2(pos.x + text.x + 6.0f, pos.y + text.y + 4.0f), + IM_COL32(255, 255, 255, 180), 4.0f); + draw_list->AddText(pos, IM_COL32(84, 93, 105, 255), label); + } + draw_list->PopClipRect(); + + const bool canvas_hovered = ImGui::IsItemHovered(); + const bool double_clicked = canvas_hovered && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left); + bool overlay_hovered = false; + if (const std::string google_maps_url = route_google_maps_url(trace); !google_maps_url.empty()) { + std::string label = std::string("Google Maps ") + icon::BOX_ARROW_UP_RIGHT; + const ImVec2 text_size = ImGui::CalcTextSize(label.c_str()); + const ImVec2 button_size(text_size.x + 20.0f, text_size.y + 10.0f); + const ImVec2 button_pos(rect_max.x - button_size.x - 28.0f, rect_min.y + 10.0f); + ImGui::SetCursorScreenPos(button_pos); + ImGui::SetNextItemAllowOverlap(); + if (ImGui::Button("##open_google_maps", button_size)) { + open_external_url(google_maps_url); + state->status_text = "Opened Google Maps"; + } + overlay_hovered = ImGui::IsItemHovered(); + draw_list->AddText(ImVec2(button_pos.x + 10.0f, button_pos.y + (button_size.y - text_size.y) * 0.5f), + ImGui::GetColorU32(ImGuiCol_Text), label.c_str()); + } + const bool hovered = canvas_hovered && !overlay_hovered; + if (hovered && ImGui::GetIO().MouseWheel != 0.0f) { + const float next_zoom = std::clamp(static_cast(zoom) + ImGui::GetIO().MouseWheel * MAP_WHEEL_ZOOM_STEP, + static_cast(min_zoom), static_cast(MAP_MAX_ZOOM)); + if (std::abs(next_zoom - zoom) > 1.0e-4f) { + const ImVec2 mouse = ImGui::GetIO().MousePos; + const double mouse_world_x = top_left_x + (mouse.x - rect_min.x); + const double mouse_world_y = top_left_y + (mouse.y - rect_min.y); + const double mouse_lon = world_x_to_lon(mouse_world_x, zoom); + const double mouse_lat = world_y_to_lat(mouse_world_y, zoom); + const double next_center_x = lon_to_world_x(mouse_lon, next_zoom) - (mouse.x - rect_min.x) + rect_width * 0.5; + const double next_center_y = lat_to_world_y(mouse_lat, next_zoom) - (mouse.y - rect_min.y) + rect_height * 0.5; + map_state.zoom = next_zoom; + map_state.center_lon = world_x_to_lon(next_center_x, next_zoom); + map_state.center_lat = world_y_to_lat(next_center_y, next_zoom); + map_state.follow = false; + clamp_map_center(&map_state, map_bounds, size); + } + } + if (hovered && ImGui::IsMouseDragging(ImGuiMouseButton_Left, 2.0f)) { + const ImVec2 delta = ImGui::GetIO().MouseDelta; + const double next_center_x = center_x - delta.x; + const double next_center_y = center_y - delta.y; + map_state.center_lon = world_x_to_lon(next_center_x, zoom); + map_state.center_lat = world_y_to_lat(next_center_y, zoom); + map_state.follow = false; + clamp_map_center(&map_state, map_bounds, size); + } else if (hovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { + const ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Left); + if (drag_delta.x * drag_delta.x + drag_delta.y * drag_delta.y < 16.0f) { + const ImVec2 mouse = ImGui::GetIO().MousePos; + double best_dist = std::numeric_limits::max(); + double best_time = state->tracker_time; + for (const GpsPoint &point : trace.points) { + const ImVec2 screen = gps_to_screen(point.lat, point.lon, zoom, top_left_x, top_left_y, rect_min); + const double dx = static_cast(screen.x - mouse.x); + const double dy = static_cast(screen.y - mouse.y); + const double dist = dx * dx + dy * dy; + if (dist < best_dist) { + best_dist = dist; + best_time = point.time; + } + } + state->tracker_time = best_time; + state->has_tracker_time = true; + } + ImGui::ResetMouseDragDelta(ImGuiMouseButton_Left); + } + if (double_clicked) { + map_state.initialized = false; + } +} diff --git a/tools/jotpluggler/map.h b/tools/jotpluggler/map.h new file mode 100644 index 00000000000000..97473f1ba90576 --- /dev/null +++ b/tools/jotpluggler/map.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +struct GpsTrace; +struct GeoBounds { + double south = 0.0; + double west = 0.0; + double north = 0.0; + double east = 0.0; + + bool valid() const { + return south < north && west < east; + } +}; + +struct RouteBasemap; +struct MapCacheStats { + uint64_t bytes = 0; + size_t files = 0; +}; + +class MapDataManager { +public: + MapDataManager(); + ~MapDataManager(); + + MapDataManager(const MapDataManager &) = delete; + MapDataManager &operator=(const MapDataManager &) = delete; + + void pump(); + void ensureTrace(const GpsTrace &trace); + void clearCache(); + bool loading() const; + const RouteBasemap *current() const; + MapCacheStats cacheStats() const; + +private: + struct Request { + std::string key; + GeoBounds bounds; + std::string query; + }; + + void run(); + + mutable std::mutex mutex_; + std::condition_variable cv_; + bool stopping_ = false; + std::unique_ptr pending_; + std::unique_ptr active_; + std::unique_ptr completed_; + std::unique_ptr current_; + std::thread worker_; +}; diff --git a/tools/jotpluggler/math_eval.py b/tools/jotpluggler/math_eval.py new file mode 100755 index 00000000000000..a865c88a3a7777 --- /dev/null +++ b/tools/jotpluggler/math_eval.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 + +import json +import sys +import textwrap +import traceback + +import numpy as np + + +def _load_manifest(path: str) -> dict: + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def _load_vector(path: str) -> np.ndarray: + return np.fromfile(path, dtype=np.float64) + + +def _write_vector(path: str, values: np.ndarray) -> None: + np.asarray(values, dtype=np.float64).tofile(path) + + +def _resample_to_reference(ref_t: np.ndarray, src_t: np.ndarray, src_v: np.ndarray) -> np.ndarray: + ref_t = np.asarray(ref_t, dtype=np.float64).reshape(-1) + src_t = np.asarray(src_t, dtype=np.float64).reshape(-1) + src_v = np.asarray(src_v, dtype=np.float64).reshape(-1) + if ref_t.size == 0 or src_t.size == 0 or src_v.size == 0: + return np.empty_like(ref_t) + indices = np.searchsorted(src_t, ref_t, side="right") - 1 + indices = np.clip(indices, 0, src_v.size - 1) + return src_v[indices] + + +def _evaluate_user_code(code: str, env: dict): + stripped = code.strip() + if not stripped: + raise ValueError("Function body is empty") + + expr = stripped + if expr.startswith("return "): + expr = expr[7:].strip() + try: + return eval(expr, env, env) + except SyntaxError: + pass + + function_src = "def __jotpluggler_eval__():\n" + textwrap.indent(code, " ") + exec(function_src, env, env) + return env["__jotpluggler_eval__"]() + + +def main() -> int: + if len(sys.argv) != 6: + print("usage: math_eval.py ", file=sys.stderr) + return 2 + + manifest_path, globals_path, code_path, out_t_path, out_v_path = sys.argv[1:6] + manifest = _load_manifest(manifest_path) + + series_t = {} + series_v = {} + for entry in manifest.get("series", []): + path = entry["path"] + series_t[path] = _load_vector(entry["t"]) + series_v[path] = _load_vector(entry["v"]) + + first_path = manifest.get("linked_source") or None + + def remember(path: str) -> None: + nonlocal first_path + if first_path is None: + first_path = path + + def t(path: str) -> np.ndarray: + remember(path) + return series_t[path] + + def v(path: str) -> np.ndarray: + remember(path) + return series_v[path] + + additional_sources = list(manifest.get("additional_sources", [])) + linked_source = manifest.get("linked_source") or "" + paths = list(manifest.get("paths", [])) + + env = { + "__builtins__": __builtins__, + "np": np, + "t": t, + "v": v, + "paths": paths, + "linked_source": linked_source, + "additional_sources": additional_sources, + } + + reference_time = None + if linked_source: + reference_time = series_t[linked_source] + env["time"] = reference_time + env["value"] = series_v[linked_source] + + for i, path in enumerate(additional_sources, start=1): + if reference_time is None: + env[f"t{i}"] = series_t[path] + env[f"v{i}"] = series_v[path] + else: + env[f"t{i}"] = reference_time + env[f"v{i}"] = _resample_to_reference(reference_time, series_t[path], series_v[path]) + + with open(globals_path, encoding="utf-8") as f: + globals_code = f.read() + if globals_code.strip(): + exec(globals_code, env, env) + + with open(code_path, encoding="utf-8") as f: + user_code = f.read() + result = _evaluate_user_code(user_code, env) + + if isinstance(result, tuple) and len(result) == 2: + result_t, result_v = result + else: + if first_path is None: + raise ValueError("No reference series found. Set an input timeseries or return (times, values).") + result_t = series_t[first_path] + result_v = result + + result_t = np.asarray(result_t, dtype=np.float64).reshape(-1) + result_v = np.asarray(result_v, dtype=np.float64).reshape(-1) + if result_t.size == 0 or result_v.size == 0: + raise ValueError("Custom series returned an empty result") + if result_t.shape != result_v.shape: + raise ValueError(f"Time/value arrays must have the same shape, got {result_t.shape} and {result_v.shape}") + + _write_vector(out_t_path, result_t) + _write_vector(out_v_path, result_v) + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception as err: + traceback.print_exc() + raise SystemExit(1) from err diff --git a/tools/jotpluggler/plot.cc b/tools/jotpluggler/plot.cc new file mode 100644 index 00000000000000..019eff70702c0b --- /dev/null +++ b/tools/jotpluggler/plot.cc @@ -0,0 +1,936 @@ +#include "tools/jotpluggler/internal.h" + +#include "implot.h" +#include "imgui_internal.h" + +#include +#include +#include + +struct PlotBounds { + double x_min = 0.0; + double x_max = 1.0; + double y_min = 0.0; + double y_max = 1.0; +}; + +bool curve_has_samples(const AppSession &session, const Curve &curve) { + if (curve_has_local_samples(curve)) return true; + if (curve.name.empty() || curve.name.front() != '/') { + return false; + } + const RouteSeries *series = app_find_route_series(session, curve.name); + return series != nullptr && series->times.size() > 1 && series->times.size() == series->values.size(); +} + +void extend_range(const std::vector &values, bool *found, double *min_value, double *max_value) { + if (values.empty()) { + return; + } + const auto [min_it, max_it] = std::minmax_element(values.begin(), values.end()); + if (!*found) { + *min_value = *min_it; + *max_value = *max_it; + *found = true; + return; + } + *min_value = std::min(*min_value, *min_it); + *max_value = std::max(*max_value, *max_it); +} + +void ensure_non_degenerate_range(double *min_value, double *max_value, double pad_fraction, double fallback_pad) { + if (*max_value <= *min_value) { + const double pad = std::max(std::abs(*min_value) * 0.1, fallback_pad); + *min_value -= pad; + *max_value += pad; + return; + } + const double span = *max_value - *min_value; + const double pad = std::max(span * pad_fraction, fallback_pad); + *min_value -= pad; + *max_value += pad; +} + +struct PreparedCurve { + int pane_curve_index = -1; + std::string label; + std::array color = {160, 170, 180}; + float line_weight = 2.0f; + bool stairs = false; + const EnumInfo *enum_info = nullptr; + SeriesFormat display_info; + std::optional legend_value; + std::vector xs; + std::vector ys; +}; + +struct StateBlock { + double t0 = 0.0; + double t1 = 0.0; + int value = 0; + std::string label; +}; + +struct PaneValueFormatContext { + SeriesFormat format; + bool valid = false; +}; + +bool curves_are_bool_like(const std::vector &prepared_curves) { + if (prepared_curves.empty()) { + return false; + } + for (const PreparedCurve &curve : prepared_curves) { + if (!curve.display_info.integer_like || curve.ys.empty()) { + return false; + } + bool found_finite = false; + for (double value : curve.ys) { + if (!std::isfinite(value)) continue; + found_finite = true; + if (std::abs(value) > 0.01 && std::abs(value - 1.0) > 0.01) { + return false; + } + } + if (!found_finite) { + return false; + } + } + return true; +} + +ImU32 state_block_color(int value, float alpha = 1.0f) { + static constexpr std::array, 8> kPalette = {{ + {{111, 143, 175}}, + {{0, 163, 108}}, + {{255, 195, 0}}, + {{199, 0, 57}}, + {{123, 97, 255}}, + {{0, 150, 136}}, + {{214, 48, 49}}, + {{52, 73, 94}}, + }}; + const size_t index = static_cast(std::abs(value)) % kPalette.size(); + return ImGui::GetColorU32(color_rgb(kPalette[index], alpha)); +} + +std::string state_block_label(const PreparedCurve &curve, int value) { + if (curve.enum_info != nullptr && value >= 0 && static_cast(value) < curve.enum_info->names.size()) { + const std::string &name = curve.enum_info->names[static_cast(value)]; + if (!name.empty()) { + return name; + } + } + return std::to_string(value); +} + +std::vector build_state_blocks(const PreparedCurve &curve) { + std::vector blocks; + if (curve.xs.size() < 2 || curve.xs.size() != curve.ys.size()) { + return blocks; + } + + int current_value = static_cast(std::llround(curve.ys.front())); + double start_time = curve.xs.front(); + for (size_t i = 1; i < curve.xs.size(); ++i) { + const int value = static_cast(std::llround(curve.ys[i])); + if (value == current_value) { + continue; + } + const double end_time = curve.xs[i]; + if (end_time > start_time) { + blocks.push_back(StateBlock{ + .t0 = start_time, + .t1 = end_time, + .value = current_value, + .label = state_block_label(curve, current_value), + }); + } + current_value = value; + start_time = end_time; + } + + const double final_time = curve.xs.back(); + if (final_time >= start_time) { + blocks.push_back(StateBlock{ + .t0 = start_time, + .t1 = final_time, + .value = current_value, + .label = state_block_label(curve, current_value), + }); + } + return blocks; +} + +void app_decimate_samples_impl(const std::vector &xs_in, + const std::vector &ys_in, + int max_points, + std::vector *xs_out, + std::vector *ys_out) { + + const size_t bucket_count = std::max(1, static_cast(max_points / 4)); + const size_t bucket_size = std::max( + 1, + static_cast(std::ceil(static_cast(xs_in.size()) / static_cast(bucket_count)))); + xs_out->reserve(bucket_count * 4 + 2); + ys_out->reserve(bucket_count * 4 + 2); + + size_t last_index = std::numeric_limits::max(); + auto append_index = [&](size_t index) { + if (index >= xs_in.size() || index == last_index) { + return; + } + xs_out->push_back(xs_in[index]); + ys_out->push_back(ys_in[index]); + last_index = index; + }; + + for (size_t start = 0; start < xs_in.size(); start += bucket_size) { + const size_t end = std::min(xs_in.size(), start + bucket_size); + size_t min_index = start; + size_t max_index = start; + for (size_t index = start + 1; index < end; ++index) { + if (ys_in[index] < ys_in[min_index]) { + min_index = index; + } + if (ys_in[index] > ys_in[max_index]) { + max_index = index; + } + } + + std::array indices = {start, min_index, max_index, end - 1}; + std::sort(indices.begin(), indices.end()); + for (size_t index : indices) { + append_index(index); + } + } +} + +void app_decimate_samples(const std::vector &xs_in, + const std::vector &ys_in, + int max_points, + std::vector *xs_out, + std::vector *ys_out) { + xs_out->clear(); + ys_out->clear(); + if (xs_in.empty() || xs_in.size() != ys_in.size()) { + return; + } + if (max_points <= 0 || static_cast(xs_in.size()) <= max_points) { + *xs_out = xs_in; + *ys_out = ys_in; + return; + } + app_decimate_samples_impl(xs_in, ys_in, max_points, xs_out, ys_out); +} + +void app_decimate_samples(std::vector &&xs_in, + std::vector &&ys_in, + int max_points, + std::vector *xs_out, + std::vector *ys_out) { + xs_out->clear(); + ys_out->clear(); + if (xs_in.empty() || xs_in.size() != ys_in.size()) { + return; + } + if (max_points <= 0 || static_cast(xs_in.size()) <= max_points) { + *xs_out = std::move(xs_in); + *ys_out = std::move(ys_in); + return; + } + app_decimate_samples_impl(xs_in, ys_in, max_points, xs_out, ys_out); +} + +std::optional app_sample_xy_value_at_time(const std::vector &xs, + const std::vector &ys, + bool stairs, + double tm) { + if (xs.size() < 2 || xs.size() != ys.size()) { + return std::nullopt; + } + if (tm <= xs.front()) return ys.front(); + if (tm >= xs.back()) return ys.back(); + + const auto upper = std::lower_bound(xs.begin(), xs.end(), tm); + if (upper == xs.begin()) return ys.front(); + if (upper == xs.end()) return ys.back(); + + const size_t upper_index = static_cast(std::distance(xs.begin(), upper)); + const size_t lower_index = upper_index - 1; + const double x0 = xs[lower_index]; + const double x1 = xs[upper_index]; + const double y0 = ys[lower_index]; + const double y1 = ys[upper_index]; + if (std::abs(tm - x1) < 1.0e-9) return y1; + if (stairs || x1 <= x0) return y0; + const double alpha = (tm - x0) / (x1 - x0); + return y0 + (y1 - y0) * alpha; +} + +int format_numeric_axis_tick(double value, char *buf, int size, void *user_data) { + const auto *ctx = static_cast(user_data); + if (ctx == nullptr || !ctx->valid) { + return std::snprintf(buf, size, "%.6g", value); + } + if (ctx->format.integer_like) { + const double nearest_int = std::round(value); + if (std::abs(value - nearest_int) > 1.0e-6) { + int decimals = 1; + while (decimals < 4) { + const double scale = std::pow(10.0, decimals); + const double rounded = std::round(value * scale) / scale; + if (std::abs(value - rounded) <= 1.0e-6) { + break; + } + ++decimals; + } + return std::snprintf(buf, size, "%.*f", decimals, value); + } + } + return std::snprintf(buf, size, ctx->format.fmt, value); +} + +void merge_pane_value_format(PaneValueFormatContext *ctx, const SeriesFormat &format) { + if (!ctx->valid) { + ctx->format = format; + ctx->valid = true; + return; + } + ctx->format.has_negative = ctx->format.has_negative || format.has_negative; + ctx->format.digits_before = std::max(ctx->format.digits_before, format.digits_before); + ctx->format.decimals = std::max(ctx->format.decimals, format.decimals); + ctx->format.integer_like = ctx->format.decimals == 0; + const int sign_width = ctx->format.has_negative ? 1 : 0; + const int dot_width = ctx->format.decimals > 0 ? 1 : 0; + ctx->format.total_width = sign_width + ctx->format.digits_before + dot_width + ctx->format.decimals; + std::snprintf(ctx->format.fmt, sizeof(ctx->format.fmt), "%%%d.%df", + ctx->format.total_width, ctx->format.decimals); +} + +std::string curve_legend_label(const PreparedCurve &curve, bool has_cursor_time, size_t label_width) { + if (!has_cursor_time) return curve.label; + if (!curve.legend_value.has_value()) return curve.label; + const std::string value_text = format_display_value(*curve.legend_value, curve.display_info, curve.enum_info); + if (value_text.empty()) return curve.label; + const size_t padded_width = std::max(label_width, curve.label.size()); + return curve.label + std::string(padded_width - curve.label.size() + 2, ' ') + value_text; +} + +bool build_curve_series(const AppSession &session, + const Curve &curve, + const UiState &state, + int max_points, + PreparedCurve *prepared) { + std::vector xs; + std::vector ys; + if (curve_has_local_samples(curve)) { + xs = curve.xs; + ys = curve.ys; + } else { + const RouteSeries *series = app_find_route_series(session, curve.name); + if (series == nullptr || series->times.size() < 2 || series->times.size() != series->values.size()) { + return false; + } + + size_t begin_index = 0; + size_t end_index = series->times.size(); + if (state.has_shared_range && state.x_view_max > state.x_view_min) { + auto begin_it = std::lower_bound(series->times.begin(), series->times.end(), state.x_view_min); + auto end_it = std::upper_bound(series->times.begin(), series->times.end(), state.x_view_max); + begin_index = begin_it == series->times.begin() ? 0 : static_cast(std::distance(series->times.begin(), begin_it - 1)); + end_index = end_it == series->times.end() ? series->times.size() : static_cast(std::distance(series->times.begin(), end_it + 1)); + end_index = std::min(end_index, series->times.size()); + } + if (end_index <= begin_index + 1) return false; + xs.assign(series->times.begin() + begin_index, series->times.begin() + end_index); + ys.assign(series->values.begin() + begin_index, series->values.begin() + end_index); + } + + std::vector transformed_xs; + std::vector transformed_ys; + if (curve.derivative) { + if (xs.size() < 2) return false; + transformed_xs.reserve(xs.size() - 1); + transformed_ys.reserve(ys.size() - 1); + for (size_t i = 1; i < xs.size(); ++i) { + const double dt = curve.derivative_dt > 0.0 ? curve.derivative_dt : (xs[i] - xs[i - 1]); + if (dt <= 0.0) continue; + transformed_xs.push_back(xs[i]); + transformed_ys.push_back((ys[i] - ys[i - 1]) / dt); + } + } else { + transformed_xs = std::move(xs); + transformed_ys = std::move(ys); + } + + if (transformed_xs.size() < 2 || transformed_xs.size() != transformed_ys.size()) { + return false; + } + + for (double &value : transformed_ys) { + value = value * curve.value_scale + curve.value_offset; + } + + prepared->label = app_curve_display_name(curve); + prepared->color = curve.color; + prepared->line_weight = curve.derivative ? 1.8f : 2.25f; + if (!curve.derivative + && curve.value_scale == 1.0 + && curve.value_offset == 0.0 + && !curve_has_local_samples(curve) + && !curve.name.empty() + && curve.name.front() == '/') { + auto it = session.route_data.enum_info.find(curve.name); + if (it != session.route_data.enum_info.end()) { + prepared->enum_info = &it->second; + } + } + if (prepared->enum_info != nullptr) { + prepared->display_info = compute_series_format(transformed_ys, true); + } else if (!curve_has_local_samples(curve) + && !curve.derivative + && curve.value_scale == 1.0 + && curve.value_offset == 0.0 + && !curve.name.empty() + && curve.name.front() == '/') { + auto display_it = session.route_data.series_formats.find(curve.name); + if (display_it != session.route_data.series_formats.end()) { + prepared->display_info = display_it->second; + } else { + prepared->display_info = compute_series_format(transformed_ys, false); + } + } else { + prepared->display_info = compute_series_format(transformed_ys, false); + } + const bool stairs = !curve.derivative && prepared->display_info.integer_like; + if (state.has_tracker_time) { + prepared->legend_value = app_sample_xy_value_at_time(transformed_xs, transformed_ys, stairs, state.tracker_time); + } + if (stairs) { + prepared->xs = std::move(transformed_xs); + prepared->ys = std::move(transformed_ys); + } else { + app_decimate_samples(std::move(transformed_xs), std::move(transformed_ys), max_points, &prepared->xs, &prepared->ys); + } + prepared->stairs = stairs; + return prepared->xs.size() > 1 && prepared->xs.size() == prepared->ys.size(); +} + +bool draw_pane_close_button_overlay() { + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 content_min = ImGui::GetWindowContentRegionMin(); + const ImVec2 content_max = ImGui::GetWindowContentRegionMax(); + const ImRect rect(ImVec2(window_pos.x + content_max.x - 42.0f, window_pos.y + content_min.y + 4.0f), + ImVec2(window_pos.x + content_max.x - 4.0f, window_pos.y + content_min.y + 42.0f)); + const bool hovered = ImGui::IsMouseHoveringRect(rect.Min, rect.Max, false); + const bool held = hovered && ImGui::IsMouseDown(ImGuiMouseButton_Left); + if (hovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + const float pad = 11.0f; + const ImU32 color = hovered || held + ? ImGui::GetColorU32(color_rgb(72, 79, 88)) + : ImGui::GetColorU32(color_rgb(138, 146, 156)); + draw_list->AddLine(ImVec2(rect.Min.x + pad, rect.Min.y + pad), + ImVec2(rect.Max.x - pad, rect.Max.y - pad), + color, + 2.4f); + draw_list->AddLine(ImVec2(rect.Min.x + pad, rect.Max.y - pad), + ImVec2(rect.Max.x - pad, rect.Min.y + pad), + color, + 2.4f); + return hovered && ImGui::IsMouseClicked(ImGuiMouseButton_Left); +} + +void draw_pane_frame_overlay() { + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 content_min = ImGui::GetWindowContentRegionMin(); + const ImVec2 content_max = ImGui::GetWindowContentRegionMax(); + const ImRect frame_rect(ImVec2(window_pos.x + content_min.x, window_pos.y + content_min.y), + ImVec2(window_pos.x + content_max.x, window_pos.y + content_max.y)); + ImGui::GetWindowDrawList()->AddRect(frame_rect.Min, + frame_rect.Max, + ImGui::GetColorU32(color_rgb(186, 190, 196)), + 0.0f, + 0, + 1.0f); +} + +PlotBounds compute_plot_bounds(const Pane &pane, + const std::vector &prepared_curves, + const UiState &state) { + PlotBounds bounds; + bounds.x_min = state.has_shared_range ? state.x_view_min : 0.0; + bounds.x_max = state.has_shared_range ? state.x_view_max : 1.0; + if (bounds.x_max <= bounds.x_min) { + bounds.x_max = bounds.x_min + 1.0; + } + + bool found = false; + double min_value = 0.0; + double max_value = 1.0; + for (const PreparedCurve &curve : prepared_curves) { + extend_range(curve.ys, &found, &min_value, &max_value); + } + if (!found) { + min_value = 0.0; + max_value = 1.0; + } + if (curves_are_bool_like(prepared_curves)) { + min_value = std::min(min_value, 0.0); + max_value = std::max(max_value, 1.0); + } + ensure_non_degenerate_range(&min_value, &max_value, PLOT_Y_PADDING_FRACTION, 0.1); + if (pane.range.has_y_limit_min) { + min_value = pane.range.y_limit_min; + } + if (pane.range.has_y_limit_max) { + max_value = pane.range.y_limit_max; + } + ensure_non_degenerate_range(&min_value, &max_value, 0.0, 0.1); + bounds.y_min = min_value; + bounds.y_max = max_value; + return bounds; +} + +void draw_state_blocks_pane(const std::vector &prepared_curves, UiState *state) { + if (prepared_curves.empty() || !state->has_shared_range || state->x_view_max <= state->x_view_min) { + return; + } + + ImDrawList *draw_list = ImPlot::GetPlotDrawList(); + const ImVec2 plot_min = ImPlot::GetPlotPos(); + const ImVec2 plot_size = ImPlot::GetPlotSize(); + const int curve_count = static_cast(prepared_curves.size()); + if (plot_size.x <= 2.0f || plot_size.y <= 2.0f || curve_count <= 0) { + return; + } + + float label_width = 0.0f; + if (curve_count > 1) { + for (const PreparedCurve &curve : prepared_curves) { + label_width = std::max(label_width, ImGui::CalcTextSize(curve.label.c_str()).x); + } + label_width = std::clamp(label_width + 14.0f, 72.0f, std::min(160.0f, plot_size.x * 0.35f)); + } + + const float row_height = plot_size.y / static_cast(curve_count); + const float blocks_min_x = plot_min.x + label_width; + const float blocks_max_x = plot_min.x + plot_size.x; + const float blocks_width = std::max(1.0f, blocks_max_x - blocks_min_x); + const double x_span = std::max(1.0e-9, state->x_view_max - state->x_view_min); + + struct HoveredBlock { + int curve_index = -1; + StateBlock block; + }; + std::optional hovered; + + const ImVec2 mouse_pos = ImGui::GetMousePos(); + const bool plot_hovered = ImPlot::IsPlotHovered(); + + for (int curve_index = 0; curve_index < curve_count; ++curve_index) { + const PreparedCurve &curve = prepared_curves[static_cast(curve_index)]; + const float y0 = plot_min.y + row_height * static_cast(curve_index); + const float y1 = y0 + row_height; + const std::vector blocks = build_state_blocks(curve); + + if (curve_index > 0) { + draw_list->AddLine(ImVec2(plot_min.x, y0), ImVec2(plot_min.x + plot_size.x, y0), + IM_COL32(210, 214, 220, 255), 1.0f); + } + if (curve_count > 1) { + draw_list->AddLine(ImVec2(blocks_min_x, y0), ImVec2(blocks_min_x, y1), + IM_COL32(210, 214, 220, 255), 1.0f); + const float label_left = plot_min.x + 6.0f; + const float label_right = std::max(label_left + 12.0f, blocks_min_x - 6.0f); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(120, 128, 138)); + ImGui::RenderTextEllipsis(draw_list, + ImVec2(label_left, y0 + 4.0f), + ImVec2(label_right, y1 - 4.0f), + label_right, + curve.label.c_str(), + nullptr, + nullptr); + ImGui::PopStyleColor(); + } + + for (const StateBlock &block : blocks) { + const double visible_t0 = std::max(block.t0, state->x_view_min); + const double visible_t1 = std::min(block.t1, state->x_view_max); + if (visible_t1 <= visible_t0) { + continue; + } + const float x0 = blocks_min_x + static_cast((visible_t0 - state->x_view_min) / x_span) * blocks_width; + const float x1 = blocks_min_x + static_cast((visible_t1 - state->x_view_min) / x_span) * blocks_width; + const ImU32 fill_color = state_block_color(block.value, 0.15f); + const ImU32 line_color = state_block_color(block.value, 0.90f); + draw_list->AddRectFilled(ImVec2(x0, y0), ImVec2(std::max(x1, x0 + 1.0f), y1), fill_color); + draw_list->AddLine(ImVec2(x0, y0), ImVec2(x0, y1), line_color, 2.0f); + + const float block_width = x1 - x0; + if (block_width > 14.0f) { + const float text_left = x0 + 6.0f; + const float text_right = x1 - 6.0f; + if (text_right > text_left) { + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(state_block_color(block.value, 0.80f))); + ImGui::RenderTextEllipsis(draw_list, + ImVec2(text_left, y0 + 4.0f), + ImVec2(text_right, y1 - 4.0f), + text_right, + block.label.c_str(), + nullptr, + nullptr); + ImGui::PopStyleColor(); + } + } + + if (plot_hovered && mouse_pos.x >= blocks_min_x && mouse_pos.x <= blocks_max_x && mouse_pos.y >= y0 && mouse_pos.y <= y1) { + const double hover_time = state->x_view_min + static_cast((mouse_pos.x - blocks_min_x) / blocks_width) * x_span; + if (hover_time >= block.t0 && hover_time <= block.t1) { + hovered = HoveredBlock{ + .curve_index = curve_index, + .block = block, + }; + } + } + } + } + + if (hovered.has_value()) { + const HoveredBlock &info = *hovered; + ImGui::BeginTooltip(); + if (curve_count > 1) { + ImGui::Text("%s: %s (%d)", prepared_curves[static_cast(info.curve_index)].label.c_str(), + info.block.label.c_str(), info.block.value); + } else { + ImGui::Text("%s (%d)", info.block.label.c_str(), info.block.value); + } + ImGui::Separator(); + ImGui::Text("%.3fs -> %.3fs", info.block.t0, info.block.t1); + ImGui::Text("duration: %.3fs", info.block.t1 - info.block.t0); + ImGui::EndTooltip(); + } +} + +void persist_shared_range_to_tab(WorkspaceTab *tab, const UiState &state) { + if (tab == nullptr || !state.has_shared_range) { + return; + } + const double x_min = state.x_view_min; + const double x_max = state.x_view_max > state.x_view_min ? state.x_view_max : state.x_view_min + 1.0; + for (Pane &pane : tab->panes) { + pane.range.valid = true; + pane.range.left = x_min; + pane.range.right = x_max; + } +} + +void clear_pane_vertical_limits(Pane *pane) { + if (pane == nullptr) { + return; + } + pane->range.has_y_limit_min = false; + pane->range.has_y_limit_max = false; +} + +PlotBounds current_plot_bounds_for_pane(const AppSession &session, const Pane &pane, const UiState &state) { + std::vector prepared_curves; + prepared_curves.reserve(pane.curves.size()); + constexpr int kAxisEditorMaxPoints = 2048; + for (size_t curve_index = 0; curve_index < pane.curves.size(); ++curve_index) { + const Curve &curve = pane.curves[curve_index]; + if (!curve.visible || !curve_has_samples(session, curve)) continue; + PreparedCurve prepared; + if (build_curve_series(session, curve, state, kAxisEditorMaxPoints, &prepared)) { + prepared.pane_curve_index = static_cast(curve_index); + prepared_curves.push_back(std::move(prepared)); + } + } + return compute_plot_bounds(pane, prepared_curves, state); +} + +void open_axis_limits_editor(const AppSession &session, UiState *state, int pane_index) { + ensure_shared_range(state, session); + clamp_shared_range(state, session); + const WorkspaceTab *tab = app_active_tab(session.layout, *state); + if (tab == nullptr || pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return; + } + + const Pane &pane = tab->panes[static_cast(pane_index)]; + const PlotBounds bounds = current_plot_bounds_for_pane(session, pane, *state); + AxisLimitsEditorState &editor = state->axis_limits; + editor.open = true; + editor.pane_index = pane_index; + editor.x_min = state->x_view_min; + editor.x_max = state->x_view_max; + editor.y_min_enabled = pane.range.has_y_limit_min; + editor.y_max_enabled = pane.range.has_y_limit_max; + editor.y_min = pane.range.has_y_limit_min ? pane.range.y_limit_min : bounds.y_min; + editor.y_max = pane.range.has_y_limit_max ? pane.range.y_limit_max : bounds.y_max; +} + +bool apply_axis_limits_editor(AppSession *session, UiState *state) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + if (tab == nullptr) return false; + + AxisLimitsEditorState &editor = state->axis_limits; + if (editor.pane_index < 0 || editor.pane_index >= static_cast(tab->panes.size())) { + state->error_text = "The selected pane is no longer available."; + state->open_error_popup = true; + return false; + } + if (!std::isfinite(editor.x_min) || !std::isfinite(editor.x_max)) { + state->error_text = "Axis limits must be finite numbers."; + state->open_error_popup = true; + return false; + } + if (editor.x_max <= editor.x_min) { + state->error_text = "X max must be greater than X min."; + state->open_error_popup = true; + return false; + } + if (editor.y_min_enabled && !std::isfinite(editor.y_min)) { + state->error_text = "Y min must be a finite number."; + state->open_error_popup = true; + return false; + } + if (editor.y_max_enabled && !std::isfinite(editor.y_max)) { + state->error_text = "Y max must be a finite number."; + state->open_error_popup = true; + return false; + } + if (editor.y_min_enabled && editor.y_max_enabled && editor.y_max <= editor.y_min) { + state->error_text = "Y max must be greater than Y min."; + state->open_error_popup = true; + return false; + } + + const SketchLayout before_layout = session->layout; + state->has_shared_range = true; + state->x_view_min = editor.x_min; + state->x_view_max = editor.x_max; + if (session->data_mode == SessionDataMode::Stream) { + state->follow_latest = infer_stream_follow_state(*state, *session); + } else { + state->follow_latest = false; + } + state->suppress_range_side_effects = true; + clamp_shared_range(state, *session); + persist_shared_range_to_tab(tab, *state); + + Pane &pane = tab->panes[static_cast(editor.pane_index)]; + pane.range.has_y_limit_min = editor.y_min_enabled; + pane.range.has_y_limit_max = editor.y_max_enabled; + if (editor.y_min_enabled) { + pane.range.y_limit_min = editor.y_min; + } + if (editor.y_max_enabled) { + pane.range.y_limit_max = editor.y_max; + } + + const PlotBounds bounds = current_plot_bounds_for_pane(*session, pane, *state); + pane.range.valid = true; + pane.range.left = state->x_view_min; + pane.range.right = state->x_view_max; + pane.range.bottom = bounds.y_min; + pane.range.top = bounds.y_max; + + state->undo.push(before_layout); + const bool ok = mark_layout_dirty(session, state); + if (ok) { + state->status_text = "Axis limits updated"; + } + return ok; +} + +void draw_plot(const AppSession &session, Pane *pane, UiState *state) { + std::vector prepared_curves; + prepared_curves.reserve(pane->curves.size()); + const int max_points = std::max(256, static_cast(ImGui::GetContentRegionAvail().x) * 2); + for (size_t curve_index = 0; curve_index < pane->curves.size(); ++curve_index) { + const Curve &curve = pane->curves[curve_index]; + if (!curve.visible || !curve_has_samples(session, curve)) continue; + PreparedCurve prepared; + if (build_curve_series(session, curve, *state, max_points, &prepared)) { + prepared.pane_curve_index = static_cast(curve_index); + prepared_curves.push_back(std::move(prepared)); + } + } + + const PlotBounds bounds = compute_plot_bounds(*pane, prepared_curves, *state); + PaneValueFormatContext pane_value_format; + bool state_block_mode = !prepared_curves.empty(); + size_t max_legend_label_width = 0; + for (const PreparedCurve &curve : prepared_curves) { + max_legend_label_width = std::max(max_legend_label_width, curve.label.size()); + if (curve.enum_info == nullptr) { + state_block_mode = false; + merge_pane_value_format(&pane_value_format, curve.display_info); + } + } + const int supported_count = static_cast(prepared_curves.size()); + const ImVec2 plot_size = ImGui::GetContentRegionAvail(); + const bool has_cursor_time = state->has_tracker_time; + const double cursor_time = state->tracker_time; + + ImPlot::PushStyleColor(ImPlotCol_PlotBg, color_rgb(255, 255, 255)); + ImPlot::PushStyleColor(ImPlotCol_PlotBorder, color_rgb(186, 190, 196)); + ImPlot::PushStyleColor(ImPlotCol_LegendBg, color_rgb(248, 249, 251, 0.92f)); + ImPlot::PushStyleColor(ImPlotCol_LegendBorder, color_rgb(168, 175, 184)); + ImPlot::PushStyleColor(ImPlotCol_LegendText, color_rgb(57, 62, 69)); + ImPlot::PushStyleColor(ImPlotCol_TitleText, color_rgb(57, 62, 69)); + ImPlot::PushStyleColor(ImPlotCol_InlayText, color_rgb(95, 103, 112)); + ImPlot::PushStyleColor(ImPlotCol_AxisGrid, color_rgb(188, 196, 206)); + ImPlot::PushStyleColor(ImPlotCol_AxisText, color_rgb(95, 103, 112)); + ImPlot::PushStyleColor(ImPlotCol_AxisBg, color_rgb(255, 255, 255, 0.0f)); + ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, color_rgb(214, 220, 228, 0.45f)); + ImPlot::PushStyleColor(ImPlotCol_AxisBgActive, color_rgb(199, 209, 222, 0.55f)); + ImPlot::PushStyleColor(ImPlotCol_Selection, color_rgb(252, 211, 77, 0.28f)); + ImPlot::PushStyleColor(ImPlotCol_Crosshairs, color_rgb(120, 128, 138, 0.70f)); + ImPlot::PushStyleVar(ImPlotStyleVar_LegendPadding, ImVec2(56.0f, 10.0f)); + + ImPlotFlags plot_flags = ImPlotFlags_NoTitle | ImPlotFlags_NoMenus; + if (state_block_mode) { + plot_flags |= ImPlotFlags_NoLegend | ImPlotFlags_NoMouseText; + } + if (supported_count == 0) { + plot_flags |= ImPlotFlags_NoLegend; + } + + const ImPlotAxisFlags x_axis_flags = ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_NoHighlight; + ImPlotAxisFlags y_axis_flags = ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_NoHighlight; + if (state_block_mode) { + y_axis_flags |= ImPlotAxisFlags_NoDecorations; + } + const bool explicit_y = pane->range.has_y_limit_min || pane->range.has_y_limit_max; + if (!state_block_mode && !explicit_y && supported_count > 0) { + y_axis_flags |= ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit; + } + + const double previous_x_min = state->x_view_min; + const double previous_x_max = state->x_view_max; + app_push_mono_font(); + if (ImPlot::BeginPlot("##plot", plot_size, plot_flags)) { + ImPlot::SetupAxes(nullptr, nullptr, x_axis_flags, y_axis_flags); + ImPlot::SetupAxisFormat(ImAxis_X1, "%.1f"); + if (state_block_mode) { + ImPlot::SetupAxisLimits(ImAxis_Y1, 0.0, 1.0, ImPlotCond_Always); + } else if (pane_value_format.valid) { + ImPlot::SetupAxisFormat(ImAxis_Y1, format_numeric_axis_tick, &pane_value_format); + } else { + ImPlot::SetupAxisFormat(ImAxis_Y1, "%.6g"); + } + ImPlot::SetupAxisLinks(ImAxis_X1, &state->x_view_min, &state->x_view_max); + if (state->route_x_max > state->route_x_min) { + const double x_constraint_min = session.data_mode == SessionDataMode::Stream + ? state->route_x_min - std::max(MIN_HORIZONTAL_ZOOM_SECONDS, session.stream_buffer_seconds) + : state->route_x_min; + ImPlot::SetupAxisLimitsConstraints(ImAxis_X1, x_constraint_min, state->route_x_max); + } + if (!state_block_mode) { + ImPlot::SetupMouseText(ImPlotLocation_SouthEast, ImPlotMouseTextFlags_NoAuxAxes); + } + if (!state_block_mode && (explicit_y || supported_count == 0)) { + ImPlot::SetupAxisLimits(ImAxis_Y1, bounds.y_min, bounds.y_max, ImPlotCond_Always); + } + if (!state_block_mode && supported_count > 0) { + ImPlot::SetupLegend(ImPlotLocation_NorthEast); + } + + if (state_block_mode) { + draw_state_blocks_pane(prepared_curves, state); + } else { + for (size_t i = 0; i < prepared_curves.size(); ++i) { + const PreparedCurve &curve = prepared_curves[i]; + std::string series_id = curve_legend_label(curve, has_cursor_time, max_legend_label_width) + "###curve" + std::to_string(curve.pane_curve_index); + ImPlotSpec spec; + spec.LineColor = color_rgb(curve.color); + spec.LineWeight = curve.line_weight; + spec.Flags = ImPlotLineFlags_SkipNaN; + if (!curve.xs.empty() && curve.xs.size() == curve.ys.size()) { + if (curve.stairs) { + spec.Flags = ImPlotStairsFlags_PreStep; + ImPlot::PlotStairs(series_id.c_str(), curve.xs.data(), curve.ys.data(), static_cast(curve.xs.size()), spec); + } else { + ImPlot::PlotLine(series_id.c_str(), curve.xs.data(), curve.ys.data(), static_cast(curve.xs.size()), spec); + } + } + } + } + if (has_cursor_time) { + const double clamped_cursor_time = std::clamp(cursor_time, state->route_x_min, state->route_x_max); + ImPlotSpec cursor_spec; + cursor_spec.LineColor = color_rgb(108, 118, 128, 0.7f); + cursor_spec.LineWeight = 1.0f; + cursor_spec.Flags = ImPlotItemFlags_NoLegend; + ImPlot::PlotInfLines("##tracker_cursor", &clamped_cursor_time, 1, cursor_spec); + } + if (ImPlot::IsPlotHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { + state->tracker_time = std::clamp(ImPlot::GetPlotMousePos().x, state->route_x_min, state->route_x_max); + state->has_tracker_time = true; + } + ImPlot::EndPlot(); + } + app_pop_mono_font(); + clamp_shared_range(state, session); + if (std::abs(state->x_view_min - previous_x_min) > 1.0e-6 + || std::abs(state->x_view_max - previous_x_max) > 1.0e-6) { + if (!state->suppress_range_side_effects) { + if (session.data_mode == SessionDataMode::Stream) { + state->follow_latest = infer_stream_follow_state(*state, session); + } else { + state->follow_latest = false; + } + } + } + ImPlot::PopStyleVar(); + ImPlot::PopStyleColor(12); +} + +std::optional draw_pane_context_menu(const WorkspaceTab &tab, int pane_index) { + if (!ImGui::BeginPopupContextWindow("##pane_context")) return std::nullopt; + + PaneMenuAction action; + action.pane_index = pane_index; + const Pane *pane = pane_index >= 0 && pane_index < static_cast(tab.panes.size()) + ? &tab.panes[static_cast(pane_index)] + : nullptr; + const bool has_curves = pane_index >= 0 + && pane_index < static_cast(tab.panes.size()) + && !tab.panes[static_cast(pane_index)].curves.empty(); + const bool is_plot = pane != nullptr && pane->kind == PaneKind::Plot; + if (icon_menu_item(icon::SLIDERS, "Edit Axis Limits...", nullptr, false, is_plot)) { + action.kind = PaneMenuActionKind::OpenAxisLimits; + } + icon_menu_item(icon::PALETTE, "Edit Curve Style...", nullptr, false, false && is_plot); + if (action.kind == PaneMenuActionKind::None + && icon_menu_item(icon::PLUS_SLASH_MINUS, "Apply filter to data...", nullptr, false, has_curves && is_plot)) { + action.kind = PaneMenuActionKind::OpenCustomSeries; + } + ImGui::Separator(); + if (action.kind == PaneMenuActionKind::None && icon_menu_item(icon::DISTRIBUTE_HORIZONTAL, "Split Left / Right")) { + action.kind = PaneMenuActionKind::SplitRight; + } else if (action.kind == PaneMenuActionKind::None + && icon_menu_item(icon::DISTRIBUTE_VERTICAL, "Split Top / Bottom")) { + action.kind = PaneMenuActionKind::SplitBottom; + } + ImGui::Separator(); + if (icon_menu_item(icon::ZOOM_OUT, "Zoom Out", nullptr, false, is_plot)) { + action.kind = PaneMenuActionKind::ResetView; + } + ImGui::Separator(); + if (icon_menu_item(icon::TRASH, "Remove ALL curves", nullptr, false, is_plot)) { + action.kind = PaneMenuActionKind::Clear; + } + ImGui::Separator(); + icon_menu_item(icon::FILE_EARMARK_IMAGE, "Copy image to clipboard", nullptr, false, false); + icon_menu_item(icon::SAVE, "Save plot to file", nullptr, false, false); + icon_menu_item(icon::BAR_CHART, "Show data statistics", nullptr, false, false); + ImGui::EndPopup(); + if (action.kind == PaneMenuActionKind::None) return std::nullopt; + return action; +} diff --git a/tools/jotpluggler/render.cc b/tools/jotpluggler/render.cc new file mode 100644 index 00000000000000..54f0c16cc394b9 --- /dev/null +++ b/tools/jotpluggler/render.cc @@ -0,0 +1,173 @@ +#include "tools/jotpluggler/internal.h" + +#include "imgui_impl_glfw.h" +#include "imgui_impl_opengl3.h" +#include "imgui_impl_opengl3_loader.h" + +#include + +namespace fs = std::filesystem; + +void draw_fps_overlay(const UiState &state, float top_offset) { + if (!state.show_fps_overlay) { + return; + } + ImGuiViewport *viewport = ImGui::GetMainViewport(); + const ImGuiIO &io = ImGui::GetIO(); + const float fps = io.Framerate; + const std::string label = util::string_format("%.1f fps", fps); + + const ImVec2 padding(10.0f, 8.0f); + const ImVec2 margin(12.0f, 10.0f); + app_push_mono_font(); + ImFont *font = ImGui::GetFont(); + const float font_size = ImGui::GetFontSize(); + const ImVec2 text_size = ImGui::CalcTextSize(label.c_str()); + app_pop_mono_font(); + const ImVec2 size(text_size.x + padding.x * 2.0f, text_size.y + padding.y * 2.0f); + const ImVec2 pos(viewport->Pos.x + viewport->Size.x - size.x - margin.x, + viewport->Pos.y + top_offset + margin.y); + ImDrawList *draw_list = ImGui::GetForegroundDrawList(viewport); + const ImVec2 max(pos.x + size.x, pos.y + size.y); + draw_list->AddRectFilled(pos, max, ImGui::GetColorU32(color_rgb(248, 249, 251, 0.92f)), 4.0f); + draw_list->AddRect(pos, max, ImGui::GetColorU32(color_rgb(182, 188, 196, 0.95f)), 4.0f); + draw_list->AddText(font, font_size, ImVec2(pos.x + padding.x, pos.y + padding.y), + ImGui::GetColorU32(color_rgb(57, 62, 69)), label.c_str(), nullptr); +} + +void render_layout(AppSession *session, UiState *state, bool show_camera_feed) { + if (!state->fps_overlay_initialized) { + state->show_fps_overlay = false; + state->fps_overlay_initialized = true; + } + ensure_shared_range(state, *session); + if (state->follow_latest) { + update_follow_range(state, *session); + state->suppress_range_side_effects = true; + } else { + clamp_shared_range(state, *session); + } + const bool ctrl = ImGui::GetIO().KeyCtrl || ImGui::GetIO().KeySuper; + const bool shift = ImGui::GetIO().KeyShift; + if (!ImGui::GetIO().WantTextInput && ctrl && ImGui::IsKeyPressed(ImGuiKey_Z, false)) { + if (shift) { + apply_redo(session, state); + } else { + apply_undo(session, state); + } + } + if (!ImGui::GetIO().WantTextInput && ctrl && ImGui::IsKeyPressed(ImGuiKey_F, false)) { + state->open_find_signal = true; + } + if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow, false)) { + step_tracker(state, -1.0); + } + if (ImGui::IsKeyPressed(ImGuiKey_RightArrow, false)) { + step_tracker(state, 1.0); + } + if (!ImGui::GetIO().WantTextInput && ImGui::IsKeyPressed(ImGuiKey_Space, false)) { + state->playback_playing = !state->playback_playing; + } + advance_playback(state, *session); + CameraFeedView *sidebar_camera = session->pane_camera_feeds[static_cast(sidebar_preview_camera_view(*session))].get(); + if (show_camera_feed && sidebar_camera != nullptr && state->has_tracker_time) { + sidebar_camera->update(state->tracker_time); + } + const float menu_height = draw_main_menu_bar(session, state); + UiMetrics ui = compute_ui_metrics(ImGui::GetMainViewport()->Size, menu_height, state->sidebar_width); + if (state->browser_nodes_dirty) { + rebuild_browser_nodes(session, state); + state->browser_nodes_dirty = false; + } + state->sidebar_width = ui.sidebar_width; + draw_sidebar(session, ui, state, show_camera_feed); + draw_workspace(session, ui, state); + draw_sidebar_resizer(ui, state); + if (!state->custom_series.selected && !state->logs.selected) { + draw_pane_windows(session, state); + } + draw_status_bar(*session, ui, state); + draw_popups(session, state); + draw_fps_overlay(*state, menu_height); +} + +void save_framebuffer_png(const fs::path &output_path, int width, int height) { + ensure_parent_dir(output_path); + if (width <= 0 || height <= 0) throw std::runtime_error("Invalid framebuffer size"); + + std::vector pixels(static_cast(width) * static_cast(height) * 4U, 0); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()); + + const fs::path ppm_path = output_path.parent_path() / (output_path.stem().string() + ".ppm"); + std::string ppm = util::string_format("P6\n%d %d\n255\n", width, height); + ppm.reserve(ppm.size() + static_cast(width) * static_cast(height) * 3U); + for (int y = height - 1; y >= 0; --y) { + for (int x = 0; x < width; ++x) { + const size_t index = static_cast((y * width + x) * 4); + ppm.append(reinterpret_cast(&pixels[index]), 3); + } + } + write_file_or_throw(ppm_path, ppm.data(), ppm.size()); + + const std::string command = "convert " + shell_quote(ppm_path.string()) + " " + shell_quote(output_path.string()); + run_system_or_throw(command, "image conversion"); + fs::remove(ppm_path); +} + +void render_frame(GLFWwindow *window, AppSession *session, UiState *state, const fs::path *capture_path) { + glfwPollEvents(); + + int framebuffer_width = 0; + int framebuffer_height = 0; + glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height); + + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + + if (state->request_save_layout) { + if (session->layout_path.empty()) { + state->open_save_layout = true; + } else { + save_layout(session, state, session->layout_path.string()); + } + state->request_save_layout = false; + } + if (state->request_reset_layout) { + reset_layout(session, state); + state->request_reset_layout = false; + } + poll_async_route_load(session, state); + if (session->data_mode == SessionDataMode::Stream && session->stream_poller) { + StreamExtractBatch batch; + std::string error_text; + if (session->stream_poller->consume(&batch, &error_text)) { + if (!error_text.empty()) { + state->error_text = error_text; + state->open_error_popup = true; + state->status_text = "Stream disconnected"; + } else { + apply_stream_batch(session, state, std::move(batch)); + } + } + } + + const bool show_camera = capture_path == nullptr && session->data_mode != SessionDataMode::Stream; + render_layout(session, state, show_camera); + ImGui::Render(); + if (state->request_close) { + glfwSetWindowShouldClose(window, GLFW_TRUE); + state->request_close = false; + } + + glViewport(0, 0, framebuffer_width, framebuffer_height); + glClearColor(227.0f / 255.0f, 229.0f / 255.0f, 233.0f / 255.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + if (capture_path != nullptr) { + save_framebuffer_png(*capture_path, framebuffer_width, framebuffer_height); + } + glfwSwapBuffers(window); + state->suppress_range_side_effects = false; +} diff --git a/tools/jotpluggler/runtime.cc b/tools/jotpluggler/runtime.cc new file mode 100644 index 00000000000000..3247a5d01da8b4 --- /dev/null +++ b/tools/jotpluggler/runtime.cc @@ -0,0 +1,1277 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" + +#include "cereal/services.h" +#include "common/timing.h" +#include "imgui_impl_glfw.h" +#include "imgui_impl_opengl3.h" +#include "imgui_impl_opengl3_loader.h" +#include "implot.h" +#include "libyuv.h" +#include "msgq_repo/msgq/ipc.h" +#include "tools/replay/framereader.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "system/camerad/cameras/nv12_info.h" + +namespace { + +std::atomic g_glfw_alive{false}; +const bool kLogCameraTimings = env_flag_enabled("JOTP_CAMERA_TIMINGS"); + +CameraType decoder_camera_type(CameraViewKind view) { + switch (view) { + case CameraViewKind::Driver: return DriverCam; + case CameraViewKind::WideRoad: return WideRoadCam; + case CameraViewKind::QRoad: return RoadCam; + case CameraViewKind::Road: + default: return RoadCam; + } +} + +bool stream_batch_has_data(const StreamExtractBatch &batch) { + return !batch.series.empty() + || !batch.can_messages.empty() + || !batch.logs.empty() + || !batch.timeline.empty() + || !batch.enum_info.empty() + || !batch.car_fingerprint.empty() + || !batch.dbc_name.empty(); +} + +bool should_subscribe_stream_service(const std::string &name) { + static const std::array kSkippedServices = {{ + "roadEncodeIdx", + "driverEncodeIdx", + "wideRoadEncodeIdx", + "qRoadEncodeIdx", + "roadEncodeData", + "driverEncodeData", + "wideRoadEncodeData", + "qRoadEncodeData", + "livestreamWideRoadEncodeIdx", + "livestreamRoadEncodeIdx", + "livestreamDriverEncodeIdx", + "thumbnail", + }}; + if (name == "rawAudioData") return false; + for (std::string_view skipped : kSkippedServices) { + if (name == skipped) return false; + } + return true; +} + +void glfw_error_callback(int error, const char *description) { + const std::string_view desc = description != nullptr ? description : "unknown"; + if (error == 65539 && desc.find("Invalid window attribute 0x0002000D") != std::string_view::npos) { + return; + } + std::cerr << "GLFW error " << error << ": " << desc << "\n"; +} + +} // namespace + +GlfwRuntime::GlfwRuntime(const Options &options) { + glfwSetErrorCallback(glfw_error_callback); + if (!glfwInit()) throw std::runtime_error("glfwInit failed"); + g_glfw_alive.store(true); + + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); +#ifdef __APPLE__ + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); +#endif + const bool fixed_size = !options.show; + glfwWindowHint(GLFW_RESIZABLE, fixed_size ? GLFW_FALSE : GLFW_TRUE); + glfwWindowHint(GLFW_VISIBLE, options.show ? GLFW_TRUE : GLFW_FALSE); + + window_ = glfwCreateWindow(options.width, options.height, "jotpluggler", nullptr, nullptr); + if (window_ == nullptr) { + glfwTerminate(); + throw std::runtime_error("glfwCreateWindow failed"); + } + + if (fixed_size) { + glfwSetWindowSizeLimits(window_, options.width, options.height, options.width, options.height); + } + glfwMakeContextCurrent(window_); + glfwSwapInterval(options.show ? 1 : 0); +} + +GlfwRuntime::~GlfwRuntime() { + if (window_ != nullptr) { + glfwDestroyWindow(window_); + } + g_glfw_alive.store(false); + glfwTerminate(); +} + +GLFWwindow *GlfwRuntime::window() const { + return window_; +} + +ImGuiRuntime::ImGuiRuntime(GLFWwindow *window) { + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + + ImGuiIO &io = ImGui::GetIO(); + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + io.IniFilename = nullptr; + io.LogFilename = nullptr; + + if (!ImGui_ImplGlfw_InitForOpenGL(window, true)) { + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + throw std::runtime_error("ImGui_ImplGlfw_InitForOpenGL failed"); + } + if (!ImGui_ImplOpenGL3_Init("#version 330")) { + ImGui_ImplGlfw_Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + throw std::runtime_error("ImGui_ImplOpenGL3_Init failed"); + } +} + +ImGuiRuntime::~ImGuiRuntime() { + ImGui_ImplOpenGL3_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); +} + +struct TerminalRouteProgress::Impl { + explicit Impl(bool enabled) : enabled_(enabled) {} + + void update(const RouteLoadProgress &progress) { + std::lock_guard lock(mutex_); + if (!enabled_) { + return; + } + + double overall = 0.0; + std::string detail = "Resolving route"; + if (progress.stage == RouteLoadStage::Finished) { + overall = 1.0; + detail = "Ready"; + } else if (progress.total_segments > 0) { + const bool finalizing = progress.segments_downloaded >= progress.total_segments + && progress.segments_parsed >= progress.total_segments; + if (finalizing) { + overall = 0.99; + detail = "Finalizing route data"; + } else { + const double total_work = static_cast(progress.total_segments) * 2.0; + const double complete_work = static_cast(progress.segments_downloaded + progress.segments_parsed); + overall = total_work <= 0.0 ? 0.0 : std::clamp(complete_work / total_work, 0.0, 0.99); + std::ostringstream desc; + desc << "Downloaded " << progress.segments_downloaded << "/" << progress.total_segments + << " Parsed " << progress.segments_parsed << "/" << progress.total_segments; + detail = desc.str(); + } + } + + render(overall, detail); + } + + void finish() { + std::lock_guard lock(mutex_); + if (!enabled_ || !rendered_) { + return; + } + render(1.0, "Ready"); + std::fputc('\n', stderr); + std::fflush(stderr); + rendered_ = false; + } + + void render(double progress, const std::string &detail) { + const int percent = std::clamp(static_cast(std::round(progress * 100.0)), 0, 100); + if (percent == last_percent_ && detail == last_detail_) { + return; + } + + constexpr int kWidth = 20; + const int filled = std::clamp(static_cast(std::round(progress * kWidth)), 0, kWidth); + const std::string bar = std::string(static_cast(filled), '=') + std::string(static_cast(kWidth - filled), ' '); + std::ostringstream line; + line << "\r[" << bar << "] " << percent << "% " << detail; + + const std::string text = line.str(); + std::fprintf(stderr, "%s", text.c_str()); + if (text.size() < last_line_width_) { + std::fprintf(stderr, "%s", std::string(last_line_width_ - text.size(), ' ').c_str()); + } + std::fflush(stderr); + + rendered_ = true; + last_percent_ = percent; + last_detail_ = detail; + last_line_width_ = text.size(); + } + + bool enabled_ = false; + bool rendered_ = false; + int last_percent_ = -1; + size_t last_line_width_ = 0; + std::string last_detail_; + std::mutex mutex_; +}; + +TerminalRouteProgress::TerminalRouteProgress(bool enabled) + : impl_(std::make_unique(enabled)) {} + +TerminalRouteProgress::~TerminalRouteProgress() { + finish(); +} + +void TerminalRouteProgress::update(const RouteLoadProgress &progress) { + impl_->update(progress); +} + +void TerminalRouteProgress::finish() { + impl_->finish(); +} + +struct AsyncRouteLoader::Impl { + explicit Impl(bool enable_terminal_progress) + : terminal_progress(enable_terminal_progress) {} + + ~Impl() { + join(); + } + + void start(const std::string &route_name_value, const std::string &data_dir_value, const std::string &dbc_name_value) { + join(); + { + std::lock_guard lock(mutex); + route_name = route_name_value; + data_dir = data_dir_value; + dbc_name = dbc_name_value; + result.reset(); + error_text.clear(); + } + active.store(!route_name_value.empty()); + completed.store(route_name_value.empty()); + success.store(route_name_value.empty()); + total_segments.store(0); + segments_downloaded.store(0); + segments_parsed.store(0); + if (route_name_value.empty()) { + return; + } + + worker = std::thread([this]() { + try { + RouteData route_data = load_route_data(route_name, data_dir, dbc_name, [this](const RouteLoadProgress &progress) { + total_segments.store(progress.total_segments > 0 ? progress.total_segments : progress.segment_count); + segments_downloaded.store(progress.segments_downloaded); + segments_parsed.store(progress.segments_parsed); + terminal_progress.update(progress); + }); + { + std::lock_guard lock(mutex); + result = std::make_unique(std::move(route_data)); + error_text.clear(); + } + success.store(true); + } catch (const std::exception &err) { + std::lock_guard lock(mutex); + result.reset(); + error_text = err.what(); + success.store(false); + } + active.store(false); + completed.store(true); + terminal_progress.finish(); + }); + } + + RouteLoadSnapshot snapshot() const { + RouteLoadSnapshot snapshot; + snapshot.active = active.load(); + snapshot.total_segments = total_segments.load(); + snapshot.segments_downloaded = segments_downloaded.load(); + snapshot.segments_parsed = segments_parsed.load(); + return snapshot; + } + + bool consume(RouteData *route_data, std::string *error_text_out) { + if (!completed.load()) return false; + join(); + std::lock_guard lock(mutex); + completed.store(false); + if (result) { + *route_data = std::move(*result); + result.reset(); + if (error_text_out != nullptr) { + error_text_out->clear(); + } + return true; + } + if (error_text_out != nullptr) { + *error_text_out = error_text; + } + return true; + } + + void join() { + if (worker.joinable()) { + worker.join(); + } + } + + mutable std::mutex mutex; + std::thread worker; + std::unique_ptr result; + std::string route_name; + std::string data_dir; + std::string dbc_name; + std::string error_text; + std::atomic active{false}; + std::atomic completed{false}; + std::atomic success{false}; + std::atomic total_segments{0}; + std::atomic segments_downloaded{0}; + std::atomic segments_parsed{0}; + TerminalRouteProgress terminal_progress; +}; + +AsyncRouteLoader::AsyncRouteLoader(bool enable_terminal_progress) + : impl_(std::make_unique(enable_terminal_progress)) {} + +AsyncRouteLoader::~AsyncRouteLoader() = default; + +void AsyncRouteLoader::start(const std::string &route_name, const std::string &data_dir, const std::string &dbc_name) { + impl_->start(route_name, data_dir, dbc_name); +} + +RouteLoadSnapshot AsyncRouteLoader::snapshot() const { + return impl_->snapshot(); +} + +bool AsyncRouteLoader::consume(RouteData *route_data, std::string *error_text) { + return impl_->consume(route_data, error_text); +} + +struct StreamPoller::Impl { + ~Impl() { + stop(); + } + + void start(const StreamSourceConfig &requested_source, + double requested_buffer_seconds, + const std::string &dbc_name, + std::optional time_offset) { + stop(); + { + std::lock_guard lock(mutex); + pending = {}; + pending_series_slots.clear(); + pending_can_slots.clear(); + error_text.clear(); + source = requested_source; + if (source.kind == StreamSourceKind::CerealLocal) { + source.address = "127.0.0.1"; + } else if (source.kind == StreamSourceKind::CerealRemote) { + source.address = normalize_stream_address(source.address); + } + buffer_seconds = std::max(1.0, requested_buffer_seconds); + latest_dbc_name = dbc_name; + latest_car_fingerprint.clear(); + } + received_messages.store(0); + connected.store(false); + paused.store(false); + running.store(true); + worker = std::thread([this, dbc_name, time_offset]() { + try { + StreamAccumulator accumulator(dbc_name, time_offset); + switch (source.kind) { + case StreamSourceKind::CerealLocal: + case StreamSourceKind::CerealRemote: + run_cereal_source(&accumulator); + break; + } + } catch (const std::exception &err) { + std::lock_guard lock(mutex); + error_text = err.what(); + } + connected.store(false); + running.store(false); + }); + } + + void setPaused(bool paused_value) { + paused.store(paused_value); + if (paused_value) { + std::lock_guard lock(mutex); + pending = {}; + pending_series_slots.clear(); + pending_can_slots.clear(); + error_text.clear(); + } + } + + void set_error_text(std::string text) { + std::lock_guard lock(mutex); + error_text = std::move(text); + } + + void clear_error_text() { + std::lock_guard lock(mutex); + error_text.clear(); + } + + void stop() { + running.store(false); + paused.store(false); + if (worker.joinable()) { + worker.join(); + } + connected.store(false); + } + + StreamPollSnapshot snapshot() const { + StreamPollSnapshot out; + out.active = running.load(); + out.connected = connected.load(); + out.paused = paused.load(); + out.source_kind = source.kind; + out.source_label = stream_source_target_label(source); + out.buffer_seconds = buffer_seconds; + out.received_messages = received_messages.load(); + std::lock_guard lock(mutex); + out.dbc_name = latest_dbc_name; + out.car_fingerprint = latest_car_fingerprint; + return out; + } + + bool consume(StreamExtractBatch *batch, std::string *out_error_text) { + std::lock_guard lock(mutex); + const bool has_error = !error_text.empty(); + const bool has_batch = stream_batch_has_data(pending); + if (!has_error && !has_batch) return false; + if (batch != nullptr) { + *batch = std::move(pending); + pending = {}; + pending_series_slots.clear(); + pending_can_slots.clear(); + } + if (out_error_text != nullptr) { + *out_error_text = error_text; + error_text.clear(); + } + return true; + } + + static void merge_route_series(RouteSeries *dst, RouteSeries *src) { + if (src->times.empty()) { + return; + } + if (dst->path.empty()) { + dst->path = src->path; + } + dst->times.insert(dst->times.end(), src->times.begin(), src->times.end()); + dst->values.insert(dst->values.end(), src->values.begin(), src->values.end()); + } + + static void merge_can_message_data(CanMessageData *dst, CanMessageData *src) { + if (src->samples.empty()) { + return; + } + if (dst->samples.empty()) { + *dst = std::move(*src); + return; + } + dst->samples.insert(dst->samples.end(), + std::make_move_iterator(src->samples.begin()), + std::make_move_iterator(src->samples.end())); + } + + static void merge_batch(StreamExtractBatch *dst, + std::unordered_map *series_slots, + std::unordered_map *can_slots, + StreamExtractBatch *src) { + for (RouteSeries &series : src->series) { + auto [it, inserted] = series_slots->try_emplace(series.path, dst->series.size()); + if (inserted) { + dst->series.push_back(RouteSeries{.path = series.path}); + } + merge_route_series(&dst->series[it->second], &series); + } + for (CanMessageData &message : src->can_messages) { + auto [it, inserted] = can_slots->try_emplace(message.id, dst->can_messages.size()); + if (inserted) { + dst->can_messages.push_back(CanMessageData{.id = message.id}); + } + merge_can_message_data(&dst->can_messages[it->second], &message); + } + if (!src->logs.empty()) { + dst->logs.insert(dst->logs.end(), + std::make_move_iterator(src->logs.begin()), + std::make_move_iterator(src->logs.end())); + } + if (!src->timeline.empty()) { + dst->timeline.insert(dst->timeline.end(), + std::make_move_iterator(src->timeline.begin()), + std::make_move_iterator(src->timeline.end())); + } + for (auto &[path, info] : src->enum_info) { + dst->enum_info[path] = std::move(info); + } + if (!src->car_fingerprint.empty()) { + dst->car_fingerprint = src->car_fingerprint; + } + if (!src->dbc_name.empty()) { + dst->dbc_name = src->dbc_name; + } + } + + void publish_batch(StreamAccumulator *accumulator) { + StreamExtractBatch batch = accumulator->takeBatch(); + if (!stream_batch_has_data(batch)) { + return; + } + std::lock_guard lock(mutex); + merge_batch(&pending, &pending_series_slots, &pending_can_slots, &batch); + latest_dbc_name = pending.dbc_name; + latest_car_fingerprint = pending.car_fingerprint; + } + + void run_cereal_source(StreamAccumulator *accumulator) { + if (source.kind == StreamSourceKind::CerealRemote) { + setenv("ZMQ", "1", 1); + } else { + unsetenv("ZMQ"); + } + + std::unique_ptr context(Context::create()); + std::unique_ptr poller(Poller::create()); + std::vector> sockets; + sockets.reserve(services.size()); + for (const auto &[name, info] : services) { + if (!should_subscribe_stream_service(name)) continue; + std::unique_ptr socket( + SubSocket::create(context.get(), name.c_str(), source.address.c_str(), false, true, info.queue_size)); + if (socket == nullptr) continue; + socket->setTimeout(0); + poller->registerSocket(socket.get()); + sockets.push_back(std::move(socket)); + } + if (sockets.empty()) throw std::runtime_error("Failed to connect to any cereal service"); + connected.store(true); + + while (running.load()) { + std::vector ready = poller->poll(1); + for (SubSocket *socket : ready) { + while (running.load()) { + std::unique_ptr msg(socket->receive(true)); + if (!msg) break; + const size_t size = msg->getSize(); + if (size < sizeof(capnp::word) || (size % sizeof(capnp::word)) != 0) { + continue; + } + if (paused.load()) { + received_messages.fetch_add(1); + continue; + } + kj::ArrayPtr data(reinterpret_cast(msg->getData()), + size / sizeof(capnp::word)); + accumulator->appendEvent(data); + received_messages.fetch_add(1); + } + } + publish_batch(accumulator); + } + } + + mutable std::mutex mutex; + std::thread worker; + std::atomic running{false}; + std::atomic connected{false}; + std::atomic paused{false}; + std::atomic received_messages{0}; + StreamExtractBatch pending; + std::unordered_map pending_series_slots; + std::unordered_map pending_can_slots; + std::string error_text; + StreamSourceConfig source; + std::string latest_dbc_name; + std::string latest_car_fingerprint; + double buffer_seconds = 30.0; +}; + +StreamPoller::StreamPoller() + : impl_(std::make_unique()) {} + +StreamPoller::~StreamPoller() = default; + +void StreamPoller::start(const StreamSourceConfig &source, + double buffer_seconds, + const std::string &dbc_name, + std::optional time_offset) { + impl_->start(source, buffer_seconds, dbc_name, time_offset); +} + +void StreamPoller::setPaused(bool paused) { + impl_->setPaused(paused); +} + +void StreamPoller::stop() { + impl_->stop(); +} + +StreamPollSnapshot StreamPoller::snapshot() const { + return impl_->snapshot(); +} + +bool StreamPoller::consume(StreamExtractBatch *batch, std::string *error_text) { + return impl_->consume(batch, error_text); +} + +struct CameraFeedView::Impl { + struct RequestKey { + int segment = -1; + int decode_index = -1; + }; + + struct DecodeRequest { + RequestKey key; + std::string path; + uint64_t serial = 0; + uint64_t generation = 0; + }; + + struct PreloadTask { + int segment = -1; + std::string path; + uint64_t generation = 0; + }; + + struct DecodeResult { + RequestKey key; + bool success = false; + int width = 0; + int height = 0; + double decode_ms = 0.0; + std::vector rgba; + }; + + static constexpr float kDefaultAspect = 1208.0f / 1928.0f; + static constexpr size_t kCachedFrames = 8; + static constexpr int kPrefetchAhead = 2; + static constexpr int kImmediateNearbyFrameDistance = 8; + static constexpr int kPreloadWorkerCount = 2; + + Impl() { + demand_worker = std::thread([this]() { demand_worker_loop(); }); + for (int i = 0; i < kPreloadWorkerCount; ++i) { + preload_workers.emplace_back([this]() { preload_worker_loop(); }); + } + } + + ~Impl() { + stop.store(true); + cv.notify_all(); + if (demand_worker.joinable()) { + demand_worker.join(); + } + for (std::thread &worker : preload_workers) { + if (worker.joinable()) { + worker.join(); + } + } + destroy_texture(); + } + + void setRouteData(const RouteData &route_data) { + setCameraIndex(route_data.road_camera, CameraViewKind::Road); + } + + void setCameraIndex(const CameraFeedIndex &camera_index, CameraViewKind view) { + destroy_texture(); + { + std::lock_guard lock(mutex); + route_index = camera_index; + camera_view = view; + pending_request.reset(); + pending_result.reset(); + cached_results.clear(); + preload_queue.clear(); + preload_focus_segment = -1; + ++route_generation; + latest_request_serial = 0; + int initial_focus_segment = -1; + if (!route_index.entries.empty()) { + initial_focus_segment = route_index.entries.front().segment; + } else { + for (const CameraSegmentFile &segment_file : route_index.segment_files) { + if (!segment_file.path.empty()) { + initial_focus_segment = segment_file.segment; + break; + } + } + } + if (initial_focus_segment >= 0) { + rebuild_preload_queue_locked(initial_focus_segment); + } + } + abort_demand_work.store(true); + abort_preload_work.store(true); + active_request.reset(); + displayed_request.reset(); + failed_request.reset(); + frame_width = 0; + frame_height = 0; + cv.notify_all(); + } + + void update(double tracker_time) { + upload_pending_result(); + std::optional request = request_for_time(tracker_time); + if (!request.has_value()) { + return; + } + if (same_request(active_request, request->key) || same_request(displayed_request, request->key) || + same_request(failed_request, request->key)) { + return; + } + if (try_upload_cached_result(request->key)) { + return; + } + try_upload_nearby_cached_result(request->key); + + bool focus_changed = false; + { + std::lock_guard lock(mutex); + if (preload_focus_segment != request->key.segment) { + rebuild_preload_queue_locked(request->key.segment); + focus_changed = true; + } + request->serial = ++latest_request_serial; + request->generation = route_generation; + pending_request = request; + } + abort_demand_work.store(true); + if (focus_changed) { + abort_preload_work.store(true); + } + active_request = request->key; + failed_request.reset(); + cv.notify_all(); + } + + void draw(float width, bool loading) { + const float preview_width = std::max(1.0f, width); + const float preview_height = preview_width * preview_aspect(); + drawSized(ImVec2(preview_width, preview_height), loading, false); + ImGui::Spacing(); + } + + void drawSized(ImVec2 size, bool loading, bool fit_to_pane) { + size.x = std::max(1.0f, size.x); + size.y = std::max(1.0f, size.y); + const float aspect = preview_aspect(); + ImVec2 frame_size = size; + ImVec2 top_left = ImGui::GetCursorScreenPos(); + ImVec2 uv0(0.0f, 0.0f); + ImVec2 uv1(1.0f, 1.0f); + if (aspect > 0.0f && !fit_to_pane) { + frame_size.y = std::min(size.y, size.x * aspect); + frame_size.x = std::min(size.x, frame_size.y / aspect); + top_left = ImVec2(top_left.x + (size.x - frame_size.x) * 0.5f, + top_left.y + (size.y - frame_size.y) * 0.5f); + } else if (aspect > 0.0f && fit_to_pane) { + const float src_aspect = 1.0f / aspect; + const float dst_aspect = size.x / size.y; + if (dst_aspect > src_aspect) { + const float visible_v = std::clamp(src_aspect / dst_aspect, 0.0f, 1.0f); + const float v_pad = (1.0f - visible_v) * 0.5f; + uv0.y = v_pad; + uv1.y = 1.0f - v_pad; + } else if (dst_aspect < src_aspect) { + const float visible_u = std::clamp(dst_aspect / src_aspect, 0.0f, 1.0f); + const float u_pad = (1.0f - visible_u) * 0.5f; + uv0.x = u_pad; + uv1.x = 1.0f - u_pad; + } + } + ImGui::InvisibleButton("##camera_feed_sized", size); + if (texture != 0) { + ImGui::GetWindowDrawList()->AddImage(static_cast(texture), + top_left, + ImVec2(top_left.x + frame_size.x, top_left.y + frame_size.y), + uv0, + uv1); + } else { + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(top_left, ImVec2(top_left.x + frame_size.x, top_left.y + frame_size.y), IM_COL32(45, 47, 50, 255)); + draw_list->AddRect(top_left, ImVec2(top_left.x + frame_size.x, top_left.y + frame_size.y), IM_COL32(95, 100, 106, 255)); + + const char *label = (loading || has_video_source()) ? "loading" : "no video"; + const ImVec2 text_size = ImGui::CalcTextSize(label); + const ImVec2 text_pos(top_left.x + (frame_size.x - text_size.x) * 0.5f, + top_left.y + (frame_size.y - text_size.y) * 0.5f); + draw_list->AddText(text_pos, IM_COL32(187, 187, 187, 255), label); + } + } + + static bool same_request(const std::optional &lhs, const RequestKey &rhs) { + return lhs.has_value() && lhs->segment == rhs.segment && lhs->decode_index == rhs.decode_index; + } + + bool has_video_source() const { + std::lock_guard lock(mutex); + return !route_index.entries.empty() && !route_index.segment_files.empty(); + } + + float preview_aspect() const { + if (frame_width > 0 && frame_height > 0) return static_cast(frame_height) / static_cast(frame_width); + return kDefaultAspect; + } + + std::optional request_for_time(double tracker_time) const { + std::lock_guard lock(mutex); + if (route_index.entries.empty()) return std::nullopt; + + auto it = std::lower_bound(route_index.entries.begin(), route_index.entries.end(), tracker_time, + [](const CameraFrameIndexEntry &entry, double tm) { + return entry.timestamp < tm; + }); + if (it == route_index.entries.end()) { + it = std::prev(route_index.entries.end()); + } else if (it != route_index.entries.begin()) { + const auto prev = std::prev(it); + if (std::abs(prev->timestamp - tracker_time) <= std::abs(it->timestamp - tracker_time)) { + it = prev; + } + } + + auto path_it = std::find_if(route_index.segment_files.begin(), route_index.segment_files.end(), + [&](const CameraSegmentFile &segment) { + return segment.segment == it->segment && !segment.path.empty(); + }); + if (path_it == route_index.segment_files.end()) return std::nullopt; + + return DecodeRequest{ + .key = RequestKey{.segment = it->segment, .decode_index = it->decode_index}, + .path = path_it->path, + }; + } + + void upload_pending_result() { + std::optional result; + { + std::lock_guard lock(mutex); + if (!pending_result.has_value()) { + return; + } + result = std::move(pending_result); + pending_result.reset(); + } + + active_request.reset(); + if (!result->success || result->rgba.empty() || result->width <= 0 || result->height <= 0) { + failed_request = result->key; + return; + } + + upload_result(*result); + } + + void upload_result(const DecodeResult &result) { + remember_cached_result(result); + + const bool new_size = texture_width != result.width || texture_height != result.height; + if (texture == 0) { + glGenTextures(1, &texture); + } + glBindTexture(GL_TEXTURE_2D, texture); + if (new_size) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, result.width, result.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, result.rgba.data()); + texture_width = result.width; + texture_height = result.height; + } else { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, result.width, result.height, GL_RGBA, GL_UNSIGNED_BYTE, result.rgba.data()); + } + glBindTexture(GL_TEXTURE_2D, 0); + + frame_width = result.width; + frame_height = result.height; + displayed_request = result.key; + failed_request.reset(); + } + + bool try_upload_cached_result(const RequestKey &key) { + std::optional result; + { + std::lock_guard lock(mutex); + auto it = std::find_if(cached_results.begin(), cached_results.end(), [&](const DecodeResult &cached) { + return cached.key.segment == key.segment && cached.key.decode_index == key.decode_index; + }); + if (it == cached_results.end()) { + return false; + } + result = *it; + } + active_request.reset(); + upload_result(*result); + return true; + } + + bool try_upload_nearby_cached_result(const RequestKey &key) { + std::optional result; + int best_distance = std::numeric_limits::max(); + { + std::lock_guard lock(mutex); + for (const DecodeResult &cached : cached_results) { + if (cached.key.segment != key.segment) continue; + const int distance = std::abs(cached.key.decode_index - key.decode_index); + if (distance == 0 || distance > kImmediateNearbyFrameDistance || distance >= best_distance) continue; + best_distance = distance; + result = cached; + } + } + if (!result.has_value()) { + return false; + } + upload_result(*result); + return true; + } + + void remember_cached_result(const DecodeResult &result) { + std::lock_guard lock(mutex); + auto it = std::find_if(cached_results.begin(), cached_results.end(), [&](const DecodeResult &cached) { + return cached.key.segment == result.key.segment && cached.key.decode_index == result.key.decode_index; + }); + if (it != cached_results.end()) { + cached_results.erase(it); + } + cached_results.push_front(result); + while (cached_results.size() > kCachedFrames) { + cached_results.pop_back(); + } + } + + void destroy_texture() { + if (texture != 0 && g_glfw_alive.load() && glfwGetCurrentContext() != nullptr) { + glDeleteTextures(1, &texture); + } + texture = 0; + texture_width = 0; + texture_height = 0; + frame_width = 0; + frame_height = 0; + } + + static bool ensure_decode_buffer(FrameReader *reader, VisionBuf *buf, bool &allocated, int &w, int &h) { + if (!reader) return false; + if (allocated && w == reader->width && h == reader->height) return true; + if (allocated) { buf->free(); allocated = false; } + const auto [stride, y_height, _uv_height, size] = get_nv12_info(reader->width, reader->height); + buf->allocate(size); + buf->init_yuv(reader->width, reader->height, stride, stride * y_height); + w = reader->width; + h = reader->height; + allocated = true; + return true; + } + + void publish_result(const DecodeRequest &request, DecodeResult result) { + std::lock_guard lock(mutex); + if (!pending_request.has_value() || pending_request->serial != request.serial || + pending_request->generation != request.generation) { + return; + } + pending_result = std::move(result); + } + + bool has_newer_pending_request(uint64_t serial) const { + std::lock_guard lock(mutex); + return pending_request.has_value() && pending_request->serial != serial; + } + + void rebuild_preload_queue_locked(int focus_segment) { + std::vector ordered; + ordered.reserve(route_index.segment_files.size()); + for (const CameraSegmentFile &segment_file : route_index.segment_files) { + if (segment_file.path.empty()) continue; + if (segment_file.segment == focus_segment) continue; + ordered.push_back(PreloadTask{ + .segment = segment_file.segment, + .path = segment_file.path, + .generation = route_generation, + }); + } + std::sort(ordered.begin(), ordered.end(), [&](const PreloadTask &a, const PreloadTask &b) { + const int distance_a = std::abs(a.segment - focus_segment); + const int distance_b = std::abs(b.segment - focus_segment); + if (distance_a != distance_b) return distance_a < distance_b; + return a.segment < b.segment; + }); + preload_queue.assign(ordered.begin(), ordered.end()); + preload_focus_segment = focus_segment; + } + + std::shared_ptr find_loaded_reader_locked(int segment, uint64_t generation) { + if (readers_generation != generation) { + readers.clear(); + loading_segments.clear(); + readers_generation = generation; + } + auto it = readers.find(segment); + return it != readers.end() ? it->second : nullptr; + } + + std::shared_ptr ensure_reader_loaded(int segment, + const std::string &path, + uint64_t generation, + const char *reason, + std::atomic *abort_flag, + bool wait_for_inflight) { + while (!stop.load()) { + { + std::unique_lock lock(readers_mutex); + if (std::shared_ptr cached = find_loaded_reader_locked(segment, generation)) { + return cached; + } + if (loading_segments.find(segment) != loading_segments.end()) { + if (!wait_for_inflight) { + return nullptr; + } + readers_cv.wait(lock, [&]() { + return stop.load() + || readers_generation != generation + || loading_segments.find(segment) == loading_segments.end(); + }); + continue; + } + loading_segments.insert(segment); + } + + auto reader = std::make_shared(); + const auto load_begin = std::chrono::steady_clock::now(); + const bool loaded = reader->load(decoder_camera_type(camera_view), path, false, abort_flag, true); + + { + std::lock_guard lock(readers_mutex); + if (readers_generation != generation) { + readers.clear(); + loading_segments.clear(); + readers_generation = generation; + } + loading_segments.erase(segment); + if (loaded) { + readers[segment] = reader; + } + } + readers_cv.notify_all(); + + if (!loaded) { + return nullptr; + } + if (kLogCameraTimings) { + const double load_ms = std::chrono::duration(std::chrono::steady_clock::now() - load_begin).count(); + std::fprintf(stderr, "camera[%s] %s-load seg=%d %.1fms\n", + camera_view_spec(camera_view).runtime_name, reason, segment, load_ms); + } + return reader; + } + return nullptr; + } + + void preload_worker_loop() { + while (true) { + std::optional preload; + { + std::unique_lock lock(mutex); + cv.wait(lock, [&]() { return stop.load() || !preload_queue.empty(); }); + if (stop.load()) { + break; + } + preload = preload_queue.front(); + preload_queue.pop_front(); + } + + abort_preload_work.store(false); + { + std::lock_guard lock(readers_mutex); + if (find_loaded_reader_locked(preload->segment, preload->generation)) { + continue; + } + } + ensure_reader_loaded(preload->segment, preload->path, preload->generation, "preload", + &abort_preload_work, false); + } + } + + void demand_worker_loop() { + uint64_t handled_serial = 0; + VisionBuf decode_buffer; + bool buffer_allocated = false; + int buffer_width = 0; + int buffer_height = 0; + + while (true) { + std::optional request; + { + std::unique_lock lock(mutex); + cv.wait(lock, [&]() { + return stop.load() || (pending_request.has_value() && pending_request->serial != handled_serial); + }); + if (stop.load()) break; + request = *pending_request; + handled_serial = request->serial; + } + + abort_demand_work.store(false); + + DecodeResult result{.key = request->key}; + std::shared_ptr reader = ensure_reader_loaded(request->key.segment, request->path, + request->generation, "demand", + &abort_demand_work, true); + if (!reader) { + publish_result(*request, std::move(result)); + continue; + } + if (has_newer_pending_request(request->serial)) { + continue; + } + + const auto decode_begin = std::chrono::steady_clock::now(); + if (!ensure_decode_buffer(reader.get(), &decode_buffer, buffer_allocated, buffer_width, buffer_height) || + !reader->get(request->key.decode_index, &decode_buffer)) { + publish_result(*request, std::move(result)); + continue; + } + + result.width = reader->width; + result.height = reader->height; + result.rgba.resize(static_cast(result.width) * static_cast(result.height) * 4U, 0); + libyuv::NV12ToABGR(decode_buffer.y, + static_cast(decode_buffer.stride), + decode_buffer.uv, + static_cast(decode_buffer.stride), + result.rgba.data(), + result.width * 4, + result.width, + result.height); + result.success = true; + result.decode_ms = std::chrono::duration(std::chrono::steady_clock::now() - decode_begin).count(); + publish_result(*request, std::move(result)); + + for (int offset = 1; offset <= kPrefetchAhead; ++offset) { + if (stop.load() || has_newer_pending_request(request->serial)) { + break; + } + const int next_index = request->key.decode_index + offset; + if (next_index < 0 || next_index >= static_cast(reader->getFrameCount())) { + break; + } + if (!reader->get(next_index, &decode_buffer)) { + break; + } + DecodeResult prefetched{ + .key = RequestKey{.segment = request->key.segment, .decode_index = next_index}, + .success = true, + .width = reader->width, + .height = reader->height, + }; + prefetched.rgba.resize(static_cast(prefetched.width) * static_cast(prefetched.height) * 4U, 0); + libyuv::NV12ToABGR(decode_buffer.y, + static_cast(decode_buffer.stride), + decode_buffer.uv, + static_cast(decode_buffer.stride), + prefetched.rgba.data(), + prefetched.width * 4, + prefetched.width, + prefetched.height); + remember_cached_result(prefetched); + } + } + + if (buffer_allocated) { + decode_buffer.free(); + } + } + + mutable std::mutex mutex; + std::condition_variable cv; + std::thread demand_worker; + std::vector preload_workers; + std::atomic stop{false}; + std::atomic abort_demand_work{false}; + std::atomic abort_preload_work{false}; + CameraFeedIndex route_index; + CameraViewKind camera_view = CameraViewKind::Road; + std::optional pending_request; + std::optional pending_result; + std::deque preload_queue; + int preload_focus_segment = -1; + std::deque cached_results; + uint64_t latest_request_serial = 0; + uint64_t route_generation = 1; + std::optional active_request; + std::optional displayed_request; + std::optional failed_request; + std::mutex readers_mutex; + std::condition_variable readers_cv; + std::unordered_map> readers; + std::unordered_set loading_segments; + uint64_t readers_generation = 0; + GLuint texture = 0; + int texture_width = 0; + int texture_height = 0; + int frame_width = 0; + int frame_height = 0; +}; + +CameraFeedView::CameraFeedView() + : impl_(std::make_unique()) {} + +CameraFeedView::~CameraFeedView() = default; + +void CameraFeedView::setRouteData(const RouteData &route_data) { + impl_->setRouteData(route_data); +} + +void CameraFeedView::setCameraIndex(const CameraFeedIndex &camera_index, CameraViewKind view) { + impl_->setCameraIndex(camera_index, view); +} + +void CameraFeedView::update(double tracker_time) { + impl_->update(tracker_time); +} + +void CameraFeedView::draw(float width, bool loading) { + impl_->draw(width, loading); +} + +void CameraFeedView::drawSized(ImVec2 size, bool loading, bool fit_to_pane) { + impl_->drawSized(size, loading, fit_to_pane); +} diff --git a/tools/jotpluggler/session.cc b/tools/jotpluggler/session.cc new file mode 100644 index 00000000000000..beb0a292beb0bf --- /dev/null +++ b/tools/jotpluggler/session.cc @@ -0,0 +1,772 @@ +#include "tools/jotpluggler/internal.h" + +#include "imgui_internal.h" + +#include +#include +#include + +namespace fs = std::filesystem; + +const RouteSeries *app_find_route_series(const AppSession &session, const std::string &path) { + auto it = session.series_by_path.find(path); + return it == session.series_by_path.end() ? nullptr : it->second; +} + +void sync_camera_feeds(AppSession *session) { + for (size_t i = 0; i < kCameraViewSpecs.size(); ++i) { + if (session->pane_camera_feeds[i]) { + session->pane_camera_feeds[i]->setCameraIndex(session->route_data.*(kCameraViewSpecs[i].route_member), kCameraViewSpecs[i].view); + } + } +} + +void apply_route_data(AppSession *session, UiState *state, RouteData route_data) { + if (!route_data.route_id.empty()) { + session->route_id = route_data.route_id; + } else if (session->route_name.empty() && session->data_mode == SessionDataMode::Route) { + session->route_id = {}; + } + session->route_data = std::move(route_data); + rebuild_route_index(session); + rebuild_browser_nodes(session, state); + state->browser_nodes_dirty = false; + refresh_all_custom_curves(session, state); + sync_camera_feeds(session); + state->has_shared_range = false; + state->has_tracker_time = false; + reset_shared_range(state, *session); +} + +bool restore_undo_layout(AppSession *session, UiState *state, const SketchLayout &layout, const char *status_text) { + session->layout = layout; + cancel_rename_tab(state); + state->custom_series.request_select = false; + state->active_tab_index = std::clamp(layout.current_tab_index, 0, std::max(0, static_cast(layout.tabs.size()) - 1)); + state->requested_tab_index = state->active_tab_index; + sync_ui_state(state, session->layout); + mark_all_docks_dirty(state); + const bool autosave_ok = autosave_layout(session, state); + if (autosave_ok) { + state->status_text = status_text; + } + return autosave_ok; +} + +bool apply_undo(AppSession *session, UiState *state) { + if (!state->undo.can_undo()) { + return false; + } + return restore_undo_layout(session, state, state->undo.undo(), "Undo"); +} + +bool apply_redo(AppSession *session, UiState *state) { + if (!state->undo.can_redo()) { + return false; + } + return restore_undo_layout(session, state, state->undo.redo(), "Redo"); +} + +std::optional> tab_default_x_range(const WorkspaceTab &tab) { + bool found = false; + double min_value = 0.0; + double max_value = 1.0; + for (const Pane &pane : tab.panes) { + if (!pane.range.valid || pane.range.right <= pane.range.left) continue; + if (!found) { + min_value = pane.range.left; + max_value = pane.range.right; + found = true; + } else { + min_value = std::min(min_value, pane.range.left); + max_value = std::max(max_value, pane.range.right); + } + } + if (!found) return std::nullopt; + return std::make_pair(min_value, max_value); +} + +bool infer_stream_follow_state(const UiState &state, const AppSession &session) { + if (session.data_mode != SessionDataMode::Stream || !state.has_shared_range || !session.route_data.has_time_range) { + return false; + } + const double target_span = std::max(MIN_HORIZONTAL_ZOOM_SECONDS, session.stream_buffer_seconds); + const double current_span = std::max(0.0, state.x_view_max - state.x_view_min); + const double edge_epsilon = std::max(0.05, target_span * 0.02); + return std::abs(state.x_view_max - state.route_x_max) <= edge_epsilon + && std::abs(current_span - target_span) <= edge_epsilon; +} + +void ensure_shared_range(UiState *state, const AppSession &session) { + if (session.route_data.has_time_range) { + state->route_x_min = session.route_data.x_min; + state->route_x_max = session.route_data.x_max; + } else { + state->route_x_min = 0.0; + state->route_x_max = 1.0; + } + + if (state->has_shared_range) { + return; + } + + if (session.data_mode == SessionDataMode::Stream) { + const double target_span = std::max(MIN_HORIZONTAL_ZOOM_SECONDS, session.stream_buffer_seconds); + if (session.route_data.has_time_range) { + state->x_view_max = state->route_x_max; + state->x_view_min = state->x_view_max - target_span; + } else { + state->x_view_min = 0.0; + state->x_view_max = target_span; + } + if (state->x_view_max <= state->x_view_min) { + state->x_view_max = state->x_view_min + 1.0; + } + state->has_shared_range = true; + if (!state->has_tracker_time || state->tracker_time < state->route_x_min || state->tracker_time > state->route_x_max) { + state->tracker_time = state->route_x_max; + state->has_tracker_time = session.route_data.has_time_range; + } + return; + } + + if (const WorkspaceTab *tab = app_active_tab(session.layout, *state); tab != nullptr) { + if (std::optional> tab_range = tab_default_x_range(*tab); tab_range.has_value()) { + state->x_view_min = tab_range->first; + state->x_view_max = tab_range->second; + state->has_shared_range = true; + if (!state->has_tracker_time || state->tracker_time < state->route_x_min || state->tracker_time > state->route_x_max) { + state->tracker_time = state->route_x_min; + state->has_tracker_time = true; + } + return; + } + } + + state->x_view_min = state->route_x_min; + state->x_view_max = state->route_x_max; + if (state->x_view_max <= state->x_view_min) { + state->x_view_max = state->x_view_min + 1.0; + } + state->has_shared_range = true; + if (!state->has_tracker_time || state->tracker_time < state->route_x_min || state->tracker_time > state->route_x_max) { + state->tracker_time = state->route_x_min; + state->has_tracker_time = true; + } +} + +void clamp_shared_range(UiState *state, const AppSession &session) { + if (!state->has_shared_range) { + return; + } + const double min_span = MIN_HORIZONTAL_ZOOM_SECONDS; + double span = state->x_view_max - state->x_view_min; + if (span < min_span) { + const double center = 0.5 * (state->x_view_min + state->x_view_max); + span = min_span; + state->x_view_min = center - span * 0.5; + state->x_view_max = center + span * 0.5; + } + if (session.data_mode == SessionDataMode::Stream) { + if (session.route_data.has_time_range && state->x_view_max > state->route_x_max) { + state->x_view_min -= state->x_view_max - state->route_x_max; + state->x_view_max = state->route_x_max; + } + if (state->x_view_max <= state->x_view_min) { + state->x_view_max = state->x_view_min + min_span; + } + if (state->has_tracker_time && session.route_data.has_time_range) { + state->tracker_time = std::clamp(state->tracker_time, state->route_x_min, state->route_x_max); + } + if (session.route_data.has_time_range) { + state->follow_latest = infer_stream_follow_state(*state, session); + } + return; + } + if (state->route_x_max > state->route_x_min) { + if (state->x_view_min < state->route_x_min) { + state->x_view_max += state->route_x_min - state->x_view_min; + state->x_view_min = state->route_x_min; + } + if (state->x_view_max > state->route_x_max) { + state->x_view_min -= state->x_view_max - state->route_x_max; + state->x_view_max = state->route_x_max; + } + if (state->x_view_min < state->route_x_min) { + state->x_view_min = state->route_x_min; + } + if (state->x_view_max <= state->x_view_min) { + state->x_view_max = std::min(state->route_x_max, state->x_view_min + min_span); + } + } + if (state->has_tracker_time) { + state->tracker_time = std::clamp(state->tracker_time, state->route_x_min, state->route_x_max); + } +} + +void reset_shared_range(UiState *state, const AppSession &session) { + state->has_shared_range = false; + ensure_shared_range(state, session); + clamp_shared_range(state, session); +} + +void update_follow_range(UiState *state, const AppSession &session) { + if (!state->follow_latest || !state->has_shared_range) { + return; + } + const double span = session.data_mode == SessionDataMode::Stream + ? std::max(MIN_HORIZONTAL_ZOOM_SECONDS, session.stream_buffer_seconds) + : std::max(MIN_HORIZONTAL_ZOOM_SECONDS, state->x_view_max - state->x_view_min); + const double route_span = state->route_x_max - state->route_x_min; + if (route_span <= 0.0) { + return; + } + state->x_view_max = state->route_x_max; + state->x_view_min = state->x_view_max - span; + clamp_shared_range(state, session); +} + +void advance_playback(UiState *state, const AppSession &session) { + if (!state->playback_playing || !state->has_shared_range || state->route_x_max <= state->route_x_min) { + return; + } + + const double delta = std::max(0.0, static_cast(ImGui::GetIO().DeltaTime)) * state->playback_rate; + const double view_span = std::max(MIN_HORIZONTAL_ZOOM_SECONDS, state->x_view_max - state->x_view_min); + const double loop_min = state->playback_loop + ? std::clamp(state->x_view_min, state->route_x_min, state->route_x_max) + : state->route_x_min; + const double loop_max = state->playback_loop + ? std::clamp(state->x_view_max, state->route_x_min, state->route_x_max) + : state->route_x_max; + + state->tracker_time += delta; + if (state->tracker_time >= loop_max) { + if (state->playback_loop) { + state->tracker_time = loop_min; + } else { + state->tracker_time = state->route_x_max; + state->playback_playing = false; + } + } + + if (!state->playback_loop) { + constexpr double kScrollStartFraction = 0.70; + const double scroll_anchor = state->x_view_min + view_span * kScrollStartFraction; + if (state->tracker_time > scroll_anchor && state->x_view_max < state->route_x_max) { + state->x_view_min = state->tracker_time - view_span * kScrollStartFraction; + state->x_view_max = state->x_view_min + view_span; + clamp_shared_range(state, session); + } else if (state->tracker_time < state->x_view_min || state->tracker_time > state->x_view_max) { + state->x_view_min = state->tracker_time - view_span * 0.5; + state->x_view_max = state->x_view_min + view_span; + clamp_shared_range(state, session); + } + } +} + +void step_tracker(UiState *state, double direction) { + if (!state->has_shared_range) { + return; + } + state->tracker_time += direction * std::max(0.001, state->playback_step); + state->tracker_time = std::clamp(state->tracker_time, state->route_x_min, state->route_x_max); +} + +const char *log_selector_name(LogSelector selector) { + static constexpr const char *kLabels[] = {"a", "r", "q"}; + const size_t index = static_cast(selector); + return index < std::size(kLabels) ? kLabels[index] : kLabels[0]; +} + +const char *log_selector_description(LogSelector selector) { + static constexpr const char *kLabels[] = { + "any of rlog or qlog", + "rlog only", + "qlog only", + }; + const size_t index = static_cast(selector); + return index < std::size(kLabels) ? kLabels[index] : kLabels[0]; +} + +std::string shorten_route_part(std::string_view text, size_t keep) { + if (text.size() <= keep) { + return std::string(text); + } + return std::string(text.substr(0, keep)); +} + +bool parse_slice_spec(std::string_view text, int *begin, int *end) { + const auto parse_nonnegative = [](std::string_view value, int *out) { + if (value.empty()) return false; + char *end_ptr = nullptr; + const long parsed = std::strtol(std::string(value).c_str(), &end_ptr, 10); + if (end_ptr == nullptr || *end_ptr != '\0' || parsed < 0) { + return false; + } + *out = static_cast(parsed); + return true; + }; + const std::string trimmed = util::strip(std::string(text)); + if (trimmed.empty()) { + return false; + } + const size_t colon = trimmed.find(':'); + int parsed_begin = 0; + if (!parse_nonnegative(trimmed.substr(0, colon), &parsed_begin)) { + return false; + } + int parsed_end = parsed_begin; + if (colon != std::string::npos) { + const std::string end_text = trimmed.substr(colon + 1); + if (end_text.empty()) { + parsed_end = -1; + } else if (!parse_nonnegative(end_text, &parsed_end) || parsed_end < parsed_begin) { + return false; + } + } + *begin = parsed_begin; + *end = parsed_end; + return true; +} + +std::string format_duration_short(double seconds) { + const double clamped = std::max(0.0, seconds); + const int total_ms = static_cast(std::round(clamped * 1000.0)); + const int minutes = total_ms / 60000; + const int rem_ms = total_ms % 60000; + const int secs = rem_ms / 1000; + const int millis = rem_ms % 1000; + return util::string_format("%d:%02d.%03d", minutes, secs, millis); +} + +bool apply_route_identifier(AppSession *session, UiState *state, const RouteIdentifier &route_id, const char *status_text) { + if (route_id.empty()) { + return false; + } + if (!reload_session(session, state, route_id.full_spec(), session->data_dir)) { + return false; + } + state->status_text = status_text; + return true; +} + +bool apply_route_slice_change(AppSession *session, UiState *state, std::string_view slice_text) { + int begin = 0; + int end = 0; + if (!parse_slice_spec(slice_text, &begin, &end)) { + state->error_text = "Slice must be N, N:, or N:M."; + state->open_error_popup = true; + return false; + } + RouteIdentifier next = session->route_id; + next.slice_begin = begin; + next.slice_end = end; + next.slice_explicit = true; + return apply_route_identifier(session, state, next, "Updated route slice"); +} + +bool apply_route_selector_change(AppSession *session, UiState *state, LogSelector selector) { + RouteIdentifier next = session->route_id; + next.selector = selector; + next.selector_explicit = true; + return apply_route_identifier(session, state, next, "Updated log selector"); +} + +ImU32 route_chip_part_color(int part_index, bool explicit_part) { + constexpr std::array, 4> BASE = {{ + {70, 96, 126}, // dongle + {100, 86, 148}, // log id + {72, 112, 86}, // slice + {156, 104, 38}, // selector + }}; + const std::array &base = BASE[static_cast(std::clamp(part_index, 0, 3))]; + if (explicit_part) { + return ImGui::GetColorU32(color_rgb(base[0], base[1], base[2])); + } + const int gray = 144; + return ImGui::GetColorU32(color_rgb((base[0] + gray) / 2, (base[1] + gray) / 2, (base[2] + gray) / 2)); +} + +bool draw_route_chip_text_button(const char *id, + std::string_view text, + ImVec2 pos, + ImU32 color, + ImDrawList *draw_list, + const char *tooltip = nullptr) { + const ImVec2 size = ImGui::CalcTextSize(text.data(), text.data() + text.size()); + ImGui::SetCursorScreenPos(pos); + ImGui::InvisibleButton(id, size); + const bool hovered = ImGui::IsItemHovered(); + if (hovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + draw_list->AddRectFilled(ImVec2(pos.x - 5.0f, pos.y - 1.0f), + ImVec2(pos.x + size.x + 5.0f, pos.y + size.y + 2.0f), + ImGui::GetColorU32(color_rgb(225, 231, 239, 0.95f)), 0.0f); + } + draw_list->AddText(pos, color, text.data(), text.data() + text.size()); + if (tooltip != nullptr && ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(tooltip); + ImGui::EndTooltip(); + } + return ImGui::IsItemClicked(ImGuiMouseButton_Left); +} + +void draw_route_copy_feedback(UiState *state, ImDrawList *draw_list, ImVec2 chip_max) { + if (state->route_copy_feedback_text.empty()) { + return; + } + const double now = ImGui::GetTime(); + if (now >= state->route_copy_feedback_until) { + state->route_copy_feedback_text.clear(); + state->route_copy_feedback_until = 0.0; + return; + } + + const float alpha = static_cast(std::clamp((state->route_copy_feedback_until - now) / 1.1, 0.0, 1.0)); + const ImVec2 text_size = ImGui::CalcTextSize(state->route_copy_feedback_text.c_str()); + const ImVec2 pad(9.0f, 5.0f); + const ImVec2 bubble_min(chip_max.x - text_size.x - pad.x * 2.0f, chip_max.y + 7.0f); + const ImVec2 bubble_max(chip_max.x, bubble_min.y + text_size.y + pad.y * 2.0f); + draw_list->AddRectFilled(bubble_min, bubble_max, + ImGui::GetColorU32(color_rgb(46, 125, 80, 0.96f * alpha)), 7.0f); + draw_list->AddRect(bubble_min, bubble_max, + ImGui::GetColorU32(color_rgb(35, 96, 61, 0.9f * alpha)), 7.0f, 0, 1.0f); + draw_list->AddText(ImVec2(std::floor(bubble_min.x + pad.x), std::floor(bubble_min.y + pad.y)), + ImGui::GetColorU32(color_rgb(247, 251, 248, alpha)), + state->route_copy_feedback_text.c_str()); +} + +void draw_route_info_popup(AppSession *session, UiState *state, ImVec2 anchor) { + if (session->route_id.empty()) { + return; + } + ImGui::SetNextWindowPos(anchor, ImGuiCond_Appearing); + ImGui::SetNextWindowSizeConstraints(ImVec2(300.0f, 0.0f), ImVec2(420.0f, FLT_MAX)); + if (!app_begin_popup("##route_info_popup", ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings)) { + return; + } + + ImGui::TextUnformatted("Route Info"); + ImGui::Separator(); + app_push_mono_font(); + ImGui::TextUnformatted(session->route_id.canonical().c_str()); + app_pop_mono_font(); + + const char *copy_icon = icon::CLIPBOARD; + const char *link_icon = icon::BOX_ARROW_UP_RIGHT; + const std::string useradmin_label = std::string("Useradmin ") + link_icon; + const std::string connect_label = std::string("comma connect ") + link_icon; + if (ImGui::Button(copy_icon, ImVec2(34.0f, 26.0f))) { + ImGui::SetClipboardText(session->route_id.canonical().c_str()); + state->status_text = "Copied route to clipboard"; + state->route_copy_feedback_text = "Copied"; + state->route_copy_feedback_until = ImGui::GetTime() + 1.1; + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted("Copy route"); + ImGui::EndTooltip(); + } + ImGui::SameLine(); + if (ImGui::Button(useradmin_label.c_str(), ImVec2(132.0f, 26.0f))) { + open_external_url(route_useradmin_url(session->route_id)); + state->status_text = "Opened useradmin"; + } + ImGui::SameLine(); + if (ImGui::Button(connect_label.c_str(), ImVec2(156.0f, 26.0f))) { + open_external_url(route_connect_url(session->route_id)); + state->status_text = "Opened comma connect"; + } + + ImGui::Spacing(); + const int loaded_begin = session->route_id.available_begin; + const int loaded_end = session->route_id.available_end; + const int loaded_count = loaded_end >= loaded_begin ? (loaded_end - loaded_begin + 1) : 0; + ImGui::Text("Duration %s", format_duration_short(session->route_data.x_max - session->route_data.x_min).c_str()); + ImGui::Text("Segments %s (%d)", session->route_id.display_slice().c_str(), loaded_count); + ImGui::Text("Selector %s", log_selector_description(session->route_id.selector)); + if (!session->route_data.car_fingerprint.empty()) { + ImGui::TextWrapped("Car %s", session->route_data.car_fingerprint.c_str()); + } + if (!session->route_data.dbc_name.empty()) { + ImGui::TextWrapped("DBC %s", session->route_data.dbc_name.c_str()); + } + + ImGui::EndPopup(); +} + +void draw_route_id_chip(AppSession *session, UiState *state) { + if (session->data_mode != SessionDataMode::Route || session->route_id.empty()) { + return; + } + + ImGuiWindow *window = ImGui::GetCurrentWindow(); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + const RouteIdentifier &route_id = session->route_id; + app_push_bold_font(); + const std::string dongle_text = shorten_route_part(route_id.dongle_id, 8); + const std::string log_text = shorten_route_part(route_id.log_id, 16); + const std::string slice_text = route_id.display_slice(); + const std::string selector_text(1, route_id.selector_char()); + const std::string sep_text = " / "; + + const ImVec2 dongle_size = ImGui::CalcTextSize(dongle_text.c_str()); + const ImVec2 log_size = ImGui::CalcTextSize(log_text.c_str()); + const ImVec2 slice_size = state->editing_route_slice + ? ImVec2(68.0f, ImGui::GetFrameHeight()) + : ImGui::CalcTextSize(slice_text.c_str()); + const ImVec2 selector_size = ImGui::CalcTextSize(selector_text.c_str()); + const ImVec2 sep_size = ImGui::CalcTextSize(sep_text.c_str()); + constexpr float chip_pad_x = 12.0f; + constexpr float info_size = 18.0f; + const float chip_h = 28.0f; + const float chip_w = chip_pad_x * 2.0f + dongle_size.x + sep_size.x + log_size.x + sep_size.x + + slice_size.x + sep_size.x + selector_size.x + 10.0f + info_size; + const float menu_right = window->Pos.x + window->Size.x - 8.0f; + const float cursor_x = ImGui::GetCursorScreenPos().x + 4.0f; + const float chip_x = std::clamp(cursor_x, window->Pos.x + 48.0f, std::max(window->Pos.x + 48.0f, menu_right - chip_w)); + const float chip_y = std::floor(window->Pos.y + std::max(0.0f, (window->Size.y - chip_h) * 0.5f)); + const ImVec2 chip_min(chip_x, chip_y); + const ImVec2 chip_max(chip_x + chip_w, chip_y + chip_h); + const float text_y = std::floor(chip_y + std::max(0.0f, (chip_h - ImGui::GetTextLineHeight()) * 0.5f)); + const ImU32 chip_bg = ImGui::GetColorU32(color_rgb(247, 249, 252)); + const ImU32 chip_border = ImGui::GetColorU32(color_rgb(184, 191, 200)); + const ImU32 sep = ImGui::GetColorU32(color_rgb(162, 170, 178)); + draw_list->AddRectFilled(chip_min, chip_max, chip_bg, 0.0f); + draw_list->AddRect(chip_min, chip_max, chip_border, 0.0f, 0, 1.0f); + + float x = chip_x + chip_pad_x; + const bool dongle_click = draw_route_chip_text_button( + "##route_dongle", dongle_text, ImVec2(x, text_y), route_chip_part_color(0, true), draw_list, + "Device identifier"); + x += dongle_size.x; + draw_list->AddText(ImVec2(x, text_y), sep, sep_text.c_str()); + x += sep_size.x; + const bool log_click = draw_route_chip_text_button( + "##route_log", log_text, ImVec2(x, text_y), route_chip_part_color(1, true), draw_list, + "Route identifier"); + x += log_size.x; + draw_list->AddText(ImVec2(x, text_y), sep, sep_text.c_str()); + x += sep_size.x; + + if (state->editing_route_slice) { + ImGui::SetCursorScreenPos(ImVec2(x - 4.0f, chip_y + 1.0f)); + ImGui::SetNextItemWidth(76.0f); + if (state->focus_route_slice_input) { + ImGui::SetKeyboardFocusHere(); + state->focus_route_slice_input = false; + } + const bool applied = input_text_string("##route_slice_edit", &state->route_slice_buffer, + ImGuiInputTextFlags_EnterReturnsTrue); + const bool deactivated = ImGui::IsItemDeactivated(); + const bool clicked_elsewhere = ImGui::IsMouseClicked(ImGuiMouseButton_Left) + && !ImGui::IsItemHovered() + && !ImGui::IsItemActive(); + if (applied) { + if (apply_route_slice_change(session, state, state->route_slice_buffer)) { + state->editing_route_slice = false; + } + } else if (ImGui::IsKeyPressed(ImGuiKey_Escape)) { + state->editing_route_slice = false; + } else if (deactivated || clicked_elsewhere) { + const std::string trimmed = util::strip(state->route_slice_buffer); + if (trimmed != route_id.display_slice()) { + int begin = 0; + int end = 0; + if (parse_slice_spec(trimmed, &begin, &end)) { + apply_route_slice_change(session, state, trimmed); + } else { + state->status_text = "Canceled route slice edit"; + } + } + state->editing_route_slice = false; + } + x += slice_size.x; + } else { + const bool slice_click = draw_route_chip_text_button( + "##route_slice", slice_text, ImVec2(x, text_y), + route_chip_part_color(2, route_id.slice_explicit), draw_list, + "Segment range"); + if (slice_click) { + state->editing_route_slice = true; + state->focus_route_slice_input = true; + state->route_slice_buffer = route_id.display_slice(); + } + x += slice_size.x; + } + + draw_list->AddText(ImVec2(x, text_y), sep, sep_text.c_str()); + x += sep_size.x; + const bool selector_click = draw_route_chip_text_button( + "##route_selector", selector_text, ImVec2(x, text_y), + route_chip_part_color(3, route_id.selector_explicit), draw_list, + "Log selector"); + if (selector_click) { + ImGui::OpenPopup("##route_selector_popup"); + } + x += selector_size.x + 10.0f; + + const ImVec2 info_center(x + info_size * 0.5f, chip_y + chip_h * 0.5f); + ImGui::SetCursorScreenPos(ImVec2(x, chip_y + (chip_h - info_size) * 0.5f)); + ImGui::InvisibleButton("##route_info_button", ImVec2(info_size, info_size)); + const bool info_hovered = ImGui::IsItemHovered(); + if (info_hovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + draw_list->AddCircleFilled(info_center, info_size * 0.5f, + ImGui::GetColorU32(info_hovered ? color_rgb(220, 229, 240) : color_rgb(239, 243, 248))); + draw_list->AddCircle(info_center, info_size * 0.5f, chip_border, 20, 1.0f); + const char *info_text = icon::INFO_CIRCLE; + const ImVec2 info_text_size = ImGui::CalcTextSize(info_text); + draw_list->AddText(ImVec2(std::floor(info_center.x - info_text_size.x * 0.5f), + std::floor(info_center.y - info_text_size.y * 0.5f)), + route_chip_part_color(0, true), info_text); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted("Route details"); + ImGui::EndTooltip(); + } + if (ImGui::IsItemClicked(ImGuiMouseButton_Left)) { + ImGui::OpenPopup("##route_info_popup"); + } + + app_pop_bold_font(); + + if (dongle_click || log_click) { + ImGui::SetClipboardText(route_id.canonical().c_str()); + state->status_text = "Copied route to clipboard"; + state->route_copy_feedback_text = "Copied"; + state->route_copy_feedback_until = ImGui::GetTime() + 1.1; + } + + ImGui::SetNextWindowPos(ImVec2(chip_max.x - 60.0f, chip_max.y + 4.0f), ImGuiCond_Appearing); + if (app_begin_popup("##route_selector_popup")) { + for (LogSelector selector : {LogSelector::Auto, LogSelector::RLog, LogSelector::QLog}) { + const bool selected = route_id.selector == selector; + const std::string label = std::string(log_selector_name(selector)) + " " + log_selector_description(selector); + if (ImGui::Selectable(label.c_str(), selected) && !selected) { + apply_route_selector_change(session, state, selector); + } + if (selected) { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndPopup(); + } + + draw_route_copy_feedback(state, draw_list, chip_max); + draw_route_info_popup(session, state, ImVec2(std::max(window->Pos.x + 16.0f, chip_max.x - 360.0f), chip_max.y + 6.0f)); +} + +std::string format_cache_bytes(uint64_t bytes) { + if (bytes >= (1ULL << 30)) { + return util::string_format("%.1f GiB", static_cast(bytes) / static_cast(1ULL << 30)); + } else if (bytes >= (1ULL << 20)) { + return util::string_format("%.1f MiB", static_cast(bytes) / static_cast(1ULL << 20)); + } else if (bytes >= (1ULL << 10)) { + return util::string_format("%.1f KiB", static_cast(bytes) / static_cast(1ULL << 10)); + } + return util::string_format("%llu B", static_cast(bytes)); +} + +MapCacheStats directory_cache_stats(const fs::path &root) { + MapCacheStats stats; + std::error_code ec; + if (!fs::exists(root, ec)) { + return stats; + } + fs::recursive_directory_iterator it(root, fs::directory_options::skip_permission_denied, ec); + for (const fs::directory_entry &entry : it) { + if (ec) { + ec.clear(); + continue; + } + const fs::file_status status = entry.symlink_status(ec); + if (ec || !fs::is_regular_file(status)) { + ec.clear(); + continue; + } + const uintmax_t size = entry.file_size(ec); + if (!ec) { + stats.bytes += static_cast(size); + ++stats.files; + } else { + ec.clear(); + } + } + return stats; +} + +float draw_main_menu_bar(AppSession *session, UiState *state) { + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(7.0f, 5.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(9.0f, 6.0f)); + float height = ImGui::GetFrameHeight(); + if (ImGui::BeginMainMenuBar()) { + if (ImGui::BeginMenu("File")) { + if (ImGui::MenuItem("Undo", "Ctrl+Z", false, state->undo.can_undo())) { + apply_undo(session, state); + } + if (ImGui::MenuItem("Redo", "Ctrl+Shift+Z", false, state->undo.can_redo())) { + apply_redo(session, state); + } + ImGui::Separator(); + if (ImGui::MenuItem("Open Route...")) { + state->open_open_route = true; + } + if (ImGui::MenuItem("Stream...")) { + state->open_stream = true; + } + if (ImGui::MenuItem("Find Signal...", "Ctrl+F")) { + state->open_find_signal = true; + } + ImGui::Separator(); + if (ImGui::MenuItem("New Layout")) { + start_new_layout(session, state); + } + if (ImGui::MenuItem("Load Layout...")) { + state->open_load_layout = true; + } + if (ImGui::MenuItem("Save Layout")) { + state->request_save_layout = true; + } + if (ImGui::MenuItem("Save Layout As...")) { + state->open_save_layout = true; + } + if (ImGui::MenuItem("Reset Layout")) { + state->request_reset_layout = true; + } + ImGui::Separator(); + if (ImGui::MenuItem("Show DEPRECATED Fields", nullptr, state->show_deprecated_fields)) { + state->show_deprecated_fields = !state->show_deprecated_fields; + rebuild_browser_nodes(session, state); + } + if (ImGui::MenuItem("Show FPS", nullptr, state->show_fps_overlay)) { + state->show_fps_overlay = !state->show_fps_overlay; + } + if (ImGui::MenuItem("Preferences...")) { + state->open_preferences = true; + } + ImGui::Separator(); + if (ImGui::MenuItem("Reset Plot View")) { + reset_shared_range(state, *session); + state->follow_latest = session->data_mode == SessionDataMode::Stream; + clamp_shared_range(state, *session); + state->suppress_range_side_effects = true; + state->status_text = "Plot view reset"; + } + ImGui::Separator(); + if (ImGui::MenuItem("Close")) { + state->request_close = true; + } + ImGui::EndMenu(); + } + ImGui::SameLine(0.0f, 8.0f); + draw_route_id_chip(session, state); + height = ImGui::GetWindowSize().y; + ImGui::EndMainMenuBar(); + } + ImGui::PopStyleVar(2); + return height; +} diff --git a/tools/jotpluggler/sidebar.cc b/tools/jotpluggler/sidebar.cc new file mode 100644 index 00000000000000..c120b47908e6b1 --- /dev/null +++ b/tools/jotpluggler/sidebar.cc @@ -0,0 +1,215 @@ +#include "tools/jotpluggler/internal.h" + +std::string dbc_combo_label(const AppSession &session) { + if (!session.dbc_override.empty()) return session.dbc_override; + if (!session.route_data.dbc_name.empty()) return "Auto: " + session.route_data.dbc_name; + return "Auto"; +} + +float timeline_time_to_x(double time_value, double route_min, double route_max, float x_min, float x_max) { + const double span = route_max - route_min; + if (span <= 0.0) { + return x_min; + } + const double ratio = (time_value - route_min) / span; + return x_min + static_cast(ratio * static_cast(x_max - x_min)); +} + +double timeline_x_to_time(float x, double route_min, double route_max, float x_min, float x_max) { + const float width = std::max(1.0f, x_max - x_min); + const float clamped_x = std::clamp(x, x_min, x_max); + const double ratio = static_cast((clamped_x - x_min) / width); + return route_min + ratio * (route_max - route_min); +} + +void reset_timeline_view(UiState *state, const AppSession &session) { + state->follow_latest = session.data_mode == SessionDataMode::Stream; + reset_shared_range(state, session); +} + +void draw_timeline_bar_contents(const AppSession &session, UiState *state, float width) { + if (!session.route_data.has_time_range) { + ImGui::Dummy(ImVec2(width, TIMELINE_BAR_HEIGHT)); + return; + } + + const ImVec2 cursor = ImGui::GetCursorScreenPos(); + const ImVec2 size(width, TIMELINE_BAR_HEIGHT); + const ImVec2 bar_min(cursor.x + 1.0f, cursor.y + 1.0f); + const ImVec2 bar_max(cursor.x + size.x - 1.0f, cursor.y + size.y - 1.0f); + const double route_min = state->route_x_min; + const double route_max = state->route_x_max; + const float vp_left = timeline_time_to_x(std::clamp(state->x_view_min, route_min, route_max), + route_min, route_max, bar_min.x, bar_max.x); + const float vp_right = timeline_time_to_x(std::clamp(state->x_view_max, route_min, route_max), + route_min, route_max, bar_min.x, bar_max.x); + + ImGui::InvisibleButton("##timeline_button", size); + const bool hovered = ImGui::IsItemHovered(); + const bool active = ImGui::IsItemActive(); + const bool double_clicked = hovered && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + + draw_list->AddRectFilled(bar_min, bar_max, timeline_entry_color(TimelineEntry::Type::None, 0.2f)); + if (session.route_data.timeline.empty()) { + draw_list->AddRectFilled(ImVec2(vp_left, bar_min.y), ImVec2(vp_right, bar_max.y), + timeline_entry_color(TimelineEntry::Type::None, 1.0f)); + } else { + for (const TimelineEntry &entry : session.route_data.timeline) { + float x0 = timeline_time_to_x(entry.start_time, route_min, route_max, bar_min.x, bar_max.x); + float x1 = timeline_time_to_x(entry.end_time, route_min, route_max, bar_min.x, bar_max.x); + x1 = std::max(x1, x0 + 1.0f); + draw_list->AddRectFilled(ImVec2(x0, bar_min.y), ImVec2(x1, bar_max.y), + timeline_entry_color(entry.type, 0.25f)); + } + for (const TimelineEntry &entry : session.route_data.timeline) { + float x0 = std::max(timeline_time_to_x(entry.start_time, route_min, route_max, bar_min.x, bar_max.x), vp_left); + float x1 = std::min(std::max(timeline_time_to_x(entry.end_time, route_min, route_max, bar_min.x, bar_max.x), x0 + 1.0f), vp_right); + if (x1 <= x0) { + continue; + } + draw_list->AddRectFilled(ImVec2(x0, bar_min.y), ImVec2(x1, bar_max.y), + timeline_entry_color(entry.type, 1.0f)); + } + } + + draw_list->AddLine(ImVec2(vp_left, bar_min.y), ImVec2(vp_left, bar_max.y), IM_COL32(60, 70, 80, 200), 1.0f); + draw_list->AddLine(ImVec2(vp_right, bar_min.y), ImVec2(vp_right, bar_max.y), IM_COL32(60, 70, 80, 200), 1.0f); + if (state->has_tracker_time) { + const float cx = timeline_time_to_x(std::clamp(state->tracker_time, route_min, route_max), + route_min, route_max, bar_min.x, bar_max.x); + draw_list->AddLine(ImVec2(cx, bar_min.y), ImVec2(cx, bar_max.y), IM_COL32(220, 60, 50, 255), 1.5f); + } + draw_list->AddRect(bar_min, bar_max, IM_COL32(170, 178, 186, 255), 0.0f, 0, 1.0f); + + const float edge_grab = 4.0f; + const float mouse_x = ImGui::GetIO().MousePos.x; + const double mouse_time = timeline_x_to_time(mouse_x, route_min, route_max, bar_min.x, bar_max.x); + if (double_clicked) { + reset_timeline_view(state, session); + } else if (hovered && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { + state->timeline_drag_anchor_time = mouse_time; + state->timeline_drag_anchor_x_min = state->x_view_min; + state->timeline_drag_anchor_x_max = state->x_view_max; + if (std::abs(mouse_x - vp_left) <= edge_grab) { + state->timeline_drag_mode = TimelineDragMode::ResizeLeft; + } else if (std::abs(mouse_x - vp_right) <= edge_grab) { + state->timeline_drag_mode = TimelineDragMode::ResizeRight; + } else if (mouse_x >= vp_left && mouse_x <= vp_right) { + state->timeline_drag_mode = TimelineDragMode::PanViewport; + } else { + state->timeline_drag_mode = TimelineDragMode::ScrubCursor; + state->tracker_time = std::clamp(mouse_time, route_min, route_max); + state->has_tracker_time = true; + } + } + + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) { + state->timeline_drag_mode = TimelineDragMode::None; + } else if (active || state->timeline_drag_mode != TimelineDragMode::None) { + switch (state->timeline_drag_mode) { + case TimelineDragMode::ScrubCursor: + state->tracker_time = std::clamp(mouse_time, route_min, route_max); + state->has_tracker_time = true; + break; + case TimelineDragMode::PanViewport: { + const double delta = mouse_time - state->timeline_drag_anchor_time; + state->x_view_min = state->timeline_drag_anchor_x_min + delta; + state->x_view_max = state->timeline_drag_anchor_x_max + delta; + clamp_shared_range(state, session); + break; + } + case TimelineDragMode::ResizeLeft: + state->x_view_min = std::min(mouse_time, state->x_view_max - MIN_HORIZONTAL_ZOOM_SECONDS); + clamp_shared_range(state, session); + break; + case TimelineDragMode::ResizeRight: + state->x_view_max = std::max(mouse_time, state->x_view_min + MIN_HORIZONTAL_ZOOM_SECONDS); + clamp_shared_range(state, session); + break; + case TimelineDragMode::None: + break; + } + } + + if (hovered) { + if (std::abs(mouse_x - vp_left) <= edge_grab || std::abs(mouse_x - vp_right) <= edge_grab) { + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } else if (mouse_x >= vp_left && mouse_x <= vp_right) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + ImGui::BeginTooltip(); + ImGui::Text("t=%.1fs — %s", mouse_time, timeline_entry_label(timeline_type_at_time(session.route_data.timeline, mouse_time))); + ImGui::EndTooltip(); + } +} + +void draw_status_bar(const AppSession &session, const UiMetrics &ui, UiState *state) { + ImGui::SetNextWindowPos(ImVec2(ui.content_x, ui.status_bar_y)); + ImGui::SetNextWindowSize(ImVec2(ui.content_w, STATUS_BAR_HEIGHT)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_WindowBg, color_rgb(247, 248, 250)); + ImGui::PushStyleColor(ImGuiCol_Border, color_rgb(188, 193, 199)); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoSavedSettings; + if (ImGui::Begin("##status_bar", nullptr, flags)) { + draw_timeline_bar_contents(session, state, ui.content_w); + const float row_y = TIMELINE_BAR_HEIGHT + 8.0f; + ImGui::SetCursorPos(ImVec2(8.0f, row_y)); + ImGui::BeginDisabled(!session.route_data.has_time_range); + ImGui::Checkbox("Loop", &state->playback_loop); + ImGui::SameLine(0.0f, 10.0f); + if (ImGui::Button(state->playback_playing ? "Pause" : "Play", ImVec2(56.0f, 0.0f))) { + state->playback_playing = !state->playback_playing; + } + ImGui::SameLine(0.0f, 10.0f); + if (ImGui::Button("Reset View", ImVec2(86.0f, 0.0f))) { + reset_timeline_view(state, session); + } + const float controls_end_x = ImGui::GetItemRectMax().x - ImGui::GetWindowPos().x; + ImGui::EndDisabled(); + + const char *status_text = state->status_text.empty() ? "Ready" : state->status_text.c_str(); + const float status_x = controls_end_x + 16.0f; + ImGui::SetCursorPos(ImVec2(status_x, row_y + 2.0f)); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(102, 110, 118)); + ImGui::TextUnformatted(status_text); + ImGui::PopStyleColor(); + + } + ImGui::End(); + ImGui::PopStyleColor(2); + ImGui::PopStyleVar(); +} + +void draw_sidebar_resizer(const UiMetrics &ui, UiState *state) { + constexpr float kHandleWidth = 14.0f; + ImGui::SetNextWindowPos(ImVec2(ui.sidebar_width - kHandleWidth * 0.5f, ui.top_offset)); + ImGui::SetNextWindowSize(ImVec2(kHandleWidth, std::max(1.0f, ui.height - ui.top_offset))); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoBackground; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + if (ImGui::Begin("##sidebar_resizer", nullptr, flags)) { + ImGui::InvisibleButton("##sidebar_resizer_button", ImVec2(kHandleWidth, std::max(1.0f, ui.height - ui.top_offset))); + if (ImGui::IsItemHovered() || ImGui::IsItemActive()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } + if (ImGui::IsItemActive()) { + const float max_width = std::min(SIDEBAR_MAX_WIDTH, ui.width * 0.6f); + state->sidebar_width = std::clamp(ImGui::GetIO().MousePos.x, SIDEBAR_MIN_WIDTH, max_width); + } + + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + const ImVec2 origin = ImGui::GetWindowPos(); + draw_list->AddLine(ImVec2(origin.x + kHandleWidth * 0.5f, origin.y), + ImVec2(origin.x + kHandleWidth * 0.5f, origin.y + std::max(1.0f, ui.height - ui.top_offset)), + IM_COL32(194, 198, 204, 255)); + } + ImGui::End(); + ImGui::PopStyleVar(); +} diff --git a/tools/jotpluggler/sketch_layout.cc b/tools/jotpluggler/sketch_layout.cc new file mode 100644 index 00000000000000..20912801693c08 --- /dev/null +++ b/tools/jotpluggler/sketch_layout.cc @@ -0,0 +1,1899 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/car_fingerprint_to_dbc.h" +#include "tools/jotpluggler/common.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/util.h" +#include "json11/json11.hpp" +#include "tools/replay/logreader.h" +#include "tools/replay/py_downloader.h" + +namespace fs = std::filesystem; + +namespace { + +struct RouteSelection { + std::string dongle_id; + std::string timestamp; + int begin_segment = 0; + int end_segment = -1; + bool slice_explicit = false; + LogSelector selector = LogSelector::Auto; + bool selector_explicit = false; + std::string canonical_name; +}; + +struct SegmentLogs { + std::string rlog; + std::string qlog; + std::string fcamera; + std::string dcamera; + std::string ecamera; + std::string qcamera; +}; + +struct SchemaIndex { + size_t fixed_series_count = 0; + std::vector fixed_paths; + + static const SchemaIndex &instance(); +}; + +constexpr size_t INVALID_DYNAMIC_SLOT = std::numeric_limits::max(); + +struct SeriesAccumulator { + explicit SeriesAccumulator(size_t fixed_count = 0) : fixed_series(fixed_count) {} + + std::vector fixed_series; + std::vector dynamic_series; + std::vector can_messages; + std::unordered_map dynamic_slots; + std::unordered_map> list_scalar_slots; + std::unordered_map can_message_slots; + std::unordered_map enum_info; +}; + +void append_fixed_scalar_point(RouteSeries *series, double tm, double value); +void append_dynamic_scalar_point(const std::string &path, double tm, double value, SeriesAccumulator *series); +RouteSeries *ensure_list_scalar_series(const std::string &base_path, size_t index, SeriesAccumulator *series); +void append_can_frame(CanServiceKind service, + uint8_t bus, + uint32_t address, + uint16_t bus_time, + capnp::Data::Reader dat, + double tm, + SeriesAccumulator *series); +void decode_can_frame(const dbc::Database *can_dbc, + const std::string &service_name, + uint8_t bus, + uint32_t address, + const uint8_t *raw, + size_t data_size, + double tm, + SeriesAccumulator *series); + +#include "tools/jotpluggler/generated_event_extractors.h" + +struct LoadedRouteArtifacts { + std::vector series; + std::vector can_messages; + std::vector logs; + std::vector timeline; + std::unordered_map enum_info; +}; + +struct RouteMetadata { + std::string car_fingerprint; +}; + +struct LoadStats { + using Clock = std::chrono::steady_clock; + using TimePoint = Clock::time_point; + + struct SegmentStats { + int segment_number = -1; + std::string log_path; + double download_seconds = 0.0; + double decompress_seconds = 0.0; + double parse_seconds = 0.0; + double extract_seconds = 0.0; + size_t compressed_bytes = 0; + size_t decompressed_bytes = 0; + size_t event_count = 0; + size_t series_count = 0; + bool failed = false; + }; + + explicit LoadStats(const RouteLoadProgressCallback &callback) : progress(callback) {} + + void publish(RouteLoadStage stage, size_t segment_index, const std::string &segment_name) { + if (!progress) { + return; + } + RouteLoadProgress update; + update.stage = stage; + update.segment_index = segment_index; + update.segment_count = segment_count; + update.current = stage == RouteLoadStage::DownloadingSegment + ? segments_downloaded.load() + : segments_parsed.load(); + update.total = total_segments.load(); + update.segments_downloaded = segments_downloaded.load(); + update.segments_parsed = segments_parsed.load(); + update.total_segments = total_segments.load(); + update.bytes_downloaded = bytes_downloaded.load(); + update.num_workers = num_workers; + update.segment_name = segment_name; + std::lock_guard lock(progress_mutex); + progress(update); + } + + void print_summary(size_t final_series_count) const { + const auto secs = [](TimePoint a, TimePoint b) { return std::chrono::duration(b - a).count(); }; + const auto mb = [](size_t bytes) { return static_cast(bytes) / (1024.0 * 1024.0); }; + double dl = 0, dc = 0, pa = 0, ex = 0; + size_t ev = 0, cb = 0, db = 0; + for (const auto &s : segments) { + dl += s.download_seconds; dc += s.decompress_seconds; + pa += s.parse_seconds; ex += s.extract_seconds; + ev += s.event_count; cb += s.compressed_bytes; db += s.decompressed_bytes; + } + std::cerr << std::fixed << std::setprecision(1) + << "route loaded in " << secs(load_start, load_end) << "s (" << segment_count << " segments, " << num_workers << " workers)\n" + << " resolve: " << secs(load_start, resolve_end) << "s fetch: " << dl << "s (" << mb(cb) << " MB)" + << " decompress: " << dc << "s (" << mb(db) << " MB)\n" + << " parse: " << pa << "s (" << ev << " events) extract: " << ex << "s merge: " << secs(merge_start, merge_end) << "s" + << " series: " << final_series_count << " paths\n"; + for (const auto &s : segments) { + std::cerr << " seg " << std::setw(2) << s.segment_number << ": " + << (s.failed ? "FAILED" : std::to_string(s.download_seconds) + "s + " + std::to_string(s.parse_seconds) + + "s (" + std::to_string(s.event_count) + " ev, " + std::to_string(s.series_count) + " series)") << "\n"; + } + std::cerr.unsetf(std::ios::floatfield); + } + + TimePoint load_start; + TimePoint resolve_end; + TimePoint merge_start; + TimePoint merge_end; + TimePoint load_end; + size_t segment_count = 0; + int num_workers = 1; + std::vector segments; + std::atomic segments_downloaded{0}; + std::atomic segments_parsed{0}; + std::atomic total_segments{0}; + std::atomic bytes_downloaded{0}; + RouteLoadProgressCallback progress; + mutable std::mutex progress_mutex; +}; + +// Skip individual messages that our local Cap'n Proto schema can't project, +// such as logs recorded by a newer build. +template +void with_parseable_event(kj::ArrayPtr data, Fn &&fn) { + try { + capnp::FlatArrayMessageReader event_reader(data); + fn(event_reader.getRoot()); + } catch (const kj::Exception &) { + return; + } +} + +std::string curve_label(std::string_view series_name) { + return std::string(series_name.empty() ? std::string_view{"plot"} : series_name); +} + +bool parse_segment_number(std::string_view value, int *out) { + if (value.empty()) return false; + char *end = nullptr; + const long parsed = std::strtol(std::string(value).c_str(), &end, 10); + if (end == nullptr || *end != '\0') return false; + *out = static_cast(parsed); + return true; +} + +bool is_log_selector_char(char c) { + return c == 'a' || c == 'r' || c == 'q'; +} + +LogSelector parse_log_selector_char(char c) { + switch (c) { + case 'r': return LogSelector::RLog; + case 'q': return LogSelector::QLog; + case 'a': + default: return LogSelector::Auto; + } +} + +const std::string &selected_log_path(const SegmentLogs &segment, LogSelector selector) { + switch (selector) { + case LogSelector::RLog: + return segment.rlog; + case LogSelector::QLog: + return segment.qlog; + case LogSelector::Auto: + default: + return !segment.rlog.empty() ? segment.rlog : segment.qlog; + } +} + +RouteSelection parse_route_selection(std::string route_name) { + RouteSelection route = {}; + route_name = util::strip(route_name); + if (route_name.size() >= 2 && route_name[route_name.size() - 2] == '/' + && is_log_selector_char(static_cast(std::tolower(route_name.back())))) { + route.selector = parse_log_selector_char(static_cast(std::tolower(route_name.back()))); + route.selector_explicit = true; + route_name.resize(route_name.size() - 2); + } + static const std::regex pattern(R"(^(([a-z0-9]{16})[|_/])?(.{20})((--|/)((-?\d+(:(-?\d+)?)?)|(:-?\d+)))?$)"); + std::smatch match; + if (!std::regex_match(route_name, match, pattern)) return route; + + route.dongle_id = match[2].str(); + route.timestamp = match[3].str(); + route.canonical_name = route.dongle_id + "|" + route.timestamp; + + const std::string separator = match[5].str(); + const std::string range_str = match[6].str(); + if (!range_str.empty()) { + route.slice_explicit = true; + if (separator == "/") { + size_t pos = range_str.find(':'); + int begin_segment = 0; + if (!parse_segment_number(range_str.substr(0, pos), &begin_segment)) { + return {}; + } + route.begin_segment = begin_segment; + route.end_segment = begin_segment; + if (pos != std::string::npos) { + int end_segment = -1; + const std::string end_str = range_str.substr(pos + 1); + if (!end_str.empty() && !parse_segment_number(end_str, &end_segment)) { + return {}; + } + route.end_segment = end_str.empty() ? -1 : end_segment; + } + } else if (separator == "--") { + int begin_segment = 0; + if (!parse_segment_number(range_str, &begin_segment)) return {}; + route.begin_segment = begin_segment; + } + } + return route; +} + +void add_log_file_to_segments(std::map *segments, int segment_number, const std::string &file) { + std::string name = extractFileName(file); + const size_t pos = name.find_last_of("--"); + name = pos != std::string::npos ? name.substr(pos + 2) : name; + SegmentLogs &segment = (*segments)[segment_number]; + if (name == "rlog.bz2" || name == "rlog.zst" || name == "rlog") { + segment.rlog = file; + } else if (name == "qlog.bz2" || name == "qlog.zst" || name == "qlog") { + segment.qlog = file; + } else if (name == "fcamera.hevc") { + segment.fcamera = file; + } else if (name == "dcamera.hevc") { + segment.dcamera = file; + } else if (name == "ecamera.hevc") { + segment.ecamera = file; + } else if (name == "qcamera.ts") { + segment.qcamera = file; + } +} + +std::map trim_segments(std::map segments, const RouteSelection &route) { + if (route.begin_segment > 0) { + segments.erase(segments.begin(), segments.lower_bound(route.begin_segment)); + } + if (route.end_segment >= 0) { + segments.erase(segments.upper_bound(route.end_segment), segments.end()); + } + return segments; +} + +std::map load_segments_from_json(const json11::Json &json) { + std::map segments; + static const std::regex rx(R"(\/(\d+)\/)"); + for (const auto &value : json.object_items()) { + for (const auto &url : value.second.array_items()) { + const std::string url_str = url.string_value(); + std::smatch match; + if (!std::regex_search(url_str, match, rx)) continue; + add_log_file_to_segments(&segments, std::stoi(match[1].str()), url_str); + } + } + return segments; +} + +std::map load_segments_from_server(const RouteSelection &route) { + const std::string result = PyDownloader::getRouteFiles(route.canonical_name); + if (result.empty()) throw std::runtime_error("Failed to fetch route files for " + route.canonical_name); + + std::string parse_error; + const auto json = json11::Json::parse(result, parse_error); + if (!parse_error.empty()) throw std::runtime_error("Failed to parse route file list for " + route.canonical_name); + if (json.is_object() && json["error"].is_string()) { + throw std::runtime_error("Route API error for " + route.canonical_name + ": " + json["error"].string_value()); + } + return load_segments_from_json(json); +} + +std::map load_segments_from_local(const RouteSelection &route, const std::string &data_dir) { + std::map segments; + const std::string pattern = route.timestamp + "--"; + for (const auto &entry : fs::directory_iterator(data_dir)) { + if (!entry.is_directory()) continue; + const std::string dirname = entry.path().filename().string(); + if (dirname.find(pattern) == std::string::npos) continue; + const size_t marker = dirname.rfind("--"); + if (marker == std::string::npos) continue; + int segment_number = 0; + if (!parse_segment_number(dirname.substr(marker + 2), &segment_number)) { + continue; + } + for (const auto &file : fs::directory_iterator(entry.path())) { + if (file.is_regular_file()) { + add_log_file_to_segments(&segments, segment_number, file.path().string()); + } + } + } + return segments; +} + +RouteIdentifier make_route_identifier(const RouteSelection &route, const std::map &segments) { + RouteIdentifier route_id; + route_id.dongle_id = route.dongle_id; + route_id.log_id = route.timestamp; + route_id.slice_begin = route.begin_segment; + route_id.slice_end = route.end_segment; + route_id.slice_explicit = route.slice_explicit; + route_id.selector = route.selector; + route_id.selector_explicit = route.selector_explicit; + if (!segments.empty()) { + route_id.available_begin = segments.begin()->first; + route_id.available_end = segments.rbegin()->first; + } + return route_id; +} + +std::string detect_dbc_for_fingerprint(std::string_view car_fingerprint) { + return std::string(dbc_for_car_fingerprint(car_fingerprint)); +} + +std::vector available_dbc_names_impl() { + std::set names; + for (const fs::path &dbc_dir : { + repo_root() / "opendbc" / "dbc", + repo_root() / "tools" / "jotpluggler" / "generated_dbcs", + }) { + if (fs::exists(dbc_dir) && fs::is_directory(dbc_dir)) { + for (const auto &entry : fs::directory_iterator(dbc_dir)) { + if (!entry.is_regular_file() || entry.path().extension() != ".dbc") { + continue; + } + names.insert(entry.path().stem().string()); + } + } + } + for (const auto &[_, dbc_name] : kCarFingerprintToDbc) { + if (!dbc_name.empty()) { + names.insert(std::string(dbc_name)); + } + } + return std::vector(names.begin(), names.end()); +} + +fs::path resolve_dbc_path(const std::string &dbc_name) { + for (const fs::path &candidate : { + repo_root() / "opendbc" / "dbc" / (dbc_name + ".dbc"), + repo_root() / "tools" / "jotpluggler" / "generated_dbcs" / (dbc_name + ".dbc"), + }) { + if (fs::exists(candidate)) return candidate; + } + throw std::runtime_error("DBC not found: " + dbc_name); +} + +std::array parse_color(std::string_view color) { + if (!color.empty() && color.front() == '#') { + color.remove_prefix(1); + } + if (color.size() != 6) return {160, 170, 180}; + + std::array out = {}; + for (size_t i = 0; i < 3; ++i) { + const std::string byte(color.substr(i * 2, 2)); + char *end = nullptr; + const long parsed = std::strtol(byte.c_str(), &end, 16); + if (end == nullptr || *end != '\0' || parsed < 0 || parsed > 255) return {160, 170, 180}; + out[i] = static_cast(parsed); + } + return out; +} + +uint8_t android_priority_to_level(uint8_t priority) { + switch (priority) { + case 2: + case 3: + return 10; + case 4: + return 20; + case 5: + return 30; + case 6: + return 40; + case 7: + default: + return 50; + } +} + +uint8_t alert_status_to_level(cereal::SelfdriveState::AlertStatus status) { + switch (status) { + case cereal::SelfdriveState::AlertStatus::NORMAL: + return 20; + case cereal::SelfdriveState::AlertStatus::USER_PROMPT: + return 30; + case cereal::SelfdriveState::AlertStatus::CRITICAL: + return 40; + } + return 20; +} + +TimelineEntry::Type alert_status_to_timeline_type(cereal::SelfdriveState::AlertStatus status, bool enabled) { + if (!enabled) { + return TimelineEntry::Type::None; + } + switch (status) { + case cereal::SelfdriveState::AlertStatus::NORMAL: + return TimelineEntry::Type::Engaged; + case cereal::SelfdriveState::AlertStatus::USER_PROMPT: + return TimelineEntry::Type::AlertInfo; + case cereal::SelfdriveState::AlertStatus::CRITICAL: + return TimelineEntry::Type::AlertCritical; + } + return TimelineEntry::Type::Engaged; +} + +void append_timeline_entry(std::vector *timeline, double mono_time, TimelineEntry::Type type) { + if (timeline == nullptr) { + return; + } + if (!timeline->empty() && timeline->back().type == type) { + timeline->back().end_time = std::max(timeline->back().end_time, mono_time); + return; + } + timeline->push_back(TimelineEntry{ + .start_time = mono_time, + .end_time = mono_time, + .type = type, + }); +} + +double android_wall_time_seconds(uint64_t timestamp) { + if (timestamp == 0) return 0.0; + if (timestamp > 1000000000000ULL) return static_cast(timestamp) / 1.0e9; + if (timestamp > 1000000000ULL) return static_cast(timestamp) / 1.0e6; + return static_cast(timestamp); +} + +std::optional json_u64_value(const json11::Json &value) { + if (value.is_number()) { + const double number = value.number_value(); + if (number >= 0.0) return static_cast(number); + } + if (value.is_string()) { + try { + return static_cast(std::stoull(value.string_value())); + } catch (...) { + } + } + return std::nullopt; +} + +std::optional json_int_value(const json11::Json &value) { + if (value.is_number()) return value.int_value(); + if (value.is_string()) { + try { + return std::stoi(value.string_value()); + } catch (...) { + } + } + return std::nullopt; +} + +std::string json_value_for_log(const json11::Json &value) { + if (value.is_string()) return value.string_value(); + if (value.is_bool()) return value.bool_value() ? "true" : "false"; + return value.dump(); +} + +std::string format_journal_context(const json11::Json &parsed, int pid, int tid) { + std::vector lines; + if (pid != 0 || tid != 0) { + lines.push_back("pid=" + std::to_string(pid) + ", tid=" + std::to_string(tid)); + } + + const std::array preferred_keys = { + "_HOSTNAME", + "_TRANSPORT", + "PRIORITY", + "SYSLOG_FACILITY", + "__MONOTONIC_TIMESTAMP", + }; + for (const char *key : preferred_keys) { + const json11::Json &value = parsed[key]; + if (!value.is_null()) { + lines.push_back(std::string(key) + "=" + json_value_for_log(value)); + } + } + return join(lines, "\n"); +} + +std::string alert_message_text(const cereal::SelfdriveState::Reader &state) { + std::string text = state.getAlertText1().cStr(); + const std::string text2 = state.getAlertText2().cStr(); + if (!text2.empty()) { + text += " - " + text2; + } + return text; +} + +bool same_log_entry(const LogEntry &a, const LogEntry &b) { + return a.mono_time == b.mono_time + && a.level == b.level + && a.source == b.source + && a.func == b.func + && a.message == b.message + && a.context == b.context + && a.origin == b.origin; +} + +void append_log_event(cereal::Event::Which which, + const cereal::Event::Reader &event, + double time_offset, + std::vector *logs, + std::string *last_alert_key) { + const double boot_time = static_cast(event.getLogMonoTime()) / 1.0e9; + const double mono_time = boot_time - time_offset; + + auto make_entry = [&](LogOrigin origin, uint8_t level = 20) { + LogEntry e; + e.mono_time = mono_time; + e.boot_time = boot_time; + e.origin = origin; + e.level = level; + return e; + }; + + switch (which) { + case cereal::Event::Which::LOG_MESSAGE: + case cereal::Event::Which::ERROR_LOG_MESSAGE: { + const std::string raw = which == cereal::Event::Which::LOG_MESSAGE + ? event.getLogMessage().cStr() : event.getErrorLogMessage().cStr(); + auto entry = make_entry(LogOrigin::Log, which == cereal::Event::Which::ERROR_LOG_MESSAGE ? 40 : 20); + entry.source = "log"; + entry.message = raw; + std::string err; + if (const auto p = json11::Json::parse(raw, err); err.empty() && p.is_object()) { + entry.wall_time = p["created"].number_value(); + if (p["levelnum"].is_number()) entry.level = static_cast(p["levelnum"].int_value()); + const std::string fn = p["filename"].string_value(); + const int ln = p["lineno"].is_number() ? p["lineno"].int_value() : 0; + entry.source = fn.empty() ? "log" : fn + (ln > 0 ? ":" + std::to_string(ln) : ""); + entry.func = p["funcname"].string_value(); + if (p["msg"].is_string()) entry.message = p["msg"].string_value(); + if (!p["ctx"].is_null()) entry.context = p["ctx"].dump(); + } + logs->push_back(std::move(entry)); + break; + } + case cereal::Event::Which::ANDROID_LOG: { + const auto android = event.getAndroidLog(); + auto entry = make_entry(LogOrigin::Android, android_priority_to_level(android.getPriority())); + entry.wall_time = android_wall_time_seconds(android.getTs()); + entry.source = android.hasTag() ? android.getTag().cStr() : "android"; + entry.message = android.hasMessage() ? android.getMessage().cStr() : std::string(); + entry.context = "pid=" + std::to_string(android.getPid()) + ", tid=" + std::to_string(android.getTid()); + if (!entry.message.empty()) { + std::string err; + if (const auto p = json11::Json::parse(entry.message, err); err.empty() && p.is_object()) { + if (p["MESSAGE"].is_string()) entry.message = p["MESSAGE"].string_value(); + if (p["SYSLOG_IDENTIFIER"].is_string() && !p["SYSLOG_IDENTIFIER"].string_value().empty()) + entry.source = p["SYSLOG_IDENTIFIER"].string_value(); + if (auto pri = json_int_value(p["PRIORITY"]); pri.has_value()) + entry.level = android_priority_to_level(*pri); + if (auto ts = json_u64_value(p["__REALTIME_TIMESTAMP"]); ts.has_value()) + entry.wall_time = android_wall_time_seconds(*ts); + entry.context = format_journal_context(p, android.getPid(), android.getTid()); + } + } + logs->push_back(std::move(entry)); + break; + } + case cereal::Event::Which::SELFDRIVE_STATE: { + const auto sd = event.getSelfdriveState(); + const std::string alert_type = sd.getAlertType().cStr(); + const std::string alert_text1 = sd.getAlertText1().cStr(); + if (alert_text1.empty() && alert_type.empty()) break; + const std::string key = alert_type + "\n" + alert_text1 + "\n" + std::string(sd.getAlertText2().cStr()); + if (last_alert_key != nullptr && key == *last_alert_key) break; + if (last_alert_key != nullptr) *last_alert_key = key; + auto entry = make_entry(LogOrigin::Alert, alert_status_to_level(sd.getAlertStatus())); + entry.source = "alert"; + entry.func = alert_type; + entry.message = alert_message_text(sd); + logs->push_back(std::move(entry)); + break; + } + default: + break; + } +} + +std::vector extract_segment_timeline(const std::vector &events) { + std::vector timeline; + timeline.reserve(events.size() / 16); + + for (const Event &event_record : events) { + if (event_record.which != cereal::Event::Which::SELFDRIVE_STATE) { + continue; + } + with_parseable_event(event_record.data, [&](const cereal::Event::Reader &event) { + const auto sd = event.getSelfdriveState(); + const double mono_time = static_cast(event.getLogMonoTime()) / 1.0e9; + append_timeline_entry(&timeline, mono_time, alert_status_to_timeline_type(sd.getAlertStatus(), sd.getEnabled())); + }); + } + + return timeline; +} + +std::vector extract_segment_logs(const std::vector &events) { + std::vector logs; + logs.reserve(events.size() / 8); + std::string last_alert_key; + + for (const Event &event_record : events) { + with_parseable_event(event_record.data, [&](const cereal::Event::Reader &event) { + append_log_event(event_record.which, event, 0.0, &logs, &last_alert_key); + }); + } + + return logs; +} + +RouteMetadata extract_segment_metadata(const std::vector &events) { + RouteMetadata metadata; + for (const Event &event_record : events) { + if (event_record.which != cereal::Event::Which::CAR_PARAMS) continue; + with_parseable_event(event_record.data, [&](const cereal::Event::Reader &event) { + metadata.car_fingerprint = event.getCarParams().getCarFingerprint().cStr(); + }); + if (!metadata.car_fingerprint.empty()) break; + } + return metadata; +} + +RouteMetadata detect_route_metadata(const std::map &segments, LogSelector selector) { + for (const auto &[_, segment] : segments) { + const std::string &log_path = selector == LogSelector::Auto + ? (!segment.qlog.empty() ? segment.qlog : segment.rlog) + : selected_log_path(segment, selector); + if (log_path.empty()) { + continue; + } + LogReader reader; + if (!reader.load(log_path, nullptr, true)) continue; + RouteMetadata metadata = extract_segment_metadata(reader.events); + if (!metadata.car_fingerprint.empty()) return metadata; + } + return {}; +} + +std::vector normalize_sizes(const json11::Json &sizes_json, size_t child_count) { + std::vector parsed; + if (sizes_json.is_array()) { + for (const json11::Json &value : sizes_json.array_items()) { + if (value.is_number()) { + parsed.push_back(std::max(value.number_value(), 0.0)); + } + } + } + + if (parsed.size() != child_count || child_count == 0) return std::vector(child_count, child_count == 0 ? 0.0 : 1.0 / static_cast(child_count)); + + const double total = std::accumulate(parsed.begin(), parsed.end(), 0.0); + if (total <= 0.0) return std::vector(child_count, 1.0 / static_cast(child_count)); + for (double &value : parsed) { + value /= total; + } + return parsed; +} + +PlotRange parse_range(const json11::Json &pane_node) { + PlotRange range; + const json11::Json &range_node = pane_node["range"]; + if (range_node.is_object()) { + range.valid = true; + range.left = range_node["left"].number_value(); + range.right = range_node["right"].number_value(); + range.bottom = range_node["bottom"].number_value(); + range.top = range_node["top"].is_number() ? range_node["top"].number_value() : 1.0; + } + const json11::Json &limit_y_node = pane_node["y_limits"]; + if (limit_y_node.is_object()) { + if (limit_y_node["min"].is_number()) { + range.has_y_limit_min = true; + range.y_limit_min = limit_y_node["min"].number_value(); + } + if (limit_y_node["max"].is_number()) { + range.has_y_limit_max = true; + range.y_limit_max = limit_y_node["max"].number_value(); + } + } + return range; +} + +Curve parse_curve(const json11::Json &curve_node) { + Curve curve; + curve.name = curve_node["name"].string_value(); + curve.label = curve_label(curve.name); + curve.color = parse_color(curve_node["color"].string_value()); + + const std::string transform_name = curve_node["transform"].string_value(); + if (transform_name == "derivative") { + curve.derivative = true; + curve.derivative_dt = curve_node["derivative_dt"].is_number() ? curve_node["derivative_dt"].number_value() : 0.0; + } else if (transform_name == "scale") { + curve.value_scale = curve_node["scale"].is_number() ? curve_node["scale"].number_value() : 1.0; + curve.value_offset = curve_node["offset"].is_number() ? curve_node["offset"].number_value() : 0.0; + } + const json11::Json &custom_node = curve_node["custom_python"]; + if (custom_node.is_object()) { + CustomPythonSeries spec; + spec.linked_source = custom_node["linked_source"].string_value(); + spec.globals_code = custom_node["globals_code"].string_value(); + spec.function_code = custom_node["function_code"].string_value(); + for (const json11::Json &source : custom_node["additional_sources"].array_items()) { + if (source.is_string()) { + spec.additional_sources.push_back(source.string_value()); + } + } + curve.custom_python = std::move(spec); + } + return curve; +} + +std::string pane_title(const json11::Json &dock_area_node) { + const std::string raw = dock_area_node["title"].string_value(); + return raw.empty() ? "..." : raw; +} + +Pane parse_dock_area(const json11::Json &dock_area_node) { + Pane pane; + const std::string kind = dock_area_node["kind"].string_value(); + if (kind == "map") { + pane.kind = PaneKind::Map; + } else if (kind == "camera") { + pane.kind = PaneKind::Camera; + const std::string camera_view = dock_area_node["camera_view"].string_value(); + if (const CameraViewSpec *spec = camera_view_spec_from_layout_name(camera_view)) { + pane.camera_view = spec->view; + } else { + pane.camera_view = CameraViewKind::Road; + } + } + pane.range = parse_range(dock_area_node); + const json11::Json &curves_node = dock_area_node["curves"]; + if (curves_node.is_array()) { + for (const json11::Json &curve_node : curves_node.array_items()) { + if (curve_node.is_object()) { + pane.curves.push_back(parse_curve(curve_node)); + } + } + } + pane.title = pane_title(dock_area_node); + return pane; +} + +WorkspaceNode parse_workspace_node(const json11::Json &node, WorkspaceTab *tab) { + WorkspaceNode workspace_node; + if (!node.is_object()) return workspace_node; + + if (node["curves"].is_array()) { + workspace_node.is_pane = true; + workspace_node.pane_index = static_cast(tab->panes.size()); + tab->panes.push_back(parse_dock_area(node)); + return workspace_node; + } + + const json11::Json &children_node = node["children"]; + if (!children_node.is_array()) return workspace_node; + + const std::vector children = children_node.array_items(); + if (children.empty()) return workspace_node; + + const std::string split = node["split"].string_value(); + workspace_node.orientation = split == "vertical" ? SplitOrientation::Vertical : SplitOrientation::Horizontal; + const std::vector sizes = normalize_sizes(node["sizes"], children.size()); + workspace_node.sizes.reserve(sizes.size()); + workspace_node.children.reserve(children.size()); + for (size_t i = 0; i < children.size(); ++i) { + workspace_node.sizes.push_back(static_cast(sizes[i])); + workspace_node.children.push_back(parse_workspace_node(children[i], tab)); + } + return workspace_node; +} + +WorkspaceTab parse_tab(const json11::Json &tab, const fs::path &layout_path) { + WorkspaceTab workspace_tab; + workspace_tab.tab_name = tab["name"].string_value().empty() ? "tab1" : tab["name"].string_value(); + const json11::Json &dock_root = tab["root"]; + if (!dock_root.is_object()) throw std::runtime_error("Layout tab has no dock content: " + layout_path.string()); + workspace_tab.root = parse_workspace_node(dock_root, &workspace_tab); + return workspace_tab; +} + +SketchLayout parse_layout(const fs::path &layout_path) { + const std::string text = util::read_file(layout_path.string()); + if (text.empty()) throw std::runtime_error("Failed to read layout JSON: " + layout_path.string()); + + std::string parse_error; + const json11::Json root = json11::Json::parse(text, parse_error); + if (!parse_error.empty() || !root.is_object()) { + throw std::runtime_error("Failed to parse layout JSON: " + layout_path.string()); + } + SketchLayout layout; + for (const json11::Json &tab : root["tabs"].array_items()) { + if (tab.is_object()) { + layout.tabs.push_back(parse_tab(tab, layout_path)); + } + } + if (layout.tabs.empty()) throw std::runtime_error("Layout has no tabs: " + layout_path.string()); + const json11::Json &tab_index = root["current_tab_index"].is_number() ? root["current_tab_index"] : root["currentTabIndex"]; + layout.current_tab_index = std::clamp(tab_index.is_number() ? tab_index.int_value() : 0, + 0, + static_cast(layout.tabs.size()) - 1); + return layout; +} + +const SchemaIndex &SchemaIndex::instance() { + static const SchemaIndex index = [] { + SchemaIndex out; + out.fixed_paths = static_event_fixed_paths(); + out.fixed_series_count = out.fixed_paths.size(); + return out; + }(); + return index; +} + +bool is_absolute_curve(const std::string &name) { + return !name.empty() && name.front() == '/'; +} + +void append_scalar_point(RouteSeries *series, + const std::string &path, + double tm, + double value) { + if (series->path.empty()) { + series->path = path; + } + series->times.push_back(tm); + series->values.push_back(value); +} + +void append_fixed_scalar_point(RouteSeries *series, double tm, double value) { + series->times.push_back(tm); + series->values.push_back(value); +} + +CanMessageData *ensure_can_message(CanServiceKind service, uint8_t bus, uint32_t address, SeriesAccumulator *series) { + const CanMessageId id{service, bus, address}; + auto [it, inserted] = series->can_message_slots.try_emplace(id, series->can_messages.size()); + if (inserted) { + series->can_messages.push_back(CanMessageData{.id = id}); + } + return &series->can_messages[it->second]; +} + +void append_can_frame(CanServiceKind service, + uint8_t bus, + uint32_t address, + uint16_t bus_time, + capnp::Data::Reader dat, + double tm, + SeriesAccumulator *series) { + CanMessageData *message = ensure_can_message(service, bus, address, series); + message->samples.push_back(CanFrameSample{ + .mono_time = tm, + .bus_time = bus_time, + .data = std::string(reinterpret_cast(dat.begin()), dat.size()), + }); +} + +void append_dynamic_scalar_point(const std::string &path, double tm, double value, SeriesAccumulator *series); + +void decode_can_frame(const dbc::Database *can_dbc, + const std::string &service_name, + uint8_t bus, + uint32_t address, + const uint8_t *raw, + size_t data_size, + double tm, + SeriesAccumulator *series) { + if (can_dbc == nullptr) { + return; + } + const dbc::Message *message = can_dbc->message(address); + if (message == nullptr) { + return; + } + const std::string base_path = "/" + service_name + "/" + std::to_string(bus) + "/" + message->name; + for (const dbc::Signal &signal : message->signals) { + std::optional value = dbc::signalValue(signal, *message, raw, data_size); + if (!value.has_value()) continue; + const std::string path = base_path + "/" + signal.name; + append_dynamic_scalar_point(path, tm, *value, series); + if (series->enum_info.find(path) == series->enum_info.end()) { + std::vector enum_names = can_dbc->enumNames(signal); + if (!enum_names.empty()) { + series->enum_info.emplace(path, EnumInfo{.names = std::move(enum_names)}); + } + } + } +} + +void append_live_can_frame(CanServiceKind service, + const LiveCanFrame &frame, + double time_offset, + const dbc::Database *can_dbc, + SeriesAccumulator *series) { + const double tm = frame.mono_time - time_offset; + CanMessageData *message = ensure_can_message(service, frame.bus, frame.address, series); + message->samples.push_back(CanFrameSample{ + .mono_time = tm, + .bus_time = frame.bus_time, + .data = frame.data, + }); + decode_can_frame(can_dbc, + service == CanServiceKind::Can ? "can" : "sendcan", + frame.bus, + frame.address, + reinterpret_cast(frame.data.data()), + frame.data.size(), + tm, + series); +} + +SeriesAccumulator make_series_accumulator(const SchemaIndex &schema) { + SeriesAccumulator out(schema.fixed_series_count); + for (size_t i = 0; i < schema.fixed_paths.size(); ++i) { + out.fixed_series[i].path = schema.fixed_paths[i]; + } + return out; +} + +size_t ensure_dynamic_slot(const std::string &path, SeriesAccumulator *series) { + auto [it, inserted] = series->dynamic_slots.try_emplace(path, series->dynamic_series.size()); + if (inserted) { + series->dynamic_series.push_back(RouteSeries{it->first}); + } + return it->second; +} + +RouteSeries *ensure_dynamic_series(const std::string &path, SeriesAccumulator *series) { + return &series->dynamic_series[ensure_dynamic_slot(path, series)]; +} + +RouteSeries *ensure_list_scalar_series(const std::string &base_path, size_t index, SeriesAccumulator *series) { + auto [it, _] = series->list_scalar_slots.try_emplace(base_path); + std::vector &slots = it->second; + if (slots.size() <= index) { + slots.resize(index + 1, INVALID_DYNAMIC_SLOT); + } + if (slots[index] == INVALID_DYNAMIC_SLOT) { + slots[index] = ensure_dynamic_slot(base_path + "/" + std::to_string(index), series); + } + return &series->dynamic_series[slots[index]]; +} + +void append_dynamic_scalar_point(const std::string &path, double tm, double value, SeriesAccumulator *series) { + append_scalar_point(ensure_dynamic_series(path, series), path, tm, value); +} + +void append_event_fast(cereal::Event::Which which, + int32_t eidx_segnum, + kj::ArrayPtr data, + const dbc::Database *can_dbc, + bool skip_raw_can, + double time_offset, + SeriesAccumulator *series) { + if (eidx_segnum != -1) { + return; + } + with_parseable_event(data, [&](const cereal::Event::Reader &event) { + append_event_static_reader(which, event, can_dbc, skip_raw_can, time_offset, series); + }); +} + +void append_events_fast_range(const std::vector &events, + size_t begin, + size_t end, + const dbc::Database *can_dbc, + bool skip_raw_can, + SeriesAccumulator *series) { + for (size_t i = begin; i < end; ++i) { + const Event &event_record = events[i]; + append_event_fast(event_record.which, + event_record.eidx_segnum, + event_record.data, + can_dbc, + skip_raw_can, + 0.0, + series); + } +} + +void merge_route_series(RouteSeries *dst, RouteSeries *src) { + if (src->times.empty()) { + return; + } + if (dst->times.empty()) { + *dst = std::move(*src); + return; + } + + dst->times.reserve(dst->times.size() + src->times.size()); + dst->values.reserve(dst->values.size() + src->values.size()); + dst->times.insert(dst->times.end(), src->times.begin(), src->times.end()); + dst->values.insert(dst->values.end(), src->values.begin(), src->values.end()); +} + +void merge_can_message_data(CanMessageData *dst, CanMessageData *src) { + if (src->samples.empty()) { + return; + } + if (dst->samples.empty()) { + *dst = std::move(*src); + return; + } + dst->samples.reserve(dst->samples.size() + src->samples.size()); + dst->samples.insert(dst->samples.end(), + std::make_move_iterator(src->samples.begin()), + std::make_move_iterator(src->samples.end())); +} + +void merge_series_accumulator(SeriesAccumulator *dst, SeriesAccumulator *src) { + if (dst->fixed_series.size() != src->fixed_series.size()) { + throw std::runtime_error("Fixed-series slot count mismatch during merge"); + } + + for (size_t i = 0; i < dst->fixed_series.size(); ++i) { + merge_route_series(&dst->fixed_series[i], &src->fixed_series[i]); + } + for (auto &series : src->dynamic_series) { + if (series.path.empty()) continue; + RouteSeries &dst_series = dst->dynamic_series[ensure_dynamic_slot(series.path, dst)]; + merge_route_series(&dst_series, &series); + } + for (auto &message : src->can_messages) { + CanMessageData &dst_message = *ensure_can_message(message.id.service, message.id.bus, message.id.address, dst); + merge_can_message_data(&dst_message, &message); + } + for (auto &[path, info] : src->enum_info) { + dst->enum_info.try_emplace(path, std::move(info)); + } +} + +size_t populated_series_count(const SeriesAccumulator &series) { + size_t count = 0; + for (const RouteSeries &fixed : series.fixed_series) { + count += !fixed.times.empty(); + } + for (const RouteSeries &dynamic : series.dynamic_series) { + count += !dynamic.times.empty(); + } + return count; +} + +bool series_is_sorted(const RouteSeries &series) { + for (size_t i = 1; i < series.times.size(); ++i) { + if (series.times[i] < series.times[i - 1]) return false; + } + return true; +} + +void sort_series_by_time(RouteSeries *series) { + if (series->times.size() <= 1 || series_is_sorted(*series)) { + return; + } + std::vector order(series->times.size()); + std::iota(order.begin(), order.end(), 0); + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { + return series->times[a] < series->times[b]; + }); + + std::vector sorted_times(series->times.size()); + std::vector sorted_values(series->values.size()); + for (size_t i = 0; i < order.size(); ++i) { + sorted_times[i] = series->times[order[i]]; + sorted_values[i] = series->values[order[i]]; + } + series->times = std::move(sorted_times); + series->values = std::move(sorted_values); +} + +std::vector collect_series(SeriesAccumulator &&series) { + std::vector out; + out.reserve(series.fixed_series.size() + series.dynamic_series.size()); + for (auto &fixed : series.fixed_series) { + sort_series_by_time(&fixed); + if (!fixed.times.empty()) { + out.push_back(std::move(fixed)); + } + } + for (auto &dynamic : series.dynamic_series) { + sort_series_by_time(&dynamic); + if (!dynamic.times.empty()) { + out.push_back(std::move(dynamic)); + } + } + return out; +} + +RouteData build_route_data(std::vector &&series_list, + std::vector &&can_messages, + std::vector &&logs, + std::vector &&timeline, + std::unordered_map &&enum_info, + std::string car_fingerprint, + std::string dbc_name) { + RouteData route_data; + route_data.series.reserve(series_list.size()); + route_data.paths.reserve(series_list.size()); + for (RouteSeries &series : series_list) { + if (series.times.empty()) continue; + route_data.has_time_range = true; + route_data.x_min = route_data.series.empty() ? series.times.front() : std::min(route_data.x_min, series.times.front()); + route_data.x_max = route_data.series.empty() ? series.times.back() : std::max(route_data.x_max, series.times.back()); + route_data.paths.push_back(series.path); + route_data.series.push_back(std::move(series)); + } + + std::sort(route_data.paths.begin(), route_data.paths.end()); + std::sort(route_data.series.begin(), route_data.series.end(), [](const RouteSeries &a, const RouteSeries &b) { + return a.path < b.path; + }); + std::sort(logs.begin(), logs.end(), [](const LogEntry &a, const LogEntry &b) { + return a.mono_time < b.mono_time; + }); + logs.erase(std::unique(logs.begin(), logs.end(), [](const LogEntry &a, const LogEntry &b) { + return same_log_entry(a, b); + }), + logs.end()); + + std::vector deduped_logs; + deduped_logs.reserve(logs.size()); + for (LogEntry &entry : logs) { + if (!deduped_logs.empty() + && entry.origin == LogOrigin::Alert + && deduped_logs.back().origin == LogOrigin::Alert + && deduped_logs.back().func == entry.func + && deduped_logs.back().message == entry.message) { + continue; + } + deduped_logs.push_back(std::move(entry)); + } + route_data.logs = std::move(deduped_logs); + + if (!route_data.has_time_range && !route_data.logs.empty()) { + route_data.has_time_range = true; + route_data.x_min = route_data.logs.front().mono_time; + route_data.x_max = route_data.logs.back().mono_time; + } + if (!route_data.has_time_range) { + bool initialized = false; + for (const CanMessageData &message : can_messages) { + if (message.samples.empty()) continue; + if (!initialized) { + route_data.x_min = message.samples.front().mono_time; + route_data.x_max = message.samples.back().mono_time; + initialized = true; + } else { + route_data.x_min = std::min(route_data.x_min, message.samples.front().mono_time); + route_data.x_max = std::max(route_data.x_max, message.samples.back().mono_time); + } + } + route_data.has_time_range = initialized; + } + if (!route_data.has_time_range && !timeline.empty()) { + route_data.has_time_range = true; + route_data.x_min = timeline.front().start_time; + route_data.x_max = timeline.back().end_time; + } + + if (route_data.has_time_range) { + const double time_offset = route_data.x_min; + for (RouteSeries &series : route_data.series) { + for (double &tm : series.times) { + tm -= time_offset; + } + } + for (LogEntry &entry : route_data.logs) { + entry.boot_time = entry.mono_time; + entry.mono_time -= time_offset; + } + for (CanMessageData &message : can_messages) { + for (CanFrameSample &sample : message.samples) { + sample.mono_time -= time_offset; + } + } + for (TimelineEntry &entry : timeline) { + entry.start_time -= time_offset; + entry.end_time -= time_offset; + } + route_data.x_max -= time_offset; + route_data.x_min = 0.0; + } + + std::sort(timeline.begin(), timeline.end(), [](const TimelineEntry &a, const TimelineEntry &b) { + return a.start_time < b.start_time; + }); + std::vector merged_timeline; + merged_timeline.reserve(timeline.size()); + for (TimelineEntry &entry : timeline) { + if (!merged_timeline.empty() && merged_timeline.back().type == entry.type) { + merged_timeline.back().end_time = std::max(merged_timeline.back().end_time, entry.end_time); + continue; + } + merged_timeline.push_back(std::move(entry)); + } + route_data.timeline = std::move(merged_timeline); + std::sort(can_messages.begin(), can_messages.end(), [](const CanMessageData &a, const CanMessageData &b) { + return std::make_tuple(a.id.service, a.id.bus, a.id.address) + < std::make_tuple(b.id.service, b.id.bus, b.id.address); + }); + route_data.can_messages = std::move(can_messages); + + route_data.enum_info = std::move(enum_info); + route_data.car_fingerprint = std::move(car_fingerprint); + route_data.dbc_name = std::move(dbc_name); + rebuild_gps_trace(&route_data); + route_data.roots = collect_route_roots_for_paths(route_data.paths); + return route_data; +} + +const RouteSeries *find_route_series(const RouteData &route_data, std::string_view path) { + auto it = std::lower_bound(route_data.series.begin(), route_data.series.end(), path, + [](const RouteSeries &series, std::string_view target) { + return series.path < target; + }); + if (it == route_data.series.end() || it->path != path) return nullptr; + return &(*it); +} + +std::optional sample_series_at_time(const RouteSeries &series, double tm) { + if (series.times.empty() || series.times.size() != series.values.size()) { + return std::nullopt; + } + if (tm <= series.times.front()) { + return series.values.front(); + } + if (tm >= series.times.back()) { + return series.values.back(); + } + auto upper = std::lower_bound(series.times.begin(), series.times.end(), tm); + if (upper == series.times.begin()) { + return series.values.front(); + } + if (upper == series.times.end()) { + return series.values.back(); + } + const size_t upper_index = static_cast(std::distance(series.times.begin(), upper)); + const size_t lower_index = upper_index - 1; + const double t0 = series.times[lower_index]; + const double t1 = series.times[upper_index]; + const double v0 = series.values[lower_index]; + const double v1 = series.values[upper_index]; + if (t1 <= t0) { + return v0; + } + const double alpha = (tm - t0) / (t1 - t0); + return v0 + (v1 - v0) * alpha; +} + +} // namespace + +void rebuild_gps_trace(RouteData *route_data) { + route_data->gps_trace = {}; + const RouteSeries *latitude = find_route_series(*route_data, "/gpsLocationExternal/latitude"); + const RouteSeries *longitude = find_route_series(*route_data, "/gpsLocationExternal/longitude"); + const RouteSeries *has_fix = find_route_series(*route_data, "/gpsLocationExternal/hasFix"); + if (latitude == nullptr || longitude == nullptr || has_fix == nullptr) { + return; + } + + const RouteSeries *bearing = find_route_series(*route_data, "/gpsLocationExternal/bearingDeg"); + size_t count = std::min({latitude->times.size(), latitude->values.size(), + longitude->times.size(), longitude->values.size(), + has_fix->times.size(), has_fix->values.size()}); + if (count == 0) { + return; + } + + bool found = false; + route_data->gps_trace.points.reserve(count); + for (size_t i = 0; i < count; ++i) { + if (has_fix->values[i] < 0.5) { + continue; + } + const double lat = latitude->values[i]; + const double lon = longitude->values[i]; + if (!std::isfinite(lat) || !std::isfinite(lon)) { + continue; + } + const double tm = latitude->times[i]; + const float bearing_value = bearing != nullptr + ? static_cast(sample_series_at_time(*bearing, tm).value_or(0.0)) + : 0.0f; + route_data->gps_trace.points.push_back(GpsPoint{ + .time = tm, + .lat = lat, + .lon = lon, + .bearing = bearing_value, + .type = timeline_type_at_time(route_data->timeline, tm), + }); + if (!found) { + route_data->gps_trace.min_lat = route_data->gps_trace.max_lat = lat; + route_data->gps_trace.min_lon = route_data->gps_trace.max_lon = lon; + found = true; + } else { + route_data->gps_trace.min_lat = std::min(route_data->gps_trace.min_lat, lat); + route_data->gps_trace.max_lat = std::max(route_data->gps_trace.max_lat, lat); + route_data->gps_trace.min_lon = std::min(route_data->gps_trace.min_lon, lon); + route_data->gps_trace.max_lon = std::max(route_data->gps_trace.max_lon, lon); + } + } + if (!found) { + route_data->gps_trace = {}; + } +} + +namespace { + +void build_camera_index(const std::map &segments, + const RouteData &route_data, + std::string SegmentLogs::*file_member, + std::string_view index_name, + CameraFeedIndex *out) { + *out = {}; + out->segment_files.reserve(segments.size()); + + std::unordered_set available_segments; + available_segments.reserve(segments.size()); + for (const auto &[segment_number, segment] : segments) { + const std::string &path = segment.*file_member; + if (path.empty()) continue; + out->segment_files.push_back(CameraSegmentFile{ + .segment = segment_number, + .path = path, + }); + available_segments.insert(segment_number); + } + if (out->segment_files.empty()) { + return; + } + + const std::string prefix = "/" + std::string(index_name); + const RouteSeries *segment_numbers = find_route_series(route_data, prefix + "/segmentNum"); + const RouteSeries *decode_indices = find_route_series(route_data, prefix + "/segmentId"); + if (decode_indices == nullptr) { + decode_indices = find_route_series(route_data, prefix + "/segmentIdEncode"); + } + const RouteSeries *frame_ids = find_route_series(route_data, prefix + "/frameId"); + if (segment_numbers == nullptr || decode_indices == nullptr) { + return; + } + + size_t count = std::min(segment_numbers->times.size(), segment_numbers->values.size()); + count = std::min(count, decode_indices->values.size()); + if (frame_ids != nullptr) { + count = std::min(count, frame_ids->values.size()); + } + out->entries.reserve(count); + for (size_t i = 0; i < count; ++i) { + const int segment_number = static_cast(std::llround(segment_numbers->values[i])); + if (available_segments.find(segment_number) == available_segments.end()) { + continue; + } + const int decode_index = static_cast(std::llround(decode_indices->values[i])); + const uint32_t frame_id = frame_ids != nullptr + ? static_cast(std::llround(frame_ids->values[i])) + : static_cast(std::max(0, decode_index)); + out->entries.push_back(CameraFrameIndexEntry{ + .timestamp = segment_numbers->times[i], + .segment = segment_number, + .decode_index = decode_index, + .frame_id = frame_id, + }); + } + + std::sort(out->entries.begin(), out->entries.end(), + [](const CameraFrameIndexEntry &a, const CameraFrameIndexEntry &b) { + return a.timestamp < b.timestamp; + }); +} + +size_t load_worker_budget() { + size_t worker_count = std::thread::hardware_concurrency(); + if (worker_count == 0) { + worker_count = 1; + } + if (const char *raw = std::getenv("JOTP_LOAD_WORKERS"); raw != nullptr && std::strlen(raw) > 0) { + char *end = nullptr; + const unsigned long parsed = std::strtoul(raw, &end, 10); + if (end != nullptr && *end == '\0' && parsed > 0) { + worker_count = static_cast(parsed); + } + } + return std::max(1, worker_count); +} + +size_t segment_worker_count(size_t segment_count, size_t worker_budget) { + return std::max(1, std::min(worker_budget, segment_count)); +} + +size_t extract_chunk_count(size_t event_count, size_t worker_budget, size_t segment_workers) { + if (event_count < 4096) return 1; + const size_t per_segment_budget = std::max(1, worker_budget / std::max(1, segment_workers)); + const size_t chunk_target = std::max(1, (event_count + 14999) / 15000); + return std::max(1, std::min({per_segment_budget, chunk_target, static_cast(8)})); +} + +SeriesAccumulator extract_segment_series(const std::vector &events, + const SchemaIndex &schema, + const dbc::Database *can_dbc, + bool skip_raw_can, + size_t worker_budget, + size_t segment_workers) { + const size_t chunk_count = extract_chunk_count(events.size(), worker_budget, segment_workers); + if (chunk_count <= 1 || events.empty()) { + SeriesAccumulator series = make_series_accumulator(schema); + append_events_fast_range(events, 0, events.size(), can_dbc, skip_raw_can, &series); + return series; + } + + const size_t events_per_chunk = (events.size() + chunk_count - 1) / chunk_count; + std::vector chunk_results; + chunk_results.reserve(chunk_count); + for (size_t i = 0; i < chunk_count; ++i) { + chunk_results.push_back(make_series_accumulator(schema)); + } + + std::vector workers; + workers.reserve(chunk_count > 0 ? chunk_count - 1 : 0); + for (size_t chunk = 1; chunk < chunk_count; ++chunk) { + workers.emplace_back([&, chunk]() { + const size_t begin = chunk * events_per_chunk; + const size_t end = std::min(events.size(), begin + events_per_chunk); + append_events_fast_range(events, begin, end, can_dbc, skip_raw_can, &chunk_results[chunk]); + }); + } + append_events_fast_range(events, 0, std::min(events.size(), events_per_chunk), can_dbc, skip_raw_can, &chunk_results[0]); + for (std::thread &worker : workers) { + worker.join(); + } + + SeriesAccumulator merged = make_series_accumulator(schema); + for (SeriesAccumulator &chunk : chunk_results) { + merge_series_accumulator(&merged, &chunk); + } + return merged; +} + +LoadedRouteArtifacts load_route_series_parallel( + const std::map &segments, + const SchemaIndex &schema, + const dbc::Database *can_dbc, + LogSelector selector, + bool skip_raw_can, + LoadStats *stats) { + struct SegmentResult { + SeriesAccumulator series; + std::vector logs; + std::vector timeline; + }; + + const std::vector> segment_list(segments.begin(), segments.end()); + std::vector results; + results.reserve(segment_list.size()); + for (size_t i = 0; i < segment_list.size(); ++i) { + results.emplace_back(SegmentResult{make_series_accumulator(schema)}); + } + std::atomic next_segment{0}; + std::mutex error_mutex; + std::string first_error; + const size_t worker_budget = static_cast(stats->num_workers); + const size_t segment_workers = segment_worker_count(segment_list.size(), worker_budget); + + auto worker = [&]() { + while (true) { + const size_t index = next_segment.fetch_add(1); + if (index >= segment_list.size()) { + return; + } + + const auto &[segment_number, segment] = segment_list[index]; + const std::string &log_path = selected_log_path(segment, selector); + LoadStats::SegmentStats &segment_stats = stats->segments[index]; + segment_stats.segment_number = segment_number; + segment_stats.log_path = log_path; + if (log_path.empty()) { + segment_stats.failed = true; + std::lock_guard lock(error_mutex); + if (first_error.empty()) { + first_error = "Missing log path for segment " + std::to_string(segment_number); + } + stats->publish(RouteLoadStage::DownloadingSegment, index, std::to_string(segment_number)); + stats->publish(RouteLoadStage::ParsingSegment, index, std::to_string(segment_number)); + continue; + } + + LogReader reader; + if (!reader.load(log_path, nullptr, true)) { + segment_stats.failed = true; + std::lock_guard lock(error_mutex); + if (first_error.empty()) { + first_error = "Failed to load log segment: " + log_path; + } + stats->publish(RouteLoadStage::DownloadingSegment, index, std::to_string(segment_number)); + stats->publish(RouteLoadStage::ParsingSegment, index, std::to_string(segment_number)); + continue; + } + + segment_stats.download_seconds = reader.download_seconds(); + segment_stats.decompress_seconds = reader.decompress_seconds(); + segment_stats.parse_seconds = reader.parse_seconds(); + segment_stats.compressed_bytes = reader.compressed_size(); + segment_stats.decompressed_bytes = reader.decompressed_size(); + stats->bytes_downloaded.fetch_add(reader.compressed_size()); + stats->segments_downloaded.fetch_add(1); + stats->publish(RouteLoadStage::DownloadingSegment, index, std::to_string(segment_number)); + + const auto extract_start = LoadStats::Clock::now(); + results[index].series = extract_segment_series(reader.events, schema, can_dbc, skip_raw_can, worker_budget, segment_workers); + results[index].logs = extract_segment_logs(reader.events); + results[index].timeline = extract_segment_timeline(reader.events); + segment_stats.extract_seconds = std::chrono::duration(LoadStats::Clock::now() - extract_start).count(); + segment_stats.event_count = reader.events.size(); + segment_stats.series_count = populated_series_count(results[index].series); + stats->segments_parsed.fetch_add(1); + stats->publish(RouteLoadStage::ParsingSegment, index, std::to_string(segment_number)); + } + }; + + std::vector workers; + workers.reserve(segment_workers); + for (size_t i = 0; i < segment_workers; ++i) { + workers.emplace_back(worker); + } + for (std::thread &thread : workers) { + thread.join(); + } + + if (!first_error.empty()) throw std::runtime_error(first_error); + + stats->merge_start = LoadStats::Clock::now(); + SeriesAccumulator merged = make_series_accumulator(schema); + for (size_t i = 0; i < results.size(); ++i) { + merge_series_accumulator(&merged, &results[i].series); + } + std::vector logs; + std::vector timeline; + for (SegmentResult &result : results) { + if (!result.logs.empty()) { + logs.insert(logs.end(), + std::make_move_iterator(result.logs.begin()), + std::make_move_iterator(result.logs.end())); + } + if (!result.timeline.empty()) { + timeline.insert(timeline.end(), + std::make_move_iterator(result.timeline.begin()), + std::make_move_iterator(result.timeline.end())); + } + } + LoadedRouteArtifacts artifacts; + artifacts.series = collect_series(std::move(merged)); + artifacts.can_messages = std::move(merged.can_messages); + artifacts.logs = std::move(logs); + artifacts.timeline = std::move(timeline); + artifacts.enum_info = std::move(merged.enum_info); + stats->merge_end = LoadStats::Clock::now(); + return artifacts; +} + +std::vector collect_layout_roots(const SketchLayout &layout) { + std::vector roots; + for (const auto &tab : layout.tabs) { + for (const auto &pane : tab.panes) { + for (const auto &curve : pane.curves) { + std::string root = "custom"; + if (is_absolute_curve(curve.name)) { + const size_t slash = curve.name.find('/', 1); + root = curve.name.substr(1, slash == std::string::npos ? std::string::npos : slash - 1); + } + if (std::find(roots.begin(), roots.end(), root) == roots.end()) { + roots.push_back(root); + } + } + } + } + if (roots.empty()) { + roots.push_back("layout"); + } + return roots; +} + +} // namespace + +std::vector collect_route_roots_for_paths(const std::vector &paths) { + std::vector roots; + for (const std::string &path : paths) { + if (!is_absolute_curve(path)) continue; + const size_t slash = path.find('/', 1); + const std::string root = path.substr(1, slash == std::string::npos ? std::string::npos : slash - 1); + if (!root.empty() && std::find(roots.begin(), roots.end(), root) == roots.end()) { + roots.push_back(root); + } + } + std::sort(roots.begin(), roots.end()); + return roots; +} + +struct StreamAccumulator::Impl { + const SchemaIndex &schema = SchemaIndex::instance(); + SeriesAccumulator series = make_series_accumulator(schema); + std::vector logs; + std::vector timeline; + std::string last_alert_key; + std::string manual_dbc_name; + std::string detected_dbc_name; + std::string car_fingerprint; + std::optional can_dbc; + std::optional time_offset; + + void refresh_dbc() { + const std::string next_dbc = !manual_dbc_name.empty() ? manual_dbc_name : detect_dbc_for_fingerprint(car_fingerprint); + if (next_dbc == detected_dbc_name) { + return; + } + detected_dbc_name = next_dbc; + can_dbc = load_dbc_by_name(detected_dbc_name); + } +}; + +StreamAccumulator::StreamAccumulator(const std::string &dbc_name, std::optional time_offset) + : impl_(std::make_unique()) { + impl_->manual_dbc_name = dbc_name; + impl_->time_offset = time_offset; + impl_->refresh_dbc(); +} + +StreamAccumulator::~StreamAccumulator() = default; + +void StreamAccumulator::setDbcName(const std::string &dbc_name) { + impl_->manual_dbc_name = dbc_name; + impl_->refresh_dbc(); +} + +void StreamAccumulator::appendEvent(kj::ArrayPtr data) { + with_parseable_event(data, [&](const cereal::Event::Reader &event) { + const cereal::Event::Which which = event.which(); + const double boot_time = static_cast(event.getLogMonoTime()) / 1.0e9; + if (!impl_->time_offset.has_value()) { + impl_->time_offset = boot_time; + } + if (which == cereal::Event::Which::CAR_PARAMS) { + const std::string fingerprint = event.getCarParams().getCarFingerprint().cStr(); + if (!fingerprint.empty() && fingerprint != impl_->car_fingerprint) { + impl_->car_fingerprint = fingerprint; + impl_->refresh_dbc(); + } + } + + append_event_static_reader(which, + event, + impl_->can_dbc ? &*impl_->can_dbc : nullptr, + impl_->can_dbc.has_value(), + *impl_->time_offset, + &impl_->series); + append_log_event(which, event, *impl_->time_offset, &impl_->logs, &impl_->last_alert_key); + if (which == cereal::Event::Which::SELFDRIVE_STATE) { + const auto sd = event.getSelfdriveState(); + append_timeline_entry(&impl_->timeline, boot_time - *impl_->time_offset, + alert_status_to_timeline_type(sd.getAlertStatus(), sd.getEnabled())); + } + }); +} + +void StreamAccumulator::appendCanFrames(CanServiceKind service, const std::vector &frames) { + if (frames.empty()) { + return; + } + if (!impl_->time_offset.has_value()) { + impl_->time_offset = frames.front().mono_time; + } + for (const LiveCanFrame &frame : frames) { + append_live_can_frame(service, + frame, + *impl_->time_offset, + impl_->can_dbc ? &*impl_->can_dbc : nullptr, + &impl_->series); + } +} + +StreamExtractBatch StreamAccumulator::takeBatch() { + StreamExtractBatch batch; + batch.car_fingerprint = impl_->car_fingerprint; + batch.dbc_name = impl_->detected_dbc_name; + if (impl_->time_offset.has_value()) { + batch.has_time_offset = true; + batch.time_offset = *impl_->time_offset; + } + if (impl_->logs.empty() && impl_->timeline.empty() + && populated_series_count(impl_->series) == 0 + && impl_->series.enum_info.empty() + && impl_->series.can_messages.empty()) { + return batch; + } + + SeriesAccumulator emitted = std::move(impl_->series); + batch.can_messages = std::move(emitted.can_messages); + batch.enum_info = std::move(emitted.enum_info); + batch.series = collect_series(std::move(emitted)); + batch.logs = std::move(impl_->logs); + batch.timeline = std::move(impl_->timeline); + impl_->series = make_series_accumulator(impl_->schema); + impl_->logs.clear(); + impl_->timeline.clear(); + return batch; +} + +const std::string &StreamAccumulator::carFingerprint() const { + return impl_->car_fingerprint; +} + +const std::string &StreamAccumulator::dbc_name() const { + return impl_->detected_dbc_name; +} + +std::optional StreamAccumulator::timeOffset() const { + return impl_->time_offset; +} + +SketchLayout load_sketch_layout(const fs::path &layout_path) { + SketchLayout layout = parse_layout(layout_path); + layout.roots = collect_layout_roots(layout); + return layout; +} + +RouteData load_route_data(const std::string &route_name, + const std::string &data_dir, + const std::string &dbc_name, + const RouteLoadProgressCallback &progress) { + if (route_name.empty()) return RouteData{}; + + const RouteSelection route = parse_route_selection(route_name); + if (route.canonical_name.empty() || (data_dir.empty() && route.dongle_id.empty())) { + throw std::runtime_error("Invalid route format: " + route_name); + } + LoadStats stats(progress); + stats.load_start = LoadStats::Clock::now(); + std::map segments = data_dir.empty() + ? load_segments_from_server(route) + : load_segments_from_local(route, data_dir); + segments = trim_segments(std::move(segments), route); + if (segments.empty()) throw std::runtime_error("No log segments found for " + route_name); + stats.resolve_end = LoadStats::Clock::now(); + stats.segment_count = segments.size(); + stats.total_segments.store(segments.size()); + stats.num_workers = static_cast(load_worker_budget()); + stats.segments.resize(segments.size()); + stats.publish(RouteLoadStage::Resolving, 0, {}); + + const RouteMetadata metadata = detect_route_metadata(segments, route.selector); + const std::string resolved_dbc = !dbc_name.empty() ? dbc_name : detect_dbc_for_fingerprint(metadata.car_fingerprint); + const std::optional can_dbc = load_dbc_by_name(resolved_dbc); + + const SchemaIndex &schema = SchemaIndex::instance(); + LoadedRouteArtifacts artifacts = load_route_series_parallel(segments, schema, can_dbc ? &*can_dbc : nullptr, + route.selector, can_dbc.has_value(), &stats); + RouteData route_data = build_route_data(std::move(artifacts.series), + std::move(artifacts.can_messages), + std::move(artifacts.logs), + std::move(artifacts.timeline), + std::move(artifacts.enum_info), + metadata.car_fingerprint, + resolved_dbc); + route_data.route_id = make_route_identifier(route, segments); + build_camera_index(segments, route_data, &SegmentLogs::fcamera, "roadEncodeIdx", &route_data.road_camera); + build_camera_index(segments, route_data, &SegmentLogs::dcamera, "driverEncodeIdx", &route_data.driver_camera); + build_camera_index(segments, route_data, &SegmentLogs::ecamera, "wideRoadEncodeIdx", &route_data.wide_road_camera); + build_camera_index(segments, route_data, &SegmentLogs::qcamera, "qRoadEncodeIdx", &route_data.qroad_camera); + stats.load_end = LoadStats::Clock::now(); + stats.publish(RouteLoadStage::Finished, segments.size(), {}); + stats.print_summary(route_data.series.size()); + return route_data; +} + +RouteIdentifier parse_route_identifier(std::string_view route_name) { + return make_route_identifier(parse_route_selection(std::string(route_name)), {}); +} + +std::vector available_dbc_names() { + return available_dbc_names_impl(); +} + +std::optional load_dbc_by_name(const std::string &dbc_name) { + if (dbc_name.empty()) { + return std::nullopt; + } + try { + return std::optional(std::in_place, resolve_dbc_path(dbc_name)); + } catch (...) { + return std::nullopt; + } +} + +std::vector decode_can_messages(const std::vector &can_messages, + const std::string &dbc_name, + std::unordered_map *enum_info) { + if (enum_info != nullptr) { + enum_info->clear(); + } + const std::optional can_dbc = load_dbc_by_name(dbc_name); + if (!can_dbc.has_value()) { + return {}; + } + + SeriesAccumulator series; + for (const CanMessageData &message : can_messages) { + const char *service_name = message.id.service == CanServiceKind::Can ? "can" : "sendcan"; + for (const CanFrameSample &sample : message.samples) { + decode_can_frame(&*can_dbc, + service_name, + message.id.bus, + message.id.address, + reinterpret_cast(sample.data.data()), + sample.data.size(), + sample.mono_time, + &series); + } + } + if (enum_info != nullptr) { + *enum_info = std::move(series.enum_info); + } + return collect_series(std::move(series)); +} diff --git a/tools/jotpluggler/stream.cc b/tools/jotpluggler/stream.cc new file mode 100644 index 00000000000000..fcfa6585bbf60e --- /dev/null +++ b/tools/jotpluggler/stream.cc @@ -0,0 +1,207 @@ +#include "tools/jotpluggler/internal.h" + +#include + +template +std::optional stream_batch_extreme_time(const StreamExtractBatch &batch, + Cmp cmp, + SeriesAccessor series_time, + LogAccessor log_time_fn) { + std::optional result; + for (const RouteSeries &series : batch.series) { + if (!series.times.empty()) { + const double t = series_time(series); + result = result.has_value() ? cmp(*result, t) : t; + } + } + if (!batch.logs.empty()) { + const double t = log_time_fn(batch); + result = result.has_value() ? cmp(*result, t) : t; + } + if (!batch.timeline.empty()) { + const double t = cmp(batch.timeline.front().start_time, batch.timeline.back().end_time); + result = result.has_value() ? cmp(*result, t) : t; + } + for (const CanMessageData &message : batch.can_messages) { + if (!message.samples.empty()) { + const double t = cmp(message.samples.front().mono_time, message.samples.back().mono_time); + result = result.has_value() ? cmp(*result, t) : t; + } + } + return result; +} + +std::optional earliest_stream_batch_time(const StreamExtractBatch &batch) { + return stream_batch_extreme_time(batch, + [](double a, double b) { return std::min(a, b); }, + [](const RouteSeries &s) { return s.times.front(); }, + [](const StreamExtractBatch &b) { return b.logs.front().mono_time; }); +} + +std::optional latest_stream_batch_time(const StreamExtractBatch &batch) { + return stream_batch_extreme_time(batch, + [](double a, double b) { return std::max(a, b); }, + [](const RouteSeries &s) { return s.times.back(); }, + [](const StreamExtractBatch &b) { return b.logs.back().mono_time; }); +} + +bool layout_has_custom_curves(const SketchLayout &layout) { + for (const WorkspaceTab &tab : layout.tabs) { + for (const Pane &pane : tab.panes) { + for (const Curve &curve : pane.curves) { + if (curve.custom_python.has_value()) return true; + } + } + } + return false; +} + +void append_stream_timeline_entries(std::vector *timeline, std::vector entries) { + for (TimelineEntry &entry : entries) { + if (!timeline->empty() && timeline->back().type == entry.type) { + timeline->back().end_time = std::max(timeline->back().end_time, entry.end_time); + } else { + timeline->push_back(std::move(entry)); + } + } +} + +bool can_message_less(const CanMessageData &a, const CanMessageData &b) { + return std::make_tuple(a.id.service, a.id.bus, a.id.address) + < std::make_tuple(b.id.service, b.id.bus, b.id.address); +} + +void apply_stream_batch(AppSession *session, UiState *state, StreamExtractBatch batch) { + if (batch.has_time_offset) { + session->stream_time_offset = batch.time_offset; + } + if (!batch.car_fingerprint.empty()) { + session->route_data.car_fingerprint = batch.car_fingerprint; + } + if (!batch.dbc_name.empty()) { + session->route_data.dbc_name = batch.dbc_name; + } + if (!batch.enum_info.empty()) { + for (auto &[path, info] : batch.enum_info) { + session->route_data.enum_info[path] = std::move(info); + } + } + + bool new_paths = false; + std::vector new_series; + std::vector touched_paths; + touched_paths.reserve(batch.series.size()); + for (RouteSeries &incoming : batch.series) { + touched_paths.push_back(incoming.path); + auto existing_it = session->series_by_path.find(incoming.path); + if (existing_it == session->series_by_path.end()) { + new_series.push_back(std::move(incoming)); + new_paths = true; + continue; + } + RouteSeries &existing = *existing_it->second; + existing.times.insert(existing.times.end(), incoming.times.begin(), incoming.times.end()); + existing.values.insert(existing.values.end(), incoming.values.begin(), incoming.values.end()); + } + for (RouteSeries &series : new_series) { + session->route_data.paths.push_back(series.path); + session->route_data.series.push_back(std::move(series)); + } + + if (!batch.logs.empty()) { + std::sort(batch.logs.begin(), batch.logs.end(), [](const LogEntry &a, const LogEntry &b) { + return a.mono_time < b.mono_time; + }); + const size_t old_size = session->route_data.logs.size(); + session->route_data.logs.insert(session->route_data.logs.end(), + std::make_move_iterator(batch.logs.begin()), + std::make_move_iterator(batch.logs.end())); + if (old_size > 0 && session->route_data.logs.size() > old_size + && session->route_data.logs[old_size - 1].mono_time > session->route_data.logs[old_size].mono_time) { + std::inplace_merge(session->route_data.logs.begin(), + session->route_data.logs.begin() + static_cast(old_size), + session->route_data.logs.end(), + [](const LogEntry &a, const LogEntry &b) { + return a.mono_time < b.mono_time; + }); + } + } + if (!batch.timeline.empty()) { + append_stream_timeline_entries(&session->route_data.timeline, std::move(batch.timeline)); + } + + for (CanMessageData &incoming : batch.can_messages) { + auto it = std::lower_bound(session->route_data.can_messages.begin(), + session->route_data.can_messages.end(), + incoming, + can_message_less); + if (it == session->route_data.can_messages.end() + || can_message_less(incoming, *it) + || can_message_less(*it, incoming)) { + session->route_data.can_messages.insert(it, std::move(incoming)); + } else { + it->samples.insert(it->samples.end(), + std::make_move_iterator(incoming.samples.begin()), + std::make_move_iterator(incoming.samples.end())); + } + } + + if (new_paths) { + const size_t old_path_count = session->route_data.paths.size() - new_series.size(); + std::sort(session->route_data.paths.begin() + static_cast(old_path_count), session->route_data.paths.end()); + std::inplace_merge(session->route_data.paths.begin(), + session->route_data.paths.begin() + static_cast(old_path_count), + session->route_data.paths.end()); + const size_t old_series_count = session->route_data.series.size() - new_series.size(); + auto series_cmp = [](const RouteSeries &a, const RouteSeries &b) { return a.path < b.path; }; + std::sort(session->route_data.series.begin() + static_cast(old_series_count), + session->route_data.series.end(), series_cmp); + std::inplace_merge(session->route_data.series.begin(), + session->route_data.series.begin() + static_cast(old_series_count), + session->route_data.series.end(), series_cmp); + session->route_data.roots = collect_route_roots_for_paths(session->route_data.paths); + rebuild_route_index(session); + rebuild_browser_nodes(session, state); + state->browser_nodes_dirty = false; + } else { + for (const std::string &path : touched_paths) { + auto series_it = session->series_by_path.find(path); + if (series_it == session->series_by_path.end() || series_it->second == nullptr) continue; + const bool enum_like = session->route_data.enum_info.find(path) != session->route_data.enum_info.end(); + session->route_data.series_formats[path] = compute_series_format(series_it->second->values, enum_like); + } + } + const std::optional earliest_time = earliest_stream_batch_time(batch); + const std::optional latest_time = latest_stream_batch_time(batch); + if (earliest_time.has_value() && latest_time.has_value()) { + if (!session->route_data.has_time_range) { + session->route_data.x_min = *earliest_time; + session->route_data.x_max = *latest_time; + } else { + session->route_data.x_min = std::min(session->route_data.x_min, *earliest_time); + session->route_data.x_max = std::max(session->route_data.x_max, *latest_time); + } + session->route_data.has_time_range = true; + } + + if (new_paths + || std::find(touched_paths.begin(), touched_paths.end(), "/gpsLocationExternal/latitude") != touched_paths.end() + || std::find(touched_paths.begin(), touched_paths.end(), "/gpsLocationExternal/longitude") != touched_paths.end() + || std::find(touched_paths.begin(), touched_paths.end(), "/gpsLocationExternal/hasFix") != touched_paths.end() + || std::find(touched_paths.begin(), touched_paths.end(), "/gpsLocationExternal/bearingDeg") != touched_paths.end()) { + rebuild_gps_trace(&session->route_data); + } + + if (latest_time.has_value() && layout_has_custom_curves(session->layout) + && *latest_time >= session->next_stream_custom_refresh_time) { + refresh_all_custom_curves(session, state); + session->next_stream_custom_refresh_time = *latest_time + 0.1; + } + if (state->follow_latest || !state->has_tracker_time) { + state->tracker_time = session->route_data.x_max; + state->has_tracker_time = session->route_data.has_time_range; + } + if (!state->has_shared_range) { + reset_shared_range(state, *session); + } +} diff --git a/tools/jotpluggler/util.cc b/tools/jotpluggler/util.cc new file mode 100644 index 00000000000000..5c20e795f6ba06 --- /dev/null +++ b/tools/jotpluggler/util.cc @@ -0,0 +1,59 @@ +#include "tools/jotpluggler/util.h" + +#include +#include +#include +#include + +std::string read_file_or_throw(const std::filesystem::path &path) { + const std::string contents = util::read_file(path.string()); + if (!contents.empty() || std::filesystem::exists(path)) { + return contents; + } + throw std::runtime_error("Failed to read " + path.string()); +} + +void write_file_or_throw(const std::filesystem::path &path, const void *data, size_t size) { + ensure_parent_dir(path); + const std::string path_string = path.string(); + const void *bytes = size == 0 ? static_cast("") : data; + if (util::write_file(path_string.c_str(), bytes, size, O_WRONLY | O_CREAT | O_TRUNC) != 0) { + throw std::runtime_error("Failed to write " + path_string); + } +} + +void write_file_or_throw(const std::filesystem::path &path, std::string_view contents) { + write_file_or_throw(path, contents.data(), contents.size()); +} + +void run_system_or_throw(const std::string &command, std::string_view action) { + const int ret = std::system(command.c_str()); + if (ret != 0) { + throw std::runtime_error(util::string_format("%.*s failed with exit code %d", + static_cast(action.size()), action.data(), ret)); + } +} + +CommandResult run_process_capture_output(const std::vector &args) { + std::string command; + for (const std::string &arg : args) { + if (!command.empty()) command += ' '; + command += shell_quote(arg); + } + command += " 2>&1"; + + FILE *pipe = popen(command.c_str(), "r"); + if (pipe == nullptr) { + throw std::runtime_error("popen() failed"); + } + + CommandResult result; + std::array buf = {}; + while (fgets(buf.data(), static_cast(buf.size()), pipe) != nullptr) { + result.output += buf.data(); + } + + const int status = pclose(pipe); + result.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : 1; + return result; +} diff --git a/tools/jotpluggler/util.h b/tools/jotpluggler/util.h new file mode 100644 index 00000000000000..ea77a236f0e487 --- /dev/null +++ b/tools/jotpluggler/util.h @@ -0,0 +1,103 @@ +#pragma once + +#include "common/util.h" +#include "imgui.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +inline ImVec4 color_rgb(int r, int g, int b, float alpha = 1.0f) { + return ImVec4(static_cast(r) / 255.0f, + static_cast(g) / 255.0f, + static_cast(b) / 255.0f, + alpha); +} + +inline ImVec4 color_rgb(const std::array &color, float alpha = 1.0f) { + return color_rgb(color[0], color[1], color[2], alpha); +} + +inline std::string lowercase_copy(std::string_view value) { + std::string out(value); + std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return out; +} + +inline int imgui_resize_callback(ImGuiInputTextCallbackData *data) { + if (data->EventFlag != ImGuiInputTextFlags_CallbackResize || data->UserData == nullptr) return 0; + auto *text = static_cast(data->UserData); + text->resize(static_cast(data->BufTextLen)); + data->Buf = text->data(); + return 0; +} + +inline bool input_text_string(const char *label, + std::string *text, + ImGuiInputTextFlags flags = 0) { + flags |= ImGuiInputTextFlags_CallbackResize; + return ImGui::InputText(label, text->data(), text->capacity() + 1, + flags, imgui_resize_callback, text); +} + +inline bool input_text_with_hint_string(const char *label, + const char *hint, + std::string *text, + ImGuiInputTextFlags flags = 0) { + flags |= ImGuiInputTextFlags_CallbackResize; + return ImGui::InputTextWithHint(label, hint, text->data(), text->capacity() + 1, + flags, imgui_resize_callback, text); +} + +inline bool input_text_multiline_string(const char *label, + std::string *text, + const ImVec2 &size = ImVec2(0.0f, 0.0f), + ImGuiInputTextFlags flags = 0) { + flags |= ImGuiInputTextFlags_CallbackResize; + return ImGui::InputTextMultiline(label, text->data(), text->capacity() + 1, + size, flags, imgui_resize_callback, text); +} + +inline bool is_local_stream_address(std::string_view address) { + return address.empty() || address == "127.0.0.1" || address == "localhost"; +} + +inline void ensure_parent_dir(const std::filesystem::path &path) { + if (path.has_parent_path()) { + std::filesystem::create_directories(path.parent_path()); + } +} + +inline std::string shell_quote(std::string_view value) { + std::string quoted; + quoted.reserve(value.size() + 8); + quoted.push_back('\''); + for (char c : value) { + if (c == '\'') { + quoted += "'\\''"; + } else { + quoted.push_back(c); + } + } + quoted.push_back('\''); + return quoted; +} + +struct CommandResult { + int exit_code = 0; + std::string output; +}; + +std::string read_file_or_throw(const std::filesystem::path &path); +void write_file_or_throw(const std::filesystem::path &path, std::string_view contents); +void write_file_or_throw(const std::filesystem::path &path, const void *data, size_t size); +void run_system_or_throw(const std::string &command, std::string_view action); +CommandResult run_process_capture_output(const std::vector &args); diff --git a/tools/joystick/README.md b/tools/joystick/README.md index aea93dad535ca5..eb67060ca85b06 100644 --- a/tools/joystick/README.md +++ b/tools/joystick/README.md @@ -2,33 +2,33 @@ **Hardware needed**: device running openpilot, laptop, joystick (optional) -With joystickd, you can connect your laptop to your comma device over the network and debug controls using a joystick or keyboard. -joystickd uses [inputs](https://pypi.org/project/inputs) which supports many common gamepads and joysticks. +With joystick_control, you can connect your laptop to your comma device over the network and debug controls using a joystick or keyboard. +joystick_control uses [inputs](https://pypi.org/project/inputs) which supports many common gamepads and joysticks. ## Usage -The car must be off, and openpilot must be offroad before starting `joystickd`. +The car must be off, and openpilot must be offroad before starting `joystick_control`. ### Using a keyboard -SSH into your comma device and start joystickd with the following command: +SSH into your comma device and start joystick_control with the following command: ```shell -tools/joystick/joystickd.py --keyboard +tools/joystick/joystick_control.py --keyboard ``` The available buttons and axes will print showing their key mappings. In general, the WASD keys control gas and brakes and steering torque in 5% increments. ### Joystick on your comma three -Plug the joystick into your comma three aux USB-C port. Then, SSH into the device and start `joystickd.py`. +Plug the joystick into your comma three aux USB-C port. Then, SSH into the device and start `joystick_control.py`. ### Joystick on your laptop -In order to use a joystick over the network, we need to run joystickd locally from your laptop and have it send `testJoystick` packets over the network to the comma device. +In order to use a joystick over the network, we need to run joystick_control locally from your laptop and have it send `testJoystick` packets over the network to the comma device. 1. Connect a joystick to your PC. -2. Connect your laptop to your comma device's hotspot and open a new SSH shell. Since joystickd is being run on your laptop, we need to write a parameter to let controlsd know to start in joystick debug mode: +2. Connect your laptop to your comma device's hotspot and open a new SSH shell. Since joystick_control is being run on your laptop, we need to write a parameter to let controlsd know to start in joystick debug mode: ```shell # on your comma device echo -n "1" > /data/params/d/JoystickDebugMode @@ -38,11 +38,11 @@ In order to use a joystick over the network, we need to run joystickd locally fr # on your comma device cereal/messaging/bridge {LAPTOP_IP} testJoystick ``` -4. Start joystickd on your laptop in ZMQ mode. +4. Start joystick_control on your laptop in ZMQ mode. ```shell # on your laptop export ZMQ=1 - tools/joystick/joystickd.py + tools/joystick/joystick_control.py ``` --- diff --git a/tools/joystick/joystick_control.py b/tools/joystick/joystick_control.py new file mode 100755 index 00000000000000..b1f14043b759ae --- /dev/null +++ b/tools/joystick/joystick_control.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +import os +import argparse +import threading +import numpy as np +from inputs import UnpluggedError, get_gamepad + +from cereal import messaging +from openpilot.common.params import Params +from openpilot.common.realtime import Ratekeeper +from openpilot.system.hardware import HARDWARE +from openpilot.tools.lib.kbhit import KBHit + +EXPO = 0.4 + + +class Keyboard: + def __init__(self): + self.kb = KBHit() + self.axis_increment = 0.05 # 5% of full actuation each key press + self.axes_map = {'w': 'gb', 's': 'gb', + 'a': 'steer', 'd': 'steer'} + self.axes_values = {'gb': 0., 'steer': 0.} + self.axes_order = ['gb', 'steer'] + self.cancel = False + + def update(self): + key = self.kb.getch().lower() + self.cancel = False + if key == 'r': + self.axes_values = dict.fromkeys(self.axes_values, 0.) + elif key == 'c': + self.cancel = True + elif key in self.axes_map: + axis = self.axes_map[key] + incr = self.axis_increment if key in ['w', 'a'] else -self.axis_increment + self.axes_values[axis] = float(np.clip(self.axes_values[axis] + incr, -1, 1)) + else: + return False + return True + + +class Joystick: + def __init__(self): + # This class supports a PlayStation 5 DualSense controller on the comma 3X + # TODO: find a way to get this from API or detect gamepad/PC, perhaps "inputs" doesn't support it + self.cancel_button = 'BTN_NORTH' # BTN_NORTH=X/triangle + if HARDWARE.get_device_type() == 'pc': + accel_axis = 'ABS_Z' + steer_axis = 'ABS_RX' + # TODO: once the longcontrol API is finalized, we can replace this with outputting gas/brake and steering + self.flip_map = {'ABS_RZ': accel_axis} + else: + accel_axis = 'ABS_RX' + steer_axis = 'ABS_Z' + self.flip_map = {'ABS_RY': accel_axis} + + self.min_axis_value = {accel_axis: 0., steer_axis: 0.} + self.max_axis_value = {accel_axis: 255., steer_axis: 255.} + self.axes_values = {accel_axis: 0., steer_axis: 0.} + self.axes_order = [accel_axis, steer_axis] + self.cancel = False + + def update(self): + try: + joystick_event = get_gamepad()[0] + except (OSError, UnpluggedError): + self.axes_values = dict.fromkeys(self.axes_values, 0.) + return False + + event = (joystick_event.code, joystick_event.state) + + # flip left trigger to negative accel + if event[0] in self.flip_map: + event = (self.flip_map[event[0]], -event[1]) + + if event[0] == self.cancel_button: + if event[1] == 1: + self.cancel = True + elif event[1] == 0: # state 0 is falling edge + self.cancel = False + elif event[0] in self.axes_values: + self.max_axis_value[event[0]] = max(event[1], self.max_axis_value[event[0]]) + self.min_axis_value[event[0]] = min(event[1], self.min_axis_value[event[0]]) + + norm = -float(np.interp(event[1], [self.min_axis_value[event[0]], self.max_axis_value[event[0]]], [-1., 1.])) + norm = norm if abs(norm) > 0.03 else 0. # center can be noisy, deadzone of 3% + self.axes_values[event[0]] = EXPO * norm ** 3 + (1 - EXPO) * norm # less action near center for fine control + else: + return False + return True + + +def send_thread(joystick): + pm = messaging.PubMaster(['testJoystick']) + + rk = Ratekeeper(100, print_delay_threshold=None) + + while True: + if rk.frame % 20 == 0: + print('\n' + ', '.join(f'{name}: {round(v, 3)}' for name, v in joystick.axes_values.items())) + + joystick_msg = messaging.new_message('testJoystick') + joystick_msg.valid = True + joystick_msg.testJoystick.axes = [joystick.axes_values[ax] for ax in joystick.axes_order] + + pm.send('testJoystick', joystick_msg) + + rk.keep_time() + + +def joystick_control_thread(joystick): + Params().put_bool('JoystickDebugMode', True, block=True) + threading.Thread(target=send_thread, args=(joystick,), daemon=True).start() + while True: + joystick.update() + + +def main(): + joystick_control_thread(Joystick()) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Publishes events from your joystick to control your car.\n' + + 'openpilot must be offroad before starting joystick_control. This tool supports ' + + 'a PlayStation 5 DualSense controller on the comma 3X.', + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument('--keyboard', action='store_true', help='Use your keyboard instead of a joystick') + args = parser.parse_args() + + if not Params().get_bool("IsOffroad") and "ZMQ" not in os.environ: + print("The car must be off before running joystick_control.") + exit() + + print() + if args.keyboard: + print('Gas/brake control: `W` and `S` keys') + print('Steering control: `A` and `D` keys') + print('Buttons') + print('- `R`: Resets axes') + print('- `C`: Cancel cruise control') + else: + print('Using joystick, make sure to run cereal/messaging/bridge on your device if running over the network!') + print('If not running on a comma device, the mapping may need to be adjusted.') + + joystick = Keyboard() if args.keyboard else Joystick() + joystick_control_thread(joystick) diff --git a/tools/joystick/joystickd.py b/tools/joystick/joystickd.py index bb8f48383589d8..789dad562318f2 100755 --- a/tools/joystick/joystickd.py +++ b/tools/joystick/joystickd.py @@ -1,119 +1,81 @@ #!/usr/bin/env python3 -import os -import argparse -import threading -from inputs import get_gamepad - -import cereal.messaging as messaging -from openpilot.common.realtime import Ratekeeper -from openpilot.common.numpy_fast import interp, clip + +import math +import numpy as np + +from cereal import messaging, car +from opendbc.car.vehicle_model import VehicleModel +from openpilot.common.realtime import DT_CTRL, Ratekeeper from openpilot.common.params import Params -from openpilot.tools.lib.kbhit import KBHit - -JS_EXPO = 0.4 - - -class Keyboard: - def __init__(self): - self.kb = KBHit() - self.axis_increment = 0.05 # 5% of full actuation each key press - self.axes_map = {'w': 'gb', 's': 'gb', - 'a': 'steer', 'd': 'steer'} - self.axes_values = {'gb': 0., 'steer': 0.} - self.axes_order = ['gb', 'steer'] - self.cancel = False - - def update(self): - key = self.kb.getch().lower() - self.cancel = False - if key == 'r': - self.axes_values = {ax: 0. for ax in self.axes_values} - elif key == 'c': - self.cancel = True - elif key in self.axes_map: - axis = self.axes_map[key] - incr = self.axis_increment if key in ['w', 'a'] else -self.axis_increment - self.axes_values[axis] = clip(self.axes_values[axis] + incr, -1, 1) - else: - return False - return True - - -class Joystick: - def __init__(self): - # This class supports a PlayStation 5 DualSense controller on the comma 3X - # TODO: find a way to get this from API or detect gamepad/PC, perhaps "inputs" doesn't support it - # TODO: the mapping can also be wrong on PC depending on the driver - self.cancel_button = 'BTN_NORTH' # BTN_NORTH=X/triangle - accel_axis = 'ABS_Y' - steer_axis = 'ABS_Z' - self.min_axis_value = {accel_axis: 0., steer_axis: 0.} - self.max_axis_value = {accel_axis: 255., steer_axis: 255.} - self.axes_values = {accel_axis: 0., steer_axis: 0.} - self.axes_order = [accel_axis, steer_axis] - self.cancel = False - - def update(self): - joystick_event = get_gamepad()[0] - event = (joystick_event.code, joystick_event.state) - if event[0] == self.cancel_button: - if event[1] == 1: - self.cancel = True - elif event[1] == 0: # state 0 is falling edge - self.cancel = False - elif event[0] in self.axes_values: - self.max_axis_value[event[0]] = max(event[1], self.max_axis_value[event[0]]) - self.min_axis_value[event[0]] = min(event[1], self.min_axis_value[event[0]]) - - norm = -interp(event[1], [self.min_axis_value[event[0]], self.max_axis_value[event[0]]], [-1., 1.]) - norm = norm if abs(norm) > 0.02 else 0. # center can be noisy, deadzone of 2% - self.axes_values[event[0]] = JS_EXPO * norm ** 3 + (1 - JS_EXPO) * norm # less action near center for fine control - else: - return False - return True +from openpilot.common.swaglog import cloudlog + +LongCtrlState = car.CarControl.Actuators.LongControlState +MAX_LAT_ACCEL = 3.0 + +def joystickd_thread(): + params = Params() + cloudlog.info("joystickd is waiting for CarParams") + CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + VM = VehicleModel(CP) + + sm = messaging.SubMaster(['carState', 'onroadEvents', 'liveParameters', 'selfdriveState', 'testJoystick'], frequency=1. / DT_CTRL) + pm = messaging.PubMaster(['carControl', 'controlsState']) -def send_thread(joystick): - joystick_sock = messaging.pub_sock('testJoystick') rk = Ratekeeper(100, print_delay_threshold=None) while 1: - dat = messaging.new_message('testJoystick') - dat.testJoystick.axes = [joystick.axes_values[a] for a in joystick.axes_order] - dat.testJoystick.buttons = [joystick.cancel] - joystick_sock.send(dat.to_bytes()) - print('\n' + ', '.join(f'{name}: {round(v, 3)}' for name, v in joystick.axes_values.items())) + sm.update(0) + + cc_msg = messaging.new_message('carControl') + cc_msg.valid = True + CC = cc_msg.carControl + CC.enabled = sm['selfdriveState'].enabled + CC.latActive = sm['selfdriveState'].active and not sm['carState'].steerFaultTemporary and not sm['carState'].steerFaultPermanent + CC.longActive = CC.enabled and not any(e.overrideLongitudinal for e in sm['onroadEvents']) and CP.openpilotLongitudinalControl + CC.cruiseControl.cancel = sm['carState'].cruiseState.enabled and (not CC.enabled or not CP.pcmCruise) + CC.hudControl.leadDistanceBars = 2 + + actuators = CC.actuators + + # reset joystick if it hasn't been received in a while + should_reset_joystick = sm.recv_frame['testJoystick'] == 0 or (sm.frame - sm.recv_frame['testJoystick'])*DT_CTRL > 0.2 + + if not should_reset_joystick: + joystick_axes = sm['testJoystick'].axes + else: + joystick_axes = [0.0, 0.0] + + if CC.longActive: + actuators.accel = 4.0 * float(np.clip(joystick_axes[0], -1, 1)) + actuators.longControlState = LongCtrlState.pid if sm['carState'].vEgo > CP.vEgoStopping else LongCtrlState.stopping + CC.cruiseControl.resume = actuators.accel > 0.0 + + if CC.latActive: + max_curvature = MAX_LAT_ACCEL / max(sm['carState'].vEgo ** 2, 5) + max_angle = math.degrees(VM.get_steer_from_curvature(max_curvature, sm['carState'].vEgo, sm['liveParameters'].roll)) + + actuators.torque = float(np.clip(joystick_axes[1], -1, 1)) + actuators.steeringAngleDeg, actuators.curvature = actuators.torque * max_angle, actuators.torque * -max_curvature + + pm.send('carControl', cc_msg) + + cs_msg = messaging.new_message('controlsState') + cs_msg.valid = True + controlsState = cs_msg.controlsState + controlsState.lateralControlState.init('debugState') + + lp = sm['liveParameters'] + steer_angle_without_offset = math.radians(sm['carState'].steeringAngleDeg - lp.angleOffsetDeg) + controlsState.curvature = -VM.calc_curvature(steer_angle_without_offset, sm['carState'].vEgo, lp.roll) + + pm.send('controlsState', cs_msg) + rk.keep_time() -def joystick_thread(joystick): - Params().put_bool('JoystickDebugMode', True) - threading.Thread(target=send_thread, args=(joystick,), daemon=True).start() - while True: - joystick.update() - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Publishes events from your joystick to control your car.\n' + - 'openpilot must be offroad before starting joystickd. This tool supports ' + - 'a PlayStation 5 DualSense controller on the comma 3X.', - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument('--keyboard', action='store_true', help='Use your keyboard instead of a joystick') - args = parser.parse_args() - - if not Params().get_bool("IsOffroad") and "ZMQ" not in os.environ: - print("The car must be off before running joystickd.") - exit() - - print() - if args.keyboard: - print('Gas/brake control: `W` and `S` keys') - print('Steering control: `A` and `D` keys') - print('Buttons') - print('- `R`: Resets axes') - print('- `C`: Cancel cruise control') - else: - print('Using joystick, make sure to run cereal/messaging/bridge on your device if running over the network!') - print('If not running on a comma device, the mapping may need to be adjusted.') - - joystick = Keyboard() if args.keyboard else Joystick() - joystick_thread(joystick) +def main(): + joystickd_thread() + + +if __name__ == "__main__": + main() diff --git a/tools/latencylogger/README.md b/tools/latencylogger/README.md deleted file mode 100644 index 24169dfaefe3f9..00000000000000 --- a/tools/latencylogger/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# LatencyLogger - -LatencyLogger is a tool to track the time from first pixel to actuation. Timestamps are printed in a table as well as plotted in a graph. Start openpilot with `LOG_TIMESTAMPS=1` set to enable the necessary logging. - -## Usage - -``` -$ python3 latency_logger.py -h -usage: latency_logger.py [-h] [--relative] [--demo] [--plot] [route_or_segment_name] - -A tool for analyzing openpilot's end-to-end latency - -positional arguments: - route_or_segment_name - The route to print (default: None) - -optional arguments: - -h, --help show this help message and exit - --relative Make timestamps relative to the start of each frame (default: False) - --demo Use the demo route instead of providing one (default: False) - --plot If a plot should be generated (default: False) - --offset Offset service to better visualize overlap (default: False) -``` -To timestamp an event, use `LOGT("msg")` in c++ code or `cloudlog.timestamp("msg")` in python code. If the print is warning for frameId assignment ambiguity, use `LOGT(frameId ,"msg")`. - -## Examples - -Timestamps are visualized as diamonds - -| | Relative | Absolute | -| ------------- | ------------- | ------------- | -| Inline | ![inrel](https://user-images.githubusercontent.com/42323981/170559939-465df3b1-bf87-46d5-b5ee-5cc87dc49470.png) | ![inabs](https://user-images.githubusercontent.com/42323981/170559985-a82f87e7-82c4-4e48-a348-4221568dd589.png) | -| Offset | ![offrel](https://user-images.githubusercontent.com/42323981/170559854-93fba90f-acc4-4d08-b317-d3f8fc649ea8.png) | ![offabs](https://user-images.githubusercontent.com/42323981/170559782-06ed5599-d4e3-4701-ad78-5c1eec6cb61e.png) | - -Printed timestamps of a frame with internal durations. -``` -Frame ID: 1202 - camerad - wideRoadCameraState start of frame 0.0 - roadCameraState start of frame 0.049583 - wideRoadCameraState published 35.01206 - WideRoadCamera: Image set 35.020028 - roadCameraState published 38.508261 - RoadCamera: Image set 38.520344 - RoadCamera: Transformed 38.616176 - wideRoadCameraState.processingTime 3.152403049170971 - roadCameraState.processingTime 6.453451234847307 - modeld - Image added 40.909841 - Extra image added 42.515027 - Execution finished 63.002552 - modelV2 published 63.148747 - modelV2.modelExecutionTime 23.62649142742157 - modelV2.gpuExecutionTime 0.0 - plannerd - longitudinalPlan published 69.715999 - longitudinalPlan.solverExecutionTime 0.5619999719783664 - controlsd - Data sampled 70.217763 - Events updated 71.037178 - sendcan published 72.278775 - controlsState published 72.825226 - Data sampled 80.008354 - Events updated 80.787666 - sendcan published 81.849682 - controlsState published 82.238323 - Data sampled 90.521123 - Events updated 91.626003 - sendcan published 93.413218 - controlsState published 94.143989 - Data sampled 100.991497 - Events updated 101.973774 - sendcan published 103.565575 - controlsState published 104.146088 - Data sampled 110.284387 - Events updated 111.183541 - sendcan published 112.981692 - controlsState published 113.731994 - pandad - sending sendcan to panda: 250027001751393037323631 81.928119 - sendcan sent to panda: 250027001751393037323631 82.164834 - sending sendcan to panda: 250027001751393037323631 93.569986 - sendcan sent to panda: 250027001751393037323631 93.92795 - sending sendcan to panda: 250027001751393037323631 103.689167 - sendcan sent to panda: 250027001751393037323631 104.012235 - sending sendcan to panda: 250027001751393037323631 113.109555 - sendcan sent to panda: 250027001751393037323631 113.525487 - sending sendcan to panda: 250027001751393037323631 122.508434 - sendcan sent to panda: 250027001751393037323631 122.834314 -``` diff --git a/tools/latencylogger/latency_logger.py b/tools/latencylogger/latency_logger.py deleted file mode 100755 index f145cc35e47d96..00000000000000 --- a/tools/latencylogger/latency_logger.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import json -import matplotlib.patches as mpatches -import matplotlib.pyplot as plt -import sys -from bisect import bisect_left, bisect_right -from collections import defaultdict - -from openpilot.tools.lib.logreader import LogReader - -DEMO_ROUTE = "9f583b1d93915c31|2022-05-18--10-49-51--0" - -SERVICES = ['camerad', 'modeld', 'plannerd', 'controlsd', 'pandad'] -MONOTIME_KEYS = ['modelMonoTime', 'lateralPlanMonoTime'] -MSGQ_TO_SERVICE = { - 'roadCameraState': 'camerad', - 'wideRoadCameraState': 'camerad', - 'modelV2': 'modeld', - 'longitudinalPlan': 'plannerd', - 'sendcan': 'controlsd', - 'controlsState': 'controlsd' -} -SERVICE_TO_DURATIONS = { - 'camerad': ['processingTime'], - 'modeld': ['modelExecutionTime', 'gpuExecutionTime'], - 'plannerd': ['solverExecutionTime'], -} - -def read_logs(lr): - data = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) - mono_to_frame = {} - frame_mismatches = [] - frame_id_fails = 0 - latest_sendcan_monotime = 0 - for msg in lr: - if msg.which() == 'sendcan': - latest_sendcan_monotime = msg.logMonoTime - continue - - if msg.which() in MSGQ_TO_SERVICE: - service = MSGQ_TO_SERVICE[msg.which()] - msg_obj = getattr(msg, msg.which()) - - frame_id = -1 - if hasattr(msg_obj, "frameId"): - frame_id = msg_obj.frameId - else: - continue_outer = False - for key in MONOTIME_KEYS: - if hasattr(msg_obj, key): - if getattr(msg_obj, key) == 0: - # Filter out controlsd messages which arrive before the camera loop - continue_outer = True - elif getattr(msg_obj, key) in mono_to_frame: - frame_id = mono_to_frame[getattr(msg_obj, key)] - if continue_outer: - continue - if frame_id == -1: - frame_id_fails += 1 - continue - mono_to_frame[msg.logMonoTime] = frame_id - data['timestamp'][frame_id][service].append((msg.which()+" published", msg.logMonoTime)) - - next_service = SERVICES[SERVICES.index(service)+1] - if not data['start'][frame_id][next_service]: - data['start'][frame_id][next_service] = msg.logMonoTime - data['end'][frame_id][service] = msg.logMonoTime - - if service in SERVICE_TO_DURATIONS: - for duration in SERVICE_TO_DURATIONS[service]: - data['duration'][frame_id][service].append((msg.which()+"."+duration, getattr(msg_obj, duration))) - - if service == SERVICES[0]: - data['timestamp'][frame_id][service].append((msg.which()+" start of frame", msg_obj.timestampSof)) - if not data['start'][frame_id][service]: - data['start'][frame_id][service] = msg_obj.timestampSof - elif msg.which() == 'controlsState': - # Sendcan is published before controlsState, but the frameId is retrieved in CS - data['timestamp'][frame_id][service].append(("sendcan published", latest_sendcan_monotime)) - elif msg.which() == 'modelV2': - if msg_obj.frameIdExtra != frame_id: - frame_mismatches.append(frame_id) - - if frame_id_fails > 20: - print("Warning, many frameId fetch fails", frame_id_fails) - if len(frame_mismatches) > 20: - print("Warning, many frame mismatches", len(frame_mismatches)) - return (data, frame_mismatches) - -# This is not needed in 3.10 as a "key" parameter is added to bisect -class KeyifyList: - def __init__(self, inner, key): - self.inner = inner - self.key = key - def __len__(self): - return len(self.inner) - def __getitem__(self, k): - return self.key(self.inner[k]) - -def find_frame_id(time, service, start_times, end_times): - left = bisect_left(KeyifyList(list(start_times.items()), - lambda x: x[1][service] if x[1][service] else -1), time) - 1 - right = bisect_right(KeyifyList(list(end_times.items()), - lambda x: x[1][service] if x[1][service] else float("inf")), time) - return left, right - -def find_t0(start_times, frame_id=-1): - frame_id = frame_id if frame_id > -1 else min(start_times.keys()) - m = max(start_times.keys()) - while frame_id <= m: - for service in SERVICES: - if start_times[frame_id][service]: - return start_times[frame_id][service] - frame_id += 1 - raise Exception('No start time has been set') - -def insert_cloudlogs(lr, timestamps, start_times, end_times): - # at least one cloudlog must be made in controlsd - - t0 = find_t0(start_times) - failed_inserts = 0 - latest_controls_frameid = 0 - for msg in lr: - if msg.which() == "logMessage": - jmsg = json.loads(msg.logMessage) - if "timestamp" in jmsg['msg']: - time = int(jmsg['msg']['timestamp']['time']) - service = jmsg['ctx']['daemon'] - event = jmsg['msg']['timestamp']['event'] - if time < t0: - # Filter out controlsd messages which arrive before the camera loop - continue - - if "frame_id" in jmsg['msg']['timestamp']: - timestamps[int(jmsg['msg']['timestamp']['frame_id'])][service].append((event, time)) - continue - - if service == "pandad": - timestamps[latest_controls_frameid][service].append((event, time)) - end_times[latest_controls_frameid][service] = time - else: - frame_id = find_frame_id(time, service, start_times, end_times) - if frame_id: - if frame_id[0] != frame_id[1]: - event += " (warning: ambiguity)" - frame_id = frame_id[0] - if service == 'controlsd': - latest_controls_frameid = frame_id - timestamps[frame_id][service].append((event, time)) - else: - failed_inserts += 1 - - if latest_controls_frameid == 0: - print("Warning: failed to bind pandad logs to a frame ID. Add a timestamp cloudlog in controlsd.") - elif failed_inserts > len(timestamps): - print(f"Warning: failed to bind {failed_inserts} cloudlog timestamps to a frame ID") - -def print_timestamps(timestamps, durations, start_times, relative): - t0 = find_t0(start_times) - for frame_id in timestamps.keys(): - print('='*80) - print("Frame ID:", frame_id) - if relative: - t0 = find_t0(start_times, frame_id) - - for service in SERVICES: - print(" "+service) - events = timestamps[frame_id][service] - for event, time in sorted(events, key = lambda x: x[1]): - print(" "+'%-53s%-53s' %(event, str((time-t0)/1e6))) - for event, time in durations[frame_id][service]: - print(" "+'%-53s%-53s' %(event, str(time*1000))) - -def graph_timestamps(timestamps, start_times, end_times, relative, offset_services=False, title=""): - plt.rcParams.update({'font.size': 18}) - - t0 = find_t0(start_times) - fig, ax = plt.subplots() - ax.set_xlim(0, 130 if relative else 750) - ax.set_ylim(0, 17) - ax.set_xlabel('Time (milliseconds)') - colors = ['blue', 'green', 'red', 'yellow', 'purple'] - offsets = [[0, -5*j] for j in range(len(SERVICES))] if offset_services else None - height = 0.3 if offset_services else 0.9 - assert len(colors) == len(SERVICES), 'Each service needs a color' - - points = {"x": [], "y": [], "labels": []} - for i, (frame_id, services) in enumerate(timestamps.items()): - if relative: - t0 = find_t0(start_times, frame_id) - service_bars = [] - for service, events in services.items(): - if start_times[frame_id][service] and end_times[frame_id][service]: - start = start_times[frame_id][service] - end = end_times[frame_id][service] - service_bars.append(((start-t0)/1e6,(end-start)/1e6)) - for event in events: - points['x'].append((event[1]-t0)/1e6) - points['y'].append(i) - points['labels'].append(event[0]) - ax.broken_barh(service_bars, (i-height/2, height), facecolors=(colors), alpha=0.5, offsets=offsets) - - ax.scatter(points['x'], points['y'], marker='d', edgecolor='black') - for i, label in enumerate(points['labels']): - ax.annotate(label, (points['x'][i], points['y'][i]), textcoords="offset points", xytext=(0,10), ha='center') - - plt.title(title) - fig.set_size_inches(18, 9) - plt.legend(handles=[mpatches.Patch(color=colors[i], label=SERVICES[i]) for i in range(len(SERVICES))]) - plt.show() - -def get_timestamps(lr): - lr = list(lr) - data, frame_mismatches = read_logs(lr) - insert_cloudlogs(lr, data['timestamp'], data['start'], data['end']) - return data, frame_mismatches - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="A tool for analyzing openpilot's end-to-end latency", - formatter_class = argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("--relative", action="store_true", help="Make timestamps relative to the start of each frame") - parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") - parser.add_argument("--plot", action="store_true", help="If a plot should be generated") - parser.add_argument("--offset", action="store_true", help="Vertically offset service to better visualize overlap") - parser.add_argument("route_or_segment_name", nargs='?', help="The route to print") - - if len(sys.argv) == 1: - parser.print_help() - sys.exit() - args = parser.parse_args() - - r = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() - lr = LogReader(r, sort_by_time=True) - - data, _ = get_timestamps(lr) - print_timestamps(data['timestamp'], data['duration'], data['start'], args.relative) - if args.plot: - graph_timestamps(data['timestamp'], data['start'], data['end'], args.relative, offset_services=args.offset, title=r) diff --git a/tools/lateral_maneuvers/.gitignore b/tools/lateral_maneuvers/.gitignore new file mode 100644 index 00000000000000..a0b6efe6b3f9a1 --- /dev/null +++ b/tools/lateral_maneuvers/.gitignore @@ -0,0 +1 @@ +/lateral_reports/ diff --git a/tools/lateral_maneuvers/README.md b/tools/lateral_maneuvers/README.md new file mode 100644 index 00000000000000..3a54bc74099bef --- /dev/null +++ b/tools/lateral_maneuvers/README.md @@ -0,0 +1,42 @@ +# Lateral Maneuvers Testing Tool + +> [!WARNING] +> Use caution when using this tool. + +Test your vehicle's lateral control tuning with this tool. The tool will test the vehicle's ability to follow a few lateral maneuvers and includes a tool to generate a report from the route. + +## Instructions + +1. Check out a development branch such as `master` on your comma device. +2. The full maneuver suite runs at 20 and 30 mph. +3. Enable "Lateral Maneuver Mode" in Settings > Developer on the device while offroad. Alternatively, set the parameter manually: + + ```sh + echo -n 1 > /data/params/d/LateralManeuverMode + ``` + +4. Turn your vehicle back on. You will see "Lateral Maneuver Mode". + +5. Ensure the area ahead is clear, as openpilot will command lateral acceleration steps in this mode. Once you are ready, set ACC manually to the target speed shown on screen and let openpilot stabilize lateral. After 1 seconds of steady straight driving, the maneuver will begin automatically. openpilot lateral control stays engaged between maneuvers normally while waiting for the next maneuver's readiness conditions. The maneuver will be aborted and repeated if speed is out of range, steering is touched or openpilot disengages. + +6. When the testing is complete, you'll see an alert that says "Maneuvers Finished." Complete the route by pulling over and turning off the vehicle. + +7. Visit https://connect.comma.ai and locate the route(s). They will stand out with lots of orange intervals in their timeline. Ensure "All logs" show as "uploaded." + + ![image](https://github.com/user-attachments/assets/cfe4c6d9-752f-4b24-b421-4b90a01933dc) + +8. Gather the route ID and then run the report generator. The file will be exported to the same directory: + + ```sh + $ python tools/lateral_maneuvers/generate_report.py 98395b7c5b27882e/000001cc--5a73bde686 + + processing report for KIA_EV6 + plotting maneuver: step right 20mph, runs: 3 + plotting maneuver: step left 20mph, runs: 3 + plotting maneuver: sine 0.5Hz 20mph, runs: 3 + plotting maneuver: step right 30mph, runs: 3 + + Opening report: /home/batman/openpilot/tools/lateral_maneuvers/lateral_reports/KIA_EV6_98395b7c5b27882e_000001cc--5a73bde686.html + ``` + +You can reach out on [Discord](https://discord.comma.ai) if you have any questions about these instructions or the tool itself. diff --git a/tools/lateral_maneuvers/generate_report.py b/tools/lateral_maneuvers/generate_report.py new file mode 100755 index 00000000000000..9a6fe1b979aa7b --- /dev/null +++ b/tools/lateral_maneuvers/generate_report.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +import argparse +import base64 +import io +import math +import numpy as np +import os +import webbrowser +from collections import defaultdict +from pathlib import Path +import matplotlib.pyplot as plt +from openpilot.common.utils import tabulate + +from cereal import car +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.controls.lib.latcontrol_torque import LP_FILTER_CUTOFF_HZ +from openpilot.tools.lib.logreader import LogReader +from openpilot.system.hardware.hw import Paths +from openpilot.common.constants import CV +from openpilot.tools.longitudinal_maneuvers.generate_report import format_car_params + + +def lat_accel(curvature, v): + return curvature * max(v, 1.0) ** 2 + + +def report(platform, route, _description, CP, ID, maneuvers): + output_path = Path(__file__).resolve().parent / "lateral_reports" + output_fn = output_path / f"{platform}_{route.replace('/', '_')}.html" + output_path.mkdir(exist_ok=True) + target_cross_times = defaultdict(list) + + builder = [ + "\n", + "

Lateral maneuver report

\n", + f"

{platform}

\n", + f"

{route}

\n", + f"

{ID.gitCommit}, {ID.gitBranch}, {ID.gitRemote}

\n", + ] + if _description is not None: + builder.append(f"

Description: {_description}

\n") + builder.append(f"

CarParams

{format_car_params(CP)}
\n") + builder.append('{ summary }') # to be replaced below + for description, runs in maneuvers: + # filter incomplete runs + completed_runs = [msgs for msgs in runs + if any(m.alertDebug.alertText1 == 'Complete' for m in msgs if m.which() == 'alertDebug')] + print(f'plotting maneuver: {description}') + if not completed_runs: + continue + builder.append("
\n") + builder.append(f"

{description}

\n") + for run, msgs in enumerate(completed_runs): + t_carControl, carControl = zip(*[(m.logMonoTime, m.carControl) for m in msgs if m.which() == 'carControl'], strict=True) + t_carState, carState = zip(*[(m.logMonoTime, m.carState) for m in msgs if m.which() == 'carState'], strict=True) + t_controlsState, controlsState = zip(*[(m.logMonoTime, m.controlsState) for m in msgs if m.which() == 'controlsState'], strict=True) + t_lateralPlan, lateralPlan = zip(*[(m.logMonoTime, m.lateralManeuverPlan) for m in msgs if m.which() == 'lateralManeuverPlan' and m.valid], strict=True) + t_carOutput, carOutput = zip(*[(m.logMonoTime, m.carOutput) for m in msgs if m.which() == 'carOutput'], strict=True) + + # make time relative seconds + t_carControl = [(t - t_carControl[0]) / 1e9 for t in t_carControl] + t_carState = [(t - t_carState[0]) / 1e9 for t in t_carState] + t_controlsState = [(t - t_controlsState[0]) / 1e9 for t in t_controlsState] + t_lateralPlan = [(t - t_lateralPlan[0]) / 1e9 for t in t_lateralPlan] + t_carOutput = [(t - t_carOutput[0]) / 1e9 for t in t_carOutput] + + # maneuver validity + latActive = [m.latActive for m in carControl] + maneuver_valid = all(latActive) and not any(cs.steeringPressed for cs in carState) + + _open = 'open' if maneuver_valid else '' + title = f'Run #{int(run)+1}' + (' (invalid maneuver!)' if not maneuver_valid else '') + + builder.append(f"

{title}

\n") + + baseline_accel = lat_accel(controlsState[0].curvature, carState[0].vEgo) + v_ego = [m.vEgo for m in carState] + cross_markers = [] + + if description.startswith('sine'): + amplitude = max(abs(lat_accel(lp.desiredCurvature, v) - baseline_accel) + for lp, v in zip(lateralPlan, v_ego, strict=False)) + threshold = amplitude * 0.5 + builder.append('

50% peak') + for t, cs, v in zip(t_controlsState, controlsState, v_ego, strict=False): + actual = lat_accel(cs.curvature, v) - baseline_accel + if abs(actual) > threshold: + builder.append(f', crossed in {t:.3f}s') + cross_markers.append((t, actual + baseline_accel)) + if maneuver_valid: + target_cross_times[description].append(t) + break + else: + builder.append(', not crossed') + builder.append('

') + if maneuver_valid: + target_cross_times.setdefault(description, []) + else: + action_targets = [(0, lat_accel(lateralPlan[0].desiredCurvature, v_ego[0]) - baseline_accel)] + for i in range(1, min(len(lateralPlan), len(v_ego))): + if abs(lateralPlan[i].desiredCurvature - lateralPlan[i - 1].desiredCurvature) > 0.001: + desired = lat_accel(lateralPlan[i].desiredCurvature, v_ego[i]) - baseline_accel + action_targets.append((i, desired)) + + for j, (start_i, act_target) in enumerate(action_targets): + start_time = t_lateralPlan[start_i] + end_time = t_lateralPlan[action_targets[j + 1][0]] if j + 1 < len(action_targets) else t_controlsState[-1] + + builder.append(f'

aTarget: {round(act_target, 1)} m/s^2') + prev_crossed = False + for t, cs, v in zip(t_controlsState, controlsState, v_ego, strict=False): + if not (start_time <= t <= end_time): + continue + actual_accel = lat_accel(cs.curvature, v) - baseline_accel + crossed = (0 < act_target < actual_accel) or (0 > act_target > actual_accel) + if crossed and prev_crossed: + cross_time = t - start_time + builder.append(f', crossed in {cross_time:.3f}s') + cross_markers.append((t, act_target + baseline_accel)) + if maneuver_valid: + target_cross_times[description].append(cross_time) + break + prev_crossed = crossed + else: + builder.append(', not crossed') + builder.append('

') + if maneuver_valid: + target_cross_times.setdefault(description, []) + + plt.rcParams['font.size'] = 40 + fig = plt.figure(figsize=(30, 30)) + ax = fig.subplots(4, 1, sharex=True, gridspec_kw={'height_ratios': [5, 3, 3, 3]}) + + ax[0].grid(linewidth=4) + desired_lat_accel = [lat_accel(m.desiredCurvature, v) for m, v in zip(lateralPlan, v_ego, strict=False)] + if description.startswith('sine'): + ax[0].plot(t_lateralPlan[:len(desired_lat_accel)], desired_lat_accel, label='desired lat accel', linewidth=6) + else: + t_desired = [t_lateralPlan[0]] + t_lateralPlan[:len(desired_lat_accel)] + desired_lat_accel = [baseline_accel] + desired_lat_accel + ax[0].step(t_desired, desired_lat_accel, label='desired lat accel', linewidth=6, where='post') + actual_lat_accel = [lat_accel(cs.curvature, v) for cs, v in zip(controlsState, v_ego, strict=False)] + ax[0].plot(t_controlsState[:len(actual_lat_accel)], actual_lat_accel, label='actual lat accel', linewidth=6) + ax[0].set_ylabel('Lateral Accel (m/s^2)') + + for ct, cv in cross_markers: + ax[0].plot(ct, cv, marker='o', markersize=50, markeredgewidth=7, markeredgecolor='black', markerfacecolor='None') + + ax2 = ax[0].twinx() + if CP.steerControlType == car.CarParams.SteerControlType.angle: + ax2.plot(t_carOutput, [-m.actuatorsOutput.steeringAngleDeg for m in carOutput], 'C2', label='steer angle', linewidth=6) + else: + ax2.plot(t_carOutput, [-m.actuatorsOutput.torque for m in carOutput], 'C2', label='steer torque', linewidth=6) + + h1, l1 = ax[0].get_legend_handles_labels() + h2, l2 = ax2.get_legend_handles_labels() + ax[0].legend(h1 + h2, l1 + l2, prop={'size': 30}) + + ax[1].grid(linewidth=4) + ax[1].plot(t_carState, [v * CV.MS_TO_MPH for v in v_ego], label='vEgo', linewidth=6) + ax[1].set_ylabel('Velocity (mph)') + ax[1].yaxis.set_major_formatter(plt.FormatStrFormatter('%.1f')) + ax[1].legend() + + t_accel = np.array(t_controlsState[:len(actual_lat_accel)]) + raw_jerk = np.gradient(actual_lat_accel, t_accel) + dt_avg = np.mean(np.diff(t_accel)) + jerk_filter = FirstOrderFilter(0.0, 1 / (2 * np.pi * LP_FILTER_CUTOFF_HZ), dt_avg) + filtered_jerk = [jerk_filter.update(j) for j in raw_jerk] + ax[2].grid(linewidth=4) + ax[2].plot(t_accel, filtered_jerk, label='actual jerk', linewidth=6) + if CP.steerControlType == car.CarParams.SteerControlType.torque: + desired_jerk = [cs.lateralControlState.torqueState.desiredLateralJerk for cs in controlsState] + ax[2].plot(t_controlsState[:len(controlsState)], desired_jerk, label='desired jerk', linewidth=6) + ax[2].set_ylabel('Jerk (m/s^3)') + ax[2].legend() + + ax[3].grid(linewidth=4) + ax[3].plot(t_carControl, [math.degrees(m.orientationNED[0]) for m in carControl], label='roll', linewidth=6) + ax[3].set_ylabel('Roll (deg)') + ax[3].legend() + + ax[-1].set_xlabel("Time (s)") + fig.tight_layout() + + buffer = io.BytesIO() + fig.savefig(buffer, format='webp') + plt.close(fig) + buffer.seek(0) + builder.append(f"\n") + builder.append("
\n") + + summary = ["

Summary

\n"] + cols = ['maneuver', 'crossed', 'mean', 'min', 'max'] + table = [] + for description, times in target_cross_times.items(): + l = [description, len(times)] + if len(times): + l.extend([round(sum(times) / len(times), 2), round(min(times), 2), round(max(times), 2)]) + table.append(l) + summary.append(tabulate(table, headers=cols, tablefmt='html', numalign='left') + '\n') + + sum_idx = builder.index('{ summary }') + builder[sum_idx:sum_idx + 1] = summary + + with open(output_fn, "w") as f: + f.write(''.join(builder)) + + print(f"\nOpening report: {output_fn}\n") + webbrowser.open_new_tab(str(output_fn)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Generate lateral maneuver report from route') + parser.add_argument('route', type=str, help='Route name (e.g. 00000000--5f742174be)') + parser.add_argument('description', type=str, nargs='?') + + args = parser.parse_args() + + if '/' in args.route or '|' in args.route: + lr = LogReader(args.route, only_union_types=True) + else: + segs = [seg for seg in os.listdir(Paths.log_root()) if args.route in seg] + lr = LogReader([os.path.join(Paths.log_root(), seg, 'rlog.zst') for seg in segs], only_union_types=True) + + CP = lr.first('carParams') + ID = lr.first('initData') + platform = CP.carFingerprint + print('processing report for', platform) + + maneuvers: list[tuple[str, list[list]]] = [] + active_prev = False + description_prev = None + + for msg in lr: + if msg.which() == 'alertDebug': + active = 'Active' in msg.alertDebug.alertText1 or msg.alertDebug.alertText1 == 'Complete' + if active and not active_prev: + if msg.alertDebug.alertText2 == description_prev: + maneuvers[-1][1].append([]) + else: + maneuvers.append((msg.alertDebug.alertText2, [[]])) + description_prev = maneuvers[-1][0] + active_prev = active + + if active_prev: + maneuvers[-1][1][-1].append(msg) + + report(platform, args.route, args.description, CP, ID, maneuvers) diff --git a/tools/lateral_maneuvers/lateral_maneuversd.py b/tools/lateral_maneuvers/lateral_maneuversd.py new file mode 100755 index 00000000000000..4f68d9be085194 --- /dev/null +++ b/tools/lateral_maneuvers/lateral_maneuversd.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +import numpy as np +from dataclasses import dataclass + +from cereal import messaging, car +from openpilot.common.constants import CV +from openpilot.common.realtime import DT_MDL +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.controls.lib.drive_helpers import MIN_SPEED +from openpilot.tools.longitudinal_maneuvers.maneuversd import Action, Maneuver as _Maneuver + +# thresholds for starting maneuvers +MAX_SPEED_DEV = 0.7 # deviation in m/s +MAX_CURV = 0.002 # 500 m radius +MAX_ROLL = 0.12 # 6.8° +TIMER = 2.0 # sec stable conditions before starting maneuver + +@dataclass +class Maneuver(_Maneuver): + _baseline_curvature: float = 0.0 + + def get_accel(self, v_ego: float, lat_active: bool, curvature: float, roll: float) -> float: + self._run_completed = False + # only start maneuver on straight, flat roads + ready = abs(v_ego - self.initial_speed) < MAX_SPEED_DEV and lat_active and abs(curvature) < MAX_CURV and abs(roll) < MAX_ROLL + self._ready_cnt = (self._ready_cnt + 1) if ready else max(self._ready_cnt - 1, 0) + + if self._ready_cnt > (TIMER / DT_MDL): + if not self._active: + self._baseline_curvature = curvature + self._active = True + + if not self._active: + return 0.0 + + return self._step() + + def reset(self): + super().reset() + self._ready_cnt = 0 + + +def _sine_action(amplitude, period, duration): + t = np.linspace(0, duration, int(duration / DT_MDL) + 1) + a = amplitude * np.sin(2 * np.pi * t / period) + return Action(a.tolist(), t.tolist()) + + +MANEUVERS = [ + Maneuver( + "step right 20mph", + [Action([0.5], [1.0]), Action([-0.5], [1.5])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "step left 20mph", + [Action([-0.5], [1.0]), Action([0.5], [1.5])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "sine 0.5Hz 20mph", + [_sine_action(1.0, 2.0, 2.0), Action([0.0], [0.5])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "step right 30mph", + [Action([0.5], [1.0]), Action([-0.5], [1.5])], + repeat=2, + initial_speed=30. * CV.MPH_TO_MS, + ), + Maneuver( + "step left 30mph", + [Action([-0.5], [1.0]), Action([0.5], [1.5])], + repeat=2, + initial_speed=30. * CV.MPH_TO_MS, + ), + Maneuver( + "sine 0.5Hz 30mph", + [_sine_action(1.0, 2.0, 2.0), Action([0.0], [0.5])], + repeat=2, + initial_speed=30. * CV.MPH_TO_MS, + ), +] + + +def main(): + params = Params() + cloudlog.info("lateral_maneuversd is waiting for CarParams") + messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + + sm = messaging.SubMaster(['carState', 'carControl', 'controlsState', 'selfdriveState', 'modelV2'], poll='modelV2') + pm = messaging.PubMaster(['lateralManeuverPlan', 'alertDebug']) + + maneuvers = iter(MANEUVERS) + maneuver = None + complete_cnt = 0 + display_holdoff = 0 + prev_text = '' + + while True: + sm.update() + + if maneuver is None: + maneuver = next(maneuvers, None) + + alert_msg = messaging.new_message('alertDebug') + alert_msg.valid = True + + plan_send = messaging.new_message('lateralManeuverPlan') + + accel = 0 + v_ego = max(sm['carState'].vEgo, 0) + curvature = sm['controlsState'].desiredCurvature + + if complete_cnt > 0: + complete_cnt -= 1 + alert_msg.alertDebug.alertText1 = 'Completed' + alert_msg.alertDebug.alertText2 = maneuver.description + elif maneuver is not None: + # reset maneuver on steering override or out of range speed + if sm['carState'].steeringPressed or (maneuver.active and abs(v_ego - maneuver.initial_speed) > MAX_SPEED_DEV): + maneuver.reset() + + roll = sm['carControl'].orientationNED[0] if len(sm['carControl'].orientationNED) == 3 else 0.0 + accel = maneuver.get_accel(v_ego, sm['carControl'].latActive, curvature, roll) + + if maneuver._run_completed: + complete_cnt = int(1.0 / DT_MDL) + alert_msg.alertDebug.alertText1 = 'Complete' + alert_msg.alertDebug.alertText2 = maneuver.description + elif maneuver.active: + action_remaining = maneuver.actions[maneuver._action_index].time_bp[-1] - maneuver._action_frames * DT_MDL + if maneuver.description.startswith('sine'): + freq = maneuver.description.split()[1] + alert_msg.alertDebug.alertText1 = f'Active sine {freq} {max(action_remaining, 0):.1f}s' + else: + alert_msg.alertDebug.alertText1 = f'Active {accel:+.1f}m/s² {max(action_remaining, 0):.1f}s' + alert_msg.alertDebug.alertText2 = maneuver.description + elif not (abs(v_ego - maneuver.initial_speed) < MAX_SPEED_DEV and sm['carControl'].latActive): + alert_msg.alertDebug.alertText1 = f'Set speed to {maneuver.initial_speed * CV.MS_TO_MPH:0.0f} mph' + elif maneuver._ready_cnt > 0: + ready_time = max(TIMER - maneuver._ready_cnt * DT_MDL, 0) + alert_msg.alertDebug.alertText1 = f'Starting: {int(ready_time) + 1}' + alert_msg.alertDebug.alertText2 = maneuver.description + else: + curv_ok = abs(curvature) < MAX_CURV + reason = 'road not straight' if not curv_ok else 'road not flat' + alert_msg.alertDebug.alertText1 = f'Waiting: {reason}' + alert_msg.alertDebug.alertText2 = maneuver.description + else: + alert_msg.alertDebug.alertText1 = 'Maneuvers Finished' + + # prevent flickering text + setup = ('Set speed', 'Starting', 'Waiting') + text = alert_msg.alertDebug.alertText1 + same = text == prev_text or (text.startswith('Starting') and prev_text.startswith('Starting')) + if not same and text.startswith(setup) and prev_text.startswith(setup) and display_holdoff > 0: + alert_msg.alertDebug.alertText1 = prev_text + display_holdoff -= 1 + else: + prev_text = text + display_holdoff = int(0.5 / DT_MDL) if text.startswith(setup) else 0 + + pm.send('alertDebug', alert_msg) + + plan_send.valid = maneuver is not None and maneuver.active and complete_cnt == 0 + if plan_send.valid: + plan_send.lateralManeuverPlan.desiredCurvature = maneuver._baseline_curvature + accel / max(v_ego, MIN_SPEED) ** 2 + pm.send('lateralManeuverPlan', plan_send) + + if maneuver is not None and maneuver.finished and complete_cnt == 0: + maneuver = None + + +if __name__ == "__main__": + main() diff --git a/tools/lib/api.py b/tools/lib/api.py index 92a75d2a3b6abd..f84fe758695fc3 100644 --- a/tools/lib/api.py +++ b/tools/lib/api.py @@ -1,7 +1,10 @@ import os import requests +from requests.adapters import HTTPAdapter, Retry API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') +# TODO: this should be merged into common.api + class CommaApi: def __init__(self, token=None): self.session = requests.Session() @@ -9,17 +12,20 @@ def __init__(self, token=None): if token: self.session.headers['Authorization'] = 'JWT ' + token + retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504]) + self.session.mount('https://', HTTPAdapter(max_retries=retries)) + def request(self, method, endpoint, **kwargs): - resp = self.session.request(method, API_HOST + '/' + endpoint, **kwargs) - resp_json = resp.json() - if isinstance(resp_json, dict) and resp_json.get('error'): - if resp.status_code in [401, 403]: - raise UnauthorizedError('Unauthorized. Authenticate with tools/lib/auth.py') - - e = APIError(str(resp.status_code) + ":" + resp_json.get('description', str(resp_json['error']))) - e.status_code = resp.status_code - raise e - return resp_json + with self.session.request(method, API_HOST + '/' + endpoint, **kwargs) as resp: + resp_json = resp.json() + if isinstance(resp_json, dict) and resp_json.get('error'): + if resp.status_code in [401, 403]: + raise UnauthorizedError('Unauthorized. Authenticate with tools/lib/auth.py') + + e = APIError(str(resp.status_code) + ":" + resp_json.get('description', str(resp_json['error']))) + e.status_code = resp.status_code + raise e + return resp_json def get(self, endpoint, **kwargs): return self.request('GET', endpoint, **kwargs) diff --git a/tools/lib/comma_car_segments.py b/tools/lib/comma_car_segments.py index fe9c350a9b82c2..cd19356d6627de 100644 --- a/tools/lib/comma_car_segments.py +++ b/tools/lib/comma_car_segments.py @@ -14,7 +14,8 @@ def get_comma_car_segments_database(): ret = {} for platform in database: - ret[MIGRATION.get(platform, platform)] = database[platform] + # TODO: remove this when commaCarSegments is updated to remove selector + ret[MIGRATION.get(platform, platform)] = [s.rstrip('/s') for s in database[platform]] return ret @@ -86,5 +87,5 @@ def get_repo_url(path): return get_repo_raw_url(path) -def get_url(route, segment, file="rlog.bz2"): +def get_url(route, segment, file="rlog.zst"): return get_repo_url(f"segments/{route.replace('|', '/')}/{segment}/{file}") diff --git a/tools/lib/file_downloader.py b/tools/lib/file_downloader.py new file mode 100755 index 00000000000000..5b31a5894cf265 --- /dev/null +++ b/tools/lib/file_downloader.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +""" +CLI tool for downloading files and querying the comma API. +Called by C++ replay/cabana via subprocess. + +Subcommands: + route-files - Get route file URLs as JSON + download - Download URL to local cache, print local path + devices - List user's devices as JSON + device-routes - List routes for a device as JSON +""" +import argparse +import hashlib +import json +import os +import sys +import tempfile +import shutil + +from openpilot.system.hardware.hw import Paths +from openpilot.tools.lib.api import CommaApi, UnauthorizedError, APIError +from openpilot.tools.lib.auth_config import get_token +from openpilot.tools.lib.url_file import URLFile + + +def api_call(func): + """Run an API call, outputting JSON result or error to stdout.""" + try: + result = func(CommaApi(get_token())) + json.dump(result, sys.stdout) + except UnauthorizedError: + json.dump({"error": "unauthorized"}, sys.stdout) + except APIError as e: + error = "not_found" if getattr(e, 'status_code', 0) == 404 else str(e) + json.dump({"error": error}, sys.stdout) + except Exception as e: + json.dump({"error": str(e)}, sys.stdout) + sys.stdout.write("\n") + sys.stdout.flush() + + +def cache_file_path(url): + url_without_query = url.split("?")[0] + return os.path.join(Paths.download_cache_root(), hashlib.sha256(url_without_query.encode()).hexdigest()) + + +def cmd_route_files(args): + api_call(lambda api: api.get(f"v1/route/{args.route}/files")) + + +def cmd_download(args): + url = args.url + use_cache = not args.no_cache + + if use_cache: + local_path = cache_file_path(url) + if os.path.exists(local_path): + sys.stdout.write(local_path + "\n") + sys.stdout.flush() + return + + try: + # Stream the file in a single HTTP request instead of making + # a separate Range request per chunk (which was very slow). + pool = URLFile.pool_manager() + r = pool.request("GET", url, preload_content=False) + if r.status not in (200, 206): + sys.stderr.write(f"ERROR:HTTP {r.status}\n") + sys.stderr.flush() + sys.exit(1) + + total = int(r.headers.get('content-length', 0)) + if total <= 0: + sys.stderr.write("ERROR:File not found or empty\n") + sys.stderr.flush() + sys.exit(1) + + os.makedirs(Paths.download_cache_root(), exist_ok=True) + tmp_fd, tmp_path = tempfile.mkstemp(dir=Paths.download_cache_root()) + try: + downloaded = 0 + chunk_size = 1024 * 1024 + with os.fdopen(tmp_fd, 'wb') as f: + for data in r.stream(chunk_size): + f.write(data) + downloaded += len(data) + sys.stderr.write(f"PROGRESS:{downloaded}:{total}\n") + sys.stderr.flush() + + if use_cache: + shutil.move(tmp_path, local_path) + sys.stdout.write(local_path + "\n") + else: + sys.stdout.write(tmp_path + "\n") + except Exception: + try: + os.unlink(tmp_path) + except OSError: + pass + raise + finally: + r.release_conn() + + except Exception as e: + sys.stderr.write(f"ERROR:{e}\n") + sys.stderr.flush() + sys.exit(1) + + sys.stdout.flush() + + +def cmd_devices(args): + api_call(lambda api: api.get("v1/me/devices/")) + + +def cmd_device_routes(args): + def fetch(api): + if args.preserved: + return api.get(f"v1/devices/{args.dongle_id}/routes/preserved") + params = {} + if args.start is not None: + params['start'] = args.start + if args.end is not None: + params['end'] = args.end + return api.get(f"v1/devices/{args.dongle_id}/routes_segments", params=params) + api_call(fetch) + + +def main(): + parser = argparse.ArgumentParser(description="File downloader CLI for openpilot tools") + subparsers = parser.add_subparsers(dest="command", required=True) + + p_rf = subparsers.add_parser("route-files") + p_rf.add_argument("route") + p_rf.set_defaults(func=cmd_route_files) + + p_dl = subparsers.add_parser("download") + p_dl.add_argument("url") + p_dl.add_argument("--no-cache", action="store_true") + p_dl.set_defaults(func=cmd_download) + + p_dev = subparsers.add_parser("devices") + p_dev.set_defaults(func=cmd_devices) + + p_dr = subparsers.add_parser("device-routes") + p_dr.add_argument("dongle_id") + p_dr.add_argument("--start", type=int, default=None) + p_dr.add_argument("--end", type=int, default=None) + p_dr.add_argument("--preserved", action="store_true") + p_dr.set_defaults(func=cmd_device_routes) + + args = parser.parse_args() + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/tools/lib/file_sources.py b/tools/lib/file_sources.py new file mode 100755 index 00000000000000..cb7bf15114e273 --- /dev/null +++ b/tools/lib/file_sources.py @@ -0,0 +1,57 @@ +from collections.abc import Callable + +from openpilot.tools.lib.comma_car_segments import get_url as get_comma_segments_url +from openpilot.tools.lib.openpilotci import get_url +from openpilot.tools.lib.filereader import DATA_ENDPOINT, file_exists, internal_source_available +from openpilot.tools.lib.route import Route, SegmentRange, FileName + +# When passed a tuple of file names, each source will return the first that exists (rlog.zst, rlog.bz2) +FileNames = tuple[str, ...] +Source = Callable[[SegmentRange, list[int], FileNames], dict[int, str]] + +InternalUnavailableException = Exception("Internal source not available") + + +def comma_api_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames) -> dict[int, str]: + route = Route(sr.route_name) + + # comma api will have already checked if the file exists + if fns == FileName.RLOG: + return {seg: route.log_paths()[seg] for seg in seg_idxs if route.log_paths()[seg] is not None} + else: + return {seg: route.qlog_paths()[seg] for seg in seg_idxs if route.qlog_paths()[seg] is not None} + + +def internal_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames, endpoint_url: str = DATA_ENDPOINT) -> dict[int, str]: + if not internal_source_available(endpoint_url): + raise InternalUnavailableException + + def get_internal_url(sr: SegmentRange, seg, file): + return f"{endpoint_url.rstrip('/')}/{sr.dongle_id}/{sr.log_id}/{seg}/{file}" + + return eval_source({seg: [get_internal_url(sr, seg, fn) for fn in fns] for seg in seg_idxs}) + + +def openpilotci_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames) -> dict[int, str]: + return eval_source({seg: [get_url(sr.route_name, seg, fn) for fn in fns] for seg in seg_idxs}) + + +def comma_car_segments_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames) -> dict[int, str]: + return eval_source({seg: get_comma_segments_url(sr.route_name, seg) for seg in seg_idxs}) + + +def eval_source(files: dict[int, list[str] | str]) -> dict[int, str]: + # Returns valid file URLs given a list of possible file URLs for each segment (e.g. rlog.bz2, rlog.zst) + valid_files: dict[int, str] = {} + + for seg_idx, urls in files.items(): + if isinstance(urls, str): + urls = [urls] + + # Add first valid file URL + for url in urls: + if file_exists(url): + valid_files[seg_idx] = url + break + + return valid_files diff --git a/tools/lib/filereader.py b/tools/lib/filereader.py index 963d7a8cdb6e10..f5418be81a6c94 100644 --- a/tools/lib/filereader.py +++ b/tools/lib/filereader.py @@ -1,5 +1,9 @@ import os +import io +import posixpath import socket +from functools import cache +from openpilot.common.utils import retry from urllib.parse import urlparse from openpilot.tools.lib.url_file import URLFile @@ -7,11 +11,17 @@ DATA_ENDPOINT = os.getenv("DATA_ENDPOINT", "http://data-raw.comma.internal/") -def internal_source_available(url=DATA_ENDPOINT): +@cache +@retry(delay=0.0) +def internal_source_available(url: str) -> bool: + if os.path.isdir(url): + return True + try: hostname = urlparse(url).hostname port = urlparse(url).port or 80 - with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(0.5) s.connect((hostname, port)) return True except (socket.gaierror, ConnectionRefusedError): @@ -21,19 +31,28 @@ def internal_source_available(url=DATA_ENDPOINT): def resolve_name(fn): if fn.startswith("cd:/"): - return fn.replace("cd:/", DATA_ENDPOINT) + return posixpath.join(DATA_ENDPOINT, fn[4:]) return fn +@cache def file_exists(fn): fn = resolve_name(fn) if fn.startswith(("http://", "https://")): return URLFile(fn).get_length_online() != -1 return os.path.exists(fn) +class DiskFile(io.BufferedReader): + def get_multi_range(self, ranges: list[tuple[int, int]]) -> list[bytes]: + parts = [] + for r in ranges: + self.seek(r[0]) + parts.append(self.read(r[1] - r[0])) + return parts -def FileReader(fn, debug=False): +def FileReader(fn): fn = resolve_name(fn) if fn.startswith(("http://", "https://")): - return URLFile(fn, debug=debug) - return open(fn, "rb") + return URLFile(fn) + else: + return DiskFile(open(fn, "rb")) diff --git a/tools/lib/framereader.py b/tools/lib/framereader.py index 275b9b65b84cf3..c9236515630b54 100644 --- a/tools/lib/framereader.py +++ b/tools/lib/framereader.py @@ -1,537 +1,173 @@ -import json import os -import pickle -import struct import subprocess -import threading -from enum import IntEnum -from functools import wraps +import json +import logging +from collections.abc import Iterator +from collections import OrderedDict import numpy as np -from lru import LRU - -import _io -from openpilot.tools.lib.cache import cache_path_for_file_path, DEFAULT_CACHE_DIR +from openpilot.tools.lib.filereader import FileReader, resolve_name from openpilot.tools.lib.exceptions import DataUnreadableError from openpilot.tools.lib.vidindex import hevc_index -from openpilot.common.file_helpers import atomic_write_in_dir -from openpilot.tools.lib.filereader import FileReader, resolve_name +logger = logging.getLogger("tools") HEVC_SLICE_B = 0 HEVC_SLICE_P = 1 HEVC_SLICE_I = 2 +class LRUCache: + def __init__(self, capacity: int): + self._cache: OrderedDict = OrderedDict() + self.capacity = capacity -class GOPReader: - def get_gop(self, num): - # returns (start_frame_num, num_frames, frames_to_skip, gop_data) - raise NotImplementedError + def __getitem__(self, key): + self._cache.move_to_end(key) + return self._cache[key] + def __setitem__(self, key, value): + self._cache[key] = value + if len(self._cache) > self.capacity: + self._cache.popitem(last=False) -class DoNothingContextManager: - def __enter__(self): - return self + def __contains__(self, key): + return key in self._cache - def __exit__(self, *x): - pass - - -class FrameType(IntEnum): - raw = 1 - h265_stream = 2 - - -def fingerprint_video(fn): +def assert_hvec(fn: str) -> None: with FileReader(fn) as f: header = f.read(4) if len(header) == 0: raise DataUnreadableError(f"{fn} is empty") - elif header == b"\x00\xc0\x12\x00": - return FrameType.raw elif header == b"\x00\x00\x00\x01": - if 'hevc' in fn: - return FrameType.h265_stream - else: + if 'hevc' not in fn: raise NotImplementedError(fn) - else: - raise NotImplementedError(fn) +def decompress_video_data(rawdat, w, h, pix_fmt="rgb24", vid_fmt='hevc', hwaccel="auto", loglevel="info") -> np.ndarray: + threads = os.getenv("FFMPEG_THREADS", "0") + args = ["ffmpeg", "-v", loglevel, + "-threads", threads, + "-hwaccel", hwaccel, + "-c:v", "hevc", + "-vsync", "0", + "-f", vid_fmt, + "-flags2", "showall", + "-i", "pipe:0", + "-f", "rawvideo", + "-pix_fmt", pix_fmt, + "pipe:1"] + dat = subprocess.check_output(args, input=rawdat) + + ret: np.ndarray + if pix_fmt == "rgb24": + ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, h, w, 3) + elif pix_fmt in ["nv12", "yuv420p"]: + ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, (h*w*3//2)) + else: + raise NotImplementedError(f"Unsupported pixel format: {pix_fmt}") + return ret def ffprobe(fn, fmt=None): fn = resolve_name(fn) cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams"] if fmt: cmd += ["-f", fmt] - cmd += ["-i", "-"] + cmd += ["-i", "pipe:0"] try: with FileReader(fn) as f: ffprobe_output = subprocess.check_output(cmd, input=f.read(4096)) except subprocess.CalledProcessError as e: raise DataUnreadableError(fn) from e - return json.loads(ffprobe_output) +def get_index_data(fn: str, index_data: dict|None = None): + if index_data is None: + index_data = get_video_index(fn) + if index_data is None: + raise DataUnreadableError(f"Failed to index {fn!r}") + stream = index_data["probe"]["streams"][0] + return index_data["index"], index_data["global_prefix"], stream["width"], stream["height"] -def cache_fn(func): - @wraps(func) - def cache_inner(fn, *args, **kwargs): - if kwargs.pop('no_cache', None): - cache_path = None - else: - cache_dir = kwargs.pop('cache_dir', DEFAULT_CACHE_DIR) - cache_path = cache_path_for_file_path(fn, cache_dir) - - if cache_path and os.path.exists(cache_path): - with open(cache_path, "rb") as cache_file: - cache_value = pickle.load(cache_file) - else: - cache_value = func(fn, *args, **kwargs) - if cache_path: - with atomic_write_in_dir(cache_path, mode="wb", overwrite=True) as cache_file: - pickle.dump(cache_value, cache_file, -1) - - return cache_value - - return cache_inner - - -@cache_fn -def index_stream(fn, ft): - if ft != FrameType.h265_stream: - raise NotImplementedError("Only h265 supported") - +def get_video_index(fn): + assert_hvec(fn) frame_types, dat_len, prefix = hevc_index(fn) index = np.array(frame_types + [(0xFFFFFFFF, dat_len)], dtype=np.uint32) probe = ffprobe(fn, "hevc") - return { 'index': index, 'global_prefix': prefix, 'probe': probe } - -def get_video_index(fn, frame_type, cache_dir=DEFAULT_CACHE_DIR): - return index_stream(fn, frame_type, cache_dir=cache_dir) - -def read_file_check_size(f, sz, cookie): - buff = bytearray(sz) - bytes_read = f.readinto(buff) - assert bytes_read == sz, (bytes_read, sz) - return buff - - -def rgb24toyuv(rgb): - yuv_from_rgb = np.array([[ 0.299 , 0.587 , 0.114 ], - [-0.14714119, -0.28886916, 0.43601035 ], - [ 0.61497538, -0.51496512, -0.10001026 ]]) - img = np.dot(rgb.reshape(-1, 3), yuv_from_rgb.T).reshape(rgb.shape) - - - - ys = img[:, :, 0] - us = (img[::2, ::2, 1] + img[1::2, ::2, 1] + img[::2, 1::2, 1] + img[1::2, 1::2, 1]) / 4 + 128 - vs = (img[::2, ::2, 2] + img[1::2, ::2, 2] + img[::2, 1::2, 2] + img[1::2, 1::2, 2]) / 4 + 128 - - return ys, us, vs - - -def rgb24toyuv420(rgb): - ys, us, vs = rgb24toyuv(rgb) - - y_len = rgb.shape[0] * rgb.shape[1] - uv_len = y_len // 4 - - yuv420 = np.empty(y_len + 2 * uv_len, dtype=rgb.dtype) - yuv420[:y_len] = ys.reshape(-1) - yuv420[y_len:y_len + uv_len] = us.reshape(-1) - yuv420[y_len + uv_len:y_len + 2 * uv_len] = vs.reshape(-1) - - return yuv420.clip(0, 255).astype('uint8') - - -def rgb24tonv12(rgb): - ys, us, vs = rgb24toyuv(rgb) - - y_len = rgb.shape[0] * rgb.shape[1] - uv_len = y_len // 4 - - nv12 = np.empty(y_len + 2 * uv_len, dtype=rgb.dtype) - nv12[:y_len] = ys.reshape(-1) - nv12[y_len::2] = us.reshape(-1) - nv12[y_len+1::2] = vs.reshape(-1) - - return nv12.clip(0, 255).astype('uint8') - - -def decompress_video_data(rawdat, vid_fmt, w, h, pix_fmt): - threads = os.getenv("FFMPEG_THREADS", "0") - cuda = os.getenv("FFMPEG_CUDA", "0") == "1" - args = ["ffmpeg", "-v", "quiet", - "-threads", threads, - "-hwaccel", "none" if not cuda else "cuda", - "-c:v", "hevc", - "-vsync", "0", - "-f", vid_fmt, - "-flags2", "showall", - "-i", "-", - "-threads", threads, - "-f", "rawvideo", - "-pix_fmt", pix_fmt, - "-"] - dat = subprocess.check_output(args, input=rawdat) - - if pix_fmt == "rgb24": - ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, h, w, 3) - elif pix_fmt == "nv12": - ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, (h*w*3//2)) - elif pix_fmt == "yuv420p": - ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, (h*w*3//2)) - elif pix_fmt == "yuv444p": - ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, 3, h, w) - else: - raise NotImplementedError - - return ret - - -class BaseFrameReader: - # properties: frame_type, frame_count, w, h - - def __enter__(self): - return self - - def __exit__(self, *args): - self.close() - - def close(self): - pass - - def get(self, num, count=1, pix_fmt="yuv420p"): - raise NotImplementedError - - -def FrameReader(fn, cache_dir=DEFAULT_CACHE_DIR, readahead=False, readbehind=False, index_data=None): - frame_type = fingerprint_video(fn) - if frame_type == FrameType.raw: - return RawFrameReader(fn) - elif frame_type in (FrameType.h265_stream,): - if not index_data: - index_data = get_video_index(fn, frame_type, cache_dir) - return StreamFrameReader(fn, frame_type, index_data, readahead=readahead, readbehind=readbehind) - else: - raise NotImplementedError(frame_type) - - -class RawData: - def __init__(self, f): - self.f = _io.FileIO(f, 'rb') - self.lenn = struct.unpack("I", self.f.read(4))[0] - self.count = os.path.getsize(f) / (self.lenn+4) - - def read(self, i): - self.f.seek((self.lenn+4)*i + 4) - return self.f.read(self.lenn) - - -class RawFrameReader(BaseFrameReader): - def __init__(self, fn): - # raw camera +class FfmpegDecoder: + def __init__(self, fn: str, index_data: dict|None = None, + pix_fmt: str = "rgb24", hwaccel="auto", loglevel="quiet"): self.fn = fn - self.frame_type = FrameType.raw - self.rawfile = RawData(self.fn) - self.frame_count = self.rawfile.count - self.w, self.h = 640, 480 - - def load_and_debayer(self, img): - img = np.frombuffer(img, dtype='uint8').reshape(960, 1280) - cimg = np.dstack([img[0::2, 1::2], ((img[0::2, 0::2].astype("uint16") + img[1::2, 1::2].astype("uint16")) >> 1).astype("uint8"), img[1::2, 0::2]]) - return cimg - - def get(self, num, count=1, pix_fmt="yuv420p"): - assert self.frame_count is not None - assert num+count <= self.frame_count - - if pix_fmt not in ("nv12", "yuv420p", "rgb24"): - raise ValueError(f"Unsupported pixel format {pix_fmt!r}") - - app = [] - for i in range(num, num+count): - dat = self.rawfile.read(i) - rgb_dat = self.load_and_debayer(dat) - if pix_fmt == "rgb24": - app.append(rgb_dat) - elif pix_fmt == "nv12": - app.append(rgb24tonv12(rgb_dat)) - elif pix_fmt == "yuv420p": - app.append(rgb24toyuv420(rgb_dat)) - else: - raise NotImplementedError - - return app - - -class VideoStreamDecompressor: - def __init__(self, fn, vid_fmt, w, h, pix_fmt): - self.fn = fn - self.vid_fmt = vid_fmt - self.w = w - self.h = h + self.index, self.prefix, self.w, self.h = get_index_data(fn, index_data) + self.frame_count = len(self.index) - 1 # sentinel row at the end + self.iframes = np.where(self.index[:, 0] == HEVC_SLICE_I)[0] self.pix_fmt = pix_fmt - - if pix_fmt in ("nv12", "yuv420p"): - self.out_size = w*h*3//2 # yuv420p - elif pix_fmt in ("rgb24", "yuv444p"): - self.out_size = w*h*3 - else: - raise NotImplementedError - - self.proc = None - self.t = threading.Thread(target=self.write_thread) - self.t.daemon = True - - def write_thread(self): - try: + self.loglevel, self.hwaccel = loglevel, hwaccel + + def _gop_bounds(self, frame_idx: int): + f_b = frame_idx + while f_b > 0 and self.index[f_b, 0] != HEVC_SLICE_I: + f_b -= 1 + f_e = frame_idx + 1 + while f_e < self.frame_count and self.index[f_e, 0] != HEVC_SLICE_I: + f_e += 1 + return f_b, f_e, self.index[f_b, 1], self.index[f_e, 1] + + def _decode_gop(self, raw: bytes) -> Iterator[np.ndarray]: + yield from decompress_video_data(raw, self.w, self.h, pix_fmt=self.pix_fmt, hwaccel=self.hwaccel, loglevel=self.loglevel) + + def get_gop_start(self, frame_idx: int): + return self.iframes[np.searchsorted(self.iframes, frame_idx, side="right") - 1] + + def get_iterator(self, start_fidx: int = 0, end_fidx: int|None = None, + frame_skip: int = 1) -> Iterator[tuple[int, np.ndarray]]: + end_fidx = end_fidx or self.frame_count + fidx = start_fidx + while fidx < end_fidx: + f_b, f_e, off_b, off_e = self._gop_bounds(fidx) with FileReader(self.fn) as f: - while True: - r = f.read(1024*1024) - if len(r) == 0: - break - self.proc.stdin.write(r) - except BrokenPipeError: - pass - finally: - self.proc.stdin.close() - - def read(self): - threads = os.getenv("FFMPEG_THREADS", "0") - cuda = os.getenv("FFMPEG_CUDA", "0") == "1" - cmd = [ - "ffmpeg", - "-threads", threads, - "-hwaccel", "none" if not cuda else "cuda", - "-c:v", "hevc", - # "-avioflags", "direct", - "-analyzeduration", "0", - "-probesize", "32", - "-flush_packets", "0", - # "-fflags", "nobuffer", - "-vsync", "0", - "-f", self.vid_fmt, - "-i", "pipe:0", - "-threads", threads, - "-f", "rawvideo", - "-pix_fmt", self.pix_fmt, - "pipe:1" - ] - self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) - try: - self.t.start() - - while True: - dat = self.proc.stdout.read(self.out_size) - if len(dat) == 0: - break - assert len(dat) == self.out_size - if self.pix_fmt == "rgb24": - ret = np.frombuffer(dat, dtype=np.uint8).reshape((self.h, self.w, 3)) - elif self.pix_fmt == "yuv420p": - ret = np.frombuffer(dat, dtype=np.uint8) - elif self.pix_fmt == "nv12": - ret = np.frombuffer(dat, dtype=np.uint8) - elif self.pix_fmt == "yuv444p": - ret = np.frombuffer(dat, dtype=np.uint8).reshape((3, self.h, self.w)) - else: - raise RuntimeError(f"unknown pix_fmt: {self.pix_fmt}") - yield ret - - result_code = self.proc.wait() - assert result_code == 0, result_code - finally: - self.proc.kill() - self.t.join() - -class StreamGOPReader(GOPReader): - def __init__(self, fn, frame_type, index_data): - assert frame_type == FrameType.h265_stream - - self.fn = fn - - self.frame_type = frame_type - self.frame_count = None - self.w, self.h = None, None - - self.prefix = None - self.index = None - - self.index = index_data['index'] - self.prefix = index_data['global_prefix'] - probe = index_data['probe'] - - self.prefix_frame_data = None - self.num_prefix_frames = 0 - self.vid_fmt = "hevc" - - i = 0 - while i < self.index.shape[0] and self.index[i, 0] != HEVC_SLICE_I: - i += 1 - self.first_iframe = i - - assert self.first_iframe == 0 - - self.frame_count = len(self.index) - 1 - - self.w = probe['streams'][0]['width'] - self.h = probe['streams'][0]['height'] - - def _lookup_gop(self, num): - frame_b = num - while frame_b > 0 and self.index[frame_b, 0] != HEVC_SLICE_I: - frame_b -= 1 - - frame_e = num + 1 - while frame_e < (len(self.index) - 1) and self.index[frame_e, 0] != HEVC_SLICE_I: - frame_e += 1 - - offset_b = self.index[frame_b, 1] - offset_e = self.index[frame_e, 1] - - return (frame_b, frame_e, offset_b, offset_e) - - def get_gop(self, num): - frame_b, frame_e, offset_b, offset_e = self._lookup_gop(num) - assert frame_b <= num < frame_e - - num_frames = frame_e - frame_b - - with FileReader(self.fn) as f: - f.seek(offset_b) - rawdat = f.read(offset_e - offset_b) - - if num < self.first_iframe: - assert self.prefix_frame_data - rawdat = self.prefix_frame_data + rawdat - - rawdat = self.prefix + rawdat - - skip_frames = 0 - if num < self.first_iframe: - skip_frames = self.num_prefix_frames - - return frame_b, num_frames, skip_frames, rawdat - - -class GOPFrameReader(BaseFrameReader): - #FrameReader with caching and readahead for formats that are group-of-picture based - - def __init__(self, readahead=False, readbehind=False): - self.open_ = True - - self.readahead = readahead - self.readbehind = readbehind - self.frame_cache = LRU(64) - - if self.readahead: - self.cache_lock = threading.RLock() - self.readahead_last = None - self.readahead_len = 30 - self.readahead_c = threading.Condition() - self.readahead_thread = threading.Thread(target=self._readahead_thread) - self.readahead_thread.daemon = True - self.readahead_thread.start() - else: - self.cache_lock = DoNothingContextManager() - - def close(self): - if not self.open_: - return - self.open_ = False - - if self.readahead: - self.readahead_c.acquire() - self.readahead_c.notify() - self.readahead_c.release() - self.readahead_thread.join() - - def _readahead_thread(self): - while True: - self.readahead_c.acquire() - try: - if not self.open_: - break - self.readahead_c.wait() - finally: - self.readahead_c.release() - if not self.open_: - break - assert self.readahead_last - num, pix_fmt = self.readahead_last - - if self.readbehind: - for k in range(num - 1, max(0, num - self.readahead_len), -1): - self._get_one(k, pix_fmt) - else: - for k in range(num, min(self.frame_count, num + self.readahead_len)): - self._get_one(k, pix_fmt) - - def _get_one(self, num, pix_fmt): - assert num < self.frame_count - - if (num, pix_fmt) in self.frame_cache: - return self.frame_cache[(num, pix_fmt)] - - with self.cache_lock: - if (num, pix_fmt) in self.frame_cache: - return self.frame_cache[(num, pix_fmt)] - - frame_b, num_frames, skip_frames, rawdat = self.get_gop(num) - - ret = decompress_video_data(rawdat, self.vid_fmt, self.w, self.h, pix_fmt) - ret = ret[skip_frames:] - assert ret.shape[0] == num_frames - - for i in range(ret.shape[0]): - self.frame_cache[(frame_b+i, pix_fmt)] = ret[i] - - return self.frame_cache[(num, pix_fmt)] - - def get(self, num, count=1, pix_fmt="yuv420p"): - assert self.frame_count is not None - - if num + count > self.frame_count: - raise ValueError(f"{num + count} > {self.frame_count}") - - if pix_fmt not in ("nv12", "yuv420p", "rgb24", "yuv444p"): - raise ValueError(f"Unsupported pixel format {pix_fmt!r}") - - ret = [self._get_one(num + i, pix_fmt) for i in range(count)] - - if self.readahead: - self.readahead_last = (num+count, pix_fmt) - self.readahead_c.acquire() - self.readahead_c.notify() - self.readahead_c.release() - - return ret - - -class StreamFrameReader(StreamGOPReader, GOPFrameReader): - def __init__(self, fn, frame_type, index_data, readahead=False, readbehind=False): - StreamGOPReader.__init__(self, fn, frame_type, index_data) - GOPFrameReader.__init__(self, readahead, readbehind) - - -def GOPFrameIterator(gop_reader, pix_fmt): - dec = VideoStreamDecompressor(gop_reader.fn, gop_reader.vid_fmt, gop_reader.w, gop_reader.h, pix_fmt) - yield from dec.read() - + f.seek(off_b) + raw = self.prefix + f.read(off_e - off_b) + # number of frames to discard inside this GOP before the wanted one + for i, frm in enumerate(decompress_video_data(raw, self.w, self.h, self.pix_fmt, hwaccel=self.hwaccel, loglevel=self.loglevel)): + fidx = f_b + i + if fidx >= end_fidx: + return + elif fidx >= start_fidx and (fidx - start_fidx) % frame_skip == 0: + yield fidx, frm + fidx += 1 + +def FrameIterator(fn: str, index_data: dict|None=None, pix_fmt: str = "rgb24", + start_fidx:int=0, end_fidx=None, frame_skip:int=1, hwaccel="auto", loglevel="quiet") -> Iterator[np.ndarray]: + dec = FfmpegDecoder(fn, pix_fmt=pix_fmt, index_data=index_data, hwaccel=hwaccel, loglevel=loglevel) + for _, frame in dec.get_iterator(start_fidx=start_fidx, end_fidx=end_fidx, frame_skip=frame_skip): + yield frame + +class FrameReader: + def __init__(self, fn: str, index_data: dict|None = None, cache_size: int = 30, + pix_fmt: str = "rgb24", hwaccel="auto", loglevel="quiet"): + self.decoder = FfmpegDecoder(fn, index_data=index_data, pix_fmt=pix_fmt, hwaccel=hwaccel, loglevel=loglevel) + self.iframes = self.decoder.iframes + self._cache: LRUCache = LRUCache(cache_size) + self.w, self.h, self.frame_count, = self.decoder.w, self.decoder.h, self.decoder.frame_count + self.pix_fmt = pix_fmt -def FrameIterator(fn, pix_fmt, **kwargs): - fr = FrameReader(fn, **kwargs) - if isinstance(fr, GOPReader): - yield from GOPFrameIterator(fr, pix_fmt) - else: - for i in range(fr.frame_count): - yield fr.get(i, pix_fmt=pix_fmt)[0] + self.it: Iterator[tuple[int, np.ndarray]] | None = None + self.fidx = -1 + + def get(self, fidx:int): + if fidx in self._cache: # If frame is cached, return it + return self._cache[fidx] + read_start = self.decoder.get_gop_start(fidx) + if not self.it or fidx < self.fidx or read_start != self.decoder.get_gop_start(self.fidx): # If the frame is in a different GOP, reset the iterator + self.it = self.decoder.get_iterator(read_start) + self.fidx = -1 + while self.fidx < fidx: + self.fidx, frame = next(self.it) + self._cache[self.fidx] = frame + return self._cache[fidx] diff --git a/tools/lib/github_utils.py b/tools/lib/github_utils.py new file mode 100644 index 00000000000000..6a443b4155bc7d --- /dev/null +++ b/tools/lib/github_utils.py @@ -0,0 +1,113 @@ +import base64 +import requests +from http import HTTPMethod + +class GithubUtils: + def __init__(self, api_token, data_token, owner='commaai', api_repo='openpilot', data_repo='ci-artifacts'): + self.OWNER = owner + self.API_REPO = api_repo + self.DATA_REPO = data_repo + self.API_TOKEN = api_token + self.DATA_TOKEN = data_token + + @property + def API_ROUTE(self): + return f"https://api.github.com/repos/{self.OWNER}/{self.API_REPO}" + + @property + def DATA_ROUTE(self): + return f"https://api.github.com/repos/{self.OWNER}/{self.DATA_REPO}" + + def api_call(self, path, data="", method=HTTPMethod.GET, accept="", data_call=False, raise_on_failure=True): + token = self.DATA_TOKEN if data_call else self.API_TOKEN + if token: + headers = {"Authorization": f"Bearer {self.DATA_TOKEN if data_call else self.API_TOKEN}", \ + "Accept": f"application/vnd.github{accept}+json"} + else: + headers = {} + path = f'{self.DATA_ROUTE if data_call else self.API_ROUTE}/{path}' + r = requests.request(method, path, headers=headers, data=data) + if not r.ok and raise_on_failure: + raise Exception(f"Call to {path} failed with {r.status_code}") + else: + return r + + def upload_file(self, bucket, path, file_name): + with open(path, "rb") as f: + encoded = base64.b64encode(f.read()).decode() + + # check if file already exists + sha = self.get_file_sha(bucket, file_name) + sha = f'"sha":"{sha}",' if sha else '' + + data = f'{{"message":"uploading {file_name}", \ + "branch":"{bucket}", \ + "committer":{{"name":"Vehicle Researcher", "email": "user@comma.ai"}}, \ + {sha} \ + "content":"{encoded}"}}' + github_path = f"contents/{file_name}" + self.api_call(github_path, data=data, method=HTTPMethod.PUT, data_call=True) + + def upload_files(self, bucket, files): + self.create_bucket(bucket) + for file_name,path in files: + self.upload_file(bucket, path, file_name) + + def create_bucket(self, bucket): + if self.get_bucket_sha(bucket): + return + master_sha = self.get_bucket_sha('master') + github_path = "git/refs" + data = f'{{"ref":"refs/heads/{bucket}", "sha":"{master_sha}"}}' + self.api_call(github_path, data=data, method=HTTPMethod.POST, data_call=True) + + def get_bucket_sha(self, bucket): + github_path = f"git/ref/heads/{bucket}" + r = self.api_call(github_path, data_call=True, raise_on_failure=False) + return r.json()['object']['sha'] if r.ok else None + + def get_file_url(self, bucket, file_name): + github_path = f"contents/{file_name}?ref={bucket}" + r = self.api_call(github_path, data_call=True) + return r.json()['download_url'] + + def get_file_sha(self, bucket, file_name): + github_path = f"contents/{file_name}?ref={bucket}" + r = self.api_call(github_path, data_call=True, raise_on_failure=False) + return r.json()['sha'] if r.ok else None + + def get_pr_number(self, pr_branch): + github_path = f"commits/{pr_branch}/pulls" + r = self.api_call(github_path) + return r.json()[0]['number'] + + def get_bucket_link(self, bucket): + return f'https://raw.githubusercontent.com/{self.OWNER}/{self.DATA_REPO}/refs/heads/{bucket}' + + def comment_on_pr(self, comment, pr_branch, commenter="", overwrite=False): + pr_number = self.get_pr_number(pr_branch) + data = f'{{"body": "{comment}"}}' + github_path = f'issues/{pr_number}/comments' + if overwrite: + r = self.api_call(github_path) + comments = [x['id'] for x in r.json() if x['user']['login'] == commenter] + if comments: + github_path = f'issues/comments/{comments[0]}' + self.api_call(github_path, data=data, method=HTTPMethod.PATCH) + return + + self.api_call(github_path, data=data, method=HTTPMethod.POST) + + # upload files to github and comment them on the pr + def comment_images_on_pr(self, title, commenter, pr_branch, bucket, images): + self.upload_files(bucket, images) + table = [f'
{title}
■ Disengaged
'] + for i,f in enumerate(images): + if not (i % 2): + table.append('') + table.append(f'') + if (i % 2): + table.append('') + table.append('
') + table = ''.join(table) + self.comment_on_pr(table, commenter, pr_branch) diff --git a/tools/lib/helpers.py b/tools/lib/helpers.py index 7c34e17cb1ee0c..8c976e7ecced29 100644 --- a/tools/lib/helpers.py +++ b/tools/lib/helpers.py @@ -9,7 +9,7 @@ class RE: INDEX = r'-?[0-9]+' SLICE = fr'(?P{INDEX})?:?(?P{INDEX})?:?(?P{INDEX})?' - SEGMENT_RANGE = fr'{ROUTE_NAME}(?:(--|/)(?P({SLICE})))?(?:/(?P([qras])))?' + SEGMENT_RANGE = fr'{ROUTE_NAME}(?:(--|/)(?P({SLICE})))?(?:/(?P([qra])))?' BOOTLOG_NAME = ROUTE_NAME diff --git a/tools/lib/kbhit.py b/tools/lib/kbhit.py index 3881ee7d18bc59..c6365cdfecc42a 100755 --- a/tools/lib/kbhit.py +++ b/tools/lib/kbhit.py @@ -4,13 +4,13 @@ import atexit from select import select -STDIN_FD = sys.stdin.fileno() class KBHit: def __init__(self) -> None: ''' Creates a KBHit object that you can call to do various keyboard things. ''' + self.stdin_fd = sys.stdin.fileno() self.set_kbhit_terminal() def set_kbhit_terminal(self) -> None: @@ -18,12 +18,12 @@ def set_kbhit_terminal(self) -> None: ''' # Save the terminal settings - self.old_term = termios.tcgetattr(STDIN_FD) + self.old_term = termios.tcgetattr(self.stdin_fd) self.new_term = self.old_term.copy() # New terminal setting unbuffered self.new_term[3] &= ~(termios.ICANON | termios.ECHO) - termios.tcsetattr(STDIN_FD, termios.TCSAFLUSH, self.new_term) + termios.tcsetattr(self.stdin_fd, termios.TCSAFLUSH, self.new_term) # Support normal-terminal reset at exit atexit.register(self.set_normal_term) @@ -32,7 +32,7 @@ def set_normal_term(self) -> None: ''' Resets to normal terminal. On Windows this is a no-op. ''' - termios.tcsetattr(STDIN_FD, termios.TCSAFLUSH, self.old_term) + termios.tcsetattr(self.stdin_fd, termios.TCSAFLUSH, self.old_term) @staticmethod def getch() -> str: diff --git a/tools/lib/log_time_series.py b/tools/lib/log_time_series.py new file mode 100644 index 00000000000000..5e8aa4f73b3211 --- /dev/null +++ b/tools/lib/log_time_series.py @@ -0,0 +1,84 @@ +import numpy as np + + +def flatten_type_dict(d, sep="/", prefix=None): + res = {} + if isinstance(d, dict): + for key, val in d.items(): + if prefix is None: + res.update(flatten_type_dict(val, prefix=key)) + else: + res.update(flatten_type_dict(val, prefix=prefix + sep + key)) + return res + elif isinstance(d, list): + return {prefix: np.array(d)} + else: + return {prefix: d} + + +def get_message_dict(message, typ): + valid = message.valid + message = message._get(typ) + if not hasattr(message, 'to_dict') or typ in ('qcomGnss', 'ubloxGnss'): + # TODO: support these + #print("skipping", typ) + return + + msg_dict = message.to_dict(verbose=True) + msg_dict = flatten_type_dict(msg_dict) + msg_dict['_valid'] = valid + return msg_dict + + +def append_dict(path, t, d, values): + if path not in values: + group = {} + group["t"] = [] + for k in d: + group[k] = [] + values[path] = group + else: + group = values[path] + + group["t"].append(t) + for k, v in d.items(): + group[k].append(v) + + +def potentially_ragged_array(arr, dtype=None, **kwargs): + # TODO: is there a better way to detect inhomogeneous shapes? + try: + return np.array(arr, dtype=dtype, **kwargs) + except ValueError: + return np.array(arr, dtype=object, **kwargs) + +def msgs_to_time_series(msgs): + """ + Convert an iterable of canonical capnp messages into a dictionary of time series. + Each time series has a value with key "t" which consists of monotonically increasing timestamps + in seconds. + """ + values = {} + for msg in msgs: + typ = msg.which() + + tm = msg.logMonoTime / 1.0e9 + msg_dict = get_message_dict(msg, typ) + if msg_dict is not None: + append_dict(typ, tm, msg_dict, values) + + # Sort values by time. + for group in values.values(): + order = np.argsort(group["t"]) + for name, group_values in group.items(): + group[name] = potentially_ragged_array(group_values)[order] + + return values + + +if __name__ == "__main__": + import sys + from openpilot.tools.lib.logreader import LogReader + m = msgs_to_time_series(LogReader(sys.argv[1])) + print(m['driverCameraState']['t']) + print(np.diff(m['driverCameraState']['timestampSof'])) diff --git a/tools/lib/logreader.py b/tools/lib/logreader.py index cf8748929cdff0..9696c8524d104d 100755 --- a/tools/lib/logreader.py +++ b/tools/lib/logreader.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 import bz2 -from functools import cache, partial +from functools import partial import multiprocessing import capnp import enum @@ -12,15 +12,15 @@ import warnings import zstandard as zstd -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Iterable, Iterator from urllib.parse import parse_qs, urlparse from cereal import log as capnp_log from openpilot.common.swaglog import cloudlog -from openpilot.tools.lib.comma_car_segments import get_url as get_comma_segments_url -from openpilot.tools.lib.openpilotci import get_url -from openpilot.tools.lib.filereader import FileReader, file_exists, internal_source_available -from openpilot.tools.lib.route import Route, SegmentRange +from openpilot.tools.lib.filereader import FileReader +from openpilot.tools.lib.file_sources import comma_api_source, internal_source, openpilotci_source, comma_car_segments_source, Source +from openpilot.tools.lib.route import SegmentRange, FileName +from openpilot.tools.lib.log_time_series import msgs_to_time_series LogMessage = type[capnp._DynamicStructReader] LogIterable = Iterable[LogMessage] @@ -39,8 +39,55 @@ def save_log(dest, log_msgs, compress=True): f.write(dat) +def decompress_stream(data: bytes): + dctx = zstd.ZstdDecompressor() + decompressed_data = b"" + + with dctx.stream_reader(data) as reader: + decompressed_data = reader.read() + + return decompressed_data + + +class CachedEventReader: + __slots__ = ('_evt', '_enum') + + def __init__(self, evt: capnp._DynamicStructReader, _enum: str | None = None): + """All capnp attribute accesses are expensive, and which() is often called multiple times""" + self._evt = evt + self._enum: str | None = _enum + + # fast pickle support + def __reduce__(self): + return CachedEventReader._reducer, (self._evt.as_builder().to_bytes(), self._enum) + + @staticmethod + def _reducer(data: bytes, _enum: str | None = None): + with capnp_log.Event.from_bytes(data) as evt: + return CachedEventReader(evt, _enum) + + def __repr__(self): + return self._evt.__repr__() + + def __str__(self): + return self._evt.__str__() + + def __dir__(self): + return dir(self._evt) + + def which(self) -> str: + if self._enum is None: + self._enum = self._evt.which() + return self._enum + + def __getattr__(self, name: str): + if name.startswith("__") and name.endswith("__"): + return getattr(self, name) + return getattr(self._evt, name) + + class _LogFileReader: - def __init__(self, fn, canonicalize=True, only_union_types=False, sort_by_time=False, dat=None): + def __init__(self, fn, only_union_types=False, sort_by_time=False, dat=None): self.data_version = None self._only_union_types = only_union_types @@ -49,7 +96,7 @@ def __init__(self, fn, canonicalize=True, only_union_types=False, sort_by_time=F _, ext = os.path.splitext(urllib.parse.urlparse(fn).path) if ext not in ('', '.bz2', '.zst'): # old rlogs weren't compressed - raise Exception(f"unknown extension {ext}") + raise ValueError(f"unknown extension {ext}") with FileReader(fn) as f: dat = f.read() @@ -58,14 +105,14 @@ def __init__(self, fn, canonicalize=True, only_union_types=False, sort_by_time=F dat = bz2.decompress(dat) elif ext == ".zst" or dat.startswith(b'\x28\xB5\x2F\xFD'): # https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#zstandard-frames - dat = zstd.decompress(dat) + dat = decompress_stream(dat) ents = capnp_log.Event.read_multiple_bytes(dat) self._ents = [] try: for e in ents: - self._ents.append(e) + self._ents.append(CachedEventReader(e)) except capnp.KjException: warnings.warn("Corrupted events detected", RuntimeWarning, stacklevel=1) @@ -87,151 +134,93 @@ def __iter__(self) -> Iterator[capnp._DynamicStructReader]: class ReadMode(enum.StrEnum): RLOG = "r" # only read rlogs QLOG = "q" # only read qlogs - SANITIZED = "s" # read from the commaCarSegments database AUTO = "a" # default to rlogs, fallback to qlogs AUTO_INTERACTIVE = "i" # default to rlogs, fallback to qlogs with a prompt from the user -LogPath = str | None -ValidFileCallable = Callable[[LogPath], bool] -Source = Callable[[SegmentRange, ReadMode], list[LogPath]] - -InternalUnavailableException = Exception("Internal source not available") - - -@cache -def default_valid_file(fn: LogPath) -> bool: - return fn is not None and file_exists(fn) - - -def auto_strategy(rlog_paths: list[LogPath], qlog_paths: list[LogPath], interactive: bool, valid_file: ValidFileCallable) -> list[LogPath]: - # auto select logs based on availability - missing_rlogs = [rlog is None or not valid_file(rlog) for rlog in rlog_paths].count(True) - if missing_rlogs != 0: - if interactive: - if input(f"{missing_rlogs}/{len(rlog_paths)} rlogs were not found, would you like to fallback to qlogs for those segments? (y/n) ").lower() != "y": - return rlog_paths - else: - cloudlog.warning(f"{missing_rlogs}/{len(rlog_paths)} rlogs were not found, falling back to qlogs for those segments...") - - return [rlog if valid_file(rlog) else (qlog if valid_file(qlog) else None) - for (rlog, qlog) in zip(rlog_paths, qlog_paths, strict=True)] - return rlog_paths - - -def apply_strategy(mode: ReadMode, rlog_paths: list[LogPath], qlog_paths: list[LogPath], valid_file: ValidFileCallable = default_valid_file) -> list[LogPath]: - if mode == ReadMode.RLOG: - return rlog_paths - elif mode == ReadMode.QLOG: - return qlog_paths - elif mode == ReadMode.AUTO: - return auto_strategy(rlog_paths, qlog_paths, False, valid_file) - elif mode == ReadMode.AUTO_INTERACTIVE: - return auto_strategy(rlog_paths, qlog_paths, True, valid_file) - raise Exception(f"invalid mode: {mode}") - - -def comma_api_source(sr: SegmentRange, mode: ReadMode) -> list[LogPath]: - route = Route(sr.route_name) - - rlog_paths = [route.log_paths()[seg] for seg in sr.seg_idxs] - qlog_paths = [route.qlog_paths()[seg] for seg in sr.seg_idxs] - - # comma api will have already checked if the file exists - def valid_file(fn): - return fn is not None - - return apply_strategy(mode, rlog_paths, qlog_paths, valid_file=valid_file) +class LogsUnavailable(Exception): + pass -def internal_source(sr: SegmentRange, mode: ReadMode, file_ext: str = "bz2") -> list[LogPath]: - if not internal_source_available(): - raise InternalUnavailableException - - def get_internal_url(sr: SegmentRange, seg, file): - return f"cd:/{sr.dongle_id}/{sr.log_id}/{seg}/{file}.{file_ext}" - - # TODO: list instead of using static URLs to support routes with multiple file extensions - rlog_paths = [get_internal_url(sr, seg, "rlog") for seg in sr.seg_idxs] - qlog_paths = [get_internal_url(sr, seg, "qlog") for seg in sr.seg_idxs] - - return apply_strategy(mode, rlog_paths, qlog_paths) - - -def internal_source_zst(sr: SegmentRange, mode: ReadMode, file_ext: str = "zst") -> list[LogPath]: - return internal_source(sr, mode, file_ext) - - -def openpilotci_source(sr: SegmentRange, mode: ReadMode, file_ext: str = "bz2") -> list[LogPath]: - rlog_paths = [get_url(sr.route_name, seg, f"rlog.{file_ext}") for seg in sr.seg_idxs] - qlog_paths = [get_url(sr.route_name, seg, f"qlog.{file_ext}") for seg in sr.seg_idxs] - - return apply_strategy(mode, rlog_paths, qlog_paths) - - -def openpilotci_source_zst(sr: SegmentRange, mode: ReadMode) -> list[LogPath]: - return openpilotci_source(sr, mode, "zst") - - -def comma_car_segments_source(sr: SegmentRange, mode=ReadMode.RLOG) -> list[LogPath]: - return [get_comma_segments_url(sr.route_name, seg) for seg in sr.seg_idxs] - - -def testing_closet_source(sr: SegmentRange, mode=ReadMode.RLOG) -> list[LogPath]: - if not internal_source_available('http://testing.comma.life'): - raise InternalUnavailableException - return [f"http://testing.comma.life/download/{sr.route_name.replace('|', '/')}/{seg}/rlog" for seg in sr.seg_idxs] +def direct_source(file_or_url: str) -> list[str]: + return [file_or_url] -def direct_source(file_or_url: str) -> list[LogPath]: - return [file_or_url] +# TODO this should apply to camera files as well +def auto_source(identifier: str, sources: list[Source], default_mode: ReadMode) -> list[str]: + exceptions = {} + sr = SegmentRange(identifier) + needed_seg_idxs = sr.seg_idxs -def get_invalid_files(files): - for f in files: - if f is None or not file_exists(f): - yield f + mode = default_mode if sr.selector is None else ReadMode(sr.selector) + if mode == ReadMode.QLOG: + try_fns = [FileName.QLOG] + else: + try_fns = [FileName.RLOG] + # If selector allows it, fallback to qlogs + if mode in (ReadMode.AUTO, ReadMode.AUTO_INTERACTIVE): + try_fns.append(FileName.QLOG) -def check_source(source: Source, *args) -> list[LogPath]: - files = source(*args) - assert len(files) > 0, "No files on source" - assert next(get_invalid_files(files), False) is False, "Some files are invalid" - return files + # Build a dict of valid files as we evaluate each source. May contain mix of rlogs, qlogs, and None. + # This function only returns when we've sourced all files, or throws an exception + valid_files: dict[int, str] = {} + for fn in try_fns: + for source in sources: + try: + files = source(sr, needed_seg_idxs, fn) + # Build a dict of valid files + valid_files |= files -def auto_source(sr: SegmentRange, mode=ReadMode.RLOG, sources: list[Source] = None) -> list[LogPath]: - if mode == ReadMode.SANITIZED: - return comma_car_segments_source(sr, mode) + # Don't check for segment files that have already been found + needed_seg_idxs = [idx for idx in needed_seg_idxs if idx not in valid_files] - if sources is None: - sources = [internal_source, internal_source_zst, openpilotci_source, openpilotci_source_zst, - comma_api_source, comma_car_segments_source, testing_closet_source] - exceptions = {} + # We've found all files, return them + if len(needed_seg_idxs) == 0: + return list(valid_files.values()) + else: + raise FileNotFoundError(f"Did not find {fn} for seg idxs {needed_seg_idxs} of {sr.route_name}") - # for automatic fallback modes, auto_source needs to first check if rlogs exist for any source - if mode in [ReadMode.AUTO, ReadMode.AUTO_INTERACTIVE]: - for source in sources: - try: - return check_source(source, sr, ReadMode.RLOG) - except Exception: - pass + except Exception as e: + exceptions[source.__name__] = e - # Automatically determine viable source - for source in sources: - try: - return check_source(source, sr, mode) - except Exception as e: - exceptions[source.__name__] = e + if fn == try_fns[0]: + missing_logs = len(needed_seg_idxs) + if mode == ReadMode.AUTO: + cloudlog.warning(f"{missing_logs}/{len(sr.seg_idxs)} rlogs were not found, falling back to qlogs for those segments...") + elif mode == ReadMode.AUTO_INTERACTIVE: + if input(f"{missing_logs}/{len(sr.seg_idxs)} rlogs were not found, would you like to fallback to qlogs for those segments? (y/N) ").lower() != "y": + break - raise Exception("auto_source could not find any valid source, exceptions for sources:\n - " + - "\n - ".join([f"{k}: {repr(v)}" for k, v in exceptions.items()])) + missing_logs = len(needed_seg_idxs) + raise LogsUnavailable(f"{missing_logs}/{len(sr.seg_idxs)} logs were not found, please ensure all logs " + + "are uploaded. You can fall back to qlogs with '/a' selector at the end of the route name.\n\n" + + "Exceptions for sources:\n - " + "\n - ".join([f"{k}: {repr(v)}" for k, v in exceptions.items()])) def parse_indirect(identifier: str) -> str: if "useradmin.comma.ai" in identifier: query = parse_qs(urlparse(identifier).query) - return query["onebox"][0] + identifier = query["onebox"][0] + elif "connect.comma.ai" in identifier: + path = urlparse(identifier).path.strip("/").split("/") + path = ['/'.join(path[:2]), *path[2:]] # recombine log id + + identifier = path[0] + if len(path) > 2: + # convert url with seconds to segments + start, end = int(path[1]) // 60, int(path[2]) // 60 + 1 + identifier = f"{identifier}/{start}:{end}" + + # add selector if it exists + if len(path) > 3: + identifier += f"/{path[3]}" + else: + # add selector if it exists + identifier = "/".join(path) + return identifier @@ -242,7 +231,7 @@ def parse_direct(identifier: str): class LogReader: - def _parse_identifier(self, identifier: str) -> list[LogPath]: + def _parse_identifier(self, identifier: str) -> list[str]: # useradmin, etc. identifier = parse_indirect(identifier) @@ -251,20 +240,16 @@ def _parse_identifier(self, identifier: str) -> list[LogPath]: if direct_parsed is not None: return direct_source(identifier) - sr = SegmentRange(identifier) - mode = self.default_mode if sr.selector is None else ReadMode(sr.selector) - - identifiers = self.source(sr, mode) - - invalid_count = len(list(get_invalid_files(identifiers))) - assert invalid_count == 0, (f"{invalid_count}/{len(identifiers)} invalid log(s) found, please ensure all logs " + - "are uploaded or auto fallback to qlogs with '/a' selector at the end of the route name.") + identifiers = auto_source(identifier, self.sources, self.default_mode) return identifiers def __init__(self, identifier: str | list[str], default_mode: ReadMode = ReadMode.RLOG, - source: Source = auto_source, sort_by_time=False, only_union_types=False): + sources: list[Source] | None = None, sort_by_time=False, only_union_types=False): + if sources is None: + sources = [internal_source, comma_api_source, openpilotci_source, comma_car_segments_source] + self.default_mode = default_mode - self.source = source + self.sources = sources self.identifier = identifier if isinstance(identifier, str): self.identifier = [identifier] @@ -287,11 +272,11 @@ def __iter__(self): def _run_on_segment(self, func, i): return func(self._get_lr(i)) - def run_across_segments(self, num_processes, func, desc=None): + def run_across_segments(self, num_processes, func, disable_tqdm=False, desc=None): with multiprocessing.Pool(num_processes) as pool: ret = [] num_segs = len(self.logreader_identifiers) - for p in tqdm.tqdm(pool.imap(partial(self._run_on_segment, func), range(num_segs)), total=num_segs, desc=desc): + for p in tqdm.tqdm(pool.imap(partial(self._run_on_segment, func), range(num_segs)), total=num_segs, disable=disable_tqdm, desc=desc): ret.extend(p) return ret @@ -310,6 +295,10 @@ def filter(self, msg_type: str): def first(self, msg_type: str): return next(self.filter(msg_type), None) + @property + def time_series(self): + return msgs_to_time_series(self) + if __name__ == "__main__": import codecs diff --git a/tools/lib/openpilotci.py b/tools/lib/openpilotci.py index 1c1e1f171b7858..6b484dfdadab0a 100644 --- a/tools/lib/openpilotci.py +++ b/tools/lib/openpilotci.py @@ -1,12 +1,4 @@ -from openpilot.tools.lib.openpilotcontainers import OpenpilotCIContainer +BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" -def get_url(*args, **kwargs): - return OpenpilotCIContainer.get_url(*args, **kwargs) - -def upload_file(*args, **kwargs): - return OpenpilotCIContainer.upload_file(*args, **kwargs) - -def upload_bytes(*args, **kwargs): - return OpenpilotCIContainer.upload_bytes(*args, **kwargs) - -BASE_URL = OpenpilotCIContainer.BASE_URL +def get_url(route_name: str, segment_num, filename: str) -> str: + return BASE_URL + f"{route_name.replace('|', '/')}/{segment_num}/{filename}" diff --git a/tools/lib/route.py b/tools/lib/route.py index ddb8b0486eaf57..98334a06c86a6d 100644 --- a/tools/lib/route.py +++ b/tools/lib/route.py @@ -1,20 +1,24 @@ import os import re +import requests from functools import cache from urllib.parse import urlparse from collections import defaultdict from itertools import chain from openpilot.tools.lib.auth_config import get_token -from openpilot.tools.lib.api import CommaApi +from openpilot.tools.lib.api import APIError, CommaApi from openpilot.tools.lib.helpers import RE -QLOG_FILENAMES = ['qlog', 'qlog.bz2', 'qlog.zst'] -QCAMERA_FILENAMES = ['qcamera.ts'] -LOG_FILENAMES = ['rlog', 'rlog.bz2', 'raw_log.bz2', 'rlog.zst'] -CAMERA_FILENAMES = ['fcamera.hevc', 'video.hevc'] -DCAMERA_FILENAMES = ['dcamera.hevc'] -ECAMERA_FILENAMES = ['ecamera.hevc'] + +class FileName: + RLOG = ("rlog.zst", "rlog.bz2") + QLOG = ("qlog.zst", "qlog.bz2") + QCAMERA = ('qcamera.ts',) + FCAMERA = ('fcamera.hevc',) + ECAMERA = ('ecamera.hevc',) + DCAMERA = ('dcamera.hevc',) + BOOTLOG = ('bootlog.zst', 'bootlog.bz2') class Route: @@ -72,22 +76,22 @@ def _get_segments_remote(self): if segments.get(segment_name): segments[segment_name] = Segment( segment_name, - url if fn in LOG_FILENAMES else segments[segment_name].log_path, - url if fn in QLOG_FILENAMES else segments[segment_name].qlog_path, - url if fn in CAMERA_FILENAMES else segments[segment_name].camera_path, - url if fn in DCAMERA_FILENAMES else segments[segment_name].dcamera_path, - url if fn in ECAMERA_FILENAMES else segments[segment_name].ecamera_path, - url if fn in QCAMERA_FILENAMES else segments[segment_name].qcamera_path, + url if fn in FileName.RLOG else segments[segment_name].log_path, + url if fn in FileName.QLOG else segments[segment_name].qlog_path, + url if fn in FileName.FCAMERA else segments[segment_name].camera_path, + url if fn in FileName.DCAMERA else segments[segment_name].dcamera_path, + url if fn in FileName.ECAMERA else segments[segment_name].ecamera_path, + url if fn in FileName.QCAMERA else segments[segment_name].qcamera_path, ) else: segments[segment_name] = Segment( segment_name, - url if fn in LOG_FILENAMES else None, - url if fn in QLOG_FILENAMES else None, - url if fn in CAMERA_FILENAMES else None, - url if fn in DCAMERA_FILENAMES else None, - url if fn in ECAMERA_FILENAMES else None, - url if fn in QCAMERA_FILENAMES else None, + url if fn in FileName.RLOG else None, + url if fn in FileName.QLOG else None, + url if fn in FileName.FCAMERA else None, + url if fn in FileName.DCAMERA else None, + url if fn in FileName.ECAMERA else None, + url if fn in FileName.QCAMERA else None, ) return sorted(segments.values(), key=lambda seg: seg.name.segment_num) @@ -124,32 +128,32 @@ def _get_segments_local(self, data_dir): for segment, files in segment_files.items(): try: - log_path = next(path for path, filename in files if filename in LOG_FILENAMES) + log_path = next(path for path, filename in files if filename in FileName.RLOG) except StopIteration: log_path = None try: - qlog_path = next(path for path, filename in files if filename in QLOG_FILENAMES) + qlog_path = next(path for path, filename in files if filename in FileName.QLOG) except StopIteration: qlog_path = None try: - camera_path = next(path for path, filename in files if filename in CAMERA_FILENAMES) + camera_path = next(path for path, filename in files if filename in FileName.FCAMERA) except StopIteration: camera_path = None try: - dcamera_path = next(path for path, filename in files if filename in DCAMERA_FILENAMES) + dcamera_path = next(path for path, filename in files if filename in FileName.DCAMERA) except StopIteration: dcamera_path = None try: - ecamera_path = next(path for path, filename in files if filename in ECAMERA_FILENAMES) + ecamera_path = next(path for path, filename in files if filename in FileName.ECAMERA) except StopIteration: ecamera_path = None try: - qcamera_path = next(path for path, filename in files if filename in QCAMERA_FILENAMES) + qcamera_path = next(path for path, filename in files if filename in FileName.QCAMERA) except StopIteration: qcamera_path = None @@ -162,6 +166,7 @@ def _get_segments_local(self, data_dir): class Segment: def __init__(self, name, log_path, qlog_path, camera_path, dcamera_path, ecamera_path, qcamera_path): + self._events = None self._name = SegmentName(name) self.log_path = log_path self.qlog_path = qlog_path @@ -174,6 +179,29 @@ def __init__(self, name, log_path, qlog_path, camera_path, dcamera_path, ecamera def name(self): return self._name + @staticmethod + @cache + def _get_route_metadata(route_name: str): + api = CommaApi(get_token()) + return api.get(f'v1/route/{route_name}') + + @property + def url(self): + route_name = self._name.route_name.canonical_name + metadata = self._get_route_metadata(route_name) + return f'{metadata["url"]}/{self._name.segment_num}' + + @property + def events(self): + if not self._events: + try: + resp = requests.get(f'{self.url}/events.json') + resp.raise_for_status() + self._events = resp.json() + except Exception as e: + raise APIError(f'error getting events for segment {self._name}') from e + return self._events + class RouteName: def __init__(self, name_str: str): @@ -191,9 +219,16 @@ def canonical_name(self) -> str: return self._canonical_name @property def dongle_id(self) -> str: return self._dongle_id + @property + def log_id(self) -> str: return self._time_str + @property def time_str(self) -> str: return self._time_str + @property + def azure_prefix(self): + return f'{self.dongle_id}/{self.log_id}' + def __str__(self) -> str: return self._canonical_name @@ -217,12 +252,23 @@ def __init__(self, name_str: str, allow_route_name=False): @property def canonical_name(self) -> str: return self._canonical_name + # TODO should only use one name + @property + def data_name(self) -> str: return f"{self._route_name.canonical_name}/{self._num}" + + @property + def azure_prefix(self): + return f'{self.dongle_id}/{self.log_id}/{self._num}' + @property def dongle_id(self) -> str: return self._route_name.dongle_id @property def time_str(self) -> str: return self._route_name.time_str + @property + def log_id(self) -> str: return self._route_name.time_str + @property def segment_num(self) -> int: return self._num @@ -234,6 +280,30 @@ def data_dir(self) -> str | None: return self._data_dir def __str__(self) -> str: return self._canonical_name + @staticmethod + def from_file_name(file_name): + # ??????/xxxxxxxxxxxxxxxx|1111-11-11-11--11-11-11/1/rlog.bz2 + dongle_id, route_name, segment_num = file_name.replace('|', '/').split('/')[-4:-1] + return SegmentName(dongle_id + "|" + route_name + "--" + segment_num) + + @staticmethod + def from_device_key(dongle_id, key): + # 2018-05-07--18-56-13--5/rlog.bz2 + segment_name = key.split('/')[0] + return SegmentName(dongle_id + "|" + segment_name) + + @staticmethod + def from_file_key(key): + # 38c52c217150700f/2018-05-07--18-56-13/5/rlog.bz2 + az_prefix = '/'.join(key.split('/')[:3]) + return SegmentName.from_azure_prefix(az_prefix) + + @staticmethod + def from_azure_prefix(prefix): + # xxxxxxxx/1111-11-11-11--11-11-11/0 + dongle_id, route_name, segment_num = prefix.split("/") + return SegmentName(dongle_id + "|" + route_name + "--" + segment_num) + @cache def get_max_seg_number_cached(sr: 'SegmentRange') -> int: diff --git a/tools/lib/tests/test_caching.py b/tools/lib/tests/test_caching.py index 2bb63b4dce581b..cb14098e6dcbca 100644 --- a/tools/lib/tests/test_caching.py +++ b/tools/lib/tests/test_caching.py @@ -2,11 +2,13 @@ import os import shutil import socket +import tempfile import pytest from openpilot.selfdrive.test.helpers import http_server_context from openpilot.system.hardware.hw import Paths -from openpilot.tools.lib.url_file import URLFile +from openpilot.tools.lib.url_file import URLFile, prune_cache +import openpilot.tools.lib.url_file as url_file_module class CachingTestRequestHandler(http.server.BaseHTTPRequestHandler): @@ -54,13 +56,13 @@ def test_pipeline_defaults(self, host): for k, v in retry_defaults.items(): assert getattr(URLFile.pool_manager().connection_pool_kw["retries"], k) == v - # ensure caching off by default and cache dir doesn't get created - os.environ.pop("FILEREADER_CACHE", None) + # ensure caching on by default and cache dir gets created + os.environ.pop("DISABLE_FILEREADER_CACHE", None) if os.path.exists(Paths.download_cache_root()): shutil.rmtree(Paths.download_cache_root()) URLFile(f"{host}/test.txt").get_length() URLFile(f"{host}/test.txt").read() - assert not os.path.exists(Paths.download_cache_root()) + assert os.path.exists(Paths.download_cache_root()) def compare_loads(self, url, start=0, length=None): """Compares range between cached and non cached version""" @@ -88,7 +90,7 @@ def compare_loads(self, url, start=0, length=None): def test_small_file(self): # Make sure we don't force cache - os.environ["FILEREADER_CACHE"] = "0" + os.environ.pop("DISABLE_FILEREADER_CACHE", None) small_file_url = "https://raw.githubusercontent.com/commaai/openpilot/master/docs/SAFETY.md" # If you want large file to be larger than a chunk # large_file_url = "https://commadataci.blob.core.windows.net/openpilotci/0375fdf7b1ce594d/2019-06-13--08-32-25/3/fcamera.hevc" @@ -117,7 +119,10 @@ def test_large_file(self): @pytest.mark.parametrize("cache_enabled", [True, False]) def test_recover_from_missing_file(self, host, cache_enabled): - os.environ["FILEREADER_CACHE"] = "1" if cache_enabled else "0" + if cache_enabled: + os.environ.pop("DISABLE_FILEREADER_CACHE", None) + else: + os.environ["DISABLE_FILEREADER_CACHE"] = "1" file_url = f"{host}/test.png" @@ -128,3 +133,35 @@ def test_recover_from_missing_file(self, host, cache_enabled): CachingTestRequestHandler.FILE_EXISTS = True length = URLFile(file_url).get_length() assert length == 4 + + +class TestCache: + def test_prune_cache(self, monkeypatch): + with tempfile.TemporaryDirectory() as tmpdir: + monkeypatch.setattr(Paths, 'download_cache_root', staticmethod(lambda: tmpdir + "/")) + + # setup test files and manifest + manifest_lines = [] + for i in range(3): + fname = f"hash_{i}" + with open(tmpdir + "/" + fname, "wb") as f: + f.truncate(1000) + manifest_lines.append(f"{fname} {1000 + i}") + with open(tmpdir + "/manifest.txt", "w") as f: + f.write('\n'.join(manifest_lines)) + + # under limit, shouldn't prune + assert len(os.listdir(tmpdir)) == 4 + prune_cache() + assert len(os.listdir(tmpdir)) == 4 + + # set a tiny cache limit to force eviction (1.5 chunks worth) + monkeypatch.setattr(url_file_module, 'CACHE_SIZE', url_file_module.CHUNK_SIZE + url_file_module.CHUNK_SIZE // 2) + + # prune_cache should evict oldest files to get under limit + prune_cache() + remaining = os.listdir(tmpdir) + # should have evicted at least one file + manifest + assert len(remaining) < 4 + # newest file should remain + assert manifest_lines[2].split()[0] in remaining diff --git a/tools/lib/tests/test_logreader.py b/tools/lib/tests/test_logreader.py index 230b6a65eabde0..123f142383a308 100644 --- a/tools/lib/tests/test_logreader.py +++ b/tools/lib/tests/test_logreader.py @@ -7,10 +7,11 @@ import pytest import requests -from parameterized import parameterized +from openpilot.common.parameterized import parameterized from cereal import log as capnp_log -from openpilot.tools.lib.logreader import LogIterable, LogReader, comma_api_source, parse_indirect, ReadMode, InternalUnavailableException +from openpilot.tools.lib.logreader import LogsUnavailable, LogIterable, LogReader, parse_indirect, ReadMode +from openpilot.tools.lib.file_sources import comma_api_source, InternalUnavailableException from openpilot.tools.lib.route import SegmentRange from openpilot.tools.lib.url_file import URLFileException @@ -36,12 +37,12 @@ def setup_source_scenario(mocker, is_internal=False): comma_api_source_mock.__name__ = comma_api_source_mock._mock_name if is_internal: - internal_source_mock.return_value = [QLOG_FILE] + internal_source_mock.return_value = {3: QLOG_FILE} else: internal_source_mock.side_effect = InternalUnavailableException - openpilotci_source_mock.return_value = [None] - comma_api_source_mock.return_value = [QLOG_FILE] + openpilotci_source_mock.return_value = {} + comma_api_source_mock.return_value = {3: QLOG_FILE} yield @@ -71,6 +72,7 @@ class TestLogReader: (f"https://useradmin.comma.ai/?onebox={TEST_ROUTE.replace('/', '|')}", ALL_SEGS), (f"https://useradmin.comma.ai/?onebox={TEST_ROUTE.replace('/', '%7C')}", ALL_SEGS), ]) + @pytest.mark.skip("this got flaky. internet tests are stupid.") def test_indirect_parsing(self, identifier, expected): parsed = parse_indirect(identifier) sr = SegmentRange(parsed) @@ -90,8 +92,11 @@ def test_canonical_name(self, identifier, expected): @pytest.mark.parametrize("cache_enabled", [True, False]) def test_direct_parsing(self, mocker, cache_enabled): - file_exists_mock = mocker.patch("openpilot.tools.lib.logreader.file_exists") - os.environ["FILEREADER_CACHE"] = "1" if cache_enabled else "0" + file_exists_mock = mocker.patch("openpilot.tools.lib.filereader.file_exists") + if cache_enabled: + os.environ.pop("DISABLE_FILEREADER_CACHE", None) + else: + os.environ["DISABLE_FILEREADER_CACHE"] = "1" qlog = tempfile.NamedTemporaryFile(mode='wb', delete=False) with requests.get(QLOG_FILE, stream=True) as r: @@ -179,7 +184,10 @@ def test_helpers(self): @parameterized.expand([(True,), (False,)]) @pytest.mark.slow def test_run_across_segments(self, cache_enabled): - os.environ["FILEREADER_CACHE"] = "1" if cache_enabled else "0" + if cache_enabled: + os.environ.pop("DISABLE_FILEREADER_CACHE", None) + else: + os.environ["DISABLE_FILEREADER_CACHE"] = "1" lr = LogReader(f"{TEST_ROUTE}/0:4") assert len(lr.run_across_segments(4, noop)) == len(list(lr)) @@ -193,28 +201,27 @@ def test_auto_mode(self, subtests, mocker): with subtests.test("interactive_yes"): mocker.patch("sys.stdin", new=io.StringIO("y\n")) - lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO_INTERACTIVE, source=comma_api_source) + lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO_INTERACTIVE, sources=[comma_api_source]) log_len = len(list(lr)) assert qlog_len == log_len with subtests.test("interactive_no"): mocker.patch("sys.stdin", new=io.StringIO("n\n")) - with pytest.raises(AssertionError): - lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO_INTERACTIVE, source=comma_api_source) + with pytest.raises(LogsUnavailable): + lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO_INTERACTIVE, sources=[comma_api_source]) with subtests.test("non_interactive"): - lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO, source=comma_api_source) + lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO, sources=[comma_api_source]) log_len = len(list(lr)) assert qlog_len == log_len @pytest.mark.parametrize("is_internal", [True, False]) - @pytest.mark.slow def test_auto_source_scenarios(self, mocker, is_internal): lr = LogReader(QLOG_FILE) qlog_len = len(list(lr)) with setup_source_scenario(mocker, is_internal=is_internal): - lr = LogReader(f"{TEST_ROUTE}/0/q") + lr = LogReader(f"{TEST_ROUTE}/3/q") log_len = len(list(lr)) assert qlog_len == log_len diff --git a/tools/lib/tests/test_readers.py b/tools/lib/tests/test_readers.py deleted file mode 100644 index 624531a1a856d2..00000000000000 --- a/tools/lib/tests/test_readers.py +++ /dev/null @@ -1,63 +0,0 @@ -import pytest -import requests -import tempfile - -from collections import defaultdict -import numpy as np -from openpilot.tools.lib.framereader import FrameReader -from openpilot.tools.lib.logreader import LogReader - - -class TestReaders: - @pytest.mark.skip("skip for bandwidth reasons") - def test_logreader(self): - def _check_data(lr): - hist = defaultdict(int) - for l in lr: - hist[l.which()] += 1 - - assert hist['carControl'] == 6000 - assert hist['logMessage'] == 6857 - - with tempfile.NamedTemporaryFile(suffix=".bz2") as fp: - r = requests.get("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/raw_log.bz2?raw=true", timeout=10) - fp.write(r.content) - fp.flush() - - lr_file = LogReader(fp.name) - _check_data(lr_file) - - lr_url = LogReader("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/raw_log.bz2?raw=true") - _check_data(lr_url) - - @pytest.mark.skip("skip for bandwidth reasons") - def test_framereader(self): - def _check_data(f): - assert f.frame_count == 1200 - assert f.w == 1164 - assert f.h == 874 - - frame_first_30 = f.get(0, 30) - assert len(frame_first_30) == 30 - - print(frame_first_30[15]) - - print("frame_0") - frame_0 = f.get(0, 1) - frame_15 = f.get(15, 1) - - print(frame_15[0]) - - assert np.all(frame_first_30[0] == frame_0[0]) - assert np.all(frame_first_30[15] == frame_15[0]) - - with tempfile.NamedTemporaryFile(suffix=".hevc") as fp: - r = requests.get("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/video.hevc?raw=true", timeout=10) - fp.write(r.content) - fp.flush() - - fr_file = FrameReader(fp.name) - _check_data(fr_file) - - fr_url = FrameReader("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/video.hevc?raw=true") - _check_data(fr_url) diff --git a/tools/lib/url_file.py b/tools/lib/url_file.py index 2d3d14ce8a456a..de120704659620 100644 --- a/tools/lib/url_file.py +++ b/tools/lib/url_file.py @@ -1,31 +1,61 @@ import logging import os +import re import socket import time -from hashlib import sha256 +from hashlib import md5 from urllib3 import PoolManager, Retry from urllib3.response import BaseHTTPResponse from urllib3.util import Timeout -from openpilot.common.file_helpers import atomic_write_in_dir +from openpilot.common.utils import atomic_write from openpilot.system.hardware.hw import Paths +from urllib3.exceptions import MaxRetryError + # Cache chunk size K = 1000 CHUNK_SIZE = 1000 * K +CACHE_SIZE = 10 * 1024 * 1024 * 1024 # total cache size in GB logging.getLogger("urllib3").setLevel(logging.WARNING) -def hash_256(link: str) -> str: - hsh = str(sha256((link.split("?")[0]).encode('utf-8')).hexdigest()) - return hsh +def hash_url(link: str) -> str: + return md5((link.split("?")[0]).encode('utf-8')).hexdigest() + + +def prune_cache(new_entry: str | None = None) -> None: + """Evicts oldest cache files (LRU) until cache is under the size limit.""" + # we use a manifest to avoid tons of os.stat syscalls (slow) + manifest = {} + manifest_path = Paths.download_cache_root() + "manifest.txt" + if os.path.exists(manifest_path): + with open(manifest_path) as f: + manifest = {parts[0]: int(parts[1]) for line in f if (parts := line.strip().split()) and len(parts) == 2} + + if new_entry: + manifest[new_entry] = int(time.time()) # noqa: TID251 + + # evict the least recently used files until under limit + sorted_items = sorted(manifest.items(), key=lambda x: x[1]) + while len(manifest) * CHUNK_SIZE > CACHE_SIZE and sorted_items: + key, _ = sorted_items.pop(0) + try: + os.remove(Paths.download_cache_root() + key) + except OSError: + pass + manifest.pop(key, None) + + # write out manifest + with atomic_write(manifest_path, mode="w", overwrite=True) as f: + f.write('\n'.join(f"{k} {v}" for k, v in manifest.items())) class URLFileException(Exception): pass class URLFile: - _pool_manager: PoolManager|None = None + _pool_manager: PoolManager | None = None @staticmethod def reset() -> None: @@ -34,19 +64,18 @@ def reset() -> None: @staticmethod def pool_manager() -> PoolManager: if URLFile._pool_manager is None: - socket_options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),] + socket_options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] retries = Retry(total=5, backoff_factor=0.5, status_forcelist=[409, 429, 503, 504]) URLFile._pool_manager = PoolManager(num_pools=10, maxsize=100, socket_options=socket_options, retries=retries) return URLFile._pool_manager - def __init__(self, url: str, timeout: int=10, debug: bool=False, cache: bool|None=None): + def __init__(self, url: str, timeout: int = 10, cache: bool | None = None): self._url = url self._timeout = Timeout(connect=timeout, read=timeout) self._pos = 0 - self._length: int|None = None - self._debug = debug - # True by default, false if FILEREADER_CACHE is defined, but can be overwritten by the cache input - self._force_download = not int(os.environ.get("FILEREADER_CACHE", "0")) + self._length: int | None = None + # Caching enabled by default, can be disabled with DISABLE_FILEREADER_CACHE=1, or overwritten by the cache input + self._force_download = int(os.environ.get("DISABLE_FILEREADER_CACHE", "0")) == 1 if cache is not None: self._force_download = not cache @@ -59,8 +88,11 @@ def __enter__(self): def __exit__(self, exc_type, exc_value, traceback) -> None: pass - def _request(self, method: str, url: str, headers: dict[str, str]|None=None) -> BaseHTTPResponse: - return URLFile.pool_manager().request(method, url, timeout=self._timeout, headers=headers) + def _request(self, method: str, url: str, headers: dict[str, str] | None = None) -> BaseHTTPResponse: + try: + return URLFile.pool_manager().request(method, url, timeout=self._timeout, headers=headers) + except MaxRetryError as e: + raise URLFileException(f"Failed to {method} {url}: {e}") from e def get_length_online(self) -> int: response = self._request('HEAD', self._url) @@ -73,7 +105,7 @@ def get_length(self) -> int: if self._length is not None: return self._length - file_length_path = os.path.join(Paths.download_cache_root(), hash_256(self._url) + "_length") + file_length_path = os.path.join(Paths.download_cache_root(), hash_url(self._url) + "_length") if not self._force_download and os.path.exists(file_length_path): with open(file_length_path) as file_length: content = file_length.read() @@ -82,11 +114,11 @@ def get_length(self) -> int: self._length = self.get_length_online() if not self._force_download and self._length != -1: - with atomic_write_in_dir(file_length_path, mode="w") as file_length: + with atomic_write(file_length_path, mode="w", overwrite=True) as file_length: file_length.write(str(self._length)) return self._length - def read(self, ll: int|None=None) -> bytes: + def read(self, ll: int | None = None) -> bytes: if self._force_download: return self.read_aux(ll=ll) @@ -99,14 +131,15 @@ def read(self, ll: int|None=None) -> bytes: while True: self._pos = position chunk_number = self._pos / CHUNK_SIZE - file_name = hash_256(self._url) + "_" + str(chunk_number) + file_name = hash_url(self._url) + "_" + str(chunk_number) full_path = os.path.join(Paths.download_cache_root(), str(file_name)) data = None # If we don't have a file, download it if not os.path.exists(full_path): data = self.read_aux(ll=CHUNK_SIZE) - with atomic_write_in_dir(full_path, mode="wb") as new_cached_file: + with atomic_write(full_path, mode="wb", overwrite=True) as new_cached_file: new_cached_file.write(data) + prune_cache(file_name) else: with open(full_path, "rb") as cached_file: data = cached_file.read() @@ -118,43 +151,66 @@ def read(self, ll: int|None=None) -> bytes: self._pos = file_end return response - def read_aux(self, ll: int|None=None) -> bytes: - download_range = False - headers = {} - if self._pos != 0 or ll is not None: - if ll is None: - end = self.get_length() - 1 - else: - end = min(self._pos + ll, self.get_length()) - 1 - if self._pos >= end: - return b"" - headers['Range'] = f"bytes={self._pos}-{end}" - download_range = True - - if self._debug: - t1 = time.time() - - response = self._request('GET', self._url, headers=headers) - ret = response.data - - if self._debug: - t2 = time.time() - if t2 - t1 > 0.1: - print(f"get {self._url} {headers!r} {t2 - t1:.3f} slow") - - response_code = response.status - if response_code == 416: # Requested Range Not Satisfiable - raise URLFileException(f"Error, range out of bounds {response_code} {headers} ({self._url}): {repr(ret)[:500]}") - if download_range and response_code != 206: # Partial Content - raise URLFileException(f"Error, requested range but got unexpected response {response_code} {headers} ({self._url}): {repr(ret)[:500]}") - if (not download_range) and response_code != 200: # OK - raise URLFileException(f"Error {response_code} {headers} ({self._url}): {repr(ret)[:500]}") - - self._pos += len(ret) - return ret - - def seek(self, pos:int) -> None: - self._pos = pos + def read_aux(self, ll: int | None = None) -> bytes: + if ll is None: + length = self.get_length() + if length == -1: + raise URLFileException(f"Remote file is empty or doesn't exist: {self._url}") + end = length + else: + end = self._pos + ll + data = self.get_multi_range([(self._pos, end)]) + self._pos += len(data[0]) + return data[0] + + def get_multi_range(self, ranges: list[tuple[int, int]]) -> list[bytes]: + # HTTP range requests are inclusive + assert all(e > s for s, e in ranges), "Range end must be greater than start" + rs = [f"{s}-{e-1}" for s, e in ranges if e > s] + + r = self._request("GET", self._url, headers={"Range": "bytes=" + ",".join(rs)}) + if r.status not in [200, 206]: + raise URLFileException(f"Expected 206 or 200 response {r.status} ({self._url})") + + ctype = (r.headers.get("content-type") or "").lower() + if "multipart/byteranges" not in ctype: + return [r.data,] + + m = re.search(r'boundary="?([^";]+)"?', ctype) + if not m: + raise URLFileException(f"Missing multipart boundary ({self._url})") + boundary = m.group(1).encode() + + parts = [] + for chunk in r.data.split(b"--" + boundary): + if b"\r\n\r\n" not in chunk: + continue + payload = chunk.split(b"\r\n\r\n", 1)[1].rstrip(b"\r\n") + if payload and payload != b"--": + parts.append(payload) + if len(parts) != len(ranges): + raise URLFileException(f"Expected {len(ranges)} parts, got {len(parts)} ({self._url})") + return parts + + def seekable(self) -> bool: + return True + + def seek(self, pos: int, whence: int = 0) -> int: + pos = int(pos) + if whence == os.SEEK_SET: + self._pos = pos + elif whence == os.SEEK_CUR: + self._pos += pos + elif whence == os.SEEK_END: + length = self.get_length() + assert length != -1, "Cannot seek from end on unknown length file" + self._pos = length + pos + else: + raise URLFileException("Invalid whence value") + return self._pos + + def tell(self) -> int: + return self._pos @property def name(self) -> str: diff --git a/tools/lib/vidindex.py b/tools/lib/vidindex.py index f2e4e9ca45e3e9..4aef6fb4d5a039 100755 --- a/tools/lib/vidindex.py +++ b/tools/lib/vidindex.py @@ -140,7 +140,7 @@ def get_ue(dat: bytes, start_idx: int, skip_bits: int) -> tuple[int, int]: j -= 1 if prefix_val == 1 and prefix_len - 1 == suffix_len: - val = 2**(prefix_len-1) - 1 + suffix_val + val = int(2**(prefix_len-1) - 1 + suffix_val) size = prefix_len + suffix_len return val, size i += 1 diff --git a/tools/longitudinal_maneuvers/.gitignore b/tools/longitudinal_maneuvers/.gitignore new file mode 100644 index 00000000000000..e819fa62683a97 --- /dev/null +++ b/tools/longitudinal_maneuvers/.gitignore @@ -0,0 +1 @@ +/longitudinal_reports/ diff --git a/tools/longitudinal_maneuvers/README.md b/tools/longitudinal_maneuvers/README.md new file mode 100644 index 00000000000000..643af7fd826e18 --- /dev/null +++ b/tools/longitudinal_maneuvers/README.md @@ -0,0 +1,48 @@ +# Longitudinal Maneuvers Testing Tool + +Test your vehicle's longitudinal control tuning with this tool. The tool will test the vehicle's ability to follow a few longitudinal maneuvers and includes a tool to generate a report from the route. + +
Sample snapshot of a report.
+ +## Instructions + +1. Check out a development branch such as `master` on your comma device. +2. Locate either a large empty parking lot or road devoid of any car or foot traffic. Flat, straight road is preferred. The full maneuver suite can take 1 mile or more if left running, however it is recommended to disengage openpilot between maneuvers and turn around if there is not enough space. +3. Turn off the vehicle and set this parameter which will signal to openpilot to start the longitudinal maneuver daemon: + + ```sh + echo -n 1 > /data/params/d/LongitudinalManeuverMode + ``` + +4. Turn your vehicle back on. You will see the "Longitudinal Maneuver Mode" alert: + + ![videoframe_6652](https://github.com/user-attachments/assets/e9d4c95a-cd76-4ab7-933e-19937792fa0f) + +5. Ensure the road ahead is clear, as openpilot will not brake for any obstructions in this mode. Once you are ready, press "Set" on your steering wheel to start the tests. The tests will run for about 4 minutes. If you need to pause the tests, press "Cancel" on your steering wheel. You can resume the tests by pressing "Resume" on your steering wheel. + + **Note:** For GM cars, it is recommended to hold down the resume button for all low-speed tests (starting, stopping and creep) to avoid the car entering standstill. + + ![cog-clip-00 01 11 250-00 01 22 250](https://github.com/user-attachments/assets/c312c1cc-76e8-46e1-a05e-bb9dfb58994f) + +6. When the testing is complete, you'll see an alert that says "Maneuvers Finished." Complete the route by pulling over and turning off the vehicle. + + ![fin2](https://github.com/user-attachments/assets/c06960ae-7cfb-44af-beaa-4dc28848e49d) + +7. Visit https://connect.comma.ai and locate the route(s). They will stand out with lots of orange intervals in their timeline. Ensure "All logs" show as "uploaded." + + ![image](https://github.com/user-attachments/assets/cfe4c6d9-752f-4b24-b421-4b90a01933dc) + +8. Gather the route ID and then run the report generator. The file will be exported to the same directory: + + ```sh + $ python tools/longitudinal_maneuvers/generate_report.py 57048cfce01d9625/0000010e--5b26bc3be7 'pcm accel compensation' + + processing report for LEXUS_ES_TSS2 + plotting maneuver: start from stop, runs: 4 + plotting maneuver: creep: alternate between +1m/s^2 and -1m/s^2, runs: 2 + plotting maneuver: gas step response: +1m/s^2 from 20mph, runs: 2 + + Report written to /home/batman/openpilot/tools/longitudinal_maneuvers/longitudinal_reports/LEXUS_ES_TSS2_57048cfce01d9625_0000010e--5b26bc3be7.html + ``` + +You can reach out on [Discord](https://discord.comma.ai) if you have any questions about these instructions or the tool itself. diff --git a/tools/longitudinal_maneuvers/generate_report.py b/tools/longitudinal_maneuvers/generate_report.py new file mode 100755 index 00000000000000..32bdb5b1c4cb09 --- /dev/null +++ b/tools/longitudinal_maneuvers/generate_report.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +import argparse +import base64 +import io +import os +import math +import pprint +import webbrowser +from collections import defaultdict +from pathlib import Path +import matplotlib.pyplot as plt +from openpilot.common.utils import tabulate + +from openpilot.tools.lib.logreader import LogReader +from openpilot.system.hardware.hw import Paths + + +def format_car_params(CP): + return pprint.pformat({k: v for k, v in CP.to_dict().items() if not k.endswith('DEPRECATED')}, indent=2) + + +def report(platform, route, _description, CP, ID, maneuvers): + output_path = Path(__file__).resolve().parent / "longitudinal_reports" + output_fn = output_path / f"{platform}_{route.replace('/', '_')}.html" + output_path.mkdir(exist_ok=True) + target_cross_times = defaultdict(list) + + builder = [ + "\n", + "

Longitudinal maneuver report

\n", + f"

{platform}

\n", + f"

{route}

\n", + f"

{ID.gitCommit}, {ID.gitBranch}, {ID.gitRemote}

\n", + ] + if _description is not None: + builder.append(f"

Description: {_description}

\n") + builder.append(f"

CarParams

{format_car_params(CP)}
\n") + builder.append('{ summary }') # to be replaced below + for description, runs in maneuvers: + print(f'plotting maneuver: {description}, runs: {len(runs)}') + builder.append("
\n") + builder.append(f"

{description}

\n") + for run, msgs in enumerate(runs): + t_carControl, carControl = zip(*[(m.logMonoTime, m.carControl) for m in msgs if m.which() == 'carControl'], strict=True) + t_carOutput, carOutput = zip(*[(m.logMonoTime, m.carOutput) for m in msgs if m.which() == 'carOutput'], strict=True) + t_carState, carState = zip(*[(m.logMonoTime, m.carState) for m in msgs if m.which() == 'carState'], strict=True) + t_livePose, livePose = zip(*[(m.logMonoTime, m.livePose) for m in msgs if m.which() == 'livePose'], strict=True) + t_longitudinalPlan, longitudinalPlan = zip(*[(m.logMonoTime, m.longitudinalPlan) for m in msgs if m.which() == 'longitudinalPlan'], strict=True) + + # make time relative seconds + t_carControl = [(t - t_carControl[0]) / 1e9 for t in t_carControl] + t_carOutput = [(t - t_carOutput[0]) / 1e9 for t in t_carOutput] + t_carState = [(t - t_carState[0]) / 1e9 for t in t_carState] + t_livePose = [(t - t_livePose[0]) / 1e9 for t in t_livePose] + t_longitudinalPlan = [(t - t_longitudinalPlan[0]) / 1e9 for t in t_longitudinalPlan] + + # maneuver validity + longActive = [m.longActive for m in carControl] + maneuver_valid = all(longActive) and (not any(cs.cruiseState.standstill for cs in carState) or CP.autoResumeSng) + + _open = 'open' if maneuver_valid else '' + title = f'Run #{int(run)+1}' + (' (invalid maneuver!)' if not maneuver_valid else '') + + builder.append(f"

{title}

\n") + + # get first acceleration target and first intersection + aTarget = longitudinalPlan[0].aTarget + target_cross_time = None + builder.append(f'

Initial aTarget: {round(aTarget, 2)} m/s^2') + + # Localizer is noisy, require two consecutive 20Hz frames above threshold + prev_crossed = False + for t, lp in zip(t_livePose, livePose, strict=True): + crossed = (0 < aTarget < lp.accelerationDevice.x) or (0 > aTarget > lp.accelerationDevice.x) + if crossed and prev_crossed: + builder.append(f', crossed in {t:.3f}s') + target_cross_time = t + if maneuver_valid: + target_cross_times[description].append(t) + break + prev_crossed = crossed + else: + builder.append(', not crossed') + builder.append('

') + + pitches = [math.degrees(m.orientationNED[1]) for m in carControl] + builder.append(f'

Average pitch: {sum(pitches) / len(pitches):0.2f} degrees

') + + plt.rcParams['font.size'] = 40 + fig = plt.figure(figsize=(30, 26)) + ax = fig.subplots(4, 1, sharex=True, gridspec_kw={'height_ratios': [5, 3, 1, 1]}) + + ax[0].grid(linewidth=4) + ax[0].plot(t_carControl, [m.actuators.accel for m in carControl], label='carControl.actuators.accel', linewidth=6) + ax[0].plot(t_carOutput, [m.actuatorsOutput.accel for m in carOutput], label='carOutput.actuatorsOutput.accel', linewidth=6) + ax[0].plot(t_longitudinalPlan, [m.aTarget for m in longitudinalPlan], label='longitudinalPlan.aTarget', linewidth=6) + ax[0].plot(t_carState, [m.aEgo for m in carState], label='carState.aEgo', linewidth=6) + ax[0].plot(t_livePose, [m.accelerationDevice.x for m in livePose], label='livePose.accelerationDevice.x', linewidth=6) + # TODO localizer accel + ax[0].set_ylabel('Acceleration (m/s^2)') + #ax[0].set_ylim(-6.5, 6.5) + ax[0].legend(prop={'size': 30}) + + if target_cross_time is not None: + ax[0].plot(target_cross_time, aTarget, marker='o', markersize=50, markeredgewidth=7, markeredgecolor='black', markerfacecolor='None') + + ax[1].grid(linewidth=4) + ax[1].plot(t_carState, [m.vEgo for m in carState], 'g', label='vEgo', linewidth=6) + ax[1].set_ylabel('Velocity (m/s)') + ax[1].legend() + + ax[2].plot(t_carControl, longActive, label='longActive', linewidth=6) + ax[3].plot(t_carState, [m.gasPressed for m in carState], label='gasPressed', linewidth=6) + ax[3].plot(t_carState, [m.brakePressed for m in carState], label='brakePressed', linewidth=6) + for i in (2, 3): + ax[i].set_yticks([0, 1], minor=False) + ax[i].set_ylim(-1, 2) + ax[i].legend() + + ax[-1].set_xlabel("Time (s)") + fig.tight_layout() + + buffer = io.BytesIO() + fig.savefig(buffer, format='webp') + plt.close(fig) + buffer.seek(0) + builder.append(f"\n") + builder.append("
\n") + + summary = ["

Summary

\n"] + cols = ['maneuver', 'crossed', 'runs', 'mean', 'min', 'max'] + table = [] + for description, runs in maneuvers: + times = target_cross_times[description] + l = [description, len(times), len(runs)] + if len(times): + l.extend([round(sum(times) / len(times), 2), round(min(times), 2), round(max(times), 2)]) + table.append(l) + summary.append(tabulate(table, headers=cols, tablefmt='html', numalign='left') + '\n') + + sum_idx = builder.index('{ summary }') + builder[sum_idx:sum_idx + 1] = summary + + with open(output_fn, "w") as f: + f.write(''.join(builder)) + + print(f"\nOpening report: {output_fn}\n") + webbrowser.open_new_tab(str(output_fn)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Generate longitudinal maneuver report from route') + parser.add_argument('route', type=str, help='Route name (e.g. 00000000--5f742174be)') + parser.add_argument('description', type=str, nargs='?') + + args = parser.parse_args() + + if '/' in args.route or '|' in args.route: + lr = LogReader(args.route) + else: + segs = [seg for seg in os.listdir(Paths.log_root()) if args.route in seg] + lr = LogReader([os.path.join(Paths.log_root(), seg, 'rlog.zst') for seg in segs]) + + CP = lr.first('carParams') + ID = lr.first('initData') + platform = CP.carFingerprint + print('processing report for', platform) + + maneuvers: list[tuple[str, list[list]]] = [] + active_prev = False + description_prev = None + + for msg in lr: + if msg.which() == 'alertDebug': + active = 'Maneuver Active' in msg.alertDebug.alertText1 + if active and not active_prev: + if msg.alertDebug.alertText2 == description_prev: + maneuvers[-1][1].append([]) + else: + maneuvers.append((msg.alertDebug.alertText2, [[]])) + description_prev = maneuvers[-1][0] + active_prev = active + + if active_prev: + maneuvers[-1][1][-1].append(msg) + + report(platform, args.route, args.description, CP, ID, maneuvers) diff --git a/tools/longitudinal_maneuvers/maneuver_helpers.py b/tools/longitudinal_maneuvers/maneuver_helpers.py new file mode 100644 index 00000000000000..9fc65fb9e679b5 --- /dev/null +++ b/tools/longitudinal_maneuvers/maneuver_helpers.py @@ -0,0 +1,18 @@ +from enum import IntEnum + +class Axis(IntEnum): + TIME = 0 + EGO_POSITION = 1 + LEAD_DISTANCE= 2 + EGO_V = 3 + LEAD_V = 4 + EGO_A = 5 + D_REL = 6 + +axis_labels = {Axis.TIME: 'Time (s)', + Axis.EGO_POSITION: 'Ego position (m)', + Axis.LEAD_DISTANCE: 'Lead absolute position (m)', + Axis.EGO_V: 'Ego Velocity (m/s)', + Axis.LEAD_V: 'Lead Velocity (m/s)', + Axis.EGO_A: 'Ego acceleration (m/s^2)', + Axis.D_REL: 'Lead distance (m)'} diff --git a/tools/longitudinal_maneuvers/maneuversd.py b/tools/longitudinal_maneuvers/maneuversd.py new file mode 100755 index 00000000000000..f8dc6787cc488b --- /dev/null +++ b/tools/longitudinal_maneuvers/maneuversd.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +import numpy as np +from dataclasses import dataclass + +from cereal import messaging, car +from openpilot.common.constants import CV +from openpilot.common.realtime import DT_MDL +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog + + +@dataclass +class Action: + accel_bp: list[float] # m/s^2 + time_bp: list[float] # seconds + + def __post_init__(self): + assert len(self.accel_bp) == len(self.time_bp) + + +@dataclass +class Maneuver: + description: str + actions: list[Action] + repeat: int = 0 + initial_speed: float = 0. # m/s + + _active: bool = False + _finished: bool = False + _run_completed: bool = False + _action_index: int = 0 + _action_frames: int = 0 + _ready_cnt: int = 0 + _repeated: int = 0 + + def _step(self) -> float: + self._run_completed = False + action = self.actions[self._action_index] + action_accel = np.interp(self._action_frames * DT_MDL, action.time_bp, action.accel_bp) + + self._action_frames += 1 + + # reached duration of action + if self._action_frames > (action.time_bp[-1] / DT_MDL): + # next action + if self._action_index < len(self.actions) - 1: + self._action_index += 1 + self._action_frames = 0 + # repeat maneuver + elif self._repeated < self.repeat: + self._repeated += 1 + self._run_completed = True + self.reset() + # finish maneuver + else: + self._run_completed = True + self._finished = True + + return float(action_accel) + + def get_accel(self, v_ego: float, long_active: bool, standstill: bool, cruise_standstill: bool) -> float: + ready = abs(v_ego - self.initial_speed) < 0.3 and long_active and not cruise_standstill + if self.initial_speed < 0.01: + ready = ready and standstill + self._ready_cnt = (self._ready_cnt + 1) if ready else 0 + + if self._ready_cnt > (3. / DT_MDL): + self._active = True + + if not self._active: + return min(max(self.initial_speed - v_ego, -2.), 2.) + + return self._step() + + def reset(self): + self._active = False + self._action_frames = 0 + self._action_index = 0 + + @property + def finished(self): + return self._finished + + @property + def active(self): + return self._active + + +MANEUVERS = [ + Maneuver( + "come to stop", + [Action([-0.5], [12])], + repeat=2, + initial_speed=5., + ), + Maneuver( + "start from stop", + [Action([1.5], [6])], + repeat=2, + initial_speed=0., + ), + Maneuver( + "creep: alternate between +1m/s^2 and -1m/s^2", + [ + Action([1], [3]), Action([-1], [3]), + Action([1], [3]), Action([-1], [3]), + Action([1], [3]), Action([-1], [3]), + ], + repeat=2, + initial_speed=0., + ), + Maneuver( + "brake step response: -1m/s^2 from 20mph", + [Action([-1], [3])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "brake step response: -4m/s^2 from 20mph", + [Action([-4], [3])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "gas step response: +1m/s^2 from 20mph", + [Action([1], [3])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "gas step response: +4m/s^2 from 20mph", + [Action([4], [3])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), +] + + +def main(): + params = Params() + cloudlog.info("joystickd is waiting for CarParams") + CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + + sm = messaging.SubMaster(['carState', 'carControl', 'controlsState', 'selfdriveState', 'modelV2'], poll='modelV2') + pm = messaging.PubMaster(['longitudinalPlan', 'driverAssistance', 'alertDebug']) + + maneuvers = iter(MANEUVERS) + maneuver = None + + while True: + sm.update() + + if maneuver is None: + maneuver = next(maneuvers, None) + + alert_msg = messaging.new_message('alertDebug') + alert_msg.valid = True + + plan_send = messaging.new_message('longitudinalPlan') + plan_send.valid = sm.all_checks() + + longitudinalPlan = plan_send.longitudinalPlan + accel = 0 + v_ego = max(sm['carState'].vEgo, 0) + + if maneuver is not None: + accel = maneuver.get_accel(v_ego, sm['carControl'].longActive, sm['carState'].standstill, sm['carState'].cruiseState.standstill) + + if maneuver.active: + alert_msg.alertDebug.alertText1 = f'Maneuver Active: {accel:0.2f} m/s^2' + else: + alert_msg.alertDebug.alertText1 = f'Setting up to {maneuver.initial_speed * CV.MS_TO_MPH:0.2f} mph' + alert_msg.alertDebug.alertText2 = f'{maneuver.description}' + else: + alert_msg.alertDebug.alertText1 = 'Maneuvers Finished' + + pm.send('alertDebug', alert_msg) + + longitudinalPlan.aTarget = accel + longitudinalPlan.shouldStop = v_ego < CP.vEgoStopping and accel < 1e-2 + + longitudinalPlan.allowBrake = True + longitudinalPlan.allowThrottle = True + longitudinalPlan.hasLead = True + + longitudinalPlan.speeds = [0.2] # triggers carControl.cruiseControl.resume in controlsd + + pm.send('longitudinalPlan', plan_send) + + assistance_send = messaging.new_message('driverAssistance') + assistance_send.valid = True + pm.send('driverAssistance', assistance_send) + + if maneuver is not None and maneuver.finished: + maneuver = None diff --git a/tools/longitudinal_maneuvers/mpc_longitudinal_tuning_report.py b/tools/longitudinal_maneuvers/mpc_longitudinal_tuning_report.py new file mode 100644 index 00000000000000..ae3fee7355af64 --- /dev/null +++ b/tools/longitudinal_maneuvers/mpc_longitudinal_tuning_report.py @@ -0,0 +1,292 @@ +import io +import sys +import markdown +import numpy as np +import matplotlib.pyplot as plt +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.controls.tests.test_following_distance import desired_follow_distance +from openpilot.tools.longitudinal_maneuvers.maneuver_helpers import Axis, axis_labels +from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver + + +def get_html_from_results(results, labels, AXIS): + fig, ax = plt.subplots(figsize=(16, 8)) + for idx, key in enumerate(results.keys()): + ax.plot(results[key][:, Axis.TIME], results[key][:, AXIS], label=labels[idx]) + + ax.set_xlabel(axis_labels[Axis.TIME]) + ax.set_ylabel(axis_labels[AXIS]) + ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0) + ax.grid(True, linestyle='--', alpha=0.7) + ax.text(-0.075, 0.5, '.', transform=ax.transAxes, color='none') + + fig_buffer = io.StringIO() + fig.savefig(fig_buffer, format='svg', bbox_inches='tight') + plt.close(fig) + return fig_buffer.getvalue() + '
' + +def generate_mpc_tuning_report(): + htmls = [] + + results = {} + name = 'Resuming behind lead' + labels = [] + for lead_accel in np.linspace(1.0, 4.0, 4): + man = Maneuver( + '', + duration=11, + initial_speed=0.0, + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(0.0, 0.0), + speed_lead_values=[0.0, 10 * lead_accel], + cruise_values=[100, 100], + prob_lead_values=[1.0, 1.0], + breakpoints=[1., 11], + ) + valid, results[lead_accel] = man.evaluate() + labels.append(f'{lead_accel} m/s^2 lead acceleration') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'Approaching stopped car from 140m' + labels = [] + for speed in np.arange(0,45,5): + man = Maneuver( + name, + duration=30., + initial_speed=float(speed), + lead_relevancy=True, + initial_distance_lead=140., + speed_lead_values=[0.0, 0.], + breakpoints=[0., 30.], + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s approach speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Following 5s (triangular) oscillating lead' + labels = [] + speed = np.int64(10) + for oscil in np.arange(0, 10, 1): + man = Maneuver( + '', + duration=30., + initial_speed=float(speed), + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(speed, speed), + speed_lead_values=[speed, speed, speed - oscil, speed + oscil, speed - oscil, speed + oscil, speed - oscil], + breakpoints=[0.,2., 5, 8, 15, 18, 25.], + ) + valid, results[oscil] = man.evaluate() + labels.append(f'{oscil} m/s oscillation size') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'Following 5s (sinusoidal) oscillating lead' + labels = [] + speed = np.int64(10) + duration = float(30) + f_osc = 1. / 5 + for oscil in np.arange(0, 10, 1): + bps = DT_MDL * np.arange(int(duration / DT_MDL)) + lead_speeds = speed + oscil * np.sin(2 * np.pi * f_osc * bps) + man = Maneuver( + '', + duration=duration, + initial_speed=float(speed), + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(speed, speed), + speed_lead_values=lead_speeds, + breakpoints=bps, + ) + valid, results[oscil] = man.evaluate() + labels.append(f'{oscil} m/s oscillation size') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'Speed profile when converging to steady state lead at 30m/s' + labels = [] + for distance in np.arange(20, 140, 10): + man = Maneuver( + '', + duration=50, + initial_speed=30.0, + lead_relevancy=True, + initial_distance_lead=distance, + speed_lead_values=[30.0], + breakpoints=[0.], + ) + valid, results[distance] = man.evaluate() + labels.append(f'{distance} m initial distance') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Speed profile when converging to steady state lead at 20m/s' + labels = [] + for distance in np.arange(20, 140, 10): + man = Maneuver( + '', + duration=50, + initial_speed=20.0, + lead_relevancy=True, + initial_distance_lead=distance, + speed_lead_values=[20.0], + breakpoints=[0.], + ) + valid, results[distance] = man.evaluate() + labels.append(f'{distance} m initial distance') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Following car at 30m/s that comes to a stop' + labels = [] + for stop_time in np.arange(4, 14, 1): + man = Maneuver( + '', + duration=30, + initial_speed=30.0, + cruise_values=[30.0, 30.0, 30.0], + lead_relevancy=True, + initial_distance_lead=60.0, + speed_lead_values=[30.0, 30.0, 0.0], + breakpoints=[0., 5., 5 + stop_time], + ) + valid, results[stop_time] = man.evaluate() + labels.append(f'{stop_time} seconds stop time') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Response to cut-in at half follow distance' + labels = [] + for speed in np.arange(0, 40, 5): + man = Maneuver( + '', + duration=20, + initial_speed=float(speed), + cruise_values=[speed, speed, speed], + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(speed, speed)/2, + speed_lead_values=[speed, speed, speed], + prob_lead_values=[0.0, 0.0, 1.0], + breakpoints=[0., 5.0, 5.01], + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Follow a lead that accelerates at 2m/s^2 until steady state speed' + labels = [] + for speed in np.arange(0, 40, 5): + man = Maneuver( + '', + duration=60, + initial_speed=0.0, + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(0.0, 0.0), + speed_lead_values=[0.0, 0.0, speed], + prob_lead_values=[1.0, 1.0, 1.0], + breakpoints=[0., 1.0, speed/2], + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'From stop to cruise' + labels = [] + for speed in np.arange(0, 40, 5): + man = Maneuver( + '', + duration=50, + initial_speed=0.0, + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(0.0, 0.0), + speed_lead_values=[0.0, 0.0], + cruise_values=[0.0, speed], + prob_lead_values=[0.0, 0.0], + breakpoints=[1., 1.01], + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'From cruise to min' + labels = [] + for speed in np.arange(10, 40, 5): + man = Maneuver( + '', + duration=50, + initial_speed=float(speed), + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(0.0, 0.0), + speed_lead_values=[0.0, 0.0], + cruise_values=[speed, 10.0], + prob_lead_values=[0.0, 0.0], + breakpoints=[1., 1.01], + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + return htmls + +if __name__ == '__main__': + htmls = generate_mpc_tuning_report() + + if len(sys.argv) < 2: + file_name = 'long_mpc_tune_report.html' + else: + file_name = sys.argv[1] + + with open(file_name, 'w') as f: + f.write(markdown.markdown('# MPC longitudinal tuning report')) + for html in htmls: + f.write(html) diff --git a/tools/mac_setup.sh b/tools/mac_setup.sh deleted file mode 100755 index 062de6aabf788b..00000000000000 --- a/tools/mac_setup.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -ROOT="$(cd $DIR/../ && pwd)" -ARCH=$(uname -m) - -if [[ $SHELL == "/bin/zsh" ]]; then - RC_FILE="$HOME/.zshrc" -elif [[ $SHELL == "/bin/bash" ]]; then - RC_FILE="$HOME/.bash_profile" -fi - -# Install brew if required -if [[ $(command -v brew) == "" ]]; then - echo "Installing Homebrew" - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - echo "[ ] installed brew t=$SECONDS" - - # make brew available now - if [[ $ARCH == "x86_64" ]]; then - echo 'eval "$(/usr/local/bin/brew shellenv)"' >> $RC_FILE - eval "$(/usr/local/bin/brew shellenv)" - else - echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> $RC_FILE - eval "$(/opt/homebrew/bin/brew shellenv)" - fi -fi - -brew bundle --file=- <<-EOS -brew "cppcheck" -brew "git-lfs" -brew "zlib" -brew "capnp" -brew "coreutils" -brew "eigen" -brew "ffmpeg" -brew "glfw" -brew "libarchive" -brew "libusb" -brew "libtool" -brew "llvm" -brew "openssl@3.0" -brew "qt@5" -brew "zeromq" -cask "gcc-arm-embedded" -brew "portaudio" -brew "gcc@13" -EOS - -echo "[ ] finished brew install t=$SECONDS" - -BREW_PREFIX=$(brew --prefix) - -# archive backend tools for pip dependencies -export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/zlib/lib" -export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/bzip2/lib" -export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/zlib/include" -export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/bzip2/include" - -# pycurl curl/openssl backend dependencies -export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/openssl@3/lib" -export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/openssl@3/include" -export PYCURL_CURL_CONFIG=/usr/bin/curl-config -export PYCURL_SSL_LIBRARY=openssl - -# install python dependencies -$DIR/install_python_dependencies.sh -echo "[ ] installed python dependencies t=$SECONDS" - -# brew does not link qt5 by default -# check if qt5 can be linked, if not, prompt the user to link it -QT_BIN_LOCATION="$(command -v lupdate || :)" -if [ -n "$QT_BIN_LOCATION" ]; then - # if qt6 is linked, prompt the user to unlink it and link the right version - QT_BIN_VERSION="$(lupdate -version | awk '{print $NF}')" - if [[ ! "$QT_BIN_VERSION" =~ 5\.[0-9]+\.[0-9]+ ]]; then - echo - echo "lupdate/lrelease available at PATH is $QT_BIN_VERSION" - if [[ "$QT_BIN_LOCATION" == "$(brew --prefix)/"* ]]; then - echo "Run the following command to link qt5:" - echo "brew unlink qt@6 && brew link qt@5" - else - echo "Remove conflicting qt entries from PATH and run the following command to link qt5:" - echo "brew link qt@5" - fi - fi -else - brew link qt@5 -fi - -echo -echo "---- OPENPILOT SETUP DONE ----" -echo "Open a new shell or configure your active shell env by running:" -echo "source $RC_FILE" diff --git a/tools/op.sh b/tools/op.sh index 4c792edefeba47..cc7e751f87da0b 100755 --- a/tools/op.sh +++ b/tools/op.sh @@ -21,18 +21,30 @@ if [ "$(uname)" == "Darwin" ] && [ $SHELL == "/bin/bash" ]; then fi function op_install() { echo "Installing op system-wide..." - CMD="\nalias op='"$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )/op.sh" \"\$@\"'\n" - grep "alias op=" "$RC_FILE" &> /dev/null || printf "$CMD" >> $RC_FILE + OP_SH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )/op.sh" + CMD=$(cat </dev/null || printf '\n%s\n' "$CMD" >> "$RC_FILE" echo -e " ↳ [${GREEN}✔${NC}] op installed successfully. Open a new shell to use it." } -function loge() { - if [[ -f "$LOG_FILE" ]]; then - # error type - echo "$1" >> $LOG_FILE - # error log - echo "$2" >> $LOG_FILE - fi +function retry() { + local attempts=$1 + shift + for i in $(seq 1 "$attempts"); do + if "$@"; then + return 0 + fi + if [ "$i" -lt "$attempts" ]; then + echo " Attempt $i/$attempts failed, retrying in 5s..." + sleep 5 + fi + done + return 1 } function op_run_command() { @@ -52,6 +64,7 @@ function op_run_command() { # be default, assume openpilot dir is in current directory OPENPILOT_ROOT=$(pwd) function op_get_openpilot_dir() { + # First try traversing up the directory tree while [[ "$OPENPILOT_ROOT" != '/' ]]; do if find "$OPENPILOT_ROOT/launch_openpilot.sh" -maxdepth 1 -mindepth 1 &> /dev/null; then @@ -59,6 +72,15 @@ function op_get_openpilot_dir() { fi OPENPILOT_ROOT="$(readlink -f "$OPENPILOT_ROOT/"..)" done + + # Fallback to hardcoded directories if not found + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" + for dir in "${SCRIPT_DIR%/tools}" "$HOME/openpilot" "/data/openpilot"; do + if [[ -f "$dir/launch_openpilot.sh" ]]; then + OPENPILOT_ROOT="$dir" + return 0 + fi + done } function op_install_post_commit() { @@ -94,7 +116,7 @@ function op_check_git() { fi echo "Checking for git lfs files..." - if [[ $(file -b $OPENPILOT_ROOT/selfdrive/modeld/models/supercombo.onnx) == "data" ]]; then + if [[ $(file -b $OPENPILOT_ROOT/selfdrive/modeld/models/dmonitoring_model.onnx) == "data" ]]; then echo -e " ↳ [${GREEN}✔${NC}] git lfs files found." else echo -e " ↳ [${RED}✗${NC}] git lfs files not found! Run 'git lfs pull'" @@ -123,13 +145,11 @@ function op_check_os() { ;; * ) echo -e " ↳ [${RED}✗${NC}] Incompatible Ubuntu version $VERSION_CODENAME detected!" - loge "ERROR_INCOMPATIBLE_UBUNTU" "$VERSION_CODENAME" return 1 ;; esac else echo -e " ↳ [${RED}✗${NC}] No /etc/os-release on your system. Make sure you're running on Ubuntu, or similar!" - loge "ERROR_UNKNOWN_UBUNTU" return 1 fi @@ -137,25 +157,6 @@ function op_check_os() { echo -e " ↳ [${GREEN}✔${NC}] macOS detected." else echo -e " ↳ [${RED}✗${NC}] OS type $OSTYPE not supported!" - loge "ERROR_UNKNOWN_OS" "$OSTYPE" - return 1 - fi -} - -function op_check_python() { - echo "Checking for compatible python version..." - REQUIRED_PYTHON_VERSION=$(grep "requires-python" $OPENPILOT_ROOT/pyproject.toml) - INSTALLED_PYTHON_VERSION=$(python3 --version 2> /dev/null || true) - - if [[ -z $INSTALLED_PYTHON_VERSION ]]; then - echo -e " ↳ [${RED}✗${NC}] python3 not found on your system. You need python version at least $(echo $REQUIRED_PYTHON_VERSION | tr -d -c '[0-9.]') to continue!" - loge "ERROR_PYTHON_NOT_FOUND" - return 1 - elif [[ $(echo $INSTALLED_PYTHON_VERSION | grep -o '[0-9]\+\.[0-9]\+' | tr -d -c '[0-9]') -ge $(echo $REQUIRED_PYTHON_VERSION | tr -d -c '[0-9]') ]]; then - echo -e " ↳ [${GREEN}✔${NC}] $INSTALLED_PYTHON_VERSION detected." - else - echo -e " ↳ [${RED}✗${NC}] You need python version at least $(echo $REQUIRED_PYTHON_VERSION | tr -d -c '[0-9.]') to continue!" - loge "ERROR_PYTHON_VERSION" "$INSTALLED_PYTHON_VERSION" return 1 fi } @@ -184,8 +185,6 @@ function op_before_cmd() { op_activate_venv - result="${result}\n$(( op_check_python ) 2>&1)" || (echo -e "$result" && return 1) - if [[ -z $VERBOSE ]]; then echo -e "${BOLD}Checking system →${NC} [${GREEN}✔${NC}]" else @@ -196,30 +195,29 @@ function op_before_cmd() { function op_setup() { op_get_openpilot_dir cd $OPENPILOT_ROOT + if [[ -n "${OPENPILOT_LFS_URL:-}" ]]; then + git config lfs.url "$OPENPILOT_LFS_URL" + fi op_check_openpilot_dir op_check_os echo "Installing dependencies..." st="$(date +%s)" - if [[ "$OSTYPE" == "linux-gnu"* ]]; then - SETUP_SCRIPT="tools/ubuntu_setup.sh" - elif [[ "$OSTYPE" == "darwin"* ]]; then - SETUP_SCRIPT="tools/mac_setup.sh" - fi + SETUP_SCRIPT="tools/setup_dependencies.sh" if ! $OPENPILOT_ROOT/$SETUP_SCRIPT; then echo -e " ↳ [${RED}✗${NC}] Dependencies installation failed!" - loge "ERROR_DEPENDENCIES_INSTALLATION" return 1 fi et="$(date +%s)" echo -e " ↳ [${GREEN}✔${NC}] Dependencies installed successfully in $((et - st)) seconds." + op_activate_venv + echo "Getting git submodules..." st="$(date +%s)" - if ! git submodule update --filter=blob:none --jobs 4 --init --recursive; then + if ! retry 3 git submodule update --jobs 4 --init --recursive; then echo -e " ↳ [${RED}✗${NC}] Getting git submodules failed!" - loge "ERROR_GIT_SUBMODULES" return 1 fi et="$(date +%s)" @@ -227,9 +225,8 @@ function op_setup() { echo "Pulling git lfs files..." st="$(date +%s)" - if ! git lfs pull; then + if ! retry 3 git lfs pull; then echo -e " ↳ [${RED}✗${NC}] Pulling git lfs files failed!" - loge "ERROR_GIT_LFS" return 1 fi et="$(date +%s)" @@ -238,11 +235,21 @@ function op_setup() { op_check } +function op_auth() { + op_before_cmd + op_run_command tools/lib/auth.py "$@" +} + function op_activate_venv() { # bash 3.2 can't handle this without the 'set +e' set +e source $OPENPILOT_ROOT/.venv/bin/activate &> /dev/null || true set -e + + # persist venv on PATH across GitHub Actions steps + if [ -n "$GITHUB_PATH" ]; then + echo "$OPENPILOT_ROOT/.venv/bin" >> "$GITHUB_PATH" + fi } function op_venv() { @@ -263,17 +270,51 @@ function op_venv() { esac } +function op_adb() { + op_before_cmd + op_run_command tools/scripts/adb_ssh.sh "$@" +} + +function op_ssh() { + op_before_cmd + op_run_command tools/scripts/ssh.py "$@" +} + +function op_script() { + op_before_cmd + + case $1 in + som-debug ) op_run_command panda/scripts/som_debug.sh "${@:2}" ;; + * ) + echo -e "Unknown script '$1'. Available scripts:" + echo -e " ${BOLD}som-debug${NC} SOM serial debug console via panda" + return 1 + ;; + esac +} + function op_check() { VERBOSE=1 op_before_cmd unset VERBOSE } +function op_esim() { + op_before_cmd + op_run_command system/hardware/esim.py "$@" +} + function op_build() { CDIR=$(pwd) op_before_cmd cd "$CDIR" - op_run_command scons $@ + if [[ -f "/AGNOS" ]]; then + # needed on AGNOS to not run out of memory + op_run_command system/manager/build.py + else + # scons is fine on PC + op_run_command scons $@ + fi } function op_juggle() { @@ -307,6 +348,54 @@ function op_sim() { op_run_command exec tools/sim/launch_openpilot.sh } +function op_clip() { + op_before_cmd + op_run_command tools/clip/run.py $@ +} + +function op_switch() { + REMOTE="origin" + if [ "$#" -gt 1 ]; then + REMOTE="$1" + shift + fi + + if [ -z "$1" ]; then + echo -e "${BOLD}${UNDERLINE}Usage:${NC} op switch [REMOTE] " + return 1 + fi + BRANCH="$1" + + git config --replace-all remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" + git submodule deinit --all --force + git fetch "$REMOTE" "$BRANCH" + git checkout -f FETCH_HEAD + git checkout -B "$BRANCH" --track "$REMOTE"/"$BRANCH" + git submodule deinit --all --force + git reset --hard "${REMOTE}/${BRANCH}" + git clean -df + git submodule update --init --recursive + git submodule foreach git reset --hard + git submodule foreach git clean -df + + # remove openpilot update flag if present + rm -f .overlay_init +} + +function op_start() { + if [[ -f "/AGNOS" ]]; then + op_before_cmd + op_run_command sudo systemctl restart comma $@ + fi +} + +function op_stop() { + if [[ -f "/AGNOS" ]]; then + op_before_cmd + op_run_command sudo systemctl stop comma $@ + fi +} + function op_default() { echo "An openpilot helper" echo "" @@ -315,24 +404,30 @@ function op_default() { echo " op is only a wrapper for existing scripts, tools, and commands." echo " op will always show you what it will run on your system." echo "" - echo " op will try to find your openpilot directory in the following order:" - echo " 1: use the directory specified with the --dir option" - echo " 2: use the current working directory" - echo " 3: go up the file tree non-recursively" - echo "" echo -e "${BOLD}${UNDERLINE}Usage:${NC} op [OPTIONS] " echo "" echo -e "${BOLD}${UNDERLINE}Commands [System]:${NC}" - echo -e " ${BOLD}check${NC} Check the development environment (git, os, python) to start using openpilot" + echo -e " ${BOLD}auth${NC} Authenticate yourself for API use" + echo -e " ${BOLD}check${NC} Check the development environment (git, os) to start using openpilot" + echo -e " ${BOLD}esim${NC} Manage eSIM profiles on your comma device" echo -e " ${BOLD}venv${NC} Activate the python virtual environment" echo -e " ${BOLD}setup${NC} Install openpilot dependencies" echo -e " ${BOLD}build${NC} Run the openpilot build system in the current working directory" echo -e " ${BOLD}install${NC} Install the 'op' tool system wide" + echo -e " ${BOLD}switch${NC} Switch to a different git branch with a clean slate (nukes any changes)" + echo -e " ${BOLD}start${NC} Starts (or restarts) openpilot" + echo -e " ${BOLD}stop${NC} Stops openpilot" echo "" echo -e "${BOLD}${UNDERLINE}Commands [Tooling]:${NC}" echo -e " ${BOLD}juggle${NC} Run PlotJuggler" echo -e " ${BOLD}replay${NC} Run Replay" echo -e " ${BOLD}cabana${NC} Run Cabana" + echo -e " ${BOLD}clip${NC} Run clip (linux only)" + echo -e " ${BOLD}adb${NC} Run adb shell" + echo -e " ${BOLD}ssh${NC} comma prime SSH helper" + echo "" + echo -e "${BOLD}${UNDERLINE}Commands [Scripts]:${NC}" + echo -e " ${BOLD}script${NC} Run a script (e.g. op script som-debug)" echo "" echo -e "${BOLD}${UNDERLINE}Commands [Testing]:${NC}" echo -e " ${BOLD}sim${NC} Run openpilot in a simulator" @@ -367,13 +462,14 @@ function _op() { -d | --dir ) shift 1; OPENPILOT_ROOT="$1"; shift 1 ;; --dry ) shift 1; DRY="1" ;; -n | --no-verify ) shift 1; NO_VERIFY="1" ;; - -l | --log ) shift 1; LOG_FILE="$1" ; shift 1 ;; esac # parse Commands case $1 in + auth ) shift 1; op_auth "$@" ;; venv ) shift 1; op_venv "$@" ;; check ) shift 1; op_check "$@" ;; + esim ) shift 1; op_esim "$@" ;; setup ) shift 1; op_setup "$@" ;; build ) shift 1; op_build "$@" ;; juggle ) shift 1; op_juggle "$@" ;; @@ -381,9 +477,17 @@ function _op() { lint ) shift 1; op_lint "$@" ;; test ) shift 1; op_test "$@" ;; replay ) shift 1; op_replay "$@" ;; + clip ) shift 1; op_clip "$@" ;; sim ) shift 1; op_sim "$@" ;; install ) shift 1; op_install "$@" ;; + switch ) shift 1; op_switch "$@" ;; + start ) shift 1; op_start "$@" ;; + stop ) shift 1; op_stop "$@" ;; + restart ) shift 1; op_restart "$@" ;; post-commit ) shift 1; op_install_post_commit "$@" ;; + adb ) shift 1; op_adb "$@" ;; + ssh ) shift 1; op_ssh "$@" ;; + script ) shift 1; op_script "$@" ;; * ) op_default "$@" ;; esac } diff --git a/tools/plotjuggler/.gitignore b/tools/plotjuggler/.gitignore deleted file mode 100644 index 45559d0b091498..00000000000000 --- a/tools/plotjuggler/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -bin/ -bin -*.rlog diff --git a/tools/plotjuggler/README.md b/tools/plotjuggler/README.md index dc301efcb79c8d..3249971bfcf5e4 100644 --- a/tools/plotjuggler/README.md +++ b/tools/plotjuggler/README.md @@ -13,14 +13,13 @@ Once you've [set up the openpilot environment](../README.md), this command will ``` $ ./juggle.py -h usage: juggle.py [-h] [--demo] [--can] [--stream] [--layout [LAYOUT]] [--install] [--dbc DBC] - [route_or_segment_name] [segment_count] + [route_or_segment_name] A helper to run PlotJuggler on openpilot routes positional arguments: route_or_segment_name The route or segment name to plot (cabana share URL accepted) (default: None) - segment_count The number of segments to plot (default: None) optional arguments: -h, --help show this help message and exit @@ -34,15 +33,19 @@ optional arguments: ``` -Examples using route name: +Example using route name: -`./juggle.py "a2a0ccea32023010/2023-07-27--13-01-19"` +`./juggle.py "5beb9b58bd12b691/0000010a--a51155e496"` -Examples using segment range: +Examples using segment: -`./juggle.py "a2a0ccea32023010/2023-07-27--13-01-19/1"` +`./juggle.py "5beb9b58bd12b691/0000010a--a51155e496/1"` -`./juggle.py "a2a0ccea32023010/2023-07-27--13-01-19/1/q" # use qlogs` +`./juggle.py "5beb9b58bd12b691/0000010a--a51155e496/1/q" # use qlogs` + +Example using segment range: + +`./juggle.py "5beb9b58bd12b691/0000010a--a51155e496/0:1"` ## Streaming @@ -58,7 +61,7 @@ If streaming to PlotJuggler from a replay on your PC, simply run: `./juggle.py - For a quick demo, go through the installation step and run this command: -`./juggle.py --demo --layout=layouts/demo.xml` +`./juggle.py --demo --layout=layouts/tuning.xml` ## Layouts diff --git a/tools/plotjuggler/juggle.py b/tools/plotjuggler/juggle.py index 82bd36622f87d8..a31c62c940edcf 100755 --- a/tools/plotjuggler/juggle.py +++ b/tools/plotjuggler/juggle.py @@ -12,11 +12,16 @@ from opendbc.car.fingerprints import MIGRATION from openpilot.common.basedir import BASEDIR +from openpilot.common.swaglog import cloudlog +from openpilot.tools.cabana.dbc.generate_dbc_json import generate_dbc_dict from openpilot.tools.lib.logreader import LogReader, ReadMode, save_log +from openpilot.selfdrive.test.process_replay.migration import migrate_all juggle_dir = os.path.dirname(os.path.realpath(__file__)) -DEMO_ROUTE = "a2a0ccea32023010|2023-07-27--13-01-19" +os.environ['LD_LIBRARY_PATH'] = os.environ.get('LD_LIBRARY_PATH', '') + f":{juggle_dir}/bin/" + +DEMO_ROUTE = "5beb9b58bd12b691/0000010a--a51155e496" RELEASES_URL = "https://github.com/commaai/PlotJuggler/releases/download/latest" INSTALL_DIR = os.path.join(juggle_dir, "bin") PLOTJUGGLER_BIN = os.path.join(juggle_dir, "bin/plotjuggler") @@ -24,9 +29,21 @@ MAX_STREAMING_BUFFER_SIZE = 1000 +def print_jotpluggler_banner(): + purple = "\033[95m" if sys.stdout.isatty() else "" + reset = "\033[0m" if purple else "" + print(f"{purple}+-------------------------------------------------------------+{reset}") + print(f"{purple}|{reset} JotPluggler is the future! Try it like this: {purple}|{reset}") + print(f"{purple}|{reset} ./tools/jotpluggler/jotpluggler --demo --layout tuning {purple}|{reset}") + print(f"{purple}|{reset} {purple}|{reset}") + print(f"{purple}|{reset} PlotJuggler will be deleted soon. {purple}|{reset}") + print(f"{purple}|{reset} Missing a feature? Open an issue or post in #dev-openpilot. {purple}|{reset}") + print(f"{purple}+-------------------------------------------------------------+{reset}") + + def install(): m = f"{platform.system()}-{platform.machine()}" - supported = ("Linux-x86_64", "Linux-aarch64", "Darwin-arm64", "Darwin-x86_64") + supported = ("Linux-x86_64", "Linux-aarch64", "Darwin-arm64") if m not in supported: raise Exception(f"Unsupported platform: '{m}'. Supported platforms: {supported}") @@ -42,7 +59,7 @@ def install(): tmpf.write(chunk) with tarfile.open(tmp.name) as tar: - tar.extractall(path=INSTALL_DIR) + tar.extractall(path=INSTALL_DIR, filter="data") def get_plotjuggler_version(): @@ -51,49 +68,52 @@ def get_plotjuggler_version(): return tuple(map(int, version.split("."))) -def start_juggler(fn=None, dbc=None, layout=None, route_or_segment_name=None): +def start_juggler(fn=None, dbc=None, layout=None, route_or_segment_name=None, platform=None): env = os.environ.copy() env["BASEDIR"] = BASEDIR env["PATH"] = f"{INSTALL_DIR}:{os.getenv('PATH', '')}" if dbc: + if os.path.exists(dbc): + dbc = os.path.abspath(dbc) env["DBC_NAME"] = dbc extra_args = "" if fn is not None: - extra_args += f" -d {fn}" + extra_args += f" -d {os.path.abspath(fn)}" if layout is not None: - extra_args += f" -l {layout}" + extra_args += f" -l {os.path.abspath(layout)}" if route_or_segment_name is not None: - extra_args += f" --window_title \"{route_or_segment_name}\"" + extra_args += f" --window_title \"{route_or_segment_name}{f' ({platform})' if platform is not None else ''}\"" cmd = f'{PLOTJUGGLER_BIN} --buffer_size {MAX_STREAMING_BUFFER_SIZE} --plugin_folders {INSTALL_DIR}{extra_args}' subprocess.call(cmd, shell=True, env=env, cwd=juggle_dir) def process(can, lr): - return [d for d in lr if can or d.which() not in ['can', 'sendcan']] + return [d for d in lr if can or d.which() not in ['can', 'sendcan'] and not d.which().startswith('customReserved')] -def juggle_route(route_or_segment_name, can, layout, dbc=None): - sr = LogReader(route_or_segment_name, default_mode=ReadMode.AUTO_INTERACTIVE) +def juggle_route(route_or_segment_name, can, layout, dbc, should_migrate): + lr = LogReader(route_or_segment_name, default_mode=ReadMode.AUTO_INTERACTIVE) - all_data = sr.run_across_segments(24, partial(process, can)) + all_data = lr.run_across_segments(24, partial(process, can)) + if should_migrate: + all_data = migrate_all(all_data) # Infer DBC name from logs + platform = None if dbc is None: - for cp in [m for m in all_data if m.which() == 'carParams']: - try: - DBC = __import__(f"opendbc.car.{cp.carParams.carName}.values", fromlist=['DBC']).DBC - fingerprint = cp.carParams.carFingerprint - dbc = DBC[MIGRATION.get(fingerprint, fingerprint)]['pt'] - except Exception: - pass - break + try: + CP = lr.first('carParams') + platform = MIGRATION.get(CP.carFingerprint, CP.carFingerprint) + dbc = generate_dbc_dict()[platform] + except Exception: + cloudlog.exception("Failed to get DBC name from logs!") with tempfile.NamedTemporaryFile(suffix='.rlog', dir=juggle_dir) as tmp: save_log(tmp.name, all_data, compress=False) del all_data - start_juggler(tmp.name, dbc, layout, route_or_segment_name) + start_juggler(tmp.name, dbc, layout, route_or_segment_name, platform) if __name__ == "__main__": @@ -103,16 +123,22 @@ def juggle_route(route_or_segment_name, can, layout, dbc=None): parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") parser.add_argument("--can", action="store_true", help="Parse CAN data") parser.add_argument("--stream", action="store_true", help="Start PlotJuggler in streaming mode") + parser.add_argument("--no-migration", action="store_true", help="Do not perform log migration") parser.add_argument("--layout", nargs='?', help="Run PlotJuggler with a pre-defined layout") parser.add_argument("--install", action="store_true", help="Install or update PlotJuggler + plugins") parser.add_argument("--dbc", help="Set the DBC name to load for parsing CAN data. If not set, the DBC will be automatically inferred from the logs.") parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to plot (cabana share URL accepted)") if len(sys.argv) == 1: + print_jotpluggler_banner() + print() parser.print_help() sys.exit() args = parser.parse_args() + print_jotpluggler_banner() + print() + if args.install: install() sys.exit() @@ -129,4 +155,4 @@ def juggle_route(route_or_segment_name, can, layout, dbc=None): start_juggler(layout=args.layout) else: route_or_segment_name = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() - juggle_route(route_or_segment_name, args.can, args.layout, args.dbc) + juggle_route(route_or_segment_name, args.can, args.layout, args.dbc, not args.no_migration) diff --git a/tools/plotjuggler/layouts/controls_mismatch_debug.xml b/tools/plotjuggler/layouts/controls_mismatch_debug.xml index 7f9def379c5df5..cf337aa7df7813 100644 --- a/tools/plotjuggler/layouts/controls_mismatch_debug.xml +++ b/tools/plotjuggler/layouts/controls_mismatch_debug.xml @@ -8,7 +8,7 @@ - + @@ -16,7 +16,7 @@ - + @@ -58,4 +58,3 @@ - diff --git a/tools/plotjuggler/layouts/demo.xml b/tools/plotjuggler/layouts/demo.xml deleted file mode 100644 index 7026221374f8e8..00000000000000 --- a/tools/plotjuggler/layouts/demo.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - prevX = 0 -prevY = 0 -is_first = true - if (is_first) then - is_first = false - prevX = time - prevY = value -end - -dx = time - prevX -dy = value - prevY -prevX = time -prevY = value - -return dy/dx - /carState/vEgo - - - - - - diff --git a/tools/plotjuggler/layouts/gps.xml b/tools/plotjuggler/layouts/gps.xml new file mode 100644 index 00000000000000..8fd3b53f93d740 --- /dev/null +++ b/tools/plotjuggler/layouts/gps.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/plotjuggler/layouts/gps_vs_llk.xml b/tools/plotjuggler/layouts/gps_vs_llk.xml index 69b8f20058bbf9..2051c2bef2db83 100644 --- a/tools/plotjuggler/layouts/gps_vs_llk.xml +++ b/tools/plotjuggler/layouts/gps_vs_llk.xml @@ -24,8 +24,8 @@ - - + + @@ -72,12 +72,11 @@ return distance /gpsLocationExternal/latitude /gpsLocationExternal/longitude - /liveLocationKalman/positionGeodetic/value/0 - /liveLocationKalman/positionGeodetic/value/1 + /liveLocationKalmanDEPRECATED/positionGeodetic/value/0 + /liveLocationKalmanDEPRECATED/positionGeodetic/value/1 - diff --git a/tools/plotjuggler/layouts/locationd_debug.xml b/tools/plotjuggler/layouts/locationd_debug.xml new file mode 100644 index 00000000000000..5377e1535cbf0e --- /dev/null +++ b/tools/plotjuggler/layouts/locationd_debug.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/plotjuggler/layouts/longitudinal.xml b/tools/plotjuggler/layouts/longitudinal.xml index 33a24f76d66d7c..460de97025fc74 100644 --- a/tools/plotjuggler/layouts/longitudinal.xml +++ b/tools/plotjuggler/layouts/longitudinal.xml @@ -11,6 +11,7 @@ + diff --git a/tools/plotjuggler/layouts/max-torque-debug.xml b/tools/plotjuggler/layouts/max-torque-debug.xml index 8cfd30599ef09c..9a6693165e976f 100644 --- a/tools/plotjuggler/layouts/max-torque-debug.xml +++ b/tools/plotjuggler/layouts/max-torque-debug.xml @@ -24,7 +24,7 @@ - + diff --git a/tools/plotjuggler/layouts/system_lag_debug.xml b/tools/plotjuggler/layouts/system_lag_debug.xml index a90bba0e279627..88511ffe09bbe2 100644 --- a/tools/plotjuggler/layouts/system_lag_debug.xml +++ b/tools/plotjuggler/layouts/system_lag_debug.xml @@ -45,7 +45,7 @@ - + @@ -64,4 +64,3 @@ - diff --git a/tools/plotjuggler/layouts/torque-controller.xml b/tools/plotjuggler/layouts/torque-controller.xml index b4edfdcc181aa1..8e9a1a852635e3 100644 --- a/tools/plotjuggler/layouts/torque-controller.xml +++ b/tools/plotjuggler/layouts/torque-controller.xml @@ -1,193 +1,180 @@ - + - + - - + + - - + + - - + + - - + + - - + + - - - + + + - - + + - - + + - - - + + + - + - - - - + + + + - - - + + - - - + + + - - + + - - - + + + - - - + + - + - - - - + + + + - - + + + - - - + + + - - + + - - - + + + - - + + + - + - - - - + + + + - - - - - - - + - - - + + + - - - - + + + - - - + + + - + - + - - - - + + + + - - + + - - - + + + - - - + + + - + + - - - + + + - - - - - - + + + + - - - + + + - - - - - - + @@ -199,44 +186,62 @@ + + + + + + + + + + + + + - + - return (0) - /carState/canValid + return value * 3.6 + /carState/vEgo - + + + return value * 2.23694 + /carState/vEgo + + return (value * v1 ^ 2) - (v2 * 9.81) - /controlsState/curvature + /controlsState/desiredCurvature /carState/vEgo /liveParameters/roll - + return (value * v1 ^ 2) - (v2 * 9.81) - /controlsState/desiredCurvature + /controlsState/curvature /carState/vEgo /liveParameters/roll - + - return value * 2.23694 - /carState/vEgo + return value + 0.2 + /carParams/steerActuatorDelay - + - return value * 3.6 - /carState/vEgo + return (0) + /carState/canValid diff --git a/tools/plotjuggler/layouts/tuning.xml b/tools/plotjuggler/layouts/tuning.xml index 503e726caf46d6..699f6ff683ea32 100644 --- a/tools/plotjuggler/layouts/tuning.xml +++ b/tools/plotjuggler/layouts/tuning.xml @@ -24,14 +24,14 @@ - + - + @@ -39,7 +39,7 @@ - + @@ -71,7 +71,7 @@ - + @@ -126,7 +126,7 @@ - + @@ -161,11 +161,11 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /liveLocationKalman/angularVelocityCalibrated/value/2 + /carControl/angularVelocity/2 /carState/steeringPressed /carControl/enabled - /liveLocationKalman/velocityCalibrated/value/0 + /carState/vEgo @@ -206,7 +206,7 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /lateralPlan/curvatures/0 + /modelV2/action/desiredCurvature /carState/steeringPressed /carControl/enabled @@ -284,8 +284,17 @@ end /carControl/enabled + + + return (math.abs(value - v1) > 0.001 or math.abs(v2 - v3) > 0.05) and 1 or 0 + /carControl/actuators/torque + + /carOutput/actuatorsOutput/torque + /carControl/actuators/steeringAngleDeg + /carOutput/actuatorsOutput/steeringAngleDeg + + - diff --git a/tools/plotjuggler/test_plotjuggler.py b/tools/plotjuggler/test_plotjuggler.py index a2c509f9432a26..26bad25c3ec416 100644 --- a/tools/plotjuggler/test_plotjuggler.py +++ b/tools/plotjuggler/test_plotjuggler.py @@ -1,9 +1,12 @@ import os import glob +import shutil import signal import subprocess import time +import pytest + from openpilot.common.basedir import BASEDIR from openpilot.common.timeout import Timeout from openpilot.tools.plotjuggler.juggle import DEMO_ROUTE, install @@ -12,6 +15,7 @@ class TestPlotJuggler: + @pytest.mark.skipif(not shutil.which('qmake'), reason="Qt not installed") def test_demo(self): install() diff --git a/tools/profiling/ftrace.sh b/tools/profiling/ftrace.sh index 7d5d1f5f9d6114..57c0944ae3af8e 100755 --- a/tools/profiling/ftrace.sh +++ b/tools/profiling/ftrace.sh @@ -8,14 +8,15 @@ echo boot > trace_clock echo 1000 > buffer_size_kb # /sys/kernel/tracing/available_events -echo 1 > events/irq/enable -echo 1 > events/sched/enable -echo 1 > events/kgsl/enable -echo 1 > events/camera/enable +echo 0 > events/enable +#echo 1 > events/irq/enable +#echo 1 > events/sched/enable +#echo 1 > events/kgsl/enable +#echo 1 > events/camera/enable echo 1 > events/workqueue/enable echo > trace -sleep 5 +sleep 2 echo 0 > tracing_on cp trace /tmp/trace diff --git a/tools/replay/.gitignore b/tools/replay/.gitignore index 83f0e99a8b9842..aa615770a240d2 100644 --- a/tools/replay/.gitignore +++ b/tools/replay/.gitignore @@ -1,5 +1,2 @@ -moc_* -*.moc - replay tests/test_replay diff --git a/tools/replay/README.md b/tools/replay/README.md index 67cfcd75a61810..d2beda994030a3 100644 --- a/tools/replay/README.md +++ b/tools/replay/README.md @@ -1,31 +1,55 @@ # Replay -## Replay driving data +`replay` allows you to simulate a driving session by replaying all messages logged during the use of openpilot. This provides a way to analyze and visualize system behavior as if it were live. -`replay` replays all the messages logged while running openpilot. +## Setup + +Before starting a replay, you need to authenticate with your comma account using `auth.py`. This will allow you to access your routes from the server. ```bash -# Log in via browser to have access to routes from your comma account +# Authenticate to access routes from your comma account: python3 tools/lib/auth.py +``` + +## Replay a Remote Route +You can replay a route from your comma account by specifying the route name. -# Start a replay +```bash +# Start a replay with a specific route: tools/replay/replay # Example: -tools/replay/replay 'a2a0ccea32023010|2023-07-27--13-01-19' -# or use --demo to replay the default demo route: +tools/replay/replay '5beb9b58bd12b691/0000010a--a51155e496' + +# Replay the default demo route: tools/replay/replay --demo +``` -# watch the replay with the normal openpilot UI -cd selfdrive/ui && ./ui +## Replay a Local Route +To replay a route stored locally on your machine, specify the route name and provide the path to the directory where the route files are stored. + +```bash +# Replay a local route +tools/replay/replay --data_dir="/path_to/route" + +# Example: +# If you have a local route stored at /path_to_routes with segments like: +# 5beb9b58bd12b691/0000010a--a51155e496--0 +# 5beb9b58bd12b691/0000010a--a51155e496--1 +# You can replay it like this: +tools/replay/replay "5beb9b58bd12b691/0000010a--a51155e496" --data_dir="/path_to_routes" +``` -# or try out radar point visualization in Rerun: -python3 replay/rp_visualization.py +## Send Messages via ZMQ +By default, replay sends messages via MSGQ. To switch to ZMQ, set the ZMQ environment variable. -# NOTE: To visualize radar points, make sure tools/replay/replay is running. +```bash +# Start replay and send messages via ZMQ: +ZMQ=1 tools/replay/replay ``` -## usage +## Usage +For more information on available options and arguments, use the help command: ``` bash $ tools/replay/replay -h @@ -34,12 +58,14 @@ Mock openpilot components by publishing logged messages. Options: -h, --help Displays this help. - -a, --allow whitelist of services to send - -b, --block blacklist of services to send + -a, --allow whitelist of services to send (comma-separated) + -b, --block blacklist of services to send (comma-separated) -c, --cache cache segments in memory. default is 5 -s, --start start from -x playback . between 0.2 - 3 --demo use a demo route instead of providing your own + --auto Auto load the route from the best available source (no video): + internal, openpilotci, comma_api, car_segments, testing_closet --data_dir local directory with routes --prefix set OPENPILOT_PREFIX --dcam load driver camera @@ -49,7 +75,7 @@ Options: --qcam load qcamera --no-hw-decoder disable HW video decoding --no-vipc do not output video - --all do output all messages including uiDebug, userFlag. + --all do output all messages including uiDebug, userBookmark. this may causes issues when used along with UI Arguments: @@ -57,6 +83,22 @@ Arguments: connect.comma.ai ``` +## Visualize the Replay in the openpilot UI +To visualize the replay within the openpilot UI, run the following commands: + +```bash +tools/replay/replay +cd selfdrive/ui && ./ui.py +``` + +## Work with plotjuggler +If you want to use replay with plotjuggler, you can stream messages by running: + +```bash +tools/replay/replay +tools/plotjuggler/juggle.py --stream +``` + ## watch3 watch all three cameras simultaneously from your comma three routes with watch3 @@ -68,7 +110,7 @@ simply replay a route using the `--dcam` and `--ecam` flags: cd tools/replay && ./replay --demo --dcam --ecam # then start watch3 -cd selfdrive/ui && ./watch3 +cd selfdrive/ui && ./watch3.py ``` ![](https://i.imgur.com/IeaOdAb.png) diff --git a/tools/replay/SConscript b/tools/replay/SConscript index 1f966d437263a3..4d6ca9671e5f5e 100644 --- a/tools/replay/SConscript +++ b/tools/replay/SConscript @@ -1,19 +1,39 @@ -Import('env', 'qt_env', 'arch', 'common', 'messaging', 'visionipc', 'cereal') +import os +import shutil +import subprocess -base_frameworks = qt_env['FRAMEWORKS'] -base_libs = [common, messaging, cereal, visionipc, - 'm', 'ssl', 'crypto', 'pthread', 'qt_util'] + qt_env["LIBS"] +Import('env', 'arch', 'common', 'messaging', 'visionipc', 'cereal') +replay_env = env.Clone() +replay_env['CCFLAGS'] += ['-Wno-deprecated-declarations'] if arch == "Darwin": - base_frameworks.append('OpenCL') -else: - base_libs.append('OpenCL') + openssl_prefix = None + brew = shutil.which("brew") + if brew: + openssl_prefix = subprocess.check_output([brew, '--prefix', 'openssl@3'], encoding='utf8').strip() + else: + for candidate in ("/opt/homebrew/opt/openssl@3", "/usr/local/opt/openssl@3"): + if os.path.isdir(candidate): + openssl_prefix = candidate + break + if not openssl_prefix: + raise FileNotFoundError("openssl@3 not found (brew not on PATH and no keg at /opt/homebrew or /usr/local)") + replay_env['CPPPATH'] += [f'{openssl_prefix}/include'] + replay_env['LIBPATH'] += [f'{openssl_prefix}/lib'] -replay_lib_src = ["replay.cc", "consoleui.cc", "camera.cc", "filereader.cc", "logreader.cc", "framereader.cc", "route.cc", "util.cc"] -replay_lib = qt_env.Library("qt_replay", replay_lib_src, LIBS=base_libs, FRAMEWORKS=base_frameworks) +base_frameworks = ['VideoToolbox', 'CoreMedia', 'CoreFoundation', 'CoreVideo'] if arch == "Darwin" else [] +base_libs = [common, messaging, cereal, visionipc, 'm', 'pthread'] + +replay_lib_src = ["replay.cc", "consoleui.cc", "camera.cc", "filereader.cc", "logreader.cc", "framereader.cc", + "route.cc", "util.cc", "seg_mgr.cc", "timeline.cc", "py_downloader.cc"] +if arch != "Darwin": + replay_lib_src.append("qcom_decoder.cc") +replay_lib = replay_env.Library("replay", replay_lib_src, LIBS=base_libs, FRAMEWORKS=base_frameworks) Export('replay_lib') -replay_libs = [replay_lib, 'avutil', 'avcodec', 'avformat', 'bz2', 'zstd', 'curl', 'yuv', 'ncurses'] + base_libs -qt_env.Program("replay", ["main.cc"], LIBS=replay_libs, FRAMEWORKS=base_frameworks) +replay_libs = [replay_lib, 'avformat', 'avcodec', 'swresample', 'avutil', 'x264', 'z', 'bz2', 'zstd', 'yuv', 'ncurses'] + base_libs +if arch != "Darwin": + replay_libs += ['va', 'va-drm', 'drm'] +replay_env.Program("replay", ["main.cc"], LIBS=replay_libs, FRAMEWORKS=base_frameworks) if GetOption('extras'): - qt_env.Program('tests/test_replay', ['tests/test_runner.cc', 'tests/test_replay.cc'], LIBS=[replay_libs, base_libs]) + replay_env.Program('tests/test_replay', ['tests/test_replay.cc'], LIBS=replay_libs) diff --git a/tools/replay/camera.cc b/tools/replay/camera.cc index ded966da6d6eb3..671c0320bb0809 100644 --- a/tools/replay/camera.cc +++ b/tools/replay/camera.cc @@ -1,22 +1,14 @@ #include "tools/replay/camera.h" +#include + #include -#include -#include "third_party/linux/include/msm_media_info.h" +#include "system/camerad/cameras/nv12_info.h" #include "tools/replay/util.h" const int BUFFER_COUNT = 40; -std::tuple get_nv12_info(int width, int height) { - int nv12_width = VENUS_Y_STRIDE(COLOR_FMT_NV12, width); - int nv12_height = VENUS_Y_SCANLINES(COLOR_FMT_NV12, height); - assert(nv12_width == VENUS_UV_STRIDE(COLOR_FMT_NV12, width)); - assert(nv12_height / 2 == VENUS_UV_SCANLINES(COLOR_FMT_NV12, height)); - size_t nv12_buffer_size = 2346 * nv12_width; // comes from v4l2_format.fmt.pix_mp.plane_fmt[0].sizeimage - return {nv12_width, nv12_height, nv12_buffer_size}; -} - CameraServer::CameraServer(std::pair camera_size[MAX_CAMERAS]) { for (int i = 0; i < MAX_CAMERAS; ++i) { std::tie(cameras_[i].width, cameras_[i].height) = camera_size[i]; @@ -48,9 +40,10 @@ void CameraServer::startVipcServer() { if (cam.width > 0 && cam.height > 0) { rInfo("camera[%d] frame size %dx%d", cam.type, cam.width, cam.height); - auto [nv12_width, nv12_height, nv12_buffer_size] = get_nv12_info(cam.width, cam.height); - vipc_server_->create_buffers_with_sizes(cam.stream_type, BUFFER_COUNT, false, cam.width, cam.height, - nv12_buffer_size, nv12_width, nv12_width * nv12_height); + auto [stride, y_height, uv_height_, buffer_size] = get_nv12_info(cam.width, cam.height); + (void)uv_height_; // unused in replay + vipc_server_->create_buffers_with_sizes(cam.stream_type, BUFFER_COUNT, cam.width, cam.height, + buffer_size, stride, stride * y_height); if (!cam.thread.joinable()) { cam.thread = std::thread(&CameraServer::cameraThread, this, std::ref(cam)); } diff --git a/tools/replay/camera.h b/tools/replay/camera.h index 21c3d98dcf2550..9433018848852e 100644 --- a/tools/replay/camera.h +++ b/tools/replay/camera.h @@ -10,8 +10,6 @@ #include "tools/replay/framereader.h" #include "tools/replay/logreader.h" -std::tuple get_nv12_info(int width, int height); - class CameraServer { public: CameraServer(std::pair camera_size[MAX_CAMERAS] = nullptr); diff --git a/tools/replay/can_replay.py b/tools/replay/can_replay.py index ff27b50067f9b4..07173200779aeb 100755 --- a/tools/replay/can_replay.py +++ b/tools/replay/can_replay.py @@ -5,10 +5,8 @@ import usb1 import threading -os.environ['FILEREADER_CACHE'] = '1' - from openpilot.common.realtime import config_realtime_process, Ratekeeper, DT_CTRL -from openpilot.selfdrive.pandad import can_capnp_to_can_list +from openpilot.selfdrive.pandad import can_capnp_to_list from openpilot.tools.lib.logreader import LogReader from panda import PandaJungle @@ -80,17 +78,15 @@ def connect(): time.sleep(1) -def process(lr): - return [can_capnp_to_can_list(m.can) for m in lr if m.which() == 'can'] def load_route(route_or_segment_name): print("Loading log...") - sr = LogReader(route_or_segment_name) - CP = sr.first("carParams") - print(f"carFingerprint (for hardcoding fingerprint): '{CP.carFingerprint}'") - CAN_MSGS = sr.run_across_segments(24, process) - print("Finished loading...") - return CAN_MSGS + lr = LogReader(route_or_segment_name) + CP = lr.first("carParams") + print(f"carFingerprint: '{CP.carFingerprint}'") + mbytes = [m.as_builder().to_bytes() for m in lr if m.which() == 'can'] + return [m[1] for m in can_capnp_to_list(mbytes)] + if __name__ == "__main__": parser = argparse.ArgumentParser(description="Replay CAN messages from a route to all connected pandas and jungles in a loop.", @@ -99,7 +95,7 @@ def load_route(route_or_segment_name): args = parser.parse_args() if args.route_or_segment_name is None: - args.route_or_segment_name = "77611a1fac303767/2020-03-24--09-50-38/1:3" + args.route_or_segment_name = "77611a1fac303767/2020-03-24--09-50-38/2:4" CAN_MSGS = load_route(args.route_or_segment_name) diff --git a/tools/replay/consoleui.cc b/tools/replay/consoleui.cc index 21ca0ad74b8468..2d21b4efc02876 100644 --- a/tools/replay/consoleui.cc +++ b/tools/replay/consoleui.cc @@ -1,14 +1,15 @@ #include "tools/replay/consoleui.h" +#include #include #include #include #include -#include - +#include "common/ratekeeper.h" #include "common/util.h" #include "common/version.h" +#include "tools/replay/py_downloader.h" namespace { @@ -55,9 +56,11 @@ void add_str(WINDOW *w, const char *str, Color color = Color::Default, bool bold if (color != Color::Default) wattroff(w, COLOR_PAIR(color)); } +ExitHandler do_exit; + } // namespace -ConsoleUI::ConsoleUI(Replay *replay, QObject *parent) : replay(replay), sm({"carState", "liveParameters"}), QObject(parent) { +ConsoleUI::ConsoleUI(Replay *replay) : replay(replay), sm({"carState", "liveParameters"}) { // Initialize curses initscr(); clear(); @@ -80,27 +83,21 @@ ConsoleUI::ConsoleUI(Replay *replay, QObject *parent) : replay(replay), sm({"car initWindows(); - qRegisterMetaType("uint64_t"); - qRegisterMetaType("ReplyMsgType"); installMessageHandler([this](ReplyMsgType type, const std::string msg) { - emit logMessageSignal(type, QString::fromStdString(msg)); + std::scoped_lock lock(mutex); + logs.emplace_back(type, msg); }); installDownloadProgressHandler([this](uint64_t cur, uint64_t total, bool success) { - emit updateProgressBarSignal(cur, total, success); + std::scoped_lock lock(mutex); + progress_cur = cur; + progress_total = total; + download_success = success; }); - - QObject::connect(replay, &Replay::streamStarted, this, &ConsoleUI::updateSummary); - QObject::connect(¬ifier, SIGNAL(activated(int)), SLOT(readyRead())); - QObject::connect(this, &ConsoleUI::updateProgressBarSignal, this, &ConsoleUI::updateProgressBar); - QObject::connect(this, &ConsoleUI::logMessageSignal, this, &ConsoleUI::logMessage); - - sm_timer.callOnTimeout(this, &ConsoleUI::updateStatus); - sm_timer.start(100); - getch_timer.start(1000, this); - readyRead(); } ConsoleUI::~ConsoleUI() { + installDownloadProgressHandler(nullptr); + installMessageHandler(nullptr); endwin(); } @@ -119,7 +116,12 @@ void ConsoleUI::initWindows() { w[Win::Log] = newwin(log_height - 2, max_width - 2 * BORDER_SIZE, 18, BORDER_SIZE); scrollok(w[Win::Log], true); } - w[Win::Help] = newwin(5, max_width - (2 * BORDER_SIZE), max_height - 6, BORDER_SIZE); + if (max_height >= 23) { + w[Win::Help] = newwin(5, max_width - (2 * BORDER_SIZE), max_height - 6, BORDER_SIZE); + } else if (max_height >= 17) { + w[Win::Help] = newwin(1, max_width - (2 * BORDER_SIZE), max_height - 1, BORDER_SIZE); + mvwprintw(w[Win::Help], 0, 0, "Expand screen vertically to list available commands"); + } // set the title bar wbkgd(w[Win::Title], A_REVERSE); @@ -128,7 +130,7 @@ void ConsoleUI::initWindows() { // show windows on the real screen refresh(); displayTimelineDesc(); - displayHelp(); + if (max_height >= 23) displayHelp(); updateSummary(); updateTimeline(); for (auto win : w) { @@ -136,9 +138,7 @@ void ConsoleUI::initWindows() { } } -void ConsoleUI::timerEvent(QTimerEvent *ev) { - if (ev->timerId() != getch_timer.timerId()) return; - +void ConsoleUI::updateSize() { if (is_term_resized(max_height, max_width)) { for (auto win : w) { if (win) delwin(win); @@ -149,7 +149,6 @@ void ConsoleUI::timerEvent(QTimerEvent *ev) { initWindows(); rWarning("resize term %dx%d", max_height, max_width); } - updateTimeline(); } void ConsoleUI::updateStatus() { @@ -162,23 +161,18 @@ void ConsoleUI::updateStatus() { add_str(win, unit.c_str()); }; static const std::pair status_text[] = { - {"loading...", Color::Red}, {"playing", Color::Green}, {"paused...", Color::Yellow}, }; sm.update(0); - if (status != Status::Paused) { - auto events = replay->events(); - uint64_t current_mono_time = replay->routeStartNanos() + replay->currentSeconds() * 1e9; - bool playing = !events->empty() && events->back().mono_time > current_mono_time; - status = playing ? Status::Playing : Status::Waiting; - } auto [status_str, status_color] = status_text[status]; write_item(0, 0, "STATUS: ", status_str, " ", false, status_color); + auto cur_ts = replay->routeDateTime() + (int)replay->currentSeconds(); + char *time_string = ctime(&cur_ts); std::string current_segment = " - " + std::to_string((int)(replay->currentSeconds() / 60)); - write_item(0, 25, "TIME: ", replay->currentDateTime().toString("ddd MMMM dd hh:mm:ss").toStdString(), current_segment, true); + write_item(0, 25, "TIME: ", time_string, current_segment, true); auto p = sm["liveParameters"].getLiveParameters(); write_item(1, 0, "STIFFNESS: ", util::string_format("%.2f %%", p.getStiffnessFactor() * 100), " "); @@ -218,7 +212,7 @@ void ConsoleUI::displayTimelineDesc() { } } -void ConsoleUI::logMessage(ReplyMsgType type, const QString &msg) { +void ConsoleUI::logMessage(ReplyMsgType type, const std::string &msg) { if (auto win = w[Win::Log]) { Color color = Color::Default; if (type == ReplyMsgType::Debug) { @@ -228,26 +222,26 @@ void ConsoleUI::logMessage(ReplyMsgType type, const QString &msg) { } else if (type == ReplyMsgType::Critical) { color = Color::Red; } - add_str(win, qPrintable(msg + "\n"), color); + add_str(win, (msg + "\n").c_str(), color); wrefresh(win); } } -void ConsoleUI::updateProgressBar(uint64_t cur, uint64_t total, bool success) { +void ConsoleUI::updateProgressBar() { werase(w[Win::DownloadBar]); - if (success && cur < total) { + if (download_success && progress_cur < progress_total) { const int width = 35; - const float progress = cur / (double)total; + const float progress = progress_cur / (double)progress_total; const int pos = width * progress; wprintw(w[Win::DownloadBar], "Downloading [%s>%s] %d%% %s", std::string(pos, '=').c_str(), - std::string(width - pos, ' ').c_str(), int(progress * 100.0), formattedDataSize(total).c_str()); + std::string(width - pos, ' ').c_str(), int(progress * 100.0), formattedDataSize(progress_total).c_str()); } wrefresh(w[Win::DownloadBar]); } void ConsoleUI::updateSummary() { const auto &route = replay->route(); - mvwprintw(w[Win::Stats], 0, 0, "Route: %s, %lu segments", qPrintable(route->name()), route->segments().size()); + mvwprintw(w[Win::Stats], 0, 0, "Route: %s, %lu segments", route.name().c_str(), route.segments().size()); mvwprintw(w[Win::Stats], 1, 0, "Car Fingerprint: %s", replay->carFingerprint().c_str()); wrefresh(w[Win::Stats]); } @@ -263,18 +257,18 @@ void ConsoleUI::updateTimeline() { wattroff(win, COLOR_PAIR(Color::Disengaged)); const int total_sec = replay->maxSeconds() - replay->minSeconds(); - for (auto [begin, end, type] : replay->getTimeline()) { - int start_pos = ((begin - replay->minSeconds()) / total_sec) * width; - int end_pos = ((end - replay->minSeconds()) / total_sec) * width; - if (type == TimelineType::Engaged) { + for (const auto &entry : *replay->getTimeline()) { + int start_pos = ((entry.start_time - replay->minSeconds()) / total_sec) * width; + int end_pos = ((entry.end_time - replay->minSeconds()) / total_sec) * width; + if (entry.type == TimelineType::Engaged) { mvwchgat(win, 1, start_pos, end_pos - start_pos + 1, A_COLOR, Color::Engaged, NULL); mvwchgat(win, 2, start_pos, end_pos - start_pos + 1, A_COLOR, Color::Engaged, NULL); - } else if (type == TimelineType::UserFlag) { + } else if (entry.type == TimelineType::UserBookmark) { mvwchgat(win, 3, start_pos, end_pos - start_pos + 1, ACS_S3, Color::Cyan, NULL); } else { auto color_id = Color::Green; - if (type != TimelineType::AlertInfo) { - color_id = type == TimelineType::AlertWarning ? Color::Yellow : Color::Red; + if (entry.type != TimelineType::AlertInfo) { + color_id = entry.type == TimelineType::AlertWarning ? Color::Yellow : Color::Red; } mvwchgat(win, 3, start_pos, end_pos - start_pos + 1, ACS_S3, color_id, NULL); } @@ -288,16 +282,9 @@ void ConsoleUI::updateTimeline() { wrefresh(win); } -void ConsoleUI::readyRead() { - int c; - while ((c = getch()) != ERR) { - handleKey(c); - } -} - void ConsoleUI::pauseReplay(bool pause) { replay->pause(pause); - status = pause ? Status::Paused : Status::Waiting; + status = pause ? Status::Paused : Status::Playing; } void ConsoleUI::handleKey(char c) { @@ -305,7 +292,6 @@ void ConsoleUI::handleKey(char c) { // pause the replay and blocking getchar() pauseReplay(true); updateStatus(); - getch_timer.stop(); curs_set(true); nodelay(stdscr, false); @@ -330,7 +316,6 @@ void ConsoleUI::handleKey(char c) { nodelay(stdscr, true); curs_set(false); refresh(); - getch_timer.start(1000, this); } else if (c == '+' || c == '=') { auto it = std::upper_bound(speed_array.begin(), speed_array.end(), replay->getSpeed()); @@ -350,7 +335,7 @@ void ConsoleUI::handleKey(char c) { } else if (c == 'd') { replay->seekToFlag(FindFlag::nextDisEngagement); } else if (c == 't') { - replay->seekToFlag(FindFlag::nextUserFlag); + replay->seekToFlag(FindFlag::nextUserBookmark); } else if (c == 'i') { replay->seekToFlag(FindFlag::nextInfo); } else if (c == 'w') { @@ -367,7 +352,37 @@ void ConsoleUI::handleKey(char c) { replay->seekTo(-10, true); } else if (c == ' ') { pauseReplay(!replay->isPaused()); - } else if (c == 'q' || c == 'Q') { - qApp->exit(); } } + +int ConsoleUI::exec() { + RateKeeper rk("Replay", 20); + + while (!do_exit) { + int c = getch(); + if (c == 'q' || c == 'Q') { + break; + } + handleKey(c); + + if (rk.frame() % 25) { + updateSize(); + updateSummary(); + } + + updateTimeline(); + updateStatus(); + + { + std::scoped_lock lock(mutex); + updateProgressBar(); + for (auto &[type, msg] : logs) { + logMessage(type, msg); + } + logs.clear(); + } + + rk.keepTime(); + } + return 0; +} diff --git a/tools/replay/consoleui.h b/tools/replay/consoleui.h index 6ed44bc623c5df..7731f8017f51e1 100644 --- a/tools/replay/consoleui.h +++ b/tools/replay/consoleui.h @@ -1,22 +1,18 @@ #pragma once #include -#include -#include -#include -#include -#include +#include +#include #include "tools/replay/replay.h" #include -class ConsoleUI : public QObject { - Q_OBJECT - +class ConsoleUI { public: - ConsoleUI(Replay *replay, QObject *parent = 0); + ConsoleUI(Replay *replay); ~ConsoleUI(); - inline static const std::array speed_array = {0.2f, 0.5f, 1.0f, 2.0f, 3.0f}; + int exec(); + inline static const std::array speed_array = {0.2f, 0.5f, 1.0f, 2.0f, 4.0f, 8.0f}; private: void initWindows(); @@ -27,25 +23,21 @@ class ConsoleUI : public QObject { void updateSummary(); void updateStatus(); void pauseReplay(bool pause); + void updateSize(); + void updateProgressBar(); + void logMessage(ReplyMsgType type, const std::string &msg); - enum Status { Waiting, Playing, Paused }; + enum Status { Playing, Paused }; enum Win { Title, Stats, Log, LogBorder, DownloadBar, Timeline, TimelineDesc, Help, CarState, Max}; std::array w{}; SubMaster sm; Replay *replay; - QBasicTimer getch_timer; - QTimer sm_timer; - QSocketNotifier notifier{0, QSocketNotifier::Read, this}; int max_width, max_height; - Status status = Status::Waiting; - -signals: - void updateProgressBarSignal(uint64_t cur, uint64_t total, bool success); - void logMessageSignal(ReplyMsgType type, const QString &msg); + Status status = Status::Playing; -private slots: - void readyRead(); - void timerEvent(QTimerEvent *ev); - void updateProgressBar(uint64_t cur, uint64_t total, bool success); - void logMessage(ReplyMsgType type, const QString &msg); + std::mutex mutex; + std::vector> logs; + uint64_t progress_cur = 0; + uint64_t progress_total = 0; + bool download_success = false; }; diff --git a/tools/replay/filereader.cc b/tools/replay/filereader.cc index d74aaebabaec14..93a6a1193f372d 100644 --- a/tools/replay/filereader.cc +++ b/tools/replay/filereader.cc @@ -1,49 +1,14 @@ #include "tools/replay/filereader.h" -#include - #include "common/util.h" -#include "system/hardware/hw.h" -#include "tools/replay/util.h" - -std::string cacheFilePath(const std::string &url) { - static std::string cache_path = [] { - const std::string comma_cache = Path::download_cache_root(); - util::create_directories(comma_cache, 0755); - return comma_cache.back() == '/' ? comma_cache : comma_cache + "/"; - }(); - - return cache_path + sha256(getUrlWithoutQuery(url)); -} +#include "tools/replay/py_downloader.h" std::string FileReader::read(const std::string &file, std::atomic *abort) { - const bool is_remote = file.find("https://") == 0; - const std::string local_file = is_remote ? cacheFilePath(file) : file; - std::string result; - - if ((!is_remote || cache_to_local_) && util::file_exists(local_file)) { - result = util::read_file(local_file); - } else if (is_remote) { - result = download(file, abort); - if (cache_to_local_ && !result.empty()) { - std::ofstream fs(local_file, std::ios::binary | std::ios::out); - fs.write(result.data(), result.size()); - } - } - return result; -} - -std::string FileReader::download(const std::string &url, std::atomic *abort) { - for (int i = 0; i <= max_retries_ && !(abort && *abort); ++i) { - if (i > 0) { - rWarning("download failed, retrying %d", i); - util::sleep_for(3000); - } - - std::string result = httpGet(url, chunk_size_, abort); - if (!result.empty()) { - return result; - } + const bool is_remote = (file.find("https://") == 0) || (file.find("http://") == 0); + if (is_remote) { + std::string local_path = PyDownloader::download(file, cache_to_local_, abort); + if (local_path.empty()) return {}; + return util::read_file(local_path); } - return {}; + return util::read_file(file); } diff --git a/tools/replay/filereader.h b/tools/replay/filereader.h index 34aa91e858ecfd..30740cd0ac3872 100644 --- a/tools/replay/filereader.h +++ b/tools/replay/filereader.h @@ -5,16 +5,10 @@ class FileReader { public: - FileReader(bool cache_to_local, size_t chunk_size = 0, int retries = 3) - : cache_to_local_(cache_to_local), chunk_size_(chunk_size), max_retries_(retries) {} + FileReader(bool cache_to_local) : cache_to_local_(cache_to_local) {} virtual ~FileReader() {} std::string read(const std::string &file, std::atomic *abort = nullptr); private: - std::string download(const std::string &url, std::atomic *abort); - size_t chunk_size_; - int max_retries_; bool cache_to_local_; }; - -std::string cacheFilePath(const std::string &url); diff --git a/tools/replay/framereader.cc b/tools/replay/framereader.cc index 26ef4684a41680..a643f0d3a78229 100644 --- a/tools/replay/framereader.cc +++ b/tools/replay/framereader.cc @@ -6,8 +6,10 @@ #include #include "common/util.h" -#include "third_party/libyuv/include/libyuv.h" +#include "libyuv.h" +#include "tools/replay/py_downloader.h" #include "tools/replay/util.h" +#include "system/hardware/hw.h" #ifdef __APPLE__ #define HW_DEVICE_TYPE AV_HWDEVICE_TYPE_VIDEOTOOLBOX @@ -37,7 +39,16 @@ struct DecoderManager { return it->second.get(); } - auto decoder = std::make_unique(); + std::unique_ptr decoder; + #ifndef __APPLE__ + if (!Hardware::PC() && hw_decoder) { + decoder = std::make_unique(); + } else + #endif + { + decoder = std::make_unique(); + } + if (!decoder->open(codecpar, hw_decoder)) { decoder.reset(nullptr); } @@ -61,13 +72,13 @@ FrameReader::~FrameReader() { if (input_ctx) avformat_close_input(&input_ctx); } -bool FrameReader::load(CameraType type, const std::string &url, bool no_hw_decoder, std::atomic *abort, bool local_cache, int chunk_size, int retries) { - auto local_file_path = url.find("https://") == 0 ? cacheFilePath(url) : url; - if (!util::file_exists(local_file_path)) { - FileReader f(local_cache, chunk_size, retries); - if (f.read(url, abort).empty()) { - return false; - } +bool FrameReader::load(CameraType type, const std::string &url, bool no_hw_decoder, std::atomic *abort, bool local_cache) { + std::string local_file_path; + if (url.find("https://") == 0 || url.find("http://") == 0) { + local_file_path = PyDownloader::download(url, local_cache, abort); + if (local_file_path.empty()) return false; + } else { + local_file_path = url; } return loadFromFile(type, local_file_path, no_hw_decoder, abort); } @@ -80,7 +91,13 @@ bool FrameReader::loadFromFile(CameraType type, const std::string &file, bool no } input_ctx->probesize = 10 * 1024 * 1024; // 10MB - decoder_ = decoder_manager.acquire(type, input_ctx->streams[0]->codecpar, !no_hw_decoder); + video_stream_idx_ = av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0); + if (video_stream_idx_ < 0) { + rError("No video stream found in file"); + return false; + } + + decoder_ = decoder_manager.acquire(type, input_ctx->streams[video_stream_idx_]->codecpar, !no_hw_decoder); if (!decoder_) { return false; } @@ -90,7 +107,9 @@ bool FrameReader::loadFromFile(CameraType type, const std::string &file, bool no AVPacket pkt; packets_info.reserve(60 * 20); // 20fps, one minute while (!(abort && *abort) && av_read_frame(input_ctx, &pkt) == 0) { - packets_info.emplace_back(PacketInfo{.flags = pkt.flags, .pos = pkt.pos}); + if (pkt.stream_index == video_stream_idx_) { + packets_info.emplace_back(PacketInfo{.flags = pkt.flags, .pos = pkt.pos}); + } av_packet_unref(&pkt); } avio_seek(input_ctx->pb, 0, SEEK_SET); @@ -106,19 +125,19 @@ bool FrameReader::get(int idx, VisionBuf *buf) { // class VideoDecoder -VideoDecoder::VideoDecoder() { +FFmpegVideoDecoder::FFmpegVideoDecoder() { av_frame_ = av_frame_alloc(); hw_frame_ = av_frame_alloc(); } -VideoDecoder::~VideoDecoder() { +FFmpegVideoDecoder::~FFmpegVideoDecoder() { if (hw_device_ctx) av_buffer_unref(&hw_device_ctx); if (decoder_ctx) avcodec_free_context(&decoder_ctx); av_frame_free(&av_frame_); av_frame_free(&hw_frame_); } -bool VideoDecoder::open(AVCodecParameters *codecpar, bool hw_decoder) { +bool FFmpegVideoDecoder::open(AVCodecParameters *codecpar, bool hw_decoder) { const AVCodec *decoder = avcodec_find_decoder(codecpar->codec_id); if (!decoder) return false; @@ -141,7 +160,7 @@ bool VideoDecoder::open(AVCodecParameters *codecpar, bool hw_decoder) { return true; } -bool VideoDecoder::initHardwareDecoder(AVHWDeviceType hw_device_type) { +bool FFmpegVideoDecoder::initHardwareDecoder(AVHWDeviceType hw_device_type) { const AVCodecHWConfig *config = nullptr; for (int i = 0; (config = avcodec_get_hw_config(decoder_ctx->codec, i)) != nullptr; i++) { if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && config->device_type == hw_device_type) { @@ -167,35 +186,51 @@ bool VideoDecoder::initHardwareDecoder(AVHWDeviceType hw_device_type) { return true; } -bool VideoDecoder::decode(FrameReader *reader, int idx, VisionBuf *buf) { - int from_idx = idx; +bool FFmpegVideoDecoder::decode(FrameReader *reader, int idx, VisionBuf *buf) { + int current_idx = idx; if (idx != reader->prev_idx + 1) { // seeking to the nearest key frame for (int i = idx; i >= 0; --i) { if (reader->packets_info[i].flags & AV_PKT_FLAG_KEY) { - from_idx = i; + current_idx = i; break; } } - avio_seek(reader->input_ctx->pb, reader->packets_info[from_idx].pos, SEEK_SET); + + auto pos = reader->packets_info[current_idx].pos; + int ret = avformat_seek_file(reader->input_ctx, 0, pos, pos, pos, AVSEEK_FLAG_BYTE); + if (ret < 0) { + rError("Failed to seek to byte position %lld: %d", pos, AVERROR(ret)); + return false; + } + avcodec_flush_buffers(decoder_ctx); } reader->prev_idx = idx; - bool result = false; AVPacket pkt; - for (int i = from_idx; i <= idx; ++i) { - if (av_read_frame(reader->input_ctx, &pkt) == 0) { - AVFrame *f = decodeFrame(&pkt); - if (f && i == idx) { - result = copyBuffer(f, buf); - } + while (av_read_frame(reader->input_ctx, &pkt) >= 0) { + // Skip non-video packets + if (pkt.stream_index != reader->video_stream_idx_) { av_packet_unref(&pkt); + continue; + } + + AVFrame *frame = decodeFrame(&pkt); + av_packet_unref(&pkt); + if (!frame) { + rError("Failed to decode frame at index %d", current_idx); + return false; + } + + if (current_idx++ == idx) { + return copyBuffer(frame, buf); } } - return result; + rError("Failed to find frame at index %d", idx); + return false; } -AVFrame *VideoDecoder::decodeFrame(AVPacket *pkt) { +AVFrame *FFmpegVideoDecoder::decodeFrame(AVPacket *pkt) { int ret = avcodec_send_packet(decoder_ctx, pkt); if (ret < 0) { rError("Error sending a packet for decoding: %d", ret); @@ -215,7 +250,7 @@ AVFrame *VideoDecoder::decodeFrame(AVPacket *pkt) { return (av_frame_->format == hw_pix_fmt) ? hw_frame_ : av_frame_; } -bool VideoDecoder::copyBuffer(AVFrame *f, VisionBuf *buf) { +bool FFmpegVideoDecoder::copyBuffer(AVFrame *f, VisionBuf *buf) { if (hw_pix_fmt == HW_PIX_FMT) { for (int i = 0; i < height/2; i++) { memcpy(buf->y + (i*2 + 0)*buf->stride, f->data[0] + (i*2 + 0)*f->linesize[0], width); @@ -232,3 +267,47 @@ bool VideoDecoder::copyBuffer(AVFrame *f, VisionBuf *buf) { } return true; } + +#ifndef __APPLE__ +bool QcomVideoDecoder::open(AVCodecParameters *codecpar, bool hw_decoder) { + if (codecpar->codec_id != AV_CODEC_ID_HEVC) { + rError("Hardware decoder only supports HEVC codec"); + return false; + } + width = codecpar->width; + height = codecpar->height; + msm_vidc.init(VIDEO_DEVICE, width, height, V4L2_PIX_FMT_HEVC); + return true; +} + +bool QcomVideoDecoder::decode(FrameReader *reader, int idx, VisionBuf *buf) { + int from_idx = idx; + if (idx != reader->prev_idx + 1) { + // seeking to the nearest key frame + for (int i = idx; i >= 0; --i) { + if (reader->packets_info[i].flags & AV_PKT_FLAG_KEY) { + from_idx = i; + break; + } + } + + auto pos = reader->packets_info[from_idx].pos; + int ret = avformat_seek_file(reader->input_ctx, 0, pos, pos, pos, AVSEEK_FLAG_BYTE); + if (ret < 0) { + rError("Failed to seek to byte position %lld: %d", pos, AVERROR(ret)); + return false; + } + } + reader->prev_idx = idx; + bool result = false; + AVPacket pkt; + msm_vidc.avctx = reader->input_ctx; + for (int i = from_idx; i <= idx; ++i) { + if (av_read_frame(reader->input_ctx, &pkt) == 0) { + result = msm_vidc.decodeFrame(&pkt, buf) && (i == idx); + av_packet_unref(&pkt); + } + } + return result; +} +#endif diff --git a/tools/replay/framereader.h b/tools/replay/framereader.h index 7a4d024aa20f23..3609d64f8b2be7 100644 --- a/tools/replay/framereader.h +++ b/tools/replay/framereader.h @@ -4,8 +4,11 @@ #include #include "msgq/visionipc/visionbuf.h" -#include "system/camerad/cameras/camera_common.h" -#include "tools/replay/filereader.h" +#include "tools/replay/util.h" + +#ifndef __APPLE__ +#include "tools/replay/qcom_decoder.h" +#endif extern "C" { #include @@ -18,8 +21,7 @@ class FrameReader { public: FrameReader(); ~FrameReader(); - bool load(CameraType type, const std::string &url, bool no_hw_decoder = false, std::atomic *abort = nullptr, bool local_cache = false, - int chunk_size = -1, int retries = 0); + bool load(CameraType type, const std::string &url, bool no_hw_decoder = false, std::atomic *abort = nullptr, bool local_cache = false); bool loadFromFile(CameraType type, const std::string &file, bool no_hw_decoder = false, std::atomic *abort = nullptr); bool get(int idx, VisionBuf *buf); size_t getFrameCount() const { return packets_info.size(); } @@ -28,6 +30,7 @@ class FrameReader { VideoDecoder *decoder_ = nullptr; AVFormatContext *input_ctx = nullptr; + int video_stream_idx_ = -1; int prev_idx = -1; struct PacketInfo { int flags; @@ -39,11 +42,18 @@ class FrameReader { class VideoDecoder { public: - VideoDecoder(); - ~VideoDecoder(); - bool open(AVCodecParameters *codecpar, bool hw_decoder); - bool decode(FrameReader *reader, int idx, VisionBuf *buf); + virtual ~VideoDecoder() = default; + virtual bool open(AVCodecParameters *codecpar, bool hw_decoder) = 0; + virtual bool decode(FrameReader *reader, int idx, VisionBuf *buf) = 0; int width = 0, height = 0; +}; + +class FFmpegVideoDecoder : public VideoDecoder { +public: + FFmpegVideoDecoder(); + ~FFmpegVideoDecoder() override; + bool open(AVCodecParameters *codecpar, bool hw_decoder) override; + bool decode(FrameReader *reader, int idx, VisionBuf *buf) override; private: bool initHardwareDecoder(AVHWDeviceType hw_device_type); @@ -55,3 +65,16 @@ class VideoDecoder { AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; AVBufferRef *hw_device_ctx = nullptr; }; + +#ifndef __APPLE__ +class QcomVideoDecoder : public VideoDecoder { +public: + QcomVideoDecoder() {}; + ~QcomVideoDecoder() override {}; + bool open(AVCodecParameters *codecpar, bool hw_decoder) override; + bool decode(FrameReader *reader, int idx, VisionBuf *buf) override; + +private: + MsmVidc msm_vidc = MsmVidc(); +}; +#endif diff --git a/tools/replay/lib/rp_helpers.py b/tools/replay/lib/rp_helpers.py deleted file mode 100644 index 95eef9d233da30..00000000000000 --- a/tools/replay/lib/rp_helpers.py +++ /dev/null @@ -1,108 +0,0 @@ -import numpy as np -from openpilot.selfdrive.controls.radard import RADAR_TO_CAMERA - -# Color palette used for rerun AnnotationContext -rerunColorPalette = [(96, "red", (255, 0, 0)), - (100, "pink", (255, 36, 0)), - (124, "yellow", (255, 255, 0)), - (230, "vibrantpink", (255, 36, 170)), - (240, "orange", (255, 146, 0)), - (255, "white", (255, 255, 255)), - (110, "carColor", (255,0,127))] - - -class UIParams: - lidar_x, lidar_y, lidar_zoom = 384, 960, 6 - lidar_car_x, lidar_car_y = lidar_x / 2., lidar_y / 1.1 - car_hwidth = 1.7272 / 2 * lidar_zoom - car_front = 2.6924 * lidar_zoom - car_back = 1.8796 * lidar_zoom - car_color = rerunColorPalette[6][0] -UP = UIParams - - -def to_topdown_pt(y, x): - px, py = x * UP.lidar_zoom + UP.lidar_car_x, -y * UP.lidar_zoom + UP.lidar_car_y - if px > 0 and py > 0 and px < UP.lidar_x and py < UP.lidar_y: - return int(px), int(py) - return -1, -1 - - -def draw_path(path, lid_overlay, lid_color=None): - x, y = np.asarray(path.x), np.asarray(path.y) - # draw lidar path point on lidar - if lid_color is not None and lid_overlay is not None: - for i in range(len(x)): - px, py = to_topdown_pt(x[i], y[i]) - if px != -1: - lid_overlay[px, py] = lid_color - - -def plot_model(m, lid_overlay): - if lid_overlay is None: - return - for lead in m.leadsV3: - if lead.prob < 0.5: - continue - x, y = lead.x[0], lead.y[0] - x_std = lead.xStd[0] - x -= RADAR_TO_CAMERA - _, py_top = to_topdown_pt(x + x_std, y) - px, py_bottom = to_topdown_pt(x - x_std, y) - lid_overlay[int(round(px - 4)):int(round(px + 4)), py_top:py_bottom] = rerunColorPalette[2][0] - - for path in m.laneLines: - draw_path(path, lid_overlay, rerunColorPalette[2][0]) - for edge in m.roadEdges: - draw_path(edge, lid_overlay, rerunColorPalette[0][0]) - draw_path(m.position, lid_overlay, rerunColorPalette[0][0]) - - -def plot_lead(rs, lid_overlay): - for lead in [rs.leadOne, rs.leadTwo]: - if not lead.status: - continue - x = lead.dRel - px_left, py = to_topdown_pt(x, -10) - px_right, _ = to_topdown_pt(x, 10) - lid_overlay[px_left:px_right, py] = rerunColorPalette[0][0] - - -def maybe_update_radar_points(lt, lid_overlay): - ar_pts = [] - if lt is not None: - ar_pts = {} - for track in lt: - ar_pts[track.trackId] = [track.dRel, track.yRel, track.vRel, track.aRel, track.oncoming, track.stationary] - for ids, pt in ar_pts.items(): - # negative here since radar is left positive - px, py = to_topdown_pt(pt[0], -pt[1]) - if px != -1: - if pt[-1]: - color = rerunColorPalette[4][0] - elif pt[-2]: - color = rerunColorPalette[3][0] - else: - color = rerunColorPalette[5][0] - if int(ids) == 1: - lid_overlay[px - 2:px + 2, py - 10:py + 10] = rerunColorPalette[1][0] - else: - lid_overlay[px - 2:px + 2, py - 2:py + 2] = color - - -def get_blank_lid_overlay(UP): - lid_overlay = np.zeros((UP.lidar_x, UP.lidar_y), 'uint8') - # Draw the car. - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)):int( - round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y - - UP.car_front))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)):int( - round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y + - UP.car_back))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)), int( - round(UP.lidar_car_y - UP.car_front)):int(round( - UP.lidar_car_y + UP.car_back))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x + UP.car_hwidth)), int( - round(UP.lidar_car_y - UP.car_front)):int(round( - UP.lidar_car_y + UP.car_back))] = UP.car_color - return lid_overlay diff --git a/tools/replay/lib/ui_helpers.py b/tools/replay/lib/ui_helpers.py new file mode 100644 index 00000000000000..039dd4f235959f --- /dev/null +++ b/tools/replay/lib/ui_helpers.py @@ -0,0 +1,220 @@ +import itertools + +import matplotlib.pyplot as plt +import numpy as np +import pyray as rl + +from matplotlib.backends.backend_agg import FigureCanvasAgg +from matplotlib.offsetbox import AnchoredOffsetbox, HPacker, TextArea + +from openpilot.common.transformations.camera import get_view_frame_from_calib_frame +from openpilot.selfdrive.controls.radard import RADAR_TO_CAMERA + + +RED = (255, 0, 0) +GREEN = (0, 255, 0) +BLUE = (0, 0, 255) +YELLOW = (255, 255, 0) +BLACK = (0, 0, 0) +WHITE = (255, 255, 255) + + +class UIParams: + lidar_x, lidar_y, lidar_zoom = 384, 960, 6 + lidar_car_x, lidar_car_y = lidar_x / 2.0, lidar_y / 1.1 + car_hwidth = 1.7272 / 2 * lidar_zoom + car_front = 2.6924 * lidar_zoom + car_back = 1.8796 * lidar_zoom + car_color = 110 + + +UP = UIParams + +METER_WIDTH = 20 + + +class Calibration: + def __init__(self, num_px, rpy, intrinsic, calib_scale): + self.intrinsic = intrinsic + self.extrinsics_matrix = get_view_frame_from_calib_frame(rpy[0], rpy[1], rpy[2], 0.0)[:, :3] + self.zoom = calib_scale + + def car_space_to_ff(self, x, y, z): + car_space_projective = np.column_stack((x, y, z)).T + + ep = self.extrinsics_matrix.dot(car_space_projective) + kep = self.intrinsic.dot(ep) + return (kep[:-1, :] / kep[-1, :]).T + + def car_space_to_bb(self, x, y, z): + pts = self.car_space_to_ff(x, y, z) + return pts / self.zoom + + +_COLOR_CACHE: dict[tuple[int, int, int], int] = { + (255, 0, 0): 1, # RED + (0, 255, 0): 2, # GREEN + (0, 0, 255): 3, # BLUE + (255, 255, 0): 4, # YELLOW + (0, 0, 0): 0, # BLACK + (255, 255, 255): 255, # WHITE +} + + +def find_color(lidar_surface, color): + return _COLOR_CACHE.get(color, 255) + + +def to_topdown_pt(y, x): + px, py = x * UP.lidar_zoom + UP.lidar_car_x, -y * UP.lidar_zoom + UP.lidar_car_y + if px > 0 and py > 0 and px < UP.lidar_x and py < UP.lidar_y: + return int(px), int(py) + return -1, -1 + + +def draw_path(path, color, img, calibration, top_down, lid_color=None, z_off=0): + x, y, z = np.asarray(path.x), np.asarray(path.y), np.asarray(path.z) + z_off + pts = calibration.car_space_to_bb(x, y, z) + pts = np.round(pts).astype(int) + + # draw lidar path point on lidar + # find color in 8 bit + if lid_color is not None and top_down is not None: + tcolor = find_color(top_down[0], lid_color) + for i in range(len(x)): + px, py = to_topdown_pt(x[i], y[i]) + if px != -1: + top_down[1][px, py] = tcolor + + height, width = img.shape[:2] + for x, y in pts: + if 1 < x < width - 1 and 1 < y < height - 1: + for a, b in itertools.permutations([-1, 0, -1], 2): + img[y + a, x + b] = color + + +def init_plots(arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles): + color_palette = {"r": (1, 0, 0), "g": (0, 1, 0), "b": (0, 0, 1), "k": (0, 0, 0), "y": (1, 1, 0), "p": (0, 1, 1), "m": (1, 0, 1)} + label_palette = {**color_palette, "b": (43/255, 114/255, 1.0)} + + dpi = 90 + fig = plt.figure(figsize=(575 / dpi, 600 / dpi), dpi=dpi) + canvas = FigureCanvasAgg(fig) + + fig.set_facecolor((0.2, 0.2, 0.2)) + + axs = [] + for pn in range(len(plot_ylims)): + ax = fig.add_subplot(len(plot_ylims), 1, len(axs) + 1) + ax.set_xlim(plot_xlims[pn][0], plot_xlims[pn][1]) + ax.set_ylim(plot_ylims[pn][0], plot_ylims[pn][1]) + ax.patch.set_facecolor((0.4, 0.4, 0.4)) + axs.append(ax) + + plots, idxs, plot_select = [], [], [] + for i, pl_list in enumerate(plot_names): + for j, item in enumerate(pl_list): + (plot,) = axs[i].plot(arr[:, name_to_arr_idx[item]], label=item, color=color_palette[plot_colors[i][j]], linestyle=plot_styles[i][j]) + plots.append(plot) + idxs.append(name_to_arr_idx[item]) + plot_select.append(i) + # Build colored title: each label colored to match its plot line + title_texts = [] + for j2, (nm, cl) in enumerate(zip(pl_list, plot_colors[i], strict=False)): + if j2 > 0: + title_texts.append(TextArea(", ", textprops=dict(color="white", fontsize=10))) + title_texts.append(TextArea(nm, textprops=dict(color=label_palette[cl], fontsize=10))) + packed = HPacker(children=title_texts, pad=0, sep=0) + ab = AnchoredOffsetbox(loc='lower center', child=packed, bbox_to_anchor=(0.5, 1.0), + bbox_transform=axs[i].transAxes, frameon=False, pad=0) + axs[i].add_artist(ab) + axs[i].tick_params(axis="x", colors="white") + axs[i].tick_params(axis="y", colors="white") + + if i < len(plot_ylims) - 1: + axs[i].set_xticks([]) + + canvas.draw() + + # Pre-create texture for plots (reuse each frame to avoid log spam) + w, h = canvas.get_width_height() + plot_image = rl.gen_image_color(w, h, rl.BLACK) + plot_texture = rl.load_texture_from_image(plot_image) + rl.unload_image(plot_image) + + def draw_plots(arr): + for ax in axs: + ax.draw_artist(ax.patch) + for i in range(len(plots)): + plots[i].set_ydata(arr[:, idxs[i]]) + axs[plot_select[i]].draw_artist(plots[i]) + + raw_data = np.ascontiguousarray(canvas.buffer_rgba(), dtype=np.uint8) + rl.update_texture(plot_texture, rl.ffi.cast("void *", raw_data.ctypes.data)) + return plot_texture + + return draw_plots + + +def plot_model(m, img, calibration, top_down): + if calibration is None or top_down is None: + return + + for lead in m.leadsV3: + if lead.prob < 0.5: + continue + + x, y = lead.x[0], lead.y[0] + x_std = lead.xStd[0] + x -= RADAR_TO_CAMERA + + _, py_top = to_topdown_pt(x + x_std, y) + px, py_bottom = to_topdown_pt(x - x_std, y) + top_down[1][int(round(px - 4)) : int(round(px + 4)), py_top:py_bottom] = find_color(top_down[0], YELLOW) + + for path, prob, _ in zip(m.laneLines, m.laneLineProbs, m.laneLineStds, strict=True): + color = (0, int(255 * prob), 0) + draw_path(path, color, img, calibration, top_down, YELLOW) + + for edge, std in zip(m.roadEdges, m.roadEdgeStds, strict=True): + prob = max(1 - std, 0) + color = (int(255 * prob), 0, 0) + draw_path(edge, color, img, calibration, top_down, RED) + + color = (255, 0, 0) + draw_path(m.position, color, img, calibration, top_down, RED, 1.22) + + +def plot_lead(rs, top_down): + for lead in [rs.leadOne, rs.leadTwo]: + if not lead.status: + continue + + x = lead.dRel + px_left, py = to_topdown_pt(x, -10) + px_right, _ = to_topdown_pt(x, 10) + top_down[1][px_left:px_right, py] = find_color(top_down[0], RED) + + +def maybe_update_radar_points(lt, lid_overlay): + ar_pts = [] + if lt is not None: + ar_pts = {} + for track in lt: + ar_pts[track.trackId] = [track.dRel, track.yRel, track.vRel, track.aRel] + for pt in ar_pts.values(): + # negative here since radar is left positive + px, py = to_topdown_pt(pt[0], -pt[1]) + if px != -1: + lid_overlay[px - 4 : px + 4, py - 4 : py + 4] = 0 + lid_overlay[px - 2 : px + 2, py - 2 : py + 2] = 255 + + +def get_blank_lid_overlay(UP): + lid_overlay = np.zeros((UP.lidar_x, UP.lidar_y), 'uint8') + # Draw the car. + lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)) : int(round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y - UP.car_front))] = UP.car_color + lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)) : int(round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y + UP.car_back))] = UP.car_color + lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)), int(round(UP.lidar_car_y - UP.car_front)) : int(round(UP.lidar_car_y + UP.car_back))] = UP.car_color + lid_overlay[int(round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y - UP.car_front)) : int(round(UP.lidar_car_y + UP.car_back))] = UP.car_color + return lid_overlay diff --git a/tools/replay/logreader.cc b/tools/replay/logreader.cc index 75abb8417b597f..54b69dc168c1e6 100644 --- a/tools/replay/logreader.cc +++ b/tools/replay/logreader.cc @@ -1,31 +1,68 @@ #include "tools/replay/logreader.h" #include +#include #include #include "tools/replay/filereader.h" +#include "tools/replay/py_downloader.h" #include "tools/replay/util.h" #include "common/util.h" -bool LogReader::load(const std::string &url, std::atomic *abort, bool local_cache, int chunk_size, int retries) { - std::string data = FileReader(local_cache, chunk_size, retries).read(url, abort); +bool LogReader::load(const std::string &url, std::atomic *abort, bool local_cache, + const ProgressCallback &progress) { + using Clock = std::chrono::steady_clock; + compressed_size_ = 0; + decompressed_size_ = 0; + download_seconds_ = 0.0; + decompress_seconds_ = 0.0; + parse_seconds_ = 0.0; + + if (progress) { + installDownloadProgressHandler([progress](uint64_t cur, uint64_t total, bool success) { + if (success) { + progress(ProgressStage::Downloading, cur, total); + } + }); + } + const auto download_start = Clock::now(); + std::string data = FileReader(local_cache).read(url, abort); + const auto download_end = Clock::now(); + if (progress) { + installDownloadProgressHandler(nullptr); + } + compressed_size_ = data.size(); + download_seconds_ = std::chrono::duration(download_end - download_start).count(); if (!data.empty()) { + const auto decompress_start = Clock::now(); if (url.find(".bz2") != std::string::npos || util::starts_with(data, "BZh9")) { data = decompressBZ2(data, abort); } else if (url.find(".zst") != std::string::npos || util::starts_with(data, "\x28\xB5\x2F\xFD")) { data = decompressZST(data, abort); } + const auto decompress_end = Clock::now(); + decompress_seconds_ = std::chrono::duration(decompress_end - decompress_start).count(); } + decompressed_size_ = data.size(); - bool success = !data.empty() && load(data.data(), data.size(), abort); + bool success = !data.empty() && load(data.data(), data.size(), abort, progress); if (filters_.empty()) raw_ = std::move(data); return success; } -bool LogReader::load(const char *data, size_t size, std::atomic *abort) { +bool LogReader::load(const char *data, size_t size, std::atomic *abort, + const ProgressCallback &progress) { + using Clock = std::chrono::steady_clock; + const auto parse_start = Clock::now(); try { events.reserve(65000); kj::ArrayPtr words((const capnp::word *)data, size / sizeof(capnp::word)); + const uint64_t total_bytes = size; + const uint64_t report_step = std::max(1, total_bytes / 200); + uint64_t last_reported = 0; + if (progress) { + progress(ProgressStage::Parsing, 0, total_bytes); + } while (words.size() > 0 && !(abort && *abort)) { capnp::FlatArrayMessageReader reader(words); auto event = reader.getRoot(); @@ -56,15 +93,30 @@ bool LogReader::load(const char *data, size_t size, std::atomic *abort) { events.emplace_back(which, sof ? sof : mono_time, event_data, idx.getSegmentNum()); } } + + if (progress) { + const uint64_t current_bytes = + total_bytes - static_cast(words.size() * sizeof(capnp::word)); + if (current_bytes >= total_bytes || current_bytes - last_reported >= report_step) { + progress(ProgressStage::Parsing, current_bytes, total_bytes); + last_reported = current_bytes; + } + } } } catch (const kj::Exception &e) { rWarning("Failed to parse log : %s.\nRetrieved %zu events from corrupt log", e.getDescription().cStr(), events.size()); } + if (progress) { + progress(ProgressStage::Parsing, size, size); + } + if (requires_migration) { migrateOldEvents(); } + parse_seconds_ = std::chrono::duration(Clock::now() - parse_start).count(); + if (!events.empty() && !(abort && *abort)) { events.shrink_to_fit(); std::sort(events.begin(), events.end()); @@ -90,18 +142,19 @@ void LogReader::migrateOldEvents() { new_evt.setLogMonoTime(old_evt.getLogMonoTime()); auto new_state = new_evt.initSelfdriveState(); - new_state.setActive(old_state.getActiveDEPRECATED()); - new_state.setAlertSize(old_state.getAlertSizeDEPRECATED()); - new_state.setAlertSound(old_state.getAlertSound2DEPRECATED()); - new_state.setAlertStatus(old_state.getAlertStatusDEPRECATED()); - new_state.setAlertText1(old_state.getAlertText1DEPRECATED()); - new_state.setAlertText2(old_state.getAlertText2DEPRECATED()); - new_state.setAlertType(old_state.getAlertTypeDEPRECATED()); - new_state.setEnabled(old_state.getEnabledDEPRECATED()); - new_state.setEngageable(old_state.getEngageableDEPRECATED()); - new_state.setExperimentalMode(old_state.getExperimentalModeDEPRECATED()); - new_state.setPersonality(old_state.getPersonalityDEPRECATED()); - new_state.setState(old_state.getStateDEPRECATED()); + auto old_dep = old_state.getDeprecated(); + new_state.setActive(old_dep.getActive()); + new_state.setAlertSize(old_dep.getAlertSize()); + new_state.setAlertSound(old_dep.getAlertSound2()); + new_state.setAlertStatus(old_dep.getAlertStatus()); + new_state.setAlertText1(old_dep.getAlertText1()); + new_state.setAlertText2(old_dep.getAlertText2()); + new_state.setAlertType(old_dep.getAlertType()); + new_state.setEnabled(old_dep.getEnabled()); + new_state.setEngageable(old_dep.getEngageable()); + new_state.setExperimentalMode(old_dep.getExperimentalMode()); + new_state.setPersonality(old_dep.getPersonality()); + new_state.setState(old_dep.getState()); // Serialize the new event to the buffer auto buf_size = msg.getSerializedSize(); diff --git a/tools/replay/logreader.h b/tools/replay/logreader.h index ab35954db6ca30..fe11ab0f77d3bb 100644 --- a/tools/replay/logreader.h +++ b/tools/replay/logreader.h @@ -1,10 +1,11 @@ #pragma once +#include +#include #include #include #include "cereal/gen/cpp/log.capnp.h" -#include "system/camerad/cameras/camera_common.h" #include "tools/replay/util.h" const CameraType ALL_CAMERAS[] = {RoadCam, DriverCam, WideRoadCam}; @@ -27,12 +28,26 @@ class Event { class LogReader { public: + enum class ProgressStage { + Downloading, + Parsing, + }; + + using ProgressCallback = std::function; + LogReader(const std::vector &filters = {}) { filters_ = filters; } bool load(const std::string &url, std::atomic *abort = nullptr, - bool local_cache = false, int chunk_size = -1, int retries = 0); - bool load(const char *data, size_t size, std::atomic *abort = nullptr); + bool local_cache = false, const ProgressCallback &progress = {}); + bool load(const char *data, size_t size, std::atomic *abort = nullptr, + const ProgressCallback &progress = {}); std::vector events; + uint64_t compressed_size() const { return compressed_size_; } + uint64_t decompressed_size() const { return decompressed_size_; } + double download_seconds() const { return download_seconds_; } + double decompress_seconds() const { return decompress_seconds_; } + double parse_seconds() const { return parse_seconds_; } + private: void migrateOldEvents(); @@ -40,4 +55,9 @@ class LogReader { bool requires_migration = true; std::vector filters_; MonotonicBuffer buffer_{1024 * 1024}; + uint64_t compressed_size_ = 0; + uint64_t decompressed_size_ = 0; + double download_seconds_ = 0.0; + double decompress_seconds_ = 0.0; + double parse_seconds_ = 0.0; }; diff --git a/tools/replay/main.cc b/tools/replay/main.cc index a0c072438dfdc9..bdb9cf4f35a873 100644 --- a/tools/replay/main.cc +++ b/tools/replay/main.cc @@ -1,83 +1,187 @@ -#include -#include +#include + +#include +#include +#include +#include +#include +#include #include "common/prefix.h" +#include "common/timing.h" #include "tools/replay/consoleui.h" #include "tools/replay/replay.h" +#include "tools/replay/util.h" -int main(int argc, char *argv[]) { -#ifdef __APPLE__ - // With all sockets opened, we might hit the default limit of 256 on macOS - util::set_file_descriptor_limit(1024); -#endif +const std::string helpText = +R"(Usage: replay [options] [route] +Options: + -a, --allow Whitelist of services to send (comma-separated) + -b, --block Blacklist of services to send (comma-separated) + -c, --cache Cache segments in memory. Default is 5 + -s, --start Start from + -x, --playback Playback + --demo Use a demo route instead of providing your own + --auto Auto load the route from the best available source (no video): + internal, openpilotci, comma_api, car_segments, testing_closet + -d, --data_dir Local directory with routes + -p, --prefix Set OPENPILOT_PREFIX + --dcam Load driver camera + --ecam Load wide road camera + --no-loop Stop at the end of the route + --no-cache Turn off local cache + --qcam Load qcamera + --no-hw-decoder Disable HW video decoding + --no-vipc Do not output video + --all Output all messages including bookmarkButton, uiDebug, userBookmark + --benchmark Run in benchmark mode (process all events then exit with stats) + -h, --help Show this help message +)"; + +struct ReplayConfig { + std::string route; + std::vector allow; + std::vector block; + std::string data_dir; + std::string prefix; + uint32_t flags = REPLAY_FLAG_NONE; + bool auto_source = false; + int start_seconds = 0; + int cache_segments = -1; + float playback_speed = -1; +}; + +bool parseArgs(int argc, char *argv[], ReplayConfig &config) { + const struct option cli_options[] = { + {"allow", required_argument, nullptr, 'a'}, + {"block", required_argument, nullptr, 'b'}, + {"cache", required_argument, nullptr, 'c'}, + {"start", required_argument, nullptr, 's'}, + {"playback", required_argument, nullptr, 'x'}, + {"demo", no_argument, nullptr, 0}, + {"auto", no_argument, nullptr, 0}, + {"data_dir", required_argument, nullptr, 'd'}, + {"prefix", required_argument, nullptr, 'p'}, + {"dcam", no_argument, nullptr, 0}, + {"ecam", no_argument, nullptr, 0}, + {"no-loop", no_argument, nullptr, 0}, + {"no-cache", no_argument, nullptr, 0}, + {"qcam", no_argument, nullptr, 0}, + {"no-hw-decoder", no_argument, nullptr, 0}, + {"no-vipc", no_argument, nullptr, 0}, + {"all", no_argument, nullptr, 0}, + {"benchmark", no_argument, nullptr, 0}, + {"help", no_argument, nullptr, 'h'}, + {nullptr, 0, nullptr, 0}, // Terminating entry + }; - QCoreApplication app(argc, argv); - - const std::tuple flags[] = { - {"dcam", REPLAY_FLAG_DCAM, "load driver camera"}, - {"ecam", REPLAY_FLAG_ECAM, "load wide road camera"}, - {"no-loop", REPLAY_FLAG_NO_LOOP, "stop at the end of the route"}, - {"no-cache", REPLAY_FLAG_NO_FILE_CACHE, "turn off local cache"}, - {"qcam", REPLAY_FLAG_QCAMERA, "load qcamera"}, - {"no-hw-decoder", REPLAY_FLAG_NO_HW_DECODER, "disable HW video decoding"}, - {"no-vipc", REPLAY_FLAG_NO_VIPC, "do not output video"}, - {"all", REPLAY_FLAG_ALL_SERVICES, "do output all messages including uiDebug, userFlag" - ". this may causes issues when used along with UI"} + const std::map flag_map = { + {"dcam", REPLAY_FLAG_DCAM}, + {"ecam", REPLAY_FLAG_ECAM}, + {"no-loop", REPLAY_FLAG_NO_LOOP}, + {"no-cache", REPLAY_FLAG_NO_FILE_CACHE}, + {"qcam", REPLAY_FLAG_QCAMERA}, + {"no-hw-decoder", REPLAY_FLAG_NO_HW_DECODER}, + {"no-vipc", REPLAY_FLAG_NO_VIPC}, + {"all", REPLAY_FLAG_ALL_SERVICES}, + {"benchmark", REPLAY_FLAG_BENCHMARK}, }; - QCommandLineParser parser; - parser.setApplicationDescription("Mock openpilot components by publishing logged messages."); - parser.addHelpOption(); - parser.addPositionalArgument("route", "the drive to replay. find your drives at connect.comma.ai"); - parser.addOption({{"a", "allow"}, "whitelist of services to send", "allow"}); - parser.addOption({{"b", "block"}, "blacklist of services to send", "block"}); - parser.addOption({{"c", "cache"}, "cache segments in memory. default is 5", "n"}); - parser.addOption({{"s", "start"}, "start from ", "seconds"}); - parser.addOption({"x", QString("playback . between %1 - %2") - .arg(ConsoleUI::speed_array.front()).arg(ConsoleUI::speed_array.back()), "speed"}); - parser.addOption({"demo", "use a demo route instead of providing your own"}); - parser.addOption({"data_dir", "local directory with routes", "data_dir"}); - parser.addOption({"prefix", "set OPENPILOT_PREFIX", "prefix"}); - for (auto &[name, _, desc] : flags) { - parser.addOption({name, desc}); + if (argc == 1) { + std::cout << helpText; + return false; } - parser.process(app); - const QStringList args = parser.positionalArguments(); - if (args.empty() && !parser.isSet("demo")) { - parser.showHelp(); + int opt, option_index = 0; + while ((opt = getopt_long(argc, argv, "a:b:c:s:x:d:p:h", cli_options, &option_index)) != -1) { + switch (opt) { + case 'a': config.allow = split(optarg, ','); break; + case 'b': config.block = split(optarg, ','); break; + case 'c': config.cache_segments = std::atoi(optarg); break; + case 's': config.start_seconds = std::atoi(optarg); break; + case 'x': config.playback_speed = std::atof(optarg); break; + case 'd': config.data_dir = optarg; break; + case 'p': config.prefix = optarg; break; + case 0: { + std::string name = cli_options[option_index].name; + if (name == "demo") config.route = DEMO_ROUTE; + else if (name == "auto") config.auto_source = true; + else config.flags |= flag_map.at(name); + break; + } + case 'h': std::cout << helpText; return false; + default: return false; + } } - const QString route = args.empty() ? DEMO_ROUTE : args.first(); - QStringList allow = parser.value("allow").isEmpty() ? QStringList{} : parser.value("allow").split(","); - QStringList block = parser.value("block").isEmpty() ? QStringList{} : parser.value("block").split(","); + // Check for a route name (first positional argument) + if (config.route.empty() && optind < argc) { + config.route = argv[optind]; + } - uint32_t replay_flags = REPLAY_FLAG_NONE; - for (const auto &[name, flag, _] : flags) { - if (parser.isSet(name)) { - replay_flags |= flag; - } + if (config.route.empty()) { + std::cerr << "No route provided. Use --help for usage information.\n"; + return false; + } + + return true; +} + +int main(int argc, char *argv[]) { +#ifdef __APPLE__ + // With all sockets opened, we might hit the default limit of 256 on macOS + util::set_file_descriptor_limit(1024); +#endif + + // The vendored ncurses static library has a wrong compiled-in terminfo path. + // Point it at the system terminfo database if not already set. + setenv("TERMINFO_DIRS", "/usr/share/terminfo:/lib/terminfo:/usr/lib/terminfo", 0); + + ReplayConfig config; + + if (!parseArgs(argc, argv, config)) { + return 1; } std::unique_ptr op_prefix; - auto prefix = parser.value("prefix"); - if (!prefix.isEmpty()) { - op_prefix.reset(new OpenpilotPrefix(prefix.toStdString())); + if (!config.prefix.empty()) { + op_prefix = std::make_unique(config.prefix); } - Replay *replay = new Replay(route, allow, block, nullptr, replay_flags, parser.value("data_dir"), &app); - if (!parser.value("c").isEmpty()) { - replay->setSegmentCacheLimit(parser.value("c").toInt()); + Replay replay(config.route, config.allow, config.block, nullptr, config.flags, config.data_dir, config.auto_source); + if (config.cache_segments > 0) { + replay.setSegmentCacheLimit(config.cache_segments); } - if (!parser.value("x").isEmpty()) { - replay->setSpeed(std::clamp(parser.value("x").toFloat(), - ConsoleUI::speed_array.front(), ConsoleUI::speed_array.back())); + if (config.playback_speed > 0) { + replay.setSpeed(std::clamp(config.playback_speed, ConsoleUI::speed_array.front(), ConsoleUI::speed_array.back())); } - if (!replay->load()) { + if (!replay.load()) { + return 1; + } + + if (config.flags & REPLAY_FLAG_BENCHMARK) { + replay.start(config.start_seconds); + replay.waitForFinished(); + + const auto &stats = replay.getBenchmarkStats(); + uint64_t process_start = stats.process_start_ts; + + std::cout << "\n===== REPLAY BENCHMARK RESULTS =====\n"; + std::cout << "Route: " << replay.route().name() << "\n\n"; + + std::cout << "TIMELINE:\n"; + std::cout << " t=0 ms process start\n"; + for (const auto &[ts, event] : stats.timeline) { + double ms = (ts - process_start) / 1e6; + std::cout << " t=" << std::fixed << std::setprecision(0) << ms << " ms" + << std::string(std::max(1, 8 - static_cast(std::to_string(static_cast(ms)).length())), ' ') + << event << "\n"; + } + return 0; } - ConsoleUI console_ui(replay); - replay->start(parser.value("start").toInt()); - return app.exec(); + ConsoleUI console_ui(&replay); + replay.start(config.start_seconds); + return console_ui.exec(); } diff --git a/tools/replay/py_downloader.cc b/tools/replay/py_downloader.cc new file mode 100644 index 00000000000000..d27a77e6ee353b --- /dev/null +++ b/tools/replay/py_downloader.cc @@ -0,0 +1,180 @@ +#include "tools/replay/py_downloader.h" + +#include +#include +#include +#include +#include +#include + +#include "tools/replay/util.h" + +namespace { + +static std::mutex handler_mutex; +static DownloadProgressHandler progress_handler = nullptr; + +// Run a Python command and capture stdout. Stderr is left attached to the parent. +// Returns stdout content. If abort is signaled, kills the child process. +std::string runPython(const std::vector &args, std::atomic *abort = nullptr) { + // Build argv for execvp + std::vector argv; + argv.push_back("python3"); + argv.push_back("-m"); + argv.push_back("openpilot.tools.lib.file_downloader"); + for (const auto &a : args) { + argv.push_back(a.c_str()); + } + argv.push_back(nullptr); + + int stdout_pipe[2]; + if (pipe(stdout_pipe) != 0) { + rWarning("py_downloader: pipe() failed"); + return {}; + } + + pid_t pid = fork(); + if (pid < 0) { + rWarning("py_downloader: fork() failed"); + close(stdout_pipe[0]); close(stdout_pipe[1]); + return {}; + } + + if (pid == 0) { + // Child process — detach from controlling terminal so Python + // cannot corrupt terminal settings needed by ncurses in the parent. + setsid(); + int devnull = open("/dev/null", O_RDONLY); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + if (devnull > STDERR_FILENO) close(devnull); + } + + // Clear OPENPILOT_PREFIX so the Python process uses default paths + // (e.g. ~/.comma/auth.json). The prefix is only for IPC in the parent. + unsetenv("OPENPILOT_PREFIX"); + + close(stdout_pipe[0]); + dup2(stdout_pipe[1], STDOUT_FILENO); + close(stdout_pipe[1]); + + execvp("python3", const_cast(argv.data())); + _exit(127); + } + + // Parent process + close(stdout_pipe[1]); + + std::string stdout_data; + char buf[4096]; + + // Use select() so abort can interrupt while waiting for Python output. + fd_set rfds; + bool stdout_open = true; + + while (stdout_open) { + if (abort && *abort) { + kill(pid, SIGTERM); + break; + } + + FD_ZERO(&rfds); + FD_SET(stdout_pipe[0], &rfds); + + struct timeval tv = {0, 100000}; // 100ms timeout + int ret = select(stdout_pipe[0] + 1, &rfds, nullptr, nullptr, &tv); + if (ret < 0) break; + + if (FD_ISSET(stdout_pipe[0], &rfds)) { + ssize_t n = read(stdout_pipe[0], buf, sizeof(buf)); + if (n <= 0) { + stdout_open = false; + } else { + stdout_data.append(buf, n); + } + } + } + + // Drain remaining pipe data to prevent child from blocking on write + while (true) { + ssize_t n = read(stdout_pipe[0], buf, sizeof(buf)); + if (n <= 0) break; + stdout_data.append(buf, n); + } + close(stdout_pipe[0]); + + int status; + waitpid(pid, &status, 0); + + const bool aborted = abort && *abort; + const bool expected_sigterm = aborted && WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM; + bool failed = aborted || + (WIFEXITED(status) && WEXITSTATUS(status) != 0) || + WIFSIGNALED(status); + if (failed) { + if (expected_sigterm) { + // Route/camera teardown cancels outstanding downloader subprocesses. + // Keep that expected shutdown path quiet. + } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + rWarning("py_downloader: process exited with code %d", WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + rWarning("py_downloader: process killed by signal %d", WTERMSIG(status)); + } + std::lock_guard lk(handler_mutex); + if (progress_handler) { + progress_handler(0, 0, false); + } + return {}; + } + + // Trim trailing newline + while (!stdout_data.empty() && (stdout_data.back() == '\n' || stdout_data.back() == '\r')) { + stdout_data.pop_back(); + } + + return stdout_data; +} + +} // namespace + +void installDownloadProgressHandler(DownloadProgressHandler handler) { + std::lock_guard lk(handler_mutex); + progress_handler = handler; +} + +namespace PyDownloader { + +std::string download(const std::string &url, bool use_cache, std::atomic *abort) { + std::vector args = {"download", url}; + if (!use_cache) { + args.push_back("--no-cache"); + } + return runPython(args, abort); +} + +std::string getRouteFiles(const std::string &route) { + return runPython({"route-files", route}); +} + +std::string getDevices() { + return runPython({"devices"}); +} + +std::string getDeviceRoutes(const std::string &dongle_id, int64_t start_ms, int64_t end_ms, bool preserved) { + std::vector args = {"device-routes", dongle_id}; + if (preserved) { + args.push_back("--preserved"); + } else { + if (start_ms > 0) { + args.push_back("--start"); + args.push_back(std::to_string(start_ms)); + } + if (end_ms > 0) { + args.push_back("--end"); + args.push_back(std::to_string(end_ms)); + } + } + return runPython(args); +} + +} // namespace PyDownloader diff --git a/tools/replay/py_downloader.h b/tools/replay/py_downloader.h new file mode 100644 index 00000000000000..535189784c84aa --- /dev/null +++ b/tools/replay/py_downloader.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include + +typedef std::function DownloadProgressHandler; +void installDownloadProgressHandler(DownloadProgressHandler handler); + +namespace PyDownloader { + +// Downloads url to local cache, returns local file path. Reports progress via installDownloadProgressHandler. +std::string download(const std::string &url, bool use_cache = true, std::atomic *abort = nullptr); + +// Returns JSON string of route files (same format as /v1/route/.../files API) +std::string getRouteFiles(const std::string &route); + +// Returns JSON string of user's devices +std::string getDevices(); + +// Returns JSON string of device routes +std::string getDeviceRoutes(const std::string &dongle_id, int64_t start_ms = 0, int64_t end_ms = 0, bool preserved = false); + +} // namespace PyDownloader diff --git a/tools/replay/qcom_decoder.cc b/tools/replay/qcom_decoder.cc new file mode 100644 index 00000000000000..b7f04a063be3d9 --- /dev/null +++ b/tools/replay/qcom_decoder.cc @@ -0,0 +1,346 @@ +#include "qcom_decoder.h" + +#include +#include +#include + + +#include "common/swaglog.h" +#include "common/util.h" + +// echo "0xFFFF" > /sys/kernel/debug/msm_vidc/debug_level + +static void copyBuffer(VisionBuf *src_buf, VisionBuf *dst_buf) { + // Copy Y plane + memcpy(dst_buf->y, src_buf->y, src_buf->height * src_buf->stride); + // Copy UV plane + memcpy(dst_buf->uv, src_buf->uv, src_buf->height / 2 * src_buf->stride); +} + +static void request_buffers(int fd, v4l2_buf_type buf_type, unsigned int count) { + struct v4l2_requestbuffers reqbuf = { + .count = count, + .type = buf_type, + .memory = V4L2_MEMORY_USERPTR + }; + util::safe_ioctl(fd, VIDIOC_REQBUFS, &reqbuf, "VIDIOC_REQBUFS failed"); +} + +MsmVidc::~MsmVidc() { + if (fd > 0) { + close(fd); + } +} + +bool MsmVidc::init(const char* dev, size_t width, size_t height, uint64_t codec) { + LOG("Initializing msm_vidc device %s", dev); + this->w = width; + this->h = height; + this->fd = open(dev, O_RDWR, 0); + if (fd < 0) { + LOGE("failed to open video device %s", dev); + return false; + } + subscribeEvents(); + v4l2_buf_type out_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + setPlaneFormat(out_type, V4L2_PIX_FMT_HEVC); // Also allocates the output buffer + setFPS(FPS); + request_buffers(fd, out_type, OUTPUT_BUFFER_COUNT); + util::safe_ioctl(fd, VIDIOC_STREAMON, &out_type, "VIDIOC_STREAMON OUTPUT failed"); + restartCapture(); + setupPolling(); + + this->initialized = true; + return true; +} + +VisionBuf* MsmVidc::decodeFrame(AVPacket *pkt, VisionBuf *buf) { + assert(initialized && (pkt != nullptr) && (buf != nullptr)); + + this->frame_ready = false; + this->current_output_buf = buf; + bool sent_packet = false; + + while (!this->frame_ready) { + if (!sent_packet) { + int buf_index = getBufferUnlocked(); + if (buf_index >= 0) { + assert(buf_index < out_buf_cnt); + sendPacket(buf_index, pkt); + sent_packet = true; + } + } + + if (poll(pfd, nfds, -1) < 0) { + LOGE("poll() error: %d", errno); + return nullptr; + } + + if (VisionBuf* result = processEvents()) { + return result; + } + } + + return buf; +} + +VisionBuf* MsmVidc::processEvents() { + for (int idx = 0; idx < nfds; idx++) { + short revents = pfd[idx].revents; + if (!revents) continue; + + if (idx == ev[EV_VIDEO]) { + if (revents & (POLLIN | POLLRDNORM)) { + VisionBuf *result = handleCapture(); + if (result == this->current_output_buf) { + this->frame_ready = true; + } + } + if (revents & (POLLOUT | POLLWRNORM)) { + handleOutput(); + } + if (revents & POLLPRI) { + handleEvent(); + } + } else { + LOGE("Unexpected event on fd %d", pfd[idx].fd); + } + } + return nullptr; +} + +VisionBuf* MsmVidc::handleCapture() { + struct v4l2_buffer buf = {0}; + struct v4l2_plane planes[1] = {0}; + buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + buf.memory = V4L2_MEMORY_USERPTR; + buf.m.planes = planes; + buf.length = 1; + util::safe_ioctl(this->fd, VIDIOC_DQBUF, &buf, "VIDIOC_DQBUF CAPTURE failed"); + + if (this->reconfigure_pending || buf.m.planes[0].bytesused == 0) { + return nullptr; + } + + copyBuffer(&cap_bufs[buf.index], this->current_output_buf); + queueCaptureBuffer(buf.index); + return this->current_output_buf; +} + +bool MsmVidc::subscribeEvents() { + for (uint32_t event : subscriptions) { + struct v4l2_event_subscription sub = { .type = event}; + util::safe_ioctl(fd, VIDIOC_SUBSCRIBE_EVENT, &sub, "VIDIOC_SUBSCRIBE_EVENT failed"); + } + return true; +} + +bool MsmVidc::setPlaneFormat(enum v4l2_buf_type type, uint32_t fourcc) { + struct v4l2_format fmt = {.type = type}; + struct v4l2_pix_format_mplane *pix = &fmt.fmt.pix_mp; + *pix = { + .width = (__u32)this->w, + .height = (__u32)this->h, + .pixelformat = fourcc + }; + util::safe_ioctl(fd, VIDIOC_S_FMT, &fmt, "VIDIOC_S_FMT failed"); + if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + this->out_buf_size = pix->plane_fmt[0].sizeimage; + int ion_size = this->out_buf_size * OUTPUT_BUFFER_COUNT; // Output (input) buffers are ION buffer. + this->out_buf.allocate(ion_size); // mmap rw + for (int i = 0; i < OUTPUT_BUFFER_COUNT; i++) { + this->out_buf_off[i] = i * this->out_buf_size; + this->out_buf_addr[i] = (char *)this->out_buf.addr + this->out_buf_off[i]; + this->out_buf_flag[i] = false; + } + LOGD("Set output buffer size to %d, count %d, addr %p", this->out_buf_size, OUTPUT_BUFFER_COUNT, this->out_buf.addr); + } else if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { + request_buffers(this->fd, type, CAPTURE_BUFFER_COUNT); + util::safe_ioctl(fd, VIDIOC_G_FMT, &fmt, "VIDIOC_G_FMT failed"); + const __u32 y_size = pix->plane_fmt[0].sizeimage; + const __u32 y_stride = pix->plane_fmt[0].bytesperline; + for (int i = 0; i < CAPTURE_BUFFER_COUNT; i++) { + size_t uv_offset = (size_t)y_stride * pix->height; + size_t required = uv_offset + (y_stride * pix->height / 2); // enough for Y + UV. For linear NV12, UV plane starts at y_stride * height. + size_t alloc_size = std::max(y_size, required); + this->cap_bufs[i].allocate(alloc_size); + this->cap_bufs[i].init_yuv(pix->width, pix->height, y_stride, uv_offset); + } + LOGD("Set capture buffer size to %d, count %d, addr %p, extradata size %d", + pix->plane_fmt[0].sizeimage, CAPTURE_BUFFER_COUNT, this->cap_bufs[0].addr, pix->plane_fmt[1].sizeimage); + } + return true; +} + +bool MsmVidc::setFPS(uint32_t fps) { + struct v4l2_streamparm streamparam = { + .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, + }; + streamparam.parm.output.timeperframe = {1, fps}; + util::safe_ioctl(fd, VIDIOC_S_PARM, &streamparam, "VIDIOC_S_PARM failed"); + return true; +} + +bool MsmVidc::restartCapture() { + // stop if already initialized + enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + if (this->initialized) { + LOGD("Restarting capture, flushing buffers..."); + util::safe_ioctl(this->fd, VIDIOC_STREAMOFF, &type, "VIDIOC_STREAMOFF CAPTURE failed"); + struct v4l2_requestbuffers reqbuf = {.type = type, .memory = V4L2_MEMORY_USERPTR}; + util::safe_ioctl(this->fd, VIDIOC_REQBUFS, &reqbuf, "VIDIOC_REQBUFS failed"); + for (size_t i = 0; i < CAPTURE_BUFFER_COUNT; ++i) { + this->cap_bufs[i].free(); + this->cap_buf_flag[i] = false; // mark as not queued + cap_bufs[i].~VisionBuf(); + new (&cap_bufs[i]) VisionBuf(); + } + } + // setup, start and queue capture buffers + setDBP(); + setPlaneFormat(type, V4L2_PIX_FMT_NV12); + util::safe_ioctl(this->fd, VIDIOC_STREAMON, &type, "VIDIOC_STREAMON CAPTURE failed"); + for (size_t i = 0; i < CAPTURE_BUFFER_COUNT; ++i) { + queueCaptureBuffer(i); + } + + return true; +} + +bool MsmVidc::queueCaptureBuffer(int i) { + struct v4l2_buffer buf = {0}; + struct v4l2_plane planes[1] = {0}; + + buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + buf.memory = V4L2_MEMORY_USERPTR; + buf.index = i; + buf.m.planes = planes; + buf.length = 1; + // decoded frame plane + planes[0].m.userptr = (unsigned long)this->cap_bufs[i].addr; // no security + planes[0].length = this->cap_bufs[i].len; + planes[0].reserved[0] = this->cap_bufs[i].fd; // ION fd + planes[0].reserved[1] = 0; + planes[0].bytesused = this->cap_bufs[i].len; + planes[0].data_offset = 0; + util::safe_ioctl(this->fd, VIDIOC_QBUF, &buf, "VIDIOC_QBUF failed"); + this->cap_buf_flag[i] = true; // mark as queued + return true; +} + +bool MsmVidc::queueOutputBuffer(int i, size_t size) { + struct v4l2_buffer buf = {0}; + struct v4l2_plane planes[1] = {0}; + + buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + buf.memory = V4L2_MEMORY_USERPTR; + buf.index = i; + buf.m.planes = planes; + buf.length = 1; + // decoded frame plane + planes[0].m.userptr = (unsigned long)this->out_buf_off[i]; // check this + planes[0].length = this->out_buf_size; + planes[0].reserved[0] = this->out_buf.fd; // ION fd + planes[0].reserved[1] = 0; + planes[0].bytesused = size; + planes[0].data_offset = 0; + assert((this->out_buf_off[i] & 0xfff) == 0); // must be 4 KiB aligned + assert(this->out_buf_size % 4096 == 0); // ditto for size + + util::safe_ioctl(this->fd, VIDIOC_QBUF, &buf, "VIDIOC_QBUF failed"); + this->out_buf_flag[i] = true; // mark as queued + return true; +} + +bool MsmVidc::setDBP() { + struct v4l2_ext_control control[2] = {0}; + struct v4l2_ext_controls controls = {0}; + control[0].id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE; + control[0].value = 1; // V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY + control[1].id = V4L2_CID_MPEG_VIDC_VIDEO_DPB_COLOR_FORMAT; + control[1].value = 0; // V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_NONE + controls.count = 2; + controls.ctrl_class = V4L2_CTRL_CLASS_MPEG; + controls.controls = control; + util::safe_ioctl(fd, VIDIOC_S_EXT_CTRLS, &controls, "VIDIOC_S_EXT_CTRLS failed"); + return true; +} + +bool MsmVidc::setupPolling() { + // Initialize poll array + pfd[EV_VIDEO] = {fd, POLLIN | POLLOUT | POLLWRNORM | POLLRDNORM | POLLPRI, 0}; + ev[EV_VIDEO] = EV_VIDEO; + nfds = 1; + return true; +} + +bool MsmVidc::sendPacket(int buf_index, AVPacket *pkt) { + assert(buf_index >= 0 && buf_index < out_buf_cnt); + assert(pkt != nullptr && pkt->data != nullptr && pkt->size > 0); + // Prepare output buffer + memset(this->out_buf_addr[buf_index], 0, this->out_buf_size); + uint8_t * data = (uint8_t *)this->out_buf_addr[buf_index]; + memcpy(data, pkt->data, pkt->size); + queueOutputBuffer(buf_index, pkt->size); + return true; +} + +int MsmVidc::getBufferUnlocked() { + for (int i = 0; i < this->out_buf_cnt; i++) { + if (!out_buf_flag[i]) { + return i; + } + } + return -1; +} + + +bool MsmVidc::handleOutput() { + struct v4l2_buffer buf = {0}; + struct v4l2_plane planes[1]; + buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + buf.memory = V4L2_MEMORY_USERPTR; + buf.m.planes = planes; + buf.length = 1; + util::safe_ioctl(this->fd, VIDIOC_DQBUF, &buf, "VIDIOC_DQBUF OUTPUT failed"); + this->out_buf_flag[buf.index] = false; // mark as not queued + return true; +} + +bool MsmVidc::handleEvent() { + // dequeue event + struct v4l2_event event = {0}; + util::safe_ioctl(this->fd, VIDIOC_DQEVENT, &event, "VIDIOC_DQEVENT failed"); + switch (event.type) { + case V4L2_EVENT_MSM_VIDC_PORT_SETTINGS_CHANGED_INSUFFICIENT: { + unsigned int *ptr = (unsigned int *)event.u.data; + unsigned int height = ptr[0]; + unsigned int width = ptr[1]; + this->w = width; + this->h = height; + LOGD("Port Reconfig received insufficient, new size %ux%u, flushing capture bufs...", width, height); // This is normal + struct v4l2_decoder_cmd dec; + dec.flags = V4L2_QCOM_CMD_FLUSH_CAPTURE; + dec.cmd = V4L2_QCOM_CMD_FLUSH; + util::safe_ioctl(this->fd, VIDIOC_DECODER_CMD, &dec, "VIDIOC_DECODER_CMD FLUSH_CAPTURE failed"); + this->reconfigure_pending = true; + LOGD("Waiting for flush done event to reconfigure capture queue"); + break; + } + + case V4L2_EVENT_MSM_VIDC_FLUSH_DONE: { + unsigned int *ptr = (unsigned int *)event.u.data; + unsigned int flags = ptr[0]; + if (flags & V4L2_QCOM_CMD_FLUSH_CAPTURE) { + if (this->reconfigure_pending) { + this->restartCapture(); + this->reconfigure_pending = false; + } + } + break; + } + default: + break; + } + return true; +} diff --git a/tools/replay/qcom_decoder.h b/tools/replay/qcom_decoder.h new file mode 100644 index 00000000000000..1d7522cc70e693 --- /dev/null +++ b/tools/replay/qcom_decoder.h @@ -0,0 +1,88 @@ +#pragma once + +#include +#include + +#include "msgq/visionipc/visionbuf.h" + +extern "C" { + #include + #include +} + +#define V4L2_EVENT_MSM_VIDC_START (V4L2_EVENT_PRIVATE_START + 0x00001000) +#define V4L2_EVENT_MSM_VIDC_FLUSH_DONE (V4L2_EVENT_MSM_VIDC_START + 1) +#define V4L2_EVENT_MSM_VIDC_PORT_SETTINGS_CHANGED_INSUFFICIENT (V4L2_EVENT_MSM_VIDC_START + 3) +#define V4L2_CID_MPEG_MSM_VIDC_BASE 0x00992000 +#define V4L2_CID_MPEG_VIDC_VIDEO_DPB_COLOR_FORMAT (V4L2_CID_MPEG_MSM_VIDC_BASE + 44) +#define V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE (V4L2_CID_MPEG_MSM_VIDC_BASE + 22) +#define V4L2_QCOM_CMD_FLUSH_CAPTURE (1 << 1) +#define V4L2_QCOM_CMD_FLUSH (4) + +#define VIDEO_DEVICE "/dev/video32" +#define OUTPUT_BUFFER_COUNT 8 +#define CAPTURE_BUFFER_COUNT 8 +#define FPS 20 + + +class MsmVidc { +public: + MsmVidc() = default; + ~MsmVidc(); + + bool init(const char* dev, size_t width, size_t height, uint64_t codec); + VisionBuf* decodeFrame(AVPacket* pkt, VisionBuf* buf); + + AVFormatContext* avctx = nullptr; + int fd = 0; + +private: + bool initialized = false; + bool reconfigure_pending = false; + bool frame_ready = false; + + VisionBuf* current_output_buf = nullptr; + VisionBuf out_buf; // Single input buffer + VisionBuf cap_bufs[CAPTURE_BUFFER_COUNT]; // Capture (output) buffers + + size_t w = 1928, h = 1208; + size_t cap_height = 0, cap_width = 0; + + int cap_buf_size = 0; + int out_buf_size = 0; + + size_t cap_plane_off[CAPTURE_BUFFER_COUNT] = {0}; + size_t cap_plane_stride[CAPTURE_BUFFER_COUNT] = {0}; + bool cap_buf_flag[CAPTURE_BUFFER_COUNT] = {false}; + + size_t out_buf_off[OUTPUT_BUFFER_COUNT] = {0}; + void* out_buf_addr[OUTPUT_BUFFER_COUNT] = {0}; + bool out_buf_flag[OUTPUT_BUFFER_COUNT] = {false}; + const int out_buf_cnt = OUTPUT_BUFFER_COUNT; + + const int subscriptions[2] = { + V4L2_EVENT_MSM_VIDC_FLUSH_DONE, + V4L2_EVENT_MSM_VIDC_PORT_SETTINGS_CHANGED_INSUFFICIENT + }; + + enum { EV_VIDEO, EV_COUNT }; + struct pollfd pfd[EV_COUNT] = {0}; + int ev[EV_COUNT] = {-1}; + int nfds = 0; + + VisionBuf* processEvents(); + bool setupOutput(); + bool subscribeEvents(); + bool setPlaneFormat(v4l2_buf_type type, uint32_t fourcc); + bool setFPS(uint32_t fps); + bool restartCapture(); + bool queueCaptureBuffer(int i); + bool queueOutputBuffer(int i, size_t size); + bool setDBP(); + bool setupPolling(); + bool sendPacket(int buf_index, AVPacket* pkt); + int getBufferUnlocked(); + VisionBuf* handleCapture(); + bool handleOutput(); + bool handleEvent(); +}; diff --git a/tools/replay/replay.cc b/tools/replay/replay.cc index 34dd33bc1a477d..d8d59e41a43578 100644 --- a/tools/replay/replay.cc +++ b/tools/replay/replay.cc @@ -1,364 +1,191 @@ #include "tools/replay/replay.h" -#include -#include #include #include +#include +#include #include "cereal/services.h" #include "common/params.h" -#include "common/timing.h" #include "tools/replay/util.h" static void interrupt_sleep_handler(int signal) {} -Replay::Replay(QString route, QStringList allow, QStringList block, SubMaster *sm_, - uint32_t flags, QString data_dir, QObject *parent) : sm(sm_), flags_(flags), QObject(parent) { - // Register signal handler for SIGUSR1 +// Helper function to notify events with safety checks +template +void notifyEvent(Callback &callback, Args &&...args) { + if (callback) callback(std::forward(args)...); +} + +Replay::Replay(const std::string &route, std::vector allow, std::vector block, + SubMaster *sm, uint32_t flags, const std::string &data_dir, bool auto_source) + : sm_(sm), flags_(flags), seg_mgr_(std::make_unique(route, flags, data_dir, auto_source)) { std::signal(SIGUSR1, interrupt_sleep_handler); + if (flags_ & REPLAY_FLAG_BENCHMARK) { + benchmark_stats_.process_start_ts = nanos_since_boot(); + seg_mgr_->setBenchmarkCallback([this](int seg_num, const std::string& event) { + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), + "segment " + std::to_string(seg_num) + " " + event); + }); + } + if (!(flags_ & REPLAY_FLAG_ALL_SERVICES)) { - block << "uiDebug" << "userFlag"; + block.insert(block.end(), {"bookmarkButton", "uiDebug", "userBookmark"}); } - auto event_struct = capnp::Schema::from().asStruct(); - sockets_.resize(event_struct.getUnionFields().size()); + setupServices(allow, block); + setupSegmentManager(!allow.empty() || !block.empty()); +} + +void Replay::setupServices(const std::vector &allow, const std::vector &block) { + auto event_schema = capnp::Schema::from().asStruct(); + sockets_.resize(event_schema.getUnionFields().size(), nullptr); + + std::vector active_services; + active_services.reserve(services.size()); + for (const auto &[name, _] : services) { - if (!block.contains(name.c_str()) && (allow.empty() || allow.contains(name.c_str()))) { - uint16_t which = event_struct.getFieldByName(name).getProto().getDiscriminantValue(); + bool is_blocked = std::find(block.begin(), block.end(), name) != block.end(); + bool is_allowed = allow.empty() || std::find(allow.begin(), allow.end(), name) != allow.end(); + if (is_allowed && !is_blocked) { + uint16_t which = event_schema.getFieldByName(name).getProto().getDiscriminantValue(); sockets_[which] = name.c_str(); + active_services.push_back(name.c_str()); } } - if (!allow.isEmpty()) { - for (int i = 0; i < sockets_.size(); ++i) { - filters_.push_back(i == cereal::Event::Which::INIT_DATA || i == cereal::Event::Which::CAR_PARAMS || sockets_[i]); - } + + std::string services_str = join(active_services, ", "); + rInfo("active services: %s", services_str.c_str()); + if (!sm_) { + pm_ = std::make_unique(active_services); } +} - std::vector s; - std::copy_if(sockets_.begin(), sockets_.end(), std::back_inserter(s), - [](const char *name) { return name != nullptr; }); - qDebug() << "services " << s; - qDebug() << "loading route " << route; +void Replay::setupSegmentManager(bool has_filters) { + seg_mgr_->setCallback([this]() { handleSegmentMerge(); }); - if (sm == nullptr) { - pm = std::make_unique(s); + if (has_filters) { + std::vector filters(sockets_.size(), false); + for (size_t i = 0; i < sockets_.size(); ++i) { + filters[i] = (i == cereal::Event::Which::INIT_DATA || i == cereal::Event::Which::CAR_PARAMS || sockets_[i]); + } + seg_mgr_->setFilters(filters); } - route_ = std::make_unique(route, data_dir); } Replay::~Replay() { - stop(); -} - -void Replay::stop() { - exit_ = true; - if (stream_thread_ != nullptr) { + if (stream_thread_.joinable()) { rInfo("shutdown: in progress..."); - pauseStreamThread(); - stream_cv_.notify_one(); - stream_thread_->quit(); - stream_thread_->wait(); - stream_thread_->deleteLater(); - stream_thread_ = nullptr; + interruptStream([this]() { + exit_ = true; + return false; + }); + stream_thread_.join(); rInfo("shutdown: done"); } - timeline_future.waitForFinished(); - camera_server_.reset(nullptr); - segments_.clear(); + camera_server_.reset(); + seg_mgr_.reset(); } bool Replay::load() { - if (!route_->load()) { - qCritical() << "failed to load route" << route_->name() - << "from" << (route_->dir().isEmpty() ? "server" : route_->dir()); - return false; - } + rInfo("loading route %s", seg_mgr_->route_.name().c_str()); - for (auto &[n, f] : route_->segments()) { - bool has_log = !f.rlog.isEmpty() || !f.qlog.isEmpty(); - bool has_video = !f.road_cam.isEmpty() || !f.qcamera.isEmpty(); - if (has_log && (has_video || hasFlag(REPLAY_FLAG_NO_VIPC))) { - segments_.insert({n, nullptr}); - } - } - if (segments_.empty()) { - qCritical() << "no valid segments in route" << route_->name(); - return false; + if (!seg_mgr_->load()) return false; + + if (hasFlag(REPLAY_FLAG_BENCHMARK)) { + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), "route metadata loaded"); } - rInfo("load route %s with %zu valid segments", qPrintable(route_->name()), segments_.size()); - max_seconds_ = (segments_.rbegin()->first + 1) * 60; - return true; -} -void Replay::start(int seconds) { - seekTo(route_->identifier().begin_segment * 60 + seconds, false); + min_seconds_ = seg_mgr_->route_.segments().begin()->first * 60; + max_seconds_ = (seg_mgr_->route_.segments().rbegin()->first + 1) * 60; + return true; } -void Replay::updateEvents(const std::function &update_events_function) { - pauseStreamThread(); +void Replay::interruptStream(const std::function &update_fn) { + if (stream_thread_.joinable() && stream_thread_id) { + pthread_kill(stream_thread_id, SIGUSR1); // Interrupt sleep in stream thread + } { - std::unique_lock lk(stream_lock_); - events_ready_ = update_events_function(); - paused_ = user_paused_; + interrupt_requested_ = true; + std::unique_lock lock(stream_lock_); + events_ready_ = update_fn(); + interrupt_requested_ = user_paused_; } stream_cv_.notify_one(); } void Replay::seekTo(double seconds, bool relative) { - updateEvents([&]() { - double target_time = relative ? seconds + currentSeconds() : seconds; - target_time = std::max(double(0.0), target_time); - int target_segment = (int)target_time / 60; - if (segments_.count(target_segment) == 0) { - rWarning("Can't seek to %.2f s segment %d is invalid", target_time, target_segment); - return true; - } - if (target_time > max_seconds_) { - rWarning("Can't seek to %.2f s, time is invalid", target_time); - return true; - } + double target_time = relative ? seconds + currentSeconds() : seconds; + target_time = std::max(0.0, target_time); + int target_segment = target_time / 60; + if (!seg_mgr_->hasSegment(target_segment)) { + rWarning("Invalid seek to %.2f s (segment %d)", target_time, target_segment); + return; + } - rInfo("Seeking to %d s, segment %d", (int)target_time, target_segment); - current_segment_ = target_segment; + rInfo("Seeking to %d s, segment %d", (int)target_time, target_segment); + notifyEvent(onSeeking, target_time); + + interruptStream([&]() { + current_segment_.store(target_segment); cur_mono_time_ = route_start_ts_ + target_time * 1e9; - seeking_to_ = target_time; + cur_which_ = cereal::Event::Which::INIT_DATA; + seeking_to_.store(target_time, std::memory_order_relaxed); return false; }); + seg_mgr_->setCurrentSegment(target_segment); checkSeekProgress(); - updateSegmentsCache(); } void Replay::checkSeekProgress() { - if (seeking_to_) { - auto it = segments_.find(int(*seeking_to_ / 60)); - if (it != segments_.end() && it->second && it->second->isLoaded()) { - emit seekedTo(*seeking_to_); - seeking_to_ = std::nullopt; - // wake up stream thread - updateEvents([]() { return true; }); - } else { - // Emit signal indicating the ongoing seek operation - emit seeking(*seeking_to_); - } - } -} + if (!seg_mgr_->getEventData()->isSegmentLoaded(current_segment_.load())) return; -void Replay::seekToFlag(FindFlag flag) { - if (auto next = find(flag)) { - seekTo(*next - 2, false); // seek to 2 seconds before next + double seek_to = seeking_to_.exchange(-1.0, std::memory_order_acquire); + if (seek_to >= 0 && onSeekedTo) { + onSeekedTo(seek_to); } -} -void Replay::buildTimeline() { - uint64_t engaged_begin = 0; - bool engaged = false; - - auto alert_status = cereal::SelfdriveState::AlertStatus::NORMAL; - auto alert_size = cereal::SelfdriveState::AlertSize::NONE; - uint64_t alert_begin = 0; - std::string alert_type; - - const TimelineType timeline_types[] = { - [(int)cereal::SelfdriveState::AlertStatus::NORMAL] = TimelineType::AlertInfo, - [(int)cereal::SelfdriveState::AlertStatus::USER_PROMPT] = TimelineType::AlertWarning, - [(int)cereal::SelfdriveState::AlertStatus::CRITICAL] = TimelineType::AlertCritical, - }; - - const auto &route_segments = route_->segments(); - for (auto it = route_segments.cbegin(); it != route_segments.cend() && !exit_; ++it) { - std::shared_ptr log(new LogReader()); - if (!log->load(it->second.qlog.toStdString(), &exit_, !hasFlag(REPLAY_FLAG_NO_FILE_CACHE), 0, 3) || log->events.empty()) continue; - - std::vector> timeline; - for (const Event &e : log->events) { - if (e.which == cereal::Event::Which::SELFDRIVE_STATE) { - capnp::FlatArrayMessageReader reader(e.data); - auto event = reader.getRoot(); - auto cs = event.getSelfdriveState(); - - if (engaged != cs.getEnabled()) { - if (engaged) { - timeline.push_back({toSeconds(engaged_begin), toSeconds(e.mono_time), TimelineType::Engaged}); - } - engaged_begin = e.mono_time; - engaged = cs.getEnabled(); - } - - if (alert_type != cs.getAlertType().cStr() || alert_status != cs.getAlertStatus()) { - if (!alert_type.empty() && alert_size != cereal::SelfdriveState::AlertSize::NONE) { - timeline.push_back({toSeconds(alert_begin), toSeconds(e.mono_time), timeline_types[(int)alert_status]}); - } - alert_begin = e.mono_time; - alert_type = cs.getAlertType().cStr(); - alert_size = cs.getAlertSize(); - alert_status = cs.getAlertStatus(); - } - } else if (e.which == cereal::Event::Which::USER_FLAG) { - timeline.push_back({toSeconds(e.mono_time), toSeconds(e.mono_time), TimelineType::UserFlag}); - } - } - - if (it->first == route_segments.rbegin()->first) { - if (engaged) { - timeline.push_back({toSeconds(engaged_begin), toSeconds(log->events.back().mono_time), TimelineType::Engaged}); - } - if (!alert_type.empty() && alert_size != cereal::SelfdriveState::AlertSize::NONE) { - timeline.push_back({toSeconds(alert_begin), toSeconds(log->events.back().mono_time), timeline_types[(int)alert_status]}); - } - - max_seconds_ = std::ceil(toSeconds(log->events.back().mono_time)); - emit minMaxTimeChanged(route_segments.cbegin()->first * 60.0, max_seconds_); - } - { - std::lock_guard lk(timeline_lock); - timeline_.insert(timeline_.end(), timeline.begin(), timeline.end()); - std::sort(timeline_.begin(), timeline_.end(), [](auto &l, auto &r) { return std::get<2>(l) < std::get<2>(r); }); - } - emit qLogLoaded(log); - } + // Resume the interrupted stream + interruptStream([]() { return true; }); } -std::optional Replay::find(FindFlag flag) { - int cur_ts = currentSeconds(); - for (auto [start_ts, end_ts, type] : getTimeline()) { - if (type == TimelineType::Engaged) { - if (flag == FindFlag::nextEngagement && start_ts > cur_ts) { - return start_ts; - } else if (flag == FindFlag::nextDisEngagement && end_ts > cur_ts) { - return end_ts; - } - } else if (start_ts > cur_ts) { - if ((flag == FindFlag::nextUserFlag && type == TimelineType::UserFlag) || - (flag == FindFlag::nextInfo && type == TimelineType::AlertInfo) || - (flag == FindFlag::nextWarning && type == TimelineType::AlertWarning) || - (flag == FindFlag::nextCritical && type == TimelineType::AlertCritical)) { - return start_ts; - } - } +void Replay::seekToFlag(FindFlag flag) { + if (auto next = timeline_.find(currentSeconds(), flag)) { + seekTo(*next - 2, false); // seek to 2 seconds before next } - return std::nullopt; } void Replay::pause(bool pause) { if (user_paused_ != pause) { - pauseStreamThread(); - { - std::unique_lock lk(stream_lock_); + interruptStream([=]() { rWarning("%s at %.2f s", pause ? "paused..." : "resuming", currentSeconds()); - paused_ = user_paused_ = pause; - } - stream_cv_.notify_one(); - } -} - -void Replay::pauseStreamThread() { - paused_ = true; - // Send SIGUSR1 to interrupt clock_nanosleep - if (stream_thread_ && stream_thread_id) { - pthread_kill(stream_thread_id, SIGUSR1); - } -} - -void Replay::segmentLoadFinished(bool success) { - if (!success) { - Segment *seg = qobject_cast(sender()); - rWarning("failed to load segment %d, removing it from current replay list", seg->seg_num); - updateEvents([&]() { - segments_.erase(seg->seg_num); - return !segments_.empty(); + user_paused_ = pause; + return !pause; }); } - updateSegmentsCache(); } -void Replay::updateSegmentsCache() { - auto cur = segments_.lower_bound(current_segment_.load()); - if (cur == segments_.end()) return; - - // Calculate the range of segments to load - auto begin = std::prev(cur, std::min(segment_cache_limit / 2, std::distance(segments_.begin(), cur))); - auto end = std::next(begin, std::min(segment_cache_limit, std::distance(begin, segments_.end()))); - begin = std::prev(end, std::min(segment_cache_limit, std::distance(segments_.begin(), end))); - - loadSegmentInRange(begin, cur, end); - mergeSegments(begin, end); - - // free segments out of current semgnt window. - std::for_each(segments_.begin(), begin, [](auto &e) { e.second.reset(nullptr); }); - std::for_each(end, segments_.end(), [](auto &e) { e.second.reset(nullptr); }); - - // start stream thread - const auto &cur_segment = cur->second; - if (stream_thread_ == nullptr && cur_segment->isLoaded()) { - startStream(cur_segment.get()); - } -} - -void Replay::loadSegmentInRange(SegmentMap::iterator begin, SegmentMap::iterator cur, SegmentMap::iterator end) { - auto loadNextSegment = [this](auto first, auto last) { - auto it = std::find_if(first, last, [](const auto &seg_it) { return !seg_it.second || !seg_it.second->isLoaded(); }); - if (it != last && !it->second) { - rDebug("loading segment %d...", it->first); - it->second = std::make_unique(it->first, route_->at(it->first), flags_, filters_); - QObject::connect(it->second.get(), &Segment::loadFinished, this, &Replay::segmentLoadFinished); - return true; - } - return false; - }; - - // Try loading forward segments, then reverse segments - if (!loadNextSegment(cur, end)) { - loadNextSegment(std::make_reverse_iterator(cur), std::make_reverse_iterator(begin)); - } -} - -void Replay::mergeSegments(const SegmentMap::iterator &begin, const SegmentMap::iterator &end) { - std::set segments_to_merge; - size_t new_events_size = 0; - for (auto it = begin; it != end; ++it) { - if (it->second && it->second->isLoaded()) { - segments_to_merge.insert(it->first); - new_events_size += it->second->log->events.size(); - } - } - - if (segments_to_merge == merged_segments_) return; +void Replay::handleSegmentMerge() { + if (exit_) return; - rDebug("merge segments %s", std::accumulate(segments_to_merge.begin(), segments_to_merge.end(), std::string{}, - [](auto & a, int b) { return a + (a.empty() ? "" : ", ") + std::to_string(b); }).c_str()); - - std::vector new_events; - new_events.reserve(new_events_size); - - // Merge events from segments_to_merge into new_events - for (int n : segments_to_merge) { - size_t size = new_events.size(); - const auto &events = segments_.at(n)->log->events; - std::copy_if(events.begin(), events.end(), std::back_inserter(new_events), - [this](const Event &e) { return e.which < sockets_.size() && sockets_[e.which] != nullptr; }); - std::inplace_merge(new_events.begin(), new_events.begin() + size, new_events.end()); - } - - if (stream_thread_) { - emit segmentsMerged(); + auto event_data = seg_mgr_->getEventData(); + if (!stream_thread_.joinable() && !event_data->segments.empty()) { + startStream(event_data->segments.begin()->second); } + notifyEvent(onSegmentsMerged); - updateEvents([&]() { - events_.swap(new_events); - merged_segments_ = segments_to_merge; - // Wake up the stream thread if the current segment is loaded or invalid. - return !seeking_to_ && (isSegmentMerged(current_segment_) || (segments_.count(current_segment_) == 0)); - }); + // Interrupt the stream to handle segment merge + interruptStream([]() { return false; }); checkSeekProgress(); } -void Replay::startStream(const Segment *cur_segment) { - const auto &events = cur_segment->log->events; +void Replay::startStream(const std::shared_ptr segment) { + const auto &events = segment->log->events; route_start_ts_ = events.front().mono_time; cur_mono_time_ += route_start_ts_ - 1; // get datetime from INIT_DATA, fallback to datetime in the route name - route_date_time_ = route()->datetime(); + route_date_time_ = route().datetime(); auto it = std::find_if(events.cbegin(), events.cend(), [](const Event &e) { return e.which == cereal::Event::Which::INIT_DATA; }); if (it != events.cend()) { @@ -366,7 +193,7 @@ void Replay::startStream(const Segment *cur_segment) { auto event = reader.getRoot(); uint64_t wall_time = event.getInitData().getWallTimeNanos(); if (wall_time > 0) { - route_date_time_ = QDateTime::fromMSecsSinceEpoch(wall_time / 1e6); + route_date_time_ = wall_time / 1e6; } } @@ -376,6 +203,7 @@ void Replay::startStream(const Segment *cur_segment) { capnp::FlatArrayMessageReader reader(it->data); auto event = reader.getRoot(); car_fingerprint_ = event.getCarParams().getCarFingerprint(); + capnp::MallocMessageBuilder builder; builder.setRoot(event.getCarParams()); auto words = capnp::messageToFlatArray(builder); @@ -390,29 +218,25 @@ void Replay::startStream(const Segment *cur_segment) { if (!hasFlag(REPLAY_FLAG_NO_VIPC)) { std::pair camera_size[MAX_CAMERAS] = {}; for (auto type : ALL_CAMERAS) { - if (auto &fr = cur_segment->frames[type]) { + if (auto &fr = segment->frames[type]) { camera_size[type] = {fr->width, fr->height}; } } camera_server_ = std::make_unique(camera_size); } - emit segmentsMerged(); - // start stream thread - stream_thread_ = new QThread(); - QObject::connect(stream_thread_, &QThread::started, [=]() { streamThread(); }); - stream_thread_->start(); + timeline_.initialize(seg_mgr_->route_, route_start_ts_, !(flags_ & REPLAY_FLAG_NO_FILE_CACHE), + [this](std::shared_ptr log) { notifyEvent(onQLogLoaded, log); }); - timeline_future = QtConcurrent::run(this, &Replay::buildTimeline); - emit streamStarted(); + stream_thread_ = std::thread(&Replay::streamThread, this); } void Replay::publishMessage(const Event *e) { - if (event_filter && event_filter(e, filter_opaque)) return; + if (event_filter_ && event_filter_(e)) return; - if (sm == nullptr) { + if (!sm_) { auto bytes = e->data.asBytes(); - int ret = pm->send(sockets_[e->which], (capnp::byte *)bytes.begin(), bytes.size()); + int ret = pm_->send(sockets_[e->which], (capnp::byte *)bytes.begin(), bytes.size()); if (ret == -1) { rWarning("stop publishing %s due to multiple publishers error", sockets_[e->which]); sockets_[e->which] = nullptr; @@ -420,7 +244,7 @@ void Replay::publishMessage(const Event *e) { } else { capnp::FlatArrayMessageReader reader(e->data); auto event = reader.getRoot(); - sm->update_msgs(nanos_since_boot(), {{sockets_[e->which], event}}); + sm_->update_msgs(nanos_since_boot(), {{sockets_[e->which], event}}); } } @@ -436,9 +260,9 @@ void Replay::publishFrame(const Event *e) { if ((cam == DriverCam && !hasFlag(REPLAY_FLAG_DCAM)) || (cam == WideRoadCam && !hasFlag(REPLAY_FLAG_ECAM))) return; // Camera isdisabled - if (isSegmentMerged(e->eidx_segnum)) { - auto &segment = segments_.at(e->eidx_segnum); - if (auto &frame = segment->frames[cam]; frame) { + auto seg_it = event_data_->segments.find(e->eidx_segnum); + if (seg_it != event_data_->segments.end()) { + if (auto &frame = seg_it->second->frames[cam]; frame) { camera_server_->pushFrame(cam, frame.get(), e); } } @@ -446,60 +270,104 @@ void Replay::publishFrame(const Event *e) { void Replay::streamThread() { stream_thread_id = pthread_self(); - cereal::Event::Which cur_which = cereal::Event::Which::INIT_DATA; std::unique_lock lk(stream_lock_); + int last_processed_segment = -1; + uint64_t segment_start_time = 0; + bool streaming_started = false; + while (true) { - stream_cv_.wait(lk, [=]() { return exit_ || ( events_ready_ && !paused_); }); + stream_cv_.wait(lk, [this]() { return exit_ || (events_ready_ && !interrupt_requested_); }); + if (exit_) break; - Event event(cur_which, cur_mono_time_, {}); - auto first = std::upper_bound(events_.cbegin(), events_.cend(), event); - if (first == events_.cend()) { + event_data_ = seg_mgr_->getEventData(); + const auto &events = event_data_->events; + auto first = std::upper_bound(events.cbegin(), events.cend(), Event(cur_which_, cur_mono_time_, {})); + if (first == events.cend()) { rInfo("waiting for events..."); events_ready_ = false; continue; } - auto it = publishEvents(first, events_.cend()); + if (!streaming_started && hasFlag(REPLAY_FLAG_BENCHMARK)) { + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), "streaming started"); + streaming_started = true; + } + + auto it = publishEvents(first, events.cend(), last_processed_segment, segment_start_time); // Ensure frames are sent before unlocking to prevent race conditions if (camera_server_) { camera_server_->waitForSent(); } - if (it != events_.cend()) { - cur_which = it->which; - } else if (!hasFlag(REPLAY_FLAG_NO_LOOP)) { - // Check for loop end and restart if necessary - int last_segment = segments_.rbegin()->first; - if (current_segment_ >= last_segment && isSegmentMerged(last_segment)) { + if (it == events.cend() && !hasFlag(REPLAY_FLAG_NO_LOOP) && !hasFlag(REPLAY_FLAG_BENCHMARK)) { + int last_segment = seg_mgr_->route_.segments().rbegin()->first; + if (event_data_->isSegmentLoaded(last_segment)) { rInfo("reaches the end of route, restart from beginning"); - QMetaObject::invokeMethod(this, std::bind(&Replay::seekTo, this, minSeconds(), false), Qt::QueuedConnection); + stream_lock_.unlock(); + seekTo(minSeconds(), false); + stream_lock_.lock(); } + } else if (it == events.cend() && hasFlag(REPLAY_FLAG_BENCHMARK)) { + // Exit benchmark mode after first segment completes + exit_ = true; + break; } } + + if (hasFlag(REPLAY_FLAG_BENCHMARK)) { + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), "benchmark done"); + + { + std::unique_lock lock(benchmark_lock_); + benchmark_done_ = true; + } + benchmark_cv_.notify_one(); + } } std::vector::const_iterator Replay::publishEvents(std::vector::const_iterator first, - std::vector::const_iterator last) { + std::vector::const_iterator last, + int &last_processed_segment, + uint64_t &segment_start_time) { uint64_t evt_start_ts = cur_mono_time_; uint64_t loop_start_ts = nanos_since_boot(); double prev_replay_speed = speed_; - for (; !paused_ && first != last; ++first) { + for (; !interrupt_requested_ && first != last; ++first) { const Event &evt = *first; + int segment = toSeconds(evt.mono_time) / 60; + if (current_segment_.load(std::memory_order_relaxed) != segment) { + current_segment_.store(segment, std::memory_order_relaxed); + seg_mgr_->setCurrentSegment(segment); + } - if (current_segment_ != segment) { - current_segment_ = segment; - QMetaObject::invokeMethod(this, &Replay::updateSegmentsCache, Qt::QueuedConnection); + // Track segment completion for benchmark timeline + if (hasFlag(REPLAY_FLAG_BENCHMARK) && segment != last_processed_segment) { + if (last_processed_segment >= 0 && segment_start_time > 0) { + uint64_t processing_time_ns = nanos_since_boot() - segment_start_time; + double processing_time_ms = processing_time_ns / 1e6; + double realtime_factor = 60.0 / (processing_time_ns / 1e9); // 60s per segment + + std::ostringstream oss; + oss << "segment " << last_processed_segment << " done publishing (" + << std::fixed << std::setprecision(0) << processing_time_ms << " ms, " + << std::fixed << std::setprecision(0) << realtime_factor << "x realtime)"; + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), oss.str()); + } + segment_start_time = nanos_since_boot(); + last_processed_segment = segment; } - // Skip events if socket is not present + cur_mono_time_ = evt.mono_time; + cur_which_ = evt.which; + + // Skip events if socket is not present if (!sockets_[evt.which]) continue; - cur_mono_time_ = evt.mono_time; const uint64_t current_nanos = nanos_since_boot(); const int64_t time_diff = (evt.mono_time - evt_start_ts) / speed_ - (current_nanos - loop_start_ts); @@ -510,11 +378,12 @@ std::vector::const_iterator Replay::publishEvents(std::vector::con evt_start_ts = evt.mono_time; loop_start_ts = current_nanos; prev_replay_speed = speed_; - } else if (time_diff > 0) { - precise_nano_sleep(time_diff, paused_); + } else if (time_diff > 0 && !hasFlag(REPLAY_FLAG_BENCHMARK)) { + // Skip sleep in benchmark mode for maximum throughput + precise_nano_sleep(time_diff, interrupt_requested_); } - if (paused_) break; + if (interrupt_requested_) break; if (evt.eidx_segnum == -1) { publishMessage(&evt); @@ -528,3 +397,12 @@ std::vector::const_iterator Replay::publishEvents(std::vector::con return first; } + +void Replay::waitForFinished() { + if (!hasFlag(REPLAY_FLAG_BENCHMARK)) { + return; + } + + std::unique_lock lock(benchmark_lock_); + benchmark_cv_.wait(lock, [this]() { return benchmark_done_; }); +} diff --git a/tools/replay/replay.h b/tools/replay/replay.h index ac829ffb71b752..3e2bc7c00e8641 100644 --- a/tools/replay/replay.h +++ b/tools/replay/replay.h @@ -1,24 +1,18 @@ #pragma once #include -#include +#include #include +#include #include -#include #include -#include #include -#include - -#include #include "tools/replay/camera.h" -#include "tools/replay/route.h" - -const QString DEMO_ROUTE = "a2a0ccea32023010|2023-07-27--13-01-19"; +#include "tools/replay/seg_mgr.h" +#include "tools/replay/timeline.h" -// one segment uses about 100M of memory -constexpr int MIN_SEGMENTS_CACHE = 5; +#define DEMO_ROUTE "5beb9b58bd12b691/0000010a--a51155e496" enum REPLAY_FLAGS { REPLAY_FLAG_NONE = 0x0000, @@ -30,129 +24,102 @@ enum REPLAY_FLAGS { REPLAY_FLAG_NO_HW_DECODER = 0x0100, REPLAY_FLAG_NO_VIPC = 0x0400, REPLAY_FLAG_ALL_SERVICES = 0x0800, + REPLAY_FLAG_BENCHMARK = 0x1000, }; -enum class FindFlag { - nextEngagement, - nextDisEngagement, - nextUserFlag, - nextInfo, - nextWarning, - nextCritical +struct BenchmarkStats { + uint64_t process_start_ts = 0; + std::vector> timeline; }; -enum class TimelineType { None, Engaged, AlertInfo, AlertWarning, AlertCritical, UserFlag }; -typedef bool (*replayEventFilter)(const Event *, void *); -Q_DECLARE_METATYPE(std::shared_ptr); - -class Replay : public QObject { - Q_OBJECT - +class Replay { public: - Replay(QString route, QStringList allow, QStringList block, SubMaster *sm = nullptr, - uint32_t flags = REPLAY_FLAG_NONE, QString data_dir = "", QObject *parent = 0); + Replay(const std::string &route, std::vector allow, std::vector block, SubMaster *sm = nullptr, + uint32_t flags = REPLAY_FLAG_NONE, const std::string &data_dir = "", bool auto_source = false); ~Replay(); bool load(); - RouteLoadError lastRouteError() const { return route_->lastError(); } - void start(int seconds = 0); - void stop(); + RouteLoadError lastRouteError() const { return route().lastError(); } + void start(int seconds = 0) { seekTo(min_seconds_ + seconds, false); } void pause(bool pause); void seekToFlag(FindFlag flag); void seekTo(double seconds, bool relative); inline bool isPaused() const { return user_paused_; } - // the filter is called in streaming thread.try to return quickly from it to avoid blocking streaming. - // the filter function must return true if the event should be filtered. - // otherwise it must return false. - inline void installEventFilter(replayEventFilter filter, void *opaque) { - filter_opaque = opaque; - event_filter = filter; - } - inline int segmentCacheLimit() const { return segment_cache_limit; } - inline void setSegmentCacheLimit(int n) { segment_cache_limit = std::max(MIN_SEGMENTS_CACHE, n); } + inline int segmentCacheLimit() const { return seg_mgr_->segment_cache_limit_; } + inline void setSegmentCacheLimit(int n) { seg_mgr_->segment_cache_limit_ = std::max(MIN_SEGMENTS_CACHE, n); } inline bool hasFlag(REPLAY_FLAGS flag) const { return flags_ & flag; } - inline void addFlag(REPLAY_FLAGS flag) { flags_ |= flag; } - inline void removeFlag(REPLAY_FLAGS flag) { flags_ &= ~flag; } - inline const Route* route() const { return route_.get(); } + void setLoop(bool loop) { loop ? flags_ &= ~REPLAY_FLAG_NO_LOOP : flags_ |= REPLAY_FLAG_NO_LOOP; } + bool loop() const { return !(flags_ & REPLAY_FLAG_NO_LOOP); } + const Route &route() const { return seg_mgr_->route_; } inline double currentSeconds() const { return double(cur_mono_time_ - route_start_ts_) / 1e9; } - inline QDateTime routeDateTime() const { return route_date_time_; } - inline QDateTime currentDateTime() const { return route_date_time_.addSecs(currentSeconds()); } + inline std::time_t routeDateTime() const { return route_date_time_; } inline uint64_t routeStartNanos() const { return route_start_ts_; } inline double toSeconds(uint64_t mono_time) const { return (mono_time - route_start_ts_) / 1e9; } - inline double minSeconds() const { return !segments_.empty() ? segments_.begin()->first * 60 : 0; } + inline double minSeconds() const { return min_seconds_; } inline double maxSeconds() const { return max_seconds_; } inline void setSpeed(float speed) { speed_ = speed; } inline float getSpeed() const { return speed_; } - inline const std::vector *events() const { return &events_; } - inline const std::map> &segments() const { return segments_; } inline const std::string &carFingerprint() const { return car_fingerprint_; } - inline const std::vector> getTimeline() { - std::lock_guard lk(timeline_lock); - return timeline_; - } - -signals: - void streamStarted(); - void segmentsMerged(); - void seeking(double sec); - void seekedTo(double sec); - void qLogLoaded(std::shared_ptr qlog); - void minMaxTimeChanged(double min_sec, double max_sec); - -protected slots: - void segmentLoadFinished(bool success); - -protected: - typedef std::map> SegmentMap; - std::optional find(FindFlag flag); - void pauseStreamThread(); - void startStream(const Segment *cur_segment); + inline const std::shared_ptr> getTimeline() const { return timeline_.getEntries(); } + inline const std::optional findAlertAtTime(double sec) const { return timeline_.findAlertAtTime(sec); } + const std::shared_ptr getEventData() const { return seg_mgr_->getEventData(); } + void installEventFilter(std::function filter) { event_filter_ = filter; } + void waitForFinished(); + const BenchmarkStats &getBenchmarkStats() const { return benchmark_stats_; } + + // Event callback functions + std::function onSegmentsMerged = nullptr; + std::function onSeeking = nullptr; + std::function onSeekedTo = nullptr; + std::function)> onQLogLoaded = nullptr; + +private: + void setupServices(const std::vector &allow, const std::vector &block); + void setupSegmentManager(bool has_filters); + void startStream(const std::shared_ptr segment); void streamThread(); - void updateSegmentsCache(); - void loadSegmentInRange(SegmentMap::iterator begin, SegmentMap::iterator cur, SegmentMap::iterator end); - void mergeSegments(const SegmentMap::iterator &begin, const SegmentMap::iterator &end); - void updateEvents(const std::function& update_events_function); + void handleSegmentMerge(); + void interruptStream(const std::function& update_fn); std::vector::const_iterator publishEvents(std::vector::const_iterator first, - std::vector::const_iterator last); + std::vector::const_iterator last, + int &last_processed_segment, + uint64_t &segment_start_time); void publishMessage(const Event *e); void publishFrame(const Event *e); - void buildTimeline(); void checkSeekProgress(); - inline bool isSegmentMerged(int n) const { return merged_segments_.count(n) > 0; } + + std::unique_ptr seg_mgr_; + Timeline timeline_; pthread_t stream_thread_id = 0; - QThread *stream_thread_ = nullptr; + std::thread stream_thread_; std::mutex stream_lock_; bool user_paused_ = false; std::condition_variable stream_cv_; std::atomic current_segment_ = 0; - std::optional seeking_to_; - SegmentMap segments_; - // the following variables must be protected with stream_lock_ + std::atomic seeking_to_ = -1.0; std::atomic exit_ = false; - std::atomic paused_ = false; + std::atomic interrupt_requested_ = false; bool events_ready_ = false; - QDateTime route_date_time_; + std::time_t route_date_time_; uint64_t route_start_ts_ = 0; std::atomic cur_mono_time_ = 0; - std::atomic max_seconds_ = 0; - std::vector events_; - std::set merged_segments_; - - // messaging - SubMaster *sm = nullptr; - std::unique_ptr pm; + cereal::Event::Which cur_which_ = cereal::Event::Which::INIT_DATA; + double min_seconds_ = 0; + double max_seconds_ = 0; + SubMaster *sm_ = nullptr; + std::unique_ptr pm_; std::vector sockets_; - std::vector filters_; - std::unique_ptr route_; std::unique_ptr camera_server_; std::atomic flags_ = REPLAY_FLAG_NONE; - std::mutex timeline_lock; - QFuture timeline_future; - std::vector> timeline_; std::string car_fingerprint_; std::atomic speed_ = 1.0; - replayEventFilter event_filter = nullptr; - void *filter_opaque = nullptr; - int segment_cache_limit = MIN_SEGMENTS_CACHE; + std::function event_filter_ = nullptr; + + std::shared_ptr event_data_ = std::make_shared(); + + BenchmarkStats benchmark_stats_; + std::condition_variable benchmark_cv_; + std::mutex benchmark_lock_; + bool benchmark_done_ = false; }; diff --git a/tools/replay/route.cc b/tools/replay/route.cc index c1e65526cf7b5e..df4fa813cf4571 100644 --- a/tools/replay/route.cc +++ b/tools/replay/route.cc @@ -1,102 +1,152 @@ #include "tools/replay/route.h" -#include -#include -#include -#include -#include -#include #include +#include +#include -#include "selfdrive/ui/qt/api.h" +#include "json11/json11.hpp" #include "system/hardware/hw.h" +#include "tools/replay/py_downloader.h" #include "tools/replay/replay.h" #include "tools/replay/util.h" -Route::Route(const QString &route, const QString &data_dir) : data_dir_(data_dir) { - route_ = parseRoute(route); -} +Route::Route(const std::string &route, const std::string &data_dir, bool auto_source) + : route_string_(route), data_dir_(data_dir), auto_source_(auto_source) {} -RouteIdentifier Route::parseRoute(const QString &str) { +RouteIdentifier Route::parseRoute(const std::string &str) { RouteIdentifier identifier = {}; - QRegularExpression rx(R"(^((?[a-z0-9]{16})[|_/])?(?.{20})((?--|/)(?((-?\d+(:(-?\d+)?)?)|(:-?\d+))))?$)"); - if (auto match = rx.match(str); match.hasMatch()) { - identifier.dongle_id = match.captured("dongle_id"); - identifier.timestamp = match.captured("timestamp"); + static const std::regex pattern(R"(^(([a-z0-9]{16})[|_/])?(.{20})((--|/)((-?\d+(:(-?\d+)?)?)|(:-?\d+)))?$)"); + std::smatch match; + + if (std::regex_match(str, match, pattern)) { + identifier.dongle_id = match[2].str(); + identifier.timestamp = match[3].str(); identifier.str = identifier.dongle_id + "|" + identifier.timestamp; - auto range_str = match.captured("range"); - if (auto separator = match.captured("separator"); separator == "/" && !range_str.isEmpty()) { - auto range = range_str.split(":"); - identifier.begin_segment = identifier.end_segment = range[0].toInt(); - if (range.size() == 2) { - identifier.end_segment = range[1].isEmpty() ? -1 : range[1].toInt(); + + const auto separator = match[5].str(); + const auto range_str = match[6].str(); + if (!range_str.empty()) { + if (separator == "/") { + int pos = range_str.find(':'); + int begin_seg = std::stoi(range_str.substr(0, pos)); + identifier.begin_segment = identifier.end_segment = begin_seg; + if (pos != std::string::npos) { + auto end_seg_str = range_str.substr(pos + 1); + identifier.end_segment = end_seg_str.empty() ? -1 : std::stoi(end_seg_str); + } + } else if (separator == "--") { + identifier.begin_segment = std::atoi(range_str.c_str()); } - } else if (separator == "--") { - identifier.begin_segment = range_str.toInt(); } } return identifier; } bool Route::load() { - err_ = RouteLoadError::None; - if (route_.str.isEmpty() || (data_dir_.isEmpty() && route_.dongle_id.isEmpty())) { + route_ = parseRoute(route_string_); + if (route_.str.empty() || (data_dir_.empty() && route_.dongle_id.empty())) { rInfo("invalid route format"); return false; } - date_time_ = QDateTime::fromString(route_.timestamp, "yyyy-MM-dd--HH-mm-ss"); - bool ret = data_dir_.isEmpty() ? loadFromServer() : loadFromLocal(); - if (ret) { - if (route_.begin_segment == -1) route_.begin_segment = segments_.rbegin()->first; - if (route_.end_segment == -1) route_.end_segment = segments_.rbegin()->first; - for (auto it = segments_.begin(); it != segments_.end(); /**/) { - if (it->first < route_.begin_segment || it->first > route_.end_segment) { - it = segments_.erase(it); - } else { - ++it; + + // Parse the timestamp from the route identifier (only applicable for old route formats). + struct tm tm_time = {0}; + if (strptime(route_.timestamp.c_str(), "%Y-%m-%d--%H-%M-%S", &tm_time)) { + date_time_ = mktime(&tm_time); + } + + if (!loadSegments()) { + rInfo("Failed to load segments"); + return false; + } + + return true; +} + +bool Route::loadSegments() { + if (!auto_source_) { + bool ret = data_dir_.empty() ? loadFromServer() : loadFromLocal(); + if (ret) { + // Trim segments + if (route_.begin_segment > 0) { + segments_.erase(segments_.begin(), segments_.lower_bound(route_.begin_segment)); } + if (route_.end_segment >= 0) { + segments_.erase(segments_.upper_bound(route_.end_segment), segments_.end()); + } + } + return !segments_.empty(); + } + return loadFromAutoSource(); +} + +bool Route::loadFromAutoSource() { + auto origin_prefix = getenv("OPENPILOT_PREFIX"); + if (origin_prefix) { + setenv("OPENPILOT_PREFIX", "", 1); + } + auto cmd = util::string_format("../auto_source.py \"%s\"", route_string_.c_str()); + auto log_files = split(util::check_output(cmd), '\n'); + if (origin_prefix) { + setenv("OPENPILOT_PREFIX", origin_prefix, 1); + } + + const static std::regex rx(R"(\/(\d+)\/)"); + for (int i = 0; i < log_files.size(); ++i) { + int seg_num = i; + std::smatch match; + if (std::regex_search(log_files[i], match, rx)) { + seg_num = std::stoi(match[1]); } + addFileToSegment(seg_num, log_files[i]); } return !segments_.empty(); } -bool Route::loadFromServer(int retries) { - for (int i = 1; i <= retries; ++i) { - QString result; - QEventLoop loop; - HttpRequest http(nullptr, !Hardware::PC()); - QObject::connect(&http, &HttpRequest::requestDone, [&loop, &result](const QString &json, bool success, QNetworkReply::NetworkError err) { - result = json; - loop.exit((int)err); - }); - http.sendRequest(CommaApi::BASE_URL + "/v1/route/" + route_.str + "/files"); - auto err = (QNetworkReply::NetworkError)loop.exec(); - if (err == QNetworkReply::NoError) { - return loadFromJson(result); - } else if (err == QNetworkReply::ContentAccessDenied || err == QNetworkReply::AuthenticationRequiredError) { - rWarning(">> Unauthorized. Authenticate with tools/lib/auth.py <<"); - err_ = RouteLoadError::AccessDenied; - return false; - } else if (err == QNetworkReply::ContentNotFoundError) { +bool Route::loadFromServer() { + std::string result = PyDownloader::getRouteFiles(route_.str); + if (result.empty()) { + err_ = RouteLoadError::NetworkError; + rWarning("Failed to fetch route files from server"); + return false; + } + + // Check for error field in JSON response + std::string parse_err; + auto json = json11::Json::parse(result, parse_err); + if (!parse_err.empty()) { + err_ = RouteLoadError::NetworkError; + rWarning("Failed to parse route files response"); + return false; + } + + if (json.is_object() && json["error"].is_string()) { + const std::string &error = json["error"].string_value(); + if (error == "unauthorized") { + rWarning(">> Unauthorized. Authenticate with tools/lib/auth.py <<"); + err_ = RouteLoadError::Unauthorized; + } else if (error == "not_found") { rWarning("The specified route could not be found on the server."); err_ = RouteLoadError::FileNotFound; - return false; } else { + rWarning("API error: %s", error.c_str()); err_ = RouteLoadError::NetworkError; } - rWarning("Retrying %d/%d", i, retries); - util::sleep_for(3000); + return false; } - return false; + + return loadFromJson(json); } -bool Route::loadFromJson(const QString &json) { - QRegExp rx(R"(\/(\d+)\/)"); - for (const auto &value : QJsonDocument::fromJson(json.trimmed().toUtf8()).object()) { - for (const auto &url : value.toArray()) { - QString url_str = url.toString(); - if (rx.indexIn(url_str) != -1) { - addFileToSegment(rx.cap(1).toInt(), url_str); +bool Route::loadFromJson(const json11::Json &json) { + const static std::regex rx(R"(\/(\d+)\/)"); + for (const auto &value : json.object_items()) { + const auto &urlArray = value.second.array_items(); + for (const auto &url : urlArray) { + std::string url_str = url.string_value(); + std::smatch match; + if (std::regex_search(url_str, match, rx)) { + addFileToSegment(std::stoi(match[1]), url_str); } } } @@ -104,23 +154,26 @@ bool Route::loadFromJson(const QString &json) { } bool Route::loadFromLocal() { - QDirIterator it(data_dir_, {QString("%1--*").arg(route_.timestamp)}, QDir::Dirs | QDir::NoDotAndDotDot); - while (it.hasNext()) { - QString segment = it.next(); - const int seg_num = segment.mid(segment.lastIndexOf("--") + 2).toInt(); - QDir segment_dir(segment); - for (const auto &f : segment_dir.entryList(QDir::Files)) { - addFileToSegment(seg_num, segment_dir.absoluteFilePath(f)); + std::string pattern = route_.timestamp + "--"; + for (const auto &entry : std::filesystem::directory_iterator(data_dir_)) { + if (entry.is_directory() && entry.path().filename().string().find(pattern) != std::string::npos) { + std::string segment = entry.path().string(); + int seg_num = std::atoi(segment.substr(segment.rfind("--") + 2).c_str()); + + for (const auto &file : std::filesystem::directory_iterator(segment)) { + if (file.is_regular_file()) { + addFileToSegment(seg_num, file.path().string()); + } + } } } return !segments_.empty(); } -void Route::addFileToSegment(int n, const QString &file) { - QString name = QUrl(file).fileName(); - - const int pos = name.lastIndexOf("--"); - name = pos != -1 ? name.mid(pos + 2) : name; +void Route::addFileToSegment(int n, const std::string &file) { + std::string name = extractFileName(file); + auto pos = name.find_last_of("--"); + name = pos != std::string::npos ? name.substr(pos + 2) : name; if (name == "rlog.bz2" || name == "rlog.zst" || name == "rlog") { segments_[n].rlog = file; @@ -139,28 +192,33 @@ void Route::addFileToSegment(int n, const QString &file) { // class Segment -Segment::Segment(int n, const SegmentFile &files, uint32_t flags, const std::vector &filters) - : seg_num(n), flags(flags), filters_(filters) { +Segment::Segment(int n, const SegmentFile &files, uint32_t flags, const std::vector &filters, + std::function callback) + : seg_num(n), flags(flags), filters_(filters), on_load_finished_(callback) { // [RoadCam, DriverCam, WideRoadCam, log]. fallback to qcamera/qlog const std::array file_list = { - (flags & REPLAY_FLAG_QCAMERA) || files.road_cam.isEmpty() ? files.qcamera : files.road_cam, + (flags & REPLAY_FLAG_QCAMERA) || files.road_cam.empty() ? files.qcamera : files.road_cam, flags & REPLAY_FLAG_DCAM ? files.driver_cam : "", flags & REPLAY_FLAG_ECAM ? files.wide_road_cam : "", - files.rlog.isEmpty() ? files.qlog : files.rlog, + files.rlog.empty() ? files.qlog : files.rlog, }; for (int i = 0; i < file_list.size(); ++i) { - if (!file_list[i].isEmpty() && (!(flags & REPLAY_FLAG_NO_VIPC) || i >= MAX_CAMERAS)) { + if (!file_list[i].empty() && (!(flags & REPLAY_FLAG_NO_VIPC) || i >= MAX_CAMERAS)) { ++loading_; - synchronizer_.addFuture(QtConcurrent::run(this, &Segment::loadFile, i, file_list[i].toStdString())); + threads_.emplace_back(&Segment::loadFile, this, i, file_list[i]); } } } Segment::~Segment() { - disconnect(); + { + std::lock_guard lock(mutex_); + on_load_finished_ = nullptr; // Prevent callback after destruction + } abort_ = true; - synchronizer_.setCancelOnWait(true); - synchronizer_.waitForFinished(); + for (auto &thread : threads_) { + if (thread.joinable()) thread.join(); + } } void Segment::loadFile(int id, const std::string file) { @@ -168,10 +226,10 @@ void Segment::loadFile(int id, const std::string file) { bool success = false; if (id < MAX_CAMERAS) { frames[id] = std::make_unique(); - success = frames[id]->load((CameraType)id, file, flags & REPLAY_FLAG_NO_HW_DECODER, &abort_, local_cache, 20 * 1024 * 1024, 3); + success = frames[id]->load((CameraType)id, file, flags & REPLAY_FLAG_NO_HW_DECODER, &abort_, local_cache); } else { log = std::make_unique(filters_); - success = log->load(file, &abort_, local_cache, 0, 3); + success = log->load(file, &abort_, local_cache); } if (!success) { @@ -180,6 +238,15 @@ void Segment::loadFile(int id, const std::string file) { } if (--loading_ == 0) { - emit loadFinished(!abort_); + std::lock_guard lock(mutex_); + load_state_ = !abort_ ? LoadState::Loaded : LoadState::Failed; + if (on_load_finished_) { + on_load_finished_(seg_num, !abort_); + } } } + +Segment::LoadState Segment::getState() { + std::scoped_lock lock(mutex_); + return load_state_; +} diff --git a/tools/replay/route.h b/tools/replay/route.h index acc73d509a1f6d..50f3eba8545ed4 100644 --- a/tools/replay/route.h +++ b/tools/replay/route.h @@ -1,19 +1,21 @@ #pragma once +#include #include #include +#include #include +#include #include -#include -#include - +#include "json11/json11.hpp" #include "tools/replay/framereader.h" #include "tools/replay/logreader.h" #include "tools/replay/util.h" enum class RouteLoadError { None, + Unauthorized, AccessDenied, NetworkError, FileNotFound, @@ -21,68 +23,73 @@ enum class RouteLoadError { }; struct RouteIdentifier { - QString dongle_id; - QString timestamp; + std::string dongle_id; + std::string timestamp; int begin_segment = 0; int end_segment = -1; - QString str; + std::string str; }; struct SegmentFile { - QString rlog; - QString qlog; - QString road_cam; - QString driver_cam; - QString wide_road_cam; - QString qcamera; + std::string rlog; + std::string qlog; + std::string road_cam; + std::string driver_cam; + std::string wide_road_cam; + std::string qcamera; }; class Route { public: - Route(const QString &route, const QString &data_dir = {}); + Route(const std::string &route, const std::string &data_dir = {}, bool auto_source = false); bool load(); RouteLoadError lastError() const { return err_; } - inline const QString &name() const { return route_.str; } - inline const QDateTime datetime() const { return date_time_; } - inline const QString &dir() const { return data_dir_; } + inline const std::string &name() const { return route_.str; } + inline const std::time_t datetime() const { return date_time_; } + inline const std::string &dir() const { return data_dir_; } inline const RouteIdentifier &identifier() const { return route_; } inline const std::map &segments() const { return segments_; } inline const SegmentFile &at(int n) { return segments_.at(n); } - static RouteIdentifier parseRoute(const QString &str); + static RouteIdentifier parseRoute(const std::string &str); protected: + bool loadSegments(); + bool loadFromAutoSource(); bool loadFromLocal(); - bool loadFromServer(int retries = 3); - bool loadFromJson(const QString &json); - void addFileToSegment(int seg_num, const QString &file); + bool loadFromServer(); + bool loadFromJson(const json11::Json &json); + void addFileToSegment(int seg_num, const std::string &file); RouteIdentifier route_ = {}; - QString data_dir_; + std::string data_dir_; std::map segments_; - QDateTime date_time_; + std::time_t date_time_ = 0; RouteLoadError err_ = RouteLoadError::None; + bool auto_source_ = false; + std::string route_string_; }; -class Segment : public QObject { - Q_OBJECT - +class Segment { public: - Segment(int n, const SegmentFile &files, uint32_t flags, const std::vector &filters = {}); + enum class LoadState {Loading, Loaded, Failed}; + + Segment(int n, const SegmentFile &files, uint32_t flags, const std::vector &filters, + std::function callback); ~Segment(); - inline bool isLoaded() const { return !loading_ && !abort_; } + LoadState getState(); const int seg_num = 0; std::unique_ptr log; std::unique_ptr frames[MAX_CAMERAS] = {}; -signals: - void loadFinished(bool success); - protected: void loadFile(int id, const std::string file); std::atomic abort_ = false; std::atomic loading_ = 0; - QFutureSynchronizer synchronizer_; + std::mutex mutex_; + std::vector threads_; + std::function on_load_finished_ = nullptr; uint32_t flags; std::vector filters_; + LoadState load_state_ = LoadState::Loading; }; diff --git a/tools/replay/rp_visualization.py b/tools/replay/rp_visualization.py deleted file mode 100755 index 01058967b2cc56..00000000000000 --- a/tools/replay/rp_visualization.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import os -import sys -import numpy as np -import rerun as rr -import cereal.messaging as messaging -from openpilot.common.basedir import BASEDIR -from openpilot.tools.replay.lib.rp_helpers import (UP, rerunColorPalette, - get_blank_lid_overlay, - maybe_update_radar_points, plot_lead, - plot_model) -from msgq.visionipc import VisionIpcClient, VisionStreamType - -os.environ['BASEDIR'] = BASEDIR - -UP.lidar_zoom = 6 - -def visualize(addr): - sm = messaging.SubMaster(['radarState', 'liveTracks', 'modelV2'], addr=addr) - vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True) - while True: - if not vipc_client.is_connected(): - vipc_client.connect(True) - new_data = vipc_client.recv() - if new_data is None or not new_data.data.any(): - continue - - sm.update(0) - lid_overlay = get_blank_lid_overlay(UP) - if sm.recv_frame['modelV2']: - plot_model(sm['modelV2'], lid_overlay) - if sm.recv_frame['radarState']: - plot_lead(sm['radarState'], lid_overlay) - liveTracksTime = sm.logMonoTime['liveTracks'] - maybe_update_radar_points(sm['liveTracks'], lid_overlay) - rr.set_time_nanos("TIMELINE", liveTracksTime) - rr.log("tracks", rr.SegmentationImage(np.flip(np.rot90(lid_overlay, k=-1), axis=1))) - - -def get_arg_parser(): - parser = argparse.ArgumentParser( - description="Show replay data in a UI.", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("ip_address", nargs="?", default="127.0.0.1", - help="The ip address on which to receive zmq messages.") - parser.add_argument("--frame-address", default=None, - help="The frame address (fully qualified ZMQ endpoint for frames) on which to receive zmq messages.") - return parser - - -if __name__ == "__main__": - args = get_arg_parser().parse_args(sys.argv[1:]) - if args.ip_address != "127.0.0.1": - os.environ["ZMQ"] = "1" - messaging.reset_context() - rr.init("RadarPoints", spawn= True) - rr.log("tracks", rr.AnnotationContext(rerunColorPalette), static=True) - visualize(args.ip_address) diff --git a/tools/replay/seg_mgr.cc b/tools/replay/seg_mgr.cc new file mode 100644 index 00000000000000..0778cacbc1b50f --- /dev/null +++ b/tools/replay/seg_mgr.cc @@ -0,0 +1,147 @@ +#include "tools/replay/seg_mgr.h" + +#include + +SegmentManager::~SegmentManager() { + { + std::unique_lock lock(mutex_); + exit_ = true; + } + cv_.notify_one(); + if (thread_.joinable()) thread_.join(); +} + +bool SegmentManager::load() { + if (!route_.load()) { + rError("failed to load route: %s", route_.name().c_str()); + return false; + } + + for (const auto &[n, file] : route_.segments()) { + if (!file.rlog.empty() || !file.qlog.empty()) { + segments_.insert({n, nullptr}); + } + } + + if (segments_.empty()) { + rInfo("no valid segments in route: %s", route_.name().c_str()); + return false; + } + + rInfo("loaded route %s with %zu valid segments", route_.name().c_str(), segments_.size()); + thread_ = std::thread(&SegmentManager::manageSegmentCache, this); + return true; +} + +void SegmentManager::setCurrentSegment(int seg_num) { + { + std::unique_lock lock(mutex_); + if (cur_seg_num_ == seg_num) return; + + cur_seg_num_ = seg_num; + needs_update_ = true; + } + cv_.notify_one(); +} + +void SegmentManager::manageSegmentCache() { + while (true) { + std::unique_lock lock(mutex_); + cv_.wait(lock, [this]() { return exit_ || needs_update_; }); + if (exit_) break; + + needs_update_ = false; + auto cur = segments_.lower_bound(cur_seg_num_); + if (cur == segments_.end()) continue; + + // Calculate the range of segments to load + auto begin = std::prev(cur, std::min(segment_cache_limit_ / 2, std::distance(segments_.begin(), cur))); + auto end = std::next(begin, std::min(segment_cache_limit_, std::distance(begin, segments_.end()))); + begin = std::prev(end, std::min(segment_cache_limit_, std::distance(segments_.begin(), end))); + + lock.unlock(); + + loadSegmentsInRange(begin, cur, end); + bool merged = mergeSegments(begin, end); + + // Free segments outside the current range + std::for_each(segments_.begin(), begin, [](auto &segment) { segment.second.reset(); }); + std::for_each(end, segments_.end(), [](auto &segment) { segment.second.reset(); }); + + if (merged && onSegmentMergedCallback_) { + onSegmentMergedCallback_(); // Notify listener that segments have been merged + } + } +} + +bool SegmentManager::mergeSegments(const SegmentMap::iterator &begin, const SegmentMap::iterator &end) { + std::set segments_to_merge; + size_t total_event_count = 0; + for (auto it = begin; it != end; ++it) { + const auto &segment = it->second; + if (segment && segment->getState() == Segment::LoadState::Loaded) { + segments_to_merge.insert(segment->seg_num); + total_event_count += segment->log->events.size(); + } + } + + if (segments_to_merge == merged_segments_) return false; + + auto merged_event_data = std::make_shared(); + auto &merged_events = merged_event_data->events; + merged_events.reserve(total_event_count); + + std::string segments_str = join(segments_to_merge, ", "); + rDebug("merging segments: %s", segments_str.c_str()); + for (int n : segments_to_merge) { + const auto &events = segments_.at(n)->log->events; + if (events.empty()) continue; + + // Skip INIT_DATA if present + auto events_begin = (events.front().which == cereal::Event::Which::INIT_DATA) ? std::next(events.begin()) : events.begin(); + + size_t previous_size = merged_events.size(); + merged_events.insert(merged_events.end(), events_begin, events.end()); + std::inplace_merge(merged_events.begin(), merged_events.begin() + previous_size, merged_events.end()); + + merged_event_data->segments[n] = segments_.at(n); + } + + std::atomic_store(&event_data_, std::move(merged_event_data)); + merged_segments_ = segments_to_merge; + + return true; +} + +void SegmentManager::loadSegmentsInRange(SegmentMap::iterator begin, SegmentMap::iterator cur, SegmentMap::iterator end) { + auto tryLoadSegment = [this](auto first, auto last) { + for (auto it = first; it != last; ++it) { + auto &segment_ptr = it->second; + if (!segment_ptr) { + if (onBenchmarkEvent_) { + onBenchmarkEvent_(it->first, "loading"); + } + segment_ptr = std::make_shared( + it->first, route_.at(it->first), flags_, filters_, + [this](int seg_num, bool success) { + if (onBenchmarkEvent_) { + onBenchmarkEvent_(seg_num, success ? "loaded" : "load failed"); + } + std::unique_lock lock(mutex_); + needs_update_ = true; + cv_.notify_one(); + }); + } + + if (segment_ptr->getState() == Segment::LoadState::Loading) { + return true; // Segment is still loading + } + } + return false; // No segments need loading + }; + + // Try forward loading, then reverse if necessary + if (!tryLoadSegment(cur, end)) { + tryLoadSegment(std::make_reverse_iterator(cur), std::make_reverse_iterator(begin)); + } +} diff --git a/tools/replay/seg_mgr.h b/tools/replay/seg_mgr.h new file mode 100644 index 00000000000000..54e156fb60af11 --- /dev/null +++ b/tools/replay/seg_mgr.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "tools/replay/route.h" + +constexpr int MIN_SEGMENTS_CACHE = 5; + +using SegmentMap = std::map>; + +class SegmentManager { +public: + struct EventData { + std::vector events; // Events extracted from the segments + SegmentMap segments; // Associated segments that contributed to these events + bool isSegmentLoaded(int n) const { return segments.find(n) != segments.end(); } + }; + + SegmentManager(const std::string &route_name, uint32_t flags, const std::string &data_dir = "", bool auto_source = false) + : flags_(flags), route_(route_name, data_dir, auto_source), event_data_(std::make_shared()) {} + ~SegmentManager(); + + bool load(); + void setCurrentSegment(int seg_num); + void setCallback(const std::function &callback) { onSegmentMergedCallback_ = callback; } + void setBenchmarkCallback(const std::function &callback) { onBenchmarkEvent_ = callback; } + void setFilters(const std::vector &filters) { filters_ = filters; } + const std::shared_ptr getEventData() const { return std::atomic_load(&event_data_); } + bool hasSegment(int n) const { return segments_.find(n) != segments_.end(); } + + Route route_; + int segment_cache_limit_ = MIN_SEGMENTS_CACHE; + +private: + void manageSegmentCache(); + void loadSegmentsInRange(SegmentMap::iterator begin, SegmentMap::iterator cur, SegmentMap::iterator end); + bool mergeSegments(const SegmentMap::iterator &begin, const SegmentMap::iterator &end); + + std::vector filters_; + uint32_t flags_; + + std::mutex mutex_; + std::condition_variable cv_; + std::thread thread_; + int cur_seg_num_ = -1; + bool needs_update_ = false; + bool exit_ = false; + + SegmentMap segments_; + std::shared_ptr event_data_; + std::function onSegmentMergedCallback_ = nullptr; + std::function onBenchmarkEvent_ = nullptr; + std::set merged_segments_; +}; diff --git a/tools/replay/tests/test_replay.cc b/tools/replay/tests/test_replay.cc index 3e5bfdf984e309..45fcc981915c63 100644 --- a/tools/replay/tests/test_replay.cc +++ b/tools/replay/tests/test_replay.cc @@ -1,63 +1,9 @@ -#include -#include - -#include - +#define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" -#include "common/util.h" +#include "tools/replay/filereader.h" #include "tools/replay/replay.h" -#include "tools/replay/util.h" const std::string TEST_RLOG_URL = "https://commadataci.blob.core.windows.net/openpilotci/0c94aa1e1296d7c6/2021-05-05--19-48-37/0/rlog.bz2"; -const std::string TEST_RLOG_CHECKSUM = "5b966d4bb21a100a8c4e59195faeb741b975ccbe268211765efd1763d892bfb3"; - -const int TEST_REPLAY_SEGMENTS = std::getenv("TEST_REPLAY_SEGMENTS") ? atoi(std::getenv("TEST_REPLAY_SEGMENTS")) : 1; - -bool download_to_file(const std::string &url, const std::string &local_file, int chunk_size = 5 * 1024 * 1024, int retries = 3) { - do { - if (httpDownload(url, local_file, chunk_size)) { - return true; - } - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - } while (--retries >= 0); - return false; -} - -TEST_CASE("httpMultiPartDownload") { - char filename[] = "/tmp/XXXXXX"; - close(mkstemp(filename)); - - const size_t chunk_size = 5 * 1024 * 1024; - std::string content; - SECTION("download to file") { - REQUIRE(download_to_file(TEST_RLOG_URL, filename, chunk_size)); - content = util::read_file(filename); - } - SECTION("download to buffer") { - for (int i = 0; i < 3 && content.empty(); ++i) { - content = httpGet(TEST_RLOG_URL, chunk_size); - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - } - REQUIRE(!content.empty()); - } - REQUIRE(content.size() == 9112651); - REQUIRE(sha256(content) == TEST_RLOG_CHECKSUM); -} - -TEST_CASE("FileReader") { - auto enable_local_cache = GENERATE(true, false); - std::string cache_file = cacheFilePath(TEST_RLOG_URL); - system(("rm " + cache_file + " -f").c_str()); - - FileReader reader(enable_local_cache); - std::string content = reader.read(TEST_RLOG_URL); - REQUIRE(sha256(content) == TEST_RLOG_CHECKSUM); - if (enable_local_cache) { - REQUIRE(sha256(util::read_file(cache_file)) == TEST_RLOG_CHECKSUM); - } else { - REQUIRE(util::file_exists(cache_file) == false); - } -} TEST_CASE("LogReader") { SECTION("corrupt log") { @@ -70,107 +16,3 @@ TEST_CASE("LogReader") { REQUIRE(log.events.size() > 0); } } - -void read_segment(int n, const SegmentFile &segment_file, uint32_t flags) { - QEventLoop loop; - Segment segment(n, segment_file, flags); - QObject::connect(&segment, &Segment::loadFinished, [&]() { - REQUIRE(segment.isLoaded() == true); - REQUIRE(segment.log != nullptr); - REQUIRE(segment.frames[RoadCam] != nullptr); - if (flags & REPLAY_FLAG_DCAM) { - REQUIRE(segment.frames[DriverCam] != nullptr); - } - if (flags & REPLAY_FLAG_ECAM) { - REQUIRE(segment.frames[WideRoadCam] != nullptr); - } - - // test LogReader & FrameReader - REQUIRE(segment.log->events.size() > 0); - REQUIRE(std::is_sorted(segment.log->events.begin(), segment.log->events.end())); - - for (auto cam : ALL_CAMERAS) { - auto &fr = segment.frames[cam]; - if (!fr) continue; - - if (cam == RoadCam || cam == WideRoadCam) { - REQUIRE(fr->getFrameCount() == 1200); - } - auto [nv12_width, nv12_height, nv12_buffer_size] = get_nv12_info(fr->width, fr->height); - VisionBuf buf; - buf.allocate(nv12_buffer_size); - buf.init_yuv(fr->width, fr->height, nv12_width, nv12_width * nv12_height); - // sequence get 100 frames - for (int i = 0; i < 100; ++i) { - REQUIRE(fr->get(i, &buf)); - } - } - - loop.quit(); - }); - loop.exec(); -} - -std::string download_demo_route() { - static std::string data_dir; - - if (data_dir == "") { - char tmp_path[] = "/tmp/root_XXXXXX"; - data_dir = mkdtemp(tmp_path); - - Route remote_route(DEMO_ROUTE); - assert(remote_route.load()); - - // Create a local route from remote for testing - const std::string route_name = DEMO_ROUTE.mid(17).toStdString(); - for (int i = 0; i < 2; ++i) { - std::string log_path = util::string_format("%s/%s--%d/", data_dir.c_str(), route_name.c_str(), i); - util::create_directories(log_path, 0755); - REQUIRE(download_to_file(remote_route.at(i).rlog.toStdString(), log_path + "rlog.bz2")); - REQUIRE(download_to_file(remote_route.at(i).qcamera.toStdString(), log_path + "qcamera.ts")); - } - } - - return data_dir; -} - - -TEST_CASE("Local route") { - std::string data_dir = download_demo_route(); - - auto flags = GENERATE(0, REPLAY_FLAG_QCAMERA); - Route route(DEMO_ROUTE, QString::fromStdString(data_dir)); - REQUIRE(route.load()); - REQUIRE(route.segments().size() == 2); - for (int i = 0; i < TEST_REPLAY_SEGMENTS; ++i) { - read_segment(i, route.at(i), flags); - } -} - -TEST_CASE("Remote route") { - auto flags = GENERATE(0, REPLAY_FLAG_QCAMERA); - Route route(DEMO_ROUTE); - REQUIRE(route.load()); - REQUIRE(route.segments().size() == 13); - for (int i = 0; i < TEST_REPLAY_SEGMENTS; ++i) { - read_segment(i, route.at(i), flags); - } -} - -TEST_CASE("seek_to") { - QEventLoop loop; - int seek_to = util::random_int(0, 2 * 59); - Replay replay(DEMO_ROUTE, {}, {}, nullptr, REPLAY_FLAG_NO_VIPC); - - QObject::connect(&replay, &Replay::seekedTo, [&](double sec) { - INFO("seek to " << seek_to << "s sought to" << sec); - REQUIRE(sec >= seek_to); - loop.quit(); - }); - - REQUIRE(replay.load()); - replay.start(); - replay.seekTo(seek_to, false); - - loop.exec(); -} diff --git a/tools/replay/tests/test_runner.cc b/tools/replay/tests/test_runner.cc deleted file mode 100644 index b20ac86c64847b..00000000000000 --- a/tools/replay/tests/test_runner.cc +++ /dev/null @@ -1,10 +0,0 @@ -#define CATCH_CONFIG_RUNNER -#include "catch2/catch.hpp" -#include - -int main(int argc, char **argv) { - // unit tests for Qt - QCoreApplication app(argc, argv); - const int res = Catch::Session().run(argc, argv); - return (res < 0xff ? res : 0xff); -} diff --git a/tools/replay/timeline.cc b/tools/replay/timeline.cc new file mode 100644 index 00000000000000..08dca5c89eb09e --- /dev/null +++ b/tools/replay/timeline.cc @@ -0,0 +1,111 @@ +#include "tools/replay/timeline.h" + +#include +#include + +#include "cereal/gen/cpp/log.capnp.h" + +Timeline::~Timeline() { + should_exit_.store(true); + if (thread_.joinable()) { + thread_.join(); + } +} + +void Timeline::initialize(const Route &route, uint64_t route_start_ts, bool local_cache, + std::function)> callback) { + thread_ = std::thread(&Timeline::buildTimeline, this, route, route_start_ts, local_cache, callback); +} + +std::optional Timeline::find(double cur_ts, FindFlag flag) const { + for (const auto &entry : *getEntries()) { + if (entry.type == TimelineType::Engaged) { + if (flag == FindFlag::nextEngagement && entry.start_time > cur_ts) { + return entry.start_time; + } else if (flag == FindFlag::nextDisEngagement && entry.end_time > cur_ts) { + return entry.end_time; + } + } else if (entry.start_time > cur_ts) { + if ((flag == FindFlag::nextUserBookmark && entry.type == TimelineType::UserBookmark) || + (flag == FindFlag::nextInfo && entry.type == TimelineType::AlertInfo) || + (flag == FindFlag::nextWarning && entry.type == TimelineType::AlertWarning) || + (flag == FindFlag::nextCritical && entry.type == TimelineType::AlertCritical)) { + return entry.start_time; + } + } + } + return std::nullopt; +} + +std::optional Timeline::findAlertAtTime(double target_time) const { + for (const auto &entry : *getEntries()) { + if (entry.start_time > target_time) break; + if (entry.end_time >= target_time && entry.type >= TimelineType::AlertInfo) { + return entry; + } + } + return std::nullopt; +} + +void Timeline::buildTimeline(const Route &route, uint64_t route_start_ts, bool local_cache, + std::function)> callback) { + std::optional current_engaged_idx, current_alert_idx; + + for (const auto &segment : route.segments()) { + if (should_exit_) break; + + auto log = std::make_shared(); + if (!log->load(segment.second.qlog, &should_exit_, local_cache) || log->events.empty()) { + continue; // Skip if log loading fails or no events + } + + for (const Event &e : log->events) { + double seconds = (e.mono_time - route_start_ts) / 1e9; + if (e.which == cereal::Event::Which::SELFDRIVE_STATE) { + capnp::FlatArrayMessageReader reader(e.data); + auto cs = reader.getRoot().getSelfdriveState(); + updateEngagementStatus(cs, current_engaged_idx, seconds); + updateAlertStatus(cs, current_alert_idx, seconds); + } else if (e.which == cereal::Event::Which::USER_BOOKMARK) { + staging_entries_.emplace_back(Entry{seconds, seconds, TimelineType::UserBookmark}); + } + } + + // Sort and finalize the timeline entries + auto entries = std::make_shared>(staging_entries_); + std::sort(entries->begin(), entries->end(), [](auto &a, auto &b) { return a.start_time < b.start_time; }); + std::atomic_store(&timeline_entries_, std::move(entries)); + + callback(log); // Notify the callback once the log is processed + } +} + +void Timeline::updateEngagementStatus(const cereal::SelfdriveState::Reader &cs, std::optional &idx, double seconds) { + if (idx) staging_entries_[*idx].end_time = seconds; + if (cs.getEnabled()) { + if (!idx) { + idx = staging_entries_.size(); + staging_entries_.emplace_back(Entry{seconds, seconds, TimelineType::Engaged}); + } + } else { + idx.reset(); + } +} + +void Timeline::updateAlertStatus(const cereal::SelfdriveState::Reader &cs, std::optional &idx, double seconds) { + static auto alert_types = std::array{TimelineType::AlertInfo, TimelineType::AlertWarning, TimelineType::AlertCritical}; + + Entry *entry = idx ? &staging_entries_[*idx] : nullptr; + if (entry) entry->end_time = seconds; + if (cs.getAlertSize() != cereal::SelfdriveState::AlertSize::NONE) { + auto type = alert_types[(int)cs.getAlertStatus()]; + std::string text1 = cs.getAlertText1().cStr(); + std::string text2 = cs.getAlertText2().cStr(); + if (!entry || entry->type != type || entry->text1 != text1 || entry->text2 != text2) { + idx = staging_entries_.size(); + staging_entries_.emplace_back(Entry{seconds, seconds, type, text1, text2}); // Start a new entry + } + } else { + idx.reset(); + } +} diff --git a/tools/replay/timeline.h b/tools/replay/timeline.h new file mode 100644 index 00000000000000..9688b6b95e8ebc --- /dev/null +++ b/tools/replay/timeline.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +#include + +#include "tools/replay/route.h" + +enum class TimelineType { None, Engaged, AlertInfo, AlertWarning, AlertCritical, UserBookmark }; +enum class FindFlag { nextEngagement, nextDisEngagement, nextUserBookmark, nextInfo, nextWarning, nextCritical }; + +class Timeline { +public: + struct Entry { + double start_time; + double end_time; + TimelineType type; + std::string text1; + std::string text2; + }; + + Timeline() : timeline_entries_(std::make_shared>()) {} + ~Timeline(); + + void initialize(const Route &route, uint64_t route_start_ts, bool local_cache, + std::function)> callback); + std::optional find(double cur_ts, FindFlag flag) const; + std::optional findAlertAtTime(double target_time) const; + const std::shared_ptr> getEntries() const { return std::atomic_load(&timeline_entries_); } + +private: + void buildTimeline(const Route &route, uint64_t route_start_ts, bool local_cache, + std::function)> callback); + void updateEngagementStatus(const cereal::SelfdriveState::Reader &cs, std::optional &idx, double seconds); + void updateAlertStatus(const cereal::SelfdriveState::Reader &cs, std::optional &idx, double seconds); + + std::thread thread_; + std::atomic should_exit_ = false; + + // Temporarily holds entries before they are sorted and finalized + std::vector staging_entries_; + + // Final sorted timeline entries + std::shared_ptr> timeline_entries_; +}; diff --git a/tools/replay/ui.py b/tools/replay/ui.py new file mode 100755 index 00000000000000..405c79f42502f5 --- /dev/null +++ b/tools/replay/ui.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +import argparse +import os +import sys + +import numpy as np +import pyray as rl + +import cereal.messaging as messaging +from openpilot.common.basedir import BASEDIR +from openpilot.common.transformations.camera import DEVICE_CAMERAS +from openpilot.tools.replay.lib.ui_helpers import ( + UP, + BLACK, + GREEN, + YELLOW, + Calibration, + get_blank_lid_overlay, + init_plots, + maybe_update_radar_points, + plot_lead, + plot_model, +) +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView + +os.environ['BASEDIR'] = BASEDIR + +ANGLE_SCALE = 5.0 + + +def ui_thread(addr): + # Get monitor info before creating window + rl.set_config_flags(rl.ConfigFlags.FLAG_MSAA_4X_HINT) + rl.init_window(1, 1, "") + max_height = rl.get_monitor_height(0) + rl.close_window() + + hor_mode = os.getenv("HORIZONTAL") is not None + hor_mode = True if max_height < 960 + 300 else hor_mode + + if hor_mode: + size = (640 + 384 + 640, 960) + write_x = 5 + write_y = 680 + else: + size = (640 + 384, 960 + 300) + write_x = 645 + write_y = 970 + + rl.set_trace_log_level(rl.TraceLogLevel.LOG_ERROR) + rl.set_config_flags(rl.ConfigFlags.FLAG_MSAA_4X_HINT) + rl.init_window(size[0], size[1], "openpilot debug UI") + rl.set_target_fps(60) + + # Load font + font_path = os.path.join(BASEDIR, "selfdrive/assets/fonts/JetBrainsMono-Medium.ttf") + font = rl.load_font_ex(font_path, 32, None, 0) + + camera_view = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) + + # Overlay texture for model/lane line drawing + overlay_img = np.zeros((480, 640, 4), dtype='uint8') + overlay_image = rl.gen_image_color(640, 480, rl.BLANK) + overlay_texture = rl.load_texture_from_image(overlay_image) + rl.unload_image(overlay_image) + + # lid_overlay array is (lidar_x, lidar_y) = (384, 960) + top_down_image = rl.gen_image_color(UP.lidar_x, UP.lidar_y, rl.BLACK) + top_down_texture = rl.load_texture_from_image(top_down_image) + rl.unload_image(top_down_image) + + sm = messaging.SubMaster( + [ + 'carState', + 'longitudinalPlan', + 'carControl', + 'radarState', + 'liveCalibration', + 'controlsState', + 'selfdriveState', + 'liveTracks', + 'modelV2', + 'liveParameters', + 'roadCameraState', + ], + addr=addr, + ) + + img = np.zeros((480, 640, 3), dtype='uint8') + num_px = 0 + calibration = None + + lid_overlay_blank = get_blank_lid_overlay(UP) + + # plots + name_to_arr_idx = { + "gas": 0, + "computer_gas": 1, + "user_brake": 2, + "computer_brake": 3, + "v_ego": 4, + "v_pid": 5, + "angle_steers_des": 6, + "angle_steers": 7, + "angle_steers_k": 8, + "steer_torque": 9, + "v_override": 10, + "v_cruise": 11, + "a_ego": 12, + "a_target": 13, + } + + plot_arr = np.zeros((100, len(name_to_arr_idx.values()))) + + plot_xlims = [(0, plot_arr.shape[0]), (0, plot_arr.shape[0]), (0, plot_arr.shape[0]), (0, plot_arr.shape[0])] + plot_ylims = [(-0.1, 1.1), (-ANGLE_SCALE, ANGLE_SCALE), (0.0, 75.0), (-3.5, 2.0)] + plot_names = [ + ["gas", "computer_gas", "user_brake", "computer_brake"], + ["angle_steers", "angle_steers_des", "angle_steers_k", "steer_torque"], + ["v_ego", "v_override", "v_pid", "v_cruise"], + ["a_ego", "a_target"], + ] + plot_colors = [["b", "b", "g", "r", "y"], ["b", "g", "y", "r"], ["b", "g", "r", "y"], ["b", "r"]] + plot_styles = [["-", "-", "-", "-", "-"], ["-", "-", "-", "-"], ["-", "-", "-", "-"], ["-", "-"]] + + draw_plots = init_plots(plot_arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles) + + # Palette for converting lid_overlay grayscale indices to RGBA colors + palette = np.zeros((256, 4), dtype=np.uint8) + palette[:, 3] = 255 # alpha + palette[1] = [255, 0, 0, 255] # RED + palette[2] = [0, 255, 0, 255] # GREEN + palette[3] = [0, 0, 255, 255] # BLUE + palette[4] = [255, 255, 0, 255] # YELLOW + palette[110] = [110, 110, 110, 255] # car_color (gray) + palette[255] = [255, 255, 255, 255] # WHITE + + while not rl.window_should_close(): + rl.begin_drawing() + rl.clear_background(rl.Color(64, 64, 64, 255)) + + # Render camera (NV12->RGB on GPU via shader) + if camera_view.frame: + cam_h = 640.0 * camera_view.frame.height / camera_view.frame.width + else: + cam_h = 480.0 + camera_view.render(rl.Rectangle(0, 0, 640, cam_h)) + + lid_overlay = lid_overlay_blank.copy() + top_down = top_down_texture, lid_overlay + + sm.update(0) + + camera = DEVICE_CAMERAS[("tici", str(sm['roadCameraState'].sensor))] + calib_scale = camera.fcam.width / 640.0 + + if camera_view.frame: + num_px = camera_view.frame.width * camera_view.frame.height + + intrinsic_matrix = camera.fcam.intrinsics + + w = sm['controlsState'].lateralControlState.which() + if w == 'lqrStateDEPRECATED': + angle_steers_k = sm['controlsState'].lateralControlState.lqrStateDEPRECATED.steeringAngleDeg + elif w == 'indiState': + angle_steers_k = sm['controlsState'].lateralControlState.indiState.steeringAngleDeg + else: + angle_steers_k = np.inf + + if sm.updated['carState']: + plot_arr[:-1] = plot_arr[1:] + plot_arr[-1, name_to_arr_idx['angle_steers']] = sm['carState'].steeringAngleDeg + plot_arr[-1, name_to_arr_idx['angle_steers_des']] = sm['carControl'].actuators.steeringAngleDeg + plot_arr[-1, name_to_arr_idx['angle_steers_k']] = angle_steers_k + plot_arr[-1, name_to_arr_idx['gas']] = sm['carState'].gasDEPRECATED + # TODO gas is deprecated + plot_arr[-1, name_to_arr_idx['computer_gas']] = np.clip(sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) + plot_arr[-1, name_to_arr_idx['user_brake']] = sm['carState'].brake + plot_arr[-1, name_to_arr_idx['steer_torque']] = sm['carControl'].actuators.torque * ANGLE_SCALE + # TODO brake is deprecated + plot_arr[-1, name_to_arr_idx['computer_brake']] = np.clip(-sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) + plot_arr[-1, name_to_arr_idx['v_ego']] = sm['carState'].vEgo + plot_arr[-1, name_to_arr_idx['v_cruise']] = sm['carState'].cruiseState.speed + plot_arr[-1, name_to_arr_idx['a_ego']] = sm['carState'].aEgo + + plot_arr[-1, name_to_arr_idx['a_target']] = sm['longitudinalPlan'].aTarget + + # Draw model overlays onto img, then blit as transparent overlay + img[:] = 0 + if sm.recv_frame['modelV2']: + plot_model(sm['modelV2'], img, calibration, top_down) + + if sm.recv_frame['radarState']: + plot_lead(sm['radarState'], top_down) + + # draw all radar points + maybe_update_radar_points(sm['liveTracks'].points, top_down[1]) + + if sm.updated['liveCalibration'] and num_px: + rpyCalib = np.asarray(sm['liveCalibration'].rpyCalib) + calibration = Calibration(num_px, rpyCalib, intrinsic_matrix, calib_scale) + + # Update overlay texture (RGB img -> RGBA with non-black pixels visible) + mask = np.any(img > 0, axis=2) + overlay_img[:, :, :3] = img + overlay_img[:, :, 3] = mask * 255 + rl.update_texture(overlay_texture, rl.ffi.cast("void *", overlay_img.ctypes.data)) + rl.draw_texture(overlay_texture, 0, 0, rl.WHITE) # noqa: TID251 + + # display alerts + rl.draw_text_ex(font, sm['selfdriveState'].alertText1, rl.Vector2(180, 150), 30, 0, rl.RED) + rl.draw_text_ex(font, sm['selfdriveState'].alertText2, rl.Vector2(180, 190), 20, 0, rl.RED) + + # draw plots (texture is reused internally) + plot_texture = draw_plots(plot_arr) + if hor_mode: + rl.draw_texture(plot_texture, 640 + 384, 0, rl.WHITE) # noqa: TID251 + else: + rl.draw_texture(plot_texture, 0, 600, rl.WHITE) # noqa: TID251 + + # Convert lid_overlay to RGBA and update top_down texture + # lid_overlay is (384, 960), need to transpose to (960, 384) for row-major RGBA buffer + lid_rgba = palette[lid_overlay.T] + rl.update_texture(top_down_texture, rl.ffi.cast("void *", np.ascontiguousarray(lid_rgba).ctypes.data)) + rl.draw_texture(top_down_texture, 640, 0, rl.WHITE) # noqa: TID251 + + SPACING = 25 + lines = [ + ("ENABLED", GREEN if sm['selfdriveState'].enabled else BLACK), + ("SPEED: " + str(round(sm['carState'].vEgo, 1)) + " m/s", YELLOW), + ("LONG CONTROL STATE: " + str(sm['controlsState'].longControlState), YELLOW), + ("LONG MPC SOURCE: " + str(sm['longitudinalPlan'].longitudinalPlanSource), YELLOW), + None, + ("ANGLE OFFSET (AVG): " + str(round(sm['liveParameters'].angleOffsetAverageDeg, 2)) + " deg", YELLOW), + ("ANGLE OFFSET (INSTANT): " + str(round(sm['liveParameters'].angleOffsetDeg, 2)) + " deg", YELLOW), + ("STIFFNESS: " + str(round(sm['liveParameters'].stiffnessFactor * 100.0, 2)) + " %", YELLOW), + ("STEER RATIO: " + str(round(sm['liveParameters'].steerRatio, 2)), YELLOW), + ] + + for i, line in enumerate(lines): + if line is not None: + color = rl.Color(line[1][0], line[1][1], line[1][2], 255) + rl.draw_text_ex(font, line[0], rl.Vector2(write_x, write_y + i * SPACING), 20, 0, color) + + rl.end_drawing() + + rl.unload_texture(overlay_texture) + rl.unload_texture(top_down_texture) + rl.unload_font(font) + camera_view.close() + rl.close_window() + + +def get_arg_parser(): + parser = argparse.ArgumentParser(description="Show replay data in a UI.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument("ip_address", nargs="?", default="127.0.0.1", help="The ip address on which to receive zmq messages.") + + parser.add_argument("--frame-address", default=None, help="The frame address (fully qualified ZMQ endpoint for frames) on which to receive zmq messages.") + return parser + + +if __name__ == "__main__": + args = get_arg_parser().parse_args(sys.argv[1:]) + + if args.ip_address != "127.0.0.1": + os.environ["ZMQ"] = "1" + messaging.reset_context() + + ui_thread(args.ip_address) diff --git a/tools/replay/unlog_ci_segment.py b/tools/replay/unlog_ci_segment.py deleted file mode 100755 index adc0b19e9ba891..00000000000000 --- a/tools/replay/unlog_ci_segment.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import bisect -import select -import sys -import termios -import time -import tty -from collections import defaultdict - -import cereal.messaging as messaging -from openpilot.tools.lib.framereader import FrameReader -from openpilot.tools.lib.logreader import LogReader -from openpilot.tools.lib.openpilotci import get_url - -IGNORE = ['initData', 'sentinel'] - - -def input_ready(): - return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) - - -def replay(route, segment, loop): - route = route.replace('|', '/') - - lr = LogReader(get_url(route, segment, "rlog.bz2")) - fr = FrameReader(get_url(route, segment, "fcamera.hevc"), readahead=True) - - # Build mapping from frameId to segmentId from roadEncodeIdx, type == fullHEVC - msgs = [m for m in lr if m.which() not in IGNORE] - msgs = sorted(msgs, key=lambda m: m.logMonoTime) - times = [m.logMonoTime for m in msgs] - frame_idx = {m.roadEncodeIdx.frameId: m.roadEncodeIdx.segmentId for m in msgs if m.which() == 'roadEncodeIdx' and m.roadEncodeIdx.type == 'fullHEVC'} - - socks = {} - lag = 0.0 - i = 0 - max_i = len(msgs) - 2 - - while True: - msg = msgs[i].as_builder() - next_msg = msgs[i + 1] - - start_time = time.time() - w = msg.which() - - if w == 'roadCameraState': - try: - img = fr.get(frame_idx[msg.roadCameraState.frameId], pix_fmt="rgb24") - img = img[0][:, :, ::-1] # Convert RGB to BGR, which is what the camera outputs - msg.roadCameraState.image = img.flatten().tobytes() - except (KeyError, ValueError): - pass - - if w not in socks: - socks[w] = messaging.pub_sock(w) - - try: - if socks[w]: - socks[w].send(msg.to_bytes()) - except messaging.messaging_pyx.MultiplePublishersError: - socks[w] = None - - lag += (next_msg.logMonoTime - msg.logMonoTime) / 1e9 - lag -= time.time() - start_time - - dt = max(lag, 0.0) - lag -= dt - time.sleep(dt) - - if lag < -1.0 and i % 1000 == 0: - print(f"{-lag:.2f} s behind") - - if input_ready(): - key = sys.stdin.read(1) - - # Handle pause - if key == " ": - while True: - if input_ready() and sys.stdin.read(1) == " ": - break - time.sleep(0.01) - - # Handle seek - dt = defaultdict(int, s=10, S=-10)[key] - new_time = msgs[i].logMonoTime + dt * 1e9 - i = bisect.bisect_left(times, new_time) - - i = (i + 1) % max_i if loop else min(i + 1, max_i) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--loop", action='store_true') - parser.add_argument("route") - parser.add_argument("segment") - args = parser.parse_args() - - orig_settings = termios.tcgetattr(sys.stdin) - tty.setcbreak(sys.stdin) - - try: - replay(args.route, args.segment, args.loop) - termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings) - except Exception: - termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings) - raise diff --git a/tools/replay/util.cc b/tools/replay/util.cc index 81e87b7dd393b8..7b308b5c3d4704 100644 --- a/tools/replay/util.cc +++ b/tools/replay/util.cc @@ -1,20 +1,12 @@ #include "tools/replay/util.h" #include -#include -#include #include -#include -#include #include #include -#include #include -#include #include -#include -#include #include #include "common/timing.h" @@ -51,91 +43,6 @@ void logMessage(ReplyMsgType type, const char *fmt, ...) { free(msg_buf); } -namespace { - -struct CURLGlobalInitializer { - CURLGlobalInitializer() { curl_global_init(CURL_GLOBAL_DEFAULT); } - ~CURLGlobalInitializer() { curl_global_cleanup(); } -}; - -static CURLGlobalInitializer curl_initializer; - -template -struct MultiPartWriter { - T *buf; - size_t *total_written; - size_t offset; - size_t end; - - size_t write(char *data, size_t size, size_t count) { - size_t bytes = size * count; - if ((offset + bytes) > end) return 0; - - if constexpr (std::is_same::value) { - memcpy(buf->data() + offset, data, bytes); - } else if constexpr (std::is_same::value) { - buf->seekp(offset); - buf->write(data, bytes); - } - - offset += bytes; - *total_written += bytes; - return bytes; - } -}; - -template -size_t write_cb(char *data, size_t size, size_t count, void *userp) { - auto w = (MultiPartWriter *)userp; - return w->write(data, size, count); -} - -size_t dumy_write_cb(char *data, size_t size, size_t count, void *userp) { return size * count; } - -struct DownloadStats { - void installDownloadProgressHandler(DownloadProgressHandler handler) { - std::lock_guard lk(lock); - download_progress_handler = handler; - } - - void add(const std::string &url, uint64_t total_bytes) { - std::lock_guard lk(lock); - items[url] = {0, total_bytes}; - } - - void remove(const std::string &url) { - std::lock_guard lk(lock); - items.erase(url); - } - - void update(const std::string &url, uint64_t downloaded, bool success = true) { - std::lock_guard lk(lock); - items[url].first = downloaded; - - auto stat = std::accumulate(items.begin(), items.end(), std::pair{}, [=](auto &a, auto &b){ - return std::pair{a.first + b.second.first, a.second + b.second.second}; - }); - double tm = millis_since_boot(); - if (download_progress_handler && ((tm - prev_tm) > 500 || !success || stat.first >= stat.second)) { - download_progress_handler(stat.first, stat.second, success); - prev_tm = tm; - } - } - - std::mutex lock; - std::map> items; - double prev_tm = 0; - DownloadProgressHandler download_progress_handler = nullptr; -}; - -static DownloadStats download_stats; - -} // namespace - -void installDownloadProgressHandler(DownloadProgressHandler handler) { - download_stats.installDownloadProgressHandler(handler); -} - std::string formattedDataSize(size_t size) { if (size < 1024) { return std::to_string(size) + " B"; @@ -146,138 +53,11 @@ std::string formattedDataSize(size_t size) { } } -size_t getRemoteFileSize(const std::string &url, std::atomic *abort) { - CURL *curl = curl_easy_init(); - if (!curl) return -1; - - curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, dumy_write_cb); - curl_easy_setopt(curl, CURLOPT_HEADER, 1); - curl_easy_setopt(curl, CURLOPT_NOBODY, 1); - - CURLM *cm = curl_multi_init(); - curl_multi_add_handle(cm, curl); - int still_running = 1; - while (still_running > 0 && !(abort && *abort)) { - CURLMcode mc = curl_multi_perform(cm, &still_running); - if (mc != CURLM_OK) break; - if (still_running > 0) { - curl_multi_wait(cm, nullptr, 0, 1000, nullptr); - } - } - - double content_length = -1; - curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &content_length); - curl_multi_remove_handle(cm, curl); - curl_easy_cleanup(curl); - curl_multi_cleanup(cm); - return content_length > 0 ? (size_t)content_length : 0; -} - std::string getUrlWithoutQuery(const std::string &url) { size_t idx = url.find("?"); return (idx == std::string::npos ? url : url.substr(0, idx)); } -template -bool httpDownload(const std::string &url, T &buf, size_t chunk_size, size_t content_length, std::atomic *abort) { - download_stats.add(url, content_length); - - int parts = 1; - if (chunk_size > 0 && content_length > 10 * 1024 * 1024) { - parts = std::nearbyint(content_length / (float)chunk_size); - parts = std::clamp(parts, 1, 5); - } - - CURLM *cm = curl_multi_init(); - size_t written = 0; - std::map> writers; - const int part_size = content_length / parts; - for (int i = 0; i < parts; ++i) { - CURL *eh = curl_easy_init(); - writers[eh] = { - .buf = &buf, - .total_written = &written, - .offset = (size_t)(i * part_size), - .end = i == parts - 1 ? content_length : (i + 1) * part_size, - }; - curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, write_cb); - curl_easy_setopt(eh, CURLOPT_WRITEDATA, (void *)(&writers[eh])); - curl_easy_setopt(eh, CURLOPT_URL, url.c_str()); - curl_easy_setopt(eh, CURLOPT_RANGE, util::string_format("%d-%d", writers[eh].offset, writers[eh].end - 1).c_str()); - curl_easy_setopt(eh, CURLOPT_HTTPGET, 1); - curl_easy_setopt(eh, CURLOPT_NOSIGNAL, 1); - curl_easy_setopt(eh, CURLOPT_FOLLOWLOCATION, 1); - - curl_multi_add_handle(cm, eh); - } - - int still_running = 1; - size_t prev_written = 0; - while (still_running > 0 && !(abort && *abort)) { - CURLMcode mc = curl_multi_perform(cm, &still_running); - if (mc != CURLM_OK) { - break; - } - if (still_running > 0) { - curl_multi_wait(cm, nullptr, 0, 1000, nullptr); - } - - if (((written - prev_written) / (double)content_length) >= 0.01) { - download_stats.update(url, written); - prev_written = written; - } - } - - CURLMsg *msg; - int msgs_left = -1; - int complete = 0; - while ((msg = curl_multi_info_read(cm, &msgs_left)) && !(abort && *abort)) { - if (msg->msg == CURLMSG_DONE) { - if (msg->data.result == CURLE_OK) { - long res_status = 0; - curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &res_status); - if (res_status == 206) { - complete++; - } else { - rWarning("Download failed: http error code: %d", res_status); - } - } else { - rWarning("Download failed: connection failure: %d", msg->data.result); - } - } - } - - bool success = complete == parts; - download_stats.update(url, written, success); - download_stats.remove(url); - - for (const auto &[e, w] : writers) { - curl_multi_remove_handle(cm, e); - curl_easy_cleanup(e); - } - curl_multi_cleanup(cm); - - return success; -} - -std::string httpGet(const std::string &url, size_t chunk_size, std::atomic *abort) { - size_t size = getRemoteFileSize(url, abort); - if (size == 0) return {}; - - std::string result(size, '\0'); - return httpDownload(url, result, chunk_size, size, abort) ? result : ""; -} - -bool httpDownload(const std::string &url, const std::string &file, size_t chunk_size, std::atomic *abort) { - size_t size = getRemoteFileSize(url, abort); - if (size == 0) return false; - - std::ofstream of(file, std::ios::binary | std::ios::out); - of.seekp(size - 1).write("\0", 1); - return httpDownload(url, of, chunk_size, size, abort); -} - std::string decompressBZ2(const std::string &in, std::atomic *abort) { return decompressBZ2((std::byte *)in.data(), in.size(), abort); } @@ -329,8 +109,17 @@ std::string decompressZST(const std::byte *in, size_t in_size, std::atomic // Initialize input and output buffers ZSTD_inBuffer input = {in, in_size, 0}; + + // Estimate and reserve memory for decompressed data + size_t estimatedDecompressedSize = ZSTD_getFrameContentSize(in, in_size); + if (estimatedDecompressedSize == ZSTD_CONTENTSIZE_ERROR || estimatedDecompressedSize == ZSTD_CONTENTSIZE_UNKNOWN) { + estimatedDecompressedSize = in_size * 2; // Use a fallback size + } + std::string decompressedData; - const size_t bufferSize = ZSTD_DStreamOutSize(); // recommended output buffer size + decompressedData.reserve(estimatedDecompressedSize); + + const size_t bufferSize = ZSTD_DStreamOutSize(); // Recommended output buffer size std::string outputBuffer(bufferSize, '\0'); while (input.pos < input.size && !(abort && *abort)) { @@ -353,11 +142,11 @@ std::string decompressZST(const std::byte *in, size_t in_size, std::atomic return {}; } -void precise_nano_sleep(int64_t nanoseconds, std::atomic &should_exit) { +void precise_nano_sleep(int64_t nanoseconds, std::atomic &interrupt_requested) { struct timespec req, rem; req.tv_sec = nanoseconds / 1000000000; req.tv_nsec = nanoseconds % 1000000000; - while (!should_exit) { + while (!interrupt_requested) { #ifdef __APPLE__ int ret = nanosleep(&req, &rem); if (ret == 0 || errno != EINTR) @@ -372,13 +161,24 @@ void precise_nano_sleep(int64_t nanoseconds, std::atomic &should_exit) { } } -std::string sha256(const std::string &str) { - unsigned char hash[SHA256_DIGEST_LENGTH]; - SHA256_CTX sha256; - SHA256_Init(&sha256); - SHA256_Update(&sha256, str.c_str(), str.size()); - SHA256_Final(hash, &sha256); - return util::hexdump(hash, SHA256_DIGEST_LENGTH); +std::vector split(std::string_view source, char delimiter) { + std::vector fields; + size_t last = 0; + for (size_t i = 0; i < source.length(); ++i) { + if (source[i] == delimiter) { + fields.emplace_back(source.substr(last, i - last)); + last = i + 1; + } + } + fields.emplace_back(source.substr(last)); + return fields; +} + +std::string extractFileName(const std::string &file) { + size_t queryPos = file.find_first_of("?"); + std::string path = (queryPos != std::string::npos) ? file.substr(0, queryPos) : file; + size_t lastSlash = path.find_last_of("/\\"); + return (lastSlash != std::string::npos) ? path.substr(lastSlash + 1) : path; } // MonotonicBuffer diff --git a/tools/replay/util.h b/tools/replay/util.h index c3b016c3918b13..a2d0f6203a8d1a 100644 --- a/tools/replay/util.h +++ b/tools/replay/util.h @@ -3,7 +3,17 @@ #include #include #include +#include #include +#include +#include +#include "cereal/messaging/messaging.h" + +enum CameraType { + RoadCam = 0, + DriverCam, + WideRoadCam +}; enum class ReplyMsgType { Info, @@ -36,17 +46,22 @@ class MonotonicBuffer { static constexpr float growth_factor = 1.5; }; -std::string sha256(const std::string &str); -void precise_nano_sleep(int64_t nanoseconds, std::atomic &should_exit); +void precise_nano_sleep(int64_t nanoseconds, std::atomic &interrupt_requested); std::string decompressBZ2(const std::string &in, std::atomic *abort = nullptr); std::string decompressBZ2(const std::byte *in, size_t in_size, std::atomic *abort = nullptr); std::string decompressZST(const std::string &in, std::atomic *abort = nullptr); std::string decompressZST(const std::byte *in, size_t in_size, std::atomic *abort = nullptr); std::string getUrlWithoutQuery(const std::string &url); -size_t getRemoteFileSize(const std::string &url, std::atomic *abort = nullptr); -std::string httpGet(const std::string &url, size_t chunk_size = 0, std::atomic *abort = nullptr); - -typedef std::function DownloadProgressHandler; -void installDownloadProgressHandler(DownloadProgressHandler); -bool httpDownload(const std::string &url, const std::string &file, size_t chunk_size = 0, std::atomic *abort = nullptr); std::string formattedDataSize(size_t size); +std::string extractFileName(const std::string& file); +std::vector split(std::string_view source, char delimiter); + +template +std::string join(const Iterable& elements, const std::string& separator) { + std::ostringstream oss; + for (auto it = elements.begin(); it != elements.end(); ++it) { + if (it != elements.begin()) oss << separator; + oss << *it; + } + return oss.str(); +} diff --git a/tools/rerun/README.md b/tools/rerun/README.md deleted file mode 100644 index dc0a901e60fed5..00000000000000 --- a/tools/rerun/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# Rerun -Rerun is a tool to quickly visualize time series data. It supports all openpilot logs , both the `logMessages` and video logs. - -[Instructions](https://rerun.io/docs/reference/viewer/overview) for navigation within the Rerun Viewer. - -## Usage -``` -usage: run.py [-h] [--demo] [--qcam] [--fcam] [--ecam] [--dcam] [route_or_segment_name] - -A helper to run rerun on openpilot routes - -positional arguments: - route_or_segment_name - The route or segment name to plot (default: None) - -options: - -h, --help show this help message and exit - --demo Use the demo route instead of providing one (default: False) - --qcam Show low-res road camera (default: False) - --fcam Show driving camera (default: False) - --ecam Show wide camera (default: False) - --dcam Show driver monitoring camera (default: False) -``` - -Examples using route name to observe accelerometer and qcamera: - -`./run.sh --qcam "a2a0ccea32023010/2023-07-27--13-01-19"` - -Examples using segment range (more on [SegmentRange](https://github.com/commaai/openpilot/tree/master/tools/lib)): - -`./run.sh --qcam "a2a0ccea32023010/2023-07-27--13-01-19/2:4"` - -## Cautions: -- Showing hevc videos (`--fcam`, `--ecam`, and `--dcam`) are expensive, and it's recommended to use `--qcam` for optimized performance. If possible, limiting your route to a few segments using `SegmentRange` will speed up logging and reduce memory usage - -## Demo -`./run.sh --qcam --demo` diff --git a/tools/rerun/camera_reader.py b/tools/rerun/camera_reader.py deleted file mode 100644 index 8366a3c1cf4986..00000000000000 --- a/tools/rerun/camera_reader.py +++ /dev/null @@ -1,93 +0,0 @@ -import tqdm -import subprocess -import multiprocessing -from enum import StrEnum -from functools import partial -from collections import namedtuple - -from openpilot.tools.lib.framereader import ffprobe - -CameraConfig = namedtuple("CameraConfig", ["qcam", "fcam", "ecam", "dcam"]) - -class CameraType(StrEnum): - qcam = "qcamera" - fcam = "fcamera" - ecam = "ecamera" - dcam = "dcamera" - - -def probe_packet_info(camera_path): - args = ["ffprobe", "-v", "quiet", "-show_packets", "-probesize", "10M", camera_path] - dat = subprocess.check_output(args) - dat = dat.decode().split() - return dat - - -class _FrameReader: - def __init__(self, camera_path, segment, h, w, start_time): - self.camera_path = camera_path - self.segment = segment - self.h = h - self.w = w - self.start_time = start_time - - self.ts = self._get_ts() - - def _read_stream_nv12(self): - frame_sz = self.w * self.h * 3 // 2 - proc = subprocess.Popen( - ["ffmpeg", "-v", "quiet", "-i", self.camera_path, "-f", "rawvideo", "-pix_fmt", "nv12", "-"], - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL - ) - try: - while True: - dat = proc.stdout.read(frame_sz) - if len(dat) == 0: - break - yield dat - finally: - proc.kill() - - def _get_ts(self): - dat = probe_packet_info(self.camera_path) - try: - ret = [float(d.split('=')[1]) for d in dat if d.startswith("pts_time=")] - except ValueError: - # pts_times aren't available. Infer timestamps from duration_times - ret = [d for d in dat if d.startswith("duration_time")] - ret = [float(d.split('=')[1])*(i+1)+(self.segment*60)+self.start_time for i, d in enumerate(ret)] - return ret - - def __iter__(self): - for i, frame in enumerate(self._read_stream_nv12()): - yield self.ts[i], frame - - -class CameraReader: - def __init__(self, camera_paths, start_time, seg_idxs): - self.seg_idxs = seg_idxs - self.camera_paths = camera_paths - self.start_time = start_time - - probe = ffprobe(camera_paths[0])["streams"][0] - self.h = probe["height"] - self.w = probe["width"] - - self.__frs = {} - - def _get_fr(self, i): - if i not in self.__frs: - self.__frs[i] = _FrameReader(self.camera_paths[i], segment=i, h=self.h, w=self.w, start_time=self.start_time) - return self.__frs[i] - - def _run_on_segment(self, func, i): - return func(self._get_fr(i)) - - def run_across_segments(self, num_processes, func, desc=None): - with multiprocessing.Pool(num_processes) as pool: - num_segs = len(self.seg_idxs) - for _ in tqdm.tqdm(pool.imap_unordered(partial(self._run_on_segment, func), self.seg_idxs), total=num_segs, desc=desc): - continue - diff --git a/tools/rerun/run.py b/tools/rerun/run.py deleted file mode 100755 index 6ce8a379375fc8..00000000000000 --- a/tools/rerun/run.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python3 - -import sys -import argparse -import multiprocessing -import rerun as rr -import rerun.blueprint as rrb -from functools import partial -from collections import defaultdict - -from cereal.services import SERVICE_LIST -from openpilot.tools.rerun.camera_reader import probe_packet_info, CameraReader, CameraConfig, CameraType -from openpilot.tools.lib.logreader import LogReader -from openpilot.tools.lib.route import Route, SegmentRange - - -NUM_CPUS = multiprocessing.cpu_count() -DEMO_ROUTE = "a2a0ccea32023010|2023-07-27--13-01-19" -RR_TIMELINE_NAME = "Timeline" -RR_WIN = "openpilot logs" - - -""" -Relevant upstream Rerun issues: -- loading videos directly: https://github.com/rerun-io/rerun/issues/6532 -""" - -class Rerunner: - def __init__(self, route, segment_range, camera_config): - self.lr = LogReader(route_or_segment_name) - - # hevc files don't have start_time. We get it from qcamera.ts - start_time = 0 - dat = probe_packet_info(route.qcamera_paths()[0]) - for d in dat: - if d.startswith("pts_time="): - start_time = float(d.split('=')[1]) - break - - qcam, fcam, ecam, dcam = camera_config - self.camera_readers = {} - if qcam: - self.camera_readers[CameraType.qcam] = CameraReader(route.qcamera_paths(), start_time, segment_range.seg_idxs) - if fcam: - self.camera_readers[CameraType.fcam] = CameraReader(route.camera_paths(), start_time, segment_range.seg_idxs) - if ecam: - self.camera_readers[CameraType.ecam] = CameraReader(route.ecamera_paths(), start_time, segment_range.seg_idxs) - if dcam: - self.camera_readers[CameraType.dcam] = CameraReader(route.dcamera_paths(), start_time, segment_range.seg_idxs) - - def _create_blueprint(self): - blueprint = None - service_views = [] - - for topic in sorted(SERVICE_LIST.keys()): - View = rrb.TimeSeriesView if topic != "thumbnail" else rrb.Spatial2DView - service_views.append(View(name=topic, origin=f"/{topic}/", visible=False)) - rr.log(topic, rr.SeriesLine(name=topic), timeless=True) - - center_view = [rrb.Vertical(*service_views, name="streams")] - if len(self.camera_readers): - center_view.append(rrb.Vertical(*[rrb.Spatial2DView(name=cam_type, origin=cam_type) for cam_type in self.camera_readers.keys()], name="cameras")) - - blueprint = rrb.Blueprint( - rrb.Horizontal( - *center_view - ), - rrb.SelectionPanel(expanded=False), - rrb.TimePanel(expanded=False), - ) - return blueprint - - @staticmethod - def _parse_msg(msg, parent_key=''): - stack = [(msg, parent_key)] - while stack: - current_msg, current_parent_key = stack.pop() - if isinstance(current_msg, list): - for index, item in enumerate(current_msg): - new_key = f"{current_parent_key}/{index}" - if isinstance(item, (int, float)): - yield new_key, item - elif isinstance(item, dict): - stack.append((item, new_key)) - elif isinstance(current_msg, dict): - for key, value in current_msg.items(): - new_key = f"{current_parent_key}/{key}" - if isinstance(value, (int, float)): - yield new_key, value - elif isinstance(value, dict): - stack.append((value, new_key)) - elif isinstance(value, list): - for index, item in enumerate(value): - if isinstance(item, (int, float)): - yield f"{new_key}/{index}", item - else: - pass # Not a plottable value - - @staticmethod - @rr.shutdown_at_exit - def _process_log_msgs(blueprint, lr): - rr.init(RR_WIN) - rr.connect() - rr.send_blueprint(blueprint) - - log_msgs = defaultdict(lambda: defaultdict(list)) - for msg in lr: - msg_type = msg.which() - - if msg_type == "thumbnail": - continue - - for entity_path, dat in Rerunner._parse_msg(msg.to_dict()[msg_type], msg_type): - log_msgs[entity_path]["times"].append(msg.logMonoTime) - log_msgs[entity_path]["data"].append(dat) - - for entity_path, log_msg in log_msgs.items(): - rr.send_columns( - entity_path, - times=[rr.TimeNanosColumn(RR_TIMELINE_NAME, log_msg["times"])], - components=[rr.components.ScalarBatch(log_msg["data"])] - ) - - return [] - - @staticmethod - @rr.shutdown_at_exit - def _process_cam_readers(blueprint, cam_type, h, w, fr): - rr.init(RR_WIN) - rr.connect() - rr.send_blueprint(blueprint) - - for ts, frame in fr: - rr.set_time_nanos(RR_TIMELINE_NAME, int(ts * 1e9)) - rr.log(cam_type, rr.Image(bytes=frame, width=w, height=h, pixel_format=rr.PixelFormat.NV12)) - - def load_data(self): - rr.init(RR_WIN, spawn=True) - - startup_blueprint = self._create_blueprint() - self.lr.run_across_segments(NUM_CPUS, partial(self._process_log_msgs, startup_blueprint), desc="Log messages") - for cam_type, cr in self.camera_readers.items(): - cr.run_across_segments(NUM_CPUS, partial(self._process_cam_readers, startup_blueprint, cam_type, cr.h, cr.w), desc=cam_type) - - rr.send_blueprint(self._create_blueprint()) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description="A helper to run rerun on openpilot routes", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") - parser.add_argument("--qcam", action="store_true", help="Show low-res road camera") - parser.add_argument("--fcam", action="store_true", help="Show driving camera") - parser.add_argument("--ecam", action="store_true", help="Show wide camera") - parser.add_argument("--dcam", action="store_true", help="Show driver monitoring camera") - parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to plot") - args = parser.parse_args() - - if not args.demo and not args.route_or_segment_name: - parser.print_help() - sys.exit() - - camera_config = CameraConfig(args.qcam, args.fcam, args.ecam, args.dcam) - route_or_segment_name = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() - - sr = SegmentRange(route_or_segment_name) - r = Route(sr.route_name) - - hevc_requested = any(camera_config[1:]) - if len(sr.seg_idxs) > 1 and hevc_requested: - print("You're requesting more than 1 segment with hevc videos, " + \ - "please be aware that might take a lot of memory " + \ - "since rerun isn't yet well supported for high resolution video logging") - response = input("Do you wish to continue? (Y/n): ") - if response.strip().lower() != "y": - sys.exit() - - rerunner = Rerunner(r, sr, camera_config) - rerunner.load_data() - diff --git a/tools/rerun/run.sh b/tools/rerun/run.sh deleted file mode 100755 index 0c026153603cbc..00000000000000 --- a/tools/rerun/run.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash - -# TODO: remove this file once Rerun has interface to set log message level -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" - -RUST_LOG=warn $DIR/run.py $@ - diff --git a/tools/scripts/adb_ssh.sh b/tools/scripts/adb_ssh.sh new file mode 100755 index 00000000000000..b9668e7e0b4335 --- /dev/null +++ b/tools/scripts/adb_ssh.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Forward all openpilot service ports +while IFS=' ' read -r name port; do + adb forward "tcp:${port}" "tcp:${port}" > /dev/null +done < <(python3 - <<'PY' +from cereal.services import SERVICE_LIST + +FNV_PRIME = 0x100000001b3 +FNV_OFFSET_BASIS = 0xcbf29ce484222325 +START_PORT = 8023 +MAX_PORT = 65535 +PORT_RANGE = MAX_PORT - START_PORT +MASK = 0xffffffffffffffff + +def fnv1a(endpoint: str) -> int: + h = FNV_OFFSET_BASIS + for b in endpoint.encode(): + h ^= b + h = (h * FNV_PRIME) & MASK + return h + +ports = set() +for name in SERVICE_LIST.keys(): + port = START_PORT + fnv1a(name) % PORT_RANGE + ports.add((name, port)) + +for name, port in sorted(ports): + print(f"{name} {port}") +PY +) + +# Forward SSH port, finding a free local port if 2222 is taken. +SSH_PORT=2222 +while ss -tln | grep -q ":${SSH_PORT} "; do + SSH_PORT=$((SSH_PORT + 1)) +done +adb forward tcp:${SSH_PORT} tcp:22 + +# SSH! +ssh comma@localhost -p ${SSH_PORT} "$@" diff --git a/tools/scripts/devsync.py b/tools/scripts/devsync.py new file mode 100755 index 00000000000000..98312dd5454491 --- /dev/null +++ b/tools/scripts/devsync.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +import argparse +import shlex +import subprocess +import threading +import time + +from watchdog.events import FileSystemEventHandler +from watchdog.observers import Observer + +from openpilot.common.basedir import BASEDIR + + +def build_rsync_cmd(args) -> list[str]: + ssh = [ + "ssh", + "-o", "ControlMaster=auto", + "-o", f"ControlPath=/tmp/devsync-{args.ip}.ctl", + "-o", "ControlPersist=10m", + "-o", "StrictHostKeyChecking=accept-new", + ] + if args.identity: + ssh += ["-i", args.identity] + + return [ + "rsync", "-az", + "--files-from=-", "--from0", + "-e", " ".join(shlex.quote(p) for p in ssh), + "--out-format=%n", + BASEDIR + "/", f"comma@{args.ip}:{args.remote}/", + ] + + +def git_tracked_files() -> bytes: + return subprocess.check_output( + ["git", "-C", BASEDIR, "ls-files", "--recurse-submodules", "-z"] + ) + + +class Handler(FileSystemEventHandler): + def __init__(self, sync_fn): + self.dirty = threading.Event() + self.sync_fn = sync_fn + + def on_any_event(self, event): + if not event.is_directory: + self.dirty.set() + + def run(self): + while True: + time.sleep(1) + if self.dirty.is_set(): + self.dirty.clear() + self.sync_fn() + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("ip", help="device IP / hostname") + p.add_argument("--remote", default="/data/openpilot", help="remote path on device") + p.add_argument("-i", "--identity", default=None, help="ssh identity file") + args = p.parse_args() + + print(f"[devsync] watching {BASEDIR}") + print(f"[devsync] target comma@{args.ip}:{args.remote}") + + def run_sync(): + file_list = git_tracked_files() + cmd = build_rsync_cmd(args) + t0 = time.monotonic() + r = subprocess.run(cmd, input=file_list, capture_output=True) + dt = time.monotonic() - t0 + if r.returncode: + print(f"[devsync] ERR rc={r.returncode} in {dt:.2f}s") + return + files = [ln for ln in r.stdout.decode().splitlines() if ln.strip()] + msg = f"{len(files)} files: {', '.join(files)}" if files else "no changes" + print(f"[devsync] {dt:.2f}s · {msg}") + + run_sync() + + handler = Handler(run_sync) + obs = Observer() + obs.schedule(handler, BASEDIR, recursive=True) + obs.start() + handler.run() + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("\n[devsync] stopping") diff --git a/tools/scripts/extract_audio.py b/tools/scripts/extract_audio.py new file mode 100755 index 00000000000000..2a6ad9f9e3ab5b --- /dev/null +++ b/tools/scripts/extract_audio.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +import os +import sys +import wave +import argparse +import numpy as np + +from openpilot.tools.lib.logreader import LogReader, ReadMode + + +def extract_audio(route_or_segment_name, output_file=None, play=False): + lr = LogReader(route_or_segment_name, default_mode=ReadMode.AUTO_INTERACTIVE) + audio_messages = list(lr.filter("rawAudioData")) + if not audio_messages: + print("No rawAudioData messages found in logs") + return + sample_rate = audio_messages[0].sampleRate + + audio_chunks = [] + total_frames = 0 + for msg in audio_messages: + audio_array = np.frombuffer(msg.data, dtype=np.int16) + audio_chunks.append(audio_array) + total_frames += len(audio_array) + full_audio = np.concatenate(audio_chunks) + + print(f"Found {total_frames} frames from {len(audio_messages)} audio messages at {sample_rate} Hz") + + if output_file: + if write_wav_file(output_file, full_audio, sample_rate): + print(f"Audio written to {output_file}") + else: + print("Audio extraction canceled.") + if play: + play_audio(full_audio, sample_rate) + + +def write_wav_file(filename, audio_data, sample_rate): + if os.path.exists(filename): + if input(f"File '{filename}' exists. Overwrite? (y/N): ").lower() not in ['y', 'yes']: + return False + + with wave.open(filename, 'wb') as wav_file: + wav_file.setnchannels(1) # Mono + wav_file.setsampwidth(2) # 16-bit + wav_file.setframerate(sample_rate) + wav_file.writeframes(audio_data.tobytes()) + return True + + +def play_audio(audio_data, sample_rate): + try: + import sounddevice as sd + + print("Playing audio... Press Ctrl+C to stop") + sd.play(audio_data, sample_rate) + sd.wait() + except KeyboardInterrupt: + print("\nPlayback stopped") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Extract audio data from openpilot logs") + parser.add_argument("-o", "--output", help="Output WAV file path") + parser.add_argument("--play", action="store_true", help="Play audio with sounddevice") + parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name") + + if len(sys.argv) == 1: + parser.print_help() + sys.exit() + args = parser.parse_args() + + output_file = args.output + if not args.output and not args.play: + output_file = "extracted_audio.wav" + + extract_audio(args.route_or_segment_name.strip(), output_file, args.play) diff --git a/tools/scripts/fetch_image_from_route.py b/tools/scripts/fetch_image_from_route.py index b59e7c895e7693..77bf48f946a7fa 100755 --- a/tools/scripts/fetch_image_from_route.py +++ b/tools/scripts/fetch_image_from_route.py @@ -31,13 +31,13 @@ segments = r.json()[camera] if segment >= len(segments): - raise Exception("segment %d not found, got %d segments" % (segment, len(segments))) + raise Exception(f"segment {segment} not found, got {len(segments)} segments") fr = FrameReader(segments[segment]) if frame >= fr.frame_count: - raise Exception("frame %d not found, got %d frames" % (frame, fr.frame_count)) + raise Exception("frame {frame} not found, got {fr.frame_count} frames") -im = Image.fromarray(fr.get(frame, count=1, pix_fmt="rgb24")[0]) +im = Image.fromarray(fr.get(frame)) fn = f"uxxx_{route.replace('|', '_')}_{segment}_{frame}.png" im.save(fn) print(f"saved {fn}") diff --git a/tools/scripts/setup_ssh_keys.py b/tools/scripts/setup_ssh_keys.py index 699765eee1d565..e599dd3c5d6e4b 100755 --- a/tools/scripts/setup_ssh_keys.py +++ b/tools/scripts/setup_ssh_keys.py @@ -15,9 +15,9 @@ if keys.status_code == 200: params = Params() - params.put_bool("SshEnabled", True) - params.put("GithubSshKeys", keys.text) - params.put("GithubUsername", username) - print("Setup ssh keys successfully") + params.put_bool("SshEnabled", True, block=True) + params.put("GithubSshKeys", keys.text, block=True) + params.put("GithubUsername", username, block=True) + print("Set up ssh keys successfully") else: print("Error getting public keys from github") diff --git a/tools/scripts/ssh.py b/tools/scripts/ssh.py new file mode 100755 index 00000000000000..e454afb6912f65 --- /dev/null +++ b/tools/scripts/ssh.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import os +import sys +import argparse +import re + +from openpilot.common.basedir import BASEDIR +from openpilot.tools.lib.auth_config import get_token +from openpilot.tools.lib.api import CommaApi + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="A helper for connecting to devices over the comma prime SSH proxy.\ + Adding your SSH key to your SSH config is recommended for more convenient use; see https://docs.comma.ai/how-to/connect-to-comma/.") + parser.add_argument("device", help="device name or dongle id") + parser.add_argument("--host", help="ssh jump server host", default="ssh.comma.ai") + parser.add_argument("--port", help="ssh jump server port", default=22, type=int) + parser.add_argument("--key", help="ssh key", default=os.path.join(BASEDIR, "system/hardware/tici/id_rsa")) + parser.add_argument("--debug", help="enable debug output", action="store_true") + args = parser.parse_args() + + r = CommaApi(get_token()).get("v1/me/devices") + devices = {x['dongle_id']: x['alias'] for x in r} + + if not re.match("[0-9a-zA-Z]{16}", args.device): + user_input = args.device.replace(" ", "").lower() + matches = { k: v for k, v in devices.items() if isinstance(v, str) and user_input in v.replace(" ", "").lower() } + if len(matches) == 1: + dongle_id = list(matches.keys())[0] + else: + print(f"failed to look up dongle id for \"{args.device}\"", file=sys.stderr) + if len(matches) > 1: + print("found multiple matches:", file=sys.stderr) + for k, v in matches.items(): + print(f" \"{v}\" ({k})", file=sys.stderr) + exit(1) + else: + dongle_id = args.device + + name = dongle_id + if dongle_id in devices: + name = f"{devices[dongle_id]} ({dongle_id})" + print(f"connecting to {name} through {args.host}:{args.port} ...") + + command = [ + "ssh", + "-i", args.key, + "-o", f"ProxyCommand=ssh -i {args.key} -W %h:%p -p %p %h@{args.host}", + "-p", str(args.port), + ] + if args.debug: + command += ["-v"] + command += [ + f"comma@comma-{dongle_id}", + ] + if args.debug: + print(" ".join([f"'{c}'" if " " in c else c for c in command])) + os.execvp(command[0], command) diff --git a/tools/setup.sh b/tools/setup.sh index e0a9a4f6a6325e..dafd466ef92bd1 100755 --- a/tools/setup.sh +++ b/tools/setup.sh @@ -1,6 +1,5 @@ #!/usr/bin/env bash - -set -e +set -euo pipefail RED='\033[0;31m' GREEN='\033[0;32m' @@ -34,39 +33,6 @@ cat << 'EOF' EOF } -function sentry_send_event() { - SENTRY_KEY=dd0cba62ba0ac07ff9f388f8f1e6a7f4 - SENTRY_URL=https://sentry.io/api/4507726145781760/store/ - - EVENT=$1 - EVENT_TYPE=${2:-$EVENT} - EVENT_LOG=${3:-"NA"} - - PLATFORM=$(uname -s) - ARCH=$(uname -m) - SYSTEM=$(uname -a) - if [[ $PLATFORM == "Darwin" ]]; then - OS="macos" - elif [[ $PLATFORM == "Linux" ]]; then - OS="linux" - fi - - if [[ $ARCH == armv8* ]] || [[ $ARCH == arm64* ]] || [[ $ARCH == aarch64* ]]; then - ARCH="aarch64" - elif [[ $ARCH == "x86_64" ]] || [[ $ARCH == i686* ]]; then - ARCH="x86" - fi - - PYTHON_VERSION=$(echo $(python3 --version 2> /dev/null || echo "NA")) - BRANCH=$(echo $(git -C $OPENPILOT_ROOT rev-parse --abbrev-ref HEAD 2> /dev/null || echo "NA")) - COMMIT=$(echo $(git -C $OPENPILOT_ROOT rev-parse HEAD 2> /dev/null || echo "NA")) - - curl -s -o /dev/null -X POST -g --data "{ \"exception\": { \"values\": [{ \"type\": \"$EVENT\" }] }, \"tags\" : { \"event_type\" : \"$EVENT_TYPE\", \"event_log\" : \"$EVENT_LOG\", \"os\" : \"$OS\", \"arch\" : \"$ARCH\", \"python_version\" : \"$PYTHON_VERSION\" , \"git_branch\" : \"$BRANCH\", \"git_commit\" : \"$COMMIT\", \"system\" : \"$SYSTEM\" } }" \ - -H 'Content-Type: application/json' \ - -H "X-Sentry-Auth: Sentry sentry_version=7, sentry_key=$SENTRY_KEY, sentry_client=op_setup/0.1" \ - $SENTRY_URL 2> /dev/null -} - function check_stdin() { if [ -t 0 ]; then INTERACTIVE=1 @@ -132,7 +98,6 @@ function check_git() { echo "Checking for git..." if ! command -v "git" > /dev/null 2>&1; then echo -e " ↳ [${RED}✗${NC}] git not found on your system, can't continue!" - sentry_send_event "SETUP_FAILURE" "ERROR_GIT_NOT_FOUND" return 1 else echo -e " ↳ [${GREEN}✔${NC}] git found.\n" @@ -151,7 +116,6 @@ function git_clone() { fi echo -e " ↳ [${RED}✗${NC}] failed to clone openpilot!" - sentry_send_event "SETUP_FAILURE" "ERROR_GIT_CLONE" return 1 } @@ -160,18 +124,9 @@ function install_with_op() { $OPENPILOT_ROOT/tools/op.sh install $OPENPILOT_ROOT/tools/op.sh post-commit - LOG_FILE=$(mktemp) - - if ! $OPENPILOT_ROOT/tools/op.sh --log $LOG_FILE setup; then + if ! $OPENPILOT_ROOT/tools/op.sh setup; then echo -e "\n[${RED}✗${NC}] failed to install openpilot!" - - ERROR_TYPE="$(cat "$LOG_FILE" | sed '1p;d')" - ERROR_LOG="$(cat "$LOG_FILE" | sed '2p;d')" - sentry_send_event "SETUP_FAILURE" "$ERROR_TYPE" "$ERROR_LOG" || true - return 1 - else - sentry_send_event "SETUP_SUCCESS" || true fi echo -e "\n----------------------------------------------------------------------" diff --git a/tools/setup_dependencies.sh b/tools/setup_dependencies.sh new file mode 100755 index 00000000000000..3fb7165a5097f3 --- /dev/null +++ b/tools/setup_dependencies.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +ROOT="$(cd "$DIR/../" && pwd)" + +function retry() { + local attempts=$1 + shift + for i in $(seq 1 "$attempts"); do + if "$@"; then + return 0 + fi + if [ "$i" -lt "$attempts" ]; then + echo " Attempt $i/$attempts failed, retrying in 5s..." + sleep 5 + fi + done + return 1 +} + +function install_linux_deps() { + SUDO="" + + if [[ ! $(id -u) -eq 0 ]]; then + if [[ -z $(which sudo) ]]; then + echo "Please install sudo or run as root" + exit 1 + fi + SUDO="sudo" + fi + + # normal stuff, this mostly for bare docker images + if command -v apt-get > /dev/null 2>&1; then + $SUDO apt-get update + $SUDO apt-get install -y --no-install-recommends ca-certificates build-essential curl libcurl4-openssl-dev locales git + elif command -v dnf > /dev/null 2>&1; then + $SUDO dnf install -y ca-certificates gcc gcc-c++ make curl libcurl-devel glibc-langpack-en git + elif command -v yum > /dev/null 2>&1; then + $SUDO yum install -y ca-certificates gcc gcc-c++ make curl libcurl-devel glibc-langpack-en git + elif command -v pacman > /dev/null 2>&1; then + $SUDO pacman -Syu --noconfirm --needed base-devel ca-certificates curl git + elif command -v zypper > /dev/null 2>&1; then + $SUDO zypper --non-interactive refresh + $SUDO zypper --non-interactive install ca-certificates gcc gcc-c++ make curl libcurl-devel glibc-locale git + elif command -v apk > /dev/null 2>&1; then + $SUDO apk add --no-cache ca-certificates build-base curl curl-dev musl-locales git + elif command -v xbps-install > /dev/null 2>&1; then + $SUDO xbps-install -Syu base-devel ca-certificates curl git libcurl-devel glibc-locales + else + echo "Unsupported Linux distribution. Supported package managers: apt-get, dnf, yum, pacman, zypper, apk, xbps-install." + exit 1 + fi + + if [[ -d "/etc/udev/rules.d/" ]]; then + $SUDO tee /etc/udev/rules.d/11-openpilot.rules > /dev/null <<-EOF + # Panda Jungle devices + SUBSYSTEM=="usb", ATTRS{idVendor}=="3801", ATTRS{idProduct}=="ddcf", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="3801", ATTRS{idProduct}=="ddef", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="bbaa", ATTRS{idProduct}=="ddcf", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="bbaa", ATTRS{idProduct}=="ddef", MODE="0666" + + # Panda devices + SUBSYSTEM=="usb", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="df11", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="3801", ATTRS{idProduct}=="ddcc", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="3801", ATTRS{idProduct}=="ddee", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="bbaa", ATTRS{idProduct}=="ddcc", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="bbaa", ATTRS{idProduct}=="ddee", MODE="0666" + + # comma devices over ADB + SUBSYSTEM=="usb", ATTR{idVendor}=="04d8", ATTR{idProduct}=="1234", ENV{adb_user}="yes" + EOF + + # delete the old ones + $SUDO rm -f /etc/udev/rules.d/11-panda.rules /etc/udev/rules.d/12-panda_jungle.rules /etc/udev/rules.d/50-comma-adb.rules + + $SUDO udevadm control --reload-rules && $SUDO udevadm trigger || true + fi +} + +function install_python_deps() { + # Increase the pip timeout to handle TimeoutError + export PIP_DEFAULT_TIMEOUT=200 + + cd "$ROOT" + + if ! command -v "uv" > /dev/null 2>&1; then + echo "installing uv..." + # TODO: outer retry can be removed once https://github.com/axodotdev/cargo-dist/pull/2311 is merged + retry 3 sh -c 'curl --retry 5 --retry-delay 5 --retry-all-errors -LsSf https://astral.sh/uv/install.sh | UV_GITHUB_TOKEN="${GITHUB_TOKEN:-}" sh' + UV_BIN="$HOME/.local/bin" + PATH="$UV_BIN:$PATH" + fi + + echo "updating uv..." + # ok to fail, can also fail due to installing with brew + uv self update || true + + echo "installing python packages..." + uv sync --frozen --all-extras + source .venv/bin/activate +} + +# --- Main --- + +if [[ "$OSTYPE" == "linux-gnu"* ]]; then + install_linux_deps + echo "[ ] installed system dependencies t=$SECONDS" +elif [[ "$OSTYPE" == "darwin"* ]]; then + if [[ $SHELL == "/bin/zsh" ]]; then + RC_FILE="$HOME/.zshrc" + elif [[ $SHELL == "/bin/bash" ]]; then + RC_FILE="$HOME/.bash_profile" + fi +fi + +if [ -f "$ROOT/pyproject.toml" ]; then + install_python_deps + echo "[ ] installed python dependencies t=$SECONDS" +fi + +if [[ "$OSTYPE" == "darwin"* ]] && [[ -n "${RC_FILE:-}" ]]; then + echo + echo "---- OPENPILOT SETUP DONE ----" + echo "Open a new shell or configure your active shell env by running:" + echo "source $RC_FILE" +fi diff --git a/tools/sim/bridge/common.py b/tools/sim/bridge/common.py index be1d7505a3ef13..499420ec4b2a41 100644 --- a/tools/sim/bridge/common.py +++ b/tools/sim/bridge/common.py @@ -1,6 +1,7 @@ import signal import threading import functools +import numpy as np from collections import namedtuple from enum import Enum @@ -9,7 +10,6 @@ from opendbc.car.honda.values import CruiseButtons from openpilot.common.params import Params -from openpilot.common.numpy_fast import clip from openpilot.common.realtime import Ratekeeper from openpilot.selfdrive.test.helpers import set_params_enabled from openpilot.tools.sim.lib.common import SimulatorState, World @@ -40,19 +40,18 @@ class SimulatorBridge(ABC): def __init__(self, dual_camera, high_quality): set_params_enabled() self.params = Params() - self.params.put_bool("ExperimentalLongitudinalEnabled", True) + self.params.put_bool("AlphaLongitudinalEnabled", True, block=True) self.rk = Ratekeeper(100, None) self.dual_camera = dual_camera self.high_quality = high_quality - self._exit_event = threading.Event() + self._exit_event: threading.Event | None = None self._threads = [] self._keep_alive = True self.started = Value('i', False) signal.signal(signal.SIGTERM, self._on_shutdown) - self._exit = threading.Event() self.simulator_state = SimulatorState() self.world: World | None = None @@ -76,7 +75,9 @@ def bridge_keep_alive(self, q: Queue, retries: int): def close(self, reason): self.started.value = False - self._exit_event.set() + + if self._exit_event is not None: + self._exit_event.set() if self.world is not None: self.world.close(reason) @@ -103,6 +104,8 @@ def _run(self, q: Queue): self.simulated_car = SimulatedCar() self.simulated_sensors = SimulatedSensors(self.dual_camera) + self._exit_event = threading.Event() + self.simulated_car_thread = threading.Thread(target=rk_loop, args=(functools.partial(self.simulated_car.update, self.simulator_state), 100, self._exit_event)) self.simulated_car_thread.start() @@ -170,8 +173,8 @@ def _run(self, q: Queue): self.simulator_state.is_engaged = self.simulated_car.sm['selfdriveState'].active if self.simulator_state.is_engaged: - throttle_op = clip(self.simulated_car.sm['carControl'].actuators.accel / 1.6, 0.0, 1.0) - brake_op = clip(-self.simulated_car.sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) + throttle_op = np.clip(self.simulated_car.sm['carControl'].actuators.accel / 1.6, 0.0, 1.0) + brake_op = np.clip(-self.simulated_car.sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) steer_op = self.simulated_car.sm['carControl'].actuators.steeringAngleDeg self.past_startup_engaged = True diff --git a/tools/sim/bridge/metadrive/metadrive_common.py b/tools/sim/bridge/metadrive/metadrive_common.py index 42a7eb60dd47c6..0106579b20c656 100644 --- a/tools/sim/bridge/metadrive/metadrive_common.py +++ b/tools/sim/bridge/metadrive/metadrive_common.py @@ -13,11 +13,9 @@ def __init__(self, *args, **kwargs): def get_rgb_array_cpu(self): origin_img = self.cpu_texture - img = np.frombuffer(origin_img.getRamImage().getData(), dtype=np.uint8) - img = img.reshape((origin_img.getYSize(), origin_img.getXSize(), -1)) - img = img[:,:,:3] # RGBA to RGB - # img = np.swapaxes(img, 1, 0) - img = img[::-1] # Flip on vertical axis + img = np.frombuffer(origin_img.getRamImageAs("RGB").getData(), dtype=np.uint8) + img = img.reshape((origin_img.getYSize(), origin_img.getXSize(), 3)) + img = img[::-1] # Flip on vertical axis return img diff --git a/tools/sim/bridge/metadrive/metadrive_world.py b/tools/sim/bridge/metadrive/metadrive_world.py index 5bb4555dc1e97d..c5111289d01394 100644 --- a/tools/sim/bridge/metadrive/metadrive_world.py +++ b/tools/sim/bridge/metadrive/metadrive_world.py @@ -105,7 +105,7 @@ def read_sensors(self, state: SimulatorState): if x_dist >= dist_threshold or y_dist >= dist_threshold: # position not the same during staying still, > threshold is considered moving self.distance_moved += x_dist + y_dist - time_check_threshold = 30 + time_check_threshold = 29 current_time = time.monotonic() since_last_check = current_time - self.last_check_timestamp if since_last_check >= time_check_threshold: diff --git a/tools/sim/launch_openpilot.sh b/tools/sim/launch_openpilot.sh index fa5ac731bd3e8f..392f365d037c9b 100755 --- a/tools/sim/launch_openpilot.sh +++ b/tools/sim/launch_openpilot.sh @@ -6,7 +6,7 @@ export SIMULATION="1" export SKIP_FW_QUERY="1" export FINGERPRINT="HONDA_CIVIC_2022" -export BLOCK="${BLOCK},camerad,loggerd,encoderd,micd,logmessaged" +export BLOCK="${BLOCK},camerad,loggerd,encoderd,micd,logmessaged,manage_athenad" if [[ "$CI" ]]; then # TODO: offscreen UI should work export BLOCK="${BLOCK},ui" diff --git a/tools/sim/lib/camerad.py b/tools/sim/lib/camerad.py index b58cbeaaf26334..7634b8524d1716 100644 --- a/tools/sim/lib/camerad.py +++ b/tools/sim/lib/camerad.py @@ -1,14 +1,39 @@ import numpy as np -import os -import pyopencl as cl -import pyopencl.array as cl_array from msgq.visionipc import VisionIpcServer, VisionStreamType from cereal import messaging -from openpilot.common.basedir import BASEDIR from openpilot.tools.sim.lib.common import W, H + +def rgb_to_nv12(rgb): + """Convert RGB image to NV12 (YUV420) format using BT.601 coefficients.""" + h, w = rgb.shape[:2] + r = rgb[:, :, 0].astype(np.int32) + g = rgb[:, :, 1].astype(np.int32) + b = rgb[:, :, 2].astype(np.int32) + + # Y plane - BT.601 coefficients (matches original OpenCL kernel) + y = (((b * 13 + g * 65 + r * 33) + 64) >> 7) + 16 + y = np.clip(y, 0, 255).astype(np.uint8) + + # Subsample RGB for UV (2x2 box filter) + r_sub = (r[0::2, 0::2] + r[0::2, 1::2] + r[1::2, 0::2] + r[1::2, 1::2] + 2) >> 2 + g_sub = (g[0::2, 0::2] + g[0::2, 1::2] + g[1::2, 0::2] + g[1::2, 1::2] + 2) >> 2 + b_sub = (b[0::2, 0::2] + b[0::2, 1::2] + b[1::2, 0::2] + b[1::2, 1::2] + 2) >> 2 + + # U and V planes + u = np.clip((b_sub * 56 - g_sub * 37 - r_sub * 19 + 0x8080) >> 8, 0, 255).astype(np.uint8) + v = np.clip((r_sub * 56 - g_sub * 47 - b_sub * 9 + 0x8080) >> 8, 0, 255).astype(np.uint8) + + # Interleave UV for NV12 format + uv = np.empty((h // 2, w), dtype=np.uint8) + uv[:, 0::2] = u + uv[:, 1::2] = v + + return np.concatenate([y.ravel(), uv.ravel()]).tobytes() + + class Camerad: """Simulates the camerad daemon""" def __init__(self, dual_camera): @@ -18,24 +43,12 @@ def __init__(self, dual_camera): self.frame_wide_id = 0 self.vipc_server = VisionIpcServer("camerad") - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 5, False, W, H) + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 5, W, H) if dual_camera: - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 5, False, W, H) + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 5, W, H) self.vipc_server.start_listener() - # set up for pyopencl rgb to yuv conversion - self.ctx = cl.create_some_context() - self.queue = cl.CommandQueue(self.ctx) - cl_arg = f" -DHEIGHT={H} -DWIDTH={W} -DRGB_STRIDE={W * 3} -DUV_WIDTH={W // 2} -DUV_HEIGHT={H // 2} -DRGB_SIZE={W * H} -DCL_DEBUG " - - kernel_fn = os.path.join(BASEDIR, "tools/sim/rgb_to_nv12.cl") - with open(kernel_fn) as f: - prg = cl.Program(self.ctx, f.read()).build(cl_arg) - self.krnl = prg.rgb_to_nv12 - self.Wdiv4 = W // 4 if (W % 4 == 0) else (W + (4 - W % 4)) // 4 - self.Hdiv4 = H // 4 if (H % 4 == 0) else (H + (4 - H % 4)) // 4 - def cam_send_yuv_road(self, yuv): self._send_yuv(yuv, self.frame_road_id, 'roadCameraState', VisionStreamType.VISION_STREAM_ROAD) self.frame_road_id += 1 @@ -44,16 +57,11 @@ def cam_send_yuv_wide_road(self, yuv): self._send_yuv(yuv, self.frame_wide_id, 'wideRoadCameraState', VisionStreamType.VISION_STREAM_WIDE_ROAD) self.frame_wide_id += 1 - # Returns: yuv bytes def rgb_to_yuv(self, rgb): + """Convert RGB to NV12 YUV format.""" assert rgb.shape == (H, W, 3), f"{rgb.shape}" assert rgb.dtype == np.uint8 - - rgb_cl = cl_array.to_device(self.queue, rgb) - yuv_cl = cl_array.empty_like(rgb_cl) - self.krnl(self.queue, (self.Wdiv4, self.Hdiv4), None, rgb_cl.data, yuv_cl.data).wait() - yuv = np.resize(yuv_cl.get(), rgb.size // 2) - return yuv.data.tobytes() + return rgb_to_nv12(rgb) def _send_yuv(self, yuv, frame_id, pub_type, yuv_type): eof = int(frame_id * 0.05 * 1e9) diff --git a/tools/sim/lib/manual_ctrl.py b/tools/sim/lib/manual_ctrl.py index 972f7023bb9323..c2be0d0458eb62 100755 --- a/tools/sim/lib/manual_ctrl.py +++ b/tools/sim/lib/manual_ctrl.py @@ -133,8 +133,8 @@ def wheel_poll_thread(q: 'Queue[str]') -> NoReturn: button_name_list.append(btn_name) button_states[btn_name] = 0 - print('%d axes found: %s' % (num_axes, ', '.join(axis_name_list))) - print('%d buttons found: %s' % (num_buttons, ', '.join(button_name_list))) + print(f'{num_axes} axes found: {", ".join(axis_name_list)}') + print(f'{num_buttons} buttons found: {", ".join(button_name_list)}') # Enable FF import evdev diff --git a/tools/sim/lib/simulated_car.py b/tools/sim/lib/simulated_car.py index 253623ded7222a..03da594769d604 100644 --- a/tools/sim/lib/simulated_car.py +++ b/tools/sim/lib/simulated_car.py @@ -1,16 +1,17 @@ +import traceback import cereal.messaging as messaging from opendbc.can.packer import CANPacker from opendbc.can.parser import CANParser +from opendbc.car.honda.values import HondaSafetyFlags from openpilot.common.params import Params from openpilot.selfdrive.pandad.pandad_api_impl import can_list_to_can_capnp from openpilot.tools.sim.lib.common import SimulatorState -from panda.python import Panda class SimulatedCar: """Simulates a honda civic 2022 (panda state + can messages) to OpenPilot""" - packer = CANPacker("honda_civic_ex_2022_can_generated") + packer = CANPacker("honda_bosch_radarless_generated") def __init__(self): self.pm = messaging.PubMaster(['can', 'pandaStates']) @@ -22,7 +23,7 @@ def __init__(self): @staticmethod def get_car_can_parser(): - dbc_f = 'honda_civic_ex_2022_can_generated' + dbc_f = 'honda_bosch_radarless_generated' checks = [] return CANParser(dbc_f, checks, 0) @@ -45,7 +46,7 @@ def send_can_messages(self, simulator_state: SimulatorState): msg.append(self.packer.make_can_msg("SCM_BUTTONS", 0, {"CRUISE_BUTTONS": simulator_state.cruise_button})) - msg.append(self.packer.make_can_msg("GEARBOX", 0, {"GEAR": 4, "GEAR_SHIFTER": 8})) + msg.append(self.packer.make_can_msg("GEARBOX_AUTO", 0, {"GEAR_SHIFTER": 4})) msg.append(self.packer.make_can_msg("GAS_PEDAL_2", 0, {})) msg.append(self.packer.make_can_msg("SEATBELT_STATUS", 0, {"SEATBELT_DRIVER_LATCHED": 1})) msg.append(self.packer.make_can_msg("STEER_STATUS", 0, {"STEER_TORQUE_SENSOR": simulator_state.user_torque})) @@ -55,7 +56,6 @@ def send_can_messages(self, simulator_state: SimulatorState): msg.append(self.packer.make_can_msg("STEER_MOTOR_TORQUE", 0, {})) msg.append(self.packer.make_can_msg("EPB_STATUS", 0, {})) msg.append(self.packer.make_can_msg("DOORS_STATUS", 0, {})) - msg.append(self.packer.make_can_msg("CRUISE_PARAMS", 0, {})) msg.append(self.packer.make_can_msg("CRUISE", 0, {})) msg.append(self.packer.make_can_msg("CRUISE_FAULT_STATUS", 0, {})) msg.append(self.packer.make_can_msg("SCM_FEEDBACK", 0, @@ -84,7 +84,7 @@ def send_panda_state(self, simulator_state): if self.params.get_bool("ObdMultiplexingEnabled") != self.obd_multiplexing: self.obd_multiplexing = not self.obd_multiplexing - self.params.put_bool("ObdMultiplexingChanged", True) + self.params.put_bool("ObdMultiplexingChanged", True, block=True) dat = messaging.new_message('pandaStates', 1) dat.valid = True @@ -94,14 +94,18 @@ def send_panda_state(self, simulator_state): 'controlsAllowed': True, 'safetyModel': 'hondaBosch', 'alternativeExperience': self.sm["carParams"].alternativeExperience, - 'safetyParam': Panda.FLAG_HONDA_RADARLESS | Panda.FLAG_HONDA_BOSCH_LONG, + 'safetyParam': HondaSafetyFlags.RADARLESS.value | HondaSafetyFlags.BOSCH_LONG.value, } self.pm.send('pandaStates', dat) def update(self, simulator_state: SimulatorState): - self.send_can_messages(simulator_state) + try: + self.send_can_messages(simulator_state) - if self.idx % 50 == 0: # only send panda states at 2hz - self.send_panda_state(simulator_state) + if self.idx % 50 == 0: # only send panda states at 2hz + self.send_panda_state(simulator_state) - self.idx += 1 + self.idx += 1 + except Exception: + traceback.print_exc() + raise diff --git a/tools/sim/lib/simulated_sensors.py b/tools/sim/lib/simulated_sensors.py index e78f9847365567..d6d822c582bbe1 100644 --- a/tools/sim/lib/simulated_sensors.py +++ b/tools/sim/lib/simulated_sensors.py @@ -23,17 +23,12 @@ def __init__(self, dual_camera=False): def send_imu_message(self, simulator_state: 'SimulatorState'): for _ in range(5): dat = messaging.new_message('accelerometer', valid=True) - dat.accelerometer.sensor = 4 - dat.accelerometer.type = 0x10 dat.accelerometer.timestamp = dat.logMonoTime # TODO: use the IMU timestamp dat.accelerometer.init('acceleration') dat.accelerometer.acceleration.v = [simulator_state.imu.accelerometer.x, simulator_state.imu.accelerometer.y, simulator_state.imu.accelerometer.z] self.pm.send('accelerometer', dat) - # copied these numbers from locationd dat = messaging.new_message('gyroscope', valid=True) - dat.gyroscope.sensor = 5 - dat.gyroscope.type = 0x10 dat.gyroscope.timestamp = dat.logMonoTime # TODO: use the IMU timestamp dat.gyroscope.init('gyroUncalibrated') dat.gyroscope.gyroUncalibrated.v = [simulator_state.imu.gyroscope.x, simulator_state.imu.gyroscope.y, simulator_state.imu.gyroscope.z] @@ -53,7 +48,7 @@ def send_gps_message(self, simulator_state: 'SimulatorState'): for _ in range(10): dat = messaging.new_message('gpsLocationExternal', valid=True) dat.gpsLocationExternal = { - "unixTimestampMillis": int(time.time() * 1000), + "unixTimestampMillis": int(time.time() * 1000), # noqa: TID251 "flags": 1, # valid fix "horizontalAccuracy": 1.0, "verticalAccuracy": 1.0, @@ -92,11 +87,12 @@ def send_fake_driver_monitoring(self): # dmonitoringd output dat = messaging.new_message('driverMonitoringState', valid=True) - dat.driverMonitoringState = { - "faceDetected": True, - "isDistracted": False, - "awarenessStatus": 1., - } + dm = dat.driverMonitoringState + dm.alertLevel = log.DriverMonitoringState.AlertLevel.none + dm.activePolicy = log.DriverMonitoringState.MonitoringPolicy.vision + dm.visionPolicyState.faceDetected = True + dm.visionPolicyState.isDistracted = False + dm.visionPolicyState.awarenessPercent = 100 self.pm.send('driverMonitoringState', dat) def send_camera_images(self, world: 'World'): @@ -109,7 +105,7 @@ def send_camera_images(self, world: 'World'): self.camerad.cam_send_yuv_wide_road(yuv) def update(self, simulator_state: 'SimulatorState', world: 'World'): - now = time.time() + now = time.monotonic() self.send_imu_message(simulator_state) self.send_gps_message(simulator_state) diff --git a/tools/sim/rgb_to_nv12.cl b/tools/sim/rgb_to_nv12.cl deleted file mode 100644 index 54816d5d7d5202..00000000000000 --- a/tools/sim/rgb_to_nv12.cl +++ /dev/null @@ -1,119 +0,0 @@ -#define RGB_TO_Y(r, g, b) ((((mul24(b, 13) + mul24(g, 65) + mul24(r, 33)) + 64) >> 7) + 16) -#define RGB_TO_U(r, g, b) ((mul24(b, 56) - mul24(g, 37) - mul24(r, 19) + 0x8080) >> 8) -#define RGB_TO_V(r, g, b) ((mul24(r, 56) - mul24(g, 47) - mul24(b, 9) + 0x8080) >> 8) -#define AVERAGE(x, y, z, w) ((convert_ushort(x) + convert_ushort(y) + convert_ushort(z) + convert_ushort(w) + 1) >> 1) - -inline void convert_2_ys(__global uchar * out_yuv, int yi, const uchar8 rgbs1) { - uchar2 yy = (uchar2)( - RGB_TO_Y(rgbs1.s2, rgbs1.s1, rgbs1.s0), - RGB_TO_Y(rgbs1.s5, rgbs1.s4, rgbs1.s3) - ); -#ifdef CL_DEBUG - if(yi >= RGB_SIZE) - printf("Y vector2 overflow, %d > %d\n", yi, RGB_SIZE); -#endif - vstore2(yy, 0, out_yuv + yi); -} - -inline void convert_4_ys(__global uchar * out_yuv, int yi, const uchar8 rgbs1, const uchar8 rgbs3) { - const uchar4 yy = (uchar4)( - RGB_TO_Y(rgbs1.s2, rgbs1.s1, rgbs1.s0), - RGB_TO_Y(rgbs1.s5, rgbs1.s4, rgbs1.s3), - RGB_TO_Y(rgbs3.s0, rgbs1.s7, rgbs1.s6), - RGB_TO_Y(rgbs3.s3, rgbs3.s2, rgbs3.s1) - ); -#ifdef CL_DEBUG - if(yi > RGB_SIZE - 4) - printf("Y vector4 overflow, %d > %d\n", yi, RGB_SIZE - 4); -#endif - vstore4(yy, 0, out_yuv + yi); -} - -inline void convert_uv(__global uchar * out_yuv, int uvi, - const uchar8 rgbs1, const uchar8 rgbs2) { - // U & V: average of 2x2 pixels square - const short ab = AVERAGE(rgbs1.s0, rgbs1.s3, rgbs2.s0, rgbs2.s3); - const short ag = AVERAGE(rgbs1.s1, rgbs1.s4, rgbs2.s1, rgbs2.s4); - const short ar = AVERAGE(rgbs1.s2, rgbs1.s5, rgbs2.s2, rgbs2.s5); -#ifdef CL_DEBUG - if(uvi >= RGB_SIZE + RGB_SIZE / 2) - printf("UV overflow, %d >= %d\n", uvi, RGB_SIZE + RGB_SIZE / 2); -#endif - out_yuv[uvi] = RGB_TO_U(ar, ag, ab); - out_yuv[uvi+1] = RGB_TO_V(ar, ag, ab); -} - -inline void convert_2_uvs(__global uchar * out_yuv, int uvi, - const uchar8 rgbs1, const uchar8 rgbs2, const uchar8 rgbs3, const uchar8 rgbs4) { - // U & V: average of 2x2 pixels square - const short ab1 = AVERAGE(rgbs1.s0, rgbs1.s3, rgbs2.s0, rgbs2.s3); - const short ag1 = AVERAGE(rgbs1.s1, rgbs1.s4, rgbs2.s1, rgbs2.s4); - const short ar1 = AVERAGE(rgbs1.s2, rgbs1.s5, rgbs2.s2, rgbs2.s5); - const short ab2 = AVERAGE(rgbs1.s6, rgbs3.s1, rgbs2.s6, rgbs4.s1); - const short ag2 = AVERAGE(rgbs1.s7, rgbs3.s2, rgbs2.s7, rgbs4.s2); - const short ar2 = AVERAGE(rgbs3.s0, rgbs3.s3, rgbs4.s0, rgbs4.s3); - uchar4 uv = (uchar4)( - RGB_TO_U(ar1, ag1, ab1), - RGB_TO_V(ar1, ag1, ab1), - RGB_TO_U(ar2, ag2, ab2), - RGB_TO_V(ar2, ag2, ab2) - ); -#ifdef CL_DEBUG1 - if(uvi > RGB_SIZE + RGB_SIZE / 2 - 4) - printf("UV2 overflow, %d >= %d\n", uvi, RGB_SIZE + RGB_SIZE / 2 - 2); -#endif - vstore4(uv, 0, out_yuv + uvi); -} - -__kernel void rgb_to_nv12(__global uchar const * const rgb, - __global uchar * out_yuv) -{ - const int dx = get_global_id(0); - const int dy = get_global_id(1); - const int col = mul24(dx, 4); // Current column in rgb image - const int row = mul24(dy, 4); // Current row in rgb image - const int bgri_start = mad24(row, RGB_STRIDE, mul24(col, 3)); // Start offset of rgb data being converted - const int yi_start = mad24(row, WIDTH, col); // Start offset in the target yuv buffer - int uvi = mad24(row / 2, WIDTH, RGB_SIZE + col); - int num_col = min(WIDTH - col, 4); - int num_row = min(HEIGHT - row, 4); - if(num_row == 4) { - const uchar8 rgbs0_0 = vload8(0, rgb + bgri_start); - const uchar8 rgbs0_1 = vload8(0, rgb + bgri_start + 8); - const uchar8 rgbs1_0 = vload8(0, rgb + bgri_start + RGB_STRIDE); - const uchar8 rgbs1_1 = vload8(0, rgb + bgri_start + RGB_STRIDE + 8); - const uchar8 rgbs2_0 = vload8(0, rgb + bgri_start + RGB_STRIDE * 2); - const uchar8 rgbs2_1 = vload8(0, rgb + bgri_start + RGB_STRIDE * 2 + 8); - const uchar8 rgbs3_0 = vload8(0, rgb + bgri_start + RGB_STRIDE * 3); - const uchar8 rgbs3_1 = vload8(0, rgb + bgri_start + RGB_STRIDE * 3 + 8); - if(num_col == 4) { - convert_4_ys(out_yuv, yi_start, rgbs0_0, rgbs0_1); - convert_4_ys(out_yuv, yi_start + WIDTH, rgbs1_0, rgbs1_1); - convert_4_ys(out_yuv, yi_start + WIDTH * 2, rgbs2_0, rgbs2_1); - convert_4_ys(out_yuv, yi_start + WIDTH * 3, rgbs3_0, rgbs3_1); - convert_2_uvs(out_yuv, uvi, rgbs0_0, rgbs1_0, rgbs0_1, rgbs1_1); - convert_2_uvs(out_yuv, uvi + WIDTH, rgbs2_0, rgbs3_0, rgbs2_1, rgbs3_1); - } else if(num_col == 2) { - convert_2_ys(out_yuv, yi_start, rgbs0_0); - convert_2_ys(out_yuv, yi_start + WIDTH, rgbs1_0); - convert_2_ys(out_yuv, yi_start + WIDTH * 2, rgbs2_0); - convert_2_ys(out_yuv, yi_start + WIDTH * 3, rgbs3_0); - convert_uv(out_yuv, uvi, rgbs0_0, rgbs1_0); - convert_uv(out_yuv, uvi + WIDTH, rgbs2_0, rgbs3_0); - } - } else { - const uchar8 rgbs0_0 = vload8(0, rgb + bgri_start); - const uchar8 rgbs0_1 = vload8(0, rgb + bgri_start + 8); - const uchar8 rgbs1_0 = vload8(0, rgb + bgri_start + RGB_STRIDE); - const uchar8 rgbs1_1 = vload8(0, rgb + bgri_start + RGB_STRIDE + 8); - if(num_col == 4) { - convert_4_ys(out_yuv, yi_start, rgbs0_0, rgbs0_1); - convert_4_ys(out_yuv, yi_start + WIDTH, rgbs1_0, rgbs1_1); - convert_2_uvs(out_yuv, uvi, rgbs0_0, rgbs1_0, rgbs0_1, rgbs1_1); - } else if(num_col == 2) { - convert_2_ys(out_yuv, yi_start, rgbs0_0); - convert_2_ys(out_yuv, yi_start + WIDTH, rgbs1_0); - convert_uv(out_yuv, uvi, rgbs0_0, rgbs1_0); - } - } -} diff --git a/tools/sim/tests/test_metadrive_bridge.py b/tools/sim/tests/test_metadrive_bridge.py index 8849e901cbbc8f..9be640d736e159 100644 --- a/tools/sim/tests/test_metadrive_bridge.py +++ b/tools/sim/tests/test_metadrive_bridge.py @@ -8,14 +8,10 @@ from openpilot.tools.sim.tests.test_sim_bridge import TestSimBridgeBase @pytest.mark.slow -@pytest.mark.filterwarnings("ignore::pyopencl.CompilerWarning") # Unimportant warning of non-empty compile log class TestMetaDriveBridge(TestSimBridgeBase): @pytest.fixture(autouse=True) def setup_create_bridge(self, test_duration): - # run bridge test for at least 60s, since not-moving check runs every 30s - if test_duration < 60: - test_duration = 60 - self.test_duration = test_duration + self.test_duration = 30 def create_bridge(self): return MetaDriveBridge(False, False, self.test_duration, True) diff --git a/tools/sim/tests/test_sim_bridge.py b/tools/sim/tests/test_sim_bridge.py index 12f38b86c31b85..d58cddff7fabf0 100644 --- a/tools/sim/tests/test_sim_bridge.py +++ b/tools/sim/tests/test_sim_bridge.py @@ -89,7 +89,4 @@ def teardown_method(self): p.terminate() for p in reversed(self.processes): - if isinstance(p, subprocess.Popen): - p.wait(15) - else: - p.join(15) + p.kill() diff --git a/tools/ubuntu_setup.sh b/tools/ubuntu_setup.sh deleted file mode 100755 index f425e14cf2f71d..00000000000000 --- a/tools/ubuntu_setup.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" - -# NOTE: this is used in a docker build, so do not run any scripts here. - -$DIR/install_ubuntu_dependencies.sh -$DIR/install_python_dependencies.sh diff --git a/tools/webcam/README.md b/tools/webcam/README.md index c756069bb5d683..6abbc47935ed21 100644 --- a/tools/webcam/README.md +++ b/tools/webcam/README.md @@ -1,37 +1,31 @@ # Run openpilot with webcam on PC What's needed: -- Ubuntu 24.04 +- Ubuntu 24.04 ([WSL2 is not supported](https://github.com/commaai/openpilot/issues/34216)) or macOS - GPU (recommended) -- Two USB webcams, at least 720p and 78 degrees FOV (e.g. Logitech C920/C615) -- [Car harness](https://comma.ai/shop/products/comma-car-harness) with black panda to connect to your car -- [Panda paw](https://comma.ai/shop/products/panda-paw) or USB-A to USB-A cable to connect panda to your computer -That's it! +- One USB webcam, at least 720p and 78 degrees FOV (e.g. Logitech C920/C615, NexiGo N60) +- [Car harness](https://comma.ai/shop/products/comma-car-harness) +- [panda](https://comma.ai/shop/panda) +- USB-A to USB-A cable to connect panda to your computer ## Setup openpilot -``` -cd ~ -git clone https://github.com/commaai/openpilot.git -``` -- Follow [this readme](https://github.com/commaai/openpilot/tree/master/tools) to install the requirements -- Install [OpenCL Driver](https://registrationcenter-download.intel.com/akdlm/irc_nas/vcp/15532/l_opencl_p_18.1.0.015.tgz) - -## Build openpilot for webcam -``` -cd ~/openpilot -USE_WEBCAM=1 scons -j$(nproc) -``` +- Follow [this readme](../README.md) to install and build the requirements ## Connect the hardware -- Connect the road facing camera first, then the driver facing camera -- (default indexes are 1 and 2; can be modified in system/camerad/cameras/camera_webcam.cc) +- Connect the camera first - Connect your computer to panda ## GO ``` -cd ~/openpilot/system/manager -NOSENSOR=1 USE_WEBCAM=1 ./manager.py +USE_WEBCAM=1 system/manager/manager.py ``` - Start the car, then the UI should show the road webcam's view -- Adjust and secure the webcams (you can run tools/webcam/front_mount_helper.py to help mount the driver camera) +- Adjust and secure the webcam - Finish calibration and engage! + +## Specify Cameras + +Use the `ROAD_CAM` (default 0) and optional `DRIVER_CAM`, `WIDE_CAM` environment variables to specify which camera is which (ie. `ROAD_CAM=1` uses `/dev/video1`, on Ubuntu, for the road camera): +``` +USE_WEBCAM=1 ROAD_CAM=1 system/manager/manager.py +``` diff --git a/tools/webcam/camera.py b/tools/webcam/camera.py index 8358846f3a017f..7926766c6f915a 100644 --- a/tools/webcam/camera.py +++ b/tools/webcam/camera.py @@ -1,4 +1,5 @@ import av +import cv2 as cv class Camera: def __init__(self, cam_type_state, stream_type, camera_id): @@ -10,11 +11,16 @@ def __init__(self, cam_type_state, stream_type, camera_id): self.stream_type = stream_type self.cur_frame_id = 0 - self.container = av.open(camera_id) - assert self.container.streams.video, f"Can't open video stream for camera {camera_id}" - self.video_stream = self.container.streams.video[0] - self.W = self.video_stream.codec_context.width - self.H = self.video_stream.codec_context.height + print(f"Opening {cam_type_state} at {camera_id}") + + self.cap = cv.VideoCapture(camera_id) + + self.cap.set(cv.CAP_PROP_FRAME_WIDTH, 1280.0) + self.cap.set(cv.CAP_PROP_FRAME_HEIGHT, 720.0) + self.cap.set(cv.CAP_PROP_FPS, 25.0) + + self.W = self.cap.get(cv.CAP_PROP_FRAME_WIDTH) + self.H = self.cap.get(cv.CAP_PROP_FRAME_HEIGHT) @classmethod def bgr2nv12(self, bgr): @@ -22,8 +28,12 @@ def bgr2nv12(self, bgr): return frame.reformat(format='nv12').to_ndarray() def read_frames(self): - for frame in self.container.decode(self.video_stream): - img = frame.to_rgb().to_ndarray()[:,:, ::-1] # convert to bgr24 - yuv = Camera.bgr2nv12(img) + while True: + ret, frame = self.cap.read() + if not ret: + break + # Rotate the frame 180 degrees (flip both axes) + frame = cv.flip(frame, -1) + yuv = Camera.bgr2nv12(frame) yield yuv.data.tobytes() - self.container.close() + self.cap.release() diff --git a/tools/webcam/camerad.py b/tools/webcam/camerad.py index 47dddfce981c89..f1e70d948a0ac3 100755 --- a/tools/webcam/camerad.py +++ b/tools/webcam/camerad.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import threading import os +import platform from collections import namedtuple from msgq.visionipc import VisionIpcServer, VisionStreamType @@ -9,14 +10,19 @@ from openpilot.tools.webcam.camera import Camera from openpilot.common.realtime import Ratekeeper -DUAL_CAM = os.getenv("DUAL_CAMERA") +ROAD_CAM = os.getenv("ROAD_CAM", "0") +WIDE_CAM = os.getenv("WIDE_CAM") +DRIVER_CAM = os.getenv("DRIVER_CAM") + CameraType = namedtuple("CameraType", ["msg_name", "stream_type", "cam_id"]) + CAMERAS = [ - CameraType("roadCameraState", VisionStreamType.VISION_STREAM_ROAD, os.getenv("CAMERA_ROAD_ID", "0")), - CameraType("driverCameraState", VisionStreamType.VISION_STREAM_DRIVER, os.getenv("CAMERA_DRIVER_ID", "1")), + CameraType("roadCameraState", VisionStreamType.VISION_STREAM_ROAD, ROAD_CAM) ] -if DUAL_CAM: - CAMERAS.append(CameraType("wideRoadCameraState", VisionStreamType.VISION_STREAM_WIDE_ROAD, DUAL_CAM)) +if WIDE_CAM: + CAMERAS.append(CameraType("wideRoadCameraState", VisionStreamType.VISION_STREAM_WIDE_ROAD, WIDE_CAM)) +if DRIVER_CAM: + CAMERAS.append(CameraType("driverCameraState", VisionStreamType.VISION_STREAM_DRIVER, DRIVER_CAM)) class Camerad: def __init__(self): @@ -25,9 +31,10 @@ def __init__(self): self.cameras = [] for c in CAMERAS: - cam = Camera(c.msg_name, c.stream_type, c.cam_id) + cam_device = f"/dev/video{c.cam_id}" if platform.system() != "Darwin" else c.cam_id + cam = Camera(c.msg_name, c.stream_type, cam_device) self.cameras.append(cam) - self.vipc_server.create_buffers(c.stream_type, 20, False, cam.W, cam.H) + self.vipc_server.create_buffers(c.stream_type, 20, cam.W, cam.H) self.vipc_server.start_listener() diff --git a/tools/webcam/start_camerad.sh b/tools/webcam/start_camerad.sh deleted file mode 100755 index d4828b3e25ce69..00000000000000 --- a/tools/webcam/start_camerad.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash - -# export the block below when call manager.py -export BLOCK="${BLOCK},camerad" -export USE_WEBCAM="1" - -# Change camera index according to your setting -export CAMERA_ROAD_ID="0" -export CAMERA_DRIVER_ID="1" -export DUAL_CAMERA="2" # camera index for wide road camera - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" - -$DIR/camerad.py diff --git a/uv.lock b/uv.lock index 141cf787975190..dc51d2a45ef8bc 100644 --- a/uv.lock +++ b/uv.lock @@ -1,26 +1,27 @@ version = 1 -requires-python = ">=3.11" -resolution-markers = [ - "python_full_version < '3.12' and platform_system == 'Darwin'", - "python_full_version < '3.12' and platform_machine == 'aarch64' and platform_system == 'Linux'", - "(python_full_version < '3.12' and platform_machine != 'aarch64' and platform_system != 'Darwin') or (python_full_version < '3.12' and platform_system != 'Darwin' and platform_system != 'Linux')", - "python_full_version >= '3.12' and platform_system == 'Darwin'", - "python_full_version >= '3.12' and platform_machine == 'aarch64' and platform_system == 'Linux'", - "(python_full_version >= '3.12' and platform_machine != 'aarch64' and platform_system != 'Darwin') or (python_full_version >= '3.12' and platform_system != 'Darwin' and platform_system != 'Linux')", +revision = 3 +requires-python = ">=3.12.3, <3.13" + +[[package]] +name = "acados" +version = "0.2.2" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=acados&rev=release-acados#25933c81c7db5573afe38f012f52befc15cdb804" } +dependencies = [ + { name = "numpy" }, ] [[package]] name = "aiohappyeyeballs" -version = "2.4.0" +version = "2.6.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/2d/f7/22bba300a16fd1cad99da1a23793fe43963ee326d012fdf852d0b4035955/aiohappyeyeballs-2.4.0.tar.gz", hash = "sha256:55a1714f084e63d49639800f95716da97a1f173d46a16dfcfda0016abb93b6b2", size = 16786 } +sdist = { url = "https://files.pythonhosted.org/packages/33/c6/61a2d7b7572279226bb2e7f61d7a19ca7c90da0329c93fa0d560cbf288d8/aiohappyeyeballs-2.6.2.tar.gz", hash = "sha256:e202810ee718bd01fc6ef49e8ea53d023d5cb6b581076d7925aa499fa55dbe64", size = 22591, upload-time = "2026-05-20T15:12:24.631Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/18/b6/58ea188899950d759a837f9a58b2aee1d1a380ea4d6211ce9b1823748851/aiohappyeyeballs-2.4.0-py3-none-any.whl", hash = "sha256:7ce92076e249169a13c2f49320d1967425eaf1f407522d707d59cac7628d62bd", size = 12155 }, + { url = "https://files.pythonhosted.org/packages/5f/fc/a7bf5b6e4e617b45f90f2d9d2a68519c249c81dd4fc2658c7a2a61c4f4b7/aiohappyeyeballs-2.6.2-py3-none-any.whl", hash = "sha256:4708045e2d7a6c6bdf8aafa8ed39649eaf926a4543b54560659129e3365953c4", size = 15062, upload-time = "2026-05-20T15:12:23.328Z" }, ] [[package]] name = "aiohttp" -version = "3.10.5" +version = "3.13.5" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "aiohappyeyeballs" }, @@ -28,734 +29,437 @@ dependencies = [ { name = "attrs" }, { name = "frozenlist" }, { name = "multidict" }, + { name = "propcache" }, { name = "yarl" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ca/28/ca549838018140b92a19001a8628578b0f2a3b38c16826212cc6f706e6d4/aiohttp-3.10.5.tar.gz", hash = "sha256:f071854b47d39591ce9a17981c46790acb30518e2f83dfca8db2dfa091178691", size = 7524360 } +sdist = { url = "https://files.pythonhosted.org/packages/77/9a/152096d4808df8e4268befa55fba462f440f14beab85e8ad9bf990516918/aiohttp-3.13.5.tar.gz", hash = "sha256:9d98cc980ecc96be6eb4c1994ce35d28d8b1f5e5208a23b421187d1209dbb7d1", size = 7858271, upload-time = "2026-03-31T22:01:03.343Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f1/90/54ccb1e4eadfb6c95deff695582453f6208584431d69bf572782e9ae542b/aiohttp-3.10.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8c6a4e5e40156d72a40241a25cc226051c0a8d816610097a8e8f517aeacd59a2", size = 586455 }, - { url = "https://files.pythonhosted.org/packages/c3/7a/95e88c02756e7e718f054e1bb3ec6ad5d0ee4a2ca2bb1768c5844b3de30a/aiohttp-3.10.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:2c634a3207a5445be65536d38c13791904fda0748b9eabf908d3fe86a52941cf", size = 397255 }, - { url = "https://files.pythonhosted.org/packages/07/4f/767387b39990e1ee9aba8ce642abcc286d84d06e068dc167dab983898f18/aiohttp-3.10.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4aff049b5e629ef9b3e9e617fa6e2dfeda1bf87e01bcfecaf3949af9e210105e", size = 388973 }, - { url = "https://files.pythonhosted.org/packages/61/46/0df41170a4d228c07b661b1ba9d87101d99a79339dc93b8b1183d8b20545/aiohttp-3.10.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1942244f00baaacaa8155eca94dbd9e8cc7017deb69b75ef67c78e89fdad3c77", size = 1326126 }, - { url = "https://files.pythonhosted.org/packages/af/20/da0d65e07ce49d79173fed41598f487a0a722e87cfbaa8bb7e078a7c1d39/aiohttp-3.10.5-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e04a1f2a65ad2f93aa20f9ff9f1b672bf912413e5547f60749fa2ef8a644e061", size = 1364538 }, - { url = "https://files.pythonhosted.org/packages/aa/20/b59728405114e57541ba9d5b96033e69d004e811ded299537f74237629ca/aiohttp-3.10.5-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7f2bfc0032a00405d4af2ba27f3c429e851d04fad1e5ceee4080a1c570476697", size = 1399896 }, - { url = "https://files.pythonhosted.org/packages/2a/92/006690c31b830acbae09d2618e41308fe4c81c0679b3b33a3af859e0b7bf/aiohttp-3.10.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:424ae21498790e12eb759040bbb504e5e280cab64693d14775c54269fd1d2bb7", size = 1312914 }, - { url = "https://files.pythonhosted.org/packages/d4/71/1a253ca215b6c867adbd503f1e142117527ea8775e65962bc09b2fad1d2c/aiohttp-3.10.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:975218eee0e6d24eb336d0328c768ebc5d617609affaca5dbbd6dd1984f16ed0", size = 1271301 }, - { url = "https://files.pythonhosted.org/packages/0a/ab/5d1d9ff9ce6cce8fa54774d0364e64a0f3cd50e512ff09082ced8e5217a1/aiohttp-3.10.5-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4120d7fefa1e2d8fb6f650b11489710091788de554e2b6f8347c7a20ceb003f5", size = 1291652 }, - { url = "https://files.pythonhosted.org/packages/75/5f/f90510ea954b9ae6e7a53d2995b97a3e5c181110fdcf469bc9238445871d/aiohttp-3.10.5-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:b90078989ef3fc45cf9221d3859acd1108af7560c52397ff4ace8ad7052a132e", size = 1286289 }, - { url = "https://files.pythonhosted.org/packages/be/9e/1f523414237798660921817c82b9225a363af436458caf584d2fa6a2eb4a/aiohttp-3.10.5-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:ba5a8b74c2a8af7d862399cdedce1533642fa727def0b8c3e3e02fcb52dca1b1", size = 1341848 }, - { url = "https://files.pythonhosted.org/packages/f6/36/443472ddaa85d7d80321fda541d9535b23ecefe0bf5792cc3955ea635190/aiohttp-3.10.5-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:02594361128f780eecc2a29939d9dfc870e17b45178a867bf61a11b2a4367277", size = 1361619 }, - { url = "https://files.pythonhosted.org/packages/19/f6/3ecbac0bc4359c7d7ba9e85c6b10f57e20edaf1f97751ad2f892db231ad0/aiohttp-3.10.5-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:8fb4fc029e135859f533025bc82047334e24b0d489e75513144f25408ecaf058", size = 1320869 }, - { url = "https://files.pythonhosted.org/packages/34/7e/ed74ffb36e3a0cdec1b05d8fbaa29cb532371d5a20058b3a8052fc90fe7c/aiohttp-3.10.5-cp311-cp311-win32.whl", hash = "sha256:e1ca1ef5ba129718a8fc827b0867f6aa4e893c56eb00003b7367f8a733a9b072", size = 359271 }, - { url = "https://files.pythonhosted.org/packages/98/1b/718901f04bc8c886a742be9e83babb7b93facabf7c475cc95e2b3ab80b4d/aiohttp-3.10.5-cp311-cp311-win_amd64.whl", hash = "sha256:349ef8a73a7c5665cca65c88ab24abe75447e28aa3bc4c93ea5093474dfdf0ff", size = 379143 }, - { url = "https://files.pythonhosted.org/packages/d9/1c/74f9dad4a2fc4107e73456896283d915937f48177b99867b63381fadac6e/aiohttp-3.10.5-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:305be5ff2081fa1d283a76113b8df7a14c10d75602a38d9f012935df20731487", size = 583468 }, - { url = "https://files.pythonhosted.org/packages/12/29/68d090551f2b58ce76c2b436ced8dd2dfd32115d41299bf0b0c308a5483c/aiohttp-3.10.5-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:3a1c32a19ee6bbde02f1cb189e13a71b321256cc1d431196a9f824050b160d5a", size = 394066 }, - { url = "https://files.pythonhosted.org/packages/8f/f7/971f88b4cdcaaa4622925ba7d86de47b48ec02a9040a143514b382f78da4/aiohttp-3.10.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:61645818edd40cc6f455b851277a21bf420ce347baa0b86eaa41d51ef58ba23d", size = 389098 }, - { url = "https://files.pythonhosted.org/packages/f1/5a/fe3742efdce551667b2ddf1158b27c5b8eb1edc13d5e14e996e52e301025/aiohttp-3.10.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6c225286f2b13bab5987425558baa5cbdb2bc925b2998038fa028245ef421e75", size = 1332742 }, - { url = "https://files.pythonhosted.org/packages/1a/52/a25c0334a1845eb4967dff279151b67ca32a948145a5812ed660ed900868/aiohttp-3.10.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8ba01ebc6175e1e6b7275c907a3a36be48a2d487549b656aa90c8a910d9f3178", size = 1372134 }, - { url = "https://files.pythonhosted.org/packages/96/3d/33c1d8efc2d8ec36bff9a8eca2df9fdf8a45269c6e24a88e74f2aa4f16bd/aiohttp-3.10.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8eaf44ccbc4e35762683078b72bf293f476561d8b68ec8a64f98cf32811c323e", size = 1414413 }, - { url = "https://files.pythonhosted.org/packages/64/74/0f1ddaa5f0caba1d946f0dd0c31f5744116e4a029beec454ec3726d3311f/aiohttp-3.10.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b1c43eb1ab7cbf411b8e387dc169acb31f0ca0d8c09ba63f9eac67829585b44f", size = 1328107 }, - { url = "https://files.pythonhosted.org/packages/0a/32/c10118f0ad50e4093227234f71fd0abec6982c29367f65f32ee74ed652c4/aiohttp-3.10.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:de7a5299827253023c55ea549444e058c0eb496931fa05d693b95140a947cb73", size = 1280126 }, - { url = "https://files.pythonhosted.org/packages/c6/c9/77e3d648d97c03a42acfe843d03e97be3c5ef1b4d9de52e5bd2d28eed8e7/aiohttp-3.10.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4790f0e15f00058f7599dab2b206d3049d7ac464dc2e5eae0e93fa18aee9e7bf", size = 1292660 }, - { url = "https://files.pythonhosted.org/packages/7e/5d/99c71f8e5c8b64295be421b4c42d472766b263a1fe32e91b64bf77005bf2/aiohttp-3.10.5-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:44b324a6b8376a23e6ba25d368726ee3bc281e6ab306db80b5819999c737d820", size = 1300988 }, - { url = "https://files.pythonhosted.org/packages/8f/2c/76d2377dd947f52fbe8afb19b18a3b816d66c7966755c04030f93b1f7b2d/aiohttp-3.10.5-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:0d277cfb304118079e7044aad0b76685d30ecb86f83a0711fc5fb257ffe832ca", size = 1339268 }, - { url = "https://files.pythonhosted.org/packages/fd/e6/3d9d935cc705d57ed524d82ec5d6b678a53ac1552720ae41282caa273584/aiohttp-3.10.5-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:54d9ddea424cd19d3ff6128601a4a4d23d54a421f9b4c0fff740505813739a91", size = 1366993 }, - { url = "https://files.pythonhosted.org/packages/fe/c2/f7eed4d602f3f224600d03ab2e1a7734999b0901b1c49b94dc5891340433/aiohttp-3.10.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4f1c9866ccf48a6df2b06823e6ae80573529f2af3a0992ec4fe75b1a510df8a6", size = 1329459 }, - { url = "https://files.pythonhosted.org/packages/ce/8f/27f205b76531fc592abe29e1ad265a16bf934a9f609509c02d765e6a8055/aiohttp-3.10.5-cp312-cp312-win32.whl", hash = "sha256:dc4826823121783dccc0871e3f405417ac116055bf184ac04c36f98b75aacd12", size = 356968 }, - { url = "https://files.pythonhosted.org/packages/39/8c/4f6c0b2b3629f6be6c81ab84d9d577590f74f01d4412bfc4067958eaa1e1/aiohttp-3.10.5-cp312-cp312-win_amd64.whl", hash = "sha256:22c0a23a3b3138a6bf76fc553789cb1a703836da86b0f306b6f0dc1617398abc", size = 377650 }, - { url = "https://files.pythonhosted.org/packages/7b/b9/03b4327897a5b5d29338fa9b514f1c2f66a3e4fc88a4e40fad478739314d/aiohttp-3.10.5-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:7f6b639c36734eaa80a6c152a238242bedcee9b953f23bb887e9102976343092", size = 576994 }, - { url = "https://files.pythonhosted.org/packages/67/1b/20c2e159cd07b8ed6dde71c2258233902fdf415b2fe6174bd2364ba63107/aiohttp-3.10.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f29930bc2921cef955ba39a3ff87d2c4398a0394ae217f41cb02d5c26c8b1b77", size = 390684 }, - { url = "https://files.pythonhosted.org/packages/4d/6b/ff83b34f157e370431d8081c5d1741963f4fb12f9aaddb2cacbf50305225/aiohttp-3.10.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f489a2c9e6455d87eabf907ac0b7d230a9786be43fbe884ad184ddf9e9c1e385", size = 386176 }, - { url = "https://files.pythonhosted.org/packages/4d/a1/6e92817eb657de287560962df4959b7ddd22859c4b23a0309e2d3de12538/aiohttp-3.10.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:123dd5b16b75b2962d0fff566effb7a065e33cd4538c1692fb31c3bda2bfb972", size = 1303310 }, - { url = "https://files.pythonhosted.org/packages/04/29/200518dc7a39c30ae6d5bc232d7207446536e93d3d9299b8e95db6e79c54/aiohttp-3.10.5-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b98e698dc34966e5976e10bbca6d26d6724e6bdea853c7c10162a3235aba6e16", size = 1340445 }, - { url = "https://files.pythonhosted.org/packages/8e/20/53f7bba841ba7b5bb5dea580fea01c65524879ba39cb917d08c845524717/aiohttp-3.10.5-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c3b9162bab7e42f21243effc822652dc5bb5e8ff42a4eb62fe7782bcbcdfacf6", size = 1385121 }, - { url = "https://files.pythonhosted.org/packages/f1/b4/d99354ad614c48dd38fb1ee880a1a54bd9ab2c3bcad3013048d4a1797d3a/aiohttp-3.10.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1923a5c44061bffd5eebeef58cecf68096e35003907d8201a4d0d6f6e387ccaa", size = 1299669 }, - { url = "https://files.pythonhosted.org/packages/51/39/ca1de675f2a5729c71c327e52ac6344e63f036bd37281686ae5c3fb13bfb/aiohttp-3.10.5-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d55f011da0a843c3d3df2c2cf4e537b8070a419f891c930245f05d329c4b0689", size = 1252638 }, - { url = "https://files.pythonhosted.org/packages/54/cf/a3ae7ff43138422d477348e309ef8275779701bf305ff6054831ef98b782/aiohttp-3.10.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:afe16a84498441d05e9189a15900640a2d2b5e76cf4efe8cbb088ab4f112ee57", size = 1266889 }, - { url = "https://files.pythonhosted.org/packages/6e/7a/c6027ad70d9fb23cf254a26144de2723821dade1a624446aa22cd0b6d012/aiohttp-3.10.5-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:f8112fb501b1e0567a1251a2fd0747baae60a4ab325a871e975b7bb67e59221f", size = 1266249 }, - { url = "https://files.pythonhosted.org/packages/64/fd/ed136d46bc2c7e3342fed24662b4827771d55ceb5a7687847aae977bfc17/aiohttp-3.10.5-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1e72589da4c90337837fdfe2026ae1952c0f4a6e793adbbfbdd40efed7c63599", size = 1311036 }, - { url = "https://files.pythonhosted.org/packages/76/9a/43eeb0166f1119256d6f43468f900db1aed7fbe32069d2a71c82f987db4d/aiohttp-3.10.5-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:4d46c7b4173415d8e583045fbc4daa48b40e31b19ce595b8d92cf639396c15d5", size = 1338756 }, - { url = "https://files.pythonhosted.org/packages/d5/bc/d01ff0810b3f5e26896f76d44225ed78b088ddd33079b85cd1a23514318b/aiohttp-3.10.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:33e6bc4bab477c772a541f76cd91e11ccb6d2efa2b8d7d7883591dfb523e5987", size = 1299976 }, - { url = "https://files.pythonhosted.org/packages/3e/c9/50a297c4f7ab57a949f4add2d3eafe5f3e68bb42f739e933f8b32a092bda/aiohttp-3.10.5-cp313-cp313-win32.whl", hash = "sha256:c58c6837a2c2a7cf3133983e64173aec11f9c2cd8e87ec2fdc16ce727bcf1a04", size = 355609 }, - { url = "https://files.pythonhosted.org/packages/65/28/aee9d04fb0b3b1f90622c338a08e54af5198e704a910e20947c473298fd0/aiohttp-3.10.5-cp313-cp313-win_amd64.whl", hash = "sha256:38172a70005252b6893088c0f5e8a47d173df7cc2b2bd88650957eb84fcf5022", size = 375697 }, + { url = "https://files.pythonhosted.org/packages/be/6f/353954c29e7dcce7cf00280a02c75f30e133c00793c7a2ed3776d7b2f426/aiohttp-3.13.5-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:023ecba036ddd840b0b19bf195bfae970083fd7024ce1ac22e9bba90464620e9", size = 748876, upload-time = "2026-03-31T21:57:36.319Z" }, + { url = "https://files.pythonhosted.org/packages/f5/1b/428a7c64687b3b2e9cd293186695affc0e1e54a445d0361743b231f11066/aiohttp-3.13.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:15c933ad7920b7d9a20de151efcd05a6e38302cbf0e10c9b2acb9a42210a2416", size = 499557, upload-time = "2026-03-31T21:57:38.236Z" }, + { url = "https://files.pythonhosted.org/packages/29/47/7be41556bfbb6917069d6a6634bb7dd5e163ba445b783a90d40f5ac7e3a7/aiohttp-3.13.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab2899f9fa2f9f741896ebb6fa07c4c883bfa5c7f2ddd8cf2aafa86fa981b2d2", size = 500258, upload-time = "2026-03-31T21:57:39.923Z" }, + { url = "https://files.pythonhosted.org/packages/67/84/c9ecc5828cb0b3695856c07c0a6817a99d51e2473400f705275a2b3d9239/aiohttp-3.13.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a60eaa2d440cd4707696b52e40ed3e2b0f73f65be07fd0ef23b6b539c9c0b0b4", size = 1749199, upload-time = "2026-03-31T21:57:41.938Z" }, + { url = "https://files.pythonhosted.org/packages/f0/d3/3c6d610e66b495657622edb6ae7c7fd31b2e9086b4ec50b47897ad6042a9/aiohttp-3.13.5-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:55b3bdd3292283295774ab585160c4004f4f2f203946997f49aac032c84649e9", size = 1721013, upload-time = "2026-03-31T21:57:43.904Z" }, + { url = "https://files.pythonhosted.org/packages/49/a0/24409c12217456df0bae7babe3b014e460b0b38a8e60753d6cb339f6556d/aiohttp-3.13.5-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c2b2355dc094e5f7d45a7bb262fe7207aa0460b37a0d87027dcf21b5d890e7d5", size = 1781501, upload-time = "2026-03-31T21:57:46.285Z" }, + { url = "https://files.pythonhosted.org/packages/98/9d/b65ec649adc5bccc008b0957a9a9c691070aeac4e41cea18559fef49958b/aiohttp-3.13.5-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b38765950832f7d728297689ad78f5f2cf79ff82487131c4d26fe6ceecdc5f8e", size = 1878981, upload-time = "2026-03-31T21:57:48.734Z" }, + { url = "https://files.pythonhosted.org/packages/57/d8/8d44036d7eb7b6a8ec4c5494ea0c8c8b94fbc0ed3991c1a7adf230df03bf/aiohttp-3.13.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b18f31b80d5a33661e08c89e202edabf1986e9b49c42b4504371daeaa11b47c1", size = 1767934, upload-time = "2026-03-31T21:57:51.171Z" }, + { url = "https://files.pythonhosted.org/packages/31/04/d3f8211f273356f158e3464e9e45484d3fb8c4ce5eb2f6fe9405c3273983/aiohttp-3.13.5-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:33add2463dde55c4f2d9635c6ab33ce154e5ecf322bd26d09af95c5f81cfa286", size = 1566671, upload-time = "2026-03-31T21:57:53.326Z" }, + { url = "https://files.pythonhosted.org/packages/41/db/073e4ebe00b78e2dfcacff734291651729a62953b48933d765dc513bf798/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:327cc432fdf1356fb4fbc6fe833ad4e9f6aacb71a8acaa5f1855e4b25910e4a9", size = 1705219, upload-time = "2026-03-31T21:57:55.385Z" }, + { url = "https://files.pythonhosted.org/packages/48/45/7dfba71a2f9fd97b15c95c06819de7eb38113d2cdb6319669195a7d64270/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:7c35b0bf0b48a70b4cb4fc5d7bed9b932532728e124874355de1a0af8ec4bc88", size = 1743049, upload-time = "2026-03-31T21:57:57.341Z" }, + { url = "https://files.pythonhosted.org/packages/18/71/901db0061e0f717d226386a7f471bb59b19566f2cae5f0d93874b017271f/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:df23d57718f24badef8656c49743e11a89fd6f5358fa8a7b96e728fda2abf7d3", size = 1749557, upload-time = "2026-03-31T21:57:59.626Z" }, + { url = "https://files.pythonhosted.org/packages/08/d5/41eebd16066e59cd43728fe74bce953d7402f2b4ddfdfef2c0e9f17ca274/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:02e048037a6501a5ec1f6fc9736135aec6eb8a004ce48838cb951c515f32c80b", size = 1558931, upload-time = "2026-03-31T21:58:01.972Z" }, + { url = "https://files.pythonhosted.org/packages/30/e6/4a799798bf05740e66c3a1161079bda7a3dd8e22ca392481d7a7f9af82a6/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:31cebae8b26f8a615d2b546fee45d5ffb76852ae6450e2a03f42c9102260d6fe", size = 1774125, upload-time = "2026-03-31T21:58:04.007Z" }, + { url = "https://files.pythonhosted.org/packages/84/63/7749337c90f92bc2cb18f9560d67aa6258c7060d1397d21529b8004fcf6f/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:888e78eb5ca55a615d285c3c09a7a91b42e9dd6fc699b166ebd5dee87c9ccf14", size = 1732427, upload-time = "2026-03-31T21:58:06.337Z" }, + { url = "https://files.pythonhosted.org/packages/98/de/cf2f44ff98d307e72fb97d5f5bbae3bfcb442f0ea9790c0bf5c5c2331404/aiohttp-3.13.5-cp312-cp312-win32.whl", hash = "sha256:8bd3ec6376e68a41f9f95f5ed170e2fcf22d4eb27a1f8cb361d0508f6e0557f3", size = 433534, upload-time = "2026-03-31T21:58:08.712Z" }, + { url = "https://files.pythonhosted.org/packages/aa/ca/eadf6f9c8fa5e31d40993e3db153fb5ed0b11008ad5d9de98a95045bed84/aiohttp-3.13.5-cp312-cp312-win_amd64.whl", hash = "sha256:110e448e02c729bcebb18c60b9214a87ba33bac4a9fa5e9a5f139938b56c6cb1", size = 460446, upload-time = "2026-03-31T21:58:10.945Z" }, ] [[package]] name = "aioice" -version = "0.9.0" +version = "0.10.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "dnspython" }, { name = "ifaddr" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/33/b6/e2b0e48ccb5b04fe29265e93f14a0915f416e359c897ae87d570566c430b/aioice-0.9.0.tar.gz", hash = "sha256:fc2401b1c4b6e19372eaaeaa28fd1bd9cbf6b0e412e48625297c53b495eebd1e", size = 40324 } +sdist = { url = "https://files.pythonhosted.org/packages/67/04/df7286233f468e19e9bedff023b6b246182f0b2ccb04ceeb69b2994021c6/aioice-0.10.2.tar.gz", hash = "sha256:bf236c6829ee33c8e540535d31cd5a066b531cb56de2be94c46be76d68b1a806", size = 44307, upload-time = "2025-11-28T15:56:48.836Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/35/d21e48d3ba25d32aba5d142d54c4491376c659dd74d052a30dd25198007b/aioice-0.9.0-py3-none-any.whl", hash = "sha256:b609597a3a5a611e0004ff04772e16aceb881d51c25c0afc4ceac05d5e50024e", size = 24177 }, + { url = "https://files.pythonhosted.org/packages/c7/e3/0d23b1f930c17d371ce1ec36ee529f22fd19ebc2a07fe3418e3d1d884ce2/aioice-0.10.2-py3-none-any.whl", hash = "sha256:14911c15ab12d096dd14d372ebb4aecbb7420b52c9b76fdfcf54375dec17fcbf", size = 24875, upload-time = "2025-11-28T15:56:47.847Z" }, ] [[package]] name = "aiortc" -version = "1.9.0" +version = "1.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "aioice" }, { name = "av" }, - { name = "cffi" }, { name = "cryptography" }, { name = "google-crc32c" }, { name = "pyee" }, { name = "pylibsrtp" }, { name = "pyopenssl" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/71/32/e9b01e2271124643e5dc15c273f2bb8155efebf5bc2115407441ac62f4c5/aiortc-1.9.0.tar.gz", hash = "sha256:03faa76d76ef0e5989ac10386898b029369756102217230e2fcd4b029c50b303", size = 1168973 } +sdist = { url = "https://files.pythonhosted.org/packages/51/9c/4e027bfe0195de0442da301e2389329496745d40ae44d2d7c4571c4290ce/aiortc-1.14.0.tar.gz", hash = "sha256:adc8a67ace10a085721e588e06a00358ed8eaf5f6b62f0a95358ff45628dd762", size = 1180864, upload-time = "2025-10-13T21:40:37.905Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/93/01/db89910fc4dfb72ca25fd9a41326762a490d93d39d2fc4aac3f86c05857d/aiortc-1.9.0-cp38-abi3-macosx_10_9_x86_64.whl", hash = "sha256:e3e67c1970c2cffacac53c8f161df264efc62b22721c64a621940935028ee087", size = 1216069 }, - { url = "https://files.pythonhosted.org/packages/4c/6d/76ed96521080492c7264eacf73a8cba2202f1ff9f59af1776c5a2532f332/aiortc-1.9.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:d893cb3d4ffa0ff4f9bb03a88f0a700cdbcd4c0dc060a46c59a27ccd1c890663", size = 896012 }, - { url = "https://files.pythonhosted.org/packages/8c/87/1f666108764fa5b557bed4f0fd5e2acccd739bb2cca2b766dcacb53e5669/aiortc-1.9.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:176b4eb38d833667f87cf719a7a3e105e25a35b138b30893294418c1c96e38db", size = 1779113 }, - { url = "https://files.pythonhosted.org/packages/32/03/f3233e936f7a81549bd95f33f3d304e2a9211cb35d819d74570c0718b1ac/aiortc-1.9.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c44b610f36b8d17123855dfbe915fa6874201765b8a2c7fd9cf72d14cf417740", size = 1896322 }, - { url = "https://files.pythonhosted.org/packages/96/99/6672cf57777801c6ddacc13e1ee07f8c2151d0847a4f81455eeec998eaed/aiortc-1.9.0-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:55505adb31d56cba19a1ef8ad6aa9b727ccdba2a83bfbfb4aa79ef3c472026a6", size = 1918600 }, - { url = "https://files.pythonhosted.org/packages/76/e3/bdb76e7e51bc4fc7a5869597de2effad073ccf5ef14de3aed742d7384107/aiortc-1.9.0-cp38-abi3-win32.whl", hash = "sha256:680b703e35870e301535c930bfe32e7d012224a91ce51531aba45a3124ef07cc", size = 923055 }, - { url = "https://files.pythonhosted.org/packages/6a/df/de098b31a3fbf1117f6d4cb84c14518636054e3c95a9d9f693a1123c95b3/aiortc-1.9.0-cp38-abi3-win_amd64.whl", hash = "sha256:de5e7020cfc2d2d9fb95690926ff2e3b3c30cd4f5f5bc68d5b6756a8eebb686e", size = 1009610 }, + { url = "https://files.pythonhosted.org/packages/57/ab/31646a49209568cde3b97eeade0d28bb78b400e6645c56422c101df68932/aiortc-1.14.0-py3-none-any.whl", hash = "sha256:4b244d7e482f4e1f67e685b3468269628eca1ec91fa5b329ab517738cfca086e", size = 93183, upload-time = "2025-10-13T21:40:36.59Z" }, ] [[package]] name = "aiosignal" -version = "1.3.1" +version = "1.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "frozenlist" }, + { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ae/67/0952ed97a9793b4958e5736f6d2b346b414a2cd63e82d05940032f45b32f/aiosignal-1.3.1.tar.gz", hash = "sha256:54cd96e15e1649b75d6c87526a6ff0b6c1b0dd3459f43d9ca11d48c339b68cfc", size = 19422 } +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/76/ac/a7305707cb852b7e16ff80eaf5692309bde30e2b1100a1fcacdc8f731d97/aiosignal-1.3.1-py3-none-any.whl", hash = "sha256:f8376fb07dd1e86a584e4fcdec80b36b7f81aac666ebc724e2c090300dd83b17", size = 7617 }, + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, ] [[package]] name = "attrs" -version = "24.2.0" +version = "26.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fc/0f/aafca9af9315aee06a89ffde799a10a582fe8de76c563ee80bbcdc08b3fb/attrs-24.2.0.tar.gz", hash = "sha256:5cfb1b9148b5b086569baec03f20d7b6bf3bcacc9a42bebf87ffaaca362f6346", size = 792678 } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6a/21/5b6702a7f963e95456c0de2d495f67bf5fd62840ac655dc451586d23d39a/attrs-24.2.0-py3-none-any.whl", hash = "sha256:81921eb96de3191c8258c199618104dd27ac608d9366f5e35d011eae1867ede2", size = 63001 }, + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] [[package]] name = "av" -version = "12.3.0" +version = "16.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/00/f8/5adeeae0c42a7130933d168b8d84a21c98a32cb9fcf9222e2541ed0d9c7b/av-12.3.0.tar.gz", hash = "sha256:04b1892562aff3277efc79f32bd8f1d0cbb64ed011241cb3e96f9ad471816c22", size = 3833953 } +sdist = { url = "https://files.pythonhosted.org/packages/78/cd/3a83ffbc3cc25b39721d174487fb0d51a76582f4a1703f98e46170ce83d4/av-16.1.0.tar.gz", hash = "sha256:a094b4fd87a3721dacf02794d3d2c82b8d712c85b9534437e82a8a978c175ffd", size = 4285203, upload-time = "2026-01-11T07:31:33.772Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5d/20/256fa4fc4ef9bb46fdc4be4662e13a30b0334487c955961f3816d94db04b/av-12.3.0-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:cc06a806419fddc7102150ffe353c7d96b99b95fd12864280c91c851603fd4cb", size = 24658122 }, - { url = "https://files.pythonhosted.org/packages/5d/45/a9d0475539b4f49deb34f3da558de31cefc6be867d5c0603d575a8485069/av-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8e2130ff622a574d3d5d6e88ac335efcdd98c375bb341f87d9fe540830a746f5", size = 19923068 }, - { url = "https://files.pythonhosted.org/packages/af/27/1f2b3e46059c6618fd76ba12a96b49dc8515a426cd477032cd33f80505e8/av-12.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8e8b9bd99f916ff4d1278654e94658e6ace7ca60f6321f254d09c8cd81d9095b", size = 32555100 }, - { url = "https://files.pythonhosted.org/packages/28/34/759741d397a8bdbb8a359b8b5d49832a444b26c9a7f79c0f88be76a6b979/av-12.3.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9e375d1d89a5c6edfd9f66701fdb6cc9161cc1ff99d15ff0bda21ee1ad38e9e0", size = 31936355 }, - { url = "https://files.pythonhosted.org/packages/b4/6e/77426cb92117c941b0f759908bc83f34f259b11b353acb5de95972b452f7/av-12.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ef9066fd8d86548e12d587cbfe7b852159e48ff3c732271c3032668d4bd7c599", size = 34416598 }, - { url = "https://files.pythonhosted.org/packages/ff/d3/4b0fddcd54d0a88ee7e035f239ebb56ce139fac8e02ee0942c43746a66ff/av-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:bfaa9864560e43d45d254ed95f70ab1aab24a2fa0cc35ac99eef362f1453bec0", size = 25975217 }, - { url = "https://files.pythonhosted.org/packages/e4/c1/0636bccf5a1a2c935952614b9d34d8d8aae078c9773a60efb5376702f499/av-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5174e995772ebe33561980dca625f830aea8d39a4338728dedb41ae7dc2605af", size = 24669628 }, - { url = "https://files.pythonhosted.org/packages/ef/7d/9126abdafe20fa73d2c19fd108450363253cfea283c350618cc1434f473c/av-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:028d8b40308536f740dace3efd0178eb96825b414897c9594fb74136532901cb", size = 19928928 }, - { url = "https://files.pythonhosted.org/packages/27/75/c1b9e0aa4bd0d8b8311f366b6b38f6c6600d66baddfe2888accc7f76b1f5/av-12.3.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b030791ecc6185776d832d19ce196f61daf3e17e591a9bb6fd181280e1754138", size = 32793461 }, - { url = "https://files.pythonhosted.org/packages/5a/06/1364c445f8a8ab4870f0f5c4530b496257ae09de7fa01b6108525abea8b9/av-12.3.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a3703a35481fda5798a27bf6208c1ec3b61c18931625771fb3c9fd870539c7d7", size = 32217647 }, - { url = "https://files.pythonhosted.org/packages/27/08/220d5a1ae7e7830d66d041c71e607c1f5df2e3598b12fb406b0d7c2defa7/av-12.3.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:32f3eef56b2df289db6105f9fe2ebc9a8134a8adbd62190daeb8e22c4ff47794", size = 34746451 }, - { url = "https://files.pythonhosted.org/packages/96/67/9f1c444864d4f3e3773100b9ed20e670f80d5575b7a8fd53cca20de9d681/av-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:62d036ee8321d67190887012c3dbcd1ad83248603cc29ea75fbb75835b8d6e6e", size = 25977611 }, + { url = "https://files.pythonhosted.org/packages/9c/84/2535f55edcd426cebec02eb37b811b1b0c163f26b8d3f53b059e2ec32665/av-16.1.0-cp312-cp312-macosx_11_0_x86_64.whl", hash = "sha256:640f57b93f927fba8689f6966c956737ee95388a91bd0b8c8b5e0481f73513d6", size = 26945785, upload-time = "2026-01-09T20:18:34.486Z" }, + { url = "https://files.pythonhosted.org/packages/b6/17/ffb940c9e490bf42e86db4db1ff426ee1559cd355a69609ec1efe4d3a9eb/av-16.1.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:ae3fb658eec00852ebd7412fdc141f17f3ddce8afee2d2e1cf366263ad2a3b35", size = 21481147, upload-time = "2026-01-09T20:18:36.716Z" }, + { url = "https://files.pythonhosted.org/packages/15/c1/e0d58003d2d83c3921887d5c8c9b8f5f7de9b58dc2194356a2656a45cfdc/av-16.1.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:27ee558d9c02a142eebcbe55578a6d817fedfde42ff5676275504e16d07a7f86", size = 39517197, upload-time = "2026-01-11T09:57:31.937Z" }, + { url = "https://files.pythonhosted.org/packages/32/77/787797b43475d1b90626af76f80bfb0c12cfec5e11eafcfc4151b8c80218/av-16.1.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:7ae547f6d5fa31763f73900d43901e8c5fa6367bb9a9840978d57b5a7ae14ed2", size = 41174337, upload-time = "2026-01-11T09:57:35.792Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ac/d90df7f1e3b97fc5554cf45076df5045f1e0a6adf13899e10121229b826c/av-16.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8cf065f9d438e1921dc31fc7aa045790b58aee71736897866420d80b5450f62a", size = 40817720, upload-time = "2026-01-11T09:57:39.039Z" }, + { url = "https://files.pythonhosted.org/packages/80/6f/13c3a35f9dbcebafd03fe0c4cbd075d71ac8968ec849a3cfce406c35a9d2/av-16.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a345877a9d3cc0f08e2bc4ec163ee83176864b92587afb9d08dff50f37a9a829", size = 42267396, upload-time = "2026-01-11T09:57:42.115Z" }, + { url = "https://files.pythonhosted.org/packages/c8/b9/275df9607f7fb44317ccb1d4be74827185c0d410f52b6e2cd770fe209118/av-16.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:f49243b1d27c91cd8c66fdba90a674e344eb8eb917264f36117bf2b6879118fd", size = 31752045, upload-time = "2026-01-11T09:57:45.106Z" }, ] [[package]] -name = "azure-core" -version = "1.30.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "requests" }, - { name = "six" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/99/d4/1f469fa246f554b86fb5cebc30eef1b2a38b7af7a2c2791bce0a4c6e4604/azure-core-1.30.2.tar.gz", hash = "sha256:a14dc210efcd608821aa472d9fb8e8d035d29b68993819147bc290a8ac224472", size = 271104 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ef/d7/69d53f37733f8cb844862781767aef432ff3152bc9b9864dc98c7e286ce9/azure_core-1.30.2-py3-none-any.whl", hash = "sha256:cf019c1ca832e96274ae85abd3d9f752397194d9fea3b41487290562ac8abe4a", size = 194253 }, -] +name = "bootstrap-icons" +version = "1.10.5.0" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=bootstrap-icons&rev=release-bootstrap-icons#d7e41838af9320328dd7102f9288a94f0cf0fa9f" } [[package]] -name = "azure-identity" -version = "1.17.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "azure-core" }, - { name = "cryptography" }, - { name = "msal" }, - { name = "msal-extensions" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/51/c9/f7e3926686a89670ce641b360bd2da9a2d7a12b3e532403462d99f81e9d5/azure-identity-1.17.1.tar.gz", hash = "sha256:32ecc67cc73f4bd0595e4f64b1ca65cd05186f4fe6f98ed2ae9f1aa32646efea", size = 246652 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/49/83/a777861351e7b99e7c84ff3b36bab35e87b6e5d36e50b6905e148c696515/azure_identity-1.17.1-py3-none-any.whl", hash = "sha256:db8d59c183b680e763722bfe8ebc45930e6c57df510620985939f7f3191e0382", size = 173229 }, -] +name = "bzip2" +version = "1.0.8" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=bzip2&rev=release-bzip2#12916f9f84848239e5a69a8c5a282f3dcb0d86a3" } [[package]] -name = "azure-storage-blob" -version = "12.22.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "azure-core" }, - { name = "cryptography" }, - { name = "isodate" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/92/de/9cea85c0d5fc21f99bcf9f060fc2287cb95236b70431fa63cb69890a121e/azure-storage-blob-12.22.0.tar.gz", hash = "sha256:b3804bb4fe8ab1c32771fa464053da772a682c2737b19da438a3f4e5e3b3736e", size = 564873 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a8/52/b578c94048469fbf9f6378e2b2a46a2d0ccba3d59a7845dbed22ebf61601/azure_storage_blob-12.22.0-py3-none-any.whl", hash = "sha256:bb7d2d824ce3f11f14a27ee7d9281289f7e072ac8311c52e3652672455b7d5e8", size = 404892 }, -] +name = "capnproto" +version = "1.0.1" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=capnproto&rev=release-capnproto#a75eb83bd98440e890261f82aa8dcfbda0b0a206" } [[package]] -name = "casadi" -version = "3.6.6" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f2/d4/1d54b291225d3ada8bc149726bcb8480a56155430c86a2b03a9210048b3a/casadi-3.6.6.tar.gz", hash = "sha256:104601d37ab7ebf897bce7e097823bb090dd7629a7cc4c2e76780f46fc0e59f6", size = 5130529 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c0/7d/1b34f46cc84299e52982cdf13eda446c82ae648c4ba764beea67d25d287f/casadi-3.6.6-cp27-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:e969f8d4fe41f00474dc7fdc250007a1bb97f6872ccc202cca5211214340ef58", size = 46027234 }, - { url = "https://files.pythonhosted.org/packages/b9/c7/b23eaef7a10ef8e1b90988b881c4ad2da5c0162e7092efad5851754bd55e/casadi-3.6.6-cp27-none-manylinux1_i686.whl", hash = "sha256:2f6234b9ed2718a7e07b65cfeff9740112664e1d833c867971913be18ebb7a89", size = 51124371 }, - { url = "https://files.pythonhosted.org/packages/dc/d9/9da9a7138f714a25c1b253de368d98319662c965dd09563298cc9b6402fa/casadi-3.6.6-cp27-none-manylinux2010_x86_64.whl", hash = "sha256:878ca90794f24467955979a7eec7802f7e11adf40ef390878d211449d7d299a8", size = 57532419 }, - { url = "https://files.pythonhosted.org/packages/0c/28/5776a48622638839a6e7dffc90d02e5ae1c770a648ff2993b0a3060dd347/casadi-3.6.6-cp27-none-win_amd64.whl", hash = "sha256:f5c0e9312e58f4a35f7b7a009b423bfddd1adc065447cae248dce686cec5b08d", size = 46170765 }, - { url = "https://files.pythonhosted.org/packages/b7/97/047a46d8f650a04f7692ad506de85c01b96e7eba6e85f38adc7e449fe8ee/casadi-3.6.6-cp311-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:bbfa84129c534e17f4abfeb42b3f6d8d86b8602f93b756b73a9e43febfb9f1f0", size = 46033180 }, - { url = "https://files.pythonhosted.org/packages/47/f5/d966cd1a9fc7f0b7b6e251e17dde944e5175f01751fb7694e8146c873290/casadi-3.6.6-cp311-none-macosx_11_0_arm64.whl", hash = "sha256:1af055099cf650d5be35dc19fb093b1d6a7e9b11c6ab47746044a3783e268bdf", size = 42524191 }, - { url = "https://files.pythonhosted.org/packages/65/e8/49ee8ec0985c7426da5129e909b936a618bbf09f05876a078382186e8ce8/casadi-3.6.6-cp311-none-manylinux2014_aarch64.whl", hash = "sha256:ffcba96fe3695223c9f88b9d870cbeb08b7adb92929bfe15bad0e2143e62790d", size = 44898213 }, - { url = "https://files.pythonhosted.org/packages/29/2f/813c20dbd2c68b2bbc529e2860697b7eff0033fe87059835427feb42d256/casadi-3.6.6-cp311-none-manylinux2014_i686.whl", hash = "sha256:0fd493876c673ad149b03513c4f72275611643f2225f4f5d7c7ff828f75805a1", size = 71590867 }, - { url = "https://files.pythonhosted.org/packages/dc/35/1a46121dfb787f5c18572ce9594210c28384b4e1a614c5845da9e3594bda/casadi-3.6.6-cp311-none-manylinux2014_x86_64.whl", hash = "sha256:4a8e0660f19a18bc9c2ebe2da6e76589e464c613045dfd623e373d9638ace507", size = 75809472 }, - { url = "https://files.pythonhosted.org/packages/97/ab/2192d8e23a65b33e09f491eebffc45630598a1130d67dcbd1a86181d8686/casadi-3.6.6-cp311-none-win_amd64.whl", hash = "sha256:3bab3f398b4b4ea39d861c19a99d95ae3210fa1cb8acee2903538dcdb415b253", size = 46199272 }, - { url = "https://files.pythonhosted.org/packages/e6/72/688d4f44cb0e4dd42e8f84814d2d1ea1cc57d52a5ffd52f79c50487a8230/casadi-3.6.6-cp312-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:6cd3e42e29c1011eb644b5686df309935febec80c2a5893f12f226b3dc710f21", size = 46036373 }, - { url = "https://files.pythonhosted.org/packages/04/c4/59831c12bac5d9e323d1f22917eeab7c060ce3bfff4290295880c567e985/casadi-3.6.6-cp312-none-macosx_11_0_arm64.whl", hash = "sha256:aa4840aeb5457728ec70cf6b30142bfb9215378b1b8e622c8d799c03f9c1a0c2", size = 42524042 }, - { url = "https://files.pythonhosted.org/packages/70/5f/391fe2294a8404759f261e91b655c0552ad2e88a6881728d13319aa0948f/casadi-3.6.6-cp312-none-manylinux2014_aarch64.whl", hash = "sha256:ed024102d03713db772cb98fe5147c3ff59e0aea3113c2e80b86b4e76dfeb163", size = 44898992 }, - { url = "https://files.pythonhosted.org/packages/5b/2c/2c2537033b14d4c3f60d5929ccad43bd5f2d513857580fbadf35a532c342/casadi-3.6.6-cp312-none-manylinux2014_i686.whl", hash = "sha256:7197e0ba22472227e2e85f4ba6f7f1a8624fb2675c9a0e92da1ac4f3927b603d", size = 71588201 }, - { url = "https://files.pythonhosted.org/packages/fe/58/dfa6b2238666372b391e2a02c4eb9437f276f3babe472f2f804784d38b8e/casadi-3.6.6-cp312-none-manylinux2014_x86_64.whl", hash = "sha256:3b1fc585faf0d41aa7fd41b0ac1079b8eda5ad8cc8d0cc042cfceb44352827f5", size = 75813774 }, - { url = "https://files.pythonhosted.org/packages/41/21/dac7073d9d27d3527cf64797f5ae010a7e05e32864ccdf6b461597c323a0/casadi-3.6.6-cp312-none-win_amd64.whl", hash = "sha256:1111aed9afee22c52ba824d60e189a93b8db379d3749ea6d51434c796c7db74f", size = 46199935 }, -] +name = "catch2" +version = "2.13.10" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=catch2&rev=release-catch2#7287b4c99d23fdd87e66f9941b0e35ece6b4d91b" } [[package]] name = "certifi" -version = "2024.8.30" +version = "2026.5.20" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b0/ee/9b19140fe824b367c04c5e1b369942dd754c4c5462d5674002f75c4dedc1/certifi-2024.8.30.tar.gz", hash = "sha256:bec941d2aa8195e248a60b31ff9f0558284cf01a52591ceda73ea9afffd69fd9", size = 168507 } +sdist = { url = "https://files.pythonhosted.org/packages/f3/ce/ee2ecad540810a79593028e88299baeae54d346cc7a0d94b6199988b89b1/certifi-2026.5.20.tar.gz", hash = "sha256:69dea482ab64caa7b9f6aba1c6bf48bb6a5448d1c0f1b17ab42ad8c763a5344d", size = 135422, upload-time = "2026-05-20T11:46:50.073Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/12/90/3c9ff0512038035f59d279fddeb79f5f1eccd8859f06d6163c58798b9487/certifi-2024.8.30-py3-none-any.whl", hash = "sha256:922820b53db7a7257ffbda3f597266d435245903d80737e34f8a45ff3e3230d8", size = 167321 }, + { url = "https://files.pythonhosted.org/packages/59/8c/57e832b7af6d7c5abe66eb3fbe3a3a32f4d11ea23a1aa7131371035be991/certifi-2026.5.20-py3-none-any.whl", hash = "sha256:3c52e209ba0a4ad7aebe60436a4ab349c39e1e602e8c134221e546902ad25897", size = 134134, upload-time = "2026-05-20T11:46:48.578Z" }, ] [[package]] name = "cffi" -version = "1.17.0" +version = "2.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pycparser" }, + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1e/bf/82c351342972702867359cfeba5693927efe0a8dd568165490144f554b18/cffi-1.17.0.tar.gz", hash = "sha256:f3157624b7558b914cb039fd1af735e5e8049a87c817cc215109ad1c8779df76", size = 516073 } +sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/53/cc/9298fb6235522e00e47d78d6aa7f395332ef4e5f6fe124f9a03aa60600f7/cffi-1.17.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c5d97162c196ce54af6700949ddf9409e9833ef1003b4741c2b39ef46f1d9720", size = 181912 }, - { url = "https://files.pythonhosted.org/packages/e7/79/dc5334fbe60635d0846c56597a8d2af078a543ff22bc48d36551a0de62c2/cffi-1.17.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:5ba5c243f4004c750836f81606a9fcb7841f8874ad8f3bf204ff5e56332b72b9", size = 178297 }, - { url = "https://files.pythonhosted.org/packages/39/d7/ef1b6b16b51ccbabaced90ff0d821c6c23567fc4b2e4a445aea25d3ceb92/cffi-1.17.0-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bb9333f58fc3a2296fb1d54576138d4cf5d496a2cc118422bd77835e6ae0b9cb", size = 444909 }, - { url = "https://files.pythonhosted.org/packages/29/b8/6e3c61885537d985c78ef7dd779b68109ba256263d74a2f615c40f44548d/cffi-1.17.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:435a22d00ec7d7ea533db494da8581b05977f9c37338c80bc86314bec2619424", size = 468854 }, - { url = "https://files.pythonhosted.org/packages/0b/49/adad1228e19b931e523c2731e6984717d5f9e33a2f9971794ab42815b29b/cffi-1.17.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d1df34588123fcc88c872f5acb6f74ae59e9d182a2707097f9e28275ec26a12d", size = 476890 }, - { url = "https://files.pythonhosted.org/packages/76/54/c00f075c3e7fd14d9011713bcdb5b4f105ad044c5ad948db7b1a0a7e4e78/cffi-1.17.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df8bb0010fdd0a743b7542589223a2816bdde4d94bb5ad67884348fa2c1c67e8", size = 459374 }, - { url = "https://files.pythonhosted.org/packages/f3/b9/f163bb3fa4fbc636ee1f2a6a4598c096cdef279823ddfaa5734e556dd206/cffi-1.17.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a8b5b9712783415695663bd463990e2f00c6750562e6ad1d28e072a611c5f2a6", size = 466891 }, - { url = "https://files.pythonhosted.org/packages/31/52/72bbc95f6d06ff2e88a6fa13786be4043e542cb24748e1351aba864cb0a7/cffi-1.17.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ffef8fd58a36fb5f1196919638f73dd3ae0db1a878982b27a9a5a176ede4ba91", size = 477658 }, - { url = "https://files.pythonhosted.org/packages/67/20/d694811457eeae0c7663fa1a7ca201ce495533b646c1180d4ac25684c69c/cffi-1.17.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:4e67d26532bfd8b7f7c05d5a766d6f437b362c1bf203a3a5ce3593a645e870b8", size = 453890 }, - { url = "https://files.pythonhosted.org/packages/dc/79/40cbf5739eb4f694833db5a27ce7f63e30a9b25b4a836c4f25fb7272aacc/cffi-1.17.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:45f7cd36186db767d803b1473b3c659d57a23b5fa491ad83c6d40f2af58e4dbb", size = 478254 }, - { url = "https://files.pythonhosted.org/packages/e9/eb/2c384c385cca5cae67ca10ac4ef685277680b8c552b99aedecf4ea23ff7e/cffi-1.17.0-cp311-cp311-win32.whl", hash = "sha256:a9015f5b8af1bb6837a3fcb0cdf3b874fe3385ff6274e8b7925d81ccaec3c5c9", size = 171285 }, - { url = "https://files.pythonhosted.org/packages/ca/42/74cb1e0f1b79cb64672f3cb46245b506239c1297a20c0d9c3aeb3929cb0c/cffi-1.17.0-cp311-cp311-win_amd64.whl", hash = "sha256:b50aaac7d05c2c26dfd50c3321199f019ba76bb650e346a6ef3616306eed67b0", size = 180842 }, - { url = "https://files.pythonhosted.org/packages/1a/1f/7862231350cc959a3138889d2c8d33da7042b22e923457dfd4cd487d772a/cffi-1.17.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:aec510255ce690d240f7cb23d7114f6b351c733a74c279a84def763660a2c3bc", size = 182826 }, - { url = "https://files.pythonhosted.org/packages/8b/8c/26119bf8b79e05a1c39812064e1ee7981e1f8a5372205ba5698ea4dd958d/cffi-1.17.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2770bb0d5e3cc0e31e7318db06efcbcdb7b31bcb1a70086d3177692a02256f59", size = 178494 }, - { url = "https://files.pythonhosted.org/packages/61/94/4882c47d3ad396d91f0eda6ef16d45be3d752a332663b7361933039ed66a/cffi-1.17.0-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:db9a30ec064129d605d0f1aedc93e00894b9334ec74ba9c6bdd08147434b33eb", size = 454459 }, - { url = "https://files.pythonhosted.org/packages/0f/7c/a6beb119ad515058c5ee1829742d96b25b2b9204ff920746f6e13bf574eb/cffi-1.17.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a47eef975d2b8b721775a0fa286f50eab535b9d56c70a6e62842134cf7841195", size = 478502 }, - { url = "https://files.pythonhosted.org/packages/61/8a/2575cd01a90e1eca96a30aec4b1ac101a6fae06c49d490ac2704fa9bc8ba/cffi-1.17.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f3e0992f23bbb0be00a921eae5363329253c3b86287db27092461c887b791e5e", size = 485381 }, - { url = "https://files.pythonhosted.org/packages/cd/66/85899f5a9f152db49646e0c77427173e1b77a1046de0191ab3b0b9a5e6e3/cffi-1.17.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6107e445faf057c118d5050560695e46d272e5301feffda3c41849641222a828", size = 470907 }, - { url = "https://files.pythonhosted.org/packages/00/13/150924609bf377140abe6e934ce0a57f3fc48f1fd956ec1f578ce97a4624/cffi-1.17.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eb862356ee9391dc5a0b3cbc00f416b48c1b9a52d252d898e5b7696a5f9fe150", size = 479074 }, - { url = "https://files.pythonhosted.org/packages/17/fd/7d73d7110155c036303b0a6462c56250e9bc2f4119d7591d27417329b4d1/cffi-1.17.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:c1c13185b90bbd3f8b5963cd8ce7ad4ff441924c31e23c975cb150e27c2bf67a", size = 484225 }, - { url = "https://files.pythonhosted.org/packages/fc/83/8353e5c9b01bb46332dac3dfb18e6c597a04ceb085c19c814c2f78a8c0d0/cffi-1.17.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:17c6d6d3260c7f2d94f657e6872591fe8733872a86ed1345bda872cfc8c74885", size = 488388 }, - { url = "https://files.pythonhosted.org/packages/73/0c/f9d5ca9a095b1fc88ef77d1f8b85d11151c374144e4606da33874e17b65b/cffi-1.17.0-cp312-cp312-win32.whl", hash = "sha256:c3b8bd3133cd50f6b637bb4322822c94c5ce4bf0d724ed5ae70afce62187c492", size = 172096 }, - { url = "https://files.pythonhosted.org/packages/72/21/8c5d285fe20a6e31d29325f1287bb0e55f7d93630a5a44cafdafb5922495/cffi-1.17.0-cp312-cp312-win_amd64.whl", hash = "sha256:dca802c8db0720ce1c49cce1149ff7b06e91ba15fa84b1d59144fef1a1bc7ac2", size = 181478 }, - { url = "https://files.pythonhosted.org/packages/17/8f/581f2f3c3464d5f7cf87c2f7a5ba9acc6976253e02d73804240964243ec2/cffi-1.17.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:6ce01337d23884b21c03869d2f68c5523d43174d4fc405490eb0091057943118", size = 182638 }, - { url = "https://files.pythonhosted.org/packages/8d/1c/c9afa66684b7039f48018eb11b229b659dfb32b7a16b88251bac106dd1ff/cffi-1.17.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cab2eba3830bf4f6d91e2d6718e0e1c14a2f5ad1af68a89d24ace0c6b17cced7", size = 178453 }, - { url = "https://files.pythonhosted.org/packages/cc/b6/1a134d479d3a5a1ff2fabbee551d1d3f1dd70f453e081b5f70d604aae4c0/cffi-1.17.0-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:14b9cbc8f7ac98a739558eb86fabc283d4d564dafed50216e7f7ee62d0d25377", size = 454441 }, - { url = "https://files.pythonhosted.org/packages/b1/b4/e1569475d63aad8042b0935dbf62ae2a54d1e9142424e2b0e924d2d4a529/cffi-1.17.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b00e7bcd71caa0282cbe3c90966f738e2db91e64092a877c3ff7f19a1628fdcb", size = 478543 }, - { url = "https://files.pythonhosted.org/packages/d2/40/a9ad03fbd64309dec5bb70bc803a9a6772602de0ee164d7b9a6ca5a89249/cffi-1.17.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:41f4915e09218744d8bae14759f983e466ab69b178de38066f7579892ff2a555", size = 485463 }, - { url = "https://files.pythonhosted.org/packages/a6/1a/f10be60e006dd9242a24bcc2b1cd55c34c578380100f742d8c610f7a5d26/cffi-1.17.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e4760a68cab57bfaa628938e9c2971137e05ce48e762a9cb53b76c9b569f1204", size = 470854 }, - { url = "https://files.pythonhosted.org/packages/cc/b3/c035ed21aa3d39432bd749fe331ee90e4bc83ea2dbed1f71c4bc26c41084/cffi-1.17.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:011aff3524d578a9412c8b3cfaa50f2c0bd78e03eb7af7aa5e0df59b158efb2f", size = 479096 }, - { url = "https://files.pythonhosted.org/packages/00/cb/6f7edde01131de9382c89430b8e253b8c8754d66b63a62059663ceafeab2/cffi-1.17.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:a003ac9edc22d99ae1286b0875c460351f4e101f8c9d9d2576e78d7e048f64e0", size = 484013 }, - { url = "https://files.pythonhosted.org/packages/b9/83/8e4e8c211ea940210d293e951bf06b1bfb90f2eeee590e9778e99b4a8676/cffi-1.17.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:ef9528915df81b8f4c7612b19b8628214c65c9b7f74db2e34a646a0a2a0da2d4", size = 488119 }, - { url = "https://files.pythonhosted.org/packages/5e/52/3f7cfbc4f444cb4f73ff17b28690d12436dde665f67d68f1e1687908ab6c/cffi-1.17.0-cp313-cp313-win32.whl", hash = "sha256:70d2aa9fb00cf52034feac4b913181a6e10356019b18ef89bc7c12a283bf5f5a", size = 172122 }, - { url = "https://files.pythonhosted.org/packages/94/19/cf5baa07ee0f0e55eab7382459fbddaba0fdb0ba45973dd92556ae0d02db/cffi-1.17.0-cp313-cp313-win_amd64.whl", hash = "sha256:b7b6ea9e36d32582cda3465f54c4b454f62f23cb083ebc7a94e2ca6ef011c3a7", size = 181504 }, + { url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271, upload-time = "2025-09-08T23:22:44.795Z" }, + { url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048, upload-time = "2025-09-08T23:22:45.938Z" }, + { url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529, upload-time = "2025-09-08T23:22:47.349Z" }, + { url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097, upload-time = "2025-09-08T23:22:48.677Z" }, + { url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983, upload-time = "2025-09-08T23:22:50.06Z" }, + { url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519, upload-time = "2025-09-08T23:22:51.364Z" }, + { url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572, upload-time = "2025-09-08T23:22:52.902Z" }, + { url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963, upload-time = "2025-09-08T23:22:54.518Z" }, + { url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361, upload-time = "2025-09-08T23:22:55.867Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" }, + { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" }, + { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" }, ] [[package]] name = "charset-normalizer" -version = "3.3.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/63/09/c1bc53dab74b1816a00d8d030de5bf98f724c52c1635e07681d312f20be8/charset-normalizer-3.3.2.tar.gz", hash = "sha256:f30c3cb33b24454a82faecaf01b19c18562b1e89558fb6c56de4d9118a032fd5", size = 104809 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/68/77/02839016f6fbbf808e8b38601df6e0e66c17bbab76dff4613f7511413597/charset_normalizer-3.3.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:802fe99cca7457642125a8a88a084cef28ff0cf9407060f7b93dca5aa25480db", size = 191647 }, - { url = "https://files.pythonhosted.org/packages/3e/33/21a875a61057165e92227466e54ee076b73af1e21fe1b31f1e292251aa1e/charset_normalizer-3.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:573f6eac48f4769d667c4442081b1794f52919e7edada77495aaed9236d13a96", size = 121434 }, - { url = "https://files.pythonhosted.org/packages/dd/51/68b61b90b24ca35495956b718f35a9756ef7d3dd4b3c1508056fa98d1a1b/charset_normalizer-3.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:549a3a73da901d5bc3ce8d24e0600d1fa85524c10287f6004fbab87672bf3e1e", size = 118979 }, - { url = "https://files.pythonhosted.org/packages/e4/a6/7ee57823d46331ddc37dd00749c95b0edec2c79b15fc0d6e6efb532e89ac/charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f27273b60488abe721a075bcca6d7f3964f9f6f067c8c4c605743023d7d3944f", size = 136582 }, - { url = "https://files.pythonhosted.org/packages/74/f1/0d9fe69ac441467b737ba7f48c68241487df2f4522dd7246d9426e7c690e/charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1ceae2f17a9c33cb48e3263960dc5fc8005351ee19db217e9b1bb15d28c02574", size = 146645 }, - { url = "https://files.pythonhosted.org/packages/05/31/e1f51c76db7be1d4aef220d29fbfa5dbb4a99165d9833dcbf166753b6dc0/charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:65f6f63034100ead094b8744b3b97965785388f308a64cf8d7c34f2f2e5be0c4", size = 139398 }, - { url = "https://files.pythonhosted.org/packages/40/26/f35951c45070edc957ba40a5b1db3cf60a9dbb1b350c2d5bef03e01e61de/charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:753f10e867343b4511128c6ed8c82f7bec3bd026875576dfd88483c5c73b2fd8", size = 140273 }, - { url = "https://files.pythonhosted.org/packages/07/07/7e554f2bbce3295e191f7e653ff15d55309a9ca40d0362fcdab36f01063c/charset_normalizer-3.3.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4a78b2b446bd7c934f5dcedc588903fb2f5eec172f3d29e52a9096a43722adfc", size = 142577 }, - { url = "https://files.pythonhosted.org/packages/d8/b5/eb705c313100defa57da79277d9207dc8d8e45931035862fa64b625bfead/charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:e537484df0d8f426ce2afb2d0f8e1c3d0b114b83f8850e5f2fbea0e797bd82ae", size = 137747 }, - { url = "https://files.pythonhosted.org/packages/19/28/573147271fd041d351b438a5665be8223f1dd92f273713cb882ddafe214c/charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:eb6904c354526e758fda7167b33005998fb68c46fbc10e013ca97f21ca5c8887", size = 143375 }, - { url = "https://files.pythonhosted.org/packages/cf/7c/f3b682fa053cc21373c9a839e6beba7705857075686a05c72e0f8c4980ca/charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:deb6be0ac38ece9ba87dea880e438f25ca3eddfac8b002a2ec3d9183a454e8ae", size = 148474 }, - { url = "https://files.pythonhosted.org/packages/1e/49/7ab74d4ac537ece3bc3334ee08645e231f39f7d6df6347b29a74b0537103/charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:4ab2fe47fae9e0f9dee8c04187ce5d09f48eabe611be8259444906793ab7cbce", size = 140232 }, - { url = "https://files.pythonhosted.org/packages/2d/dc/9dacba68c9ac0ae781d40e1a0c0058e26302ea0660e574ddf6797a0347f7/charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:80402cd6ee291dcb72644d6eac93785fe2c8b9cb30893c1af5b8fdd753b9d40f", size = 140859 }, - { url = "https://files.pythonhosted.org/packages/6c/c2/4a583f800c0708dd22096298e49f887b49d9746d0e78bfc1d7e29816614c/charset_normalizer-3.3.2-cp311-cp311-win32.whl", hash = "sha256:7cd13a2e3ddeed6913a65e66e94b51d80a041145a026c27e6bb76c31a853c6ab", size = 92509 }, - { url = "https://files.pythonhosted.org/packages/57/ec/80c8d48ac8b1741d5b963797b7c0c869335619e13d4744ca2f67fc11c6fc/charset_normalizer-3.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:663946639d296df6a2bb2aa51b60a2454ca1cb29835324c640dafb5ff2131a77", size = 99870 }, - { url = "https://files.pythonhosted.org/packages/d1/b2/fcedc8255ec42afee97f9e6f0145c734bbe104aac28300214593eb326f1d/charset_normalizer-3.3.2-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:0b2b64d2bb6d3fb9112bafa732def486049e63de9618b5843bcdd081d8144cd8", size = 192892 }, - { url = "https://files.pythonhosted.org/packages/2e/7d/2259318c202f3d17f3fe6438149b3b9e706d1070fe3fcbb28049730bb25c/charset_normalizer-3.3.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:ddbb2551d7e0102e7252db79ba445cdab71b26640817ab1e3e3648dad515003b", size = 122213 }, - { url = "https://files.pythonhosted.org/packages/3a/52/9f9d17c3b54dc238de384c4cb5a2ef0e27985b42a0e5cc8e8a31d918d48d/charset_normalizer-3.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:55086ee1064215781fff39a1af09518bc9255b50d6333f2e4c74ca09fac6a8f6", size = 119404 }, - { url = "https://files.pythonhosted.org/packages/99/b0/9c365f6d79a9f0f3c379ddb40a256a67aa69c59609608fe7feb6235896e1/charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8f4a014bc36d3c57402e2977dada34f9c12300af536839dc38c0beab8878f38a", size = 137275 }, - { url = "https://files.pythonhosted.org/packages/91/33/749df346e93d7a30cdcb90cbfdd41a06026317bfbfb62cd68307c1a3c543/charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a10af20b82360ab00827f916a6058451b723b4e65030c5a18577c8b2de5b3389", size = 147518 }, - { url = "https://files.pythonhosted.org/packages/72/1a/641d5c9f59e6af4c7b53da463d07600a695b9824e20849cb6eea8a627761/charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8d756e44e94489e49571086ef83b2bb8ce311e730092d2c34ca8f7d925cb20aa", size = 140182 }, - { url = "https://files.pythonhosted.org/packages/ee/fb/14d30eb4956408ee3ae09ad34299131fb383c47df355ddb428a7331cfa1e/charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:90d558489962fd4918143277a773316e56c72da56ec7aa3dc3dbbe20fdfed15b", size = 141869 }, - { url = "https://files.pythonhosted.org/packages/df/3e/a06b18788ca2eb6695c9b22325b6fde7dde0f1d1838b1792a0076f58fe9d/charset_normalizer-3.3.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6ac7ffc7ad6d040517be39eb591cac5ff87416c2537df6ba3cba3bae290c0fed", size = 144042 }, - { url = "https://files.pythonhosted.org/packages/45/59/3d27019d3b447a88fe7e7d004a1e04be220227760264cc41b405e863891b/charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:7ed9e526742851e8d5cc9e6cf41427dfc6068d4f5a3bb03659444b4cabf6bc26", size = 138275 }, - { url = "https://files.pythonhosted.org/packages/7b/ef/5eb105530b4da8ae37d506ccfa25057961b7b63d581def6f99165ea89c7e/charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:8bdb58ff7ba23002a4c5808d608e4e6c687175724f54a5dade5fa8c67b604e4d", size = 144819 }, - { url = "https://files.pythonhosted.org/packages/a2/51/e5023f937d7f307c948ed3e5c29c4b7a3e42ed2ee0b8cdf8f3a706089bf0/charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:6b3251890fff30ee142c44144871185dbe13b11bab478a88887a639655be1068", size = 149415 }, - { url = "https://files.pythonhosted.org/packages/24/9d/2e3ef673dfd5be0154b20363c5cdcc5606f35666544381bee15af3778239/charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_s390x.whl", hash = "sha256:b4a23f61ce87adf89be746c8a8974fe1c823c891d8f86eb218bb957c924bb143", size = 141212 }, - { url = "https://files.pythonhosted.org/packages/5b/ae/ce2c12fcac59cb3860b2e2d76dc405253a4475436b1861d95fe75bdea520/charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:efcb3f6676480691518c177e3b465bcddf57cea040302f9f4e6e191af91174d4", size = 142167 }, - { url = "https://files.pythonhosted.org/packages/ed/3a/a448bf035dce5da359daf9ae8a16b8a39623cc395a2ffb1620aa1bce62b0/charset_normalizer-3.3.2-cp312-cp312-win32.whl", hash = "sha256:d965bba47ddeec8cd560687584e88cf699fd28f192ceb452d1d7ee807c5597b7", size = 93041 }, - { url = "https://files.pythonhosted.org/packages/b6/7c/8debebb4f90174074b827c63242c23851bdf00a532489fba57fef3416e40/charset_normalizer-3.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:96b02a3dc4381e5494fad39be677abcb5e6634bf7b4fa83a6dd3112607547001", size = 100397 }, - { url = "https://files.pythonhosted.org/packages/28/76/e6222113b83e3622caa4bb41032d0b1bf785250607392e1b778aca0b8a7d/charset_normalizer-3.3.2-py3-none-any.whl", hash = "sha256:3e4d1f6587322d2788836a99c69062fbb091331ec940e02d12d179c1d53e25fc", size = 48543 }, +version = "3.4.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e7/a1/67fe25fac3c7642725500a3f6cfe5821ad557c3abb11c9d20d12c7008d3e/charset_normalizer-3.4.7.tar.gz", hash = "sha256:ae89db9e5f98a11a4bf50407d4363e7b09b31e55bc117b4f7d80aab97ba009e5", size = 144271, upload-time = "2026-04-02T09:28:39.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/eb/4fc8d0a7110eb5fc9cc161723a34a8a6c200ce3b4fbf681bc86feee22308/charset_normalizer-3.4.7-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:eca9705049ad3c7345d574e3510665cb2cf844c2f2dcfe675332677f081cbd46", size = 311328, upload-time = "2026-04-02T09:26:24.331Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e3/0fadc706008ac9d7b9b5be6dc767c05f9d3e5df51744ce4cc9605de7b9f4/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6178f72c5508bfc5fd446a5905e698c6212932f25bcdd4b47a757a50605a90e2", size = 208061, upload-time = "2026-04-02T09:26:25.568Z" }, + { url = "https://files.pythonhosted.org/packages/42/f0/3dd1045c47f4a4604df85ec18ad093912ae1344ac706993aff91d38773a2/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e1421b502d83040e6d7fb2fb18dff63957f720da3d77b2fbd3187ceb63755d7b", size = 229031, upload-time = "2026-04-02T09:26:26.865Z" }, + { url = "https://files.pythonhosted.org/packages/dc/67/675a46eb016118a2fbde5a277a5d15f4f69d5f3f5f338e5ee2f8948fcf43/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:edac0f1ab77644605be2cbba52e6b7f630731fc42b34cb0f634be1a6eface56a", size = 225239, upload-time = "2026-04-02T09:26:28.044Z" }, + { url = "https://files.pythonhosted.org/packages/4b/f8/d0118a2f5f23b02cd166fa385c60f9b0d4f9194f574e2b31cef350ad7223/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5649fd1c7bade02f320a462fdefd0b4bd3ce036065836d4f42e0de958038e116", size = 216589, upload-time = "2026-04-02T09:26:29.239Z" }, + { url = "https://files.pythonhosted.org/packages/b1/f1/6d2b0b261b6c4ceef0fcb0d17a01cc5bc53586c2d4796fa04b5c540bc13d/charset_normalizer-3.4.7-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:203104ed3e428044fd943bc4bf45fa73c0730391f9621e37fe39ecf477b128cb", size = 202733, upload-time = "2026-04-02T09:26:30.5Z" }, + { url = "https://files.pythonhosted.org/packages/6f/c0/7b1f943f7e87cc3db9626ba17807d042c38645f0a1d4415c7a14afb5591f/charset_normalizer-3.4.7-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:298930cec56029e05497a76988377cbd7457ba864beeea92ad7e844fe74cd1f1", size = 212652, upload-time = "2026-04-02T09:26:31.709Z" }, + { url = "https://files.pythonhosted.org/packages/38/dd/5a9ab159fe45c6e72079398f277b7d2b523e7f716acc489726115a910097/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:708838739abf24b2ceb208d0e22403dd018faeef86ddac04319a62ae884c4f15", size = 211229, upload-time = "2026-04-02T09:26:33.282Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ff/531a1cad5ca855d1c1a8b69cb71abfd6d85c0291580146fda7c82857caa1/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:0f7eb884681e3938906ed0434f20c63046eacd0111c4ba96f27b76084cd679f5", size = 203552, upload-time = "2026-04-02T09:26:34.845Z" }, + { url = "https://files.pythonhosted.org/packages/c1/4c/a5fb52d528a8ca41f7598cb619409ece30a169fbdf9cdce592e53b46c3a6/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4dc1e73c36828f982bfe79fadf5919923f8a6f4df2860804db9a98c48824ce8d", size = 230806, upload-time = "2026-04-02T09:26:36.152Z" }, + { url = "https://files.pythonhosted.org/packages/59/7a/071feed8124111a32b316b33ae4de83d36923039ef8cf48120266844285b/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:aed52fea0513bac0ccde438c188c8a471c4e0f457c2dd20cdbf6ea7a450046c7", size = 212316, upload-time = "2026-04-02T09:26:37.672Z" }, + { url = "https://files.pythonhosted.org/packages/fd/35/f7dba3994312d7ba508e041eaac39a36b120f32d4c8662b8814dab876431/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:fea24543955a6a729c45a73fe90e08c743f0b3334bbf3201e6c4bc1b0c7fa464", size = 227274, upload-time = "2026-04-02T09:26:38.93Z" }, + { url = "https://files.pythonhosted.org/packages/8a/2d/a572df5c9204ab7688ec1edc895a73ebded3b023bb07364710b05dd1c9be/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bb6d88045545b26da47aa879dd4a89a71d1dce0f0e549b1abcb31dfe4a8eac49", size = 218468, upload-time = "2026-04-02T09:26:40.17Z" }, + { url = "https://files.pythonhosted.org/packages/86/eb/890922a8b03a568ca2f336c36585a4713c55d4d67bf0f0c78924be6315ca/charset_normalizer-3.4.7-cp312-cp312-win32.whl", hash = "sha256:2257141f39fe65a3fdf38aeccae4b953e5f3b3324f4ff0daf9f15b8518666a2c", size = 148460, upload-time = "2026-04-02T09:26:41.416Z" }, + { url = "https://files.pythonhosted.org/packages/35/d9/0e7dffa06c5ab081f75b1b786f0aefc88365825dfcd0ac544bdb7b2b6853/charset_normalizer-3.4.7-cp312-cp312-win_amd64.whl", hash = "sha256:5ed6ab538499c8644b8a3e18debabcd7ce684f3fa91cf867521a7a0279cab2d6", size = 159330, upload-time = "2026-04-02T09:26:42.554Z" }, + { url = "https://files.pythonhosted.org/packages/9e/5d/481bcc2a7c88ea6b0878c299547843b2521ccbc40980cb406267088bc701/charset_normalizer-3.4.7-cp312-cp312-win_arm64.whl", hash = "sha256:56be790f86bfb2c98fb742ce566dfb4816e5a83384616ab59c49e0604d49c51d", size = 147828, upload-time = "2026-04-02T09:26:44.075Z" }, + { url = "https://files.pythonhosted.org/packages/db/8f/61959034484a4a7c527811f4721e75d02d653a35afb0b6054474d8185d4c/charset_normalizer-3.4.7-py3-none-any.whl", hash = "sha256:3dce51d0f5e7951f8bb4900c257dad282f49190fdbebecd4ba99bcc41fef404d", size = 61958, upload-time = "2026-04-02T09:28:37.794Z" }, ] [[package]] name = "click" -version = "8.1.7" +version = "8.4.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "platform_system == 'Windows'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/96/d3/f04c7bfcf5c1862a2a5b845c6b2b360488cf47af55dfa79c98f6a6bf98b5/click-8.1.7.tar.gz", hash = "sha256:ca9853ad459e787e2192211578cc907e7594e294c7ccc834310722b41b9ca6de", size = 336121 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/00/2e/d53fa4befbf2cfa713304affc7ca780ce4fc1fd8710527771b58311a3229/click-8.1.7-py3-none-any.whl", hash = "sha256:ae74fb96c20a0277a1d615f1e4d73c8414f5a98db8b799a7931d1582f3390c28", size = 97941 }, + { name = "colorama", marker = "sys_platform == 'win32'" }, ] - -[[package]] -name = "cloudpickle" -version = "3.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c8/72/42a6570fc61b1f8913529728ad314c7cf5961540728dcad22c33fb2db6b6/cloudpickle-3.0.0.tar.gz", hash = "sha256:996d9a482c6fb4f33c1a35335cf8afd065d2a56e973270364840712d9131a882", size = 21231 } +sdist = { url = "https://files.pythonhosted.org/packages/9b/98/518d8e5081007684232226f475082b30087d0f585e8457db087298259f49/click-8.4.1.tar.gz", hash = "sha256:918b5633eddf6b41c32d4f454bf0de810065c74e3f7dbf8ee5452f8be88d3e96", size = 353007, upload-time = "2026-05-22T04:08:37.769Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/96/43/dae06432d0c4b1dc9e9149ad37b4ca8384cf6eb7700cd9215b177b914f0a/cloudpickle-3.0.0-py3-none-any.whl", hash = "sha256:246ee7d0c295602a036e86369c77fecda4ab17b506496730f2f576d9016fd9c7", size = 20088 }, + { url = "https://files.pythonhosted.org/packages/c7/0d/67e5b4109ea4a837e80daa87c2c696711955e40449a97e8926672534def2/click-8.4.1-py3-none-any.whl", hash = "sha256:482be17c6991b8c19c5429a1e995d9b0efdbb63172824c41f99965dc0ade8ec2", size = 116639, upload-time = "2026-05-22T04:08:35.26Z" }, ] [[package]] name = "codespell" -version = "2.3.0" +version = "2.4.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a0/a9/98353dfc7afcdf18cffd2dd3e959a25eaaf2728cf450caa59af89648a8e4/codespell-2.3.0.tar.gz", hash = "sha256:360c7d10f75e65f67bad720af7007e1060a5d395670ec11a7ed1fed9dd17471f", size = 329791 } +sdist = { url = "https://files.pythonhosted.org/packages/2d/9d/1d0903dff693160f893ca6abcabad545088e7a2ee0a6deae7c24e958be69/codespell-2.4.2.tar.gz", hash = "sha256:3c33be9ae34543807f088aeb4832dfad8cb2dae38da61cac0a7045dd376cfdf3", size = 352058, upload-time = "2026-03-05T18:10:42.936Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0e/20/b6019add11e84f821184234cea0ad91442373489ef7ccfa3d73a71b908fa/codespell-2.3.0-py3-none-any.whl", hash = "sha256:a9c7cef2501c9cfede2110fd6d4e5e62296920efe9abfb84648df866e47f58d1", size = 329167 }, + { url = "https://files.pythonhosted.org/packages/42/a1/52fa05533e95fe45bcc09bcf8a503874b1c08f221a4e35608017e0938f55/codespell-2.4.2-py3-none-any.whl", hash = "sha256:97e0c1060cf46bd1d5db89a936c98db8c2b804e1fdd4b5c645e82a1ec6b1f886", size = 353715, upload-time = "2026-03-05T18:10:41.398Z" }, ] [[package]] name = "colorama" version = "0.4.6" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 }, -] - -[[package]] -name = "coloredlogs" -version = "15.0.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "humanfriendly" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/cc/c7/eed8f27100517e8c0e6b923d5f0845d0cb99763da6fdee00478f91db7325/coloredlogs-15.0.1.tar.gz", hash = "sha256:7c991aa71a4577af2f82600d8f8f3a89f936baeaf9b50a9c197da014e5bf16b0", size = 278520 } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a7/06/3d6badcf13db419e25b07041d9c7b4a2c331d3f4e7134445ec5df57714cd/coloredlogs-15.0.1-py2.py3-none-any.whl", hash = "sha256:612ee75c546f53e92e70049c9dbfcc18c935a2b9a53b66085ce9ef6a6e5c0934", size = 46018 }, + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] [[package]] name = "contourpy" -version = "1.3.0" +version = "1.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f5/f6/31a8f28b4a2a4fa0e01085e542f3081ab0588eff8e589d39d775172c9792/contourpy-1.3.0.tar.gz", hash = "sha256:7ffa0db17717a8ffb127efd0c95a4362d996b892c2904db72428d5b52e1938a4", size = 13464370 } +sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/1f/9375917786cb39270b0ee6634536c0e22abf225825602688990d8f5c6c19/contourpy-1.3.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0fa4c02abe6c446ba70d96ece336e621efa4aecae43eaa9b030ae5fb92b309ad", size = 266356 }, - { url = "https://files.pythonhosted.org/packages/05/46/9256dd162ea52790c127cb58cfc3b9e3413a6e3478917d1f811d420772ec/contourpy-1.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:834e0cfe17ba12f79963861e0f908556b2cedd52e1f75e6578801febcc6a9f49", size = 250915 }, - { url = "https://files.pythonhosted.org/packages/e1/5d/3056c167fa4486900dfbd7e26a2fdc2338dc58eee36d490a0ed3ddda5ded/contourpy-1.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dbc4c3217eee163fa3984fd1567632b48d6dfd29216da3ded3d7b844a8014a66", size = 310443 }, - { url = "https://files.pythonhosted.org/packages/ca/c2/1a612e475492e07f11c8e267ea5ec1ce0d89971be496c195e27afa97e14a/contourpy-1.3.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4865cd1d419e0c7a7bf6de1777b185eebdc51470800a9f42b9e9decf17762081", size = 348548 }, - { url = "https://files.pythonhosted.org/packages/45/cf/2c2fc6bb5874158277b4faf136847f0689e1b1a1f640a36d76d52e78907c/contourpy-1.3.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:303c252947ab4b14c08afeb52375b26781ccd6a5ccd81abcdfc1fafd14cf93c1", size = 319118 }, - { url = "https://files.pythonhosted.org/packages/03/33/003065374f38894cdf1040cef474ad0546368eea7e3a51d48b8a423961f8/contourpy-1.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:637f674226be46f6ba372fd29d9523dd977a291f66ab2a74fbeb5530bb3f445d", size = 323162 }, - { url = "https://files.pythonhosted.org/packages/42/80/e637326e85e4105a802e42959f56cff2cd39a6b5ef68d5d9aee3ea5f0e4c/contourpy-1.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:76a896b2f195b57db25d6b44e7e03f221d32fe318d03ede41f8b4d9ba1bff53c", size = 1265396 }, - { url = "https://files.pythonhosted.org/packages/7c/3b/8cbd6416ca1bbc0202b50f9c13b2e0b922b64be888f9d9ee88e6cfabfb51/contourpy-1.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e1fd23e9d01591bab45546c089ae89d926917a66dceb3abcf01f6105d927e2cb", size = 1324297 }, - { url = "https://files.pythonhosted.org/packages/4d/2c/021a7afaa52fe891f25535506cc861c30c3c4e5a1c1ce94215e04b293e72/contourpy-1.3.0-cp311-cp311-win32.whl", hash = "sha256:d402880b84df3bec6eab53cd0cf802cae6a2ef9537e70cf75e91618a3801c20c", size = 171808 }, - { url = "https://files.pythonhosted.org/packages/8d/2f/804f02ff30a7fae21f98198828d0857439ec4c91a96e20cf2d6c49372966/contourpy-1.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:6cb6cc968059db9c62cb35fbf70248f40994dfcd7aa10444bbf8b3faeb7c2d67", size = 217181 }, - { url = "https://files.pythonhosted.org/packages/c9/92/8e0bbfe6b70c0e2d3d81272b58c98ac69ff1a4329f18c73bd64824d8b12e/contourpy-1.3.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:570ef7cf892f0afbe5b2ee410c507ce12e15a5fa91017a0009f79f7d93a1268f", size = 267838 }, - { url = "https://files.pythonhosted.org/packages/e3/04/33351c5d5108460a8ce6d512307690b023f0cfcad5899499f5c83b9d63b1/contourpy-1.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:da84c537cb8b97d153e9fb208c221c45605f73147bd4cadd23bdae915042aad6", size = 251549 }, - { url = "https://files.pythonhosted.org/packages/51/3d/aa0fe6ae67e3ef9f178389e4caaaa68daf2f9024092aa3c6032e3d174670/contourpy-1.3.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0be4d8425bfa755e0fd76ee1e019636ccc7c29f77a7c86b4328a9eb6a26d0639", size = 303177 }, - { url = "https://files.pythonhosted.org/packages/56/c3/c85a7e3e0cab635575d3b657f9535443a6f5d20fac1a1911eaa4bbe1aceb/contourpy-1.3.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9c0da700bf58f6e0b65312d0a5e695179a71d0163957fa381bb3c1f72972537c", size = 341735 }, - { url = "https://files.pythonhosted.org/packages/dd/8d/20f7a211a7be966a53f474bc90b1a8202e9844b3f1ef85f3ae45a77151ee/contourpy-1.3.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eb8b141bb00fa977d9122636b16aa67d37fd40a3d8b52dd837e536d64b9a4d06", size = 314679 }, - { url = "https://files.pythonhosted.org/packages/6e/be/524e377567defac0e21a46e2a529652d165fed130a0d8a863219303cee18/contourpy-1.3.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3634b5385c6716c258d0419c46d05c8aa7dc8cb70326c9a4fb66b69ad2b52e09", size = 320549 }, - { url = "https://files.pythonhosted.org/packages/0f/96/fdb2552a172942d888915f3a6663812e9bc3d359d53dafd4289a0fb462f0/contourpy-1.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0dce35502151b6bd35027ac39ba6e5a44be13a68f55735c3612c568cac3805fd", size = 1263068 }, - { url = "https://files.pythonhosted.org/packages/2a/25/632eab595e3140adfa92f1322bf8915f68c932bac468e89eae9974cf1c00/contourpy-1.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:aea348f053c645100612b333adc5983d87be69acdc6d77d3169c090d3b01dc35", size = 1322833 }, - { url = "https://files.pythonhosted.org/packages/73/e3/69738782e315a1d26d29d71a550dbbe3eb6c653b028b150f70c1a5f4f229/contourpy-1.3.0-cp312-cp312-win32.whl", hash = "sha256:90f73a5116ad1ba7174341ef3ea5c3150ddf20b024b98fb0c3b29034752c8aeb", size = 172681 }, - { url = "https://files.pythonhosted.org/packages/0c/89/9830ba00d88e43d15e53d64931e66b8792b46eb25e2050a88fec4a0df3d5/contourpy-1.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:b11b39aea6be6764f84360fce6c82211a9db32a7c7de8fa6dd5397cf1d079c3b", size = 218283 }, - { url = "https://files.pythonhosted.org/packages/53/a1/d20415febfb2267af2d7f06338e82171824d08614084714fb2c1dac9901f/contourpy-1.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:3e1c7fa44aaae40a2247e2e8e0627f4bea3dd257014764aa644f319a5f8600e3", size = 267879 }, - { url = "https://files.pythonhosted.org/packages/aa/45/5a28a3570ff6218d8bdfc291a272a20d2648104815f01f0177d103d985e1/contourpy-1.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:364174c2a76057feef647c802652f00953b575723062560498dc7930fc9b1cb7", size = 251573 }, - { url = "https://files.pythonhosted.org/packages/39/1c/d3f51540108e3affa84f095c8b04f0aa833bb797bc8baa218a952a98117d/contourpy-1.3.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:32b238b3b3b649e09ce9aaf51f0c261d38644bdfa35cbaf7b263457850957a84", size = 303184 }, - { url = "https://files.pythonhosted.org/packages/00/56/1348a44fb6c3a558c1a3a0cd23d329d604c99d81bf5a4b58c6b71aab328f/contourpy-1.3.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d51fca85f9f7ad0b65b4b9fe800406d0d77017d7270d31ec3fb1cc07358fdea0", size = 340262 }, - { url = "https://files.pythonhosted.org/packages/2b/23/00d665ba67e1bb666152131da07e0f24c95c3632d7722caa97fb61470eca/contourpy-1.3.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:732896af21716b29ab3e988d4ce14bc5133733b85956316fb0c56355f398099b", size = 313806 }, - { url = "https://files.pythonhosted.org/packages/5a/42/3cf40f7040bb8362aea19af9a5fb7b32ce420f645dd1590edcee2c657cd5/contourpy-1.3.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d73f659398a0904e125280836ae6f88ba9b178b2fed6884f3b1f95b989d2c8da", size = 319710 }, - { url = "https://files.pythonhosted.org/packages/05/32/f3bfa3fc083b25e1a7ae09197f897476ee68e7386e10404bdf9aac7391f0/contourpy-1.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c6c7c2408b7048082932cf4e641fa3b8ca848259212f51c8c59c45aa7ac18f14", size = 1264107 }, - { url = "https://files.pythonhosted.org/packages/1c/1e/1019d34473a736664f2439542b890b2dc4c6245f5c0d8cdfc0ccc2cab80c/contourpy-1.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f317576606de89da6b7e0861cf6061f6146ead3528acabff9236458a6ba467f8", size = 1322458 }, - { url = "https://files.pythonhosted.org/packages/22/85/4f8bfd83972cf8909a4d36d16b177f7b8bdd942178ea4bf877d4a380a91c/contourpy-1.3.0-cp313-cp313-win32.whl", hash = "sha256:31cd3a85dbdf1fc002280c65caa7e2b5f65e4a973fcdf70dd2fdcb9868069294", size = 172643 }, - { url = "https://files.pythonhosted.org/packages/cc/4a/fb3c83c1baba64ba90443626c228ca14f19a87c51975d3b1de308dd2cf08/contourpy-1.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:4553c421929ec95fb07b3aaca0fae668b2eb5a5203d1217ca7c34c063c53d087", size = 218301 }, - { url = "https://files.pythonhosted.org/packages/76/65/702f4064f397821fea0cb493f7d3bc95a5d703e20954dce7d6d39bacf378/contourpy-1.3.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:345af746d7766821d05d72cb8f3845dfd08dd137101a2cb9b24de277d716def8", size = 278972 }, - { url = "https://files.pythonhosted.org/packages/80/85/21f5bba56dba75c10a45ec00ad3b8190dbac7fd9a8a8c46c6116c933e9cf/contourpy-1.3.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3bb3808858a9dc68f6f03d319acd5f1b8a337e6cdda197f02f4b8ff67ad2057b", size = 263375 }, - { url = "https://files.pythonhosted.org/packages/0a/64/084c86ab71d43149f91ab3a4054ccf18565f0a8af36abfa92b1467813ed6/contourpy-1.3.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:420d39daa61aab1221567b42eecb01112908b2cab7f1b4106a52caaec8d36973", size = 307188 }, - { url = "https://files.pythonhosted.org/packages/3d/ff/d61a4c288dc42da0084b8d9dc2aa219a850767165d7d9a9c364ff530b509/contourpy-1.3.0-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4d63ee447261e963af02642ffcb864e5a2ee4cbfd78080657a9880b8b1868e18", size = 345644 }, - { url = "https://files.pythonhosted.org/packages/ca/aa/00d2313d35ec03f188e8f0786c2fc61f589306e02fdc158233697546fd58/contourpy-1.3.0-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:167d6c890815e1dac9536dca00828b445d5d0df4d6a8c6adb4a7ec3166812fa8", size = 317141 }, - { url = "https://files.pythonhosted.org/packages/8d/6a/b5242c8cb32d87f6abf4f5e3044ca397cb1a76712e3fa2424772e3ff495f/contourpy-1.3.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:710a26b3dc80c0e4febf04555de66f5fd17e9cf7170a7b08000601a10570bda6", size = 323469 }, - { url = "https://files.pythonhosted.org/packages/6f/a6/73e929d43028a9079aca4bde107494864d54f0d72d9db508a51ff0878593/contourpy-1.3.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:75ee7cb1a14c617f34a51d11fa7524173e56551646828353c4af859c56b766e2", size = 1260894 }, - { url = "https://files.pythonhosted.org/packages/2b/1e/1e726ba66eddf21c940821df8cf1a7d15cb165f0682d62161eaa5e93dae1/contourpy-1.3.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:33c92cdae89ec5135d036e7218e69b0bb2851206077251f04a6c4e0e21f03927", size = 1314829 }, + { url = "https://files.pythonhosted.org/packages/be/45/adfee365d9ea3d853550b2e735f9d66366701c65db7855cd07621732ccfc/contourpy-1.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b08a32ea2f8e42cf1d4be3169a98dd4be32bafe4f22b6c4cb4ba810fa9e5d2cb", size = 293419, upload-time = "2025-07-26T12:01:21.16Z" }, + { url = "https://files.pythonhosted.org/packages/53/3e/405b59cfa13021a56bba395a6b3aca8cec012b45bf177b0eaf7a202cde2c/contourpy-1.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:556dba8fb6f5d8742f2923fe9457dbdd51e1049c4a43fd3986a0b14a1d815fc6", size = 273979, upload-time = "2025-07-26T12:01:22.448Z" }, + { url = "https://files.pythonhosted.org/packages/d4/1c/a12359b9b2ca3a845e8f7f9ac08bdf776114eb931392fcad91743e2ea17b/contourpy-1.3.3-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d9abc807cf7d0e047b95ca5d957cf4792fcd04e920ca70d48add15c1a90ea7", size = 332653, upload-time = "2025-07-26T12:01:24.155Z" }, + { url = "https://files.pythonhosted.org/packages/63/12/897aeebfb475b7748ea67b61e045accdfcf0d971f8a588b67108ed7f5512/contourpy-1.3.3-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b2e8faa0ed68cb29af51edd8e24798bb661eac3bd9f65420c1887b6ca89987c8", size = 379536, upload-time = "2025-07-26T12:01:25.91Z" }, + { url = "https://files.pythonhosted.org/packages/43/8a/a8c584b82deb248930ce069e71576fc09bd7174bbd35183b7943fb1064fd/contourpy-1.3.3-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:626d60935cf668e70a5ce6ff184fd713e9683fb458898e4249b63be9e28286ea", size = 384397, upload-time = "2025-07-26T12:01:27.152Z" }, + { url = "https://files.pythonhosted.org/packages/cc/8f/ec6289987824b29529d0dfda0d74a07cec60e54b9c92f3c9da4c0ac732de/contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e655fcef08aba35ec9610536bfe90267d7ab5ba944f7032549c55a146da1", size = 362601, upload-time = "2025-07-26T12:01:28.808Z" }, + { url = "https://files.pythonhosted.org/packages/05/0a/a3fe3be3ee2dceb3e615ebb4df97ae6f3828aa915d3e10549ce016302bd1/contourpy-1.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:451e71b5a7d597379ef572de31eeb909a87246974d960049a9848c3bc6c41bf7", size = 1331288, upload-time = "2025-07-26T12:01:31.198Z" }, + { url = "https://files.pythonhosted.org/packages/33/1d/acad9bd4e97f13f3e2b18a3977fe1b4a37ecf3d38d815333980c6c72e963/contourpy-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:459c1f020cd59fcfe6650180678a9993932d80d44ccde1fa1868977438f0b411", size = 1403386, upload-time = "2025-07-26T12:01:33.947Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8f/5847f44a7fddf859704217a99a23a4f6417b10e5ab1256a179264561540e/contourpy-1.3.3-cp312-cp312-win32.whl", hash = "sha256:023b44101dfe49d7d53932be418477dba359649246075c996866106da069af69", size = 185018, upload-time = "2025-07-26T12:01:35.64Z" }, + { url = "https://files.pythonhosted.org/packages/19/e8/6026ed58a64563186a9ee3f29f41261fd1828f527dd93d33b60feca63352/contourpy-1.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:8153b8bfc11e1e4d75bcb0bff1db232f9e10b274e0929de9d608027e0d34ff8b", size = 226567, upload-time = "2025-07-26T12:01:36.804Z" }, + { url = "https://files.pythonhosted.org/packages/d1/e2/f05240d2c39a1ed228d8328a78b6f44cd695f7ef47beb3e684cf93604f86/contourpy-1.3.3-cp312-cp312-win_arm64.whl", hash = "sha256:07ce5ed73ecdc4a03ffe3e1b3e3c1166db35ae7584be76f65dbbe28a7791b0cc", size = 193655, upload-time = "2025-07-26T12:01:37.999Z" }, ] [[package]] name = "coverage" -version = "7.6.1" +version = "7.14.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/54/fd/0ab2772530e946e1be1abd0bc09e647ec9b02e88f0867857601fefca8953/coverage-7.14.1.tar.gz", hash = "sha256:30c08f7d90415aa98b3c990385dea2939b0da55f38515e5b369b83655f8523be", size = 920132, upload-time = "2026-05-26T20:41:36.783Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3d/b7/bdbb725ba02c5b42825b200c940f38b7a54fcad24627b7192f78f8110d76/coverage-7.14.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a06c76364a9360e33d6d23769aefdf7f66f38e2ffb60ceb1baaa4989d83b695c", size = 220022, upload-time = "2026-05-26T20:39:03.702Z" }, + { url = "https://files.pythonhosted.org/packages/72/81/fdc0898a55c6219223291ec1a1fe89966ef212ce82276aa0899df84b5de0/coverage-7.14.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fad54e871165f6ec2f536063ac74c3104508a12963e64072ba44bd822de52b0c", size = 220379, upload-time = "2026-05-26T20:39:05.381Z" }, + { url = "https://files.pythonhosted.org/packages/de/72/de048c4a25e13bce59ac6a339351c10bdf2515e07459afcdaf04dc3143a2/coverage-7.14.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:84b535f00655ecafe1d929d1fb00ed5d6fa3051ea643ab2c161a3887b86f294b", size = 251888, upload-time = "2026-05-26T20:39:07.367Z" }, + { url = "https://files.pythonhosted.org/packages/28/30/300c343f68beb9d4cbb64ec81e58c5b6b80b56927f72d2b38654ac26e013/coverage-7.14.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6b6b0853b895fe0e98cbfc580d1ec3393d9302b4b1e96a77b3f5c91fdab899e6", size = 254624, upload-time = "2026-05-26T20:39:09.037Z" }, + { url = "https://files.pythonhosted.org/packages/b1/ed/7b25642496e8170b6bac14adce00537c6e5fa2d586159401a4de3e8b49e6/coverage-7.14.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:442cc9c952b2df400cda54bb04ab87330cf2cd08a8692cbbea36773531eb6f37", size = 255739, upload-time = "2026-05-26T20:39:10.889Z" }, + { url = "https://files.pythonhosted.org/packages/7f/a2/abd210b8c4e29c24e4624916db97bb519097a91034aaeb767f937e7da794/coverage-7.14.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8270544c361ed405a27a060dbc9ed2c124b084d96dfdc2d9a2510482aef981ad", size = 257998, upload-time = "2026-05-26T20:39:12.722Z" }, + { url = "https://files.pythonhosted.org/packages/7f/24/7c50beed3792fe62f6ce0545c6686ce83379719e2c0276179333d97eae92/coverage-7.14.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:48b283b1dd6372e8de2a7a9a4c4d5dc06f4d4fd209b876f3c88a7a205a0c8f84", size = 252296, upload-time = "2026-05-26T20:39:14.259Z" }, + { url = "https://files.pythonhosted.org/packages/15/05/0f874628ebcbfc77ead559ff210281ef06a97db08481832e7dd39274a135/coverage-7.14.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5b0c99ba93a07d56f6df340bb79be53202a082b2fdb81bfe6190b741a3470d54", size = 253658, upload-time = "2026-05-26T20:39:15.923Z" }, + { url = "https://files.pythonhosted.org/packages/99/6f/ca6ad067364b337ef997802115e7ecad2abd2248b05471464b0dea02b4d4/coverage-7.14.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:e471bc5769ff073b058cfadb0d736b56ce067c8560eabeb0da88462df98c23e7", size = 251803, upload-time = "2026-05-26T20:39:17.537Z" }, + { url = "https://files.pythonhosted.org/packages/c0/30/b9b4d377cd9f40baf228068f5a81faf8450c6228503011bd499708483a50/coverage-7.14.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f497a1ea81d4cd7c10ddcaa685135b9aabd291af3d55775a9ddf3cb7a364cdd9", size = 255873, upload-time = "2026-05-26T20:39:19.414Z" }, + { url = "https://files.pythonhosted.org/packages/3c/21/7c721a9e5e6bb88547d30a787aefb97512d3f54c1324c7488d9b3743f7f9/coverage-7.14.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:2222be86d0b54f5dd5a38f45f17f315f737245e857bf0bdedc70734f84a13c02", size = 251372, upload-time = "2026-05-26T20:39:21.169Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f8ae5a2200130e1503cd7661a6cd3b2b7bacef98277fbf3571fb13f8b766/coverage-7.14.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:85e85586565842f6932abebd4c18bcb1074223dc0b3576e7d173ca710622813a", size = 253245, upload-time = "2026-05-26T20:39:23.097Z" }, + { url = "https://files.pythonhosted.org/packages/34/62/70a9024672a5f6910517d9628c52c9afbdd3cf8f46426af52bb148a56fff/coverage-7.14.1-cp312-cp312-win32.whl", hash = "sha256:4a28fd227808366b196a75476dced2eb35b351d6766ba9c858dc93319e87f4f1", size = 222567, upload-time = "2026-05-26T20:39:24.868Z" }, + { url = "https://files.pythonhosted.org/packages/f6/81/8b7cd386839b039ebe1855733b9f9449a8dec5d79564018234f185a7fa70/coverage-7.14.1-cp312-cp312-win_amd64.whl", hash = "sha256:54acdb6674a4661768d7bf7db32dfb9f46ab1d764f8aba6df75ce1a6a088724e", size = 223372, upload-time = "2026-05-26T20:39:26.603Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ba/b44d472022f620d289d95fa830143235c0c36461c6f2437ea8d51e5481ed/coverage-7.14.1-cp312-cp312-win_arm64.whl", hash = "sha256:99cd41ff91afd94896fea3bc002706b6ae4ce95727d06e4a0f39c0a8d8bd8b1a", size = 221989, upload-time = "2026-05-26T20:39:28.242Z" }, + { url = "https://files.pythonhosted.org/packages/8a/3c/1a983b9a745d7f83d53f057bcc5bf79ba6a2bbc08266b3f0c7d6fe630c9b/coverage-7.14.1-py3-none-any.whl", hash = "sha256:a252f21c27e38347e60111a3266b03827422a7d5525951aceee313aa68bab1d2", size = 211815, upload-time = "2026-05-26T20:41:34.078Z" }, +] + +[[package]] +name = "crcmod-plus" +version = "2.3.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f7/08/7e37f82e4d1aead42a7443ff06a1e406aabf7302c4f00a546e4b320b994c/coverage-7.6.1.tar.gz", hash = "sha256:953510dfb7b12ab69d20135a0662397f077c59b1e6379a768e97c59d852ee51d", size = 798791 } +sdist = { url = "https://files.pythonhosted.org/packages/0b/0c/71733bbaf38e9f1eaecfdf7f8e350993f3dcac208a5297c41503ae66e513/crcmod_plus-2.3.1.tar.gz", hash = "sha256:732ffe3c3ce3ef9b272e1827d8fb894590c4d6ff553f2a2b41ae30f4f94b0f5d", size = 22319, upload-time = "2025-10-10T22:14:21.691Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ad/5f/67af7d60d7e8ce61a4e2ddcd1bd5fb787180c8d0ae0fbd073f903b3dd95d/coverage-7.6.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:7dea0889685db8550f839fa202744652e87c60015029ce3f60e006f8c4462c93", size = 206796 }, - { url = "https://files.pythonhosted.org/packages/e1/0e/e52332389e057daa2e03be1fbfef25bb4d626b37d12ed42ae6281d0a274c/coverage-7.6.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ed37bd3c3b063412f7620464a9ac1314d33100329f39799255fb8d3027da50d3", size = 207244 }, - { url = "https://files.pythonhosted.org/packages/aa/cd/766b45fb6e090f20f8927d9c7cb34237d41c73a939358bc881883fd3a40d/coverage-7.6.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d85f5e9a5f8b73e2350097c3756ef7e785f55bd71205defa0bfdaf96c31616ff", size = 239279 }, - { url = "https://files.pythonhosted.org/packages/70/6c/a9ccd6fe50ddaf13442a1e2dd519ca805cbe0f1fcd377fba6d8339b98ccb/coverage-7.6.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9bc572be474cafb617672c43fe989d6e48d3c83af02ce8de73fff1c6bb3c198d", size = 236859 }, - { url = "https://files.pythonhosted.org/packages/14/6f/8351b465febb4dbc1ca9929505202db909c5a635c6fdf33e089bbc3d7d85/coverage-7.6.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0c0420b573964c760df9e9e86d1a9a622d0d27f417e1a949a8a66dd7bcee7bc6", size = 238549 }, - { url = "https://files.pythonhosted.org/packages/68/3c/289b81fa18ad72138e6d78c4c11a82b5378a312c0e467e2f6b495c260907/coverage-7.6.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1f4aa8219db826ce6be7099d559f8ec311549bfc4046f7f9fe9b5cea5c581c56", size = 237477 }, - { url = "https://files.pythonhosted.org/packages/ed/1c/aa1efa6459d822bd72c4abc0b9418cf268de3f60eeccd65dc4988553bd8d/coverage-7.6.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:fc5a77d0c516700ebad189b587de289a20a78324bc54baee03dd486f0855d234", size = 236134 }, - { url = "https://files.pythonhosted.org/packages/fb/c8/521c698f2d2796565fe9c789c2ee1ccdae610b3aa20b9b2ef980cc253640/coverage-7.6.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b48f312cca9621272ae49008c7f613337c53fadca647d6384cc129d2996d1133", size = 236910 }, - { url = "https://files.pythonhosted.org/packages/7d/30/033e663399ff17dca90d793ee8a2ea2890e7fdf085da58d82468b4220bf7/coverage-7.6.1-cp311-cp311-win32.whl", hash = "sha256:1125ca0e5fd475cbbba3bb67ae20bd2c23a98fac4e32412883f9bcbaa81c314c", size = 209348 }, - { url = "https://files.pythonhosted.org/packages/20/05/0d1ccbb52727ccdadaa3ff37e4d2dc1cd4d47f0c3df9eb58d9ec8508ca88/coverage-7.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:8ae539519c4c040c5ffd0632784e21b2f03fc1340752af711f33e5be83a9d6c6", size = 210230 }, - { url = "https://files.pythonhosted.org/packages/7e/d4/300fc921dff243cd518c7db3a4c614b7e4b2431b0d1145c1e274fd99bd70/coverage-7.6.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:95cae0efeb032af8458fc27d191f85d1717b1d4e49f7cb226cf526ff28179778", size = 206983 }, - { url = "https://files.pythonhosted.org/packages/e1/ab/6bf00de5327ecb8db205f9ae596885417a31535eeda6e7b99463108782e1/coverage-7.6.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5621a9175cf9d0b0c84c2ef2b12e9f5f5071357c4d2ea6ca1cf01814f45d2391", size = 207221 }, - { url = "https://files.pythonhosted.org/packages/92/8f/2ead05e735022d1a7f3a0a683ac7f737de14850395a826192f0288703472/coverage-7.6.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:260933720fdcd75340e7dbe9060655aff3af1f0c5d20f46b57f262ab6c86a5e8", size = 240342 }, - { url = "https://files.pythonhosted.org/packages/0f/ef/94043e478201ffa85b8ae2d2c79b4081e5a1b73438aafafccf3e9bafb6b5/coverage-7.6.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:07e2ca0ad381b91350c0ed49d52699b625aab2b44b65e1b4e02fa9df0e92ad2d", size = 237371 }, - { url = "https://files.pythonhosted.org/packages/1f/0f/c890339dd605f3ebc269543247bdd43b703cce6825b5ed42ff5f2d6122c7/coverage-7.6.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c44fee9975f04b33331cb8eb272827111efc8930cfd582e0320613263ca849ca", size = 239455 }, - { url = "https://files.pythonhosted.org/packages/d1/04/7fd7b39ec7372a04efb0f70c70e35857a99b6a9188b5205efb4c77d6a57a/coverage-7.6.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:877abb17e6339d96bf08e7a622d05095e72b71f8afd8a9fefc82cf30ed944163", size = 238924 }, - { url = "https://files.pythonhosted.org/packages/ed/bf/73ce346a9d32a09cf369f14d2a06651329c984e106f5992c89579d25b27e/coverage-7.6.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:3e0cadcf6733c09154b461f1ca72d5416635e5e4ec4e536192180d34ec160f8a", size = 237252 }, - { url = "https://files.pythonhosted.org/packages/86/74/1dc7a20969725e917b1e07fe71a955eb34bc606b938316bcc799f228374b/coverage-7.6.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c3c02d12f837d9683e5ab2f3d9844dc57655b92c74e286c262e0fc54213c216d", size = 238897 }, - { url = "https://files.pythonhosted.org/packages/b6/e9/d9cc3deceb361c491b81005c668578b0dfa51eed02cd081620e9a62f24ec/coverage-7.6.1-cp312-cp312-win32.whl", hash = "sha256:e05882b70b87a18d937ca6768ff33cc3f72847cbc4de4491c8e73880766718e5", size = 209606 }, - { url = "https://files.pythonhosted.org/packages/47/c8/5a2e41922ea6740f77d555c4d47544acd7dc3f251fe14199c09c0f5958d3/coverage-7.6.1-cp312-cp312-win_amd64.whl", hash = "sha256:b5d7b556859dd85f3a541db6a4e0167b86e7273e1cdc973e5b175166bb634fdb", size = 210373 }, - { url = "https://files.pythonhosted.org/packages/8c/f9/9aa4dfb751cb01c949c990d136a0f92027fbcc5781c6e921df1cb1563f20/coverage-7.6.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a4acd025ecc06185ba2b801f2de85546e0b8ac787cf9d3b06e7e2a69f925b106", size = 207007 }, - { url = "https://files.pythonhosted.org/packages/b9/67/e1413d5a8591622a46dd04ff80873b04c849268831ed5c304c16433e7e30/coverage-7.6.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a6d3adcf24b624a7b778533480e32434a39ad8fa30c315208f6d3e5542aeb6e9", size = 207269 }, - { url = "https://files.pythonhosted.org/packages/14/5b/9dec847b305e44a5634d0fb8498d135ab1d88330482b74065fcec0622224/coverage-7.6.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d0c212c49b6c10e6951362f7c6df3329f04c2b1c28499563d4035d964ab8e08c", size = 239886 }, - { url = "https://files.pythonhosted.org/packages/7b/b7/35760a67c168e29f454928f51f970342d23cf75a2bb0323e0f07334c85f3/coverage-7.6.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6e81d7a3e58882450ec4186ca59a3f20a5d4440f25b1cff6f0902ad890e6748a", size = 237037 }, - { url = "https://files.pythonhosted.org/packages/f7/95/d2fd31f1d638df806cae59d7daea5abf2b15b5234016a5ebb502c2f3f7ee/coverage-7.6.1-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:78b260de9790fd81e69401c2dc8b17da47c8038176a79092a89cb2b7d945d060", size = 239038 }, - { url = "https://files.pythonhosted.org/packages/6e/bd/110689ff5752b67924efd5e2aedf5190cbbe245fc81b8dec1abaffba619d/coverage-7.6.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a78d169acd38300060b28d600344a803628c3fd585c912cacc9ea8790fe96862", size = 238690 }, - { url = "https://files.pythonhosted.org/packages/d3/a8/08d7b38e6ff8df52331c83130d0ab92d9c9a8b5462f9e99c9f051a4ae206/coverage-7.6.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:2c09f4ce52cb99dd7505cd0fc8e0e37c77b87f46bc9c1eb03fe3bc9991085388", size = 236765 }, - { url = "https://files.pythonhosted.org/packages/d6/6a/9cf96839d3147d55ae713eb2d877f4d777e7dc5ba2bce227167d0118dfe8/coverage-7.6.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6878ef48d4227aace338d88c48738a4258213cd7b74fd9a3d4d7582bb1d8a155", size = 238611 }, - { url = "https://files.pythonhosted.org/packages/74/e4/7ff20d6a0b59eeaab40b3140a71e38cf52547ba21dbcf1d79c5a32bba61b/coverage-7.6.1-cp313-cp313-win32.whl", hash = "sha256:44df346d5215a8c0e360307d46ffaabe0f5d3502c8a1cefd700b34baf31d411a", size = 209671 }, - { url = "https://files.pythonhosted.org/packages/35/59/1812f08a85b57c9fdb6d0b383d779e47b6f643bc278ed682859512517e83/coverage-7.6.1-cp313-cp313-win_amd64.whl", hash = "sha256:8284cf8c0dd272a247bc154eb6c95548722dce90d098c17a883ed36e67cdb129", size = 210368 }, - { url = "https://files.pythonhosted.org/packages/9c/15/08913be1c59d7562a3e39fce20661a98c0a3f59d5754312899acc6cb8a2d/coverage-7.6.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:d3296782ca4eab572a1a4eca686d8bfb00226300dcefdf43faa25b5242ab8a3e", size = 207758 }, - { url = "https://files.pythonhosted.org/packages/c4/ae/b5d58dff26cade02ada6ca612a76447acd69dccdbb3a478e9e088eb3d4b9/coverage-7.6.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:502753043567491d3ff6d08629270127e0c31d4184c4c8d98f92c26f65019962", size = 208035 }, - { url = "https://files.pythonhosted.org/packages/b8/d7/62095e355ec0613b08dfb19206ce3033a0eedb6f4a67af5ed267a8800642/coverage-7.6.1-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6a89ecca80709d4076b95f89f308544ec8f7b4727e8a547913a35f16717856cb", size = 250839 }, - { url = "https://files.pythonhosted.org/packages/7c/1e/c2967cb7991b112ba3766df0d9c21de46b476d103e32bb401b1b2adf3380/coverage-7.6.1-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a318d68e92e80af8b00fa99609796fdbcdfef3629c77c6283566c6f02c6d6704", size = 246569 }, - { url = "https://files.pythonhosted.org/packages/8b/61/a7a6a55dd266007ed3b1df7a3386a0d760d014542d72f7c2c6938483b7bd/coverage-7.6.1-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:13b0a73a0896988f053e4fbb7de6d93388e6dd292b0d87ee51d106f2c11b465b", size = 248927 }, - { url = "https://files.pythonhosted.org/packages/c8/fa/13a6f56d72b429f56ef612eb3bc5ce1b75b7ee12864b3bd12526ab794847/coverage-7.6.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:4421712dbfc5562150f7554f13dde997a2e932a6b5f352edcce948a815efee6f", size = 248401 }, - { url = "https://files.pythonhosted.org/packages/75/06/0429c652aa0fb761fc60e8c6b291338c9173c6aa0f4e40e1902345b42830/coverage-7.6.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:166811d20dfea725e2e4baa71fffd6c968a958577848d2131f39b60043400223", size = 246301 }, - { url = "https://files.pythonhosted.org/packages/52/76/1766bb8b803a88f93c3a2d07e30ffa359467810e5cbc68e375ebe6906efb/coverage-7.6.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:225667980479a17db1048cb2bf8bfb39b8e5be8f164b8f6628b64f78a72cf9d3", size = 247598 }, - { url = "https://files.pythonhosted.org/packages/66/8b/f54f8db2ae17188be9566e8166ac6df105c1c611e25da755738025708d54/coverage-7.6.1-cp313-cp313t-win32.whl", hash = "sha256:170d444ab405852903b7d04ea9ae9b98f98ab6d7e63e1115e82620807519797f", size = 210307 }, - { url = "https://files.pythonhosted.org/packages/9f/b0/e0dca6da9170aefc07515cce067b97178cefafb512d00a87a1c717d2efd5/coverage-7.6.1-cp313-cp313t-win_amd64.whl", hash = "sha256:b9f222de8cded79c49bf184bdbc06630d4c58eec9459b939b4a690c82ed05657", size = 211453 }, + { url = "https://files.pythonhosted.org/packages/47/e0/2dad2e6f0cd4914b4144496d9785780ec820e200816c080df785cfa34da6/crcmod_plus-2.3.1-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:b7e35e0f7d93d7571c2c9c3d6760e456999ea4c1eae5ead6acac247b5a79e469", size = 23279, upload-time = "2025-10-10T22:13:47.281Z" }, + { url = "https://files.pythonhosted.org/packages/66/76/53c0b65b9679b903f98fc54efa32b0e5a19634712a45200c7a80674aa6f5/crcmod_plus-2.3.1-cp311-abi3-macosx_10_9_x86_64.whl", hash = "sha256:6853243120db84677b94b625112116f0ef69cd581741d20de58dce4c34242654", size = 20185, upload-time = "2025-10-10T22:13:48.06Z" }, + { url = "https://files.pythonhosted.org/packages/98/79/2b4dc9bb26394873d7699737124408b5106264ae33053fdec600e9a9fa65/crcmod_plus-2.3.1-cp311-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:17735bc4e944d552ea18c8609fc6d08a5e64ee9b29cc216ba4d623754029cc3a", size = 26999, upload-time = "2025-10-10T22:13:48.854Z" }, + { url = "https://files.pythonhosted.org/packages/bb/e8/f5d66778b5a1bff915807016561a02b5cebf6b3840fb8a2be40bbb0c8575/crcmod_plus-2.3.1-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8ac755040a2a35f43ab331978c48a9acb4ff64b425f282a296be467a410f00c3", size = 27536, upload-time = "2025-10-10T22:13:49.956Z" }, + { url = "https://files.pythonhosted.org/packages/f3/2c/0113ad30cadad40c22eef08c0f2618f2446dd282f02268fecbcfc9fda3c1/crcmod_plus-2.3.1-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7bdcfb838ca093ca673a3bbb37f62d1e5ec7182e00cc5ee2d00759f9f9f8ab11", size = 27385, upload-time = "2025-10-10T22:13:50.765Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ba/501ef1b02119402cf1a31c01eb2cb8399660bca863c2f4dd3dc060220284/crcmod_plus-2.3.1-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9166bc3c9b5e7b07b4e6854cac392b4a451b31d58d3950e48c140ab7b5d05394", size = 27135, upload-time = "2025-10-10T22:13:51.889Z" }, + { url = "https://files.pythonhosted.org/packages/49/90/d4556c9db69c83e726c5b88da3d656fdaac7d60c4d27b43cb939bed80069/crcmod_plus-2.3.1-cp311-abi3-win32.whl", hash = "sha256:cb99b694cce5c862560cf332a8b5e793620e28f0de3726995608bbd6f9b6e09a", size = 22384, upload-time = "2025-10-10T22:13:53.016Z" }, + { url = "https://files.pythonhosted.org/packages/4d/7e/57bb97a8c7b4e19900744f58b67dc83bc9c83aaac670deeede9fb3bfab6a/crcmod_plus-2.3.1-cp311-abi3-win_amd64.whl", hash = "sha256:82b0f7e968c430c5a80fe0fc59e75cb54f2e84df2ed0cee5a3ff9cadfbf8a220", size = 22912, upload-time = "2025-10-10T22:13:53.849Z" }, ] -[package.optional-dependencies] -toml = [ - { name = "tomli", marker = "python_full_version == '3.11'" }, -] - -[[package]] -name = "crcmod" -version = "1.7" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6b/b0/e595ce2a2527e169c3bcd6c33d2473c1918e0b7f6826a043ca1245dd4e5b/crcmod-1.7.tar.gz", hash = "sha256:dc7051a0db5f2bd48665a990d3ec1cc305a466a77358ca4492826f41f283601e", size = 89670 } - [[package]] name = "cryptography" -version = "43.0.1" +version = "48.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/de/ba/0664727028b37e249e73879348cc46d45c5c1a2a2e81e8166462953c5755/cryptography-43.0.1.tar.gz", hash = "sha256:203e92a75716d8cfb491dc47c79e17d0d9207ccffcbcb35f598fbe463ae3444d", size = 686927 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/58/28/b92c98a04ba762f8cdeb54eba5c4c84e63cac037a7c5e70117d337b15ad6/cryptography-43.0.1-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:8385d98f6a3bf8bb2d65a73e17ed87a3ba84f6991c155691c51112075f9ffc5d", size = 6223222 }, - { url = "https://files.pythonhosted.org/packages/33/13/1193774705783ba364121aa2a60132fa31a668b8ababd5edfa1662354ccd/cryptography-43.0.1-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27e613d7077ac613e399270253259d9d53872aaf657471473ebfc9a52935c062", size = 3794751 }, - { url = "https://files.pythonhosted.org/packages/5e/4b/39bb3c4c8cfb3e94e736b8d8859ce5c81536e91a1033b1d26770c4249000/cryptography-43.0.1-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:68aaecc4178e90719e95298515979814bda0cbada1256a4485414860bd7ab962", size = 3981827 }, - { url = "https://files.pythonhosted.org/packages/ce/dc/1471d4d56608e1013237af334b8a4c35d53895694fbb73882d1c4fd3f55e/cryptography-43.0.1-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:de41fd81a41e53267cb020bb3a7212861da53a7d39f863585d13ea11049cf277", size = 3780034 }, - { url = "https://files.pythonhosted.org/packages/ad/43/7a9920135b0d5437cc2f8f529fa757431eb6a7736ddfadfdee1cc5890800/cryptography-43.0.1-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f98bf604c82c416bc829e490c700ca1553eafdf2912a91e23a79d97d9801372a", size = 3993407 }, - { url = "https://files.pythonhosted.org/packages/cc/42/9ab8467af6c0b76f3d9b8f01d1cf25b9c9f3f2151f4acfab888d21c55a72/cryptography-43.0.1-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:61ec41068b7b74268fa86e3e9e12b9f0c21fcf65434571dbb13d954bceb08042", size = 3886457 }, - { url = "https://files.pythonhosted.org/packages/a4/65/430509e31700286ec02868a2457d2111d03ccefc20349d24e58d171ae0a7/cryptography-43.0.1-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:014f58110f53237ace6a408b5beb6c427b64e084eb451ef25a28308270086494", size = 4081499 }, - { url = "https://files.pythonhosted.org/packages/bb/18/a04b6467e6e09df8c73b91dcee8878f4a438a43a3603dc3cd6f8003b92d8/cryptography-43.0.1-cp37-abi3-win32.whl", hash = "sha256:2bd51274dcd59f09dd952afb696bf9c61a7a49dfc764c04dd33ef7a6b502a1e2", size = 2616504 }, - { url = "https://files.pythonhosted.org/packages/cc/73/0eacbdc437202edcbdc07f3576ed8fb8b0ab79d27bf2c5d822d758a72faa/cryptography-43.0.1-cp37-abi3-win_amd64.whl", hash = "sha256:666ae11966643886c2987b3b721899d250855718d6d9ce41b521252a17985f4d", size = 3067456 }, - { url = "https://files.pythonhosted.org/packages/8a/b6/bc54b371f02cffd35ff8dc6baba88304d7cf8e83632566b4b42e00383e03/cryptography-43.0.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:ac119bb76b9faa00f48128b7f5679e1d8d437365c5d26f1c2c3f0da4ce1b553d", size = 6225263 }, - { url = "https://files.pythonhosted.org/packages/00/0e/8217e348a1fa417ec4c78cd3cdf24154f5e76fd7597343a35bd403650dfd/cryptography-43.0.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1bbcce1a551e262dfbafb6e6252f1ae36a248e615ca44ba302df077a846a8806", size = 3794368 }, - { url = "https://files.pythonhosted.org/packages/3d/ed/38b6be7254d8f7251fde8054af597ee8afa14f911da67a9410a45f602fc3/cryptography-43.0.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:58d4e9129985185a06d849aa6df265bdd5a74ca6e1b736a77959b498e0505b85", size = 3981750 }, - { url = "https://files.pythonhosted.org/packages/64/f3/b7946c3887cf7436f002f4cbb1e6aec77b8d299b86be48eeadfefb937c4b/cryptography-43.0.1-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:d03a475165f3134f773d1388aeb19c2d25ba88b6a9733c5c590b9ff7bbfa2e0c", size = 3778925 }, - { url = "https://files.pythonhosted.org/packages/ac/7e/ebda4dd4ae098a0990753efbb4b50954f1d03003846b943ea85070782da7/cryptography-43.0.1-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:511f4273808ab590912a93ddb4e3914dfd8a388fed883361b02dea3791f292e1", size = 3993152 }, - { url = "https://files.pythonhosted.org/packages/43/f6/feebbd78a3e341e3913846a3bb2c29d0b09b1b3af1573c6baabc2533e147/cryptography-43.0.1-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:80eda8b3e173f0f247f711eef62be51b599b5d425c429b5d4ca6a05e9e856baa", size = 3886392 }, - { url = "https://files.pythonhosted.org/packages/bd/4c/ab0b9407d5247576290b4fd8abd06b7f51bd414f04eef0f2800675512d61/cryptography-43.0.1-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38926c50cff6f533f8a2dae3d7f19541432610d114a70808f0926d5aaa7121e4", size = 4082606 }, - { url = "https://files.pythonhosted.org/packages/05/36/e532a671998d6fcfdb9122da16434347a58a6bae9465e527e450e0bc60a5/cryptography-43.0.1-cp39-abi3-win32.whl", hash = "sha256:a575913fb06e05e6b4b814d7f7468c2c660e8bb16d8d5a1faf9b33ccc569dd47", size = 2617948 }, - { url = "https://files.pythonhosted.org/packages/b3/c6/c09cee6968add5ff868525c3815e5dccc0e3c6e89eec58dc9135d3c40e88/cryptography-43.0.1-cp39-abi3-win_amd64.whl", hash = "sha256:d75601ad10b059ec832e78823b348bfa1a59f6b8d545db3a24fd44362a1564cb", size = 3070445 }, +sdist = { url = "https://files.pythonhosted.org/packages/9f/a9/db8f313fdcd85d767d4973515e1db101f9c71f95fced83233de224673757/cryptography-48.0.0.tar.gz", hash = "sha256:5c3932f4436d1cccb036cb0eaef46e6e2db91035166f1ad6505c3c9d5a635920", size = 832984, upload-time = "2026-05-04T22:59:38.133Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/3d/01f6dd9190170a5a241e0e98c2d04be3664a9e6f5b9b872cde63aff1c3dd/cryptography-48.0.0-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:0c558d2cdffd8f4bbb30fc7134c74d2ca9a476f830bb053074498fbc86f41ed6", size = 8001587, upload-time = "2026-05-04T22:57:36.803Z" }, + { url = "https://files.pythonhosted.org/packages/b2/6e/e90527eef33f309beb811cf7c982c3aeffcce8e3edb178baa4ca3ae4a6fa/cryptography-48.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f5333311663ea94f75dd408665686aaf426563556bb5283554a3539177e03b8c", size = 4690433, upload-time = "2026-05-04T22:57:40.373Z" }, + { url = "https://files.pythonhosted.org/packages/90/04/673510ed51ddff56575f306cf1617d80411ee76831ccd3097599140efdfe/cryptography-48.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7995ef305d7165c3f11ae07f2517e5a4f1d5c18da1376a0a9ed496336b69e5f3", size = 4710620, upload-time = "2026-05-04T22:57:42.935Z" }, + { url = "https://files.pythonhosted.org/packages/14/d5/e9c4ef932c8d800490c34d8bd589d64a31d5890e27ec9e9ad532be893294/cryptography-48.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:40ba1f85eaa6959837b1d51c9767e230e14612eea4ef110ee8854ada22da1bf5", size = 4696283, upload-time = "2026-05-04T22:57:45.294Z" }, + { url = "https://files.pythonhosted.org/packages/0c/29/174b9dfb60b12d59ecfc6cfa04bc88c21b42a54f01b8aae09bb6e51e4c7f/cryptography-48.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:369a6348999f94bbd53435c894377b20ab95f25a9065c283570e70150d8abc3c", size = 5296573, upload-time = "2026-05-04T22:57:47.933Z" }, + { url = "https://files.pythonhosted.org/packages/95/38/0d29a6fd7d0d1373f0c0c88a04ba20e359b257753ac497564cd660fc1d55/cryptography-48.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:a0e692c683f4df67815a2d258b324e66f4738bd7a96a218c826dce4f4bd05d8f", size = 4743677, upload-time = "2026-05-04T22:57:50.067Z" }, + { url = "https://files.pythonhosted.org/packages/30/be/eef653013d5c63b6a490529e0316f9ac14a37602965d4903efed1399f32b/cryptography-48.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:18349bbc56f4743c8b12dc32e2bccb2cf83ee8b69a3bba74ef8ae857e26b3d25", size = 4330808, upload-time = "2026-05-04T22:57:52.301Z" }, + { url = "https://files.pythonhosted.org/packages/84/9e/500463e87abb7a0a0f9f256ec21123ecde0a7b5541a15e840ea54551fd81/cryptography-48.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:7e8eac43dfca5c4cccc6dad9a80504436fca53bb9bc3100a2386d730fbe6b602", size = 4695941, upload-time = "2026-05-04T22:57:54.603Z" }, + { url = "https://files.pythonhosted.org/packages/e3/dc/7303087450c2ec9e7fbb750e17c2abfbc658f23cbd0e54009509b7cc4091/cryptography-48.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:9ccdac7d40688ecb5a3b4a604b8a88c8002e3442d6c60aead1db2a89a041560c", size = 5252579, upload-time = "2026-05-04T22:57:57.207Z" }, + { url = "https://files.pythonhosted.org/packages/d0/c0/7101d3b7215edcdc90c45da544961fd8ed2d6448f77577460fa75a8443f7/cryptography-48.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:bd72e68b06bb1e96913f97dd4901119bc17f39d4586a5adf2d3e47bc2b9d58b5", size = 4743326, upload-time = "2026-05-04T22:57:59.535Z" }, + { url = "https://files.pythonhosted.org/packages/ac/d8/5b833bad13016f562ab9d063d68199a4bd121d18458e439515601d3357ec/cryptography-48.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:59baa2cb386c4f0b9905bd6eb4c2a79a69a128408fd31d32ca4d7102d4156321", size = 4826672, upload-time = "2026-05-04T22:58:01.996Z" }, + { url = "https://files.pythonhosted.org/packages/98/e1/7074eb8bf3c135558c73fc2bcf0f5633f912e6fb87e868a55c454080ef09/cryptography-48.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9249e3cd978541d665967ac2cb2787fd6a62bddf1e75b3e347a594d7dacf4f74", size = 4972574, upload-time = "2026-05-04T22:58:03.968Z" }, + { url = "https://files.pythonhosted.org/packages/04/70/e5a1b41d325f797f39427aa44ef8baf0be500065ab6d8e10369d850d4a4f/cryptography-48.0.0-cp311-abi3-win32.whl", hash = "sha256:9c459db21422be75e2809370b829a87eb37f74cd785fc4aa9ea1e5f43b47cda4", size = 3294868, upload-time = "2026-05-04T22:58:06.467Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ac/8ac51b4a5fc5932eb7ee5c517ba7dc8cd834f0048962b6b352f00f41ebf9/cryptography-48.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:5b012212e08b8dd5edc78ef54da83dd9892fd9105323b3993eff6bea65dc21d7", size = 3817107, upload-time = "2026-05-04T22:58:08.845Z" }, + { url = "https://files.pythonhosted.org/packages/f2/63/61d4a4e1c6b6bab6ce1e213cd36a24c415d90e76d78c5eb8577c5541d2e8/cryptography-48.0.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:58d00498e8933e4a194f3076aee1b4a97dfec1a6da444535755822fe5d8b0b86", size = 7983482, upload-time = "2026-05-04T22:58:43.769Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ac/f5b5995b87770c693e2596559ffafe195b4033a57f14a82268a2842953f3/cryptography-48.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:614d0949f4790582d2cc25553abd09dd723025f0c0e7c67376a1d77196743d6e", size = 4683266, upload-time = "2026-05-04T22:58:46.064Z" }, + { url = "https://files.pythonhosted.org/packages/ec/c6/8b14f67e18338fbc4adb76f66c001f5c3610b3e2d1837f268f47a347dbbb/cryptography-48.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7ce4bfae76319a532a2dc68f82cc32f5676ee792a983187dac07183690e5c66f", size = 4696228, upload-time = "2026-05-04T22:58:48.22Z" }, + { url = "https://files.pythonhosted.org/packages/ea/73/f808fbae9514bd91b47875b003f13e284c8c6bdfd904b7944e803937eec1/cryptography-48.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:2eb992bbd4661238c5a397594c83f5b4dc2bc5b848c365c8f991b6780efcc5c7", size = 4689097, upload-time = "2026-05-04T22:58:50.9Z" }, + { url = "https://files.pythonhosted.org/packages/93/01/d86632d7d28db8ae83221995752eeb6639ffb374c2d22955648cf8d52797/cryptography-48.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:22a5cb272895dce158b2cacdfdc3debd299019659f42947dbdac6f32d68fe832", size = 5283582, upload-time = "2026-05-04T22:58:53.017Z" }, + { url = "https://files.pythonhosted.org/packages/02/e1/50edc7a50334807cc4791fc4a0ce7468b4a1416d9138eab358bfc9a3d70b/cryptography-48.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2b4d59804e8408e2fea7d1fbaf218e5ec984325221db76e6a241a9abd6cdd95c", size = 4730479, upload-time = "2026-05-04T22:58:55.611Z" }, + { url = "https://files.pythonhosted.org/packages/6f/af/99a582b1b1641ff5911ac559beb45097cf79efd4ead4657f578ef1af2d47/cryptography-48.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:984a20b0f62a26f48a3396c72e4bc34c66e356d356bf370053066b3b6d54634a", size = 4326481, upload-time = "2026-05-04T22:58:57.607Z" }, + { url = "https://files.pythonhosted.org/packages/90/ee/89aa26a06ef0a7d7611788ffd571a7c50e368cc6a4d5eef8b4884e866edb/cryptography-48.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:5a5ed8fde7a1d09376ca0b40e68cd59c69fe23b1f9768bd5824f54681626032a", size = 4688713, upload-time = "2026-05-04T22:59:00.077Z" }, + { url = "https://files.pythonhosted.org/packages/70/ba/bcb1b0bb7a33d4c7c0c4d4c7874b4a62ae4f56113a5f4baefa362dfb1f0f/cryptography-48.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:8cd666227ef7af430aa5914a9910e0ddd703e75f039cef0825cd0da71b6b711a", size = 5238165, upload-time = "2026-05-04T22:59:02.317Z" }, + { url = "https://files.pythonhosted.org/packages/c9/70/ca4003b1ce5ca3dc3186ada51908c8a9b9ff7d5cab83cc0d43ee14ec144f/cryptography-48.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9071196d81abc88b3516ac8cdfad32e2b66dd4a5393a8e68a961e9161ddc6239", size = 4729947, upload-time = "2026-05-04T22:59:05.255Z" }, + { url = "https://files.pythonhosted.org/packages/44/a0/4ec7cf774207905aef1a8d11c3750d5a1db805eb380ee4e16df317870128/cryptography-48.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1e2d54c8be6152856a36f0882ab231e70f8ec7f14e93cf87db8a2ed056bf160c", size = 4822059, upload-time = "2026-05-04T22:59:07.802Z" }, + { url = "https://files.pythonhosted.org/packages/1e/75/a2e55f99c16fcac7b5d6c1eb19ad8e00799854d6be5ca845f9259eae1681/cryptography-48.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a5da777e32ffed6f85a7b2b3f7c5cbc88c146bfcd0a1d7baf5fcc6c52ee35dd4", size = 4960575, upload-time = "2026-05-04T22:59:09.851Z" }, + { url = "https://files.pythonhosted.org/packages/b8/23/6e6f32143ab5d8b36ca848a502c4bcd477ae75b9e1677e3530d669062578/cryptography-48.0.0-cp39-abi3-win32.whl", hash = "sha256:77a2ccbbe917f6710e05ba9adaa25fb5075620bf3ea6fb751997875aff4ae4bd", size = 3279117, upload-time = "2026-05-04T22:59:12.019Z" }, + { url = "https://files.pythonhosted.org/packages/9d/9a/0fea98a70cf1749d41d738836f6349d97945f7c89433a259a6c2642eefeb/cryptography-48.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:16cd65b9330583e4619939b3a3843eec1e6e789744bb01e7c7e2e62e33c239c8", size = 3792100, upload-time = "2026-05-04T22:59:14.884Z" }, ] [[package]] name = "cycler" version = "0.12.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615 } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321 }, + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, ] [[package]] name = "cython" -version = "3.0.11" +version = "3.2.5" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/84/4d/b720d6000f4ca77f030bd70f12550820f0766b568e43f11af7f7ad9061aa/cython-3.0.11.tar.gz", hash = "sha256:7146dd2af8682b4ca61331851e6aebce9fe5158e75300343f80c07ca80b1faff", size = 2755544 } +sdist = { url = "https://files.pythonhosted.org/packages/3f/3b/ebd94c8b85f8e41b5015a9ed94ee3df866024d480d05cd08b774684fb81d/cython-3.2.5.tar.gz", hash = "sha256:3dd42e4cf36ad15f265bdfec2337cc00c688c8eb6d374ffd13bb19437c27bba1", size = 3286381, upload-time = "2026-05-23T19:34:08.439Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f8/73/e55be864199cd674cb3426a052726c205589b1ac66fb0090e7fe793b60b3/Cython-3.0.11-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:75ba1c70b6deeaffbac123856b8d35f253da13552207aa969078611c197377e4", size = 3113599 }, - { url = "https://files.pythonhosted.org/packages/09/c9/537108d0980beffff55336baaf8b34162ad0f3f33ededcb5db07069bc8ef/Cython-3.0.11-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:af91497dc098718e634d6ec8f91b182aea6bb3690f333fc9a7777bc70abe8810", size = 3441131 }, - { url = "https://files.pythonhosted.org/packages/93/03/e330b241ad8aa12bb9d98b58fb76d4eb7dcbe747479aab5c29fce937b9e7/Cython-3.0.11-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3999fb52d3328a6a5e8c63122b0a8bd110dfcdb98dda585a3def1426b991cba7", size = 3595065 }, - { url = "https://files.pythonhosted.org/packages/4a/84/a3c40f2c0439d425daa5aa4e3a6fdbbb41341a14a6fd97f94906f528d9a4/Cython-3.0.11-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d566a4e09b8979be8ab9f843bac0dd216c81f5e5f45661a9b25cd162ed80508c", size = 3641667 }, - { url = "https://files.pythonhosted.org/packages/6d/93/bdb61e0254ed8f1d21a14088a473584ecb1963d68dba5682158aa45c70ef/Cython-3.0.11-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:46aec30f217bdf096175a1a639203d44ac73a36fe7fa3dd06bd012e8f39eca0f", size = 3503650 }, - { url = "https://files.pythonhosted.org/packages/f8/62/0da548144c71176155ff5355c4cc40fb28b9effe22e830b55cec8072bdf2/Cython-3.0.11-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ddd1fe25af330f4e003421636746a546474e4ccd8f239f55d2898d80983d20ed", size = 3709662 }, - { url = "https://files.pythonhosted.org/packages/56/d3/d9c9eaf3611a9fe5256266d07b6a5f9069aa84d20d9f6aa5824289513315/Cython-3.0.11-cp311-cp311-win32.whl", hash = "sha256:221de0b48bf387f209003508e602ce839a80463522fc6f583ad3c8d5c890d2c1", size = 2577870 }, - { url = "https://files.pythonhosted.org/packages/fd/10/236fcc0306f85a2db1b8bc147aea714b66a2f27bac4d9e09e5b2c5d5dcca/Cython-3.0.11-cp311-cp311-win_amd64.whl", hash = "sha256:3ff8ac1f0ecd4f505db4ab051e58e4531f5d098b6ac03b91c3b902e8d10c67b3", size = 2785053 }, - { url = "https://files.pythonhosted.org/packages/58/50/fbb23239efe2183e4eaf76689270d6f5b3bbcf9be9ad1eb97cc34349e6fc/Cython-3.0.11-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:11996c40c32abf843ba652a6d53cb15944c88d91f91fc4e6f0028f5df8a8f8a1", size = 3141274 }, - { url = "https://files.pythonhosted.org/packages/87/e5/76379edb21fd5bb9e2aaa1d305492bc35bba96dfb51f5d96867d9863b6df/Cython-3.0.11-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:63f2c892e9f9c1698ecfee78205541623eb31cd3a1b682668be7ac12de94aa8e", size = 3340904 }, - { url = "https://files.pythonhosted.org/packages/9a/ef/44af6aded89444dc45f4466ff207a05d3376c641cf1146c03fd14c55ae64/Cython-3.0.11-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8b14c24f1dc4c4c9d997cca8d1b7fb01187a218aab932328247dcf5694a10102", size = 3514052 }, - { url = "https://files.pythonhosted.org/packages/e0/d5/ef8c7b6aa7a83c508f5c3bf0dfb9eb0a2a9be910c0b1f205f842128269c3/Cython-3.0.11-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c8eed5c015685106db15dd103fd040948ddca9197b1dd02222711815ea782a27", size = 3573721 }, - { url = "https://files.pythonhosted.org/packages/e5/4a/58d6c208563504a35febff94904bb291b368a8b0f28a5e0593c770967caa/Cython-3.0.11-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:780f89c95b8aec1e403005b3bf2f0a2afa060b3eba168c86830f079339adad89", size = 3393594 }, - { url = "https://files.pythonhosted.org/packages/a0/92/a60a400be286dc661609da9db903680bba1423362000b689cf8ef0aec811/Cython-3.0.11-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a690f2ff460682ea985e8d38ec541be97e0977fa0544aadc21efc116ff8d7579", size = 3601319 }, - { url = "https://files.pythonhosted.org/packages/ac/11/f02fc24d1a071b93e1d07497b0a528687b1f93bb4945c635119480fab3c0/Cython-3.0.11-cp312-cp312-win32.whl", hash = "sha256:2252b5aa57621848e310fe7fa6f7dce5f73aa452884a183d201a8bcebfa05a00", size = 2608335 }, - { url = "https://files.pythonhosted.org/packages/35/00/78ffea3a0ab176267a25ff049518b2582db7ac265bbf27944243d1a81ce2/Cython-3.0.11-cp312-cp312-win_amd64.whl", hash = "sha256:da394654c6da15c1d37f0b7ec5afd325c69a15ceafee2afba14b67a5df8a82c8", size = 2792586 }, - { url = "https://files.pythonhosted.org/packages/eb/19/1d7164b724f62b67c59aa3531a2be8ed1a0c7e4e80afcc6502d8409c4ee3/Cython-3.0.11-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4341d6a64d47112884e0bcf31e6c075268220ee4cd02223047182d4dda94d637", size = 3134881 }, - { url = "https://files.pythonhosted.org/packages/0a/d7/8d834d7ec4b6e55db857f44e328246d40cb527917040fabf3c48d27609b3/Cython-3.0.11-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:351955559b37e6c98b48aecb178894c311be9d731b297782f2b78d111f0c9015", size = 3330582 }, - { url = "https://files.pythonhosted.org/packages/1c/ae/d520f3cd94a8926bc47275a968e51bbc669a28f27a058cdfc5c3081fbbf7/Cython-3.0.11-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c02361af9bfa10ff1ccf967fc75159e56b1c8093caf565739ed77a559c1f29f", size = 3503750 }, - { url = "https://files.pythonhosted.org/packages/6e/e4/45c556f4a6d40b6938368d420d3c985bbef9088b7d4a8d8c6648d50e4a94/Cython-3.0.11-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6823aef13669a32caf18bbb036de56065c485d9f558551a9b55061acf9c4c27f", size = 3566498 }, - { url = "https://files.pythonhosted.org/packages/ce/2d/544f6aa3cab31b99ddb07e7eaaaca6a43db52fe0dc59090195c48fc0b033/Cython-3.0.11-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6fb68cef33684f8cc97987bee6ae919eee7e18ee6a3ad7ed9516b8386ef95ae6", size = 3389063 }, - { url = "https://files.pythonhosted.org/packages/55/1a/9d871cc1514df273cd2ccfe3efe5ff1df509ce11768c02a834052709f152/Cython-3.0.11-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:790263b74432cb997740d73665f4d8d00b9cd1cecbdd981d93591ddf993d4f12", size = 3596353 }, - { url = "https://files.pythonhosted.org/packages/47/4e/4db412f595de4b2224a81ea5332ce107ce3e93bf87275c78648f2e3e37b8/Cython-3.0.11-cp313-cp313-win32.whl", hash = "sha256:e6dd395d1a704e34a9fac00b25f0036dce6654c6b898be6f872ac2bb4f2eda48", size = 2602768 }, - { url = "https://files.pythonhosted.org/packages/e7/91/8a29e1bce2f8a893a4c24874943b64e8ede14fac9990bd4a3f13a46c2720/Cython-3.0.11-cp313-cp313-win_amd64.whl", hash = "sha256:52186101d51497519e99b60d955fd5cb3bf747c67f00d742e70ab913f1e42d31", size = 2784414 }, - { url = "https://files.pythonhosted.org/packages/43/39/bdbec9142bc46605b54d674bf158a78b191c2b75be527c6dcf3e6dfe90b8/Cython-3.0.11-py2.py3-none-any.whl", hash = "sha256:0e25f6425ad4a700d7f77cd468da9161e63658837d1bc34861a9861a4ef6346d", size = 1171267 }, + { url = "https://files.pythonhosted.org/packages/20/a6/efc97000fdb2f34e2431eb09a6ab4de9fbd3bcdb73a8f9d224afa4a9abd3/cython-3.2.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:eb38b89e5a8eb2508a1a0832063826b0703dfb02be84e4aa34b8818ce0ca50fe", size = 2979670, upload-time = "2026-05-23T19:34:41.281Z" }, + { url = "https://files.pythonhosted.org/packages/84/b7/951206add609c11f3bb9e82329a653c39a8bc9039c13bce57362caf84bb6/cython-3.2.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c80e1e5cba5b4b9890364e9360939fc298c474f25754bb4bb861270d24bda6d6", size = 3232779, upload-time = "2026-05-23T19:34:43.347Z" }, + { url = "https://files.pythonhosted.org/packages/a1/aa/8a1d02eabe8bc1e5066fde920010a4a4a4c5f0bac3625d8e7c946f72ef98/cython-3.2.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e2c976ee96da4deff50506c7882ccebb4a932fc178ef27eb42bfde959839", size = 3400054, upload-time = "2026-05-23T19:34:45.6Z" }, + { url = "https://files.pythonhosted.org/packages/57/30/67a1b6192c828456f096d4bf4d840b9a749904b9030d9f857549fc1f9b53/cython-3.2.5-cp312-cp312-win_amd64.whl", hash = "sha256:29243859d6824e2d33bae92fc83d591c3671b6d9ac1b757fa264b894ae906c2b", size = 2759539, upload-time = "2026-05-23T19:34:47.341Z" }, + { url = "https://files.pythonhosted.org/packages/a3/de/e3e0cf5704fe569d54b8cd5dc316c9fbf08b1b74728732f86e90168b7a3f/cython-3.2.5-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:224149d18d980e6ea5001b70fc7ce096c1891d59035dfa9cc5ede50f55804913", size = 2879054, upload-time = "2026-05-23T19:35:18.265Z" }, + { url = "https://files.pythonhosted.org/packages/3c/d1/0a6a8caa35c4c57a1f1866b1141c2d00c6af67f73edbe34b2baec6919ccf/cython-3.2.5-cp39-abi3-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:992a50e90d01813333752f374a4405863113059ec67102ab8d6a431a171ee328", size = 3210422, upload-time = "2026-05-23T19:35:20.641Z" }, + { url = "https://files.pythonhosted.org/packages/07/b8/2523398ec96bb0c9bf69ada625a2256a581940b09fe11fcd0029f26ef4ad/cython-3.2.5-cp39-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8d7b81e6a52a84a02993f01aa5873786ba1dd593c892d93d5fe9866da0bad297", size = 2863809, upload-time = "2026-05-23T19:35:22.416Z" }, + { url = "https://files.pythonhosted.org/packages/ff/3d/6b2f316d97bdb02283d79934e50da5cedfec65a536cdd3d69cc3a93486f9/cython-3.2.5-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:34d21aeb08477c9173e8be7a566b19e880a7c8109ec6bb47a4b20cb680141114", size = 2992518, upload-time = "2026-05-23T19:35:24.737Z" }, + { url = "https://files.pythonhosted.org/packages/68/2c/c9238db1eba208e226d363c00c8b74bf531a6b40c75df2334baa85e142bf/cython-3.2.5-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:c4c79e697db55f082a2d3ba97702e71881d5bb1f56f0a80fa338e69101e4c59b", size = 2886221, upload-time = "2026-05-23T19:35:26.64Z" }, + { url = "https://files.pythonhosted.org/packages/2d/15/229cc5c2ed92bb8b43c73a3d31c2b4eaf498409300c34a06d93147f7a42b/cython-3.2.5-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:39acb30eba78ba6d995d5cf3d97d57d450663d93aac6f8b93753d2b89d768c60", size = 3226990, upload-time = "2026-05-23T19:35:28.979Z" }, + { url = "https://files.pythonhosted.org/packages/56/31/9c0024f2c772fc303f8cae2a204bcad2fedfaf921ba71cf13a878639432d/cython-3.2.5-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:382122de8d6b6024fc374fabc3a2b14ba5860ed981c25055ed14fe44278b9dc7", size = 3111004, upload-time = "2026-05-23T19:35:30.957Z" }, + { url = "https://files.pythonhosted.org/packages/82/71/8b528247e42ee63cbe1c1d53805d30b28663fa782c88da4a9b69a1a412dd/cython-3.2.5-cp39-abi3-win32.whl", hash = "sha256:0bc29c7f870b09efdb1f583fbec9592b33af81a7ce273b89c8f5163d7572d5c1", size = 2440395, upload-time = "2026-05-23T19:35:33.082Z" }, + { url = "https://files.pythonhosted.org/packages/50/4d/81c91d3279d156ee2c9ead7ed9eaa862e498066d759e92fb83d0d842c5a7/cython-3.2.5-cp39-abi3-win_arm64.whl", hash = "sha256:85b2944c3eddfc230f9082720195a2e9f869908e5a8b3185be1be832755ee7fc", size = 2446963, upload-time = "2026-05-23T19:35:35.267Z" }, + { url = "https://files.pythonhosted.org/packages/d4/5c/9cd909e6a8bb178e4e0f9a2a9227c8201a2be38abe45ada4a4c3e9154277/cython-3.2.5-py3-none-any.whl", hash = "sha256:dc1c8cebb7df5bce37f5f8dc1e5bf04313272a5973d50a55c0ec76c83812911b", size = 1257622, upload-time = "2026-05-23T19:34:05.163Z" }, ] [[package]] -name = "dictdiffer" -version = "0.9.0" +name = "deepmerge" +version = "2.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/61/7b/35cbccb7effc5d7e40f4c55e2b79399e1853041997fcda15c9ff160abba0/dictdiffer-0.9.0.tar.gz", hash = "sha256:17bacf5fbfe613ccf1b6d512bd766e6b21fb798822a133aa86098b8ac9997578", size = 31513 } +sdist = { url = "https://files.pythonhosted.org/packages/a8/3a/b0ba594708f1ad0bc735884b3ad854d3ca3bdc1d741e56e40bbda6263499/deepmerge-2.0.tar.gz", hash = "sha256:5c3d86081fbebd04dd5de03626a0607b809a98fb6ccba5770b62466fe940ff20", size = 19890, upload-time = "2024-08-30T05:31:50.308Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/47/ef/4cb333825d10317a36a1154341ba37e6e9c087bac99c1990ef07ffdb376f/dictdiffer-0.9.0-py2.py3-none-any.whl", hash = "sha256:442bfc693cfcadaf46674575d2eba1c53b42f5e404218ca2c2ff549f2df56595", size = 16754 }, + { url = "https://files.pythonhosted.org/packages/2d/82/e5d2c1c67d19841e9edc74954c827444ae826978499bde3dfc1d007c8c11/deepmerge-2.0-py3-none-any.whl", hash = "sha256:6de9ce507115cff0bed95ff0ce9ecc31088ef50cbdf09bc90a09349a318b3d00", size = 13475, upload-time = "2024-08-30T05:31:48.659Z" }, ] [[package]] name = "dnspython" -version = "2.6.1" +version = "2.8.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/37/7d/c871f55054e403fdfd6b8f65fd6d1c4e147ed100d3e9f9ba1fe695403939/dnspython-2.6.1.tar.gz", hash = "sha256:e8f0f9c23a7b7cb99ded64e6c3a6f3e701d78f50c55e002b839dea7225cff7cc", size = 332727 } +sdist = { url = "https://files.pythonhosted.org/packages/8c/8b/57666417c0f90f08bcafa776861060426765fdb422eb10212086fb811d26/dnspython-2.8.0.tar.gz", hash = "sha256:181d3c6996452cb1189c4046c61599b84a5a86e099562ffde77d26984ff26d0f", size = 368251, upload-time = "2025-09-07T18:58:00.022Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/87/a1/8c5287991ddb8d3e4662f71356d9656d91ab3a36618c3dd11b280df0d255/dnspython-2.6.1-py3-none-any.whl", hash = "sha256:5ef3b9680161f6fa89daf8ad451b5f1a33b18ae8a1c6778cdf4b43f08c0a6e50", size = 307696 }, + { url = "https://files.pythonhosted.org/packages/ba/5a/18ad964b0086c6e62e2e7500f7edc89e3faa45033c71c1893d34eed2b2de/dnspython-2.8.0-py3-none-any.whl", hash = "sha256:01d9bbc4a2d76bf0db7c1f729812ded6d912bd318d3b1cf81d30c0f845dbf3af", size = 331094, upload-time = "2025-09-07T18:57:58.071Z" }, ] [[package]] -name = "ewmhlib" -version = "0.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "python-xlib", marker = "sys_platform == 'linux'" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/2f/3a/46ca34abf0725a754bc44ef474ad34aedcc3ea23b052d97b18b76715a6a9/EWMHlib-0.2-py3-none-any.whl", hash = "sha256:f5b07d8cfd4c7734462ee744c32d490f2f3233fa7ab354240069344208d2f6f5", size = 46657 }, -] +name = "eigen" +version = "3.4.0" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=eigen&rev=release-eigen#f855b17636a376d8399f3df03629ff3e535f6b22" } [[package]] name = "execnet" -version = "2.1.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/bb/ff/b4c0dc78fbe20c3e59c0c7334de0c27eb4001a2b2017999af398bf730817/execnet-2.1.1.tar.gz", hash = "sha256:5189b52c6121c24feae288166ab41b32549c7e2348652736540b9e6e7d4e72e3", size = 166524 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/43/09/2aea36ff60d16dd8879bdb2f5b3ee0ba8d08cbbdcdfe870e695ce3784385/execnet-2.1.1-py3-none-any.whl", hash = "sha256:26dee51f1b80cebd6d0ca8e74dd8745419761d3bef34163928cbebbdc4749fdc", size = 40612 }, -] - -[[package]] -name = "farama-notifications" -version = "0.0.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/2e/2c/8384832b7a6b1fd6ba95bbdcae26e7137bb3eedc955c42fd5cdcc086cfbf/Farama-Notifications-0.0.4.tar.gz", hash = "sha256:13fceff2d14314cf80703c8266462ebf3733c7d165336eee998fc58e545efd18", size = 2131 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/05/2c/ffc08c54c05cdce6fbed2aeebc46348dbe180c6d2c541c7af7ba0aa5f5f8/Farama_Notifications-0.0.4-py3-none-any.whl", hash = "sha256:14de931035a41961f7c056361dc7f980762a143d05791ef5794a751a2caf05ae", size = 2511 }, -] - -[[package]] -name = "filelock" -version = "3.15.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/08/dd/49e06f09b6645156550fb9aee9cc1e59aba7efbc972d665a1bd6ae0435d4/filelock-3.15.4.tar.gz", hash = "sha256:2207938cbc1844345cb01a5a95524dae30f0ce089eba5b00378295a17e3e90cb", size = 18007 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ae/f0/48285f0262fe47103a4a45972ed2f9b93e4c80b8fd609fa98da78b2a5706/filelock-3.15.4-py3-none-any.whl", hash = "sha256:6ca1fffae96225dab4c6eaf1c4f4f28cd2568d3ec2a44e15a08520504de468e7", size = 16159 }, -] - -[[package]] -name = "flaky" -version = "3.8.1" +version = "2.1.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5b/c5/ef69119a01427204ff2db5fc8f98001087bcce719bbb94749dcd7b191365/flaky-3.8.1.tar.gz", hash = "sha256:47204a81ec905f3d5acfbd61daeabcada8f9d4031616d9bcb0618461729699f5", size = 25248 } +sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/b8/b830fc43663246c3f3dd1ae7dca4847b96ed992537e85311e27fa41ac40e/flaky-3.8.1-py2.py3-none-any.whl", hash = "sha256:194ccf4f0d3a22b2de7130f4b62e45e977ac1b5ccad74d4d48f3005dcc38815e", size = 19139 }, + { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" }, ] [[package]] -name = "flatbuffers" -version = "24.3.25" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a9/74/2df95ef84b214d2bee0886d572775a6f38793f5ca6d7630c3239c91104ac/flatbuffers-24.3.25.tar.gz", hash = "sha256:de2ec5b203f21441716617f38443e0a8ebf3d25bf0d9c0bb0ce68fa00ad546a4", size = 22139 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/41/f0/7e988a019bc54b2dbd0ad4182ef2d53488bb02e58694cd79d61369e85900/flatbuffers-24.3.25-py2.py3-none-any.whl", hash = "sha256:8dbdec58f935f3765e4f7f3cf635ac3a77f83568138d6a2311f524ec96364812", size = 26784 }, -] +name = "ffmpeg" +version = "7.1.0" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=ffmpeg&rev=release-ffmpeg#f5153626027621f8ac0cdec056d254d3a1ef6acd" } [[package]] name = "fonttools" -version = "4.53.1" +version = "4.63.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c6/cb/cd80a0da995adde8ade6044a8744aee0da5efea01301cadf770f7fbe7dcc/fonttools-4.53.1.tar.gz", hash = "sha256:e128778a8e9bc11159ce5447f76766cefbd876f44bd79aff030287254e4752c4", size = 3452797 } +sdist = { url = "https://files.pythonhosted.org/packages/84/69/c97f2c18e0db87d2c7b15da1974dace76ae938f1cfa22e2727a648b7ed43/fonttools-4.63.0.tar.gz", hash = "sha256:caeb583deeb5168e694b65cda8b4ee62abedfa66cf88488734466f2366b9c4e0", size = 3597189, upload-time = "2026-05-14T12:04:30.958Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8b/6a/206391c869ab22d1374e2575cad7cab36b93b9e3d37f48f4696eed2c6e9e/fonttools-4.53.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:da33440b1413bad53a8674393c5d29ce64d8c1a15ef8a77c642ffd900d07bfe1", size = 2762654 }, - { url = "https://files.pythonhosted.org/packages/f5/7e/4060d88dbfaf446e1c9f0fe9cf13dba36ba47c4da85ce5c1df084ce47e7d/fonttools-4.53.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:5ff7e5e9bad94e3a70c5cd2fa27f20b9bb9385e10cddab567b85ce5d306ea923", size = 2247865 }, - { url = "https://files.pythonhosted.org/packages/e1/67/fff766817e17d67208f8a1e72de15066149485acb5e4ff0816b11fd5fca3/fonttools-4.53.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c6e7170d675d12eac12ad1a981d90f118c06cf680b42a2d74c6c931e54b50719", size = 4873046 }, - { url = "https://files.pythonhosted.org/packages/a4/22/0a0ad59d9367997fd74a00ad2e88d10559122e09f105e94d34c155aecc0a/fonttools-4.53.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bee32ea8765e859670c4447b0817514ca79054463b6b79784b08a8df3a4d78e3", size = 4920859 }, - { url = "https://files.pythonhosted.org/packages/0b/c4/b4e2f1699a5e2244373a6e8175f862f49f377b444adc6c7b1fe1f5b3d04d/fonttools-4.53.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6e08f572625a1ee682115223eabebc4c6a2035a6917eac6f60350aba297ccadb", size = 4885904 }, - { url = "https://files.pythonhosted.org/packages/64/e7/b9a07c386adf8ad0348163fbcaab74daed6ef18ddb3f49b61b5c19900aeb/fonttools-4.53.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b21952c092ffd827504de7e66b62aba26fdb5f9d1e435c52477e6486e9d128b2", size = 5054708 }, - { url = "https://files.pythonhosted.org/packages/e9/53/2a79462ae38d7943e63290209c04fef89677c67b29cb329cdc549c18d4d5/fonttools-4.53.1-cp311-cp311-win32.whl", hash = "sha256:9dfdae43b7996af46ff9da520998a32b105c7f098aeea06b2226b30e74fbba88", size = 2158885 }, - { url = "https://files.pythonhosted.org/packages/c8/e1/059700c154bd7170d1c37061239836d2e51ff608f47075450f06dd3c292a/fonttools-4.53.1-cp311-cp311-win_amd64.whl", hash = "sha256:d4d0096cb1ac7a77b3b41cd78c9b6bc4a400550e21dc7a92f2b5ab53ed74eb02", size = 2205133 }, - { url = "https://files.pythonhosted.org/packages/87/63/8271f50f3e7bff8b78e03914c4c2893f2f21bd4db2975c60d11ecfbdd174/fonttools-4.53.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:d92d3c2a1b39631a6131c2fa25b5406855f97969b068e7e08413325bc0afba58", size = 2756146 }, - { url = "https://files.pythonhosted.org/packages/dd/bd/cb8fd2dddd68089c112bf42a88afe188b8ace73f94406539857dcc9347a6/fonttools-4.53.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3b3c8ebafbee8d9002bd8f1195d09ed2bd9ff134ddec37ee8f6a6375e6a4f0e8", size = 2244990 }, - { url = "https://files.pythonhosted.org/packages/ae/71/2b9761e25697bdaf3dfe8269541bd4324f3eb0e4cc13f71d7f90cd272394/fonttools-4.53.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:32f029c095ad66c425b0ee85553d0dc326d45d7059dbc227330fc29b43e8ba60", size = 4787604 }, - { url = "https://files.pythonhosted.org/packages/db/2b/5779cfd48625e013c2dfcf0c246474d5b1f5d061a5f1e476037bf9fff3a3/fonttools-4.53.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:10f5e6c3510b79ea27bb1ebfcc67048cde9ec67afa87c7dd7efa5c700491ac7f", size = 4871141 }, - { url = "https://files.pythonhosted.org/packages/b8/3d/ac3cec35a503bf789d03e9d155a220c9e574f4f1573f00a3bea55695d535/fonttools-4.53.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f677ce218976496a587ab17140da141557beb91d2a5c1a14212c994093f2eae2", size = 4764714 }, - { url = "https://files.pythonhosted.org/packages/ac/9f/27135ac0328e22cca1ba23ee6a1a1f971c13e9f0387adc5598d4635c501d/fonttools-4.53.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:9e6ceba2a01b448e36754983d376064730690401da1dd104ddb543519470a15f", size = 5023568 }, - { url = "https://files.pythonhosted.org/packages/04/40/44d6a94e52e91fe104f9ca95944466af34828992cbc66b666f541de137f1/fonttools-4.53.1-cp312-cp312-win32.whl", hash = "sha256:791b31ebbc05197d7aa096bbc7bd76d591f05905d2fd908bf103af4488e60670", size = 2147572 }, - { url = "https://files.pythonhosted.org/packages/6d/9a/b695930e1b4e6929cc60e294489421632a05c105ac8c56ee63ef56a47872/fonttools-4.53.1-cp312-cp312-win_amd64.whl", hash = "sha256:6ed170b5e17da0264b9f6fae86073be3db15fa1bd74061c8331022bca6d09bab", size = 2193313 }, - { url = "https://files.pythonhosted.org/packages/e4/b9/0394d67056d4ad36a3807b439571934b318f1df925593a95e9ec0516b1a7/fonttools-4.53.1-py3-none-any.whl", hash = "sha256:f1f8758a2ad110bd6432203a344269f445a2907dc24ef6bccfd0ac4e14e0d71d", size = 1090472 }, + { url = "https://files.pythonhosted.org/packages/08/ef/b3c6b9b5be2f82416d73fe2ed2e96e2793cd80e7510bd6a17ca79cdd88ec/fonttools-4.63.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:37dd23e621e3b0aef1baa70a303b80aaf38449632cfc8fd2a55fb285bbccfc02", size = 2881131, upload-time = "2026-05-14T12:03:13.386Z" }, + { url = "https://files.pythonhosted.org/packages/44/a0/c815bea63117fa63e4e1c01f8a1110d2112fa003f838e6467094ec2432ce/fonttools-4.63.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a9faff9e0c1f76f9fd55899d2ce785832efebab37eb8ae13995853aef178bef0", size = 2426704, upload-time = "2026-05-14T12:03:15.801Z" }, + { url = "https://files.pythonhosted.org/packages/44/04/0b91d8e916e92ad1fac9e4624760baf0fd5ff2ead614c2f68fb21373f03f/fonttools-4.63.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef3048ef05dbb552b89817713d9cac912e00d0fde4a3105c00d29e52e10c89af", size = 5044298, upload-time = "2026-05-14T12:03:18.085Z" }, + { url = "https://files.pythonhosted.org/packages/77/c7/2342da9830e3e9d4870305ca5d2091d2a83284f2953079b7bdd3b5e029d8/fonttools-4.63.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:58dc6bb86a78d782f00f9190ca02c119cf5bbe2807536e361e18d42019f877d8", size = 4999800, upload-time = "2026-05-14T12:03:20.161Z" }, + { url = "https://files.pythonhosted.org/packages/e6/6d/67fe16c48d7ce050979b33f47e0d28a318f02da030602e944c34f7a16ef3/fonttools-4.63.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ee08ebfa58f6e1aeff5697ab9582105bb620008c1caafb681e4c557e7483027b", size = 4982666, upload-time = "2026-05-14T12:03:22.87Z" }, + { url = "https://files.pythonhosted.org/packages/f2/00/3bbab338c07c71fa56269953845e92c951a61457bbbb0f1022551ea266d9/fonttools-4.63.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:27fdc65af8da6f88b9c6121c47a464cbe359fcfff7ff6fc2d37a1f395d755b78", size = 5133598, upload-time = "2026-05-14T12:03:25.168Z" }, + { url = "https://files.pythonhosted.org/packages/62/f2/aa27c7f98db5b064883dadcc5283947e81e034de42e22a33675878d98b54/fonttools-4.63.0-cp312-cp312-win32.whl", hash = "sha256:af2fd1664d00a397d75f806985ddb36282091c2131a73a6485c23b4a34722263", size = 2292575, upload-time = "2026-05-14T12:03:27.496Z" }, + { url = "https://files.pythonhosted.org/packages/87/36/cccb9bc2a6ab63d1b2980374f0dca72ce95ae267c9b4cfe77455bb70d0d4/fonttools-4.63.0-cp312-cp312-win_amd64.whl", hash = "sha256:59ac449f8cca9b4ffa08d2e7bbadad87ce710d69d1eda5c3c1ce579baa987272", size = 2343211, upload-time = "2026-05-14T12:03:30.057Z" }, + { url = "https://files.pythonhosted.org/packages/2c/47/c99d5268f354002ce80f8d029cd9d7d872969da1de8b93d32de4dc56d6f4/fonttools-4.63.0-py3-none-any.whl", hash = "sha256:445af2eab030a16b9171ea8bdda7ebf7d96bda2df88ee182a464252f6e05e20d", size = 1164562, upload-time = "2026-05-14T12:04:29.092Z" }, ] [[package]] name = "frozenlist" -version = "1.4.1" +version = "1.8.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/cf/3d/2102257e7acad73efc4a0c306ad3953f68c504c16982bbdfee3ad75d8085/frozenlist-1.4.1.tar.gz", hash = "sha256:c037a86e8513059a2613aaba4d817bb90b9d9b6b69aace3ce9c877e8c8ed402b", size = 37820 } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/01/bc/8d33f2d84b9368da83e69e42720cff01c5e199b5a868ba4486189a4d8fa9/frozenlist-1.4.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a0cb6f11204443f27a1628b0e460f37fb30f624be6051d490fa7d7e26d4af3d0", size = 97060 }, - { url = "https://files.pythonhosted.org/packages/af/b2/904500d6a162b98a70e510e743e7ea992241b4f9add2c8063bf666ca21df/frozenlist-1.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b46c8ae3a8f1f41a0d2ef350c0b6e65822d80772fe46b653ab6b6274f61d4a49", size = 55347 }, - { url = "https://files.pythonhosted.org/packages/5b/9c/f12b69997d3891ddc0d7895999a00b0c6a67f66f79498c0e30f27876435d/frozenlist-1.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:fde5bd59ab5357e3853313127f4d3565fc7dad314a74d7b5d43c22c6a5ed2ced", size = 53374 }, - { url = "https://files.pythonhosted.org/packages/ac/6e/e0322317b7c600ba21dec224498c0c5959b2bce3865277a7c0badae340a9/frozenlist-1.4.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:722e1124aec435320ae01ee3ac7bec11a5d47f25d0ed6328f2273d287bc3abb0", size = 273288 }, - { url = "https://files.pythonhosted.org/packages/a7/76/180ee1b021568dad5b35b7678616c24519af130ed3fa1e0f1ed4014e0f93/frozenlist-1.4.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2471c201b70d58a0f0c1f91261542a03d9a5e088ed3dc6c160d614c01649c106", size = 284737 }, - { url = "https://files.pythonhosted.org/packages/05/08/40159d706a6ed983c8aca51922a93fc69f3c27909e82c537dd4054032674/frozenlist-1.4.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c757a9dd70d72b076d6f68efdbb9bc943665ae954dad2801b874c8c69e185068", size = 280267 }, - { url = "https://files.pythonhosted.org/packages/e0/18/9f09f84934c2b2aa37d539a322267939770362d5495f37783440ca9c1b74/frozenlist-1.4.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f146e0911cb2f1da549fc58fc7bcd2b836a44b79ef871980d605ec392ff6b0d2", size = 258778 }, - { url = "https://files.pythonhosted.org/packages/b3/c9/0bc5ee7e1f5cc7358ab67da0b7dfe60fbd05c254cea5c6108e7d1ae28c63/frozenlist-1.4.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4f9c515e7914626b2a2e1e311794b4c35720a0be87af52b79ff8e1429fc25f19", size = 272276 }, - { url = "https://files.pythonhosted.org/packages/12/5d/147556b73a53ad4df6da8bbb50715a66ac75c491fdedac3eca8b0b915345/frozenlist-1.4.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:c302220494f5c1ebeb0912ea782bcd5e2f8308037b3c7553fad0e48ebad6ad82", size = 272424 }, - { url = "https://files.pythonhosted.org/packages/83/61/2087bbf24070b66090c0af922685f1d0596c24bb3f3b5223625bdeaf03ca/frozenlist-1.4.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:442acde1e068288a4ba7acfe05f5f343e19fac87bfc96d89eb886b0363e977ec", size = 260881 }, - { url = "https://files.pythonhosted.org/packages/a8/be/a235bc937dd803258a370fe21b5aa2dd3e7bfe0287a186a4bec30c6cccd6/frozenlist-1.4.1-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:1b280e6507ea8a4fa0c0a7150b4e526a8d113989e28eaaef946cc77ffd7efc0a", size = 282327 }, - { url = "https://files.pythonhosted.org/packages/5d/e7/b2469e71f082948066b9382c7b908c22552cc705b960363c390d2e23f587/frozenlist-1.4.1-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:fe1a06da377e3a1062ae5fe0926e12b84eceb8a50b350ddca72dc85015873f74", size = 281502 }, - { url = "https://files.pythonhosted.org/packages/db/1b/6a5b970e55dffc1a7d0bb54f57b184b2a2a2ad0b7bca16a97ca26d73c5b5/frozenlist-1.4.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:db9e724bebd621d9beca794f2a4ff1d26eed5965b004a97f1f1685a173b869c2", size = 272292 }, - { url = "https://files.pythonhosted.org/packages/1a/05/ebad68130e6b6eb9b287dacad08ea357c33849c74550c015b355b75cc714/frozenlist-1.4.1-cp311-cp311-win32.whl", hash = "sha256:e774d53b1a477a67838a904131c4b0eef6b3d8a651f8b138b04f748fccfefe17", size = 44446 }, - { url = "https://files.pythonhosted.org/packages/b3/21/c5aaffac47fd305d69df46cfbf118768cdf049a92ee6b0b5cb029d449dcf/frozenlist-1.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:fb3c2db03683b5767dedb5769b8a40ebb47d6f7f45b1b3e3b4b51ec8ad9d9825", size = 50459 }, - { url = "https://files.pythonhosted.org/packages/b4/db/4cf37556a735bcdb2582f2c3fa286aefde2322f92d3141e087b8aeb27177/frozenlist-1.4.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:1979bc0aeb89b33b588c51c54ab0161791149f2461ea7c7c946d95d5f93b56ae", size = 93937 }, - { url = "https://files.pythonhosted.org/packages/46/03/69eb64642ca8c05f30aa5931d6c55e50b43d0cd13256fdd01510a1f85221/frozenlist-1.4.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:cc7b01b3754ea68a62bd77ce6020afaffb44a590c2289089289363472d13aedb", size = 53656 }, - { url = "https://files.pythonhosted.org/packages/3f/ab/c543c13824a615955f57e082c8a5ee122d2d5368e80084f2834e6f4feced/frozenlist-1.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c9c92be9fd329ac801cc420e08452b70e7aeab94ea4233a4804f0915c14eba9b", size = 51868 }, - { url = "https://files.pythonhosted.org/packages/a9/b8/438cfd92be2a124da8259b13409224d9b19ef8f5a5b2507174fc7e7ea18f/frozenlist-1.4.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5c3894db91f5a489fc8fa6a9991820f368f0b3cbdb9cd8849547ccfab3392d86", size = 280652 }, - { url = "https://files.pythonhosted.org/packages/54/72/716a955521b97a25d48315c6c3653f981041ce7a17ff79f701298195bca3/frozenlist-1.4.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ba60bb19387e13597fb059f32cd4d59445d7b18b69a745b8f8e5db0346f33480", size = 286739 }, - { url = "https://files.pythonhosted.org/packages/65/d8/934c08103637567084568e4d5b4219c1016c60b4d29353b1a5b3587827d6/frozenlist-1.4.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8aefbba5f69d42246543407ed2461db31006b0f76c4e32dfd6f42215a2c41d09", size = 289447 }, - { url = "https://files.pythonhosted.org/packages/70/bb/d3b98d83ec6ef88f9bd63d77104a305d68a146fd63a683569ea44c3085f6/frozenlist-1.4.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:780d3a35680ced9ce682fbcf4cb9c2bad3136eeff760ab33707b71db84664e3a", size = 265466 }, - { url = "https://files.pythonhosted.org/packages/0b/f2/b8158a0f06faefec33f4dff6345a575c18095a44e52d4f10c678c137d0e0/frozenlist-1.4.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9acbb16f06fe7f52f441bb6f413ebae6c37baa6ef9edd49cdd567216da8600cd", size = 281530 }, - { url = "https://files.pythonhosted.org/packages/ea/a2/20882c251e61be653764038ece62029bfb34bd5b842724fff32a5b7a2894/frozenlist-1.4.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:23b701e65c7b36e4bf15546a89279bd4d8675faabc287d06bbcfac7d3c33e1e6", size = 281295 }, - { url = "https://files.pythonhosted.org/packages/4c/f9/8894c05dc927af2a09663bdf31914d4fb5501653f240a5bbaf1e88cab1d3/frozenlist-1.4.1-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:3e0153a805a98f5ada7e09826255ba99fb4f7524bb81bf6b47fb702666484ae1", size = 268054 }, - { url = "https://files.pythonhosted.org/packages/37/ff/a613e58452b60166507d731812f3be253eb1229808e59980f0405d1eafbf/frozenlist-1.4.1-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:dd9b1baec094d91bf36ec729445f7769d0d0cf6b64d04d86e45baf89e2b9059b", size = 286904 }, - { url = "https://files.pythonhosted.org/packages/cc/6e/0091d785187f4c2020d5245796d04213f2261ad097e0c1cf35c44317d517/frozenlist-1.4.1-cp312-cp312-musllinux_1_1_s390x.whl", hash = "sha256:1a4471094e146b6790f61b98616ab8e44f72661879cc63fa1049d13ef711e71e", size = 290754 }, - { url = "https://files.pythonhosted.org/packages/a5/c2/e42ad54bae8bcffee22d1e12a8ee6c7717f7d5b5019261a8c861854f4776/frozenlist-1.4.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:5667ed53d68d91920defdf4035d1cdaa3c3121dc0b113255124bcfada1cfa1b8", size = 282602 }, - { url = "https://files.pythonhosted.org/packages/b6/61/56bad8cb94f0357c4bc134acc30822e90e203b5cb8ff82179947de90c17f/frozenlist-1.4.1-cp312-cp312-win32.whl", hash = "sha256:beee944ae828747fd7cb216a70f120767fc9f4f00bacae8543c14a6831673f89", size = 44063 }, - { url = "https://files.pythonhosted.org/packages/3e/dc/96647994a013bc72f3d453abab18340b7f5e222b7b7291e3697ca1fcfbd5/frozenlist-1.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:64536573d0a2cb6e625cf309984e2d873979709f2cf22839bf2d61790b448ad5", size = 50452 }, - { url = "https://files.pythonhosted.org/packages/83/10/466fe96dae1bff622021ee687f68e5524d6392b0a2f80d05001cd3a451ba/frozenlist-1.4.1-py3-none-any.whl", hash = "sha256:04ced3e6a46b4cfffe20f9ae482818e34eba9b5fb0ce4056e4cc9b6e212d09b7", size = 11552 }, + { url = "https://files.pythonhosted.org/packages/69/29/948b9aa87e75820a38650af445d2ef2b6b8a6fab1a23b6bb9e4ef0be2d59/frozenlist-1.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1", size = 87782, upload-time = "2025-10-06T05:36:06.649Z" }, + { url = "https://files.pythonhosted.org/packages/64/80/4f6e318ee2a7c0750ed724fa33a4bdf1eacdc5a39a7a24e818a773cd91af/frozenlist-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b", size = 50594, upload-time = "2025-10-06T05:36:07.69Z" }, + { url = "https://files.pythonhosted.org/packages/2b/94/5c8a2b50a496b11dd519f4a24cb5496cf125681dd99e94c604ccdea9419a/frozenlist-1.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4", size = 50448, upload-time = "2025-10-06T05:36:08.78Z" }, + { url = "https://files.pythonhosted.org/packages/6a/bd/d91c5e39f490a49df14320f4e8c80161cfcce09f1e2cde1edd16a551abb3/frozenlist-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383", size = 242411, upload-time = "2025-10-06T05:36:09.801Z" }, + { url = "https://files.pythonhosted.org/packages/8f/83/f61505a05109ef3293dfb1ff594d13d64a2324ac3482be2cedc2be818256/frozenlist-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4", size = 243014, upload-time = "2025-10-06T05:36:11.394Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cb/cb6c7b0f7d4023ddda30cf56b8b17494eb3a79e3fda666bf735f63118b35/frozenlist-1.8.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8", size = 234909, upload-time = "2025-10-06T05:36:12.598Z" }, + { url = "https://files.pythonhosted.org/packages/31/c5/cd7a1f3b8b34af009fb17d4123c5a778b44ae2804e3ad6b86204255f9ec5/frozenlist-1.8.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b", size = 250049, upload-time = "2025-10-06T05:36:14.065Z" }, + { url = "https://files.pythonhosted.org/packages/c0/01/2f95d3b416c584a1e7f0e1d6d31998c4a795f7544069ee2e0962a4b60740/frozenlist-1.8.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52", size = 256485, upload-time = "2025-10-06T05:36:15.39Z" }, + { url = "https://files.pythonhosted.org/packages/ce/03/024bf7720b3abaebcff6d0793d73c154237b85bdf67b7ed55e5e9596dc9a/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29", size = 237619, upload-time = "2025-10-06T05:36:16.558Z" }, + { url = "https://files.pythonhosted.org/packages/69/fa/f8abdfe7d76b731f5d8bd217827cf6764d4f1d9763407e42717b4bed50a0/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3", size = 250320, upload-time = "2025-10-06T05:36:17.821Z" }, + { url = "https://files.pythonhosted.org/packages/f5/3c/b051329f718b463b22613e269ad72138cc256c540f78a6de89452803a47d/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143", size = 246820, upload-time = "2025-10-06T05:36:19.046Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/58282e8f98e444b3f4dd42448ff36fa38bef29e40d40f330b22e7108f565/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608", size = 250518, upload-time = "2025-10-06T05:36:20.763Z" }, + { url = "https://files.pythonhosted.org/packages/8f/96/007e5944694d66123183845a106547a15944fbbb7154788cbf7272789536/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa", size = 239096, upload-time = "2025-10-06T05:36:22.129Z" }, + { url = "https://files.pythonhosted.org/packages/66/bb/852b9d6db2fa40be96f29c0d1205c306288f0684df8fd26ca1951d461a56/frozenlist-1.8.0-cp312-cp312-win32.whl", hash = "sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf", size = 39985, upload-time = "2025-10-06T05:36:23.661Z" }, + { url = "https://files.pythonhosted.org/packages/b8/af/38e51a553dd66eb064cdf193841f16f077585d4d28394c2fa6235cb41765/frozenlist-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746", size = 44591, upload-time = "2025-10-06T05:36:24.958Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1dc65480ab147339fecc70797e9c2f69d9cea9cf38934ce08df070fdb9cb/frozenlist-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd", size = 40102, upload-time = "2025-10-06T05:36:26.333Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, ] [[package]] -name = "future-fstrings" -version = "1.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5d/e2/3874574cce18a2e3608abfe5b4b5b3c9765653c464f5da18df8971cf501d/future_fstrings-1.2.0.tar.gz", hash = "sha256:6cf41cbe97c398ab5a81168ce0dbb8ad95862d3caf23c21e4430627b90844089", size = 5786 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ab/6d/ea1d52e9038558dd37f5d30647eb9f07888c164960a5d4daa5f970c6da25/future_fstrings-1.2.0-py2.py3-none-any.whl", hash = "sha256:90e49598b553d8746c4dc7d9442e0359d038c3039d802c91c0a55505da318c63", size = 6138 }, -] +name = "gcc-arm-none-eabi" +version = "13.2.1" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=gcc-arm-none-eabi&rev=release-gcc-arm-none-eabi#15791161bd7a752ef821ad6d999a364b13d6e9ca" } [[package]] -name = "ghp-import" -version = "2.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "python-dateutil" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034 }, -] +name = "git-lfs" +version = "3.6.1" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=git-lfs&rev=release-git-lfs#035fb711541a6d8609bb57b26c2f31813c743eb3" } [[package]] name = "google-crc32c" -version = "1.6.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/67/72/c3298da1a3773102359c5a78f20dae8925f5ea876e37354415f68594a6fb/google_crc32c-1.6.0.tar.gz", hash = "sha256:6eceb6ad197656a1ff49ebfbbfa870678c75be4344feb35ac1edf694309413dc", size = 14472 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7d/14/ab47972ac79b6e7b03c8be3a7ef44b530a60e69555668dbbf08fc5692a98/google_crc32c-1.6.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:f7a1fc29803712f80879b0806cb83ab24ce62fc8daf0569f2204a0cfd7f68ed4", size = 30267 }, - { url = "https://files.pythonhosted.org/packages/54/7d/738cb0d25ee55629e7d07da686decf03864a366e5e863091a97b7bd2b8aa/google_crc32c-1.6.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:40b05ab32a5067525670880eb5d169529089a26fe35dce8891127aeddc1950e8", size = 30112 }, - { url = "https://files.pythonhosted.org/packages/3e/6d/33ca50cbdeec09c31bb5dac277c90994edee975662a4c890bda7ffac90ef/google_crc32c-1.6.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a9e4b426c3702f3cd23b933436487eb34e01e00327fac20c9aebb68ccf34117d", size = 32861 }, - { url = "https://files.pythonhosted.org/packages/67/1e/4870896fc81ec77b1b5ebae7fdd680d5a4d40e19a4b6d724032f996ca77a/google_crc32c-1.6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:51c4f54dd8c6dfeb58d1df5e4f7f97df8abf17a36626a217f169893d1d7f3e9f", size = 32490 }, - { url = "https://files.pythonhosted.org/packages/00/9c/f5f5af3ddaa7a639d915f8f58b09bbb8d1db90ecd0459b62cd430eb9a4b6/google_crc32c-1.6.0-cp311-cp311-win_amd64.whl", hash = "sha256:bb8b3c75bd157010459b15222c3fd30577042a7060e29d42dabce449c087f2b3", size = 33446 }, - { url = "https://files.pythonhosted.org/packages/cf/41/65a91657d6a8123c6c12f9aac72127b6ac76dda9e2ba1834026a842eb77c/google_crc32c-1.6.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:ed767bf4ba90104c1216b68111613f0d5926fb3780660ea1198fc469af410e9d", size = 30268 }, - { url = "https://files.pythonhosted.org/packages/59/d0/ee743a267c7d5c4bb8bd865f7d4c039505f1c8a4b439df047fdc17be9769/google_crc32c-1.6.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:62f6d4a29fea082ac4a3c9be5e415218255cf11684ac6ef5488eea0c9132689b", size = 30113 }, - { url = "https://files.pythonhosted.org/packages/25/53/e5e449c368dd26ade5fb2bb209e046d4309ed0623be65b13f0ce026cb520/google_crc32c-1.6.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c87d98c7c4a69066fd31701c4e10d178a648c2cac3452e62c6b24dc51f9fcc00", size = 32995 }, - { url = "https://files.pythonhosted.org/packages/52/12/9bf6042d5b0ac8c25afed562fb78e51b0641474097e4139e858b45de40a5/google_crc32c-1.6.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bd5e7d2445d1a958c266bfa5d04c39932dc54093fa391736dbfdb0f1929c1fb3", size = 32614 }, - { url = "https://files.pythonhosted.org/packages/76/29/fc20f5ec36eac1eea0d0b2de4118c774c5f59c513f2a8630d4db6991f3e0/google_crc32c-1.6.0-cp312-cp312-win_amd64.whl", hash = "sha256:7aec8e88a3583515f9e0957fe4f5f6d8d4997e36d0f61624e70469771584c760", size = 33445 }, -] - -[[package]] -name = "gymnasium" -version = "0.29.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cloudpickle" }, - { name = "farama-notifications" }, - { name = "numpy" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0d/f8/5699ddb3e1c4f6d97b8930e573074849b921da8374fccd141f0f3a9bd713/gymnasium-0.29.1.tar.gz", hash = "sha256:1a532752efcb7590478b1cc7aa04f608eb7a2fdad5570cd217b66b6a35274bb1", size = 820485 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a8/4d/3cbfd81ed84db450dbe73a89afcd8bc405273918415649ac6683356afe92/gymnasium-0.29.1-py3-none-any.whl", hash = "sha256:61c3384b5575985bb7f85e43213bcb40f36fcdff388cae6bc229304c71f2843e", size = 953939 }, -] - -[[package]] -name = "humanfriendly" -version = "10.0" +version = "1.8.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyreadline3", marker = "sys_platform == 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/cc/3f/2c29224acb2e2df4d2046e4c73ee2662023c58ff5b113c4c1adac0886c43/humanfriendly-10.0.tar.gz", hash = "sha256:6b0b831ce8f15f7300721aa49829fc4e83921a9a301cc7f606be6686a2288ddc", size = 360702 } +sdist = { url = "https://files.pythonhosted.org/packages/03/41/4b9c02f99e4c5fb477122cd5437403b552873f014616ac1d19ac8221a58d/google_crc32c-1.8.0.tar.gz", hash = "sha256:a428e25fb7691024de47fecfbff7ff957214da51eddded0da0ae0e0f03a2cf79", size = 14192, upload-time = "2025-12-16T00:35:25.142Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f0/0f/310fb31e39e2d734ccaa2c0fb981ee41f7bd5056ce9bc29b2248bd569169/humanfriendly-10.0-py2.py3-none-any.whl", hash = "sha256:1697e1a8a8f550fd43c2865cd84542fc175a61dcb779b6fee18cf6b6ccba1477", size = 86794 }, + { url = "https://files.pythonhosted.org/packages/e9/5f/7307325b1198b59324c0fa9807cafb551afb65e831699f2ce211ad5c8240/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:4b8286b659c1335172e39563ab0a768b8015e88e08329fa5321f774275fc3113", size = 31300, upload-time = "2025-12-16T00:21:56.723Z" }, + { url = "https://files.pythonhosted.org/packages/21/8e/58c0d5d86e2220e6a37befe7e6a94dd2f6006044b1a33edf1ff6d9f7e319/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:2a3dc3318507de089c5384cc74d54318401410f82aa65b2d9cdde9d297aca7cb", size = 30867, upload-time = "2025-12-16T00:38:31.302Z" }, + { url = "https://files.pythonhosted.org/packages/ce/a9/a780cc66f86335a6019f557a8aaca8fbb970728f0efd2430d15ff1beae0e/google_crc32c-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:14f87e04d613dfa218d6135e81b78272c3b904e2a7053b841481b38a7d901411", size = 33364, upload-time = "2025-12-16T00:40:22.96Z" }, + { url = "https://files.pythonhosted.org/packages/21/3f/3457ea803db0198c9aaca2dd373750972ce28a26f00544b6b85088811939/google_crc32c-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb5c869c2923d56cb0c8e6bcdd73c009c36ae39b652dbe46a05eb4ef0ad01454", size = 33740, upload-time = "2025-12-16T00:40:23.96Z" }, + { url = "https://files.pythonhosted.org/packages/df/c0/87c2073e0c72515bb8733d4eef7b21548e8d189f094b5dad20b0ecaf64f6/google_crc32c-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:3cc0c8912038065eafa603b238abf252e204accab2a704c63b9e14837a854962", size = 34437, upload-time = "2025-12-16T00:35:21.395Z" }, ] [[package]] @@ -766,277 +470,171 @@ dependencies = [ { name = "attrs" }, { name = "sortedcontainers" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/45/f2/f77da8271b1abb630cb2090ead2f5aa4acc9639d632e8e68187f52527e4b/hypothesis-6.47.5.tar.gz", hash = "sha256:e0c1e253fc97e7ecdb9e2bbff2cf815d8739e0d1d3d093d67c3af5bb6a7211b0", size = 326641 } +sdist = { url = "https://files.pythonhosted.org/packages/45/f2/f77da8271b1abb630cb2090ead2f5aa4acc9639d632e8e68187f52527e4b/hypothesis-6.47.5.tar.gz", hash = "sha256:e0c1e253fc97e7ecdb9e2bbff2cf815d8739e0d1d3d093d67c3af5bb6a7211b0", size = 326641, upload-time = "2022-06-25T20:58:48.926Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d3/a7/389bbaade2cbbb2534cb2715986041ed01c6d792152c527e71f7f68e93b5/hypothesis-6.47.5-py3-none-any.whl", hash = "sha256:87049b781ee11ec1c7948565b889ab02e428a1e32d427ab4de8fdb3649242d06", size = 387311 }, + { url = "https://files.pythonhosted.org/packages/d3/a7/389bbaade2cbbb2534cb2715986041ed01c6d792152c527e71f7f68e93b5/hypothesis-6.47.5-py3-none-any.whl", hash = "sha256:87049b781ee11ec1c7948565b889ab02e428a1e32d427ab4de8fdb3649242d06", size = 387311, upload-time = "2022-06-25T20:58:45.281Z" }, ] [[package]] name = "idna" -version = "3.8" +version = "3.17" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e8/ac/e349c5e6d4543326c6883ee9491e3921e0d07b55fdf3cce184b40d63e72a/idna-3.8.tar.gz", hash = "sha256:d838c2c0ed6fced7693d5e8ab8e734d5f8fda53a039c0164afb0b82e771e3603", size = 189467 } +sdist = { url = "https://files.pythonhosted.org/packages/b9/28/99c51f664567218d824af024c0251650fb27e4ca066df188dab0769c5b91/idna-3.17.tar.gz", hash = "sha256:5eb0cb53bc467c12eadcf6de83163ad8527cec9416f44b9b61b19caedad2b87f", size = 196048, upload-time = "2026-05-28T14:32:38.55Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/22/7e/d71db821f177828df9dea8c42ac46473366f191be53080e552e628aad991/idna-3.8-py3-none-any.whl", hash = "sha256:050b4e5baadcd44d760cedbd2b8e639f2ff89bbc7a5730fcc662954303377aac", size = 66894 }, + { url = "https://files.pythonhosted.org/packages/de/a7/f76514cc40ad6234098ecdebda08732d75964776c51a42845b7da10649e2/idna-3.17-py3-none-any.whl", hash = "sha256:466e48829084efe2548012b855df21540b96f2e20e51bd124c851536556a592c", size = 65316, upload-time = "2026-05-28T14:32:37.035Z" }, ] [[package]] name = "ifaddr" version = "0.2.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e8/ac/fb4c578f4a3256561548cd825646680edcadb9440f3f68add95ade1eb791/ifaddr-0.2.0.tar.gz", hash = "sha256:cc0cbfcaabf765d44595825fb96a99bb12c79716b73b44330ea38ee2b0c4aed4", size = 10485 } +sdist = { url = "https://files.pythonhosted.org/packages/e8/ac/fb4c578f4a3256561548cd825646680edcadb9440f3f68add95ade1eb791/ifaddr-0.2.0.tar.gz", hash = "sha256:cc0cbfcaabf765d44595825fb96a99bb12c79716b73b44330ea38ee2b0c4aed4", size = 10485, upload-time = "2022-06-15T21:40:27.561Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9c/1f/19ebc343cc71a7ffa78f17018535adc5cbdd87afb31d7c34874680148b32/ifaddr-0.2.0-py3-none-any.whl", hash = "sha256:085e0305cfe6f16ab12d72e2024030f5d52674afad6911bb1eee207177b8a748", size = 12314 }, + { url = "https://files.pythonhosted.org/packages/9c/1f/19ebc343cc71a7ffa78f17018535adc5cbdd87afb31d7c34874680148b32/ifaddr-0.2.0-py3-none-any.whl", hash = "sha256:085e0305cfe6f16ab12d72e2024030f5d52674afad6911bb1eee207177b8a748", size = 12314, upload-time = "2022-06-15T21:40:25.756Z" }, ] [[package]] -name = "importlib-metadata" -version = "8.4.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "zipp" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c0/bd/fa8ce65b0a7d4b6d143ec23b0f5fd3f7ab80121078c465bc02baeaab22dc/importlib_metadata-8.4.0.tar.gz", hash = "sha256:9a547d3bc3608b025f93d403fdd1aae741c24fbb8314df4b155675742ce303c5", size = 54320 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c0/14/362d31bf1076b21e1bcdcb0dc61944822ff263937b804a79231df2774d28/importlib_metadata-8.4.0-py3-none-any.whl", hash = "sha256:66f342cc6ac9818fc6ff340576acd24d65ba0b3efabb2b4ac08b598965a4a2f1", size = 26269 }, -] +name = "imgui" +version = "1.92.7" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=imgui&rev=release-imgui#af4a30c3930c5e19cf8cea128e342686ba283624" } [[package]] name = "iniconfig" -version = "2.0.0" +version = "2.3.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d7/4b/cbd8e699e64a6f16ca3a8220661b5f83792b3017d0f79807cb8708d33913/iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3", size = 4646 } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ef/a6/62565a6e1cf69e10f5727360368e451d4b7f58beeac6173dc9db836a5b46/iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374", size = 5892 }, + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] [[package]] name = "inputs" version = "0.5" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d1/cd/5f434220920f76eb73d19bb7aab8d857445f40aa642718e6e51e850cd663/inputs-0.5.tar.gz", hash = "sha256:a31d5b96a3525f1232f326be9e7ce8ccaf873c6b1fb84d9f3c9bc3d79b23eae4", size = 33393 } +sdist = { url = "https://files.pythonhosted.org/packages/d1/cd/5f434220920f76eb73d19bb7aab8d857445f40aa642718e6e51e850cd663/inputs-0.5.tar.gz", hash = "sha256:a31d5b96a3525f1232f326be9e7ce8ccaf873c6b1fb84d9f3c9bc3d79b23eae4", size = 33393, upload-time = "2018-10-05T22:38:14.206Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d0/94/040a0d9c81f018c39bd887b7b825013b024deb0a6c795f9524797e2cd41b/inputs-0.5-py2.py3-none-any.whl", hash = "sha256:13f894564e52134cf1e3862b1811da034875eb1f2b62e6021e3776e9669a96ec", size = 33630 }, + { url = "https://files.pythonhosted.org/packages/d0/94/040a0d9c81f018c39bd887b7b825013b024deb0a6c795f9524797e2cd41b/inputs-0.5-py2.py3-none-any.whl", hash = "sha256:13f894564e52134cf1e3862b1811da034875eb1f2b62e6021e3776e9669a96ec", size = 33630, upload-time = "2018-10-05T22:38:28.28Z" }, ] [[package]] -name = "isodate" -version = "0.6.1" +name = "jeepney" +version = "0.9.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/db/7a/c0a56c7d56c7fa723988f122fa1f1ccf8c5c4ccc48efad0d214b49e5b1af/isodate-0.6.1.tar.gz", hash = "sha256:48c5881de7e8b0a0d648cb024c8062dc84e7b840ed81e864c7614fd3c127bde9", size = 28443 } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6f/357efd7602486741aa73ffc0617fb310a29b588ed0fd69c2399acbb85b0c/jeepney-0.9.0.tar.gz", hash = "sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732", size = 106758, upload-time = "2025-02-27T18:51:01.684Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/85/7882d311924cbcfc70b1890780763e36ff0b140c7e51c110fc59a532f087/isodate-0.6.1-py2.py3-none-any.whl", hash = "sha256:0751eece944162659049d35f4f549ed815792b38793f07cf73381c1c87cbed96", size = 41722 }, + { url = "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", hash = "sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683", size = 49010, upload-time = "2025-02-27T18:51:00.104Z" }, ] [[package]] name = "jinja2" -version = "3.1.4" +version = "3.1.6" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "markupsafe" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ed/55/39036716d19cab0747a5020fc7e907f362fbf48c984b14e62127f7e68e5d/jinja2-3.1.4.tar.gz", hash = "sha256:4a3aee7acbbe7303aede8e9648d13b8bf88a429282aa6122a993f0ac800cb369", size = 240245 } +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/31/80/3a54838c3fb461f6fec263ebf3a3a41771bd05190238de3486aae8540c36/jinja2-3.1.4-py3-none-any.whl", hash = "sha256:bc5dd2abb727a5319567b7a813e6a2e7318c39f4f487cfe6c89c6f9c7d25197d", size = 133271 }, + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, ] [[package]] name = "json-rpc" version = "1.15.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6d/9e/59f4a5b7855ced7346ebf40a2e9a8942863f644378d956f68bcef2c88b90/json-rpc-1.15.0.tar.gz", hash = "sha256:e6441d56c1dcd54241c937d0a2dcd193bdf0bdc539b5316524713f554b7f85b9", size = 28854 } +sdist = { url = "https://files.pythonhosted.org/packages/6d/9e/59f4a5b7855ced7346ebf40a2e9a8942863f644378d956f68bcef2c88b90/json-rpc-1.15.0.tar.gz", hash = "sha256:e6441d56c1dcd54241c937d0a2dcd193bdf0bdc539b5316524713f554b7f85b9", size = 28854, upload-time = "2023-06-11T09:45:49.078Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/94/9e/820c4b086ad01ba7d77369fb8b11470a01fac9b4977f02e18659cf378b6b/json_rpc-1.15.0-py2.py3-none-any.whl", hash = "sha256:4a4668bbbe7116feb4abbd0f54e64a4adcf4b8f648f19ffa0848ad0f6606a9bf", size = 39450 }, + { url = "https://files.pythonhosted.org/packages/94/9e/820c4b086ad01ba7d77369fb8b11470a01fac9b4977f02e18659cf378b6b/json_rpc-1.15.0-py2.py3-none-any.whl", hash = "sha256:4a4668bbbe7116feb4abbd0f54e64a4adcf4b8f648f19ffa0848ad0f6606a9bf", size = 39450, upload-time = "2023-06-11T09:45:47.136Z" }, ] +[[package]] +name = "json11" +version = "20170411.0" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=json11&rev=release-json11#0443a506c32eadfec2071a7c163c38c6c7b81d66" } + [[package]] name = "kiwisolver" -version = "1.4.6" +version = "1.5.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/52/bd/e54734b47fa63b52e34bad5b60e6842628b9a47c14254c5557f2a4b37b2e/kiwisolver-1.4.6.tar.gz", hash = "sha256:3cda29d601445e6aa11f80d90a9b8c2ae501650c55d7ad29829bd44499c9e7e0", size = 97171 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/9a/d22443947c1bfacff8596fe588ac5c3bf9e88a1b557c9e3fec12f1487133/kiwisolver-1.4.6-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:45a5cb5abad1ad9c265eed7e058fefafeb7964565b93b397ba2f480faec8d674", size = 122442 }, - { url = "https://files.pythonhosted.org/packages/b8/70/888ce89a1a2b4fbeb141729a4ea73c7227e758a7a8e0f5f7b9a10c83e03a/kiwisolver-1.4.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:7e52b2568c47fb4f54d17576954e02b1de156c85152f87283a99db9670fd18c0", size = 65755 }, - { url = "https://files.pythonhosted.org/packages/17/fb/8d7100e23b1130256bb480a19e2a99b9100c268c0ea4ce6ce42073301ef0/kiwisolver-1.4.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:00af95204100bc1d0f26e1ed52ec77d6e3da5c9b845c88d31875c164e4ba6c0c", size = 64311 }, - { url = "https://files.pythonhosted.org/packages/77/34/704e1e382a5b59097ed546d1093758e6c106eb4b5ffd9340704b6cb5414e/kiwisolver-1.4.6-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:50ab1fedf86f3951a9e90a64edd15f598860ed60cd3664259756f097d527b5ae", size = 1334259 }, - { url = "https://files.pythonhosted.org/packages/2f/8d/63f912f0f7245cbcd0ee9956585509dc85cb764adbe8d06e342596f03536/kiwisolver-1.4.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dbc985766bf20141ce64baecc39fb9fedbce094b2b8de1bb62676b79328988e4", size = 1426582 }, - { url = "https://files.pythonhosted.org/packages/37/cb/ae78c5a007d3c71aecd6d008c9923b29e14ef3663ccc2bc05f5dde9f071c/kiwisolver-1.4.6-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f1942a155c737a7c3835a957897f0cc9ebc0085b7a75d934d86aecb1b27b8873", size = 1541078 }, - { url = "https://files.pythonhosted.org/packages/bf/69/f21cdc8537c08e7cc2097361b1d7ad3c47192509dfca7848e42abe6f2dec/kiwisolver-1.4.6-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f464403e391724f8e7dff188d3fb77a85bd1273b3fdba182e6671abcc44434f8", size = 1470055 }, - { url = "https://files.pythonhosted.org/packages/79/25/b4e6929ee94dcb3144cacb2f427dc27aaec42aeb9367421b2efd5f771393/kiwisolver-1.4.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce5efe545eea86f52ec5a1185e5052815ea86778e8268bad71fa46433f7c0bef", size = 1426374 }, - { url = "https://files.pythonhosted.org/packages/40/dd/11ae8c3276e7f975f8c7e6117184cc3afe1ef5a71745456926104b0c468d/kiwisolver-1.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cb30165f71b7b3378668346e220c81d590593a3a1ff76428a53780310df03f35", size = 2222229 }, - { url = "https://files.pythonhosted.org/packages/67/28/46b28157c237e6c08d40843f4d1ccb74ef727c6c420ced5864e0501b5200/kiwisolver-1.4.6-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:f5a987f740e1c9964e614acb87ba1f014b4be760a341effc8dc789913d1840e6", size = 2368628 }, - { url = "https://files.pythonhosted.org/packages/33/77/8d876efef1921bd918a9dca177fe5e9adda372b4b19300101a38aca5558b/kiwisolver-1.4.6-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f2ceaa6d0450623d108956647ef19a1a28c7e07880f1171c932477308d44d80b", size = 2329025 }, - { url = "https://files.pythonhosted.org/packages/fe/55/d9637527165b65fc3281d52415aaa12a8526200362ebd8ababb1962149c5/kiwisolver-1.4.6-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:788cbf99738f18ae8a27b9d4d7314502b4b917005cfdacd1d6a59038332ae24d", size = 2468484 }, - { url = "https://files.pythonhosted.org/packages/b7/7d/2297d08507d54a6a73c6f4377d8b7a795b4715caeca571e8a494f527d120/kiwisolver-1.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2f6668678a6b9488a7f8a6320e1b1c6396d179a976472dbc08d1600d04119511", size = 2284076 }, - { url = "https://files.pythonhosted.org/packages/8f/5b/64bc3c75c269b8820d98120c9d41079bac3129d83eed1892c50c4d760d2d/kiwisolver-1.4.6-cp311-cp311-win32.whl", hash = "sha256:10a09a3e4213c2806bcfd2eb4edb756c557973d2cacf06873b18a247fce897da", size = 46643 }, - { url = "https://files.pythonhosted.org/packages/5f/40/2b03bc57af2e41da8fec1b30d16f733ee28b85888a5368688e99d5c664c2/kiwisolver-1.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:683ffef2c51fdc54112dc610d06b59b88c21e23fb669b905da6d5bec80da1bde", size = 56023 }, - { url = "https://files.pythonhosted.org/packages/23/f1/ea9a7d24ad1f8c4144dd4eefb11d456f2aa90fc59a6f373b8de5f770f35a/kiwisolver-1.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:3b852c7f0ed9a2fd339c228829bca0964233ed45de50aae3e87b72ca37d177f8", size = 48540 }, - { url = "https://files.pythonhosted.org/packages/81/84/8a5b628c6f2e661a48b296f335fdc1503f8ab5f49782db79217439853a34/kiwisolver-1.4.6-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:979df7e9334f6a3694ee9be8d42817e519ef6d155a16499714d082cf41296852", size = 121807 }, - { url = "https://files.pythonhosted.org/packages/7f/2f/92210b842c87a22df953727c2ba2ceb28827de3a47dc157701d4524885fa/kiwisolver-1.4.6-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:50c9c6c42bb6ca231626d1182b9128e89c5ce3c64456f811ff0280deb42d7bfe", size = 65529 }, - { url = "https://files.pythonhosted.org/packages/51/8f/e1a0d4be4f549a2ef7a9dfa478b50ee92e9b9156e0194072c96f8b934757/kiwisolver-1.4.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ace86489e7951bd26329a589198d3875c3d48380f889c69d3eb254b506a80101", size = 63895 }, - { url = "https://files.pythonhosted.org/packages/6d/0a/b82266406429d3a114f861d9dbfe08eee9ba1475ea09a75cefc0ccbb5372/kiwisolver-1.4.6-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f94771988da902b475f78e85cf63c5c94392773b4a6494234d87c1b363b2fbc5", size = 1369291 }, - { url = "https://files.pythonhosted.org/packages/61/b5/2e68f99a97131bd06f7eeca5294541cde33d92af875f945cd4c1296c94a4/kiwisolver-1.4.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a62379eee430b1c477bb0a0bf6858a57c7c0dad9cee8b3144a5cb5d366c66a54", size = 1461449 }, - { url = "https://files.pythonhosted.org/packages/89/9e/47db05cdf2109a2e375c076fce6088c5fb493331225f8e588bd1992f287c/kiwisolver-1.4.6-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e99b97d69499a7414572c906fbc7ca312519f2e17999730129f6c4492786e953", size = 1579164 }, - { url = "https://files.pythonhosted.org/packages/1f/d7/b6d86dd194ef83a259e30e2356c3ed16b40f59053a13dd6295c2ab99816e/kiwisolver-1.4.6-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ab93f58afe3a02922a343189404f24ed885564e6316649790240124b95ef1d6e", size = 1507308 }, - { url = "https://files.pythonhosted.org/packages/5a/5f/f011569a61d48b39bbf606d675de79c85effabc1fbd291a6396538a8cc87/kiwisolver-1.4.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:34105f4460ba50fc18a16a8e77a5122f7affe075628763fda748ad0ec534c3ee", size = 1464190 }, - { url = "https://files.pythonhosted.org/packages/97/44/9adc480290c47e3a3f2bac4e1de2b3f164fef80c50b2e68d25f1503e36de/kiwisolver-1.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0081f85f0222620563409d4804c6567a930a45dafbe9674c7913fde131653992", size = 2247874 }, - { url = "https://files.pythonhosted.org/packages/5c/5a/0585de17a52af89689b9d79575317e54d5541bc8d0aa8449faf8b9fd58a2/kiwisolver-1.4.6-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:df2a4a7cc2e01991e039a792457751b601bdf30143ab5f23f9a1e58f20c875f4", size = 2404199 }, - { url = "https://files.pythonhosted.org/packages/05/9c/fb3c9c407415126e31918db329de230988e779c9205a7099d674e5f64775/kiwisolver-1.4.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1f401784df70ea2870e4e10adade66b5b06cb2c151bc2a8a414a1d10554e9a81", size = 2352457 }, - { url = "https://files.pythonhosted.org/packages/e2/e7/d7768d21801eb26dea144c264b4da10b995af279b017056c242c8f2ed5ac/kiwisolver-1.4.6-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:b19761c8c613b6d04c44f1a4797a144b44136f17ec009ccfb025e17b5698140c", size = 2501358 }, - { url = "https://files.pythonhosted.org/packages/92/47/fe6423e99e5e00fd8c014013bd146c019b299defee0d78a8fc8619c77d88/kiwisolver-1.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ee7289430ded484cc2eff9d8ffcce58ed7fe2c26919321dbc0580322a49e0120", size = 2314119 }, - { url = "https://files.pythonhosted.org/packages/ee/90/d6ede870b381ae0386475c20327b1c8e52d3b3ced0c9a6d4f1bb067bfba2/kiwisolver-1.4.6-cp312-cp312-win32.whl", hash = "sha256:331b9d9f408e874ecf34bd79b79df8e099f0b1b351b8844609c1bfdc8d2d45b2", size = 46366 }, - { url = "https://files.pythonhosted.org/packages/6a/32/755f2db6c96102ebb7f078f617b17be18d5ba9ecf1423fec2194e5812451/kiwisolver-1.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:a9be95d086578b3ada61a4621c0e7ee5f456820bfdccc3329061fdeae1e31179", size = 55882 }, - { url = "https://files.pythonhosted.org/packages/85/86/1c4fb5c0cd90bd1048d7de3febc8f94cd015d8c523d96a7aff4fc0045b00/kiwisolver-1.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:773f2d87825779ab69196dfcf63e9d91043273421c6128c8d4ed82bc6316068f", size = 48533 }, - { url = "https://files.pythonhosted.org/packages/6d/16/de2395bfdc90626e8e7dc86f2349b0802d7e91d9cce4cd992c69ba2a8084/kiwisolver-1.4.6-cp313-cp313-win_arm64.whl", hash = "sha256:140f376c22b5148453acff768cff19c34ebbd593126617018732ea1d9ce65547", size = 48533 }, -] +sdist = { url = "https://files.pythonhosted.org/packages/d0/67/9c61eccb13f0bdca9307614e782fec49ffdde0f7a2314935d489fa93cd9c/kiwisolver-1.5.0.tar.gz", hash = "sha256:d4193f3d9dc3f6f79aaed0e5637f45d98850ebf01f7ca20e69457f3e8946b66a", size = 103482, upload-time = "2026-03-09T13:15:53.382Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/b2/818b74ebea34dabe6d0c51cb1c572e046730e64844da6ed646d5298c40ce/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:4e9750bc21b886308024f8a54ccb9a2cc38ac9fa813bf4348434e3d54f337ff9", size = 123158, upload-time = "2026-03-09T13:13:23.127Z" }, + { url = "https://files.pythonhosted.org/packages/bf/d9/405320f8077e8e1c5c4bd6adc45e1e6edf6d727b6da7f2e2533cf58bff71/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:72ec46b7eba5b395e0a7b63025490d3214c11013f4aacb4f5e8d6c3041829588", size = 66388, upload-time = "2026-03-09T13:13:24.765Z" }, + { url = "https://files.pythonhosted.org/packages/99/9f/795fedf35634f746151ca8839d05681ceb6287fbed6cc1c9bf235f7887c2/kiwisolver-1.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ed3a984b31da7481b103f68776f7128a89ef26ed40f4dc41a2223cda7fb24819", size = 64068, upload-time = "2026-03-09T13:13:25.878Z" }, + { url = "https://files.pythonhosted.org/packages/c4/13/680c54afe3e65767bed7ec1a15571e1a2f1257128733851ade24abcefbcc/kiwisolver-1.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bb5136fb5352d3f422df33f0c879a1b0c204004324150cc3b5e3c4f310c9049f", size = 1477934, upload-time = "2026-03-09T13:13:27.166Z" }, + { url = "https://files.pythonhosted.org/packages/c8/2f/cebfcdb60fd6a9b0f6b47a9337198bcbad6fbe15e68189b7011fd914911f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b2af221f268f5af85e776a73d62b0845fc8baf8ef0abfae79d29c77d0e776aaf", size = 1278537, upload-time = "2026-03-09T13:13:28.707Z" }, + { url = "https://files.pythonhosted.org/packages/f2/0d/9b782923aada3fafb1d6b84e13121954515c669b18af0c26e7d21f579855/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b0f172dc8ffaccb8522d7c5d899de00133f2f1ca7b0a49b7da98e901de87bf2d", size = 1296685, upload-time = "2026-03-09T13:13:30.528Z" }, + { url = "https://files.pythonhosted.org/packages/27/70/83241b6634b04fe44e892688d5208332bde130f38e610c0418f9ede47ded/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6ab8ba9152203feec73758dad83af9a0bbe05001eb4639e547207c40cfb52083", size = 1346024, upload-time = "2026-03-09T13:13:32.818Z" }, + { url = "https://files.pythonhosted.org/packages/e4/db/30ed226fb271ae1a6431fc0fe0edffb2efe23cadb01e798caeb9f2ceae8f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:cdee07c4d7f6d72008d3f73b9bf027f4e11550224c7c50d8df1ae4a37c1402a6", size = 987241, upload-time = "2026-03-09T13:13:34.435Z" }, + { url = "https://files.pythonhosted.org/packages/ec/bd/c314595208e4c9587652d50959ead9e461995389664e490f4dce7ff0f782/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7c60d3c9b06fb23bd9c6139281ccbdc384297579ae037f08ae90c69f6845c0b1", size = 2227742, upload-time = "2026-03-09T13:13:36.4Z" }, + { url = "https://files.pythonhosted.org/packages/c1/43/0499cec932d935229b5543d073c2b87c9c22846aab48881e9d8d6e742a2d/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:e315e5ec90d88e140f57696ff85b484ff68bb311e36f2c414aa4286293e6dee0", size = 2323966, upload-time = "2026-03-09T13:13:38.204Z" }, + { url = "https://files.pythonhosted.org/packages/3d/6f/79b0d760907965acfd9d61826a3d41f8f093c538f55cd2633d3f0db269f6/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:1465387ac63576c3e125e5337a6892b9e99e0627d52317f3ca79e6930d889d15", size = 1977417, upload-time = "2026-03-09T13:13:39.966Z" }, + { url = "https://files.pythonhosted.org/packages/ab/31/01d0537c41cb75a551a438c3c7a80d0c60d60b81f694dac83dd436aec0d0/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:530a3fd64c87cffa844d4b6b9768774763d9caa299e9b75d8eca6a4423b31314", size = 2491238, upload-time = "2026-03-09T13:13:41.698Z" }, + { url = "https://files.pythonhosted.org/packages/e4/34/8aefdd0be9cfd00a44509251ba864f5caf2991e36772e61c408007e7f417/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1d9daea4ea6b9be74fe2f01f7fbade8d6ffab263e781274cffca0dba9be9eec9", size = 2294947, upload-time = "2026-03-09T13:13:43.343Z" }, + { url = "https://files.pythonhosted.org/packages/ad/cf/0348374369ca588f8fe9c338fae49fa4e16eeb10ffb3d012f23a54578a9e/kiwisolver-1.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:f18c2d9782259a6dc132fdc7a63c168cbc74b35284b6d75c673958982a378384", size = 73569, upload-time = "2026-03-09T13:13:45.792Z" }, + { url = "https://files.pythonhosted.org/packages/28/26/192b26196e2316e2bd29deef67e37cdf9870d9af8e085e521afff0fed526/kiwisolver-1.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:f7c7553b13f69c1b29a5bde08ddc6d9d0c8bfb84f9ed01c30db25944aeb852a7", size = 64997, upload-time = "2026-03-09T13:13:46.878Z" }, + { url = "https://files.pythonhosted.org/packages/1c/fa/2910df836372d8761bb6eff7d8bdcb1613b5c2e03f260efe7abe34d388a7/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_10_13_x86_64.whl", hash = "sha256:5ae8e62c147495b01a0f4765c878e9bfdf843412446a247e28df59936e99e797", size = 130262, upload-time = "2026-03-09T13:15:35.629Z" }, + { url = "https://files.pythonhosted.org/packages/0f/41/c5f71f9f00aabcc71fee8b7475e3f64747282580c2fe748961ba29b18385/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:f6764a4ccab3078db14a632420930f6186058750df066b8ea2a7106df91d3203", size = 138036, upload-time = "2026-03-09T13:15:36.894Z" }, + { url = "https://files.pythonhosted.org/packages/fa/06/7399a607f434119c6e1fdc8ec89a8d51ccccadf3341dee4ead6bd14caaf5/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c31c13da98624f957b0fb1b5bae5383b2333c2c3f6793d9825dd5ce79b525cb7", size = 194295, upload-time = "2026-03-09T13:15:38.22Z" }, + { url = "https://files.pythonhosted.org/packages/b5/91/53255615acd2a1eaca307ede3c90eb550bae9c94581f8c00081b6b1c8f44/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:1f1489f769582498610e015a8ef2d36f28f505ab3096d0e16b4858a9ec214f57", size = 75987, upload-time = "2026-03-09T13:15:39.65Z" }, +] + +[[package]] +name = "libjpeg" +version = "3.1.0" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=libjpeg&rev=release-libjpeg#a615ec26d971cc4cca9a1a426e2c996760fe3c7f" } [[package]] -name = "libusb1" -version = "3.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/af/19/53ecbfb96d6832f2272d13b84658c360802fcfff7c0c497ab8f6bf15ac40/libusb1-3.1.0.tar.gz", hash = "sha256:4ee9b0a55f8bd0b3ea7017ae919a6c1f439af742c4a4b04543c5fd7af89b828c", size = 83013 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/85/5c/9169aea7690df382b677d9f725accc3ec864849c5ab49991e3823a942392/libusb1-3.1.0-py3-none-any.whl", hash = "sha256:9d9f16e2c199cab91f48ead585d3f5ec7e8e4be428a25ddfed22abf786fa9b3a", size = 62368 }, - { url = "https://files.pythonhosted.org/packages/2f/84/d851eb09565ff72b0dfbb988f4e1c79d3746c16eda5bb8e81ec6ce3bb16e/libusb1-3.1.0-py3-none-win32.whl", hash = "sha256:bc7874302565721f443a27d8182fcc7152e5b560523f12f1377b130f473e4a0c", size = 127838 }, - { url = "https://files.pythonhosted.org/packages/02/a5/620d383ec17051f42a907f21517eb498ddecd45b2b81e46cc42e6ec4038e/libusb1-3.1.0-py3-none-win_amd64.whl", hash = "sha256:77a06ecfb3d002d7c2ce369e28d0138b292fe8db8a3d102b73fda231a716dd35", size = 140380 }, -] +name = "libusb" +version = "1.0.29" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=libusb&rev=release-libusb#23132cff0d629bf69590e23b6a682950433aaec8" } [[package]] -name = "lru-dict" -version = "1.3.0" +name = "libusb1" +version = "3.4.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/96/e3/42c87871920602a3c8300915bd0292f76eccc66c38f782397acbf8a62088/lru-dict-1.3.0.tar.gz", hash = "sha256:54fd1966d6bd1fcde781596cb86068214edeebff1db13a2cea11079e3fd07b6b", size = 13123 } +sdist = { url = "https://files.pythonhosted.org/packages/89/35/f9d2a990d092d647b47540cd229e1d68432c0f51183484ca189612a4824c/libusb1-3.4.0.tar.gz", hash = "sha256:9cf5638506d54f21bf36550d97ea63189111a23c4d8078f630103a2052135f45", size = 91206, upload-time = "2026-05-16T20:59:19.315Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a8/c9/6fac0cb67160f0efa3cc76a6a7d04d5e21a516eeb991ebba08f4f8f01ec5/lru_dict-1.3.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:20c595764695d20bdc3ab9b582e0cc99814da183544afb83783a36d6741a0dac", size = 17750 }, - { url = "https://files.pythonhosted.org/packages/61/14/f90dee4bc547ae266dbeffd4e11611234bb6af511dea48f3bc8dac1de478/lru_dict-1.3.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:d9b30a8f50c3fa72a494eca6be5810a1b5c89e4f0fda89374f0d1c5ad8d37d51", size = 11055 }, - { url = "https://files.pythonhosted.org/packages/4e/63/a0ae20525f9d52f62ac0def47935f8a2b3b6fcd2c145218b9a27fc1fb910/lru_dict-1.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9710737584650a4251b9a566cbb1a86f83437adb209c9ba43a4e756d12faf0d7", size = 11330 }, - { url = "https://files.pythonhosted.org/packages/e9/c6/8c2b81b61e5206910c81b712500736227289aefe4ccfb36137aa21807003/lru_dict-1.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b84c321ae34f2f40aae80e18b6fa08b31c90095792ab64bb99d2e385143effaa", size = 31793 }, - { url = "https://files.pythonhosted.org/packages/f9/d7/af9733f94df67a2e9e31ef47d4c41aff1836024f135cdbda4743eb628452/lru_dict-1.3.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:eed24272b4121b7c22f234daed99899817d81d671b3ed030c876ac88bc9dc890", size = 33090 }, - { url = "https://files.pythonhosted.org/packages/5b/6e/5b09b069a70028bcf05dbdc57a301fbe8b3bafecf916f2ed5a3065c79a71/lru_dict-1.3.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9bd13af06dab7c6ee92284fd02ed9a5613a07d5c1b41948dc8886e7207f86dfd", size = 29795 }, - { url = "https://files.pythonhosted.org/packages/21/92/4690daefc2602f7c3429ecf54572d37a9e3c372d370344d2185daa4d5ecc/lru_dict-1.3.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a1efc59bfba6aac33684d87b9e02813b0e2445b2f1c444dae2a0b396ad0ed60c", size = 31586 }, - { url = "https://files.pythonhosted.org/packages/3c/67/0a29a91087196b02f278d8765120ee4e7486f1f72a4c505fd1cd3109e627/lru_dict-1.3.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:cfaf75ac574447afcf8ad998789071af11d2bcf6f947643231f692948839bd98", size = 36662 }, - { url = "https://files.pythonhosted.org/packages/36/54/8d56c514cd2333b652bd44c8f1962ab986cbe68e8ad7258c9e0f360cddb6/lru_dict-1.3.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:c95f8751e2abd6f778da0399c8e0239321d560dbc58cb063827123137d213242", size = 35118 }, - { url = "https://files.pythonhosted.org/packages/f5/9a/c7a175d10d503b86974cb07141ca175947145dd1c7370fcda86fbbcaf326/lru_dict-1.3.0-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:abd0c284b26b5c4ee806ca4f33ab5e16b4bf4d5ec9e093e75a6f6287acdde78e", size = 38198 }, - { url = "https://files.pythonhosted.org/packages/fd/59/2e5086c8e8a05a7282a824a2a37e3c45cd5714e7b83d8bc0267cb3bb5b4f/lru_dict-1.3.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:2a47740652b25900ac5ce52667b2eade28d8b5fdca0ccd3323459df710e8210a", size = 36542 }, - { url = "https://files.pythonhosted.org/packages/12/52/80d0a06e5f45fe7c278dd662da6ea5b39f2ff003248f448189932f6b71c2/lru_dict-1.3.0-cp311-cp311-win32.whl", hash = "sha256:a690c23fc353681ed8042d9fe8f48f0fb79a57b9a45daea2f0be1eef8a1a4aa4", size = 12533 }, - { url = "https://files.pythonhosted.org/packages/ce/fe/1f12f33513310860ec6d722709ec4ad8256d9dcc3385f6ae2a244e6e66f5/lru_dict-1.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:efd3f4e0385d18f20f7ea6b08af2574c1bfaa5cb590102ef1bee781bdfba84bc", size = 13651 }, - { url = "https://files.pythonhosted.org/packages/fc/5c/385f080747eb3083af87d8e4c9068f3c4cab89035f6982134889940dafd8/lru_dict-1.3.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:c279068f68af3b46a5d649855e1fb87f5705fe1f744a529d82b2885c0e1fc69d", size = 17174 }, - { url = "https://files.pythonhosted.org/packages/3c/de/5ef2ed75ce55d7059d1b96177ba04fa7ee1f35564f97bdfcd28fccfbe9d2/lru_dict-1.3.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:350e2233cfee9f326a0d7a08e309372d87186565e43a691b120006285a0ac549", size = 10742 }, - { url = "https://files.pythonhosted.org/packages/ca/05/f69a6abb0062d2cf2ce0aaf0284b105b97d1da024ca6d3d0730e6151242e/lru_dict-1.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4eafb188a84483b3231259bf19030859f070321b00326dcb8e8c6cbf7db4b12f", size = 11079 }, - { url = "https://files.pythonhosted.org/packages/ea/59/cf891143abe58a455b8eaa9175f0e80f624a146a2bf9a1ca842ee0ef930a/lru_dict-1.3.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:73593791047e36b37fdc0b67b76aeed439fcea80959c7d46201240f9ec3b2563", size = 32469 }, - { url = "https://files.pythonhosted.org/packages/59/88/d5976e9f70107ce11e45d93c6f0c2d5eaa1fc30bb3c8f57525eda4510dff/lru_dict-1.3.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1958cb70b9542773d6241974646e5410e41ef32e5c9e437d44040d59bd80daf2", size = 33496 }, - { url = "https://files.pythonhosted.org/packages/6c/f8/94d6e910d54fc1fa05c0ee1cd608c39401866a18cf5e5aff238449b33c11/lru_dict-1.3.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bc1cd3ed2cee78a47f11f3b70be053903bda197a873fd146e25c60c8e5a32cd6", size = 29914 }, - { url = "https://files.pythonhosted.org/packages/ca/b9/9db79780c8a3cfd66bba6847773061e5cf8a3746950273b9985d47bbfe53/lru_dict-1.3.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:82eb230d48eaebd6977a92ddaa6d788f14cf4f4bcf5bbffa4ddfd60d051aa9d4", size = 32241 }, - { url = "https://files.pythonhosted.org/packages/9b/b6/08a623019daec22a40c4d6d2c40851dfa3d129a53b2f9469db8eb13666c1/lru_dict-1.3.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:5ad659cbc349d0c9ba8e536b5f40f96a70c360f43323c29f4257f340d891531c", size = 37320 }, - { url = "https://files.pythonhosted.org/packages/70/0b/d3717159c26155ff77679cee1b077d22e1008bf45f19921e193319cd8e46/lru_dict-1.3.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:ba490b8972531d153ac0d4e421f60d793d71a2f4adbe2f7740b3c55dce0a12f1", size = 35054 }, - { url = "https://files.pythonhosted.org/packages/04/74/f2ae00de7c27984a19b88d2b09ac877031c525b01199d7841ec8fa657fd6/lru_dict-1.3.0-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:c0131351b8a7226c69f1eba5814cbc9d1d8daaf0fdec1ae3f30508e3de5262d4", size = 38613 }, - { url = "https://files.pythonhosted.org/packages/5a/0b/e30236aafe31b4247aa9ae61ba8aac6dde75c3ea0e47a8fb7eef53f6d5ce/lru_dict-1.3.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:0e88dba16695f17f41701269fa046197a3fd7b34a8dba744c8749303ddaa18df", size = 37143 }, - { url = "https://files.pythonhosted.org/packages/1c/28/b59bcebb8d76ba8147a784a8be7eab6a4ad3395b9236e73740ff675a5a52/lru_dict-1.3.0-cp312-cp312-win32.whl", hash = "sha256:6ffaf595e625b388babc8e7d79b40f26c7485f61f16efe76764e32dce9ea17fc", size = 12653 }, - { url = "https://files.pythonhosted.org/packages/bd/18/06d9710cb0a0d3634f8501e4bdcc07abe64a32e404d82895a6a36fab97f6/lru_dict-1.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:cf9da32ef2582434842ab6ba6e67290debfae72771255a8e8ab16f3e006de0aa", size = 13811 }, + { url = "https://files.pythonhosted.org/packages/d4/64/d4b59444e4d3b6979aa5eb58840634465a24b41a9ab03dcf8434c9b89551/libusb1-3.4.0-py3-none-any.whl", hash = "sha256:e83d034e44c3efe1c4599c6281d34bca50a38c12cab3b7b6217d583161a01ffd", size = 67373, upload-time = "2026-05-16T20:59:13.142Z" }, + { url = "https://files.pythonhosted.org/packages/7e/55/a838a4278fac4ee49bf670ddc59d621999a1cb2a3188fb13a23609ea4f06/libusb1-3.4.0-py3-none-win32.whl", hash = "sha256:0a1aa1416034690eb9dc9a895eda0fef44d853bca1053eb1de50a5906684846d", size = 129704, upload-time = "2026-05-16T20:59:15.243Z" }, + { url = "https://files.pythonhosted.org/packages/5f/08/02aecf6dad627534a5835244ece14d7f187ef430354d9b8551199934d059/libusb1-3.4.0-py3-none-win_amd64.whl", hash = "sha256:b7dcc1f324a895af6aac708bc5513a17373f97349cc2ab8a277519c788bd18ca", size = 141212, upload-time = "2026-05-16T20:59:17.286Z" }, ] [[package]] -name = "lxml" -version = "5.3.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e7/6b/20c3a4b24751377aaa6307eb230b66701024012c29dd374999cc92983269/lxml-5.3.0.tar.gz", hash = "sha256:4e109ca30d1edec1ac60cdbe341905dc3b8f55b16855e03a54aaf59e51ec8c6f", size = 3679318 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5c/a8/449faa2a3cbe6a99f8d38dcd51a3ee8844c17862841a6f769ea7c2a9cd0f/lxml-5.3.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:74bcb423462233bc5d6066e4e98b0264e7c1bed7541fff2f4e34fe6b21563c8b", size = 8141056 }, - { url = "https://files.pythonhosted.org/packages/ac/8a/ae6325e994e2052de92f894363b038351c50ee38749d30cc6b6d96aaf90f/lxml-5.3.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a3d819eb6f9b8677f57f9664265d0a10dd6551d227afb4af2b9cd7bdc2ccbf18", size = 4425238 }, - { url = "https://files.pythonhosted.org/packages/f8/fb/128dddb7f9086236bce0eeae2bfb316d138b49b159f50bc681d56c1bdd19/lxml-5.3.0-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5b8f5db71b28b8c404956ddf79575ea77aa8b1538e8b2ef9ec877945b3f46442", size = 5095197 }, - { url = "https://files.pythonhosted.org/packages/b4/f9/a181a8ef106e41e3086629c8bdb2d21a942f14c84a0e77452c22d6b22091/lxml-5.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c3406b63232fc7e9b8783ab0b765d7c59e7c59ff96759d8ef9632fca27c7ee4", size = 4809809 }, - { url = "https://files.pythonhosted.org/packages/25/2f/b20565e808f7f6868aacea48ddcdd7e9e9fb4c799287f21f1a6c7c2e8b71/lxml-5.3.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2ecdd78ab768f844c7a1d4a03595038c166b609f6395e25af9b0f3f26ae1230f", size = 5407593 }, - { url = "https://files.pythonhosted.org/packages/23/0e/caac672ec246d3189a16c4d364ed4f7d6bf856c080215382c06764058c08/lxml-5.3.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:168f2dfcfdedf611eb285efac1516c8454c8c99caf271dccda8943576b67552e", size = 4866657 }, - { url = "https://files.pythonhosted.org/packages/67/a4/1f5fbd3f58d4069000522196b0b776a014f3feec1796da03e495cf23532d/lxml-5.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa617107a410245b8660028a7483b68e7914304a6d4882b5ff3d2d3eb5948d8c", size = 4967017 }, - { url = "https://files.pythonhosted.org/packages/ee/73/623ecea6ca3c530dd0a4ed0d00d9702e0e85cd5624e2d5b93b005fe00abd/lxml-5.3.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:69959bd3167b993e6e710b99051265654133a98f20cec1d9b493b931942e9c16", size = 4810730 }, - { url = "https://files.pythonhosted.org/packages/1d/ce/fb84fb8e3c298f3a245ae3ea6221c2426f1bbaa82d10a88787412a498145/lxml-5.3.0-cp311-cp311-manylinux_2_28_ppc64le.whl", hash = "sha256:bd96517ef76c8654446fc3db9242d019a1bb5fe8b751ba414765d59f99210b79", size = 5455154 }, - { url = "https://files.pythonhosted.org/packages/b1/72/4d1ad363748a72c7c0411c28be2b0dc7150d91e823eadad3b91a4514cbea/lxml-5.3.0-cp311-cp311-manylinux_2_28_s390x.whl", hash = "sha256:ab6dd83b970dc97c2d10bc71aa925b84788c7c05de30241b9e96f9b6d9ea3080", size = 4969416 }, - { url = "https://files.pythonhosted.org/packages/42/07/b29571a58a3a80681722ea8ed0ba569211d9bb8531ad49b5cacf6d409185/lxml-5.3.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:eec1bb8cdbba2925bedc887bc0609a80e599c75b12d87ae42ac23fd199445654", size = 5013672 }, - { url = "https://files.pythonhosted.org/packages/b9/93/bde740d5a58cf04cbd38e3dd93ad1e36c2f95553bbf7d57807bc6815d926/lxml-5.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6a7095eeec6f89111d03dabfe5883a1fd54da319c94e0fb104ee8f23616b572d", size = 4878644 }, - { url = "https://files.pythonhosted.org/packages/56/b5/645c8c02721d49927c93181de4017164ec0e141413577687c3df8ff0800f/lxml-5.3.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:6f651ebd0b21ec65dfca93aa629610a0dbc13dbc13554f19b0113da2e61a4763", size = 5511531 }, - { url = "https://files.pythonhosted.org/packages/85/3f/6a99a12d9438316f4fc86ef88c5d4c8fb674247b17f3173ecadd8346b671/lxml-5.3.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:f422a209d2455c56849442ae42f25dbaaba1c6c3f501d58761c619c7836642ec", size = 5402065 }, - { url = "https://files.pythonhosted.org/packages/80/8a/df47bff6ad5ac57335bf552babfb2408f9eb680c074ec1ba412a1a6af2c5/lxml-5.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:62f7fdb0d1ed2065451f086519865b4c90aa19aed51081979ecd05a21eb4d1be", size = 5069775 }, - { url = "https://files.pythonhosted.org/packages/08/ae/e7ad0f0fbe4b6368c5ee1e3ef0c3365098d806d42379c46c1ba2802a52f7/lxml-5.3.0-cp311-cp311-win32.whl", hash = "sha256:c6379f35350b655fd817cd0d6cbeef7f265f3ae5fedb1caae2eb442bbeae9ab9", size = 3474226 }, - { url = "https://files.pythonhosted.org/packages/c3/b5/91c2249bfac02ee514ab135e9304b89d55967be7e53e94a879b74eec7a5c/lxml-5.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:9c52100e2c2dbb0649b90467935c4b0de5528833c76a35ea1a2691ec9f1ee7a1", size = 3814971 }, - { url = "https://files.pythonhosted.org/packages/eb/6d/d1f1c5e40c64bf62afd7a3f9b34ce18a586a1cccbf71e783cd0a6d8e8971/lxml-5.3.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:e99f5507401436fdcc85036a2e7dc2e28d962550afe1cbfc07c40e454256a859", size = 8171753 }, - { url = "https://files.pythonhosted.org/packages/bd/83/26b1864921869784355459f374896dcf8b44d4af3b15d7697e9156cb2de9/lxml-5.3.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:384aacddf2e5813a36495233b64cb96b1949da72bef933918ba5c84e06af8f0e", size = 4441955 }, - { url = "https://files.pythonhosted.org/packages/e0/d2/e9bff9fb359226c25cda3538f664f54f2804f4b37b0d7c944639e1a51f69/lxml-5.3.0-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:874a216bf6afaf97c263b56371434e47e2c652d215788396f60477540298218f", size = 5050778 }, - { url = "https://files.pythonhosted.org/packages/88/69/6972bfafa8cd3ddc8562b126dd607011e218e17be313a8b1b9cc5a0ee876/lxml-5.3.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65ab5685d56914b9a2a34d67dd5488b83213d680b0c5d10b47f81da5a16b0b0e", size = 4748628 }, - { url = "https://files.pythonhosted.org/packages/5d/ea/a6523c7c7f6dc755a6eed3d2f6d6646617cad4d3d6d8ce4ed71bfd2362c8/lxml-5.3.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aac0bbd3e8dd2d9c45ceb82249e8bdd3ac99131a32b4d35c8af3cc9db1657179", size = 5322215 }, - { url = "https://files.pythonhosted.org/packages/99/37/396fbd24a70f62b31d988e4500f2068c7f3fd399d2fd45257d13eab51a6f/lxml-5.3.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b369d3db3c22ed14c75ccd5af429086f166a19627e84a8fdade3f8f31426e52a", size = 4813963 }, - { url = "https://files.pythonhosted.org/packages/09/91/e6136f17459a11ce1757df864b213efbeab7adcb2efa63efb1b846ab6723/lxml-5.3.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c24037349665434f375645fa9d1f5304800cec574d0310f618490c871fd902b3", size = 4923353 }, - { url = "https://files.pythonhosted.org/packages/1d/7c/2eeecf87c9a1fca4f84f991067c693e67340f2b7127fc3eca8fa29d75ee3/lxml-5.3.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:62d172f358f33a26d6b41b28c170c63886742f5b6772a42b59b4f0fa10526cb1", size = 4740541 }, - { url = "https://files.pythonhosted.org/packages/3b/ed/4c38ba58defca84f5f0d0ac2480fdcd99fc7ae4b28fc417c93640a6949ae/lxml-5.3.0-cp312-cp312-manylinux_2_28_ppc64le.whl", hash = "sha256:c1f794c02903c2824fccce5b20c339a1a14b114e83b306ff11b597c5f71a1c8d", size = 5346504 }, - { url = "https://files.pythonhosted.org/packages/a5/22/bbd3995437e5745cb4c2b5d89088d70ab19d4feabf8a27a24cecb9745464/lxml-5.3.0-cp312-cp312-manylinux_2_28_s390x.whl", hash = "sha256:5d6a6972b93c426ace71e0be9a6f4b2cfae9b1baed2eed2006076a746692288c", size = 4898077 }, - { url = "https://files.pythonhosted.org/packages/0a/6e/94537acfb5b8f18235d13186d247bca478fea5e87d224644e0fe907df976/lxml-5.3.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:3879cc6ce938ff4eb4900d901ed63555c778731a96365e53fadb36437a131a99", size = 4946543 }, - { url = "https://files.pythonhosted.org/packages/8d/e8/4b15df533fe8e8d53363b23a41df9be907330e1fa28c7ca36893fad338ee/lxml-5.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:74068c601baff6ff021c70f0935b0c7bc528baa8ea210c202e03757c68c5a4ff", size = 4816841 }, - { url = "https://files.pythonhosted.org/packages/1a/e7/03f390ea37d1acda50bc538feb5b2bda6745b25731e4e76ab48fae7106bf/lxml-5.3.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ecd4ad8453ac17bc7ba3868371bffb46f628161ad0eefbd0a855d2c8c32dd81a", size = 5417341 }, - { url = "https://files.pythonhosted.org/packages/ea/99/d1133ab4c250da85a883c3b60249d3d3e7c64f24faff494cf0fd23f91e80/lxml-5.3.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:7e2f58095acc211eb9d8b5771bf04df9ff37d6b87618d1cbf85f92399c98dae8", size = 5327539 }, - { url = "https://files.pythonhosted.org/packages/7d/ed/e6276c8d9668028213df01f598f385b05b55a4e1b4662ee12ef05dab35aa/lxml-5.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e63601ad5cd8f860aa99d109889b5ac34de571c7ee902d6812d5d9ddcc77fa7d", size = 5012542 }, - { url = "https://files.pythonhosted.org/packages/36/88/684d4e800f5aa28df2a991a6a622783fb73cf0e46235cfa690f9776f032e/lxml-5.3.0-cp312-cp312-win32.whl", hash = "sha256:17e8d968d04a37c50ad9c456a286b525d78c4a1c15dd53aa46c1d8e06bf6fa30", size = 3486454 }, - { url = "https://files.pythonhosted.org/packages/fc/82/ace5a5676051e60355bd8fb945df7b1ba4f4fb8447f2010fb816bfd57724/lxml-5.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:c1a69e58a6bb2de65902051d57fde951febad631a20a64572677a1052690482f", size = 3816857 }, - { url = "https://files.pythonhosted.org/packages/94/6a/42141e4d373903bfea6f8e94b2f554d05506dfda522ada5343c651410dc8/lxml-5.3.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8c72e9563347c7395910de6a3100a4840a75a6f60e05af5e58566868d5eb2d6a", size = 8156284 }, - { url = "https://files.pythonhosted.org/packages/91/5e/fa097f0f7d8b3d113fb7312c6308af702f2667f22644441715be961f2c7e/lxml-5.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e92ce66cd919d18d14b3856906a61d3f6b6a8500e0794142338da644260595cd", size = 4432407 }, - { url = "https://files.pythonhosted.org/packages/2d/a1/b901988aa6d4ff937f2e5cfc114e4ec561901ff00660c3e56713642728da/lxml-5.3.0-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1d04f064bebdfef9240478f7a779e8c5dc32b8b7b0b2fc6a62e39b928d428e51", size = 5048331 }, - { url = "https://files.pythonhosted.org/packages/30/0f/b2a54f48e52de578b71bbe2a2f8160672a8a5e103df3a78da53907e8c7ed/lxml-5.3.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5c2fb570d7823c2bbaf8b419ba6e5662137f8166e364a8b2b91051a1fb40ab8b", size = 4744835 }, - { url = "https://files.pythonhosted.org/packages/82/9d/b000c15538b60934589e83826ecbc437a1586488d7c13f8ee5ff1f79a9b8/lxml-5.3.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0c120f43553ec759f8de1fee2f4794452b0946773299d44c36bfe18e83caf002", size = 5316649 }, - { url = "https://files.pythonhosted.org/packages/e3/ee/ffbb9eaff5e541922611d2c56b175c45893d1c0b8b11e5a497708a6a3b3b/lxml-5.3.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:562e7494778a69086f0312ec9689f6b6ac1c6b65670ed7d0267e49f57ffa08c4", size = 4812046 }, - { url = "https://files.pythonhosted.org/packages/15/ff/7ff89d567485c7b943cdac316087f16b2399a8b997007ed352a1248397e5/lxml-5.3.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:423b121f7e6fa514ba0c7918e56955a1d4470ed35faa03e3d9f0e3baa4c7e492", size = 4918597 }, - { url = "https://files.pythonhosted.org/packages/c6/a3/535b6ed8c048412ff51268bdf4bf1cf052a37aa7e31d2e6518038a883b29/lxml-5.3.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:c00f323cc00576df6165cc9d21a4c21285fa6b9989c5c39830c3903dc4303ef3", size = 4738071 }, - { url = "https://files.pythonhosted.org/packages/7a/8f/cbbfa59cb4d4fd677fe183725a76d8c956495d7a3c7f111ab8f5e13d2e83/lxml-5.3.0-cp313-cp313-manylinux_2_28_ppc64le.whl", hash = "sha256:1fdc9fae8dd4c763e8a31e7630afef517eab9f5d5d31a278df087f307bf601f4", size = 5342213 }, - { url = "https://files.pythonhosted.org/packages/5c/fb/db4c10dd9958d4b52e34d1d1f7c1f434422aeaf6ae2bbaaff2264351d944/lxml-5.3.0-cp313-cp313-manylinux_2_28_s390x.whl", hash = "sha256:658f2aa69d31e09699705949b5fc4719cbecbd4a97f9656a232e7d6c7be1a367", size = 4893749 }, - { url = "https://files.pythonhosted.org/packages/f2/38/bb4581c143957c47740de18a3281a0cab7722390a77cc6e610e8ebf2d736/lxml-5.3.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:1473427aff3d66a3fa2199004c3e601e6c4500ab86696edffdbc84954c72d832", size = 4945901 }, - { url = "https://files.pythonhosted.org/packages/fc/d5/18b7de4960c731e98037bd48fa9f8e6e8f2558e6fbca4303d9b14d21ef3b/lxml-5.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a87de7dd873bf9a792bf1e58b1c3887b9264036629a5bf2d2e6579fe8e73edff", size = 4815447 }, - { url = "https://files.pythonhosted.org/packages/97/a8/cd51ceaad6eb849246559a8ef60ae55065a3df550fc5fcd27014361c1bab/lxml-5.3.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:0d7b36afa46c97875303a94e8f3ad932bf78bace9e18e603f2085b652422edcd", size = 5411186 }, - { url = "https://files.pythonhosted.org/packages/89/c3/1e3dabab519481ed7b1fdcba21dcfb8832f57000733ef0e71cf6d09a5e03/lxml-5.3.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:cf120cce539453ae086eacc0130a324e7026113510efa83ab42ef3fcfccac7fb", size = 5324481 }, - { url = "https://files.pythonhosted.org/packages/b6/17/71e9984cf0570cd202ac0a1c9ed5c1b8889b0fc8dc736f5ef0ffb181c284/lxml-5.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:df5c7333167b9674aa8ae1d4008fa4bc17a313cc490b2cca27838bbdcc6bb15b", size = 5011053 }, - { url = "https://files.pythonhosted.org/packages/69/68/9f7e6d3312a91e30829368c2b3217e750adef12a6f8eb10498249f4e8d72/lxml-5.3.0-cp313-cp313-win32.whl", hash = "sha256:c802e1c2ed9f0c06a65bc4ed0189d000ada8049312cfeab6ca635e39c9608957", size = 3485634 }, - { url = "https://files.pythonhosted.org/packages/7d/db/214290d58ad68c587bd5d6af3d34e56830438733d0d0856c0275fde43652/lxml-5.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:406246b96d552e0503e17a1006fd27edac678b3fcc9f1be71a2f94b4ff61528d", size = 3814417 }, -] +name = "libyuv" +version = "1922.0" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=libyuv&rev=release-libyuv#70295e7a22d89f9c5bdb61dd93c30f0cbb55d815" } [[package]] name = "markdown" -version = "3.7" +version = "3.10.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/54/28/3af612670f82f4c056911fbbbb42760255801b3068c48de792d354ff4472/markdown-3.7.tar.gz", hash = "sha256:2ae2471477cfd02dbbf038d5d9bc226d40def84b4fe2986e49b59b6b472bbed2", size = 357086 } +sdist = { url = "https://files.pythonhosted.org/packages/2b/f4/69fa6ed85ae003c2378ffa8f6d2e3234662abd02c10d216c0ba96081a238/markdown-3.10.2.tar.gz", hash = "sha256:994d51325d25ad8aa7ce4ebaec003febcce822c3f8c911e3b17c52f7f589f950", size = 368805, upload-time = "2026-02-09T14:57:26.942Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3f/08/83871f3c50fc983b88547c196d11cf8c3340e37c32d2e9d6152abe2c61f7/Markdown-3.7-py3-none-any.whl", hash = "sha256:7eb6df5690b81a1d7942992c97fad2938e956e79df20cbc6186e9c3a77b1c803", size = 106349 }, + { url = "https://files.pythonhosted.org/packages/de/1f/77fa3081e4f66ca3576c896ae5d31c3002ac6607f9747d2e3aa49227e464/markdown-3.10.2-py3-none-any.whl", hash = "sha256:e91464b71ae3ee7afd3017d9f358ef0baf158fd9a298db92f1d4761133824c36", size = 108180, upload-time = "2026-02-09T14:57:25.787Z" }, ] [[package]] name = "markupsafe" -version = "2.1.5" +version = "3.0.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/87/5b/aae44c6655f3801e81aa3eef09dbbf012431987ba564d7231722f68df02d/MarkupSafe-2.1.5.tar.gz", hash = "sha256:d283d37a890ba4c1ae73ffadf8046435c76e7bc2247bbb63c00bd1a709c6544b", size = 19384 } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/11/e7/291e55127bb2ae67c64d66cef01432b5933859dfb7d6949daa721b89d0b3/MarkupSafe-2.1.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:629ddd2ca402ae6dbedfceeba9c46d5f7b2a61d9749597d4307f943ef198fc1f", size = 18219 }, - { url = "https://files.pythonhosted.org/packages/6b/cb/aed7a284c00dfa7c0682d14df85ad4955a350a21d2e3b06d8240497359bf/MarkupSafe-2.1.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5b7b716f97b52c5a14bffdf688f971b2d5ef4029127f1ad7a513973cfd818df2", size = 14098 }, - { url = "https://files.pythonhosted.org/packages/1c/cf/35fe557e53709e93feb65575c93927942087e9b97213eabc3fe9d5b25a55/MarkupSafe-2.1.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ec585f69cec0aa07d945b20805be741395e28ac1627333b1c5b0105962ffced", size = 29014 }, - { url = "https://files.pythonhosted.org/packages/97/18/c30da5e7a0e7f4603abfc6780574131221d9148f323752c2755d48abad30/MarkupSafe-2.1.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b91c037585eba9095565a3556f611e3cbfaa42ca1e865f7b8015fe5c7336d5a5", size = 28220 }, - { url = "https://files.pythonhosted.org/packages/0c/40/2e73e7d532d030b1e41180807a80d564eda53babaf04d65e15c1cf897e40/MarkupSafe-2.1.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7502934a33b54030eaf1194c21c692a534196063db72176b0c4028e140f8f32c", size = 27756 }, - { url = "https://files.pythonhosted.org/packages/18/46/5dca760547e8c59c5311b332f70605d24c99d1303dd9a6e1fc3ed0d73561/MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:0e397ac966fdf721b2c528cf028494e86172b4feba51d65f81ffd65c63798f3f", size = 33988 }, - { url = "https://files.pythonhosted.org/packages/6d/c5/27febe918ac36397919cd4a67d5579cbbfa8da027fa1238af6285bb368ea/MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:c061bb86a71b42465156a3ee7bd58c8c2ceacdbeb95d05a99893e08b8467359a", size = 32718 }, - { url = "https://files.pythonhosted.org/packages/f8/81/56e567126a2c2bc2684d6391332e357589a96a76cb9f8e5052d85cb0ead8/MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:3a57fdd7ce31c7ff06cdfbf31dafa96cc533c21e443d57f5b1ecc6cdc668ec7f", size = 33317 }, - { url = "https://files.pythonhosted.org/packages/00/0b/23f4b2470accb53285c613a3ab9ec19dc944eaf53592cb6d9e2af8aa24cc/MarkupSafe-2.1.5-cp311-cp311-win32.whl", hash = "sha256:397081c1a0bfb5124355710fe79478cdbeb39626492b15d399526ae53422b906", size = 16670 }, - { url = "https://files.pythonhosted.org/packages/b7/a2/c78a06a9ec6d04b3445a949615c4c7ed86a0b2eb68e44e7541b9d57067cc/MarkupSafe-2.1.5-cp311-cp311-win_amd64.whl", hash = "sha256:2b7c57a4dfc4f16f7142221afe5ba4e093e09e728ca65c51f5620c9aaeb9a617", size = 17224 }, - { url = "https://files.pythonhosted.org/packages/53/bd/583bf3e4c8d6a321938c13f49d44024dbe5ed63e0a7ba127e454a66da974/MarkupSafe-2.1.5-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:8dec4936e9c3100156f8a2dc89c4b88d5c435175ff03413b443469c7c8c5f4d1", size = 18215 }, - { url = "https://files.pythonhosted.org/packages/48/d6/e7cd795fc710292c3af3a06d80868ce4b02bfbbf370b7cee11d282815a2a/MarkupSafe-2.1.5-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:3c6b973f22eb18a789b1460b4b91bf04ae3f0c4234a0a6aa6b0a92f6f7b951d4", size = 14069 }, - { url = "https://files.pythonhosted.org/packages/51/b5/5d8ec796e2a08fc814a2c7d2584b55f889a55cf17dd1a90f2beb70744e5c/MarkupSafe-2.1.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ac07bad82163452a6884fe8fa0963fb98c2346ba78d779ec06bd7a6262132aee", size = 29452 }, - { url = "https://files.pythonhosted.org/packages/0a/0d/2454f072fae3b5a137c119abf15465d1771319dfe9e4acbb31722a0fff91/MarkupSafe-2.1.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f5dfb42c4604dddc8e4305050aa6deb084540643ed5804d7455b5df8fe16f5e5", size = 28462 }, - { url = "https://files.pythonhosted.org/packages/2d/75/fd6cb2e68780f72d47e6671840ca517bda5ef663d30ada7616b0462ad1e3/MarkupSafe-2.1.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ea3d8a3d18833cf4304cd2fc9cbb1efe188ca9b5efef2bdac7adc20594a0e46b", size = 27869 }, - { url = "https://files.pythonhosted.org/packages/b0/81/147c477391c2750e8fc7705829f7351cf1cd3be64406edcf900dc633feb2/MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:d050b3361367a06d752db6ead6e7edeb0009be66bc3bae0ee9d97fb326badc2a", size = 33906 }, - { url = "https://files.pythonhosted.org/packages/8b/ff/9a52b71839d7a256b563e85d11050e307121000dcebc97df120176b3ad93/MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:bec0a414d016ac1a18862a519e54b2fd0fc8bbfd6890376898a6c0891dd82e9f", size = 32296 }, - { url = "https://files.pythonhosted.org/packages/88/07/2dc76aa51b481eb96a4c3198894f38b480490e834479611a4053fbf08623/MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:58c98fee265677f63a4385256a6d7683ab1832f3ddd1e66fe948d5880c21a169", size = 33038 }, - { url = "https://files.pythonhosted.org/packages/96/0c/620c1fb3661858c0e37eb3cbffd8c6f732a67cd97296f725789679801b31/MarkupSafe-2.1.5-cp312-cp312-win32.whl", hash = "sha256:8590b4ae07a35970728874632fed7bd57b26b0102df2d2b233b6d9d82f6c62ad", size = 16572 }, - { url = "https://files.pythonhosted.org/packages/3f/14/c3554d512d5f9100a95e737502f4a2323a1959f6d0d01e0d0997b35f7b10/MarkupSafe-2.1.5-cp312-cp312-win_amd64.whl", hash = "sha256:823b65d8706e32ad2df51ed89496147a42a2a6e01c13cfb6ffb8b1e92bc910bb", size = 17127 }, + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, ] [[package]] name = "matplotlib" -version = "3.9.2" +version = "3.10.9" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "contourpy" }, @@ -1049,535 +647,266 @@ dependencies = [ { name = "pyparsing" }, { name = "python-dateutil" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/9e/d8/3d7f706c69e024d4287c1110d74f7dabac91d9843b99eadc90de9efc8869/matplotlib-3.9.2.tar.gz", hash = "sha256:96ab43906269ca64a6366934106fa01534454a69e471b7bf3d79083981aaab92", size = 36088381 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/77/c2/f9d7fe80a8fcce9bb128d1381c6fe41a8d286d7e18395e273002e8e0fa34/matplotlib-3.9.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:d8dd059447824eec055e829258ab092b56bb0579fc3164fa09c64f3acd478772", size = 7902925 }, - { url = "https://files.pythonhosted.org/packages/28/ba/8be09886eb56ac04a218a1dc3fa728a5c4cac60b019b4f1687885166da00/matplotlib-3.9.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c797dac8bb9c7a3fd3382b16fe8f215b4cf0f22adccea36f1545a6d7be310b41", size = 7773193 }, - { url = "https://files.pythonhosted.org/packages/e6/9a/5991972a560db3ab621312a7ca5efec339ae2122f25901c0846865c4b72f/matplotlib-3.9.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d719465db13267bcef19ea8954a971db03b9f48b4647e3860e4bc8e6ed86610f", size = 8202378 }, - { url = "https://files.pythonhosted.org/packages/01/75/6c7ce560e95714a10fcbb3367d1304975a1a3e620f72af28921b796403f3/matplotlib-3.9.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8912ef7c2362f7193b5819d17dae8629b34a95c58603d781329712ada83f9447", size = 8314361 }, - { url = "https://files.pythonhosted.org/packages/6e/49/dc7384c6c092958e0b75e754efbd9e52500154939c3d715789cee9fb8a53/matplotlib-3.9.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:7741f26a58a240f43bee74965c4882b6c93df3e7eb3de160126d8c8f53a6ae6e", size = 9091428 }, - { url = "https://files.pythonhosted.org/packages/8b/ce/15b0bb2fb29b3d46211d8ca740b96b5232499fc49200b58b8d571292c9a6/matplotlib-3.9.2-cp311-cp311-win_amd64.whl", hash = "sha256:ae82a14dab96fbfad7965403c643cafe6515e386de723e498cf3eeb1e0b70cc7", size = 7829377 }, - { url = "https://files.pythonhosted.org/packages/82/de/54f7f38ce6de79cb77d513bb3eaa4e0b1031e9fd6022214f47943fa53a88/matplotlib-3.9.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:ac43031375a65c3196bee99f6001e7fa5bdfb00ddf43379d3c0609bdca042df9", size = 7892511 }, - { url = "https://files.pythonhosted.org/packages/35/3e/5713b84a02b24b2a4bd4d6673bfc03017e6654e1d8793ece783b7ed4d484/matplotlib-3.9.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:be0fc24a5e4531ae4d8e858a1a548c1fe33b176bb13eff7f9d0d38ce5112a27d", size = 7769370 }, - { url = "https://files.pythonhosted.org/packages/5b/bd/c404502aa1824456d2862dd6b9b0c1917761a51a32f7f83ff8cf94b6d117/matplotlib-3.9.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bf81de2926c2db243c9b2cbc3917619a0fc85796c6ba4e58f541df814bbf83c7", size = 8193260 }, - { url = "https://files.pythonhosted.org/packages/27/75/de5b9cd67648051cae40039da0c8cbc497a0d99acb1a1f3d087cd66d27b7/matplotlib-3.9.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f6ee45bc4245533111ced13f1f2cace1e7f89d1c793390392a80c139d6cf0e6c", size = 8306310 }, - { url = "https://files.pythonhosted.org/packages/de/e3/2976e4e54d7ee76eaf54b7639fdc10a223d05c2bdded7045233e9871e469/matplotlib-3.9.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:306c8dfc73239f0e72ac50e5a9cf19cc4e8e331dd0c54f5e69ca8758550f1e1e", size = 9086717 }, - { url = "https://files.pythonhosted.org/packages/d2/92/c2b9464a0562feb6ae780bdc152364810862e07ef5e6affa2b7686028db2/matplotlib-3.9.2-cp312-cp312-win_amd64.whl", hash = "sha256:5413401594cfaff0052f9d8b1aafc6d305b4bd7c4331dccd18f561ff7e1d3bd3", size = 7832805 }, - { url = "https://files.pythonhosted.org/packages/5c/7f/8932eac316b32f464b8f9069f151294dcd892c8fbde61fe8bcd7ba7f7f7e/matplotlib-3.9.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:18128cc08f0d3cfff10b76baa2f296fc28c4607368a8402de61bb3f2eb33c7d9", size = 7893012 }, - { url = "https://files.pythonhosted.org/packages/90/89/9db9db3dd0ff3e2c49e452236dfe29e60b5586a88f8928ca1d153d0da8b5/matplotlib-3.9.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4876d7d40219e8ae8bb70f9263bcbe5714415acfdf781086601211335e24f8aa", size = 7769810 }, - { url = "https://files.pythonhosted.org/packages/67/26/d2661cdc2e1410b8929c5f12dfd521e4528abfed1b3c3d5a28ac48258b43/matplotlib-3.9.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6d9f07a80deab4bb0b82858a9e9ad53d1382fd122be8cde11080f4e7dfedb38b", size = 8193779 }, - { url = "https://files.pythonhosted.org/packages/95/70/4839eaa672bf4eacc98ebc8d23633e02b6daf39e294e7433c4ab11a689be/matplotlib-3.9.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f7c0410f181a531ec4e93bbc27692f2c71a15c2da16766f5ba9761e7ae518413", size = 8306260 }, - { url = "https://files.pythonhosted.org/packages/88/62/7b263b2cb2724b45d3a4f9c8c6137696cc3ef037d44383fb01ac2a9555c2/matplotlib-3.9.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:909645cce2dc28b735674ce0931a4ac94e12f5b13f6bb0b5a5e65e7cea2c192b", size = 9086073 }, - { url = "https://files.pythonhosted.org/packages/b0/6d/3572fe243c74112fef120f0bc86f5edd21f49b60e8322fc7f6a01fe945dd/matplotlib-3.9.2-cp313-cp313-win_amd64.whl", hash = "sha256:f32c7410c7f246838a77d6d1eff0c0f87f3cb0e7c4247aebea71a6d5a68cab49", size = 7833041 }, - { url = "https://files.pythonhosted.org/packages/03/8f/9d505be3eb2f40ec731674fb6b47d10cc3147bbd6a9ea7a08c8da55415c6/matplotlib-3.9.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:37e51dd1c2db16ede9cfd7b5cabdfc818b2c6397c83f8b10e0e797501c963a03", size = 7933657 }, - { url = "https://files.pythonhosted.org/packages/5d/68/44b458b9794bcff2a66921f8c9a8110a50a0bb099bd5f7cabb428a1dc765/matplotlib-3.9.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:b82c5045cebcecd8496a4d694d43f9cc84aeeb49fe2133e036b207abe73f4d30", size = 7799276 }, - { url = "https://files.pythonhosted.org/packages/47/79/8486d4ddcaaf676314b5fb58e8fe19d1a6210a443a7c31fa72d4215fcb87/matplotlib-3.9.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f053c40f94bc51bc03832a41b4f153d83f2062d88c72b5e79997072594e97e51", size = 8221027 }, - { url = "https://files.pythonhosted.org/packages/56/62/72a472181578c3d035dcda0d0fa2e259ba2c4cb91132588a348bb705b70d/matplotlib-3.9.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dbe196377a8248972f5cede786d4c5508ed5f5ca4a1e09b44bda889958b33f8c", size = 8329097 }, - { url = "https://files.pythonhosted.org/packages/01/8a/760f7fce66b39f447ad160800619d0bd5d0936d2b4633587116534a4afe0/matplotlib-3.9.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5816b1e1fe8c192cbc013f8f3e3368ac56fbecf02fb41b8f8559303f24c5015e", size = 9093770 }, -] - -[[package]] -name = "mergedeep" -version = "1.3.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661 } +sdist = { url = "https://files.pythonhosted.org/packages/63/1b/4be5be87d43d327a0cf4de1a56e86f7f84c89312452406cf122efe2839e6/matplotlib-3.10.9.tar.gz", hash = "sha256:fd66508e8c6877d98e586654b608a0456db8d7e8a546eb1e2600efd957302358", size = 34811233, upload-time = "2026-04-24T00:14:13.539Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354 }, + { url = "https://files.pythonhosted.org/packages/35/c6/5581e26c72233ebb2a2a6fed2d24fb7c66b4700120b813f51b0555acf0b6/matplotlib-3.10.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f0c3c28d9fbcc1fe7a03be236d73430cf6409c41fb2383a7ac52fe932b072cb1", size = 8319908, upload-time = "2026-04-24T00:12:21.323Z" }, + { url = "https://files.pythonhosted.org/packages/b7/18/4880dd762e40cd360c1bf06e890c5a97b997e91cb324602b1a19950ad5ce/matplotlib-3.10.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:41cb28c2bd769aa3e98322c6ab09854cbcc52ab69d2759d681bba3e327b2b320", size = 8216016, upload-time = "2026-04-24T00:12:23.4Z" }, + { url = "https://files.pythonhosted.org/packages/32/91/d024616abdba99e83120e07a20658976f6a343646710760c4a51df126029/matplotlib-3.10.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ae20801130378b82d647ff5047c07316295b68dc054ca6b3c13519d0ea624285", size = 8789336, upload-time = "2026-04-24T00:12:26.096Z" }, + { url = "https://files.pythonhosted.org/packages/5c/04/030a2f61ef2158f5e4c259487a92ac877732499fb33d871585d89e03c42d/matplotlib-3.10.9-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6c63ebcd8b4b169eb2f5c200552ae6b8be8999a005b6b507ed76fb8d7d674fe2", size = 9604602, upload-time = "2026-04-24T00:12:29.052Z" }, + { url = "https://files.pythonhosted.org/packages/fc/c2/541e4d09d87bb6b5830fc28b4c887a9a8cf4e1c6cee698a8c05552ae2003/matplotlib-3.10.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d75d11c949914165976c621b2324f9ef162af7ebf4b057ddf95dd1dba7e5edcf", size = 9670966, upload-time = "2026-04-24T00:12:32.131Z" }, + { url = "https://files.pythonhosted.org/packages/04/a1/4571fc46e7702de8d0c2dc54ad1b2f8e29328dea3ee90831181f7353d93c/matplotlib-3.10.9-cp312-cp312-win_amd64.whl", hash = "sha256:d091f9d758b34aaaaa6331d13574bf01891d903b3dec59bfff458ef7551de5d6", size = 8217462, upload-time = "2026-04-24T00:12:35.226Z" }, + { url = "https://files.pythonhosted.org/packages/4b/d0/2269edb12aa30c13c8bcc9382892e39943ce1d28aab4ec296e0381798e81/matplotlib-3.10.9-cp312-cp312-win_arm64.whl", hash = "sha256:10cc5ce06d10231c36f40e875f3c7e8050362a4ee8f0ee5d29a6b3277d57bb42", size = 8136688, upload-time = "2026-04-24T00:12:37.442Z" }, ] [[package]] name = "metadrive-simulator" version = "0.4.2.3" -source = { url = "https://github.com/commaai/metadrive/releases/download/MetaDrive-minimal/metadrive_simulator-0.4.2.3-py3-none-any.whl" } +source = { git = "https://github.com/commaai/metadrive.git?rev=minimal#2716f55a9c7b928ce957a497a15c2c19840c08bc" } dependencies = [ - { name = "filelock" }, - { name = "gymnasium" }, - { name = "lxml" }, - { name = "matplotlib" }, { name = "numpy" }, - { name = "opencv-python-headless" }, { name = "panda3d" }, { name = "panda3d-gltf" }, - { name = "pillow" }, - { name = "progressbar" }, - { name = "psutil" }, - { name = "pygments" }, - { name = "requests" }, - { name = "shapely" }, - { name = "tqdm" }, - { name = "yapf" }, -] -wheels = [ - { url = "https://github.com/commaai/metadrive/releases/download/MetaDrive-minimal/metadrive_simulator-0.4.2.3-py3-none-any.whl", hash = "sha256:6242d4e37e6c592d5eb1cadf497637540d3b754b89813a88c50a93c7fc88b02d" }, -] - -[package.metadata] -requires-dist = [ - { name = "cuda-python", marker = "extra == 'cuda'", specifier = "==12.0.0" }, - { name = "filelock" }, - { name = "glfw", marker = "extra == 'cuda'" }, - { name = "gym", marker = "extra == 'gym'", specifier = ">=0.19.0,<=0.26.0" }, - { name = "gymnasium", specifier = ">=0.28" }, - { name = "lxml" }, - { name = "matplotlib" }, - { name = "numpy", specifier = ">=1.21.6" }, - { name = "opencv-python-headless" }, - { name = "panda3d", specifier = "==1.10.14" }, - { name = "panda3d-gltf", specifier = "==0.13" }, - { name = "pillow" }, - { name = "progressbar" }, - { name = "psutil" }, - { name = "pygments" }, - { name = "pyopengl", marker = "extra == 'cuda'", specifier = "==3.1.6" }, - { name = "pyopengl-accelerate", marker = "extra == 'cuda'", specifier = "==3.1.6" }, - { name = "pyrr", marker = "extra == 'cuda'", specifier = "==0.10.3" }, - { name = "requests" }, - { name = "shapely" }, - { name = "tqdm" }, - { name = "yapf" }, - { name = "zmq", marker = "extra == 'ros'" }, -] - -[[package]] -name = "mkdocs" -version = "1.6.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "click" }, - { name = "colorama", marker = "platform_system == 'Windows'" }, - { name = "ghp-import" }, - { name = "jinja2" }, - { name = "markdown" }, - { name = "markupsafe" }, - { name = "mergedeep" }, - { name = "mkdocs-get-deps" }, - { name = "packaging" }, - { name = "pathspec" }, - { name = "pyyaml" }, - { name = "pyyaml-env-tag" }, - { name = "watchdog" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451 }, -] - -[[package]] -name = "mkdocs-get-deps" -version = "0.2.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mergedeep" }, - { name = "platformdirs" }, - { name = "pyyaml" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/98/f5/ed29cd50067784976f25ed0ed6fcd3c2ce9eb90650aa3b2796ddf7b6870b/mkdocs_get_deps-0.2.0.tar.gz", hash = "sha256:162b3d129c7fad9b19abfdcb9c1458a651628e4b1dea628ac68790fb3061c60c", size = 10239 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9f/d4/029f984e8d3f3b6b726bd33cafc473b75e9e44c0f7e80a5b29abc466bdea/mkdocs_get_deps-0.2.0-py3-none-any.whl", hash = "sha256:2bf11d0b133e77a0dd036abeeb06dec8775e46efa526dc70667d8863eefc6134", size = 9521 }, -] - -[[package]] -name = "mouseinfo" -version = "0.1.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyperclip" }, - { name = "python3-xlib", marker = "platform_system == 'Linux'" }, - { name = "rubicon-objc", marker = "platform_system == 'Darwin'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/28/fa/b2ba8229b9381e8f6381c1dcae6f4159a7f72349e414ed19cfbbd1817173/MouseInfo-0.1.3.tar.gz", hash = "sha256:2c62fb8885062b8e520a3cce0a297c657adcc08c60952eb05bc8256ef6f7f6e7", size = 10850 } [[package]] name = "mpmath" version = "1.3.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198 }, -] - -[[package]] -name = "msal" -version = "1.30.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cryptography" }, - { name = "pyjwt", extra = ["crypto"] }, - { name = "requests" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/03/ce/45b9af8f43fbbf34d15162e1e39ce34b675c234c56638277cc05562b6dbf/msal-1.30.0.tar.gz", hash = "sha256:b4bf00850092e465157d814efa24a18f788284c9a479491024d62903085ea2fb", size = 142510 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ab/82/8f19334da43b7ef72d995587991a446f140346d76edb96a2c1a2689588e9/msal-1.30.0-py3-none-any.whl", hash = "sha256:423872177410cb61683566dc3932db7a76f661a5d2f6f52f02a047f101e1c1de", size = 111760 }, -] - -[[package]] -name = "msal-extensions" -version = "1.2.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "msal" }, - { name = "portalocker" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2d/38/ad49272d0a5af95f7a0cb64a79bbd75c9c187f3b789385a143d8d537a5eb/msal_extensions-1.2.0.tar.gz", hash = "sha256:6f41b320bfd2933d631a215c91ca0dd3e67d84bd1a2f50ce917d5874ec646bef", size = 22391 } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/69/314d887a01599669fb330da14e5c6ff5f138609e322812a942a74ef9b765/msal_extensions-1.2.0-py3-none-any.whl", hash = "sha256:cf5ba83a2113fa6dc011a254a72f1c223c88d7dfad74cc30617c4679a417704d", size = 19254 }, + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, ] [[package]] name = "multidict" -version = "6.0.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f9/79/722ca999a3a09a63b35aac12ec27dfa8e5bb3a38b0f857f7a1a209a88836/multidict-6.0.5.tar.gz", hash = "sha256:f7e301075edaf50500f0b341543c41194d8df3ae5caf4702f2095f3ca73dd8da", size = 59867 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5f/da/b10ea65b850b54f44a6479177c6987f456bc2d38f8dc73009b78afcf0ede/multidict-6.0.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:f285e862d2f153a70586579c15c44656f888806ed0e5b56b64489afe4a2dbfba", size = 50815 }, - { url = "https://files.pythonhosted.org/packages/21/db/3403263f158b0bc7b0d4653766d71cb39498973f2042eead27b2e9758782/multidict-6.0.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:53689bb4e102200a4fafa9de9c7c3c212ab40a7ab2c8e474491914d2305f187e", size = 30269 }, - { url = "https://files.pythonhosted.org/packages/02/c1/b15ecceb6ffa5081ed2ed450aea58d65b0e0358001f2b426705f9f41f4c2/multidict-6.0.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:612d1156111ae11d14afaf3a0669ebf6c170dbb735e510a7438ffe2369a847fd", size = 30500 }, - { url = "https://files.pythonhosted.org/packages/3f/e1/7fdd0f39565df3af87d6c2903fb66a7d529fbd0a8a066045d7a5b6ad1145/multidict-6.0.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7be7047bd08accdb7487737631d25735c9a04327911de89ff1b26b81745bd4e3", size = 130751 }, - { url = "https://files.pythonhosted.org/packages/76/bc/9f593f9e38c6c09bbf0344b56ad67dd53c69167937c2edadee9719a5e17d/multidict-6.0.5-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de170c7b4fe6859beb8926e84f7d7d6c693dfe8e27372ce3b76f01c46e489fcf", size = 138185 }, - { url = "https://files.pythonhosted.org/packages/28/32/d7799a208701d537b92705f46c777ded812a6dc139c18d8ed599908f6b1c/multidict-6.0.5-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:04bde7a7b3de05732a4eb39c94574db1ec99abb56162d6c520ad26f83267de29", size = 133585 }, - { url = "https://files.pythonhosted.org/packages/52/ec/be54a3ad110f386d5bd7a9a42a4ff36b3cd723ebe597f41073a73ffa16b8/multidict-6.0.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:85f67aed7bb647f93e7520633d8f51d3cbc6ab96957c71272b286b2f30dc70ed", size = 128684 }, - { url = "https://files.pythonhosted.org/packages/36/e1/a680eabeb71e25d4733276d917658dfa1cd3a99b1223625dbc247d266c98/multidict-6.0.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:425bf820055005bfc8aa9a0b99ccb52cc2f4070153e34b701acc98d201693733", size = 120994 }, - { url = "https://files.pythonhosted.org/packages/ef/08/08f4f44a8a43ea4cee13aa9cdbbf4a639af8db49310a0637ca389c4cf817/multidict-6.0.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:d3eb1ceec286eba8220c26f3b0096cf189aea7057b6e7b7a2e60ed36b373b77f", size = 159689 }, - { url = "https://files.pythonhosted.org/packages/aa/a9/46cdb4cb40bbd4b732169413f56b04a6553460b22bd914f9729c9ba63761/multidict-6.0.5-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:7901c05ead4b3fb75113fb1dd33eb1253c6d3ee37ce93305acd9d38e0b5f21a4", size = 150611 }, - { url = "https://files.pythonhosted.org/packages/e9/32/35668bb3e6ab2f12f4e4f7f4000f72f714882a94f904d4c3633fbd036753/multidict-6.0.5-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:e0e79d91e71b9867c73323a3444724d496c037e578a0e1755ae159ba14f4f3d1", size = 164444 }, - { url = "https://files.pythonhosted.org/packages/fa/10/f1388a91552af732d8ec48dab928abc209e732767e9e8f92d24c3544353c/multidict-6.0.5-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:29bfeb0dff5cb5fdab2023a7a9947b3b4af63e9c47cae2a10ad58394b517fddc", size = 160158 }, - { url = "https://files.pythonhosted.org/packages/14/c3/f602601f1819983e018156e728e57b3f19726cb424b543667faab82f6939/multidict-6.0.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e030047e85cbcedbfc073f71836d62dd5dadfbe7531cae27789ff66bc551bd5e", size = 156072 }, - { url = "https://files.pythonhosted.org/packages/82/a6/0290af8487326108c0d03d14f8a0b8b1001d71e4494df5f96ab0c88c0b88/multidict-6.0.5-cp311-cp311-win32.whl", hash = "sha256:2f4848aa3baa109e6ab81fe2006c77ed4d3cd1e0ac2c1fbddb7b1277c168788c", size = 25731 }, - { url = "https://files.pythonhosted.org/packages/88/aa/ea217cb18325aa05cb3e3111c19715f1e97c50a4a900cbc20e54648de5f5/multidict-6.0.5-cp311-cp311-win_amd64.whl", hash = "sha256:2faa5ae9376faba05f630d7e5e6be05be22913782b927b19d12b8145968a85ea", size = 28176 }, - { url = "https://files.pythonhosted.org/packages/90/9c/7fda9c0defa09538c97b1f195394be82a1f53238536f70b32eb5399dfd4e/multidict-6.0.5-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:51d035609b86722963404f711db441cf7134f1889107fb171a970c9701f92e1e", size = 49575 }, - { url = "https://files.pythonhosted.org/packages/be/21/d6ca80dd1b9b2c5605ff7475699a8ff5dc6ea958cd71fb2ff234afc13d79/multidict-6.0.5-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:cbebcd5bcaf1eaf302617c114aa67569dd3f090dd0ce8ba9e35e9985b41ac35b", size = 29638 }, - { url = "https://files.pythonhosted.org/packages/9c/18/9565f32c19d186168731e859692dfbc0e98f66a1dcf9e14d69c02a78b75a/multidict-6.0.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2ffc42c922dbfddb4a4c3b438eb056828719f07608af27d163191cb3e3aa6cc5", size = 29874 }, - { url = "https://files.pythonhosted.org/packages/4e/4e/3815190e73e6ef101b5681c174c541bf972a1b064e926e56eea78d06e858/multidict-6.0.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ceb3b7e6a0135e092de86110c5a74e46bda4bd4fbfeeb3a3bcec79c0f861e450", size = 129914 }, - { url = "https://files.pythonhosted.org/packages/0c/08/bb47f886457e2259aefc10044e45c8a1b62f0c27228557e17775869d0341/multidict-6.0.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:79660376075cfd4b2c80f295528aa6beb2058fd289f4c9252f986751a4cd0496", size = 134589 }, - { url = "https://files.pythonhosted.org/packages/d5/2f/952f79b5f0795cf4e34852fc5cf4dfda6166f63c06c798361215b69c131d/multidict-6.0.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e4428b29611e989719874670fd152b6625500ad6c686d464e99f5aaeeaca175a", size = 133259 }, - { url = "https://files.pythonhosted.org/packages/24/1f/af976383b0b772dd351210af5b60ff9927e3abb2f4a103e93da19a957da0/multidict-6.0.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d84a5c3a5f7ce6db1f999fb9438f686bc2e09d38143f2d93d8406ed2dd6b9226", size = 130779 }, - { url = "https://files.pythonhosted.org/packages/fc/b1/b0a7744be00b0f5045c7ed4e4a6b8ee6bde4672b2c620474712299df5979/multidict-6.0.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:76c0de87358b192de7ea9649beb392f107dcad9ad27276324c24c91774ca5271", size = 120125 }, - { url = "https://files.pythonhosted.org/packages/d0/bf/2a1d667acf11231cdf0b97a6cd9f30e7a5cf847037b5cf6da44884284bd0/multidict-6.0.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:79a6d2ba910adb2cbafc95dad936f8b9386e77c84c35bc0add315b856d7c3abb", size = 167095 }, - { url = "https://files.pythonhosted.org/packages/5e/e8/ad6ee74b1a2050d3bc78f566dabcc14c8bf89cbe87eecec866c011479815/multidict-6.0.5-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:92d16a3e275e38293623ebf639c471d3e03bb20b8ebb845237e0d3664914caef", size = 155823 }, - { url = "https://files.pythonhosted.org/packages/45/7c/06926bb91752c52abca3edbfefac1ea90d9d1bc00c84d0658c137589b920/multidict-6.0.5-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:fb616be3538599e797a2017cccca78e354c767165e8858ab5116813146041a24", size = 170233 }, - { url = "https://files.pythonhosted.org/packages/3c/29/3dd36cf6b9c5abba8b97bba84eb499a168ba59c3faec8829327b3887d123/multidict-6.0.5-cp312-cp312-musllinux_1_1_s390x.whl", hash = "sha256:14c2976aa9038c2629efa2c148022ed5eb4cb939e15ec7aace7ca932f48f9ba6", size = 169035 }, - { url = "https://files.pythonhosted.org/packages/60/47/9a0f43470c70bbf6e148311f78ef5a3d4996b0226b6d295bdd50fdcfe387/multidict-6.0.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:435a0984199d81ca178b9ae2c26ec3d49692d20ee29bc4c11a2a8d4514c67eda", size = 166229 }, - { url = "https://files.pythonhosted.org/packages/1d/23/c1b7ae7a0b8a3e08225284ef3ecbcf014b292a3ee821bc4ed2185fd4ce7d/multidict-6.0.5-cp312-cp312-win32.whl", hash = "sha256:9fe7b0653ba3d9d65cbe7698cca585bf0f8c83dbbcc710db9c90f478e175f2d5", size = 25840 }, - { url = "https://files.pythonhosted.org/packages/4a/68/66fceb758ad7a88993940dbdf3ac59911ba9dc46d7798bf6c8652f89f853/multidict-6.0.5-cp312-cp312-win_amd64.whl", hash = "sha256:01265f5e40f5a17f8241d52656ed27192be03bfa8764d88e8220141d1e4b3556", size = 27905 }, - { url = "https://files.pythonhosted.org/packages/fa/a2/17e1e23c6be0a916219c5292f509360c345b5fa6beeb50d743203c27532c/multidict-6.0.5-py3-none-any.whl", hash = "sha256:0d63c74e3d7ab26de115c49bffc92cc77ed23395303d496eae515d4204a625e7", size = 9729 }, -] - -[[package]] -name = "mypy" -version = "1.11.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mypy-extensions" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5c/86/5d7cbc4974fd564550b80fbb8103c05501ea11aa7835edf3351d90095896/mypy-1.11.2.tar.gz", hash = "sha256:7f9993ad3e0ffdc95c2a14b66dee63729f021968bff8ad911867579c65d13a79", size = 3078806 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e2/aa/cc56fb53ebe14c64f1fe91d32d838d6f4db948b9494e200d2f61b820b85d/mypy-1.11.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:75746e06d5fa1e91bfd5432448d00d34593b52e7e91a187d981d08d1f33d4385", size = 10859630 }, - { url = "https://files.pythonhosted.org/packages/04/c8/b19a760fab491c22c51975cf74e3d253b8c8ce2be7afaa2490fbf95a8c59/mypy-1.11.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a976775ab2256aadc6add633d44f100a2517d2388906ec4f13231fafbb0eccca", size = 10037973 }, - { url = "https://files.pythonhosted.org/packages/88/57/7e7e39f2619c8f74a22efb9a4c4eff32b09d3798335625a124436d121d89/mypy-1.11.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cd953f221ac1379050a8a646585a29574488974f79d8082cedef62744f0a0104", size = 12416659 }, - { url = "https://files.pythonhosted.org/packages/fc/a6/37f7544666b63a27e46c48f49caeee388bf3ce95f9c570eb5cfba5234405/mypy-1.11.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:57555a7715c0a34421013144a33d280e73c08df70f3a18a552938587ce9274f4", size = 12897010 }, - { url = "https://files.pythonhosted.org/packages/84/8b/459a513badc4d34acb31c736a0101c22d2bd0697b969796ad93294165cfb/mypy-1.11.2-cp311-cp311-win_amd64.whl", hash = "sha256:36383a4fcbad95f2657642a07ba22ff797de26277158f1cc7bd234821468b1b6", size = 9562873 }, - { url = "https://files.pythonhosted.org/packages/35/3a/ed7b12ecc3f6db2f664ccf85cb2e004d3e90bec928e9d7be6aa2f16b7cdf/mypy-1.11.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:e8960dbbbf36906c5c0b7f4fbf2f0c7ffb20f4898e6a879fcf56a41a08b0d318", size = 10990335 }, - { url = "https://files.pythonhosted.org/packages/04/e4/1a9051e2ef10296d206519f1df13d2cc896aea39e8683302f89bf5792a59/mypy-1.11.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:06d26c277962f3fb50e13044674aa10553981ae514288cb7d0a738f495550b36", size = 10007119 }, - { url = "https://files.pythonhosted.org/packages/f3/3c/350a9da895f8a7e87ade0028b962be0252d152e0c2fbaafa6f0658b4d0d4/mypy-1.11.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6e7184632d89d677973a14d00ae4d03214c8bc301ceefcdaf5c474866814c987", size = 12506856 }, - { url = "https://files.pythonhosted.org/packages/b6/49/ee5adf6a49ff13f4202d949544d3d08abb0ea1f3e7f2a6d5b4c10ba0360a/mypy-1.11.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:3a66169b92452f72117e2da3a576087025449018afc2d8e9bfe5ffab865709ca", size = 12952066 }, - { url = "https://files.pythonhosted.org/packages/27/c0/b19d709a42b24004d720db37446a42abadf844d5c46a2c442e2a074d70d9/mypy-1.11.2-cp312-cp312-win_amd64.whl", hash = "sha256:969ea3ef09617aff826885a22ece0ddef69d95852cdad2f60c8bb06bf1f71f70", size = 9664000 }, - { url = "https://files.pythonhosted.org/packages/42/3a/bdf730640ac523229dd6578e8a581795720a9321399de494374afc437ec5/mypy-1.11.2-py3-none-any.whl", hash = "sha256:b499bc07dbdcd3de92b0a8b29fdf592c111276f6a12fe29c30f6c417dd546d12", size = 2619625 }, -] - -[[package]] -name = "mypy-extensions" -version = "1.0.0" +version = "6.7.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/98/a4/1ab47638b92648243faf97a5aeb6ea83059cc3624972ab6b8d2316078d3f/mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782", size = 4433 } +sdist = { url = "https://files.pythonhosted.org/packages/1a/c2/c2d94cbe6ac1753f3fc980da97b3d930efe1da3af3c9f5125354436c073d/multidict-6.7.1.tar.gz", hash = "sha256:ec6652a1bee61c53a3e5776b6049172c53b6aaba34f18c9ad04f82712bac623d", size = 102010, upload-time = "2026-01-26T02:46:45.979Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/e2/5d3f6ada4297caebe1a2add3b126fe800c96f56dbe5d1988a2cbe0b267aa/mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d", size = 4695 }, + { url = "https://files.pythonhosted.org/packages/8d/9c/f20e0e2cf80e4b2e4b1c365bf5fe104ee633c751a724246262db8f1a0b13/multidict-6.7.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a90f75c956e32891a4eda3639ce6dd86e87105271f43d43442a3aedf3cddf172", size = 76893, upload-time = "2026-01-26T02:43:52.754Z" }, + { url = "https://files.pythonhosted.org/packages/fe/cf/18ef143a81610136d3da8193da9d80bfe1cb548a1e2d1c775f26b23d024a/multidict-6.7.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fccb473e87eaa1382689053e4a4618e7ba7b9b9b8d6adf2027ee474597128cd", size = 45456, upload-time = "2026-01-26T02:43:53.893Z" }, + { url = "https://files.pythonhosted.org/packages/a9/65/1caac9d4cd32e8433908683446eebc953e82d22b03d10d41a5f0fefe991b/multidict-6.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b0fa96985700739c4c7853a43c0b3e169360d6855780021bfc6d0f1ce7c123e7", size = 43872, upload-time = "2026-01-26T02:43:55.041Z" }, + { url = "https://files.pythonhosted.org/packages/cf/3b/d6bd75dc4f3ff7c73766e04e705b00ed6dbbaccf670d9e05a12b006f5a21/multidict-6.7.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cb2a55f408c3043e42b40cc8eecd575afa27b7e0b956dfb190de0f8499a57a53", size = 251018, upload-time = "2026-01-26T02:43:56.198Z" }, + { url = "https://files.pythonhosted.org/packages/fd/80/c959c5933adedb9ac15152e4067c702a808ea183a8b64cf8f31af8ad3155/multidict-6.7.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb0ce7b2a32d09892b3dd6cc44877a0d02a33241fafca5f25c8b6b62374f8b75", size = 258883, upload-time = "2026-01-26T02:43:57.499Z" }, + { url = "https://files.pythonhosted.org/packages/86/85/7ed40adafea3d4f1c8b916e3b5cc3a8e07dfcdcb9cd72800f4ed3ca1b387/multidict-6.7.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c3a32d23520ee37bf327d1e1a656fec76a2edd5c038bf43eddfa0572ec49c60b", size = 242413, upload-time = "2026-01-26T02:43:58.755Z" }, + { url = "https://files.pythonhosted.org/packages/d2/57/b8565ff533e48595503c785f8361ff9a4fde4d67de25c207cd0ba3befd03/multidict-6.7.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9c90fed18bffc0189ba814749fdcc102b536e83a9f738a9003e569acd540a733", size = 268404, upload-time = "2026-01-26T02:44:00.216Z" }, + { url = "https://files.pythonhosted.org/packages/e0/50/9810c5c29350f7258180dfdcb2e52783a0632862eb334c4896ac717cebcb/multidict-6.7.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:da62917e6076f512daccfbbde27f46fed1c98fee202f0559adec8ee0de67f71a", size = 269456, upload-time = "2026-01-26T02:44:02.202Z" }, + { url = "https://files.pythonhosted.org/packages/f3/8d/5e5be3ced1d12966fefb5c4ea3b2a5b480afcea36406559442c6e31d4a48/multidict-6.7.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bfde23ef6ed9db7eaee6c37dcec08524cb43903c60b285b172b6c094711b3961", size = 256322, upload-time = "2026-01-26T02:44:03.56Z" }, + { url = "https://files.pythonhosted.org/packages/31/6e/d8a26d81ac166a5592782d208dd90dfdc0a7a218adaa52b45a672b46c122/multidict-6.7.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3758692429e4e32f1ba0df23219cd0b4fc0a52f476726fff9337d1a57676a582", size = 253955, upload-time = "2026-01-26T02:44:04.845Z" }, + { url = "https://files.pythonhosted.org/packages/59/4c/7c672c8aad41534ba619bcd4ade7a0dc87ed6b8b5c06149b85d3dd03f0cd/multidict-6.7.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:398c1478926eca669f2fd6a5856b6de9c0acf23a2cb59a14c0ba5844fa38077e", size = 251254, upload-time = "2026-01-26T02:44:06.133Z" }, + { url = "https://files.pythonhosted.org/packages/7b/bd/84c24de512cbafbdbc39439f74e967f19570ce7924e3007174a29c348916/multidict-6.7.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c102791b1c4f3ab36ce4101154549105a53dc828f016356b3e3bcae2e3a039d3", size = 252059, upload-time = "2026-01-26T02:44:07.518Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ba/f5449385510825b73d01c2d4087bf6d2fccc20a2d42ac34df93191d3dd03/multidict-6.7.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a088b62bd733e2ad12c50dad01b7d0166c30287c166e137433d3b410add807a6", size = 263588, upload-time = "2026-01-26T02:44:09.382Z" }, + { url = "https://files.pythonhosted.org/packages/d7/11/afc7c677f68f75c84a69fe37184f0f82fce13ce4b92f49f3db280b7e92b3/multidict-6.7.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3d51ff4785d58d3f6c91bdbffcb5e1f7ddfda557727043aa20d20ec4f65e324a", size = 259642, upload-time = "2026-01-26T02:44:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/2b/17/ebb9644da78c4ab36403739e0e6e0e30ebb135b9caf3440825001a0bddcb/multidict-6.7.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc5907494fccf3e7d3f94f95c91d6336b092b5fc83811720fae5e2765890dfba", size = 251377, upload-time = "2026-01-26T02:44:12.042Z" }, + { url = "https://files.pythonhosted.org/packages/ca/a4/840f5b97339e27846c46307f2530a2805d9d537d8b8bd416af031cad7fa0/multidict-6.7.1-cp312-cp312-win32.whl", hash = "sha256:28ca5ce2fd9716631133d0e9a9b9a745ad7f60bac2bccafb56aa380fc0b6c511", size = 41887, upload-time = "2026-01-26T02:44:14.245Z" }, + { url = "https://files.pythonhosted.org/packages/80/31/0b2517913687895f5904325c2069d6a3b78f66cc641a86a2baf75a05dcbb/multidict-6.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:fcee94dfbd638784645b066074b338bc9cc155d4b4bffa4adce1615c5a426c19", size = 46053, upload-time = "2026-01-26T02:44:15.371Z" }, + { url = "https://files.pythonhosted.org/packages/0c/5b/aba28e4ee4006ae4c7df8d327d31025d760ffa992ea23812a601d226e682/multidict-6.7.1-cp312-cp312-win_arm64.whl", hash = "sha256:ba0a9fb644d0c1a2194cf7ffb043bd852cea63a57f66fbd33959f7dae18517bf", size = 43307, upload-time = "2026-01-26T02:44:16.852Z" }, + { url = "https://files.pythonhosted.org/packages/81/08/7036c080d7117f28a4af526d794aab6a84463126db031b007717c1a6676e/multidict-6.7.1-py3-none-any.whl", hash = "sha256:55d97cc6dae627efa6a6e548885712d4864b81110ac76fa4e534c03819fa4a56", size = 12319, upload-time = "2026-01-26T02:46:44.004Z" }, ] [[package]] -name = "natsort" -version = "8.4.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e2/a9/a0c57aee75f77794adaf35322f8b6404cbd0f89ad45c87197a937764b7d0/natsort-8.4.0.tar.gz", hash = "sha256:45312c4a0e5507593da193dedd04abb1469253b601ecaf63445ad80f0a1ea581", size = 76575 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ef/82/7a9d0550484a62c6da82858ee9419f3dd1ccc9aa1c26a1e43da3ecd20b0d/natsort-8.4.0-py3-none-any.whl", hash = "sha256:4732914fb471f56b5cce04d7bae6f164a592c7712e1c85f9ef585e197299521c", size = 38268 }, -] +name = "ncurses" +version = "6.5" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=ncurses&rev=release-ncurses#eae89aae0266b3fbae7b808a3c0c19a97a82a81c" } [[package]] name = "numpy" -version = "1.26.4" +version = "2.4.6" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/65/6e/09db70a523a96d25e115e71cc56a6f9031e7b8cd166c1ac8438307c14058/numpy-1.26.4.tar.gz", hash = "sha256:2a02aba9ed12e4ac4eb3ea9421c420301a0c6460d9830d74a9df87efa4912010", size = 15786129 } +sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/11/57/baae43d14fe163fa0e4c47f307b6b2511ab8d7d30177c491960504252053/numpy-1.26.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4c66707fabe114439db9068ee468c26bbdf909cac0fb58686a42a24de1760c71", size = 20630554 }, - { url = "https://files.pythonhosted.org/packages/1a/2e/151484f49fd03944c4a3ad9c418ed193cfd02724e138ac8a9505d056c582/numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:edd8b5fe47dab091176d21bb6de568acdd906d1887a4584a15a9a96a1dca06ef", size = 13997127 }, - { url = "https://files.pythonhosted.org/packages/79/ae/7e5b85136806f9dadf4878bf73cf223fe5c2636818ba3ab1c585d0403164/numpy-1.26.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ab55401287bfec946ced39700c053796e7cc0e3acbef09993a9ad2adba6ca6e", size = 14222994 }, - { url = "https://files.pythonhosted.org/packages/3a/d0/edc009c27b406c4f9cbc79274d6e46d634d139075492ad055e3d68445925/numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:666dbfb6ec68962c033a450943ded891bed2d54e6755e35e5835d63f4f6931d5", size = 18252005 }, - { url = "https://files.pythonhosted.org/packages/09/bf/2b1aaf8f525f2923ff6cfcf134ae5e750e279ac65ebf386c75a0cf6da06a/numpy-1.26.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:96ff0b2ad353d8f990b63294c8986f1ec3cb19d749234014f4e7eb0112ceba5a", size = 13885297 }, - { url = "https://files.pythonhosted.org/packages/df/a0/4e0f14d847cfc2a633a1c8621d00724f3206cfeddeb66d35698c4e2cf3d2/numpy-1.26.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:60dedbb91afcbfdc9bc0b1f3f402804070deed7392c23eb7a7f07fa857868e8a", size = 18093567 }, - { url = "https://files.pythonhosted.org/packages/d2/b7/a734c733286e10a7f1a8ad1ae8c90f2d33bf604a96548e0a4a3a6739b468/numpy-1.26.4-cp311-cp311-win32.whl", hash = "sha256:1af303d6b2210eb850fcf03064d364652b7120803a0b872f5211f5234b399f20", size = 5968812 }, - { url = "https://files.pythonhosted.org/packages/3f/6b/5610004206cf7f8e7ad91c5a85a8c71b2f2f8051a0c0c4d5916b76d6cbb2/numpy-1.26.4-cp311-cp311-win_amd64.whl", hash = "sha256:cd25bcecc4974d09257ffcd1f098ee778f7834c3ad767fe5db785be9a4aa9cb2", size = 15811913 }, - { url = "https://files.pythonhosted.org/packages/95/12/8f2020a8e8b8383ac0177dc9570aad031a3beb12e38847f7129bacd96228/numpy-1.26.4-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b3ce300f3644fb06443ee2222c2201dd3a89ea6040541412b8fa189341847218", size = 20335901 }, - { url = "https://files.pythonhosted.org/packages/75/5b/ca6c8bd14007e5ca171c7c03102d17b4f4e0ceb53957e8c44343a9546dcc/numpy-1.26.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:03a8c78d01d9781b28a6989f6fa1bb2c4f2d51201cf99d3dd875df6fbd96b23b", size = 13685868 }, - { url = "https://files.pythonhosted.org/packages/79/f8/97f10e6755e2a7d027ca783f63044d5b1bc1ae7acb12afe6a9b4286eac17/numpy-1.26.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9fad7dcb1aac3c7f0584a5a8133e3a43eeb2fe127f47e3632d43d677c66c102b", size = 13925109 }, - { url = "https://files.pythonhosted.org/packages/0f/50/de23fde84e45f5c4fda2488c759b69990fd4512387a8632860f3ac9cd225/numpy-1.26.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:675d61ffbfa78604709862923189bad94014bef562cc35cf61d3a07bba02a7ed", size = 17950613 }, - { url = "https://files.pythonhosted.org/packages/4c/0c/9c603826b6465e82591e05ca230dfc13376da512b25ccd0894709b054ed0/numpy-1.26.4-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:ab47dbe5cc8210f55aa58e4805fe224dac469cde56b9f731a4c098b91917159a", size = 13572172 }, - { url = "https://files.pythonhosted.org/packages/76/8c/2ba3902e1a0fc1c74962ea9bb33a534bb05984ad7ff9515bf8d07527cadd/numpy-1.26.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:1dda2e7b4ec9dd512f84935c5f126c8bd8b9f2fc001e9f54af255e8c5f16b0e0", size = 17786643 }, - { url = "https://files.pythonhosted.org/packages/28/4a/46d9e65106879492374999e76eb85f87b15328e06bd1550668f79f7b18c6/numpy-1.26.4-cp312-cp312-win32.whl", hash = "sha256:50193e430acfc1346175fcbdaa28ffec49947a06918b7b92130744e81e640110", size = 5677803 }, - { url = "https://files.pythonhosted.org/packages/16/2e/86f24451c2d530c88daf997cb8d6ac622c1d40d19f5a031ed68a4b73a374/numpy-1.26.4-cp312-cp312-win_amd64.whl", hash = "sha256:08beddf13648eb95f8d867350f6a018a4be2e5ad54c8d8caed89ebca558b2818", size = 15517754 }, + { url = "https://files.pythonhosted.org/packages/95/2a/3d7b5ac8aac24feaf9ad7ed58f45b0bbc06d37e4338ae84c9f2298b570f9/numpy-2.4.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:001fbb8e08d942dd57599e781f2472269ee7f2755fae407b4f67b2f0b17da3f1", size = 16689119, upload-time = "2026-05-18T23:33:54.065Z" }, + { url = "https://files.pythonhosted.org/packages/ea/12/92c4c131527599e8288d6918e888d88726f84d805d784b771f32408aeaef/numpy-2.4.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ebfb099f8dcf083deef3ac1ca4c1503f387cf76296fcb3816b66f5ecb5f54fdb", size = 14699246, upload-time = "2026-05-18T23:33:57.621Z" }, + { url = "https://files.pythonhosted.org/packages/ad/fe/c0a6b7b2ca128a8fb228575147073b660656734b8ebe4d76c8fd748dcc79/numpy-2.4.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:3213d622a0283a39a93d188f3cf72b26862df52fbb4ca3697f51705016523d41", size = 5204410, upload-time = "2026-05-18T23:34:00.302Z" }, + { url = "https://files.pythonhosted.org/packages/f3/d4/9770d14ba719432bb90a421bfd443872ed0f70f7264b64bec12ea363d5fd/numpy-2.4.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:357cc07a6d7b0b182ff02249616a03742827ebb1277546b5c7cd7f7620a45698", size = 6551240, upload-time = "2026-05-18T23:34:02.852Z" }, + { url = "https://files.pythonhosted.org/packages/c9/c6/50a46a6205feba2343f1d6d17438107c5dc491ed1c736e6ea68689fd906b/numpy-2.4.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f9fb9157b4ce2971008323afe46053787b526ef624fea915b261468a8421a0f", size = 15671012, upload-time = "2026-05-18T23:34:05.485Z" }, + { url = "https://files.pythonhosted.org/packages/99/60/14115e6364fa676c5397c2ad3004e527e9aa487abf5d0706ec81bbd08529/numpy-2.4.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:90f9849678c75fe7afa2d348ac842c168b0a4d3d61919687216dfc547976d853", size = 16645538, upload-time = "2026-05-18T23:34:09.265Z" }, + { url = "https://files.pythonhosted.org/packages/ae/c5/693cbe59e57db94d2231fa519ca3978dc9e19da5a8f088588f5c6e947ff2/numpy-2.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c1a2af6c6ef86344a6b0db6b97834208bf598db514f2b155042439b62605601a", size = 17020706, upload-time = "2026-05-18T23:34:13.053Z" }, + { url = "https://files.pythonhosted.org/packages/ef/fc/85b7c4eff9b4966ade25c2273cf7e7012e92366c032058653934b37de044/numpy-2.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e5805d5a22fd19c8ccff10a9561f9df94436b0545619ea579db2d3c35294bce2", size = 18368541, upload-time = "2026-05-18T23:34:17.024Z" }, + { url = "https://files.pythonhosted.org/packages/f6/81/e1b27545deedce7f4a0b348618c6b62d74e36a4dc9ccd42f3eb2f85eee32/numpy-2.4.6-cp312-cp312-win32.whl", hash = "sha256:e3eeb0aabd6bd5ce64faae67e9935203a6991b4bc2a485a767fbafb2c5125f45", size = 5962825, upload-time = "2026-05-18T23:34:20.3Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ca/feab00bd44aa5fe1ad2c18f08b4d3bb92e26484b0b1d1443897809ed528c/numpy-2.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:d8e8286dd7cea7895157318d1b91cdacac64c479f3cbc8dce548331728484751", size = 12321687, upload-time = "2026-05-18T23:34:23.095Z" }, + { url = "https://files.pythonhosted.org/packages/63/cf/5a6d34850a39d1093558564f77ee8e8e0bee5061151b8f05a55711001ec7/numpy-2.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:4081eb135ac24158bd51cdfbef16f1c64df7063b1143f24731387137c092bec8", size = 10221482, upload-time = "2026-05-18T23:34:25.876Z" }, ] [[package]] -name = "onnx" -version = "1.16.2" +name = "opencv-python-headless" +version = "4.13.0.92" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy" }, - { name = "protobuf" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d8/83/09d7715612f72236b439eba6ebfecdaac59d99562dfc1d7a90dddb6168e1/onnx-1.16.2.tar.gz", hash = "sha256:b33a282b038813c4b69e73ea65c2909768e8dd6cc10619b70632335daf094646", size = 12308861 } wheels = [ - { url = "https://files.pythonhosted.org/packages/ea/d0/b6e02665c3e7ec097f194a75afc16698ce7729b810f0e67ac085a735f6e5/onnx-1.16.2-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:859b41574243c9bfd0abce03c15c78a1f270cc03c7f99629b984daf7adfa5003", size = 16505840 }, - { url = "https://files.pythonhosted.org/packages/82/fc/04b03e31b6741c3b430d04cfa055660242eba800e15c1c3394db3082098d/onnx-1.16.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:39a57d196fe5d73861e70d9625674e6caf8ca13c5e9c740462cf530a07cd2e1c", size = 15793427 }, - { url = "https://files.pythonhosted.org/packages/0b/8b/443486985df06b2e934d1a833f44786f22af06f2ba144ec5ce61f63beb2e/onnx-1.16.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7b98aa9733bd4b781eb931d33b4078ff2837e7d68062460726d6dd011f332bd4", size = 15924140 }, - { url = "https://files.pythonhosted.org/packages/de/20/74f04969a7d0112ce261e549a8b776bf0a262dc109c1e5e70b794ebecedb/onnx-1.16.2-cp311-cp311-win32.whl", hash = "sha256:e9f018b2e172efeea8c2473a51a825652767726374145d7cfdebdc7a27446fdd", size = 14338020 }, - { url = "https://files.pythonhosted.org/packages/41/d3/6f18b81626b9bc7f53f85e766fb688026e803da4ff20160afd80172542e7/onnx-1.16.2-cp311-cp311-win_amd64.whl", hash = "sha256:e66e4512a30df8916db5cf84f47d47b3250b9ab9a98d9cffe142c98c54598ba0", size = 14439804 }, - { url = "https://files.pythonhosted.org/packages/8c/a4/bd05b4a952d07a12c42206ea67fe855e633bb455c6128e388f3d66b46a7e/onnx-1.16.2-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:bfdb8c2eb4c92f55626376e00993db8fcc753da4b80babf28d99636af8dbae6b", size = 16510753 }, - { url = "https://files.pythonhosted.org/packages/8f/3d/6d623912bd7262abba8f7d1b2930896c8ccc3e11eda668b27d28e43c7705/onnx-1.16.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9b77a6c138f284dfc9b06fa370768aa4fd167efc49ff740e2158dd02eedde8d0", size = 15791696 }, - { url = "https://files.pythonhosted.org/packages/bb/2a/68851578adab1fd8abc4418c29f9944ad3d653452db76269c87f42ebe7e3/onnx-1.16.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ca12e47965e590b63f31681c8c563c75449a04178f27eac1ff64bad314314fb3", size = 15923654 }, - { url = "https://files.pythonhosted.org/packages/76/54/f909b428ab922cf9f3b1deec372173a0f4be313ae249b44c2db627a1f3e9/onnx-1.16.2-cp312-cp312-win32.whl", hash = "sha256:324fe3551e91ffd74b43dbcf1d48e96579f4c1be2ff1224591ecd3ec6daa6139", size = 14338109 }, - { url = "https://files.pythonhosted.org/packages/2b/66/121875d593a51ffd7a35315855c0e09ceca43c0bfe0e98af72053cc83682/onnx-1.16.2-cp312-cp312-win_amd64.whl", hash = "sha256:080b19b0bd2b5536b4c61812464fe495758d6c9cfed3fdd3f20516e616212bee", size = 14441282 }, + { url = "https://files.pythonhosted.org/packages/79/42/2310883be3b8826ac58c3f2787b9358a2d46923d61f88fedf930bc59c60c/opencv_python_headless-4.13.0.92-cp37-abi3-macosx_13_0_arm64.whl", hash = "sha256:1a7d040ac656c11b8c38677cc8cccdc149f98535089dbe5b081e80a4e5903209", size = 46247192, upload-time = "2026-02-05T07:01:35.187Z" }, + { url = "https://files.pythonhosted.org/packages/2d/1e/6f9e38005a6f7f22af785df42a43139d0e20f169eb5787ce8be37ee7fcc9/opencv_python_headless-4.13.0.92-cp37-abi3-macosx_14_0_x86_64.whl", hash = "sha256:3e0a6f0a37994ec6ce5f59e936be21d5d6384a4556f2d2da9c2f9c5dc948394c", size = 32568914, upload-time = "2026-02-05T07:01:51.989Z" }, + { url = "https://files.pythonhosted.org/packages/21/76/9417a6aef9def70e467a5bf560579f816148a4c658b7d525581b356eda9e/opencv_python_headless-4.13.0.92-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5c8cfc8e87ed452b5cecb9419473ee5560a989859fe1d10d1ce11ae87b09a2cb", size = 33703709, upload-time = "2026-02-05T10:24:46.469Z" }, + { url = "https://files.pythonhosted.org/packages/92/ce/bd17ff5772938267fd49716e94ca24f616ff4cb1ff4c6be13085108037be/opencv_python_headless-4.13.0.92-cp37-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0525a3d2c0b46c611e2130b5fdebc94cf404845d8fa64d2f3a3b679572a5bd22", size = 56016764, upload-time = "2026-02-05T10:26:48.904Z" }, + { url = "https://files.pythonhosted.org/packages/8f/b4/b7bcbf7c874665825a8c8e1097e93ea25d1f1d210a3e20d4451d01da30aa/opencv_python_headless-4.13.0.92-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:eb60e36b237b1ebd40a912da5384b348df8ed534f6f644d8e0b4f103e272ba7d", size = 35010236, upload-time = "2026-02-05T10:28:11.031Z" }, + { url = "https://files.pythonhosted.org/packages/4b/33/b5db29a6c00eb8f50708110d8d453747ca125c8b805bc437b289dbdcc057/opencv_python_headless-4.13.0.92-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:0bd48544f77c68b2941392fcdf9bcd2b9cdf00e98cb8c29b2455d194763cf99e", size = 60391106, upload-time = "2026-02-05T10:30:14.236Z" }, + { url = "https://files.pythonhosted.org/packages/fb/c3/52cfea47cd33e53e8c0fbd6e7c800b457245c1fda7d61660b4ffe9596a7f/opencv_python_headless-4.13.0.92-cp37-abi3-win32.whl", hash = "sha256:a7cf08e5b191f4ebb530791acc0825a7986e0d0dee2a3c491184bd8599848a4b", size = 30812232, upload-time = "2026-02-05T07:02:29.594Z" }, + { url = "https://files.pythonhosted.org/packages/4a/90/b338326131ccb2aaa3c2c85d00f41822c0050139a4bfe723cfd95455bd2d/opencv_python_headless-4.13.0.92-cp37-abi3-win_amd64.whl", hash = "sha256:77a82fe35ddcec0f62c15f2ba8a12ecc2ed4207c17b0902c7a3151ae29f37fb6", size = 40070414, upload-time = "2026-02-05T07:02:26.448Z" }, ] [[package]] -name = "onnxruntime" -version = "1.19.0" -source = { registry = "https://pypi.org/simple" } +name = "openpilot" +version = "0.1.0" +source = { editable = "." } dependencies = [ - { name = "coloredlogs" }, - { name = "flatbuffers" }, + { name = "acados" }, + { name = "aiohttp" }, + { name = "aiortc" }, + { name = "av" }, + { name = "bootstrap-icons" }, + { name = "bzip2" }, + { name = "capnproto" }, + { name = "catch2" }, + { name = "cffi" }, + { name = "crcmod-plus" }, + { name = "cython" }, + { name = "eigen" }, + { name = "ffmpeg" }, + { name = "gcc-arm-none-eabi" }, + { name = "git-lfs" }, + { name = "inputs" }, + { name = "jeepney" }, + { name = "json-rpc" }, + { name = "json11" }, + { name = "libjpeg" }, + { name = "libusb" }, + { name = "libusb1" }, + { name = "libyuv" }, + { name = "ncurses" }, { name = "numpy" }, - { name = "packaging" }, - { name = "protobuf" }, - { name = "sympy" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/80/16/fc200316725d04731d8ffc5d2105887a1e400d760b0c7fd464744335cd29/onnxruntime-1.19.0-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:a2b53b3c287cd933e5eb597273926e899082d8c84ab96e1b34035764a1627e17", size = 16778356 }, - { url = "https://files.pythonhosted.org/packages/cc/3c/ff2ecf2a842822bc5e9758747bdfd4163c53af470421f07afd6cba1ced7d/onnxruntime-1.19.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e94984663963e74fbb468bde9ec6f19dcf890b594b35e249c4dc8789d08993c5", size = 11492628 }, - { url = "https://files.pythonhosted.org/packages/fa/ca/769da06e76b14a315a1effa5b01d906963379495cd82c00b5023be4c3e61/onnxruntime-1.19.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f379d1f050cfb55ce015d53727b78ee362febc065c38eed81512b22b757da73", size = 13172071 }, - { url = "https://files.pythonhosted.org/packages/75/7c/5a7e3fd98f9af3c43d6073c38afff8c18d201a72d1eba77c93dd230b8501/onnxruntime-1.19.0-cp311-cp311-win32.whl", hash = "sha256:4ccb48faea02503275ae7e79e351434fc43c294c4cb5c4d8bcb7479061396614", size = 9589924 }, - { url = "https://files.pythonhosted.org/packages/78/86/fd21288f9e4096d9c27bd0f221cb61719baa97d5e187549a9f0e84e386ae/onnxruntime-1.19.0-cp311-cp311-win_amd64.whl", hash = "sha256:9cdc8d311289a84e77722de68bd22b8adfb94eea26f4be6f9e017350faac8b18", size = 11083172 }, - { url = "https://files.pythonhosted.org/packages/d1/3c/7cd126254658f0371fadf8651957387d7f743b1b85545e3b783a7f717215/onnxruntime-1.19.0-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:1b59eaec1be9a8613c5fdeaafe67f73a062edce3ac03bbbdc9e2d98b58a30617", size = 16789643 }, - { url = "https://files.pythonhosted.org/packages/bf/6e/aae5420a45cbbcacef4c65f70067c11bed7cbb8fda12e0728f37d29746e5/onnxruntime-1.19.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be4144d014a4b25184e63ce7a463a2e7796e2f3df931fccc6a6aefa6f1365dc5", size = 11483896 }, - { url = "https://files.pythonhosted.org/packages/e6/0f/ad2ec6d490d9cb4ea82dd46382396827cb8ca9a469a56368fc7ef2fb52a4/onnxruntime-1.19.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:10d7e7d4ca7021ce7f29a66dbc6071addf2de5839135339bd855c6d9c2bba371", size = 13177713 }, - { url = "https://files.pythonhosted.org/packages/de/4e/059cae46e48d183ac9b1d0be7ece1c5878711f4a31a206a9dcb34a89e3f5/onnxruntime-1.19.0-cp312-cp312-win32.whl", hash = "sha256:87f2c58b577a1fb31dc5d92b647ecc588fd5f1ea0c3ad4526f5f80a113357c8d", size = 9591661 }, - { url = "https://files.pythonhosted.org/packages/a0/ed/7ac157855cd2135ba894836ce4d027830b78d71832c9e658046e5b1b3d23/onnxruntime-1.19.0-cp312-cp312-win_amd64.whl", hash = "sha256:8a1f50d49676d7b69566536ff039d9e4e95fc482a55673719f46528218ecbb94", size = 11084335 }, -] - -[[package]] -name = "onnxruntime-gpu" -version = "1.19.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "coloredlogs" }, - { name = "flatbuffers" }, - { name = "numpy" }, - { name = "packaging" }, - { name = "protobuf" }, - { name = "sympy" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/14/cf/fbe7d9d1dfb09876f8b1c79ab00fecc7c151be30660edea6dfe768752588/onnxruntime_gpu-1.19.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c8bae9164d9586cbf7c7976915b515584d077470307a255b7ca03cf425ce38bf", size = 223132057 }, - { url = "https://files.pythonhosted.org/packages/ed/6c/32d9d64b2ab2d17871d67f07144990adf996400466fdbcb751a9217a927c/onnxruntime_gpu-1.19.0-cp311-cp311-win_amd64.whl", hash = "sha256:62418bf4bde804afd1cea1e391f1ee4ba5f50e09cd0397c852e150c013e27ae4", size = 223248909 }, - { url = "https://files.pythonhosted.org/packages/6d/b4/7ce4b35f062e76cd0cac0bf26b4f510eb7e49e5f9ffbe2ed6356bbc05fb3/onnxruntime_gpu-1.19.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cbceb55c265266350fa731365ccd224dc29c352470671a24cbc153fe0c4be1f9", size = 223122847 }, - { url = "https://files.pythonhosted.org/packages/f0/3d/cadf1ba55ebeb700f1209d90a32a896d971b54d67208bc6148d697958049/onnxruntime_gpu-1.19.0-cp312-cp312-win_amd64.whl", hash = "sha256:35405747644bf8d9d9c84fb6ee3dd04cc594e9c3f5448735c68565fb3372b1cd", size = 223250583 }, -] - -[[package]] -name = "opencv-python-headless" -version = "4.10.0.84" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2f/7e/d20f68a5f1487adf19d74378d349932a386b1ece3be9be9915e5986db468/opencv-python-headless-4.10.0.84.tar.gz", hash = "sha256:f2017c6101d7c2ef8d7bc3b414c37ff7f54d64413a1847d89970b6b7069b4e1a", size = 95117755 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1c/9b/583c8d9259f6fc19413f83fd18dd8e6cbc8eefb0b4dc6da52dd151fe3272/opencv_python_headless-4.10.0.84-cp37-abi3-macosx_11_0_arm64.whl", hash = "sha256:a4f4bcb07d8f8a7704d9c8564c224c8b064c63f430e95b61ac0bffaa374d330e", size = 54835657 }, - { url = "https://files.pythonhosted.org/packages/c0/7b/b4c67f5dad7a9a61c47f7a39e4050e8a4628bd64b3c3daaeb755d759f928/opencv_python_headless-4.10.0.84-cp37-abi3-macosx_12_0_x86_64.whl", hash = "sha256:5ae454ebac0eb0a0b932e3406370aaf4212e6a3fdb5038cc86c7aea15a6851da", size = 56475470 }, - { url = "https://files.pythonhosted.org/packages/91/61/f838ce2046f3ec3591ea59ea3549085e399525d3b4558c4ed60b55ed88c0/opencv_python_headless-4.10.0.84-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:46071015ff9ab40fccd8a163da0ee14ce9846349f06c6c8c0f2870856ffa45db", size = 29329705 }, - { url = "https://files.pythonhosted.org/packages/d1/09/248f86a404567303cdf120e4a301f389b68e3b18e5c0cc428de327da609c/opencv_python_headless-4.10.0.84-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:377d08a7e48a1405b5e84afcbe4798464ce7ee17081c1c23619c8b398ff18295", size = 49858781 }, - { url = "https://files.pythonhosted.org/packages/30/c0/66f88d58500e990a9a0a5c06f98862edf1d0a3a430781218a8c193948438/opencv_python_headless-4.10.0.84-cp37-abi3-win32.whl", hash = "sha256:9092404b65458ed87ce932f613ffbb1106ed2c843577501e5768912360fc50ec", size = 28675298 }, - { url = "https://files.pythonhosted.org/packages/26/d0/22f68eb23eea053a31655960f133c0be9726c6a881547e6e9e7e2a946c4f/opencv_python_headless-4.10.0.84-cp37-abi3-win_amd64.whl", hash = "sha256:afcf28bd1209dd58810d33defb622b325d3cbe49dcd7a43a902982c33e5fad05", size = 38754031 }, -] - -[[package]] -name = "openpilot" -version = "0.1.0" -source = { editable = "." } -dependencies = [ - { name = "aiohttp" }, - { name = "aiortc" }, - { name = "casadi" }, - { name = "cffi" }, - { name = "crcmod" }, - { name = "cython" }, - { name = "future-fstrings" }, - { name = "json-rpc" }, - { name = "libusb1" }, - { name = "numpy" }, - { name = "onnx" }, - { name = "onnxruntime", marker = "platform_machine == 'aarch64' and platform_system == 'Linux'" }, - { name = "onnxruntime-gpu", marker = "platform_machine == 'x86_64' and platform_system == 'Linux'" }, + { name = "pillow" }, { name = "psutil" }, - { name = "pyaudio" }, { name = "pycapnp" }, { name = "pycryptodome" }, { name = "pyjwt" }, { name = "pyserial" }, { name = "pyzmq" }, + { name = "qrcode" }, + { name = "raylib" }, { name = "requests" }, { name = "scons" }, { name = "sentry-sdk" }, { name = "setproctitle" }, { name = "setuptools" }, - { name = "smbus2" }, { name = "sounddevice" }, - { name = "spidev", marker = "platform_system == 'Linux'" }, + { name = "spidev", marker = "sys_platform == 'linux'" }, { name = "sympy" }, { name = "tqdm" }, { name = "websocket-client" }, + { name = "xattr" }, + { name = "xvfb" }, + { name = "zeromq" }, { name = "zstandard" }, + { name = "zstd" }, ] [package.optional-dependencies] dev = [ - { name = "av" }, - { name = "azure-identity" }, - { name = "azure-storage-blob" }, - { name = "dictdiffer" }, - { name = "flaky" }, - { name = "inputs" }, - { name = "lru-dict" }, { name = "matplotlib" }, - { name = "metadrive-simulator", marker = "platform_machine != 'aarch64'" }, - { name = "parameterized" }, - { name = "pyautogui" }, - { name = "pyopencl", marker = "platform_machine != 'aarch64'" }, - { name = "pyprof2calltree" }, - { name = "pyqt5", marker = "platform_machine == 'x86_64'" }, - { name = "pytools", marker = "platform_machine != 'aarch64'" }, - { name = "pywinctl" }, - { name = "rerun-sdk" }, - { name = "tabulate" }, - { name = "types-requests" }, - { name = "types-tabulate" }, + { name = "opencv-python-headless" }, ] docs = [ { name = "jinja2" }, - { name = "mkdocs" }, - { name = "natsort" }, + { name = "zensical" }, ] testing = [ { name = "codespell" }, { name = "coverage" }, { name = "hypothesis" }, - { name = "mypy" }, { name = "pre-commit-hooks" }, { name = "pytest" }, - { name = "pytest-asyncio" }, - { name = "pytest-cov" }, { name = "pytest-cpp" }, { name = "pytest-mock" }, - { name = "pytest-randomly" }, - { name = "pytest-repeat" }, { name = "pytest-subtests" }, - { name = "pytest-timeout" }, { name = "pytest-xdist" }, { name = "ruff" }, + { name = "ty" }, +] +tools = [ + { name = "imgui" }, + { name = "metadrive-simulator", marker = "platform_machine != 'aarch64'" }, ] [package.metadata] requires-dist = [ + { name = "acados", git = "https://github.com/commaai/dependencies.git?subdirectory=acados&rev=release-acados" }, { name = "aiohttp" }, { name = "aiortc" }, - { name = "av", marker = "extra == 'dev'" }, - { name = "azure-identity", marker = "extra == 'dev'" }, - { name = "azure-storage-blob", marker = "extra == 'dev'" }, - { name = "casadi", specifier = ">=3.6.6" }, + { name = "av" }, + { name = "bootstrap-icons", git = "https://github.com/commaai/dependencies.git?subdirectory=bootstrap-icons&rev=release-bootstrap-icons" }, + { name = "bzip2", git = "https://github.com/commaai/dependencies.git?subdirectory=bzip2&rev=release-bzip2" }, + { name = "capnproto", git = "https://github.com/commaai/dependencies.git?subdirectory=capnproto&rev=release-capnproto" }, + { name = "catch2", git = "https://github.com/commaai/dependencies.git?subdirectory=catch2&rev=release-catch2" }, { name = "cffi" }, { name = "codespell", marker = "extra == 'testing'" }, { name = "coverage", marker = "extra == 'testing'" }, - { name = "crcmod" }, + { name = "crcmod-plus" }, { name = "cython" }, - { name = "dictdiffer", marker = "extra == 'dev'" }, - { name = "flaky", marker = "extra == 'dev'" }, - { name = "future-fstrings" }, + { name = "eigen", git = "https://github.com/commaai/dependencies.git?subdirectory=eigen&rev=release-eigen" }, + { name = "ffmpeg", git = "https://github.com/commaai/dependencies.git?subdirectory=ffmpeg&rev=release-ffmpeg" }, + { name = "gcc-arm-none-eabi", git = "https://github.com/commaai/dependencies.git?subdirectory=gcc-arm-none-eabi&rev=release-gcc-arm-none-eabi" }, + { name = "git-lfs", git = "https://github.com/commaai/dependencies.git?subdirectory=git-lfs&rev=release-git-lfs" }, { name = "hypothesis", marker = "extra == 'testing'", specifier = "==6.47.*" }, - { name = "inputs", marker = "extra == 'dev'" }, + { name = "imgui", marker = "extra == 'tools'", git = "https://github.com/commaai/dependencies.git?subdirectory=imgui&rev=release-imgui" }, + { name = "inputs" }, + { name = "jeepney" }, { name = "jinja2", marker = "extra == 'docs'" }, { name = "json-rpc" }, + { name = "json11", git = "https://github.com/commaai/dependencies.git?subdirectory=json11&rev=release-json11" }, + { name = "libjpeg", git = "https://github.com/commaai/dependencies.git?subdirectory=libjpeg&rev=release-libjpeg" }, + { name = "libusb", git = "https://github.com/commaai/dependencies.git?subdirectory=libusb&rev=release-libusb" }, { name = "libusb1" }, - { name = "lru-dict", marker = "extra == 'dev'" }, + { name = "libyuv", git = "https://github.com/commaai/dependencies.git?subdirectory=libyuv&rev=release-libyuv" }, { name = "matplotlib", marker = "extra == 'dev'" }, - { name = "metadrive-simulator", marker = "platform_machine != 'aarch64' and extra == 'dev'", url = "https://github.com/commaai/metadrive/releases/download/MetaDrive-minimal/metadrive_simulator-0.4.2.3-py3-none-any.whl" }, - { name = "mkdocs", marker = "extra == 'docs'" }, - { name = "mypy", marker = "extra == 'testing'" }, - { name = "natsort", marker = "extra == 'docs'" }, - { name = "numpy", specifier = "<2.0.0" }, - { name = "onnx", specifier = ">=1.14.0" }, - { name = "onnxruntime", marker = "platform_machine == 'aarch64' and platform_system == 'Linux'", specifier = ">=1.16.3" }, - { name = "onnxruntime-gpu", marker = "platform_machine == 'x86_64' and platform_system == 'Linux'", specifier = ">=1.16.3" }, - { name = "parameterized", marker = "extra == 'dev'", specifier = ">=0.8,<0.9" }, + { name = "metadrive-simulator", marker = "platform_machine != 'aarch64' and extra == 'tools'", git = "https://github.com/commaai/metadrive.git?rev=minimal" }, + { name = "ncurses", git = "https://github.com/commaai/dependencies.git?subdirectory=ncurses&rev=release-ncurses" }, + { name = "numpy", specifier = ">=2.0" }, + { name = "opencv-python-headless", marker = "extra == 'dev'" }, + { name = "pillow" }, { name = "pre-commit-hooks", marker = "extra == 'testing'" }, { name = "psutil" }, - { name = "pyaudio" }, - { name = "pyautogui", marker = "extra == 'dev'" }, - { name = "pycapnp" }, + { name = "pycapnp", specifier = "==2.1.0" }, { name = "pycryptodome" }, { name = "pyjwt" }, - { name = "pyopencl", marker = "platform_machine != 'aarch64' and extra == 'dev'" }, - { name = "pyprof2calltree", marker = "extra == 'dev'" }, - { name = "pyqt5", marker = "platform_machine == 'x86_64' and extra == 'dev'", specifier = "==5.15.2" }, { name = "pyserial" }, { name = "pytest", marker = "extra == 'testing'" }, - { name = "pytest-asyncio", marker = "extra == 'testing'" }, - { name = "pytest-cov", marker = "extra == 'testing'" }, { name = "pytest-cpp", marker = "extra == 'testing'" }, { name = "pytest-mock", marker = "extra == 'testing'" }, - { name = "pytest-randomly", marker = "extra == 'testing'" }, - { name = "pytest-repeat", marker = "extra == 'testing'" }, { name = "pytest-subtests", marker = "extra == 'testing'" }, - { name = "pytest-timeout", marker = "extra == 'testing'" }, - { name = "pytest-xdist", marker = "extra == 'testing'" }, - { name = "pytools", marker = "platform_machine != 'aarch64' and extra == 'dev'", specifier = "<2024.1.11" }, - { name = "pywinctl", marker = "extra == 'dev'" }, + { name = "pytest-xdist", marker = "extra == 'testing'", git = "https://github.com/sshane/pytest-xdist?rev=2b4372bd62699fb412c4fe2f95bf9f01bd2018da" }, { name = "pyzmq" }, + { name = "qrcode" }, + { name = "raylib", git = "https://github.com/commaai/dependencies.git?subdirectory=raylib&rev=release-raylib" }, { name = "requests" }, - { name = "rerun-sdk", marker = "extra == 'dev'", specifier = ">=0.18" }, { name = "ruff", marker = "extra == 'testing'" }, { name = "scons" }, { name = "sentry-sdk" }, { name = "setproctitle" }, { name = "setuptools" }, - { name = "smbus2" }, { name = "sounddevice" }, - { name = "spidev", marker = "platform_system == 'Linux'" }, + { name = "spidev", marker = "sys_platform == 'linux'" }, { name = "sympy" }, - { name = "tabulate", marker = "extra == 'dev'" }, { name = "tqdm" }, - { name = "types-requests", marker = "extra == 'dev'" }, - { name = "types-tabulate", marker = "extra == 'dev'" }, + { name = "ty", marker = "extra == 'testing'" }, { name = "websocket-client" }, + { name = "xattr" }, + { name = "xvfb", git = "https://github.com/commaai/dependencies.git?subdirectory=xvfb&rev=release-xvfb" }, + { name = "zensical", marker = "extra == 'docs'" }, + { name = "zeromq", git = "https://github.com/commaai/dependencies.git?subdirectory=zeromq&rev=release-zeromq" }, { name = "zstandard" }, + { name = "zstd", git = "https://github.com/commaai/dependencies.git?subdirectory=zstd&rev=release-zstd" }, ] +provides-extras = ["docs", "testing", "dev", "tools"] [[package]] name = "packaging" -version = "24.1" +version = "26.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/51/65/50db4dda066951078f0a96cf12f4b9ada6e4b811516bf0262c0f4f7064d4/packaging-24.1.tar.gz", hash = "sha256:026ed72c8ed3fcce5bf8950572258698927fd1dbda10a5e981cdf0ac37f4f002", size = 148788 } +sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/08/aa/cc0199a5f0ad350994d660967a8efb233fe0416e4639146c089643407ce6/packaging-24.1-py3-none-any.whl", hash = "sha256:5b8f2217dbdbd2f7f384c41c628544e6d52f2d0f53c6d0c3ea61aa5d1d7ff124", size = 53985 }, + { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, ] [[package]] @@ -1585,17 +914,12 @@ name = "panda3d" version = "1.10.14" source = { registry = "https://pypi.org/simple" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f5/9a/31d07e3d7c1b40335e8418c540d63f4d33c571648ed8d69896ab778e65c3/panda3d-1.10.14-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:54b8ef9fe3684960a2c7d47b0d63c0354c17bc516795e59db6c1e5bda8c16c1c", size = 67700752 }, - { url = "https://files.pythonhosted.org/packages/61/05/fce327535d8907ac01f43813c980f30ea86d37db62c340847519ea2ab222/panda3d-1.10.14-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:93414675894b18eea8d27edc1bbd1dc719eae207d45ec263d47195504bc4705f", size = 118966179 }, - { url = "https://files.pythonhosted.org/packages/8a/54/24e205231e7b1bced58ba9620fbec7114673d821fc7ad9ed1804cab556b4/panda3d-1.10.14-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:d1bc0d926f90c8fa14a1587fa9dbe5f89a4eda8c9684fa183a8eaa35fc8e891a", size = 55145295 }, - { url = "https://files.pythonhosted.org/packages/06/d3/38e989822292935d7473d35117099f71481cc6b104cb2dd048cb8058a5a8/panda3d-1.10.14-cp311-cp311-win32.whl", hash = "sha256:1039340a4a7965fe4c3e904edb4fff691584df435a154fecccf534587cd07a34", size = 53137177 }, - { url = "https://files.pythonhosted.org/packages/5c/32/b16c81661ed0d8ad62976004d81845baa321e53314e253ef0841155be770/panda3d-1.10.14-cp311-cp311-win_amd64.whl", hash = "sha256:1ddf01040b9c5497fb8659e3c5ef793a26c869cfdfb1b75e6d04d6fba0c03b73", size = 64447666 }, - { url = "https://files.pythonhosted.org/packages/5a/d4/90e98993b1a3f3c9fae83267f8c51186e676a8c1365c4180dfc65cd7ba62/panda3d-1.10.14-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:1bfbcee77779f12ecce6a3d5a856e573b25d6343f8c4b107e814d9702e70a65d", size = 67839196 }, - { url = "https://files.pythonhosted.org/packages/dc/e5/862821575073863ce49cc57b8349b47cb25ce11feae0e419b3d023ac1a69/panda3d-1.10.14-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:bc6540c5559d7e14a8992eff7de0157b7c42406b7ba221941ed224289496841c", size = 119271341 }, - { url = "https://files.pythonhosted.org/packages/f4/20/f16d91805777825e530037177d9075c83da7384f12b778b133e3164a31f3/panda3d-1.10.14-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:143daab1ce6bedcba711ea3f6cab0ebe5082f22c5f43e7178fadd2dd01209da7", size = 47604077 }, - { url = "https://files.pythonhosted.org/packages/11/69/806dcdbaee3e8deee1956abeea0d3d3e504315d2e9814de82a44809a8617/panda3d-1.10.14-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:3c4399a286a142de7ff86f9356d7e526bbbd38892d7f7d39fecb5c33064972bc", size = 55539594 }, - { url = "https://files.pythonhosted.org/packages/ad/25/005de5e2b6d0acd546f8b3f2b547cd29e308cdd04a397f0ea68046e26571/panda3d-1.10.14-cp312-cp312-win32.whl", hash = "sha256:e92e0dd907e2af33085a2c31ca2263dc8023b1b7bc70ce1b9fbc84631e130e51", size = 53479813 }, - { url = "https://files.pythonhosted.org/packages/74/bb/cb57563855da994614a33f57bd5691fbcd69f12e5ccddd30d387d0be287f/panda3d-1.10.14-cp312-cp312-win_amd64.whl", hash = "sha256:a5f2defd822d38848f8ae1956115adcb6cc7f464f03a67e73681cc72df125ef4", size = 64893222 }, + { url = "https://files.pythonhosted.org/packages/5a/d4/90e98993b1a3f3c9fae83267f8c51186e676a8c1365c4180dfc65cd7ba62/panda3d-1.10.14-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:1bfbcee77779f12ecce6a3d5a856e573b25d6343f8c4b107e814d9702e70a65d", size = 67839196, upload-time = "2024-01-08T19:01:00.417Z" }, + { url = "https://files.pythonhosted.org/packages/dc/e5/862821575073863ce49cc57b8349b47cb25ce11feae0e419b3d023ac1a69/panda3d-1.10.14-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:bc6540c5559d7e14a8992eff7de0157b7c42406b7ba221941ed224289496841c", size = 119271341, upload-time = "2024-01-08T19:01:09.455Z" }, + { url = "https://files.pythonhosted.org/packages/f4/20/f16d91805777825e530037177d9075c83da7384f12b778b133e3164a31f3/panda3d-1.10.14-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:143daab1ce6bedcba711ea3f6cab0ebe5082f22c5f43e7178fadd2dd01209da7", size = 47604077, upload-time = "2024-05-28T20:25:37.118Z" }, + { url = "https://files.pythonhosted.org/packages/11/69/806dcdbaee3e8deee1956abeea0d3d3e504315d2e9814de82a44809a8617/panda3d-1.10.14-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:3c4399a286a142de7ff86f9356d7e526bbbd38892d7f7d39fecb5c33064972bc", size = 55539594, upload-time = "2024-01-08T19:01:15.979Z" }, + { url = "https://files.pythonhosted.org/packages/ad/25/005de5e2b6d0acd546f8b3f2b547cd29e308cdd04a397f0ea68046e26571/panda3d-1.10.14-cp312-cp312-win32.whl", hash = "sha256:e92e0dd907e2af33085a2c31ca2263dc8023b1b7bc70ce1b9fbc84631e130e51", size = 53479813, upload-time = "2024-01-08T19:01:20.923Z" }, + { url = "https://files.pythonhosted.org/packages/74/bb/cb57563855da994614a33f57bd5691fbcd69f12e5ccddd30d387d0be287f/panda3d-1.10.14-cp312-cp312-win_amd64.whl", hash = "sha256:a5f2defd822d38848f8ae1956115adcb6cc7f464f03a67e73681cc72df125ef4", size = 64893222, upload-time = "2024-01-08T19:01:26.347Z" }, ] [[package]] @@ -1606,3774 +930,730 @@ dependencies = [ { name = "panda3d" }, { name = "panda3d-simplepbr" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/07/7f/9f18fc3fa843a080acb891af6bcc12262e7bdf1d194a530f7042bebfc81f/panda3d-gltf-0.13.tar.gz", hash = "sha256:d06d373bdd91cf530909b669f43080e599463bbf6d3ef00c3558bad6c6b19675", size = 25573 } +sdist = { url = "https://files.pythonhosted.org/packages/07/7f/9f18fc3fa843a080acb891af6bcc12262e7bdf1d194a530f7042bebfc81f/panda3d-gltf-0.13.tar.gz", hash = "sha256:d06d373bdd91cf530909b669f43080e599463bbf6d3ef00c3558bad6c6b19675", size = 25573, upload-time = "2021-05-21T05:46:32.738Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/70/94/98ed1f81ca0f5daf6de80533805cc1e98ac162abe4e3e1d382caa7ba5c3c/panda3d_gltf-0.13-py3-none-any.whl", hash = "sha256:02d1a980f447bb1895ff4b48c667f289ba78f07a28ef308d8839b665a621efe2", size = 25568 }, + { url = "https://files.pythonhosted.org/packages/70/94/98ed1f81ca0f5daf6de80533805cc1e98ac162abe4e3e1d382caa7ba5c3c/panda3d_gltf-0.13-py3-none-any.whl", hash = "sha256:02d1a980f447bb1895ff4b48c667f289ba78f07a28ef308d8839b665a621efe2", size = 25568, upload-time = "2021-05-21T05:46:31.28Z" }, ] [[package]] name = "panda3d-simplepbr" -version = "0.12.0" +version = "0.13.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "panda3d" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b1/af/505608eef09d7f9b822e69dc7631cd14102650b8fe1b6f60d9562d2788d9/panda3d-simplepbr-0.12.0.tar.gz", hash = "sha256:c71d490afeeb3a90455dcfde1d30c41f321a38742a97d18834e5c31016331ed5", size = 1929980 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/46/4c/926e1cf17abfb1d91e12bf38e653cacf10e30c5030e37f9078f0f41aaf40/panda3d_simplepbr-0.12.0-py3-none-any.whl", hash = "sha256:6c43d1990ff07840cf1c557561d6122fd1250d8e76aacf227b61c3789149bcf9", size = 2458121 }, -] - -[[package]] -name = "parameterized" -version = "0.8.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c6/23/2288f308d238b4f261c039cafcd650435d624de97c6ffc903f06ea8af50f/parameterized-0.8.1.tar.gz", hash = "sha256:41bbff37d6186430f77f900d777e5bb6a24928a1c46fb1de692f8b52b8833b5c", size = 23936 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/31/13/fe468c8c7400a8eca204e6e160a29bf7dcd45a76e20f1c030f3eaa690d93/parameterized-0.8.1-py2.py3-none-any.whl", hash = "sha256:9cbb0b69a03e8695d68b3399a8a5825200976536fe1cb79db60ed6a4c8c9efe9", size = 26354 }, -] - -[[package]] -name = "pathspec" -version = "0.12.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043 } +sdist = { url = "https://files.pythonhosted.org/packages/0d/be/c4d1ded04c22b357277cf6e6a44c1ab4abb285a700bd1991460460e05b99/panda3d_simplepbr-0.13.1.tar.gz", hash = "sha256:c83766d7c8f47499f365a07fe1dff078fc8b3054c2689bdc8dceabddfe7f1a35", size = 6216055, upload-time = "2025-03-30T16:57:41.087Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191 }, + { url = "https://files.pythonhosted.org/packages/11/5d/3744c6550dddf933785a37cdd4a9921fe13284e6d115b5a2637fe390f158/panda3d_simplepbr-0.13.1-py3-none-any.whl", hash = "sha256:cda41cb57cff035b851646956cfbdcc408bee42511dabd4f2d7bd4fbf48c57a9", size = 2457097, upload-time = "2025-03-30T16:57:39.729Z" }, ] [[package]] name = "pillow" -version = "10.4.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/cd/74/ad3d526f3bf7b6d3f408b73fde271ec69dfac8b81341a318ce825f2b3812/pillow-10.4.0.tar.gz", hash = "sha256:166c1cd4d24309b30d61f79f4a9114b7b2313d7450912277855ff5dfd7cd4a06", size = 46555059 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a7/62/c9449f9c3043c37f73e7487ec4ef0c03eb9c9afc91a92b977a67b3c0bbc5/pillow-10.4.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:0a9ec697746f268507404647e531e92889890a087e03681a3606d9b920fbee3c", size = 3509265 }, - { url = "https://files.pythonhosted.org/packages/f4/5f/491dafc7bbf5a3cc1845dc0430872e8096eb9e2b6f8161509d124594ec2d/pillow-10.4.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dfe91cb65544a1321e631e696759491ae04a2ea11d36715eca01ce07284738be", size = 3375655 }, - { url = "https://files.pythonhosted.org/packages/73/d5/c4011a76f4207a3c151134cd22a1415741e42fa5ddecec7c0182887deb3d/pillow-10.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5dc6761a6efc781e6a1544206f22c80c3af4c8cf461206d46a1e6006e4429ff3", size = 4340304 }, - { url = "https://files.pythonhosted.org/packages/ac/10/c67e20445a707f7a610699bba4fe050583b688d8cd2d202572b257f46600/pillow-10.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5e84b6cc6a4a3d76c153a6b19270b3526a5a8ed6b09501d3af891daa2a9de7d6", size = 4452804 }, - { url = "https://files.pythonhosted.org/packages/a9/83/6523837906d1da2b269dee787e31df3b0acb12e3d08f024965a3e7f64665/pillow-10.4.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:bbc527b519bd3aa9d7f429d152fea69f9ad37c95f0b02aebddff592688998abe", size = 4365126 }, - { url = "https://files.pythonhosted.org/packages/ba/e5/8c68ff608a4203085158cff5cc2a3c534ec384536d9438c405ed6370d080/pillow-10.4.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:76a911dfe51a36041f2e756b00f96ed84677cdeb75d25c767f296c1c1eda1319", size = 4533541 }, - { url = "https://files.pythonhosted.org/packages/f4/7c/01b8dbdca5bc6785573f4cee96e2358b0918b7b2c7b60d8b6f3abf87a070/pillow-10.4.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:59291fb29317122398786c2d44427bbd1a6d7ff54017075b22be9d21aa59bd8d", size = 4471616 }, - { url = "https://files.pythonhosted.org/packages/c8/57/2899b82394a35a0fbfd352e290945440e3b3785655a03365c0ca8279f351/pillow-10.4.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:416d3a5d0e8cfe4f27f574362435bc9bae57f679a7158e0096ad2beb427b8696", size = 4600802 }, - { url = "https://files.pythonhosted.org/packages/4d/d7/a44f193d4c26e58ee5d2d9db3d4854b2cfb5b5e08d360a5e03fe987c0086/pillow-10.4.0-cp311-cp311-win32.whl", hash = "sha256:7086cc1d5eebb91ad24ded9f58bec6c688e9f0ed7eb3dbbf1e4800280a896496", size = 2235213 }, - { url = "https://files.pythonhosted.org/packages/c1/d0/5866318eec2b801cdb8c82abf190c8343d8a1cd8bf5a0c17444a6f268291/pillow-10.4.0-cp311-cp311-win_amd64.whl", hash = "sha256:cbed61494057c0f83b83eb3a310f0bf774b09513307c434d4366ed64f4128a91", size = 2554498 }, - { url = "https://files.pythonhosted.org/packages/d4/c8/310ac16ac2b97e902d9eb438688de0d961660a87703ad1561fd3dfbd2aa0/pillow-10.4.0-cp311-cp311-win_arm64.whl", hash = "sha256:f5f0c3e969c8f12dd2bb7e0b15d5c468b51e5017e01e2e867335c81903046a22", size = 2243219 }, - { url = "https://files.pythonhosted.org/packages/05/cb/0353013dc30c02a8be34eb91d25e4e4cf594b59e5a55ea1128fde1e5f8ea/pillow-10.4.0-cp312-cp312-macosx_10_10_x86_64.whl", hash = "sha256:673655af3eadf4df6b5457033f086e90299fdd7a47983a13827acf7459c15d94", size = 3509350 }, - { url = "https://files.pythonhosted.org/packages/e7/cf/5c558a0f247e0bf9cec92bff9b46ae6474dd736f6d906315e60e4075f737/pillow-10.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:866b6942a92f56300012f5fbac71f2d610312ee65e22f1aa2609e491284e5597", size = 3374980 }, - { url = "https://files.pythonhosted.org/packages/84/48/6e394b86369a4eb68b8a1382c78dc092245af517385c086c5094e3b34428/pillow-10.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:29dbdc4207642ea6aad70fbde1a9338753d33fb23ed6956e706936706f52dd80", size = 4343799 }, - { url = "https://files.pythonhosted.org/packages/3b/f3/a8c6c11fa84b59b9df0cd5694492da8c039a24cd159f0f6918690105c3be/pillow-10.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf2342ac639c4cf38799a44950bbc2dfcb685f052b9e262f446482afaf4bffca", size = 4459973 }, - { url = "https://files.pythonhosted.org/packages/7d/1b/c14b4197b80150fb64453585247e6fb2e1d93761fa0fa9cf63b102fde822/pillow-10.4.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:f5b92f4d70791b4a67157321c4e8225d60b119c5cc9aee8ecf153aace4aad4ef", size = 4370054 }, - { url = "https://files.pythonhosted.org/packages/55/77/40daddf677897a923d5d33329acd52a2144d54a9644f2a5422c028c6bf2d/pillow-10.4.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:86dcb5a1eb778d8b25659d5e4341269e8590ad6b4e8b44d9f4b07f8d136c414a", size = 4539484 }, - { url = "https://files.pythonhosted.org/packages/40/54/90de3e4256b1207300fb2b1d7168dd912a2fb4b2401e439ba23c2b2cabde/pillow-10.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:780c072c2e11c9b2c7ca37f9a2ee8ba66f44367ac3e5c7832afcfe5104fd6d1b", size = 4477375 }, - { url = "https://files.pythonhosted.org/packages/13/24/1bfba52f44193860918ff7c93d03d95e3f8748ca1de3ceaf11157a14cf16/pillow-10.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:37fb69d905be665f68f28a8bba3c6d3223c8efe1edf14cc4cfa06c241f8c81d9", size = 4608773 }, - { url = "https://files.pythonhosted.org/packages/55/04/5e6de6e6120451ec0c24516c41dbaf80cce1b6451f96561235ef2429da2e/pillow-10.4.0-cp312-cp312-win32.whl", hash = "sha256:7dfecdbad5c301d7b5bde160150b4db4c659cee2b69589705b6f8a0c509d9f42", size = 2235690 }, - { url = "https://files.pythonhosted.org/packages/74/0a/d4ce3c44bca8635bd29a2eab5aa181b654a734a29b263ca8efe013beea98/pillow-10.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:1d846aea995ad352d4bdcc847535bd56e0fd88d36829d2c90be880ef1ee4668a", size = 2554951 }, - { url = "https://files.pythonhosted.org/packages/b5/ca/184349ee40f2e92439be9b3502ae6cfc43ac4b50bc4fc6b3de7957563894/pillow-10.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:e553cad5179a66ba15bb18b353a19020e73a7921296a7979c4a2b7f6a5cd57f9", size = 2243427 }, - { url = "https://files.pythonhosted.org/packages/c3/00/706cebe7c2c12a6318aabe5d354836f54adff7156fd9e1bd6c89f4ba0e98/pillow-10.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8bc1a764ed8c957a2e9cacf97c8b2b053b70307cf2996aafd70e91a082e70df3", size = 3525685 }, - { url = "https://files.pythonhosted.org/packages/cf/76/f658cbfa49405e5ecbfb9ba42d07074ad9792031267e782d409fd8fe7c69/pillow-10.4.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6209bb41dc692ddfee4942517c19ee81b86c864b626dbfca272ec0f7cff5d9fb", size = 3374883 }, - { url = "https://files.pythonhosted.org/packages/46/2b/99c28c4379a85e65378211971c0b430d9c7234b1ec4d59b2668f6299e011/pillow-10.4.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bee197b30783295d2eb680b311af15a20a8b24024a19c3a26431ff83eb8d1f70", size = 4339837 }, - { url = "https://files.pythonhosted.org/packages/f1/74/b1ec314f624c0c43711fdf0d8076f82d9d802afd58f1d62c2a86878e8615/pillow-10.4.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1ef61f5dd14c300786318482456481463b9d6b91ebe5ef12f405afbba77ed0be", size = 4455562 }, - { url = "https://files.pythonhosted.org/packages/4a/2a/4b04157cb7b9c74372fa867096a1607e6fedad93a44deeff553ccd307868/pillow-10.4.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:297e388da6e248c98bc4a02e018966af0c5f92dfacf5a5ca22fa01cb3179bca0", size = 4366761 }, - { url = "https://files.pythonhosted.org/packages/ac/7b/8f1d815c1a6a268fe90481232c98dd0e5fa8c75e341a75f060037bd5ceae/pillow-10.4.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:e4db64794ccdf6cb83a59d73405f63adbe2a1887012e308828596100a0b2f6cc", size = 4536767 }, - { url = "https://files.pythonhosted.org/packages/e5/77/05fa64d1f45d12c22c314e7b97398ffb28ef2813a485465017b7978b3ce7/pillow-10.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:bd2880a07482090a3bcb01f4265f1936a903d70bc740bfcb1fd4e8a2ffe5cf5a", size = 4477989 }, - { url = "https://files.pythonhosted.org/packages/12/63/b0397cfc2caae05c3fb2f4ed1b4fc4fc878f0243510a7a6034ca59726494/pillow-10.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4b35b21b819ac1dbd1233317adeecd63495f6babf21b7b2512d244ff6c6ce309", size = 4610255 }, - { url = "https://files.pythonhosted.org/packages/7b/f9/cfaa5082ca9bc4a6de66ffe1c12c2d90bf09c309a5f52b27759a596900e7/pillow-10.4.0-cp313-cp313-win32.whl", hash = "sha256:551d3fd6e9dc15e4c1eb6fc4ba2b39c0c7933fa113b220057a34f4bb3268a060", size = 2235603 }, - { url = "https://files.pythonhosted.org/packages/01/6a/30ff0eef6e0c0e71e55ded56a38d4859bf9d3634a94a88743897b5f96936/pillow-10.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:030abdbe43ee02e0de642aee345efa443740aa4d828bfe8e2eb11922ea6a21ea", size = 2554972 }, - { url = "https://files.pythonhosted.org/packages/48/2c/2e0a52890f269435eee38b21c8218e102c621fe8d8df8b9dd06fabf879ba/pillow-10.4.0-cp313-cp313-win_arm64.whl", hash = "sha256:5b001114dd152cfd6b23befeb28d7aee43553e2402c9f159807bf55f33af8a8d", size = 2243375 }, -] - -[[package]] -name = "platformdirs" -version = "4.2.2" +version = "12.2.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f5/52/0763d1d976d5c262df53ddda8d8d4719eedf9594d046f117c25a27261a19/platformdirs-4.2.2.tar.gz", hash = "sha256:38b7b51f512eed9e84a22788b4bce1de17c0adb134d6becb09836e37d8654cd3", size = 20916 } +sdist = { url = "https://files.pythonhosted.org/packages/8c/21/c2bcdd5906101a30244eaffc1b6e6ce71a31bd0742a01eb89e660ebfac2d/pillow-12.2.0.tar.gz", hash = "sha256:a830b1a40919539d07806aa58e1b114df53ddd43213d9c8b75847eee6c0182b5", size = 46987819, upload-time = "2026-04-01T14:46:17.687Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/68/13/2aa1f0e1364feb2c9ef45302f387ac0bd81484e9c9a4c5688a322fbdfd08/platformdirs-4.2.2-py3-none-any.whl", hash = "sha256:2d7a1657e36a80ea911db832a8a6ece5ee53d8de21edd5cc5879af6530b1bfee", size = 18146 }, + { url = "https://files.pythonhosted.org/packages/58/be/7482c8a5ebebbc6470b3eb791812fff7d5e0216c2be3827b30b8bb6603ed/pillow-12.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d192a155bbcec180f8564f693e6fd9bccff5a7af9b32e2e4bf8c9c69dbad6b5", size = 5308279, upload-time = "2026-04-01T14:43:13.246Z" }, + { url = "https://files.pythonhosted.org/packages/d8/95/0a351b9289c2b5cbde0bacd4a83ebc44023e835490a727b2a3bd60ddc0f4/pillow-12.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3f40b3c5a968281fd507d519e444c35f0ff171237f4fdde090dd60699458421", size = 4695490, upload-time = "2026-04-01T14:43:15.584Z" }, + { url = "https://files.pythonhosted.org/packages/de/af/4e8e6869cbed569d43c416fad3dc4ecb944cb5d9492defaed89ddd6fe871/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:03e7e372d5240cc23e9f07deca4d775c0817bffc641b01e9c3af208dbd300987", size = 6284462, upload-time = "2026-04-01T14:43:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/e9/9e/c05e19657fd57841e476be1ab46c4d501bffbadbafdc31a6d665f8b737b6/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b86024e52a1b269467a802258c25521e6d742349d760728092e1bc2d135b4d76", size = 8094744, upload-time = "2026-04-01T14:43:20.716Z" }, + { url = "https://files.pythonhosted.org/packages/2b/54/1789c455ed10176066b6e7e6da1b01e50e36f94ba584dc68d9eebfe9156d/pillow-12.2.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7371b48c4fa448d20d2714c9a1f775a81155050d383333e0a6c15b1123dda005", size = 6398371, upload-time = "2026-04-01T14:43:23.443Z" }, + { url = "https://files.pythonhosted.org/packages/43/e3/fdc657359e919462369869f1c9f0e973f353f9a9ee295a39b1fea8ee1a77/pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:62f5409336adb0663b7caa0da5c7d9e7bdbaae9ce761d34669420c2a801b2780", size = 7087215, upload-time = "2026-04-01T14:43:26.758Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f8/2f6825e441d5b1959d2ca5adec984210f1ec086435b0ed5f52c19b3b8a6e/pillow-12.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:01afa7cf67f74f09523699b4e88c73fb55c13346d212a59a2db1f86b0a63e8c5", size = 6509783, upload-time = "2026-04-01T14:43:29.56Z" }, + { url = "https://files.pythonhosted.org/packages/67/f9/029a27095ad20f854f9dba026b3ea6428548316e057e6fc3545409e86651/pillow-12.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc3d34d4a8fbec3e88a79b92e5465e0f9b842b628675850d860b8bd300b159f5", size = 7212112, upload-time = "2026-04-01T14:43:32.091Z" }, + { url = "https://files.pythonhosted.org/packages/be/42/025cfe05d1be22dbfdb4f264fe9de1ccda83f66e4fc3aac94748e784af04/pillow-12.2.0-cp312-cp312-win32.whl", hash = "sha256:58f62cc0f00fd29e64b29f4fd923ffdb3859c9f9e6105bfc37ba1d08994e8940", size = 6378489, upload-time = "2026-04-01T14:43:34.601Z" }, + { url = "https://files.pythonhosted.org/packages/5d/7b/25a221d2c761c6a8ae21bfa3874988ff2583e19cf8a27bf2fee358df7942/pillow-12.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:7f84204dee22a783350679a0333981df803dac21a0190d706a50475e361c93f5", size = 7084129, upload-time = "2026-04-01T14:43:37.213Z" }, + { url = "https://files.pythonhosted.org/packages/10/e1/542a474affab20fd4a0f1836cb234e8493519da6b76899e30bcc5d990b8b/pillow-12.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:af73337013e0b3b46f175e79492d96845b16126ddf79c438d7ea7ff27783a414", size = 2463612, upload-time = "2026-04-01T14:43:39.421Z" }, ] [[package]] name = "pluggy" -version = "1.5.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/96/2d/02d4312c973c6050a18b314a5ad0b3210edb65a906f868e31c111dede4a6/pluggy-1.5.0.tar.gz", hash = "sha256:2cffa88e94fdc978c4c574f15f9e59b7f4201d439195c3715ca9e2486f1d0cf1", size = 67955 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/88/5f/e351af9a41f866ac3f1fac4ca0613908d9a41741cfcf2228f4ad853b697d/pluggy-1.5.0-py3-none-any.whl", hash = "sha256:44e1ad92c8ca002de6377e165f3e0f1be63266ab4d554740532335b9d75ea669", size = 20556 }, -] - -[[package]] -name = "portalocker" -version = "2.10.1" +version = "1.6.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pywin32", marker = "platform_system == 'Windows'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ed/d3/c6c64067759e87af98cc668c1cc75171347d0f1577fab7ca3749134e3cd4/portalocker-2.10.1.tar.gz", hash = "sha256:ef1bf844e878ab08aee7e40184156e1151f228f103aa5c6bd0724cc330960f8f", size = 40891 } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9b/fb/a70a4214956182e0d7a9099ab17d50bfcba1056188e9b14f35b9e2b62a0d/portalocker-2.10.1-py3-none-any.whl", hash = "sha256:53a5984ebc86a025552264b459b46a2086e269b21823cb572f8f28ee759e45bf", size = 18423 }, + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] [[package]] name = "pre-commit-hooks" -version = "4.6.0" +version = "6.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "ruamel-yaml" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/83/0d/b4e97cd99b26c0cd8265c9f19ee7e55248142f0c9955e4d119de96fa4a13/pre_commit_hooks-4.6.0.tar.gz", hash = "sha256:eb1f43ee67869cd41b4c59017fad4a0f9d4d61201d163f2135535aaf65035a2b", size = 29579 } +sdist = { url = "https://files.pythonhosted.org/packages/36/4d/93e63e48f8fd16d6c1e4cef5dabadcade4d1325c7fd6f29f075a4d2284f3/pre_commit_hooks-6.0.0.tar.gz", hash = "sha256:76d8370c006f5026cdd638a397a678d26dda735a3c88137e05885a020f824034", size = 28293, upload-time = "2025-08-09T19:25:04.6Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/d8/d09b270248bc2441f966dd094a3de8ae813112d2687036f621202bdef80b/pre_commit_hooks-4.6.0-py2.py3-none-any.whl", hash = "sha256:a69199e6a2d45ec59c1020a81ca1549abddc2afb798276d9a0d951752d6abbfe", size = 41193 }, + { url = "https://files.pythonhosted.org/packages/12/46/eba9be9daa403fa94854ce16a458c29df9a01c6c047931c3d8be6016cd9a/pre_commit_hooks-6.0.0-py2.py3-none-any.whl", hash = "sha256:76161b76d321d2f8ee2a8e0b84c30ee8443e01376121fd1c90851e33e3bd7ee2", size = 41338, upload-time = "2025-08-09T19:25:03.513Z" }, ] [[package]] -name = "progressbar" -version = "2.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a3/a6/b8e451f6cff1c99b4747a2f7235aa904d2d49e8e1464e0b798272aa84358/progressbar-2.5.tar.gz", hash = "sha256:5d81cb529da2e223b53962afd6c8ca0f05c6670e40309a7219eacc36af9b6c63", size = 10046 } - -[[package]] -name = "protobuf" -version = "5.28.0" +name = "propcache" +version = "0.5.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5f/d7/331ee1f3b798c34d2257c79d5426ecbe95d46d2b40ba808a29da6947f6d8/protobuf-5.28.0.tar.gz", hash = "sha256:dde74af0fa774fa98892209992295adbfb91da3fa98c8f67a88afe8f5a349add", size = 422388 } +sdist = { url = "https://files.pythonhosted.org/packages/ec/44/c87281c333769159c50594f22610f77398a47ccbfbbf23074e744e86f87c/propcache-0.5.2.tar.gz", hash = "sha256:01c4fc7480cd0598bb4b57022df55b9ca296da7fc5a8760bd8451a7e63a7d427", size = 50208, upload-time = "2026-05-08T21:02:12.199Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/66/34/fc43138c93316839080324cb066f35224b75dae56b9f0fdd9d47c988ee9a/protobuf-5.28.0-cp310-abi3-win32.whl", hash = "sha256:66c3edeedb774a3508ae70d87b3a19786445fe9a068dd3585e0cefa8a77b83d0", size = 419672 }, - { url = "https://files.pythonhosted.org/packages/de/f7/e7e03be7e7307123f6467080f283e484de7e892db54dd9a46f057d08c9ee/protobuf-5.28.0-cp310-abi3-win_amd64.whl", hash = "sha256:6d7cc9e60f976cf3e873acb9a40fed04afb5d224608ed5c1a105db4a3f09c5b6", size = 431486 }, - { url = "https://files.pythonhosted.org/packages/ce/ec/34f67d6a3398aa360524d90f75a8c648c99c807b2f1001f5ab16355c1d12/protobuf-5.28.0-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:532627e8fdd825cf8767a2d2b94d77e874d5ddb0adefb04b237f7cc296748681", size = 414744 }, - { url = "https://files.pythonhosted.org/packages/fe/79/636415c84eed9835fed83183db73fd6ea7ba76a85cae321ff2eaad722e85/protobuf-5.28.0-cp38-abi3-manylinux2014_aarch64.whl", hash = "sha256:018db9056b9d75eb93d12a9d35120f97a84d9a919bcab11ed56ad2d399d6e8dd", size = 316527 }, - { url = "https://files.pythonhosted.org/packages/19/15/da43113361db20f2d521bc38d92549edbe06856aeec085c420b2b8af5751/protobuf-5.28.0-cp38-abi3-manylinux2014_x86_64.whl", hash = "sha256:6206afcb2d90181ae8722798dcb56dc76675ab67458ac24c0dd7d75d632ac9bd", size = 316615 }, - { url = "https://files.pythonhosted.org/packages/e3/b2/4df9958122a0377e571972c71692420bafd623d1df3ce506d88c2aba7e12/protobuf-5.28.0-py3-none-any.whl", hash = "sha256:510ed78cd0980f6d3218099e874714cdf0d8a95582e7b059b06cabad855ed0a0", size = 169574 }, + { url = "https://files.pythonhosted.org/packages/4a/cb/e27bc2b2737a0bb49962b275efa051e8f1c35a936df7d5139b6b658b7dc9/propcache-0.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:806719138ecd720339a12410fb9614ac9b2b2d3a5fdf8235d56981c36f4039ba", size = 95887, upload-time = "2026-05-08T21:00:11.277Z" }, + { url = "https://files.pythonhosted.org/packages/e6/13/b8ae04c59392f8d11c6cd9fb4011d1dc7c86b81225c770280300e259ffe1/propcache-0.5.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:db2b80ea58eab4f86b2beec3cc8b39e8ff9276ac20e96b7cce43c8ae84cd6b5a", size = 54654, upload-time = "2026-05-08T21:00:12.604Z" }, + { url = "https://files.pythonhosted.org/packages/2c/7d/49777a3e20b55863d4794384a38acd460c04157b0a00f8602b0d508b8431/propcache-0.5.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e5cbfac9f61484f7e9f3597775500cd3ebe8274e9b050c38f9525c77c97520bf", size = 55190, upload-time = "2026-05-08T21:00:13.935Z" }, + { url = "https://files.pythonhosted.org/packages/44/c7/085d0cd63062e84044e3f05797749c3f8e3938ff3aeb0eb2f69d43fafc91/propcache-0.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbc581d2814337da56222fab8dc5f161cd798a434e49bac27930aaef798e144", size = 59995, upload-time = "2026-05-08T21:00:15.526Z" }, + { url = "https://files.pythonhosted.org/packages/9c/42/32cf8e3009e92b2645cf1e944f701e8ea4e924dffde1ee26db860bcbf7e4/propcache-0.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:857187f381f88c8e2fa2fe56ab94879d011b883d5a2ee5a1b60a8cd2a06846d9", size = 63422, upload-time = "2026-05-08T21:00:16.824Z" }, + { url = "https://files.pythonhosted.org/packages/9e/1b/f112433f99fc979431b87a39ef169e3f8df070d99a72792c56d6937ac48b/propcache-0.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:178b4a2cdaac1818e2bf1c5a99b94383fa73ea5382e032a48dec07dc5668dc42", size = 64342, upload-time = "2026-05-08T21:00:18.362Z" }, + { url = "https://files.pythonhosted.org/packages/14/15/5574111ae50dd6e879456888c0eadd4c5a869959775854e18e18a6b345f3/propcache-0.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f328175a2cde1f0ff2c4ed8ce968b9dcfb55f3a7153f39e2957ed994da13476", size = 61639, upload-time = "2026-05-08T21:00:19.692Z" }, + { url = "https://files.pythonhosted.org/packages/cc/da/4d775080b1490c0ae604acda868bd71aabe3a89ed16f2aa4339eb8a283e7/propcache-0.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5671d09a36b06d0fd4a3da0fccbcae360e9b1570924171a15e9e0997f0249fba", size = 61588, upload-time = "2026-05-08T21:00:21.155Z" }, + { url = "https://files.pythonhosted.org/packages/04/ac/f076982cbe2195ee9cf32de5a1e46951d9fb399fc207f390562dd0fd8fb2/propcache-0.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:80168e2ebe4d3ec6599d10ad8f520304ae1cad9b6c5a95372aef1b66b7bfb53a", size = 60029, upload-time = "2026-05-08T21:00:22.713Z" }, + { url = "https://files.pythonhosted.org/packages/70/60/189be62e0dd898dce3b331e1b8c7a543cd3a405ac0c81fe8ee8a9d5d77e1/propcache-0.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:45f11346f884bc47444f6e6647131055844134c3175b629f84952e2b5cd62b64", size = 56774, upload-time = "2026-05-08T21:00:24.001Z" }, + { url = "https://files.pythonhosted.org/packages/ea/9e/93377b9c7939c1ffae98f878dee955efadfd638078bc86dbc21f9d52f651/propcache-0.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8e778ebd44ef4f66ed60a0416b06b489687db264a9c0b3620362f26489492913", size = 63532, upload-time = "2026-05-08T21:00:25.545Z" }, + { url = "https://files.pythonhosted.org/packages/14/f9/590ef6cfb9b8028d516d287812ece32bb0bc5f11fbb9c8bf6b2e6313fec8/propcache-0.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:c0cb9ed24c8964e172768d455a38254c2dd8a552905729ce006cad3d3dda59b1", size = 61592, upload-time = "2026-05-08T21:00:27.186Z" }, + { url = "https://files.pythonhosted.org/packages/b4/5e/70958b3034c297a630bba2f17ca7abc2d5f39a803ad7e370ab79d1ecd022/propcache-0.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:1d1ad32d9d4355e2be65574fd0bfd3677e7066b009cd5b9b2dee8aa6a6393b33", size = 64788, upload-time = "2026-05-08T21:00:28.8Z" }, + { url = "https://files.pythonhosted.org/packages/12/fd/77fe5936d8c3086ca9048f7f415f122ed82e53884a9ec193646b42deef06/propcache-0.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c80f4ba3e8f00189165999a742ee526ebeccedf6c3f7beb0c7df821e9772435a", size = 62514, upload-time = "2026-05-08T21:00:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/cf/74/66bd798b5b3be70aa1b391f5cc9d6a0a5532d7fd3b19ec0b213e72e6ad9d/propcache-0.5.2-cp312-cp312-win32.whl", hash = "sha256:8c7972d8f193740d9175f0998ab38717e6cd322d5935c5b0fef8c0d323fd9031", size = 39018, upload-time = "2026-05-08T21:00:31.622Z" }, + { url = "https://files.pythonhosted.org/packages/61/7c/5c0d34aa3024694d6dcb9271cdbdd08c4e47c1c0ad95ec7e7bc74cdea145/propcache-0.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:d9ee8826a7d47863a08ac44e1a5f611a462eefc3a194b492da242128bec75b42", size = 42322, upload-time = "2026-05-08T21:00:32.918Z" }, + { url = "https://files.pythonhosted.org/packages/4d/91/875812f1a3feb20ceba818ef39fbe4d92f1081e04ac815c822496d0d038b/propcache-0.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:2800a4a8ead6b28cccd1ec54b59346f0def7922ee1c7598e8499c733cfbb7c84", size = 38172, upload-time = "2026-05-08T21:00:35.124Z" }, + { url = "https://files.pythonhosted.org/packages/3a/ed/1cdcab6ba3d6ab7feca11fc14f0eeea80755bb53ef4e892079f31b10a25f/propcache-0.5.2-py3-none-any.whl", hash = "sha256:be1ddfcbb376e3de5d2e2db1d58d6d67463e6b4f9f040c000de8e300295465fe", size = 14036, upload-time = "2026-05-08T21:02:10.673Z" }, ] [[package]] name = "psutil" -version = "6.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/18/c7/8c6872f7372eb6a6b2e4708b88419fb46b857f7a2e1892966b851cc79fc9/psutil-6.0.0.tar.gz", hash = "sha256:8faae4f310b6d969fa26ca0545338b21f73c6b15db7c4a8d934a5482faa818f2", size = 508067 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c5/66/78c9c3020f573c58101dc43a44f6855d01bbbd747e24da2f0c4491200ea3/psutil-6.0.0-cp27-none-win32.whl", hash = "sha256:02b69001f44cc73c1c5279d02b30a817e339ceb258ad75997325e0e6169d8b35", size = 249766 }, - { url = "https://files.pythonhosted.org/packages/e1/3f/2403aa9558bea4d3854b0e5e567bc3dd8e9fbc1fc4453c0aa9aafeb75467/psutil-6.0.0-cp27-none-win_amd64.whl", hash = "sha256:21f1fb635deccd510f69f485b87433460a603919b45e2a324ad65b0cc74f8fb1", size = 253024 }, - { url = "https://files.pythonhosted.org/packages/0b/37/f8da2fbd29690b3557cca414c1949f92162981920699cd62095a984983bf/psutil-6.0.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:c588a7e9b1173b6e866756dde596fd4cad94f9399daf99ad8c3258b3cb2b47a0", size = 250961 }, - { url = "https://files.pythonhosted.org/packages/35/56/72f86175e81c656a01c4401cd3b1c923f891b31fbcebe98985894176d7c9/psutil-6.0.0-cp36-abi3-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6ed2440ada7ef7d0d608f20ad89a04ec47d2d3ab7190896cd62ca5fc4fe08bf0", size = 287478 }, - { url = "https://files.pythonhosted.org/packages/19/74/f59e7e0d392bc1070e9a70e2f9190d652487ac115bb16e2eff6b22ad1d24/psutil-6.0.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5fd9a97c8e94059b0ef54a7d4baf13b405011176c3b6ff257c247cae0d560ecd", size = 290455 }, - { url = "https://files.pythonhosted.org/packages/cd/5f/60038e277ff0a9cc8f0c9ea3d0c5eb6ee1d2470ea3f9389d776432888e47/psutil-6.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e2e8d0054fc88153ca0544f5c4d554d42e33df2e009c4ff42284ac9ebdef4132", size = 292046 }, - { url = "https://files.pythonhosted.org/packages/8b/20/2ff69ad9c35c3df1858ac4e094f20bd2374d33c8643cf41da8fd7cdcb78b/psutil-6.0.0-cp37-abi3-win32.whl", hash = "sha256:a495580d6bae27291324fe60cea0b5a7c23fa36a7cd35035a16d93bdcf076b9d", size = 253560 }, - { url = "https://files.pythonhosted.org/packages/73/44/561092313ae925f3acfaace6f9ddc4f6a9c748704317bad9c8c8f8a36a79/psutil-6.0.0-cp37-abi3-win_amd64.whl", hash = "sha256:33ea5e1c975250a720b3a6609c490db40dae5d83a4eb315170c4fe0d8b1f34b3", size = 257399 }, - { url = "https://files.pythonhosted.org/packages/7c/06/63872a64c312a24fb9b4af123ee7007a306617da63ff13bcc1432386ead7/psutil-6.0.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:ffe7fc9b6b36beadc8c322f84e1caff51e8703b88eee1da46d1e3a6ae11b4fd0", size = 251988 }, -] - -[[package]] -name = "pyarrow" -version = "17.0.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/27/4e/ea6d43f324169f8aec0e57569443a38bab4b398d09769ca64f7b4d467de3/pyarrow-17.0.0.tar.gz", hash = "sha256:4beca9521ed2c0921c1023e68d097d0299b62c362639ea315572a58f3f50fd28", size = 1112479 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f9/46/ce89f87c2936f5bb9d879473b9663ce7a4b1f4359acc2f0eb39865eaa1af/pyarrow-17.0.0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:1c8856e2ef09eb87ecf937104aacfa0708f22dfeb039c363ec99735190ffb977", size = 29028748 }, - { url = "https://files.pythonhosted.org/packages/8d/8e/ce2e9b2146de422f6638333c01903140e9ada244a2a477918a368306c64c/pyarrow-17.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2e19f569567efcbbd42084e87f948778eb371d308e137a0f97afe19bb860ccb3", size = 27190965 }, - { url = "https://files.pythonhosted.org/packages/3b/c8/5675719570eb1acd809481c6d64e2136ffb340bc387f4ca62dce79516cea/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b244dc8e08a23b3e352899a006a26ae7b4d0da7bb636872fa8f5884e70acf15", size = 39269081 }, - { url = "https://files.pythonhosted.org/packages/5e/78/3931194f16ab681ebb87ad252e7b8d2c8b23dad49706cadc865dff4a1dd3/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0b72e87fe3e1db343995562f7fff8aee354b55ee83d13afba65400c178ab2597", size = 39864921 }, - { url = "https://files.pythonhosted.org/packages/d8/81/69b6606093363f55a2a574c018901c40952d4e902e670656d18213c71ad7/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:dc5c31c37409dfbc5d014047817cb4ccd8c1ea25d19576acf1a001fe07f5b420", size = 38740798 }, - { url = "https://files.pythonhosted.org/packages/4c/21/9ca93b84b92ef927814cb7ba37f0774a484c849d58f0b692b16af8eebcfb/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:e3343cb1e88bc2ea605986d4b94948716edc7a8d14afd4e2c097232f729758b4", size = 39871877 }, - { url = "https://files.pythonhosted.org/packages/30/d1/63a7c248432c71c7d3ee803e706590a0b81ce1a8d2b2ae49677774b813bb/pyarrow-17.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:a27532c38f3de9eb3e90ecab63dfda948a8ca859a66e3a47f5f42d1e403c4d03", size = 25151089 }, - { url = "https://files.pythonhosted.org/packages/d4/62/ce6ac1275a432b4a27c55fe96c58147f111d8ba1ad800a112d31859fae2f/pyarrow-17.0.0-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:9b8a823cea605221e61f34859dcc03207e52e409ccf6354634143e23af7c8d22", size = 29019418 }, - { url = "https://files.pythonhosted.org/packages/8e/0a/dbd0c134e7a0c30bea439675cc120012337202e5fac7163ba839aa3691d2/pyarrow-17.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f1e70de6cb5790a50b01d2b686d54aaf73da01266850b05e3af2a1bc89e16053", size = 27152197 }, - { url = "https://files.pythonhosted.org/packages/cb/05/3f4a16498349db79090767620d6dc23c1ec0c658a668d61d76b87706c65d/pyarrow-17.0.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0071ce35788c6f9077ff9ecba4858108eebe2ea5a3f7cf2cf55ebc1dbc6ee24a", size = 39263026 }, - { url = "https://files.pythonhosted.org/packages/c2/0c/ea2107236740be8fa0e0d4a293a095c9f43546a2465bb7df34eee9126b09/pyarrow-17.0.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:757074882f844411fcca735e39aae74248a1531367a7c80799b4266390ae51cc", size = 39880798 }, - { url = "https://files.pythonhosted.org/packages/f6/b0/b9164a8bc495083c10c281cc65064553ec87b7537d6f742a89d5953a2a3e/pyarrow-17.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:9ba11c4f16976e89146781a83833df7f82077cdab7dc6232c897789343f7891a", size = 38715172 }, - { url = "https://files.pythonhosted.org/packages/f1/c4/9625418a1413005e486c006e56675334929fad864347c5ae7c1b2e7fe639/pyarrow-17.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:b0c6ac301093b42d34410b187bba560b17c0330f64907bfa4f7f7f2444b0cf9b", size = 39874508 }, - { url = "https://files.pythonhosted.org/packages/ae/49/baafe2a964f663413be3bd1cf5c45ed98c5e42e804e2328e18f4570027c1/pyarrow-17.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:392bc9feabc647338e6c89267635e111d71edad5fcffba204425a7c8d13610d7", size = 25099235 }, -] - -[[package]] -name = "pyaudio" -version = "0.2.14" +version = "7.2.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/26/1d/8878c7752febb0f6716a7e1a52cb92ac98871c5aa522cba181878091607c/PyAudio-0.2.14.tar.gz", hash = "sha256:78dfff3879b4994d1f4fc6485646a57755c6ee3c19647a491f790a0895bd2f87", size = 47066 } +sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7b/f0/b0eab89eafa70a86b7b566a4df2f94c7880a2d483aa8de1c77d335335b5b/PyAudio-0.2.14-cp311-cp311-win32.whl", hash = "sha256:506b32a595f8693811682ab4b127602d404df7dfc453b499c91a80d0f7bad289", size = 144624 }, - { url = "https://files.pythonhosted.org/packages/82/d8/f043c854aad450a76e476b0cf9cda1956419e1dacf1062eb9df3c0055abe/PyAudio-0.2.14-cp311-cp311-win_amd64.whl", hash = "sha256:bbeb01d36a2f472ae5ee5e1451cacc42112986abe622f735bb870a5db77cf903", size = 164070 }, - { url = "https://files.pythonhosted.org/packages/8d/45/8d2b76e8f6db783f9326c1305f3f816d4a12c8eda5edc6a2e1d03c097c3b/PyAudio-0.2.14-cp312-cp312-win32.whl", hash = "sha256:5fce4bcdd2e0e8c063d835dbe2860dac46437506af509353c7f8114d4bacbd5b", size = 144750 }, - { url = "https://files.pythonhosted.org/packages/b0/6a/d25812e5f79f06285767ec607b39149d02aa3b31d50c2269768f48768930/PyAudio-0.2.14-cp312-cp312-win_amd64.whl", hash = "sha256:12f2f1ba04e06ff95d80700a78967897a489c05e093e3bffa05a84ed9c0a7fa3", size = 164126 }, + { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, + { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, + { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, + { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, + { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, + { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, ] -[[package]] -name = "pyautogui" -version = "0.9.54" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mouseinfo" }, - { name = "pygetwindow" }, - { name = "pymsgbox" }, - { name = "pyobjc-core", marker = "platform_system == 'Darwin'" }, - { name = "pyobjc-framework-quartz", marker = "platform_system == 'Darwin'" }, - { name = "pyscreeze" }, - { name = "python3-xlib", marker = "platform_system == 'Linux'" }, - { name = "pytweening" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/65/ff/cdae0a8c2118a0de74b6cf4cbcdcaf8fd25857e6c3f205ce4b1794b27814/PyAutoGUI-0.9.54.tar.gz", hash = "sha256:dd1d29e8fd118941cb193f74df57e5c6ff8e9253b99c7b04f39cfc69f3ae04b2", size = 61236 } - [[package]] name = "pycapnp" -version = "2.0.0" +version = "2.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9b/fb/54b46b52c1fa2acd9afd81bd05810c61bb1b05c6084c9625b64bc6d41843/pycapnp-2.0.0.tar.gz", hash = "sha256:503ab9b7b16773590ee226f2460408972c6b1c2cb2d819037115b919bef682be", size = 574848 } +sdist = { url = "https://files.pythonhosted.org/packages/15/86/a57e3c92acd3e1d2fc3dcad683ada191f722e4ac927e1a384b228ec2780a/pycapnp-2.1.0.tar.gz", hash = "sha256:69cc3d861fee1c9b26c73ad2e8a5d51e76ad87e4ff9be33a4fd2fc72f5846aec", size = 689734, upload-time = "2025-09-05T03:50:40.851Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cb/82/cf311b1a9800b605759a38a0c337a55a639b685427364294e98a0f9b7306/pycapnp-2.0.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:829c7eb4e5f23dbcac25466110faf72a691035cf87c5d46e5053da15790e428d", size = 1673673 }, - { url = "https://files.pythonhosted.org/packages/ae/55/4c03ca95c568776a1f637db9ffdcf302fb63f46e4d2a4f13edd8cb1a5f90/pycapnp-2.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dab60fbe3e4eaf99ec97918a0a776216c6c149b6d49261383d91c2201adb475d", size = 1513351 }, - { url = "https://files.pythonhosted.org/packages/55/98/e4b2dea076f8a2575abc45cd879a91bc9aa975c69ae2ac1cab61d83c5087/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c48a0582078bb74d7326d28571db0b8e6919563365537a5a13e8f5360c12bfc", size = 4910666 }, - { url = "https://files.pythonhosted.org/packages/1d/ee/3b5a182588f89074f4002fa6247e3f963bb85bc808acd1ac8deed91f1fa7/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bcb5ab54aff857e3711d2c0cc934194aaffacdeb3481daa56863daef07d27941", size = 5007434 }, - { url = "https://files.pythonhosted.org/packages/c5/e9/515a2ca7fdc84d57c654280d0b71dfd782fd1773d384c0ec0d56dc6fc35b/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9600778036e6fe9dbea68f0c37678c5f4d561d2f2306b3cb741de5e1670ef2ae", size = 5188923 }, - { url = "https://files.pythonhosted.org/packages/70/60/5db346e238985a526ba7589ed24f92195dad39e7dec9d85b17a567600b6f/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7278ba0262fab8c398e77d634ae7ba026866d44b52cbfc27262be8d396ecacd1", size = 5048105 }, - { url = "https://files.pythonhosted.org/packages/e3/ff/02b4a87c9ff9793f26d8f3d95312d902d260c094f216d84e19528a506606/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:23b2458d43c82302980a96518c96df257429204d2cc02bfff0c8cb6ebb371e01", size = 5063172 }, - { url = "https://files.pythonhosted.org/packages/10/a1/35a7e14d765f99cfdcdfdcebc69bdf382f27016944470daa7a03c557f681/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:dd7755cc3fedc2ad8cc7864a0729471ddeff10c184963fe0f3689e295130f1b2", size = 5408718 }, - { url = "https://files.pythonhosted.org/packages/5c/59/8bc8a993c38808c6fd90b10becba8de4a54543e8441bd87ce44ef3b7eee4/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:d47baf6b3db9981625ffc5ff188e089f2ebca8e7e1afb97aa5eb7bebb7bf3650", size = 5596714 }, - { url = "https://files.pythonhosted.org/packages/ea/7d/79c481ef77f29e81355e92bb250f0d2a37a76f5fe0ba9433bf6c6c88b6e4/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:b375be92d93fdb6f7ac127ea9390bcec0fed4e485db137b084f9e7114dde7c83", size = 5709896 }, - { url = "https://files.pythonhosted.org/packages/59/8d/f2eceeea1e8cae8b8a70a4752af5b772916f455e2ed388d0887e2b57d080/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:959bfdf1cddb3e5528e2293c4a375382be9a1bf044b073bc2e7eca1eb6b3a9a2", size = 5594823 }, - { url = "https://files.pythonhosted.org/packages/2c/86/f8284637b61f83232e5618dd561a66080dd98ce2272d7e3ae89335d4fd97/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d873af167cf5cc7578ce5432eefcb442f866c8f7a6c57d188baf8c5e709fa39d", size = 5572564 }, - { url = "https://files.pythonhosted.org/packages/b3/b2/7f99d28a9935d1e37ec6955922c57b2be24fe0b74fe25929643686cc11e5/pycapnp-2.0.0-cp311-cp311-win32.whl", hash = "sha256:40ca8018e0b7686d549b920f087049b92a3e6f06976d9f5a8112603fc560cac4", size = 1040268 }, - { url = "https://files.pythonhosted.org/packages/1d/37/89ab98961f18cffeae20d98cfc24afcfa85024bc014ecc48b0c4ac264fe0/pycapnp-2.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d15cd8e46d541a899c84809095d7d7b3951f43642d1859e7a39bd91910778479", size = 1141758 }, - { url = "https://files.pythonhosted.org/packages/ce/d5/0ee84de3ce34a86c373b6cfbea17d5486c2ca942d51efa99a0069723c1e3/pycapnp-2.0.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:0c111ef96676df25b8afef98f369d45f838ad4434e2898e48199eb43ef704efe", size = 1645816 }, - { url = "https://files.pythonhosted.org/packages/35/1e/580572083165ba791fac5ae2d8917facb94db6e3f0500421673f55165dac/pycapnp-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0d18906eb1fd1b9f206d93a9591ceedce1d52e7766b66e68f271453f104e9dca", size = 1507892 }, - { url = "https://files.pythonhosted.org/packages/d7/ed/46b3cc5d32c525b6a3acb67eb43de2cec692a62775ec1ab66dafe2b7d6ad/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5d1ed365ab1beabb8838068907a7190cc0b6f16de3499d783627e670fcc0eb2", size = 4707960 }, - { url = "https://files.pythonhosted.org/packages/8e/51/0a0a4d4e44138adb84959478ea4966196c5ad32022f768b9b64d1590cb3e/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:495b39a7aa2629931bbca27ad743ce591c6c41e8f81792276be424742d9cd1c1", size = 4791780 }, - { url = "https://files.pythonhosted.org/packages/28/71/2b59c6ddb253b25b3d01ee6f7b32b0297ac205c7272beeb6d13399054430/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:50e814fbde072dcc3d868b5b5cbb9b7a66a70bff9ad03942f3be9baf3ca1cfc6", size = 4961068 }, - { url = "https://files.pythonhosted.org/packages/c3/b8/b64fdefa59d6d2802b5ee0a9439396c23a3e5954da6909be81f2722a234c/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:920fdda62d5fdef7a48339104dff0ceb9dcc21b138491f854457ba3a3d4d63ec", size = 4872917 }, - { url = "https://files.pythonhosted.org/packages/c8/55/867595f575eb6cb3662e9a0b50a24b4be42df86f2938003e586f6c81606f/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3f9142eb4714c152b09dda0b055ea9dd43fd8fd894132e7eb4fa235fb4915edd", size = 4912169 }, - { url = "https://files.pythonhosted.org/packages/e4/11/0d36b45e5005ecdf8510081d16c6fb7b22b49651f64af36d138df97980cc/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:c98f1d0c4d32109d03e42828ce3c65236afc895033633cbed3ca092993702e7b", size = 5201744 }, - { url = "https://files.pythonhosted.org/packages/05/29/ad1357998656b7141939e55bb3aea727c7a5478026feed7f8ee8cf52c935/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:4d3250c1875a309d67551843cd8bf3c5e7fccf159b7f5c118a92aee36c0e871c", size = 5351113 }, - { url = "https://files.pythonhosted.org/packages/5a/b1/f4c442907948a29b6427dd7436f31d3732bb0d77f5c1dbcad749ba56dac0/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:174e6babe01f5507111c0ed226cd0b5e9325a9d2850751cfe4a57c1670f13881", size = 5472055 }, - { url = "https://files.pythonhosted.org/packages/c1/06/a6eceb8b8015f518c0ccae1de5d1a6e18ed73b62b4b111aff54ce5f4f566/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_s390x.whl", hash = "sha256:ed38ece414341285695526792e020f391f29f5064b2126d0367c8bdeef28e3e9", size = 5395743 }, - { url = "https://files.pythonhosted.org/packages/e7/b0/63f2b0327853ae08158de61b4dfc7fa43ae5a5c00f1d28f769e7c30cdf55/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8a20b7dc55ef83a1fa446bf12680bce25caeb8f81788b623b072c3ec820db50d", size = 5405076 }, - { url = "https://files.pythonhosted.org/packages/7d/24/e025dd95f1abf34e373fbab8841ac8e5fa62afe3af4a4b0c61bd01354400/pycapnp-2.0.0-cp312-cp312-win32.whl", hash = "sha256:145eea66233fb5ac9152cd1c06b999ddb691815126f87f5cc37b9cda5d569f8a", size = 1030361 }, - { url = "https://files.pythonhosted.org/packages/3f/70/a71108ee9d4db9a027b665a2c383202407207174f1956195d5be45aca705/pycapnp-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:b8b03000769b29b36a8810f458b931f0f706f42027ee6676821eff28092d7734", size = 1135121 }, + { url = "https://files.pythonhosted.org/packages/74/0e/66b41ba600e5f2523e900b7cc0d2e8496b397a1f2d6a5b7b323ab83418b7/pycapnp-2.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d2ec561bc948d11f64f43bf9601bede5d6a603d105ae311bd5583c7130624a4", size = 1619223, upload-time = "2025-09-05T03:48:54.64Z" }, + { url = "https://files.pythonhosted.org/packages/40/6e/9bcb30180bd40cb0534124ff7f8ba8746a735018d593f608bf40c97821c0/pycapnp-2.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:132cd97f57f6b6636323ca9b68d389dd90b96e87af38cde31e2b5c5a064f277e", size = 1484321, upload-time = "2025-09-05T03:48:55.85Z" }, + { url = "https://files.pythonhosted.org/packages/14/0a/9ee1c9ecaff499e4fd1df2f0335bc20f666ec6ce5cd80f8ab055007f3c9b/pycapnp-2.1.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:568e79268ba7c02a71fe558a8aec1ae3c0f0e6aff809ff618a46afe4964957d2", size = 5143502, upload-time = "2025-09-05T03:48:57.733Z" }, + { url = "https://files.pythonhosted.org/packages/4d/50/65837e1416f7a8861ca1e8fe4582a5aef37192d7ef5e2ecfe46880bfdf9c/pycapnp-2.1.0-cp312-cp312-manylinux_2_28_ppc64le.whl", hash = "sha256:bcbf6f882d78d368c8e4bb792295392f5c4d71ddffa13a48da27e7bd47b99e37", size = 5508134, upload-time = "2025-09-05T03:48:59.383Z" }, + { url = "https://files.pythonhosted.org/packages/a1/59/46df6db800e77dbc3cc940723fb3fd7bc837327c858edf464a0f904bf547/pycapnp-2.1.0-cp312-cp312-manylinux_2_28_s390x.whl", hash = "sha256:dc25b96e393410dde25c61c1df3ce644700ef94826c829426d58c2c6b3e2d2f5", size = 5631794, upload-time = "2025-09-05T03:49:03.511Z" }, + { url = "https://files.pythonhosted.org/packages/63/9d/18e978500d5f6bd8d152f4d6919e3cfb83ead8a71c14613bbb54322df8b9/pycapnp-2.1.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:48938e0436ab1be615fc0a41434119a2065490a6212b9a5e56949e89b0588b76", size = 5369378, upload-time = "2025-09-05T03:49:05.539Z" }, + { url = "https://files.pythonhosted.org/packages/96/dc/726f1917e9996dc29f9fd1cf30674a14546cdbdfa0777e1982b6bd1ad628/pycapnp-2.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0c20de0f6e0b3fa9fa1df3864cf46051db3511b63bc29514d1092af65f2b82a0", size = 5999140, upload-time = "2025-09-05T03:49:07.341Z" }, + { url = "https://files.pythonhosted.org/packages/fd/3a/3bbc4c5776fc32fbf8a59df5c7c5810efd292b933cd6545eb4b16d896268/pycapnp-2.1.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:18caca6527862475167c10ea0809531130585aa8a86cc76cd1629eb87ee30637", size = 6454308, upload-time = "2025-09-05T03:49:08.998Z" }, + { url = "https://files.pythonhosted.org/packages/bf/dd/17e2d7808424f10ffddc47329b980488ed83ec716c504791787e593a7a93/pycapnp-2.1.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9dcc11237697007b66e3bfc500d2ad892bd79672c9b50d61fbf728c6aaf936de", size = 6544212, upload-time = "2025-09-05T03:49:10.675Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/68090013128d7853f34c43828dd4dc80a7c8516fd1b56057b134e1e4c2c0/pycapnp-2.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c151edf78155b6416e7cb31e2e333d302d742ba52bb37d4dbdf71e75cc999d46", size = 6295279, upload-time = "2025-09-05T03:49:12.712Z" }, + { url = "https://files.pythonhosted.org/packages/5b/52/7d85212b4fcf127588888f71d3dbf5558ee7dc302eba760b12b1b325f9a3/pycapnp-2.1.0-cp312-cp312-win32.whl", hash = "sha256:c09b28419321dafafc644d60c57ff8ccaf3c3e686801b6060c612a7a3c580944", size = 1038995, upload-time = "2025-09-05T03:49:14.165Z" }, + { url = "https://files.pythonhosted.org/packages/f2/12/25d283ebf5c28717364647672e7494dc46196ca7a662f5420e4866f45687/pycapnp-2.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:560cb69cc02b0347e85b0629e4c2f0a316240900aa905392f9df6bab0a359989", size = 1176620, upload-time = "2025-09-05T03:49:15.545Z" }, ] [[package]] name = "pycparser" -version = "2.22" +version = "3.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1d/b2/31537cf4b1ca988837256c910a668b553fceb8f069bedc4b1c826024b52c/pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6", size = 172736 } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/13/a3/a812df4e2dd5696d1f351d58b8fe16a405b234ad2886a0dab9183fb78109/pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc", size = 117552 }, + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, ] [[package]] name = "pycryptodome" -version = "3.20.0" +version = "3.23.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b9/ed/19223a0a0186b8a91ebbdd2852865839237a21c74f1fbc4b8d5b62965239/pycryptodome-3.20.0.tar.gz", hash = "sha256:09609209ed7de61c2b560cc5c8c4fbf892f8b15b1faf7e4cbffac97db1fffda7", size = 4794232 } +sdist = { url = "https://files.pythonhosted.org/packages/8e/a6/8452177684d5e906854776276ddd34eca30d1b1e15aa1ee9cefc289a33f5/pycryptodome-3.23.0.tar.gz", hash = "sha256:447700a657182d60338bab09fdb27518f8856aecd80ae4c6bdddb67ff5da44ef", size = 4921276, upload-time = "2025-05-17T17:21:45.242Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ff/96/b0d494defb3346378086848a8ece5ddfd138a66c4a05e038fca873b2518c/pycryptodome-3.20.0-cp35-abi3-macosx_10_9_universal2.whl", hash = "sha256:ac1c7c0624a862f2e53438a15c9259d1655325fc2ec4392e66dc46cdae24d044", size = 2427142 }, - { url = "https://files.pythonhosted.org/packages/24/80/56a04e2ae622d7f38c1c01aef46a26c6b73a2ad15c9705a8e008b5befb03/pycryptodome-3.20.0-cp35-abi3-macosx_10_9_x86_64.whl", hash = "sha256:76658f0d942051d12a9bd08ca1b6b34fd762a8ee4240984f7c06ddfb55eaf15a", size = 1590045 }, - { url = "https://files.pythonhosted.org/packages/ea/94/82ebfa5c83d980907ceebf79b00909a569d258bdfd9b0264d621fa752cfd/pycryptodome-3.20.0-cp35-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f35d6cee81fa145333137009d9c8ba90951d7d77b67c79cbe5f03c7eb74d8fe2", size = 2061748 }, - { url = "https://files.pythonhosted.org/packages/af/20/5f29ec45462360e7f61e8688af9fe4a0afae057edfabdada662e11bf97e7/pycryptodome-3.20.0-cp35-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76cb39afede7055127e35a444c1c041d2e8d2f1f9c121ecef573757ba4cd2c3c", size = 2135687 }, - { url = "https://files.pythonhosted.org/packages/e5/1f/6bc4beb4adc07b847e5d3fddbec4522c2c3aa05df9e61b91dc4eff6a4946/pycryptodome-3.20.0-cp35-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:49a4c4dc60b78ec41d2afa392491d788c2e06edf48580fbfb0dd0f828af49d25", size = 2164262 }, - { url = "https://files.pythonhosted.org/packages/30/4b/cbc67cda0efd55d7ddcc98374c4b9c853022a595ed1d78dd15c961bc7f6e/pycryptodome-3.20.0-cp35-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:fb3b87461fa35afa19c971b0a2b7456a7b1db7b4eba9a8424666104925b78128", size = 2054347 }, - { url = "https://files.pythonhosted.org/packages/0d/08/01987ab75ca789247a88c8b2f0ce374ef7d319e79589e0842e316a272662/pycryptodome-3.20.0-cp35-abi3-musllinux_1_1_i686.whl", hash = "sha256:acc2614e2e5346a4a4eab6e199203034924313626f9620b7b4b38e9ad74b7e0c", size = 2192762 }, - { url = "https://files.pythonhosted.org/packages/b5/bf/798630923b67f4201059c2d690105998f20a6a8fb9b5ab68d221985155b3/pycryptodome-3.20.0-cp35-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:210ba1b647837bfc42dd5a813cdecb5b86193ae11a3f5d972b9a0ae2c7e9e4b4", size = 2155230 }, - { url = "https://files.pythonhosted.org/packages/39/12/5fe7f5b9212dda9f5a26f842a324d6541fe1ca8059602124ff30db1e874b/pycryptodome-3.20.0-cp35-abi3-win32.whl", hash = "sha256:8d6b98d0d83d21fb757a182d52940d028564efe8147baa9ce0f38d057104ae72", size = 1723464 }, - { url = "https://files.pythonhosted.org/packages/1f/90/d131c0eb643290230dfa4108b7c2d135122d88b714ad241d77beb4782a76/pycryptodome-3.20.0-cp35-abi3-win_amd64.whl", hash = "sha256:9b3ae153c89a480a0ec402e23db8d8d84a3833b65fa4b15b81b83be9d637aab9", size = 1759588 }, - { url = "https://files.pythonhosted.org/packages/17/87/c7153fcd400df0f4a67d7d92cdb6b5e43f309c22434374b8a61849dfb280/pycryptodome-3.20.0-pp27-pypy_73-manylinux2010_x86_64.whl", hash = "sha256:4401564ebf37dfde45d096974c7a159b52eeabd9969135f0426907db367a652a", size = 1639310 }, - { url = "https://files.pythonhosted.org/packages/68/9a/88d984405b087e8c8dd9a9d4c81a6fa675454e5fcf2ae01d9553b3128637/pycryptodome-3.20.0-pp27-pypy_73-win32.whl", hash = "sha256:ec1f93feb3bb93380ab0ebf8b859e8e5678c0f010d2d78367cf6bc30bfeb148e", size = 1708332 }, + { url = "https://files.pythonhosted.org/packages/db/6c/a1f71542c969912bb0e106f64f60a56cc1f0fabecf9396f45accbe63fa68/pycryptodome-3.23.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:187058ab80b3281b1de11c2e6842a357a1f71b42cb1e15bce373f3d238135c27", size = 2495627, upload-time = "2025-05-17T17:20:47.139Z" }, + { url = "https://files.pythonhosted.org/packages/6e/4e/a066527e079fc5002390c8acdd3aca431e6ea0a50ffd7201551175b47323/pycryptodome-3.23.0-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:cfb5cd445280c5b0a4e6187a7ce8de5a07b5f3f897f235caa11f1f435f182843", size = 1640362, upload-time = "2025-05-17T17:20:50.392Z" }, + { url = "https://files.pythonhosted.org/packages/50/52/adaf4c8c100a8c49d2bd058e5b551f73dfd8cb89eb4911e25a0c469b6b4e/pycryptodome-3.23.0-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:67bd81fcbe34f43ad9422ee8fd4843c8e7198dd88dd3d40e6de42ee65fbe1490", size = 2182625, upload-time = "2025-05-17T17:20:52.866Z" }, + { url = "https://files.pythonhosted.org/packages/5f/e9/a09476d436d0ff1402ac3867d933c61805ec2326c6ea557aeeac3825604e/pycryptodome-3.23.0-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c8987bd3307a39bc03df5c8e0e3d8be0c4c3518b7f044b0f4c15d1aa78f52575", size = 2268954, upload-time = "2025-05-17T17:20:55.027Z" }, + { url = "https://files.pythonhosted.org/packages/f9/c5/ffe6474e0c551d54cab931918127c46d70cab8f114e0c2b5a3c071c2f484/pycryptodome-3.23.0-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:aa0698f65e5b570426fc31b8162ed4603b0c2841cbb9088e2b01641e3065915b", size = 2308534, upload-time = "2025-05-17T17:20:57.279Z" }, + { url = "https://files.pythonhosted.org/packages/18/28/e199677fc15ecf43010f2463fde4c1a53015d1fe95fb03bca2890836603a/pycryptodome-3.23.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:53ecbafc2b55353edcebd64bf5da94a2a2cdf5090a6915bcca6eca6cc452585a", size = 2181853, upload-time = "2025-05-17T17:20:59.322Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ea/4fdb09f2165ce1365c9eaefef36625583371ee514db58dc9b65d3a255c4c/pycryptodome-3.23.0-cp37-abi3-musllinux_1_2_i686.whl", hash = "sha256:156df9667ad9f2ad26255926524e1c136d6664b741547deb0a86a9acf5ea631f", size = 2342465, upload-time = "2025-05-17T17:21:03.83Z" }, + { url = "https://files.pythonhosted.org/packages/22/82/6edc3fc42fe9284aead511394bac167693fb2b0e0395b28b8bedaa07ef04/pycryptodome-3.23.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:dea827b4d55ee390dc89b2afe5927d4308a8b538ae91d9c6f7a5090f397af1aa", size = 2267414, upload-time = "2025-05-17T17:21:06.72Z" }, + { url = "https://files.pythonhosted.org/packages/59/fe/aae679b64363eb78326c7fdc9d06ec3de18bac68be4b612fc1fe8902693c/pycryptodome-3.23.0-cp37-abi3-win32.whl", hash = "sha256:507dbead45474b62b2bbe318eb1c4c8ee641077532067fec9c1aa82c31f84886", size = 1768484, upload-time = "2025-05-17T17:21:08.535Z" }, + { url = "https://files.pythonhosted.org/packages/54/2f/e97a1b8294db0daaa87012c24a7bb714147c7ade7656973fd6c736b484ff/pycryptodome-3.23.0-cp37-abi3-win_amd64.whl", hash = "sha256:c75b52aacc6c0c260f204cbdd834f76edc9fb0d8e0da9fbf8352ef58202564e2", size = 1799636, upload-time = "2025-05-17T17:21:10.393Z" }, + { url = "https://files.pythonhosted.org/packages/18/3d/f9441a0d798bf2b1e645adc3265e55706aead1255ccdad3856dbdcffec14/pycryptodome-3.23.0-cp37-abi3-win_arm64.whl", hash = "sha256:11eeeb6917903876f134b56ba11abe95c0b0fd5e3330def218083c7d98bbcb3c", size = 1703675, upload-time = "2025-05-17T17:21:13.146Z" }, ] [[package]] name = "pyee" -version = "12.0.0" +version = "13.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d2/a7/8faaa62a488a2a1e0d56969757f087cbd2729e9bcfa508c230299f366b4c/pyee-12.0.0.tar.gz", hash = "sha256:c480603f4aa2927d4766eb41fa82793fe60a82cbfdb8d688e0d08c55a534e145", size = 29675 } +sdist = { url = "https://files.pythonhosted.org/packages/8b/04/e7c1fe4dc78a6fdbfd6c337b1c3732ff543b8a397683ab38378447baa331/pyee-13.0.1.tar.gz", hash = "sha256:0b931f7c14535667ed4c7e0d531716368715e860b988770fc7eb8578d1f67fc8", size = 31655, upload-time = "2026-02-14T21:12:28.044Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/0d/95993c08c721ec68892547f2117e8f9dfbcef2ca71e098533541b4a54d5f/pyee-12.0.0-py3-none-any.whl", hash = "sha256:7b14b74320600049ccc7d0e0b1becd3b4bd0a03c745758225e31a59f4095c990", size = 14831 }, -] - -[[package]] -name = "pygetwindow" -version = "0.0.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyrect" }, + { url = "https://files.pythonhosted.org/packages/a0/c4/b4d4827c93ef43c01f599ef31453ccc1c132b353284fc6c87d535c233129/pyee-13.0.1-py3-none-any.whl", hash = "sha256:af2f8fede4171ef667dfded53f96e2ed0d6e6bd7ee3bb46437f77e3b57689228", size = 15659, upload-time = "2026-02-14T21:12:26.263Z" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e1/70/c7a4f46dbf06048c6d57d9489b8e0f9c4c3d36b7479f03c5ca97eaa2541d/PyGetWindow-0.0.9.tar.gz", hash = "sha256:17894355e7d2b305cd832d717708384017c1698a90ce24f6f7fbf0242dd0a688", size = 9699 } [[package]] name = "pygments" -version = "2.18.0" +version = "2.20.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/8e/62/8336eff65bcbc8e4cb5d05b55faf041285951b6e80f33e2bff2024788f31/pygments-2.18.0.tar.gz", hash = "sha256:786ff802f32e91311bff3889f6e9a86e81505fe99f2735bb6d60ae0c5004f199", size = 4891905 } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f7/3f/01c8b82017c199075f8f788d0d906b9ffbbc5a47dc9918a945e13d5a2bda/pygments-2.18.0-py3-none-any.whl", hash = "sha256:b8e6aca0523f3ab76fee51799c488e38782ac06eafcf95e7ba832985c8e7b13a", size = 1205513 }, + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, ] [[package]] name = "pyjwt" -version = "2.9.0" +version = "2.13.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fb/68/ce067f09fca4abeca8771fe667d89cc347d1e99da3e093112ac329c6020e/pyjwt-2.9.0.tar.gz", hash = "sha256:7e1e5b56cc735432a7369cbfa0efe50fa113ebecdc04ae6922deba8b84582d0c", size = 78825 } +sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/79/84/0fdf9b18ba31d69877bd39c9cd6052b47f3761e9910c15de788e519f079f/PyJWT-2.9.0-py3-none-any.whl", hash = "sha256:3b02fb0f44517787776cf48f2ae25d8e14f300e6d7545a4315cee571a415e850", size = 22344 }, -] - -[package.optional-dependencies] -crypto = [ - { name = "cryptography" }, + { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" }, ] [[package]] name = "pylibsrtp" -version = "0.10.0" +version = "1.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cffi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/6b/ae/c95199144eed954976223bdce3f94564eb6c43567111aff8048a26a429bd/pylibsrtp-0.10.0.tar.gz", hash = "sha256:d8001912d7f51bd05b4ea3551747930631777fd37892cf3bfe0e541a742e699f", size = 10557 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1c/d2/ffc24f80e83a54d9b309cdae6b31cf9294b4f3a85ab107827fd272d1e687/pylibsrtp-0.10.0-cp38-abi3-macosx_10_9_x86_64.whl", hash = "sha256:6a1121ceea3339e0a84842a4a9da0fcf57cc8f99eb60dbf31a46d978b4170e7c", size = 1704188 }, - { url = "https://files.pythonhosted.org/packages/66/3e/db86a09a5cb290a274f76ce25f4fae3a7e3c4a4dbc64baf7e2aaa57a32bb/pylibsrtp-0.10.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:ca1994e73c6857b0a695fdde94cc5ac846c1b0d5d8766255a1dc2db40857f667", size = 2028580 }, - { url = "https://files.pythonhosted.org/packages/21/ab/9b2b5ad2ceaa1660de16e0a2e3c54a2043a9c4a3eef7718930c78dc84e77/pylibsrtp-0.10.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bb7640b524544603d07bd4373b04c9582c8cfe41d9789d3f492081f053bed9c1", size = 2484470 }, - { url = "https://files.pythonhosted.org/packages/ab/e6/b0a30e79aa2312834b33f5e9c0ad459fc94e195c610634ee9665fafb1fc8/pylibsrtp-0.10.0-cp38-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f13aa945e1dcf8c138bf3d4a6e34056c4c2f69bf9934bc53b320ef14c7317ccc", size = 2078367 }, - { url = "https://files.pythonhosted.org/packages/16/78/9ea0c88490ad4fe9683ddf3bbee702c7a2331e83a333bb3aa52e8d7d909b/pylibsrtp-0.10.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1b2ef1c32d1145239dd0fe7b7fbe083334d345df6b4597fc66faf914a32682d9", size = 2134898 }, - { url = "https://files.pythonhosted.org/packages/00/f6/c76fa5401f9d95c14db70de0cf4fad922ad61686843bc3e7411178a64bc8/pylibsrtp-0.10.0-cp38-abi3-win32.whl", hash = "sha256:8c6fe2576b2ab13942b47db6c2ffe71f5eb1edc1dc3bdd7283169fecd5249e74", size = 1130881 }, - { url = "https://files.pythonhosted.org/packages/4c/31/85a58625edc0b6967fe0904c9d89d019bcece3f3e3bf775b9151a8cf9d0d/pylibsrtp-0.10.0-cp38-abi3-win_amd64.whl", hash = "sha256:cd965d4b0e9a77b362526cab119f4d9ce39b83f1f20f46c6af8e694b86fa19a7", size = 1448840 }, -] - -[[package]] -name = "pymonctl" -version = "0.92" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ewmhlib", marker = "sys_platform == 'linux'" }, - { name = "pyobjc", marker = "sys_platform == 'darwin'" }, - { name = "python-xlib", marker = "sys_platform == 'linux'" }, - { name = "pywin32", marker = "sys_platform == 'win32'" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/2d/13/076a20da28b82be281f7e43e16d9da0f545090f5d14b2125699232b9feba/PyMonCtl-0.92-py3-none-any.whl", hash = "sha256:2495d8dab78f9a7dbce37e74543e60b8bd404a35c3108935697dda7768611b5a", size = 45945 }, -] - -[[package]] -name = "pymsgbox" -version = "1.0.9" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7d/ff/4c6f31a4f08979f12a663f2aeb6c8b765d3bd592e66eaaac445f547bb875/PyMsgBox-1.0.9.tar.gz", hash = "sha256:2194227de8bff7a3d6da541848705a155dcbb2a06ee120d9f280a1d7f51263ff", size = 18829 } - -[[package]] -name = "pyobjc" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-accessibility", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-accounts", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-addressbook" }, - { name = "pyobjc-framework-adservices", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-adsupport", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-applescriptkit" }, - { name = "pyobjc-framework-applescriptobjc", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-applicationservices" }, - { name = "pyobjc-framework-apptrackingtransparency", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-audiovideobridging", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-authenticationservices", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-automaticassessmentconfiguration", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-automator" }, - { name = "pyobjc-framework-avfoundation", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-avkit", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-avrouting", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-backgroundassets", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-browserenginekit", marker = "platform_release >= '23.4'" }, - { name = "pyobjc-framework-businesschat", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-calendarstore", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-callkit", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-cfnetwork" }, - { name = "pyobjc-framework-cinematic", marker = "platform_release >= '23.0'" }, - { name = "pyobjc-framework-classkit", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-cloudkit", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-collaboration", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-colorsync", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-contacts", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-contactsui", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-coreaudio" }, - { name = "pyobjc-framework-coreaudiokit" }, - { name = "pyobjc-framework-corebluetooth", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-coredata" }, - { name = "pyobjc-framework-corehaptics", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-corelocation", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-coremedia", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-coremediaio", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-coremidi" }, - { name = "pyobjc-framework-coreml", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-coremotion", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-coreservices" }, - { name = "pyobjc-framework-corespotlight", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-coretext" }, - { name = "pyobjc-framework-corewlan", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-cryptotokenkit", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-datadetection", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-devicecheck", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-dictionaryservices", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-discrecording" }, - { name = "pyobjc-framework-discrecordingui" }, - { name = "pyobjc-framework-diskarbitration" }, - { name = "pyobjc-framework-dvdplayback" }, - { name = "pyobjc-framework-eventkit", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-exceptionhandling" }, - { name = "pyobjc-framework-executionpolicy", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-extensionkit", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-externalaccessory", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-fileprovider", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-fileproviderui", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-findersync", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-fsevents", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-gamecenter", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-gamecontroller", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-gamekit", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-gameplaykit", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-healthkit", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-imagecapturecore", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-inputmethodkit", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-installerplugins" }, - { name = "pyobjc-framework-instantmessage", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-intents", marker = "platform_release >= '16.0'" }, - { name = "pyobjc-framework-intentsui", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-iobluetooth" }, - { name = "pyobjc-framework-iobluetoothui" }, - { name = "pyobjc-framework-iosurface", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-ituneslibrary", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-kernelmanagement", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-latentsemanticmapping" }, - { name = "pyobjc-framework-launchservices" }, - { name = "pyobjc-framework-libdispatch", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-libxpc", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-linkpresentation", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-localauthentication", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-localauthenticationembeddedui", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-mailkit", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-mapkit", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-mediaaccessibility", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-medialibrary", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-mediaplayer", marker = "platform_release >= '16.0'" }, - { name = "pyobjc-framework-mediatoolbox", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-metal", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-metalfx", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-metalkit", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-metalperformanceshaders", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-metalperformanceshadersgraph", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-metrickit", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-mlcompute", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-modelio", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-multipeerconnectivity", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-naturallanguage", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-netfs", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-network", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-networkextension", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-notificationcenter", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-opendirectory", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-osakit" }, - { name = "pyobjc-framework-oslog", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-passkit", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-pencilkit", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-phase", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-photos", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-photosui", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-preferencepanes" }, - { name = "pyobjc-framework-pushkit", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-quartz" }, - { name = "pyobjc-framework-quicklookthumbnailing", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-replaykit", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-safariservices", marker = "platform_release >= '16.0'" }, - { name = "pyobjc-framework-safetykit", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-scenekit", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-screencapturekit", marker = "platform_release >= '21.4'" }, - { name = "pyobjc-framework-screensaver" }, - { name = "pyobjc-framework-screentime", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-scriptingbridge", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-searchkit" }, - { name = "pyobjc-framework-security" }, - { name = "pyobjc-framework-securityfoundation" }, - { name = "pyobjc-framework-securityinterface" }, - { name = "pyobjc-framework-sensitivecontentanalysis", marker = "platform_release >= '23.0'" }, - { name = "pyobjc-framework-servicemanagement", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-sharedwithyou", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-sharedwithyoucore", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-shazamkit", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-social", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-soundanalysis", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-speech", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-spritekit", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-storekit", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-symbols", marker = "platform_release >= '23.0'" }, - { name = "pyobjc-framework-syncservices" }, - { name = "pyobjc-framework-systemconfiguration" }, - { name = "pyobjc-framework-systemextensions", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-threadnetwork", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-uniformtypeidentifiers", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-usernotifications", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-usernotificationsui", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-videosubscriberaccount", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-videotoolbox", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-virtualization", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-vision", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-webkit" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e0/20/722e33f62631370c1475d773cadf4290d3c6f3a0e9d025fa6e2528270eaa/pyobjc-10.3.1.tar.gz", hash = "sha256:476dd5c72394e4cfcdac6dfd756839011a0159353247f45e3e07cc0b3536c9d4", size = 10975 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cb/a5/4b9ed66894d804dc57c13b7fdb8f65ed831f13514216ce736e1455dfe214/pyobjc-10.3.1-py3-none-any.whl", hash = "sha256:dfa9ff44a353b9d0bf1245c25c94d1eee6d0cb26d9c5433bbcd67a265f7654ae", size = 4050 }, -] - -[[package]] -name = "pyobjc-core" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b7/40/a38d78627bd882d86c447db5a195ff307001ae02c1892962c656f2fd6b83/pyobjc_core-10.3.1.tar.gz", hash = "sha256:b204a80ccc070f9ab3f8af423a3a25a6fd787e228508d00c4c30f8ac538ba720", size = 935027 } +sdist = { url = "https://files.pythonhosted.org/packages/0d/a6/6e532bec974aaecbf9fe4e12538489fb1c28456e65088a50f305aeab9f89/pylibsrtp-1.0.0.tar.gz", hash = "sha256:b39dff075b263a8ded5377f2490c60d2af452c9f06c4d061c7a2b640612b34d4", size = 10858, upload-time = "2025-10-13T16:12:31.552Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ba/69/e782f176bb5ac71473563f4e5cf825c48b1d7d1fbe1fadde201027804e45/pyobjc_core-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:899d3c84d2933d292c808f385dc881a140cf08632907845043a333a9d7c899f9", size = 775224 }, - { url = "https://files.pythonhosted.org/packages/cd/4d/d5d552b209fbca644cf9e0115a4cef8bc5f6726a44303eb7ae8d8a920a9e/pyobjc_core-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:6ff5823d13d0a534cdc17fa4ad47cf5bee4846ce0fd27fc40012e12b46db571b", size = 825968 }, - { url = "https://files.pythonhosted.org/packages/2e/8b/341571ac5d625968083cbd718e1af7eac54197ed3d404dfff9467c3a8c88/pyobjc_core-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:2581e8e68885bcb0e11ec619e81ef28e08ee3fac4de20d8cc83bc5af5bcf4a90", size = 827410 }, + { url = "https://files.pythonhosted.org/packages/aa/af/89e61a62fa3567f1b7883feb4d19e19564066c2fcd41c37e08d317b51881/pylibsrtp-1.0.0-cp310-abi3-macosx_10_9_x86_64.whl", hash = "sha256:822c30ea9e759b333dc1f56ceac778707c51546e97eb874de98d7d378c000122", size = 1865017, upload-time = "2025-10-13T16:12:15.62Z" }, + { url = "https://files.pythonhosted.org/packages/8d/0e/8d215484a9877adcf2459a8b28165fc89668b034565277fd55d666edd247/pylibsrtp-1.0.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:aaad74e5c8cbc1c32056c3767fea494c1e62b3aea2c908eda2a1051389fdad76", size = 2182739, upload-time = "2025-10-13T16:12:17.121Z" }, + { url = "https://files.pythonhosted.org/packages/57/3f/76a841978877ae13eac0d4af412c13bbd5d83b3df2c1f5f2175f2e0f68e5/pylibsrtp-1.0.0-cp310-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9209b86e662ebbd17c8a9e8549ba57eca92a3e87fb5ba8c0e27b8c43cd08a767", size = 2732922, upload-time = "2025-10-13T16:12:18.348Z" }, + { url = "https://files.pythonhosted.org/packages/0e/14/cf5d2a98a66fdfe258f6b036cda570f704a644fa861d7883a34bc359501e/pylibsrtp-1.0.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:293c9f2ac21a2bd689c477603a1aa235d85cf252160e6715f0101e42a43cbedc", size = 2434534, upload-time = "2025-10-13T16:12:20.074Z" }, + { url = "https://files.pythonhosted.org/packages/bd/08/a3f6e86c04562f7dce6717cd2206a0f84ca85c5e38121d998e0e330194c3/pylibsrtp-1.0.0-cp310-abi3-manylinux_2_28_i686.whl", hash = "sha256:81fb8879c2e522021a7cbd3f4bda1b37c192e1af939dfda3ff95b4723b329663", size = 2345818, upload-time = "2025-10-13T16:12:21.439Z" }, + { url = "https://files.pythonhosted.org/packages/8e/d5/130c2b5b4b51df5631684069c6f0a6761c59d096a33d21503ac207cf0e47/pylibsrtp-1.0.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:4ddb562e443cf2e557ea2dfaeef0d7e6b90e96dd38eb079b4ab2c8e34a79f50b", size = 2774490, upload-time = "2025-10-13T16:12:22.659Z" }, + { url = "https://files.pythonhosted.org/packages/91/e3/715a453bfee3bea92a243888ad359094a7727cc6d393f21281320fe7798c/pylibsrtp-1.0.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:f02e616c9dfab2b03b32d8cc7b748f9d91814c0211086f987629a60f05f6e2cc", size = 2372603, upload-time = "2025-10-13T16:12:24.036Z" }, + { url = "https://files.pythonhosted.org/packages/e3/56/52fa74294254e1f53a4ff170ee2006e57886cf4bb3db46a02b4f09e1d99f/pylibsrtp-1.0.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:c134fa09e7b80a5b7fed626230c5bc257fd771bd6978e754343e7a61d96bc7e6", size = 2451269, upload-time = "2025-10-13T16:12:25.475Z" }, + { url = "https://files.pythonhosted.org/packages/1e/51/2e9b34f484cbdd3bac999bf1f48b696d7389433e900639089e8fc4e0da0d/pylibsrtp-1.0.0-cp310-abi3-win32.whl", hash = "sha256:bae377c3b402b17b9bbfbfe2534c2edba17aa13bea4c64ce440caacbe0858b55", size = 1247503, upload-time = "2025-10-13T16:12:27.39Z" }, + { url = "https://files.pythonhosted.org/packages/c3/70/43db21af194580aba2d9a6d4c7bd8c1a6e887fa52cd810b88f89096ecad2/pylibsrtp-1.0.0-cp310-abi3-win_amd64.whl", hash = "sha256:8d6527c4a78a39a8d397f8862a8b7cdad4701ee866faf9de4ab8c70be61fd34d", size = 1601659, upload-time = "2025-10-13T16:12:29.037Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ec/6e02b2561d056ea5b33046e3cad21238e6a9097b97d6ccc0fbe52b50c858/pylibsrtp-1.0.0-cp310-abi3-win_arm64.whl", hash = "sha256:2696bdb2180d53ac55d0eb7b58048a2aa30cd4836dd2ca683669889137a94d2a", size = 1159246, upload-time = "2025-10-13T16:12:30.285Z" }, ] [[package]] -name = "pyobjc-framework-accessibility" -version = "10.3.1" +name = "pymdown-extensions" +version = "10.21.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, + { name = "markdown" }, + { name = "pyyaml" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/24/20/18a45998ae8bf9ce532a29f8eaebdaa7f15a7f77b3c34a8304714b393166/pyobjc_framework_accessibility-10.3.1.tar.gz", hash = "sha256:c973306417441e6bed5f9be6154e6399aa7f38fa9b6bcf3368fa42d92ef3030b", size = 29349 } +sdist = { url = "https://files.pythonhosted.org/packages/9e/26/d1015444da4d952a1ca487a236b522eb979766f0295a0bd0c5fc089989a9/pymdown_extensions-10.21.3.tar.gz", hash = "sha256:72cfcf55f07aea0d4af2c4f11dd4e52466ddfb1bb819673146398e0bd3a77354", size = 854140, upload-time = "2026-05-13T12:57:32.267Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1f/be/f20998cbba98386a47784ea9b7738c6b6d106f1dd30a7f99387e7ee5bb53/pyobjc_framework_Accessibility-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:4a1b10d2098b5e3887d4e52b13c2d7619f248ceeaa4e78bb21c51c25c7d391c3", size = 10723 }, - { url = "https://files.pythonhosted.org/packages/50/36/6afe05e0ebf8b194d7d26730fa39b09279e7f819945c909875cbc7435b6d/pyobjc_framework_Accessibility-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:4926eeef40d750215f0787d2124407a4c65bc03407e402ea47901b713e8765e5", size = 10781 }, - { url = "https://files.pythonhosted.org/packages/ad/61/46d9bd68309ec9e1659ce14fe6c46e0754112d8fc8e1fc49797ae6bb8f6e/pyobjc_framework_Accessibility-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b5b9d7373d1a8a06f57baca2f67279c3b0c61ecfb17fa6da964e0e275e7d18ed", size = 7489 }, - { url = "https://files.pythonhosted.org/packages/ec/5d/0ffe3abc230e694e0a8aaf8f9a8c4f4f3b7f98787d53be5a5eba979654ad/pyobjc_framework_Accessibility-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:94dbc5f223e6485820c14e7dee99d8f4d5cbf0600353033822dcab7ec4bc998e", size = 10653 }, + { url = "https://files.pythonhosted.org/packages/7e/85/545a951eecc270fcd688288c600017e2050a1aacb56c711d208586d3e470/pymdown_extensions-10.21.3-py3-none-any.whl", hash = "sha256:d7a5d08014fc571e80ca21dd6f854e31f94c489800350564d55d15b3c41e76b6", size = 269002, upload-time = "2026-05-13T12:57:30.296Z" }, ] [[package]] -name = "pyobjc-framework-accounts" -version = "10.3.1" +name = "pyopenssl" +version = "26.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "cryptography" }, + { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/cf/be/a4e4eeebfa140f0e00fe2fb882802cc4a5fa7f12c7fea01e35314fcf276c/pyobjc_framework_accounts-10.3.1.tar.gz", hash = "sha256:3d55738e7b3290af8cd4993fd2b670242a952deb995a69911be2a1be4c509a86", size = 16180 } +sdist = { url = "https://files.pythonhosted.org/packages/1a/51/27a5ad5f939d08f690a326ef9582cda7140555180db71695f6fb747d6a36/pyopenssl-26.2.0.tar.gz", hash = "sha256:8c6fcecd1183a7fc897548dfe388b0cdb7f37e018200d8409cf33959dbe35387", size = 182195, upload-time = "2026-05-04T23:06:09.72Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/27/8c/23a9128a0252d6ef7643edd5c90d18699fb7a8ae9849e47806408d3d15d2/pyobjc_framework_Accounts-10.3.1-py2.py3-none-any.whl", hash = "sha256:451488f91263afd23233287f223ba00c0ee5c93d64cd10e133d72bc6a0fc48aa", size = 4727 }, + { url = "https://files.pythonhosted.org/packages/73/b8/a0e2790ae249d6f38c9f66de7a211621a7ab2650217bcd04e1262f578a56/pyopenssl-26.2.0-py3-none-any.whl", hash = "sha256:4f9d971bc5298b8bc1fab282803da04bf000c755d4ad9d99b52de2569ca19a70", size = 55823, upload-time = "2026-05-04T23:06:08.395Z" }, ] [[package]] -name = "pyobjc-framework-addressbook" -version = "10.3.1" +name = "pyparsing" +version = "3.3.2" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/21/0a/68769f71cbf9f46070059def94a5c7b0b218626652d7aa589e15f4e8b876/pyobjc_framework_addressbook-10.3.1.tar.gz", hash = "sha256:cde99b855c39b56ca52479b0a1e2daa3ef5de12cebfe780c3c802a5f59a484cc", size = 84696 } +sdist = { url = "https://files.pythonhosted.org/packages/f3/91/9c6ee907786a473bf81c5f53cf703ba0957b23ab84c264080fb5a450416f/pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc", size = 6851574, upload-time = "2026-01-21T03:57:59.36Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1b/11/7843baf1041c7c42e272178eb0f1f6b19bd1460e59a4515741b8e553375d/pyobjc_framework_AddressBook-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:02ab8cb2300d55beaddee4f113a5c4a78ef737eda6c704678487529e391062e2", size = 13244 }, - { url = "https://files.pythonhosted.org/packages/e3/29/d1ccc5aaf041d68f35f64df1ba0acd5c3d8b13f3deaf4b3ac94b8f67e792/pyobjc_framework_AddressBook-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:1cfa893c21920f5420f3e57da314315e92c855a83f0718482dc33bdb859b9f24", size = 13302 }, - { url = "https://files.pythonhosted.org/packages/37/bc/36f19b723404bfa739aa59c4df15a42387ed8c5c55ea168fbe74b0de0771/pyobjc_framework_AddressBook-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:7aa89a352f1729de1cb4d7841906487d9db752c2802af5695596b1cf5290acfb", size = 10829 }, - { url = "https://files.pythonhosted.org/packages/c0/b2/730fe2665b385fe5ad59fee25d562ed182f3369885d467aafcb369fb9c63/pyobjc_framework_AddressBook-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:f25864847b4a81289dd08e7052455699ee011a4df98f4da0b07f46523c212592", size = 13610 }, + { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" }, ] [[package]] -name = "pyobjc-framework-adservices" -version = "10.3.1" +name = "pyserial" +version = "3.5" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ab/9b/eaeb7c8f30899979113b91d8317efd30743d335bdaaa8fb88434e7bf7616/pyobjc_framework_adservices-10.3.1.tar.gz", hash = "sha256:28123eb111d023f708e1d86f5f3f76bd4f6bb0d932466863f84b3e322b11537a", size = 11838 } +sdist = { url = "https://files.pythonhosted.org/packages/1e/7d/ae3f0a63f41e4d2f6cb66a5b57197850f919f59e558159a4dd3a818f5082/pyserial-3.5.tar.gz", hash = "sha256:3c77e014170dfffbd816e6ffc205e9842efb10be9f58ec16d3e8675b4925cddb", size = 159125, upload-time = "2020-11-23T03:59:15.045Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c7/85/bfd64830a47b363ae31e2366ec68da065c35abd9fc08adaa4cd6daa48d42/pyobjc_framework_AdServices-10.3.1-py2.py3-none-any.whl", hash = "sha256:c839c4267ad8443393e4d138396026764ee43776164da8a8ed9ac248b7d9c0d9", size = 3105 }, + { url = "https://files.pythonhosted.org/packages/07/bc/587a445451b253b285629263eb51c2d8e9bcea4fc97826266d186f96f558/pyserial-3.5-py2.py3-none-any.whl", hash = "sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0", size = 90585, upload-time = "2020-11-23T03:59:13.41Z" }, ] [[package]] -name = "pyobjc-framework-adsupport" -version = "10.3.1" +name = "pytest" +version = "9.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/87/cf/9b40ef87f1315858e3dce9f807b359e43a6183616a6a8d2caab533d49a3e/pyobjc_framework_adsupport-10.3.1.tar.gz", hash = "sha256:ba85a00cf20c42501d8083092f7ca0fcd1e616b1725e6512e75bcb60a6d58528", size = 11991 } +sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/549bd94f1a0a402dc8cf64563a117c0f3765662e2e668477624baeec44d5/pytest-9.0.3.tar.gz", hash = "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c", size = 1572165, upload-time = "2026-04-07T17:16:18.027Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/20/3e/3d43c0a398390c358a777fec7ccf9cf94523cc41618a59fcf72dc2172990/pyobjc_framework_AdSupport-10.3.1-py2.py3-none-any.whl", hash = "sha256:0e403ec206ada472b2c0b129ed656342a97c20110ca8398ab907100516b0e48c", size = 3018 }, + { url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" }, ] [[package]] -name = "pyobjc-framework-applescriptkit" -version = "10.3.1" +name = "pytest-cpp" +version = "2.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "pytest" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/5c/c4/42e37476f31dddecb3d7b83b076d5e94b754837e2326b0218227b20f96ec/pyobjc_framework_applescriptkit-10.3.1.tar.gz", hash = "sha256:add2e63598b699666bcf00ac59f6f1046266df1665bec71b142cd21b89037064", size = 11779 } +sdist = { url = "https://files.pythonhosted.org/packages/cf/a1/c2679d7ff2da20a0f89c7820ae2739cde739eac9b43c192531117b31b5f4/pytest_cpp-2.6.0.tar.gz", hash = "sha256:c2f49d3c038539ac84786a94d852e4f4619c34c95979c2bc69c20b3bdf051d85", size = 465490, upload-time = "2024-09-18T00:08:08.251Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0c/0b/6638a036e5e4b8451d9c5e96da5ec1bfcf4bee68b09b2e28158445d767e4/pyobjc_framework_AppleScriptKit-10.3.1-py2.py3-none-any.whl", hash = "sha256:97ce878ff334b6853405a62e164debb9e6695110e64db5ed596008c0fde84970", size = 3930 }, + { url = "https://files.pythonhosted.org/packages/2a/44/dc2f5d53165264ae5831f361fe7723c45da05718a97015b2eddc452cf503/pytest_cpp-2.6.0-py3-none-any.whl", hash = "sha256:b33de94609450feea2fba9efff3558b8ac8f1fdf40a99e263b395d4798b911bb", size = 15074, upload-time = "2024-09-18T00:08:06.415Z" }, ] [[package]] -name = "pyobjc-framework-applescriptobjc" -version = "10.3.1" +name = "pytest-mock" +version = "3.15.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "pytest" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/80/9e/db9d93764db336ed53da548cd7b52b6fbd7d493101b801b164f5c1f5fce8/pyobjc_framework_applescriptobjc-10.3.1.tar.gz", hash = "sha256:a87101d86b08e06e2c0e51630ac76d4c70f01cf1ed7af281f3138e63146e279b", size = 11797 } +sdist = { url = "https://files.pythonhosted.org/packages/68/14/eb014d26be205d38ad5ad20d9a80f7d201472e08167f0bb4361e251084a9/pytest_mock-3.15.1.tar.gz", hash = "sha256:1849a238f6f396da19762269de72cb1814ab44416fa73a8686deac10b0d87a0f", size = 34036, upload-time = "2025-09-16T16:37:27.081Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/94/1f/700ba04ece5f7c654cd58617a26427a0337e21003f1efd38132af48e0427/pyobjc_framework_AppleScriptObjC-10.3.1-py2.py3-none-any.whl", hash = "sha256:2d64c74a4af48656bb407eb177fe5f1d3c0f7bd9c578e5583dffde8e3d55f5df", size = 4027 }, + { url = "https://files.pythonhosted.org/packages/5a/cc/06253936f4a7fa2e0f48dfe6d851d9c56df896a9ab09ac019d70b760619c/pytest_mock-3.15.1-py3-none-any.whl", hash = "sha256:0a25e2eb88fe5168d535041d09a4529a188176ae608a6d249ee65abc0949630d", size = 10095, upload-time = "2025-09-16T16:37:25.734Z" }, ] [[package]] -name = "pyobjc-framework-applicationservices" -version = "10.3.1" +name = "pytest-subtests" +version = "0.15.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coretext" }, - { name = "pyobjc-framework-quartz" }, + { name = "attrs" }, + { name = "pytest" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/66/a6/3704b63c6e844739e3b7e324d1268fb6f7cb485550267719660779266c60/pyobjc_framework_applicationservices-10.3.1.tar.gz", hash = "sha256:f27cb64aa4d129ce671fd42638c985eb2a56d544214a95fe3214a007eacc4790", size = 182738 } +sdist = { url = "https://files.pythonhosted.org/packages/bb/d9/20097971a8d315e011e055d512fa120fd6be3bdb8f4b3aa3e3c6bf77bebc/pytest_subtests-0.15.0.tar.gz", hash = "sha256:cb495bde05551b784b8f0b8adfaa27edb4131469a27c339b80fd8d6ba33f887c", size = 18525, upload-time = "2025-10-20T16:26:18.358Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/78/24/31fdd15f88d3a0a88ba88b27d1f134c7819221886bf56644af12fe672c6d/pyobjc_framework_ApplicationServices-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d886ba1f65df47b77ff7546f3fc9bc7d08cfb6b3c04433b719f6b0689a2c0d1f", size = 31029 }, - { url = "https://files.pythonhosted.org/packages/af/01/bf2d335e3f176227a142f466419a9400dd752e7f02f03674a276f39c1d78/pyobjc_framework_ApplicationServices-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:be157f2c3ffb254064ef38249670af8cada5e519a714d2aa5da3740934d89bc8", size = 31072 }, - { url = "https://files.pythonhosted.org/packages/a5/44/44821633fb0a94e5072997eb56496a72c071ed22a1c93e53915b5a14dbb5/pyobjc_framework_ApplicationServices-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:57737f41731661e4a3b78793ec9173f61242a32fa560c3e4e58484465d049c32", size = 30950 }, + { url = "https://files.pythonhosted.org/packages/23/64/bba465299b37448b4c1b84c7a04178399ac22d47b3dc5db1874fe55a2bd3/pytest_subtests-0.15.0-py3-none-any.whl", hash = "sha256:da2d0ce348e1f8d831d5a40d81e3aeac439fec50bd5251cbb7791402696a9493", size = 9185, upload-time = "2025-10-20T16:26:17.239Z" }, ] [[package]] -name = "pyobjc-framework-apptrackingtransparency" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } +name = "pytest-xdist" +version = "3.7.1.dev24+g2b4372bd6" +source = { git = "https://github.com/sshane/pytest-xdist?rev=2b4372bd62699fb412c4fe2f95bf9f01bd2018da#2b4372bd62699fb412c4fe2f95bf9f01bd2018da" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/75/63/b7039473d92211938645c44069b2e8bc65eefc229a3aac1ff8ccf0f13415/pyobjc_framework_apptrackingtransparency-10.3.1.tar.gz", hash = "sha256:2e381db5f7d3985207b5ff2975e41bf0f9147080345b2e1b4b242f8799290d04", size = 12547 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f2/ab/7be81bd560ea539f5fa39c81c55af759d69a667ad9bb81efb2094e8a7b1c/pyobjc_framework_AppTrackingTransparency-10.3.1-py2.py3-none-any.whl", hash = "sha256:7c0e3a5cad402e8c3c5da1f070be0f49bb827e6d9e5165744f64e082633a4b45", size = 3459 }, + { name = "execnet" }, + { name = "pytest" }, ] [[package]] -name = "pyobjc-framework-audiovideobridging" -version = "10.3.1" +name = "python-dateutil" +version = "2.9.0.post0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "six" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f9/f8/437666f24f295986ad9ea77a694f7db98889a8367fad46d93b84ae028e28/pyobjc_framework_audiovideobridging-10.3.1.tar.gz", hash = "sha256:b2c1d5977a92915f6af2203e3b4c9b8a8392bc51e0fc13ccb393589419387119", size = 59209 } +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/82/ec/da418b96f03e5dd7d0bf0974843292756d89dd9e2604384e5da802332ffd/pyobjc_framework_AudioVideoBridging-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4f6067b2f50fb48c9ecb521b8865d93dfbd46510a4322cc2041b1e917678f39b", size = 11124 }, - { url = "https://files.pythonhosted.org/packages/2f/5b/f03579fb2c77b72981beab1cbb58d9f02ea6a7d0309a9fb4e859a6ede73b/pyobjc_framework_AudioVideoBridging-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:1aebc6c1aafb3cdfc5f9fad2dfe2dfccfbab159dc8dbfe54cfea777108e80e44", size = 11152 }, - { url = "https://files.pythonhosted.org/packages/a7/3f/cd2f1187295ba9824129823911bdbd984bb49d9c86336c08d77a8f19bccb/pyobjc_framework_AudioVideoBridging-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:b1fb0af1df78800205cd7a7cd90e58b640513bbb944fe6a8d89df43e626a27a8", size = 11094 }, + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, ] [[package]] -name = "pyobjc-framework-authenticationservices" -version = "10.3.1" +name = "pyyaml" +version = "6.0.3" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/35/3b/12082a13266fed356222a5c6c3eaf6ddcf21099f7a5b76b3fff58568042a/pyobjc_framework_authenticationservices-10.3.1.tar.gz", hash = "sha256:0ac834f4a5cbe3cf20acd4f6a96df77bc643a1ae248e394d06964db9fe0d6310", size = 86405 } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ce/f3/7e2ed16674d77f7f124d9aed88e44d420c1de9bf405fe3a020fa4550ffc5/pyobjc_framework_AuthenticationServices-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:fa0a11fb64e30f14f01ec2d3a2a89a3e1a554db62111b0612f1782722b6dd534", size = 19963 }, - { url = "https://files.pythonhosted.org/packages/87/8c/51425897927005f8d42b26fd1c5ce6b934dcff287f3d643b21cba2a8fcd2/pyobjc_framework_AuthenticationServices-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:e2753cdd5480f97753dc32d9f41d7e6cb75b09f7ce950b2eea4a9851e0a437db", size = 19902 }, - { url = "https://files.pythonhosted.org/packages/22/c5/23298f667061724b479b5c6707e985ac36541d04e023110427a4a936098b/pyobjc_framework_AuthenticationServices-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:91c2cc0e963d6ac44c3a6014270b54e6499f1aae64d82482d96114c38fb99817", size = 13723 }, - { url = "https://files.pythonhosted.org/packages/27/d1/0d3a08a92ca7dd92311f8b13e08f41f2f5d558bad17a4db53dcd007b951a/pyobjc_framework_AuthenticationServices-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:d715bbdf1c94ea838830930a41de0554905760943cff1510268d8e485c826ee8", size = 19988 }, + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, ] [[package]] -name = "pyobjc-framework-automaticassessmentconfiguration" -version = "10.3.1" +name = "pyzmq" +version = "27.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "cffi", marker = "implementation_name == 'pypy'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/67/0d/19f8aee86e91da5a9f6954870f21d839b835a20e84eb2221b839797be705/pyobjc_framework_automaticassessmentconfiguration-10.3.1.tar.gz", hash = "sha256:f7846d04493e90eddbacfb7cffebc11b3f76f0800d3dc2bec39441732a20ac56", size = 22477 } +sdist = { url = "https://files.pythonhosted.org/packages/04/0b/3c9baedbdf613ecaa7aa07027780b8867f57b6293b6ee50de316c9f3222b/pyzmq-27.1.0.tar.gz", hash = "sha256:ac0765e3d44455adb6ddbf4417dcce460fc40a05978c08efdf2948072f6db540", size = 281750, upload-time = "2025-09-08T23:10:18.157Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/ce/ebe221179d1e860ade2128f8a5bce3da22df1db4f4abe567197620abda7a/pyobjc_framework_AutomaticAssessmentConfiguration-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:f717f6df5886123a55584f8dd85626c42387f5b55edcd3d68ff306b3fe56a206", size = 8590 }, - { url = "https://files.pythonhosted.org/packages/6a/14/c929d3ef97471462292072011e2ad228516892b6e0077f0b6ea62adc0c27/pyobjc_framework_AutomaticAssessmentConfiguration-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:ab84a771835f346e8a45d19e05f0c2ef8bb3dca81461fb2acc6c9f031794ec63", size = 8637 }, - { url = "https://files.pythonhosted.org/packages/fe/b8/fe90a1e80487f95986c2d0aa55a2714b955aa9be3e21cf06e8458f2392c2/pyobjc_framework_AutomaticAssessmentConfiguration-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:66fd582549ef602a8bcaadb57de8a06cb0dc0367c2a508b20c580fde2232daed", size = 6588 }, - { url = "https://files.pythonhosted.org/packages/3b/1c/c761dcab6f5ea6f1137a4bc9e1ce584010daaabbcdf4c11d66a0e490b2b1/pyobjc_framework_AutomaticAssessmentConfiguration-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:578512ae1443e031c3fbfec7eefa71e5ac5fc8cac892ad7183c5ac0b894d494d", size = 8915 }, + { url = "https://files.pythonhosted.org/packages/92/e7/038aab64a946d535901103da16b953c8c9cc9c961dadcbf3609ed6428d23/pyzmq-27.1.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:452631b640340c928fa343801b0d07eb0c3789a5ffa843f6e1a9cee0ba4eb4fc", size = 1306279, upload-time = "2025-09-08T23:08:03.807Z" }, + { url = "https://files.pythonhosted.org/packages/e8/5e/c3c49fdd0f535ef45eefcc16934648e9e59dace4a37ee88fc53f6cd8e641/pyzmq-27.1.0-cp312-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1c179799b118e554b66da67d88ed66cd37a169f1f23b5d9f0a231b4e8d44a113", size = 895645, upload-time = "2025-09-08T23:08:05.301Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e5/b0b2504cb4e903a74dcf1ebae157f9e20ebb6ea76095f6cfffea28c42ecd/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3837439b7f99e60312f0c926a6ad437b067356dc2bc2ec96eb395fd0fe804233", size = 652574, upload-time = "2025-09-08T23:08:06.828Z" }, + { url = "https://files.pythonhosted.org/packages/f8/9b/c108cdb55560eaf253f0cbdb61b29971e9fb34d9c3499b0e96e4e60ed8a5/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43ad9a73e3da1fab5b0e7e13402f0b2fb934ae1c876c51d0afff0e7c052eca31", size = 840995, upload-time = "2025-09-08T23:08:08.396Z" }, + { url = "https://files.pythonhosted.org/packages/c2/bb/b79798ca177b9eb0825b4c9998c6af8cd2a7f15a6a1a4272c1d1a21d382f/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0de3028d69d4cdc475bfe47a6128eb38d8bc0e8f4d69646adfbcd840facbac28", size = 1642070, upload-time = "2025-09-08T23:08:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/9c/80/2df2e7977c4ede24c79ae39dcef3899bfc5f34d1ca7a5b24f182c9b7a9ca/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:cf44a7763aea9298c0aa7dbf859f87ed7012de8bda0f3977b6fb1d96745df856", size = 2021121, upload-time = "2025-09-08T23:08:11.907Z" }, + { url = "https://files.pythonhosted.org/packages/46/bd/2d45ad24f5f5ae7e8d01525eb76786fa7557136555cac7d929880519e33a/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f30f395a9e6fbca195400ce833c731e7b64c3919aa481af4d88c3759e0cb7496", size = 1878550, upload-time = "2025-09-08T23:08:13.513Z" }, + { url = "https://files.pythonhosted.org/packages/e6/2f/104c0a3c778d7c2ab8190e9db4f62f0b6957b53c9d87db77c284b69f33ea/pyzmq-27.1.0-cp312-abi3-win32.whl", hash = "sha256:250e5436a4ba13885494412b3da5d518cd0d3a278a1ae640e113c073a5f88edd", size = 559184, upload-time = "2025-09-08T23:08:15.163Z" }, + { url = "https://files.pythonhosted.org/packages/fc/7f/a21b20d577e4100c6a41795842028235998a643b1ad406a6d4163ea8f53e/pyzmq-27.1.0-cp312-abi3-win_amd64.whl", hash = "sha256:9ce490cf1d2ca2ad84733aa1d69ce6855372cb5ce9223802450c9b2a7cba0ccf", size = 619480, upload-time = "2025-09-08T23:08:17.192Z" }, + { url = "https://files.pythonhosted.org/packages/78/c2/c012beae5f76b72f007a9e91ee9401cb88c51d0f83c6257a03e785c81cc2/pyzmq-27.1.0-cp312-abi3-win_arm64.whl", hash = "sha256:75a2f36223f0d535a0c919e23615fc85a1e23b71f40c7eb43d7b1dedb4d8f15f", size = 552993, upload-time = "2025-09-08T23:08:18.926Z" }, ] [[package]] -name = "pyobjc-framework-automator" -version = "10.3.1" +name = "qrcode" +version = "8.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/88/ca/fe39648043bf7ab2e5f09707cca9254277555c1a09973ade71fc029f7dff/pyobjc_framework_automator-10.3.1.tar.gz", hash = "sha256:330042475479f054ac98abd568b523fc0165c39eeefffc23bd65d35780939316", size = 195097 } +sdist = { url = "https://files.pythonhosted.org/packages/8f/b2/7fc2931bfae0af02d5f53b174e9cf701adbb35f39d69c2af63d4a39f81a9/qrcode-8.2.tar.gz", hash = "sha256:35c3f2a4172b33136ab9f6b3ef1c00260dd2f66f858f24d88418a015f446506c", size = 43317, upload-time = "2025-05-01T15:44:24.726Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/46/d9/129cbbf10c38b8a9f907cbfbb44dc9746861c3a2d306d49963e401016480/pyobjc_framework_Automator-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:63632d2c1d069ca29a077b15ab20a0a0acc0a5f33ee322c9c8cc854702c66549", size = 10019 }, - { url = "https://files.pythonhosted.org/packages/41/a7/745ae406ed296d4503556a5e8697bdad6ac9004e01a55a598aef660915fb/pyobjc_framework_Automator-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:4bc8afe0a52bee09f7f99bdfc62100654f08113de47e74488c0af2afcd646e23", size = 10077 }, - { url = "https://files.pythonhosted.org/packages/00/0c/bdc85fe1824d0551e4e9cdd0f2467b1615c8a40ed972172fc70b6494979c/pyobjc_framework_Automator-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:8609e1295030d2a46916965cd070072a90b6528abc25ae4d02e50818d2cb252f", size = 7776 }, - { url = "https://files.pythonhosted.org/packages/00/0c/4c81e55eb886112756177f86389558ee0b04ec060b4eaca122e4f83f8bdc/pyobjc_framework_Automator-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:2f482464b3f91405a5a59e3b96ae89c5062af81023ea0fc803353fdfe8cc4a9d", size = 10372 }, + { url = "https://files.pythonhosted.org/packages/dd/b8/d2d6d731733f51684bbf76bf34dab3b70a9148e8f2cef2bb544fccec681a/qrcode-8.2-py3-none-any.whl", hash = "sha256:16e64e0716c14960108e85d853062c9e8bba5ca8252c0b4d0231b9df4060ff4f", size = 45986, upload-time = "2025-05-01T15:44:22.781Z" }, ] [[package]] -name = "pyobjc-framework-avfoundation" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } +name = "raylib" +version = "6.0.0.0" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=raylib&rev=release-raylib#dbf05cd774c2f74a70a0ee9ebb80015ed70ce718" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coreaudio" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5b/4f/0f509c925c28d4b0ea709ccb9fd9a229c6552187f7506aa1e583d66cf658/pyobjc_framework_avfoundation-10.3.1.tar.gz", hash = "sha256:2f94bee3a4217b46d9416cad066e4f357bf0f344079c328736114451ae19ae94", size = 695146 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a9/62/5b7cfc6ea3d5df7d61b29eb6572ef4abc8027af5538ceff4f2582f672bcb/pyobjc_framework_AVFoundation-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:0896f6650df35f0229d1fb3aa3fbf632647dd815d4921cb61d9eb7fa26be6237", size = 67777 }, - { url = "https://files.pythonhosted.org/packages/0c/34/2f0e42bfedf3d15381944940bded10266d25f8843f2aed85ac731d880dd5/pyobjc_framework_AVFoundation-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:0cb27cc95288d95df7504adf474596f8855de7fa7798bbc1bbfbdfbbcb940952", size = 67973 }, - { url = "https://files.pythonhosted.org/packages/5e/41/3c5b35d8fee491a8c2998d5bf8bc1f746edf4ce338759b1019c6470cb0ee/pyobjc_framework_AVFoundation-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ccb606ef0806d952a04db45ae691167678121df1d8d7c2f8cc73745695097033", size = 55449 }, - { url = "https://files.pythonhosted.org/packages/db/bb/b7eb1bb9ba12a0717c944f7a60f6decafa745cf7281a935671ccd0739b42/pyobjc_framework_AVFoundation-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:00889eb915479aa9ea392cdd241e4b635ae0fa3114f043d08cf3e1d1b5a23bd4", size = 67995 }, + { name = "cffi" }, ] [[package]] -name = "pyobjc-framework-avkit" -version = "10.3.1" +name = "requests" +version = "2.34.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b5/de/7de605cea8176d69a41503dd544c0af02760c4518be3049b877563cc0c36/pyobjc_framework_avkit-10.3.1.tar.gz", hash = "sha256:97ca35b5f0cec98f5c8521fedb8537bb23d82739b7102e4ac732d3c3944c8ccc", size = 38986 } +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/22/b3/76c4c4a6455928f130aa08d121ef717536e77d58fb6013f7d3fd609bbc8a/pyobjc_framework_AVKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:bb6025331e5ed493d5ca0a35fab14026820e0d8b0a091fc6010b4ef77aa4bf16", size = 12368 }, - { url = "https://files.pythonhosted.org/packages/3a/42/d683ad96e4b51cccbd99109c7fa5350a841015844fe0e042df040d4f8ad6/pyobjc_framework_AVKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:675832ec9c088c2010bd9cd9f912ff5c45ff608d7d94233347d49f1b91f690ca", size = 12418 }, - { url = "https://files.pythonhosted.org/packages/78/e2/3932538c415f2e592a5e9313699fb7714d96cf1113f1dea6f8af75065106/pyobjc_framework_AVKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:1d92e1d5d098af87667f3eac0609c39c58320c095cdcb7737958cc4895569f22", size = 8435 }, - { url = "https://files.pythonhosted.org/packages/25/ae/158378a4753102daeb89e5c0f5ae827c97015ab8d84d4d021965071d386c/pyobjc_framework_AVKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:91bf61fa8d8ef3764345b085038a4081165a8c54b4f0c2a11ee07f86a1556689", size = 12282 }, + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] [[package]] -name = "pyobjc-framework-avrouting" -version = "10.3.1" +name = "ruamel-yaml" +version = "0.19.1" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/66/d5/b3012c90b18722b9d8e27f6a570ac534da89e4902bf5805f0bb39e340891/pyobjc_framework_avrouting-10.3.1.tar.gz", hash = "sha256:7026059b24daf8e1da05d7867f450e82abe412fe5c438faf9344f46e3b83da39", size = 18663 } +sdist = { url = "https://files.pythonhosted.org/packages/c7/3b/ebda527b56beb90cb7652cb1c7e4f91f48649fbcd8d2eb2fb6e77cd3329b/ruamel_yaml-0.19.1.tar.gz", hash = "sha256:53eb66cd27849eff968ebf8f0bf61f46cdac2da1d1f3576dd4ccee9b25c31993", size = 142709, upload-time = "2026-01-02T16:50:31.84Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d0/58/b01ddd24cb808eca3ef0254cc6e00fb47c53ce41c18f37ac23ea64db4cd7/pyobjc_framework_AVRouting-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:30b05ea44f21d481e39905684c79176c04060e0e92c1ad31756fed6aa39b07df", size = 8260 }, - { url = "https://files.pythonhosted.org/packages/9f/e3/d814c295e9a4f4cf8c8f283371a42c992b0996b96a99bbda7e2e8efa2976/pyobjc_framework_AVRouting-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:af940e322cb9ce9d79b47b829c5df41ac4980aca2cda1fbe1ead4ed0f9f589a4", size = 8314 }, - { url = "https://files.pythonhosted.org/packages/4a/d0/7c689243a9da880ff6eacb3694f40098507b22e300752ca8a11cbf31de09/pyobjc_framework_AVRouting-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:3e5101311ee84c884c0eba201b3b7f92e1a2325132a9e44b9b7ad84cdd28b4c2", size = 6015 }, - { url = "https://files.pythonhosted.org/packages/aa/58/60bbff72a9aec1b8419461e94946a531878385993aaca1789795906fe69e/pyobjc_framework_AVRouting-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:186e891c2a271492612b3db2b5c2050c56ed1bfce1f6146de8dbf05e7cd7623b", size = 8628 }, + { url = "https://files.pythonhosted.org/packages/b8/0c/51f6841f1d84f404f92463fc2b1ba0da357ca1e3db6b7fbda26956c3b82a/ruamel_yaml-0.19.1-py3-none-any.whl", hash = "sha256:27592957fedf6e0b62f281e96effd28043345e0e66001f97683aa9a40c667c93", size = 118102, upload-time = "2026-01-02T16:50:29.201Z" }, ] [[package]] -name = "pyobjc-framework-backgroundassets" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bb/be/6a0039ac75e7d9b84f7250d2301e0fe6529c0db6c137e398e31d04f65629/pyobjc_framework_backgroundassets-10.3.1.tar.gz", hash = "sha256:5e1198f81db6f30ead2a55e8ea39264f9fce83dcf8e31a68e5f0ea08c5cfe9b5", size = 21762 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/53/b0/8de66724de73e39c00ccddfd4f8d56eac4ea9da810fc79a86ef59b522621/pyobjc_framework_BackgroundAssets-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:f725d33a5d633c514e4973489e1bdca391976a5c04443451acaaacc5ccd4095e", size = 9684 }, - { url = "https://files.pythonhosted.org/packages/cd/bb/d3de8275de550fae2bb0263252fb784859f5ed07cf43783f1a243d5e9766/pyobjc_framework_BackgroundAssets-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:14cc84ad7bef64986fe240d23205870fc40dd7b1d2a1819d3dd7924c4898b5c2", size = 9743 }, - { url = "https://files.pythonhosted.org/packages/bd/a7/fecbc4d0b6d0583f2a0eba81f920fd03b68afe6beb8fbf75691283a74702/pyobjc_framework_BackgroundAssets-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:e28624ecfba067b5e0fc91d5818cb3d20d0ba189a7e8a724678abbecc233c13e", size = 7222 }, - { url = "https://files.pythonhosted.org/packages/11/da/f25864ee44ccc600a7b93c07e0a7b45f88a9ed302de708c88bd9edfd9ba5/pyobjc_framework_BackgroundAssets-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:aed2307c7fdd690e4dd214cbfacf4e7d5dd07e6cdd88ce1c02c4ddde3deea843", size = 10224 }, +name = "ruff" +version = "0.15.15" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/84/6f/a76f7d96e5c962f5b69cee865e49c15c1116897c01990faa8a57edb62e7f/ruff-0.15.15.tar.gz", hash = "sha256:b8dff018130b46d8e5bf0f926ef6b60cf871d6d5ae45fc9334e09632daa741d6", size = 4706985, upload-time = "2026-05-28T14:16:57.784Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/9d/3a45c05b8ab04b4705989de70a79008e27c8003296a0feaee9edc18dd7e9/ruff-0.15.15-py3-none-linux_armv6l.whl", hash = "sha256:cf93e5388f412e1b108b1f8b34a6e036b70fe8aff89393befad96fe48670311b", size = 10710652, upload-time = "2026-05-28T14:16:06.701Z" }, + { url = "https://files.pythonhosted.org/packages/05/66/da974431624bf3b49f6ee1f9543c02d929ff1cba78b0d5a79c38cf21f744/ruff-0.15.15-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:ac5a646d1f6a7dadd5d50842dae2c1f9862ac887ef5d1b1375e02def791fde6e", size = 11096615, upload-time = "2026-05-28T14:16:23.313Z" }, + { url = "https://files.pythonhosted.org/packages/8c/09/7443452e5d290230a712103f2fdceeef7184f3ec99a2bd01c8be78aaceb5/ruff-0.15.15-py3-none-macosx_11_0_arm64.whl", hash = "sha256:77d955a431430c66f72dd94e379ad38a16daea3d25094872ac4edf9e797be530", size = 10436683, upload-time = "2026-05-28T14:16:40.974Z" }, + { url = "https://files.pythonhosted.org/packages/53/01/d330c26a57fa4f3943a14424904027428315b700fe4d14a84bb123a649e5/ruff-0.15.15-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7614ee79c69788cf6cedd568069ade9cecc22a1ad20494efe8d0c9ebb4b622d4", size = 10769064, upload-time = "2026-05-28T14:16:28.905Z" }, + { url = "https://files.pythonhosted.org/packages/1d/85/cc8770f8bdff541b1da8392d1634141fe4a0e3f4ee596605959b7906c27f/ruff-0.15.15-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3cdb1679e06a1f6b47bc384714ae96f6e2fb65ca441eb78c43d2ca554176ce1f", size = 10511987, upload-time = "2026-05-28T14:16:43.732Z" }, + { url = "https://files.pythonhosted.org/packages/7c/29/8c190c1472b63013583ba391f3342036e02010544c1270455ed8e519bdf3/ruff-0.15.15-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2728b93d7b23a603ea2c0ac6eb73d760bd38ec9de35f35fb41e18f7a3fee7622", size = 11275100, upload-time = "2026-05-28T14:16:55.244Z" }, + { url = "https://files.pythonhosted.org/packages/9f/6b/7e145ce2cc8e63d6834eca03d83a0e18d121def5c69f91b4cf4011ed4879/ruff-0.15.15-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:be582fcc0db438902c7792b08d6ddf6c9b9e21addaa10092c2c741cfb09e5a45", size = 12176903, upload-time = "2026-05-28T14:16:14.368Z" }, + { url = "https://files.pythonhosted.org/packages/80/a3/d5974637f68e451f7fadf015cf3101d1cd7d8ba5027cffe0b9e3826ebe6b/ruff-0.15.15-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7aa77465b8ecaf1a27bea098d696f7fed5e1eccbd10b321b682d6de586ae5627", size = 11404550, upload-time = "2026-05-28T14:16:20.138Z" }, + { url = "https://files.pythonhosted.org/packages/fe/1c/e6e5e568f22be4fb05d6244234aba384c06b451252453b821e1a529263cf/ruff-0.15.15-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:48decfa11d740de4889de623be1463308346312f2409a56e24aa280c86162dc4", size = 11382027, upload-time = "2026-05-28T14:16:46.615Z" }, + { url = "https://files.pythonhosted.org/packages/1d/01/170921b49fcd2e8858825593f91cf7146c3e40a5c3e6df763e4bb0484dde/ruff-0.15.15-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:a5015088452ca0081387063649ec67f06d3d1d6b8b936a1f836b5e9657ecd48c", size = 11366041, upload-time = "2026-05-28T14:16:26.247Z" }, + { url = "https://files.pythonhosted.org/packages/87/54/a7bad711d7de93254e15e06a4c375b89a03d18de45d3e5dcc86a4472fb1a/ruff-0.15.15-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:f5294aab6356c81600fcdea3a62bb1b924dfd5e91767c12318d3f68f86af57cd", size = 10741795, upload-time = "2026-05-28T14:16:17.11Z" }, + { url = "https://files.pythonhosted.org/packages/c9/31/38c075963668f8b41c6914ee0f6f318727fbe30ab9145cb29e6df464c5fa/ruff-0.15.15-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:db5bd4d802415cca656dc1616070b725952d6ae95eb5d4831e49fbd94a38f75f", size = 10511117, upload-time = "2026-05-28T14:16:31.767Z" }, + { url = "https://files.pythonhosted.org/packages/9d/96/6ff689e1f7e375d1d97075eca022f74c2bab59554a432fe4d2e6f091986a/ruff-0.15.15-py3-none-musllinux_1_2_i686.whl", hash = "sha256:587a6278ed42059191c1a466e490bd7930fb50bd2e255398bc29616c895a61cb", size = 10994867, upload-time = "2026-05-28T14:16:35.149Z" }, + { url = "https://files.pythonhosted.org/packages/c3/c2/5dce0ab9f92a8d534fa62b9bf9caca3eddb8c1a81b616f5e195ada4f0d6e/ruff-0.15.15-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:df0c1c084f5f4be9812f61518a45c440d3c30d69ce4bf6c5270e66d38338f02a", size = 11482101, upload-time = "2026-05-28T14:16:49.598Z" }, + { url = "https://files.pythonhosted.org/packages/b1/c0/1003b60edd697c649faf61f1a34094b1abb38fb3d1181e3f895781250a08/ruff-0.15.15-py3-none-win32.whl", hash = "sha256:29428ea79694afbe756d45fd59b36f22b6b020dc0443cf7de0173046236964b9", size = 10716774, upload-time = "2026-05-28T14:16:52.337Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/1269eddd6945a06c23f055ef7848886e37cf9d6a8bebb386a3115f01470c/ruff-0.15.15-py3-none-win_amd64.whl", hash = "sha256:8df0323902e15e24bc4bf246da830573d3cf3352bd0b9a164eab335d111ff4a4", size = 11868463, upload-time = "2026-05-28T14:16:11.333Z" }, + { url = "https://files.pythonhosted.org/packages/4e/b2/920464c907b191e37469d477a1aa8bc048b8f36c4c1610dfa4ab87b39e18/ruff-0.15.15-py3-none-win_arm64.whl", hash = "sha256:3c8ceca6792f38196b8f589bc92eccd03eef286602da92e5dc05cc42ef6441b7", size = 11138498, upload-time = "2026-05-28T14:16:38.425Z" }, ] [[package]] -name = "pyobjc-framework-browserenginekit" -version = "10.3.1" +name = "scons" +version = "4.10.1" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coreaudio" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/48/09/61f1688824a500f74e4fee94cec3ec3bef87e58a5205026761e4d292f027/pyobjc_framework_browserenginekit-10.3.1.tar.gz", hash = "sha256:0f6ea100bcf06f2b3f915dab27cf2f038698b39510fb47d3769f72ff62c1e80b", size = 21016 } +sdist = { url = "https://files.pythonhosted.org/packages/7d/c9/2f430bb39e4eccba32ce8008df4a3206df651276422204e177a09e12b30b/scons-4.10.1.tar.gz", hash = "sha256:99c0e94a42a2c1182fa6859b0be697953db07ba936ecc9817ae0d218ced20b15", size = 3258403, upload-time = "2025-11-16T22:43:39.258Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/fa/fb104e8dba10800982d499da02d2422a9faef685438a12c9e899385693c1/pyobjc_framework_BrowserEngineKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:86c92ef4e79db4066f7887426e99cfec8902fc8949fb666359cf2a9e519106fc", size = 10579 }, - { url = "https://files.pythonhosted.org/packages/68/a4/85deec80d0b26a31ddf830039448ef4d98a74f21ce9c817fb88147fc275c/pyobjc_framework_BrowserEngineKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:69766ba235976e0a1961d3925228d2ef12808298acd0cd66fe9e883424f0f9a4", size = 10639 }, - { url = "https://files.pythonhosted.org/packages/e1/dd/e324a9760722f719fcc6f1f0ed0b02d52ee523436d7e03e16dcec416fc98/pyobjc_framework_BrowserEngineKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:5394a5a801563834764ae46204f8ce4d61a0e2d4567716361eaf5f5e3a27aba7", size = 7416 }, - { url = "https://files.pythonhosted.org/packages/4c/8c/4b11a2cfd7df34507c8da6c4c54da4de135e856f9bca2d86524c8e67b4c1/pyobjc_framework_BrowserEngineKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:d5aeff43abed7e87f637086a05f1b77083cfc7cab07c09c447ae2b23621b2945", size = 10480 }, + { url = "https://files.pythonhosted.org/packages/ce/bf/931fb9fbb87234c32b8b1b1c15fba23472a10777c12043336675633809a7/scons-4.10.1-py3-none-any.whl", hash = "sha256:bd9d1c52f908d874eba92a8c0c0a8dcf2ed9f3b88ab956d0fce1da479c4e7126", size = 4136069, upload-time = "2025-11-16T22:43:35.933Z" }, ] [[package]] -name = "pyobjc-framework-businesschat" -version = "10.3.1" +name = "sentry-sdk" +version = "2.61.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "certifi" }, + { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/19/7414a07489dbeef3b1bd40845cb9bd0e035062da3879ca20fb01a7901302/pyobjc_framework_businesschat-10.3.1.tar.gz", hash = "sha256:53e52981f9da336fcaf6783e82509e06faf8868931213ac70e6bd7395a5859a4", size = 12088 } +sdist = { url = "https://files.pythonhosted.org/packages/63/3b/4bc6b348bbd331daa14d4babe9f2b99bc854f4da41560eefb9488d78481d/sentry_sdk-2.61.1.tar.gz", hash = "sha256:9c6adccb3feefa9ba032c8d295ca477575c2f11896046a2b0ad686c47c4af555", size = 459429, upload-time = "2026-06-01T07:24:18.875Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/85/0e/b3f16873394b9d88c3217a5fe3e736e36af049f813c18af5a1bf38279cd8/pyobjc_framework_BusinessChat-10.3.1-py2.py3-none-any.whl", hash = "sha256:952b60f558e3d3498e6191d717bf62c1803f4e1ad040ae29d130090671ec004f", size = 3088 }, + { url = "https://files.pythonhosted.org/packages/df/54/c9218db183846e08efaf68534889ef42e499dde432778881104a42f7071b/sentry_sdk-2.61.1-py3-none-any.whl", hash = "sha256:fa36eaf4b8ad708f718500d4bdcc1532637526a22beb874d88cbc0a46458b5ae", size = 483735, upload-time = "2026-06-01T07:24:17.027Z" }, ] [[package]] -name = "pyobjc-framework-calendarstore" -version = "10.3.1" +name = "setproctitle" +version = "1.3.7" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/10/85/c4bb713e7e4d3f197ac975f5425ecf5469c1ea91d7b80d32eb4437b004f4/pyobjc_framework_calendarstore-10.3.1.tar.gz", hash = "sha256:21f627b0afb9a667794b451dd3a03f12ea3f74358dc5977c33b8ecc8b9736c27", size = 62920 } +sdist = { url = "https://files.pythonhosted.org/packages/8d/48/49393a96a2eef1ab418b17475fb92b8fcfad83d099e678751b05472e69de/setproctitle-1.3.7.tar.gz", hash = "sha256:bc2bc917691c1537d5b9bca1468437176809c7e11e5694ca79a9ca12345dcb9e", size = 27002, upload-time = "2025-09-05T12:51:25.278Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e3/7f/2e3325244afa35fa610757a7f0488965b6fe89504d13ad2325527f515139/pyobjc_framework_CalendarStore-10.3.1-py2.py3-none-any.whl", hash = "sha256:7afb59e793ea6d28706423faa50bb1f25532d8ed7388c8540596ce41891445ca", size = 4865 }, + { url = "https://files.pythonhosted.org/packages/fb/f0/2dc88e842077719d7384d86cc47403e5102810492b33680e7dadcee64cd8/setproctitle-1.3.7-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2dc99aec591ab6126e636b11035a70991bc1ab7a261da428491a40b84376654e", size = 18049, upload-time = "2025-09-05T12:49:36.241Z" }, + { url = "https://files.pythonhosted.org/packages/f0/b4/50940504466689cda65680c9e9a1e518e5750c10490639fa687489ac7013/setproctitle-1.3.7-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cdd8aa571b7aa39840fdbea620e308a19691ff595c3a10231e9ee830339dd798", size = 13079, upload-time = "2025-09-05T12:49:38.088Z" }, + { url = "https://files.pythonhosted.org/packages/d0/99/71630546b9395b095f4082be41165d1078204d1696c2d9baade3de3202d0/setproctitle-1.3.7-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2906b6c7959cdb75f46159bf0acd8cc9906cf1361c9e1ded0d065fe8f9039629", size = 32932, upload-time = "2025-09-05T12:49:39.271Z" }, + { url = "https://files.pythonhosted.org/packages/50/22/cee06af4ffcfb0e8aba047bd44f5262e644199ae7527ae2c1f672b86495c/setproctitle-1.3.7-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6915964a6dda07920a1159321dcd6d94fc7fc526f815ca08a8063aeca3c204f1", size = 33736, upload-time = "2025-09-05T12:49:40.565Z" }, + { url = "https://files.pythonhosted.org/packages/5c/00/a5949a8bb06ef5e7df214fc393bb2fb6aedf0479b17214e57750dfdd0f24/setproctitle-1.3.7-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cff72899861c765bd4021d1ff1c68d60edc129711a2fdba77f9cb69ef726a8b6", size = 35605, upload-time = "2025-09-05T12:49:42.362Z" }, + { url = "https://files.pythonhosted.org/packages/b0/3a/50caca532a9343828e3bf5778c7a84d6c737a249b1796d50dd680290594d/setproctitle-1.3.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b7cb05bd446687ff816a3aaaf831047fc4c364feff7ada94a66024f1367b448c", size = 33143, upload-time = "2025-09-05T12:49:43.515Z" }, + { url = "https://files.pythonhosted.org/packages/ca/14/b843a251296ce55e2e17c017d6b9f11ce0d3d070e9265de4ecad948b913d/setproctitle-1.3.7-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:3a57b9a00de8cae7e2a1f7b9f0c2ac7b69372159e16a7708aa2f38f9e5cc987a", size = 34434, upload-time = "2025-09-05T12:49:45.31Z" }, + { url = "https://files.pythonhosted.org/packages/c8/b7/06145c238c0a6d2c4bc881f8be230bb9f36d2bf51aff7bddcb796d5eed67/setproctitle-1.3.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d8828b356114f6b308b04afe398ed93803d7fca4a955dd3abe84430e28d33739", size = 32795, upload-time = "2025-09-05T12:49:46.419Z" }, + { url = "https://files.pythonhosted.org/packages/ef/dc/ef76a81fac9bf27b84ed23df19c1f67391a753eed6e3c2254ebcb5133f56/setproctitle-1.3.7-cp312-cp312-win32.whl", hash = "sha256:b0304f905efc845829ac2bc791ddebb976db2885f6171f4a3de678d7ee3f7c9f", size = 12552, upload-time = "2025-09-05T12:49:47.635Z" }, + { url = "https://files.pythonhosted.org/packages/e2/5b/a9fe517912cd6e28cf43a212b80cb679ff179a91b623138a99796d7d18a0/setproctitle-1.3.7-cp312-cp312-win_amd64.whl", hash = "sha256:9888ceb4faea3116cf02a920ff00bfbc8cc899743e4b4ac914b03625bdc3c300", size = 13247, upload-time = "2025-09-05T12:49:49.16Z" }, ] [[package]] -name = "pyobjc-framework-callkit" -version = "10.3.1" +name = "setuptools" +version = "82.0.1" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d3/b2/be5cf42e2b288073fa5d693d869ac2fbfb091a34e8edd5aa67f50fa6982f/pyobjc_framework_callkit-10.3.1.tar.gz", hash = "sha256:350390023e9ac98ff6c91b1f51da2489eef2e23aa649d0f63c13cf1d8be1e0df", size = 31907 } +sdist = { url = "https://files.pythonhosted.org/packages/4f/db/cfac1baf10650ab4d1c111714410d2fbb77ac5a616db26775db562c8fab2/setuptools-82.0.1.tar.gz", hash = "sha256:7d872682c5d01cfde07da7bccc7b65469d3dca203318515ada1de5eda35efbf9", size = 1152316, upload-time = "2026-03-09T12:47:17.221Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/92/01/4e419642221949f459459633be2e0ef456c7cdb8fb02644a805b31008e86/pyobjc_framework_CallKit-10.3.1-py2.py3-none-any.whl", hash = "sha256:495354bea298efdc81c970154083b83aff985f2c294d4883a62de3cc4129e34e", size = 4916 }, + { url = "https://files.pythonhosted.org/packages/9d/76/f789f7a86709c6b087c5a2f52f911838cad707cc613162401badc665acfe/setuptools-82.0.1-py3-none-any.whl", hash = "sha256:a59e362652f08dcd477c78bb6e7bd9d80a7995bc73ce773050228a348ce2e5bb", size = 1006223, upload-time = "2026-03-09T12:47:15.026Z" }, ] [[package]] -name = "pyobjc-framework-cfnetwork" -version = "10.3.1" +name = "six" +version = "1.17.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/fb/e6/e1d6b0d0b21ba5241712389aea46dba4ee9d5c955738076f5ec9d75b5f29/pyobjc_framework_cfnetwork-10.3.1.tar.gz", hash = "sha256:0e4c51a75dbf4e2b1c0d4ee60a363f9d31d682d2dd2f6b74aded769d2d883aa8", size = 66882 } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2b/0a/1e8ecd8604952650c38b53469c2a383c341e99e0a559cb8a6a8c9a178826/pyobjc_framework_CFNetwork-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:e6027a90c5442e36a4ef91c9e10896efb5bc1bb4743d732adf3422112922f6cf", size = 18955 }, - { url = "https://files.pythonhosted.org/packages/cf/25/90a071f9ca9dd35bbb0d86246be3a99e71386aa7ee8ed7a31ba151110e89/pyobjc_framework_CFNetwork-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:dff41296378029f1a5e9cedbc133b243f096a93fcc8d6985c555459328cfe11e", size = 19011 }, - { url = "https://files.pythonhosted.org/packages/09/e9/840b9d1d09802e6d9a31c31545ea39e0ed834ff3fb84c0cfc0b5027fad47/pyobjc_framework_CFNetwork-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:01f1c4c43792e993c613b5b8923953eea774d4a7567fbc1861edb2c6c0cfa770", size = 13770 }, - { url = "https://files.pythonhosted.org/packages/e7/2d/bc2e628e12d0bd7e287ed8f7af3b0df347d1814d950a566fe3cd48e01480/pyobjc_framework_CFNetwork-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:f6a5d6fe5e230cc0d53b9673902f1571ab68b542f3630d7c1319ea1e3e480f22", size = 19002 }, + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] [[package]] -name = "pyobjc-framework-cinematic" -version = "10.3.1" +name = "sortedcontainers" +version = "2.4.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-avfoundation" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-metal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2a/83/90a5f31fd89bfa030c812c869ab69cf0e333e13ee2e3c1e4877ed883d6d3/pyobjc_framework_cinematic-10.3.1.tar.gz", hash = "sha256:7edaaa7e325aeb39cd0c33329c25783dd54af294229884556daad36d1d1b9d72", size = 19342 } +sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8f/d1/cc9c887e748d172fc0928f0d80cf03f598daba9757ea08187e6295d6dc4c/pyobjc_framework_Cinematic-10.3.1-py2.py3-none-any.whl", hash = "sha256:48bf35d594f4f010266a028bbf93bd953cc78db7658d3c614e219b482c8d73b2", size = 4193 }, + { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, ] [[package]] -name = "pyobjc-framework-classkit" -version = "10.3.1" +name = "sounddevice" +version = "0.5.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "cffi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a9/b8/cc33b734656f6617394b410a9805d05511aecdb665591936acfd66060dfd/pyobjc_framework_classkit-10.3.1.tar.gz", hash = "sha256:e15700d32007bf77c5c740bc9931c864bb7739cdfcd2b0595377c3ed35ecfe25", size = 32503 } +sdist = { url = "https://files.pythonhosted.org/packages/2a/f9/2592608737553638fca98e21e54bfec40bf577bb98a61b2770c912aab25e/sounddevice-0.5.5.tar.gz", hash = "sha256:22487b65198cb5bf2208755105b524f78ad173e5ab6b445bdab1c989f6698df3", size = 143191, upload-time = "2026-01-23T18:36:43.529Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2b/a1/b18ea640218aaa4e3005b02eaa68eb10cd8e5036a38eb15cedff2055a380/pyobjc_framework_ClassKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:980d2605296428d177b0111af914d0dd4a0c5116da5ae944cdd8b6bba733e758", size = 8390 }, - { url = "https://files.pythonhosted.org/packages/93/ae/e15dbc7c011b6c047754a4638baa9c870006544b66f792534e60403decf3/pyobjc_framework_ClassKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:17dec45d5ec7db663bc87ddf80b8185d2134177f265a12a9a6df778901183412", size = 8442 }, - { url = "https://files.pythonhosted.org/packages/4e/41/969326adb114e3d16bbe23b61d0c9d7bb5788d598ddbffaf2a87666fe240/pyobjc_framework_ClassKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b74155902851e8e2b31b34c606dd33f9e24d9b8992568cc71b60e1ddc553d99e", size = 6452 }, - { url = "https://files.pythonhosted.org/packages/68/26/1a566a950018abc0b38ecef709810ad87d1e33126624e3b751be3370881d/pyobjc_framework_ClassKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:776a600182b7de58676ac661b235356f46683e758d99db1cf60f52aac335389f", size = 8673 }, + { url = "https://files.pythonhosted.org/packages/1e/0a/478e441fd049002cf308520c0d62dd8333e7c6cc8d997f0dda07b9fbcc46/sounddevice-0.5.5-py3-none-any.whl", hash = "sha256:30ff99f6c107f49d25ad16a45cacd8d91c25a1bcdd3e81a206b921a3a6405b1f", size = 32807, upload-time = "2026-01-23T18:36:35.649Z" }, + { url = "https://files.pythonhosted.org/packages/56/f9/c037c35f6d0b6bc3bc7bfb314f1d6f1f9a341328ef47cd63fc4f850a7b27/sounddevice-0.5.5-py3-none-macosx_10_6_x86_64.macosx_10_6_universal2.whl", hash = "sha256:05eb9fd6c54c38d67741441c19164c0dae8ce80453af2d8c4ad2e7823d15b722", size = 108557, upload-time = "2026-01-23T18:36:37.41Z" }, + { url = "https://files.pythonhosted.org/packages/88/a1/d19dd9889cd4bce2e233c4fac007cd8daaf5b9fe6e6a5d432cf17be0b807/sounddevice-0.5.5-py3-none-win32.whl", hash = "sha256:1234cc9b4c9df97b6cbe748146ae0ec64dd7d6e44739e8e42eaa5b595313a103", size = 317765, upload-time = "2026-01-23T18:36:39.047Z" }, + { url = "https://files.pythonhosted.org/packages/c3/0e/002ed7c4c1c2ab69031f78989d3b789fee3a7fba9e586eb2b81688bf4961/sounddevice-0.5.5-py3-none-win_amd64.whl", hash = "sha256:cfc6b2c49fb7f555591c78cb8ecf48d6a637fd5b6e1db5fec6ed9365d64b3519", size = 365324, upload-time = "2026-01-23T18:36:40.496Z" }, + { url = "https://files.pythonhosted.org/packages/4e/39/a61d4b83a7746b70d23d9173be688c0c6bfc7173772344b7442c2c155497/sounddevice-0.5.5-py3-none-win_arm64.whl", hash = "sha256:3861901ddd8230d2e0e8ae62ac320cdd4c688d81df89da036dcb812f757bb3e6", size = 317115, upload-time = "2026-01-23T18:36:42.235Z" }, ] [[package]] -name = "pyobjc-framework-cloudkit" -version = "10.3.1" +name = "spidev" +version = "3.8" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-accounts" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coredata" }, - { name = "pyobjc-framework-corelocation" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/84/2d/22c51450dddeb9d851529f90ebd4f15fc12a4f3c9b2ceae4df8841fde64e/pyobjc_framework_cloudkit-10.3.1.tar.gz", hash = "sha256:4c7db72c2bb2fcf63365df91bf2eefa83cee4004606b901e1da89b75da652309", size = 98916 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a1/68/49c0dac7cf069a13352e9bb7092aa0a0caeb5646e2c3a7b9eabfb07279ce/pyobjc_framework_CloudKit-10.3.1-py2.py3-none-any.whl", hash = "sha256:53670f47320063b80aa60edd2d813308dce85dfd2112461dd13c060aa9e5b47a", size = 10475 }, -] +sdist = { url = "https://files.pythonhosted.org/packages/67/87/039b6eeea781598015b538691bc174cc0bf77df9d4d2d3b8bf9245c0de8c/spidev-3.8.tar.gz", hash = "sha256:2bc02fb8c6312d519ebf1f4331067427c0921d3f77b8bcaf05189a2e8b8382c0", size = 13893, upload-time = "2025-09-15T18:56:20.672Z" } [[package]] -name = "pyobjc-framework-cocoa" -version = "10.3.1" +name = "sympy" +version = "1.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, + { name = "mpmath" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a7/6c/b62e31e6e00f24e70b62f680e35a0d663ba14ff7601ae591b5d20e251161/pyobjc_framework_cocoa-10.3.1.tar.gz", hash = "sha256:1cf20714daaa986b488fb62d69713049f635c9d41a60c8da97d835710445281a", size = 4941542 } +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d4/ad/436c3619d1a84f83d55ff9c709b122e4d1ac2ee9af467b68fcb60e5ad3a6/pyobjc_framework_Cocoa-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:5f31021f4f8fdf873b57a97ee1f3c1620dbe285e0b4eaed73dd0005eb72fd773", size = 396142 }, - { url = "https://files.pythonhosted.org/packages/29/73/9a913537d6d63758243f76a3d3acbae8eb77705c278eceaf37198e58dcf5/pyobjc_framework_Cocoa-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:11b4e0bad4bbb44a4edda128612f03cdeab38644bbf174de0c13129715497296", size = 396183 }, - { url = "https://files.pythonhosted.org/packages/93/1f/b203c35ac17ff50b101433783988b527c1b7d7386c175c9aec1c89da5426/pyobjc_framework_Cocoa-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:de5e62e5ccf2871a94acf3bf79646b20ea893cc9db78afa8d1fe1b0d0f7cbdb0", size = 395004 }, + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, ] [[package]] -name = "pyobjc-framework-collaboration" -version = "10.3.1" +name = "tomli" +version = "2.4.1" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0d/cd/8bc8e3c4cf93b1044d5e582904ec5c55656f4385bd25f86f924b4ed25ae3/pyobjc_framework_collaboration-10.3.1.tar.gz", hash = "sha256:bbca3de3679b058cbb89ad911e3bdfe491a02b4fa219d5f9219c022774ba237a", size = 15830 } +sdist = { url = "https://files.pythonhosted.org/packages/22/de/48c59722572767841493b26183a0d1cc411d54fd759c5607c4590b6563a6/tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f", size = 17543, upload-time = "2026-03-25T20:22:03.828Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/c0/b26f50c0669f49fa652a96b6496deba5c9181ddec5ac59c4de8251666857/pyobjc_framework_Collaboration-10.3.1-py2.py3-none-any.whl", hash = "sha256:889b1e00bdea09c2423e9b8d493492ec45a70787ddc533bf67d060c7ec0e1f78", size = 4490 }, + { url = "https://files.pythonhosted.org/packages/c1/ba/42f134a3fe2b370f555f44b1d72feebb94debcab01676bf918d0cb70e9aa/tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a", size = 155924, upload-time = "2026-03-25T20:21:21.626Z" }, + { url = "https://files.pythonhosted.org/packages/dc/c7/62d7a17c26487ade21c5422b646110f2162f1fcc95980ef7f63e73c68f14/tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085", size = 150018, upload-time = "2026-03-25T20:21:23.002Z" }, + { url = "https://files.pythonhosted.org/packages/5c/05/79d13d7c15f13bdef410bdd49a6485b1c37d28968314eabee452c22a7fda/tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9", size = 244948, upload-time = "2026-03-25T20:21:24.04Z" }, + { url = "https://files.pythonhosted.org/packages/10/90/d62ce007a1c80d0b2c93e02cab211224756240884751b94ca72df8a875ca/tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5", size = 253341, upload-time = "2026-03-25T20:21:25.177Z" }, + { url = "https://files.pythonhosted.org/packages/1a/7e/caf6496d60152ad4ed09282c1885cca4eea150bfd007da84aea07bcc0a3e/tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585", size = 248159, upload-time = "2026-03-25T20:21:26.364Z" }, + { url = "https://files.pythonhosted.org/packages/99/e7/c6f69c3120de34bbd882c6fba7975f3d7a746e9218e56ab46a1bc4b42552/tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1", size = 253290, upload-time = "2026-03-25T20:21:27.46Z" }, + { url = "https://files.pythonhosted.org/packages/d6/2f/4a3c322f22c5c66c4b836ec58211641a4067364f5dcdd7b974b4c5da300c/tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917", size = 98141, upload-time = "2026-03-25T20:21:28.492Z" }, + { url = "https://files.pythonhosted.org/packages/24/22/4daacd05391b92c55759d55eaee21e1dfaea86ce5c571f10083360adf534/tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9", size = 108847, upload-time = "2026-03-25T20:21:29.386Z" }, + { url = "https://files.pythonhosted.org/packages/68/fd/70e768887666ddd9e9f5d85129e84910f2db2796f9096aa02b721a53098d/tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257", size = 95088, upload-time = "2026-03-25T20:21:30.677Z" }, + { url = "https://files.pythonhosted.org/packages/7b/61/cceae43728b7de99d9b847560c262873a1f6c98202171fd5ed62640b494b/tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe", size = 14583, upload-time = "2026-03-25T20:22:03.012Z" }, ] [[package]] -name = "pyobjc-framework-colorsync" -version = "10.3.1" +name = "tqdm" +version = "4.67.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/43/16/b5cf65d3cdae2127a868e06b21e9c59e2ef531e65c4ee58afcaef2c4fe69/pyobjc_framework_colorsync-10.3.1.tar.gz", hash = "sha256:180960ed6f76084b35073eff49fcca41a8fa883c3236949a40f75daa28ee8f94", size = 31940 } +sdist = { url = "https://files.pythonhosted.org/packages/09/a9/6ba95a270c6f1fbcd8dac228323f2777d886cb206987444e4bce66338dd4/tqdm-4.67.3.tar.gz", hash = "sha256:7d825f03f89244ef73f1d4ce193cb1774a8179fd96f31d7e1dcde62092b960bb", size = 169598, upload-time = "2026-02-03T17:35:53.048Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/3e/273fcd5803daf481ecc3d76adafd455040375acd63582e501cb3e2717de3/pyobjc_framework_ColorSync-10.3.1-py2.py3-none-any.whl", hash = "sha256:0c37075e9b0f1dabc0aa1755687e1a5dada08ae0914ebb593c7810bf8090cf83", size = 5599 }, + { url = "https://files.pythonhosted.org/packages/16/e1/3079a9ff9b8e11b846c6ac5c8b5bfb7ff225eee721825310c91b3b50304f/tqdm-4.67.3-py3-none-any.whl", hash = "sha256:ee1e4c0e59148062281c49d80b25b67771a127c85fc9676d3be5f243206826bf", size = 78374, upload-time = "2026-02-03T17:35:50.982Z" }, ] [[package]] -name = "pyobjc-framework-contacts" -version = "10.3.1" +name = "ty" +version = "0.0.41" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/eb/a9/112ee53259220322f6729c446fd7b779d3bae7b24804bd342f51764dc6bc/pyobjc_framework_contacts-10.3.1.tar.gz", hash = "sha256:7120b5593a20e936cb5589b93ef7fd5558c86bd6ec8003f427afb87c04bbea20", size = 68431 } +sdist = { url = "https://files.pythonhosted.org/packages/eb/8b/a64ba465cbc5d1b83c561a498ee5e7729b810606220277cafa93983e6ce1/ty-0.0.41.tar.gz", hash = "sha256:1e8b55bf4729634b2db64a7d9541cd880087cd681e87efc36e6a056cf05fb648", size = 5765398, upload-time = "2026-06-01T11:49:36.815Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c5/f9/7efe17e729ed96aac2618c24513c95bdf61762d2f7e9a288f4c290e32e3d/pyobjc_framework_Contacts-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:401e40ff638712d011fe54c7b1e9929af994e87cb03d129cd95df2fb90439e4e", size = 12768 }, - { url = "https://files.pythonhosted.org/packages/6f/e9/b13466931afbe95b5acd368ad0f177e530e458a76f8a7a2f1fb54f58b465/pyobjc_framework_Contacts-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:83de186cd4037171c63899987caa66cc01527688b15176e899cf1a06e6baab09", size = 12769 }, - { url = "https://files.pythonhosted.org/packages/d3/5e/b092b4fe3735d2b19790e9094bce9691a02fb9ef98d203aec039a2b0023c/pyobjc_framework_Contacts-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:e0bbffb430505ad3f91fd58f65b0a6e7535ab5bb28c2ca69ee8a6349f3edfe3c", size = 9411 }, - { url = "https://files.pythonhosted.org/packages/b3/8a/37fbb2012ca0a15aafdf1aff03317c11ed60d14ebcd1418638897075d5e6/pyobjc_framework_Contacts-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:d47f694977cf33f5d0b73e2f111edcd57f2ef0cd9a6a38e03b1dea965b8657cc", size = 12681 }, + { url = "https://files.pythonhosted.org/packages/8f/22/b032e4d0f35a436f60eabaa19c70dbed6f5095eb7e30c53ddff918aafcff/ty-0.0.41-py3-none-linux_armv6l.whl", hash = "sha256:5f61c5c06616129ce31dd74141e18be69f5e4204a9a0f4505688213353475b30", size = 11541803, upload-time = "2026-06-01T11:49:33.837Z" }, + { url = "https://files.pythonhosted.org/packages/46/f8/78f073febd728f19f0fcbe2e320855ed337b871ed775e0abe5c7b25bbc6a/ty-0.0.41-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:25d6b4fbf198ae7523b8e4845ec3c7e1b1cd5efa1712febcad3856e70e66632b", size = 11275600, upload-time = "2026-06-01T11:49:59.384Z" }, + { url = "https://files.pythonhosted.org/packages/62/c6/b1b46684514e7372960348c723657f56db56799c36542571b49c77c18c87/ty-0.0.41-py3-none-macosx_11_0_arm64.whl", hash = "sha256:3509788ed3753669cdd28d289f281b834ceee91b4de648fcf0ef60677a75b030", size = 10695726, upload-time = "2026-06-01T11:50:05.232Z" }, + { url = "https://files.pythonhosted.org/packages/36/73/badf085590648a14bfe06571799becefaa2b409c5838c39b198b790c8f58/ty-0.0.41-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b8c04f1424c872f1d8d28efbd69fb52728fcc6c37aa2d11675bf16f76d33ae14", size = 11196461, upload-time = "2026-06-01T11:50:07.174Z" }, + { url = "https://files.pythonhosted.org/packages/ff/8f/399ee615282f80fd912b5ce4b3fe31206a6d40283e0700046aebbbb893f2/ty-0.0.41-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:53e52bfce12f3723c376d690625f5c462fe318c46dbe53b16d36c266388ee04c", size = 11310318, upload-time = "2026-06-01T11:49:50.663Z" }, + { url = "https://files.pythonhosted.org/packages/e8/43/204e8fe9f4f8932dd8e42a23e3aa8a365a93ecc601f67172da1c4cea50c0/ty-0.0.41-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c4f1d606602dc0eb895a0943af737d638311c7afd48b414897fd42a05e876a76", size = 11785266, upload-time = "2026-06-01T11:49:48.733Z" }, + { url = "https://files.pythonhosted.org/packages/e3/85/9098e96e40324ebd3797c3cad20ea0d855b56219806605e10b6455cf71b3/ty-0.0.41-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e8f3c41f0b6b0525bcc8d76a9a5921cccda11886ae11f73e2d51e20e185bafb3", size = 12328093, upload-time = "2026-06-01T11:49:52.945Z" }, + { url = "https://files.pythonhosted.org/packages/0e/41/b6a4d29591e86a27ab1364ddc70d6cee9a78cff1ede5466f6862f0384a68/ty-0.0.41-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bff8c4468933961e656664c3ef190800e3d50582c248aed41bb8a1578d64864a", size = 11979937, upload-time = "2026-06-01T11:49:29.633Z" }, + { url = "https://files.pythonhosted.org/packages/94/b2/6772c2c24fe412ebd0d57166d36afc176948857f7e90f368d321c561a12e/ty-0.0.41-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c83077a5c56770b1dab5b086a908a4e77740fb8f29d862ed05bd4c854549603d", size = 11859185, upload-time = "2026-06-01T11:49:46.474Z" }, + { url = "https://files.pythonhosted.org/packages/75/59/e4a1e0feef9d74308621c3a8b1558db97fa1c022948341d0eed1bdfc59a1/ty-0.0.41-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:8067fae5532ad3c48295c7ddbd1657ea3ee7392810c57810c9c98fe83d43d57f", size = 12036836, upload-time = "2026-06-01T11:49:39.182Z" }, + { url = "https://files.pythonhosted.org/packages/31/67/38f5312c74d51a510fb46c55b49880af6ca186cb87618938c67e808a45a5/ty-0.0.41-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:73a245242380bac3fbf3005d085c153923a45de8918001fad475af54c6fd50e4", size = 11179559, upload-time = "2026-06-01T11:50:01.355Z" }, + { url = "https://files.pythonhosted.org/packages/8c/55/f8cb36874dc1b8b26c6ae066f8ebec392197caa22becdc55bc7e53d251a5/ty-0.0.41-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:4eb25f5dc398aa0a5fbd90de62d6a0fd3713354e566ba93cc53670fe84067ee1", size = 11347231, upload-time = "2026-06-01T11:49:55.093Z" }, + { url = "https://files.pythonhosted.org/packages/8d/96/2d4369d7e8240b2dea1d7a7985709c38c6ccc57bbc8dbbdae3db5ee8d71a/ty-0.0.41-py3-none-musllinux_1_2_i686.whl", hash = "sha256:092c3a1ef9e3a189f71428092e736080ef42bf5c14412aa61bee8d644261797d", size = 11446240, upload-time = "2026-06-01T11:49:31.822Z" }, + { url = "https://files.pythonhosted.org/packages/8b/b0/36f09bfb568bc14f8496f2ace503c63c9152b4b65da4518cd3be0aa85312/ty-0.0.41-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:53edeb6e2ac430fe789454471f0e22a2a71581100818271150bd8f89fa468cc7", size = 11947795, upload-time = "2026-06-01T11:49:41.654Z" }, + { url = "https://files.pythonhosted.org/packages/92/33/ffd38f5e3ecb25e1b7aac314d902ceaa93be16f4874dc236f9da79509468/ty-0.0.41-py3-none-win32.whl", hash = "sha256:f66bdf3afb71f11d412a4c704fa9691e0209cbc8268a19489c8960c7b74eac8b", size = 10776684, upload-time = "2026-06-01T11:50:03.309Z" }, + { url = "https://files.pythonhosted.org/packages/ce/35/4c3e821906cfb05a88c232f5c1202be7ed336e05f4cc796213c809ab6177/ty-0.0.41-py3-none-win_amd64.whl", hash = "sha256:c18386e5c3a0c3d118ce58ee0d8a35f8d18d6b1020ca8ec690f6064e6230a79b", size = 11860965, upload-time = "2026-06-01T11:49:57.07Z" }, + { url = "https://files.pythonhosted.org/packages/5e/20/7c587e4c3c6da1757555831cac308c4add7a958f8b1c7f76cb1dd55ceabf/ty-0.0.41-py3-none-win_arm64.whl", hash = "sha256:289eb66ee5c3554d59b0ea69885ddc5fc8051f3228dd9fee2501799db4a07117", size = 11206414, upload-time = "2026-06-01T11:49:44.395Z" }, ] [[package]] -name = "pyobjc-framework-contactsui" -version = "10.3.1" +name = "typing-extensions" +version = "4.15.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-contacts" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ad/17/ce9b512e29ca92eb519328d0fc1e12b6b048ac379447c7f4f2be4266599e/pyobjc_framework_contactsui-10.3.1.tar.gz", hash = "sha256:51601501d5bc94c59ad458c7bb1d1994c497b373307dad8bd2ea2aa348f66c4a", size = 17921 } +sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9b/d0/67150306b40068d05cb7794ed5762fe85c5d9eb0a6148b1860d7fab3cab1/pyobjc_framework_ContactsUI-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:0e939e46ccff1e07e7fa6768a35d646b7302886a99b9efe6b31dea4ea67674ad", size = 7906 }, - { url = "https://files.pythonhosted.org/packages/48/7e/2a9b1e4ae673406bad4278126491a818e2a55e4791c7cec62487947f1096/pyobjc_framework_ContactsUI-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:4adc77f2fb7ae4e2999cfd72f5d3b8e0e039880f9d60cb8e15050607b249c730", size = 7965 }, - { url = "https://files.pythonhosted.org/packages/0d/cc/998cfd89b2308f8bb971b3cd85901e531e91eea82cda7d7afba967f21655/pyobjc_framework_ContactsUI-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:1a605d93b4826cd4646cced6383cb253e65c8babcfd230d5894c1c4d67f6e147", size = 5688 }, - { url = "https://files.pythonhosted.org/packages/4d/56/63b61f49146a9d1890b8a06f93bf99fd15d61afdc65f6d75689aec53217c/pyobjc_framework_ContactsUI-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:62ae604a000233c729712e420de734c97afdd9187fdd0bef8e61fbc8c4f6eda0", size = 8251 }, + { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, ] [[package]] -name = "pyobjc-framework-coreaudio" -version = "10.3.1" +name = "urllib3" +version = "2.7.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c5/fe/39351e6a58f4a9b1fce5a5e982830612277233084fe72b1d84b4de890f3b/pyobjc_framework_coreaudio-10.3.1.tar.gz", hash = "sha256:c81c709bf955aea474a4de380b187f3c2e56c864ca7de520b08362b73070c795", size = 125676 } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6f/dd/e4be148694e5e73885aaf00a92720293674fd510d87369cf5ba300f24660/pyobjc_framework_CoreAudio-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bd58e69cabbc987d0c2854ab2d13516889cfe4a2094b80296591ad7df0f30e40", size = 35672 }, - { url = "https://files.pythonhosted.org/packages/21/1c/af5e88a24dc7f437852a9605949c5eeaedb7bba9883b2c3cd275dea3729b/pyobjc_framework_CoreAudio-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:e0aeca61a425d846afc92350ffba970e1e503469182f5f0ea436de98cfd00d96", size = 36444 }, - { url = "https://files.pythonhosted.org/packages/31/50/3917e5190b65e4f29a5977c9713651c779f48753042d2fdc3f8dbda12353/pyobjc_framework_CoreAudio-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:21cecd1b023b6960d1071c106345656de45a399196701b07c7e5c076321f25ad", size = 36199 }, + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, ] [[package]] -name = "pyobjc-framework-coreaudiokit" -version = "10.3.1" +name = "websocket-client" +version = "1.9.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coreaudio" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1f/4e/79a20d1ab459467de5695f96057e034d6457b061da68951b41af211b1fe3/pyobjc_framework_coreaudiokit-10.3.1.tar.gz", hash = "sha256:81f35d5dc45cda043e01f0ca045311f4aebc36c51cb71e859b30ea0edf90b3db", size = 19761 } +sdist = { url = "https://files.pythonhosted.org/packages/2c/41/aa4bf9664e4cda14c3b39865b12251e8e7d239f4cd0e3cc1b6c2ccde25c1/websocket_client-1.9.0.tar.gz", hash = "sha256:9e813624b6eb619999a97dc7958469217c3176312b3a16a4bd1bc7e08a46ec98", size = 70576, upload-time = "2025-10-07T21:16:36.495Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/13/d3/6cc3624b3dfc5f5d25221e8b46d456c5f3f1bbefe9fc1a9a030406a31ddf/pyobjc_framework_CoreAudioKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:dfc967bc448cc0a1fce932e6af15ad42f5ea3eb2f793396e364cf39005c812eb", size = 7331 }, - { url = "https://files.pythonhosted.org/packages/e6/2e/45509db91d9fcb0df6e1a24884596e2e560f20d6083a06f6bf9e72e42b84/pyobjc_framework_CoreAudioKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:6634f3f15d257e93cad4644eb08f5b32376e8a8a7ae2e95d99d36d935b5e9ba2", size = 7395 }, - { url = "https://files.pythonhosted.org/packages/1a/12/424094bba2cf1ccdaf2b3aa2ad25462799a2f1978c116e4a7011504b696e/pyobjc_framework_CoreAudioKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:c2bf1b0c9f6c1d27c98b87bf4cf1ba3d0fa550dd771de948614ca21d15779a01", size = 5463 }, - { url = "https://files.pythonhosted.org/packages/43/df/910252ab44c47e48421f57be17c539e2f828653834cfbc7343e9f379db4e/pyobjc_framework_CoreAudioKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:d5b3adabd7278e64a0deab6d0f6912bfcc667bc26054f5141a556897157dd8f9", size = 7452 }, + { url = "https://files.pythonhosted.org/packages/34/db/b10e48aa8fff7407e67470363eac595018441cf32d5e1001567a7aeba5d2/websocket_client-1.9.0-py3-none-any.whl", hash = "sha256:af248a825037ef591efbf6ed20cc5faa03d3b47b9e5a2230a529eeee1c1fc3ef", size = 82616, upload-time = "2025-10-07T21:16:34.951Z" }, ] [[package]] -name = "pyobjc-framework-corebluetooth" -version = "10.3.1" +name = "xattr" +version = "1.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "cffi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f7/69/89afd7747f42d2eb1e8f4b7f2ba2739d98ccf36f6b5c72474802962494de/pyobjc_framework_corebluetooth-10.3.1.tar.gz", hash = "sha256:dc5d326ab5541b8b68e7e920aa8363851e779cb8c33842f6cfeef4674cc62f94", size = 50210 } +sdist = { url = "https://files.pythonhosted.org/packages/08/d5/25f7b19af3a2cb4000cac4f9e5525a40bec79f4f5d0ac9b517c0544586a0/xattr-1.3.0.tar.gz", hash = "sha256:30439fabd7de0787b27e9a6e1d569c5959854cb322f64ce7380fedbfa5035036", size = 17148, upload-time = "2025-10-13T22:16:47.353Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/33/2f/b34311bc453472e34c7a9473b1da21d79f7126d61f95d85e7d679cbd98c1/pyobjc_framework_CoreBluetooth-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:c89ee6fba0ed359c46b4908a7d01f88f133be025bd534cbbf4fb9c183e62fc97", size = 14052 }, - { url = "https://files.pythonhosted.org/packages/af/a2/946a7099d5181ebfa59eb390471b30b51f04da935f8ef8d9a9ac3a102e13/pyobjc_framework_CoreBluetooth-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:2f261a386aa6906f9d4601d35ff71a13315dbca1a0698bf1f1ecfe3971de4648", size = 14102 }, - { url = "https://files.pythonhosted.org/packages/87/43/a344c043be35a516c0e1b7c69cb1945c3150a11416fdd89f066214ef65fc/pyobjc_framework_CoreBluetooth-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:5211df0da2e8be511d9a54a48505dd7af0c4d04546fe2027dd723801d633c6ba", size = 10202 }, - { url = "https://files.pythonhosted.org/packages/f0/a4/ed61aba4cd2d66d0569669d047bcaf249fe28dd79331015fd0d6387dbd60/pyobjc_framework_CoreBluetooth-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:b8becd4e406be289a2d423611d3ad40730532a1f6728effb2200e68c9c04c3e8", size = 13942 }, + { url = "https://files.pythonhosted.org/packages/bf/78/00bdc9290066173e53e1e734d8d8e1a84a6faa9c66aee9df81e4d9aeec1c/xattr-1.3.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:dd4e63614722d183e81842cb237fd1cc978d43384166f9fe22368bfcb187ebe5", size = 23476, upload-time = "2025-10-13T22:16:06.942Z" }, + { url = "https://files.pythonhosted.org/packages/53/16/5243722294eb982514fa7b6b87a29dfb7b29b8e5e1486500c5babaf6e4b3/xattr-1.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:995843ef374af73e3370b0c107319611f3cdcdb6d151d629449efecad36be4c4", size = 18556, upload-time = "2025-10-13T22:16:08.209Z" }, + { url = "https://files.pythonhosted.org/packages/d6/5c/d7ab0e547bea885b55f097206459bd612cefb652c5fc1f747130cbc0d42c/xattr-1.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fa23a25220e29d956cedf75746e3df6cc824cc1553326d6516479967c540e386", size = 18869, upload-time = "2025-10-13T22:16:10.319Z" }, + { url = "https://files.pythonhosted.org/packages/98/25/25cc7d64f07de644b7e9057842227adf61017e5bcfe59a79df79f768874c/xattr-1.3.0-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b4345387087fffcd28f709eb45aae113d911e1a1f4f0f70d46b43ba81e69ccdd", size = 38797, upload-time = "2025-10-13T22:16:11.624Z" }, + { url = "https://files.pythonhosted.org/packages/a9/24/cc350bcdbed006dfcc6ade0ac817693b8b3d4b2787f20e427fd0697042e4/xattr-1.3.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fe92bb05eb849ab468fe13e942be0f8d7123f15d074f3aba5223fad0c4b484de", size = 38956, upload-time = "2025-10-13T22:16:13.121Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b2/9416317ac89e2ed759a861857cda0d5e284c3691e6f460d36cc2bd5ce4d1/xattr-1.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6c42ef5bdac3febbe28d3db14d3a8a159d84ba5daca2b13deae6f9f1fc0d4092", size = 38214, upload-time = "2025-10-13T22:16:14.389Z" }, + { url = "https://files.pythonhosted.org/packages/38/63/188f7cb41ab35d795558325d5cc8ab552171d5498cfb178fd14409651e18/xattr-1.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2aaa5d66af6523332189108f34e966ca120ff816dfa077ca34b31e6263f8a236", size = 37754, upload-time = "2025-10-13T22:16:15.306Z" }, ] [[package]] -name = "pyobjc-framework-coredata" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/cc/17/1929fabc88d265373ce2b5e5c3136aae03c30ee42df66bd0810fa71328da/pyobjc_framework_coredata-10.3.1.tar.gz", hash = "sha256:8a75094942c8f3ddc1bcbde920c87658d7bb4c7534a4652e60db42d17f4b4a4a", size = 229850 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e6/18/5662deb09d3bff1390f6eab760f0e806a91d604d867960978245304a44ca/pyobjc_framework_CoreData-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:2313aba4236f3a909d2747f4327da83be884adadb734a602ed4319addf88edd7", size = 16618 }, - { url = "https://files.pythonhosted.org/packages/51/69/d07e0b235e22dbe33cf5fc7b377828a0965ca4eb156ba7db1ba380c79a20/pyobjc_framework_CoreData-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:065ff3058f4bc8544422ad1f10dff037bdeed25263cc8ec5c609e54231bf9347", size = 16675 }, - { url = "https://files.pythonhosted.org/packages/b0/39/3a3d76a11980a7757ce91b8a3de71a1486dc9d9f32d7b087d6a29df8e643/pyobjc_framework_CoreData-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:049acf980e5226b132a4285c3a94cc8266380e57050c8fd4caec3c5df4ef8c4d", size = 14186 }, - { url = "https://files.pythonhosted.org/packages/36/31/a18ce8a793a4129968409199153799aac71b2461b994a7fb8125e0fa723d/pyobjc_framework_CoreData-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:2f1f4e1217fc02f66435dc2a5cb2e0b41c684c435f13d96bf05cd3d1e0ad4e2c", size = 17130 }, -] +name = "xvfb" +version = "1.20.11.post1" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=xvfb&rev=release-xvfb#f0bb0b0d9154ea7858f3c0333b607ba7d356b571" } [[package]] -name = "pyobjc-framework-corehaptics" -version = "10.3.1" +name = "yarl" +version = "1.24.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/6b/04/ef530d0c30cf81a772ddee64cbfeb7cafd9428d87df96bbc6eb41b77d80f/pyobjc_framework_corehaptics-10.3.1.tar.gz", hash = "sha256:5a7cc117c0b64428e1f08dc9c8b76dbc5d8f61f80dc41e911d11ddee4e0e2059", size = 36854 } +sdist = { url = "https://files.pythonhosted.org/packages/79/12/1e8f37460ea0f7eb59c221fdaf0ed75e7ac43e97f8093b9c6f411df50a78/yarl-1.24.2.tar.gz", hash = "sha256:9ac374123c6fd7abf64d1fec93962b0bd4ee2c19751755a762a72dd96c0378f8", size = 210798, upload-time = "2026-05-19T21:31:05.599Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2b/70/b41b0423b1dce4c98e87787c5af254275ad88db1a781eca5d8d440a4c882/pyobjc_framework_CoreHaptics-10.3.1-py2.py3-none-any.whl", hash = "sha256:163b83ea727cbac5c0963d16ffda89c9f1626ed633d5e52830c7918b8599a693", size = 4987 }, + { url = "https://files.pythonhosted.org/packages/f0/da/866bcb01076ba49d2b42b309867bed3826421f1c479655eb7a607b44f20b/yarl-1.24.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:b975866c184564c827e0877380f0dae57dcca7e52782128381b72feff6dfceb8", size = 129957, upload-time = "2026-05-19T21:28:51.695Z" }, + { url = "https://files.pythonhosted.org/packages/bf/1d/fcefb70922ea2268a8971d8e5874d9a8218644200fb8465f1dcad55e6851/yarl-1.24.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3b075301a2836a0e297b1b658cb6d6135df535d62efefdd60366bd589c2c82f2", size = 92164, upload-time = "2026-05-19T21:28:53.242Z" }, + { url = "https://files.pythonhosted.org/packages/29/b6/170e2b8d4e3bc30e6bfdcca53556537f5bf595e938632dfcb059311f3ff6/yarl-1.24.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8ae44649b00947634ab0dab2a374a638f52923a6e67083f2c156cd5cbd1a881d", size = 91688, upload-time = "2026-05-19T21:28:54.865Z" }, + { url = "https://files.pythonhosted.org/packages/fe/a5/c9f655d5553ea0b99fdac9d6a99ad3f9b3e73b8e5758bb46f58c9831f74c/yarl-1.24.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:507cc19f0b45454e2d6dcd62ff7d062b9f77a2812404e62dbdaec05b50faa035", size = 102902, upload-time = "2026-05-19T21:28:56.963Z" }, + { url = "https://files.pythonhosted.org/packages/5d/bc/6b9664d815d79af4ee553337f9d606c56bbf269186ada9172de45f1b5f60/yarl-1.24.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c4c17bad5a530912d2111825d3f05e89bab2dd376aaa8cbc77e449e6db63e576", size = 97931, upload-time = "2026-05-19T21:28:58.56Z" }, + { url = "https://files.pythonhosted.org/packages/98/ec/32ba48acae30fecd60928f5791188b80a9d6ee3840507ffda29fecd37b71/yarl-1.24.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f5f0cbb112838a4a293985b6ed73948a547dadcc1ba6d2089938e7abdedceef8", size = 111030, upload-time = "2026-05-19T21:29:00.148Z" }, + { url = "https://files.pythonhosted.org/packages/82/5a/6f4cd081e5f4934d2ae3a8ef4abe3afacc010d26f0035ee91b35cd7d7c37/yarl-1.24.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5ec8356b8a6afcf81fc7aeeef13b1ff7a49dec00f313394bbb9e83830d32ccd7", size = 110392, upload-time = "2026-05-19T21:29:02.155Z" }, + { url = "https://files.pythonhosted.org/packages/7a/da/323a01c349bd5fb01bb6652e314d9bb218cee630a736bdb810ad50e4013f/yarl-1.24.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7e7ebcdef69dec6c6451e616f32b622a6d4a2e92b445c992f7c8e5274a6bbc4c", size = 105612, upload-time = "2026-05-19T21:29:04.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/80/264ab684f181e1a876389374519ff05d10248725535ae2ac4e8ac4e563d6/yarl-1.24.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:47a55d6cf6db2f401017a9e96e5288844e5051911fb4e0c8311a3980f5e59a7d", size = 104487, upload-time = "2026-05-19T21:29:06.491Z" }, + { url = "https://files.pythonhosted.org/packages/41/07/efabe5df87e96d7ad5959760b888344be48cd6884db127b407c6b5503adc/yarl-1.24.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3065657c80a2321225e804048597ad55658a7e76b32d6f5ee4074d04c50401db", size = 102333, upload-time = "2026-05-19T21:29:08.267Z" }, + { url = "https://files.pythonhosted.org/packages/44/0c/bcf7c42603e1009295f586d8890f2ba032c8b53310e815adf0a202c73d9f/yarl-1.24.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:cb84b80d88e19ede158619b80813968713d8d008b0e2497a576e6a0557d50712", size = 99025, upload-time = "2026-05-19T21:29:10.682Z" }, + { url = "https://files.pythonhosted.org/packages/4f/82/84482ab1a57a0f21a08afe6a7004c61d741f8f2ecc3b05c321577c612164/yarl-1.24.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:990de4f680b1c217e77ff0d6aa0029f9eb79889c11fb3e9a3942c7eba29c1996", size = 110507, upload-time = "2026-05-19T21:29:12.954Z" }, + { url = "https://files.pythonhosted.org/packages/c4/8d/a546ba1dfe1b0f290e05fef145cd07614c0f15df1a707195e512d1e39d1d/yarl-1.24.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:abb8ec0323b80161e3802da3150ef660b41d0e9be2048b76a363d93eee992c2b", size = 103719, upload-time = "2026-05-19T21:29:14.893Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b6/267f2a09213138473adfce6b8a6e17791d7fee70bd4d9003218e4dec58b0/yarl-1.24.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:e7977781f83638a4c73e0f88425563d70173e0dfd90ac006a45c65036293ee3c", size = 110438, upload-time = "2026-05-19T21:29:16.485Z" }, + { url = "https://files.pythonhosted.org/packages/48/2d/1c8d89c7c5f9cad9fb2902445d94e2ab1d7aa35de029afbb8ae95c42d00f/yarl-1.24.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e30dd55825dc554ec5b66a94953b8eda8745926514c5089dfcacecb9c99b5bd1", size = 105719, upload-time = "2026-05-19T21:29:18.367Z" }, + { url = "https://files.pythonhosted.org/packages/a7/25/722e3b93bd687009afb2d59a35e13d30ddd8f80571445bb0c4e4ce26ec66/yarl-1.24.2-cp312-cp312-win_amd64.whl", hash = "sha256:7dafe10c12ddd4d120d528c4b5599c953bd7b12845347d507b95451195bb6cad", size = 92901, upload-time = "2026-05-19T21:29:20.014Z" }, + { url = "https://files.pythonhosted.org/packages/39/47/4486ccfb674c04854a1ef8aa77868b6a6f765feaf69633409d7ca4f02cb8/yarl-1.24.2-cp312-cp312-win_arm64.whl", hash = "sha256:044a09d8401fcf8681977faef6d286b8ade1e2d2e9dceda175d1cfa5ca496f30", size = 87229, upload-time = "2026-05-19T21:29:22.1Z" }, + { url = "https://files.pythonhosted.org/packages/fd/4d/4b880086bd0d3e034d25647be1d830afc3e3f610e98c4ab3490af6b1b6d5/yarl-1.24.2-py3-none-any.whl", hash = "sha256:2783d9226db8797636cd6896e4de81feed252d1db72265686c9558d97a4d94b9", size = 53576, upload-time = "2026-05-19T21:31:03.909Z" }, ] [[package]] -name = "pyobjc-framework-corelocation" -version = "10.3.1" +name = "zensical" +version = "0.0.43" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, + { name = "click" }, + { name = "deepmerge" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "pyyaml" }, + { name = "tomli" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/06/35/8cf7ab8f9b7be5b81deac4d74fdc89607a3eeb901f785cc7d50332eaa275/pyobjc_framework_corelocation-10.3.1.tar.gz", hash = "sha256:8ae54e5bd4c07f7224639d815f7a6537fadee17c11cb35dd99c2804bac1825ab", size = 89219 } +sdist = { url = "https://files.pythonhosted.org/packages/d4/85/ec45162e7824a8f879d887ef0774ee65926bf7d1064e2eebccc7eaee3378/zensical-0.0.43.tar.gz", hash = "sha256:dc2d3804ff562795c1024130e0c3ce79736467930729dda314f096d0e35b98c8", size = 3932396, upload-time = "2026-05-19T09:44:07.418Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7a/a0/9268f18f0daec40460590a724eef778f6012d81da3e4c668b478486288f4/pyobjc_framework_CoreLocation-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:4cc83a730db7f78ca5ceef45ea4c992084d8c90bed189939fa3f51f8e9ea83ae", size = 12928 }, - { url = "https://files.pythonhosted.org/packages/e9/e3/16b8d53786cee07c496d614ca29aeb1e110a93fea501983b54158d23622e/pyobjc_framework_CoreLocation-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:97d5aa35214e417c9a03ac7209630dc445b98652932642dd0497f1ec52624bfe", size = 12978 }, - { url = "https://files.pythonhosted.org/packages/f8/1d/e290bc1dc73bccc09a6483dd86dcce057477f367622a94b704cee987a0e8/pyobjc_framework_CoreLocation-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:86d0e00b7eef5a3e2f01ea309cdcf58807b251138008edcfc65d3c31af8a5bd2", size = 9865 }, - { url = "https://files.pythonhosted.org/packages/c4/85/aec923825469aa315d1fbdf5cd5988158fee5f0740f44b0c18b0b6624fd6/pyobjc_framework_CoreLocation-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:5c4ded6388f99a18ce2b9d7082b8a43a19b6d9f8f121e2147d10bb37a25e1714", size = 12840 }, + { url = "https://files.pythonhosted.org/packages/55/c2/55e0709607ae41c266987c3b91a1a9702b37fbbef0d07eddfe5e25c2d823/zensical-0.0.43-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:17c335362b6bac3a50178181694a964f6d9f0c516fc532129ba5a0a5c4103fb6", size = 12706531, upload-time = "2026-05-19T09:43:32.729Z" }, + { url = "https://files.pythonhosted.org/packages/2c/64/ce8627bc5ea30556162b29b041fe97d6a6aef2a87b51f12def628e4fa608/zensical-0.0.43-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:b8fe97f185194215f6193af45a17d2b30ebd72c8113e3650f2d7d6767b9c2206", size = 12563012, upload-time = "2026-05-19T09:43:35.962Z" }, + { url = "https://files.pythonhosted.org/packages/66/d1/533bc9454f0e06b3d9d8bd2e7ac405308c3d4dee6572acab98f0ed6d1c07/zensical-0.0.43-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4c4c85978c765b3e7f347e8102dfe1373d4bbe4229d7008b6bdbf352f1fbcd7f", size = 12947599, upload-time = "2026-05-19T09:43:38.754Z" }, + { url = "https://files.pythonhosted.org/packages/75/a0/94f47d6fb592997be7ab9526938c929f0199adf2637c3c2b2b9b2101b28e/zensical-0.0.43-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:90d7c06ffd07b2bdf78bef041d541baba8a3ea51fd2dd84dbdbc5b0229076524", size = 12904911, upload-time = "2026-05-19T09:43:42.434Z" }, + { url = "https://files.pythonhosted.org/packages/96/fb/1db3ad9a86ff772f74a8bc60ad5b447aa02a158e70f94adacf50bdd5c40f/zensical-0.0.43-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:60022f4a6b95e46ec0023f51052fcd491743b3ebd08c0066b22a5cf1e741fecd", size = 13269386, upload-time = "2026-05-19T09:43:45.387Z" }, + { url = "https://files.pythonhosted.org/packages/31/ee/b24fd0f94885519d851c35615b086d069a1077b0198021a56755395a4633/zensical-0.0.43-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e278eb948a0b7545d50609d713c7c27e366dade4523ff73a311a5d5f136518a", size = 12999364, upload-time = "2026-05-19T09:43:48.549Z" }, + { url = "https://files.pythonhosted.org/packages/28/78/401ccd7afd9d2690f81b5319b7f1eed05108154ce20e4207053914518c1c/zensical-0.0.43-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b85e5ab99fbda13823e67c43a4be6e5ebda6600602969c6575e143f20ac203fd", size = 13124392, upload-time = "2026-05-19T09:43:50.965Z" }, + { url = "https://files.pythonhosted.org/packages/98/b3/9af6eba5826b0ef143fc8308bd1e219e221441e307a958e39f824ba9ab53/zensical-0.0.43-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:751385accc92cccfd4560dabed7c423870686ef6ede244a67e5c96286af25e8f", size = 13177538, upload-time = "2026-05-19T09:43:53.964Z" }, + { url = "https://files.pythonhosted.org/packages/be/6b/cd090bd6659d32692487206469988ee84d41aa6de4cdf9e380f847da90e2/zensical-0.0.43-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:dd3ff5bfa6e65cf3d2550dc639c3da2a3bfa11087b83d57e06623c4c1607d583", size = 13327086, upload-time = "2026-05-19T09:43:56.8Z" }, + { url = "https://files.pythonhosted.org/packages/79/5b/ac2555354b5a53cb9c2c942811905c47be0b9f5603d3c1328ee8564333eb/zensical-0.0.43-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85055a115b12f49c6ab194dcf04f966fc06b690ed6a8ddddd819929fc5f340e6", size = 13284645, upload-time = "2026-05-19T09:43:59.329Z" }, + { url = "https://files.pythonhosted.org/packages/d0/c6/1688ec6e5be15e3ab367d7804753291bfbdff3109b06e20c19ce30a7129c/zensical-0.0.43-cp310-abi3-win32.whl", hash = "sha256:8a75ddd4bb3cd3c4a8e71d2ebae44c5611fd636c1d355c6124dd96e2f9c52838", size = 12256740, upload-time = "2026-05-19T09:44:02.102Z" }, + { url = "https://files.pythonhosted.org/packages/ca/a8/d967e70eac810a7e9eb8c5150d6d02848a1f42260f42977c71debed3cb02/zensical-0.0.43-cp310-abi3-win_amd64.whl", hash = "sha256:03a9d1744a6394ad66c355d6f1de04cfd92efa525b0b94bf6dbf6971c5cd2c6b", size = 12496166, upload-time = "2026-05-19T09:44:04.915Z" }, ] [[package]] -name = "pyobjc-framework-coremedia" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/68/9f/5e500c16472053db65dc917b7ea9cdc0fa8fde140ea4c38500a4c341b0a4/pyobjc_framework_coremedia-10.3.1.tar.gz", hash = "sha256:bc3e0cddf5f546b5d8407d8f46b203f1bd4396ad5dbfdc0d064a560b3fe31221", size = 180773 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3b/99/5ca053be93f30cb8420b72a1e7eefb778677e072f86ea2525dd6d848ae88/pyobjc_framework_CoreMedia-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:e63b002cf5e34540cba3f3a1704603ea0fb076ffc1ea42c2393a0679f40846de", size = 29040 }, - { url = "https://files.pythonhosted.org/packages/9e/2f/2b118b5f3c8fe955efd466398d519ffeb2e02e2957ae61953f8f4df0c798/pyobjc_framework_CoreMedia-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:c6eaf48f202becab10679e3b5dd62607ddec2739495db45882524592cabf3997", size = 29052 }, - { url = "https://files.pythonhosted.org/packages/cc/47/2af2541dcd14c7d2891a10b31d6b285099963be2a67d3778ce92458592fd/pyobjc_framework_CoreMedia-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:98b8ab02e6ec979007b706e05166e16bd61121e47fbc6e449f4b2de2c58f3cb6", size = 28679 }, -] - -[[package]] -name = "pyobjc-framework-coremediaio" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/08/67/1c22ff55baf5018d3ca4979f8c319e055ecff8b51ea91d53b8654503cc35/pyobjc_framework_coremediaio-10.3.1.tar.gz", hash = "sha256:5da3ed78475223dd3400fdb55fb97d543a248086f5cf8b77bf4aceac3df1513c", size = 88655 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9b/0b/80fcc75ecd8afb2f3966146985716e165321bbbcf00bdce2119feaf3be9e/pyobjc_framework_CoreMediaIO-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:07e19e89489a372ebea9e8a5cfaf1ec03fd570e65ed3fa2dfa44719d1e337a36", size = 17233 }, - { url = "https://files.pythonhosted.org/packages/92/5d/14312b4d3f8108124bdf69d2f5aa49d73a9c537e2ae44da698c618e66ab9/pyobjc_framework_CoreMediaIO-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:c3bc3d8f3648b6a4126983119d9fc4e21d2c7ec06beb284c57039ca1033ceb03", size = 17284 }, - { url = "https://files.pythonhosted.org/packages/82/54/078fadaa51f063d94b30eff55f20aa3b0a0fa2b21934bb37ac461941ef27/pyobjc_framework_CoreMediaIO-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b158612a62cabd7f61c1f2a4d08d4cb4682e1b2ba140a4d09ca88b1ae3014443", size = 13371 }, - { url = "https://files.pythonhosted.org/packages/d8/2a/cad9e2d9a234c805cf11d5f5b62cb7ad5e30ae0ba5814ddfced8ec3527b4/pyobjc_framework_CoreMediaIO-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:b3e9a9813bf5331bd0981e0a66ff380c5c927854f644e5cb62a2beaabd73b15f", size = 17146 }, -] - -[[package]] -name = "pyobjc-framework-coremidi" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bf/9f/38d8668499e0c590e51b3f3091d972e09a1f45e4efba94373c22d23d2b88/pyobjc_framework_coremidi-10.3.1.tar.gz", hash = "sha256:818454b56edae082a3a4b4366a7e93b8bb54856be01ee21bb8527a22a4732efc", size = 78441 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/67/9800fbbfec104699c2d03adde3fa26ec5c60505f2005abb9fc37c841096a/pyobjc_framework_CoreMIDI-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:00a6869c2365b90cdf6e1ed0bbde6d87fe4daaa40ed243ee810e3cc3945f185a", size = 17489 }, - { url = "https://files.pythonhosted.org/packages/3c/0d/d8adf38ed03bf331934635dc1dc6e9c636b08df5bccdaa55db6d1e85a789/pyobjc_framework_CoreMIDI-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:92d04962f7ea63be03127880d4659f718f5b44b6a57a0e619a96d9def619bddb", size = 17870 }, - { url = "https://files.pythonhosted.org/packages/1f/30/1ff3b49c3c117d30fedd85edf02b4c502a250f0717efb8caa0c04f81a333/pyobjc_framework_CoreMIDI-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:1be5f2d3c0c7c23817ad49a25d8cf8c84b9e420bd5fedc0065ec1322f5d5f2ab", size = 12784 }, - { url = "https://files.pythonhosted.org/packages/5d/d1/fc3226b125b0c7359539c508e939ad28f67acd487c628b3828c80a65720b/pyobjc_framework_CoreMIDI-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:bbe2bfb537e8adcca703a2c76b21ca1741d32691205af00a5ec67c025ee5d8e1", size = 17920 }, -] - -[[package]] -name = "pyobjc-framework-coreml" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5b/a2/08a73df17f344700f48444e3000ebdf0ca78765bf0816387de7392380255/pyobjc_framework_coreml-10.3.1.tar.gz", hash = "sha256:6b7091142cfaafee76f1a804329e7a4e3aeca921eea8644e9ceba4cc2751f705", size = 66750 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a9/93/fd46439a3d974e4c9bde868b056410abfcb897d30ddb58a0ebf31116fa5d/pyobjc_framework_CoreML-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:c1fdcc0487807afa9cd0f88f25697e0e2e093d0219e8e1aa42aa3674dd78c2cb", size = 11647 }, - { url = "https://files.pythonhosted.org/packages/d5/7d/b875857b4116e68ecead251e53ef9f456650d4e740903e73775bea459bd0/pyobjc_framework_CoreML-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:21c87e84c807b5dbe61e0f016d9aefa32d3212f175cc4b976b5c08770be7a58c", size = 11707 }, - { url = "https://files.pythonhosted.org/packages/06/97/98fd2df3eef998bc47af5b298b3b9e8040ee410b7ead298cd1da31a700b5/pyobjc_framework_CoreML-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:a0877aed5d4cdbb63d1246cd5384c09d78a0667e83c435a1257d10017c11c1a4", size = 9158 }, - { url = "https://files.pythonhosted.org/packages/d8/2e/75833ebb0b3037c32836d8a713bf8113cfb9420ee1c882e60177b5e892eb/pyobjc_framework_CoreML-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:4bd3f1acfb3245727727b71cbcf7d21a33d7e00fa488e41ad01527764b969b92", size = 11585 }, -] - -[[package]] -name = "pyobjc-framework-coremotion" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6c/77/cef3cee6010e926754cc80faa455b5a7530d740f9b5a83a94fd4bd34484a/pyobjc_framework_coremotion-10.3.1.tar.gz", hash = "sha256:6ba61ffd360473b018702b9ae025eb16b8aaa45c6e533121522f26eef93a9f71", size = 54459 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/7a/c208726685a2bae7edd597d6209f275d5052e3244ebed3d8c0f9b2e3de5a/pyobjc_framework_CoreMotion-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a003478eeb520c7f28be4d9dc8f9e02df6ffa8921d46c8879e2b298c9fbc6926", size = 9805 }, - { url = "https://files.pythonhosted.org/packages/d3/2c/dda7dbf8ffd5ae61986b2201ded7c600da7d6e3edab967065317a5b233e1/pyobjc_framework_CoreMotion-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:63c8f831ad522212627f99ae8d6f34161628230afd544203646e7d66596d6437", size = 9835 }, - { url = "https://files.pythonhosted.org/packages/fb/b3/521793543cc0266d6a6a2e4be3b660d99d0e16508cfa54436c116597b49e/pyobjc_framework_CoreMotion-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:9b78d2bcc71149821a49266eb548faea23abd7a25b7cd3f7a7f20b1d343a8786", size = 9794 }, -] - -[[package]] -name = "pyobjc-framework-coreservices" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-fsevents" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/18/c6/9214c4e64a22e92233f67f6518dc60269b30b317a169861f8cb8150adaef/pyobjc_framework_coreservices-10.3.1.tar.gz", hash = "sha256:2e46d008ee4ff586420175888c45f8eb0f002ed5b840c8f7893c560af01b2d72", size = 859909 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d1/a5/63364d45385f91a8026130d32b64e8b5a392865e4bde54a6acb7a7124a2e/pyobjc_framework_CoreServices-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:58d5708ee0a2ad7eea180864fe68123a2464b987ea089d0646ce69e2002500b0", size = 29708 }, - { url = "https://files.pythonhosted.org/packages/81/d8/d657d510b9655ab5a6b8ab4b45727f7164288a57dd20ced9f5a4ee5a98a9/pyobjc_framework_CoreServices-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:9d43b77fa11af139ba39d94921e695cf804226737f68167f8bdb8f1c449c932e", size = 29825 }, - { url = "https://files.pythonhosted.org/packages/f5/e3/a24517a8a4b6cd85105aca9f57c7cbf3ffe598f377edd88dcf1c4928e80e/pyobjc_framework_CoreServices-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:e6c7b6bb821cc7fb4f04c08560d460783a7fa08093f5e153241bf10296a16cb4", size = 28293 }, - { url = "https://files.pythonhosted.org/packages/82/41/a14f936b823d615bf799341adebed81b26bd641a0962e313f008bf23e0d6/pyobjc_framework_CoreServices-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:ccb64113ee612a05308ab8ed57ec224e22445d5a125bec11e24c35d58d1f77e4", size = 29751 }, -] - -[[package]] -name = "pyobjc-framework-corespotlight" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9f/fa/e0ef8d255265a2aaa575244df3d629c46a4eda6c64a210a9faf62fd70772/pyobjc_framework_corespotlight-10.3.1.tar.gz", hash = "sha256:6b8ad243a65943d631434a9ff4696458cdd3d0cb631cfeb501a967fe29445c30", size = 69476 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8b/80/d84bc74e1feca7d54ff3fe18d28abe2304a0eb01eb1e6df540d176fdc51e/pyobjc_framework_CoreSpotlight-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:4aa9b01b8d722ba9e803ec4a2329ee8da0bdecb9a004a668b793b957544a6d81", size = 9615 }, - { url = "https://files.pythonhosted.org/packages/b2/b5/706eea1e71054177e2e7cd3a48eb40471a8b48b7199453b05a0239eb388f/pyobjc_framework_CoreSpotlight-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:9684f735fd3d3e8fae447e90a2c246bf6a8d4ca37f619174208d65daa86d9ca0", size = 9675 }, - { url = "https://files.pythonhosted.org/packages/74/5a/14c0f369d8adbbcc47f9c86a7fcaa0c7f603cf6e29f6c91f85b2e206c42d/pyobjc_framework_CoreSpotlight-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:31b2a1309c747bb6e4d1ddc8368885af2948af55441fbf9817ebac193c1b815b", size = 7327 }, - { url = "https://files.pythonhosted.org/packages/cb/64/43e4d5505e16f5570e777e19ea9b6045cba45de8c9d2849aa003462a69c7/pyobjc_framework_CoreSpotlight-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:ba5a20e860af7246da67bb00db15d8bd5c5110b8a12a44568bd68030f51db478", size = 10091 }, -] - -[[package]] -name = "pyobjc-framework-coretext" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9e/9f/d363cb1548808f538d7ae267a9fcb999dfb5693056fdaa5bc93de089cfef/pyobjc_framework_coretext-10.3.1.tar.gz", hash = "sha256:b8fa2d5078ed774431ae64ba886156e319aec0b8c6cc23dabfd86778265b416f", size = 233428 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0e/f6/ccc934adf50fa77c7d7d8bdb13ede25d1a0a62c67fec571ae2bd8557c41d/pyobjc_framework_CoreText-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:834142a14235bd80edaef8d3a28d1e203ed3c988810a9b78005df7c561390288", size = 30266 }, - { url = "https://files.pythonhosted.org/packages/66/8e/4341253c550d6cf4da1a8c33d8d310b6ddbbaaea09eca26ea5eaff176e4b/pyobjc_framework_CoreText-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ae6c09d29eeaf30a67aa70e08a465b1f1e47d12e22b3a34ae8bc8fdb7e2e7342", size = 30404 }, - { url = "https://files.pythonhosted.org/packages/6d/7a/850261594a2a7ec54f27449db2c2494cc0b79897c765fea1581e03268f7e/pyobjc_framework_CoreText-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:51ca95df1db9401366f11a7467f64be57f9a0630d31c357237d4062df0216938", size = 30331 }, -] - -[[package]] -name = "pyobjc-framework-corewlan" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9f/b0/6e708d931e85db91de439c080d3af77422d7935b7527ce81888f8ff6ed8b/pyobjc_framework_corewlan-10.3.1.tar.gz", hash = "sha256:d340d976b5d072b917c6d3de130cb4e7a944ee0fdf4e1335b2aa6b1d4d6b4e14", size = 57781 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1b/a3/4afc5aaae025cd2367ecf267a9dbe68c5e62290c70046063658972f5699b/pyobjc_framework_CoreWLAN-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:0b9b9a6f54c11b6adcb04eb07686c8a8372140619876073d6355498da7ecd074", size = 10060 }, - { url = "https://files.pythonhosted.org/packages/9f/fa/8be58eaab2a6c3159f3a048394ee9d85910e03ebb3e9e03630cc76baf1f0/pyobjc_framework_CoreWLAN-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:8d68dabd2fdb74e5263f1e05fa039621c197907347e045cd672a54b3ac537140", size = 10110 }, - { url = "https://files.pythonhosted.org/packages/4a/83/4940889c281457873c25499e3c775d2899df2142ccd787fc02c678916ab1/pyobjc_framework_CoreWLAN-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:995260e02f858ffa0781ec0d632e60e0567c45fd551102d36fe67a351f81697e", size = 8174 }, - { url = "https://files.pythonhosted.org/packages/1f/5d/5740991885dc7bffff526148d6b8ea77dadba49ce6c1d42a6d14013006ef/pyobjc_framework_CoreWLAN-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:e7120d4f7a73cfc283ca499165e8aaf2628bfb82773917e144c293447cabbdba", size = 10283 }, -] - -[[package]] -name = "pyobjc-framework-cryptotokenkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/07/15/49981d93f8402c655cbda9181a55e0f5879715d3f6c344070ba41d2511f1/pyobjc_framework_cryptotokenkit-10.3.1.tar.gz", hash = "sha256:ef1c4a3b9bc5429eceda59724279428e1f8740df2c5a511d061b244113b6fd97", size = 48548 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/8c/6d12957ca129241a992932dd6387bd188f9c0523370b1a286ae8f7093617/pyobjc_framework_CryptoTokenKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:6c88948bc8d30cd125ae29ffe551315e08c0fb49654d4f36ba4b3f0fe2f85259", size = 13332 }, - { url = "https://files.pythonhosted.org/packages/87/b4/afaf21d0d993c98f293d72c1985ff687b4e87db4110f31599d5d4c1181fd/pyobjc_framework_CryptoTokenKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:bf0735d5d8e3ff61650deaa9670df62032dc218b865f21cd6b36b0d4c00b88ae", size = 13388 }, - { url = "https://files.pythonhosted.org/packages/0f/0e/457eae08f55e50ac281f87859ddca75a31bddff25181145ab653e65afa98/pyobjc_framework_CryptoTokenKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:bd58e48912a9b044c0203e39938b2108cab9b3a4903134ebb1ef610b45570802", size = 9664 }, - { url = "https://files.pythonhosted.org/packages/01/c9/eb29a4611eeb0b611671a392f7774d17cfa5ffd8c59440831cafd54d119c/pyobjc_framework_CryptoTokenKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:b53fdc79a095d327dff7e68e2545b0825437520f105b1341e5f638e8e1afb490", size = 13241 }, -] - -[[package]] -name = "pyobjc-framework-datadetection" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/28/9b/8b3a633ef4a215095bf1e008f4921bb9647a61a1f5b24e8ab94e89473df9/pyobjc_framework_datadetection-10.3.1.tar.gz", hash = "sha256:5394350cd7e7f40562dc0777f26dd9ddf4a595d20cb6e3cd601938e9490c963e", size = 12682 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/1e/bc1dde224086ad91e2eedcebdb698f3d9a3c81b4b7da3b0548bd9c6a42ef/pyobjc_framework_DataDetection-10.3.1-py2.py3-none-any.whl", hash = "sha256:618ea90267fd4b83d09b557b67342ad5f3ac579090020e081dca6c664f1ae598", size = 3106 }, -] - -[[package]] -name = "pyobjc-framework-devicecheck" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/23/40/51f5e655f4d003227df3077151d20e8490e17e28043e0c4152cec9fcdfac/pyobjc_framework_devicecheck-10.3.1.tar.gz", hash = "sha256:7f6f95c84dc3d1f62aa07061f79b47d19463390d977e5afb444ef9fdd9177a9d", size = 13134 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/2b/9f22fc10b09daa6283ee5e9273aa6f25c61a1aee6afc44ce55fd353dfed0/pyobjc_framework_DeviceCheck-10.3.1-py2.py3-none-any.whl", hash = "sha256:9a3b291a2583bac2b65ff902c4b7872c1068736e249765906f530ae5a6eb8085", size = 3293 }, -] - -[[package]] -name = "pyobjc-framework-dictionaryservices" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-coreservices" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a9/ee/ecf4fc40acfdc71a42f6efb7de6cd12b43ee73b3a2397872145584157aef/pyobjc_framework_dictionaryservices-10.3.1.tar.gz", hash = "sha256:c9fb8ed1b92f63c6f568bcdbadf628baab1cb8bb4cd01dbd65424d59c236a552", size = 10131 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/57/2c/ded526049d60a7863bc08244454a4ae02250b15d2c07c16ad695bb4a71f6/pyobjc_framework_DictionaryServices-10.3.1-py2.py3-none-any.whl", hash = "sha256:e40933bc96764450dff16cd8ca8080ec83157a93ed43574441848ea52f24918d", size = 3505 }, -] - -[[package]] -name = "pyobjc-framework-discrecording" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e3/0a/07b7871e9bbfb59676be857046c8285549edaf285e8c1508b67db62ddf9c/pyobjc_framework_discrecording-10.3.1.tar.gz", hash = "sha256:47865c9a0d24366b6ede01d326d57404346c3d01e249f417bd2b0b3de00d6c54", size = 101624 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/7c/9754edfb2144025245309e7433d55feb736ddf03855b9c9f974191544657/pyobjc_framework_DiscRecording-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:99ee7b1762c7e2a4e0b74c36416f4095695ea33505c7de03875a4f46a5729af7", size = 14642 }, - { url = "https://files.pythonhosted.org/packages/c6/bb/841c9452714e028486bd11f189038e91b72e0b9490307e59e4061dcd9574/pyobjc_framework_DiscRecording-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:c4233f2649e34be2dd158752f0f0180c7db4ee705cc14aa62bc03c1f77318ca3", size = 14704 }, - { url = "https://files.pythonhosted.org/packages/ea/4a/0997edb3613da5584aab28cea828efe742558de8b09cca5dce88e4307aad/pyobjc_framework_DiscRecording-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:54016cd30b81f1f065d3a4d90b008c1bcfa77891cc79c68d72dff65e9d81e083", size = 12517 }, - { url = "https://files.pythonhosted.org/packages/d4/09/65703b2911be89885d39129309af08c70f1b83832a23346afbae4f84e7e0/pyobjc_framework_DiscRecording-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:da84170af530cda7b1f32023d5e8b98b62914c573c6ef571e562473d0b94fe6f", size = 14979 }, -] - -[[package]] -name = "pyobjc-framework-discrecordingui" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-discrecording" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e6/5e/12669a09410b9707bd27ba93274cd9e817acc6d43ff358299974a52fa624/pyobjc_framework_discrecordingui-10.3.1.tar.gz", hash = "sha256:4b9c804a97c89001feddb58106cdc3e099e241314f7c4de062842d27b1318b68", size = 18181 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/78/57528e38d638bfb618f3d16b684b85a74c24e9443e3e986cc5dc1dc3ffda/pyobjc_framework_DiscRecordingUI-10.3.1-py2.py3-none-any.whl", hash = "sha256:cb25c70117a5c5eeb4ef74a96da48e2da171f01b7e92d1b7bbd7808068e8960c", size = 4344 }, -] - -[[package]] -name = "pyobjc-framework-diskarbitration" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/4e/e8/9f1929c51bcfd78bde9763cc08200eb498528534664701730077beea31d3/pyobjc_framework_diskarbitration-10.3.1.tar.gz", hash = "sha256:0776318cb56f8e095066a880812c4fc5db2071687846e23a000a947a079f6c6c", size = 18667 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/e8/9670d42e001ad2577b7526fa1cb400328c4b3851e0b7171875fe43459a4f/pyobjc_framework_DiskArbitration-10.3.1-py2.py3-none-any.whl", hash = "sha256:f0f727435da388efd035bdd510607a5f5769b22be2361afc5b8d4ee081c70cce", size = 4432 }, -] - -[[package]] -name = "pyobjc-framework-dvdplayback" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/72/b6/7f7d140ce091b9813e11f1b980956e607b552ead399abed5a70662f721c0/pyobjc_framework_dvdplayback-10.3.1.tar.gz", hash = "sha256:1f7c22624dee9b1b54def15f12a3f7cacb28052cd864a845eb24b7f59de12257", size = 53047 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/32/62882a136a3f17eef51cf81e13d69159e448c51cc9b136cf2b32375426ce/pyobjc_framework_DVDPlayback-10.3.1-py2.py3-none-any.whl", hash = "sha256:c0fb2e96ce4eae8def642f1c4beaec2da3cdf61db1562d4b5199d1334d1a10fe", size = 7836 }, -] - -[[package]] -name = "pyobjc-framework-eventkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ac/c4/995108bba1fb40eac108501038ae44c57099310982d1a6339b6a5fa47d82/pyobjc_framework_eventkit-10.3.1.tar.gz", hash = "sha256:3eef14ba439be1c5bc47da561ccea3941daba663577efac7a58e3031d27e056b", size = 64043 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/29/7f/1edbb57ab0cb591aa924279aabedf3fe508f62de136465adc44d77ab17a9/pyobjc_framework_EventKit-10.3.1-py2.py3-none-any.whl", hash = "sha256:ad9f42431bd058ff72feba3bbce6fbd88b2a278c3b2c1cdb4625ea5f60f1ecda", size = 6413 }, -] - -[[package]] -name = "pyobjc-framework-exceptionhandling" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/00/88/1328bdac98aa75de421ffea4e16f0b894e39b4ea6569b3a109b531798d20/pyobjc_framework_exceptionhandling-10.3.1.tar.gz", hash = "sha256:ff6208777739f8a886d0cbfe20692b41cc4e5e0607419c47d2c5d405b6b4c6ee", size = 17129 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/90/05/da9e1a8dce6d333d7b9e714c5c228b01b9208b827aaf2862e7c993541eb6/pyobjc_framework_ExceptionHandling-10.3.1-py2.py3-none-any.whl", hash = "sha256:79843a681a1d0f9ee2b7014dcf7e1182c99c83e49cf6cea81df934ebbdf4050b", size = 6670 }, -] - -[[package]] -name = "pyobjc-framework-executionpolicy" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/54/8e/e5a3c06123a4ec3b845dac82450f4f1b4e5b80c0863881fb538f900762b0/pyobjc_framework_executionpolicy-10.3.1.tar.gz", hash = "sha256:cc066dc8378fc2a1a4e6129c4d09e2076dc9a5b09925f8dd959aad591cbf9a44", size = 12825 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/45/559ddb59ce80f07c8c2ed81a3dd2b3ce7eb9399076cb556c8544dd444ead/pyobjc_framework_ExecutionPolicy-10.3.1-py2.py3-none-any.whl", hash = "sha256:f2eb203fa4c7dcf18a0ab3a4a94cb30a9f82cf888c237994dbbdb15adf01c8d2", size = 3343 }, -] - -[[package]] -name = "pyobjc-framework-extensionkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e7/6a/2803c373283c66eb0d38f139aa1bfa7eb9dc909bc470856ae2308f064e39/pyobjc_framework_extensionkit-10.3.1.tar.gz", hash = "sha256:91946030195fa17c5248655b10786ea60b9aee7d83a4627ba56768600b4e7674", size = 17592 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f1/a0/927202bf17e502e9e5e44821666e21158d6f251bd770d8478148ad66b0da/pyobjc_framework_ExtensionKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:e2b54a5b32c959fc1500936b73c7ebd6d7ffcad23d74b9a6ff3db4ea5660f731", size = 7953 }, - { url = "https://files.pythonhosted.org/packages/2a/af/5db1176b6ddf9319054cff45550a32d60a6339918cc1f9e5c65717624c54/pyobjc_framework_ExtensionKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:f5b1e9c7e3a64224acae7b4c2d26d2a654edc54382e9e88aa3b056f4033508f8", size = 8010 }, - { url = "https://files.pythonhosted.org/packages/0b/43/bf841d52b0da616d850821e28a299fe87fa0e50a45796be6994251801539/pyobjc_framework_ExtensionKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:62bc537cbeabb24667434c82515827e64c31d761bdcd02cc3ea6bb6a9a35873e", size = 5736 }, - { url = "https://files.pythonhosted.org/packages/83/1b/113201c23f9c9fc562b456362340669eb6744eb38081df093f6a9a7095dc/pyobjc_framework_ExtensionKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:c66797352b71a944810447c81133935656d8ea9bb847775a1532cf06d8deb1d3", size = 8286 }, -] - -[[package]] -name = "pyobjc-framework-externalaccessory" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/db/51/61ed6de7d4950f3810e0b5f95cad1a225a1fff8eef13223ebcbc659a4888/pyobjc_framework_externalaccessory-10.3.1.tar.gz", hash = "sha256:3ba1a7242448126b4af0fb93963790d0066766bcba2770d935111093e87b7b83", size = 20735 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d1/52/4606f684f4ab1708c5506813aadad620563cbf3dac16e40ef55e0febc511/pyobjc_framework_ExternalAccessory-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:4395607570f1dd91abd786422fc516f83b4b2a5185321e6581d33dbe74a52c63", size = 8945 }, - { url = "https://files.pythonhosted.org/packages/d8/b2/81b6d4046e658fc1da5d041d7303cc6a0c1b336c30b29de84260b10c7472/pyobjc_framework_ExternalAccessory-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:3fcdbb2338e7bd0fb66e9074dc95f2f989146ae92c66eb4282cfc1a6533cbe6c", size = 9006 }, - { url = "https://files.pythonhosted.org/packages/34/66/d51429f2071419e064b5c31e903074116c59f8617977b3f9a5c06c1fe36d/pyobjc_framework_ExternalAccessory-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b076ba07c84b1f4ef9a8a1aa095b66416119b1484b5111b2dd3041f2d301d1a1", size = 6537 }, - { url = "https://files.pythonhosted.org/packages/05/e2/d43cf99a6aed9de76c41bdc8f99ac39ba6926a39b01ae778bae844fabb3a/pyobjc_framework_ExternalAccessory-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:4771cddfed6422502831a9bf88fa572918d1ca71a3e34e068f442d1197630267", size = 9334 }, -] - -[[package]] -name = "pyobjc-framework-fileprovider" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2e/69/c4ebc6738e8a3f5e0c9394791434813fa2656dbe2356fdf4c611a57e7391/pyobjc_framework_fileprovider-10.3.1.tar.gz", hash = "sha256:63a4160e6cbede0f682145f4303ed889bd9f3c9fccfecdc32636a8d95aeceeab", size = 63649 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/00/39/5e4358e76d1285607166b623a8e0222b75e1560142907b8ff18b4ba9b0f2/pyobjc_framework_FileProvider-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b44bcbf3d826fd8a0cbc53142c65655433d553205fb36811486757e2089e6c5f", size = 18163 }, - { url = "https://files.pythonhosted.org/packages/d2/87/3925b479aac490f3e96c5d56da813bfddcb75dca5597526d958eb0b3484b/pyobjc_framework_FileProvider-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:b28294768dc71190019c2b2638e27b7ebf6edb65a90721b86613083bd86f6b2d", size = 18140 }, - { url = "https://files.pythonhosted.org/packages/89/bc/4465ba82721da0718c0555cdc74bb777ac40eaf5b49e97248530fca2fc62/pyobjc_framework_FileProvider-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:bb07a0b7e259030c7bc034c590c77a22e44427320c99bf74e5348551fe0da011", size = 18108 }, -] - -[[package]] -name = "pyobjc-framework-fileproviderui" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-fileprovider" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bf/5c/b130db2b86ff41da6422cd9ed54959202052c0b7401992b467c6cc29ec16/pyobjc_framework_fileproviderui-10.3.1.tar.gz", hash = "sha256:2a3f3b9b81aff216df76bc72c8e8730d7ba7f3b2412720f68b722bae58f82797", size = 12546 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ea/f2/1ddd3a5866a596daa4def91c3cb6e07f0a395232e49865f4e16c6929fb95/pyobjc_framework_FileProviderUI-10.3.1-py2.py3-none-any.whl", hash = "sha256:14be680a7fc78def5174ec5a6d890d407678cff723d6b359bba66bc0a78bd31a", size = 3317 }, -] - -[[package]] -name = "pyobjc-framework-findersync" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/67/70/0a2d490c88541912cab2d245093460190ddeed3bcde9faa3bc5e987c2247/pyobjc_framework_findersync-10.3.1.tar.gz", hash = "sha256:b4a08e0a87c54f62623038de1929fab018fe44fca5372a455bb524b9f90e9196", size = 14228 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ba/b5/bd7cd2bb1ac4c13da19309ce5db976f5b533ab8ec44744ec15963de7b131/pyobjc_framework_FinderSync-10.3.1-py2.py3-none-any.whl", hash = "sha256:d4778de8a9b386c16812d470d1ad44d7370970d1dbc75d8bea390d4f5cd12be4", size = 4478 }, -] - -[[package]] -name = "pyobjc-framework-fsevents" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a6/fe/53eb4883293b4920544570feb1d8290e937df706ee063a26061f3aebfa72/pyobjc_framework_fsevents-10.3.1.tar.gz", hash = "sha256:6269fd8aa3f62d8a6312e316043aca6d7d792812bff09b617bbd6ca9f0f6e440", size = 27274 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/38/29/84087044fbc34b60920cb921c03b69033d73ef713b98df05f35fcbef4b57/pyobjc_framework_FSEvents-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:7348e1aa268819b005e1ab648b5bac348052d3513aacf768c2c3999d6ffbf81e", size = 13056 }, - { url = "https://files.pythonhosted.org/packages/76/2c/1624ca745f6aad9fe1a1784487a1354a2324a7fdc262f8fca44fcf7498c2/pyobjc_framework_FSEvents-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:420736c645e15006c1ed962767bfd164b1d5dba7d9dc3cd9730e4c9922b05c27", size = 13138 }, - { url = "https://files.pythonhosted.org/packages/a6/93/79ee931a931f94a30f636c896cce6eaa11c754c4e3d9e7eda3af54844b6e/pyobjc_framework_FSEvents-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:56b48def729acaa0b7c27335a40519ca7d17e6d45649ba68e0f9f1c70e902994", size = 8872 }, - { url = "https://files.pythonhosted.org/packages/b9/32/7d7b848cb444737bc87d86f38a1eadf52907e4525506b3e72d4dd9ebb944/pyobjc_framework_FSEvents-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:282ebeeba0190524fe1d5d21d729ebcb7034e379a8039a6ccdf5f5c6e4470e02", size = 12989 }, -] - -[[package]] -name = "pyobjc-framework-gamecenter" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/46/2f/82cea539bd5a3c764c7acb065face9d1176011f58643323fde30f05997cd/pyobjc_framework_gamecenter-10.3.1.tar.gz", hash = "sha256:221ae88ee69816b95861b1a0dc781c1c17775d38fcf0388327620535479b6a07", size = 30111 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c0/0c/4d598091446f6df9b425b3c9d754d29a69b14a7662a3b19e3c47e482b23c/pyobjc_framework_GameCenter-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:eba1058859fb30bef8227ce649dcf7531545aeff81c3cfd3e3b80ef8fe87bf70", size = 19192 }, - { url = "https://files.pythonhosted.org/packages/40/26/47ed05bc86f1fb24ce9261facfe23d6ea264d7af93a22ab6d831dfce6560/pyobjc_framework_GameCenter-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:3329261e8a6a3b0df3abd4a7a3cc66cc8e47be919279a08249e08f94a0e4448f", size = 19226 }, - { url = "https://files.pythonhosted.org/packages/68/05/19df2f01e4d31f752c47ae667a1a9302b3fac7db9d126d35788c2a4fac62/pyobjc_framework_GameCenter-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:d2420c7d28f9eab337955a1872179295ba92e3d8db0e5b1b8d40442e7079d711", size = 12705 }, - { url = "https://files.pythonhosted.org/packages/e1/39/b6c69bacd37b96143b7dd61be6bde201a7a5058ee085166cd42600927009/pyobjc_framework_GameCenter-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:6bd556e798cf52b94434c48cabf299060dd79b668f0021826995ceee520db8af", size = 19224 }, -] - -[[package]] -name = "pyobjc-framework-gamecontroller" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/49/6e/1ee46fe9870ce020529ce883c04291a7c7f43adad2b6fbc9b0c44d2549c0/pyobjc_framework_gamecontroller-10.3.1.tar.gz", hash = "sha256:f9f252b5fed5de2a8c7fdd2e302b6ed6e0b82015d7da75b28984c5ea5909345e", size = 94100 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/dc/8c/d307f5ce6d03f552f66fb178d8da11bee59b410ff58538a5a4801195d606/pyobjc_framework_GameController-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:cfb754d29660e90f295ba443cc84fb189e5ca9d1f019c35a382cb24dd4e08bf8", size = 20409 }, - { url = "https://files.pythonhosted.org/packages/21/77/279da82f58d551fde28594a26180245b373a52c8b77fb0430e8099e69575/pyobjc_framework_GameController-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:a7a1e34a4ebcf9f653bc4a066b7d08d9124d462bc7e1c434ead983a6ae093382", size = 20424 }, - { url = "https://files.pythonhosted.org/packages/00/ea/8298cf9776d26890e97b7718517e4313acabea2a574f3bd0e655dce74dba/pyobjc_framework_GameController-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:a23bb9c97063fb334990cac20dcab1389942495cb028350a232faebb804d73c2", size = 14112 }, - { url = "https://files.pythonhosted.org/packages/ab/62/278908b0a50d654222ea699fcb95f9d8830627b6eee029fd0a0b576ccd6b/pyobjc_framework_GameController-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:e90afaa5a5d28771e60b4f60ff89b80037d4e9e558d680872810216299aea1a8", size = 20487 }, -] - -[[package]] -name = "pyobjc-framework-gamekit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/84/aa/897e74e41c80f0eaec994c4b0852e680e5eb22868d3a4681b46f06cf4032/pyobjc_framework_gamekit-10.3.1.tar.gz", hash = "sha256:7d21a8f45c32ac94ce0e70b6c6fe72928fe75cb1a6bd6d7715e2bf39b291b70b", size = 137591 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1a/b0/c0818f700b2df034e2b3b43643e7c73dbba3c72e1ce0a1494753d8591847/pyobjc_framework_GameKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:57930e2b65296719b2998c9816ab844983460f3358c57a120f09ebe78013b64c", size = 22352 }, - { url = "https://files.pythonhosted.org/packages/8e/93/cd9ad8514ec750da969eefc1466ce0d43b14fd4c51bf10daf5d5396513df/pyobjc_framework_GameKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:5634ac5f8b3569355f4fe8b2e6a06450d8aee555119607f7d738f5c85900c1b6", size = 22385 }, - { url = "https://files.pythonhosted.org/packages/02/0a/9a4459f0feb2b8dc9ae8408f47121efeb263e5d90ed73772691055795c4d/pyobjc_framework_GameKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:83f689c959cdfaa311f6702d9e99402faf47e390334fb3880d255dc72e2d2a90", size = 15690 }, - { url = "https://files.pythonhosted.org/packages/53/e5/39cd4287f4d49114328c931fbf04b5870e7e6178eef4eec0d54a76813b7b/pyobjc_framework_GameKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:c861e575ed4543241adbc53162fb651395ba73c68a697f4b5aceaa61754e19c1", size = 22392 }, -] - -[[package]] -name = "pyobjc-framework-gameplaykit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-spritekit" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/02/df/3a6e19a496dec873d26f255458a3e557f6e3aa004f04ca83f9de4e85e9e8/pyobjc_framework_gameplaykit-10.3.1.tar.gz", hash = "sha256:2035b81f7bc34b93636753cc3f9b06cd08171afc5c95bb2327a82fd3195f3c36", size = 55768 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1a/7a/d9ed333da4ec5a6dfeb2ec4634aaeb37208e71eb58475dcc15508d39233d/pyobjc_framework_GameplayKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:cb54cfc4dbc69f1888c59ddce9da97ddc03f5003794fe47d56942a89c478e138", size = 13800 }, - { url = "https://files.pythonhosted.org/packages/c6/09/ab7746307ba028d8921022d0d54950e3c232fa01003f31bb7ee392b1873f/pyobjc_framework_GameplayKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:eb49a732c82b17ff66f6e878b2cb9ba27e2222be303a337f2af4ed1a34a404bf", size = 13848 }, - { url = "https://files.pythonhosted.org/packages/4f/50/d0ee718890009926586a5f3d3df538cbaa594573660268c20eb777110509/pyobjc_framework_GameplayKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:8a0c2148e9b421922accfe565a398effe9622653c71d0bb4eb1b69ac90ee257f", size = 9859 }, - { url = "https://files.pythonhosted.org/packages/85/f2/78fc1e58328b9890355716b38c2cdfd11ec9d130f90a5be2ef68eb8d78b1/pyobjc_framework_GameplayKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:628406ca0d0ce283cc0735a4e532dd04a3a4d57a4c22c3ee4338ba64d1b13790", size = 13711 }, -] - -[[package]] -name = "pyobjc-framework-healthkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c0/68/fdda86963c5b3f86941623176acc2d7df03183ea9d3bbfff9088283d2bd2/pyobjc_framework_healthkit-10.3.1.tar.gz", hash = "sha256:45622fedb42bbd95dcc096248bbc41dacd857d9db120ff7310f74f3bad4b23e1", size = 113769 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a6/b7/532df1501af543fa78383d440818c07badf6911931da7b79da5fc33ed590/pyobjc_framework_HealthKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:80aee8bf0e7af6e434e9023c2d2050c2a2fe8e53abbf0e1f2285a932836fdd17", size = 18910 }, - { url = "https://files.pythonhosted.org/packages/f9/d5/33b2e71ac4089a96031da4e079c79545d09b2acfa720987ee08d34f73e4f/pyobjc_framework_HealthKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:ac9abec44c02edfe7f2151f529bac1c9544fb99ee1caffff55b331281b374463", size = 18964 }, - { url = "https://files.pythonhosted.org/packages/fd/99/8ed9d4ef41c1be5a3807b9bcd97abe4e1e152d587478e07a9dbcf2f3dd51/pyobjc_framework_HealthKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b64d4e61a8009a0a5586d464b591186570f654b20937f78941875ef3b7865505", size = 16426 }, - { url = "https://files.pythonhosted.org/packages/a4/3b/4b52e663b5243eb62cb836300d5b6e2c425f4b027a0b31133d10093449d7/pyobjc_framework_HealthKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:5bfcaac3a3947d070611d1fed1abe8858e049ef0ab1050f46974a7333b6369f6", size = 19429 }, -] - -[[package]] -name = "pyobjc-framework-imagecapturecore" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2f/32/36b2b34e2ae902552854c1e5d24cb4d587875f4400791a30740213f57178/pyobjc_framework_imagecapturecore-10.3.1.tar.gz", hash = "sha256:9ce83c38b8ccee6b022faadb9cd7b8716119092cd41b6c2cabce3670101119bf", size = 81896 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3b/2e/416250b77c56389059d9456a214d7c9e64c64e2f25d22d3f30a29dd4f327/pyobjc_framework_ImageCaptureCore-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:649e0b7bf428ad3fe90faaf63dbd09d234563a32b3cee5a6f2d28ab31927bd54", size = 16958 }, - { url = "https://files.pythonhosted.org/packages/62/cc/4e3a24a111197c29c863432ed5d5eb80a347f8e63a035e45d8d4691f6692/pyobjc_framework_ImageCaptureCore-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:5bab844c665b3ac07b191e94130f543eb23c5cfd014035f025efacb7a48aa68c", size = 17018 }, - { url = "https://files.pythonhosted.org/packages/59/50/f6b84e10e09ea683bfb1cfa2ef0e7fdec983697178cd6d156bff9d6f6554/pyobjc_framework_ImageCaptureCore-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:0fd14f9183c1fcee67cf09f36ccbe156186da84a83419917fd3ca81a5de23d97", size = 12770 }, - { url = "https://files.pythonhosted.org/packages/bf/b5/2d667e372f66db8af3a8dd9d3afcc2907f78bff44deeef7b38245348c374/pyobjc_framework_ImageCaptureCore-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:d625d84094f51dd4389d1dea7c53480c3311dd19447d96b3c9eb06be5a935fd6", size = 16880 }, -] - -[[package]] -name = "pyobjc-framework-inputmethodkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3b/1b/28c9e10640e0b73dcd7b4693c9ee1fb5519443bd8fd5debb0066261a0abd/pyobjc_framework_inputmethodkit-10.3.1.tar.gz", hash = "sha256:637ba2da38da5f558443b4529b33bab276380336e977807347ee9dad81d42109", size = 24489 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/b3/9e04e21ce92cb822dabdd30fda046ac1ba17015cb12e8902bcd4acfd1a93/pyobjc_framework_InputMethodKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:d1c3beb88f94eb6b0bdc458ef49f331d064c0260758134cef1cf941684f46c83", size = 9532 }, - { url = "https://files.pythonhosted.org/packages/30/66/7480b6ca7654be7964783a1195b2b928c0cc2b22e34d8f225bcdfe9ee7ad/pyobjc_framework_InputMethodKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:d0f7538ac549b61afc93df895375114464f778e06a66a4c2684cbbf247a8f4c7", size = 9592 }, - { url = "https://files.pythonhosted.org/packages/72/18/c1e5a19310f27df1aa35e5eefb7245f0927bb6663085ffab1a4016ea5294/pyobjc_framework_InputMethodKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:7f5ff42a59209f3ede24181e5d1bb8d69f8ad428189f177c1bfd55d328f85575", size = 7461 }, - { url = "https://files.pythonhosted.org/packages/4b/eb/dfc9f160481226e2e46b4d94772aa2063ef87d4431f51fbd0766949951e1/pyobjc_framework_InputMethodKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:3fcd444b97cf2343a6c37b828dcc85080cc6a2c5ba508010dae4ebe836480d2b", size = 9786 }, -] - -[[package]] -name = "pyobjc-framework-installerplugins" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a2/cd/a9594b8200b1460630d21af18c9fc38741ff748c5457bf5958c5599795c7/pyobjc_framework_installerplugins-10.3.1.tar.gz", hash = "sha256:280808bbce36090b59197756fdb56c19838845a5fc25966a435dbc5fc4ddbbf0", size = 26514 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/52/1a/06a5d257d20dcb64f9f20c4fb7cc518016add734a70c9547676af0d4131b/pyobjc_framework_InstallerPlugins-10.3.1-py2.py3-none-any.whl", hash = "sha256:2b32cde6fb8bbb3e1ffd04d7acbe3132291ad5937fc7af5820062e8aece7b5cc", size = 4392 }, -] - -[[package]] -name = "pyobjc-framework-instantmessage" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c7/fc/51a0707b48507ca4963333452fd17119cc325bbbefdac460bd960f6a935e/pyobjc_framework_instantmessage-10.3.1.tar.gz", hash = "sha256:bb1560a2f92a2def179b6381c17d406331b7818fa0fd1ba98f09ed94415f8a7b", size = 32767 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0d/04/089eee187804a418167d901c38cc4bb7cfb7045b53756fe3404011161a5a/pyobjc_framework_InstantMessage-10.3.1-py2.py3-none-any.whl", hash = "sha256:51a096e55a423423dbfbf19cc976a49915987ce68b9038f8ce3db9c3cde11718", size = 5016 }, -] - -[[package]] -name = "pyobjc-framework-intents" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/64/dc/120a1891de4ea2c4c5fa382100ac9706dda75a64dd6185367ddc8d89710e/pyobjc_framework_intents-10.3.1.tar.gz", hash = "sha256:89f0ed49c515b75c8811d9f6771ac635e799dfaf11921172729f8e0857c8c0e9", size = 361884 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/82/32/4050983e2d7a6d7ecb5eefd49e76f173b293862b27ae5e8850aa1c8d6fd1/pyobjc_framework_Intents-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:4d5a899e8cffd63096aec69edafac78e76d591afd07059a96377d6893ba56649", size = 32440 }, - { url = "https://files.pythonhosted.org/packages/49/30/71306e19f0f52658474a6325387b384459137b4a5ea302f41d7eafa7f508/pyobjc_framework_Intents-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:b6da33ba8a1e6ae169eb67c1c83bf4e0aeb365fb368162ba002ef26cdc9f853f", size = 32474 }, - { url = "https://files.pythonhosted.org/packages/53/17/ad5540101c620f98bffe55969861b64a65bf87f6269702be5345dc9c733c/pyobjc_framework_Intents-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:332e5b74dceb8315e289d462058b9ec65544562936098b50b8003999954032b6", size = 26862 }, - { url = "https://files.pythonhosted.org/packages/60/b2/a58d92da0d457754ead621108cca76c7157a9dba94449850389bac10a226/pyobjc_framework_Intents-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:6e77fea5fc4136888459c8ece7d48fe3eac3a37c665e9ba8aaeb18c1671eb083", size = 32464 }, -] - -[[package]] -name = "pyobjc-framework-intentsui" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-intents" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/df/51/3cff5de2db25fb516eba66480e90ceea293fc12d715d51a16ebb242c0893/pyobjc_framework_intentsui-10.3.1.tar.gz", hash = "sha256:68f42cabbd36889060d07b21f156f1dae78243d42b34c652448c687d07cbca62", size = 18822 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8a/ed/adbe8714da27be1056a936e51cfbba36bed6046ba1fedc3f54b006f7f0cf/pyobjc_framework_IntentsUI-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bd2fed37c96f1d97abcbd6d98b2da90ba2c744f968e2c4e0735dce77bbbc95f4", size = 9607 }, - { url = "https://files.pythonhosted.org/packages/6b/fc/97bf965283261206b971f329a7d02180cdf14ad5a30d5cae2f9962b0153a/pyobjc_framework_IntentsUI-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:e9fe0ba78c9dd500ef9c13227dd1a60e39df460c84180d8325f5022edd80178b", size = 9642 }, - { url = "https://files.pythonhosted.org/packages/ce/23/d23acf3e451bc64d40d2b7cf0e03620399a3540c74b16e8d5b6a191cfbd2/pyobjc_framework_IntentsUI-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6c124ceb8e7b7a1f3fb6c2c159e47f9dca42ece6e1645d763235660ea98e7915", size = 9591 }, -] - -[[package]] -name = "pyobjc-framework-iobluetooth" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e9/98/b6aade04f7e07de0e81f0312c19bbd21ea61986ab8158a0986aec6c5efd5/pyobjc_framework_iobluetooth-10.3.1.tar.gz", hash = "sha256:bca424889d7fdd5bcb728d312e91ee681e73c0c2ac16ba37068603d699043d39", size = 226060 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a6/4f/d75da040aca8563c56e2a7b5322ee236e2bfdb71181f761e846a5b759c88/pyobjc_framework_IOBluetooth-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:cdd8bd3da07c6935657bbcf47e6fc6b3b7a2ed9bd7e8ef83bbbd5f4a0e8884f3", size = 41473 }, - { url = "https://files.pythonhosted.org/packages/31/0e/bede89b5275ad1af549f86de3ec9395d01b1bb6db5592e2c4d69fa242776/pyobjc_framework_IOBluetooth-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:d5c7ca666050b63c5dd87ede54beebdba7fc12a60bd754d77155da9f7e60618c", size = 41527 }, - { url = "https://files.pythonhosted.org/packages/7a/9c/c8dad67d2d990fffb9ae1adb8452147076e2d1d2405634e319e6757a97b2/pyobjc_framework_IOBluetooth-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9f90d8ea40f770b41ad97e17e19ad10e49daa1684f750e681db42707dbec9768", size = 36977 }, - { url = "https://files.pythonhosted.org/packages/82/c9/4c7bf05da12c96657b51568be9177cf6a50b9ce0aa852d016f5d24fed68c/pyobjc_framework_IOBluetooth-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:17303009a3c1ac48eaaa2c3a96a114ef47adcb1fffbf965e7538447bb02adde1", size = 41421 }, -] - -[[package]] -name = "pyobjc-framework-iobluetoothui" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-iobluetooth" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d4/e2/3793269efe06505b1b4224ea395912c697896054bdc0bddcc3889796ceac/pyobjc_framework_iobluetoothui-10.3.1.tar.gz", hash = "sha256:6db82aeb360641b878f8ed73c2074db0425664d9411317b2e01962e0929fa29c", size = 19226 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d2/b4/47b9746727a7a199d674bb864525016bf2d22aae7e58021e96cbeb70c048/pyobjc_framework_IOBluetoothUI-10.3.1-py2.py3-none-any.whl", hash = "sha256:ae283c3fecbeb99adba9b3c3d5d06caaad741da726fc7a1dd50ecc0376e03ae8", size = 3653 }, -] - -[[package]] -name = "pyobjc-framework-iosurface" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b1/45/8cc7def9b73ec0c3423b7c4878ee3e02fd27e72085574f4c5b7b284bebc5/pyobjc_framework_iosurface-10.3.1.tar.gz", hash = "sha256:94e4a109a94f0e365bd60ce68aab6ff166fef6f30a40f7682c76902f5fc3aa34", size = 19262 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/36/2d/c2519d5d8e78d60245d7336d2f44a48041b5ffee9b8f2bac9f5672033e6d/pyobjc_framework_IOSurface-10.3.1-py2.py3-none-any.whl", hash = "sha256:4171a33a09ee006ad28ba29e6d12cee821e2c0ba09b4beddae8db16580fb9bc7", size = 4572 }, -] - -[[package]] -name = "pyobjc-framework-ituneslibrary" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/53/a8/63766d37cc93e2a92a53bb3b5dc769fed0ac27509bfb251cb94878792432/pyobjc_framework_ituneslibrary-10.3.1.tar.gz", hash = "sha256:3899f8555ae02f6441a711892cdc6537404215b3d5f8a7ea4594f7460c58c9b2", size = 40017 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f0/c7/05cf8de68b85c574cf5929a4771cbdbd4ae2448d3381d4ef7f5066e510fe/pyobjc_framework_iTunesLibrary-10.3.1-py2.py3-none-any.whl", hash = "sha256:9485e986f6075d04e10c196e5dc36e4c3b60116a45849683a61c876e5fb45fde", size = 4821 }, -] - -[[package]] -name = "pyobjc-framework-kernelmanagement" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2a/b2/0c894451b949023e00b76e17e46ce65dfa30e5005c5500958d6f90a20fcd/pyobjc_framework_kernelmanagement-10.3.1.tar.gz", hash = "sha256:04c41bc0d0ce014318acf9e333aba302092d2698ec408cbf0b022f3a507ecfa1", size = 11933 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d6/75/140a6075df7c97c4e70014e696066d5b077d4116b9228287d87f63f1c1ca/pyobjc_framework_KernelManagement-10.3.1-py2.py3-none-any.whl", hash = "sha256:e07134bf3815370d3d9c37f9813edec12758f86fdbbbc67036ab72e8b767ddee", size = 3279 }, -] - -[[package]] -name = "pyobjc-framework-latentsemanticmapping" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6e/17/435b483033f21fa1d95132e93c0cedbf93567f00e6ffb579989e0c070f9c/pyobjc_framework_latentsemanticmapping-10.3.1.tar.gz", hash = "sha256:0bca94fd00f59f49874c8266bfacb09a7c56ad13b4d405c241421cef201f8943", size = 16630 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8c/ee/af2199401d4a6ce71b195338a2fa63bba0d33d9402622146906b741ec601/pyobjc_framework_LatentSemanticMapping-10.3.1-py2.py3-none-any.whl", hash = "sha256:c80c709b983273c8f29e86a04c52e98e8e6b0e723a400f7d6036fcabfd850367", size = 5035 }, -] - -[[package]] -name = "pyobjc-framework-launchservices" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-coreservices" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/34/dd/53ff73cc0fbf1ad21d3acdd387830f793541dd023150866853e4f00d8dc1/pyobjc_framework_launchservices-10.3.1.tar.gz", hash = "sha256:7f16af2acabca0c2953eb7333bfe652bf853bb9d9e59b771f9d228468bccdea3", size = 20012 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/56/77/848cc9be87327fed05e46a67ffa5abcc0edd5c0777c4b98b6e2e6537882c/pyobjc_framework_LaunchServices-10.3.1-py2.py3-none-any.whl", hash = "sha256:3ce840027b43c4bd95dc31aaa9b4bfff1d431e782669b4c95e2b12d386c05000", size = 3489 }, -] - -[[package]] -name = "pyobjc-framework-libdispatch" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b7/37/1a7d9e5a04ab42aa8186f3493478c055601503ac7f8d58b8501d23db8b21/pyobjc_framework_libdispatch-10.3.1.tar.gz", hash = "sha256:f5c3475498cb32f54d75e21952670e4a32c8517fb2db2e90869f634edc942446", size = 44771 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5b/8b/44d0a44bfb68ead2481f95516f1d791e6e72667a9514c36d8d7df87a58bc/pyobjc_framework_libdispatch-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3e0db3138aae333f0b87b42586bc016430a76638af169aab9cef6afee4e5f887", size = 20491 }, - { url = "https://files.pythonhosted.org/packages/40/1c/4d16cbe1d41462184e908d757537349cebddc7444950ea24dfbaf2a957ca/pyobjc_framework_libdispatch-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:b209dbc9338cd87e053ede4d782b8c445bcc0b9a3d0365a6ffa1f9cd5143c301", size = 20542 }, - { url = "https://files.pythonhosted.org/packages/fa/36/c95b42c290d41687c2f01599feff82f4b6f9774006c4dd051f5d6a9949fe/pyobjc_framework_libdispatch-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a74e62314376dc2d34bc5d4a86cedaf5795786178ebccd0553c58e8fa73400a3", size = 15643 }, -] - -[[package]] -name = "pyobjc-framework-libxpc" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8e/9d/8a7eb8d3570f2f41fd265513655fbf28e2ab93155a0053f46277fd61b097/pyobjc_framework_libxpc-10.3.1.tar.gz", hash = "sha256:b3c9e9fd281b5610e3bef486e91570b0afa8ab8eb0c01c0baa5e2ec49ccb7329", size = 39868 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/14/58/70effee80f0f0f840b6e6639252cdc749a4f7ee043d2ad66528ce354b507/pyobjc_framework_libxpc-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:e0afba29b6bf5c3de3ef51f60e06c026ab7be7ce44600047dece5d3bf4e758af", size = 19484 }, - { url = "https://files.pythonhosted.org/packages/2c/5f/bd9bcd9d13a1ccb61c906b68f998556b3319ea83ce722be7ee5559103ce5/pyobjc_framework_libxpc-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:123b72dff148a56d48120448bd9742190326f87661f4ae6f5363e112de0e554f", size = 19582 }, - { url = "https://files.pythonhosted.org/packages/8c/56/ef3ede2cea30acf4b251a5da5a2f32db17486acbf66ab8cfc28ae2a922d5/pyobjc_framework_libxpc-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:72a35a21f4bbbfb4a5c4c23e3180c3273b7720fe4cd150b975cb5d08cbc4fe13", size = 19531 }, -] - -[[package]] -name = "pyobjc-framework-linkpresentation" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b3/f2/8317cff954187875cc82dd8a08de69adbd1efb48451cd2b6836f347392db/pyobjc_framework_linkpresentation-10.3.1.tar.gz", hash = "sha256:535d452cc33d61074ba9bad7707d6c0a23d474fb045ed4322e5f87bfb0b7e865", size = 14174 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a4/6a/6347826cc12c01bfd2f6c804af1d99d4df8cd74440a412562b72cbbd97f5/pyobjc_framework_LinkPresentation-10.3.1-py2.py3-none-any.whl", hash = "sha256:e49ac094eb3a60a87f37edc24657feb051614a4d4464ad2580831288ead521f9", size = 3467 }, -] - -[[package]] -name = "pyobjc-framework-localauthentication" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-security" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d7/a9/bb2c2c3171a600dad5c7db509cdeef5a1a3cd7a22266a515145ebd5497b0/pyobjc_framework_localauthentication-10.3.1.tar.gz", hash = "sha256:ad85411f1899a2ba89349df6a92db99fcaa80a4232a4934a1a176c60698d46b1", size = 26240 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/98/d5/3d5290b829f1f722b7593e01cc06406d6de404a35d91640241d885e2c01e/pyobjc_framework_LocalAuthentication-10.3.1-py2.py3-none-any.whl", hash = "sha256:565910d7d2075cd53c6d4ffdbb15d9b93267f1b1ba4c502d354778865d0dc2ec", size = 5678 }, -] - -[[package]] -name = "pyobjc-framework-localauthenticationembeddedui" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-localauthentication" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/00/36/ba89365d6bdbed5db435e0b4e2dc310a977dab5a306453c4f7ef8de745f2/pyobjc_framework_localauthenticationembeddedui-10.3.1.tar.gz", hash = "sha256:f915190f6106b9f9234750abf48f87445c364ccbca8f8dd565bba1b66ddd55a3", size = 13305 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/bd/e5/a393e16847f7605b80c643e961f60bed3c6c3b4758693907cdf88058a9bd/pyobjc_framework_LocalAuthenticationEmbeddedUI-10.3.1-py2.py3-none-any.whl", hash = "sha256:d69ef723f4525e6476e51bd166d56e97c9274500f98aa209a659e7567793dc01", size = 3559 }, -] - -[[package]] -name = "pyobjc-framework-mailkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d3/1a/683f99e9af1966de9173c1696946ec52b7d45d346aee8a638d1104eade95/pyobjc_framework_mailkit-10.3.1.tar.gz", hash = "sha256:90ad82786ae01a275aeec842e73b1fef12d9f91a67edcde8ff6a145859dc9f92", size = 26043 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/21/99/b91c7329119c9ab2397307cb5e37f0e27a8a31fefbf8376cdc1b07b76ba6/pyobjc_framework_MailKit-10.3.1-py2.py3-none-any.whl", hash = "sha256:7c403525e01bed0888946552e512ca4d1b018c3f6ef3d293fff85b90dc02a411", size = 4494 }, -] - -[[package]] -name = "pyobjc-framework-mapkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-corelocation" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/53/f3/1f711e0311ddf3a838d1fe2ec1ab7c52cdb52d4a6144edcd2bd49becbe6c/pyobjc_framework_mapkit-10.3.1.tar.gz", hash = "sha256:f433228c404b9ef4a66e808995daccc1306f7123296317651078a6a734ac1ab0", size = 135465 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4d/b8/03c9b2de80e18a53df9d0f0881fd08015beb4cdf8e4d28d76f25c6315089/pyobjc_framework_MapKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:cfee94ad82e673eaebc3159732b5cff1fc4f7e3bee6f17cc4fabd641c260b769", size = 22766 }, - { url = "https://files.pythonhosted.org/packages/48/76/e957f714814e21c25b579d4bb98f13b92c8f17f8666f8b4be89705a0a3c0/pyobjc_framework_MapKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:dd65d6eff1397afc0b2108b0e9387a6c2390b1387731a8e0dd8298b8d0641635", size = 22999 }, - { url = "https://files.pythonhosted.org/packages/e0/8d/d1248ff4a2ae562a0b00a19e4b9c1b5077045e7e9b6e7c0e4a45b39605dc/pyobjc_framework_MapKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ffadc4968c3d815dd8ffc2867e962546a8681620c704888dfe1e7aa718cb3d90", size = 16246 }, - { url = "https://files.pythonhosted.org/packages/7c/bc/cb3ccf25e51650bce1a91f680aadf646cf238dbe92a38b73fb5fe17badbe/pyobjc_framework_MapKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:f14f90bcb68baee70a838b3cecb9d909da43175da49cbe90dd6cca57c37a6ae5", size = 22852 }, -] - -[[package]] -name = "pyobjc-framework-mediaaccessibility" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c1/d9/e82531ed727311b54bbbeb9da0bec5c098b8cf8017d541fc77175f4bf322/pyobjc_framework_mediaaccessibility-10.3.1.tar.gz", hash = "sha256:c249e1eee636e77b5f00db3bf85174cb3e0cb53ca991a17e53a1f200377f4289", size = 16607 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/87/01/0adc256ed71a620be9fd357ac72b51a5b08af175104778201e0873de651f/pyobjc_framework_MediaAccessibility-10.3.1-py2.py3-none-any.whl", hash = "sha256:c4304ea53c7e85320b58d773cce2288f62dcb5b9c5a295be1ecfaa6645a9fea6", size = 4113 }, -] - -[[package]] -name = "pyobjc-framework-medialibrary" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/01/1c/c8355ad906e2051a3d73bef221ce559f417cd58e94dc5af1163bd3669c09/pyobjc_framework_medialibrary-10.3.1.tar.gz", hash = "sha256:703ffd0904fc86d4fbfbbd4952be43e91a6d477c53ce2868e4c18c3eb295f5c6", size = 17661 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d7/f8/d4afc0ccb1506ba85a873a238db934a83c349440f09c64d9ed287d5c5a88/pyobjc_framework_MediaLibrary-10.3.1-py2.py3-none-any.whl", hash = "sha256:25f16d610e3ea5d983175a6c07351596bd5dd2fcca194f1eac5686c670bbdb3b", size = 3974 }, -] - -[[package]] -name = "pyobjc-framework-mediaplayer" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-avfoundation" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/10/00/6d991d13624e8e9288ee289945737bd7e48cce6df7497ee25f2c39c4d173/pyobjc_framework_mediaplayer-10.3.1.tar.gz", hash = "sha256:97043df5ef89d4fbe217813e8f4ee1e226d8a43dee4eac00fff95e6b8a7772be", size = 77337 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b2/40/92912923eabb827ad6d97205d6091575118e312d58efd190766b38bb3b55/pyobjc_framework_MediaPlayer-10.3.1-py2.py3-none-any.whl", hash = "sha256:5b428cc28e57c1778bd431156c3adb948650f7503f266689559d0ece94b34e8a", size = 6548 }, -] - -[[package]] -name = "pyobjc-framework-mediatoolbox" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a6/8e/a4abb578ad0207ef723fac1255738ea2a3fab3c5b0b0c49a3bb30463257f/pyobjc_framework_mediatoolbox-10.3.1.tar.gz", hash = "sha256:f141056dce0dc16ec21be596fea58acb4a668045f53e12a0f250990d936b44f2", size = 21516 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/60/13/6e20282c95f86912f7883cfba346366eaef41148fd1f3de150bbca72b132/pyobjc_framework_MediaToolbox-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:d4ef616e233c40fcac99298ee4ab95a9b6439cffe28e96ce07b66c00f598bd30", size = 13236 }, - { url = "https://files.pythonhosted.org/packages/67/dc/e05fbf599d579a6a77b150ee764bf7d3012bbe02dc386c11e7a45cf08d92/pyobjc_framework_MediaToolbox-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:a8acfa377b593b043e8c9ff1aa6cbbde92b7feaea60578ea2d0b61ac3edd15dc", size = 13297 }, - { url = "https://files.pythonhosted.org/packages/03/02/f0494b7b0556d8090efc19421c640bc8ee624b3638ead8201636c03edeca/pyobjc_framework_MediaToolbox-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:f989f07304dae82b1307e179f185a80b66ed36b0dd15d1b3bf6ec8092b766100", size = 8145 }, - { url = "https://files.pythonhosted.org/packages/54/0d/ba00d64c83e4465f53f36af9e879749a1634b43c2ea0888a6bb7e0ce03a7/pyobjc_framework_MediaToolbox-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:4114fb3749dacf6dd83113823b846e77671c0e8b1209ca6e4402f09e6727c185", size = 13024 }, -] - -[[package]] -name = "pyobjc-framework-metal" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8c/5e/2df5fdb85a5753ebe6e1a1b1905da565a408a4f090f7c1d89f3a3143d18b/pyobjc_framework_metal-10.3.1.tar.gz", hash = "sha256:495307db0bfd2063f28b7c8fa350af71afcfbf5f5f2186a6a751b4cb2ef46a1a", size = 299751 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/40/405b6d09b646756b450dfe9b47f9fb4c6a8cfc93dd94bccf2e4469c03ab3/pyobjc_framework_Metal-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:4a42f3aa47eb5e0d3f29bf07f239c2ba33725701546ea6d3c5d019133e0fbce1", size = 55675 }, - { url = "https://files.pythonhosted.org/packages/2d/09/3bcf777771e3db8cf692d64395e78555dc158098eb6a49ebf8d55168941b/pyobjc_framework_Metal-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:cc33d05e376d3a2f42da24b397f6353d9cb8e5990c79c9255a82637b7b8f256c", size = 56186 }, - { url = "https://files.pythonhosted.org/packages/09/cd/763b1469d6a33687bae43a489599db7942f2788e1d9a1d499f132dd0a504/pyobjc_framework_Metal-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:22762ba170d0fc4538dd7f582da1fd7673160e369eca74efe3d6d35bfdd50522", size = 38287 }, - { url = "https://files.pythonhosted.org/packages/43/e1/86702984f0f229be8ccc6c3f02f2d3598b67f17e898590ba127229fcbfda/pyobjc_framework_Metal-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:7fef3ebfd6cfbd7cbfe45aaa86dd32034303d933871d8450f4c990dbdefda176", size = 55756 }, -] - -[[package]] -name = "pyobjc-framework-metalfx" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-metal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5f/b0/a479ef7219d4176806e6f49718da59feb1dc222605f45f5e06777a6c6a3c/pyobjc_framework_metalfx-10.3.1.tar.gz", hash = "sha256:3ea0f259397523a84a320b3925dcaaa5c039494accc3cb412b63e6f7f66f9513", size = 21547 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/4a/0490ead36e933453bf7de321a38831c5379753b8f748efd1eb2a1eb649fc/pyobjc_framework_MetalFX-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:ea4bed69e6a9ab4cd4fa6160554cb7df72316e849a34b839bf8d9c69ab445b24", size = 10514 }, - { url = "https://files.pythonhosted.org/packages/a1/f7/f4734b1d4fce902c6c5b57e095924f7eee03d960ff77e7f4067c16da5165/pyobjc_framework_MetalFX-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:f3ecae357688a4730191d57ffbc3db6abb950b756e8b98f23689d4bf08f34c20", size = 10566 }, - { url = "https://files.pythonhosted.org/packages/08/63/262ed4e448880398809e047d836a53b4310e61b4c737997507e51d221a8e/pyobjc_framework_MetalFX-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:0179ce8ac828b6d6e2542d2d4f68850290eb3f16112205a758419225dd51b448", size = 7042 }, - { url = "https://files.pythonhosted.org/packages/2b/07/5597fc8d24cb3b01b7fdcb1986a41e5f2edd9aae9ba253b4d736768ccc73/pyobjc_framework_MetalFX-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:b3ae624f7e0a5c60b856889753af560b7cbd1a5f47db01f120a668e429afd1c9", size = 10490 }, -] - -[[package]] -name = "pyobjc-framework-metalkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-metal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f0/6d/c5a782ee9def0feda16cf41c7326680f306293f4446185f3b0040e3e956c/pyobjc_framework_metalkit-10.3.1.tar.gz", hash = "sha256:905eaad9dce29082efd5cc56195337d2e8bff86ccfad36ec5127f818155ec038", size = 38269 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5d/aa/3ec47cb09ae256e118f4f54f1759503714ff2a47474ba3f0fd7a83c3b5bf/pyobjc_framework_MetalKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:c198c61d967812837538a793b1ff862bbd868d954abcd6ee558662c45c4dbf12", size = 8782 }, - { url = "https://files.pythonhosted.org/packages/9c/1b/d8fc542e7ca1c296439fbe17d96c45943ad265c63727e1d03f988a931246/pyobjc_framework_MetalKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:7c0155d731766be52cf18de6ad61339c16217bde330e17ef50808366856c1b85", size = 8840 }, - { url = "https://files.pythonhosted.org/packages/87/ef/cd801629d09a8d9f5eb9d95b8c1809c48752bd13d1e0ba049b73bb627ed6/pyobjc_framework_MetalKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:48ae5e7c81c97e231c52036c8e2acb22bb59feaf0cb13f7678c87b16d9faaf9f", size = 6581 }, - { url = "https://files.pythonhosted.org/packages/b2/b1/d38a5a62ab8a3db2728474370c3aa3e8fd21b889f2093eb4365c8f4bb4bc/pyobjc_framework_MetalKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:de632a7cdca1a0a13097a363dd441b9550ad91de6da6c88952c77acfd4b3a100", size = 9134 }, -] - -[[package]] -name = "pyobjc-framework-metalperformanceshaders" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-metal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/4a/f5/d6b25e063691ab304ed39b3d8121262f661b2e56630bf3b07476134e08a4/pyobjc_framework_metalperformanceshaders-10.3.1.tar.gz", hash = "sha256:1a9e91dc9e748834c95b7a596b943203761f6533352631c7abe612f804b23d50", size = 215419 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/9f/ca54b26d1fbaa3589f00d3e55107b499017ec7f4972b46f808513f45bddb/pyobjc_framework_MetalPerformanceShaders-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:a6f72fd528033ff0b176e909394edfc34f90b711fc6dcb225ba41b042929b71a", size = 33033 }, - { url = "https://files.pythonhosted.org/packages/1d/93/58b86080d4008854fd071f4d46589d394133a4a61795ee55959beec762f2/pyobjc_framework_MetalPerformanceShaders-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:59c971d79c0d02a451571cd0122296aba05b46d7eecedea75ed8ce892d1119a1", size = 32981 }, - { url = "https://files.pythonhosted.org/packages/12/f4/1e02afb41d226afdf64b38c8a34af9f5690c08c988d1cb12247d82ca7c5d/pyobjc_framework_MetalPerformanceShaders-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:969bc8caea30d71f963fb763c8d837f36d403e47c1ff6ed449ceb09783322944", size = 26388 }, - { url = "https://files.pythonhosted.org/packages/0c/ab/1b7e063d30e65629c653f4af89cf3072ede8a3f99cb1a690dd73d7bfc934/pyobjc_framework_MetalPerformanceShaders-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:b02da6a5dc9088cadf38dce21aa39027bc668493876d3af684b91f039f123df2", size = 33121 }, -] - -[[package]] -name = "pyobjc-framework-metalperformanceshadersgraph" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-metalperformanceshaders" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e6/0c/c00edcdc19f692d0d261d2a0c43f296f240c236704666e287e60dea23edd/pyobjc_framework_metalperformanceshadersgraph-10.3.1.tar.gz", hash = "sha256:4bf2045036f97dcaabbf16ee8527f1787c7e9366611b9b9ed4bfabc81c19343f", size = 81585 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/19/71/0dbf9660d2a31470bb6e5d5338aed82c1906c4624e8629e24cf612fa4e14/pyobjc_framework_MetalPerformanceShadersGraph-10.3.1-py2.py3-none-any.whl", hash = "sha256:a0288c53a024bc47348da2ccd8dc980d389dacc9d1d33b3412614e88732dc424", size = 6045 }, -] - -[[package]] -name = "pyobjc-framework-metrickit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b2/71/82f14e24708d44eb0c53b4fc57224bf5db8fa268c0632974abd6ea4b2e7f/pyobjc_framework_metrickit-10.3.1.tar.gz", hash = "sha256:f0b96fe9da0e26759f38d9e4cdf7d9c8be9c6ba35403bc8e675183a6f81dd0b3", size = 31749 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d5/7e/f940ff748d257d0c44415a4f7d1dfad1fa0fabb4d76f77bec62e780abf3d/pyobjc_framework_MetricKit-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:59b6959d6f79f71080d386ad08665c19e52d0cc57943716da180bbb3369c9569", size = 8165 }, - { url = "https://files.pythonhosted.org/packages/a5/c3/0308e5941f509f84b0026dd56329941d4a7bb3859028ddcf4acaede186e9/pyobjc_framework_MetricKit-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:f73d240b5e8f2351d6c2258b71a6d06b45ec964523f54acf05af50dc4ffac821", size = 8179 }, - { url = "https://files.pythonhosted.org/packages/fe/ba/3f3e0272354366a6759a0529b32f6fc2f0d21a5071873fd26fc89f304c16/pyobjc_framework_MetricKit-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:58dbfc7b9ae7701a59b9b2a5a5f874a9e393f10b27f39155714d1b49ea725226", size = 8124 }, -] - -[[package]] -name = "pyobjc-framework-mlcompute" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/db/9a/405b3091a514670d36d21a9f1a9441555ae3b6cc0e6913765484af1cf52f/pyobjc_framework_mlcompute-10.3.1.tar.gz", hash = "sha256:9ac94b0a9511fedceacda846865daa05358eec5a4bf62be534b69eb4d7aced9b", size = 68347 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/82/1d9ad402910d9def7622c2b85a147364ecb31ad1add4a3ddb64c98f5abaf/pyobjc_framework_MLCompute-10.3.1-py2.py3-none-any.whl", hash = "sha256:e5f8d98ee43fc795f44dab322299cf8957d7e6acb54139cecebfc7f4b2562b6c", size = 6410 }, -] - -[[package]] -name = "pyobjc-framework-modelio" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/98/d1/3020a89e0e1145b831351b1e0b34b89b3af7055843384c2a138d3ef4979a/pyobjc_framework_modelio-10.3.1.tar.gz", hash = "sha256:b1da37d10c38c63006d5173b49d18891b2db2c9acdbb6dbd21c73f17c0ccab7e", size = 93075 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ba/fb/cd67b4b488f9c7463dfd9ddf4ed10796ecf9e20037b11143700e75b8568c/pyobjc_framework_ModelIO-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:e841be15f1847ffe1d30e0efdbc57d3c6f1a2db7553946bc15dde0d8f57b620d", size = 21656 }, - { url = "https://files.pythonhosted.org/packages/d7/1d/b403003258b758287c515e40895806e0dd60af7329714d0267db7add00a0/pyobjc_framework_ModelIO-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:53d4cc794e0dbc94e622ed164556f82db723f9c3b2d9dbf72bdf44468eb4efa5", size = 21690 }, - { url = "https://files.pythonhosted.org/packages/a1/ef/929e4076ad6104d3f195c60f53f8cb52436829f0a3e3d1a168bb4a0e04e1/pyobjc_framework_ModelIO-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:856e8d63c10238f4b23d30b9fb903d64b9f2b44e4f30f30a28bfc665e1adc5ac", size = 16181 }, - { url = "https://files.pythonhosted.org/packages/29/e4/cb3111bd389461df071ed721734191c1aa9ec9941a7c40783de55d7a9414/pyobjc_framework_ModelIO-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:b59069c79c0865334e0036b1938e009addf035bfec36f7d4d871037c14c7accd", size = 21652 }, -] - -[[package]] -name = "pyobjc-framework-multipeerconnectivity" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a6/bf/14b2e58b3462ab15fba8fb07fa493da6531d6c8da07382ef2b63e429be4a/pyobjc_framework_multipeerconnectivity-10.3.1.tar.gz", hash = "sha256:eb801d44194eb7eafcb0a21094c4ce78bcf41ed727125b048755838b59de3271", size = 23441 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/51/50/54225bb1e4f98f469531090efb98a5771c4696558f41ceea385194e0c272/pyobjc_framework_MultipeerConnectivity-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:1c0b65734f1e9b907c6198b035ad47c49819711c49694fe73cdf475be37db82e", size = 12779 }, - { url = "https://files.pythonhosted.org/packages/8e/e7/09d67a41a11c0c005200149cfa92e69a9c92f80381622f1f50f3936175e5/pyobjc_framework_MultipeerConnectivity-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:f0e466da15a3daf2c140be66da99ac0526b584fbd6dc08ed82e542e706964449", size = 12833 }, - { url = "https://files.pythonhosted.org/packages/4c/f2/c2aede1feb1517a64bcc9bb2341e4c76027b2287a2283d0ac42048bae17b/pyobjc_framework_MultipeerConnectivity-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:5538caad124908481ee43755d439898f9d7eb0f200856ba246c730ca5fd77e15", size = 8959 }, - { url = "https://files.pythonhosted.org/packages/63/8e/7c070f8cc3a302a3968dbd3318434c40e513440df07d9eb41b522426bc02/pyobjc_framework_MultipeerConnectivity-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:5350d13115b252bf6fa374dba1ef13ffd746b15b16f45d1b77b9231aebdf5b57", size = 12702 }, -] - -[[package]] -name = "pyobjc-framework-naturallanguage" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1f/37/a0af80f8bb4ce27b5d6ab5d6bb8a71ea950cbdf81ec73c03b03388d8c572/pyobjc_framework_naturallanguage-10.3.1.tar.gz", hash = "sha256:49f19d0dba34802696a270d690db310ff03f1c85d6fb411734cb13667db90dd9", size = 39154 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/81/37/7aabe277c3cfd6dc756959e6fa2bacf8e8e1c435b67e33f6a0c799e2a5ae/pyobjc_framework_NaturalLanguage-10.3.1-py2.py3-none-any.whl", hash = "sha256:d0e47fad66bb74fa68b50093500f5cb49d8a772b522f8c92e725f2e65942dd9c", size = 4923 }, -] - -[[package]] -name = "pyobjc-framework-netfs" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/90/94/d467f7bc9efdf633f6cb40b83357f1cb91308efea2738f37b7c682e6619a/pyobjc_framework_netfs-10.3.1.tar.gz", hash = "sha256:46466917f7b0aca3772bf4dfd586b583992c60ecd71c39f7d28ff7665d057637", size = 15212 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/08/1a6effdc97f3eede536e66a7c7e1c50cce644e8d4d5e258a243985997b2a/pyobjc_framework_NetFS-10.3.1-py2.py3-none-any.whl", hash = "sha256:84faa7325c4ecc2f4ad199d8c52cebcb520ad2e7713f356c7a5a849839398d77", size = 3791 }, -] - -[[package]] -name = "pyobjc-framework-network" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b7/a2/547e786e3ff87e4facf038b0375d8fd4a48a8f6c69762efc7aac87b2d379/pyobjc_framework_network-10.3.1.tar.gz", hash = "sha256:87a5839d4ab2ae452b4e563bd7a00569557ede4b8cd1eb77c973cdf45fb8f5ab", size = 104030 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a1/83/d8799253ebf55496dd0725d9ba4cd03260fc161dee6f128fd3e78ae6a79f/pyobjc_framework_Network-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:56df88c10b948b3b09dd6d0e9061da33683e294d0450efd9076354f41e214f58", size = 19084 }, - { url = "https://files.pythonhosted.org/packages/43/ce/d5e00d0dcf234a0269c079948c855467f5af0464d4d1d44148c20c69f602/pyobjc_framework_Network-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:0336fc0b80a2481d3a032b94e7dfddbb8d0f1ec10e36e80ad424a028b00679ac", size = 19128 }, - { url = "https://files.pythonhosted.org/packages/cb/9c/899932cbf529094f2bf4be1eb863fa78a791dd1095ad0ed92d4e25d11e50/pyobjc_framework_Network-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:1e2cbc4d209b6789d8a3bd85cfe472bae50ca2d54355beb25b8336ed65d846e0", size = 14613 }, - { url = "https://files.pythonhosted.org/packages/6d/04/1a5d7daa7704ac3d096a3c76a3ffde49df5b836a7f6f355e72f95f7fbdd2/pyobjc_framework_Network-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:c665f3dcfb1375835dd0c6ce10079f22be73f92213fc3d48b176d9c67fc221a9", size = 14385 }, -] - -[[package]] -name = "pyobjc-framework-networkextension" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/dc/46/1af5ad27f16af7ef97cced31dc70d92cf85c08d1e15a32997f9e40496601/pyobjc_framework_networkextension-10.3.1.tar.gz", hash = "sha256:c5a094862061565ca6d37457db42f55f344ec24dd7604ddf5d72e20ae7f63fdd", size = 130653 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/35/fd/085d7b5ab96a5eec797933246e268773728d58ce4cccfbb06bc210590c4f/pyobjc_framework_NetworkExtension-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:baacdb4ad595d5c5ce9660e10ea476fab9bfd1a1def2357eae7918f5019bb8c0", size = 13808 }, - { url = "https://files.pythonhosted.org/packages/4d/e3/3afdc6ec7c8ecf596b35b3e32f95fc23d755ce42af40375cd96041eeb587/pyobjc_framework_NetworkExtension-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:c1efc35dc4ddced3f0e5400e8ae9b28b7585f0cf5701023dd957f3cbd58d361f", size = 13864 }, - { url = "https://files.pythonhosted.org/packages/2d/b2/c907e55127ade6d290f89c61ee20066def925e0b7f539d602d13bb221a08/pyobjc_framework_NetworkExtension-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:aeba32d9b9809bb1296d85da00f0c221daf54b25fd864dc9bf03a7007f5ad601", size = 11564 }, - { url = "https://files.pythonhosted.org/packages/d8/df/34dfbcc84a34b3edd4813da0324091f83da64a8d246738903f947c739e94/pyobjc_framework_NetworkExtension-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:1c8ef5fce8846fb3bf459bedf7a31ff0428a9c3184c8b26ced8e322c956e8ec0", size = 14222 }, -] - -[[package]] -name = "pyobjc-framework-notificationcenter" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/11/a4/105abbec54e815ab9de653bba08db37524589c369badab6e1a5e3bd598a3/pyobjc_framework_notificationcenter-10.3.1.tar.gz", hash = "sha256:3e6efe0fe6389601bb87086f5585fa7e74b2143236b7d5afd02b617a73656419", size = 21039 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cd/f8/eb4a4703d3b91d91ed050411ac129612d11ce34f3f01cca8c7912cc08ea1/pyobjc_framework_NotificationCenter-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:2818922c2c3f45721515733b452d20a507368a87b793fa976c21945773582abc", size = 10603 }, - { url = "https://files.pythonhosted.org/packages/0a/6e/3be21a76248fcfb4c703bda266f2b289bb0df07ad1ea551209d71ede808b/pyobjc_framework_NotificationCenter-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:e08264759b84a21631e143afce1696920207d418be7f8853dbde18dbc7881667", size = 10668 }, - { url = "https://files.pythonhosted.org/packages/82/6c/1d18ab74c090818f4c7be1ee9d126ff4c272acf28db0fac65cdd77a9908e/pyobjc_framework_NotificationCenter-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:1560edad4e9fe01cbf3a70bb6e2668985e13903497d3fdc92276d6cecf9e4742", size = 7127 }, - { url = "https://files.pythonhosted.org/packages/57/59/bdf3194bd3693132370f4cc1a002bde09dd248f2a49026e5ec4785970083/pyobjc_framework_NotificationCenter-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:992ea7c86d0330cf10113b829525d74a95d97d0d7245e4e277f75ecbb37b596e", size = 10524 }, -] - -[[package]] -name = "pyobjc-framework-opendirectory" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/32/1e/85e8d9ea9ee43a111a6d278c5006a3a58c4573af60ba7932402cb3ca5e84/pyobjc_framework_opendirectory-10.3.1.tar.gz", hash = "sha256:cddc25632eebeb6bf0d886ae0fc919d574e458c597691226ba15bbf134ab51a6", size = 159659 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ca/17/74c8d815ddd43d206311baf00237c8a14c4c3cb7ad656ef33afcfe370655/pyobjc_framework_OpenDirectory-10.3.1-py2.py3-none-any.whl", hash = "sha256:7e787e65409aad082faed2ed0c2cd52cccea61702d9c83b6acdcac3fa50a562f", size = 11425 }, -] - -[[package]] -name = "pyobjc-framework-osakit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ce/db/2ee141472cb30079b8881d4839f4d46d38bed2e78e04d5ecf44885d05cd7/pyobjc_framework_osakit-10.3.1.tar.gz", hash = "sha256:0af326b831fa29fca11ffe2b641807ad3c233be9eb403e62328fa784528da4ab", size = 18286 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f3/37/f644ff0e1013ee25a3c543f4240687f7ab79580df401cafff8e5dfea278c/pyobjc_framework_OSAKit-10.3.1-py2.py3-none-any.whl", hash = "sha256:aaa60e6f455febe45f9be6487c59f11450de81bd7f49a6e4db576a38bcaf1c68", size = 3784 }, -] - -[[package]] -name = "pyobjc-framework-oslog" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/11/ba/45a84a9a26608c8dd2d909f8ad8183434c17b1d4071ce910388c80a07637/pyobjc_framework_oslog-10.3.1.tar.gz", hash = "sha256:592c3e50cf824c2c07779771aa0065de2dbb4c615de43e8949b39d19ba04d744", size = 22288 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/79/ef/1d18049de4f5d459107e1703cb42d3e159dffa988bc9968ec43c7cef3742/pyobjc_framework_OSLog-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:4799619f9ae12287923e2bc39fc021c75ea4e8bcb0e8ff44201f1018d017db98", size = 7898 }, - { url = "https://files.pythonhosted.org/packages/08/94/609913d615527e891fadf4b3c319ce6df143c5c160ba5e69904fa4d2a666/pyobjc_framework_OSLog-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:7ff719367249c09318a87df47ef8e1c8d18ab5f4b9e94862e7ca9c8fad21ed9a", size = 7958 }, - { url = "https://files.pythonhosted.org/packages/09/d8/faa0f2c72c2a24a3fa44c9d56f613e4ccbd213cb2702481dd750acfd7d0d/pyobjc_framework_OSLog-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:5ae0848bf6de69c95802f11bb4aff5c2edac5c5e6179b9a06a0e4fe05ed48b53", size = 5790 }, - { url = "https://files.pythonhosted.org/packages/fe/33/8185fa32c8705f1b16b0d91b62ab290159d7611f2cf46db0fea7c8c87703/pyobjc_framework_OSLog-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:cded4c706fcf3fd78ef257ab096f4f8cefc70cca81553d2fae88841aaf5d620d", size = 8054 }, -] - -[[package]] -name = "pyobjc-framework-passkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a5/5a/8336d8fe6371e7696235d131d042572156299d6a0c566a5854f127270adc/pyobjc_framework_passkit-10.3.1.tar.gz", hash = "sha256:4c3eea19c1ae3edf6e7858ab815bcd8ecf517a146928ce6a843910729372f010", size = 94853 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f0/ba/9e247686f64ee75840104d4e85a2c21316ce6abaa0697b0fa826edd69442/pyobjc_framework_PassKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:ce09205aae4e15d3639d76a558c072ae106e8c7dafe9a451c5e27967498b74cd", size = 13868 }, - { url = "https://files.pythonhosted.org/packages/6a/af/081c1c6fd9bbcd93ea983e5ea2111011c669c96cc6d6146e07f570aeb136/pyobjc_framework_PassKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:79ff6fa8ad4c0f9b4a992122b22e2b2b4200534221eb1bfe86bf473fb3c7ca23", size = 13907 }, - { url = "https://files.pythonhosted.org/packages/27/f3/092e31c4892f50eb4b94ddbf29f6a7b658820714e40fdd6e5cf4b22c00d1/pyobjc_framework_PassKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:bbb71ac6fc51da06d0fd6cb4d83eb79b704c2bab694a93899d3f83c753c9740b", size = 10785 }, - { url = "https://files.pythonhosted.org/packages/e8/c3/b1a04f416c25f0f4c194137ba8ce4444a7c0e7f3b42b38b278e3a707ff5e/pyobjc_framework_PassKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:d41409ee24eee2318023c3ba23218db152fc262ebcbea9021dc533fe80a73f32", size = 13787 }, -] - -[[package]] -name = "pyobjc-framework-pencilkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d2/8e/9152ecf82135f5f6ec94f4b407948cdee9b8f01ead2896613422dbfe8ef1/pyobjc_framework_pencilkit-10.3.1.tar.gz", hash = "sha256:4dfd8e0179be5ecf67b768317a88d86d93df1c8674d422afa14957cf80e6e01f", size = 18784 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1b/41/a15fd222e8f9b28ab18440ac3d4c2aca98c640f2e1456dbc018c451c7556/pyobjc_framework_PencilKit-10.3.1-py2.py3-none-any.whl", hash = "sha256:dc05376fbc5887391ff4e778b6f4b2fa20264aac58cd5fe5f47e4930186c1674", size = 3653 }, -] - -[[package]] -name = "pyobjc-framework-phase" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-avfoundation" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f8/7c/57e7a130932027f11ce8bfb68e8a6a910b9ec11c8bd4647605d0c6ff1ade/pyobjc_framework_phase-10.3.1.tar.gz", hash = "sha256:5be2ea5d36ea9620f5278f5ad3b02cc243511be3b137aa28b1523e8f6da54f99", size = 43938 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/82/5b/948fcead87fc9badb4de137829423ce53f1d03a5f8d873e4d0cea01745da/pyobjc_framework_PHASE-10.3.1-py2.py3-none-any.whl", hash = "sha256:eec5a38983d65a4cf022dd01dc6f290ec163399e79592203443b4115ea3c8510", size = 6233 }, -] - -[[package]] -name = "pyobjc-framework-photos" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/4f/e3/764707657dc2ee986510ac137dfcb98ca3498fa21ed7c79e711df3b85736/pyobjc_framework_photos-10.3.1.tar.gz", hash = "sha256:8d538c399720062523694f7669aa82dcb75a7b192fb4aca93cf782d04e4c39be", size = 74176 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/03/e2/7e46258b4c0f75a48e639bc1423830c34067b101bd5512c80db4a6554b1f/pyobjc_framework_Photos-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:9a382201dd14a3f3076d8689267d63520803a1ad1716fb66df5c1bb578bc6384", size = 12793 }, - { url = "https://files.pythonhosted.org/packages/ef/20/3fcc8803c0503bfd7e7f2fb81889d1f41f12cc1660a1b37f31743d271821/pyobjc_framework_Photos-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:9c72efff52bed483b0dfaa569a21355f7620f25672a0245c5db8c1df86abc7b8", size = 12850 }, - { url = "https://files.pythonhosted.org/packages/3a/14/8eff6e370acfff5e75902ccb66cbea6d609e54dba87501570642b44cae2e/pyobjc_framework_Photos-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:4841948ce4fe3d5060ec08e760b0b6e476e923782f32b9af2ffe8eb2a4fbb385", size = 9744 }, - { url = "https://files.pythonhosted.org/packages/17/25/83a32b4743b63c7262c476bd0acbca8304e942483e599acade70aa0dc345/pyobjc_framework_Photos-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:50710703d18d0b13c48e02ab4edcca72a67ee20aac2a75664bfb725c8cb3a677", size = 12687 }, -] - -[[package]] -name = "pyobjc-framework-photosui" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/aa/34/6ee322114383d37c4921fc15e41ba4595347f0b108e14d6232e540d77c5e/pyobjc_framework_photosui-10.3.1.tar.gz", hash = "sha256:e9eb961c6be1f3e00d76cc0a8ec15b50ac0692bd5b5c86268ad08f6d09cf390d", size = 38914 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b4/69/422c3f59a3d9f632aaa2440d2cf7f80cd22b6930ef965a0892923bf8b879/pyobjc_framework_PhotosUI-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:88665561d9ef7e9fd2ceb4e7e5da0fc3412a397d4c48a2121250462781106d30", size = 12574 }, - { url = "https://files.pythonhosted.org/packages/09/69/5de76149d57fd1a22cfa8be06e8f7bf76a334e488abafbac6e39773942ac/pyobjc_framework_PhotosUI-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:3254605c33e090742d0303a3b5b8ddab5489dbf28ea8a287566106e6887ee561", size = 12626 }, - { url = "https://files.pythonhosted.org/packages/95/3d/c7b7147d02ecdea07fc0ec3bad0c3f4eafa4297e83e02aa336ab4b962d94/pyobjc_framework_PhotosUI-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9370e36bb4ae1e7128006ff6a6b43448ebf8586784749e2a1fa30bbb2ef8fedf", size = 8573 }, - { url = "https://files.pythonhosted.org/packages/65/f2/df518ac867baff73fbf91f7a9e97165065f9db96785c45b2bda6d68d5774/pyobjc_framework_PhotosUI-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:a756c3bbf945ceaa7d184c41053c2a9c1a89b32ffcdf752664b1180927b22cb2", size = 12506 }, -] - -[[package]] -name = "pyobjc-framework-preferencepanes" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8a/56/da2d75cf4900a62cafde27d875bbe0dc0e9c3624b6d4c08adc69d9336033/pyobjc_framework_preferencepanes-10.3.1.tar.gz", hash = "sha256:eef150416a39a0109a8a37e9978ac4a55ad0b125ef6053a7431524ede5c69783", size = 25330 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/78/54/e2d55873233287481d11f9d92254e0fc8a86d2c37c062186c1867d41c7a6/pyobjc_framework_PreferencePanes-10.3.1-py2.py3-none-any.whl", hash = "sha256:319b58b6c8f876f67e879b3a4f74afd6d892aa43a7f9ef4320819265b281c9e5", size = 4384 }, -] - -[[package]] -name = "pyobjc-framework-pushkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/30/d6/2fec9c42a76466902b14afeea7a9c8cc2c90aeafd3f3dbe72af474681dc5/pyobjc_framework_pushkit-10.3.1.tar.gz", hash = "sha256:cc4da5382cf48c29637af1c633490203358a6ab0c76f0c006079cf144eeb9568", size = 19167 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/37/33/0b2cf5dadd448498490a31e52dbbbc6015a62402128fb4e7aac90f3d3889/pyobjc_framework_PushKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:39e21ac2b9a529e99d6d33c439c96d4d2bb97d2c56bd6d92b2c5bd497e925851", size = 8204 }, - { url = "https://files.pythonhosted.org/packages/3d/cd/51e1ac0bd23813b6e11a7e1363a104096adc6d56bd2a5f9180014e110d8b/pyobjc_framework_PushKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:e20f94ad3fbebf34c613c880e655d0f918d891b0a70763f99bb5d11e0af65c73", size = 8256 }, - { url = "https://files.pythonhosted.org/packages/51/a5/5fad3f215db4b300f5e3efcaa1b1393bcd6c14a141435102798ff7cb2766/pyobjc_framework_PushKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:79f0e66b88473e7fdef304dce06d7d63c3e5e38b12deafcd06a5bd3506ed9398", size = 5969 }, - { url = "https://files.pythonhosted.org/packages/21/ab/c15351016775f0134b3d500f599d07fb20fffae7ec85c089e1ee79f047c9/pyobjc_framework_PushKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:ee90959fc7b171930cffdf07cb7865d56a2cb4b723c5826ccf95d6e865dee4bd", size = 8630 }, -] - -[[package]] -name = "pyobjc-framework-quartz" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f7/a2/f488d801197b9b4d28d0b8d85947f9e2c8a6e89c5e6d4a828fc7cccfb57a/pyobjc_framework_quartz-10.3.1.tar.gz", hash = "sha256:b6d7e346d735c9a7f147cd78e6da79eeae416a0b7d3874644c83a23786c6f886", size = 3775947 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/62/b3/ba33c4a3406fec862a5107da03d8daacbc11daa355f446a8849e1bf2c73e/pyobjc_framework_Quartz-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:96578d4a3e70164efe44ad7dc320ecd4e211758ffcde5dcd694de1bbdfe090a4", size = 227260 }, - { url = "https://files.pythonhosted.org/packages/0f/08/215f38dbebfca74f49276a9471531f360b4fb7888106f78953909919ca53/pyobjc_framework_Quartz-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ca35f92486869a41847a1703bb176aab8a53dbfd8e678d1f4d68d8e6e1581c71", size = 227195 }, - { url = "https://files.pythonhosted.org/packages/ce/7a/78b512061af37a4466607143a9876192f04c5810b16e4cb097fbbfa02dc5/pyobjc_framework_Quartz-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:00a0933267e3a46ea4afcc35d117b2efb920f06de797fa66279c52e7057e3590", size = 226586 }, -] - -[[package]] -name = "pyobjc-framework-quicklookthumbnailing" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/29/04/ef2db0a73af5b2530de728529f5d637bbe5f09bf4165493db0ab3df2018b/pyobjc_framework_quicklookthumbnailing-10.3.1.tar.gz", hash = "sha256:ee26be78df9ce46ffa6f971f4ce167a0e98f38167aeb86cfc1b41270f15c96a3", size = 15534 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/bb/d2/6c199cf69d5402cd4317600e7a4f925964a2eb9df44e4a09437af5dbf037/pyobjc_framework_QuickLookThumbnailing-10.3.1-py2.py3-none-any.whl", hash = "sha256:e5095c0ad8cf1f91a6ed9aa5c4fb7c9b1da122d495ce131bae8d7faa06da9505", size = 3814 }, -] - -[[package]] -name = "pyobjc-framework-replaykit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5b/37/dbadcb487150f4ea1a691c83d09f1ed58463bed6b4fa54dca6aeb1584d06/pyobjc_framework_replaykit-10.3.1.tar.gz", hash = "sha256:21762c8674b629fb670c3cbd515c593f1b5f98ee24ee4834a09055cb08849068", size = 23417 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/de/0a/173ad3f0ae54f172b59a351244a7b049cedca96d2b9b88d2609ea611dd1d/pyobjc_framework_ReplayKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:1d89020e770763947c0e3e3a201b541b81b455656e574d390ad0b0e32a67640a", size = 10127 }, - { url = "https://files.pythonhosted.org/packages/36/c9/493a621107b3d2540140acfa70e72fb9f340485d38b475f1590d57608bc9/pyobjc_framework_ReplayKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:b753658337d25964acb83f5edc465b772f276b4c88fc8bd03ad633b4466f6bd4", size = 10163 }, - { url = "https://files.pythonhosted.org/packages/13/3f/3cbeb95beb520422d20d050ae107a8238ca118c36eeddad645248255ef12/pyobjc_framework_ReplayKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:fafbc37ef6e44ac5019b4a4b751b3de6d5983500705e8dea2fc62134f8c0dc24", size = 7153 }, - { url = "https://files.pythonhosted.org/packages/5a/7f/0fcd8020fb8b29e31c42ce0a672b58c4e3b41d8a587ce621e06a68d89b0a/pyobjc_framework_ReplayKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:22ca748ae8325e41e0526f13822d2c477ab879cb2d454eee1db47ca91353c986", size = 10047 }, -] - -[[package]] -name = "pyobjc-framework-safariservices" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/69/63/c12192ed8b5a08cc5313aef6d4e6d86d9d17171d4325a7f6e2f8c0da7a19/pyobjc_framework_safariservices-10.3.1.tar.gz", hash = "sha256:9c5278576e7c28c3d93e74ebe5d39d07c5c91572ddf03ea01cc45d9a06dc8d0a", size = 29436 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6c/43/e7fd640b320252360e5777b4544dd18a7b507ecd4e31e8a54b877dff761d/pyobjc_framework_SafariServices-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:c8afb977b5858d3fd27136146db46a9f2ec43c35f5af269dbcb51c46a422dd7e", size = 7405 }, - { url = "https://files.pythonhosted.org/packages/af/ef/5a28fa9b7e9aea7e011e58f461b60f0fab27488859b1f83b556fcc4c5151/pyobjc_framework_SafariServices-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:adb0332cbfa086892524efa253c873ecc4a8b00c60db45be3362759c4b4ae87d", size = 7461 }, - { url = "https://files.pythonhosted.org/packages/e4/62/5a2293203ec1b2c787a33bb0d7ee8a3cb9e4a6aac455b436e39915f362f8/pyobjc_framework_SafariServices-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:7a171f08527c6bd297633e72bc597d68ec74419b5315f8c8122311537a8a6340", size = 5942 }, - { url = "https://files.pythonhosted.org/packages/a7/71/2dcd9ba1b7bd51619db281ff74cbda5ab1a49225bebb8e19ff5ab0556eda/pyobjc_framework_SafariServices-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:aaba0ea92410820d94fef0b93d337478f0e416967cb2aa4e667dd4d1bb561c1e", size = 7461 }, -] - -[[package]] -name = "pyobjc-framework-safetykit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d8/db/1d099ed2b3655caacad70315a6789b47277f9939f73d4f13810bf27f9e29/pyobjc_framework_safetykit-10.3.1.tar.gz", hash = "sha256:8421be801ce29053e67a2c91673913562c3ad9d4bb1fbaa934a3a365d8bff12d", size = 19035 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c1/13/35bfd2d99a20f035d8c1e0c266b2c5d90c64f8f075d6d70743c8b1fa4118/pyobjc_framework_SafetyKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:e554cb94bc2f89f525ccaa4ed827390d188eba8bb24049acdc764f3dfee9af08", size = 8039 }, - { url = "https://files.pythonhosted.org/packages/9c/86/7f33005e00824520fa611bcc63ecbbe55979b94dc1599df44d1c8a7ab92c/pyobjc_framework_SafetyKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:8eb160cc4f3b7e6d58f2eecc205f016afd5f4278b9641e49d5ef9c4df7b6df8c", size = 8089 }, - { url = "https://files.pythonhosted.org/packages/55/84/79d6e20377c6cfe07f8289c4dabeda78c5a8c455c465a5793c6e2a4b5d6f/pyobjc_framework_SafetyKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:3674b92d8b72d0a6006cb899ec2f605d1d5a6a59ff2d90c51ee2ccfd0f069d10", size = 5921 }, - { url = "https://files.pythonhosted.org/packages/58/50/d8bbb45c931ec9c5205bc1fb3d03336e6c992b90b9444b3c6ed6be0069c7/pyobjc_framework_SafetyKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:ac700aa2cbddc8a31626815886e42d0d1591572914c2b15df2dd07871ee84568", size = 8324 }, -] - -[[package]] -name = "pyobjc-framework-scenekit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/23/cb/0451b9463cc1d19eef523dfc6098c5d774cbd5f4cae9fbc6884b17cd5cd9/pyobjc_framework_scenekit-10.3.1.tar.gz", hash = "sha256:99cf0db3055d9bae0a8643400e528a8c012235db8ee6a1864ea0b03a0854c9d0", size = 155276 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/46/37/d10538c3547f8aac05fd8d7b519ce46f54ed1eda6f77686e319f0191a0ee/pyobjc_framework_SceneKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:7a108ef1a660a7928d1d44e415c84f544d296745d5350235addaab82777b080a", size = 32978 }, - { url = "https://files.pythonhosted.org/packages/cf/73/79c969fe840aede23074ba229c077653e778c7a6735709a642c17c870862/pyobjc_framework_SceneKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:08fb5dd8c10a5624a0bf3dd9f448b2fe4c8b9c7c3c98708d28b0b4c72dd2a107", size = 33193 }, - { url = "https://files.pythonhosted.org/packages/4a/d0/b9de585d75d71666026deea22bf5249eb7c2ec0394489239db1423f4743e/pyobjc_framework_SceneKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:08601223416fa048d9468f961b170e3c2009d7e2434eea92c12ee12f6c672961", size = 22568 }, - { url = "https://files.pythonhosted.org/packages/44/17/6c72f136bdd00e2bb7093247db6be90117f9a0512cc3a15fa56073886843/pyobjc_framework_SceneKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:2984a543221190547bff603a6a59c931cda7099b91ac7412e11c962e8f6c3bc1", size = 33117 }, -] - -[[package]] -name = "pyobjc-framework-screencapturekit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d4/20/51dbb697dc5d3bc522771afa375e05370e6357b49dacf1bafe7dae37908f/pyobjc_framework_screencapturekit-10.3.1.tar.gz", hash = "sha256:cb1a2e746e0f98ea14a11ea35d059d38587340beeeb905812085e2c7ceb14e0c", size = 34829 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1a/67/ff55c30ac3508f3c1214a084f321d2268c56d15fe5be436591a5ee24eb7e/pyobjc_framework_ScreenCaptureKit-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0953f8d43bd7f0012decebe34401d361c4a64472190960204b3214e4850e4ef2", size = 11398 }, - { url = "https://files.pythonhosted.org/packages/b2/c7/25af6462a4f161dca7ffb375348716b6cb271c29e356bbfd4e4693f87b69/pyobjc_framework_ScreenCaptureKit-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:a80928dc483046ac72294fd576c53f793045aad700b740ec9591b23a3ccc011d", size = 11435 }, - { url = "https://files.pythonhosted.org/packages/cd/3d/17cb4d822faf26efe04e2f0749783abeaddb86529c1af59ec8f8270deccb/pyobjc_framework_ScreenCaptureKit-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:4d8e280a076e7bc40eaa9730f97da84421b891c30f6e3fdea4f6c30bdb298243", size = 11368 }, -] - -[[package]] -name = "pyobjc-framework-screensaver" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/dc/7c/55374bae0be8632e2c76b911af3bcdfd5b5ea417c125d8268f8207c77516/pyobjc_framework_screensaver-10.3.1.tar.gz", hash = "sha256:0bbc5b574f12e95f6f6e48ced40b601e46e560ef6786845c15c57d78e6cd083e", size = 22037 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/63/26/d9db1199855e3b3227bfe3c156750786f23d600055732eea2be28314b4c3/pyobjc_framework_ScreenSaver-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:31bffb17ec131509c4cc584e98328497310ea644c764b50fb6bf7850617ec5a5", size = 7961 }, - { url = "https://files.pythonhosted.org/packages/b5/0a/0eac07594070e89c796fb56858fa75f2a39dbc407e02ded06624d26120ed/pyobjc_framework_ScreenSaver-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:ff25ad7cfffa116feaa117989f0a4b68dd6b7318aea4320ece6f75caf0092cfa", size = 8166 }, - { url = "https://files.pythonhosted.org/packages/6a/34/2e98bf93ba933c466f206087d31c5aec678aa13270817a8be3bf0c2be622/pyobjc_framework_ScreenSaver-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:51e5bce05a3ada526c5c19b21cfb383cd7653d78f175c5abaf500a67ddab1c19", size = 6285 }, - { url = "https://files.pythonhosted.org/packages/7a/c7/76e8315650b4d90c2ef690480fba37d75dcf5aa1c3fe177238348e6d2e7d/pyobjc_framework_ScreenSaver-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:616ffb4bac2a56108778e33be6fe75b28f19511157abc411960b72324276635d", size = 8005 }, -] - -[[package]] -name = "pyobjc-framework-screentime" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/38/a5/b2b9c57eb364ccc1074442ce956b0052f71e903b7b944a93bc4888deb94d/pyobjc_framework_screentime-10.3.1.tar.gz", hash = "sha256:351179d5bf951aa754c72f50ba8785212adf1b26abe10149c750fafd0a3108ae", size = 13365 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b5/00/475bee668c55ca6d39464bb80ffb7e8c3012b027183e6d91c675b4b5e5aa/pyobjc_framework_ScreenTime-10.3.1-py2.py3-none-any.whl", hash = "sha256:d4f8a0784dc7d7060dadae2e4b5aae5e1afe8bbf453ce49cbb1860b8920114c3", size = 3403 }, -] - -[[package]] -name = "pyobjc-framework-scriptingbridge" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/10/45/ef1ae83f84555c3cf7ba18e53be9ace9f4225e56b852d7f5d79b5c516d4f/pyobjc_framework_scriptingbridge-10.3.1.tar.gz", hash = "sha256:6bfb45efd0a1cda38a37154afe69f86ea086d5cbdfbc33b3e31c0bda97537fe9", size = 20828 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d8/4f/33f9ddb57f3cfc88d878e2bfbe99ecc10f775bd62a0bbc3b53ec4fad709c/pyobjc_framework_ScriptingBridge-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:3a88e1a6c6b7d8935ab4baa9dcdeccb9cb08a44906bdd69b77302f48c88408d9", size = 8365 }, - { url = "https://files.pythonhosted.org/packages/10/bb/f692b524f4ff77535f6d7b4f9e54f8fa2ed5e82e01bea9506f5a78bbf9f8/pyobjc_framework_ScriptingBridge-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:66b55a9c12572f9bd6c00fd0a5aa5353354e7b717e37ffd1e843614d2fbde3d5", size = 8424 }, - { url = "https://files.pythonhosted.org/packages/cb/d6/19275587fd90c3f1d0c6eebc881f802eac1e0e63d66a0b380d63dbe01fc7/pyobjc_framework_ScriptingBridge-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:387c0720842a1285afde5b56c43d9ed1332736ff8f6119ba6c6a551018552182", size = 6535 }, - { url = "https://files.pythonhosted.org/packages/51/f3/8417c284db5b68f958d8421b331cb3d4ab4caf85a7af8110dede55b084aa/pyobjc_framework_ScriptingBridge-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:90022f44f2bf0563bf5a75669198b9d778f76ece719f237750e9c5fcb00a601d", size = 8510 }, -] - -[[package]] -name = "pyobjc-framework-searchkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-coreservices" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/85/74/1ee0012987c203f6776b7ca3da12b68623d9861c96ddc9575809c38864bc/pyobjc_framework_searchkit-10.3.1.tar.gz", hash = "sha256:7efb76b7af9d8f0f08efb91543f4dba0b00261ed41abb121ada80175cc82d65d", size = 30449 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a8/40/9c3231a96b55776338005ec60f278488111f4093af8bc9f1c7f17696406e/pyobjc_framework_SearchKit-10.3.1-py2.py3-none-any.whl", hash = "sha256:48ec776603e350405c7311f29d5941e0e9d6b6a75e2aec69e0acd28be0979905", size = 3320 }, -] - -[[package]] -name = "pyobjc-framework-security" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/20/db/3fa2a151c53f2d87d9da725948d33f8bb4c7f36d6cb468411ae4b46ad474/pyobjc_framework_security-10.3.1.tar.gz", hash = "sha256:0d4e679a8aebaef9b54bd24e2fe2794ad5c28d601b6d140ed38370594bcb6fa0", size = 252496 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6f/d2/c8e65fd0d5905883bfae7c087645bba247e109570d5c55f814cdaa027eea/pyobjc_framework_Security-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:499372b4b87de0198601e0c6b3d3e43d48605218149a5808c6567b601147a9bf", size = 41023 }, - { url = "https://files.pythonhosted.org/packages/36/96/f8f714d8eaa7e7741475a53c3e6a06cc550cd996153e5076fe2276e00ad2/pyobjc_framework_Security-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:b3daed9661bd80245dd8dbc738a17870226969db27f6dbb3424ec0ebdbb6ba83", size = 41069 }, - { url = "https://files.pythonhosted.org/packages/5a/32/4d233b667ae2b7a9106c4a7ebb2552801cc4474c66f6a23750d13f60e289/pyobjc_framework_Security-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6120e91282985bcec3b44c1bc4f9c26d40cd07b4ac3dc81f745d73c13f8b5523", size = 41021 }, -] - -[[package]] -name = "pyobjc-framework-securityfoundation" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-security" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/40/d6/908dcceb7cd5dcfa3ff265dfcb945a8707256f7ab09ee709d86cb26ae1d4/pyobjc_framework_securityfoundation-10.3.1.tar.gz", hash = "sha256:414b13acabfae584729cd614e27247d250ec225d31140e8d971aa08536d6150c", size = 12595 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/93/43/3f0b77bc72a9c419b355cbdaaa4a289ae838f6593421292b790b58512888/pyobjc_framework_SecurityFoundation-10.3.1-py2.py3-none-any.whl", hash = "sha256:c352cde672c9c2afa89575c362a0714e589c118485cec49ba230327e92c8a9a6", size = 3383 }, -] - -[[package]] -name = "pyobjc-framework-securityinterface" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-security" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b6/8b/d2dfd658f279fe6d3416b45c5030a65342ded0150ba56e028f6dcc9b38e1/pyobjc_framework_securityinterface-10.3.1.tar.gz", hash = "sha256:cd25f342a2b53cbffd134443506d5e75c96ba7145135debb8932c1252d57269a", size = 31921 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/05/17/ba99db445a991ecba87f82d190756fb9c9943c68000e2e7d093e830f1051/pyobjc_framework_SecurityInterface-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:7a9bbca70e8a27bd79a0b8846f7d08b693dd309ff780f92f713fee57ff9d3ddf", size = 10731 }, - { url = "https://files.pythonhosted.org/packages/b6/e3/281084dfecb61453da2ccf36c8cbf3c6db24191c973a0c4f14397a1ec186/pyobjc_framework_SecurityInterface-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:b964ecbde276611c14fd70884ab9c08c4aae75633deda1a29813dbe42dc83dd6", size = 10780 }, - { url = "https://files.pythonhosted.org/packages/bc/ec/2af619d126a82869ced4d6ef8af7f9bfcebcb721cad70ccb0792c7f84ddd/pyobjc_framework_SecurityInterface-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:8c2998c09767f0214891c553fadb8ec72a8273c95fca820c44cb11f3b0cdb8a4", size = 7515 }, - { url = "https://files.pythonhosted.org/packages/7e/b1/8bd136570f27057f2a73bb27f67f2ed638169d9660474d77e9b531e821a7/pyobjc_framework_SecurityInterface-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:d913d30d04c9f01679ead33c95ad53dade587995f48c778a6de4d7da239b43e3", size = 10809 }, -] - -[[package]] -name = "pyobjc-framework-sensitivecontentanalysis" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ef/3d/7b50fb510374640c7562fc3cc83a75d91bd23f3f53a15579bd0061ffc3bd/pyobjc_framework_sensitivecontentanalysis-10.3.1.tar.gz", hash = "sha256:ac8dd18d77ccc0bb4eb24839cf39da9981db64e53f52b09636e47bd7b3066f84", size = 12006 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fc/bc/09d3c469f63366eff7caf148e53bf38a3752178a62a99881a0ef11453549/pyobjc_framework_SensitiveContentAnalysis-10.3.1-py2.py3-none-any.whl", hash = "sha256:6b5cfe771a28300d766ff14ff81313fda946943d54a039d5574478a070933e03", size = 3451 }, -] - -[[package]] -name = "pyobjc-framework-servicemanagement" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ec/de/f60506eef312ea3cbd5eacd1308bfb7e68f8d1a032573840f46b7de3a122/pyobjc_framework_servicemanagement-10.3.1.tar.gz", hash = "sha256:d048a803ad34c997dcc99ba778fca9d91cc5adfa1d115202e4bf22d9b04fd92c", size = 15746 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/09/ed/72cbba493d3e6d17127f39f1436b12248a812ca9714fdcf02f6834e7bb93/pyobjc_framework_ServiceManagement-10.3.1-py2.py3-none-any.whl", hash = "sha256:6b7ca0de9cf74439df0947aae29f5f31d58eeacb0ff55e1465faed540d31de4b", size = 4927 }, -] - -[[package]] -name = "pyobjc-framework-sharedwithyou" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-sharedwithyoucore" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a2/c8/261b3ae7063550b157fd33e9931c53007e4b7ff209a6d5a393b301af67c3/pyobjc_framework_sharedwithyou-10.3.1.tar.gz", hash = "sha256:7e35b631bc77b040151515e4fee9c8f47bc313924fc3e5970e940f1343db039b", size = 27924 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f9/94/e54dfbdb57e82d65cc78a881ed02240e7bd6f12b4b8da5d003ff18acaf07/pyobjc_framework_SharedWithYou-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:175cb32c93c55511f86ccf02b1da2fdcbc2a0f92422d451ff5dd4a864b3f3faf", size = 8782 }, - { url = "https://files.pythonhosted.org/packages/e8/35/ccb26fa87164b6616f208b87fc255cce06bb23443473f1fa3ab2f89fa59d/pyobjc_framework_SharedWithYou-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:8a1ee78d6220e02e073c5fe6fea8f223ef870086c1afe60f346e7bb3dbdcb165", size = 8831 }, - { url = "https://files.pythonhosted.org/packages/e1/33/f7a2fe06b25836687e829408763d86b593aff9b0f6921443bb3e4be1cbaf/pyobjc_framework_SharedWithYou-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:824d56ecf85dbaa938a2db42bf2f5a55a4e9f94019dee2dc90578040cc2bbd3c", size = 6591 }, - { url = "https://files.pythonhosted.org/packages/4f/33/bb8c76ac26329e37b22386d238cd97683494e5e8f875c0a6682b7ea524c6/pyobjc_framework_SharedWithYou-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:bc37e1c86f460095085a5060149ca013d4dcb9b54337887bff86a2e07302c0f1", size = 9084 }, -] - -[[package]] -name = "pyobjc-framework-sharedwithyoucore" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/58/ba/09d6cfb51167b14711d2a2526d69994566eec101578af0e39b84a4794e5b/pyobjc_framework_sharedwithyoucore-10.3.1.tar.gz", hash = "sha256:e4768b7fdb18730e225bbebc9c9f9acfa7e44e648875816aff8c7e7f0e82afbf", size = 24331 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f3/4f/7d1f125b94f5fd88d66c4d5969b54fd2902e9c683a6ad6092e8b8638856e/pyobjc_framework_SharedWithYouCore-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:b0fb4e84e15765d913d5383b61004b7ff9a637f198ec7c3dee07632f3a4e2b4c", size = 8540 }, - { url = "https://files.pythonhosted.org/packages/ba/d7/06cc06c15fa69500c9f321e575cc296913e560b04ab448b477f7bec012d3/pyobjc_framework_SharedWithYouCore-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:9b480058016216e5a3715e3ff50f5430159ec4235dcd110141f53637f5dbb51d", size = 8589 }, - { url = "https://files.pythonhosted.org/packages/44/cf/09ca1c5a2dbcfe58a0f36f4aaefe094f1c9e93a5c054b5e332115775a9f4/pyobjc_framework_SharedWithYouCore-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:17a5e29f832d395030b1ab5dfcf43dad2a9c0f917e6b443ac383dea06e3aa304", size = 6321 }, - { url = "https://files.pythonhosted.org/packages/e5/90/aaf3a46470effa512fd7aa9f8cd35ed1ce861b785c8dc5f5519052a249c0/pyobjc_framework_SharedWithYouCore-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:1e51f315b5b16b340a1a12d4a0f3244f1925f14c9e148ca4dfdcfad6baa7ee5a", size = 8886 }, -] - -[[package]] -name = "pyobjc-framework-shazamkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/07/d7/5cf2157fd163084d75d1cf9cf2de774d373387162a7b03c19cbcd193f22f/pyobjc_framework_shazamkit-10.3.1.tar.gz", hash = "sha256:deef11a43e773b876df31eeadbfc447892fda0607e314ca2afb2c012284cfa32", size = 22923 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/05/05/ac965959bfd2261bbcc590e1db7f9b7b59a39736db6b7398a20a8d510d38/pyobjc_framework_ShazamKit-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:cc77fde1503ec1f96d7b9a05ad784d29d94065732f0cfe089321be423e5045f3", size = 8628 }, - { url = "https://files.pythonhosted.org/packages/77/03/470f30e129d93faee2cc418a38acabd16b331b403cb201d3cefe380ae9a4/pyobjc_framework_ShazamKit-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:012560cab1997c1da6e19388b5192f68dcdf806c2f8d7bd1e66da37512d18b30", size = 8652 }, - { url = "https://files.pythonhosted.org/packages/d0/23/2139cd328324253b27384d99a50232ee930ac33fb829cfad3f7e29283455/pyobjc_framework_ShazamKit-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:4356bdcb9ca50da243b9d79da27851b799483865072f7c86a8a9674300d31819", size = 8592 }, -] - -[[package]] -name = "pyobjc-framework-social" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/94/a8/c5a8ea9eea5ec096e03fcda22f3bf5077710a988dbcdbc543afed7478d34/pyobjc_framework_social-10.3.1.tar.gz", hash = "sha256:d1303cf3860ad02a8795c099e17888923505a9c45be407da50721a9a8a5b2efd", size = 13749 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/89/bc/aa8ad14fc35f7a08fdc78757bfb341f3f4da9c6c8036201777d5f17b5ca7/pyobjc_framework_Social-10.3.1-py2.py3-none-any.whl", hash = "sha256:f83617c07db7c8bd15b3b9e0878ab2b6a286dcbd9a8c7f451da204f75db880e9", size = 4065 }, -] - -[[package]] -name = "pyobjc-framework-soundanalysis" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/cc/23/bb9bc28f3d96e1316ac257b6b0605bcefb4b38879b9594272bbc9505e341/pyobjc_framework_soundanalysis-10.3.1.tar.gz", hash = "sha256:faa533644231f99dbdc2fcc3ecb9181c5df4f4dc68d42856729214021c83c881", size = 15578 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5a/f6/350c7b3e9ceba976a4669c87b86cf378918cb6938a6083cc16aeb271c81b/pyobjc_framework_SoundAnalysis-10.3.1-py2.py3-none-any.whl", hash = "sha256:ef67207ff4045e5db37f017bdcd07d4b42464c86fe6c3b56524f6f22a9cde216", size = 3789 }, -] - -[[package]] -name = "pyobjc-framework-speech" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e6/8c/cc25b4267f884139b9677ea3fed8a8b99c423ef3f72dcc35eae6a01e4007/pyobjc_framework_speech-10.3.1.tar.gz", hash = "sha256:5b77b1d1ced0d1ad7244037b865dda2b83e8f9562d76d1e9fa4fea3b89e437b8", size = 29979 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4c/13/112143807eae621c4237bdc75e6275af9915313ea64cffe3fd6e255ca6ae/pyobjc_framework_Speech-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:07afd82d76b98b67a78c07098a814a0b862bcf00fc072d49d8da435202008a18", size = 9135 }, - { url = "https://files.pythonhosted.org/packages/14/f1/6902241407b59de5c889e72fe05a329d107e97e50c6829023b9adfbab7e7/pyobjc_framework_Speech-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:444994d062286ff2769e07425d511503b2047b381afad1d64c8517ef4e44d01f", size = 9190 }, - { url = "https://files.pythonhosted.org/packages/13/98/f1f6ac438b9712f351e7fb013be4d95eb40692f5570eaea8138c4ccb4337/pyobjc_framework_Speech-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:e7fad907f9c0c49c5272f316d20e66ba0415038203ca277381753b035c16061a", size = 6712 }, - { url = "https://files.pythonhosted.org/packages/0d/f9/ae6eb7a2c72f15820ab8bbbf3b57be719fb491fe6523a7e9d1700c613b82/pyobjc_framework_Speech-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:2294b60e1ab59b1340b820e6fee67766a959edd580d73e3b938f15653805d64c", size = 9555 }, -] - -[[package]] -name = "pyobjc-framework-spritekit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/fc/a3/037c63ce21d3a01d1d3c891b17979c5c1ce13a0893c97848bf2eb3e30442/pyobjc_framework_spritekit-10.3.1.tar.gz", hash = "sha256:2c11f35f48302f487c51ba8030f5cf79493a9dc0993dd901016ae4b8d8047c8b", size = 95557 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cd/15/df384944ae0699ff3dffe20e0f9f3d64f09d58d2ee33dbc4beff2e359e38/pyobjc_framework_SpriteKit-10.3.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:af355eccc18437e0932e1b327817e8f50d194bfa471b65b4733185ba606ab792", size = 17827 }, - { url = "https://files.pythonhosted.org/packages/78/19/60a5a3da996744095234e01445e93cbfdedb44dd0b0e01b661bb6618de7b/pyobjc_framework_SpriteKit-10.3.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:c3fd6aaecd7abd6ebc83d4c37a22950d55b75911fdb99628b2677f44085a0212", size = 17881 }, - { url = "https://files.pythonhosted.org/packages/fb/ef/f237933784a49e693948cbe0926e132e886d7f0b3009eb92b9d822b829cb/pyobjc_framework_SpriteKit-10.3.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a1f0537bc0331cca58cc50307f3b114ab8bfd51576df3038b6037353aa77085f", size = 17833 }, -] - -[[package]] -name = "pyobjc-framework-storekit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bb/42/e0ebe600ca0572fea164c2308bdd8866cb09167ef1617ed66d5c9a9a6026/pyobjc_framework_storekit-10.3.1.tar.gz", hash = "sha256:913b4aad7dc31df7d8011c54a695da65cc57819f4b48c98abaed4e6d9ff7d323", size = 63667 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/dd/a10721d0d7634deff95a2e5d514269fa89b8d1754a7c724d85eab155286b/pyobjc_framework_StoreKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:f9c50a980846b236884504ad42690d49935bda3de5d779fca3cdfb16d43fa8d1", size = 12630 }, - { url = "https://files.pythonhosted.org/packages/d7/45/06593054fa5ac13701e1571f1560b0b9418e47b0a8f98dcd8521ca748804/pyobjc_framework_StoreKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:b3846b249a6fc5d26c80320098858978e0a16f46e98fc998075f16f539ac89fc", size = 12682 }, - { url = "https://files.pythonhosted.org/packages/a1/14/2e120443f39891d350ce213939cd20a52158dccd92ad9046d72744812723/pyobjc_framework_StoreKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:c3575facbb3d238b8c9f3054c1422488414d89a42906dbcbfdbb47ef8be3da66", size = 9084 }, - { url = "https://files.pythonhosted.org/packages/2b/e7/49a1b2b3ef3a16ea29110db454f7428e78472aacba230e4d96c81e18451c/pyobjc_framework_StoreKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:2b5848f0e08b42dd4dabe5822b436b904a697e923f529ccaad910dfb822b2b9d", size = 12544 }, -] - -[[package]] -name = "pyobjc-framework-symbols" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d7/2b/e32921c7f2e00ba41fdd6befc0f7aabf17bc4c136f2b6a0cf4f44939940e/pyobjc_framework_symbols-10.3.1.tar.gz", hash = "sha256:3e3f35ef3646b5f9c0653d9dbf5693cf87de3df04420cb2679dad74c75965d18", size = 11785 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/97/bb/f4a01bec12bc1c9dfe86b0428d39a5e9d5614e0f433b5eda42af43d3d1c0/pyobjc_framework_Symbols-10.3.1-py2.py3-none-any.whl", hash = "sha256:6e171da5af2612e186cc4cf896ad7f2672c021a1fc18bc8ef49b79c4c831202d", size = 2958 }, -] - -[[package]] -name = "pyobjc-framework-syncservices" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coredata" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/77/eb/6b73844bc7a4f964128cde7fffbe4243b62c691626b4b101337b6ac7caff/pyobjc_framework_syncservices-10.3.1.tar.gz", hash = "sha256:1cd5e3eaf85a11996184afad1da47037cd921e302ccb35fe388b19f91a685669", size = 49572 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/da/cf/bf62d8583436bad00a8b0bf59a6f0b1009b25229f51522a22f2164beeff5/pyobjc_framework_SyncServices-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:aa98a38f59f230da7817dc08055c8049fa961193af16caa262c51e4ec8b5de20", size = 14394 }, - { url = "https://files.pythonhosted.org/packages/ca/ed/3a406dde3ec505c5650ce8b379e566f146a84a22efca1b7a12a10e61e613/pyobjc_framework_SyncServices-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:9d3798cc745143d44da101bb0eb9d482326b761f48c3699251191e9c3656ee6c", size = 14450 }, - { url = "https://files.pythonhosted.org/packages/78/82/402f2ddb89c41c1c2db4aa6b9683d169bbddac89c284951126415734170b/pyobjc_framework_SyncServices-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:97020a88d743a6f12ed3f72d062ab96712a7cc0e7b0293c7c5860c014002cc73", size = 10337 }, - { url = "https://files.pythonhosted.org/packages/84/e0/e72454fbef0749ba98e77ac91a5fc055abadec202ee75b1d95001fcf0fab/pyobjc_framework_SyncServices-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:b9b7bc58b04654172968cdc1cfe74b43ca0ad2e03c24c7921234a57be2c22985", size = 14329 }, -] - -[[package]] -name = "pyobjc-framework-systemconfiguration" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1f/34/4a8a79ae382296533cf0aa51377f53d9157aa41484c83a506d9dc43fc9e1/pyobjc_framework_systemconfiguration-10.3.1.tar.gz", hash = "sha256:1bf6ffe98faa4e208bf594c857ba23cd56fe404bc579188ff53b704844d9c402", size = 124143 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fc/23/4986e3f009493910f552e74cf239e09802d1df059075b021611959f22c5f/pyobjc_framework_SystemConfiguration-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:200c4b7d3483e5ccb86d4d5783ace8c26d4b3f9130684280f30080d53f62d4c5", size = 21723 }, - { url = "https://files.pythonhosted.org/packages/9c/65/c2db36889167836e1d26134c650e638cbf0667ceb815b2cc6d8bb9ed1ced/pyobjc_framework_SystemConfiguration-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:403392b0e2085cf528547d468bc523fbee418381bb61446eb4aa1f9a1c8a8494", size = 21800 }, - { url = "https://files.pythonhosted.org/packages/28/75/7a9635b41648b24c50eeb2c36a23e9ac37a3b5af8602fd42a34c4275e072/pyobjc_framework_SystemConfiguration-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:f38a824261a30dc9961e13a7b9759dd0c77e1c7c4681e3c80c5751c560735289", size = 16960 }, - { url = "https://files.pythonhosted.org/packages/17/8e/fc0b787b8b68b1baf1f1881150f6b6d8d1b5480cf1f22ea063260a057ac9/pyobjc_framework_SystemConfiguration-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:4e8816524cbb6c6ea9e1c596fc9a16c91f2063eba394135be9437bdbd469e125", size = 21680 }, -] - -[[package]] -name = "pyobjc-framework-systemextensions" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/dd/d2/eab93a69f95c757104112cb0bce3e1fc70de59ca47ff0c60d180f306819f/pyobjc_framework_systemextensions-10.3.1.tar.gz", hash = "sha256:34412e75c95a585d222ea23efc3eba436210ec0345cec6c7dc78d16e027d03e1", size = 19844 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0e/a9/5c97bbf22f792fd4beb01dc2bad894eab5f62687122fd9b156c743c04f8f/pyobjc_framework_SystemExtensions-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:b24edd33c71cb02a16bdd9b26d3a229a6b2a815c26a4c908b1b8b6cdf4f6c84a", size = 8672 }, - { url = "https://files.pythonhosted.org/packages/d5/bd/caf73e19fb2b4bae267df4cef98debfad7db265228337c4ab84540507561/pyobjc_framework_SystemExtensions-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:e2a24501a782d2b6f7fa339619eb5c988db6b31a6043d029f40f67c54fd9399e", size = 8739 }, - { url = "https://files.pythonhosted.org/packages/fb/c8/c92741bd28ed5eb51d6d62fe512c9d8cc9bb7956cf1729b2f09400f95df7/pyobjc_framework_SystemExtensions-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:1cacd2356142307cf221d568f3e7adda654c28c90c223db3830746f4c2b12aea", size = 6412 }, - { url = "https://files.pythonhosted.org/packages/9d/79/5cf9fad837bb20f221ac981e3f300eecb9a92d154bc53685173654baee30/pyobjc_framework_SystemExtensions-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:6561876b2fd5c40620073fae9b924f2d8e0110e8573756ffc9521e4fbc825249", size = 9091 }, -] - -[[package]] -name = "pyobjc-framework-threadnetwork" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/dc/6c/c502594ac550436bb8d989b18734eeabd5ce189c2ebb1f4895e3e00d424d/pyobjc_framework_threadnetwork-10.3.1.tar.gz", hash = "sha256:1038210a8e5dfa86aefd10894563913e767e95d1c1bd4333ae5f9c6cabbb3ce9", size = 12639 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/21/d0/bcc8756d01a1d4f400148f67123a7238429be7c2ddb95f94d15beec8372f/pyobjc_framework_ThreadNetwork-10.3.1-py2.py3-none-any.whl", hash = "sha256:95ddbed8a114cc1f05db613bb53247465ec48ccaad2b56f5da466317808fc32b", size = 3377 }, -] - -[[package]] -name = "pyobjc-framework-uniformtypeidentifiers" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1f/54/10c56c741e7c95ee4dd8db06afac5e59722e5372e35f3c5a3e7c2954c746/pyobjc_framework_uniformtypeidentifiers-10.3.1.tar.gz", hash = "sha256:1985fee7e1f1157db36f3c19ee0ad273677eeff10467f575086246bbeffcdf50", size = 18476 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/37/5c/48f1c942fa870439598e296eb2136fc5cec3f4a6e08bff25f727dc5e9bb8/pyobjc_framework_UniformTypeIdentifiers-10.3.1-py2.py3-none-any.whl", hash = "sha256:8bd1516ccec1807e2ad92a071242d83e9d1eda08ddbfae04dacc30d76c3d734c", size = 4467 }, -] - -[[package]] -name = "pyobjc-framework-usernotifications" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/12/d2/32432d2b579ca393f65f7ae7b53cf887f2efda861c4e1b372428f65dd4bf/pyobjc_framework_usernotifications-10.3.1.tar.gz", hash = "sha256:ddb5de88fb659c2241429b6408ddcabbfc0c2c9e4a7f5f543a6fab1c4953403b", size = 45987 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e6/63/3d1151dd355936977c3a713d0952f384d0f175e2d8ed29352ba374f17c80/pyobjc_framework_UserNotifications-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:d85c293e0520530ac7152b3f293c5606f0495b7727de331ef4e198278bf40e98", size = 9677 }, - { url = "https://files.pythonhosted.org/packages/32/4d/631dd68f95261db9acd8488519bf9afd9359686cd5a027ba653f64b60f04/pyobjc_framework_UserNotifications-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:0001bb25f15e6f8cac81bcb58cab8161a15a6fe41f6c475e8da364c913bdb090", size = 9721 }, - { url = "https://files.pythonhosted.org/packages/2b/37/b052c7afbe4d9e7e6c6fbe3faf2fc81e766bcb8012809b496315177e1295/pyobjc_framework_UserNotifications-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:0bba49b0f290f5597b94a80608c785b61d61aa3885cdf05529862e47fe1cec67", size = 7315 }, - { url = "https://files.pythonhosted.org/packages/f7/46/188efc812446f32793673d1d3d000e037052373e2bb19e0a3e5d1036b53b/pyobjc_framework_UserNotifications-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:59294fa6110778de145c9299c220990d057a6a171d37ab5d8a6ab1780bf7888f", size = 10049 }, -] - -[[package]] -name = "pyobjc-framework-usernotificationsui" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-usernotifications" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/df/10/a525f13919955d653fd431f527974e2604b0b8727c886de1ec7e2bf34189/pyobjc_framework_usernotificationsui-10.3.1.tar.gz", hash = "sha256:80390b5361bb6014dc32d0afbf581280e7762a4f67460a736f461f613d397094", size = 13288 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/17/4b/1a198d4d8907d83f4334d34dae76572e18362391ee0644c9a5bc002980e7/pyobjc_framework_UserNotificationsUI-10.3.1-py2.py3-none-any.whl", hash = "sha256:bc6cb92a6ac947e8fe9685f3c1964c5a9f98e576b936b0bbff8c528f47f976d2", size = 3522 }, -] - -[[package]] -name = "pyobjc-framework-videosubscriberaccount" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c8/a6/41d6afaa800bf8839c45642b60d7fa13a0e292d477762c33ce22ba1c0aa6/pyobjc_framework_videosubscriberaccount-10.3.1.tar.gz", hash = "sha256:f62509e976b805bc76ff5928444677ac542b52dd9f7781ac0731d7c4b22bed96", size = 23793 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/88/38/a9e721db0fa383eeabaadd6c6762ea33d6f50a25c22b70ee82c31d536e66/pyobjc_framework_VideoSubscriberAccount-10.3.1-py2.py3-none-any.whl", hash = "sha256:4b489f0007dce8ea17f37316175dac2768cd173a4d4c7a1d5f87fb3991c1e518", size = 4295 }, -] - -[[package]] -name = "pyobjc-framework-videotoolbox" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/65/e4/435561672801cb29a398b208e75e6823e6c369027cd51f0774f3b24f2baf/pyobjc_framework_videotoolbox-10.3.1.tar.gz", hash = "sha256:7ebc281523b2b37aff17ce6eabd0c81081864b3e3e4a83ae72b18fd70c57c521", size = 66253 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f7/98/96be1155746ad418400628191c9dd5e8354bb9f7f842c3c134a04d47efa5/pyobjc_framework_VideoToolbox-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:bc52aa91f568060e0087762f2a4d876bf7b683e5396779e93925252e26f0330b", size = 12471 }, - { url = "https://files.pythonhosted.org/packages/3b/e1/dbe5951097e627f6a7be79ee9a662beba8fb4eb20cebabab1d810f4aa881/pyobjc_framework_VideoToolbox-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:3d20ea92b597f4758f24ed8e19f7a7a372faf6478d739e7cb7f7cd73d3e8617a", size = 12527 }, - { url = "https://files.pythonhosted.org/packages/30/19/45ba628af703952faa1989fc5801102067b406595089dbaea50c4ab1016d/pyobjc_framework_VideoToolbox-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:761e3cd05090f5d9e9fbae2c25e3f352f19aa86a0d02a1189b94ec5c4bc37111", size = 10050 }, - { url = "https://files.pythonhosted.org/packages/a6/6c/51641d571758869feac26a48f625be1bcfe8ef3e30badcc36823baffe486/pyobjc_framework_VideoToolbox-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:7d4fb38f95e91f62d14b05fafcc6197775e9eaf4e5b698bc1fb313756f59b10d", size = 12811 }, -] - -[[package]] -name = "pyobjc-framework-virtualization" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2e/d1/427065aab5570855228fe0bc3d387fcc4c76e18538c28c5fc2497b0f75f2/pyobjc_framework_virtualization-10.3.1.tar.gz", hash = "sha256:8348ddef18eb943d151e5b5977e4d410012ee2e3f6048c16f7cfe0c1a73536cb", size = 61591 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6a/3f/5e11618a50c525bd89b8219360f1782dc6aff52cae6548cd767dc32af74c/pyobjc_framework_Virtualization-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:c046abcebf6a64a47ea50311f3e4aaae424dbac719e847cd15b375ebe99a51ed", size = 12300 }, - { url = "https://files.pythonhosted.org/packages/2f/41/9ef6d54da4bbc517ca5132a01e385b0ec3e329f9437a12fea608016a89a1/pyobjc_framework_Virtualization-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:dc14f6c3deaf367adff18b509e766dc78c4695a4cd76e4aad3ff4b1e207a4635", size = 12343 }, - { url = "https://files.pythonhosted.org/packages/9e/f5/7a98665de2b20a524600b2cca273bf7364e6adb51b77b9b8ee12549b2d58/pyobjc_framework_Virtualization-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:bd79c1bb45113957f24cbf8b6d0ff175361c52c97e326313ecd76cfa015f6cef", size = 9124 }, - { url = "https://files.pythonhosted.org/packages/9e/6a/732e29e221584680c669a2cf5e0c148832ef3643588cbf8ba1ec971be773/pyobjc_framework_Virtualization-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:6e5e6645e31acd07d30b1607c4cdaf0ae0e4d8223471a8a089004c2deb6fdea5", size = 12231 }, -] - -[[package]] -name = "pyobjc-framework-vision" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coreml" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7c/55/ff278351cb47f939a932dc5d9d80a8a0d51a427e27e0419833d49219e757/pyobjc_framework_vision-10.3.1.tar.gz", hash = "sha256:aa071656d395afc2d624600a9f30d6a3344aa747bf37f613ff3972158c40881c", size = 108532 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/24/4a/c6e7e1aaa2e095be007c82fa4861fae9496737a6a446b0671e12d39bd1fd/pyobjc_framework_Vision-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:dff3582678930461a0bb11bf070854d49f6944a851dc89edc63fac93c75ddf39", size = 17706 }, - { url = "https://files.pythonhosted.org/packages/63/a0/aa85feda6dc7d3a516f4d5059e421a7692d1f4d43e9d3f66e4f56f1281cb/pyobjc_framework_Vision-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:32626183c51674efb3b5738e2884c3fea37edca010117cf71bd72cb3c49c869a", size = 22423 }, - { url = "https://files.pythonhosted.org/packages/c5/ac/ef1f7365ce8b5f0f912553a3dd182998ddef60a5ae7998304231035b0755/pyobjc_framework_Vision-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2473b346a112c51ac485184305bd13c402e0db45f2df3d277315bd49efba18e9", size = 15731 }, - { url = "https://files.pythonhosted.org/packages/0c/c8/9c6e715b310613aff7612d0b70588cca53e066b577f69db5d66d62e147b9/pyobjc_framework_Vision-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:4302e2c5f68c9667ecd4273809cbc4611af6368b123d69596e5b088f1b1aa16b", size = 17614 }, -] - -[[package]] -name = "pyobjc-framework-webkit" -version = "10.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/15/6b/50c1000354e9de966a150b4a41c291c83517eec9bd162f43ea4e55444d64/pyobjc_framework_webkit-10.3.1.tar.gz", hash = "sha256:7ad9f4eb91a6dff39848d9c2ab71f170aeab4b6396bcec8e5a780739f9be4222", size = 610874 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3b/8b/bddff1733fb4da9b23039b1a51f755a446a127fbab08a6e4fbaae0445510/pyobjc_framework_WebKit-10.3.1-cp36-abi3-macosx_10_13_universal2.whl", hash = "sha256:df52913e4c3cb77d4551d9848e30be01b82cace54cede850c88a7e0ab41a20a9", size = 44518 }, - { url = "https://files.pythonhosted.org/packages/fa/e9/304f8cc6e3a5ac7062c77134e14579ad33941a761b43c97f1be8aa16ad0a/pyobjc_framework_WebKit-10.3.1-cp36-abi3-macosx_10_9_universal2.whl", hash = "sha256:207a7aa57817d3ab3fa033e42ab612f8c00521f13ff2871547c92cd94ed51f85", size = 44626 }, - { url = "https://files.pythonhosted.org/packages/e1/8a/a5bd21238eb1cc5bbc2efc1e3fafad64ec60cd43d728e7d02767b041fe66/pyobjc_framework_WebKit-10.3.1-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:c0d4c1ba0fafae503a8df95e7b6bd4236951ba72508ec62809e37825f382c635", size = 32764 }, - { url = "https://files.pythonhosted.org/packages/77/5a/c9620198d192abc6e8e694301507a3e6c8c76f4d3aac3bac24414f807c95/pyobjc_framework_WebKit-10.3.1-cp36-abi3-macosx_11_0_universal2.whl", hash = "sha256:c8e3334978a1bd927ea14ed73f56d6741561a69d31d082d2b23d1b48446917c8", size = 44697 }, -] - -[[package]] -name = "pyopencl" -version = "2024.2.7" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, - { name = "platformdirs" }, - { name = "pytools" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/92/68/a26269be1ba101b740a7b47d81032cf71c50a8700cc71ab2c49f0fcccec9/pyopencl-2024.2.7.tar.gz", hash = "sha256:6ae4458a959b6ad9c138fb711a52c4d57c2c2f798eb3aecc4c26830cb2726140", size = 470964 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/2b/0c830171d30de73c76a3ff92989959278d88d50e50e03b1ce5f1ffb04169/pyopencl-2024.2.7-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:31cc3907adb4d88e4b2cc05270054598a4544ed59539547a7eba11bb2304ea17", size = 450436 }, - { url = "https://files.pythonhosted.org/packages/12/fc/db5f1a1c4251b8bc7ece6e55664b84de30d5fc71f4d505b5974082e366b3/pyopencl-2024.2.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a65049fa87b461fe35a28a35f63f33f7e8e5a9f2862c401a3dfaddf2597c6954", size = 442814 }, - { url = "https://files.pythonhosted.org/packages/b2/fe/e91597055c9d38e654f60a359db88848be8c5ea845a5b5199d312248ee81/pyopencl-2024.2.7-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e891c16828d7702240429da667992639802407345e3b3d134054d06e006cb1e", size = 697975 }, - { url = "https://files.pythonhosted.org/packages/c2/6e/b8baa2a08aef4fe94345181e169b141d62695b08350bb3bc46eb084075b2/pyopencl-2024.2.7-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d25a7493a76cf8974e5ddaded7ea6d990cf5a98d3dee692244ff169f85d1da73", size = 1023203 }, - { url = "https://files.pythonhosted.org/packages/84/da/4abd1f95de9d0ff5522a1dad3256d0e0bd6810ef70d9dc789aa6e42d1838/pyopencl-2024.2.7-cp311-cp311-win_amd64.whl", hash = "sha256:df1ee130db7f2d05335d2d540d01059bb2a0f5ad418172f70275237a627f3744", size = 488840 }, - { url = "https://files.pythonhosted.org/packages/00/37/3a35de98b4763421aa5c488e4c59cf02ae27cab205f4369f0549a87950cd/pyopencl-2024.2.7-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:0666d9e1b90446db298e495e61ad4eb5a4bb336220ef00dce0bc3135006d2a16", size = 449910 }, - { url = "https://files.pythonhosted.org/packages/f7/3d/5b03e70e907a14fc5c127bcb77b021e06ec02a50503fe5d20bdbf6a76d10/pyopencl-2024.2.7-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d5e3542a2b9a05a1a689bcbddcec2b0535ac581b4d33a6a3a93c28c67bf661fe", size = 442406 }, - { url = "https://files.pythonhosted.org/packages/a9/c1/5b42d9d23ddb7586a29df5c368071c3fd3078f7736d9c23d10a634cdf13a/pyopencl-2024.2.7-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:26dff4233a16f4809b236100902c58ac2b071a11955127b1798885ead739077b", size = 697909 }, - { url = "https://files.pythonhosted.org/packages/67/6c/88b9d848f9b50bdc27c534efc8636b82f92a4d34b282bbc5cd58329fe31f/pyopencl-2024.2.7-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:69f58764bcde9d7c9a48aaabf831fcc0e8e54f5cc3ebf1806f392bb56f8c6d6d", size = 1023229 }, - { url = "https://files.pythonhosted.org/packages/68/27/2078a4990e45e29b1fb09feb8ec0310e965ef0333e59174882107a813a1e/pyopencl-2024.2.7-cp312-cp312-win_amd64.whl", hash = "sha256:59565d08cb03e03e6c63582dba849472846254465ba8ae532ff87aec0c41f4ea", size = 489398 }, -] - -[[package]] -name = "pyopenssl" -version = "24.2.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cryptography" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5d/70/ff56a63248562e77c0c8ee4aefc3224258f1856977e0c1472672b62dadb8/pyopenssl-24.2.1.tar.gz", hash = "sha256:4247f0dbe3748d560dcbb2ff3ea01af0f9a1a001ef5f7c4c647956ed8cbf0e95", size = 184323 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d9/dd/e0aa7ebef5168c75b772eda64978c597a9129b46be17779054652a7999e4/pyOpenSSL-24.2.1-py3-none-any.whl", hash = "sha256:967d5719b12b243588573f39b0c677637145c7a1ffedcd495a487e58177fbb8d", size = 58390 }, -] - -[[package]] -name = "pyparsing" -version = "3.1.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/83/08/13f3bce01b2061f2bbd582c9df82723de943784cf719a35ac886c652043a/pyparsing-3.1.4.tar.gz", hash = "sha256:f86ec8d1a83f11977c9a6ea7598e8c27fc5cddfa5b07ea2241edbbde1d7bc032", size = 900231 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/0c/0e3c05b1c87bb6a1c76d281b0f35e78d2d80ac91b5f8f524cebf77f51049/pyparsing-3.1.4-py3-none-any.whl", hash = "sha256:a6a7ee4235a3f944aa1fa2249307708f893fe5717dc603503c6c7969c070fb7c", size = 104100 }, -] - -[[package]] -name = "pyperclip" -version = "1.9.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/30/23/2f0a3efc4d6a32f3b63cdff36cd398d9701d26cda58e3ab97ac79fb5e60d/pyperclip-1.9.0.tar.gz", hash = "sha256:b7de0142ddc81bfc5c7507eea19da920b92252b548b96186caf94a5e2527d310", size = 20961 } - -[[package]] -name = "pyprof2calltree" -version = "1.4.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ca/2a/e9a76261183b4b5e059a6625d7aae0bcb0a77622bc767d4497148ce2e218/pyprof2calltree-1.4.5.tar.gz", hash = "sha256:a635672ff31677486350b2be9a823ef92f740e6354a6aeda8fa4a8a3768e8f2f", size = 10080 } - -[[package]] -name = "pyqt5" -version = "5.15.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyqt5-sip" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/28/6c/640e3f5c734c296a7193079a86842a789edb7988dca39eab44579088a1d1/PyQt5-5.15.2.tar.gz", hash = "sha256:372b08dc9321d1201e4690182697c5e7ffb2e0770e6b4a45519025134b12e4fc", size = 3265445 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/28/fcaf2aeede42456538d1543aefa253d70282bf326f5f795c99233366b66f/PyQt5-5.15.2-5.15.2-cp35.cp36.cp37.cp38.cp39-abi3-macosx_10_13_intel.whl", hash = "sha256:894ca4ae767a8d6cf5903784b71f755073c78cb8c167eecf6e4ed6b3b055ac6a", size = 47599356 }, - { url = "https://files.pythonhosted.org/packages/91/cf/cc705497cdae04c3c0bc34f94b91e31b6585bb65eb561f18473c998caae1/PyQt5-5.15.2-5.15.2-cp35.cp36.cp37.cp38.cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:29889845688a54d62820585ad5b2e0200a36b304ff3d7a555e95599f110ba4ce", size = 68328841 }, -] - -[[package]] -name = "pyqt5-sip" -version = "12.15.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1b/15/78318d50f10062c428e97e7ce387e772616a4673c356018b905f247a6a85/PyQt5_sip-12.15.0.tar.gz", hash = "sha256:d23fdfcf363b5cedd9d39f8a9c5710e7d52804f5b08a58e91c638b36eafcb702", size = 104024 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e9/7e/4b87c65adf9cb74895acc129043d04bb300436cab1e39469f4a9fc40b602/PyQt5_sip-12.15.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:855563d4d3b59ce7438bbf2dd32fed2707787defa40f3efe94f204a19ef92b25", size = 122436 }, - { url = "https://files.pythonhosted.org/packages/ec/90/8bf505a096553a253e1a65078ca1aeb6de8a83f27afa3a43bb89ae29da31/PyQt5_sip-12.15.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:0b718a362f4392430903bbb2a4b9bbff9841a16a52f0cfdd5b5bbd9d11457980", size = 276022 }, - { url = "https://files.pythonhosted.org/packages/6b/80/ed1a360df9128e0e26e28c6341174a7e02efc57816799af5e3a3cb865fc8/PyQt5_sip-12.15.0-cp311-cp311-win32.whl", hash = "sha256:2575f428de584a12009fd29d00c89df16ed101a3b38beba818dfdcbc4a10709c", size = 49065 }, - { url = "https://files.pythonhosted.org/packages/4e/d6/ea034ad64290c541042dc4c349d5aa854c8a0b54802a0759ec37671f0939/PyQt5_sip-12.15.0-cp311-cp311-win_amd64.whl", hash = "sha256:c85be433fbafcb3d417581c0e1b67c8198d23858166e4f938e971c2262c13cdb", size = 59009 }, - { url = "https://files.pythonhosted.org/packages/90/47/de48934a0d692c65b0833924a618786146c0869910c707a5e508351d5b91/PyQt5_sip-12.15.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:852b75cf208825602480e95ab63314108f872d0da251e9ad3deaaff5a183a6f5", size = 124312 }, - { url = "https://files.pythonhosted.org/packages/d1/6c/9a2fe24f8970e092613f709283a2101403490a209a30de3de89a413d9915/PyQt5_sip-12.15.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:0cd21c3215e3c47fdd5fa7a2dc3dd1e07a7230b0626e905a7217925068c788b9", size = 281431 }, - { url = "https://files.pythonhosted.org/packages/90/53/0a4dc2d448619f2a51849e124d375ec7a8e95c938eccfaf8711bb77a62b6/PyQt5_sip-12.15.0-cp312-cp312-win32.whl", hash = "sha256:b58eeedc9b2a3037b136bf96915196c391a33be470ed1c0723d7163ef0b727a2", size = 49408 }, - { url = "https://files.pythonhosted.org/packages/aa/c2/c07c531fe5a6124d91942c48a85ff4e14918766cd37819f7841cf2debabb/PyQt5_sip-12.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:24a1d4937332bf0a38dd95bb2ce4d89723df449f6e912b52ef0e107e11fefac1", size = 57922 }, -] - -[[package]] -name = "pyreadline3" -version = "3.4.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d7/86/3d61a61f36a0067874a00cb4dceb9028d34b6060e47828f7fc86fb9f7ee9/pyreadline3-3.4.1.tar.gz", hash = "sha256:6f3d1f7b8a31ba32b73917cefc1f28cc660562f39aea8646d30bd6eff21f7bae", size = 86465 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/56/fc/a3c13ded7b3057680c8ae95a9b6cc83e63657c38e0005c400a5d018a33a7/pyreadline3-3.4.1-py3-none-any.whl", hash = "sha256:b0efb6516fd4fb07b45949053826a62fa4cb353db5be2bbb4a7aa1fdd1e345fb", size = 95203 }, -] - -[[package]] -name = "pyrect" -version = "0.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/cb/04/2ba023d5f771b645f7be0c281cdacdcd939fe13d1deb331fc5ed1a6b3a98/PyRect-0.2.0.tar.gz", hash = "sha256:f65155f6df9b929b67caffbd57c0947c5ae5449d3b580d178074bffb47a09b78", size = 17219 } - -[[package]] -name = "pyscreeze" -version = "1.0.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pillow", marker = "python_full_version < '3.12'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ee/f0/cb456ac4f1a73723d5b866933b7986f02bacea27516629c00f8e7da94c2d/pyscreeze-1.0.1.tar.gz", hash = "sha256:cf1662710f1b46aa5ff229ee23f367da9e20af4a78e6e365bee973cad0ead4be", size = 27826 } - -[[package]] -name = "pyserial" -version = "3.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1e/7d/ae3f0a63f41e4d2f6cb66a5b57197850f919f59e558159a4dd3a818f5082/pyserial-3.5.tar.gz", hash = "sha256:3c77e014170dfffbd816e6ffc205e9842efb10be9f58ec16d3e8675b4925cddb", size = 159125 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/bc/587a445451b253b285629263eb51c2d8e9bcea4fc97826266d186f96f558/pyserial-3.5-py2.py3-none-any.whl", hash = "sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0", size = 90585 }, -] - -[[package]] -name = "pytest" -version = "8.3.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "iniconfig" }, - { name = "packaging" }, - { name = "pluggy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b4/8c/9862305bdcd6020bc7b45b1b5e7397a6caf1a33d3025b9a003b39075ffb2/pytest-8.3.2.tar.gz", hash = "sha256:c132345d12ce551242c87269de812483f5bcc87cdbb4722e48487ba194f9fdce", size = 1439314 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/f9/cf155cf32ca7d6fa3601bc4c5dd19086af4b320b706919d48a4c79081cf9/pytest-8.3.2-py3-none-any.whl", hash = "sha256:4ba08f9ae7dcf84ded419494d229b48d0903ea6407b030eaec46df5e6a73bba5", size = 341802 }, -] - -[[package]] -name = "pytest-asyncio" -version = "0.24.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/52/6d/c6cf50ce320cf8611df7a1254d86233b3df7cc07f9b5f5cbcb82e08aa534/pytest_asyncio-0.24.0.tar.gz", hash = "sha256:d081d828e576d85f875399194281e92bf8a68d60d72d1a2faf2feddb6c46b276", size = 49855 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/96/31/6607dab48616902f76885dfcf62c08d929796fc3b2d2318faf9fd54dbed9/pytest_asyncio-0.24.0-py3-none-any.whl", hash = "sha256:a811296ed596b69bf0b6f3dc40f83bcaf341b155a269052d82efa2b25ac7037b", size = 18024 }, -] - -[[package]] -name = "pytest-cov" -version = "5.0.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "coverage", extra = ["toml"] }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/74/67/00efc8d11b630c56f15f4ad9c7f9223f1e5ec275aaae3fa9118c6a223ad2/pytest-cov-5.0.0.tar.gz", hash = "sha256:5837b58e9f6ebd335b0f8060eecce69b662415b16dc503883a02f45dfeb14857", size = 63042 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/78/3a/af5b4fa5961d9a1e6237b530eb87dd04aea6eb83da09d2a4073d81b54ccf/pytest_cov-5.0.0-py3-none-any.whl", hash = "sha256:4f0764a1219df53214206bf1feea4633c3b558a2925c8b59f144f682861ce652", size = 21990 }, -] - -[[package]] -name = "pytest-cpp" -version = "2.5.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama" }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/72/6da4fd6ea5afd44e10dbed76ef666c0732e27317a753099bc163f3330a91/pytest-cpp-2.5.0.tar.gz", hash = "sha256:695604baa21bc95291bb4ea7263a7aa960753de57c2d17d224c4652fbcf65cdc", size = 465039 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/32/d5/b7b5c75dc2e11555898fbec78f88970c43f27439436ac83e65de6afcd2c6/pytest_cpp-2.5.0-py3-none-any.whl", hash = "sha256:137bcaa6487307b4c362245fcd4abf35de64ee85e6375f4d06cd31e6a64f9701", size = 15064 }, -] - -[[package]] -name = "pytest-mock" -version = "3.14.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c6/90/a955c3ab35ccd41ad4de556596fa86685bf4fc5ffcc62d22d856cfd4e29a/pytest-mock-3.14.0.tar.gz", hash = "sha256:2719255a1efeceadbc056d6bf3df3d1c5015530fb40cf347c0f9afac88410bd0", size = 32814 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f2/3b/b26f90f74e2986a82df6e7ac7e319b8ea7ccece1caec9f8ab6104dc70603/pytest_mock-3.14.0-py3-none-any.whl", hash = "sha256:0b72c38033392a5f4621342fe11e9219ac11ec9d375f8e2a0c164539e0d70f6f", size = 9863 }, -] - -[[package]] -name = "pytest-randomly" -version = "3.15.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c9/d4/6e924a0b2855736d942703dec88dfc98b4fe0881c8fa849b6b0fbb9182fa/pytest_randomly-3.15.0.tar.gz", hash = "sha256:b908529648667ba5e54723088edd6f82252f540cc340d748d1fa985539687047", size = 21743 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/24/d3/00e575657422055c4ea220b2f80e8cc6026ab7130372b7067444d1b0ac10/pytest_randomly-3.15.0-py3-none-any.whl", hash = "sha256:0516f4344b29f4e9cdae8bce31c4aeebf59d0b9ef05927c33354ff3859eeeca6", size = 8685 }, -] - -[[package]] -name = "pytest-repeat" -version = "0.9.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/86/5e/99365eb229efff0b1bd475886150fc6db9937ab7e1bd21f6f65c1279e0eb/pytest_repeat-0.9.3.tar.gz", hash = "sha256:ffd3836dfcd67bb270bec648b330e20be37d2966448c4148c4092d1e8aba8185", size = 6272 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/49/a8/0a0aec0c2541b8baf4a0b95af2ba99abce217ee43534adf9cb7c908cf184/pytest_repeat-0.9.3-py3-none-any.whl", hash = "sha256:26ab2df18226af9d5ce441c858f273121e92ff55f5bb311d25755b8d7abdd8ed", size = 4196 }, -] - -[[package]] -name = "pytest-subtests" -version = "0.13.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "attrs" }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/67/fe/e691d2f4ce061a475f488cad1ef58431556affea323dde5c764fd7515a70/pytest_subtests-0.13.1.tar.gz", hash = "sha256:989e38f0f1c01bc7c6b2e04db7d9fd859db35d77c2c1a430c831a70cbf3fde2d", size = 15936 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f5/ac/fc132cb88e8f2042cebcb6ef0ffac40017c514fbadf3931e0b4bcb4bdfb6/pytest_subtests-0.13.1-py3-none-any.whl", hash = "sha256:ab616a22f64cd17c1aee65f18af94dbc30c444f8683de2b30895c3778265e3bd", size = 8038 }, -] - -[[package]] -name = "pytest-timeout" -version = "2.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/93/0d/04719abc7a4bdb3a7a1f968f24b0f5253d698c9cc94975330e9d3145befb/pytest-timeout-2.3.1.tar.gz", hash = "sha256:12397729125c6ecbdaca01035b9e5239d4db97352320af155b3f5de1ba5165d9", size = 17697 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/03/27/14af9ef8321f5edc7527e47def2a21d8118c6f329a9342cc61387a0c0599/pytest_timeout-2.3.1-py3-none-any.whl", hash = "sha256:68188cb703edfc6a18fad98dc25a3c61e9f24d644b0b70f33af545219fc7813e", size = 14148 }, -] - -[[package]] -name = "pytest-xdist" -version = "3.6.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "execnet" }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/41/c4/3c310a19bc1f1e9ef50075582652673ef2bfc8cd62afef9585683821902f/pytest_xdist-3.6.1.tar.gz", hash = "sha256:ead156a4db231eec769737f57668ef58a2084a34b2e55c4a8fa20d861107300d", size = 84060 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6d/82/1d96bf03ee4c0fdc3c0cbe61470070e659ca78dc0086fb88b66c185e2449/pytest_xdist-3.6.1-py3-none-any.whl", hash = "sha256:9ed4adfb68a016610848639bb7e02c9352d5d9f03d04809919e2dafc3be4cca7", size = 46108 }, -] - -[[package]] -name = "python-dateutil" -version = "2.9.0.post0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892 }, -] - -[[package]] -name = "python-xlib" -version = "0.33" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/86/f5/8c0653e5bb54e0cbdfe27bf32d41f27bc4e12faa8742778c17f2a71be2c0/python-xlib-0.33.tar.gz", hash = "sha256:55af7906a2c75ce6cb280a584776080602444f75815a7aff4d287bb2d7018b32", size = 269068 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fc/b8/ff33610932e0ee81ae7f1269c890f697d56ff74b9f5b2ee5d9b7fa2c5355/python_xlib-0.33-py2.py3-none-any.whl", hash = "sha256:c3534038d42e0df2f1392a1b30a15a4ff5fdc2b86cfa94f072bf11b10a164398", size = 182185 }, -] - -[[package]] -name = "python3-xlib" -version = "0.15" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ef/c6/2c5999de3bb1533521f1101e8fe56fd9c266732f4d48011c7c69b29d12ae/python3-xlib-0.15.tar.gz", hash = "sha256:dc4245f3ae4aa5949c1d112ee4723901ade37a96721ba9645f2bfa56e5b383f8", size = 132828 } - -[[package]] -name = "pytools" -version = "2024.1.10" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "platformdirs" }, - { name = "siphash24" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ee/0f/56e109c0307f831b5d598ad73976aaaa84b4d0e98da29a642e797eaa940c/pytools-2024.1.10.tar.gz", hash = "sha256:9af6f4b045212c49be32bb31fe19606c478ee4b09631886d05a32459f4ce0a12", size = 81741 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/66/cf/0a6aaa44b1f9e02b8c0648b5665a82246a93bcc75224c167b4fafa25c093/pytools-2024.1.10-py3-none-any.whl", hash = "sha256:9cabb71038048291400e244e2da441a051d86053339bc484e64e58d8ea263f44", size = 88108 }, -] - -[[package]] -name = "pytweening" -version = "1.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/79/0c/c16bc93ac2755bac0066a8ecbd2a2931a1735a6fffd99a2b9681c7e83e90/pytweening-1.2.0.tar.gz", hash = "sha256:243318b7736698066c5f362ec5c2b6434ecf4297c3c8e7caa8abfe6af4cac71b", size = 171241 } - -[[package]] -name = "pywin32" -version = "306" -source = { registry = "https://pypi.org/simple" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8b/1e/fc18ad83ca553e01b97aa8393ff10e33c1fb57801db05488b83282ee9913/pywin32-306-cp311-cp311-win32.whl", hash = "sha256:e65028133d15b64d2ed8f06dd9fbc268352478d4f9289e69c190ecd6818b6407", size = 8507689 }, - { url = "https://files.pythonhosted.org/packages/7e/9e/ad6b1ae2a5ad1066dc509350e0fbf74d8d50251a51e420a2a8feaa0cecbd/pywin32-306-cp311-cp311-win_amd64.whl", hash = "sha256:a7639f51c184c0272e93f244eb24dafca9b1855707d94c192d4a0b4c01e1100e", size = 9227547 }, - { url = "https://files.pythonhosted.org/packages/91/20/f744bff1da8f43388498503634378dbbefbe493e65675f2cc52f7185c2c2/pywin32-306-cp311-cp311-win_arm64.whl", hash = "sha256:70dba0c913d19f942a2db25217d9a1b726c278f483a919f1abfed79c9cf64d3a", size = 10388324 }, - { url = "https://files.pythonhosted.org/packages/14/91/17e016d5923e178346aabda3dfec6629d1a26efe587d19667542105cf0a6/pywin32-306-cp312-cp312-win32.whl", hash = "sha256:383229d515657f4e3ed1343da8be101000562bf514591ff383ae940cad65458b", size = 8507705 }, - { url = "https://files.pythonhosted.org/packages/83/1c/25b79fc3ec99b19b0a0730cc47356f7e2959863bf9f3cd314332bddb4f68/pywin32-306-cp312-cp312-win_amd64.whl", hash = "sha256:37257794c1ad39ee9be652da0462dc2e394c8159dfd913a8a4e8eb6fd346da0e", size = 9227429 }, - { url = "https://files.pythonhosted.org/packages/1c/43/e3444dc9a12f8365d9603c2145d16bf0a2f8180f343cf87be47f5579e547/pywin32-306-cp312-cp312-win_arm64.whl", hash = "sha256:5821ec52f6d321aa59e2db7e0a35b997de60c201943557d108af9d4ae1ec7040", size = 10388145 }, -] - -[[package]] -name = "pywinbox" -version = "0.7" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ewmhlib", marker = "sys_platform == 'linux'" }, - { name = "pyobjc", marker = "sys_platform == 'darwin'" }, - { name = "python-xlib", marker = "sys_platform == 'linux'" }, - { name = "pywin32", marker = "sys_platform == 'win32'" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/b1/37/d59397221e15d2a7f38afaa4e8e6b8c244d818044f7daa0bdc5988df0a69/PyWinBox-0.7-py3-none-any.whl", hash = "sha256:8b2506a8dd7afa0a910b368762adfac885274132ef9151b0c81b0d2c6ffd6f83", size = 12274 }, -] - -[[package]] -name = "pywinctl" -version = "0.4" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ewmhlib", marker = "sys_platform == 'linux'" }, - { name = "pymonctl" }, - { name = "pyobjc", marker = "sys_platform == 'darwin'" }, - { name = "python-xlib", marker = "sys_platform == 'linux'" }, - { name = "pywin32", marker = "sys_platform == 'win32'" }, - { name = "pywinbox" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/ff/53/a7234a6b6d0c5cf295950166498623046422a333d8af79a26552ab40b9a6/PyWinCtl-0.4-py3-none-any.whl", hash = "sha256:8c4a92bd57e35fd280c5c04f048cc822e236abffe2fa17351096b0e28907172d", size = 60338 }, -] - -[[package]] -name = "pyyaml" -version = "6.0.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f8/aa/7af4e81f7acba21a4c6be026da38fd2b872ca46226673c89a758ebdc4fd2/PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774", size = 184612 }, - { url = "https://files.pythonhosted.org/packages/8b/62/b9faa998fd185f65c1371643678e4d58254add437edb764a08c5a98fb986/PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee", size = 172040 }, - { url = "https://files.pythonhosted.org/packages/ad/0c/c804f5f922a9a6563bab712d8dcc70251e8af811fce4524d57c2c0fd49a4/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c", size = 736829 }, - { url = "https://files.pythonhosted.org/packages/51/16/6af8d6a6b210c8e54f1406a6b9481febf9c64a3109c541567e35a49aa2e7/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317", size = 764167 }, - { url = "https://files.pythonhosted.org/packages/75/e4/2c27590dfc9992f73aabbeb9241ae20220bd9452df27483b6e56d3975cc5/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85", size = 762952 }, - { url = "https://files.pythonhosted.org/packages/9b/97/ecc1abf4a823f5ac61941a9c00fe501b02ac3ab0e373c3857f7d4b83e2b6/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4", size = 735301 }, - { url = "https://files.pythonhosted.org/packages/45/73/0f49dacd6e82c9430e46f4a027baa4ca205e8b0a9dce1397f44edc23559d/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e", size = 756638 }, - { url = "https://files.pythonhosted.org/packages/22/5f/956f0f9fc65223a58fbc14459bf34b4cc48dec52e00535c79b8db361aabd/PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5", size = 143850 }, - { url = "https://files.pythonhosted.org/packages/ed/23/8da0bbe2ab9dcdd11f4f4557ccaf95c10b9811b13ecced089d43ce59c3c8/PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44", size = 161980 }, - { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873 }, - { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302 }, - { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154 }, - { url = "https://files.pythonhosted.org/packages/95/0f/b8938f1cbd09739c6da569d172531567dbcc9789e0029aa070856f123984/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425", size = 766223 }, - { url = "https://files.pythonhosted.org/packages/b9/2b/614b4752f2e127db5cc206abc23a8c19678e92b23c3db30fc86ab731d3bd/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476", size = 767542 }, - { url = "https://files.pythonhosted.org/packages/d4/00/dd137d5bcc7efea1836d6264f049359861cf548469d18da90cd8216cf05f/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48", size = 731164 }, - { url = "https://files.pythonhosted.org/packages/c9/1f/4f998c900485e5c0ef43838363ba4a9723ac0ad73a9dc42068b12aaba4e4/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b", size = 756611 }, - { url = "https://files.pythonhosted.org/packages/df/d1/f5a275fdb252768b7a11ec63585bc38d0e87c9e05668a139fea92b80634c/PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4", size = 140591 }, - { url = "https://files.pythonhosted.org/packages/0c/e8/4f648c598b17c3d06e8753d7d13d57542b30d56e6c2dedf9c331ae56312e/PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8", size = 156338 }, - { url = "https://files.pythonhosted.org/packages/ef/e3/3af305b830494fa85d95f6d95ef7fa73f2ee1cc8ef5b495c7c3269fb835f/PyYAML-6.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba", size = 181309 }, - { url = "https://files.pythonhosted.org/packages/45/9f/3b1c20a0b7a3200524eb0076cc027a970d320bd3a6592873c85c92a08731/PyYAML-6.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1", size = 171679 }, - { url = "https://files.pythonhosted.org/packages/7c/9a/337322f27005c33bcb656c655fa78325b730324c78620e8328ae28b64d0c/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133", size = 733428 }, - { url = "https://files.pythonhosted.org/packages/a3/69/864fbe19e6c18ea3cc196cbe5d392175b4cf3d5d0ac1403ec3f2d237ebb5/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484", size = 763361 }, - { url = "https://files.pythonhosted.org/packages/04/24/b7721e4845c2f162d26f50521b825fb061bc0a5afcf9a386840f23ea19fa/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5", size = 759523 }, - { url = "https://files.pythonhosted.org/packages/2b/b2/e3234f59ba06559c6ff63c4e10baea10e5e7df868092bf9ab40e5b9c56b6/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc", size = 726660 }, - { url = "https://files.pythonhosted.org/packages/fe/0f/25911a9f080464c59fab9027482f822b86bf0608957a5fcc6eaac85aa515/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652", size = 751597 }, - { url = "https://files.pythonhosted.org/packages/14/0d/e2c3b43bbce3cf6bd97c840b46088a3031085179e596d4929729d8d68270/PyYAML-6.0.2-cp313-cp313-win32.whl", hash = "sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183", size = 140527 }, - { url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446 }, -] - -[[package]] -name = "pyyaml-env-tag" -version = "0.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyyaml" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/fb/8e/da1c6c58f751b70f8ceb1eb25bc25d524e8f14fe16edcce3f4e3ba08629c/pyyaml_env_tag-0.1.tar.gz", hash = "sha256:70092675bda14fdec33b31ba77e7543de9ddc88f2e5b99160396572d11525bdb", size = 5631 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5a/66/bbb1dd374f5c870f59c5bb1db0e18cbe7fa739415a24cbd95b2d1f5ae0c4/pyyaml_env_tag-0.1-py3-none-any.whl", hash = "sha256:af31106dec8a4d68c60207c1886031cbf839b68aa7abccdb19868200532c2069", size = 3911 }, -] - -[[package]] -name = "pyzmq" -version = "26.2.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cffi", marker = "implementation_name == 'pypy'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/fd/05/bed626b9f7bb2322cdbbf7b4bd8f54b1b617b0d2ab2d3547d6e39428a48e/pyzmq-26.2.0.tar.gz", hash = "sha256:070672c258581c8e4f640b5159297580a9974b026043bd4ab0470be9ed324f1f", size = 271975 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/12/20/de7442172f77f7c96299a0ac70e7d4fb78cd51eca67aa2cf552b66c14196/pyzmq-26.2.0-cp311-cp311-macosx_10_15_universal2.whl", hash = "sha256:8f7e66c7113c684c2b3f1c83cdd3376103ee0ce4c49ff80a648643e57fb22218", size = 1340639 }, - { url = "https://files.pythonhosted.org/packages/98/4d/5000468bd64c7910190ed0a6c76a1ca59a68189ec1f007c451dc181a22f4/pyzmq-26.2.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3a495b30fc91db2db25120df5847d9833af237546fd59170701acd816ccc01c4", size = 1008710 }, - { url = "https://files.pythonhosted.org/packages/e1/bf/c67fd638c2f9fbbab8090a3ee779370b97c82b84cc12d0c498b285d7b2c0/pyzmq-26.2.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77eb0968da535cba0470a5165468b2cac7772cfb569977cff92e240f57e31bef", size = 673129 }, - { url = "https://files.pythonhosted.org/packages/86/94/99085a3f492aa538161cbf27246e8886ff850e113e0c294a5b8245f13b52/pyzmq-26.2.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6ace4f71f1900a548f48407fc9be59c6ba9d9aaf658c2eea6cf2779e72f9f317", size = 910107 }, - { url = "https://files.pythonhosted.org/packages/31/1d/346809e8a9b999646d03f21096428453465b1bca5cd5c64ecd048d9ecb01/pyzmq-26.2.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:92a78853d7280bffb93df0a4a6a2498cba10ee793cc8076ef797ef2f74d107cf", size = 867960 }, - { url = "https://files.pythonhosted.org/packages/ab/68/6fb6ae5551846ad5beca295b7bca32bf0a7ce19f135cb30e55fa2314e6b6/pyzmq-26.2.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:689c5d781014956a4a6de61d74ba97b23547e431e9e7d64f27d4922ba96e9d6e", size = 869204 }, - { url = "https://files.pythonhosted.org/packages/0f/f9/18417771dee223ccf0f48e29adf8b4e25ba6d0e8285e33bcbce078070bc3/pyzmq-26.2.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:0aca98bc423eb7d153214b2df397c6421ba6373d3397b26c057af3c904452e37", size = 1203351 }, - { url = "https://files.pythonhosted.org/packages/e0/46/f13e67fe0d4f8a2315782cbad50493de6203ea0d744610faf4d5f5b16e90/pyzmq-26.2.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:1f3496d76b89d9429a656293744ceca4d2ac2a10ae59b84c1da9b5165f429ad3", size = 1514204 }, - { url = "https://files.pythonhosted.org/packages/50/11/ddcf7343b7b7a226e0fc7b68cbf5a5bb56291fac07f5c3023bb4c319ebb4/pyzmq-26.2.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:5c2b3bfd4b9689919db068ac6c9911f3fcb231c39f7dd30e3138be94896d18e6", size = 1414339 }, - { url = "https://files.pythonhosted.org/packages/01/14/1c18d7d5b7be2708f513f37c61bfadfa62161c10624f8733f1c8451b3509/pyzmq-26.2.0-cp311-cp311-win32.whl", hash = "sha256:eac5174677da084abf378739dbf4ad245661635f1600edd1221f150b165343f4", size = 576928 }, - { url = "https://files.pythonhosted.org/packages/3b/1b/0a540edd75a41df14ec416a9a500b9fec66e554aac920d4c58fbd5756776/pyzmq-26.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:5a509df7d0a83a4b178d0f937ef14286659225ef4e8812e05580776c70e155d5", size = 642317 }, - { url = "https://files.pythonhosted.org/packages/98/77/1cbfec0358078a4c5add529d8a70892db1be900980cdb5dd0898b3d6ab9d/pyzmq-26.2.0-cp311-cp311-win_arm64.whl", hash = "sha256:c0e6091b157d48cbe37bd67233318dbb53e1e6327d6fc3bb284afd585d141003", size = 543834 }, - { url = "https://files.pythonhosted.org/packages/28/2f/78a766c8913ad62b28581777ac4ede50c6d9f249d39c2963e279524a1bbe/pyzmq-26.2.0-cp312-cp312-macosx_10_15_universal2.whl", hash = "sha256:ded0fc7d90fe93ae0b18059930086c51e640cdd3baebdc783a695c77f123dcd9", size = 1343105 }, - { url = "https://files.pythonhosted.org/packages/b7/9c/4b1e2d3d4065be715e007fe063ec7885978fad285f87eae1436e6c3201f4/pyzmq-26.2.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:17bf5a931c7f6618023cdacc7081f3f266aecb68ca692adac015c383a134ca52", size = 1008365 }, - { url = "https://files.pythonhosted.org/packages/4f/ef/5a23ec689ff36d7625b38d121ef15abfc3631a9aecb417baf7a4245e4124/pyzmq-26.2.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55cf66647e49d4621a7e20c8d13511ef1fe1efbbccf670811864452487007e08", size = 665923 }, - { url = "https://files.pythonhosted.org/packages/ae/61/d436461a47437d63c6302c90724cf0981883ec57ceb6073873f32172d676/pyzmq-26.2.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4661c88db4a9e0f958c8abc2b97472e23061f0bc737f6f6179d7a27024e1faa5", size = 903400 }, - { url = "https://files.pythonhosted.org/packages/47/42/fc6d35ecefe1739a819afaf6f8e686f7f02a4dd241c78972d316f403474c/pyzmq-26.2.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ea7f69de383cb47522c9c208aec6dd17697db7875a4674c4af3f8cfdac0bdeae", size = 860034 }, - { url = "https://files.pythonhosted.org/packages/07/3b/44ea6266a6761e9eefaa37d98fabefa112328808ac41aa87b4bbb668af30/pyzmq-26.2.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:7f98f6dfa8b8ccaf39163ce872bddacca38f6a67289116c8937a02e30bbe9711", size = 860579 }, - { url = "https://files.pythonhosted.org/packages/38/6f/4df2014ab553a6052b0e551b37da55166991510f9e1002c89cab7ce3b3f2/pyzmq-26.2.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:e3e0210287329272539eea617830a6a28161fbbd8a3271bf4150ae3e58c5d0e6", size = 1196246 }, - { url = "https://files.pythonhosted.org/packages/38/9d/ee240fc0c9fe9817f0c9127a43238a3e28048795483c403cc10720ddef22/pyzmq-26.2.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:6b274e0762c33c7471f1a7471d1a2085b1a35eba5cdc48d2ae319f28b6fc4de3", size = 1507441 }, - { url = "https://files.pythonhosted.org/packages/85/4f/01711edaa58d535eac4a26c294c617c9a01f09857c0ce191fd574d06f359/pyzmq-26.2.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:29c6a4635eef69d68a00321e12a7d2559fe2dfccfa8efae3ffb8e91cd0b36a8b", size = 1406498 }, - { url = "https://files.pythonhosted.org/packages/07/18/907134c85c7152f679ed744e73e645b365f3ad571f38bdb62e36f347699a/pyzmq-26.2.0-cp312-cp312-win32.whl", hash = "sha256:989d842dc06dc59feea09e58c74ca3e1678c812a4a8a2a419046d711031f69c7", size = 575533 }, - { url = "https://files.pythonhosted.org/packages/ce/2c/a6f4a20202a4d3c582ad93f95ee78d79bbdc26803495aec2912b17dbbb6c/pyzmq-26.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:2a50625acdc7801bc6f74698c5c583a491c61d73c6b7ea4dee3901bb99adb27a", size = 637768 }, - { url = "https://files.pythonhosted.org/packages/5f/0e/eb16ff731632d30554bf5af4dbba3ffcd04518219d82028aea4ae1b02ca5/pyzmq-26.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:4d29ab8592b6ad12ebbf92ac2ed2bedcfd1cec192d8e559e2e099f648570e19b", size = 540675 }, - { url = "https://files.pythonhosted.org/packages/04/a7/0f7e2f6c126fe6e62dbae0bc93b1bd3f1099cf7fea47a5468defebe3f39d/pyzmq-26.2.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:9dd8cd1aeb00775f527ec60022004d030ddc51d783d056e3e23e74e623e33726", size = 1006564 }, - { url = "https://files.pythonhosted.org/packages/31/b6/a187165c852c5d49f826a690857684333a6a4a065af0a6015572d2284f6a/pyzmq-26.2.0-cp313-cp313-macosx_10_15_universal2.whl", hash = "sha256:28c812d9757fe8acecc910c9ac9dafd2ce968c00f9e619db09e9f8f54c3a68a3", size = 1340447 }, - { url = "https://files.pythonhosted.org/packages/68/ba/f4280c58ff71f321602a6e24fd19879b7e79793fb8ab14027027c0fb58ef/pyzmq-26.2.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4d80b1dd99c1942f74ed608ddb38b181b87476c6a966a88a950c7dee118fdf50", size = 665485 }, - { url = "https://files.pythonhosted.org/packages/77/b5/c987a5c53c7d8704216f29fc3d810b32f156bcea488a940e330e1bcbb88d/pyzmq-26.2.0-cp313-cp313-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8c997098cc65e3208eca09303630e84d42718620e83b733d0fd69543a9cab9cb", size = 903484 }, - { url = "https://files.pythonhosted.org/packages/29/c9/07da157d2db18c72a7eccef8e684cefc155b712a88e3d479d930aa9eceba/pyzmq-26.2.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7ad1bc8d1b7a18497dda9600b12dc193c577beb391beae5cd2349184db40f187", size = 859981 }, - { url = "https://files.pythonhosted.org/packages/43/09/e12501bd0b8394b7d02c41efd35c537a1988da67fc9c745cae9c6c776d31/pyzmq-26.2.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:bea2acdd8ea4275e1278350ced63da0b166421928276c7c8e3f9729d7402a57b", size = 860334 }, - { url = "https://files.pythonhosted.org/packages/eb/ff/f5ec1d455f8f7385cc0a8b2acd8c807d7fade875c14c44b85c1bddabae21/pyzmq-26.2.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:23f4aad749d13698f3f7b64aad34f5fc02d6f20f05999eebc96b89b01262fb18", size = 1196179 }, - { url = "https://files.pythonhosted.org/packages/ec/8a/bb2ac43295b1950fe436a81fc5b298be0b96ac76fb029b514d3ed58f7b27/pyzmq-26.2.0-cp313-cp313-musllinux_1_1_i686.whl", hash = "sha256:a4f96f0d88accc3dbe4a9025f785ba830f968e21e3e2c6321ccdfc9aef755115", size = 1507668 }, - { url = "https://files.pythonhosted.org/packages/a9/49/dbc284ebcfd2dca23f6349227ff1616a7ee2c4a35fe0a5d6c3deff2b4fed/pyzmq-26.2.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:ced65e5a985398827cc9276b93ef6dfabe0273c23de8c7931339d7e141c2818e", size = 1406539 }, - { url = "https://files.pythonhosted.org/packages/00/68/093cdce3fe31e30a341d8e52a1ad86392e13c57970d722c1f62a1d1a54b6/pyzmq-26.2.0-cp313-cp313-win32.whl", hash = "sha256:31507f7b47cc1ead1f6e86927f8ebb196a0bab043f6345ce070f412a59bf87b5", size = 575567 }, - { url = "https://files.pythonhosted.org/packages/92/ae/6cc4657148143412b5819b05e362ae7dd09fb9fe76e2a539dcff3d0386bc/pyzmq-26.2.0-cp313-cp313-win_amd64.whl", hash = "sha256:70fc7fcf0410d16ebdda9b26cbd8bf8d803d220a7f3522e060a69a9c87bf7bad", size = 637551 }, - { url = "https://files.pythonhosted.org/packages/6c/67/fbff102e201688f97c8092e4c3445d1c1068c2f27bbd45a578df97ed5f94/pyzmq-26.2.0-cp313-cp313-win_arm64.whl", hash = "sha256:c3789bd5768ab5618ebf09cef6ec2b35fed88709b104351748a63045f0ff9797", size = 540378 }, - { url = "https://files.pythonhosted.org/packages/3f/fe/2d998380b6e0122c6c4bdf9b6caf490831e5f5e2d08a203b5adff060c226/pyzmq-26.2.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:034da5fc55d9f8da09015d368f519478a52675e558c989bfcb5cf6d4e16a7d2a", size = 1007378 }, - { url = "https://files.pythonhosted.org/packages/4a/f4/30d6e7157f12b3a0390bde94d6a8567cdb88846ed068a6e17238a4ccf600/pyzmq-26.2.0-cp313-cp313t-macosx_10_15_universal2.whl", hash = "sha256:c92d73464b886931308ccc45b2744e5968cbaade0b1d6aeb40d8ab537765f5bc", size = 1329532 }, - { url = "https://files.pythonhosted.org/packages/82/86/3fe917870e15ee1c3ad48229a2a64458e36036e64b4afa9659045d82bfa8/pyzmq-26.2.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:794a4562dcb374f7dbbfb3f51d28fb40123b5a2abadee7b4091f93054909add5", size = 653242 }, - { url = "https://files.pythonhosted.org/packages/50/2d/242e7e6ef6c8c19e6cb52d095834508cd581ffb925699fd3c640cdc758f1/pyzmq-26.2.0-cp313-cp313t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:aee22939bb6075e7afededabad1a56a905da0b3c4e3e0c45e75810ebe3a52672", size = 888404 }, - { url = "https://files.pythonhosted.org/packages/ac/11/7270566e1f31e4ea73c81ec821a4b1688fd551009a3d2bab11ec66cb1e8f/pyzmq-26.2.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2ae90ff9dad33a1cfe947d2c40cb9cb5e600d759ac4f0fd22616ce6540f72797", size = 845858 }, - { url = "https://files.pythonhosted.org/packages/91/d5/72b38fbc69867795c8711bdd735312f9fef1e3d9204e2f63ab57085434b9/pyzmq-26.2.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:43a47408ac52647dfabbc66a25b05b6a61700b5165807e3fbd40063fcaf46386", size = 847375 }, - { url = "https://files.pythonhosted.org/packages/dd/9a/10ed3c7f72b4c24e719c59359fbadd1a27556a28b36cdf1cd9e4fb7845d5/pyzmq-26.2.0-cp313-cp313t-musllinux_1_1_aarch64.whl", hash = "sha256:25bf2374a2a8433633c65ccb9553350d5e17e60c8eb4de4d92cc6bd60f01d306", size = 1183489 }, - { url = "https://files.pythonhosted.org/packages/72/2d/8660892543fabf1fe41861efa222455811adac9f3c0818d6c3170a1153e3/pyzmq-26.2.0-cp313-cp313t-musllinux_1_1_i686.whl", hash = "sha256:007137c9ac9ad5ea21e6ad97d3489af654381324d5d3ba614c323f60dab8fae6", size = 1492932 }, - { url = "https://files.pythonhosted.org/packages/7b/d6/32fd69744afb53995619bc5effa2a405ae0d343cd3e747d0fbc43fe894ee/pyzmq-26.2.0-cp313-cp313t-musllinux_1_1_x86_64.whl", hash = "sha256:470d4a4f6d48fb34e92d768b4e8a5cc3780db0d69107abf1cd7ff734b9766eb0", size = 1392485 }, -] - -[[package]] -name = "requests" -version = "2.32.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "charset-normalizer" }, - { name = "idna" }, - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/63/70/2bf7780ad2d390a8d301ad0b550f1581eadbd9a20f896afe06353c2a2913/requests-2.32.3.tar.gz", hash = "sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760", size = 131218 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f9/9b/335f9764261e915ed497fcdeb11df5dfd6f7bf257d4a6a2a686d80da4d54/requests-2.32.3-py3-none-any.whl", hash = "sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6", size = 64928 }, -] - -[[package]] -name = "rerun-sdk" -version = "0.18.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "attrs" }, - { name = "numpy" }, - { name = "pillow" }, - { name = "pyarrow" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/b8/57/28eca6dd15bb4f22d8db6b10107b0150f926bfee00d9921ee3666d94ea21/rerun_sdk-0.18.2-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:bc4e73275f428e4e9feb8e85f88db7a9fd18b997b1570de62f949a926978f1b2", size = 33042864 }, - { url = "https://files.pythonhosted.org/packages/97/6c/712f82dcf774f1b9cd7bc4e9a7dc190f2088de22e33ad66486c8058c5455/rerun_sdk-0.18.2-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:efbba40a59710ae83607cb0dc140398a35979c2d2acf5190c9def2ac4697f6a8", size = 32104282 }, - { url = "https://files.pythonhosted.org/packages/83/f9/fe349c911cd61df85167fccffdafedcc923dd2eed055f811b957c8b738b5/rerun_sdk-0.18.2-cp38-abi3-manylinux_2_31_aarch64.whl", hash = "sha256:2a5e3b618b6d1bfde09bd5614a898995f3c318cc69d8f6d569924a2cd41536ce", size = 38459061 }, - { url = "https://files.pythonhosted.org/packages/c9/88/ee72d28bdf8e1821fe6cd3e1de85ca7931706452b4892cb4a90256d78cf0/rerun_sdk-0.18.2-cp38-abi3-manylinux_2_31_x86_64.whl", hash = "sha256:8fdfc4c51ef2e75cb68d39e56f0d7c196eff250cb9a0260c07d5e2d6736e31b0", size = 38761761 }, - { url = "https://files.pythonhosted.org/packages/01/36/f0675261e1e620141515b837f65b015cda05a493153c59158b0ac1b80a3c/rerun_sdk-0.18.2-cp38-abi3-win_amd64.whl", hash = "sha256:c929ade91d3be301b26671b25e70fb529524ced915523d266641c6fc667a1eb5", size = 29534437 }, -] - -[[package]] -name = "ruamel-yaml" -version = "0.18.6" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ruamel-yaml-clib", marker = "python_full_version < '3.13' and platform_python_implementation == 'CPython'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/29/81/4dfc17eb6ebb1aac314a3eb863c1325b907863a1b8b1382cdffcb6ac0ed9/ruamel.yaml-0.18.6.tar.gz", hash = "sha256:8b27e6a217e786c6fbe5634d8f3f11bc63e0f80f6a5890f28863d9c45aac311b", size = 143362 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/73/67/8ece580cc363331d9a53055130f86b096bf16e38156e33b1d3014fffda6b/ruamel.yaml-0.18.6-py3-none-any.whl", hash = "sha256:57b53ba33def16c4f3d807c0ccbc00f8a6081827e81ba2491691b76882d0c636", size = 117761 }, -] - -[[package]] -name = "ruamel-yaml-clib" -version = "0.2.8" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/46/ab/bab9eb1566cd16f060b54055dd39cf6a34bfa0240c53a7218c43e974295b/ruamel.yaml.clib-0.2.8.tar.gz", hash = "sha256:beb2e0404003de9a4cab9753a8805a8fe9320ee6673136ed7f04255fe60bb512", size = 213824 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b1/15/971b385c098e8d0d170893f5ba558452bb7b776a0c90658b8f4dd0e3382b/ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bef08cd86169d9eafb3ccb0a39edb11d8e25f3dae2b28f5c52fd997521133069", size = 148870 }, - { url = "https://files.pythonhosted.org/packages/01/b0/4ddef56e9f703d7909febc3a421d709a3482cda25826816ec595b73e3847/ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:b16420e621d26fdfa949a8b4b47ade8810c56002f5389970db4ddda51dbff248", size = 134475 }, - { url = "https://files.pythonhosted.org/packages/a4/f7/22d6b620ed895a05d40802d8281eff924dc6190f682d933d4efff60db3b5/ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:25c515e350e5b739842fc3228d662413ef28f295791af5e5110b543cf0b57d9b", size = 544020 }, - { url = "https://files.pythonhosted.org/packages/7c/e4/0d19d65e340f93df1c47f323d95fa4b256bb28320290f5fddef90837853a/ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_24_aarch64.whl", hash = "sha256:1707814f0d9791df063f8c19bb51b0d1278b8e9a2353abbb676c2f685dee6afe", size = 642643 }, - { url = "https://files.pythonhosted.org/packages/c9/ff/f781eb5e2ae011e586d5426e2086a011cf1e0f59704a6cad1387975c5a62/ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:46d378daaac94f454b3a0e3d8d78cafd78a026b1d71443f4966c696b48a6d899", size = 695832 }, - { url = "https://files.pythonhosted.org/packages/e3/41/f62e67ac651358b8f0d60cfb12ab2daf99b1b69eeaa188d0cec809d943a6/ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:09b055c05697b38ecacb7ac50bdab2240bfca1a0c4872b0fd309bb07dc9aa3a9", size = 730923 }, - { url = "https://files.pythonhosted.org/packages/9f/f0/19ab8acbf983cd1b37f47d27ceb8b10a738d60d36316a54bad57e0d73fbb/ruamel.yaml.clib-0.2.8-cp311-cp311-win32.whl", hash = "sha256:53a300ed9cea38cf5a2a9b069058137c2ca1ce658a874b79baceb8f892f915a7", size = 99999 }, - { url = "https://files.pythonhosted.org/packages/ec/54/d8a795997921d87224c65d44499ca595a833093fb215b133f920c1062956/ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl", hash = "sha256:c2a72e9109ea74e511e29032f3b670835f8a59bbdc9ce692c5b4ed91ccf1eedb", size = 118008 }, - { url = "https://files.pythonhosted.org/packages/7a/a2/eb5e9d088cb9d15c24d956944c09dca0a89108ad6e2e913c099ef36e3f0d/ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ebc06178e8821efc9692ea7544aa5644217358490145629914d8020042c24aa1", size = 144636 }, - { url = "https://files.pythonhosted.org/packages/66/98/8de4f22bbfd9135deb3422e96d450c4bc0a57d38c25976119307d2efe0aa/ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:edaef1c1200c4b4cb914583150dcaa3bc30e592e907c01117c08b13a07255ec2", size = 135684 }, - { url = "https://files.pythonhosted.org/packages/30/d3/5fe978cd01a61c12efd24d65fa68c6f28f28c8073a06cf11db3a854390ca/ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d176b57452ab5b7028ac47e7b3cf644bcfdc8cacfecf7e71759f7f51a59e5c92", size = 734571 }, - { url = "https://files.pythonhosted.org/packages/55/b3/e2531a050758b717c969cbf76c103b75d8a01e11af931b94ba656117fbe9/ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_24_aarch64.whl", hash = "sha256:1dc67314e7e1086c9fdf2680b7b6c2be1c0d8e3a8279f2e993ca2a7545fecf62", size = 643946 }, - { url = "https://files.pythonhosted.org/packages/0d/aa/06db7ca0995b513538402e11280282c615b5ae5f09eb820460d35fb69715/ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:3213ece08ea033eb159ac52ae052a4899b56ecc124bb80020d9bbceeb50258e9", size = 692169 }, - { url = "https://files.pythonhosted.org/packages/27/38/4cf4d482b84ecdf51efae6635cc5483a83cf5ca9d9c13e205a750e251696/ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aab7fd643f71d7946f2ee58cc88c9b7bfc97debd71dcc93e03e2d174628e7e2d", size = 740325 }, - { url = "https://files.pythonhosted.org/packages/6f/67/c62c6eea53a4feb042727a3d6c18f50dc99683c2b199c06bd2a9e3db8e22/ruamel.yaml.clib-0.2.8-cp312-cp312-win32.whl", hash = "sha256:5c365d91c88390c8d0a8545df0b5857172824b1c604e867161e6b3d59a827eaa", size = 98639 }, - { url = "https://files.pythonhosted.org/packages/10/d2/52a3d810d0b5b3720725c0504a27b3fced7b6f310fe928f7019d79387bc1/ruamel.yaml.clib-0.2.8-cp312-cp312-win_amd64.whl", hash = "sha256:1758ce7d8e1a29d23de54a16ae867abd370f01b5a69e1a3ba75223eaa3ca1a1b", size = 115305 }, -] - -[[package]] -name = "rubicon-objc" -version = "0.4.9" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6d/5f/13512d73208a16c4938622da1c497b14932e2874c0b062d535405d9c6ffb/rubicon_objc-0.4.9.tar.gz", hash = "sha256:3d77a5b2d10cb1e49679aa90b7824b46f67b3fd636229aa4a1b902d24aec6a58", size = 172844 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0b/e3/f3d12557a4eed94dc88c780e0eac87f04d232d1a4f1beffc3fb0e50dc330/rubicon_objc-0.4.9-py3-none-any.whl", hash = "sha256:c351b3800cf74c8c23f7d534f008fd5de46c63818de7a44de96daffdb3ed8b8c", size = 63022 }, -] - -[[package]] -name = "ruff" -version = "0.6.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5d/f9/0b32e5d1c6f957df49398cd882a011e9488fcbca0d6acfeeea50ccd37a4d/ruff-0.6.3.tar.gz", hash = "sha256:183b99e9edd1ef63be34a3b51fee0a9f4ab95add123dbf89a71f7b1f0c991983", size = 2463514 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/72/68/1da6a1e39a03a229ea57c511691d6225072759cc7764206c3f0989521194/ruff-0.6.3-py3-none-linux_armv6l.whl", hash = "sha256:97f58fda4e309382ad30ede7f30e2791d70dd29ea17f41970119f55bdb7a45c3", size = 9696928 }, - { url = "https://files.pythonhosted.org/packages/6e/59/3b8b1d3a4271c6eb6ceecd3cef19a6d881639a0f18ad651563d6f619aaae/ruff-0.6.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:3b061e49b5cf3a297b4d1c27ac5587954ccb4ff601160d3d6b2f70b1622194dc", size = 9448462 }, - { url = "https://files.pythonhosted.org/packages/35/4f/b942ecb8bbebe53aa9b33e9b96df88acd50b70adaaed3070f1d92131a1cb/ruff-0.6.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:34e2824a13bb8c668c71c1760a6ac7d795ccbd8d38ff4a0d8471fdb15de910b1", size = 9176190 }, - { url = "https://files.pythonhosted.org/packages/a0/20/b0bcb29d4ee437f3567b73b6905c034e2e94d29b9b826c66daecc1cf6388/ruff-0.6.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bddfbb8d63c460f4b4128b6a506e7052bad4d6f3ff607ebbb41b0aa19c2770d1", size = 10108892 }, - { url = "https://files.pythonhosted.org/packages/9c/e3/211bc759f424e8823a9937e0f678695ca02113c621dfde1fa756f9f26f6d/ruff-0.6.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ced3eeb44df75353e08ab3b6a9e113b5f3f996bea48d4f7c027bc528ba87b672", size = 9476471 }, - { url = "https://files.pythonhosted.org/packages/b2/a3/2ec35a2d7a554364864206f0e46812b92a074ad8a014b923d821ead532aa/ruff-0.6.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:47021dff5445d549be954eb275156dfd7c37222acc1e8014311badcb9b4ec8c1", size = 10294802 }, - { url = "https://files.pythonhosted.org/packages/03/8b/56ef687b3489c88886dea48c78fb4969b6b65f18007d0ac450070edd1f58/ruff-0.6.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:7d7bd20dc07cebd68cc8bc7b3f5ada6d637f42d947c85264f94b0d1cd9d87384", size = 11022372 }, - { url = "https://files.pythonhosted.org/packages/a5/21/327d147feb442adb88975e81e2263102789eba9ad2afa102c661912a482f/ruff-0.6.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:500f166d03fc6d0e61c8e40a3ff853fa8a43d938f5d14c183c612df1b0d6c58a", size = 10596596 }, - { url = "https://files.pythonhosted.org/packages/6c/86/ff386de63729da3e08c8099c57f577a00ec9f3eea711b23ac07cf3588dc5/ruff-0.6.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:42844ff678f9b976366b262fa2d1d1a3fe76f6e145bd92c84e27d172e3c34500", size = 11572830 }, - { url = "https://files.pythonhosted.org/packages/38/5d/b33284c108e3f315ddd09b70296fd76bd28ecf8965a520bc93f3bbd8ac40/ruff-0.6.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70452a10eb2d66549de8e75f89ae82462159855e983ddff91bc0bce6511d0470", size = 10262577 }, - { url = "https://files.pythonhosted.org/packages/29/99/9cdfad0d7f460e66567236eddc691473791afd9aff93a0dfcdef0462a6c7/ruff-0.6.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:65a533235ed55f767d1fc62193a21cbf9e3329cf26d427b800fdeacfb77d296f", size = 10098751 }, - { url = "https://files.pythonhosted.org/packages/a8/9f/f801a1619f5549e552f1f722f1db57eb39e7e1d83d482133142781d450de/ruff-0.6.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d2e2c23cef30dc3cbe9cc5d04f2899e7f5e478c40d2e0a633513ad081f7361b5", size = 9563859 }, - { url = "https://files.pythonhosted.org/packages/0b/4d/fb2424faf04ffdb960ae2b3a1d991c5183dd981003de727d2d5cc38abc98/ruff-0.6.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:d8a136aa7d228975a6aee3dd8bea9b28e2b43e9444aa678fb62aeb1956ff2351", size = 9914291 }, - { url = "https://files.pythonhosted.org/packages/2e/dd/94fddf002a8f6152e8ebfbb51d3f93febc415c1fe694345623c31ce8b33b/ruff-0.6.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:f92fe93bc72e262b7b3f2bba9879897e2d58a989b4714ba6a5a7273e842ad2f8", size = 10331549 }, - { url = "https://files.pythonhosted.org/packages/b4/73/ca9c2f9237a430ca423b6dca83b77e9a428afeb7aec80596e86c369123fe/ruff-0.6.3-py3-none-win32.whl", hash = "sha256:7a62d3b5b0d7f9143d94893f8ba43aa5a5c51a0ffc4a401aa97a81ed76930521", size = 7962163 }, - { url = "https://files.pythonhosted.org/packages/55/ce/061c605b1dfb52748d59bc0c7a8507546c178801156415773d18febfd71d/ruff-0.6.3-py3-none-win_amd64.whl", hash = "sha256:746af39356fee2b89aada06c7376e1aa274a23493d7016059c3a72e3b296befb", size = 8800901 }, - { url = "https://files.pythonhosted.org/packages/63/28/ae4ffe7d3b6134ca6d31ebef07447ef70097c4a9e8fbbc519b374c5c1559/ruff-0.6.3-py3-none-win_arm64.whl", hash = "sha256:14a9528a8b70ccc7a847637c29e56fd1f9183a9db743bbc5b8e0c4ad60592a82", size = 8229171 }, -] - -[[package]] -name = "scons" -version = "4.8.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ec/5c/cc835a17633de8b260ec1a6e527b5c57f4975cee5949f49e57ad4d5fab4b/scons-4.8.0.tar.gz", hash = "sha256:2c7377ff6a22ca136c795ae3dc3d0824696e5478d1e4940f2af75659b0d45454", size = 3243129 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7b/01/4ea08ba8414db39e597939ff82d587082674f616f78e3dc505dae4b6a176/SCons-4.8.0-py3-none-any.whl", hash = "sha256:760fbfd05e459113e9a1362ab2b00e12ea4195607e820a127d30e6275c8436a1", size = 4122772 }, -] - -[[package]] -name = "sentry-sdk" -version = "2.13.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bb/41/97f673384dae5ed81cc2a568cc5c28e76deee85f8ba50def862e86150a5a/sentry_sdk-2.13.0.tar.gz", hash = "sha256:8d4a576f7a98eb2fdb40e13106e41f330e5c79d72a68be1316e7852cf4995260", size = 279937 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ad/7e/e9ca09f24a6c334286631a2d32c267cdc5edad5ac03fd9d20a01a82f1c35/sentry_sdk-2.13.0-py2.py3-none-any.whl", hash = "sha256:6beede8fc2ab4043da7f69d95534e320944690680dd9a963178a49de71d726c6", size = 309078 }, -] - -[[package]] -name = "setproctitle" -version = "1.3.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ff/e1/b16b16a1aa12174349d15b73fd4b87e641a8ae3fb1163e80938dbbf6ae98/setproctitle-1.3.3.tar.gz", hash = "sha256:c913e151e7ea01567837ff037a23ca8740192880198b7fbb90b16d181607caae", size = 27253 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/17/7f9d5ddf4cfc4386e74565ccf63b8381396336e4629bb165b52b803ceddb/setproctitle-1.3.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:334f7ed39895d692f753a443102dd5fed180c571eb6a48b2a5b7f5b3564908c8", size = 16948 }, - { url = "https://files.pythonhosted.org/packages/ff/5d/77edf4c29c8d6728b49d3f0abb22159bb9c0c4ddebd721c09486b34985c8/setproctitle-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:950f6476d56ff7817a8fed4ab207727fc5260af83481b2a4b125f32844df513a", size = 11305 }, - { url = "https://files.pythonhosted.org/packages/13/f0/263954ca925a278036f100405e7ba82d4341e1e6bdc09f35362a7b40f684/setproctitle-1.3.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:195c961f54a09eb2acabbfc90c413955cf16c6e2f8caa2adbf2237d1019c7dd8", size = 31578 }, - { url = "https://files.pythonhosted.org/packages/79/52/503b546da451deb78fde27fec96c39d3f63a7958be60c9a837de89f47a0d/setproctitle-1.3.3-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f05e66746bf9fe6a3397ec246fe481096664a9c97eb3fea6004735a4daf867fd", size = 32910 }, - { url = "https://files.pythonhosted.org/packages/48/72/aeb734419a58a85ca7845c3d0011c322597da4ff601ebbc28f6c1dfd1ae8/setproctitle-1.3.3-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b5901a31012a40ec913265b64e48c2a4059278d9f4e6be628441482dd13fb8b5", size = 30086 }, - { url = "https://files.pythonhosted.org/packages/fd/df/44b267cb8f073a4ae77e120f0705ab3a07165ad90cecd4881b34c7e1e37b/setproctitle-1.3.3-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:64286f8a995f2cd934082b398fc63fca7d5ffe31f0e27e75b3ca6b4efda4e353", size = 31076 }, - { url = "https://files.pythonhosted.org/packages/82/c2/79ad43c914418cb1920e0198ac7326061c05cd4ec75c86ed0ca456b7e957/setproctitle-1.3.3-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:184239903bbc6b813b1a8fc86394dc6ca7d20e2ebe6f69f716bec301e4b0199d", size = 41226 }, - { url = "https://files.pythonhosted.org/packages/81/1b/0498c36a07a73d39a7070f45d96a299006e624efc07fc2e2296286237316/setproctitle-1.3.3-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:664698ae0013f986118064b6676d7dcd28fefd0d7d5a5ae9497cbc10cba48fa5", size = 39723 }, - { url = "https://files.pythonhosted.org/packages/3a/fe/ebbcffd6012b9cf5edb017a9c30cfc2beccf707f5bf495da8cf69b4abe69/setproctitle-1.3.3-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:e5119a211c2e98ff18b9908ba62a3bd0e3fabb02a29277a7232a6fb4b2560aa0", size = 42773 }, - { url = "https://files.pythonhosted.org/packages/64/b1/5786c0442435eb18d04299c8ce7d1f86feb5154444ac684963527a76e169/setproctitle-1.3.3-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:417de6b2e214e837827067048f61841f5d7fc27926f2e43954567094051aff18", size = 41089 }, - { url = "https://files.pythonhosted.org/packages/33/fb/14b41e920406a12de0a164ef3b86d62edb4fac63d91d9f86f3b80dae5b38/setproctitle-1.3.3-cp311-cp311-win32.whl", hash = "sha256:6a143b31d758296dc2f440175f6c8e0b5301ced3b0f477b84ca43cdcf7f2f476", size = 11066 }, - { url = "https://files.pythonhosted.org/packages/7e/ba/f6da9ba74e8c2c662e932b27a01025c1bee2846222f6a2e87a69c259772f/setproctitle-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:a680d62c399fa4b44899094027ec9a1bdaf6f31c650e44183b50d4c4d0ccc085", size = 11817 }, - { url = "https://files.pythonhosted.org/packages/32/22/9672612b194e4ac5d9fb67922ad9d30232b4b66129b0381ab5efeb6ae88f/setproctitle-1.3.3-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:d4460795a8a7a391e3567b902ec5bdf6c60a47d791c3b1d27080fc203d11c9dc", size = 16917 }, - { url = "https://files.pythonhosted.org/packages/49/e5/562ff00f2f3f4253ff8fa6886e0432b8eae8cde82530ac19843d8ed2c485/setproctitle-1.3.3-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:bdfd7254745bb737ca1384dee57e6523651892f0ea2a7344490e9caefcc35e64", size = 11264 }, - { url = "https://files.pythonhosted.org/packages/8f/1f/f97ea7bf71c873590a63d62ba20bf7294439d1c28603e5c63e3616c2131a/setproctitle-1.3.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:477d3da48e216d7fc04bddab67b0dcde633e19f484a146fd2a34bb0e9dbb4a1e", size = 31907 }, - { url = "https://files.pythonhosted.org/packages/66/fb/2d90806b9a2ed97c140baade3d1d2d41d3b51458300a2d999268be24d21d/setproctitle-1.3.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ab2900d111e93aff5df9fddc64cf51ca4ef2c9f98702ce26524f1acc5a786ae7", size = 33333 }, - { url = "https://files.pythonhosted.org/packages/38/39/e7ce791f5635f3a16bd21d6b79bd9280c4c4aed8ab936b4b21334acf05a7/setproctitle-1.3.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:088b9efc62d5aa5d6edf6cba1cf0c81f4488b5ce1c0342a8b67ae39d64001120", size = 30573 }, - { url = "https://files.pythonhosted.org/packages/20/22/fd76bbde4194d4e31d5b31a02f80c8e7e54a99d3d8ff34f3d656c6655689/setproctitle-1.3.3-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a6d50252377db62d6a0bb82cc898089916457f2db2041e1d03ce7fadd4a07381", size = 31601 }, - { url = "https://files.pythonhosted.org/packages/51/5c/a6257cc68e17abcc4d4a78cc6666aa0d3805af6d942576625c4a468a72f0/setproctitle-1.3.3-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:87e668f9561fd3a457ba189edfc9e37709261287b52293c115ae3487a24b92f6", size = 40717 }, - { url = "https://files.pythonhosted.org/packages/db/31/4f0faad7ef641be4e8dfcbc40829775f2d6a4ca1ff435a4074047fa3dad1/setproctitle-1.3.3-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:287490eb90e7a0ddd22e74c89a92cc922389daa95babc833c08cf80c84c4df0a", size = 39384 }, - { url = "https://files.pythonhosted.org/packages/22/17/8763dc4f9ddf36af5f043ceec213b0f9f45f09fd2d5061a89c699aabe8b0/setproctitle-1.3.3-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:4fe1c49486109f72d502f8be569972e27f385fe632bd8895f4730df3c87d5ac8", size = 42350 }, - { url = "https://files.pythonhosted.org/packages/7b/b2/2403cecf2e5c5b4da22f7d9df4b2149bf92d03a3422185e682e81055549c/setproctitle-1.3.3-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4a6ba2494a6449b1f477bd3e67935c2b7b0274f2f6dcd0f7c6aceae10c6c6ba3", size = 40704 }, - { url = "https://files.pythonhosted.org/packages/5e/c1/11e80061ac06aece2a0ffcaf018cdc088aebb2fc586f68201755518532ad/setproctitle-1.3.3-cp312-cp312-win32.whl", hash = "sha256:2df2b67e4b1d7498632e18c56722851ba4db5d6a0c91aaf0fd395111e51cdcf4", size = 11057 }, - { url = "https://files.pythonhosted.org/packages/90/e8/ece468e93e99d3b2826e9649f6d03e80f071d451e20c742f201f77d1bea1/setproctitle-1.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:f38d48abc121263f3b62943f84cbaede05749047e428409c2c199664feb6abc7", size = 11809 }, -] - -[[package]] -name = "setuptools" -version = "74.1.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/27/cb/e754933c1ca726b0d99980612dc9da2886e76c83968c246cfb50f491a96b/setuptools-74.1.1.tar.gz", hash = "sha256:2353af060c06388be1cecbf5953dcdb1f38362f87a2356c480b6b4d5fcfc8847", size = 1357738 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/48/f3/e30ee63caefa90716afdffd7d9ae959cd8d0dbd2d0a0eb9fe1d73ddf806b/setuptools-74.1.1-py3-none-any.whl", hash = "sha256:fc91b5f89e392ef5b77fe143b17e32f65d3024744fba66dc3afe07201684d766", size = 1263655 }, -] - -[[package]] -name = "shapely" -version = "2.0.6" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/4a/89/0d20bac88016be35ff7d3c0c2ae64b477908f1b1dfa540c5d69ac7af07fe/shapely-2.0.6.tar.gz", hash = "sha256:997f6159b1484059ec239cacaa53467fd8b5564dabe186cd84ac2944663b0bf6", size = 282361 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/37/15/269d8e1f7f658a37e61f7028683c546f520e4e7cedba1e32c77ff9d3a3c7/shapely-2.0.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5aeb0f51a9db176da9a30cb2f4329b6fbd1e26d359012bb0ac3d3c7781667a9e", size = 1449578 }, - { url = "https://files.pythonhosted.org/packages/37/63/e182e43081fffa0a2d970c480f2ef91647a6ab94098f61748c23c2a485f2/shapely-2.0.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9a7a78b0d51257a367ee115f4d41ca4d46edbd0dd280f697a8092dd3989867b2", size = 1296792 }, - { url = "https://files.pythonhosted.org/packages/6e/5a/d019f69449329dcd517355444fdb9ddd58bec5e080b8bdba007e8e4c546d/shapely-2.0.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f32c23d2f43d54029f986479f7c1f6e09c6b3a19353a3833c2ffb226fb63a855", size = 2443997 }, - { url = "https://files.pythonhosted.org/packages/25/aa/53f145e5a610a49af9ac49f2f1be1ec8659ebd5c393d66ac94e57c83b00e/shapely-2.0.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b3dc9fb0eb56498912025f5eb352b5126f04801ed0e8bdbd867d21bdbfd7cbd0", size = 2528334 }, - { url = "https://files.pythonhosted.org/packages/64/64/0c7b0a22b416d36f6296b92bb4219d82b53d0a7c47e16fd0a4c85f2f117c/shapely-2.0.6-cp311-cp311-win32.whl", hash = "sha256:d93b7e0e71c9f095e09454bf18dad5ea716fb6ced5df3cb044564a00723f339d", size = 1294669 }, - { url = "https://files.pythonhosted.org/packages/b1/5a/6a67d929c467a1973b6bb9f0b00159cc343b02bf9a8d26db1abd2f87aa23/shapely-2.0.6-cp311-cp311-win_amd64.whl", hash = "sha256:c02eb6bf4cfb9fe6568502e85bb2647921ee49171bcd2d4116c7b3109724ef9b", size = 1442032 }, - { url = "https://files.pythonhosted.org/packages/46/77/efd9f9d4b6a762f976f8b082f54c9be16f63050389500fb52e4f6cc07c1a/shapely-2.0.6-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:cec9193519940e9d1b86a3b4f5af9eb6910197d24af02f247afbfb47bcb3fab0", size = 1450326 }, - { url = "https://files.pythonhosted.org/packages/68/53/5efa6e7a4036a94fe6276cf7bbb298afded51ca3396b03981ad680c8cc7d/shapely-2.0.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:83b94a44ab04a90e88be69e7ddcc6f332da7c0a0ebb1156e1c4f568bbec983c3", size = 1298480 }, - { url = "https://files.pythonhosted.org/packages/88/a2/1be1db4fc262e536465a52d4f19d85834724fedf2299a1b9836bc82fe8fa/shapely-2.0.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:537c4b2716d22c92036d00b34aac9d3775e3691f80c7aa517c2c290351f42cd8", size = 2439311 }, - { url = "https://files.pythonhosted.org/packages/d5/7d/9a57e187cbf2fbbbdfd4044a4f9ce141c8d221f9963750d3b001f0ec080d/shapely-2.0.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:98fea108334be345c283ce74bf064fa00cfdd718048a8af7343c59eb40f59726", size = 2524835 }, - { url = "https://files.pythonhosted.org/packages/6d/0a/f407509ab56825f39bf8cfce1fb410238da96cf096809c3e404e5bc71ea1/shapely-2.0.6-cp312-cp312-win32.whl", hash = "sha256:42fd4cd4834747e4990227e4cbafb02242c0cffe9ce7ef9971f53ac52d80d55f", size = 1295613 }, - { url = "https://files.pythonhosted.org/packages/7b/b3/857afd9dfbfc554f10d683ac412eac6fa260d1f4cd2967ecb655c57e831a/shapely-2.0.6-cp312-cp312-win_amd64.whl", hash = "sha256:665990c84aece05efb68a21b3523a6b2057e84a1afbef426ad287f0796ef8a48", size = 1442539 }, - { url = "https://files.pythonhosted.org/packages/34/e8/d164ef5b0eab86088cde06dee8415519ffd5bb0dd1bd9d021e640e64237c/shapely-2.0.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:42805ef90783ce689a4dde2b6b2f261e2c52609226a0438d882e3ced40bb3013", size = 1445344 }, - { url = "https://files.pythonhosted.org/packages/ce/e2/9fba7ac142f7831757a10852bfa465683724eadbc93d2d46f74a16f9af04/shapely-2.0.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6d2cb146191a47bd0cee8ff5f90b47547b82b6345c0d02dd8b25b88b68af62d7", size = 1296182 }, - { url = "https://files.pythonhosted.org/packages/cf/dc/790d4bda27d196cd56ec66975eaae3351c65614cafd0e16ddde39ec9fb92/shapely-2.0.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e3fdef0a1794a8fe70dc1f514440aa34426cc0ae98d9a1027fb299d45741c381", size = 2423426 }, - { url = "https://files.pythonhosted.org/packages/af/b0/f8169f77eac7392d41e231911e0095eb1148b4d40c50ea9e34d999c89a7e/shapely-2.0.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c665a0301c645615a107ff7f52adafa2153beab51daf34587170d85e8ba6805", size = 2513249 }, - { url = "https://files.pythonhosted.org/packages/f6/1d/a8c0e9ab49ff2f8e4dedd71b0122eafb22a18ad7e9d256025e1f10c84704/shapely-2.0.6-cp313-cp313-win32.whl", hash = "sha256:0334bd51828f68cd54b87d80b3e7cee93f249d82ae55a0faf3ea21c9be7b323a", size = 1294848 }, - { url = "https://files.pythonhosted.org/packages/23/38/2bc32dd1e7e67a471d4c60971e66df0bdace88656c47a9a728ace0091075/shapely-2.0.6-cp313-cp313-win_amd64.whl", hash = "sha256:d37d070da9e0e0f0a530a621e17c0b8c3c9d04105655132a87cfff8bd77cc4c2", size = 1441371 }, -] - -[[package]] -name = "siphash24" -version = "1.6" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/19/d8/beb5183d1acc5a013d273452eac750b51e40855917a1841dead80fcf3086/siphash24-1.6.tar.gz", hash = "sha256:242d6901a81260f618938635a25ae7f208e744f7ee6c571f1b255c1c4c62917d", size = 19659 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/a5/0ffc51fe2e5f96258f0edfae15944006b09517ad7e98fdcbda05c67c70f6/siphash24-1.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3e1b3963c392a2d63cbe16af9171d789d2f15e69eb8314b21fe1e11bdc08205f", size = 80669 }, - { url = "https://files.pythonhosted.org/packages/80/ea/41d648cbbf3248a30f545f9e41ad5dedee19fcbad1d2baa7e39ae6f2779e/siphash24-1.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:de23d12c8a015904081e347900433a0c4b5e07690dbd0a104ad88929f3b91948", size = 75379 }, - { url = "https://files.pythonhosted.org/packages/48/a7/d6dcc551c8d53e436c58b7ecc96d1de0c0379c21b1e71b2543d38c039c95/siphash24-1.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8be513de01677e57989e028185a16e531942f7a9578d441481abe8b1085c45d6", size = 100466 }, - { url = "https://files.pythonhosted.org/packages/eb/46/b906d7e05e3d84239d6a04e3d5f106d96ab26483951c7cf2c5769ea8c894/siphash24-1.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ef89477ce8f2e67fca025ad9b1c85b7498c6959baa7d9a502cbb5d8c7085f5b7", size = 105913 }, - { url = "https://files.pythonhosted.org/packages/4c/98/20159e2be9a957da2dffb3e18648c51ea7a0f09c49b8dce1cb268ca55ca7/siphash24-1.6-cp311-cp311-win32.whl", hash = "sha256:f702e646dc60b7d7915fa37f9357a03a2ec41ffb360b6946baf4801eb9f7e98f", size = 67528 }, - { url = "https://files.pythonhosted.org/packages/0d/0a/d8da621e624f3dbcf9a7a8066c54ddd2f6af437fc23169431caf6f9b403b/siphash24-1.6-cp311-cp311-win_amd64.whl", hash = "sha256:38715f61f0873e4a8b05125e14f349f465c64a1aaf79b6af0ff6f5f420d55dc5", size = 79961 }, - { url = "https://files.pythonhosted.org/packages/12/e4/ed944e92883b45996cf2c94447dd47b899c87674340b081b9e8cb317a88f/siphash24-1.6-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:51eefacbe82f8f48bc603eb97f54bf3819324349b69a9cd131ba02c40b1e6c61", size = 82399 }, - { url = "https://files.pythonhosted.org/packages/f9/d1/6ddbd7ba8972789f60282b9b9b1f88f08d26ef0913906e8ad5a9806c8432/siphash24-1.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c63321003aa1856b1bfd48e6ffbd4bff98afeaacb0fc902cb2ae44b861476335", size = 76253 }, - { url = "https://files.pythonhosted.org/packages/0d/87/0f125c1e069d09c4a39ab09d76fa9d4fe698bde68197627faeb38603f643/siphash24-1.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f0ff4d068e9b0b3f138ef8e8b6f5de1990539d9d590e75a9a8beb6887535184a", size = 98184 }, - { url = "https://files.pythonhosted.org/packages/86/57/a274de0a91016cd4f870334a2af1193ffcdb88e34345ca098afea6dd10cb/siphash24-1.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4c1a671d91095e1872ca9988695200064ccca8db60133638d6061755fe669552", size = 103311 }, - { url = "https://files.pythonhosted.org/packages/5d/d4/b6a0c9f119b22938e36d74e0859167ae76c0ea0f7d7786eb48120b0e129d/siphash24-1.6-cp312-cp312-win32.whl", hash = "sha256:2dab672fcda08149b8c15f82ee74d732386428f53239cdb002ac2ad0a1f2f2bc", size = 68366 }, - { url = "https://files.pythonhosted.org/packages/ef/de/6ebd0f96184f8479e8348dcba93a9f14ff54ac3c6a68866cc77c334d7bdf/siphash24-1.6-cp312-cp312-win_amd64.whl", hash = "sha256:226af78af3b992c953cc4808f2c6a4bba320e91e6c89b34aa2492064fa417ae8", size = 81096 }, -] - -[[package]] -name = "six" -version = "1.16.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/71/39/171f1c67cd00715f190ba0b100d606d440a28c93c7714febeca8b79af85e/six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926", size = 34041 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d9/5a/e7c31adbe875f2abbb91bd84cf2dc52d792b5a01506781dbcf25c91daf11/six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254", size = 11053 }, -] - -[[package]] -name = "smbus2" -version = "0.4.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/98/17/9663936e52a348b3ad1c85e6ca6071d2abf00a5f64f2df50bec8dcca6e16/smbus2-0.4.3.tar.gz", hash = "sha256:36f2288a8e1a363cb7a7b2244ec98d880eb5a728a2494ac9c71e9de7bf6a803a", size = 16801 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d6/5b/3ada173f07b4ec9bfa03b779e59ecada48eb7cb1a29f51cfce70edce7f3f/smbus2-0.4.3-py2.py3-none-any.whl", hash = "sha256:a2fc29cfda4081ead2ed61ef2c4fc041d71dd40a8d917e85216f44786fca2d1d", size = 11553 }, -] - -[[package]] -name = "sortedcontainers" -version = "2.4.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575 }, -] - -[[package]] -name = "sounddevice" -version = "0.5.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cffi" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/87/92/62d87d7b53a4e1041f0d9e049e225fce3c7bc266c0162c023feb245b999d/sounddevice-0.5.0.tar.gz", hash = "sha256:0de95277654b3d403d9c15ded3c6cedf307e9b27cc9ce7bd995a2891d0c955af", size = 52564 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e6/3c/241480772b55a39d4c07f2d88cf43e0a2955cc662f369c33dfb4fb79e9fa/sounddevice-0.5.0-py3-none-any.whl", hash = "sha256:8a734043ab1f751cb20f6f25d8f07408a1aadf2eeca923061849d38bb59f9e3d", size = 32107 }, - { url = "https://files.pythonhosted.org/packages/61/10/10f05bbe463424467bb24e4804130fb854d7cc0bc7aa7c040867f21cc997/sounddevice-0.5.0-py3-none-macosx_10_6_x86_64.macosx_10_6_universal2.whl", hash = "sha256:73eb7cb1e8ab1e1ba09c228239e9d0b160006de380921687e44610ad9a19ac32", size = 107746 }, - { url = "https://files.pythonhosted.org/packages/73/4c/783f44af582a5e6cdecbc14e154ab0775c9e645a9567869facd172ecd582/sounddevice-0.5.0-py3-none-win32.whl", hash = "sha256:919de43040e8737258370ddf929a9cd1a3d6c493ca173bab70a3c7cb15c71e97", size = 167621 }, - { url = "https://files.pythonhosted.org/packages/bf/2a/58fa1704b5cf8041564337674790426d39d630e7407e54e17a1212332959/sounddevice-0.5.0-py3-none-win_amd64.whl", hash = "sha256:f28b7ef16f293d7b048a614dd087dfe39c3e313d94a50539bb52022b7ef27ece", size = 189785 }, -] - -[[package]] -name = "spidev" -version = "3.6" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c7/d9/401c0a7be089e02826cf2c201f489876b601f15be100fe391ef9c2faed83/spidev-3.6.tar.gz", hash = "sha256:14dbc37594a4aaef85403ab617985d3c3ef464d62bc9b769ef552db53701115b", size = 11917 } - -[[package]] -name = "sympy" -version = "1.13.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mpmath" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/94/15/4a041424c7187f41cce678f5a02189b244e9aac61a18b45cd415a3a470f3/sympy-1.13.2.tar.gz", hash = "sha256:401449d84d07be9d0c7a46a64bd54fe097667d5e7181bfe67ec777be9e01cb13", size = 7532926 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c1/f9/6845bf8fca0eaf847da21c5d5bc6cd92797364662824a11d3f836423a1a5/sympy-1.13.2-py3-none-any.whl", hash = "sha256:c51d75517712f1aed280d4ce58506a4a88d635d6b5dd48b39102a7ae1f3fcfe9", size = 6189289 }, -] - -[[package]] -name = "tabulate" -version = "0.9.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ec/fe/802052aecb21e3797b8f7902564ab6ea0d60ff8ca23952079064155d1ae1/tabulate-0.9.0.tar.gz", hash = "sha256:0095b12bf5966de529c0feb1fa08671671b3368eec77d7ef7ab114be2c068b3c", size = 81090 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/40/44/4a5f08c96eb108af5cb50b41f76142f0afa346dfa99d5296fe7202a11854/tabulate-0.9.0-py3-none-any.whl", hash = "sha256:024ca478df22e9340661486f85298cff5f6dcdba14f3813e8830015b9ed1948f", size = 35252 }, -] - -[[package]] -name = "tomli" -version = "2.0.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c0/3f/d7af728f075fb08564c5949a9c95e44352e23dee646869fa104a3b2060a3/tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f", size = 15164 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/97/75/10a9ebee3fd790d20926a90a2547f0bf78f371b2f13aa822c759680ca7b9/tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc", size = 12757 }, -] - -[[package]] -name = "tqdm" -version = "4.66.5" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama", marker = "platform_system == 'Windows'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/58/83/6ba9844a41128c62e810fddddd72473201f3eacde02046066142a2d96cc5/tqdm-4.66.5.tar.gz", hash = "sha256:e1020aef2e5096702d8a025ac7d16b1577279c9d63f8375b63083e9a5f0fcbad", size = 169504 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/48/5d/acf5905c36149bbaec41ccf7f2b68814647347b72075ac0b1fe3022fdc73/tqdm-4.66.5-py3-none-any.whl", hash = "sha256:90279a3770753eafc9194a0364852159802111925aa30eb3f9d85b0e805ac7cd", size = 78351 }, -] - -[[package]] -name = "types-requests" -version = "2.32.0.20240712" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5e/9e/7663eb27c33568b8fc20ccdaf2a1ce53a9530c42a7cceb9f552a6ff4a1d8/types-requests-2.32.0.20240712.tar.gz", hash = "sha256:90c079ff05e549f6bf50e02e910210b98b8ff1ebdd18e19c873cd237737c1358", size = 17896 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/30/4d/cbed87a6912fbd9259ce23a5d4aa1de9816edf75eec6ed9a757c00906c8e/types_requests-2.32.0.20240712-py3-none-any.whl", hash = "sha256:f754283e152c752e46e70942fa2a146b5bc70393522257bb85bd1ef7e019dcc3", size = 15816 }, -] - -[[package]] -name = "types-tabulate" -version = "0.9.0.20240106" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/cf/9d/65b82ce032fd1cc4df752461175a800c1cfc336461f07ceff10c6a5913eb/types-tabulate-0.9.0.20240106.tar.gz", hash = "sha256:c9b6db10dd7fcf55bd1712dd3537f86ddce72a08fd62bb1af4338c7096ce947e", size = 3442 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f0/17/d53c0bb370100313df6800e9096bdfc27b32b8e4a9390bfb35bc4b17db78/types_tabulate-0.9.0.20240106-py3-none-any.whl", hash = "sha256:0378b7b6fe0ccb4986299496d027a6d4c218298ecad67199bbd0e2d7e9d335a1", size = 3350 }, -] - -[[package]] -name = "typing-extensions" -version = "4.12.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/df/db/f35a00659bc03fec321ba8bce9420de607a1d37f8342eee1863174c69557/typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8", size = 85321 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/26/9f/ad63fc0248c5379346306f8668cda6e2e2e9c95e01216d2b8ffd9ff037d0/typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d", size = 37438 }, -] - -[[package]] -name = "urllib3" -version = "2.2.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/43/6d/fa469ae21497ddc8bc93e5877702dca7cb8f911e337aca7452b5724f1bb6/urllib3-2.2.2.tar.gz", hash = "sha256:dd505485549a7a552833da5e6063639d0d177c04f23bc3864e41e5dc5f612168", size = 292266 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ca/1c/89ffc63a9605b583d5df2be791a27bc1a42b7c32bab68d3c8f2f73a98cd4/urllib3-2.2.2-py3-none-any.whl", hash = "sha256:a448b2f64d686155468037e1ace9f2d2199776e17f0a46610480d311f73e3472", size = 121444 }, -] - -[[package]] -name = "watchdog" -version = "5.0.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/cd/5e/95dcd86d8339fcf76385f7fad5e49cbfd989b6c6199127121c9587febc65/watchdog-5.0.2.tar.gz", hash = "sha256:dcebf7e475001d2cdeb020be630dc5b687e9acdd60d16fea6bb4508e7b94cf76", size = 127779 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/80/52/51046f428e813270cd959bee9d2343f103c10adf10e957f69d6710a38ab8/watchdog-5.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:dae7a1879918f6544201d33666909b040a46421054a50e0f773e0d870ed7438d", size = 96276 }, - { url = "https://files.pythonhosted.org/packages/b3/8e/0e5671f3950fd2049bbeb8c965cb53e143bfd72869e5e4c60dda572121cd/watchdog-5.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c4a440f725f3b99133de610bfec93d570b13826f89616377715b9cd60424db6e", size = 88269 }, - { url = "https://files.pythonhosted.org/packages/b5/34/9c436ec85f7234b468e49380f57cc784b4e22f058febe17221f25ce85c4b/watchdog-5.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f8b2918c19e0d48f5f20df458c84692e2a054f02d9df25e6c3c930063eca64c1", size = 88914 }, - { url = "https://files.pythonhosted.org/packages/ef/41/fe19a56aa8ea7e453311f2b4fd2bfb172d21bd72ef6ae0fd40c304c74edf/watchdog-5.0.2-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:aa9cd6e24126d4afb3752a3e70fce39f92d0e1a58a236ddf6ee823ff7dba28ee", size = 96365 }, - { url = "https://files.pythonhosted.org/packages/cc/02/86d631595ec1c5678e23e9359741d2dea460be0712b41a243281b37e90ba/watchdog-5.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:f627c5bf5759fdd90195b0c0431f99cff4867d212a67b384442c51136a098ed7", size = 88330 }, - { url = "https://files.pythonhosted.org/packages/d8/a7/5c57f05def91ff11528f0aa0d4c23efc99fa064ec69c262fedc6c9885697/watchdog-5.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d7594a6d32cda2b49df3fd9abf9b37c8d2f3eab5df45c24056b4a671ac661619", size = 88935 }, - { url = "https://files.pythonhosted.org/packages/80/1a/a681c0093eea33b18a7348b398302628ab96647f59eaf06a5a047e8a1f39/watchdog-5.0.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ba32efcccfe2c58f4d01115440d1672b4eb26cdd6fc5b5818f1fb41f7c3e1889", size = 96362 }, - { url = "https://files.pythonhosted.org/packages/c4/aa/0c827bd35716d91b5a4a2a6c5ca7638d936e6055dec8ce85414383ab887f/watchdog-5.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:963f7c4c91e3f51c998eeff1b3fb24a52a8a34da4f956e470f4b068bb47b78ee", size = 88336 }, - { url = "https://files.pythonhosted.org/packages/6e/ba/da13d47dacc84bfab52310e74f954eb440c5cdee11ff8786228f17343a3d/watchdog-5.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8c47150aa12f775e22efff1eee9f0f6beee542a7aa1a985c271b1997d340184f", size = 88938 }, - { url = "https://files.pythonhosted.org/packages/5b/cb/c13dfc4714547c4a63f27a50d5d0bbda655ef06d93595c016822ff771032/watchdog-5.0.2-py3-none-manylinux2014_aarch64.whl", hash = "sha256:5597c051587f8757798216f2485e85eac583c3b343e9aa09127a3a6f82c65ee8", size = 78960 }, - { url = "https://files.pythonhosted.org/packages/cb/ed/78acaa8e95e193a46925f7beeed45c29569d0ee572216df622bb0908abf3/watchdog-5.0.2-py3-none-manylinux2014_armv7l.whl", hash = "sha256:53ed1bf71fcb8475dd0ef4912ab139c294c87b903724b6f4a8bd98e026862e6d", size = 78960 }, - { url = "https://files.pythonhosted.org/packages/2f/54/30bde6279d2f77e6c2838a89e9975038bba4adbfb029f9b8e01cf2813199/watchdog-5.0.2-py3-none-manylinux2014_i686.whl", hash = "sha256:29e4a2607bd407d9552c502d38b45a05ec26a8e40cc7e94db9bb48f861fa5abc", size = 78958 }, - { url = "https://files.pythonhosted.org/packages/f4/db/886241c6d02f165fbf633b633dc5ceddc6c145fec3704828606743ddb663/watchdog-5.0.2-py3-none-manylinux2014_ppc64.whl", hash = "sha256:b6dc8f1d770a8280997e4beae7b9a75a33b268c59e033e72c8a10990097e5fde", size = 78957 }, - { url = "https://files.pythonhosted.org/packages/a9/74/c255a2146280adcb2d1b5ccb7580e71114b253f356a6c4ea748b0eb7a7b5/watchdog-5.0.2-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:d2ab34adc9bf1489452965cdb16a924e97d4452fcf88a50b21859068b50b5c3b", size = 78960 }, - { url = "https://files.pythonhosted.org/packages/8a/dc/4bdc31a35ffce526280c5a29b64b939624761f47e3fcdac34808589d0845/watchdog-5.0.2-py3-none-manylinux2014_s390x.whl", hash = "sha256:7d1aa7e4bb0f0c65a1a91ba37c10e19dabf7eaaa282c5787e51371f090748f4b", size = 78959 }, - { url = "https://files.pythonhosted.org/packages/9d/53/e71b01aa5737a21664b731de5f91c5b0721ff64d237e43efc56a99254fa1/watchdog-5.0.2-py3-none-manylinux2014_x86_64.whl", hash = "sha256:726eef8f8c634ac6584f86c9c53353a010d9f311f6c15a034f3800a7a891d941", size = 78959 }, - { url = "https://files.pythonhosted.org/packages/5d/0e/c37862900200436a554a4c411645f29887fe3fb4d4e465fbedcf1e0e383a/watchdog-5.0.2-py3-none-win32.whl", hash = "sha256:bda40c57115684d0216556671875e008279dea2dc00fcd3dde126ac8e0d7a2fb", size = 78947 }, - { url = "https://files.pythonhosted.org/packages/8f/ab/f1a3791be609e18596ce6a52c00274f1b244340b87379eb78c4df15f6b2b/watchdog-5.0.2-py3-none-win_amd64.whl", hash = "sha256:d010be060c996db725fbce7e3ef14687cdcc76f4ca0e4339a68cc4532c382a73", size = 78950 }, - { url = "https://files.pythonhosted.org/packages/53/99/f5065334d157518ec8c707aa790c93d639fac582be4f7caec5db8c6fa089/watchdog-5.0.2-py3-none-win_ia64.whl", hash = "sha256:3960136b2b619510569b90f0cd96408591d6c251a75c97690f4553ca88889769", size = 78948 }, -] - -[[package]] -name = "websocket-client" -version = "1.8.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e6/30/fba0d96b4b5fbf5948ed3f4681f7da2f9f64512e1d303f94b4cc174c24a5/websocket_client-1.8.0.tar.gz", hash = "sha256:3239df9f44da632f96012472805d40a23281a991027ce11d2f45a6f24ac4c3da", size = 54648 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5a/84/44687a29792a70e111c5c477230a72c4b957d88d16141199bf9acb7537a3/websocket_client-1.8.0-py3-none-any.whl", hash = "sha256:17b44cc997f5c498e809b22cdf2d9c7a9e71c02c8cc2b6c56e7c2d1239bfa526", size = 58826 }, -] - -[[package]] -name = "yapf" -version = "0.40.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "importlib-metadata" }, - { name = "platformdirs" }, - { name = "tomli" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b9/14/c1f0ebd083fddd38a7c832d5ffde343150bd465689d12c549c303fbcd0f5/yapf-0.40.2.tar.gz", hash = "sha256:4dab8a5ed7134e26d57c1647c7483afb3f136878b579062b786c9ba16b94637b", size = 252068 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/66/c9/d4b03b2490107f13ebd68fe9496d41ae41a7de6275ead56d0d4621b11ffd/yapf-0.40.2-py3-none-any.whl", hash = "sha256:adc8b5dd02c0143108878c499284205adb258aad6db6634e5b869e7ee2bd548b", size = 254707 }, -] - -[[package]] -name = "yarl" -version = "1.9.7" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "idna" }, - { name = "multidict" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ce/50/dcf6d0ea0da893b23f73ea5b21fa1f96fd45e9cb4404cc6b665368b4ab19/yarl-1.9.7.tar.gz", hash = "sha256:f28e602edeeec01fc96daf7728e8052bc2e12a672e2a138561a1ebaf30fd9df7", size = 153261 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b4/26/99c3331253bf9d906d8292aba292d5801cef75537098a47027431746e43c/yarl-1.9.7-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:596069ddeaf72b5eb36cd714dcd2b5751d0090d05a8d65113b582ed9e1c801fb", size = 188476 }, - { url = "https://files.pythonhosted.org/packages/dc/f2/789992d30e2b6c9a6460e1da4d59ec1d5c91aa624b97788cce4ce83f9a54/yarl-1.9.7-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cb870907e8b86b2f32541403da9455afc1e535ce483e579bea0e6e79a0cc751c", size = 112728 }, - { url = "https://files.pythonhosted.org/packages/f2/d2/95e5686881ac6e864d6edb18d92e5cc80a18d1b4ddcbc84f2f0d3b451da9/yarl-1.9.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ca5e86be84492fa403c4dcd4dcaf8e1b1c4ffc747b5176f7c3d09878c45719b0", size = 110853 }, - { url = "https://files.pythonhosted.org/packages/d7/cc/773c741e3fe0f9d38c87e1faacc4c5864dbe840fcc46e889482678b2891f/yarl-1.9.7-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a99cecfb51c84d00132db909e83ae388793ca86e48df7ae57f1be0beab0dcce5", size = 504153 }, - { url = "https://files.pythonhosted.org/packages/a5/a4/7fabbd75113591b6cbab9a71e3a2e3c0170fb7958afa3a399e8ed9968023/yarl-1.9.7-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:25508739e9b44d251172145f54c084b71747b09e4d237dc2abb045f46c36a66e", size = 525561 }, - { url = "https://files.pythonhosted.org/packages/52/01/2aabad17c2549e7068f8ec855e9de8d56d95a3a0823e3a398ea17582c6a0/yarl-1.9.7-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:60f3b5aec3146b6992640592856414870f5b20eb688c1f1d5f7ac010a7f86561", size = 520140 }, - { url = "https://files.pythonhosted.org/packages/46/c9/68d4f410c24a10fe0a9d0ab6fa975da433329cd611f12cf11f35e625c60d/yarl-1.9.7-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b1557456afce5db3d655b5f8a31cdcaae1f47e57958760525c44b76e812b4987", size = 508027 }, - { url = "https://files.pythonhosted.org/packages/f8/87/107ac4245975b7ef5d65b99375fa9e1e71bbe66974a4d2c4a6e9375c77d2/yarl-1.9.7-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:71bb1435a84688ed831220c5305d96161beb65cac4a966374475348aa3de4575", size = 489310 }, - { url = "https://files.pythonhosted.org/packages/c0/81/c6e44b3b41227b44337d9bbd0a585b79e3ce12e75500b6470b1b0ea2b5a2/yarl-1.9.7-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f87d8645a7a806ec8f66aac5e3b1dcb5014849ff53ffe2a1f0b86ca813f534c7", size = 504009 }, - { url = "https://files.pythonhosted.org/packages/36/07/272c6c0d36c13a7fd62d2ae3850a70abe1de54afc503a2eb3d61fd083b3e/yarl-1.9.7-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:58e3f01673873b8573da3abe138debc63e4e68541b2104a55df4c10c129513a4", size = 502250 }, - { url = "https://files.pythonhosted.org/packages/d3/23/a26969785e3639b73c796061deb4e3d12df8813bf6f8a51483ab57039b6d/yarl-1.9.7-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8af0bbd4d84f8abdd9b11be9488e32c76b1501889b73c9e2292a15fb925b378b", size = 533891 }, - { url = "https://files.pythonhosted.org/packages/d7/f0/a73047a29b643869ff3f8af51d400763546c1ac98fa7b8eab5c0d12905dd/yarl-1.9.7-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:7fc441408ed0d9c6d2d627a02e281c21f5de43eb5209c16636a17fc704f7d0f8", size = 537621 }, - { url = "https://files.pythonhosted.org/packages/be/ff/531ce46088bd8834bedf09cb2252b3af3d1f8a4b79f4c4e5d8c5480caa51/yarl-1.9.7-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a9552367dc440870556da47bb289a806f08ad06fbc4054072d193d9e5dd619ba", size = 519177 }, - { url = "https://files.pythonhosted.org/packages/cd/71/28e058729ea289903a19169dda80944fb13704f06e03defb4be97e97f7b3/yarl-1.9.7-cp311-cp311-win32.whl", hash = "sha256:628619008680a11d07243391271b46f07f13b75deb9fe92ef342305058c70722", size = 98901 }, - { url = "https://files.pythonhosted.org/packages/7e/bd/1ddd698d8307f35c71a6ee5e3dffeeff0f9e95d926ed9444a0df23a39d5e/yarl-1.9.7-cp311-cp311-win_amd64.whl", hash = "sha256:bc23d870864971c8455cfba17498ccefa53a5719ea9f5fce5e7e9c1606b5755f", size = 108645 }, - { url = "https://files.pythonhosted.org/packages/dd/4e/b3d7679b158a981e6fa36c1d4388a7c3f4adb1b5c33ec22708ec550ddf91/yarl-1.9.7-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:0d8cf3d0b67996edc11957aece3fbce4c224d0451c7c3d6154ec3a35d0e55f6b", size = 188957 }, - { url = "https://files.pythonhosted.org/packages/0e/7b/2fe90636cf0f745210bcb79347369a3882e829e1070ab7d8b3949684d209/yarl-1.9.7-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:3a7748cd66fef49c877e59503e0cc76179caf1158d1080228e67e1db14554f08", size = 113292 }, - { url = "https://files.pythonhosted.org/packages/e2/ee/fae90e40bb4c2af6fd8a1a50d052140101a6634f1d2b32596a6cf53f4244/yarl-1.9.7-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4a6fa3aeca8efabb0fbbb3b15e0956b0cb77f7d9db67c107503c30af07cd9e00", size = 110974 }, - { url = "https://files.pythonhosted.org/packages/28/60/3e985358440d6467c2ea81673000aef762c448462ab88e98e6676845f24f/yarl-1.9.7-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cf37dd0008e5ac5c3880198976063c491b6a15b288d150d12833248cf2003acb", size = 504133 }, - { url = "https://files.pythonhosted.org/packages/e3/ae/f0730026d7011f5403a8f49fec4e666358db43a0339dc8259b19a7c2e6f1/yarl-1.9.7-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:87aa5308482f248f8c3bd9311cd6c7dfd98ea1a8e57e35fb11e4adcac3066003", size = 521269 }, - { url = "https://files.pythonhosted.org/packages/24/5d/1b982866e45906f236cb9a93ec9a07a5b61854b34f0f6fa368056ee9cda3/yarl-1.9.7-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:867b13c1b361f9ba5d2f84dc5408082f5d744c83f66de45edc2b96793a9c5e48", size = 518617 }, - { url = "https://files.pythonhosted.org/packages/8c/ec/eaab7e272ddf1eab39b793e5cd3af304ac28d9342f6a3f2e356276bcc4fe/yarl-1.9.7-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:48ce93947554c2c85fe97fc4866646ec90840bc1162e4db349b37d692a811755", size = 510893 }, - { url = "https://files.pythonhosted.org/packages/98/c3/ed093752106c61e3b2a108f798649cb24119484802bb5ca521a36cf559bd/yarl-1.9.7-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fcd3d94b848cba132f39a5b40d80b0847d001a91a6f35a2204505cdd46afe1b2", size = 487621 }, - { url = "https://files.pythonhosted.org/packages/71/ff/bce0bda27957d4f8cdb8e56b807f185683e8b6a3717637fb8d1faa39269d/yarl-1.9.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d06d6a8f98dd87646d98f0c468be14b201e47ec6092ad569adf835810ad0dffb", size = 506332 }, - { url = "https://files.pythonhosted.org/packages/ff/b5/95702c9719808331d2401e13660af86b323139f0293feb3a44698a194439/yarl-1.9.7-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:91567ff4fce73d2e7ac67ed5983ad26ba2343bc28cb22e1e1184a9677df98d7c", size = 505515 }, - { url = "https://files.pythonhosted.org/packages/17/7d/74a41e5d49329be134602a7e840adf3a499c7562afb982282d079067d5e4/yarl-1.9.7-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1d5594512541e63188fea640b7f066c218d2176203d6e6f82abf702ae3dca3b2", size = 528662 }, - { url = "https://files.pythonhosted.org/packages/c1/f9/8a9083b6b73944c0bb5c99cfc0edf3bec14456b621f76b338fc945afc69f/yarl-1.9.7-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9c2743e43183e4afbb07d5605693299b8756baff0b086c25236c761feb0e3c56", size = 539801 }, - { url = "https://files.pythonhosted.org/packages/44/74/877076885263c214abbed93462ef2e4e95579c047d188530c849ea207846/yarl-1.9.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:daa69a3a2204355af39f4cfe7f3870d87c53d77a597b5100b97e3faa9460428b", size = 524783 }, - { url = "https://files.pythonhosted.org/packages/95/58/e509c4ad1460bce6cf5cd485c5baa5c4c6a9a53999a82f90462f7908ee26/yarl-1.9.7-cp312-cp312-win32.whl", hash = "sha256:36b16884336c15adf79a4bf1d592e0c1ffdb036a760e36a1361565b66785ec6c", size = 98822 }, - { url = "https://files.pythonhosted.org/packages/b0/71/c8136c8c240ccf9d38715aaad31fb4f2c2f14e83c6db6b83d389274b0e9e/yarl-1.9.7-cp312-cp312-win_amd64.whl", hash = "sha256:2ead2f87a1174963cc406d18ac93d731fbb190633d3995fa052d10cefae69ed8", size = 108657 }, - { url = "https://files.pythonhosted.org/packages/2b/3c/c159233854485307e3355af11099d9c351c8475b10b2b3dc64bb8cdc608b/yarl-1.9.7-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:808eddabcb6f7b2cdb6929b3e021ac824a2c07dc7bc83f7618e18438b1b65781", size = 185789 }, - { url = "https://files.pythonhosted.org/packages/89/f3/24c3b30a9d95827280130ecb6ef33f0ab2bdc690391f19178493cf149196/yarl-1.9.7-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:395ab0d8ce6d104a988da429bcbfd445e03fb4c911148dfd523f69d13f772e47", size = 111661 }, - { url = "https://files.pythonhosted.org/packages/5c/a1/e610bfb3c74efdbeeff19ee370e6a76dd552c66680a9180777828dc2e7fa/yarl-1.9.7-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:49827dfccbd59c4499605c13805e947349295466e490860a855b7c7e82ec9c75", size = 109560 }, - { url = "https://files.pythonhosted.org/packages/d0/aa/dc3657bcf79cd98bdfa03c1b85c88de2a36037171894fa56890146e08615/yarl-1.9.7-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f6b8bbdd425d0978311520ea99fb6c0e9e04e64aee84fac05f3157ace9f81b05", size = 485985 }, - { url = "https://files.pythonhosted.org/packages/cf/2a/a69ad3ae4facef03df228790e6f4cfd4971cc267ee140fc8f6331c7e6194/yarl-1.9.7-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:71d33fd1c219b5b28ee98cd76da0c9398a4ed4792fd75c94135237db05ba5ca8", size = 501335 }, - { url = "https://files.pythonhosted.org/packages/f5/8f/b0a35ecd3f31fdffa704d11bf452a277ce4b29e7b878a94e636349945d87/yarl-1.9.7-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:62440431741d0b7d410e5cbad800885e3289048140a43390ecab4f0b96dde3bb", size = 502295 }, - { url = "https://files.pythonhosted.org/packages/39/68/bfc953df3a6ee6c0c9cd9f84d488681e377e49b8ced6d2d5b9289d639c89/yarl-1.9.7-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4db97210433366dfba55590e48285b89ad0146c52bf248dd0da492dd9f0f72cf", size = 493550 }, - { url = "https://files.pythonhosted.org/packages/40/5d/5092b93da54659f1e737f95d9a554f79aa68d1fda05e26c9f0e86184d894/yarl-1.9.7-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:653597b615809f2e5f4dba6cd805608b6fd3597128361a22cc612cf7c7a4d1bf", size = 470835 }, - { url = "https://files.pythonhosted.org/packages/66/e6/dedce99c469f8d1c66432006910adf943fdb7d0cfb77f026030e234f234f/yarl-1.9.7-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df47612129e66f7ce7c9994d4cd4e6852f6e3bf97699375d86991481796eeec8", size = 490437 }, - { url = "https://files.pythonhosted.org/packages/50/52/b36cd8d9356734fda4a668ce358f56ecb16c7171b8a658fdfde31476de7c/yarl-1.9.7-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:5e338b6febbae6c9fe86924bac3ea9c1944e33255c249543cd82a4af6df6047b", size = 492765 }, - { url = "https://files.pythonhosted.org/packages/aa/9e/6ad4300fc040fc34e323f1254a05886a6441d05bd251a9a4063ed8d35c32/yarl-1.9.7-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:e649d37d04665dddb90994bbf0034331b6c14144cc6f3fbce400dc5f28dc05b7", size = 508901 }, - { url = "https://files.pythonhosted.org/packages/77/cc/8b27ea0a0faaba43b389c3a170c25a1fc063c34ae41c8660055e47d5dc89/yarl-1.9.7-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:0a1b8fd849567be56342e988e72c9d28bd3c77b9296c38b9b42d2fe4813c9d3f", size = 519676 }, - { url = "https://files.pythonhosted.org/packages/ca/e6/1b88c9b952c69b4bfb5d38260de4bf65eab4d0787bfcdc0a4d680e084ccb/yarl-1.9.7-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f9d715b2175dff9a49c6dafdc2ab3f04850ba2f3d4a77f69a5a1786b057a9d45", size = 510005 }, - { url = "https://files.pythonhosted.org/packages/72/81/c456d5060bf4c2cb1213cd71e9211e0859ce6fff444bd13c61e2ae681b64/yarl-1.9.7-cp313-cp313-win32.whl", hash = "sha256:bc9233638b07c2e4a3a14bef70f53983389bffa9e8cb90a2da3f67ac9c5e1842", size = 483263 }, - { url = "https://files.pythonhosted.org/packages/5d/08/fe455390603d0377140c1ef02287dd32d3d4a0a6d596aa4a1fc881ac68d2/yarl-1.9.7-cp313-cp313-win_amd64.whl", hash = "sha256:62e110772330d7116f91e79cd83fef92545cb2f36414c95881477aa01971f75f", size = 491236 }, - { url = "https://files.pythonhosted.org/packages/48/04/8cc40203453e4bce05cd3e9a5bea930ac0086aa4848a9c41aa1da13ae1a0/yarl-1.9.7-py3-none-any.whl", hash = "sha256:49935cc51d272264358962d050d726c3e5603a616f53e52ea88e9df1728aa2ee", size = 35402 }, -] - -[[package]] -name = "zipp" -version = "3.20.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d3/8b/1239a3ef43a0d0ebdca623fb6413bc7702c321400c5fdd574f0b7aa0fbb4/zipp-3.20.1.tar.gz", hash = "sha256:c22b14cc4763c5a5b04134207736c107db42e9d3ef2d9779d465f5f1bcba572b", size = 23848 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/9e/c96f7a4cd0bf5625bb409b7e61e99b1130dc63a98cb8b24aeabae62d43e8/zipp-3.20.1-py3-none-any.whl", hash = "sha256:9960cd8967c8f85a56f920d5d507274e74f9ff813a0ab8889a5b5be2daf44064", size = 8988 }, -] +name = "zeromq" +version = "4.3.5" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=zeromq&rev=release-zeromq#40b29e8e88a69802e8afc4f71f5c955bc2d5c74c" } [[package]] name = "zstandard" -version = "0.23.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cffi", marker = "platform_python_implementation == 'PyPy'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ed/f6/2ac0287b442160a89d726b17a9184a4c615bb5237db763791a7fd16d9df1/zstandard-0.23.0.tar.gz", hash = "sha256:b2d8c62d08e7255f68f7a740bae85b3c9b8e5466baa9cbf7f57f1cde0ac6bc09", size = 681701 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9e/40/f67e7d2c25a0e2dc1744dd781110b0b60306657f8696cafb7ad7579469bd/zstandard-0.23.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:34895a41273ad33347b2fc70e1bff4240556de3c46c6ea430a7ed91f9042aa4e", size = 788699 }, - { url = "https://files.pythonhosted.org/packages/e8/46/66d5b55f4d737dd6ab75851b224abf0afe5774976fe511a54d2eb9063a41/zstandard-0.23.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:77ea385f7dd5b5676d7fd943292ffa18fbf5c72ba98f7d09fc1fb9e819b34c23", size = 633681 }, - { url = "https://files.pythonhosted.org/packages/63/b6/677e65c095d8e12b66b8f862b069bcf1f1d781b9c9c6f12eb55000d57583/zstandard-0.23.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:983b6efd649723474f29ed42e1467f90a35a74793437d0bc64a5bf482bedfa0a", size = 4944328 }, - { url = "https://files.pythonhosted.org/packages/59/cc/e76acb4c42afa05a9d20827116d1f9287e9c32b7ad58cc3af0721ce2b481/zstandard-0.23.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:80a539906390591dd39ebb8d773771dc4db82ace6372c4d41e2d293f8e32b8db", size = 5311955 }, - { url = "https://files.pythonhosted.org/packages/78/e4/644b8075f18fc7f632130c32e8f36f6dc1b93065bf2dd87f03223b187f26/zstandard-0.23.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:445e4cb5048b04e90ce96a79b4b63140e3f4ab5f662321975679b5f6360b90e2", size = 5344944 }, - { url = "https://files.pythonhosted.org/packages/76/3f/dbafccf19cfeca25bbabf6f2dd81796b7218f768ec400f043edc767015a6/zstandard-0.23.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd30d9c67d13d891f2360b2a120186729c111238ac63b43dbd37a5a40670b8ca", size = 5442927 }, - { url = "https://files.pythonhosted.org/packages/0c/c3/d24a01a19b6733b9f218e94d1a87c477d523237e07f94899e1c10f6fd06c/zstandard-0.23.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d20fd853fbb5807c8e84c136c278827b6167ded66c72ec6f9a14b863d809211c", size = 4864910 }, - { url = "https://files.pythonhosted.org/packages/1c/a9/cf8f78ead4597264f7618d0875be01f9bc23c9d1d11afb6d225b867cb423/zstandard-0.23.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ed1708dbf4d2e3a1c5c69110ba2b4eb6678262028afd6c6fbcc5a8dac9cda68e", size = 4935544 }, - { url = "https://files.pythonhosted.org/packages/2c/96/8af1e3731b67965fb995a940c04a2c20997a7b3b14826b9d1301cf160879/zstandard-0.23.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:be9b5b8659dff1f913039c2feee1aca499cfbc19e98fa12bc85e037c17ec6ca5", size = 5467094 }, - { url = "https://files.pythonhosted.org/packages/ff/57/43ea9df642c636cb79f88a13ab07d92d88d3bfe3e550b55a25a07a26d878/zstandard-0.23.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:65308f4b4890aa12d9b6ad9f2844b7ee42c7f7a4fd3390425b242ffc57498f48", size = 4860440 }, - { url = "https://files.pythonhosted.org/packages/46/37/edb78f33c7f44f806525f27baa300341918fd4c4af9472fbc2c3094be2e8/zstandard-0.23.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:98da17ce9cbf3bfe4617e836d561e433f871129e3a7ac16d6ef4c680f13a839c", size = 4700091 }, - { url = "https://files.pythonhosted.org/packages/c1/f1/454ac3962671a754f3cb49242472df5c2cced4eb959ae203a377b45b1a3c/zstandard-0.23.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8ed7d27cb56b3e058d3cf684d7200703bcae623e1dcc06ed1e18ecda39fee003", size = 5208682 }, - { url = "https://files.pythonhosted.org/packages/85/b2/1734b0fff1634390b1b887202d557d2dd542de84a4c155c258cf75da4773/zstandard-0.23.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:b69bb4f51daf461b15e7b3db033160937d3ff88303a7bc808c67bbc1eaf98c78", size = 5669707 }, - { url = "https://files.pythonhosted.org/packages/52/5a/87d6971f0997c4b9b09c495bf92189fb63de86a83cadc4977dc19735f652/zstandard-0.23.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:034b88913ecc1b097f528e42b539453fa82c3557e414b3de9d5632c80439a473", size = 5201792 }, - { url = "https://files.pythonhosted.org/packages/79/02/6f6a42cc84459d399bd1a4e1adfc78d4dfe45e56d05b072008d10040e13b/zstandard-0.23.0-cp311-cp311-win32.whl", hash = "sha256:f2d4380bf5f62daabd7b751ea2339c1a21d1c9463f1feb7fc2bdcea2c29c3160", size = 430586 }, - { url = "https://files.pythonhosted.org/packages/be/a2/4272175d47c623ff78196f3c10e9dc7045c1b9caf3735bf041e65271eca4/zstandard-0.23.0-cp311-cp311-win_amd64.whl", hash = "sha256:62136da96a973bd2557f06ddd4e8e807f9e13cbb0bfb9cc06cfe6d98ea90dfe0", size = 495420 }, - { url = "https://files.pythonhosted.org/packages/7b/83/f23338c963bd9de687d47bf32efe9fd30164e722ba27fb59df33e6b1719b/zstandard-0.23.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b4567955a6bc1b20e9c31612e615af6b53733491aeaa19a6b3b37f3b65477094", size = 788713 }, - { url = "https://files.pythonhosted.org/packages/5b/b3/1a028f6750fd9227ee0b937a278a434ab7f7fdc3066c3173f64366fe2466/zstandard-0.23.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e172f57cd78c20f13a3415cc8dfe24bf388614324d25539146594c16d78fcc8", size = 633459 }, - { url = "https://files.pythonhosted.org/packages/26/af/36d89aae0c1f95a0a98e50711bc5d92c144939efc1f81a2fcd3e78d7f4c1/zstandard-0.23.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b0e166f698c5a3e914947388c162be2583e0c638a4703fc6a543e23a88dea3c1", size = 4945707 }, - { url = "https://files.pythonhosted.org/packages/cd/2e/2051f5c772f4dfc0aae3741d5fc72c3dcfe3aaeb461cc231668a4db1ce14/zstandard-0.23.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:12a289832e520c6bd4dcaad68e944b86da3bad0d339ef7989fb7e88f92e96072", size = 5306545 }, - { url = "https://files.pythonhosted.org/packages/0a/9e/a11c97b087f89cab030fa71206963090d2fecd8eb83e67bb8f3ffb84c024/zstandard-0.23.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d50d31bfedd53a928fed6707b15a8dbeef011bb6366297cc435accc888b27c20", size = 5337533 }, - { url = "https://files.pythonhosted.org/packages/fc/79/edeb217c57fe1bf16d890aa91a1c2c96b28c07b46afed54a5dcf310c3f6f/zstandard-0.23.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:72c68dda124a1a138340fb62fa21b9bf4848437d9ca60bd35db36f2d3345f373", size = 5436510 }, - { url = "https://files.pythonhosted.org/packages/81/4f/c21383d97cb7a422ddf1ae824b53ce4b51063d0eeb2afa757eb40804a8ef/zstandard-0.23.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:53dd9d5e3d29f95acd5de6802e909ada8d8d8cfa37a3ac64836f3bc4bc5512db", size = 4859973 }, - { url = "https://files.pythonhosted.org/packages/ab/15/08d22e87753304405ccac8be2493a495f529edd81d39a0870621462276ef/zstandard-0.23.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:6a41c120c3dbc0d81a8e8adc73312d668cd34acd7725f036992b1b72d22c1772", size = 4936968 }, - { url = "https://files.pythonhosted.org/packages/eb/fa/f3670a597949fe7dcf38119a39f7da49a8a84a6f0b1a2e46b2f71a0ab83f/zstandard-0.23.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:40b33d93c6eddf02d2c19f5773196068d875c41ca25730e8288e9b672897c105", size = 5467179 }, - { url = "https://files.pythonhosted.org/packages/4e/a9/dad2ab22020211e380adc477a1dbf9f109b1f8d94c614944843e20dc2a99/zstandard-0.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9206649ec587e6b02bd124fb7799b86cddec350f6f6c14bc82a2b70183e708ba", size = 4848577 }, - { url = "https://files.pythonhosted.org/packages/08/03/dd28b4484b0770f1e23478413e01bee476ae8227bbc81561f9c329e12564/zstandard-0.23.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:76e79bc28a65f467e0409098fa2c4376931fd3207fbeb6b956c7c476d53746dd", size = 4693899 }, - { url = "https://files.pythonhosted.org/packages/2b/64/3da7497eb635d025841e958bcd66a86117ae320c3b14b0ae86e9e8627518/zstandard-0.23.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:66b689c107857eceabf2cf3d3fc699c3c0fe8ccd18df2219d978c0283e4c508a", size = 5199964 }, - { url = "https://files.pythonhosted.org/packages/43/a4/d82decbab158a0e8a6ebb7fc98bc4d903266bce85b6e9aaedea1d288338c/zstandard-0.23.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9c236e635582742fee16603042553d276cca506e824fa2e6489db04039521e90", size = 5655398 }, - { url = "https://files.pythonhosted.org/packages/f2/61/ac78a1263bc83a5cf29e7458b77a568eda5a8f81980691bbc6eb6a0d45cc/zstandard-0.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a8fffdbd9d1408006baaf02f1068d7dd1f016c6bcb7538682622c556e7b68e35", size = 5191313 }, - { url = "https://files.pythonhosted.org/packages/e7/54/967c478314e16af5baf849b6ee9d6ea724ae5b100eb506011f045d3d4e16/zstandard-0.23.0-cp312-cp312-win32.whl", hash = "sha256:dc1d33abb8a0d754ea4763bad944fd965d3d95b5baef6b121c0c9013eaf1907d", size = 430877 }, - { url = "https://files.pythonhosted.org/packages/75/37/872d74bd7739639c4553bf94c84af7d54d8211b626b352bc57f0fd8d1e3f/zstandard-0.23.0-cp312-cp312-win_amd64.whl", hash = "sha256:64585e1dba664dc67c7cdabd56c1e5685233fbb1fc1966cfba2a340ec0dfff7b", size = 495595 }, - { url = "https://files.pythonhosted.org/packages/80/f1/8386f3f7c10261fe85fbc2c012fdb3d4db793b921c9abcc995d8da1b7a80/zstandard-0.23.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:576856e8594e6649aee06ddbfc738fec6a834f7c85bf7cadd1c53d4a58186ef9", size = 788975 }, - { url = "https://files.pythonhosted.org/packages/16/e8/cbf01077550b3e5dc86089035ff8f6fbbb312bc0983757c2d1117ebba242/zstandard-0.23.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:38302b78a850ff82656beaddeb0bb989a0322a8bbb1bf1ab10c17506681d772a", size = 633448 }, - { url = "https://files.pythonhosted.org/packages/06/27/4a1b4c267c29a464a161aeb2589aff212b4db653a1d96bffe3598f3f0d22/zstandard-0.23.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d2240ddc86b74966c34554c49d00eaafa8200a18d3a5b6ffbf7da63b11d74ee2", size = 4945269 }, - { url = "https://files.pythonhosted.org/packages/7c/64/d99261cc57afd9ae65b707e38045ed8269fbdae73544fd2e4a4d50d0ed83/zstandard-0.23.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2ef230a8fd217a2015bc91b74f6b3b7d6522ba48be29ad4ea0ca3a3775bf7dd5", size = 5306228 }, - { url = "https://files.pythonhosted.org/packages/7a/cf/27b74c6f22541f0263016a0fd6369b1b7818941de639215c84e4e94b2a1c/zstandard-0.23.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:774d45b1fac1461f48698a9d4b5fa19a69d47ece02fa469825b442263f04021f", size = 5336891 }, - { url = "https://files.pythonhosted.org/packages/fa/18/89ac62eac46b69948bf35fcd90d37103f38722968e2981f752d69081ec4d/zstandard-0.23.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6f77fa49079891a4aab203d0b1744acc85577ed16d767b52fc089d83faf8d8ed", size = 5436310 }, - { url = "https://files.pythonhosted.org/packages/a8/a8/5ca5328ee568a873f5118d5b5f70d1f36c6387716efe2e369010289a5738/zstandard-0.23.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ac184f87ff521f4840e6ea0b10c0ec90c6b1dcd0bad2f1e4a9a1b4fa177982ea", size = 4859912 }, - { url = "https://files.pythonhosted.org/packages/ea/ca/3781059c95fd0868658b1cf0440edd832b942f84ae60685d0cfdb808bca1/zstandard-0.23.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:c363b53e257246a954ebc7c488304b5592b9c53fbe74d03bc1c64dda153fb847", size = 4936946 }, - { url = "https://files.pythonhosted.org/packages/ce/11/41a58986f809532742c2b832c53b74ba0e0a5dae7e8ab4642bf5876f35de/zstandard-0.23.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:e7792606d606c8df5277c32ccb58f29b9b8603bf83b48639b7aedf6df4fe8171", size = 5466994 }, - { url = "https://files.pythonhosted.org/packages/83/e3/97d84fe95edd38d7053af05159465d298c8b20cebe9ccb3d26783faa9094/zstandard-0.23.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a0817825b900fcd43ac5d05b8b3079937073d2b1ff9cf89427590718b70dd840", size = 4848681 }, - { url = "https://files.pythonhosted.org/packages/6e/99/cb1e63e931de15c88af26085e3f2d9af9ce53ccafac73b6e48418fd5a6e6/zstandard-0.23.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:9da6bc32faac9a293ddfdcb9108d4b20416219461e4ec64dfea8383cac186690", size = 4694239 }, - { url = "https://files.pythonhosted.org/packages/ab/50/b1e703016eebbc6501fc92f34db7b1c68e54e567ef39e6e59cf5fb6f2ec0/zstandard-0.23.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:fd7699e8fd9969f455ef2926221e0233f81a2542921471382e77a9e2f2b57f4b", size = 5200149 }, - { url = "https://files.pythonhosted.org/packages/aa/e0/932388630aaba70197c78bdb10cce2c91fae01a7e553b76ce85471aec690/zstandard-0.23.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:d477ed829077cd945b01fc3115edd132c47e6540ddcd96ca169facff28173057", size = 5655392 }, - { url = "https://files.pythonhosted.org/packages/02/90/2633473864f67a15526324b007a9f96c96f56d5f32ef2a56cc12f9548723/zstandard-0.23.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fa6ce8b52c5987b3e34d5674b0ab529a4602b632ebab0a93b07bfb4dfc8f8a33", size = 5191299 }, - { url = "https://files.pythonhosted.org/packages/b0/4c/315ca5c32da7e2dc3455f3b2caee5c8c2246074a61aac6ec3378a97b7136/zstandard-0.23.0-cp313-cp313-win32.whl", hash = "sha256:a9b07268d0c3ca5c170a385a0ab9fb7fdd9f5fd866be004c4ea39e44edce47dd", size = 430862 }, - { url = "https://files.pythonhosted.org/packages/a2/bf/c6aaba098e2d04781e8f4f7c0ba3c7aa73d00e4c436bcc0cf059a66691d1/zstandard-0.23.0-cp313-cp313-win_amd64.whl", hash = "sha256:f3513916e8c645d0610815c257cbfd3242adfd5c4cfa78be514e5a3ebb42a41b", size = 495578 }, -] +version = "0.25.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/fc/f26eb6ef91ae723a03e16eddb198abcfce2bc5a42e224d44cc8b6765e57e/zstandard-0.25.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7b3c3a3ab9daa3eed242d6ecceead93aebbb8f5f84318d82cee643e019c4b73b", size = 795738, upload-time = "2025-09-14T22:16:56.237Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1c/d920d64b22f8dd028a8b90e2d756e431a5d86194caa78e3819c7bf53b4b3/zstandard-0.25.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:913cbd31a400febff93b564a23e17c3ed2d56c064006f54efec210d586171c00", size = 640436, upload-time = "2025-09-14T22:16:57.774Z" }, + { url = "https://files.pythonhosted.org/packages/53/6c/288c3f0bd9fcfe9ca41e2c2fbfd17b2097f6af57b62a81161941f09afa76/zstandard-0.25.0-cp312-cp312-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:011d388c76b11a0c165374ce660ce2c8efa8e5d87f34996aa80f9c0816698b64", size = 5343019, upload-time = "2025-09-14T22:16:59.302Z" }, + { url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" }, + { url = "https://files.pythonhosted.org/packages/b7/37/a6ce629ffdb43959e92e87ebdaeebb5ac81c944b6a75c9c47e300f85abdf/zstandard-0.25.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7149623bba7fdf7e7f24312953bcf73cae103db8cae49f8154dd1eadc8a29ecb", size = 5394148, upload-time = "2025-09-14T22:17:03.091Z" }, + { url = "https://files.pythonhosted.org/packages/e3/79/2bf870b3abeb5c070fe2d670a5a8d1057a8270f125ef7676d29ea900f496/zstandard-0.25.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6a573a35693e03cf1d67799fd01b50ff578515a8aeadd4595d2a7fa9f3ec002a", size = 5451652, upload-time = "2025-09-14T22:17:04.979Z" }, + { url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" }, + { url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" }, + { url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" }, + { url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" }, + { url = "https://files.pythonhosted.org/packages/18/e1/97680c664a1bf9a247a280a053d98e251424af51f1b196c6d52f117c9720/zstandard-0.25.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:809c5bcb2c67cd0ed81e9229d227d4ca28f82d0f778fc5fea624a9def3963f91", size = 5268008, upload-time = "2025-09-14T22:17:13.627Z" }, + { url = "https://files.pythonhosted.org/packages/1e/73/316e4010de585ac798e154e88fd81bb16afc5c5cb1a72eeb16dd37e8024a/zstandard-0.25.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f27662e4f7dbf9f9c12391cb37b4c4c3cb90ffbd3b1fb9284dadbbb8935fa708", size = 5433517, upload-time = "2025-09-14T22:17:16.103Z" }, + { url = "https://files.pythonhosted.org/packages/5b/60/dd0f8cfa8129c5a0ce3ea6b7f70be5b33d2618013a161e1ff26c2b39787c/zstandard-0.25.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99c0c846e6e61718715a3c9437ccc625de26593fea60189567f0118dc9db7512", size = 5814292, upload-time = "2025-09-14T22:17:17.827Z" }, + { url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/ff/8d/0309daffea4fcac7981021dbf21cdb2e3427a9e76bafbcdbdf5392ff99a4/zstandard-0.25.0-cp312-cp312-win32.whl", hash = "sha256:23ebc8f17a03133b4426bcc04aabd68f8236eb78c3760f12783385171b0fd8bd", size = 436922, upload-time = "2025-09-14T22:17:24.398Z" }, + { url = "https://files.pythonhosted.org/packages/79/3b/fa54d9015f945330510cb5d0b0501e8253c127cca7ebe8ba46a965df18c5/zstandard-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:ffef5a74088f1e09947aecf91011136665152e0b4b359c42be3373897fb39b01", size = 506276, upload-time = "2025-09-14T22:17:21.429Z" }, + { url = "https://files.pythonhosted.org/packages/ea/6b/8b51697e5319b1f9ac71087b0af9a40d8a6288ff8025c36486e0c12abcc4/zstandard-0.25.0-cp312-cp312-win_arm64.whl", hash = "sha256:181eb40e0b6a29b3cd2849f825e0fa34397f649170673d385f3598ae17cca2e9", size = 462679, upload-time = "2025-09-14T22:17:23.147Z" }, +] + +[[package]] +name = "zstd" +version = "1.5.6" +source = { git = "https://github.com/commaai/dependencies.git?subdirectory=zstd&rev=release-zstd#13015596466eb68825f109ad0d5aefa6330cc495" } diff --git a/zensical.toml b/zensical.toml new file mode 100644 index 00000000000000..7e5ca2c5db45b9 --- /dev/null +++ b/zensical.toml @@ -0,0 +1,81 @@ +[project] +site_name = "openpilot docs" +site_url = "https://docs.comma.ai" +repo_url = "https://github.com/commaai/openpilot/" + +docs_dir = "docs" +site_dir = "docs_site/" + +extra_css = ["stylesheets/extra.css"] + +nav = [ + { "What is openpilot?" = "index.md" }, + { "How-to" = [ + { "Turn the speed blue" = "how-to/turn-the-speed-blue.md" }, + { "Connect to a comma 3X or four" = "how-to/connect-to-comma.md" }, + { "Add support for a car" = "how-to/car-port.md" }, + ] }, + { "Concepts" = [ + { "Logs" = "concepts/logs.md" }, + { "Safety" = "concepts/safety.md" }, + { "Glossary" = "concepts/glossary.md" }, + ] }, + { "Contributing" = [ + { "Feedback" = "contributing/feedback.md" }, + { "Roadmap" = "contributing/roadmap.md" }, + { "Contributing Guide →" = "https://github.com/commaai/openpilot/blob/master/docs/CONTRIBUTING.md" }, + ] }, + { "Links" = [ + { "Blog →" = "https://blog.comma.ai" }, + { "Bounties →" = "https://comma.ai/bounties" }, + { "GitHub →" = "https://github.com/commaai" }, + { "Discord →" = "https://discord.comma.ai" }, + { "X →" = "https://x.com/comma_ai" }, + ] }, +] + +[project.theme] +logo = "assets/comma-logo.png" +features = [ + "navigation.expand", + "navigation.sections", + "navigation.instant", + "navigation.instant.prefetch", + "content.code.copy", + "content.action.edit", + "content.action.view", +] + +[[project.extra.social]] +icon = "fontawesome/brands/github" +link = "https://github.com/commaai" + +[[project.extra.social]] +icon = "fontawesome/brands/discord" +link = "https://discord.comma.ai" + +[[project.extra.social]] +icon = "fontawesome/brands/x-twitter" +link = "https://x.com/comma_ai" + +[project.markdown_extensions.attr_list] + +[project.markdown_extensions.admonition] + +[project.markdown_extensions.md_in_html] + +[project.markdown_extensions.pymdownx.highlight] +anchor_linenums = true +line_spans = "__span" +pygments_lang_class = true + +[project.markdown_extensions.pymdownx.inlinehilite] + +[project.markdown_extensions.pymdownx.magiclink] + +[project.markdown_extensions.pymdownx.superfences] +custom_fences = [{ name = "mermaid", class = "mermaid" }] + +[project.markdown_extensions.pymdownx.details] + +[project.markdown_extensions."ext.glossary"]